Skip to content

Commit

Permalink
Avoid executing queries when calling caches_count_where (#16)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
GregAtkinAcademia authored Jul 14, 2022
1 parent 456b0a3 commit 8a6609e
Showing 1 changed file with 10 additions and 17 deletions.
27 changes: 10 additions & 17 deletions lib/cached_counts.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 8a6609e

Please sign in to comment.