calculations.rb 13.5 KB
Newer Older
1
module ActiveRecord
2
  module Calculations
3 4 5 6 7 8 9 10 11 12 13
    # Count the records.
    #
    #   Person.count
    #   # => the total count of all people
    #
    #   Person.count(:age)
    #   # => returns the total count of all people whose age is present in database
    #
    #   Person.count(:all)
    #   # => performs a COUNT(*) (:all is an alias for '*')
    #
14
    #   Person.distinct.count(:age)
15
    #   # => counts the number of different age values
16
    #
V
Vijay Dev 已提交
17
    # If +count+ is used with +group+, it returns a Hash whose keys represent the aggregated column,
18 19 20 21
    # and the values are the respective amounts:
    #
    #   Person.group(:city).count
    #   # => { 'Rome' => 5, 'Paris' => 3 }
22
    def count(column_name = nil, options = {})
23 24
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
25 26
      column_name, options = nil, column_name if column_name.is_a?(Hash)
      calculate(:count, column_name, options)
27 28
    end

29 30
    # Calculates the average value on a given column. Returns +nil+ if there's
    # no row. See +calculate+ for examples with options.
31
    #
32
    #   Person.average(:age) # => 35.8
33
    def average(column_name, options = {})
34 35
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
36
      calculate(:average, column_name, options)
37 38
    end

39
    # Calculates the minimum value on a given column. The value is returned
40 41 42
    # with the same data type of the column, or +nil+ if there's no row. See
    # +calculate+ for examples with options.
    #
43
    #   Person.minimum(:age) # => 7
44
    def minimum(column_name, options = {})
45 46
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
47
      calculate(:minimum, column_name, options)
48 49
    end

50 51 52 53
    # 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.
    #
54
    #   Person.maximum(:age) # => 93
55
    def maximum(column_name, options = {})
56 57
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
58
      calculate(:maximum, column_name, options)
59 60
    end

61 62 63 64
    # 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.
    #
65
    #   Person.sum(:age) # => 4562
66
    def sum(*args)
67
      calculate(:sum, *args)
68 69
    end

70
    # This calculates aggregate values in the given column. Methods for count, sum, average,
71
    # minimum, and maximum have been added as shortcuts.
72 73
    #
    # There are two basic forms of output:
74
    #
75
    #   * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
76
    #     for AVG, and the given column's type for everything else.
77
    #
78 79 80 81
    #   * Grouped values: This returns an ordered hash of the values and groups them. It
    #     takes either a column name, or the name of a belongs_to association.
    #
    #       values = Person.group('last_name').maximum(:age)
82
    #       puts values["Drake"]
83
    #       # => 43
84
    #
85
    #       drake  = Family.find_by(last_name: 'Drake')
86
    #       values = Person.group(:family).maximum(:age) # Person belongs_to :family
87
    #       puts values[drake]
88
    #       # => 43
89 90 91 92 93 94 95
    #
    #       values.each do |family, max_age|
    #       ...
    #       end
    #
    #   Person.calculate(:count, :all) # The same as Person.count
    #   Person.average(:age) # SELECT AVG(age) FROM people...
96 97
    #
    #   # Selects the minimum age for any family without any minors
98
    #   Person.group(:last_name).having("min(age) > 17").minimum(:age)
99
    #
100
    #   Person.sum("2 * age")
101
    def calculate(operation, column_name, options = {})
102 103
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
104
      if column_name.is_a?(Symbol) && attribute_alias?(column_name)
105
        column_name = attribute_alias(column_name)
106 107
      end

108
      if has_include?(column_name)
109
        construct_relation_for_association_calculations.calculate(operation, column_name, options)
110
      else
111
        perform_calculation(operation, column_name, options)
112 113 114
      end
    end

115 116
    # Use <tt>pluck</tt> as a shortcut to select one or more attributes without
    # loading a bunch of records just to grab the attributes you want.
J
Jeremy Kemper 已提交
117 118 119 120 121 122 123 124
    #
    #   Person.pluck(:name)
    #
    # instead of
    #
    #   Person.all.map(&:name)
    #
    # Pluck returns an <tt>Array</tt> of attribute values type-casted to match
V
Vijay Dev 已提交
125
    # the plucked column names, if they can be deduced. Plucking an SQL fragment
J
Jeremy Kemper 已提交
126
    # returns String values by default.
127
    #
J
Jeremy Kemper 已提交
128 129 130 131
    #   Person.pluck(:id)
    #   # SELECT people.id FROM people
    #   # => [1, 2, 3]
    #
132 133
    #   Person.pluck(:id, :name)
    #   # SELECT people.id, people.name FROM people
134
    #   # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
135
    #
136
    #   Person.pluck('DISTINCT role')
J
Jeremy Kemper 已提交
137 138 139
    #   # SELECT DISTINCT role FROM people
    #   # => ['admin', 'member', 'guest']
    #
A
AvnerCohen 已提交
140
    #   Person.where(age: 21).limit(5).pluck(:id)
J
Jeremy Kemper 已提交
141 142 143 144 145 146
    #   # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
    #   # => [2, 3]
    #
    #   Person.pluck('DATEDIFF(updated_at, created_at)')
    #   # SELECT DATEDIFF(updated_at, created_at) FROM people
    #   # => ['0', '27761', '173']
147
    #
148
    def pluck(*column_names)
149
      column_names.map! do |column_name|
150
        if column_name.is_a?(Symbol) && attribute_alias?(column_name)
151
          attribute_alias(column_name)
152
        else
153
          column_name.to_s
154
        end
155
      end
156

157 158
      if has_include?(column_names.first)
        construct_relation_for_association_calculations.pluck(*column_names)
159
      else
160
        relation = spawn
161
        relation.select_values = column_names.map { |cn|
162
          columns_hash.key?(cn) ? arel_table[cn] : cn
163
        }
164
        result = klass.connection.select_all(relation.arel, nil, bind_values)
165
        columns = result.columns.map do |key|
166
          klass.column_types.fetch(key) {
167
            result.column_types.fetch(key) { result.identity_type }
168
          }
169
        end
170

171 172
        result = result.map do |attributes|
          values = klass.initialize_attributes(attributes).values
173

174
          columns.zip(values).map { |column, value| column.type_cast value }
175
        end
176
        columns.one? ? result.map!(&:first) : result
177 178 179
      end
    end

T
twinturbo 已提交
180 181 182
    # Pluck all the ID's for the relation using the table's primary key
    #
    #   Person.ids # SELECT people.id FROM people
B
Ben Pickles 已提交
183
    #   Person.joins(:companies).ids # SELECT people.id FROM people INNER JOIN companies ON companies.person_id = people.id
T
twinturbo 已提交
184 185 186 187
    def ids
      pluck primary_key
    end

188 189
    private

190 191 192 193
    def has_include?(column_name)
      eager_loading? || (includes_values.present? && (column_name || references_eager_loaded_tables?))
    end

194
    def perform_calculation(operation, column_name, options = {})
195 196
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
197 198
      operation = operation.to_s.downcase

199
      # If #count is used with #distinct / #uniq it is considered distinct. (eg. relation.distinct.count)
200
      distinct = self.distinct_value
201

202
      if operation == "count"
203
        column_name ||= select_for_count
204

205
        unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
206 207
          distinct = true
        end
208

209
        column_name = primary_key if column_name == :all && distinct
210
        distinct = nil if column_name =~ /\s*DISTINCT[\s(]+/i
211 212
      end

213
      if group_values.any?
214
        execute_grouped_calculation(operation, column_name, distinct)
215
      else
N
Neeraj Singh 已提交
216
        execute_simple_calculation(operation, column_name, distinct)
217
      end
P
Pratik Naik 已提交
218 219
    end

220
    def aggregate_column(column_name)
221
      if @klass.column_names.include?(column_name.to_s)
222
        Arel::Attribute.new(@klass.unscoped.table, column_name)
223
      else
224
        Arel.sql(column_name == :all ? "*" : column_name.to_s)
225
      end
226 227
    end

228 229 230 231
    def operation_over_aggregate_column(column, operation, distinct)
      operation == 'count' ? column.count(distinct) : column.send(operation)
    end

232
    def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
233
      # Postgresql doesn't like ORDER BY when there are no GROUP BY
234
      relation = reorder(nil)
235

236 237
      column_alias = column_name

238 239 240
      if operation == "count" && (relation.limit_value || relation.offset_value)
        # Shortcut when limit is zero.
        return 0 if relation.limit_value == 0
241

242 243 244
        query_builder = build_count_subquery(relation, column_name, distinct)
      else
        column = aggregate_column(column_name)
245

246
        select_value = operation_over_aggregate_column(column, operation, distinct)
247

248
        column_alias = select_value.alias
249 250 251
        relation.select_values = [select_value]

        query_builder = relation.arel
252 253
      end

A
Aaron Patterson 已提交
254
      result = @klass.connection.select_all(query_builder, nil, relation.bind_values)
255 256 257 258 259 260 261
      row    = result.first
      value  = row && row.values.first
      column = result.column_types.fetch(column_alias) do
        column_for(column_name)
      end

      type_cast_calculated_value(value, column, operation)
262 263
    end

264
    def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
265 266 267
      group_attrs = group_values

      if group_attrs.first.respond_to?(:to_sym)
268 269 270
        association  = @klass.reflect_on_association(group_attrs.first.to_sym)
        associated   = group_attrs.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
        group_fields = Array(associated ? association.foreign_key : group_attrs)
271 272 273 274
      else
        group_fields = group_attrs
      end

A
Aaron Patterson 已提交
275 276 277
      group_aliases = group_fields.map { |field|
        column_alias_for(field)
      }
A
Aaron Patterson 已提交
278
      group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
279
        [aliaz, field]
A
Aaron Patterson 已提交
280
      }
281

282
      group = group_fields
283

284 285
      if operation == 'count' && column_name == :all
        aggregate_alias = 'count_all'
286
      else
A
Aaron Patterson 已提交
287
        aggregate_alias = column_alias_for([operation, column_name].join(' '))
288 289
      end

A
Aaron Patterson 已提交
290 291 292 293 294 295
      select_values = [
        operation_over_aggregate_column(
          aggregate_column(column_name),
          operation,
          distinct).as(aggregate_alias)
      ]
296
      select_values += select_values unless having_values.empty?
A
Aaron Patterson 已提交
297 298

      select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
299 300 301 302 303
        if field.respond_to?(:as)
          field.as(aliaz)
        else
          "#{field} AS #{aliaz}"
        end
A
Aaron Patterson 已提交
304 305
      }

A
Aaron Patterson 已提交
306 307
      relation = except(:group)
      relation.group_values  = group
A
Aaron Patterson 已提交
308
      relation.select_values = select_values
309

310
      calculated_data = @klass.connection.select_all(relation, nil, bind_values)
311 312

      if association
313
        key_ids     = calculated_data.collect { |row| row[group_aliases.first] }
314
        key_records = association.klass.base_class.find(key_ids)
315
        key_records = Hash[key_records.map { |r| [r.id, r] }]
316 317
      end

R
Raghunadh 已提交
318
      Hash[calculated_data.map do |row|
319
        key = group_columns.map { |aliaz, col_name|
320
          column = calculated_data.column_types.fetch(aliaz) do
321
            column_for(col_name)
322
          end
A
Aaron Patterson 已提交
323 324
          type_cast_calculated_value(row[aliaz], column)
        }
325
        key = key.first if key.size == 1
E
Emilio Tagua 已提交
326
        key = key_records[key] if associated
327 328 329

        column_type = calculated_data.column_types.fetch(aggregate_alias) { column_for(column_name) }
        [key, type_cast_calculated_value(row[aggregate_alias], column_type, operation)]
E
Emilio Tagua 已提交
330
      end]
331
    end
332

333 334 335 336 337 338 339 340
    # 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"
341
    def column_alias_for(keys)
342 343 344 345
      if keys.respond_to? :name
        keys = "#{keys.relation.name}.#{keys.name}"
      end

346
      table_name = keys.to_s.downcase
347 348 349 350 351 352 353 354 355
      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)
356
      field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
357
      @klass.columns_hash[field_name]
358 359 360
    end

    def type_cast_calculated_value(value, column, operation = nil)
361 362
      case operation
        when 'count'   then value.to_i
363
        when 'sum'     then type_cast_using_column(value || 0, column)
364
        when 'average' then value.respond_to?(:to_d) ? value.to_d : value
365
        else type_cast_using_column(value, column)
366 367 368 369 370 371 372
      end
    end

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

373 374 375 376 377 378 379 380 381
    # TODO: refactor to allow non-string `select_values` (eg. Arel nodes).
    def select_for_count
      if select_values.present?
        select_values.join(", ")
      else
        :all
      end
    end

382
    def build_count_subquery(relation, column_name, distinct)
383 384 385 386 387 388 389 390 391 392
      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)
393
    end
394 395
  end
end