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 ); 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, created_at TIMESTAMPTZ NOT NULL ); 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, position INT NOT NULL, PRIMARY KEY (chat_id, user_id) ); CREATE INDEX IF NOT EXISTS chat_members_user_id_idx ON chat_members (user_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 CASCADE, text TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL ); CREATE INDEX IF NOT EXISTS messages_chat_history_idx ON messages (chat_id, created_at ASC, id ASC);