Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ private static final class Order extends BaseEntity implements BusinessIdSlot {
private OrderNumber orderNumber;

private Order(long id) {
updateId(id);
__internalSet("id", id);
}

@Override
Expand Down
4 changes: 2 additions & 2 deletions examples/scalar-type-probe/GeneratedExplicitNullTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public class GeneratedExplicitNullTest {
assertFalse(full.__internalHasMutationLedger());
full.updateOptionalInteger(37);full.updateOptionalString(null);
full.updateProperty("optional_integer",37);full.updateProperty("optional_string",null);
full.handleUpdate("optional_integer",37,37);full.updateId(id);full.updateVersion(1L);
full.handleUpdate("optional_integer",37,37);
assertSame(state,full.__internalLoadState());assertEquals(EntityStatus.PERSISTED,full.get$status());
assertTrue(full.getUpdatedProperties().isEmpty());assertFalse(full.__internalHasMutationLedger());
full.auditAs("Confirm equal loaded values produce no write").save(f.context);
Expand All @@ -68,7 +68,7 @@ public class GeneratedExplicitNullTest {
boolean hadLedger=reference.__internalHasMutationLedger();
var referenceLedger=hadLedger?reference.getEntityMutationLedger():null;
assertFalse(reference.isPropertyLoaded("version"));
assertThrows(TeaQLRuntimeException.class,()->reference.updateVersion(null));
assertThrows(TeaQLRuntimeException.class,()->reference.updateProperty("version",null));
assertSame(referenceState,reference.__internalLoadState());assertEquals(EntityStatus.REFER,reference.get$status());
assertEquals(hadLedger,reference.__internalHasMutationLedger());
if(hadLedger)assertSame(referenceLedger,reference.getEntityMutationLedger());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ static void unchanged(TypePlatform reference,LoadState state){
long before=f.data.calls;int auditCount=f.audits.size(),policyCount=f.policies.size();int rejected=0;
assertThrows(TeaQLRuntimeException.class,()->reference.updateName("must not appear"));unchanged(reference,state);rejected++;
assertThrows(TeaQLRuntimeException.class,()->reference.updateProperty("name","must not appear either"));unchanged(reference,state);rejected++;
assertThrows(TeaQLRuntimeException.class,()->reference.updateVersion(9L));unchanged(reference,state);rejected++;
assertThrows(TeaQLRuntimeException.class,()->reference.updateProperty("version",9L));unchanged(reference,state);rejected++;
// Explicit negative fault injection through the legacy runtime cache
// seam; this is not an application API discovery/recommendation.
assertThrows(TeaQLRuntimeException.class,()->reference.cacheRelation("negative_cache",owner));unchanged(reference,state);rejected++;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ private static final class LedgerProbe extends BaseEntity {
private String name = "original";

private LedgerProbe(long id) {
updateId(id);
__internalInitializeNewEntityId(id);
}

private void updateName(String replacement) {
Expand Down
10 changes: 5 additions & 5 deletions teaql-core/src/main/java/io/teaql/core/BaseEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public Long getId() {
return id;
}

public BaseEntity updateId(Long id) {
BaseEntity updateId(Long id) {
if (isPropertyLoaded(ID_PROPERTY) && ObjectUtil.equals(this.id, id)) {
return this;
}
Expand All @@ -113,13 +113,13 @@ public BaseEntity updateId(Long id) {
return this;
}

@FrameworkInternal("Generated schema bootstrap fixed-ID creation only")
@FrameworkInternal("New entity ID initialization for Q creation and generated bootstrap")
public void __internalInitializeNewEntityId(Long fixedId) {
if (fixedId == null || fixedId <= 0) {
throw new IllegalArgumentException("Generated bootstrap ID must be positive");
throw new IllegalArgumentException("Creation ID must be positive");
}
if (id != null || !newItem()) {
throw new IllegalStateException("Fixed bootstrap ID can only initialize a new entity");
throw new IllegalStateException("Creation ID can only initialize a new entity");
}
id = fixedId;
markPropertyLoaded(ID_PROPERTY);
Expand All @@ -131,7 +131,7 @@ public Long getVersion() {
return version;
}

public BaseEntity updateVersion(Long version) {
BaseEntity updateVersion(Long version) {
if (isPropertyLoaded(VERSION_PROPERTY) && ObjectUtil.equals(this.version, version)) {
return this;
}
Expand Down
17 changes: 17 additions & 0 deletions teaql-core/src/main/java/io/teaql/core/ExecutableRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,23 @@ public T newEntity(UserContext context) {
return NewEntityLifecycle.initialize(context, request.getTypeName(), initialized);
}

/** Creates a new aggregate with an explicit ID; never changes an existing entity. */
public T newEntityWithId(Long id, UserContext context) {
if (context == null) throw new IllegalArgumentException("UserContext is required for entity creation");
if (id == null || id <= 0) throw new IllegalArgumentException("Creation ID must be positive");
T entity = request.internalNewEntity();
if (!(entity instanceof BaseEntity base)) {
throw new IllegalArgumentException("Explicit-ID creation requires a generated BaseEntity");
}
InternalIdGenerationService ids = context.capability(InternalIdGenerationService.class);
if (ids == null) {
throw new IllegalStateException("Explicit-ID creation requires an InternalIdGenerationService");
}
ids.ensureFloor(base.typeName(), id);
base.__internalInitializeNewEntityId(id);
return context.initializeEntity(request.getTypeName(), entity);
}

public SmartList<T> executeForList(UserContext context) {
return context.executeForList(this);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ default long nextId(String typeName) {

/**
* Advances the allocation state for {@code typeName} so future generated IDs are greater
* than {@code floor}. Generated schema bootstrap uses this after reserving model-defined IDs.
* than {@code floor}. Generated schema bootstrap and explicit-ID entity creation use this
* to reserve identities before subsequent automatic allocation.
*/
default void ensureFloor(String typeName, long floor) {
throw new UnsupportedOperationException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,4 @@ default Expression<T, U> save(UserContext userContext) {
});
}

default Expression<T, U> updateId(Long id) {
return apply(
entity -> {
entity.__internalSet("id", id);
return entity;
});
}
}
40 changes: 40 additions & 0 deletions teaql-core/src/test/java/io/teaql/core/BaseRequestTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,46 @@ public void testExecutableRequestCreatesEntityThroughTrustedContext() {
assertTrue(entity.isPropertyLoaded("id"));
}

@Test
public void testExplicitIdCreationInitializesBeforeTrustedContextAndDoesNotExposeSystemUpdaters() throws Exception {
java.util.concurrent.atomic.AtomicInteger initialized = new java.util.concurrent.atomic.AtomicInteger();
java.util.concurrent.atomic.AtomicLong floor = new java.util.concurrent.atomic.AtomicLong();
InternalIdGenerationService ids = new InternalIdGenerationService() {
public Long generateId(UserContext current, Entity entity) { return floor.incrementAndGet(); }
public void ensureFloor(String type, long value) { floor.accumulateAndGet(value, Math::max); }
};
UserContext context = (UserContext) Proxy.newProxyInstance(
UserContext.class.getClassLoader(), new Class<?>[] { UserContext.class },
(proxy, method, args) -> {
if (method.getName().equals("capability") && args[0] == InternalIdGenerationService.class) return ids;
if (method.getName().equals("initializeEntity")) {
BaseEntity value = (BaseEntity) args[1];
assertEquals(Long.valueOf(1234L), value.getId());
assertEquals(EntityStatus.NEW, value.get$status());
initialized.incrementAndGet();
return value;
}
throw new UnsupportedOperationException(method.getName());
});
var executable = new BaseRequest.TempRequest(BaseEntity.class, "BaseEntity", BaseEntity::new)
.internalComment("Create imported entity").purpose("Preserve external identity");
BaseEntity entity = (BaseEntity) executable.newEntityWithId(1234L, context);
assertEquals(Long.valueOf(1234L), entity.getId());
assertEquals(1, initialized.get());
assertEquals(1234L, floor.get());
assertEquals(Long.valueOf(1235L), ids.generateId(context, entity));
org.junit.Assert.assertThrows(IllegalArgumentException.class, () -> executable.newEntityWithId(0L, context));
org.junit.Assert.assertThrows(IllegalArgumentException.class, () -> executable.newEntityWithId(null, context));
assertEquals(1, initialized.get());
UserContext missingIds = (UserContext) Proxy.newProxyInstance(
UserContext.class.getClassLoader(), new Class<?>[] { UserContext.class },
(proxy, method, args) -> null);
org.junit.Assert.assertThrows(IllegalStateException.class, () -> executable.newEntityWithId(7L, missingIds));
org.junit.Assert.assertThrows(NoSuchMethodException.class, () -> BaseEntity.class.getMethod("updateId", Long.class));
org.junit.Assert.assertThrows(NoSuchMethodException.class, () -> BaseEntity.class.getMethod("updateVersion", Long.class));
org.junit.Assert.assertThrows(NoSuchMethodException.class, () -> io.teaql.core.value.BaseEntityExpression.class.getMethod("updateId", Long.class));
}

@Test
public void testEnhanceChildren() {
BaseRequest.TempRequest subReq = new BaseRequest.TempRequest(BaseEntity.class, "ChildEntity");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public void testMarkAsCheckedAndNeedCheck() {

// Check another entity when list is not null but does not contain
DummyEntity entity2 = new DummyEntity();
entity2.updateId(2L);
entity2.__internalSet("id", 2L);
assertTrue(checker.needCheck(context, entity2));

// Check null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,19 @@ static class Subject extends BaseEntity {

@Test
public void distinguishesValueLoadedNullAndNotLoaded() {
Subject value = new Subject(); value.updateId(1L); value.loadName("TeaQL");
Subject value = new Subject(); value.__internalSet("id", 1L); value.loadName("TeaQL");
Expression<Subject, Subject> root = new ValueExpression<>(value);
Expression<Subject, String> expression = new LoadedPropertyExpression<>(root, "name", Subject::getName);
assertEquals("TeaQL", expression.eval());
assertEquals("TeaQL", expression.orIfNull("fallback"));

Subject loadedNull = new Subject(); loadedNull.updateId(2L); loadedNull.loadName(null);
Subject loadedNull = new Subject(); loadedNull.__internalSet("id", 2L); loadedNull.loadName(null);
Expression<Subject, String> nullExpression = new LoadedPropertyExpression<>(
new ValueExpression<>(loadedNull), "name", Subject::getName);
assertNull(nullExpression.eval());
assertEquals("fallback", nullExpression.orIfNull("fallback"));

Subject partial = new Subject(); partial.updateId(3L);
Subject partial = new Subject(); partial.__internalSet("id", 3L);
Expression<Subject, String> missing = new LoadedPropertyExpression<>(
new ValueExpression<>(partial), "name", Subject::getName);
TeaQLNotLoadedException error = assertThrows(TeaQLNotLoadedException.class, missing::eval);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
public class SmartListExpressionTest {

static class DummyEntity extends BaseEntity {
public DummyEntity(Long id) { updateId(id); }
public DummyEntity(Long id) { __internalSet("id", id); }
@Override public String typeName() { return "dummy"; }
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ private TeaQLDatabase database(InvocationHandler action) throws Exception {
@Test public void writeAndReadbackUseDistinctExecutionsAndRetainLineageWithoutEntityIds() throws Exception {
var db = database((proxy, method, args) -> method.getName().equals("update") ? 1 : List.of(Map.of("id", 17L)));
var entity = new BaseEntity();
entity.updateId(17L);
entity.__internalSet("id", 17L);
var intent = MutationIntent.of("save school");
var lineage = List.of(new TraceNode(TraceKind.AUDIT_REASON, "School", 99887766L, "save school"));
var trace = SqlExecutionTrace.mutation(entity, lineage, "update", intent);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ static final class JsonGraphEntity extends BaseEntity {
}

@Test public void smartListBackReferencesKeepTheActiveSerializationPath() throws Exception {
var parent = new NamedRelationsEntity(); parent.updateId(7L);
var parent = new NamedRelationsEntity(); parent.__internalSet("id", 7L);
parent.childList = io.teaql.core.SmartList.<BaseEntity>unloaded().map(child -> child);
var child = new JsonGraphEntity(); child.updateId(9L); child.__internalSet("child", parent);
var child = new JsonGraphEntity(); child.__internalSet("id", 9L); child.__internalSet("child", parent);
parent.childList.add(child);
var mapper = new ObjectMapper().registerModule(TeaQLModule.INSTANCE);
var tree = mapper.valueToTree(parent);
Expand Down Expand Up @@ -144,8 +144,8 @@ public static class CyclicEntity extends BaseEntity {

@Test
public void cyclicIndexedGraphsUseIdentityReferencesAndDoNotRetainAPathAcrossWrites() throws Exception {
var first = new CyclicEntity(); first.updateId(1L); first.updateVersion(1L);
var second = new CyclicEntity(); second.updateId(2L); second.updateVersion(1L);
var first = new CyclicEntity(); first.__internalSet("id", 1L); first.__internalSet("version", 1L);
var second = new CyclicEntity(); second.__internalSet("id", 2L); second.__internalSet("version", 1L);
first.__internalSet("peer", second); second.__internalSet("peer", first);
var mapper = new ObjectMapper().registerModule(TeaQLModule.INSTANCE);
var json = mapper.readTree(mapper.writeValueAsString(first));
Expand All @@ -157,8 +157,8 @@ public void cyclicIndexedGraphsUseIdentityReferencesAndDoNotRetainAPathAcrossWri

@Test
public void sharedReferencesOutsideTheActivePathAreNotReducedToIdentityOnly() throws Exception {
var first = new CyclicEntity(); first.updateId(1L); first.updateVersion(1L);
var second = new CyclicEntity(); second.updateId(2L); second.updateVersion(1L);
var first = new CyclicEntity(); first.__internalSet("id", 1L); first.__internalSet("version", 1L);
var second = new CyclicEntity(); second.__internalSet("id", 2L); second.__internalSet("version", 1L);
first.__internalSet("peer", second);
second.putAdditional("_label", "shared child");
first.putAdditional("_again", second);
Expand Down Expand Up @@ -251,8 +251,8 @@ public void setName(String name) {
@Test
public void serializesDynamicPropertiesWithTeaQLModule() throws Exception {
BaseEntity entity = new BaseEntity();
entity.updateId(1001L);
entity.updateVersion(7L);
entity.__internalSet("id", 1001L);
entity.__internalSet("version", 7L);
entity.setComment("internal comment");
entity.setTraceChain(java.util.List.of(new io.teaql.core.TraceNode(
io.teaql.core.TraceKind.AUDIT_REASON, entity.typeName(), 1001L, "internal trace")));
Expand Down Expand Up @@ -290,7 +290,7 @@ public void deserializesBaseEntityWithoutBeanMutation() throws Exception {
@Test
public void serializesBaseEntitySubclassesWithTeaQLSerializer() throws Exception {
NamedEntity entity = new NamedEntity();
entity.updateId(1001L);
entity.__internalSet("id", 1001L);
entity.setName("should-not-use-bean-getter");
entity.putAdditional("#customer_asset_no", "A-10086");

Expand Down
Loading
Loading