Skip to content

Commit c1d04cc

Browse files
authored
Merge pull request rails#52696 from jhawthorn/cached_row_count
Add :row_count in cached sql.active_record payload
2 parents 11f1f35 + 31309b8 commit c1d04cc

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ def lookup_sql_cache(sql, name, binds)
266266
if result
267267
ActiveSupport::Notifications.instrument(
268268
"sql.active_record",
269-
cache_notification_info(sql, name, binds)
269+
cache_notification_info_result(sql, name, binds, result)
270270
)
271271
end
272272

@@ -288,13 +288,19 @@ def cache_sql(sql, name, binds)
288288
if hit
289289
ActiveSupport::Notifications.instrument(
290290
"sql.active_record",
291-
cache_notification_info(sql, name, binds)
291+
cache_notification_info_result(sql, name, binds, result)
292292
)
293293
end
294294

295295
result.dup
296296
end
297297

298+
def cache_notification_info_result(sql, name, binds, result)
299+
payload = cache_notification_info(sql, name, binds)
300+
payload[:row_count] = result.length
301+
payload
302+
end
303+
298304
# Database adapters can override this method to
299305
# provide custom cache information.
300306
def cache_notification_info(sql, name, binds)

activerecord/test/cases/instrumentation_test.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,29 @@ def test_payload_row_count_on_raw_sql
149149
ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber
150150
end
151151

152+
def test_payload_row_count_on_cache
153+
events = []
154+
callback = -> (event) do
155+
payload = event.payload
156+
events << payload if payload[:sql].include?("SELECT")
157+
end
158+
159+
Book.create!(name: "row count book")
160+
ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
161+
Book.cache do
162+
Book.first
163+
Book.first
164+
end
165+
end
166+
167+
assert_equal 2, events.size
168+
assert_not events[0][:cached]
169+
assert events[1][:cached]
170+
171+
assert_equal 1, events[0][:row_count]
172+
assert_equal 1, events[1][:row_count]
173+
end
174+
152175
def test_payload_connection_with_query_cache_disabled
153176
connection = ClothingItem.lease_connection
154177
subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |_, _, _, _, payload|

0 commit comments

Comments
 (0)