CREATE TABLE users ( id uuid PRIMARY KEY, username varchar(32) NOT NULL UNIQUE, display_name varchar(100) NOT NULL, password_hash varchar(255) NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE chats ( id uuid PRIMARY KEY, title varchar(100) NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); 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 CASCADE, PRIMARY KEY (chat_id, user_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), text varchar(4000) NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX messages_chat_created_idx ON messages(chat_id, created_at, id); CREATE TABLE sessions ( token varchar(128) PRIMARY KEY, user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, expires_at timestamptz NOT NULL ); CREATE INDEX sessions_expiry_idx ON sessions(expires_at); CREATE TABLE idempotency_keys ( user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, key varchar(128) NOT NULL, body_hash varchar(128) NOT NULL, message_id uuid NOT NULL UNIQUE REFERENCES messages(id) ON DELETE CASCADE, PRIMARY KEY (user_id, chat_id, key) ); CREATE TABLE attachments ( id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, owner_id uuid NOT NULL REFERENCES users(id), filename varchar(255) NOT NULL, content_type varchar(32) NOT NULL, size_bytes bigint NOT NULL, sha256 varchar(64) NOT NULL, object_key varchar(255) NOT NULL UNIQUE, status varchar(16) NOT NULL DEFAULT 'queued', error_code varchar(64), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE attachment_variants ( attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, name varchar(32) NOT NULL, content_type varchar(64) NOT NULL, size_bytes bigint NOT NULL, sha256 varchar(64) NOT NULL, width integer NOT NULL, height integer NOT NULL, object_key varchar(255) NOT NULL UNIQUE, PRIMARY KEY (attachment_id, name) ); CREATE TABLE attachment_jobs ( job_id uuid PRIMARY KEY, attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id) ON DELETE CASCADE, attempt integer NOT NULL DEFAULT 0, status varchar(16) NOT NULL DEFAULT 'queued', available_at timestamptz NOT NULL DEFAULT now(), error_code varchar(64), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE message_attachments ( message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE, attachment_id uuid NOT NULL REFERENCES attachments(id), PRIMARY KEY (message_id, attachment_id) );