@@ -234,7 +234,7 @@ def calculate(operation, column_name)
234
234
if operation == "count"
235
235
unless distinct_value || distinct_select? ( column_name || select_for_count )
236
236
relation . distinct!
237
- relation . select_values = [ klass . primary_key || table [ Arel . star ] ]
237
+ relation . select_values = Array ( klass . primary_key || table [ Arel . star ] )
238
238
end
239
239
# PostgreSQL: ORDER BY expressions must appear in SELECT list when using DISTINCT
240
240
relation . order_values = [ ] if group_values . empty?
@@ -459,7 +459,7 @@ def operation_over_aggregate_column(column, operation, distinct)
459
459
end
460
460
461
461
def execute_simple_calculation ( operation , column_name , distinct ) # :nodoc:
462
- if operation == "count" && ( column_name == :all && distinct || has_limit_or_offset? )
462
+ if build_count_subquery? ( operation , column_name , distinct )
463
463
# Shortcut when limit is zero.
464
464
return 0 if limit_value == 0
465
465
@@ -632,12 +632,30 @@ def type_cast_calculated_value(value, operation, type)
632
632
def select_for_count
633
633
if select_values . present?
634
634
return select_values . first if select_values . one?
635
- select_values . join ( ", " )
635
+
636
+ select_values . map do |field |
637
+ column = arel_column ( field . to_s ) do |attr_name |
638
+ Arel . sql ( attr_name )
639
+ end
640
+
641
+ if column . is_a? ( Arel ::Nodes ::SqlLiteral )
642
+ column
643
+ else
644
+ "#{ adapter_class . quote_table_name ( column . relation . name ) } .#{ adapter_class . quote_column_name ( column . name ) } "
645
+ end
646
+ end . join ( ", " )
636
647
else
637
648
:all
638
649
end
639
650
end
640
651
652
+ def build_count_subquery? ( operation , column_name , distinct )
653
+ # SQLite and older MySQL does not support `COUNT DISTINCT` with `*` or
654
+ # multiple columns, so we need to use subquery for this.
655
+ operation == "count" &&
656
+ ( ( ( column_name == :all || select_values . many? ) && distinct ) || has_limit_or_offset? )
657
+ end
658
+
641
659
def build_count_subquery ( relation , column_name , distinct )
642
660
if column_name == :all
643
661
column_alias = Arel . star
0 commit comments