summaryrefslogtreecommitdiff
path: root/lib/gitlab/pagination/keyset/iterator.rb
blob: 3bc8c0bf616a7381838c9e6ca0c8ebdddaf4a5eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# frozen_string_literal: true

module Gitlab
  module Pagination
    module Keyset
      class Iterator
        def initialize(scope:, use_union_optimization: false)
          @scope = scope
          @order = Gitlab::Pagination::Keyset::Order.extract_keyset_order_object(scope)
          @use_union_optimization = use_union_optimization
        end

        # rubocop: disable CodeReuse/ActiveRecord
        def each_batch(of: 1000)
          cursor_attributes = {}

          loop do
            current_scope = scope.dup.limit(of)
            relation = order
              .apply_cursor_conditions(current_scope, cursor_attributes, { use_union_optimization: @use_union_optimization })
              .reorder(order)
              .limit(of)

            yield relation

            last_record = relation.last
            break unless last_record

            cursor_attributes = order.cursor_attributes_for_node(last_record)
          end
        end
        # rubocop: enable CodeReuse/ActiveRecord

        private

        attr_reader :scope, :order
      end
    end
  end
end