From 8006b0add965552fef95e29b9dd97fd73da51c7c Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Wed, 20 Nov 2024 00:46:13 -0500 Subject: [PATCH] Prune DraftAttachment managed objects from drafts persistent store --- .../CoreData/DraftsPersistentContainer.swift | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/Packages/ComposeUI/Sources/ComposeUI/CoreData/DraftsPersistentContainer.swift b/Packages/ComposeUI/Sources/ComposeUI/CoreData/DraftsPersistentContainer.swift index 06c4679d..c4a5a3ab 100644 --- a/Packages/ComposeUI/Sources/ComposeUI/CoreData/DraftsPersistentContainer.swift +++ b/Packages/ComposeUI/Sources/ComposeUI/CoreData/DraftsPersistentContainer.swift @@ -170,17 +170,26 @@ public class DraftsPersistentContainer: NSPersistentContainer { return } performBackgroundTask { context in + let orphanedAttachmentsReq: NSFetchRequest = DraftAttachment.fetchRequest() + orphanedAttachmentsReq.predicate = NSPredicate(format: "draft == nil") + let deleteReq = NSBatchDeleteRequest(fetchRequest: orphanedAttachmentsReq) + do { + try context.execute(deleteReq) + } catch { + logger.error("Failed to remove orphaned attachments: \(String(describing: error), privacy: .public)") + } + let allAttachmentsReq = DraftAttachment.fetchRequest() allAttachmentsReq.predicate = NSPredicate(format: "fileURL != nil") guard let allAttachments = try? context.fetch(allAttachmentsReq) else { return } - let orphaned = Set(files).subtracting(allAttachments.lazy.compactMap(\.fileURL)) - for url in orphaned { + let orphanedFiles = Set(files).subtracting(allAttachments.lazy.compactMap(\.fileURL)) + for url in orphanedFiles { do { try FileManager.default.removeItem(at: url) } catch { - logger.error("Failed to remove orphaned attachment: \(String(describing: error), privacy: .public)") + logger.error("Failed to remove orphaned attachment files: \(String(describing: error), privacy: .public)") } } completion()