Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 254 lines (230 sloc) 13.832 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.
12 # * Count by conditions or joins: For backwards compatibility, you can pass in +conditions+ and +joins+ as individual parameters.
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 #
32 # Examples for count by +conditions+ and +joins+ (for backwards compatibility):
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
131 # For backwards compatibility, we need to handle both count(conditions=nil, joins=nil) or count(options={}) or count(column_name=:all, options={}).
132 if args.size >= 0 && args.size <= 2
133 if args.first.is_a?(Hash)
134 options = args.first
135 elsif args[1].is_a?(Hash)
136 options = args[1]
137 column_name = args.first
138 else
139 # Handle legacy paramter options: def count(conditions=nil, joins=nil)
140 options.merge!(:conditions => args[0]) if args.length > 0
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
141 options.merge!(:joins => args[1]) if args.length > 1
df7b746 @technoweenie Fix the HasManyAssociation#count method so it uses the new ActiveRecord:...
technoweenie authored
142 end
143 else
144 raise(ArgumentError, "Unexpected parameters passed to count(*args): expected either count(conditions=nil, joins=nil) or count(options={})")
145 end
146 [column_name, options]
147 end
148
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
149 def construct_calculation_sql(operation, column_name, options) #:nodoc:
150 scope = scope(:find)
151 merged_includes = merge_includes(scope ? scope[:include] : [], options[:include])
152 aggregate_alias = column_alias_for(operation, column_name)
153 use_workaround = !Base.connection.supports_count_distinct? && options[:distinct] && operation.to_s.downcase == 'count'
154 join_dependency = nil
155
156 if merged_includes.any? && operation.to_s.downcase == 'count'
157 options[:distinct] = true
158 column_name = [table_name, primary_key] * '.'
159 end
160
161 sql = "SELECT #{operation}(#{'DISTINCT ' if options[:distinct]}#{column_name}) AS #{aggregate_alias}"
162
163 # A (slower) workaround if we're using a backend, like sqlite, that doesn't support COUNT DISTINCT.
164 sql = "SELECT COUNT(*) AS #{aggregate_alias}" if use_workaround
165
fed7d33 @dhh Fixed documentation
dhh authored
166 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
167 sql << " FROM (SELECT DISTINCT #{column_name}" if use_workaround
fed7d33 @dhh Fixed documentation
dhh authored
168 sql << " FROM #{table_name} "
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
169 if merged_includes.any?
170 join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merged_includes, options[:joins])
171 sql << join_dependency.join_associations.collect{|join| join.association_join }.join
172 end
fed7d33 @dhh Fixed documentation
dhh authored
173 add_joins!(sql, options, scope)
174 add_conditions!(sql, options[:conditions], scope)
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
175 add_limited_ids_condition!(sql, options, join_dependency) if join_dependency && !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
b2c0ddf Add support for FrontBase (http://www.frontbase.com/) with a new adapter...
Marcel Molina authored
176 sql << " GROUP BY #{options[:group_alias]} " if options[:group]
177
178 if options[:group] && options[:having]
179 # FrontBase requires identifiers in the HAVING clause and chokes on function calls
180 if Base.connection.adapter_name == 'FrontBase'
181 options[:having].downcase!
182 options[:having].gsub!(/#{operation}\s*\(\s*#{column_name}\s*\)/, aggregate_alias)
183 end
184
185 sql << " HAVING #{options[:having]} "
186 end
187
f106e2c @technoweenie Fix bug where calculations with long alias names return null. [Rick]
technoweenie authored
188 sql << " ORDER BY #{options[:order]} " if options[:order]
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
189 add_limit!(sql, options, scope)
190 sql << ')' if use_workaround
9466211 @technoweenie fix calculations for the Oracle Adapter (closes #4626) [Michael Schoen]
technoweenie authored
191 sql
fed7d33 @dhh Fixed documentation
dhh authored
192 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
193
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
194 def execute_simple_calculation(operation, column_name, column, options) #:nodoc:
195 value = connection.select_value(construct_calculation_sql(operation, column_name, options))
fed7d33 @dhh Fixed documentation
dhh authored
196 type_cast_calculated_value(value, column, operation)
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
197 end
198
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
199 def execute_grouped_calculation(operation, column_name, column, options) #:nodoc:
fed7d33 @dhh Fixed documentation
dhh authored
200 group_attr = options[:group].to_s
201 association = reflect_on_association(group_attr.to_sym)
202 associated = association && association.macro == :belongs_to # only count belongs_to associations
203 group_field = (associated ? "#{options[:group]}_id" : options[:group]).to_s
204 group_alias = column_alias_for(group_field)
205 group_column = column_for group_field
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
206 sql = construct_calculation_sql(operation, column_name, options.merge(:group_field => group_field, :group_alias => group_alias))
fed7d33 @dhh Fixed documentation
dhh authored
207 calculated_data = connection.select_all(sql)
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
208 aggregate_alias = column_alias_for(operation, column_name)
fed7d33 @dhh Fixed documentation
dhh authored
209
210 if association
211 key_ids = calculated_data.collect { |row| row[group_alias] }
212 key_records = association.klass.base_class.find(key_ids)
213 key_records = key_records.inject({}) { |hsh, r| hsh.merge(r.id => r) }
214 end
215
216 calculated_data.inject(OrderedHash.new) do |all, row|
217 key = associated ? key_records[row[group_alias].to_i] : type_cast_calculated_value(row[group_alias], group_column)
218 value = row[aggregate_alias]
219 all << [key, type_cast_calculated_value(value, column, operation)]
220 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
221 end
222
223 private
fed7d33 @dhh Fixed documentation
dhh authored
224 def validate_calculation_options(operation, options = {})
4251662 @technoweenie Allow all calculations to take the :include option, not just COUNT (clos...
technoweenie authored
225 options.assert_valid_keys(CALCULATIONS_OPTIONS)
fed7d33 @dhh Fixed documentation
dhh authored
226 end
ad9f678 @dhh Compatibility patches for calculations
dhh authored
227
fed7d33 @dhh Fixed documentation
dhh authored
228 # converts a given key to the value that the database adapter returns as
229 #
230 # users.id #=> users_id
231 # sum(id) #=> sum_id
232 # count(distinct users.id) #=> count_distinct_users_id
233 # count(*) #=> count_all
234 def column_alias_for(*keys)
f106e2c @technoweenie Fix bug where calculations with long alias names return null. [Rick]
technoweenie authored
235 connection.table_alias_for(keys.join(' ').downcase.gsub(/\*/, 'all').gsub(/\W+/, ' ').strip.gsub(/ +/, '_'))
fed7d33 @dhh Fixed documentation
dhh authored
236 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
237
fed7d33 @dhh Fixed documentation
dhh authored
238 def column_for(field)
239 field_name = field.to_s.split('.').last
240 columns.detect { |c| c.name.to_s == field_name }
241 end
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
242
fed7d33 @dhh Fixed documentation
dhh authored
243 def type_cast_calculated_value(value, column, operation = nil)
244 operation = operation.to_s.downcase
245 case operation
246 when 'count' then value.to_i
247 when 'avg' then value.to_f
248 else column ? column.type_cast(value) : value
249 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Ba...
dhh authored
250 end
251 end
252 end
445cb5c @NZKoz Add support for :include to with_scope [andrew@redlinesoftware.com]
NZKoz authored
253 end
Something went wrong with that request. Please try again.