From 9c0cf300054365a76a648c7dcfb93a5d78991818 Mon Sep 17 00:00:00 2001 From: Jumana B Date: Thu, 23 Nov 2023 13:15:05 -0500 Subject: [PATCH] Remove redundant group by and add a composite index (#2033) * remove redundant group by * fix tests * Added composite index --- app/dao/fact_notification_status_dao.py | 7 ++-- .../versions/0440_add_index_n_history_comp.py | 37 +++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 migrations/versions/0440_add_index_n_history_comp.py diff --git a/app/dao/fact_notification_status_dao.py b/app/dao/fact_notification_status_dao.py index fc065c8c39..061075609a 100644 --- a/app/dao/fact_notification_status_dao.py +++ b/app/dao/fact_notification_status_dao.py @@ -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 diff --git a/migrations/versions/0440_add_index_n_history_comp.py b/migrations/versions/0440_add_index_n_history_comp.py new file mode 100644 index 0000000000..4b65da8a39 --- /dev/null +++ b/migrations/versions/0440_add_index_n_history_comp.py @@ -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")