Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Change old primary key in realm migration

Tags:

android

realm

Can I change old primary key with new primary key in realm migration script?

like image 670
Amol Suryawanshi Avatar asked Jan 05 '23 23:01

Amol Suryawanshi


1 Answers

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");
like image 111
EpicPandaForce Avatar answered Jan 07 '23 12:01

EpicPandaForce