@@ -8,18 +8,43 @@ module ConnectionAdapters
88 module SQLServer
99 module CoreExt
1010 module Calculations
11- # Same as original except we don't perform PostgreSQL hack that removes ordering.
1211 def calculate ( operation , column_name )
13- return super unless klass . connection . adapter_name == "SQLServer"
12+ if klass . connection . sqlserver?
13+ _calculate ( operation , column_name )
14+ else
15+ super
16+ end
17+ end
18+
19+ private
20+
21+ # Same as original `calculate` method except we don't perform PostgreSQL hack that removes ordering.
22+ def _calculate ( operation , column_name )
23+ operation = operation . to_s . downcase
24+
25+ if @none
26+ case operation
27+ when "count" , "sum"
28+ result = group_values . any? ? Hash . new : 0
29+ return @async ? Promise ::Complete . new ( result ) : result
30+ when "average" , "minimum" , "maximum"
31+ result = group_values . any? ? Hash . new : nil
32+ return @async ? Promise ::Complete . new ( result ) : result
33+ end
34+ end
1435
1536 if has_include? ( column_name )
1637 relation = apply_join_dependency
1738
18- if operation . to_s . downcase == "count"
39+ if operation == "count"
1940 unless distinct_value || distinct_select? ( column_name || select_for_count )
2041 relation . distinct!
21- relation . select_values = [ klass . primary_key || table [ Arel . star ] ]
42+ relation . select_values = [ klass . primary_key || table [ Arel . star ] ]
2243 end
44+ # PostgreSQL: ORDER BY expressions must appear in SELECT list when using DISTINCT
45+ # Start of monkey-patch
46+ # relation.order_values = [] if group_values.empty?
47+ # End of monkey-patch
2348 end
2449
2550 relation . calculate ( operation , column_name )
@@ -28,8 +53,6 @@ def calculate(operation, column_name)
2853 end
2954 end
3055
31- private
32-
3356 def build_count_subquery ( relation , column_name , distinct )
3457 return super unless klass . connection . adapter_name == "SQLServer"
3558
0 commit comments