ALTER TABLE attachments DROP CONSTRAINT attachments_status_check; ALTER TABLE attachments ADD CHECK (status IN ('pending','queued','processing','ready','failed')); CREATE TABLE attachment_jobs ( id uuid PRIMARY KEY, attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, pipeline_version integer NOT NULL CHECK (pipeline_version > 0), attempt integer NOT NULL DEFAULT 1 CHECK (attempt > 0), created_at timestamptz NOT NULL DEFAULT now(), UNIQUE (attachment_id, pipeline_version) ); CREATE TABLE attachment_outbox ( job_id uuid NOT NULL REFERENCES attachment_jobs(id) ON DELETE CASCADE, attempt integer NOT NULL CHECK (attempt > 0), available_at timestamptz NOT NULL DEFAULT now(), published_at timestamptz, PRIMARY KEY (job_id, attempt) ); CREATE INDEX attachment_outbox_due_idx ON attachment_outbox (available_at) WHERE published_at IS NULL; CREATE TABLE attachment_variants ( attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, pipeline_version integer NOT NULL CHECK (pipeline_version > 0), variant text NOT NULL CHECK (variant IN ('thumbnail','crop','optimized')), object_key text NOT NULL UNIQUE, content_type text NOT NULL CHECK (content_type IN ('image/jpeg','image/webp')), size_bytes bigint NOT NULL CHECK (size_bytes > 0), sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), width integer NOT NULL CHECK (width > 0), height integer NOT NULL CHECK (height > 0), PRIMARY KEY (attachment_id, pipeline_version, variant) );