Prune DraftAttachment managed objects from drafts persistent store

This commit is contained in:
Shadowfacts 2024-11-20 00:46:13 -05:00
parent b9e3d8ec5e
commit 8006b0add9
1 changed files with 12 additions and 3 deletions

View File

@ -170,17 +170,26 @@ public class DraftsPersistentContainer: NSPersistentContainer {
return return
} }
performBackgroundTask { context in performBackgroundTask { context in
let orphanedAttachmentsReq: NSFetchRequest<any NSFetchRequestResult> = 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() let allAttachmentsReq = DraftAttachment.fetchRequest()
allAttachmentsReq.predicate = NSPredicate(format: "fileURL != nil") allAttachmentsReq.predicate = NSPredicate(format: "fileURL != nil")
guard let allAttachments = try? context.fetch(allAttachmentsReq) else { guard let allAttachments = try? context.fetch(allAttachmentsReq) else {
return return
} }
let orphaned = Set(files).subtracting(allAttachments.lazy.compactMap(\.fileURL)) let orphanedFiles = Set(files).subtracting(allAttachments.lazy.compactMap(\.fileURL))
for url in orphaned { for url in orphanedFiles {
do { do {
try FileManager.default.removeItem(at: url) try FileManager.default.removeItem(at: url)
} catch { } 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() completion()