4

Realm migration from a required variable to nullable

I had a variable which was a REQUIRED field in my previous version of realm. But for the newer version i want it to be not required but a nullable one. How do i do it through realm migration?

Ankur
  • 677
  • 1
  • 7
  • 21

2 Answers2

8

You can check the example in migrationExample provided by Realm team

if (oldVersion == 2) {
   RealmObjectSchema personSchema = schema.get("ClassName");
   personSchema.setNullable("nullableFielName", true);
}

If you have already synced with Realm Object Server, please check this: https://realm.io/docs/java/latest/#syncing-migrations

Ralphilius
  • 1,746
  • 2
  • 16
  • 28
  • Have done it already. An error occurs 'Caused by: java.lang.IllegalStateException: The following changes cannot be made in additive-only schema mode: -Property 'nullableFielName' has been made optional' – Ankur Feb 21 '18 at 06:50
  • Okay this issue is with Realm Object Server. – Ankur Feb 21 '18 at 07:24
  • 1
    This is a "destructive" schema operation so the only thing you can do is add a new field that is nullable, and I *think* you can define a migration that would apply a transform for the data into the new field. Removing the current field from code *should* keep it in the schema, but "hide" it from the API. – EpicPandaForce Feb 21 '18 at 09:55
  • @Ankur You can follow the link in the updated answer for more information about updating schema on Realm Object Server. – Ralphilius Feb 22 '18 at 09:04
1

You can change the table in realm by either doing this First you declare your variable as optional

open class YourModel: RealmObject() {
@SerializedName("english") var english: String? = "" }

and then do this in your migration file

 override fun migrate(realm: DynamicRealm?, oldVersion: Long, newVersion: Long) {
    val schema = realm?.schema
    if (oldVersion < 1L) {
                schema?.get("YourModel")
                        ?.removeField("english")
                        ?.addField("english", String::class.java)}

or

 schema?.get("YourModel")
                   ?.setNullable("english",true)}
naqi
  • 55
  • 8