FIX: improve performance of post alerter job (#22378)

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.
This commit is contained in:
Krzysztof Kotlarek 2023-07-03 19:58:53 +10:00 committed by GitHub
parent b3a23bd9d6
commit 7a204e754c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 6 additions and 9 deletions

View File

@ -270,15 +270,12 @@ class PostAlerter
end end
def category_or_tag_muters(topic) def category_or_tag_muters(topic)
User user_ids_sql = <<~SQL
.joins( SELECT user_id FROM category_users WHERE category_id = #{topic.category_id.to_i} AND notification_level = #{CategoryUser.notification_levels[:muted]}
"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}", 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]}
.joins("LEFT JOIN topic_tags ON topic_tags.topic_id = #{topic.id.to_i}") SQL
.joins( User.where("id IN (#{user_ids_sql})")
"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")
end end
def notify_first_post_watchers(post, user_ids, notified = nil) def notify_first_post_watchers(post, user_ids, notified = nil)