KQLiteMigration

abstract class KQLiteMigration(val fromVersion: Int, val toVersion: Int)

Represents a migration path for a KQLiteDatabase. Migration happens in EXCLUSIVE transaction.

Each migration must specify a fromVersion and a toVersion to define the schema transformation it handles. The migrate method contains the actual migration logic to update the database schema and/or data from the fromVersion to the toVersion.

The entire migration process is wrapped in an EXCLUSIVE transaction, ensuring that the migration is atomic. If an exception is thrown, the transaction will be rolled back, leaving the database in its original state before the migration began.

This can handle both upgrade and downgrade scenarios depending upon the implementation. Direct migration takes priority over step by step migration.

Example

class MigrationV12 : KQLiteMigration(1, 2) {
override fun migrate(database: KQLiteDatabase) {
// It is already in EXCLUSIVE TRANSACTION

// Fetching KQLitePragma object and disabling foreign keys
val pragma = database.pragma()
pragma.foreignKeys.set(false)

// Fetching KQLiteSchema object
val schema = database.schema()

// RENAME TABLE: 'users_old' to 'users'
// Assuming the `Users` table name has been changed to 'users'
// ALTER TABLE `users_old` RENAME TO `users`;
schema
.alterTable(Users)
.renameTable("users_old", Users.tableName)
}
}

This migration will be executed when the database needs to be upgraded from version 1 to 2.

Author

MOHAMMAD AZIM ANSARI

See also

Constructors

Link copied to clipboard
constructor(fromVersion: Int, toVersion: Int)

Properties

Link copied to clipboard

The starting database version for this migration.

Link copied to clipboard

The ending database version after this migration is applied.

Functions

Link copied to clipboard
abstract fun migrate(database: KQLiteDatabase)

Executes the migration logic.

Link copied to clipboard
open override fun toString(): String

Returns a string representation of the migration, indicating the start and end versions.