PERF: Improve query for "Tech Support" badge

The old query could be extremely slow and resource intensive.
This also switches `granted_at` from `current_timestamp` to the date of the most recent accepted answer for each user.
This commit is contained in:
Gerhard Schlager 2022-11-21 17:56:22 +01:00 committed by Gerhard Schlager
parent f3b7fbb914
commit bbb3212258

View File

@ -40,25 +40,17 @@ Badge.seed(:name) do |badge|
badge.system = false badge.system = false
end end
tech_support_query = <<-EOS tech_support_query = <<-SQL
SELECT id user_id, current_timestamp granted_at SELECT p.user_id, MAX(pcf.created_at) AS granted_at
FROM users FROM post_custom_fields pcf
WHERE id IN ( JOIN badge_posts p ON pcf.post_id = p.id
SELECT p1.user_id JOIN topics t ON p.topic_id = t.id
FROM post_custom_fields pc WHERE pcf.name = 'is_accepted_answer'
JOIN badge_posts p1 ON p1.id = pc.post_id AND p.user_id <> t.user_id -- ignore topics solved by OP
JOIN topics t1 ON p1.topic_id = t1.id AND (:backfill OR p.id IN (:post_ids))
WHERE p1.user_id <> t1.user_id AND GROUP BY p.user_id
name = 'is_accepted_answer' AND HAVING COUNT(*) >= 10
p1.user_id IN ( SQL
SELECT user_id
FROM posts
WHERE :backfill OR p1.id IN (:post_ids)
)
GROUP BY p1.user_id
HAVING COUNT(*) > 9
)
EOS
Badge.seed(:name) do |badge| Badge.seed(:name) do |badge|
badge.name = I18n.t("badges.tech_support.name") badge.name = I18n.t("badges.tech_support.name")