Pārlūkot izejas kodu

Batch inserts to core data

Sam King 1 gadu atpakaļ
vecāks
revīzija
3e6825633b
2 mainītis faili ar 17 papildinājumiem un 4 dzēšanām
  1. 15 2
      Model/JSONImporter.swift
  2. 2 2
      TrioTests/JSONImporterTests.swift

+ 15 - 2
Model/JSONImporter.swift

@@ -74,8 +74,21 @@ class JSONImporter {
         // only import glucose values from the last 24 hours that don't exist
         let glucoseHistory = glucoseHistoryFull
             .filter { $0.dateString >= twentyFourHoursAgo && $0.dateString <= now && !existingDates.contains($0.dateString) }
-        for glucoseEntry in glucoseHistory {
-            try glucoseEntry.store(in: context)
+
+        // Create a background context for batch processing
+        let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
+        backgroundContext.parent = context
+
+        try await backgroundContext.perform {
+            for glucoseEntry in glucoseHistory {
+                try glucoseEntry.store(in: backgroundContext)
+            }
+
+            try backgroundContext.save()
+        }
+
+        try await context.perform {
+            try self.context.save()
         }
     }
 }

+ 2 - 2
TrioTests/JSONImporterTests.swift

@@ -13,7 +13,7 @@ import Testing
 
 class BundleReference {}
 
-@Suite("JSON Importer Tests") struct JSONImporterTests: Injectable {
+@Suite("JSON Importer Tests", .serialized) struct JSONImporterTests: Injectable {
     var coreDataStack: CoreDataStack!
     var context: NSManagedObjectContext!
     var importer: JSONImporter!
@@ -58,7 +58,7 @@ class BundleReference {}
         let path = testBundle.path(forResource: "glucose", ofType: "json")!
         let url = URL(filePath: path)
 
-        // more than 24 hours past the most recent entry
+        // more than 24 hours in the future from the most recent entry
         let now = Date("2025-04-29T19:32:52.000Z")!
         try await importer.importGlucoseHistory(url: url, now: now)