Skip to content

Android Room Migration

DodaTech 2 min read

In this tutorial, you'll learn about Android Room Migration. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

You roll out an app update and users hit IllegalStateException: Migration didn't properly handle — the app crashes, data is lost, or the Migration runs but columns are missing.

Wrong Approach ❌

// Automatic destructive migration — DROPS ALL DATA!
Room.databaseBuilder(context, AppDatabase::class.java, "my-db")
    .fallbackToDestructiveMigration()
    .build()
val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(db: SupportSQLiteDatabase) {
        db.execSQL("ALTER TABLE users ADD COLUMN age INTEGER")
        // Forgot to handle the existing NOT NULL constraint
    }
}

Output: User data wiped on every schema change. SQLiteException: Cannot add NOT NULL column with default value NULL.

Right Approach ✅

val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(db: SupportSQLiteDatabase) {
        // Step 1: Create new table with desired schema
        db.execSQL("""
            CREATE TABLE users_new (
                id TEXT PRIMARY KEY NOT NULL,
                name TEXT NOT NULL,
                age INTEGER NOT NULL DEFAULT 0
            )
        """)
        // Step 2: Copy data from old table
        db.execSQL("INSERT INTO users_new (id, name) SELECT id, name FROM users")
        // Step 3: Drop old table
        db.execSQL("DROP TABLE users")
        // Step 4: Rename new table
        db.execSQL("ALTER TABLE users_new RENAME TO users")
    }
}

Output: Safe Migration preserving existing data with new schema.

Prevention

  • Write MigrationTest classes using Room.inMemoryDatabaseBuilder.
  • Test both forward and backward migrations.
  • For complex migrations, use the copy-drop-rename pattern.
  • Never use fallbackToDestructiveMigration() in production.
  • Annotate the @Database with exportSchema = true and check in the JSON.

Common Mistakes with room Migration

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### How do I test migrations without a device?

Room provides MigrationTestHelper from androidx.room:room-testing. Create a test that creates a database at version N, runs the Migration, and asserts the schema.

### What happens if I skip a Migration version?

Room requires every intermediate version. If you go from version 1 to 3, Room needs Migration_1_2 and Migration_2_3. You can also write a single Migration from 1 to 3 covering both changes.

### Can I revert a Migration?

Room does not support reverting. If a bad Migration ships, you must provide a new Migration that fixes the schema. Always test migrations thoroughly before release.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro