diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2d616e439..6f6132878 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,6 +10,22 @@ jobs: build: name: Build and Test runs-on: ubuntu-latest + services: + postgres: + image: postgres:16-alpine@sha256:cf78e76683b9ca8c5733cbbdce6c9262b45b6767934dd0a95e671f9a0fc20685 + env: + POSTGRES_DB: teaql_rollup_279 + POSTGRES_USER: postgres + POSTGRES_PASSWORD: teaql-example-ci-fixture-only + ports: + - 127.0.0.1:5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d teaql_rollup_279" + --health-interval 5s --health-timeout 5s --health-retries 12 + env: + TEAQL_TEST_POSTGRES_JDBC_URL: jdbc:postgresql://127.0.0.1:5432/teaql_rollup_279 + TEAQL_TEST_POSTGRES_USER: postgres + TEAQL_TEST_POSTGRES_PASSWORD: teaql-example-ci-fixture-only timeout-minutes: 150 permissions: contents: read @@ -22,6 +38,13 @@ jobs: java-version: '21' distribution: 'temurin' cache: maven + - name: Mark dedicated PostgreSQL diagnostics fixture + run: | + docker exec -i -u postgres '${{ job.services.postgres.id }}' \ + psql -X -v ON_ERROR_STOP=1 -d teaql_rollup_279 <<'SQL' + COMMENT ON DATABASE teaql_rollup_279 IS 'TeaQL #279 owned layered statistics fixture'; + CREATE EXTENSION IF NOT EXISTS fuzzystrmatch; + SQL - name: Build with Maven run: mvn -B install - name: Verify managed Jackson runtime versions diff --git a/.github/workflows/example-gate.yml b/.github/workflows/example-gate.yml index 5da0c01ac..92c19eea1 100644 --- a/.github/workflows/example-gate.yml +++ b/.github/workflows/example-gate.yml @@ -7,6 +7,18 @@ on: jobs: examples: runs-on: ubuntu-latest + services: + postgres: + image: postgres:16-alpine@sha256:cf78e76683b9ca8c5733cbbdce6c9262b45b6767934dd0a95e671f9a0fc20685 + env: + POSTGRES_DB: teaql_rollup_279 + POSTGRES_USER: postgres + POSTGRES_PASSWORD: teaql-example-ci-fixture-only + ports: + - 127.0.0.1:5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d teaql_rollup_279" + --health-interval 5s --health-timeout 5s --health-retries 12 permissions: contents: read defaults: @@ -18,6 +30,9 @@ jobs: TEAQL_S3_BUCKET: teaql-java-example-ci TEAQL_S3_ACCESS_KEY: teaql-java-example-ci TEAQL_S3_SECRET_KEY: teaql-java-example-ci-fixture-only + TEAQL_TEST_POSTGRES_JDBC_URL: jdbc:postgresql://127.0.0.1:5432/teaql_rollup_279 + TEAQL_TEST_POSTGRES_USER: postgres + TEAQL_TEST_POSTGRES_PASSWORD: teaql-example-ci-fixture-only steps: - name: Check out runtime under test uses: actions/checkout@v4 @@ -30,13 +45,13 @@ jobs: uses: actions/checkout@v4 with: repository: teaql/teaql-code-gen - ref: 554a1b7fa1e5c053e52290c3ee48925901cebe00 + ref: 47a9c444599814aa0b85eea58e88344f7fe3c520 path: generator ssh-key: ${{ secrets.TEAQL_CODEGEN_READONLY_DEPLOY_KEY }} persist-credentials: false - name: Verify pinned generator source run: | - test "$(git -C "$TEAQL_CODEGEN_DIR" rev-parse HEAD)" = 554a1b7fa1e5c053e52290c3ee48925901cebe00 + test "$(git -C "$TEAQL_CODEGEN_DIR" rev-parse HEAD)" = 47a9c444599814aa0b85eea58e88344f7fe3c520 test -z "$(git -C "$TEAQL_CODEGEN_DIR" status --porcelain)" - name: Install example verification tools run: sudo apt-get update && sudo apt-get install -y ripgrep @@ -45,6 +60,13 @@ jobs: distribution: temurin java-version: '21' cache: maven + - name: Mark dedicated PostgreSQL diagnostics fixture + run: | + docker exec -i -u postgres '${{ job.services.postgres.id }}' \ + psql -X -v ON_ERROR_STOP=1 -d teaql_rollup_279 <<'SQL' + COMMENT ON DATABASE teaql_rollup_279 IS 'TeaQL #279 owned layered statistics fixture'; + CREATE EXTENSION IF NOT EXISTS fuzzystrmatch; + SQL - name: Prime third-party dependencies for offline source-paired probes # The gate copies third-party downloads into a disposable Maven home # and explicitly excludes every TeaQL/model artifact from that cache. @@ -70,6 +92,10 @@ jobs: fs.rmSync(owned, {recursive: true}); } NODE + # This job created every reactor target above. Retain dependency + # downloads, but return the ephemeral CI checkout to the target-free + # input required by source-paired inheritance verification. + mvn -B -ntp clean - name: Start dedicated S3 example fixture run: | docker run -d --name teaql-java-example-s3 \ diff --git a/examples/business-id-runtime/pom.xml b/examples/business-id-runtime/pom.xml index 40fa63595..4cd2051d7 100644 --- a/examples/business-id-runtime/pom.xml +++ b/examples/business-id-runtime/pom.xml @@ -6,7 +6,7 @@ io.teaql teaql-java-parent - 1.556-RELEASE + 1.557-RELEASE ../../pom.xml teaql-business-id-example diff --git a/examples/conformance/README.md b/examples/conformance/README.md index 020d82198..3ab1ad9d5 100644 --- a/examples/conformance/README.md +++ b/examples/conformance/README.md @@ -38,6 +38,50 @@ 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. + +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 +completion of every graph/dynamic-field case in all seven languages. + +## Natural Checker messages + +```bash +node examples/conformance/natural-messages/verify-local.cjs +``` + +The [focused example](natural-messages/README.md) uses a separately evaluated, +two-entity generated model and local runtime sources. Two rounds share one +SQLite store. Actual generated Q/E and audited Save verify human-readable +English/Chinese child-field messages, unchanged machine pointers and rule IDs, +original UTF-16 validation length after masking, rejection before provider/audit +calls, automatic Context rollback and successful correction. Presentation +metadata is attached through the runtime module seam; automatic generator +emission and published-package acceptance remain separate gates. + ## 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..79c9ecbf2 --- /dev/null +++ b/examples/conformance/context-derived/GeneratedContextFixTest.java @@ -0,0 +1,271 @@ +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 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; +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 ("NORMALIZE".equals(row.getName())) row.updateName("entry"); + 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 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() { + 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("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)); + 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()); + // 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"); + } + + 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..6a72add9b --- /dev/null +++ b/examples/conformance/context-derived/verify-local.cjs @@ -0,0 +1,98 @@ +'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', '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'); + 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]; + 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.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'))); + 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/examples/conformance/lib/pom.xml b/examples/conformance/lib/pom.xml index 8606fff55..eae44f2c7 100644 --- a/examples/conformance/lib/pom.xml +++ b/examples/conformance/lib/pom.xml @@ -12,7 +12,7 @@ 21 4.1.1 - 1.556-RELEASE + 1.557-RELEASE UTF-8 true diff --git a/examples/conformance/natural-messages/AGENTS.md b/examples/conformance/natural-messages/AGENTS.md new file mode 100644 index 000000000..809e2ad34 --- /dev/null +++ b/examples/conformance/natural-messages/AGENTS.md @@ -0,0 +1,17 @@ +# Natural Checker example + +The parent conformance safety rules apply, but use this example's model and +entities, not the parent's Work Item table: + +```bash +cargo teaql --input examples/conformance/natural-messages/model.xml java-assist-/ +``` + +Entities: `catalog`, `entry`. Use field-specific Query Assist when needed. +`automatic-fixture/` is the current immutable generated library and passive +metadata; `fixture/` preserves the earlier generated input. Neither is an +API-discovery source. Do not install replacement Checkers or hand-built +presentation metadata in the application to make this example pass. +Modify application-owned examples or runtime code; model changes require +evaluation, regeneration and refreshed fixture-origin hashes. Run the local +verifier and retain its exit-zero evidence before claiming acceptance. diff --git a/examples/conformance/natural-messages/GeneratedNaturalMessagesTest.java b/examples/conformance/natural-messages/GeneratedNaturalMessagesTest.java new file mode 100644 index 000000000..dd24853af --- /dev/null +++ b/examples/conformance/natural-messages/GeneratedNaturalMessagesTest.java @@ -0,0 +1,145 @@ +package io.teaql.examples.naturalmessages; + +import com.example.checkernaturalmessageservice.*; +import com.example.checkernaturalmessageservice.catalog.Catalog; +import com.example.checkernaturalmessageservice.entry.*; +import io.teaql.core.*; +import io.teaql.core.checker.*; +import io.teaql.core.meta.SimpleEntityMetaFactory; +import io.teaql.core.businessid.BusinessClock; +import io.teaql.core.sqlite.SqliteDataServiceExecutor; +import io.teaql.provider.jdbc.JdbcSqlExecutor; +import io.teaql.runtime.*; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.*; +import java.sql.*; +import java.util.*; +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.*; + +/** Automatic generated metadata and native Checkers through normal Q/E/Save. */ +public class GeneratedNaturalMessagesTest { + private static final LocalDateTime A = LocalDateTime.of(2026, 11, 12, 12, 0), B = A.plusHours(1); + private static final String PRIVATE_NAME = "密钥🔑" + "x".repeat(98); // 101 scalars, 102 UTF-16 units. + + private static CheckException reject(Catalog graph, UserContext context, Source connections, + AtomicInteger audits, String expected) throws Exception { + int before = connections.calls.get(); + var failure = assertThrows(CheckException.class, + () -> graph.auditAs("Reject the second child before database or audit activity").save(context)); + assertEquals(before, connections.calls.get()); assertEquals(0, audits.get()); + assertEquals(1, failure.getViolates().size()); + var result = failure.getViolates().get(0); + assertEquals("Entry", result.getRootType()); + assertEquals("entry_list[1].name", result.getLocation().modelPath()); + assertEquals("/entryList/1/name", result.getLocation().instancePath()); + assertEquals(expected, result.getNaturalLanguageStatement()); + String response = new ObjectMapper().writeValueAsString(Map.of("errors", failure.getViolates().stream() + .map(value -> value.toWire(JsonFieldNamingProfile.CAMEL_CASE)).toList())); + assertFalse(response.contains(PRIVATE_NAME)); assertFalse(failure.toString().contains(PRIVATE_NAME)); + System.out.println("JAVA_NATURAL_CHECKER_RESPONSE=" + response); + return failure; + } + + @Test public void generatedGraphProducesSafeNaturalMessagesAndStillSavesValidChanges() throws Exception { + String database = System.getenv("TEAQL_NATURAL_MESSAGES_DB"); assertNotNull("use a persistent owned SQLite path", database); + String source = System.getProperty("teaql.expected.runtime.root"); + assertNotNull(source); + assertTrue(java.nio.file.Path.of(TeaQLRuntime.class.getProtectionDomain().getCodeSource().getLocation().toURI()) + .startsWith(java.nio.file.Path.of(source))); + var connections = new Source("jdbc:sqlite:" + database); + var sql = new JdbcSqlExecutor(connections); + var sqlite = new SqliteDataServiceExecutor("sqlite", sql, connections); + var nextId = new AtomicLong(System.currentTimeMillis()); + var runtime = TeaQLRuntime.builder().metadata(new SimpleEntityMetaFactory()).dataService("sqlite", sqlite) + .dataService("default", sqlite).executionLogging(false) + .idGenerationService(new InternalIdGenerationService() { + public Long generateId(UserContext context, Entity entity) { return nextId.incrementAndGet(); } + public void ensureFloor(String type, long floor) { nextId.accumulateAndGet(floor, Math::max); } + }).businessClock(new BusinessClock() { + public LocalDate businessDate(UserContext context) { return businessDateTime(context).toLocalDate(); } + public LocalDateTime businessDateTime(UserContext context) { return context.getAttribute("businessNow", LocalDateTime.class); } + }).build(); + runtime.install(GeneratedRuntimeModule.module()); + var context = new DefaultUserContext(runtime); context.putAttribute("businessNow", A); + context.ensureSchema(); + context.ensureSchema(); + var catalogs = Q.catalogs().limit(1).comment("Find the provisioned validation root") + .purpose("Verify generated schema bootstrap before graph validation").executeForList(context); + assertEquals("ensureSchema provisions the root", 1, catalogs.size()); var catalog = catalogs.get(0); + context.withActiveRoot(new ContextEntityRef("Catalog", catalog.getId())); + for (String name : List.of("first", "second")) { + var entry = Q.entries().comment("Prepare a validation example row").purpose("Create a complete typed test graph").newEntity(context); + entry.updateCatalog(catalog); entry.updateName(name); + entry.auditAs("Create an example entry through the generated mutation API").save(context); + } + var graph = Q.catalogs().withIdIs(catalog.getId()).limit(1) + .selectEntryListWith(Q.entries().orderByIdDescending().limit(2).comment("Load the latest two validation entries")) + .comment("Load the parent and its bounded entry graph") + .purpose("Verify indexed Checker failures through generated Q and E").executeForOne(context); + assertEquals(2, graph.getEntryList().size()); var entry = graph.getEntryList().get(1); + var other = graph.getEntryList().get(0); + assertEquals("first", E.entry(entry).getName().eval()); + assertEquals("second", E.entry(other).getName().eval()); + long parentVersion = graph.getVersion(), previousVersion = entry.getVersion(); + LocalDateTime previousUpdate = E.entry(entry).getUpdateTime().eval(); + context.putAttribute("businessNow", B); + other.updateName("changed"); entry.updateName(null); + var audits = new AtomicInteger(); context.putAttribute(AppAuditEventSink.class.getName(), (AppAuditEventSink) (caller, event) -> audits.incrementAndGet()); + int before = connections.calls.get(); + var english = reject(graph, context, connections, audits, "The name of the 2nd entry is required."); + assertEquals(CheckResult.RuleId.REQUIRED, english.getViolates().get(0).getRuleId()); + assertEquals(previousUpdate, E.entry(entry).getUpdateTime().eval()); + context.setLocaleCode("zh-CN"); + reject(graph, context, connections, audits, "请填写第2项明细的名称。"); + context.setLocaleCode("en"); + entry.updateName(PRIVATE_NAME); + var length = reject(graph, context, connections, audits, + "The name of the 2nd entry must not exceed 100 UTF-16 code units; its current length is 102."); + assertNotEquals(PRIVATE_NAME, length.getViolates().get(0).getInputValue()); + var rendererCalls = new AtomicInteger(); + context.installCheckerMessageRenderer(request -> { + rendererCalls.incrementAndGet(); + assertEquals("密钥" + "*".repeat(97) + "xx", request.arguments().get("input")); + assertEquals(102, ((Number) request.arguments().get("input_len")).intValue()); + return "Private " + PRIVATE_NAME; + }); + reject(graph, context, connections, audits, "Private [REDACTED]"); + assertEquals(1, rendererCalls.get()); + context.installCheckerMessageRenderer(CheckerMessageRenderer.STANDARD); + assertEquals(before, connections.calls.get()); assertEquals(0, audits.get()); + assertEquals(previousUpdate, E.entry(entry).getUpdateTime().eval()); + assertEquals(previousVersion, (long) entry.getVersion()); + entry.updateName("first"); other.updateName("second"); + graph.auditAs("Cancel invalid caller edits without writing automatic Context values").save(context); + assertEquals(before, connections.calls.get()); assertEquals(0, audits.get()); + entry.updateName("accepted"); graph.auditAs("Persist the valid corrected entry").save(context); + assertEquals(1, audits.get()); + var stored = Q.entries().withIdIs(entry.getId()).limit(1).comment("Read the corrected entry") + .purpose("Prove readable diagnostics preserve successful audited mutation").executeForOne(context); + assertEquals("accepted", E.entry(stored).getName().eval()); assertEquals(B, E.entry(stored).getUpdateTime().eval()); + assertEquals(previousVersion + 1, (long) stored.getVersion()); + assertEquals(parentVersion, (long) graph.getVersion()); + System.out.println("JAVA_NATURAL_CHECKER_SQLITE=" + new ObjectMapper().writeValueAsString(Map.ofEntries( + Map.entry("passed", true), Map.entry("typedQ", true), Map.entry("typedE", true), + Map.entry("automaticMetadata", true), Map.entry("originalGeneratedChecker", true), Map.entry("responses", 4), + Map.entry("providerCallsOnRejection", 0), Map.entry("transactionCallsOnRejection", 0), + Map.entry("updatedAudits", audits.get()), Map.entry("customerRendererCalls", rendererCalls.get()), + Map.entry("unchangedParent", graph.getVersion() == parentVersion), Map.entry("version", stored.getVersion())))); + } + + 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 user, String password) 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/natural-messages/README.md b/examples/conformance/natural-messages/README.md new file mode 100644 index 000000000..aa32e05a1 --- /dev/null +++ b/examples/conformance/natural-messages/README.md @@ -0,0 +1,86 @@ +# Natural Checker messages from a generated SQLite graph + +Tracking: [Java #278](https://github.com/teaql/teaql-java/issues/278), +[conformance #244](https://github.com/teaql/teaql-conformance/issues/244). + +This two-entity example returns complete human-readable messages while keeping +canonical error identity separate. For the second entry of a loaded catalog: + +```text +The name of the 2nd entry is required. +The name of the 2nd entry must not exceed 100 UTF-16 code units; its current length is 102. +``` + +The corresponding pointer remains `/entryList/1/name`, not index 2. Switching +the trusted Context to `zh-CN` produces `请填写第2项明细的名称。` without frontend +sentence assembly. The model supplies no specific classifier, so it uses `项`. +A private name's length error reports its original 102 UTF-16 code units, +not its 101 Unicode scalars or its masked value's length. Neither the message nor the +structured response exposes that private value. + +## Run locally + +```bash +TEAQL_NATURAL_MESSAGES_UNIT_TESTS=1 \ +TEAQL_NATURAL_MESSAGES_EVIDENCE_DIR=/absolute/new-evidence-directory \ +node examples/conformance/natural-messages/verify-local.cjs +``` + +Run from the runtime repository with JDK 21, Maven and Node available. `MAVEN` +can select a local Maven executable. This is an offline, source-paired gate; +framework dependencies must already be available. It installs or publishes no +TeaQL artifacts and refuses an existing explicit evidence destination. + +The verifier validates every generated fixture hash, copies current runtime +sources to an owned scratch reactor, binds only the disposable generated POM to +those sources, and runs the example twice against the same SQLite file. It +removes its build/source copies after owned processes exit. It retains compact +receipts, logs and the database in the evidence directory. + +## What the example proves + +- `ensureSchema` provisions the root; sample entries use generated mutation + methods and audited Save, never application-written INSERT statements. +- Bounded generated Q loads the parent and latest two entries. Generated E + reads complete modeled fields; it is not replaced by reflection or raw maps. +- The unmodified generated Checker reports required and private-length failures + at the second child; no application-owned replacement Checker is installed. +- The parent remains unchanged, and the first child is also modified. The + renderer nevertheless resolves the second child's full path from the parent + graph, not from the first writable entity. +- English and Chinese validations reject before any provider call or committed + audit. Failed automatic timestamp changes roll back, while caller edits remain + available for correction. +- Correcting/reverting invalid edits causes no Context-only write; a real + corrected change subsequently saves and reads back successfully. +- Four backend responses each carry one structured violation, original rule IDs, + zero-based pointers, projected inputs and complete human messages. +- A customer renderer receives only projected input and its original length, + runs once for that violation and cannot restore the rejected private value. +- An independent read-only SQLite oracle confirms only the corrected entries + reach version 2; siblings remain unchanged across both rounds. + +`GeneratedRuntimeModule.module()` installs both the generated Checker and +passive model metadata. Application code does not construct presentation +descriptors or call `withCheckerPresentation(...)`. Only the disposable generated +POM is pinned to the repository-local runtime; generated implementation and +metadata hashes remain unchanged. + +## Fixture origin + +`automatic-fixture/` is the current generated input. Its 24-file manifest, +raw model, evaluation output and generator origin are retained alongside +`generation.json`. `JavaNaturalMessagesGenerationTest` evaluates the model and +generates the library from the local generator source; the paired conformance +receipt binds the emitted file hashes to that source snapshot. + +`fixture/` preserves the earlier service-generated library unchanged. Its +original raw model remains at `fixture/model.xml`; its old generation receipt +and top-level `evaluation.md` are historical evidence, not the current input. +The old manually composed acceptance must not be presented as automatic +generator-composition acceptance. + +The old Context Fix fixture remains unchanged. Its model is not reused for new +generation because the current evaluator now requires an additional credential +mask declaration there. This new example does not bypass evaluation or weaken +the frozen old fixture's provenance guards. diff --git a/examples/conformance/natural-messages/automatic-fixture/evaluation.json b/examples/conformance/natural-messages/automatic-fixture/evaluation.json new file mode 100644 index 000000000..23caa7479 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/evaluation.json @@ -0,0 +1,108 @@ +{ + "solids" : [ { + "ruleId" : "KSML-UPLOAD-001", + "title" : "Model upload is non-empty", + "message" : "The upload contains 1 files.", + "path" : "model.zip", + "objectName" : null, + "fieldName" : null, + "xmlPath" : null, + "lineNumber" : null, + "reportTarget" : "model.zip", + "action" : "Check agents/ERROR-FIX.md" + }, { + "ruleId" : "KSML-UPLOAD-005", + "title" : "Valid entrypoint found", + "message" : "Resolved entrypoint: model.xml", + "path" : "model.xml", + "objectName" : null, + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 1, + "reportTarget" : "model.xml", + "action" : "Check agents/ERROR-FIX.md" + }, { + "ruleId" : "KSML-XML-002", + "title" : "XML is well-formed", + "message" : "The XML document model.xml was parsed successfully.", + "path" : "model.xml", + "objectName" : null, + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 1, + "reportTarget" : "model.xml", + "action" : "Check agents/ERROR-FIX.md" + }, { + "ruleId" : "KSML-ROOT-003", + "title" : "Standard root name", + "message" : "Root name 'checker-natural-message-service' is well-formed.", + "path" : "/root", + "objectName" : null, + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 1, + "reportTarget" : "/root", + "action" : "Check agents/ERROR-FIX.md" + }, { + "ruleId" : "KSML-ROOT-008", + "title" : "Default JSON field naming", + "message" : "External JSON business fields use the default camelCase profile.", + "path" : "/root", + "objectName" : null, + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 1, + "reportTarget" : "/root", + "action" : "Check agents/ERROR-FIX.md" + }, { + "ruleId" : "KSML-REFERENCE-003", + "title" : "Reference target exists", + "message" : "Reference 'catalog' in 'entry' successfully resolves to target object 'catalog'.", + "path" : "/root/entry/catalog", + "objectName" : "entry", + "fieldName" : "catalog", + "xmlPath" : "model.xml", + "lineNumber" : 3, + "reportTarget" : "entry.catalog", + "action" : "Check agents/ERROR-FIX.md" + }, { + "ruleId" : "KSML-DOMAIN-ROOT-003", + "title" : "One domain root found", + "message" : "Exactly one domain root candidate 'catalog' was found.", + "path" : "/root", + "objectName" : null, + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 1, + "reportTarget" : "/root", + "action" : "Check agents/ERROR-FIX.md" + } ], + "warnings" : [ { + "ruleId" : "KSML-OBJECT-001", + "title" : "Missing object display metadata", + "message" : "Object 'catalog' is missing display metadata: _module, _module_key", + "path" : "/root/catalog", + "objectName" : "catalog", + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 2, + "reportTarget" : "catalog", + "action" : "Check agents/ERROR-FIX.md" + }, { + "ruleId" : "KSML-OBJECT-001", + "title" : "Missing object display metadata", + "message" : "Object 'entry' is missing display metadata: _module, _module_key", + "path" : "/root/entry", + "objectName" : "entry", + "fieldName" : null, + "xmlPath" : "model.xml", + "lineNumber" : 3, + "reportTarget" : "entry", + "action" : "Check agents/ERROR-FIX.md" + } ], + "suggestions" : [ ], + "errors" : [ ], + "privacyFindings" : [ ], + "privacyRegions" : [ ], + "errorSummaries" : [ ] +} diff --git a/examples/conformance/natural-messages/automatic-fixture/generated-files.json b/examples/conformance/natural-messages/automatic-fixture/generated-files.json new file mode 100644 index 000000000..71da0366a --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/generated-files.json @@ -0,0 +1,26 @@ +{ + "lib/pom.xml" : "479e713e132cfa183e781202098f84e0b74a44a6a535837aa8d92da01ffb00e1", + "lib/src/main/java/com/example/checkernaturalmessageservice/BaseServiceConfiguration.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/checkernaturalmessageservice/CheckerNaturalMessageServiceUserContext.java" : "2d2f927741f43badf499995f1b1715e7132856b9b495ab5392e31404b272d68e", + "lib/src/main/java/com/example/checkernaturalmessageservice/Checkers.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/checkernaturalmessageservice/Constants.java" : "0a3f386cf80db0789aa7f49f4490643e598dff29c093f3ba36efb408b38dc34c", + "lib/src/main/java/com/example/checkernaturalmessageservice/E.java" : "01b3a1dc741ed939a0f6f7ccecdbe80f26ff96c6994ad0ea79ae0aff6d0d41e6", + "lib/src/main/java/com/example/checkernaturalmessageservice/EntityMetaRegistry.java" : "dd804b5fc295c1d2afa3ec7567f3912b48f5bcbb40da2824cd4fbe1d4358c73b", + "lib/src/main/java/com/example/checkernaturalmessageservice/GeneratedRuntimeModule.java" : "4c95cb099a8ce1ab7236f6053f697f1a4a51ce99bc29a078f6a514aff41bf244", + "lib/src/main/java/com/example/checkernaturalmessageservice/Q.java" : "8c7a515a0258aa1c2e14f409b39593662fea7f70469604d00fec37d5ab4639ce", + "lib/src/main/java/com/example/checkernaturalmessageservice/Repositories.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/checkernaturalmessageservice/catalog/Catalog.java" : "e0da39fe42d25ed3bf188707608d2902ca832db884d829e572f4ab18a4d4698e", + "lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogChecker.java" : "eca4ca4a74652d673dec8474df6bf84b3962e2ed0bc100e1ff65a6cb9258bbc6", + "lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogExpression.java" : "4dd395c2be2af0d42cff8cef266ee8558579075a0af93c078d65b0490c727a75", + "lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogListExpression.java" : "29e679c28f5a44fed2128801f482fe24c2d282f13aaccf7e8c5b97d399436ac2", + "lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogRequest.java" : "4c2503727bad7b9802f6ce241ba4e049a02bd895606481e341679c03a0597d20", + "lib/src/main/java/com/example/checkernaturalmessageservice/entry/Entry.java" : "6e004619e98d31cdcfcffe82dfd9a94c5207e04efca5346ff8fd15a4aa22547c", + "lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryChecker.java" : "d6c13306e3d1460045be65bc784877feb42965d3ba13553c7042a70a26b4ac36", + "lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryExpression.java" : "a9f23feb178ab004742193070857a988154cb1a320bd8aef099c9f6756b98bf0", + "lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryListExpression.java" : "c5c16734297e776337278c1f8df2371a4df5f51103f6cf2c0b0b7975b2f805b9", + "lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryRequest.java" : "07924f164eee9f3d812f18346ee278d300381d8d1822712aeed1d45deacd01fd", + "lib/src/main/java/com/example/checkernaturalmessageservice/sampledata/SampleDataService.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler" : "e7343d1366c418947fc058200104a8748265db5763f3861de9cda088cdb9dbce", + "teaql/checker-model.json" : "dbac03cd54b294e3e60a62752aeb170ad1ad722a7dfb8feb639c569ff3e73b1a", + "teaql/model-provenance.json" : "b0a02c87ec8602c39a345acb2082a4ac15645b4596ce81b6e014ee753813cde4" +} diff --git a/examples/conformance/natural-messages/automatic-fixture/generation.json b/examples/conformance/natural-messages/automatic-fixture/generation.json new file mode 100644 index 000000000..d874e93d3 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/generation.json @@ -0,0 +1,13 @@ +{ + "schema": "teaql.generated-example-provenance/v1", + "generatorCommit": "c1304f73e0ea0eb0bdbad6fd1ebdada16e3dbe12", + "upstreamTest": "com.skynet.codegenerator.JavaNaturalMessagesGenerationTest", + "fixtureOutputProperty": "teaql.java.natural.fixture.output", + "scope": "java-lib-core", + "runtimeDependency": "local repository source", + "modelSha256": "6e7bc9313817b3ebe452a0080c2e073d289362f450304b709f6bc794cd8e7f68", + "generationReceipt": "teaql-conformance/evidence/2026-11-12-natural-checker-java-generation-first/receipt.json", + "generationReceiptSha256": "535a7a4bd0fb153a7bb5b3032127bbf67db43789d56bdb1535bb2fb7127af05f", + "implementationHandEdited": false, + "publicPublication": false +} diff --git a/examples/conformance/natural-messages/automatic-fixture/lib/pom.xml b/examples/conformance/natural-messages/automatic-fixture/lib/pom.xml new file mode 100644 index 000000000..c4d841499 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/pom.xml @@ -0,0 +1,142 @@ + + + 4.0.0 + + com.example + checker-natural-message-service-core + 0.0.1-SNAPSHOT + jar + + + 21 + 4.1.1 + 1.557-SNAPSHOT + 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.557-SNAPSHOT + + + 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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/BaseServiceConfiguration.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/BaseServiceConfiguration.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/CheckerNaturalMessageServiceUserContext.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/CheckerNaturalMessageServiceUserContext.java new file mode 100644 index 000000000..b8ff37b1d --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/CheckerNaturalMessageServiceUserContext.java @@ -0,0 +1,10 @@ + +package com.example.checkernaturalmessageservice; + +import io.teaql.core.UserContext; +public interface CheckerNaturalMessageServiceUserContext extends UserContext{ + + + + +} \ No newline at end of file diff --git a/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Checkers.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Checkers.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Constants.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Constants.java new file mode 100644 index 000000000..fe730fc93 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Constants.java @@ -0,0 +1,9 @@ + +package com.example.checkernaturalmessageservice; + +import com.example.checkernaturalmessageservice.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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/E.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/E.java new file mode 100644 index 000000000..167e0960a --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/E.java @@ -0,0 +1,18 @@ + +package com.example.checkernaturalmessageservice; + +import com.example.checkernaturalmessageservice.catalog.Catalog; +import com.example.checkernaturalmessageservice.catalog.CatalogExpression; +import com.example.checkernaturalmessageservice.entry.Entry; +import com.example.checkernaturalmessageservice.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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/EntityMetaRegistry.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/EntityMetaRegistry.java new file mode 100644 index 000000000..05b22f6d0 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/EntityMetaRegistry.java @@ -0,0 +1,214 @@ + +package com.example.checkernaturalmessageservice; + +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.checkernaturalmessageservice.catalog.Catalog.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.checkernaturalmessageservice.catalog.Catalog.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.checkernaturalmessageservice.catalog.Catalog.class); + entityDescriptor.setEntitySupplier(com.example.checkernaturalmessageservice.catalog.Catalog::new); + entityDescriptor.with("name", "catalog") + .with("zh_CN", "目录"); + + entityDescriptor.setAuditMaskFields(java.util.List.of()); + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.catalog.Catalog.ID_PROPERTY, Long.class) + ; + PropertyDescriptor name = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.catalog.Catalog.NAME_PROPERTY, String.class) + ; + PropertyDescriptor version = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.catalog.Catalog.VERSION_PROPERTY, Long.class) + ; + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.catalog.Catalog.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.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.checkernaturalmessageservice.catalog.Catalog.NAME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.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("zh_CN", "名称") + .with("graphqlType", "String") + .with("isTime", "false") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.catalog.Catalog.VERSION_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.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.checkernaturalmessageservice.entry.Entry.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.checkernaturalmessageservice.entry.Entry.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.checkernaturalmessageservice.entry.Entry.class); + entityDescriptor.setEntitySupplier(com.example.checkernaturalmessageservice.entry.Entry::new); + entityDescriptor.with("name", "entry") + .with("zh_CN", "明细") + .with("audit_mask_fields", "name"); + + entityDescriptor.setAuditMaskFields(java.util.List.of(com.example.checkernaturalmessageservice.entry.Entry.NAME_PROPERTY)); + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.ID_PROPERTY, Long.class) + ; + PropertyDescriptor catalog = + entityDescriptor.addObjectProperty($factory, com.example.checkernaturalmessageservice.entry.Entry.CATALOG_PROPERTY, com.example.checkernaturalmessageservice.catalog.Catalog.INTERNAL_TYPE, com.example.checkernaturalmessageservice.catalog.Catalog.ENTRY_LIST_PROPERTY, com.example.checkernaturalmessageservice.catalog.Catalog.class) + ; + PropertyDescriptor name = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.NAME_PROPERTY, String.class) + ; + PropertyDescriptor createTime = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.CREATE_TIME_PROPERTY, LocalDateTime.class) + ; + PropertyDescriptor updateTime = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.UPDATE_TIME_PROPERTY, LocalDateTime.class) + ; + PropertyDescriptor version = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.VERSION_PROPERTY, Long.class) + ; + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.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.checkernaturalmessageservice.entry.Entry.CATALOG_PROPERTY).with("required", "true"); + + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.NAME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.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("zh_CN", "名称") + .with("graphqlType", "String") + .with("isTime", "false") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.CREATE_TIME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.CREATE_TIME_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.checkernaturalmessageservice.entry.Entry.UPDATE_TIME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.UPDATE_TIME_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.checkernaturalmessageservice.entry.Entry.VERSION_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/GeneratedRuntimeModule.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/GeneratedRuntimeModule.java new file mode 100644 index 000000000..7fd451161 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/GeneratedRuntimeModule.java @@ -0,0 +1,37 @@ +package com.example.checkernaturalmessageservice; + +/** 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.checkernaturalmessageservice.catalog.CatalogChecker(), new com.example.checkernaturalmessageservice.entry.EntryChecker()) + .withCheckerPresentation(io.teaql.core.checker.CheckerPresentation.Model.fromJson(String.join("", "{\"schema\":\"teaql.checker-model/v1\",\"revision\":\"sha256:9ea98ce6f86d4528fa8abed527685e55e825dcb5a695c61871b7aeab0eba3967\",\"entities\":{\"Catalog\":{\"labels\":{\"en\":\"catalog\",\"zh-CN\":\"目录\"},\"fields\":[{\"name\":\"entry_list\",\"targetType\":\"Entry\",\"labels\":{\"en\":\"entry\",\"zh-CN\":\"明细\"},\"aliases\":[\"EntryList\",\"entryList\"]},{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]},{\"name\":\"name\",\"labels\":{\"en\":\"name\",\"zh-CN\":\"名称\"},\"aliases\":[\"Name\"]},{\"name\":\"version\",\"labels\":{\"en\":\"version\"},\"aliases\":[\"Version\"]}]},\"Entry\":{\"labels\":{\"en\":\"entry\",\"zh-CN\":\"明细\"},\"fields\":[{\"name\":\"catalog\",\"targetType\":\"Catalog\",\"labels\":{\"en\":\"catalog\",\"zh-CN\":\"目录\"},\"aliases\":[\"Catalog\"]},{\"name\":\"create_time\",\"labels\":{\"en\":\"create time\"},\"aliases\":[\"CreateTime\",\"createTime\"]},{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]},{\"name\":\"name\",\"labels\":{\"en\":\"name\",\"zh-CN\":\"名称\"},\"aliases\":[\"Name\"]},{\"name\":\"update_time\",\"labels\":{\"en\":\"update time\"},\"aliases\":[\"UpdateTime\",\"updateTime\"]},{\"name\":\"version\",\"labels\":{\"en\":\"version\"},\"aliases\":[\"Version\"]}]}}}"))) + .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("create_time", "createTime"), java.util.Map.entry("update_time", "updateTime"), 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.checkernaturalmessageservice.catalog.Catalog domainRoot; + if (domainRoots.isEmpty()) { + domainRoot = new com.example.checkernaturalmessageservice.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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Q.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Q.java new file mode 100644 index 000000000..1a74d86e8 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Q.java @@ -0,0 +1,25 @@ + +package com.example.checkernaturalmessageservice; + +import io.teaql.core.criteria.Operator; + +public class Q { + public static com.example.checkernaturalmessageservice.catalog.CatalogRequest catalogs(){ + return new com.example.checkernaturalmessageservice.catalog.CatalogRequest(com.example.checkernaturalmessageservice.catalog.Catalog.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.checkernaturalmessageservice.catalog.CatalogRequest catalogsWithMinimalFields(){ + return new com.example.checkernaturalmessageservice.catalog.CatalogRequest(com.example.checkernaturalmessageservice.catalog.Catalog.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + + public static com.example.checkernaturalmessageservice.entry.EntryRequest entries(){ + return new com.example.checkernaturalmessageservice.entry.EntryRequest(com.example.checkernaturalmessageservice.entry.Entry.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.checkernaturalmessageservice.entry.EntryRequest entriesWithMinimalFields(){ + return new com.example.checkernaturalmessageservice.entry.EntryRequest(com.example.checkernaturalmessageservice.entry.Entry.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + +} \ No newline at end of file diff --git a/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Repositories.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Repositories.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/Catalog.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/Catalog.java new file mode 100644 index 000000000..a7070458c --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/Catalog.java @@ -0,0 +1,130 @@ + +package com.example.checkernaturalmessageservice.catalog; + +import com.example.checkernaturalmessageservice.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 = "17d8d23d986f660e08bbf4204a52837ff356311f48de5ad8046528786b1394bb"; + 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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogChecker.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogChecker.java new file mode 100644 index 000000000..760afc099 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogChecker.java @@ -0,0 +1,52 @@ + +package com.example.checkernaturalmessageservice.catalog; + +import com.example.checkernaturalmessageservice.entry.Entry; +import com.example.checkernaturalmessageservice.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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogExpression.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogExpression.java new file mode 100644 index 000000000..502db83b9 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogExpression.java @@ -0,0 +1,51 @@ + +package com.example.checkernaturalmessageservice.catalog; + +import com.example.checkernaturalmessageservice.entry.Entry; +import com.example.checkernaturalmessageservice.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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogListExpression.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogListExpression.java new file mode 100644 index 000000000..e58cf190b --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogListExpression.java @@ -0,0 +1,25 @@ + +package com.example.checkernaturalmessageservice.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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogRequest.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogRequest.java new file mode 100644 index 000000000..e18c4afc2 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogRequest.java @@ -0,0 +1,579 @@ + +package com.example.checkernaturalmessageservice.catalog; + +import com.example.checkernaturalmessageservice.Q; +import com.example.checkernaturalmessageservice.entry.Entry; +import com.example.checkernaturalmessageservice.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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/Entry.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/Entry.java new file mode 100644 index 000000000..8e6dfc21f --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/Entry.java @@ -0,0 +1,169 @@ + +package com.example.checkernaturalmessageservice.entry; + +import com.example.checkernaturalmessageservice.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 = "8e34a18976365b7e707005f06d9441ba9a12b1923c7f21baf92af523ac70a9db"; + 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("create_time", 3), java.util.Map.entry("update_time", 4), java.util.Map.entry("version", 5)); + 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("create_time", java.util.List.of("createTime", "create_time")), java.util.Map.entry("update_time", java.util.List.of("updateTime", "update_time")), 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 CREATE_TIME_PROPERTY = "create_time"; + public static final String UPDATE_TIME_PROPERTY = "update_time"; + private Catalog catalog; + + private String name; + + private LocalDateTime createTime; + + private LocalDateTime updateTime; + + + public Catalog getCatalog(){ + return this.catalog; + } + + public String getName(){ + return this.name; + } + + public LocalDateTime getCreateTime(){ + return this.createTime; + } + + public LocalDateTime getUpdateTime(){ + return this.updateTime; + } + + 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 updateCreateTime(LocalDateTime createTime){ + if(isPropertyLoaded(CREATE_TIME_PROPERTY) && Objects.equals(this.createTime, createTime)){ + return this; + } + handleUpdate(CREATE_TIME_PROPERTY, getCreateTime(), createTime); + this.createTime = createTime; + return this; + } + + public Entry updateUpdateTime(LocalDateTime updateTime){ + if(isPropertyLoaded(UPDATE_TIME_PROPERTY) && Objects.equals(this.updateTime, updateTime)){ + return this; + } + handleUpdate(UPDATE_TIME_PROPERTY, getUpdateTime(), updateTime); + this.updateTime = updateTime; + 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 "create_time": this.createTime = (LocalDateTime) value; break; + + case "update_time": this.updateTime = (LocalDateTime) value; 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 "create_time": return this.createTime; + case "update_time": return this.updateTime; + 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 "createTime": return this.createTime; + case "updateTime": return this.updateTime; + default: return super.__internalGet(property); + } + } + } + +} \ No newline at end of file diff --git a/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryChecker.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryChecker.java new file mode 100644 index 000000000..b173894ed --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryChecker.java @@ -0,0 +1,103 @@ + +package com.example.checkernaturalmessageservice.entry; + +import com.example.checkernaturalmessageservice.catalog.Catalog; +import com.example.checkernaturalmessageservice.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, "create_time"), () -> { + entry.updateCreateTime(_context.evaluate("now")); + _context.recordFixEvidence(new io.teaql.core.checker.FixEvidence(type(), "create_time", + "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, "update_time"), () -> { + entry.updateUpdateTime(_context.evaluate("now")); + _context.recordFixEvidence(new io.teaql.core.checker.FixEvidence(type(), "update_time", + "now".equalsIgnoreCase("now") ? io.teaql.core.checker.FixEvidence.Source.CLOCK : io.teaql.core.checker.FixEvidence.Source.CONTEXT, + "now".equalsIgnoreCase("now") ? "graphClock" : "contextFunction:now")); + }); + } + }else if(entry.updateItem()){ + if(_contextFixEligible){ + applyContextFix(_context, newLocation(_parentLocation, "update_time"), () -> { + entry.updateUpdateTime(_context.evaluate("now")); + _context.recordFixEvidence(new io.teaql.core.checker.FixEvidence(type(), "update_time", + "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("create_time")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "create_time"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("update_time")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "update_time"), "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")); + checkCreateTime(_context, entry.getProperty(Entry.CREATE_TIME_PROPERTY), newLocation(_parentLocation, "create_time")); + checkUpdateTime(_context, entry.getProperty(Entry.UPDATE_TIME_PROPERTY), newLocation(_parentLocation, "update_time")); + } + + 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 checkCreateTime(UserContext _context, LocalDateTime createTime, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, createTime); + if((createTime == null)){ + return; + } + } + public void checkUpdateTime(UserContext _context, LocalDateTime updateTime, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, updateTime); + if((updateTime == null)){ + return; + } + } +} \ No newline at end of file diff --git a/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryExpression.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryExpression.java new file mode 100644 index 000000000..671981367 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryExpression.java @@ -0,0 +1,68 @@ + +package com.example.checkernaturalmessageservice.entry; + +import com.example.checkernaturalmessageservice.catalog.Catalog; +import com.example.checkernaturalmessageservice.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 getCreateTime(){ + return loaded("create_time", "getCreateTime", Entry::getCreateTime); + } + public EntryExpression updateCreateTime(LocalDateTime createTime){ + return new EntryExpression(this, $it -> ((Entry)$it).updateCreateTime(createTime)); + } + + public Expression getUpdateTime(){ + return loaded("update_time", "getUpdateTime", Entry::getUpdateTime); + } + public EntryExpression updateUpdateTime(LocalDateTime updateTime){ + return new EntryExpression(this, $it -> ((Entry)$it).updateUpdateTime(updateTime)); + } + +} \ No newline at end of file diff --git a/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryListExpression.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryListExpression.java new file mode 100644 index 000000000..5d46271ad --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryListExpression.java @@ -0,0 +1,25 @@ + +package com.example.checkernaturalmessageservice.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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryRequest.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryRequest.java new file mode 100644 index 000000000..399f03b55 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryRequest.java @@ -0,0 +1,888 @@ + +package com.example.checkernaturalmessageservice.entry; + +import com.example.checkernaturalmessageservice.Q; +import com.example.checkernaturalmessageservice.catalog.Catalog; +import com.example.checkernaturalmessageservice.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().selectCreateTime().selectUpdateTime().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.CREATE_TIME_PROPERTY); + selectProperty(Entry.UPDATE_TIME_PROPERTY); + selectProperty(Entry.VERSION_PROPERTY); + return this; + } + + public EntryRequest selectAll(){ + super.selectAll(); + return selectId().selectCatalog().selectName().selectCreateTime().selectUpdateTime().selectVersion(); + } + + public EntryRequest selectChildren(){ + super.selectAny(); + return selectId().selectCatalog().selectName().selectCreateTime().selectUpdateTime().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 selectCreateTime(){ + selectProperty(Entry.CREATE_TIME_PROPERTY); + return this; + } + + /** + * fill the createTime with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS createTime) to fetch createTime property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectCreateTime(){ + unselectProperty(Entry.CREATE_TIME_PROPERTY); + return this; + } + public EntryRequest selectUpdateTime(){ + selectProperty(Entry.UPDATE_TIME_PROPERTY); + return this; + } + + /** + * fill the updateTime with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS updateTime) to fetch updateTime property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectUpdateTime(){ + unselectProperty(Entry.UPDATE_TIME_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 filterByCreateTime(LocalDateTime... createTime){ + if (createTime == null || createTime.length == 0) { + throw new IllegalArgumentException("filterByCreateTime parameter createTime cannot be empty"); + } + return appendSearchCriteria(createCreateTimeCriteria(Operator.EQUAL, (Object[])createTime)); + } + + public EntryRequest withCreateTime(Operator operator, Object... values){ + return appendSearchCriteria(createCreateTimeCriteria(operator, values)); + } + + public EntryRequest withCreateTimeIsUnknown(){ + return withCreateTime(Operator.IS_NULL); + } + + public EntryRequest withCreateTimeIsKnown(){ + return withCreateTime(Operator.IS_NOT_NULL); + } + + public SearchCriteria createCreateTimeCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.CREATE_TIME_PROPERTY, operator, values); + } + + public EntryRequest withCreateTimeIs(LocalDateTime createTime){ + return withCreateTime(Operator.EQUAL, createTime); + } + + public EntryRequest withCreateTimeIsNot(LocalDateTime createTime){ + return withCreateTime(Operator.NOT_EQUAL, createTime); + } + + public EntryRequest withCreateTimeIn(LocalDateTime... createTime){ + return withCreateTime(Operator.IN, (Object[])createTime); + } + + public EntryRequest withCreateTimeNotIn(LocalDateTime... createTime){ + return withCreateTime(Operator.NOT_IN, (Object[])createTime); + } + public EntryRequest withCreateTimeGreaterThan(LocalDateTime createTime){ + return withCreateTime(Operator.GREATER_THAN, createTime); + } + + public EntryRequest withCreateTimeGreaterThanOrEqualTo(LocalDateTime createTime){ + return withCreateTime(Operator.GREATER_THAN_OR_EQUAL, createTime); + } + + public EntryRequest withCreateTimeLessThan(LocalDateTime createTime){ + return withCreateTime(Operator.LESS_THAN, createTime); + } + + public EntryRequest withCreateTimeLessThanOrEqualTo(LocalDateTime createTime){ + return withCreateTime(Operator.LESS_THAN_OR_EQUAL, createTime); + } + + public EntryRequest withCreateTimeBetween(LocalDateTime startOfCreateTime, LocalDateTime endOfCreateTime){ + return withCreateTime(Operator.BETWEEN, startOfCreateTime, endOfCreateTime); + } + public EntryRequest withCreateTimeBefore(LocalDateTime createTime){ + return withCreateTime(Operator.LESS_THAN, createTime); + } + + public EntryRequest withCreateTimeBefore(Date createTime){ + return withCreateTime(Operator.LESS_THAN, createTime); + } + + public EntryRequest withCreateTimeAfter(LocalDateTime createTime){ + return withCreateTime(Operator.GREATER_THAN, createTime); + } + + public EntryRequest withCreateTimeAfter(Date createTime){ + return withCreateTime(Operator.GREATER_THAN, createTime); + } + + public EntryRequest withCreateTimeBetween(Date startOfCreateTime, Date endOfCreateTime){ + return withCreateTime(Operator.BETWEEN, startOfCreateTime, endOfCreateTime); + } + + + + + public EntryRequest filterByUpdateTime(LocalDateTime... updateTime){ + if (updateTime == null || updateTime.length == 0) { + throw new IllegalArgumentException("filterByUpdateTime parameter updateTime cannot be empty"); + } + return appendSearchCriteria(createUpdateTimeCriteria(Operator.EQUAL, (Object[])updateTime)); + } + + public EntryRequest withUpdateTime(Operator operator, Object... values){ + return appendSearchCriteria(createUpdateTimeCriteria(operator, values)); + } + + public EntryRequest withUpdateTimeIsUnknown(){ + return withUpdateTime(Operator.IS_NULL); + } + + public EntryRequest withUpdateTimeIsKnown(){ + return withUpdateTime(Operator.IS_NOT_NULL); + } + + public SearchCriteria createUpdateTimeCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.UPDATE_TIME_PROPERTY, operator, values); + } + + public EntryRequest withUpdateTimeIs(LocalDateTime updateTime){ + return withUpdateTime(Operator.EQUAL, updateTime); + } + + public EntryRequest withUpdateTimeIsNot(LocalDateTime updateTime){ + return withUpdateTime(Operator.NOT_EQUAL, updateTime); + } + + public EntryRequest withUpdateTimeIn(LocalDateTime... updateTime){ + return withUpdateTime(Operator.IN, (Object[])updateTime); + } + + public EntryRequest withUpdateTimeNotIn(LocalDateTime... updateTime){ + return withUpdateTime(Operator.NOT_IN, (Object[])updateTime); + } + public EntryRequest withUpdateTimeGreaterThan(LocalDateTime updateTime){ + return withUpdateTime(Operator.GREATER_THAN, updateTime); + } + + public EntryRequest withUpdateTimeGreaterThanOrEqualTo(LocalDateTime updateTime){ + return withUpdateTime(Operator.GREATER_THAN_OR_EQUAL, updateTime); + } + + public EntryRequest withUpdateTimeLessThan(LocalDateTime updateTime){ + return withUpdateTime(Operator.LESS_THAN, updateTime); + } + + public EntryRequest withUpdateTimeLessThanOrEqualTo(LocalDateTime updateTime){ + return withUpdateTime(Operator.LESS_THAN_OR_EQUAL, updateTime); + } + + public EntryRequest withUpdateTimeBetween(LocalDateTime startOfUpdateTime, LocalDateTime endOfUpdateTime){ + return withUpdateTime(Operator.BETWEEN, startOfUpdateTime, endOfUpdateTime); + } + public EntryRequest withUpdateTimeBefore(LocalDateTime updateTime){ + return withUpdateTime(Operator.LESS_THAN, updateTime); + } + + public EntryRequest withUpdateTimeBefore(Date updateTime){ + return withUpdateTime(Operator.LESS_THAN, updateTime); + } + + public EntryRequest withUpdateTimeAfter(LocalDateTime updateTime){ + return withUpdateTime(Operator.GREATER_THAN, updateTime); + } + + public EntryRequest withUpdateTimeAfter(Date updateTime){ + return withUpdateTime(Operator.GREATER_THAN, updateTime); + } + + public EntryRequest withUpdateTimeBetween(Date startOfUpdateTime, Date endOfUpdateTime){ + return withUpdateTime(Operator.BETWEEN, startOfUpdateTime, endOfUpdateTime); + } + + + + + 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 groupByCreateTime(){ + groupBy(Entry.CREATE_TIME_PROPERTY); + return this; + } + + public EntryRequest groupByCreateTimeAs(String retName){ + groupBy(retName, Entry.CREATE_TIME_PROPERTY); + return this; + } + + public EntryRequest groupByCreateTimeWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.CREATE_TIME_PROPERTY, function); + return this; + } + + public EntryRequest groupByUpdateTime(){ + groupBy(Entry.UPDATE_TIME_PROPERTY); + return this; + } + + public EntryRequest groupByUpdateTimeAs(String retName){ + groupBy(retName, Entry.UPDATE_TIME_PROPERTY); + return this; + } + + public EntryRequest groupByUpdateTimeWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.UPDATE_TIME_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 orderByCreateTimeAscending(){ + addOrderByAscending(Entry.CREATE_TIME_PROPERTY); + return this; + } + + public EntryRequest orderByCreateTimeDescending(){ + addOrderByDescending(Entry.CREATE_TIME_PROPERTY); + return this; + } + + public EntryRequest orderByUpdateTimeAscending(){ + addOrderByAscending(Entry.UPDATE_TIME_PROPERTY); + return this; + } + + public EntryRequest orderByUpdateTimeDescending(){ + addOrderByDescending(Entry.UPDATE_TIME_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/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/sampledata/SampleDataService.java b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/java/com/example/checkernaturalmessageservice/sampledata/SampleDataService.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/natural-messages/automatic-fixture/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler new file mode 100644 index 000000000..57a8cdc0e --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler @@ -0,0 +1,2 @@ + +com.example.checkernaturalmessageservice.EntityMetaRegistry \ No newline at end of file diff --git a/examples/conformance/natural-messages/automatic-fixture/model.xml b/examples/conformance/natural-messages/automatic-fixture/model.xml new file mode 100644 index 000000000..20e7bd802 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/model.xml @@ -0,0 +1,5 @@ + + + + diff --git a/examples/conformance/natural-messages/automatic-fixture/teaql/checker-model.json b/examples/conformance/natural-messages/automatic-fixture/teaql/checker-model.json new file mode 100644 index 000000000..30dcd07eb --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/teaql/checker-model.json @@ -0,0 +1 @@ +{"schema":"teaql.checker-model/v1","revision":"sha256:9ea98ce6f86d4528fa8abed527685e55e825dcb5a695c61871b7aeab0eba3967","entities":{"Catalog":{"labels":{"en":"catalog","zh-CN":"目录"},"fields":[{"name":"entry_list","targetType":"Entry","labels":{"en":"entry","zh-CN":"明细"},"aliases":["EntryList","entryList"]},{"name":"id","labels":{"en":"id"},"aliases":["Id"]},{"name":"name","labels":{"en":"name","zh-CN":"名称"},"aliases":["Name"]},{"name":"version","labels":{"en":"version"},"aliases":["Version"]}]},"Entry":{"labels":{"en":"entry","zh-CN":"明细"},"fields":[{"name":"catalog","targetType":"Catalog","labels":{"en":"catalog","zh-CN":"目录"},"aliases":["Catalog"]},{"name":"create_time","labels":{"en":"create time"},"aliases":["CreateTime","createTime"]},{"name":"id","labels":{"en":"id"},"aliases":["Id"]},{"name":"name","labels":{"en":"name","zh-CN":"名称"},"aliases":["Name"]},{"name":"update_time","labels":{"en":"update time"},"aliases":["UpdateTime","updateTime"]},{"name":"version","labels":{"en":"version"},"aliases":["Version"]}]}}} \ No newline at end of file diff --git a/examples/conformance/natural-messages/automatic-fixture/teaql/model-provenance.json b/examples/conformance/natural-messages/automatic-fixture/teaql/model-provenance.json new file mode 100644 index 000000000..725e88115 --- /dev/null +++ b/examples/conformance/natural-messages/automatic-fixture/teaql/model-provenance.json @@ -0,0 +1 @@ +{"schemaVersion":1,"modelUuid":null,"revisionHash":"sha256:b7fe340e07a920295caf8233b44cc229e2d72411969218dc902350a9d047dc49","generatorVersion":"unknown"} \ No newline at end of file diff --git a/examples/conformance/natural-messages/evaluation.md b/examples/conformance/natural-messages/evaluation.md new file mode 100644 index 000000000..7065c0f8e --- /dev/null +++ b/examples/conformance/natural-messages/evaluation.md @@ -0,0 +1,23 @@ +model input: examples/conformance/natural-messages/model.xml +using https://api.teaql.io/latest/evaluate + +# KSML Evaluation Report +## 📊 Summary +- **Errors**: 0 +- **Warnings**: 0 +- **Suggestions**: 0 +- **Solids**: 9 + +## ✅ Solids + +| Rule ID | Target | Source | Message | +|---------|--------|--------|---------| +| `KSML-UPLOAD-001` | `` | — | The upload contains 1 files. | +| `KSML-UPLOAD-005` | `` | `model.xml:2` | Resolved entrypoint: model.xml | +| `KSML-XML-002` | `` | `model.xml:2` | The XML document model.xml was parsed successfully. | +| `KSML-ROOT-003` | `` | `model.xml:2` | Root name 'checker-natural-message-service' is well-formed. | +| `KSML-ROOT-008` | `` | `model.xml:2` | External JSON business fields use the default camelCase profile. | +| `KSML-OBJECT-001` | `catalog` | `model.xml:4` | Object 'catalog' defines display name, module, and module key metadata. | +| `KSML-OBJECT-001` | `entry` | `model.xml:6` | Object 'entry' defines display name, module, and module key metadata. | +| `KSML-REFERENCE-003` | `entry.catalog` | `model.xml:8` | Reference 'catalog' in 'entry' successfully resolves to target object 'catalog'. | +| `KSML-DOMAIN-ROOT-003` | `` | `model.xml:2` | Exactly one domain root candidate 'catalog' was found. | diff --git a/examples/conformance/natural-messages/fixture/generated-files.json b/examples/conformance/natural-messages/fixture/generated-files.json new file mode 100644 index 000000000..ad46b9edd --- /dev/null +++ b/examples/conformance/natural-messages/fixture/generated-files.json @@ -0,0 +1,25 @@ +{ + "lib/src/main/java/com/example/checkernaturalmessageservice/Checkers.java": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogChecker.java": "f1b522de551b7ecc06dcf86762a847063478d8b2130bb8c620fc815855b0c35a", + "lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryChecker.java": "12fee59c726c8cb6e3465ec0e7e0b3c50a3a8cff72c55b395cb7f367d6c88014", + "lib/src/main/java/com/example/checkernaturalmessageservice/Repositories.java": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogListExpression.java": "29e679c28f5a44fed2128801f482fe24c2d282f13aaccf7e8c5b97d399436ac2", + "lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryListExpression.java": "c5c16734297e776337278c1f8df2371a4df5f51103f6cf2c0b0b7975b2f805b9", + "lib/src/main/java/com/example/checkernaturalmessageservice/Q.java": "8c7a515a0258aa1c2e14f409b39593662fea7f70469604d00fec37d5ab4639ce", + "lib/src/main/java/com/example/checkernaturalmessageservice/EntityMetaRegistry.java": "f552b5864413e4da4246d4737d236f383c205434c30b421040554b0adfd53f24", + "lib/src/main/java/com/example/checkernaturalmessageservice/GeneratedRuntimeModule.java": "0432bd4e3597b73c2040303823a3eaabd8fe66da3cfb950d52acb6f922ab919b", + "lib/src/main/java/com/example/checkernaturalmessageservice/Constants.java": "0a3f386cf80db0789aa7f49f4490643e598dff29c093f3ba36efb408b38dc34c", + "lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogRequest.java": "16e7012c78893845aa6e846c545a5c13b0f50d77db19e0ce5997cb5f64730afc", + "lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryRequest.java": "9316113e0966524f88d30644626ee4e2705a74285bcddb8e20d3f0bcce924ec9", + "lib/src/main/java/com/example/checkernaturalmessageservice/catalog/Catalog.java": "e0da39fe42d25ed3bf188707608d2902ca832db884d829e572f4ab18a4d4698e", + "lib/src/main/java/com/example/checkernaturalmessageservice/entry/Entry.java": "df97863bc02d18c06f27b985ec86db4b3e7d71ce85609f8e2a97c943594b0fbf", + "lib/src/main/java/com/example/checkernaturalmessageservice/sampledata/SampleDataService.java": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/checkernaturalmessageservice/E.java": "01b3a1dc741ed939a0f6f7ccecdbe80f26ff96c6994ad0ea79ae0aff6d0d41e6", + "lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogExpression.java": "4dd395c2be2af0d42cff8cef266ee8558579075a0af93c078d65b0490c727a75", + "lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryExpression.java": "f44bf55c944559c0188869895dd988abb4f55e33738a0bc0ad20b9c83d744983", + "lib/src/main/java/com/example/checkernaturalmessageservice/BaseServiceConfiguration.java": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler": "e7343d1366c418947fc058200104a8748265db5763f3861de9cda088cdb9dbce", + "lib/pom.xml": "7d0dc9e99b3455bbecb42c0b32b381325e1bedb6a59a5e1bf3728c09db8855dc", + "lib/src/main/java/com/example/checkernaturalmessageservice/CheckerNaturalMessageServiceUserContext.java": "2d2f927741f43badf499995f1b1715e7132856b9b495ab5392e31404b272d68e", + "teaql/model-provenance.json": "402579c45fd233e554ac10ed319f900146fe26d9d48e2a0bc1e0e80e5fa7d9af" +} diff --git a/examples/conformance/natural-messages/fixture/generation.json b/examples/conformance/natural-messages/fixture/generation.json new file mode 100644 index 000000000..5c16fe0a2 --- /dev/null +++ b/examples/conformance/natural-messages/fixture/generation.json @@ -0,0 +1,22 @@ +{ + "schema": "teaql.natural-checker-example-generation/v1", + "command": [ + "cargo-teaql", + "--input", + "model.xml", + "--output", + "fixture", + "java-lib-core" + ], + "cliVersion": "2.0.14", + "modelSha256": "ee15bf3c0a5867537456abea4935b85781eb56c5e7f5c9628bc4e3945ca90fb1", + "archiveSha256": "7df3f71c6a842b87c7547a4a3b006ebf2ea9c42f444aac2fdd79fa0c05cd5a3d", + "archiveBytes": 25728, + "archiveSourceEquality": true, + "provenance": { + "schemaVersion": 1, + "modelUuid": null, + "revisionHash": "sha256:3f21a8d130e4d3f3006fbdaf1ef336ab8b4db99932935b966f6be220293ad287", + "generatorVersion": "061eb063" + } +} diff --git a/examples/conformance/natural-messages/fixture/lib/pom.xml b/examples/conformance/natural-messages/fixture/lib/pom.xml new file mode 100644 index 000000000..f133119e9 --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/pom.xml @@ -0,0 +1,142 @@ + + + 4.0.0 + + com.example + checker-natural-message-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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/BaseServiceConfiguration.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/BaseServiceConfiguration.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/CheckerNaturalMessageServiceUserContext.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/CheckerNaturalMessageServiceUserContext.java new file mode 100644 index 000000000..b8ff37b1d --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/CheckerNaturalMessageServiceUserContext.java @@ -0,0 +1,10 @@ + +package com.example.checkernaturalmessageservice; + +import io.teaql.core.UserContext; +public interface CheckerNaturalMessageServiceUserContext extends UserContext{ + + + + +} \ No newline at end of file diff --git a/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Checkers.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Checkers.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Constants.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Constants.java new file mode 100644 index 000000000..fe730fc93 --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Constants.java @@ -0,0 +1,9 @@ + +package com.example.checkernaturalmessageservice; + +import com.example.checkernaturalmessageservice.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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/E.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/E.java new file mode 100644 index 000000000..167e0960a --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/E.java @@ -0,0 +1,18 @@ + +package com.example.checkernaturalmessageservice; + +import com.example.checkernaturalmessageservice.catalog.Catalog; +import com.example.checkernaturalmessageservice.catalog.CatalogExpression; +import com.example.checkernaturalmessageservice.entry.Entry; +import com.example.checkernaturalmessageservice.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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/EntityMetaRegistry.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/EntityMetaRegistry.java new file mode 100644 index 000000000..c489bc1d8 --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/EntityMetaRegistry.java @@ -0,0 +1,273 @@ + +package com.example.checkernaturalmessageservice; + +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.checkernaturalmessageservice.catalog.Catalog.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.checkernaturalmessageservice.catalog.Catalog.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.checkernaturalmessageservice.catalog.Catalog.class); + entityDescriptor.setEntitySupplier(com.example.checkernaturalmessageservice.catalog.Catalog::new); + entityDescriptor.with("name", "Validation Catalog") + .with("module", "Validation") + .with("module_key", "main"); + + entityDescriptor.setAuditMaskFields(java.util.List.of()); + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.catalog.Catalog.ID_PROPERTY, Long.class) + ; + PropertyDescriptor name = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.catalog.Catalog.NAME_PROPERTY, String.class) + ; + PropertyDescriptor version = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.catalog.Catalog.VERSION_PROPERTY, Long.class) + ; + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.catalog.Catalog.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.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.checkernaturalmessageservice.catalog.Catalog.NAME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.catalog.Catalog.NAME_PROPERTY).with("isPassword", "false") + .with("max", "100") + .with("isVersion", "false") + .with("javaType", "java.lang.String") + .with("candidates", "Validation 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.checkernaturalmessageservice.catalog.Catalog.VERSION_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.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.checkernaturalmessageservice.entry.Entry.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.checkernaturalmessageservice.entry.Entry.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.checkernaturalmessageservice.entry.Entry.class); + entityDescriptor.setEntitySupplier(com.example.checkernaturalmessageservice.entry.Entry::new); + entityDescriptor.with("name", "Validation Entry") + .with("module", "Validation") + .with("module_key", "main") + .with("audit_mask_fields", "protected_note"); + + entityDescriptor.setAuditMaskFields(java.util.List.of(com.example.checkernaturalmessageservice.entry.Entry.PROTECTED_NOTE_PROPERTY)); + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.ID_PROPERTY, Long.class) + ; + PropertyDescriptor catalog = + entityDescriptor.addObjectProperty($factory, com.example.checkernaturalmessageservice.entry.Entry.CATALOG_PROPERTY, com.example.checkernaturalmessageservice.catalog.Catalog.INTERNAL_TYPE, com.example.checkernaturalmessageservice.catalog.Catalog.ENTRY_LIST_PROPERTY, com.example.checkernaturalmessageservice.catalog.Catalog.class) + ; + PropertyDescriptor name = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.NAME_PROPERTY, String.class) + ; + PropertyDescriptor quantity = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.QUANTITY_PROPERTY, Integer.class) + ; + PropertyDescriptor description = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.DESCRIPTION_PROPERTY, String.class) + ; + PropertyDescriptor protectedNote = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.PROTECTED_NOTE_PROPERTY, String.class) + ; + PropertyDescriptor createTime = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.CREATE_TIME_PROPERTY, LocalDateTime.class) + ; + PropertyDescriptor updateTime = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.UPDATE_TIME_PROPERTY, LocalDateTime.class) + ; + PropertyDescriptor version = + entityDescriptor.addSimpleProperty(com.example.checkernaturalmessageservice.entry.Entry.VERSION_PROPERTY, Long.class) + ; + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.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.checkernaturalmessageservice.entry.Entry.CATALOG_PROPERTY).with("required", "true"); + + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.NAME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.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.checkernaturalmessageservice.entry.Entry.QUANTITY_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.QUANTITY_PROPERTY).with("isPassword", "false") + .with("db2_sqlType", "decimal(19,7)") + .with("isVersion", "false") + .with("oracle_sqlType", "number(19,7)") + .with("javaType", "java.lang.Integer") + .with("sqlType", "INTEGER") + .with("isId", "false") + .with("isBool", "false") + .with("isBaseEntityField", "false") + .with("isNumber", "true") + .with("isInt", "true") + .with("isString", "false") + .with("isDate", "false") + .with("graphqlType", "Int") + .with("isTime", "false") + .with("isText", "false"); + + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.DESCRIPTION_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.DESCRIPTION_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.checkernaturalmessageservice.entry.Entry.PROTECTED_NOTE_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.PROTECTED_NOTE_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.checkernaturalmessageservice.entry.Entry.CREATE_TIME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.CREATE_TIME_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.checkernaturalmessageservice.entry.Entry.UPDATE_TIME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.entry.Entry.UPDATE_TIME_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.checkernaturalmessageservice.entry.Entry.VERSION_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.checkernaturalmessageservice.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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/GeneratedRuntimeModule.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/GeneratedRuntimeModule.java new file mode 100644 index 000000000..cf32f037b --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/GeneratedRuntimeModule.java @@ -0,0 +1,36 @@ +package com.example.checkernaturalmessageservice; + +/** 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.checkernaturalmessageservice.catalog.CatalogChecker(), new com.example.checkernaturalmessageservice.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("quantity", "quantity"), java.util.Map.entry("description", "description"), java.util.Map.entry("protected_note", "protectedNote"), java.util.Map.entry("create_time", "createTime"), java.util.Map.entry("update_time", "updateTime"), 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.checkernaturalmessageservice.catalog.Catalog domainRoot; + if (domainRoots.isEmpty()) { + domainRoot = new com.example.checkernaturalmessageservice.catalog.Catalog(); + io.teaql.core.GeneratedSchemaBootstrap.initializeFixedId(context, domainRoot, 1L); + domainRoot.updateName("Validation 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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Q.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Q.java new file mode 100644 index 000000000..1a74d86e8 --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Q.java @@ -0,0 +1,25 @@ + +package com.example.checkernaturalmessageservice; + +import io.teaql.core.criteria.Operator; + +public class Q { + public static com.example.checkernaturalmessageservice.catalog.CatalogRequest catalogs(){ + return new com.example.checkernaturalmessageservice.catalog.CatalogRequest(com.example.checkernaturalmessageservice.catalog.Catalog.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.checkernaturalmessageservice.catalog.CatalogRequest catalogsWithMinimalFields(){ + return new com.example.checkernaturalmessageservice.catalog.CatalogRequest(com.example.checkernaturalmessageservice.catalog.Catalog.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + + public static com.example.checkernaturalmessageservice.entry.EntryRequest entries(){ + return new com.example.checkernaturalmessageservice.entry.EntryRequest(com.example.checkernaturalmessageservice.entry.Entry.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.checkernaturalmessageservice.entry.EntryRequest entriesWithMinimalFields(){ + return new com.example.checkernaturalmessageservice.entry.EntryRequest(com.example.checkernaturalmessageservice.entry.Entry.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + +} \ No newline at end of file diff --git a/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Repositories.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/Repositories.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/Catalog.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/Catalog.java new file mode 100644 index 000000000..a7070458c --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/Catalog.java @@ -0,0 +1,130 @@ + +package com.example.checkernaturalmessageservice.catalog; + +import com.example.checkernaturalmessageservice.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 = "17d8d23d986f660e08bbf4204a52837ff356311f48de5ad8046528786b1394bb"; + 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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogChecker.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogChecker.java new file mode 100644 index 000000000..1d730810d --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogChecker.java @@ -0,0 +1,51 @@ + +package com.example.checkernaturalmessageservice.catalog; + +import com.example.checkernaturalmessageservice.entry.Entry; +import com.example.checkernaturalmessageservice.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; + } + 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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogExpression.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogExpression.java new file mode 100644 index 000000000..502db83b9 --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogExpression.java @@ -0,0 +1,51 @@ + +package com.example.checkernaturalmessageservice.catalog; + +import com.example.checkernaturalmessageservice.entry.Entry; +import com.example.checkernaturalmessageservice.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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogListExpression.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogListExpression.java new file mode 100644 index 000000000..e58cf190b --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogListExpression.java @@ -0,0 +1,25 @@ + +package com.example.checkernaturalmessageservice.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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogRequest.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogRequest.java new file mode 100644 index 000000000..5358f2aea --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/catalog/CatalogRequest.java @@ -0,0 +1,731 @@ + +package com.example.checkernaturalmessageservice.catalog; + +import com.example.checkernaturalmessageservice.Q; +import com.example.checkernaturalmessageservice.entry.Entry; +import com.example.checkernaturalmessageservice.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; + } + public CatalogRequest minQuantityOfEntries(){ + addRelationScalarAggregate("minQuantityOfEntries", Q.entries().unlimited(), + Entry.CATALOG_PROPERTY, Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("min".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "minQuantityOfEntries", null, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest minQuantityOfEntriesAs(String name){ + return minQuantityOfEntriesAs(name, Q.entries().unlimited()); + } + + public CatalogRequest minQuantityOfEntriesAs(String name, EntryRequest subRequest){ + addRelationScalarAggregate(name, subRequest, Entry.CATALOG_PROPERTY, + Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("min".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "minQuantityOfEntriesAs", name, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + public CatalogRequest maxQuantityOfEntries(){ + addRelationScalarAggregate("maxQuantityOfEntries", Q.entries().unlimited(), + Entry.CATALOG_PROPERTY, Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("max".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "maxQuantityOfEntries", null, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest maxQuantityOfEntriesAs(String name){ + return maxQuantityOfEntriesAs(name, Q.entries().unlimited()); + } + + public CatalogRequest maxQuantityOfEntriesAs(String name, EntryRequest subRequest){ + addRelationScalarAggregate(name, subRequest, Entry.CATALOG_PROPERTY, + Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("max".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "maxQuantityOfEntriesAs", name, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + public CatalogRequest sumQuantityOfEntries(){ + addRelationScalarAggregate("sumQuantityOfEntries", Q.entries().unlimited(), + Entry.CATALOG_PROPERTY, Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("sum".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sumQuantityOfEntries", null, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest sumQuantityOfEntriesAs(String name){ + return sumQuantityOfEntriesAs(name, Q.entries().unlimited()); + } + + public CatalogRequest sumQuantityOfEntriesAs(String name, EntryRequest subRequest){ + addRelationScalarAggregate(name, subRequest, Entry.CATALOG_PROPERTY, + Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("sum".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sumQuantityOfEntriesAs", name, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + public CatalogRequest avgQuantityOfEntries(){ + addRelationScalarAggregate("avgQuantityOfEntries", Q.entries().unlimited(), + Entry.CATALOG_PROPERTY, Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("avg".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "avgQuantityOfEntries", null, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest avgQuantityOfEntriesAs(String name){ + return avgQuantityOfEntriesAs(name, Q.entries().unlimited()); + } + + public CatalogRequest avgQuantityOfEntriesAs(String name, EntryRequest subRequest){ + addRelationScalarAggregate(name, subRequest, Entry.CATALOG_PROPERTY, + Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("avg".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "avgQuantityOfEntriesAs", name, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + public CatalogRequest standardDeviationQuantityOfEntries(){ + addRelationScalarAggregate("stdDevQuantityOfEntries", Q.entries().unlimited(), + Entry.CATALOG_PROPERTY, Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "standardDeviationQuantityOfEntries", null, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest standardDeviationQuantityOfEntriesAs(String name){ + return standardDeviationQuantityOfEntriesAs(name, Q.entries().unlimited()); + } + + public CatalogRequest standardDeviationQuantityOfEntriesAs(String name, EntryRequest subRequest){ + addRelationScalarAggregate(name, subRequest, Entry.CATALOG_PROPERTY, + Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "standardDeviationQuantityOfEntriesAs", name, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + public CatalogRequest squareRootOfPopulationStandardDeviationQuantityOfEntries(){ + addRelationScalarAggregate("stdDevPopQuantityOfEntries", Q.entries().unlimited(), + Entry.CATALOG_PROPERTY, Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "squareRootOfPopulationStandardDeviationQuantityOfEntries", null, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest squareRootOfPopulationStandardDeviationQuantityOfEntriesAs(String name){ + return squareRootOfPopulationStandardDeviationQuantityOfEntriesAs(name, Q.entries().unlimited()); + } + + public CatalogRequest squareRootOfPopulationStandardDeviationQuantityOfEntriesAs(String name, EntryRequest subRequest){ + addRelationScalarAggregate(name, subRequest, Entry.CATALOG_PROPERTY, + Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "squareRootOfPopulationStandardDeviationQuantityOfEntriesAs", name, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + public CatalogRequest sampleVarianceQuantityOfEntries(){ + addRelationScalarAggregate("varSampQuantityOfEntries", Q.entries().unlimited(), + Entry.CATALOG_PROPERTY, Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_samp".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sampleVarianceQuantityOfEntries", null, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest sampleVarianceQuantityOfEntriesAs(String name){ + return sampleVarianceQuantityOfEntriesAs(name, Q.entries().unlimited()); + } + + public CatalogRequest sampleVarianceQuantityOfEntriesAs(String name, EntryRequest subRequest){ + addRelationScalarAggregate(name, subRequest, Entry.CATALOG_PROPERTY, + Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_samp".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sampleVarianceQuantityOfEntriesAs", name, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + public CatalogRequest samplePopulationVarianceQuantityOfEntries(){ + addRelationScalarAggregate("varPopQuantityOfEntries", Q.entries().unlimited(), + Entry.CATALOG_PROPERTY, Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "samplePopulationVarianceQuantityOfEntries", null, Catalog.ENTRY_LIST_PROPERTY)); + return this; + } + + public CatalogRequest samplePopulationVarianceQuantityOfEntriesAs(String name){ + return samplePopulationVarianceQuantityOfEntriesAs(name, Q.entries().unlimited()); + } + + public CatalogRequest samplePopulationVarianceQuantityOfEntriesAs(String name, EntryRequest subRequest){ + addRelationScalarAggregate(name, subRequest, Entry.CATALOG_PROPERTY, + Entry.QUANTITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "samplePopulationVarianceQuantityOfEntriesAs", 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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/Entry.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/Entry.java new file mode 100644 index 000000000..3ccd3cb9b --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/Entry.java @@ -0,0 +1,231 @@ + +package com.example.checkernaturalmessageservice.entry; + +import com.example.checkernaturalmessageservice.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 = "a24d0c5535a958061d28d3bc95458f9f730a25ed0176dfe41a997281df2a754b"; + 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("quantity", 3), java.util.Map.entry("description", 4), java.util.Map.entry("protected_note", 5), java.util.Map.entry("create_time", 6), java.util.Map.entry("update_time", 7), java.util.Map.entry("version", 8)); + 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("quantity", java.util.List.of("quantity", "quantity")), java.util.Map.entry("description", java.util.List.of("description", "description")), java.util.Map.entry("protected_note", java.util.List.of("protectedNote", "protected_note")), java.util.Map.entry("create_time", java.util.List.of("createTime", "create_time")), java.util.Map.entry("update_time", java.util.List.of("updateTime", "update_time")), 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 QUANTITY_PROPERTY = "quantity"; + public static final String DESCRIPTION_PROPERTY = "description"; + public static final String PROTECTED_NOTE_PROPERTY = "protected_note"; + public static final String CREATE_TIME_PROPERTY = "create_time"; + public static final String UPDATE_TIME_PROPERTY = "update_time"; + private Catalog catalog; + + private String name; + + private Integer quantity; + + private String description; + + private String protectedNote; + + private LocalDateTime createTime; + + private LocalDateTime updateTime; + + + public Catalog getCatalog(){ + return this.catalog; + } + + public String getName(){ + return this.name; + } + + public Integer getQuantity(){ + return this.quantity; + } + + public String getDescription(){ + return this.description; + } + + public String getProtectedNote(){ + return this.protectedNote; + } + + public LocalDateTime getCreateTime(){ + return this.createTime; + } + + public LocalDateTime getUpdateTime(){ + return this.updateTime; + } + + 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 updateQuantity(Integer quantity){ + if(isPropertyLoaded(QUANTITY_PROPERTY) && Objects.equals(this.quantity, quantity)){ + return this; + } + handleUpdate(QUANTITY_PROPERTY, getQuantity(), quantity); + this.quantity = quantity; + return this; + } + + public Entry updateDescription(String description){ + description = (description == null ? null : description.trim()); + if(isPropertyLoaded(DESCRIPTION_PROPERTY) && Objects.equals(this.description, description)){ + return this; + } + handleUpdate(DESCRIPTION_PROPERTY, getDescription(), description); + this.description = description; + return this; + } + + public Entry updateProtectedNote(String protectedNote){ + protectedNote = (protectedNote == null ? null : protectedNote.trim()); + if(isPropertyLoaded(PROTECTED_NOTE_PROPERTY) && Objects.equals(this.protectedNote, protectedNote)){ + return this; + } + handleUpdate(PROTECTED_NOTE_PROPERTY, getProtectedNote(), protectedNote); + this.protectedNote = protectedNote; + return this; + } + + public Entry updateCreateTime(LocalDateTime createTime){ + if(isPropertyLoaded(CREATE_TIME_PROPERTY) && Objects.equals(this.createTime, createTime)){ + return this; + } + handleUpdate(CREATE_TIME_PROPERTY, getCreateTime(), createTime); + this.createTime = createTime; + return this; + } + + public Entry updateUpdateTime(LocalDateTime updateTime){ + if(isPropertyLoaded(UPDATE_TIME_PROPERTY) && Objects.equals(this.updateTime, updateTime)){ + return this; + } + handleUpdate(UPDATE_TIME_PROPERTY, getUpdateTime(), updateTime); + this.updateTime = updateTime; + 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 "quantity": this.quantity = (Integer) value; break; + + case "description": this.description = (value == null ? null : ((String)value).trim()); break; + + case "protected_note": this.protectedNote = (value == null ? null : ((String)value).trim()); break; + + case "create_time": this.createTime = (LocalDateTime) value; break; + + case "update_time": this.updateTime = (LocalDateTime) value; 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 "quantity": return this.quantity; + case "description": return this.description; + case "protected_note": return this.protectedNote; + case "create_time": return this.createTime; + case "update_time": return this.updateTime; + 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 "quantity": return this.quantity; + case "description": return this.description; + case "protectedNote": return this.protectedNote; + case "createTime": return this.createTime; + case "updateTime": return this.updateTime; + default: return super.__internalGet(property); + } + } + } + +} \ No newline at end of file diff --git a/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryChecker.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryChecker.java new file mode 100644 index 000000000..6995aaa57 --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryChecker.java @@ -0,0 +1,122 @@ + +package com.example.checkernaturalmessageservice.entry; + +import com.example.checkernaturalmessageservice.catalog.Catalog; +import com.example.checkernaturalmessageservice.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; + } + if(entry.needPersist()){ + } + if(entry.newItem()){ + if(entry.getCreateTime() == null){ + entry.updateCreateTime(_context.evaluate("now")); + _context.recordFixEvidence(new io.teaql.core.checker.FixEvidence(type(), "create_time", io.teaql.core.checker.FixEvidence.Source.CLOCK, "graphClock")); + }if(entry.getUpdateTime() == null){ + entry.updateUpdateTime(_context.evaluate("now")); + _context.recordFixEvidence(new io.teaql.core.checker.FixEvidence(type(), "update_time", io.teaql.core.checker.FixEvidence.Source.CLOCK, "graphClock")); + } + }else if(entry.updateItem()){ + entry.updateUpdateTime(_context.evaluate("now")); + _context.recordFixEvidence(new io.teaql.core.checker.FixEvidence(type(), "update_time", io.teaql.core.checker.FixEvidence.Source.CLOCK, "graphClock")); + 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("quantity")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "quantity"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("description")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "description"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("protected_note")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "protected_note"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("create_time")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "create_time"), "Mutation requires a fully loaded entity"); + } + if(!entry.isPropertyLoaded("update_time")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "update_time"), "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")); + checkQuantity(_context, entry.getProperty(Entry.QUANTITY_PROPERTY), newLocation(_parentLocation, "quantity")); + checkDescription(_context, entry.getProperty(Entry.DESCRIPTION_PROPERTY), newLocation(_parentLocation, "description")); + checkProtectedNote(_context, entry.getProperty(Entry.PROTECTED_NOTE_PROPERTY), newLocation(_parentLocation, "protected_note")); + checkCreateTime(_context, entry.getProperty(Entry.CREATE_TIME_PROPERTY), newLocation(_parentLocation, "create_time")); + checkUpdateTime(_context, entry.getProperty(Entry.UPDATE_TIME_PROPERTY), newLocation(_parentLocation, "update_time")); + } + + 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 checkQuantity(UserContext _context, Integer quantity, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, quantity); + if((quantity == null)){ + return; + } + } + public void checkDescription(UserContext _context, String description, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, description); + if((description == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, description); + + } + public void checkProtectedNote(UserContext _context, String protectedNote, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, protectedNote); + if((protectedNote == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, protectedNote); + + } + public void checkCreateTime(UserContext _context, LocalDateTime createTime, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, createTime); + if((createTime == null)){ + return; + } + } + public void checkUpdateTime(UserContext _context, LocalDateTime updateTime, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, updateTime); + if((updateTime == null)){ + return; + } + } +} \ No newline at end of file diff --git a/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryExpression.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryExpression.java new file mode 100644 index 000000000..ff1dac301 --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryExpression.java @@ -0,0 +1,89 @@ + +package com.example.checkernaturalmessageservice.entry; + +import com.example.checkernaturalmessageservice.catalog.Catalog; +import com.example.checkernaturalmessageservice.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 getQuantity(){ + return loaded("quantity", "getQuantity", Entry::getQuantity); + } + public EntryExpression updateQuantity(Integer quantity){ + return new EntryExpression(this, $it -> ((Entry)$it).updateQuantity(quantity)); + } + + public Expression getDescription(){ + return loaded("description", "getDescription", Entry::getDescription); + } + public EntryExpression updateDescription(String description){ + return new EntryExpression(this, $it -> ((Entry)$it).updateDescription(description)); + } + + public Expression getProtectedNote(){ + return loaded("protected_note", "getProtectedNote", Entry::getProtectedNote); + } + public EntryExpression updateProtectedNote(String protectedNote){ + return new EntryExpression(this, $it -> ((Entry)$it).updateProtectedNote(protectedNote)); + } + + public Expression getCreateTime(){ + return loaded("create_time", "getCreateTime", Entry::getCreateTime); + } + public EntryExpression updateCreateTime(LocalDateTime createTime){ + return new EntryExpression(this, $it -> ((Entry)$it).updateCreateTime(createTime)); + } + + public Expression getUpdateTime(){ + return loaded("update_time", "getUpdateTime", Entry::getUpdateTime); + } + public EntryExpression updateUpdateTime(LocalDateTime updateTime){ + return new EntryExpression(this, $it -> ((Entry)$it).updateUpdateTime(updateTime)); + } + +} \ No newline at end of file diff --git a/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryListExpression.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryListExpression.java new file mode 100644 index 000000000..5d46271ad --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryListExpression.java @@ -0,0 +1,25 @@ + +package com.example.checkernaturalmessageservice.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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryRequest.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryRequest.java new file mode 100644 index 000000000..bfd7d2b84 --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/entry/EntryRequest.java @@ -0,0 +1,1343 @@ + +package com.example.checkernaturalmessageservice.entry; + +import com.example.checkernaturalmessageservice.Q; +import com.example.checkernaturalmessageservice.catalog.Catalog; +import com.example.checkernaturalmessageservice.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().selectQuantity().selectDescription().selectProtectedNote().selectCreateTime().selectUpdateTime().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.QUANTITY_PROPERTY); + selectProperty(Entry.DESCRIPTION_PROPERTY); + selectProperty(Entry.PROTECTED_NOTE_PROPERTY); + selectProperty(Entry.CREATE_TIME_PROPERTY); + selectProperty(Entry.UPDATE_TIME_PROPERTY); + selectProperty(Entry.VERSION_PROPERTY); + return this; + } + + public EntryRequest selectAll(){ + super.selectAll(); + return selectId().selectCatalog().selectName().selectQuantity().selectDescription().selectProtectedNote().selectCreateTime().selectUpdateTime().selectVersion(); + } + + public EntryRequest selectChildren(){ + super.selectAny(); + return selectId().selectCatalog().selectName().selectQuantity().selectDescription().selectProtectedNote().selectCreateTime().selectUpdateTime().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 selectQuantity(){ + selectProperty(Entry.QUANTITY_PROPERTY); + return this; + } + + /** + * fill the quantity with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS quantity) to fetch quantity property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + /** + * fill the quantity with customized aggrFunction, TEAQL uses ({aggrFunction}(quantity) AS quantity to fetch quantity property. + * @param aggrFunction aggrFunction + */ + public EntryRequest selectQuantity(AggrFunction aggrFunction){ + selectProperty(Entry.QUANTITY_PROPERTY, aggrFunction); + return this; + } + + + public EntryRequest unselectQuantity(){ + unselectProperty(Entry.QUANTITY_PROPERTY); + return this; + } + public EntryRequest selectDescription(){ + selectProperty(Entry.DESCRIPTION_PROPERTY); + return this; + } + + /** + * fill the description with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS description) to fetch description property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectDescription(){ + unselectProperty(Entry.DESCRIPTION_PROPERTY); + return this; + } + public EntryRequest selectProtectedNote(){ + selectProperty(Entry.PROTECTED_NOTE_PROPERTY); + return this; + } + + /** + * fill the protectedNote with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS protectedNote) to fetch protectedNote property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectProtectedNote(){ + unselectProperty(Entry.PROTECTED_NOTE_PROPERTY); + return this; + } + public EntryRequest selectCreateTime(){ + selectProperty(Entry.CREATE_TIME_PROPERTY); + return this; + } + + /** + * fill the createTime with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS createTime) to fetch createTime property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectCreateTime(){ + unselectProperty(Entry.CREATE_TIME_PROPERTY); + return this; + } + public EntryRequest selectUpdateTime(){ + selectProperty(Entry.UPDATE_TIME_PROPERTY); + return this; + } + + /** + * fill the updateTime with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS updateTime) to fetch updateTime property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public EntryRequest unselectUpdateTime(){ + unselectProperty(Entry.UPDATE_TIME_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 filterByQuantity(Integer... quantity){ + if (quantity == null || quantity.length == 0) { + throw new IllegalArgumentException("filterByQuantity parameter quantity cannot be empty"); + } + return appendSearchCriteria(createQuantityCriteria(Operator.EQUAL, (Object[])quantity)); + } + + public EntryRequest withQuantity(Operator operator, Object... values){ + return appendSearchCriteria(createQuantityCriteria(operator, values)); + } + + public EntryRequest withQuantityIsUnknown(){ + return withQuantity(Operator.IS_NULL); + } + + public EntryRequest withQuantityIsKnown(){ + return withQuantity(Operator.IS_NOT_NULL); + } + + public SearchCriteria createQuantityCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.QUANTITY_PROPERTY, operator, values); + } + + public EntryRequest withQuantityIs(Integer quantity){ + return withQuantity(Operator.EQUAL, quantity); + } + + public EntryRequest withQuantityIsNot(Integer quantity){ + return withQuantity(Operator.NOT_EQUAL, quantity); + } + + public EntryRequest withQuantityIn(Integer... quantity){ + return withQuantity(Operator.IN, (Object[])quantity); + } + + public EntryRequest withQuantityNotIn(Integer... quantity){ + return withQuantity(Operator.NOT_IN, (Object[])quantity); + } + public EntryRequest withQuantityGreaterThan(Integer quantity){ + return withQuantity(Operator.GREATER_THAN, quantity); + } + + public EntryRequest withQuantityGreaterThanOrEqualTo(Integer quantity){ + return withQuantity(Operator.GREATER_THAN_OR_EQUAL, quantity); + } + + public EntryRequest withQuantityLessThan(Integer quantity){ + return withQuantity(Operator.LESS_THAN, quantity); + } + + public EntryRequest withQuantityLessThanOrEqualTo(Integer quantity){ + return withQuantity(Operator.LESS_THAN_OR_EQUAL, quantity); + } + + public EntryRequest withQuantityBetween(Integer startOfQuantity, Integer endOfQuantity){ + return withQuantity(Operator.BETWEEN, startOfQuantity, endOfQuantity); + } + + + + public EntryRequest filterByDescription(String... description){ + if (description == null || description.length == 0) { + throw new IllegalArgumentException("filterByDescription parameter description cannot be empty"); + } + return appendSearchCriteria(createDescriptionCriteria(Operator.EQUAL, (Object[])description)); + } + + public EntryRequest withDescription(Operator operator, Object... values){ + return appendSearchCriteria(createDescriptionCriteria(operator, values)); + } + + public EntryRequest withDescriptionIsUnknown(){ + return withDescription(Operator.IS_NULL); + } + + public EntryRequest withDescriptionIsKnown(){ + return withDescription(Operator.IS_NOT_NULL); + } + + public SearchCriteria createDescriptionCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.DESCRIPTION_PROPERTY, operator, values); + } + + public EntryRequest withDescriptionIsNot(String description){ + return withDescription(Operator.NOT_EQUAL, description); + } + + public EntryRequest withDescriptionIn(String... description){ + return withDescription(Operator.IN, (Object[])description); + } + + public EntryRequest withDescriptionNotIn(String... description){ + return withDescription(Operator.NOT_IN, (Object[])description); + } + public EntryRequest withDescriptionGreaterThan(String description){ + return withDescription(Operator.GREATER_THAN, description); + } + + public EntryRequest withDescriptionGreaterThanOrEqualTo(String description){ + return withDescription(Operator.GREATER_THAN_OR_EQUAL, description); + } + + public EntryRequest withDescriptionLessThan(String description){ + return withDescription(Operator.LESS_THAN, description); + } + + public EntryRequest withDescriptionLessThanOrEqualTo(String description){ + return withDescription(Operator.LESS_THAN_OR_EQUAL, description); + } + + public EntryRequest withDescriptionBetween(String startOfDescription, String endOfDescription){ + return withDescription(Operator.BETWEEN, startOfDescription, endOfDescription); + } + public EntryRequest withDescriptionStartingWith(String description){ + return withDescription(Operator.BEGIN_WITH, description); + } + public EntryRequest withDescriptionContaining(String description){ + return withDescription(Operator.CONTAIN, description); + } + + public EntryRequest withDescriptionNotContaining(String description){ + return withDescription(Operator.NOT_CONTAIN, description); + } + + public EntryRequest withDescriptionNotStartingWith(String description){ + return withDescription(Operator.NOT_BEGIN_WITH, description); + } + + public EntryRequest withDescriptionEndingWith(String description){ + return withDescription(Operator.END_WITH, description); + } + + public EntryRequest withDescriptionNotEndingWith(String description){ + return withDescription(Operator.NOT_END_WITH, description); + } + + public EntryRequest withDescriptionIs(String description){ + return withDescription(Operator.EQUAL, description); + } + + public EntryRequest withDescriptionSoundingLike(String description){ + return withDescription(Operator.SOUNDS_LIKE, description); + } + + + + public EntryRequest filterByProtectedNote(String... protectedNote){ + if (protectedNote == null || protectedNote.length == 0) { + throw new IllegalArgumentException("filterByProtectedNote parameter protectedNote cannot be empty"); + } + return appendSearchCriteria(createProtectedNoteCriteria(Operator.EQUAL, (Object[])protectedNote)); + } + + public EntryRequest withProtectedNote(Operator operator, Object... values){ + return appendSearchCriteria(createProtectedNoteCriteria(operator, values)); + } + + public EntryRequest withProtectedNoteIsUnknown(){ + return withProtectedNote(Operator.IS_NULL); + } + + public EntryRequest withProtectedNoteIsKnown(){ + return withProtectedNote(Operator.IS_NOT_NULL); + } + + public SearchCriteria createProtectedNoteCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.PROTECTED_NOTE_PROPERTY, operator, values); + } + + public EntryRequest withProtectedNoteIsNot(String protectedNote){ + return withProtectedNote(Operator.NOT_EQUAL, protectedNote); + } + + public EntryRequest withProtectedNoteIn(String... protectedNote){ + return withProtectedNote(Operator.IN, (Object[])protectedNote); + } + + public EntryRequest withProtectedNoteNotIn(String... protectedNote){ + return withProtectedNote(Operator.NOT_IN, (Object[])protectedNote); + } + public EntryRequest withProtectedNoteGreaterThan(String protectedNote){ + return withProtectedNote(Operator.GREATER_THAN, protectedNote); + } + + public EntryRequest withProtectedNoteGreaterThanOrEqualTo(String protectedNote){ + return withProtectedNote(Operator.GREATER_THAN_OR_EQUAL, protectedNote); + } + + public EntryRequest withProtectedNoteLessThan(String protectedNote){ + return withProtectedNote(Operator.LESS_THAN, protectedNote); + } + + public EntryRequest withProtectedNoteLessThanOrEqualTo(String protectedNote){ + return withProtectedNote(Operator.LESS_THAN_OR_EQUAL, protectedNote); + } + + public EntryRequest withProtectedNoteBetween(String startOfProtectedNote, String endOfProtectedNote){ + return withProtectedNote(Operator.BETWEEN, startOfProtectedNote, endOfProtectedNote); + } + public EntryRequest withProtectedNoteStartingWith(String protectedNote){ + return withProtectedNote(Operator.BEGIN_WITH, protectedNote); + } + public EntryRequest withProtectedNoteContaining(String protectedNote){ + return withProtectedNote(Operator.CONTAIN, protectedNote); + } + + public EntryRequest withProtectedNoteNotContaining(String protectedNote){ + return withProtectedNote(Operator.NOT_CONTAIN, protectedNote); + } + + public EntryRequest withProtectedNoteNotStartingWith(String protectedNote){ + return withProtectedNote(Operator.NOT_BEGIN_WITH, protectedNote); + } + + public EntryRequest withProtectedNoteEndingWith(String protectedNote){ + return withProtectedNote(Operator.END_WITH, protectedNote); + } + + public EntryRequest withProtectedNoteNotEndingWith(String protectedNote){ + return withProtectedNote(Operator.NOT_END_WITH, protectedNote); + } + + public EntryRequest withProtectedNoteIs(String protectedNote){ + return withProtectedNote(Operator.EQUAL, protectedNote); + } + + public EntryRequest withProtectedNoteSoundingLike(String protectedNote){ + return withProtectedNote(Operator.SOUNDS_LIKE, protectedNote); + } + + + + public EntryRequest filterByCreateTime(LocalDateTime... createTime){ + if (createTime == null || createTime.length == 0) { + throw new IllegalArgumentException("filterByCreateTime parameter createTime cannot be empty"); + } + return appendSearchCriteria(createCreateTimeCriteria(Operator.EQUAL, (Object[])createTime)); + } + + public EntryRequest withCreateTime(Operator operator, Object... values){ + return appendSearchCriteria(createCreateTimeCriteria(operator, values)); + } + + public EntryRequest withCreateTimeIsUnknown(){ + return withCreateTime(Operator.IS_NULL); + } + + public EntryRequest withCreateTimeIsKnown(){ + return withCreateTime(Operator.IS_NOT_NULL); + } + + public SearchCriteria createCreateTimeCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.CREATE_TIME_PROPERTY, operator, values); + } + + public EntryRequest withCreateTimeIs(LocalDateTime createTime){ + return withCreateTime(Operator.EQUAL, createTime); + } + + public EntryRequest withCreateTimeIsNot(LocalDateTime createTime){ + return withCreateTime(Operator.NOT_EQUAL, createTime); + } + + public EntryRequest withCreateTimeIn(LocalDateTime... createTime){ + return withCreateTime(Operator.IN, (Object[])createTime); + } + + public EntryRequest withCreateTimeNotIn(LocalDateTime... createTime){ + return withCreateTime(Operator.NOT_IN, (Object[])createTime); + } + public EntryRequest withCreateTimeGreaterThan(LocalDateTime createTime){ + return withCreateTime(Operator.GREATER_THAN, createTime); + } + + public EntryRequest withCreateTimeGreaterThanOrEqualTo(LocalDateTime createTime){ + return withCreateTime(Operator.GREATER_THAN_OR_EQUAL, createTime); + } + + public EntryRequest withCreateTimeLessThan(LocalDateTime createTime){ + return withCreateTime(Operator.LESS_THAN, createTime); + } + + public EntryRequest withCreateTimeLessThanOrEqualTo(LocalDateTime createTime){ + return withCreateTime(Operator.LESS_THAN_OR_EQUAL, createTime); + } + + public EntryRequest withCreateTimeBetween(LocalDateTime startOfCreateTime, LocalDateTime endOfCreateTime){ + return withCreateTime(Operator.BETWEEN, startOfCreateTime, endOfCreateTime); + } + public EntryRequest withCreateTimeBefore(LocalDateTime createTime){ + return withCreateTime(Operator.LESS_THAN, createTime); + } + + public EntryRequest withCreateTimeBefore(Date createTime){ + return withCreateTime(Operator.LESS_THAN, createTime); + } + + public EntryRequest withCreateTimeAfter(LocalDateTime createTime){ + return withCreateTime(Operator.GREATER_THAN, createTime); + } + + public EntryRequest withCreateTimeAfter(Date createTime){ + return withCreateTime(Operator.GREATER_THAN, createTime); + } + + public EntryRequest withCreateTimeBetween(Date startOfCreateTime, Date endOfCreateTime){ + return withCreateTime(Operator.BETWEEN, startOfCreateTime, endOfCreateTime); + } + + + + + public EntryRequest filterByUpdateTime(LocalDateTime... updateTime){ + if (updateTime == null || updateTime.length == 0) { + throw new IllegalArgumentException("filterByUpdateTime parameter updateTime cannot be empty"); + } + return appendSearchCriteria(createUpdateTimeCriteria(Operator.EQUAL, (Object[])updateTime)); + } + + public EntryRequest withUpdateTime(Operator operator, Object... values){ + return appendSearchCriteria(createUpdateTimeCriteria(operator, values)); + } + + public EntryRequest withUpdateTimeIsUnknown(){ + return withUpdateTime(Operator.IS_NULL); + } + + public EntryRequest withUpdateTimeIsKnown(){ + return withUpdateTime(Operator.IS_NOT_NULL); + } + + public SearchCriteria createUpdateTimeCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Entry.UPDATE_TIME_PROPERTY, operator, values); + } + + public EntryRequest withUpdateTimeIs(LocalDateTime updateTime){ + return withUpdateTime(Operator.EQUAL, updateTime); + } + + public EntryRequest withUpdateTimeIsNot(LocalDateTime updateTime){ + return withUpdateTime(Operator.NOT_EQUAL, updateTime); + } + + public EntryRequest withUpdateTimeIn(LocalDateTime... updateTime){ + return withUpdateTime(Operator.IN, (Object[])updateTime); + } + + public EntryRequest withUpdateTimeNotIn(LocalDateTime... updateTime){ + return withUpdateTime(Operator.NOT_IN, (Object[])updateTime); + } + public EntryRequest withUpdateTimeGreaterThan(LocalDateTime updateTime){ + return withUpdateTime(Operator.GREATER_THAN, updateTime); + } + + public EntryRequest withUpdateTimeGreaterThanOrEqualTo(LocalDateTime updateTime){ + return withUpdateTime(Operator.GREATER_THAN_OR_EQUAL, updateTime); + } + + public EntryRequest withUpdateTimeLessThan(LocalDateTime updateTime){ + return withUpdateTime(Operator.LESS_THAN, updateTime); + } + + public EntryRequest withUpdateTimeLessThanOrEqualTo(LocalDateTime updateTime){ + return withUpdateTime(Operator.LESS_THAN_OR_EQUAL, updateTime); + } + + public EntryRequest withUpdateTimeBetween(LocalDateTime startOfUpdateTime, LocalDateTime endOfUpdateTime){ + return withUpdateTime(Operator.BETWEEN, startOfUpdateTime, endOfUpdateTime); + } + public EntryRequest withUpdateTimeBefore(LocalDateTime updateTime){ + return withUpdateTime(Operator.LESS_THAN, updateTime); + } + + public EntryRequest withUpdateTimeBefore(Date updateTime){ + return withUpdateTime(Operator.LESS_THAN, updateTime); + } + + public EntryRequest withUpdateTimeAfter(LocalDateTime updateTime){ + return withUpdateTime(Operator.GREATER_THAN, updateTime); + } + + public EntryRequest withUpdateTimeAfter(Date updateTime){ + return withUpdateTime(Operator.GREATER_THAN, updateTime); + } + + public EntryRequest withUpdateTimeBetween(Date startOfUpdateTime, Date endOfUpdateTime){ + return withUpdateTime(Operator.BETWEEN, startOfUpdateTime, endOfUpdateTime); + } + + + + + 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 minQuantity(){ + return minQuantityAs(prefix("minOf",Entry.QUANTITY_PROPERTY)); + } + + public EntryRequest minQuantityAs(String retName){ + super.min(retName, Entry.QUANTITY_PROPERTY); + return this; + } + public EntryRequest maxQuantity(){ + return maxQuantityAs(prefix("maxOf",Entry.QUANTITY_PROPERTY)); + } + + public EntryRequest maxQuantityAs(String retName){ + super.max(retName, Entry.QUANTITY_PROPERTY); + return this; + } + public EntryRequest sumQuantity(){ + return sumQuantityAs(prefix("sumOf",Entry.QUANTITY_PROPERTY)); + } + + public EntryRequest sumQuantityAs(String retName){ + super.sum(retName, Entry.QUANTITY_PROPERTY); + return this; + } + public EntryRequest avgQuantity(){ + return avgQuantityAs(prefix("avgOf",Entry.QUANTITY_PROPERTY)); + } + + public EntryRequest avgQuantityAs(String retName){ + super.avg(retName, Entry.QUANTITY_PROPERTY); + return this; + } + public EntryRequest standardDeviationQuantity(){ + return standardDeviationQuantityAs(prefix("standardDeviationOf",Entry.QUANTITY_PROPERTY)); + } + + public EntryRequest standardDeviationQuantityAs(String retName){ + super.standardDeviation(retName, Entry.QUANTITY_PROPERTY); + return this; + } + public EntryRequest squareRootOfPopulationStandardDeviationQuantity(){ + return squareRootOfPopulationStandardDeviationQuantityAs(prefix("squareRootOfPopulationStandardDeviationOf",Entry.QUANTITY_PROPERTY)); + } + + public EntryRequest squareRootOfPopulationStandardDeviationQuantityAs(String retName){ + super.squareRootOfPopulationStandardDeviation(retName, Entry.QUANTITY_PROPERTY); + return this; + } + public EntryRequest sampleVarianceQuantity(){ + return sampleVarianceQuantityAs(prefix("sampleVarianceOf",Entry.QUANTITY_PROPERTY)); + } + + public EntryRequest sampleVarianceQuantityAs(String retName){ + super.sampleVariance(retName, Entry.QUANTITY_PROPERTY); + return this; + } + public EntryRequest samplePopulationVarianceQuantity(){ + return samplePopulationVarianceQuantityAs(prefix("samplePopulationVarianceOf",Entry.QUANTITY_PROPERTY)); + } + + public EntryRequest samplePopulationVarianceQuantityAs(String retName){ + super.samplePopulationVariance(retName, Entry.QUANTITY_PROPERTY); + 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 groupByQuantity(){ + groupBy(Entry.QUANTITY_PROPERTY); + return this; + } + + public EntryRequest groupByQuantityAs(String retName){ + groupBy(retName, Entry.QUANTITY_PROPERTY); + return this; + } + + public EntryRequest groupByQuantityWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.QUANTITY_PROPERTY, function); + return this; + } + + public EntryRequest groupByDescription(){ + groupBy(Entry.DESCRIPTION_PROPERTY); + return this; + } + + public EntryRequest groupByDescriptionAs(String retName){ + groupBy(retName, Entry.DESCRIPTION_PROPERTY); + return this; + } + + public EntryRequest groupByDescriptionWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.DESCRIPTION_PROPERTY, function); + return this; + } + + public EntryRequest groupByProtectedNote(){ + groupBy(Entry.PROTECTED_NOTE_PROPERTY); + return this; + } + + public EntryRequest groupByProtectedNoteAs(String retName){ + groupBy(retName, Entry.PROTECTED_NOTE_PROPERTY); + return this; + } + + public EntryRequest groupByProtectedNoteWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.PROTECTED_NOTE_PROPERTY, function); + return this; + } + + public EntryRequest groupByCreateTime(){ + groupBy(Entry.CREATE_TIME_PROPERTY); + return this; + } + + public EntryRequest groupByCreateTimeAs(String retName){ + groupBy(retName, Entry.CREATE_TIME_PROPERTY); + return this; + } + + public EntryRequest groupByCreateTimeWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.CREATE_TIME_PROPERTY, function); + return this; + } + + public EntryRequest groupByUpdateTime(){ + groupBy(Entry.UPDATE_TIME_PROPERTY); + return this; + } + + public EntryRequest groupByUpdateTimeAs(String retName){ + groupBy(retName, Entry.UPDATE_TIME_PROPERTY); + return this; + } + + public EntryRequest groupByUpdateTimeWithFunction(String retName, AggrFunction function){ + groupBy(retName, Entry.UPDATE_TIME_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 orderByQuantityAscending(){ + addOrderByAscending(Entry.QUANTITY_PROPERTY); + return this; + } + + public EntryRequest orderByQuantityDescending(){ + addOrderByDescending(Entry.QUANTITY_PROPERTY); + return this; + } + + public EntryRequest orderByDescriptionAscending(){ + addOrderByAscending(Entry.DESCRIPTION_PROPERTY); + return this; + } + + public EntryRequest orderByDescriptionDescending(){ + addOrderByDescending(Entry.DESCRIPTION_PROPERTY); + return this; + } + public EntryRequest orderByDescriptionAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Entry.DESCRIPTION_PROPERTY); + return this; + } + + public EntryRequest orderByDescriptionDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Entry.DESCRIPTION_PROPERTY); + return this; + } + public EntryRequest orderByProtectedNoteAscending(){ + addOrderByAscending(Entry.PROTECTED_NOTE_PROPERTY); + return this; + } + + public EntryRequest orderByProtectedNoteDescending(){ + addOrderByDescending(Entry.PROTECTED_NOTE_PROPERTY); + return this; + } + public EntryRequest orderByProtectedNoteAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Entry.PROTECTED_NOTE_PROPERTY); + return this; + } + + public EntryRequest orderByProtectedNoteDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Entry.PROTECTED_NOTE_PROPERTY); + return this; + } + public EntryRequest orderByCreateTimeAscending(){ + addOrderByAscending(Entry.CREATE_TIME_PROPERTY); + return this; + } + + public EntryRequest orderByCreateTimeDescending(){ + addOrderByDescending(Entry.CREATE_TIME_PROPERTY); + return this; + } + + public EntryRequest orderByUpdateTimeAscending(){ + addOrderByAscending(Entry.UPDATE_TIME_PROPERTY); + return this; + } + + public EntryRequest orderByUpdateTimeDescending(){ + addOrderByDescending(Entry.UPDATE_TIME_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/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/sampledata/SampleDataService.java b/examples/conformance/natural-messages/fixture/lib/src/main/java/com/example/checkernaturalmessageservice/sampledata/SampleDataService.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/conformance/natural-messages/fixture/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler b/examples/conformance/natural-messages/fixture/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler new file mode 100644 index 000000000..57a8cdc0e --- /dev/null +++ b/examples/conformance/natural-messages/fixture/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler @@ -0,0 +1,2 @@ + +com.example.checkernaturalmessageservice.EntityMetaRegistry \ No newline at end of file diff --git a/examples/conformance/natural-messages/fixture/model.xml b/examples/conformance/natural-messages/fixture/model.xml new file mode 100644 index 000000000..49beea4e7 --- /dev/null +++ b/examples/conformance/natural-messages/fixture/model.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/examples/conformance/natural-messages/fixture/teaql/model-provenance.json b/examples/conformance/natural-messages/fixture/teaql/model-provenance.json new file mode 100644 index 000000000..33aef104c --- /dev/null +++ b/examples/conformance/natural-messages/fixture/teaql/model-provenance.json @@ -0,0 +1 @@ +{"schemaVersion":1,"modelUuid":null,"revisionHash":"sha256:3f21a8d130e4d3f3006fbdaf1ef336ab8b4db99932935b966f6be220293ad287","generatorVersion":"061eb063"} \ No newline at end of file diff --git a/examples/conformance/natural-messages/model.xml b/examples/conformance/natural-messages/model.xml new file mode 100644 index 000000000..20e7bd802 --- /dev/null +++ b/examples/conformance/natural-messages/model.xml @@ -0,0 +1,5 @@ + + + + diff --git a/examples/conformance/natural-messages/verify-local.cjs b/examples/conformance/natural-messages/verify-local.cjs new file mode 100644 index 000000000..738c3a86c --- /dev/null +++ b/examples/conformance/natural-messages/verify-local.cjs @@ -0,0 +1,133 @@ +'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, 'automatic-fixture'); +const sha = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); +const requested = process.env.TEAQL_NATURAL_MESSAGES_EVIDENCE_DIR; +const output = requested ? path.resolve(requested) : fs.mkdtempSync(path.join(os.tmpdir(), 'teaql-natural-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-natural-build-')); +const runner = createOwnedRunner(); +const report = {schema: 'teaql.java-natural-checker-messages/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/') || ['teaql/model-provenance.json','teaql/checker-model.json'].includes(name)) && !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(__dirname, '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; + report.generation = JSON.parse(fs.readFileSync(path.join(fixture, 'generation.json'))); + assert.equal(report.generation.modelSha256, fixtureInputs.modelSha256); + report.schema = 'teaql.java-natural-checker-messages/v1'; + 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/naturalmessages'); + const sourceHash = crypto.createHash('sha256'); report.sourceHashes = {}; + for (const name of [...new Set(sourceFiles)].sort()) { + const file = path.join(repo, name); + assert(fs.existsSync(file) && fs.lstatSync(file).isFile(), 'source missing or not a regular file: ' + name); + assert.equal(fs.realpathSync(file), file, 'source path escapes through a link'); + const bytes = fs.readFileSync(file); sourceHash.update(name + '\0'); sourceHash.update(bytes); + report.sourceHashes[name] = sha(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, 'GeneratedNaturalMessagesTest.java')); + report.applicationSha256 = sha(app); fs.writeFileSync(path.join(tests, 'GeneratedNaturalMessagesTest.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.examplesnatural-checker-consumer${version}com.examplechecker-natural-message-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.testnatural-checker-reactor0pomruntimemodel/libconsumer'); + if (process.env.TEAQL_NATURAL_MESSAGES_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) { + const xml = file.replace(/\.txt$/, '.xml'), xmlFile = 'TEST-' + xml; + const bytes = fs.readFileSync(path.join(directory, xmlFile)); + const retained = path.join(output, 'unit-reports', module, xmlFile); + fs.mkdirSync(path.dirname(retained), {recursive: true}); fs.writeFileSync(retained, bytes); + report.unit.suites.push({module, file, tests: +summary[1], failures: +summary[2], errors: +summary[3], skipped: +summary[4], + report: path.relative(output, retained), sha256: sha(bytes)}); + } + } + } + assert(report.unit.suites.some(suite => suite.file.includes('NaturalCheckerMessageTest') && suite.tests >= 15)); + } + for (const round of [1, 2]) { + const command = [process.env.MAVEN || 'mvn', '-o', '-q', '-ntp', '-f', reactor, '-pl', ':natural-checker-consumer', '-am', + 'test', '-Dtest=GeneratedNaturalMessagesTest', '-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_NATURAL_MESSAGES_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)); + const frames = [...bytes.toString().matchAll(/^JAVA_NATURAL_CHECKER_SQLITE=(.+)$/gm)].map(match => JSON.parse(match[1])); + assert.equal(frames.length, 1); const facts = frames[0]; + assert(facts.passed && facts.typedQ && facts.typedE && facts.automaticMetadata && facts.originalGeneratedChecker && facts.unchangedParent); + assert.equal(facts.updatedAudits, 1); assert.equal(facts.customerRendererCalls, 1); assert.equal(facts.responses, 4); + assert.equal(facts.providerCallsOnRejection, 0); assert.equal(facts.transactionCallsOnRejection, 0); + const responses = [...bytes.toString().matchAll(/^JAVA_NATURAL_CHECKER_RESPONSE=(.+)$/gm)].map(match => JSON.parse(match[1])); + assert.equal(responses.length, 4); + for (const response of responses) { + assert.equal(response.errors.length, 1); + assert(response.errors.every(error => error.entityType === 'Entry' && error.instancePath === '/entryList/1/name')); + assert(!JSON.stringify(response).includes('密钥🔑' + 'x'.repeat(98)), 'private name reached the response'); + } + report.rounds[report.rounds.length - 1].responses = responses; + report.rounds[report.rounds.length - 1].facts = facts; + assert.deepEqual(inputs(), fixtureInputs, 'generated fixture changed'); + } + const oracle = cp.spawnSync('python3', ['-c', 'import json,sqlite3,sys; c=sqlite3.connect("file:"+sys.argv[1]+"?mode=ro",uri=True); print(json.dumps({"integrity":c.execute("pragma quick_check").fetchone()[0],"rows":c.execute("select name,version from entry_data order by id").fetchall()})); c.close()', path.join(output, 'fixture.sqlite')], {encoding:'utf8'}); + assert.equal(oracle.status, 0, oracle.stderr); report.databaseOracle = JSON.parse(oracle.stdout); + assert.deepEqual(report.databaseOracle, {integrity:'ok', rows:[['accepted',2],['second',1],['accepted',2],['second',1]]}); + const finalFiles = cp.execFileSync('git', ['-C', repo, 'ls-files', '-z', '--cached', '--others', '--exclude-standard']) + .toString().split('\0').filter(Boolean); + const finalHashes = {}; + for (const name of [...new Set(finalFiles)].sort()) { + const file = path.join(repo, name); assert(fs.lstatSync(file).isFile(), 'final source not a regular file: ' + name); + assert.equal(fs.realpathSync(file), file); finalHashes[name] = sha(fs.readFileSync(file)); + } + assert.deepEqual(finalHashes, report.sourceHashes, 'runtime, generated library or application changed during verification'); + report.sourceUnchanged = true; + report.sameDatabase = true; report.databaseSha256 = sha(fs.readFileSync(path.join(output, 'fixture.sqlite'))); + report.passed = true; console.log('PASS generated Java natural Checker messages through SQLite 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('Natural Checker evidence: ' + output); + } +} +main().catch(error => { console.error(error.stack); process.exitCode ||= 1; }); diff --git a/examples/conformance/pom.xml b/examples/conformance/pom.xml index 4374ef62f..9c5443e6d 100644 --- a/examples/conformance/pom.xml +++ b/examples/conformance/pom.xml @@ -16,7 +16,7 @@ 1.0.0 UTF-8 true - 1.556-RELEASE + 1.557-RELEASE diff --git a/examples/fix-e-alignment/verify-rollup-postgres.cjs b/examples/fix-e-alignment/verify-rollup-postgres.cjs new file mode 100644 index 000000000..edf0b3833 --- /dev/null +++ b/examples/fix-e-alignment/verify-rollup-postgres.cjs @@ -0,0 +1,169 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),cp=require('node:child_process'),crypto=require('node:crypto'),assert=require('node:assert/strict'); +const {createOwnedRunner,ownedBytes}=require('./owned-command.cjs'); +const hash=bytes=>crypto.createHash('sha256').update(bytes).digest('hex'); +async function main(){ + const [output,container,port]=process.argv.slice(2),repo=path.resolve(__dirname,'../..'); + assert(output&&path.isAbsolute(output)&&!fs.existsSync(output),'Use a fresh absolute evidence path'); + assert(container&&/^[a-zA-Z0-9_-]+$/.test(container)); assert(port&&/^\d{1,5}$/.test(port)&&Number(port)>0&&Number(port)<65536); + assert(fs.statfsSync(repo).bavail*fs.statfsSync(repo).bsize>4*1024**3); + const targets=fs.readdirSync(repo).filter(n=>fs.existsSync(path.join(repo,n,'pom.xml'))).map(n=>path.join(repo,n,'target')); + assert(targets.every(p=>!fs.existsSync(p)),'Use an isolated target-free Java worktree'); + fs.mkdirSync(output,{recursive:true}); + const runner=createOwnedRunner(),lock=path.join(os.tmpdir(),'teaql-rollup-postgres-279.lock');let ownsLock=false,secret=''; + const receipt={schema:'teaql.java-rollup-postgres/v1',passed:false,publication:false,commands:[], + commit:cp.execFileSync('git',['rev-parse','HEAD'],{cwd:repo,encoding:'utf8'}).trim()}; + const sql=(query,database='postgres')=>cp.execFileSync('docker',['exec','-i','-u','postgres',container,'psql','-X','-v','ON_ERROR_STOP=1','-d',database,'-At'], + {input:query,encoding:'utf8',stdio:['pipe','pipe','pipe']}).trim(); + const counts=xml=>Object.fromEntries(['tests','failures','errors','skipped'].map(k=>{const m=xml.match(new RegExp('\\b'+k+'="(\\d+)"'));assert(m);return[k,Number(m[1])];})); + try{ + const fd=fs.openSync(lock,'wx');ownsLock=true;try{fs.writeFileSync(fd,JSON.stringify({pid:process.pid,repo,output}));}finally{fs.closeSync(fd);} + const database='teaql_rollup_279',marker='TeaQL #279 owned layered statistics fixture'; + const exists=sql("SELECT COUNT(*) FROM pg_database WHERE datname='teaql_rollup_279';")==='1'; + if(exists)assert.equal(sql("SELECT COALESCE(shobj_description(oid,'pg_database'),'') FROM pg_database WHERE datname='teaql_rollup_279';"),marker); + else{sql('CREATE DATABASE teaql_rollup_279;');sql("COMMENT ON DATABASE teaql_rollup_279 IS 'TeaQL #279 owned layered statistics fixture';");} + receipt.database={database,container,port:Number(port),created:!exists,ownership:marker,retained:true,server:sql('SELECT version();')}; + // Fixture provisioning only, after the exact database ownership check. + sql('CREATE EXTENSION IF NOT EXISTS fuzzystrmatch;',database); + receipt.database.extensions={fuzzystrmatch:sql("SELECT extversion FROM pg_extension WHERE extname='fuzzystrmatch';",database)}; + assert(receipt.database.extensions.fuzzystrmatch,'SOUNDEX grouping requires the real PostgreSQL extension'); + secret=cp.execFileSync('docker',['exec',container,'sh','-c','printf %s "$POSTGRES_PASSWORD"'],{encoding:'utf8',stdio:['ignore','pipe','pipe']});assert(secret); + const env={...process.env,TEAQL_TEST_POSTGRES_JDBC_URL:'jdbc:postgresql://127.0.0.1:'+port+'/'+database, + TEAQL_TEST_POSTGRES_USER:'postgres',TEAQL_TEST_POSTGRES_PASSWORD:secret}; + receipt.sourceHashes={}; + for(const file of ['pom.xml','teaql-sql-portable/pom.xml', + 'teaql-postgres/pom.xml', + 'teaql-postgres/src/test/java/io/teaql/postgres/PostgresStatisticalDiagnosticsTest.java', + 'teaql-postgres/src/main/java/io/teaql/core/postgres/PostgresDataServiceExecutor.java', + 'teaql-data-service-sql/src/main/java/io/teaql/dataservice/sql/SqlDataServiceExecutor.java', + 'teaql-provider-jdbc/src/main/java/io/teaql/provider/jdbc/JdbcSqlExecutor.java', + 'teaql-core/src/main/java/io/teaql/core/QueryRequestTraceNode.java', + 'teaql-core/src/main/java/io/teaql/core/QueryRequestScope.java', + 'teaql-core/src/main/java/io/teaql/core/ExecutionMetadata.java', + 'teaql-core/src/main/java/io/teaql/core/SqlExecutionTrace.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/LogPrivacy.java', + 'teaql-runtime/src/test/java/io/teaql/runtime/LogPrivacyTest.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/SqlLogProjectionCache.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/SqlDiagnosticEvent.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/DefaultTextRuntimeLogSink.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/SensitiveDiagnosticTextRuntimeLogSink.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/SqlParameters.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/internal/TempRequest.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/LayeredAggregationTest.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/PostgresLayeredAggregationIT.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/LayeredAggregation.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/internal/StatisticalGroupingExpression.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/internal/StatisticalIntegerOperand.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/internal/StatisticalMeasureExpression.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/internal/StatisticalMeasureExpressionTest.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/internal/StatisticalIntegerOperandTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/internal/StatisticalOrderExpression.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/internal/StatisticalOrderExpressionTest.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/internal/StatisticalGroupingExpressionTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/SqlAstCompiler.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/SqlCompilerDelegate.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/SQLColumnResolver.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/expression/PropertyParser.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/dialect/SqlDialect.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/PortableSQLDatabaseTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/PortableSQLRepository.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/StatisticalResultFilter.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/expression/AggrExpressionParser.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/expression/SubQueryParser.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/dialect/PostgreSqlDialect.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/StatisticsRequestPreparation.java', + 'teaql-core/src/main/java/io/teaql/core/BaseRequest.java','teaql-core/src/main/java/io/teaql/core/AggrFunction.java', + 'teaql-core/src/main/java/io/teaql/core/SubQuerySearchCriteria.java','teaql-core/src/main/java/io/teaql/core/QueryNavigation.java', + 'teaql-core/src/test/java/io/teaql/core/QueryNavigationTest.java', + 'teaql-core/src/main/java/io/teaql/core/QueryRequestSnapshot.java', + 'teaql-core/src/main/java/io/teaql/core/QueryRequestGraphCopy.java', + 'teaql-core/src/main/java/io/teaql/core/SearchRequest.java', + 'teaql-core/src/test/java/io/teaql/core/QueryRequestSnapshotIsolationTest.java', + 'teaql-runtime/src/test/java/io/teaql/runtime/RequestedListCountTest.java', + 'teaql-runtime/src/test/java/io/teaql/runtime/TeaQLRuntimeTest.java', + 'examples/fix-e-alignment/verify-rollup-postgres.cjs']){ + const bytes=fs.readFileSync(path.join(repo,file));receipt.sourceHashes[file]=hash(bytes); + const target=path.join(output,'sources',file);fs.mkdirSync(path.dirname(target),{recursive:true});fs.writeFileSync(target,bytes); + } + async function run(command,name,runEnv=env){ + const fd=fs.openSync(path.join(output,name),'wx');let result; + try{result=await runner.run(command,{cwd:repo,env:runEnv,timeout:900000,stdio:['ignore',fd,fd]});}finally{fs.closeSync(fd);} + const bytes=fs.readFileSync(path.join(output,name));receipt.commands.push({command,result,log:name,logSha256:hash(bytes)}); + assert.equal(result.status,0,bytes.toString().slice(-5000));return bytes.toString(); + } + receipt.rounds=[]; + for(const round of [1,2]){ + const log=await run([process.env.MAVEN||'mvn','-o','-B','-pl','teaql-sql-portable','-am','-Dtest=PostgresLayeredAggregationIT', + '-Dsurefire.failIfNoSpecifiedTests=false','test'],'postgres-round-'+round+'.log'); + const report=path.join(repo,'teaql-sql-portable/target/surefire-reports/TEST-io.teaql.core.sql.portable.PostgresLayeredAggregationIT.xml'); + const xml=fs.readFileSync(report,'utf8'),junit=counts(xml);fs.copyFileSync(report,path.join(output,'junit-round-'+round+'.xml')); + assert.deepEqual(junit,{tests:66,failures:0,errors:0,skipped:0}); + const observations=log.split(/\r?\n/).filter(l=>l.startsWith('JAVA_POSTGRES_ROLLUP=')).map(l=>JSON.parse(l.slice('JAVA_POSTGRES_ROLLUP='.length))); + assert.deepEqual(observations.map(o=>o.case).sort(),['extended-owner-grain','empty-extended','all-null-source-singleton-parent','variance-having', + ...['positive','negative','neighboring'].flatMap(kind=>['ordinary','parent','nested','having-ordinary','having-parent','having-nested'].map(layer=>'numeric-'+layer+'-'+kind)), + 'gbk-ordinary','gbk-parent','gbk-nested','gbk-binary-ordinary','gbk-binary-parent','bitwise-expression-fields','bitwise-expression-parameters', + 'expression-measure-owner-grain','expression-measure-transforms'].sort()); + receipt.rounds.push({round,junit,observations}); + } + receipt.diagnosticRounds=[]; + for(const round of [1,2]){ + const log=await run([process.env.MAVEN||'mvn','-o','-B','-pl','teaql-postgres','-am', + '-Dtest=PostgresStatisticalDiagnosticsTest','-Dsurefire.failIfNoSpecifiedTests=false','test'], + 'postgres-diagnostics-'+round+'.log'); + const report=path.join(repo,'teaql-postgres/target/surefire-reports/TEST-io.teaql.postgres.PostgresStatisticalDiagnosticsTest.xml'); + const xml=fs.readFileSync(report,'utf8'),junit=counts(xml);fs.copyFileSync(report,path.join(output,'diagnostic-junit-'+round+'.xml')); + assert.deepEqual(junit,{tests:3,failures:0,errors:0,skipped:0}); + const observations=log.split(/\r?\n/).filter(l=>l.startsWith('JAVA_POSTGRES_DIAGNOSTICS=')) + .map(l=>JSON.parse(l.slice('JAVA_POSTGRES_DIAGNOSTICS='.length))); + assert.equal(observations.length,2,'Missing repeated instrumented provider logs'); + for(const observation of observations){ + assert.equal(observation.physicalStatements,1);assert.equal(observation.schools,5);assert.equal(observation.total,3300); + assert.deepEqual(observation.telemetryTree,observation.requestTree); + assert(!observation.text.includes('PRIVATE-PLATFORM-279'),'Raw masked value reached text log'); + assert(observation.text.includes('/* masked */'),'Missing masked parameter marker'); + } + const failures=log.split(/\r?\n/).filter(l=>l.startsWith('JAVA_POSTGRES_FAILURE_DIAGNOSTICS=')) + .map(l=>JSON.parse(l.slice('JAVA_POSTGRES_FAILURE_DIAGNOSTICS='.length))); + assert.equal(failures.length,2,'Missing repeated real provider failure diagnostics'); + for(const failure of failures){ + assert.equal(failure.physicalStatements,1);assert.equal(failure.outcome,'failure'); + assert.deepEqual(failure.telemetryTree,failure.requestTree);assert(!failure.text.includes('PRIVATE-PLATFORM-279')); + } + const streams=log.split(/\r?\n/).filter(l=>l.startsWith('JAVA_POSTGRES_STREAM_DIAGNOSTICS=')) + .map(l=>JSON.parse(l.slice('JAVA_POSTGRES_STREAM_DIAGNOSTICS='.length))); + assert.equal(streams.length,4,'Missing success and early-close cursor diagnostics'); + for(const stream of streams){ + assert.equal(stream.physicalStatements,1);assert(['success','cancelled'].includes(stream.outcome)); + assert.equal(stream.rowsConsumed,stream.outcome==='success'?5:1);assert.deepEqual(stream.telemetryTree,stream.requestTree); + assert(!stream.text.includes('PRIVATE-PLATFORM-279')); + } + const denials=log.split(/\r?\n/).filter(l=>l.startsWith('JAVA_POSTGRES_STREAM_DENIAL=')) + .map(l=>JSON.parse(l.slice('JAVA_POSTGRES_STREAM_DENIAL='.length))); + assert.equal(denials.length,2);for(const denial of denials)assert.equal(denial.physicalStatements,0); + receipt.diagnosticRounds.push({round,junit,observations,failures,streams,denials}); + } + receipt.remainingFixtureTables=Number(sql("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name IN('rollup_school','rollup_kind','rollup_platform');",database)); + assert.equal(receipt.remainingFixtureTables,0,'Each test must roll back its own fixture, not leave tables for the next test'); + const nativeEnv={...process.env};delete nativeEnv.TEAQL_TEST_POSTGRES_JDBC_URL;delete nativeEnv.TEAQL_TEST_POSTGRES_PASSWORD;delete nativeEnv.TEAQL_TEST_POSTGRES_USER; + await run([process.env.MAVEN||'mvn','-o','-B','-pl','teaql-sql-portable','-am','test'],'native-regression.log',nativeEnv); + receipt.nativeSuites={}; + const nativeModules=new Set(['teaql-utils','teaql-dynamic-fields-api','teaql-core','teaql-runtime','teaql-sql-portable']); + for(const target of targets){if(!nativeModules.has(path.basename(path.dirname(target))))continue; + const dir=path.join(target,'surefire-reports');if(!fs.existsSync(dir))continue; + receipt.nativeSuites[path.basename(path.dirname(target))]=fs.readdirSync(dir).filter(n=>/^TEST-.*\.xml$/.test(n)&&!n.includes('PostgresLayeredAggregationIT')) + .map(name=>({name,...counts(fs.readFileSync(path.join(dir,name),'utf8'))}));} + const suites=Object.values(receipt.nativeSuites).flat();assert(suites.every(x=>x.failures===0&&x.errors===0)); + receipt.nativeTestsPassed=suites.reduce((n,s)=>n+s.tests-s.skipped,0);assert(receipt.nativeTestsPassed>=1118); + for(const[file,expected]of Object.entries(receipt.sourceHashes))assert.equal(hash(fs.readFileSync(path.join(repo,file))),expected,'Source changed: '+file); + receipt.sameDatabase=true;receipt.passed=true; + }catch(error){receipt.error=secret?String(error.message).split(secret).join('[REDACTED]'):error.message;process.exitCode=1;} + finally{ + if(runner.safeToClean){receipt.cleanup=[];for(const target of targets)if(fs.existsSync(target)){receipt.cleanup.push({path:target,bytes:ownedBytes(target)});fs.rmSync(target,{recursive:true});} + if(ownsLock)fs.unlinkSync(lock); + }else receipt.unsafeRetention={targets,processGroup:runner.unsafeGroup,lock:ownsLock?lock:undefined}; + runner.dispose();fs.writeFileSync(path.join(output,'receipt.json'),JSON.stringify(receipt,null,2)+'\n'); + process.stdout.write(JSON.stringify({passed:receipt.passed,evidence:output,error:receipt.error?.slice(-1000),rounds:receipt.rounds?.map(x=>x.junit), + nativeTestsPassed:receipt.nativeTestsPassed,removedBytes:receipt.cleanup?.reduce((n,x)=>n+x.bytes,0)})+'\n'); + } +} +main().catch(e=>{console.error(e.message);process.exitCode=1;}); diff --git a/examples/fix-e-alignment/verify-rollup.cjs b/examples/fix-e-alignment/verify-rollup.cjs new file mode 100644 index 000000000..7963474a2 --- /dev/null +++ b/examples/fix-e-alignment/verify-rollup.cjs @@ -0,0 +1,126 @@ +'use strict'; +// A local-source gate: never installs/publishes Maven artifacts. Only outputs +// created in this initially target-free worktree are eligible for cleanup. +const fs = require('node:fs'), path = require('node:path'), assert = require('node:assert/strict'); +const cp = require('node:child_process'), crypto = require('node:crypto'); +const {createOwnedRunner, ownedBytes} = require('./owned-command.cjs'); +const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); +async function main() { + const repo = path.resolve(__dirname, '../..'); + const output = process.argv[2]; + assert(output && path.isAbsolute(output) && !fs.existsSync(output), 'Supply a fresh absolute evidence path'); + const targets = fs.readdirSync(repo).filter(name => fs.existsSync(path.join(repo, name, 'pom.xml'))) + .map(name => path.join(repo, name, 'target')); + assert(targets.every(target => !fs.existsSync(target)), 'Use an isolated worktree without Maven targets'); + assert(fs.statfsSync(repo).bavail * fs.statfsSync(repo).bsize > 4 * 1024 ** 3, 'Need 4 GiB free'); + fs.mkdirSync(output, {recursive: true}); + const receipt = {schema: 'teaql.java-rollup-acceptance/v1', passed: false, publication: false, + commit: cp.execFileSync('git', ['rev-parse', 'HEAD'], {cwd: repo, encoding: 'utf8'}).trim()}; + const runner = createOwnedRunner(); + try { + const source = 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/PortableSQLDatabaseTest.java'; + receipt.testSourceSha256 = hash(fs.readFileSync(path.join(repo, source))); + receipt.sourceHashes = {}; + for (const name of [source, 'teaql-runtime/src/main/java/io/teaql/runtime/TeaQLRuntime.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/LayeredAggregationTest.java', + 'teaql-core/src/main/java/io/teaql/core/SearchRequest.java', + 'teaql-core/src/main/java/io/teaql/core/BaseRequest.java', + 'teaql-core/src/main/java/io/teaql/core/SubQuerySearchCriteria.java', + 'teaql-core/src/main/java/io/teaql/core/QueryRequestGraphCopy.java', + 'teaql-core/src/main/java/io/teaql/core/QueryNavigation.java', + 'teaql-core/src/test/java/io/teaql/core/QueryNavigationTest.java', + 'teaql-core/src/main/java/io/teaql/core/QueryRequestSnapshot.java', + 'teaql-core/src/test/java/io/teaql/core/BaseRequestTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/StatisticalResultFilter.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/StatisticalResultFilterTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/SqlAstCompiler.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/expression/AggrExpressionParser.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/expression/SubQueryParser.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/expression/AggrExpressionParserTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/SqlLikeIntent.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/dialect/PostgreSqlDialect.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/PostgreSqlIdentifierTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/PortableSQLRepository.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/LayeredAggregation.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/StatisticsRequestPreparation.java', + 'examples/fix-e-alignment/verify-rollup.cjs']) { + const bytes = fs.readFileSync(path.join(repo, name)); receipt.sourceHashes[name] = hash(bytes); + const target = path.join(output, 'sources', name); fs.mkdirSync(path.dirname(target), {recursive: true}); + fs.writeFileSync(target, bytes); + } + fs.writeFileSync(path.join(output, 'source-changes.patch'), + cp.execFileSync('git', ['diff', '--binary', 'HEAD'], {cwd: repo})); + const command = [process.env.MAVEN || 'mvn', '-o', '-B', '-pl', 'teaql-sql-portable', '-am', + '-Dtest=PortableSQLDatabaseTest#rollup*,LayeredAggregationTest,StatisticalResultFilterTest,AggrExpressionParserTest', '-Dsurefire.failIfNoSpecifiedTests=false', 'test']; + const fd = fs.openSync(path.join(output, 'test.log'), 'wx'); + try { receipt.result = await runner.run(command, {cwd: repo, env: process.env, + timeout: 900000, stdio: ['ignore', fd, fd]}); } + finally { fs.closeSync(fd); } + receipt.command = command; + receipt.logSha256 = hash(fs.readFileSync(path.join(output, 'test.log'))); + const report = path.join(repo, 'teaql-sql-portable/target/surefire-reports/TEST-io.teaql.core.sql.portable.PortableSQLDatabaseTest.xml'); + assert(fs.existsSync(report), 'No JUnit report: this is not a verified runtime result'); + fs.copyFileSync(report, path.join(output, 'junit.xml')); + const xml = fs.readFileSync(report, 'utf8'); + const counts = xml => Object.fromEntries(['tests', 'failures', 'errors', 'skipped'].map(name => { + const match = xml.match(new RegExp('\\b' + name + '="(\\d+)"')); + assert(match, 'Missing JUnit count: ' + name); return [name, Number(match[1])]; + })); + const layeredReport = path.join(path.dirname(report), 'TEST-io.teaql.core.sql.portable.LayeredAggregationTest.xml'); + assert(fs.existsSync(layeredReport), 'No layered statistics report'); + fs.copyFileSync(layeredReport, path.join(output, 'junit-layered.xml')); + const filterReport = path.join(path.dirname(report), 'TEST-io.teaql.core.sql.StatisticalResultFilterTest.xml'); + assert(fs.existsSync(filterReport), 'No statistical filter security report'); + fs.copyFileSync(filterReport, path.join(output, 'junit-filter.xml')); + const parserReport = path.join(path.dirname(report), 'TEST-io.teaql.core.sql.expression.AggrExpressionParserTest.xml'); + assert(fs.existsSync(parserReport), 'No aggregate operator compiler report'); + fs.copyFileSync(parserReport, path.join(output, 'junit-operators.xml')); + receipt.focusedSuites = [counts(xml), counts(fs.readFileSync(layeredReport, 'utf8')), counts(fs.readFileSync(filterReport, 'utf8')), + counts(fs.readFileSync(parserReport, 'utf8'))]; + receipt.junit = Object.fromEntries(['tests', 'failures', 'errors', 'skipped'].map(key => + [key, receipt.focusedSuites.reduce((sum, suite) => sum + suite[key], 0)])); + receipt.passed = receipt.result.status === 0 && receipt.junit.tests >= 36 + && ['failures', 'errors', 'skipped'].every(name => receipt.junit[name] === 0); + assert(receipt.passed, 'Roll-up acceptance failed: ' + JSON.stringify(receipt.junit)); + receipt.passed = false; + const regressionCommand = [process.env.MAVEN || 'mvn', '-o', '-B', '-pl', 'teaql-sql-portable', '-am', 'test']; + const regressionFd = fs.openSync(path.join(output, 'native-regression.log'), 'wx'); let regression; + try { regression = await runner.run(regressionCommand, {cwd: repo, env: process.env, + timeout: 900000, stdio: ['ignore', regressionFd, regressionFd]}); } + finally { fs.closeSync(regressionFd); } + const suites = {}; + for (const target of targets) { + const directory = path.join(target, 'surefire-reports'); + if (!fs.existsSync(directory)) continue; + const files = fs.readdirSync(directory).filter(name => /^TEST-.*\.xml$/.test(name)); + suites[path.basename(path.dirname(target))] = files.map(name => ({name, ...counts(fs.readFileSync(path.join(directory, name), 'utf8'))})); + } + receipt.nativeRegression = {command: regressionCommand, result: regression, suites, + logSha256: hash(fs.readFileSync(path.join(output, 'native-regression.log')))}; + assert.equal(regression.status, 0, 'Native regression failed'); + for (const module of ['teaql-core', 'teaql-runtime', 'teaql-sql-portable']) { + assert(suites[module]?.reduce((sum, suite) => sum + suite.tests, 0) >= 20, 'Missing complete native suite: ' + module); + } + assert(Object.values(suites).flat().every(suite => suite.failures === 0 && suite.errors === 0), 'Native JUnit failure'); + for (const [name, expected] of Object.entries(receipt.sourceHashes)) { + assert.equal(hash(fs.readFileSync(path.join(repo, name))), expected, 'Source changed during verification: ' + name); + } + receipt.passed = true; + } catch (error) { + receipt.error = error.message; process.exitCode = runner.interrupted === 'SIGINT' ? 130 : 1; + } finally { + receipt.cleanup = []; + if (runner.safeToClean) { + for (const target of targets) if (fs.existsSync(target)) { + const bytes = ownedBytes(target); fs.rmSync(target, {recursive: true}); + receipt.cleanup.push({path: target, bytes}); + } + } else receipt.unsafeRetention = {targets, processGroup: runner.unsafeGroup}; + runner.dispose(); + fs.writeFileSync(path.join(output, 'receipt.json'), JSON.stringify(receipt, null, 2) + '\n'); + process.stdout.write(JSON.stringify({passed: receipt.passed, evidence: output, focused: receipt.junit, + nativeTests: Object.values(receipt.nativeRegression?.suites || {}).flat().reduce((sum, suite) => sum + suite.tests, 0), + error: receipt.error, removedBytes: receipt.cleanup.reduce((sum, item) => sum + item.bytes, 0)}) + '\n'); + } +} +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/examples/fix-e-alignment/verify-sqlite-statistics.cjs b/examples/fix-e-alignment/verify-sqlite-statistics.cjs new file mode 100644 index 000000000..e4d27f66f --- /dev/null +++ b/examples/fix-e-alignment/verify-sqlite-statistics.cjs @@ -0,0 +1,181 @@ +'use strict'; +const fs = require('node:fs'), path = require('node:path'), assert = require('node:assert/strict'); +const cp = require('node:child_process'), crypto = require('node:crypto'); +const {createOwnedRunner, ownedBytes} = require('./owned-command.cjs'); +const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); +const counts = xml => Object.fromEntries(['tests', 'failures', 'errors', 'skipped'].map(key => { + const match = xml.match(new RegExp('\\b' + key + '="(\\d+)"')); + assert(match, 'Missing JUnit count: ' + key); return [key, Number(match[1])]; +})); +async function main() { + const repo = path.resolve(__dirname, '../..'), output = process.argv[2]; + assert(output && path.isAbsolute(output) && !fs.existsSync(output), 'Supply a fresh absolute evidence path'); + const targets = fs.readdirSync(repo).filter(name => fs.existsSync(path.join(repo, name, 'pom.xml'))) + .map(name => path.join(repo, name, 'target')); + assert(targets.every(target => !fs.existsSync(target)), 'Isolated target-free worktree required'); + assert(fs.statfsSync(repo).bavail * fs.statfsSync(repo).bsize > 4 * 1024 ** 3, 'Need 4 GiB free'); + fs.mkdirSync(output, {recursive: true}); + const runner = createOwnedRunner(); + const receipt = {schema: 'teaql.java-sqlite-statistics/v1', passed: false, publication: false, + commit: cp.execFileSync('git', ['rev-parse', 'HEAD'], {cwd: repo, encoding: 'utf8'}).trim(), + sourceHashes: {}, commands: []}; + try { + for (const name of ['pom.xml', 'teaql-sqlite/pom.xml', + 'teaql-core/src/main/java/io/teaql/core/AggrFunction.java', + 'teaql-core/src/main/java/io/teaql/core/BaseRequest.java', + 'teaql-core/src/main/java/io/teaql/core/QueryRequestTraceNode.java', + 'teaql-core/src/main/java/io/teaql/core/QueryRequestScope.java', + 'teaql-core/src/main/java/io/teaql/core/ExecutionMetadata.java', + 'teaql-core/src/main/java/io/teaql/core/SqlExecutionTrace.java', + 'teaql-core/src/test/java/io/teaql/core/QueryRequestTraceNodeTest.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/LogPrivacy.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/SqlLogProjectionCache.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/SqlDiagnosticEvent.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/DefaultTextRuntimeLogSink.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/SensitiveDiagnosticTextRuntimeLogSink.java', + 'teaql-runtime/src/test/java/io/teaql/runtime/LogPrivacyTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/SqlParameters.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/expression/SubQueryParser.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/internal/TempRequest.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/TeaQLRuntime.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/StatisticsRequestPreparation.java', + 'teaql-runtime/src/test/java/io/teaql/runtime/StatisticalMembershipPreparationTest.java', + 'teaql-core/src/main/java/io/teaql/core/QueryRequestSnapshot.java', + 'teaql-core/src/main/java/io/teaql/core/QueryRequestGraphCopy.java', + 'teaql-core/src/main/java/io/teaql/core/SearchRequest.java', + 'teaql-core/src/test/java/io/teaql/core/QueryRequestSnapshotIsolationTest.java', + 'teaql-core/src/test/java/io/teaql/core/QueryCriteriaAlternativesTest.java', + 'teaql-runtime/src/test/java/io/teaql/runtime/RequestedListCountTest.java', + 'teaql-runtime/src/test/java/io/teaql/runtime/TeaQLRuntimeTest.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/StatisticsRequestPreparation.java', + 'teaql-sqlite/src/main/java/io/teaql/core/sqlite/SqliteDataServiceExecutor.java', + 'teaql-sqlite/src/main/java/io/teaql/core/sqlite/SqliteDialect.java', + 'teaql-sqlite/src/main/java/io/teaql/core/sqlite/SqliteDecimalFunctions.java', + 'teaql-sqlite/src/test/java/io/teaql/core/sqlite/SqliteStatisticalDecimalTest.java', + 'teaql-sqlite/src/main/java/io/teaql/core/sqlite/SqliteStatisticalFunctions.java', + 'teaql-sqlite/src/main/java/io/teaql/core/sqlite/SqliteGbkEncoding.java', + 'teaql-sqlite/src/main/java/io/teaql/core/sqlite/SqliteGbkFunctions.java', + 'teaql-sqlite/src/test/java/io/teaql/core/sqlite/SqliteStatisticalFunctionsTest.java', + 'teaql-sqlite/src/test/java/io/teaql/core/sqlite/SqliteGbkFunctionsTest.java', + 'teaql-provider-jdbc/src/main/java/io/teaql/provider/jdbc/JdbcSqlExecutor.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/LayeredAggregation.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/internal/StatisticalGroupingExpression.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/internal/StatisticalIntegerOperand.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/internal/StatisticalMeasureExpression.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/internal/StatisticalMeasureExpressionTest.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/internal/StatisticalIntegerOperandTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/internal/StatisticalOrderExpression.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/internal/StatisticalOrderExpressionTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/dialect/PostgreSqlDialect.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/internal/StatisticalGroupingExpressionTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/PortableSQLRepository.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/PortableSQLDataService.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/expression/AggrExpressionParser.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/expression/AggrExpressionParserTest.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/LayeredAggregationTest.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/InheritedSelectTableFlagTest.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/PortableSQLDatabaseTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/SqlAstCompiler.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/StatisticalResultFilter.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/StatisticalResultFilterTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/SQLColumnResolver.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/expression/PropertyParser.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/SqlCompilerDelegate.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/dialect/SqlDialect.java', + 'teaql-sqlite/src/test/java/io/teaql/sqlite/DerivedQueryTraceSqliteTest.java', + 'examples/fix-e-alignment/verify-sqlite-statistics.cjs', + 'examples/fix-e-alignment/owned-command.cjs']) { + if (!fs.existsSync(path.join(repo, name))) { + assert(name.endsWith('/SqliteStatisticalFunctions.java'), 'Missing source: ' + name); + continue; + } + const bytes = fs.readFileSync(path.join(repo, name)); receipt.sourceHashes[name] = hash(bytes); + const target = path.join(output, 'sources', name); + fs.mkdirSync(path.dirname(target), {recursive: true}); fs.writeFileSync(target, bytes); + } + fs.writeFileSync(path.join(output, 'source-changes.patch'), + cp.execFileSync('git', ['diff', '--binary', 'HEAD'], {cwd: repo})); + async function execute(label, options) { + const command = [process.env.MAVEN || 'mvn', '-o', '-B', '-pl', 'teaql-sqlite', '-am', ...options, 'test']; + const log = path.join(output, label + '.log'), fd = fs.openSync(log, 'wx'); + let result; + try { result = await runner.run(command, {cwd: repo, env: process.env, + timeout: 900000, stdio: ['ignore', fd, fd]}); } + finally { fs.closeSync(fd); } + const run = {command, result, logSha256: hash(fs.readFileSync(log)), suites: {}}; + receipt.commands.push(run); + for (const target of targets) { + const directory = path.join(target, 'surefire-reports'); + if (!fs.existsSync(directory)) continue; + const module = path.basename(path.dirname(target)); + const files = fs.readdirSync(directory).filter(name => /^TEST-.*\.xml$/.test(name)); + run.suites[module] = files.map(name => { + const bytes = fs.readFileSync(path.join(directory, name)); + const saved = path.join(output, label, module, name); + fs.mkdirSync(path.dirname(saved), {recursive: true}); fs.writeFileSync(saved, bytes); + return {name, ...counts(bytes.toString('utf8'))}; + }); + } + assert.equal(result.status, 0, label + ' command failed'); + assert(Object.values(run.suites).flat().every(s => !s.failures && !s.errors && !s.skipped), 'JUnit failure/skip'); + return run; + } + for (let round = 1; round <= 2; round++) { + const run = await execute('focused-' + round, + ['-Dtest=QueryRequestTraceNodeTest,LogPrivacyTest,QueryRequestSnapshotIsolationTest,QueryCriteriaAlternativesTest,SqliteStatisticalFunctionsTest,SqliteGbkFunctionsTest,SqliteStatisticalDecimalTest,StatisticalResultFilterTest,DerivedQueryTraceSqliteTest#loadedCollectionFacetsRetainPerParentMembershipCountsAndRequestedEmpty,LayeredAggregationTest,AggrExpressionParserTest,StatisticalGroupingExpressionTest,StatisticalIntegerOperandTest,StatisticalMeasureExpressionTest,InheritedSelectTableFlagTest,StatisticalMembershipPreparationTest', '-Dsurefire.failIfNoSpecifiedTests=false']); + assert.equal(run.suites['teaql-core']?.find(s => s.name.endsWith('.QueryRequestTraceNodeTest.xml'))?.tests, + 4, 'Missing identity-based detached request tree acceptance'); + assert(run.suites['teaql-runtime']?.find(s => s.name.endsWith('.LogPrivacyTest.xml'))?.tests >= 12, + 'Missing request tree mask, debug downgrade and telemetry projection acceptance'); + assert.equal(run.suites['teaql-core']?.find(s => s.name.endsWith('.QueryRequestSnapshotIsolationTest.xml'))?.tests, + 5, 'Missing independent graph snapshot/copy acceptance'); + assert.equal(run.suites['teaql-core']?.find(s => s.name.endsWith('.QueryCriteriaAlternativesTest.xml'))?.tests, + 6, 'Missing criteria alternative composition acceptance'); + assert.equal(run.suites['teaql-sql-portable']?.find(s => s.name.endsWith('.InheritedSelectTableFlagTest.xml'))?.tests, + 3, 'Missing inherited discriminator table qualification'); + assert.equal(run.suites['teaql-runtime']?.find(s => s.name.endsWith('.StatisticalMembershipPreparationTest.xml'))?.tests, + 9, 'Missing statistical membership preparation and ordinary-wrapper policy at entity execution boundaries'); + assert.equal(run.suites['teaql-sqlite']?.find(s => s.name.endsWith('.SqliteStatisticalFunctionsTest.xml'))?.tests, + 21, 'Missing statistical kernels, typed expressions, binary grouping and combined request logs'); + assert.equal(run.suites['teaql-sqlite']?.find(s => s.name.endsWith('.SqliteGbkFunctionsTest.xml'))?.tests, + 3, 'Missing GBK byte profile, error privacy and per-connection installation'); + assert.equal(run.suites['teaql-sqlite']?.find(s => s.name.endsWith('.SqliteStatisticalDecimalTest.xml'))?.tests, + 9, 'Missing exact Decimal sorting, range, HAVING and unsupported-function tests'); + assert.equal(run.suites['teaql-sqlite']?.find(s => s.name.endsWith('.DerivedQueryTraceSqliteTest.xml'))?.tests, + 1, 'Missing real collection Facet regression'); + assert.equal(run.suites['teaql-sql-portable']?.find(s => s.name.endsWith('.LayeredAggregationTest.xml'))?.tests, + 57, 'Missing complete shared roll-up statistics and real combined request-binding suite'); + assert.equal(run.suites['teaql-sql-portable']?.find(s=>s.name.endsWith('.StatisticalMeasureExpressionTest.xml'))?.tests, + 5,'Missing bounded statistical scalar typing'); + assert.equal(run.suites['teaql-sql-portable']?.find(s => s.name.endsWith('.StatisticalGroupingExpressionTest.xml'))?.tests, + 4, 'Missing grouping expression safety and binary GBK compatibility tests'); + assert.equal(run.suites['teaql-sql-portable']?.find(s=>s.name.endsWith('.StatisticalIntegerOperandTest.xml'))?.tests, + 4,'Missing bounded integer expression typing and custom-parser acceptance'); + assert.equal(run.suites['teaql-sql-portable']?.find(s => s.name.endsWith('.AggrExpressionParserTest.xml'))?.tests, + 3, 'Missing aggregate operator compiler regression'); + assert.equal(run.suites['teaql-sql-portable']?.find(s => s.name.endsWith('.StatisticalResultFilterTest.xml'))?.tests, + 6, 'Missing HAVING provenance, parameter masking and alias isolation'); + } + const regression = await execute('native-regression', []); + for (const module of ['teaql-core', 'teaql-runtime', 'teaql-sql-portable', 'teaql-provider-jdbc', 'teaql-sqlite']) + assert(regression.suites[module]?.some(s => s.tests > 0), 'Missing reactor suite: ' + module); + for (const [name, expected] of Object.entries(receipt.sourceHashes)) + assert.equal(hash(fs.readFileSync(path.join(repo, name))), expected, 'Source changed: ' + name); + receipt.passed = true; + } catch (error) { + receipt.error = error.message; process.exitCode = runner.interrupted === 'SIGINT' ? 130 : 1; + } finally { + receipt.cleanup = []; + if (runner.safeToClean) { + for (const target of targets) if (fs.existsSync(target)) { + const bytes = ownedBytes(target); fs.rmSync(target, {recursive: true}); receipt.cleanup.push({path: target, bytes}); + } + } else receipt.unsafeRetention = {targets, processGroup: runner.unsafeGroup}; + runner.dispose(); + fs.writeFileSync(path.join(output, 'receipt.json'), JSON.stringify(receipt, null, 2) + '\n'); + process.stdout.write(JSON.stringify({passed: receipt.passed, evidence: output, + tests: receipt.commands.map(run => Object.values(run.suites).flat().reduce((sum, s) => sum + s.tests, 0)), + error: receipt.error, removedBytes: receipt.cleanup.reduce((sum, item) => sum + item.bytes, 0)}) + '\n'); + } +} +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/examples/http-resilience/pom.xml b/examples/http-resilience/pom.xml index bd8ba7119..37d50b531 100644 --- a/examples/http-resilience/pom.xml +++ b/examples/http-resilience/pom.xml @@ -1,6 +1,6 @@ 4.0.0 - io.teaqlteaql-java-parent1.556-RELEASE../../pom.xml + io.teaqlteaql-java-parent1.557-RELEASE../../pom.xml teaql-http-resilience-example io.teaqlteaql-runtime diff --git a/examples/inheritance-save/AGENTS.md b/examples/inheritance-save/AGENTS.md new file mode 100644 index 000000000..fdb95448d --- /dev/null +++ b/examples/inheritance-save/AGENTS.md @@ -0,0 +1,16 @@ +# Inherited save example instructions + +- Implement application-owned tests and services only. `lib/` is unchanged + generation output, bound by `generated-files.json`; never edit it manually. +- Discover APIs through targeted `assist/` help or current model-aware Assist, + not generated library source. Report `MISSING_ASSIST` for missing operations. +- All queries are bounded and carry comment and purpose. Saves carry an audit + reason and execute with the same UserContext. +- A typed parent view remains a parent object. `runtimeType()` is readonly + subtype information, not permission to cast or select a child checker. +- Never insert parent rows manually or write business data through test SQL. + SQL is limited to read-only oracles and maintainer-approved test-fixture DDL: + reject-only triggers may reject a named test value, never repair or seed rows. +- Run `node verify.cjs --output /absolute/new/evidence-directory`. It requires + an isolated runtime checkout with no existing Maven targets, verifies local + class origins and removes only the build outputs created by its own run. diff --git a/examples/inheritance-save/README.md b/examples/inheritance-save/README.md new file mode 100644 index 000000000..6b5661541 --- /dev/null +++ b/examples/inheritance-save/README.md @@ -0,0 +1,64 @@ +# Generic and inherited audited saves + +This six-object SQLite example saves Academy through a generic audited helper, +then reads and updates the same logical object through generated Academy and +School Q/E APIs. It never inserts a parent row manually. The first lifecycle +checks unchanged save, incomplete-target rejection, inherited/local edits, +independent stale copies, parent-view edits, deletion, retained tombstones and +recovery through ordinary audited save. Recovery with field corrections advances +the root version once and retains corrected fields and intent in its audit. +An unrelated SchoolType at the same numeric ID must retain its own version. + +The example also supports the local PostgreSQL verification provider. The +runtime owns Context setup and schema/bootstrap; the generated library supplies +typed queries, expressions and mutation methods. Runtime dependencies compile +from this repository in an offline Maven reactor, not a published artifact. + +```bash +JAVA_HOME=/path/to/jdk21 MAVEN=/path/to/mvn \ + node examples/inheritance-save/verify.cjs --output /absolute/new/evidence +``` + +For an existing, explicitly selected local PostgreSQL fixture: + +```bash +JAVA_HOME=/path/to/jdk21 MAVEN=/path/to/mvn \ + node examples/inheritance-save/verify.cjs --output /absolute/new/pg-evidence \ + --provider postgres --postgres-container teaql-postgres --postgres-port 5433 +``` + +Use a runtime checkout without Maven targets; the verifier refuses to delete or +reuse unknown build outputs. It runs two rounds on the same owned database, +verifies local class origins and generated hashes, and retains compact logs, +JUnit reports and the database. Its compiler targets and scratch reactor are +removed after child processes exit. Existing services and databases are not +restarted or emptied. + +The fixture's model requests the candidate Java version. The verifier records an +explicit Maven property override to the current local source coordinate. This +is source validation, not certification of a published candidate version. +`generation-origin.json` identifies the fresh generation receipt and targeted +Assist; `generated-files.json` binds the unchanged generated library. + +Queries retain their native typed view. `runtimeType()` supplies readonly +next-subtype information: School views of TrainingAcademy report Academy, +whereas Academy views report TrainingAcademy. It never selects a different +checker or authorizes a cast. The example covers six base/middle/leaf/sibling +combinations, minimal selection, streaming and parent update/no-op readback. +The verifier checks root-owned versions and mapped child storage independently +with read-only SQL. It is registered in `scripts/verify-examples.sh`. + +The tested root-version sequence is `1 → 2 → 3 → -4 → 5 → -6 → 7 → 8`. +Marker-only recovery, recovery with edits, stale/live/partial recovery rejection, +and recovery audit lineage are checked on both providers. Native tests also +cover prepared recovery batches, policy intent and the default family ID space. +The example's deliberate numeric-ID collisions use a controlled fixture +allocator, not a claim about default allocation order. + +Test-only, reject-only DDL triggers prove mixed-object atomicity: the trigger +first checks that this round's Platform edit is visible in the transaction, +then rejects a named School value. Read-only Q/E and SQL verify neither edit +commits and no committed audit escapes. Correcting the child and retrying the +same graph succeeds with exactly two committed events. Application mutations +still use generated APIs exclusively; fixture SQL never seeds, repairs or +compensates business rows. diff --git a/examples/inheritance-save/assist/create-academy-assist.md b/examples/inheritance-save/assist/create-academy-assist.md new file mode 100644 index 000000000..ff674532a --- /dev/null +++ b/examples/inheritance-save/assist/create-academy-assist.md @@ -0,0 +1,89 @@ + + +# Java Assist — Create `Academy` + +Use the exact generated `Q.academies()` entry point. The +trusted `UserContext` owns actor, tenant, policy, provider, initialization, and +audit infrastructure; none of those values belong in writable business input. + +```java +package com.example.inheritancematchingservice; + +import io.teaql.core.UserContext; +import com.example.inheritancematchingservice.academy.Academy; + +public final class AcademyCreateService { + private AcademyCreateService() {} + + public static Academy create( + com.example.inheritancematchingservice.platform.Platform platform, + java.lang.String name, + java.lang.Integer studentCapacity, + java.lang.String campusCode, + UserContext context) { + var entity = Q.academies() + .comment("what: initialize Academy") + .purpose("why: create Academy") + .newEntity(context); + + entity.updatePlatform(platform); + entity.updateName(name); + entity.updateStudentCapacity(studentCapacity); + entity.updateCampusCode(campusCode); + + entity.auditAs("Create Academy for the requested business operation") + .save(context); + return entity; + } +} +``` + +Only the generated updater methods above are writable. Constant candidates, +when present, are also generated and must be copied exactly: +- `updateSchoolTypeToPrimary()` +- `updateSchoolTypeToSecondary()` + + +Compile the source unchanged. Test persistence and query-back, and prove that +blank/missing intent, blank/missing audit reason, unknown fields, and attempted +trusted-context overrides fail. Never instantiate a generated entity directly +for creation and do not edit generated sources. + + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact JAVA generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `create`. + +- Validate and allow-list writable business fields; never mass-assign dynamic JSON. +- Create through the generated request/entity API, attach a non-empty audit reason, + save with the same UserContext, and return the runtime's native save result. +- Add a negative test proving a missing audit reason cannot write. diff --git a/examples/inheritance-save/assist/delete-academy-assist.md b/examples/inheritance-save/assist/delete-academy-assist.md new file mode 100644 index 000000000..b2617971b --- /dev/null +++ b/examples/inheritance-save/assist/delete-academy-assist.md @@ -0,0 +1,100 @@ + + +# Java Assist — Delete `Academy` + +Load the current row and its original optimistic version. Delete means audited, +version-aware soft deletion; do not issue SQL or invent a physical-delete API. + +```java +package com.example.inheritancematchingservice; + +import io.teaql.core.UserContext; + +public final class AcademyDeleteService { + private AcademyDeleteService() {} + + public static boolean delete(Long id, UserContext context) { + var entity = Q.academies() + .withIdIs(id) + + .comment("what: load current Academy for deletion") + .purpose("why: preserve original version for optimistic locking") + .executeForOne(context); + if (entity == null) { + return false; + } + + entity.markForDeletion() + .auditAs("Delete Academy for the requested business operation") + .save(context); + return true; + } + + public static boolean restore(Long id, UserContext context) { + var entity = Q.academies() + .withIdIs(id) + + .deletedRowsOnly() + .limit(1) + .comment("what: load deleted Academy for recovery") + .purpose("why: preserve the deleted optimistic version") + .executeForOne(context); + if (entity == null) { + return false; + } + entity.markToRecover() + .auditAs("Restore Academy for the requested business operation") + .save(context); + return true; + } +} +``` + +Compile the source unchanged. Prove that the row remains stored with a negative +version, normal requests hide it, `deletedRowsOnly()` can retrieve it, a stale +independently loaded copy conflicts, a missing ID returns false, blank/missing +audit fails, and invented physical-delete methods do not compile. + +Recovery needs no scalar-field update. `markToRecover()` records a pending recovery; +audited `save(context)` restores visibility and advances the negative version to +a positive one. A graph can recover several children with independent local comments +using one audited root save. Test committed SQL/readback/audit lineage as well as Q/E +visibility; a status flag alone is not evidence that the row was recovered. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact JAVA generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `delete`. + +- Load the policy-scoped current entity, mark it for deletion, then use audited + save with the same UserContext. Do not invent a physical-delete API. +- Require an audit reason and optimistic version. Test missing audit and stale + version as explicit failures. diff --git a/examples/inheritance-save/assist/expression-academy-assist.md b/examples/inheritance-save/assist/expression-academy-assist.md new file mode 100644 index 000000000..019ebd19c --- /dev/null +++ b/examples/inheritance-save/assist/expression-academy-assist.md @@ -0,0 +1,119 @@ + + +# Java Assist — Expression `Academy` + +Generated expressions preserve three states: a loaded value, a loaded database +Null, and NotLoaded. `eval()` returns the first two as the native Java value or +`null`; it throws `TeaQLNotLoadedException` for NotLoaded. `orIfNull` applies only +to loaded Null and deliberately propagates NotLoaded. + +For a JSON boundary, use the exception's `toWire()` projection, not its message. +Its `location` retains canonical KSML segments and `instancePath` is an RFC 6901 +JSON Pointer in the model's JSON naming profile. `getAccessPath()` is Java-native +diagnostic display only; do not parse it to reconstruct field identity. +`attemptedLocation` retains the full traversal. `originalExpression` and +`expressionWithBrokenPoint` retain native calls with one `` at the +first missing node. Use `suggestedFix.location` with Q Assist, not guessed APIs. + +The following is complete model-derived source. + +```java +package com.example.inheritancematchingservice; + +import com.example.inheritancematchingservice.academy.Academy; + +public final class AcademyExpressionService { + private AcademyExpressionService() {} + + public static java.lang.Long extractId(Academy entity) { + return E.academy(entity).getId().eval(); + } + + public static java.lang.Long extractIdOrIfNull(Academy entity, java.lang.Long fallback) { + return E.academy(entity).getId().orIfNull(fallback); + } + + public static com.example.inheritancematchingservice.platform.Platform traversePlatform(Academy entity) { + return E.academy(entity).getPlatform().eval(); + } + + public static com.example.inheritancematchingservice.schooltype.SchoolType traverseSchoolType(Academy entity) { + return E.academy(entity).getSchoolType().eval(); + } + + public static java.lang.String extractName(Academy entity) { + return E.academy(entity).getName().eval(); + } + + public static java.lang.String extractNameOrIfNull(Academy entity, java.lang.String fallback) { + return E.academy(entity).getName().orIfNull(fallback); + } + + public static java.lang.Integer extractStudentCapacity(Academy entity) { + return E.academy(entity).getStudentCapacity().eval(); + } + + public static java.lang.Integer extractStudentCapacityOrIfNull(Academy entity, java.lang.Integer fallback) { + return E.academy(entity).getStudentCapacity().orIfNull(fallback); + } + + public static java.lang.Long extractVersion(Academy entity) { + return E.academy(entity).getVersion().eval(); + } + + public static java.lang.Long extractVersionOrIfNull(Academy entity, java.lang.Long fallback) { + return E.academy(entity).getVersion().orIfNull(fallback); + } + + public static java.lang.String extractCampusCode(Academy entity) { + return E.academy(entity).getCampusCode().eval(); + } + + public static java.lang.String extractCampusCodeOrIfNull(Academy entity, java.lang.String fallback) { + return E.academy(entity).getCampusCode().orIfNull(fallback); + } + +} +``` + +Select every field and relation before traversal. Never catch +`TeaQLNotLoadedException` merely to provide a default, and never replace the E +facade with optional chaining or direct getters. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact JAVA generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `expression`. + +- Distinguish a loaded null from a field or relation that was not projected. A + NotLoaded/coding error must remain visible; do not turn it into an ordinary null. +- Select every traversed relation first and use the generated E/expression API for + scalar, object, and list traversal. Do not translate Java accessor names by guess. diff --git a/examples/inheritance-save/assist/query-academy-assist.md b/examples/inheritance-save/assist/query-academy-assist.md new file mode 100644 index 000000000..2aa7e5366 --- /dev/null +++ b/examples/inheritance-save/assist/query-academy-assist.md @@ -0,0 +1,128 @@ + + +# Java Assist — Query `Academy` + +Use the exact generated `Q.academiesWithMinimalFields()` +entry point. The request is bounded, stably ordered, and receives trusted +runtime and policy state only from `UserContext`. + +```java +package com.example.inheritancematchingservice; + +import io.teaql.core.SmartList; +import io.teaql.core.UserContext; +import com.example.inheritancematchingservice.academy.Academy; + +public final class AcademyQueryService { + private AcademyQueryService() {} + + public static SmartList queryById( + UserContext context, Long entityId) { + return Q.academiesWithMinimalFields() + .withIdIs(entityId) + + .orderByIdAscending() + .limit(20) + .comment("what: load the requested Academy row") + .purpose("why: serve the authorized Academy view") + .executeForList(context); + } +} +``` + +Compile and execute this source unchanged. Use only generated projection, +predicate, ordering, and relation-selection APIs. Reuse the same active filters +for rows, count, facets, and aggregates. Missing or blank intent, unknown +fields, unbounded reads, and trusted-context inputs must fail. Use generated +relation loading rather than handwritten child-query loops; never guess a plural. + +## Criteria alternatives and independent membership + +The request returns the native `Academy` view, not an automatically +constructed child class. `row.runtimeType()` supplies its readonly next-subtype +identifier; for a multilevel object this may be the next child rather than the +final leaf. The hint does not load child fields or select a child checker. + + +`matchingAnyOf(childRequests...)` adds OR-combined ID subqueries for this +inheritance root. It does not turn the children's criteria into alternatives. +`matchingIdsOf(otherRequest)` is independent same-entity ID membership. It keeps +the other request's complete grouping, roll-up, HAVING and statistical result +page. A statistical request must return `id` as a final selected key; grouping +it away is not an ID lookup and fails before SQL. + +Use `request.copy()` when you need an independent query graph. It preserves the +generated request types, current source/parent filters, measures, HAVING, ordering +and bounds. Later changes through a roll-up parent handle still affect the original +source, but not the copy. Copying does not access Context or execute SQL. Without +an explicit copy, typed roll-up parent handles remain live. Custom request subclasses +must provide a type-preserving copy factory; unsupported custom expressions are +reported rather than silently shared by an explicit copy. + + +## Field-specific Query Assist + +Use the canonical KSML field name from this list. Do not substitute a language member name, JSON name, or database column. + +| KSML field | Type | Field help | +| --- | --- | --- | +| `id` | `id` | `java-assist-query/academy.id` | +| `platform` | `relation` | `java-assist-query/academy.platform` | +| `school_type` | `relation` | `java-assist-query/academy.school_type` | +| `name` | `string` | `java-assist-query/academy.name` | +| `student_capacity` | `integer` | `java-assist-query/academy.student_capacity` | +| `version` | `version` | `java-assist-query/academy.version` | +| `campus_code` | `string` | `java-assist-query/academy.campus_code` | + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact JAVA generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `query`. + +- Use generated projection, relation, predicate, sort, and aggregate APIs; never + concatenate application SQL or silently ignore an unsupported filter. +- Rows, record count, facets, and aggregates must share the same active filter. +- Add negative tests for missing purpose/comment and forbidden dynamic fields. + +### Optional per-parent Top-N optimization + +- Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution + stage. Use the field-specific relation Assist for the exact generated selector. +- Give the child a per-parent limit and deterministic ordering with an ID tie-breaker; + bound the parent query separately. A single-parent detail query is not batch Top-N. +- Server providers default to a window query (`threshold = 0`). A positive threshold + permits bounded probes only when the already-loaded parent count is at or below it; + above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default. +- Measure before opting in. Do not infer a threshold from table size or execute COUNT + or statistics queries to choose a plan. Keep an index on foreign key + sort + ID. +- Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry. + Runtime-managed probes are not application-owned N+1 loops; neither strategy changes + authorization, loaded-state semantics or the required comment/purpose. diff --git a/examples/inheritance-save/assist/query-school-assist.md b/examples/inheritance-save/assist/query-school-assist.md new file mode 100644 index 000000000..2c434ddab --- /dev/null +++ b/examples/inheritance-save/assist/query-school-assist.md @@ -0,0 +1,127 @@ + + +# Java Assist — Query `School` + +Use the exact generated `Q.schoolsWithMinimalFields()` +entry point. The request is bounded, stably ordered, and receives trusted +runtime and policy state only from `UserContext`. + +```java +package com.example.inheritancematchingservice; + +import io.teaql.core.SmartList; +import io.teaql.core.UserContext; +import com.example.inheritancematchingservice.school.School; + +public final class SchoolQueryService { + private SchoolQueryService() {} + + public static SmartList queryById( + UserContext context, Long entityId) { + return Q.schoolsWithMinimalFields() + .withIdIs(entityId) + + .orderByIdAscending() + .limit(20) + .comment("what: load the requested School row") + .purpose("why: serve the authorized School view") + .executeForList(context); + } +} +``` + +Compile and execute this source unchanged. Use only generated projection, +predicate, ordering, and relation-selection APIs. Reuse the same active filters +for rows, count, facets, and aggregates. Missing or blank intent, unknown +fields, unbounded reads, and trusted-context inputs must fail. Use generated +relation loading rather than handwritten child-query loops; never guess a plural. + +## Criteria alternatives and independent membership + +The request returns the native `School` view, not an automatically +constructed child class. `row.runtimeType()` supplies its readonly next-subtype +identifier; for a multilevel object this may be the next child rather than the +final leaf. The hint does not load child fields or select a child checker. + + +`matchingAnyOf(childRequests...)` adds OR-combined ID subqueries for this +inheritance root. It does not turn the children's criteria into alternatives. +`matchingIdsOf(otherRequest)` is independent same-entity ID membership. It keeps +the other request's complete grouping, roll-up, HAVING and statistical result +page. A statistical request must return `id` as a final selected key; grouping +it away is not an ID lookup and fails before SQL. + +Use `request.copy()` when you need an independent query graph. It preserves the +generated request types, current source/parent filters, measures, HAVING, ordering +and bounds. Later changes through a roll-up parent handle still affect the original +source, but not the copy. Copying does not access Context or execute SQL. Without +an explicit copy, typed roll-up parent handles remain live. Custom request subclasses +must provide a type-preserving copy factory; unsupported custom expressions are +reported rather than silently shared by an explicit copy. + + +## Field-specific Query Assist + +Use the canonical KSML field name from this list. Do not substitute a language member name, JSON name, or database column. + +| KSML field | Type | Field help | +| --- | --- | --- | +| `id` | `id` | `java-assist-query/school.id` | +| `platform` | `relation` | `java-assist-query/school.platform` | +| `school_type` | `relation` | `java-assist-query/school.school_type` | +| `name` | `string` | `java-assist-query/school.name` | +| `student_capacity` | `integer` | `java-assist-query/school.student_capacity` | +| `version` | `version` | `java-assist-query/school.version` | + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact JAVA generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `query`. + +- Use generated projection, relation, predicate, sort, and aggregate APIs; never + concatenate application SQL or silently ignore an unsupported filter. +- Rows, record count, facets, and aggregates must share the same active filter. +- Add negative tests for missing purpose/comment and forbidden dynamic fields. + +### Optional per-parent Top-N optimization + +- Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution + stage. Use the field-specific relation Assist for the exact generated selector. +- Give the child a per-parent limit and deterministic ordering with an ID tie-breaker; + bound the parent query separately. A single-parent detail query is not batch Top-N. +- Server providers default to a window query (`threshold = 0`). A positive threshold + permits bounded probes only when the already-loaded parent count is at or below it; + above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default. +- Measure before opting in. Do not infer a threshold from table size or execute COUNT + or statistics queries to choose a plan. Keep an index on foreign key + sort + ID. +- Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry. + Runtime-managed probes are not application-owned N+1 loops; neither strategy changes + authorization, loaded-state semantics or the required comment/purpose. diff --git a/examples/inheritance-save/assist/update-academy-assist.md b/examples/inheritance-save/assist/update-academy-assist.md new file mode 100644 index 000000000..5cf1fa3ff --- /dev/null +++ b/examples/inheritance-save/assist/update-academy-assist.md @@ -0,0 +1,91 @@ + + +# Java Assist — Update `Academy` + +Load the current row and its original optimistic version. Never reconstruct an +entity from an ID/version supplied by a client. Only the model-derived writable +scalar arguments below may be changed. + +An entity update is not a partial DTO patch. Load every scalar field before +modification so checker rules can validate the complete business state. Never +use `WithMinimalFields()` or a reduced projection for an entity that will be saved. + +```java +package com.example.inheritancematchingservice; + +import io.teaql.core.UserContext; +import com.example.inheritancematchingservice.academy.Academy; + +public final class AcademyUpdateService { + private AcademyUpdateService() {} + + public static Academy update( + Long id, + java.lang.String campusCode, + boolean throwIfMissing, + UserContext context) { + var entity = Q.academies() + .withIdIs(id) + + .comment("what: load current Academy for update") + .purpose("why: preserve original version for optimistic locking") + .executeForOne(context); + if (entity == null) { + if (throwIfMissing) { + throw new IllegalArgumentException("Academy not found: " + id); + } + return null; + } + + entity.updateCampusCode(campusCode); + + entity.auditAs("Update Academy for the requested business operation") + .save(context); + return entity; + } +} +``` + +Compile the source unchanged. Prove persistence and query-back, a conflict from +an independently loaded stale copy, null and throwing not-found behavior, +missing/blank audit rejection, and compilation failure for unknown or trusted +fields. Constant and relation updates require an explicitly selected generated +method; do not invent a generic setter. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact JAVA generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `update`. + +- Load the tenant-scoped current entity first so its original version participates + in optimistic locking; do not reconstruct versioned state from untrusted JSON. +- Allow-list writable fields, attach the generated audit-reason API, and save with + the same UserContext. Add a stale-version rejection test. diff --git a/examples/inheritance-save/generated-files.json b/examples/inheritance-save/generated-files.json new file mode 100644 index 000000000..a931a5d92 --- /dev/null +++ b/examples/inheritance-save/generated-files.json @@ -0,0 +1,46 @@ +{ + "lib/pom.xml" : "f47c6cfdb931a1943eca1fd24f92fd360819d3d1d8faeffab18fb00ebffc0048", + "lib/src/main/java/com/example/inheritancematchingservice/BaseServiceConfiguration.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/inheritancematchingservice/Checkers.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/inheritancematchingservice/Constants.java" : "916f41797ceeeb89650ed3df3c69f744baaaadf69273ac1a5ef5df7c23210dba", + "lib/src/main/java/com/example/inheritancematchingservice/E.java" : "8259d4ff7302a5cb632dd6f54654a363a381d7cf4b4768cb69ac7f0b5e0d8ec1", + "lib/src/main/java/com/example/inheritancematchingservice/EntityMetaRegistry.java" : "a406851aabc74afb74ec5cda54a59bf816a67ba3c5022e911116032bef2be3b3", + "lib/src/main/java/com/example/inheritancematchingservice/GeneratedRuntimeModule.java" : "693701578b8c35182dfe78ffdf1be8a28078e9a598ee0fed003fd30d29b61e9a", + "lib/src/main/java/com/example/inheritancematchingservice/InheritanceMatchingServiceUserContext.java" : "97b48694df0e8ea0757e3ad11768dfbf8c0bc74c459784860d16c8e1ae8dd937", + "lib/src/main/java/com/example/inheritancematchingservice/Q.java" : "f8c44522ddaeebf36a6a0428fac2500224c02bb0ec23c141b1f2a81737bd7666", + "lib/src/main/java/com/example/inheritancematchingservice/Repositories.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/inheritancematchingservice/academy/Academy.java" : "f3266a95e74172fb50c64aacdab6381c8e0d4ac49ebaf15358e6dfe67b487e3e", + "lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyChecker.java" : "1e0187a88488e968d93cd180dfd84e10330a9011cb4fe3edf5b60a8898b45708", + "lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyExpression.java" : "8370df1fe82550fe482581d296c1e31876c65038e3b3082c41a1e0af61936b13", + "lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyListExpression.java" : "6a2ca94ca8e7343a2ab074580ced5a4494bcacd5afd66d175f72837248fd4ecb", + "lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyRequest.java" : "22bac4800a50da9f944d7adf744c95effc2f6368d3f40a0913eaf9b91d961ccd", + "lib/src/main/java/com/example/inheritancematchingservice/college/College.java" : "9bdb82ee2d16ac37faacafc35bb8212e7a530b7e46335e06257f058374461c05", + "lib/src/main/java/com/example/inheritancematchingservice/college/CollegeChecker.java" : "e8edd9178db335cbad64504e7f94d60bf83f719d119ac01a00d16932c5e57d63", + "lib/src/main/java/com/example/inheritancematchingservice/college/CollegeExpression.java" : "f21d4bb04ec6f36aebc11c86552052dee53f2b02808d839d7058e51310461abd", + "lib/src/main/java/com/example/inheritancematchingservice/college/CollegeListExpression.java" : "a89b341c3c2d55ef8650d7dfe75cb5d954b16e3b392b959f8d6c585223ca74d0", + "lib/src/main/java/com/example/inheritancematchingservice/college/CollegeRequest.java" : "27588840f5de0800c406bf6ec142c64423d93954f175ece95954aa7236f96d9a", + "lib/src/main/java/com/example/inheritancematchingservice/platform/Platform.java" : "2d0347e54ca56a14edfdd7781b34db313dd263736e60518dc0af2443d706665d", + "lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformChecker.java" : "297a063a3dc563562ee3ac4581b48072a793b7bbd748552682f080e8cafb4f79", + "lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformExpression.java" : "e8c00499b35b4e62ee357629653644e2634bb3d7bec45961763ab791dcc73cd5", + "lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformListExpression.java" : "c1d13f123bab9409a9b6e1133d0fb8de06f8235322afe5c550e8a24204d07bff", + "lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformRequest.java" : "18c6b2b7d319bbfff05bc3946c2e92e536c9a891cdc46d49694404a00f4968ab", + "lib/src/main/java/com/example/inheritancematchingservice/sampledata/SampleDataService.java" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lib/src/main/java/com/example/inheritancematchingservice/school/School.java" : "3ba2a4ad5f4220ead5f9dadfb7a720fad4407e0046382d9daf41346b9c9c5d92", + "lib/src/main/java/com/example/inheritancematchingservice/school/SchoolChecker.java" : "d5fbbad3eadf1baed8f8e61e90cbcf6f95eb6756e22786ba1488ed95c4e976a9", + "lib/src/main/java/com/example/inheritancematchingservice/school/SchoolExpression.java" : "f668134245f8392fecaf18b979516b6d60aa0af5b9922325720f2e666e417095", + "lib/src/main/java/com/example/inheritancematchingservice/school/SchoolListExpression.java" : "67e482d8be45be9d6f23c206dc7564cff7da1b2ccd69205d3df109c2e6c77749", + "lib/src/main/java/com/example/inheritancematchingservice/school/SchoolRequest.java" : "f826a9b55aa8fbcd4d78e7c6499930c19d01d0e3a635fd35b973b8a6926fdc3b", + "lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolType.java" : "eb3e51a859272074c1cf7ed27b001db49b6dd3e649f3d748c59951af7fe2ec94", + "lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeChecker.java" : "3be09b35400e494a050d687ac746a19f5abc863aa6abe0d2356993d3c3a0df35", + "lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeExpression.java" : "fc23cff73051d98628fab7f060bc6309f01403d6f11939d8fd02d2e9dc6c9c97", + "lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeListExpression.java" : "cd36a4d43c5e0d775e84998504f7ca3625516ce6fa87fbe7aa2f74cdd295287a", + "lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeRequest.java" : "25075ebfc9217aff119603328924d02584c285228917a267b6d4195093e5b9b4", + "lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademy.java" : "1af9893df0aa522b60e7ceb7ab1d84c917c4f54873e638013cc020788e873f6d", + "lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyChecker.java" : "a42c0eaae62ce9375e9e4563bbc9c11674331180c49969a3c5d2a5ba70ea7a17", + "lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyExpression.java" : "a4afe5f0732e93b7428d1d34fb5484274555f968b42fecd0e41923405952be22", + "lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyListExpression.java" : "2184e87b2b4ec812738d871c840eee3ab46aeb764fa92e0ed40cac76733d2f8f", + "lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyRequest.java" : "8b08986eae115dcb26476f4550b4debe70ce826aaf87baa5cf2796bc3f6a2ac7", + "lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler" : "b4712d25600d9aa37c887c75b81ae8cc95c291f91c0d8604d5e6dbec21e926e7", + "teaql/checker-model.json" : "369def38a021b04fca5a8c8d7f68b7f495a0781b816e28b917729217bd6dc242", + "teaql/model-provenance.json" : "ee193bbe93b52415aac7c5064b3df8304ca51521a006f7a0e8a79ebc4c9cd780" +} diff --git a/examples/inheritance-save/generation-origin.json b/examples/inheritance-save/generation-origin.json new file mode 100644 index 000000000..6bbca801b --- /dev/null +++ b/examples/inheritance-save/generation-origin.json @@ -0,0 +1,9 @@ +{ + "schema": "teaql.generated-java-inheritance-example/v1", + "generatorBaseCommit": "77081b0935ab49c90b15f345c29a7724c407b3dd", + "sourceReceipt": "teaql-conformance/evidence/2026-11-14-java-subtype-assist-generation/receipt.json", + "sourceReceiptSha256": "077581ede000c6fdec9598d679a13482e5d9f18217f8dad82a33bfa6b8f5bcaf", + "generatedFiles": 44, + "generatedManifest": "generated-files.json", + "note": "The candidate contains uncommitted generator changes. The receipt source hashes identify that implementation. Its generated library is byte-identical to the runtime acceptance fixture; targeted Assist is refreshed from the same generation. Runtime dependencies use local source, not a published package." +} diff --git a/examples/inheritance-save/lib/pom.xml b/examples/inheritance-save/lib/pom.xml new file mode 100644 index 000000000..c533a0130 --- /dev/null +++ b/examples/inheritance-save/lib/pom.xml @@ -0,0 +1,142 @@ + + + 4.0.0 + + com.example + inheritance-matching-service-core + 0.0.1-SNAPSHOT + jar + + + 21 + 4.1.1 + 1.557-SNAPSHOT + 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 + ${teaql.version} + + + 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/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/BaseServiceConfiguration.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/BaseServiceConfiguration.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/Checkers.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/Checkers.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/Constants.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/Constants.java new file mode 100644 index 000000000..f49fc64d6 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/Constants.java @@ -0,0 +1,13 @@ + +package com.example.inheritancematchingservice; + +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.schooltype.SchoolType; + +public interface Constants { + public static final long PLATFORM_ID = 1l; + public static final Platform PLATFORM = Platform.refer(PLATFORM_ID); + public static final long SCHOOL_TYPE_PRIMARY_ID = 1001l ; + public static final SchoolType SCHOOL_TYPE_PRIMARY = SchoolType.refer(SCHOOL_TYPE_PRIMARY_ID);public static final long SCHOOL_TYPE_SECONDARY_ID = 1002l ; + public static final SchoolType SCHOOL_TYPE_SECONDARY = SchoolType.refer(SCHOOL_TYPE_SECONDARY_ID); +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/E.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/E.java new file mode 100644 index 000000000..d60a64aec --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/E.java @@ -0,0 +1,38 @@ + +package com.example.inheritancematchingservice; + +import com.example.inheritancematchingservice.academy.Academy; +import com.example.inheritancematchingservice.academy.AcademyExpression; +import com.example.inheritancematchingservice.college.College; +import com.example.inheritancematchingservice.college.CollegeExpression; +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.platform.PlatformExpression; +import com.example.inheritancematchingservice.school.School; +import com.example.inheritancematchingservice.school.SchoolExpression; +import com.example.inheritancematchingservice.schooltype.SchoolType; +import com.example.inheritancematchingservice.schooltype.SchoolTypeExpression; +import com.example.inheritancematchingservice.trainingacademy.TrainingAcademy; +import com.example.inheritancematchingservice.trainingacademy.TrainingAcademyExpression; +import io.teaql.core.checker.JsonFieldNamingProfile; +import io.teaql.core.value.ValueExpression; + +public class E { + public static PlatformExpression platform(Platform platform){ + return new PlatformExpression(new ValueExpression(platform, JsonFieldNamingProfile.fromModelValue("camelCase"), "E.platform()")); + } + public static SchoolTypeExpression schoolType(SchoolType schoolType){ + return new SchoolTypeExpression(new ValueExpression(schoolType, JsonFieldNamingProfile.fromModelValue("camelCase"), "E.schoolType()")); + } + public static SchoolExpression school(School school){ + return new SchoolExpression(new ValueExpression(school, JsonFieldNamingProfile.fromModelValue("camelCase"), "E.school()")); + } + public static AcademyExpression academy(Academy academy){ + return new AcademyExpression(new ValueExpression(academy, JsonFieldNamingProfile.fromModelValue("camelCase"), "E.academy()")); + } + public static TrainingAcademyExpression trainingAcademy(TrainingAcademy trainingAcademy){ + return new TrainingAcademyExpression(new ValueExpression(trainingAcademy, JsonFieldNamingProfile.fromModelValue("camelCase"), "E.trainingAcademy()")); + } + public static CollegeExpression college(College college){ + return new CollegeExpression(new ValueExpression(college, JsonFieldNamingProfile.fromModelValue("camelCase"), "E.college()")); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/EntityMetaRegistry.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/EntityMetaRegistry.java new file mode 100644 index 000000000..9223f1614 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/EntityMetaRegistry.java @@ -0,0 +1,779 @@ + +package com.example.inheritancematchingservice; + +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; + +public class EntityMetaRegistry implements EntityMetaAssembler { + private EntityMetaFactory $factory; + + @Override + public void assemble(EntityMetaFactory factory) { + this.$factory = factory; + registerPlatform(); + registerSchoolType(); + registerSchool(); + registerAcademy(); + registerTrainingAcademy(); + registerCollege(); + } + private void registerPlatform() { + FieldLayout.installGenerated(com.example.inheritancematchingservice.platform.Platform.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.inheritancematchingservice.platform.Platform.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.inheritancematchingservice.platform.Platform.class); + entityDescriptor.setEntitySupplier(com.example.inheritancematchingservice.platform.Platform::new); + entityDescriptor.with("name", "Platform") + + .with("module", "Organization") + + .with("module_key", "organization") + ; + + entityDescriptor.setAuditMaskFields(java.util.List.of()); + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.platform.Platform.ID_PROPERTY, Long.class) + ; + PropertyDescriptor name = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.platform.Platform.NAME_PROPERTY, String.class) + ; + PropertyDescriptor baseUrl = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.platform.Platform.BASE_URL_PROPERTY, String.class) + ; + PropertyDescriptor version = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.platform.Platform.VERSION_PROPERTY, Long.class) + ; + entityDescriptor.findProperty(com.example.inheritancematchingservice.platform.Platform.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.platform.Platform.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.inheritancematchingservice.platform.Platform.NAME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.platform.Platform.NAME_PROPERTY).with("isPassword", "false") + + .with("max", "100") + + .with("isVersion", "false") + + .with("javaType", "java.lang.String") + + .with("candidates", "Inheritance Campus") + + .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.inheritancematchingservice.platform.Platform.BASE_URL_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.platform.Platform.BASE_URL_PROPERTY).with("isPassword", "false") + + .with("max", "100") + + .with("isVersion", "false") + + .with("javaType", "java.lang.String") + + .with("candidates", "https://inheritance.example.com") + + .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.inheritancematchingservice.platform.Platform.VERSION_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.platform.Platform.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 registerSchoolType() { + FieldLayout.installGenerated(com.example.inheritancematchingservice.schooltype.SchoolType.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.inheritancematchingservice.schooltype.SchoolType.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.inheritancematchingservice.schooltype.SchoolType.class); + entityDescriptor.setEntitySupplier(com.example.inheritancematchingservice.schooltype.SchoolType::new); + entityDescriptor.with("name", "School Type") + + .with("module", "Academics") + + .with("module_key", "academics") + + .with("constant", "true") + + .with("identifier", "code") + ; + + entityDescriptor.setAuditMaskFields(java.util.List.of()); + PropertyDescriptor platform = + entityDescriptor.addObjectProperty($factory, com.example.inheritancematchingservice.schooltype.SchoolType.PLATFORM_PROPERTY, com.example.inheritancematchingservice.platform.Platform.INTERNAL_TYPE, com.example.inheritancematchingservice.platform.Platform.SCHOOL_TYPE_LIST_PROPERTY, com.example.inheritancematchingservice.platform.Platform.class) + ; + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.schooltype.SchoolType.ID_PROPERTY, Long.class) + ; + PropertyDescriptor name = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.schooltype.SchoolType.NAME_PROPERTY, String.class) + ; + PropertyDescriptor code = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.schooltype.SchoolType.CODE_PROPERTY, String.class) + ; + PropertyDescriptor version = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.schooltype.SchoolType.VERSION_PROPERTY, Long.class) + ; + entityDescriptor.findProperty(com.example.inheritancematchingservice.schooltype.SchoolType.PLATFORM_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.schooltype.SchoolType.PLATFORM_PROPERTY).with("candidates", "platform()") + ; + + entityDescriptor.findProperty(com.example.inheritancematchingservice.schooltype.SchoolType.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.schooltype.SchoolType.ID_PROPERTY).with("isPassword", "false") + + .with("isVersion", "false") + + .with("oracle_sqlType", "number(11)") + + .with("javaType", "java.lang.Long") + + .with("candidates", "1001,1002") + + .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.inheritancematchingservice.schooltype.SchoolType.NAME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.schooltype.SchoolType.NAME_PROPERTY).with("isPassword", "false") + + .with("max", "100") + + .with("isVersion", "false") + + .with("javaType", "java.lang.String") + + .with("candidates", "Primary,Secondary") + + .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.inheritancematchingservice.schooltype.SchoolType.CODE_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.schooltype.SchoolType.CODE_PROPERTY).with("identifier", "true") + + .with("isPassword", "false") + + .with("max", "100") + + .with("isVersion", "false") + + .with("javaType", "java.lang.String") + + .with("candidates", "PRIMARY,SECONDARY") + + .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.inheritancematchingservice.schooltype.SchoolType.VERSION_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.schooltype.SchoolType.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 registerSchool() { + FieldLayout.installGenerated(com.example.inheritancematchingservice.school.School.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.inheritancematchingservice.school.School.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.inheritancematchingservice.school.School.class); + entityDescriptor.setEntitySupplier(com.example.inheritancematchingservice.school.School::new); + entityDescriptor.with("name", "School") + + .with("module", "Academics") + + .with("module_key", "academics") + ; + + entityDescriptor.setAuditMaskFields(java.util.List.of()); + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.school.School.ID_PROPERTY, Long.class) + ; + PropertyDescriptor platform = + entityDescriptor.addObjectProperty($factory, com.example.inheritancematchingservice.school.School.PLATFORM_PROPERTY, com.example.inheritancematchingservice.platform.Platform.INTERNAL_TYPE, com.example.inheritancematchingservice.platform.Platform.SCHOOL_LIST_PROPERTY, com.example.inheritancematchingservice.platform.Platform.class) + ; + PropertyDescriptor schoolType = + entityDescriptor.addObjectProperty($factory, com.example.inheritancematchingservice.school.School.SCHOOL_TYPE_PROPERTY, com.example.inheritancematchingservice.schooltype.SchoolType.INTERNAL_TYPE, com.example.inheritancematchingservice.schooltype.SchoolType.SCHOOL_LIST_PROPERTY, com.example.inheritancematchingservice.schooltype.SchoolType.class) + ; + PropertyDescriptor name = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.school.School.NAME_PROPERTY, String.class) + ; + PropertyDescriptor studentCapacity = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.school.School.STUDENT_CAPACITY_PROPERTY, Integer.class) + ; + PropertyDescriptor version = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.school.School.VERSION_PROPERTY, Long.class) + ; + entityDescriptor.findProperty(com.example.inheritancematchingservice.school.School.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.school.School.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.inheritancematchingservice.school.School.PLATFORM_PROPERTY).with("required", "true"); + + entityDescriptor.findProperty(com.example.inheritancematchingservice.school.School.SCHOOL_TYPE_PROPERTY).with("required", "true"); + + entityDescriptor.findProperty(com.example.inheritancematchingservice.school.School.NAME_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.school.School.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.inheritancematchingservice.school.School.STUDENT_CAPACITY_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.school.School.STUDENT_CAPACITY_PROPERTY).with("isPassword", "false") + + .with("db2_sqlType", "decimal(19,7)") + + .with("isVersion", "false") + + .with("oracle_sqlType", "number(19,7)") + + .with("javaType", "java.lang.Integer") + + .with("sqlType", "INTEGER") + + .with("isId", "false") + + .with("isBool", "false") + + .with("isBaseEntityField", "false") + + .with("isNumber", "true") + + .with("isInt", "true") + + .with("isString", "false") + + .with("isDate", "false") + + .with("graphqlType", "Int") + + .with("isTime", "false") + + .with("isText", "false") + ; + + entityDescriptor.findProperty(com.example.inheritancematchingservice.school.School.VERSION_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.school.School.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 registerAcademy() { + FieldLayout.installGenerated(com.example.inheritancematchingservice.academy.Academy.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.inheritancematchingservice.academy.Academy.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.inheritancematchingservice.academy.Academy.class); + entityDescriptor.setEntitySupplier(com.example.inheritancematchingservice.academy.Academy::new); + entityDescriptor.with("name", "Academy") + + .with("module", "Academics") + + .with("module_key", "academics") + + .with("parent", "school") + ; + + entityDescriptor.setAuditMaskFields(java.util.List.of()); + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.academy.Academy.ID_PROPERTY, Long.class) + ; + PropertyDescriptor campusCode = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.academy.Academy.CAMPUS_CODE_PROPERTY, String.class) + ; + entityDescriptor.setParent($factory.resolveEntityDescriptor(com.example.inheritancematchingservice.school.School.INTERNAL_TYPE)); + entityDescriptor.findProperty(com.example.inheritancematchingservice.academy.Academy.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.academy.Academy.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.inheritancematchingservice.academy.Academy.CAMPUS_CODE_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.academy.Academy.CAMPUS_CODE_PROPERTY).with("isPassword", "false") + + .with("max", "100") + + .with("column", "Legacy Campus Code") + .with("columnName", "Legacy Campus Code") + .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") + ; + + $factory.register(entityDescriptor); + } + private void registerTrainingAcademy() { + FieldLayout.installGenerated(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.class); + entityDescriptor.setEntitySupplier(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy::new); + entityDescriptor.with("name", "Training Academy") + + .with("module", "Academics") + + .with("module_key", "academics") + + .with("parent", "academy") + ; + + entityDescriptor.setAuditMaskFields(java.util.List.of()); + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.ID_PROPERTY, Long.class) + ; + PropertyDescriptor specialty = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.SPECIALTY_PROPERTY, String.class) + ; + entityDescriptor.setParent($factory.resolveEntityDescriptor(com.example.inheritancematchingservice.academy.Academy.INTERNAL_TYPE)); + entityDescriptor.findProperty(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.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.inheritancematchingservice.trainingacademy.TrainingAcademy.SPECIALTY_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.SPECIALTY_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") + ; + + $factory.register(entityDescriptor); + } + private void registerCollege() { + FieldLayout.installGenerated(com.example.inheritancematchingservice.college.College.__TEAQL_FIELD_LAYOUT); + EntityDescriptor entityDescriptor = new EntityDescriptor(); + entityDescriptor.setType(com.example.inheritancematchingservice.college.College.INTERNAL_TYPE); + entityDescriptor.setTargetType(com.example.inheritancematchingservice.college.College.class); + entityDescriptor.setEntitySupplier(com.example.inheritancematchingservice.college.College::new); + entityDescriptor.with("name", "College") + + .with("module", "Academics") + + .with("module_key", "academics") + + .with("parent", "school") + ; + + entityDescriptor.setAuditMaskFields(java.util.List.of()); + PropertyDescriptor id = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.college.College.ID_PROPERTY, Long.class) + ; + PropertyDescriptor degreeLevel = + entityDescriptor.addSimpleProperty(com.example.inheritancematchingservice.college.College.DEGREE_LEVEL_PROPERTY, String.class) + ; + entityDescriptor.setParent($factory.resolveEntityDescriptor(com.example.inheritancematchingservice.school.School.INTERNAL_TYPE)); + entityDescriptor.findProperty(com.example.inheritancematchingservice.college.College.ID_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.college.College.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.inheritancematchingservice.college.College.DEGREE_LEVEL_PROPERTY).with("required", "true"); + entityDescriptor.findProperty(com.example.inheritancematchingservice.college.College.DEGREE_LEVEL_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") + ; + + $factory.register(entityDescriptor); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/GeneratedRuntimeModule.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/GeneratedRuntimeModule.java new file mode 100644 index 000000000..b7a4cb471 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/GeneratedRuntimeModule.java @@ -0,0 +1,74 @@ +package com.example.inheritancematchingservice; + +/** 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.inheritancematchingservice.platform.PlatformChecker(), new com.example.inheritancematchingservice.schooltype.SchoolTypeChecker(), new com.example.inheritancematchingservice.school.SchoolChecker(), new com.example.inheritancematchingservice.academy.AcademyChecker(), new com.example.inheritancematchingservice.trainingacademy.TrainingAcademyChecker(), new com.example.inheritancematchingservice.college.CollegeChecker()) + .withCheckerPresentation(io.teaql.core.checker.CheckerPresentation.Model.fromJson(String.join("", "{\"schema\":\"teaql.checker-model/v1\",\"revision\":\"sha256:43a0ab45b8baa27dfb7d9eccaf6f8ac33e36491d16f13a7817729d8673c0b53a\",\"entities\":{\"Academy\":{\"labels\":{\"en\":\"Academy\"},\"fields\":[{\"name\":\"campus_code\",\"labels\":{\"en\":\"campus code\"},\"aliases\":[\"CampusCode\",\"campusCode\"]},{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]}]},\"College\":{\"labels\":{\"en\":\"College\"},\"fields\":[{\"name\":\"degree_level\",\"labels\":{\"en\":\"degree level\"},\"aliases\":[\"DegreeLevel\",\"degreeLevel\"]},{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]}]},\"Platform\":{\"labels\":{\"en\":\"Platform\"},\"fields\":[{\"name\":\"base_url\",\"labels\":{\"en\":\"base url\"},\"aliases\":[\"BaseUrl\",\"baseUrl\"]},{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]},{\"name\":\"name\",\"labels\":{\"en\":\"name\"},\"aliases\":[\"Name\"]},{\"name\":\"school_list\",\"targetType\":\"School\",\"labels\":{\"en\":\"School\"},\"aliases\":[\"SchoolList\",\"schoolList\"]},{\"name\":\"school_type_list\",\"targetType\":\"SchoolType\",\"labels\":{\"en\":\"School Type\"},\"aliases\":[\"SchoolTypeList\",\"schoolTypeList\"]},{\"name\":\"version\",\"labels\":{\"en\":\"version\"},\"aliases\":[\"Version\"]}]},\"School\":{\"labels\":{\"en\":\"School\"},\"fields\":[{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]},{\"name\":\"name\",\"labels\":{\"en\":\"name\"},\"aliases\":[\"Name\"]},{\"name\":\"platform\",\"targetType\":\"Platform\",\"labels\":{\"en\":\"Platform\"},\"aliases\":[\"Platform\"]},{\"name\":\"school_type\",\"targetType\":\"SchoolType\",\"labels\":{\"en\":\"School Type\"},\"aliases\":[\"SchoolType\",\"schoolType\"]},{\"name\":\"student_capacity\",\"labels\":{\"en\":\"student capacity\"},\"aliases\":[\"StudentCapacity\",\"studentCapacity\"]},{\"name\":\"version\",\"labels\":{\"en\":\"version\"},\"aliases\":[\"Version\"]}]},\"SchoolType\":{\"labels\":{\"en\":\"School Type\"},\"fields\":[{\"name\":\"code\",\"labels\":{\"en\":\"code\"},\"aliases\":[\"Code\"]},{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]},{\"name\":\"name\",\"labels\":{\"en\":\"name\"},\"aliases\":[\"Name\"]},{\"name\":\"platform\",\"targetType\":\"Platform\",\"labels\":{\"en\":\"Platform\"},\"aliases\":[\"Platform\"]},{\"name\":\"school_list\",\"targetType\":\"School\",\"labels\":{\"en\":\"School\"},\"aliases\":[\"SchoolList\",\"schoolList\"]},{\"name\":\"version\",\"labels\":{\"en\":\"version\"},\"aliases\":[\"Version\"]}]},\"TrainingAcademy\":{\"labels\":{\"en\":\"Training Academy\"},\"fields\":[{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]},{\"name\":\"specialty\",\"labels\":{\"en\":\"specialty\"},\"aliases\":[\"Specialty\"]}]}}}"))) + .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("Platform", java.util.Map.ofEntries(java.util.Map.entry("id", "id"), java.util.Map.entry("name", "name"), java.util.Map.entry("base_url", "baseUrl"), java.util.Map.entry("version", "version"))), + java.util.Map.entry("SchoolType", java.util.Map.ofEntries(java.util.Map.entry("platform", "platform"), java.util.Map.entry("id", "id"), java.util.Map.entry("name", "name"), java.util.Map.entry("code", "code"), java.util.Map.entry("version", "version"))), + java.util.Map.entry("School", java.util.Map.ofEntries(java.util.Map.entry("id", "id"), java.util.Map.entry("platform", "platform"), java.util.Map.entry("school_type", "schoolType"), java.util.Map.entry("name", "name"), java.util.Map.entry("student_capacity", "studentCapacity"), java.util.Map.entry("version", "version"))), + java.util.Map.entry("Academy", java.util.Map.ofEntries(java.util.Map.entry("id", "id"), java.util.Map.entry("campus_code", "campusCode"))), + java.util.Map.entry("TrainingAcademy", java.util.Map.ofEntries(java.util.Map.entry("id", "id"), java.util.Map.entry("specialty", "specialty"))), + java.util.Map.entry("College", java.util.Map.ofEntries(java.util.Map.entry("id", "id"), java.util.Map.entry("degree_level", "degreeLevel"))) + ); + } + + /** 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.platforms().withIdIs(1L).comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(context); + com.example.inheritancematchingservice.platform.Platform domainRoot; + if (domainRoots.isEmpty()) { + domainRoot = new com.example.inheritancematchingservice.platform.Platform(); + io.teaql.core.GeneratedSchemaBootstrap.initializeFixedId(context, domainRoot, 1L); + domainRoot.updateName("Inheritance Campus"); + domainRoot.updateBaseUrl("https://inheritance.example.com"); + domainRoot.auditAs("create generated Domain Root Platform").save(context); + } else { domainRoot = domainRoots.get(0); } + context.withActiveRoot(new io.teaql.core.ContextEntityRef("Platform", domainRoot.getId())); + var constantSchoolType1001Rows = Q.schoolTypes().withIdIs(1001L).comment("what: locate generated constant").purpose("why: idempotent runtime bootstrap").executeForList(context); + if (constantSchoolType1001Rows.isEmpty()) { + com.example.inheritancematchingservice.schooltype.SchoolType constantSchoolType1001 = new com.example.inheritancematchingservice.schooltype.SchoolType(); + constantSchoolType1001 = io.teaql.core.GeneratedSchemaBootstrap.initializeFixedId(context, constantSchoolType1001, 1001L); + constantSchoolType1001.updatePlatform(domainRoot); + constantSchoolType1001.updateName("Primary"); + constantSchoolType1001.updateCode("PRIMARY"); + constantSchoolType1001.auditAs("create model constant SchoolType(1001)").save(context); + } else { + com.example.inheritancematchingservice.schooltype.SchoolType constantSchoolType1001 = constantSchoolType1001Rows.get(0); + boolean changed = false; + if (!(java.util.Objects.equals(constantSchoolType1001.getPlatform().getId(), domainRoot.getId()))) { constantSchoolType1001.updatePlatform(domainRoot); changed = true; } + if (!(java.util.Objects.equals(constantSchoolType1001.getName(), "Primary"))) { constantSchoolType1001.updateName("Primary"); changed = true; } + if (!(java.util.Objects.equals(constantSchoolType1001.getCode(), "PRIMARY"))) { constantSchoolType1001.updateCode("PRIMARY"); changed = true; } + if (changed) constantSchoolType1001.auditAs("reconcile model constant SchoolType(1001)").save(context); + } + var constantSchoolType1002Rows = Q.schoolTypes().withIdIs(1002L).comment("what: locate generated constant").purpose("why: idempotent runtime bootstrap").executeForList(context); + if (constantSchoolType1002Rows.isEmpty()) { + com.example.inheritancematchingservice.schooltype.SchoolType constantSchoolType1002 = new com.example.inheritancematchingservice.schooltype.SchoolType(); + constantSchoolType1002 = io.teaql.core.GeneratedSchemaBootstrap.initializeFixedId(context, constantSchoolType1002, 1002L); + constantSchoolType1002.updatePlatform(domainRoot); + constantSchoolType1002.updateName("Secondary"); + constantSchoolType1002.updateCode("SECONDARY"); + constantSchoolType1002.auditAs("create model constant SchoolType(1002)").save(context); + } else { + com.example.inheritancematchingservice.schooltype.SchoolType constantSchoolType1002 = constantSchoolType1002Rows.get(0); + boolean changed = false; + if (!(java.util.Objects.equals(constantSchoolType1002.getPlatform().getId(), domainRoot.getId()))) { constantSchoolType1002.updatePlatform(domainRoot); changed = true; } + if (!(java.util.Objects.equals(constantSchoolType1002.getName(), "Secondary"))) { constantSchoolType1002.updateName("Secondary"); changed = true; } + if (!(java.util.Objects.equals(constantSchoolType1002.getCode(), "SECONDARY"))) { constantSchoolType1002.updateCode("SECONDARY"); changed = true; } + if (changed) constantSchoolType1002.auditAs("reconcile model constant SchoolType(1002)").save(context); + } + } +} diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/InheritanceMatchingServiceUserContext.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/InheritanceMatchingServiceUserContext.java new file mode 100644 index 000000000..4a92c7681 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/InheritanceMatchingServiceUserContext.java @@ -0,0 +1,10 @@ + +package com.example.inheritancematchingservice; + +import io.teaql.core.UserContext; +public interface InheritanceMatchingServiceUserContext extends UserContext{ + + + + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/Q.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/Q.java new file mode 100644 index 000000000..879107e45 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/Q.java @@ -0,0 +1,78 @@ + +package com.example.inheritancematchingservice; + +import io.teaql.core.criteria.Operator; + +public class Q { + public static com.example.inheritancematchingservice.platform.PlatformRequest platforms(){ + return new com.example.inheritancematchingservice.platform.PlatformRequest(com.example.inheritancematchingservice.platform.Platform.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.inheritancematchingservice.platform.PlatformRequest platformsWithMinimalFields(){ + return new com.example.inheritancematchingservice.platform.PlatformRequest(com.example.inheritancematchingservice.platform.Platform.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + + public static com.example.inheritancematchingservice.schooltype.SchoolTypeRequest schoolTypes(){ + return new com.example.inheritancematchingservice.schooltype.SchoolTypeRequest(com.example.inheritancematchingservice.schooltype.SchoolType.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.inheritancematchingservice.schooltype.SchoolTypeRequest schoolTypesWithMinimalFields(){ + return new com.example.inheritancematchingservice.schooltype.SchoolTypeRequest(com.example.inheritancematchingservice.schooltype.SchoolType.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + + public static com.example.inheritancematchingservice.school.SchoolRequest schools(){ + return new com.example.inheritancematchingservice.school.SchoolRequest(com.example.inheritancematchingservice.school.School.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.inheritancematchingservice.school.SchoolRequest schoolsWithMinimalFields(){ + return new com.example.inheritancematchingservice.school.SchoolRequest(com.example.inheritancematchingservice.school.School.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + public static com.example.inheritancematchingservice.school.SchoolRequest schoolsWithChildren(){ + com.example.inheritancematchingservice.school.SchoolRequest school = new com.example.inheritancematchingservice.school.SchoolRequest(com.example.inheritancematchingservice.school.School.class).unselectVersion().unlimited().selectSelfFields(); + school.enhanceChild( + academiesWithChildren() + ); + school.enhanceChild( + new com.example.inheritancematchingservice.college.CollegeRequest(com.example.inheritancematchingservice.college.College.class).unselectVersion().unlimited().selectSelfFields() + ); + return school; + } + + public static com.example.inheritancematchingservice.academy.AcademyRequest academies(){ + return new com.example.inheritancematchingservice.academy.AcademyRequest(com.example.inheritancematchingservice.academy.Academy.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.inheritancematchingservice.academy.AcademyRequest academiesWithMinimalFields(){ + return new com.example.inheritancematchingservice.academy.AcademyRequest(com.example.inheritancematchingservice.academy.Academy.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + public static com.example.inheritancematchingservice.academy.AcademyRequest academiesWithChildren(){ + com.example.inheritancematchingservice.academy.AcademyRequest academy = new com.example.inheritancematchingservice.academy.AcademyRequest(com.example.inheritancematchingservice.academy.Academy.class).unselectVersion().unlimited().selectSelfFields(); + academy.enhanceChild( + new com.example.inheritancematchingservice.trainingacademy.TrainingAcademyRequest(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.class).unselectVersion().unlimited().selectSelfFields() + ); + return academy; + } + + public static com.example.inheritancematchingservice.trainingacademy.TrainingAcademyRequest trainingAcademies(){ + return new com.example.inheritancematchingservice.trainingacademy.TrainingAcademyRequest(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.inheritancematchingservice.trainingacademy.TrainingAcademyRequest trainingAcademiesWithMinimalFields(){ + return new com.example.inheritancematchingservice.trainingacademy.TrainingAcademyRequest(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + + public static com.example.inheritancematchingservice.college.CollegeRequest colleges(){ + return new com.example.inheritancematchingservice.college.CollegeRequest(com.example.inheritancematchingservice.college.College.class).selectSelf().withVersion(Operator.GREATER_THAN, 0l); + } + public static com.example.inheritancematchingservice.college.CollegeRequest collegesWithMinimalFields(){ + return new com.example.inheritancematchingservice.college.CollegeRequest(com.example.inheritancematchingservice.college.College.class).withVersion(Operator.GREATER_THAN, 0l); + } + + + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/Repositories.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/Repositories.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/Academy.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/Academy.java new file mode 100644 index 000000000..9ad63d6af --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/Academy.java @@ -0,0 +1,132 @@ + +package com.example.inheritancematchingservice.academy; + +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.school.School; +import io.teaql.core.Audited; +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.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 Academy extends School implements RemoteInput { + public static String INTERNAL_TYPE = "Academy"; + + // Framework metadata: complete fixed layout, independent of SQL/projection order. + public static final String __TEAQL_FIELD_LAYOUT_REVISION = "cd7f0bf3e8a453342d310c02c751feb21ed2383f4c58932743069e1be291b526"; + public static final java.util.Map __TEAQL_FIXED_FIELD_INDEXES = + java.util.Map.ofEntries(java.util.Map.entry("id", 0), java.util.Map.entry("platform", 1), java.util.Map.entry("school_type", 2), java.util.Map.entry("name", 3), java.util.Map.entry("student_capacity", 4), java.util.Map.entry("version", 5), java.util.Map.entry("campus_code", 6)); + 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("platform", java.util.List.of("platform", "platform")), java.util.Map.entry("school_type", java.util.List.of("schoolType", "school_type")), java.util.Map.entry("name", java.util.List.of("name", "name")), java.util.Map.entry("student_capacity", java.util.List.of("studentCapacity", "student_capacity")), java.util.Map.entry("version", java.util.List.of("version", "version")), java.util.Map.entry("campus_code", java.util.List.of("campusCode", "Legacy Campus Code"))); + 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( + Academy.class, __TEAQL_FIELD_LAYOUT_REVISION, + __TEAQL_FIXED_FIELD_INDEXES, __TEAQL_FIXED_FIELD_MAPPINGS, __TEAQL_FIXED_RELATION_NAMES, + JsonFieldNamingProfile.fromModelValue("camelCase"))); + + + public static final String CAMPUS_CODE_PROPERTY = "campus_code"; + private String campusCode; + + + public String getCampusCode(){ + return this.campusCode; + } + + public Academy updateCampusCode(String campusCode){ + campusCode = (campusCode == null ? null : campusCode.trim()); + if(isPropertyLoaded(CAMPUS_CODE_PROPERTY) && Objects.equals(this.campusCode, campusCode)){ + return this; + } + handleUpdate(CAMPUS_CODE_PROPERTY, getCampusCode(), campusCode); + this.campusCode = campusCode; + return this; + } + + public Academy updatePlatform(Platform platform){ + super.updatePlatform(platform); + return this; + } + + public Academy updateSchoolTypeToPrimary(){ + super.updateSchoolTypeToPrimary(); + return this; + } + public Academy updateSchoolTypeToSecondary(){ + super.updateSchoolTypeToSecondary(); + return this; + } + + public Academy updateName(String name){ + super.updateName(name); + return this; + } + + public Academy updateStudentCapacity(Integer studentCapacity){ + super.updateStudentCapacity(studentCapacity); + return this; + } + + + public static Academy refer(Long id){ + Academy refer = new Academy(); + refer.__internalSet("id", id); + refer.set$status(EntityStatus.REFER); + return refer; + } + @Override + public String typeName(){ + return INTERNAL_TYPE; + } + + public Academy 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 "campus_code": this.campusCode = (value == null ? null : ((String)value).trim()); break; + + default: super.__internalSet(property, value); + } + } + + @Override + @FrameworkInternal + public Object __internalGet(String property) { + switch (property) { + case "campus_code": return this.campusCode; + default: + // Presentation uses the installed Java member mapping; SQL and + // hydration retain canonical names. These aliases only read. + switch (property) { + case "campusCode": return this.campusCode; + default: return super.__internalGet(property); + } + } + } + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyChecker.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyChecker.java new file mode 100644 index 000000000..e25259399 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyChecker.java @@ -0,0 +1,49 @@ + +package com.example.inheritancematchingservice.academy; + +import com.example.inheritancematchingservice.school.SchoolChecker; +import io.teaql.core.UserContext; +import io.teaql.core.checker.Checker; +import io.teaql.core.checker.ObjectLocation; + +public class AcademyChecker implements Checker{ + + public String type(){ + return Academy.INTERNAL_TYPE; + } + + public void checkAndFix(UserContext _context, Academy academy, ObjectLocation _parentLocation){ + if(needCheck(_context, academy)){ + markAsChecked(_context, academy); + new SchoolChecker().doCheck(_context, academy, _parentLocation); + + doCheck(_context, academy, _parentLocation); + } + } + + public void doCheck(UserContext _context, Academy academy, ObjectLocation _parentLocation){ + if((academy == null)){ + return; + } + boolean _contextFixEligible = needContextFix(_context, academy); + if(academy.needPersist()){ + } + if(academy.newItem()){ + }else if(academy.updateItem()){ + if(!academy.isPropertyLoaded("campus_code")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "campus_code"), "Mutation requires a fully loaded entity"); + } + + } + checkCampusCode(_context, academy.getProperty(Academy.CAMPUS_CODE_PROPERTY), newLocation(_parentLocation, "campus_code")); + } + + public void checkCampusCode(UserContext _context, String campusCode, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, campusCode); + if((campusCode == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, campusCode); + + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyExpression.java new file mode 100644 index 000000000..e96e73ae3 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyExpression.java @@ -0,0 +1,43 @@ + +package com.example.inheritancematchingservice.academy; + +import com.example.inheritancematchingservice.school.SchoolExpression; +import io.teaql.core.UserContext; +import io.teaql.core.value.BaseEntityExpression; +import io.teaql.core.value.Expression; +import java.util.function.Function; + +public class AcademyExpression extends SchoolExpression implements BaseEntityExpression { + public AcademyExpression(Expression expression){ + super(expression); + } + + public AcademyExpression(Expression expression, Function function){ + super(expression, function); + } + + public AcademyExpression updateId(Long id){ + return new AcademyExpression(this, $it -> {((Academy)$it).__internalSet("id", id); return this;}); + } + + public AcademyExpression save(UserContext userContext){ + return new AcademyExpression(this, $it -> ((Academy)$it).auditAs("Saved by Expression").save(userContext)); + } + + public AcademyExpression save(String intent, UserContext userContext){ + return new AcademyExpression(this, $it -> ((Academy)$it).auditAs(intent).save(userContext)); + } + + public boolean isNull() { + return resolve() == null; + } + + + public Expression getCampusCode(){ + return loaded("campus_code", "getCampusCode", Academy::getCampusCode); + } + public AcademyExpression updateCampusCode(String campusCode){ + return new AcademyExpression(this, $it -> ((Academy)$it).updateCampusCode(campusCode)); + } + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyListExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyListExpression.java new file mode 100644 index 000000000..0f349aa3f --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyListExpression.java @@ -0,0 +1,25 @@ + +package com.example.inheritancematchingservice.academy; + +import io.teaql.core.SmartList; +import io.teaql.core.value.Expression; +import io.teaql.core.value.SmartListExpression; +import java.util.function.Function; + +public class AcademyListExpression extends SmartListExpression { + public AcademyListExpression(Expression> expression){ + super(expression); + } + + public AcademyListExpression(Expression expression, Function> function){ + super(expression, function); + } + + public AcademyExpression first() { + return new AcademyExpression(super.first()); + } + + public AcademyExpression get(int index) { + return new AcademyExpression(super.get(index)); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyRequest.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyRequest.java new file mode 100644 index 000000000..57d1b0d78 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/academy/AcademyRequest.java @@ -0,0 +1,970 @@ + +package com.example.inheritancematchingservice.academy; + +import cn.hutool.core.util.ObjectUtil; +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.platform.PlatformRequest; +import com.example.inheritancematchingservice.school.SchoolRequest; +import com.example.inheritancematchingservice.schooltype.SchoolType; +import com.example.inheritancematchingservice.schooltype.SchoolTypeRequest; +import com.example.inheritancematchingservice.trainingacademy.TrainingAcademy; +import io.teaql.core.AggrFunction; +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.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class AcademyRequest extends SchoolRequest { + + /** + * @deprecated AI agents and business code must use the generated Q facade + * instead of constructing request builders directly. + */ + @Deprecated + @SuppressWarnings("unchecked") + public AcademyRequest(Class returnType){ + this(returnType, () -> (T) new Academy()); + } + + protected AcademyRequest(Class returnType, java.util.function.Supplier factory){ + super(returnType, factory); + selectId(); + selectVersion(); + } + + public AcademyRequest comment(String comment){ + super.internalComment(comment); + return this; + } + + /** Independent query graph; ordinary roll-up handles remain live. */ + @Override + @SuppressWarnings("unchecked") + public AcademyRequest copy(){ + return (AcademyRequest) super.copy(); + } + + @Override + @SuppressWarnings("unchecked") + protected io.teaql.core.BaseRequest internalCopyTarget(){ + return new AcademyRequest<>((Class) returnType(), this::internalNewEntity); + } + + // purpose() 继承自 BaseRequest,返回 ExecutableRequest(终结方法) + + public AcademyRequest returnType(Class returnType){ + super.setReturnType(returnType); + return this; + } + + public AcademyRequest enableAggregationCache(long cacheExpiredMillis){ + super.enableAggregationCache(); + super.aggregateCacheTime(cacheExpiredMillis); + return this; + } + + public AcademyRequest enableAggregationCache(){ + return enableAggregationCache(0l); + } + + + public AcademyRequest 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 AcademyRequest optimizeForContinuousPageFetch(){ + super.optimizeForContinuousPageFetch(); + return this; + } + + public AcademyRequest optimizeForContinuousPageFetch(String namespace, int ttlSeconds){ + super.optimizeForContinuousPageFetch(namespace, ttlSeconds); + return this; + } + + public AcademyRequest optimizePaginationWithIdSet(){ + super.optimizePaginationWithIdSet(); + return this; + } + + public AcademyRequest optimizePaginationWithIdSet( + String namespace, int ttlSeconds, int maxIds){ + super.optimizePaginationWithIdSet(namespace, ttlSeconds, maxIds); + return this; + } + + public AcademyRequest topNProbeParentThreshold(int threshold){ + super.topNProbeParentThreshold(threshold); + return this; + } + + public AcademyRequest appendSearchCriteria(SearchCriteria searchCriteria){ + return (AcademyRequest)super.appendSearchCriteria(searchCriteria); + } + + public AcademyRequest filter(String property1, Operator operator, String property2){ + return appendSearchCriteria(new TwoOperatorCriteria(operator, new PropertyReference(property1), new PropertyReference(property2))); + } + + + public AcademyRequest matchingAnyOf(AcademyRequest... academies){ + if(ObjectUtil.isEmpty(academies)){ + return this; + } + List l = new ArrayList(); + for(AcademyRequest academy:academies){ + l.add(new SubQuerySearchCriteria(Academy.ID_PROPERTY, academy, Academy.ID_PROPERTY)); + } + return appendSearchCriteria(SearchCriteria.or(l.toArray(new SearchCriteria[l.size()]))); + } + + public AcademyRequest enhanceChild(AcademyRequest academy){ + super.enhanceSelf(academy); + return this; + } + public AcademyRequest matchingIdsOf(AcademyRequest request){ + Objects.requireNonNull(request, "matching request"); + return appendSearchCriteria(new SubQuerySearchCriteria( + Academy.ID_PROPERTY, request, Academy.ID_PROPERTY)); + } + + public AcademyRequest enhanceChildrenIfNeeded(){ + this.enhanceChild( +new com.example.inheritancematchingservice.trainingacademy.TrainingAcademyRequest(com.example.inheritancematchingservice.trainingacademy.TrainingAcademy.class).unlimited().selectSelfWithoutParent() +); + return this; + } + + public AcademyRequest withDeletedRows(){ + super.withDeletedRows(); + return this; + } + + public AcademyRequest deletedRowsOnly(){ + super.deletedRowsOnly(); + return this; + } + + public AcademyRequest selectSelf(){ + super.selectSelf(); + return selectCampusCode(); + } + + public AcademyRequest selectSelfFields(){ + return selectSelf(); + } + + public AcademyRequest selectSelfWithoutParent(){ + selectId(); + selectVersion(); + selectProperty(Academy.CAMPUS_CODE_PROPERTY); + return this; + } + + public AcademyRequest selectAll(){ + super.selectAll(); + return selectCampusCode(); + } + + public AcademyRequest selectChildren(){ + super.selectAny(); + return selectCampusCode(); + } + + + public AcademyRequest selectCampusCode(){ + selectProperty(Academy.CAMPUS_CODE_PROPERTY); + return this; + } + + /** + * fill the campusCode with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS campusCode) to fetch campusCode property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public AcademyRequest unselectCampusCode(){ + unselectProperty(Academy.CAMPUS_CODE_PROPERTY); + return this; + } + public AcademyRequest selectPlatformIdOnly(){ + super.selectPlatformIdOnly(); + return this; + } + + public AcademyRequest selectPlatform(){ + super.selectPlatform(); + return this; + } + + public AcademyRequest selectPlatformWith(PlatformRequest platform){ + super.selectPlatformWith(platform); + return this; + } + + public AcademyRequest unselectPlatform(){ + super.unselectPlatform(); + return this; + } + public AcademyRequest selectSchoolTypeIdOnly(){ + super.selectSchoolTypeIdOnly(); + return this; + } + + public AcademyRequest selectSchoolType(){ + super.selectSchoolType(); + return this; + } + + public AcademyRequest selectSchoolTypeWith(SchoolTypeRequest schoolType){ + super.selectSchoolTypeWith(schoolType); + return this; + } + + public AcademyRequest unselectSchoolType(){ + super.unselectSchoolType(); + return this; + } + public AcademyRequest selectName(){ + super.selectName(); + return this; + } + + /** + * fill the name with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS name) to fetch name property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public AcademyRequest unselectName(){ + super.unselectName(); + return this; + } + public AcademyRequest selectStudentCapacity(){ + super.selectStudentCapacity(); + return this; + } + + /** + * fill the studentCapacity with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS studentCapacity) to fetch studentCapacity property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + /** + * fill the studentCapacity with customized aggrFunction, TEAQL uses ({aggrFunction}(studentCapacity) AS studentCapacity to fetch studentCapacity property. + * @param aggrFunction aggrFunction + */ + public AcademyRequest selectStudentCapacity(AggrFunction aggrFunction){ + super.selectStudentCapacity(aggrFunction); + return this; + } + + + public AcademyRequest unselectStudentCapacity(){ + super.unselectStudentCapacity(); + return this; + } + public AcademyRequest selectVersion(){ + super.selectVersion(); + return this; + } + + /** + * fill the version with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS version) to fetch version property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public AcademyRequest unselectVersion(){ + super.unselectVersion(); + return this; + } + public AcademyRequest selectId(){ + super.selectId(); + return this; + } + + /** + * fill the id with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS id) to fetch id property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public AcademyRequest unselectId(){ + super.unselectId(); + return this; + } + + public AcademyRequest isTrainingAcademy(){ + return matchTypes(TrainingAcademy.INTERNAL_TYPE); + } + + public AcademyRequest matchTypes(String... types){ + super.matchType(types); + return this; + } + + public AcademyRequest withTypeGroup(){ + super.withTypeGroup(); + return this; + } + + public AcademyRequest filterByCampusCode(String... campusCode){ + if (campusCode == null || campusCode.length == 0) { + throw new IllegalArgumentException("filterByCampusCode parameter campusCode cannot be empty"); + } + return appendSearchCriteria(createCampusCodeCriteria(Operator.EQUAL, (Object[])campusCode)); + } + + public AcademyRequest withCampusCode(Operator operator, Object... values){ + return appendSearchCriteria(createCampusCodeCriteria(operator, values)); + } + + public AcademyRequest withCampusCodeIsUnknown(){ + return withCampusCode(Operator.IS_NULL); + } + + public AcademyRequest withCampusCodeIsKnown(){ + return withCampusCode(Operator.IS_NOT_NULL); + } + + public SearchCriteria createCampusCodeCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Academy.CAMPUS_CODE_PROPERTY, operator, values); + } + + public AcademyRequest withCampusCodeIsNot(String campusCode){ + return withCampusCode(Operator.NOT_EQUAL, campusCode); + } + + public AcademyRequest withCampusCodeIn(String... campusCode){ + return withCampusCode(Operator.IN, (Object[])campusCode); + } + + public AcademyRequest withCampusCodeNotIn(String... campusCode){ + return withCampusCode(Operator.NOT_IN, (Object[])campusCode); + } + public AcademyRequest withCampusCodeGreaterThan(String campusCode){ + return withCampusCode(Operator.GREATER_THAN, campusCode); + } + + public AcademyRequest withCampusCodeGreaterThanOrEqualTo(String campusCode){ + return withCampusCode(Operator.GREATER_THAN_OR_EQUAL, campusCode); + } + + public AcademyRequest withCampusCodeLessThan(String campusCode){ + return withCampusCode(Operator.LESS_THAN, campusCode); + } + + public AcademyRequest withCampusCodeLessThanOrEqualTo(String campusCode){ + return withCampusCode(Operator.LESS_THAN_OR_EQUAL, campusCode); + } + + public AcademyRequest withCampusCodeBetween(String startOfCampusCode, String endOfCampusCode){ + return withCampusCode(Operator.BETWEEN, startOfCampusCode, endOfCampusCode); + } + public AcademyRequest withCampusCodeStartingWith(String campusCode){ + return withCampusCode(Operator.BEGIN_WITH, campusCode); + } + public AcademyRequest withCampusCodeContaining(String campusCode){ + return withCampusCode(Operator.CONTAIN, campusCode); + } + + public AcademyRequest withCampusCodeNotContaining(String campusCode){ + return withCampusCode(Operator.NOT_CONTAIN, campusCode); + } + + public AcademyRequest withCampusCodeNotStartingWith(String campusCode){ + return withCampusCode(Operator.NOT_BEGIN_WITH, campusCode); + } + + public AcademyRequest withCampusCodeEndingWith(String campusCode){ + return withCampusCode(Operator.END_WITH, campusCode); + } + + public AcademyRequest withCampusCodeNotEndingWith(String campusCode){ + return withCampusCode(Operator.NOT_END_WITH, campusCode); + } + + public AcademyRequest withCampusCodeIs(String campusCode){ + return withCampusCode(Operator.EQUAL, campusCode); + } + + public AcademyRequest withCampusCodeSoundingLike(String campusCode){ + return withCampusCode(Operator.SOUNDS_LIKE, campusCode); + } + + + + public AcademyRequest filterByPlatform(Platform platform){ + return (AcademyRequest)super.filterByPlatform(platform); + } + + public AcademyRequest withPlatform(Operator operator, Object... values){ + return (AcademyRequest)super.withPlatform(operator, values); + } + + public AcademyRequest withPlatformIsUnknown(){ + return (AcademyRequest)super.withPlatformIsUnknown(); + } + + public AcademyRequest withPlatformIsKnown(){ + return (AcademyRequest)super.withPlatformIsKnown(); + } + + public AcademyRequest filterByPlatform(Long platform){ + return (AcademyRequest)super.filterByPlatform(platform); + } + + public AcademyRequest withPlatformMatching(PlatformRequest platform){ + return (AcademyRequest)super.withPlatformMatching(platform); + } + + public AcademyRequest filterBySchoolType(SchoolType schoolType){ + return (AcademyRequest)super.filterBySchoolType(schoolType); + } + + public AcademyRequest withSchoolType(Operator operator, Object... values){ + return (AcademyRequest)super.withSchoolType(operator, values); + } + + public AcademyRequest withSchoolTypeIsUnknown(){ + return (AcademyRequest)super.withSchoolTypeIsUnknown(); + } + + public AcademyRequest withSchoolTypeIsKnown(){ + return (AcademyRequest)super.withSchoolTypeIsKnown(); + } + + public AcademyRequest filterBySchoolType(Long schoolType){ + return (AcademyRequest)super.filterBySchoolType(schoolType); + } + + public AcademyRequest withSchoolTypeMatching(SchoolTypeRequest schoolType){ + return (AcademyRequest)super.withSchoolTypeMatching(schoolType); + } + + public AcademyRequest filterByName(String name){ + return (AcademyRequest)super.filterByName(name); + } + + public AcademyRequest withName(Operator operator, Object... values){ + return (AcademyRequest)super.withName(operator, values); + } + + public AcademyRequest withNameIsUnknown(){ + return (AcademyRequest)super.withNameIsUnknown(); + } + + public AcademyRequest withNameIsKnown(){ + return (AcademyRequest)super.withNameIsKnown(); + } + + public AcademyRequest withNameStartingWith(String Name){ + return (AcademyRequest)super.withNameStartingWith(Name); + } + public AcademyRequest withNameContaining(String Name){ + return (AcademyRequest)super.withNameContaining(Name); + } + + public AcademyRequest withNameEndingWith(String Name){ + return (AcademyRequest)super.withNameEndingWith(Name); + } + + + public AcademyRequest filterByStudentCapacity(Integer studentCapacity){ + return (AcademyRequest)super.filterByStudentCapacity(studentCapacity); + } + + public AcademyRequest withStudentCapacity(Operator operator, Object... values){ + return (AcademyRequest)super.withStudentCapacity(operator, values); + } + + public AcademyRequest withStudentCapacityIsUnknown(){ + return (AcademyRequest)super.withStudentCapacityIsUnknown(); + } + + public AcademyRequest withStudentCapacityIsKnown(){ + return (AcademyRequest)super.withStudentCapacityIsKnown(); + } + + public AcademyRequest withStudentCapacityGreaterThan(Integer studentCapacity){ + return (AcademyRequest)super.withStudentCapacityGreaterThan(studentCapacity); + } + + public AcademyRequest withStudentCapacityGreaterThanOrEqualTo(Integer studentCapacity){ + return (AcademyRequest)super.withStudentCapacityGreaterThanOrEqualTo(studentCapacity); + } + + public AcademyRequest withStudentCapacityLessThan(Integer studentCapacity){ + return (AcademyRequest)super.withStudentCapacityLessThan(studentCapacity); + } + + public AcademyRequest withStudentCapacityLessThanOrEqualTo(Integer studentCapacity){ + return (AcademyRequest)super.withStudentCapacityLessThanOrEqualTo(studentCapacity); + } + + public AcademyRequest withStudentCapacityBetween(Integer startOfStudentCapacity, Integer endOfStudentCapacity){ + return (AcademyRequest)super.withStudentCapacityBetween(startOfStudentCapacity, endOfStudentCapacity); + } + + + public AcademyRequest filterByVersion(Long version){ + return (AcademyRequest)super.filterByVersion(version); + } + + public AcademyRequest withVersion(Operator operator, Object... values){ + return (AcademyRequest)super.withVersion(operator, values); + } + + public AcademyRequest withVersionIsUnknown(){ + return (AcademyRequest)super.withVersionIsUnknown(); + } + + public AcademyRequest withVersionIsKnown(){ + return (AcademyRequest)super.withVersionIsKnown(); + } + + + public AcademyRequest withIdIs(Long value){ + return (AcademyRequest)super.withIdIs(value); + } + + public AcademyRequest withId(Operator operator, Object... values){ + return (AcademyRequest)super.withId(operator, values); + } + + + public AcademyRequest count(){ + super.count(); + setPageCountOperation(io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.NAMED_COUNT, "count", null, null)); + return this; + } + public AcademyRequest 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 AcademyRequest minStudentCapacity(){ + super.minStudentCapacity(); + return this; + } + + public AcademyRequest minStudentCapacityAs(String retName){ + super.minStudentCapacityAs(retName); + return this; + } + public AcademyRequest maxStudentCapacity(){ + super.maxStudentCapacity(); + return this; + } + + public AcademyRequest maxStudentCapacityAs(String retName){ + super.maxStudentCapacityAs(retName); + return this; + } + public AcademyRequest sumStudentCapacity(){ + super.sumStudentCapacity(); + return this; + } + + public AcademyRequest sumStudentCapacityAs(String retName){ + super.sumStudentCapacityAs(retName); + return this; + } + public AcademyRequest avgStudentCapacity(){ + super.avgStudentCapacity(); + return this; + } + + public AcademyRequest avgStudentCapacityAs(String retName){ + super.avgStudentCapacityAs(retName); + return this; + } + public AcademyRequest stddevStudentCapacity(){ + super.standardDeviationStudentCapacity(); + return this; + } + + public AcademyRequest stddevStudentCapacityAs(String retName){ + super.standardDeviationStudentCapacityAs(retName); + return this; + } + public AcademyRequest stddev_popStudentCapacity(){ + super.squareRootOfPopulationStandardDeviationStudentCapacity(); + return this; + } + + public AcademyRequest stddev_popStudentCapacityAs(String retName){ + super.squareRootOfPopulationStandardDeviationStudentCapacityAs(retName); + return this; + } + public AcademyRequest var_sampStudentCapacity(){ + super.sampleVarianceStudentCapacity(); + return this; + } + + public AcademyRequest var_sampStudentCapacityAs(String retName){ + super.sampleVarianceStudentCapacityAs(retName); + return this; + } + public AcademyRequest var_popStudentCapacity(){ + super.samplePopulationVarianceStudentCapacity(); + return this; + } + + public AcademyRequest var_popStudentCapacityAs(String retName){ + super.samplePopulationVarianceStudentCapacityAs(retName); + return this; + } + public AcademyRequest groupByPlatformWithDetails(){ + super.groupByPlatformWithDetails(); + return this; + } + + public AcademyRequest groupByPlatformWithDetails(PlatformRequest subRequest){ + super.groupByPlatformWithDetails(subRequest); + return this; + } + + public AcademyRequest groupBySchoolTypeWithDetails(){ + super.groupBySchoolTypeWithDetails(); + return this; + } + + public AcademyRequest groupBySchoolTypeWithDetails(SchoolTypeRequest subRequest){ + super.groupBySchoolTypeWithDetails(subRequest); + return this; + } + + + + + + public AcademyRequest countDistinctCampusCode(){ + return countDistinctCampusCodeAs("campus_code_distinct_count"); + } + + public AcademyRequest countDistinctCampusCodeAs(String alias){ + super.countDistinctProperty(alias, Academy.CAMPUS_CODE_PROPERTY); + return this; + } + public AcademyRequest countDistinctPlatform(){ + return countDistinctPlatformAs("platform_distinct_count"); + } + + public AcademyRequest countDistinctPlatformAs(String alias){ + super.countDistinctProperty(alias, Academy.PLATFORM_PROPERTY); + return this; + } + public AcademyRequest countDistinctSchoolType(){ + return countDistinctSchoolTypeAs("school_type_distinct_count"); + } + + public AcademyRequest countDistinctSchoolTypeAs(String alias){ + super.countDistinctProperty(alias, Academy.SCHOOL_TYPE_PROPERTY); + return this; + } + public AcademyRequest countDistinctName(){ + return countDistinctNameAs("name_distinct_count"); + } + + public AcademyRequest countDistinctNameAs(String alias){ + super.countDistinctProperty(alias, Academy.NAME_PROPERTY); + return this; + } + public AcademyRequest countDistinctStudentCapacity(){ + return countDistinctStudentCapacityAs("student_capacity_distinct_count"); + } + + public AcademyRequest countDistinctStudentCapacityAs(String alias){ + super.countDistinctProperty(alias, Academy.STUDENT_CAPACITY_PROPERTY); + return this; + } + public AcademyRequest countDistinctVersion(){ + return countDistinctVersionAs("version_distinct_count"); + } + + public AcademyRequest countDistinctVersionAs(String alias){ + super.countDistinctProperty(alias, Academy.VERSION_PROPERTY); + return this; + } + public AcademyRequest countDistinctId(){ + return countDistinctIdAs("id_distinct_count"); + } + + public AcademyRequest countDistinctIdAs(String alias){ + super.countDistinctProperty(alias, Academy.ID_PROPERTY); + return this; + } + + public AcademyRequest groupByCampusCode(){ + groupBy(Academy.CAMPUS_CODE_PROPERTY); + return this; + } + + public AcademyRequest groupByCampusCodeAs(String retName){ + groupBy(retName, Academy.CAMPUS_CODE_PROPERTY); + return this; + } + + public AcademyRequest groupByCampusCodeWithFunction(String retName, AggrFunction function){ + groupBy(retName, Academy.CAMPUS_CODE_PROPERTY, function); + return this; + } + + + public AcademyRequest groupByPlatformWith(PlatformRequest subRequest){ + super.groupByPlatformWith(subRequest); + return this; + } + public AcademyRequest groupByPlatform(){ + super.groupByPlatform(); + return this; + } + + public AcademyRequest groupByPlatformAs(String retName){ + super.groupByPlatformAs(retName); + return this; + } + + public AcademyRequest groupByPlatformWithFunction(String retName, AggrFunction function){ + super.groupByPlatformWithFunction(retName, function); + return this; + } + public AcademyRequest groupBySchoolTypeWith(SchoolTypeRequest subRequest){ + super.groupBySchoolTypeWith(subRequest); + return this; + } + public AcademyRequest groupBySchoolType(){ + super.groupBySchoolType(); + return this; + } + + public AcademyRequest groupBySchoolTypeAs(String retName){ + super.groupBySchoolTypeAs(retName); + return this; + } + + public AcademyRequest groupBySchoolTypeWithFunction(String retName, AggrFunction function){ + super.groupBySchoolTypeWithFunction(retName, function); + return this; + } + + public AcademyRequest groupByName(){ + super.groupByName(); + return this; + } + + public AcademyRequest groupByNameAs(String retName){ + super.groupByNameAs(retName); + return this; + } + + public AcademyRequest groupByNameWithFunction(String retName, AggrFunction function){ + super.groupByNameWithFunction(retName, function); + return this; + } + + public AcademyRequest groupByStudentCapacity(){ + super.groupByStudentCapacity(); + return this; + } + + public AcademyRequest groupByStudentCapacityAs(String retName){ + super.groupByStudentCapacityAs(retName); + return this; + } + + public AcademyRequest groupByStudentCapacityWithFunction(String retName, AggrFunction function){ + super.groupByStudentCapacityWithFunction(retName, function); + return this; + } + + public AcademyRequest groupByVersion(){ + super.groupByVersion(); + return this; + } + + public AcademyRequest groupByVersionAs(String retName){ + super.groupByVersionAs(retName); + return this; + } + + public AcademyRequest groupByVersionWithFunction(String retName, AggrFunction function){ + super.groupByVersionWithFunction(retName, function); + return this; + } + + public AcademyRequest groupById(){ + super.groupById(); + return this; + } + + public AcademyRequest groupByIdAs(String retName){ + super.groupByIdAs(retName); + return this; + } + + public AcademyRequest groupByIdWithFunction(String retName, AggrFunction function){ + super.groupByIdWithFunction(retName, function); + return this; + } + + public AcademyRequest orderByCampusCodeAscending(){ + addOrderByAscending(Academy.CAMPUS_CODE_PROPERTY); + return this; + } + + public AcademyRequest orderByCampusCodeDescending(){ + addOrderByDescending(Academy.CAMPUS_CODE_PROPERTY); + return this; + } + public AcademyRequest orderByCampusCodeAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Academy.CAMPUS_CODE_PROPERTY); + return this; + } + + public AcademyRequest orderByCampusCodeDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Academy.CAMPUS_CODE_PROPERTY); + return this; + } + public AcademyRequest orderByPlatformAscending(){ + super.orderByPlatformAscending(); + return this; + } + + public AcademyRequest orderByPlatformDescending(){ + super.orderByPlatformDescending(); + return this; + } + + public AcademyRequest orderBySchoolTypeAscending(){ + super.orderBySchoolTypeAscending(); + return this; + } + + public AcademyRequest orderBySchoolTypeDescending(){ + super.orderBySchoolTypeDescending(); + return this; + } + + public AcademyRequest orderByNameAscending(){ + super.orderByNameAscending(); + return this; + } + + public AcademyRequest orderByNameDescending(){ + super.orderByNameDescending(); + return this; + } + public AcademyRequest orderByNameAscendingUsingGBK(){ + super.orderByNameAscendingUsingGBK(); + return this; + } + + public AcademyRequest orderByNameDescendingUsingGBK(){ + super.orderByNameDescendingUsingGBK(); + return this; + } + public AcademyRequest orderByStudentCapacityAscending(){ + super.orderByStudentCapacityAscending(); + return this; + } + + public AcademyRequest orderByStudentCapacityDescending(){ + super.orderByStudentCapacityDescending(); + return this; + } + + public AcademyRequest orderByVersionAscending(){ + super.orderByVersionAscending(); + return this; + } + + public AcademyRequest orderByVersionDescending(){ + super.orderByVersionDescending(); + return this; + } + + public AcademyRequest orderByIdAscending(){ + super.orderByIdAscending(); + return this; + } + + public AcademyRequest orderByIdDescending(){ + super.orderByIdDescending(); + return this; + } + + + + + + /** + * get topN records + * @param topN records number + */ + public AcademyRequest top(int topN) { + super.top(topN); + return this; + } + + /** Cross-runtime bounded-query alias. */ + public AcademyRequest limit(int limit) { + return top(limit); + } + + /** + * get records from offset(inclusive) to offset+size(exclusive) + * @param offset record offset + * @param size records number + */ + public AcademyRequest offset(int offset, int size) { + super.offset(offset, size); + return this; + } + + /** + * retrieve all records + */ + public AcademyRequest unlimited() { + super.unlimited(); + return this; + } + + /** + * get records of one page + * @param pageNumber page number(1-based) + * @param pageSize page size + */ + public AcademyRequest 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 AcademyRequest page(int pageNumber) { + return page(pageNumber, 10); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/College.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/College.java new file mode 100644 index 000000000..e00f1ef19 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/College.java @@ -0,0 +1,132 @@ + +package com.example.inheritancematchingservice.college; + +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.school.School; +import io.teaql.core.Audited; +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.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 College extends School implements RemoteInput { + public static String INTERNAL_TYPE = "College"; + + // Framework metadata: complete fixed layout, independent of SQL/projection order. + public static final String __TEAQL_FIELD_LAYOUT_REVISION = "992021f4267b1280cc0bfbc2f71330457b7b5f1549e06205c85c0db79c2ac489"; + public static final java.util.Map __TEAQL_FIXED_FIELD_INDEXES = + java.util.Map.ofEntries(java.util.Map.entry("id", 0), java.util.Map.entry("platform", 1), java.util.Map.entry("school_type", 2), java.util.Map.entry("name", 3), java.util.Map.entry("student_capacity", 4), java.util.Map.entry("version", 5), java.util.Map.entry("degree_level", 6)); + 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("platform", java.util.List.of("platform", "platform")), java.util.Map.entry("school_type", java.util.List.of("schoolType", "school_type")), java.util.Map.entry("name", java.util.List.of("name", "name")), java.util.Map.entry("student_capacity", java.util.List.of("studentCapacity", "student_capacity")), java.util.Map.entry("version", java.util.List.of("version", "version")), java.util.Map.entry("degree_level", java.util.List.of("degreeLevel", "degree_level"))); + 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( + College.class, __TEAQL_FIELD_LAYOUT_REVISION, + __TEAQL_FIXED_FIELD_INDEXES, __TEAQL_FIXED_FIELD_MAPPINGS, __TEAQL_FIXED_RELATION_NAMES, + JsonFieldNamingProfile.fromModelValue("camelCase"))); + + + public static final String DEGREE_LEVEL_PROPERTY = "degree_level"; + private String degreeLevel; + + + public String getDegreeLevel(){ + return this.degreeLevel; + } + + public College updateDegreeLevel(String degreeLevel){ + degreeLevel = (degreeLevel == null ? null : degreeLevel.trim()); + if(isPropertyLoaded(DEGREE_LEVEL_PROPERTY) && Objects.equals(this.degreeLevel, degreeLevel)){ + return this; + } + handleUpdate(DEGREE_LEVEL_PROPERTY, getDegreeLevel(), degreeLevel); + this.degreeLevel = degreeLevel; + return this; + } + + public College updatePlatform(Platform platform){ + super.updatePlatform(platform); + return this; + } + + public College updateSchoolTypeToPrimary(){ + super.updateSchoolTypeToPrimary(); + return this; + } + public College updateSchoolTypeToSecondary(){ + super.updateSchoolTypeToSecondary(); + return this; + } + + public College updateName(String name){ + super.updateName(name); + return this; + } + + public College updateStudentCapacity(Integer studentCapacity){ + super.updateStudentCapacity(studentCapacity); + return this; + } + + + public static College refer(Long id){ + College refer = new College(); + refer.__internalSet("id", id); + refer.set$status(EntityStatus.REFER); + return refer; + } + @Override + public String typeName(){ + return INTERNAL_TYPE; + } + + public College 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 "degree_level": this.degreeLevel = (value == null ? null : ((String)value).trim()); break; + + default: super.__internalSet(property, value); + } + } + + @Override + @FrameworkInternal + public Object __internalGet(String property) { + switch (property) { + case "degree_level": return this.degreeLevel; + default: + // Presentation uses the installed Java member mapping; SQL and + // hydration retain canonical names. These aliases only read. + switch (property) { + case "degreeLevel": return this.degreeLevel; + default: return super.__internalGet(property); + } + } + } + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeChecker.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeChecker.java new file mode 100644 index 000000000..83d57ae45 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeChecker.java @@ -0,0 +1,49 @@ + +package com.example.inheritancematchingservice.college; + +import com.example.inheritancematchingservice.school.SchoolChecker; +import io.teaql.core.UserContext; +import io.teaql.core.checker.Checker; +import io.teaql.core.checker.ObjectLocation; + +public class CollegeChecker implements Checker{ + + public String type(){ + return College.INTERNAL_TYPE; + } + + public void checkAndFix(UserContext _context, College college, ObjectLocation _parentLocation){ + if(needCheck(_context, college)){ + markAsChecked(_context, college); + new SchoolChecker().doCheck(_context, college, _parentLocation); + + doCheck(_context, college, _parentLocation); + } + } + + public void doCheck(UserContext _context, College college, ObjectLocation _parentLocation){ + if((college == null)){ + return; + } + boolean _contextFixEligible = needContextFix(_context, college); + if(college.needPersist()){ + } + if(college.newItem()){ + }else if(college.updateItem()){ + if(!college.isPropertyLoaded("degree_level")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "degree_level"), "Mutation requires a fully loaded entity"); + } + + } + checkDegreeLevel(_context, college.getProperty(College.DEGREE_LEVEL_PROPERTY), newLocation(_parentLocation, "degree_level")); + } + + public void checkDegreeLevel(UserContext _context, String degreeLevel, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, degreeLevel); + if((degreeLevel == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, degreeLevel); + + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeExpression.java new file mode 100644 index 000000000..2df72960d --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeExpression.java @@ -0,0 +1,43 @@ + +package com.example.inheritancematchingservice.college; + +import com.example.inheritancematchingservice.school.SchoolExpression; +import io.teaql.core.UserContext; +import io.teaql.core.value.BaseEntityExpression; +import io.teaql.core.value.Expression; +import java.util.function.Function; + +public class CollegeExpression extends SchoolExpression implements BaseEntityExpression { + public CollegeExpression(Expression expression){ + super(expression); + } + + public CollegeExpression(Expression expression, Function function){ + super(expression, function); + } + + public CollegeExpression updateId(Long id){ + return new CollegeExpression(this, $it -> {((College)$it).__internalSet("id", id); return this;}); + } + + public CollegeExpression save(UserContext userContext){ + return new CollegeExpression(this, $it -> ((College)$it).auditAs("Saved by Expression").save(userContext)); + } + + public CollegeExpression save(String intent, UserContext userContext){ + return new CollegeExpression(this, $it -> ((College)$it).auditAs(intent).save(userContext)); + } + + public boolean isNull() { + return resolve() == null; + } + + + public Expression getDegreeLevel(){ + return loaded("degree_level", "getDegreeLevel", College::getDegreeLevel); + } + public CollegeExpression updateDegreeLevel(String degreeLevel){ + return new CollegeExpression(this, $it -> ((College)$it).updateDegreeLevel(degreeLevel)); + } + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeListExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeListExpression.java new file mode 100644 index 000000000..a4442c5b7 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeListExpression.java @@ -0,0 +1,25 @@ + +package com.example.inheritancematchingservice.college; + +import io.teaql.core.SmartList; +import io.teaql.core.value.Expression; +import io.teaql.core.value.SmartListExpression; +import java.util.function.Function; + +public class CollegeListExpression extends SmartListExpression { + public CollegeListExpression(Expression> expression){ + super(expression); + } + + public CollegeListExpression(Expression expression, Function> function){ + super(expression, function); + } + + public CollegeExpression first() { + return new CollegeExpression(super.first()); + } + + public CollegeExpression get(int index) { + return new CollegeExpression(super.get(index)); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeRequest.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeRequest.java new file mode 100644 index 000000000..fd542aff0 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/college/CollegeRequest.java @@ -0,0 +1,939 @@ + +package com.example.inheritancematchingservice.college; + +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.platform.PlatformRequest; +import com.example.inheritancematchingservice.school.SchoolRequest; +import com.example.inheritancematchingservice.schooltype.SchoolType; +import com.example.inheritancematchingservice.schooltype.SchoolTypeRequest; +import io.teaql.core.AggrFunction; +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.util.Objects; + +public class CollegeRequest extends SchoolRequest { + + /** + * @deprecated AI agents and business code must use the generated Q facade + * instead of constructing request builders directly. + */ + @Deprecated + @SuppressWarnings("unchecked") + public CollegeRequest(Class returnType){ + this(returnType, () -> (T) new College()); + } + + protected CollegeRequest(Class returnType, java.util.function.Supplier factory){ + super(returnType, factory); + selectId(); + selectVersion(); + } + + public CollegeRequest comment(String comment){ + super.internalComment(comment); + return this; + } + + /** Independent query graph; ordinary roll-up handles remain live. */ + @Override + @SuppressWarnings("unchecked") + public CollegeRequest copy(){ + return (CollegeRequest) super.copy(); + } + + @Override + @SuppressWarnings("unchecked") + protected io.teaql.core.BaseRequest internalCopyTarget(){ + return new CollegeRequest<>((Class) returnType(), this::internalNewEntity); + } + + // purpose() 继承自 BaseRequest,返回 ExecutableRequest(终结方法) + + public CollegeRequest returnType(Class returnType){ + super.setReturnType(returnType); + return this; + } + + public CollegeRequest enableAggregationCache(long cacheExpiredMillis){ + super.enableAggregationCache(); + super.aggregateCacheTime(cacheExpiredMillis); + return this; + } + + public CollegeRequest enableAggregationCache(){ + return enableAggregationCache(0l); + } + + + public CollegeRequest 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 CollegeRequest optimizeForContinuousPageFetch(){ + super.optimizeForContinuousPageFetch(); + return this; + } + + public CollegeRequest optimizeForContinuousPageFetch(String namespace, int ttlSeconds){ + super.optimizeForContinuousPageFetch(namespace, ttlSeconds); + return this; + } + + public CollegeRequest optimizePaginationWithIdSet(){ + super.optimizePaginationWithIdSet(); + return this; + } + + public CollegeRequest optimizePaginationWithIdSet( + String namespace, int ttlSeconds, int maxIds){ + super.optimizePaginationWithIdSet(namespace, ttlSeconds, maxIds); + return this; + } + + public CollegeRequest topNProbeParentThreshold(int threshold){ + super.topNProbeParentThreshold(threshold); + return this; + } + + public CollegeRequest appendSearchCriteria(SearchCriteria searchCriteria){ + return (CollegeRequest)super.appendSearchCriteria(searchCriteria); + } + + public CollegeRequest filter(String property1, Operator operator, String property2){ + return appendSearchCriteria(new TwoOperatorCriteria(operator, new PropertyReference(property1), new PropertyReference(property2))); + } + + + public CollegeRequest matchingAnyOf(CollegeRequest college){ + super.internalMatchAny(college); + return this; + } + + public CollegeRequest matchingIdsOf(CollegeRequest request){ + Objects.requireNonNull(request, "matching request"); + return appendSearchCriteria(new SubQuerySearchCriteria( + College.ID_PROPERTY, request, College.ID_PROPERTY)); + } + + public CollegeRequest enhanceChildrenIfNeeded(){ + return this; + } + + public CollegeRequest withDeletedRows(){ + super.withDeletedRows(); + return this; + } + + public CollegeRequest deletedRowsOnly(){ + super.deletedRowsOnly(); + return this; + } + + public CollegeRequest selectSelf(){ + super.selectSelf(); + return selectDegreeLevel(); + } + + public CollegeRequest selectSelfFields(){ + return selectSelf(); + } + + public CollegeRequest selectSelfWithoutParent(){ + selectId(); + selectVersion(); + selectProperty(College.DEGREE_LEVEL_PROPERTY); + return this; + } + + public CollegeRequest selectAll(){ + super.selectAll(); + return selectDegreeLevel(); + } + + public CollegeRequest selectChildren(){ + super.selectAny(); + return selectDegreeLevel(); + } + + + public CollegeRequest selectDegreeLevel(){ + selectProperty(College.DEGREE_LEVEL_PROPERTY); + return this; + } + + /** + * fill the degreeLevel with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS degreeLevel) to fetch degreeLevel property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public CollegeRequest unselectDegreeLevel(){ + unselectProperty(College.DEGREE_LEVEL_PROPERTY); + return this; + } + public CollegeRequest selectPlatformIdOnly(){ + super.selectPlatformIdOnly(); + return this; + } + + public CollegeRequest selectPlatform(){ + super.selectPlatform(); + return this; + } + + public CollegeRequest selectPlatformWith(PlatformRequest platform){ + super.selectPlatformWith(platform); + return this; + } + + public CollegeRequest unselectPlatform(){ + super.unselectPlatform(); + return this; + } + public CollegeRequest selectSchoolTypeIdOnly(){ + super.selectSchoolTypeIdOnly(); + return this; + } + + public CollegeRequest selectSchoolType(){ + super.selectSchoolType(); + return this; + } + + public CollegeRequest selectSchoolTypeWith(SchoolTypeRequest schoolType){ + super.selectSchoolTypeWith(schoolType); + return this; + } + + public CollegeRequest unselectSchoolType(){ + super.unselectSchoolType(); + return this; + } + public CollegeRequest selectName(){ + super.selectName(); + return this; + } + + /** + * fill the name with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS name) to fetch name property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public CollegeRequest unselectName(){ + super.unselectName(); + return this; + } + public CollegeRequest selectStudentCapacity(){ + super.selectStudentCapacity(); + return this; + } + + /** + * fill the studentCapacity with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS studentCapacity) to fetch studentCapacity property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + /** + * fill the studentCapacity with customized aggrFunction, TEAQL uses ({aggrFunction}(studentCapacity) AS studentCapacity to fetch studentCapacity property. + * @param aggrFunction aggrFunction + */ + public CollegeRequest selectStudentCapacity(AggrFunction aggrFunction){ + super.selectStudentCapacity(aggrFunction); + return this; + } + + + public CollegeRequest unselectStudentCapacity(){ + super.unselectStudentCapacity(); + return this; + } + public CollegeRequest selectVersion(){ + super.selectVersion(); + return this; + } + + /** + * fill the version with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS version) to fetch version property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public CollegeRequest unselectVersion(){ + super.unselectVersion(); + return this; + } + public CollegeRequest selectId(){ + super.selectId(); + return this; + } + + /** + * fill the id with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS id) to fetch id property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public CollegeRequest unselectId(){ + super.unselectId(); + return this; + } + + public CollegeRequest filterByDegreeLevel(String... degreeLevel){ + if (degreeLevel == null || degreeLevel.length == 0) { + throw new IllegalArgumentException("filterByDegreeLevel parameter degreeLevel cannot be empty"); + } + return appendSearchCriteria(createDegreeLevelCriteria(Operator.EQUAL, (Object[])degreeLevel)); + } + + public CollegeRequest withDegreeLevel(Operator operator, Object... values){ + return appendSearchCriteria(createDegreeLevelCriteria(operator, values)); + } + + public CollegeRequest withDegreeLevelIsUnknown(){ + return withDegreeLevel(Operator.IS_NULL); + } + + public CollegeRequest withDegreeLevelIsKnown(){ + return withDegreeLevel(Operator.IS_NOT_NULL); + } + + public SearchCriteria createDegreeLevelCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(College.DEGREE_LEVEL_PROPERTY, operator, values); + } + + public CollegeRequest withDegreeLevelIsNot(String degreeLevel){ + return withDegreeLevel(Operator.NOT_EQUAL, degreeLevel); + } + + public CollegeRequest withDegreeLevelIn(String... degreeLevel){ + return withDegreeLevel(Operator.IN, (Object[])degreeLevel); + } + + public CollegeRequest withDegreeLevelNotIn(String... degreeLevel){ + return withDegreeLevel(Operator.NOT_IN, (Object[])degreeLevel); + } + public CollegeRequest withDegreeLevelGreaterThan(String degreeLevel){ + return withDegreeLevel(Operator.GREATER_THAN, degreeLevel); + } + + public CollegeRequest withDegreeLevelGreaterThanOrEqualTo(String degreeLevel){ + return withDegreeLevel(Operator.GREATER_THAN_OR_EQUAL, degreeLevel); + } + + public CollegeRequest withDegreeLevelLessThan(String degreeLevel){ + return withDegreeLevel(Operator.LESS_THAN, degreeLevel); + } + + public CollegeRequest withDegreeLevelLessThanOrEqualTo(String degreeLevel){ + return withDegreeLevel(Operator.LESS_THAN_OR_EQUAL, degreeLevel); + } + + public CollegeRequest withDegreeLevelBetween(String startOfDegreeLevel, String endOfDegreeLevel){ + return withDegreeLevel(Operator.BETWEEN, startOfDegreeLevel, endOfDegreeLevel); + } + public CollegeRequest withDegreeLevelStartingWith(String degreeLevel){ + return withDegreeLevel(Operator.BEGIN_WITH, degreeLevel); + } + public CollegeRequest withDegreeLevelContaining(String degreeLevel){ + return withDegreeLevel(Operator.CONTAIN, degreeLevel); + } + + public CollegeRequest withDegreeLevelNotContaining(String degreeLevel){ + return withDegreeLevel(Operator.NOT_CONTAIN, degreeLevel); + } + + public CollegeRequest withDegreeLevelNotStartingWith(String degreeLevel){ + return withDegreeLevel(Operator.NOT_BEGIN_WITH, degreeLevel); + } + + public CollegeRequest withDegreeLevelEndingWith(String degreeLevel){ + return withDegreeLevel(Operator.END_WITH, degreeLevel); + } + + public CollegeRequest withDegreeLevelNotEndingWith(String degreeLevel){ + return withDegreeLevel(Operator.NOT_END_WITH, degreeLevel); + } + + public CollegeRequest withDegreeLevelIs(String degreeLevel){ + return withDegreeLevel(Operator.EQUAL, degreeLevel); + } + + public CollegeRequest withDegreeLevelSoundingLike(String degreeLevel){ + return withDegreeLevel(Operator.SOUNDS_LIKE, degreeLevel); + } + + + + public CollegeRequest filterByPlatform(Platform platform){ + return (CollegeRequest)super.filterByPlatform(platform); + } + + public CollegeRequest withPlatform(Operator operator, Object... values){ + return (CollegeRequest)super.withPlatform(operator, values); + } + + public CollegeRequest withPlatformIsUnknown(){ + return (CollegeRequest)super.withPlatformIsUnknown(); + } + + public CollegeRequest withPlatformIsKnown(){ + return (CollegeRequest)super.withPlatformIsKnown(); + } + + public CollegeRequest filterByPlatform(Long platform){ + return (CollegeRequest)super.filterByPlatform(platform); + } + + public CollegeRequest withPlatformMatching(PlatformRequest platform){ + return (CollegeRequest)super.withPlatformMatching(platform); + } + + public CollegeRequest filterBySchoolType(SchoolType schoolType){ + return (CollegeRequest)super.filterBySchoolType(schoolType); + } + + public CollegeRequest withSchoolType(Operator operator, Object... values){ + return (CollegeRequest)super.withSchoolType(operator, values); + } + + public CollegeRequest withSchoolTypeIsUnknown(){ + return (CollegeRequest)super.withSchoolTypeIsUnknown(); + } + + public CollegeRequest withSchoolTypeIsKnown(){ + return (CollegeRequest)super.withSchoolTypeIsKnown(); + } + + public CollegeRequest filterBySchoolType(Long schoolType){ + return (CollegeRequest)super.filterBySchoolType(schoolType); + } + + public CollegeRequest withSchoolTypeMatching(SchoolTypeRequest schoolType){ + return (CollegeRequest)super.withSchoolTypeMatching(schoolType); + } + + public CollegeRequest filterByName(String name){ + return (CollegeRequest)super.filterByName(name); + } + + public CollegeRequest withName(Operator operator, Object... values){ + return (CollegeRequest)super.withName(operator, values); + } + + public CollegeRequest withNameIsUnknown(){ + return (CollegeRequest)super.withNameIsUnknown(); + } + + public CollegeRequest withNameIsKnown(){ + return (CollegeRequest)super.withNameIsKnown(); + } + + public CollegeRequest withNameStartingWith(String Name){ + return (CollegeRequest)super.withNameStartingWith(Name); + } + public CollegeRequest withNameContaining(String Name){ + return (CollegeRequest)super.withNameContaining(Name); + } + + public CollegeRequest withNameEndingWith(String Name){ + return (CollegeRequest)super.withNameEndingWith(Name); + } + + + public CollegeRequest filterByStudentCapacity(Integer studentCapacity){ + return (CollegeRequest)super.filterByStudentCapacity(studentCapacity); + } + + public CollegeRequest withStudentCapacity(Operator operator, Object... values){ + return (CollegeRequest)super.withStudentCapacity(operator, values); + } + + public CollegeRequest withStudentCapacityIsUnknown(){ + return (CollegeRequest)super.withStudentCapacityIsUnknown(); + } + + public CollegeRequest withStudentCapacityIsKnown(){ + return (CollegeRequest)super.withStudentCapacityIsKnown(); + } + + public CollegeRequest withStudentCapacityGreaterThan(Integer studentCapacity){ + return (CollegeRequest)super.withStudentCapacityGreaterThan(studentCapacity); + } + + public CollegeRequest withStudentCapacityGreaterThanOrEqualTo(Integer studentCapacity){ + return (CollegeRequest)super.withStudentCapacityGreaterThanOrEqualTo(studentCapacity); + } + + public CollegeRequest withStudentCapacityLessThan(Integer studentCapacity){ + return (CollegeRequest)super.withStudentCapacityLessThan(studentCapacity); + } + + public CollegeRequest withStudentCapacityLessThanOrEqualTo(Integer studentCapacity){ + return (CollegeRequest)super.withStudentCapacityLessThanOrEqualTo(studentCapacity); + } + + public CollegeRequest withStudentCapacityBetween(Integer startOfStudentCapacity, Integer endOfStudentCapacity){ + return (CollegeRequest)super.withStudentCapacityBetween(startOfStudentCapacity, endOfStudentCapacity); + } + + + public CollegeRequest filterByVersion(Long version){ + return (CollegeRequest)super.filterByVersion(version); + } + + public CollegeRequest withVersion(Operator operator, Object... values){ + return (CollegeRequest)super.withVersion(operator, values); + } + + public CollegeRequest withVersionIsUnknown(){ + return (CollegeRequest)super.withVersionIsUnknown(); + } + + public CollegeRequest withVersionIsKnown(){ + return (CollegeRequest)super.withVersionIsKnown(); + } + + + public CollegeRequest withIdIs(Long value){ + return (CollegeRequest)super.withIdIs(value); + } + + public CollegeRequest withId(Operator operator, Object... values){ + return (CollegeRequest)super.withId(operator, values); + } + + + public CollegeRequest count(){ + super.count(); + setPageCountOperation(io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.NAMED_COUNT, "count", null, null)); + return this; + } + public CollegeRequest 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 CollegeRequest minStudentCapacity(){ + super.minStudentCapacity(); + return this; + } + + public CollegeRequest minStudentCapacityAs(String retName){ + super.minStudentCapacityAs(retName); + return this; + } + public CollegeRequest maxStudentCapacity(){ + super.maxStudentCapacity(); + return this; + } + + public CollegeRequest maxStudentCapacityAs(String retName){ + super.maxStudentCapacityAs(retName); + return this; + } + public CollegeRequest sumStudentCapacity(){ + super.sumStudentCapacity(); + return this; + } + + public CollegeRequest sumStudentCapacityAs(String retName){ + super.sumStudentCapacityAs(retName); + return this; + } + public CollegeRequest avgStudentCapacity(){ + super.avgStudentCapacity(); + return this; + } + + public CollegeRequest avgStudentCapacityAs(String retName){ + super.avgStudentCapacityAs(retName); + return this; + } + public CollegeRequest stddevStudentCapacity(){ + super.standardDeviationStudentCapacity(); + return this; + } + + public CollegeRequest stddevStudentCapacityAs(String retName){ + super.standardDeviationStudentCapacityAs(retName); + return this; + } + public CollegeRequest stddev_popStudentCapacity(){ + super.squareRootOfPopulationStandardDeviationStudentCapacity(); + return this; + } + + public CollegeRequest stddev_popStudentCapacityAs(String retName){ + super.squareRootOfPopulationStandardDeviationStudentCapacityAs(retName); + return this; + } + public CollegeRequest var_sampStudentCapacity(){ + super.sampleVarianceStudentCapacity(); + return this; + } + + public CollegeRequest var_sampStudentCapacityAs(String retName){ + super.sampleVarianceStudentCapacityAs(retName); + return this; + } + public CollegeRequest var_popStudentCapacity(){ + super.samplePopulationVarianceStudentCapacity(); + return this; + } + + public CollegeRequest var_popStudentCapacityAs(String retName){ + super.samplePopulationVarianceStudentCapacityAs(retName); + return this; + } + public CollegeRequest groupByPlatformWithDetails(){ + super.groupByPlatformWithDetails(); + return this; + } + + public CollegeRequest groupByPlatformWithDetails(PlatformRequest subRequest){ + super.groupByPlatformWithDetails(subRequest); + return this; + } + + public CollegeRequest groupBySchoolTypeWithDetails(){ + super.groupBySchoolTypeWithDetails(); + return this; + } + + public CollegeRequest groupBySchoolTypeWithDetails(SchoolTypeRequest subRequest){ + super.groupBySchoolTypeWithDetails(subRequest); + return this; + } + + + + + + public CollegeRequest countDistinctDegreeLevel(){ + return countDistinctDegreeLevelAs("degree_level_distinct_count"); + } + + public CollegeRequest countDistinctDegreeLevelAs(String alias){ + super.countDistinctProperty(alias, College.DEGREE_LEVEL_PROPERTY); + return this; + } + public CollegeRequest countDistinctPlatform(){ + return countDistinctPlatformAs("platform_distinct_count"); + } + + public CollegeRequest countDistinctPlatformAs(String alias){ + super.countDistinctProperty(alias, College.PLATFORM_PROPERTY); + return this; + } + public CollegeRequest countDistinctSchoolType(){ + return countDistinctSchoolTypeAs("school_type_distinct_count"); + } + + public CollegeRequest countDistinctSchoolTypeAs(String alias){ + super.countDistinctProperty(alias, College.SCHOOL_TYPE_PROPERTY); + return this; + } + public CollegeRequest countDistinctName(){ + return countDistinctNameAs("name_distinct_count"); + } + + public CollegeRequest countDistinctNameAs(String alias){ + super.countDistinctProperty(alias, College.NAME_PROPERTY); + return this; + } + public CollegeRequest countDistinctStudentCapacity(){ + return countDistinctStudentCapacityAs("student_capacity_distinct_count"); + } + + public CollegeRequest countDistinctStudentCapacityAs(String alias){ + super.countDistinctProperty(alias, College.STUDENT_CAPACITY_PROPERTY); + return this; + } + public CollegeRequest countDistinctVersion(){ + return countDistinctVersionAs("version_distinct_count"); + } + + public CollegeRequest countDistinctVersionAs(String alias){ + super.countDistinctProperty(alias, College.VERSION_PROPERTY); + return this; + } + public CollegeRequest countDistinctId(){ + return countDistinctIdAs("id_distinct_count"); + } + + public CollegeRequest countDistinctIdAs(String alias){ + super.countDistinctProperty(alias, College.ID_PROPERTY); + return this; + } + + public CollegeRequest groupByDegreeLevel(){ + groupBy(College.DEGREE_LEVEL_PROPERTY); + return this; + } + + public CollegeRequest groupByDegreeLevelAs(String retName){ + groupBy(retName, College.DEGREE_LEVEL_PROPERTY); + return this; + } + + public CollegeRequest groupByDegreeLevelWithFunction(String retName, AggrFunction function){ + groupBy(retName, College.DEGREE_LEVEL_PROPERTY, function); + return this; + } + + + public CollegeRequest groupByPlatformWith(PlatformRequest subRequest){ + super.groupByPlatformWith(subRequest); + return this; + } + public CollegeRequest groupByPlatform(){ + super.groupByPlatform(); + return this; + } + + public CollegeRequest groupByPlatformAs(String retName){ + super.groupByPlatformAs(retName); + return this; + } + + public CollegeRequest groupByPlatformWithFunction(String retName, AggrFunction function){ + super.groupByPlatformWithFunction(retName, function); + return this; + } + public CollegeRequest groupBySchoolTypeWith(SchoolTypeRequest subRequest){ + super.groupBySchoolTypeWith(subRequest); + return this; + } + public CollegeRequest groupBySchoolType(){ + super.groupBySchoolType(); + return this; + } + + public CollegeRequest groupBySchoolTypeAs(String retName){ + super.groupBySchoolTypeAs(retName); + return this; + } + + public CollegeRequest groupBySchoolTypeWithFunction(String retName, AggrFunction function){ + super.groupBySchoolTypeWithFunction(retName, function); + return this; + } + + public CollegeRequest groupByName(){ + super.groupByName(); + return this; + } + + public CollegeRequest groupByNameAs(String retName){ + super.groupByNameAs(retName); + return this; + } + + public CollegeRequest groupByNameWithFunction(String retName, AggrFunction function){ + super.groupByNameWithFunction(retName, function); + return this; + } + + public CollegeRequest groupByStudentCapacity(){ + super.groupByStudentCapacity(); + return this; + } + + public CollegeRequest groupByStudentCapacityAs(String retName){ + super.groupByStudentCapacityAs(retName); + return this; + } + + public CollegeRequest groupByStudentCapacityWithFunction(String retName, AggrFunction function){ + super.groupByStudentCapacityWithFunction(retName, function); + return this; + } + + public CollegeRequest groupByVersion(){ + super.groupByVersion(); + return this; + } + + public CollegeRequest groupByVersionAs(String retName){ + super.groupByVersionAs(retName); + return this; + } + + public CollegeRequest groupByVersionWithFunction(String retName, AggrFunction function){ + super.groupByVersionWithFunction(retName, function); + return this; + } + + public CollegeRequest groupById(){ + super.groupById(); + return this; + } + + public CollegeRequest groupByIdAs(String retName){ + super.groupByIdAs(retName); + return this; + } + + public CollegeRequest groupByIdWithFunction(String retName, AggrFunction function){ + super.groupByIdWithFunction(retName, function); + return this; + } + + public CollegeRequest orderByDegreeLevelAscending(){ + addOrderByAscending(College.DEGREE_LEVEL_PROPERTY); + return this; + } + + public CollegeRequest orderByDegreeLevelDescending(){ + addOrderByDescending(College.DEGREE_LEVEL_PROPERTY); + return this; + } + public CollegeRequest orderByDegreeLevelAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(College.DEGREE_LEVEL_PROPERTY); + return this; + } + + public CollegeRequest orderByDegreeLevelDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(College.DEGREE_LEVEL_PROPERTY); + return this; + } + public CollegeRequest orderByPlatformAscending(){ + super.orderByPlatformAscending(); + return this; + } + + public CollegeRequest orderByPlatformDescending(){ + super.orderByPlatformDescending(); + return this; + } + + public CollegeRequest orderBySchoolTypeAscending(){ + super.orderBySchoolTypeAscending(); + return this; + } + + public CollegeRequest orderBySchoolTypeDescending(){ + super.orderBySchoolTypeDescending(); + return this; + } + + public CollegeRequest orderByNameAscending(){ + super.orderByNameAscending(); + return this; + } + + public CollegeRequest orderByNameDescending(){ + super.orderByNameDescending(); + return this; + } + public CollegeRequest orderByNameAscendingUsingGBK(){ + super.orderByNameAscendingUsingGBK(); + return this; + } + + public CollegeRequest orderByNameDescendingUsingGBK(){ + super.orderByNameDescendingUsingGBK(); + return this; + } + public CollegeRequest orderByStudentCapacityAscending(){ + super.orderByStudentCapacityAscending(); + return this; + } + + public CollegeRequest orderByStudentCapacityDescending(){ + super.orderByStudentCapacityDescending(); + return this; + } + + public CollegeRequest orderByVersionAscending(){ + super.orderByVersionAscending(); + return this; + } + + public CollegeRequest orderByVersionDescending(){ + super.orderByVersionDescending(); + return this; + } + + public CollegeRequest orderByIdAscending(){ + super.orderByIdAscending(); + return this; + } + + public CollegeRequest orderByIdDescending(){ + super.orderByIdDescending(); + return this; + } + + + + + + /** + * get topN records + * @param topN records number + */ + public CollegeRequest top(int topN) { + super.top(topN); + return this; + } + + /** Cross-runtime bounded-query alias. */ + public CollegeRequest limit(int limit) { + return top(limit); + } + + /** + * get records from offset(inclusive) to offset+size(exclusive) + * @param offset record offset + * @param size records number + */ + public CollegeRequest offset(int offset, int size) { + super.offset(offset, size); + return this; + } + + /** + * retrieve all records + */ + public CollegeRequest unlimited() { + super.unlimited(); + return this; + } + + /** + * get records of one page + * @param pageNumber page number(1-based) + * @param pageSize page size + */ + public CollegeRequest 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 CollegeRequest page(int pageNumber) { + return page(pageNumber, 10); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/Platform.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/Platform.java new file mode 100644 index 000000000..db2a9a7ca --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/Platform.java @@ -0,0 +1,173 @@ + +package com.example.inheritancematchingservice.platform; + +import com.example.inheritancematchingservice.school.School; +import com.example.inheritancematchingservice.schooltype.SchoolType; +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 Platform extends BaseEntity implements RemoteInput { + public static String INTERNAL_TYPE = "Platform"; + + // Framework metadata: complete fixed layout, independent of SQL/projection order. + public static final String __TEAQL_FIELD_LAYOUT_REVISION = "fb6f885aa255ea9a640abdacbfd75ce6a8def1126fdd5125a9de45c533c26d44"; + 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("base_url", 2), java.util.Map.entry("version", 3)); + 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("base_url", java.util.List.of("baseUrl", "base_url")), 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( + "school_type_list", "school_list"); + public static final FieldLayout __TEAQL_FIELD_LAYOUT = + FieldLayout.installGenerated(FieldLayout.generated( + Platform.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 BASE_URL_PROPERTY = "base_url"; + public static final String SCHOOL_TYPE_LIST_PROPERTY = "school_type_list"; + public static final String SCHOOL_LIST_PROPERTY = "school_list"; + private String name; + + private String baseUrl; + + private SmartList schoolTypeList; + private SmartList schoolList; + + public String getName(){ + return this.name; + } + + public String getBaseUrl(){ + return this.baseUrl; + } + + public SmartList getSchoolTypeList(){ + return this.schoolTypeList == null ? SmartList.unloaded() : this.schoolTypeList; + } + public SmartList getSchoolList(){ + return this.schoolList == null ? SmartList.unloaded() : this.schoolList; + } + public Platform 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 Platform updateBaseUrl(String baseUrl){ + baseUrl = (baseUrl == null ? null : baseUrl.trim()); + if(isPropertyLoaded(BASE_URL_PROPERTY) && Objects.equals(this.baseUrl, baseUrl)){ + return this; + } + handleUpdate(BASE_URL_PROPERTY, getBaseUrl(), baseUrl); + this.baseUrl = baseUrl; + return this; + } + + public Platform addSchoolType(SchoolType schoolType){ + if (schoolType == null){ + return this; + } + + if(null == this.schoolTypeList){ + SmartList teaqlUnloadedItems = SmartList.unloaded(); + this.schoolTypeList = teaqlUnloadedItems.map(value -> value); + } + + this.schoolTypeList.add(schoolType); + schoolType.updatePlatform(this); + return this; + } + public Platform addSchool(School school){ + if (school == null){ + return this; + } + + if(null == this.schoolList){ + SmartList teaqlUnloadedItems = SmartList.unloaded(); + this.schoolList = teaqlUnloadedItems.map(value -> value); + } + + this.schoolList.add(school); + school.updatePlatform(this); + return this; + } + + public static Platform refer(Long id){ + Platform refer = new Platform(); + refer.__internalSet("id", id); + refer.set$status(EntityStatus.REFER); + return refer; + } + @Override + public String typeName(){ + return INTERNAL_TYPE; + } + + public Platform 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 "base_url": this.baseUrl = (value == null ? null : ((String)value).trim()); break; + + case "school_type_list": this.schoolTypeList = (SmartList) value; break; + case "school_list": this.schoolList = (SmartList) value; break; + default: super.__internalSet(property, value); + } + } + + @Override + @FrameworkInternal + public Object __internalGet(String property) { + switch (property) { + case "name": return this.name; + case "base_url": return this.baseUrl; + case "school_type_list": return this.schoolTypeList; + case "school_list": return this.schoolList; + 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; + case "baseUrl": return this.baseUrl; + default: return super.__internalGet(property); + } + } + } + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformChecker.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformChecker.java new file mode 100644 index 000000000..da7313686 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformChecker.java @@ -0,0 +1,70 @@ + +package com.example.inheritancematchingservice.platform; + +import com.example.inheritancematchingservice.school.School; +import com.example.inheritancematchingservice.school.SchoolChecker; +import com.example.inheritancematchingservice.schooltype.SchoolType; +import com.example.inheritancematchingservice.schooltype.SchoolTypeChecker; +import io.teaql.core.UserContext; +import io.teaql.core.checker.Checker; +import io.teaql.core.checker.ObjectLocation; + +public class PlatformChecker implements Checker{ + + public String type(){ + return Platform.INTERNAL_TYPE; + } + + public void checkAndFix(UserContext _context, Platform platform, ObjectLocation _parentLocation){ + if(needCheck(_context, platform)){ + markAsChecked(_context, platform); + doCheck(_context, platform, _parentLocation); + } + } + + public void doCheck(UserContext _context, Platform platform, ObjectLocation _parentLocation){ + if((platform == null)){ + return; + } + boolean _contextFixEligible = needContextFix(_context, platform); + if(platform.needPersist()){ + } + if(platform.newItem()){ + }else if(platform.updateItem()){ + if(!platform.isPropertyLoaded("name")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "name"), "Mutation requires a fully loaded entity"); + } + if(!platform.isPropertyLoaded("base_url")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "base_url"), "Mutation requires a fully loaded entity"); + } + + } + checkName(_context, platform.getProperty(Platform.NAME_PROPERTY), newLocation(_parentLocation, "name")); + checkBaseUrl(_context, platform.getProperty(Platform.BASE_URL_PROPERTY), newLocation(_parentLocation, "base_url")); + for(int i = 0; platform.getSchoolTypeList() != null && i < platform.getSchoolTypeList().size(); i++){ + SchoolType schoolType = platform.getSchoolTypeList().get(i); + new SchoolTypeChecker().checkAndFix(_context, schoolType, newLocation(_parentLocation, "school_type_list", i)); + } + for(int i = 0; platform.getSchoolList() != null && i < platform.getSchoolList().size(); i++){ + School school = platform.getSchoolList().get(i); + new SchoolChecker().checkAndFix(_context, school, newLocation(_parentLocation, "school_list", i)); + } + } + + public void checkName(UserContext _context, String name, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, name); + if((name == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, name); + + } + public void checkBaseUrl(UserContext _context, String baseUrl, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, baseUrl); + if((baseUrl == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, baseUrl); + + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformExpression.java new file mode 100644 index 000000000..739be6bf5 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformExpression.java @@ -0,0 +1,66 @@ + +package com.example.inheritancematchingservice.platform; + +import com.example.inheritancematchingservice.school.School; +import com.example.inheritancematchingservice.school.SchoolListExpression; +import com.example.inheritancematchingservice.schooltype.SchoolType; +import com.example.inheritancematchingservice.schooltype.SchoolTypeListExpression; +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 PlatformExpression extends ExpressionAdaptor implements BaseEntityExpression { + public PlatformExpression(Expression expression){ + super(expression); + } + + public PlatformExpression(Expression expression, Function function){ + super(expression, function); + } + + public PlatformExpression updateId(Long id){ + return new PlatformExpression(this, $it -> {((Platform)$it).__internalSet("id", id); return this;}); + } + + public PlatformExpression save(UserContext userContext){ + return new PlatformExpression(this, $it -> ((Platform)$it).auditAs("Saved by Expression").save(userContext)); + } + + public PlatformExpression save(String intent, UserContext userContext){ + return new PlatformExpression(this, $it -> ((Platform)$it).auditAs(intent).save(userContext)); + } + + public boolean isNull() { + return resolve() == null; + } + + + public Expression getName(){ + return loaded("name", "getName", Platform::getName); + } + public PlatformExpression updateName(String name){ + return new PlatformExpression(this, $it -> ((Platform)$it).updateName(name)); + } + + public Expression getBaseUrl(){ + return loaded("base_url", "getBaseUrl", Platform::getBaseUrl); + } + public PlatformExpression updateBaseUrl(String baseUrl){ + return new PlatformExpression(this, $it -> ((Platform)$it).updateBaseUrl(baseUrl)); + } + + public SchoolTypeListExpression getSchoolTypeList(){ + return new SchoolTypeListExpression(loaded("school_type_list", "getSchoolTypeList", Platform::getSchoolTypeList)); + } + public SchoolListExpression getSchoolList(){ + return new SchoolListExpression(loaded("school_list", "getSchoolList", Platform::getSchoolList)); + } + public PlatformExpression addSchoolType(SchoolType schoolType){ + return new PlatformExpression(this, $it -> ((Platform)$it).addSchoolType(schoolType)); + } + public PlatformExpression addSchool(School school){ + return new PlatformExpression(this, $it -> ((Platform)$it).addSchool(school)); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformListExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformListExpression.java new file mode 100644 index 000000000..7722b7b89 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformListExpression.java @@ -0,0 +1,25 @@ + +package com.example.inheritancematchingservice.platform; + +import io.teaql.core.SmartList; +import io.teaql.core.value.Expression; +import io.teaql.core.value.SmartListExpression; +import java.util.function.Function; + +public class PlatformListExpression extends SmartListExpression { + public PlatformListExpression(Expression> expression){ + super(expression); + } + + public PlatformListExpression(Expression expression, Function> function){ + super(expression, function); + } + + public PlatformExpression first() { + return new PlatformExpression(super.first()); + } + + public PlatformExpression get(int index) { + return new PlatformExpression(super.get(index)); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformRequest.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformRequest.java new file mode 100644 index 000000000..97090dd96 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/platform/PlatformRequest.java @@ -0,0 +1,980 @@ + +package com.example.inheritancematchingservice.platform; + +import com.example.inheritancematchingservice.Q; +import com.example.inheritancematchingservice.school.School; +import com.example.inheritancematchingservice.school.SchoolRequest; +import com.example.inheritancematchingservice.schooltype.SchoolType; +import com.example.inheritancematchingservice.schooltype.SchoolTypeRequest; +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.util.Objects; + +public class PlatformRequest extends BaseRequest { + + /** + * @deprecated AI agents and business code must use the generated Q facade + * instead of constructing request builders directly. + */ + @Deprecated + @SuppressWarnings("unchecked") + public PlatformRequest(Class returnType){ + this(returnType, () -> (T) new Platform()); + } + + protected PlatformRequest(Class returnType, java.util.function.Supplier factory){ + super(returnType, factory); + selectId(); + selectVersion(); + } + + public PlatformRequest comment(String comment){ + super.internalComment(comment); + return this; + } + + /** Independent query graph; ordinary roll-up handles remain live. */ + @Override + @SuppressWarnings("unchecked") + public PlatformRequest copy(){ + return (PlatformRequest) super.copy(); + } + + @Override + @SuppressWarnings("unchecked") + protected io.teaql.core.BaseRequest internalCopyTarget(){ + return new PlatformRequest<>((Class) returnType(), this::internalNewEntity); + } + + // purpose() 继承自 BaseRequest,返回 ExecutableRequest(终结方法) + + public PlatformRequest returnType(Class returnType){ + super.setReturnType(returnType); + return this; + } + + public PlatformRequest enableAggregationCache(long cacheExpiredMillis){ + super.enableAggregationCache(); + super.aggregateCacheTime(cacheExpiredMillis); + return this; + } + + public PlatformRequest enableAggregationCache(){ + return enableAggregationCache(0l); + } + + + public PlatformRequest 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 PlatformRequest optimizeForContinuousPageFetch(){ + super.optimizeForContinuousPageFetch(); + return this; + } + + public PlatformRequest optimizeForContinuousPageFetch(String namespace, int ttlSeconds){ + super.optimizeForContinuousPageFetch(namespace, ttlSeconds); + return this; + } + + public PlatformRequest optimizePaginationWithIdSet(){ + super.optimizePaginationWithIdSet(); + return this; + } + + public PlatformRequest optimizePaginationWithIdSet( + String namespace, int ttlSeconds, int maxIds){ + super.optimizePaginationWithIdSet(namespace, ttlSeconds, maxIds); + return this; + } + + public PlatformRequest topNProbeParentThreshold(int threshold){ + super.topNProbeParentThreshold(threshold); + return this; + } + + public PlatformRequest appendSearchCriteria(SearchCriteria searchCriteria){ + return (PlatformRequest)super.appendSearchCriteria(searchCriteria); + } + + public PlatformRequest filter(String property1, Operator operator, String property2){ + return appendSearchCriteria(new TwoOperatorCriteria(operator, new PropertyReference(property1), new PropertyReference(property2))); + } + + + public PlatformRequest matchingAnyOf(PlatformRequest platform){ + super.internalMatchAny(platform); + return this; + } + + public PlatformRequest matchingIdsOf(PlatformRequest request){ + Objects.requireNonNull(request, "matching request"); + return appendSearchCriteria(new SubQuerySearchCriteria( + Platform.ID_PROPERTY, request, Platform.ID_PROPERTY)); + } + + public PlatformRequest enhanceChildrenIfNeeded(){ + return this; + } + + public PlatformRequest withDeletedRows(){ + super.withDeletedRows(); + return this; + } + + public PlatformRequest deletedRowsOnly(){ + super.deletedRowsOnly(); + return this; + } + + public PlatformRequest selectSelf(){ + super.selectSelf(); + return selectId().selectName().selectBaseUrl().selectVersion(); + } + + public PlatformRequest selectSelfFields(){ + return selectSelf(); + } + + public PlatformRequest selectSelfWithoutParent(){ + selectId(); + selectVersion(); + selectProperty(Platform.ID_PROPERTY); + selectProperty(Platform.NAME_PROPERTY); + selectProperty(Platform.BASE_URL_PROPERTY); + selectProperty(Platform.VERSION_PROPERTY); + return this; + } + + public PlatformRequest selectAll(){ + super.selectAll(); + return selectId().selectName().selectBaseUrl().selectVersion(); + } + + public PlatformRequest selectChildren(){ + super.selectAny(); + selectSchoolTypeList().selectSchoolList(); + return selectId().selectName().selectBaseUrl().selectVersion(); + } + + + public PlatformRequest selectId(){ + selectProperty(Platform.ID_PROPERTY); + return this; + } + + /** + * fill the id with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS id) to fetch id property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public PlatformRequest unselectId(){ + unselectProperty(Platform.ID_PROPERTY); + return this; + } + public PlatformRequest selectName(){ + selectProperty(Platform.NAME_PROPERTY); + return this; + } + + /** + * fill the name with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS name) to fetch name property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public PlatformRequest unselectName(){ + unselectProperty(Platform.NAME_PROPERTY); + return this; + } + public PlatformRequest selectBaseUrl(){ + selectProperty(Platform.BASE_URL_PROPERTY); + return this; + } + + /** + * fill the baseUrl with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS baseUrl) to fetch baseUrl property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public PlatformRequest unselectBaseUrl(){ + unselectProperty(Platform.BASE_URL_PROPERTY); + return this; + } + public PlatformRequest selectVersion(){ + selectProperty(Platform.VERSION_PROPERTY); + return this; + } + + /** + * fill the version with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS version) to fetch version property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public PlatformRequest unselectVersion(){ + unselectProperty(Platform.VERSION_PROPERTY); + return this; + } + public PlatformRequest selectSchoolTypeList(){ + return selectSchoolTypeListWith(Q.schoolTypes().selectSelf()); + } + + public PlatformRequest selectSchoolTypeListWith(SchoolTypeRequest schoolTypeList){ + enhanceRelation(Platform.SCHOOL_TYPE_LIST_PROPERTY, schoolTypeList, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_SELECT, "selectSchoolTypeListWith", null, Platform.SCHOOL_TYPE_LIST_PROPERTY)); + return this; + } + public PlatformRequest selectSchoolList(){ + return selectSchoolListWith(Q.schools().selectSelf()); + } + + public PlatformRequest selectSchoolListWith(SchoolRequest schoolList){ + enhanceRelation(Platform.SCHOOL_LIST_PROPERTY, schoolList, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_SELECT, "selectSchoolListWith", null, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest withId(Operator operator, Object... values){ + return appendSearchCriteria(createIdCriteria(operator, values)); + } + + public SearchCriteria createIdCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Platform.ID_PROPERTY, operator, values); + } + + public PlatformRequest withIdIsNot(Long id){ + return withId(Operator.NOT_EQUAL, id); + } + + public PlatformRequest withIdIn(Long... id){ + return withId(Operator.IN, (Object[])id); + } + + public PlatformRequest withIdNotIn(Long... id){ + return withId(Operator.NOT_IN, (Object[])id); + } + public PlatformRequest withIdIs(Long id){ + return withId(Operator.EQUAL, id); + } + + + + public PlatformRequest 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 PlatformRequest withName(Operator operator, Object... values){ + return appendSearchCriteria(createNameCriteria(operator, values)); + } + + public PlatformRequest withNameIsUnknown(){ + return withName(Operator.IS_NULL); + } + + public PlatformRequest withNameIsKnown(){ + return withName(Operator.IS_NOT_NULL); + } + + public SearchCriteria createNameCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Platform.NAME_PROPERTY, operator, values); + } + + public PlatformRequest withNameIsNot(String name){ + return withName(Operator.NOT_EQUAL, name); + } + + public PlatformRequest withNameIn(String... name){ + return withName(Operator.IN, (Object[])name); + } + + public PlatformRequest withNameNotIn(String... name){ + return withName(Operator.NOT_IN, (Object[])name); + } + public PlatformRequest withNameGreaterThan(String name){ + return withName(Operator.GREATER_THAN, name); + } + + public PlatformRequest withNameGreaterThanOrEqualTo(String name){ + return withName(Operator.GREATER_THAN_OR_EQUAL, name); + } + + public PlatformRequest withNameLessThan(String name){ + return withName(Operator.LESS_THAN, name); + } + + public PlatformRequest withNameLessThanOrEqualTo(String name){ + return withName(Operator.LESS_THAN_OR_EQUAL, name); + } + + public PlatformRequest withNameBetween(String startOfName, String endOfName){ + return withName(Operator.BETWEEN, startOfName, endOfName); + } + public PlatformRequest withNameStartingWith(String name){ + return withName(Operator.BEGIN_WITH, name); + } + public PlatformRequest withNameContaining(String name){ + return withName(Operator.CONTAIN, name); + } + + public PlatformRequest withNameNotContaining(String name){ + return withName(Operator.NOT_CONTAIN, name); + } + + public PlatformRequest withNameNotStartingWith(String name){ + return withName(Operator.NOT_BEGIN_WITH, name); + } + + public PlatformRequest withNameEndingWith(String name){ + return withName(Operator.END_WITH, name); + } + + public PlatformRequest withNameNotEndingWith(String name){ + return withName(Operator.NOT_END_WITH, name); + } + + public PlatformRequest withNameIs(String name){ + return withName(Operator.EQUAL, name); + } + + public PlatformRequest withNameSoundingLike(String name){ + return withName(Operator.SOUNDS_LIKE, name); + } + + + + public PlatformRequest filterByBaseUrl(String... baseUrl){ + if (baseUrl == null || baseUrl.length == 0) { + throw new IllegalArgumentException("filterByBaseUrl parameter baseUrl cannot be empty"); + } + return appendSearchCriteria(createBaseUrlCriteria(Operator.EQUAL, (Object[])baseUrl)); + } + + public PlatformRequest withBaseUrl(Operator operator, Object... values){ + return appendSearchCriteria(createBaseUrlCriteria(operator, values)); + } + + public PlatformRequest withBaseUrlIsUnknown(){ + return withBaseUrl(Operator.IS_NULL); + } + + public PlatformRequest withBaseUrlIsKnown(){ + return withBaseUrl(Operator.IS_NOT_NULL); + } + + public SearchCriteria createBaseUrlCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Platform.BASE_URL_PROPERTY, operator, values); + } + + public PlatformRequest withBaseUrlIsNot(String baseUrl){ + return withBaseUrl(Operator.NOT_EQUAL, baseUrl); + } + + public PlatformRequest withBaseUrlIn(String... baseUrl){ + return withBaseUrl(Operator.IN, (Object[])baseUrl); + } + + public PlatformRequest withBaseUrlNotIn(String... baseUrl){ + return withBaseUrl(Operator.NOT_IN, (Object[])baseUrl); + } + public PlatformRequest withBaseUrlGreaterThan(String baseUrl){ + return withBaseUrl(Operator.GREATER_THAN, baseUrl); + } + + public PlatformRequest withBaseUrlGreaterThanOrEqualTo(String baseUrl){ + return withBaseUrl(Operator.GREATER_THAN_OR_EQUAL, baseUrl); + } + + public PlatformRequest withBaseUrlLessThan(String baseUrl){ + return withBaseUrl(Operator.LESS_THAN, baseUrl); + } + + public PlatformRequest withBaseUrlLessThanOrEqualTo(String baseUrl){ + return withBaseUrl(Operator.LESS_THAN_OR_EQUAL, baseUrl); + } + + public PlatformRequest withBaseUrlBetween(String startOfBaseUrl, String endOfBaseUrl){ + return withBaseUrl(Operator.BETWEEN, startOfBaseUrl, endOfBaseUrl); + } + public PlatformRequest withBaseUrlStartingWith(String baseUrl){ + return withBaseUrl(Operator.BEGIN_WITH, baseUrl); + } + public PlatformRequest withBaseUrlContaining(String baseUrl){ + return withBaseUrl(Operator.CONTAIN, baseUrl); + } + + public PlatformRequest withBaseUrlNotContaining(String baseUrl){ + return withBaseUrl(Operator.NOT_CONTAIN, baseUrl); + } + + public PlatformRequest withBaseUrlNotStartingWith(String baseUrl){ + return withBaseUrl(Operator.NOT_BEGIN_WITH, baseUrl); + } + + public PlatformRequest withBaseUrlEndingWith(String baseUrl){ + return withBaseUrl(Operator.END_WITH, baseUrl); + } + + public PlatformRequest withBaseUrlNotEndingWith(String baseUrl){ + return withBaseUrl(Operator.NOT_END_WITH, baseUrl); + } + + public PlatformRequest withBaseUrlIs(String baseUrl){ + return withBaseUrl(Operator.EQUAL, baseUrl); + } + + public PlatformRequest withBaseUrlSoundingLike(String baseUrl){ + return withBaseUrl(Operator.SOUNDS_LIKE, baseUrl); + } + + + + public PlatformRequest 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 PlatformRequest withVersion(Operator operator, Object... values){ + return appendSearchCriteria(createVersionCriteria(operator, values)); + } + + public PlatformRequest withVersionIsUnknown(){ + return withVersion(Operator.IS_NULL); + } + + public PlatformRequest withVersionIsKnown(){ + return withVersion(Operator.IS_NOT_NULL); + } + + public SearchCriteria createVersionCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(Platform.VERSION_PROPERTY, operator, values); + } + + public PlatformRequest withVersionIs(Long version){ + return withVersion(Operator.EQUAL, version); + } + + public PlatformRequest withVersionIsNot(Long version){ + return withVersion(Operator.NOT_EQUAL, version); + } + + public PlatformRequest withVersionIn(Long... version){ + return withVersion(Operator.IN, (Object[])version); + } + + public PlatformRequest withVersionNotIn(Long... version){ + return withVersion(Operator.NOT_IN, (Object[])version); + } + public PlatformRequest withVersionGreaterThan(Long version){ + return withVersion(Operator.GREATER_THAN, version); + } + + public PlatformRequest withVersionGreaterThanOrEqualTo(Long version){ + return withVersion(Operator.GREATER_THAN_OR_EQUAL, version); + } + + public PlatformRequest withVersionLessThan(Long version){ + return withVersion(Operator.LESS_THAN, version); + } + + public PlatformRequest withVersionLessThanOrEqualTo(Long version){ + return withVersion(Operator.LESS_THAN_OR_EQUAL, version); + } + + public PlatformRequest withVersionBetween(Long startOfVersion, Long endOfVersion){ + return withVersion(Operator.BETWEEN, startOfVersion, endOfVersion); + } + + + public PlatformRequest withSchoolTypeListMatching(SchoolTypeRequest schoolTypeRequest){ + return appendSearchCriteria(new SubQuerySearchCriteria(Platform.ID_PROPERTY, schoolTypeRequest, SchoolType.PLATFORM_PROPERTY)); + } + + public PlatformRequest withoutSchoolTypeListMatching(SchoolTypeRequest schoolTypeRequest){ + return appendSearchCriteria(SearchCriteria.not(new SubQuerySearchCriteria(Platform.ID_PROPERTY, schoolTypeRequest, SchoolType.PLATFORM_PROPERTY))); + } + + public PlatformRequest haveSchoolTypes(){ + return withSchoolTypeListMatching(Q.schoolTypes().unlimited()); + } + + public PlatformRequest haveNoSchoolTypes(){ + return withoutSchoolTypeListMatching(Q.schoolTypes().unlimited()); + } + public PlatformRequest withSchoolListMatching(SchoolRequest schoolRequest){ + return appendSearchCriteria(new SubQuerySearchCriteria(Platform.ID_PROPERTY, schoolRequest, School.PLATFORM_PROPERTY)); + } + + public PlatformRequest withoutSchoolListMatching(SchoolRequest schoolRequest){ + return appendSearchCriteria(SearchCriteria.not(new SubQuerySearchCriteria(Platform.ID_PROPERTY, schoolRequest, School.PLATFORM_PROPERTY))); + } + + public PlatformRequest haveSchools(){ + return withSchoolListMatching(Q.schools().unlimited()); + } + + public PlatformRequest haveNoSchools(){ + return withoutSchoolListMatching(Q.schools().unlimited()); + } + + public PlatformRequest count(){ + super.count(); + setPageCountOperation(io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.NAMED_COUNT, "count", null, null)); + return this; + } + public PlatformRequest 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 PlatformRequest countDistinctId(){ + return countDistinctIdAs("id_distinct_count"); + } + + public PlatformRequest countDistinctIdAs(String alias){ + super.countDistinctProperty(alias, Platform.ID_PROPERTY); + return this; + } + public PlatformRequest countDistinctName(){ + return countDistinctNameAs("name_distinct_count"); + } + + public PlatformRequest countDistinctNameAs(String alias){ + super.countDistinctProperty(alias, Platform.NAME_PROPERTY); + return this; + } + public PlatformRequest countDistinctBaseUrl(){ + return countDistinctBaseUrlAs("base_url_distinct_count"); + } + + public PlatformRequest countDistinctBaseUrlAs(String alias){ + super.countDistinctProperty(alias, Platform.BASE_URL_PROPERTY); + return this; + } + public PlatformRequest countDistinctVersion(){ + return countDistinctVersionAs("version_distinct_count"); + } + + public PlatformRequest countDistinctVersionAs(String alias){ + super.countDistinctProperty(alias, Platform.VERSION_PROPERTY); + return this; + } + public PlatformRequest groupBySchoolTypesWithDetails(SchoolTypeRequest subRequest){ + aggregate(Platform.SCHOOL_TYPE_LIST_PROPERTY, subRequest); + return this; + } + public PlatformRequest groupBySchoolsWithDetails(SchoolRequest subRequest){ + aggregate(Platform.SCHOOL_LIST_PROPERTY, subRequest); + return this; + } + + public PlatformRequest groupById(){ + groupBy(Platform.ID_PROPERTY); + return this; + } + + public PlatformRequest groupByIdAs(String retName){ + groupBy(retName, Platform.ID_PROPERTY); + return this; + } + + public PlatformRequest groupByIdWithFunction(String retName, AggrFunction function){ + groupBy(retName, Platform.ID_PROPERTY, function); + return this; + } + + public PlatformRequest groupByName(){ + groupBy(Platform.NAME_PROPERTY); + return this; + } + + public PlatformRequest groupByNameAs(String retName){ + groupBy(retName, Platform.NAME_PROPERTY); + return this; + } + + public PlatformRequest groupByNameWithFunction(String retName, AggrFunction function){ + groupBy(retName, Platform.NAME_PROPERTY, function); + return this; + } + + public PlatformRequest groupByBaseUrl(){ + groupBy(Platform.BASE_URL_PROPERTY); + return this; + } + + public PlatformRequest groupByBaseUrlAs(String retName){ + groupBy(retName, Platform.BASE_URL_PROPERTY); + return this; + } + + public PlatformRequest groupByBaseUrlWithFunction(String retName, AggrFunction function){ + groupBy(retName, Platform.BASE_URL_PROPERTY, function); + return this; + } + + public PlatformRequest groupByVersion(){ + groupBy(Platform.VERSION_PROPERTY); + return this; + } + + public PlatformRequest groupByVersionAs(String retName){ + groupBy(retName, Platform.VERSION_PROPERTY); + return this; + } + + public PlatformRequest groupByVersionWithFunction(String retName, AggrFunction function){ + groupBy(retName, Platform.VERSION_PROPERTY, function); + return this; + } + + + + public PlatformRequest orderByIdAscending(){ + addOrderByAscending(Platform.ID_PROPERTY); + return this; + } + + public PlatformRequest orderByIdDescending(){ + addOrderByDescending(Platform.ID_PROPERTY); + return this; + } + + public PlatformRequest orderByNameAscending(){ + addOrderByAscending(Platform.NAME_PROPERTY); + return this; + } + + public PlatformRequest orderByNameDescending(){ + addOrderByDescending(Platform.NAME_PROPERTY); + return this; + } + public PlatformRequest orderByNameAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Platform.NAME_PROPERTY); + return this; + } + + public PlatformRequest orderByNameDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Platform.NAME_PROPERTY); + return this; + } + public PlatformRequest orderByBaseUrlAscending(){ + addOrderByAscending(Platform.BASE_URL_PROPERTY); + return this; + } + + public PlatformRequest orderByBaseUrlDescending(){ + addOrderByDescending(Platform.BASE_URL_PROPERTY); + return this; + } + public PlatformRequest orderByBaseUrlAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(Platform.BASE_URL_PROPERTY); + return this; + } + + public PlatformRequest orderByBaseUrlDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(Platform.BASE_URL_PROPERTY); + return this; + } + public PlatformRequest orderByVersionAscending(){ + addOrderByAscending(Platform.VERSION_PROPERTY); + return this; + } + + public PlatformRequest orderByVersionDescending(){ + addOrderByDescending(Platform.VERSION_PROPERTY); + return this; + } + + + public PlatformRequest statsFromSchoolTypesAs(String name, SchoolTypeRequest subRequest){ + return statsFromSchoolTypesAs(name, subRequest, false); + } + + public PlatformRequest statsFromSchoolTypesAs(String name, SchoolTypeRequest subRequest, boolean singleResult){ + addRelationAggregate(name, subRequest, SchoolType.PLATFORM_PROPERTY, singleResult, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "statsFromSchoolTypesAs", name, Platform.SCHOOL_TYPE_LIST_PROPERTY)); + return this; + } + + public PlatformRequest statsFromSchoolTypes(SchoolTypeRequest subRequest){ + return statsFromSchoolTypesAs(REFINEMENTS, subRequest); + } + public PlatformRequest statsFromSchoolsAs(String name, SchoolRequest subRequest){ + return statsFromSchoolsAs(name, subRequest, false); + } + + public PlatformRequest statsFromSchoolsAs(String name, SchoolRequest subRequest, boolean singleResult){ + addRelationAggregate(name, subRequest, School.PLATFORM_PROPERTY, singleResult, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "statsFromSchoolsAs", name, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest statsFromSchools(SchoolRequest subRequest){ + return statsFromSchoolsAs(REFINEMENTS, subRequest); + } + public PlatformRequest countSchoolTypes(){ + addRelationCount("Count", Q.schoolTypes().unlimited(), SchoolType.PLATFORM_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countSchoolTypes", null, Platform.SCHOOL_TYPE_LIST_PROPERTY)); + return this; + } + + public PlatformRequest countSchoolTypesAs(String name){ + addRelationCount(name, Q.schoolTypes().unlimited(), SchoolType.PLATFORM_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countSchoolTypesAs", name, Platform.SCHOOL_TYPE_LIST_PROPERTY)); + return this; + } + + public PlatformRequest countSchoolTypesWith(String name, SchoolTypeRequest subRequest){ + addRelationCount(name, subRequest, SchoolType.PLATFORM_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countSchoolTypesWith", name, Platform.SCHOOL_TYPE_LIST_PROPERTY)); + return this; + } + public PlatformRequest countSchools(){ + addRelationCount("Count", Q.schools().unlimited(), School.PLATFORM_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countSchools", null, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest countSchoolsAs(String name){ + addRelationCount(name, Q.schools().unlimited(), School.PLATFORM_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countSchoolsAs", name, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest countSchoolsWith(String name, SchoolRequest subRequest){ + addRelationCount(name, subRequest, School.PLATFORM_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countSchoolsWith", name, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + public PlatformRequest minStudentCapacityOfSchools(){ + addRelationScalarAggregate("minStudentCapacityOfSchools", Q.schools().unlimited(), + School.PLATFORM_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("min".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "minStudentCapacityOfSchools", null, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest minStudentCapacityOfSchoolsAs(String name){ + return minStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public PlatformRequest minStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.PLATFORM_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("min".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "minStudentCapacityOfSchoolsAs", name, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + public PlatformRequest maxStudentCapacityOfSchools(){ + addRelationScalarAggregate("maxStudentCapacityOfSchools", Q.schools().unlimited(), + School.PLATFORM_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("max".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "maxStudentCapacityOfSchools", null, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest maxStudentCapacityOfSchoolsAs(String name){ + return maxStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public PlatformRequest maxStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.PLATFORM_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("max".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "maxStudentCapacityOfSchoolsAs", name, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + public PlatformRequest sumStudentCapacityOfSchools(){ + addRelationScalarAggregate("sumStudentCapacityOfSchools", Q.schools().unlimited(), + School.PLATFORM_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("sum".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sumStudentCapacityOfSchools", null, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest sumStudentCapacityOfSchoolsAs(String name){ + return sumStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public PlatformRequest sumStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.PLATFORM_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("sum".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sumStudentCapacityOfSchoolsAs", name, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + public PlatformRequest avgStudentCapacityOfSchools(){ + addRelationScalarAggregate("avgStudentCapacityOfSchools", Q.schools().unlimited(), + School.PLATFORM_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("avg".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "avgStudentCapacityOfSchools", null, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest avgStudentCapacityOfSchoolsAs(String name){ + return avgStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public PlatformRequest avgStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.PLATFORM_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("avg".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "avgStudentCapacityOfSchoolsAs", name, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + public PlatformRequest standardDeviationStudentCapacityOfSchools(){ + addRelationScalarAggregate("stdDevStudentCapacityOfSchools", Q.schools().unlimited(), + School.PLATFORM_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "standardDeviationStudentCapacityOfSchools", null, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest standardDeviationStudentCapacityOfSchoolsAs(String name){ + return standardDeviationStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public PlatformRequest standardDeviationStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.PLATFORM_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "standardDeviationStudentCapacityOfSchoolsAs", name, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + public PlatformRequest squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(){ + addRelationScalarAggregate("stdDevPopStudentCapacityOfSchools", Q.schools().unlimited(), + School.PLATFORM_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "squareRootOfPopulationStandardDeviationStudentCapacityOfSchools", null, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(String name){ + return squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public PlatformRequest squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.PLATFORM_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs", name, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + public PlatformRequest sampleVarianceStudentCapacityOfSchools(){ + addRelationScalarAggregate("varSampStudentCapacityOfSchools", Q.schools().unlimited(), + School.PLATFORM_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_samp".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sampleVarianceStudentCapacityOfSchools", null, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest sampleVarianceStudentCapacityOfSchoolsAs(String name){ + return sampleVarianceStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public PlatformRequest sampleVarianceStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.PLATFORM_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_samp".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sampleVarianceStudentCapacityOfSchoolsAs", name, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + public PlatformRequest samplePopulationVarianceStudentCapacityOfSchools(){ + addRelationScalarAggregate("varPopStudentCapacityOfSchools", Q.schools().unlimited(), + School.PLATFORM_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "samplePopulationVarianceStudentCapacityOfSchools", null, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + public PlatformRequest samplePopulationVarianceStudentCapacityOfSchoolsAs(String name){ + return samplePopulationVarianceStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public PlatformRequest samplePopulationVarianceStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.PLATFORM_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "samplePopulationVarianceStudentCapacityOfSchoolsAs", name, Platform.SCHOOL_LIST_PROPERTY)); + return this; + } + + + + /** + * get topN records + * @param topN records number + */ + public PlatformRequest top(int topN) { + super.top(topN); + return this; + } + + /** Cross-runtime bounded-query alias. */ + public PlatformRequest limit(int limit) { + return top(limit); + } + + /** + * get records from offset(inclusive) to offset+size(exclusive) + * @param offset record offset + * @param size records number + */ + public PlatformRequest offset(int offset, int size) { + super.offset(offset, size); + return this; + } + + /** + * retrieve all records + */ + public PlatformRequest unlimited() { + super.unlimited(); + return this; + } + + /** + * get records of one page + * @param pageNumber page number(1-based) + * @param pageSize page size + */ + public PlatformRequest 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 PlatformRequest page(int pageNumber) { + return page(pageNumber, 10); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/sampledata/SampleDataService.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/sampledata/SampleDataService.java new file mode 100644 index 000000000..e69de29bb diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/School.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/School.java new file mode 100644 index 000000000..9d4e5bdcc --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/School.java @@ -0,0 +1,184 @@ + +package com.example.inheritancematchingservice.school; + +import com.example.inheritancematchingservice.Constants; +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.schooltype.SchoolType; +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.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 School extends BaseEntity implements RemoteInput { + public static String INTERNAL_TYPE = "School"; + + // Framework metadata: complete fixed layout, independent of SQL/projection order. + public static final String __TEAQL_FIELD_LAYOUT_REVISION = "23ce18d8c80d8d15fa2363ed814bde7c8f04861a2547ac0a722514c1626da577"; + public static final java.util.Map __TEAQL_FIXED_FIELD_INDEXES = + java.util.Map.ofEntries(java.util.Map.entry("id", 0), java.util.Map.entry("platform", 1), java.util.Map.entry("school_type", 2), java.util.Map.entry("name", 3), java.util.Map.entry("student_capacity", 4), java.util.Map.entry("version", 5)); + 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("platform", java.util.List.of("platform", "platform")), java.util.Map.entry("school_type", java.util.List.of("schoolType", "school_type")), java.util.Map.entry("name", java.util.List.of("name", "name")), java.util.Map.entry("student_capacity", java.util.List.of("studentCapacity", "student_capacity")), 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( + School.class, __TEAQL_FIELD_LAYOUT_REVISION, + __TEAQL_FIXED_FIELD_INDEXES, __TEAQL_FIXED_FIELD_MAPPINGS, __TEAQL_FIXED_RELATION_NAMES, + JsonFieldNamingProfile.fromModelValue("camelCase"))); + + + public static final String PLATFORM_PROPERTY = "platform"; + public static final String SCHOOL_TYPE_PROPERTY = "school_type"; + public static final String NAME_PROPERTY = "name"; + public static final String STUDENT_CAPACITY_PROPERTY = "student_capacity"; + private Platform platform; + + private SchoolType schoolType; + + private String name; + + private Integer studentCapacity; + + + public Platform getPlatform(){ + return this.platform; + } + + public SchoolType getSchoolType(){ + return this.schoolType; + } + + public String getName(){ + return this.name; + } + + public Integer getStudentCapacity(){ + return this.studentCapacity; + } + + public School updatePlatform(Platform platform){ + if(isPropertyLoaded(PLATFORM_PROPERTY) && Objects.equals(this.platform, platform)){ + return this; + } + handleUpdate(PLATFORM_PROPERTY, getPlatform(), platform); + this.platform = platform; + return this; + } + + protected School updateSchoolType(SchoolType schoolType){ + if(isPropertyLoaded(SCHOOL_TYPE_PROPERTY) && Objects.equals(this.schoolType, schoolType)){ + return this; + } + handleUpdate(SCHOOL_TYPE_PROPERTY, getSchoolType(), schoolType); + this.schoolType = schoolType; + return this; + } + + public School 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 School updateStudentCapacity(Integer studentCapacity){ + if(isPropertyLoaded(STUDENT_CAPACITY_PROPERTY) && Objects.equals(this.studentCapacity, studentCapacity)){ + return this; + } + handleUpdate(STUDENT_CAPACITY_PROPERTY, getStudentCapacity(), studentCapacity); + this.studentCapacity = studentCapacity; + return this; + } + + public boolean isSchoolTypePrimary(){ + return Objects.equals(getSchoolType(), Constants.SCHOOL_TYPE_PRIMARY); + } + + public School updateSchoolTypeToPrimary(){ + return updateSchoolType(Constants.SCHOOL_TYPE_PRIMARY); + } + public boolean isSchoolTypeSecondary(){ + return Objects.equals(getSchoolType(), Constants.SCHOOL_TYPE_SECONDARY); + } + + public School updateSchoolTypeToSecondary(){ + return updateSchoolType(Constants.SCHOOL_TYPE_SECONDARY); + } + + public static School refer(Long id){ + School refer = new School(); + refer.__internalSet("id", id); + refer.set$status(EntityStatus.REFER); + return refer; + } + @Override + public String typeName(){ + return INTERNAL_TYPE; + } + + public School 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 "platform": this.platform = (Platform) value; break; + + case "school_type": this.schoolType = (SchoolType) value; break; + + case "name": this.name = (value == null ? null : ((String)value).trim()); break; + + case "student_capacity": this.studentCapacity = (Integer) value; break; + + default: super.__internalSet(property, value); + } + } + + @Override + @FrameworkInternal + public Object __internalGet(String property) { + switch (property) { + case "platform": return this.platform; + case "school_type": return this.schoolType; + case "name": return this.name; + case "student_capacity": return this.studentCapacity; + default: + // Presentation uses the installed Java member mapping; SQL and + // hydration retain canonical names. These aliases only read. + switch (property) { + case "platform": return this.platform; + case "schoolType": return this.schoolType; + case "name": return this.name; + case "studentCapacity": return this.studentCapacity; + default: return super.__internalGet(property); + } + } + } + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolChecker.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolChecker.java new file mode 100644 index 000000000..a78eb9f31 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolChecker.java @@ -0,0 +1,82 @@ + +package com.example.inheritancematchingservice.school; + +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.platform.PlatformChecker; +import com.example.inheritancematchingservice.schooltype.SchoolType; +import com.example.inheritancematchingservice.schooltype.SchoolTypeChecker; +import io.teaql.core.UserContext; +import io.teaql.core.checker.Checker; +import io.teaql.core.checker.ObjectLocation; + +public class SchoolChecker implements Checker{ + + public String type(){ + return School.INTERNAL_TYPE; + } + + public void checkAndFix(UserContext _context, School school, ObjectLocation _parentLocation){ + if(needCheck(_context, school)){ + markAsChecked(_context, school); + doCheck(_context, school, _parentLocation); + } + } + + public void doCheck(UserContext _context, School school, ObjectLocation _parentLocation){ + if((school == null)){ + return; + } + boolean _contextFixEligible = needContextFix(_context, school); + if(school.needPersist()){ + } + if(school.newItem()){ + }else if(school.updateItem()){ + if(!school.isPropertyLoaded("platform")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "platform"), "Mutation requires a fully loaded entity"); + } + if(!school.isPropertyLoaded("school_type")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "school_type"), "Mutation requires a fully loaded entity"); + } + if(!school.isPropertyLoaded("name")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "name"), "Mutation requires a fully loaded entity"); + } + if(!school.isPropertyLoaded("student_capacity")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "student_capacity"), "Mutation requires a fully loaded entity"); + } + + } + checkPlatform(_context, school.getProperty(School.PLATFORM_PROPERTY), newLocation(_parentLocation, "platform")); + checkSchoolType(_context, school.getProperty(School.SCHOOL_TYPE_PROPERTY), newLocation(_parentLocation, "school_type")); + checkName(_context, school.getProperty(School.NAME_PROPERTY), newLocation(_parentLocation, "name")); + checkStudentCapacity(_context, school.getProperty(School.STUDENT_CAPACITY_PROPERTY), newLocation(_parentLocation, "student_capacity")); + } + + public void checkPlatform(UserContext _context, Platform platform, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, platform); + if((platform == null)){ + return; + } + new PlatformChecker().checkAndFix(_context, platform, _parentLocation); + } + public void checkSchoolType(UserContext _context, SchoolType schoolType, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, schoolType); + if((schoolType == null)){ + return; + } + new SchoolTypeChecker().checkAndFix(_context, schoolType, _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 checkStudentCapacity(UserContext _context, Integer studentCapacity, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, studentCapacity); + if((studentCapacity == null)){ + return; + } + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolExpression.java new file mode 100644 index 000000000..a61cc398d --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolExpression.java @@ -0,0 +1,73 @@ + +package com.example.inheritancematchingservice.school; + +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.platform.PlatformExpression; +import com.example.inheritancematchingservice.schooltype.SchoolType; +import com.example.inheritancematchingservice.schooltype.SchoolTypeExpression; +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 SchoolExpression extends ExpressionAdaptor implements BaseEntityExpression { + public SchoolExpression(Expression expression){ + super(expression); + } + + public SchoolExpression(Expression expression, Function function){ + super(expression, function); + } + + public SchoolExpression updateId(Long id){ + return new SchoolExpression(this, $it -> {((School)$it).__internalSet("id", id); return this;}); + } + + public SchoolExpression save(UserContext userContext){ + return new SchoolExpression(this, $it -> ((School)$it).auditAs("Saved by Expression").save(userContext)); + } + + public SchoolExpression save(String intent, UserContext userContext){ + return new SchoolExpression(this, $it -> ((School)$it).auditAs(intent).save(userContext)); + } + + public boolean isNull() { + return resolve() == null; + } + + + public PlatformExpression getPlatform(){ + return new PlatformExpression(loaded("platform", "getPlatform", School::getPlatform)); + } + + public SchoolExpression updatePlatform(Platform platform){ + return new SchoolExpression(this, $it -> ((School)$it).updatePlatform(platform)); + } + + public SchoolTypeExpression getSchoolType(){ + return new SchoolTypeExpression(loaded("school_type", "getSchoolType", School::getSchoolType)); + } + + public SchoolExpression updateSchoolTypeToPrimary(){ + return new SchoolExpression(this, $it -> ((School)$it).updateSchoolTypeToPrimary()); + } + public SchoolExpression updateSchoolTypeToSecondary(){ + return new SchoolExpression(this, $it -> ((School)$it).updateSchoolTypeToSecondary()); + } + + public Expression getName(){ + return loaded("name", "getName", School::getName); + } + public SchoolExpression updateName(String name){ + return new SchoolExpression(this, $it -> ((School)$it).updateName(name)); + } + + public Expression getStudentCapacity(){ + return loaded("student_capacity", "getStudentCapacity", School::getStudentCapacity); + } + public SchoolExpression updateStudentCapacity(Integer studentCapacity){ + return new SchoolExpression(this, $it -> ((School)$it).updateStudentCapacity(studentCapacity)); + } + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolListExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolListExpression.java new file mode 100644 index 000000000..0756f9a1c --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolListExpression.java @@ -0,0 +1,25 @@ + +package com.example.inheritancematchingservice.school; + +import io.teaql.core.SmartList; +import io.teaql.core.value.Expression; +import io.teaql.core.value.SmartListExpression; +import java.util.function.Function; + +public class SchoolListExpression extends SmartListExpression { + public SchoolListExpression(Expression> expression){ + super(expression); + } + + public SchoolListExpression(Expression expression, Function> function){ + super(expression, function); + } + + public SchoolExpression first() { + return new SchoolExpression(super.first()); + } + + public SchoolExpression get(int index) { + return new SchoolExpression(super.get(index)); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolRequest.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolRequest.java new file mode 100644 index 000000000..689122a2a --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/school/SchoolRequest.java @@ -0,0 +1,1046 @@ + +package com.example.inheritancematchingservice.school; + +import cn.hutool.core.util.ObjectUtil; +import com.example.inheritancematchingservice.Q; +import com.example.inheritancematchingservice.academy.Academy; +import com.example.inheritancematchingservice.college.College; +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.platform.PlatformRequest; +import com.example.inheritancematchingservice.schooltype.SchoolType; +import com.example.inheritancematchingservice.schooltype.SchoolTypeRequest; +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.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class SchoolRequest extends BaseRequest { + + /** + * @deprecated AI agents and business code must use the generated Q facade + * instead of constructing request builders directly. + */ + @Deprecated + @SuppressWarnings("unchecked") + public SchoolRequest(Class returnType){ + this(returnType, () -> (T) new School()); + } + + protected SchoolRequest(Class returnType, java.util.function.Supplier factory){ + super(returnType, factory); + selectId(); + selectVersion(); + } + + public SchoolRequest comment(String comment){ + super.internalComment(comment); + return this; + } + + /** Independent query graph; ordinary roll-up handles remain live. */ + @Override + @SuppressWarnings("unchecked") + public SchoolRequest copy(){ + return (SchoolRequest) super.copy(); + } + + @Override + @SuppressWarnings("unchecked") + protected io.teaql.core.BaseRequest internalCopyTarget(){ + return new SchoolRequest<>((Class) returnType(), this::internalNewEntity); + } + + // purpose() 继承自 BaseRequest,返回 ExecutableRequest(终结方法) + + public SchoolRequest returnType(Class returnType){ + super.setReturnType(returnType); + return this; + } + + public SchoolRequest enableAggregationCache(long cacheExpiredMillis){ + super.enableAggregationCache(); + super.aggregateCacheTime(cacheExpiredMillis); + return this; + } + + public SchoolRequest enableAggregationCache(){ + return enableAggregationCache(0l); + } + + + public SchoolRequest 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 SchoolRequest optimizeForContinuousPageFetch(){ + super.optimizeForContinuousPageFetch(); + return this; + } + + public SchoolRequest optimizeForContinuousPageFetch(String namespace, int ttlSeconds){ + super.optimizeForContinuousPageFetch(namespace, ttlSeconds); + return this; + } + + public SchoolRequest optimizePaginationWithIdSet(){ + super.optimizePaginationWithIdSet(); + return this; + } + + public SchoolRequest optimizePaginationWithIdSet( + String namespace, int ttlSeconds, int maxIds){ + super.optimizePaginationWithIdSet(namespace, ttlSeconds, maxIds); + return this; + } + + public SchoolRequest topNProbeParentThreshold(int threshold){ + super.topNProbeParentThreshold(threshold); + return this; + } + + public SchoolRequest appendSearchCriteria(SearchCriteria searchCriteria){ + return (SchoolRequest)super.appendSearchCriteria(searchCriteria); + } + + public SchoolRequest filter(String property1, Operator operator, String property2){ + return appendSearchCriteria(new TwoOperatorCriteria(operator, new PropertyReference(property1), new PropertyReference(property2))); + } + + + public SchoolRequest matchingAnyOf(SchoolRequest... schools){ + if(ObjectUtil.isEmpty(schools)){ + return this; + } + List l = new ArrayList(); + for(SchoolRequest school:schools){ + l.add(new SubQuerySearchCriteria(School.ID_PROPERTY, school, School.ID_PROPERTY)); + } + return appendSearchCriteria(SearchCriteria.or(l.toArray(new SearchCriteria[l.size()]))); + } + + public SchoolRequest enhanceChild(SchoolRequest school){ + super.enhanceSelf(school); + return this; + } + public SchoolRequest matchingIdsOf(SchoolRequest request){ + Objects.requireNonNull(request, "matching request"); + return appendSearchCriteria(new SubQuerySearchCriteria( + School.ID_PROPERTY, request, School.ID_PROPERTY)); + } + + public SchoolRequest enhanceChildrenIfNeeded(){ + this.enhanceChild( +Q.academiesWithChildren() +).enhanceChild( +new com.example.inheritancematchingservice.college.CollegeRequest(com.example.inheritancematchingservice.college.College.class).unlimited().selectSelfWithoutParent() +); + return this; + } + + public SchoolRequest withDeletedRows(){ + super.withDeletedRows(); + return this; + } + + public SchoolRequest deletedRowsOnly(){ + super.deletedRowsOnly(); + return this; + } + + public SchoolRequest selectSelf(){ + super.selectSelf(); + return selectId().selectPlatformIdOnly().selectSchoolTypeIdOnly().selectName().selectStudentCapacity().selectVersion(); + } + + public SchoolRequest selectSelfFields(){ + return selectSelf(); + } + + public SchoolRequest selectSelfWithoutParent(){ + selectId(); + selectVersion(); + selectProperty(School.ID_PROPERTY); + selectProperty(School.PLATFORM_PROPERTY); + selectProperty(School.SCHOOL_TYPE_PROPERTY); + selectProperty(School.NAME_PROPERTY); + selectProperty(School.STUDENT_CAPACITY_PROPERTY); + selectProperty(School.VERSION_PROPERTY); + return this; + } + + public SchoolRequest selectAll(){ + super.selectAll(); + return selectId().selectPlatform().selectSchoolType().selectName().selectStudentCapacity().selectVersion(); + } + + public SchoolRequest selectChildren(){ + super.selectAny(); + return selectId().selectPlatform().selectSchoolType().selectName().selectStudentCapacity().selectVersion(); + } + + + public SchoolRequest selectId(){ + selectProperty(School.ID_PROPERTY); + return this; + } + + /** + * fill the id with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS id) to fetch id property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public SchoolRequest unselectId(){ + unselectProperty(School.ID_PROPERTY); + return this; + } + public SchoolRequest selectPlatformIdOnly(){ + selectProperty(School.PLATFORM_PROPERTY); + return this; + } + + public SchoolRequest selectPlatform(){ + return selectPlatformWith(Q.platforms().unlimited().selectSelf()); + } + + public SchoolRequest selectPlatformWith(PlatformRequest platform){ + selectProperty(School.PLATFORM_PROPERTY); + enhanceRelation(School.PLATFORM_PROPERTY, platform, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_SELECT, "selectPlatformWith", null, School.PLATFORM_PROPERTY)); + return this; + } + + public SchoolRequest unselectPlatform(){ + unselectProperty(School.PLATFORM_PROPERTY); + return this; + } + public SchoolRequest selectSchoolTypeIdOnly(){ + selectProperty(School.SCHOOL_TYPE_PROPERTY); + return this; + } + + public SchoolRequest selectSchoolType(){ + return selectSchoolTypeWith(Q.schoolTypes().unlimited().selectSelf()); + } + + public SchoolRequest selectSchoolTypeWith(SchoolTypeRequest schoolType){ + selectProperty(School.SCHOOL_TYPE_PROPERTY); + enhanceRelation(School.SCHOOL_TYPE_PROPERTY, schoolType, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_SELECT, "selectSchoolTypeWith", null, School.SCHOOL_TYPE_PROPERTY)); + return this; + } + + public SchoolRequest unselectSchoolType(){ + unselectProperty(School.SCHOOL_TYPE_PROPERTY); + return this; + } + public SchoolRequest selectName(){ + selectProperty(School.NAME_PROPERTY); + return this; + } + + /** + * fill the name with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS name) to fetch name property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public SchoolRequest unselectName(){ + unselectProperty(School.NAME_PROPERTY); + return this; + } + public SchoolRequest selectStudentCapacity(){ + selectProperty(School.STUDENT_CAPACITY_PROPERTY); + return this; + } + + /** + * fill the studentCapacity with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS studentCapacity) to fetch studentCapacity property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + /** + * fill the studentCapacity with customized aggrFunction, TEAQL uses ({aggrFunction}(studentCapacity) AS studentCapacity to fetch studentCapacity property. + * @param aggrFunction aggrFunction + */ + public SchoolRequest selectStudentCapacity(AggrFunction aggrFunction){ + selectProperty(School.STUDENT_CAPACITY_PROPERTY, aggrFunction); + return this; + } + + + public SchoolRequest unselectStudentCapacity(){ + unselectProperty(School.STUDENT_CAPACITY_PROPERTY); + return this; + } + public SchoolRequest selectVersion(){ + selectProperty(School.VERSION_PROPERTY); + return this; + } + + /** + * fill the version with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS version) to fetch version property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public SchoolRequest unselectVersion(){ + unselectProperty(School.VERSION_PROPERTY); + return this; + } + + public SchoolRequest isAcademy(){ + return matchTypes(Academy.INTERNAL_TYPE); + } + public SchoolRequest isCollege(){ + return matchTypes(College.INTERNAL_TYPE); + } + + public SchoolRequest matchTypes(String... types){ + super.matchType(types); + return this; + } + + public SchoolRequest withTypeGroup(){ + super.withTypeGroup(); + return this; + } + + public SchoolRequest withId(Operator operator, Object... values){ + return appendSearchCriteria(createIdCriteria(operator, values)); + } + + public SearchCriteria createIdCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(School.ID_PROPERTY, operator, values); + } + + public SchoolRequest withIdIsNot(Long id){ + return withId(Operator.NOT_EQUAL, id); + } + + public SchoolRequest withIdIn(Long... id){ + return withId(Operator.IN, (Object[])id); + } + + public SchoolRequest withIdNotIn(Long... id){ + return withId(Operator.NOT_IN, (Object[])id); + } + public SchoolRequest withIdIs(Long id){ + return withId(Operator.EQUAL, id); + } + + + + public SchoolRequest filterByPlatform(Platform... platform){ + if (platform == null || platform.length == 0) { + throw new IllegalArgumentException("filterByPlatform parameter platform cannot be empty"); + } + return appendSearchCriteria(createPlatformCriteria(Operator.EQUAL, (Object[])platform)); + } + + public SchoolRequest withPlatform(Operator operator, Object... values){ + return appendSearchCriteria(createPlatformCriteria(operator, values)); + } + + public SchoolRequest withPlatformIsUnknown(){ + return withPlatform(Operator.IS_NULL); + } + + public SchoolRequest withPlatformIsKnown(){ + return withPlatform(Operator.IS_NOT_NULL); + } + + public SearchCriteria createPlatformCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(School.PLATFORM_PROPERTY, operator, values); + } + + public SchoolRequest filterByPlatform(Long platform){ + if(platform == null){ + return this; + } + return withPlatform(Operator.EQUAL, platform); + } + public SchoolRequest withPlatformMatching(PlatformRequest platform){ + return appendSearchCriteria(new SubQuerySearchCriteria(School.PLATFORM_PROPERTY, platform, Platform.ID_PROPERTY)); + } + + public SchoolRequest withoutPlatformMatching(PlatformRequest platform){ + return appendSearchCriteria(SearchCriteria.not( + new SubQuerySearchCriteria(School.PLATFORM_PROPERTY, platform, Platform.ID_PROPERTY))); + } + + public SchoolRequest filterBySchoolType(SchoolType... schoolType){ + if (schoolType == null || schoolType.length == 0) { + throw new IllegalArgumentException("filterBySchoolType parameter schoolType cannot be empty"); + } + return appendSearchCriteria(createSchoolTypeCriteria(Operator.EQUAL, (Object[])schoolType)); + } + + public SchoolRequest withSchoolType(Operator operator, Object... values){ + return appendSearchCriteria(createSchoolTypeCriteria(operator, values)); + } + + public SchoolRequest withSchoolTypeIsUnknown(){ + return withSchoolType(Operator.IS_NULL); + } + + public SchoolRequest withSchoolTypeIsKnown(){ + return withSchoolType(Operator.IS_NOT_NULL); + } + + public SearchCriteria createSchoolTypeCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(School.SCHOOL_TYPE_PROPERTY, operator, values); + } + + public SchoolRequest filterBySchoolType(Long schoolType){ + if(schoolType == null){ + return this; + } + return withSchoolType(Operator.EQUAL, schoolType); + } + public SchoolRequest withSchoolTypeMatching(SchoolTypeRequest schoolType){ + return appendSearchCriteria(new SubQuerySearchCriteria(School.SCHOOL_TYPE_PROPERTY, schoolType, SchoolType.ID_PROPERTY)); + } + + public SchoolRequest withoutSchoolTypeMatching(SchoolTypeRequest schoolType){ + return appendSearchCriteria(SearchCriteria.not( + new SubQuerySearchCriteria(School.SCHOOL_TYPE_PROPERTY, schoolType, SchoolType.ID_PROPERTY))); + } + + public SchoolRequest 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 SchoolRequest withName(Operator operator, Object... values){ + return appendSearchCriteria(createNameCriteria(operator, values)); + } + + public SchoolRequest withNameIsUnknown(){ + return withName(Operator.IS_NULL); + } + + public SchoolRequest withNameIsKnown(){ + return withName(Operator.IS_NOT_NULL); + } + + public SearchCriteria createNameCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(School.NAME_PROPERTY, operator, values); + } + + public SchoolRequest withNameIsNot(String name){ + return withName(Operator.NOT_EQUAL, name); + } + + public SchoolRequest withNameIn(String... name){ + return withName(Operator.IN, (Object[])name); + } + + public SchoolRequest withNameNotIn(String... name){ + return withName(Operator.NOT_IN, (Object[])name); + } + public SchoolRequest withNameGreaterThan(String name){ + return withName(Operator.GREATER_THAN, name); + } + + public SchoolRequest withNameGreaterThanOrEqualTo(String name){ + return withName(Operator.GREATER_THAN_OR_EQUAL, name); + } + + public SchoolRequest withNameLessThan(String name){ + return withName(Operator.LESS_THAN, name); + } + + public SchoolRequest withNameLessThanOrEqualTo(String name){ + return withName(Operator.LESS_THAN_OR_EQUAL, name); + } + + public SchoolRequest withNameBetween(String startOfName, String endOfName){ + return withName(Operator.BETWEEN, startOfName, endOfName); + } + public SchoolRequest withNameStartingWith(String name){ + return withName(Operator.BEGIN_WITH, name); + } + public SchoolRequest withNameContaining(String name){ + return withName(Operator.CONTAIN, name); + } + + public SchoolRequest withNameNotContaining(String name){ + return withName(Operator.NOT_CONTAIN, name); + } + + public SchoolRequest withNameNotStartingWith(String name){ + return withName(Operator.NOT_BEGIN_WITH, name); + } + + public SchoolRequest withNameEndingWith(String name){ + return withName(Operator.END_WITH, name); + } + + public SchoolRequest withNameNotEndingWith(String name){ + return withName(Operator.NOT_END_WITH, name); + } + + public SchoolRequest withNameIs(String name){ + return withName(Operator.EQUAL, name); + } + + public SchoolRequest withNameSoundingLike(String name){ + return withName(Operator.SOUNDS_LIKE, name); + } + + + + public SchoolRequest filterByStudentCapacity(Integer... studentCapacity){ + if (studentCapacity == null || studentCapacity.length == 0) { + throw new IllegalArgumentException("filterByStudentCapacity parameter studentCapacity cannot be empty"); + } + return appendSearchCriteria(createStudentCapacityCriteria(Operator.EQUAL, (Object[])studentCapacity)); + } + + public SchoolRequest withStudentCapacity(Operator operator, Object... values){ + return appendSearchCriteria(createStudentCapacityCriteria(operator, values)); + } + + public SchoolRequest withStudentCapacityIsUnknown(){ + return withStudentCapacity(Operator.IS_NULL); + } + + public SchoolRequest withStudentCapacityIsKnown(){ + return withStudentCapacity(Operator.IS_NOT_NULL); + } + + public SearchCriteria createStudentCapacityCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(School.STUDENT_CAPACITY_PROPERTY, operator, values); + } + + public SchoolRequest withStudentCapacityIs(Integer studentCapacity){ + return withStudentCapacity(Operator.EQUAL, studentCapacity); + } + + public SchoolRequest withStudentCapacityIsNot(Integer studentCapacity){ + return withStudentCapacity(Operator.NOT_EQUAL, studentCapacity); + } + + public SchoolRequest withStudentCapacityIn(Integer... studentCapacity){ + return withStudentCapacity(Operator.IN, (Object[])studentCapacity); + } + + public SchoolRequest withStudentCapacityNotIn(Integer... studentCapacity){ + return withStudentCapacity(Operator.NOT_IN, (Object[])studentCapacity); + } + public SchoolRequest withStudentCapacityGreaterThan(Integer studentCapacity){ + return withStudentCapacity(Operator.GREATER_THAN, studentCapacity); + } + + public SchoolRequest withStudentCapacityGreaterThanOrEqualTo(Integer studentCapacity){ + return withStudentCapacity(Operator.GREATER_THAN_OR_EQUAL, studentCapacity); + } + + public SchoolRequest withStudentCapacityLessThan(Integer studentCapacity){ + return withStudentCapacity(Operator.LESS_THAN, studentCapacity); + } + + public SchoolRequest withStudentCapacityLessThanOrEqualTo(Integer studentCapacity){ + return withStudentCapacity(Operator.LESS_THAN_OR_EQUAL, studentCapacity); + } + + public SchoolRequest withStudentCapacityBetween(Integer startOfStudentCapacity, Integer endOfStudentCapacity){ + return withStudentCapacity(Operator.BETWEEN, startOfStudentCapacity, endOfStudentCapacity); + } + + + + public SchoolRequest 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 SchoolRequest withVersion(Operator operator, Object... values){ + return appendSearchCriteria(createVersionCriteria(operator, values)); + } + + public SchoolRequest withVersionIsUnknown(){ + return withVersion(Operator.IS_NULL); + } + + public SchoolRequest withVersionIsKnown(){ + return withVersion(Operator.IS_NOT_NULL); + } + + public SearchCriteria createVersionCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(School.VERSION_PROPERTY, operator, values); + } + + public SchoolRequest withVersionIs(Long version){ + return withVersion(Operator.EQUAL, version); + } + + public SchoolRequest withVersionIsNot(Long version){ + return withVersion(Operator.NOT_EQUAL, version); + } + + public SchoolRequest withVersionIn(Long... version){ + return withVersion(Operator.IN, (Object[])version); + } + + public SchoolRequest withVersionNotIn(Long... version){ + return withVersion(Operator.NOT_IN, (Object[])version); + } + public SchoolRequest withVersionGreaterThan(Long version){ + return withVersion(Operator.GREATER_THAN, version); + } + + public SchoolRequest withVersionGreaterThanOrEqualTo(Long version){ + return withVersion(Operator.GREATER_THAN_OR_EQUAL, version); + } + + public SchoolRequest withVersionLessThan(Long version){ + return withVersion(Operator.LESS_THAN, version); + } + + public SchoolRequest withVersionLessThanOrEqualTo(Long version){ + return withVersion(Operator.LESS_THAN_OR_EQUAL, version); + } + + public SchoolRequest withVersionBetween(Long startOfVersion, Long endOfVersion){ + return withVersion(Operator.BETWEEN, startOfVersion, endOfVersion); + } + + + + public SchoolRequest count(){ + super.count(); + setPageCountOperation(io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.NAMED_COUNT, "count", null, null)); + return this; + } + public SchoolRequest 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 SchoolRequest minStudentCapacity(){ + return minStudentCapacityAs(prefix("minOf",School.STUDENT_CAPACITY_PROPERTY)); + } + + public SchoolRequest minStudentCapacityAs(String retName){ + super.min(retName, School.STUDENT_CAPACITY_PROPERTY); + return this; + } + public SchoolRequest maxStudentCapacity(){ + return maxStudentCapacityAs(prefix("maxOf",School.STUDENT_CAPACITY_PROPERTY)); + } + + public SchoolRequest maxStudentCapacityAs(String retName){ + super.max(retName, School.STUDENT_CAPACITY_PROPERTY); + return this; + } + public SchoolRequest sumStudentCapacity(){ + return sumStudentCapacityAs(prefix("sumOf",School.STUDENT_CAPACITY_PROPERTY)); + } + + public SchoolRequest sumStudentCapacityAs(String retName){ + super.sum(retName, School.STUDENT_CAPACITY_PROPERTY); + return this; + } + public SchoolRequest avgStudentCapacity(){ + return avgStudentCapacityAs(prefix("avgOf",School.STUDENT_CAPACITY_PROPERTY)); + } + + public SchoolRequest avgStudentCapacityAs(String retName){ + super.avg(retName, School.STUDENT_CAPACITY_PROPERTY); + return this; + } + public SchoolRequest standardDeviationStudentCapacity(){ + return standardDeviationStudentCapacityAs(prefix("standardDeviationOf",School.STUDENT_CAPACITY_PROPERTY)); + } + + public SchoolRequest standardDeviationStudentCapacityAs(String retName){ + super.standardDeviation(retName, School.STUDENT_CAPACITY_PROPERTY); + return this; + } + public SchoolRequest squareRootOfPopulationStandardDeviationStudentCapacity(){ + return squareRootOfPopulationStandardDeviationStudentCapacityAs(prefix("squareRootOfPopulationStandardDeviationOf",School.STUDENT_CAPACITY_PROPERTY)); + } + + public SchoolRequest squareRootOfPopulationStandardDeviationStudentCapacityAs(String retName){ + super.squareRootOfPopulationStandardDeviation(retName, School.STUDENT_CAPACITY_PROPERTY); + return this; + } + public SchoolRequest sampleVarianceStudentCapacity(){ + return sampleVarianceStudentCapacityAs(prefix("sampleVarianceOf",School.STUDENT_CAPACITY_PROPERTY)); + } + + public SchoolRequest sampleVarianceStudentCapacityAs(String retName){ + super.sampleVariance(retName, School.STUDENT_CAPACITY_PROPERTY); + return this; + } + public SchoolRequest samplePopulationVarianceStudentCapacity(){ + return samplePopulationVarianceStudentCapacityAs(prefix("samplePopulationVarianceOf",School.STUDENT_CAPACITY_PROPERTY)); + } + + public SchoolRequest samplePopulationVarianceStudentCapacityAs(String retName){ + super.samplePopulationVariance(retName, School.STUDENT_CAPACITY_PROPERTY); + return this; + } + public SchoolRequest groupByPlatformWithDetails(){ + return groupByPlatformWithDetails(Q.platforms().unlimited()); + } + + public SchoolRequest groupByPlatformWithDetails(PlatformRequest subRequest){ + aggregate(School.PLATFORM_PROPERTY, subRequest); + return this; + } + + public SchoolRequest groupBySchoolTypeWithDetails(){ + return groupBySchoolTypeWithDetails(Q.schoolTypes().unlimited()); + } + + public SchoolRequest groupBySchoolTypeWithDetails(SchoolTypeRequest subRequest){ + aggregate(School.SCHOOL_TYPE_PROPERTY, subRequest); + return this; + } + + + + + public SchoolRequest countDistinctId(){ + return countDistinctIdAs("id_distinct_count"); + } + + public SchoolRequest countDistinctIdAs(String alias){ + super.countDistinctProperty(alias, School.ID_PROPERTY); + return this; + } + public SchoolRequest countDistinctPlatform(){ + return countDistinctPlatformAs("platform_distinct_count"); + } + + public SchoolRequest countDistinctPlatformAs(String alias){ + super.countDistinctProperty(alias, School.PLATFORM_PROPERTY); + return this; + } + public SchoolRequest countDistinctSchoolType(){ + return countDistinctSchoolTypeAs("school_type_distinct_count"); + } + + public SchoolRequest countDistinctSchoolTypeAs(String alias){ + super.countDistinctProperty(alias, School.SCHOOL_TYPE_PROPERTY); + return this; + } + public SchoolRequest countDistinctName(){ + return countDistinctNameAs("name_distinct_count"); + } + + public SchoolRequest countDistinctNameAs(String alias){ + super.countDistinctProperty(alias, School.NAME_PROPERTY); + return this; + } + public SchoolRequest countDistinctStudentCapacity(){ + return countDistinctStudentCapacityAs("student_capacity_distinct_count"); + } + + public SchoolRequest countDistinctStudentCapacityAs(String alias){ + super.countDistinctProperty(alias, School.STUDENT_CAPACITY_PROPERTY); + return this; + } + public SchoolRequest countDistinctVersion(){ + return countDistinctVersionAs("version_distinct_count"); + } + + public SchoolRequest countDistinctVersionAs(String alias){ + super.countDistinctProperty(alias, School.VERSION_PROPERTY); + return this; + } + + public SchoolRequest groupById(){ + groupBy(School.ID_PROPERTY); + return this; + } + + public SchoolRequest groupByIdAs(String retName){ + groupBy(retName, School.ID_PROPERTY); + return this; + } + + public SchoolRequest groupByIdWithFunction(String retName, AggrFunction function){ + groupBy(retName, School.ID_PROPERTY, function); + return this; + } + public SchoolRequest groupByPlatformWith(PlatformRequest subRequest){ + groupBy(School.PLATFORM_PROPERTY, subRequest, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "groupByPlatformWith", null, "platform")); + return this; + } + public SchoolRequest groupByPlatform(){ + groupBy(School.PLATFORM_PROPERTY); + return this; + } + + public SchoolRequest groupByPlatformAs(String retName){ + groupBy(retName, School.PLATFORM_PROPERTY); + return this; + } + + public SchoolRequest groupByPlatformWithFunction(String retName, AggrFunction function){ + groupBy(retName, School.PLATFORM_PROPERTY, function); + return this; + } + public SchoolRequest groupBySchoolTypeWith(SchoolTypeRequest subRequest){ + groupBy(School.SCHOOL_TYPE_PROPERTY, subRequest, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "groupBySchoolTypeWith", null, "school_type")); + return this; + } + public SchoolRequest groupBySchoolType(){ + groupBy(School.SCHOOL_TYPE_PROPERTY); + return this; + } + + public SchoolRequest groupBySchoolTypeAs(String retName){ + groupBy(retName, School.SCHOOL_TYPE_PROPERTY); + return this; + } + + public SchoolRequest groupBySchoolTypeWithFunction(String retName, AggrFunction function){ + groupBy(retName, School.SCHOOL_TYPE_PROPERTY, function); + return this; + } + + public SchoolRequest groupByName(){ + groupBy(School.NAME_PROPERTY); + return this; + } + + public SchoolRequest groupByNameAs(String retName){ + groupBy(retName, School.NAME_PROPERTY); + return this; + } + + public SchoolRequest groupByNameWithFunction(String retName, AggrFunction function){ + groupBy(retName, School.NAME_PROPERTY, function); + return this; + } + + public SchoolRequest groupByStudentCapacity(){ + groupBy(School.STUDENT_CAPACITY_PROPERTY); + return this; + } + + public SchoolRequest groupByStudentCapacityAs(String retName){ + groupBy(retName, School.STUDENT_CAPACITY_PROPERTY); + return this; + } + + public SchoolRequest groupByStudentCapacityWithFunction(String retName, AggrFunction function){ + groupBy(retName, School.STUDENT_CAPACITY_PROPERTY, function); + return this; + } + + public SchoolRequest groupByVersion(){ + groupBy(School.VERSION_PROPERTY); + return this; + } + + public SchoolRequest groupByVersionAs(String retName){ + groupBy(retName, School.VERSION_PROPERTY); + return this; + } + + public SchoolRequest groupByVersionWithFunction(String retName, AggrFunction function){ + groupBy(retName, School.VERSION_PROPERTY, function); + return this; + } + + public SchoolRequest withSchoolTypeIsPrimary(){ + filterBySchoolType(com.example.inheritancematchingservice.Constants.SCHOOL_TYPE_PRIMARY); + return this; + } + + + public SchoolRequest withSchoolTypeIsSecondary(){ + filterBySchoolType(com.example.inheritancematchingservice.Constants.SCHOOL_TYPE_SECONDARY); + return this; + } + + + + + public SchoolRequest orderByIdAscending(){ + addOrderByAscending(School.ID_PROPERTY); + return this; + } + + public SchoolRequest orderByIdDescending(){ + addOrderByDescending(School.ID_PROPERTY); + return this; + } + + public SchoolRequest orderByPlatformAscending(){ + addOrderByAscending(School.PLATFORM_PROPERTY); + return this; + } + + public SchoolRequest orderByPlatformDescending(){ + addOrderByDescending(School.PLATFORM_PROPERTY); + return this; + } + + public SchoolRequest orderBySchoolTypeAscending(){ + addOrderByAscending(School.SCHOOL_TYPE_PROPERTY); + return this; + } + + public SchoolRequest orderBySchoolTypeDescending(){ + addOrderByDescending(School.SCHOOL_TYPE_PROPERTY); + return this; + } + + public SchoolRequest orderByNameAscending(){ + addOrderByAscending(School.NAME_PROPERTY); + return this; + } + + public SchoolRequest orderByNameDescending(){ + addOrderByDescending(School.NAME_PROPERTY); + return this; + } + public SchoolRequest orderByNameAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(School.NAME_PROPERTY); + return this; + } + + public SchoolRequest orderByNameDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(School.NAME_PROPERTY); + return this; + } + public SchoolRequest orderByStudentCapacityAscending(){ + addOrderByAscending(School.STUDENT_CAPACITY_PROPERTY); + return this; + } + + public SchoolRequest orderByStudentCapacityDescending(){ + addOrderByDescending(School.STUDENT_CAPACITY_PROPERTY); + return this; + } + + public SchoolRequest orderByVersionAscending(){ + addOrderByAscending(School.VERSION_PROPERTY); + return this; + } + + public SchoolRequest orderByVersionDescending(){ + addOrderByDescending(School.VERSION_PROPERTY); + return this; + } + + + public PlatformRequest rollUpToPlatform(){ + PlatformRequest platform = Q.platforms().unlimited(); + this.internalRollUpTo("platform", platform, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "rollUpToPlatform", null, "platform")); + return platform; + } + + public SchoolTypeRequest rollUpToSchoolType(){ + SchoolTypeRequest schoolType = Q.schoolTypes().unlimited(); + this.internalRollUpTo("school_type", schoolType, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "rollUpToSchoolType", null, "school_type")); + return schoolType; + } + + + + + + public SchoolRequest facetByPlatformAs(String facetName, PlatformRequest platform){ + return facetByPlatformAs(facetName, platform, true); + } + + public SchoolRequest facetByPlatformAs(String facetName, PlatformRequest platform, boolean includeAllFacets){ + addFacet(facetName, School.PLATFORM_PROPERTY, platform, includeAllFacets, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.FACET, "facetByPlatformAs", facetName, School.PLATFORM_PROPERTY)); + return this; + } + public SchoolRequest facetBySchoolTypeAs(String facetName, SchoolTypeRequest schoolType){ + return facetBySchoolTypeAs(facetName, schoolType, true); + } + + public SchoolRequest facetBySchoolTypeAs(String facetName, SchoolTypeRequest schoolType, boolean includeAllFacets){ + addFacet(facetName, School.SCHOOL_TYPE_PROPERTY, schoolType, includeAllFacets, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.FACET, "facetBySchoolTypeAs", facetName, School.SCHOOL_TYPE_PROPERTY)); + return this; + } + + + /** + * get topN records + * @param topN records number + */ + public SchoolRequest top(int topN) { + super.top(topN); + return this; + } + + /** Cross-runtime bounded-query alias. */ + public SchoolRequest limit(int limit) { + return top(limit); + } + + /** + * get records from offset(inclusive) to offset+size(exclusive) + * @param offset record offset + * @param size records number + */ + public SchoolRequest offset(int offset, int size) { + super.offset(offset, size); + return this; + } + + /** + * retrieve all records + */ + public SchoolRequest unlimited() { + super.unlimited(); + return this; + } + + /** + * get records of one page + * @param pageNumber page number(1-based) + * @param pageSize page size + */ + public SchoolRequest 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 SchoolRequest page(int pageNumber) { + return page(pageNumber, 10); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolType.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolType.java new file mode 100644 index 000000000..87ead0675 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolType.java @@ -0,0 +1,172 @@ + +package com.example.inheritancematchingservice.schooltype; + +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.school.School; +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 SchoolType extends BaseEntity implements RemoteInput { + public static String INTERNAL_TYPE = "SchoolType"; + + // Framework metadata: complete fixed layout, independent of SQL/projection order. + public static final String __TEAQL_FIELD_LAYOUT_REVISION = "595b434cfd28e9e4b60604e6092f6b709bf97fbb85753ad9f93443a203ae2e25"; + public static final java.util.Map __TEAQL_FIXED_FIELD_INDEXES = + java.util.Map.ofEntries(java.util.Map.entry("platform", 0), java.util.Map.entry("id", 1), java.util.Map.entry("name", 2), java.util.Map.entry("code", 3), java.util.Map.entry("version", 4)); + public static final java.util.Map> __TEAQL_FIXED_FIELD_MAPPINGS = + java.util.Map.ofEntries(java.util.Map.entry("platform", java.util.List.of("platform", "platform")), 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("code", java.util.List.of("code", "code")), 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( + "school_list"); + public static final FieldLayout __TEAQL_FIELD_LAYOUT = + FieldLayout.installGenerated(FieldLayout.generated( + SchoolType.class, __TEAQL_FIELD_LAYOUT_REVISION, + __TEAQL_FIXED_FIELD_INDEXES, __TEAQL_FIXED_FIELD_MAPPINGS, __TEAQL_FIXED_RELATION_NAMES, + JsonFieldNamingProfile.fromModelValue("camelCase"))); + + + public static final String PLATFORM_PROPERTY = "platform"; + public static final String NAME_PROPERTY = "name"; + public static final String CODE_PROPERTY = "code"; + public static final String SCHOOL_LIST_PROPERTY = "school_list"; + private Platform platform; + + private String name; + + private String code; + + private SmartList schoolList; + + public Platform getPlatform(){ + return this.platform; + } + + public String getName(){ + return this.name; + } + + public String getCode(){ + return this.code; + } + + public SmartList getSchoolList(){ + return this.schoolList == null ? SmartList.unloaded() : this.schoolList; + } + public SchoolType updatePlatform(Platform platform){ + if(isPropertyLoaded(PLATFORM_PROPERTY) && Objects.equals(this.platform, platform)){ + return this; + } + handleUpdate(PLATFORM_PROPERTY, getPlatform(), platform); + this.platform = platform; + return this; + } + + public SchoolType 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 SchoolType updateCode(String code){ + code = (code == null ? null : code.trim()); + if(isPropertyLoaded(CODE_PROPERTY) && Objects.equals(this.code, code)){ + return this; + } + handleUpdate(CODE_PROPERTY, getCode(), code); + this.code = code; + return this; + } + + public SchoolType addSchool(School school){ + if (school == null){ + return this; + } + + if(null == this.schoolList){ + SmartList teaqlUnloadedItems = SmartList.unloaded(); + this.schoolList = teaqlUnloadedItems.map(value -> value); + } + + this.schoolList.add(school); + school.updateProperty(School.SCHOOL_TYPE_PROPERTY, this); + return this; + } + + public static SchoolType refer(Long id){ + SchoolType refer = new SchoolType(); + refer.__internalSet("id", id); + refer.set$status(EntityStatus.REFER); + return refer; + } + @Override + public String typeName(){ + return INTERNAL_TYPE; + } + + public SchoolType 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 "platform": this.platform = (Platform) value; break; + + case "name": this.name = (value == null ? null : ((String)value).trim()); break; + + case "code": this.code = (value == null ? null : ((String)value).trim()); break; + + case "school_list": this.schoolList = (SmartList) value; break; + default: super.__internalSet(property, value); + } + } + + @Override + @FrameworkInternal + public Object __internalGet(String property) { + switch (property) { + case "platform": return this.platform; + case "name": return this.name; + case "code": return this.code; + case "school_list": return this.schoolList; + default: + // Presentation uses the installed Java member mapping; SQL and + // hydration retain canonical names. These aliases only read. + switch (property) { + case "platform": return this.platform; + case "name": return this.name; + case "code": return this.code; + default: return super.__internalGet(property); + } + } + } + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeChecker.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeChecker.java new file mode 100644 index 000000000..96466d7ed --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeChecker.java @@ -0,0 +1,77 @@ + +package com.example.inheritancematchingservice.schooltype; + +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.platform.PlatformChecker; +import com.example.inheritancematchingservice.school.School; +import com.example.inheritancematchingservice.school.SchoolChecker; +import io.teaql.core.UserContext; +import io.teaql.core.checker.Checker; +import io.teaql.core.checker.ObjectLocation; + +public class SchoolTypeChecker implements Checker{ + + public String type(){ + return SchoolType.INTERNAL_TYPE; + } + + public void checkAndFix(UserContext _context, SchoolType schoolType, ObjectLocation _parentLocation){ + if(needCheck(_context, schoolType)){ + markAsChecked(_context, schoolType); + doCheck(_context, schoolType, _parentLocation); + } + } + + public void doCheck(UserContext _context, SchoolType schoolType, ObjectLocation _parentLocation){ + if((schoolType == null)){ + return; + } + boolean _contextFixEligible = needContextFix(_context, schoolType); + if(schoolType.needPersist()){ + } + if(schoolType.newItem()){ + }else if(schoolType.updateItem()){ + if(!schoolType.isPropertyLoaded("platform")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "platform"), "Mutation requires a fully loaded entity"); + } + if(!schoolType.isPropertyLoaded("name")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "name"), "Mutation requires a fully loaded entity"); + } + if(!schoolType.isPropertyLoaded("code")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "code"), "Mutation requires a fully loaded entity"); + } + + } + checkPlatform(_context, schoolType.getProperty(SchoolType.PLATFORM_PROPERTY), newLocation(_parentLocation, "platform")); + checkName(_context, schoolType.getProperty(SchoolType.NAME_PROPERTY), newLocation(_parentLocation, "name")); + checkCode(_context, schoolType.getProperty(SchoolType.CODE_PROPERTY), newLocation(_parentLocation, "code")); + for(int i = 0; schoolType.getSchoolList() != null && i < schoolType.getSchoolList().size(); i++){ + School school = schoolType.getSchoolList().get(i); + new SchoolChecker().checkAndFix(_context, school, newLocation(_parentLocation, "school_list", i)); + } + } + + public void checkPlatform(UserContext _context, Platform platform, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, platform); + if((platform == null)){ + return; + } + new PlatformChecker().checkAndFix(_context, platform, _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 checkCode(UserContext _context, String code, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, code); + if((code == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, code); + + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeExpression.java new file mode 100644 index 000000000..493934427 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeExpression.java @@ -0,0 +1,68 @@ + +package com.example.inheritancematchingservice.schooltype; + +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.platform.PlatformExpression; +import com.example.inheritancematchingservice.school.School; +import com.example.inheritancematchingservice.school.SchoolListExpression; +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 SchoolTypeExpression extends ExpressionAdaptor implements BaseEntityExpression { + public SchoolTypeExpression(Expression expression){ + super(expression); + } + + public SchoolTypeExpression(Expression expression, Function function){ + super(expression, function); + } + + public SchoolTypeExpression updateId(Long id){ + return new SchoolTypeExpression(this, $it -> {((SchoolType)$it).__internalSet("id", id); return this;}); + } + + public SchoolTypeExpression save(UserContext userContext){ + return new SchoolTypeExpression(this, $it -> ((SchoolType)$it).auditAs("Saved by Expression").save(userContext)); + } + + public SchoolTypeExpression save(String intent, UserContext userContext){ + return new SchoolTypeExpression(this, $it -> ((SchoolType)$it).auditAs(intent).save(userContext)); + } + + public boolean isNull() { + return resolve() == null; + } + + + public PlatformExpression getPlatform(){ + return new PlatformExpression(loaded("platform", "getPlatform", SchoolType::getPlatform)); + } + + public SchoolTypeExpression updatePlatform(Platform platform){ + return new SchoolTypeExpression(this, $it -> ((SchoolType)$it).updatePlatform(platform)); + } + + public Expression getName(){ + return loaded("name", "getName", SchoolType::getName); + } + public SchoolTypeExpression updateName(String name){ + return new SchoolTypeExpression(this, $it -> ((SchoolType)$it).updateName(name)); + } + + public Expression getCode(){ + return loaded("code", "getCode", SchoolType::getCode); + } + public SchoolTypeExpression updateCode(String code){ + return new SchoolTypeExpression(this, $it -> ((SchoolType)$it).updateCode(code)); + } + + public SchoolListExpression getSchoolList(){ + return new SchoolListExpression(loaded("school_list", "getSchoolList", SchoolType::getSchoolList)); + } + public SchoolTypeExpression addSchool(School school){ + return new SchoolTypeExpression(this, $it -> ((SchoolType)$it).addSchool(school)); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeListExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeListExpression.java new file mode 100644 index 000000000..1d5de85df --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeListExpression.java @@ -0,0 +1,25 @@ + +package com.example.inheritancematchingservice.schooltype; + +import io.teaql.core.SmartList; +import io.teaql.core.value.Expression; +import io.teaql.core.value.SmartListExpression; +import java.util.function.Function; + +public class SchoolTypeListExpression extends SmartListExpression { + public SchoolTypeListExpression(Expression> expression){ + super(expression); + } + + public SchoolTypeListExpression(Expression expression, Function> function){ + super(expression, function); + } + + public SchoolTypeExpression first() { + return new SchoolTypeExpression(super.first()); + } + + public SchoolTypeExpression get(int index) { + return new SchoolTypeExpression(super.get(index)); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeRequest.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeRequest.java new file mode 100644 index 000000000..82c7b7e0f --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/schooltype/SchoolTypeRequest.java @@ -0,0 +1,1052 @@ + +package com.example.inheritancematchingservice.schooltype; + +import com.example.inheritancematchingservice.Q; +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.platform.PlatformRequest; +import com.example.inheritancematchingservice.school.School; +import com.example.inheritancematchingservice.school.SchoolRequest; +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.util.Objects; + +public class SchoolTypeRequest extends BaseRequest { + + /** + * @deprecated AI agents and business code must use the generated Q facade + * instead of constructing request builders directly. + */ + @Deprecated + @SuppressWarnings("unchecked") + public SchoolTypeRequest(Class returnType){ + this(returnType, () -> (T) new SchoolType()); + } + + protected SchoolTypeRequest(Class returnType, java.util.function.Supplier factory){ + super(returnType, factory); + selectId(); + selectVersion(); + } + + public SchoolTypeRequest comment(String comment){ + super.internalComment(comment); + return this; + } + + /** Independent query graph; ordinary roll-up handles remain live. */ + @Override + @SuppressWarnings("unchecked") + public SchoolTypeRequest copy(){ + return (SchoolTypeRequest) super.copy(); + } + + @Override + @SuppressWarnings("unchecked") + protected io.teaql.core.BaseRequest internalCopyTarget(){ + return new SchoolTypeRequest<>((Class) returnType(), this::internalNewEntity); + } + + // purpose() 继承自 BaseRequest,返回 ExecutableRequest(终结方法) + + public SchoolTypeRequest returnType(Class returnType){ + super.setReturnType(returnType); + return this; + } + + public SchoolTypeRequest enableAggregationCache(long cacheExpiredMillis){ + super.enableAggregationCache(); + super.aggregateCacheTime(cacheExpiredMillis); + return this; + } + + public SchoolTypeRequest enableAggregationCache(){ + return enableAggregationCache(0l); + } + + + public SchoolTypeRequest 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 SchoolTypeRequest optimizeForContinuousPageFetch(){ + super.optimizeForContinuousPageFetch(); + return this; + } + + public SchoolTypeRequest optimizeForContinuousPageFetch(String namespace, int ttlSeconds){ + super.optimizeForContinuousPageFetch(namespace, ttlSeconds); + return this; + } + + public SchoolTypeRequest optimizePaginationWithIdSet(){ + super.optimizePaginationWithIdSet(); + return this; + } + + public SchoolTypeRequest optimizePaginationWithIdSet( + String namespace, int ttlSeconds, int maxIds){ + super.optimizePaginationWithIdSet(namespace, ttlSeconds, maxIds); + return this; + } + + public SchoolTypeRequest topNProbeParentThreshold(int threshold){ + super.topNProbeParentThreshold(threshold); + return this; + } + + public SchoolTypeRequest appendSearchCriteria(SearchCriteria searchCriteria){ + return (SchoolTypeRequest)super.appendSearchCriteria(searchCriteria); + } + + public SchoolTypeRequest filter(String property1, Operator operator, String property2){ + return appendSearchCriteria(new TwoOperatorCriteria(operator, new PropertyReference(property1), new PropertyReference(property2))); + } + + + public SchoolTypeRequest matchingAnyOf(SchoolTypeRequest schoolType){ + super.internalMatchAny(schoolType); + return this; + } + + public SchoolTypeRequest matchingIdsOf(SchoolTypeRequest request){ + Objects.requireNonNull(request, "matching request"); + return appendSearchCriteria(new SubQuerySearchCriteria( + SchoolType.ID_PROPERTY, request, SchoolType.ID_PROPERTY)); + } + + public SchoolTypeRequest enhanceChildrenIfNeeded(){ + return this; + } + + public SchoolTypeRequest withDeletedRows(){ + super.withDeletedRows(); + return this; + } + + public SchoolTypeRequest deletedRowsOnly(){ + super.deletedRowsOnly(); + return this; + } + + public SchoolTypeRequest selectSelf(){ + super.selectSelf(); + return selectPlatformIdOnly().selectId().selectName().selectCode().selectVersion(); + } + + public SchoolTypeRequest selectSelfFields(){ + return selectSelf(); + } + + public SchoolTypeRequest selectSelfWithoutParent(){ + selectId(); + selectVersion(); + selectProperty(SchoolType.PLATFORM_PROPERTY); + selectProperty(SchoolType.ID_PROPERTY); + selectProperty(SchoolType.NAME_PROPERTY); + selectProperty(SchoolType.CODE_PROPERTY); + selectProperty(SchoolType.VERSION_PROPERTY); + return this; + } + + public SchoolTypeRequest selectAll(){ + super.selectAll(); + return selectPlatform().selectId().selectName().selectCode().selectVersion(); + } + + public SchoolTypeRequest selectChildren(){ + super.selectAny(); + selectSchoolList(); + return selectPlatform().selectId().selectName().selectCode().selectVersion(); + } + + + public SchoolTypeRequest selectPlatformIdOnly(){ + selectProperty(SchoolType.PLATFORM_PROPERTY); + return this; + } + + public SchoolTypeRequest selectPlatform(){ + return selectPlatformWith(Q.platforms().unlimited().selectSelf()); + } + + public SchoolTypeRequest selectPlatformWith(PlatformRequest platform){ + selectProperty(SchoolType.PLATFORM_PROPERTY); + enhanceRelation(SchoolType.PLATFORM_PROPERTY, platform, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_SELECT, "selectPlatformWith", null, SchoolType.PLATFORM_PROPERTY)); + return this; + } + + public SchoolTypeRequest unselectPlatform(){ + unselectProperty(SchoolType.PLATFORM_PROPERTY); + return this; + } + public SchoolTypeRequest selectId(){ + selectProperty(SchoolType.ID_PROPERTY); + return this; + } + + /** + * fill the id with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS id) to fetch id property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public SchoolTypeRequest unselectId(){ + unselectProperty(SchoolType.ID_PROPERTY); + return this; + } + public SchoolTypeRequest selectName(){ + selectProperty(SchoolType.NAME_PROPERTY); + return this; + } + + /** + * fill the name with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS name) to fetch name property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public SchoolTypeRequest unselectName(){ + unselectProperty(SchoolType.NAME_PROPERTY); + return this; + } + public SchoolTypeRequest selectCode(){ + selectProperty(SchoolType.CODE_PROPERTY); + return this; + } + + /** + * fill the code with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS code) to fetch code property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public SchoolTypeRequest unselectCode(){ + unselectProperty(SchoolType.CODE_PROPERTY); + return this; + } + public SchoolTypeRequest selectVersion(){ + selectProperty(SchoolType.VERSION_PROPERTY); + return this; + } + + /** + * fill the version with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS version) to fetch version property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public SchoolTypeRequest unselectVersion(){ + unselectProperty(SchoolType.VERSION_PROPERTY); + return this; + } + public SchoolTypeRequest selectSchoolList(){ + return selectSchoolListWith(Q.schools().selectSelf()); + } + + public SchoolTypeRequest selectSchoolListWith(SchoolRequest schoolList){ + enhanceRelation(SchoolType.SCHOOL_LIST_PROPERTY, schoolList, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_SELECT, "selectSchoolListWith", null, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest filterByPlatform(Platform... platform){ + if (platform == null || platform.length == 0) { + throw new IllegalArgumentException("filterByPlatform parameter platform cannot be empty"); + } + return appendSearchCriteria(createPlatformCriteria(Operator.EQUAL, (Object[])platform)); + } + + public SchoolTypeRequest withPlatform(Operator operator, Object... values){ + return appendSearchCriteria(createPlatformCriteria(operator, values)); + } + + public SchoolTypeRequest withPlatformIsUnknown(){ + return withPlatform(Operator.IS_NULL); + } + + public SchoolTypeRequest withPlatformIsKnown(){ + return withPlatform(Operator.IS_NOT_NULL); + } + + public SearchCriteria createPlatformCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(SchoolType.PLATFORM_PROPERTY, operator, values); + } + + public SchoolTypeRequest filterByPlatform(Long platform){ + if(platform == null){ + return this; + } + return withPlatform(Operator.EQUAL, platform); + } + public SchoolTypeRequest withPlatformMatching(PlatformRequest platform){ + return appendSearchCriteria(new SubQuerySearchCriteria(SchoolType.PLATFORM_PROPERTY, platform, Platform.ID_PROPERTY)); + } + + public SchoolTypeRequest withoutPlatformMatching(PlatformRequest platform){ + return appendSearchCriteria(SearchCriteria.not( + new SubQuerySearchCriteria(SchoolType.PLATFORM_PROPERTY, platform, Platform.ID_PROPERTY))); + } + + public SchoolTypeRequest withId(Operator operator, Object... values){ + return appendSearchCriteria(createIdCriteria(operator, values)); + } + + public SearchCriteria createIdCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(SchoolType.ID_PROPERTY, operator, values); + } + + public SchoolTypeRequest withIdIsNot(Long id){ + return withId(Operator.NOT_EQUAL, id); + } + + public SchoolTypeRequest withIdIn(Long... id){ + return withId(Operator.IN, (Object[])id); + } + + public SchoolTypeRequest withIdNotIn(Long... id){ + return withId(Operator.NOT_IN, (Object[])id); + } + public SchoolTypeRequest withIdIs(Long id){ + return withId(Operator.EQUAL, id); + } + + + + public SchoolTypeRequest 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 SchoolTypeRequest withName(Operator operator, Object... values){ + return appendSearchCriteria(createNameCriteria(operator, values)); + } + + public SchoolTypeRequest withNameIsUnknown(){ + return withName(Operator.IS_NULL); + } + + public SchoolTypeRequest withNameIsKnown(){ + return withName(Operator.IS_NOT_NULL); + } + + public SearchCriteria createNameCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(SchoolType.NAME_PROPERTY, operator, values); + } + + public SchoolTypeRequest withNameIsNot(String name){ + return withName(Operator.NOT_EQUAL, name); + } + + public SchoolTypeRequest withNameIn(String... name){ + return withName(Operator.IN, (Object[])name); + } + + public SchoolTypeRequest withNameNotIn(String... name){ + return withName(Operator.NOT_IN, (Object[])name); + } + public SchoolTypeRequest withNameGreaterThan(String name){ + return withName(Operator.GREATER_THAN, name); + } + + public SchoolTypeRequest withNameGreaterThanOrEqualTo(String name){ + return withName(Operator.GREATER_THAN_OR_EQUAL, name); + } + + public SchoolTypeRequest withNameLessThan(String name){ + return withName(Operator.LESS_THAN, name); + } + + public SchoolTypeRequest withNameLessThanOrEqualTo(String name){ + return withName(Operator.LESS_THAN_OR_EQUAL, name); + } + + public SchoolTypeRequest withNameBetween(String startOfName, String endOfName){ + return withName(Operator.BETWEEN, startOfName, endOfName); + } + public SchoolTypeRequest withNameStartingWith(String name){ + return withName(Operator.BEGIN_WITH, name); + } + public SchoolTypeRequest withNameContaining(String name){ + return withName(Operator.CONTAIN, name); + } + + public SchoolTypeRequest withNameNotContaining(String name){ + return withName(Operator.NOT_CONTAIN, name); + } + + public SchoolTypeRequest withNameNotStartingWith(String name){ + return withName(Operator.NOT_BEGIN_WITH, name); + } + + public SchoolTypeRequest withNameEndingWith(String name){ + return withName(Operator.END_WITH, name); + } + + public SchoolTypeRequest withNameNotEndingWith(String name){ + return withName(Operator.NOT_END_WITH, name); + } + + public SchoolTypeRequest withNameIs(String name){ + return withName(Operator.EQUAL, name); + } + + public SchoolTypeRequest withNameSoundingLike(String name){ + return withName(Operator.SOUNDS_LIKE, name); + } + + + + public SchoolTypeRequest filterByCode(String... code){ + if (code == null || code.length == 0) { + throw new IllegalArgumentException("filterByCode parameter code cannot be empty"); + } + return appendSearchCriteria(createCodeCriteria(Operator.EQUAL, (Object[])code)); + } + + public SchoolTypeRequest withCode(Operator operator, Object... values){ + return appendSearchCriteria(createCodeCriteria(operator, values)); + } + + public SchoolTypeRequest withCodeIsUnknown(){ + return withCode(Operator.IS_NULL); + } + + public SchoolTypeRequest withCodeIsKnown(){ + return withCode(Operator.IS_NOT_NULL); + } + + public SearchCriteria createCodeCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(SchoolType.CODE_PROPERTY, operator, values); + } + + public SchoolTypeRequest withCodeIsNot(String code){ + return withCode(Operator.NOT_EQUAL, code); + } + + public SchoolTypeRequest withCodeIn(String... code){ + return withCode(Operator.IN, (Object[])code); + } + + public SchoolTypeRequest withCodeNotIn(String... code){ + return withCode(Operator.NOT_IN, (Object[])code); + } + public SchoolTypeRequest withCodeGreaterThan(String code){ + return withCode(Operator.GREATER_THAN, code); + } + + public SchoolTypeRequest withCodeGreaterThanOrEqualTo(String code){ + return withCode(Operator.GREATER_THAN_OR_EQUAL, code); + } + + public SchoolTypeRequest withCodeLessThan(String code){ + return withCode(Operator.LESS_THAN, code); + } + + public SchoolTypeRequest withCodeLessThanOrEqualTo(String code){ + return withCode(Operator.LESS_THAN_OR_EQUAL, code); + } + + public SchoolTypeRequest withCodeBetween(String startOfCode, String endOfCode){ + return withCode(Operator.BETWEEN, startOfCode, endOfCode); + } + public SchoolTypeRequest withCodeStartingWith(String code){ + return withCode(Operator.BEGIN_WITH, code); + } + public SchoolTypeRequest withCodeContaining(String code){ + return withCode(Operator.CONTAIN, code); + } + + public SchoolTypeRequest withCodeNotContaining(String code){ + return withCode(Operator.NOT_CONTAIN, code); + } + + public SchoolTypeRequest withCodeNotStartingWith(String code){ + return withCode(Operator.NOT_BEGIN_WITH, code); + } + + public SchoolTypeRequest withCodeEndingWith(String code){ + return withCode(Operator.END_WITH, code); + } + + public SchoolTypeRequest withCodeNotEndingWith(String code){ + return withCode(Operator.NOT_END_WITH, code); + } + + public SchoolTypeRequest withCodeIs(String code){ + return withCode(Operator.EQUAL, code); + } + + public SchoolTypeRequest withCodeSoundingLike(String code){ + return withCode(Operator.SOUNDS_LIKE, code); + } + + + + public SchoolTypeRequest 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 SchoolTypeRequest withVersion(Operator operator, Object... values){ + return appendSearchCriteria(createVersionCriteria(operator, values)); + } + + public SchoolTypeRequest withVersionIsUnknown(){ + return withVersion(Operator.IS_NULL); + } + + public SchoolTypeRequest withVersionIsKnown(){ + return withVersion(Operator.IS_NOT_NULL); + } + + public SearchCriteria createVersionCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(SchoolType.VERSION_PROPERTY, operator, values); + } + + public SchoolTypeRequest withVersionIs(Long version){ + return withVersion(Operator.EQUAL, version); + } + + public SchoolTypeRequest withVersionIsNot(Long version){ + return withVersion(Operator.NOT_EQUAL, version); + } + + public SchoolTypeRequest withVersionIn(Long... version){ + return withVersion(Operator.IN, (Object[])version); + } + + public SchoolTypeRequest withVersionNotIn(Long... version){ + return withVersion(Operator.NOT_IN, (Object[])version); + } + public SchoolTypeRequest withVersionGreaterThan(Long version){ + return withVersion(Operator.GREATER_THAN, version); + } + + public SchoolTypeRequest withVersionGreaterThanOrEqualTo(Long version){ + return withVersion(Operator.GREATER_THAN_OR_EQUAL, version); + } + + public SchoolTypeRequest withVersionLessThan(Long version){ + return withVersion(Operator.LESS_THAN, version); + } + + public SchoolTypeRequest withVersionLessThanOrEqualTo(Long version){ + return withVersion(Operator.LESS_THAN_OR_EQUAL, version); + } + + public SchoolTypeRequest withVersionBetween(Long startOfVersion, Long endOfVersion){ + return withVersion(Operator.BETWEEN, startOfVersion, endOfVersion); + } + + + public SchoolTypeRequest withSchoolListMatching(SchoolRequest schoolRequest){ + return appendSearchCriteria(new SubQuerySearchCriteria(SchoolType.ID_PROPERTY, schoolRequest, School.SCHOOL_TYPE_PROPERTY)); + } + + public SchoolTypeRequest withoutSchoolListMatching(SchoolRequest schoolRequest){ + return appendSearchCriteria(SearchCriteria.not(new SubQuerySearchCriteria(SchoolType.ID_PROPERTY, schoolRequest, School.SCHOOL_TYPE_PROPERTY))); + } + + public SchoolTypeRequest haveSchools(){ + return withSchoolListMatching(Q.schools().unlimited()); + } + + public SchoolTypeRequest haveNoSchools(){ + return withoutSchoolListMatching(Q.schools().unlimited()); + } + + public SchoolTypeRequest count(){ + super.count(); + setPageCountOperation(io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.NAMED_COUNT, "count", null, null)); + return this; + } + public SchoolTypeRequest 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 SchoolTypeRequest groupByPlatformWithDetails(){ + return groupByPlatformWithDetails(Q.platforms().unlimited()); + } + + public SchoolTypeRequest groupByPlatformWithDetails(PlatformRequest subRequest){ + aggregate(SchoolType.PLATFORM_PROPERTY, subRequest); + return this; + } + + + + + + public SchoolTypeRequest countDistinctPlatform(){ + return countDistinctPlatformAs("platform_distinct_count"); + } + + public SchoolTypeRequest countDistinctPlatformAs(String alias){ + super.countDistinctProperty(alias, SchoolType.PLATFORM_PROPERTY); + return this; + } + public SchoolTypeRequest countDistinctId(){ + return countDistinctIdAs("id_distinct_count"); + } + + public SchoolTypeRequest countDistinctIdAs(String alias){ + super.countDistinctProperty(alias, SchoolType.ID_PROPERTY); + return this; + } + public SchoolTypeRequest countDistinctName(){ + return countDistinctNameAs("name_distinct_count"); + } + + public SchoolTypeRequest countDistinctNameAs(String alias){ + super.countDistinctProperty(alias, SchoolType.NAME_PROPERTY); + return this; + } + public SchoolTypeRequest countDistinctCode(){ + return countDistinctCodeAs("code_distinct_count"); + } + + public SchoolTypeRequest countDistinctCodeAs(String alias){ + super.countDistinctProperty(alias, SchoolType.CODE_PROPERTY); + return this; + } + public SchoolTypeRequest countDistinctVersion(){ + return countDistinctVersionAs("version_distinct_count"); + } + + public SchoolTypeRequest countDistinctVersionAs(String alias){ + super.countDistinctProperty(alias, SchoolType.VERSION_PROPERTY); + return this; + } + public SchoolTypeRequest groupBySchoolsWithDetails(SchoolRequest subRequest){ + aggregate(SchoolType.SCHOOL_LIST_PROPERTY, subRequest); + return this; + } + + public SchoolTypeRequest groupByPlatformWith(PlatformRequest subRequest){ + groupBy(SchoolType.PLATFORM_PROPERTY, subRequest, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "groupByPlatformWith", null, "platform")); + return this; + } + public SchoolTypeRequest groupByPlatform(){ + groupBy(SchoolType.PLATFORM_PROPERTY); + return this; + } + + public SchoolTypeRequest groupByPlatformAs(String retName){ + groupBy(retName, SchoolType.PLATFORM_PROPERTY); + return this; + } + + public SchoolTypeRequest groupByPlatformWithFunction(String retName, AggrFunction function){ + groupBy(retName, SchoolType.PLATFORM_PROPERTY, function); + return this; + } + + public SchoolTypeRequest groupById(){ + groupBy(SchoolType.ID_PROPERTY); + return this; + } + + public SchoolTypeRequest groupByIdAs(String retName){ + groupBy(retName, SchoolType.ID_PROPERTY); + return this; + } + + public SchoolTypeRequest groupByIdWithFunction(String retName, AggrFunction function){ + groupBy(retName, SchoolType.ID_PROPERTY, function); + return this; + } + + public SchoolTypeRequest groupByName(){ + groupBy(SchoolType.NAME_PROPERTY); + return this; + } + + public SchoolTypeRequest groupByNameAs(String retName){ + groupBy(retName, SchoolType.NAME_PROPERTY); + return this; + } + + public SchoolTypeRequest groupByNameWithFunction(String retName, AggrFunction function){ + groupBy(retName, SchoolType.NAME_PROPERTY, function); + return this; + } + + public SchoolTypeRequest groupByCode(){ + groupBy(SchoolType.CODE_PROPERTY); + return this; + } + + public SchoolTypeRequest groupByCodeAs(String retName){ + groupBy(retName, SchoolType.CODE_PROPERTY); + return this; + } + + public SchoolTypeRequest groupByCodeWithFunction(String retName, AggrFunction function){ + groupBy(retName, SchoolType.CODE_PROPERTY, function); + return this; + } + + public SchoolTypeRequest groupByVersion(){ + groupBy(SchoolType.VERSION_PROPERTY); + return this; + } + + public SchoolTypeRequest groupByVersionAs(String retName){ + groupBy(retName, SchoolType.VERSION_PROPERTY); + return this; + } + + public SchoolTypeRequest groupByVersionWithFunction(String retName, AggrFunction function){ + groupBy(retName, SchoolType.VERSION_PROPERTY, function); + return this; + } + + + + public SchoolTypeRequest orderByPlatformAscending(){ + addOrderByAscending(SchoolType.PLATFORM_PROPERTY); + return this; + } + + public SchoolTypeRequest orderByPlatformDescending(){ + addOrderByDescending(SchoolType.PLATFORM_PROPERTY); + return this; + } + + public SchoolTypeRequest orderByIdAscending(){ + addOrderByAscending(SchoolType.ID_PROPERTY); + return this; + } + + public SchoolTypeRequest orderByIdDescending(){ + addOrderByDescending(SchoolType.ID_PROPERTY); + return this; + } + + public SchoolTypeRequest orderByNameAscending(){ + addOrderByAscending(SchoolType.NAME_PROPERTY); + return this; + } + + public SchoolTypeRequest orderByNameDescending(){ + addOrderByDescending(SchoolType.NAME_PROPERTY); + return this; + } + public SchoolTypeRequest orderByNameAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(SchoolType.NAME_PROPERTY); + return this; + } + + public SchoolTypeRequest orderByNameDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(SchoolType.NAME_PROPERTY); + return this; + } + public SchoolTypeRequest orderByCodeAscending(){ + addOrderByAscending(SchoolType.CODE_PROPERTY); + return this; + } + + public SchoolTypeRequest orderByCodeDescending(){ + addOrderByDescending(SchoolType.CODE_PROPERTY); + return this; + } + public SchoolTypeRequest orderByCodeAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(SchoolType.CODE_PROPERTY); + return this; + } + + public SchoolTypeRequest orderByCodeDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(SchoolType.CODE_PROPERTY); + return this; + } + public SchoolTypeRequest orderByVersionAscending(){ + addOrderByAscending(SchoolType.VERSION_PROPERTY); + return this; + } + + public SchoolTypeRequest orderByVersionDescending(){ + addOrderByDescending(SchoolType.VERSION_PROPERTY); + return this; + } + + + public SchoolTypeRequest statsFromSchoolsAs(String name, SchoolRequest subRequest){ + return statsFromSchoolsAs(name, subRequest, false); + } + + public SchoolTypeRequest statsFromSchoolsAs(String name, SchoolRequest subRequest, boolean singleResult){ + addRelationAggregate(name, subRequest, School.SCHOOL_TYPE_PROPERTY, singleResult, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "statsFromSchoolsAs", name, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest statsFromSchools(SchoolRequest subRequest){ + return statsFromSchoolsAs(REFINEMENTS, subRequest); + } + public PlatformRequest rollUpToPlatform(){ + PlatformRequest platform = Q.platforms().unlimited(); + this.internalRollUpTo("platform", platform, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "rollUpToPlatform", null, "platform")); + return platform; + } + + + + + + public SchoolTypeRequest countSchools(){ + addRelationCount("Count", Q.schools().unlimited(), School.SCHOOL_TYPE_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countSchools", null, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest countSchoolsAs(String name){ + addRelationCount(name, Q.schools().unlimited(), School.SCHOOL_TYPE_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countSchoolsAs", name, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest countSchoolsWith(String name, SchoolRequest subRequest){ + addRelationCount(name, subRequest, School.SCHOOL_TYPE_PROPERTY, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.RELATION_COUNT, "countSchoolsWith", name, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + public SchoolTypeRequest minStudentCapacityOfSchools(){ + addRelationScalarAggregate("minStudentCapacityOfSchools", Q.schools().unlimited(), + School.SCHOOL_TYPE_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("min".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "minStudentCapacityOfSchools", null, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest minStudentCapacityOfSchoolsAs(String name){ + return minStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public SchoolTypeRequest minStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.SCHOOL_TYPE_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("min".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "minStudentCapacityOfSchoolsAs", name, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + public SchoolTypeRequest maxStudentCapacityOfSchools(){ + addRelationScalarAggregate("maxStudentCapacityOfSchools", Q.schools().unlimited(), + School.SCHOOL_TYPE_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("max".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "maxStudentCapacityOfSchools", null, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest maxStudentCapacityOfSchoolsAs(String name){ + return maxStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public SchoolTypeRequest maxStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.SCHOOL_TYPE_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("max".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "maxStudentCapacityOfSchoolsAs", name, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + public SchoolTypeRequest sumStudentCapacityOfSchools(){ + addRelationScalarAggregate("sumStudentCapacityOfSchools", Q.schools().unlimited(), + School.SCHOOL_TYPE_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("sum".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sumStudentCapacityOfSchools", null, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest sumStudentCapacityOfSchoolsAs(String name){ + return sumStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public SchoolTypeRequest sumStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.SCHOOL_TYPE_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("sum".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sumStudentCapacityOfSchoolsAs", name, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + public SchoolTypeRequest avgStudentCapacityOfSchools(){ + addRelationScalarAggregate("avgStudentCapacityOfSchools", Q.schools().unlimited(), + School.SCHOOL_TYPE_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("avg".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "avgStudentCapacityOfSchools", null, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest avgStudentCapacityOfSchoolsAs(String name){ + return avgStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public SchoolTypeRequest avgStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.SCHOOL_TYPE_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("avg".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "avgStudentCapacityOfSchoolsAs", name, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + public SchoolTypeRequest standardDeviationStudentCapacityOfSchools(){ + addRelationScalarAggregate("stdDevStudentCapacityOfSchools", Q.schools().unlimited(), + School.SCHOOL_TYPE_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "standardDeviationStudentCapacityOfSchools", null, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest standardDeviationStudentCapacityOfSchoolsAs(String name){ + return standardDeviationStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public SchoolTypeRequest standardDeviationStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.SCHOOL_TYPE_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "standardDeviationStudentCapacityOfSchoolsAs", name, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + public SchoolTypeRequest squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(){ + addRelationScalarAggregate("stdDevPopStudentCapacityOfSchools", Q.schools().unlimited(), + School.SCHOOL_TYPE_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "squareRootOfPopulationStandardDeviationStudentCapacityOfSchools", null, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(String name){ + return squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public SchoolTypeRequest squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.SCHOOL_TYPE_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("stddev_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs", name, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + public SchoolTypeRequest sampleVarianceStudentCapacityOfSchools(){ + addRelationScalarAggregate("varSampStudentCapacityOfSchools", Q.schools().unlimited(), + School.SCHOOL_TYPE_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_samp".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sampleVarianceStudentCapacityOfSchools", null, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest sampleVarianceStudentCapacityOfSchoolsAs(String name){ + return sampleVarianceStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public SchoolTypeRequest sampleVarianceStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.SCHOOL_TYPE_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_samp".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "sampleVarianceStudentCapacityOfSchoolsAs", name, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + public SchoolTypeRequest samplePopulationVarianceStudentCapacityOfSchools(){ + addRelationScalarAggregate("varPopStudentCapacityOfSchools", Q.schools().unlimited(), + School.SCHOOL_TYPE_PROPERTY, School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "samplePopulationVarianceStudentCapacityOfSchools", null, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest samplePopulationVarianceStudentCapacityOfSchoolsAs(String name){ + return samplePopulationVarianceStudentCapacityOfSchoolsAs(name, Q.schools().unlimited()); + } + + public SchoolTypeRequest samplePopulationVarianceStudentCapacityOfSchoolsAs(String name, SchoolRequest subRequest){ + addRelationScalarAggregate(name, subRequest, School.SCHOOL_TYPE_PROPERTY, + School.STUDENT_CAPACITY_PROPERTY, + io.teaql.core.AggrFunction.valueOf("var_pop".toUpperCase(java.util.Locale.ROOT)), + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.AGGREGATE, "samplePopulationVarianceStudentCapacityOfSchoolsAs", name, SchoolType.SCHOOL_LIST_PROPERTY)); + return this; + } + + public SchoolTypeRequest facetByPlatformAs(String facetName, PlatformRequest platform){ + return facetByPlatformAs(facetName, platform, true); + } + + public SchoolTypeRequest facetByPlatformAs(String facetName, PlatformRequest platform, boolean includeAllFacets){ + addFacet(facetName, SchoolType.PLATFORM_PROPERTY, platform, includeAllFacets, + io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.FACET, "facetByPlatformAs", facetName, SchoolType.PLATFORM_PROPERTY)); + return this; + } + + + /** + * get topN records + * @param topN records number + */ + public SchoolTypeRequest top(int topN) { + super.top(topN); + return this; + } + + /** Cross-runtime bounded-query alias. */ + public SchoolTypeRequest limit(int limit) { + return top(limit); + } + + /** + * get records from offset(inclusive) to offset+size(exclusive) + * @param offset record offset + * @param size records number + */ + public SchoolTypeRequest offset(int offset, int size) { + super.offset(offset, size); + return this; + } + + /** + * retrieve all records + */ + public SchoolTypeRequest unlimited() { + super.unlimited(); + return this; + } + + /** + * get records of one page + * @param pageNumber page number(1-based) + * @param pageSize page size + */ + public SchoolTypeRequest 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 SchoolTypeRequest page(int pageNumber) { + return page(pageNumber, 10); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademy.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademy.java new file mode 100644 index 000000000..bde31f315 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademy.java @@ -0,0 +1,137 @@ + +package com.example.inheritancematchingservice.trainingacademy; + +import com.example.inheritancematchingservice.academy.Academy; +import com.example.inheritancematchingservice.platform.Platform; +import io.teaql.core.Audited; +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.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 TrainingAcademy extends Academy implements RemoteInput { + public static String INTERNAL_TYPE = "TrainingAcademy"; + + // Framework metadata: complete fixed layout, independent of SQL/projection order. + public static final String __TEAQL_FIELD_LAYOUT_REVISION = "febc19f1547b3c9d17b9acd2ae34f398323bbe38ad635615cf4c19a534590fbc"; + public static final java.util.Map __TEAQL_FIXED_FIELD_INDEXES = + java.util.Map.ofEntries(java.util.Map.entry("id", 0), java.util.Map.entry("platform", 1), java.util.Map.entry("school_type", 2), java.util.Map.entry("name", 3), java.util.Map.entry("student_capacity", 4), java.util.Map.entry("version", 5), java.util.Map.entry("campus_code", 6), java.util.Map.entry("specialty", 7)); + 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("platform", java.util.List.of("platform", "platform")), java.util.Map.entry("school_type", java.util.List.of("schoolType", "school_type")), java.util.Map.entry("name", java.util.List.of("name", "name")), java.util.Map.entry("student_capacity", java.util.List.of("studentCapacity", "student_capacity")), java.util.Map.entry("version", java.util.List.of("version", "version")), java.util.Map.entry("campus_code", java.util.List.of("campusCode", "Legacy Campus Code")), java.util.Map.entry("specialty", java.util.List.of("specialty", "specialty"))); + 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( + TrainingAcademy.class, __TEAQL_FIELD_LAYOUT_REVISION, + __TEAQL_FIXED_FIELD_INDEXES, __TEAQL_FIXED_FIELD_MAPPINGS, __TEAQL_FIXED_RELATION_NAMES, + JsonFieldNamingProfile.fromModelValue("camelCase"))); + + + public static final String SPECIALTY_PROPERTY = "specialty"; + private String specialty; + + + public String getSpecialty(){ + return this.specialty; + } + + public TrainingAcademy updateSpecialty(String specialty){ + specialty = (specialty == null ? null : specialty.trim()); + if(isPropertyLoaded(SPECIALTY_PROPERTY) && Objects.equals(this.specialty, specialty)){ + return this; + } + handleUpdate(SPECIALTY_PROPERTY, getSpecialty(), specialty); + this.specialty = specialty; + return this; + } + + public TrainingAcademy updateCampusCode(String campusCode){ + super.updateCampusCode(campusCode); + return this; + } + + public TrainingAcademy updatePlatform(Platform platform){ + super.updatePlatform(platform); + return this; + } + + public TrainingAcademy updateSchoolTypeToPrimary(){ + super.updateSchoolTypeToPrimary(); + return this; + } + public TrainingAcademy updateSchoolTypeToSecondary(){ + super.updateSchoolTypeToSecondary(); + return this; + } + + public TrainingAcademy updateName(String name){ + super.updateName(name); + return this; + } + + public TrainingAcademy updateStudentCapacity(Integer studentCapacity){ + super.updateStudentCapacity(studentCapacity); + return this; + } + + + public static TrainingAcademy refer(Long id){ + TrainingAcademy refer = new TrainingAcademy(); + refer.__internalSet("id", id); + refer.set$status(EntityStatus.REFER); + return refer; + } + @Override + public String typeName(){ + return INTERNAL_TYPE; + } + + public TrainingAcademy 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 "specialty": this.specialty = (value == null ? null : ((String)value).trim()); break; + + default: super.__internalSet(property, value); + } + } + + @Override + @FrameworkInternal + public Object __internalGet(String property) { + switch (property) { + case "specialty": return this.specialty; + default: + // Presentation uses the installed Java member mapping; SQL and + // hydration retain canonical names. These aliases only read. + switch (property) { + case "specialty": return this.specialty; + default: return super.__internalGet(property); + } + } + } + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyChecker.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyChecker.java new file mode 100644 index 000000000..bc8629f7a --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyChecker.java @@ -0,0 +1,49 @@ + +package com.example.inheritancematchingservice.trainingacademy; + +import com.example.inheritancematchingservice.academy.AcademyChecker; +import io.teaql.core.UserContext; +import io.teaql.core.checker.Checker; +import io.teaql.core.checker.ObjectLocation; + +public class TrainingAcademyChecker implements Checker{ + + public String type(){ + return TrainingAcademy.INTERNAL_TYPE; + } + + public void checkAndFix(UserContext _context, TrainingAcademy trainingAcademy, ObjectLocation _parentLocation){ + if(needCheck(_context, trainingAcademy)){ + markAsChecked(_context, trainingAcademy); + new AcademyChecker().doCheck(_context, trainingAcademy, _parentLocation); + + doCheck(_context, trainingAcademy, _parentLocation); + } + } + + public void doCheck(UserContext _context, TrainingAcademy trainingAcademy, ObjectLocation _parentLocation){ + if((trainingAcademy == null)){ + return; + } + boolean _contextFixEligible = needContextFix(_context, trainingAcademy); + if(trainingAcademy.needPersist()){ + } + if(trainingAcademy.newItem()){ + }else if(trainingAcademy.updateItem()){ + if(!trainingAcademy.isPropertyLoaded("specialty")){ + invalidTypeCheck(_context, newLocation(_parentLocation, "specialty"), "Mutation requires a fully loaded entity"); + } + + } + checkSpecialty(_context, trainingAcademy.getProperty(TrainingAcademy.SPECIALTY_PROPERTY), newLocation(_parentLocation, "specialty")); + } + + public void checkSpecialty(UserContext _context, String specialty, ObjectLocation _parentLocation){ + requiredCheck(_context, _parentLocation, specialty); + if((specialty == null)){ + return; + } + maxStringCheck(_context, _parentLocation, 100, specialty); + + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyExpression.java new file mode 100644 index 000000000..2a61e8419 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyExpression.java @@ -0,0 +1,43 @@ + +package com.example.inheritancematchingservice.trainingacademy; + +import com.example.inheritancematchingservice.academy.AcademyExpression; +import io.teaql.core.UserContext; +import io.teaql.core.value.BaseEntityExpression; +import io.teaql.core.value.Expression; +import java.util.function.Function; + +public class TrainingAcademyExpression extends AcademyExpression implements BaseEntityExpression { + public TrainingAcademyExpression(Expression expression){ + super(expression); + } + + public TrainingAcademyExpression(Expression expression, Function function){ + super(expression, function); + } + + public TrainingAcademyExpression updateId(Long id){ + return new TrainingAcademyExpression(this, $it -> {((TrainingAcademy)$it).__internalSet("id", id); return this;}); + } + + public TrainingAcademyExpression save(UserContext userContext){ + return new TrainingAcademyExpression(this, $it -> ((TrainingAcademy)$it).auditAs("Saved by Expression").save(userContext)); + } + + public TrainingAcademyExpression save(String intent, UserContext userContext){ + return new TrainingAcademyExpression(this, $it -> ((TrainingAcademy)$it).auditAs(intent).save(userContext)); + } + + public boolean isNull() { + return resolve() == null; + } + + + public Expression getSpecialty(){ + return loaded("specialty", "getSpecialty", TrainingAcademy::getSpecialty); + } + public TrainingAcademyExpression updateSpecialty(String specialty){ + return new TrainingAcademyExpression(this, $it -> ((TrainingAcademy)$it).updateSpecialty(specialty)); + } + +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyListExpression.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyListExpression.java new file mode 100644 index 000000000..f96108cb3 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyListExpression.java @@ -0,0 +1,25 @@ + +package com.example.inheritancematchingservice.trainingacademy; + +import io.teaql.core.SmartList; +import io.teaql.core.value.Expression; +import io.teaql.core.value.SmartListExpression; +import java.util.function.Function; + +public class TrainingAcademyListExpression extends SmartListExpression { + public TrainingAcademyListExpression(Expression> expression){ + super(expression); + } + + public TrainingAcademyListExpression(Expression expression, Function> function){ + super(expression, function); + } + + public TrainingAcademyExpression first() { + return new TrainingAcademyExpression(super.first()); + } + + public TrainingAcademyExpression get(int index) { + return new TrainingAcademyExpression(super.get(index)); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyRequest.java b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyRequest.java new file mode 100644 index 000000000..511589548 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/java/com/example/inheritancematchingservice/trainingacademy/TrainingAcademyRequest.java @@ -0,0 +1,1024 @@ + +package com.example.inheritancematchingservice.trainingacademy; + +import com.example.inheritancematchingservice.academy.AcademyRequest; +import com.example.inheritancematchingservice.platform.Platform; +import com.example.inheritancematchingservice.platform.PlatformRequest; +import com.example.inheritancematchingservice.schooltype.SchoolType; +import com.example.inheritancematchingservice.schooltype.SchoolTypeRequest; +import io.teaql.core.AggrFunction; +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.util.Objects; + +public class TrainingAcademyRequest extends AcademyRequest { + + /** + * @deprecated AI agents and business code must use the generated Q facade + * instead of constructing request builders directly. + */ + @Deprecated + @SuppressWarnings("unchecked") + public TrainingAcademyRequest(Class returnType){ + this(returnType, () -> (T) new TrainingAcademy()); + } + + protected TrainingAcademyRequest(Class returnType, java.util.function.Supplier factory){ + super(returnType, factory); + selectId(); + selectVersion(); + } + + public TrainingAcademyRequest comment(String comment){ + super.internalComment(comment); + return this; + } + + /** Independent query graph; ordinary roll-up handles remain live. */ + @Override + @SuppressWarnings("unchecked") + public TrainingAcademyRequest copy(){ + return (TrainingAcademyRequest) super.copy(); + } + + @Override + @SuppressWarnings("unchecked") + protected io.teaql.core.BaseRequest internalCopyTarget(){ + return new TrainingAcademyRequest<>((Class) returnType(), this::internalNewEntity); + } + + // purpose() 继承自 BaseRequest,返回 ExecutableRequest(终结方法) + + public TrainingAcademyRequest returnType(Class returnType){ + super.setReturnType(returnType); + return this; + } + + public TrainingAcademyRequest enableAggregationCache(long cacheExpiredMillis){ + super.enableAggregationCache(); + super.aggregateCacheTime(cacheExpiredMillis); + return this; + } + + public TrainingAcademyRequest enableAggregationCache(){ + return enableAggregationCache(0l); + } + + + public TrainingAcademyRequest 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 TrainingAcademyRequest optimizeForContinuousPageFetch(){ + super.optimizeForContinuousPageFetch(); + return this; + } + + public TrainingAcademyRequest optimizeForContinuousPageFetch(String namespace, int ttlSeconds){ + super.optimizeForContinuousPageFetch(namespace, ttlSeconds); + return this; + } + + public TrainingAcademyRequest optimizePaginationWithIdSet(){ + super.optimizePaginationWithIdSet(); + return this; + } + + public TrainingAcademyRequest optimizePaginationWithIdSet( + String namespace, int ttlSeconds, int maxIds){ + super.optimizePaginationWithIdSet(namespace, ttlSeconds, maxIds); + return this; + } + + public TrainingAcademyRequest topNProbeParentThreshold(int threshold){ + super.topNProbeParentThreshold(threshold); + return this; + } + + public TrainingAcademyRequest appendSearchCriteria(SearchCriteria searchCriteria){ + return (TrainingAcademyRequest)super.appendSearchCriteria(searchCriteria); + } + + public TrainingAcademyRequest filter(String property1, Operator operator, String property2){ + return appendSearchCriteria(new TwoOperatorCriteria(operator, new PropertyReference(property1), new PropertyReference(property2))); + } + + + public TrainingAcademyRequest matchingAnyOf(TrainingAcademyRequest trainingAcademy){ + super.internalMatchAny(trainingAcademy); + return this; + } + + public TrainingAcademyRequest matchingIdsOf(TrainingAcademyRequest request){ + Objects.requireNonNull(request, "matching request"); + return appendSearchCriteria(new SubQuerySearchCriteria( + TrainingAcademy.ID_PROPERTY, request, TrainingAcademy.ID_PROPERTY)); + } + + public TrainingAcademyRequest enhanceChildrenIfNeeded(){ + return this; + } + + public TrainingAcademyRequest withDeletedRows(){ + super.withDeletedRows(); + return this; + } + + public TrainingAcademyRequest deletedRowsOnly(){ + super.deletedRowsOnly(); + return this; + } + + public TrainingAcademyRequest selectSelf(){ + super.selectSelf(); + return selectSpecialty(); + } + + public TrainingAcademyRequest selectSelfFields(){ + return selectSelf(); + } + + public TrainingAcademyRequest selectSelfWithoutParent(){ + selectId(); + selectVersion(); + selectProperty(TrainingAcademy.SPECIALTY_PROPERTY); + return this; + } + + public TrainingAcademyRequest selectAll(){ + super.selectAll(); + return selectSpecialty(); + } + + public TrainingAcademyRequest selectChildren(){ + super.selectAny(); + return selectSpecialty(); + } + + + public TrainingAcademyRequest selectSpecialty(){ + selectProperty(TrainingAcademy.SPECIALTY_PROPERTY); + return this; + } + + /** + * fill the specialty with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS specialty) to fetch specialty property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public TrainingAcademyRequest unselectSpecialty(){ + unselectProperty(TrainingAcademy.SPECIALTY_PROPERTY); + return this; + } + public TrainingAcademyRequest selectCampusCode(){ + super.selectCampusCode(); + return this; + } + + /** + * fill the campusCode with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS campusCode) to fetch campusCode property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public TrainingAcademyRequest unselectCampusCode(){ + super.unselectCampusCode(); + return this; + } + public TrainingAcademyRequest selectPlatformIdOnly(){ + super.selectPlatformIdOnly(); + return this; + } + + public TrainingAcademyRequest selectPlatform(){ + super.selectPlatform(); + return this; + } + + public TrainingAcademyRequest selectPlatformWith(PlatformRequest platform){ + super.selectPlatformWith(platform); + return this; + } + + public TrainingAcademyRequest unselectPlatform(){ + super.unselectPlatform(); + return this; + } + public TrainingAcademyRequest selectSchoolTypeIdOnly(){ + super.selectSchoolTypeIdOnly(); + return this; + } + + public TrainingAcademyRequest selectSchoolType(){ + super.selectSchoolType(); + return this; + } + + public TrainingAcademyRequest selectSchoolTypeWith(SchoolTypeRequest schoolType){ + super.selectSchoolTypeWith(schoolType); + return this; + } + + public TrainingAcademyRequest unselectSchoolType(){ + super.unselectSchoolType(); + return this; + } + public TrainingAcademyRequest selectName(){ + super.selectName(); + return this; + } + + /** + * fill the name with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS name) to fetch name property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public TrainingAcademyRequest unselectName(){ + super.unselectName(); + return this; + } + public TrainingAcademyRequest selectStudentCapacity(){ + super.selectStudentCapacity(); + return this; + } + + /** + * fill the studentCapacity with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS studentCapacity) to fetch studentCapacity property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + /** + * fill the studentCapacity with customized aggrFunction, TEAQL uses ({aggrFunction}(studentCapacity) AS studentCapacity to fetch studentCapacity property. + * @param aggrFunction aggrFunction + */ + public TrainingAcademyRequest selectStudentCapacity(AggrFunction aggrFunction){ + super.selectStudentCapacity(aggrFunction); + return this; + } + + + public TrainingAcademyRequest unselectStudentCapacity(){ + super.unselectStudentCapacity(); + return this; + } + public TrainingAcademyRequest selectVersion(){ + super.selectVersion(); + return this; + } + + /** + * fill the version with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS version) to fetch version property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public TrainingAcademyRequest unselectVersion(){ + super.unselectVersion(); + return this; + } + public TrainingAcademyRequest selectId(){ + super.selectId(); + return this; + } + + /** + * fill the id with customized rawSqlSegment, TEAQL uses ({rawSqlSegment} AS id) to fetch id property. + * @param rawSqlSegment customized rawSqlSegment + */ + + + + + public TrainingAcademyRequest unselectId(){ + super.unselectId(); + return this; + } + + public TrainingAcademyRequest filterBySpecialty(String... specialty){ + if (specialty == null || specialty.length == 0) { + throw new IllegalArgumentException("filterBySpecialty parameter specialty cannot be empty"); + } + return appendSearchCriteria(createSpecialtyCriteria(Operator.EQUAL, (Object[])specialty)); + } + + public TrainingAcademyRequest withSpecialty(Operator operator, Object... values){ + return appendSearchCriteria(createSpecialtyCriteria(operator, values)); + } + + public TrainingAcademyRequest withSpecialtyIsUnknown(){ + return withSpecialty(Operator.IS_NULL); + } + + public TrainingAcademyRequest withSpecialtyIsKnown(){ + return withSpecialty(Operator.IS_NOT_NULL); + } + + public SearchCriteria createSpecialtyCriteria(Operator operator, Object... values) { + return createBasicSearchCriteria(TrainingAcademy.SPECIALTY_PROPERTY, operator, values); + } + + public TrainingAcademyRequest withSpecialtyIsNot(String specialty){ + return withSpecialty(Operator.NOT_EQUAL, specialty); + } + + public TrainingAcademyRequest withSpecialtyIn(String... specialty){ + return withSpecialty(Operator.IN, (Object[])specialty); + } + + public TrainingAcademyRequest withSpecialtyNotIn(String... specialty){ + return withSpecialty(Operator.NOT_IN, (Object[])specialty); + } + public TrainingAcademyRequest withSpecialtyGreaterThan(String specialty){ + return withSpecialty(Operator.GREATER_THAN, specialty); + } + + public TrainingAcademyRequest withSpecialtyGreaterThanOrEqualTo(String specialty){ + return withSpecialty(Operator.GREATER_THAN_OR_EQUAL, specialty); + } + + public TrainingAcademyRequest withSpecialtyLessThan(String specialty){ + return withSpecialty(Operator.LESS_THAN, specialty); + } + + public TrainingAcademyRequest withSpecialtyLessThanOrEqualTo(String specialty){ + return withSpecialty(Operator.LESS_THAN_OR_EQUAL, specialty); + } + + public TrainingAcademyRequest withSpecialtyBetween(String startOfSpecialty, String endOfSpecialty){ + return withSpecialty(Operator.BETWEEN, startOfSpecialty, endOfSpecialty); + } + public TrainingAcademyRequest withSpecialtyStartingWith(String specialty){ + return withSpecialty(Operator.BEGIN_WITH, specialty); + } + public TrainingAcademyRequest withSpecialtyContaining(String specialty){ + return withSpecialty(Operator.CONTAIN, specialty); + } + + public TrainingAcademyRequest withSpecialtyNotContaining(String specialty){ + return withSpecialty(Operator.NOT_CONTAIN, specialty); + } + + public TrainingAcademyRequest withSpecialtyNotStartingWith(String specialty){ + return withSpecialty(Operator.NOT_BEGIN_WITH, specialty); + } + + public TrainingAcademyRequest withSpecialtyEndingWith(String specialty){ + return withSpecialty(Operator.END_WITH, specialty); + } + + public TrainingAcademyRequest withSpecialtyNotEndingWith(String specialty){ + return withSpecialty(Operator.NOT_END_WITH, specialty); + } + + public TrainingAcademyRequest withSpecialtyIs(String specialty){ + return withSpecialty(Operator.EQUAL, specialty); + } + + public TrainingAcademyRequest withSpecialtySoundingLike(String specialty){ + return withSpecialty(Operator.SOUNDS_LIKE, specialty); + } + + + + public TrainingAcademyRequest filterByCampusCode(String campusCode){ + return (TrainingAcademyRequest)super.filterByCampusCode(campusCode); + } + + public TrainingAcademyRequest withCampusCode(Operator operator, Object... values){ + return (TrainingAcademyRequest)super.withCampusCode(operator, values); + } + + public TrainingAcademyRequest withCampusCodeIsUnknown(){ + return (TrainingAcademyRequest)super.withCampusCodeIsUnknown(); + } + + public TrainingAcademyRequest withCampusCodeIsKnown(){ + return (TrainingAcademyRequest)super.withCampusCodeIsKnown(); + } + + public TrainingAcademyRequest withCampusCodeStartingWith(String CampusCode){ + return (TrainingAcademyRequest)super.withCampusCodeStartingWith(CampusCode); + } + public TrainingAcademyRequest withCampusCodeContaining(String CampusCode){ + return (TrainingAcademyRequest)super.withCampusCodeContaining(CampusCode); + } + + public TrainingAcademyRequest withCampusCodeEndingWith(String CampusCode){ + return (TrainingAcademyRequest)super.withCampusCodeEndingWith(CampusCode); + } + + + public TrainingAcademyRequest filterByPlatform(Platform platform){ + return (TrainingAcademyRequest)super.filterByPlatform(platform); + } + + public TrainingAcademyRequest withPlatform(Operator operator, Object... values){ + return (TrainingAcademyRequest)super.withPlatform(operator, values); + } + + public TrainingAcademyRequest withPlatformIsUnknown(){ + return (TrainingAcademyRequest)super.withPlatformIsUnknown(); + } + + public TrainingAcademyRequest withPlatformIsKnown(){ + return (TrainingAcademyRequest)super.withPlatformIsKnown(); + } + + public TrainingAcademyRequest filterByPlatform(Long platform){ + return (TrainingAcademyRequest)super.filterByPlatform(platform); + } + + public TrainingAcademyRequest withPlatformMatching(PlatformRequest platform){ + return (TrainingAcademyRequest)super.withPlatformMatching(platform); + } + + public TrainingAcademyRequest filterBySchoolType(SchoolType schoolType){ + return (TrainingAcademyRequest)super.filterBySchoolType(schoolType); + } + + public TrainingAcademyRequest withSchoolType(Operator operator, Object... values){ + return (TrainingAcademyRequest)super.withSchoolType(operator, values); + } + + public TrainingAcademyRequest withSchoolTypeIsUnknown(){ + return (TrainingAcademyRequest)super.withSchoolTypeIsUnknown(); + } + + public TrainingAcademyRequest withSchoolTypeIsKnown(){ + return (TrainingAcademyRequest)super.withSchoolTypeIsKnown(); + } + + public TrainingAcademyRequest filterBySchoolType(Long schoolType){ + return (TrainingAcademyRequest)super.filterBySchoolType(schoolType); + } + + public TrainingAcademyRequest withSchoolTypeMatching(SchoolTypeRequest schoolType){ + return (TrainingAcademyRequest)super.withSchoolTypeMatching(schoolType); + } + + public TrainingAcademyRequest filterByName(String name){ + return (TrainingAcademyRequest)super.filterByName(name); + } + + public TrainingAcademyRequest withName(Operator operator, Object... values){ + return (TrainingAcademyRequest)super.withName(operator, values); + } + + public TrainingAcademyRequest withNameIsUnknown(){ + return (TrainingAcademyRequest)super.withNameIsUnknown(); + } + + public TrainingAcademyRequest withNameIsKnown(){ + return (TrainingAcademyRequest)super.withNameIsKnown(); + } + + public TrainingAcademyRequest withNameStartingWith(String Name){ + return (TrainingAcademyRequest)super.withNameStartingWith(Name); + } + public TrainingAcademyRequest withNameContaining(String Name){ + return (TrainingAcademyRequest)super.withNameContaining(Name); + } + + public TrainingAcademyRequest withNameEndingWith(String Name){ + return (TrainingAcademyRequest)super.withNameEndingWith(Name); + } + + + public TrainingAcademyRequest filterByStudentCapacity(Integer studentCapacity){ + return (TrainingAcademyRequest)super.filterByStudentCapacity(studentCapacity); + } + + public TrainingAcademyRequest withStudentCapacity(Operator operator, Object... values){ + return (TrainingAcademyRequest)super.withStudentCapacity(operator, values); + } + + public TrainingAcademyRequest withStudentCapacityIsUnknown(){ + return (TrainingAcademyRequest)super.withStudentCapacityIsUnknown(); + } + + public TrainingAcademyRequest withStudentCapacityIsKnown(){ + return (TrainingAcademyRequest)super.withStudentCapacityIsKnown(); + } + + public TrainingAcademyRequest withStudentCapacityGreaterThan(Integer studentCapacity){ + return (TrainingAcademyRequest)super.withStudentCapacityGreaterThan(studentCapacity); + } + + public TrainingAcademyRequest withStudentCapacityGreaterThanOrEqualTo(Integer studentCapacity){ + return (TrainingAcademyRequest)super.withStudentCapacityGreaterThanOrEqualTo(studentCapacity); + } + + public TrainingAcademyRequest withStudentCapacityLessThan(Integer studentCapacity){ + return (TrainingAcademyRequest)super.withStudentCapacityLessThan(studentCapacity); + } + + public TrainingAcademyRequest withStudentCapacityLessThanOrEqualTo(Integer studentCapacity){ + return (TrainingAcademyRequest)super.withStudentCapacityLessThanOrEqualTo(studentCapacity); + } + + public TrainingAcademyRequest withStudentCapacityBetween(Integer startOfStudentCapacity, Integer endOfStudentCapacity){ + return (TrainingAcademyRequest)super.withStudentCapacityBetween(startOfStudentCapacity, endOfStudentCapacity); + } + + + public TrainingAcademyRequest filterByVersion(Long version){ + return (TrainingAcademyRequest)super.filterByVersion(version); + } + + public TrainingAcademyRequest withVersion(Operator operator, Object... values){ + return (TrainingAcademyRequest)super.withVersion(operator, values); + } + + public TrainingAcademyRequest withVersionIsUnknown(){ + return (TrainingAcademyRequest)super.withVersionIsUnknown(); + } + + public TrainingAcademyRequest withVersionIsKnown(){ + return (TrainingAcademyRequest)super.withVersionIsKnown(); + } + + + public TrainingAcademyRequest withIdIs(Long value){ + return (TrainingAcademyRequest)super.withIdIs(value); + } + + public TrainingAcademyRequest withId(Operator operator, Object... values){ + return (TrainingAcademyRequest)super.withId(operator, values); + } + + + public TrainingAcademyRequest count(){ + super.count(); + setPageCountOperation(io.teaql.core.QueryOperation.nativeMethod(io.teaql.core.QueryOperation.Kind.NAMED_COUNT, "count", null, null)); + return this; + } + public TrainingAcademyRequest 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 TrainingAcademyRequest minStudentCapacity(){ + super.minStudentCapacity(); + return this; + } + + public TrainingAcademyRequest minStudentCapacityAs(String retName){ + super.minStudentCapacityAs(retName); + return this; + } + public TrainingAcademyRequest maxStudentCapacity(){ + super.maxStudentCapacity(); + return this; + } + + public TrainingAcademyRequest maxStudentCapacityAs(String retName){ + super.maxStudentCapacityAs(retName); + return this; + } + public TrainingAcademyRequest sumStudentCapacity(){ + super.sumStudentCapacity(); + return this; + } + + public TrainingAcademyRequest sumStudentCapacityAs(String retName){ + super.sumStudentCapacityAs(retName); + return this; + } + public TrainingAcademyRequest avgStudentCapacity(){ + super.avgStudentCapacity(); + return this; + } + + public TrainingAcademyRequest avgStudentCapacityAs(String retName){ + super.avgStudentCapacityAs(retName); + return this; + } + public TrainingAcademyRequest stddevStudentCapacity(){ + super.standardDeviationStudentCapacity(); + return this; + } + + public TrainingAcademyRequest stddevStudentCapacityAs(String retName){ + super.standardDeviationStudentCapacityAs(retName); + return this; + } + public TrainingAcademyRequest stddev_popStudentCapacity(){ + super.squareRootOfPopulationStandardDeviationStudentCapacity(); + return this; + } + + public TrainingAcademyRequest stddev_popStudentCapacityAs(String retName){ + super.squareRootOfPopulationStandardDeviationStudentCapacityAs(retName); + return this; + } + public TrainingAcademyRequest var_sampStudentCapacity(){ + super.sampleVarianceStudentCapacity(); + return this; + } + + public TrainingAcademyRequest var_sampStudentCapacityAs(String retName){ + super.sampleVarianceStudentCapacityAs(retName); + return this; + } + public TrainingAcademyRequest var_popStudentCapacity(){ + super.samplePopulationVarianceStudentCapacity(); + return this; + } + + public TrainingAcademyRequest var_popStudentCapacityAs(String retName){ + super.samplePopulationVarianceStudentCapacityAs(retName); + return this; + } + public TrainingAcademyRequest groupByPlatformWithDetails(){ + super.groupByPlatformWithDetails(); + return this; + } + + public TrainingAcademyRequest groupByPlatformWithDetails(PlatformRequest subRequest){ + super.groupByPlatformWithDetails(subRequest); + return this; + } + + public TrainingAcademyRequest groupBySchoolTypeWithDetails(){ + super.groupBySchoolTypeWithDetails(); + return this; + } + + public TrainingAcademyRequest groupBySchoolTypeWithDetails(SchoolTypeRequest subRequest){ + super.groupBySchoolTypeWithDetails(subRequest); + return this; + } + + + + + + public TrainingAcademyRequest countDistinctSpecialty(){ + return countDistinctSpecialtyAs("specialty_distinct_count"); + } + + public TrainingAcademyRequest countDistinctSpecialtyAs(String alias){ + super.countDistinctProperty(alias, TrainingAcademy.SPECIALTY_PROPERTY); + return this; + } + public TrainingAcademyRequest countDistinctCampusCode(){ + return countDistinctCampusCodeAs("campus_code_distinct_count"); + } + + public TrainingAcademyRequest countDistinctCampusCodeAs(String alias){ + super.countDistinctProperty(alias, TrainingAcademy.CAMPUS_CODE_PROPERTY); + return this; + } + public TrainingAcademyRequest countDistinctPlatform(){ + return countDistinctPlatformAs("platform_distinct_count"); + } + + public TrainingAcademyRequest countDistinctPlatformAs(String alias){ + super.countDistinctProperty(alias, TrainingAcademy.PLATFORM_PROPERTY); + return this; + } + public TrainingAcademyRequest countDistinctSchoolType(){ + return countDistinctSchoolTypeAs("school_type_distinct_count"); + } + + public TrainingAcademyRequest countDistinctSchoolTypeAs(String alias){ + super.countDistinctProperty(alias, TrainingAcademy.SCHOOL_TYPE_PROPERTY); + return this; + } + public TrainingAcademyRequest countDistinctName(){ + return countDistinctNameAs("name_distinct_count"); + } + + public TrainingAcademyRequest countDistinctNameAs(String alias){ + super.countDistinctProperty(alias, TrainingAcademy.NAME_PROPERTY); + return this; + } + public TrainingAcademyRequest countDistinctStudentCapacity(){ + return countDistinctStudentCapacityAs("student_capacity_distinct_count"); + } + + public TrainingAcademyRequest countDistinctStudentCapacityAs(String alias){ + super.countDistinctProperty(alias, TrainingAcademy.STUDENT_CAPACITY_PROPERTY); + return this; + } + public TrainingAcademyRequest countDistinctVersion(){ + return countDistinctVersionAs("version_distinct_count"); + } + + public TrainingAcademyRequest countDistinctVersionAs(String alias){ + super.countDistinctProperty(alias, TrainingAcademy.VERSION_PROPERTY); + return this; + } + public TrainingAcademyRequest countDistinctId(){ + return countDistinctIdAs("id_distinct_count"); + } + + public TrainingAcademyRequest countDistinctIdAs(String alias){ + super.countDistinctProperty(alias, TrainingAcademy.ID_PROPERTY); + return this; + } + + public TrainingAcademyRequest groupBySpecialty(){ + groupBy(TrainingAcademy.SPECIALTY_PROPERTY); + return this; + } + + public TrainingAcademyRequest groupBySpecialtyAs(String retName){ + groupBy(retName, TrainingAcademy.SPECIALTY_PROPERTY); + return this; + } + + public TrainingAcademyRequest groupBySpecialtyWithFunction(String retName, AggrFunction function){ + groupBy(retName, TrainingAcademy.SPECIALTY_PROPERTY, function); + return this; + } + + + public TrainingAcademyRequest groupByCampusCode(){ + super.groupByCampusCode(); + return this; + } + + public TrainingAcademyRequest groupByCampusCodeAs(String retName){ + super.groupByCampusCodeAs(retName); + return this; + } + + public TrainingAcademyRequest groupByCampusCodeWithFunction(String retName, AggrFunction function){ + super.groupByCampusCodeWithFunction(retName, function); + return this; + } + public TrainingAcademyRequest groupByPlatformWith(PlatformRequest subRequest){ + super.groupByPlatformWith(subRequest); + return this; + } + public TrainingAcademyRequest groupByPlatform(){ + super.groupByPlatform(); + return this; + } + + public TrainingAcademyRequest groupByPlatformAs(String retName){ + super.groupByPlatformAs(retName); + return this; + } + + public TrainingAcademyRequest groupByPlatformWithFunction(String retName, AggrFunction function){ + super.groupByPlatformWithFunction(retName, function); + return this; + } + public TrainingAcademyRequest groupBySchoolTypeWith(SchoolTypeRequest subRequest){ + super.groupBySchoolTypeWith(subRequest); + return this; + } + public TrainingAcademyRequest groupBySchoolType(){ + super.groupBySchoolType(); + return this; + } + + public TrainingAcademyRequest groupBySchoolTypeAs(String retName){ + super.groupBySchoolTypeAs(retName); + return this; + } + + public TrainingAcademyRequest groupBySchoolTypeWithFunction(String retName, AggrFunction function){ + super.groupBySchoolTypeWithFunction(retName, function); + return this; + } + + public TrainingAcademyRequest groupByName(){ + super.groupByName(); + return this; + } + + public TrainingAcademyRequest groupByNameAs(String retName){ + super.groupByNameAs(retName); + return this; + } + + public TrainingAcademyRequest groupByNameWithFunction(String retName, AggrFunction function){ + super.groupByNameWithFunction(retName, function); + return this; + } + + public TrainingAcademyRequest groupByStudentCapacity(){ + super.groupByStudentCapacity(); + return this; + } + + public TrainingAcademyRequest groupByStudentCapacityAs(String retName){ + super.groupByStudentCapacityAs(retName); + return this; + } + + public TrainingAcademyRequest groupByStudentCapacityWithFunction(String retName, AggrFunction function){ + super.groupByStudentCapacityWithFunction(retName, function); + return this; + } + + public TrainingAcademyRequest groupByVersion(){ + super.groupByVersion(); + return this; + } + + public TrainingAcademyRequest groupByVersionAs(String retName){ + super.groupByVersionAs(retName); + return this; + } + + public TrainingAcademyRequest groupByVersionWithFunction(String retName, AggrFunction function){ + super.groupByVersionWithFunction(retName, function); + return this; + } + + public TrainingAcademyRequest groupById(){ + super.groupById(); + return this; + } + + public TrainingAcademyRequest groupByIdAs(String retName){ + super.groupByIdAs(retName); + return this; + } + + public TrainingAcademyRequest groupByIdWithFunction(String retName, AggrFunction function){ + super.groupByIdWithFunction(retName, function); + return this; + } + + public TrainingAcademyRequest orderBySpecialtyAscending(){ + addOrderByAscending(TrainingAcademy.SPECIALTY_PROPERTY); + return this; + } + + public TrainingAcademyRequest orderBySpecialtyDescending(){ + addOrderByDescending(TrainingAcademy.SPECIALTY_PROPERTY); + return this; + } + public TrainingAcademyRequest orderBySpecialtyAscendingUsingGBK(){ + addOrderByAscendingUsingGBK(TrainingAcademy.SPECIALTY_PROPERTY); + return this; + } + + public TrainingAcademyRequest orderBySpecialtyDescendingUsingGBK(){ + addOrderByDescendingUsingGBK(TrainingAcademy.SPECIALTY_PROPERTY); + return this; + } + public TrainingAcademyRequest orderByCampusCodeAscending(){ + super.orderByCampusCodeAscending(); + return this; + } + + public TrainingAcademyRequest orderByCampusCodeDescending(){ + super.orderByCampusCodeDescending(); + return this; + } + public TrainingAcademyRequest orderByCampusCodeAscendingUsingGBK(){ + super.orderByCampusCodeAscendingUsingGBK(); + return this; + } + + public TrainingAcademyRequest orderByCampusCodeDescendingUsingGBK(){ + super.orderByCampusCodeDescendingUsingGBK(); + return this; + } + public TrainingAcademyRequest orderByPlatformAscending(){ + super.orderByPlatformAscending(); + return this; + } + + public TrainingAcademyRequest orderByPlatformDescending(){ + super.orderByPlatformDescending(); + return this; + } + + public TrainingAcademyRequest orderBySchoolTypeAscending(){ + super.orderBySchoolTypeAscending(); + return this; + } + + public TrainingAcademyRequest orderBySchoolTypeDescending(){ + super.orderBySchoolTypeDescending(); + return this; + } + + public TrainingAcademyRequest orderByNameAscending(){ + super.orderByNameAscending(); + return this; + } + + public TrainingAcademyRequest orderByNameDescending(){ + super.orderByNameDescending(); + return this; + } + public TrainingAcademyRequest orderByNameAscendingUsingGBK(){ + super.orderByNameAscendingUsingGBK(); + return this; + } + + public TrainingAcademyRequest orderByNameDescendingUsingGBK(){ + super.orderByNameDescendingUsingGBK(); + return this; + } + public TrainingAcademyRequest orderByStudentCapacityAscending(){ + super.orderByStudentCapacityAscending(); + return this; + } + + public TrainingAcademyRequest orderByStudentCapacityDescending(){ + super.orderByStudentCapacityDescending(); + return this; + } + + public TrainingAcademyRequest orderByVersionAscending(){ + super.orderByVersionAscending(); + return this; + } + + public TrainingAcademyRequest orderByVersionDescending(){ + super.orderByVersionDescending(); + return this; + } + + public TrainingAcademyRequest orderByIdAscending(){ + super.orderByIdAscending(); + return this; + } + + public TrainingAcademyRequest orderByIdDescending(){ + super.orderByIdDescending(); + return this; + } + + + + + + /** + * get topN records + * @param topN records number + */ + public TrainingAcademyRequest top(int topN) { + super.top(topN); + return this; + } + + /** Cross-runtime bounded-query alias. */ + public TrainingAcademyRequest limit(int limit) { + return top(limit); + } + + /** + * get records from offset(inclusive) to offset+size(exclusive) + * @param offset record offset + * @param size records number + */ + public TrainingAcademyRequest offset(int offset, int size) { + super.offset(offset, size); + return this; + } + + /** + * retrieve all records + */ + public TrainingAcademyRequest unlimited() { + super.unlimited(); + return this; + } + + /** + * get records of one page + * @param pageNumber page number(1-based) + * @param pageSize page size + */ + public TrainingAcademyRequest 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 TrainingAcademyRequest page(int pageNumber) { + return page(pageNumber, 10); + } +} \ No newline at end of file diff --git a/examples/inheritance-save/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler b/examples/inheritance-save/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler new file mode 100644 index 000000000..7ff0f1b51 --- /dev/null +++ b/examples/inheritance-save/lib/src/main/resources/META-INF/services/io.teaql.core.meta.EntityMetaAssembler @@ -0,0 +1,2 @@ + +com.example.inheritancematchingservice.EntityMetaRegistry \ No newline at end of file diff --git a/examples/inheritance-save/model.xml b/examples/inheritance-save/model.xml new file mode 100644 index 000000000..0e11303a8 --- /dev/null +++ b/examples/inheritance-save/model.xml @@ -0,0 +1,20 @@ + + + + + <_value id="1001" name="Primary" code="PRIMARY"/> + <_value id="1002" name="Secondary" code="SECONDARY"/> + + + + + + diff --git a/examples/inheritance-save/pom.xml b/examples/inheritance-save/pom.xml new file mode 100644 index 000000000..238c7ee43 --- /dev/null +++ b/examples/inheritance-save/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + io.teaqlteaql-java-parent1.557-RELEASE../../pom.xml + io.teaql.examplesinherited-save-example + + com.exampleinheritance-matching-service-core0.0.1-SNAPSHOT + io.teaqlteaql-runtime${teaql.version} + io.teaqlteaql-sqlite${teaql.version} + io.teaqlteaql-postgres${teaql.version} + org.postgresqlpostgresql42.7.3 + junitjunittest + + org.apache.maven.pluginsmaven-surefire-pluginfalse + diff --git a/examples/inheritance-save/src/test/java/io/teaql/examples/inheritance/GraphRollbackProbe.java b/examples/inheritance-save/src/test/java/io/teaql/examples/inheritance/GraphRollbackProbe.java new file mode 100644 index 000000000..51a7894ac --- /dev/null +++ b/examples/inheritance-save/src/test/java/io/teaql/examples/inheritance/GraphRollbackProbe.java @@ -0,0 +1,53 @@ +package io.teaql.examples.inheritance; + +import com.example.inheritancematchingservice.*; +import io.teaql.core.*; +import io.teaql.runtime.SafeAuditEvent; +import java.util.*; +import javax.sql.DataSource; +import static org.junit.Assert.*; + +/** Reject-only, maintainer-approved fixture DDL; business I/O remains Q/E/save. */ +final class GraphRollbackProbe { + static Map verify(UserContext context,long id,List events, + DataSource source,String provider,int round) throws Exception { + if(round==1)try(var connection=source.getConnection();var sql=connection.createStatement()) { + if(provider.equals("sqlite"))sql.execute("CREATE TRIGGER owned_reject_late_school BEFORE UPDATE ON school_data WHEN NEW.name='ROLLBACK_REJECT' BEGIN SELECT CASE WHEN (SELECT name FROM platform_data WHERE id=1)=('Graph root '||NEW.id) THEN RAISE(ABORT,'owned late school fault') ELSE RAISE(ABORT,'owned fault before earlier root write') END; END;"); + else { + sql.execute("CREATE FUNCTION owned_reject_late_school() RETURNS trigger LANGUAGE plpgsql AS $owned$ BEGIN IF NEW.name='ROLLBACK_REJECT' THEN IF (SELECT name FROM platform_data WHERE id=1)=('Graph root '||NEW.id::text) THEN RAISE EXCEPTION 'owned late school fault'; ELSE RAISE EXCEPTION 'owned fault before earlier root write'; END IF; END IF; RETURN NEW; END $owned$"); + sql.execute("CREATE TRIGGER owned_reject_late_school BEFORE UPDATE ON school_data FOR EACH ROW EXECUTE FUNCTION owned_reject_late_school()"); + } + } + var root=Q.platforms().withIdIs(1L) + .selectSchoolListWith(Q.schools().withIdIs(id).limit(1)).limit(1) + .comment("Load the complete graph for transactional fault injection") + .purpose("Verify two logical participants commit through one audited save").executeForOne(context); + assertNotNull(root);assertEquals(Integer.valueOf(1),E.platform(root).getSchoolList().size().eval()); + var child=root.getSchoolList().get(0); + long rootVersion=root.getVersion();String rootName=E.platform(root).getName().eval(); + String childName=E.school(child).getName().eval();assertEquals(Long.valueOf(7),child.getVersion()); + root.updateName("Graph root "+id);child.updateName("ROLLBACK_REJECT"); + child.setComment("Correct the selected child in the shared graph"); + int before=events.size(); + RuntimeException failure=assertThrows(RuntimeException.class,()->root.auditAs("Exercise rollback after an earlier logical participant wrote").save(context)); + boolean late=false;for(Throwable cause=failure;cause!=null;cause=cause.getCause())if(String.valueOf(cause.getMessage()).contains("owned late school fault"))late=true; + assertTrue("The reject-only trigger must observe the earlier root write",late); + assertEquals(before,events.size());assertEquals(Long.valueOf(rootVersion),root.getVersion()); + var persistedRoot=Q.platforms().withIdIs(1L).limit(1).comment("Read the root after child failure") + .purpose("Prove the earlier root write and its version were rolled back").executeForOne(context); + var persistedChild=Q.schools().withIdIs(id).limit(1).comment("Read the child after injected failure") + .purpose("Reject partial graph persistence").executeForOne(context); + assertEquals(Long.valueOf(rootVersion),persistedRoot.getVersion());assertEquals(rootName,E.platform(persistedRoot).getName().eval()); + assertEquals(Long.valueOf(7),persistedChild.getVersion());assertEquals(childName,E.school(persistedChild).getName().eval()); + assertTrue(child.getUpdatedProperties().contains("name")); + child.updateName("Graph child "+id); + root.auditAs("Retry the same graph after correcting the rejected child").save(context); + assertEquals(Long.valueOf(rootVersion+1),root.getVersion()); + var retried=Q.schools().withIdIs(id).limit(1).comment("Read the retried graph child") + .purpose("Verify retained ledger intent commits only once").executeForOne(context); + assertEquals(Long.valueOf(8),retried.getVersion());assertEquals("Graph child "+id,E.school(retried).getName().eval()); + assertEquals(before+2,events.size()); + return Map.of("passed",true,"id",id,"rootVersionBefore",rootVersion,"rootVersionAfter",root.getVersion(), + "childVersionAfter",8,"failedAudits",0,"retryAudits",2,"generatedQAndE",true,"retrySameGraph",true); + } +} diff --git a/examples/inheritance-save/src/test/java/io/teaql/examples/inheritance/InheritanceLifecycleExampleTest.java b/examples/inheritance-save/src/test/java/io/teaql/examples/inheritance/InheritanceLifecycleExampleTest.java new file mode 100644 index 000000000..6220e3fe5 --- /dev/null +++ b/examples/inheritance-save/src/test/java/io/teaql/examples/inheritance/InheritanceLifecycleExampleTest.java @@ -0,0 +1,225 @@ +package io.teaql.examples.inheritance; + +import com.example.inheritancematchingservice.*; +import com.example.inheritancematchingservice.academy.Academy; +import com.example.inheritancematchingservice.school.School; +import io.teaql.core.*; +import io.teaql.core.meta.SimpleEntityMetaFactory; +import io.teaql.core.sqlite.SingleConnectionDataSource; +import io.teaql.core.sqlite.SqliteDataServiceExecutor; +import io.teaql.core.postgres.PostgresDataServiceExecutor; +import io.teaql.provider.jdbc.JdbcSqlExecutor; +import io.teaql.runtime.*; +import java.nio.file.Path; +import java.util.*; +import org.junit.Test; +import static org.junit.Assert.*; + +/** Same natural-save lifecycle as the Rust example; never inserts a parent row. */ +public class InheritanceLifecycleExampleTest { + private static final class FixtureIds implements InternalIdGenerationService { + long next = 10000; + @Override public Long generateId(UserContext context, Entity entity) { return next++; } + @Override public long nextId(String type) { return next++; } + @Override public void ensureFloor(String type, long floor) { next = Math.max(next, floor + 1); } + } + + private static T save(T entity, UserContext context, String comment) { + return entity.auditAs(comment).save(context); + } + + private static Academy child(UserContext context, long id) { + return Q.academies().withIdIs(id).limit(1).comment("Load one complete inherited object") + .purpose("Verify the shared lifecycle through the typed child view").executeForOne(context); + } + + private static School parent(UserContext context, long id) { + return Q.schools().withIdIs(id).limit(1).comment("Load one complete parent view") + .purpose("Verify inherited values and the authoritative root version").executeForOne(context); + } + + @Test public void naturalLifecycleThroughGenericAuditedSave() throws Exception { + String provider = System.getProperty("teaql.inheritance.provider", "sqlite"); + int round = Integer.parseInt(System.getProperty("teaql.inheritance.round")); + assertTrue(Set.of("sqlite", "postgres").contains(provider)); + for (var component : List.of(BaseRequest.class, TeaQLRuntime.class, JdbcSqlExecutor.class)) + assertTrue(component.getName(), Path.of(component.getProtectionDomain().getCodeSource().getLocation().toURI()).toRealPath() + .startsWith(Path.of(System.getProperty("teaql.expected.runtime.root")).toRealPath())); + assertTrue(Path.of(Q.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toRealPath() + .startsWith(Path.of(System.getProperty("teaql.expected.inheritance.root")).toRealPath())); + SingleConnectionDataSource sqlite = provider.equals("sqlite") ? new SingleConnectionDataSource( + "jdbc:sqlite:" + System.getProperty("teaql.inheritance.database")) : null; + try { + javax.sql.DataSource source = sqlite; + if (provider.equals("postgres")) { + var pg = new org.postgresql.ds.PGSimpleDataSource(); + pg.setURL(System.getenv("TEAQL_TEST_INHERITANCE_JDBC_URL")); + pg.setUser(System.getenv("TEAQL_TEST_POSTGRES_USER")); + pg.setPassword(System.getenv("TEAQL_TEST_POSTGRES_PASSWORD")); source = pg; + } + assertNotNull(source); + var driver = new JdbcSqlExecutor(source); var ids = new FixtureIds(); + MutationPolicy observer = new MutationPolicy() { + public MutationPolicyIdentity identity() { return new MutationPolicyIdentity("inheritance-example","1","source-fixture"); } + public MutationDecision review(UserContext ignored, MutationPlan plan) { + if ("Recover and correct both declaring tables atomically".equals(plan.auditReason())) { + assertEquals(1,plan.operations().size()); + assertEquals(MutationOperationKind.RECOVER,plan.operations().get(0).kind()); + assertEquals("Corrected recovered academy",plan.operations().get(0).changedValues().get("name")); + assertEquals("WEST",plan.operations().get(0).changedValues().get("campus_code")); + } + return MutationDecision.allow(); + } + }; + var runtime = TeaQLRuntime.builder().metadata(new SimpleEntityMetaFactory()) + .dataService("default", provider.equals("sqlite") + ? new SqliteDataServiceExecutor("default", driver, source) + : new PostgresDataServiceExecutor("default", driver)) + .idGenerationService(ids).mutationPolicyRegistry(key -> Optional.of(observer)).build().install(GeneratedRuntimeModule.module()); + UserContext context = new DefaultUserContext(runtime); + context.ensureSchema(); context.ensureSchema(); + var auditEvents = new ArrayList(); + context.putAttribute(AppAuditEventSink.class.getName(),(AppAuditEventSink)(ignored,event)->auditEvents.add(event)); + // Deliberately collide only the numeric ID with a constant entity. + ids.next = 1000 + round; + var platform = Q.platformsWithMinimalFields().withIdIs(1L).limit(1) + .comment("Reuse the provisioned root").purpose("Never seed a second Platform").executeForOne(context); + var academy = Q.academies().comment("Create a subtype without manually materializing its parent") + .purpose("Compare Java and Rust inherited audited persistence").newEntity(context); + academy.updatePlatform(platform); academy.updateSchoolTypeToPrimary(); + academy.updateName("Natural inheritance academy"); academy.updateStudentCapacity(20); + academy.updateCampusCode("NORTH"); + School genericView = academy; + var saved = save(genericView, context, "Create one inherited object through a generic save"); + assertSame(academy, saved); assertEquals(Academy.class, saved.getClass()); + long id = saved.getId(); assertEquals(Long.valueOf(1), saved.getVersion()); + assertNotNull(parent(context, id)); + assertEquals("Natural inheritance academy", E.academy(child(context,id)).getName().eval()); + assertEquals(Long.valueOf(1), save(academy,context,"Save unchanged inherited state").getVersion()); + var partial = Q.academiesWithMinimalFields().withIdIs(id).selectName().limit(1) + .comment("Load only the name for a negative mutation case") + .purpose("Reject changed incomplete mutation targets").executeForOne(context); + partial.updateName("Incomplete write must be rejected"); + assertThrows(RuntimeException.class, () -> save(partial,context,"Reject a partial inherited mutation")); + var current = child(context,id); var stale = child(context,id); + current.updateName("Updated inherited academy"); current.updateCampusCode("SOUTH"); + assertEquals(Long.valueOf(2),save(current,context,"Update ancestor and local fields together").getVersion()); + stale.updateCampusCode("STALE"); + assertThrows(RuntimeException.class, () -> save(stale,context,"Reject an independent stale view")); + var root = parent(context,id); assertEquals(Long.valueOf(2),root.getVersion()); + assertEquals("Updated inherited academy",E.school(root).getName().eval()); + assertEquals(School.class,root.getClass()); + assertEquals("Academy",root.runtimeType()); + assertSame(root,save(root,context,"Keep an unchanged parent view without losing its subtype")); + assertEquals(Long.valueOf(2),root.getVersion()); + assertEquals("Academy",root.runtimeType()); + root.updateName("Parent edited academy"); + assertEquals(Long.valueOf(3),save(root,context,"Edit inherited state through its parent").getVersion()); + assertEquals("Academy", root.runtimeType()); + var reloaded = child(context,id); assertEquals(Long.valueOf(3),reloaded.getVersion()); + assertEquals("Parent edited academy",E.academy(reloaded).getName().eval()); + assertEquals("SOUTH",reloaded.getCampusCode()); + reloaded.markForDeletion(); + assertEquals(Long.valueOf(-4),save(reloaded,context,"Mark the subtype for deletion and save").getVersion()); + assertNull(child(context,id)); assertNull(parent(context,id)); + var deleted = Q.academies().deletedRowsOnly().withIdIs(id).limit(1) + .comment("Read the retained inherited tombstone") + .purpose("Verify deletion is root-owned and not physical row removal").executeForOne(context); + assertNotNull(deleted); assertEquals(Long.valueOf(-4),deleted.getVersion()); + assertEquals("Parent edited academy",E.academy(deleted).getName().eval()); + assertEquals("Academy", deleted.runtimeType()); + var staleDeleted = Q.academies().deletedRowsOnly().withIdIs(id).limit(1) + .comment("Read an independent tombstone before recovery") + .purpose("Reject obsolete negative versions without shared ledgers").executeForOne(context); + var partialRecovery=Q.academiesWithMinimalFields().deletedRowsOnly().withIdIs(id).selectName().limit(1) + .comment("Load an intentionally incomplete recovery target") + .purpose("Reject recovery without loading the complete object").executeForOne(context); + partialRecovery.markToRecover(); + int beforeRejected=auditEvents.size(); + assertThrows(RuntimeException.class,()->save(partialRecovery,context,"Reject incomplete recovery")); + assertEquals(beforeRejected,auditEvents.size()); + deleted.markToRecover(); + var recovered = save(deleted,context,"Recover without inventing a scalar edit"); + assertEquals(Long.valueOf(5),recovered.getVersion()); + assertEquals("Academy",recovered.runtimeType()); + assertEquals(Long.valueOf(5),child(context,id).getVersion()); + assertEquals(Long.valueOf(5),parent(context,id).getVersion()); + staleDeleted.markToRecover(); + assertThrows(RuntimeException.class,()->save(staleDeleted,context,"Reject obsolete recovery version")); + recovered.markForDeletion(); + assertEquals(Long.valueOf(-6),save(recovered,context,"Delete before recovery with edits").getVersion()); + var editedRecovery = Q.academies().deletedRowsOnly().withIdIs(id).limit(1) + .comment("Load a complete tombstone for correction and recovery") + .purpose("Commit ancestor and child edits with one recovery version").executeForOne(context); + editedRecovery.markToRecover(); + editedRecovery.updateName("Corrected recovered academy"); + editedRecovery.updateCampusCode("WEST"); + assertTrue(editedRecovery.getUpdatedProperties().containsAll(List.of("name","campus_code"))); + var corrected = save(editedRecovery,context,"Recover and correct both declaring tables atomically"); + assertEquals(Long.valueOf(7),corrected.getVersion()); + assertEquals("Corrected recovered academy",E.academy(child(context,id)).getName().eval()); + assertEquals("WEST",child(context,id).getCampusCode()); + assertEquals("Corrected recovered academy",E.school(parent(context,id)).getName().eval()); + assertEquals(Long.valueOf(7),parent(context,id).getVersion()); + var live=child(context,id); + int beforeLiveRejection=auditEvents.size(); + assertThrows(RuntimeException.class,()->{live.markToRecover();save(live,context,"Reject recovery of a live object");}); + assertEquals(beforeLiveRejection,auditEvents.size()); + var recoveryAudits=auditEvents.stream().filter(event->event.kind()==MutationAuditKind.RECOVERED && event.entityType().equals("Academy") && Objects.equals(event.entityId(),id)).toList(); + assertEquals(2,recoveryAudits.size()); + for(var event:recoveryAudits)assertTrue(event.traceChain().stream().anyMatch(node->node.getKind()==TraceKind.AUDIT_REASON && !node.getComment().isBlank())); + assertTrue(recoveryAudits.get(1).fields().stream().anyMatch(field->field.name().equals("campus_code"))); + assertTrue(recoveryAudits.get(1).fields().stream().anyMatch(field->field.name().equals("name"))); + var rollback=GraphRollbackProbe.verify(context,id,auditEvents,source,provider,round); + var constant = Q.schoolTypes().withIdIs(id).limit(1).comment("Read an unrelated type at the same numeric ID") + .purpose("Reject optimistic-version reuse across distinct entity families").executeForOne(context); + assertNotNull(constant); assertEquals(Long.valueOf(1),constant.getVersion()); + var subtypeViews = new ArrayList>(); + subtypeViews.add(List.of(root.getClass().getSimpleName(), "Academy", root.runtimeType())); + ids.next = 2000 + round; + var training = Q.trainingAcademies().comment("Create a grandchild for typed-view identity checks") + .purpose("Compare the same three-level inheritance semantics").newEntity(context); + training.updatePlatform(platform); training.updateSchoolTypeToPrimary(); training.updateName("Training Robotics"); + training.updateStudentCapacity(80); training.updateCampusCode("NORTH"); training.updateSpecialty("robotics"); + save(training,context,"Create one most-derived training academy"); + var trainingRoot = parent(context,training.getId()); var trainingMiddle = child(context,training.getId()); + assertEquals(School.class,trainingRoot.getClass()); assertEquals("Academy",trainingRoot.runtimeType()); + assertEquals(Academy.class,trainingMiddle.getClass()); assertEquals("TrainingAcademy",trainingMiddle.runtimeType()); + subtypeViews.add(List.of(trainingRoot.getClass().getSimpleName(), "TrainingAcademy", trainingRoot.runtimeType())); + subtypeViews.add(List.of(trainingMiddle.getClass().getSimpleName(), "TrainingAcademy", trainingMiddle.runtimeType())); + var leaf = Q.trainingAcademiesWithMinimalFields().withIdIs(training.getId()).selectName().limit(1) + .comment("Read a minimal leaf view").purpose("Keep the leaf type without an implicit cast").executeForOne(context); + assertEquals("TrainingAcademy",leaf.runtimeType()); + subtypeViews.add(List.of(leaf.getClass().getSimpleName(), "TrainingAcademy", leaf.runtimeType())); + var minimal = Q.schoolsWithMinimalFields().withIdIs(training.getId()).selectName().limit(1) + .comment("Read a minimal parent view").purpose("Retain subtype information without loading child fields").executeForOne(context); + assertEquals("Academy",minimal.runtimeType()); assertEquals(School.class,minimal.getClass()); + try (var stream = Q.schoolsWithMinimalFields().withIdIs(training.getId()).selectName().limit(1) + .comment("Stream one typed parent view").purpose("Match list and stream subtype metadata").executeForStream(context)) { + var streamed = stream.toList(); assertEquals(1,streamed.size()); + assertEquals(School.class,streamed.get(0).getClass()); assertEquals("Academy",streamed.get(0).runtimeType()); + } + ids.next = 3000 + round; + var college = Q.colleges().comment("Create a sibling subtype").purpose("Keep sibling branch identities distinct").newEntity(context); + college.updatePlatform(platform); college.updateSchoolTypeToPrimary(); college.updateName("College Arts"); + college.updateStudentCapacity(60); college.updateDegreeLevel("arts");save(college,context,"Create the sibling branch"); + var sibling = parent(context,college.getId()); assertEquals("College",sibling.runtimeType()); + subtypeViews.add(List.of(sibling.getClass().getSimpleName(), "College", sibling.runtimeType())); + ids.next = 4000 + round; + var base = Q.schools().comment("Create a base object without a child branch").purpose("Keep base identity when no subtype exists").newEntity(context); + base.updatePlatform(platform); base.updateSchoolTypeToPrimary(); base.updateName("Base School");base.updateStudentCapacity(100); + save(base,context,"Create one plain parent object");var baseView = parent(context,base.getId()); + assertEquals("School",baseView.runtimeType());subtypeViews.add(List.of(baseView.getClass().getSimpleName(),"School",baseView.runtimeType())); + var proof = new LinkedHashMap(); + proof.put("passed",true); proof.put("provider",provider); proof.put("round",round); proof.put("id",id); + proof.put("caseCount",17); proof.put("versions",List.of(1,2,3,-4,5,-6,7,8)); proof.put("manualParentSeed",false); + proof.put("genericSavePreservesType",true); proof.put("sameIdOtherTypeUnchanged",true); + proof.put("typedViewSubtypeMetadata",true); proof.put("subtypeViews",subtypeViews); + proof.put("parentNoopSubtypeRetained",true); + proof.put("recoveryWithoutScalarEdit",true);proof.put("recoveryWithEdits",true);proof.put("staleRecoveryRejected",true); + proof.put("partialRecoveryRejected",true);proof.put("liveRecoveryRejected",true);proof.put("recoveryAuditLineage",true); + proof.put("mixedGraphRollback",true);proof.put("retrySameGraph",true);proof.put("rollback",rollback); + System.out.println("INHERITED_SAVE_PARITY="+new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(proof)); + } finally { if(sqlite!=null) sqlite.close(); } + } +} diff --git a/examples/inheritance-save/teaql/checker-model.json b/examples/inheritance-save/teaql/checker-model.json new file mode 100644 index 000000000..4903f3d90 --- /dev/null +++ b/examples/inheritance-save/teaql/checker-model.json @@ -0,0 +1 @@ +{"schema":"teaql.checker-model/v1","revision":"sha256:43a0ab45b8baa27dfb7d9eccaf6f8ac33e36491d16f13a7817729d8673c0b53a","entities":{"Academy":{"labels":{"en":"Academy"},"fields":[{"name":"campus_code","labels":{"en":"campus code"},"aliases":["CampusCode","campusCode"]},{"name":"id","labels":{"en":"id"},"aliases":["Id"]}]},"College":{"labels":{"en":"College"},"fields":[{"name":"degree_level","labels":{"en":"degree level"},"aliases":["DegreeLevel","degreeLevel"]},{"name":"id","labels":{"en":"id"},"aliases":["Id"]}]},"Platform":{"labels":{"en":"Platform"},"fields":[{"name":"base_url","labels":{"en":"base url"},"aliases":["BaseUrl","baseUrl"]},{"name":"id","labels":{"en":"id"},"aliases":["Id"]},{"name":"name","labels":{"en":"name"},"aliases":["Name"]},{"name":"school_list","targetType":"School","labels":{"en":"School"},"aliases":["SchoolList","schoolList"]},{"name":"school_type_list","targetType":"SchoolType","labels":{"en":"School Type"},"aliases":["SchoolTypeList","schoolTypeList"]},{"name":"version","labels":{"en":"version"},"aliases":["Version"]}]},"School":{"labels":{"en":"School"},"fields":[{"name":"id","labels":{"en":"id"},"aliases":["Id"]},{"name":"name","labels":{"en":"name"},"aliases":["Name"]},{"name":"platform","targetType":"Platform","labels":{"en":"Platform"},"aliases":["Platform"]},{"name":"school_type","targetType":"SchoolType","labels":{"en":"School Type"},"aliases":["SchoolType","schoolType"]},{"name":"student_capacity","labels":{"en":"student capacity"},"aliases":["StudentCapacity","studentCapacity"]},{"name":"version","labels":{"en":"version"},"aliases":["Version"]}]},"SchoolType":{"labels":{"en":"School Type"},"fields":[{"name":"code","labels":{"en":"code"},"aliases":["Code"]},{"name":"id","labels":{"en":"id"},"aliases":["Id"]},{"name":"name","labels":{"en":"name"},"aliases":["Name"]},{"name":"platform","targetType":"Platform","labels":{"en":"Platform"},"aliases":["Platform"]},{"name":"school_list","targetType":"School","labels":{"en":"School"},"aliases":["SchoolList","schoolList"]},{"name":"version","labels":{"en":"version"},"aliases":["Version"]}]},"TrainingAcademy":{"labels":{"en":"Training Academy"},"fields":[{"name":"id","labels":{"en":"id"},"aliases":["Id"]},{"name":"specialty","labels":{"en":"specialty"},"aliases":["Specialty"]}]}}} \ No newline at end of file diff --git a/examples/inheritance-save/teaql/model-provenance.json b/examples/inheritance-save/teaql/model-provenance.json new file mode 100644 index 000000000..05f68038c --- /dev/null +++ b/examples/inheritance-save/teaql/model-provenance.json @@ -0,0 +1 @@ +{"schemaVersion":1,"modelUuid":null,"revisionHash":null,"generatorVersion":"unknown"} \ No newline at end of file diff --git a/examples/inheritance-save/verify.cjs b/examples/inheritance-save/verify.cjs new file mode 100644 index 000000000..d96979aca --- /dev/null +++ b/examples/inheritance-save/verify.cjs @@ -0,0 +1,134 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),cp=require('node:child_process'); +const crypto=require('node:crypto'),assert=require('node:assert/strict'); +const {createOwnedRunner,ownedBytes}=require('../fix-e-alignment/owned-command.cjs'); +const sha=bytes=>crypto.createHash('sha256').update(bytes).digest('hex'); +const repo=path.resolve(__dirname,'../..'); +async function main(){ + const args={};for(let i=2;ifs.existsSync(path.join(repo,name,'pom.xml'))).map(name=>path.join(repo,name,'target')); + targets.push(path.join(__dirname,'target'),path.join(__dirname,'lib/target')); + assert(targets.every(file=>!fs.existsSync(file)),'Use an isolated target-free runtime checkout'); + assert(fs.statfsSync(repo).bavail*fs.statfsSync(repo).bsize>4*1024**3); + fs.mkdirSync(output,{recursive:true});const runner=createOwnedRunner();let scratch,owned=false; + const receipt={schema:'teaql.java-inherited-save-parity/v1',passed:false,publication:false,provider,commands:[],rounds:[]}; + try{ + scratch=fs.mkdtempSync(path.join(os.tmpdir(),'teaql-java-inheritance-'));owned=true; + const generated=JSON.parse(fs.readFileSync(path.join(__dirname,'generated-files.json'))); + const inventory=()=>Object.fromEntries(Object.keys(generated).map(name=>[name,sha(fs.readFileSync(path.join(__dirname,name)))])); + assert.deepEqual(inventory(),generated);receipt.generatedFileHashes=generated; + receipt.sourceCommit=cp.execFileSync('git',['rev-parse','HEAD'],{cwd:repo,encoding:'utf8'}).trim(); + const sources=['pom.xml','teaql-core/src/main/java/io/teaql/core/Entity.java','teaql-core/src/main/java/io/teaql/core/Audited.java', + 'teaql-core/src/main/java/io/teaql/core/BaseEntity.java','teaql-core/src/main/java/io/teaql/core/checker/Checker.java', + 'teaql-core/src/main/java/io/teaql/core/EntityStatus.java','teaql-core/src/test/java/io/teaql/core/EntityMutationLedgerTest.java', + 'teaql-runtime/src/main/java/io/teaql/runtime/TeaQLRuntime.java','teaql-runtime/src/test/java/io/teaql/runtime/TeaQLRuntimeTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/PortableSQLRepository.java','teaql-sql-portable/src/main/java/io/teaql/core/sql/SqlAstCompiler.java', + 'examples/fix-e-alignment/owned-command.cjs','examples/inheritance-save/pom.xml','examples/inheritance-save/verify.cjs', + 'examples/inheritance-save/src/test/java/io/teaql/examples/inheritance/InheritanceLifecycleExampleTest.java']; + sources.push('examples/inheritance-save/src/test/java/io/teaql/examples/inheritance/GraphRollbackProbe.java'); + sources.push('teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/PortableSQLDataService.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/VersionLifecyclePortableSQLTest.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/SqlParameterPropagationTest.java', + 'teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/IdSpaceIdGenerator.java', + 'teaql-sql-portable/src/test/java/io/teaql/core/sql/portable/IdSpaceIdGeneratorTest.java'); + const sourceHashes=()=>Object.fromEntries(sources.map(name=>[name,sha(fs.readFileSync(path.join(repo,name)))])); + receipt.sourceHashes=sourceHashes(); + const version=fs.readFileSync(path.join(repo,'pom.xml'),'utf8').match(/([^<]+)<\/version>/)[1]; + receipt.localSourceVersionOverride=version; + const escape=value=>value.replaceAll('&','&').replaceAll('<','<').replaceAll('"','"'); + const reactor='4.0.0io.teaql.testinherited-save-reactor0.0.0pom' + +[repo,path.join(__dirname,'lib'),__dirname].map(dir=>''+escape(path.relative(scratch,dir))+'').join('')+''; + fs.writeFileSync(path.join(scratch,'pom.xml'),reactor);fs.writeFileSync(path.join(output,'reactor-pom.xml'),reactor); + const env={...process.env,TEAQL_TELEMETRY_ENABLED:'false'}; + async function run(command,log){const fd=fs.openSync(path.join(output,log),'wx');let result; + try{result=await runner.run(command,{cwd:repo,env,timeout:900000,stdio:['ignore',fd,fd]});}finally{fs.closeSync(fd);} + const bytes=fs.readFileSync(path.join(output,log));receipt.commands.push({command,log,exitCode:result.status,signal:result.signal,logSha256:sha(bytes)}); + assert.equal(result.status,0,bytes.toString().slice(-7000));return bytes.toString(); + } + let pgSql; + if(provider==='postgres'){ + const container=args['--postgres-container'],port=Number(args['--postgres-port']); + assert(container&&/^[a-zA-Z0-9_-]+$/.test(container));assert(Number.isInteger(port)&&port>0&&port<65536); + const database='teaql_java_inherited_280_'+sha(Buffer.from(output)).slice(0,12); + const sql=(db,statement)=>cp.execFileSync('docker',['exec','-i','-u','postgres',container,'psql','-X','-v','ON_ERROR_STOP=1','-At','-d',db],{input:statement,encoding:'utf8',stdio:['pipe','pipe','pipe']}).trim(); + assert.equal(sql('postgres',"SELECT count(*) FROM pg_database WHERE datname='"+database+"';"),'0','Never reuse an unexpected database'); + sql('postgres','CREATE DATABASE '+database+';');sql('postgres',"COMMENT ON DATABASE "+database+" IS 'TeaQL #280 owned inheritance parity fixture';"); + const password=cp.execFileSync('docker',['exec',container,'sh','-c','printf %s "$POSTGRES_PASSWORD"'],{encoding:'utf8',stdio:['ignore','pipe','pipe']});assert(password); + env.TEAQL_TEST_INHERITANCE_JDBC_URL='jdbc:postgresql://127.0.0.1:'+port+'/'+database;env.TEAQL_TEST_POSTGRES_USER='postgres';env.TEAQL_TEST_POSTGRES_PASSWORD=password; + receipt.database={name:database,container,port,created:true,retained:true,ownership:'TeaQL #280 owned inheritance parity fixture'}; + pgSql=statement=>sql(database,statement); + } + for(const round of [1,2]){ + const log=await run([process.env.MAVEN||'mvn','-o','-B','-ntp','-f',path.join(scratch,'pom.xml'),'-pl',':inherited-save-example','-am', + '-Dteaql.version='+version,'-Dtest=InheritanceLifecycleExampleTest','-Dsurefire.failIfNoSpecifiedTests=false', + '-Dteaql.expected.runtime.root='+repo,'-Dteaql.expected.inheritance.root='+path.join(__dirname,'lib'), + '-Dteaql.inheritance.provider='+provider,'-Dteaql.inheritance.round='+round, + '-Dteaql.inheritance.database='+path.join(output,'inheritance.sqlite'),'test'],'round-'+round+'.log'); + const lines=log.split('\n').filter(line=>line.startsWith('INHERITED_SAVE_PARITY='));assert.equal(lines.length,1); + const proof=JSON.parse(lines[0].slice('INHERITED_SAVE_PARITY='.length));assert.equal(proof.passed,true);assert.equal(proof.round,round);assert.equal(proof.manualParentSeed,false); + assert.deepEqual(proof.versions,[1,2,3,-4,5,-6,7,8]);assert.equal(proof.genericSavePreservesType,true);assert.equal(proof.sameIdOtherTypeUnchanged,true); + for(const key of ['recoveryWithoutScalarEdit','recoveryWithEdits','staleRecoveryRejected'])assert.equal(proof[key],true,key); + for(const key of ['partialRecoveryRejected','liveRecoveryRejected','recoveryAuditLineage','mixedGraphRollback','retrySameGraph'])assert.equal(proof[key],true,key); + assert.equal(proof.rollback.passed,true);assert.equal(proof.rollback.retrySameGraph,true);assert.equal(proof.rollback.failedAudits,0);assert.equal(proof.rollback.retryAudits,2); + assert.equal(proof.typedViewSubtypeMetadata,true); + assert.equal(proof.parentNoopSubtypeRetained,true); + assert.deepEqual(proof.subtypeViews,[['School','Academy','Academy'],['School','TrainingAcademy','Academy'], + ['Academy','TrainingAcademy','TrainingAcademy'],['TrainingAcademy','TrainingAcademy','TrainingAcademy'], + ['School','College','College'],['School','School','School']]); + receipt.rounds.push(proof); + const report=path.join(__dirname,'target/surefire-reports/TEST-io.teaql.examples.inheritance.InheritanceLifecycleExampleTest.xml'); + const xml=fs.readFileSync(report,'utf8');for(const key of ['failures','errors','skipped'])assert.equal(Number(xml.match(new RegExp('\\b'+key+'="(\\d+)"'))[1]),0); + fs.copyFileSync(report,path.join(output,'junit-'+round+'.xml')); + } + await run([process.env.MAVEN||'mvn','-o','-B','-ntp','-pl','teaql-runtime','-am', + '-Dtest=AuditedTest,EntityMutationLedgerTest,TeaQLRuntimeTest','-Dsurefire.failIfNoSpecifiedTests=false','test'],'native-view-dispatch.log'); + for(const [module,name] of [['teaql-core','io.teaql.core.AuditedTest'],['teaql-core','io.teaql.core.EntityMutationLedgerTest'],['teaql-runtime','io.teaql.runtime.TeaQLRuntimeTest']]){ + const report=path.join(repo,module,'target/surefire-reports/TEST-'+name+'.xml');const xml=fs.readFileSync(report,'utf8'); + assert(Number(xml.match(/\btests="(\d+)"/)[1])>0); + for(const key of ['failures','errors','skipped'])assert.equal(Number(xml.match(new RegExp('\\b'+key+'="(\\d+)"'))[1]),0); + fs.copyFileSync(report,path.join(output,'junit-'+name+'.xml')); + } + await run([process.env.MAVEN||'mvn','-o','-B','-ntp','-pl','teaql-sql-portable','-am', + '-Dtest=VersionLifecyclePortableSQLTest,SqlParameterPropagationTest,IdSpaceIdGeneratorTest','-Dsurefire.failIfNoSpecifiedTests=false','test'],'native-recovery-provider.log'); + for(const name of ['VersionLifecyclePortableSQLTest','SqlParameterPropagationTest','IdSpaceIdGeneratorTest']){ + const report=path.join(repo,'teaql-sql-portable/target/surefire-reports/TEST-io.teaql.core.sql.portable.'+name+'.xml');const xml=fs.readFileSync(report,'utf8'); + assert(Number(xml.match(/\btests="(\d+)"/)[1])>0); + for(const key of ['failures','errors','skipped'])assert.equal(Number(xml.match(new RegExp('\\b'+key+'="(\\d+)"'))[1]),0); + fs.copyFileSync(report,path.join(output,'junit-'+name+'.xml')); + } + // Independent, read-only storage oracle; the application never uses SQL to + // create a parent, repair a discriminator, or conceal failed persistence. + const parentQuery='SELECT id,version FROM school_data ORDER BY id'; + const childQuery='SELECT a.id,s.version,a."Legacy Campus Code" FROM academy_data a JOIN school_data s ON s.id=a.id ORDER BY a.id'; + const constantQuery='SELECT id,version FROM school_type_data ORDER BY id'; + if(provider==='sqlite'){ + const python='import sqlite3,sys,pathlib,json; c=sqlite3.connect(pathlib.Path(sys.argv[1]).resolve().as_uri()+"?mode=ro",uri=True); r={"parents":c.execute(sys.argv[2]).fetchall(),"children":c.execute(sys.argv[3]).fetchall(),"constants":c.execute(sys.argv[4]).fetchall(),"childColumns":[x[1] for x in c.execute("PRAGMA table_info(academy_data)")]}; c.close(); print(json.dumps(r))'; + receipt.oracle=JSON.parse(await run(['python3','-B','-c',python,path.join(output,'inheritance.sqlite'),parentQuery,childQuery,constantQuery],'oracle.log')); + }else{ + const rows=query=>JSON.parse(pgSql("BEGIN READ ONLY; SELECT coalesce(jsonb_agg(to_jsonb(t)),'[]'::jsonb)::text FROM ("+query+") t; COMMIT;").split('\n').find(line=>line.startsWith('['))); + receipt.oracle={parents:rows(parentQuery).map(x=>[x.id,x.version]),children:rows(childQuery).map(x=>[x.id,x.version,x['Legacy Campus Code']]), + constants:rows(constantQuery).map(x=>[x.id,x.version]),childColumns:rows("SELECT column_name FROM information_schema.columns WHERE table_schema='public' AND table_name='academy_data' ORDER BY ordinal_position").map(x=>x.column_name)}; + fs.writeFileSync(path.join(output,'oracle.log'),JSON.stringify(receipt.oracle,null,2)+'\n'); + } + assert.deepEqual(receipt.oracle.parents,[[1001,8],[1002,8],[2001,1],[2002,1],[3001,1],[3002,1],[4001,1],[4002,1]]); + assert.deepEqual(receipt.oracle.children,[[1001,8,'WEST'],[1002,8,'WEST'],[2001,1,'NORTH'],[2002,1,'NORTH']]); + assert.deepEqual(receipt.oracle.constants,[[1001,1],[1002,1]]);assert(!receipt.oracle.childColumns.includes('version')); + receipt.independentReadOnlyOracle=true; + assert.deepEqual(inventory(),generated);receipt.generatedLibraryUnchanged=true;assert.deepEqual(sourceHashes(),receipt.sourceHashes);receipt.sameDatabase=true;receipt.passed=true; + }catch(error){receipt.error=String(error);process.exitCode=1;} + finally{ + if(owned&&runner.safeToClean){const reports=path.join(__dirname,'target/surefire-reports');if(fs.existsSync(reports)){ + fs.mkdirSync(path.join(output,'last-junit'),{recursive:true}); + for(const file of fs.readdirSync(reports))if(/\.(xml|txt)$/.test(file))fs.copyFileSync(path.join(reports,file),path.join(output,'last-junit',file)); + }} + receipt.disposableBytesRemoved=0; + if(runner.safeToClean&&owned){for(const dir of [...targets,scratch])if(fs.existsSync(dir)){receipt.disposableBytesRemoved+=ownedBytes(dir);fs.rmSync(dir,{recursive:true});}} + else if(scratch)receipt.unsafeRetention={scratch,targets,processGroup:runner.unsafeGroup}; + runner.dispose();receipt.scratchRemoved=!scratch||!fs.existsSync(scratch); + fs.writeFileSync(path.join(output,'receipt.json'),JSON.stringify(receipt,null,2)+'\n'); + console.log(JSON.stringify({passed:receipt.passed,evidence:output,error:receipt.error?.slice(-1500),scratchRemoved:receipt.scratchRemoved,disposableBytesRemoved:receipt.disposableBytesRemoved})); + } +} +main().catch(error=>{console.error(error);process.exitCode=1;}); diff --git a/examples/object-storage/pom.xml b/examples/object-storage/pom.xml index f5a1cfec4..7c082fe5f 100644 --- a/examples/object-storage/pom.xml +++ b/examples/object-storage/pom.xml @@ -1,6 +1,6 @@ 4.0.0 - io.teaqlteaql-java-parent1.556-RELEASE../../pom.xml + io.teaqlteaql-java-parent1.557-RELEASE../../pom.xml teaql-object-storage-example io.teaqlteaql-runtime diff --git a/examples/order-management/java-app-console/pom.xml b/examples/order-management/java-app-console/pom.xml index b8db1212d..fcea2c6f4 100644 --- a/examples/order-management/java-app-console/pom.xml +++ b/examples/order-management/java-app-console/pom.xml @@ -11,7 +11,7 @@ 21 UTF-8 - 1.556-RELEASE + 1.557-RELEASE diff --git a/examples/order-management/java-lib-core/lib/pom.xml b/examples/order-management/java-lib-core/lib/pom.xml index b7291e4a0..2fcf76bd7 100644 --- a/examples/order-management/java-lib-core/lib/pom.xml +++ b/examples/order-management/java-lib-core/lib/pom.xml @@ -12,7 +12,7 @@ 21 4.1.1 - 1.556-RELEASE + 1.557-RELEASE UTF-8 true diff --git a/examples/round-trip-reference-runtime/pom.xml b/examples/round-trip-reference-runtime/pom.xml index b780ac77d..265b611be 100644 --- a/examples/round-trip-reference-runtime/pom.xml +++ b/examples/round-trip-reference-runtime/pom.xml @@ -6,7 +6,7 @@ io.teaql teaql-java-parent - 1.556-RELEASE + 1.557-RELEASE ../../pom.xml teaql-round-trip-reference-example diff --git a/examples/scalar-type-probe/empty-observations.cjs b/examples/scalar-type-probe/empty-observations.cjs index 5ed9d7667..05a4ba8f1 100644 --- a/examples/scalar-type-probe/empty-observations.cjs +++ b/examples/scalar-type-probe/empty-observations.cjs @@ -29,9 +29,15 @@ function observation(r,round){ assert.deepEqual(empty.sql[index].traceChain.slice(2).map(n=>n.comment),[operation,comment]); } for(const includeAll of [true,false]){ - const facet=next('EA-06',logging,9);assert.equal(facet.includeAll,includeAll);assert.equal(facet.visibleRows,1); + const facet=next('EA-06',logging,5);assert.equal(facet.includeAll,includeAll);assert.equal(facet.visibleRows,1); const expected=vectors.bucketCases[1].expected;assert.deepEqual(facet.values,includeAll?expected:expected.filter(v=>v.count>0)); - for(const sql of facet.sql.slice(2))assert.equal(sql.traceChain[2].comment,'facetByTypePlatformAs("buckets")'); + // Unlimited nested membership now stays inline instead of producing four + // materialization SELECTs. Keep every business count, null and lineage check. + for(const sql of facet.sql.slice(1))assert.equal(sql.traceChain[2].comment,'facetByTypePlatformAs("buckets")'); + assert.deepEqual(facet.sql.map(sql=>sql.tracePath.filter(n=>n.kind==='RELATION').map(n=>n.name)), + [[],[],['type_platform'],['type_platform','scalar_type_probe_list'],['type_platform','scalar_type_probe_list']]); + for(const sql of facet.sql.slice(0,2))assert.match(sql.sql,/type_platform IN \(SELECT id FROM type_platform_data/); + for(const sql of facet.sql.slice(3))assert.match(sql.sql,/id IN \(SELECT id FROM scalar_type_probe_data/); assert(facet.sql.some(s=>s.traceChain.some(n=>n.comment==='sum facet contributions'))); assert(facet.sql.some(s=>s.traceChain.some(n=>n.comment==='count facet contributions'))); } @@ -41,6 +47,6 @@ function observation(r,round){ const recovery=next('QUERY-RECOVERY',logging,1);assert.equal(recovery.sql[0].comment,'load independent detail after SQLite failure'); assert.equal(recovery.sql[0].traceChain[1].comment,'load independent detail after SQLite failure'); } - assert.equal(total,66);return {round,cases:22,sqlDriverAttempts:total,loggingModes:2,emptyVectors:8,realSQLiteErrors:2,independentRecoveries:2}; + assert.equal(total,50);return {round,cases:22,sqlDriverAttempts:total,loggingModes:2,emptyVectors:8,realSQLiteErrors:2,independentRecoveries:2}; } module.exports={observation}; diff --git a/examples/school-management/lib/pom.xml b/examples/school-management/lib/pom.xml index 2e9f4bc97..06d3ffb40 100644 --- a/examples/school-management/lib/pom.xml +++ b/examples/school-management/lib/pom.xml @@ -12,7 +12,7 @@ 21 4.1.1 - 1.556-RELEASE + 1.557-RELEASE UTF-8 true diff --git a/examples/school-management/pom.xml b/examples/school-management/pom.xml index d83f373f2..e7c6d0ca2 100644 --- a/examples/school-management/pom.xml +++ b/examples/school-management/pom.xml @@ -16,7 +16,7 @@ 0.0.1-SNAPSHOT UTF-8 true - 1.556-RELEASE + 1.557-RELEASE diff --git a/examples/security-foundations/pom.xml b/examples/security-foundations/pom.xml index 5c1e5269f..72a89e3eb 100644 --- a/examples/security-foundations/pom.xml +++ b/examples/security-foundations/pom.xml @@ -6,7 +6,7 @@ io.teaql teaql-java-parent - 1.556-RELEASE + 1.557-RELEASE ../../pom.xml teaql-security-foundations-example diff --git a/examples/shared-load-state/pom.xml b/examples/shared-load-state/pom.xml index fd4751336..c9cf6df0a 100644 --- a/examples/shared-load-state/pom.xml +++ b/examples/shared-load-state/pom.xml @@ -3,7 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - io.teaqlteaql-java-parent1.556-RELEASE + io.teaqlteaql-java-parent1.557-RELEASE ../../pom.xml shared-load-state-example 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 eeba40397..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 @@ -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. + assertEquals(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"); diff --git a/examples/standard-order/generated/lib/pom.xml b/examples/standard-order/generated/lib/pom.xml index 21b5c8cec..57703388f 100644 --- a/examples/standard-order/generated/lib/pom.xml +++ b/examples/standard-order/generated/lib/pom.xml @@ -12,7 +12,7 @@ 21 4.1.1 - 1.556-RELEASE + 1.557-RELEASE UTF-8 true @@ -67,7 +67,7 @@ io.teaql teaql-sqlite - 1.556-RELEASE + 1.557-RELEASE io.teaql diff --git a/examples/standard-order/pom.xml b/examples/standard-order/pom.xml index c76a630e3..e68edf37b 100644 --- a/examples/standard-order/pom.xml +++ b/examples/standard-order/pom.xml @@ -3,7 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 io.teaqlteaql-java-parent - 1.556-RELEASE../../pom.xml + 1.557-RELEASE../../pom.xml teaql-standard-order-example 21 diff --git a/examples/trace-chain/lib/pom.xml b/examples/trace-chain/lib/pom.xml index 6883f029f..20467e3f6 100644 --- a/examples/trace-chain/lib/pom.xml +++ b/examples/trace-chain/lib/pom.xml @@ -12,7 +12,7 @@ 21 4.1.1 - 1.556-RELEASE + 1.557-RELEASE UTF-8 true @@ -67,7 +67,7 @@ io.teaql teaql-sqlite - 1.556-RELEASE + 1.557-RELEASE io.teaql diff --git a/examples/trace-chain/pom.xml b/examples/trace-chain/pom.xml index 19fa45ec4..8141f0923 100644 --- a/examples/trace-chain/pom.xml +++ b/examples/trace-chain/pom.xml @@ -6,7 +6,7 @@ io.teaql teaql-java-parent - 1.556-RELEASE + 1.557-RELEASE ../../pom.xml teaql-trace-chain-example diff --git a/examples/trace-chain/src/test/java/io/teaql/examples/tracechain/GeneratedFacetTraceExampleTest.java b/examples/trace-chain/src/test/java/io/teaql/examples/tracechain/GeneratedFacetTraceExampleTest.java index b1e9c528a..141670c95 100644 --- a/examples/trace-chain/src/test/java/io/teaql/examples/tracechain/GeneratedFacetTraceExampleTest.java +++ b/examples/trace-chain/src/test/java/io/teaql/examples/tracechain/GeneratedFacetTraceExampleTest.java @@ -165,18 +165,25 @@ public class GeneratedFacetTraceExampleTest { assertEquals(orderId, E.customerOrder(order).getId().eval().longValue()); assertEquals("nested count uses both filtered payments, not the visible payment page", 2, count(order)); var raw = fixture.queryResults.get(fixture.queryResults.size() - 1).statements(); - // The page and its COUNT each materialize the predicate. Both - // real SELECTs must belong to the originating collector. - var routes = List.of(List.of("payment"), List.of(), List.of("payment"), - List.of(), List.of("payment"), List.of("payment"), + // Unbounded membership is now inlined into both the page and + // COUNT. It must retain request ancestry, without inventing + // two physical SELECTs for the inlined predicate. + var routes = List.of(List.of(), List.of(), + List.of("payment"), List.of("payment"), List.of("payment", "customerOrder")); + for (int i : List.of(0, 1)) { + assertTrue("membership stays in the real statement", + raw.get(i).getParameterizedQuery().contains("payment IN (SELECT id FROM payment_data")); + assertTrue("inlined Payment request retains its diagnostic ancestry", + raw.get(i).getRequestTree().stream().anyMatch(node -> "Payment".equals(node.name()))); + } assertEquals(routes.size(), raw.size()); for (int i = 0; i < raw.size(); i++) { assertPath(raw.get(i), routes.get(i), comment, purpose); assertEquals("real SELECT completed", "success", raw.get(i).getExecutionOutcome()); var safe = LogPrivacy.sql(raw.get(i), false); assertPath(safe, routes.get(i), comment, purpose); - if (i == 3 || i == 5) { + if (i == 1 || i == 3) { assertTrue("physical membership COUNT", raw.get(i).getParameterizedQuery().toUpperCase().contains("COUNT(")); assertFalse("membership count must not reuse the visible page limit", raw.get(i).getParameterizedQuery().toUpperCase().contains("LIMIT 1")); @@ -185,7 +192,7 @@ public class GeneratedFacetTraceExampleTest { assertEquals(logging ? raw.size() : 0, fixture.sql.size()); for (int i = 0; i < fixture.sql.size(); i++) assertPath(fixture.sql.get(i), routes.get(i), comment, purpose); assertTrue(fixture.context.getTraceChain().isEmpty()); - System.out.printf("JAVA_NESTED_FACET {\"logging\":%s,\"includeAll\":%s,\"visible\":1,\"paymentCount\":2,\"orderCount\":2,\"physicalStatements\":7,\"safeSinkStatements\":%d}%n", + System.out.printf("JAVA_NESTED_FACET {\"logging\":%s,\"includeAll\":%s,\"visible\":1,\"paymentCount\":2,\"orderCount\":2,\"physicalStatements\":5,\"safeSinkStatements\":%d}%n", logging, includeAll, fixture.sql.size()); } } diff --git a/examples/trace-chain/verify.sh b/examples/trace-chain/verify.sh index 71eaf901e..8c855608e 100644 --- a/examples/trace-chain/verify.sh +++ b/examples/trace-chain/verify.sh @@ -71,8 +71,8 @@ for repetition in 1 2; do if [[ $logging == true ]]; then reverse_sink_count=10; fi grep -Fq "JAVA_GENERATED_REVERSE_FACET logging=$logging includeAll=$all parents=3 fullCounts=true requestedEmpty=true physicalStatements=10 safeSinkStatements=$reverse_sink_count mutationCommands=0" "$log" sink_count=0 - if [[ $logging == true ]]; then sink_count=7; fi - grep -Fq "JAVA_NESTED_FACET {\"logging\":$logging,\"includeAll\":$all,\"visible\":1,\"paymentCount\":2,\"orderCount\":2,\"physicalStatements\":7,\"safeSinkStatements\":$sink_count}" "$log" + if [[ $logging == true ]]; then sink_count=5; fi + grep -Fq "JAVA_NESTED_FACET {\"logging\":$logging,\"includeAll\":$all,\"visible\":1,\"paymentCount\":2,\"orderCount\":2,\"physicalStatements\":5,\"safeSinkStatements\":$sink_count}" "$log" for exists in false true; do facet_rows=0 if [[ $exists == true ]]; then facet_rows=1; fi diff --git a/pom.xml b/pom.xml index 94577e340..98359d085 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ io.teaql teaql-java-parent - 1.556-RELEASE + 1.557-RELEASE pom teaql-java-parent diff --git a/scripts/verify-examples.sh b/scripts/verify-examples.sh index e222486c6..c6025e1bb 100755 --- a/scripts/verify-examples.sh +++ b/scripts/verify-examples.sh @@ -10,9 +10,10 @@ cleanup() { result=$?; trap - EXIT; wait; rm -rf -- "$build_dir"; exit "$result" trap cleanup EXIT : "${TEAQL_CODEGEN_DIR:?Set TEAQL_CODEGEN_DIR to the local generator checkout}" node "$repo/scripts/prepare-example-isolation.cjs" "$build_dir" "$TEAQL_CODEGEN_DIR" "$evidence_dir" -export MAVEN_OPTS="${MAVEN_OPTS:-} -Dmaven.repo.local=$build_dir/maven" +runtime_version="$(node -e 'const fs=require("fs");process.stdout.write(fs.readFileSync(process.argv[1],"utf8").match(/([^<]+)<\/version>/)[1])' "$repo/pom.xml")" +export MAVEN_OPTS="${MAVEN_OPTS:-} -Dmaven.repo.local=$build_dir/maven -Dteaql.version=$runtime_version" echo "Native example artifacts use an isolated disposable Maven repository; compact evidence: $evidence_dir" -expected=(business-id-runtime conformance exact-decimal fix-e-alignment http-resilience object-storage order-management round-trip-reference-runtime scalar-type-probe school-management security-foundations shared-load-state standard-order trace-chain) +expected=(business-id-runtime conformance exact-decimal fix-e-alignment http-resilience inheritance-save object-storage order-management round-trip-reference-runtime scalar-type-probe school-management security-foundations shared-load-state standard-order trace-chain) mapfile -t actual < <(find "$repo/examples" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort) if [[ "${actual[*]}" != "${expected[*]}" ]]; then echo "example inventory changed; update scripts/verify-examples.sh: ${actual[*]}" >&2 @@ -23,6 +24,8 @@ cd "$repo" # This verifier needs original Git provenance and already creates its own # disposable source-paired reactor. It never builds in the source repository. node "${TEAQL_JAVA_EXAMPLE_SOURCE_ROOT:-$repo}/examples/fix-e-alignment/verify-local.cjs" +node "${TEAQL_JAVA_EXAMPLE_SOURCE_ROOT:-$repo}/examples/inheritance-save/verify.cjs" \ + --output "$evidence_dir/inheritance-save" bash examples/object-storage/verify.sh bash examples/http-resilience/verify.sh mvn -q -DskipTests install @@ -86,4 +89,7 @@ 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" +TEAQL_NATURAL_MESSAGES_EVIDENCE_DIR="$evidence_dir/natural-messages" \ + node "${TEAQL_JAVA_EXAMPLE_SOURCE_ROOT:-$repo}/examples/conformance/natural-messages/verify-local.cjs" echo "PASS: all Java examples" diff --git a/teaql-android/pom.xml b/teaql-android/pom.xml index 0a9b27a77..878162428 100644 --- a/teaql-android/pom.xml +++ b/teaql-android/pom.xml @@ -7,7 +7,7 @@ io.teaql teaql-java-parent - 1.556-RELEASE + 1.557-RELEASE teaql-android diff --git a/teaql-business-id-jdbc/pom.xml b/teaql-business-id-jdbc/pom.xml index 510f40fc6..0a050b215 100644 --- a/teaql-business-id-jdbc/pom.xml +++ b/teaql-business-id-jdbc/pom.xml @@ -7,7 +7,7 @@ io.teaql teaql-java-parent - 1.556-RELEASE + 1.557-RELEASE ../pom.xml diff --git a/teaql-cloud/pom.xml b/teaql-cloud/pom.xml index eb52757f1..3f6e2909f 100644 --- a/teaql-cloud/pom.xml +++ b/teaql-cloud/pom.xml @@ -6,7 +6,7 @@ io.teaql teaql-java-parent - 1.556-RELEASE + 1.557-RELEASE teaql-cloud teaql-cloud diff --git a/teaql-context-runtime-tools/pom.xml b/teaql-context-runtime-tools/pom.xml index c343e5349..38ef0c7be 100644 --- a/teaql-context-runtime-tools/pom.xml +++ b/teaql-context-runtime-tools/pom.xml @@ -6,7 +6,7 @@ io.teaql teaql-java-parent - 1.556-RELEASE + 1.557-RELEASE teaql-context-runtime-tools diff --git a/teaql-core/pom.xml b/teaql-core/pom.xml index 2e230b3e9..102865067 100644 --- a/teaql-core/pom.xml +++ b/teaql-core/pom.xml @@ -7,7 +7,7 @@ io.teaql teaql-java-parent - 1.556-RELEASE + 1.557-RELEASE ../pom.xml diff --git a/teaql-core/src/main/java/io/teaql/core/AggrFunction.java b/teaql-core/src/main/java/io/teaql/core/AggrFunction.java index dac21c410..1482e6847 100644 --- a/teaql-core/src/main/java/io/teaql/core/AggrFunction.java +++ b/teaql-core/src/main/java/io/teaql/core/AggrFunction.java @@ -6,6 +6,7 @@ public enum AggrFunction implements PropertyFunction { MAX, AVG, COUNT, + COUNT_DISTINCT, SUM, GBK, STDDEV, 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..a2168879f 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,45 @@ 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); + } + }); + // 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; + } + }; + } + @FrameworkInternal("Physical transaction rollback; native values are captured by runtime metadata") public Runnable __internalCaptureMutationRollback() { var savedUpdates = new HashMap<>(updatedProperties); @@ -588,6 +627,7 @@ public Entity updateProperty(String propertyName, Object value) { boolean wasLoaded = isPropertyLoaded(propertyName); Object oldValue = getProperty(propertyName); if (wasLoaded && ObjectUtil.equals(oldValue, value)) return this; + validatePendingRecoveryIdentity(propertyName, value); setProperty(propertyName, value); handleUpdate(propertyName, oldValue, value, wasLoaded); return this; @@ -614,6 +654,7 @@ private void handleUpdate(String propertyName, Object oldValue, Object newValue, // Check before publishing state, including the equal-null case on an // ID-only reference. Null backing storage is not proof of loaded Null. get$status().next(EntityAction.UPDATE); + validatePendingRecoveryIdentity(propertyName, newValue); if (wasLoaded && ObjectUtil.equals(oldValue, newValue)) return; gotoNextStatus(EntityAction.UPDATE); markPropertyLoaded(propertyName); @@ -661,6 +702,17 @@ private Map mutableUpdatedProperties() { return updatedProperties; } + private void validatePendingRecoveryIdentity(String propertyName, Object value) { + if ($status != EntityStatus.UPDATED_RECOVER) return; + Object baseline; + if (ID_PROPERTY.equals(propertyName)) baseline = id; + else if (VERSION_PROPERTY.equals(propertyName)) baseline = version; + else return; + if (!ObjectUtil.equals(baseline, value)) { + throw new TeaQLRuntimeException("Cannot change " + propertyName + " while entity recovery is pending"); + } + } + public void gotoNextStatus(EntityAction action) { set$status(get$status().next(action)); } @@ -750,6 +802,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()); @@ -758,6 +817,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/BaseRequest.java b/teaql-core/src/main/java/io/teaql/core/BaseRequest.java index 896ab5fdc..7df3f35a9 100644 --- a/teaql-core/src/main/java/io/teaql/core/BaseRequest.java +++ b/teaql-core/src/main/java/io/teaql/core/BaseRequest.java @@ -32,8 +32,10 @@ public abstract class BaseRequest implements SearchRequest protected String comment; protected String purpose; protected Map queryOperations = new HashMap<>(); + protected transient Map rollUpOperations = new HashMap<>(); protected QueryOperation pageCountOperation; @Override public Map queryOperations() { return Map.copyOf(queryOperations); } + @Override public QueryOperation rollUpOperation(String relation) { return rollUpOperations.get(relation); } @Override public QueryOperation pageCountOperation() { return pageCountOperation; } @FrameworkInternal("Generator supplies the exact native count method and alias") @com.fasterxml.jackson.annotation.JsonIgnore @@ -52,6 +54,9 @@ public abstract class BaseRequest implements SearchRequest // search conditions protected SearchCriteria searchCriteria; + // Statistical result conditions are not predicates on the source rows. + protected SearchCriteria having; + // order by protected OrderBys orderBys = new OrderBys(); @@ -109,6 +114,18 @@ public BaseRequest(Class pReturnType, Supplier entityFactory) { this.entityFactory = entityFactory; } + /** An independent typed query graph; building or copying never accesses Context. */ + @SuppressWarnings("unchecked") + public BaseRequest copy() { + return (BaseRequest) new QueryRequestGraphCopy(true).request(this, 0); + } + + /** Generated requests override this factory without reflection. */ + @FrameworkInternal("Type-preserving allocation for an explicit query graph copy") + protected BaseRequest internalCopyTarget() { + throw new TeaQLRuntimeException("Query copy requires a type-preserving request factory for " + getTypeName()); + } + public String getSearchForText() { return searchForText; } @@ -234,6 +251,23 @@ public SearchCriteria getSearchCriteria() { return searchCriteria; } + @Override public SearchCriteria getHaving() { return having; } + + @FrameworkInternal("Parser and derived population copies replace statistical result conditions") + public void replaceHaving(SearchCriteria condition) { having = condition; } + + /** Append an AND condition on selected group/measure aliases. */ + public BaseRequest having(SearchCriteria condition) { + if (condition != null) having = having == null ? condition : SearchCriteria.and(having, condition); + return this; + } + + public BaseRequest having(String alias, Operator operator, Object... values) { + SearchCriteria condition = internalCreateSearchCriteria(alias, refineOperator(operator, values), values); + if (condition == null) throw new TeaQLRuntimeException("unsupported HAVING operator: " + operator); + return having(condition); + } + /** * Replaces the current criteria as one atomic parser operation. Dynamic input adapters use * this to roll back a partially resolved relation path when a later field segment is stale. @@ -357,10 +391,7 @@ protected BaseRequest buildRequest(Map map) { } protected BaseRequest internalMatchAny(SearchRequest anotherRequest) { - if (searchCriteria == null) { - return this; - } - + Objects.requireNonNull(anotherRequest, "matching request"); if (anotherRequest.getSearchCriteria() == null) { return this; } @@ -377,12 +408,14 @@ protected BaseRequest internalMatchAny(SearchRequest anotherRequest) { List subExpress = extractSearchCriteriaExcludeVersion(anotherRequest); // collection search criteria other than version criteria int length = subExpress.size(); + if (length == 0) { + return this; + } SearchCriteria[] searchCriteriaArray = new SearchCriteria[length]; for (int i = 0; i < length; i++) { searchCriteriaArray[i] = (SearchCriteria) subExpress.get(i); } - ((AND) this.searchCriteria).getExpressions().add(SearchCriteria.or(searchCriteriaArray)); - return this; + return appendSearchCriteria(SearchCriteria.or(searchCriteriaArray)); } protected BaseRequest withDeletedRows() { @@ -670,6 +703,27 @@ public void groupBy(String propertyName, SearchRequest subRequest) { .getComplexDimensions() .add(new SimpleNamedExpression(propertyName, new PropertyReference(propertyName))); this.propagateDimensions.put(propertyName, subRequest); + rollUpOperations.remove(propertyName); + } + + @FrameworkInternal("Generator supplies the exact native statistical Q method") + public void groupBy(String propertyName, SearchRequest subRequest, QueryOperation operation) { + groupBy(propertyName, subRequest); + if (operation != null) rollUpOperations.put(propertyName, operation); + } + + /** Generated navigation replaces its own binding, never an application predicate. */ + protected final void internalRollUpTo(String property, SearchRequest parent) { + internalRollUpTo(property, parent, null); + } + + protected final void internalRollUpTo(String property, SearchRequest parent, QueryOperation operation) { + Objects.requireNonNull(property, "property"); Objects.requireNonNull(parent, "parent"); + SearchCriteria cleaned = QueryNavigation.clear(searchCriteria, property, 0); + searchCriteria = cleaned; + aggregations.getComplexDimensions().removeIf(dimension -> property.equals(dimension.name())); + groupBy(property, parent, operation); + appendSearchCriteria(new SubQuerySearchCriteria(property, parent, BaseEntity.ID_PROPERTY, true)); } public void addAggregate(String retName, String propertyName, AggrFunction function) { @@ -713,6 +767,17 @@ public void countProperty(String retName, String propertyName) { addAggregate(retName, propertyName, AggrFunction.COUNT); } + public void countDistinctProperty(String propertyName) { + countDistinctProperty(propertyName, propertyName); + } + + public void countDistinctProperty(String retName, String propertyName) { + if ("*".equals(propertyName)) { + throw new IllegalArgumentException("COUNT DISTINCT requires a field, not all rows"); + } + addAggregate(retName, propertyName, AggrFunction.COUNT_DISTINCT); + } + public void sum(String propertyName) { sum(propertyName, propertyName); } @@ -973,6 +1038,7 @@ public boolean equals(Object pO) { && Objects.equals(getSimpleDynamicProperties(), that.getSimpleDynamicProperties()) && Objects.equals(getDynamicPropertyMetadata(), that.getDynamicPropertyMetadata()) && Objects.equals(getSearchCriteria(), that.getSearchCriteria()) + && Objects.equals(getHaving(), that.getHaving()) && Objects.equals(orderBys, that.orderBys) && Objects.equals(getSlice(), that.getSlice()) && Objects.equals(enhanceRelations, that.enhanceRelations) @@ -995,6 +1061,7 @@ public int hashCode() { getSimpleDynamicProperties(), getDynamicPropertyMetadata(), getSearchCriteria(), + getHaving(), orderBys, getSlice(), enhanceRelations, @@ -1099,6 +1166,11 @@ public String getTypeName() { return type; } + @Override protected BaseRequest internalCopyTarget() { + return entityDescriptor == null ? new TempRequest(returnType(), type, this::internalNewEntity) + : new TempRequest(entityDescriptor); + } + @Override protected EntityDescriptor getEntityDescriptor() { return entityDescriptor != null ? entityDescriptor : super.getEntityDescriptor(); 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/main/java/io/teaql/core/EntityStatus.java b/teaql-core/src/main/java/io/teaql/core/EntityStatus.java index cdaf482ab..8d270e6f4 100644 --- a/teaql-core/src/main/java/io/teaql/core/EntityStatus.java +++ b/teaql-core/src/main/java/io/teaql/core/EntityStatus.java @@ -56,6 +56,9 @@ public enum EntityStatus { statusTransaction.put(UPDATED_DELETED, UPDATE, UPDATED_DELETED); statusTransaction.put(UPDATED_RECOVER, PERSIST, PERSISTED); statusTransaction.put(UPDATED_RECOVER, RECOVER, UPDATED_RECOVER); + // Correcting a tombstone after marking it for recovery must keep the + // pending recovery, not become an ordinary positive-version update. + statusTransaction.put(UPDATED_RECOVER, UPDATE, UPDATED_RECOVER); } public EntityStatus next(EntityAction action) { diff --git a/teaql-core/src/main/java/io/teaql/core/ExecutionMetadata.java b/teaql-core/src/main/java/io/teaql/core/ExecutionMetadata.java index 243d85666..143f843e1 100644 --- a/teaql-core/src/main/java/io/teaql/core/ExecutionMetadata.java +++ b/teaql-core/src/main/java/io/teaql/core/ExecutionMetadata.java @@ -18,6 +18,7 @@ public final class ExecutionMetadata { private String debugQuery; private List traceChain; private List requestTraceChain = List.of(); + private List requestTree = List.of(); private List mutationLineage = List.of(); private String statementOperation; private String comment; @@ -116,6 +117,9 @@ public void setParameters(List parameters) { public List getRequestTraceChain() { return requestTraceChain; } @com.fasterxml.jackson.annotation.JsonProperty("traceChain") public void setRequestTraceChain(List trace) { requestTraceChain = trace == null ? List.of() : List.copyOf(trace); } + @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY) + public List getRequestTree() { return requestTree; } + public void setRequestTree(List nodes) { requestTree = nodes == null ? List.of() : List.copyOf(nodes); } @com.fasterxml.jackson.annotation.JsonProperty("tracePath") public List getTracePath() { return traceChain == null ? List.of() : traceChain; } diff --git a/teaql-core/src/main/java/io/teaql/core/QueryNavigation.java b/teaql-core/src/main/java/io/teaql/core/QueryNavigation.java new file mode 100644 index 000000000..6f0903ae9 --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/QueryNavigation.java @@ -0,0 +1,41 @@ +package io.teaql.core; + +import io.teaql.core.criteria.AND; +import io.teaql.core.criteria.OR; +import io.teaql.core.criteria.NOT; +import io.teaql.core.criteria.IsNotNull; +import java.util.ArrayList; + +/** Pure builder rewrite. A null result means TRUE in the new joined population. */ +final class QueryNavigation { + private QueryNavigation() {} + + static SearchCriteria clear(SearchCriteria criteria, String relation, int depth) { + if (depth > 64) throw new TeaQLRuntimeException("Roll-up navigation expression exceeds 64 levels"); + if (criteria instanceof SubQuerySearchCriteria membership && membership.navigationOwned() + && relation.equals(membership.getPropertyName())) return null; + if (criteria != null && (criteria.getClass() == AND.class || criteria.getClass() == OR.class)) { + boolean and = criteria.getClass() == AND.class; + var result = new ArrayList(); + for (var operand : ((FunctionApply) criteria).getExpressions()) { + if (!(operand instanceof SearchCriteria condition)) + throw new TeaQLRuntimeException("Roll-up navigation Boolean operands must be conditions"); + var rewritten = clear(condition, relation, depth + 1); + if (rewritten != null) result.add(rewritten); + else if (!and) result.add(new IsNotNull(new PropertyReference(BaseEntity.ID_PROPERTY))); + } + if (and && result.isEmpty()) return null; + if (result.size() == 1) return result.get(0); + return and ? SearchCriteria.and(result.toArray(SearchCriteria[]::new)) : SearchCriteria.or(result.toArray(SearchCriteria[]::new)); + } + if (criteria != null && criteria.getClass() == NOT.class) { + var operands = ((FunctionApply) criteria).getExpressions(); + if (operands.size() != 1 || !(operands.get(0) instanceof SearchCriteria condition)) + throw new TeaQLRuntimeException("Roll-up navigation NOT requires one condition"); + var rewritten = clear(condition, relation, depth + 1); + return SearchCriteria.not(rewritten == null + ? new IsNotNull(new PropertyReference(BaseEntity.ID_PROPERTY)) : rewritten); + } + return criteria; + } +} diff --git a/teaql-core/src/main/java/io/teaql/core/QueryRequestGraphCopy.java b/teaql-core/src/main/java/io/teaql/core/QueryRequestGraphCopy.java new file mode 100644 index 000000000..c3ae3efb0 --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/QueryRequestGraphCopy.java @@ -0,0 +1,199 @@ +package io.teaql.core; + +import io.teaql.core.criteria.*; +import java.util.*; + +/** One bounded copy operation; identity is shared only inside the copied AST. */ +@SuppressWarnings({"rawtypes", "unchecked"}) +final class QueryRequestGraphCopy { + private static final Set> IMMUTABLE_NUMBERS = Set.of(Byte.class, Short.class, Integer.class, + Long.class, Float.class, Double.class, java.math.BigInteger.class, java.math.BigDecimal.class); + private static final Set> FUNCTIONS = Set.of(FunctionApply.class, AggrExpression.class, + AND.class, OR.class, NOT.class, Between.class, OneOperatorCriteria.class, TwoOperatorCriteria.class, + EQ.class, InEquation.class, NotBeginWith.class, NotEndWith.class, NotIn.class, + LTE.class, InLarge.class, GT.class, GTE.class, BeginWith.class, IN.class, LT.class, + Contain.class, NotContain.class, EndWith.class, IsNull.class, IsNotNull.class); + private final boolean typed; + private final IdentityHashMap, BaseRequest> requests = new IdentityHashMap<>(); + private final IdentityHashMap active = new IdentityHashMap<>(); + private final IdentityHashMap expressions = new IdentityHashMap<>(); + private int requestDepth; + private int nodes; + + QueryRequestGraphCopy(boolean typed) { this.typed = typed; } + + BaseRequest request(SearchRequest source, int depth) { + if (source == null) return null; + if (active.containsKey(source) || depth > 64) throw invalid("Cyclic or oversized query request graph"); + var previous = requests.get(source); + if (previous != null) return previous; + if (!typed) return new QueryRequestSnapshot(source, source.requestScope(), source.diagnosticSource(), this, depth); + if (!(source instanceof BaseRequest builder)) throw invalid("Query copy requires a typed request factory"); + var target = builder.internalCopyTarget(); + if (target == null || target == source || target.getClass() != source.getClass()) + throw invalid("Query copy factory must return a fresh request of the same type"); + populate(source, target, depth); + return target; + } + + void populate(SearchRequest source, BaseRequest target, int depth) { + if (depth > 64 || active.put(source, true) != null || ++nodes > 10000) + throw invalid("Cyclic or oversized query request graph"); + requests.put(source, target); + int previousDepth = requestDepth; requestDepth = depth; + try { + if (source instanceof BaseRequest builder) { + builder.propagateMetadata(target); + target.propagateAggregationCache = builder.propagateAggregationCache; + } + target.comment = source.comment(); target.purpose = source.purpose(); + target.projections = named(source.getProjections()); + target.simpleDynamicProperties = named(source.getSimpleDynamicProperties()); + target.dynamicPropertyMetadata = source.getDynamicPropertyMetadata(); + target.searchCriteria = (SearchCriteria) expression(source.getSearchCriteria(), 0); + target.having = (SearchCriteria) expression(source.getHaving(), 0); + target.orderBys = new OrderBys(); + if (source.getOrderBy() != null) for (var order : source.getOrderBy().getOrderBys()) { + var copy = new OrderBy("id"); copy.setDirection(order.getDirection()); + copy.setExpression(expression(order.getExpression(), 0)); target.orderBys.addOrderBy(copy); + } + var slice = source.getSlice(); + target.slice = slice == null || depth > 0 && !slice.hasExplicitPage() ? null : slice.copy(); + target.partitionProperty = source.getPartitionProperty(); + target.aggregations = new Aggregations(); + if (source.getAggregations() != null) { + var aggregation = source.getAggregations(); target.aggregations.setName(aggregation.getName()); + target.aggregations.setAggregates(named(aggregation.getAggregates())); + target.aggregations.setSimpleDimensions(named(aggregation.getSimpleDimensions())); + target.aggregations.setComplexDimensions(named(aggregation.getComplexDimensions())); + } + target.enhanceRelations = children(source.enhanceRelations()); + target.enhanceChildren = children(source.enhanceChildren()); + target.propagateAggregations = children(source.getPropagateAggregations()); + target.propagateDimensions = children(source.getPropagateDimensions()); + target.dynamicAggregateAttributes = new ArrayList<>(); + for (var aggregation : source.getDynamicAggregateAttributes()) + target.dynamicAggregateAttributes.add((SimpleAggregation) expression(aggregation, 0)); + target.facetRequests = new ArrayList<>(); + for (var facet : source.getFacetRequests()) { + var copy = new FacetRequest(); copy.setFacetName(facet.getFacetName()); copy.setRelationName(facet.getRelationName()); + copy.setMergeCriteria(facet.isMergeCriteria()); copy.setOperation(facet.getOperation()); + copy.setRequest(request(facet.getRequest(), depth + 1)); target.facetRequests.add(copy); + } + target.queryOperations = new HashMap<>(source.queryOperations()); target.pageCountOperation = source.pageCountOperation(); + target.rollUpOperations = new HashMap<>(); + target.propagateDimensions.keySet().forEach(relation -> { + var operation = source.rollUpOperation(relation); + if (operation != null) target.rollUpOperations.put(relation, operation); + }); + target.cacheAggregation = source.tryCacheAggregation(); target.aggregateCacheTime = source.getAggregateCacheTime(); + target.hardLimit = source.hardLimit(); target.continuousPageFetchOptions = source.continuousPageFetchOptions(); + target.idSetPaginationOptions = source.idSetPaginationOptions(); target.topNProbeParentThreshold = source.topNProbeParentThreshold(); + target.extensions = new HashMap<>(); + if (source.getExtensions() != null) source.getExtensions().forEach((key, value) -> target.extensions.put(key, value(value, 0))); + target.searchForText = source.getSearchForText(); target.dynamicFieldSelection = source.getDynamicFieldSelection(); + } finally { requestDepth = previousDepth; active.remove(source); } + } + + private Map children(Map source) { + var result = new LinkedHashMap(); + if (source != null) source.forEach((name, child) -> result.put(name, request(child, requestDepth + 1))); + return result; + } + + private List named(List source) { + var result = new ArrayList(); + if (source != null) for (var item : source) result.add((SimpleNamedExpression) expression(item, 0)); + return result; + } + + private Expression expression(Expression source, int depth) { + if (source == null) return null; + if (depth > 64 || active.containsKey(source)) throw invalid("Cyclic or oversized query expression"); + var previous = expressions.get(source); if (previous != null) return previous; + if (++nodes > 10000) throw invalid("Query expression graph exceeds its node limit"); + active.put(source, true); + try { + Expression copy; + if (source.getClass() == PropertyReference.class) copy = new PropertyReference(((PropertyReference) source).getPropertyName()); + else if (source.getClass() == Parameter.class) { + var parameter = (Parameter) source; + if (parameter.getOperator() == null) throw invalid("Query parameter is missing an operator"); + copy = new Parameter(parameter.getName(), value(parameter.getValue(), 0), parameter.getOperator()); + } else if (source.getClass() == Constant.class) { + var constant = new Constant(); constant.setValue(value(((Constant) source).getValue(), 0)); copy = constant; + } else if (source.getClass() == SimpleNamedExpression.class) { + var named = (SimpleNamedExpression) source; copy = new SimpleNamedExpression(named.name(), expression(named.getExpression(), depth + 1)); + } else if (source.getClass() == SubQuerySearchCriteria.class) { + var membership = (SubQuerySearchCriteria) source; + copy = new SubQuerySearchCriteria(membership.getPropertyName(), request(membership.getDependsOn(), requestDepth + 1), + membership.getDependsOnPropertyName(), membership.navigationOwned()); + } else if (source.getClass() == VersionSearchCriteria.class) + copy = new VersionSearchCriteria((SearchCriteria) expression(((VersionSearchCriteria) source).getSearchCriteria(), depth + 1)); + else if (source.getClass() == TypeCriteria.class) + copy = new TypeCriteria((Parameter) expression(((TypeCriteria) source).getTypeParameter(), depth + 1)); + else if (source.getClass() == SimpleAggregation.class) { + var aggregate = (SimpleAggregation) source; + var result = new SimpleAggregation(aggregate.getName(), request(aggregate.getAggregateRequest(), requestDepth + 1), aggregate.isSingleNumber()); + result.setOperation(aggregate.getOperation()); copy = result; + } else if (source instanceof FunctionApply function && FUNCTIONS.contains(source.getClass())) { + var arguments = function.getExpressions().stream().map(argument -> expression(argument, depth + 1)).toArray(Expression[]::new); + int arity = source instanceof Between ? 3 : source instanceof TwoOperatorCriteria ? 2 + : source instanceof NOT || source instanceof AggrExpression || source instanceof OneOperatorCriteria ? 1 : -1; + if (arity >= 0 && arguments.length != arity) throw invalid("Invalid query function arity"); + if ((source instanceof AND || source instanceof OR) + && Arrays.stream(arguments).anyMatch(argument -> !(argument instanceof SearchCriteria))) + throw invalid("Boolean query functions require conditions"); + if (source instanceof AND) copy = new AND(Arrays.copyOf(arguments, arguments.length, SearchCriteria[].class)); + else if (source instanceof OR) copy = new OR(Arrays.copyOf(arguments, arguments.length, SearchCriteria[].class)); + else if (source instanceof NOT) copy = new NOT((SearchCriteria) arguments[0]); + else if (source instanceof AggrExpression) copy = new AggrExpression((AggrFunction) function.getOperator(), arguments[0]); + else if (source instanceof Between) copy = new Between(arguments[0], arguments[1], arguments[2]); + else if (source instanceof TwoOperatorCriteria) copy = new TwoOperatorCriteria(function.getOperator(), arguments[0], arguments[1]); + else if (source instanceof OneOperatorCriteria) copy = new OneOperatorCriteria((Operator) function.getOperator(), arguments[0]); + else copy = new FunctionApply(function.getOperator(), arguments); + } else { + // Execution snapshots retain trusted custom parser extensions. + // Explicit copies cannot silently claim to freeze unknown ASTs. + if (typed) throw invalid("Query copy does not support expression type " + source.getClass().getName()); + copy = source; + } + expressions.put(source, copy); return copy; + } finally { active.remove(source); } + } + + private Object value(Object source, int depth) { + if (source == null || source instanceof String || immutableNumber(source) || source instanceof Boolean + || source instanceof Character || source instanceof Enum || source instanceof UUID + || (source instanceof java.time.temporal.TemporalAccessor && source.getClass().getPackageName().equals("java.time")) + || source instanceof java.time.Duration || source instanceof java.time.Period) return source; + if (depth > 64 || active.put(source, true) != null) throw invalid("Cyclic or oversized query parameter container"); + try { + // Date.clone preserves the JDK SQL subclasses (including Timestamp + // nanoseconds) without adding a java.sql dependency to core. + if (source instanceof Date date && (source.getClass() == Date.class + || source.getClass().getPackageName().equals("java.sql"))) return date.clone(); + if (source instanceof List list) { var result = new ArrayList<>(); for (var item : list) result.add(value(item, depth + 1)); return result; } + if (source instanceof Set set) { var result = new LinkedHashSet<>(); for (var item : set) result.add(value(item, depth + 1)); return result; } + if (source instanceof Map map) { var result = new LinkedHashMap<>(); map.forEach((key, item) -> result.put(value(key, depth + 1), value(item, depth + 1))); return result; } + if (source instanceof byte[] bytes) return bytes.clone(); + if (source instanceof short[] values) return values.clone(); + if (source instanceof int[] values) return values.clone(); + if (source instanceof long[] values) return values.clone(); + if (source instanceof float[] values) return values.clone(); + if (source instanceof double[] values) return values.clone(); + if (source instanceof boolean[] values) return values.clone(); + if (source instanceof char[] values) return values.clone(); + if (source instanceof Object[] array) { var result = array.clone(); for (int i=0; i request, QueryRequestScope scope) { this(request, scope, request.diagnosticSource()); } public QueryRequestSnapshot(SearchRequest request, QueryRequestScope scope, SearchRequest diagnosticSource) { + this(request, scope, diagnosticSource, new QueryRequestGraphCopy(false), 0); + } + QueryRequestSnapshot(SearchRequest request, QueryRequestScope scope, SearchRequest diagnosticSource, + QueryRequestGraphCopy graph, int depth) { super((Class) request.returnType(), request::internalNewEntity); original = request; typeName = request.getTypeName(); this.scope = scope; this.diagnosticSource = diagnosticSource; - if (request instanceof BaseRequest base) base.propagateMetadata(this); + graph.populate(request, this, depth); + if (scope != null && scope.parentRequest() != null && slice != null && !slice.hasExplicitPage()) + slice = null; comment = scope == null ? request.comment() : scope.intent().comment(); purpose = scope == null ? request.purpose() : scope.purpose(); - projections = new ArrayList<>(request.getProjections()); - simpleDynamicProperties = new ArrayList<>(request.getSimpleDynamicProperties()); - dynamicPropertyMetadata = request.getDynamicPropertyMetadata(); - searchCriteria = request.getSearchCriteria(); - orderBys = new OrderBys(); - if (request.getOrderBy() != null) for (OrderBy source : request.getOrderBy().getOrderBys()) { - OrderBy order = new OrderBy("id"); order.setExpression(source.getExpression()); order.setDirection(source.getDirection()); - orderBys.addOrderBy(order); - } - if (request.getSlice() == null) slice = null; - else { slice = new Slice(); slice.setOffset(request.getSlice().getOffset()); slice.setSize(request.getSlice().getSize()); } - partitionProperty = request.getPartitionProperty(); - aggregations = copyAggregations(request.getAggregations()); - enhanceRelations = copyRequests(request.enhanceRelations()); - enhanceChildren = copyRequests(request.enhanceChildren()); - propagateAggregations = copyRequests(request.getPropagateAggregations()); - propagateDimensions = copyRequests(request.getPropagateDimensions()); - dynamicAggregateAttributes = new ArrayList<>(); - for (SimpleAggregation source : request.getDynamicAggregateAttributes()) { - var aggregate = new SimpleAggregation(source.getName(), new QueryRequestSnapshot(source.getAggregateRequest(), source.getAggregateRequest().requestScope()), source.isSingleNumber()); - aggregate.setOperation(source.getOperation()); - dynamicAggregateAttributes.add(aggregate); - } - facetRequests = new ArrayList<>(); - for (FacetRequest source : request.getFacetRequests()) { - var facet = new FacetRequest(); - facet.setFacetName(source.getFacetName()); facet.setRelationName(source.getRelationName()); - facet.setMergeCriteria(source.isMergeCriteria()); facet.setOperation(source.getOperation()); - if (source.getRequest() != null) facet.setRequest(new QueryRequestSnapshot(source.getRequest(), source.getRequest().requestScope())); - facetRequests.add(facet); - } - queryOperations = new HashMap<>(request.queryOperations()); - pageCountOperation = request.pageCountOperation(); - cacheAggregation = request.tryCacheAggregation(); aggregateCacheTime = request.getAggregateCacheTime(); - hardLimit = request.hardLimit(); continuousPageFetchOptions = request.continuousPageFetchOptions(); - idSetPaginationOptions = request.idSetPaginationOptions(); topNProbeParentThreshold = request.topNProbeParentThreshold(); - if (request.getExtensions() != null) extensions.putAll(request.getExtensions()); - searchForText = request.getSearchForText(); dynamicFieldSelection = request.getDynamicFieldSelection(); - } - private static java.util.Map copyRequests(java.util.Map requests) { - var result = new HashMap(); - if (requests != null) requests.forEach((name, query) -> result.put(name, new QueryRequestSnapshot(query, query.requestScope()))); - return result; - } - private static Aggregations copyAggregations(Aggregations source) { - Aggregations result = new Aggregations(); - if (source != null) { - result.setName(source.getName()); result.setAggregates(new ArrayList<>(source.getAggregates())); - result.setSimpleDimensions(new ArrayList<>(source.getSimpleDimensions())); - result.setComplexDimensions(new ArrayList<>(source.getComplexDimensions())); - } - return result; } @Override public String getTypeName() { return typeName; } @Override public QueryIntent inheritedQueryIntent() { return scope != null ? scope.intent() : original == null ? null : original.inheritedQueryIntent(); } diff --git a/teaql-core/src/main/java/io/teaql/core/QueryRequestTraceNode.java b/teaql-core/src/main/java/io/teaql/core/QueryRequestTraceNode.java new file mode 100644 index 000000000..94dd05990 --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/QueryRequestTraceNode.java @@ -0,0 +1,34 @@ +package io.teaql.core; + +import java.util.*; + +/** Detached invocation-local diagnostics, never a writable request ownership API. */ +public record QueryRequestTraceNode(int id, Integer parentId, String kind, String name, + String detail, @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) String method) { + public static List fromScopes(List scopes) { + if (scopes.size() < 2) return List.of(); + var distinct = Collections.newSetFromMap(new IdentityHashMap()); + distinct.addAll(scopes); + if (distinct.size() < 2) return List.of(); + var indices = new IdentityHashMap(); + var nodes = new ArrayList(); + for (var leaf : scopes) { + var ancestry = new ArrayList(); + for (var current = leaf; current != null; current = current.parentRequest()) ancestry.add(current); + Collections.reverse(ancestry); + for (var scope : ancestry) { + if (indices.containsKey(scope)) continue; + Integer parent; + if (scope.parentRequest() == null) { + parent = nodes.size(); + nodes.add(new QueryRequestTraceNode(parent, null, "purpose", scope.requestName(), scope.purpose(), null)); + } else parent = Objects.requireNonNull(indices.get(scope.parentRequest())); + int id = nodes.size(); + nodes.add(new QueryRequestTraceNode(id, parent, "comment", scope.requestName(), scope.comment(), + scope.operation() == null ? null : scope.operation().method())); + indices.put(scope, id); + } + } + return List.copyOf(nodes); + } +} diff --git a/teaql-core/src/main/java/io/teaql/core/RuntimeModule.java b/teaql-core/src/main/java/io/teaql/core/RuntimeModule.java index 57470e6e6..7a06fa982 100644 --- a/teaql-core/src/main/java/io/teaql/core/RuntimeModule.java +++ b/teaql-core/src/main/java/io/teaql/core/RuntimeModule.java @@ -14,19 +14,23 @@ public final class RuntimeModule { private final List metadataAssemblers; private final List> checkers; private final List bootstraps; + private final io.teaql.core.checker.CheckerPresentation.Model checkerPresentation; private RuntimeModule(List metadataAssemblers, List> checkers, - List bootstraps) { + List bootstraps, + io.teaql.core.checker.CheckerPresentation.Model checkerPresentation) { this.metadataAssemblers = Collections.unmodifiableList(new ArrayList<>(metadataAssemblers)); this.checkers = Collections.unmodifiableList(new ArrayList<>(checkers)); this.bootstraps = Collections.unmodifiableList(new ArrayList<>(bootstraps)); + this.checkerPresentation = checkerPresentation; } public static RuntimeModule of(EntityMetaAssembler... metadataAssemblers) { Objects.requireNonNull(metadataAssemblers, "metadataAssemblers"); Arrays.stream(metadataAssemblers).forEach(assembler -> Objects.requireNonNull(assembler, "metadataAssembler")); - return new RuntimeModule(Arrays.asList(metadataAssemblers), Collections.emptyList(), Collections.emptyList()); + return new RuntimeModule(Arrays.asList(metadataAssemblers), Collections.emptyList(), Collections.emptyList(), + io.teaql.core.checker.CheckerPresentation.Model.empty()); } /** Adds generated model checkers to this passive manifest. */ @@ -35,16 +39,23 @@ public RuntimeModule withCheckers(Checker... checkers) { List> combined = new ArrayList<>(this.checkers); Arrays.stream(checkers).forEach(checker -> combined.add(Objects.requireNonNull(checker, "checker"))); - return new RuntimeModule(metadataAssemblers, combined, bootstraps); + return new RuntimeModule(metadataAssemblers, combined, bootstraps, checkerPresentation); } /** Adds generated typed bootstrap code while keeping installation passive. */ public RuntimeModule withBootstrap(GeneratedSchemaBootstrap bootstrap) { List combined = new ArrayList<>(bootstraps); combined.add(Objects.requireNonNull(bootstrap, "bootstrap")); - return new RuntimeModule(metadataAssemblers, checkers, combined); + return new RuntimeModule(metadataAssemblers, checkers, combined, checkerPresentation); } + /** Adds immutable generated vocabulary and explicit canonical/alias mappings; installation performs no I/O. */ + public RuntimeModule withCheckerPresentation(io.teaql.core.checker.CheckerPresentation.Model model) { + return new RuntimeModule(metadataAssemblers, checkers, bootstraps, Objects.requireNonNull(model, "model")); + } + + public io.teaql.core.checker.CheckerPresentation.Model checkerPresentation() { return checkerPresentation; } + public RuntimeModule and(RuntimeModule other) { Objects.requireNonNull(other, "other"); List combined = new ArrayList<>(metadataAssemblers); @@ -53,7 +64,7 @@ public RuntimeModule and(RuntimeModule other) { combinedCheckers.addAll(other.checkers); List combinedBootstraps = new ArrayList<>(bootstraps); combinedBootstraps.addAll(other.bootstraps); - return new RuntimeModule(combined, combinedCheckers, combinedBootstraps); + return new RuntimeModule(combined, combinedCheckers, combinedBootstraps, checkerPresentation.merge(other.checkerPresentation)); } public void install(EntityMetaFactory metadata) { diff --git a/teaql-core/src/main/java/io/teaql/core/SearchRequest.java b/teaql-core/src/main/java/io/teaql/core/SearchRequest.java index a421b4bda..a9ab8ac06 100644 --- a/teaql-core/src/main/java/io/teaql/core/SearchRequest.java +++ b/teaql-core/src/main/java/io/teaql/core/SearchRequest.java @@ -58,6 +58,10 @@ default T internalNewEntity() { @com.fasterxml.jackson.annotation.JsonIgnore default Map queryOperations() { return Map.of(); } + @com.fasterxml.jackson.annotation.JsonIgnore + @FrameworkInternal("Generator-supplied statistical navigation, not query JSON") + default QueryOperation rollUpOperation(String relation) { return null; } + @com.fasterxml.jackson.annotation.JsonIgnore default QueryOperation pageCountOperation() { return null; } @@ -100,6 +104,9 @@ default String purpose() { SearchCriteria getSearchCriteria(); + /** Conditions on named statistical results, evaluated after grouping. */ + default SearchCriteria getHaving() { return null; } + Aggregations getAggregations(); Map getPropagateAggregations(); @@ -143,7 +150,7 @@ default boolean hasSimpleAgg() { if (aggregations == null) { return false; } - return !aggregations.getAggregates().isEmpty(); + return !aggregations.getAggregates().isEmpty() || !aggregations.getDimensions().isEmpty(); } default List dataProperties(UserContext context) { @@ -168,7 +175,7 @@ default List dataProperties(UserContext context) { } String partitionProperty = getPartitionProperty(); - if (partitionProperty != null && getSlice().getSize() != 0) { + if (partitionProperty != null && getSlice() != null && getSlice().getSize() != 0) { allRelationProperties.add(partitionProperty); } diff --git a/teaql-core/src/main/java/io/teaql/core/Slice.java b/teaql-core/src/main/java/io/teaql/core/Slice.java index e7974de04..46afc56cc 100644 --- a/teaql-core/src/main/java/io/teaql/core/Slice.java +++ b/teaql-core/src/main/java/io/teaql/core/Slice.java @@ -3,6 +3,17 @@ public class Slice { private int offset; private int size = 1000; + // Execution semantics, not a query JSON property. Defaults are outer-page + // policy; only an explicitly configured page can bound a nested population. + private boolean explicitPage; + + public boolean hasExplicitPage() { return explicitPage; } + + public Slice copy() { + Slice copy = new Slice(); + copy.offset = offset; copy.size = size; copy.explicitPage = explicitPage; + return copy; + } public int getOffset() { return offset; @@ -10,6 +21,7 @@ public int getOffset() { public void setOffset(int pOffset) { offset = pOffset; + explicitPage = true; } public int getSize() { @@ -18,5 +30,6 @@ public int getSize() { public void setSize(int pSize) { size = pSize; + explicitPage = true; } } diff --git a/teaql-core/src/main/java/io/teaql/core/SqlExecutionTrace.java b/teaql-core/src/main/java/io/teaql/core/SqlExecutionTrace.java index 5d7893526..931c05f83 100644 --- a/teaql-core/src/main/java/io/teaql/core/SqlExecutionTrace.java +++ b/teaql-core/src/main/java/io/teaql/core/SqlExecutionTrace.java @@ -7,7 +7,15 @@ public record SqlExecutionTrace(List source, List mutationLineage, String operation, @com.fasterxml.jackson.annotation.JsonIgnore java.util.function.Consumer statementObserver, @com.fasterxml.jackson.annotation.JsonIgnore MutationIntent mutationIntent, - @com.fasterxml.jackson.annotation.JsonIgnore QueryRequestScope queryScope) { + @com.fasterxml.jackson.annotation.JsonIgnore QueryRequestScope queryScope, + @com.fasterxml.jackson.annotation.JsonIgnore List requestTree) { + public SqlExecutionTrace(List source, List mutationLineage, String operation, + java.util.function.Consumer observer, MutationIntent intent, QueryRequestScope scope) { + this(source, mutationLineage, operation, observer, intent, scope, List.of()); + } + public SqlExecutionTrace withRequestTree(List nodes) { + return new SqlExecutionTrace(source, mutationLineage, operation, statementObserver, mutationIntent, queryScope, nodes); + } public SqlExecutionTrace(List source, List mutationLineage, String operation, java.util.function.Consumer statementObserver, MutationIntent mutationIntent) { this(source, mutationLineage, operation, statementObserver, mutationIntent, null); @@ -22,10 +30,11 @@ public SqlExecutionTrace(List source, List mutationLineage /** Invocation-owned collection; never installed on Context or a cached repository. */ public SqlExecutionTrace collecting(java.util.function.Consumer observer) { - return new SqlExecutionTrace(source, mutationLineage, operation, observer, mutationIntent, queryScope); + return new SqlExecutionTrace(source, mutationLineage, operation, observer, mutationIntent, queryScope, requestTree); } public void recordStatement(ExecutionMetadata metadata) { + metadata.setRequestTree(requestTree); var path = SqlTracePath.canonical(metadata.getTraceChain(), metadata.getBackend(), operation); metadata.setTraceChain(path.path()); metadata.setComment(path.comment()); @@ -44,6 +53,7 @@ public void recordStatement(ExecutionMetadata metadata) { public SqlExecutionTrace { source = List.copyOf(source); mutationLineage = List.copyOf(mutationLineage); + requestTree = List.copyOf(requestTree); } public static SqlExecutionTrace mutation(Entity entity, List lineage, String operation, @@ -74,6 +84,7 @@ public SqlExecutionTrace readback(MutationIntent intent) { } public void applyTo(ExecutionMetadata metadata) { + metadata.setRequestTree(requestTree); metadata.setTraceChain(source); if (queryScope != null) metadata.setRequestTraceChain(queryScope.traceChain()); metadata.setMutationLineage(mutationLineage); diff --git a/teaql-core/src/main/java/io/teaql/core/SubQuerySearchCriteria.java b/teaql-core/src/main/java/io/teaql/core/SubQuerySearchCriteria.java index c50efdbc0..5284fa56c 100644 --- a/teaql-core/src/main/java/io/teaql/core/SubQuerySearchCriteria.java +++ b/teaql-core/src/main/java/io/teaql/core/SubQuerySearchCriteria.java @@ -9,14 +9,23 @@ public class SubQuerySearchCriteria implements SearchCriteria, PropertyAware { private String propertyName; private SearchRequest dependsOn; private String dependsOnPropertyName; + private final boolean navigationOwned; public SubQuerySearchCriteria( String pPropertyName, SearchRequest pDependsOn, String pDependsOnPropertyName) { + this(pPropertyName, pDependsOn, pDependsOnPropertyName, false); + } + + SubQuerySearchCriteria(String pPropertyName, SearchRequest pDependsOn, + String pDependsOnPropertyName, boolean navigationOwned) { propertyName = pPropertyName; dependsOn = pDependsOn; dependsOnPropertyName = pDependsOnPropertyName; + this.navigationOwned = navigationOwned; } + boolean navigationOwned() { return navigationOwned; } + public String getPropertyName() { return propertyName; } diff --git a/teaql-core/src/main/java/io/teaql/core/UserContext.java b/teaql-core/src/main/java/io/teaql/core/UserContext.java index 44c613f91..7c87013c2 100644 --- a/teaql-core/src/main/java/io/teaql/core/UserContext.java +++ b/teaql-core/src/main/java/io/teaql/core/UserContext.java @@ -24,6 +24,9 @@ public interface UserContext extends OptNullBasicTypeFromObjectGetter { String TEAQL_LOCALE = "teaql.locale"; String TEAQL_I18N_CATALOG = "teaql.i18n.catalog"; + String TEAQL_CHECKER_MESSAGES = "teaql.checker.messages"; + String TEAQL_CHECKER_PRESENTATION_MODEL = "teaql.checker.presentation.model"; + String TEAQL_CHECKER_MESSAGE_RENDERER = "teaql.checker.message.renderer"; String TEAQL_ACTIVE_ROOT = "teaql.active.root"; String TEAQL_FIX_EVIDENCE_CURRENT = "teaql.fix.evidence.current"; String TEAQL_FIX_EVIDENCE_LAST = "teaql.fix.evidence.last"; @@ -147,6 +150,45 @@ default I18nCatalog i18nCatalog() { return catalog == null ? I18nCatalog.builtin() : catalog; } + /** Trusted composition only; never hydrate these resources from query or mutation JSON. */ + default UserContext installCheckerMessageCatalog(io.teaql.core.i18n.CheckerMessageCatalog catalog) { + putAttribute(TEAQL_CHECKER_MESSAGES, java.util.Objects.requireNonNull(catalog, "catalog")); + return this; + } + + default io.teaql.core.i18n.CheckerMessageCatalog checkerMessageCatalog() { + Object value = getAttribute(TEAQL_CHECKER_MESSAGES); + return value instanceof io.teaql.core.i18n.CheckerMessageCatalog catalog ? catalog + : io.teaql.core.i18n.CheckerMessageCatalog.builtin(); + } + + default UserContext installCheckerPresentationModel(io.teaql.core.checker.CheckerPresentation.Model model) { + putAttribute(TEAQL_CHECKER_PRESENTATION_MODEL, java.util.Objects.requireNonNull(model, "model")); + return this; + } + + default io.teaql.core.checker.CheckerPresentation.Model checkerPresentationModel() { + Object value = getAttribute(TEAQL_CHECKER_PRESENTATION_MODEL); + return value instanceof io.teaql.core.checker.CheckerPresentation.Model model ? model + : io.teaql.core.checker.CheckerPresentation.Model.empty(); + } + + default UserContext installCheckerMessageRenderer(io.teaql.core.checker.CheckerMessageRenderer renderer) { + putAttribute(TEAQL_CHECKER_MESSAGE_RENDERER, java.util.Objects.requireNonNull(renderer, "renderer")); + return this; + } + + default io.teaql.core.checker.CheckerMessageRenderer checkerMessageRenderer() { + Object value = getAttribute(TEAQL_CHECKER_MESSAGE_RENDERER); + return value instanceof io.teaql.core.checker.CheckerMessageRenderer renderer ? renderer + : io.teaql.core.checker.CheckerMessageRenderer.STANDARD; + } + + /** Value-free quality diagnostics; application adapters may collect these fixed framework codes. */ + default void checkerMessageWarning(String code) { + System.getLogger("io.teaql.core.checker.messages").log(System.Logger.Level.WARNING, code); + } + default CheckResult translateCheckResult(CheckResult result) { io.teaql.core.checker.internal.CheckerDiagnostics.translate(this, List.of(result)); return result; diff --git a/teaql-core/src/main/java/io/teaql/core/checker/CheckResult.java b/teaql-core/src/main/java/io/teaql/core/checker/CheckResult.java index 0514d1ab0..79efc8fcb 100644 --- a/teaql-core/src/main/java/io/teaql/core/checker/CheckResult.java +++ b/teaql-core/src/main/java/io/teaql/core/checker/CheckResult.java @@ -14,6 +14,8 @@ public class CheckResult { private String naturalLanguageStatement; private String sourceInstancePath; + @com.fasterxml.jackson.annotation.JsonIgnore + private CheckerPresentation presentation; public static CheckResult required(ObjectLocation location) { CheckResult checkResult = new CheckResult(); @@ -105,8 +107,16 @@ public ObjectLocation getLocation() { public void setLocation(ObjectLocation pLocation) { location = pLocation; + if (presentation != null) presentation = presentation.relocate(pLocation); } + /** Internal immutable model/path snapshot; intentionally absent from wire serialization. */ + @com.fasterxml.jackson.annotation.JsonIgnore + public CheckerPresentation getPresentation() { return presentation; } + + @com.fasterxml.jackson.annotation.JsonIgnore + public void setPresentation(CheckerPresentation presentation) { this.presentation = presentation; } + public String getRootType() { return rootType; } 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..b4801b370 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) { @@ -223,6 +245,7 @@ default void appendResult(UserContext context, CheckResult result) { if (result.getRootType() == null || result.getRootType().isBlank()) { result.setRootType(type()); } + io.teaql.core.checker.internal.CheckerMessageRendering.bind(context, result); context.translateCheckResult(result); java.util.List list = (java.util.List) CheckerInvocation.attribute(context, TEAQL_DATA_CHECK_RESULT); if (list == null) { @@ -246,7 +269,7 @@ default void checkAndFix(UserContext context, T entity) { checkAndFix(context, entity, null); return; } - try (var invocation = CheckerInvocation.open(context)) { + try (var invocation = CheckerInvocation.open(context, entity == null ? type() : entity.typeName())) { checkAndFix(context, entity, null); java.util.List violations = (java.util.List) invocation.attribute(TEAQL_DATA_CHECK_RESULT); diff --git a/teaql-core/src/main/java/io/teaql/core/checker/CheckerMessageRenderer.java b/teaql-core/src/main/java/io/teaql/core/checker/CheckerMessageRenderer.java new file mode 100644 index 000000000..6ad131203 --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/checker/CheckerMessageRenderer.java @@ -0,0 +1,24 @@ +package io.teaql.core.checker; + +import io.teaql.core.i18n.CheckerMessageCatalog; +import java.util.Map; +import java.util.Objects; +import java.util.function.Consumer; + +/** Trusted application SPI. Input has projected scalar arguments, never entities or a mutable Context. */ +@FunctionalInterface +public interface CheckerMessageRenderer { + String render(Request request); + + record Request(CheckerPresentation presentation, CheckerMessageCatalog catalog, + CheckerMessageCatalog.Selection selection, Map arguments, + Consumer warningSink) { + public Request { + Objects.requireNonNull(presentation); Objects.requireNonNull(catalog); + Objects.requireNonNull(selection); arguments = Map.copyOf(arguments); Objects.requireNonNull(warningSink); + } + } + + CheckerMessageRenderer STANDARD = request -> request.presentation().render(request.catalog(), + request.selection(), request.arguments(), request.warningSink()); +} 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..c4b3a2948 --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/checker/CheckerPresentation.java @@ -0,0 +1,208 @@ +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) { + private static final Model EMPTY = new Model("unconfigured", Map.of(), io.teaql.core.i18n.CheckerMessageDefaults.currentObjectLabels()); + 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"); + } + public static Model empty() { return EMPTY; } + + /** Parse passive generated descriptors once at module composition, never during rendering. */ + public static Model fromJson(String source) { return CheckerPresentationJson.parse(source); } + + /** Compose passive generated modules once; conflicting identities require an explicit model decision. */ + public Model merge(Model other) { + Objects.requireNonNull(other); + if (this == EMPTY) return other; + if (other == EMPTY || this == other) return this; + Map combined = new HashMap<>(entities); + Map labels = new EnumMap<>(Locale.class); labels.putAll(currentObject); + boolean changed = false; + for (var entry : other.entities.entrySet()) { + Entity previous = combined.putIfAbsent(entry.getKey(), entry.getValue()); + if (previous == null) changed = true; + else if (!previous.labels.equals(entry.getValue().labels) || !previous.fields.equals(entry.getValue().fields)) + throw new IllegalArgumentException("Conflicting Checker presentation entity metadata"); + } + for (var entry : other.currentObject.entrySet()) { + String previous = labels.putIfAbsent(entry.getKey(), entry.getValue()); + if (previous == null) changed = true; + else if (!previous.equals(entry.getValue())) throw new IllegalArgumentException("Conflicting Checker current-object vocabulary"); + } + return changed ? new Model(revision + "+" + other.revision, combined, labels) : this; + } + } + + 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 if (cursor.getClass() == ObjectLocation.class && cursor.getParent() == null) { /* root anchor, not a property */ } + 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(); } + + /** A caller relocating a violation keeps its captured origin, even after the invocation has closed. */ + public CheckerPresentation relocate(ObjectLocation location) { return capture(model, rootType, location); } + + /** 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(locale); + return render(catalog, catalog.select(locale, rule, shape), safeArguments, warningSink); + } + + /** Render with a previously resolved template so grammar and constraint units use that Locale. */ + public String render(CheckerMessageCatalog catalog, CheckerMessageCatalog.Selection selection, + Map safeArguments, Consumer warningSink) { + Objects.requireNonNull(catalog); Objects.requireNonNull(selection); 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. */ } + }; + 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/checker/CheckerPresentationJson.java b/teaql-core/src/main/java/io/teaql/core/checker/CheckerPresentationJson.java new file mode 100644 index 000000000..259b3c5ab --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/checker/CheckerPresentationJson.java @@ -0,0 +1,95 @@ +package io.teaql.core.checker; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.teaql.core.i18n.CheckerMessageDefaults; +import io.teaql.core.i18n.Locale; +import java.io.IOException; +import java.util.*; + +/** Data-only metadata loader. No reflection, resource lookup or object access. */ +final class CheckerPresentationJson { + private CheckerPresentationJson() { } + + static CheckerPresentation.Model parse(String source) { + Objects.requireNonNull(source, "source"); + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION); + mapper.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + JsonNode root = mapper.readTree(source); + object(root, Set.of("schema", "revision", "entities", "currentObject")); + if (!"teaql.checker-model/v1".equals(text(root.get("schema")))) throw invalid(); + String revision = text(root.get("revision")); + JsonNode descriptors = root.get("entities"); + object(descriptors, null); + Map entities = new LinkedHashMap<>(); + var iterator = descriptors.fields(); + while (iterator.hasNext()) { + var entry = iterator.next(); + String identity = text(mapper.getNodeFactory().textNode(entry.getKey())); + JsonNode entity = entry.getValue(); + object(entity, Set.of("labels", "fields")); + JsonNode fieldNodes = entity.get("fields"); + if (fieldNodes == null || !fieldNodes.isArray()) throw invalid(); + List fields = new ArrayList<>(); + for (JsonNode field : fieldNodes) { + object(field, Set.of("name", "targetType", "labels", "classifiers", "aliases")); + String name = text(field.get("name")); + String target = field.has("targetType") ? text(field.get("targetType")) : null; + Set aliases = new HashSet<>(); + if (field.has("aliases")) { + JsonNode aliasNodes = field.get("aliases"); + if (!aliasNodes.isArray()) throw invalid(); + for (JsonNode alias : aliasNodes) if (!aliases.add(text(alias))) throw invalid(); + } + fields.add(new CheckerPresentation.Field(name, target, labels(field.get("labels")), + labels(field.get("classifiers")), aliases)); + } + entities.put(identity, new CheckerPresentation.Entity(labels(entity.get("labels")), fields)); + } + Map current = new EnumMap<>(Locale.class); + current.putAll(CheckerMessageDefaults.currentObjectLabels()); + if (root.has("currentObject")) current.putAll(labels(root.get("currentObject"))); + return new CheckerPresentation.Model(revision, entities, current); + } catch (IOException malformed) { + // Parser diagnostics can contain raw source fragments; do not expose them. + throw invalid(); + } + } + + private static Map labels(JsonNode node) { + if (node == null) return Map.of(); + object(node, null); + Map labels = new EnumMap<>(Locale.class); + var iterator = node.fields(); + while (iterator.hasNext()) { + var entry = iterator.next(); + Locale locale = Locale.fromCode(entry.getKey()); + if (labels.putIfAbsent(locale, text(entry.getValue())) != null) throw invalid(); + } + return labels; + } + + private static void object(JsonNode node, Set allowed) { + if (node == null || !node.isObject()) throw invalid(); + if (allowed != null) node.fieldNames().forEachRemaining(key -> { if (!allowed.contains(key)) throw invalid(); }); + } + + private static String text(JsonNode node) { + if (node == null || !node.isTextual()) throw invalid(); + String value = node.textValue(); + if (value.isBlank() || value.codePoints().anyMatch(character -> { + int kind = Character.getType(character); + return kind == Character.CONTROL || kind == Character.FORMAT + || kind == Character.LINE_SEPARATOR || kind == Character.PARAGRAPH_SEPARATOR; + })) throw invalid(); + return value; + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Checker presentation model"); + } +} diff --git a/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerDiagnostics.java b/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerDiagnostics.java index 1c7cd95e0..fb322ae0d 100644 --- a/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerDiagnostics.java +++ b/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerDiagnostics.java @@ -27,6 +27,7 @@ private static void translate(UserContext context, List results, bo boolean allow=SensitiveValueProjection.plaintextEnabled(); int[] lengths=new int[results.size()]; boolean[] automatic=new boolean[results.size()]; + Set presentationWarnings=new HashSet<>(); for (int i=0;i results, bo for (int i=0;i results, bo // An earlier callback can mention a field whose violation is discovered // later. Redact it before the graph's exception can escape. if (scope != null && scope.attribute(Checker.TEAQL_DATA_CHECK_RESULT) instanceof List previous) - for (Object value : previous) if (value instanceof CheckResult result && !CheckerPresentationCache.isAutomatic(result)) - result.setNaturalLanguageStatement(SensitiveValueProjection.scrub(result.getNaturalLanguageStatement(),secrets)); + for (Object value : previous) if (value instanceof CheckResult result && !results.contains(result)) { + Integer length=CheckerPresentationCache.validationLength(result); + if (length != null) { + var rendered=CheckerMessageRendering.render(context,result,length,secrets,presentationWarnings); + result.setNaturalLanguageStatement(rendered.text()); + CheckerPresentationCache.remember(result,length,rendered.plans()); + } else result.setNaturalLanguageStatement(SensitiveValueProjection.scrub(result.getNaturalLanguageStatement(),secrets)); + } if (invokeHook) for (var result : results) { String before=result.getNaturalLanguageStatement(); context.translateCheckResult(result); diff --git a/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerInvocation.java b/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerInvocation.java index 61619bea0..6172ff6d2 100644 --- a/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerInvocation.java +++ b/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerInvocation.java @@ -29,6 +29,9 @@ private record Completed(WeakReference context, List e private final UserContext context; private final CheckerInvocation parent; private final boolean mutationOnly; + private final io.teaql.core.checker.CheckerPresentation.Model presentationModel; + private final String presentationOrigin; + private final java.util.Set presentationWarnings = new java.util.HashSet<>(); private final Map attributes = new HashMap<>(); private boolean closed; private List diagnosticSecrets; @@ -39,10 +42,12 @@ List diagnosticSecrets() { return diagnosticSecrets; } - private CheckerInvocation(UserContext context, boolean mutationOnly) { + private CheckerInvocation(UserContext context, boolean mutationOnly, String presentationOrigin) { this.context = java.util.Objects.requireNonNull(context, "context"); this.parent = ACTIVE.get(); this.mutationOnly = mutationOnly; + this.presentationOrigin = presentationOrigin; + this.presentationModel = context.checkerPresentationModel(); attributes.put(Checker.TEAQL_DATA_CHECK_RESULT, new ArrayList()); attributes.put(Checker.TEAQL_DATA_CHECKED_ITEMS, new ArrayList<>()); attributes.put(UserContext.TEAQL_FIX_EVIDENCE_CURRENT, new ArrayList()); @@ -53,14 +58,28 @@ private CheckerInvocation(UserContext context, boolean mutationOnly) { /** Internal synchronous runtime boundary; do not open scopes in business code. */ public static CheckerInvocation open(UserContext context) { - return new CheckerInvocation(context, false); + return open(context, null); + } + + public static CheckerInvocation open(UserContext context, String origin) { + return new CheckerInvocation(context, false, origin); } /** Save validates changed objects, not untouched partial reference details. */ public static CheckerInvocation openMutation(UserContext context) { - return new CheckerInvocation(context, true); + return openMutation(context, null); + } + + public static CheckerInvocation openMutation(UserContext context, String origin) { + return new CheckerInvocation(context, true, origin); } + public io.teaql.core.checker.CheckerPresentation presentation(io.teaql.core.checker.ObjectLocation location) { + return io.teaql.core.checker.CheckerPresentation.capture(presentationModel, presentationOrigin, location); + } + + boolean firstPresentationWarning(String code) { return presentationWarnings.add(code); } + public boolean mutationOnly() { return mutationOnly; } @@ -126,6 +145,7 @@ public void close() { else ACTIVE.set(parent); attributes.clear(); if (diagnosticSecrets != null) diagnosticSecrets.clear(); + presentationWarnings.clear(); closed = true; } } diff --git a/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerMessageRendering.java b/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerMessageRendering.java new file mode 100644 index 000000000..7ec8a7353 --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerMessageRendering.java @@ -0,0 +1,182 @@ +package io.teaql.core.checker.internal; + +import io.teaql.core.UserContext; +import io.teaql.core.checker.*; +import io.teaql.core.i18n.*; +import io.teaql.core.utils.SensitiveValueProjection; +import java.util.*; +import java.util.function.Consumer; + +/** Connects already-projected Checker results to pure presentation, without data or clock access. */ +public final class CheckerMessageRendering { + private static final Set WARNING_CODES = Set.of("CHECKER_MESSAGE_LABEL_FALLBACK", + "CHECKER_MESSAGE_RENDER_FALLBACK", "CHECKER_MESSAGE_GENERIC_RULE"); + private CheckerMessageRendering() {} + + public static void bind(UserContext context, CheckResult result) { + if (result.getPresentation() != null) return; + var scope = CheckerInvocation.current(context); + try { + result.setPresentation(scope == null + ? CheckerPresentation.capture(context.checkerPresentationModel(), null, result.getLocation()) + : scope.presentation(result.getLocation())); + } catch (RuntimeException ignored) { + warning(context, scope, new HashSet<>(), "CHECKER_MESSAGE_RENDER_FALLBACK"); + result.setPresentation(fallbackPresentation(result)); + } + } + + private static CheckerPresentation fallbackPresentation(CheckResult result) { + try { return CheckerPresentation.capture(CheckerPresentation.Model.empty(), null, result.getLocation()); } + catch (RuntimeException ignored) { return CheckerPresentation.capture(CheckerPresentation.Model.empty(), null, null); } + } + + private static void warning(UserContext context, CheckerInvocation scope, Set localWarnings, String code) { + String known = canonicalWarning(code); + if (localWarnings.add(known) && (scope == null || scope.firstPresentationWarning(known))) { + try { context.checkerMessageWarning(known); } catch (RuntimeException ignored) { /* Logging must not replace a Checker failure. */ } + } + } + + private static String canonicalWarning(String code) { + return code != null && WARNING_CODES.contains(code) ? code : "CHECKER_MESSAGE_RENDER_FALLBACK"; + } + + private record Key(io.teaql.core.i18n.Locale locale, CheckerMessageCatalog.Shape shape) {} + private record Plan(CheckerMessageCatalog.Selection selection, CheckerMessageCatalog.Template legacy, + io.teaql.core.i18n.Locale locale, boolean generic, boolean custom) { + Plan project(java.util.function.UnaryOperator projection) { + return new Plan(custom ? new CheckerMessageCatalog.Selection(selection.template().projectLiterals(projection), selection.locale()) : selection, + legacy == null ? null : legacy.projectLiterals(projection), locale, generic, custom); + } + } + + /** Exactly one rule's 15 Locale x 3 shape plans, or a safe customer literal; never a callback. */ + static final class Plans { + private final String rule; + private final CheckerMessageCatalog catalog; + private final Map entries; + private final String literal; + private Plans(String rule, CheckerMessageCatalog catalog, Map entries, String literal) { + this.rule = rule; this.catalog = catalog; this.entries = Map.copyOf(entries); this.literal = literal; + } + private Plans project(List secrets) { + if (secrets.isEmpty()) return this; + java.util.function.UnaryOperator projection = text -> SensitiveValueProjection.scrub(text, secrets); + if (literal != null) return new Plans(rule, CheckerMessageCatalog.builtin(), Map.of(), projection.apply(literal)); + Map projected = new HashMap<>(); entries.forEach((key, plan) -> projected.put(key, plan.project(projection))); + return new Plans(rule, catalog.projectForRule(rule, projection), projected, null); + } + private Plan get(io.teaql.core.i18n.Locale locale, CheckerMessageCatalog.Shape shape) { + return entries.get(new Key(locale, shape)); + } + } + + record Rendered(String text, Plans plans) {} + + private static Plans prepare(UserContext context, String rule, List secrets) { + var catalog = context.checkerMessageCatalog().projectForRule(rule, text -> SensitiveValueProjection.scrub(text, secrets)); + var legacy = context.i18nCatalog(); + Map entries = new HashMap<>(); + for (var locale : io.teaql.core.i18n.Locale.values()) for (var shape : CheckerMessageCatalog.Shape.values()) { + Plan plan = null; + for (var candidate : locale == io.teaql.core.i18n.Locale.ENGLISH ? List.of(locale) + : List.of(locale, io.teaql.core.i18n.Locale.ENGLISH)) { + var selection = catalog.override(candidate, rule, shape); + if (selection != null) { plan = new Plan(selection, null, candidate, false, true); break; } + String application = legacy.applicationMessage(candidate, rule); + if (application != null) { + var template = CheckerMessageCatalog.legacyTemplate(application) + .projectLiterals(text -> SensitiveValueProjection.scrub(text, secrets)); + plan = new Plan(null, template, candidate, false, false); break; + } + selection = CheckerMessageCatalog.builtin().lookup(candidate, rule, shape); + if (selection != null) { plan = new Plan(selection, null, candidate, false, false); break; } + } + if (plan == null) plan = new Plan(CheckerMessageCatalog.builtin().select(locale, "checker.invalid", shape), null, locale, true, false); + entries.put(new Key(locale, shape), plan); + } + return new Plans(rule, catalog, entries, null); + } + + static Rendered render(UserContext context, CheckResult result, int validationLength, + List diagnosticSecrets, Set localWarnings) { + Consumer warn = code -> warning(context, CheckerInvocation.current(context), localWarnings, code); + // Unsupported explicit Locales are still typed configuration errors, not a language fallback. + io.teaql.core.i18n.Locale locale = Objects.requireNonNullElse(context.locale(), io.teaql.core.i18n.Locale.ENGLISH); + try { + bind(context, result); + var presentation = result.getPresentation(); + String rule = I18nCatalog.messageKey(result); + var previous = CheckerPresentationCache.plans(result); + boolean initial = previous == null || !previous.rule.equals(rule); + Plans plans = (initial ? prepare(context, rule, diagnosticSecrets) : previous).project(diagnosticSecrets); + if (plans.literal != null) return new Rendered(plans.literal, plans); + Plan plan = plans.get(locale, presentation.shape()); + if (plan.generic()) warn.accept("CHECKER_MESSAGE_GENERIC_RULE"); + Map arguments = arguments(result, validationLength, plan.locale()); + if (plan.legacy() != null) { + arguments.put("location", canonicalLocation(result.getLocation())); + arguments.putIfAbsent("input", "null"); arguments.putIfAbsent("system", "null"); + return new Rendered(plan.legacy().render(arguments), plans); + } + var renderer = initial ? context.checkerMessageRenderer() : CheckerMessageRenderer.STANDARD; + if (renderer == CheckerMessageRenderer.STANDARD) + return new Rendered(presentation.render(plans.catalog, plan.selection(), arguments, warn), plans); + // The SPI may retain its input. Do not hand it a callback capturing UserContext or an invocation. + Set queuedWarnings = new LinkedHashSet<>(); + Consumer queue = code -> queuedWarnings.add(canonicalWarning(code)); + String message; + try { message = renderer.render(new CheckerMessageRenderer.Request(presentation, plans.catalog, plan.selection(), arguments, queue)); } + finally { queuedWarnings.forEach(warn); } + if (message == null || message.isBlank()) throw new IllegalArgumentException("Empty rendered Checker message"); + message = SensitiveValueProjection.scrub(message, diagnosticSecrets); + return new Rendered(message, new Plans(rule, CheckerMessageCatalog.builtin(), Map.of(), message)); + } catch (io.teaql.core.i18n.UnsupportedLocaleException unsupported) { throw unsupported; } + catch (RuntimeException failure) { + // Do not disclose provider causes or lose the original rule and structured location. + warn.accept("CHECKER_MESSAGE_RENDER_FALLBACK"); + var presentation = result.getPresentation(); + if (presentation == null) presentation = fallbackPresentation(result); + // Failed customer callbacks are not retried during exception aggregation or relocation. + Map generic = new HashMap<>(); + for (var candidate : io.teaql.core.i18n.Locale.values()) for (var shape : CheckerMessageCatalog.Shape.values()) + generic.put(new Key(candidate, shape), new Plan(CheckerMessageCatalog.builtin().select(candidate, "checker.invalid", shape), null, candidate, false, false)); + Plans plans = new Plans(I18nCatalog.messageKey(result), CheckerMessageCatalog.builtin(), generic, null); + return new Rendered(presentation.render(plans.catalog, plans.get(locale, presentation.shape()).selection(), Map.of(), warn), plans); + } + } + + private static Map arguments(CheckResult result, int validationLength, io.teaql.core.i18n.Locale locale) { + Map values = new HashMap<>(); + if (result.getSystemValue() != null) values.put("system", scalar(result.getSystemValue())); + if (result.getInputValue() != null) values.put("input", scalar(result.getInputValue())); + values.put("input_len", validationLength); + // Java's existing String/CharSequence length constraints measure UTF-16 code units. + values.put("unit", CheckerMessageDefaults.unit(locale, "utf16")); + return values; + } + + private static String canonicalLocation(ObjectLocation location) { + Deque steps = new ArrayDeque<>(); + for (var cursor = location; cursor != null; cursor = cursor.getParent()) steps.addFirst(cursor); + StringBuilder path = new StringBuilder(); + for (var step : steps) { + if (step instanceof HashLocation hash) { + if (!path.isEmpty()) path.append('.'); path.append(hash.getMember()); + } else if (step instanceof ArrayLocation array) path.append('[').append(array.getIndex()).append(']'); + } + return path.toString(); + } + + private static Object scalar(Object value) { + if (value == null) return "null"; + Class type = value.getClass(); + if (type == String.class || 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) return value; + if (type == Boolean.class || type == java.time.LocalDate.class || type == java.time.LocalDateTime.class + || type == java.time.Instant.class) return value.toString(); + return "[value omitted]"; + } +} diff --git a/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerPresentationCache.java b/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerPresentationCache.java index 46878d72a..7158c386f 100644 --- a/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerPresentationCache.java +++ b/teaql-core/src/main/java/io/teaql/core/checker/internal/CheckerPresentationCache.java @@ -9,9 +9,9 @@ import java.util.Map; import java.util.WeakHashMap; -/** Safe presentation provenance only: no raw message, input, entity or Context. */ +/** Fingerprints, original measurement and finite safe plans; no raw input, entity or Context. */ final class CheckerPresentationCache { - private record Entry(int length, byte[] messageDigest, byte[] inputDigest) {} + private record Entry(int length, byte[] messageDigest, byte[] inputDigest, CheckerMessageRendering.Plans plans) {} private static final Map GENERATED=Collections.synchronizedMap(new WeakHashMap<>()); private CheckerPresentationCache() {} @@ -25,8 +25,13 @@ static Integer validationLength(CheckResult result) { static boolean isAutomatic(CheckResult result) { return automaticEntry(result) != null; } - static void remember(CheckResult result,int validationLength) { - GENERATED.put(result,new Entry(validationLength,digest(result.getNaturalLanguageStatement()),inputDigest(result.getInputValue()))); + static CheckerMessageRendering.Plans plans(CheckResult result) { + Entry entry = automaticEntry(result); + return entry == null ? null : entry.plans(); + } + + static void remember(CheckResult result,int validationLength, CheckerMessageRendering.Plans plans) { + GENERATED.put(result,new Entry(validationLength,digest(result.getNaturalLanguageStatement()),inputDigest(result.getInputValue()),plans)); } static void forget(CheckResult result) { GENERATED.remove(result); } 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-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..e3129e67a --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/i18n/CheckerMessageCatalog.java @@ -0,0 +1,289 @@ +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); } + + /** Project custom literals only; typed placeholders are never scrubbed or recompiled. */ + public Template projectLiterals(java.util.function.UnaryOperator projection) { + return new Template(nodes.stream().map(node -> node.argument() == null + ? new Node(projection.apply(node.literal()), null) : node).toList()); + } + + 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; } + + /** Retain only this rule and location patterns, with no unprojected application text. */ + public CheckerMessageCatalog projectForRule(String rule, java.util.function.UnaryOperator projection) { + Objects.requireNonNull(rule); Objects.requireNonNull(projection); + if (builtin) return this; // Public built-in vocabulary must not be scrubbed as rejected input. + Map safe = new EnumMap<>(Locale.class); + for (var entry : locales.entrySet()) { + Map shapes = new EnumMap<>(Shape.class); + entry.getValue().rules().getOrDefault(rule, Map.of()).forEach((shape, template) -> + shapes.put(shape, template.projectLiterals(projection))); + Map patterns = new HashMap<>(); + entry.getValue().patterns().forEach((name, template) -> patterns.put(name, template.projectLiterals(projection))); + safe.put(entry.getKey(), new Messages(shapes.isEmpty() ? Map.of() : Map.of(rule, Map.copyOf(shapes)), + Map.copyOf(patterns), entry.getValue().separator() == null ? null : projection.apply(entry.getValue().separator()))); + } + return new CheckerMessageCatalog(safe, false); + } + + /** Legacy placeholders are compiled once; unknown braces remain literal compatibility text. */ + public static Template legacyTemplate(String source) { + Objects.requireNonNull(source); + List nodes = new ArrayList<>(); StringBuilder literal = new StringBuilder(); + for (int i = 0; i < source.length();) { + String argument = null; + for (String name : List.of("location", "system", "input", "input_len")) + if (source.startsWith("{" + name + "}", i)) { argument = name; break; } + if (argument == null) { literal.append(source.charAt(i++)); continue; } + if (!literal.isEmpty()) { nodes.add(new Node(literal.toString(), null)); literal.setLength(0); } + nodes.add(new Node(null, argument)); i += argument.length() + 2; + } + if (!literal.isEmpty()) nodes.add(new Node(literal.toString(), null)); + return new Template(nodes); + } + + /** 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); + } + + /** Exact-locale lookup without fallback, for composition with explicit legacy application overrides. */ + public Selection lookup(Locale locale, String rule, Shape shape) { + 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/java/io/teaql/core/i18n/CheckerMessageDefaults.java b/teaql-core/src/main/java/io/teaql/core/i18n/CheckerMessageDefaults.java new file mode 100644 index 000000000..d95782d86 --- /dev/null +++ b/teaql-core/src/main/java/io/teaql/core/i18n/CheckerMessageDefaults.java @@ -0,0 +1,49 @@ +package io.teaql.core.i18n; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.util.*; + +/** Shared immutable runtime vocabulary, loaded once during composition, never while rendering. */ +public final class CheckerMessageDefaults { + private static final Map> VALUES = load(); + private static final Map CURRENT = currentObjects(); + private CheckerMessageDefaults() {} + + public static Map currentObjectLabels() { return CURRENT; } + + /** Select the unit actually measured by a Checker, not a conversion of that measurement. */ + public static String unit(Locale locale, String countingUnit) { + String value = VALUES.get(locale).get(countingUnit); + if (value == null || "currentObject".equals(countingUnit)) throw new IllegalArgumentException("Unsupported Checker counting unit"); + return value; + } + + private static Map currentObjects() { + Map result = new EnumMap<>(Locale.class); + VALUES.forEach((locale, labels) -> result.put(locale, labels.get("currentObject"))); + return Map.copyOf(result); + } + + private static Map> load() { + try (var input = CheckerMessageDefaults.class.getResourceAsStream("checker-presentation-v1.json")) { + if (input == null) throw new IllegalArgumentException("Missing Checker presentation defaults"); + var root = new ObjectMapper().readTree(input); + if (!"teaql.checker-presentation/v1".equals(root.path("schema").asText())) + throw new IllegalArgumentException("Unsupported Checker presentation defaults"); + Map> result = new EnumMap<>(Locale.class); + root.path("locales").fields().forEachRemaining(entry -> { + Map labels = new HashMap<>(); + for (String key : List.of("currentObject", "utf16", "scalar", "byte")) { + var value = entry.getValue().path(key); + if (!value.isTextual() || value.textValue().isBlank()) throw new IllegalArgumentException("Incomplete Checker presentation defaults"); + labels.put(key, value.textValue()); + } + if (result.put(Locale.fromCode(entry.getKey()), Map.copyOf(labels)) != null) + throw new IllegalArgumentException("Duplicate Checker presentation Locale"); + }); + if (result.size() != Locale.values().length) throw new IllegalArgumentException("Incomplete Checker presentation Locale set"); + return Map.copyOf(result); + } catch (IOException exception) { throw new ExceptionInInitializerError("Cannot load Checker presentation defaults"); } + } +} diff --git a/teaql-core/src/main/java/io/teaql/core/i18n/I18nCatalog.java b/teaql-core/src/main/java/io/teaql/core/i18n/I18nCatalog.java index 92b6a9ca9..1a9ca9f63 100644 --- a/teaql-core/src/main/java/io/teaql/core/i18n/I18nCatalog.java +++ b/teaql-core/src/main/java/io/teaql/core/i18n/I18nCatalog.java @@ -52,11 +52,7 @@ public String render(CheckResult result, Locale locale) { /** Render projected input while retaining the unit used by the actual validation. */ public String render(CheckResult result, Locale locale, int originalInputLength) { - String key = switch (result.getRuleId()) { - case REQUIRED -> "checker.required"; case MIN -> "checker.min"; case MAX -> "checker.max"; - case MIN_STR_LEN -> "checker.minLength"; case MAX_STR_LEN -> "checker.maxLength"; - default -> "checker." + result.getRuleId().name().toLowerCase(java.util.Locale.ROOT); - }; + String key = messageKey(result); String input = String.valueOf(result.getInputValue()); return message(locale, key) .replace("{location}", String.valueOf(result.getLocation())) @@ -65,6 +61,41 @@ public String render(CheckResult result, Locale locale, int originalInputLength) .replace("{input_len}", String.valueOf(originalInputLength)); } + public static String messageKey(CheckResult result) { + if (result.getRuleId() == null) return "checker.invalid"; + return switch (result.getRuleId()) { + case REQUIRED -> "checker.required"; case MIN -> "checker.min"; case MAX -> "checker.max"; + case MIN_STR_LEN -> "checker.minLength"; case MAX_STR_LEN -> "checker.maxLength"; + default -> "checker." + result.getRuleId().name().toLowerCase(java.util.Locale.ROOT); + }; + } + + /** Exact Locale, explicit application text only. Do not mistake historical built-ins for overrides. */ + public String applicationMessage(Locale locale, String key) { + for (I18nCatalog current = this; current != null && current != BUILTIN; current = current.fallback) { + String value = current.messages.getOrDefault(locale.code(), Map.of()).get(key); + if (value != null && !value.isBlank()) return value; + } + return null; + } + + /** Single-pass compatibility interpolation: keep unknown legacy braces literal, never reparse inserted data. */ + public static String renderApplicationMessage(String template, Map arguments) { + StringBuilder result = new StringBuilder(); + for (int i = 0; i < template.length();) { + if (template.charAt(i) == '{') { + String key = template.startsWith("{location}", i) ? "location" + : template.startsWith("{system}", i) ? "system" + : template.startsWith("{input}", i) ? "input" + : template.startsWith("{input_len}", i) ? "input_len" : null; + String value = key == null ? null : arguments.get(key); + if (value != null) { result.append(value); i += key.length() + 2; continue; } + } + result.append(template.charAt(i++)); + } + return result.toString(); + } + private static I18nCatalog loadBuiltin() { InputStream input = I18nCatalog.class.getResourceAsStream("builtin-messages-v1.json"); if (input == null) throw new ExceptionInInitializerError("Missing built-in i18n 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/main/resources/io/teaql/core/i18n/checker-presentation-v1.json b/teaql-core/src/main/resources/io/teaql/core/i18n/checker-presentation-v1.json new file mode 100644 index 000000000..eefe3e7a8 --- /dev/null +++ b/teaql-core/src/main/resources/io/teaql/core/i18n/checker-presentation-v1.json @@ -0,0 +1,95 @@ +{ + "schema": "teaql.checker-presentation/v1", + "locales": { + "en": { + "currentObject": "current object", + "utf16": "UTF-16 code units", + "scalar": "Unicode scalar values", + "byte": "bytes" + }, + "zh-CN": { + "currentObject": "当前对象", + "utf16": "个 UTF-16 代码单元", + "scalar": "个 Unicode 标量值", + "byte": "字节" + }, + "zh-TW": { + "currentObject": "目前物件", + "utf16": "個 UTF-16 程式碼單元", + "scalar": "個 Unicode 純量值", + "byte": "位元組" + }, + "ja": { + "currentObject": "現在のオブジェクト", + "utf16": "UTF-16コード単位", + "scalar": "Unicodeスカラー値", + "byte": "バイト" + }, + "ko": { + "currentObject": "현재 객체", + "utf16": "UTF-16 코드 단위", + "scalar": "유니코드 스칼라 값", + "byte": "바이트" + }, + "de": { + "currentObject": "aktuelles Objekt", + "utf16": "UTF-16-Codeeinheiten", + "scalar": "Unicode-Skalarwerte", + "byte": "Bytes" + }, + "fr": { + "currentObject": "objet actuel", + "utf16": "unités de code UTF-16", + "scalar": "valeurs scalaires Unicode", + "byte": "octets" + }, + "es": { + "currentObject": "objeto actual", + "utf16": "unidades de código UTF-16", + "scalar": "valores escalares Unicode", + "byte": "bytes" + }, + "pt": { + "currentObject": "objeto atual", + "utf16": "unidades de código UTF-16", + "scalar": "valores escalares Unicode", + "byte": "bytes" + }, + "ar": { + "currentObject": "الكائن الحالي", + "utf16": "وحدات ترميز UTF-16", + "scalar": "قيم Unicode القياسية", + "byte": "بايت" + }, + "th": { + "currentObject": "ออบเจ็กต์ปัจจุบัน", + "utf16": "หน่วยรหัส UTF-16", + "scalar": "ค่าสเกลาร์ Unicode", + "byte": "ไบต์" + }, + "id": { + "currentObject": "objek saat ini", + "utf16": "unit kode UTF-16", + "scalar": "nilai skalar Unicode", + "byte": "bita" + }, + "fil": { + "currentObject": "kasalukuyang bagay", + "utf16": "yunit ng code na UTF-16", + "scalar": "scalar na halaga ng Unicode", + "byte": "byte" + }, + "uk": { + "currentObject": "поточний об’єкт", + "utf16": "кодових одиниць UTF-16", + "scalar": "скалярних значень Unicode", + "byte": "байтів" + }, + "vi": { + "currentObject": "đối tượng hiện tại", + "utf16": "đơn vị mã UTF-16", + "scalar": "giá trị vô hướng Unicode", + "byte": "byte" + } + } +} diff --git a/teaql-core/src/test/java/io/teaql/core/BaseRequestTest.java b/teaql-core/src/test/java/io/teaql/core/BaseRequestTest.java index 7a6ba35ed..e2ee2660e 100644 --- a/teaql-core/src/test/java/io/teaql/core/BaseRequestTest.java +++ b/teaql-core/src/test/java/io/teaql/core/BaseRequestTest.java @@ -142,6 +142,35 @@ public void testDeletedRows() { assertTrue(request.getSearchCriteria() instanceof VersionSearchCriteria); } + @Test + public void havingIsSeparateFromSourceCriteriaAndSurvivesSnapshots() { + request.having("total", Operator.GREATER_THAN, 10L); + var snapshot = new QueryRequestSnapshot<>(request, null); + var condition = snapshot.getHaving(); + request.having("count", Operator.GREATER_THAN, 1L); + request.having("total", Operator.LESS_THAN, 100L); + assertNull(request.getSearchCriteria()); + assertEquals(condition, snapshot.getHaving()); + assertNotEquals(condition, request.getHaving()); + assertEquals(request.getHaving(), new QueryRequestSnapshot<>(request, null).getHaving()); + } + + @Test + public void havingParticipatesInRequestEqualityAndHashing() { + var other = new BaseRequest.TempRequest(BaseEntity.class, "BaseEntity"); + // Hold existing identity-based fields equal while varying HAVING only. + other.setSlice(request.getSlice()); + other.setAggregations(request.getAggregations()); + assertEquals(request, other); + int previousHash = request.hashCode(); + request.having("total", Operator.GREATER_THAN, 10L); + assertNotEquals(request, other); + assertNotEquals(previousHash, request.hashCode()); + other.having("total", Operator.GREATER_THAN, 10L); + assertEquals(request, other); + assertEquals(request.hashCode(), other.hashCode()); + } + @Test public void testSliceAndOrderBy() { request.top(10); 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()); + } +} diff --git a/teaql-core/src/test/java/io/teaql/core/EntityMutationLedgerTest.java b/teaql-core/src/test/java/io/teaql/core/EntityMutationLedgerTest.java index d95112d91..8848fd61a 100644 --- a/teaql-core/src/test/java/io/teaql/core/EntityMutationLedgerTest.java +++ b/teaql-core/src/test/java/io/teaql/core/EntityMutationLedgerTest.java @@ -10,6 +10,20 @@ public class EntityMutationLedgerTest { + @Test + public void recoveryPreservesSubsequentEditsAndItsDistinctVersionTransition() { + var pending = EntityStatus.PERSISTED_DELETED.next(EntityAction.RECOVER).next(EntityAction.UPDATE); + assertEquals(EntityStatus.UPDATED_RECOVER,pending); + assertEquals(EntityStatus.PERSISTED,pending.next(EntityAction.PERSIST)); + var ledger = new EntityMutationLedger(); + var key = new EntityKey("Academy",7L); + ledger.set(key,"campus_code","WEST"); + ledger.markAsRecover(key); + assertEquals("WEST",ledger.get(key,"campus_code")); + assertTrue(ledger.recoveredKeys().contains(key)); + assertEquals(7L,MutationVersions.next(MutationOperationKind.RECOVER,-6L)); + } + private static final EntityKey ORDER = new EntityKey("Order", 1L); private static final EntityKey OTHER_ORDER = new EntityKey("Order", 2L); diff --git a/teaql-core/src/test/java/io/teaql/core/QueryCriteriaAlternativesTest.java b/teaql-core/src/test/java/io/teaql/core/QueryCriteriaAlternativesTest.java new file mode 100644 index 000000000..6619990e6 --- /dev/null +++ b/teaql-core/src/test/java/io/teaql/core/QueryCriteriaAlternativesTest.java @@ -0,0 +1,74 @@ +package io.teaql.core; + +import io.teaql.core.criteria.*; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class QueryCriteriaAlternativesTest { + private static BaseRequest.TempRequest request() { + return new BaseRequest.TempRequest(BaseEntity.class, "School"); + } + private static BaseRequest.TempRequest live() { + var request = request(); + request.appendSearchCriteria(request.createBasicSearchCriteria("version", Operator.GREATER_THAN, 0L)); + return request; + } + private static SearchCriteria condition(String field, long value) { + return new EQ(new PropertyReference(field), new Parameter(field, value, Operator.EQUAL)); + } + private static BaseRequest.TempRequest alternatives() { + var request = live(); + request.appendSearchCriteria(condition("capacity", 100)); + request.appendSearchCriteria(condition("id", 1)); + return request; + } + private static void assertAlternatives(Expression expression) { + assertTrue(expression instanceof OR); + assertEquals(List.of("capacity", "id"), expression.properties(null)); + } + + @Test public void versionOnlyReceiverRetainsItsGuardAndAddsAnOrGroup() { + var receiver = live();var guard = receiver.getSearchCriteria();var source = alternatives(); + receiver.internalMatchAny(source); + var combined = (AND) receiver.getSearchCriteria(); + assertSame(guard, combined.first());assertAlternatives(combined.second()); + assertEquals(3, ((AND) source.getSearchCriteria()).getExpressions().size()); + } + + @Test public void receiverWithoutCriteriaStillAppliesTheAlternatives() { + var receiver = request();receiver.internalMatchAny(alternatives()); + assertAlternatives(receiver.getSearchCriteria()); + } + + @Test public void aSingleExistingConditionIsNotCastToAnd() { + var receiver = request();var existing = condition("owner", 42);receiver.appendSearchCriteria(existing); + receiver.internalMatchAny(alternatives()); + var combined = (AND) receiver.getSearchCriteria(); + assertSame(existing, combined.first());assertAlternatives(combined.second()); + } + + @Test public void emptyOrVersionOnlySourceIsANoOpRatherThanAnEmptyOr() { + var receiver = live();var before = receiver.getSearchCriteria(); + receiver.internalMatchAny(request());receiver.internalMatchAny(live()); + var onlyVersions = live(); + onlyVersions.appendSearchCriteria(onlyVersions.createBasicSearchCriteria("version", Operator.EQUAL, 99L)); + receiver.internalMatchAny(onlyVersions);assertSame(before, receiver.getSearchCriteria()); + } + + @Test public void explicitNestedBooleanGroupsAreNotFlattenedIntoAlternatives() { + var source = live();var nested = SearchCriteria.and(condition("capacity", 100), condition("owner", 42)); + source.appendSearchCriteria(nested);source.appendSearchCriteria(condition("id", 1)); + var receiver = live();receiver.internalMatchAny(source); + var alternatives = (OR) ((AND) receiver.getSearchCriteria()).second(); + assertEquals(2, alternatives.getExpressions().size());assertSame(nested, alternatives.first()); + } + + @Test public void nonAndSourceIsOneConditionAndNeverCopiesItsPageOrMeasures() { + var source = request();var filter = condition("capacity", 100);source.appendSearchCriteria(filter); + source.groupBy("id");source.count("count");source.top(0); + var receiver = live();var beforeSlice = receiver.getSlice();receiver.internalMatchAny(source); + assertSame(filter, ((AND) receiver.getSearchCriteria()).second()); + assertSame(beforeSlice, receiver.getSlice());assertTrue(receiver.getAggregations().getAggregates().isEmpty()); + } +} diff --git a/teaql-core/src/test/java/io/teaql/core/QueryNavigationTest.java b/teaql-core/src/test/java/io/teaql/core/QueryNavigationTest.java new file mode 100644 index 000000000..17a81a43e --- /dev/null +++ b/teaql-core/src/test/java/io/teaql/core/QueryNavigationTest.java @@ -0,0 +1,68 @@ +package io.teaql.core; + +import io.teaql.core.criteria.Operator; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class QueryNavigationTest { + public static class Row extends BaseEntity { @Override public String typeName() { return "School"; } } + static class Request extends BaseRequest { + Request() { super(Row.class); } + @Override public String getTypeName() { return "School"; } + @Override protected BaseRequest internalCopyTarget() { return new Request(); } + @Override public Request copy() { return (Request) super.copy(); } + void navigate(SearchRequest parent) { internalRollUpTo("kind", parent); } + } + static List memberships(SearchCriteria criteria) { + var result = new ArrayList(); + if (criteria instanceof SubQuerySearchCriteria membership) result.add(membership); + else if (criteria instanceof FunctionApply function) + for (var operand : function.getExpressions()) if (operand instanceof SearchCriteria condition) result.addAll(memberships(condition)); + return result; + } + + @Test public void latestTargetReplacesItsMembershipAndDimension() { + var source=new Request();var first=new Request();var second=new Request(); + source.navigate(first);source.navigate(second); + assertSame(second,source.getPropagateDimensions().get("kind")); + assertEquals(1,source.getAggregations().getComplexDimensions().size()); + assertEquals(1,memberships(source.getSearchCriteria()).size()); + assertSame(second,memberships(source.getSearchCriteria()).get(0).getDependsOn()); + } + @Test public void copiedNavigationDoesNotRebindTheOriginal() { + var source=new Request();var first=new Request();source.navigate(first); + var copy=source.copy();var replacement=new Request();copy.navigate(replacement); + assertSame(first,source.getPropagateDimensions().get("kind")); + assertSame(replacement,copy.getPropagateDimensions().get("kind")); + assertEquals(1,memberships(copy.getSearchCriteria()).size()); + } + @Test public void anIdenticalBusinessPredicateIsNotOwnedByNavigation() { + var source=new Request();var parent=new Request(); + source.appendSearchCriteria(new SubQuerySearchCriteria("kind",parent,"id"));source.navigate(parent); + var copy=source.copy();var replacement=new Request();copy.navigate(replacement); + var members=memberships(copy.getSearchCriteria());assertEquals(2,members.size()); + assertEquals(1,members.stream().filter(SubQuerySearchCriteria::navigationOwned).count()); + assertTrue(members.stream().anyMatch(member->!member.navigationOwned() && member.getDependsOn()!=replacement)); + } + @Test public void alternativesRetainUnrelatedFieldsForNormalValidation() { + var request=new Request();var unknown=request.createBasicSearchCriteria("unknown_logical_field",Operator.EQUAL,1L); + var owned=new SubQuerySearchCriteria("kind",new Request(),"id",true); + var result=QueryNavigation.clear(SearchCriteria.or(owned,unknown),"kind",0); + assertTrue(((FunctionApply)result).getExpressions().contains(unknown)); + assertEquals(2,((FunctionApply)result).getExpressions().size()); + } + @Test public void repeatedNavigationDoesNotAccumulateAstNodes() { + var source=new Request();for(int index=0;index<100;index++)source.navigate(new Request()); + assertEquals(1,source.getAggregations().getComplexDimensions().size()); + assertEquals(1,memberships(source.getSearchCriteria()).size()); + } + @Test public void rejectedRebindingLeavesTheOriginalCriteriaUntouched() { + SearchCriteria criteria=new SubQuerySearchCriteria("kind",new Request(),"id",true); + for(int depth=0;depth<65;depth++)criteria=SearchCriteria.not(criteria); + var source=new Request();source.replaceSearchCriteria(criteria);var before=source.getSearchCriteria(); + assertThrows(TeaQLRuntimeException.class,()->source.navigate(new Request())); + assertSame(before,source.getSearchCriteria());assertTrue(source.getPropagateDimensions().isEmpty()); + } +} diff --git a/teaql-core/src/test/java/io/teaql/core/QueryRequestSnapshotIsolationTest.java b/teaql-core/src/test/java/io/teaql/core/QueryRequestSnapshotIsolationTest.java new file mode 100644 index 000000000..836cb6267 --- /dev/null +++ b/teaql-core/src/test/java/io/teaql/core/QueryRequestSnapshotIsolationTest.java @@ -0,0 +1,89 @@ +package io.teaql.core; + +import io.teaql.core.criteria.*; +import java.util.*; +import org.junit.Test; +import static org.junit.Assert.*; + +public class QueryRequestSnapshotIsolationTest { + private static BaseRequest.TempRequest request(String name) { + return new BaseRequest.TempRequest(BaseEntity.class, name); + } + + @Test public void snapshotFreezesMutableGroupingAndHavingOperands() { + var source = request("School"); + var property = new PropertyReference("capacity"); + var measure = new SimpleNamedExpression("total", new AggrExpression(AggrFunction.SUM, property)); + source.addAggregate(measure); + var values = new ArrayList(List.of(1L, 2L)); + var parameter = new Parameter("total", values, Operator.IN); + source.having(new TwoOperatorCriteria(Operator.IN, new PropertyReference("total"), parameter)); + var frozen = new QueryRequestSnapshot<>(source, null); + property.setPropertyName("id"); + ((List) parameter.getValue()).add(3L); + assertEquals(List.of("capacity"), frozen.getAggregations().getAggregates().get(0).properties(null)); + var saved = (Parameter) ((FunctionApply) frozen.getHaving()).second(); + assertEquals(List.of(1L, 2L), saved.getValue()); + } + + @Test public void snapshotPreservesSharedParentIdentityWithoutSharingTheBuilder() { + var parent = request("Kind"); parent.groupBy("name"); + var source = request("School"); source.groupBy("kind", parent); + source.appendSearchCriteria(new SubQuerySearchCriteria("kind", parent, "id")); + var frozen = new QueryRequestSnapshot<>(source, null); + var copiedParent = frozen.getPropagateDimensions().get("kind"); + assertNotSame(parent, copiedParent); + assertSame(copiedParent, ((SubQuerySearchCriteria) frozen.getSearchCriteria()).getDependsOn()); + parent.groupBy("code"); + assertEquals(1, copiedParent.getAggregations().getSimpleDimensions().size()); + } + + @Test public void explicitCopyPreservesTypedNodesAndDetachesEveryMutableAstContainer() { + var parent = request("Kind"); parent.groupBy("name"); parent.offset(0, 2); + var source = request("School"); source.groupBy("kind", parent); + source.appendSearchCriteria(new SubQuerySearchCriteria("kind", parent, "id")); + source.having("count", Operator.GREATER_THAN, 1L); + var date = new Date(1234); var counts = new long[]{1L,2L}; + source.setExtensions(new HashMap<>(Map.of("labels", new ArrayList<>(List.of("original")), "date", date, "counts", counts))); + var frozen = source.copy(); + var child = frozen.getPropagateDimensions().get("kind"); + assertEquals(parent.getClass(), child.getClass()); + assertSame(child, ((SubQuerySearchCriteria) frozen.getSearchCriteria()).getDependsOn()); + parent.getSlice().setSize(9); parent.groupBy("code"); + ((List) source.getExtension("labels")).add("changed"); + date.setTime(9999); counts[0]=99; + assertEquals(2, child.getSlice().getSize()); + assertEquals(1, child.getAggregations().getSimpleDimensions().size()); + assertEquals(List.of("original"), frozen.getExtension("labels")); + assertEquals(1234, ((Date) frozen.getExtension("date")).getTime()); + assertArrayEquals(new long[]{1L,2L}, (long[]) frozen.getExtension("counts")); + assertNotSame(source.getHaving(), frozen.getHaving()); + } + + @Test public void cyclicAndDeepGraphsFailWithoutStackOverflow() { + var cycle = request("School"); cycle.groupBy("self", cycle); + assertThrows(TeaQLRuntimeException.class, () -> cycle.copy()); + assertThrows(TeaQLRuntimeException.class, () -> new QueryRequestSnapshot<>(cycle, null)); + var root = request("School"); var current = root; + for (int i=0; i<70; i++) { var child = request("School"); current.groupBy("next", child); current = child; } + assertThrows(TeaQLRuntimeException.class, () -> root.copy()); + var expression = new FunctionApply(Operator.SOUNDS_LIKE, new PropertyReference("name")); + expression.getExpressions().set(0, expression); + var invalid = request("School"); invalid.getAggregations().getSimpleDimensions().add(new SimpleNamedExpression("key", expression)); + assertThrows(TeaQLRuntimeException.class, () -> invalid.copy()); + } + + @Test public void explicitCopyRejectsUnknownMutableExpressionsAndValuesWithoutEchoingPayloads() { + var custom = request("School"); + custom.getProjections().add(new SimpleNamedExpression("custom", new Expression() {})); + assertThrows(TeaQLRuntimeException.class, () -> custom.copy()); + var unknown = request("School"); + unknown.setExtensions(Map.of("secret", new StringBuilder("not-for-diagnostics"))); + var failure = assertThrows(TeaQLRuntimeException.class, () -> unknown.copy()); + assertFalse(failure.getMessage().contains("not-for-diagnostics")); + unknown.setExtensions(Map.of("mutableNumber", new java.util.concurrent.atomic.AtomicLong(1))); + assertThrows(TeaQLRuntimeException.class, () -> unknown.copy()); + unknown.setExtensions(Map.of("clock", java.time.Clock.systemUTC())); + assertThrows(TeaQLRuntimeException.class, () -> unknown.copy()); + } +} diff --git a/teaql-core/src/test/java/io/teaql/core/QueryRequestTraceNodeTest.java b/teaql-core/src/test/java/io/teaql/core/QueryRequestTraceNodeTest.java new file mode 100644 index 000000000..19890ec76 --- /dev/null +++ b/teaql-core/src/test/java/io/teaql/core/QueryRequestTraceNodeTest.java @@ -0,0 +1,60 @@ +package io.teaql.core; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class QueryRequestTraceNodeTest { + private static QueryRequestScope root() { + return QueryRequestScope.root("School", QueryIntent.of("Load schools", "Render the dashboard")); + } + + @Test public void oneRequestUsesExistingChainWithoutDuplicateTree() { + var root = root(); + assertTrue(QueryRequestTraceNode.fromScopes(List.of()).isEmpty()); + assertTrue(QueryRequestTraceNode.fromScopes(List.of(root)).isEmpty()); + assertTrue(QueryRequestTraceNode.fromScopes(List.of(root, root)).isEmpty()); + } + + @Test public void identicalSiblingCommentsDoNotInventAncestry() { + var root = root(); + var left = root.deriveChild("Kind", "Same local comment"); + var right = root.deriveChild("Kind", "Same local comment"); + var nodes = QueryRequestTraceNode.fromScopes(List.of(left, right, root, left)); + assertEquals(4, nodes.size()); + assertEquals("purpose", nodes.get(0).kind()); + assertNull(nodes.get(0).parentId()); + assertEquals(Integer.valueOf(1), nodes.get(2).parentId()); + assertEquals(Integer.valueOf(1), nodes.get(3).parentId()); + assertEquals(nodes.get(2).detail(), nodes.get(3).detail()); + for (int index = 0; index < nodes.size(); index++) { + assertEquals(index, nodes.get(index).id()); + assertTrue(nodes.get(index).parentId() == null || nodes.get(index).parentId() < index); + } + assertThrows(UnsupportedOperationException.class, () -> nodes.clear()); + } + + @Test public void nativeOperationAndLocalCommentRemainSeparate() throws Exception { + var root = root(); + var operation = root.deriveOperation("Kind", QueryOperation.nativeMethod( + QueryOperation.Kind.AGGREGATE, "rollUpToKind", null, "kind")); + var child = operation.deriveChild("Kind", "Group visible types"); + var nodes = QueryRequestTraceNode.fromScopes(List.of(child, root)); + var json = new ObjectMapper().valueToTree(nodes); + assertTrue(json.get(0).get("parentId").isNull()); + assertEquals("rollUpToKind", json.get(2).get("method").asText()); + assertEquals("rollUpToKind()", json.get(2).get("detail").asText()); + assertEquals(2, json.get(3).get("parentId").asInt()); + assertEquals("Group visible types", json.get(3).get("detail").asText()); + assertFalse(json.get(3).has("method")); + } + + @Test public void independentEqualRootsAreNotMergedByContent() { + var nodes = QueryRequestTraceNode.fromScopes(List.of(root(), root())); + assertEquals(4, nodes.size()); + assertNull(nodes.get(0).parentId()); + assertNull(nodes.get(2).parentId()); + assertEquals(Integer.valueOf(2), nodes.get(3).parentId()); + } +} diff --git a/teaql-core/src/test/java/io/teaql/core/RejectedMutationStateTest.java b/teaql-core/src/test/java/io/teaql/core/RejectedMutationStateTest.java index 02564f3d8..1eb741a76 100644 --- a/teaql-core/src/test/java/io/teaql/core/RejectedMutationStateTest.java +++ b/teaql-core/src/test/java/io/teaql/core/RejectedMutationStateTest.java @@ -6,7 +6,7 @@ import org.junit.runners.Parameterized; import static org.junit.Assert.*; -/** Rejected operations cannot rewrite payload, availability, lifecycle or intent. */ +/** Rejections are atomic; business edits preserve pending recovery and its identity. */ @RunWith(Parameterized.class) public class RejectedMutationStateTest { enum Availability {NOT_LOADED, NULL, VALUE} @@ -65,15 +65,35 @@ void unchanged(Row row){ private final EntityStatus status;private final Availability availability; public RejectedMutationStateTest(EntityStatus status,Availability availability){this.status=status;this.availability=availability;} void reject(Row row,Runnable action){var before=new Snapshot(row);assertThrows(TeaQLRuntimeException.class,action::run);before.unchanged(row);} - @Test public void typedUpdateRejectsBeforeChangingAvailability(){var row=row(status,availability);reject(row,()->row.updateName("attempted typed value"));} - @Test public void genericUpdateRejectsBeforeChangingPayload(){var row=row(status,availability);reject(row,()->row.updateProperty("name","attempted generic value"));} + void businessUpdate(Row row,Runnable action,Runnable accepted){ + if(status!=EntityStatus.UPDATED_RECOVER){reject(row,action);return;} + var before=new Snapshot(row);action.run();accepted.run(); + assertEquals(EntityStatus.UPDATED_RECOVER,row.get$status()); + assertEquals(before.id,row.getId());assertEquals(before.version,row.getVersion());assertEquals(before.originalVersion,row.getOriginalVersion()); + assertEquals(before.comment,row.getComment());assertEquals(before.trace,row.getTraceChain()); + assertSame(before.ledger,row.getEntityMutationLedger()); + assertEquals(before.recovered,row.getEntityMutationLedger().recoveredKeys()); + assertEquals(before.created,row.getEntityMutationLedger().newKeys()); + assertEquals(before.deleted,row.getEntityMutationLedger().deletedKeys()); + } + @Test public void typedUpdateFollowsLifecycleBeforeChangingAvailability(){var row=row(status,availability);businessUpdate(row,()->row.updateName("attempted typed value"),()->{ + assertEquals("attempted typed value",row.name);assertTrue(row.isPropertyLoaded("name")); + assertEquals("attempted typed value",row.getEntityMutationLedger().get(new EntityKey("GuardedRow",100L),"name")); + });} + @Test public void genericUpdateFollowsLifecycleBeforeChangingPayload(){var row=row(status,availability);businessUpdate(row,()->row.updateProperty("name","attempted generic value"),()->{ + assertEquals("attempted generic value",row.name);assertTrue(row.isPropertyLoaded("name")); + });} @Test public void versionUpdateRejectsBeforeClaimingASelectedVersion(){var row=row(status,availability);reject(row,()->row.updateVersion(9L));} @Test public void identityUpdateRejectsWithoutChangingTheKey(){var row=row(status,availability);reject(row,()->row.updateId(101L));} - @Test public void directUpdateHookRejectsBeforeChangingAvailability(){var row=row(status,availability);reject(row,()->row.handleUpdate("name",row.name,"attempted hook value"));} - @Test public void cacheAttachmentRejectsBeforeAddingAReference(){var row=row(status,availability);reject(row,()->row.cacheRelation("owner",foreign(200)));} - @Test public void cacheReplacementRejectsBeforeOverwritingAPreviousReference(){ + @Test public void genericVersionUpdateRejectsBeforeChangingPayload(){var row=row(status,availability);reject(row,()->row.updateProperty("version",9L));} + @Test public void genericIdentityUpdateRejectsBeforeChangingPayload(){var row=row(status,availability);reject(row,()->row.updateProperty("id",101L));} + @Test public void directUpdateHookFollowsLifecycleBeforeChangingAvailability(){var row=row(status,availability);businessUpdate(row,()->row.handleUpdate("name",row.name,"attempted hook value"),()->{ + assertTrue(row.isPropertyLoaded("name"));assertEquals("attempted hook value",row.getEntityMutationLedger().get(new EntityKey("GuardedRow",100L),"name")); + });} + @Test public void cacheAttachmentFollowsLifecycleBeforeAddingAReference(){var row=row(status,availability);var owner=foreign(200);businessUpdate(row,()->row.cacheRelation("owner",owner),()->assertSame(owner,row.getProperty("owner")));} + @Test public void cacheReplacementFollowsLifecycleBeforeOverwritingAPreviousReference(){ var row=row(status,availability);row.set$status(EntityStatus.NEW);row.cacheRelation("owner",foreign(200));row.set$status(status); - reject(row,()->row.cacheRelation("owner",foreign(201))); + var owner=foreign(201);businessUpdate(row,()->row.cacheRelation("owner",owner),()->assertSame(owner,row.getProperty("owner"))); } @Test public void deletionRejectionAlreadyRetainsTheExistingState(){var row=row(status,availability);reject(row,row::markForDeletion);} } diff --git a/teaql-core/src/test/java/io/teaql/core/SlicePopulationTest.java b/teaql-core/src/test/java/io/teaql/core/SlicePopulationTest.java new file mode 100644 index 000000000..7bc9dfc30 --- /dev/null +++ b/teaql-core/src/test/java/io/teaql/core/SlicePopulationTest.java @@ -0,0 +1,24 @@ +package io.teaql.core; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; +import static org.junit.Assert.*; + +public class SlicePopulationTest { + @Test public void copiedDefaultIsNotAnExplicitNestedTopN() throws Exception { + var defaults = new Slice(); + assertEquals(1000, defaults.getSize()); + assertFalse(defaults.hasExplicitPage()); assertFalse(defaults.copy().hasExplicitPage()); + var explicit = defaults.copy(); explicit.setSize(1000); + assertTrue(explicit.hasExplicitPage()); assertTrue(explicit.copy().hasExplicitPage()); + assertFalse(defaults.hasExplicitPage()); + assertFalse(new ObjectMapper().writeValueAsString(explicit).contains("explicit")); + } + + @Test public void offsetAndZeroAreExplicitBusinessSelections() { + var offset = new Slice(); offset.setOffset(5); assertTrue(offset.copy().hasExplicitPage()); + assertEquals(5, offset.copy().getOffset()); + var zero = new Slice(); zero.setSize(0); assertTrue(zero.copy().hasExplicitPage()); + assertEquals(0, zero.copy().getSize()); + } +} diff --git a/teaql-core/src/test/java/io/teaql/core/checker/CheckerPresentationJsonTest.java b/teaql-core/src/test/java/io/teaql/core/checker/CheckerPresentationJsonTest.java new file mode 100644 index 000000000..58c6a381f --- /dev/null +++ b/teaql-core/src/test/java/io/teaql/core/checker/CheckerPresentationJsonTest.java @@ -0,0 +1,43 @@ +package io.teaql.core.checker; + +import io.teaql.core.i18n.CheckerMessageCatalog; +import io.teaql.core.i18n.Locale; +import java.util.Map; +import org.junit.Test; +import static org.junit.Assert.*; + +public class CheckerPresentationJsonTest { + private static final String MODEL = """ + {"schema":"teaql.checker-model/v1","revision":"generated-test","entities":{ + "Catalog":{"labels":{"en":"catalog","zh-CN":"目录"},"fields":[{"name":"entry_list","aliases":["entryList"],"targetType":"Entry", + "labels":{"en":"entry","zh-CN":"明细"},"classifiers":{"zh-CN":"条"}}]}, + "Entry":{"labels":{"en":"entry","zh-CN":"明细"},"fields":[{"name":"name","labels":{"en":"name","zh-CN":"名称"}}]} + }} + """; + @Test public void generatedModelResolvesAliasAndLocaleWithoutLoadingAnyEntity() { + var model=CheckerPresentation.Model.fromJson(MODEL); + assertEquals("generated-test",model.revision()); + var presentation=CheckerPresentation.capture(model,"Catalog",ObjectLocation.hashRoot("entryList").element(1).member("name")); + assertEquals("The name of the 2nd entry is required.",presentation.render( + CheckerMessageCatalog.builtin(),Locale.ENGLISH,"checker.required",Map.of(),code->fail(code))); + assertEquals("请填写第2条明细的名称。",presentation.render( + CheckerMessageCatalog.builtin(),Locale.CHINESE_SIMPLIFIED,"checker.required",Map.of(),code->fail(code))); + assertThrows(UnsupportedOperationException.class,()->model.entities().clear()); + } + @Test public void rejectsDuplicateKeysLocalesAliasesUnknownMembersAndTrailingData() { + for(String source:new String[]{ + MODEL.replace("\"revision\":\"generated-test\"","\"revision\":\"first\",\"revision\":\"second\""), + MODEL.replace("\"en\":\"name\"","\"en\":\"name\",\"en-US\":\"different\""), + MODEL.replace("[\"entryList\"]","[\"entry_list\"]"), + MODEL.replace("[\"entryList\"]","[\"entryList\",\"entryList\"]"), + MODEL.replace("\"revision\":","\"execute\":true,\"revision\":"), + MODEL.replace("\"teaql.checker-model/v1\"","\"teaql.i18n/v1\""), + MODEL.replace("\"en\":\"name\"","\"en\":\"line\\nnext\""), + MODEL+" {}" + }) assertThrows(IllegalArgumentException.class,()->CheckerPresentation.Model.fromJson(source)); + } + @Test public void parserFailureNeverEchoesTheSource() { + var error=assertThrows(IllegalArgumentException.class,()->CheckerPresentation.Model.fromJson("{raw-secret-canary")); + assertFalse(error.toString().contains("raw-secret-canary"));assertNull(error.getCause()); + } +} 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..9de9e9541 --- /dev/null +++ b/teaql-core/src/test/java/io/teaql/core/i18n/CheckerMessageCatalogTest.java @@ -0,0 +1,235 @@ +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")) { + var fixture = JSON.readTree(input); + try (var roots = CheckerMessageCatalogTest.class.getResourceAsStream("natural-root-cases-v1.json")) { + for (var rootCase : JSON.readTree(roots).get("cases")) + ((com.fasterxml.jackson.databind.node.ArrayNode) fixture.get("cases")).add(rootCase); + } + return fixture; + } + } + + 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 safePlansProjectOnlyCustomLiteralNodesAndRetainOnlyTheirRule() { + var catalog = catalog("{\"en\":{\"rules\":{\"checker.min\":{\"two\":\"Secret 1 {field} of {object}: {system}.\"},\"checker.required\":{\"one\":\"UNRELATED {field}\"}},\"locationPatterns\":{\"item\":\"Secret 1 {ordinal} {relation}\"}}}"); + var safe = catalog.projectForRule("checker.min", text -> text.replace("1", "[REDACTED]")); + assertNull(safe.override(Locale.ENGLISH, "checker.required", CheckerMessageCatalog.Shape.ONE)); + assertEquals("Secret [REDACTED] amount of the 1st entry: 12.", safe.override(Locale.ENGLISH, "checker.min", CheckerMessageCatalog.Shape.TWO) + .render(Map.of("field", "amount", "object", "the 1st entry", "system", 12))); + assertEquals("Secret [REDACTED] 1st entry", safe.item(Locale.ENGLISH, "entry", 0, "")); + assertSame(CheckerMessageCatalog.builtin(), CheckerMessageCatalog.builtin().projectForRule("checker.min", text -> "DO NOT REWRITE BUILTINS")); + } + + @Test public void projectedLegacyNodesNeverReparseArgumentsOrUnknownBraces() { + var template = CheckerMessageCatalog.legacyTemplate("Secret 1 {location}: {input_len}/{system}; {unknown}") + .projectLiterals(text -> text.replace("1", "[REDACTED]")); + assertEquals("Secret [REDACTED] {system}: 1/12; {unknown}", + template.render(Map.of("location", "{system}", "input_len", 1, "system", 12))); + } + + @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()}