premium-minds / sonar-postgres-plugin

Sonar plugin to analyze issues with Postgresql SQL scripts
MIT License
0 stars 1 forks source link

Adding column with unique constraint is blocking #30

Closed froque closed 10 months ago

froque commented 10 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

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"