android6-2 Exercise 3: Migration and its test ========================================== @Entity( tableName = "notes", indices = [Index(value = ["remoteId"], unique = true)] ) data class NoteEntity( @PrimaryKey(autoGenerate = true) val id: Long = 0, val text: String, val createdAt: Long = System.currentTimeMillis(), val remoteId: Long? = null, @ColumnInfo(defaultValue = "0") val pinned: Boolean = false // new in version 3 ) @Database(entities = [NoteEntity::class], version = 3, exportSchema = true) abstract class AppDatabase : RoomDatabase() { /* ... */ } import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase val MIGRATION_2_3 = object : Migration(2, 3) { override fun migrate(db: SupportSQLiteDatabase) { db.execSQL("ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0") } } // Where the database is built: Room.databaseBuilder(context, AppDatabase::class.java, "notes.db") .addMigrations(MIGRATION_2_3) .build() // app/src/androidTest/.../MigrationTest.kt @RunWith(AndroidJUnit4::class) class MigrationTest { private val dbName = "migration-test" @get:Rule val helper = MigrationTestHelper( InstrumentationRegistry.getInstrumentation(), AppDatabase::class.java ) @Test fun migrate2To3_keepsNotesAndAddsPinned() { // 1. Create the database at the OLD version and insert a row with raw SQL helper.createDatabase(dbName, 2).apply { execSQL("INSERT INTO notes (id, text, createdAt) VALUES (1, 'Hi', 0)") close() } // 2. Run the migration; Room validates the resulting schema val db = helper.runMigrationsAndValidate(dbName, 3, true, MIGRATION_2_3) // 3. You check the DATA yourself: the helper only validates the schema db.query("SELECT text, pinned FROM notes WHERE id = 1").use { cursor -> assertTrue(cursor.moveToFirst()) assertEquals("Hi", cursor.getString(0)) assertEquals(0, cursor.getInt(1)) } } } Schema export: set exportSchema = true (above) and configure the schema location through Room's Gradle plugin (docs: the location is configured there and the files belong in version control); take the plugin id and syntax from the current Room docs, which were not confirmed here. Build once so version 2 and 3 JSON files exist (you need the version 2 file: if you did not export at version 2, recreate it by building the version 2 code with export on, or check out the earlier commit). Break it: change the migration SQL to DEFAULT 1, or drop the column; the test should fail on schema validation or on the pinned value assertion. Report how you configured the location and what failed. Code unrun.