sbdchd / squawk

🐘 linter for PostgreSQL, focused on migrations
https://squawkhq.com
GNU General Public License v3.0
541 stars 37 forks source link

Adding column with unique constraint is blocking #336

Closed froque closed 5 months ago

froque commented 5 months ago
ALTER TABLE IF EXISTS foo ADD COLUMN IF NOT EXISTS bar text CONSTRAINT foo_bar_unique UNIQUE;

also blocks updates while the index is built

❯ cat unique.sql            
ALTER TABLE IF EXISTS foo ADD COLUMN IF NOT EXISTS bar text CONSTRAINT foo_bar_unique UNIQUE;
❯ squawk unique.sql 
Found 0 issues in 1 file 🎉
❯ squawk --version  
squawk 0.26.0

Solution:

split into 3 steps:

step 1 - create column without constraint

ALTER TABLE IF EXISTS foo ADD COLUMN IF NOT EXISTS bar text;

step 2 - add unique index concurrently

 -- allows reads and writes while index is built
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS foo_bar_idx ON foo (bar);

step 3 - create table constraint from unique index

ALTER TABLE foo ADD CONSTRAINT foo_bar_unique UNIQUE USING INDEX foo_bar_idx;
-- NOTICE:  ALTER TABLE / ADD CONSTRAINT USING INDEX will rename index "foo_bar_idx" to "foo_bar_unique"
chdsbd commented 5 months ago

I think we could update the existing disallowed-unique-constraint rule to cover this