Skip to content

Commit

Permalink
Fix distinct alias when multiple databases used
Browse files Browse the repository at this point in the history
  • Loading branch information
aidanharan committed Nov 23, 2024
1 parent 17255fd commit e050157
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 9 additions & 0 deletions test/cases/adapter_test_sqlserver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit e050157

Please sign in to comment.