简体   繁体   中英

How to perform a query inside a realm migration?

I'm moving a field from linked object to a non calculated field

public dynamic var venue: Venue!

Now I need to create a migration to populate this field that before this change was calculated using linkedobjects

My migration is like this

if (oldSchemaVersion < 7) {
    migration.enumerate(VenueRoom.className()) { oldObject, newObject in
        let venue = try! Realm().objects(Venue).filter("ANY venueRooms.id = %@", oldObject!["id"]!).first
        newObject!["venue"] = venue
    }
}

But it doesn't work with the following error

"Provided schema version 0 is less than last set version 6." UserInfo={NSLocalizedDescription=Provided schema version 0 is less than last set version 6.}:

What seems to make sense

Then I try the following approach to get a realm instance with the correct configuration

if (oldSchemaVersion < 7) {
    migration.enumerate(VenueRoom.className()) { oldObject, newObject in
        let configuration = Realm.Configuration(
            schemaVersion: self.schemaVersion,
            migrationBlock: nil
        )
        let realm = try! Realm(configuration: configuration)

        let venue = realm.objects(Venue).filter("ANY venueRooms.id = %@", oldObject!["id"]!).first
        newObject!["venue"] = venue
    }
}

But it gets stuck on

let realm = try! Realm(configuration: configuration)

It never comes back from that statement, no error.

What's the correct way to perform a query inside a migration?

Executing a query within a migration block is not currently supported . Until support is added you'll want to use Migration.enumerate(_:_:) to enumerate objects of a given type and perform any filtering you need in Swift.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM