0

Is there a way to make a Entity property unique when storing using PersistentEntityStore?

Such than any put operation with a duplicate property value would translate to a rollback or should not commit. Is this possible?

quarks
  • 33,478
  • 73
  • 290
  • 513

1 Answers1

1

There is no specific way to declare such an index. If PersistentEntityStore#executeInTransaction() or PersistentEntityStore#computeInTransaction() is used to define a transaction, then one can check if a property is unique directly in the lambda:

entityStore.executeInTransaction(txn -> {
    // ...
    if (!txn.find("EntityType", "propertyName", propValue).isEmpty()) {
        throw new ExodusException("Unique property violation");
    }
    entity.setProperty("propertyName", propValue);
    // ...
});

This way of setting properties can be extracted, for example, to a Kotlin extension function:

fun StoreTransaction.setProperty(entity: Entity, entityType: String, propName: String, propValue: Comparable<*>) {
    if(!find(entityType, propName, propValue).isEmpty) {
        throw ExodusException("Unique property violation: $propName = $propValue")
    }
    entity.setProperty(propName, propValue)
}
Vyacheslav Lukianov
  • 1,913
  • 8
  • 12
  • What is the difference of the two code snippets above? – quarks Oct 19 '18 at 10:06
  • @xybrek they are the same, but the second one is in Kotlin, and it can be used in Kotlin code as a regular function. It generalizes the pattern. – Vyacheslav Lukianov Oct 19 '18 at 10:13
  • Actually this is what I did, apparently I wanted to have a way to set a property (whether it should be unique or not) of an entity at runtime. And I was not able to achieve it. – quarks Oct 19 '18 at 10:14
  • @xybrek probably, you can define a metadata (superstructure over EntityStore API) that could answer the question in runtime whether a property is unique? – Vyacheslav Lukianov Oct 19 '18 at 10:23
  • Yeah I think this is the solution but I am not sure what is this "superstructure", can you give more details? – quarks Oct 19 '18 at 10:25
  • It depends on design of your application, but at a glimpse it can be thought as a set of pairs of strings (entity type + property name). If a pair is present in the set, then corresponding property is unique. It can be mutable at runtime. – Vyacheslav Lukianov Oct 19 '18 at 11:09
  • Where can this set of pairs of string? In the entity itselft or somewhere else? – quarks Oct 19 '18 at 11:54