activerecord 3.2.13 → 3.2.14.rc1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of activerecord might be problematic. Click here for more details.

Files changed (37) hide show
  1. data/CHANGELOG.md +148 -2
  2. data/lib/active_record/associations/association.rb +9 -3
  3. data/lib/active_record/associations/belongs_to_association.rb +1 -1
  4. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +2 -1
  5. data/lib/active_record/associations/builder/belongs_to.rb +4 -1
  6. data/lib/active_record/associations/builder/belongs_to.rb.orig +95 -0
  7. data/lib/active_record/associations/collection_association.rb +1 -1
  8. data/lib/active_record/associations/has_many_association.rb +1 -2
  9. data/lib/active_record/associations/has_many_association.rb.orig +116 -0
  10. data/lib/active_record/associations/join_dependency.rb +1 -1
  11. data/lib/active_record/associations/join_dependency/join_association.rb +6 -1
  12. data/lib/active_record/associations/preloader/through_association.rb +1 -2
  13. data/lib/active_record/associations/through_association.rb +1 -1
  14. data/lib/active_record/autosave_association.rb +7 -12
  15. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +2 -2
  16. data/lib/active_record/connection_adapters/abstract/schema_statements.rb.orig +619 -0
  17. data/lib/active_record/connection_adapters/connection_specification.rb.orig +124 -0
  18. data/lib/active_record/connection_adapters/mysql2_adapter.rb +5 -3
  19. data/lib/active_record/connection_adapters/postgresql/cast.rb.orig +136 -0
  20. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb.orig +485 -0
  21. data/lib/active_record/connection_adapters/postgresql_adapter.rb +9 -3
  22. data/lib/active_record/core.rb.orig +452 -0
  23. data/lib/active_record/explain_subscriber.rb +1 -1
  24. data/lib/active_record/model_schema.rb +4 -2
  25. data/lib/active_record/nested_attributes.rb +41 -17
  26. data/lib/active_record/railtie.rb +6 -7
  27. data/lib/active_record/railties/databases.rake +2 -1
  28. data/lib/active_record/relation/calculations.rb +5 -6
  29. data/lib/active_record/relation/calculations.rb.orig +378 -0
  30. data/lib/active_record/relation/finder_methods.rb +1 -0
  31. data/lib/active_record/relation/finder_methods.rb.orig +405 -0
  32. data/lib/active_record/relation/spawn_methods.rb +34 -3
  33. data/lib/active_record/store.rb +1 -1
  34. data/lib/active_record/version.rb +2 -2
  35. data/lib/rails/generators/active_record/observer/observer_generator.rb.orig +15 -0
  36. metadata +117 -70
  37. checksums.yaml +0 -7
@@ -15,7 +15,7 @@ module ActiveRecord
15
15
  # On the other hand, we want to monitor the performance of our real database
16
16
  # queries, not the performance of the access to the query cache.
17
17
  IGNORED_PAYLOADS = %w(SCHEMA EXPLAIN CACHE)
18
- EXPLAINED_SQLS = /\A\s*(select|update|delete|insert)/i
18
+ EXPLAINED_SQLS = /\A\s*(select|update|delete|insert)\b/i
19
19
  def ignore_payload?(payload)
20
20
  payload[:exception] || IGNORED_PAYLOADS.include?(payload[:name]) || payload[:sql] !~ EXPLAINED_SQLS
21
21
  end
@@ -159,7 +159,7 @@ module ActiveRecord
159
159
  # The name of the column containing the object's class when Single Table Inheritance is used
160
160
  def inheritance_column
161
161
  if self == Base
162
- 'type'
162
+ (@inheritance_column ||= nil) || 'type'
163
163
  else
164
164
  (@inheritance_column ||= nil) || superclass.inheritance_column
165
165
  end
@@ -173,6 +173,7 @@ module ActiveRecord
173
173
  def inheritance_column=(value)
174
174
  @original_inheritance_column = inheritance_column
175
175
  @inheritance_column = value.to_s
176
+ @explicit_inheritance_column = true
176
177
  end
177
178
 
178
179
  def set_inheritance_column(value = nil, &block) #:nodoc:
@@ -300,7 +301,8 @@ module ActiveRecord
300
301
  connection.schema_cache.clear_table_cache!(table_name) if table_exists?
301
302
 
302
303
  @column_names = @content_columns = @column_defaults = @columns = @columns_hash = nil
303
- @dynamic_methods_hash = @inheritance_column = nil
304
+ @dynamic_methods_hash = nil
305
+ @inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
304
306
  @arel_engine = @relation = nil
305
307
  end
306
308
 
@@ -92,8 +92,9 @@ module ActiveRecord
92
92
  # accepts_nested_attributes_for :posts
93
93
  # end
94
94
  #
95
- # You can now set or update attributes on an associated post model through
96
- # the attribute hash.
95
+ # You can now set or update attributes on the associated posts through
96
+ # an attribute hash for a member: include the key +:posts_attributes+
97
+ # with an array of hashes of post attributes as a value.
97
98
  #
98
99
  # For each hash that does _not_ have an <tt>id</tt> key a new record will
99
100
  # be instantiated, unless the hash also contains a <tt>_destroy</tt> key
@@ -116,10 +117,10 @@ module ActiveRecord
116
117
  # hashes if they fail to pass your criteria. For example, the previous
117
118
  # example could be rewritten as:
118
119
  #
119
- # class Member < ActiveRecord::Base
120
- # has_many :posts
121
- # accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
122
- # end
120
+ # class Member < ActiveRecord::Base
121
+ # has_many :posts
122
+ # accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
123
+ # end
123
124
  #
124
125
  # params = { :member => {
125
126
  # :name => 'joe', :posts_attributes => [
@@ -136,19 +137,19 @@ module ActiveRecord
136
137
  #
137
138
  # Alternatively, :reject_if also accepts a symbol for using methods:
138
139
  #
139
- # class Member < ActiveRecord::Base
140
- # has_many :posts
141
- # accepts_nested_attributes_for :posts, :reject_if => :new_record?
142
- # end
140
+ # class Member < ActiveRecord::Base
141
+ # has_many :posts
142
+ # accepts_nested_attributes_for :posts, :reject_if => :new_record?
143
+ # end
143
144
  #
144
- # class Member < ActiveRecord::Base
145
- # has_many :posts
146
- # accepts_nested_attributes_for :posts, :reject_if => :reject_posts
145
+ # class Member < ActiveRecord::Base
146
+ # has_many :posts
147
+ # accepts_nested_attributes_for :posts, :reject_if => :reject_posts
147
148
  #
148
- # def reject_posts(attributed)
149
- # attributed['title'].blank?
150
- # end
151
- # end
149
+ # def reject_posts(attributed)
150
+ # attributed['title'].blank?
151
+ # end
152
+ # end
152
153
  #
153
154
  # If the hash contains an <tt>id</tt> key that matches an already
154
155
  # associated record, the matching record will be modified:
@@ -185,6 +186,29 @@ module ActiveRecord
185
186
  # member.save
186
187
  # member.reload.posts.length # => 1
187
188
  #
189
+ # Nested attributes for an associated collection can also be passed in
190
+ # the form of a hash of hashes instead of an array of hashes:
191
+ #
192
+ # Member.create(:name => 'joe',
193
+ # :posts_attributes => { :first => { :title => 'Foo' },
194
+ # :second => { :title => 'Bar' } })
195
+ #
196
+ # has the same effect as
197
+ #
198
+ # Member.create(:name => 'joe',
199
+ # :posts_attributes => [ { :title => 'Foo' },
200
+ # { :title => 'Bar' } ])
201
+ #
202
+ # The keys of the hash which is the value for +:posts_attributes+ are
203
+ # ignored in this case.
204
+ # However, it is not allowed to use +'id'+ or +:id+ for one of
205
+ # such keys, otherwise the hash will be wrapped in an array and
206
+ # interpreted as an attribute hash for a single post.
207
+ #
208
+ # Passing attributes for an associated collection in the form of a hash
209
+ # of hashes can be used with hashes generated from HTTP/HTML parameters,
210
+ # where there maybe no natural way to submit an array of hashes.
211
+ #
188
212
  # === Saving
189
213
  #
190
214
  # All changes to models, including the destruction of those marked for
@@ -30,6 +30,7 @@ module ActiveRecord
30
30
  )
31
31
 
32
32
  rake_tasks do
33
+ require "active_record/base"
33
34
  load "active_record/railties/databases.rake"
34
35
  end
35
36
 
@@ -38,9 +39,14 @@ module ActiveRecord
38
39
  # first time. Also, make it output to STDERR.
39
40
  console do |app|
40
41
  require "active_record/railties/console_sandbox" if app.sandbox?
42
+ require "active_record/base"
41
43
  ActiveRecord::Base.logger = Logger.new(STDERR)
42
44
  end
43
45
 
46
+ runner do |app|
47
+ require "active_record/base"
48
+ end
49
+
44
50
  initializer "active_record.initialize_timezone" do
45
51
  ActiveSupport.on_load(:active_record) do
46
52
  self.time_zone_aware_attributes = true
@@ -83,13 +89,6 @@ module ActiveRecord
83
89
  end
84
90
  end
85
91
 
86
- initializer "active_record.validate_explain_support" do |app|
87
- if app.config.active_record[:auto_explain_threshold_in_seconds] &&
88
- !ActiveRecord::Base.connection.supports_explain?
89
- warn "auto_explain_threshold_in_seconds is set but will be ignored because your adapter does not support this feature. Please unset the configuration to avoid this warning."
90
- end
91
- end
92
-
93
92
  # Expose database runtime to controller for logging.
94
93
  initializer "active_record.log_runtime" do |app|
95
94
  require "active_record/railties/controller_runtime"
@@ -355,7 +355,7 @@ db_namespace = namespace :db do
355
355
  base_dir = File.join [Rails.root, ENV['FIXTURES_PATH'] || %w{test fixtures}].flatten
356
356
  fixtures_dir = File.join [base_dir, ENV['FIXTURES_DIR']].compact
357
357
 
358
- (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir["#{fixtures_dir}/**/*.{yml,csv}"].map {|f| f[(fixtures_dir.size + 1)..-5] }).each do |fixture_file|
358
+ (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir["#{fixtures_dir}/**/*.yml"].map {|f| f[(fixtures_dir.size + 1)..-5] }).each do |fixture_file|
359
359
  ActiveRecord::Fixtures.create_fixtures(fixtures_dir, fixture_file)
360
360
  end
361
361
  end
@@ -427,6 +427,7 @@ db_namespace = namespace :db do
427
427
  end
428
428
  `pg_dump -i -s -x -O -f #{Shellwords.escape(filename)} #{search_path} #{Shellwords.escape(config['database'])}`
429
429
  raise 'Error dumping database' if $?.exitstatus == 1
430
+ File.open(filename, "a") { |f| f << "SET search_path TO #{ActiveRecord::Base.connection.schema_search_path};\n\n" }
430
431
  when /sqlite/
431
432
  dbfile = config['database']
432
433
  `sqlite3 #{dbfile} .schema > #{filename}`
@@ -179,14 +179,13 @@ module ActiveRecord
179
179
  def pluck(column_name)
180
180
  if column_name.is_a?(Symbol) && column_names.include?(column_name.to_s)
181
181
  column_name = "#{connection.quote_table_name(table_name)}.#{connection.quote_column_name(column_name)}"
182
- else
183
- column_name = column_name.to_s
184
182
  end
185
183
 
186
- relation = clone
187
- relation.select_values = [column_name]
188
- klass.connection.select_all(relation.arel).map! do |attributes|
189
- klass.type_cast_attribute(attributes.keys.first, klass.initialize_attributes(attributes))
184
+ result = klass.connection.exec_query(select(column_name).to_sql)
185
+ last_column = result.columns.last
186
+
187
+ result.map do |attributes|
188
+ klass.type_cast_attribute(last_column, klass.initialize_attributes(attributes))
190
189
  end
191
190
  end
192
191
 
@@ -0,0 +1,378 @@
1
+ require 'active_support/core_ext/object/blank'
2
+ require 'active_support/core_ext/object/try'
3
+
4
+ module ActiveRecord
5
+ module Calculations
6
+ # Count operates using three different approaches.
7
+ #
8
+ # * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
9
+ # * Count using column: By passing a column name to count, it will return a count of all the
10
+ # rows for the model with supplied column present.
11
+ # * Count using options will find the row count matched by the options used.
12
+ #
13
+ # The third approach, count using options, accepts an option hash as the only parameter. The options are:
14
+ #
15
+ # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
16
+ # See conditions in the intro to ActiveRecord::Base.
17
+ # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id"
18
+ # (rarely needed) or named associations in the same form used for the <tt>:include</tt> option, which will
19
+ # perform an INNER JOIN on the associated table(s). If the value is a string, then the records
20
+ # will be returned read-only since they will have attributes that do not correspond to the table's columns.
21
+ # Pass <tt>:readonly => false</tt> to override.
22
+ # * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs.
23
+ # The symbols named refer to already defined associations. When using named associations, count
24
+ # returns the number of DISTINCT items for the model you're counting.
25
+ # See eager loading under Associations.
26
+ # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
27
+ # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
28
+ # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example,
29
+ # want to do a join but not include the joined columns.
30
+ # * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as
31
+ # SELECT COUNT(DISTINCT posts.id) ...
32
+ # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an
33
+ # alternate table name (or even the name of a database view).
34
+ #
35
+ # Examples for counting all:
36
+ # Person.count # returns the total count of all people
37
+ #
38
+ # Examples for counting by column:
39
+ # Person.count(:age) # returns the total count of all people whose age is present in database
40
+ #
41
+ # Examples for count with options:
42
+ # Person.count(:conditions => "age > 26")
43
+ #
44
+ # # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
45
+ # Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job)
46
+ #
47
+ # # finds the number of rows matching the conditions and joins.
48
+ # Person.count(:conditions => "age > 26 AND job.salary > 60000",
49
+ # :joins => "LEFT JOIN jobs on jobs.person_id = person.id")
50
+ #
51
+ # Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
52
+ # Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
53
+ #
54
+ # Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition.
55
+ # Use Person.count instead.
56
+ def count(column_name = nil, options = {})
57
+ column_name, options = nil, column_name if column_name.is_a?(Hash)
58
+ calculate(:count, column_name, options)
59
+ end
60
+
61
+ # Calculates the average value on a given column. Returns +nil+ if there's
62
+ # no row. See +calculate+ for examples with options.
63
+ #
64
+ # Person.average('age') # => 35.8
65
+ def average(column_name, options = {})
66
+ calculate(:average, column_name, options)
67
+ end
68
+
69
+ # Calculates the minimum value on a given column. The value is returned
70
+ # with the same data type of the column, or +nil+ if there's no row. See
71
+ # +calculate+ for examples with options.
72
+ #
73
+ # Person.minimum('age') # => 7
74
+ def minimum(column_name, options = {})
75
+ calculate(:minimum, column_name, options)
76
+ end
77
+
78
+ # Calculates the maximum value on a given column. The value is returned
79
+ # with the same data type of the column, or +nil+ if there's no row. See
80
+ # +calculate+ for examples with options.
81
+ #
82
+ # Person.maximum('age') # => 93
83
+ def maximum(column_name, options = {})
84
+ calculate(:maximum, column_name, options)
85
+ end
86
+
87
+ # Calculates the sum of values on a given column. The value is returned
88
+ # with the same data type of the column, 0 if there's no row. See
89
+ # +calculate+ for examples with options.
90
+ #
91
+ # Person.sum('age') # => 4562
92
+ def sum(*args)
93
+ if block_given?
94
+ self.to_a.sum(*args) {|*block_args| yield(*block_args)}
95
+ else
96
+ calculate(:sum, *args)
97
+ end
98
+ end
99
+
100
+ # This calculates aggregate values in the given column. Methods for count, sum, average,
101
+ # minimum, and maximum have been added as shortcuts. Options such as <tt>:conditions</tt>,
102
+ # <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
103
+ #
104
+ # There are two basic forms of output:
105
+ # * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
106
+ # for AVG, and the given column's type for everything else.
107
+ # * Grouped values: This returns an ordered hash of the values and groups them by the
108
+ # <tt>:group</tt> option. It takes either a column name, or the name of a belongs_to association.
109
+ #
110
+ # values = Person.maximum(:age, :group => 'last_name')
111
+ # puts values["Drake"]
112
+ # => 43
113
+ #
114
+ # drake = Family.find_by_last_name('Drake')
115
+ # values = Person.maximum(:age, :group => :family) # Person belongs_to :family
116
+ # puts values[drake]
117
+ # => 43
118
+ #
119
+ # values.each do |family, max_age|
120
+ # ...
121
+ # end
122
+ #
123
+ # Options:
124
+ # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
125
+ # See conditions in the intro to ActiveRecord::Base.
126
+ # * <tt>:include</tt>: Eager loading, see Associations for details. Since calculations don't load anything,
127
+ # the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.
128
+ # * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id".
129
+ # (Rarely needed).
130
+ # The records will be returned read-only since they will have attributes that do not correspond to the
131
+ # table's columns.
132
+ # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
133
+ # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
134
+ # * <tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be changed if you for example
135
+ # want to do a join, but not include the joined columns.
136
+ # * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as
137
+ # SELECT COUNT(DISTINCT posts.id) ...
138
+ #
139
+ # Examples:
140
+ # Person.calculate(:count, :all) # The same as Person.count
141
+ # Person.average(:age) # SELECT AVG(age) FROM people...
142
+ # Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for
143
+ # # everyone with a last name other than 'Drake'
144
+ #
145
+ # # Selects the minimum age for any family without any minors
146
+ # Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name)
147
+ #
148
+ # Person.sum("2 * age")
149
+ def calculate(operation, column_name, options = {})
150
+ if options.except(:distinct).present?
151
+ apply_finder_options(options.except(:distinct)).calculate(operation, column_name, :distinct => options[:distinct])
152
+ else
153
+ relation = with_default_scope
154
+
155
+ if relation.equal?(self)
156
+ if eager_loading? || (includes_values.present? && references_eager_loaded_tables?)
157
+ construct_relation_for_association_calculations.calculate(operation, column_name, options)
158
+ else
159
+ perform_calculation(operation, column_name, options)
160
+ end
161
+ else
162
+ relation.calculate(operation, column_name, options)
163
+ end
164
+ end
165
+ rescue ThrowResult
166
+ 0
167
+ end
168
+
169
+ # This method is designed to perform select by a single column as direct SQL query
170
+ # Returns <tt>Array</tt> with values of the specified column name
171
+ # The values has same data type as column.
172
+ #
173
+ # Examples:
174
+ #
175
+ # Person.pluck(:id) # SELECT people.id FROM people
176
+ # Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
177
+ # Person.where(:confirmed => true).limit(5).pluck(:id)
178
+ #
179
+ def pluck(column_name)
180
+ <<<<<<< HEAD
181
+ if column_name.is_a?(Symbol) && column_names.include?(column_name.to_s)
182
+ column_name = "#{connection.quote_table_name(table_name)}.#{connection.quote_column_name(column_name)}"
183
+ else
184
+ column_name = column_name.to_s
185
+ end
186
+
187
+ relation = clone
188
+ relation.select_values = [column_name]
189
+ klass.connection.select_all(relation.arel).map! do |attributes|
190
+ =======
191
+ column_name = column_name.to_s
192
+ klass.connection.select_all(select(column_name).arel).map! do |attributes|
193
+ >>>>>>> parent of 7240202... Merge pull request #8209 from senny/backport_8176
194
+ klass.type_cast_attribute(attributes.keys.first, klass.initialize_attributes(attributes))
195
+ end
196
+ end
197
+
198
+ private
199
+
200
+ def perform_calculation(operation, column_name, options = {})
201
+ operation = operation.to_s.downcase
202
+
203
+ # If #count is used in conjuction with #uniq it is considered distinct. (eg. relation.uniq.count)
204
+ distinct = options[:distinct] || self.uniq_value
205
+
206
+ if operation == "count"
207
+ column_name ||= (select_for_count || :all)
208
+
209
+ unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
210
+ distinct = true
211
+ end
212
+
213
+ column_name = primary_key if column_name == :all && distinct
214
+
215
+ distinct = nil if column_name =~ /\s*DISTINCT\s+/i
216
+ end
217
+
218
+ if @group_values.any?
219
+ execute_grouped_calculation(operation, column_name, distinct)
220
+ else
221
+ execute_simple_calculation(operation, column_name, distinct)
222
+ end
223
+ end
224
+
225
+ def aggregate_column(column_name)
226
+ if @klass.column_names.include?(column_name.to_s)
227
+ Arel::Attribute.new(@klass.unscoped.table, column_name)
228
+ else
229
+ Arel.sql(column_name == :all ? "*" : column_name.to_s)
230
+ end
231
+ end
232
+
233
+ def operation_over_aggregate_column(column, operation, distinct)
234
+ operation == 'count' ? column.count(distinct) : column.send(operation)
235
+ end
236
+
237
+ def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
238
+ # Postgresql doesn't like ORDER BY when there are no GROUP BY
239
+ relation = reorder(nil)
240
+
241
+ if operation == "count" && (relation.limit_value || relation.offset_value)
242
+ # Shortcut when limit is zero.
243
+ return 0 if relation.limit_value == 0
244
+
245
+ query_builder = build_count_subquery(relation, column_name, distinct)
246
+ else
247
+ column = aggregate_column(column_name)
248
+
249
+ select_value = operation_over_aggregate_column(column, operation, distinct)
250
+
251
+ relation.select_values = [select_value]
252
+
253
+ query_builder = relation.arel
254
+ end
255
+
256
+ type_cast_calculated_value(@klass.connection.select_value(query_builder), column_for(column_name), operation)
257
+ end
258
+
259
+ def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
260
+ group_attrs = @group_values
261
+
262
+ if group_attrs.first.respond_to?(:to_sym)
263
+ association = @klass.reflect_on_association(group_attrs.first.to_sym)
264
+ associated = group_attrs.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
265
+ group_fields = Array(associated ? association.foreign_key : group_attrs)
266
+ else
267
+ group_fields = group_attrs
268
+ end
269
+
270
+ group_aliases = group_fields.map { |field| column_alias_for(field) }
271
+ group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
272
+ [aliaz, column_for(field)]
273
+ }
274
+
275
+ group = @klass.connection.adapter_name == 'FrontBase' ? group_aliases : group_fields
276
+
277
+ if operation == 'count' && column_name == :all
278
+ aggregate_alias = 'count_all'
279
+ else
280
+ aggregate_alias = column_alias_for(operation, column_name)
281
+ end
282
+
283
+ select_values = [
284
+ operation_over_aggregate_column(
285
+ aggregate_column(column_name),
286
+ operation,
287
+ distinct).as(aggregate_alias)
288
+ ]
289
+ select_values += @select_values unless @having_values.empty?
290
+
291
+ select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
292
+ if field.respond_to?(:as)
293
+ field.as(aliaz)
294
+ else
295
+ "#{field} AS #{aliaz}"
296
+ end
297
+ }
298
+
299
+ relation = except(:group).group(group)
300
+ relation.select_values = select_values
301
+
302
+ calculated_data = @klass.connection.select_all(relation)
303
+
304
+ if association
305
+ key_ids = calculated_data.collect { |row| row[group_aliases.first] }
306
+ key_records = association.klass.base_class.find(key_ids)
307
+ key_records = Hash[key_records.map { |r| [r.id, r] }]
308
+ end
309
+
310
+ ActiveSupport::OrderedHash[calculated_data.map do |row|
311
+ key = group_columns.map { |aliaz, column|
312
+ type_cast_calculated_value(row[aliaz], column)
313
+ }
314
+ key = key.first if key.size == 1
315
+ key = key_records[key] if associated
316
+ [key, type_cast_calculated_value(row[aggregate_alias], column_for(column_name), operation)]
317
+ end]
318
+ end
319
+
320
+ # Converts the given keys to the value that the database adapter returns as
321
+ # a usable column name:
322
+ #
323
+ # column_alias_for("users.id") # => "users_id"
324
+ # column_alias_for("sum(id)") # => "sum_id"
325
+ # column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
326
+ # column_alias_for("count(*)") # => "count_all"
327
+ # column_alias_for("count", "id") # => "count_id"
328
+ def column_alias_for(*keys)
329
+ keys.map! {|k| k.respond_to?(:to_sql) ? k.to_sql : k}
330
+ table_name = keys.join(' ')
331
+ table_name.downcase!
332
+ table_name.gsub!(/\*/, 'all')
333
+ table_name.gsub!(/\W+/, ' ')
334
+ table_name.strip!
335
+ table_name.gsub!(/ +/, '_')
336
+
337
+ @klass.connection.table_alias_for(table_name)
338
+ end
339
+
340
+ def column_for(field)
341
+ field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
342
+ @klass.columns.detect { |c| c.name.to_s == field_name }
343
+ end
344
+
345
+ def type_cast_calculated_value(value, column, operation = nil)
346
+ case operation
347
+ when 'count' then value.to_i
348
+ when 'sum' then type_cast_using_column(value || '0', column)
349
+ when 'average' then value.respond_to?(:to_d) ? value.to_d : value
350
+ else type_cast_using_column(value, column)
351
+ end
352
+ end
353
+
354
+ def type_cast_using_column(value, column)
355
+ column ? column.type_cast(value) : value
356
+ end
357
+
358
+ def select_for_count
359
+ if @select_values.present?
360
+ select = @select_values.join(", ")
361
+ select if select !~ /(,|\*)/
362
+ end
363
+ end
364
+
365
+ def build_count_subquery(relation, column_name, distinct)
366
+ column_alias = Arel.sql('count_column')
367
+ subquery_alias = Arel.sql('subquery_for_count')
368
+
369
+ aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias)
370
+ relation.select_values = [aliased_column]
371
+ subquery = relation.arel.as(subquery_alias)
372
+
373
+ sm = Arel::SelectManager.new relation.engine
374
+ select_value = operation_over_aggregate_column(column_alias, 'count', distinct)
375
+ sm.project(select_value).from(subquery)
376
+ end
377
+ end
378
+ end