Files
mtusi2026lab4/scripts/explain_history.sql
T

57 lines
2.6 KiB
PL/PgSQL

\set chat '00000000-0000-4000-8000-000000000100'
\pset pager off
\echo '== Объём данных'
SELECT count(*) AS messages_total,
count(*) FILTER (WHERE chat_id = :'chat') AS messages_in_chat,
pg_size_pretty(pg_relation_size('messages')) AS table_size,
pg_size_pretty(pg_relation_size('messages_chat_history_idx')) AS index_size
FROM messages;
\echo
\echo '== 1. Первая страница (limit 50, запрос берёт 51 строку)'
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at,
COALESCE((SELECT array_agg(a.attachment_id ORDER BY a.position) FROM message_attachments a
WHERE a.message_id = messages.id), '{}'::uuid[]) AS attachment_ids
FROM messages
WHERE chat_id = :'chat'
ORDER BY created_at, id LIMIT 51;
-- cursor на 5000-е сообщение чата, как его получил бы клиент после 100 страниц
SELECT created_at AS after_time, id AS after_id FROM messages
WHERE chat_id = :'chat' ORDER BY created_at, id OFFSET 4999 LIMIT 1 \gset
\echo
\echo '== 2. Страница из середины истории: keyset после 5000-го сообщения'
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at,
COALESCE((SELECT array_agg(a.attachment_id ORDER BY a.position) FROM message_attachments a
WHERE a.message_id = messages.id), '{}'::uuid[]) AS attachment_ids
FROM messages
WHERE chat_id = :'chat' AND (created_at, id) > (:'after_time', :'after_id')
ORDER BY created_at, id LIMIT 51;
\echo
\echo '== 3. Та же страница через OFFSET (так делать не стали)'
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at,
COALESCE((SELECT array_agg(a.attachment_id ORDER BY a.position) FROM message_attachments a
WHERE a.message_id = messages.id), '{}'::uuid[]) AS attachment_ids
FROM messages
WHERE chat_id = :'chat'
ORDER BY created_at, id OFFSET 5000 LIMIT 51;
\echo
\echo '== 4. Запрос из пункта 2 без индекса messages_chat_history_idx (DROP INDEX внутри транзакции с ROLLBACK)'
BEGIN;
DROP INDEX messages_chat_history_idx;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at,
COALESCE((SELECT array_agg(a.attachment_id ORDER BY a.position) FROM message_attachments a
WHERE a.message_id = messages.id), '{}'::uuid[]) AS attachment_ids
FROM messages
WHERE chat_id = :'chat' AND (created_at, id) > (:'after_time', :'after_id')
ORDER BY created_at, id LIMIT 51;
ROLLBACK;