ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1 CHECK(pipeline_version BETWEEN 1 AND 2); ALTER TABLE attachments ADD COLUMN published_pipeline_version integer NOT NULL DEFAULT 0 CHECK(published_pipeline_version BETWEEN 0 AND 2); UPDATE attachments SET published_pipeline_version=1 WHERE status='ready'; ALTER TABLE attachment_jobs DROP CONSTRAINT attachment_jobs_attachment_id_key; ALTER TABLE attachment_jobs ADD CONSTRAINT attachment_jobs_version_key UNIQUE(attachment_id,pipeline_version); ALTER TABLE attachment_jobs ADD COLUMN superseded_at timestamptz; CREATE TABLE attachment_pipeline_upgrades ( id bigserial PRIMARY KEY, attachment_id uuid NOT NULL REFERENCES attachments(id), from_version integer NOT NULL,to_version integer NOT NULL,reason text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp() ); CREATE TABLE attachment_publications ( id bigserial PRIMARY KEY,attachment_id uuid NOT NULL REFERENCES attachments(id), job_id uuid NOT NULL REFERENCES attachment_jobs(id),pipeline_version integer NOT NULL, variants jsonb NOT NULL,published_at timestamptz NOT NULL DEFAULT clock_timestamp() ); INSERT INTO attachment_publications(attachment_id,job_id,pipeline_version,variants) SELECT a.id,j.id,1,a.variants FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.status='ready';