Vasili Fedotov
Vasili Fedotov

Reputation: 1171

How to migrate Room Database from different Enum types

I have a Room database table with the following field.

itemType: Int

due to changes beyond my control, I need to save it as a string. i.e.:

itemType: String

so I added a database migration like so: (this is an abstract simplified version of my actual table)

database.execSQL("CREATE TABLE IF NOT EXISTS User_Backup (id TEXT NOT NULL, name TEXT NOT NULL, itemType TEXT NOT NULL, PRIMARY KEY(id))")
database.execSQL("INSERT INTO User_Backup(id,name) SELECT id,name FROM UserTable")
database.execSQL("DROP TABLE UserTable")
database.execSQL("ALTER TABLE User_Backup RENAME TO UserTable")

this very nicely alters the table and changes the type from int to String and retains all other data. the only problem is that my itemType field is left blank.

and I can't copy it as is because the new data should be mapped to a new structure.

for example:

1-> admin
2-> super user
3-> guest

etc...

how do I add this part to the migration?

Upvotes: 0

Views: 404

Answers (1)

Amit Tiwary
Amit Tiwary

Reputation: 797

You can use CASE to convert int val to string. It can be lengthy code and since it is enum so I assume you already know all int values of previous table itemType. You can code it like

database.execSQL("INSERT INTO User_Backup(id,name, itemType) SELECT id,name, CASE WHEN itemType == 1 THEN 'admin' WHEN itemType == 2 THEN 'super user' WHEN itemType == 3 THEN 'guest' .. ELSE 'else case value' END as itemType FROM UserTable")

Upvotes: 1

Related Questions