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

Fix reverting the addition of invalid foreign keys and check constraints #45896

Merged
merged 1 commit into from
Aug 29, 2022

Conversation

fatkodima
Copy link
Member

Adding foreign keys and check constraints to an existing (large) table is dangerous in PostgreSQL, because they need to be checked (validated) and while they are validated, the table stays exclusively locked. So, usually, they are added as invalid and then validated in a separate transaction.

Something like:

class AddForeignKeyFromRepositoriesToUsers < ActiveRecord::Migration[7.1]
  disable_ddl_transaction!

  def change
    add_foreign_key :repositories, :users, validate: false
    validate_foreign_key :repositories, :users
  end
end

This migration is reversible, because of the bug in

(validate.nil? || validate == options.fetch(:validate, validate)) &&

Note the missing self in options.fetch....

Similar migration was also always reversible before #45808 (because before that PR, only name was checked for check constraints to match the searched one).

So, this PR fixes defined_for? for both foreign keys and check constraints to work correctly with validity and makes adding them them as invalid a reversible operation.

@byroot byroot merged commit 9b6abb5 into rails:main Aug 29, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants