Skip to content

Commit 6ff9e82

Browse files
committed
Pass existing connection to #arel in #to_sql
This prevents having to do another connection lookup when manually generating SQL for a Relation. Additionally, by adding a connection parameter to `#arel` the `{update,delete}_all` methods can now go through `#arel` instead of `#build_arel`. This prevents having to rebuild the Arel AST in cases where a relation is re-used for querying after calling `{update,delete}_all`.
1 parent 019f162 commit 6ff9e82

File tree

3 files changed

+10
-6
lines changed

3 files changed

+10
-6
lines changed

activerecord/lib/active_record/associations/join_dependency/join_association.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def join_constraints(foreign_table, foreign_klass, join_type, alias_tracker)
5353
end
5454
end
5555

56-
arel = scope.arel(alias_tracker.aliases)
56+
arel = scope.arel(aliases: alias_tracker.aliases)
5757
nodes = arel.constraints.first
5858

5959
if nodes.is_a?(Arel::Nodes::And)

activerecord/lib/active_record/relation.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -625,7 +625,7 @@ def update_all(updates)
625625
end
626626

627627
model.with_connection do |c|
628-
arel = eager_loading? ? apply_join_dependency.arel : build_arel(c)
628+
arel = eager_loading? ? apply_join_dependency.arel : arel(c)
629629
arel.source.left = table
630630

631631
key = if model.composite_primary_key?
@@ -1040,7 +1040,7 @@ def delete_all
10401040
end
10411041

10421042
model.with_connection do |c|
1043-
arel = eager_loading? ? apply_join_dependency.arel : build_arel(c)
1043+
arel = eager_loading? ? apply_join_dependency.arel : arel(c)
10441044
arel.source.left = table
10451045

10461046
key = if model.composite_primary_key?
@@ -1233,7 +1233,7 @@ def to_sql
12331233
end
12341234
else
12351235
model.with_connection do |conn|
1236-
conn.unprepared_statement { conn.to_sql(arel) }
1236+
conn.unprepared_statement { conn.to_sql(arel(conn)) }
12371237
end
12381238
end
12391239
end

activerecord/lib/active_record/relation/query_methods.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1591,8 +1591,12 @@ def excluding!(records) # :nodoc:
15911591
end
15921592

15931593
# Returns the Arel object associated with the relation.
1594-
def arel(aliases = nil) # :nodoc:
1595-
@arel ||= with_connection { |c| build_arel(c, aliases) }
1594+
def arel(conn = nil, aliases: nil) # :nodoc:
1595+
@arel ||= if conn
1596+
build_arel(conn, aliases)
1597+
else
1598+
with_connection { |c| build_arel(c, aliases) }
1599+
end
15961600
end
15971601

15981602
def construct_join_dependency(associations, join_type) # :nodoc:

0 commit comments

Comments
 (0)