OrmLite - save data before table upgrade

2019-06-08 06:39发布

It is possible to save the data from a table before my model changes the database?

For example i rename a column and will not lose the data. So i.e. i want to fetch all data from column c1, rename my column to c2 and write all data back.

2条回答
淡お忘
2楼-- · 2019-06-08 07:24

i want to fetch all data from column c1, rename my column to c2 and write all data back.

Sqlite does not support the renaming of columns so this will not work under Android. You can certainly add an additional column however. There is some good documentation on schema changes under Android/ORMLite. See this page:

http://ormlite.com/docs/upgrade-schema

For example, you can do the following schema updates:

dao.executeRaw(
    "ALTER TABLE `account` ADD COLUMN hasDog BOOLEAN DEFAULT 0;");
dao.updateRaw("UPDATE `account` SET hasDog = 1 WHERE dogCount > 0;");
查看更多
做自己的国王
3楼-- · 2019-06-08 07:36

Here's a quote from the ORMLite documentation: "You can’t rename or remove a column or change the constraints".

So your choices are:

  1. leave things as they are,
  2. add a new column, copying all the data from old to new as part of the upgrade, and just ignore the old column altogether, or
  3. Use a drop/create strategy to upgrade: back up the data from table into a temporary table, drop the table, re-create it as you'd like it to be, copy all the data back into it, and finally drop the temporary table.

Database upgrades are always nervous affairs (need lots of error handling, lots of testing), frankly if the name is the only thing that concerns you, I'd leave it alone (option 1). If you really need to change it then option 2 is low risk but leaves a 'dead' column and data lying around. Option 3 may be your choice if, for example, the data is a significant percentage of the overall database size.

查看更多
登录 后发表回答