A platform for community discussion. Free, open, simple.
PERF: Optimize topic query for many categories (#20743)
Bianca Nenciufb3c610f0929
diff --git a/lib/guardian/topic_guardian.rb b/lib/guardian/topic_guardian.rbindex 56da4650a7c..9ba3a248c5d 100644--- a/lib/guardian/topic_guardian.rb+++ b/lib/guardian/topic_guardian.rb@@ -288,20 +288,18 @@ module TopicGuardiantopic&.access_topic_via_group.present? && authenticated?end- def filter_allowed_categories(records)+ def filter_allowed_categories(records, category_id_column: "topics.category_id")return records if is_admin? && !SiteSetting.suppress_secured_categories_from_adminrecords =- (- if allowed_category_ids.size == 0- records.where("topics.category_id IS NULL")- else- records.where(- "topics.category_id IS NULL or topics.category_id IN (?)",- allowed_category_ids,- )- end- )+ if allowed_category_ids.size == 0+ records.where("#{category_id_column} IS NULL")+ else+ records.where(+ "#{category_id_column} IS NULL or #{category_id_column} IN (?)",+ allowed_category_ids,+ )+ endrecords.references(:categories)enddiff --git a/lib/topic_query.rb b/lib/topic_query.rbindex 977db1fe7b2..ed1be76886a 100644--- a/lib/topic_query.rb+++ b/lib/topic_query.rb@@ -776,7 +776,11 @@ class TopicQueryresult = apply_ordering(result, options)- all_listable_topics = @guardian.filter_allowed_categories(Topic.unscoped.listable_topics)+ all_listable_topics =+ @guardian.filter_allowed_categories(+ Topic.unscoped.listable_topics,+ category_id_column: "categories.id",+ )if options[:include_pms] || options[:include_all_pms]all_pm_topics =@@ -937,12 +941,12 @@ class TopicQuery].flatten.map(&:to_i)category_ids << category_id if category_id.present? && category_ids.exclude?(category_id)- list = list.where("topics.category_id IN (?)", category_ids) if category_ids.present?+ list = list.where("categories.id IN (?)", category_ids) if category_ids.present?elsecategory_ids = SiteSetting.default_categories_muted.split("|").map(&:to_i)category_ids -= [category_id] if category_id.present? && category_ids.include?(category_id)- list = list.where("topics.category_id NOT IN (?)", category_ids) if category_ids.present?+ list = list.where("categories.id NOT IN (?)", category_ids) if category_ids.present?endlist