forked from mtusi2026/mtusi2026lab2
lab2
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Seed >=10k messages and print EXPLAIN (ANALYZE, BUFFERS) for history pagination."""
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import psycopg
|
||||
|
||||
|
||||
def main():
|
||||
url = os.environ.get('DATABASE_URL')
|
||||
if not url:
|
||||
print('Set DATABASE_URL', file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
chat_id = os.environ.get('EXPLAIN_CHAT_ID')
|
||||
user_id = os.environ.get('EXPLAIN_USER_ID')
|
||||
count = int(os.environ.get('EXPLAIN_MESSAGE_COUNT', '10000'))
|
||||
with psycopg.connect(url) as conn:
|
||||
if not chat_id or not user_id:
|
||||
user_id = str(uuid.uuid4())
|
||||
chat_id = str(uuid.uuid4())
|
||||
now = datetime.now(timezone.utc)
|
||||
conn.execute(
|
||||
'INSERT INTO users (id, username, display_name, password_hash, created_at) '
|
||||
'VALUES (%s, %s, %s, %s, %s)',
|
||||
(user_id, 'bench_' + uuid.uuid4().hex[:8], 'Bench', 'x', now),
|
||||
)
|
||||
conn.execute(
|
||||
'INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)',
|
||||
(chat_id, 'Bench', now),
|
||||
)
|
||||
conn.execute(
|
||||
'INSERT INTO chat_members (chat_id, user_id, position) VALUES (%s, %s, 0)',
|
||||
(chat_id, user_id),
|
||||
)
|
||||
print(f'created chat_id={chat_id} user_id={user_id}')
|
||||
existing = conn.execute(
|
||||
'SELECT count(*) FROM messages WHERE chat_id = %s',
|
||||
(chat_id,),
|
||||
).fetchone()[0]
|
||||
need = max(0, count - existing)
|
||||
base = datetime.now(timezone.utc)
|
||||
with conn.cursor() as cur:
|
||||
for index in range(need):
|
||||
cur.execute(
|
||||
'INSERT INTO messages (id, chat_id, sender_id, text, created_at) '
|
||||
'VALUES (%s, %s, %s, %s, %s)',
|
||||
(
|
||||
str(uuid.uuid4()),
|
||||
chat_id,
|
||||
user_id,
|
||||
'm',
|
||||
base,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
plan = conn.execute(
|
||||
'EXPLAIN (ANALYZE, BUFFERS) '
|
||||
'SELECT id FROM messages WHERE chat_id = %s '
|
||||
'ORDER BY created_at ASC, id ASC LIMIT 50',
|
||||
(chat_id,),
|
||||
).fetchall()
|
||||
for row in plan:
|
||||
print(row[0])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user