Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Grouped query performance of total_count using SQL #1023

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -32,15 +32,17 @@ def total_count(column_name = :all, _options = nil) #:nodoc:

c = c.limit(max_pages * limit_value) if max_pages && max_pages.respond_to?(:*)

# .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
end
# Handle grouping with a subquery
@total_count = if c.group_values.any?
# Only count non-null values of column_name if supplied
c = c.where.not column_name => nil unless column_name.nil? || column_name == :all

c.connection.select_value(<<-SQL.strip).to_i
SELECT count(*) FROM (#{c.except(:select).select("1").to_sql}) subquery
SQL
else
c.count(column_name)
end
end

# Turn this Relation to a "without count mode" Relation.
Expand Down
Expand Up @@ -105,13 +105,13 @@ class ActiveRecordRelationMethodsTest < ActiveSupport::TestCase
end

test 'calculating STI total_count with GROUP BY clause' do
{
'Fenton' => Dog,
'Bob' => Dog,
'Garfield' => Cat,
'Bob' => Cat,
'Caine' => Insect
}.each { |name, type| type.create!(name: name) }
[
['Fenton', Dog],
['Bob', Dog],
['Garfield', Cat],
['Bob', Cat],
['Caine', Insect]
].each { |name, type| type.create!(name: name) }

assert_equal 3, Mammal.group(:name).page(1).total_count
end
Expand Down