-- Migration 003: Attachments & Message-Attachment links for Lab 4 (S3 metadata in PostgreSQL) ALTER TABLE messages DROP CONSTRAINT IF EXISTS chk_messages_text; ALTER TABLE messages ADD CONSTRAINT chk_messages_text CHECK (char_length(text) <= 4000); 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 CONSTRAINT chk_attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')), size_bytes BIGINT NOT NULL CONSTRAINT chk_attachments_size_bytes CHECK (size_bytes >= 1 AND size_bytes <= 10485760), sha256 CHAR(64) NOT NULL, object_key TEXT NOT NULL UNIQUE, status VARCHAR(16) NOT NULL DEFAULT 'ready' CONSTRAINT chk_attachments_status CHECK (status IN ('pending', 'ready', 'failed')), error_code VARCHAR(64), created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); CREATE INDEX IF NOT EXISTS idx_attachments_chat_id ON attachments (chat_id); CREATE INDEX IF NOT EXISTS idx_attachments_status_created ON attachments (status, 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, ord INT NOT NULL DEFAULT 0, PRIMARY KEY (message_id, attachment_id) ); CREATE INDEX IF NOT EXISTS idx_message_attachments_att_id ON message_attachments (attachment_id);