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 text NOT NULL, content_type text NOT NULL, size_bytes bigint NOT NULL, sha256 char(64) NOT NULL, object_key text NOT NULL, status text NOT NULL, error_code text, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), CONSTRAINT attachments_filename_length CHECK (char_length(filename) BETWEEN 1 AND 255), CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')), CONSTRAINT attachments_size_positive CHECK (size_bytes > 0 AND size_bytes <= 10485760), CONSTRAINT attachments_sha256_format CHECK (sha256 ~ '^[a-f0-9]{64}$'), CONSTRAINT attachments_object_key_unique UNIQUE (object_key), CONSTRAINT attachments_status CHECK (status IN ('pending', 'ready', 'failed')), CONSTRAINT attachments_error_code CHECK ( (status = 'ready' AND error_code IS NULL) OR (status = 'failed' AND error_code IS NOT NULL) OR (status = 'pending') ) ); CREATE INDEX attachments_chat_created_idx ON attachments (chat_id, created_at); CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending'; 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 int NOT NULL, PRIMARY KEY (message_id, attachment_id), CONSTRAINT message_attachments_position CHECK (position >= 0) ); CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);