From d3a409456f2cb36cdcc92a9367c0533584fc9433 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Tue, 12 Sep 2017 14:05:25 +0800 Subject: [PATCH] PERF: Bypass AR and execute SQL directly. --- app/models/topic.rb | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/app/models/topic.rb b/app/models/topic.rb index b9e1f47ad42..52aa1255e5f 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -1224,12 +1224,21 @@ SQL end def pm_with_non_human_user? - Topic.private_messages - .joins("LEFT JOIN topic_allowed_groups ON topics.id = topic_allowed_groups.topic_id") - .where("topic_allowed_groups.topic_id IS NULL") - .where("topics.id = ?", self.id) - .where("(SELECT COUNT(*) FROM topic_allowed_users WHERE topic_allowed_users.topic_id = ? AND topic_allowed_users.user_id > 0) = 1", self.id) - .exists? + sql = <<~SQL + SELECT 1 FROM topics + LEFT JOIN topic_allowed_groups ON topics.id = topic_allowed_groups.topic_id + WHERE topic_allowed_groups.topic_id IS NULL + AND topics.archetype = :private_message + AND topics.id = :topic_id + AND ( + SELECT COUNT(*) FROM topic_allowed_users + WHERE topic_allowed_users.topic_id = :topic_id + AND topic_allowed_users.user_id > 0 + ) = 1 + SQL + + result = Topic.exec_sql(sql, private_message: Archetype.private_message, topic_id: self.id) + result.ntuples != 0 end private