-- Chats, explicit membership and message history. 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) ); -- Chat lists are ordered by (created_at, id) for the same keyset cursor. CREATE INDEX chats_order_idx ON chats (created_at, id); 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, joined_at timestamptz NOT NULL, PRIMARY KEY (chat_id, user_id) ); -- "Chats of the current user" and the membership check on every read. 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 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, CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 1 AND 4000) ); -- Serves history keyset pagination exactly: equality on chat_id, then the -- (created_at, id) tuple used by both ORDER BY and the cursor predicate. -- Justification and EXPLAIN (ANALYZE, BUFFERS) are in evidence/explain-history.txt. CREATE INDEX messages_chat_order_idx ON messages (chat_id, created_at, id);