Skip to content

A platform for community discussion. Free, open, simple.

DEV: Delete upload references on draft cleanup (#26877)

Ted Johansson9655bf3e24c7
diff --git a/app/models/draft.rb b/app/models/draft.rb
index 1f759d4e2cf..8e97aaf512a 100644
--- a/app/models/draft.rb
+++ b/app/models/draft.rb
@@ -237,19 +237,18 @@ class Draft < ActiveRecord::Base
end
def self.cleanup!
- DB.exec(<<~SQL)
- DELETE FROM drafts
- WHERE sequence < (
+ Draft.where(<<~SQL).in_batches(of: 100).destroy_all
+ sequence < (
SELECT MAX(s.sequence)
FROM draft_sequences s
- WHERE s.draft_key = drafts.draft_key
- AND s.user_id = drafts.user_id
+ WHERE s.draft_key = drafts.draft_key
+ AND s.user_id = drafts.user_id
)
SQL
# remove old drafts
delete_drafts_older_than_n_days = SiteSetting.delete_drafts_older_than_n_days.days.ago
- Draft.where("updated_at < ?", delete_drafts_older_than_n_days).destroy_all
+ Draft.where("updated_at < ?", delete_drafts_older_than_n_days).in_batches(of: 100).destroy_all
UserStat.update_draft_count
end
diff --git a/db/post_migrate/20240506035024_clear_orphaned_draft_upload_references.rb b/db/post_migrate/20240506035024_clear_orphaned_draft_upload_references.rb
new file mode 100644
index 00000000000..a349aa073c0
--- /dev/null
+++ b/db/post_migrate/20240506035024_clear_orphaned_draft_upload_references.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+class ClearOrphanedDraftUploadReferences < ActiveRecord::Migration[7.0]
+ def up
+ execute <<~SQL
+ DELETE
+ FROM
+ "upload_references"
+ WHERE
+ "upload_references"."target_type" = 'Draft' AND
+ "upload_references"."target_id" NOT IN (
+ SELECT "drafts"."id" FROM "drafts"
+ )
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/spec/models/draft_spec.rb b/spec/models/draft_spec.rb
index daa0a205f1c..cf7ce63e247 100644
--- a/spec/models/draft_spec.rb
+++ b/spec/models/draft_spec.rb
@@ -133,6 +133,7 @@ RSpec.describe Draft do
key = Draft::NEW_TOPIC
Draft.set(user, key, 0, "draft")
+
Draft.cleanup!
expect(Draft.count).to eq 1
expect(user.user_stat.draft_count).to eq(1)
@@ -142,10 +143,16 @@ RSpec.describe Draft do
Draft.set(user, key, seq, "draft")
DraftSequence.update_all("sequence = sequence + 1")
+ draft = Draft.first
+ draft.upload_references << UploadReference.create!(target: draft, upload: Fabricate(:upload))
+
+ expect(UploadReference.count).to eq(1)
+
Draft.cleanup!
expect(Draft.count).to eq 0
expect(user.reload.user_stat.draft_count).to eq(0)
+ expect(UploadReference.count).to eq(0)
Draft.set(Fabricate(:user), Draft::NEW_TOPIC, 0, "draft")