From 56ead539526d1927154a9c9ab5312337fc184eb7 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Thu, 12 Nov 2026 00:44:06 +0800 Subject: [PATCH 01/47] fix: stage Context-derived Fix only for real entity mutations (#277) --- examples/conformance/README.md | 22 + .../GeneratedContextFixTest.java | 158 ++ .../fixture/generated-files.json | 25 + .../context-derived/fixture/lib/pom.xml | 142 ++ .../BaseServiceConfiguration.java | 0 .../example/contextfixservice/Checkers.java | 0 .../example/contextfixservice/Constants.java | 9 + .../ContextFixServiceUserContext.java | 13 + .../java/com/example/contextfixservice/E.java | 18 + .../contextfixservice/EntityMetaRegistry.java | 303 ++++ .../GeneratedRuntimeModule.java | 36 + .../java/com/example/contextfixservice/Q.java | 25 + .../contextfixservice/Repositories.java | 0 .../contextfixservice/catalog/Catalog.java | 130 ++ .../catalog/CatalogChecker.java | 52 + .../catalog/CatalogExpression.java | 51 + .../catalog/CatalogListExpression.java | 25 + .../catalog/CatalogRequest.java | 579 ++++++ .../contextfixservice/entry/Entry.java | 274 +++ .../contextfixservice/entry/EntryChecker.java | 170 ++ .../entry/EntryExpression.java | 103 ++ .../entry/EntryListExpression.java | 25 + .../contextfixservice/entry/EntryRequest.java | 1583 +++++++++++++++++ .../sampledata/SampleDataService.java | 0 .../io.teaql.core.meta.EntityMetaAssembler | 2 + .../context-derived/fixture/model.xml | 5 + .../fixture/teaql/model-provenance.json | 1 + .../context-derived/verify-local.cjs | 78 + scripts/verify-examples.sh | 1 + .../main/java/io/teaql/core/BaseEntity.java | 31 + .../java/io/teaql/core/checker/Checker.java | 22 + .../checker/internal/ContextFixFields.java | 47 + .../java/io/teaql/runtime/TeaQLRuntime.java | 24 +- .../runtime/ContextDerivedMutationTest.java | 194 ++ 34 files changed, 4146 insertions(+), 2 deletions(-) create mode 100644 examples/conformance/context-derived/GeneratedContextFixTest.java create mode 100644 examples/conformance/context-derived/fixture/generated-files.json create mode 100644 examples/conformance/context-derived/fixture/lib/pom.xml create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/BaseServiceConfiguration.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Checkers.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Constants.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/ContextFixServiceUserContext.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/E.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/EntityMetaRegistry.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/GeneratedRuntimeModule.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Q.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Repositories.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/Catalog.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogChecker.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogExpression.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogListExpression.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogRequest.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/Entry.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryChecker.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryExpression.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryListExpression.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryRequest.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/sampledata/SampleDataService.java create mode 100644 examples/conformance/context-derived/fixture/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler create mode 100644 examples/conformance/context-derived/fixture/model.xml create mode 100644 examples/conformance/context-derived/fixture/teaql/model-provenance.json create mode 100644 examples/conformance/context-derived/verify-local.cjs create mode 100644 teaql-core/src/main/java/io/teaql/core/checker/internal/ContextFixFields.java create mode 100644 teaql-runtime/src/test/java/io/teaql/runtime/ContextDerivedMutationTest.java diff --git a/examples/conformance/README.md b/examples/conformance/README.md index 020d82198..556fe6fdc 100644 --- a/examples/conformance/README.md +++ b/examples/conformance/README.md @@ -38,6 +38,28 @@ clock/root and ordinary required/range vectors, not arbitrary custom context fixers, a range-constrained generated default, security/TTL clock behavior or the complete seven-runtime diagnostic contract. +## Context-derived fields + +The focused Context-derived field gate is: + +```bash +node examples/conformance/context-derived/verify-local.cjs +``` + +It compiles an unmodified two-object generated library with local runtime +sources and runs typed Q/E and audited Save against one SQLite file twice. +Different request time, IP, and actor do not update an unchanged object. +A real edit applies update-scoped Context values and preserves create-only +values. Failed validation restores automatic Context fields while retaining +the caller's edit, which can be corrected or reverted. The application-owned +Checker and metadata customization demonstrate the same guard for non-clock +Context fields; generated timestamp assignments use that guard too. + +`TEAQL_CONTEXT_FIX_EVIDENCE_DIR` chooses a new directory for compact receipts, +logs, hashes and the SQLite store. Temporary source/build consumers are removed +on exit. This is local source acceptance, not a public-package release or +completion of every graph/dynamic-field case in all seven languages. + ## Caller-owned Spring transactions ```bash diff --git a/examples/conformance/context-derived/GeneratedContextFixTest.java b/examples/conformance/context-derived/GeneratedContextFixTest.java new file mode 100644 index 000000000..d355ae8d0 --- /dev/null +++ b/examples/conformance/context-derived/GeneratedContextFixTest.java @@ -0,0 +1,158 @@ +package io.teaql.examples.contextfix; + +import com.example.contextfixservice.*; +import com.example.contextfixservice.entry.*; +import io.teaql.core.*; +import io.teaql.core.checker.*; +import io.teaql.core.meta.*; +import io.teaql.core.businessid.BusinessClock; +import io.teaql.core.sqlite.SqliteDataServiceExecutor; +import io.teaql.provider.jdbc.JdbcSqlExecutor; +import io.teaql.runtime.*; +import java.time.*; +import java.sql.*; +import java.util.concurrent.atomic.*; +import java.io.PrintWriter; +import java.util.logging.Logger; +import javax.sql.DataSource; +import org.junit.Test; +import static org.junit.Assert.*; + +/** Application-owned customization of an unmodified generated library. */ +public class GeneratedContextFixTest { + static final LocalDateTime A = LocalDateTime.of(2026, 11, 11, 10, 0), B = A.plusHours(1); + static class Context extends DefaultUserContext { + Context(TeaQLRuntime runtime) { super(runtime); } + @Override @SuppressWarnings("unchecked") protected T evaluateExpression(String expression, Object... args) { + if ("uniStr".equals(expression)) { + if (Boolean.TRUE.equals(getAttribute("brokenContext"))) + throw new IllegalStateException("PRIVATE_CONTEXT_PROVIDER_CANARY"); + return (T) "fixture-token"; + } + return null; + } + } + static class ContextChecker extends EntryChecker { + @Override public void doCheck(UserContext context, Entry row, ObjectLocation location) { + // Freeze eligibility before the first automatic assignment. + boolean eligible = needContextFix(context, row); + if (eligible) { + if (row.isNew()) { + row.updateSourceIp(context.getAttribute("clientIp", String.class)); + row.updateOpenedBy(context.getAttribute("actor", String.class)); + } + row.updateLastIp(context.getAttribute("clientIp", String.class)); + row.updateChangedBy(context.getAttribute("actor", String.class)); + } + super.doCheck(context, row, location); + if ("INVALID".equals(row.getName())) invalidTypeCheck(context, newLocation(location, "name"), "fixture rejection"); + } + } + + @Test public void generatedQAndEAuditedSaveUsesContextOnlyForRealChanges() throws Exception { + String source = System.getProperty("teaql.expected.runtime.root"); + if (source != null) assertTrue(java.nio.file.Path.of(TeaQLRuntime.class.getProtectionDomain().getCodeSource().getLocation().toURI()) + .startsWith(java.nio.file.Path.of(source))); + String database = System.getenv("TEAQL_CONTEXT_FIX_DB"); + assertNotNull("use an owned persistent SQLite path", database); + var ds = new Source("jdbc:sqlite:" + database); + var metadata = new SimpleEntityMetaFactory(); + var data = new SqliteDataServiceExecutor("sqlite", new JdbcSqlExecutor(ds), ds); + var ids = new AtomicLong(System.currentTimeMillis()); + var runtime = TeaQLRuntime.builder().metadata(metadata).dataService("sqlite", data) + .dataService("default", data).idGenerationService(new InternalIdGenerationService() { + public Long generateId(UserContext ctx, Entity row) { return ids.incrementAndGet(); } + public void ensureFloor(String type, long floor) { ids.accumulateAndGet(floor, Math::max); } + }) + .businessClock(new BusinessClock() { + public LocalDate businessDate(UserContext ctx) { return businessDateTime(ctx).toLocalDate(); } + public LocalDateTime businessDateTime(UserContext ctx) { return ctx.getAttribute("businessNow", LocalDateTime.class); } + }).executionLogging(false).build(); + runtime.install(GeneratedRuntimeModule.module()); + var descriptor = metadata.resolveEntityDescriptor("Entry"); + // Supported model-aware customization; never patch the emitted library. + descriptor.findProperty("source_ip").with("createFunction", "clientIp"); + descriptor.findProperty("opened_by").with("createFunction", "actor"); + descriptor.findProperty("last_ip").with("updateFunction", "clientIp"); + descriptor.findProperty("changed_by").with("updateFunction", "actor"); + runtime.install(RuntimeModule.of().withCheckers(new ContextChecker())); + var context = new Context(runtime); + context.putAttribute("businessNow", A); context.putAttribute("clientIp", "192.0.2.10"); context.putAttribute("actor", "alice"); + context.ensureSchema(); + var roots = Q.catalogs().limit(1).comment("find fixture root").purpose("verify Context save").executeForList(context); + var catalog = roots.isEmpty() ? Q.catalogs().comment("create fixture root").purpose("verify Context save").newEntity(context) : roots.get(0); + if (catalog.isNew()) { catalog.updateName("Catalog"); catalog.auditAs("create Context fixture root").save(context); } + context.withActiveRoot(new ContextEntityRef("Catalog", catalog.getId())); + var failedCreate = Q.entries().comment("create with broken Context supplier").purpose("verify Fix location").newEntity(context); + failedCreate.updateName("failed"); failedCreate.updateCatalog(catalog); + context.putAttribute("brokenContext", true); + int beforeFixFailure = ds.calls.get(); + var fixError = assertThrows(CheckException.class, + () -> failedCreate.auditAs("reject broken Context supplier").save(context)); + assertEquals("Entry", fixError.getViolates().get(0).getRootType()); + assertEquals("/guardedToken", fixError.getViolates().get(0).getLocation().instancePath()); + assertTrue(fixError.getMessage().contains("guarded_token")); + assertFalse(fixError.getMessage().contains("PRIVATE_CONTEXT_PROVIDER_CANARY")); + assertEquals(beforeFixFailure, ds.calls.get()); + assertNull(failedCreate.getBornAt()); assertNull(failedCreate.getLastIp()); + assertEquals("failed", failedCreate.getName()); + context.putAttribute("brokenContext", false); + var row = Q.entries().comment("create Context fixture").purpose("verify generated Context injection").newEntity(context); + row.updateName("entry"); row.updateCatalog(catalog); row.auditAs("create Context fixture").save(context); + long id = row.getId(); + assertEquals(A, row.getBornAt()); assertEquals("alice", row.getOpenedBy()); + + var audit = new AtomicInteger(); + context.putAttribute(AppAuditEventSink.class.getName(), (AppAuditEventSink) (ctx, event) -> audit.incrementAndGet()); + context.putAttribute("businessNow", B); context.putAttribute("clientIp", "192.0.2.20"); context.putAttribute("actor", "bob"); + row = Q.entries().withIdIs(id).limit(1).comment("reload full fixture").purpose("verify no-op").executeForList(context).get(0); + long version = row.getVersion(); int connections = ds.calls.get(); + row.auditAs("first unchanged save under Context B").save(context); + row.auditAs("second unchanged save under Context B").save(context); + assertEquals(connections, ds.calls.get()); assertEquals(0, audit.get()); + assertEquals(Long.valueOf(version), row.getVersion()); assertEquals(A, row.getTouchedAt()); + assertEquals("192.0.2.10", row.getLastIp()); assertEquals("alice", row.getChangedBy()); + + row.updateName("INVALID"); Entry invalid = row; + connections = ds.calls.get(); + var error = assertThrows(CheckException.class, () -> invalid.auditAs("reject Context fixture").save(context)); + assertEquals("Entry", error.getViolates().get(0).getRootType()); + assertEquals("/name", error.getViolates().get(0).getLocation().instancePath()); + assertEquals(connections, ds.calls.get()); assertEquals(0, audit.get()); + assertEquals(A, row.getTouchedAt()); assertEquals("192.0.2.10", row.getLastIp()); + assertEquals("INVALID", row.getName()); + row.updateName("entry"); row.auditAs("cancel failed caller edit").save(context); + assertEquals(connections, ds.calls.get()); + + context.putAttribute("clientIp", "x".repeat(101)); row.updateName("blocked"); Entry invalidContext = row; + var contextError = assertThrows(CheckException.class, + () -> invalidContext.auditAs("reject invalid Context IP").save(context)); + var ipError = contextError.getViolates().stream() + .filter(item -> "last_ip".equals(item.getLocation().modelPath())).findFirst().orElseThrow(); + assertEquals("Entry", ipError.getRootType()); + assertEquals("/lastIp", ipError.getLocation().instancePath()); + assertEquals(connections, ds.calls.get()); assertEquals(0, audit.get()); + assertEquals("192.0.2.10", row.getLastIp()); + context.putAttribute("clientIp", "192.0.2.20"); + row.updateName("updated"); row.auditAs("real business update under Context B").save(context); + assertEquals(1, audit.get()); + var persisted = Q.entries().withIdIs(id).limit(1).comment("read back real update").purpose("verify SQLite persistence").executeForList(context).get(0); + assertEquals("updated", E.entry(persisted).getName().eval()); + assertEquals(A, persisted.getBornAt()); assertEquals("192.0.2.10", persisted.getSourceIp()); + assertEquals("alice", persisted.getOpenedBy()); assertEquals(B, persisted.getTouchedAt()); + assertEquals("192.0.2.20", persisted.getLastIp()); assertEquals("bob", persisted.getChangedBy()); + assertEquals(Long.valueOf(version + 1), persisted.getVersion()); + System.out.println("JAVA_CONTEXT_FIX_SQLITE=passed typedQ=true typedE=true noOpProviderCalls=0 failedCheckProviderCalls=0 updateAudits=1 objectLocation=true"); + } + + static final class Source implements DataSource { + final String url; final AtomicInteger calls = new AtomicInteger(); Source(String url) { this.url = url; } + public Connection getConnection() throws SQLException { calls.incrementAndGet(); return DriverManager.getConnection(url); } + public Connection getConnection(String u, String p) throws SQLException { return getConnection(); } + public PrintWriter getLogWriter() { return null; } public void setLogWriter(PrintWriter writer) {} + public void setLoginTimeout(int timeout) {} public int getLoginTimeout() { return 0; } + public Logger getParentLogger() { return Logger.getGlobal(); } + public T unwrap(Class type) throws SQLException { throw new SQLException("not a wrapper"); } + public boolean isWrapperFor(Class type) { return false; } + } +} diff --git a/examples/conformance/context-derived/fixture/generated-files.json b/examples/conformance/context-derived/fixture/generated-files.json new file mode 100644 index 000000000..1b30188c9 --- /dev/null +++ b/examples/conformance/context-derived/fixture/generated-files.json @@ -0,0 +1,25 @@ +{ + "lib/pom.xml" : "d84156f85a56541ad74bc068af3edd47c453c7840c8f98bf5665450d8af882c3", + "lib/src/main/java/com/example/contextfixservice/BaseServiceConfiguration.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/contextfixservice/Checkers.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/contextfixservice/Constants.java" : "3c0502eaaa2a2aaea2503fe1c700c4902e1766caf2b3db5ce7631268846715df", + "lib/src/main/java/com/example/contextfixservice/ContextFixServiceUserContext.java" : "86503139320fff959fe7e647781e51acb35ebf1b9c11aa53bbe79a508a14f4b5", + "lib/src/main/java/com/example/contextfixservice/E.java" : "655904f161dfb15713f58aac7cca1ac4db0a76ea67ef11575e37f9965d2b2aaf", + "lib/src/main/java/com/example/contextfixservice/EntityMetaRegistry.java" : "98b2b2452053aaa185f488583c58aa5e631cc25df68ec6479c84beed3bf6e97a", + "lib/src/main/java/com/example/contextfixservice/GeneratedRuntimeModule.java" : "641c1efd2cf75f5b73a75a0e59b7d47eb67fe2b5dde8abf706db5cc686c6f96a", + "lib/src/main/java/com/example/contextfixservice/Q.java" : "71ee43beda34f940ec0815aea9312f2d29d4fb218e1d50a419fec84d90591000", + "lib/src/main/java/com/example/contextfixservice/Repositories.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/contextfixservice/catalog/Catalog.java" : "0de7cc1b4adb23bd8dd01b5e88de83de858c1a48d31af01cdfb3b676ab1cf55e", + "lib/src/main/java/com/example/contextfixservice/catalog/CatalogChecker.java" : "ab950dbd72ef028423238bb148b60cd805ceb513b7c967e6795577063a1b247e", + "lib/src/main/java/com/example/contextfixservice/catalog/CatalogExpression.java" : "4201917d77ee847298abff38c2e8e6d821e68bba60e2e6e6b610bc59851e9553", + "lib/src/main/java/com/example/contextfixservice/catalog/CatalogListExpression.java" : "cddfca7d41e8112294ff0bf34ee59270177d7480249d130dc61a63a539f42c49", + "lib/src/main/java/com/example/contextfixservice/catalog/CatalogRequest.java" : "2d3dd418617a5c07c56f9fb7ec3df4f3358cd09ad3c16b9479bcb8726ec13519", + "lib/src/main/java/com/example/contextfixservice/entry/Entry.java" : "657f36230a7f6da7bac4d5e95acc9a1d65962fc67ef58e5536ba2311055c972f", + "lib/src/main/java/com/example/contextfixservice/entry/EntryChecker.java" : "7b02cc075dc39f296d9c4126c66b7a85e5bb3ebdb0c0154026309d37b255ccc2", + "lib/src/main/java/com/example/contextfixservice/entry/EntryExpression.java" : "5cda4d60429e76b29cc176a3f412add939bc3140bc152c5e2eeb5a90ac74db87", + "lib/src/main/java/com/example/contextfixservice/entry/EntryListExpression.java" : "a3df8cb675fc122c15b116f5d7f609c45b24addd8c3c1bac137c44bf19572221", + "lib/src/main/java/com/example/contextfixservice/entry/EntryRequest.java" : "6981d1fe40f62e54294e5635ac213906edb11f1b89243dbc86928895262d41ac", + "lib/src/main/java/com/example/contextfixservice/sampledata/SampleDataService.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler" : "a559507aefd933185ba6026a0d6fd55bfee397855be3ab248aa7f6c911477846", + "teaql/model-provenance.json" : "236cd90c149323654912dcb508f5603e60226fdcdfaa4851115a58a133c0606c" +} diff --git a/examples/conformance/context-derived/fixture/lib/pom.xml b/examples/conformance/context-derived/fixture/lib/pom.xml new file mode 100644 index 000000000..9dbc9977b --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/pom.xml @@ -0,0 +1,142 @@ + + + 4.0.0 + + com.example + context-fix-service-core + 0.0.1-SNAPSHOT + jar + + + 21 + 4.1.1 + 1.556-RELEASE + UTF-8 + true + + + + + teaql + https://maven.teaql.io/repository/maven-releases/ + + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + org.apache.tomcat.embed + tomcat-embed-core + 11.0.26 + + + org.apache.tomcat.embed + tomcat-embed-el + 11.0.26 + + + org.apache.tomcat.embed + tomcat-embed-websocket + 11.0.26 + + + + + + + org.springframework.boot + spring-boot-autoconfigure + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework + spring-tx + + + io.teaql + teaql-sqlite + 1.556-RELEASE + + + io.teaql + teaql-core + ${teaql.version} + + + io.teaql + teaql-runtime + ${teaql.version} + + + cn.hutool + hutool-all + 5.8.20 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.12.1 + + ${java.version} + ${maven.compiler.parameters} + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.5.0 + + + enforce-java-version + + enforce + + + + + [${java.version},) + + + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.3.0 + + + attach-sources + + jar-no-fork + + + + + + + + + + target-repo + https://maven.teaql.io/repository/maven-releases/ + + + \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/BaseServiceConfiguration.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/BaseServiceConfiguration.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Checkers.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Checkers.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Constants.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Constants.java new file mode 100644 index 000000000..f359466e1 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Constants.java @@ -0,0 +1,9 @@ + +package com.example.contextfixservice; + +import com.example.contextfixservice.catalog.Catalog; + +public interface Constants { + public static final long CATALOG_ID = 1l; + public static final Catalog CATALOG = Catalog.refer(CATALOG_ID); +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/ContextFixServiceUserContext.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/ContextFixServiceUserContext.java new file mode 100644 index 000000000..4e02f8d3f --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/ContextFixServiceUserContext.java @@ -0,0 +1,13 @@ + +package com.example.contextfixservice; + +import io.teaql.core.UserContext; +public interface ContextFixServiceUserContext extends UserContext{ + public default String uniStr(String prefix){ + throw new RuntimeException("not implemented yet"); + } + + + + +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/E.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/E.java new file mode 100644 index 000000000..ce74647eb --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/E.java @@ -0,0 +1,18 @@ + +package com.example.contextfixservice; + +import com.example.contextfixservice.catalog.Catalog; +import com.example.contextfixservice.catalog.CatalogExpression; +import com.example.contextfixservice.entry.Entry; +import com.example.contextfixservice.entry.EntryExpression; +import io.teaql.core.checker.JsonFieldNamingProfile; +import io.teaql.core.value.ValueExpression; + +public class E { + public static CatalogExpression catalog(Catalog catalog){ + return new CatalogExpression(new ValueExpression(catalog, JsonFieldNamingProfile.fromModelValue("camelCase"), "E.catalog()")); + } + public static EntryExpression entry(Entry entry){ + return new EntryExpression(new ValueExpression(entry, JsonFieldNamingProfile.fromModelValue("camelCase"), "E.entry()")); + } +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/EntityMetaRegistry.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/EntityMetaRegistry.java new file mode 100644 index 000000000..d871642c1 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/EntityMetaRegistry.java @@ -0,0 +1,303 @@ + +package com.example.contextfixservice; + +import io.teaql.core.FieldLayout; +import io.teaql.core.meta.EntityDescriptor; +import io.teaql.core.meta.EntityMetaAssembler; +import io.teaql.core.meta.EntityMetaFactory; +import io.teaql.core.meta.PropertyDescriptor; +import java.time.LocalDateTime; + +public class EntityMetaRegistry implements EntityMetaAssembler { + private EntityMetaFactory $factory; + + @Override + public void assemble(EntityMetaFactory factory) { + this.$factory = factory; + registerCatalog(); + registerEntry(); + } + private void registerCatalog() { + FieldLayout.installGenerated(com.example.contextfixservice.catalog.Catalog.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.contextfixservice.catalog.Catalog.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.contextfixservice.catalog.Catalog.class); + entityDescriptor.setEntitySupplier(com.example.contextfixservice.catalog.Catalog::new); + entityDescriptor.setAuditMaskFields(java.util.List.of()); + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.catalog.Catalog.ID_PROPERTY, Long.class) + ; + PropertyDescriptor name = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.catalog.Catalog.NAME_PROPERTY, String.class) + ; + PropertyDescriptor version = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.catalog.Catalog.VERSION_PROPERTY, Long.class) + ; + entityDescriptor.findProperty(com.example.contextfixservice.catalog.Catalog.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.catalog.Catalog.ID_PROPERTY).with("isPassword", "false") + .with("isVersion", "false") + .with("oracle_sqlType", "number(11)") + .with("javaType", "java.lang.Long") + .with("sqlType", "BIGINT") + .with("isId", "true") + .with("isBaseEntityField", "true") + .with("isBool", "false") + .with("isNumber", "false") + .with("isString", "false") + .with("isDate", "false") + .with("snowflake_sqlType", "number") + .with("graphqlType", "Long") + .with("isTime", "false") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.contextfixservice.catalog.Catalog.NAME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.catalog.Catalog.NAME_PROPERTY).with("isPassword", "false") + .with("max", "100") + .with("isVersion", "false") + .with("javaType", "java.lang.String") + .with("candidates", "Catalog") + .with("sqlType", "VARCHAR()") + .with("isId", "false") + .with("isBool", "false") + .with("isBaseEntityField", "false") + .with("isNumber", "false") + .with("isString", "true") + .with("isDate", "false") + .with("graphqlType", "String") + .with("isTime", "false") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.contextfixservice.catalog.Catalog.VERSION_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.catalog.Catalog.VERSION_PROPERTY).with("isPassword", "false") + .with("isVersion", "true") + .with("oracle_sqlType", "number(11)") + .with("javaType", "java.lang.Long") + .with("sqlType", "BIGINT") + .with("isId", "false") + .with("isBaseEntityField", "true") + .with("isBool", "false") + .with("isNumber", "false") + .with("isString", "false") + .with("isDate", "false") + .with("snowflake_sqlType", "number") + .with("graphqlType", "Long") + .with("isTime", "false") + .with("isText", "false"); + + $factory.register(entityDescriptor); + } + private void registerEntry() { + FieldLayout.installGenerated(com.example.contextfixservice.entry.Entry.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.contextfixservice.entry.Entry.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.contextfixservice.entry.Entry.class); + entityDescriptor.setEntitySupplier(com.example.contextfixservice.entry.Entry::new); + entityDescriptor.setAuditMaskFields(java.util.List.of()); + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.entry.Entry.ID_PROPERTY, Long.class) + ; + PropertyDescriptor catalog = + entityDescriptor.addObjectProperty($factory, com.example.contextfixservice.entry.Entry.CATALOG_PROPERTY, com.example.contextfixservice.catalog.Catalog.INTERNAL_TYPE, com.example.contextfixservice.catalog.Catalog.ENTRY_LIST_PROPERTY, com.example.contextfixservice.catalog.Catalog.class) + ; + PropertyDescriptor name = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.entry.Entry.NAME_PROPERTY, String.class) + ; + PropertyDescriptor bornAt = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.entry.Entry.BORN_AT_PROPERTY, LocalDateTime.class) + ; + PropertyDescriptor touchedAt = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.entry.Entry.TOUCHED_AT_PROPERTY, LocalDateTime.class) + ; + PropertyDescriptor sourceIp = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.entry.Entry.SOURCE_IP_PROPERTY, String.class) + ; + PropertyDescriptor lastIp = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.entry.Entry.LAST_IP_PROPERTY, String.class) + ; + PropertyDescriptor openedBy = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.entry.Entry.OPENED_BY_PROPERTY, String.class) + ; + PropertyDescriptor changedBy = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.entry.Entry.CHANGED_BY_PROPERTY, String.class) + ; + PropertyDescriptor guardedToken = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.entry.Entry.GUARDED_TOKEN_PROPERTY, String.class) + ; + PropertyDescriptor version = + entityDescriptor.addSimpleProperty(com.example.contextfixservice.entry.Entry.VERSION_PROPERTY, Long.class) + ; + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.ID_PROPERTY).with("isPassword", "false") + .with("isVersion", "false") + .with("oracle_sqlType", "number(11)") + .with("javaType", "java.lang.Long") + .with("sqlType", "BIGINT") + .with("isId", "true") + .with("isBaseEntityField", "true") + .with("isBool", "false") + .with("isNumber", "false") + .with("isString", "false") + .with("isDate", "false") + .with("snowflake_sqlType", "number") + .with("graphqlType", "Long") + .with("isTime", "false") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.CATALOG_PROPERTY).with("required", "true"); + + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.NAME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.NAME_PROPERTY).with("isPassword", "false") + .with("max", "100") + .with("isVersion", "false") + .with("javaType", "java.lang.String") + .with("sqlType", "VARCHAR()") + .with("isId", "false") + .with("isBool", "false") + .with("isBaseEntityField", "false") + .with("isNumber", "false") + .with("isString", "true") + .with("isDate", "false") + .with("graphqlType", "String") + .with("isTime", "false") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.BORN_AT_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.BORN_AT_PROPERTY).with("isPassword", "false") + .with("isVersion", "false") + .with("javaType", "java.time.LocalDateTime") + .with("sqlType", "TIMESTAMP") + .with("isId", "false") + .with("isBool", "false") + .with("isBaseEntityField", "false") + .with("isNumber", "false") + .with("mssql_sqlType", "dateTime") + .with("isDateTime", "true") + .with("createFunction", "now") + .with("isDate", "true") + .with("isString", "false") + .with("graphqlType", "LocalTime") + .with("isTime", "true") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.TOUCHED_AT_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.TOUCHED_AT_PROPERTY).with("isPassword", "false") + .with("isVersion", "false") + .with("updateFunction", "now") + .with("javaType", "java.time.LocalDateTime") + .with("sqlType", "TIMESTAMP") + .with("isId", "false") + .with("isBool", "false") + .with("isBaseEntityField", "false") + .with("isNumber", "false") + .with("mssql_sqlType", "dateTime") + .with("isDateTime", "true") + .with("createFunction", "now") + .with("isDate", "true") + .with("isString", "false") + .with("graphqlType", "LocalTime") + .with("isTime", "true") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.SOURCE_IP_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.SOURCE_IP_PROPERTY).with("isPassword", "false") + .with("max", "100") + .with("isVersion", "false") + .with("javaType", "java.lang.String") + .with("sqlType", "VARCHAR()") + .with("isId", "false") + .with("isBool", "false") + .with("isBaseEntityField", "false") + .with("isNumber", "false") + .with("isString", "true") + .with("isDate", "false") + .with("graphqlType", "String") + .with("isTime", "false") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.LAST_IP_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.LAST_IP_PROPERTY).with("isPassword", "false") + .with("max", "100") + .with("isVersion", "false") + .with("javaType", "java.lang.String") + .with("sqlType", "VARCHAR()") + .with("isId", "false") + .with("isBool", "false") + .with("isBaseEntityField", "false") + .with("isNumber", "false") + .with("isString", "true") + .with("isDate", "false") + .with("graphqlType", "String") + .with("isTime", "false") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.OPENED_BY_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.OPENED_BY_PROPERTY).with("isPassword", "false") + .with("max", "100") + .with("isVersion", "false") + .with("javaType", "java.lang.String") + .with("sqlType", "VARCHAR()") + .with("isId", "false") + .with("isBool", "false") + .with("isBaseEntityField", "false") + .with("isNumber", "false") + .with("isString", "true") + .with("isDate", "false") + .with("graphqlType", "String") + .with("isTime", "false") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.CHANGED_BY_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.CHANGED_BY_PROPERTY).with("isPassword", "false") + .with("max", "100") + .with("isVersion", "false") + .with("javaType", "java.lang.String") + .with("sqlType", "VARCHAR()") + .with("isId", "false") + .with("isBool", "false") + .with("isBaseEntityField", "false") + .with("isNumber", "false") + .with("isString", "true") + .with("isDate", "false") + .with("graphqlType", "String") + .with("isTime", "false") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.GUARDED_TOKEN_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.GUARDED_TOKEN_PROPERTY).with("isPassword", "false") + .with("max", "100") + .with("prefix", "") + .with("isVersion", "false") + .with("javaType", "java.lang.String") + .with("sqlType", "VARCHAR()") + .with("isId", "false") + .with("isBool", "false") + .with("isBaseEntityField", "false") + .with("isNumber", "false") + .with("createFunction", "uniStr") + .with("isString", "true") + .with("isDate", "false") + .with("graphqlType", "String") + .with("isTime", "false") + .with("isText", "false") + .with("createFunctionArgNames", "prefix"); + + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.VERSION_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.contextfixservice.entry.Entry.VERSION_PROPERTY).with("isPassword", "false") + .with("isVersion", "true") + .with("oracle_sqlType", "number(11)") + .with("javaType", "java.lang.Long") + .with("sqlType", "BIGINT") + .with("isId", "false") + .with("isBaseEntityField", "true") + .with("isBool", "false") + .with("isNumber", "false") + .with("isString", "false") + .with("isDate", "false") + .with("snowflake_sqlType", "number") + .with("graphqlType", "Long") + .with("isTime", "false") + .with("isText", "false"); + + $factory.register(entityDescriptor); + } +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/GeneratedRuntimeModule.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/GeneratedRuntimeModule.java new file mode 100644 index 000000000..9ad995608 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/GeneratedRuntimeModule.java @@ -0,0 +1,36 @@ +package com.example.contextfixservice; + +/** Passive generated manifest. Database changes require context.ensureSchema(). */ +public final class GeneratedRuntimeModule { + private static final io.teaql.core.RuntimeModule MODULE = io.teaql.core.RuntimeModule.of(new EntityMetaRegistry()) + .withCheckers(new com.example.contextfixservice.catalog.CatalogChecker(), new com.example.contextfixservice.entry.EntryChecker()) + .withBootstrap(GeneratedRuntimeModule::ensureGeneratedBootstrap); + + private GeneratedRuntimeModule() {} + public static io.teaql.core.RuntimeModule module() { return MODULE; } + + /** Canonical KSML field to selected JSON wire name, consumed by HTTP/TFP adapters. */ + public static java.util.Map> wireFieldMappings() { + return java.util.Map.ofEntries( + java.util.Map.entry("Catalog", java.util.Map.ofEntries(java.util.Map.entry("id", "id"), java.util.Map.entry("name", "name"), java.util.Map.entry("version", "version"))), + java.util.Map.entry("Entry", java.util.Map.ofEntries(java.util.Map.entry("id", "id"), java.util.Map.entry("catalog", "catalog"), java.util.Map.entry("name", "name"), java.util.Map.entry("born_at", "bornAt"), java.util.Map.entry("touched_at", "touchedAt"), java.util.Map.entry("source_ip", "sourceIp"), java.util.Map.entry("last_ip", "lastIp"), java.util.Map.entry("opened_by", "openedBy"), java.util.Map.entry("changed_by", "changedBy"), java.util.Map.entry("guarded_token", "guardedToken"), java.util.Map.entry("version", "version"))) + ); + } + + /** Accepted legacy aliases; empty until explicitly declared by the model. */ + public static java.util.Map> wireFieldAliases() { + return java.util.Map.of(); + } + + private static void ensureGeneratedBootstrap(io.teaql.core.UserContext context) { + var domainRoots = Q.catalogs().withIdIs(1L).comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(context); + com.example.contextfixservice.catalog.Catalog domainRoot; + if (domainRoots.isEmpty()) { + domainRoot = new com.example.contextfixservice.catalog.Catalog(); + io.teaql.core.GeneratedSchemaBootstrap.initializeFixedId(context, domainRoot, 1L); + domainRoot.updateName("Catalog"); + domainRoot.auditAs("create generated Domain Root Catalog").save(context); + } else { domainRoot = domainRoots.get(0); } + context.withActiveRoot(new io.teaql.core.ContextEntityRef("Catalog", domainRoot.getId())); + } +} diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Q.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Q.java new file mode 100644 index 000000000..b8c9d8f3a --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Q.java @@ -0,0 +1,25 @@ + +package com.example.contextfixservice; + +import io.teaql.core.criteria.Operator; + +public class Q { + public static com.example.contextfixservice.catalog.CatalogRequest catalogs(){ + return new com.example.contextfixservice.catalog.CatalogRequest(com.example.contextfixservice.catalog.Catalog.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.contextfixservice.catalog.CatalogRequest catalogsWithMinimalFields(){ + return new com.example.contextfixservice.catalog.CatalogRequest(com.example.contextfixservice.catalog.Catalog.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + + public static com.example.contextfixservice.entry.EntryRequest entries(){ + return new com.example.contextfixservice.entry.EntryRequest(com.example.contextfixservice.entry.Entry.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.contextfixservice.entry.EntryRequest entriesWithMinimalFields(){ + return new com.example.contextfixservice.entry.EntryRequest(com.example.contextfixservice.entry.Entry.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Repositories.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/Repositories.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/Catalog.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/Catalog.java new file mode 100644 index 000000000..7ab1bb4e6 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/Catalog.java @@ -0,0 +1,130 @@ + +package com.example.contextfixservice.catalog; + +import com.example.contextfixservice.entry.Entry; +import io.teaql.core.Audited; +import io.teaql.core.BaseEntity; +import io.teaql.core.EntityStatus; +import io.teaql.core.FieldLayout; +import io.teaql.core.FrameworkInternal; +import io.teaql.core.RemoteInput; +import io.teaql.core.SmartList; +import io.teaql.core.checker.JsonFieldNamingProfile; +import java.util.Objects; + +/** + * [TEAQL AI WARNING] + * TeaQL was explicitly designed to PREVENT AI hallucinations and random guessing. + * DO NOT GUESS METHOD NAMES! + * The methods listed below are the ONLY valid ways to interact with this entity. + * If you encounter compilation errors (e.g., method not found), DO NOT guess another method name. + * Read the method signatures in this file before proceeding. + */ +public class Catalog extends BaseEntity implements RemoteInput { + public static String INTERNAL_TYPE = "Catalog"; + + // Framework metadata: complete fixed layout, independent of SQL/projection order. + public static final String __TEAQL_FIELD_LAYOUT_REVISION = "0dcb16e6cbbd1798e584c9779cf0bb7037ed8624c44749752b291414d58d4dd5"; + public static final java.util.Map __TEAQL_FIXED_FIELD_INDEXES = + java.util.Map.ofEntries(java.util.Map.entry("id", 0), java.util.Map.entry("name", 1), java.util.Map.entry("version", 2)); + public static final java.util.Map> __TEAQL_FIXED_FIELD_MAPPINGS = + java.util.Map.ofEntries(java.util.Map.entry("id", java.util.List.of("id", "id")), java.util.Map.entry("name", java.util.List.of("name", "name")), java.util.Map.entry("version", java.util.List.of("version", "version"))); + public static final java.util.Set __TEAQL_FIXED_RELATION_NAMES = java.util.Set.of( + "entry_list"); + public static final FieldLayout __TEAQL_FIELD_LAYOUT = + FieldLayout.installGenerated(FieldLayout.generated( + Catalog.class, __TEAQL_FIELD_LAYOUT_REVISION, + __TEAQL_FIXED_FIELD_INDEXES, __TEAQL_FIXED_FIELD_MAPPINGS, __TEAQL_FIXED_RELATION_NAMES, + JsonFieldNamingProfile.fromModelValue("camelCase"))); + + + public static final String NAME_PROPERTY = "name"; + public static final String ENTRY_LIST_PROPERTY = "entry_list"; + private String name; + + private SmartList entryList; + + public String getName(){ + return this.name; + } + + public SmartList getEntryList(){ + return this.entryList == null ? SmartList.unloaded() : this.entryList; + } + public Catalog updateName(String name){ + name = (name == null ? null : name.trim()); + if(isPropertyLoaded(NAME_PROPERTY) && Objects.equals(this.name, name)){ + return this; + } + handleUpdate(NAME_PROPERTY, getName(), name); + this.name = name; + return this; + } + + public Catalog addEntry(Entry entry){ + if (entry == null){ + return this; + } + + if(null == this.entryList){ + SmartList teaqlUnloadedItems = SmartList.unloaded(); + this.entryList = teaqlUnloadedItems.map(value -> value); + } + + this.entryList.add(entry); + entry.updateCatalog(this); + return this; + } + + public static Catalog refer(Long id){ + Catalog refer = new Catalog(); + refer.__internalSet("id", id); + refer.set$status(EntityStatus.REFER); + return refer; + } + @Override + public String typeName(){ + return INTERNAL_TYPE; + } + + public Catalog comment(String comment){ + this.setComment(comment); + return this; + } + + @Override + @SuppressWarnings("unchecked") + public Audited auditAs(String action) { + return new Audited<>(this, action); + } + + // ===== Framework Internal: generated switch dispatch ===== + @Override + @FrameworkInternal + public void __internalSet(String property, Object value) { + markPropertyLoaded(property); + switch (property) { + case "name": this.name = (value == null ? null : ((String)value).trim()); break; + + case "entry_list": this.entryList = (SmartList) value; break; + default: super.__internalSet(property, value); + } + } + + @Override + @FrameworkInternal + public Object __internalGet(String property) { + switch (property) { + case "name": return this.name; + case "entry_list": return this.entryList; + default: + // Presentation uses the installed Java member mapping; SQL and + // hydration retain canonical names. These aliases only read. + switch (property) { + case "name": return this.name; + default: return super.__internalGet(property); + } + } + } + +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogChecker.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogChecker.java new file mode 100644 index 000000000..b00ede579 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogChecker.java @@ -0,0 +1,52 @@ + +package com.example.contextfixservice.catalog; + +import com.example.contextfixservice.entry.Entry; +import com.example.contextfixservice.entry.EntryChecker; +import io.teaql.core.UserContext; +import io.teaql.core.checker.Checker; +import io.teaql.core.checker.ObjectLocation; + +public class CatalogChecker implements Checker{ + + public String type(){ + return Catalog.INTERNAL_TYPE; + } + + public void checkAndFix(UserContext _context, Catalog catalog, ObjectLocation _parentLocation){ + if(needCheck(_context, catalog)){ + markAsChecked(_context, catalog); + doCheck(_context, catalog, _parentLocation); + } + } + + public void doCheck(UserContext _context, Catalog catalog, ObjectLocation _parentLocation){ + if((catalog == null)){ + return; + } + boolean _contextFixEligible = needContextFix(_context, catalog); + if(catalog.needPersist()){ + } + if(catalog.newItem()){ + }else if(catalog.updateItem()){ + if(!catalog.isPropertyLoaded("name")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "name"), "Mutation requires a fully loaded entity"); + } + + } + checkName(_context, catalog.getProperty(Catalog.NAME_PROPERTY), newLocation(_parentLocation, "name")); + for(int i = 0; catalog.getEntryList() != null && i < catalog.getEntryList().size(); i++){ + Entry entry = catalog.getEntryList().get(i); + new EntryChecker().checkAndFix(_context, entry, newLocation(_parentLocation, "entry_list", i)); + } + } + + public void checkName(UserContext _context, String name, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, name); + if((name == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, name); + + } +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogExpression.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogExpression.java new file mode 100644 index 000000000..34e0edeb3 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogExpression.java @@ -0,0 +1,51 @@ + +package com.example.contextfixservice.catalog; + +import com.example.contextfixservice.entry.Entry; +import com.example.contextfixservice.entry.EntryListExpression; +import io.teaql.core.UserContext; +import io.teaql.core.value.BaseEntityExpression; +import io.teaql.core.value.Expression; +import io.teaql.core.value.ExpressionAdaptor; +import java.util.function.Function; + +public class CatalogExpression extends ExpressionAdaptor implements BaseEntityExpression { + public CatalogExpression(Expression expression){ + super(expression); + } + + public CatalogExpression(Expression expression, Function function){ + super(expression, function); + } + + public CatalogExpression updateId(Long id){ + return new CatalogExpression(this, $it -> {((Catalog)$it).__internalSet("id", id); return this;}); + } + + public CatalogExpression save(UserContext userContext){ + return new CatalogExpression(this, $it -> ((Catalog)$it).auditAs("Saved by Expression").save(userContext)); + } + + public CatalogExpression save(String intent, UserContext userContext){ + return new CatalogExpression(this, $it -> ((Catalog)$it).auditAs(intent).save(userContext)); + } + + public boolean isNull() { + return resolve() == null; + } + + + public Expression getName(){ + return loaded("name", "getName", Catalog::getName); + } + public CatalogExpression updateName(String name){ + return new CatalogExpression(this, $it -> ((Catalog)$it).updateName(name)); + } + + public EntryListExpression getEntryList(){ + return new EntryListExpression(loaded("entry_list", "getEntryList", Catalog::getEntryList)); + } + public CatalogExpression addEntry(Entry entry){ + return new CatalogExpression(this, $it -> ((Catalog)$it).addEntry(entry)); + } +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogListExpression.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogListExpression.java new file mode 100644 index 000000000..a10d96871 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogListExpression.java @@ -0,0 +1,25 @@ + +package com.example.contextfixservice.catalog; + +import io.teaql.core.SmartList; +import io.teaql.core.value.Expression; +import io.teaql.core.value.SmartListExpression; +import java.util.function.Function; + +public class CatalogListExpression extends SmartListExpression { + public CatalogListExpression(Expression> expression){ + super(expression); + } + + public CatalogListExpression(Expression expression, Function> function){ + super(expression, function); + } + + public CatalogExpression first() { + return new CatalogExpression(super.first()); + } + + public CatalogExpression get(int index) { + return new CatalogExpression(super.get(index)); + } +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogRequest.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogRequest.java new file mode 100644 index 000000000..0681d09e8 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/catalog/CatalogRequest.java @@ -0,0 +1,579 @@ + +package com.example.contextfixservice.catalog; + +import com.example.contextfixservice.Q; +import com.example.contextfixservice.entry.Entry; +import com.example.contextfixservice.entry.EntryRequest; +import io.teaql.core.AggrFunction; +import io.teaql.core.BaseRequest; +import io.teaql.core.PropertyReference; +import io.teaql.core.SearchCriteria; +import io.teaql.core.SubQuerySearchCriteria; +import io.teaql.core.criteria.Operator; +import io.teaql.core.criteria.TwoOperatorCriteria; + +public class CatalogRequest extends BaseRequest { + + /** + * @deprecated AI agents and business code must use the generated Q facade + * instead of constructing request builders directly. + */ + @Deprecated + @SuppressWarnings("unchecked") + public CatalogRequest(Class returnType){ + this(returnType, () -> (T) new Catalog()); + } + + protected CatalogRequest(Class returnType, java.util.function.Supplier factory){ + super(returnType, factory); + selectId(); + selectVersion(); + } + + public CatalogRequest comment(String comment){ + super.internalComment(comment); + return this; + } + + // purpose() 继承自 BaseRequest,返回 ExecutableRequest(终结方法) + + public CatalogRequest returnType(Class returnType){ + super.setReturnType(returnType); + return this; + } + + public CatalogRequest enableAggregationCache(long cacheExpiredMillis){ + super.enableAggregationCache(); + super.aggregateCacheTime(cacheExpiredMillis); + return this; + } + + public CatalogRequest enableAggregationCache(){ + return enableAggregationCache(0l); + } + + + public CatalogRequest propagateAggregationCache(long cacheExpiredMillis){ + super.propagateAggregationCache(cacheExpiredMillis); + return this; + } + + /** + * Accept best-effort stateful seek optimization for browsing consecutive pages. + * Do not use this for business processing that must visit every row exactly once. + */ + public CatalogRequest optimizeForContinuousPageFetch(){ + super.optimizeForContinuousPageFetch(); + return this; + } + + public CatalogRequest optimizeForContinuousPageFetch(String namespace, int ttlSeconds){ + super.optimizeForContinuousPageFetch(namespace, ttlSeconds); + return this; + } + + public CatalogRequest optimizePaginationWithIdSet(){ + super.optimizePaginationWithIdSet(); + return this; + } + + public CatalogRequest optimizePaginationWithIdSet( + String namespace, int ttlSeconds, int maxIds){ + super.optimizePaginationWithIdSet(namespace, ttlSeconds, maxIds); + return this; + } + + public CatalogRequest topNProbeParentThreshold(int threshold){ + super.topNProbeParentThreshold(threshold); + return this; + } + + public CatalogRequest appendSearchCriteria(SearchCriteria searchCriteria){ + return (CatalogRequest)super.appendSearchCriteria(searchCriteria); + } + + public CatalogRequest filter(String property1, Operator operator, String property2){ + return appendSearchCriteria(new TwoOperatorCriteria(operator, new PropertyReference(property1), new PropertyReference(property2))); + } + + + public CatalogRequest matchingAnyOf(CatalogRequest catalog){ + super.internalMatchAny(catalog); + return this; + } + + public CatalogRequest enhanceChildrenIfNeeded(){ + return this; + } + + public CatalogRequest withDeletedRows(){ + super.withDeletedRows(); + return this; + } + + public CatalogRequest deletedRowsOnly(){ + super.deletedRowsOnly(); + return this; + } + + public CatalogRequest selectSelf(){ + super.selectSelf(); + return selectId().selectName().selectVersion(); + } + + public CatalogRequest selectSelfFields(){ + return selectSelf(); + } + + public CatalogRequest selectSelfWithoutParent(){ + selectId(); + selectVersion(); + selectProperty(Catalog.ID_PROPERTY); + selectProperty(Catalog.NAME_PROPERTY); + selectProperty(Catalog.VERSION_PROPERTY); + return this; + } + + public CatalogRequest selectAll(){ + super.selectAll(); + return selectId().selectName().selectVersion(); + } + + public CatalogRequest selectChildren(){ + super.selectAny(); + selectEntryList(); + return selectId().selectName().selectVersion(); + } + + + public CatalogRequest selectId(){ + selectProperty(Catalog.ID_PROPERTY); + return this; + } + + /** + * fill the id with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS id) to fetch id property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public CatalogRequest unselectId(){ + unselectProperty(Catalog.ID_PROPERTY); + return this; + } + public CatalogRequest selectName(){ + selectProperty(Catalog.NAME_PROPERTY); + return this; + } + + /** + * fill the name with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS name) to fetch name property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public CatalogRequest unselectName(){ + unselectProperty(Catalog.NAME_PROPERTY); + return this; + } + public CatalogRequest selectVersion(){ + selectProperty(Catalog.VERSION_PROPERTY); + return this; + } + + /** + * fill the version with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS version) to fetch version property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public CatalogRequest unselectVersion(){ + unselectProperty(Catalog.VERSION_PROPERTY); + return this; + } + public CatalogRequest selectEntryList(){ + return selectEntryListWith(Q.entries().selectSelf()); + } + + public CatalogRequest selectEntryListWith(EntryRequest entryList){ + enhanceRelation(Catalog.ENTRY_LIST_PROPERTY, entryList, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_SELECT, "selectEntryListWith", null, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest withId(Operator operator, Object... values){ + return appendSearchCriteria(createIdCriteria(operator, values)); + } + + public SearchCriteria createIdCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Catalog.ID_PROPERTY, operator, values); + } + + public CatalogRequest withIdIsNot(Long id){ + return withId(Operator.NOT_EQUAL, id); + } + + public CatalogRequest withIdIn(Long... id){ + return withId(Operator.IN, (Object[])id); + } + + public CatalogRequest withIdNotIn(Long... id){ + return withId(Operator.NOT_IN, (Object[])id); + } + public CatalogRequest withIdIs(Long id){ + return withId(Operator.EQUAL, id); + } + + + + public CatalogRequest filterByName(String... name){ + if (name == null || name.length == 0) { + throw new IllegalArgumentException("filterByName parameter name cannot be empty"); + } + return appendSearchCriteria(createNameCriteria(Operator.EQUAL, (Object[])name)); + } + + public CatalogRequest withName(Operator operator, Object... values){ + return appendSearchCriteria(createNameCriteria(operator, values)); + } + + public CatalogRequest withNameIsUnknown(){ + return withName(Operator.IS_NULL); + } + + public CatalogRequest withNameIsKnown(){ + return withName(Operator.IS_NOT_NULL); + } + + public SearchCriteria createNameCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Catalog.NAME_PROPERTY, operator, values); + } + + public CatalogRequest withNameIsNot(String name){ + return withName(Operator.NOT_EQUAL, name); + } + + public CatalogRequest withNameIn(String... name){ + return withName(Operator.IN, (Object[])name); + } + + public CatalogRequest withNameNotIn(String... name){ + return withName(Operator.NOT_IN, (Object[])name); + } + public CatalogRequest withNameGreaterThan(String name){ + return withName(Operator.GREATER_THAN, name); + } + + public CatalogRequest withNameGreaterThanOrEqualTo(String name){ + return withName(Operator.GREATER_THAN_OR_EQUAL, name); + } + + public CatalogRequest withNameLessThan(String name){ + return withName(Operator.LESS_THAN, name); + } + + public CatalogRequest withNameLessThanOrEqualTo(String name){ + return withName(Operator.LESS_THAN_OR_EQUAL, name); + } + + public CatalogRequest withNameBetween(String startOfName, String endOfName){ + return withName(Operator.BETWEEN, startOfName, endOfName); + } + public CatalogRequest withNameStartingWith(String name){ + return withName(Operator.BEGIN_WITH, name); + } + public CatalogRequest withNameContaining(String name){ + return withName(Operator.CONTAIN, name); + } + + public CatalogRequest withNameNotContaining(String name){ + return withName(Operator.NOT_CONTAIN, name); + } + + public CatalogRequest withNameNotStartingWith(String name){ + return withName(Operator.NOT_BEGIN_WITH, name); + } + + public CatalogRequest withNameEndingWith(String name){ + return withName(Operator.END_WITH, name); + } + + public CatalogRequest withNameNotEndingWith(String name){ + return withName(Operator.NOT_END_WITH, name); + } + + public CatalogRequest withNameIs(String name){ + return withName(Operator.EQUAL, name); + } + + public CatalogRequest withNameSoundingLike(String name){ + return withName(Operator.SOUNDS_LIKE, name); + } + + + + public CatalogRequest filterByVersion(Long... version){ + if (version == null || version.length == 0) { + throw new IllegalArgumentException("filterByVersion parameter version cannot be empty"); + } + return appendSearchCriteria(createVersionCriteria(Operator.EQUAL, (Object[])version)); + } + + public CatalogRequest withVersion(Operator operator, Object... values){ + return appendSearchCriteria(createVersionCriteria(operator, values)); + } + + public CatalogRequest withVersionIsUnknown(){ + return withVersion(Operator.IS_NULL); + } + + public CatalogRequest withVersionIsKnown(){ + return withVersion(Operator.IS_NOT_NULL); + } + + public SearchCriteria createVersionCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Catalog.VERSION_PROPERTY, operator, values); + } + + public CatalogRequest withVersionIs(Long version){ + return withVersion(Operator.EQUAL, version); + } + + public CatalogRequest withVersionIsNot(Long version){ + return withVersion(Operator.NOT_EQUAL, version); + } + + public CatalogRequest withVersionIn(Long... version){ + return withVersion(Operator.IN, (Object[])version); + } + + public CatalogRequest withVersionNotIn(Long... version){ + return withVersion(Operator.NOT_IN, (Object[])version); + } + public CatalogRequest withVersionGreaterThan(Long version){ + return withVersion(Operator.GREATER_THAN, version); + } + + public CatalogRequest withVersionGreaterThanOrEqualTo(Long version){ + return withVersion(Operator.GREATER_THAN_OR_EQUAL, version); + } + + public CatalogRequest withVersionLessThan(Long version){ + return withVersion(Operator.LESS_THAN, version); + } + + public CatalogRequest withVersionLessThanOrEqualTo(Long version){ + return withVersion(Operator.LESS_THAN_OR_EQUAL, version); + } + + public CatalogRequest withVersionBetween(Long startOfVersion, Long endOfVersion){ + return withVersion(Operator.BETWEEN, startOfVersion, endOfVersion); + } + + + public CatalogRequest withEntryListMatching(EntryRequest entryRequest){ + return appendSearchCriteria(new SubQuerySearchCriteria(Catalog.ID_PROPERTY, entryRequest, Entry.CATALOG_PROPERTY)); + } + + public CatalogRequest withoutEntryListMatching(EntryRequest entryRequest){ + return appendSearchCriteria(SearchCriteria.not(new SubQuerySearchCriteria(Catalog.ID_PROPERTY, entryRequest, Entry.CATALOG_PROPERTY))); + } + + public CatalogRequest haveEntries(){ + return withEntryListMatching(Q.entries().unlimited()); + } + + public CatalogRequest haveNoEntries(){ + return withoutEntryListMatching(Q.entries().unlimited()); + } + + public CatalogRequest count(){ + super.count(); + setPageCountOperation(io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.NAMED_COUNT, "count", null, null)); + return this; + } + public CatalogRequest countAs(String retName){ + super.count(retName); + setPageCountOperation(io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.NAMED_COUNT, "countAs", retName, null)); + return this; + } + public CatalogRequest groupByEntriesWithDetails(EntryRequest subRequest){ + aggregate(Catalog.ENTRY_LIST_PROPERTY, subRequest); + return this; + } + + public CatalogRequest groupById(){ + groupBy(Catalog.ID_PROPERTY); + return this; + } + + public CatalogRequest groupByIdAs(String retName){ + groupBy(retName, Catalog.ID_PROPERTY); + return this; + } + + public CatalogRequest groupByIdWithFunction(String retName, AggrFunction function){ + groupBy(retName, Catalog.ID_PROPERTY, function); + return this; + } + + public CatalogRequest groupByName(){ + groupBy(Catalog.NAME_PROPERTY); + return this; + } + + public CatalogRequest groupByNameAs(String retName){ + groupBy(retName, Catalog.NAME_PROPERTY); + return this; + } + + public CatalogRequest groupByNameWithFunction(String retName, AggrFunction function){ + groupBy(retName, Catalog.NAME_PROPERTY, function); + return this; + } + + public CatalogRequest groupByVersion(){ + groupBy(Catalog.VERSION_PROPERTY); + return this; + } + + public CatalogRequest groupByVersionAs(String retName){ + groupBy(retName, Catalog.VERSION_PROPERTY); + return this; + } + + public CatalogRequest groupByVersionWithFunction(String retName, AggrFunction function){ + groupBy(retName, Catalog.VERSION_PROPERTY, function); + return this; + } + + + + public CatalogRequest orderByIdAscending(){ + addOrderByAscending(Catalog.ID_PROPERTY); + return this; + } + + public CatalogRequest orderByIdDescending(){ + addOrderByDescending(Catalog.ID_PROPERTY); + return this; + } + + public CatalogRequest orderByNameAscending(){ + addOrderByAscending(Catalog.NAME_PROPERTY); + return this; + } + + public CatalogRequest orderByNameDescending(){ + addOrderByDescending(Catalog.NAME_PROPERTY); + return this; + } + public CatalogRequest orderByNameAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Catalog.NAME_PROPERTY); + return this; + } + + public CatalogRequest orderByNameDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Catalog.NAME_PROPERTY); + return this; + } + public CatalogRequest orderByVersionAscending(){ + addOrderByAscending(Catalog.VERSION_PROPERTY); + return this; + } + + public CatalogRequest orderByVersionDescending(){ + addOrderByDescending(Catalog.VERSION_PROPERTY); + return this; + } + + + public CatalogRequest statsFromEntriesAs(String name, EntryRequest subRequest){ + return statsFromEntriesAs(name, subRequest, false); + } + + public CatalogRequest statsFromEntriesAs(String name, EntryRequest subRequest, boolean singleResult){ + addRelationAggregate(name, subRequest, Entry.CATALOG_PROPERTY, singleResult, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "statsFromEntriesAs", name, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest statsFromEntries(EntryRequest subRequest){ + return statsFromEntriesAs(REFINEMENTS, subRequest); + } + public CatalogRequest countEntries(){ + addRelationCount("Count", Q.entries().unlimited(), Entry.CATALOG_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countEntries", null, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest countEntriesAs(String name){ + addRelationCount(name, Q.entries().unlimited(), Entry.CATALOG_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countEntriesAs", name, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest countEntriesWith(String name, EntryRequest subRequest){ + addRelationCount(name, subRequest, Entry.CATALOG_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countEntriesWith", name, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + + + /** + * get topN records + * @param topN records number + */ + public CatalogRequest top(int topN) { + super.top(topN); + return this; + } + + /** Cross-runtime bounded-query alias. */ + public CatalogRequest limit(int limit) { + return top(limit); + } + + /** + * get records from offset(inclusive) to offset+size(exclusive) + * @param offset record offset + * @param size records number + */ + public CatalogRequest offset(int offset, int size) { + super.offset(offset, size); + return this; + } + + /** + * retrieve all records + */ + public CatalogRequest unlimited() { + super.unlimited(); + return this; + } + + /** + * get records of one page + * @param pageNumber page number(1-based) + * @param pageSize page size + */ + public CatalogRequest page(int pageNumber, int pageSize) { + int offset = (pageNumber - 1) * pageSize; + return offset(offset, pageSize); + } + + /** + * get records of one page, default page size is 10 + * @param pageNumber page number(1-based) + */ + public CatalogRequest page(int pageNumber) { + return page(pageNumber, 10); + } +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/Entry.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/Entry.java new file mode 100644 index 000000000..c4f863c90 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/Entry.java @@ -0,0 +1,274 @@ + +package com.example.contextfixservice.entry; + +import com.example.contextfixservice.catalog.Catalog; +import io.teaql.core.Audited; +import io.teaql.core.BaseEntity; +import io.teaql.core.EntityStatus; +import io.teaql.core.FieldLayout; +import io.teaql.core.FrameworkInternal; +import io.teaql.core.RemoteInput; +import io.teaql.core.checker.JsonFieldNamingProfile; +import java.time.LocalDateTime; +import java.util.Objects; + +/** + * [TEAQL AI WARNING] + * TeaQL was explicitly designed to PREVENT AI hallucinations and random guessing. + * DO NOT GUESS METHOD NAMES! + * The methods listed below are the ONLY valid ways to interact with this entity. + * If you encounter compilation errors (e.g., method not found), DO NOT guess another method name. + * Read the method signatures in this file before proceeding. + */ +public class Entry extends BaseEntity implements RemoteInput { + public static String INTERNAL_TYPE = "Entry"; + + // Framework metadata: complete fixed layout, independent of SQL/projection order. + public static final String __TEAQL_FIELD_LAYOUT_REVISION = "7ae3f6f25be2681c105a55532a8c60a599eada522a7c70284e22e2172db13492"; + public static final java.util.Map __TEAQL_FIXED_FIELD_INDEXES = + java.util.Map.ofEntries(java.util.Map.entry("id", 0), java.util.Map.entry("catalog", 1), java.util.Map.entry("name", 2), java.util.Map.entry("born_at", 3), java.util.Map.entry("touched_at", 4), java.util.Map.entry("source_ip", 5), java.util.Map.entry("last_ip", 6), java.util.Map.entry("opened_by", 7), java.util.Map.entry("changed_by", 8), java.util.Map.entry("guarded_token", 9), java.util.Map.entry("version", 10)); + public static final java.util.Map> __TEAQL_FIXED_FIELD_MAPPINGS = + java.util.Map.ofEntries(java.util.Map.entry("id", java.util.List.of("id", "id")), java.util.Map.entry("catalog", java.util.List.of("catalog", "catalog")), java.util.Map.entry("name", java.util.List.of("name", "name")), java.util.Map.entry("born_at", java.util.List.of("bornAt", "born_at")), java.util.Map.entry("touched_at", java.util.List.of("touchedAt", "touched_at")), java.util.Map.entry("source_ip", java.util.List.of("sourceIp", "source_ip")), java.util.Map.entry("last_ip", java.util.List.of("lastIp", "last_ip")), java.util.Map.entry("opened_by", java.util.List.of("openedBy", "opened_by")), java.util.Map.entry("changed_by", java.util.List.of("changedBy", "changed_by")), java.util.Map.entry("guarded_token", java.util.List.of("guardedToken", "guarded_token")), java.util.Map.entry("version", java.util.List.of("version", "version"))); + public static final java.util.Set __TEAQL_FIXED_RELATION_NAMES = java.util.Set.of( +); + public static final FieldLayout __TEAQL_FIELD_LAYOUT = + FieldLayout.installGenerated(FieldLayout.generated( + Entry.class, __TEAQL_FIELD_LAYOUT_REVISION, + __TEAQL_FIXED_FIELD_INDEXES, __TEAQL_FIXED_FIELD_MAPPINGS, __TEAQL_FIXED_RELATION_NAMES, + JsonFieldNamingProfile.fromModelValue("camelCase"))); + + + public static final String CATALOG_PROPERTY = "catalog"; + public static final String NAME_PROPERTY = "name"; + public static final String BORN_AT_PROPERTY = "born_at"; + public static final String TOUCHED_AT_PROPERTY = "touched_at"; + public static final String SOURCE_IP_PROPERTY = "source_ip"; + public static final String LAST_IP_PROPERTY = "last_ip"; + public static final String OPENED_BY_PROPERTY = "opened_by"; + public static final String CHANGED_BY_PROPERTY = "changed_by"; + public static final String GUARDED_TOKEN_PROPERTY = "guarded_token"; + private Catalog catalog; + + private String name; + + private LocalDateTime bornAt; + + private LocalDateTime touchedAt; + + private String sourceIp; + + private String lastIp; + + private String openedBy; + + private String changedBy; + + private String guardedToken; + + + public Catalog getCatalog(){ + return this.catalog; + } + + public String getName(){ + return this.name; + } + + public LocalDateTime getBornAt(){ + return this.bornAt; + } + + public LocalDateTime getTouchedAt(){ + return this.touchedAt; + } + + public String getSourceIp(){ + return this.sourceIp; + } + + public String getLastIp(){ + return this.lastIp; + } + + public String getOpenedBy(){ + return this.openedBy; + } + + public String getChangedBy(){ + return this.changedBy; + } + + public String getGuardedToken(){ + return this.guardedToken; + } + + public Entry updateCatalog(Catalog catalog){ + if(isPropertyLoaded(CATALOG_PROPERTY) && Objects.equals(this.catalog, catalog)){ + return this; + } + handleUpdate(CATALOG_PROPERTY, getCatalog(), catalog); + this.catalog = catalog; + return this; + } + + public Entry updateName(String name){ + name = (name == null ? null : name.trim()); + if(isPropertyLoaded(NAME_PROPERTY) && Objects.equals(this.name, name)){ + return this; + } + handleUpdate(NAME_PROPERTY, getName(), name); + this.name = name; + return this; + } + + public Entry updateBornAt(LocalDateTime bornAt){ + if(isPropertyLoaded(BORN_AT_PROPERTY) && Objects.equals(this.bornAt, bornAt)){ + return this; + } + handleUpdate(BORN_AT_PROPERTY, getBornAt(), bornAt); + this.bornAt = bornAt; + return this; + } + + public Entry updateTouchedAt(LocalDateTime touchedAt){ + if(isPropertyLoaded(TOUCHED_AT_PROPERTY) && Objects.equals(this.touchedAt, touchedAt)){ + return this; + } + handleUpdate(TOUCHED_AT_PROPERTY, getTouchedAt(), touchedAt); + this.touchedAt = touchedAt; + return this; + } + + public Entry updateSourceIp(String sourceIp){ + sourceIp = (sourceIp == null ? null : sourceIp.trim()); + if(isPropertyLoaded(SOURCE_IP_PROPERTY) && Objects.equals(this.sourceIp, sourceIp)){ + return this; + } + handleUpdate(SOURCE_IP_PROPERTY, getSourceIp(), sourceIp); + this.sourceIp = sourceIp; + return this; + } + + public Entry updateLastIp(String lastIp){ + lastIp = (lastIp == null ? null : lastIp.trim()); + if(isPropertyLoaded(LAST_IP_PROPERTY) && Objects.equals(this.lastIp, lastIp)){ + return this; + } + handleUpdate(LAST_IP_PROPERTY, getLastIp(), lastIp); + this.lastIp = lastIp; + return this; + } + + public Entry updateOpenedBy(String openedBy){ + openedBy = (openedBy == null ? null : openedBy.trim()); + if(isPropertyLoaded(OPENED_BY_PROPERTY) && Objects.equals(this.openedBy, openedBy)){ + return this; + } + handleUpdate(OPENED_BY_PROPERTY, getOpenedBy(), openedBy); + this.openedBy = openedBy; + return this; + } + + public Entry updateChangedBy(String changedBy){ + changedBy = (changedBy == null ? null : changedBy.trim()); + if(isPropertyLoaded(CHANGED_BY_PROPERTY) && Objects.equals(this.changedBy, changedBy)){ + return this; + } + handleUpdate(CHANGED_BY_PROPERTY, getChangedBy(), changedBy); + this.changedBy = changedBy; + return this; + } + + public Entry updateGuardedToken(String guardedToken){ + guardedToken = (guardedToken == null ? null : guardedToken.trim()); + if(isPropertyLoaded(GUARDED_TOKEN_PROPERTY) && Objects.equals(this.guardedToken, guardedToken)){ + return this; + } + handleUpdate(GUARDED_TOKEN_PROPERTY, getGuardedToken(), guardedToken); + this.guardedToken = guardedToken; + return this; + } + + + public static Entry refer(Long id){ + Entry refer = new Entry(); + refer.__internalSet("id", id); + refer.set$status(EntityStatus.REFER); + return refer; + } + @Override + public String typeName(){ + return INTERNAL_TYPE; + } + + public Entry comment(String comment){ + this.setComment(comment); + return this; + } + + @Override + @SuppressWarnings("unchecked") + public Audited auditAs(String action) { + return new Audited<>(this, action); + } + + // ===== Framework Internal: generated switch dispatch ===== + @Override + @FrameworkInternal + public void __internalSet(String property, Object value) { + markPropertyLoaded(property); + switch (property) { + case "catalog": this.catalog = (Catalog) value; break; + + case "name": this.name = (value == null ? null : ((String)value).trim()); break; + + case "born_at": this.bornAt = (LocalDateTime) value; break; + + case "touched_at": this.touchedAt = (LocalDateTime) value; break; + + case "source_ip": this.sourceIp = (value == null ? null : ((String)value).trim()); break; + + case "last_ip": this.lastIp = (value == null ? null : ((String)value).trim()); break; + + case "opened_by": this.openedBy = (value == null ? null : ((String)value).trim()); break; + + case "changed_by": this.changedBy = (value == null ? null : ((String)value).trim()); break; + + case "guarded_token": this.guardedToken = (value == null ? null : ((String)value).trim()); break; + + default: super.__internalSet(property, value); + } + } + + @Override + @FrameworkInternal + public Object __internalGet(String property) { + switch (property) { + case "catalog": return this.catalog; + case "name": return this.name; + case "born_at": return this.bornAt; + case "touched_at": return this.touchedAt; + case "source_ip": return this.sourceIp; + case "last_ip": return this.lastIp; + case "opened_by": return this.openedBy; + case "changed_by": return this.changedBy; + case "guarded_token": return this.guardedToken; + default: + // Presentation uses the installed Java member mapping; SQL and + // hydration retain canonical names. These aliases only read. + switch (property) { + case "catalog": return this.catalog; + case "name": return this.name; + case "bornAt": return this.bornAt; + case "touchedAt": return this.touchedAt; + case "sourceIp": return this.sourceIp; + case "lastIp": return this.lastIp; + case "openedBy": return this.openedBy; + case "changedBy": return this.changedBy; + case "guardedToken": return this.guardedToken; + default: return super.__internalGet(property); + } + } + } + +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryChecker.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryChecker.java new file mode 100644 index 000000000..46bc7e8f1 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryChecker.java @@ -0,0 +1,170 @@ + +package com.example.contextfixservice.entry; + +import com.example.contextfixservice.catalog.Catalog; +import com.example.contextfixservice.catalog.CatalogChecker; +import io.teaql.core.UserContext; +import io.teaql.core.checker.Checker; +import io.teaql.core.checker.ObjectLocation; +import java.time.LocalDateTime; + +public class EntryChecker implements Checker{ + + public String type(){ + return Entry.INTERNAL_TYPE; + } + + public void checkAndFix(UserContext _context, Entry entry, ObjectLocation _parentLocation){ + if(needCheck(_context, entry)){ + markAsChecked(_context, entry); + doCheck(_context, entry, _parentLocation); + } + } + + public void doCheck(UserContext _context, Entry entry, ObjectLocation _parentLocation){ + if((entry == null)){ + return; + } + boolean _contextFixEligible = needContextFix(_context, entry); + if(entry.needPersist()){ + } + if(entry.newItem()){ + if(_contextFixEligible){ + applyContextFix(_context, newLocation(_parentLocation, "born_at"), () -> { + entry.updateBornAt(_context.evaluate("now")); + _context.recordFixEvidence(new io.teaql.core.checker.FixEvidence(type(), "born_at", + "now".equalsIgnoreCase("now") ? io.teaql.core.checker.FixEvidence.Source.CLOCK : io.teaql.core.checker.FixEvidence.Source.CONTEXT, + "now".equalsIgnoreCase("now") ? "graphClock" : "contextFunction:now")); + }); + }if(_contextFixEligible){ + applyContextFix(_context, newLocation(_parentLocation, "touched_at"), () -> { + entry.updateTouchedAt(_context.evaluate("now")); + _context.recordFixEvidence(new io.teaql.core.checker.FixEvidence(type(), "touched_at", + "now".equalsIgnoreCase("now") ? io.teaql.core.checker.FixEvidence.Source.CLOCK : io.teaql.core.checker.FixEvidence.Source.CONTEXT, + "now".equalsIgnoreCase("now") ? "graphClock" : "contextFunction:now")); + }); + }if(_contextFixEligible){ + applyContextFix(_context, newLocation(_parentLocation, "guarded_token"), () -> { + entry.updateGuardedToken(_context.evaluate("uniStr", "prefix")); + _context.recordFixEvidence(new io.teaql.core.checker.FixEvidence(type(), "guarded_token", + "now".equalsIgnoreCase("uniStr") ? io.teaql.core.checker.FixEvidence.Source.CLOCK : io.teaql.core.checker.FixEvidence.Source.CONTEXT, + "now".equalsIgnoreCase("uniStr") ? "graphClock" : "contextFunction:uniStr")); + }); + } + }else if(entry.updateItem()){ + if(_contextFixEligible){ + applyContextFix(_context, newLocation(_parentLocation, "touched_at"), () -> { + entry.updateTouchedAt(_context.evaluate("now")); + _context.recordFixEvidence(new io.teaql.core.checker.FixEvidence(type(), "touched_at", + "now".equalsIgnoreCase("now") ? io.teaql.core.checker.FixEvidence.Source.CLOCK : io.teaql.core.checker.FixEvidence.Source.CONTEXT, + "now".equalsIgnoreCase("now") ? "graphClock" : "contextFunction:now")); + }); + } + if(!entry.isPropertyLoaded("catalog")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "catalog"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("name")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "name"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("born_at")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "born_at"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("touched_at")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "touched_at"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("source_ip")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "source_ip"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("last_ip")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "last_ip"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("opened_by")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "opened_by"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("changed_by")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "changed_by"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("guarded_token")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "guarded_token"), "Mutation requires a fully loaded entity"); + } + + } + checkCatalog(_context, entry.getProperty(Entry.CATALOG_PROPERTY), newLocation(_parentLocation, "catalog")); + checkName(_context, entry.getProperty(Entry.NAME_PROPERTY), newLocation(_parentLocation, "name")); + checkBornAt(_context, entry.getProperty(Entry.BORN_AT_PROPERTY), newLocation(_parentLocation, "born_at")); + checkTouchedAt(_context, entry.getProperty(Entry.TOUCHED_AT_PROPERTY), newLocation(_parentLocation, "touched_at")); + checkSourceIp(_context, entry.getProperty(Entry.SOURCE_IP_PROPERTY), newLocation(_parentLocation, "source_ip")); + checkLastIp(_context, entry.getProperty(Entry.LAST_IP_PROPERTY), newLocation(_parentLocation, "last_ip")); + checkOpenedBy(_context, entry.getProperty(Entry.OPENED_BY_PROPERTY), newLocation(_parentLocation, "opened_by")); + checkChangedBy(_context, entry.getProperty(Entry.CHANGED_BY_PROPERTY), newLocation(_parentLocation, "changed_by")); + checkGuardedToken(_context, entry.getProperty(Entry.GUARDED_TOKEN_PROPERTY), newLocation(_parentLocation, "guarded_token")); + } + + public void checkCatalog(UserContext _context, Catalog catalog, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, catalog); + if((catalog == null)){ + return; + } + new CatalogChecker().checkAndFix(_context, catalog, _parentLocation); + } + public void checkName(UserContext _context, String name, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, name); + if((name == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, name); + + } + public void checkBornAt(UserContext _context, LocalDateTime bornAt, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, bornAt); + if((bornAt == null)){ + return; + } + } + public void checkTouchedAt(UserContext _context, LocalDateTime touchedAt, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, touchedAt); + if((touchedAt == null)){ + return; + } + } + public void checkSourceIp(UserContext _context, String sourceIp, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, sourceIp); + if((sourceIp == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, sourceIp); + + } + public void checkLastIp(UserContext _context, String lastIp, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, lastIp); + if((lastIp == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, lastIp); + + } + public void checkOpenedBy(UserContext _context, String openedBy, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, openedBy); + if((openedBy == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, openedBy); + + } + public void checkChangedBy(UserContext _context, String changedBy, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, changedBy); + if((changedBy == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, changedBy); + + } + public void checkGuardedToken(UserContext _context, String guardedToken, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, guardedToken); + if((guardedToken == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, guardedToken); + + } +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryExpression.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryExpression.java new file mode 100644 index 000000000..b61497cdf --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryExpression.java @@ -0,0 +1,103 @@ + +package com.example.contextfixservice.entry; + +import com.example.contextfixservice.catalog.Catalog; +import com.example.contextfixservice.catalog.CatalogExpression; +import io.teaql.core.UserContext; +import io.teaql.core.value.BaseEntityExpression; +import io.teaql.core.value.Expression; +import io.teaql.core.value.ExpressionAdaptor; +import java.time.LocalDateTime; +import java.util.function.Function; + +public class EntryExpression extends ExpressionAdaptor implements BaseEntityExpression { + public EntryExpression(Expression expression){ + super(expression); + } + + public EntryExpression(Expression expression, Function function){ + super(expression, function); + } + + public EntryExpression updateId(Long id){ + return new EntryExpression(this, $it -> {((Entry)$it).__internalSet("id", id); return this;}); + } + + public EntryExpression save(UserContext userContext){ + return new EntryExpression(this, $it -> ((Entry)$it).auditAs("Saved by Expression").save(userContext)); + } + + public EntryExpression save(String intent, UserContext userContext){ + return new EntryExpression(this, $it -> ((Entry)$it).auditAs(intent).save(userContext)); + } + + public boolean isNull() { + return resolve() == null; + } + + + public CatalogExpression getCatalog(){ + return new CatalogExpression(loaded("catalog", "getCatalog", Entry::getCatalog)); + } + + public EntryExpression updateCatalog(Catalog catalog){ + return new EntryExpression(this, $it -> ((Entry)$it).updateCatalog(catalog)); + } + + public Expression getName(){ + return loaded("name", "getName", Entry::getName); + } + public EntryExpression updateName(String name){ + return new EntryExpression(this, $it -> ((Entry)$it).updateName(name)); + } + + public Expression getBornAt(){ + return loaded("born_at", "getBornAt", Entry::getBornAt); + } + public EntryExpression updateBornAt(LocalDateTime bornAt){ + return new EntryExpression(this, $it -> ((Entry)$it).updateBornAt(bornAt)); + } + + public Expression getTouchedAt(){ + return loaded("touched_at", "getTouchedAt", Entry::getTouchedAt); + } + public EntryExpression updateTouchedAt(LocalDateTime touchedAt){ + return new EntryExpression(this, $it -> ((Entry)$it).updateTouchedAt(touchedAt)); + } + + public Expression getSourceIp(){ + return loaded("source_ip", "getSourceIp", Entry::getSourceIp); + } + public EntryExpression updateSourceIp(String sourceIp){ + return new EntryExpression(this, $it -> ((Entry)$it).updateSourceIp(sourceIp)); + } + + public Expression getLastIp(){ + return loaded("last_ip", "getLastIp", Entry::getLastIp); + } + public EntryExpression updateLastIp(String lastIp){ + return new EntryExpression(this, $it -> ((Entry)$it).updateLastIp(lastIp)); + } + + public Expression getOpenedBy(){ + return loaded("opened_by", "getOpenedBy", Entry::getOpenedBy); + } + public EntryExpression updateOpenedBy(String openedBy){ + return new EntryExpression(this, $it -> ((Entry)$it).updateOpenedBy(openedBy)); + } + + public Expression getChangedBy(){ + return loaded("changed_by", "getChangedBy", Entry::getChangedBy); + } + public EntryExpression updateChangedBy(String changedBy){ + return new EntryExpression(this, $it -> ((Entry)$it).updateChangedBy(changedBy)); + } + + public Expression getGuardedToken(){ + return loaded("guarded_token", "getGuardedToken", Entry::getGuardedToken); + } + public EntryExpression updateGuardedToken(String guardedToken){ + return new EntryExpression(this, $it -> ((Entry)$it).updateGuardedToken(guardedToken)); + } + +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryListExpression.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryListExpression.java new file mode 100644 index 000000000..3c0ef9888 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryListExpression.java @@ -0,0 +1,25 @@ + +package com.example.contextfixservice.entry; + +import io.teaql.core.SmartList; +import io.teaql.core.value.Expression; +import io.teaql.core.value.SmartListExpression; +import java.util.function.Function; + +public class EntryListExpression extends SmartListExpression { + public EntryListExpression(Expression> expression){ + super(expression); + } + + public EntryListExpression(Expression expression, Function> function){ + super(expression, function); + } + + public EntryExpression first() { + return new EntryExpression(super.first()); + } + + public EntryExpression get(int index) { + return new EntryExpression(super.get(index)); + } +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryRequest.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryRequest.java new file mode 100644 index 000000000..6c494b208 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/entry/EntryRequest.java @@ -0,0 +1,1583 @@ + +package com.example.contextfixservice.entry; + +import com.example.contextfixservice.Q; +import com.example.contextfixservice.catalog.Catalog; +import com.example.contextfixservice.catalog.CatalogRequest; +import io.teaql.core.AggrFunction; +import io.teaql.core.BaseRequest; +import io.teaql.core.PropertyReference; +import io.teaql.core.SearchCriteria; +import io.teaql.core.SubQuerySearchCriteria; +import io.teaql.core.criteria.Operator; +import io.teaql.core.criteria.TwoOperatorCriteria; +import java.time.LocalDateTime; +import java.util.Date; + +public class EntryRequest extends BaseRequest { + + /** + * @deprecated AI agents and business code must use the generated Q facade + * instead of constructing request builders directly. + */ + @Deprecated + @SuppressWarnings("unchecked") + public EntryRequest(Class returnType){ + this(returnType, () -> (T) new Entry()); + } + + protected EntryRequest(Class returnType, java.util.function.Supplier factory){ + super(returnType, factory); + selectId(); + selectVersion(); + } + + public EntryRequest comment(String comment){ + super.internalComment(comment); + return this; + } + + // purpose() 继承自 BaseRequest,返回 ExecutableRequest(终结方法) + + public EntryRequest returnType(Class returnType){ + super.setReturnType(returnType); + return this; + } + + public EntryRequest enableAggregationCache(long cacheExpiredMillis){ + super.enableAggregationCache(); + super.aggregateCacheTime(cacheExpiredMillis); + return this; + } + + public EntryRequest enableAggregationCache(){ + return enableAggregationCache(0l); + } + + + public EntryRequest propagateAggregationCache(long cacheExpiredMillis){ + super.propagateAggregationCache(cacheExpiredMillis); + return this; + } + + /** + * Accept best-effort stateful seek optimization for browsing consecutive pages. + * Do not use this for business processing that must visit every row exactly once. + */ + public EntryRequest optimizeForContinuousPageFetch(){ + super.optimizeForContinuousPageFetch(); + return this; + } + + public EntryRequest optimizeForContinuousPageFetch(String namespace, int ttlSeconds){ + super.optimizeForContinuousPageFetch(namespace, ttlSeconds); + return this; + } + + public EntryRequest optimizePaginationWithIdSet(){ + super.optimizePaginationWithIdSet(); + return this; + } + + public EntryRequest optimizePaginationWithIdSet( + String namespace, int ttlSeconds, int maxIds){ + super.optimizePaginationWithIdSet(namespace, ttlSeconds, maxIds); + return this; + } + + public EntryRequest topNProbeParentThreshold(int threshold){ + super.topNProbeParentThreshold(threshold); + return this; + } + + public EntryRequest appendSearchCriteria(SearchCriteria searchCriteria){ + return (EntryRequest)super.appendSearchCriteria(searchCriteria); + } + + public EntryRequest filter(String property1, Operator operator, String property2){ + return appendSearchCriteria(new TwoOperatorCriteria(operator, new PropertyReference(property1), new PropertyReference(property2))); + } + + + public EntryRequest matchingAnyOf(EntryRequest entry){ + super.internalMatchAny(entry); + return this; + } + + public EntryRequest enhanceChildrenIfNeeded(){ + return this; + } + + public EntryRequest withDeletedRows(){ + super.withDeletedRows(); + return this; + } + + public EntryRequest deletedRowsOnly(){ + super.deletedRowsOnly(); + return this; + } + + public EntryRequest selectSelf(){ + super.selectSelf(); + return selectId().selectCatalogIdOnly().selectName().selectBornAt().selectTouchedAt().selectSourceIp().selectLastIp().selectOpenedBy().selectChangedBy().selectGuardedToken().selectVersion(); + } + + public EntryRequest selectSelfFields(){ + return selectSelf(); + } + + public EntryRequest selectSelfWithoutParent(){ + selectId(); + selectVersion(); + selectProperty(Entry.ID_PROPERTY); + selectProperty(Entry.CATALOG_PROPERTY); + selectProperty(Entry.NAME_PROPERTY); + selectProperty(Entry.BORN_AT_PROPERTY); + selectProperty(Entry.TOUCHED_AT_PROPERTY); + selectProperty(Entry.SOURCE_IP_PROPERTY); + selectProperty(Entry.LAST_IP_PROPERTY); + selectProperty(Entry.OPENED_BY_PROPERTY); + selectProperty(Entry.CHANGED_BY_PROPERTY); + selectProperty(Entry.GUARDED_TOKEN_PROPERTY); + selectProperty(Entry.VERSION_PROPERTY); + return this; + } + + public EntryRequest selectAll(){ + super.selectAll(); + return selectId().selectCatalog().selectName().selectBornAt().selectTouchedAt().selectSourceIp().selectLastIp().selectOpenedBy().selectChangedBy().selectGuardedToken().selectVersion(); + } + + public EntryRequest selectChildren(){ + super.selectAny(); + return selectId().selectCatalog().selectName().selectBornAt().selectTouchedAt().selectSourceIp().selectLastIp().selectOpenedBy().selectChangedBy().selectGuardedToken().selectVersion(); + } + + + public EntryRequest selectId(){ + selectProperty(Entry.ID_PROPERTY); + return this; + } + + /** + * fill the id with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS id) to fetch id property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectId(){ + unselectProperty(Entry.ID_PROPERTY); + return this; + } + public EntryRequest selectCatalogIdOnly(){ + selectProperty(Entry.CATALOG_PROPERTY); + return this; + } + + public EntryRequest selectCatalog(){ + return selectCatalogWith(Q.catalogs().unlimited().selectSelf()); + } + + public EntryRequest selectCatalogWith(CatalogRequest catalog){ + selectProperty(Entry.CATALOG_PROPERTY); + enhanceRelation(Entry.CATALOG_PROPERTY, catalog, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_SELECT, "selectCatalogWith", null, Entry.CATALOG_PROPERTY)); + return this; + } + + public EntryRequest unselectCatalog(){ + unselectProperty(Entry.CATALOG_PROPERTY); + return this; + } + public EntryRequest selectName(){ + selectProperty(Entry.NAME_PROPERTY); + return this; + } + + /** + * fill the name with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS name) to fetch name property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectName(){ + unselectProperty(Entry.NAME_PROPERTY); + return this; + } + public EntryRequest selectBornAt(){ + selectProperty(Entry.BORN_AT_PROPERTY); + return this; + } + + /** + * fill the bornAt with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS bornAt) to fetch bornAt property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectBornAt(){ + unselectProperty(Entry.BORN_AT_PROPERTY); + return this; + } + public EntryRequest selectTouchedAt(){ + selectProperty(Entry.TOUCHED_AT_PROPERTY); + return this; + } + + /** + * fill the touchedAt with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS touchedAt) to fetch touchedAt property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectTouchedAt(){ + unselectProperty(Entry.TOUCHED_AT_PROPERTY); + return this; + } + public EntryRequest selectSourceIp(){ + selectProperty(Entry.SOURCE_IP_PROPERTY); + return this; + } + + /** + * fill the sourceIp with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS sourceIp) to fetch sourceIp property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectSourceIp(){ + unselectProperty(Entry.SOURCE_IP_PROPERTY); + return this; + } + public EntryRequest selectLastIp(){ + selectProperty(Entry.LAST_IP_PROPERTY); + return this; + } + + /** + * fill the lastIp with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS lastIp) to fetch lastIp property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectLastIp(){ + unselectProperty(Entry.LAST_IP_PROPERTY); + return this; + } + public EntryRequest selectOpenedBy(){ + selectProperty(Entry.OPENED_BY_PROPERTY); + return this; + } + + /** + * fill the openedBy with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS openedBy) to fetch openedBy property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectOpenedBy(){ + unselectProperty(Entry.OPENED_BY_PROPERTY); + return this; + } + public EntryRequest selectChangedBy(){ + selectProperty(Entry.CHANGED_BY_PROPERTY); + return this; + } + + /** + * fill the changedBy with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS changedBy) to fetch changedBy property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectChangedBy(){ + unselectProperty(Entry.CHANGED_BY_PROPERTY); + return this; + } + public EntryRequest selectGuardedToken(){ + selectProperty(Entry.GUARDED_TOKEN_PROPERTY); + return this; + } + + /** + * fill the guardedToken with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS guardedToken) to fetch guardedToken property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectGuardedToken(){ + unselectProperty(Entry.GUARDED_TOKEN_PROPERTY); + return this; + } + public EntryRequest selectVersion(){ + selectProperty(Entry.VERSION_PROPERTY); + return this; + } + + /** + * fill the version with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS version) to fetch version property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectVersion(){ + unselectProperty(Entry.VERSION_PROPERTY); + return this; + } + + public EntryRequest withId(Operator operator, Object... values){ + return appendSearchCriteria(createIdCriteria(operator, values)); + } + + public SearchCriteria createIdCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.ID_PROPERTY, operator, values); + } + + public EntryRequest withIdIsNot(Long id){ + return withId(Operator.NOT_EQUAL, id); + } + + public EntryRequest withIdIn(Long... id){ + return withId(Operator.IN, (Object[])id); + } + + public EntryRequest withIdNotIn(Long... id){ + return withId(Operator.NOT_IN, (Object[])id); + } + public EntryRequest withIdIs(Long id){ + return withId(Operator.EQUAL, id); + } + + + + public EntryRequest filterByCatalog(Catalog... catalog){ + if (catalog == null || catalog.length == 0) { + throw new IllegalArgumentException("filterByCatalog parameter catalog cannot be empty"); + } + return appendSearchCriteria(createCatalogCriteria(Operator.EQUAL, (Object[])catalog)); + } + + public EntryRequest withCatalog(Operator operator, Object... values){ + return appendSearchCriteria(createCatalogCriteria(operator, values)); + } + + public EntryRequest withCatalogIsUnknown(){ + return withCatalog(Operator.IS_NULL); + } + + public EntryRequest withCatalogIsKnown(){ + return withCatalog(Operator.IS_NOT_NULL); + } + + public SearchCriteria createCatalogCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.CATALOG_PROPERTY, operator, values); + } + + public EntryRequest filterByCatalog(Long catalog){ + if(catalog == null){ + return this; + } + return withCatalog(Operator.EQUAL, catalog); + } + public EntryRequest withCatalogMatching(CatalogRequest catalog){ + return appendSearchCriteria(new SubQuerySearchCriteria(Entry.CATALOG_PROPERTY, catalog, Catalog.ID_PROPERTY)); + } + + public EntryRequest withoutCatalogMatching(CatalogRequest catalog){ + return appendSearchCriteria(SearchCriteria.not( + new SubQuerySearchCriteria(Entry.CATALOG_PROPERTY, catalog, Catalog.ID_PROPERTY))); + } + + public EntryRequest filterByName(String... name){ + if (name == null || name.length == 0) { + throw new IllegalArgumentException("filterByName parameter name cannot be empty"); + } + return appendSearchCriteria(createNameCriteria(Operator.EQUAL, (Object[])name)); + } + + public EntryRequest withName(Operator operator, Object... values){ + return appendSearchCriteria(createNameCriteria(operator, values)); + } + + public EntryRequest withNameIsUnknown(){ + return withName(Operator.IS_NULL); + } + + public EntryRequest withNameIsKnown(){ + return withName(Operator.IS_NOT_NULL); + } + + public SearchCriteria createNameCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.NAME_PROPERTY, operator, values); + } + + public EntryRequest withNameIsNot(String name){ + return withName(Operator.NOT_EQUAL, name); + } + + public EntryRequest withNameIn(String... name){ + return withName(Operator.IN, (Object[])name); + } + + public EntryRequest withNameNotIn(String... name){ + return withName(Operator.NOT_IN, (Object[])name); + } + public EntryRequest withNameGreaterThan(String name){ + return withName(Operator.GREATER_THAN, name); + } + + public EntryRequest withNameGreaterThanOrEqualTo(String name){ + return withName(Operator.GREATER_THAN_OR_EQUAL, name); + } + + public EntryRequest withNameLessThan(String name){ + return withName(Operator.LESS_THAN, name); + } + + public EntryRequest withNameLessThanOrEqualTo(String name){ + return withName(Operator.LESS_THAN_OR_EQUAL, name); + } + + public EntryRequest withNameBetween(String startOfName, String endOfName){ + return withName(Operator.BETWEEN, startOfName, endOfName); + } + public EntryRequest withNameStartingWith(String name){ + return withName(Operator.BEGIN_WITH, name); + } + public EntryRequest withNameContaining(String name){ + return withName(Operator.CONTAIN, name); + } + + public EntryRequest withNameNotContaining(String name){ + return withName(Operator.NOT_CONTAIN, name); + } + + public EntryRequest withNameNotStartingWith(String name){ + return withName(Operator.NOT_BEGIN_WITH, name); + } + + public EntryRequest withNameEndingWith(String name){ + return withName(Operator.END_WITH, name); + } + + public EntryRequest withNameNotEndingWith(String name){ + return withName(Operator.NOT_END_WITH, name); + } + + public EntryRequest withNameIs(String name){ + return withName(Operator.EQUAL, name); + } + + public EntryRequest withNameSoundingLike(String name){ + return withName(Operator.SOUNDS_LIKE, name); + } + + + + public EntryRequest filterByBornAt(LocalDateTime... bornAt){ + if (bornAt == null || bornAt.length == 0) { + throw new IllegalArgumentException("filterByBornAt parameter bornAt cannot be empty"); + } + return appendSearchCriteria(createBornAtCriteria(Operator.EQUAL, (Object[])bornAt)); + } + + public EntryRequest withBornAt(Operator operator, Object... values){ + return appendSearchCriteria(createBornAtCriteria(operator, values)); + } + + public EntryRequest withBornAtIsUnknown(){ + return withBornAt(Operator.IS_NULL); + } + + public EntryRequest withBornAtIsKnown(){ + return withBornAt(Operator.IS_NOT_NULL); + } + + public SearchCriteria createBornAtCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.BORN_AT_PROPERTY, operator, values); + } + + public EntryRequest withBornAtIs(LocalDateTime bornAt){ + return withBornAt(Operator.EQUAL, bornAt); + } + + public EntryRequest withBornAtIsNot(LocalDateTime bornAt){ + return withBornAt(Operator.NOT_EQUAL, bornAt); + } + + public EntryRequest withBornAtIn(LocalDateTime... bornAt){ + return withBornAt(Operator.IN, (Object[])bornAt); + } + + public EntryRequest withBornAtNotIn(LocalDateTime... bornAt){ + return withBornAt(Operator.NOT_IN, (Object[])bornAt); + } + public EntryRequest withBornAtGreaterThan(LocalDateTime bornAt){ + return withBornAt(Operator.GREATER_THAN, bornAt); + } + + public EntryRequest withBornAtGreaterThanOrEqualTo(LocalDateTime bornAt){ + return withBornAt(Operator.GREATER_THAN_OR_EQUAL, bornAt); + } + + public EntryRequest withBornAtLessThan(LocalDateTime bornAt){ + return withBornAt(Operator.LESS_THAN, bornAt); + } + + public EntryRequest withBornAtLessThanOrEqualTo(LocalDateTime bornAt){ + return withBornAt(Operator.LESS_THAN_OR_EQUAL, bornAt); + } + + public EntryRequest withBornAtBetween(LocalDateTime startOfBornAt, LocalDateTime endOfBornAt){ + return withBornAt(Operator.BETWEEN, startOfBornAt, endOfBornAt); + } + public EntryRequest withBornAtBefore(LocalDateTime bornAt){ + return withBornAt(Operator.LESS_THAN, bornAt); + } + + public EntryRequest withBornAtBefore(Date bornAt){ + return withBornAt(Operator.LESS_THAN, bornAt); + } + + public EntryRequest withBornAtAfter(LocalDateTime bornAt){ + return withBornAt(Operator.GREATER_THAN, bornAt); + } + + public EntryRequest withBornAtAfter(Date bornAt){ + return withBornAt(Operator.GREATER_THAN, bornAt); + } + + public EntryRequest withBornAtBetween(Date startOfBornAt, Date endOfBornAt){ + return withBornAt(Operator.BETWEEN, startOfBornAt, endOfBornAt); + } + + + + + public EntryRequest filterByTouchedAt(LocalDateTime... touchedAt){ + if (touchedAt == null || touchedAt.length == 0) { + throw new IllegalArgumentException("filterByTouchedAt parameter touchedAt cannot be empty"); + } + return appendSearchCriteria(createTouchedAtCriteria(Operator.EQUAL, (Object[])touchedAt)); + } + + public EntryRequest withTouchedAt(Operator operator, Object... values){ + return appendSearchCriteria(createTouchedAtCriteria(operator, values)); + } + + public EntryRequest withTouchedAtIsUnknown(){ + return withTouchedAt(Operator.IS_NULL); + } + + public EntryRequest withTouchedAtIsKnown(){ + return withTouchedAt(Operator.IS_NOT_NULL); + } + + public SearchCriteria createTouchedAtCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.TOUCHED_AT_PROPERTY, operator, values); + } + + public EntryRequest withTouchedAtIs(LocalDateTime touchedAt){ + return withTouchedAt(Operator.EQUAL, touchedAt); + } + + public EntryRequest withTouchedAtIsNot(LocalDateTime touchedAt){ + return withTouchedAt(Operator.NOT_EQUAL, touchedAt); + } + + public EntryRequest withTouchedAtIn(LocalDateTime... touchedAt){ + return withTouchedAt(Operator.IN, (Object[])touchedAt); + } + + public EntryRequest withTouchedAtNotIn(LocalDateTime... touchedAt){ + return withTouchedAt(Operator.NOT_IN, (Object[])touchedAt); + } + public EntryRequest withTouchedAtGreaterThan(LocalDateTime touchedAt){ + return withTouchedAt(Operator.GREATER_THAN, touchedAt); + } + + public EntryRequest withTouchedAtGreaterThanOrEqualTo(LocalDateTime touchedAt){ + return withTouchedAt(Operator.GREATER_THAN_OR_EQUAL, touchedAt); + } + + public EntryRequest withTouchedAtLessThan(LocalDateTime touchedAt){ + return withTouchedAt(Operator.LESS_THAN, touchedAt); + } + + public EntryRequest withTouchedAtLessThanOrEqualTo(LocalDateTime touchedAt){ + return withTouchedAt(Operator.LESS_THAN_OR_EQUAL, touchedAt); + } + + public EntryRequest withTouchedAtBetween(LocalDateTime startOfTouchedAt, LocalDateTime endOfTouchedAt){ + return withTouchedAt(Operator.BETWEEN, startOfTouchedAt, endOfTouchedAt); + } + public EntryRequest withTouchedAtBefore(LocalDateTime touchedAt){ + return withTouchedAt(Operator.LESS_THAN, touchedAt); + } + + public EntryRequest withTouchedAtBefore(Date touchedAt){ + return withTouchedAt(Operator.LESS_THAN, touchedAt); + } + + public EntryRequest withTouchedAtAfter(LocalDateTime touchedAt){ + return withTouchedAt(Operator.GREATER_THAN, touchedAt); + } + + public EntryRequest withTouchedAtAfter(Date touchedAt){ + return withTouchedAt(Operator.GREATER_THAN, touchedAt); + } + + public EntryRequest withTouchedAtBetween(Date startOfTouchedAt, Date endOfTouchedAt){ + return withTouchedAt(Operator.BETWEEN, startOfTouchedAt, endOfTouchedAt); + } + + + + + public EntryRequest filterBySourceIp(String... sourceIp){ + if (sourceIp == null || sourceIp.length == 0) { + throw new IllegalArgumentException("filterBySourceIp parameter sourceIp cannot be empty"); + } + return appendSearchCriteria(createSourceIpCriteria(Operator.EQUAL, (Object[])sourceIp)); + } + + public EntryRequest withSourceIp(Operator operator, Object... values){ + return appendSearchCriteria(createSourceIpCriteria(operator, values)); + } + + public EntryRequest withSourceIpIsUnknown(){ + return withSourceIp(Operator.IS_NULL); + } + + public EntryRequest withSourceIpIsKnown(){ + return withSourceIp(Operator.IS_NOT_NULL); + } + + public SearchCriteria createSourceIpCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.SOURCE_IP_PROPERTY, operator, values); + } + + public EntryRequest withSourceIpIsNot(String sourceIp){ + return withSourceIp(Operator.NOT_EQUAL, sourceIp); + } + + public EntryRequest withSourceIpIn(String... sourceIp){ + return withSourceIp(Operator.IN, (Object[])sourceIp); + } + + public EntryRequest withSourceIpNotIn(String... sourceIp){ + return withSourceIp(Operator.NOT_IN, (Object[])sourceIp); + } + public EntryRequest withSourceIpGreaterThan(String sourceIp){ + return withSourceIp(Operator.GREATER_THAN, sourceIp); + } + + public EntryRequest withSourceIpGreaterThanOrEqualTo(String sourceIp){ + return withSourceIp(Operator.GREATER_THAN_OR_EQUAL, sourceIp); + } + + public EntryRequest withSourceIpLessThan(String sourceIp){ + return withSourceIp(Operator.LESS_THAN, sourceIp); + } + + public EntryRequest withSourceIpLessThanOrEqualTo(String sourceIp){ + return withSourceIp(Operator.LESS_THAN_OR_EQUAL, sourceIp); + } + + public EntryRequest withSourceIpBetween(String startOfSourceIp, String endOfSourceIp){ + return withSourceIp(Operator.BETWEEN, startOfSourceIp, endOfSourceIp); + } + public EntryRequest withSourceIpStartingWith(String sourceIp){ + return withSourceIp(Operator.BEGIN_WITH, sourceIp); + } + public EntryRequest withSourceIpContaining(String sourceIp){ + return withSourceIp(Operator.CONTAIN, sourceIp); + } + + public EntryRequest withSourceIpNotContaining(String sourceIp){ + return withSourceIp(Operator.NOT_CONTAIN, sourceIp); + } + + public EntryRequest withSourceIpNotStartingWith(String sourceIp){ + return withSourceIp(Operator.NOT_BEGIN_WITH, sourceIp); + } + + public EntryRequest withSourceIpEndingWith(String sourceIp){ + return withSourceIp(Operator.END_WITH, sourceIp); + } + + public EntryRequest withSourceIpNotEndingWith(String sourceIp){ + return withSourceIp(Operator.NOT_END_WITH, sourceIp); + } + + public EntryRequest withSourceIpIs(String sourceIp){ + return withSourceIp(Operator.EQUAL, sourceIp); + } + + public EntryRequest withSourceIpSoundingLike(String sourceIp){ + return withSourceIp(Operator.SOUNDS_LIKE, sourceIp); + } + + + + public EntryRequest filterByLastIp(String... lastIp){ + if (lastIp == null || lastIp.length == 0) { + throw new IllegalArgumentException("filterByLastIp parameter lastIp cannot be empty"); + } + return appendSearchCriteria(createLastIpCriteria(Operator.EQUAL, (Object[])lastIp)); + } + + public EntryRequest withLastIp(Operator operator, Object... values){ + return appendSearchCriteria(createLastIpCriteria(operator, values)); + } + + public EntryRequest withLastIpIsUnknown(){ + return withLastIp(Operator.IS_NULL); + } + + public EntryRequest withLastIpIsKnown(){ + return withLastIp(Operator.IS_NOT_NULL); + } + + public SearchCriteria createLastIpCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.LAST_IP_PROPERTY, operator, values); + } + + public EntryRequest withLastIpIsNot(String lastIp){ + return withLastIp(Operator.NOT_EQUAL, lastIp); + } + + public EntryRequest withLastIpIn(String... lastIp){ + return withLastIp(Operator.IN, (Object[])lastIp); + } + + public EntryRequest withLastIpNotIn(String... lastIp){ + return withLastIp(Operator.NOT_IN, (Object[])lastIp); + } + public EntryRequest withLastIpGreaterThan(String lastIp){ + return withLastIp(Operator.GREATER_THAN, lastIp); + } + + public EntryRequest withLastIpGreaterThanOrEqualTo(String lastIp){ + return withLastIp(Operator.GREATER_THAN_OR_EQUAL, lastIp); + } + + public EntryRequest withLastIpLessThan(String lastIp){ + return withLastIp(Operator.LESS_THAN, lastIp); + } + + public EntryRequest withLastIpLessThanOrEqualTo(String lastIp){ + return withLastIp(Operator.LESS_THAN_OR_EQUAL, lastIp); + } + + public EntryRequest withLastIpBetween(String startOfLastIp, String endOfLastIp){ + return withLastIp(Operator.BETWEEN, startOfLastIp, endOfLastIp); + } + public EntryRequest withLastIpStartingWith(String lastIp){ + return withLastIp(Operator.BEGIN_WITH, lastIp); + } + public EntryRequest withLastIpContaining(String lastIp){ + return withLastIp(Operator.CONTAIN, lastIp); + } + + public EntryRequest withLastIpNotContaining(String lastIp){ + return withLastIp(Operator.NOT_CONTAIN, lastIp); + } + + public EntryRequest withLastIpNotStartingWith(String lastIp){ + return withLastIp(Operator.NOT_BEGIN_WITH, lastIp); + } + + public EntryRequest withLastIpEndingWith(String lastIp){ + return withLastIp(Operator.END_WITH, lastIp); + } + + public EntryRequest withLastIpNotEndingWith(String lastIp){ + return withLastIp(Operator.NOT_END_WITH, lastIp); + } + + public EntryRequest withLastIpIs(String lastIp){ + return withLastIp(Operator.EQUAL, lastIp); + } + + public EntryRequest withLastIpSoundingLike(String lastIp){ + return withLastIp(Operator.SOUNDS_LIKE, lastIp); + } + + + + public EntryRequest filterByOpenedBy(String... openedBy){ + if (openedBy == null || openedBy.length == 0) { + throw new IllegalArgumentException("filterByOpenedBy parameter openedBy cannot be empty"); + } + return appendSearchCriteria(createOpenedByCriteria(Operator.EQUAL, (Object[])openedBy)); + } + + public EntryRequest withOpenedBy(Operator operator, Object... values){ + return appendSearchCriteria(createOpenedByCriteria(operator, values)); + } + + public EntryRequest withOpenedByIsUnknown(){ + return withOpenedBy(Operator.IS_NULL); + } + + public EntryRequest withOpenedByIsKnown(){ + return withOpenedBy(Operator.IS_NOT_NULL); + } + + public SearchCriteria createOpenedByCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.OPENED_BY_PROPERTY, operator, values); + } + + public EntryRequest withOpenedByIsNot(String openedBy){ + return withOpenedBy(Operator.NOT_EQUAL, openedBy); + } + + public EntryRequest withOpenedByIn(String... openedBy){ + return withOpenedBy(Operator.IN, (Object[])openedBy); + } + + public EntryRequest withOpenedByNotIn(String... openedBy){ + return withOpenedBy(Operator.NOT_IN, (Object[])openedBy); + } + public EntryRequest withOpenedByGreaterThan(String openedBy){ + return withOpenedBy(Operator.GREATER_THAN, openedBy); + } + + public EntryRequest withOpenedByGreaterThanOrEqualTo(String openedBy){ + return withOpenedBy(Operator.GREATER_THAN_OR_EQUAL, openedBy); + } + + public EntryRequest withOpenedByLessThan(String openedBy){ + return withOpenedBy(Operator.LESS_THAN, openedBy); + } + + public EntryRequest withOpenedByLessThanOrEqualTo(String openedBy){ + return withOpenedBy(Operator.LESS_THAN_OR_EQUAL, openedBy); + } + + public EntryRequest withOpenedByBetween(String startOfOpenedBy, String endOfOpenedBy){ + return withOpenedBy(Operator.BETWEEN, startOfOpenedBy, endOfOpenedBy); + } + public EntryRequest withOpenedByStartingWith(String openedBy){ + return withOpenedBy(Operator.BEGIN_WITH, openedBy); + } + public EntryRequest withOpenedByContaining(String openedBy){ + return withOpenedBy(Operator.CONTAIN, openedBy); + } + + public EntryRequest withOpenedByNotContaining(String openedBy){ + return withOpenedBy(Operator.NOT_CONTAIN, openedBy); + } + + public EntryRequest withOpenedByNotStartingWith(String openedBy){ + return withOpenedBy(Operator.NOT_BEGIN_WITH, openedBy); + } + + public EntryRequest withOpenedByEndingWith(String openedBy){ + return withOpenedBy(Operator.END_WITH, openedBy); + } + + public EntryRequest withOpenedByNotEndingWith(String openedBy){ + return withOpenedBy(Operator.NOT_END_WITH, openedBy); + } + + public EntryRequest withOpenedByIs(String openedBy){ + return withOpenedBy(Operator.EQUAL, openedBy); + } + + public EntryRequest withOpenedBySoundingLike(String openedBy){ + return withOpenedBy(Operator.SOUNDS_LIKE, openedBy); + } + + + + public EntryRequest filterByChangedBy(String... changedBy){ + if (changedBy == null || changedBy.length == 0) { + throw new IllegalArgumentException("filterByChangedBy parameter changedBy cannot be empty"); + } + return appendSearchCriteria(createChangedByCriteria(Operator.EQUAL, (Object[])changedBy)); + } + + public EntryRequest withChangedBy(Operator operator, Object... values){ + return appendSearchCriteria(createChangedByCriteria(operator, values)); + } + + public EntryRequest withChangedByIsUnknown(){ + return withChangedBy(Operator.IS_NULL); + } + + public EntryRequest withChangedByIsKnown(){ + return withChangedBy(Operator.IS_NOT_NULL); + } + + public SearchCriteria createChangedByCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.CHANGED_BY_PROPERTY, operator, values); + } + + public EntryRequest withChangedByIsNot(String changedBy){ + return withChangedBy(Operator.NOT_EQUAL, changedBy); + } + + public EntryRequest withChangedByIn(String... changedBy){ + return withChangedBy(Operator.IN, (Object[])changedBy); + } + + public EntryRequest withChangedByNotIn(String... changedBy){ + return withChangedBy(Operator.NOT_IN, (Object[])changedBy); + } + public EntryRequest withChangedByGreaterThan(String changedBy){ + return withChangedBy(Operator.GREATER_THAN, changedBy); + } + + public EntryRequest withChangedByGreaterThanOrEqualTo(String changedBy){ + return withChangedBy(Operator.GREATER_THAN_OR_EQUAL, changedBy); + } + + public EntryRequest withChangedByLessThan(String changedBy){ + return withChangedBy(Operator.LESS_THAN, changedBy); + } + + public EntryRequest withChangedByLessThanOrEqualTo(String changedBy){ + return withChangedBy(Operator.LESS_THAN_OR_EQUAL, changedBy); + } + + public EntryRequest withChangedByBetween(String startOfChangedBy, String endOfChangedBy){ + return withChangedBy(Operator.BETWEEN, startOfChangedBy, endOfChangedBy); + } + public EntryRequest withChangedByStartingWith(String changedBy){ + return withChangedBy(Operator.BEGIN_WITH, changedBy); + } + public EntryRequest withChangedByContaining(String changedBy){ + return withChangedBy(Operator.CONTAIN, changedBy); + } + + public EntryRequest withChangedByNotContaining(String changedBy){ + return withChangedBy(Operator.NOT_CONTAIN, changedBy); + } + + public EntryRequest withChangedByNotStartingWith(String changedBy){ + return withChangedBy(Operator.NOT_BEGIN_WITH, changedBy); + } + + public EntryRequest withChangedByEndingWith(String changedBy){ + return withChangedBy(Operator.END_WITH, changedBy); + } + + public EntryRequest withChangedByNotEndingWith(String changedBy){ + return withChangedBy(Operator.NOT_END_WITH, changedBy); + } + + public EntryRequest withChangedByIs(String changedBy){ + return withChangedBy(Operator.EQUAL, changedBy); + } + + public EntryRequest withChangedBySoundingLike(String changedBy){ + return withChangedBy(Operator.SOUNDS_LIKE, changedBy); + } + + + + public EntryRequest filterByGuardedToken(String... guardedToken){ + if (guardedToken == null || guardedToken.length == 0) { + throw new IllegalArgumentException("filterByGuardedToken parameter guardedToken cannot be empty"); + } + return appendSearchCriteria(createGuardedTokenCriteria(Operator.EQUAL, (Object[])guardedToken)); + } + + public EntryRequest withGuardedToken(Operator operator, Object... values){ + return appendSearchCriteria(createGuardedTokenCriteria(operator, values)); + } + + public EntryRequest withGuardedTokenIsUnknown(){ + return withGuardedToken(Operator.IS_NULL); + } + + public EntryRequest withGuardedTokenIsKnown(){ + return withGuardedToken(Operator.IS_NOT_NULL); + } + + public SearchCriteria createGuardedTokenCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.GUARDED_TOKEN_PROPERTY, operator, values); + } + + public EntryRequest withGuardedTokenIsNot(String guardedToken){ + return withGuardedToken(Operator.NOT_EQUAL, guardedToken); + } + + public EntryRequest withGuardedTokenIn(String... guardedToken){ + return withGuardedToken(Operator.IN, (Object[])guardedToken); + } + + public EntryRequest withGuardedTokenNotIn(String... guardedToken){ + return withGuardedToken(Operator.NOT_IN, (Object[])guardedToken); + } + public EntryRequest withGuardedTokenGreaterThan(String guardedToken){ + return withGuardedToken(Operator.GREATER_THAN, guardedToken); + } + + public EntryRequest withGuardedTokenGreaterThanOrEqualTo(String guardedToken){ + return withGuardedToken(Operator.GREATER_THAN_OR_EQUAL, guardedToken); + } + + public EntryRequest withGuardedTokenLessThan(String guardedToken){ + return withGuardedToken(Operator.LESS_THAN, guardedToken); + } + + public EntryRequest withGuardedTokenLessThanOrEqualTo(String guardedToken){ + return withGuardedToken(Operator.LESS_THAN_OR_EQUAL, guardedToken); + } + + public EntryRequest withGuardedTokenBetween(String startOfGuardedToken, String endOfGuardedToken){ + return withGuardedToken(Operator.BETWEEN, startOfGuardedToken, endOfGuardedToken); + } + public EntryRequest withGuardedTokenStartingWith(String guardedToken){ + return withGuardedToken(Operator.BEGIN_WITH, guardedToken); + } + public EntryRequest withGuardedTokenContaining(String guardedToken){ + return withGuardedToken(Operator.CONTAIN, guardedToken); + } + + public EntryRequest withGuardedTokenNotContaining(String guardedToken){ + return withGuardedToken(Operator.NOT_CONTAIN, guardedToken); + } + + public EntryRequest withGuardedTokenNotStartingWith(String guardedToken){ + return withGuardedToken(Operator.NOT_BEGIN_WITH, guardedToken); + } + + public EntryRequest withGuardedTokenEndingWith(String guardedToken){ + return withGuardedToken(Operator.END_WITH, guardedToken); + } + + public EntryRequest withGuardedTokenNotEndingWith(String guardedToken){ + return withGuardedToken(Operator.NOT_END_WITH, guardedToken); + } + + public EntryRequest withGuardedTokenIs(String guardedToken){ + return withGuardedToken(Operator.EQUAL, guardedToken); + } + + public EntryRequest withGuardedTokenSoundingLike(String guardedToken){ + return withGuardedToken(Operator.SOUNDS_LIKE, guardedToken); + } + + + + public EntryRequest filterByVersion(Long... version){ + if (version == null || version.length == 0) { + throw new IllegalArgumentException("filterByVersion parameter version cannot be empty"); + } + return appendSearchCriteria(createVersionCriteria(Operator.EQUAL, (Object[])version)); + } + + public EntryRequest withVersion(Operator operator, Object... values){ + return appendSearchCriteria(createVersionCriteria(operator, values)); + } + + public EntryRequest withVersionIsUnknown(){ + return withVersion(Operator.IS_NULL); + } + + public EntryRequest withVersionIsKnown(){ + return withVersion(Operator.IS_NOT_NULL); + } + + public SearchCriteria createVersionCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.VERSION_PROPERTY, operator, values); + } + + public EntryRequest withVersionIs(Long version){ + return withVersion(Operator.EQUAL, version); + } + + public EntryRequest withVersionIsNot(Long version){ + return withVersion(Operator.NOT_EQUAL, version); + } + + public EntryRequest withVersionIn(Long... version){ + return withVersion(Operator.IN, (Object[])version); + } + + public EntryRequest withVersionNotIn(Long... version){ + return withVersion(Operator.NOT_IN, (Object[])version); + } + public EntryRequest withVersionGreaterThan(Long version){ + return withVersion(Operator.GREATER_THAN, version); + } + + public EntryRequest withVersionGreaterThanOrEqualTo(Long version){ + return withVersion(Operator.GREATER_THAN_OR_EQUAL, version); + } + + public EntryRequest withVersionLessThan(Long version){ + return withVersion(Operator.LESS_THAN, version); + } + + public EntryRequest withVersionLessThanOrEqualTo(Long version){ + return withVersion(Operator.LESS_THAN_OR_EQUAL, version); + } + + public EntryRequest withVersionBetween(Long startOfVersion, Long endOfVersion){ + return withVersion(Operator.BETWEEN, startOfVersion, endOfVersion); + } + + + + public EntryRequest count(){ + super.count(); + setPageCountOperation(io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.NAMED_COUNT, "count", null, null)); + return this; + } + public EntryRequest countAs(String retName){ + super.count(retName); + setPageCountOperation(io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.NAMED_COUNT, "countAs", retName, null)); + return this; + } + public EntryRequest groupByCatalogWithDetails(){ + return groupByCatalogWithDetails(Q.catalogs().unlimited()); + } + + public EntryRequest groupByCatalogWithDetails(CatalogRequest subRequest){ + aggregate(Entry.CATALOG_PROPERTY, subRequest); + return this; + } + + + + + + + + + + + + public EntryRequest groupById(){ + groupBy(Entry.ID_PROPERTY); + return this; + } + + public EntryRequest groupByIdAs(String retName){ + groupBy(retName, Entry.ID_PROPERTY); + return this; + } + + public EntryRequest groupByIdWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.ID_PROPERTY, function); + return this; + } + public EntryRequest groupByCatalogWith(CatalogRequest subRequest){ + groupBy(Entry.CATALOG_PROPERTY, subRequest); + return this; + } + public EntryRequest groupByCatalog(){ + groupBy(Entry.CATALOG_PROPERTY); + return this; + } + + public EntryRequest groupByCatalogAs(String retName){ + groupBy(retName, Entry.CATALOG_PROPERTY); + return this; + } + + public EntryRequest groupByCatalogWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.CATALOG_PROPERTY, function); + return this; + } + + public EntryRequest groupByName(){ + groupBy(Entry.NAME_PROPERTY); + return this; + } + + public EntryRequest groupByNameAs(String retName){ + groupBy(retName, Entry.NAME_PROPERTY); + return this; + } + + public EntryRequest groupByNameWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.NAME_PROPERTY, function); + return this; + } + + public EntryRequest groupByBornAt(){ + groupBy(Entry.BORN_AT_PROPERTY); + return this; + } + + public EntryRequest groupByBornAtAs(String retName){ + groupBy(retName, Entry.BORN_AT_PROPERTY); + return this; + } + + public EntryRequest groupByBornAtWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.BORN_AT_PROPERTY, function); + return this; + } + + public EntryRequest groupByTouchedAt(){ + groupBy(Entry.TOUCHED_AT_PROPERTY); + return this; + } + + public EntryRequest groupByTouchedAtAs(String retName){ + groupBy(retName, Entry.TOUCHED_AT_PROPERTY); + return this; + } + + public EntryRequest groupByTouchedAtWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.TOUCHED_AT_PROPERTY, function); + return this; + } + + public EntryRequest groupBySourceIp(){ + groupBy(Entry.SOURCE_IP_PROPERTY); + return this; + } + + public EntryRequest groupBySourceIpAs(String retName){ + groupBy(retName, Entry.SOURCE_IP_PROPERTY); + return this; + } + + public EntryRequest groupBySourceIpWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.SOURCE_IP_PROPERTY, function); + return this; + } + + public EntryRequest groupByLastIp(){ + groupBy(Entry.LAST_IP_PROPERTY); + return this; + } + + public EntryRequest groupByLastIpAs(String retName){ + groupBy(retName, Entry.LAST_IP_PROPERTY); + return this; + } + + public EntryRequest groupByLastIpWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.LAST_IP_PROPERTY, function); + return this; + } + + public EntryRequest groupByOpenedBy(){ + groupBy(Entry.OPENED_BY_PROPERTY); + return this; + } + + public EntryRequest groupByOpenedByAs(String retName){ + groupBy(retName, Entry.OPENED_BY_PROPERTY); + return this; + } + + public EntryRequest groupByOpenedByWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.OPENED_BY_PROPERTY, function); + return this; + } + + public EntryRequest groupByChangedBy(){ + groupBy(Entry.CHANGED_BY_PROPERTY); + return this; + } + + public EntryRequest groupByChangedByAs(String retName){ + groupBy(retName, Entry.CHANGED_BY_PROPERTY); + return this; + } + + public EntryRequest groupByChangedByWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.CHANGED_BY_PROPERTY, function); + return this; + } + + public EntryRequest groupByGuardedToken(){ + groupBy(Entry.GUARDED_TOKEN_PROPERTY); + return this; + } + + public EntryRequest groupByGuardedTokenAs(String retName){ + groupBy(retName, Entry.GUARDED_TOKEN_PROPERTY); + return this; + } + + public EntryRequest groupByGuardedTokenWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.GUARDED_TOKEN_PROPERTY, function); + return this; + } + + public EntryRequest groupByVersion(){ + groupBy(Entry.VERSION_PROPERTY); + return this; + } + + public EntryRequest groupByVersionAs(String retName){ + groupBy(retName, Entry.VERSION_PROPERTY); + return this; + } + + public EntryRequest groupByVersionWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.VERSION_PROPERTY, function); + return this; + } + + + + public EntryRequest orderByIdAscending(){ + addOrderByAscending(Entry.ID_PROPERTY); + return this; + } + + public EntryRequest orderByIdDescending(){ + addOrderByDescending(Entry.ID_PROPERTY); + return this; + } + + public EntryRequest orderByCatalogAscending(){ + addOrderByAscending(Entry.CATALOG_PROPERTY); + return this; + } + + public EntryRequest orderByCatalogDescending(){ + addOrderByDescending(Entry.CATALOG_PROPERTY); + return this; + } + + public EntryRequest orderByNameAscending(){ + addOrderByAscending(Entry.NAME_PROPERTY); + return this; + } + + public EntryRequest orderByNameDescending(){ + addOrderByDescending(Entry.NAME_PROPERTY); + return this; + } + public EntryRequest orderByNameAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Entry.NAME_PROPERTY); + return this; + } + + public EntryRequest orderByNameDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Entry.NAME_PROPERTY); + return this; + } + public EntryRequest orderByBornAtAscending(){ + addOrderByAscending(Entry.BORN_AT_PROPERTY); + return this; + } + + public EntryRequest orderByBornAtDescending(){ + addOrderByDescending(Entry.BORN_AT_PROPERTY); + return this; + } + + public EntryRequest orderByTouchedAtAscending(){ + addOrderByAscending(Entry.TOUCHED_AT_PROPERTY); + return this; + } + + public EntryRequest orderByTouchedAtDescending(){ + addOrderByDescending(Entry.TOUCHED_AT_PROPERTY); + return this; + } + + public EntryRequest orderBySourceIpAscending(){ + addOrderByAscending(Entry.SOURCE_IP_PROPERTY); + return this; + } + + public EntryRequest orderBySourceIpDescending(){ + addOrderByDescending(Entry.SOURCE_IP_PROPERTY); + return this; + } + public EntryRequest orderBySourceIpAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Entry.SOURCE_IP_PROPERTY); + return this; + } + + public EntryRequest orderBySourceIpDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Entry.SOURCE_IP_PROPERTY); + return this; + } + public EntryRequest orderByLastIpAscending(){ + addOrderByAscending(Entry.LAST_IP_PROPERTY); + return this; + } + + public EntryRequest orderByLastIpDescending(){ + addOrderByDescending(Entry.LAST_IP_PROPERTY); + return this; + } + public EntryRequest orderByLastIpAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Entry.LAST_IP_PROPERTY); + return this; + } + + public EntryRequest orderByLastIpDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Entry.LAST_IP_PROPERTY); + return this; + } + public EntryRequest orderByOpenedByAscending(){ + addOrderByAscending(Entry.OPENED_BY_PROPERTY); + return this; + } + + public EntryRequest orderByOpenedByDescending(){ + addOrderByDescending(Entry.OPENED_BY_PROPERTY); + return this; + } + public EntryRequest orderByOpenedByAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Entry.OPENED_BY_PROPERTY); + return this; + } + + public EntryRequest orderByOpenedByDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Entry.OPENED_BY_PROPERTY); + return this; + } + public EntryRequest orderByChangedByAscending(){ + addOrderByAscending(Entry.CHANGED_BY_PROPERTY); + return this; + } + + public EntryRequest orderByChangedByDescending(){ + addOrderByDescending(Entry.CHANGED_BY_PROPERTY); + return this; + } + public EntryRequest orderByChangedByAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Entry.CHANGED_BY_PROPERTY); + return this; + } + + public EntryRequest orderByChangedByDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Entry.CHANGED_BY_PROPERTY); + return this; + } + public EntryRequest orderByGuardedTokenAscending(){ + addOrderByAscending(Entry.GUARDED_TOKEN_PROPERTY); + return this; + } + + public EntryRequest orderByGuardedTokenDescending(){ + addOrderByDescending(Entry.GUARDED_TOKEN_PROPERTY); + return this; + } + public EntryRequest orderByGuardedTokenAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Entry.GUARDED_TOKEN_PROPERTY); + return this; + } + + public EntryRequest orderByGuardedTokenDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Entry.GUARDED_TOKEN_PROPERTY); + return this; + } + public EntryRequest orderByVersionAscending(){ + addOrderByAscending(Entry.VERSION_PROPERTY); + return this; + } + + public EntryRequest orderByVersionDescending(){ + addOrderByDescending(Entry.VERSION_PROPERTY); + return this; + } + + + public CatalogRequest rollUpToCatalog(){ + CatalogRequest catalog = Q.catalogs().unlimited(); + this.withCatalogMatching(catalog) + .groupByCatalogWith(catalog); + return catalog; + } + + + + + + + + + + + + public EntryRequest facetByCatalogAs(String facetName, CatalogRequest catalog){ + return facetByCatalogAs(facetName, catalog, true); + } + + public EntryRequest facetByCatalogAs(String facetName, CatalogRequest catalog, boolean includeAllFacets){ + addFacet(facetName, Entry.CATALOG_PROPERTY, catalog, includeAllFacets, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.FACET, "facetByCatalogAs", facetName, Entry.CATALOG_PROPERTY)); + return this; + } + + + /** + * get topN records + * @param topN records number + */ + public EntryRequest top(int topN) { + super.top(topN); + return this; + } + + /** Cross-runtime bounded-query alias. */ + public EntryRequest limit(int limit) { + return top(limit); + } + + /** + * get records from offset(inclusive) to offset+size(exclusive) + * @param offset record offset + * @param size records number + */ + public EntryRequest offset(int offset, int size) { + super.offset(offset, size); + return this; + } + + /** + * retrieve all records + */ + public EntryRequest unlimited() { + super.unlimited(); + return this; + } + + /** + * get records of one page + * @param pageNumber page number(1-based) + * @param pageSize page size + */ + public EntryRequest page(int pageNumber, int pageSize) { + int offset = (pageNumber - 1) * pageSize; + return offset(offset, pageSize); + } + + /** + * get records of one page, default page size is 10 + * @param pageNumber page number(1-based) + */ + public EntryRequest page(int pageNumber) { + return page(pageNumber, 10); + } +} \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/sampledata/SampleDataService.java b/examples/conformance/context-derived/fixture/lib/src/main/java/com/example/contextfixservice/sampledata/SampleDataService.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/context-derived/fixture/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler b/examples/conformance/context-derived/fixture/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler new file mode 100644 index 000000000..5da6f9001 --- /dev/null +++ b/examples/conformance/context-derived/fixture/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler @@ -0,0 +1,2 @@ + +com.example.contextfixservice.EntityMetaRegistry \ No newline at end of file diff --git a/examples/conformance/context-derived/fixture/model.xml b/examples/conformance/context-derived/fixture/model.xml new file mode 100644 index 000000000..72da35859 --- /dev/null +++ b/examples/conformance/context-derived/fixture/model.xml @@ -0,0 +1,5 @@ + + + + diff --git a/examples/conformance/context-derived/fixture/teaql/model-provenance.json b/examples/conformance/context-derived/fixture/teaql/model-provenance.json new file mode 100644 index 000000000..ef531590e --- /dev/null +++ b/examples/conformance/context-derived/fixture/teaql/model-provenance.json @@ -0,0 +1 @@ +{"schemaVersion":1,"modelUuid":null,"revisionHash":null,"generatorVersion":"4e69b6c8"} \ No newline at end of file diff --git a/examples/conformance/context-derived/verify-local.cjs b/examples/conformance/context-derived/verify-local.cjs new file mode 100644 index 000000000..7f0b9f6e0 --- /dev/null +++ b/examples/conformance/context-derived/verify-local.cjs @@ -0,0 +1,78 @@ +'use strict'; +const fs = require('node:fs'), path = require('node:path'), os = require('node:os'); +const cp = require('node:child_process'), crypto = require('node:crypto'), assert = require('node:assert/strict'); +const {createOwnedRunner, ownedBytes} = require('../../fix-e-alignment/owned-command.cjs'); +const repo = path.resolve(__dirname, '../../..'), fixture = path.join(__dirname, 'fixture'); +const sha = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); +const requested = process.env.TEAQL_CONTEXT_FIX_EVIDENCE_DIR; +const output = requested ? path.resolve(requested) : fs.mkdtempSync(path.join(os.tmpdir(), 'teaql-context-evidence-')); +if (requested) { assert(!fs.existsSync(output), 'use a new evidence directory'); fs.mkdirSync(output, {recursive: true}); } +const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'teaql-context-build-')); +const runner = createOwnedRunner(); +const report = {schema: 'teaql.java-context-derived-mutation/v1', passed: false, rounds: [], publicPublication: false}; +function inputs() { + const manifest = fs.readFileSync(path.join(fixture, 'generated-files.json')); + const files = JSON.parse(manifest); + for (const [name, hash] of Object.entries(files)) { + assert((name.startsWith('lib/') || name === 'teaql/model-provenance.json') && !name.split('/').includes('..')); + const file = path.join(fixture, name); assert.equal(fs.realpathSync(file), file); + assert.equal(sha(fs.readFileSync(file)), hash, name); + } + return {files, manifestSha256: sha(manifest), modelSha256: sha(fs.readFileSync(path.join(fixture, 'model.xml')))}; +} +async function main() { + try { + const disk = fs.statfsSync(scratch); assert(disk.bavail * disk.bsize > 2 * 1024 ** 3); + const fixtureInputs = inputs(); report.fixture = fixtureInputs; + const sourceFiles = cp.execFileSync('git', ['-C', repo, 'ls-files', '-z', '--cached', '--others', '--exclude-standard']) + .toString().split('\0').filter(Boolean); + const runtime = path.join(scratch, 'runtime'), bundle = path.join(scratch, 'model'), generated = path.join(bundle, 'lib'); + const consumer = path.join(scratch, 'consumer'), tests = path.join(consumer, 'src/test/java/io/teaql/examples/contextfix'); + const sourceHash = crypto.createHash('sha256'); + for (const name of [...new Set(sourceFiles)].sort()) { + const file = path.join(repo, name); if (!fs.existsSync(file)) continue; + assert(fs.lstatSync(file).isFile(), 'no source symlinks'); + const bytes = fs.readFileSync(file); sourceHash.update(name + '\0'); sourceHash.update(bytes); + const target = path.join(runtime, name); fs.mkdirSync(path.dirname(target), {recursive: true}); fs.copyFileSync(file, target); + } + report.sourceCommit = cp.execFileSync('git', ['-C', repo, 'rev-parse', 'HEAD']).toString().trim(); + report.sourceSha256 = sourceHash.digest('hex'); + for (const name of Object.keys(fixtureInputs.files)) { + const target = path.join(bundle, name); fs.mkdirSync(path.dirname(target), {recursive: true}); + fs.copyFileSync(path.join(fixture, name), target); + } + const version = fs.readFileSync(path.join(runtime, 'pom.xml'), 'utf8').match(/([^<]+)<\/version>/)[1]; + report.metadataOverride = require('../../../scripts/pin-local-example-pom.cjs').pin(path.join(generated, 'pom.xml'), runtime, scratch); + fs.mkdirSync(tests, {recursive: true}); + const app = fs.readFileSync(path.join(__dirname, 'GeneratedContextFixTest.java')); + report.applicationSha256 = sha(app); fs.writeFileSync(path.join(tests, 'GeneratedContextFixTest.java'), app); + const dependencies = ['teaql-runtime', 'teaql-provider-jdbc', 'teaql-sqlite'].map(name => + `io.teaql${name}${version}`).join(''); + fs.writeFileSync(path.join(consumer, 'pom.xml'), `4.0.0io.teaqlteaql-java-parent${version}../runtime/pom.xmlio.teaql.examplescontext-fix-consumer${version}com.examplecontext-fix-service-core0.0.1-SNAPSHOT${dependencies}junitjunit4.13.2testorg.apache.maven.pluginsmaven-surefire-pluginfalse`); + const reactor = path.join(scratch, 'pom.xml'); + fs.writeFileSync(reactor, '4.0.0io.teaql.testcontext-reactor0pomruntimemodel/libconsumer'); + for (const round of [1, 2]) { + const command = [process.env.MAVEN || 'mvn', '-o', '-q', '-ntp', '-f', reactor, '-pl', ':context-fix-consumer', '-am', + 'test', '-Dtest=GeneratedContextFixTest', '-Dsurefire.failIfNoSpecifiedTests=false', '-Dteaql.expected.runtime.root=' + runtime]; + const log = path.join(output, 'round-' + round + '.log'), fd = fs.openSync(log, 'wx'); let result; + try { result = await runner.run(command, {cwd: scratch, timeout: 300000, env: {...process.env, + TEAQL_CONTEXT_FIX_DB: path.join(output, 'fixture.sqlite')}, stdio: ['ignore', fd, fd]}); } + finally { fs.closeSync(fd); } + const bytes = fs.readFileSync(log); + report.rounds.push({round, command, exitCode: result.status, logSha256: sha(bytes)}); + assert.equal(result.status, 0, bytes.toString().slice(-6000)); + assert.match(bytes.toString(), /JAVA_CONTEXT_FIX_SQLITE=passed typedQ=true typedE=true noOpProviderCalls=0 failedCheckProviderCalls=0 updateAudits=1 objectLocation=true/); + assert.deepEqual(inputs(), fixtureInputs, 'generated fixture changed'); + } + report.sameDatabase = true; report.databaseSha256 = sha(fs.readFileSync(path.join(output, 'fixture.sqlite'))); + report.passed = true; console.log('PASS generated Java Context Fix SQLite example twice with local runtime'); + } catch (error) { report.error = error.stack; process.exitCode ||= 1; console.error(error.stack); } + finally { + report.disposedOwnedBytes = runner.safeToClean ? ownedBytes(scratch) : 0; + if (runner.safeToClean) fs.rmSync(scratch, {recursive: true}); else report.unsafeBuildRetention = scratch; + report.scratchRemoved = !fs.existsSync(scratch); runner.dispose(); + fs.writeFileSync(path.join(output, 'receipt.json'), JSON.stringify(report, null, 2) + '\n'); + console.log('Context Fix evidence: ' + output); + } +} +main().catch(error => { console.error(error.stack); process.exitCode ||= 1; }); diff --git a/scripts/verify-examples.sh b/scripts/verify-examples.sh index e222486c6..da03b602d 100755 --- a/scripts/verify-examples.sh +++ b/scripts/verify-examples.sh @@ -86,4 +86,5 @@ TEAQL_JAVA_JSON_PROFILE_EVIDENCE_DIR="$evidence_dir/loaded-revert" \ node "${TEAQL_JAVA_EXAMPLE_SOURCE_ROOT:-$repo}/examples/scalar-type-probe/verify-json-profiles.cjs" --loaded-revert TEAQL_JAVA_JSON_PROFILE_EVIDENCE_DIR="$evidence_dir/version-lifecycle" \ node "${TEAQL_JAVA_EXAMPLE_SOURCE_ROOT:-$repo}/examples/scalar-type-probe/verify-json-profiles.cjs" --version-lifecycle +node "$repo/examples/conformance/context-derived/verify-local.cjs" echo "PASS: all Java examples" diff --git a/teaql-core/src/main/java/io/teaql/core/BaseEntity.java b/teaql-core/src/main/java/io/teaql/core/BaseEntity.java index 19d5290b2..65070fd47 100644 --- a/teaql-core/src/main/java/io/teaql/core/BaseEntity.java +++ b/teaql-core/src/main/java/io/teaql/core/BaseEntity.java @@ -376,6 +376,37 @@ public void clearUpdatedProperties() { if (!updatedProperties.isEmpty()) updatedProperties.clear(); } + /** Restore only automatic Context assignments after failed admission, not caller edits. */ + @FrameworkInternal("Context Fix rollback before persistence") + public Runnable __internalCaptureContextFix(java.util.Set fields) { + record Before(Object value, boolean loaded, PropertyChange change, boolean ledgerField, Object ledgerValue) {} + var before = new java.util.LinkedHashMap(); + var key = id == null ? null : new EntityKey(typeName(), id); + var status = $status; + for (String field : fields) { + boolean present = entityMutationLedger != null && key != null && entityMutationLedger.containsField(key, field); + before.put(field, new Before(__internalGet(field), isPropertyLoaded(field), updatedProperties.get(field), + present, present ? entityMutationLedger.get(key, field) : null)); + } + return () -> { + before.forEach((field, old) -> { + __internalSet(field, old.value()); + loadState = loadState.withLoaded(field, old.loaded()); + if (old.change() == null) { + if (!updatedProperties.isEmpty()) updatedProperties.remove(field); + } else mutableUpdatedProperties().put(field, old.change()); + if (entityMutationLedger != null && key != null) { + if (old.ledgerField()) entityMutationLedger.set(key, field, old.ledgerValue()); + else entityMutationLedger.clearField(key, field); + } + }); + if ($status == EntityStatus.UPDATED && status == EntityStatus.PERSISTED + && updatedProperties.isEmpty() && __internalDynamicMutations().isEmpty()) { + $status = status; + } + }; + } + @FrameworkInternal("Physical transaction rollback; native values are captured by runtime metadata") public Runnable __internalCaptureMutationRollback() { var savedUpdates = new HashMap<>(updatedProperties); diff --git a/teaql-core/src/main/java/io/teaql/core/checker/Checker.java b/teaql-core/src/main/java/io/teaql/core/checker/Checker.java index f976ba7fc..a0d64380f 100644 --- a/teaql-core/src/main/java/io/teaql/core/checker/Checker.java +++ b/teaql-core/src/main/java/io/teaql/core/checker/Checker.java @@ -24,6 +24,28 @@ public interface Checker { void checkAndFix(UserContext context, T entity, ObjectLocation location); + /** Compute before applying any automatic Context assignments; Check remains independent. */ + default boolean needContextFix(UserContext context, T entity) { + return entity != null && io.teaql.core.checker.internal.ContextFixFields.eligible(context, entity); + } + + /** Keep Context-provider/type failures attached to the declaring model field. */ + default void applyContextFix(UserContext context, ObjectLocation location, Runnable assignment) { + try { + assignment.run(); + } catch (CheckException located) { + throw located; + } catch (RuntimeException failure) { + // Provider messages/causes may contain request secrets. The public + // violation identifies the model field, not the provider's raw data. + var violation = CheckResult.invalidType(location, + "Context Fix failed at " + type() + "." + (location == null ? "" : location.modelPath())); + violation.setRootType(type()); + context.translateCheckResult(violation); + throw new CheckException(java.util.List.of(violation)); + } + } + default void markAsChecked(UserContext context, T entity) { java.util.List list = (java.util.List) CheckerInvocation.attribute(context, TEAQL_DATA_CHECKED_ITEMS); if (list == null) { diff --git a/teaql-core/src/main/java/io/teaql/core/checker/internal/ContextFixFields.java b/teaql-core/src/main/java/io/teaql/core/checker/internal/ContextFixFields.java new file mode 100644 index 000000000..8d7d0e5a2 --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/checker/internal/ContextFixFields.java @@ -0,0 +1,47 @@ +package io.teaql.core.checker.internal; + +import io.teaql.core.BaseEntity; +import io.teaql.core.UserContext; +import io.teaql.core.meta.EntityDescriptor; +import io.teaql.core.meta.EntityMetaFactory; +import java.util.LinkedHashSet; +import java.util.Set; + +/** Model-declared Context fields, never a list of guessed time/IP/actor column names. */ +public final class ContextFixFields { + private ContextFixFields() {} + + public static Set declared(EntityDescriptor descriptor) { + var fields = new LinkedHashSet(); + for (var current = descriptor; current != null; current = current.getParent()) { + for (var property : current.getProperties()) { + // A relation's effective attributes may traverse its reverse + // owner; Context ownership belongs to this property itself. + var attributes = property.getSelfAdditionalInfo(); + if (nonempty(attributes.get("createFunction")) || nonempty(attributes.get("updateFunction")) + || "true".equalsIgnoreCase(attributes.get("contextDerived"))) fields.add(property.getName()); + } + } + return fields; + } + + private static boolean nonempty(String value) { return value != null && !value.isBlank(); } + + public static boolean eligible(UserContext context, BaseEntity entity) { + if (entity.isMarkedAsDelete()) return false; + if (entity.isNew()) return true; + if (!entity.updateItem()) return false; + if (!entity.__internalDynamicMutations().isEmpty()) return true; + var fields = declared(EntityMetaFactory.requireFrom(context).resolveEntityDescriptor(entity.typeName())); + for (String field : entity.getUpdatedProperties()) { + if (!BaseEntity.ID_PROPERTY.equals(field) && !BaseEntity.VERSION_PROPERTY.equals(field) + && !fields.contains(field)) return true; + } + // A composed graph may have dynamic intent on this exact entity only. + if (entity.__internalHasMutationLedger() && entity.getId() != null) { + var key = new io.teaql.core.EntityKey(entity.typeName(), entity.getId()); + return entity.getEntityMutationLedger().changedFieldNames(key).stream().anyMatch(name -> name.startsWith("#")); + } + return false; + } +} diff --git a/teaql-runtime/src/main/java/io/teaql/runtime/TeaQLRuntime.java b/teaql-runtime/src/main/java/io/teaql/runtime/TeaQLRuntime.java index be081a328..16d77b5d1 100644 --- a/teaql-runtime/src/main/java/io/teaql/runtime/TeaQLRuntime.java +++ b/teaql-runtime/src/main/java/io/teaql/runtime/TeaQLRuntime.java @@ -492,8 +492,6 @@ public void saveGraph(UserContext context, Entity entity) { CanonicalMutationFields.validateGraph(context, metadata, entity); io.teaql.runtime.mutation.MutationVersionAdmission.validateGraph(metadata, entity); checkAndFix(context, entity); - CanonicalMutationFields.validateGraph(context, metadata, entity); - io.teaql.runtime.mutation.MutationVersionAdmission.validateGraph(metadata, entity); // Get entity's own EntityMutationLedger EntityMutationLedger entityMutationLedger = ((BaseEntity) entity).getEntityMutationLedger(); @@ -686,7 +684,10 @@ private void checkAndFix(UserContext context, Entity entity) { } try (var invocation = io.teaql.core.checker.internal.CheckerInvocation.openMutation(context)) { context.beginFixEvidence(); + var contextUndo = new ArrayList(); try { + captureContextFixRollback(entity, contextUndo, + Collections.newSetFromMap(new IdentityHashMap<>())); checkGraphMutations(context, entity, null, Collections.newSetFromMap(new IdentityHashMap<>())); List violations = (List) invocation.attribute(Checker.TEAQL_DATA_CHECK_RESULT); @@ -699,12 +700,31 @@ private void checkAndFix(UserContext context, Entity entity) { context.translateCheckResults(violations); throw new CheckException(new ArrayList<>(violations)); } + // Post-Fix admission belongs to the same staging boundary. + CanonicalMutationFields.validateGraph(context, metadata, entity); + io.teaql.runtime.mutation.MutationVersionAdmission.validateGraph(metadata, entity); + } catch (RuntimeException | Error failure) { + for (int index = contextUndo.size() - 1; index >= 0; index--) { + try { contextUndo.get(index).run(); } + catch (RuntimeException | Error rollbackFailure) { failure.addSuppressed(rollbackFailure); } + } + throw failure; } finally { context.finishFixEvidence(); } } } + private void captureContextFixRollback(Entity entity, List undo, Set visited) { + if (!(entity instanceof BaseEntity base) || !visited.add(entity)) return; + if (base.needPersist() && !base.isMarkedAsDelete()) { + var fields = io.teaql.core.checker.internal.ContextFixFields.declared( + metadata.resolveEntityDescriptor(entity.typeName())); + if (!fields.isEmpty()) undo.add(base.__internalCaptureContextFix(fields)); + } + visitRelatedEntities(entity, child -> captureContextFixRollback(child, undo, visited)); + } + @SuppressWarnings({"rawtypes", "unchecked"}) private void checkGraphMutations(UserContext context, Entity entity, io.teaql.core.checker.ObjectLocation location, Set visited) { diff --git a/teaql-runtime/src/test/java/io/teaql/runtime/ContextDerivedMutationTest.java b/teaql-runtime/src/test/java/io/teaql/runtime/ContextDerivedMutationTest.java new file mode 100644 index 000000000..87c0fbac6 --- /dev/null +++ b/teaql-runtime/src/test/java/io/teaql/runtime/ContextDerivedMutationTest.java @@ -0,0 +1,194 @@ +package io.teaql.runtime; + +import io.teaql.core.*; +import io.teaql.core.checker.*; +import io.teaql.core.meta.*; +import io.teaql.core.businessid.BusinessClock; +import java.time.*; +import java.util.*; +import org.junit.Test; +import static org.junit.Assert.*; + +/** Small Context fixture; real save entry, observed provider, no generated-source edits. */ +public class ContextDerivedMutationTest { + static final LocalDateTime A = LocalDateTime.of(2026, 11, 11, 10, 0); + static final LocalDateTime B = A.plusHours(1); + static final List CONTEXT = List.of("born_at", "touched_at", "source_ip", "last_ip", "opened_by", "changed_by"); + + public static final class Probe extends BaseEntity { + final Map values = new HashMap<>(); + @Override public String typeName() { return "ContextProbe"; } + @Override public Object __internalGet(String field) { + return field.equals("id") || field.equals("version") ? super.__internalGet(field) : values.get(field); + } + @Override public void __internalSet(String field, Object value) { + if (field.equals("id") || field.equals("version")) super.__internalSet(field, value); else values.put(field, value); + } + } + + static final class Provider implements MutationExecutor { + int writes; + final Map> rows = new HashMap<>(); + public MutationResult mutate(UserContext context, PersistenceMutation mutation) { + writes++; + var row = (Probe) ((EntityPersistenceMutation) mutation).getEntity(); + var stored = new HashMap<>(rows.getOrDefault(row.getId(), Map.of())); + stored.putAll(row.values); + long version = ((Number) stored.getOrDefault("version", 0L)).longValue() + 1; + stored.put("id", row.getId()); stored.put("version", version); rows.put(row.getId(), stored); + var saved = loaded(row.getId(), stored); + return new DefaultMutationResult(saved); + } + public String name() { return "context-fixture"; } + public DataServiceCapabilities capabilities() { return new DataServiceCapabilities(); } + } + + static Probe loaded(long id, Map values) { + var row = new Probe(); + row.__internalSet("id", id); row.__internalSet("version", values.getOrDefault("version", 1L)); + values.forEach(row::__internalSet); + values.keySet().forEach(row::markPropertyLoaded); + row.markPropertyLoaded("id"); row.markPropertyLoaded("version"); + row.set$status(EntityStatus.PERSISTED); + return row; + } + + static boolean contextFixAllowed(Checker checker, UserContext context, Probe row) { + // The same test also runs against the frozen pre-fix runtime. Its + // missing predicate takes the old unconditional automatic-Fix path. + try { + return (boolean) Checker.class.getMethod("needContextFix", UserContext.class, BaseEntity.class) + .invoke(checker, context, row); + } catch (NoSuchMethodException legacy) { return true; } + catch (ReflectiveOperationException error) { throw new AssertionError(error); } + } + + static final class Fixture { + final Provider provider = new Provider(); + final DefaultUserContext context; + int checks, fixes, audits; + Fixture() { + var descriptor = new EntityDescriptor(); descriptor.setType("ContextProbe"); + descriptor.setTargetType(Probe.class); descriptor.setEntitySupplier(Probe::new); + descriptor.setDataService("context-fixture"); + var props = new ArrayList(); + for (String name : List.of("id", "version", "label")) { + var property = new PropertyDescriptor(); property.setName(name); props.add(property); + } + for (String name : CONTEXT) { + var property = new PropertyDescriptor(); property.setName(name); + property.with(name.equals("born_at") || name.equals("source_ip") || name.equals("opened_by") + ? "createFunction" : "updateFunction", "contextValue"); + props.add(property); + } + var children = new Relation(); children.setName("children"); children.setOwner(descriptor); props.add(children); + descriptor.setProperties(props); + var metadata = new SimpleEntityMetaFactory(); metadata.register(descriptor); + var clock = new BusinessClock() { + public LocalDate businessDate(UserContext caller) { return businessDateTime(caller).toLocalDate(); } + public LocalDateTime businessDateTime(UserContext caller) { return (LocalDateTime) caller.getAttribute("fixture_now"); } + }; + var runtime = TeaQLRuntime.builder().metadata(metadata).dataService("context-fixture", provider) + .businessClock(clock).executionLogging(false).build(); + runtime.install(RuntimeModule.of().withCheckers(new Checker() { + public String type() { return "ContextProbe"; } + // Validation must remain callable even for a clean object. + public boolean needCheck(UserContext caller, Probe row) { return row.get$status() != EntityStatus.REFER; } + public void checkAndFix(UserContext caller, Probe row, ObjectLocation location) { + checks++; + if (contextFixAllowed(this, caller, row)) { + fixes++; + if (row.isNew()) { + row.updateProperty("born_at", caller.businessTime()); + row.updateProperty("source_ip", caller.getAttribute("fixture_ip")); + row.updateProperty("opened_by", caller.getAttribute("fixture_actor")); + } + row.updateProperty("touched_at", caller.businessTime()); + row.updateProperty("last_ip", caller.getAttribute("fixture_ip")); + row.updateProperty("changed_by", caller.getAttribute("fixture_actor")); + } + requiredCheck(caller, newLocation(location, "label"), row.values.get("label")); + if ("INVALID".equals(row.values.get("label"))) + invalidTypeCheck(caller, newLocation(location, "label"), "fixture rejection"); + } + })); + context = new DefaultUserContext(runtime); + context.putAttribute(AppAuditEventSink.class.getName(), (AppAuditEventSink) (caller, event) -> audits++); + use(A, "192.0.2.10", "alice"); + } + void use(LocalDateTime now, String ip, String actor) { + context.putAttribute("fixture_now", now); context.putAttribute("fixture_ip", ip); context.putAttribute("fixture_actor", actor); + } + Probe original(long id) { + var data = new HashMap(); data.put("label", "original"); data.put("version", 1L); + data.put("born_at", A); data.put("touched_at", A); data.put("source_ip", "192.0.2.10"); + data.put("last_ip", "192.0.2.10"); data.put("opened_by", "alice"); data.put("changed_by", "alice"); + provider.rows.put(id, new HashMap<>(data)); + return loaded(id, data); + } + void save(Probe row) { row.auditAs("verify Context-derived save semantics").save(context); } + } + + @Test public void differentContextAloneCannotCreateAnUpdateButCheckStillRuns() { + var f = new Fixture(); var row = f.original(1); var before = new HashMap<>(row.values); + f.use(B, "192.0.2.20", "bob"); f.save(row); f.save(row); + assertEquals(before, row.values); assertEquals(Long.valueOf(1), row.getVersion()); + assertEquals(0, f.provider.writes); assertEquals(0, f.audits); assertEquals(0, f.fixes); + assertEquals(2, f.checks); + } + + @Test public void realBusinessChangeUsesUpdateContextAndPreservesCreationContext() { + var f = new Fixture(); var row = f.original(1); f.use(B, "192.0.2.20", "bob"); + row.updateProperty("label", "changed"); f.save(row); + assertEquals(A, row.values.get("born_at")); assertEquals("192.0.2.10", row.values.get("source_ip")); + assertEquals("alice", row.values.get("opened_by")); assertEquals(B, row.values.get("touched_at")); + assertEquals("192.0.2.20", row.values.get("last_ip")); assertEquals("bob", row.values.get("changed_by")); + assertEquals(1, f.provider.writes); assertEquals(1, f.audits); + } + + @Test public void creationIsEligibleWithoutCallerDirtyFields() { + var f = new Fixture(); var row = new Probe(); row.__internalInitializeNewEntityId(7L); + row.__internalSet("label", "default input"); assertTrue(row.getUpdatedProperties().isEmpty()); + f.save(row); assertEquals(A, row.values.get("born_at")); assertEquals("192.0.2.10", row.values.get("source_ip")); + assertEquals("alice", row.values.get("changed_by")); assertEquals(1, f.provider.writes); + } + + @Test public void changedChildDoesNotRefreshParentOrSiblingContext() { + var f = new Fixture(); var parent = f.original(1); var child = f.original(2); var sibling = f.original(3); + parent.__internalSet("children", List.of(child, sibling)); + f.use(B, "192.0.2.20", "bob"); child.updateProperty("label", "changed child"); f.save(parent); + assertEquals(A, parent.values.get("touched_at")); assertEquals("alice", sibling.values.get("changed_by")); + assertEquals(B, child.values.get("touched_at")); assertEquals(1, f.provider.writes); + } + + @Test public void failedCheckRemovesAutomaticContextChangesButKeepsCallerIntent() { + var f = new Fixture(); var row = f.original(1); f.use(B, "192.0.2.20", "bob"); + row.updateProperty("label", "INVALID"); + var error = assertThrows(CheckException.class, () -> f.save(row)); + assertEquals("ContextProbe", error.getViolates().get(0).getRootType()); + assertEquals("label", error.getViolates().get(0).getLocation().modelPath()); + assertEquals("/label", error.getViolates().get(0).getLocation().instancePath()); + assertEquals(A, row.values.get("touched_at")); assertEquals("192.0.2.10", row.values.get("last_ip")); + assertEquals("alice", row.values.get("changed_by")); assertEquals("INVALID", row.values.get("label")); + assertEquals(Set.of("label"), new HashSet<>(row.getUpdatedProperties())); + assertEquals(0, f.provider.writes); assertEquals(0, f.audits); + row.updateProperty("label", "original"); f.save(row); + assertEquals(0, f.provider.writes); assertEquals(A, row.values.get("touched_at")); + row.updateProperty("label", "retry"); f.save(row); + assertEquals(1, f.provider.writes); assertEquals("bob", row.values.get("changed_by")); + } + + @Test public void invalidChildReportsItsExactObjectFieldAndIndex() { + var f = new Fixture(); var parent = f.original(1); var sibling = f.original(2); var child = f.original(3); + parent.__internalSet("children", List.of(sibling, child)); + f.use(B, "192.0.2.20", "bob"); child.updateProperty("label", "INVALID"); + var error = assertThrows(CheckException.class, () -> f.save(parent)); + var violation = error.getViolates().get(0); + assertEquals("ContextProbe", violation.getRootType()); + assertEquals("children[1].label", violation.getLocation().modelPath()); + assertEquals("/children/1/label", violation.getLocation().instancePath()); + assertEquals(0, f.provider.writes); assertEquals(0, f.audits); + assertEquals(A, child.values.get("touched_at")); + assertEquals("INVALID", child.values.get("label")); + } +} From 34f1ba33b6bc4b1a54ee326c7ac3fbd7cfdf9202 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Thu, 12 Nov 2026 02:55:09 +0800 Subject: [PATCH 02/47] fix(checker): discard Context staging after no-op business repair (#277) --- .../GeneratedContextFixTest.java | 8 ++++++++ .../context-derived/verify-local.cjs | 18 ++++++++++++++++++ .../main/java/io/teaql/core/BaseEntity.java | 14 +++++++++++--- .../java/io/teaql/runtime/TeaQLRuntime.java | 19 +++++++++++++++---- .../runtime/ContextDerivedMutationTest.java | 11 +++++++++++ 5 files changed, 63 insertions(+), 7 deletions(-) diff --git a/examples/conformance/context-derived/GeneratedContextFixTest.java b/examples/conformance/context-derived/GeneratedContextFixTest.java index d355ae8d0..5b31b1415 100644 --- a/examples/conformance/context-derived/GeneratedContextFixTest.java +++ b/examples/conformance/context-derived/GeneratedContextFixTest.java @@ -45,6 +45,7 @@ static class ContextChecker extends EntryChecker { row.updateChangedBy(context.getAttribute("actor", String.class)); } super.doCheck(context, row, location); + if ("NORMALIZE".equals(row.getName())) row.updateName("entry"); if ("INVALID".equals(row.getName())) invalidTypeCheck(context, newLocation(location, "name"), "fixture rejection"); } } @@ -113,6 +114,13 @@ static class ContextChecker extends EntryChecker { assertEquals(Long.valueOf(version), row.getVersion()); assertEquals(A, row.getTouchedAt()); assertEquals("192.0.2.10", row.getLastIp()); assertEquals("alice", row.getChangedBy()); + row.updateName("NORMALIZE"); + row.auditAs("normalize business edit back to its persisted value").save(context); + assertEquals("a repaired no-op must not acquire a connection", connections, ds.calls.get()); + assertEquals(0, audit.get()); assertEquals(Long.valueOf(version), row.getVersion()); + assertEquals("entry", row.getName()); assertEquals(A, row.getTouchedAt()); + assertEquals("192.0.2.10", row.getLastIp()); assertEquals("alice", row.getChangedBy()); + row.updateName("INVALID"); Entry invalid = row; connections = ds.calls.get(); var error = assertThrows(CheckException.class, () -> invalid.auditAs("reject Context fixture").save(context)); diff --git a/examples/conformance/context-derived/verify-local.cjs b/examples/conformance/context-derived/verify-local.cjs index 7f0b9f6e0..4f9732835 100644 --- a/examples/conformance/context-derived/verify-local.cjs +++ b/examples/conformance/context-derived/verify-local.cjs @@ -51,6 +51,24 @@ async function main() { fs.writeFileSync(path.join(consumer, 'pom.xml'), `4.0.0io.teaqlteaql-java-parent${version}../runtime/pom.xmlio.teaql.examplescontext-fix-consumer${version}com.examplecontext-fix-service-core0.0.1-SNAPSHOT${dependencies}junitjunit4.13.2testorg.apache.maven.pluginsmaven-surefire-pluginfalse`); const reactor = path.join(scratch, 'pom.xml'); fs.writeFileSync(reactor, '4.0.0io.teaql.testcontext-reactor0pomruntimemodel/libconsumer'); + if (process.env.TEAQL_CONTEXT_FIX_UNIT_TESTS === '1') { + const command = [process.env.MAVEN || 'mvn', '-o', '-q', '-ntp', '-f', path.join(runtime, 'pom.xml'), + '-pl', 'teaql-runtime', '-am', 'test']; + const log = path.join(output, 'unit.log'), fd = fs.openSync(log, 'wx'); let result; + try { result = await runner.run(command, {cwd: scratch, timeout: 300000, env: {...process.env}, stdio: ['ignore', fd, fd]}); } + finally { fs.closeSync(fd); } + report.unit = {command, exitCode: result.status, logSha256: sha(fs.readFileSync(log))}; + assert.equal(result.status, 0, fs.readFileSync(log, 'utf8').slice(-6000)); + report.unit.suites = []; + for (const module of fs.readdirSync(runtime)) { + const directory = path.join(runtime, module, 'target', 'surefire-reports'); + if (fs.existsSync(directory)) for (const file of fs.readdirSync(directory).filter(name => name.endsWith('.txt'))) { + const summary = fs.readFileSync(path.join(directory, file), 'utf8').match(/Tests run: (\d+), Failures: (\d+), Errors: (\d+), Skipped: (\d+)/); + if (summary) report.unit.suites.push({module, file, tests: +summary[1], failures: +summary[2], errors: +summary[3], skipped: +summary[4]}); + } + } + assert(report.unit.suites.some(suite => suite.file.includes('ContextDerivedMutationTest') && suite.tests >= 7)); + } for (const round of [1, 2]) { const command = [process.env.MAVEN || 'mvn', '-o', '-q', '-ntp', '-f', reactor, '-pl', ':context-fix-consumer', '-am', 'test', '-Dtest=GeneratedContextFixTest', '-Dsurefire.failIfNoSpecifiedTests=false', '-Dteaql.expected.runtime.root=' + runtime]; diff --git a/teaql-core/src/main/java/io/teaql/core/BaseEntity.java b/teaql-core/src/main/java/io/teaql/core/BaseEntity.java index 65070fd47..24573162d 100644 --- a/teaql-core/src/main/java/io/teaql/core/BaseEntity.java +++ b/teaql-core/src/main/java/io/teaql/core/BaseEntity.java @@ -400,9 +400,17 @@ record Before(Object value, boolean loaded, PropertyChange change, boolean ledge else entityMutationLedger.clearField(key, field); } }); - if ($status == EntityStatus.UPDATED && status == EntityStatus.PERSISTED - && updatedProperties.isEmpty() && __internalDynamicMutations().isEmpty()) { - $status = status; + // Fix may have repaired the last caller edit as well. A saved + // UPDATED status alone must not survive when all native/dynamic + // intent for this exact entity has gone away. + boolean pending = entityMutationLedger != null && key != null && ( + !entityMutationLedger.changedFieldNames(key).isEmpty() + || entityMutationLedger.isNew(key) || entityMutationLedger.isMarkedAsDelete(key) + || entityMutationLedger.recoveredKeys().contains(key)); + if ($status == EntityStatus.UPDATED + && (status == EntityStatus.PERSISTED || status == EntityStatus.UPDATED) + && updatedProperties.isEmpty() && __internalDynamicMutations().isEmpty() && !pending) { + $status = EntityStatus.PERSISTED; } }; } diff --git a/teaql-runtime/src/main/java/io/teaql/runtime/TeaQLRuntime.java b/teaql-runtime/src/main/java/io/teaql/runtime/TeaQLRuntime.java index 16d77b5d1..2eea74543 100644 --- a/teaql-runtime/src/main/java/io/teaql/runtime/TeaQLRuntime.java +++ b/teaql-runtime/src/main/java/io/teaql/runtime/TeaQLRuntime.java @@ -684,7 +684,7 @@ private void checkAndFix(UserContext context, Entity entity) { } try (var invocation = io.teaql.core.checker.internal.CheckerInvocation.openMutation(context)) { context.beginFixEvidence(); - var contextUndo = new ArrayList(); + var contextUndo = new ArrayList(); try { captureContextFixRollback(entity, contextUndo, Collections.newSetFromMap(new IdentityHashMap<>())); @@ -700,12 +700,21 @@ private void checkAndFix(UserContext context, Entity entity) { context.translateCheckResults(violations); throw new CheckException(new ArrayList<>(violations)); } + // A customer Fix can normalize the last business edit back to + // its persisted value. Automatic Context fields must not then + // become the only reason to write. Keep the repaired business + // values; undo only this entity's staged Context assignments. + for (var checkpoint : contextUndo) { + if (!io.teaql.core.checker.internal.ContextFixFields.eligible(context, checkpoint.entity())) { + checkpoint.restore().run(); + } + } // Post-Fix admission belongs to the same staging boundary. CanonicalMutationFields.validateGraph(context, metadata, entity); io.teaql.runtime.mutation.MutationVersionAdmission.validateGraph(metadata, entity); } catch (RuntimeException | Error failure) { for (int index = contextUndo.size() - 1; index >= 0; index--) { - try { contextUndo.get(index).run(); } + try { contextUndo.get(index).restore().run(); } catch (RuntimeException | Error rollbackFailure) { failure.addSuppressed(rollbackFailure); } } throw failure; @@ -715,12 +724,14 @@ private void checkAndFix(UserContext context, Entity entity) { } } - private void captureContextFixRollback(Entity entity, List undo, Set visited) { + private record ContextFixCheckpoint(BaseEntity entity, Runnable restore) {} + + private void captureContextFixRollback(Entity entity, List undo, Set visited) { if (!(entity instanceof BaseEntity base) || !visited.add(entity)) return; if (base.needPersist() && !base.isMarkedAsDelete()) { var fields = io.teaql.core.checker.internal.ContextFixFields.declared( metadata.resolveEntityDescriptor(entity.typeName())); - if (!fields.isEmpty()) undo.add(base.__internalCaptureContextFix(fields)); + if (!fields.isEmpty()) undo.add(new ContextFixCheckpoint(base, base.__internalCaptureContextFix(fields))); } visitRelatedEntities(entity, child -> captureContextFixRollback(child, undo, visited)); } diff --git a/teaql-runtime/src/test/java/io/teaql/runtime/ContextDerivedMutationTest.java b/teaql-runtime/src/test/java/io/teaql/runtime/ContextDerivedMutationTest.java index 87c0fbac6..ed500b4eb 100644 --- a/teaql-runtime/src/test/java/io/teaql/runtime/ContextDerivedMutationTest.java +++ b/teaql-runtime/src/test/java/io/teaql/runtime/ContextDerivedMutationTest.java @@ -108,6 +108,7 @@ public void checkAndFix(UserContext caller, Probe row, ObjectLocation location) row.updateProperty("changed_by", caller.getAttribute("fixture_actor")); } requiredCheck(caller, newLocation(location, "label"), row.values.get("label")); + if ("NORMALIZE".equals(row.values.get("label"))) row.updateProperty("label", "original"); if ("INVALID".equals(row.values.get("label"))) invalidTypeCheck(caller, newLocation(location, "label"), "fixture rejection"); } @@ -146,6 +147,16 @@ Probe original(long id) { assertEquals(1, f.provider.writes); assertEquals(1, f.audits); } + @Test public void repairedBusinessEditCannotLeaveAnAutomaticContextOnlyUpdate() { + var f = new Fixture(); var row = f.original(1); f.use(B, "192.0.2.20", "bob"); + row.updateProperty("label", "NORMALIZE"); f.save(row); + assertEquals("original", row.values.get("label")); + assertEquals(0, f.provider.writes); assertEquals(0, f.audits); + assertEquals(Long.valueOf(1), row.getVersion()); + assertEquals(A, row.values.get("touched_at")); assertEquals("alice", row.values.get("changed_by")); + assertTrue(row.getUpdatedProperties().isEmpty()); + } + @Test public void creationIsEligibleWithoutCallerDirtyFields() { var f = new Fixture(); var row = new Probe(); row.__internalInitializeNewEntityId(7L); row.__internalSet("label", "default input"); assertTrue(row.getUpdatedProperties().isEmpty()); From 308935f11d9726207180ac0328c52014208cacbd Mon Sep 17 00:00:00 2001 From: Philip Z Date: Thu, 12 Nov 2026 04:08:29 +0800 Subject: [PATCH 03/47] fix(core): cancel proven dynamic-field no-ops before Context Fix (#277) --- examples/conformance/README.md | 7 ++ .../GeneratedContextFixTest.java | 107 +++++++++++++++++- .../context-derived/verify-local.cjs | 4 +- .../main/java/io/teaql/core/BaseEntity.java | 18 +++ .../java/io/teaql/core/ChangeSetStack.java | 4 + .../java/io/teaql/core/EntityChangeSet.java | 8 ++ .../io/teaql/core/EntityMutationLedger.java | 4 + .../DynamicMutationNormalizationTest.java | 66 +++++++++++ 8 files changed, 216 insertions(+), 2 deletions(-) create mode 100644 teaql-core/src/test/java/io/teaql/core/DynamicMutationNormalizationTest.java diff --git a/examples/conformance/README.md b/examples/conformance/README.md index 556fe6fdc..acdb09bd1 100644 --- a/examples/conformance/README.md +++ b/examples/conformance/README.md @@ -55,6 +55,13 @@ the caller's edit, which can be corrected or reverted. The application-owned Checker and metadata customization demonstrate the same guard for non-clock Context fields; generated timestamp assignments use that guard too. +The same fixture also loads typed readonly query properties and persistent +extensions. A readonly property does not dirty the entity. A dynamic-only edit +does apply update-scoped Context values, while assigning its known persisted +value again leaves SQL, version and committed audit unchanged. The extension +provider shares the exact JDBC executor used by the owner graph transaction; +there is no hand-written mutation SQL or separately committed extension write. + `TEAQL_CONTEXT_FIX_EVIDENCE_DIR` chooses a new directory for compact receipts, logs, hashes and the SQLite store. Temporary source/build consumers are removed on exit. This is local source acceptance, not a public-package release or diff --git a/examples/conformance/context-derived/GeneratedContextFixTest.java b/examples/conformance/context-derived/GeneratedContextFixTest.java index 5b31b1415..79c9ecbf2 100644 --- a/examples/conformance/context-derived/GeneratedContextFixTest.java +++ b/examples/conformance/context-derived/GeneratedContextFixTest.java @@ -9,9 +9,12 @@ import io.teaql.core.sqlite.SqliteDataServiceExecutor; import io.teaql.provider.jdbc.JdbcSqlExecutor; import io.teaql.runtime.*; +import io.teaql.data.dynamic.*; +import io.teaql.data.dynamic.jdbc.JdbcDynamicFieldsProvider; import java.time.*; import java.sql.*; import java.util.concurrent.atomic.*; +import java.util.Map; import java.io.PrintWriter; import java.util.logging.Logger; import javax.sql.DataSource; @@ -58,7 +61,8 @@ static class ContextChecker extends EntryChecker { assertNotNull("use an owned persistent SQLite path", database); var ds = new Source("jdbc:sqlite:" + database); var metadata = new SimpleEntityMetaFactory(); - var data = new SqliteDataServiceExecutor("sqlite", new JdbcSqlExecutor(ds), ds); + var sql = new JdbcSqlExecutor(ds); + var data = new SqliteDataServiceExecutor("sqlite", sql, ds); var ids = new AtomicLong(System.currentTimeMillis()); var runtime = TeaQLRuntime.builder().metadata(metadata).dataService("sqlite", data) .dataService("default", data).idGenerationService(new InternalIdGenerationService() { @@ -150,6 +154,107 @@ static class ContextChecker extends EntryChecker { assertEquals("alice", persisted.getOpenedBy()); assertEquals(B, persisted.getTouchedAt()); assertEquals("192.0.2.20", persisted.getLastIp()); assertEquals("bob", persisted.getChangedBy()); assertEquals(Long.valueOf(version + 1), persisted.getVersion()); + // A computed result belongs to the query view, not the mutation ledger. + var readonlyRequest = Q.entries().withIdIs(id).limit(1); + readonlyRequest.setDynamicPropertyMetadata(new DynamicPropertyMetadata(Map.of("_name_copy", String.class))); + readonlyRequest.addSimpleDynamicProperty("_name_copy", new PropertyReference("name")); + var readonly = readonlyRequest.comment("Load a typed readonly query result") + .purpose("Prove view materialization is not a business edit").executeForOne(context); + assertEquals(persisted.getName(), readonly.getDynamicProperty("_name_copy")); + assertTrue(readonly.getUpdatedProperties().isEmpty()); + context.putAttribute("businessNow", B.plusHours(1)); + context.putAttribute("clientIp", "192.0.2.30"); context.putAttribute("actor", "carol"); + connections = ds.calls.get(); int auditsBefore = audit.get(); + for (int attempt = 0; attempt < 2; attempt++) + readonly.auditAs("Retain readonly properties without Context-only writes").save(context); + assertEquals(connections, ds.calls.get()); assertEquals(auditsBefore, audit.get()); + assertEquals(Long.valueOf(version + 1), readonly.getVersion()); assertEquals(B, readonly.getTouchedAt()); + assertEquals(persisted.getName(), readonly.getDynamicProperty("_name_copy")); + + // Persist extensions through the same audited graph boundary and exact JDBC executor. + var provider = new JdbcDynamicFieldsProvider(sql); provider.ensureSchema(); + DynamicFieldContext definitionContext = new DynamicFieldContext() { + public String scopeType() { return "GLOBAL"; } + public String scopeId() { return "default"; } + public String userId() { return "context-example"; } + public String purpose() { return "Verify Context Fix for persistent extensions"; } + public String comment() { return "Register a controlled extension definition"; } + public boolean strictIntent() { return true; } + public long nextId(String type) { return ids.incrementAndGet(); } + }; + if (provider.listFieldDefs(definitionContext, "Entry").stream().noneMatch(def -> "context_note".equals(def.getCode()))) { + var def = new DynamicFieldDef(); def.setScope(DynamicFieldScope.global()); def.setOwnerType("Entry"); + def.setCode("context_note"); def.setName("Context note"); def.setDataType(DynamicDataType.STRING); + provider.registerFieldDef(definitionContext, def); + } + context.putAttribute(DynamicFieldsFacade.class.getName(), + new DefaultDynamicFieldsFacade(provider).withIdGenerator(type -> ids.incrementAndGet())); + var dynamicRequest = Q.entries().withIdIs(id).limit(1); + dynamicRequest.selectDynamicFieldsWith(new DynamicFieldSelection().selectString("context_note")); + var dynamic = dynamicRequest.comment("Load typed extension definitions and values") + .purpose("Update only a persistent dynamic field").executeForOne(context); + assertEquals(DynamicFieldValue.State.NOT_LOADED, dynamic.dynamicFields().field("context_note").state()); + dynamic.updateDynamicField("context_note", "dynamic-only"); + assertTrue(dynamic.getUpdatedProperties().isEmpty()); + auditsBefore = audit.get(); + dynamic.auditAs("Persist a dynamic-only business edit with Context defaults").save(context); + assertEquals(auditsBefore + 1, audit.get()); + assertEquals(Long.valueOf(version + 2), dynamic.getVersion()); + assertEquals(B.plusHours(1), dynamic.getTouchedAt()); assertEquals("carol", dynamic.getChangedBy()); + assertEquals(A, dynamic.getBornAt()); assertEquals("alice", dynamic.getOpenedBy()); + var checkRequest = Q.entries().withIdIs(id).limit(1); + checkRequest.selectDynamicFieldsWith(new DynamicFieldSelection().selectString("context_note")); + var storedDynamic = checkRequest.comment("Read the committed extension and owner") + .purpose("Compare typed E and persistent extension readback").executeForOne(context); + assertEquals("dynamic-only", storedDynamic.dynamicFields().field("context_note").value()); + assertEquals(B.plusHours(1), E.entry(storedDynamic).getTouchedAt().eval()); + context.putAttribute("businessNow", B.plusHours(2)); context.putAttribute("actor", "dora"); + context.putAttribute("clientIp", "192.0.2.40"); + storedDynamic.updateDynamicField("context_note", "dynamic-only"); + connections = ds.calls.get(); auditsBefore = audit.get(); + storedDynamic.auditAs("An equal persistent extension is not a Context update").save(context); + assertEquals(connections, ds.calls.get()); assertEquals(auditsBefore, audit.get()); + assertEquals(Long.valueOf(version + 2), storedDynamic.getVersion()); + assertEquals("carol", storedDynamic.getChangedBy()); + // Repeat indexed failure/undo using real generated relationships, not a test-only carrier. + var graphRoot = Q.catalogs().comment("Create a separate generated graph owner") + .purpose("Verify indexed Checker locations before graph writes").newEntity(context); + graphRoot.updateName("graph-root"); graphRoot.auditAs("Create an isolated graph root").save(context); + context.withActiveRoot(new ContextEntityRef("Catalog", graphRoot.getId())); + for (String name : java.util.List.of("graph-first", "graph-second")) { + var child = Q.entries().comment("Prepare one generated graph child") + .purpose("Verify all children before persistence").newEntity(context); + child.updateName(name); child.updateCatalog(graphRoot); child.auditAs("Create a graph child").save(context); + } + var parent = Q.catalogs().withIdIs(graphRoot.getId()).limit(1) + .selectEntryListWith(Q.entries().orderByIdAscending().limit(10)) + .comment("Load the generated parent and both children") + .purpose("Verify exact child index and rollback of automatic Context values").executeForOne(context); + assertEquals(2, parent.getEntryList().size()); + var first = parent.getEntryList().get(0); var second = parent.getEntryList().get(1); + long parentVersion = parent.getVersion(), secondVersion = second.getVersion(); + LocalDateTime graphBefore = first.getTouchedAt(); + context.putAttribute("businessNow", B.plusHours(3)); context.putAttribute("actor", "eve"); + context.putAttribute("clientIp", "192.0.2.50"); + first.updateName("changed-child"); second.updateName("INVALID"); + connections = ds.calls.get(); auditsBefore = audit.get(); + var childError = assertThrows(CheckException.class, + () -> parent.auditAs("Reject a later invalid child before any graph write").save(context)); + assertTrue(childError.getViolates().stream().anyMatch(v -> "/entryList/1/name".equals(v.getLocation().instancePath()))); + assertEquals(connections, ds.calls.get()); assertEquals(auditsBefore, audit.get()); + assertEquals(graphBefore, first.getTouchedAt()); assertEquals("dora", first.getChangedBy()); + first.updateName("graph-first"); second.updateName("graph-second"); + parent.auditAs("Undo rejected graph edits without retaining automatic Context changes").save(context); + assertEquals(connections, ds.calls.get()); assertEquals(auditsBefore, audit.get()); + first.updateName("accepted-child"); parent.auditAs("Save only the genuinely changed generated child").save(context); + assertEquals(auditsBefore + 1, audit.get()); assertEquals(Long.valueOf(parentVersion), parent.getVersion()); + assertEquals(Long.valueOf(secondVersion), second.getVersion()); + var storedChild = Q.entries().withIdIs(first.getId()).limit(1) + .comment("Read the accepted graph child").purpose("Verify typed E after indexed failure and retry").executeForOne(context); + assertEquals("accepted-child", E.entry(storedChild).getName().eval()); assertEquals("eve", storedChild.getChangedBy()); + assertEquals(B.plusHours(3), E.entry(storedChild).getTouchedAt().eval()); + System.out.println("JAVA_CONTEXT_FIX_GRAPH=passed indexedLocation=true automaticUndo=true childOnly=true"); + System.out.println("JAVA_CONTEXT_FIX_EXTENSIONS=passed dynamicOnly=true readonlyNoop=true equalDynamicNoop=true"); System.out.println("JAVA_CONTEXT_FIX_SQLITE=passed typedQ=true typedE=true noOpProviderCalls=0 failedCheckProviderCalls=0 updateAudits=1 objectLocation=true"); } diff --git a/examples/conformance/context-derived/verify-local.cjs b/examples/conformance/context-derived/verify-local.cjs index 4f9732835..6a72add9b 100644 --- a/examples/conformance/context-derived/verify-local.cjs +++ b/examples/conformance/context-derived/verify-local.cjs @@ -46,7 +46,7 @@ async function main() { fs.mkdirSync(tests, {recursive: true}); const app = fs.readFileSync(path.join(__dirname, 'GeneratedContextFixTest.java')); report.applicationSha256 = sha(app); fs.writeFileSync(path.join(tests, 'GeneratedContextFixTest.java'), app); - const dependencies = ['teaql-runtime', 'teaql-provider-jdbc', 'teaql-sqlite'].map(name => + const dependencies = ['teaql-runtime', 'teaql-provider-jdbc', 'teaql-sqlite', 'teaql-dynamic-fields-jdbc'].map(name => `io.teaql${name}${version}`).join(''); fs.writeFileSync(path.join(consumer, 'pom.xml'), `4.0.0io.teaqlteaql-java-parent${version}../runtime/pom.xmlio.teaql.examplescontext-fix-consumer${version}com.examplecontext-fix-service-core0.0.1-SNAPSHOT${dependencies}junitjunit4.13.2testorg.apache.maven.pluginsmaven-surefire-pluginfalse`); const reactor = path.join(scratch, 'pom.xml'); @@ -80,6 +80,8 @@ async function main() { report.rounds.push({round, command, exitCode: result.status, logSha256: sha(bytes)}); assert.equal(result.status, 0, bytes.toString().slice(-6000)); assert.match(bytes.toString(), /JAVA_CONTEXT_FIX_SQLITE=passed typedQ=true typedE=true noOpProviderCalls=0 failedCheckProviderCalls=0 updateAudits=1 objectLocation=true/); + assert.match(bytes.toString(), /JAVA_CONTEXT_FIX_EXTENSIONS=passed dynamicOnly=true readonlyNoop=true equalDynamicNoop=true/); + assert.match(bytes.toString(), /JAVA_CONTEXT_FIX_GRAPH=passed indexedLocation=true automaticUndo=true childOnly=true/); assert.deepEqual(inputs(), fixtureInputs, 'generated fixture changed'); } report.sameDatabase = true; report.databaseSha256 = sha(fs.readFileSync(path.join(output, 'fixture.sqlite'))); diff --git a/teaql-core/src/main/java/io/teaql/core/BaseEntity.java b/teaql-core/src/main/java/io/teaql/core/BaseEntity.java index 24573162d..b841e5c25 100644 --- a/teaql-core/src/main/java/io/teaql/core/BaseEntity.java +++ b/teaql-core/src/main/java/io/teaql/core/BaseEntity.java @@ -789,6 +789,13 @@ public BaseEntity deleteDynamicField(String code) { private void stageDynamicMutation(io.teaql.data.dynamic.DynamicFieldMutation mutation) { EntityStatus nextStatus = get$status().next(EntityAction.UPDATE); + DynamicFieldValue original = dynamicOriginalValues.getOrDefault(mutation.code(), dynamicFieldValues.field(mutation.code())); + boolean restored = !newItem() && original.isLoaded() + && mutation.kind() == io.teaql.data.dynamic.DynamicFieldMutation.Kind.SET + && original.dataType() == mutation.dataType() && ObjectUtil.equals(original.value(), mutation.value()); + // A loaded persisted value, including explicit NULL, is a baseline. + // An absent/unselected value is not; new objects must still stage writes. + if (restored && !dynamicMutations.containsKey(mutation.code())) return; Map next = new HashMap<>(dynamicFieldValues.toMap()); if (mutation.kind() == io.teaql.data.dynamic.DynamicFieldMutation.Kind.SET) next.put(mutation.code(), mutation.asLoadedValue()); else next.remove(mutation.code()); @@ -797,6 +804,17 @@ private void stageDynamicMutation(io.teaql.data.dynamic.DynamicFieldMutation mut if (dynamicOriginalValues.isEmpty()) dynamicOriginalValues = new HashMap<>(); dynamicOriginalValues.putIfAbsent(mutation.code(), dynamicFieldValues.field(mutation.code())); __internalHydrateDynamicFields(values, state); + if (restored) { + dynamicMutations.remove(mutation.code()); dynamicOriginalValues.remove(mutation.code()); + EntityKey key = id == null ? null : new EntityKey(typeName(), id); + if (entityMutationLedger != null && key != null) entityMutationLedger.clearDynamicField(key, mutation.code()); + boolean pending = entityMutationLedger != null && key != null && ( + !entityMutationLedger.changedFieldNames(key).isEmpty() || entityMutationLedger.isNew(key) + || entityMutationLedger.isMarkedAsDelete(key) || entityMutationLedger.recoveredKeys().contains(key)); + if (get$status() == EntityStatus.UPDATED && updatedProperties.isEmpty() && dynamicMutations.isEmpty() && !pending) + set$status(EntityStatus.PERSISTED); + return; + } if (dynamicMutations.isEmpty()) dynamicMutations = new HashMap<>(); dynamicMutations.put(mutation.code(), mutation); set$status(nextStatus); diff --git a/teaql-core/src/main/java/io/teaql/core/ChangeSetStack.java b/teaql-core/src/main/java/io/teaql/core/ChangeSetStack.java index e0ffac448..e858f6158 100644 --- a/teaql-core/src/main/java/io/teaql/core/ChangeSetStack.java +++ b/teaql-core/src/main/java/io/teaql/core/ChangeSetStack.java @@ -80,6 +80,10 @@ void clearField(EntityKey key, String field) { for (EntityChangeSet changeSet : stack) changeSet.clearField(key, field); } + void clearDynamicField(EntityKey key, String code) { + for (EntityChangeSet changeSet : stack) changeSet.clearDynamicField(key, code); + } + public Set changedFieldNames(EntityKey key) { Set fields = new TreeSet<>(); for (EntityChangeSet changeSet : stack) { diff --git a/teaql-core/src/main/java/io/teaql/core/EntityChangeSet.java b/teaql-core/src/main/java/io/teaql/core/EntityChangeSet.java index 9fd7fec6c..354888cb8 100644 --- a/teaql-core/src/main/java/io/teaql/core/EntityChangeSet.java +++ b/teaql-core/src/main/java/io/teaql/core/EntityChangeSet.java @@ -44,6 +44,14 @@ public Map> d return Collections.unmodifiableMap(view); } + void clearDynamicField(EntityKey key, String code) { + if (dynamicChanges == null) return; + var fields = dynamicChanges.get(key); + if (fields == null) return; + fields.remove(code); + if (fields.isEmpty()) dynamicChanges.remove(key); + } + public void clearEntity(EntityKey key) { changes.remove(key); if (dynamicChanges != null) dynamicChanges.remove(key); diff --git a/teaql-core/src/main/java/io/teaql/core/EntityMutationLedger.java b/teaql-core/src/main/java/io/teaql/core/EntityMutationLedger.java index e74f8cea4..5244e8379 100644 --- a/teaql-core/src/main/java/io/teaql/core/EntityMutationLedger.java +++ b/teaql-core/src/main/java/io/teaql/core/EntityMutationLedger.java @@ -69,6 +69,10 @@ public void setDynamic(EntityKey key, io.teaql.data.dynamic.DynamicFieldMutation changeSets.currentMut().setDynamic(key, mutation); } + void clearDynamicField(EntityKey key, String code) { + changeSets.clearDynamicField(key, code); + } + public Object get(EntityKey key, String field) { return changeSets.get(key, field); } diff --git a/teaql-core/src/test/java/io/teaql/core/DynamicMutationNormalizationTest.java b/teaql-core/src/test/java/io/teaql/core/DynamicMutationNormalizationTest.java new file mode 100644 index 000000000..c26825701 --- /dev/null +++ b/teaql-core/src/test/java/io/teaql/core/DynamicMutationNormalizationTest.java @@ -0,0 +1,66 @@ +package io.teaql.core; + +import io.teaql.data.dynamic.*; +import java.util.Map; +import org.junit.Test; +import static org.junit.Assert.*; + +public class DynamicMutationNormalizationTest { + private static DynamicMemberStateTest.Row loaded(boolean known, String value) { + var row = new DynamicMemberStateTest.Row(); + row.__internalHydrate("id", 1L, row.__internalLoadState().layout().indexForLoad("id")); + row.__internalHydrate("version", 7L, row.__internalLoadState().layout().indexForLoad("version")); + row.setDynamicFieldValues(new DynamicFieldValues(new DynamicFieldMetadata(Map.of( + "note", DynamicDataType.STRING, "other", DynamicDataType.STRING)), + known ? Map.of("note", DynamicFieldValue.ofString("note", value)) : Map.of())); + row.set$status(EntityStatus.PERSISTED); return row; + } + + @Test public void equalLoadedValueDoesNotAllocateALedgerOrCreateMutationIntent() { + for (String value : java.util.Arrays.asList("same", null)) { + var row = loaded(true, value); var state = row.__internalLoadState(); + row.updateDynamicField("note", value); + assertSame(state, row.__internalLoadState()); assertFalse(row.__internalHasMutationLedger()); + assertFalse(row.needPersist()); assertTrue(row.__internalDynamicMutations().isEmpty()); + } + } + @Test public void restoreKnownNullCancelsOnlyThisDynamicCodeAcrossAllFrames() { + var row = loaded(true, null); row.updateDynamicField("note", "outer"); + var ledger = row.getEntityMutationLedger(); var key = new EntityKey(row.typeName(), row.getId()); + ledger.pushChangeSet(); row.updateDynamicField("note", "inner"); row.updateDynamicField("note", null); + assertEquals(DynamicFieldValue.State.NULL, row.dynamicFields().field("note").state()); + assertFalse(row.needPersist()); assertTrue(ledger.changedFieldNames(key).isEmpty()); + ledger.popChangeSet(); assertTrue(ledger.changedFieldNames(key).isEmpty()); + assertEquals(Long.valueOf(7), row.getOriginalVersion()); + } + @Test public void restorationRetainsAnotherDynamicFieldAndAnotherEntitysIntent() { + var row = loaded(true, "original"); row.updateDynamicField("note", "edit"); + row.updateDynamicField("other", "keep"); var ledger = row.getEntityMutationLedger(); + var other = new EntityKey("AnotherType", 1L); ledger.set(other, "name", "keep other type"); + row.updateDynamicField("note", "original"); + assertEquals(java.util.Set.of("other"), row.__internalDynamicMutations().keySet()); + assertEquals("keep other type", ledger.get(other, "name")); assertTrue(row.needPersist()); + } + @Test public void unknownNullCannotBeCancelledAgainstAnInventedBaseline() { + var row = loaded(false, null); row.updateDynamicField("note", "edit"); row.updateDynamicField("note", null); + assertTrue(row.needPersist()); assertTrue(row.__internalDynamicMutations().containsKey("note")); + } + @Test public void anEqualValueOnANewEntityIsStillAPersistableAssignment() { + var row = new DynamicMemberStateTest.Row(); row.__internalInitializeNewEntityId(2L); + row.setDynamicFieldValues(DynamicFieldValues.of(java.util.List.of(DynamicFieldValue.ofString("note", "same")))); + row.updateDynamicField("note", "same"); + assertTrue(row.isNew()); assertTrue(row.__internalDynamicMutations().containsKey("note")); + } + @Test public void restoringAnExtensionRetainsAFixedFieldAndDeletion() { + var row = loaded(true, "original"); row.markForDeletion(); row.updateProperty("name", "keep"); + row.updateDynamicField("note", "edit"); row.updateDynamicField("note", "original"); + assertTrue(row.isMarkedAsDelete()); assertTrue(row.needPersist()); + assertTrue(row.getUpdatedProperties().contains("name")); assertTrue(row.__internalDynamicMutations().isEmpty()); + assertEquals("keep", row.getEntityMutationLedger().get(new EntityKey(row.typeName(), row.getId()), "name")); + } + @Test public void readonlyLifecycleRejectsEvenAnEqualDynamicAssignment() { + var row = loaded(true, "same"); row.set$status(EntityStatus.REFER); + assertThrows(TeaQLRuntimeException.class, () -> row.updateDynamicField("note", "same")); + assertFalse(row.__internalHasMutationLedger()); assertTrue(row.__internalDynamicMutations().isEmpty()); + } +} From 159d1e0e036c4c7275bc5a05b61436639163e890 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Thu, 12 Nov 2026 04:44:45 +0800 Subject: [PATCH 04/47] test(checker): require Context Fix rollback on partial graph rejection (#277) --- .../GeneratedPartialGraphCheckerAcceptance.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedPartialGraphCheckerAcceptance.java b/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedPartialGraphCheckerAcceptance.java index eeba40397..ee8cf2437 100644 --- a/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedPartialGraphCheckerAcceptance.java +++ b/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedPartialGraphCheckerAcceptance.java @@ -33,6 +33,7 @@ static void verify(UserContext context, ObservedJdbcExecutor sql, String name) { .comment("what: reload partial Platform detail after the positive save") .purpose("why: mutate the materialized child rather than a readback identity reference").executeForOne(context); var child = row.getPlatform(); child.updateName("Partial child control"); + var childState = child.__internalLoadState(); var state = row.__internalLoadState(); long[] before = sql.counts(); assertThrows(CheckException.class, () -> child.auditAs("reject mutation of the incomplete referenced object").save(context)); @@ -40,9 +41,11 @@ static void verify(UserContext context, ObservedJdbcExecutor sql, String name) { assertSame(state, row.__internalLoadState()); assertFalse(row.getPlatform().isPropertyLoaded("baseUrl")); assertFalse(row.getPlatform().isPropertyLoaded("createTime")); - // The declared updateTime Fix is a real assignment and may detach the - // child's snapshot. It must not mark missing business fields loaded. - assertTrue(row.getPlatform().isPropertyLoaded("updateTime")); + // Failed validation withdraws automatic Context assignments, including + // their loaded bits, but preserves the caller's business edit. + assertSame(childState, child.__internalLoadState()); + assertFalse(child.isPropertyLoaded("updateTime")); + assertEquals("Partial child control", child.getName()); assertFalse(untouchedState.isLoaded("baseUrl")); assertFalse(untouchedState.isLoaded("updateTime")); System.out.println("PASS generated Java modified partial referenced object rejects before provider entry without loading missing business fields"); From c80ab5aac914e119fa573df8f00dca288ba66b74 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Thu, 12 Nov 2026 04:55:48 +0800 Subject: [PATCH 05/47] test(checker): align failed Context restoration without instance constraints (#277) --- .../GeneratedDynamicRollbackAcceptance.java | 9 ++++++--- .../GeneratedPartialGraphCheckerAcceptance.java | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedDynamicRollbackAcceptance.java b/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedDynamicRollbackAcceptance.java index 6647ed4e7..f00b28fc4 100644 --- a/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedDynamicRollbackAcceptance.java +++ b/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedDynamicRollbackAcceptance.java @@ -57,9 +57,12 @@ static School verify(UserContext context, ObservedJdbcExecutor sql, School origi assertThrows(CheckException.class, () -> streamed.get(0) .auditAs("reject extension mutation on an incomplete streamed object").save(context)); assertArrayEquals(beforeStreamRejection, sql.counts(), "incomplete stream mutation must reject before provider entry"); - // The declared timestamp Fix may detach only this modified row's state. - assertNotSame(streamedState, streamed.get(0).__internalLoadState()); - assertTrue(streamed.get(0).isPropertyLoaded("updateTime")); + // Failed validation withdraws automatic Context state, but preserves + // the caller's dynamic-field intent. Restored state is content-equal; + // immutable copy-on-write does not promise the original instance. + assertEquals(streamedState, streamed.get(0).__internalLoadState()); + assertFalse(streamed.get(0).isPropertyLoaded("updateTime")); + assertEquals("must-not-persist", streamed.get(0).dynamicFields().field(code).value()); assertSame(streamedState, streamed.get(1).__internalLoadState()); assertFalse(streamedState.isLoaded("updateTime")); assertFalse(streamed.get(0).isPropertyLoaded("address")); diff --git a/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedPartialGraphCheckerAcceptance.java b/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedPartialGraphCheckerAcceptance.java index ee8cf2437..2940bbfe3 100644 --- a/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedPartialGraphCheckerAcceptance.java +++ b/examples/shared-load-state/src/test/java/com/example/schoolmanagementservice/GeneratedPartialGraphCheckerAcceptance.java @@ -43,7 +43,7 @@ static void verify(UserContext context, ObservedJdbcExecutor sql, String name) { assertFalse(row.getPlatform().isPropertyLoaded("createTime")); // Failed validation withdraws automatic Context assignments, including // their loaded bits, but preserves the caller's business edit. - assertSame(childState, child.__internalLoadState()); + assertEquals(childState, child.__internalLoadState()); assertFalse(child.isPropertyLoaded("updateTime")); assertEquals("Partial child control", child.getName()); assertFalse(untouchedState.isLoaded("baseUrl")); From 5f8cdc0e38f23370409e162068421dff10577d12 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Thu, 12 Nov 2026 13:00:45 +0800 Subject: [PATCH 06/47] feat(checker): add immutable natural message catalog and location renderer (#278) Signed-off-by: Philip Z --- .../core/checker/CheckerPresentation.java | 171 +++++ .../core/i18n/CheckerMessageCatalog.java | 244 ++++++++ .../teaql/core/i18n/checker-messages-v1.json | 591 ++++++++++++++++++ .../core/i18n/CheckerMessageCatalogTest.java | 213 +++++++ .../io/teaql/core/i18n/natural-cases-v1.json | 405 ++++++++++++ 5 files changed, 1624 insertions(+) create mode 100644 teaql-core/src/main/java/io/teaql/core/checker/CheckerPresentation.java create mode 100644 teaql-core/src/main/java/io/teaql/core/i18n/CheckerMessageCatalog.java create mode 100644 teaql-core/src/main/resources/io/teaql/core/i18n/checker-messages-v1.json create mode 100644 teaql-core/src/test/java/io/teaql/core/i18n/CheckerMessageCatalogTest.java create mode 100644 teaql-core/src/test/resources/io/teaql/core/i18n/natural-cases-v1.json diff --git a/teaql-core/src/main/java/io/teaql/core/checker/CheckerPresentation.java b/teaql-core/src/main/java/io/teaql/core/checker/CheckerPresentation.java new file mode 100644 index 000000000..17db6b587 --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/checker/CheckerPresentation.java @@ -0,0 +1,171 @@ +package io.teaql.core.checker; + +import io.teaql.core.i18n.CheckerMessageCatalog; +import io.teaql.core.i18n.Locale; +import java.util.*; +import java.util.function.Consumer; + +/** Immutable model-aware presentation data; holds neither an entity graph nor a UserContext. */ +public final class CheckerPresentation { + public record Field(String name, String targetType, Map labels, + Map classifiers, Set aliases) { + public Field { + Objects.requireNonNull(name); labels = Map.copyOf(labels); + classifiers = Map.copyOf(classifiers); aliases = Set.copyOf(aliases); + if (name.isBlank()) throw new IllegalArgumentException("Empty model field identity"); + } + } + + public static final class Entity { + private final Map labels; + private final Map fields; + + public Entity(Map labels, List fields) { + this.labels = Map.copyOf(labels); + Map indexed = new HashMap<>(); + for (Field field : fields) { + bind(indexed, field.name(), field); + for (String alias : field.aliases()) bind(indexed, alias, field); + } + this.fields = Map.copyOf(indexed); + } + + private static void bind(Map indexed, String key, Field field) { + if (key.isBlank() || indexed.putIfAbsent(key, field) != null) + throw new IllegalArgumentException("Duplicate model field identity or alias"); + } + } + + /** One shared immutable index per generated model revision. */ + public record Model(String revision, Map entities, Map currentObject) { + public Model { + Objects.requireNonNull(revision); entities = Map.copyOf(entities); currentObject = Map.copyOf(currentObject); + if (!currentObject.containsKey(Locale.ENGLISH)) throw new IllegalArgumentException("Missing English current-object label"); + } + } + + private record Step(String identity, Field field, List indices) { + private Step { indices = List.copyOf(indices); } + } + + private final Model model; + private final String rootType; + private final List steps; + private final CheckerMessageCatalog.Shape shape; + + private CheckerPresentation(Model model, String rootType, List steps, CheckerMessageCatalog.Shape shape) { + this.model = model; this.rootType = rootType; this.steps = List.copyOf(steps); this.shape = shape; + } + + /** Resolve only explicit descriptor identities/aliases; never use the violation's declaring type as a guessed root. */ + public static CheckerPresentation capture(Model model, String rootType, ObjectLocation location) { + Objects.requireNonNull(model); + Entity entity = rootType == null ? null : model.entities().get(rootType); + boolean unusual = entity == null; + List steps = new ArrayList<>(); + String name = null; Field descriptor = null; List indices = new ArrayList<>(); + Deque segments = new ArrayDeque<>(); + for (ObjectLocation cursor = location; cursor != null; cursor = cursor.getParent()) { + if (cursor instanceof HashLocation hash) segments.addFirst(WireLocationSegment.property(hash.getMember())); + else if (cursor instanceof ArrayLocation array) segments.addFirst(WireLocationSegment.index(array.getIndex())); + else throw new IllegalArgumentException("Unsupported location segment"); + } + for (WireLocationSegment segment : segments) { + if ("property".equals(segment.kind())) { + if (name != null || !indices.isEmpty()) steps.add(new Step(name, descriptor, indices)); + name = segment.name(); indices = new ArrayList<>(); + descriptor = entity == null ? null : entity.fields.get(name); + entity = descriptor == null || descriptor.targetType() == null ? null : model.entities().get(descriptor.targetType()); + } else { + if (segment.index() == null || segment.index() < 0) throw new IllegalArgumentException("Invalid location index"); + indices.add(segment.index()); + if (name == null || indices.size() > 1) unusual = true; + } + } + if (name != null || !indices.isEmpty()) steps.add(new Step(name, descriptor, indices)); + if (steps.isEmpty() || !steps.get(steps.size() - 1).indices().isEmpty()) unusual = true; + var shape = unusual || steps.size() > 2 ? CheckerMessageCatalog.Shape.DEEP + : steps.size() == 1 ? CheckerMessageCatalog.Shape.ONE : CheckerMessageCatalog.Shape.TWO; + return new CheckerPresentation(model, rootType, steps, shape); + } + + public CheckerMessageCatalog.Shape shape() { return shape; } + public String modelRevision() { return model.revision(); } + + /** Pure O(path length) rendering. Constraint arguments must already have passed diagnostic projection. */ + public String render(CheckerMessageCatalog catalog, Locale locale, String rule, Map safeArguments, + Consumer warningSink) { + Objects.requireNonNull(catalog); Objects.requireNonNull(locale); Objects.requireNonNull(warningSink); + Set warnings = new HashSet<>(); + Consumer warn = code -> { + if (warnings.add(code)) try { warningSink.accept(code); } + catch (RuntimeException ignored) { /* A quality-warning adapter must not replace the validation failure. */ } + }; + var selection = catalog.select(locale, rule, shape); + Locale effective = selection.locale(); + Map args = new HashMap<>(); + for (String key : List.of("system", "input", "input_len", "unit")) + if (safeArguments.containsKey(key)) args.put(key, safeArguments.get(key)); + String root = rootLabel(effective, warn); + Step leaf = steps.isEmpty() ? null : steps.get(steps.size() - 1); + args.put("field", leaf == null || leaf.identity() == null ? root : label(leaf, effective, warn)); + List owners = new ArrayList<>(); + int ownerCount = steps.size() - (leaf != null && leaf.identity() != null && leaf.indices().isEmpty() ? 1 : 0); + for (int i = 0; i < ownerCount; i++) { + Step step = steps.get(i); + String relation = step.identity() == null ? root : label(step, effective, warn); + if (step.indices().isEmpty()) owners.add(catalog.reference(effective, relation)); + else for (int j = 0; j < step.indices().size(); j++) { + // Multiple selectors stay separate and visible rather than losing an index. + String itemLabel = j == 0 ? relation : currentLabel(effective, warn); + String classifier = step.field() == null ? defaultClassifier(effective) + : step.field().classifiers().getOrDefault(effective, defaultClassifier(effective)); + owners.add(catalog.item(effective, itemLabel, step.indices().get(j), sanitize(classifier))); + } + } + args.put("object", owners.isEmpty() ? root : owners.get(0)); + args.put("objectPath", owners.isEmpty() ? root : String.join(catalog.separator(effective), owners)); + return selection.render(args); + } + + private String rootLabel(Locale locale, Consumer warn) { + Entity entity = rootType == null ? null : model.entities().get(rootType); + return entity == null ? currentLabel(locale, warn) : vocabulary(entity.labels, locale, rootType, warn); + } + + private String currentLabel(Locale locale, Consumer warn) { + return vocabulary(model.currentObject(), locale, "current object", warn); + } + + private static String label(Step step, Locale locale, Consumer warn) { + return vocabulary(step.field() == null ? Map.of() : step.field().labels(), locale, + step.field() == null ? step.identity() : step.field().name(), warn); + } + + private static String vocabulary(Map labels, Locale locale, String identity, Consumer warn) { + String label = labels.get(locale); + if (label == null || label.isBlank()) { + warn.accept("CHECKER_MESSAGE_LABEL_FALLBACK"); + label = labels.get(Locale.ENGLISH); + } + if (label == null || label.isBlank()) label = identity == null ? "current object" : identity.replace('_', ' '); + String safe = sanitize(label); + if (safe.isBlank()) { + warn.accept("CHECKER_MESSAGE_LABEL_FALLBACK"); + safe = sanitize(identity == null ? "current object" : identity.replace('_', ' ')); + if (safe.isBlank()) safe = "current object"; + } + return safe; + } + + private static String sanitize(String label) { + // Control characters and bidi overrides cannot forge a path or a new diagnostic line. + StringBuilder safe = new StringBuilder(); + label.codePoints().forEach(c -> safe.appendCodePoint(Character.isISOControl(c) || Character.getType(c) == Character.FORMAT ? ' ' : c)); + return safe.toString().strip(); + } + + private static String defaultClassifier(Locale locale) { + return locale == Locale.CHINESE_SIMPLIFIED || locale == Locale.CHINESE_TRADITIONAL ? "项" : ""; + } +} diff --git a/teaql-core/src/main/java/io/teaql/core/i18n/CheckerMessageCatalog.java b/teaql-core/src/main/java/io/teaql/core/i18n/CheckerMessageCatalog.java new file mode 100644 index 000000000..2548e581f --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/i18n/CheckerMessageCatalog.java @@ -0,0 +1,244 @@ +package io.teaql.core.i18n; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +/** Immutable, data-only natural message resources. Does not change the legacy i18n schema. */ +public final class CheckerMessageCatalog { + public enum Shape { ONE, TWO, DEEP } + + private record Node(String literal, String argument) {} + + /** A compiled template interpolates once; inserted strings are never parsed as instructions. */ + public static final class Template { + private final List nodes; + + private Template(List nodes) { this.nodes = List.copyOf(nodes); } + + public String render(Map arguments) { + StringBuilder output = new StringBuilder(); + for (Node node : nodes) { + if (node.argument() == null) output.append(node.literal()); + else { + Object value = arguments.get(node.argument()); + if (value == null) throw invalid("Missing template argument"); + Class type = value.getClass(); + if (!(value instanceof String) && type != Integer.class && type != Long.class + && type != Short.class && type != Byte.class && type != Double.class && type != Float.class + && type != java.math.BigDecimal.class && type != java.math.BigInteger.class) + throw invalid("Template arguments must be projected scalar data"); + output.append(value); + } + } + return output.toString(); + } + } + + public record Selection(Template template, Locale locale) { + public Selection { Objects.requireNonNull(template); Objects.requireNonNull(locale); } + public String render(Map arguments) { return template.render(arguments); } + } + + private record Messages(Map> rules, Map patterns, String separator) {} + private static final Set CONSTRAINT_ARGS = Set.of("field", "system", "input", "input_len", "unit"); + private static final Set CORE_RULES = Set.of("checker.required", "checker.min", "checker.max", "checker.minLength", "checker.maxLength", "checker.invalid"); + private static final CheckerMessageCatalog BUILTIN = loadBuiltin(); + private final Map locales; + private final boolean builtin; + + private CheckerMessageCatalog(Map locales, boolean builtin) { + this.locales = Map.copyOf(locales); this.builtin = builtin; + } + + public static CheckerMessageCatalog builtin() { return BUILTIN; } + + /** Parse and validate completely before returning. A failed load cannot replace an active catalog. */ + public static CheckerMessageCatalog fromJson(InputStream input) { return load(input, false); } + + private static CheckerMessageCatalog load(InputStream input, boolean builtin) { + Objects.requireNonNull(input, "input"); + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION); + mapper.enable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + JsonNode root = mapper.readTree(input); + object(root, Set.of("schema", "defaultLocale", "locales")); + if (!"teaql.checker-messages/v1".equals(text(root.get("schema"))) || !"en".equals(text(root.get("defaultLocale")))) + throw invalid("Unsupported Checker message schema or default Locale"); + JsonNode entries = root.get("locales"); + if (entries == null || !entries.isObject() || entries.isEmpty()) throw invalid("Missing locales"); + Map locales = new EnumMap<>(Locale.class); + Iterator> iterator = entries.fields(); + while (iterator.hasNext()) { + var entry = iterator.next(); + Locale locale = Locale.fromCode(entry.getKey()); + if (locales.containsKey(locale)) throw invalid("Duplicate normalized Locale"); + JsonNode data = entry.getValue(); + object(data, Set.of("rules", "locationPatterns")); + if (data.isEmpty()) throw invalid("Empty Locale entry"); + Map> rules = new HashMap<>(); + JsonNode sourceRules = data.get("rules"); + if (sourceRules != null) { + if (!sourceRules.isObject() || sourceRules.isEmpty()) throw invalid("Empty rules"); + var ruleIterator = sourceRules.fields(); + while (ruleIterator.hasNext()) { + var rule = ruleIterator.next(); + if (!rule.getKey().matches("checker\\.[A-Za-z][A-Za-z0-9_.-]*")) throw invalid("Invalid rule key"); + object(rule.getValue(), Set.of("one", "two", "deep")); + if (rule.getValue().isEmpty()) throw invalid("Empty rule override"); + Map shapes = new EnumMap<>(Shape.class); + for (Shape shape : Shape.values()) { + JsonNode source = rule.getValue().get(shape.name().toLowerCase(java.util.Locale.ROOT)); + if (source == null) continue; + Set allowed = new HashSet<>(CONSTRAINT_ARGS); + if (rule.getKey().equals("checker.required") || rule.getKey().equals("checker.invalid")) + allowed.retainAll(Set.of("field")); + if (rule.getKey().equals("checker.min") || rule.getKey().equals("checker.max")) + allowed.retainAll(Set.of("field", "system", "input")); + Set required = new HashSet<>(Set.of("field")); + if (shape != Shape.ONE) { + String owner = shape == Shape.TWO ? "object" : "objectPath"; + allowed.add(owner); required.add(owner); + } + if (rule.getKey().equals("checker.min") || rule.getKey().equals("checker.max")) required.add("system"); + if (rule.getKey().equals("checker.minLength") || rule.getKey().equals("checker.maxLength")) { + required.addAll(Set.of("system", "input_len", "unit")); allowed.remove("input"); + } + shapes.put(shape, compile(text(source), allowed, required)); + } + rules.put(rule.getKey(), Map.copyOf(shapes)); + } + } + Map patterns = new HashMap<>(); + String separator = null; + JsonNode location = data.get("locationPatterns"); + if (location != null) { + object(location, Set.of("reference", "item", "separator")); + if (location.isEmpty()) throw invalid("Empty location override"); + if (location.has("reference")) patterns.put("reference", compile(text(location.get("reference")), Set.of("relation"), Set.of("relation"))); + if (location.has("item")) { + String source = text(location.get("item")); + Template compiled = compile(source, Set.of("relation", "position", "ordinal", "classifier"), Set.of("relation")); + if (compiled.nodes.stream().noneMatch(node -> "position".equals(node.argument()) || "ordinal".equals(node.argument()))) + throw invalid("Collection pattern must identify position"); + patterns.put("item", compiled); + } + if (location.has("separator")) { + separator = text(location.get("separator")); + if (separator.isEmpty() || separator.chars().anyMatch(c -> c == '{' || c == '}' || Character.isISOControl(c))) + throw invalid("Invalid location separator"); + } + } + if (builtin && (!rules.keySet().equals(CORE_RULES) + || rules.values().stream().anyMatch(shapes -> shapes.size() != Shape.values().length) + || patterns.size() != 2 || separator == null)) throw invalid("Incomplete built-in Locale"); + locales.put(locale, new Messages(Map.copyOf(rules), Map.copyOf(patterns), separator)); + } + if (builtin && locales.size() != Locale.values().length) throw invalid("Incomplete built-in Locale set"); + return new CheckerMessageCatalog(locales, builtin); + } catch (IOException exception) { + // Parser excerpts can contain a secret embedded in a malformed resource. + throw invalid("Invalid Checker message JSON"); + } + } + + /** Explicit override only: used to compose shape overrides ahead of legacy application text. */ + public Selection override(Locale locale, String rule, Shape shape) { + if (builtin) return null; + Template value = exact(locale, rule, shape); + return value == null ? null : new Selection(value, locale); + } + + /** Resolve template Locale first; callers must use it when rendering owner grammar. */ + public Selection select(Locale locale, String rule, Shape shape) { + Objects.requireNonNull(locale); Objects.requireNonNull(rule); Objects.requireNonNull(shape); + for (Locale candidate : locale == Locale.ENGLISH ? List.of(locale) : List.of(locale, Locale.ENGLISH)) { + Template value = exact(candidate, rule, shape); + if (value == null && !builtin) value = BUILTIN.exact(candidate, rule, shape); + if (value != null) return new Selection(value, candidate); + } + Template generic = BUILTIN.exact(locale, "checker.invalid", shape); + return new Selection(generic, locale); + } + + public String reference(Locale locale, String relation) { + return pattern(locale, "reference").render(Map.of("relation", relation)); + } + + public String item(Locale locale, String relation, int index, String classifier) { + if (index < 0) throw invalid("Negative collection index"); + long position = (long) index + 1; + return pattern(locale, "item").render(Map.of("relation", relation, "position", position, + "ordinal", englishOrdinal(position), "classifier", classifier)); + } + + public String separator(Locale locale) { + Messages entry = locales.get(locale); + return entry != null && entry.separator() != null ? entry.separator() : BUILTIN.locales.get(locale).separator(); + } + + private Template exact(Locale locale, String rule, Shape shape) { + Messages entry = locales.get(locale); + return entry == null ? null : entry.rules().getOrDefault(rule, Map.of()).get(shape); + } + + private Template pattern(Locale locale, String key) { + Messages entry = locales.get(locale); + Template value = entry == null ? null : entry.patterns().get(key); + return value != null ? value : BUILTIN.locales.get(locale).patterns().get(key); + } + + public static String englishOrdinal(long position) { + if (position < 1) throw invalid("Position must be positive"); + long last = position % 100; + String suffix = last >= 11 && last <= 13 ? "th" : switch ((int) (position % 10)) { + case 1 -> "st"; case 2 -> "nd"; case 3 -> "rd"; default -> "th"; + }; + return position + suffix; + } + + private static Template compile(String source, Set allowed, Set required) { + if (source.isBlank()) throw invalid("Empty template"); + List nodes = new ArrayList<>(); Set seen = new HashSet<>(); StringBuilder literal = new StringBuilder(); + for (int i = 0; i < source.length();) { + char c = source.charAt(i); + if ((c == '{' || c == '}') && i + 1 < source.length() && source.charAt(i + 1) == c) { + literal.append(c); i += 2; continue; + } + if (c == '}') throw invalid("Unmatched closing brace"); + if (c != '{') { literal.append(c); i++; continue; } + int end = source.indexOf('}', i + 1); + if (end < 0) throw invalid("Unclosed placeholder"); + String name = source.substring(i + 1, end); + if (!allowed.contains(name)) throw invalid("Unknown template argument"); + if (!literal.isEmpty()) { nodes.add(new Node(literal.toString(), null)); literal.setLength(0); } + nodes.add(new Node(null, name)); seen.add(name); i = end + 1; + } + if (!literal.isEmpty()) nodes.add(new Node(literal.toString(), null)); + if (!seen.containsAll(required)) throw invalid("Missing required template arguments"); + return new Template(nodes); + } + + private static void object(JsonNode node, Set allowed) { + if (node == null || !node.isObject()) throw invalid("Expected object"); + node.fieldNames().forEachRemaining(name -> { if (!allowed.contains(name)) throw invalid("Unknown catalog property"); }); + } + + private static String text(JsonNode node) { + if (node == null || !node.isTextual()) throw invalid("Expected text"); + return node.textValue(); + } + + private static IllegalArgumentException invalid(String message) { return new IllegalArgumentException(message); } + + private static CheckerMessageCatalog loadBuiltin() { + try (InputStream input = CheckerMessageCatalog.class.getResourceAsStream("checker-messages-v1.json")) { + if (input == null) throw new ExceptionInInitializerError("Missing natural Checker message catalog"); + return load(input, true); + } catch (IOException exception) { throw new ExceptionInInitializerError("Cannot close natural Checker catalog"); } + } +} diff --git a/teaql-core/src/main/resources/io/teaql/core/i18n/checker-messages-v1.json b/teaql-core/src/main/resources/io/teaql/core/i18n/checker-messages-v1.json new file mode 100644 index 000000000..ee87185a5 --- /dev/null +++ b/teaql-core/src/main/resources/io/teaql/core/i18n/checker-messages-v1.json @@ -0,0 +1,591 @@ +{ + "schema": "teaql.checker-messages/v1", + "defaultLocale": "en", + "locales": { + "en": { + "rules": { + "checker.required": { + "one": "The {field} is required.", + "two": "The {field} of {object} is required.", + "deep": "The {field} is required.\nLocation: {objectPath}" + }, + "checker.min": { + "one": "The {field} must be at least {system}.", + "two": "The {field} of {object} must be at least {system}.", + "deep": "The {field} must be at least {system}.\nLocation: {objectPath}" + }, + "checker.max": { + "one": "The {field} must not exceed {system}.", + "two": "The {field} of {object} must not exceed {system}.", + "deep": "The {field} must not exceed {system}.\nLocation: {objectPath}" + }, + "checker.minLength": { + "one": "The {field} must contain at least {system} {unit}; its current length is {input_len}.", + "two": "The {field} of {object} must contain at least {system} {unit}; its current length is {input_len}.", + "deep": "The {field} must contain at least {system} {unit}; its current length is {input_len}.\nLocation: {objectPath}" + }, + "checker.maxLength": { + "one": "The {field} must not exceed {system} {unit}; its current length is {input_len}.", + "two": "The {field} of {object} must not exceed {system} {unit}; its current length is {input_len}.", + "deep": "The {field} must not exceed {system} {unit}; its current length is {input_len}.\nLocation: {objectPath}" + }, + "checker.invalid": { + "one": "The {field} is invalid.", + "two": "The {field} of {object} is invalid.", + "deep": "The {field} is invalid.\nLocation: {objectPath}" + } + }, + "locationPatterns": { + "reference": "the {relation}", + "item": "the {ordinal} {relation}", + "separator": " → " + } + }, + "zh-CN": { + "rules": { + "checker.required": { + "one": "请填写{field}。", + "two": "请填写{object}的{field}。", + "deep": "请填写{field}。\n位置:{objectPath}" + }, + "checker.min": { + "one": "{field}不得小于{system}。", + "two": "{object}的{field}不得小于{system}。", + "deep": "{field}不得小于{system}。\n位置:{objectPath}" + }, + "checker.max": { + "one": "{field}不得大于{system}。", + "two": "{object}的{field}不得大于{system}。", + "deep": "{field}不得大于{system}。\n位置:{objectPath}" + }, + "checker.minLength": { + "one": "{field}至少需要{system}{unit},当前长度为{input_len}。", + "two": "{object}的{field}至少需要{system}{unit},当前长度为{input_len}。", + "deep": "{field}至少需要{system}{unit},当前长度为{input_len}。\n位置:{objectPath}" + }, + "checker.maxLength": { + "one": "{field}最多允许{system}{unit},当前长度为{input_len}。", + "two": "{object}的{field}最多允许{system}{unit},当前长度为{input_len}。", + "deep": "{field}最多允许{system}{unit},当前长度为{input_len}。\n位置:{objectPath}" + }, + "checker.invalid": { + "one": "{field}无效。", + "two": "{object}的{field}无效。", + "deep": "{field}无效。\n位置:{objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "第{position}{classifier}{relation}", + "separator": " → " + } + }, + "zh-TW": { + "rules": { + "checker.required": { + "one": "請填寫{field}。", + "two": "請填寫{object}的{field}。", + "deep": "請填寫{field}。\n位置:{objectPath}" + }, + "checker.min": { + "one": "{field}不得小於{system}。", + "two": "{object}的{field}不得小於{system}。", + "deep": "{field}不得小於{system}。\n位置:{objectPath}" + }, + "checker.max": { + "one": "{field}不得大於{system}。", + "two": "{object}的{field}不得大於{system}。", + "deep": "{field}不得大於{system}。\n位置:{objectPath}" + }, + "checker.minLength": { + "one": "{field}至少需要{system}{unit},目前長度為{input_len}。", + "two": "{object}的{field}至少需要{system}{unit},目前長度為{input_len}。", + "deep": "{field}至少需要{system}{unit},目前長度為{input_len}。\n位置:{objectPath}" + }, + "checker.maxLength": { + "one": "{field}最多允許{system}{unit},目前長度為{input_len}。", + "two": "{object}的{field}最多允許{system}{unit},目前長度為{input_len}。", + "deep": "{field}最多允許{system}{unit},目前長度為{input_len}。\n位置:{objectPath}" + }, + "checker.invalid": { + "one": "{field}無效。", + "two": "{object}的{field}無效。", + "deep": "{field}無效。\n位置:{objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "第{position}{classifier}{relation}", + "separator": " → " + } + }, + "ja": { + "rules": { + "checker.required": { + "one": "{field}は必須です。", + "two": "{object}の{field}は必須です。", + "deep": "{field}は必須です。\n場所: {objectPath}" + }, + "checker.min": { + "one": "{field}は{system}以上である必要があります。", + "two": "{object}の{field}は{system}以上である必要があります。", + "deep": "{field}は{system}以上である必要があります。\n場所: {objectPath}" + }, + "checker.max": { + "one": "{field}は{system}以下である必要があります。", + "two": "{object}の{field}は{system}以下である必要があります。", + "deep": "{field}は{system}以下である必要があります。\n場所: {objectPath}" + }, + "checker.minLength": { + "one": "{field}には少なくとも{system}{unit}が必要です。現在の長さは{input_len}です。", + "two": "{object}の{field}には少なくとも{system}{unit}が必要です。現在の長さは{input_len}です。", + "deep": "{field}には少なくとも{system}{unit}が必要です。現在の長さは{input_len}です。\n場所: {objectPath}" + }, + "checker.maxLength": { + "one": "{field}は最大{system}{unit}です。現在の長さは{input_len}です。", + "two": "{object}の{field}は最大{system}{unit}です。現在の長さは{input_len}です。", + "deep": "{field}は最大{system}{unit}です。現在の長さは{input_len}です。\n場所: {objectPath}" + }, + "checker.invalid": { + "one": "{field}が無効です。", + "two": "{object}の{field}が無効です。", + "deep": "{field}が無効です。\n場所: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{position}番目の{relation}", + "separator": " → " + } + }, + "ko": { + "rules": { + "checker.required": { + "one": "{field} 항목은 필수입니다.", + "two": "{object}의 {field} 항목은 필수입니다.", + "deep": "{field} 항목은 필수입니다.\n위치: {objectPath}" + }, + "checker.min": { + "one": "{field} 값은 {system} 이상이어야 합니다.", + "two": "{object}의 {field} 값은 {system} 이상이어야 합니다.", + "deep": "{field} 값은 {system} 이상이어야 합니다.\n위치: {objectPath}" + }, + "checker.max": { + "one": "{field} 값은 {system} 이하여야 합니다.", + "two": "{object}의 {field} 값은 {system} 이하여야 합니다.", + "deep": "{field} 값은 {system} 이하여야 합니다.\n위치: {objectPath}" + }, + "checker.minLength": { + "one": "{field} 길이는 최소 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.", + "two": "{object}의 {field} 길이는 최소 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.", + "deep": "{field} 길이는 최소 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.\n위치: {objectPath}" + }, + "checker.maxLength": { + "one": "{field} 길이는 최대 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.", + "two": "{object}의 {field} 길이는 최대 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.", + "deep": "{field} 길이는 최대 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.\n위치: {objectPath}" + }, + "checker.invalid": { + "one": "{field} 항목이 유효하지 않습니다.", + "two": "{object}의 {field} 항목이 유효하지 않습니다.", + "deep": "{field} 항목이 유효하지 않습니다.\n위치: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{position}번째 {relation}", + "separator": " → " + } + }, + "de": { + "rules": { + "checker.required": { + "one": "Das Feld {field} ist erforderlich.", + "two": "Das Feld {field} bei {object} ist erforderlich.", + "deep": "Das Feld {field} ist erforderlich.\nPosition: {objectPath}" + }, + "checker.min": { + "one": "Das Feld {field} muss mindestens {system} betragen.", + "two": "Das Feld {field} bei {object} muss mindestens {system} betragen.", + "deep": "Das Feld {field} muss mindestens {system} betragen.\nPosition: {objectPath}" + }, + "checker.max": { + "one": "Das Feld {field} darf höchstens {system} betragen.", + "two": "Das Feld {field} bei {object} darf höchstens {system} betragen.", + "deep": "Das Feld {field} darf höchstens {system} betragen.\nPosition: {objectPath}" + }, + "checker.minLength": { + "one": "Das Feld {field} muss mindestens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.", + "two": "Das Feld {field} bei {object} muss mindestens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.", + "deep": "Das Feld {field} muss mindestens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.\nPosition: {objectPath}" + }, + "checker.maxLength": { + "one": "Das Feld {field} darf höchstens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.", + "two": "Das Feld {field} bei {object} darf höchstens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.", + "deep": "Das Feld {field} darf höchstens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.\nPosition: {objectPath}" + }, + "checker.invalid": { + "one": "Das Feld {field} ist ungültig.", + "two": "Das Feld {field} bei {object} ist ungültig.", + "deep": "Das Feld {field} ist ungültig.\nPosition: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{relation} Nr. {position}", + "separator": " → " + } + }, + "fr": { + "rules": { + "checker.required": { + "one": "Le champ {field} est obligatoire.", + "two": "Le champ {field} de {object} est obligatoire.", + "deep": "Le champ {field} est obligatoire.\nEmplacement: {objectPath}" + }, + "checker.min": { + "one": "Le champ {field} doit être au moins égal à {system}.", + "two": "Le champ {field} de {object} doit être au moins égal à {system}.", + "deep": "Le champ {field} doit être au moins égal à {system}.\nEmplacement: {objectPath}" + }, + "checker.max": { + "one": "Le champ {field} ne doit pas dépasser {system}.", + "two": "Le champ {field} de {object} ne doit pas dépasser {system}.", + "deep": "Le champ {field} ne doit pas dépasser {system}.\nEmplacement: {objectPath}" + }, + "checker.minLength": { + "one": "Le champ {field} doit contenir au moins {system} {unit} ; sa longueur actuelle est {input_len}.", + "two": "Le champ {field} de {object} doit contenir au moins {system} {unit} ; sa longueur actuelle est {input_len}.", + "deep": "Le champ {field} doit contenir au moins {system} {unit} ; sa longueur actuelle est {input_len}.\nEmplacement: {objectPath}" + }, + "checker.maxLength": { + "one": "Le champ {field} ne doit pas dépasser {system} {unit} ; sa longueur actuelle est {input_len}.", + "two": "Le champ {field} de {object} ne doit pas dépasser {system} {unit} ; sa longueur actuelle est {input_len}.", + "deep": "Le champ {field} ne doit pas dépasser {system} {unit} ; sa longueur actuelle est {input_len}.\nEmplacement: {objectPath}" + }, + "checker.invalid": { + "one": "Le champ {field} est invalide.", + "two": "Le champ {field} de {object} est invalide.", + "deep": "Le champ {field} est invalide.\nEmplacement: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{relation} n° {position}", + "separator": " → " + } + }, + "es": { + "rules": { + "checker.required": { + "one": "El campo {field} es obligatorio.", + "two": "El campo {field} de {object} es obligatorio.", + "deep": "El campo {field} es obligatorio.\nUbicación: {objectPath}" + }, + "checker.min": { + "one": "El campo {field} debe ser al menos {system}.", + "two": "El campo {field} de {object} debe ser al menos {system}.", + "deep": "El campo {field} debe ser al menos {system}.\nUbicación: {objectPath}" + }, + "checker.max": { + "one": "El campo {field} no debe superar {system}.", + "two": "El campo {field} de {object} no debe superar {system}.", + "deep": "El campo {field} no debe superar {system}.\nUbicación: {objectPath}" + }, + "checker.minLength": { + "one": "El campo {field} debe contener al menos {system} {unit}; su longitud actual es {input_len}.", + "two": "El campo {field} de {object} debe contener al menos {system} {unit}; su longitud actual es {input_len}.", + "deep": "El campo {field} debe contener al menos {system} {unit}; su longitud actual es {input_len}.\nUbicación: {objectPath}" + }, + "checker.maxLength": { + "one": "El campo {field} no debe superar {system} {unit}; su longitud actual es {input_len}.", + "two": "El campo {field} de {object} no debe superar {system} {unit}; su longitud actual es {input_len}.", + "deep": "El campo {field} no debe superar {system} {unit}; su longitud actual es {input_len}.\nUbicación: {objectPath}" + }, + "checker.invalid": { + "one": "El campo {field} no es válido.", + "two": "El campo {field} de {object} no es válido.", + "deep": "El campo {field} no es válido.\nUbicación: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{relation} n.º {position}", + "separator": " → " + } + }, + "pt": { + "rules": { + "checker.required": { + "one": "O campo {field} é obrigatório.", + "two": "O campo {field} de {object} é obrigatório.", + "deep": "O campo {field} é obrigatório.\nLocalização: {objectPath}" + }, + "checker.min": { + "one": "O campo {field} deve ser pelo menos {system}.", + "two": "O campo {field} de {object} deve ser pelo menos {system}.", + "deep": "O campo {field} deve ser pelo menos {system}.\nLocalização: {objectPath}" + }, + "checker.max": { + "one": "O campo {field} não deve exceder {system}.", + "two": "O campo {field} de {object} não deve exceder {system}.", + "deep": "O campo {field} não deve exceder {system}.\nLocalização: {objectPath}" + }, + "checker.minLength": { + "one": "O campo {field} deve conter pelo menos {system} {unit}; o comprimento atual é {input_len}.", + "two": "O campo {field} de {object} deve conter pelo menos {system} {unit}; o comprimento atual é {input_len}.", + "deep": "O campo {field} deve conter pelo menos {system} {unit}; o comprimento atual é {input_len}.\nLocalização: {objectPath}" + }, + "checker.maxLength": { + "one": "O campo {field} não deve exceder {system} {unit}; o comprimento atual é {input_len}.", + "two": "O campo {field} de {object} não deve exceder {system} {unit}; o comprimento atual é {input_len}.", + "deep": "O campo {field} não deve exceder {system} {unit}; o comprimento atual é {input_len}.\nLocalização: {objectPath}" + }, + "checker.invalid": { + "one": "O campo {field} é inválido.", + "two": "O campo {field} de {object} é inválido.", + "deep": "O campo {field} é inválido.\nLocalização: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{relation} n.º {position}", + "separator": " → " + } + }, + "ar": { + "rules": { + "checker.required": { + "one": "الحقل {field} مطلوب.", + "two": "الحقل {field} في {object} مطلوب.", + "deep": "الحقل {field} مطلوب.\nالموقع: {objectPath}" + }, + "checker.min": { + "one": "يجب ألا تقل قيمة الحقل {field} عن {system}.", + "two": "يجب ألا تقل قيمة الحقل {field} في {object} عن {system}.", + "deep": "يجب ألا تقل قيمة الحقل {field} عن {system}.\nالموقع: {objectPath}" + }, + "checker.max": { + "one": "يجب ألا تزيد قيمة الحقل {field} عن {system}.", + "two": "يجب ألا تزيد قيمة الحقل {field} في {object} عن {system}.", + "deep": "يجب ألا تزيد قيمة الحقل {field} عن {system}.\nالموقع: {objectPath}" + }, + "checker.minLength": { + "one": "يجب ألا يقل طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.", + "two": "يجب ألا يقل طول الحقل {field} في {object} عن {system} {unit}؛ الطول الحالي هو {input_len}.", + "deep": "يجب ألا يقل طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.\nالموقع: {objectPath}" + }, + "checker.maxLength": { + "one": "يجب ألا يزيد طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.", + "two": "يجب ألا يزيد طول الحقل {field} في {object} عن {system} {unit}؛ الطول الحالي هو {input_len}.", + "deep": "يجب ألا يزيد طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.\nالموقع: {objectPath}" + }, + "checker.invalid": { + "one": "الحقل {field} غير صالح.", + "two": "الحقل {field} في {object} غير صالح.", + "deep": "الحقل {field} غير صالح.\nالموقع: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{relation} رقم {position}", + "separator": " → " + } + }, + "th": { + "rules": { + "checker.required": { + "one": "ต้องระบุ{field}", + "two": "ต้องระบุ{field}ของ{object}", + "deep": "ต้องระบุ{field}\nตำแหน่ง: {objectPath}" + }, + "checker.min": { + "one": "{field}ต้องมีค่าอย่างน้อย {system}", + "two": "{field}ของ{object}ต้องมีค่าอย่างน้อย {system}", + "deep": "{field}ต้องมีค่าอย่างน้อย {system}\nตำแหน่ง: {objectPath}" + }, + "checker.max": { + "one": "{field}ต้องมีค่าไม่เกิน {system}", + "two": "{field}ของ{object}ต้องมีค่าไม่เกิน {system}", + "deep": "{field}ต้องมีค่าไม่เกิน {system}\nตำแหน่ง: {objectPath}" + }, + "checker.minLength": { + "one": "{field}ต้องมีความยาวอย่างน้อย {system} {unit} ความยาวปัจจุบันคือ {input_len}", + "two": "{field}ของ{object}ต้องมีความยาวอย่างน้อย {system} {unit} ความยาวปัจจุบันคือ {input_len}", + "deep": "{field}ต้องมีความยาวอย่างน้อย {system} {unit} ความยาวปัจจุบันคือ {input_len}\nตำแหน่ง: {objectPath}" + }, + "checker.maxLength": { + "one": "{field}ต้องมีความยาวไม่เกิน {system} {unit} ความยาวปัจจุบันคือ {input_len}", + "two": "{field}ของ{object}ต้องมีความยาวไม่เกิน {system} {unit} ความยาวปัจจุบันคือ {input_len}", + "deep": "{field}ต้องมีความยาวไม่เกิน {system} {unit} ความยาวปัจจุบันคือ {input_len}\nตำแหน่ง: {objectPath}" + }, + "checker.invalid": { + "one": "{field}ไม่ถูกต้อง", + "two": "{field}ของ{object}ไม่ถูกต้อง", + "deep": "{field}ไม่ถูกต้อง\nตำแหน่ง: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{relation}ลำดับที่ {position}", + "separator": " → " + } + }, + "id": { + "rules": { + "checker.required": { + "one": "Kolom {field} wajib diisi.", + "two": "Kolom {field} pada {object} wajib diisi.", + "deep": "Kolom {field} wajib diisi.\nLokasi: {objectPath}" + }, + "checker.min": { + "one": "Nilai {field} minimal {system}.", + "two": "Nilai {field} pada {object} minimal {system}.", + "deep": "Nilai {field} minimal {system}.\nLokasi: {objectPath}" + }, + "checker.max": { + "one": "Nilai {field} maksimal {system}.", + "two": "Nilai {field} pada {object} maksimal {system}.", + "deep": "Nilai {field} maksimal {system}.\nLokasi: {objectPath}" + }, + "checker.minLength": { + "one": "Panjang {field} minimal {system} {unit}; panjang saat ini {input_len}.", + "two": "Panjang {field} pada {object} minimal {system} {unit}; panjang saat ini {input_len}.", + "deep": "Panjang {field} minimal {system} {unit}; panjang saat ini {input_len}.\nLokasi: {objectPath}" + }, + "checker.maxLength": { + "one": "Panjang {field} maksimal {system} {unit}; panjang saat ini {input_len}.", + "two": "Panjang {field} pada {object} maksimal {system} {unit}; panjang saat ini {input_len}.", + "deep": "Panjang {field} maksimal {system} {unit}; panjang saat ini {input_len}.\nLokasi: {objectPath}" + }, + "checker.invalid": { + "one": "Kolom {field} tidak valid.", + "two": "Kolom {field} pada {object} tidak valid.", + "deep": "Kolom {field} tidak valid.\nLokasi: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{relation} ke-{position}", + "separator": " → " + } + }, + "fil": { + "rules": { + "checker.required": { + "one": "Kinakailangan ang {field}.", + "two": "Kinakailangan ang {field} ng {object}.", + "deep": "Kinakailangan ang {field}.\nLokasyon: {objectPath}" + }, + "checker.min": { + "one": "Ang {field} ay dapat hindi bababa sa {system}.", + "two": "Ang {field} ng {object} ay dapat hindi bababa sa {system}.", + "deep": "Ang {field} ay dapat hindi bababa sa {system}.\nLokasyon: {objectPath}" + }, + "checker.max": { + "one": "Ang {field} ay dapat hindi lumampas sa {system}.", + "two": "Ang {field} ng {object} ay dapat hindi lumampas sa {system}.", + "deep": "Ang {field} ay dapat hindi lumampas sa {system}.\nLokasyon: {objectPath}" + }, + "checker.minLength": { + "one": "Ang {field} ay dapat may hindi bababa sa {system} {unit}; ang kasalukuyang haba ay {input_len}.", + "two": "Ang {field} ng {object} ay dapat may hindi bababa sa {system} {unit}; ang kasalukuyang haba ay {input_len}.", + "deep": "Ang {field} ay dapat may hindi bababa sa {system} {unit}; ang kasalukuyang haba ay {input_len}.\nLokasyon: {objectPath}" + }, + "checker.maxLength": { + "one": "Ang {field} ay dapat may hindi hihigit sa {system} {unit}; ang kasalukuyang haba ay {input_len}.", + "two": "Ang {field} ng {object} ay dapat may hindi hihigit sa {system} {unit}; ang kasalukuyang haba ay {input_len}.", + "deep": "Ang {field} ay dapat may hindi hihigit sa {system} {unit}; ang kasalukuyang haba ay {input_len}.\nLokasyon: {objectPath}" + }, + "checker.invalid": { + "one": "Hindi wasto ang {field}.", + "two": "Hindi wasto ang {field} ng {object}.", + "deep": "Hindi wasto ang {field}.\nLokasyon: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{relation} bilang {position}", + "separator": " → " + } + }, + "uk": { + "rules": { + "checker.required": { + "one": "Поле {field} є обов’язковим.", + "two": "Поле {field} для {object} є обов’язковим.", + "deep": "Поле {field} є обов’язковим.\nРозташування: {objectPath}" + }, + "checker.min": { + "one": "Значення поля {field} має бути не менше {system}.", + "two": "Значення поля {field} для {object} має бути не менше {system}.", + "deep": "Значення поля {field} має бути не менше {system}.\nРозташування: {objectPath}" + }, + "checker.max": { + "one": "Значення поля {field} має бути не більше {system}.", + "two": "Значення поля {field} для {object} має бути не більше {system}.", + "deep": "Значення поля {field} має бути не більше {system}.\nРозташування: {objectPath}" + }, + "checker.minLength": { + "one": "Поле {field} має містити щонайменше {system} {unit}; поточна довжина — {input_len}.", + "two": "Поле {field} для {object} має містити щонайменше {system} {unit}; поточна довжина — {input_len}.", + "deep": "Поле {field} має містити щонайменше {system} {unit}; поточна довжина — {input_len}.\nРозташування: {objectPath}" + }, + "checker.maxLength": { + "one": "Поле {field} має містити не більше {system} {unit}; поточна довжина — {input_len}.", + "two": "Поле {field} для {object} має містити не більше {system} {unit}; поточна довжина — {input_len}.", + "deep": "Поле {field} має містити не більше {system} {unit}; поточна довжина — {input_len}.\nРозташування: {objectPath}" + }, + "checker.invalid": { + "one": "Поле {field} є недійсним.", + "two": "Поле {field} для {object} є недійсним.", + "deep": "Поле {field} є недійсним.\nРозташування: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{relation} № {position}", + "separator": " → " + } + }, + "vi": { + "rules": { + "checker.required": { + "one": "Trường {field} là bắt buộc.", + "two": "Trường {field} của {object} là bắt buộc.", + "deep": "Trường {field} là bắt buộc.\nVị trí: {objectPath}" + }, + "checker.min": { + "one": "Giá trị {field} phải ít nhất là {system}.", + "two": "Giá trị {field} của {object} phải ít nhất là {system}.", + "deep": "Giá trị {field} phải ít nhất là {system}.\nVị trí: {objectPath}" + }, + "checker.max": { + "one": "Giá trị {field} không được vượt quá {system}.", + "two": "Giá trị {field} của {object} không được vượt quá {system}.", + "deep": "Giá trị {field} không được vượt quá {system}.\nVị trí: {objectPath}" + }, + "checker.minLength": { + "one": "Độ dài {field} phải ít nhất là {system} {unit}; độ dài hiện tại là {input_len}.", + "two": "Độ dài {field} của {object} phải ít nhất là {system} {unit}; độ dài hiện tại là {input_len}.", + "deep": "Độ dài {field} phải ít nhất là {system} {unit}; độ dài hiện tại là {input_len}.\nVị trí: {objectPath}" + }, + "checker.maxLength": { + "one": "Độ dài {field} không được vượt quá {system} {unit}; độ dài hiện tại là {input_len}.", + "two": "Độ dài {field} của {object} không được vượt quá {system} {unit}; độ dài hiện tại là {input_len}.", + "deep": "Độ dài {field} không được vượt quá {system} {unit}; độ dài hiện tại là {input_len}.\nVị trí: {objectPath}" + }, + "checker.invalid": { + "one": "Trường {field} không hợp lệ.", + "two": "Trường {field} của {object} không hợp lệ.", + "deep": "Trường {field} không hợp lệ.\nVị trí: {objectPath}" + } + }, + "locationPatterns": { + "reference": "{relation}", + "item": "{relation} thứ {position}", + "separator": " → " + } + } + } +} diff --git a/teaql-core/src/test/java/io/teaql/core/i18n/CheckerMessageCatalogTest.java b/teaql-core/src/test/java/io/teaql/core/i18n/CheckerMessageCatalogTest.java new file mode 100644 index 000000000..d8a57629f --- /dev/null +++ b/teaql-core/src/test/java/io/teaql/core/i18n/CheckerMessageCatalogTest.java @@ -0,0 +1,213 @@ +package io.teaql.core.i18n; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.teaql.core.checker.CheckerPresentation; +import io.teaql.core.checker.JsonFieldNamingProfile; +import io.teaql.core.checker.ObjectLocation; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.*; +import org.junit.Test; +import static org.junit.Assert.*; + +public class CheckerMessageCatalogTest { + private static final ObjectMapper JSON = new ObjectMapper(); + + private static Map labels(JsonNode node) { + Map output = new EnumMap<>(Locale.class); + if (node != null) node.fields().forEachRemaining(entry -> output.put(Locale.fromCode(entry.getKey()), entry.getValue().textValue())); + return output; + } + + private static JsonNode fixture() throws IOException { + try (var input = CheckerMessageCatalogTest.class.getResourceAsStream("natural-cases-v1.json")) { + return JSON.readTree(input); + } + } + + private static CheckerPresentation.Model model(JsonNode fixture) { + Map entities = new HashMap<>(); + fixture.get("entities").fields().forEachRemaining(entry -> { + List fields = new ArrayList<>(); + for (JsonNode field : entry.getValue().get("fields")) { + Set aliases = new HashSet<>(); + field.path("aliases").forEach(alias -> aliases.add(alias.textValue())); + fields.add(new CheckerPresentation.Field(field.get("name").textValue(), field.path("targetType").textValue(), + labels(field.get("labels")), labels(field.get("classifiers")), aliases)); + } + entities.put(entry.getKey(), new CheckerPresentation.Entity(labels(entry.getValue().get("labels")), fields)); + }); + return new CheckerPresentation.Model(fixture.get("revision").textValue(), entities, labels(fixture.get("currentObject"))); + } + + private static ObjectLocation location(JsonNode path) { + ObjectLocation location = null; + for (JsonNode step : path) { + location = step.isIntegralNumber() + ? location == null ? ObjectLocation.arrayRoot(step.intValue()) : location.element(step.intValue()) + : location == null ? ObjectLocation.hashRoot(step.textValue()) : location.member(step.textValue()); + } + return location; + } + + private static Map arguments(JsonNode node) { + Map args = new HashMap<>(); + if (node != null) node.fields().forEachRemaining(entry -> args.put(entry.getKey(), entry.getValue().isNumber() ? entry.getValue().numberValue() : entry.getValue().textValue())); + return args; + } + + @Test public void sharedGoldenLocationsAndConstraints() throws Exception { + var fixture = fixture(); var model = model(fixture); + for (var test : fixture.get("cases")) { + String name = test.get("name").textValue(); + var location = location(test.get("path")); + String pointer = location == null ? null : location.instancePath(); + String origin = test.has("origin") ? test.get("origin").textValue() : fixture.get("origin").textValue(); + var presentation = CheckerPresentation.capture(model, origin, location); + assertEquals(name, test.get("shape").textValue(), presentation.shape().name()); + String message = presentation.render(CheckerMessageCatalog.builtin(), Locale.fromCode(test.get("locale").textValue()), + test.get("rule").textValue(), arguments(test.get("arguments")), warning -> {}); + assertEquals(name, test.get("expected").textValue(), message); + assertEquals(name, pointer, location == null ? null : location.instancePath()); + if (test.has("instancePath")) assertEquals(test.get("instancePath").textValue(), pointer); + if (name.equals("two-list")) { + assertEquals("/entry_list/1/name", location.instancePath(JsonFieldNamingProfile.SNAKE_CASE)); + assertEquals("/entryList/1/name", pointer); + } + } + } + + @Test public void allLocalesAllRulesAllShapesAreComplete() { + var catalog = CheckerMessageCatalog.builtin(); + for (var locale : Locale.values()) for (var shape : CheckerMessageCatalog.Shape.values()) + for (String rule : List.of("required", "min", "max", "minLength", "maxLength", "invalid")) { + var selected = catalog.select(locale, "checker." + rule, shape); + assertEquals(locale, selected.locale()); + String message = selected.render(Map.of("field", "FIELD", "object", "OWNER", "objectPath", "CHAIN", + "system", 8, "input_len", 9, "unit", "UNIT")); + assertTrue(message, message.contains("FIELD")); assertFalse(message, message.contains("{")); + if (shape == CheckerMessageCatalog.Shape.TWO) assertTrue(message, message.contains("OWNER")); + if (shape == CheckerMessageCatalog.Shape.DEEP) assertTrue(message, message.contains("CHAIN")); + } + } + + private static CheckerMessageCatalog catalog(String locales) { + return parse("{\"schema\":\"teaql.checker-messages/v1\",\"defaultLocale\":\"en\",\"locales\":" + locales + "}"); + } + private static CheckerMessageCatalog parse(String source) { + return CheckerMessageCatalog.fromJson(new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8))); + } + + @Test public void partialOverridesAndEffectiveLocale() throws Exception { + var overrides = catalog("{\"en\":{\"rules\":{\"checker.custom\":{\"two\":\"Supply {field} for {object}.\"},\"checker.required\":{\"one\":\"Supply {field}.\"}}}}"); + var model = model(fixture()); + var path = ObjectLocation.hashRoot("entry_list").element(1).member("name"); + var presentation = CheckerPresentation.capture(model, "Catalog", path); + assertEquals("Supply name for the 2nd entry.", presentation.render(overrides, Locale.CHINESE_SIMPLIFIED, "checker.custom", Map.of(), warning -> {})); + assertEquals("请填写第2条明细的名称。", presentation.render(overrides, Locale.CHINESE_SIMPLIFIED, "checker.required", Map.of(), warning -> {})); + assertNull(overrides.override(Locale.ENGLISH, "checker.required", CheckerMessageCatalog.Shape.TWO)); + assertNotNull(overrides.override(Locale.ENGLISH, "checker.required", CheckerMessageCatalog.Shape.ONE)); + } + + @Test public void invalidCatalogsRejectWithoutReplacingTheCurrentCatalog() { + String[] broken = { + "{\"en\":{\"rules\":{\"checker.required\":{\"one\":\"{field} {input}\"}}}}", + "{\"en\":{\"rules\":{\"checker.required\":{\"one\":\"{secret}\"}}}}", + "{\"en\":{\"rules\":{\"checker.required\":{\"one\":\"\"}}}}", + "{\"en\":{\"rules\":{\"checker.required\":{\"two\":\"{field}\"}}}}", + "{\"en\":{\"rules\":{\"checker.required\":{\"deep\":\"{field} {object}\"}}}}", + "{\"en\":{\"rules\":{\"checker.required\":{\"three\":\"{field}\"}}}}", + "{\"en\":{\"rules\":{\"checker.min\":{\"one\":\"{field}\"}}}}", + "{\"en\":{\"rules\":{\"checker.maxLength\":{\"one\":\"{field} {system} {unit} {input_len} {input}\"}}}}", + "{\"en\":{\"rules\":{\"checker.required\":{\"one\":\"{field\"}}}}", + "{\"en\":{\"rules\":{\"checker.required\":{\"one\":\"{field}\",\"one\":\"duplicate\"}}}}", + "{\"en\":{\"rules\":{\"checker.required\":{\"one\":\"{field}\"}}},\"en-US\":{\"rules\":{\"checker.required\":{\"one\":\"{field}\"}}}}", + "{\"en\":{\"locationPatterns\":{\"item\":\"{relation}\"}}}", + "{\"en\":{\"locationPatterns\":{\"separator\":\"{input}\"}}}" + }; + var current = CheckerMessageCatalog.builtin(); + for (String source : broken) { + assertThrows(IllegalArgumentException.class, () -> catalog(source)); + assertSame(current, CheckerMessageCatalog.builtin()); + } + assertThrows(IllegalArgumentException.class, () -> parse("{\"schema\":\"teaql.i18n/v1\"}")); + assertThrows(IllegalArgumentException.class, () -> parse("{\"schema\":\"teaql.checker-messages/v1\",\"defaultLocale\":\"en\",\"locales\":{\"en\":{\"rules\":{\"checker.required\":{\"one\":\"{field}\"}}}}} {}")); + var error = assertThrows(IllegalArgumentException.class, () -> parse("{\"schema\": SECRET_PARSE_TEXT")); + assertFalse(error.toString().contains("SECRET_PARSE_TEXT")); assertNull(error.getCause()); + } + + @Test public void literalValuesNeverBecomeTemplateInstructions() { + var catalog = catalog("{\"en\":{\"rules\":{\"checker.required\":{\"one\":\"{{literal}} {field}\"}}}}"); + assertEquals("{literal} {system} ${process.exit()}