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.
This commit is contained in:
GotthardG 2025-02-03 11:46:27 +01:00
parent aa70935e11
commit 70962ba67a

View File

@ -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}" 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 = ( dewars = (
db.query(DewarModel) db.query(DewarModel)
.join(LogisticsEventModel, DewarModel.id == LogisticsEventModel.dewar_id) .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( .filter(
LogisticsEventModel.slot_id == slot_id, LogisticsEventModel.slot_id == slot_id,
LogisticsEventModel.event_type == "beamline", LogisticsEventModel.event_type
== "beamline", # Ensure latest event is "beamline"
) )
.all() .all()
) )