diff --git a/server/commands/documentPermanentDeleter.test.ts b/server/commands/documentPermanentDeleter.test.ts index af6809bfca..d75b3f4980 100644 --- a/server/commands/documentPermanentDeleter.test.ts +++ b/server/commands/documentPermanentDeleter.test.ts @@ -1,7 +1,11 @@ import { subDays } from "date-fns"; import { errToString } from "@shared/utils/error"; import { Attachment, Document } from "@server/models"; -import { buildAttachment, buildDocument } from "@server/test/factories"; +import { + buildAttachment, + buildDocument, + buildDraftDocument, +} from "@server/test/factories"; import { mockTaskSchedule } from "@server/test/support"; import documentPermanentDeleter from "./documentPermanentDeleter"; @@ -154,6 +158,23 @@ describe("documentPermanentDeleter", () => { expect(child.parentDocumentId).toEqual(parent.id); }); + it("should detach draft children rather than cascade delete them", async () => { + const parent = await buildDocument({ + publishedAt: subDays(new Date(), 90), + deletedAt: subDays(new Date(), 60), + }); + const child = await buildDraftDocument({ + teamId: parent.teamId, + parentDocumentId: parent.id, + }); + + const countDeletedDoc = await documentPermanentDeleter([parent]); + expect(countDeletedDoc).toEqual(1); + + const reloaded = await Document.unscoped().findByPk(child.id); + expect(reloaded?.parentDocumentId).toEqual(null); + }); + it("should not destroy attachments referenced in other documents", async () => { const document1 = await buildDocument(); const document = await buildDocument({ diff --git a/server/commands/documentPermanentDeleter.ts b/server/commands/documentPermanentDeleter.ts index 2634b51aad..6432d055e7 100644 --- a/server/commands/documentPermanentDeleter.ts +++ b/server/commands/documentPermanentDeleter.ts @@ -93,7 +93,9 @@ export default async function documentPermanentDeleter(documents: Document[]) { const deletedIds = stillDeleted.map((document) => document.id); for (const batch of chunk(deletedIds, 100)) { - await Document.update( + // Unscoped so that drafts and templates are detached too, otherwise the + // destroy below cascades and removes them. + await Document.unscoped().update( { parentDocumentId: null, },