Migration does not working: I hope to know the execution condition


#1

Hello, I made a migration function as below, and call it in AppDelegate.

class func migrationDB() {
    var migrated: Bool = false
    
    do {
        let schemaVersion = try schemaVersionAtURL(Realm.Configuration(encryptionKey: ENCRYPTION_KEY).fileURL!, encryptionKey: ENCRYPTION_KEY)
        print("schemaVersion", schemaVersion)
    } catch {
        print("Error in reading schemaVersion", error)
    }
    
    let migrationBlock: MigrationBlock = { migration, oldSchemaVersion in
        print("migration, oldSchemaVersion", migration, oldSchemaVersion)
        
        migration.enumerateObjects(ofType: Outgo.className(), { oldObject, newObject in
            if (oldSchemaVersion < 1) {
                newObject?["newColumn"] = 0
                
                migrated = true
            }
        })
        
        print("Migration complete.")
    }
    Realm.Configuration.defaultConfiguration = Realm.Configuration(encryptionKey: ENCRYPTION_KEY, schemaVersion: LOCAL_DB_VERSION, migrationBlock: migrationBlock)
    print("migrated", migrated)
}

Log

schemaVersion 0
migrated false

The schemaVersion logged in the do~catch block is 0.
And the value of constant LOCAL_DB_VERSION is 1 now.
But it seems like the migrationBlock is not triggered.
I hope to know why, and the execution condition exactly.

Thank you.


#2

Can you try to print the new schemaVersion after the print(“migrated”, migrated) too?


#3

Sure. it’s ‘0’, too.

schemaVersion 0
migrated false
schemaVersion 0

#4

That that why your migration block is not called. The new realm version is the same as the old one.


#5

Its probably true, but do you open the realm? The new settings will apply only when you open a new Realm.


#6

Thank you for your reply.

But of course I tried to open the realm right after the migration method…


#7

How and where can I set the newer version? Is this here?

Realm.Configuration(encryptionKey: ENCRYPTION_KEY, schemaVersion: LOCAL_DB_VERSION, migrationBlock: migrationBlock)

The LOCAL_DB_VERSION is 1
and old schemaVersion is 0 as the log.
I can’t understand how it works.


#8

Thank you so so much. I got it.
I found the reason! I forgot to LOAD REALM WITH NEW CONFIGURATION!


#9

Nice catch.
Glad that you finally found out.