Detect future database migrations

Hi,

Can a DatabaseMigrator detect (or report) that a database has migrated further than the migrator itself supports?
For example: A user with app version 1.1 sends the document (database) to a user with version 1.0. This new user should now get an error that the document is too new for his app to open.

Thanks in advance.

Kind regards,

Remco Poelstra

Hello @remcopoelstra,

This is quite an expectable use case, but it is not addressed in the documentation.

You can use this sample code:

extension DatabaseMigrator {
    /// Returns whether database contains unknown migration
    /// identifiers, which is likely the sign that the database
    /// has migrated further than the migrator itself supports.
    func hasBeenSuperseded(_ db: Database) throws -> Bool {
        let identifiers = try appliedIdentifiers(db)
        let migrations = try appliedMigrations(db)
        return identifiers != Set(migrations)
    }
}

try database.read { db in
    if try migrator.hasCompletedMigrations(db) == false {
        // document too old
    }
    if try migrator.hasBeenSuperseded(db) {
        // document too new
    }
}

Thank you for your report. The hasBeenSuperseded(_:) method is likely to be added to GRDB 5.

2 Likes

Hi,

Thanks! Looks like this extension works just fine (I had to change migrator to 'self' though).

Great :-) I have updated the sample code :+1: