calculations.rb 13.4 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 }
P
Pratik Naik 已提交
22
    def count(column_name = nil, options = {})
23 24
      column_name, options = nil, column_name if column_name.is_a?(Hash)
      calculate(:count, column_name, options)
25 26
    end

27 28
    # Calculates the average value on a given column. Returns +nil+ if there's
    # no row. See +calculate+ for examples with options.
29
    #
30
    #   Person.average(:age) # => 35.8
31
    def average(column_name, options = {})
32
      calculate(:average, column_name, options)
33 34
    end

35
    # Calculates the minimum value on a given column. The value is returned
36 37 38
    # with the same data type of the column, or +nil+ if there's no row. See
    # +calculate+ for examples with options.
    #
39
    #   Person.minimum(:age) # => 7
40
    def minimum(column_name, options = {})
41
      calculate(:minimum, column_name, options)
42 43
    end

44 45 46 47
    # 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.
    #
48
    #   Person.maximum(:age) # => 93
49
    def maximum(column_name, options = {})
50
      calculate(:maximum, column_name, options)
51 52
    end

53 54 55 56
    # 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.
    #
57
    #   Person.sum(:age) # => 4562
58
    def sum(*args)
59
      calculate(:sum, *args)
60 61
    end

62
    # This calculates aggregate values in the given column. Methods for count, sum, average,
63
    # minimum, and maximum have been added as shortcuts.
64 65
    #
    # There are two basic forms of output:
66
    #
67
    #   * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
68
    #     for AVG, and the given column's type for everything else.
69
    #
70 71 72 73
    #   * 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)
74
    #       puts values["Drake"]
75
    #       # => 43
76
    #
77
    #       drake  = Family.find_by(last_name: 'Drake')
78
    #       values = Person.group(:family).maximum(:age) # Person belongs_to :family
79
    #       puts values[drake]
80
    #       # => 43
81 82 83 84 85 86 87
    #
    #       values.each do |family, max_age|
    #       ...
    #       end
    #
    #   Person.calculate(:count, :all) # The same as Person.count
    #   Person.average(:age) # SELECT AVG(age) FROM people...
88 89
    #
    #   # Selects the minimum age for any family without any minors
90
    #   Person.group(:last_name).having("min(age) > 17").minimum(:age)
91
    #
92
    #   Person.sum("2 * age")
93
    def calculate(operation, column_name, options = {})
94
      relation = with_default_scope
95

96 97 98 99
      if column_name.is_a?(Symbol) && attribute_aliases.key?(column_name.to_s)
        column_name = attribute_aliases[column_name.to_s].to_sym
      end

100
      if relation.equal?(self)
101
        if has_include?(column_name)
102
          construct_relation_for_association_calculations.calculate(operation, column_name, options)
103
        else
104
          perform_calculation(operation, column_name, options)
105
        end
106 107
      else
        relation.calculate(operation, column_name, options)
108 109 110
      end
    end

111 112
    # 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 已提交
113 114 115 116 117 118 119 120
    #
    #   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 已提交
121
    # the plucked column names, if they can be deduced. Plucking an SQL fragment
J
Jeremy Kemper 已提交
122
    # returns String values by default.
123
    #
J
Jeremy Kemper 已提交
124 125 126 127
    #   Person.pluck(:id)
    #   # SELECT people.id FROM people
    #   # => [1, 2, 3]
    #
128 129
    #   Person.pluck(:id, :name)
    #   # SELECT people.id, people.name FROM people
130
    #   # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
131
    #
132
    #   Person.pluck('DISTINCT role')
J
Jeremy Kemper 已提交
133 134 135
    #   # SELECT DISTINCT role FROM people
    #   # => ['admin', 'member', 'guest']
    #
A
AvnerCohen 已提交
136
    #   Person.where(age: 21).limit(5).pluck(:id)
J
Jeremy Kemper 已提交
137 138 139 140 141 142
    #   # 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']
143
    #
144
    def pluck(*column_names)
145
      column_names.map! do |column_name|
146 147 148 149 150 151 152 153
        if column_name.is_a?(Symbol)
          if attribute_aliases.key?(column_name.to_s)
            column_name = attribute_aliases[column_name.to_s].to_sym
          end

          if self.columns_hash.key?(column_name.to_s)
            column_name = "#{connection.quote_table_name(table_name)}.#{connection.quote_column_name(column_name)}"
          end
154
        end
155 156

        column_name
157
      end
158

159 160
      if has_include?(column_names.first)
        construct_relation_for_association_calculations.pluck(*column_names)
161
      else
162 163 164
        relation = spawn
        relation.select_values = column_names
        result = klass.connection.select_all(relation.arel, nil, bind_values)
165
        columns = result.columns.map do |key|
166 167 168 169
          klass.column_types.fetch(key) {
            result.column_types.fetch(key) {
              Class.new { def type_cast(v); v; end }.new
            }
170
          }
171
        end
172

173 174
        result = result.map do |attributes|
          values = klass.initialize_attributes(attributes).values
175

176 177
          columns.zip(values).map do |column, value|
            column.type_cast(value)
178
          end
179
        end
180
        columns.one? ? result.map!(&:first) : result
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 195 196 197
    def has_include?(column_name)
      eager_loading? || (includes_values.present? && (column_name || references_eager_loaded_tables?))
    end

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

201
      # If #count is used with #distinct / #uniq it is considered distinct. (eg. relation.distinct.count)
202 203 204 205 206 207
      distinct = self.distinct_value
      if options.has_key?(:distinct)
        ActiveSupport::Deprecation.warn "The :distinct option for `Relation#count` is deprecated. " \
          "Please use `Relation#distinct` instead. (eg. `relation.distinct.count`)"
        distinct = options[:distinct]
      end
208

209
      if operation == "count"
210 211
        column_name ||= (select_for_count || :all)

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

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
242
      relation = reorder(nil)
243

244 245
      column_alias = column_name

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

250 251 252
        query_builder = build_count_subquery(relation, column_name, distinct)
      else
        column = aggregate_column(column_name)
253

254
        select_value = operation_over_aggregate_column(column, operation, distinct)
255

256
        column_alias = select_value.alias
257 258 259
        relation.select_values = [select_value]

        query_builder = relation.arel
260 261
      end

A
Aaron Patterson 已提交
262
      result = @klass.connection.select_all(query_builder, nil, relation.bind_values)
263 264 265 266 267 268 269
      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)
270 271
    end

272
    def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
273 274 275
      group_attrs = group_values

      if group_attrs.first.respond_to?(:to_sym)
276 277 278
        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)
279 280 281 282
      else
        group_fields = group_attrs
      end

A
Aaron Patterson 已提交
283 284 285
      group_aliases = group_fields.map { |field|
        column_alias_for(field)
      }
A
Aaron Patterson 已提交
286
      group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
287
        [aliaz, field]
A
Aaron Patterson 已提交
288
      }
289

290
      group = group_fields
291

292 293
      if operation == 'count' && column_name == :all
        aggregate_alias = 'count_all'
294
      else
A
Aaron Patterson 已提交
295
        aggregate_alias = column_alias_for([operation, column_name].join(' '))
296 297
      end

A
Aaron Patterson 已提交
298 299 300 301 302 303
      select_values = [
        operation_over_aggregate_column(
          aggregate_column(column_name),
          operation,
          distinct).as(aggregate_alias)
      ]
304
      select_values += select_values unless having_values.empty?
A
Aaron Patterson 已提交
305 306

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

A
Aaron Patterson 已提交
314 315
      relation = except(:group)
      relation.group_values  = group
A
Aaron Patterson 已提交
316
      relation.select_values = select_values
317

318
      calculated_data = @klass.connection.select_all(relation, nil, bind_values)
319 320

      if association
321
        key_ids     = calculated_data.collect { |row| row[group_aliases.first] }
322
        key_records = association.klass.base_class.find(key_ids)
323
        key_records = Hash[key_records.map { |r| [r.id, r] }]
324 325
      end

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

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

352
      table_name = keys.to_s.downcase
353 354 355 356 357 358 359 360 361
      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)
362
      field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
363
      @klass.columns_hash[field_name]
364 365 366
    end

    def type_cast_calculated_value(value, column, operation = nil)
367 368
      case operation
        when 'count'   then value.to_i
369
        when 'sum'     then type_cast_using_column(value || 0, column)
370
        when 'average' then value.respond_to?(:to_d) ? value.to_d : value
371
        else type_cast_using_column(value, column)
372 373 374 375 376 377 378
      end
    end

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

P
Pratik Naik 已提交
379
    def select_for_count
380 381
      if select_values.present?
        select = select_values.join(", ")
382
        select if select !~ /[,*]/
P
Pratik Naik 已提交
383 384
      end
    end
385 386

    def build_count_subquery(relation, column_name, distinct)
387 388 389 390 391 392 393 394 395 396
      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)
397
    end
398 399
  end
end