Skip to content

Syntax for "WITH RECURSIVE" is slightly different in SQL Server #1188

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/arel/visitors/sqlserver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,11 @@ def collect_optimizer_hints(o, collector)
collector
end

def visit_Arel_Nodes_WithRecursive(o, collector)
collector << "WITH "
collect_ctes(o.children, collector)
end

# SQLServer ToSql/Visitor (Additions)

def visit_Arel_Nodes_SelectStatement_SQLServer_Lock(collector, options = {})
Expand Down
23 changes: 23 additions & 0 deletions test/cases/coerced_tests.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2732,3 +2732,26 @@ def test_assert_queries_match_coerced
end
end
end

module ActiveRecord
class WithTest < ActiveRecord::TestCase
# SQL contains just 'WITH' instead of 'WITH RECURSIVE' as expected by the original test.
coerce_tests! :test_with_recursive
def test_with_recursive_coerced
top_companies = Company.where(firm_id: nil).to_a
child_companies = Company.where(firm_id: top_companies).to_a
top_companies_and_children = (top_companies.map(&:id) + child_companies.map(&:id)).sort

relation = Company.with_recursive(
top_companies_and_children: [
Company.where(firm_id: nil),
Company.joins("JOIN top_companies_and_children ON companies.firm_id = top_companies_and_children.id"),
]
).from("top_companies_and_children AS companies")

assert_equal top_companies_and_children, relation.order(:id).pluck(:id)
assert_match "WITH ", relation.to_sql
end
end
end

Loading