Challenge - 5 Problems
Database Migration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate2:00remaining
What happens after a database migration?
You have an Android app using Room database. You add a new column to a table and write a migration from version 1 to 2. What will the app do after updating if the migration is correct?
Attempts:
2 left
💡 Hint
Think about what a migration is supposed to do to keep data safe.
✗ Incorrect
A correct migration updates the database schema to the new version while preserving existing data. It applies changes like adding columns or tables without deleting data.
📝 Syntax
intermediate2:00remaining
Identify the correct Room migration code snippet
Which Kotlin code snippet correctly defines a migration from version 1 to 2 that adds a new column 'age' to the 'User' table with a default value 0?
Android Kotlin
val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { // migration code here } }
Attempts:
2 left
💡 Hint
Adding a non-null column requires a default value in SQLite.
✗ Incorrect
Option B correctly adds a new non-null INTEGER column with a default value, which is required to avoid errors during migration.
❓ lifecycle
advanced2:00remaining
When is the migration code executed in an Android app?
At what point during the app lifecycle does Room execute the migration code when upgrading the database version?
Attempts:
2 left
💡 Hint
Think about when the app needs to access the database after an update.
✗ Incorrect
Room runs migrations when the database is opened for the first time after an update, ensuring the schema is current before queries run.
🔧 Debug
advanced2:00remaining
Why does this migration cause a crash?
You wrote this migration code:
val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE User ADD COLUMN email TEXT NOT NULL")
}
}
The app crashes on upgrade. Why?
Attempts:
2 left
💡 Hint
SQLite requires a default value when adding NOT NULL columns.
✗ Incorrect
SQLite cannot add a NOT NULL column without a default value because existing rows would violate the constraint, causing a crash.
🧠 Conceptual
expert3:00remaining
What is the best practice for handling complex schema changes in Room migrations?
You need to rename a column and change its type in a Room database migration. SQLite does not support renaming columns directly. What is the recommended approach?
Attempts:
2 left
💡 Hint
Think about how to preserve data when SQLite lacks direct support for renaming columns.
✗ Incorrect
Since SQLite does not support renaming columns or changing types directly, the best practice is to create a new table with the new schema, copy data over, drop the old table, and rename the new one.