ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_nonblank; ALTER TABLE messages ADD COLUMN IF NOT EXISTS attachment_ids UUID[] NOT NULL DEFAULT ARRAY[]::UUID[]; 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 VARCHAR(255) NOT NULL, content_type VARCHAR(32) NOT NULL CHECK (content_type IN ('image/png','image/jpeg')), size_bytes BIGINT NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760), sha256 CHAR(64) NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), object_key TEXT NOT NULL UNIQUE, status VARCHAR(16) NOT NULL CHECK (status IN ('ready')), created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments(chat_id, 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, PRIMARY KEY(message_id, attachment_id) );