Cris
Cris

Reputation: 824

Room migration add column with value depending on existing ones

I am trying to create a Migration on my Room database, which means to add a new column called "name".

override fun migrate(database: SupportSQLiteDatabase) {
    database.execSQL("ALTER TABLE TimerEntry ADD COLUMN name TEXT NOT NULL")
}

This value cannot be null, and I would like the default value to be computed based on the values of the other columns.

This is my entity:

@Entity
data class TimerEntry (var hours: Int, var minutes: Int, var seconds: Int, var name: String = String.format("%02d:%02d:%02d", hours, minutes, seconds))

As you can see, in case no name is provided, its value is computed based on the values of the other parameters. I would like my Migration to do the exact same thing: Insert a new value into name which should be the result of formatting hours, minutes and seconds

Upvotes: 2

Views: 5798

Answers (1)

Nieto
Nieto

Reputation: 1191

You can't do that only with SQL.

I think the best way to do it is to assign a default value in ALTER TABLE and then for each row compute the name value and insert the updated model back to the database.

override fun migrate(database: SupportSQLiteDatabase) {
    database.execSQL("ALTER TABLE TimerEntry ADD COLUMN name TEXT NOT NULL DEFAULT 'tmp'")

    // Get all TimerEntry rows
    // Compute and assign name field
    // Update database
}

Upvotes: 4

Related Questions