Swift Core数据迁移崩溃:从(null)中选择“最大(z_pk)”中的语法错误

发布于 2025-02-01 18:24:24 字数 5617 浏览 2 评论 0原文

我正在通过测试项目尝试核心数据,并且在核心数据和迁移方面面临一些问题。在轻巧的自动迁移过程中,发生崩溃以下:

 [logging] near "null": syntax error in "SELECT MAX(Z_PK) FROM (null)"



[error] error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134110)
CoreData: error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134110)
CoreData: annotation: userInfo:
CoreData: annotation:   sourceURL : file:///var/mobile/Containers/Data/Application/D712273A-6E49-4B19-9919-3E55F6A5A37D/Library/Application%20Support/TestApp.sqlite
CoreData: annotation:   reason : Cannot migrate store in-place: near "null": syntax error
CoreData: annotation:   destinationURL : file:///var/mobile/Containers/Data/Application/D712273A-6E49-4B19-9919-3E55F6A5A37D/Library/Application%20Support/TestApp.sqlite
CoreData: annotation:   NSUnderlyingError : Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." UserInfo={reason=near "null": syntax error, NSSQLiteErrorDomain=1, NSUnderlyingException=near "null": syntax error}
CoreData: annotation: storeType: SQLite
CoreData: annotation: configuration: (null)
CoreData: annotation: URL: file:///var/mobile/Containers/Data/Application/D712273A-6E49-4B19-9919-3E55F6A5A37D/Library/Application%20Support/TestApp.sqlite
CoreData: annotation: options:
CoreData: annotation:   NSInferMappingModelAutomaticallyOption : 1
CoreData: annotation:   NSMigratePersistentStoresAutomaticallyOption : 1
CoreData: annotation:   NSPersistentStoreFileProtectionKey : NSFileProtectionComplete
CoreData: annotation: <NSPersistentStoreCoordinator: 0x281cf1500>: Attempting recovery from error encountered during addPersistentStore: Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration."

这是用于在SwiftUi应用中加载数据库的PersistenCecointainer的代码:

struct PersistenceController {
    static let shared = PersistenceController()

    static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext
        for _ in 0..<10 {
            let newItem = Relation(context: viewContext)
            newItem.date = Date()
        }
        do {
            try viewContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
        return result
    }()

    var container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "TestApp")
        
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        
        if let storeDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first {
                let sqliteURL = storeDirectory.appendingPathComponent("TestApp.sqlite")
                
                //Set Protection for Core data sql file
                let description = NSPersistentStoreDescription(url: sqliteURL)
                description.shouldInferMappingModelAutomatically = true
                description.shouldMigrateStoreAutomatically = true
                description.setOption(FileProtectionType.complete as NSObject, forKey: NSPersistentStoreFileProtectionKey)
                container.persistentStoreDescriptions = [description]
            }
        
       
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
        
    }
    
    
}

这更多是关于我要更改的模型。我有一个名为“合作伙伴”的简单模型:

”

“在此处输入图像说明”

我可以在必要时显示有关关系的更多详细信息。

我只是添加了一个新的字符串可选属性,所以我认为轻巧的迁移很容易。

我创建了大量的测试数据来尝试某些功能,并且我很乐意避免放下数据库^^,并且由于这是一个测试项目,我想了解Avoir重复它的问题。

任何人都可以帮助理解这个“从(null)中选择最大(z_pk)”的地方以及如何解决它?

I'm trying out Core Data with a test project and I'm facing some issues with Core Data and migrations. During the lightweight automatic migration, a crash occurs with the following :

 [logging] near "null": syntax error in "SELECT MAX(Z_PK) FROM (null)"



[error] error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134110)
CoreData: error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134110)
CoreData: annotation: userInfo:
CoreData: annotation:   sourceURL : file:///var/mobile/Containers/Data/Application/D712273A-6E49-4B19-9919-3E55F6A5A37D/Library/Application%20Support/TestApp.sqlite
CoreData: annotation:   reason : Cannot migrate store in-place: near "null": syntax error
CoreData: annotation:   destinationURL : file:///var/mobile/Containers/Data/Application/D712273A-6E49-4B19-9919-3E55F6A5A37D/Library/Application%20Support/TestApp.sqlite
CoreData: annotation:   NSUnderlyingError : Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." UserInfo={reason=near "null": syntax error, NSSQLiteErrorDomain=1, NSUnderlyingException=near "null": syntax error}
CoreData: annotation: storeType: SQLite
CoreData: annotation: configuration: (null)
CoreData: annotation: URL: file:///var/mobile/Containers/Data/Application/D712273A-6E49-4B19-9919-3E55F6A5A37D/Library/Application%20Support/TestApp.sqlite
CoreData: annotation: options:
CoreData: annotation:   NSInferMappingModelAutomaticallyOption : 1
CoreData: annotation:   NSMigratePersistentStoresAutomaticallyOption : 1
CoreData: annotation:   NSPersistentStoreFileProtectionKey : NSFileProtectionComplete
CoreData: annotation: <NSPersistentStoreCoordinator: 0x281cf1500>: Attempting recovery from error encountered during addPersistentStore: Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration."

Here is the code of the PersistenceCointainer used to load database in the SwiftUI App :

struct PersistenceController {
    static let shared = PersistenceController()

    static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext
        for _ in 0..<10 {
            let newItem = Relation(context: viewContext)
            newItem.date = Date()
        }
        do {
            try viewContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
        return result
    }()

    var container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "TestApp")
        
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        
        if let storeDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first {
                let sqliteURL = storeDirectory.appendingPathComponent("TestApp.sqlite")
                
                //Set Protection for Core data sql file
                let description = NSPersistentStoreDescription(url: sqliteURL)
                description.shouldInferMappingModelAutomatically = true
                description.shouldMigrateStoreAutomatically = true
                description.setOption(FileProtectionType.complete as NSObject, forKey: NSPersistentStoreFileProtectionKey)
                container.persistentStoreDescriptions = [description]
            }
        
       
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
        
    }
    
    
}

Here is more about the model I'm trying to change. I have a simple model called "Partner" :

enter image description here

enter image description here

I can show more details of the relations if necessary.

I'm simply adding a new String optional attribute, so I thought lightweight migration would be easy.

I have created a lot of test data to try some features and I'd enjoy avoiding to drop my database ^^ And since it's a test project I'd like to understand where the issue comes from to avoir repeating it.

Can anybody help understand where does this "SELECT MAX(Z_PK) FROM (null)" comes from and how I could fix it ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖乖哒 2025-02-08 18:24:24

好的,所以我尝试在数据库内挖掘,但找不到任何看起来很奇怪的数据。

我Juste创建了一个从旧合作伙伴模型创建的映射模型,并指定了新字段应采用“默认”值,迁移效用:所以我想我永远都不知道什么是此错误的真正原因:)

我对面对此错误的任何人的建议:尝试创建映射模型(步骤7/8 in 此教程

Ok so I tried to dig inside the database and didn't find any strange-looking data.

I juste created a Mapping Model from the old to the new Partner Model, and specified that the new field should take the "default" value, and the migrations worked : so I guess I'll never know what was the real reason for this bug :)

My advice for anyone that would face this bug : try creating a Mapping Model (steps 7/8 in this tutorial)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文