2019-08-22 06:57:44 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2015-11-12 10:16:49 -05:00
|
|
|
require 'spec_helper'
|
|
|
|
|
2017-07-10 10:24:02 -04:00
|
|
|
describe Gitlab::SQL::Union do
|
2016-12-08 20:56:31 -05:00
|
|
|
let(:relation_1) { User.where(email: 'alice@example.com').select(:id) }
|
|
|
|
let(:relation_2) { User.where(email: 'bob@example.com').select(:id) }
|
|
|
|
|
|
|
|
def to_sql(relation)
|
|
|
|
relation.reorder(nil).to_sql
|
|
|
|
end
|
|
|
|
|
2015-11-12 10:16:49 -05:00
|
|
|
describe '#to_sql' do
|
|
|
|
it 'returns a String joining relations together using a UNION' do
|
2016-12-08 20:56:31 -05:00
|
|
|
union = described_class.new([relation_1, relation_2])
|
|
|
|
|
2019-10-23 08:06:18 -04:00
|
|
|
expect(union.to_sql).to eq("(#{to_sql(relation_1)})\nUNION\n(#{to_sql(relation_2)})")
|
2016-12-08 20:56:31 -05:00
|
|
|
end
|
2015-11-12 10:16:49 -05:00
|
|
|
|
2016-12-08 20:56:31 -05:00
|
|
|
it 'skips Model.none segements' do
|
|
|
|
empty_relation = User.none
|
|
|
|
union = described_class.new([empty_relation, relation_1, relation_2])
|
2015-11-12 10:16:49 -05:00
|
|
|
|
2017-08-09 05:52:22 -04:00
|
|
|
expect {User.where("users.id IN (#{union.to_sql})").to_a}.not_to raise_error
|
2019-10-23 08:06:18 -04:00
|
|
|
expect(union.to_sql).to eq("(#{to_sql(relation_1)})\nUNION\n(#{to_sql(relation_2)})")
|
2015-11-12 10:16:49 -05:00
|
|
|
end
|
2017-10-02 04:14:23 -04:00
|
|
|
|
|
|
|
it 'uses UNION ALL when removing duplicates is disabled' do
|
|
|
|
union = described_class
|
|
|
|
.new([relation_1, relation_2], remove_duplicates: false)
|
|
|
|
|
|
|
|
expect(union.to_sql).to include('UNION ALL')
|
|
|
|
end
|
2017-09-07 05:46:58 -04:00
|
|
|
|
|
|
|
it 'returns `NULL` if all relations are empty' do
|
|
|
|
empty_relation = User.none
|
|
|
|
union = described_class.new([empty_relation, empty_relation])
|
|
|
|
|
|
|
|
expect(union.to_sql).to eq('NULL')
|
|
|
|
end
|
2015-11-12 10:16:49 -05:00
|
|
|
end
|
|
|
|
end
|