summaryrefslogtreecommitdiff
path: root/spec/lib/unnested_in_filters/rewriter_spec.rb
blob: fe34fba579b17bce9ff4b791e681c530643adb56 (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
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe UnnestedInFilters::Rewriter do
  let(:rewriter) { described_class.new(relation) }

  before(:all) do
    User.include(UnnestedInFilters::Dsl)
  end

  describe '#rewrite?' do
    subject(:rewrite?) { rewriter.rewrite? }

    context 'when a join table is receiving an IN list query' do
      let(:relation) { User.joins(:status).where(status: { message: %w[foo bar] }).order(id: :desc).limit(2) }

      it { is_expected.to be_falsey }
    end

    context 'when the given relation does not have an `IN` predicate' do
      let(:relation) { User.where(username: 'user') }

      it { is_expected.to be_falsey }
    end

    context 'when the given relation has an `IN` predicate' do
      context 'when there is no index coverage for the used columns' do
        let(:relation) { User.where(username: %w(user_1 user_2), state: :active) }

        it { is_expected.to be_falsey }
      end

      context 'when there is an index coverage for the used columns' do
        let(:relation) { User.where(state: :active, user_type: [:support_bot, :alert_bot]) }

        it { is_expected.to be_truthy }

        context 'when there is an ordering' do
          let(:relation) { User.where(state: %w(active blocked banned)).order(order).limit(2) }

          context 'when the order is an Arel node' do
            let(:order) { { user_type: :desc } }

            it { is_expected.to be_truthy }
          end

          context 'when the order is a Keyset order' do
            let(:order) do
              Gitlab::Pagination::Keyset::Order.build(
                [
                  Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
                    attribute_name: 'user_type',
                    order_expression: User.arel_table['user_type'].desc,
                    nullable: :not_nullable,
                    distinct: false
                  )
                ])
            end

            it { is_expected.to be_truthy }
          end
        end
      end
    end
  end

  describe '#rewrite' do
    let(:recorded_queries) { ActiveRecord::QueryRecorder.new { rewriter.rewrite.load } }
    let(:relation) { User.where(state: :active, user_type: %i(support_bot alert_bot)).limit(2) }

    let(:expected_query) do
      <<~SQL
        SELECT
          "users".*
        FROM
          unnest('{1,2}'::smallint[]) AS "user_types"("user_type"),
          LATERAL (
            SELECT
              "users".*
            FROM
              "users"
            WHERE
              "users"."state" = 'active' AND
              (users."user_type" = "user_types"."user_type")
            LIMIT 2
          ) AS users
        LIMIT 2
      SQL
    end

    subject(:issued_query) { recorded_queries.occurrences.each_key.first }

    it 'changes the query' do
      expect(issued_query.gsub(/\s/, '')).to start_with(expected_query.gsub(/\s/, ''))
    end

    context 'when the relation has a subquery' do
      let(:relation) { User.where(state: User.select(:state), user_type: %i(support_bot alert_bot)).limit(1) }

      let(:expected_query) do
        <<~SQL
          SELECT
            "users".*
          FROM
            unnest(ARRAY(SELECT "users"."state" FROM "users")::character varying[]) AS "states"("state"),
            unnest('{1,2}'::smallint[]) AS "user_types"("user_type"),
            LATERAL (
              SELECT
                "users".*
              FROM
                "users"
              WHERE
                (users."state" = "states"."state") AND
                (users."user_type" = "user_types"."user_type")
              LIMIT 1
            ) AS users
          LIMIT 1
        SQL
      end

      it 'changes the query' do
        expect(issued_query.gsub(/\s/, '')).to start_with(expected_query.gsub(/\s/, ''))
      end
    end

    context 'when there is an order' do
      let(:relation) { User.where(state: %w(active blocked banned)).order(order).limit(2) }
      let(:expected_query) do
        <<~SQL
          SELECT
            "users".*
          FROM
            unnest('{active,blocked,banned}'::charactervarying[]) AS "states"("state"),
            LATERAL (
              SELECT
                "users".*
              FROM
                "users"
              WHERE
                (users."state" = "states"."state")
              ORDER BY
                "users"."user_type" DESC
              LIMIT 2
            ) AS users
          ORDER BY
            "users"."user_type" DESC
          LIMIT 2
        SQL
      end

      context 'when the order is an Arel node' do
        let(:order) { { user_type: :desc } }

        it 'changes the query' do
          expect(issued_query.gsub(/\s/, '')).to start_with(expected_query.gsub(/\s/, ''))
        end
      end

      context 'when the order is a Keyset order' do
        let(:order) do
          Gitlab::Pagination::Keyset::Order.build(
            [
              Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
                attribute_name: 'user_type',
                order_expression: User.arel_table['user_type'].desc,
                nullable: :not_nullable,
                distinct: false
              )
            ])
        end

        it 'changes the query' do
          expect(issued_query.gsub(/\s/, '')).to start_with(expected_query.gsub(/\s/, ''))
        end
      end
    end

    context 'when the combined attributes include the primary key' do
      let(:relation) { User.where(user_type: %i(support_bot alert_bot)).order(id: :desc).limit(2) }

      let(:expected_query) do
        <<~SQL
          SELECT
              "users".*
          FROM
              "users"
          WHERE
              "users"."id" IN (
                  SELECT
                      "users"."id"
                  FROM
                      unnest('{1,2}' :: smallint []) AS "user_types"("user_type"),
                      LATERAL (
                          SELECT
                              "users"."user_type",
                              "users"."id"
                          FROM
                              "users"
                          WHERE
                              (users."user_type" = "user_types"."user_type")
                          ORDER BY
                              "users"."id" DESC
                          LIMIT
                              2
                      ) AS users
                  ORDER BY
                      "users"."id" DESC
                  LIMIT
                      2
              )
          ORDER BY
              "users"."id" DESC
          LIMIT
              2
        SQL
      end

      it 'changes the query' do
        expect(issued_query.gsub(/\s/, '')).to start_with(expected_query.gsub(/\s/, ''))
      end
    end

    context 'when a join table is receiving an IN list query' do
      let(:relation) { User.joins(:status).where(status: { message: %w[foo bar] }).order(id: :desc).limit(2) }

      let(:expected_query) do
        <<~SQL
          SELECT
              "users".*
          FROM
              "users"
          WHERE
              "users"."id" IN (
                  SELECT
                      "users"."id"
                  FROM
                      LATERAL (
                          SELECT
                              message,
                              "users"."id"
                          FROM
                              "users"
                              INNER JOIN "user_statuses" "status" ON "status"."user_id" = "users"."id"
                          WHERE
                              "status"."message" IN ('foo', 'bar')
                          ORDER BY
                              "users"."id" DESC
                          LIMIT 2) AS users
                  ORDER BY
                      "users"."id" DESC
                  LIMIT 2)
          ORDER BY
              "users"."id" DESC
          LIMIT 2
        SQL
      end

      it 'does not rewrite the in statement for the joined table' do
        expect(issued_query.gsub(/\s/, '')).to start_with(expected_query.gsub(/\s/, ''))
      end
    end

    describe 'logging' do
      subject(:load_reload) { rewriter.rewrite }

      before do
        allow(::Gitlab::AppLogger).to receive(:info)
      end

      it 'logs the call' do
        load_reload

        expect(::Gitlab::AppLogger)
          .to have_received(:info).with(message: 'Query is being rewritten by `UnnestedInFilters`', model: 'User')
      end
    end
  end
end