From 70962ba67a81063cfc8933d153c464a2c5f9cb3f Mon Sep 17 00:00:00 2001 From: GotthardG <51994228+GotthardG@users.noreply.github.com> Date: Mon, 3 Feb 2025 11:46:27 +0100 Subject: [PATCH] Refactor dewar query to use latest event subquery. Replaces the previous query logic with a subquery to find the latest logistics event for each dewar. Ensures that only dewars with the most recent "beamline" event are retrieved, improving query accuracy and clarity. --- backend/app/routers/puck.py | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/backend/app/routers/puck.py b/backend/app/routers/puck.py index 5caac6c..fe197e6 100644 --- a/backend/app/routers/puck.py +++ b/backend/app/routers/puck.py @@ -394,13 +394,32 @@ async def get_pucks_by_slot(slot_identifier: str, db: Session = Depends(get_db)) status_code=404, detail=f"Slot not found for identifier {slot_identifier}" ) - # Fetch dewars in the slot + # Subquery to find the latest event for each dewar + latest_event_subquery = ( + db.query( + LogisticsEventModel.dewar_id.label("dewar_id"), + func.max(LogisticsEventModel.timestamp).label("latest_event_time"), + ) + .group_by(LogisticsEventModel.dewar_id) + .subquery(name="latest_event_subquery") + ) + + # Main query to fetch dewars where the latest event is "beamline" dewars = ( db.query(DewarModel) .join(LogisticsEventModel, DewarModel.id == LogisticsEventModel.dewar_id) + .join( + latest_event_subquery, + (LogisticsEventModel.dewar_id == latest_event_subquery.c.dewar_id) + & ( + LogisticsEventModel.timestamp + == latest_event_subquery.c.latest_event_time + ), # Match latest event + ) .filter( LogisticsEventModel.slot_id == slot_id, - LogisticsEventModel.event_type == "beamline", + LogisticsEventModel.event_type + == "beamline", # Ensure latest event is "beamline" ) .all() )