Files
samsikandCursor ae4d626ce6 Add PostgreSQL storage and Valkey sessions for lab2.
Messages survive restart in Postgres, and bearer sessions persist in Valkey with AOF.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-09 01:21:39 +03:00

50 lines
1.8 KiB
SQL

-- Источник истины lab2: пользователи, чаты, участники, сообщения.
-- Сессии здесь не хранятся: их источник истины — Valkey (AOF + volume).
--
-- Транзакции приложения:
-- регистрация — один INSERT, уникальность username держит UNIQUE
-- создание чата — одна транзакция: чат и все chat_members, иначе откат
-- сообщение — один INSERT, только если отправитель уже участник
--
-- Индекс истории messages_history_idx покрывает keyset-запрос
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
-- ORDER BY created_at, id
-- LIMIT $4
-- Страница читается диапазоном индекса, а не сканом всей таблицы.
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_username_unique UNIQUE (username)
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL
);
CREATE INDEX chats_created_idx ON chats (created_at, id);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id),
user_id uuid NOT NULL REFERENCES users (id),
position integer NOT NULL,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id),
sender_id uuid NOT NULL REFERENCES users (id),
text text NOT NULL,
created_at timestamptz NOT NULL
);
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);