Skip to content

Commit ad7d29a

Browse files
committed
Add database role support for enumerator in batches
1 parent 922ee56 commit ad7d29a

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

lib/job-iteration/active_record_cursor.rb

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def update_from_record(record)
6464
end
6565
end
6666

67-
def next_batch(batch_size)
67+
def next_batch(batch_size, database_role: nil)
6868
return if @reached_end
6969

7070
relation = @base_relation.limit(batch_size)
@@ -74,7 +74,13 @@ def next_batch(batch_size)
7474
end
7575

7676
records = relation.uncached do
77-
relation.to_a
77+
if database_role.present?
78+
ActiveRecord::Base.connected_to(role: database_role) do
79+
relation.to_a
80+
end
81+
else
82+
relation.to_a
83+
end
7884
end
7985

8086
update_from_record(records.last) unless records.empty?

lib/job-iteration/active_record_enumerator.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@ module JobIteration
77
class ActiveRecordEnumerator
88
SQL_DATETIME_WITH_NSEC = "%Y-%m-%d %H:%M:%S.%N"
99

10-
def initialize(relation, columns: nil, batch_size: 100, cursor: nil)
10+
def initialize(relation, columns: nil, batch_size: 100, cursor: nil, database_role: nil)
1111
@relation = relation
1212
@batch_size = batch_size
13+
@database_role = database_role
1314
@columns = if columns
1415
Array(columns)
1516
else
@@ -31,7 +32,7 @@ def records
3132
def batches
3233
cursor = finder_cursor
3334
Enumerator.new(method(:size)) do |yielder|
34-
while (records = cursor.next_batch(@batch_size))
35+
while (records = cursor.next_batch(@batch_size, database_role: @database_role))
3536
yielder.yield(records, cursor_value(records.last)) if records.any?
3637
end
3738
end

0 commit comments

Comments
 (0)