Files
mtusi2026lab5/migrations/005_image_jobs.sql
T

38 lines
1.8 KiB
SQL

ALTER TABLE attachments
ADD COLUMN status text NOT NULL DEFAULT 'ready' CHECK (status IN ('queued','processing','ready','failed')),
ADD COLUMN error_code text,
ADD COLUMN active_version integer NOT NULL DEFAULT 0,
ADD COLUMN result_version integer NOT NULL DEFAULT 0,
ADD COLUMN variants jsonb NOT NULL DEFAULT '[]',
ADD CHECK ((status='failed') = (error_code IS NOT NULL)),
ADD CHECK (active_version >= result_version AND result_version >= 0);
-- A queued row is also the transactional outbox entry. Keep completed rows as
-- the deduplication ledger and failed rows as the operator's dead-letter registry.
CREATE TABLE image_jobs (
id uuid PRIMARY KEY,
attachment_id uuid NOT NULL REFERENCES attachments(id),
version integer NOT NULL CHECK (version IN (1,2)),
attempt integer NOT NULL DEFAULT 1,
cycle_start integer NOT NULL DEFAULT 1 CHECK (cycle_start BETWEEN 1 AND attempt),
state text NOT NULL DEFAULT 'queued' CHECK (state IN ('queued','processing','ready','failed')),
published boolean NOT NULL DEFAULT false,
next_at timestamptz NOT NULL DEFAULT clock_timestamp(),
lease_until timestamptz,
error_code text,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
UNIQUE (attachment_id,version),
CHECK ((state='processing') = (lease_until IS NOT NULL))
);
CREATE INDEX image_jobs_outbox ON image_jobs(next_at,id) WHERE state='queued' AND NOT published;
CREATE INDEX image_jobs_lease ON image_jobs(lease_until,id) WHERE state='processing';
CREATE TABLE image_job_replays (
job_id uuid NOT NULL REFERENCES image_jobs(id),
attempt integer NOT NULL,
previous_error text NOT NULL,
replayed_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (job_id,attempt)
);