diff --git a/lib/arel/visitors/sqlserver.rb b/lib/arel/visitors/sqlserver.rb index 8392eb102..3dfe35bbe 100644 --- a/lib/arel/visitors/sqlserver.rb +++ b/lib/arel/visitors/sqlserver.rb @@ -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 = {}) diff --git a/test/cases/coerced_tests.rb b/test/cases/coerced_tests.rb index c4359096d..4e18c5f92 100644 --- a/test/cases/coerced_tests.rb +++ b/test/cases/coerced_tests.rb @@ -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 +