CoreDataStack.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. import CoreData
  2. import Foundation
  3. import OSLog
  4. class CoreDataStack: ObservableObject {
  5. static let shared = CoreDataStack()
  6. static let identifier = "CoreDataStack"
  7. private var notificationToken: NSObjectProtocol?
  8. private let inMemory: Bool
  9. private init(inMemory: Bool = false) {
  10. self.inMemory = inMemory
  11. // Observe Core Data remote change notifications on the queue where the changes were made
  12. notificationToken = Foundation.NotificationCenter.default.addObserver(
  13. forName: .NSPersistentStoreRemoteChange,
  14. object: nil,
  15. queue: nil
  16. ) { _ in
  17. debugPrint("Received a persistent store remote change notification")
  18. Task {
  19. await self.fetchPersistentHistory()
  20. }
  21. }
  22. }
  23. deinit {
  24. if let observer = notificationToken {
  25. Foundation.NotificationCenter.default.removeObserver(observer)
  26. }
  27. }
  28. /// A persistent history token used for fetching transactions from the store
  29. /// Save the last token to User defaults
  30. private var lastToken: NSPersistentHistoryToken? {
  31. get {
  32. UserDefaults.standard.lastHistoryToken
  33. }
  34. set {
  35. UserDefaults.standard.lastHistoryToken = newValue
  36. }
  37. }
  38. /// A persistent container to set up the Core Data Stack
  39. lazy var persistentContainer: NSPersistentContainer = {
  40. let container = NSPersistentContainer(name: "Core_Data")
  41. guard let description = container.persistentStoreDescriptions.first else {
  42. fatalError("Failed \(DebuggingIdentifiers.failed) to retrieve a persistent store description")
  43. }
  44. if inMemory {
  45. description.url = URL(fileURLWithPath: "/dev/null")
  46. }
  47. // Enable persistent store remote change notifications
  48. /// - Tag: persistentStoreRemoteChange
  49. description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
  50. // Enable persistent history tracking
  51. /// - Tag: persistentHistoryTracking
  52. description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
  53. // Enable lightweight migration
  54. /// - Tag: lightweightMigration
  55. description.shouldMigrateStoreAutomatically = true
  56. description.shouldInferMappingModelAutomatically = true
  57. container.loadPersistentStores { _, error in
  58. if let error = error as NSError? {
  59. fatalError("Unresolved Error \(DebuggingIdentifiers.failed) \(error), \(error.userInfo)")
  60. }
  61. }
  62. container.viewContext.automaticallyMergesChangesFromParent = false
  63. container.viewContext.name = "viewContext"
  64. /// - Tag: viewContextmergePolicy
  65. container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  66. container.viewContext.undoManager = nil
  67. container.viewContext.shouldDeleteInaccessibleFaults = true
  68. return container
  69. }()
  70. /// Creates and configures a private queue context
  71. func newTaskContext() -> NSManagedObjectContext {
  72. // Create a private queue context
  73. /// - Tag: newBackgroundContext
  74. let taskContext = persistentContainer.newBackgroundContext()
  75. /// ensure that the background contexts stay in sync with the main context
  76. taskContext.automaticallyMergesChangesFromParent = true
  77. taskContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  78. taskContext.undoManager = nil
  79. return taskContext
  80. }
  81. func fetchPersistentHistory() async {
  82. do {
  83. try await fetchPersistentHistoryTransactionsAndChanges()
  84. } catch {
  85. debugPrint("\(error.localizedDescription)")
  86. }
  87. }
  88. private func fetchPersistentHistoryTransactionsAndChanges() async throws {
  89. let taskContext = newTaskContext()
  90. taskContext.name = "persistentHistoryContext"
  91. debugPrint("Start fetching persistent history changes from the store ... \(DebuggingIdentifiers.inProgress)")
  92. try await taskContext.perform {
  93. // Execute the persistent history change since the last transaction
  94. /// - Tag: fetchHistory
  95. let changeRequest = NSPersistentHistoryChangeRequest.fetchHistory(after: self.lastToken)
  96. let historyResult = try taskContext.execute(changeRequest) as? NSPersistentHistoryResult
  97. if let history = historyResult?.result as? [NSPersistentHistoryTransaction], !history.isEmpty {
  98. self.mergePersistentHistoryChanges(from: history)
  99. return
  100. }
  101. }
  102. }
  103. private func mergePersistentHistoryChanges(from history: [NSPersistentHistoryTransaction]) {
  104. debugPrint("Received \(history.count) persistent history transactions")
  105. // Update view context with objectIDs from history change request
  106. /// - Tag: mergeChanges
  107. let viewContext = persistentContainer.viewContext
  108. viewContext.perform {
  109. for transaction in history {
  110. viewContext.mergeChanges(fromContextDidSave: transaction.objectIDNotification())
  111. self.lastToken = transaction.token
  112. }
  113. }
  114. }
  115. // Clean old Persistent History
  116. /// - Tag: clearHistory
  117. func cleanupPersistentHistoryTokens(before date: Date) async {
  118. let taskContext = newTaskContext()
  119. taskContext.name = "cleanPersistentHistoryTokensContext"
  120. await taskContext.perform {
  121. let deleteHistoryTokensRequest = NSPersistentHistoryChangeRequest.deleteHistory(before: date)
  122. do {
  123. try taskContext.execute(deleteHistoryTokensRequest)
  124. debugPrint("\(DebuggingIdentifiers.succeeded) Successfully deleted persistent history before \(date)")
  125. } catch {
  126. debugPrint(
  127. "\(DebuggingIdentifiers.failed) Failed to delete persistent history before \(date): \(error.localizedDescription)"
  128. )
  129. }
  130. }
  131. }
  132. }
  133. // MARK: - Delete
  134. extension CoreDataStack {
  135. /// Synchronously delete entry with specified object IDs
  136. /// - Tag: synchronousDelete
  137. func deleteObject(identifiedBy objectID: NSManagedObjectID) async {
  138. let viewContext = persistentContainer.viewContext
  139. debugPrint("Start deleting data from the store ...\(DebuggingIdentifiers.inProgress)")
  140. await viewContext.perform {
  141. do {
  142. let entryToDelete = viewContext.object(with: objectID)
  143. viewContext.delete(entryToDelete)
  144. guard viewContext.hasChanges else { return }
  145. try viewContext.save()
  146. debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  147. } catch {
  148. debugPrint("Failed to delete data: \(error.localizedDescription)")
  149. }
  150. }
  151. }
  152. /// Asynchronously deletes records for entities
  153. /// - Tag: batchDelete
  154. func batchDeleteOlderThan<T: NSManagedObject>(_ objectType: T.Type, dateKey: String, days: Int) async throws {
  155. let taskContext = newTaskContext()
  156. taskContext.name = "deleteContext"
  157. taskContext.transactionAuthor = "batchDelete"
  158. // Get the number of days we want to keep the data
  159. let targetDate = Calendar.current.date(byAdding: .day, value: -days, to: Date())!
  160. // Fetch all the objects that are older than the specified days
  161. let fetchRequest = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: objectType))
  162. fetchRequest.predicate = NSPredicate(format: "%K < %@", dateKey, targetDate as NSDate)
  163. fetchRequest.resultType = .managedObjectIDResultType
  164. do {
  165. // Execute the Fetch Request
  166. let objectIDs = try await taskContext.perform {
  167. try taskContext.fetch(fetchRequest)
  168. }
  169. // Guard check if there are NSManagedObjects older than 90 days
  170. guard !objectIDs.isEmpty else {
  171. debugPrint("No objects found older than \(days) days.")
  172. return
  173. }
  174. // Execute the Batch Delete
  175. try await taskContext.perform {
  176. let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: objectIDs)
  177. guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  178. let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  179. let success = batchDeleteResult.result as? Bool, success
  180. else {
  181. debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  182. throw CoreDataError.batchDeleteError
  183. }
  184. }
  185. debugPrint("Successfully deleted data older than \(days) days. \(DebuggingIdentifiers.succeeded)")
  186. } catch {
  187. debugPrint("Failed to fetch or delete data: \(error.localizedDescription) \(DebuggingIdentifiers.failed)")
  188. throw CoreDataError.batchDeleteError
  189. }
  190. }
  191. }
  192. // MARK: - Fetch Requests
  193. extension CoreDataStack {
  194. // Fetch in background thread
  195. /// - Tag: backgroundFetch
  196. func fetchEntities<T: NSManagedObject>(
  197. ofType type: T.Type,
  198. onContext context: NSManagedObjectContext,
  199. predicate: NSPredicate,
  200. key: String,
  201. ascending: Bool,
  202. fetchLimit: Int? = nil,
  203. batchSize: Int? = nil,
  204. propertiesToFetch: [String]? = nil,
  205. callingFunction: String = #function,
  206. callingClass: String = #fileID
  207. ) -> [T] {
  208. let request = NSFetchRequest<T>(entityName: String(describing: type))
  209. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  210. request.predicate = predicate
  211. if let limit = fetchLimit {
  212. request.fetchLimit = limit
  213. }
  214. if let batchSize = batchSize {
  215. request.fetchBatchSize = batchSize
  216. }
  217. if let propertiesTofetch = propertiesToFetch {
  218. request.propertiesToFetch = propertiesTofetch
  219. request.resultType = .managedObjectResultType
  220. } else {
  221. request.resultType = .managedObjectResultType
  222. }
  223. context.name = "fetchContext"
  224. context.transactionAuthor = "fetchEntities"
  225. var result: [T]?
  226. /// we need to ensure that the fetch immediately returns a value as long as the whole app does not use the async await pattern, otherwise we could perform this asynchronously with backgroundContext.perform and not block the thread
  227. context.performAndWait {
  228. do {
  229. debugPrint(
  230. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
  231. )
  232. result = try context.fetch(request)
  233. } catch let error as NSError {
  234. debugPrint(
  235. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  236. )
  237. }
  238. }
  239. return result ?? []
  240. }
  241. // Fetch Async
  242. func fetchEntitiesAsync<T: NSManagedObject>(
  243. ofType type: T.Type,
  244. onContext context: NSManagedObjectContext,
  245. predicate: NSPredicate,
  246. key: String,
  247. ascending: Bool,
  248. fetchLimit: Int? = nil,
  249. batchSize: Int? = nil,
  250. propertiesToFetch: [String]? = nil,
  251. callingFunction: String = #function,
  252. callingClass: String = #fileID
  253. ) async -> [T] {
  254. let request = NSFetchRequest<T>(entityName: String(describing: type))
  255. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  256. request.predicate = predicate
  257. if let limit = fetchLimit {
  258. request.fetchLimit = limit
  259. }
  260. if let batchSize = batchSize {
  261. request.fetchBatchSize = batchSize
  262. }
  263. if let propertiesTofetch = propertiesToFetch {
  264. request.propertiesToFetch = propertiesTofetch
  265. request.resultType = .managedObjectResultType
  266. } else {
  267. request.resultType = .managedObjectResultType
  268. }
  269. context.name = "fetchContext"
  270. context.transactionAuthor = "fetchEntities"
  271. return await context.perform {
  272. do {
  273. debugPrint(
  274. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
  275. )
  276. return try context.fetch(request)
  277. } catch let error as NSError {
  278. debugPrint(
  279. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  280. )
  281. return []
  282. }
  283. }
  284. }
  285. }
  286. // MARK: - Save
  287. /// This function is used when terminating the App to ensure any unsaved changes on the view context made their way to the persistent container
  288. extension CoreDataStack {
  289. func save() {
  290. let context = persistentContainer.viewContext
  291. guard context.hasChanges else { return }
  292. do {
  293. try context.save()
  294. } catch {
  295. debugPrint("Error saving context \(DebuggingIdentifiers.failed): \(error)")
  296. }
  297. }
  298. }
  299. extension NSManagedObjectContext {
  300. // takes a context as a parameter to be executed either on the main thread or on a background thread
  301. /// - Tag: save
  302. func saveContext(
  303. onContext: NSManagedObjectContext,
  304. callingFunction: String = #function,
  305. callingClass: String = #fileID
  306. ) throws {
  307. do {
  308. guard onContext.hasChanges else { return }
  309. try onContext.save()
  310. debugPrint(
  311. "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
  312. )
  313. } catch let error as NSError {
  314. debugPrint(
  315. "Saving to Core Data failed in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.failed) with error \(error), \(error.userInfo)"
  316. )
  317. throw error
  318. }
  319. }
  320. }