discourse/db/migrate/20220118065658_add_constraints_to_user_stat.rb
Alan Guo Xiang Tan 5bd55acf83
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`.
2022-02-07 11:23:34 +08:00

26 lines
671 B
Ruby

# frozen_string_literal: true
class AddConstraintsToUserStat < ActiveRecord::Migration[6.1]
def up
execute(<<~SQL)
UPDATE user_stats
SET post_count = 0
WHERE post_count < 0
SQL
execute(<<~SQL)
UPDATE user_stats
SET topic_count = 0
WHERE topic_count < 0
SQL
execute "ALTER TABLE user_stats ADD CONSTRAINT topic_count_positive CHECK (topic_count >= 0)"
execute "ALTER TABLE user_stats ADD CONSTRAINT post_count_positive CHECK (post_count >= 0)"
end
def down
execute "ALTER TABLE user_stats DROP CONSTRAINT topic_count_positive"
execute "ALTER TABLE user_stats DROP CONSTRAINT post_count_positive"
end
end