FIX: Add DB constraints for post & topic counter cache for UserStat (#15626)

Ensures that `UserStat#post_count` and `UserStat#topic_count` does not
go below 0. When it does like it did now, we tend to have bugs in our
code since we're usually coding with the assumption that the count isn't
negative.

In order to support the constraints, our post and topic fabricators in
tests will now automatically increment the count for the respective
user's `UserStat` as well. We have to do this because our fabricators
bypasss `PostCreator` which holds the responsibility of updating `UserStat#post_count` and
`UserStat#topic_count`.
This commit is contained in:
Alan Guo Xiang Tan
2022-02-07 11:23:34 +08:00
committed by GitHub
parent 81e175e6ba
commit 5bd55acf83
19 changed files with 167 additions and 113 deletions

View File

@ -599,15 +599,10 @@ class PostCreator
@user.create_user_stat if @user.user_stat.nil?
if @user.user_stat.first_post_created_at.nil?
@user.user_stat.first_post_created_at = @post.created_at
@user.user_stat.update!(first_post_created_at: @post.created_at)
end
unless @post.topic.private_message?
@user.user_stat.post_count += 1 if @post.post_type == Post.types[:regular] && !@post.is_first_post?
@user.user_stat.topic_count += 1 if @post.is_first_post?
end
@user.user_stat.save!
UserStatCountUpdater.increment!(@post)
if !@topic.private_message? && @post.post_type != Post.types[:whisper]
@user.update(last_posted_at: @post.created_at)