← 中文资源

简体中文版本

幂等的约束与索引迁移

索引有 CREATE/DROP IF NOT EXISTS,约束却没有:ADD CONSTRAINT 前先查 pg_constraint 用 DO 块守卫,迁移脚本重复执行也不会报错中断。

阅读英文原文

实现说明

实际执行的是 SELECT / CREATE / ALTER——pg_constraint 是涉及的对象。 从子句角度看,用到了:WHERE 按条件筛出这条语句真正触碰的行;守住子表行与父表对应关系的 REFERENCES 外键。

常见问题

这段 SQL 涉及哪些对象?

引用的是 pg_constraint。

核心语句

CREATE INDEX IF NOT EXISTS idx_orders_customer_created
    ON orders (customer_id, created_at DESC);
ALTER TABLE orders DROP CONSTRAINT IF EXISTS orders_legacy_check;
DROP INDEX IF EXISTS idx_orders_legacy;

代码示例

-- Migration scripts must be re-runnable: indexes have IF NOT EXISTS, constraints do not
CREATE INDEX IF NOT EXISTS idx_orders_customer_created
    ON orders (customer_id, created_at DESC);

-- ADD CONSTRAINT has no IF NOT EXISTS: probe pg_constraint first, then attach
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint
        WHERE conname = 'orders_customer_fk'
          AND conrelid = 'orders'::regclass
    ) THEN
        ALTER TABLE orders
            ADD CONSTRAINT orders_customer_fk
            FOREIGN KEY (customer_id) REFERENCES customers (id);
    END IF;
END
$$;

-- The drop direction is idempotent the same way
DROP INDEX IF EXISTS idx_orders_legacy;
ALTER TABLE orders DROP CONSTRAINT IF EXISTS orders_legacy_check;