-- Add an auditable cancellation exclusion count without changing released facts. -- PostgreSQL 15+. Migrations 008 through 019 remain immutable. BEGIN; DO $$ BEGIN IF current_database() <> 'booking_test' THEN RAISE EXCEPTION 'ARR migration is allowed only in booking_test'; END IF; IF to_regclass('finance.daily_versions') IS NULL OR to_regclass('finance.daily_records') IS NULL OR NOT EXISTS ( SELECT 1 FROM pg_constraint WHERE conrelid = 'ingestion.artifacts'::regclass AND conname = 'artifacts_artifact_kind_check' AND pg_get_constraintdef(oid) LIKE '%ohip_json%' ) THEN RAISE EXCEPTION 'ARR migration 019 must be applied first'; END IF; END $$; ALTER TABLE finance.daily_versions ADD COLUMN excluded_cancelled_rows integer NOT NULL DEFAULT 0 CHECK (excluded_cancelled_rows >= 0); ALTER TABLE finance.daily_versions DROP CONSTRAINT daily_versions_counts_reconcile; ALTER TABLE finance.daily_versions ADD CONSTRAINT daily_versions_counts_reconcile CHECK ( source_rows = retained_rows + excluded_rate_code_rows + duplicate_rows + validation_failed_rows + price_unmatched_rows + excluded_cancelled_rows ); ALTER TABLE finance.daily_records DROP CONSTRAINT daily_records_outcome_check; ALTER TABLE finance.daily_records ADD CONSTRAINT daily_records_outcome_check CHECK (outcome IN ( 'retained', 'excluded_rate_code', 'duplicate', 'validation_failed', 'price_unmatched', 'excluded_cancelled' )); COMMENT ON COLUMN finance.daily_versions.excluded_cancelled_rows IS 'Source rows explicitly excluded as cancelled under the pinned processor rules; older versions remain zero.'; COMMIT;