Skip to content

Commit

Permalink
Fix: use eager_load should fetch from db
Browse files Browse the repository at this point in the history
  • Loading branch information
OuYangJinTing committed Apr 12, 2020
1 parent e016fa2 commit 7b6aea7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 18 deletions.
31 changes: 13 additions & 18 deletions lib/second_level_cache/active_record/finder_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,13 @@ module FinderMethods
# Article.where("articles.user_id = 1").find(prams[:id])
# Article.where("user_id = 1 AND ...").find(params[:id])
def find_one(id)
return super(id) unless second_level_cache_enabled?
return super(id) unless select_all_column?
return super unless cachable?

id = id.id if ActiveRecord::Base == id
if cachable?
record = @klass.read_second_level_cache(id)
return record if record && where_values_match_cache?(record)
end
record = @klass.read_second_level_cache(id)
return record if record && where_values_match_cache?(record)

record = super(id)
record = super
record.write_second_level_cache
record
end
Expand All @@ -44,26 +41,28 @@ def find_one(id)
# User.where(age: 18).first
#
def first(limit = nil)
return super(limit) if limit.to_i > 1
return super if limit.to_i > 1
return super unless cachable?
# only have primary_key condition in where
if cachable? && where_values_hash.length == 1 && where_values_hash.key?(primary_key)
if where_values_hash.length == 1 && where_values_hash.key?(primary_key)
record = @klass.read_second_level_cache(where_values_hash[primary_key])
return record if record
end

record = super(limit)
record&.write_second_level_cache if select_all_column?
record = super
record&.write_second_level_cache
record
end

private

# readonly_value - active_record/relation/query_methods.rb Rails 5.1 true/false
def cachable?
limit_one? &&
second_level_cache_enabled? &&
limit_one? &&
!eager_loading? &&
select_values.blank? &&
order_values_can_cache? &&
includes_values.blank? &&
preload_values.blank? &&
readonly_value.blank? &&
joins_values.blank? &&
!@klass.locking_enabled? &&
Expand Down Expand Up @@ -96,10 +95,6 @@ def where_values_match_cache?(record)
def limit_one?
limit_value.blank? || limit_value == 1
end

def select_all_column?
select_values.blank?
end
end
end
end
9 changes: 9 additions & 0 deletions test/finder_methods_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ def test_should_fetch_from_db_if_where_use_string
end
end

def test_should_fetch_from_db_when_use_eager_load
@user.write_second_level_cache
assert_queries(:any) do
assert_sql(/LEFT\sOUTER\sJOIN\s\"books\"/m) do
User.eager_load(:books).find(@user.id)
end
end
end

def test_where_and_first_should_with_cache
@user.write_second_level_cache
assert_no_queries do
Expand Down

0 comments on commit 7b6aea7

Please sign in to comment.