Merge pull request #3507 from jmazzi/issue-3503

Preserve SELECT columns on the COUNT for finder_sql when possible
This commit is contained in:
Jeremy Kemper 2011-11-03 21:14:51 -07:00
parent b5f908a7ad
commit 533a9f84b0
2 changed files with 21 additions and 2 deletions

View File

@ -344,8 +344,12 @@ module ActiveRecord
if options[:counter_sql]
interpolate(options[:counter_sql])
else
# replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
# replace the SELECT clause with COUNT(SELECTS), preserving any hints within /* ... */
interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) do
count_with = $2.to_s
count_with = '*' if count_with.blank? || count_with =~ /,/
"SELECT #{$1}COUNT(#{count_with}) FROM"
end
end
end

View File

@ -41,6 +41,21 @@ class HasManyAssociationsTestForCountWithCountSql < ActiveRecord::TestCase
end
end
class HasManyAssociationsTestForCountDistinctWithFinderSql < ActiveRecord::TestCase
class Invoice < ActiveRecord::Base
has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT DISTINCT line_items.amount from line_items"
end
def test_should_count_distinct_results
invoice = Invoice.new
invoice.custom_line_items << LineItem.new(:amount => 0)
invoice.custom_line_items << LineItem.new(:amount => 0)
invoice.save!
assert_equal 1, invoice.custom_line_items.count
end
end
class HasManyAssociationsTest < ActiveRecord::TestCase