PERF: Fix N+1 queries on private messages route.

This commit is contained in:
Guo Xiang Tan 2020-09-11 15:18:23 +08:00
parent 44fba9463b
commit dbc630f45b
No known key found for this signature in database
GPG Key ID: FBD110179AAC1F20
2 changed files with 6 additions and 9 deletions

View File

@ -88,7 +88,8 @@ class TopicListItemSerializer < ListableTopicSerializer
end
def allowed_user_count
object.allowed_users.count
# Don't use count as it will result in a query
object.allowed_users.length
end
def include_allowed_user_count?

View File

@ -528,23 +528,19 @@ class TopicQuery
options = @options
options.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
result
elsif 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_id
FROM topic_allowed_users