-- One-time migration for product lifecycle statuses and SKU archival. -- Run during a maintenance window before deploying the product-service code -- that uses PRODUCT_STATUS_INVENTORY / ON_SALE / OFF_SALE. BEGIN; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS is_archived BOOLEAN NOT NULL DEFAULT FALSE; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ; ALTER TABLE product.product_items DROP CONSTRAINT IF EXISTS chk_product_items_archived; ALTER TABLE product.product_items ADD CONSTRAINT chk_product_items_archived CHECK ((is_archived = FALSE AND archived_at IS NULL) OR (is_archived = TRUE AND archived_at IS NOT NULL)); ALTER TABLE product.products DROP CONSTRAINT IF EXISTS chk_products_status; -- Current values are 0=DRAFT, 1=ON_SALE, 3=OFF_SALE. Value 2 has no -- supported current meaning and is moved to INVENTORY as the safe state. UPDATE product.products SET status = CASE status WHEN 0 THEN 1 WHEN 1 THEN 2 WHEN 3 THEN 3 ELSE 1 END; ALTER TABLE product.products ALTER COLUMN status SET DEFAULT 1; ALTER TABLE product.products ADD CONSTRAINT chk_products_status CHECK (status IN (1, 2, 3)); COMMIT; -- CREATE INDEX CONCURRENTLY cannot run inside the transaction above. CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_product_items_sku_no_active ON product.product_items (sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE; CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_product_items_active_product_id ON product.product_items (product_id) WHERE deleted_at IS NULL AND is_archived = FALSE; -- Drop the legacy index only after uq_product_items_sku_no_active is valid. DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no;