From cbdab71179e60a97137f00c5ed070225dd9c8e4c Mon Sep 17 00:00:00 2001 From: Sam Date: Wed, 20 Jun 2018 18:11:39 +1000 Subject: [PATCH] PERF: stop counting participants on very large topics This query gets very expensive and can be bypassed on large topics --- lib/topic_view.rb | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/lib/topic_view.rb b/lib/topic_view.rb index 45e7f2bc3df..e064a3ba93f 100644 --- a/lib/topic_view.rb +++ b/lib/topic_view.rb @@ -296,17 +296,26 @@ class TopicView end end + # if a topic has more that N posts no longer attempt to + # get accurate participant count, instead grab cached count + # from topic + MAX_POSTS_COUNT_PARTICIPANTS = 500 + def participant_count @participant_count ||= begin if participants.size == MAX_PARTICIPANTS - sql = <<~SQL - SELECT COUNT(DISTINCT user_id) - FROM posts - WHERE id IN (:post_ids) - AND user_id IS NOT NULL - SQL - DB.query_single(sql, post_ids: unfiltered_post_ids).first.to_i + if unfiltered_post_ids.length > MAX_POSTS_COUNT_PARTICIPANTS + @topic.participant_count + else + sql = <<~SQL + SELECT COUNT(DISTINCT user_id) + FROM posts + WHERE id IN (:post_ids) + AND user_id IS NOT NULL + SQL + DB.query_single(sql, post_ids: unfiltered_post_ids).first.to_i + end else participants.size end