Files
mtusi2026lab2/scripts/seed_10k.sql
T
2026-10-23 18:55:20 +03:00

54 lines
2.1 KiB
SQL

-- Synthetic history for the index evidence. Never run this against real data:
-- it deletes only messages of the dedicated seed chat and re-creates them.
\set ON_ERROR_STOP on
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', 'seed_10k', 'Seed 10k',
'not-a-login-hash', '2026-01-01T00:00:00Z')
ON CONFLICT (id) DO NOTHING;
INSERT INTO chats (id, title, created_at)
VALUES ('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', 'Seed 10k history', '2026-01-01T00:00:00Z')
ON CONFLICT (id) DO NOTHING;
INSERT INTO chat_members (chat_id, user_id)
VALUES ('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa')
ON CONFLICT DO NOTHING;
DELETE FROM messages WHERE chat_id = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(),
'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
'seed message ' || g,
'2026-01-01T00:00:00Z'::timestamptz + (g || ' seconds')::interval
FROM generate_series(1, 10000) AS g;
-- Remove index entries left by the previous seed run; without this the plan
-- reads dead entries and the buffer count reflects history, not page depth.
VACUUM (ANALYZE) messages;
SELECT count(*) AS seeded_messages
FROM messages
WHERE chat_id = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
-- First page: the same predicate the API sends with an empty cursor.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
AND (created_at, id) > ('0001-01-01T00:00:00Z'::timestamptz, '00000000-0000-0000-0000-000000000000'::uuid)
ORDER BY created_at, id
LIMIT 51;
-- Deep page: the cursor points at message 5000, so a correct plan seeks there
-- instead of scanning the first 5000 rows.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
AND (created_at, id) > ('2026-01-01T01:23:20Z'::timestamptz, '00000000-0000-0000-0000-000000000000'::uuid)
ORDER BY created_at, id
LIMIT 51;