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

Backfill code should be unscoped #77

Merged
merged 1 commit into from
May 30, 2019

Conversation

matrinox
Copy link
Contributor

@matrinox matrinox commented May 30, 2019

Context

If the model you're adding a column to has a default_scope (e.g. w/ soft deletion), the code to backfill won't update all rows. This can become a problem if you need to perform an unscoped query in the app and the default column is not set. This PR makes it so that all rows are updated.

Change

  • Add unscoped to backfill code

Example

Given the following migration...

class AddDefaultColumn < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :x, :string, default: '3'
  end
end

...it now reports the following message:

== 20190530211525 AddDefaultColumn: migrating =================================
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

=== Dangerous operation detected #strong_migrations ===

Adding a column with a non-null default causes the entire table to be rewritten.
Instead, add the column without a default value, then change the default.

class AddDefaultColumn < ActiveRecord::Migration[5.0]
  def up
    add_column :users, :x, :string
    change_column_default :users, :x, "3"
  end

  def down
    remove_column :users, :x
  end
end

Then backfill the existing rows in the Rails console or a separate migration with disable_ddl_transaction!.

class BackfillAddDefaultColumn < ActiveRecord::Migration[5.0]
  disable_ddl_transaction!

  def change
    User.unscoped.in_batches.update_all x: "3"
  end
end

@ankane ankane merged commit 189149f into ankane:master May 30, 2019
@ankane
Copy link
Owner

ankane commented May 30, 2019

Looks great, thanks @matrinox 👍

@matrinox matrinox deleted the add-unscoped-to-backfill-code branch May 30, 2019 21:59
@matrinox
Copy link
Contributor Author

@ankane Thanks! ping me when you've released the version with this 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.

2 participants