73 lines
2.9 KiB
Python
73 lines
2.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Seed one synthetic 10k-message chat and show the indexed keyset query plan."""
|
|
import asyncio
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
import sys
|
|
import uuid
|
|
|
|
import asyncpg
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
|
|
from app.core.config import settings
|
|
|
|
|
|
async def main() -> None:
|
|
pool = await asyncpg.create_pool(
|
|
settings.resolved_database_url(),
|
|
min_size=1,
|
|
max_size=2,
|
|
command_timeout=settings.db_command_timeout_seconds,
|
|
)
|
|
user_id, chat_id = uuid.uuid4(), uuid.uuid4()
|
|
username = 'explain_' + uuid.uuid4().hex[:12]
|
|
base_time = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
|
try:
|
|
async with pool.acquire() as connection:
|
|
async with connection.transaction():
|
|
await connection.execute(
|
|
'INSERT INTO users (id, username, display_name, password_hash) '
|
|
'VALUES ($1, $2, $3, $4)',
|
|
user_id, username, 'EXPLAIN fixture', 'not-a-login-hash',
|
|
)
|
|
await connection.execute(
|
|
'INSERT INTO chats (id, title) VALUES ($1, $2)',
|
|
chat_id, 'EXPLAIN 10k fixture',
|
|
)
|
|
await connection.execute(
|
|
'INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)',
|
|
chat_id, user_id,
|
|
)
|
|
await connection.execute(
|
|
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
|
|
"SELECT md5($1::text || ':' || n::text)::uuid, $1::uuid, $2::uuid, "
|
|
"'synthetic explain message ' || n, $3::timestamptz + n * interval '1 microsecond' "
|
|
'FROM generate_series(1, 10000) AS g(n)',
|
|
str(chat_id), str(user_id), base_time,
|
|
)
|
|
await connection.execute('ANALYZE messages')
|
|
total = await connection.fetchval(
|
|
'SELECT count(*) FROM messages WHERE chat_id = $1', chat_id
|
|
)
|
|
plan = await connection.fetch(
|
|
'EXPLAIN (ANALYZE, BUFFERS) '
|
|
'SELECT id, created_at, sender_id, text FROM messages '
|
|
'WHERE chat_id = $1 AND (created_at, id) > ($2, $3) '
|
|
'ORDER BY created_at, id LIMIT 50',
|
|
chat_id, base_time, uuid.UUID(int=0),
|
|
)
|
|
rendered = '\n'.join(row['QUERY PLAN'] for row in plan)
|
|
print(f'chat_id={chat_id}; messages_in_fixture={total}')
|
|
print(rendered)
|
|
if total < 10000:
|
|
raise RuntimeError('EXPLAIN fixture did not reach 10,000 messages')
|
|
if 'messages_history_idx' not in rendered:
|
|
raise RuntimeError('planner did not choose messages_history_idx; inspect the plan')
|
|
finally:
|
|
await pool.close()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
asyncio.run(main())
|