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

Return ID in UniqueViolationException

Open cahix opened this issue 4 years ago • 2 comments

I am working with entities that specify a Unique ID I get from an external system.

These entities are nested, thus resulting in UniqueViolationException when I try to update values that already exist.

Is it possible to return the conflicting ID that is also displayed in the error message from the UniqueViolationException as a value in the exception?

Is there any other, more elegant, way to work with external unique IDs and bulk updates?

cahix avatar Sep 10 '21 12:09 cahix

message example:

ObjectBoxException: object put failed: 10201 Unique constraint for ShopOrder.uid would be violated by putting entity with ID 64 because same property value already exists in entity with ID 61

As conflicting id appears at the end of error message you can return the id simply by

addOrder(){
    // order
    // put order relations first if not exist yet
    // order with its relations
    try {
      orderBox.put(order);
    } on UniqueViolationException catch (e) {
      final id= int.tryParse(e.message.split(' ').last) ?? 0; //already exists entity id
      orderBox.put(order..id = id);
    }
}

or you can query for existing entity and get id

MdSaLaMa avatar Jul 18 '22 05:07 MdSaLaMa

@MdSaLaMa If you write it that way, make sure to add a test to confirm this works. There is no guarantee that this message won't be changed with an upcoming release.

greenrobot-team avatar Jul 18 '22 06:07 greenrobot-team