Can I change old primary key with new primary key in realm migration script?
Yes, it is possible.
RealmObjectSchema objectSchema = schema.get("MyObject");
objectSchema.addField("newId", long.class)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.setLong("newId", getNewId(obj));
}
})
.removeField("id")
.renameField("newId", "id")
.addPrimaryKey("id");
However, you can't directly create the field as
objectSchema.addField("newId", long.class, FieldAttribute.PRIMARY_KEY)
because the values are initialized to 0 in your database, which means you'll be violating the constraint on creation. So you must add the primary key constraint only after the values are set.
In your case,
RealmObjectSchema objectSchema = schema.get("MyObject");
objectSchema.addField("newId", long.class)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.setLong("newId", getNewId(obj));
}
})
.removePrimaryKey()
.addPrimaryKey("newId");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With