FIX: Destroy Drafts when increasing sequences (#27739)

Drafts used to be deleted instead of being destroyed. The callbacks that
clean up the upload references were not being called. As a result, the
upload references were not cleaned up and uploads were not deleted
either. This has been partially fixed in 9655bf3e.
This commit is contained in:
Bianca Nenciu
2024-07-10 10:43:11 +03:00
committed by GitHub
parent acc8b46d51
commit 6591a0654b
3 changed files with 45 additions and 11 deletions

View File

@ -20,12 +20,7 @@ class DraftSequence < ActiveRecord::Base
RETURNING sequence RETURNING sequence
SQL SQL
DB.exec( Draft.where(user_id: user_id).where(draft_key: key).where("sequence < ?", sequence).destroy_all
"DELETE FROM drafts WHERE user_id = :user_id AND draft_key = :draft_key AND sequence < :sequence",
draft_key: key,
user_id: user_id,
sequence: sequence,
)
UserStat.update_draft_count(user_id) UserStat.update_draft_count(user_id)

View File

@ -0,0 +1,20 @@
# frozen_string_literal: true
class ClearOrphanedDraftUploadReferences2 < ActiveRecord::Migration[7.1]
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

View File

@ -2,6 +2,7 @@
RSpec.describe DraftSequence do RSpec.describe DraftSequence do
fab!(:user) fab!(:user)
fab!(:upload)
describe ".next" do describe ".next" do
it "should produce next sequence for a key" do it "should produce next sequence for a key" do
@ -14,11 +15,29 @@ RSpec.describe DraftSequence do
2.times { expect(DraftSequence.next!(user, "test")).to eq(0) } 2.times { expect(DraftSequence.next!(user, "test")).to eq(0) }
end end
it "updates draft count" do it "deletes old drafts and associated upload references" do
Draft.create!(user: user, draft_key: "test", data: {}) Draft.set(
expect(user.reload.user_stat.draft_count).to eq(1) user,
expect(DraftSequence.next!(user, "test")).to eq 1 Draft::NEW_TOPIC,
expect(user.reload.user_stat.draft_count).to eq(0) 0,
{
reply: "[#{upload.original_filename}|attachment](#{upload.short_url})",
action: "createTopic",
title: "New topic with an upload",
categoryId: 1,
tags: [],
archetypeId: "regular",
metaData: nil,
composerTime: 10_000,
typingTime: 10_000,
}.to_json,
)
expect { DraftSequence.next!(user, Draft::NEW_TOPIC) }.to change { Draft.count }.by(
-1,
).and change { UploadReference.count }.by(-1).and change {
user.reload.user_stat.draft_count
}.by(-1)
end end
end end