mirror of
https://github.com/discourse/discourse.git
synced 2025-02-25 18:55:32 -06:00
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:
@@ -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
|
||||
Reference in New Issue
Block a user