FIX: eager load encrypt tables in search (#21)

FIX: eager load encrypt tables in search (#21)

Solve N+1 when in:personal filter is included in search

diff --git a/lib/topic_extensions.rb b/lib/topic_extensions.rb
index dc7c231..b6c4f10 100644
--- a/lib/topic_extensions.rb
+++ b/lib/topic_extensions.rb
@@ -3,6 +3,7 @@
 module TopicExtensions
   def self.prepended(base)
     base.has_one :encrypted_topics_data
+    base.has_many :encrypted_topics_users
   end
 
   def is_encrypted?
diff --git a/plugin.rb b/plugin.rb
index 9e52990..661504a 100644
--- a/plugin.rb
+++ b/plugin.rb
@@ -110,7 +110,7 @@ after_initialize do
   # paired private key.
 
   add_to_serializer(:topic_view, :topic_key, false) do
-    EncryptedTopicsUser.find_by(topic_id: object.topic.id, user_id: scope.user.id)&.key
+    object.topic.encrypted_topics_users.find { |topic_user| topic_user.user_id == scope.user.id }&.key
   end
 
   add_to_serializer(:topic_view, :include_topic_key?) do
@@ -118,7 +118,7 @@ after_initialize do
   end
 
   add_to_serializer(:basic_topic, :topic_key, false) do
-    EncryptedTopicsUser.find_by(topic_id: object.id, user_id: scope.user.id)&.key
+    object.encrypted_topics_users.find { |topic_user| topic_user.user_id == scope.user.id }&.key
   end
 
   add_to_serializer(:basic_topic, :include_topic_key?) do
@@ -126,7 +126,7 @@ after_initialize do
   end
 
   add_to_serializer(:notification, :topic_key, false) do
-    EncryptedTopicsUser.find_by(topic_id: object.topic.id, user_id: scope.user.id)&.key
+    object.topic.encrypted_topics_users.find { |topic_user| topic_user.user_id == scope.user.id }&.key
   end
 
   add_to_serializer(:notification, :include_topic_key?) do
@@ -212,6 +212,13 @@ after_initialize do
   add_permitted_post_create_param(:encrypted_raw)
   add_permitted_post_create_param(:encrypted_keys)
 
+  # TODO: Remove if check once Discourse 2.6 is stable
+  if respond_to?(:register_search_topic_eager_load)
+    register_search_topic_eager_load do |opts|
+      %i(encrypted_topics_users encrypted_topics_data) if opts[:search_pms] && SiteSetting.encrypt_enabled?
+    end
+  end
+
   NewPostManager.add_handler do |manager|
     next if !manager.args[:encrypted_raw]
 

GitHub sha: 6d51a6f4

1 Like

This commit appears in #21 which was merged by lis2.