Add archived subscription plan cleanup before unique index migration

This commit is contained in:
Yared Yemane 2026-09-24 15:27:18 +03:00
parent 1eb03b7e03
commit 38e9f81372
2 changed files with 135 additions and 0 deletions

View File

@ -0,0 +1,86 @@
-- Run separately BEFORE migration 000110, against the intended database.
-- Review docs/subscription-plan-cleanup.md first. No automatic winner selection.
BEGIN;
SET LOCAL lock_timeout = '10s';
SET LOCAL statement_timeout = '60s';
SET LOCAL search_path = public, pg_catalog;
-- Prevent concurrent plan/reference changes between archival and consolidation.
LOCK TABLE subscription_plans, user_subscriptions, payments IN EXCLUSIVE MODE;
DO $$
BEGIN
IF current_setting('yimaru.approve_plan_consolidation', true) IS DISTINCT FROM 'yes' THEN
RAISE EXCEPTION 'Review the historical-plan change, then explicitly SET yimaru.approve_plan_consolidation = ''yes'' in this session';
END IF;
IF (SELECT count(*) FROM subscription_plans
WHERE id IN (2, 9, 14) AND category = 'LEARN_ENGLISH'
AND NOT is_lifetime AND duration_value = 1 AND duration_unit = 'MONTH'
AND currency = 'ETB'
AND ((id = 2 AND price = 300 AND is_active)
OR (id = 9 AND price = 1 AND NOT is_active)
OR (id = 14 AND price = 0 AND NOT is_active))) <> 3 THEN
RAISE EXCEPTION 'Plans differ from the reviewed backup; stop and review current data';
END IF;
IF EXISTS (SELECT 1 FROM payments WHERE plan_id IN (9, 14)
AND status IN ('PENDING', 'PROCESSING')) THEN
RAISE EXCEPTION 'Duplicate plans have in-flight payments; resolve them before consolidation';
END IF;
-- Unknown references must be reviewed, even if their FK would silently SET NULL/CASCADE.
IF EXISTS (SELECT 1 FROM pg_constraint
WHERE contype = 'f' AND confrelid = 'public.subscription_plans'::regclass
AND NOT (conrelid IN ('public.payments'::regclass, 'public.user_subscriptions'::regclass)
AND conkey = ARRAY[(SELECT attnum FROM pg_attribute
WHERE attrelid = conrelid AND attname = 'plan_id')]::smallint[]
AND confkey = ARRAY[(SELECT attnum FROM pg_attribute
WHERE attrelid = confrelid AND attname = 'id')]::smallint[])) THEN
RAISE EXCEPTION 'Unexpected foreign key references subscription_plans; review before consolidation';
END IF;
END $$;
-- Deliberately fail on a repeated run; never overwrite the original archive.
CREATE SCHEMA plan_cleanup_000110;
REVOKE ALL ON SCHEMA plan_cleanup_000110 FROM PUBLIC;
CREATE TABLE plan_cleanup_000110.mapping (
old_plan_id bigint PRIMARY KEY,
canonical_plan_id bigint NOT NULL,
archived_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO plan_cleanup_000110.mapping (old_plan_id, canonical_plan_id)
VALUES (9, 2), (14, 2);
CREATE TABLE plan_cleanup_000110.subscription_plans AS
SELECT * FROM public.subscription_plans WHERE id IN (2, 9, 14);
CREATE TABLE plan_cleanup_000110.user_subscriptions AS
SELECT * FROM public.user_subscriptions WHERE plan_id IN (9, 14);
CREATE TABLE plan_cleanup_000110.payments AS
SELECT * FROM public.payments WHERE plan_id IN (9, 14);
REVOKE ALL ON ALL TABLES IN SCHEMA plan_cleanup_000110 FROM PUBLIC;
UPDATE public.user_subscriptions AS s SET plan_id = m.canonical_plan_id
FROM plan_cleanup_000110.mapping AS m WHERE s.plan_id = m.old_plan_id;
UPDATE public.payments AS p SET plan_id = m.canonical_plan_id
FROM plan_cleanup_000110.mapping AS m WHERE p.plan_id = m.old_plan_id;
DELETE FROM public.subscription_plans WHERE id IN (9, 14);
-- Ensure the full catalog satisfies the intended rule before committing anything.
-- Migration 000110 subsequently sees this exact index and leaves it in place.
CREATE UNIQUE INDEX idx_subscription_plans_category_period
ON public.subscription_plans (category, is_lifetime, duration_value, duration_unit);
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM plan_cleanup_000110.payments a
LEFT JOIN public.payments p USING (id)
WHERE p.id IS NULL OR p.plan_id <> 2
OR (to_jsonb(p) - 'plan_id') IS DISTINCT FROM (to_jsonb(a) - 'plan_id')
) OR EXISTS (
SELECT 1 FROM plan_cleanup_000110.user_subscriptions a
LEFT JOIN public.user_subscriptions s USING (id)
WHERE s.id IS NULL OR s.plan_id <> 2
OR (to_jsonb(s) - 'plan_id') IS DISTINCT FROM (to_jsonb(a) - 'plan_id')
) THEN
RAISE EXCEPTION 'Reference consolidation changed fields other than plan_id';
END IF;
END $$;
COMMIT;

View File

@ -0,0 +1,49 @@
# Subscription plan cleanup before migration 000110
This is a separate, one-time data repair, not an automatic migration. The reviewed
backup contains duplicate LEARN_ENGLISH / non-lifetime / 1 MONTH plans: active
plan 2 (ETB 300), inactive plan 9 (ETB 1), and inactive plan 14 (ETB 0).
The repair keeps plan 2 and consolidates plans 9 and 14 into it.
The backup has 86 affected payments and 85 affected subscriptions, including three
subscriptions marked ACTIVE on plan 9. Payment amounts, currency, status,
subscription dates, and all other reference-row fields are preserved. Screens
joining to the current plan will show plan 2's name and ETB 300 price. This is a
product/history change that must be accepted before execution. Old plan IDs in
external links will no longer resolve. The full original rows and mapping remain
in the restricted `plan_cleanup_000110` schema.
## Execution
1. Take a fresh database backup and test this repair on an isolated restore.
2. Pause application writes and migration startup. Use a database owner session
against the intended database at migration 109, before applying 110 or 111.
3. Execute with psql, stopping on any error:
```powershell
psql "$env:DB_URL" -X -v ON_ERROR_STOP=1 -c "SET yimaru.approve_plan_consolidation = 'yes'" -f db/maintenance/consolidate_subscription_plans_before_000110.sql
```
4. Apply migrations 110 and 111 through the normal migration runner. The repair
already creates the exact unique index, preventing new duplicates in the gap.
5. Check subscription and payment displays before resuming application traffic.
The transaction locks all three affected tables, archives full original rows,
updates only `plan_id`, removes duplicate plan rows, and validates uniqueness and
unchanged historical fields before commit. Unknown foreign keys, changed plan
attributes, in-flight payments, remaining duplicates, or an existing archive/index
abort the transaction. Do not bypass these checks without reviewing the new data.
Do not force migration versions if a prior migration failed without inspecting
the schema and migration state first.
## Recovery
The original dump remains unchanged. Prefer restoring the fresh backup into an
isolated database to verify recovery. For an immediate reversal while writes are
still paused: roll back migrations 111/110 if applied, remove the unique index
if still present, reinsert archived plans 9 and 14 using explicit column lists,
then restore only the archived reference rows' original `plan_id` values by ID,
all in one transaction. Keep the archive until recovery is verified. Do not
overwrite complete live payment/subscription rows from the archive: their status
may have changed after cleanup. Recovery after traffic resumes requires a fresh
comparison of live and archived rows and cannot safely be automated blindly.