From af545ece2af2e5485b257f650acbe82f8300008c Mon Sep 17 00:00:00 2001 From: Aidan Haran Date: Fri, 24 May 2024 20:32:45 +0100 Subject: [PATCH 1/2] Syntax for with recursive slightly different in SQL Server --- lib/arel/visitors/sqlserver.rb | 5 +++++ 1 file changed, 5 insertions(+) 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 = {}) From 2311cb00b79435b75960e9655de2d2a052807907 Mon Sep 17 00:00:00 2001 From: Aidan Haran Date: Fri, 24 May 2024 20:43:04 +0100 Subject: [PATCH 2/2] Update coerced_tests.rb --- test/cases/coerced_tests.rb | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) 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 +