import asyncio import uuid from pathlib import Path from datetime import datetime, timezone from sqlalchemy import text from src.database import engine async def main(): async with engine.begin() as conn: row = await conn.execute(text("SELECT id FROM chats LIMIT 1")) chat_row = row.first() if not chat_row: print("No chats found. Create a chat first via API.") return chat_id = chat_row[0] row = await conn.execute(text("SELECT id FROM users LIMIT 1")) user_id = row.first()[0] row = await conn.execute(text( "SELECT COUNT(*) FROM messages WHERE chat_id = :cid" ), {"cid": chat_id}) current_count = row.scalar() needed = max(0, 10_000 - current_count) if needed > 0: print(f"Generating {needed} messages for chat {chat_id}...") await conn.execute(text(""" INSERT INTO messages (id, chat_id, sender_id, text, created_at) SELECT gen_random_uuid(), :chat_id, :user_id, 'benchmark message ' || g, NOW() - (interval '1 second' * g) FROM generate_series(1, :needed) AS g """), {"chat_id": chat_id, "user_id": user_id, "needed": needed}) print(f"Inserted {needed} messages (total: {current_count + needed})") else: print(f"Already have {current_count} messages (≥10 000)") await conn.execute(text("ANALYZE messages")) print("Statistics updated via ANALYZE") report_lines = [] report_lines.append("COMPARATIVE EXPLAIN REPORT") report_lines.append(f" Generated: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}") report_lines.append(f" Chat ID: {chat_id}") report_lines.append(f" Messages: {current_count + needed}") report_lines.append("1. WITH INDEX") result = await conn.execute(text(""" EXPLAIN (ANALYZE, BUFFERS) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = :chat_id ORDER BY created_at ASC, id ASC LIMIT 51 """), {"chat_id": chat_id}) for r in result: report_lines.append(r[0]) report_lines.append("2. WITHOUT INDEX") await conn.execute(text("SET LOCAL enable_indexscan = off")) await conn.execute(text("SET LOCAL enable_bitmapscan = off")) result = await conn.execute(text(""" EXPLAIN (ANALYZE, BUFFERS) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = :chat_id ORDER BY created_at ASC, id ASC LIMIT 51 """), {"chat_id": chat_id}) for r in result: report_lines.append(r[0]) await conn.execute(text("SET LOCAL enable_indexscan = on")) await conn.execute(text("SET LOCAL enable_bitmapscan = on")) report_lines.append("KEY OBSERVATIONS") report_lines.append("Variant 1 uses 'Index Scan using messages_chat_created_id_idx'") report_lines.append("Variant 2 uses 'Seq Scan' + 'Sort' (full table scan)") report_lines.append("Compare 'Buffers: shared hit=...' and 'Execution Time'") report = "\n".join(report_lines) print("\n" + report) Path("results").mkdir(exist_ok=True) output_path = Path("results/explain_comparison.txt") output_path.write_text(report, encoding="utf-8") print(f"\nSaved to {output_path}") if __name__ == "__main__": asyncio.run(main())