Room Migration Alter Table not adding new column & migrate getting called again and again

假装没事ソ 提交于 2020-01-03 18:46:10

问题


So basically i am using room and trying to add migration from database version 1 to 2 but my alter command is not working My current implementation is below :

 void init() {
    db = Room.databaseBuilder(Global.getInstance(),
            AppDatabase.class, "feed").addMigrations(MIGRATION_1_2).build();
}

Migration property :

static final Migration MIGRATION_1_2 = new Migration(1,2) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {


        database.execSQL("ALTER TABLE 'post' ADD COLUMN 'age' INTEGER NOT NULL DEFAULT 0");
        Log.d("VROM","Migration");
    }
};

Database implementation :

@Database(entities = {Feed.class, DownloadModel.class}, version = 1) public abstract class AppDatabase extends RoomDatabase {
public abstract DaoAccess getFeedDao();}

So after incrementing the version from 1 to 2, the execSQL() is executed but new column is not added in my db. I have pulled my db from app directory and checked multiple times but column is not there. Apart from that if I kill my app and launch it again the migrate method is called again , don't know if this is the intended functionality but it breaks the functionality for me.I thought migrate will be only called once same as onUpgrade()


回答1:


Make sure your column is in model class. In your case, you are adding column age like this: ADD COLUMN 'age' INTEGER, so you must have int age in your model class.

Also, it is a good idea to write migration test to known exactly what is failing. You can find about migration test in android documentation here: https://developer.android.com/topic/libraries/architecture/room.html#db-migration-testing




回答2:


Try Changing version=2 in AppDatabase inside @Database.



来源:https://stackoverflow.com/questions/46687160/room-migration-alter-table-not-adding-new-column-migrate-getting-called-again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!