Skip to content

Commit

Permalink
Improve performance of total_count for grouped queries
Browse files Browse the repository at this point in the history
  • Loading branch information
MmKolodziej committed Jan 14, 2019
1 parent d4db85e commit 642b535
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
Expand Up @@ -29,14 +29,11 @@ def total_count(column_name = :all, _options = nil) #:nodoc:
c = except(:offset, :limit, :order)
# Remove includes only if they are irrelevant
c = c.except(:includes) unless references_eager_loaded_tables?
# .group returns an OrderedHash that responds to #count
c = c.count(column_name)
@total_count = if c.is_a?(Hash) || c.is_a?(ActiveSupport::OrderedHash)
c.count
elsif c.respond_to? :count
c.count(column_name)
else
c
# Handle grouping with a subquery
@total_count = if c.group_values.any?
c.model.from(c.except(:select).select("1")).count
else
c.count(column_name)
end
end

Expand Down
Expand Up @@ -95,6 +95,10 @@ class ActiveRecordRelationMethodsTest < ActiveSupport::TestCase
test 'total_count is calculable with page 1 per "5" (the string)' do
assert_equal 7, User.page(1).per('5').load.total_count
end

test 'calculating total_count with GROUP BY ... HAVING clause' do
assert_equal 2, Authorship.group(:user_id).having("COUNT(book_id) >= 3").page(1).total_count
end
end
end
end

0 comments on commit 642b535

Please sign in to comment.