Permalink
Browse files

mysql does not return alias names, so fall back

  • Loading branch information...
1 parent 8a130ec commit 8faf2b3d49cadd28509447edb0452dd7bfecbe5c @tenderlove tenderlove committed Dec 29, 2012
Showing with 10 additions and 4 deletions.
  1. +10 −4 activerecord/lib/active_record/relation/calculations.rb
@@ -231,6 +231,8 @@ def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
# Postgresql doesn't like ORDER BY when there are no GROUP BY
relation = reorder(nil)
+ column_alias = column_name
+
if operation == "count" && (relation.limit_value || relation.offset_value)
# Shortcut when limit is zero.
return 0 if relation.limit_value == 0
@@ -241,16 +243,20 @@ def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
select_value = operation_over_aggregate_column(column, operation, distinct)
- column_name = select_value.alias
+ column_alias = select_value.alias
relation.select_values = [select_value]
query_builder = relation.arel
end
result = @klass.connection.select_all(query_builder, nil, relation.bind_values)
- row = result.first
- value = row && row.values.first
- type_cast_calculated_value(value, result.column_types[column_name], operation)
+ 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)
end
def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:

2 comments on commit 8faf2b3

@tapn2it

looks like this commit has broken Model.count, running postgresql 9.2.2 with rails-3755a496d7cb

19] pry(main)> User.count
PK and serial sequence (2.0ms) SELECT attr.attname, seq.relname
FROM pg_class seq,
pg_attribute attr,
pg_depend dep,
pg_namespace name,
pg_constraint cons
WHERE seq.oid = dep.objid
AND seq.relkind = 'S'
AND attr.attrelid = dep.refobjid
AND attr.attnum = dep.refobjsubid
AND attr.attrelid = cons.conrelid
AND attr.attnum = cons.conkey[1]
AND cons.contype = 'p'
AND dep.refobjid = '"users"'::regclass

(1.0ms) SELECT COUNT(*) FROM "users"
NoMethodError: undefined method column_types' for [{"count"=>8}]:Array from /Users/tapn2it/.rbenv/versions/jruby-1.7.1/gemsets/stella2/jruby/1.9/bundler/gems/rails-3755a496d7cb/activerecord/lib/active_record/relation/calculations.rb:255:inexecute_simple_calculation'

@maxmmurphy

Bump!

Please sign in to comment.