0
0
Android Kotlinmobile~10 mins

Database migrations in Android Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a Room database version.

Android Kotlin
val db = Room.databaseBuilder(context, AppDatabase::class.java, "app_db")
  .version([1])
  .build()
Drag options to blanks, or click blank then click option'
A2
B1
C3
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using version 0 which is invalid
Skipping version number
2fill in blank
medium

Complete the code to add a migration from version 1 to 2.

Android Kotlin
val MIGRATION_1_2 = object : Migration(1, 2) {
  override fun migrate(database: SupportSQLiteDatabase) {
    database.execSQL([1])
  }
}
Drag options to blanks, or click blank then click option'
A"ALTER TABLE users ADD COLUMN age INTEGER DEFAULT 0"
B"DROP TABLE users"
C"CREATE TABLE users"
D"SELECT * FROM users"
Attempts:
3 left
💡 Hint
Common Mistakes
Dropping tables accidentally
Using SELECT instead of ALTER
3fill in blank
hard

Fix the error in the migration code to rename a table.

Android Kotlin
val MIGRATION_2_3 = object : Migration(2, 3) {
  override fun migrate(database: SupportSQLiteDatabase) {
    database.execSQL("ALTER TABLE users RENAME TO [1]")
  }
}
Drag options to blanks, or click blank then click option'
Ausers
Busers_new
Cusers_old
Duser
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same name as original
Using invalid table names
4fill in blank
hard

Fill both blanks to create a migration that creates a new table.

Android Kotlin
val MIGRATION_3_4 = object : Migration(3, 4) {
  override fun migrate(database: SupportSQLiteDatabase) {
    database.execSQL("CREATE TABLE [1] (id INTEGER PRIMARY KEY, name TEXT)")
    database.execSQL("INSERT INTO [2] (id, name) VALUES (1, 'Alice')")
  }
}
Drag options to blanks, or click blank then click option'
Aemployees
Busers
Ccustomers
Dstaff
Attempts:
3 left
💡 Hint
Common Mistakes
Using different table names in CREATE and INSERT
Using reserved keywords as table names
5fill in blank
hard

Fill all three blanks to define a migration that adds a new column and updates data.

Android Kotlin
val MIGRATION_4_5 = object : Migration(4, 5) {
  override fun migrate(database: SupportSQLiteDatabase) {
    database.execSQL("ALTER TABLE [1] ADD COLUMN [2] INTEGER DEFAULT 0")
    database.execSQL("UPDATE [3] SET [2] = 10 WHERE id = 1")
  }
}
Drag options to blanks, or click blank then click option'
Ausers
Bage
Dscore
Attempts:
3 left
💡 Hint
Common Mistakes
Using different table names in ALTER and UPDATE
Using invalid column names