forked from mtusi2026/mtusi2026lab3
70 lines
1.5 KiB
PL/PgSQL
70 lines
1.5 KiB
PL/PgSQL
BEGIN;
|
|
|
|
CREATE TEMP TABLE explain_ctx (
|
|
user_id UUID,
|
|
chat_id UUID
|
|
);
|
|
|
|
WITH u AS (
|
|
INSERT INTO users (username, display_name, password_hash)
|
|
VALUES (
|
|
'explain_' || substr(gen_random_uuid()::text, 1, 8),
|
|
'Explain Test',
|
|
'test-hash'
|
|
)
|
|
RETURNING id
|
|
),
|
|
c AS (
|
|
INSERT INTO chats (title)
|
|
VALUES ('explain-10000')
|
|
RETURNING id
|
|
)
|
|
INSERT INTO explain_ctx (user_id, chat_id)
|
|
SELECT u.id, c.id
|
|
FROM u CROSS JOIN c;
|
|
|
|
INSERT INTO chat_members (chat_id, user_id)
|
|
SELECT chat_id, user_id
|
|
FROM explain_ctx;
|
|
|
|
INSERT INTO messages (chat_id, sender_id, text, created_at)
|
|
SELECT
|
|
chat_id,
|
|
user_id,
|
|
'message ' || gs,
|
|
TIMESTAMPTZ '2026-01-01 00:00:00+00' + gs * INTERVAL '1 second'
|
|
FROM explain_ctx
|
|
CROSS JOIN generate_series(1, 10000) AS gs;
|
|
|
|
ANALYZE messages;
|
|
|
|
\echo '=== FIRST PAGE ==='
|
|
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = (SELECT chat_id FROM explain_ctx)
|
|
ORDER BY created_at ASC, id ASC
|
|
LIMIT 20;
|
|
|
|
\echo '=== DEEP PAGE ==='
|
|
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = (SELECT chat_id FROM explain_ctx)
|
|
AND (created_at, id) > (
|
|
TIMESTAMPTZ '2026-01-01 02:00:00+00',
|
|
(
|
|
SELECT id
|
|
FROM messages
|
|
WHERE chat_id = (SELECT chat_id FROM explain_ctx)
|
|
AND created_at = TIMESTAMPTZ '2026-01-01 02:00:00+00'
|
|
LIMIT 1
|
|
)
|
|
)
|
|
ORDER BY created_at ASC, id ASC
|
|
LIMIT 20;
|
|
|
|
ROLLBACK;
|