From cb0299c9eba6463085130debda6347abf9683463 Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Mon, 17 Jun 2019 21:49:28 +0900 Subject: PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute GROUP BY with virtual count attribute is invalid for almost all databases, but it is valid for PostgreSQL, and it had worked until Rails 5.2.2, so it is a regression for Rails 5.2.3 (caused by 311f001). I can't find perfectly solution for fixing this for now, but I would not like to break existing apps, so I decided to allow referencing virtual count attribute in ORDER BY clause when GROUP BY aggrigation (it partly revert the effect of 311f001) to fix the regression #36022. Fixes #36022. --- .../lib/active_record/relation/query_methods.rb | 25 +++++++++++++--------- 1 file changed, 15 insertions(+), 10 deletions(-) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index d1bcec9704..87a53966e4 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -1159,8 +1159,9 @@ module ActiveRecord columns.flat_map do |field| case field when Symbol - field = field.to_s - arel_column(field, &connection.method(:quote_table_name)) + arel_column(field.to_s) do |attr_name| + connection.quote_table_name(attr_name) + end when String arel_column(field, &:itself) when Proc @@ -1268,20 +1269,14 @@ module ActiveRecord order_args.map! do |arg| case arg when Symbol - arg = arg.to_s - arel_column(arg) { - Arel.sql(connection.quote_table_name(arg)) - }.asc + order_column(arg.to_s).asc when Hash arg.map { |field, dir| case field when Arel::Nodes::SqlLiteral field.send(dir.downcase) else - field = field.to_s - arel_column(field) { - Arel.sql(connection.quote_table_name(field)) - }.send(dir.downcase) + order_column(field.to_s).send(dir.downcase) end } else @@ -1290,6 +1285,16 @@ module ActiveRecord end.flatten! end + def order_column(field) + arel_column(field) do |attr_name| + if attr_name == "count" && !group_values.empty? + arel_attribute(attr_name) + else + Arel.sql(connection.quote_table_name(attr_name)) + end + end + end + # Checks to make sure that the arguments are not blank. Note that if some # blank-like object were initially passed into the query method, then this # method will not raise an error. -- cgit v1.2.3