Froze rails gems
[depot.git] / vendor / rails / activerecord / lib / active_record / calculations.rb
1 module ActiveRecord
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)
6 end
7
8 module ClassMethods
9 # Count operates using three different approaches.
10 #
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.
14 #
15 # The third approach, count using options, accepts an option hash as the only parameter. The options are:
16 #
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).
32 #
33 # Examples for counting all:
34 # Person.count # returns the total count of all people
35 #
36 # Examples for counting by column:
37 # Person.count(:age) # returns the total count of all people whose age is present in database
38 #
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 '*')
45 #
46 # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition. Use Person.count instead.
47 def count(*args)
48 calculate(:count, *construct_count_options_from_args(*args))
49 end
50
51 # Calculates the average value on a given column. The value is returned as a float. See +calculate+ for examples with options.
52 #
53 # Person.average('age')
54 def average(column_name, options = {})
55 calculate(:avg, column_name, options)
56 end
57
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.
59 #
60 # Person.minimum('age')
61 def minimum(column_name, options = {})
62 calculate(:min, column_name, options)
63 end
64
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.
66 #
67 # Person.maximum('age')
68 def maximum(column_name, options = {})
69 calculate(:max, column_name, options)
70 end
71
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.
73 #
74 # Person.sum('age')
75 def sum(column_name, options = {})
76 calculate(:sum, column_name, options)
77 end
78
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.
81 #
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.
86 #
87 # values = Person.maximum(:age, :group => 'last_name')
88 # puts values["Drake"]
89 # => 43
90 #
91 # drake = Family.find_by_last_name('Drake')
92 # values = Person.maximum(:age, :group => :family) # Person belongs_to :family
93 # puts values[drake]
94 # => 43
95 #
96 # values.each do |family, max_age|
97 # ...
98 # end
99 #
100 # Options:
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) ...
110 #
111 # Examples:
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
123 if options[:group]
124 return execute_grouped_calculation(operation, column_name, column, options)
125 else
126 return execute_simple_calculation(operation, column_name, column, options)
127 end
128 end
129 0
130 end
131
132 protected
133 def construct_count_options_from_args(*args)
134 options = {}
135 column_name = :all
136
137 # We need to handle
138 # count()
139 # count(:column_name=:all)
140 # count(options={})
141 # count(column_name=:all, options={})
142 case args.size
143 when 1
144 args[0].is_a?(Hash) ? options = args[0] : column_name = args[0]
145 when 2
146 column_name, options = args
147 else
148 raise ArgumentError, "Unexpected parameters passed to count(): #{args.inspect}"
149 end if args.size > 0
150
151 [column_name, options]
152 end
153
154 def construct_calculation_sql(operation, column_name, options) #:nodoc:
155 operation = operation.to_s.downcase
156 options = options.symbolize_keys
157
158 scope = scope(:find)
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)
162
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] * '.'
167 end
168
169 if options[:distinct]
170 use_workaround = !connection.supports_count_distinct?
171 end
172 end
173
174 if options[:distinct] && column_name.to_s !~ /\s*DISTINCT\s+/i
175 distinct = 'DISTINCT '
176 end
177 sql = "SELECT #{operation}(#{distinct}#{column_name}) AS #{aggregate_alias}"
178
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
181
182 sql << ", #{options[:group_field]} AS #{options[:group_alias]}" if options[:group]
183 if options[:from]
184 sql << " FROM #{options[:from]} "
185 else
186 sql << " FROM (SELECT #{distinct}#{column_name}" if use_workaround
187 sql << " FROM #{connection.quote_table_name(table_name)} "
188 end
189
190 joins = ""
191 add_joins!(joins, options[:joins], scope)
192
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
196 end
197
198 sql << joins unless joins.blank?
199
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])
202
203 if options[:group]
204 group_key = connection.adapter_name == 'FrontBase' ? :group_alias : :group_field
205 sql << " GROUP BY #{options[group_key]} "
206 end
207
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)
213 end
214
215 sql << " HAVING #{options[:having]} "
216 end
217
218 sql << " ORDER BY #{options[:order]} " if options[:order]
219 add_limit!(sql, options, scope)
220 sql << ") #{aggregate_alias}_subquery" if use_workaround
221 sql
222 end
223
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)
227 end
228
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)
239
240 if association
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) }
244 end
245
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)
251 all
252 end
253 end
254
255 private
256 def validate_calculation_options(operation, options = {})
257 options.assert_valid_keys(CALCULATIONS_OPTIONS)
258 end
259
260 # Converts the given keys to the value that the database adapter returns as
261 # a usable column name:
262 #
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(' ')
270 table_name.downcase!
271 table_name.gsub!(/\*/, 'all')
272 table_name.gsub!(/\W+/, ' ')
273 table_name.strip!
274 table_name.gsub!(/ +/, '_')
275
276 connection.table_alias_for(table_name)
277 end
278
279 def column_for(field)
280 field_name = field.to_s.split('.').last
281 columns.detect { |c| c.name.to_s == field_name }
282 end
283
284 def type_cast_calculated_value(value, column, operation = nil)
285 operation = operation.to_s.downcase
286 case operation
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)
291 end
292 end
293
294 def type_cast_using_column(value, column)
295 column ? column.type_cast(value) : value
296 end
297 end
298 end
299 end