debian-mirror-gitlab/spec/lib/gitlab/sql/cte_spec.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

76 lines
2.2 KiB
Ruby
Raw Permalink Normal View History

2019-12-04 20:38:33 +05:30
# frozen_string_literal: true
2018-11-08 19:23:39 +05:30
require 'spec_helper'
2020-07-28 23:09:34 +05:30
RSpec.describe Gitlab::SQL::CTE do
2022-07-23 23:45:48 +05:30
shared_examples '#to_arel' do
2018-11-08 19:23:39 +05:30
it 'generates an Arel relation for the CTE body' do
cte = described_class.new(:cte_name, relation)
sql = cte.to_arel.to_sql
2021-10-27 15:23:28 +05:30
name = ApplicationRecord.connection.quote_table_name(:cte_name)
2018-11-08 19:23:39 +05:30
2021-10-27 15:23:28 +05:30
sql1 = ApplicationRecord.connection.unprepared_statement do
2022-07-23 23:45:48 +05:30
relation.is_a?(String) ? relation : relation.to_sql
2018-11-08 19:23:39 +05:30
end
2021-04-29 21:17:54 +05:30
expected = [
"#{name} AS ",
Gitlab::Database::AsWithMaterialized.materialized_if_supported,
(' ' unless Gitlab::Database::AsWithMaterialized.materialized_if_supported.blank?),
"(#{sql1})"
].join
expect(sql).to eq(expected)
2018-11-08 19:23:39 +05:30
end
end
2022-07-23 23:45:48 +05:30
describe '#to_arel' do
context 'when relation is an ActiveRecord::Relation' do
let(:relation) { User.where(id: 1) }
include_examples '#to_arel'
end
context 'when relation is a String' do
let(:relation) { User.where(id: 1).to_sql }
include_examples '#to_arel'
end
end
2018-11-08 19:23:39 +05:30
describe '#alias_to' do
it 'returns an alias for the CTE' do
cte = described_class.new(:cte_name, nil)
table = Arel::Table.new(:kittens)
2021-10-27 15:23:28 +05:30
source_name = ApplicationRecord.connection.quote_table_name(:cte_name)
alias_name = ApplicationRecord.connection.quote_table_name(:kittens)
2018-11-08 19:23:39 +05:30
expect(cte.alias_to(table).to_sql).to eq("#{source_name} AS #{alias_name}")
end
end
describe '#apply_to' do
it 'applies a CTE to an ActiveRecord::Relation' do
user = create(:user)
cte = described_class.new(:cte_name, User.where(id: user.id))
relation = cte.apply_to(User.all)
expect(relation.to_sql).to match(/WITH .+cte_name/)
expect(relation.to_a).to eq(User.where(id: user.id).to_a)
end
end
2021-04-29 21:17:54 +05:30
it_behaves_like 'CTE with MATERIALIZED keyword examples' do
let(:expected_query_block_with_materialized) { 'WITH "some_cte" AS MATERIALIZED (' }
let(:expected_query_block_without_materialized) { 'WITH "some_cte" AS (' }
let(:query) do
cte = described_class.new(:some_cte, User.active, **options)
User.with(cte.to_arel).to_sql
end
end
2018-11-08 19:23:39 +05:30
end