CREATE TABLE attachments ( id UUID PRIMARY KEY, chat_id UUID NOT NULL REFERENCES chats (id), owner_id UUID NOT NULL, filename TEXT NOT NULL, object_key TEXT NOT NULL UNIQUE, 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 ~ '^[a-f0-9]{64}$'), integrity_missing BOOLEAN NOT NULL DEFAULT false, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL, UNIQUE (id, chat_id), FOREIGN KEY (chat_id, owner_id) REFERENCES chat_members (chat_id, user_id) ); CREATE INDEX attachments_scan ON attachments (id); ALTER TABLE messages DROP CONSTRAINT messages_text_not_blank; ALTER TABLE messages ADD CONSTRAINT messages_id_chat UNIQUE (id, chat_id); CREATE TABLE message_attachments ( message_id UUID NOT NULL, chat_id UUID NOT NULL, attachment_id UUID NOT NULL, position SMALLINT NOT NULL CHECK (position BETWEEN 0 AND 9), PRIMARY KEY (message_id, attachment_id), UNIQUE (message_id, position), FOREIGN KEY (message_id, chat_id) REFERENCES messages (id, chat_id), FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments (id, chat_id) ); ALTER TABLE message_idempotency ADD COLUMN hash_version SMALLINT NOT NULL DEFAULT 1; ---- create above / drop below ---- ALTER TABLE message_idempotency DROP COLUMN hash_version; DROP TABLE message_attachments; ALTER TABLE messages DROP CONSTRAINT messages_id_chat; ALTER TABLE messages ADD CONSTRAINT messages_text_not_blank CHECK (text !~ '^[[:space:]]*$'); DROP TABLE attachments;