Skip to content

Fix update-all for composite key #1189

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 39 additions & 3 deletions lib/arel/visitors/sqlserver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,46 @@ def visit_Arel_Nodes_Concat(o, collector)
end

def visit_Arel_Nodes_UpdateStatement(o, collector)
if o.orders.any? && o.limit.nil?
o.limit = Nodes::Limit.new(9_223_372_036_854_775_807)
if has_join_and_composite_primary_key?(o)
update_statement_using_join(o, collector)
else
o.limit = Nodes::Limit.new(9_223_372_036_854_775_807) if o.orders.any? && o.limit.nil?

super
end
super
end

def visit_Arel_Nodes_DeleteStatement(o, collector)
if has_join_and_composite_primary_key?(o)
delete_statement_using_join(o, collector)
else
super
end
end

def has_join_and_composite_primary_key?(o)
has_join_sources?(o) && o.relation.left.instance_variable_get(:@klass).composite_primary_key?
end

def delete_statement_using_join(o, collector)
collector.retryable = false

collector << "DELETE "
visit o.relation.left, collector
collector << " FROM "
visit o.relation, collector
collect_nodes_for o.wheres, collector, " WHERE ", " AND "
end

def update_statement_using_join(o, collector)
collector.retryable = false

collector << "UPDATE "
visit o.relation.left, collector
collect_nodes_for o.values, collector, " SET "
collector << " FROM "
visit o.relation, collector
collect_nodes_for o.wheres, collector, " WHERE ", " AND "
end

def visit_Arel_Nodes_Lock(o, collector)
Expand Down
Loading