CoreDataStack.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. private var lastToken: NSPersistentHistoryToken?
  30. /// A persistent container to set up the Core Data Stack
  31. lazy var persistentContainer: NSPersistentContainer = {
  32. let container = NSPersistentContainer(name: "Core_Data")
  33. guard let description = container.persistentStoreDescriptions.first else {
  34. fatalError("Failed \(DebuggingIdentifiers.failed) to retrieve a persistent store description")
  35. }
  36. if inMemory {
  37. description.url = URL(fileURLWithPath: "/dev/null")
  38. }
  39. // Enable persistent store remote change notifications
  40. /// - Tag: persistentStoreRemoteChange
  41. description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
  42. // Enable persistent history tracking
  43. /// - Tag: persistentHistoryTracking
  44. description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
  45. container.loadPersistentStores { _, error in
  46. if let error = error as NSError? {
  47. fatalError("Unresolved Error \(DebuggingIdentifiers.failed) \(error), \(error.userInfo)")
  48. }
  49. }
  50. container.viewContext.automaticallyMergesChangesFromParent = false
  51. container.viewContext.name = "viewContext"
  52. /// - Tag: viewContextmergePolicy
  53. container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  54. container.viewContext.undoManager = nil
  55. container.viewContext.shouldDeleteInaccessibleFaults = true
  56. return container
  57. }()
  58. /// Creates and configures a private queue context
  59. private func newTaskContext() -> NSManagedObjectContext {
  60. // Create a private queue context
  61. /// - Tag: newBackgroundContext
  62. let taskContext = persistentContainer.newBackgroundContext()
  63. /// ensure that the background contexts stay in sync with the main context
  64. taskContext.automaticallyMergesChangesFromParent = true
  65. taskContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  66. taskContext.undoManager = nil
  67. return taskContext
  68. }
  69. func fetchPersistentHistory() async {
  70. do {
  71. try await fetchPersistentHistoryTransactionsAndChanges()
  72. } catch {
  73. debugPrint("\(error.localizedDescription)")
  74. }
  75. }
  76. private func fetchPersistentHistoryTransactionsAndChanges() async throws {
  77. let taskContext = newTaskContext()
  78. taskContext.name = "persistentHistoryContext"
  79. debugPrint("Start fetching persistent history changes from the store ... \(DebuggingIdentifiers.inProgress)")
  80. try await taskContext.perform {
  81. // Execute the persistent history change since the last transaction
  82. /// - Tag: fetchHistory
  83. let changeRequest = NSPersistentHistoryChangeRequest.fetchHistory(after: self.lastToken)
  84. let historyResult = try taskContext.execute(changeRequest) as? NSPersistentHistoryResult
  85. if let history = historyResult?.result as? [NSPersistentHistoryTransaction], !history.isEmpty {
  86. self.mergePersistentHistoryChanges(from: history)
  87. return
  88. }
  89. }
  90. }
  91. private func mergePersistentHistoryChanges(from history: [NSPersistentHistoryTransaction]) {
  92. debugPrint("Received \(history.count) persistent history transactions")
  93. // Update view context with objectIDs from history change request
  94. /// - Tag: mergeChanges
  95. let viewContext = persistentContainer.viewContext
  96. viewContext.perform {
  97. for transaction in history {
  98. viewContext.mergeChanges(fromContextDidSave: transaction.objectIDNotification())
  99. self.lastToken = transaction.token
  100. }
  101. }
  102. }
  103. // MARK: - Fetch Requests
  104. // Fetch in background thread
  105. /// - Tag: backgroundFetch
  106. func fetchEntities<T: NSManagedObject>(
  107. ofType type: T.Type,
  108. onContext context: NSManagedObjectContext,
  109. predicate: NSPredicate,
  110. key: String,
  111. ascending: Bool,
  112. fetchLimit: Int? = nil,
  113. batchSize: Int? = nil,
  114. propertiesToFetch: [String]? = nil,
  115. callingFunction: String = #function,
  116. callingClass: String = #fileID
  117. ) -> [T] {
  118. let request = NSFetchRequest<T>(entityName: String(describing: type))
  119. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  120. request.predicate = predicate
  121. if let limit = fetchLimit {
  122. request.fetchLimit = limit
  123. }
  124. if let batchSize = batchSize {
  125. request.fetchBatchSize = batchSize
  126. }
  127. if let propertiesTofetch = propertiesToFetch {
  128. request.propertiesToFetch = propertiesTofetch
  129. request.resultType = .managedObjectResultType
  130. } else {
  131. request.resultType = .managedObjectResultType
  132. }
  133. context.name = "fetchContext"
  134. context.transactionAuthor = "fetchEntities"
  135. var result: [T]?
  136. /// 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
  137. context.performAndWait {
  138. do {
  139. debugPrint(
  140. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
  141. )
  142. result = try context.fetch(request)
  143. } catch let error as NSError {
  144. debugPrint(
  145. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  146. )
  147. }
  148. }
  149. return result ?? []
  150. }
  151. // TODO: -refactor this, currently only the BolusStateModel uses this because we need to fetch in the background, then do calculations and after this update the UI
  152. // Fetch and update UI
  153. /// - Tag: uiFetch
  154. func fetchEntitiesAndUpdateUI<T: NSManagedObject>(
  155. ofType type: T.Type,
  156. predicate: NSPredicate,
  157. key: String,
  158. ascending: Bool,
  159. fetchLimit: Int? = nil,
  160. batchSize: Int? = nil,
  161. propertiesToFetch: [String]? = nil,
  162. callingFunction: String = #function,
  163. callingClass: String = #fileID,
  164. completion: @escaping ([T]) -> Void
  165. ) {
  166. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  167. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  168. request.predicate = predicate
  169. request.resultType = .managedObjectIDResultType
  170. if let limit = fetchLimit {
  171. request.fetchLimit = limit
  172. }
  173. if let batchSize = batchSize {
  174. request.fetchBatchSize = batchSize
  175. }
  176. if let propertiesToFetch = propertiesToFetch {
  177. request.propertiesToFetch = propertiesToFetch
  178. }
  179. let taskContext = newTaskContext()
  180. taskContext.name = "fetchContext"
  181. taskContext.transactionAuthor = "fetchEntities"
  182. // perform fetch in the background
  183. //
  184. // the fetch returns a NSManagedObjectID which can be safely passed to the main queue because they are thread safe
  185. taskContext.perform {
  186. var result: [NSManagedObjectID]?
  187. do {
  188. debugPrint(
  189. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  190. )
  191. result = try taskContext.fetch(request)
  192. } catch let error as NSError {
  193. debugPrint(
  194. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  195. )
  196. }
  197. // change to the main queue to update UI
  198. DispatchQueue.main.async {
  199. if let result = result {
  200. debugPrint(
  201. "Returning fetch result to main thread in \(callingFunction) from \(callingClass) on thread \(Thread.current)"
  202. )
  203. // Convert NSManagedObjectIDs to objects in the main context
  204. let mainContext = CoreDataStack.shared.persistentContainer.viewContext
  205. let mainContextObjects = result.compactMap { mainContext.object(with: $0) as? T }
  206. completion(mainContextObjects)
  207. } else {
  208. debugPrint("Fetch result is nil in \(callingFunction) from \(callingClass) on thread \(Thread.current)")
  209. completion([])
  210. }
  211. }
  212. }
  213. }
  214. // Fetch the NSManagedObjectIDs
  215. // Useful if we need to pass the NSManagedObject to another thread as the objectID is thread safe
  216. /// - Tag: fetchIDs
  217. func fetchNSManagedObjectID<T: NSManagedObject>(
  218. ofType type: T.Type,
  219. predicate: NSPredicate,
  220. key: String,
  221. ascending: Bool,
  222. fetchLimit: Int? = nil,
  223. batchSize: Int? = nil,
  224. propertiesToFetch: [String]? = nil,
  225. callingFunction: String = #function,
  226. callingClass: String = #fileID,
  227. completion: @escaping ([NSManagedObjectID]) -> Void
  228. ) {
  229. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  230. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  231. request.predicate = predicate
  232. request.resultType = .managedObjectIDResultType
  233. if let limit = fetchLimit {
  234. request.fetchLimit = limit
  235. }
  236. if let batchSize = batchSize {
  237. request.fetchBatchSize = batchSize
  238. }
  239. if let propertiesToFetch = propertiesToFetch {
  240. request.propertiesToFetch = propertiesToFetch
  241. }
  242. let taskContext = newTaskContext()
  243. taskContext.name = "fetchContext"
  244. taskContext.transactionAuthor = "fetchEntities"
  245. // Perform fetch in the background
  246. taskContext.perform {
  247. var result: [NSManagedObjectID]?
  248. do {
  249. debugPrint(
  250. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  251. )
  252. result = try taskContext.fetch(request)
  253. } catch let error as NSError {
  254. debugPrint(
  255. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  256. )
  257. }
  258. completion(result ?? [])
  259. }
  260. }
  261. // MARK: - Delete
  262. /// Synchronously delete entries with specified object IDs
  263. /// - Tag: synchronousDelete
  264. func deleteObject(identifiedBy objectIDs: [NSManagedObjectID]) {
  265. let viewContext = persistentContainer.viewContext
  266. debugPrint("Start deleting data from the store ...\(DebuggingIdentifiers.inProgress)")
  267. viewContext.perform {
  268. objectIDs.forEach { objectID in
  269. let entryToDelete = viewContext.object(with: objectID)
  270. viewContext.delete(entryToDelete)
  271. }
  272. }
  273. debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  274. }
  275. /// Asynchronously deletes records
  276. /// - Tag: batchDelete
  277. // func batchDelete<T: NSManagedObject>(_ objects: [T]) async throws {
  278. // let objectIDs = objects.map(\.objectID)
  279. // let taskContext = newTaskContext()
  280. // // Add name and author to identify source of persistent history changes.
  281. // taskContext.name = "deleteContext"
  282. // taskContext.transactionAuthor = "batchDelete"
  283. // debugPrint("Start deleting data from the store... \(DebuggingIdentifiers.inProgress)")
  284. //
  285. // try await taskContext.perform {
  286. // // Execute the batch delete.
  287. // let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: objectIDs)
  288. // guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  289. // let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  290. // let success = batchDeleteResult.result as? Bool, success
  291. // else {
  292. // debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  293. // throw CoreDataError.batchDeleteError
  294. // }
  295. // }
  296. //
  297. // debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  298. // }
  299. }
  300. // MARK: - Save
  301. extension NSManagedObjectContext {
  302. // takes a context as a parameter to be executed either on the main thread or on a background thread
  303. /// - Tag: save
  304. func saveContext(
  305. onContext: NSManagedObjectContext,
  306. callingFunction: String = #function,
  307. callingClass: String = #fileID
  308. ) throws {
  309. do {
  310. guard onContext.hasChanges else { return }
  311. try onContext.save()
  312. debugPrint(
  313. "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
  314. )
  315. } catch let error as NSError {
  316. debugPrint(
  317. "Saving to Core Data failed in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.failed) with error \(error), \(error.userInfo)"
  318. )
  319. throw error
  320. }
  321. }
  322. }