-- +goose Up -- +goose StatementBegin ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_status_chk; ALTER TABLE attachments ADD CONSTRAINT attachments_status_chk CHECK (status IN ('pending', 'queued', 'processing', 'ready', 'failed')); ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_error_code_consistency; ALTER TABLE attachments ADD CONSTRAINT attachments_error_code_consistency CHECK ( (status IN ('pending', 'queued', 'processing', 'ready') AND error_code IS NULL) OR (status = 'failed' AND error_code IS NOT NULL) ); ALTER TABLE attachments ADD COLUMN attempts INT NOT NULL DEFAULT 0; ALTER TABLE attachments ADD CONSTRAINT attachments_attempts_nonneg CHECK (attempts >= 0); ALTER TABLE attachments ADD COLUMN next_attempt_at TIMESTAMPTZ; ALTER TABLE attachments ADD COLUMN locked_until TIMESTAMPTZ; ALTER TABLE attachments ADD COLUMN pipeline_version INT NOT NULL DEFAULT 1; ALTER TABLE attachments ADD CONSTRAINT attachments_pipeline_version_pos CHECK (pipeline_version >= 1); ALTER TABLE attachments ADD COLUMN staging_key TEXT; ALTER TABLE attachments ADD CONSTRAINT attachments_staging_key_len CHECK (staging_key IS NULL OR char_length(staging_key) BETWEEN 1 AND 1024); DROP INDEX IF EXISTS attachments_pending_idx; CREATE INDEX attachments_active_idx ON attachments (status, next_attempt_at) WHERE status IN ('queued', 'processing'); CREATE INDEX attachments_locked_idx ON attachments (locked_until) WHERE status = 'processing'; -- +goose StatementEnd -- +goose Down -- +goose StatementBegin DROP INDEX IF EXISTS attachments_locked_idx; DROP INDEX IF EXISTS attachments_active_idx; CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending'; ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_staging_key_len; ALTER TABLE attachments DROP COLUMN IF EXISTS staging_key; ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_pipeline_version_pos; ALTER TABLE attachments DROP COLUMN IF EXISTS pipeline_version; ALTER TABLE attachments DROP COLUMN IF EXISTS locked_until; ALTER TABLE attachments DROP COLUMN IF EXISTS next_attempt_at; ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_attempts_nonneg; ALTER TABLE attachments DROP COLUMN IF EXISTS attempts; ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_error_code_consistency; ALTER TABLE attachments ADD CONSTRAINT attachments_error_code_consistency CHECK ( (status IN ('ready', 'pending') AND error_code IS NULL) OR (status = 'failed' AND error_code IS NOT NULL) ); ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_status_chk; ALTER TABLE attachments ADD CONSTRAINT attachments_status_chk CHECK (status IN ('ready', 'pending', 'failed')); -- +goose StatementEnd