Avoid unscope(:order) when limit_value is presented for count

If `limit_value` is presented, records fetching order is very important
for performance. Should not unscope the order in the case.
This commit is contained in:
Ryuta Kamizono 2016-11-05 23:20:53 +09:00
parent 95ea51e97b
commit 62bb8b9dfd
2 changed files with 17 additions and 8 deletions

@ -1,5 +1,14 @@
* Fix an Active Record DateTime field NoMethodError caused by incomplete
datetime. [Bug #24195](https://github.com/rails/rails/issues/24195)
* Avoid `unscope(:order)` when `limit_value` is presented for `count`.
If `limit_value` is presented, records fetching order is very important
for performance. Should not unscope the order in the case.
*Ryuta Kamizono*
* Fix an Active Record DateTime field NoMethodError caused by incomplete
datetime.
Fixes #24195.
*Sen Zhang*

@ -223,17 +223,17 @@ def operation_over_aggregate_column(column, operation, distinct)
end
def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
# PostgreSQL doesn't like ORDER BY when there are no GROUP BY
relation = unscope(:order)
column_alias = column_name
if operation == "count" && (relation.limit_value || relation.offset_value)
if operation == "count" && (limit_value || offset_value)
# Shortcut when limit is zero.
return 0 if relation.limit_value == 0
return 0 if limit_value == 0
query_builder = build_count_subquery(relation, column_name, distinct)
query_builder = build_count_subquery(spawn, column_name, distinct)
else
# PostgreSQL doesn't like ORDER BY when there are no GROUP BY
relation = unscope(:order)
column = aggregate_column(column_name)
select_value = operation_over_aggregate_column(column, operation, distinct)