From 92ccb7c75fd0d07479ea3b458b405b8e6667e05f Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Wed, 10 Oct 2018 05:31:20 +0900 Subject: Improve DELETE with JOIN handling to avoid subqueries if possible Before: ``` Pet Destroy (0.8ms) DELETE FROM `pets` WHERE `pets`.`pet_id` IN (SELECT `pet_id` FROM (SELECT DISTINCT `pets`.`pet_id` FROM `pets` LEFT OUTER JOIN `toys` ON `toys`.`pet_id` = `pets`.`pet_id` WHERE `toys`.`name` = ?) AS __active_record_temp) [["name", "Bone"]] ``` After: ``` Pet Destroy (1.0ms) DELETE `pets` FROM `pets` LEFT OUTER JOIN `toys` ON `toys`.`pet_id` = `pets`.`pet_id` WHERE `toys`.`name` = ? [["name", "Bone"]] ``` --- activerecord/lib/arel/visitors/to_sql.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'activerecord/lib/arel/visitors/to_sql.rb') diff --git a/activerecord/lib/arel/visitors/to_sql.rb b/activerecord/lib/arel/visitors/to_sql.rb index 7c0f6c2e97..a55450956b 100644 --- a/activerecord/lib/arel/visitors/to_sql.rb +++ b/activerecord/lib/arel/visitors/to_sql.rb @@ -76,7 +76,13 @@ module Arel # :nodoc: all def visit_Arel_Nodes_DeleteStatement(o, collector) o = prepare_delete_statement(o) - collector << "DELETE FROM " + if has_join_sources?(o) + collector << "DELETE " + visit o.relation.left, collector + collector << " FROM " + else + collector << "DELETE FROM " + end collector = visit o.relation, collector collect_where_for(o, collector) -- cgit v1.2.3