Ilya Tretyakov
Ilya Tretyakov

Reputation: 7010

Could not migrate to Room

I decided to use Room in my current application. Find out that there are no type for one column in current schema and Room produce IllegalStateException on migration.

java.lang.IllegalStateException: Migration didn't properly handle item.
 Expected:
TableInfo{name='item', columns={optional_modifiers=Column{a_type=Column{name='a_type', type='BLOB', notNull=false, primaryKeyPosition=0}...}
 Found:
TableInfo{name='item', columns={optional_modifiers=Column{a_type=Column{name='a_type', type='', notNull=false, primaryKeyPosition=0}...}

Sql script of the table creation:

"create table item ("
                " id text primary key," +
                " a_type, "
//...
                ")

Entity class:

@Entity(tableName = "item")
data class Item(
    @PrimaryKey
    val id: String?,
    val a_type: String? // actually I used several types, but none of them is worked
)

Are there any way to resolve this issue?

Upvotes: 2

Views: 877

Answers (2)

Ilya Tretyakov
Ilya Tretyakov

Reputation: 7010

Sqlite doesn't allow to edit schema. So the only possible way is create the new table with correct columns info, move data to it, delete old table.

Here is the example of the code that I used

        database?.execSQL("create table table_name_tmp ( " +
            " id text not null primary key"
            ")")
        database?.execSQL("""
            insert into table_name_tmp (id)

            select id
            from table_name
            """)
        database?.execSQL("drop table table_name")
        database?.execSQL("alter table table_name_tmp rename to table_name")

Upvotes: 1

Pinakin Kansara
Pinakin Kansara

Reputation: 2381

Make modification to your class annotated with @Entity as below.

@Entity(tableName = "item")
data class Item(
   @PrimaryKey
   val id: String?,
   @ColumnInfo(typeAffinity = ColumnInfo.BLOB)
   val a_type: String?
   )

This will work, because from error it is visible that your old db schema is having name='a_type', type='BLOB', so you need to add @ColumnInfo(typeAffinity = ColumnInfo.BLOB) this will instruct room to consider data type of "a_type" as BLOB.

Recently it comes to my attention that @ColumnInfo also provide "UNDEFINED" as a type Affinity so with that you can now declare your table field without any type.Documentation

please try updated changes in your project.

@Entity(tableName = "item")
data class Item(
@PrimaryKey
val id: String?,
@ColumnInfo(typeAffinity = ColumnInfo.UNDEFINED)
val a_type: String?
)

Upvotes: 0

Related Questions