[Android/Jetpack Compose] How to migrate Data Access Object (Android Room) with re-writing the column name?

Android

When you want to migrate your app-database created by Room you have to do migration for notify the system to change some information about DB.

Especially when you re-write something like column data (i.e. column name) you have to migrate stuff.

I will focus on how to change column name as migration stuff.

How to change column name?

At first, I imagine you have already created the following Database.

@Module
@InstallIn(SingletonComponent::class)
object DatabaseProvider {
    @Volatile
    private var Instance: AppDatabase? = null

    @Singleton
    @Provides
    fun getDatabase(context: Context): AppDatabase {
        return Instance ?: synchronized(this) {
            Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "test_application_database")
                .setJournalMode(RoomDatabase.JournalMode.TRUNCATE).build()
                .also { Instance = it }
        }
    }

    @Singleton
    @Provides
    fun provideUserDao(db: AppDatabase) = db.userDao()
}

And User has the following structure.

@Entity(tableName = "user")
data class User(
    @PrimaryKey(autoGenerate = true) val key: Int? = null,
    @ColumnInfo(name = "email") val email: String,
    @ColumnInfo(name = "password") val password: String,
    @ColumnInfo(name = "last_logout")val lastLogin: Int,
)

I'd like to change one of the column name from last_logout to last_login.

You have to put the following annotaions like the below.

@RenameColumn( // ※1
    tableName = "user",
    fromColumnName = "last_logout",
    toColumnName = "last_login",
)
class NameToLastLoginAutoMigrationSpec : AutoMigrationSpec // ※2

@Database(
    entities = [User::class, Channel::class],
    version = 2,
    autoMigrations = [AutoMigration(from = 1, to = 2, // ※3 NameToLastLoginAutoMigrationSpec::class)],
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

※1 : To notify the DAO that this database want to change the column name.
※2 : you have to write to clarify the type in @Database as you can see.
※3 : To execute automigration you must tell generator what version it will generate.

Tips

If you want to see migration file written by json add the sentence in module level's gralde file.

        ksp {
            arg("room.schemaLocation", "$projectDir/schemas")
        }

コメント

タイトルとURLをコピーしました