Skip to content

A platform for community discussion. Free, open, simple.

PERF: Optimize `CategoryList#relevant_topics_query` SQL query (#36476)

Alan Guo Xiang Tan75a7b06ebe27
diff --git a/app/models/category_list.rb b/app/models/category_list.rb
index a8e282f7e84..0b85e07fa61 100644
--- a/app/models/category_list.rb
+++ b/app/models/category_list.rb
@@ -76,7 +76,11 @@ class CategoryList
def relevant_topics_query
@all_topics =
Topic
- .secured(@guardian)
+ .secured(
+ @guardian,
+ include_uncategorized: false,
+ ) # perf optimization since category featured topics can't have `category_id` set to null
+ .listable_topics
.joins(
"INNER JOIN category_featured_topics ON topics.id = category_featured_topics.topic_id",
)
diff --git a/app/models/topic.rb b/app/models/topic.rb
index 9bd5a46fe5f..3215e864746 100644
--- a/app/models/topic.rb
+++ b/app/models/topic.rb
@@ -361,7 +361,7 @@ class Topic < ActiveRecord::Base
scope :exclude_scheduled_bump_topics, -> { where.not(id: TopicTimer.scheduled_bump_topics) }
scope :secured,
- lambda { |guardian = nil|
+ lambda { |guardian = nil, include_uncategorized: true|
ids = guardian.secure_category_ids if guardian
# Query conditions
@@ -372,8 +372,10 @@ class Topic < ActiveRecord::Base
["NOT read_restricted"]
end
+ uncategorized_condition = "topics.category_id IS NULL OR" if include_uncategorized
+
where(
- "topics.category_id IS NULL OR topics.category_id IN (SELECT id FROM categories WHERE #{condition[0]})",
+ "#{uncategorized_condition} topics.category_id IN (SELECT id FROM categories WHERE #{condition[0]})",
condition[1],
)
}
diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb
index 60635b0bafc..d479244acff 100644
--- a/spec/models/topic_spec.rb
+++ b/spec/models/topic_spec.rb
@@ -2606,6 +2606,19 @@ RSpec.describe Topic do
topic,
)
end
+
+ it "excludes uncategorized topics when `include_uncategorized` kwarg is false" do
+ uncategorized_topic =
+ Fabricate(:topic, category_id: nil, archetype: Archetype.private_message)
+
+ categorized_topic = Fabricate(:topic, category: Fabricate(:category))
+
+ expect(uncategorized_topic.reload.category_id).to eq(nil)
+
+ result = Topic.secured(Guardian.new(user), include_uncategorized: false)
+
+ expect(result.pluck(:id)).to contain_exactly(categorized_topic.id)
+ end
end
describe "all_allowed_users" do