Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions lib/safe-pg-migrations/helpers/batch_over.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,25 @@

module SafePgMigrations
module Helpers
# This helper class allows to iterate over records in batches, in a similar
# way to ActiveRecord's `in_batches` method with the :use_ranges option,
# which was introduced in ActiveRecord 7.1.
#
# See:
# - https://api.rubyonrails.org/classes/ActiveRecord/Batches.html#method-i-in_batches
# - https://github.com/rails/rails/blob/v7.1.0/activerecord/CHANGELOG.md
# - https://github.com/rails/rails/pull/45414
# - https://github.com/rails/rails/commit/620f24782977b8e53e06cf0e2c905a591936e990
#
# If using ActiveRecord 7.1 or later, it's recommended to use the built-in
# method, e.g.
#
# User.in_batches(of: 100, use_ranges: true).each { |batch| ... }
#
# Otherwise, this helper can be used as a fallback:
#
# SafePgMigrations::Helpers::BatchOver.new(User, of: 100).each_batch { |batch| ... }
#
class BatchOver
def initialize(model, of: SafePgMigrations.config.backfill_batch_size)
@model = model
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,19 @@ def backfill_column_default(table_name, column_name)

Helpers::Logger.say_method_call(:backfill_column_default, table_name, column_name)

Helpers::BatchOver.new(model).each_batch do |batch|
batch_handler = lambda do |batch|
batch.update_all("#{quoted_column_name} = DEFAULT")

sleep SafePgMigrations.config.backfill_pause
end

backfill_batch_size = SafePgMigrations.config.backfill_batch_size

if ActiveRecord.version >= Gem::Version.new('7.1')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

until the patch on rails is not provided/approved/merged/released, i think is to early to switch towards rails implementation. WDYT ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, let's keep this PR in draft and keep the new small optim from #138.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

model.in_batches(of: backfill_batch_size, use_ranges: true).each(&batch_handler)
else
Helpers::BatchOver.new(model, of: backfill_batch_size).each_batch(&batch_handler)
end
end
end
end
Expand Down