summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/pagination/keyset/in_operator_optimization/query_builder_spec.rb
blob: 9f2ac9a953d41a33b324f55bc49597574f7dd688 (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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::Pagination::Keyset::InOperatorOptimization::QueryBuilder do
  let_it_be(:two_weeks_ago) { 2.weeks.ago }
  let_it_be(:three_weeks_ago) { 3.weeks.ago }
  let_it_be(:four_weeks_ago) { 4.weeks.ago }
  let_it_be(:five_weeks_ago) { 5.weeks.ago }

  let_it_be(:top_level_group) { create(:group) }
  let_it_be(:sub_group_1) { create(:group, parent: top_level_group) }
  let_it_be(:sub_group_2) { create(:group, parent: top_level_group) }
  let_it_be(:sub_sub_group_1) { create(:group, parent: sub_group_2) }

  let_it_be(:project_1) { create(:project, group: top_level_group) }
  let_it_be(:project_2) { create(:project, group: top_level_group) }

  let_it_be(:project_3) { create(:project, group: sub_group_1) }
  let_it_be(:project_4) { create(:project, group: sub_group_2) }

  let_it_be(:project_5) { create(:project, group: sub_sub_group_1) }

  let_it_be(:issues) do
    [
      create(:issue, project: project_1, created_at: three_weeks_ago, relative_position: 5),
      create(:issue, project: project_1, created_at: two_weeks_ago, relative_position: nil),
      create(:issue, project: project_2, created_at: two_weeks_ago, relative_position: 15),
      create(:issue, project: project_2, created_at: two_weeks_ago, relative_position: nil),
      create(:issue, project: project_3, created_at: four_weeks_ago, relative_position: nil),
      create(:issue, project: project_4, created_at: five_weeks_ago, relative_position: 10),
      create(:issue, project: project_5, created_at: four_weeks_ago, relative_position: nil)
    ]
  end

  let(:iterator) do
    Gitlab::Pagination::Keyset::Iterator.new(
      scope: scope.limit(batch_size),
      in_operator_optimization_options: in_operator_optimization_options
    )
  end

  shared_examples 'correct ordering examples' do |opts = {}|
    let(:all_records) do
      all_records = []
      iterator.each_batch(of: batch_size) do |records|
        all_records.concat(records)
      end
      all_records
    end

    unless opts[:skip_finder_query_test]
      it 'returns records in correct order' do
        expect(all_records).to eq(expected_order)
      end
    end

    context 'when not passing the finder query' do
      before do
        in_operator_optimization_options.delete(:finder_query)
      end

      it 'returns records in correct order' do
        expect(all_records).to eq(expected_order)
      end

      it 'loads only the order by column' do
        order_by_attribute_names = iterator
          .send(:order)
          .column_definitions
          .map(&:attribute_name)
          .map(&:to_s)

        record = all_records.first
        loaded_attributes = record.attributes.keys - ['time_estimate'] # time_estimate is always present (has default value)

        expect(loaded_attributes).to eq(order_by_attribute_names)
      end
    end
  end

  context 'when ordering by issues.id DESC' do
    let(:scope) { Issue.order(id: :desc) }
    let(:expected_order) { issues.sort_by(&:id).reverse }

    let(:in_operator_optimization_options) do
      {
        array_scope: Project.where(namespace_id: top_level_group.self_and_descendants.select(:id)).select(:id),
        array_mapping_scope: -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) },
        finder_query: -> (id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
      }
    end

    context 'when iterating records one by one' do
      let(:batch_size) { 1 }

      it_behaves_like 'correct ordering examples'
    end

    context 'when iterating records with LIMIT 3' do
      let(:batch_size) { 3 }

      it_behaves_like 'correct ordering examples'
    end

    context 'when loading records at once' do
      let(:batch_size) { issues.size + 1 }

      it_behaves_like 'correct ordering examples'
    end
  end

  context 'when ordering by issues.relative_position DESC NULLS LAST, id DESC' do
    let(:scope) { Issue.order(order) }
    let(:expected_order) { scope.to_a }

    let(:order) do
      # NULLS LAST ordering requires custom Order object for keyset pagination:
      # https://docs.gitlab.com/ee/development/database/keyset_pagination.html#complex-order-configuration
      Gitlab::Pagination::Keyset::Order.build([
        Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
          attribute_name: :relative_position,
          column_expression: Issue.arel_table[:relative_position],
          order_expression: Issue.arel_table[:relative_position].desc.nulls_last,
          reversed_order_expression: Issue.arel_table[:relative_position].asc.nulls_first,
          order_direction: :desc,
          nullable: :nulls_last,
          distinct: false
        ),
        Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
          attribute_name: :id,
          order_expression: Issue.arel_table[:id].desc,
          nullable: :not_nullable,
          distinct: true
        )
      ])
    end

    let(:in_operator_optimization_options) do
      {
        array_scope: Project.where(namespace_id: top_level_group.self_and_descendants.select(:id)).select(:id),
        array_mapping_scope: -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) },
        finder_query: -> (_relative_position_expression, id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
      }
    end

    context 'when iterating records one by one' do
      let(:batch_size) { 1 }

      it_behaves_like 'correct ordering examples'
    end

    context 'when iterating records with LIMIT 3' do
      let(:batch_size) { 3 }

      it_behaves_like 'correct ordering examples'
    end

    context 'with condition "relative_position IS NULL"' do
      let(:base_scope) { Issue.where(relative_position: nil) }
      let(:scope) { base_scope.order(order) }

      let(:in_operator_optimization_options) do
        {
          array_scope: Project.where(namespace_id: top_level_group.self_and_descendants.select(:id)).select(:id),
          array_mapping_scope: -> (id_expression) { Issue.merge(base_scope.dup).where(Issue.arel_table[:project_id].eq(id_expression)) },
          finder_query: -> (_relative_position_expression, id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
        }
      end

      context 'when iterating records one by one' do
        let(:batch_size) { 1 }

        it_behaves_like 'correct ordering examples'
      end

      context 'when iterating records with LIMIT 3' do
        let(:batch_size) { 3 }

        it_behaves_like 'correct ordering examples'
      end
    end
  end

  context 'when ordering by issues.created_at DESC, issues.id ASC' do
    let(:scope) { Issue.order(created_at: :desc, id: :asc) }
    let(:expected_order) { issues.sort_by { |issue| [issue.created_at.to_f * -1, issue.id] } }

    let(:in_operator_optimization_options) do
      {
        array_scope: Project.where(namespace_id: top_level_group.self_and_descendants.select(:id)).select(:id),
        array_mapping_scope: -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) },
        finder_query: -> (_created_at_expression, id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
      }
    end

    context 'when iterating records one by one' do
      let(:batch_size) { 1 }

      it_behaves_like 'correct ordering examples'
    end

    context 'when iterating records with LIMIT 3' do
      let(:batch_size) { 3 }

      it_behaves_like 'correct ordering examples'
    end

    context 'when loading records at once' do
      let(:batch_size) { issues.size + 1 }

      it_behaves_like 'correct ordering examples'
    end
  end

  context 'pagination support' do
    let(:scope) { Issue.order(id: :desc) }
    let(:expected_order) { issues.sort_by(&:id).reverse }

    let(:options) do
      {
        scope: scope,
        array_scope: Project.where(namespace_id: top_level_group.self_and_descendants.select(:id)).select(:id),
        array_mapping_scope: -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) },
        finder_query: -> (id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
      }
    end

    context 'offset pagination' do
      subject(:optimized_scope) { described_class.new(**options).execute }

      it 'paginates the scopes' do
        first_page = optimized_scope.page(1).per(2)
        expect(first_page).to eq(expected_order[0...2])

        second_page = optimized_scope.page(2).per(2)
        expect(second_page).to eq(expected_order[2...4])

        third_page = optimized_scope.page(3).per(2)
        expect(third_page).to eq(expected_order[4...6])
      end
    end

    context 'keyset pagination' do
      def paginator(cursor = nil)
        scope.keyset_paginate(cursor: cursor, per_page: 2, keyset_order_options: options)
      end

      it 'paginates correctly' do
        first_page = paginator.records
        expect(first_page).to eq(expected_order[0...2])

        cursor_for_page_2 = paginator.cursor_for_next_page

        second_page = paginator(cursor_for_page_2).records
        expect(second_page).to eq(expected_order[2...4])

        cursor_for_page_3 = paginator(cursor_for_page_2).cursor_for_next_page

        third_page = paginator(cursor_for_page_3).records
        expect(third_page).to eq(expected_order[4...6])
      end
    end
  end

  it 'raises error when unsupported scope is passed' do
    scope = Issue.order(Arel::Nodes::NamedFunction.new('UPPER', [Issue.arel_table[:id]]))

    options = {
      scope: scope,
      array_scope: Project.where(namespace_id: top_level_group.self_and_descendants.select(:id)).select(:id),
      array_mapping_scope: -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) },
      finder_query: -> (id_expression) { Issue.where(Issue.arel_table[:id].eq(id_expression)) }
    }

    expect { described_class.new(**options).execute }.to raise_error(/The order on the scope does not support keyset pagination/)
  end

  context 'when ordering by SQL expression' do
    let(:order) do
      # ORDER BY (id * 10), id
      Gitlab::Pagination::Keyset::Order.build([
        Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
          attribute_name: 'id_multiplied_by_ten',
          order_expression: Arel.sql('(id * 10)').asc,
          sql_type: 'integer'
        ),
        Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
          attribute_name: :id,
          order_expression: Issue.arel_table[:id].asc
        )
      ])
    end

    let(:scope) { Issue.reorder(order) }
    let(:expected_order) { issues.sort_by(&:id) }

    let(:in_operator_optimization_options) do
      {
        array_scope: Project.where(namespace_id: top_level_group.self_and_descendants.select(:id)).select(:id),
        array_mapping_scope: -> (id_expression) { Issue.where(Issue.arel_table[:project_id].eq(id_expression)) }
      }
    end

    context 'when iterating records one by one' do
      let(:batch_size) { 1 }

      it_behaves_like 'correct ordering examples', skip_finder_query_test: true
    end

    context 'when iterating records with LIMIT 3' do
      let(:batch_size) { 3 }

      it_behaves_like 'correct ordering examples', skip_finder_query_test: true
    end

    context 'when passing finder query' do
      let(:batch_size) { 3 }

      it 'raises error, loading complete rows are not supported with SQL expressions' do
        in_operator_optimization_options[:finder_query] = -> (_, _) { Issue.select(:id, '(id * 10)').where(id: -1) }

        expect(in_operator_optimization_options[:finder_query]).not_to receive(:call)

        expect do
          iterator.each_batch(of: batch_size) { |records| records.to_a }
        end.to raise_error /The "RecordLoaderStrategy" does not support/
      end
    end
  end
end