-- Existing Lab 4 rows keep their original keys, metadata and message links. ALTER TABLE attachments DROP CONSTRAINT attachments_status_check; ALTER TABLE attachments DROP CONSTRAINT attachments_check; ALTER TABLE attachments ALTER COLUMN status SET DEFAULT 'queued'; ALTER TABLE attachments ADD CHECK (status IN ('queued', 'processing', 'ready', 'failed')); ALTER TABLE attachments ADD CHECK ((status = 'failed') = (error_code IS NOT NULL)); CREATE TABLE attachment_jobs ( job_id uuid PRIMARY KEY, attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id), pipeline_version integer NOT NULL CHECK (pipeline_version = 1), staging_key text NOT NULL UNIQUE, created_at timestamptz NOT NULL, attempt integer NOT NULL DEFAULT 1, max_attempts integer NOT NULL CHECK (max_attempts BETWEEN 1 AND 20), retry_at timestamptz NOT NULL DEFAULT now(), last_error text, CHECK (attempt BETWEEN 1 AND max_attempts) ); CREATE TABLE attachment_variants ( attachment_id uuid NOT NULL REFERENCES attachments(id), pipeline_version integer NOT NULL CHECK (pipeline_version = 1), name text NOT NULL CHECK (name = 'thumbnail'), content_type text NOT NULL CHECK (content_type = 'image/jpeg'), size_bytes integer NOT NULL CHECK (size_bytes > 0), sha256 text NOT NULL CHECK (sha256 COLLATE "C" ~ '^[a-f0-9]{64}$'), width integer NOT NULL CHECK (width BETWEEN 1 AND 256), height integer NOT NULL CHECK (height BETWEEN 1 AND 256), object_key text NOT NULL UNIQUE, PRIMARY KEY (attachment_id, pipeline_version, name) );