Skip to main content

Rust Order Tutorial

Build understanding around one draft Order: load its complete item list, change Notebook quantity from 2 to 3, save the Order and line totals together, then read the result in a new process. Follow the recorded native SQLite application and learn why each query, expression and transaction boundary is needed. The version and publication boundaries below apply to this specific example.

The later seventeen-case core suite uses the retained workspace pagination repairs: WORKSPACE PASS — RELEASE PENDING. Locally repaired nullable/pagination Assist remains pending generator deployment; it is not evidence that the deployed generator has those repairs.

1. Prepare the example​

Use the Rust Order source download (SHA-256 checksum). It contains the unchanged generated library, original first-flow console, model, fixture and Cargo.lock. No site checkout, retained built workspace, runtime source checkout or generator account is needed.

Install Rustup, Bash, curl, unzip and a C compiler/linker. On macOS, install Xcode Command Line Tools; on Debian/Ubuntu, use a native build toolchain such as build-essential. SQLite is bundled in the dependency and compiled locally; no database server or Docker is required. Windows readers can use WSL; this receipt does not verify a native Windows build. Python 3 is optional for the independent SQLite check below.

From an empty working directory:

curl --fail --location --remote-name https://teaql.io/examples/order/rust-first-run/order-rust-first-run.zip
curl --fail --location --remote-name https://teaql.io/examples/order/rust-first-run/SHA256SUMS
shasum -a 256 -c SHA256SUMS # On Linux, sha256sum -c SHA256SUMS also works.
unzip order-rust-first-run.zip
cd order-rust
rustup toolchain install 1.97.1 --profile minimal
rustc --version
cargo --version
bash order.sh build

rust-toolchain.toml selects Rust 1.97.1. Check the version inside the extracted directory; an environment RUSTUP_TOOLCHAIN override takes precedence. The build uses cargo build --locked, a package-local .cargo-home cache and target directory, with four jobs by default. First use downloads crates from the public registry and requires internet access. It does not use your existing Cargo cache or send the model to a service. ORDER_BUILD_JOBS=2 bash order.sh build reduces parallel compilation if memory is limited.

All six TeaQL crates are fixed to published 5.0.7 in the application manifest; Cargo.lock fixes transitive versions and registry checksums. The generated library manifest/source are unchanged. This is a first-run qualification of the historical version, not the latest Rust runtime. Do not run cargo update, add a local runtime patch, or mix in a newly generated library while following this receipt. The later pagination qualifications at the top of this page still apply.

The package reuses the evaluated Order v1.0 model and three-order fixture. Isolation and stock use separately evaluated model revisions. For a new model, follow the Rust Quick Start and obtain scoped Assist for that generated revision.

The original first-flow application is included unchanged at rust-app-console/src/main.rs. It contains imports, startup, helpers and all eight original case handlers. The read/write excerpts below are function-body excerpts, not standalone files. Keep AuditedSave, TeaqlRuntime, CustomerOrder, OrderItem, Q, E, teaql_core::Entity and the Failure alias. prepare_edit and the transaction macro are application helpers.

2. Initialize SQLite and complete the first edit​

From the extracted order-rust directory:

bash order.sh init
bash order.sh read
bash order.sh edit
bash order.sh verify

init creates .local/orders.sqlite, explicitly ensures the schema and seeds three Orders/six items. It refuses an existing file instead of importing duplicate Orders or clearing data. Read/edit/verify refuse a missing database. Each phase starts a new process against the same absolute path, so the final read demonstrates that the edit survives process exit.

Command / phaseExpected result
init → bootstrap, seedExplicit schema setup and ORDER_OK for both phases.
read → draft-graphORD-2026-1001 is DRAFT; total 3850 USD cents.
edit → draft-editNotebook quantity 3, Notebook line total 3750, Order total 5100.
verify → restart-readbackThe same totals in another process; Order and changed item version 2, untouched items version 1.

Read/edit handlers print ORDER_CASE JSON followed by an ORDER_OK completion line. Find the Order by business number and the item by SKU; numeric IDs are not portable fixture keys. Run the edit once when comparing first-run versions. For another run, choose a new disposable absolute database path:

export ORDER_DATABASE="$(mktemp -d)/orders.sqlite"
bash order.sh init
bash order.sh read
bash order.sh edit
bash order.sh verify

Optionally check the persisted data independently after the edit:

python3 check_database.py "${ORDER_DATABASE:-$PWD/.local/orders.sqlite}" edited fixture.json

The unchanged oracle opens SQLite read-only and checks quantities, money, versions, relationships and integrity. It never seeds or repairs data. Optional bash order.sh notes runs the already-recorded value/NULL/empty/NotLoaded and invalid-quantity handlers. Expected NotLoaded panics are caught by those handlers; a failed build or unhandled process error is not an expected negative result.

What happens at startup​

The console calls service_runtime_from_env().await? and explicitly awaits context.ensure_schema(). The shell script maps ORDER_DATABASE to the factory's actual input, ORDER_WORKFLOW_SERVICE_CORE_DATABASE_URL=sqlite://..., and sets ORDER_FIXTURE. If you invoke the binary directly, ORDER_DATABASE alone does not configure the provider.

Module installation registers metadata and behavior; schema reconciliation is an explicit database operation. This disposable console initializes schema at startup. In a service, keep startup/admin schema operations separate from requests, and obtain tenant/actor/policy from trusted application context. The fixture's buyer field does not establish authorization.

First-run evidence and boundaries​

The 2026-11-14 receipt records an extracted-ZIP build with an empty Cargo cache and target directory, Rust 1.97.1 on macOS ARM64, and six published TeaQL 5.0.7 crates. It binds the archive, lockfile, downloaded crate checksums and sources. The three-order seed and edited database passed the read-only oracle. Repeated initialization left the database unchanged, and a missing-database read did not create an empty file. This is an isolated dependency/build environment, not a fresh OS image or a new multi-platform, fault or stress campaign.

The original first-flow receipt remains the authority for the original eight cases, including the optional note handlers. The later seventeen-case receipt retains its workspace pagination requirements. The download contains the original first-flow program, not the later seventeen-case program. Its passing first edit does not clear any existing pending-release or generator-deployment marker. See the package README for source layout and troubleshooting.

3. Load the full Order before editing​

let mut orders=Q::customer_orders().with_order_number_is("ORD-2026-1001").with_order_status_is_draft().limit(2)
.comment("Load full draft order state").purpose("Validate and edit one draft order").execute_for_list(context).await?;
assert_eq!(orders.data.len(),1); let mut order=orders.data.remove(0);
assert_eq!(E::customer_order(&order).get_currency_code().eval().as_deref(),Some("USD"));
let id=E::customer_order(&order).get_id().eval().ok_or("Missing order ID")?;
let children=Q::order_items().with_customer_order_matching(Q::customer_orders().with_id_is(id).limit(2))
.order_by_sku_code_asc().order_by_id_asc().limit(101)
.comment("Load complete bounded order items").purpose("Compute the full order total").execute_for_list(context).await?;
assert!(children.data.len()<=100,"Order item limit exceeded");

The outer bound of 2 detects more than one matching DRAFT Order; the application requires exactly one. This query does not prove global business-key uniqueness. The child bound of 101 is an overflow sentinel for a supported maximum of 100 items. Require exactly one Order, DRAFT status and at most 100 loaded items before continuing. A one-item preview is useful for a list screen, but cannot supply the complete total for an edit. The full source performs these checks after the query; keep them when adapting the excerpt.

comment describes the operation and purpose records the business reason. Both travel with execution through the trusted context. A buyer filter in this v1.0 fixture is a business predicate; it does not authenticate or authorize a buyer. Use the separate buyer/tenant isolation contract when implementing protected access.

4. Validate money and save one atomic edit​

The application validates integral quantity in [1, 100], USD currency, each stored line amount and the complete new Order total. Prices and totals are integer cents. It finds exactly one SKU-NOTEBOOK, computes 3 × 1250 + 3 × 450 = 5100, then changes the selected item and Order together. The following write excerpt assumes those validated, fully loaded variables; it is not a replacement for validation.

The audit reason is Edit draft Order quantity and totals atomically, named EDIT in most examples and editReason/EditReason in Go, Swift and .NET.

context.execute_in_transaction::<order_workflow_service_core::ServiceRuntimeExecutor,_,_>(|transaction|Box::pin(async move {
transaction.save_audited(order.audit_as(EDIT)).await?;
transaction.save_audited(item.audit_as(EDIT)).await?;
Ok(())
})).await?;

prepare_edit validates amounts with checked arithmetic and returns the Order plus an item clone. Save both through the same typed transaction. Updating a detached child clone and saving only the parent does not flush that clone. Keep the relation handle alive while borrowing its loaded value.

A successful audited save returns the persisted typed entity. The core example reads again after mutation, rather than treating a pre-save object as independent evidence of committed state. A rejected stale write requires reloading authoritative state and a business decision before retrying; it is not permission to overwrite the winner or retry every provider error.

5. Use projections, nulls and pages deliberately​

TaskRust API in this exampleResult / responsibility
Execute a bounded queryexecute_for_list(context).await?Typed SmartList; preserve native errors and check cardinality.
Read selected moneyE::customer_order(&order).get_total_minor().eval()Loaded integer cents; not a formatting or currency conversion API.
Access selected itemsorder.order_item_list().value()Only the relation that was explicitly loaded.
Default a selected SQL NULL noteget_order_note().or_if_null(Some("No note".to_owned()))Null-only fallback; an empty string stays empty and NotLoaded still reports a missing field.
Save an audited mutationtransaction.save_audited(order.audit_as(EDIT)).await?Persisted typed entity; the required transaction includes all changed entities.
Request an exact page totaloffset(offset as u64, limit as u64).count() → page.total_countTotal of the filtered set, independent of page length.

The note accessors in the table are called on the corresponding E expression. required, report, pageRows, load, edit and prepare_edit are application helpers where present; they are not additional generated terminal methods.

Note stateExpected behavior
Selected valueLeave at reception stays that value.
Selected SQL NULLA null-only default produces No note.
Selected empty textRemains the empty string.
Omitted fieldNative NotLoaded diagnostic, including when a null-only default is attempted.

The following page API belongs to the later workspace-qualified example, not the downloadable first-flow program. Its existing pending-release requirements remain in force; use the Rust Order query recipes and their separate workspace/fixture instructions before running it.

For a read-only list screen, that bounded-page handler validates offset >= 0 and 1 <= limit <= 3, sets a stable total/ID order and explicitly selects one item preview per Order. With validated offset, limit and buyer, its native query is:

let page=Q::customer_orders().with_buyer_reference_is(buyer.as_str()).order_by_total_minor_asc().order_by_id_asc()
.select_order_item_list_with(Q::order_items().order_by_sku_code_asc().order_by_id_asc().limit(1)).offset(offset as u64,limit as u64).count()
.comment("Read bounded Order pages").purpose("Compare filtered totals and per-order item previews").execute_for_list(context).await?;

This query only reads. Do not save its one-item preview as if it were a full Order edit or infer deletion of omitted items. The pagination fixture has eight matching BUYER-EXPORT Orders, whereas the first-edit fixture above has three Orders overall. See the page API decision guide for fixture selection, continuous export, retained-ID jumps and aggregate results.

6. Diagnose a failure before changing code​

Use the request future’s native error, preserve NotLoaded panic details, and distinguish optimistic version rejection from provider busy/locked failures. Do not flatten every Err into an empty result.

SymptomFirst action
Wrong Rust versionRun rustc --version inside the extracted directory and check RUSTUP_TOOLCHAIN; the package pins 1.97.1.
Native compiler/linker failureInstall the platform C toolchain; bundled SQLite still needs compilation. Lower ORDER_BUILD_JOBS if memory is tight.
Registry or lockfile failureRestore public registry access and the supplied manifests/lockfile; retry bash order.sh build without a runtime path patch.
Missing executableFinish build before running phases.
Existing database or partial seedChoose a new absolute ORDER_DATABASE; initialization never deletes or repairs old data.
Empty Order or duplicate rowConfirm absolute DB path, fixture and business number; preserve the cardinality check.
Wrong total after editCheck complete item loading and integer validation before the audited save.
Missing field errorReload the field/relation explicitly; do not substitute a null default.
Version conflictReload authoritative state and decide whether the requested edit is still valid.
Busy/locked, commit or cancellation failureInspect native provider error and transaction boundary; follow the Rust Order troubleshooting table.

Continue with the Order API usage guide, Rust advanced data operations, version and qualification table and documentation coverage matrix. The School regression baseline and all prior Order receipts remain unchanged.

Continue with advanced Order writes​

Follow Rust Advanced Order Mutations for explicit line deletion, legal state transitions and stale-version recovery. Each recipe explains its starting state, transaction boundary, native errors and independent readback using the existing qualified example. Start a fresh recipe database; do not reuse the quantity-edited database above.

Continue with Order queries​

Use Rust Order Queries for continuous export, retained-ID page jumps and provider summaries. The query recipes use separate nine-/ten-order datasets; keep the fixture and context/store lifetime with the operation you are learning.

Continue with buyer and tenant isolation​

Use Rust Order Isolation to upgrade the model to v1.1 and build root/buyer scope from an application-owned trusted session.