diff --git a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb index a67fa26407c27..64e87867e553d 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb @@ -266,7 +266,7 @@ def lookup_sql_cache(sql, name, binds) if result ActiveSupport::Notifications.instrument( "sql.active_record", - cache_notification_info(sql, name, binds) + cache_notification_info_result(sql, name, binds, result) ) end @@ -288,13 +288,19 @@ def cache_sql(sql, name, binds) if hit ActiveSupport::Notifications.instrument( "sql.active_record", - cache_notification_info(sql, name, binds) + cache_notification_info_result(sql, name, binds, result) ) end result.dup end + def cache_notification_info_result(sql, name, binds, result) + payload = cache_notification_info(sql, name, binds) + payload[:row_count] = result.length + payload + end + # Database adapters can override this method to # provide custom cache information. def cache_notification_info(sql, name, binds) diff --git a/activerecord/test/cases/instrumentation_test.rb b/activerecord/test/cases/instrumentation_test.rb index 5fb3d2600a552..29c02d2fd329f 100644 --- a/activerecord/test/cases/instrumentation_test.rb +++ b/activerecord/test/cases/instrumentation_test.rb @@ -149,6 +149,29 @@ def test_payload_row_count_on_raw_sql ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber end + def test_payload_row_count_on_cache + events = [] + callback = -> (event) do + payload = event.payload + events << payload if payload[:sql].include?("SELECT") + end + + Book.create!(name: "row count book") + ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do + Book.cache do + Book.first + Book.first + end + end + + assert_equal 2, events.size + assert_not events[0][:cached] + assert events[1][:cached] + + assert_equal 1, events[0][:row_count] + assert_equal 1, events[1][:row_count] + end + def test_payload_connection_with_query_cache_disabled connection = ClothingItem.lease_connection subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |_, _, _, _, payload|