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.rbindex 1f759d4e2cf..8e97aaf512a 100644--- a/app/models/draft.rb+++ b/app/models/draft.rb@@ -237,19 +237,18 @@ class Draft < ActiveRecord::Baseenddef 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 draftsdelete_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_allUserStat.update_draft_countenddiff --git a/db/post_migrate/20240506035024_clear_orphaned_draft_upload_references.rb b/db/post_migrate/20240506035024_clear_orphaned_draft_upload_references.rbnew file mode 100644index 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+enddiff --git a/spec/models/draft_spec.rb b/spec/models/draft_spec.rbindex daa0a205f1c..cf7ce63e247 100644--- a/spec/models/draft_spec.rb+++ b/spec/models/draft_spec.rb@@ -133,6 +133,7 @@ RSpec.describe Draft dokey = Draft::NEW_TOPICDraft.set(user, key, 0, "draft")+Draft.cleanup!expect(Draft.count).to eq 1expect(user.user_stat.draft_count).to eq(1)@@ -142,10 +143,16 @@ RSpec.describe Draft doDraft.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 0expect(user.reload.user_stat.draft_count).to eq(0)+ expect(UploadReference.count).to eq(0)Draft.set(Fabricate(:user), Draft::NEW_TOPIC, 0, "draft")