Skip to content

Commit

Permalink
Fix distinct alias when multiple databases used (#1262)
Browse files Browse the repository at this point in the history
  • Loading branch information
aidanharan authored Nov 23, 2024
1 parent 13ad9cd commit 2ba0c8a
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 6 deletions.
12 changes: 9 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
## Unreleased

#### Fixed

- [#1262](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1262) Fix distinct alias when multiple databases used.

## v8.0.0

#### Changed

- [#1216](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1216) Refactor adapter interface to match abstract adapter
- [#1225](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1225) Drop support to Ruby 3.1
- [#1216](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1216) Refactor adapter interface to match abstract adapter.
- [#1225](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1225) Drop support to Ruby 3.1.

#### Fixed

- [#1215](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1215) Fix mismatched foreign key errors
- [#1215](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/1215) Fix mismatched foreign key errors.

Please check [7-2-stable](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/blob/7-2-stable/CHANGELOG.md) for previous changes.
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 @@ -616,4 +616,13 @@ def setup
assert_equal Task.where("starting < ?", DateTime.current).count, 1
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 2ba0c8a

Please sign in to comment.