Files
mtusi2026lab2/scripts/explain.sql
T
RainakandClaude Opus 5.5 0c5846173b
Skeleton contracts / contracts (pull_request) Canceled after 0s
ЛР2: PostgreSQL, сессии и Valkey (на 4)
API мессенджера на FastAPI + asyncpg, миграции, Argon2id, Bearer-сессии
в PostgreSQL с кэшем Valkey, compose-стенд, restart.sh, тесты уровня 4,
EXPLAIN и отчёт.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:49:32 +03:00

79 lines
4.3 KiB
PL/PgSQL
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- Обоснование индекса истории: синтетические данные + EXPLAIN (ANALYZE, BUFFERS) реальных запросов API.
-- Seed идемпотентен (маркер — пользователь bench_owner). Пароль бенч-пользователей невалиден: войти нельзя.
\set ON_ERROR_STOP 1
\pset pager off
DO $$
DECLARE
owner uuid; peer uuid; big uuid; small uuid;
BEGIN
IF EXISTS (SELECT 1 FROM users WHERE username = 'bench_owner') THEN
RETURN;
END IF;
INSERT INTO users (username, display_name, password_hash) VALUES ('bench_owner', 'Bench', '!') RETURNING id INTO owner;
INSERT INTO users (username, display_name, password_hash) VALUES ('bench_peer', 'Bench', '!') RETURNING id INTO peer;
-- Один большой чат: 20 000 сообщений.
INSERT INTO chats (title, created_by) VALUES ('bench big', owner) RETURNING id INTO big;
INSERT INTO chat_members (chat_id, user_id) VALUES (big, owner), (big, peer);
INSERT INTO messages (chat_id, sender_id, text, created_at)
SELECT big, CASE WHEN n % 2 = 0 THEN owner ELSE peer END, 'bench message ' || n,
timestamptz '2026-01-01 00:00:00+00' + n * interval '1 second'
FROM generate_series(1, 20000) AS n;
-- 30 чатов по 1 000 сообщений — "шум" других чатов в той же таблице.
FOR i IN 1..30 LOOP
INSERT INTO chats (title, created_by) VALUES ('bench small ' || i, owner) RETURNING id INTO small;
INSERT INTO chat_members (chat_id, user_id) VALUES (small, owner);
INSERT INTO messages (chat_id, sender_id, text, created_at)
SELECT small, owner, 'noise ' || n, timestamptz '2026-01-01 00:00:00+00' + n * interval '1 second'
FROM generate_series(1, 1000) AS n;
END LOOP;
END $$;
ANALYZE users, chats, chat_members, messages;
SELECT id AS big_chat FROM chats WHERE title = 'bench big' \gset
\echo '== Объём данных'
SELECT (SELECT count(*) FROM messages) AS total_messages,
(SELECT count(*) FROM messages WHERE chat_id = :'big_chat') AS big_chat_messages,
pg_size_pretty(pg_relation_size('messages')) AS table_size,
pg_size_pretty(pg_relation_size('messages_chat_created_id_idx')) AS index_size;
-- Курсор "из середины": последняя строка 300-й страницы по 50.
SELECT created_at AS cur_t, id AS cur_i FROM messages WHERE chat_id = :'big_chat'
ORDER BY created_at, id OFFSET 14999 LIMIT 1 \gset
\echo '== 1. Первая страница (запрос API без cursor, limit=50 -> LIMIT 51)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' ORDER BY created_at, id LIMIT 51;
\echo '== 2. Страница 301 через keyset cursor (запрос API с cursor)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cur_t'::timestamptz, :'cur_i'::uuid)
ORDER BY created_at, id LIMIT 51;
\echo '== 3. Для сравнения: та же страница через OFFSET (НЕ используется в API)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' ORDER BY created_at, id OFFSET 15000 LIMIT 51;
\echo '== 4. Для сравнения: keyset-запрос без индекса (DROP INDEX внутри транзакции, затем ROLLBACK)'
BEGIN;
DROP INDEX messages_chat_created_id_idx;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cur_t'::timestamptz, :'cur_i'::uuid)
ORDER BY created_at, id LIMIT 51;
ROLLBACK;
\echo '== 5. Список чатов пользователя (запрос API GET /chats, limit=50)'
SELECT id AS owner_id FROM users WHERE username = 'bench_owner' \gset
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT cm.user_id FROM chat_members cm WHERE cm.chat_id = c.id ORDER BY cm.user_id) AS member_ids
FROM chats c JOIN chat_members m ON m.chat_id = c.id AND m.user_id = :'owner_id'
ORDER BY c.created_at, c.id LIMIT 51;