From e050157f243044e3a215d7799c97bd03ad38c4f5 Mon Sep 17 00:00:00 2001 From: Aidan Haran Date: Sat, 23 Nov 2024 20:45:20 +0000 Subject: [PATCH] Fix distinct alias when multiple databases used --- CHANGELOG.md | 6 ++++++ .../connection_adapters/sqlserver/schema_statements.rb | 10 +++++++--- test/cases/adapter_test_sqlserver.rb | 9 +++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be5209a5e..5122b2256 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## Unreleased + +#### Fixed + +- [#1262](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1262) Fix distinct alias when multiple databases used. + ## v7.1.9 #### Fixed diff --git a/lib/active_record/connection_adapters/sqlserver/schema_statements.rb b/lib/active_record/connection_adapters/sqlserver/schema_statements.rb index 8c4621e4c..fb2f4f045 100644 --- a/lib/active_record/connection_adapters/sqlserver/schema_statements.rb +++ b/lib/active_record/connection_adapters/sqlserver/schema_statements.rb @@ -347,12 +347,16 @@ def add_timestamps(table_name, **options) def columns_for_distinct(columns, orders) order_columns = orders.reject(&:blank?).map { |s| - s = s.to_sql unless s.is_a?(String) + s = visitor.compile(s) unless s.is_a?(String) s.gsub(/\s+(?:ASC|DESC)\b/i, "") .gsub(/\s+NULLS\s+(?:FIRST|LAST)\b/i, "") - }.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" } + } + .reject(&:blank?) + .reject { |s| columns.include?(s) } - (order_columns << super).join(", ") + order_columns_aliased = order_columns.map.with_index { |column, i| "#{column} AS alias_#{i}" } + + (order_columns_aliased << super).join(", ") end def update_table_definition(table_name, base) diff --git a/test/cases/adapter_test_sqlserver.rb b/test/cases/adapter_test_sqlserver.rb index 166920e4f..cb433b74e 100644 --- a/test/cases/adapter_test_sqlserver.rb +++ b/test/cases/adapter_test_sqlserver.rb @@ -581,4 +581,13 @@ def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes end end end + + describe "distinct select query" do + it "generated SQL does not contain unnecessary alias projection" do + sqls = capture_sql do + Post.includes(:comments).joins(:comments).first + end + assert_no_match(/AS alias_0/, sqls.first) + end + end end