Android room migration add a list of enums - android

I'm saving
data class Settings(
val foo: Int
)
into my room database version 1.
Now I need to extend Settings to
data class Settings(
val foo: Int,
val bar: ArrayList<Baz>
)
where
enum class Baz {
A, B, C
}
so I need to do a migration to version 2.
I have type converters for bar. I'm currently trying something like
val MIGRATION_1_2: Migration = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE settings ADD COLUMN bar TEXT")
}
}
but this gives me an IllegalStateException: Migration didn't properly handle Settings... error.
And I'm stuck. So please help! How do I get that migration working??

Turns out it was my lack of SQLite skills that was in the way.
First of all, I needed to set a default value since my barwasn't allowed to be null. Second, ALTER TABLE is crazy limited and didn't allow me to set a default value in one line.
I ended up doing
val MIGRATION_1_2: Migration = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE settings_new (foo INTEGER NOT NULL, bar TEXT NOT NULL, PRIMARY KEY(foo))")
database.execSQL("INSERT INTO settings_new (foo, bar) SELECT foo, '[]' AS bar FROM settings")
database.execSQL("DROP TABLE settings")
database.execSQL("ALTER TABLE settings_new RENAME TO settings")
}
}
In other words
Create a new temporary table (settings_new)
Move old values into the new one. Notice that we set bar as an empty array as default.
Drop the original (settings) table
Rename the temporary to the old name (i.e. settings_new --> settings)

Try to change settings table name Settings and you pass only setting..
database.execSQL("ALTER TABLE Settings ADD COLUMN bar TEXT")
after add..
database = Room.databaseBuilder(context.getApplicationContext(),
UsersDatabase.class, "Sample.db")
.addMigrations(MIGRATION_1_2)
.build();
refer this ..
Room database migration if only new table is added

Related

Migration in Room with an Android Array of Strings

I have a database in Android with Room from which I have deleted a column. I was doing the migration, and I saw that it was not as simple as doing a DROP of the deleted column.
Then I have seen that I have to take a series of steps, creating a provisional table that will later be the new table with the deleted column, but the problem is that this table contains a field that is a String Array that I don't know how to declare in SQL.
#Entity(tableName = "recipe_table")
data class RecipesDb(
#PrimaryKey
#ColumnInfo(name = "id")
val id: Long,
#ColumnInfo(name = "name")
val name: String,
#ColumnInfo(name = "category")
val category: List<String>,
#ColumnInfo(name = "isRecommended")
val isRecommended: Boolean,
#ColumnInfo(name = "images")
val images: List<String>,
#ColumnInfo(name = "ingredients")
val ingredients: List<String>,
#ColumnInfo(name = "date")
val date: Long,
#ColumnInfo(name = "time")
val time: Int,
#ColumnInfo(name = "difficult")
val difficult: String,
#ColumnInfo(name = "originalUrl")
val originalURL: String? = null,
#ColumnInfo(name = "author")
val author: String,
#ColumnInfo(name = "siteName")
val siteName: String
)
And now I have removed the ingredients column. I wanted to do something like this:
private val MIGRATION_3_2 = object : Migration(3,2) {
override fun migrate(database: SupportSQLiteDatabase) {
//Drop column isn't supported by SQLite, so the data must manually be moved
with(database) {
execSQL("CREATE TABLE Users_Backup (id INTEGER, name TEXT, PRIMARY KEY (id))")
execSQL("INSERT INTO Users_Backup SELECT id, name FROM Users")
execSQL("DROP TABLE Users")
execSQL("ALTER TABLE Users_Backup RENAME to Users")
}
}
}
But when I declare the new temporary table User_Backup, I have no idea how to specify that one of the fields is an Array. In the end I was able to do it with Room's AutoMigrations and creating an interface, but I would like to know how to do it this way as well.
The simple way is to compile the code (Ctrl+F9) with the changed #Entity annotated classes in the list of entities of the #Database annotation.
Then look at the generated java (visible via the Android View in Android Studio). There will be a class that is the same name as the #Database annotated class but suffixed with _Impl.
In this class there will be a method that is named createAllTables, This includes the SQL that room uses for creating the tables.
Just copy and paste the appropriate SQL and then change the table name, this will not only use the correct type but also apply the correct column constraints that Room expects.
I would suggest
Adding an execSQL("DROP TABLE IF EXISTS the_backup_table_name;") before you create a table (just in case it already exists)
And instead of using execSQL("DROP TABLE Users") to use execSQL("DROP TABLE IF EXISTS the_original_table_name")
Personally I always RENAME the table name of the original, then RENAME the new table and then finally DROP the renamed original.
I would use:-
private val MIGRATION_3_2 = object : Migration(3,2) {
override fun migrate(database: SupportSQLiteDatabase) {
//Drop column isn't supported by SQLite, so the data must manually be moved
with(database) {
execSQL("DROP TABLE IF EXISTS Users_Backup")
execSQL("CREATE TABLE IF NOT EXISTS ....) //<<<<< SEE NOTES BELOW, the SQL MUST BE CHANGED.
execSQL("INSERT INTO Users_Backup SELECT id, name FROM Users")
execSQL("ALTER TABLE Users RENAME TO Old_Users")
execSQL("ALTER TABLE Users_Backup RENAME to Users")
execSQL("DROP TABLE IF EXISTS Old_users")
}
}
}
note .... indicates that the SQL is copied from the generated java and that the table name is changed from Users to Users_Backup
The first line will drop the Uers_backup just in case it happens to exist, it's just a little less likely to fail under unusual circumstances.
Rather than dropping the Users table before the RENAME of the Users_Backup to Users. The 4th execSQL changes the name of the Users table, so should there be an issue with changing the Users_Backup table to be the Users table, then the original Uers table is available as Old_users.
When all has been complted then the original Users table, now named Old_Users is then dropped.
These are all just a little safer/secure.

Android Room DB Migration

Problem - Room DB getting wiped/cleared when doing force update play store update. I am working on a chat messenger application which uses Room DB as local database. Whenever I do a store update with increasing DB version, the local DB gets cleared and messages history are lost.
I'm Using Room DB. My Application is in the Play Store with the use of Room DB and the version is 4.
My Question is I'm changing the 9 tables schema, and now that I update the DB version, each table schema changes. Should I increase the DB version here? How can I accomplish this without losing the user data using Room DB for force update in Play Store? Ex. DB version is 4, I change the two tables’ elements like in the below query.
Do I need to increase DB version twice as two tables are changed or change to one number incremental will be fine? Example: Do I need DB to increase version to 6 OR keeping it 5 is enough?
private val mMigrationMessageStatus: Migration = object : Migration(4, 5) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE message_status RENAME TO MessageStatus")
database.execSQL("ALTER TABLE MessageStatus ADD COLUMN userId TEXT NOT NULL default ''")
}
}
private val mMigrationGroupMember: Migration = object : Migration(4, 5) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE group_member RENAME TO GroupMember")
database.execSQL("ALTER TABLE GroupMember ADD COLUMN userId TEXT NOT NULL default ''")
}
}
return Room.databaseBuilder(context, AppDatabase::class.java, dbName)
.allowMainThreadQueries()
.addMigrations(mMigrationMessageStatus,mMigrationGroupMember)
.build()
From room version 2.4.0, you can easily update using autoMigrations.
DATABASE CLASS
#Database(
version = 3,
autoMigrations = [
AutoMigration(from = 1, to = 2),
AutoMigration(from = 2, to = 3)
],
.....
)
DATA CLASS
#Entity(tableName = "user")
data class DataUser(
....
// I added this column, like this
#ColumnInfo(defaultValue = "")var test: String = ""
)
see reference below
android developer: room version2.4.0
android developer: autoMigration

Move tables to a new database migration Room Android

I'm using Room in Android for my databases. Recently I had to create an alternate for my main database so now I have 2 databases.
abstract class FirstDatabase : RoomDatabase()
abstract class ScondDatabase : RoomDatabase()
I have a table in the FirstDataBase that I want to copy to the SecondDataBase. I know I should write migration but I don't know how I should do that.
This is my current migration with dagger for room:
fun provideDatabaseMigration56(): Migration {
return object : Migration(DATABASE_VERSION_5, DATABASE_VERSION_6) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("DROP TABLE IF EXISTS `pins`")
}
}
}
fun provideDatabaseMigration45(): Migration {
return object : Migration(DATABASE_VERSION_4, DATABASE_VERSION_5) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE IF NOT EXISTS `pins` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `slug` TEXT NOT NULL)")
}
}
}
What you're looking for is the SQLite ATTACH DATABASE statement. This allows you to attach an additional database to the current connection and then run queries referencing tables within both. There is some detailed documentation here which shows the syntax:
ATTACH DATABASE file_name AS database_name;
You can then run queries referencing tables from both databases, but make sure that when referencing a table from the attached database that you refer to it as
database_name.table_name
as opposed to just table_name.

How to Migrate Not Null table column into Null in Android Room database

I'm new to android room library. I need to migrate a Not Null column to Null,
But room migration only allow ADD or RENAME in ALTER table query. How do execute a column migration query?
#Entity(tableName = "vehicle_detail")
data class VehicleDetailsEntity(
#PrimaryKey(autoGenerate = true)
val vehicleClientId: Long = 0,
val vehicleId: String,
val updatedOn: Date,
val updatedBy: String
)
I need to change table structure into
#Entity(tableName = "vehicle_detail")
data class VehicleDetailsEntity(
#PrimaryKey(autoGenerate = true)
val vehicleClientId: Long = 0,
val vehicleId: String,
val updatedOn: Date?,
val updatedBy: String?
)
java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
You need to run a migration since SQLite doesn't allow column constraint modification.
For that migration you need to create a new temp table and copy all your previous data to it, then delete the old table and rename the temp one to the needed table name.
If you have a scheme directory, you can find your exact creation SQL query which you should copy on your migration (I just figured it out from a scheme of mine and could not be 100% correct):
val MIGRATION_1_2: Migration = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
// Create the new table
database.execSQL(
"CREATE TABLE IF NOT EXISTS VehicleDetailsEntityTmp (vehicleId TEXT NOT NULL, updatedOn TEXT, updatedBy TEXT,vehicleClientId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL )"
)
// Copy the data
database.execSQL(
"INSERT INTO VehicleDetailsEntityTmp (vehicleId, updatedOn, updatedBy ,vehicleClientId) SELECT vehicleId, updatedOn, updatedBy ,vehicleClientId FROM VehicleDetailsEntity ")
// Remove the old table
database.execSQL("DROP TABLE VehicleDetailsEntity")
// Change the table name to the correct one
database.execSQL("ALTER TABLE VehicleDetailsEntityTmp RENAME TO VehicleDetailsEntity")
}
}

Android Room Migration: Update Attribute Name By Creating New Table

Issue
In my project I a have a room table named 'content' with a Double attribute 'archivedCount'. In the latest version of the app the attribute archivedCount attribute is re-named to dismissCount, still as type Double.
Android API Level / SQL Version
28 / 3.19
Original Content model
#Entity(tableName = "content")
data class Content(#PrimaryKey var id: String, var archiveCount: Double) : Parcelable {...}
New Content model
#Entity(tableName = "content")
data class Content(#PrimaryKey var id: String, var dismissCount: Double) : Parcelable {...}
Runtime error
java.lang.IllegalStateException: Migration didn't properly handle content(app.coinverse.content.models.Content).
I've inspected the Expected and Found tables the log prints and they appear to be identical.
Attempted Solution
I attempted the complex schema change as outlined by a Google Developer Advocate unsuccessfully in order to modify the name of one attribute / column. Here is a basic version of what I attempted. 
val MIGRATION_1_2: Migration = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
// Create the new table
database.execSQL("CREATE TABLE content_new (id TEXT, dismissCount REAL, PRIMARY KEY(id))")
// Copy the data
database.execSQL("INSERT INTO content_new (id, dismissCount) SELECT id, archiveCount FROM content")
// Remove the old table
database.execSQL("DROP TABLE content")
// Change the table name to the correct one
database.execSQL("ALTER TABLE content_new RENAME TO content")
}
}
Can't see anything wrong with your implementation, I would suggest that you use a different #Entity class that is not named Content() and try again.

Categories

Resources