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 CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255), content_type text NOT NULL CONSTRAINT attachments_ct CHECK (content_type IN ('image/png', 'image/jpeg')), size_bytes integer NOT NULL CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760), sha256 text NOT NULL CONSTRAINT attachments_sha CHECK (sha256 ~ '^[a-f0-9]{64}$'), object_key text NOT NULL, status text NOT NULL DEFAULT 'ready' CONSTRAINT attachments_status CHECK (status IN ('ready', 'failed')), error_code text, created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL ); CREATE INDEX attachments_chat_idx ON attachments (chat_id); CREATE TABLE message_attachments ( message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE, attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE RESTRICT, position smallint NOT NULL, PRIMARY KEY (message_id, attachment_id) );