Skip to content

Commit e12514a

Browse files
authored
Merge pull request rails#43076 from Shopify/ar-query-logs-nesting
Make `QueryLogs.set_context` restore previous values
2 parents a81aeb6 + 6ea85af commit e12514a

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

activerecord/lib/active_record/query_logs.rb

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,13 +96,15 @@ def update_context(**options)
9696
end
9797

9898
# Updates the context used to construct tags in the SQL comment during
99-
# execution of the provided block. Resets provided values to nil after
100-
# the block is executed.
99+
# execution of the provided block. Resets the provided keys to their
100+
# previous value once the block exits.
101101
def set_context(**options)
102+
keys = options.keys
103+
previous_context = keys.zip(context.values_at(*keys)).to_h
102104
update_context(**options)
103105
yield if block_given?
104106
ensure
105-
update_context(**options.transform_values! { NullObject.new })
107+
update_context(**previous_context)
106108
end
107109

108110
# Temporarily tag any query executed within `&block`. Can be nested.

activerecord/test/cases/query_logs_test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,4 +253,18 @@ def test_custom_proc_context_tags
253253
ActiveRecord::QueryLogs.update_context(foo: nil)
254254
ActiveRecord::QueryLogs.tags = original_tags
255255
end
256+
257+
def test_set_context_restore_state
258+
original_tags = ActiveRecord::QueryLogs.tags
259+
ActiveRecord::QueryLogs.tags = [foo: -> { context[:foo] }]
260+
ActiveRecord::QueryLogs.set_context(foo: "bar") do
261+
assert_sql(%r{/\*foo:bar\*/$}) { Dashboard.first }
262+
ActiveRecord::QueryLogs.set_context(foo: "plop") do
263+
assert_sql(%r{/\*foo:plop\*/$}) { Dashboard.first }
264+
end
265+
assert_sql(%r{/\*foo:bar\*/$}) { Dashboard.first }
266+
end
267+
ensure
268+
ActiveRecord::QueryLogs.tags = original_tags
269+
end
256270
end

0 commit comments

Comments
 (0)