CREATE TABLE IF NOT EXISTS users ( id uuid PRIMARY KEY, username varchar(32) NOT NULL UNIQUE, display_name varchar(100) NOT NULL, password_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), CONSTRAINT users_display_name_nonblank CHECK (length(btrim(display_name)) > 0) ); CREATE TABLE IF NOT EXISTS chats ( id uuid PRIMARY KEY, title varchar(100) NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), CONSTRAINT chats_title_nonblank CHECK (length(btrim(title)) > 0) ); 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 RESTRICT, PRIMARY KEY (chat_id, user_id) ); CREATE INDEX IF NOT EXISTS chat_members_by_user ON chat_members (user_id, chat_id); CREATE TABLE IF NOT EXISTS messages ( id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT, text varchar(4000) NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), CONSTRAINT messages_text_nonblank CHECK (length(btrim(text)) > 0) ); CREATE INDEX IF NOT EXISTS messages_history_keyset 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, revoked_at timestamptz, created_at timestamptz NOT NULL DEFAULT clock_timestamp() ); CREATE INDEX IF NOT EXISTS sessions_active_by_expiry ON sessions (expires_at) WHERE revoked_at IS NULL; CREATE TABLE IF NOT EXISTS schema_migrations ( version varchar(255) PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT clock_timestamp() );