A platform for community discussion. Free, open, simple.
PERF: Fix N+1 queries on private messages route.
Guo Xiang Tandbc630f45b71
diff --git a/app/serializers/topic_list_item_serializer.rb b/app/serializers/topic_list_item_serializer.rbindex d0cff44cb8f..a0addd8b66c 100644--- a/app/serializers/topic_list_item_serializer.rb+++ b/app/serializers/topic_list_item_serializer.rb@@ -88,7 +88,8 @@ class TopicListItemSerializer < ListableTopicSerializerenddef allowed_user_count- object.allowed_users.count+ # Don't use count as it will result in a query+ object.allowed_users.lengthenddef include_allowed_user_count?diff --git a/lib/topic_query.rb b/lib/topic_query.rbindex e94b03a3b04..73aa372ee58 100644--- a/lib/topic_query.rb+++ b/lib/topic_query.rb@@ -528,23 +528,19 @@ class TopicQueryoptions = @optionsoptions.reverse_merge!(per_page: per_page_setting)- result = Topic.includes(:tags)+ result = Topic.includes(:tags, :allowed_users)if type == :group- result = result- .includes(:allowed_users)- .joins("INNER JOIN topic_allowed_groups tag ON tag.topic_id = topics.id AND tag.group_id IN (SELECT id FROM groups WHERE LOWER(name) = '#{PG::Connection.escape_string(@options[:group_name].downcase)}')")+ result = result.joins(+ "INNER JOIN topic_allowed_groups tag ON tag.topic_id = topics.id AND tag.group_id IN (SELECT id FROM groups WHERE LOWER(name) = '#{PG::Connection.escape_string(@options[:group_name].downcase)}')"+ )unless user.admin?result = result.joins("INNER JOIN group_users gu ON gu.group_id = tag.group_id AND gu.user_id = #{user.id.to_i}")end-- resultelsif type == :user- result = result.includes(:allowed_users)result = result.where("topics.id IN (SELECT topic_id FROM topic_allowed_users WHERE user_id = #{user.id.to_i})")elsif type == :all- result = result.includes(:allowed_users)result = result.where("topics.id IN (SELECT topic_idFROM topic_allowed_users