This commit is contained in:
Timothy Jaeryang Baek
2026-04-11 16:55:20 -06:00
parent 674695918e
commit 09f6d7ba57
3 changed files with 53 additions and 6 deletions
+35 -1
View File
@@ -45,7 +45,10 @@ class AutomationRun(Base):
error = Column(Text, nullable=True)
created_at = Column(BigInteger, nullable=False)
__table_args__ = (Index('ix_automation_run_automation_id', 'automation_id'),)
__table_args__ = (
Index('ix_automation_run_automation_id', 'automation_id'),
Index('ix_automation_run_aid_created', 'automation_id', 'created_at'),
)
####################
@@ -308,6 +311,37 @@ class AutomationRunTable:
)
return AutomationRunModel.model_validate(row) if row else None
def get_latest_batch(
self, automation_ids: list[str], db: Optional[Session] = None
) -> dict[str, AutomationRunModel]:
"""Fetch the latest run for each automation in a single query."""
if not automation_ids:
return {}
with get_db_context(db) as db:
# Subquery: max created_at per automation_id
subq = (
db.query(
AutomationRun.automation_id,
func.max(AutomationRun.created_at).label('max_created'),
)
.filter(AutomationRun.automation_id.in_(automation_ids))
.group_by(AutomationRun.automation_id)
.subquery()
)
rows = (
db.query(AutomationRun)
.join(
subq,
(AutomationRun.automation_id == subq.c.automation_id)
& (AutomationRun.created_at == subq.c.max_created),
)
.all()
)
return {
row.automation_id: AutomationRunModel.model_validate(row)
for row in rows
}
def get_by_automation(
self,
automation_id: str,