Avoid N+1 queries problem

This commit is contained in:
Leeingnyo 2021-12-26 03:29:41 +09:00
parent bd2ed1b338
commit 0f94288bab
3 changed files with 32 additions and 3 deletions

View File

@ -72,7 +72,7 @@ class Entry
def sort_title
sort_title_cached = @sort_title
return sort_title_cached if sort_title_cached
sort_title = Storage.default.get_entry_sort_title id
sort_title = @book.entry_sort_title_db id
if sort_title
@sort_title = sort_title
return sort_title
@ -89,11 +89,12 @@ class Entry
@sort_title = sort_title
end
@book.entry_sort_title_cache = nil
@book.remove_sorted_caches [SortMethod::Auto, SortMethod::Title], username
end
def sort_title_db
Storage.default.get_entry_sort_title id
@book.entry_sort_title_db @id
end
def display_name

View File

@ -8,11 +8,14 @@ class Title
entries : Array(Entry), title : String, id : String,
encoded_title : String, mtime : Time, signature : UInt64,
entry_cover_url_cache : Hash(String, String)?
setter entry_cover_url_cache : Hash(String, String)?
setter entry_cover_url_cache : Hash(String, String)?,
entry_sort_title_cache : Hash(String, String | Nil)?
@[YAML::Field(ignore: true)]
@sort_title : String?
@[YAML::Field(ignore: true)]
@entry_sort_title_cache : Hash(String, String | Nil)?
@[YAML::Field(ignore: true)]
@entry_display_name_cache : Hash(String, String)?
@[YAML::Field(ignore: true)]
@entry_cover_url_cache : Hash(String, String)?
@ -324,6 +327,15 @@ class Title
Storage.default.get_title_sort_title id
end
def entry_sort_title_db(entry_id)
unless @entry_sort_title_cache
@entry_sort_title_cache =
Storage.default.get_entries_sort_title @entries.map &.id
end
@entry_sort_title_cache.not_nil![entry_id]?
end
def tags
Storage.default.get_title_tags @id
end

View File

@ -371,6 +371,22 @@ class Storage
sort_title
end
def get_entries_sort_title(ids : Array(String))
results = Hash(String, String | Nil).new
MainFiber.run do
get_db do |db|
db.query "select id, sort_title from ids where id in (#{ids.join "," { |id| "'#{id}'" }})" do |rs|
rs.each do
id = rs.read String
sort_title = rs.read String | Nil
results[id] = sort_title
end
end
end
end
results
end
def set_entry_sort_title(entry_id : String, sort_title : String | Nil)
sort_title = nil if sort_title == ""
MainFiber.run do