Uploaded image for project: 'Realm Java SDK'
  1. Realm Java SDK
  2. RJAVA-436

Allow updating of primary keys

      Goal

      There should be a method for updating the primary key of an object after it has been created. Previously one could update it using e.g. object.setId(newId), but starting with Realm 2.0.0 this throws an exception to keep it in line with the Realm API in other languages. See the dicussion in Pull Request #3418. The workflow of my app is similiar to the following:

      1. User creates a new object in the database while offline
      2. This object gets a temporary (negative) id, as the app does not yet know what final id the server will assign to the object
      3. User/app syncs the database when online again
      4. The server receives the new object and assigns a final id to it
      5. The app receives the final id from the server and updates the objects id to the final one (this is currently not directly supported by Realm)
            1. Expected Results

      I personally see 2 options going forward with this:

      • Reallow changing primary key fields: this would basically put it in the same state as previously with the following code to update an objects primary key:
      TestObject object = realm.where(TestObject.class).equalTo("mId", oldId).findFirst();
      object.setId(newId);
      
      • Add dedicated method for changing primary keys: this probably makes more sense if you want to align it more with the Realm API in other languages:
      realm.updatePrimaryKey(TestObject.class, oldId, newId);
      

      Actual Results

      Currently only a rather ugly and not very performant workaround does the job, basically bypassing the check by making an in-memory copy of the object:

      private static <E extends RealmObject> void updatePrimaryKey(Realm realm, Class<E> type, long oldId, long newId) {
          E object = realm.where(type).equalTo("mId", oldId).findFirst();
          E copy = realm.copyFromRealm(object);
          copy.setId(newId);
          realm.insertOrUpdate(copy);
          object.deleteFromRealm();
      }
      

      I'm really looking forward to seeing this fixed in a future update (though I absolutely acknowledge that you have lots of other issues to attend to )

      Version of Realm and tooling

      Realm version(s): >2.0.0
      Android Studio version: all
      Which Android version and device: all

      References

      realm-cocoa: https://github.com/realm/realm-cocoa/issues/4194

            Assignee:
            Unassigned Unassigned
            Reporter:
            unitosyncbot Unito Sync Bot
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: