-- Все операции идемпотентны (IF NOT EXISTS) -- Пользователи CREATE TABLE IF NOT EXISTS users ( id uuid PRIMARY KEY, username text NOT NULL, display_name text NOT NULL, password_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), CONSTRAINT users_username_re CHECK (username ~ '^[a-z0-9_]{3,32}$'), CONSTRAINT users_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100) ); CREATE UNIQUE INDEX IF NOT EXISTS users_username_key ON users (username); -- Чаты CREATE TABLE IF NOT EXISTS chats ( id uuid PRIMARY KEY, title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), created_at timestamptz NOT NULL DEFAULT now() ); -- Участники чатов CREATE TABLE IF NOT EXISTS chat_members ( chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, PRIMARY KEY (chat_id, user_id) ); CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members (user_id, chat_id); -- Сообщения CREATE TABLE IF NOT EXISTS messages ( id uuid NOT NULL, chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, sender_id uuid NOT NULL REFERENCES users(id), text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (chat_id, id) ); CREATE INDEX IF NOT EXISTS messages_history_idx ON messages (chat_id, created_at, id); -- Сессии (источник истины) CREATE TABLE IF NOT EXISTS sessions ( token_hash bytea PRIMARY KEY, user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, expires_at timestamptz NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX IF NOT EXISTS sessions_expires_idx ON sessions (expires_at);