PERF: Avoid running ignored users DB query for anon users. (#14487)

PERF: Avoid running ignored users DB query for anon users. (#14487)

diff --git a/lib/topic_view.rb b/lib/topic_view.rb
index c396604..1821927 100644
--- a/lib/topic_view.rb
+++ b/lib/topic_view.rb
@@ -725,6 +725,7 @@ class TopicView
     return posts.where(post_type: Post.types[:regular]) if @only_regular
 
     visible_types = Topic.visible_post_types(@user)
+
     if @user.present?
       posts.where("posts.user_id = ? OR post_type IN (?)", @user.id, visible_types)
     else
@@ -791,21 +792,23 @@ class TopicView
     @contains_gaps = false
     @filtered_posts = unfiltered_posts
 
-    sql = <<~SQL
+    if @user
+      sql = <<~SQL
         SELECT ignored_user_id
         FROM ignored_users as ig
-        JOIN users as u ON u.id = ig.ignored_user_id
+        INNER JOIN users as u ON u.id = ig.ignored_user_id
         WHERE ig.user_id = :current_user_id
           AND ig.ignored_user_id <> :current_user_id
           AND NOT u.admin
           AND NOT u.moderator
-    SQL
+      SQL
 
-    ignored_user_ids = DB.query_single(sql, current_user_id: @user&.id)
+      ignored_user_ids = DB.query_single(sql, current_user_id: @user.id)
 
-    if ignored_user_ids.present?
-      @filtered_posts = @filtered_posts.where.not("user_id IN (?) AND id <> ?", ignored_user_ids, first_post_id)
-      @contains_gaps = true
+      if ignored_user_ids.present?
+        @filtered_posts = @filtered_posts.where.not("user_id IN (?) AND posts.id <> ?", ignored_user_ids, first_post_id)
+        @contains_gaps = true
+      end
     end
 
     # Filters

GitHub sha: 0359adc0b84439aa19bfe7ae5ef0f3db7f3833ee

This commit appears in #14487 which was approved by lis2. It was merged by tgxworld.