db: add foreign key constraints on all tables.

Add foreign key constraints on all foreign keys on all tables.

These constraints are deferrable so that they're checked at the end of
the transaction, rather at the end of the statement. This is to reduce
lock duration and to allow for cyclic relationships.

Constraints are added in one migration then validated in another so that
the entire table isn't locked against reads and writes while the foreign
key constraints are being validated.

A few tables had invalid foreign keys. Add a fix script to fix these tables:

* A couple artist versions belonged to deleted artists.
* One dmail belonged to a deleted user.
* One forum topic visit belonged to that same deleted user.
* A few dozen note versions belonged to nonexistent posts. This came
  from RaisingK moving notes to different posts years ago, back when it
  was possible for users to set a note's post ID in the API.
* Some uploads had their parent ID set to 0.
This commit is contained in:
evazion
2022-01-09 10:59:27 -06:00
parent 3814aa21b3
commit 5623b139aa
5 changed files with 846 additions and 11 deletions

View File

@@ -1,10 +0,0 @@
#!/usr/bin/env ruby
require_relative "../../config/environment"
Favorite.transaction do
Favorite.left_outer_joins(:post).where("posts.id": nil).destroy_all
print "Commit? (yes/no): "
raise "abort" unless STDIN.readline.chomp == "yes"
end

View File

@@ -0,0 +1,15 @@
#!/usr/bin/env ruby
require_relative "../../config/environment"
ApplicationRecord.transaction do
Favorite.left_outer_joins(:post).where("posts.id": nil).destroy_all
ArtistVersion.left_outer_joins(:artist).where("artists.id": nil).destroy_all
Dmail.left_outer_joins(:owner).where("users.id": nil).destroy_all
ForumTopicVisit.left_outer_joins(:user).where("users.id": nil).destroy_all
NoteVersion.left_outer_joins(:post).where("posts.id": nil).destroy_all
Upload.where(parent_id: 0).update(parent_id: nil)
print "Commit? (yes/no): "
raise "abort" unless STDIN.readline.chomp == "yes"
end