Permalink
Browse files

MySQL returns "SUM(DISTINCT(credit_limit))" as the column name unless

an alias is provided.  Without the alias, the column cannot be found
and properly typecast.
  • Loading branch information...
1 parent bf0212b commit 2a38fd58a91a300da5acfe917e82ac681dbd5b50 @tenderlove tenderlove committed May 16, 2012
@@ -140,19 +140,26 @@ def calculate(operation, column_name, options = {})
# # => ['0', '27761', '173']
#
def pluck(column_name)
- key = column_name.to_s.split('.', 2).last
-
if column_name.is_a?(Symbol) && column_names.include?(column_name.to_s)
column_name = "#{table_name}.#{column_name}"
end
result = klass.connection.select_all(select(column_name).arel, nil, bind_values)
- column = klass.column_types[key] || result.column_types.values.first
+
+ key = column = nil
+ nullcast = Class.new { def type_cast(v); v; end }.new
result.map do |attributes|
raise ArgumentError, "Pluck expects to select just one attribute: #{attributes.inspect}" unless attributes.one?
+
value = klass.initialize_attributes(attributes).values.first
- column ? column.type_cast(value) : value
+
+ key ||= attributes.keys.first
+ column ||= klass.column_types.fetch(key) {
+ result.column_types.fetch(key, nullcast)
+ }
+
+ column.type_cast(value)
end
end
@@ -470,7 +470,11 @@ def test_pluck_with_selection_clause
assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT credit_limit').sort
assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT accounts.credit_limit').sort
assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT(credit_limit)').sort
- assert_equal [50 + 53 + 55 + 60], Account.pluck('SUM(DISTINCT(credit_limit))')
+
+ # MySQL returns "SUM(DISTINCT(credit_limit))" as the column name unless
+ # an alias is provided. Without the alias, the column cannot be found
+ # and properly typecast.
+ assert_equal [50 + 53 + 55 + 60], Account.pluck('SUM(DISTINCT(credit_limit)) as credit_limit')
end
def test_pluck_expects_a_single_selection

0 comments on commit 2a38fd5

Please sign in to comment.