Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Fixed counter_sql when no records exist in database for PostgreSQL (w…
…ould give error, not 0) #1039 [Caleb Tennis]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@1104 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information
dhh committed Apr 7, 2005
1 parent 4ab4005 commit 7b37c77
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 2 deletions.
2 changes: 2 additions & 0 deletions activerecord/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*

* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 [Caleb Tennis]

* Fixed that benchmarking times for rendering included db runtimes #987 [skaes@web.de]

* Fixed boolean queries for t/f fields in PostgreSQL #995 [dave@cherryville.org]
Expand Down
10 changes: 8 additions & 2 deletions activerecord/lib/active_record/base.rb
Expand Up @@ -426,8 +426,14 @@ def count(conditions = nil, joins = nil)
# Product.count "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
def count_by_sql(sql)
sql = sanitize_conditions(sql)
count = connection.select_one(sql, "#{name} Count").values.first
return count ? count.to_i : 0
rows = connection.select_one(sql, "#{name} Count")

if rows.nil?
return 0
else
count = rows.values.first
return count ? count.to_i : 0
end
end

# Increments the specified counter by one. So <tt>DiscussionBoard.increment_counter("post_count",
Expand Down
4 changes: 4 additions & 0 deletions activerecord/test/associations_test.rb
Expand Up @@ -250,6 +250,10 @@ def test_counting_using_sql
assert_equal 1, Firm.find_first.clients_using_counter_sql.size
assert_equal 0, Firm.find_first.clients_using_zero_counter_sql.size
end

def test_counting_non_existant_items_using_sql
assert_equal 0, Firm.find_first.no_clients_using_counter_sql.size
end

def test_belongs_to_sanity
c = Client.new
Expand Down
3 changes: 3 additions & 0 deletions activerecord/test/fixtures/company.rb
Expand Up @@ -17,6 +17,9 @@ class Firm < Company
has_many :clients_using_zero_counter_sql, :class_name => "Client",
:finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}',
:counter_sql => 'SELECT 0 FROM companies WHERE client_of = #{id}'
has_many :no_clients_using_counter_sql, :class_name => "Client",
:finder_sql => 'SELECT * FROM companies WHERE client_of = 1000',
:counter_sql => 'SELECT COUNT(*) FROM companies WHERE client_of = 1000'

has_one :account, :dependent => true
end
Expand Down

0 comments on commit 7b37c77

Please sign in to comment.