perf(*): bound list queries, batch fetches, harden media downloads

This commit is contained in:
hh committed 2026-09-01 21:38:22 +02:00
1 parent 9c12628304
commit 1fa4f18a9b
35 files changed
+473 -138

No files matched your search

+22 -1
View File
@@ -62,6 +62,18 @@ _ONE_ID = """
WHERE account_id = $1 AND scope_type = 'chat' AND scope_id = $2
"""
_MANY_IDS = """
SELECT chat_id FROM chat_stats
WHERE account_id = $1 AND chat_id = ANY($2::bigint[])
UNION
SELECT chat_id FROM dialogs
WHERE account_id = $1 AND chat_id = ANY($2::bigint[])
UNION
SELECT scope_id AS chat_id FROM capture_policy
WHERE account_id = $1 AND scope_type = 'chat'
AND scope_id = ANY($2::bigint[])
"""
_CHAT_ROWS = """
WITH ids AS ({ids})
SELECT ids.chat_id,
@@ -171,6 +183,15 @@ async def get_chat(
return _chat_item(row) if row is not None else None
async def get_chats(
pool: asyncpg.Pool, account_id: int, ids: list[int]
) -> list[ChatListItem]:
if not ids:
return []
rows = await pool.fetch(_CHAT_ROWS.format(ids=_MANY_IDS), account_id, ids)
return [_chat_item(row) for row in rows]
async def get_chat_history( # noqa: PLR0913
pool: asyncpg.Pool,
account_id: int,
@@ -308,7 +329,7 @@ async def get_message_versions(
rows = await pool.fetch(
"SELECT observed_at, edit_date, text FROM message_versions "
"WHERE account_id = $1 AND chat_id = $2 AND message_id = $3 "
"ORDER BY observed_at",
"ORDER BY observed_at LIMIT 500",
account_id,
chat_id,
message_id,