Files
mtusi2026lab6/migrations/011_versioned_pipeline.sql
T
2026-11-16 18:47:37 +03:00

42 lines
2.2 KiB
SQL

ALTER TABLE attachments
ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version > 0),
ADD COLUMN published_version integer CHECK (published_version > 0),
ADD CONSTRAINT attachments_version_order CHECK (published_version <= pipeline_version);
UPDATE attachments SET published_version=1 WHERE status='ready';
ALTER TABLE jobs
ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version > 0),
ADD COLUMN source_key text;
UPDATE jobs j SET source_key=a.s3_key FROM attachments a WHERE a.id=j.attachment_id;
ALTER TABLE jobs ALTER COLUMN source_key SET NOT NULL;
ALTER TABLE jobs DROP CONSTRAINT jobs_attachment_id_key;
ALTER TABLE jobs ADD CONSTRAINT jobs_attachment_version_key UNIQUE (attachment_id, pipeline_version);
ALTER TABLE jobs DROP CONSTRAINT jobs_status_check;
ALTER TABLE jobs ADD CONSTRAINT jobs_status_check
CHECK (status IN ('queued','processing','ready','failed','superseded'));
-- One immutable logical result per (attachment, pipeline version).
CREATE TABLE attachment_results (
attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
pipeline_version integer NOT NULL CHECK (pipeline_version > 0),
job_id uuid UNIQUE REFERENCES jobs(id),
original_key text NOT NULL,
variants jsonb NOT NULL CHECK (jsonb_typeof(variants)='array'),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (attachment_id, pipeline_version)
);
INSERT INTO attachment_results(attachment_id,pipeline_version,job_id,original_key,variants)
SELECT a.id,1,j.id,a.s3_key,a.variants FROM attachments a
LEFT JOIN jobs j ON j.attachment_id=a.id AND j.pipeline_version=1 WHERE a.status='ready';
CREATE TABLE pipeline_requests (
id bigserial PRIMARY KEY,
attachment_id uuid NOT NULL REFERENCES attachments(id),
pipeline_version integer NOT NULL CHECK (pipeline_version > 0),
job_id uuid NOT NULL UNIQUE REFERENCES jobs(id),
actor text NOT NULL CHECK (char_length(actor) BETWEEN 1 AND 100),
reason text NOT NULL CHECK (char_length(reason) BETWEEN 1 AND 500),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE(attachment_id,pipeline_version)
);