calculations.rb 14.1 KB
Newer Older
1
require 'active_support/core_ext/object/blank'
2
require 'active_support/core_ext/object/try'
3

4
module ActiveRecord
5
  module Calculations
P
Pratik Naik 已提交
6 7 8
    # Count operates using three different approaches.
    #
    # * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
9
    # * Count using column: By passing a column name to count, it will return a count of all the
N
Neeraj Singh 已提交
10
    #   rows for the model with supplied column present.
P
Pratik Naik 已提交
11 12 13 14
    # * Count using options will find the row count matched by the options used.
    #
    # The third approach, count using options, accepts an option hash as the only parameter. The options are:
    #
15
    # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
16
    #   See conditions in the intro to ActiveRecord::Base.
E
Emilio Tagua 已提交
17
    # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id"
N
Neeraj Singh 已提交
18
    #   (rarely needed) or named associations in the same form used for the <tt>:include</tt> option, which will
E
Emilio Tagua 已提交
19
    #   perform an INNER JOIN on the associated table(s). If the value is a string, then the records
N
Neeraj Singh 已提交
20
    #   will be returned read-only since they will have attributes that do not correspond to the table's columns.
P
Pratik Naik 已提交
21
    #   Pass <tt>:readonly => false</tt> to override.
22 23
    # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs.
    #   The symbols named refer to already defined associations. When using named associations, count
24
    #   returns the number of DISTINCT items for the model you're counting.
P
Pratik Naik 已提交
25 26 27
    #   See eager loading under Associations.
    # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
    # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
28
    # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example,
N
Neeraj Singh 已提交
29
    #   want to do a join but not include the joined columns.
30
    # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as
31
    #   SELECT COUNT(DISTINCT posts.id) ...
32
    # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an
33
    #   alternate table name (or even the name of a database view).
P
Pratik Naik 已提交
34 35 36 37 38 39 40 41 42
    #
    # Examples for counting all:
    #   Person.count         # returns the total count of all people
    #
    # Examples for counting by column:
    #   Person.count(:age)  # returns the total count of all people whose age is present in database
    #
    # Examples for count with options:
    #   Person.count(:conditions => "age > 26")
43 44
    #
    #   # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
45
    #   Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job)
46 47
    #
    #   # finds the number of rows matching the conditions and joins.
48 49
    #   Person.count(:conditions => "age > 26 AND job.salary > 60000",
    #                :joins => "LEFT JOIN jobs on jobs.person_id = person.id")
50
    #
P
Pratik Naik 已提交
51 52 53
    #   Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
    #   Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
    #
54
    # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition.
55
    # Use Person.count instead.
P
Pratik Naik 已提交
56 57
    def count(column_name = nil, options = {})
      column_name, options = nil, column_name if column_name.is_a?(Hash)
58
      calculate(:count, column_name, options)
59 60
    end

61 62
    # Calculates the average value on a given column. Returns +nil+ if there's
    # no row. See +calculate+ for examples with options.
63 64 65
    #
    #   Person.average('age') # => 35.8
    def average(column_name, options = {})
66
      calculate(:average, column_name, options)
67 68
    end

69
    # Calculates the minimum value on a given column. The value is returned
70 71 72 73 74
    # with the same data type of the column, or +nil+ if there's no row. See
    # +calculate+ for examples with options.
    #
    #   Person.minimum('age') # => 7
    def minimum(column_name, options = {})
75
      calculate(:minimum, column_name, options)
76 77
    end

78 79 80 81 82 83
    # Calculates the maximum value on a given column. The value is returned
    # with the same data type of the column, or +nil+ if there's no row. See
    # +calculate+ for examples with options.
    #
    #   Person.maximum('age') # => 93
    def maximum(column_name, options = {})
84
      calculate(:maximum, column_name, options)
85 86
    end

87 88 89 90 91 92
    # Calculates the sum of values on a given column. The value is returned
    # with the same data type of the column, 0 if there's no row. See
    # +calculate+ for examples with options.
    #
    #   Person.sum('age') # => 4562
    def sum(column_name, options = {})
93
      calculate(:sum, column_name, options)
94 95
    end

96
    # This calculates aggregate values in the given column. Methods for count, sum, average,
97
    # minimum, and maximum have been added as shortcuts. Options such as <tt>:conditions</tt>,
98
    # <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
99 100
    #
    # There are two basic forms of output:
101
    #   * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
102
    #     for AVG, and the given column's type for everything else.
103
    #   * Grouped values: This returns an ordered hash of the values and groups them by the
104
    #     <tt>:group</tt> option. It takes either a column name, or the name of a belongs_to association.
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    #
    #       values = Person.maximum(:age, :group => 'last_name')
    #       puts values["Drake"]
    #       => 43
    #
    #       drake  = Family.find_by_last_name('Drake')
    #       values = Person.maximum(:age, :group => :family) # Person belongs_to :family
    #       puts values[drake]
    #       => 43
    #
    #       values.each do |family, max_age|
    #       ...
    #       end
    #
    # Options:
120
    # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
121
    #   See conditions in the intro to ActiveRecord::Base.
122
    # * <tt>:include</tt>: Eager loading, see Associations for details. Since calculations don't load anything,
123
    #   the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.
124
    # * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id".
125
    #   (Rarely needed).
126
    #   The records will be returned read-only since they will have attributes that do not correspond to the
127
    #   table's columns.
128 129
    # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
    # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
130
    # * <tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be changed if you for example
131
    #   want to do a join, but not include the joined columns.
132
    # * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as
133
    #   SELECT COUNT(DISTINCT posts.id) ...
134 135 136 137
    #
    # Examples:
    #   Person.calculate(:count, :all) # The same as Person.count
    #   Person.average(:age) # SELECT AVG(age) FROM people...
138
    #   Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for
139 140 141
    #                                                                    # everyone with a last name other than 'Drake'
    #
    #   # Selects the minimum age for any family without any minors
142
    #   Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name)
143
    #
144
    #   Person.sum("2 * age")
145
    def calculate(operation, column_name, options = {})
146 147 148
      if options.except(:distinct).present?
        apply_finder_options(options.except(:distinct)).calculate(operation, column_name, :distinct => options[:distinct])
      else
149 150 151 152 153 154 155 156
        relation = with_default_scope

        if relation.equal?(self)
          if eager_loading? || (includes_values.present? && references_eager_loaded_tables?)
            construct_relation_for_association_calculations.calculate(operation, column_name, options)
          else
            perform_calculation(operation, column_name, options)
          end
157
        else
158
          relation.calculate(operation, column_name, options)
159 160 161 162 163 164 165 166 167
        end
      end
    rescue ThrowResult
      0
    end

    private

    def perform_calculation(operation, column_name, options = {})
168 169
      operation = operation.to_s.downcase

170
      distinct = options[:distinct]
171

172
      if operation == "count"
173 174
        column_name ||= (select_for_count || :all)

175
        unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
176 177
          distinct = true
        end
178

179 180
        column_name = primary_key if column_name == :all && distinct

181
        distinct = nil if column_name =~ /\s*DISTINCT\s+/i
182 183
      end

184
      if @group_values.any?
185
        execute_grouped_calculation(operation, column_name, distinct)
186
      else
N
Neeraj Singh 已提交
187
        execute_simple_calculation(operation, column_name, distinct)
188
      end
P
Pratik Naik 已提交
189 190
    end

191
    def aggregate_column(column_name)
192
      if @klass.column_names.include?(column_name.to_s)
193
        Arel::Attribute.new(@klass.unscoped.table, column_name)
194
      else
195
        Arel.sql(column_name == :all ? "*" : column_name.to_s)
196
      end
197 198
    end

199 200 201 202
    def operation_over_aggregate_column(column, operation, distinct)
      operation == 'count' ? column.count(distinct) : column.send(operation)
    end

203
    def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
204
      # Postgresql doesn't like ORDER BY when there are no GROUP BY
205
      relation = reorder(nil)
206

207 208 209
      if operation == "count" && (relation.limit_value || relation.offset_value)
        # Shortcut when limit is zero.
        return 0 if relation.limit_value == 0
210

211 212 213
        query_builder = build_count_subquery(relation, column_name, distinct)
      else
        column = aggregate_column(column_name)
214

215
        select_value = operation_over_aggregate_column(column, operation, distinct)
216

217 218 219
        relation.select_values = [select_value]

        query_builder = relation.arel
220 221 222
      end

      type_cast_calculated_value(@klass.connection.select_value(query_builder.to_sql), column_for(column_name), operation)
223 224
    end

225
    def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
226 227 228
      group_attr      = @group_values
      association     = @klass.reflect_on_association(group_attr.first.to_sym)
      associated      = group_attr.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
229
      group_fields  = Array(associated ? association.foreign_key : group_attr)
A
Aaron Patterson 已提交
230 231 232 233
      group_aliases = group_fields.map { |field| column_alias_for(field) }
      group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
        [aliaz, column_for(field)]
      }
234

235
      group = @klass.connection.adapter_name == 'FrontBase' ? group_aliases : group_fields
236

237 238
      if operation == 'count' && column_name == :all
        aggregate_alias = 'count_all'
239
      else
240
        aggregate_alias = column_alias_for(operation, column_name)
241 242
      end

A
Aaron Patterson 已提交
243 244 245 246 247 248 249 250 251 252 253
      select_values = [
        operation_over_aggregate_column(
          aggregate_column(column_name),
          operation,
          distinct).as(aggregate_alias)
      ]

      select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
        "#{field} AS #{aliaz}"
      }

254
      relation = except(:group).group(group.join(','))
A
Aaron Patterson 已提交
255
      relation.select_values = select_values
256 257 258 259

      calculated_data = @klass.connection.select_all(relation.to_sql)

      if association
260
        key_ids     = calculated_data.collect { |row| row[group_aliases.first] }
261
        key_records = association.klass.base_class.find(key_ids)
262
        key_records = Hash[key_records.map { |r| [r.id, r] }]
263 264
      end

E
Emilio Tagua 已提交
265
      ActiveSupport::OrderedHash[calculated_data.map do |row|
A
Aaron Patterson 已提交
266 267 268
        key   = group_columns.map { |aliaz, column|
          type_cast_calculated_value(row[aliaz], column)
        }
269
        key   = key.first if key.size == 1
E
Emilio Tagua 已提交
270 271 272
        key = key_records[key] if associated
        [key, type_cast_calculated_value(row[aggregate_alias], column_for(column_name), operation)]
      end]
273
    end
274

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    # Converts the given keys to the value that the database adapter returns as
    # a usable column name:
    #
    #   column_alias_for("users.id")                 # => "users_id"
    #   column_alias_for("sum(id)")                  # => "sum_id"
    #   column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
    #   column_alias_for("count(*)")                 # => "count_all"
    #   column_alias_for("count", "id")              # => "count_id"
    def column_alias_for(*keys)
      table_name = keys.join(' ')
      table_name.downcase!
      table_name.gsub!(/\*/, 'all')
      table_name.gsub!(/\W+/, ' ')
      table_name.strip!
      table_name.gsub!(/ +/, '_')

      @klass.connection.table_alias_for(table_name)
    end

    def column_for(field)
      field_name = field.to_s.split('.').last
      @klass.columns.detect { |c| c.name.to_s == field_name }
    end

    def type_cast_calculated_value(value, column, operation = nil)
300 301 302
      case operation
        when 'count'   then value.to_i
        when 'sum'     then type_cast_using_column(value || '0', column)
303
        when 'average' then value.respond_to?(:to_d) ? value.to_d : value
304
        else type_cast_using_column(value, column)
305 306 307 308 309 310 311
      end
    end

    def type_cast_using_column(value, column)
      column ? column.type_cast(value) : value
    end

P
Pratik Naik 已提交
312 313
    def select_for_count
      if @select_values.present?
314
        select = @select_values.join(", ")
P
Pratik Naik 已提交
315 316 317
        select if select !~ /(,|\*)/
      end
    end
318 319

    def build_count_subquery(relation, column_name, distinct)
320 321 322 323 324 325 326 327 328 329
      column_alias = Arel.sql('count_column')
      subquery_alias = Arel.sql('subquery_for_count')

      aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias)
      relation.select_values = [aliased_column]
      subquery = relation.arel.as(subquery_alias)

      sm = Arel::SelectManager.new relation.engine
      select_value = operation_over_aggregate_column(column_alias, 'count', distinct)
      sm.project(select_value).from(subquery)
330
    end
331 332
  end
end