Skip to content

Commit

Permalink
Wrap by parentheses custom complex sql literals in update_all
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed Mar 24, 2024
1 parent 68b20b6 commit fa2aea8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
6 changes: 5 additions & 1 deletion activerecord/lib/active_record/relation.rb
Expand Up @@ -1023,7 +1023,11 @@ def _scoping(scope, registry, all_queries = false)
def _substitute_values(values)
values.map do |name, value|
attr = table[name]
unless Arel.arel_node?(value)
if Arel.arel_node?(value)
if value.is_a?(Arel::Nodes::SqlLiteral)
value = Arel::Nodes::Grouping.new(value)
end
else
type = klass.type_for_attribute(attr.name)
value = predicate_builder.build_bind_attribute(attr.name, type.cast(value))
end
Expand Down
13 changes: 12 additions & 1 deletion activerecord/test/cases/persistence_test.rb
Expand Up @@ -17,6 +17,7 @@
require "models/minimalistic"
require "models/parrot"
require "models/minivan"
require "models/car"
require "models/person"
require "models/ship"
require "models/admin"
Expand All @@ -29,7 +30,7 @@

class PersistenceTest < ActiveRecord::TestCase
fixtures :topics, :companies, :developers, :accounts, :minimalistics, :authors, :author_addresses,
:posts, :minivans, :clothing_items, :cpk_books
:posts, :minivans, :clothing_items, :cpk_books, :people, :cars

def test_populates_non_primary_key_autoincremented_column
topic = TitlePrimaryKeyTopic.create!(title: "title pk topic")
Expand Down Expand Up @@ -908,6 +909,16 @@ def test_update_all_with_hash
assert_nil Topic.find(2).last_read
end

def test_update_all_with_custom_sql_as_value
person = people(:michael)
person.update!(cars_count: 0)

Person.update_all(cars_count: Arel.sql(<<~SQL))
select count(*) from cars where cars.person_id = people.id
SQL
assert_equal 1, person.reload.cars_count
end

def test_delete_new_record
client = Client.new(name: "37signals")
client.delete
Expand Down

0 comments on commit fa2aea8

Please sign in to comment.