PERF: Improve query for "Helpdesk" badge

The old query could be extremely slow and resource intensive.
This also switches `granted_at` from the post's creation date to the date when the post was marked as solution.
This commit is contained in:
Gerhard Schlager 2022-11-21 21:45:46 +01:00 committed by Gerhard Schlager
parent bbb3212258
commit 865433c0a7
1 changed files with 14 additions and 21 deletions

View File

@ -2,27 +2,20 @@
return unless badge_grouping = BadgeGrouping.find_by(name: "Community") return unless badge_grouping = BadgeGrouping.find_by(name: "Community")
helpdesk_query = <<-EOS helpdesk_query = <<-SQL
SELECT p.user_id, p.id post_id, p.updated_at granted_at SELECT post_id, user_id, created_at AS granted_at
FROM badge_posts p FROM (
WHERE p.post_number > 1 AND SELECT p.id AS post_id, p.user_id, pcf.created_at,
p.id IN ( ROW_NUMBER() OVER (PARTITION BY p.user_id ORDER BY pcf.created_at) AS row_number
SELECT post_id FROM ( FROM post_custom_fields pcf
SELECT pc.post_id, row_number() JOIN badge_posts p ON pcf.post_id = p.id
OVER (PARTITION BY p1.user_id ORDER BY pc.created_at) as rnum 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 name = 'is_accepted_answer' AND ) x
p1.user_id <> t1.user_id AND WHERE row_number = 1
( SQL
:backfill OR
p1.user_id IN (
select user_id from posts where p1.id IN (:post_ids)
)
)
) X WHERE rnum = 1)
EOS
Badge.seed(:name) do |badge| Badge.seed(:name) do |badge|
badge.name = I18n.t("badges.helpdesk.name") badge.name = I18n.t("badges.helpdesk.name")