refac
This commit is contained in:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user