forked from mtusi2026/mtusi2026lab2
feat: explain analyze
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
\set ON_ERROR_STOP on
|
||||
\pset pager off
|
||||
\set owner '''00000000-0000-4000-8000-000000000001'''
|
||||
\set target '''00000000-0000-4000-8000-0000000000c0'''
|
||||
|
||||
BEGIN;
|
||||
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES (:owner, 'explain_owner', 'Explain', 'not-a-real-hash');
|
||||
|
||||
INSERT INTO chats (id, title) VALUES (:target, 'explain target');
|
||||
INSERT INTO chats (id, title) SELECT gen_random_uuid(), 'explain other ' || g FROM generate_series(1, 20) g;
|
||||
INSERT INTO chat_members (chat_id, user_id) SELECT id, :owner FROM chats WHERE title LIKE 'explain %';
|
||||
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), c.id, :owner, 'synthetic message ' || g,
|
||||
timestamptz '2026-01-01 00:00:00Z' + g * interval '1 millisecond'
|
||||
FROM chats c
|
||||
CROSS JOIN LATERAL generate_series(1, CASE WHEN c.id = :target THEN 10000 ELSE 2000 END) g
|
||||
WHERE c.title LIKE 'explain %';
|
||||
|
||||
ANALYZE messages;
|
||||
|
||||
SELECT count(*) FILTER (WHERE chat_id = :target) AS target_chat_messages, count(*) AS total_messages FROM messages;
|
||||
|
||||
SELECT created_at AS anchor_ts, id AS anchor_id FROM messages WHERE chat_id = :target
|
||||
ORDER BY created_at, id OFFSET 8999 LIMIT 1 \gset
|
||||
|
||||
\echo '=== 1. Keyset, first page (index messages_chat_id_created_at_id_idx)'
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = :target
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
\echo '=== 2. Keyset, page after message #9000'
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = :target AND (created_at, id) > (:'anchor_ts'::timestamptz, :'anchor_id'::uuid)
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
\echo '=== 3. For comparison: OFFSET 9000 reads and discards all previous rows'
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = :target
|
||||
ORDER BY created_at, id OFFSET 9000 LIMIT 51;
|
||||
|
||||
\echo '=== 4. For comparison: keyset page #9000 without the index'
|
||||
DROP INDEX messages_chat_id_created_at_id_idx;
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = :target AND (created_at, id) > (:'anchor_ts'::timestamptz, :'anchor_id'::uuid)
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
ROLLBACK;
|
||||
Reference in New Issue
Block a user