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 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}$'), object_key TEXT NOT NULL UNIQUE, status TEXT NOT NULL DEFAULT 'ready', created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX idx_attachments_chat 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), position SMALLINT NOT NULL, PRIMARY KEY (message_id, attachment_id) ); CREATE INDEX idx_message_attachments_attachment ON message_attachments (attachment_id); ALTER TABLE messages DROP CONSTRAINT text_length; ALTER TABLE messages ADD CONSTRAINT text_length CHECK ( bytea_utf8_char_length(text) BETWEEN 0 AND 4000 );