Files
mtusi2026lab5/migrations/004_async_attachment_jobs.sql
T
2026-11-19 19:45:26 +03:00

39 lines
1.4 KiB
SQL

ALTER TABLE attachments
ADD COLUMN IF NOT EXISTS staging_key TEXT,
ADD COLUMN IF NOT EXISTS pipeline_version INTEGER NOT NULL DEFAULT 1;
UPDATE attachments
SET staging_key = object_key
WHERE staging_key IS NULL;
ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_status_check;
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check
CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
CREATE TABLE IF NOT EXISTS attachment_jobs (
job_id UUID PRIMARY KEY,
attachment_id UUID NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
pipeline_version INTEGER NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
lease_until TIMESTAMPTZ,
last_error TEXT,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
UNIQUE (attachment_id, pipeline_version)
);
CREATE INDEX IF NOT EXISTS attachment_jobs_ready_idx
ON attachment_jobs (status, next_attempt_at);
CREATE TABLE IF NOT EXISTS attachment_outbox (
id BIGSERIAL PRIMARY KEY,
job_id UUID NOT NULL REFERENCES attachment_jobs (job_id) ON DELETE CASCADE,
published_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS attachment_outbox_pending_idx
ON attachment_outbox (published_at, id);