一
object DatabaseMigrations {val MIGRATION_1_2 = object : Migration(1, 2) {override fun migrate(db: SupportSQLiteDatabase) {db.execSQL("ALTER TABLE users ADD COLUMN email TEXT")}}val MIGRATION_2_3 = object : Migration(2, 3) {override fun migrate(db: SupportSQLiteDatabase) {db.execSQL("""CREATE TABLE users_new (id INTEGER PRIMARY KEY NOT NULL,username TEXT NOT NULL,email TEXT,register_time TEXT)""".trimIndent())db.execSQL("""INSERT INTO users_new (id, username, email)SELECT id, name, email FROM users""".trimIndent())db.execSQL("DROP TABLE users")db.execSQL("ALTER TABLE users_new RENAME TO users")}}fun getAll() = arrayOf(MIGRATION_1_2, MIGRATION_2_3)
}
二
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabaseobject MigrationHelper {val migrations = listOf(object : Migration(1, 2) {override fun migrate(database: SupportSQLiteDatabase) {database.execSQL("ALTER TABLE users ADD COLUMN email TEXT NOT NULL DEFAULT ''")}}, object : Migration(2, 3) {override fun migrate(db: SupportSQLiteDatabase) {db.execSQL("ALTER TABLE users ADD COLUMN email_test TEXT NOT NULL DEFAULT ''")}},object : Migration(3, 4) {override fun migrate(db: SupportSQLiteDatabase) {db.execSQL("""CREATE TABLE users_new (id INTEGER PRIMARY KEY NOT NULL,username TEXT NOT NULL,email TEXT,register_time TEXT)""".trimIndent())db.execSQL("""INSERT INTO users_new (id, username, email)SELECT id, name, email FROM users""".trimIndent())db.execSQL("DROP TABLE users")db.execSQL("ALTER TABLE users_new RENAME TO users")}})
}