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), object_key text NOT NULL UNIQUE, 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 ~ '^[a-f0-9]{64}$'), created_at timestamptz NOT NULL DEFAULT clock_timestamp() ); CREATE INDEX attachments_chat_idx ON attachments(chat_id); ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}'; ALTER TABLE messages DROP CONSTRAINT messages_text_check; ALTER TABLE messages ADD CHECK (char_length(text) <= 4000); ALTER TABLE messages ADD CHECK (length(btrim(text)) > 0 OR cardinality(attachment_ids) > 0); ALTER TABLE messages ADD CHECK (cardinality(attachment_ids) <= 10);