Skip to content

Commit

Permalink
FIX: improve performance of post alerter job (discourse#22378)
Browse files Browse the repository at this point in the history
Recently, SQL query returning users who have muted category or tag were introduced, and it is causing performance issues.

It is much more effective to first get IDs of users who have CategoryUser/TagUsers related to specific topic and then in second query get relevant users.
  • Loading branch information
lis2 authored Jul 3, 2023
1 parent b3a23bd commit 7a204e7
Showing 1 changed file with 6 additions and 9 deletions.
15 changes: 6 additions & 9 deletions app/services/post_alerter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -270,15 +270,12 @@ def category_watchers(topic)
end

def category_or_tag_muters(topic)
User
.joins(
"LEFT JOIN category_users ON users.id = category_users.user_id AND category_users.category_id = #{topic.category_id.to_i} AND category_users.notification_level = #{CategoryUser.notification_levels[:muted].to_i}",
)
.joins("LEFT JOIN topic_tags ON topic_tags.topic_id = #{topic.id.to_i}")
.joins(
"LEFT JOIN tag_users ON users.id = tag_users.user_id AND tag_users.tag_id = topic_tags.tag_id AND tag_users.notification_level = #{TagUser.notification_levels[:muted].to_i}",
)
.where("category_users.id IS NOT NULL OR tag_users.id IS NOT NULL")
user_ids_sql = <<~SQL
SELECT user_id FROM category_users WHERE category_id = #{topic.category_id.to_i} AND notification_level = #{CategoryUser.notification_levels[:muted]}
UNION
SELECT user_id FROM tag_users tu JOIN topic_tags tt ON tt.tag_id = tu.tag_id AND tt.topic_id = #{topic.id} AND tu.notification_level = #{TagUser.notification_levels[:muted]}
SQL
User.where("id IN (#{user_ids_sql})")
end

def notify_first_post_watchers(post, user_ids, notified = nil)
Expand Down

0 comments on commit 7a204e7

Please sign in to comment.