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

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

74 lines
2.2 KiB
Ruby
Raw Normal View History

2019-12-04 20:38:33 +05:30
# frozen_string_literal: true
2017-09-10 17:25:29 +05:30
require 'spec_helper'
2020-07-28 23:09:34 +05:30
RSpec.describe Gitlab::SQL::RecursiveCTE do
2017-09-10 17:25:29 +05:30
let(:cte) { described_class.new(:cte_name) }
describe '#to_arel' do
it 'generates an Arel relation for the CTE body' do
rel1 = User.where(id: 1)
rel2 = User.where(id: 2)
cte << rel1
cte << rel2
sql = cte.to_arel.to_sql
2021-10-27 15:23:28 +05:30
name = ApplicationRecord.connection.quote_table_name(:cte_name)
2017-09-10 17:25:29 +05:30
2021-10-27 15:23:28 +05:30
sql1, sql2 = ApplicationRecord.connection.unprepared_statement do
2017-09-10 17:25:29 +05:30
[rel1.except(:order).to_sql, rel2.except(:order).to_sql]
end
2019-12-26 22:10:19 +05:30
expect(sql).to eq("#{name} AS ((#{sql1})\nUNION\n(#{sql2}))")
2017-09-10 17:25:29 +05:30
end
end
describe '#alias_to' do
it 'returns an alias for the CTE' do
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)
2017-09-10 17:25:29 +05:30
expect(cte.alias_to(table).to_sql).to eq("#{source_name} AS #{alias_name}")
end
2019-07-07 11:18:12 +05:30
it 'replaces dots with an underscore' do
table = Arel::Table.new('gitlab.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(:gitlab_kittens)
2019-07-07 11:18:12 +05:30
expect(cte.alias_to(table).to_sql).to eq("#{source_name} AS #{alias_name}")
end
2017-09-10 17:25:29 +05:30
end
describe '#apply_to' do
it 'applies a CTE to an ActiveRecord::Relation' do
user = create(:user)
cte = described_class.new(:cte_name)
cte << User.where(id: user.id)
relation = cte.apply_to(User.all)
expect(relation.to_sql).to match(/WITH RECURSIVE.+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
# MATERIALIZED keyword is not needed for recursive queries
let(:expected_query_block_with_materialized) { 'WITH RECURSIVE "some_cte" AS (' }
let(:expected_query_block_without_materialized) { 'WITH RECURSIVE "some_cte" AS (' }
let(:query) do
recursive_cte = described_class.new(:some_cte)
recursive_cte << User.active
User.with.recursive(recursive_cte.to_arel).to_sql
end
end
2017-09-10 17:25:29 +05:30
end