forked from mtusi2026/mtusi2026lab3
51 lines
1.8 KiB
Python
51 lines
1.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Seed 10k synthetic messages and save the indexed history query plan."""
|
|
|
|
from pathlib import Path
|
|
import subprocess
|
|
import uuid
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def psql(sql):
|
|
command = ["docker", "compose", "--env-file", ".env", "exec", "-T", "postgres",
|
|
"psql", "-U", "messenger", "-d", "messenger", "-X", "-q", "-t", "-A",
|
|
"-v", "ON_ERROR_STOP=1", "-c", sql]
|
|
return subprocess.run(command, cwd=ROOT, check=True, capture_output=True, text=True).stdout.strip()
|
|
|
|
|
|
def main():
|
|
owner = psql("SELECT id FROM users ORDER BY created_at LIMIT 1")
|
|
if not owner:
|
|
raise SystemExit("Run make test first to create a synthetic user")
|
|
owner = str(uuid.UUID(owner))
|
|
chat = str(uuid.uuid4())
|
|
psql(f"""
|
|
BEGIN;
|
|
INSERT INTO chats(id,title) VALUES ('{chat}', 'History index probe');
|
|
INSERT INTO chat_members(chat_id,user_id) VALUES ('{chat}', '{owner}');
|
|
INSERT INTO chat_versions(chat_id) VALUES ('{chat}');
|
|
INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
|
SELECT gen_random_uuid(), '{chat}', '{owner}', 'probe-' || g,
|
|
clock_timestamp() + g * interval '1 microsecond'
|
|
FROM generate_series(1,10000) AS g;
|
|
COMMIT;
|
|
ANALYZE messages;
|
|
""")
|
|
count = psql(f"SELECT count(*) FROM messages WHERE chat_id='{chat}'")
|
|
assert count == "10000", count
|
|
plan = psql(f"""
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id,chat_id,sender_id,text,created_at FROM messages
|
|
WHERE chat_id='{chat}' ORDER BY created_at,id LIMIT 101;
|
|
""")
|
|
result = f"synthetic_chat_id={chat}\nmessage_count={count}\n{plan}\n"
|
|
(ROOT / "evidence/history_explain.txt").write_text(result)
|
|
print(result)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|