From efde271c5ab7655667d1dbf3ae23efeb6e9fc7f3 Mon Sep 17 00:00:00 2001 From: Ben Thorner Date: Thu, 10 Feb 2022 14:41:53 +0000 Subject: [PATCH] Rewrite FactStatus updates to be an upsert This is consistent with the way we do billing updates [1] and is a bit less clunky. Functionally it should be the same - note that the tests already cover the "overwriting" behaviour if a row exists. [1]: https://github.com/alphagov/notifications-api/blob/9ce6d2fe924626c578cdb77467d8df0e842e9821/app/dao/fact_billing_dao.py#L522 --- app/dao/fact_notification_status_dao.py | 35 ++++++++++++++----------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/app/dao/fact_notification_status_dao.py b/app/dao/fact_notification_status_dao.py index d19ba748c..52adfd64c 100644 --- a/app/dao/fact_notification_status_dao.py +++ b/app/dao/fact_notification_status_dao.py @@ -65,26 +65,29 @@ def fetch_status_data_for_service_and_day(process_day, service_id, notification_ @autocommit def update_fact_notification_status(new_status_rows, process_day, notification_type, service_id): table = FactNotificationStatus.__table__ - FactNotificationStatus.query.filter( - FactNotificationStatus.bst_date == process_day, - FactNotificationStatus.notification_type == notification_type, - FactNotificationStatus.service_id == service_id, - ).delete() for row in new_status_rows: - db.session.connection().execute( - insert(table).values( - bst_date=process_day, - template_id=row.template_id, - service_id=service_id, - job_id=row.job_id, - notification_type=notification_type, - key_type=row.key_type, - notification_status=row.status, - notification_count=row.notification_count, - ) + stmt = insert(table).values( + bst_date=process_day, + template_id=row.template_id, + service_id=service_id, + job_id=row.job_id, + notification_type=notification_type, + key_type=row.key_type, + notification_status=row.status, + notification_count=row.notification_count, ) + stmt = stmt.on_conflict_do_update( + constraint="ft_notification_status_pkey", + set_={ + FactNotificationStatus.notification_count: stmt.excluded.notification_count, + FactNotificationStatus.updated_at: datetime.utcnow() + } + ) + + db.session.connection().execute(stmt) + def fetch_notification_status_for_service_by_month(start_date, end_date, service_id): return db.session.query(