2 module Calculations #:nodoc:
3 CALCULATIONS_OPTIONS = [:conditions, :joins, :order, :select, :group, :having, :distinct, :limit, :offset, :include, :from]
4 def self.included(base)
5 base.extend(ClassMethods)
9 # Count operates using three different approaches.
11 # * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
12 # * Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present
13 # * Count using options will find the row count matched by the options used.
15 # The third approach, count using options, accepts an option hash as the only parameter. The options are:
17 # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base.
18 # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
19 # or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s).
20 # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
21 # Pass <tt>:readonly => false</tt> to override.
22 # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer
23 # to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you're counting.
24 # See eager loading under Associations.
25 # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
26 # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
27 # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not
28 # include the joined columns.
29 # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
30 # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name
31 # of a database view).
33 # Examples for counting all:
34 # Person.count # returns the total count of all people
36 # Examples for counting by column:
37 # Person.count(:age) # returns the total count of all people whose age is present in database
39 # Examples for count with options:
40 # Person.count(:conditions => "age > 26")
41 # Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
42 # Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") # finds the number of rows matching the conditions and joins.
43 # Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
44 # Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
46 # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition. Use Person.count instead.
48 calculate(:count, *construct_count_options_from_args(*args))
51 # Calculates the average value on a given column. The value is returned as
52 # a float, or +nil+ if there's no row. See +calculate+ for examples with
55 # Person.average('age') # => 35.8
56 def average(column_name, options = {})
57 calculate(:avg, column_name, options)
60 # Calculates the minimum value on a given column. The value is returned
61 # with the same data type of the column, or +nil+ if there's no row. See
62 # +calculate+ for examples with options.
64 # Person.minimum('age') # => 7
65 def minimum(column_name, options = {})
66 calculate(:min, column_name, options)
69 # Calculates the maximum value on a given column. The value is returned
70 # with the same data type of the column, or +nil+ if there's no row. See
71 # +calculate+ for examples with options.
73 # Person.maximum('age') # => 93
74 def maximum(column_name, options = {})
75 calculate(:max, column_name, options)
78 # Calculates the sum of values on a given column. The value is returned
79 # with the same data type of the column, 0 if there's no row. See
80 # +calculate+ for examples with options.
82 # Person.sum('age') # => 4562
83 def sum(column_name, options = {})
84 calculate(:sum, column_name, options)
87 # This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
88 # Options such as <tt>:conditions</tt>, <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
90 # There are two basic forms of output:
91 # * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float for AVG, and the given column's type for everything else.
92 # * Grouped values: This returns an ordered hash of the values and groups them by the <tt>:group</tt> option. It takes either a column name, or the name
93 # of a belongs_to association.
95 # values = Person.maximum(:age, :group => 'last_name')
96 # puts values["Drake"]
99 # drake = Family.find_by_last_name('Drake')
100 # values = Person.maximum(:age, :group => :family) # Person belongs_to :family
104 # values.each do |family, max_age|
109 # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base.
110 # * <tt>:include</tt>: Eager loading, see Associations for details. Since calculations don't load anything, the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.
111 # * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed).
112 # The records will be returned read-only since they will have attributes that do not correspond to the table's columns.
113 # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
114 # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
115 # * <tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not
116 # include the joined columns.
117 # * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
120 # Person.calculate(:count, :all) # The same as Person.count
121 # Person.average(:age) # SELECT AVG(age) FROM people...
122 # Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for everyone with a last name other than 'Drake'
123 # Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name) # Selects the minimum age for any family without any minors
124 # Person.sum("2 * age")
125 def calculate(operation, column_name, options = {})
126 validate_calculation_options(operation, options)
127 column_name = options[:select] if options[:select]
128 column_name = '*' if column_name == :all
129 column = column_for column_name
130 catch :invalid_query do
132 return execute_grouped_calculation(operation, column_name, column, options)
134 return execute_simple_calculation(operation, column_name, column, options)
141 def construct_count_options_from_args(*args)
147 # count(:column_name=:all)
149 # count(column_name=:all, options={})
152 args[0].is_a?(Hash) ? options = args[0] : column_name = args[0]
154 column_name, options = args
156 raise ArgumentError, "Unexpected parameters passed to count(): #{args.inspect}"
159 [column_name, options]
162 def construct_calculation_sql(operation, column_name, options) #:nodoc:
163 operation = operation.to_s.downcase
164 options = options.symbolize_keys
167 merged_includes = merge_includes(scope ? scope[:include] : [], options[:include])
168 aggregate_alias = column_alias_for(operation, column_name)
169 column_name = "#{connection.quote_table_name(table_name)}.#{column_name}" if column_names.include?(column_name.to_s)
171 if operation == 'count'
172 if merged_includes.any?
173 options[:distinct] = true
174 column_name = options[:select] || [connection.quote_table_name(table_name), primary_key] * '.'
177 if options[:distinct]
178 use_workaround = !connection.supports_count_distinct?
182 if options[:distinct] && column_name.to_s !~ /\s*DISTINCT\s+/i
183 distinct = 'DISTINCT '
185 sql = "SELECT #{operation}(#{distinct}#{column_name}) AS #{aggregate_alias}"
187 # A (slower) workaround if we're using a backend, like sqlite, that doesn't support COUNT DISTINCT.
188 sql = "SELECT COUNT(*) AS #{aggregate_alias}" if use_workaround
190 sql << ", #{options[:group_field]} AS #{options[:group_alias]}" if options[:group]
192 sql << " FROM #{options[:from]} "
193 elsif scope && scope[:from] && !use_workaround
194 sql << " FROM #{scope[:from]} "
196 sql << " FROM (SELECT #{distinct}#{column_name}" if use_workaround
197 sql << " FROM #{connection.quote_table_name(table_name)} "
201 add_joins!(joins, options[:joins], scope)
203 if merged_includes.any?
204 join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merged_includes, joins)
205 sql << join_dependency.join_associations.collect{|join| join.association_join }.join
208 sql << joins unless joins.blank?
210 add_conditions!(sql, options[:conditions], scope)
211 add_limited_ids_condition!(sql, options, join_dependency) if join_dependency && !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
214 group_key = connection.adapter_name == 'FrontBase' ? :group_alias : :group_field
215 sql << " GROUP BY #{options[group_key]} "
218 if options[:group] && options[:having]
219 having = sanitize_sql_for_conditions(options[:having])
221 # FrontBase requires identifiers in the HAVING clause and chokes on function calls
222 if connection.adapter_name == 'FrontBase'
224 having.gsub!(/#{operation}\s*\(\s*#{column_name}\s*\)/, aggregate_alias)
227 sql << " HAVING #{having} "
230 sql << " ORDER BY #{options[:order]} " if options[:order]
231 add_limit!(sql, options, scope)
232 sql << ") #{aggregate_alias}_subquery" if use_workaround
236 def execute_simple_calculation(operation, column_name, column, options) #:nodoc:
237 value = connection.select_value(construct_calculation_sql(operation, column_name, options))
238 type_cast_calculated_value(value, column, operation)
241 def execute_grouped_calculation(operation, column_name, column, options) #:nodoc:
242 group_attr = options[:group].to_s
243 association = reflect_on_association(group_attr.to_sym)
244 associated = association && association.macro == :belongs_to # only count belongs_to associations
245 group_field = associated ? association.primary_key_name : group_attr
246 group_alias = column_alias_for(group_field)
247 group_column = column_for group_field
248 sql = construct_calculation_sql(operation, column_name, options.merge(:group_field => group_field, :group_alias => group_alias))
249 calculated_data = connection.select_all(sql)
250 aggregate_alias = column_alias_for(operation, column_name)
253 key_ids = calculated_data.collect { |row| row[group_alias] }
254 key_records = association.klass.base_class.find(key_ids)
255 key_records = key_records.inject({}) { |hsh, r| hsh.merge(r.id => r) }
258 calculated_data.inject(ActiveSupport::OrderedHash.new) do |all, row|
259 key = type_cast_calculated_value(row[group_alias], group_column)
260 key = key_records[key] if associated
261 value = row[aggregate_alias]
262 all[key] = type_cast_calculated_value(value, column, operation)
268 def validate_calculation_options(operation, options = {})
269 options.assert_valid_keys(CALCULATIONS_OPTIONS)
272 # Converts the given keys to the value that the database adapter returns as
273 # a usable column name:
275 # column_alias_for("users.id") # => "users_id"
276 # column_alias_for("sum(id)") # => "sum_id"
277 # column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
278 # column_alias_for("count(*)") # => "count_all"
279 # column_alias_for("count", "id") # => "count_id"
280 def column_alias_for(*keys)
281 table_name = keys.join(' ')
283 table_name.gsub!(/\*/, 'all')
284 table_name.gsub!(/\W+/, ' ')
286 table_name.gsub!(/ +/, '_')
288 connection.table_alias_for(table_name)
291 def column_for(field)
292 field_name = field.to_s.split('.').last
293 columns.detect { |c| c.name.to_s == field_name }
296 def type_cast_calculated_value(value, column, operation = nil)
297 operation = operation.to_s.downcase
299 when 'count' then value.to_i
300 when 'sum' then type_cast_using_column(value || '0', column)
301 when 'avg' then value && (value.is_a?(Fixnum) ? value.to_f : value).to_d
302 else type_cast_using_column(value, column)
306 def type_cast_using_column(value, column)
307 column ? column.type_cast(value) : value