PERF: Reduce records queried in `UserStat.update_first_unread_pm`.

The inefficiency here is that we were previously fetching all the
records from `TopicAllowedUser` before filtering against a limited subset of
users based on `User#last_seen_at`.
This commit is contained in:
Alan Guo Xiang Tan 2021-11-19 10:50:01 +08:00
parent 20f5474be9
commit b8c8909a9d
No known key found for this signature in database
GPG Key ID: 3F656E28E3AADEF1
1 changed files with 28 additions and 33 deletions

View File

@ -22,10 +22,6 @@ class UserStat < ActiveRecord::Base
DB.exec(<<~SQL, archetype: Archetype.private_message, now: UPDATE_UNREAD_MINUTES_AGO.minutes.ago, last_seen: last_seen, limit: limit) DB.exec(<<~SQL, archetype: Archetype.private_message, now: UPDATE_UNREAD_MINUTES_AGO.minutes.ago, last_seen: last_seen, limit: limit)
UPDATE user_stats us UPDATE user_stats us
SET first_unread_pm_at = COALESCE(Z.min_date, :now) SET first_unread_pm_at = COALESCE(Z.min_date, :now)
FROM (
SELECT
Y.user_id,
Y.min_date
FROM ( FROM (
SELECT SELECT
u1.id user_id, u1.id user_id,
@ -47,10 +43,7 @@ class UserStat < ActiveRecord::Base
ELSE t.highest_post_number ELSE t.highest_post_number
END END
AND (COALESCE(tu.notification_level, 1) >= 2) AND (COALESCE(tu.notification_level, 1) >= 2)
GROUP BY tau.user_id AND tau.user_id IN (
) AS X ON X.user_id = u1.id
) AS Y
WHERE Y.user_id IN (
SELECT id SELECT id
FROM users FROM users
WHERE last_seen_at IS NOT NULL WHERE last_seen_at IS NOT NULL
@ -58,6 +51,8 @@ class UserStat < ActiveRecord::Base
ORDER BY last_seen_at DESC ORDER BY last_seen_at DESC
LIMIT :limit LIMIT :limit
) )
GROUP BY tau.user_id
) AS X ON X.user_id = u1.id
) AS Z ) AS Z
WHERE us.user_id = Z.user_id WHERE us.user_id = Z.user_id
SQL SQL