CoreDataStack.swift 15 KB

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