Skip to main content

Order API Usage Across Seven Languages

Use this page to choose an API and interpret its result. Work through the Java, Rust, TypeScript, Python, Go, C# / .NET or Swift tutorial for native code in context.

The authority is the retained application source and its dated execution receipt. These are model-derived API spellings, not instructions to translate arbitrary English method names between languages. For another model, request scoped Assist; keep generated domain-library source unchanged.

Choose a query result​

NeedUseInterpret the result
One Order to editFull scalar Order plus complete bounded item selection; require exactly one match.Typed entities with loaded-state and version information. A minimal projection is insufficient for a full edit.
List screenBounded projection, stable ordering and explicitly selected child preview.Typed SmartList. A one-item preview does not describe the full Order.
Single nullable fieldMinimal Order request with that field explicitly selected.An E expression distinguishes selected value, selected SQL NULL and NotLoaded.
Filtered total countExplicit count on the same filtered request.Total is metadata of the matching set, not the returned page length.
Status/currency totalsProvider aggregate request carrying the same filters.Analytic rows, not hydrated Order entities.
Status buckets with empty categoriesFacets with the explicit include-all/matched-only choice.Facet result carrier separate from the returned Order page.

All executed requests require a non-empty comment and purpose. context supplies the trusted execution environment. The v1.0 examples' buyer predicates do not establish authentication or tenant authorization.

LanguageTyped list terminalSelected Order total expressionItem relation carrier
JavaexecuteForList(context)E.customerOrder(order).getTotalMinor().eval()order.getOrderItemList()
Rustexecute_for_list(context).await?E::customer_order(&order).get_total_minor().eval()Keep let handle = order.order_item_list() alive, then inspect handle.value().
TypeScriptawait request.executeForList(context)E.customerOrder(order).totalMinor().eval()order.orderItemList()
Pythonawait request.execute_for_list(context)E.customer_order(order).total_minor().eval()order.order_item_list()
GoExecuteForList(context) plus returned errorcustomer_order.NewCustomerOrderExpression(order).TotalMinor().Eval()order.OrderItemList().Items()
C# / .NETawait request.ExecuteForListAsync(context)E.CustomerOrder(order).TotalMinor().Eval()order.OrderItemList
Swifttry await request.executeForList(context)try E.customerOrder(order).totalMinor().eval()order.orderItemList

The list is the runtime's typed SmartList, with language-specific iteration and metadata access. Iteration syntax such as .map, .Data or .data does not make it an untyped SQL-row result. The application helpers named required, load, graph, edit, pageRows and report are defined in the examples; they are not extra generated APIs.

Preserve loaded state​

An empty item list means no matching children only when that relation was selected. An omitted relation does not become a loaded empty collection. Use full reloading before an edit and a minimal projection only for a read-only view.

Order note stateevalNull-only fallback
Selected Leave at receptionThat textThat text
Selected SQL NULLNative null/None/nil representationNo note
Selected empty stringEmpty stringEmpty string
Not selectedNative NotLoaded diagnosticThe same missing-field failure
LanguageNull-only operation on the selected note expression
JavagetOrderNote().orIfNull("No note")
Rustget_order_note().or_if_null(Some("No note".to_owned()))
TypeScriptorderNote().orElse("No note")
Pythonorder_note().or_if_null("No note")
GoOrderNote().OrElse(&fallback); ordinary Eval() returns value/presence.
C# / .NETOrderNote().OrIfNull("No note")
Swifttry orderNote().orElse("No note")

These are the exact example-specific accessor names. A NotLoaded error calls for selecting the field; it is not a reason to catch the error and return the null default. The retained note-value, note-null, note-empty and note-not-loaded phases establish all four cases.

Save a complete business edit​

Load one DRAFT Order and every item needed to compute its total. The tutorial supports at most 100 items, so it loads up to 101 and rejects overflow. Validate quantities and money before mutation: the KSML scalar type alone does not enforce integer USD cents, integral quantities, the application bounds or legal state transitions.

An audit reason describes the actual business write. It does not create an application transaction spanning unrelated calls.

LanguageTransaction boundary used by the core draft editImportant ownership rule
JavaAudited Order graph save.Keep the selected changed item in the saved Order graph. Explicit line removal and the separate lifecycle program use native explicit transactions.
RustTyped execute_in_transaction scope with save_audited for Order and item.A detached child clone must be saved explicitly in the same transaction.
TypeScriptAwaited audited Order graph save.Mutate the selected child belonging to that graph; validate safe integer arithmetic.
PythonAwaited audited Order graph save.Reject booleans as quantities; preserve async failures and cancellation.
GoAudited Order graph save with checked returned error.Do not ignore either (value, present) or the mutation error.
C# / .NETAwaited audited Order graph save inside the owned connection scope.Use checked arithmetic and keep the connection alive through completion.
SwiftAwaited audited Order graph save.Mutate the child inside the parent value that will be saved.

Use the persisted typed value returned by save, or reload it explicitly. Catch a version conflict at the business boundary, reload authoritative state and decide whether the request is still appropriate. Busy/locked, timeout, checker rejection and provider failures need their own diagnosis; a blind retry policy can conceal a broken transaction or overwrite the intended decision.

For line deletion, explicitly mark the intended child for deletion and recompute the complete total within one transaction. Omitting a child from a selected preview is not a delete command. For state changes, validate the current/target pair in application code before setting the generated status field; a generated setter is not the transition policy.

Advanced mutation recipes​

Read the operation in your language with its complete example open:

LanguageExplicit deletionAllowed state changesStale-version recovery
JavaRemove a lineApply policyPreserve the winner
RustRemove a lineApply policyPreserve the winner
TypeScriptRemove a lineApply policyPreserve the winner
PythonRemove a lineApply policyPreserve the winner
GoRemove a lineApply policyPreserve the winner
C# / .NETRemove a lineApply policyPreserve the winner
SwiftRemove a lineApply policyPreserve the winner

For explicit deletion, Java and Rust save the recomputed Order and marked child through one explicit transaction, Order first. The other five use one audited save of the complete loaded graph. This differs from Java's core quantity-edit recipe; a graph can schedule deletes first. The recipes explain the exact native boundary instead of assuming identical write scheduling across runtimes.

A status setter is not the state-transition policy. The application allows only DRAFT → CONFIRMED, DRAFT → CANCELLED and CONFIRMED → CANCELLED; repeated states, reversals and unknown targets reject before save. A transition result's observedVersion describes the loaded revision; read committed state again for the new version. Cancelling an Order in this v1.0 example neither deletes its items nor releases inventory.

Keep policy rejection, optimistic-version rejection and provider failure distinct. The controlled stale race retains two version-1 copies, commits B first, and then requires A to fail while every field of B's committed version-2 result stays unchanged. Several test-worker adapters collect broad errors under a report label; that label alone is not a production conflict classifier. Preserve the native error and inspect authoritative state before choosing a new business attempt.

These recipes use a fresh seed per branch. After a successful removal the target Order is total 2500/version 2 with a Pen tombstone at -2. In the stale-removal control the independently committed Pen stays live at version 2 while the attempted Order-total write rolls back to total 3850/version 1. Those are different outcomes; “rollback” does not erase a competing transaction's commit.

Choose a paging strategy​

Reader actionExisting API pathWhat to keep stable
Open a small search pageOffset/limit with stable total/ID order and exact count.Filters, ordering, validated bounds and relation-preview limits.
Export consecutive pagesContinuous-page optimization on an ID-ordered request.Reuse the trusted context and sequence key for the sequence. Inspect the actual cursor/fallback plan.
Jump between distant pagesRetained-ID pagination with explicit TTL and capacity.Matching-set scope, ordering, buyer/tenant isolation, expiry and invalidation.
Calculate totals for a list screenProvider aggregates and Facets with the same filters.Do not sum a truncated page to obtain the total of the complete matching set.
LanguageBounded-page call in the retained exampleExact total carrier
Javaoffset(offset, limit).count()page.getTotalCount()
Rustoffset(offset as u64, limit as u64).count()page.total_count
TypeScriptoffset(offset).limit(limit).count()page.totalCount
Pythonoffset(offset).limit(limit).count()page.total_count
GoOffset(uint64(offset)).Limit(uint64(limit)).Count()page.TotalCount; check the pointer before dereferencing.
C# / .NETOffset(offset).Limit(limit).Count()page.TotalCount
Swiftoffset(offset).limit(limit).count()page.totalCount

Validate signed offset/limit before unsigned casts. In this example the accepted range is offset at least zero and limit 1–3. A selected child limit(1) is a per-parent preview limit; it does not change the exact parent count.

The original fixture teaches the three-order edit. The pagination fixture has nine Orders, eight matching BUYER-EXPORT. The summary/retained-ID fixture has ten Orders and adds currency/status conditions. They share model v1.0 but must use separate databases. Do not expect the three-order edit database to produce the export fixture's counts.

Use the native bounded-page excerpt in your language tutorial. Then read the continuous export, retained-ID and summary explanations with the corresponding full application function open. Java aggregates use aggregation(context).toList(); the other six use the recorded analytic-row terminal (execute_for_rows, executeForRows, ExecuteRecords or ExecuteForRowsAsync). Analytic records have language-specific Value/alias carriers; use the language troubleshooting page before adding casts.

Export, retained-ID and summary recipes​

Choose the walkthrough for your runtime before copying an optimizer call:

LanguageConsecutive exportRandom page jumpsFull-set summaries
JavaExportRetained IDsSummaries
RustExportRetained IDsSummaries
TypeScriptExportRetained IDsSummaries
PythonExportRetained IDsSummaries
GoExportRetained IDsSummaries
C# / .NETExportRetained IDsSummaries
SwiftExportRetained IDsSummaries

Native optimizer spellings​

These are request-builder methods from the retained v1.0 examples. Namespace, TTL and maximum IDs are explicit inputs; 300 seconds and capacity 20 are example values, not universal runtime defaults. Execute the completed bounded request with its comment, purpose and trusted context.

LanguageContinuous-page configurationRetained-ID configuration
JavaoptimizeForContinuousPageFetch(namespace, ttl)optimizePaginationWithIdSet(namespace, ttl, maxIds)
Rustoptimize_for_continuous_page_fetch_with(namespace, ttl)optimize_pagination_with_id_set_config(namespace, ttl, max_ids)
TypeScriptoptimizeForContinuousPageFetchWith(namespace, ttl)optimizePaginationWithIdSetConfig(namespace, ttl, maxIds)
Pythonoptimize_for_continuous_page_fetch_with(namespace, ttl)optimize_pagination_with_id_set_config(namespace, ttl, max_ids)
GoOptimizeForContinuousPageFetchWith(namespace, ttl)OptimizePaginationWithIDSetConfig(namespace, ttl, maxIDs)
C# / .NETOptimizeForContinuousPageFetchWith(namespace, ttl)OptimizePaginationWithIdSet(namespace, ttl, maxIds)
SwiftoptimizeForContinuousPageFetch(namespace: namespace, ttlSeconds: ttl)optimizePaginationWithIdSet(namespace: namespace, ttlSeconds: ttl, maxIds: maxIds)

Keep the context alive through one sequence. Calling the console again creates another process/context; an identical namespace does not restore an in-memory cursor or retained store. The export uses ID ordering and the nine-order fixture. Retained IDs use total/ID ordering and buyer plus USD predicates on the ten-order fixture. Selecting the wrong fixture changes the meaning of the expected count before any optimizer is involved.

Observe the actual plan and count​

LanguageContinuous observationRetained observation
Javacontext.getAttribute(PortableSQLRepository.CONTINUOUS_PAGE_PLAN)Attributes PortableSQLRepository.ID_SET_PLAN and PortableSQLRepository.ID_SET_COUNT.
Rustcontext.continuous_page_plan()context.id_set_plan() and context.id_set_count().
TypeScriptcontext.continuousPagePlancontext.idSetPaginationPlan and context.idSetPaginationCount.
Pythoncontext.continuous_page_plan()context.id_set_plan() and context.id_set_count(); returns (count, accuracy); the report uses index 0.
Gocontext.ContinuousPagePlan()context.IDSetPlan() and context.IDSetCount(); returns (count, accuracy), not a presence flag.
C# / .NETcontext.ContinuousPagePlancontext.IdSetPlan and context.IdSetCount.
Swiftawait context.continuousPageObservation()await context.idSetPaginationObservation() with plan and count.

The Java constant owner is io.teaql.core.sql.portable.PortableSQLRepository. Read observations immediately after their request. Keep the native value when recording the operation; a previous request's observation or a hand-written plan label is not evidence for the current query.

ObservationCorrect meaning in these examples
CURSOR_SEEKThe runtime chose a seek plan; the retained SQL contains an ID boundary.
OFFSET_FALLBACK:FIRST_PAGE / CACHE_MISSExpected first/missing-cursor fallback. The empty export tail still has exact total 8.
Unsupported composite-sort fallbackExpected for total/ID sorting in this continuous ID-seek path; reason names vary by language.
ID_SET_BUILD / ID_SET_HITRetained set construction/reuse, corroborated by actual store events and keys.
ID_SET_FALLBACK_LIMIT_EXCEEDEDNo partial ID set is retained. With capacity 4, observed count 5 is a lower bound; exact total 8 comes from provider COUNT.

For retained IDs, Java/Rust/Python/Go/.NET wrap their native in-memory store for observation. TypeScript's example implements the public store protocol itself. Swift's public protocol exposes obtain, while its application actor adapter implements invalidation by removing the delegate for the observed key. Do not translate those adapters into nonexistent universal context invalidation methods.

Keep analytic carriers and native keys distinct​

LanguageProvider-row terminal / carrierNative status group keyNumeric/null handling in the example
Javaaggregation(context).toList()Explicit alias statusId.Analytic rows are passed into the report; Facets instead use typed status entities plus getDynamicProperty("count").
Rustexecute_for_rows(context).await?, CompactRowExplicit alias statusId.get(key) and try_f64(); preserve optional overall sum.
TypeScriptexecuteForRows(context), analytic rowsorderStatusNormalize key/count in the report, preserve overall totalMinor null.
Pythonexecute_for_rows(context), dictionariesorder_statusConvert known counts and preserve overall sum None.
GoExecuteRecords(context), Value recordsorder_statusTryU64()/TryF64(); nullable conversion for the empty overall sum.
C# / .NETExecuteForRowsAsync(context), .Rows of Value recordsorder_statusTryF64()/TryText() paths; non-null group helper and nullable overall-sum path are separate.
SwiftexecuteForRows(context), TeaQLRecordorderStatus.decimalValue conversion for reporting; optional overall sum maps to JSON null.

The shared JSON field statusId is an application normalization for several languages, not a promise that every unaliased native row contains statusId. Analytic rows are not typed Order entities; E expressions and null-only entity defaults do not replace their native record/value accessors.

Repeat buyer, currency and minimum amount on grouped aggregates, the overall aggregate, parent rows and both Facet variants. With all export-buyer USD orders, three visible rows do not change exact count 8 or sum 35350. With no matching buyer, grouped rows are empty but the overall aggregate is one row with count 0 and sum null. All-status Facets retain zero buckets; matched-only Facets omit them.

The query troubleshooting tables link native recovery guidance. These are fixed-data SQLite recipes: retained membership does not certify a transactionally frozen row snapshot, and query optimization does not implement file serialization, distributed retention or an unlimited-memory export loop.

Buyer/tenant authorization recipes​

Use the v1.1 isolation model and its qualified application, rather than adding a client-supplied tenant field to the v1.0 query recipe. Choose the native walkthrough: Java, Rust, TypeScript, Python, Go, C# / .NET or Swift.

Ownership, context and request responsibilities​

LayerResponsibility in the retained applicationBoundary
Model v1.1Adds commerce_platform.tenant_key; Order → tenant root and item → Order use existing relations.The sample key is not membership or authorization. Fresh bootstrap does not implement a live data migration.
Server session resolverSelects an application-owned actor/tenant/buyer tuple.Fixture keys a–d/readonly are synthetic, not credentials or public impersonation inputs. Real authentication is separate integration work.
Native UserContextHolds generated runtime/provider and retained-store execution state.The facade receives a server-owned context; the examples do not rebind a native tenant/actor for each session. Swift explicitly keeps fixed server values and an identity RequestPolicy.
Application facadeValidates allowed fields, resolves exactly one tenant root, scopes all Order operations by root + buyer and permits only two narrow writes.Enforced through these entry points. Arbitrary raw Q/database access is not automatically protected by this facade or SQL row-level security.
Transport adapterMust parse/limit incoming data, authenticate, map responses and manage request/principal lifetime.Console JSON probes do not certify a complete HTTP/TFP integration or exhaustive hostile-input handling.

The allowed business fields are op, orderId, orderNumber, itemId, limit and patch. Declared identity/policy fields are rejected before the first facade SELECT. Limits default to 2 and require integer 1–2 when supplied. edit-note accepts only orderNote; edit-item accepts only productName. Other patch keys are rejected together, including identity, scope, amount, status and version. Read-only sessions fail a valid write request before provider access. Keep native validation semantics and preserve non-authorization provider exceptions.

Native scope, page and aggregate calls​

Each handler first uses its native withTenantKeyIs/with_tenant_key_is equivalent with bound 2 and requires exactly one root. These are the subsequent Order predicates:

LanguageTenant-root + buyer on the Order requestExact page / analytic result
JavafilterByCommercePlatform(root).withBuyerReferenceIs(s.buyer()).count().executeForList(context), getTotalCount(); summary aggregation(context).toList().
Rustwith_commerce_platform_matching(Q::commerce_platforms().with_id_is(root)).with_buyer_reference_is(buyer)execute_for_page(context, 0, limit).await?, .data/.total_count; summary analytic get + try_f64.
TypeScriptfilterByCommercePlatform(root).withBuyerReferenceIs(buyer)executeForPage(context, 0, limit), .data SmartList/page.totalCount; summary rows via executeForRows.
Pythonfilter_by_commerce_platform(root_id).with_buyer_reference_is(buyer)execute_for_page(context, 0, limit), .data/.total_count; summary dictionaries via execute_for_rows.
GoWithCommercePlatformIs(root).WithBuyerReferenceIs(buyer)ExecuteForPage(context, 0, uint64(limit)), .Data/*TotalCount; summary ExecuteRecords + checked Value conversions.
C# / .NETFilterByCommercePlatform(root).WithBuyerReferenceIs(buyer)ExecuteForPageAsync(context, 0, limit), .Rows/.TotalCount; summary ExecuteForRowsAsync Value rows.
SwiftfilterByCommercePlatform(root).withBuyerReferenceIs(buyer)executeForPage(context, offset: 0, limit: limit), .items SmartList/.totalCount; summary TeaQLRecord .decimalValue.

Keep the native request's comment, purpose and trusted execution context. A direct ID or repeated business-key condition narrows the already authorized request; it does not replace root/buyer scope. Resolve an item through its authorized parent, never through an unscoped item-ID read. Detail/edit paths load up to three children to detect the supported two-item maximum, then reject overflow; list previews remain bounded and retained pages omit children.

Every fixture scope has two Orders totaling 7700 USD cents. The summary's provider COUNT/SUM repeats the same root + buyer predicates. The cache phase switches a,b,c,a on one context and fixed order-isolation-shared namespace: expected plans are BUILD, BUILD, BUILD, HIT with distinct authorized identities and total 2. Typed predicate identity separates sets; a trusted namespace alone does not authorize rows. Retain the .NET condition-key repair and TypeScript application-owned store.

Audited mutations and denial results​

Note edits use complete authorized Order scalar state; Python/TypeScript/Go/.NET explicitly reload scalars without loaded children before the audited save. The other three keep their recorded parent-save semantics. Item edits save only the selected owned item. Audit reasons explain the change; they do not by themselves bind the native audit principal to the session actor shown in JSON.

Facade codeInterpretation / caller action
UNAUTHENTICATEDResolve a valid server-side session before invoking the operation.
FORGED_SCOPE, INVALID_REQUEST, INVALID_BOUNDSCorrect the business payload; do not accept/coerce client identity or broaden bounds silently.
INVALID_TRUSTED_SCOPERepair missing/duplicate tenant provisioning; fail closed instead of taking the first root.
NOT_FOUNDSame response for missing and foreign Order/item identities. No public unscoped diagnostic lookup.
ITEM_LIMITComplete child-edit contract cannot be satisfied; reject the edit.
FORBIDDEN_OPERATION, FORBIDDEN_FIELDSession cannot write or patch is not the exact allowed shape; no partial write.
OK, changed: trueOne authorized note/label save completed; use fresh reads to inspect committed state.

The exact-one and overflow guards are visible in source; the retained request catalog does not add a duplicate-root migration or oversized-item campaign. The dated isolation receipt combines named JSON responses, provider SQL and independent full SQLite snapshots. Read it with the coverage boundary and native troubleshooting tables. It does not establish timing non-enumeration, concurrent membership/revocation semantics, production migration or automatic RLS.

Scope versions and release status​

ScopeLocal authorityQualification
Core Order v1.0: edit, paging and summaries17-case receiptJava and Swift published; Go, TypeScript, Rust, Python and .NET WORKSPACE PASS — RELEASE PENDING.
Buyer/tenant isolation v1.1Isolation receiptExplicit trusted-session/root/actor extension; not inferred from a buyer filter.
Stock v1.2Stock receiptOrder, inventory and request receipt participate in the reservation transaction.
Request/COMMIT cleanupLifecycle receiptAdds the Java JDBC workspace COMMIT-cleanup repair; earlier Java published scopes remain retained.
Finite concurrent load and cleanupSoak receiptSame lifecycle runtime identities; Swift published 0.3.1, six workspace runtimes pending release.

Existing nullable generation, console guide, append and pagination Assist repairs remain pending generator deployment. Keep the generated workspace's recorded dependency manifest and source identity; do not upgrade or downgrade based on a version mentioned in an example's historical result. A workspace PASS is not a published-consumer PASS. The School baseline and every historical receipt remain separate authorities.

Diagnose a failed operation​

First match the symptom against the native troubleshooting tables: Java, Rust, TypeScript, Python, Go, C# / .NET and Swift.

Match the operation's runtime, model revision and fixture before comparing its result with the recorded behavior. If a command, return shape or native error still differs, isolate that one operation on a disposable database and preserve the original error and dependency identity. The coverage matrix identifies available guidance and remaining recipe, packaging and integration work.