ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_len; ALTER TABLE messages ADD CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 0 AND 4000); CREATE TABLE IF NOT EXISTS 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, content_type text NOT NULL, size_bytes bigint NOT NULL, sha256 bytea NOT NULL, object_key text NOT NULL, status text NOT NULL, error_code text, created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL, CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255), CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')), CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760), CONSTRAINT attachments_sha256_len CHECK (octet_length(sha256) = 32), CONSTRAINT attachments_status CHECK (status IN ('pending', 'ready', 'failed')), CONSTRAINT attachments_error_state CHECK ( (status = 'pending' AND error_code IS NULL) OR (status = 'ready' AND error_code IS NULL) OR (status = 'failed' AND error_code IS NOT NULL) ), CONSTRAINT attachments_object_key_key UNIQUE (object_key) ); CREATE INDEX IF NOT EXISTS attachments_chat_created_idx ON attachments (chat_id, created_at, id); CREATE INDEX IF NOT EXISTS attachments_status_created_idx ON attachments (status, created_at); CREATE TABLE IF NOT EXISTS 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 integer NOT NULL, PRIMARY KEY (message_id, attachment_id), CONSTRAINT message_attachments_position CHECK (position >= 0), CONSTRAINT message_attachments_position_key UNIQUE (message_id, position) ); CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments (attachment_id);