Skip to content

Commit

Permalink
Merge pull request #979 from MmKolodziej/better_total_count_for_group…
Browse files Browse the repository at this point in the history
…ed_queries

Improve performance of total_count for grouped queries
  • Loading branch information
yuki24 committed Jan 25, 2019
2 parents d1c26fd + 642b535 commit b5e2e07
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 b5e2e07

Please sign in to comment.