Skip to content

Commit

Permalink
Merge pull request rails#52015 from maniSHarma7575/51991-pluck-column…
Browse files Browse the repository at this point in the history
…s-should-correctly-casts-types-when-using-postgresql

[FIX] Pluck columns should correctly casts types when using postgresql
  • Loading branch information
tenderlove committed Jun 4, 2024
2 parents f4c39b5 + a35074e commit f008c31
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 17 deletions.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/relation/calculations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -604,7 +604,7 @@ def type_cast_pluck_values(result, columns)
model.attribute_types.fetch(name = result.columns[i]) do
join_dependencies ||= build_join_dependencies
lookup_cast_type_from_join_dependencies(name, join_dependencies) ||
result.column_types[name] || Type.default_value
result.column_types[i] || Type.default_value
end
end
end
Expand Down
27 changes: 11 additions & 16 deletions activerecord/test/cases/calculations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,10 @@ def test_pluck_type_cast
assert_equal [ topic.approved ], relation.pluck(:approved)
assert_equal [ topic.last_read ], relation.pluck(:last_read)
assert_equal [ topic.written_on ], relation.pluck(:written_on)
assert_equal(
[[topic.written_on, topic.replies_count]],
relation.pluck("min(written_on)", "min(replies_count)")
)
end

def test_pluck_type_cast_with_conflict_column_names
Expand Down Expand Up @@ -1224,22 +1228,13 @@ def test_pluck_functions_with_alias
end

def test_pluck_functions_without_alias
expected = if current_adapter?(:PostgreSQLAdapter)
# PostgreSQL returns the same name for each column in the given query, so each column is named "coalesce"
# As a result Rails cannot accurately type cast each value.
# To work around this, you should use aliases in your select statement (see test_pluck_functions_with_alias).
[
["1", "The First Topic"], ["2", "The Second Topic of the day"],
["3", "The Third Topic of the day"], ["4", "The Fourth Topic of the day"],
["5", "The Fifth Topic of the day"]
]
else
[
[1, "The First Topic"], [2, "The Second Topic of the day"],
[3, "The Third Topic of the day"], [4, "The Fourth Topic of the day"],
[5, "The Fifth Topic of the day"]
]
end
expected = [
[1, "The First Topic"],
[2, "The Second Topic of the day"],
[3, "The Third Topic of the day"],
[4, "The Fourth Topic of the day"],
[5, "The Fifth Topic of the day"]
]

assert_equal expected, Topic.order(:id).pluck(
Arel.sql("COALESCE(id, 0)"),
Expand Down

0 comments on commit f008c31

Please sign in to comment.