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

@ -1184,6 +1184,8 @@ describe Guardian do
end
describe "can_recover_topic?" do
fab!(:topic) { Fabricate(:topic, user: user) }
fab!(:post) { Fabricate(:post, user: user, topic: topic) }
it "returns false for a nil user" do
expect(Guardian.new(nil).can_recover_topic?(topic)).to be_falsey
@ -1198,11 +1200,6 @@ describe Guardian do
end
context 'as a moderator' do
before do
topic.save!
post.save!
end
describe 'when post has been deleted' do
it "should return the right value" do
expect(Guardian.new(moderator).can_recover_topic?(topic)).to be_falsey
@ -1227,9 +1224,6 @@ describe Guardian do
fab!(:group_user) { Fabricate(:group_user) }
before do
topic.save!
post.save!
SiteSetting.enable_category_group_moderation = true
PostDestroyer.new(moderator, topic.first_post).destroy
topic.reload
@ -1262,10 +1256,8 @@ describe Guardian do
end
context 'as a moderator' do
before do
topic.save!
post.save!
end
fab!(:topic) { Fabricate(:topic, user: user) }
fab!(:post) { Fabricate(:post, user: user, topic: topic) }
describe 'when post has been deleted' do
it "should return the right value" do