-- Initial schema for lab2. Applied once by app/migrate.py inside one transaction. 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 DEFAULT clock_timestamp(), CONSTRAINT users_username_key UNIQUE (username), CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100) ); CREATE TABLE chats ( id uuid PRIMARY KEY, title text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100) ); -- position keeps member_ids in the order the creator sent them. CREATE TABLE chat_members ( chat_id uuid NOT NULL REFERENCES chats (id), user_id uuid NOT NULL REFERENCES users (id), position smallint NOT NULL, PRIMARY KEY (chat_id, user_id) ); -- "Chats of a user": GET /chats starts from the caller's memberships. 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, sender_id uuid NOT NULL, text text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), -- The sender must be a member of the chat, enforced by the database itself. CONSTRAINT messages_sender_member_fk FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id), CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000) ); -- Keyset pagination of history: WHERE chat_id = $1 AND (created_at, id) > ($2, $3) -- ORDER BY created_at, id LIMIT n. Justified by EXPLAIN in evidence/explain_history.txt. CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id); -- Sessions: PostgreSQL is the source of truth; Valkey only caches lookups. -- token_hash = sha256(token); the raw token is never stored. CREATE TABLE sessions ( token_hash bytea PRIMARY KEY, user_id uuid NOT NULL REFERENCES users (id), created_at timestamptz NOT NULL DEFAULT clock_timestamp(), expires_at timestamptz NOT NULL, revoked_at timestamptz ); CREATE INDEX sessions_expires_idx ON sessions (expires_at);