实现说明
这个文件依次执行 ALTER 语句。
逐子句看,这些语句使用了:CHECK 约束在写入时就把越界值拒之门外;必填列上的 NOT NULL 限定。
核心语句
ALTER TABLE profiles ADD CONSTRAINT profiles_email_required
CHECK (email IS NOT NULL)
NOT VALID;
ALTER TABLE profiles VALIDATE CONSTRAINT profiles_email_required;
ALTER TABLE profiles DROP CONSTRAINT profiles_email_required;
代码示例
-- Goal: make email NOT NULL on a table already holding millions of rows,
-- a direct ALTER COLUMN SET NOT NULL scans the whole table under a long-held lock.
-- The PG 12+ way: attach a NOT VALID CHECK declaring the same fact first
ALTER TABLE profiles ADD CONSTRAINT profiles_email_required
CHECK (email IS NOT NULL)
NOT VALID;
-- VALIDATE CONSTRAINT takes only a shared lock to verify existing rows, with reads and writes allowed throughout
ALTER TABLE profiles VALIDATE CONSTRAINT profiles_email_required;
-- The planner already knows email has no NULLs: SET NOT NULL skips the table scan and completes instantly
ALTER TABLE profiles ALTER COLUMN email SET NOT NULL;
-- Once the CHECK has served its purpose, drop it; the NOT NULL stands on its own
ALTER TABLE profiles DROP CONSTRAINT profiles_email_required;