perf: one grouped query for latest per-flat application, not N

_wohnungen_context was calling last_application_for_flat(uid, f.id)
inside the flats loop — at 100 flats that's 101 queries per poll, and
with running applications the page polls every 3s. New
db.latest_applications_by_flat(user_id) returns {flat_id: row} via a
single grouped self-join.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
EiSiMo 2026-04-21 19:06:48 +02:00
parent ebb11178e7
commit 77098c82df
2 changed files with 22 additions and 2 deletions

View file

@ -675,6 +675,24 @@ def last_application_for_flat(user_id: int, flat_id: str) -> Optional[sqlite3.Ro
).fetchone()
def latest_applications_by_flat(user_id: int) -> dict:
"""Return a dict {flat_id: latest-application-row} for all flats the user
has interacted with. One query instead of N."""
rows = _get_conn().execute(
"""SELECT a.*
FROM applications a
JOIN (
SELECT flat_id, MAX(started_at) AS maxstart
FROM applications
WHERE user_id = ?
GROUP BY flat_id
) m ON m.flat_id = a.flat_id AND m.maxstart = a.started_at
WHERE a.user_id = ?""",
(user_id, user_id),
).fetchall()
return {r["flat_id"]: r for r in rows}
def has_running_application(user_id: int) -> bool:
row = _get_conn().execute(
"SELECT 1 FROM applications WHERE user_id = ? AND finished_at IS NULL LIMIT 1",