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 Arel #1022

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,22 @@ 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?
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we get rid of if and always use the subquery approach? What would be the downside? Is it less efficient?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hum... there might be some issues when #total_count is called with a column_name...

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder what is the use case for calling #total_count with specific column_name, though.

# Only count non-null values of column_name if supplied
c = c.where.not column_name => nil unless column_name.nil? || column_name == :all

subquery = c.except(:select).select('1')
if ActiveRecord::VERSION::MAJOR >= 5
subquery = subquery.arel.as('subquery')
c.connection.select_value Arel::SelectManager.new.from(subquery).project(Arel.star.count)
else
# Arel::SelectManager.new without args is unsupported in ActiveRecord < 5
c.connection.select_value("SELECT count(*) FROM (#{subquery.to_sql}) subquery").to_i
end
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