Thursday, December 27, 2007

ActiveRecord::Base#count1 - fastest counter ever


class ActiveRecord::Base
def self.count1(conditions, unique_id = nil)
connection.execute("select count(1) from #{table_name} where #{sanitize_sql(conditions)} #{'and id<>'+unique_id.to_s if unique_id}").fetch_row.first.to_i
end
end

  • count(1) is the fastest way, as far as I know, for mysql to count table elements.
    Why should we use the relatively expensive count(*) when we can use this modest counter?
  • conditions - can come as ['title = ?','canon'] which than sanitized by sanitize_sql to 'title = "canon"', for example.
  • All this code can be put in environment.rb and than it extends your ActiveRecord::Base objects, thus it will exetend any Model in your railsish system.
  • unique_id - used when you still want to allow a certain raw (defined by id...) to be left out of the count. Useful for validations, ie:

    User.count1(['nick != ?',user.nick], user.id)>0

Everything here applies to Mysql 5.0.14
(never tested on anything else...)

Kudos to Boris Peterbarg

0 comments:

Post a Comment