From 8ed7a151073c6b2eb71c699a2217b554372cf755 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Sat, 21 Nov 2026 22:49:52 +0800 Subject: [PATCH 1/2] examples(python): add supplier onboarding localization showcase --- README.md | 1 + examples/supplier-onboarding-i18n/README.md | 98 ++++ .../generated-files.json | 48 ++ examples/supplier-onboarding-i18n/model.xml | 7 + .../python-app-console/AGENTS.md | 46 ++ .../python-app-console/README.md | 12 + .../python-app-console/STANDARD_TELEMETRY.md | 45 ++ .../python-app-console/app/__init__.py | 0 .../python-app-console/app/main.py | 87 +++ .../python-lib-core/E.py | 131 +++++ .../python-lib-core/Q.py | 22 + .../generated_search_models.py | 41 ++ .../python-lib-core/models/__init__.py | 0 .../python-lib-core/models/supplier.py | 469 +++++++++++++++ .../python-lib-core/models/warehouse.py | 448 +++++++++++++++ .../python-lib-core/pyproject.toml | 16 + .../python-lib-core/requests/__init__.py | 0 .../requests/supplier_request.py | 539 +++++++++++++++++ .../requests/warehouse_request.py | 544 ++++++++++++++++++ .../python-lib-core/runtime_module.py | 127 ++++ .../python-lib-core/teaql-i18n.json | 109 ++++ .../python-lib-core/teaql/checker-model.json | 1 + .../teaql/model-provenance.json | 1 + .../supplier-onboarding-i18n/run-example.py | 177 ++++++ examples/supplier-onboarding-i18n/run.sh | 10 + .../supplier-onboarding-i18n/semantics.json | 48 ++ .../supplier-onboarding-i18n/showcase.json | 77 +++ scripts/verify-examples.sh | 4 +- 28 files changed, 3107 insertions(+), 1 deletion(-) create mode 100644 examples/supplier-onboarding-i18n/README.md create mode 100644 examples/supplier-onboarding-i18n/generated-files.json create mode 100644 examples/supplier-onboarding-i18n/model.xml create mode 100644 examples/supplier-onboarding-i18n/python-app-console/AGENTS.md create mode 100644 examples/supplier-onboarding-i18n/python-app-console/README.md create mode 100644 examples/supplier-onboarding-i18n/python-app-console/STANDARD_TELEMETRY.md create mode 100644 examples/supplier-onboarding-i18n/python-app-console/app/__init__.py create mode 100644 examples/supplier-onboarding-i18n/python-app-console/app/main.py create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/E.py create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/Q.py create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/generated_search_models.py create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/models/__init__.py create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/models/supplier.py create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/models/warehouse.py create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/pyproject.toml create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/requests/__init__.py create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/requests/supplier_request.py create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/requests/warehouse_request.py create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/runtime_module.py create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/teaql-i18n.json create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/teaql/checker-model.json create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/teaql/model-provenance.json create mode 100644 examples/supplier-onboarding-i18n/run-example.py create mode 100644 examples/supplier-onboarding-i18n/run.sh create mode 100644 examples/supplier-onboarding-i18n/semantics.json create mode 100644 examples/supplier-onboarding-i18n/showcase.json diff --git a/README.md b/README.md index f4334841..ac15206f 100644 --- a/README.md +++ b/README.md @@ -458,6 +458,7 @@ This mutation rule does not change the tolerant unknown-field search behavior. - [Opaque reference example](examples/opaque-entity-reference) - [Binary object storage and temporary S3 URLs](examples/object-storage/README.md) - [Generated scalar probe and exact SQLite Decimal](examples/scalar-type-probe/README.md) +- [Supplier onboarding in 15 locales](examples/supplier-onboarding-i18n/README.md) ## Safe troubleshooting diff --git a/examples/supplier-onboarding-i18n/README.md b/examples/supplier-onboarding-i18n/README.md new file mode 100644 index 00000000..7dd94e7f --- /dev/null +++ b/examples/supplier-onboarding-i18n/README.md @@ -0,0 +1,98 @@ +# Supplier onboarding in 15 locales with TeaQL Python + +The [KSML model](model.xml) describes a warehouse and its suppliers. The +[semantic model](semantics.json) supplies two registrations to the generated +console. One lacks a supplier name. The other sets the minimum order quantity +to 3, below the model's limit of 10. The app makes real audited saves against +SQLite and reads the supplier table back through generated Q. + +## Run and select a locale + +Use Python 3.10 or newer and install this checkout's Python dependencies from +the repository root with `python3 -m pip install -e .`. The runner uses the +TeaQL 0.6.0 source in this checkout and the sibling generated domain library. + +```sh +bash examples/supplier-onboarding-i18n/run.sh +bash examples/supplier-onboarding-i18n/run.sh --locale fr +bash examples/supplier-onboarding-i18n/run.sh --all +bash examples/supplier-onboarding-i18n/run.sh --edge-cases +``` + +Output is UTF-8 JSON Lines. Look at `effectiveLocale`, `messageKey`, +`location`, `arguments`, and `message` on each validation row. `--all` +switches through all 15 locales in one process. Add `--repeat 2` to run the +same mode twice against one temporary database. `PYTHON` selects the Python +executable and defaults to `python3`. An empty `PYTHON` also uses that default. + +The app uses `context.set_locale_code(code)` before validation and reads +`context.language().value`. With no selection a fresh context uses `en`. +`ZH_hant` normalizes to `zh-TW`. Both the empty string and an unknown code +raise `UnsupportedLocaleError` and leave the previous locale in place. Single +locale mode reports the rejection and exits 2. The example selects locale +only through the CLI and trusted context wiring. Business input and process +locale variables supply no locale configuration. + +## How the message is produced + +1. The generated model is installed on a `UserContext` with a SQLite provider. + The setter parses and normalizes the requested locale before recording it. +2. The generated save checks the model. `CheckException.violations` contains + the rule, canonical location and parameters. The example reports + `checker.required` and `checker.min` with the source rule IDs alongside them. +3. The checker renderer chooses a template for the locale and location shape, + then binds the field label and the applicable parameters, such as + `{system}` for the lower bound. The generated presentation metadata + supplies field names where available. +4. The example explicitly installs its generated application catalog with + `I18nCatalog.from_dict(payload, I18nCatalog.builtin())`. That catalog lacks + these Vietnamese message overrides, so the two rendered messages stay + identical to the built-in Vietnamese results. The legacy catalog's + `message` method tries application and built-in entries in the selected + locale, then application and built-in English, then returns the key. + The natural checker renderer also supports per-shape templates and + generic `checker.invalid` when the rule has no natural template. + +The independent context stays French while the main context changes from +Japanese to Arabic and back. The sample's localized sentence templates can +include English domain labels when no translated label is present. +[Context source](../../src/teaql/runtime/context.py) · [Locale and catalog source](../../src/teaql/runtime/i18n.py) · [Checker rendering source](../../src/teaql/runtime/checker_messages.py) + +## Run the same scene in another runtime + +Use the corresponding example in a sibling checkout. Keep the KSML, +semantic input, rule keys and field paths. Follow the other example's build +and context wiring for its host language. + +[Java](../../../java/examples/supplier-onboarding-i18n/) · +[Rust](../../../rust/examples/supplier-onboarding-i18n/) · +[TypeScript](../../../typescript/examples/supplier-onboarding-i18n/) · +[Go](../../../go/examples/supplier-onboarding-i18n/) · +[Python](./) · +[C#/.NET](../../../dotnet/examples/supplier-onboarding-i18n/) · +[Swift](../../../swift/Examples/SupplierOnboardingI18n/) + +## Add a locale + +For a new runtime locale such as Italian, register `ITALIAN = "it"` in +`Locale` in `src/teaql/runtime/i18n.py` and add aliases in `_ALIASES` as +needed. Extend the legacy and natural built-ins and the per-locale checker +presentation defaults used in `checker_messages.py`. The legacy entry keeps +the key and placeholder. + +```json +{ + "it": { + "messages": {"checker.required": "Il campo {location} è obbligatorio"}, + "vocabulary": {} + } +} +``` + +For natural checker messages supply the appropriate `one`, `two` and +`deep` templates in `src/teaql/runtime/natural-messages-v1.json`, preserving +placeholders such as `{field}` and `{system}`. Update the shared locale model +and generator locale list before regenerating the examples. Verify alias +selection, both real saves and missing-translation fallback, plus the +separation of locale state between contexts. For overrides of an already +supported locale, explicitly attach the application catalog instead. diff --git a/examples/supplier-onboarding-i18n/generated-files.json b/examples/supplier-onboarding-i18n/generated-files.json new file mode 100644 index 00000000..3c44b7ec --- /dev/null +++ b/examples/supplier-onboarding-i18n/generated-files.json @@ -0,0 +1,48 @@ +{ + "library": { + "scope": "python-lib-core", + "sha256": { + "E.py": "4feb2016d23c5f664122f11921814bb52645cfa51b2eb201204f9ea6231d6b75", + "Q.py": "a962f69c512c902e901b903b14c1dffaa92755e7443b6877cb122a5289b0c51e", + "generated_search_models.py": "bb6b6aaeabbc8bda3c42ba1445212f00ef1f9a9c952c6892c31783b00c477594", + "models/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "models/supplier.py": "03cb7101f03365edd970f2758ebc6ea58b1d693b8cd2d49bc8132f79c4c3fc7c", + "models/warehouse.py": "1f11e4254cc939a68c49758cbc8f4fc789484ca38807f52c292594ae7247d8df", + "pyproject.toml": "16eb65d80bf164747491ae65289e5b4511c40a600d81b7bc5569fc1f161657b5", + "requests/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "requests/supplier_request.py": "0ab10d5469ab426546f82f07803fc7af145fd281dd14ce57db6b304b7d8c9508", + "requests/warehouse_request.py": "c9062219b6972e79e93d974a96a56fdefc74001b1b302e51b8babb4c28f99009", + "runtime_module.py": "7db3980bc0ef3ef0120a4003ee3d84bd6b3d7c0bb7676fa7867850267b20f2e9", + "teaql-i18n.json": "f848093c0785f2730eaa74f8a9e175e1f90943f056d84666bc964d56668e298c", + "teaql/checker-model.json": "0c70836b868047e6bbf8c5a4b167343ef9425e5c535c59ee388b634a79f2b144", + "teaql/model-provenance.json": "94ae1b99943275455fce8de247c97f10a81cdb09fef91ada0ae924b26e572759" + } + }, + "schema": "teaql.i18n-showcase-generation/v1", + "workspace": { + "applicationEntry": "app/main.py", + "domainSourcesFromSibling": true, + "scope": "python-app-console", + "sha256": { + "AGENTS.md": "c448ef9b56f4bda7dd534e666b77fde33b72d2ad9f987edd82fe83b3604f6bbc", + "E.py": "4feb2016d23c5f664122f11921814bb52645cfa51b2eb201204f9ea6231d6b75", + "Q.py": "a962f69c512c902e901b903b14c1dffaa92755e7443b6877cb122a5289b0c51e", + "README.md": "4463e00b120c1af3b6951fc43c19689b389d64b1989e0c41f66b8b5c140cd18e", + "STANDARD_TELEMETRY.md": "03391e8a7ff96c207269a3374437d7a95a16ac6563c58d6b054ab38e3bda3712", + "app/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "app/main.py": "1e019f8857f5aec33632b3b47b370832b90d1de9ecf260e0912c449ba3b23d46", + "generated_search_models.py": "bb6b6aaeabbc8bda3c42ba1445212f00ef1f9a9c952c6892c31783b00c477594", + "models/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "models/supplier.py": "03cb7101f03365edd970f2758ebc6ea58b1d693b8cd2d49bc8132f79c4c3fc7c", + "models/warehouse.py": "1f11e4254cc939a68c49758cbc8f4fc789484ca38807f52c292594ae7247d8df", + "pyproject.toml": "16eb65d80bf164747491ae65289e5b4511c40a600d81b7bc5569fc1f161657b5", + "requests/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "requests/supplier_request.py": "0ab10d5469ab426546f82f07803fc7af145fd281dd14ce57db6b304b7d8c9508", + "requests/warehouse_request.py": "c9062219b6972e79e93d974a96a56fdefc74001b1b302e51b8babb4c28f99009", + "runtime_module.py": "7db3980bc0ef3ef0120a4003ee3d84bd6b3d7c0bb7676fa7867850267b20f2e9", + "teaql-i18n.json": "f848093c0785f2730eaa74f8a9e175e1f90943f056d84666bc964d56668e298c", + "teaql/checker-model.json": "0c70836b868047e6bbf8c5a4b167343ef9425e5c535c59ee388b634a79f2b144", + "teaql/model-provenance.json": "94ae1b99943275455fce8de247c97f10a81cdb09fef91ada0ae924b26e572759" + } + } +} diff --git a/examples/supplier-onboarding-i18n/model.xml b/examples/supplier-onboarding-i18n/model.xml new file mode 100644 index 00000000..639f16fd --- /dev/null +++ b/examples/supplier-onboarding-i18n/model.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/examples/supplier-onboarding-i18n/python-app-console/AGENTS.md b/examples/supplier-onboarding-i18n/python-app-console/AGENTS.md new file mode 100644 index 00000000..e4323bd0 --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-app-console/AGENTS.md @@ -0,0 +1,46 @@ +# supplier-onboarding-service application instructions + +## TeaQL workspace rules + +- Work in application-owned files. Keep the generated domain library read-only. +- Discover API names and signatures through model-aware Assist only. + Do not read or search generated library source for API discovery. Use the + original evaluated KSML file or directory and its exact entity and field names. +- Ask for the current entity and action first. Request field-level query help + only for the fields you use. If Assist lacks the operation, report + `MISSING_ASSIST` with the entity, action, and relevant field or diagnostic. + +```text +cargo teaql --input [model] python-assist-[action]/[entity] +cargo teaql --input [model] python-assist-query/[entity].[field] +``` + +Replace the bracketed values with the actual model path, action, entity, and +field. Actions include `query`, `list-page`, `create`, `update`, `delete`, and +`expression`. Validate API usage by compiling and testing the application. + +- Use the trusted `UserContext` as the only runtime argument for generated query + execution and saves. Resolve tenant, actor, authorization, and provider + resources from trusted application setup. +- Keep queries bounded and provide a non-empty purpose and comment. Supply a + non-empty audit reason for writes through the API shown by Assist. + +## Application entry and context + +Start in `app/main.py`. Use `create_context()` to install the generated +Runtime Module and configure the provider before calling `context.ensure_schema()`. + +Every query is bounded and has non-blank comment and purpose. Use generated Q +for loading and E for loaded traversal. Load all scalar fields before mutation; +mark_for_deletion() and save(context) the composed graph with a non-blank audit_as +reason. Child reasons remain local; unannotated children inherit their parent. +Public execution accepts only UserContext. Schema changes are explicit through +context.ensure_schema(), with generated bootstrap intact. + +Verify twice on one SQLite file without database cleanup. Use unique test labels, +keep generated library hashes unchanged, and retain commands, exit statuses and +skipped/unverified checks. Local source tests do not prove a published artifact. + +## Optional standard telemetry + +See [STANDARD_TELEMETRY.md](STANDARD_TELEMETRY.md) for the selected runtime's optional module, trusted activation variables and safe startup diagnostics. diff --git a/examples/supplier-onboarding-i18n/python-app-console/README.md b/examples/supplier-onboarding-i18n/python-app-console/README.md new file mode 100644 index 00000000..ee58da05 --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-app-console/README.md @@ -0,0 +1,12 @@ +# supplier-onboarding-service Python console + +Run `python -m app.main`. Installing the generated Runtime Module is passive; +schema reconciliation remains an explicit application action. +The console main() explicitly awaits `context.ensure_schema()` after `create_context()` +and before reporting readiness. Importing the console or calling `create_context()` +does not reconcile schema. + + +## Optional standard telemetry + +See [STANDARD_TELEMETRY.md](STANDARD_TELEMETRY.md) for the selected runtime's optional module, trusted activation variables and safe startup diagnostics. diff --git a/examples/supplier-onboarding-i18n/python-app-console/STANDARD_TELEMETRY.md b/examples/supplier-onboarding-i18n/python-app-console/STANDARD_TELEMETRY.md new file mode 100644 index 00000000..f20c63af --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-app-console/STANDARD_TELEMETRY.md @@ -0,0 +1,45 @@ +## Standard OpenTelemetry module + +Use the optional standard module supplied by the selected TeaQL runtime. Match +its version to the runtime dependency selected by the model and workspace; +keep local source or internal Registry overrides during development. Do not +upgrade to an unrelated public release just to enable telemetry. A runtime +without this module reports `module_unavailable`; package installation alone +does not enable export. + +On a supported backend, configure these trusted process variables before startup, never +through a query, JSON or TFP payload: + +```bash +export TEAQL_TELEMETRY_ENABLED=true +export TEAQL_TELEMETRY_SERVICE_NAME=payment-service +export TEAQL_TELEMETRY_OTLP_ENDPOINT=http://localhost:4318 +``` + +Without enablement, startup reports `disabled` and all three activation variables; +no SDK export resources are created. Enabled startup reports safe effective +settings, full recording and masking. Invalid settings produce a fixed safe +diagnostic, not a claim of successful export. Never print credentials or raw +configuration values. + +The module automatically records supported Q, graph mutation and physical SQL +operations as traces, logs and metrics. SQL is expanded with masked parameters; +plaintext debugging never authorizes plaintext telemetry export. Full recording +does not promise lossless delivery when bounded queues or exporters fail. +Do not add per-method spans or replace the customer's global SDK providers. + +Keep schema reconciliation explicit. Run the generated ensure-schema and seed +flow through the same configured runtime to observe startup settings and audited, +idempotent seeding. Telemetry setup must not run ensure-schema implicitly. +Flush and shut down the owned pipeline at application shutdown, not per query. +Exporter failures do not change business results; durable business audit remains +an independent path. + + +### Python assembly + +Select the `telemetry` extra on the application's existing `teaql` dependency +(`teaql[telemetry]`), retaining the version and source or Registry selected by the +workspace. UserContext startup loads the module only when enabled. No application +SDK initialization or per-method spans are required; set the three variables +before starting the process. diff --git a/examples/supplier-onboarding-i18n/python-app-console/app/__init__.py b/examples/supplier-onboarding-i18n/python-app-console/app/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/supplier-onboarding-i18n/python-app-console/app/main.py b/examples/supplier-onboarding-i18n/python-app-console/app/main.py new file mode 100644 index 00000000..8d269444 --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-app-console/app/main.py @@ -0,0 +1,87 @@ +"""Run supplier registration through the generated Python workspace.""" + +import asyncio +import json +from pathlib import Path +import sys + +from teaql.data_service import SQLiteTeaQLClient +from teaql.runtime import UserContext +from teaql.runtime.i18n import CheckException, I18nCatalog, UnsupportedLocaleError + +from Q import Q +from runtime_module import GENERATED_RUNTIME_MODULE + + +def create_context(client): + return UserContext.new().install(GENERATED_RUNTIME_MODULE).insert_resource("dataService", client) + + +def emit(step, context, event_type, **details): + result = {"type": event_type, "context": step["context"], + "effectiveLocale": context.language().value, **details} + print("TEAQL_I18N_SHOWCASE " + json.dumps(result, ensure_ascii=False)) + + +async def register_supplier(context, warehouse_id, values): + supplier = (Q.suppliers().comment("Prepare supplier registration") + .purpose("Register a supplier for warehouse purchasing").new_entity(context)) + supplier.update_warehouse(warehouse_id) + supplier.update_name(values["name"]) + supplier.update_minimum_order_quantity(values["minimum_order_quantity"]) + await supplier.audit_as("Register the supplier for purchasing").save(context) + + +async def verify_failure(step, context, warehouse_id): + try: + await register_supplier(context, warehouse_id, step["input"]) + except CheckException as error: + if len(error.violations) != 1: + raise AssertionError(f"Expected one native checker result, received {error}") from error + violation, = error.violations + wire = violation.to_wire() + key = {"required": "checker.required", "min": "checker.min"}[violation.rule_id.lower()] + arguments = {"minimum": int(wire["systemValue"])} if key == "checker.min" else {} + emit(step, context, "validation", case=step["case"], messageKey=key, + nativeRule=violation.rule_id, location=violation.location.model_path, + arguments=arguments, message=wire["message"], + nativeArguments={name: wire[name] for name in ("inputValue", "systemValue") if name in wire}) + else: + raise AssertionError(f"Invalid supplier registration was stored: {step['case']}") + + +async def main(): + plan = json.load(sys.stdin) + client = SQLiteTeaQLClient(plan["database"]) + try: + contexts = {name: create_context(client) for name in ("main", "independent")} + await contexts["main"].ensure_schema() + for step in plan["steps"]: + context = contexts[step["context"]] + operation = step["operation"] + if operation == "select": + try: + context.set_locale_code(step["locale"]) + except UnsupportedLocaleError as error: + emit(step, context, "locale", requestedLocale=error.locale_code, + accepted=False, nativeError=type(error).__name__) + else: + emit(step, context, "locale", requestedLocale=step["locale"], accepted=True) + elif operation == "validate": + await verify_failure(step, context, plan["warehouse"]["id"]) + elif operation == "install-catalog": + catalog = json.loads(Path(step["path"]).read_text(encoding="utf-8")) + context.install_i18n_catalog(I18nCatalog.from_dict(catalog, I18nCatalog.builtin())) + emit(step, context, "catalog-installed") + elif operation == "verify-unchanged": + rows = await (Q.suppliers_minimal().limit(1).comment("Check the rejected registrations") + .purpose("Verify no invalid supplier was stored").execute_for_list(context)) + emit(step, context, "storage", supplierCount=len(rows)) + else: + raise ValueError(f"Unsupported example operation: {operation}") + finally: + await client.close() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/supplier-onboarding-i18n/python-lib-core/E.py b/examples/supplier-onboarding-i18n/python-lib-core/E.py new file mode 100644 index 00000000..9a4adbae --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/E.py @@ -0,0 +1,131 @@ +from teaql.runtime import ExpressionPath, JsonFieldNamingProfile, TeaQLNotLoadedError + + +class ValueExpression: + def __init__(self, value=None, error=None): + self._value = value + self._error = error + + def eval(self): + if self._error is not None: + raise self._error.terminal("eval()") + return self._value + + def or_if_null(self, fallback): + if self._error is not None: + raise self._error.terminal("or_if_null()") + return fallback if self._value is None else self._value + + +class EntityExpression: + def __init__(self, value, root=None, path=None, error=None): + self._value = value + self._root = root + self._path = path if path is not None else ExpressionPath("E.entity()") + self._error = error + + def eval(self): + if self._error is not None: + raise self._error.terminal("eval()") + return self._value + + def _scalar(self, field, canonical, method, relation_id=False): + path = self._path.member(canonical, method) + if self._error is not None: + return ValueExpression(error=self._error.with_path(path)) + if self._value is None: + return ValueExpression(None) + if field not in getattr(self._value, "_loaded_fields", set()): + return ValueExpression(error=TeaQLNotLoadedError(path.mark_missing(), canonical)) + value = getattr(self._value, field) + if relation_id and value is not None and not isinstance(value, (int, str)): + value = getattr(value, "id", None) + return ValueExpression(value) + + def _relation(self, field, canonical, method, expression_type): + path = self._path.member(canonical, method) + if self._error is not None: + return expression_type(None, self._root, path, self._error.with_path(path)) + if self._value is None: + return expression_type(None, self._root, path) + if field not in getattr(self._value, "_loaded_fields", set()): + return expression_type(None, self._root, path, TeaQLNotLoadedError(path.mark_missing(), canonical)) + value = getattr(self._value, field) + if value is not None and isinstance(value, (int, str)): + return expression_type(None, self._root, path, TeaQLNotLoadedError(path.mark_missing(), canonical)) + return expression_type(value, self._root, path) + + def _list(self, field, canonical, method, item_expression): + path = self._path.member(canonical, method) + if self._error is not None: + return ListExpression([], self._root, path, item_expression, self._error.with_path(path)) + if self._value is None: + return ListExpression([], self._root, path, item_expression) + if field not in getattr(self._value, "_loaded_fields", set()): + return ListExpression([], self._root, path, item_expression, TeaQLNotLoadedError(path.mark_missing(), canonical)) + return ListExpression(getattr(self._value, "_" + field), self._root, path, item_expression) + + +class ListExpression: + def __init__(self, values, root, path, item_expression, error=None): + self._values = values + self._root = root + self._path = path + self._item_expression = item_expression + self._error = error + + def size(self): + return (ValueExpression(error=self._error.with_path(self._path.operation("size()"))) + if self._error else ValueExpression(len(self._values))) + + def first(self): + return self._item(0, first=True) + + def get(self, index): + return self._item(index) + + def _item(self, index, first=False): + path = self._path.index(index, first) + if self._error is not None: + return self._item_expression(None, self._root, path, self._error.with_path(path)) + value = self._values[index] if 0 <= index < len(self._values) else None + return self._item_expression(value, self._root, path) + + +class WarehouseExpression(EntityExpression): + def id(self): + return self._scalar("id", "id", "id") + def name(self): + return self._scalar("name", "name", "name") + def version(self): + return self._scalar("version", "version", "version") + def supplier_list(self): + return self._list("supplier_list", "supplier_list", "supplier_list", SupplierExpression) + pass + +class SupplierExpression(EntityExpression): + def id(self): + return self._scalar("id", "id", "id") + def name(self): + return self._scalar("name", "name", "name") + def minimum_order_quantity(self): + return self._scalar("minimumOrderQuantity", "minimum_order_quantity", "minimum_order_quantity") + def version(self): + return self._scalar("version", "version", "version") + def warehouse_id(self): + return self._scalar("warehouse", "warehouse", "warehouse_id", relation_id=True) + + def warehouse(self): + return self._relation("warehouse", "warehouse", "warehouse", WarehouseExpression) + pass + +class E: + @staticmethod + def warehouse(value): + return WarehouseExpression(value, path=ExpressionPath( + "E.warehouse()", JsonFieldNamingProfile.parse("camelCase"))) + @staticmethod + def supplier(value): + return SupplierExpression(value, path=ExpressionPath( + "E.supplier()", JsonFieldNamingProfile.parse("camelCase"))) + pass \ No newline at end of file diff --git a/examples/supplier-onboarding-i18n/python-lib-core/Q.py b/examples/supplier-onboarding-i18n/python-lib-core/Q.py new file mode 100644 index 00000000..d89593d3 --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/Q.py @@ -0,0 +1,22 @@ +# Generated by teaql-code-gen +from requests.warehouse_request import WarehouseRequest +from requests.supplier_request import SupplierRequest + +class Q: + @staticmethod + def warehouses() -> WarehouseRequest: + return WarehouseRequest(minimal=False) + + @staticmethod + def warehouses_minimal() -> WarehouseRequest: + return WarehouseRequest(minimal=True) + + @staticmethod + def suppliers() -> SupplierRequest: + return SupplierRequest(minimal=False) + + @staticmethod + def suppliers_minimal() -> SupplierRequest: + return SupplierRequest(minimal=True) + + diff --git a/examples/supplier-onboarding-i18n/python-lib-core/generated_search_models.py b/examples/supplier-onboarding-i18n/python-lib-core/generated_search_models.py new file mode 100644 index 00000000..db0b91af --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/generated_search_models.py @@ -0,0 +1,41 @@ +from types import MappingProxyType + +# Generated trusted field/type metadata. Runtime owns parsing, binding and warnings. +GENERATED_SEARCH_MODELS = MappingProxyType({ + "Warehouse": MappingProxyType({ + "fields": MappingProxyType({ + "id": "integer", + "name": "string", + "version": "integer", + }), + "query_fields": MappingProxyType({ + "id": "id", + "name": "name", + "version": "version", + }), + "relations": MappingProxyType({ + "supplierList": "Supplier", + }), + }), + "Supplier": MappingProxyType({ + "fields": MappingProxyType({ + "id": "integer", + "warehouse": "integer", + "name": "string", + "minimum_order_quantity": "integer", + "minimumOrderQuantity": "integer", + "version": "integer", + }), + "query_fields": MappingProxyType({ + "id": "id", + "warehouse": "warehouse", + "name": "name", + "minimum_order_quantity": "minimum_order_quantity", + "minimumOrderQuantity": "minimum_order_quantity", + "version": "version", + }), + "relations": MappingProxyType({ + "warehouse": "Warehouse", + }), + }), +}) \ No newline at end of file diff --git a/examples/supplier-onboarding-i18n/python-lib-core/models/__init__.py b/examples/supplier-onboarding-i18n/python-lib-core/models/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/supplier-onboarding-i18n/python-lib-core/models/supplier.py b/examples/supplier-onboarding-i18n/python-lib-core/models/supplier.py new file mode 100644 index 00000000..ba3eaae6 --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/models/supplier.py @@ -0,0 +1,469 @@ +from teaql.core.mutation import InsertCommand, UpdateCommand, DeleteCommand, MutationRequest +from teaql.core.list import SmartList +from teaql.core.value import Value +from teaql.core.request_intent import MutationIntent +from teaql.core.projection_properties import ProjectionProperties +from teaql.runtime.loaded_scalar_snapshot import LoadedScalarSnapshots +from teaql.runtime import CheckException, CheckResult, EntityKey, EntityRoot, ObjectLocation +from teaql.runtime import EntityJSONField, EntityJSONSchema, JsonFieldNamingProfile +from importlib import import_module +import itertools +from copy import copy +from models.warehouse import Warehouse + + +class Supplier: + _teaql_json_schema = EntityJSONSchema("Supplier", ( + EntityJSONField("id", "id", "id"), + EntityJSONField("warehouse", "warehouse", "reference", factory=lambda: Warehouse), + EntityJSONField("name", "name", "text"), + EntityJSONField("minimum_order_quantity", "minimumOrderQuantity", "integer"), + EntityJSONField("version", "version", "version"), + ), profile=JsonFieldNamingProfile.parse("camelCase")) + _teaql_temporary_ids = itertools.count(1) + + def to_json(self, *, profile=None): + """Typed model JSON; no query, mutation or transport authorization.""" + return self._teaql_json_schema.dumps(self._teaql_json_view({}), profile=profile) + + def _teaql_json_view(self, seen): + """Detached presentation state; never marks live relations as loaded.""" + if id(self) in seen: + return seen[id(self)] + view = copy(self) + seen[id(self)] = view + view._loaded_fields = set(self._loaded_fields) + value = self.warehouse + if hasattr(value, "_teaql_json_view"): + view.warehouse = value._teaql_json_view(seen) + return view + + @classmethod + def from_json(cls, payload, *, profile=None): + """Hydrate only supplied fields into an independent mutation boundary.""" + return cls._teaql_json_schema.loads(cls, payload, profile=profile) + + @classmethod + def refer(cls, entity_id): + return cls(id=entity_id) + + @classmethod + def _teaql_new_with_fixed_id(cls, entity_id): + """Generated bootstrap capability; application code must not call it.""" + return cls(id=entity_id)._teaql_force_create() + + def _teaql_force_create(self): + self._action = "Create" + self._entity_root.mark_as_new(self._teaql_entity_key()) + return self + + def __init__(self, **kwargs): + self._entity_root = kwargs.pop("_entity_root", None) or EntityRoot() + if "id" in kwargs and "id" not in kwargs: + kwargs["id"] = kwargs.pop("id") + if "warehouse" in kwargs and "warehouse" not in kwargs: + kwargs["warehouse"] = kwargs.pop("warehouse") + if "name" in kwargs and "name" not in kwargs: + kwargs["name"] = kwargs.pop("name") + if "minimum_order_quantity" in kwargs and "minimumOrderQuantity" not in kwargs: + kwargs["minimumOrderQuantity"] = kwargs.pop("minimum_order_quantity") + if "version" in kwargs and "version" not in kwargs: + kwargs["version"] = kwargs.pop("version") + self._projection_properties = ProjectionProperties(kwargs, + ["id", "warehouse", "name", "minimumOrderQuantity", "version"]) + self._action = "Update" if kwargs.get("id") else "Create" + self._comment = None + self._loaded_fields = set(kwargs.keys()) + self.id = kwargs.get("id") + + self.warehouse = kwargs.get("warehouse") + + self.name = kwargs.get("name") + + self.minimumOrderQuantity = kwargs.get("minimumOrderQuantity") + + self.version = kwargs.get("version") + + if isinstance(self.warehouse, dict): + self.warehouse = Warehouse(**self.warehouse) + self._ledger_id = getattr(self, "id", None) + if self._ledger_id is None: + self._ledger_id = -next(self._teaql_temporary_ids) + key = self._teaql_entity_key() + if self._action == "Create": + self._entity_root.mark_as_new(key) + elif getattr(self, "version", None) is not None: + self._entity_root.set_original_version(key, int(self.version)) + LoadedScalarSnapshots.capture(self, self._teaql_snapshot_values()) + + def _teaql_snapshot_values(self): + payload = {} + if "id" in self._loaded_fields: + payload["id"] = Value.I64(self.id) + + if "warehouse" in self._loaded_fields: + payload["warehouse"] = Value.I64(getattr(self.warehouse, "id", self.warehouse)) + + if "name" in self._loaded_fields: + payload["name"] = Value.Text(self.name) + + if "minimumOrderQuantity" in self._loaded_fields: + payload["minimum_order_quantity"] = Value.I64(self.minimumOrderQuantity) + + if "version" in self._loaded_fields: + payload["version"] = Value.I64(self.version) + + return payload + + def _teaql_entity_key(self): + return EntityKey("Supplier", self._ledger_id) + + def _teaql_restore_fixed_values(self, values): + """Runtime-owned restoration supplies only known, equal scalar values.""" + if "name" in values: + value = values["name"] + raw = value.val if isinstance(value, Value) else value + self.name = raw + + if "minimum_order_quantity" in values: + value = values["minimum_order_quantity"] + raw = value.val if isinstance(value, Value) else value + self.minimumOrderQuantity = raw + + + pass + + def get_dynamic_property(self, name): + return self._projection_properties.get(name) + + def _teaql_attach_root(self, root): + if self._entity_root is not root: + root.merge_entity_from(self._entity_root, self._teaql_entity_key()) + self._entity_root = root + return self + def mark_for_deletion(self): + self._action = "Delete" + self._entity_root.mark_as_deleted(self._teaql_entity_key()) + return self + + def audit_as(self, comment: str): + MutationIntent(comment) + self._comment = comment + return self + + async def save(self, context): + # Validate the root reason before ID allocation or provider access. + MutationIntent(self._comment) + context._validate_generated_graph_input("Supplier", + lambda: self._teaql_validate_input_graph(context, set())) + return await context.execute_graph_save( + lambda session: self._teaql_save_within_graph(session.context, session), + prepare=lambda session: self._teaql_prepare_graph(session.context, session), comment=self._comment) + + def _teaql_validate_input_graph(self, context, visited, parent_field=None): + if id(self) in visited: + return + visited.add(id(self)) + LoadedScalarSnapshots.discard_restored_fields(self, context) + if self._entity_root.has_pending(self._teaql_entity_key()): + ledger = dict(self._entity_root.current_change_set().changes()).get(self._teaql_entity_key(), {}) + context._validate_mutation_fields("Supplier", ledger) + if self._action == "Update": + if "id" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("id"), message="Mutation requires a fully loaded entity", entity_type="Supplier")]) + if "warehouse" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("warehouse"), message="Mutation requires a fully loaded entity", entity_type="Supplier")]) + if "name" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("name"), message="Mutation requires a fully loaded entity", entity_type="Supplier")]) + if "minimumOrderQuantity" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("minimum_order_quantity"), message="Mutation requires a fully loaded entity", entity_type="Supplier")]) + if "version" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("version"), message="Mutation requires a fully loaded entity", entity_type="Supplier")]) + _action, command = self._teaql_build_command() + context._validate_required_mutation_input(command, parent_field=parent_field) + + async def _teaql_ensure_business_ids(self, context): + if self._action != "Create": + return + + async def _teaql_reserve_graph_ids(self, context, visited): + object_identity = id(self) + if object_identity in visited: + return + visited.add(object_identity) + if self._action == "Create" and getattr(self, "id", None) is None: + service = context.require_resource("dataService") + allocator = getattr(service, "next_id", None) + if not callable(allocator): + raise RuntimeError( + "Configured dataService does not support stable ID reservation" + ) + old_key = self._teaql_entity_key() + self.id = int(await allocator("Supplier")) + self._loaded_fields.add("id") + self._ledger_id = self.id + new_key = self._teaql_entity_key() + self._entity_root.rekey(old_key, new_key) + self._entity_root.set(new_key, "id", Value.I64(self.id)) + await self._teaql_ensure_business_ids(context) + + async def _teaql_prepare_graph(self, context, session): + # Complete all input/Fix checks before reserving any graph identity. + # Stable IDs then make the final policy plan and TraceScope concrete. + self._teaql_validate_input_graph(context, set()) + session._generated.admit_graph(self) + self._teaql_prepare_input_graph(context, set()) + # Fix may edit a sibling or its version; re-admit the whole graph before IDs. + self._teaql_validate_input_graph(context, set()) + await self._teaql_reserve_graph_ids(context, set()) + self._teaql_preflight_graph(context, session) + session._seal_generated_plan() + + def _teaql_prepare_input_graph(self, context, visited): + if id(self) in visited: + return + visited.add(id(self)) + session = context._graph_session + session._generated.observe(self) + LoadedScalarSnapshots.discard_restored_fields(self, context) + if self._entity_root.has_pending(self._teaql_entity_key()): + ledger = dict(self._entity_root.current_change_set().changes()).get(self._teaql_entity_key(), {}) + context._validate_mutation_fields("Supplier", ledger) + _action, cmd = self._teaql_build_command() + session._generated.fix(self, _action, cmd, deferred_fields=()) + + def _teaql_graph_relations(self): + return {} + + def _teaql_scalar_payload(self): + payload = {} + if "id" in self._loaded_fields: + payload["id"] = Value.I64(self.id) + + if "warehouse" in self._loaded_fields: + reference = self.warehouse + reference_id = getattr(reference, "id", reference) + payload["warehouse"] = (Value.Object(reference) + if reference is not None and hasattr(reference, "id") and reference_id is None + else Value.I64(reference_id)) + + if "name" in self._loaded_fields: + payload["name"] = Value.Text(self.name) + + if "minimumOrderQuantity" in self._loaded_fields: + payload["minimum_order_quantity"] = Value.I64(self.minimumOrderQuantity) + + if "version" in self._loaded_fields: + payload["version"] = Value.I64(self.version) + + return payload + + def _teaql_build_command(self): + payload = self._teaql_scalar_payload() + action = self._action + if action == "Update": + ledger = dict(self._entity_root.current_change_set().changes()).get(self._teaql_entity_key(), {}) + payload = {field: value for field, value in ledger.items() if field not in ("id", "version")} + if "warehouse" in payload: + reference = payload["warehouse"].val + if reference is not None and hasattr(reference, "id") and reference.id is not None: + payload["warehouse"] = Value.I64(reference.id) + if action == "Create": + cmd = InsertCommand("Supplier", payload) + elif action == "Update": + original_version = self._entity_root.original_version(self._teaql_entity_key()) + cmd = UpdateCommand("Supplier", Value.from_any(getattr(self, "id", None)), + original_version if original_version is not None else getattr(self, "version", None)) + for key, value in payload.items(): + if key not in ("id", "version"): cmd.value(key, value) + else: + original_version = self._entity_root.original_version(self._teaql_entity_key()) + cmd = DeleteCommand("Supplier", Value.from_any(getattr(self, "id", None)), + original_version if original_version is not None else getattr(self, "version", None)) + if action != "Create": + cmd.old_values = LoadedScalarSnapshots.values(self) + return action, cmd + + def _teaql_preflight_graph(self, context, session, parent=None): + if not session._generated.visit("plan", self): + return + if parent is None: + MutationIntent(self._comment) + scope = session.scope(self._teaql_entity_key(), parent, self._comment) + session.capture_loaded_values("Supplier", LoadedScalarSnapshots.values(self)) + if self._entity_root.has_pending(self._teaql_entity_key()): + if self._action == "Update": + if "id" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("id"), message="Mutation requires a fully loaded entity", entity_type="Supplier")]) + if "warehouse" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("warehouse"), message="Mutation requires a fully loaded entity", entity_type="Supplier")]) + if "name" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("name"), message="Mutation requires a fully loaded entity", entity_type="Supplier")]) + if "minimumOrderQuantity" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("minimum_order_quantity"), message="Mutation requires a fully loaded entity", entity_type="Supplier")]) + if "version" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("version"), message="Mutation requires a fully loaded entity", entity_type="Supplier")]) + action, cmd = self._teaql_build_command() + action, cmd = session._generated.finalize(self, action, cmd) + session._remember_prepared_mutation(self, action, cmd) + + async def _teaql_save_within_graph(self, context, session, parent=None): + if not session._generated.visit("write", self): + return self + session._generated.validate() + if parent is None: + MutationIntent(self._comment) + + self._teaql_attach_root(self._entity_root) + scope = session.scope(self._teaql_entity_key(), parent, self._comment) + if not self._entity_root.has_pending(self._teaql_entity_key()): + await self._teaql_cascade_children(context, session, scope) + return self + action, cmd = session._prepared_mutation(self) + + + req = session.request(cmd, scope, self._entity_root, self._teaql_entity_key()) + + # Execute the exact final checked command; no third Fix pass in SQL. + context.mark_mutation_checked(cmd) + service = context.require_resource("dataService") + result = await service.mutate(context, req) + persisted = result.persisted_record + if persisted is None: + raise RuntimeError( + "Mutation provider did not return authoritative persisted state for Supplier" + ) + rollback_payload = {field: getattr(self, field, None) for field in self._loaded_fields | {"id", "version"}} + rollback_snapshot = LoadedScalarSnapshots.values(self) + rollback_ledger_id = self._ledger_id + rollback_action = self._action + rollback_loaded_fields = set(self._loaded_fields) + old_key = self._teaql_entity_key() + if "id" in persisted: + self.id = persisted["id"] + self._loaded_fields.add("id") + elif "id" in persisted: + self.id = persisted["id"] + self._loaded_fields.add("id") + if "warehouse" in persisted: + self.warehouse = persisted["warehouse"] + self._loaded_fields.add("warehouse") + elif "warehouse" in persisted: + self.warehouse = persisted["warehouse"] + self._loaded_fields.add("warehouse") + if "name" in persisted: + self.name = persisted["name"] + self._loaded_fields.add("name") + elif "name" in persisted: + self.name = persisted["name"] + self._loaded_fields.add("name") + if "minimum_order_quantity" in persisted: + self.minimumOrderQuantity = persisted["minimum_order_quantity"] + self._loaded_fields.add("minimumOrderQuantity") + elif "minimumOrderQuantity" in persisted: + self.minimumOrderQuantity = persisted["minimumOrderQuantity"] + self._loaded_fields.add("minimumOrderQuantity") + if "version" in persisted: + self.version = persisted["version"] + self._loaded_fields.add("version") + elif "version" in persisted: + self.version = persisted["version"] + self._loaded_fields.add("version") + self._ledger_id = getattr(self, "id", self._ledger_id) + new_key = self._teaql_entity_key() + if old_key != new_key: + self._entity_root.rekey(old_key, new_key) + def rollback_entity(): + for field, value in rollback_payload.items(): + setattr(self, field, value) + self._ledger_id = rollback_ledger_id + self._action = rollback_action + self._loaded_fields = rollback_loaded_fields + LoadedScalarSnapshots.restore(self, rollback_snapshot) + if old_key != new_key: + self._entity_root.rekey(new_key, old_key) + session.after_rollback(rollback_entity) + if action != "Delete": + self._action = "Update" + session._generated.accepted(self) + + if action != "Delete": + await self._teaql_cascade_children(context, session, scope) + def commit_entity(): + session._generated.validate() + LoadedScalarSnapshots.capture(self, self._teaql_snapshot_values()) + self._entity_root.clear_entity(new_key) + if getattr(self, "version", None) is not None: + self._entity_root.accept_committed_version(new_key, int(self.version)) + session._generated.accepted(self) + session.after_commit(commit_entity) + return self + + async def _teaql_cascade_children(self, context, session, scope): + cascade_relations = [] + for relation_name, children, updater, member in cascade_relations: + for index, child in enumerate(children): + child._teaql_attach_root(self._entity_root) + current = getattr(child, member, None) + if getattr(current, "id", current) != self.id: + getattr(child, updater)(self) + try: + await child._teaql_save_within_graph(context, session, scope) + except CheckException as error: + prefix = ObjectLocation().property(relation_name).index(index) + raise CheckException([ + violation.prefixed_by(prefix) + for violation in error.violations + ]) from error + + def update_id(self, value): + if self._action != "Create": + raise ValueError("ENTITY_ID_IMMUTABLE: an existing entity ID cannot be changed") + value = int(value) if isinstance(value, str) and value.isdecimal() else value + if type(value) is not int or not 0 < value <= 18446744073709551615: + raise ValueError("ENTITY_ID_INVALID: an assigned unsigned-64 identity is required") + old_key = self._teaql_entity_key() + self._ledger_id = value + self._entity_root.rekey(old_key, self._teaql_entity_key()) + if "id" in self._loaded_fields and LoadedScalarSnapshots.same_value(self.id, value): + return self + self.id = value + self._loaded_fields.add("id") + self._entity_root.set(self._teaql_entity_key(), "id", Value.from_any(value)) + return self + + def update_name(self, value): + if "name" in self._loaded_fields and LoadedScalarSnapshots.same_value(self.name, value): + return self + self.name = value + self._loaded_fields.add("name") + self._entity_root.set(self._teaql_entity_key(), "name", Value.from_any(value)) + return self + + def update_minimum_order_quantity(self, value): + if "minimumOrderQuantity" in self._loaded_fields and LoadedScalarSnapshots.same_value(self.minimumOrderQuantity, value): + return self + self.minimumOrderQuantity = value + self._loaded_fields.add("minimumOrderQuantity") + self._entity_root.set(self._teaql_entity_key(), "minimum_order_quantity", Value.from_any(value)) + return self + + def update_version(self, value): + if "version" in self._loaded_fields and LoadedScalarSnapshots.same_value(self.version, value): + return self + self.version = value + self._loaded_fields.add("version") + self._entity_root.set(self._teaql_entity_key(), "version", Value.from_any(value)) + return self + def update_warehouse(self, value): + assigned_id = getattr(value, "id", value) if value else None + current = self.warehouse + current_id = getattr(current, "id", current) + if "warehouse" in self._loaded_fields and LoadedScalarSnapshots.same_value(current_id, assigned_id) and (assigned_id is not None or current is value): + return self + self.warehouse = value if value is not None and hasattr(value, "id") and assigned_id is None else assigned_id + self._loaded_fields.add("warehouse") + self._entity_root.set(self._teaql_entity_key(), "warehouse", + Value.Object(self.warehouse) if self.warehouse is not None and hasattr(self.warehouse, "id") + else Value.from_any(self.warehouse)) + return self diff --git a/examples/supplier-onboarding-i18n/python-lib-core/models/warehouse.py b/examples/supplier-onboarding-i18n/python-lib-core/models/warehouse.py new file mode 100644 index 00000000..62205eaa --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/models/warehouse.py @@ -0,0 +1,448 @@ +from teaql.core.mutation import InsertCommand, UpdateCommand, DeleteCommand, MutationRequest +from teaql.core.list import SmartList +from teaql.core.value import Value +from teaql.core.request_intent import MutationIntent +from teaql.core.projection_properties import ProjectionProperties +from teaql.runtime.loaded_scalar_snapshot import LoadedScalarSnapshots +from teaql.runtime import CheckException, CheckResult, EntityKey, EntityRoot, ObjectLocation +from teaql.runtime import EntityJSONField, EntityJSONSchema, JsonFieldNamingProfile +from importlib import import_module +import itertools +from copy import copy + + +class Warehouse: + _teaql_json_schema = EntityJSONSchema("Warehouse", ( + EntityJSONField("id", "id", "id"), + EntityJSONField("name", "name", "text"), + EntityJSONField("version", "version", "version"), + EntityJSONField("supplier_list", "_supplier_list", "many", factory=lambda: getattr(import_module("models.supplier"), "Supplier"), loaded_name="supplier_list") + ), profile=JsonFieldNamingProfile.parse("camelCase")) + _teaql_temporary_ids = itertools.count(1) + + def to_json(self, *, profile=None): + """Typed model JSON; no query, mutation or transport authorization.""" + return self._teaql_json_schema.dumps(self._teaql_json_view({}), profile=profile) + + def _teaql_json_view(self, seen): + """Detached presentation state; never marks live relations as loaded.""" + if id(self) in seen: + return seen[id(self)] + view = copy(self) + seen[id(self)] = view + view._loaded_fields = set(self._loaded_fields) + children = self._supplier_list + if children.is_loaded or any(child._entity_root.has_pending(child._teaql_entity_key()) for child in children): + view._loaded_fields.add("supplier_list") + view._supplier_list = [child._teaql_json_view(seen) for child in children] + return view + + @classmethod + def from_json(cls, payload, *, profile=None): + """Hydrate only supplied fields into an independent mutation boundary.""" + return cls._teaql_json_schema.loads(cls, payload, profile=profile) + + @classmethod + def refer(cls, entity_id): + return cls(id=entity_id) + + @classmethod + def _teaql_new_with_fixed_id(cls, entity_id): + """Generated bootstrap capability; application code must not call it.""" + return cls(id=entity_id)._teaql_force_create() + + def _teaql_force_create(self): + self._action = "Create" + self._entity_root.mark_as_new(self._teaql_entity_key()) + return self + + def __init__(self, **kwargs): + self._entity_root = kwargs.pop("_entity_root", None) or EntityRoot() + if "id" in kwargs and "id" not in kwargs: + kwargs["id"] = kwargs.pop("id") + if "name" in kwargs and "name" not in kwargs: + kwargs["name"] = kwargs.pop("name") + if "version" in kwargs and "version" not in kwargs: + kwargs["version"] = kwargs.pop("version") + self._projection_properties = ProjectionProperties(kwargs, + ["id", "name", "version", "supplier_list"]) + self._action = "Update" if kwargs.get("id") else "Create" + self._comment = None + self._loaded_fields = set(kwargs.keys()) + self.id = kwargs.get("id") + + self.name = kwargs.get("name") + + self.version = kwargs.get("version") + + if "supplier_list" in kwargs or kwargs.get("id") is None: + supplied = kwargs.get("supplier_list") + self._supplier_list = supplied.map(lambda item: item) if isinstance(supplied, SmartList) else SmartList(supplied or ()) + self._loaded_fields.add("supplier_list") + else: + self._supplier_list = SmartList.empty() + if self._supplier_list: + from models.supplier import Supplier + self._supplier_list = self._supplier_list.map( + lambda item: item if isinstance(item, Supplier) else Supplier(_entity_root=self._entity_root, **item) + ) + self._ledger_id = getattr(self, "id", None) + if self._ledger_id is None: + self._ledger_id = -next(self._teaql_temporary_ids) + key = self._teaql_entity_key() + if self._action == "Create": + self._entity_root.mark_as_new(key) + elif getattr(self, "version", None) is not None: + self._entity_root.set_original_version(key, int(self.version)) + LoadedScalarSnapshots.capture(self, self._teaql_snapshot_values()) + + def _teaql_snapshot_values(self): + payload = {} + if "id" in self._loaded_fields: + payload["id"] = Value.I64(self.id) + + if "name" in self._loaded_fields: + payload["name"] = Value.Text(self.name) + + if "version" in self._loaded_fields: + payload["version"] = Value.I64(self.version) + + return payload + + def _teaql_entity_key(self): + return EntityKey("Warehouse", self._ledger_id) + + def _teaql_restore_fixed_values(self, values): + """Runtime-owned restoration supplies only known, equal scalar values.""" + if "name" in values: + value = values["name"] + raw = value.val if isinstance(value, Value) else value + self.name = raw + + + pass + + def get_dynamic_property(self, name): + return self._projection_properties.get(name) + + def _teaql_attach_root(self, root): + if self._entity_root is not root: + root.merge_entity_from(self._entity_root, self._teaql_entity_key()) + self._entity_root = root + for child in self._supplier_list: + child._teaql_attach_root(root) + return self + def mark_for_deletion(self): + self._action = "Delete" + self._entity_root.mark_as_deleted(self._teaql_entity_key()) + return self + + def audit_as(self, comment: str): + MutationIntent(comment) + self._comment = comment + return self + + async def save(self, context): + # Validate the root reason before ID allocation or provider access. + MutationIntent(self._comment) + context._validate_generated_graph_input("Warehouse", + lambda: self._teaql_validate_input_graph(context, set())) + return await context.execute_graph_save( + lambda session: self._teaql_save_within_graph(session.context, session), + prepare=lambda session: self._teaql_prepare_graph(session.context, session), comment=self._comment) + + def _teaql_validate_input_graph(self, context, visited, parent_field=None): + if id(self) in visited: + return + visited.add(id(self)) + LoadedScalarSnapshots.discard_restored_fields(self, context) + if self._entity_root.has_pending(self._teaql_entity_key()): + ledger = dict(self._entity_root.current_change_set().changes()).get(self._teaql_entity_key(), {}) + context._validate_mutation_fields("Warehouse", ledger) + if self._action == "Update": + if "id" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("id"), message="Mutation requires a fully loaded entity", entity_type="Warehouse")]) + if "name" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("name"), message="Mutation requires a fully loaded entity", entity_type="Warehouse")]) + if "version" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("version"), message="Mutation requires a fully loaded entity", entity_type="Warehouse")]) + _action, command = self._teaql_build_command() + context._validate_required_mutation_input(command, parent_field=parent_field) + for index, child in enumerate(self._supplier_list): + try: + child._teaql_validate_input_graph(context, visited, "warehouse") + except CheckException as error: + prefix = ObjectLocation().property("supplier_list").index(index) + raise CheckException([ + v.prefixed_by(prefix) + for v in error.violations + ]) from error + + async def _teaql_ensure_business_ids(self, context): + if self._action != "Create": + return + + async def _teaql_reserve_graph_ids(self, context, visited): + object_identity = id(self) + if object_identity in visited: + return + visited.add(object_identity) + if self._action == "Create" and getattr(self, "id", None) is None: + service = context.require_resource("dataService") + allocator = getattr(service, "next_id", None) + if not callable(allocator): + raise RuntimeError( + "Configured dataService does not support stable ID reservation" + ) + old_key = self._teaql_entity_key() + self.id = int(await allocator("Warehouse")) + self._loaded_fields.add("id") + self._ledger_id = self.id + new_key = self._teaql_entity_key() + self._entity_root.rekey(old_key, new_key) + self._entity_root.set(new_key, "id", Value.I64(self.id)) + await self._teaql_ensure_business_ids(context) + for child in self._supplier_list: + child._teaql_attach_root(self._entity_root) + await child._teaql_reserve_graph_ids(context, visited) + + async def _teaql_prepare_graph(self, context, session): + # Complete all input/Fix checks before reserving any graph identity. + # Stable IDs then make the final policy plan and TraceScope concrete. + self._teaql_validate_input_graph(context, set()) + session._generated.admit_graph(self) + self._teaql_prepare_input_graph(context, set()) + # Fix may edit a sibling or its version; re-admit the whole graph before IDs. + self._teaql_validate_input_graph(context, set()) + await self._teaql_reserve_graph_ids(context, set()) + self._teaql_preflight_graph(context, session) + session._seal_generated_plan() + + def _teaql_prepare_input_graph(self, context, visited): + if id(self) in visited: + return + visited.add(id(self)) + session = context._graph_session + session._generated.observe(self) + LoadedScalarSnapshots.discard_restored_fields(self, context) + if self._entity_root.has_pending(self._teaql_entity_key()): + ledger = dict(self._entity_root.current_change_set().changes()).get(self._teaql_entity_key(), {}) + context._validate_mutation_fields("Warehouse", ledger) + _action, cmd = self._teaql_build_command() + session._generated.fix(self, _action, cmd, deferred_fields=()) + for index, child in enumerate(self._supplier_list): + child._teaql_attach_root(self._entity_root) + # The object reference exists even before either endpoint has a stable ID. + # Do not confuse two absent IDs with an already-established association. + if getattr(child, "warehouse", None) is not self: + child.update_warehouse(self) + try: + child._teaql_prepare_input_graph(context, visited) + except CheckException as error: + prefix = ObjectLocation().property("supplier_list").index(index) + raise CheckException([ + v.prefixed_by(prefix) + for v in error.violations + ]) from error + + def _teaql_graph_relations(self): + return {"supplier_list": tuple(self._supplier_list)} + + def _teaql_scalar_payload(self): + payload = {} + if "id" in self._loaded_fields: + payload["id"] = Value.I64(self.id) + + if "name" in self._loaded_fields: + payload["name"] = Value.Text(self.name) + + if "version" in self._loaded_fields: + payload["version"] = Value.I64(self.version) + + return payload + + def _teaql_build_command(self): + payload = self._teaql_scalar_payload() + action = self._action + if action == "Update": + ledger = dict(self._entity_root.current_change_set().changes()).get(self._teaql_entity_key(), {}) + payload = {field: value for field, value in ledger.items() if field not in ("id", "version")} + if action == "Create": + cmd = InsertCommand("Warehouse", payload) + elif action == "Update": + original_version = self._entity_root.original_version(self._teaql_entity_key()) + cmd = UpdateCommand("Warehouse", Value.from_any(getattr(self, "id", None)), + original_version if original_version is not None else getattr(self, "version", None)) + for key, value in payload.items(): + if key not in ("id", "version"): cmd.value(key, value) + else: + original_version = self._entity_root.original_version(self._teaql_entity_key()) + cmd = DeleteCommand("Warehouse", Value.from_any(getattr(self, "id", None)), + original_version if original_version is not None else getattr(self, "version", None)) + if action != "Create": + cmd.old_values = LoadedScalarSnapshots.values(self) + return action, cmd + + def _teaql_preflight_graph(self, context, session, parent=None): + if not session._generated.visit("plan", self): + return + if parent is None: + MutationIntent(self._comment) + scope = session.scope(self._teaql_entity_key(), parent, self._comment) + session.capture_loaded_values("Warehouse", LoadedScalarSnapshots.values(self)) + if self._entity_root.has_pending(self._teaql_entity_key()): + if self._action == "Update": + if "id" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("id"), message="Mutation requires a fully loaded entity", entity_type="Warehouse")]) + if "name" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("name"), message="Mutation requires a fully loaded entity", entity_type="Warehouse")]) + if "version" not in self._loaded_fields: + raise CheckException([CheckResult("invalid_type", ObjectLocation().property("version"), message="Mutation requires a fully loaded entity", entity_type="Warehouse")]) + action, cmd = self._teaql_build_command() + action, cmd = session._generated.finalize(self, action, cmd) + session._remember_prepared_mutation(self, action, cmd) + for index, child in enumerate(self._supplier_list): + child._teaql_attach_root(self._entity_root) + current = getattr(child, "warehouse", None) + if getattr(current, "id", current) != self.id: + child.update_warehouse(self) + try: + child._teaql_preflight_graph(context, session, scope) + except CheckException as error: + prefix = ObjectLocation().property("supplier_list").index(index) + raise CheckException([ + v.prefixed_by(prefix) + for v in error.violations + ]) from error + + async def _teaql_save_within_graph(self, context, session, parent=None): + if not session._generated.visit("write", self): + return self + session._generated.validate() + if parent is None: + MutationIntent(self._comment) + + self._teaql_attach_root(self._entity_root) + scope = session.scope(self._teaql_entity_key(), parent, self._comment) + if not self._entity_root.has_pending(self._teaql_entity_key()): + await self._teaql_cascade_children(context, session, scope) + return self + action, cmd = session._prepared_mutation(self) + + + req = session.request(cmd, scope, self._entity_root, self._teaql_entity_key()) + + # Execute the exact final checked command; no third Fix pass in SQL. + context.mark_mutation_checked(cmd) + service = context.require_resource("dataService") + result = await service.mutate(context, req) + persisted = result.persisted_record + if persisted is None: + raise RuntimeError( + "Mutation provider did not return authoritative persisted state for Warehouse" + ) + rollback_payload = {field: getattr(self, field, None) for field in self._loaded_fields | {"id", "version"}} + rollback_snapshot = LoadedScalarSnapshots.values(self) + rollback_ledger_id = self._ledger_id + rollback_action = self._action + rollback_loaded_fields = set(self._loaded_fields) + old_key = self._teaql_entity_key() + if "id" in persisted: + self.id = persisted["id"] + self._loaded_fields.add("id") + elif "id" in persisted: + self.id = persisted["id"] + self._loaded_fields.add("id") + if "name" in persisted: + self.name = persisted["name"] + self._loaded_fields.add("name") + elif "name" in persisted: + self.name = persisted["name"] + self._loaded_fields.add("name") + if "version" in persisted: + self.version = persisted["version"] + self._loaded_fields.add("version") + elif "version" in persisted: + self.version = persisted["version"] + self._loaded_fields.add("version") + self._ledger_id = getattr(self, "id", self._ledger_id) + new_key = self._teaql_entity_key() + if old_key != new_key: + self._entity_root.rekey(old_key, new_key) + def rollback_entity(): + for field, value in rollback_payload.items(): + setattr(self, field, value) + self._ledger_id = rollback_ledger_id + self._action = rollback_action + self._loaded_fields = rollback_loaded_fields + LoadedScalarSnapshots.restore(self, rollback_snapshot) + if old_key != new_key: + self._entity_root.rekey(new_key, old_key) + session.after_rollback(rollback_entity) + if action != "Delete": + self._action = "Update" + session._generated.accepted(self) + + if action != "Delete": + await self._teaql_cascade_children(context, session, scope) + def commit_entity(): + session._generated.validate() + LoadedScalarSnapshots.capture(self, self._teaql_snapshot_values()) + self._entity_root.clear_entity(new_key) + if getattr(self, "version", None) is not None: + self._entity_root.accept_committed_version(new_key, int(self.version)) + session._generated.accepted(self) + session.after_commit(commit_entity) + return self + + async def _teaql_cascade_children(self, context, session, scope): + cascade_relations = [] + cascade_relations.append(("supplier_list", self._supplier_list, "update_warehouse", "warehouse")) + for relation_name, children, updater, member in cascade_relations: + for index, child in enumerate(children): + child._teaql_attach_root(self._entity_root) + current = getattr(child, member, None) + if getattr(current, "id", current) != self.id: + getattr(child, updater)(self) + try: + await child._teaql_save_within_graph(context, session, scope) + except CheckException as error: + prefix = ObjectLocation().property(relation_name).index(index) + raise CheckException([ + violation.prefixed_by(prefix) + for violation in error.violations + ]) from error + + def update_id(self, value): + if self._action != "Create": + raise ValueError("ENTITY_ID_IMMUTABLE: an existing entity ID cannot be changed") + value = int(value) if isinstance(value, str) and value.isdecimal() else value + if type(value) is not int or not 0 < value <= 18446744073709551615: + raise ValueError("ENTITY_ID_INVALID: an assigned unsigned-64 identity is required") + old_key = self._teaql_entity_key() + self._ledger_id = value + self._entity_root.rekey(old_key, self._teaql_entity_key()) + if "id" in self._loaded_fields and LoadedScalarSnapshots.same_value(self.id, value): + return self + self.id = value + self._loaded_fields.add("id") + self._entity_root.set(self._teaql_entity_key(), "id", Value.from_any(value)) + return self + + def update_name(self, value): + if "name" in self._loaded_fields and LoadedScalarSnapshots.same_value(self.name, value): + return self + self.name = value + self._loaded_fields.add("name") + self._entity_root.set(self._teaql_entity_key(), "name", Value.from_any(value)) + return self + + def update_version(self, value): + if "version" in self._loaded_fields and LoadedScalarSnapshots.same_value(self.version, value): + return self + self.version = value + self._loaded_fields.add("version") + self._entity_root.set(self._teaql_entity_key(), "version", Value.from_any(value)) + return self + def supplier_list(self) -> "SmartList[Supplier]": + return self._supplier_list diff --git a/examples/supplier-onboarding-i18n/python-lib-core/pyproject.toml b/examples/supplier-onboarding-i18n/python-lib-core/pyproject.toml new file mode 100644 index 00000000..1cd0e09e --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/pyproject.toml @@ -0,0 +1,16 @@ +[project] +name = "supplier-onboarding-service-lib" +version = "1.0.0" +description = "Generated python library" +dependencies = ["teaql==0.6.0", "aiosqlite>=0.22.1"] + +[tool.setuptools] +py-modules = ["Q", "E", "runtime_module", "generated_search_models"] + +[tool.setuptools.packages.find] +where = ["."] +include = ["models*", "requests*"] + +[build-system] +requires = ["setuptools>=42"] +build-backend = "setuptools.build_meta" \ No newline at end of file diff --git a/examples/supplier-onboarding-i18n/python-lib-core/requests/__init__.py b/examples/supplier-onboarding-i18n/python-lib-core/requests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/supplier-onboarding-i18n/python-lib-core/requests/supplier_request.py b/examples/supplier-onboarding-i18n/python-lib-core/requests/supplier_request.py new file mode 100644 index 00000000..35f857b8 --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/requests/supplier_request.py @@ -0,0 +1,539 @@ +from teaql.core.query import AggregateFunction, RelationAggregate, SelectQuery +from teaql.core.request_tree import QueryOperation +from teaql.core.dynamic_search import merge_generated_scalar_search +from generated_search_models import GENERATED_SEARCH_MODELS +from teaql.core.list import SmartList +from teaql.core.request_intent import QueryIntent +from teaql.runtime import EntityRoot +from teaql.data_service import QueryRequest +from copy import deepcopy +from teaql.core.expr import ( + begin_with, between, column, contain, end_with, eq, gt, gte, + in_list, in_subquery, is_not_null, is_null, lt, lte, ne, not_begin_with, + not_contain, not_end_with, not_in_list, not_in_subquery, value, + sound_like, +) +from models.supplier import Supplier +from typing import Protocol + +class QuerySelection(Protocol): + query: SelectQuery + +class SupplierRequest: + def __init__(self, minimal=False): + self.query = SelectQuery("Supplier") + self._purpose = None + self._comment = None + self._page_count_alias = None + self._page_count_method = None + self._dynamic_search_warnings = [] + self.query.and_filter(gte("version", 1)) + if minimal: + self.select_id() + self.select_version() + else: + self.select_self_fields() + + def comment(self, c: str): + self.query.comment(c) + self._comment = c + return self + + def filter_by_json(self, source, warn=None): + kwargs = {} if warn is None else {"warn": warn} + query, warnings = merge_generated_scalar_search(self.query, source, GENERATED_SEARCH_MODELS, **kwargs) + self.query = query + self._dynamic_search_warnings.extend(warnings) + return self + + @property + def dynamic_search_warnings(self): + return tuple(dict(warning) for warning in self._dynamic_search_warnings) + + def purpose(self, p: str): + self.query.purpose(p) + self._purpose = p + return ExecutableSupplierRequest(self) + + def optimize_for_continuous_page_fetch(self): + self.query.optimize_for_continuous_page_fetch() + return self + + def optimize_for_continuous_page_fetch_with(self, namespace: str, ttl_seconds: int): + self.query.optimize_for_continuous_page_fetch_with(namespace, ttl_seconds) + return self + + def optimize_pagination_with_id_set(self): + self.query.optimize_pagination_with_id_set() + return self + + def optimize_pagination_with_id_set_config(self, namespace: str, ttl_seconds: int, max_ids: int): + self.query.optimize_pagination_with_id_set_config(namespace, ttl_seconds, max_ids) + return self + + def top_n_probe_parent_threshold(self, threshold: int): + self.query.top_n_probe_parent_threshold(threshold) + return self + + def limit(self, n: int): + self.query.limit(n) + return self + + def offset(self, n: int): + self.query.offset(n) + return self + + def with_deleted_rows(self): + self.query.with_deleted_rows() + return self + + def deleted_rows_only(self): + self.query.deleted_rows_only() + return self + + def select_self_fields(self): + self.query.project("id", "warehouse", "name", "minimum_order_quantity", "version") + return self + + def select_id(self): + self.query.project("id") + return self + + + def select_name(self): + self.query.project("name") + return self + + def select_minimum_order_quantity(self): + self.query.project("minimum_order_quantity") + return self + + def select_version(self): + self.query.project("version") + return self + + def select_warehouse_with(self, child_request): + self.query.project("warehouse") + self.query.relation_query("warehouse", child_request.query, + QueryOperation("relation-select", "select_warehouse_with", relation="warehouse")) + return self + def with_warehouse_matching(self, child_request): + child_request.query.projection = ["id"] + self.query.and_filter(in_subquery(column("warehouse"), "Warehouse", child_request.query)) + return self + + def without_warehouse_matching(self, child_request): + child_request.query.projection = ["id"] + self.query.and_filter(not_in_subquery(column("warehouse"), "Warehouse", child_request.query)) + return self + + def have_warehouse(self): + self.query.and_filter(is_not_null(column("warehouse"))) + return self + + def have_no_warehouse(self): + self.query.and_filter(is_null(column("warehouse"))) + return self + + def with_id_is(self, val): + self.query.and_filter(eq("id", val)) + return self + + def with_id_is_not(self, val): + self.query.and_filter(ne("id", val)) + return self + + def with_id_in(self, *vals): + self.query.and_filter(in_list("id", list(vals))) + return self + + def with_id_not_in(self, *vals): + self.query.and_filter(not_in_list("id", list(vals))) + return self + + def with_id_greater_than(self, val): + self.query.and_filter(gt("id", val)) + return self + + def with_id_greater_than_or_equal_to(self, val): + self.query.and_filter(gte("id", val)) + return self + + def with_id_less_than(self, val): + self.query.and_filter(lt("id", val)) + return self + + def with_id_less_than_or_equal_to(self, val): + self.query.and_filter(lte("id", val)) + return self + + def with_id_between(self, lower, upper): + self.query.and_filter(between(column("id"), value(lower), value(upper))) + return self + + def with_id_is_known(self): + self.query.and_filter(is_not_null(column("id"))) + return self + + def with_id_is_unknown(self): + self.query.and_filter(is_null(column("id"))) + return self + + def filter_by_warehouse(self, val): + self.query.and_filter(eq("warehouse", val)) + return self + + def with_name_containing(self, val: str): + self.query.and_filter(contain("name", val)) + return self + + def with_name_not_containing(self, val: str): + self.query.and_filter(not_contain("name", val)) + return self + + def with_name_starting_with(self, val: str): + self.query.and_filter(begin_with("name", val)) + return self + + def with_name_not_starting_with(self, val: str): + self.query.and_filter(not_begin_with("name", val)) + return self + + def with_name_ending_with(self, val: str): + self.query.and_filter(end_with("name", val)) + return self + + def with_name_not_ending_with(self, val: str): + self.query.and_filter(not_end_with("name", val)) + return self + + def with_name_sounding_like(self, val: str): + self.query.and_filter(sound_like("name", val)) + return self + + def with_name_is(self, val: str): + self.query.and_filter(eq("name", val)) + return self + def with_name_is_not(self, val): + self.query.and_filter(ne("name", val)) + return self + + def with_name_in(self, *vals): + self.query.and_filter(in_list("name", list(vals))) + return self + + def with_name_not_in(self, *vals): + self.query.and_filter(not_in_list("name", list(vals))) + return self + + def with_name_greater_than(self, val): + self.query.and_filter(gt("name", val)) + return self + + def with_name_greater_than_or_equal_to(self, val): + self.query.and_filter(gte("name", val)) + return self + + def with_name_less_than(self, val): + self.query.and_filter(lt("name", val)) + return self + + def with_name_less_than_or_equal_to(self, val): + self.query.and_filter(lte("name", val)) + return self + + def with_name_between(self, lower, upper): + self.query.and_filter(between(column("name"), value(lower), value(upper))) + return self + + def with_name_is_known(self): + self.query.and_filter(is_not_null(column("name"))) + return self + + def with_name_is_unknown(self): + self.query.and_filter(is_null(column("name"))) + return self + + def with_minimum_order_quantity_is(self, val): + self.query.and_filter(eq("minimum_order_quantity", val)) + return self + + def with_minimum_order_quantity_is_not(self, val): + self.query.and_filter(ne("minimum_order_quantity", val)) + return self + + def with_minimum_order_quantity_in(self, *vals): + self.query.and_filter(in_list("minimum_order_quantity", list(vals))) + return self + + def with_minimum_order_quantity_not_in(self, *vals): + self.query.and_filter(not_in_list("minimum_order_quantity", list(vals))) + return self + + def with_minimum_order_quantity_greater_than(self, val): + self.query.and_filter(gt("minimum_order_quantity", val)) + return self + + def with_minimum_order_quantity_greater_than_or_equal_to(self, val): + self.query.and_filter(gte("minimum_order_quantity", val)) + return self + + def with_minimum_order_quantity_less_than(self, val): + self.query.and_filter(lt("minimum_order_quantity", val)) + return self + + def with_minimum_order_quantity_less_than_or_equal_to(self, val): + self.query.and_filter(lte("minimum_order_quantity", val)) + return self + + def with_minimum_order_quantity_between(self, lower, upper): + self.query.and_filter(between(column("minimum_order_quantity"), value(lower), value(upper))) + return self + + def with_minimum_order_quantity_is_known(self): + self.query.and_filter(is_not_null(column("minimum_order_quantity"))) + return self + + def with_minimum_order_quantity_is_unknown(self): + self.query.and_filter(is_null(column("minimum_order_quantity"))) + return self + + def with_version_is(self, val): + self.query.and_filter(eq("version", val)) + return self + + def with_version_is_not(self, val): + self.query.and_filter(ne("version", val)) + return self + + def with_version_in(self, *vals): + self.query.and_filter(in_list("version", list(vals))) + return self + + def with_version_not_in(self, *vals): + self.query.and_filter(not_in_list("version", list(vals))) + return self + + def with_version_greater_than(self, val): + self.query.and_filter(gt("version", val)) + return self + + def with_version_greater_than_or_equal_to(self, val): + self.query.and_filter(gte("version", val)) + return self + + def with_version_less_than(self, val): + self.query.and_filter(lt("version", val)) + return self + + def with_version_less_than_or_equal_to(self, val): + self.query.and_filter(lte("version", val)) + return self + + def with_version_between(self, lower, upper): + self.query.and_filter(between(column("version"), value(lower), value(upper))) + return self + + def with_version_is_known(self): + self.query.and_filter(is_not_null(column("version"))) + return self + + def with_version_is_unknown(self): + self.query.and_filter(is_null(column("version"))) + return self + + def order_by_id_ascending(self): + self.query.order_by("id", "asc") + return self + + def order_by_id_descending(self): + self.query.order_by("id", "desc") + return self + + + def order_by_name_ascending(self): + self.query.order_by("name", "asc") + return self + + def order_by_name_descending(self): + self.query.order_by("name", "desc") + return self + + def order_by_minimum_order_quantity_ascending(self): + self.query.order_by("minimum_order_quantity", "asc") + return self + + def order_by_minimum_order_quantity_descending(self): + self.query.order_by("minimum_order_quantity", "desc") + return self + + def order_by_version_ascending(self): + self.query.order_by("version", "asc") + return self + + def order_by_version_descending(self): + self.query.order_by("version", "desc") + return self + + + def count(self): + self.query.count_field("id", "count") + self._page_count_alias = "count" + self._page_count_method = "count" + return self + + def count_as(self, ret_name: str): + self.query.count_field("id", ret_name) + self._page_count_alias = ret_name + self._page_count_method = "count_as" + return self + + def min_minimum_order_quantity(self): + return self.min_minimum_order_quantity_as("minOfMinimumOrderQuantity") + + def min_minimum_order_quantity_as(self, ret_name: str): + self.query.min("minimum_order_quantity", ret_name) + return self + def max_minimum_order_quantity(self): + return self.max_minimum_order_quantity_as("maxOfMinimumOrderQuantity") + + def max_minimum_order_quantity_as(self, ret_name: str): + self.query.max("minimum_order_quantity", ret_name) + return self + def sum_minimum_order_quantity(self): + return self.sum_minimum_order_quantity_as("sumOfMinimumOrderQuantity") + + def sum_minimum_order_quantity_as(self, ret_name: str): + self.query.sum("minimum_order_quantity", ret_name) + return self + def avg_minimum_order_quantity(self): + return self.avg_minimum_order_quantity_as("avgOfMinimumOrderQuantity") + + def avg_minimum_order_quantity_as(self, ret_name: str): + self.query.avg("minimum_order_quantity", ret_name) + return self + def standardDeviation_minimum_order_quantity(self): + return self.standardDeviation_minimum_order_quantity_as("standardDeviationOfMinimumOrderQuantity") + + def standardDeviation_minimum_order_quantity_as(self, ret_name: str): + self.query.standardDeviation("minimum_order_quantity", ret_name) + return self + def squareRootOfPopulationStandardDeviation_minimum_order_quantity(self): + return self.squareRootOfPopulationStandardDeviation_minimum_order_quantity_as("squareRootOfPopulationStandardDeviationOfMinimumOrderQuantity") + + def squareRootOfPopulationStandardDeviation_minimum_order_quantity_as(self, ret_name: str): + self.query.squareRootOfPopulationStandardDeviation("minimum_order_quantity", ret_name) + return self + def sampleVariance_minimum_order_quantity(self): + return self.sampleVariance_minimum_order_quantity_as("sampleVarianceOfMinimumOrderQuantity") + + def sampleVariance_minimum_order_quantity_as(self, ret_name: str): + self.query.sampleVariance("minimum_order_quantity", ret_name) + return self + def samplePopulationVariance_minimum_order_quantity(self): + return self.samplePopulationVariance_minimum_order_quantity_as("samplePopulationVarianceOfMinimumOrderQuantity") + + def samplePopulationVariance_minimum_order_quantity_as(self, ret_name: str): + self.query.samplePopulationVariance("minimum_order_quantity", ret_name) + return self + def group_by_id(self): + self.query.group_by("id") + return self + + def group_by_id_as(self, ret_name: str): + self.query.group_by("id") + return self + def group_by_warehouse(self): + self.query.group_by("warehouse") + return self + + def group_by_warehouse_as(self, ret_name: str): + self.query.group_by("warehouse") + return self + def group_by_name(self): + self.query.group_by("name") + return self + + def group_by_name_as(self, ret_name: str): + self.query.group_by("name") + return self + def group_by_minimum_order_quantity(self): + self.query.group_by("minimum_order_quantity") + return self + + def group_by_minimum_order_quantity_as(self, ret_name: str): + self.query.group_by("minimum_order_quantity") + return self + def group_by_version(self): + self.query.group_by("version") + return self + + def group_by_version_as(self, ret_name: str): + self.query.group_by("version") + return self + def facet_by_warehouse_as(self, name: str, request: QuerySelection, + include_all_facets: bool = True): + self.query.facet_by(name, "warehouse", request.query, include_all_facets, + QueryOperation("facet", "facet_by_warehouse_as", name, "warehouse")) + return self + + +class ExecutableSupplierRequest: + def __init__(self, request): + self._request = request + + def comment(self, c: str): + self._request.comment(c) + return self + + def new_entity(self, context) -> Supplier: + request = self._request + QueryIntent(request._comment, request._purpose) + entity = context.initialize_entity("Supplier", Supplier()) + if not isinstance(entity, Supplier): + raise TypeError("entity initializer returned an incompatible Supplier") + return entity + + async def execute_for_result(self, context): + self = self._request + req = QueryRequest(self.query, _comment=self._comment, _purpose=self._purpose) + req = context.prepare_query_request(req) + service = context.require_resource("dataService") + return await service.query(context, req) + + async def execute_for_rows(self, context): + return (await self.execute_for_result(context)).rows + + async def execute_for_list(self, context) -> SmartList[Supplier]: + from teaql.runtime.query_list import execute_typed_list + request = self._request + QueryIntent(request._comment, request._purpose) + query = deepcopy(request.query) + authorized = context.prepare_query(query) + root = QueryRequest(authorized, _comment=request._comment, _purpose=request._purpose) + operation = (QueryOperation("named-count", request._page_count_method or "count", + request._page_count_alias if request._page_count_method == "count_as" else None) + if request._page_count_alias is not None else None) + return await execute_typed_list(context, root, + lambda row: Supplier(_entity_root=EntityRoot(), **row), + count_operation=operation, count_alias=request._page_count_alias) + + async def execute_for_one(self, context): + request = deepcopy(self._request) + request.limit(1) + entities = await ExecutableSupplierRequest(request).execute_for_list(context) + return entities[0] if entities else None + + def execute_for_stream(self, context, chunk_size: int = 1000): + """Yield entity chunks lazily from the provider cursor.""" + request = deepcopy(self._request) + QueryIntent(request._comment, request._purpose) + service = context.require_resource("dataService") + if not hasattr(service, "query_stream"): + raise RuntimeError("dataService does not implement query_stream") + root = QueryRequest(context.prepare_query(request.query), _comment=request._comment, _purpose=request._purpose) + if root.query.aggregates or root.query.group_by_items or root.query.object_group_bys: + raise ValueError("Entity streams require entity rows; use a record or aggregation query") + from teaql.runtime.query_stream import execute_typed_stream + return execute_typed_stream(context, root, + lambda row: Supplier(_entity_root=EntityRoot(), **row), chunk_size) diff --git a/examples/supplier-onboarding-i18n/python-lib-core/requests/warehouse_request.py b/examples/supplier-onboarding-i18n/python-lib-core/requests/warehouse_request.py new file mode 100644 index 00000000..b46e5810 --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/requests/warehouse_request.py @@ -0,0 +1,544 @@ +from teaql.core.query import AggregateFunction, RelationAggregate, SelectQuery +from teaql.core.request_tree import QueryOperation +from teaql.core.dynamic_search import merge_generated_scalar_search +from generated_search_models import GENERATED_SEARCH_MODELS +from teaql.core.list import SmartList +from teaql.core.request_intent import QueryIntent +from teaql.runtime import EntityRoot +from teaql.data_service import QueryRequest +from copy import deepcopy +from teaql.core.expr import ( + begin_with, between, column, contain, end_with, eq, gt, gte, + in_list, in_subquery, is_not_null, is_null, lt, lte, ne, not_begin_with, + not_contain, not_end_with, not_in_list, not_in_subquery, value, + sound_like, +) +from models.warehouse import Warehouse +from typing import Protocol + +class QuerySelection(Protocol): + query: SelectQuery + +class WarehouseRequest: + def __init__(self, minimal=False): + self.query = SelectQuery("Warehouse") + self._purpose = None + self._comment = None + self._page_count_alias = None + self._page_count_method = None + self._dynamic_search_warnings = [] + self.query.and_filter(gte("version", 1)) + if minimal: + self.select_id() + self.select_version() + else: + self.select_self_fields() + + def comment(self, c: str): + self.query.comment(c) + self._comment = c + return self + + def filter_by_json(self, source, warn=None): + kwargs = {} if warn is None else {"warn": warn} + query, warnings = merge_generated_scalar_search(self.query, source, GENERATED_SEARCH_MODELS, **kwargs) + self.query = query + self._dynamic_search_warnings.extend(warnings) + return self + + @property + def dynamic_search_warnings(self): + return tuple(dict(warning) for warning in self._dynamic_search_warnings) + + def purpose(self, p: str): + self.query.purpose(p) + self._purpose = p + return ExecutableWarehouseRequest(self) + + def optimize_for_continuous_page_fetch(self): + self.query.optimize_for_continuous_page_fetch() + return self + + def optimize_for_continuous_page_fetch_with(self, namespace: str, ttl_seconds: int): + self.query.optimize_for_continuous_page_fetch_with(namespace, ttl_seconds) + return self + + def optimize_pagination_with_id_set(self): + self.query.optimize_pagination_with_id_set() + return self + + def optimize_pagination_with_id_set_config(self, namespace: str, ttl_seconds: int, max_ids: int): + self.query.optimize_pagination_with_id_set_config(namespace, ttl_seconds, max_ids) + return self + + def top_n_probe_parent_threshold(self, threshold: int): + self.query.top_n_probe_parent_threshold(threshold) + return self + + def limit(self, n: int): + self.query.limit(n) + return self + + def offset(self, n: int): + self.query.offset(n) + return self + + def with_deleted_rows(self): + self.query.with_deleted_rows() + return self + + def deleted_rows_only(self): + self.query.deleted_rows_only() + return self + + def select_self_fields(self): + self.query.project("id", "name", "version") + return self + + def select_id(self): + self.query.project("id") + return self + + def select_name(self): + self.query.project("name") + return self + + def select_version(self): + self.query.project("version") + return self + + + def with_id_is(self, val): + self.query.and_filter(eq("id", val)) + return self + + def with_id_is_not(self, val): + self.query.and_filter(ne("id", val)) + return self + + def with_id_in(self, *vals): + self.query.and_filter(in_list("id", list(vals))) + return self + + def with_id_not_in(self, *vals): + self.query.and_filter(not_in_list("id", list(vals))) + return self + + def with_id_greater_than(self, val): + self.query.and_filter(gt("id", val)) + return self + + def with_id_greater_than_or_equal_to(self, val): + self.query.and_filter(gte("id", val)) + return self + + def with_id_less_than(self, val): + self.query.and_filter(lt("id", val)) + return self + + def with_id_less_than_or_equal_to(self, val): + self.query.and_filter(lte("id", val)) + return self + + def with_id_between(self, lower, upper): + self.query.and_filter(between(column("id"), value(lower), value(upper))) + return self + + def with_id_is_known(self): + self.query.and_filter(is_not_null(column("id"))) + return self + + def with_id_is_unknown(self): + self.query.and_filter(is_null(column("id"))) + return self + + def with_name_containing(self, val: str): + self.query.and_filter(contain("name", val)) + return self + + def with_name_not_containing(self, val: str): + self.query.and_filter(not_contain("name", val)) + return self + + def with_name_starting_with(self, val: str): + self.query.and_filter(begin_with("name", val)) + return self + + def with_name_not_starting_with(self, val: str): + self.query.and_filter(not_begin_with("name", val)) + return self + + def with_name_ending_with(self, val: str): + self.query.and_filter(end_with("name", val)) + return self + + def with_name_not_ending_with(self, val: str): + self.query.and_filter(not_end_with("name", val)) + return self + + def with_name_sounding_like(self, val: str): + self.query.and_filter(sound_like("name", val)) + return self + + def with_name_is(self, val: str): + self.query.and_filter(eq("name", val)) + return self + def with_name_is_not(self, val): + self.query.and_filter(ne("name", val)) + return self + + def with_name_in(self, *vals): + self.query.and_filter(in_list("name", list(vals))) + return self + + def with_name_not_in(self, *vals): + self.query.and_filter(not_in_list("name", list(vals))) + return self + + def with_name_greater_than(self, val): + self.query.and_filter(gt("name", val)) + return self + + def with_name_greater_than_or_equal_to(self, val): + self.query.and_filter(gte("name", val)) + return self + + def with_name_less_than(self, val): + self.query.and_filter(lt("name", val)) + return self + + def with_name_less_than_or_equal_to(self, val): + self.query.and_filter(lte("name", val)) + return self + + def with_name_between(self, lower, upper): + self.query.and_filter(between(column("name"), value(lower), value(upper))) + return self + + def with_name_is_known(self): + self.query.and_filter(is_not_null(column("name"))) + return self + + def with_name_is_unknown(self): + self.query.and_filter(is_null(column("name"))) + return self + + def with_version_is(self, val): + self.query.and_filter(eq("version", val)) + return self + + def with_version_is_not(self, val): + self.query.and_filter(ne("version", val)) + return self + + def with_version_in(self, *vals): + self.query.and_filter(in_list("version", list(vals))) + return self + + def with_version_not_in(self, *vals): + self.query.and_filter(not_in_list("version", list(vals))) + return self + + def with_version_greater_than(self, val): + self.query.and_filter(gt("version", val)) + return self + + def with_version_greater_than_or_equal_to(self, val): + self.query.and_filter(gte("version", val)) + return self + + def with_version_less_than(self, val): + self.query.and_filter(lt("version", val)) + return self + + def with_version_less_than_or_equal_to(self, val): + self.query.and_filter(lte("version", val)) + return self + + def with_version_between(self, lower, upper): + self.query.and_filter(between(column("version"), value(lower), value(upper))) + return self + + def with_version_is_known(self): + self.query.and_filter(is_not_null(column("version"))) + return self + + def with_version_is_unknown(self): + self.query.and_filter(is_null(column("version"))) + return self + + def order_by_id_ascending(self): + self.query.order_by("id", "asc") + return self + + def order_by_id_descending(self): + self.query.order_by("id", "desc") + return self + + def order_by_name_ascending(self): + self.query.order_by("name", "asc") + return self + + def order_by_name_descending(self): + self.query.order_by("name", "desc") + return self + + def order_by_version_ascending(self): + self.query.order_by("version", "asc") + return self + + def order_by_version_descending(self): + self.query.order_by("version", "desc") + return self + + + def count(self): + self.query.count_field("id", "count") + self._page_count_alias = "count" + self._page_count_method = "count" + return self + + def count_as(self, ret_name: str): + self.query.count_field("id", ret_name) + self._page_count_alias = ret_name + self._page_count_method = "count_as" + return self + + def group_by_id(self): + self.query.group_by("id") + return self + + def group_by_id_as(self, ret_name: str): + self.query.group_by("id") + return self + def group_by_name(self): + self.query.group_by("name") + return self + + def group_by_name_as(self, ret_name: str): + self.query.group_by("name") + return self + def group_by_version(self): + self.query.group_by("version") + return self + + def group_by_version_as(self, ret_name: str): + self.query.group_by("version") + return self + def select_supplier_list(self): + from requests.supplier_request import SupplierRequest + return self.select_supplier_list_with(SupplierRequest()) + + def select_supplier_list_with(self, child_request): + self.query.relation_query("supplier_list", child_request.query, + QueryOperation("relation-select", "select_supplier_list_with", relation="supplier_list")) + return self + def have_suppliers(self): + from requests.supplier_request import SupplierRequest + return self.with_supplier_list_matching(SupplierRequest()) + + def have_no_suppliers(self): + from requests.supplier_request import SupplierRequest + return self.without_supplier_list_matching(SupplierRequest()) + + def with_supplier_list_matching(self, child_request): + child_request.query.projection = ["warehouse"] + self.query.and_filter(in_subquery(column("id"), "Supplier", child_request.query)) + return self + + def without_supplier_list_matching(self, child_request): + child_request.query.projection = ["warehouse"] + self.query.and_filter(not_in_subquery(column("id"), "Supplier", child_request.query)) + return self + def count_suppliers(self): + return self.count_suppliers_as("count_suppliers") + + def count_suppliers_as(self, alias: str): + from requests.supplier_request import SupplierRequest + self.count_suppliers_with(alias, SupplierRequest()) + self.query.relation_aggregates[-1].operation = QueryOperation( + "relation-count", "count_suppliers_as", alias, "supplier_list") + return self + + def count_suppliers_with(self, alias: str, child_request): + query = deepcopy(child_request.query) + query.aggregates = [] + query.count_field("id", alias) + self.query.relation_aggregates.append( + RelationAggregate("supplier_list", alias, query, True, + QueryOperation("relation-count", "count_suppliers_with", alias, "supplier_list")) + ) + return self + + def min_minimum_order_quantity_of_suppliers(self): + from requests.supplier_request import SupplierRequest + return self.min_minimum_order_quantity_of_suppliers_as( + "min_minimum_order_quantity_of_suppliers", SupplierRequest()) + + def min_minimum_order_quantity_of_suppliers_as(self, alias: str, child_request): + query = deepcopy(child_request.query) + query.aggregates = [] + query.min("minimum_order_quantity", alias) + self.query.relation_aggregates.append( + RelationAggregate("supplier_list", alias, query, True, + QueryOperation("aggregate", "min_minimum_order_quantity_of_suppliers_as", alias, "supplier_list")) + ) + return self + def max_minimum_order_quantity_of_suppliers(self): + from requests.supplier_request import SupplierRequest + return self.max_minimum_order_quantity_of_suppliers_as( + "max_minimum_order_quantity_of_suppliers", SupplierRequest()) + + def max_minimum_order_quantity_of_suppliers_as(self, alias: str, child_request): + query = deepcopy(child_request.query) + query.aggregates = [] + query.max("minimum_order_quantity", alias) + self.query.relation_aggregates.append( + RelationAggregate("supplier_list", alias, query, True, + QueryOperation("aggregate", "max_minimum_order_quantity_of_suppliers_as", alias, "supplier_list")) + ) + return self + def sum_minimum_order_quantity_of_suppliers(self): + from requests.supplier_request import SupplierRequest + return self.sum_minimum_order_quantity_of_suppliers_as( + "sum_minimum_order_quantity_of_suppliers", SupplierRequest()) + + def sum_minimum_order_quantity_of_suppliers_as(self, alias: str, child_request): + query = deepcopy(child_request.query) + query.aggregates = [] + query.sum("minimum_order_quantity", alias) + self.query.relation_aggregates.append( + RelationAggregate("supplier_list", alias, query, True, + QueryOperation("aggregate", "sum_minimum_order_quantity_of_suppliers_as", alias, "supplier_list")) + ) + return self + def avg_minimum_order_quantity_of_suppliers(self): + from requests.supplier_request import SupplierRequest + return self.avg_minimum_order_quantity_of_suppliers_as( + "avg_minimum_order_quantity_of_suppliers", SupplierRequest()) + + def avg_minimum_order_quantity_of_suppliers_as(self, alias: str, child_request): + query = deepcopy(child_request.query) + query.aggregates = [] + query.avg("minimum_order_quantity", alias) + self.query.relation_aggregates.append( + RelationAggregate("supplier_list", alias, query, True, + QueryOperation("aggregate", "avg_minimum_order_quantity_of_suppliers_as", alias, "supplier_list")) + ) + return self + def standardDeviation_minimum_order_quantity_of_suppliers(self): + from requests.supplier_request import SupplierRequest + return self.standardDeviation_minimum_order_quantity_of_suppliers_as( + "standardDeviation_minimum_order_quantity_of_suppliers", SupplierRequest()) + + def standardDeviation_minimum_order_quantity_of_suppliers_as(self, alias: str, child_request): + query = deepcopy(child_request.query) + query.aggregates = [] + query.standardDeviation("minimum_order_quantity", alias) + self.query.relation_aggregates.append( + RelationAggregate("supplier_list", alias, query, True, + QueryOperation("aggregate", "standardDeviation_minimum_order_quantity_of_suppliers_as", alias, "supplier_list")) + ) + return self + def squareRootOfPopulationStandardDeviation_minimum_order_quantity_of_suppliers(self): + from requests.supplier_request import SupplierRequest + return self.squareRootOfPopulationStandardDeviation_minimum_order_quantity_of_suppliers_as( + "squareRootOfPopulationStandardDeviation_minimum_order_quantity_of_suppliers", SupplierRequest()) + + def squareRootOfPopulationStandardDeviation_minimum_order_quantity_of_suppliers_as(self, alias: str, child_request): + query = deepcopy(child_request.query) + query.aggregates = [] + query.squareRootOfPopulationStandardDeviation("minimum_order_quantity", alias) + self.query.relation_aggregates.append( + RelationAggregate("supplier_list", alias, query, True, + QueryOperation("aggregate", "squareRootOfPopulationStandardDeviation_minimum_order_quantity_of_suppliers_as", alias, "supplier_list")) + ) + return self + def sampleVariance_minimum_order_quantity_of_suppliers(self): + from requests.supplier_request import SupplierRequest + return self.sampleVariance_minimum_order_quantity_of_suppliers_as( + "sampleVariance_minimum_order_quantity_of_suppliers", SupplierRequest()) + + def sampleVariance_minimum_order_quantity_of_suppliers_as(self, alias: str, child_request): + query = deepcopy(child_request.query) + query.aggregates = [] + query.sampleVariance("minimum_order_quantity", alias) + self.query.relation_aggregates.append( + RelationAggregate("supplier_list", alias, query, True, + QueryOperation("aggregate", "sampleVariance_minimum_order_quantity_of_suppliers_as", alias, "supplier_list")) + ) + return self + def samplePopulationVariance_minimum_order_quantity_of_suppliers(self): + from requests.supplier_request import SupplierRequest + return self.samplePopulationVariance_minimum_order_quantity_of_suppliers_as( + "samplePopulationVariance_minimum_order_quantity_of_suppliers", SupplierRequest()) + + def samplePopulationVariance_minimum_order_quantity_of_suppliers_as(self, alias: str, child_request): + query = deepcopy(child_request.query) + query.aggregates = [] + query.samplePopulationVariance("minimum_order_quantity", alias) + self.query.relation_aggregates.append( + RelationAggregate("supplier_list", alias, query, True, + QueryOperation("aggregate", "samplePopulationVariance_minimum_order_quantity_of_suppliers_as", alias, "supplier_list")) + ) + return self + +class ExecutableWarehouseRequest: + def __init__(self, request): + self._request = request + + def comment(self, c: str): + self._request.comment(c) + return self + + def new_entity(self, context) -> Warehouse: + request = self._request + QueryIntent(request._comment, request._purpose) + entity = context.initialize_entity("Warehouse", Warehouse()) + if not isinstance(entity, Warehouse): + raise TypeError("entity initializer returned an incompatible Warehouse") + return entity + + async def execute_for_result(self, context): + self = self._request + req = QueryRequest(self.query, _comment=self._comment, _purpose=self._purpose) + req = context.prepare_query_request(req) + service = context.require_resource("dataService") + return await service.query(context, req) + + async def execute_for_rows(self, context): + return (await self.execute_for_result(context)).rows + + async def execute_for_list(self, context) -> SmartList[Warehouse]: + from teaql.runtime.query_list import execute_typed_list + request = self._request + QueryIntent(request._comment, request._purpose) + query = deepcopy(request.query) + authorized = context.prepare_query(query) + root = QueryRequest(authorized, _comment=request._comment, _purpose=request._purpose) + operation = (QueryOperation("named-count", request._page_count_method or "count", + request._page_count_alias if request._page_count_method == "count_as" else None) + if request._page_count_alias is not None else None) + return await execute_typed_list(context, root, + lambda row: Warehouse(_entity_root=EntityRoot(), **row), + count_operation=operation, count_alias=request._page_count_alias) + + async def execute_for_one(self, context): + request = deepcopy(self._request) + request.limit(1) + entities = await ExecutableWarehouseRequest(request).execute_for_list(context) + return entities[0] if entities else None + + def execute_for_stream(self, context, chunk_size: int = 1000): + """Yield entity chunks lazily from the provider cursor.""" + request = deepcopy(self._request) + QueryIntent(request._comment, request._purpose) + service = context.require_resource("dataService") + if not hasattr(service, "query_stream"): + raise RuntimeError("dataService does not implement query_stream") + root = QueryRequest(context.prepare_query(request.query), _comment=request._comment, _purpose=request._purpose) + if root.query.aggregates or root.query.group_by_items or root.query.object_group_bys: + raise ValueError("Entity streams require entity rows; use a record or aggregation query") + from teaql.runtime.query_stream import execute_typed_stream + return execute_typed_stream(context, root, + lambda row: Warehouse(_entity_root=EntityRoot(), **row), chunk_size) diff --git a/examples/supplier-onboarding-i18n/python-lib-core/runtime_module.py b/examples/supplier-onboarding-i18n/python-lib-core/runtime_module.py new file mode 100644 index 00000000..a1865ac1 --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/runtime_module.py @@ -0,0 +1,127 @@ +import asyncio +from datetime import datetime, timezone +from teaql.runtime import CheckResult, ContextFix, ContextEntityRef, JsonFieldNamingProfile, ObjectLocation, RuntimeModule, create_wire_entity_metadata +from teaql.runtime import CheckerPresentationModel +from teaql.core.meta import EntityDescriptor, PropertyDescriptor, RelationDescriptor +from teaql.core.value import DataType +from Q import Q +from teaql.core.value import Value +try: + from teaql.core.graph import GraphNode +except ImportError: + class GraphNode: + def __init__(self, entity): + self.entity, self.fields = entity, {} + def set(self, field, value): + self.fields[field] = value + return self +from models.warehouse import Warehouse +from models.supplier import Supplier + +def _teaql_is_null(value): + return value.is_null() if hasattr(value, "is_null") else value is None + +def _teaql_raw(value): + return value.val if hasattr(value, "val") else value + +def _teaql_entity_id(value): + value = _teaql_raw(value) + if hasattr(value, "id"): + return value.id + if isinstance(value, dict): + return value.get("id") + return value + +class _WarehouseChecker: + def check_and_fix(self, context, record, location, results): + operation = context.get_resource("fix_operation") + if (operation == "insert" and "name" not in record) or ("name" in record and _teaql_is_null(record["name"])): + results.append(CheckResult("required", ObjectLocation().property("name"))) + if "name" in record and _teaql_raw(record["name"]) is not None and len(_teaql_raw(record["name"])) > 100: + results.append(CheckResult("max_length", ObjectLocation().property("name"), _teaql_raw(record["name"]), 100)) + + + +class _SupplierChecker: + def check_and_fix(self, context, record, location, results): + operation = context.get_resource("fix_operation") + if (operation == "insert" and "warehouse" not in record) or ("warehouse" in record and _teaql_is_null(record["warehouse"])): + results.append(CheckResult("required", ObjectLocation().property("warehouse"))) + + if (operation == "insert" and "name" not in record) or ("name" in record and _teaql_is_null(record["name"])): + results.append(CheckResult("required", ObjectLocation().property("name"))) + if "name" in record and _teaql_raw(record["name"]) is not None and not len(_teaql_raw(record["name"])) >= 1: + results.append(CheckResult("min_length", ObjectLocation().property("name"), _teaql_raw(record["name"]), 1)) + if "name" in record and _teaql_raw(record["name"]) is not None and len(_teaql_raw(record["name"])) > 80: + results.append(CheckResult("max_length", ObjectLocation().property("name"), _teaql_raw(record["name"]), 80)) + + if (operation == "insert" and "minimum_order_quantity" not in record) or ("minimum_order_quantity" in record and _teaql_is_null(record["minimum_order_quantity"])): + results.append(CheckResult("required", ObjectLocation().property("minimum_order_quantity"))) + if "minimum_order_quantity" in record and _teaql_raw(record["minimum_order_quantity"]) is not None and not _teaql_raw(record["minimum_order_quantity"]) >= 10: + results.append(CheckResult("min", ObjectLocation().property("minimum_order_quantity"), _teaql_raw(record["minimum_order_quantity"]), 10)) + if "minimum_order_quantity" in record and _teaql_raw(record["minimum_order_quantity"]) is not None and _teaql_raw(record["minimum_order_quantity"]) > 10000: + results.append(CheckResult("max", ObjectLocation().property("minimum_order_quantity"), _teaql_raw(record["minimum_order_quantity"]), 10000)) + + + +_Warehouse_DESCRIPTOR = (EntityDescriptor("Warehouse") + .audit_mask_fields([]) + .table_name("warehouse_data").property(PropertyDescriptor("id", DataType.I64).column_name("id").log_policy("plain").is_id().required()).property(PropertyDescriptor("name", DataType.Text).column_name("name").log_policy("plain").required()).property(PropertyDescriptor("version", DataType.I64).column_name("version").log_policy("plain").is_version().required()).relation(RelationDescriptor("supplier_list", "Supplier").local("id").foreign("warehouse").many()) +) + +_Supplier_DESCRIPTOR = (EntityDescriptor("Supplier") + .audit_mask_fields([]) + .table_name("supplier_data").property(PropertyDescriptor("id", DataType.I64).column_name("id").log_policy("plain").is_id().required()).property(PropertyDescriptor("warehouse", DataType.I64).column_name("warehouse").log_policy("plain").required()).property(PropertyDescriptor("name", DataType.Text).column_name("name").log_policy("plain").required()).property(PropertyDescriptor("minimum_order_quantity", DataType.I64).column_name("minimum_order_quantity").log_policy("plain").integer32().required()).property(PropertyDescriptor("version", DataType.I64).column_name("version").log_policy("plain").is_version().required()).relation(RelationDescriptor("warehouse", "Warehouse").local("warehouse").foreign("id")) +) + +async def _ensure_generated_bootstrap_once(context): + previous_actor = context.user_identifier() if hasattr(context, 'user_identifier') else None + previous_category = context.get_resource('bootstrapCategory') + if hasattr(context, 'set_user_identifier'): + context.set_user_identifier('teaql-generated-bootstrap') + context.insert_resource('bootstrapCategory', 'runtime-bootstrap') + try: + warehouse_1 = await (Q.warehouses().with_id_is(1).comment('what: locate generated bootstrap entity').purpose('why: idempotent runtime bootstrap').execute_for_one(context)) + if warehouse_1 is None: + warehouse_1 = Warehouse._teaql_new_with_fixed_id(1) + warehouse_1.update_name("Central Warehouse") + try: + await warehouse_1.audit_as('create model root Warehouse(1)').save(context) + except Exception as _teaql_create_error: + for _teaql_attempt in range(5): + warehouse_1 = await (Q.warehouses().with_id_is(1).comment('what: recover concurrent bootstrap').purpose('why: make generated bootstrap idempotent').execute_for_one(context)) + if warehouse_1 is not None: + break + if _teaql_attempt < 4: + await asyncio.sleep((_teaql_attempt + 1) * 0.01) + if warehouse_1 is None: + raise _teaql_create_error + context.with_active_root(ContextEntityRef("Warehouse", 1)) + finally: + if hasattr(context, 'set_user_identifier'): + context.set_user_identifier(previous_actor) + context.insert_resource('bootstrapCategory', previous_category) + +async def _ensure_generated_bootstrap(context): + for _teaql_attempt in range(5): + try: + await _ensure_generated_bootstrap_once(context) + return + except Exception: + if _teaql_attempt == 4: + raise + await asyncio.sleep((_teaql_attempt + 1) * 0.01) + + +# Passive generated manifest. Call ensure_schema() separately and explicitly. +_CHECKER_PRESENTATION = CheckerPresentationModel.from_json("{\"schema\":\"teaql.checker-model/v1\",\"revision\":\"sha256:f4b63b86dd7cad758f18ebc623d0a4976afb15dbe9f61002523f909bb75098b0\",\"entities\":{\"Supplier\":{\"labels\":{\"en\":\"Supplier\",\"zh-CN\":\"供应商\"},\"fields\":[{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]},{\"name\":\"minimum_order_quantity\",\"labels\":{\"en\":\"minimum order quantity\"},\"aliases\":[\"MinimumOrderQuantity\",\"minimumOrderQuantity\"]},{\"name\":\"name\",\"labels\":{\"en\":\"name\"},\"aliases\":[\"Name\"]},{\"name\":\"version\",\"labels\":{\"en\":\"version\"},\"aliases\":[\"Version\"]},{\"name\":\"warehouse\",\"targetType\":\"Warehouse\",\"labels\":{\"en\":\"Warehouse\",\"zh-CN\":\"仓库\"},\"aliases\":[\"Warehouse\"]}]},\"Warehouse\":{\"labels\":{\"en\":\"Warehouse\",\"zh-CN\":\"仓库\"},\"fields\":[{\"name\":\"id\",\"labels\":{\"en\":\"id\"},\"aliases\":[\"Id\"]},{\"name\":\"name\",\"labels\":{\"en\":\"name\"},\"aliases\":[\"Name\"]},{\"name\":\"supplier_list\",\"targetType\":\"Supplier\",\"labels\":{\"en\":\"Supplier\",\"zh-CN\":\"供应商\"},\"aliases\":[\"SupplierList\",\"supplierList\"]},{\"name\":\"version\",\"labels\":{\"en\":\"version\"},\"aliases\":[\"Version\"]}]}}}") +GENERATED_RUNTIME_MODULE = (RuntimeModule().entity(Warehouse) + .schema_entity(_Warehouse_DESCRIPTOR) + .checker("Warehouse", _WarehouseChecker()) + .wire_metadata("Warehouse", create_wire_entity_metadata("Warehouse", ["id", "name", "version"], JsonFieldNamingProfile.parse("camelCase"), {"id": ["id"], "name": ["name"], "version": ["version"]})).entity(Supplier) + .schema_entity(_Supplier_DESCRIPTOR) + .checker("Supplier", _SupplierChecker()) + .wire_metadata("Supplier", create_wire_entity_metadata("Supplier", ["id", "warehouse", "name", "minimum_order_quantity", "version"], JsonFieldNamingProfile.parse("camelCase"), {"id": ["id"], "warehouse": ["warehouse"], "name": ["name"], "minimum_order_quantity": ["minimum_order_quantity"], "version": ["version"]})) + .checker_presentation(_CHECKER_PRESENTATION) + .generated_bootstrap(_ensure_generated_bootstrap) +) \ No newline at end of file diff --git a/examples/supplier-onboarding-i18n/python-lib-core/teaql-i18n.json b/examples/supplier-onboarding-i18n/python-lib-core/teaql-i18n.json new file mode 100644 index 00000000..441a4013 --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/teaql-i18n.json @@ -0,0 +1,109 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "property.warehouse.id": "Id", + "property.warehouse.name": "Name", + "property.supplier.id": "Id", + "entity.supplier": "Supplier", + "entity.warehouse": "Warehouse", + "property.supplier.minimumOrderQuantity": "Minimum Order Quantity", + "property.supplier.name": "Name", + "property.supplier.warehouse": "Warehouse", + "property.supplier.version": "Version", + "property.warehouse.version": "Version" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + "entity.supplier": "供应商", + "entity.warehouse": "仓库", + "property.supplier.warehouse": "仓库" + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/examples/supplier-onboarding-i18n/python-lib-core/teaql/checker-model.json b/examples/supplier-onboarding-i18n/python-lib-core/teaql/checker-model.json new file mode 100644 index 00000000..1eec5fc8 --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/teaql/checker-model.json @@ -0,0 +1 @@ +{"schema":"teaql.checker-model/v1","revision":"sha256:f4b63b86dd7cad758f18ebc623d0a4976afb15dbe9f61002523f909bb75098b0","entities":{"Supplier":{"labels":{"en":"Supplier","zh-CN":"供应商"},"fields":[{"name":"id","labels":{"en":"id"},"aliases":["Id"]},{"name":"minimum_order_quantity","labels":{"en":"minimum order quantity"},"aliases":["MinimumOrderQuantity","minimumOrderQuantity"]},{"name":"name","labels":{"en":"name"},"aliases":["Name"]},{"name":"version","labels":{"en":"version"},"aliases":["Version"]},{"name":"warehouse","targetType":"Warehouse","labels":{"en":"Warehouse","zh-CN":"仓库"},"aliases":["Warehouse"]}]},"Warehouse":{"labels":{"en":"Warehouse","zh-CN":"仓库"},"fields":[{"name":"id","labels":{"en":"id"},"aliases":["Id"]},{"name":"name","labels":{"en":"name"},"aliases":["Name"]},{"name":"supplier_list","targetType":"Supplier","labels":{"en":"Supplier","zh-CN":"供应商"},"aliases":["SupplierList","supplierList"]},{"name":"version","labels":{"en":"version"},"aliases":["Version"]}]}}} \ No newline at end of file diff --git a/examples/supplier-onboarding-i18n/python-lib-core/teaql/model-provenance.json b/examples/supplier-onboarding-i18n/python-lib-core/teaql/model-provenance.json new file mode 100644 index 00000000..05f3b87b --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/teaql/model-provenance.json @@ -0,0 +1 @@ +{"schemaVersion":1,"modelUuid":null,"revisionHash":"sha256:66bd8079ce8129c77f2ed1769a9d518a285fa8abd19823e9941351de6e826436","generatorVersion":"Git"} \ No newline at end of file diff --git a/examples/supplier-onboarding-i18n/run-example.py b/examples/supplier-onboarding-i18n/run-example.py new file mode 100644 index 00000000..361e6b79 --- /dev/null +++ b/examples/supplier-onboarding-i18n/run-example.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Run a native generated-workspace adapter against the shared i18n scenarios.""" + +import argparse +import json +from pathlib import Path +import subprocess +import sys +from tempfile import TemporaryDirectory + + +PREFIX = "TEAQL_I18N_SHOWCASE " +HERE = Path(__file__).resolve().parent + + +def read_json(path): + return json.loads(Path(path).read_text(encoding="utf-8")) + + +class Scenario: + def __init__(self, model): + self.model = model + self.steps = [] + + def select(self, code, effective, *, context="main", accepted=True): + self.steps.append(( + {"operation": "select", "context": context, "locale": code}, + {"type": "locale", "context": context, "requestedLocale": code, + "effectiveLocale": effective, "accepted": accepted}, + )) + + def validate(self, effective, *, context="main", phase="ordinary"): + for case in self.model["cases"]: + expected = {"type": "validation", "context": context, "case": case["id"], + **case["error"], "phase": phase} + if effective is not None: + expected["effectiveLocale"] = effective + self.steps.append(( + {"operation": "validate", "context": context, "case": case["id"], + "input": case["input"]}, + expected, + )) + + def edges(self, catalog_file): + config = self.model["localeCases"] + self.validate(self.model["defaultLocale"], phase="default") + alias = config["alias"] + self.select(alias["input"], alias["effectiveLocale"]) + self.validate(alias["effectiveLocale"], phase="alias") + for invalid in config["unsupported"]: + self.select(invalid, alias["effectiveLocale"], accepted=False) + other = config["independentContextLocale"] + self.select(other, other, context="independent") + for index, locale in enumerate(config["switchSequence"]): + self.select(locale, locale) + self.validate(locale, phase=f"switch-{index + 1}") + self.validate(other, context="independent", phase=f"isolation-{index + 1}") + missing = config["missingTranslationLocale"] + catalog = read_json(catalog_file) + keys = [case["error"]["messageKey"] for case in self.model["cases"]] + if any(key in catalog["locales"][missing]["messages"] for key in keys): + raise ValueError(f"The application catalog must omit the example messages in {missing}") + self.select(missing, missing) + self.validate(missing, phase="builtin-before-install") + self.steps.append(( + {"operation": "install-catalog", "context": "main", "path": str(catalog_file)}, + {"type": "catalog-installed", "context": "main", "effectiveLocale": missing}, + )) + self.validate(missing, phase="missing-application-translation") + + +def compare(expected, observed): + phase = expected.get("phase") + if phase: + observed["phase"] = phase + for key, value in expected.items(): + if observed.get(key) != value: + raise ValueError(f"Unexpected {key}: expected {expected}, received {observed}") + if expected["type"] == "locale": + if type(observed.get("accepted")) is not bool or not observed.get("effectiveLocale"): + raise ValueError(f"Missing native locale selection outcome: {observed}") + if not observed["accepted"] and not observed.get("nativeError"): + raise ValueError(f"Missing native locale rejection: {observed}") + if expected["type"] == "validation": + if not observed.get("nativeRule") or not observed.get("message", "").strip(): + raise ValueError(f"Missing native rule or localized text: {observed}") + + +def execute(command, scenario, database, run_number): + payload = { + "database": str(database), "warehouse": scenario.model["warehouse"], + "steps": [request for request, _ in scenario.steps], + } + result = subprocess.run(command, input=json.dumps(payload, ensure_ascii=False), encoding="utf-8", + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=90) + if result.returncode: + print(result.stderr, file=sys.stderr, end="") + print(result.stdout, file=sys.stderr, end="") + return result.returncode + observations = [json.loads(line[len(PREFIX):]) for line in result.stdout.splitlines() + if line.startswith(PREFIX)] + if len(observations) != len(scenario.steps): + raise ValueError(f"Expected {len(scenario.steps)} native events, received {len(observations)}") + current_locale = {} + rejected_single_selection = False + for (_, expected), observed in zip(scenario.steps, observations): + if expected["type"] == "validation" and "effectiveLocale" not in expected: + expected = {**expected, "effectiveLocale": current_locale[expected["context"]]} + compare(expected, observed) + if expected["type"] == "locale": + current_locale[observed["context"]] = observed["effectiveLocale"] + rejected_single_selection |= not observed["accepted"] and "accepted" not in expected + observed["round"] = run_number + print(json.dumps(observed, ensure_ascii=False, sort_keys=True)) + by_phase = {(row.get("phase"), row.get("case")): row for row in observations} + for case in scenario.model["cases"]: + before = by_phase.get(("builtin-before-install", case["id"])) + after = by_phase.get(("missing-application-translation", case["id"])) + if before and after and before["message"] != after["message"]: + raise ValueError(f"Missing application translation changed the built-in result: {after}") + for phases in (("switch-1", "switch-3"), ("isolation-1", "isolation-2", "isolation-3")): + messages = {by_phase[phase, case["id"]]["message"] for phase in phases + if (phase, case["id"]) in by_phase} + if len(messages) > 1: + raise ValueError(f"Locale state leaked across {phases} for {case['id']}") + return 2 if rejected_single_selection else 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--locale", help="set the locale through the native UserContext") + mode.add_argument("--all", action="store_true", help="exercise all 15 locales in one native process") + mode.add_argument("--edge-cases", action="store_true", help="verify default, rejection, isolation and fallback") + parser.add_argument("--catalog", type=Path, help="generated teaql-i18n.json for --edge-cases") + parser.add_argument("--repeat", type=int, choices=(1, 2), default=1, + help="run twice against the same SQLite file") + parser.add_argument("command", nargs=argparse.REMAINDER, help="native command after --") + args = parser.parse_args() + command = args.command[1:] if args.command[:1] == ["--"] else args.command + if not command: + parser.error("a native workspace command is required after --") + model = read_json(HERE / "semantics.json") + scenario = Scenario(model) + if args.edge_cases: + if not args.catalog: + parser.error("--edge-cases requires --catalog") + scenario.edges(args.catalog.resolve(strict=True)) + elif args.all: + for definition in model["locales"]: + code = definition["code"] + scenario.select(code, code) + scenario.validate(code) + elif args.locale is not None: + # Single-language mode accepts aliases and reports the actual normalized locale. + scenario.steps.append(( + {"operation": "select", "context": "main", "locale": args.locale}, + {"type": "locale", "context": "main", "requestedLocale": args.locale}, + )) + scenario.validate(None) + else: + scenario.validate(model["defaultLocale"]) + scenario.steps.append(( + {"operation": "verify-unchanged", "context": "main"}, + {"type": "storage", "context": "main", "supplierCount": 0}, + )) + with TemporaryDirectory(prefix="teaql-i18n-supplier-") as directory: + database = Path(directory) / "registration.sqlite" + for run_number in range(1, args.repeat + 1): + status = execute(command, scenario, database, run_number) + if status: + return status + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/supplier-onboarding-i18n/run.sh b/examples/supplier-onboarding-i18n/run.sh new file mode 100644 index 00000000..f3823a28 --- /dev/null +++ b/examples/supplier-onboarding-i18n/run.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -euo pipefail + +example="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +repo="$(cd "$example/../.." && pwd)" +python="${PYTHON:-python3}" +export PYTHONDONTWRITEBYTECODE=1 +export PYTHONPATH="$example/python-lib-core:$repo/src" +exec "$python" "$example/run-example.py" --catalog "$example/python-lib-core/teaql-i18n.json" "$@" -- \ + "$python" "$example/python-app-console/app/main.py" diff --git a/examples/supplier-onboarding-i18n/semantics.json b/examples/supplier-onboarding-i18n/semantics.json new file mode 100644 index 00000000..04839b73 --- /dev/null +++ b/examples/supplier-onboarding-i18n/semantics.json @@ -0,0 +1,48 @@ +{ + "schema": "teaql.i18n-showcase/v1", + "scene": "supplier-onboarding", + "entity": "supplier", + "operation": "register a supplier for warehouse purchasing", + "warehouse": {"id": 1, "name": "Central Warehouse"}, + "defaultLocale": "en", + "locales": [ + {"code": "en", "chinese": "英语", "native": "English"}, + {"code": "zh-CN", "chinese": "简体中文", "native": "简体中文"}, + {"code": "zh-TW", "chinese": "繁体中文", "native": "繁體中文"}, + {"code": "ja", "chinese": "日语", "native": "日本語"}, + {"code": "ko", "chinese": "韩语", "native": "한국어"}, + {"code": "de", "chinese": "德语", "native": "Deutsch"}, + {"code": "fr", "chinese": "法语", "native": "français"}, + {"code": "es", "chinese": "西班牙语", "native": "español"}, + {"code": "pt", "chinese": "葡萄牙语", "native": "português"}, + {"code": "ar", "chinese": "阿拉伯语", "native": "العربية"}, + {"code": "th", "chinese": "泰语", "native": "ไทย"}, + {"code": "id", "chinese": "印度尼西亚语", "native": "Bahasa Indonesia"}, + {"code": "fil", "chinese": "菲律宾语", "native": "Filipino"}, + {"code": "uk", "chinese": "乌克兰语", "native": "Українська"}, + {"code": "vi", "chinese": "越南语", "native": "Tiếng Việt"} + ], + "cases": [ + { + "id": "missing-supplier-name", + "input": {"name": null, "minimum_order_quantity": 10}, + "error": {"messageKey": "checker.required", "location": "name"} + }, + { + "id": "order-quantity-below-minimum", + "input": {"name": "Orchid Paper", "minimum_order_quantity": 3}, + "error": { + "messageKey": "checker.min", + "location": "minimum_order_quantity", + "arguments": {"minimum": 10} + } + } + ], + "localeCases": { + "alias": {"input": "ZH_hant", "effectiveLocale": "zh-TW"}, + "unsupported": ["", "xx-XX"], + "missingTranslationLocale": "vi", + "switchSequence": ["ja", "ar", "ja"], + "independentContextLocale": "fr" + } +} diff --git a/examples/supplier-onboarding-i18n/showcase.json b/examples/supplier-onboarding-i18n/showcase.json new file mode 100644 index 00000000..661cbac0 --- /dev/null +++ b/examples/supplier-onboarding-i18n/showcase.json @@ -0,0 +1,77 @@ +{ + "generatedDomainLibraryHandEdited": false, + "goalId": "python:examples/supplier-onboarding-i18n", + "library": { + "generatedFilesManifestSHA256": "73553d4434d859fa233c501b0f714768c9273191a1cc133506923dafe161f85a", + "root": "python-lib-core", + "scope": "python-lib-core" + }, + "model": { + "path": "model.xml", + "sha256": "961f3048ca9c8e9120d81fc0ce9a3ea35629c8d9607aab80319156c21391e2c5" + }, + "producer": { + "assistSHA256": { + "python-assist-create-supplier.md": "c0f4a1ce977d7fa3d4a5fce8a409bef958de0d93288dc458a007631b0529343c", + "python-assist-i18n.md": "e248f5bc9afe4957a309ee305b94c24250be95f7729a9a5c3bcbeb1a104ccbbb", + "python-assist-query-supplier.md": "b73b5c82a0f4820187625a41c297120e8d348635804e3c4994518bbb4770cac8" + }, + "evaluationSHA256": "c7a0b3fe8953aec1f5c4a1ebc0ce02f6f17a11bd0db1fceddd395d7848dc985c", + "generatorBaseCommit": "92d612e95cde33c323a1b026b5c567f8c8fa4562", + "scopes": [ + "python-app-console", + "python-lib-core" + ] + }, + "qualification": { + "baseCommit": "615b6c18ea377d05cef3d8a823c072e2f7794548", + "evidence": "teaql-conformance/evidence/2026-11-21-i18n-standard-examples/python.jsonl", + "stdoutSHA256": "87f2352e94b5b942c769bf0f88ae0038ae0d0476e5a3d01289fd8b56af061d8e" + }, + "scene": "Warehouse supplier onboarding with two real checker rejections and locale isolation", + "schema": "teaql.model-workspace-showcase/v1", + "semanticModel": { + "path": "semantics.json", + "sha256": "5ac183bbe622b4bf7bfc157d367714d36a88722c03d64fc1ba68d8ef01faaf18" + }, + "status": "focused-verified", + "verification": [ + [ + "bash", + "run.sh", + "--all", + "--repeat", + "2" + ], + [ + "bash", + "run.sh", + "--edge-cases" + ] + ], + "workspace": { + "applicationEntry": "app/main.py", + "applicationOwnedFiles": [ + "python-app-console/app/main.py" + ], + "domainSourcesFromLibrary": [ + "E.py", + "Q.py", + "generated_search_models.py", + "models/__init__.py", + "models/supplier.py", + "models/warehouse.py", + "pyproject.toml", + "requests/__init__.py", + "requests/supplier_request.py", + "requests/warehouse_request.py", + "runtime_module.py", + "teaql-i18n.json", + "teaql/checker-model.json", + "teaql/model-provenance.json" + ], + "generatedFilesManifestSHA256": "73553d4434d859fa233c501b0f714768c9273191a1cc133506923dafe161f85a", + "root": "python-app-console", + "scope": "python-app-console" + } +} diff --git a/scripts/verify-examples.sh b/scripts/verify-examples.sh index 6b5419dc..dd69a25f 100755 --- a/scripts/verify-examples.sh +++ b/scripts/verify-examples.sh @@ -2,7 +2,7 @@ set -euo pipefail repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -expected=(business-clock business-id conformance context-derived expression-profiles facet-trace fix-e-alignment internal-id mutation-policy natural-messages object-storage opaque-entity-reference order-management query-policy scalar-type-probe school-management task_board trace-chain typed-extension-spi) +expected=(business-clock business-id conformance context-derived expression-profiles facet-trace fix-e-alignment internal-id mutation-policy natural-messages object-storage opaque-entity-reference order-management query-policy scalar-type-probe school-management supplier-onboarding-i18n task_board trace-chain typed-extension-spi) 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 @@ -40,6 +40,8 @@ bash "$repo/examples/scalar-type-probe/verify-empty.sh" "$evidence_directory/emp python "$repo/examples/fix-e-alignment/verify-local.py" TEAQL_CONTEXT_FIX_EVIDENCE_DIR="$evidence_directory/context-derived" python "$repo/examples/context-derived/verify-local.py" TEAQL_NATURAL_MESSAGES_EVIDENCE_DIR="$evidence_directory/natural-messages" python "$repo/examples/natural-messages/verify-local.py" +PYTHON=python bash "$repo/examples/supplier-onboarding-i18n/run.sh" --all --repeat 2 > "$evidence_directory/supplier-i18n-all.jsonl" +PYTHON=python bash "$repo/examples/supplier-onboarding-i18n/run.sh" --edge-cases > "$evidence_directory/supplier-i18n-edges.jsonl" TEAQL_GENERATED_E_PROFILE_EVIDENCE_DIR="$evidence_directory/expression-profiles" \ python "$repo/examples/expression-profiles/verify-local.py" PYTHONPATH="$repo/examples/conformance:$repo/src" python -m app.main From 2540ff939ec20e95953ff257c04b91ec800adf77 Mon Sep 17 00:00:00 2001 From: Philip Z Date: Tue, 24 Nov 2026 18:43:11 +0800 Subject: [PATCH 2/2] Bind supplier onboarding Python metadata to its library scope --- .../python-lib-core/generated-files.json | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 examples/supplier-onboarding-i18n/python-lib-core/generated-files.json diff --git a/examples/supplier-onboarding-i18n/python-lib-core/generated-files.json b/examples/supplier-onboarding-i18n/python-lib-core/generated-files.json new file mode 100644 index 00000000..bc927f30 --- /dev/null +++ b/examples/supplier-onboarding-i18n/python-lib-core/generated-files.json @@ -0,0 +1,16 @@ +{ + "E.py": "4feb2016d23c5f664122f11921814bb52645cfa51b2eb201204f9ea6231d6b75", + "Q.py": "a962f69c512c902e901b903b14c1dffaa92755e7443b6877cb122a5289b0c51e", + "generated_search_models.py": "bb6b6aaeabbc8bda3c42ba1445212f00ef1f9a9c952c6892c31783b00c477594", + "models/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "models/supplier.py": "03cb7101f03365edd970f2758ebc6ea58b1d693b8cd2d49bc8132f79c4c3fc7c", + "models/warehouse.py": "1f11e4254cc939a68c49758cbc8f4fc789484ca38807f52c292594ae7247d8df", + "pyproject.toml": "16eb65d80bf164747491ae65289e5b4511c40a600d81b7bc5569fc1f161657b5", + "requests/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "requests/supplier_request.py": "0ab10d5469ab426546f82f07803fc7af145fd281dd14ce57db6b304b7d8c9508", + "requests/warehouse_request.py": "c9062219b6972e79e93d974a96a56fdefc74001b1b302e51b8babb4c28f99009", + "runtime_module.py": "7db3980bc0ef3ef0120a4003ee3d84bd6b3d7c0bb7676fa7867850267b20f2e9", + "teaql-i18n.json": "f848093c0785f2730eaa74f8a9e175e1f90943f056d84666bc964d56668e298c", + "teaql/checker-model.json": "0c70836b868047e6bbf8c5a4b167343ef9425e5c535c59ee388b634a79f2b144", + "teaql/model-provenance.json": "94ae1b99943275455fce8de247c97f10a81cdb09fef91ada0ae924b26e572759" +}