Skip to content

Comments

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

Open
andrew-lewin wants to merge 1 commit intoArtur-Sulej:masterfrom
andrew-lewin:master
Open

Clarify the postgres instructions for setting NOT NULL on an existing column to prevent an ACCESS EXCLUSIVE lock#40
andrew-lewin wants to merge 1 commit intoArtur-Sulej:masterfrom
andrew-lewin:master

Conversation

@andrew-lewin
Copy link

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

… column to prevent an ACCESS EXCLUSIVE lock

`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
Copy link

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.

@lessless
Copy link

this looks like a worthy addition 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants