Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 267 lines (240 sloc) 14.165 kb
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
1 module ActiveRecord
fed7d33 @dhh Fixed documentation
dhh authored
2 module Calculations #:nodoc:
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
3 CALCULATIONS_OPTIONS = [:conditions, :joins, :order, :select, :group, :having, :distinct, :limit, :offset, :include]
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
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.
a0bf019 @jeremy Deprecation: count class method should be called with an options hash ra...
jeremy authored
12 # * Count by conditions or joins: This API has been deprecated and will be removed in Rails 2.0
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
13 # * Count using options will find the row count matched by the options used.
14 #
15 # The last 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.
18 # * <tt>:joins</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed).
19 # The records will be returned read-only since they will have attributes that do not correspond to the table's columns.
20 # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer
21 # to already defined associations. When using named associations count returns the number DISTINCT items for the model you're counting.
22 # See eager loading under Associations.
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
23 # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
24 # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
25 # * <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
26 # include the joined columns.
27 # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
28 #
29 # Examples for counting all:
30 # Person.count # returns the total count of all people
31 #
a0bf019 @jeremy Deprecation: count class method should be called with an options hash ra...
jeremy authored
32 # Examples for count by +conditions+ and +joins+ (this has been deprecated):
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
33 # Person.count("age > 26") # returns the number of people older than 26
34 # Person.find("age > 26 AND job.salary > 60000", "LEFT JOIN jobs on jobs.person_id = person.id") # returns the total number of rows matching the conditions and joins fetched by SELECT COUNT(*).
35 #
36 # Examples for count with options:
37 # Person.count(:conditions => "age > 26")
38 # 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.
39 # 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.
40 # Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
41 # Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
42 #
43 # Note: Person.count(:all) will not work because it will use :all as the condition. Use Person.count instead.
44 def count(*args)
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
45 calculate(:count, *construct_count_options_from_legacy_args(*args))
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
46 end
47
48 # Calculates average value on a given column. The value is returned as a float. See #calculate for examples with options.
49 #
50 # Person.average('age')
51 def average(column_name, options = {})
52 calculate(:avg, column_name, options)
53 end
54
55 # 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.
56 #
57 # Person.minimum('age')
58 def minimum(column_name, options = {})
59 calculate(:min, column_name, options)
60 end
61
62 # 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.
63 #
64 # Person.maximum('age')
65 def maximum(column_name, options = {})
66 calculate(:max, column_name, options)
67 end
68
69 # Calculates the sum value on a given column. The value is returned with the same data type of the column.. See #calculate for examples with options.
70 #
456ddc6 @dhh Doc fix (closes #4014) [thijs@fngtps.com]
dhh authored
71 # Person.sum('age')
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
72 def sum(column_name, options = {})
73 calculate(:sum, column_name, options)
74 end
75
76 # This calculates aggregate values in the given column: Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
77 # Options such as :conditions, :order, :group, :having, and :joins can be passed to customize the query.
78 #
79 # There are two basic forms of output:
80 # * 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.
81 # * Grouped values: This returns an ordered hash of the values and groups them by the :group option. It takes either a column name, or the name
82 # of a belongs_to association.
83 #
84 # values = Person.maximum(:age, :group => 'last_name')
85 # puts values["Drake"]
86 # => 43
87 #
88 # drake = Family.find_by_last_name('Drake')
89 # values = Person.maximum(:age, :group => :family) # Person belongs_to :family
90 # puts values[drake]
91 # => 43
92 #
93 # values.each do |family, max_age|
94 # ...
95 # end
96 #
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
97 # Options:
98 # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro.
99 # * <tt>:joins</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed).
100 # The records will be returned read-only since they will have attributes that do not correspond to the table's columns.
101 # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
102 # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
103 # * <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
104 # include the joined columns.
105 # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
106 #
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
107 # Examples:
108 # Person.calculate(:count, :all) # The same as Person.count
109 # Person.average(:age) # SELECT AVG(age) FROM people...
110 # Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for everyone with a last name other than 'Drake'
111 # Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name) # Selects the minimum age for any family without any minors
112 def calculate(operation, column_name, options = {})
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
113 validate_calculation_options(operation, options)
114 column_name = options[:select] if options[:select]
ad9f678 @dhh Compatibility patches for calculations
dhh authored
115 column_name = '*' if column_name == :all
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
116 column = column_for column_name
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
117 catch :invalid_query do
118 if options[:group]
119 return execute_grouped_calculation(operation, column_name, column, options)
120 else
121 return execute_simple_calculation(operation, column_name, column, options)
122 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
123 end
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
124 0
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
125 end
126
127 protected
df7b746 @technoweenie Fix the HasManyAssociation#count method so it uses the new ActiveRecord:...
technoweenie authored
128 def construct_count_options_from_legacy_args(*args)
129 options = {}
130 column_name = :all
a0bf019 @jeremy Deprecation: count class method should be called with an options hash ra...
jeremy authored
131
132 # We need to handle
133 # count()
134 # count(options={})
135 # count(column_name=:all, options={})
136 # count(conditions=nil, joins=nil) # deprecated
137 if args.size > 2
138 raise ArgumentError, "Unexpected parameters passed to count(options={}): #{args.inspect}"
139 elsif args.size > 0
140 if args[0].is_a?(Hash)
141 options = args[0]
df7b746 @technoweenie Fix the HasManyAssociation#count method so it uses the new ActiveRecord:...
technoweenie authored
142 elsif args[1].is_a?(Hash)
a0bf019 @jeremy Deprecation: count class method should be called with an options hash ra...
jeremy authored
143 column_name, options = args
df7b746 @technoweenie Fix the HasManyAssociation#count method so it uses the new ActiveRecord:...
technoweenie authored
144 else
a0bf019 @jeremy Deprecation: count class method should be called with an options hash ra...
jeremy authored
145 # Deprecated count(conditions, joins=nil)
146 ActiveSupport::Deprecation.warn(
147 "You called count(#{args[0].inspect}, #{args[1].inspect}), which is a deprecated API call. Instead you should use " +
148 "count(column_name, options). Passing the conditions and joins as string parameters will be removed in Rails 2.0."
149 )
150 options.merge!(:conditions => args[0])
151 options.merge!(:joins => args[1]) if args[1]
df7b746 @technoweenie Fix the HasManyAssociation#count method so it uses the new ActiveRecord:...
technoweenie authored
152 end
153 end
a0bf019 @jeremy Deprecation: count class method should be called with an options hash ra...
jeremy authored
154
df7b746 @technoweenie Fix the HasManyAssociation#count method so it uses the new ActiveRecord:...
technoweenie authored
155 [column_name, options]
156 end
a0bf019 @jeremy Deprecation: count class method should be called with an options hash ra...
jeremy authored
157
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
158 def construct_calculation_sql(operation, column_name, options) #:nodoc:
159 scope = scope(:find)
160 merged_includes = merge_includes(scope ? scope[:include] : [], options[:include])
161 aggregate_alias = column_alias_for(operation, column_name)
162 use_workaround = !Base.connection.supports_count_distinct? && options[:distinct] && operation.to_s.downcase == 'count'
163 join_dependency = nil
164
165 if merged_includes.any? && operation.to_s.downcase == 'count'
166 options[:distinct] = true
4394e40 @dhh Fixed that count distinct should use the selected column even when using...
dhh authored
167 column_name = options[:select] || [table_name, primary_key] * '.'
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
168 end
169
170 sql = "SELECT #{operation}(#{'DISTINCT ' if options[:distinct]}#{column_name}) AS #{aggregate_alias}"
171
172 # A (slower) workaround if we're using a backend, like sqlite, that doesn't support COUNT DISTINCT.
173 sql = "SELECT COUNT(*) AS #{aggregate_alias}" if use_workaround
174
fed7d33 @dhh Fixed documentation
dhh authored
175 sql << ", #{options[:group_field]} AS #{options[:group_alias]}" if options[:group]
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
176 sql << " FROM (SELECT DISTINCT #{column_name}" if use_workaround
fed7d33 @dhh Fixed documentation
dhh authored
177 sql << " FROM #{table_name} "
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
178 if merged_includes.any?
179 join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merged_includes, options[:joins])
180 sql << join_dependency.join_associations.collect{|join| join.association_join }.join
181 end
fed7d33 @dhh Fixed documentation
dhh authored
182 add_joins!(sql, options, scope)
183 add_conditions!(sql, options[:conditions], scope)
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
184 add_limited_ids_condition!(sql, options, join_dependency) if join_dependency && !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
0dc53a8 When grouping, use the appropriate option key. [Marcel Molina Jr.]
Marcel Molina authored
185
186 if options[:group]
187 group_key = Base.connection.adapter_name == 'FrontBase' ? :group_alias : :group_field
188 sql << " GROUP BY #{options[group_key]} "
189 end
b2c0ddf Add support for FrontBase (http://www.frontbase.com/) with a new adapter...
Marcel Molina authored
190
191 if options[:group] && options[:having]
192 # FrontBase requires identifiers in the HAVING clause and chokes on function calls
193 if Base.connection.adapter_name == 'FrontBase'
194 options[:having].downcase!
195 options[:having].gsub!(/#{operation}\s*\(\s*#{column_name}\s*\)/, aggregate_alias)
196 end
197
198 sql << " HAVING #{options[:having]} "
199 end
200
f106e2c @technoweenie Fix bug where calculations with long alias names return null. [Rick]
technoweenie authored
201 sql << " ORDER BY #{options[:order]} " if options[:order]
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
202 add_limit!(sql, options, scope)
203 sql << ')' if use_workaround
9466211 @technoweenie fix calculations for the Oracle Adapter (closes #4626) [Michael Schoen]
technoweenie authored
204 sql
fed7d33 @dhh Fixed documentation
dhh authored
205 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
206
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
207 def execute_simple_calculation(operation, column_name, column, options) #:nodoc:
208 value = connection.select_value(construct_calculation_sql(operation, column_name, options))
fed7d33 @dhh Fixed documentation
dhh authored
209 type_cast_calculated_value(value, column, operation)
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
210 end
211
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
212 def execute_grouped_calculation(operation, column_name, column, options) #:nodoc:
fed7d33 @dhh Fixed documentation
dhh authored
213 group_attr = options[:group].to_s
214 association = reflect_on_association(group_attr.to_sym)
215 associated = association && association.macro == :belongs_to # only count belongs_to associations
216 group_field = (associated ? "#{options[:group]}_id" : options[:group]).to_s
217 group_alias = column_alias_for(group_field)
218 group_column = column_for group_field
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
219 sql = construct_calculation_sql(operation, column_name, options.merge(:group_field => group_field, :group_alias => group_alias))
fed7d33 @dhh Fixed documentation
dhh authored
220 calculated_data = connection.select_all(sql)
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
221 aggregate_alias = column_alias_for(operation, column_name)
fed7d33 @dhh Fixed documentation
dhh authored
222
223 if association
224 key_ids = calculated_data.collect { |row| row[group_alias] }
225 key_records = association.klass.base_class.find(key_ids)
226 key_records = key_records.inject({}) { |hsh, r| hsh.merge(r.id => r) }
227 end
228
325cb12 @technoweenie Namespaced OrderedHash so the Rails implementation does not clash with a...
technoweenie authored
229 calculated_data.inject(ActiveSupport::OrderedHash.new) do |all, row|
fed7d33 @dhh Fixed documentation
dhh authored
230 key = associated ? key_records[row[group_alias].to_i] : type_cast_calculated_value(row[group_alias], group_column)
231 value = row[aggregate_alias]
232 all << [key, type_cast_calculated_value(value, column, operation)]
233 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
234 end
235
236 private
fed7d33 @dhh Fixed documentation
dhh authored
237 def validate_calculation_options(operation, options = {})
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
238 options.assert_valid_keys(CALCULATIONS_OPTIONS)
fed7d33 @dhh Fixed documentation
dhh authored
239 end
ad9f678 @dhh Compatibility patches for calculations
dhh authored
240
fed7d33 @dhh Fixed documentation
dhh authored
241 # converts a given key to the value that the database adapter returns as
242 #
243 # users.id #=> users_id
244 # sum(id) #=> sum_id
245 # count(distinct users.id) #=> count_distinct_users_id
246 # count(*) #=> count_all
247 def column_alias_for(*keys)
f106e2c @technoweenie Fix bug where calculations with long alias names return null. [Rick]
technoweenie authored
248 connection.table_alias_for(keys.join(' ').downcase.gsub(/\*/, 'all').gsub(/\W+/, ' ').strip.gsub(/ +/, '_'))
fed7d33 @dhh Fixed documentation
dhh authored
249 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
250
fed7d33 @dhh Fixed documentation
dhh authored
251 def column_for(field)
252 field_name = field.to_s.split('.').last
253 columns.detect { |c| c.name.to_s == field_name }
254 end
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
255
fed7d33 @dhh Fixed documentation
dhh authored
256 def type_cast_calculated_value(value, column, operation = nil)
257 operation = operation.to_s.downcase
258 case operation
259 when 'count' then value.to_i
260 when 'avg' then value.to_f
261 else column ? column.type_cast(value) : value
262 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
263 end
264 end
265 end
445cb5c @NZKoz Add support for :include to with_scope [andrew@redlinesoftware.com]
NZKoz authored
266 end
Something went wrong with that request. Please try again.