Use explicit join in random-jobs endpoint to avoid potential N+1 query

- Changed from using scalars().all() with lazy='joined' relationship
- Now uses explicit join similar to other audit endpoints
- Guarantees single query regardless of SQLAlchemy async behavior
This commit is contained in:
counterweight 2025-12-21 23:14:08 +01:00
parent 6b572aa81b
commit 18284c5e63
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C

View file

@ -124,20 +124,25 @@ async def get_random_job_outcomes(
_current_user: User = Depends(require_permission(Permission.VIEW_AUDIT)),
) -> list[RandomNumberOutcomeResponse]:
"""Get all random number job outcomes, newest first."""
query = select(RandomNumberOutcome).order_by(desc(RandomNumberOutcome.created_at))
# Explicit join to avoid N+1 query
query = (
select(RandomNumberOutcome, User.email)
.join(User, RandomNumberOutcome.triggered_by_user_id == User.id)
.order_by(desc(RandomNumberOutcome.created_at))
)
result = await db.execute(query)
outcomes = result.scalars().all()
rows = result.all()
return [
RandomNumberOutcomeResponse(
id=outcome.id,
job_id=outcome.job_id,
triggered_by_user_id=outcome.triggered_by_user_id,
triggered_by_email=outcome.triggered_by.email,
triggered_by_email=email,
value=outcome.value,
duration_ms=outcome.duration_ms,
status=outcome.status,
created_at=outcome.created_at,
)
for outcome in outcomes
for outcome, email in rows
]