From 8a6609e96ecbe12d08eae68deaea70feaf6d5b87 Mon Sep 17 00:00:00 2001 From: GregAtkinAcademia <59578295+GregAtkinAcademia@users.noreply.github.com> Date: Thu, 14 Jul 2022 09:44:31 -0500 Subject: [PATCH] Avoid executing queries when calling caches_count_where (#16) * Avoid executing queries when calling caches_count_where * Add back the validation of the scope * Remove newly added spec * Don't write fallback value to cache * Remove default race condition fallback proc * Use nil for fallback value when missing from cache --- lib/cached_counts.rb | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/lib/cached_counts.rb b/lib/cached_counts.rb index 0fd3d2d..7824975 100644 --- a/lib/cached_counts.rb +++ b/lib/cached_counts.rb @@ -159,16 +159,6 @@ def default_race_condition_fallback_proc(key, relation, options) fallback = Rails.cache.read(key) fallback = fallback.value if fallback.is_a?(ActiveSupport::Cache::Entry) - if fallback.nil? - begin - fallback = relation.count - rescue ActiveRecord::StatementInvalid => e - fallback = 0 - end - - Rails.cache.write key, fallback, expires_in: options.fetch(:expires_in, 1.week), raw: true - end - -> { fallback } end @@ -253,13 +243,16 @@ def add_count_attribute_methods(attribute_name, key_getter, relation_getter, def # Ensure that other reads find something in the cache, but # continue calculating here because the default is likely inaccurate. fallback_value = instance_exec &race_condition_fallback - CachedCounts.logger.warn "Setting #{fallback_value} as race_condition_fallback for #{send(key_method)}" - Rails.cache.write( - send(key_method), - fallback_value.to_i, - expires_in: 30.seconds, - raw: true - ) + + if fallback_value + CachedCounts.logger.warn "Setting #{fallback_value} as race_condition_fallback for #{send(key_method)}" + Rails.cache.write( + send(key_method), + fallback_value.to_i, + expires_in: 30.seconds, + raw: true + ) + end end relation = instance_exec(&relation_getter)