如何升级Realm Object Schema

496 阅读1分钟

Schema Version

Schema Version标识了realm schema在某一时刻的状态。realm数据库跟踪每个realm schema版本,并使用它将每个realm中的对象映射到正确的schema。

schema版本是升序整数,您可以在打开realm时将其包含在realm配置中。如果客户端应用程序在打开realm时没有指定版本号,那么该realm默认为版本0。

手动迁移必须将realm更新为更高的schema版本。如果客户端应用程序以低于realm当前版本的schema版本打开realm,或者指定的schema版本与realm当前版本相同,但包含不同的对象模式,则realm数据库会抛出错误。

增加属性

步骤

1.将新属性添加到对象的RealmModel类中。
2.重新生成RealmObject。执行 **flutter pub run realm generate** 命令
3.修改Configuration的配置版本

@RealmModel()
class _Person {
    late String firstName;
    late String lastName;
    late int age;//新增
}
//老版本1,更新为2版本
final config = Configuration.local([Person.schema], schemaVersion: 2);
final realm = Realm(config);

删除属性

步骤

删除属性不会影响现有的对象。

final config = Configuration.local([Person.schema], schemaVersion: 2);
final realm = Realm(config);

对于更复杂的模式更新,Realm Database要求您手动将给定对象的旧实例迁移到新模式。


final configWithoutPerson = Configuration.local([Car.schema],
    schemaVersion: 2,
    migrationCallback: ((migration, oldSchemaVersion) {
      // Between v1 and v2 we removed the Person type
      migration.deleteType('Person');
    }));
final realmWithoutPerson = Realm(configWithoutPerson);

重命名属性

步骤

final configWithRenamedAge =
Configuration.local([Person.schema, Car.schema],
    schemaVersion: 2,
    migrationCallback: ((migration, oldSchemaVersion) {
      // Between v1 and v2 we renamed the Person 'age' property to 'yearsSinceBirth'
      migration.renameProperty('Person', 'age', 'yearsSinceBirth');
    }));
final realmWithRenamedAge = Realm(configWithRenamedAge);