calculations.rb 14.1 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 23 24 25 26 27 28 29
    #
    # If +count+ is used with +select+, it will count the selected columns:
    #
    #   Person.select(:age).count
    #   # => counts the number of different age values
    #
    # Note: not all valid +select+ expressions are valid +count+ expressions. The specifics differ
    # between databases. In invalid cases, an error from the databsae is thrown.
30
    def count(column_name = nil, options = {})
31 32
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
33 34
      column_name, options = nil, column_name if column_name.is_a?(Hash)
      calculate(:count, column_name, options)
35 36
    end

37 38
    # Calculates the average value on a given column. Returns +nil+ if there's
    # no row. See +calculate+ for examples with options.
39
    #
40
    #   Person.average(:age) # => 35.8
41
    def average(column_name, options = {})
42 43
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
44
      calculate(:average, column_name, options)
45 46
    end

47
    # Calculates the minimum value on a given column. The value is returned
48 49 50
    # with the same data type of the column, or +nil+ if there's no row. See
    # +calculate+ for examples with options.
    #
51
    #   Person.minimum(:age) # => 7
52
    def minimum(column_name, options = {})
53 54
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
55
      calculate(:minimum, column_name, options)
56 57
    end

58 59 60 61
    # 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.
    #
62
    #   Person.maximum(:age) # => 93
63
    def maximum(column_name, options = {})
64 65
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
66
      calculate(:maximum, column_name, options)
67 68
    end

69 70 71 72
    # 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.
    #
73
    #   Person.sum(:age) # => 4562
74
    def sum(*args)
75
      calculate(:sum, *args)
76 77
    end

78
    # This calculates aggregate values in the given column. Methods for count, sum, average,
79
    # minimum, and maximum have been added as shortcuts.
80 81
    #
    # There are two basic forms of output:
82
    #
83
    #   * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
84
    #     for AVG, and the given column's type for everything else.
85
    #
86 87 88 89
    #   * 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)
90
    #       puts values["Drake"]
91
    #       # => 43
92
    #
93
    #       drake  = Family.find_by(last_name: 'Drake')
94
    #       values = Person.group(:family).maximum(:age) # Person belongs_to :family
95
    #       puts values[drake]
96
    #       # => 43
97 98 99 100 101 102 103
    #
    #       values.each do |family, max_age|
    #       ...
    #       end
    #
    #   Person.calculate(:count, :all) # The same as Person.count
    #   Person.average(:age) # SELECT AVG(age) FROM people...
104 105
    #
    #   # Selects the minimum age for any family without any minors
106
    #   Person.group(:last_name).having("min(age) > 17").minimum(:age)
107
    #
108
    #   Person.sum("2 * age")
109
    def calculate(operation, column_name, options = {})
110 111
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
112
      if column_name.is_a?(Symbol) && attribute_alias?(column_name)
113
        column_name = attribute_alias(column_name)
114 115
      end

116
      if has_include?(column_name)
117
        construct_relation_for_association_calculations.calculate(operation, column_name, options)
118
      else
119
        perform_calculation(operation, column_name, options)
120 121 122
      end
    end

123 124
    # 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 已提交
125 126 127 128 129 130 131 132
    #
    #   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 已提交
133
    # the plucked column names, if they can be deduced. Plucking an SQL fragment
J
Jeremy Kemper 已提交
134
    # returns String values by default.
135
    #
J
Jeremy Kemper 已提交
136 137 138 139
    #   Person.pluck(:id)
    #   # SELECT people.id FROM people
    #   # => [1, 2, 3]
    #
140 141
    #   Person.pluck(:id, :name)
    #   # SELECT people.id, people.name FROM people
142
    #   # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
143
    #
144
    #   Person.pluck('DISTINCT role')
J
Jeremy Kemper 已提交
145 146 147
    #   # SELECT DISTINCT role FROM people
    #   # => ['admin', 'member', 'guest']
    #
A
AvnerCohen 已提交
148
    #   Person.where(age: 21).limit(5).pluck(:id)
J
Jeremy Kemper 已提交
149 150 151 152 153 154
    #   # 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']
155
    #
156
    def pluck(*column_names)
157
      column_names.map! do |column_name|
158
        if column_name.is_a?(Symbol) && attribute_alias?(column_name)
159
          attribute_alias(column_name)
160
        else
161
          column_name.to_s
162
        end
163
      end
164

165 166
      if has_include?(column_names.first)
        construct_relation_for_association_calculations.pluck(*column_names)
167
      else
168
        relation = spawn
169
        relation.select_values = column_names.map { |cn|
170
          columns_hash.key?(cn) ? arel_table[cn] : cn
171
        }
172
        result = klass.connection.select_all(relation.arel, nil, bind_values)
173
        columns = result.columns.map do |key|
174
          klass.column_types.fetch(key) {
175
            result.column_types.fetch(key) { result.identity_type }
176
          }
177
        end
178

179
        result = result.map do |attributes|
180
          values = attributes.values
181

182
          columns.zip(values).map { |column, value| column.type_cast value }
183
        end
184
        columns.one? ? result.map!(&:first) : result
185 186 187
      end
    end

T
twinturbo 已提交
188 189 190
    # Pluck all the ID's for the relation using the table's primary key
    #
    #   Person.ids # SELECT people.id FROM people
B
Ben Pickles 已提交
191
    #   Person.joins(:companies).ids # SELECT people.id FROM people INNER JOIN companies ON companies.person_id = people.id
T
twinturbo 已提交
192 193 194 195
    def ids
      pluck primary_key
    end

196 197
    private

198
    def has_include?(column_name)
199
      eager_loading? || (includes_values.present? && ((column_name && column_name != :all) || references_eager_loaded_tables?))
200 201
    end

202
    def perform_calculation(operation, column_name, options = {})
203 204
      # TODO: Remove options argument as soon we remove support to
      # activerecord-deprecated_finders.
205 206
      operation = operation.to_s.downcase

207
      # If #count is used with #distinct / #uniq it is considered distinct. (eg. relation.distinct.count)
208
      distinct = self.distinct_value
209

210
      if operation == "count"
211
        column_name ||= select_for_count
212

213
        unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
214 215
          distinct = true
        end
216

217
        column_name = primary_key if column_name == :all && distinct
218
        distinct = nil if column_name =~ /\s*DISTINCT[\s(]+/i
219 220
      end

221
      if group_values.any?
222
        execute_grouped_calculation(operation, column_name, distinct)
223
      else
N
Neeraj Singh 已提交
224
        execute_simple_calculation(operation, column_name, distinct)
225
      end
P
Pratik Naik 已提交
226 227
    end

228
    def aggregate_column(column_name)
229
      if @klass.column_names.include?(column_name.to_s)
230
        Arel::Attribute.new(@klass.unscoped.table, column_name)
231
      else
232
        Arel.sql(column_name == :all ? "*" : column_name.to_s)
233
      end
234 235
    end

236 237 238 239
    def operation_over_aggregate_column(column, operation, distinct)
      operation == 'count' ? column.count(distinct) : column.send(operation)
    end

240
    def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
241
      # Postgresql doesn't like ORDER BY when there are no GROUP BY
L
Lauro Caetano 已提交
242
      relation = unscope(:order)
243

244 245
      column_alias = column_name

246 247
      bind_values = nil

248 249 250
      if operation == "count" && (relation.limit_value || relation.offset_value)
        # Shortcut when limit is zero.
        return 0 if relation.limit_value == 0
251

252
        query_builder = build_count_subquery(relation, column_name, distinct)
253
        bind_values = query_builder.bind_values + relation.bind_values
254 255
      else
        column = aggregate_column(column_name)
256

257
        select_value = operation_over_aggregate_column(column, operation, distinct)
258

259
        column_alias = select_value.alias
260 261 262
        relation.select_values = [select_value]

        query_builder = relation.arel
263
        bind_values = query_builder.bind_values + relation.bind_values
264 265
      end

266
      result = @klass.connection.select_all(query_builder, nil, bind_values)
267 268 269 270 271 272 273
      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)
274 275
    end

276
    def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
277 278 279
      group_attrs = group_values

      if group_attrs.first.respond_to?(:to_sym)
280
        association  = @klass._reflect_on_association(group_attrs.first.to_sym)
281 282
        associated   = group_attrs.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
        group_fields = Array(associated ? association.foreign_key : group_attrs)
283 284 285 286
      else
        group_fields = group_attrs
      end

A
Aaron Patterson 已提交
287 288 289
      group_aliases = group_fields.map { |field|
        column_alias_for(field)
      }
A
Aaron Patterson 已提交
290
      group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
291
        [aliaz, field]
A
Aaron Patterson 已提交
292
      }
293

294
      group = group_fields
295

296 297
      if operation == 'count' && column_name == :all
        aggregate_alias = 'count_all'
298
      else
A
Aaron Patterson 已提交
299
        aggregate_alias = column_alias_for([operation, column_name].join(' '))
300 301
      end

A
Aaron Patterson 已提交
302 303 304 305 306 307
      select_values = [
        operation_over_aggregate_column(
          aggregate_column(column_name),
          operation,
          distinct).as(aggregate_alias)
      ]
308
      select_values += select_values unless having_values.empty?
A
Aaron Patterson 已提交
309 310

      select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
311 312 313 314 315
        if field.respond_to?(:as)
          field.as(aliaz)
        else
          "#{field} AS #{aliaz}"
        end
A
Aaron Patterson 已提交
316 317
      }

A
Aaron Patterson 已提交
318 319
      relation = except(:group)
      relation.group_values  = group
A
Aaron Patterson 已提交
320
      relation.select_values = select_values
321

322
      calculated_data = @klass.connection.select_all(relation, nil, bind_values)
323 324

      if association
325
        key_ids     = calculated_data.collect { |row| row[group_aliases.first] }
326
        key_records = association.klass.base_class.find(key_ids)
327
        key_records = Hash[key_records.map { |r| [r.id, r] }]
328 329
      end

R
Raghunadh 已提交
330
      Hash[calculated_data.map do |row|
331
        key = group_columns.map { |aliaz, col_name|
332
          column = calculated_data.column_types.fetch(aliaz) do
333
            column_for(col_name)
334
          end
A
Aaron Patterson 已提交
335 336
          type_cast_calculated_value(row[aliaz], column)
        }
337
        key = key.first if key.size == 1
E
Emilio Tagua 已提交
338
        key = key_records[key] if associated
339 340 341

        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 已提交
342
      end]
343
    end
344

345 346 347 348 349 350 351 352
    # 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"
353
    def column_alias_for(keys)
354 355 356 357
      if keys.respond_to? :name
        keys = "#{keys.relation.name}.#{keys.name}"
      end

358
      table_name = keys.to_s.downcase
359 360 361 362 363 364 365 366 367
      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)
368
      field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
369
      @klass.columns_hash[field_name]
370 371 372
    end

    def type_cast_calculated_value(value, column, operation = nil)
373 374
      case operation
        when 'count'   then value.to_i
375
        when 'sum'     then type_cast_using_column(value || 0, column)
376
        when 'average' then value.respond_to?(:to_d) ? value.to_d : value
377
        else type_cast_using_column(value, column)
378 379 380 381 382 383 384
      end
    end

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

385 386 387 388 389 390 391 392 393
    # 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

394
    def build_count_subquery(relation, column_name, distinct)
395 396 397 398 399
      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]
400 401
      arel = relation.arel
      subquery = arel.as(subquery_alias)
402 403

      sm = Arel::SelectManager.new relation.engine
404
      sm.bind_values = arel.bind_values
405 406
      select_value = operation_over_aggregate_column(column_alias, 'count', distinct)
      sm.project(select_value).from(subquery)
407
    end
408 409
  end
end