-- Additive migration. Existing text messages have no attachment links. ALTER TABLE messages ADD CONSTRAINT messages_id_chat_id_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), 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')), size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760), sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), object_key text NOT NULL UNIQUE CHECK (object_key LIKE 'attachments/%'), -- pending is internal. The upload API exposes ready after committing metadata. status text NOT NULL CHECK (status IN ('pending', 'ready', 'failed')), error_code text, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), UNIQUE (id, chat_id), CHECK ((status = 'failed') = (error_code IS NOT NULL)) ); CREATE INDEX attachments_pending_updated_idx ON attachments (updated_at, id) WHERE status = 'pending'; CREATE TABLE message_attachments ( message_id uuid NOT NULL, attachment_id uuid NOT NULL, chat_id uuid NOT NULL, position smallint NOT NULL CHECK (position BETWEEN 0 AND 9), PRIMARY KEY (message_id, position), UNIQUE (message_id, attachment_id), FOREIGN KEY (message_id, chat_id) REFERENCES messages(id, chat_id) ON DELETE CASCADE, FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments(id, chat_id) ); CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);