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 70 71 72 73 74
    # Calculates the minimum 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.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 97
    # This calculates aggregate values in the given column.  Methods for count, sum, average,
    # 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 149 150 151 152 153 154 155 156 157 158 159 160 161
      if options.except(:distinct).present?
        apply_finder_options(options.except(:distinct)).calculate(operation, column_name, :distinct => options[:distinct])
      else
        if eager_loading? || includes_values.present?
          construct_relation_for_association_calculations.calculate(operation, column_name, options)
        else
          perform_calculation(operation, column_name, options)
        end
      end
    rescue ThrowResult
      0
    end

    private

    def perform_calculation(operation, column_name, options = {})
162 163
      operation = operation.to_s.downcase

164 165
      distinct = nil

166
      if operation == "count"
167 168
        column_name ||= (select_for_count || :all)

169
        unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
170
          distinct = true
171
          column_name = primary_key if column_name == :all
172
        end
173

174
        distinct = nil if column_name =~ /\s*DISTINCT\s+/i
175 176 177 178
      end

      distinct = options[:distinct] || distinct

179
      if @group_values.any?
180
        execute_grouped_calculation(operation, column_name, distinct)
181
      else
N
Neeraj Singh 已提交
182
        execute_simple_calculation(operation, column_name, distinct)
183
      end
P
Pratik Naik 已提交
184 185
    end

186
    def aggregate_column(column_name, subquery_alias = nil)
187
      if @klass.column_names.include?(column_name.to_s)
188
        Arel::Attribute.new(subquery_alias || @klass.unscoped.table, column_name)
189
      else
190 191 192
        if subquery_alias && (split_name = column_name.to_s.split(".")).length > 1
          column_name = split_name.last
        end
193
        Arel.sql(column_name == :all ? "*" : column_name.to_s)
194
      end
195 196
    end

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

201
    def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
202
      # Postgresql doesn't like ORDER BY when there are no GROUP BY
203 204
      relation = except(:order)

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

209 210 211
        query_builder = build_count_subquery(relation, column_name, distinct)
      else
        column = aggregate_column(column_name)
212

213
        select_value = operation_over_aggregate_column(column, operation, distinct)
214

215 216 217
        relation.select_values = [select_value]

        query_builder = relation.arel
218 219 220
      end

      type_cast_calculated_value(@klass.connection.select_value(query_builder.to_sql), column_for(column_name), operation)
221 222
    end

223
    def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
224 225 226
      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
227
      group_fields  = Array(associated ? association.foreign_key : group_attr)
A
Aaron Patterson 已提交
228 229 230 231
      group_aliases = group_fields.map { |field| column_alias_for(field) }
      group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
        [aliaz, column_for(field)]
      }
232

233
      group = @klass.connection.adapter_name == 'FrontBase' ? group_aliases : group_fields
234

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

A
Aaron Patterson 已提交
241 242 243 244 245 246 247 248 249 250 251
      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}"
      }

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

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

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

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

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    # 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)
298 299 300
      case operation
        when 'count'   then value.to_i
        when 'sum'     then type_cast_using_column(value || '0', column)
301
        when 'average' then value.respond_to?(:to_d) ? value.to_d : value
302
        else type_cast_using_column(value, column)
303 304 305 306 307 308 309
      end
    end

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

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

    def build_count_subquery(relation, column_name, distinct)
      # Arel doesn't do subqueries
      subquery_alias = arel_table.alias("subquery_for_count")
      aliased_column = aggregate_column(column_name, subquery_alias)
      select_value = operation_over_aggregate_column(aliased_column, 'count', distinct)

      relation.select_values = [(column_name == :all ? 1 : aggregate_column(column_name))]
      subquery_sql = "(#{relation.arel.to_sql}) #{subquery_alias.name}"
      subquery_alias.relation.select_manager.project(select_value).from(subquery_sql)
    end
327 328
  end
end