forked from mtusi2026/mtusi2026lab2
44 lines
1.8 KiB
Python
44 lines
1.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Produce an EXPLAIN (ANALYZE, BUFFERS) proof for the chat-history cursor query."""
|
|
import os
|
|
import uuid
|
|
|
|
import psycopg
|
|
|
|
DB_URL = os.getenv("DATABASE_URL", "postgresql://messenger:messenger@localhost:5432/messenger")
|
|
|
|
|
|
def main() -> None:
|
|
with psycopg.connect(DB_URL, connect_timeout=5) as conn:
|
|
with conn.cursor() as cur:
|
|
chat_id = uuid.uuid4()
|
|
user_id = uuid.uuid4()
|
|
cur.execute("INSERT INTO users(id, username, display_name, password_hash, created_at) VALUES (%s, %s, %s, %s, NOW())", (user_id, f"exp_{uuid.uuid4().hex[:12]}", "exp", "dummyhash"))
|
|
cur.execute("INSERT INTO chats(id, title, created_at) VALUES (%s, %s, NOW())", (chat_id, "exp"))
|
|
cur.execute("INSERT INTO chat_members(chat_id, user_id) VALUES (%s, %s)", (chat_id, user_id))
|
|
for idx in range(10000):
|
|
cur.execute(
|
|
"INSERT INTO messages(id, chat_id, sender_id, text, created_at) VALUES (%s, %s, %s, %s, NOW() - INTERVAL '%s milliseconds')",
|
|
(uuid.uuid4(), chat_id, user_id, f"msg-{idx}", idx),
|
|
)
|
|
conn.commit()
|
|
|
|
cursor_ts = "2100-01-01T00:00:00Z"
|
|
cursor_id = str(uuid.uuid4())
|
|
explain_sql = """
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = %s
|
|
AND (created_at, id) > (%s::timestamptz, %s::uuid)
|
|
ORDER BY created_at ASC, id ASC
|
|
LIMIT 1
|
|
"""
|
|
cur.execute(explain_sql, (chat_id, cursor_ts, cursor_id))
|
|
plan = cur.fetchall()
|
|
|
|
print("\n".join(row[0] for row in plan))
|
|
|
|
if __name__ == "__main__":
|
|
main()
|