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]: 9ce6d2fe92/app/dao/fact_billing_dao.py (L522)
This commit is contained in:
Ben Thorner
2022-02-10 14:41:53 +00:00
parent 7bc037f1ce
commit efde271c5a

View File

@@ -65,15 +65,9 @@ def fetch_status_data_for_service_and_day(process_day, service_id, notification_
@autocommit @autocommit
def update_fact_notification_status(new_status_rows, process_day, notification_type, service_id): def update_fact_notification_status(new_status_rows, process_day, notification_type, service_id):
table = FactNotificationStatus.__table__ 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: for row in new_status_rows:
db.session.connection().execute( stmt = insert(table).values(
insert(table).values(
bst_date=process_day, bst_date=process_day,
template_id=row.template_id, template_id=row.template_id,
service_id=service_id, service_id=service_id,
@@ -83,8 +77,17 @@ def update_fact_notification_status(new_status_rows, process_day, notification_t
notification_status=row.status, notification_status=row.status,
notification_count=row.notification_count, 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): def fetch_notification_status_for_service_by_month(start_date, end_date, service_id):
return db.session.query( return db.session.query(