From 9f7c5c5536a6e316be4c46319086b802477554b7 Mon Sep 17 00:00:00 2001 From: pbugni Date: Wed, 4 Sep 2024 16:37:49 -0700 Subject: [PATCH] TN-3313 Robustly handle race case of an updating adherence_row (#4402) Add a check for existing row before attempted insert, to prevent race case observed in logs. See [TN-3313](https://movember.atlassian.net/browse/TN-3313) for details. --- portal/models/adherence_data.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/portal/models/adherence_data.py b/portal/models/adherence_data.py index f70473656..7927982a6 100644 --- a/portal/models/adherence_data.py +++ b/portal/models/adherence_data.py @@ -77,12 +77,20 @@ def persist(patient_id, rs_id_visit, valid_for_days, data): except TypeError: raise ValueError(f"couldn't encode {k}:{v}, {type(v)}") - record = AdherenceData( - patient_id=patient_id, - rs_id_visit=rs_id_visit, - valid_till=valid_till, - data=data) - db.session.add(record) + # only a single row for a given patient, rs_id_visit allowed. replace or add + record = AdherenceData.query.filter( + AdherenceData.patient_id == patient_id).filter( + AdherenceData.rs_id_visit == rs_id_visit).first() + if record: + record.valid_till = valid_till + record.data = data + else: + record = AdherenceData( + patient_id=patient_id, + rs_id_visit=rs_id_visit, + valid_till=valid_till, + data=data) + db.session.add(record) db.session.commit() return db.session.merge(record)