forked from mtusi2026/mtusi2026lab2
lab 2 realization: PostgreSQL, Valkey, track 2
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
"""Create a dedicated 10,000-message chat; record the real history query plans."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client, check
|
||||
from infrastructure import sql, ROOT
|
||||
|
||||
c=Client('http://127.0.0.1:8080')
|
||||
a=c.user('explain')
|
||||
chat=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'EXPLAIN 10000','member_ids':[a['id']]},schema='Chat')['json']
|
||||
# IDs below are generated by the API, not external SQL input. Data is synthetic.
|
||||
cid=str(uuid.UUID(chat['id']))
|
||||
uid=str(uuid.UUID(a['id']))
|
||||
sql(f"""INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
SELECT gen_random_uuid(),'{cid}','{uid}',convert_to('synthetic history row '||g,'UTF8'),
|
||||
'2026-01-01T00:00:00Z'::timestamptz+g*interval '1 millisecond'
|
||||
FROM generate_series(1,10000) AS g;
|
||||
ANALYZE messages;""")
|
||||
check(sql(f"SELECT count(*) FROM messages WHERE chat_id='{cid}';")=='10000','seed row count')
|
||||
plans=[]
|
||||
for label,bound in [('first','2026-01-01T00:00:00Z'),('deep (after 9000 rows)','2026-01-01T00:00:09Z')]:
|
||||
last='00000000-0000-0000-0000-000000000000'
|
||||
if label.startswith('deep'):
|
||||
last=str(uuid.UUID(sql(f"SELECT id FROM messages WHERE chat_id='{cid}' AND created_at='{bound}'::timestamptz;")))
|
||||
query=f"""EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages
|
||||
WHERE chat_id='{cid}' AND (created_at,id)>('{bound}'::timestamptz,'{last}'::uuid)
|
||||
ORDER BY messages.created_at,messages.id LIMIT 51;"""
|
||||
plan=sql(query)
|
||||
if 'messages_history_idx' not in plan or 'Seq Scan' in plan or 'Sort ' in plan:
|
||||
print(plan)
|
||||
raise AssertionError('history query must use ordered index')
|
||||
plans.append(label+'\n'+query+'\n'+plan)
|
||||
path=ROOT/'evidence/explain.txt'
|
||||
path.parent.mkdir(exist_ok=True)
|
||||
path.write_text('PostgreSQL: '+sql('SELECT version();')+'\nRows in dedicated chat: 10000\n\n'+'\n\n'.join(plans)+'\n',encoding='utf-8')
|
||||
print('PASS: 10000 messages; first and deep page use messages_history_idx without Seq Scan/Sort')
|
||||
print(path.relative_to(ROOT))
|
||||
Reference in New Issue
Block a user