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_key UNIQUE (username) ); CREATE TABLE chats ( id uuid PRIMARY KEY, title text NOT NULL, created_at timestamptz NOT NULL ); CREATE TABLE chat_members ( chat_id uuid NOT NULL REFERENCES chats (id), user_id uuid NOT NULL REFERENCES users (id), position integer NOT NULL, PRIMARY KEY (chat_id, user_id) ); CREATE TABLE messages ( id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats (id), sender_id uuid NOT NULL REFERENCES users (id), body text NOT NULL, created_at timestamptz NOT NULL ); CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id); CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id); CREATE INDEX chats_order_idx ON chats (created_at, id); CREATE TABLE app_clock ( id integer PRIMARY KEY, millis bigint NOT NULL, CONSTRAINT app_clock_one CHECK (id = 1) ); INSERT INTO app_clock (id, millis) VALUES (1, 0);