DB迁移变得容易!

每当你修改数据库架构,你需要在对应的@Database类内部通过增加数据库版本。还需要添加一个迁移到配置或通过定义迁移 /assets/migrations/{DatabaseName}/{versionName.sql}。

在首次创建数据库,您可以使用版本0指定一个迁移运行时!

注意:任何提供的子类,如AlterTableMigration,UpdateTableMigration和IndexMigration应该只覆盖onPreMigrate()和调用super.onPreMigrate(),所以它的正确实例化。

注意:所有迁移必须只有一个public默认构造函数。

迁移类

基类,BaseMigration是一个非常简单的类来执行迁移:

2. @Migration(version = 2, database = AppDatabase.class)
3. public class Migration1 extends BaseMigration {

5. @Override
6. public void migrate(DatabaseWrapper database) {
7. List<SomeClass> list = SQLite.select()
8. .from(SomeClass.class)
9. .queryList(database); // must pass in wrapper in order to prevent recursive calls to DB.
10. }
11. }

添加列

此处是添加到数据库的列的一个例子:

假设我们有原来的示例类:

2. @Table
3. public class TestModel extends BaseModel {

5. @Column
6. @PrimaryKey
7. String name;

9. @Column
10. int randomNumber;
11. }

现在,我们要添加一列到这个表。我们有两种方式:

  • 利用SQL语句

ALTER TABLE TestModel ADD COLUMN timestamp INTEGER; in a {dbVersion.sql} file in the assets directory. If we need to add any other column, we have to add more lines. - 通过Migration:

2. @Migration(version = 2, database = AppDatabase.class)
3. public class Migration1 extends AlterTableMigration<TestModel> {

5. @Override
6. public void onPreMigrate() {
7. // Simple ALTER TABLE migration wraps the statements into a nice builder notation
8. addColumn(Long.class, "timestamp");
9. }
10. }

更新列

2. @Migration(version = 2, database = AppDatabase.class)
3. public class Migration1 extends UpdateTableMigration<TestModel> {

5. @Override
6. public void onPreMigrate() {
7. // UPDATE TestModel SET deviceType = "phablet" WHERE screenSize > 5.7 AND screenSize < 7;
8. set(TestModel_Table.deviceType.is("phablet"))
9. .where(TestModel_Table.screenSize.greaterThan(5.7), TestModel_Table.screenSize.lessThan(7));
10. }
11. }