CoreDataStack.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. Task {
  18. await self.fetchPersistentHistory()
  19. }
  20. }
  21. }
  22. deinit {
  23. if let observer = notificationToken {
  24. Foundation.NotificationCenter.default.removeObserver(observer)
  25. }
  26. }
  27. /// A persistent history token used for fetching transactions from the store
  28. /// Save the last token to User defaults
  29. private var lastToken: NSPersistentHistoryToken? {
  30. get {
  31. UserDefaults.standard.lastHistoryToken
  32. }
  33. set {
  34. UserDefaults.standard.lastHistoryToken = newValue
  35. }
  36. }
  37. // Factory method for tests
  38. static func createForTests() -> CoreDataStack {
  39. CoreDataStack(inMemory: true)
  40. }
  41. // Used for Canvas Preview
  42. static var preview: CoreDataStack = {
  43. let stack = CoreDataStack(inMemory: true)
  44. let context = stack.persistentContainer.viewContext
  45. let pumpHistory = PumpEventStored.makePreviewEvents(count: 10, provider: stack)
  46. return stack
  47. }()
  48. // Shared managed object model
  49. static var managedObjectModel: NSManagedObjectModel = {
  50. let bundle = Bundle(for: CoreDataStack.self)
  51. guard let url = bundle.url(forResource: "TrioCoreDataPersistentContainer", withExtension: "momd") else {
  52. fatalError("Failed \(DebuggingIdentifiers.failed) to locate momd file")
  53. }
  54. guard let model = NSManagedObjectModel(contentsOf: url) else {
  55. fatalError("Failed \(DebuggingIdentifiers.failed) to load momd file")
  56. }
  57. return model
  58. }()
  59. /// A persistent container to set up the Core Data Stack
  60. lazy var persistentContainer: NSPersistentContainer = {
  61. // Use shared model instead of loading a new one
  62. let container = NSPersistentContainer(
  63. name: "TrioCoreDataPersistentContainer",
  64. managedObjectModel: Self.managedObjectModel
  65. )
  66. guard let description = container.persistentStoreDescriptions.first else {
  67. fatalError("Failed \(DebuggingIdentifiers.failed) to retrieve a persistent store description")
  68. }
  69. if inMemory {
  70. description.url = URL(fileURLWithPath: "/dev/null")
  71. }
  72. // Enable persistent store remote change notifications
  73. /// - Tag: persistentStoreRemoteChange
  74. description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
  75. // Enable persistent history tracking
  76. /// - Tag: persistentHistoryTracking
  77. description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
  78. // Enable lightweight migration
  79. /// - Tag: lightweightMigration
  80. description.shouldMigrateStoreAutomatically = true
  81. description.shouldInferMappingModelAutomatically = true
  82. container.loadPersistentStores { _, error in
  83. if let error = error as NSError? {
  84. fatalError("Unresolved Error \(DebuggingIdentifiers.failed) \(error), \(error.userInfo)")
  85. }
  86. }
  87. container.viewContext.automaticallyMergesChangesFromParent = false
  88. container.viewContext.name = "viewContext"
  89. /// - Tag: viewContextmergePolicy
  90. container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  91. container.viewContext.undoManager = nil
  92. container.viewContext.shouldDeleteInaccessibleFaults = true
  93. return container
  94. }()
  95. /// Creates and configures a private queue context
  96. func newTaskContext() -> NSManagedObjectContext {
  97. // Create a private queue context
  98. /// - Tag: newBackgroundContext
  99. let taskContext = persistentContainer.newBackgroundContext()
  100. /// ensure that the background contexts stay in sync with the main context
  101. taskContext.automaticallyMergesChangesFromParent = false
  102. taskContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  103. taskContext.undoManager = nil
  104. return taskContext
  105. }
  106. func fetchPersistentHistory() async {
  107. do {
  108. try await fetchPersistentHistoryTransactionsAndChanges()
  109. } catch {
  110. debugPrint("\(error.localizedDescription)")
  111. }
  112. }
  113. private func fetchPersistentHistoryTransactionsAndChanges() async throws {
  114. let taskContext = newTaskContext()
  115. taskContext.name = "persistentHistoryContext"
  116. // debugPrint("Start fetching persistent history changes from the store ... \(DebuggingIdentifiers.inProgress)")
  117. try await taskContext.perform {
  118. // Execute the persistent history change since the last transaction
  119. /// - Tag: fetchHistory
  120. let changeRequest = NSPersistentHistoryChangeRequest.fetchHistory(after: self.lastToken)
  121. let historyResult = try taskContext.execute(changeRequest) as? NSPersistentHistoryResult
  122. if let history = historyResult?.result as? [NSPersistentHistoryTransaction], !history.isEmpty {
  123. self.mergePersistentHistoryChanges(from: history)
  124. return
  125. }
  126. }
  127. }
  128. private func mergePersistentHistoryChanges(from history: [NSPersistentHistoryTransaction]) {
  129. // debugPrint("Received \(history.count) persistent history transactions")
  130. // Update view context with objectIDs from history change request
  131. /// - Tag: mergeChanges
  132. let viewContext = persistentContainer.viewContext
  133. viewContext.perform {
  134. for transaction in history {
  135. viewContext.mergeChanges(fromContextDidSave: transaction.objectIDNotification())
  136. self.lastToken = transaction.token
  137. }
  138. }
  139. }
  140. // Clean old Persistent History
  141. /// - Tag: clearHistory
  142. func cleanupPersistentHistoryTokens(before date: Date) async {
  143. let taskContext = newTaskContext()
  144. taskContext.name = "cleanPersistentHistoryTokensContext"
  145. await taskContext.perform {
  146. let deleteHistoryTokensRequest = NSPersistentHistoryChangeRequest.deleteHistory(before: date)
  147. do {
  148. try taskContext.execute(deleteHistoryTokensRequest)
  149. debugPrint("\(DebuggingIdentifiers.succeeded) Successfully deleted persistent history before \(date)")
  150. } catch {
  151. debugPrint(
  152. "\(DebuggingIdentifiers.failed) Failed to delete persistent history before \(date): \(error.localizedDescription)"
  153. )
  154. }
  155. }
  156. }
  157. }
  158. // MARK: - Delete
  159. extension CoreDataStack {
  160. /// Synchronously delete entry with specified object IDs
  161. /// - Tag: synchronousDelete
  162. func deleteObject(identifiedBy objectID: NSManagedObjectID) async {
  163. let viewContext = persistentContainer.viewContext
  164. debugPrint("Start deleting data from the store ...\(DebuggingIdentifiers.inProgress)")
  165. await viewContext.perform {
  166. do {
  167. let entryToDelete = viewContext.object(with: objectID)
  168. viewContext.delete(entryToDelete)
  169. guard viewContext.hasChanges else { return }
  170. try viewContext.save()
  171. debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  172. } catch {
  173. debugPrint("Failed to delete data: \(error.localizedDescription)")
  174. }
  175. }
  176. }
  177. /// Asynchronously deletes records for entities
  178. /// - Tag: batchDelete
  179. func batchDeleteOlderThan<T: NSManagedObject>(
  180. _ objectType: T.Type,
  181. dateKey: String,
  182. days: Int,
  183. isPresetKey: String? = nil
  184. ) async throws {
  185. let taskContext = newTaskContext()
  186. taskContext.name = "deleteContext"
  187. taskContext.transactionAuthor = "batchDelete"
  188. // Get the number of days we want to keep the data
  189. let targetDate = Calendar.current.date(byAdding: .day, value: -days, to: Date())!
  190. // Fetch all the objects that are older than the specified days
  191. let fetchRequest = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: objectType))
  192. // Construct the predicate
  193. var predicates: [NSPredicate] = [NSPredicate(format: "%K < %@", dateKey, targetDate as NSDate)]
  194. if let isPresetKey = isPresetKey {
  195. predicates.append(NSPredicate(format: "%K == NO", isPresetKey))
  196. }
  197. fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
  198. fetchRequest.resultType = .managedObjectIDResultType
  199. do {
  200. // Execute the Fetch Request
  201. let objectIDs = try await taskContext.perform {
  202. try taskContext.fetch(fetchRequest)
  203. }
  204. // Guard check if there are NSManagedObjects older than the specified days
  205. guard !objectIDs.isEmpty else {
  206. // debugPrint("No objects found older than \(days) days.")
  207. return
  208. }
  209. // Execute the Batch Delete
  210. try await taskContext.perform {
  211. let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: objectIDs)
  212. guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  213. let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  214. let success = batchDeleteResult.result as? Bool, success
  215. else {
  216. debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  217. throw CoreDataError.batchDeleteError
  218. }
  219. }
  220. debugPrint("Successfully deleted data older than \(days) days. \(DebuggingIdentifiers.succeeded)")
  221. } catch {
  222. debugPrint("Failed to fetch or delete data: \(error.localizedDescription) \(DebuggingIdentifiers.failed)")
  223. throw CoreDataError.batchDeleteError
  224. }
  225. }
  226. func batchDeleteOlderThan<Parent: NSManagedObject, Child: NSManagedObject>(
  227. parentType: Parent.Type,
  228. childType: Child.Type,
  229. dateKey: String,
  230. days: Int,
  231. relationshipKey: String // The key of the Child Entity that links to the parent Entity
  232. ) async throws {
  233. let taskContext = newTaskContext()
  234. taskContext.name = "deleteContext"
  235. taskContext.transactionAuthor = "batchDelete"
  236. // Get the target date
  237. let targetDate = Calendar.current.date(byAdding: .day, value: -days, to: Date())!
  238. // Fetch Parent objects older than the target date
  239. let fetchParentRequest = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: parentType))
  240. fetchParentRequest.predicate = NSPredicate(format: "%K < %@", dateKey, targetDate as NSDate)
  241. fetchParentRequest.resultType = .managedObjectIDResultType
  242. do {
  243. let parentObjectIDs = try await taskContext.perform {
  244. try taskContext.fetch(fetchParentRequest)
  245. }
  246. guard !parentObjectIDs.isEmpty else {
  247. // debugPrint("No \(parentType) objects found older than \(days) days.")
  248. return
  249. }
  250. // Fetch Child objects related to the fetched Parent objects
  251. let fetchChildRequest = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: childType))
  252. fetchChildRequest.predicate = NSPredicate(format: "ANY %K IN %@", relationshipKey, parentObjectIDs)
  253. fetchChildRequest.resultType = .managedObjectIDResultType
  254. let childObjectIDs = try await taskContext.perform {
  255. try taskContext.fetch(fetchChildRequest)
  256. }
  257. guard !childObjectIDs.isEmpty else {
  258. // debugPrint("No \(childType) objects found related to \(parentType) objects older than \(days) days.")
  259. return
  260. }
  261. // Execute the batch delete for Child objects
  262. try await taskContext.perform {
  263. let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: childObjectIDs)
  264. guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  265. let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  266. let success = batchDeleteResult.result as? Bool, success
  267. else {
  268. debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  269. throw CoreDataError.batchDeleteError
  270. }
  271. }
  272. debugPrint(
  273. "Successfully deleted \(childType) data related to \(parentType) objects older than \(days) days. \(DebuggingIdentifiers.succeeded)"
  274. )
  275. } catch {
  276. debugPrint("Failed to fetch or delete data: \(error.localizedDescription) \(DebuggingIdentifiers.failed)")
  277. throw CoreDataError.batchDeleteError
  278. }
  279. }
  280. }
  281. // MARK: - Fetch Requests
  282. extension CoreDataStack {
  283. // Fetch in background thread
  284. /// - Tag: backgroundFetch
  285. func fetchEntities<T: NSManagedObject>(
  286. ofType type: T.Type,
  287. onContext context: NSManagedObjectContext,
  288. predicate: NSPredicate,
  289. key: String,
  290. ascending: Bool,
  291. fetchLimit: Int? = nil,
  292. batchSize: Int? = nil,
  293. propertiesToFetch: [String]? = nil,
  294. callingFunction: String = #function,
  295. callingClass: String = #fileID
  296. ) -> [Any] {
  297. let request = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: type))
  298. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  299. request.predicate = predicate
  300. if let limit = fetchLimit {
  301. request.fetchLimit = limit
  302. }
  303. if let batchSize = batchSize {
  304. request.fetchBatchSize = batchSize
  305. }
  306. if let propertiesToFetch = propertiesToFetch {
  307. request.propertiesToFetch = propertiesToFetch
  308. request.resultType = .dictionaryResultType
  309. } else {
  310. request.resultType = .managedObjectResultType
  311. }
  312. context.name = "fetchContext"
  313. context.transactionAuthor = "fetchEntities"
  314. /// 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
  315. return context.performAndWait {
  316. do {
  317. if propertiesToFetch != nil {
  318. return try context.fetch(request) as? [[String: Any]] ?? []
  319. } else {
  320. return try context.fetch(request) as? [T] ?? []
  321. }
  322. } catch let error as NSError {
  323. debugPrint(
  324. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  325. )
  326. return []
  327. }
  328. }
  329. }
  330. // Fetch Async
  331. func fetchEntitiesAsync<T: NSManagedObject>(
  332. ofType type: T.Type,
  333. onContext context: NSManagedObjectContext,
  334. predicate: NSPredicate,
  335. key: String,
  336. ascending: Bool,
  337. fetchLimit: Int? = nil,
  338. batchSize: Int? = nil,
  339. propertiesToFetch: [String]? = nil,
  340. relationshipKeyPathsForPrefetching: [String]? = nil,
  341. callingFunction: String = #function,
  342. callingClass: String = #fileID
  343. ) async -> Any {
  344. let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: String(describing: type))
  345. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  346. request.predicate = predicate
  347. if let limit = fetchLimit {
  348. request.fetchLimit = limit
  349. }
  350. if let batchSize = batchSize {
  351. request.fetchBatchSize = batchSize
  352. }
  353. if let propertiesToFetch = propertiesToFetch {
  354. request.propertiesToFetch = propertiesToFetch
  355. request.resultType = .dictionaryResultType
  356. } else {
  357. request.resultType = .managedObjectResultType
  358. }
  359. if let prefetchKeyPaths = relationshipKeyPathsForPrefetching {
  360. request.relationshipKeyPathsForPrefetching = prefetchKeyPaths
  361. }
  362. context.name = "fetchContext"
  363. context.transactionAuthor = "fetchEntities"
  364. return await context.perform {
  365. do {
  366. if propertiesToFetch != nil {
  367. return try context.fetch(request) as? [[String: Any]] ?? []
  368. } else {
  369. return try context.fetch(request) as? [T] ?? []
  370. }
  371. } catch let error as NSError {
  372. debugPrint(
  373. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  374. )
  375. return []
  376. }
  377. }
  378. }
  379. // Get NSManagedObject
  380. func getNSManagedObject<T: NSManagedObject>(
  381. with ids: [NSManagedObjectID],
  382. context: NSManagedObjectContext
  383. ) async -> [T] {
  384. await context.perform {
  385. var objects = [T]()
  386. do {
  387. for id in ids {
  388. if let object = try context.existingObject(with: id) as? T {
  389. objects.append(object)
  390. }
  391. }
  392. } catch {
  393. debugPrint("Failed to fetch objects: \(error.localizedDescription)")
  394. }
  395. return objects
  396. }
  397. }
  398. }
  399. // MARK: - Save
  400. /// This function is used when terminating the App to ensure any unsaved changes on the view context made their way to the persistent container
  401. extension CoreDataStack {
  402. func save() {
  403. let context = persistentContainer.viewContext
  404. guard context.hasChanges else { return }
  405. do {
  406. try context.save()
  407. } catch {
  408. debugPrint("Error saving context \(DebuggingIdentifiers.failed): \(error)")
  409. }
  410. }
  411. }
  412. extension NSManagedObjectContext {
  413. // takes a context as a parameter to be executed either on the main thread or on a background thread
  414. /// - Tag: save
  415. func saveContext(
  416. onContext: NSManagedObjectContext,
  417. callingFunction: String = #function,
  418. callingClass: String = #fileID
  419. ) throws {
  420. do {
  421. guard onContext.hasChanges else { return }
  422. try onContext.save()
  423. // debugPrint(
  424. // "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
  425. // )
  426. } catch let error as NSError {
  427. debugPrint(
  428. "Saving to Core Data failed in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.failed) with error \(error), \(error.userInfo)"
  429. )
  430. throw error
  431. }
  432. }
  433. }