KQLite Migration
KQLite does not support automatic migration. Migration callbacks can be defined using KQLiteMigration. KQLite allows database upgrade or downgrade as necessary based on current database version fetched using PRAGMA user_version; internally. Migration happens in an EXCLUSIVE transaction.
To migrate database, do the changes in KQLiteDatabase and KQLiteTable, one at a time and the declare the same change in KQLiteMigration. Assume current database version is 1 and we want to add last modified date column into Contacts Database.
Create Migration class
Each KQLiteMigration class determines fromVersion x --> toVersion y. It can be upgrade or downgrade depending upon given versions. In our scenario, we want to upgrade from version 1 to version 2 to add a column.
class Migration12 : KQLiteMigration(fromVersion = 1, toVersion = 2) {
override fun migrate(database: KQLiteDatabase) {
}
}
Add new column into TblContact
Add a new column lastModified into TblContact class.
object TblContact : KQLiteTable("contacts"), KQLiteAdapter {
val id = intColumn("id").notNull().primaryKey().autoIncrement()
val firstName = textColumn("first_name").notNull()
...
...
val lastModified = dateTimeColumn("last_modified")
}
Define migration steps
Whatever changes we did into the TblContact class, we have to define into KQLiteMigration class to execute SQLite queries. In current scenario, steps to add new column.
class Migration12 : KQLiteMigration(fromVersion = 1, toVersion = 2) {
override fun migrate(database: KQLiteDatabase) {
val schema = database.schema()
schema
.alterTable(TblContact)
.addColumn(TblContact.lastModified)
}
}
Version update
Increment database version so that KQLiteMigration callback is invoked on next database open.
Updated VERSION to 2 and overriden getKQLiteMigrations method to assign
Migration12.
class ContactsDatabase(
kqLiteDriver: KQLiteDriver = ContactsDatabaseDriver(getDatabaseAbsolutePath(NAME))
) : KQLiteDatabase(kqLiteDriver = kqLiteDriver) {
companion object {
const val NAME = "contacts.db"
const val VERSION = 2
}
override fun getKQLiteTables(): List {
return listOf(TblContact)
}
override fun getKQLiteMigrations(): List {
return listOf(Migration12())
}
}
For more details, see KQLiteMigration.