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
    def sum(column_name = nil, &block)
      return super &block if block_given?
      calculate(:sum, column_name)
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)
110
      if column_name.is_a?(Symbol) && attribute_alias?(column_name)
111
        column_name = attribute_alias(column_name)
112 113
      end

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

121 122
    # 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 已提交
123 124 125 126 127 128 129 130
    #
    #   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 已提交
131
    # the plucked column names, if they can be deduced. Plucking an SQL fragment
J
Jeremy Kemper 已提交
132
    # returns String values by default.
133
    #
134 135 136
    #   Person.pluck(:name)
    #   # SELECT people.name FROM people
    #   # => ['David', 'Jeremy', 'Jose']
J
Jeremy Kemper 已提交
137
    #
138 139
    #   Person.pluck(:id, :name)
    #   # SELECT people.id, people.name FROM people
140
    #   # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
141
    #
J
Jon Atack 已提交
142
    #   Person.distinct.pluck(:role)
J
Jeremy Kemper 已提交
143 144 145
    #   # SELECT DISTINCT role FROM people
    #   # => ['admin', 'member', 'guest']
    #
A
AvnerCohen 已提交
146
    #   Person.where(age: 21).limit(5).pluck(:id)
J
Jeremy Kemper 已提交
147 148 149 150 151 152
    #   # 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']
153
    #
154 155
    # See also +ids+.
    #
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 167 168
      if loaded? && (column_names - @klass.column_names).empty?
        return @records.pluck(*column_names)
      end

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

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

189 190
    private

191
    def has_include?(column_name)
192
      eager_loading? || (includes_values.present? && column_name && column_name != :all)
193 194
    end

195
    def perform_calculation(operation, column_name)
196 197
      operation = operation.to_s.downcase

J
Jon Atack 已提交
198 199
      # If #count is used with #distinct (i.e. `relation.distinct.count`) it is
      # considered distinct.
200
      distinct = self.distinct_value
201

202
      if operation == "count"
203
        column_name ||= select_for_count
204

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

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

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

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

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

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

236 237
      column_alias = column_name

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

242 243 244
        query_builder = build_count_subquery(relation, column_name, distinct)
      else
        column = aggregate_column(column_name)
245

246
        select_value = operation_over_aggregate_column(column, operation, distinct)
247

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

        query_builder = relation.arel
253 254
      end

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

      type_cast_calculated_value(value, column, operation)
263 264
    end

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

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

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

283
      group = group_fields
284

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

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

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

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

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

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

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

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

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

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

      @klass.connection.table_alias_for(table_name)
    end

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

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

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

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

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