calculations.rb 13.3 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 }
G
Godfrey Chan 已提交
22 23 24
    #
    # If +count+ is used with +group+ for multiple columns, it returns a Hash whose
    # keys are an array containing the individual values of each column and the value
25
    # of each key would be the +count+.
G
Godfrey Chan 已提交
26
    #
27
    #   Article.group(:status, :category).count
G
Godfrey Chan 已提交
28
    #   # =>  {["draft", "business"]=>10, ["draft", "technology"]=>4,
29
    #          ["published", "business"]=>0, ["published", "technology"]=>2}
G
Godfrey Chan 已提交
30
    #
31 32 33 34 35 36
    # 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
C
Cade Truitt 已提交
37
    # between databases. In invalid cases, an error from the database is thrown.
38 39
    def count(column_name = nil)
      calculate(:count, column_name)
40 41
    end

42 43
    # Calculates the average value on a given column. Returns +nil+ if there's
    # no row. See +calculate+ for examples with options.
44
    #
45
    #   Person.average(:age) # => 35.8
46 47
    def average(column_name)
      calculate(:average, column_name)
48 49
    end

50
    # Calculates the minimum value on a given column. The value is returned
51 52 53
    # with the same data type of the column, or +nil+ if there's no row. See
    # +calculate+ for examples with options.
    #
54
    #   Person.minimum(:age) # => 7
55 56
    def minimum(column_name)
      calculate(:minimum, column_name)
57 58
    end

59 60 61 62
    # 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.
    #
63
    #   Person.maximum(:age) # => 93
64 65
    def maximum(column_name)
      calculate(:maximum, column_name)
66 67
    end

68 69 70 71
    # 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.
    #
72
    #   Person.sum(:age) # => 4562
73 74 75 76 77 78
    def sum(*args, &block)
      if block_given?
        to_a.sum(&block)
      else
        calculate(:sum, *args)
      end
79 80
    end

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

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

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

168 169 170 171
      if loaded? && (column_names - @klass.column_names).empty?
        return @records.pluck(*column_names)
      end

172 173
      if has_include?(column_names.first)
        construct_relation_for_association_calculations.pluck(*column_names)
174
      else
175
        relation = spawn
176
        relation.select_values = column_names.map { |cn|
177
          columns_hash.key?(cn) ? arel_table[cn] : cn
178
        }
S
Sean Griffin 已提交
179
        result = klass.connection.select_all(relation.arel, nil, bound_attributes)
180
        result.cast_values(klass.attribute_types)
181 182 183
      end
    end

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

192 193
    private

194
    def has_include?(column_name)
195
      eager_loading? || (includes_values.present? && column_name && column_name != :all)
196 197
    end

198
    def perform_calculation(operation, column_name)
199 200
      operation = operation.to_s.downcase

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

204
      if operation == "count"
205
        column_name ||= select_for_count
206

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

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

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

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

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

234
    def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
235
      # PostgreSQL doesn't like ORDER BY when there are no GROUP BY
L
Lauro Caetano 已提交
236
      relation = unscope(:order)
237

238 239
      column_alias = column_name

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

244 245 246
        query_builder = build_count_subquery(relation, column_name, distinct)
      else
        column = aggregate_column(column_name)
247

248
        select_value = operation_over_aggregate_column(column, operation, distinct)
249

250 251
        column_alias = select_value.alias
        column_alias ||= @klass.connection.column_name_for_operation(operation, select_value)
252 253 254
        relation.select_values = [select_value]

        query_builder = relation.arel
255 256
      end

S
Sean Griffin 已提交
257
      result = @klass.connection.select_all(query_builder, nil, bound_attributes)
258 259 260
      row    = result.first
      value  = row && row.values.first
      column = result.column_types.fetch(column_alias) do
261
        type_for(column_name)
262 263 264
      end

      type_cast_calculated_value(value, column, operation)
265 266
    end

267
    def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
268 269 270
      group_attrs = group_values

      if group_attrs.first.respond_to?(:to_sym)
G
Godfrey Chan 已提交
271
        association  = @klass._reflect_on_association(group_attrs.first)
E
eileencodes 已提交
272
        associated   = group_attrs.size == 1 && association && association.belongs_to? # only count belongs_to associations
273
        group_fields = Array(associated ? association.foreign_key : group_attrs)
274 275 276 277
      else
        group_fields = group_attrs
      end

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

285
      group = group_fields
286

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

A
Aaron Patterson 已提交
293 294 295 296 297 298
      select_values = [
        operation_over_aggregate_column(
          aggregate_column(column_name),
          operation,
          distinct).as(aggregate_alias)
      ]
299
      select_values += select_values unless having_clause.empty?
A
Aaron Patterson 已提交
300 301

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

A
Aaron Patterson 已提交
309 310
      relation = except(:group)
      relation.group_values  = group
A
Aaron Patterson 已提交
311
      relation.select_values = select_values
312

S
Sean Griffin 已提交
313
      calculated_data = @klass.connection.select_all(relation, nil, relation.bound_attributes)
314 315

      if association
316
        key_ids     = calculated_data.collect { |row| row[group_aliases.first] }
317
        key_records = association.klass.base_class.where(association.klass.base_class.primary_key => key_ids)
318
        key_records = Hash[key_records.map { |r| [r.id, r] }]
319 320
      end

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

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

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

349
      table_name = keys.to_s.downcase
350 351 352 353 354 355 356 357
      table_name.gsub!(/\*/, 'all')
      table_name.gsub!(/\W+/, ' ')
      table_name.strip!
      table_name.gsub!(/ +/, '_')

      @klass.connection.table_alias_for(table_name)
    end

358
    def type_for(field)
359
      field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
360
      @klass.type_for_attribute(field_name)
361 362
    end

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

372 373 374 375 376 377 378 379 380
    # 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

381
    def build_count_subquery(relation, column_name, distinct)
382 383 384 385 386
      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]
387
      subquery = relation.arel.as(subquery_alias)
388 389 390 391

      sm = Arel::SelectManager.new relation.engine
      select_value = operation_over_aggregate_column(column_alias, 'count', distinct)
      sm.project(select_value).from(subquery)
392
    end
393 394
  end
end