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), filename VARCHAR(255) NOT NULL, content_type TEXT NOT NULL, size_bytes BIGINT NOT NULL, sha256 CHAR(64) NOT NULL, s3_key TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), CONSTRAINT attachments_filename_nonblank CHECK (length(btrim(filename)) > 0), 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 CHECK (sha256 ~ '^[a-f0-9]{64}$') ); CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments(chat_id); 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), position INTEGER NOT NULL, PRIMARY KEY (message_id, attachment_id) ); CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments(attachment_id); ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_nonblank;