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:

json154 B
{
  "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:

FieldContents
enabledWhether the plugin is enabled
pendingWhether generation remains
runsRun count
fingerprintGeneration model fingerprint
outputsOutputs, each with language, directory and file counts written and removed
diagnosticsDiagnostics with severity, code, definition type and path, pointer, member, language and message
failureLast 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:

toml63 B
[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.

json160 B
{
  "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.

  • schemas contains serde structs with original wire names. Optional fields use Option<T>. The serializer writes a field only when its value is Some(value).
  • queries contains parameter structs, inferred row structs and functions that return stardust::OwnedValues<Row>.
  • mutations contains parameter structs and functions that commit stored mutations and return stardust::Commit.
  • expressions contains 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:

json204 B
{
  "expressions/double": [
    "*",
    "?n",
    2
  ],
  "queries/items": {
    "find": [
      "?item"
    ],
    "where": [
      [
        "?item",
        "key",
        "?key"
      ]
    ]
  }
}
rust408 B
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 typeRust type
stringString
integeri64
numberf64
booleanbool
object without a schemaBTreeMap<String, stardust::Value>
arrayVec<T>
Native timestampstd::time::SystemTime
Native signed durationstardust::Dur
Entitystardust::Link
Not knownstardust::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

OperationReturnsSummary
Sdk::statusdocumentsdk.status() returns the SDK generator's owned status document.
Sdk::syncnonesdk.sync(options) waits until the SDK generator published the definitions committed before the call.

Sdk::status

rust40 B
pub fn status(&self) -> Result<Document>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe sdk owner for this operation. Keep it alive during the call.

Errors

StatusWhen
Status::UNAVAILABLEthe database does not enable the sdk plugin
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

The document describes generation outputs, diagnostics and the last run: see runs.

Examples

Describe the SDK generator

rust145 B
let sync_options = stardust::parse("{maxWait {#dur PT5S}}", Format::DUST)?;
db.sdk().sync(Some(&sync_options))?;
let result = db.sdk().status()?;
Result / 146 B
{
  "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

rust60 B
pub fn sync(&self, options: Option<&Document>) -> Result<()>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe sdk owner for this operation. Keep it alive during the call.
optionsOption<&Document>Borrowed for the callAbsent selects operation defaultsThe 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

StatusWhen
Status::INVALID_ARGUMENToptions is not an object, or an option is invalid, duplicated or unsupported
Status::FAILEDthe plugin's work failed; status describes the failure
Status::TIMEOUTmaxWait passed before the work finished
Status::UNAVAILABLEthe database does not enable the sdk plugin
Status::CLOSEDthe database is closed

Notes

Database close interrupts an active wait. See when to call sync.

Examples

Run the SDK generator and wait for it

rust145 B
let sync_options = stardust::parse("{maxWait {#dur PT5S}}", Format::DUST)?;
db.sdk().sync(Some(&sync_options))?;
let result = db.sdk().status()?;
Result / 146 B
{
  "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