Files
mtusi2026lab2/scripts/explain_pagination.py
T
healby 6038c0f375
Skeleton contracts / contracts (pull_request) Canceled after 0s
Fix cached session identity and document PR 63 regression checks
2026-10-24 08:34:58 +03:00

44 lines
2.0 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() - %s * INTERVAL '1 millisecond')",
(uuid.uuid4(), chat_id, user_id, f"msg-{idx}", idx),
)
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 51
"""
for offset in (0, 5000, 9900):
cur.execute("SELECT created_at, id FROM messages WHERE chat_id = %s ORDER BY created_at, id OFFSET %s LIMIT 1", (chat_id, offset))
cursor_ts, cursor_id = cur.fetchone()
cur.execute(explain_sql, (chat_id, cursor_ts, cursor_id))
print(f"Page after position {offset}:")
print("\n".join(row[0] for row in cur.fetchall()))
# Keep the measurement repeatable without accumulating fixtures.
conn.rollback()
if __name__ == "__main__":
main()