From 0f94288bab36d88b905d7c7cd8d402f3e62cf2c4 Mon Sep 17 00:00:00 2001 From: Leeingnyo Date: Sun, 26 Dec 2021 03:29:41 +0900 Subject: [PATCH] Avoid N+1 queries problem --- src/library/entry.cr | 5 +++-- src/library/title.cr | 14 +++++++++++++- src/storage.cr | 16 ++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/library/entry.cr b/src/library/entry.cr index 4c9c96f..067acce 100644 --- a/src/library/entry.cr +++ b/src/library/entry.cr @@ -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 diff --git a/src/library/title.cr b/src/library/title.cr index f61f01d..8465d56 100644 --- a/src/library/title.cr +++ b/src/library/title.cr @@ -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 diff --git a/src/storage.cr b/src/storage.cr index edf71ff..cd3e3c0 100644 --- a/src/storage.cr +++ b/src/storage.cr @@ -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