Writing Migrations

A Migration itself has only one required method: migrate(). You are given a SupportSQLiteDatabase, from the support database API covered in the preceding chapter. You can use the SupportSQLiteDatabase to execute whatever SQL statements you need to change the database schema to what you need.

The Migration constructor takes two parameters: the old schema version number and the new schema version number. You will only ever need one instance of a Migration for a given schema version pair, and usually the migrate() implementation for that schema version pair will be unique. Hence, the typical pattern is to implement each Migration as a Kotlin object, where you can provide the migrate() function to use for migrating the schema between that particular pair of schema versions.

To determine what needs to be done, you need to examine that schema JSON and determine what is different between the old and the new. Someday, we may get some tools to help with this. For now, you are largely stuck “eyeballing” the SQL. You can then craft the ALTER TABLE or other statements necessary to change the schema, much as you might have done in onUpgrade() of a SQLiteOpenHelper.

For example, the Migration module of the book’s primary sample project has a NoteDatabase akin to the NoteBasics module that we saw earlier in the book. One difference is that we have a MIGRATION_1_2 object that implements a Migration:

@VisibleForTesting
internal val MIGRATION_1_2 = object : Migration(1, 2) {
  override fun migrate(db: SupportSQLiteDatabase) {
    db.execSQL("ALTER TABLE notes ADD COLUMN andNowForSomethingCompletelyDifferent TEXT")
  }
}

Our migrate() function executes an ALTER TABLE statement, using execSQL() on the supplied SupportSQLiteDatabase object. The MIGRATION_1_2 object supplies 1 and 2 as the schema version pair to the Migration constructor, to identify what version pair this migrate() will handle.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.