Skip to content

Commit 92b4694

Browse files
committed
Deprecate BatchOver in favor of in_batches(use_ranges: true)
Starting from ActiveRecord 7.1, there's a built-in helper equivalent to what BatchOver does, let's use it instead of maintaining our own implementation forever. We keep BatchOver for compatibility with ActiveRecord < 7.1.
1 parent 0e9100c commit 92b4694

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

lib/safe-pg-migrations/helpers/batch_over.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,25 @@
22

33
module SafePgMigrations
44
module Helpers
5+
# This helper class allows to iterate over records in batches, in a similar
6+
# way to ActiveRecord's `in_batches` method with the :use_ranges option,
7+
# which was introduced in ActiveRecord 7.1.
8+
#
9+
# See:
10+
# - https://api.rubyonrails.org/classes/ActiveRecord/Batches.html#method-i-in_batches
11+
# - https://github.com/rails/rails/blob/v7.1.0/activerecord/CHANGELOG.md
12+
# - https://github.com/rails/rails/pull/45414
13+
# - https://github.com/rails/rails/commit/620f24782977b8e53e06cf0e2c905a591936e990
14+
#
15+
# If using ActiveRecord 7.1 or later, it's recommended to use the built-in
16+
# method, e.g.
17+
#
18+
# User.in_batches(of: 100, use_ranges: true).each { |batch| ... }
19+
#
20+
# Otherwise, this helper can be used as a fallback:
21+
#
22+
# SafePgMigrations::Helpers::BatchOver.new(User, of: 100).each_batch { |batch| ... }
23+
#
524
class BatchOver
625
def initialize(model, of: SafePgMigrations.config.backfill_batch_size)
726
@model = model

lib/safe-pg-migrations/plugins/statement_insurer/add_column.rb

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,19 @@ def backfill_column_default(table_name, column_name)
5353

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

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

5959
sleep SafePgMigrations.config.backfill_pause
6060
end
61+
62+
backfill_batch_size = SafePgMigrations.config.backfill_batch_size
63+
64+
if ActiveRecord.version >= Gem::Version.new('7.1')
65+
model.in_batches(of: backfill_batch_size, use_ranges: true).each(&batch_handler)
66+
else
67+
Helpers::BatchOver.new(model, of: backfill_batch_size).each_batch(&batch_handler)
68+
end
6169
end
6270
end
6371
end

0 commit comments

Comments
 (0)