Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 226 lines (207 sloc) 12.334 kb
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
1 module ActiveRecord
fed7d33 @dhh Fixed documentation
dhh authored
2 module Calculations #:nodoc:
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
3 CALCULATIONS_OPTIONS = [:conditions, :joins, :order, :select, :group, :having, :distinct]
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
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,…
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)
45 options = {}
46
47 #For backwards compatibility, we need to handle both count(conditions=nil, joins=nil) or count(options={}).
48 if args.size >= 0 and args.size <= 2
49 if args.first.is_a?(Hash)
50 options = args.first
51 #should we verify the options hash???
52 elsif args[1].is_a?(Hash)
53 column_name = args.first
54 options = args[1]
55 else
56 # Handle legacy paramter options: def count(conditions=nil, joins=nil)
57 options.merge!(:conditions => args[0]) if args.length > 0
58 options.merge!(:joins => args[1]) if args.length > 1
59 end
60 else
61 raise(ArgumentError, "Unexpected parameters passed to count(*args): expected either count(conditions=nil, joins=nil) or count(options={})")
62 end
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
63
445cb5c @NZKoz Add support for :include to with_scope [andrew@redlinesoftware.com]
NZKoz authored
64 (scope(:find, :include) || options[:include]) ? count_with_associations(options) : calculate(:count, :all, options)
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
65 end
66
67 # Calculates average value on a given column. The value is returned as a float. See #calculate for examples with options.
68 #
69 # Person.average('age')
70 def average(column_name, options = {})
71 calculate(:avg, column_name, options)
72 end
73
74 # 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.
75 #
76 # Person.minimum('age')
77 def minimum(column_name, options = {})
78 calculate(:min, column_name, options)
79 end
80
81 # 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.
82 #
83 # Person.maximum('age')
84 def maximum(column_name, options = {})
85 calculate(:max, column_name, options)
86 end
87
88 # 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.
89 #
456ddc6 @dhh Doc fix (closes #4014) [thijs@fngtps.com]
dhh authored
90 # Person.sum('age')
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
91 def sum(column_name, options = {})
92 calculate(:sum, column_name, options)
93 end
94
95 # This calculates aggregate values in the given column: Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
96 # Options such as :conditions, :order, :group, :having, and :joins can be passed to customize the query.
97 #
98 # There are two basic forms of output:
99 # * 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.
100 # * 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
101 # of a belongs_to association.
102 #
103 # values = Person.maximum(:age, :group => 'last_name')
104 # puts values["Drake"]
105 # => 43
106 #
107 # drake = Family.find_by_last_name('Drake')
108 # values = Person.maximum(:age, :group => :family) # Person belongs_to :family
109 # puts values[drake]
110 # => 43
111 #
112 # values.each do |family, max_age|
113 # ...
114 # end
115 #
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
116 # Options:
117 # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro.
118 # * <tt>:joins</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed).
119 # The records will be returned read-only since they will have attributes that do not correspond to the table's columns.
120 # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
121 # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
122 # * <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
123 # include the joined columns.
124 # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...
125 #
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
126 # Examples:
127 # Person.calculate(:count, :all) # The same as Person.count
128 # Person.average(:age) # SELECT AVG(age) FROM people...
129 # Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for everyone with a last name other than 'Drake'
130 # Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name) # Selects the minimum age for any family without any minors
131 def calculate(operation, column_name, options = {})
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
132 validate_calculation_options(operation, options)
133 column_name = options[:select] if options[:select]
ad9f678 @dhh Compatibility patches for calculations
dhh authored
134 column_name = '*' if column_name == :all
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
135 column = column_for column_name
ad9f678 @dhh Compatibility patches for calculations
dhh authored
136 aggregate = select_aggregate(operation, column_name, options)
137 aggregate_alias = column_alias_for(operation, column_name)
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
138 if options[:group]
ad9f678 @dhh Compatibility patches for calculations
dhh authored
139 execute_grouped_calculation(operation, column_name, column, aggregate, aggregate_alias, options)
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
140 else
ad9f678 @dhh Compatibility patches for calculations
dhh authored
141 execute_simple_calculation(operation, column_name, column, aggregate, aggregate_alias, options)
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
142 end
143 end
144
145 protected
fed7d33 @dhh Fixed documentation
dhh authored
146 def construct_calculation_sql(aggregate, aggregate_alias, options) #:nodoc:
147 scope = scope(:find)
148 sql = ["SELECT #{aggregate} AS #{aggregate_alias}"]
149 sql << ", #{options[:group_field]} AS #{options[:group_alias]}" if options[:group]
150 sql << " FROM #{table_name} "
151 add_joins!(sql, options, scope)
152 add_conditions!(sql, options[:conditions], scope)
153 sql << " GROUP BY #{options[:group_field]}" if options[:group]
154 sql << " HAVING #{options[:having]}" if options[:group] && options[:having]
155 sql << " ORDER BY #{options[:order]}" if options[:order]
156 sql.join
157 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
158
fed7d33 @dhh Fixed documentation
dhh authored
159 def execute_simple_calculation(operation, column_name, column, aggregate, aggregate_alias, options) #:nodoc:
160 value = connection.select_value(construct_calculation_sql(aggregate, aggregate_alias, options))
161 type_cast_calculated_value(value, column, operation)
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
162 end
163
fed7d33 @dhh Fixed documentation
dhh authored
164 def execute_grouped_calculation(operation, column_name, column, aggregate, aggregate_alias, options) #:nodoc:
165 group_attr = options[:group].to_s
166 association = reflect_on_association(group_attr.to_sym)
167 associated = association && association.macro == :belongs_to # only count belongs_to associations
168 group_field = (associated ? "#{options[:group]}_id" : options[:group]).to_s
169 group_alias = column_alias_for(group_field)
170 group_column = column_for group_field
171 sql = construct_calculation_sql(aggregate, aggregate_alias, options.merge(:group_field => group_field, :group_alias => group_alias))
172 calculated_data = connection.select_all(sql)
173
174 if association
175 key_ids = calculated_data.collect { |row| row[group_alias] }
176 key_records = association.klass.base_class.find(key_ids)
177 key_records = key_records.inject({}) { |hsh, r| hsh.merge(r.id => r) }
178 end
179
180 calculated_data.inject(OrderedHash.new) do |all, row|
181 key = associated ? key_records[row[group_alias].to_i] : type_cast_calculated_value(row[group_alias], group_column)
182 value = row[aggregate_alias]
183 all << [key, type_cast_calculated_value(value, column, operation)]
184 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
185 end
186
187 private
fed7d33 @dhh Fixed documentation
dhh authored
188 def validate_calculation_options(operation, options = {})
189 if operation.to_s == 'count'
190 options.assert_valid_keys(CALCULATIONS_OPTIONS + [:include])
191 else
192 options.assert_valid_keys(CALCULATIONS_OPTIONS)
193 end
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
194 end
195
fed7d33 @dhh Fixed documentation
dhh authored
196 def select_aggregate(operation, column_name, options)
197 "#{operation}(#{'DISTINCT ' if options[:distinct]}#{column_name})"
198 end
ad9f678 @dhh Compatibility patches for calculations
dhh authored
199
fed7d33 @dhh Fixed documentation
dhh authored
200 # converts a given key to the value that the database adapter returns as
201 #
202 # users.id #=> users_id
203 # sum(id) #=> sum_id
204 # count(distinct users.id) #=> count_distinct_users_id
205 # count(*) #=> count_all
206 def column_alias_for(*keys)
207 keys.join(' ').downcase.gsub(/\*/, 'all').gsub(/\W+/, ' ').strip.gsub(/ +/, '_')
208 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
209
fed7d33 @dhh Fixed documentation
dhh authored
210 def column_for(field)
211 field_name = field.to_s.split('.').last
212 columns.detect { |c| c.name.to_s == field_name }
213 end
a8d085a @dhh Make calculations typecasty! (closes #4016) [Rick Olson]
dhh authored
214
fed7d33 @dhh Fixed documentation
dhh authored
215 def type_cast_calculated_value(value, column, operation = nil)
216 operation = operation.to_s.downcase
217 case operation
218 when 'count' then value.to_i
219 when 'avg' then value.to_f
220 else column ? column.type_cast(value) : value
221 end
99307b9 @dhh Added calculations: Base.count, Base.average, Base.sum, Base.minimum,…
dhh authored
222 end
223 end
224 end
445cb5c @NZKoz Add support for :include to with_scope [andrew@redlinesoftware.com]
NZKoz authored
225 end
Something went wrong with that request. Please try again.