objectbox-dart icon indicating copy to clipboard operation
objectbox-dart copied to clipboard

@Unique with replace strategy that update instead of deleting and inserting a new one

Open AdelKanso opened this issue 2 years ago • 5 comments

Right now, @Unique with conflict: ConflictStrategy.replace remove the old object and insert a new one, this behavior causes a null relation if there's data that has relation to the old object(the one before deleting), and after deleting and inserting a new object, the related item's relations aren't updated to the new object.

AdelKanso avatar Sep 06 '22 08:09 AdelKanso

Agreed. This messes up relations big time and since neither non-integer primary keys nor composite indices are supported, relations are currently a nightmare to deal with. Unfortunately other packages like isar suffer pretty much the same issues :(

I'll try an ugly workaround in the meanwhile lol:



@Entity()
class TestModel {
  @Id()
  int objectId = 0;

  @Unique(onConflict: ConflictStrategy.replace)
  String id; // UUID

  String name;

  TestModel({
    required this.id,
    required this.name,
  });

  Future save() async {
    final existing = objectBox.store
        .box<TestModel>()
        .query(TestModel_.id.equals(id))
        .build()
        .findFirst();
    if (existing != null) {
      print('update');
      objectId = existing.objectId;
      objectBox.store.box<TestModel>().put(this, mode: PutMode.update);
    } else {
      print('insert');
      objectBox.store.box<TestModel>().put(this, mode: PutMode.insert);
    }
  }
}

//and you go like
var model = TestModel(id: Uuid().v4(), name: "Test 1");
model.save();

Chris1234567899 avatar Sep 06 '22 22:09 Chris1234567899

In case of saving multiple objects(putMany)? and what if there's a subobjects that I also want to handle?

AdelKanso avatar Sep 07 '22 07:09 AdelKanso

Thanks for the request! Please thumbs up the first post, if you are interested in this.

Vahid1919 avatar Sep 08 '22 13:09 Vahid1919

Thanks! At this point when using ConflictStrategy.replace with relations your code needs to take care of updating relations. Or maybe find a way to not having to use ConflictStrategy.replace in the first place.

AFAIK this is not different from traditional relational databases?

Anyhow, I could have sworn we documented this, but it's not. So I'll add a note to the docs to be careful when using relations.

greenrobot-team avatar Oct 04 '22 12:10 greenrobot-team

any updates on when this will be implemented

MahmoudArabyDev avatar Jan 09 '23 15:01 MahmoudArabyDev