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 ~ '^[a-f0-9]{64}$'), object_key varchar(160) NOT NULL UNIQUE, status varchar(16) NOT NULL DEFAULT 'ready' CHECK (status = 'ready'), created_at timestamptz NOT NULL DEFAULT clock_timestamp(), updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), CONSTRAINT attachments_filename_nonblank CHECK (length(filename) > 0), UNIQUE (id, chat_id) ); CREATE INDEX IF NOT EXISTS attachments_by_chat ON attachments (chat_id, created_at, id); CREATE UNIQUE INDEX IF NOT EXISTS messages_id_chat_unique ON messages (id, chat_id); CREATE TABLE IF NOT EXISTS message_attachments ( message_id uuid NOT NULL, chat_id uuid NOT NULL, attachment_id uuid NOT NULL, ordinal smallint NOT NULL CHECK (ordinal BETWEEN 0 AND 9), PRIMARY KEY (message_id, ordinal), UNIQUE (message_id, attachment_id), FOREIGN KEY (message_id, chat_id) REFERENCES messages(id, chat_id) ON DELETE CASCADE, FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments(id, chat_id) ON DELETE RESTRICT );