calculations.rb 13.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 }
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
    def sum(*args)
74
      calculate(:sum, *args)
75 76
    end

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

113
      if has_include?(column_name)
114
        construct_relation_for_association_calculations.calculate(operation, column_name)
115
      else
116
        perform_calculation(operation, column_name)
117 118 119
      end
    end

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

164 165
      if has_include?(column_names.first)
        construct_relation_for_association_calculations.pluck(*column_names)
166
      else
167
        relation = spawn
168
        relation.select_values = column_names.map { |cn|
169
          columns_hash.key?(cn) ? arel_table[cn] : cn
170
        }
S
Sean Griffin 已提交
171
        result = klass.connection.select_all(relation.arel, nil, bound_attributes)
172
        result.cast_values(klass.attribute_types)
173 174 175
      end
    end

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

184 185
    private

186
    def has_include?(column_name)
187
      eager_loading? || (includes_values.present? && column_name && column_name != :all)
188 189
    end

190
    def perform_calculation(operation, column_name)
191 192
      operation = operation.to_s.downcase

193
      # If #count is used with #distinct / #uniq it is considered distinct. (eg. relation.distinct.count)
194
      distinct = self.distinct_value
195

196
      if operation == "count"
197
        column_name ||= select_for_count
198

199
        unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
200 201
          distinct = true
        end
202

203
        column_name = primary_key if column_name == :all && distinct
204
        distinct = nil if column_name =~ /\s*DISTINCT[\s(]+/i
205 206
      end

207
      if group_values.any?
208
        execute_grouped_calculation(operation, column_name, distinct)
209
      else
N
Neeraj Singh 已提交
210
        execute_simple_calculation(operation, column_name, distinct)
211
      end
P
Pratik Naik 已提交
212 213
    end

214
    def aggregate_column(column_name)
215
      if @klass.column_names.include?(column_name.to_s)
216
        Arel::Attribute.new(@klass.unscoped.table, column_name)
217
      else
218
        Arel.sql(column_name == :all ? "*" : column_name.to_s)
219
      end
220 221
    end

222 223 224 225
    def operation_over_aggregate_column(column, operation, distinct)
      operation == 'count' ? column.count(distinct) : column.send(operation)
    end

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

230 231
      column_alias = column_name

232 233 234
      if operation == "count" && (relation.limit_value || relation.offset_value)
        # Shortcut when limit is zero.
        return 0 if relation.limit_value == 0
235

236 237 238
        query_builder = build_count_subquery(relation, column_name, distinct)
      else
        column = aggregate_column(column_name)
239

240
        select_value = operation_over_aggregate_column(column, operation, distinct)
241

242 243
        column_alias = select_value.alias
        column_alias ||= @klass.connection.column_name_for_operation(operation, select_value)
244 245 246
        relation.select_values = [select_value]

        query_builder = relation.arel
247 248
      end

S
Sean Griffin 已提交
249
      result = @klass.connection.select_all(query_builder, nil, bound_attributes)
250 251 252
      row    = result.first
      value  = row && row.values.first
      column = result.column_types.fetch(column_alias) do
253
        type_for(column_name)
254 255 256
      end

      type_cast_calculated_value(value, column, operation)
257 258
    end

259
    def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
260 261 262
      group_attrs = group_values

      if group_attrs.first.respond_to?(:to_sym)
G
Godfrey Chan 已提交
263
        association  = @klass._reflect_on_association(group_attrs.first)
E
eileencodes 已提交
264
        associated   = group_attrs.size == 1 && association && association.belongs_to? # only count belongs_to associations
265
        group_fields = Array(associated ? association.foreign_key : group_attrs)
266 267 268 269
      else
        group_fields = group_attrs
      end

A
Aaron Patterson 已提交
270 271 272
      group_aliases = group_fields.map { |field|
        column_alias_for(field)
      }
A
Aaron Patterson 已提交
273
      group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
274
        [aliaz, field]
A
Aaron Patterson 已提交
275
      }
276

277
      group = group_fields
278

279 280
      if operation == 'count' && column_name == :all
        aggregate_alias = 'count_all'
281
      else
A
Aaron Patterson 已提交
282
        aggregate_alias = column_alias_for([operation, column_name].join(' '))
283 284
      end

A
Aaron Patterson 已提交
285 286 287 288 289 290
      select_values = [
        operation_over_aggregate_column(
          aggregate_column(column_name),
          operation,
          distinct).as(aggregate_alias)
      ]
291
      select_values += select_values unless having_clause.empty?
A
Aaron Patterson 已提交
292 293

      select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
294 295 296 297 298
        if field.respond_to?(:as)
          field.as(aliaz)
        else
          "#{field} AS #{aliaz}"
        end
A
Aaron Patterson 已提交
299 300
      }

A
Aaron Patterson 已提交
301 302
      relation = except(:group)
      relation.group_values  = group
A
Aaron Patterson 已提交
303
      relation.select_values = select_values
304

S
Sean Griffin 已提交
305
      calculated_data = @klass.connection.select_all(relation, nil, relation.bound_attributes)
306 307

      if association
308
        key_ids     = calculated_data.collect { |row| row[group_aliases.first] }
309
        key_records = association.klass.base_class.where(association.klass.base_class.primary_key => key_ids)
310
        key_records = Hash[key_records.map { |r| [r.id, r] }]
311 312
      end

R
Raghunadh 已提交
313
      Hash[calculated_data.map do |row|
314
        key = group_columns.map { |aliaz, col_name|
315
          column = calculated_data.column_types.fetch(aliaz) do
316
            type_for(col_name)
317
          end
A
Aaron Patterson 已提交
318 319
          type_cast_calculated_value(row[aliaz], column)
        }
320
        key = key.first if key.size == 1
E
Emilio Tagua 已提交
321
        key = key_records[key] if associated
322

323
        column_type = calculated_data.column_types.fetch(aggregate_alias) { type_for(column_name) }
324
        [key, type_cast_calculated_value(row[aggregate_alias], column_type, operation)]
E
Emilio Tagua 已提交
325
      end]
326
    end
327

328 329 330 331 332 333 334 335
    # 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"
336
    def column_alias_for(keys)
337 338 339 340
      if keys.respond_to? :name
        keys = "#{keys.relation.name}.#{keys.name}"
      end

341
      table_name = keys.to_s.downcase
342 343 344 345 346 347 348 349
      table_name.gsub!(/\*/, 'all')
      table_name.gsub!(/\W+/, ' ')
      table_name.strip!
      table_name.gsub!(/ +/, '_')

      @klass.connection.table_alias_for(table_name)
    end

350
    def type_for(field)
351
      field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
352
      @klass.type_for_attribute(field_name)
353 354
    end

355
    def type_cast_calculated_value(value, type, operation = nil)
356 357
      case operation
        when 'count'   then value.to_i
358
        when 'sum'     then type.deserialize(value || 0)
359
        when 'average' then value.respond_to?(:to_d) ? value.to_d : value
360
        else type.deserialize(value)
361 362 363
      end
    end

364 365 366 367 368 369 370 371 372
    # 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

373
    def build_count_subquery(relation, column_name, distinct)
374 375 376 377 378
      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]
379
      subquery = relation.arel.as(subquery_alias)
380 381 382 383

      sm = Arel::SelectManager.new relation.engine
      select_value = operation_over_aggregate_column(column_alias, 'count', distinct)
      sm.project(select_value).from(subquery)
384
    end
385 386
  end
end