SDK generation
The SDK plugin generates a typed package from the database's stored definitions. While the database is open, it updates that package in the configured output directory.
The generated code calls the language binding and provides typed access to stored definitions.
Enable sdk in the plugin selection at open, with the output settings below.
Calls without it report the unavailable status.
Query results recursively omit fields containing empty objects or arrays.
Generated rows use Value::Null for absent dynamic fields and empty collections for absent list or map fields.
Null, empty strings, false, zero and array positions stay intact in the returned document.
Native time values
Generated native time fields use
std::time::SystemTime for timestamps and stardust::Dur for signed stored durations.
Timeout arguments use std::time::Duration, which cannot represent negative values.
The binding supplies the generated Serde adapters and checked instant_from_ticks, instant_to_ticks, duration_from_ticks and duration_to_ticks conversions.
The explicit tick conversions refuse precision loss and values outside the target range. These conversions perform no native operation.
A native time schema requires one string member, #utc or #dur, and sets additionalProperties to false.
For example, this schema describes a native timestamp:
{
"type": "object",
"properties": {
"#utc": {
"type": "string"
}
},
"required": [
"#utc"
],
"additionalProperties": false
}
Use #dur in both places for a duration schema.
Schema fields support lists and stored-schema references.
Scalar time fields also type query filters and rows.
Native time expression results use the same binding types.
An ordinary string schema stays text, including strings with a date-time format.
Native ticks are signed 64-bit counts of 100 ns.
Timestamp ticks count from the Unix epoch in UTC. Duration ticks can be negative.
Runs
The plugin generates once at open, and again after commits that change definitions. Data commits do not start a run. A run reads all definitions from one committed snapshot.
Each successful render replaces the output directory's contents, including the startup run. See file ownership before choosing an output directory.
Call status to inspect these fields:
| Field | Contents |
|---|---|
enabled | Whether the plugin is enabled |
pending | Whether generation remains |
runs | Run count |
fingerprint | Generation model fingerprint |
outputs | Outputs, each with language, directory and file counts written and removed |
diagnostics | Diagnostics with severity, code, definition type and path, pointer, member, language and message |
failure | Last run failure, with code and message; absent after a successful run |
When to call sync
Generation runs automatically at open and after definition commits, according to the debounce settings. Opening the database or committing definitions can finish before the generated files are ready. Call sync before compiling or reading files that must include those definitions. Applications that can use the files after automatic generation finishes do not need an explicit sync.
The call requests a render immediately, bypassing debounce. It also rebuilds files when definitions have not changed.
Its options accept only the common maxWait option. A timeout leaves the requested run active.
Repeated waits after a timeout join that run. Inspect status when generation reports failed.
Without an output language, sync validates the model inline and writes no files.
Settings
Set rust.dir to a dedicated output directory. Enable the serde feature of the stardust crate.
The generated structs use serde derives directly. Add serde with its derive feature to your application's Cargo.toml:
[dependencies]
serde = { version = "1", features = ["derive"] }Keep your Cargo project and application source outside the output directory.
The plugin writes mod.rs and one module for each definition type that has generated APIs.
{
"sdk": {
"rust": {
"dir": "gen/people"
},
"debounce": {
"#dur": "PT0.25S"
},
"max_wait": {
"#dur": "PT2S"
}
}
}
Relative paths start at the process working directory when you open the database.
Call database.sdk().sync(Some(&sync_options))? before compilation, with native options such as {maxWait {#dur PT5S}}.
The Rust modules
Import the generated mod.rs into your application with a Rust #[path] module declaration.
Each module exposes MODEL_FINGERPRINT, the deterministic fingerprint of the shared generation model.
schemascontains serde structs with original wire names. Optional fields useOption<T>. The serializer writes a field only when its value isSome(value).queriescontains parameter structs, inferred row structs and functions that returnstardust::OwnedValues<Row>.mutationscontains parameter structs and functions that commit stored mutations and returnstardust::Commit.expressionscontains parameter structs and functions that evaluate stored expressions with the database's current macros.
The functions run synchronously on the calling thread. Parameter structs pass by value, and decoded rows own their data. Query cursors implement Iterator.
The database must remain open while you advance the cursor. The cursor owns its query and rows. It releases them on exhaustion or on the first error. Drop or cursor.close() releases the cursor immediately.
Each row owns its data. Expression functions decode and release the owned result document before returning.
Binding conversion errors include the field path.
Declared defaulted parameters and optional filters use Option<T> with serde omission.
None keeps a stored default or leaves a filter unbound. Some(value) supplies the value, including zero, false or an empty collection.
Variables used only in predicates remain required. Entity filters use stardust::Link.
Aggregate outputs, window outputs and compiler result slots are not filter inputs.
Some(stardust::Value::Null) supplies explicit null where a dynamic input permits it. A declared parameter with null reports missing_parameter.
For these stored definitions:
{
"expressions/double": [
"*",
"?n",
2
],
"queries/items": {
"find": [
"?item"
],
"where": [
[
"?item",
"key",
"?key"
]
]
}
}
let doubled = expressions::double(db, expressions::DoubleParameters { n: 21 })?;
assert_eq!(doubled, 42);
let parameters = queries::ItemsParameters {
item: None,
key: Some(stardust::Value::String("b".into())),
};
let mut rows = queries::items(db, parameters, &stardust::RunOptions::default())?;
while let Some(row) = rows.next() {
let item = row?;
assert_ne!(item.item, stardust::Link(0));
}| Definition type | Rust type |
|---|---|
string | String |
integer | i64 |
number | f64 |
boolean | bool |
object without a schema | BTreeMap<String, stardust::Value> |
array | Vec<T> |
| Native timestamp | std::time::SystemTime |
| Native signed duration | stardust::Dur |
| Entity | stardust::Link |
| Not known | stardust::Value |
Direct references to stored object schemas use Box<T> so recursive records have finite size.
Arrays of schema records use Vec<T>. Native time references use the time types described above.
Other non-object references use the dynamic value fallback.
The generated code qualifies standard and binding types, so authored schema names cannot change their meaning.
Names
Struct names use PascalCase. Functions and fields use snake_case. Serde renames keep the original wire names, including leading underscores.
Each definition type has its own module. A schema and a query can share a definition name.
Member collisions, derived-name collisions and reserved-name collisions fail with Model_Errors before publication.
The plugin preserves previous output after a model error. Rename the conflicting definition or member and synchronize again.
File ownership
The plugin owns the entire configured output directory. Every successful render removes its previous contents, including edited files, unrelated files and subdirectories.
Keep application source, database files and other data outside this directory.
Do not edit generated files: the next run replaces your changes.
The plugin retains only its internal .stardust-sdk.lock file between runs.
The plugin renders and validates the package before it removes any files. Rendering errors leave the previous directory contents unchanged. A filesystem error during cleanup or writing can leave the directory empty or partly written. The next successful run clears that partial output and writes a fresh package. Use sync before a build and check its result.
Each file is written through an atomic rename. Rebuilding the whole directory is not atomic.
A destination lock prevents concurrent publication and reports Destination_Busy when another publisher holds it.
Use a separate output directory for each database, with no directory nested inside another output directory.
Cleanup removes symlinks inside the output directory without following them.
The output directory itself and the lock file must not be symlinks.
Directory inspection is limited to 65,536 entries, 64 levels and 16 MiB of stored paths.
An inspection failure leaves the previous contents unchanged.
Operations
| Operation | Returns | Summary |
|---|---|---|
| Sdk::status | document | sdk.status() returns the SDK generator's owned status document. |
| Sdk::sync | none | sdk.sync(options) waits until the SDK generator published the definitions committed before the call. |
Sdk::status
pub fn status(&self) -> Result<Document>Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
self | &Self | Borrowed for the call | Required | The sdk owner for this operation. Keep it alive during the call. |
Errors
| Status | When |
|---|---|
Status::UNAVAILABLE | the database does not enable the sdk plugin |
Status::CLOSED | the database is closed |
Status::OUT_OF_MEMORY | native memory is exhausted |
Notes
The document describes generation outputs, diagnostics and the last run: see runs.
Examples
Describe the SDK generator
let sync_options = stardust::parse("{maxWait {#dur PT5S}}", Format::DUST)?;
db.sdk().sync(Some(&sync_options))?;
let result = db.sdk().status()?;{
"enabled": true,
"pending": false,
"runs": 1,
"fingerprint": "sha256:f0e170ac54b67b0f9a8e4794922a586c21da2910b0766dcd3feb410b416b61e8"
}C exports: stardust_db_plugin_call, stardust_result_take_document, stardust_result_error, stardust_result_release
Sdk::sync
pub fn sync(&self, options: Option<&Document>) -> Result<()>Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
self | &Self | Borrowed for the call | Required | The sdk owner for this operation. Keep it alive during the call. |
options | Option<&Document> | Borrowed for the call | Absent selects operation defaults | The borrowed call options, or none. Optional maxWait is a nonnegative native duration, such as {maxWait {#dur PT5S}}. Without it, or with zero, the call checks once. |
Errors
| Status | When |
|---|---|
Status::INVALID_ARGUMENT | options is not an object, or an option is invalid, duplicated or unsupported |
Status::FAILED | the plugin's work failed; status describes the failure |
Status::TIMEOUT | maxWait passed before the work finished |
Status::UNAVAILABLE | the database does not enable the sdk plugin |
Status::CLOSED | the database is closed |
Notes
Database close interrupts an active wait. See when to call sync.
Examples
Run the SDK generator and wait for it
let sync_options = stardust::parse("{maxWait {#dur PT5S}}", Format::DUST)?;
db.sdk().sync(Some(&sync_options))?;
let result = db.sdk().status()?;{
"enabled": true,
"pending": false,
"runs": 1,
"fingerprint": "sha256:f0e170ac54b67b0f9a8e4794922a586c21da2910b0766dcd3feb410b416b61e8"
}C exports: stardust_db_plugin_call, stardust_result_take_document, stardust_result_error, stardust_result_release