Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

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.

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.

2 participants