-- A file is owned by exactly one chat. Binary bytes live only in private S3. 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 CHECK (content_type IN ('image/png','image/jpeg')), size_bytes INTEGER NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760), sha256 CHAR(64) NOT NULL, object_key VARCHAR(160) NOT NULL UNIQUE, status VARCHAR(20) NOT NULL DEFAULT 'ready' CHECK (status='ready'), created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX attachments_chat_idx ON attachments(chat_id); ALTER TABLE messages DROP CONSTRAINT nonblank_message; -- Blank text is permitted only with attachment IDs; enforced by application transaction. CREATE TABLE message_attachments ( message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE, attachment_id UUID NOT NULL REFERENCES attachments(id), position SMALLINT NOT NULL CHECK (position BETWEEN 0 AND 9), PRIMARY KEY (message_id, attachment_id), UNIQUE (message_id, position) ); CREATE INDEX message_attachments_attachment_idx ON message_attachments(attachment_id);