calculations.rb 15.6 KB
Newer Older
1 2
# frozen_string_literal: true

3 4
require "active_support/core_ext/enumerable"

5
module ActiveRecord
6
  module Calculations
7 8 9 10 11 12 13 14 15 16 17
    # 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 '*')
    #
18
    #   Person.distinct.count(:age)
19
    #   # => counts the number of different age values
20
    #
21 22
    # If #count is used with {Relation#group}[rdoc-ref:QueryMethods#group],
    # it returns a Hash whose keys represent the aggregated column,
23 24 25 26
    # and the values are the respective amounts:
    #
    #   Person.group(:city).count
    #   # => { 'Rome' => 5, 'Paris' => 3 }
G
Godfrey Chan 已提交
27
    #
28
    # If #count is used with {Relation#group}[rdoc-ref:QueryMethods#group] for multiple columns, it returns a Hash whose
G
Godfrey Chan 已提交
29
    # keys are an array containing the individual values of each column and the value
30
    # of each key would be the #count.
G
Godfrey Chan 已提交
31
    #
32
    #   Article.group(:status, :category).count
G
Godfrey Chan 已提交
33
    #   # =>  {["draft", "business"]=>10, ["draft", "technology"]=>4,
34
    #          ["published", "business"]=>0, ["published", "technology"]=>2}
G
Godfrey Chan 已提交
35
    #
36
    # If #count is used with {Relation#select}[rdoc-ref:QueryMethods#select], it will count the selected columns:
37 38 39 40
    #
    #   Person.select(:age).count
    #   # => counts the number of different age values
    #
41
    # Note: not all valid {Relation#select}[rdoc-ref:QueryMethods#select] expressions are valid #count expressions. The specifics differ
C
Cade Truitt 已提交
42
    # between databases. In invalid cases, an error from the database is thrown.
43
    def count(column_name = nil)
44 45
      if block_given?
        unless column_name.nil?
46
          raise ArgumentError, "Column name argument is not supported when a block is passed."
47 48
        end

49 50 51
        super()
      else
        calculate(:count, column_name)
52
      end
53 54
    end

55
    # Calculates the average value on a given column. Returns +nil+ if there's
56
    # no row. See #calculate for examples with options.
57
    #
58
    #   Person.average(:age) # => 35.8
59 60
    def average(column_name)
      calculate(:average, column_name)
61 62
    end

63
    # Calculates the minimum value on a given column. The value is returned
64
    # with the same data type of the column, or +nil+ if there's no row. See
65
    # #calculate for examples with options.
66
    #
67
    #   Person.minimum(:age) # => 7
68 69
    def minimum(column_name)
      calculate(:minimum, column_name)
70 71
    end

72 73
    # 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
74
    # #calculate for examples with options.
75
    #
76
    #   Person.maximum(:age) # => 93
77 78
    def maximum(column_name)
      calculate(:maximum, column_name)
79 80
    end

81
    # Calculates the sum of values on a given column. The value is returned
82 83
    # with the same data type of the column, +0+ if there's no row. See
    # #calculate for examples with options.
84
    #
85
    #   Person.sum(:age) # => 4562
86
    def sum(column_name = nil)
87 88
      if block_given?
        unless column_name.nil?
89
          raise ArgumentError, "Column name argument is not supported when a block is passed."
90 91
        end

92 93 94
        super()
      else
        calculate(:sum, column_name)
95
      end
96 97
    end

98 99
    # This calculates aggregate values in the given column. Methods for #count, #sum, #average,
    # #minimum, and #maximum have been added as shortcuts.
100
    #
101 102
    #   Person.calculate(:count, :all) # The same as Person.count
    #   Person.average(:age) # SELECT AVG(age) FROM people...
103
    #
104 105
    #   # Selects the minimum age for any family without any minors
    #   Person.group(:last_name).having("min(age) > 17").minimum(:age)
106
    #
107
    #   Person.sum("2 * age")
108
    #
109
    # There are two basic forms of output:
110
    #
111
    # * Single aggregate value: The single value is type cast to Integer for COUNT, Float
112
    #   for AVG, and the given column's type for everything else.
113
    #
114 115
    # * 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.
116
    #
117 118 119
    #      values = Person.group('last_name').maximum(:age)
    #      puts values["Drake"]
    #      # => 43
120
    #
121 122 123 124
    #      drake  = Family.find_by(last_name: 'Drake')
    #      values = Person.group(:family).maximum(:age) # Person belongs_to :family
    #      puts values[drake]
    #      # => 43
125
    #
126 127 128
    #      values.each do |family, max_age|
    #        ...
    #      end
129
    def calculate(operation, column_name)
130
      if has_include?(column_name)
131
        relation = apply_join_dependency
132

133
        if operation.to_s.downcase == "count"
134 135 136
          unless distinct_value || distinct_select?(column_name || select_for_count)
            relation.distinct!
            relation.select_values = [ klass.primary_key || table[Arel.star] ]
137
          end
138 139
          # PostgreSQL: ORDER BY expressions must appear in SELECT list when using DISTINCT
          relation.order_values = []
140
        end
141 142

        relation.calculate(operation, column_name)
143
      else
144
        perform_calculation(operation, column_name)
145 146 147
      end
    end

148
    # Use #pluck as a shortcut to select one or more attributes without
149
    # loading a bunch of records just to grab the attributes you want.
J
Jeremy Kemper 已提交
150 151 152 153 154 155 156
    #
    #   Person.pluck(:name)
    #
    # instead of
    #
    #   Person.all.map(&:name)
    #
157
    # Pluck returns an Array of attribute values type-casted to match
V
Vijay Dev 已提交
158
    # the plucked column names, if they can be deduced. Plucking an SQL fragment
J
Jeremy Kemper 已提交
159
    # returns String values by default.
160
    #
161 162 163
    #   Person.pluck(:name)
    #   # SELECT people.name FROM people
    #   # => ['David', 'Jeremy', 'Jose']
J
Jeremy Kemper 已提交
164
    #
165 166
    #   Person.pluck(:id, :name)
    #   # SELECT people.id, people.name FROM people
167
    #   # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
168
    #
J
Jon Atack 已提交
169
    #   Person.distinct.pluck(:role)
J
Jeremy Kemper 已提交
170 171 172
    #   # SELECT DISTINCT role FROM people
    #   # => ['admin', 'member', 'guest']
    #
A
AvnerCohen 已提交
173
    #   Person.where(age: 21).limit(5).pluck(:id)
J
Jeremy Kemper 已提交
174 175 176
    #   # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
    #   # => [2, 3]
    #
177
    #   Person.pluck(Arel.sql('DATEDIFF(updated_at, created_at)'))
J
Jeremy Kemper 已提交
178 179
    #   # SELECT DATEDIFF(updated_at, created_at) FROM people
    #   # => ['0', '27761', '173']
180
    #
181
    # See also #ids.
182
    #
183
    def pluck(*column_names)
184
      if loaded? && all_attributes?(column_names)
B
Ben Toews 已提交
185 186
        return records.pluck(*column_names)
      end
187

B
Ben Toews 已提交
188
      if has_include?(column_names.first)
189 190
        relation = apply_join_dependency
        relation.pluck(*column_names)
B
Ben Toews 已提交
191
      else
192
        klass.disallow_raw_sql!(column_names)
B
Ben Toews 已提交
193
        relation = spawn
194
        relation.select_values = column_names
195 196 197 198 199 200 201
        result = skip_query_cache_if_necessary do
          if where_clause.contradiction?
            ActiveRecord::Result.new([], [])
          else
            klass.connection.select_all(relation.arel, nil)
          end
        end
B
Ben Toews 已提交
202 203
        result.cast_values(klass.attribute_types)
      end
204 205
    end

206
    # Pick the value(s) from the named column(s) in the current relation.
207
    # This is short-hand for <tt>relation.limit(1).pluck(*column_names).first</tt>, and is primarily useful
208 209 210 211 212 213 214 215 216 217 218 219 220
    # when you have a relation that's already narrowed down to a single row.
    #
    # Just like #pluck, #pick will only load the actual value, not the entire record object, so it's also
    # more efficient. The value is, again like with pluck, typecast by the column type.
    #
    #   Person.where(id: 1).pick(:name)
    #   # SELECT people.name FROM people WHERE id = 1 LIMIT 1
    #   # => 'David'
    #
    #   Person.where(id: 1).pick(:name, :email_address)
    #   # SELECT people.name, people.email_address FROM people WHERE id = 1 LIMIT 1
    #   # => [ 'David', 'david@loudthinking.com' ]
    def pick(*column_names)
221 222 223 224
      if loaded? && all_attributes?(column_names)
        return records.pick(*column_names)
      end

225 226 227
      limit(1).pluck(*column_names).first
    end

T
twinturbo 已提交
228 229 230
    # Pluck all the ID's for the relation using the table's primary key
    #
    #   Person.ids # SELECT people.id FROM people
B
Ben Pickles 已提交
231
    #   Person.joins(:companies).ids # SELECT people.id FROM people INNER JOIN companies ON companies.person_id = people.id
T
twinturbo 已提交
232 233 234 235
    def ids
      pluck primary_key
    end

236
    private
237 238 239 240
      def all_attributes?(column_names)
        (column_names.map(&:to_s) - @klass.attribute_names - @klass.attribute_aliases.keys).empty?
      end

241 242 243
      def has_include?(column_name)
        eager_loading? || (includes_values.present? && column_name && column_name != :all)
      end
244

245 246
      def perform_calculation(operation, column_name)
        operation = operation.to_s.downcase
247

248 249
        # If #count is used with #distinct (i.e. `relation.distinct.count`) it is
        # considered distinct.
250
        distinct = distinct_value
251

252 253
        if operation == "count"
          column_name ||= select_for_count
254
          if column_name == :all
255 256 257
            if !distinct
              distinct = distinct_select?(select_for_count) if group_values.empty?
            elsif group_values.any? || select_values.empty? && order_values.empty?
258 259
              column_name = primary_key
            end
260
          elsif distinct_select?(column_name)
261 262
            distinct = nil
          end
263
        end
264

265 266 267 268 269
        if group_values.any?
          execute_grouped_calculation(operation, column_name, distinct)
        else
          execute_simple_calculation(operation, column_name, distinct)
        end
270 271
      end

272 273 274 275
      def distinct_select?(column_name)
        column_name.is_a?(::String) && /\bDISTINCT[\s(]/i.match?(column_name)
      end

276 277
      def aggregate_column(column_name)
        return column_name if Arel::Expressions === column_name
P
Pratik Naik 已提交
278

279 280
        arel_column(column_name.to_s) do |name|
          Arel.sql(column_name == :all ? "*" : name)
281 282
        end
      end
283

284 285
      def operation_over_aggregate_column(column_name, operation, distinct)
        column = aggregate_column(column_name)
286
        operation == "count" ? column.count(distinct) : column.send(operation)
287
      end
288

289
      def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
290
        if operation == "count" && (column_name == :all && distinct || has_limit_or_offset?)
291
          # Shortcut when limit is zero.
292
          return 0 if limit_value == 0
293

294
          query_builder = build_count_subquery(spawn, column_name, distinct)
295
        else
296
          # PostgreSQL doesn't like ORDER BY when there are no GROUP BY
297
          relation = unscope(:order).distinct!(false)
298

299 300
          select_value = operation_over_aggregate_column(column_name, operation, distinct)
          select_value.distinct = true if operation == "sum" && distinct
301

302
          relation.select_values = [select_value]
303

304
          query_builder = relation.arel
305
        end
306

307 308 309
        result = skip_query_cache_if_necessary { @klass.connection.select_all(query_builder) }

        type_cast_calculated_value(result.cast_values.first, operation) do |value|
310
          if type = klass.attribute_types[column_name.to_s]
311 312 313 314 315
            type.deserialize(value)
          else
            value
          end
        end
316 317
      end

318
      def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
319
        group_fields = group_values
320

321 322 323 324
        if group_fields.size == 1 && group_fields.first.respond_to?(:to_sym)
          association  = klass._reflect_on_association(group_fields.first)
          associated   = association && association.belongs_to? # only count belongs_to associations
          group_fields = Array(association.foreign_key) if associated
325 326
        end
        group_fields = arel_columns(group_fields)
327

328 329
        group_aliases = group_fields.map { |field|
          field = connection.visitor.compile(field) if Arel.arel_node?(field)
330
          column_alias_for(field.to_s.downcase)
331
        }
332
        group_columns = group_aliases.zip(group_fields)
333

334 335 336
        column_alias = column_alias_for("#{operation} #{column_name.to_s.downcase}")
        select_value = operation_over_aggregate_column(column_name, operation, distinct)
        select_value.as(column_alias)
A
Aaron Patterson 已提交
337

338
        select_values = [select_value]
339
        select_values += self.select_values unless having_clause.empty?
340 341 342 343 344 345 346 347

        select_values.concat group_columns.map { |aliaz, field|
          if field.respond_to?(:as)
            field.as(aliaz)
          else
            "#{field} AS #{aliaz}"
          end
        }
348

349
        relation = except(:group).distinct!(false)
350
        relation.group_values  = group_fields
351
        relation.select_values = select_values
352

353
        calculated_data = skip_query_cache_if_necessary { @klass.connection.select_all(relation.arel, nil) }
354

355 356 357
        if association
          key_ids     = calculated_data.collect { |row| row[group_aliases.first] }
          key_records = association.klass.base_class.where(association.klass.base_class.primary_key => key_ids)
358
          key_records = key_records.index_by(&:id)
359
        end
360

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
        key_types = group_columns.each_with_object({}) do |(aliaz, col_name), types|
          types[aliaz] = type_for(col_name) do
            calculated_data.column_types.fetch(aliaz, Type.default_value)
          end
        end

        hash_rows = calculated_data.cast_values(key_types).map! do |row|
          calculated_data.columns.each_with_object({}).with_index do |(column, hash), i|
            hash[column] = row[i]
          end
        end

        type = nil
        hash_rows.each_with_object({}) do |row, result|
          key = group_aliases.map { |aliaz| row[aliaz] }
376 377 378
          key = key.first if key.size == 1
          key = key_records[key] if associated

379
          result[key] = type_cast_calculated_value(row[column_alias], operation) do |value|
380
            if type ||= klass.attribute_types[column_name.to_s]
381 382 383 384 385
              type.deserialize(value)
            else
              value
            end
          end
386
        end
387
      end
388

389
      # Converts the given field to the value that the database adapter returns as
390 391 392 393 394 395
      # 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"
396
      def column_alias_for(field)
397
        column_alias = +field
398 399 400 401 402 403
        column_alias.gsub!(/\*/, "all")
        column_alias.gsub!(/\W+/, " ")
        column_alias.strip!
        column_alias.gsub!(/ +/, "_")

        connection.table_alias_for(column_alias)
404
      end
405

406 407 408 409
      def type_for(field, &block)
        field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split(".").last
        @klass.type_for_attribute(field_name, &block)
      end
410

411
      def type_cast_calculated_value(value, operation)
412
        case operation
413 414 415 416 417 418
        when "count", "sum"
          value || 0
        when "average"
          value&.respond_to?(:to_d) ? value.to_d : value
        else # "minimum", "maximum"
          yield value
419
        end
420 421
      end

422 423 424 425 426 427 428
      def select_for_count
        if select_values.present?
          return select_values.first if select_values.one?
          select_values.join(", ")
        else
          :all
        end
429 430
      end

431
      def build_count_subquery(relation, column_name, distinct)
432
        if column_name == :all
433
          column_alias = Arel.star
434 435 436 437 438
          relation.select_values = [ Arel.sql(FinderMethods::ONE_AS_ONE) ] unless distinct
        else
          column_alias = Arel.sql("count_column")
          relation.select_values = [ aggregate_column(column_name).as(column_alias) ]
        end
439

440 441
        subquery_alias = Arel.sql("subquery_for_count")
        select_value = operation_over_aggregate_column(column_alias, "count", false)
442

443
        relation.build_subquery(subquery_alias, select_value)
444
      end
445 446
  end
end