PERF: Cache user badge count in user_stats table (#8610)

This means that we no longer need to run a `count()` on the user_badges table when serializing a user
This commit is contained in:
David Taylor
2019-12-30 11:19:59 +00:00
committed by GitHub
parent c15d702ae6
commit 9348d2cfdf
6 changed files with 99 additions and 1 deletions

View File

@@ -0,0 +1,19 @@
# frozen_string_literal: true
class AddDistinctBadgeCountToUserStats < ActiveRecord::Migration[6.0]
def change
add_column :user_stats, :distinct_badge_count, :integer, default: 0, null: false
execute <<~SQL
UPDATE user_stats
SET distinct_badge_count = x.distinct_badge_count
FROM (
SELECT users.id user_id, COUNT(distinct user_badges.badge_id) distinct_badge_count
FROM users
LEFT JOIN user_badges ON user_badges.user_id = users.id
AND (user_badges.badge_id IN (SELECT id FROM badges WHERE enabled))
GROUP BY users.id
) x
WHERE user_stats.user_id = x.user_id AND user_stats.distinct_badge_count <> x.distinct_badge_count
SQL
end
end