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 a float. See +calculate+ for examples with options.
53 # Person.average('age')
54 def average(column_name
, options
= {})
55 calculate(:avg, column_name
, options
)
58 # Calculates the minimum value on a given column. The value is returned with the same data type of the column. See +calculate+ for examples with options.
60 # Person.minimum('age')
61 def minimum(column_name
, options
= {})
62 calculate(:min, column_name
, options
)
65 # Calculates the maximum value on a given column. The value is returned with the same data type of the column. See +calculate+ for examples with options.
67 # Person.maximum('age')
68 def maximum(column_name
, options
= {})
69 calculate(:max, column_name
, options
)
72 # Calculates the sum of values on a given column. The value is returned with the same data type of the column. See +calculate+ for examples with options.
75 def sum(column_name
, options
= {})
76 calculate(:sum, column_name
, options
)
79 # This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
80 # 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.
82 # There are two basic forms of output:
83 # * 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.
84 # * 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
85 # of a belongs_to association.
87 # values = Person.maximum(:age, :group => 'last_name')
88 # puts values["Drake"]
91 # drake = Family.find_by_last_name('Drake')
92 # values = Person.maximum(:age, :group => :family) # Person belongs_to :family
96 # values.each do |family, max_age|
101 # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base.
102 # * <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.
103 # * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed).
104 # The records will be returned read-only since they will have attributes that do not correspond to the table's columns.
105 # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
106 # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
107 # * <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
108 # include the joined columns.
109 # * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
112 # Person.calculate(:count, :all) # The same as Person.count
113 # Person.average(:age) # SELECT AVG(age) FROM people...
114 # Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for everyone with a last name other than 'Drake'
115 # Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name) # Selects the minimum age for any family without any minors
116 # Person.sum("2 * age")
117 def calculate(operation
, column_name
, options
= {})
118 validate_calculation_options(operation
, options
)
119 column_name
= options
[:select] if options
[:select]
120 column_name
= '*' if column_name
== :all
121 column
= column_for column_name
122 catch
:invalid_query do
124 return execute_grouped_calculation(operation
, column_name
, column
, options
)
126 return execute_simple_calculation(operation
, column_name
, column
, options
)
133 def construct_count_options_from_args(*args
)
139 # count(:column_name=:all)
141 # count(column_name=:all, options={})
144 args
[0].is_a
?(Hash
) ? options
= args
[0] : column_name
= args
[0]
146 column_name
, options
= args
148 raise ArgumentError
, "Unexpected parameters passed to count(): #{args.inspect}"
151 [column_name
, options
]
154 def construct_calculation_sql(operation
, column_name
, options
) #:nodoc:
155 operation
= operation
.to_s
.downcase
156 options
= options
.symbolize_keys
159 merged_includes
= merge_includes(scope
? scope
[:include] : [], options
[:include])
160 aggregate_alias
= column_alias_for(operation
, column_name
)
161 column_name
= "#{connection.quote_table_name(table_name)}.#{column_name}" if column_names
.include?(column_name
.to_s
)
163 if operation
== 'count'
164 if merged_includes
.any
?
165 options
[:distinct] = true
166 column_name
= options
[:select] || [connection
.quote_table_name(table_name
), primary_key
] * '.'
169 if options
[:distinct]
170 use_workaround
= !connection
.supports_count_distinct
?
174 if options
[:distinct] && column_name
.to_s
!~
/\s*DISTINCT\s+/i
175 distinct
= 'DISTINCT '
177 sql
= "SELECT #{operation}(#{distinct}#{column_name}) AS #{aggregate_alias}"
179 # A (slower) workaround if we're using a backend, like sqlite, that doesn't support COUNT DISTINCT.
180 sql
= "SELECT COUNT(*) AS #{aggregate_alias}" if use_workaround
182 sql
<< ", #{options[:group_field]} AS #{options[:group_alias]}" if options
[:group]
184 sql
<< " FROM #{options[:from]} "
186 sql
<< " FROM (SELECT #{distinct}#{column_name}" if use_workaround
187 sql
<< " FROM #{connection.quote_table_name(table_name)} "
191 add_joins
!(joins
, options
[:joins], scope
)
193 if merged_includes
.any
?
194 join_dependency
= ActiveRecord
::Associations::ClassMethods::JoinDependency.new(self, merged_includes
, joins
)
195 sql
<< join_dependency
.join_associations
.collect
{|join
| join
.association_join
}.join
198 sql
<< joins
unless joins
.blank
?
200 add_conditions
!(sql
, options
[:conditions], scope
)
201 add_limited_ids_condition
!(sql
, options
, join_dependency
) if join_dependency
&& !using_limitable_reflections
?(join_dependency
.reflections
) && ((scope
&& scope
[:limit]) || options
[:limit])
204 group_key
= connection
.adapter_name
== 'FrontBase' ? :group_alias : :group_field
205 sql
<< " GROUP BY #{options[group_key]} "
208 if options
[:group] && options
[:having]
209 # FrontBase requires identifiers in the HAVING clause and chokes on function calls
210 if connection
.adapter_name
== 'FrontBase'
211 options
[:having].downcase
!
212 options
[:having].gsub
!(/#{operation}\s*\(\s*#{column_name}\s*\)/, aggregate_alias
)
215 sql
<< " HAVING #{options[:having]} "
218 sql
<< " ORDER BY #{options[:order]} " if options
[:order]
219 add_limit
!(sql
, options
, scope
)
220 sql
<< ") #{aggregate_alias}_subquery" if use_workaround
224 def execute_simple_calculation(operation
, column_name
, column
, options
) #:nodoc:
225 value
= connection
.select_value(construct_calculation_sql(operation
, column_name
, options
))
226 type_cast_calculated_value(value
, column
, operation
)
229 def execute_grouped_calculation(operation
, column_name
, column
, options
) #:nodoc:
230 group_attr
= options
[:group].to_s
231 association
= reflect_on_association(group_attr
.to_sym
)
232 associated
= association
&& association
.macro
== :belongs_to # only count belongs_to associations
233 group_field
= associated
? association
.primary_key_name
: group_attr
234 group_alias
= column_alias_for(group_field
)
235 group_column
= column_for group_field
236 sql
= construct_calculation_sql(operation
, column_name
, options
.merge(:group_field => group_field
, :group_alias => group_alias
))
237 calculated_data
= connection
.select_all(sql
)
238 aggregate_alias
= column_alias_for(operation
, column_name
)
241 key_ids
= calculated_data
.collect
{ |row
| row
[group_alias
] }
242 key_records
= association
.klass
.base_class
.find(key_ids
)
243 key_records
= key_records
.inject({}) { |hsh
, r
| hsh
.merge(r
.id
=> r
) }
246 calculated_data
.inject(ActiveSupport
::OrderedHash.new
) do |all
, row
|
247 key
= type_cast_calculated_value(row
[group_alias
], group_column
)
248 key
= key_records
[key
] if associated
249 value
= row
[aggregate_alias
]
250 all
[key
] = type_cast_calculated_value(value
, column
, operation
)
256 def validate_calculation_options(operation
, options
= {})
257 options
.assert_valid_keys(CALCULATIONS_OPTIONS
)
260 # Converts the given keys to the value that the database adapter returns as
261 # a usable column name:
263 # column_alias_for("users.id") # => "users_id"
264 # column_alias_for("sum(id)") # => "sum_id"
265 # column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
266 # column_alias_for("count(*)") # => "count_all"
267 # column_alias_for("count", "id") # => "count_id"
268 def column_alias_for(*keys
)
269 table_name
= keys
.join(' ')
271 table_name
.gsub
!(/\*/, 'all')
272 table_name
.gsub
!(/\W+/, ' ')
274 table_name
.gsub
!(/ +/, '_')
276 connection
.table_alias_for(table_name
)
279 def column_for(field
)
280 field_name
= field
.to_s
.split('.').last
281 columns
.detect
{ |c
| c
.name
.to_s
== field_name
}
284 def type_cast_calculated_value(value
, column
, operation
= nil)
285 operation
= operation
.to_s
.downcase
287 when 'count' then value
.to_i
288 when 'sum' then type_cast_using_column(value
|| '0', column
)
289 when 'avg' then value
&& (value
.is_a
?(Fixnum
) ? value
.to_f
: value
).to_d
290 else type_cast_using_column(value
, column
)
294 def type_cast_using_column(value
, column
)
295 column
? column
.type_cast(value
) : value