Skip to content

Commit

Permalink
Remove redundant group by and add a composite index (#2033)
Browse files Browse the repository at this point in the history
* remove redundant group by

* fix tests

* Added composite index
  • Loading branch information
jzbahrai authored Nov 23, 2023
1 parent 128bc50 commit 9c0cf30
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
7 changes: 3 additions & 4 deletions app/dao/fact_notification_status_dao.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,16 +337,15 @@ def get_last_send_for_api_key(api_key_id):
notification_table = (
db.session.query(func.max(Notification.created_at).label("last_notification_created"))
.filter(Notification.api_key_id == api_key_id)
.group_by(Notification.api_key_id)
.all()
)
if not notification_table:
return (
if not notification_table[0][0]:
notification_table = (
db.session.query(func.max(NotificationHistory.created_at).label("last_notification_created"))
.filter(NotificationHistory.api_key_id == api_key_id)
.group_by(NotificationHistory.api_key_id)
.all()
)
notification_table = [] if notification_table[0][0] is None else notification_table
return notification_table


Expand Down
37 changes: 37 additions & 0 deletions migrations/versions/0440_add_index_n_history_comp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""
Revision ID: 0439_add_index_n_history
Revises: 0438_sms_templates_msgs_left
Create Date: 2023-10-05 00:00:00
"""
from datetime import datetime

from alembic import op

revision = "0440_add_index_n_history_2"
down_revision = "0439_add_index_n_history"


def index_exists(name):
connection = op.get_bind()
result = connection.execute(
"SELECT exists(SELECT 1 from pg_indexes where indexname = '{}') as ix_exists;".format(name)
).first()
return result.ix_exists


# option 1
def upgrade():
op.execute("COMMIT")
if not index_exists("ix_notification_history_created_api_key_id"):
op.create_index(
op.f("ix_notification_history_created_api_key_id"),
"notification_history",
["created_at", "api_key_id"],
postgresql_concurrently=True,
)


def downgrade():
op.drop_index(op.f("ix_notification_history_created_api_key_id"), table_name="notification_history")

0 comments on commit 9c0cf30

Please sign in to comment.