-- +goose Up CREATE TABLE users ( id uuid PRIMARY KEY DEFAULT uuidv7(), username text NOT NULL, password_hash text NOT NULL, display_name text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), CONSTRAINT users_username_key UNIQUE (username), CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), CONSTRAINT users_display_name_not_blank CHECK (btrim(display_name) <> ''), CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100) ); CREATE TABLE chats ( id uuid PRIMARY KEY DEFAULT uuidv7(), title text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), CONSTRAINT chats_title_not_blank CHECK (btrim(title) <> '') ); CREATE TABLE chat_members ( chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, user_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (chat_id, user_id) ); CREATE TABLE messages ( id uuid PRIMARY KEY DEFAULT uuidv7(), chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, sender_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT, text text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), CONSTRAINT messages_text_not_blank CHECK (btrim(text) <> ''), CONSTRAINT messages_text_length CHECK (char_length(text) <= 4000) ); CREATE TABLE 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 TABLE user_chat_versions ( user_id uuid PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE, version bigint NOT NULL DEFAULT 0 ); CREATE INDEX messages_chat_id_created_at_id_idx ON messages (chat_id, created_at, id); CREATE INDEX chat_members_user_id_chat_id_idx ON chat_members (user_id, chat_id); CREATE INDEX chats_created_at_id_idx ON chats (created_at, id); CREATE INDEX sessions_user_id_idx ON sessions (user_id); -- +goose Down DROP TABLE sessions; DROP TABLE messages; DROP TABLE chat_members; DROP TABLE chats; DROP TABLE users; DROP TABLE user_chat_versions;