From ebc09ed9ad9a04338138739226a1a92c7a2707ee Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Wed, 24 Jan 2018 08:28:02 +0900 Subject: Fix `count(:all)` with eager loading and having an order other than the driving table This is a regression caused by 6beb4de. In PostgreSQL, ORDER BY expressions must appear in SELECT list when using DISTINCT. When using `count(:all)` with eager loading, Active Record enforces DISTINCT to count the driving table records only. 6beb4de was caused the regression because `count(:all)` with DISTINCT path no longer removes ORDER BY. We need to ignore ORDER BY when DISTINCT is enforced, otherwise not always generated valid SQL for PostgreSQL. Fixes #31783. --- activerecord/lib/active_record/relation/calculations.rb | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index cb0b06cfdc..decd60c87f 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -131,7 +131,14 @@ module ActiveRecord def calculate(operation, column_name) if has_include?(column_name) relation = apply_join_dependency - relation.distinct! if operation.to_s.downcase == "count" + + if operation.to_s.downcase == "count" && !distinct_value + relation.distinct! + # PostgreSQL: ORDER BY expressions must appear in SELECT list when using DISTINCT + if (column_name == :all || column_name.nil?) && select_values.empty? + relation.order_values = [] + end + end relation.calculate(operation, column_name) else -- cgit v1.2.3