Queries and mutations

The example stores the people in a database and queries their names. It collects query pages, updates Ada's age, and reads the changed age.

The optional adaptive query planner learns from runs and compares alternative plans for stored queries. Enable it through the database's plugins open option.

Example

The example compares these results:

  • a committed mutation
  • a repeated mutation
  • a query that matches no entity

Give Ada her birthday and read her age

birthday_text holds this document:

edn82 B
{:query {:find  [?e]
         :where [[?e "name" "Ada"]]}
 :patch {:?e {:age 37}}}

query_text holds this document:

edn66 B
{:find  [?age]
 :where [
   [?e "name" "Ada"]
   [?e "age" ?age]]}
rust317 B
let birthday = stardust::parse(birthday_text, Format::EDN)?;
db.mutation(&birthday)?.run(None, &RunOptions::default(), None)?;
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut rows = query.run(None, &RunOptions::default(), None)?;
let result = rows.all_pages()?;
Result / 20 B
{:value [{:age 37}]}

Query pages

Each query page is an owned document.

  • You can keep a page after you release the rows handle, query, or database that produced it.
  • Release each page when you finish with its values. The document ownership rule applies.

Cached joins

The database can keep completed native fact joins as owned binding rows before aggregation. When you run the same query and plan again, the cache can supply those rows at the same database snapshot. Aggregates and output expressions still run for each call.

The cache uses the database working-memory budget and gives memory back when queries need it. The cache discards rows from joins that do not complete. After a write, new queries use a new snapshot. An active reader keeps the rows from its original snapshot.

Parameterized, temporal and overlay queries use their normal execution paths. Queries with predicates, derivations, member clauses or transaction terms also use those paths. Background planner trials and sampled foreground measurements execute joins directly.

Exact indexes

A query or mutation definition that compares a field with a value makes the database build that field's exact index. The comparison is a fact clause with a constant or a parameter value, or a =, <, <=, >, >= or hasPrefix predicate on a fact clause's value. With the index, a hasPrefix predicate reads only the texts that start with the prefix, and no value of another type.

  • Storing the definition starts the build. An inline query or mutation that compares a field the same way also starts one.
  • The database builds the index in the background, including the values committed before the definition. The call that started it does not wait.
  • Queries scan the field until its index is ready. The results are the same; only the time differs.
  • Use indexes_sync to wait until every index that earlier definitions and inline runs ask for is ready, for example before you measure a query.
  • An index that no definition uses any more stays until the database next opens.

Operations

OperationReturnsSummary
Database::read_entitydocumentdatabase.read_entity(entity, max_depth, max_entities) atomically returns an owned {document links revisions truncated} document, expanding links up to max_depth hops.
Database::queryqueryOpen an owned query from a path or an inline definition.
Database::mutationmutationOpen an owned mutation from a path or an inline definition.
Query::runrowsRun the query and return an owned row cursor.
Query::closenoneRelease the query handle.
Rows::next_pagedocumentRead the next page as an owned document.
Rows::pagespagesrows.pages() iterates the non-empty pages of the cursor.
Rows::all_pagesdocumentrows.all_pages() reads every remaining page into one owned array document.
Rows::closenoneRelease the rows handle.
Query::subscribesubscriptionquery.subscribe(parameters, options) opens an owned live subscription.
Subscription::nexteventWait for the next live event.
Subscription::eventseventssubscription.events() delivers events in order until the subscription is cancelled, closes or fails.
Subscription::cancelnonesubscription.cancel() ends the subscription.
Subscription::closenoneRelease the subscription handle.
Mutation::runcommitRun the mutation and return commit information.
Mutation::closenoneRelease the mutation handle.
Database::merge_patchcommitdatabase.merge_patch(patch) applies an entity-keyed patch document in one transaction and returns commit information.
Database::indexes_syncnonedatabase.indexes_sync(max_wait) waits until the database built every exact index that earlier definition commits and inline runs ask for.
Database::bulk_beginnonedatabase.bulk_begin() starts a bulk build of data merge patches held by the database.
Database::bulk_addnonedatabase.bulk_add(patch) copies and queues one merge-patch document in the bulk build.
Database::bulk_finishdocumentdatabase.bulk_finish() publishes the bulk build with one commit, ends it and returns an owned summary document.
Database::bulk_abortnonedatabase.bulk_abort() drops the bulk build in progress without writing it.

Database::read_entity

rust93 B
pub fn read_entity(&self, entity: i64, max_depth: i64, max_entities: i64) -> Result<Document>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe database owner for this operation. Keep it alive during the call.
entityi64ValueRequiredThe decimal user entity ID.
max_depthi64ValueAbsentLink hops to expand along each path, 0 through 32. 0, the default, leaves every link a {#link id} reference.
max_entitiesi64ValueAbsentThe most entity documents the result holds, counting the root and every expanded or absent target each time it is placed. 0 selects the default of 1000.

Errors

StatusWhen
Status::INVALID_ARGUMENTthe entity ID is outside the user entity range, max_depth is negative or above 32, or max_entities is negative
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

revisions maps each placed entity's decimal ID to its last-touch transaction for #_tx.stardust/checkAndSet. Empty object and array fields are omitted recursively. See entity reads for result fields, JSON Pointer links and expansion rules.

Examples

Read Bob with his mentor expanded

rust38 B
let result = db.read_entity(2, 1, 0)?;
Result / 360 B
{:value {:document  {:age    41
                     :mentor {:age  36
                              :name "Ada"
                              :role "engineer"}
                     :name   "Bob"
                     :role   "engineer"}
         :links     {"/mentor" {:#link 1}}
         :revisions {:1 4
                     :2 4}
         :truncated false}}

C exports: stardust_db_read_entity, stardust_result_take_document, stardust_result_error, stardust_result_release

Database::query

rust71 B
pub fn query<'a>(&self, source: impl Into<Source<'a>>) -> Result<Query>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe database owner for this operation. Keep it alive during the call.
sourceimpl Into<Source<'a>>ValueRequiredAn inline native definition or a stored definition path.

Errors

StatusWhen
Status::NOT_FOUNDno definition is stored at the path
Status::INVALID_DEFINITIONthe definition is invalid
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

Inline definitions are copied. Stored paths select their definition at run time.

Query documents.

Examples

Open an inline query and read its first page

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust190 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut rows = query.run(None, &RunOptions::default(), None)?;
let result = rows.next_page()?;
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

Refuse an invalid query definition

query_text holds this document:

edn12 B
{:find [?x]}
rust101 B
let definition = stardust::parse(query_text, Format::EDN)?;
let result = db.query(&definition).err();
Result / 202 B
{:value {:code    "unbound_variable"
         :message "Unbound_Variable"
         :path    nil
         :field   nil
         :entity  nil
         :offset  nil
         :status  "invalid_definition"}}

Report a missing stored query

rust46 B
let result = db.query("people/missing").err();
Result / 209 B
{:value {:code    "not_found"
         :message "no definition at this path"
         :path    "people/missing"
         :field   nil
         :entity  nil
         :offset  nil
         :status  "not_found"}}

C exports: stardust_db_query_open, stardust_db_query_error

Database::mutation

rust77 B
pub fn mutation<'a>(&self, source: impl Into<Source<'a>>) -> Result<Mutation>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe database owner for this operation. Keep it alive during the call.
sourceimpl Into<Source<'a>>ValueRequiredAn inline native definition or a stored definition path.

Errors

StatusWhen
Status::NOT_FOUNDno definition is stored at the path
Status::INVALID_DEFINITIONthe definition is invalid
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

Inline definitions are copied. Stored paths select their definition at run time.

Mutation documents.

Examples

database/mutation

birthday_text holds this document:

edn82 B
{:query {:find  [?e]
         :where [[?e "name" "Ada"]]}
 :patch {:?e {:age 37}}}
rust160 B
let source = stardust::parse(birthday_text, Format::EDN)?;
let mutation = db.mutation(&source)?;
let result = mutation.run(None, &RunOptions::default(), None)?;
Result / 153 B
{:value {:status       "committed"
         :transaction  5
         :facts        1
         :committed_at 17923367687196265
         :ids          {}}}

C exports: stardust_db_mutation_open, stardust_db_mutation_error

Query::run

rust161 B
pub fn run(
        &self,
        parameters: Option<&Document>,
        options: &RunOptions,
        explain: Option<&mut QueryExplain>,
    ) -> Result<Rows>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe query owner for this operation. Keep it alive during the call.
parametersOption<&Document>Borrowed for the callAbsent means no supplied parametersAn optional object of parameter values that merge-patches the definition's declared parameters. A parameter matched in the entity position of a fact clause takes an entity reference {#link id}, never the bare ID number: a commit returns IDs as numbers, so wrap one as {#link id}, or as the typed Link value where the binding has one, before passing it. A query run fails with entity_reference_expected when a bare number reaches that position. Projected and found entities also read back as {#link id}, so a typed field that receives one uses Link rather than a plain integer.
options&RunOptionsValueRequired options record. See field defaultsThe operation's options record. See its field defaults.
explainOption<&mut QueryExplain>Caller-owned outputAbsent skips explain outputOptional explain output. This record contains explain output for query run. The compile, plan, execute, group and order fields divide the wall time of run into stages.

Errors

StatusWhen
Status::NOT_FOUNDthe stored query definition was deleted
Status::INVALID_DEFINITIONthe loaded query definition is invalid
Status::INVALID_ARGUMENTthe parameters or run options are invalid
Status::EVALUATION_FAILEDthe query fails or exceeds max_cost
Status::CLOSEDthe query is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

Query documents.

Examples

Open an inline query and read its first page

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust190 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut rows = query.run(None, &RunOptions::default(), None)?;
let result = rows.next_page()?;
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

Capture the host duration boundary

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}

boundary_text holds this document:

edn19 B
9223372036854775807
rust394 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let boundary = stardust::parse(boundary_text, Format::EDN)?;
let seconds = boundary.i64(boundary.root()?)? as u64;
let options = RunOptions { page_size: 2, max_cost: std::time::Duration::from_secs(seconds), ..Default::default() };
let _rows = query.run(None, &options, None)?;
let result = options;
Result / 85 B
{:value {:page_size 2
         :max_cost  9223372036854775807
         :as_of     0}}

Truncate a positive sub-tick duration

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}

boundary_text holds this document:

edn2 B
99
rust391 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let boundary = stardust::parse(boundary_text, Format::EDN)?;
let nanos = boundary.i64(boundary.root()?)? as u64;
let options = RunOptions { page_size: 2, max_cost: std::time::Duration::from_nanos(nanos), ..Default::default() };
let _rows = query.run(None, &options, None)?;
let result = options;
Result / 67 B
{:value {:page_size 2
         :max_cost  0
         :as_of     0}}

Explain query execution

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust244 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut explain = stardust::QueryExplain::default();
let _rows = query.run(None, &RunOptions::default(), Some(&mut explain))?;
let result = explain;
Result / 1.1 kB
{:value {:load_definition   {:cpu         789
                             :wall        803
                             :arena_bytes 1680}
         :parameters        {:cpu         9
                             :wall        12
                             :arena_bytes 0}
         :run               {:cpu         13782
                             :wall        13889
                             :arena_bytes 7424}
         :total             {:cpu         14619
                             :wall        14743
                             :arena_bytes 9104}
         :arena_capacity    4194304
         :work              9966
         :rows              3
         :compile           326
         :plan              575
         :execute           0
         :group             0
         :order             0
         :memory_bytes      5995
         :memory_refusals   0
         :budget_bytes      10489856512
         :budget_used_bytes 10194
         :budget_peak_bytes 14267
         :budget_refusals   0
         :retry             0
         :stages_completed  3
         :retries           0}}

Run with typed query options

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust273 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let options = RunOptions { page_size: 2, max_cost: std::time::Duration::from_secs(1), ..Default::default() };
let _rows = query.run(None, &options, None)?;
let result = options;
Result / 74 B
{:value {:page_size 2
         :max_cost  10000000
         :as_of     0}}

C exports: stardust_db_query_run, stardust_db_rows_error

Query::close

rust18 B
pub fn close(self)

Consumes the receiver handle.

Parameters

ParameterTypeOwnershipDefaultMeaning
selfSelfConsumed ownerRequiredThe query owner to release. Do not use it after this call.

Examples

Open an inline query and read its first page

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust205 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut rows = query.run(None, &RunOptions::default(), None)?;
let result = rows.next_page()?;
query.close();
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

C exports: stardust_db_query_release

Rows::next_page

rust47 B
pub fn next_page(&mut self) -> Result<Document>

Parameters

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

Errors

StatusWhen
Status::EVALUATION_FAILEDthe page does not render
Status::CLOSEDthe rows is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

An empty array ends the cursor. Every page reads the snapshot selected by the run. Returned pages survive cursor and database closure.

Examples

Open an inline query and read its first page

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust190 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut rows = query.run(None, &RunOptions::default(), None)?;
let result = rows.next_page()?;
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

C exports: stardust_db_rows_next, stardust_result_take_document, stardust_result_error, stardust_result_release

Rows::pages

rust36 B
pub fn pages(&mut self) -> Pages<'_>

Parameters

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

Errors

StatusWhen
Status::EVALUATION_FAILEDa page does not render
Status::CLOSEDthe rows is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

Pages are read lazily from the run's snapshot. Rust callers own each page. In other bindings, a page closes when iteration advances. Use next to retain an owned page. Close the cursor separately.

Examples

Iterate the pages of a query run

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust514 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let options = RunOptions {
    page_size: 1,
    ..RunOptions::default()
};
let mut rows = query.run(None, &options, None)?;
let mut result = 0i64;
let mut pages = rows.pages();
while let Some(page) = pages.next() {
    let page = page?;
    let mut children = page.children(page.root()?);
    while let Some(child) = children.next() {
        child?;
        result += 1;
    }
    drop(children);
    page.close();
}
Result / 10 B
{:value 3}

C exports: stardust_db_rows_next, stardust_result_take_document, stardust_result_error, stardust_result_release, stardust_document_root, stardust_document_read_many, stardust_document_release

Rows::all_pages

rust47 B
pub fn all_pages(&mut self) -> Result<Document>

Parameters

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

Errors

StatusWhen
Status::EVALUATION_FAILEDa page does not render
Status::CLOSEDthe rows is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

The array contains rows, not page documents. Previously read pages are excluded. Memory grows with the remaining result. Use pages for bounded page-by-page processing. Close the cursor separately.

Examples

Read all remaining rows into one document

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust252 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let options = RunOptions {
    page_size: 1,
    ..RunOptions::default()
};
let mut rows = query.run(None, &options, None)?;
let result = rows.all_pages()?;
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

C exports: stardust_db_rows_next, stardust_result_take_document, stardust_result_error, stardust_result_release, stardust_document_count, stardust_document_read_many, stardust_document_i64, stardust_document_f64, stardust_document_release, stardust_document_builder_create, stardust_document_builder_add_many, stardust_document_builder_seal, stardust_document_builder_release

Rows::close

rust18 B
pub fn close(self)

Consumes the receiver handle.

Parameters

ParameterTypeOwnershipDefaultMeaning
selfSelfConsumed ownerRequiredThe rows owner to release. Do not use it after this call.

Examples

Open an inline query and read its first page

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust204 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut rows = query.run(None, &RunOptions::default(), None)?;
let result = rows.next_page()?;
rows.close();
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

C exports: stardust_db_rows_release

Query::subscribe

rust131 B
pub fn subscribe(
        &self,
        parameters: Option<&Document>,
        options: &RunOptions,
    ) -> Result<Subscription>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe query owner for this operation. Keep it alive during the call.
parametersOption<&Document>Borrowed for the callAbsent means no supplied parametersAn optional object of parameter values that merge-patches the definition's declared parameters. A parameter matched in the entity position of a fact clause takes an entity reference {#link id}, never the bare ID number: a commit returns IDs as numbers, so wrap one as {#link id}, or as the typed Link value where the binding has one, before passing it. A query run fails with entity_reference_expected when a bare number reaches that position. Projected and found entities also read back as {#link id}, so a typed field that receives one uses Link rather than a plain integer.
options&RunOptionsValueRequired options record. See field defaultsThe operation's options record. See its field defaults.

Errors

StatusWhen
Status::INVALID_DEFINITIONthe query or its callable definitions are invalid
Status::INVALID_ARGUMENTthe parameters or subscription options are invalid
Status::CLOSEDthe query is closed
Status::OUT_OF_MEMORYnative memory is exhausted
Status::LOCKEDthe shared wake dispatcher has no signal admission slot

Notes

The subscription copies its definition and parameters. Later definition edits do not change it. The page_size option is ignored.

Subscriptions register readiness callbacks automatically. Event waits use runtime notifications instead of blocking in the C ABI.

Query documents.

Examples

query/subscribe

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust260 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut subscription = query.subscribe(None, &RunOptions::default())?;
let event = subscription.next().await?.ok_or("no initial event")?;
let result = event.result;
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

Read the complete initial subscription event

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust253 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut subscription = query.subscribe(None, &RunOptions::default())?;
let event = subscription.next().await?.ok_or("no initial event")?;
let result = event;
Result / 138 B
{:value {:sequence    1
         :superseded  0
         :transaction 4
         :result      [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}}

C exports: stardust_db_query_subscribe, stardust_db_subscription_set_notify, stardust_db_subscription_error

Subscription::next

rust53 B
pub async fn next(&mut self) -> Result<Option<Event>>

Parameters

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

Errors

StatusWhen
Status::EVALUATION_FAILEDa rerun of the query failed. Every later call reports this failure
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

Await one owned event with any executor. Cancellation and closure return None. A failed rerun reports its native diagnostic. Dropping a pending future loses no event. Obtain a Canceller before borrowing the subscription for a wait. Use the executor's timeout or cancellation facilities to bound the wait.

Examples

subscription/next

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust260 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut subscription = query.subscribe(None, &RunOptions::default())?;
let event = subscription.next().await?.ok_or("no initial event")?;
let result = event.result;
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

C exports: stardust_db_subscription_next, stardust_db_subscription_error, stardust_document_release

Subscription::events

rust38 B
pub fn events(&mut self) -> Events<'_>

Parameters

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

Errors

Cancellation and closure end iteration. The iteration reports other terminal failures.

StatusWhen
Status::EVALUATION_FAILEDa rerun of the query failed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

Call events.next().await until None. Each event owns its result document. Cancellation and closure end the sequence. A query failure is returned once. Dropping the sequence early cancels the subscription. Drop or close the subscription to release its owner.

Examples

subscription/events

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust269 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut subscription = query.subscribe(None, &RunOptions::default())?;
let event = subscription.events().next().await.ok_or("no initial event")??;
let result = event.result;
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

C exports: stardust_db_subscription_next, stardust_db_subscription_error

Subscription::cancel

rust20 B
pub fn cancel(&self)

Parameters

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

Notes

Repeated cancellation is safe. Close the subscription separately to release its handle.

Examples

subscription/cancel

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust322 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut subscription = query.subscribe(None, &RunOptions::default())?;
let canceller = subscription.canceller();
let event = subscription.next().await?.ok_or("no initial event")?;
canceller.cancel();
let result = event.result;
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

C exports: stardust_db_subscription_cancel

Subscription::close

rust19 B
pub fn close(&self)

Consumes the receiver handle.

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfConsumed ownerRequiredThe subscription owner to release. Do not use it after this call.

Examples

subscription/close

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
rust282 B
let definition = stardust::parse(query_text, Format::EDN)?;
let query = db.query(&definition)?;
let mut subscription = query.subscribe(None, &RunOptions::default())?;
let event = subscription.next().await?.ok_or("no initial event")?;
let result = event.result;
subscription.close();
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

C exports: stardust_db_subscription_release

Mutation::run

rust166 B
pub fn run(
        &self,
        parameters: Option<&Document>,
        options: &RunOptions,
        explain: Option<&mut MutationExplain>,
    ) -> Result<Commit>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe mutation owner for this operation. Keep it alive during the call.
parametersOption<&Document>Borrowed for the callAbsent means no supplied parametersAn optional object of parameter values that merge-patches the definition's declared parameters. A parameter matched in the entity position of a fact clause takes an entity reference {#link id}, never the bare ID number: a commit returns IDs as numbers, so wrap one as {#link id}, or as the typed Link value where the binding has one, before passing it. A query run fails with entity_reference_expected when a bare number reaches that position. Projected and found entities also read back as {#link id}, so a typed field that receives one uses Link rather than a plain integer.
options&RunOptionsValueRequired options record. See field defaultsThe operation's options record. See its field defaults.
explainOption<&mut MutationExplain>Caller-owned outputAbsent skips explain outputOptional explain output. This record contains explain output for mutation run.

Errors

StatusWhen
Status::INVALID_DEFINITIONthe mutation selection or definition is invalid
Status::INVALID_ARGUMENTthe parameters or run options are invalid
Status::SCHEMA_VIOLATIONthe write breaks a schema
Status::CONFLICTconcurrent writes prevent the commit
Status::REJECTEDa mutation target or write guard refuses the write
Status::UNAVAILABLEthe patch sets stardust/history and no enabled plugin purges history
Status::EVALUATION_FAILEDthe mutation fails
Status::CLOSEDthe mutation is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

Mutation documents.

Examples

mutation/run

birthday_text holds this document:

edn82 B
{:query {:find  [?e]
         :where [[?e "name" "Ada"]]}
 :patch {:?e {:age 37}}}
rust160 B
let source = stardust::parse(birthday_text, Format::EDN)?;
let mutation = db.mutation(&source)?;
let result = mutation.run(None, &RunOptions::default(), None)?;
Result / 153 B
{:value {:status       "committed"
         :transaction  5
         :facts        1
         :committed_at 17923367691241152
         :ids          {}}}

Explain mutation execution

birthday_text holds this document:

edn82 B
{:query {:find  [?e]
         :where [[?e "name" "Ada"]]}
 :patch {:?e {:age 37}}}
rust239 B
let source = stardust::parse(birthday_text, Format::EDN)?;
let mutation = db.mutation(&source)?;
let mut explain = stardust::MutationExplain::default();
mutation.run(None, &RunOptions::default(), Some(&mut explain))?;
let result = explain;
Result / 649 B
{:value {:load_definition  {:cpu         3078
                            :wall        3092
                            :arena_bytes 2320}
         :parameters       {:cpu         34
                            :wall        44
                            :arena_bytes 0}
         :run              {:cpu         14526
                            :wall        44667
                            :arena_bytes 43856}
         :total            {:cpu         17795
                            :wall        47963
                            :arena_bytes 46176}
         :arena_capacity   4194304
         :stages_completed 3
         :attempts         1}}

C exports: stardust_db_mutation_run, stardust_db_result_commit_info, stardust_result_error, stardust_result_release

Mutation::close

rust18 B
pub fn close(self)

Consumes the receiver handle.

Parameters

ParameterTypeOwnershipDefaultMeaning
selfSelfConsumed ownerRequiredThe mutation owner to release. Do not use it after this call.

Examples

mutation/close

birthday_text holds this document:

edn82 B
{:query {:find  [?e]
         :where [[?e "name" "Ada"]]}
 :patch {:?e {:age 37}}}
rust178 B
let source = stardust::parse(birthday_text, Format::EDN)?;
let mutation = db.mutation(&source)?;
let result = mutation.run(None, &RunOptions::default(), None)?;
mutation.close();
Result / 153 B
{:value {:status       "committed"
         :transaction  5
         :facts        1
         :committed_at 17923367690415775
         :ids          {}}}

C exports: stardust_db_mutation_release

Database::merge_patch

rust128 B
pub fn merge_patch(
        &self,
        patch: &Document,
        explain: Option<&mut PatchExplain>,
    ) -> Result<Commit>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe database owner for this operation. Keep it alive during the call.
patch&DocumentBorrowed for the callRequiredAn entity-keyed native patch. Temporary names use #_name. #_tx holds metadata and an optional stardust/checkAndSet map from entity IDs to expected transactions. Positive expectations match exact last-touch transactions; zero requires no current facts. Conditions are consumed and checked atomically, including for no-ops.
explainOption<&mut PatchExplain>Caller-owned outputAbsent skips explain outputOptional explain output. This record contains explain output for merge_patch.

Errors

StatusWhen
Status::INVALID_COMMIT_TIMEthe #_tx commit time is not later than the last commit
Status::CONFLICTan entity revision check fails or a concurrent writer prevents the commit; a revision mismatch reports the entity and expected and actual revisions
Status::REJECTEDthe database refuses the patch; the code and diagnostic path name the reason and key
Status::UNAVAILABLEthe patch sets stardust/history and no enabled plugin purges history
Status::INVALID_ARGUMENTthe patch is not an entity-keyed object, or a link names an ID outside the user entity range
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

Patch documents.

Examples

database/merge_patch

seed_text holds this document:

edn287 B
{:#_ada {:name "Ada"
         :role "engineer"
         :age  36}
 :#_bob {:name   "Bob"
         :role   "engineer"
         :age    41
         :mentor {:#link "#_ada"}}
 :#_cy  {:name "Cy"
         :role "designer"
         :age  29}
 :#_tx  {:author "smoke"
         :reason "seed"}}
rust97 B
let patch = stardust::parse(seed_text, Format::EDN)?;
let result = db.merge_patch(&patch, None)?;
Result / 228 B
{:value {:status       "committed"
         :transaction  4
         :facts        12
         :committed_at 17923367685039269
         :ids          {:#_ada 1
                        :#_bob 2
                        :#_cy  3}}}

Explain patch validation and commit

seed_text holds this document:

edn287 B
{:#_ada {:name "Ada"
         :role "engineer"
         :age  36}
 :#_bob {:name   "Bob"
         :role   "engineer"
         :age    41
         :mentor {:#link "#_ada"}}
 :#_cy  {:name "Cy"
         :role "designer"
         :age  29}
 :#_tx  {:author "smoke"
         :reason "seed"}}
rust173 B
let patch = stardust::parse(seed_text, Format::EDN)?;
let mut explain = stardust::PatchExplain::default();
db.merge_patch(&patch, Some(&mut explain))?;
let result = explain;
Result / 484 B
{:value {:copy_patch       {:cpu         1735
                            :wall        1737
                            :arena_bytes 3096}
         :commit           {:cpu         654
                            :wall        35495
                            :arena_bytes 8008}
         :total            {:cpu         2517
                            :wall        37397
                            :arena_bytes 11118}
         :arena_capacity   4194304
         :stages_completed 2}}

Refuse a metadata-only transaction

patch_text holds this document:

edn21 B
{:#_tx {:author "x"}}
rust103 B
let patch = stardust::parse(patch_text, Format::EDN)?;
let result = db.merge_patch(&patch, None).err();
Result / 234 B
{:value {:code    "transaction_only"
         :message "a patch of only #_tx is refused: #_tx annotates a write"
         :path    "#_tx"
         :field   nil
         :entity  nil
         :offset  nil
         :status  "rejected"}}

Refuse a repeated commit time

future_text holds this document:

edn74 B
{:#_d  {:x 1}
 :#_tx {:stardust/committedAt #inst "2200-01-01T00:00:00Z"}}

older_text holds this document:

edn74 B
{:#_e  {:x 2}
 :#_tx {:stardust/committedAt #inst "2200-01-01T00:00:00Z"}}
rust192 B
let future = stardust::parse(future_text, Format::EDN)?;
db.merge_patch(&future, None)?;
let older = stardust::parse(older_text, Format::EDN)?;
let result = db.merge_patch(&older, None).err();
Result / 261 B
{:value {:code    "invalid_commit_time"
         :message "stardust/committedAt must be strictly newer than the latest commit time"
         :path    nil
         :field   nil
         :entity  nil
         :offset  nil
         :status  "invalid_commit_time"}}

C exports: stardust_db_merge_patch, stardust_db_result_commit_info, stardust_result_error, stardust_result_release

Database::indexes_sync

rust60 B
pub fn indexes_sync(&self, max_wait: Duration) -> Result<()>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe database owner for this operation. Keep it alive during the call.
max_waitDurationValueRequiredThe maximum wait. Zero checks once.

Errors

std::time::Duration cannot represent a negative max_wait. The safe host API cannot represent this argument. It makes no native call.

StatusWhen
Status::TIMEOUTmax_wait passed first
Status::CLOSEDthe database is closed

Notes

An index that cannot be built does not hold this wait.

Examples

Wait for the exact indexes of the stored queries

rust106 B
db.indexes_sync(std::time::Duration::from_secs(5))?;
let result = db.definitions("queries", "people/.*")?;
Result / 27 B
{:value ["people/by_role"]}

C exports: stardust_db_indexes_sync

Database::bulk_begin

rust38 B
pub fn bulk_begin(&self) -> Result<()>

Parameters

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

Errors

StatusWhen
Status::INVALID_ARGUMENTa bulk build is already in progress on the database
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

On a database with existing facts, each added patch commits immediately and the summary reports fallback true. Closing the database drops an unfinished build.

Examples

Start a bulk build and drop it

rust34 B
db.bulk_begin()?;
db.bulk_abort();

C exports: stardust_db_bulk_begin

Database::bulk_add

rust54 B
pub fn bulk_add(&self, patch: &Document) -> Result<()>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe database owner for this operation. Keep it alive during the call.
patch&DocumentBorrowed for the callRequiredOne borrowed entity-keyed merge-patch document, as merge_patch takes it. Temporary names use #_name and are scoped to this patch. Transaction metadata uses #_tx. The document is borrowed only until the call returns.

Errors

StatusWhen
Status::INVALID_ARGUMENTno bulk build is in progress
Status::REJECTEDthe database refuses the patch; the build has failed and later adds report the same status
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

Patches retain add order. Entity and field order within a patch does not matter. Temporary names resolve within one patch. The call waits for space within the build's memory budget. After failure, use finish for its diagnostic or abort for cleanup.

Patch documents.

Examples

Queue patches in commit order

rust360 B
db.bulk_begin()?;
// The first entity of an empty database is 1, so the second patch updates it.
// A failed add leaves the build for finish or abort; close also drops it.
db.bulk_add(&stardust::parse(r##"{"#_ada":{"name":"Ada"}}"##, Format::JSON)?)?;
db.bulk_add(&stardust::parse(r##"{"1":{"title":"Countess"}}"##, Format::JSON)?)?;
db.bulk_finish()?.close();

C exports: stardust_db_bulk_add

Database::bulk_finish

rust45 B
pub fn bulk_finish(&self) -> Result<Document>

Parameters

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

Errors

StatusWhen
Status::INVALID_ARGUMENTno bulk build is in progress
Status::REJECTEDthe database refuses a patch; an initial build publishes nothing and fallback keeps earlier commits
Status::CONFLICTanother write committed to the database during the build
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

Finish ends the build even on failure. An initial build publishes all patches or none. Fallback keeps patches already committed.

The summary contains:

FieldMeaning
statuscommitted, or no_change when nothing was written
patches, transactions, facts, entitiesLoad counts
firstTransaction, lastTransactionAssigned transaction range
fallbackWhether patches committed individually
threadsWorker count
tempBytesTemporary run bytes
memoryBytes, memoryPeakBytesReserved memory share and its peak use
phasesparse, assign, rows, updates, spill, build and commit timings, each with wallNs and cpuNs

The memory budget covers build allocations. It excludes operating-system file cache and the process baseline.

Examples

Load patches with one commit and read the summary

rust298 B
db.bulk_begin()?;
db.bulk_add(&stardust::parse(r##"{"#_ada":{"name":"Ada","title":"Countess"}}"##, Format::JSON)?)?;
// Finish ends the build also when it fails. The summary holds status,
// patches, transactions, facts, entities and phase timings.
let summary = db.bulk_finish()?;
summary.close();

C exports: stardust_db_bulk_finish, stardust_result_take_document, stardust_result_error, stardust_result_release

Database::bulk_abort

rust24 B
pub fn bulk_abort(&self)

Parameters

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

Notes

Abort preserves patches already committed in fallback mode. It is safe without a build or after database closure.

Examples

Drop a bulk build without writing it

rust210 B
let patch = stardust::parse(r##"{"#_ada":{"name":"Ada"}}"##, Format::JSON)?;
db.bulk_begin()?;
let added = db.bulk_add(&patch);
// Abort writes nothing; without a build it does nothing.
db.bulk_abort();
added?;

C exports: stardust_db_bulk_abort

run_options

This record supplies options for query and mutation run. Zero selects each default. Mutations use DB_Write_Options, whose fields are a subset.

FieldTypeUnitRangeMeaning
page_sizeu32CountHost type rangeRows per page. 0 selects the default page size. Queries only.
max_costDurationHost duration (100 ns ticks at the ABI)Tick rangeThread CPU duration limit. 0 selects the engine’s dynamic budget.
as_ofi64NoneHost type rangeA positive transaction runs a stored definition as of that transaction.

commit

This record contains the result of mutation run, merge_patch and patch_definition.

FieldTypeUnitRangeAbsentMeaning
statusCommitStatusNoneHost type range——
transactioni64NoneHost type range—Zero when nothing was written.
factsi64CountHost type range——
committed_atOption<SystemTime>UTC instant (100 ns ticks since the Unix epoch at the ABI)Tick rangeNoneRecorded commit time as a UTC instant. The call measures this value. Independent calls can differ.
idsHashMap<String, i64>NoneHost type range—Maps each #_name of a merge patch to its entity ID number. Wrap an ID as {#link id}, or as the typed Link value where the binding has one, to pass it as an entity reference.

event

This record contains the result of subscription next.

FieldTypeUnitMeaning
sequencei64CountEvent number. Event 1 is the initial result.
supersededi64CountIntermediate computed results skipped by this subscription since its previous event. Zero for its first event. The delivered result replaces them in full. This value counts neither commits nor changed rows.
transactioni64NoneTransaction the result was computed at.
resultDocumentNoneThe full query result. The event owns it and the consumer closes it.