ALTER TABLE messages ADD CONSTRAINT messages_id_chat_key UNIQUE (id, chat_id); 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) ON DELETE RESTRICT, filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255), content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')), upload_mode text NOT NULL CHECK (upload_mode IN ('proxy', 'direct')), status text NOT NULL CHECK (status IN ('pending', 'ready', 'deleting')), object_key text NOT NULL UNIQUE, size_bytes bigint CHECK (size_bytes BETWEEN 1 AND 10485760), sha256 text CHECK (sha256 ~ '^[a-f0-9]{64}$'), width integer CHECK (width > 0), height integer CHECK (height > 0), expires_at timestamptz(3), created_at timestamptz(3) NOT NULL DEFAULT now(), updated_at timestamptz(3) NOT NULL DEFAULT now(), CONSTRAINT attachments_id_chat_key UNIQUE (id, chat_id), CONSTRAINT attachments_owner_member_fk FOREIGN KEY (chat_id, owner_id) REFERENCES chat_members (chat_id, user_id), CONSTRAINT attachments_ready_complete CHECK (status <> 'ready' OR (size_bytes IS NOT NULL AND sha256 IS NOT NULL AND width IS NOT NULL AND height IS NOT NULL)), CONSTRAINT attachments_unfinished_expiry CHECK (status = 'ready' OR expires_at IS NOT NULL) ); CREATE INDEX attachments_unfinished_idx ON attachments (expires_at) WHERE status <> 'ready'; CREATE INDEX attachments_owner_direct_pending_idx ON attachments (owner_id) WHERE status = 'pending' AND upload_mode = 'direct'; CREATE TABLE message_attachments ( message_id uuid NOT NULL, chat_id uuid NOT NULL, attachment_id uuid NOT NULL, ordinal smallint NOT NULL CHECK (ordinal BETWEEN 1 AND 10), PRIMARY KEY (message_id, attachment_id), CONSTRAINT message_attachments_ordinal_key UNIQUE (message_id, ordinal), CONSTRAINT message_attachments_message_fk FOREIGN KEY (message_id, chat_id) REFERENCES messages (id, chat_id) ON DELETE CASCADE, CONSTRAINT message_attachments_attachment_fk FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments (id, chat_id) ); CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);