-- Lab2 schema. PostgreSQL is the source of truth for users, chats, chat -- membership and messages. Sessions intentionally live in Valkey with a TTL. 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_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100), CONSTRAINT users_password_hash_present CHECK (length(password_hash) > 0) ); -- Uniqueness is enforced by the database, not by a read-then-insert check, so -- two concurrent registrations of the same username cannot both succeed. CREATE UNIQUE INDEX users_username_key ON users (username); CREATE TABLE chats ( id uuid PRIMARY KEY, title text NOT NULL, created_at timestamptz NOT NULL, CONSTRAINT chats_title_length CHECK (char_length(title) BETWEEN 1 AND 100) ); CREATE TABLE chat_members ( chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, user_id uuid NOT NULL REFERENCES users (id), position integer NOT NULL, PRIMARY KEY (chat_id, user_id), CONSTRAINT chat_members_position_nonnegative CHECK (position >= 0) ); -- "Chats of the current user" walks chat_members by user_id. CREATE INDEX chat_members_user_chat_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, CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 1 AND 4000), CONSTRAINT messages_chat_fk FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE, -- The sender must be a member of the chat at the database level too, not -- only in the HTTP handler. CONSTRAINT messages_sender_membership_fk FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id) );