How to upgrade database with Sugar Orm?

╄→гoц情女王★ 提交于 2019-12-11 07:31:38

问题


I have a simple entity:

public class MyEntity extends SugarRecord {

    String name;
    int    value;

    public MyEntity() {
        //empty ctr for sugar orm
    }

    public MyEntity(String name, int value) {
        this.name = name;
        this.value = value;
    }
}

On App start I make an instance and save it like this:

  Log.i("db_test", "count_before: "+MyEntity.count(MyEntity.class)+"");
  new MyEntity("name", 10).save();
  Log.i("db_test", "count_after: "+MyEntity.count(MyEntity.class)+"");

In the log I can see:

04-12 14:58:52.538: I/db_test(10691): count_before: 0
04-12 14:58:52.555: I/Sugar(10691): MyEntity saved : 1
04-12 14:58:52.555: I/db_test(10691): count_after: 1

It is working well.

So what if I decide I would like to add a property to MyEntity class. like this:

public class MyEntity extends SugarRecord {

    String name;
    int    value;
    int    anotherValue; ///< A new property.
//...

After this I increment the Databse version because the model has changed. So I increase the following field in the manifest from 1 to 2.

  <meta-data
   android:name="VERSION"
   android:value="2"/>

This time when i ran my app I got the following error:

E/SQLiteLog(11125): (1) table MY_ENTITY has no column named ANOTHER_VALUE

java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: 

android.database.sqlite.SQLiteException: table MY_ENTITY has no column named ANOTHER_VALUE (code 1): , while compiling: INSERT OR REPLACE  INTO MY_ENTITY(ANOTHER_VALUE,ID,VALUE,NAME) VALUES (?,?,?,?)

So why is this happening?

I have made this property on my Java object.

I have incremented the database version.

What m I doing wrong?


回答1:


Whilst it's not an ideal solution, using an upgrade file to manually alter the table should allow the insert / replace to work.

AFAIK, the VERSION value is only used to identify if patches should be run.

In your case, it would be a case of adding a file called "2.sql" into your assets/sugar_upgrades/ folder, containing:

ALTER TABLE my_entity ADD COLUMN another_value int;

Source: SugarORM



来源:https://stackoverflow.com/questions/36574233/how-to-upgrade-database-with-sugar-orm

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