Artur-Sulej / excellent_migrations

An Elixir tool for checking safety of database migrations.
MIT License
232 stars 25 forks source link

Clarify the postgres instructions for setting NOT NULL on an existing column to prevent an ACCESS EXCLUSIVE lock #40

Open andrew-lewin opened 3 months ago

andrew-lewin commented 3 months ago
modify :favourite, :boolean, null: false

turns into the following SQL:

ALTER TABLE recipes
ALTER COLUMN favourite TYPE BOOLEAN
ALTER COLUMN favourite SET NOT NULL

It changes both the type and the nullability of the column. Unfortunately, in postgres, even if the type isn't changing (e.g. it was already a boolean), Postgres initiates a full table scan to ensure that everything is okay. This results in taking out an ACCESS EXCLUSIVE lock on the table for the duration. Unfortunately, to avoid this, we need to do another execute statement to ensure that just the

ALTER COLUMN favourite SET NOT NULL

is being run without the

ALTER COLUMN favourite TYPE BOOLEAN
crbelaus commented 1 month ago

I was not aware of this but it seems like an important thing to mention in the README. Will start doing it in my next migrations.