Room Auto Migration

This is my note for Udemy lesson: Advanced Android Bootcamp 2024.
We want to add email to the Student entity.

1. Edit Entity

Origin:

@Entity(tableName = "student_info")
data class Student(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "student_id")
    val id : Int,
    @ColumnInfo(name = "student_name")
    var name : String
}

After:

@Entity(tableName = "student_info")
data class Student(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "student_id")
    val id : Int,
    @ColumnInfo(name = "student_name")
    var name : String,
    @ColumnInfo(name = "student_email", defaultValue = "No Email")
    var email: String
)

2. Edit Database

Origin:

@Database(entities = [Student::class],
    version = 1
)
abstract class StudentDatabase : RoomDatabase() {
    ...
}

After:

@Database(entities = [Student::class],
    version = 2,
    autoMigrations = [AutoMigration(from = 1, to = 2)]
)
abstract class StudentDatabase : RoomDatabase() {
    ...
}

Note:
If you created a new version 3 and added another column, you cannot write autoMigrations = [AutoMigration(from = 1, to = 3)], you must write autoMigrations = [AutoMigration(from = 1, to = 2), AutoMigration(from = 2, to = 3)]