ids-svc-product/scripts/sql/migrate-product-status-and-sku-archive.sql

52 lines
1.7 KiB
PL/PgSQL

-- 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 / SOLD_OUT.
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=SOLD_OUT. 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;
-- SKU business codes are no longer unique. Remove the legacy uniqueness index
-- when this migration is applied to an existing deployment.
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no_active;
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;
-- Remove the older legacy index as well, if it is still present.
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no;