Files
mtusi2026lab6/app/tools/explain.py
T
dawuduk 14ab803529 Перенести рабочую реализацию lab5 в skeleton лабораторной 6.
API, worker, брокер и стенд остаются базой, контракт lab6 не менялся.
2026-11-17 15:15:42 +03:00

74 lines
2.7 KiB
Python

"""Seed ≥10 000 messages and print EXPLAIN (ANALYZE, BUFFERS) for keyset pagination."""
import asyncio
import os
from uuid import uuid4
import asyncpg
from app.passwords import hash_password
async def main() -> None:
conn = await asyncpg.connect(dsn=os.environ["DATABASE_URL"], timeout=10, command_timeout=120)
try:
alice = uuid4()
bob = uuid4()
chat = uuid4()
pwd = hash_password("Example-only-not-a-real-secret-123")
await conn.execute(
"INSERT INTO users (id, username, display_name, password_hash) VALUES ($1,$2,$3,$4),($5,$6,$7,$4)",
alice,
"explain_a_" + alice.hex[:8],
"Alice",
pwd,
bob,
"explain_b_" + bob.hex[:8],
"Bob",
)
await conn.execute("INSERT INTO chats (id, title) VALUES ($1,$2)", chat, "Explain chat")
await conn.execute(
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1,$2),($1,$3)",
chat,
alice,
bob,
)
n = int(os.environ.get("EXPLAIN_MESSAGES", "10000"))
await conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), $1, $2, 'seed-' || g, now() - (g || ' milliseconds')::interval
FROM generate_series(1, $3) AS g
""",
chat,
alice,
n,
)
count = await conn.fetchval("SELECT count(*) FROM messages WHERE chat_id = $1", chat)
print("seeded_messages", count, "chat_id", chat)
first = await conn.fetchrow(
"SELECT created_at, id FROM messages WHERE chat_id = $1 ORDER BY created_at, id LIMIT 1",
chat,
)
query = """
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
ORDER BY created_at, id
LIMIT 50
"""
print("\n=== WITH index messages_chat_created_id_idx ===")
plan = await conn.fetch("EXPLAIN (ANALYZE, BUFFERS) " + query, chat, first["created_at"], first["id"])
print("\n".join(row[0] for row in plan))
await conn.execute("SET enable_indexscan = off")
await conn.execute("SET enable_bitmapscan = off")
await conn.execute("SET enable_indexonlyscan = off")
print("\n=== WITHOUT index scans (seq scan baseline) ===")
plan2 = await conn.fetch("EXPLAIN (ANALYZE, BUFFERS) " + query, chat, first["created_at"], first["id"])
print("\n".join(row[0] for row in plan2))
finally:
await conn.close()
if __name__ == "__main__":
asyncio.run(main())