summaryrefslogtreecommitdiff
path: root/spec/models/concerns/from_union_spec.rb
blob: 735e14b47ec73ecfa83ac1e40e2323a4517a1f91 (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

require 'spec_helper'

describe FromUnion do
  describe '.from_union' do
    let(:model) do
      Class.new(ActiveRecord::Base) do
        self.table_name = 'users'

        include FromUnion
      end
    end

    it 'selects from the results of the UNION' do
      query = model.from_union([model.where(id: 1), model.where(id: 2)])

      expect(query.to_sql).to match(/FROM \(\(SELECT.+\)\nUNION\n\(SELECT.+\)\) users/m)
    end

    it 'supports the use of a custom alias for the sub query' do
      query = model.from_union(
        [model.where(id: 1), model.where(id: 2)],
        alias_as: 'kittens'
      )

      expect(query.to_sql).to match(/FROM \(\(SELECT.+\)\nUNION\n\(SELECT.+\)\) kittens/m)
    end

    it 'supports keeping duplicate rows' do
      query = model.from_union(
        [model.where(id: 1), model.where(id: 2)],
        remove_duplicates: false
      )

      expect(query.to_sql)
        .to match(/FROM \(\(SELECT.+\)\nUNION ALL\n\(SELECT.+\)\) users/m)
    end
  end
end