Class: SafePgMigrations::Helpers::BatchOver
- Inherits:
-
Object
- Object
- SafePgMigrations::Helpers::BatchOver
- Defined in:
- lib/safe-pg-migrations/helpers/batch_over.rb
Overview
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
In ActiveRecord 8.1, ‘in_baches(use_ranges: true)` was optimized further to use less cpu, memory, and bandwidth, see:
- https://github.com/rails/rails/releases/tag/v8.1.0
- https://github.com/rails/rails/pull/51243
- https://github.com/rails/rails/commit/c097bf6c24443323da8fe64030dd963951121dea
If using ActiveRecord 8.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| ... }
Instance Method Summary collapse
- #each_batch ⇒ Object
-
#initialize(model, of: SafePgMigrations.config.backfill_batch_size) ⇒ BatchOver
constructor
A new instance of BatchOver.
Constructor Details
#initialize(model, of: SafePgMigrations.config.backfill_batch_size) ⇒ BatchOver
Returns a new instance of BatchOver.
31 32 33 34 35 36 |
# File 'lib/safe-pg-migrations/helpers/batch_over.rb', line 31 def initialize(model, of: SafePgMigrations.config.backfill_batch_size) @model = model @of = of @current_range = nil end |
Instance Method Details
#each_batch ⇒ Object
38 39 40 |
# File 'lib/safe-pg-migrations/helpers/batch_over.rb', line 38 def each_batch yield scope.where(primary_key => @current_range) while next_batch end |