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
birthdayText holds this document:
{:query {:find [?e]
:where [[?e "name" "Ada"]]}
:patch {:?e {:age 37}}}queryText holds this document:
{:find [?age]
:where [
[?e "name" "Ada"]
[?e "age" ?age]]}birthday, err := stardust.Parse(birthdayText, stardust.EDN)
if err != nil {
return err
}
defer birthday.Close()
mutation, err := db.Mutation(birthday)
if err != nil {
return err
}
defer mutation.Close()
if _, err := mutation.Run(nil, stardust.RunOptions{}, nil); err != nil {
return err
}
definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
rows, err := query.Run(nil, stardust.RunOptions{}, nil)
if err != nil {
return err
}
defer rows.Close()
result, err := rows.AllPages()
if err != nil {
return err
}
defer result.Close(){: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
| Operation | Returns | Summary |
|---|---|---|
| Database.ReadEntity | document | database.read_entity(entity, max_depth, max_entities) atomically returns an owned {document links revisions truncated} document, expanding links up to max_depth hops. |
| Database.Query | query | Open an owned query from a path or an inline definition. |
| Database.Mutation | mutation | Open an owned mutation from a path or an inline definition. |
| Query.Run | rows | Run the query and return an owned row cursor. |
| Query.Close | none | Release the query handle. |
| Rows.Next | document | Read the next page as an owned document. |
| Rows.Pages | pages | rows.pages() iterates the non-empty pages of the cursor. |
| Rows.AllPages | document | rows.all_pages() reads every remaining page into one owned array document. |
| Rows.Close | none | Release the rows handle. |
| Query.Subscribe | subscription | query.subscribe(parameters, options) opens an owned live subscription. |
| Subscription.Next | event | Wait for the next live event. |
| Subscription.All | events | subscription.events() delivers events in order until the subscription is cancelled, closes or fails. |
| Subscription.Cancel | none | subscription.cancel() ends the subscription. |
| Subscription.Close | none | Release the subscription handle. |
| Mutation.Run | commit | Run the mutation and return commit information. |
| Mutation.Close | none | Release the mutation handle. |
| Database.MergePatch | commit | database.merge_patch(patch) applies an entity-keyed patch document in one transaction and returns commit information. |
| Database.IndexesSync | none | database.indexes_sync(max_wait) waits until the database built every exact index that earlier definition commits and inline runs ask for. |
| Database.BulkBegin | none | database.bulk_begin() starts a bulk build of data merge patches held by the database. |
| Database.BulkAdd | none | database.bulk_add(patch) copies and queues one merge-patch document in the bulk build. |
| Database.BulkFinish | document | database.bulk_finish() publishes the bulk build with one commit, ends it and returns an owned summary document. |
| Database.BulkAbort | none | database.bulk_abort() drops the bulk build in progress without writing it. |
Database.ReadEntity
func (d *Database) ReadEntity(entity, maxDepth, maxEntities int64) (*Document, error)Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
entity | int64 | Value | Required | The decimal user entity ID. |
maxDepth | int64 | Value | Absent | Link hops to expand along each path, 0 through 32. 0, the default, leaves every link a {#link id} reference. |
maxEntities | int64 | Value | Absent | The 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
| Status | When |
|---|---|
StatusInvalidArgument | the entity ID is outside the user entity range, max_depth is negative or above 32, or max_entities is negative |
StatusClosed | the database is closed |
StatusOutOfMemory | native 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
result, err := db.ReadEntity(2, 1, 0)
if err != nil {
return err
}
defer result.Close(){: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
func (d *Database) Query(definition *Document) (*Query, error)func (d *Database) QueryPath(path string) (*Query, error)Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
definition | *Document | Borrowed for the call | Required | The inline native query definition copied into the query handle. |
path | string | Value | Required | The stored query definition path selected at run time. |
Errors
| Status | When |
|---|---|
StatusNotFound | no definition is stored at the path |
StatusInvalidDefinition | the definition is invalid |
StatusClosed | the database is closed |
StatusOutOfMemory | native memory is exhausted |
Notes
Inline definitions are copied. Stored paths select their definition at run time.
Examples
Open an inline query and read its first page
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
rows, err := query.Run(nil, stardust.RunOptions{}, nil)
if err != nil {
return err
}
defer rows.Close()
result, err := rows.Next()
if err != nil {
return err
}
defer result.Close(){:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}Refuse an invalid query definition
queryText holds this document:
{:find [?x]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, result := db.Query(definition)
if query != nil {
defer query.Close()
}{:value {:violations nil
:code "unbound_variable"
:message "Unbound_Variable"
:path nil
:field nil
:entity nil
:offset nil
:status "invalid_definition"}}Report a missing stored query
query, result := db.QueryPath("people/missing")
if query != nil {
defer query.Close()
}{:value {:violations nil
: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
func (d *Database) Mutation(definition *Document) (*Mutation, error)func (d *Database) MutationPath(path string) (*Mutation, error)Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
definition | *Document | Borrowed for the call | Required | The inline native mutation definition copied into the mutation handle. |
path | string | Value | Required | The stored mutation definition path selected at run time. |
Errors
| Status | When |
|---|---|
StatusNotFound | no definition is stored at the path |
StatusInvalidDefinition | the definition is invalid |
StatusClosed | the database is closed |
StatusOutOfMemory | native memory is exhausted |
Notes
Inline definitions are copied. Stored paths select their definition at run time.
Examples
database/mutation
birthdayText holds this document:
{:query {:find [?e]
:where [[?e "name" "Ada"]]}
:patch {:?e {:age 37}}}source, err := stardust.Parse(birthdayText, stardust.EDN)
if err != nil {
return err
}
defer source.Close()
mutation, err := db.Mutation(source)
if err != nil {
return err
}
defer mutation.Close()
result, err := mutation.Run(nil, stardust.RunOptions{}, nil)
if err != nil {
return err
}{:value {:status "committed"
:transaction 5
:facts 1
:committed_at 17928498215318271
:ids {}}}C exports: stardust_db_mutation_open, stardust_db_mutation_error
Query.Run
func (q *Query) Run(parameters *Document, options RunOptions, explain *QueryExplain) (*Rows, error)Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
parameters | *Document | Borrowed for the call | Absent means no supplied parameters | An 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 | RunOptions | Value | Required options record. See field defaults | The operation's options record. See its field defaults. |
explain | *QueryExplain | Caller-owned output | Absent skips explain output | Optional 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
| Status | When |
|---|---|
StatusNotFound | the stored query definition was deleted |
StatusInvalidDefinition | the loaded query definition is invalid |
StatusInvalidArgument | the parameters or run options are invalid |
StatusEvaluationFailed | the query fails, exceeds max_cost or exceeds its automatic work limit |
StatusClosed | the query is closed |
StatusOutOfMemory | native memory is exhausted |
Notes
Examples
Open an inline query and read its first page
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
rows, err := query.Run(nil, stardust.RunOptions{}, nil)
if err != nil {
return err
}
defer rows.Close()
result, err := rows.Next()
if err != nil {
return err
}
defer result.Close(){:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}Capture the host duration boundary
boundaryText holds this document:
9223372036854775800queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
boundary, err := stardust.Parse(boundaryText, stardust.EDN)
if err != nil {
return err
}
defer boundary.Close()
boundaryRoot, err := boundary.Root()
if err != nil {
return err
}
nanoseconds, err := boundary.I64(boundaryRoot)
if err != nil {
return err
}
result := stardust.RunOptions{PageSize: 2, MaxCost: time.Duration(nanoseconds)}
rows, err := query.Run(nil, result, nil)
if err != nil {
return err
}
defer rows.Close(){:value {:page_size 2
:max_cost 92233720368547758
:as_of 0}}Refuse a positive sub-tick duration
boundaryText holds this document:
99queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
boundary, err := stardust.Parse(boundaryText, stardust.EDN)
if err != nil {
return err
}
defer boundary.Close()
boundaryRoot, err := boundary.Root()
if err != nil {
return err
}
nanoseconds, err := boundary.I64(boundaryRoot)
if err != nil {
return err
}
rows, err := query.Run(nil, stardust.RunOptions{PageSize: 2, MaxCost: time.Duration(nanoseconds)}, nil)
if rows != nil {
defer rows.Close()
}
var result *stardust.Error
if !errors.As(err, &result) {
return err
}{:value {:violations nil
:code "inexact_number"
:message "The number has no exact form in the target type: duration requires whole 100 ns ticks"
:path nil
:field nil
:entity nil
:offset nil
:status "invalid_argument"}}Explain query execution
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
var result stardust.QueryExplain
rows, err := query.Run(nil, stardust.RunOptions{}, &result)
if err != nil {
return err
}
defer rows.Close(){:value {:load_definition {:cpu 48
:wall 55
:arena_bytes 1104}
:parameters {:cpu 4
:wall 4
:arena_bytes 0}
:run {:cpu 2973
:wall 2973
:arena_bytes 7440}
:total {:cpu 3045
:wall 3051
:arena_bytes 8544}
:arena_capacity 12288
:work 866
:rows 3
:compile 141
:plan 289
:execute 0
:group 0
:order 0
:memory_bytes 79
:memory_refusals 0
:budget_bytes 10489856512
:budget_used_bytes 159
:budget_peak_bytes 2985
:budget_refusals 0
:retry 0
:stages_completed 3
:retries 0}}A negative Go duration keeps its sign at the ABI boundary
result := stardust.RunOptions{MaxCost: -time.Nanosecond}{:value {:page_size 0
:max_cost -1
:as_of 0}}Run with typed query options
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
result := stardust.RunOptions{PageSize: 2, MaxCost: time.Second}
rows, err := query.Run(nil, result, nil)
if err != nil {
return err
}
defer rows.Close(){:value {:page_size 2
:max_cost 10000000
:as_of 0}}C exports: stardust_db_query_run, stardust_db_rows_error
Query.Close
func (q *Query) Close()Consumes the receiver handle.
Examples
Open an inline query and read its first page
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
rows, err := query.Run(nil, stardust.RunOptions{}, nil)
if err != nil {
return err
}
defer rows.Close()
result, err := rows.Next()
if err != nil {
return err
}
defer result.Close()
query.Close(){:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}C exports: stardust_db_query_release
Rows.Next
func (r *Rows) Next() (*Document, error)Errors
| Status | When |
|---|---|
StatusEvaluationFailed | the page does not render |
StatusClosed | the rows is closed |
StatusOutOfMemory | native 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
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
rows, err := query.Run(nil, stardust.RunOptions{}, nil)
if err != nil {
return err
}
defer rows.Close()
result, err := rows.Next()
if err != nil {
return err
}
defer result.Close(){: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
func (r *Rows) Pages() iter.Seq2[*Document, error]Errors
| Status | When |
|---|---|
StatusEvaluationFailed | a page does not render |
StatusClosed | the rows is closed |
StatusOutOfMemory | native 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
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
rows, err := query.Run(nil, stardust.RunOptions{PageSize: 1}, nil)
if err != nil {
return err
}
defer rows.Close()
result := 0
for page, err := range rows.Pages() {
if err != nil {
return err
}
if _, err := page.Count(); err != nil {
return err
}
result++
}{: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.AllPages
func (r *Rows) AllPages() (*Document, error)Errors
| Status | When |
|---|---|
StatusEvaluationFailed | a page does not render |
StatusClosed | the rows is closed |
StatusOutOfMemory | native 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
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
rows, err := query.Run(nil, stardust.RunOptions{PageSize: 1}, nil)
if err != nil {
return err
}
defer rows.Close()
result, err := rows.AllPages()
if err != nil {
return err
}
defer result.Close(){: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
func (r *Rows) Close()Consumes the receiver handle.
Examples
Open an inline query and read its first page
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
rows, err := query.Run(nil, stardust.RunOptions{}, nil)
if err != nil {
return err
}
defer rows.Close()
result, err := rows.Next()
if err != nil {
return err
}
defer result.Close()
rows.Close(){:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}C exports: stardust_db_rows_release
Query.Subscribe
func (q *Query) Subscribe(parameters *Document, options RunOptions) (*Subscription, error)Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
parameters | *Document | Borrowed for the call | Absent means no supplied parameters | An 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 | RunOptions | Value | Required options record. See field defaults | The operation's options record. See its field defaults. |
Errors
| Status | When |
|---|---|
StatusInvalidDefinition | the query or its callable definitions are invalid |
StatusInvalidArgument | the parameters or subscription options are invalid |
StatusClosed | the query is closed |
StatusOutOfMemory | native memory is exhausted |
Notes
The subscription copies its definition and parameters. Later definition edits do not change it. After its initial evaluation, only changes to fields its query can read schedule a rerun. Unknown dependencies include all fields. The page_size option is ignored.
Subscriptions register readiness callbacks automatically. Event waits use runtime notifications instead of blocking in the C ABI.
Examples
query/subscribe
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
subscription, err := query.Subscribe(nil, stardust.RunOptions{})
if err != nil {
return err
}
defer subscription.Close()
event, err := subscription.Next(ctx, 5*time.Second)
if err != nil {
return err
}
if event == nil {
return context.DeadlineExceeded
}
result := event.Result
defer result.Close(){:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}Read the complete initial subscription event
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
subscription, err := query.Subscribe(nil, stardust.RunOptions{})
if err != nil {
return err
}
defer subscription.Close()
result, err := subscription.Next(ctx, 5*time.Second)
if err != nil {
return err
}
if result == nil {
return context.DeadlineExceeded
}
defer result.Result.Close(){: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
func (s *Subscription) Next(ctx context.Context, maxWait time.Duration) (*Event, error)Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
ctx | context.Context | Value | Required | Context controlling cancellation of the call. |
maxWait | time.Duration | Value | Required | The maximum wait. Zero checks once. |
Errors
| Status | When |
|---|---|
StatusInvalidArgument | max_wait is negative |
StatusCancelled | the subscription is cancelled or closed |
StatusEvaluationFailed | a rerun of the query failed. Every later call reports this failure |
StatusClosed | the subscription is closed |
StatusOutOfMemory | native memory is exhausted |
Notes
Each event replaces the entire result. superseded counts skipped computed results, not commits. Cancel, close and database close wake blocked waits. Windows rounds deadlines to milliseconds.
Examples
subscription/next
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
subscription, err := query.Subscribe(nil, stardust.RunOptions{})
if err != nil {
return err
}
defer subscription.Close()
event, err := subscription.Next(ctx, 5*time.Second)
if err != nil {
return err
}
if event == nil {
return context.DeadlineExceeded
}
result := event.Result
defer result.Close(){:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}C exports: stardust_db_subscription_next, stardust_db_subscription_error, stardust_document_release
Subscription.All
func (s *Subscription) All(ctx context.Context) iter.Seq2[*Event, error]Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
ctx | context.Context | Value | Required | Context controlling cancellation of the call. |
Errors
Cancellation and closure end iteration. The iteration reports other terminal failures.
| Status | When |
|---|---|
StatusEvaluationFailed | a rerun of the query failed |
StatusOutOfMemory | native memory is exhausted |
Notes
The consumer owns each result. Leaving iteration early cancels the subscription. Close the subscription separately.
Examples
subscription/events
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
subscription, err := query.Subscribe(nil, stardust.RunOptions{})
if err != nil {
return err
}
defer subscription.Close()
var result *stardust.Document
for event, err := range subscription.All(context.Background()) {
if err != nil {
return err
}
result = event.Result
break
}
defer result.Close(){:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}C exports: stardust_db_subscription_next, stardust_db_subscription_error
Subscription.Cancel
func (s *Subscription) Cancel()Notes
Repeated cancellation is safe. Close the subscription separately to release its handle.
Examples
subscription/cancel
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
subscription, err := query.Subscribe(nil, stardust.RunOptions{})
if err != nil {
return err
}
defer subscription.Close()
event, err := subscription.Next(ctx, 5*time.Second)
if err != nil {
return err
}
if event == nil {
return context.DeadlineExceeded
}
subscription.Cancel()
result := event.Result
defer result.Close(){:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}C exports: stardust_db_subscription_cancel
Subscription.Close
func (s *Subscription) Close()Consumes the receiver handle.
Examples
subscription/close
queryText holds this document:
{:find [?name]
:where [[?e "name" ?name]]
:orderBy [?name]}definition, err := stardust.Parse(queryText, stardust.EDN)
if err != nil {
return err
}
defer definition.Close()
query, err := db.Query(definition)
if err != nil {
return err
}
defer query.Close()
subscription, err := query.Subscribe(nil, stardust.RunOptions{})
if err != nil {
return err
}
defer subscription.Close()
event, err := subscription.Next(ctx, 5*time.Second)
if err != nil {
return err
}
if event == nil {
return context.DeadlineExceeded
}
result := event.Result
defer result.Close()
subscription.Close(){:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}C exports: stardust_db_subscription_release
Mutation.Run
func (m *Mutation) Run(parameters *Document, options RunOptions, explain *MutationExplain) (Commit, error)Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
parameters | *Document | Borrowed for the call | Absent means no supplied parameters | An 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 | RunOptions | Value | Required options record. See field defaults | The operation's options record. See its field defaults. |
explain | *MutationExplain | Caller-owned output | Absent skips explain output | Optional explain output. This record contains explain output for mutation run. |
Errors
| Status | When |
|---|---|
StatusInvalidDefinition | the mutation selection or definition is invalid |
StatusInvalidArgument | the parameters or run options are invalid, or a required parameter has no value |
StatusSchemaViolation | the write breaks a schema |
StatusConflict | concurrent writes prevent the commit |
StatusRejected | a mutation target or write guard refuses the write |
StatusUnavailable | the patch sets stardust/history and no enabled plugin purges history |
StatusEvaluationFailed | the mutation fails |
StatusFailed | a reactor fails; the initiating write and all derived changes are rolled back |
StatusClosed | the mutation is closed |
StatusOutOfMemory | native memory is exhausted |
Notes
Examples
mutation/run
birthdayText holds this document:
{:query {:find [?e]
:where [[?e "name" "Ada"]]}
:patch {:?e {:age 37}}}source, err := stardust.Parse(birthdayText, stardust.EDN)
if err != nil {
return err
}
defer source.Close()
mutation, err := db.Mutation(source)
if err != nil {
return err
}
defer mutation.Close()
result, err := mutation.Run(nil, stardust.RunOptions{}, nil)
if err != nil {
return err
}{:value {:status "committed"
:transaction 5
:facts 1
:committed_at 17928498219814846
:ids {}}}Explain mutation execution
birthdayText holds this document:
{:query {:find [?e]
:where [[?e "name" "Ada"]]}
:patch {:?e {:age 37}}}source, err := stardust.Parse(birthdayText, stardust.EDN)
if err != nil {
return err
}
defer source.Close()
mutation, err := db.Mutation(source)
if err != nil {
return err
}
defer mutation.Close()
var result stardust.MutationExplain
if _, err := mutation.Run(nil, stardust.RunOptions{}, &result); err != nil {
return err
}{:value {:load_definition {:cpu 750
:wall 754
:arena_bytes 1744}
:parameters {:cpu 8
:wall 9
:arena_bytes 0}
:run {:cpu 10109
:wall 33760
:arena_bytes 43984}
:total {:cpu 10967
:wall 34625
:arena_bytes 45728}
: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
func (m *Mutation) Close()Consumes the receiver handle.
Examples
mutation/close
birthdayText holds this document:
{:query {:find [?e]
:where [[?e "name" "Ada"]]}
:patch {:?e {:age 37}}}source, err := stardust.Parse(birthdayText, stardust.EDN)
if err != nil {
return err
}
defer source.Close()
mutation, err := db.Mutation(source)
if err != nil {
return err
}
defer mutation.Close()
result, err := mutation.Run(nil, stardust.RunOptions{}, nil)
if err != nil {
return err
}
mutation.Close(){:value {:status "committed"
:transaction 5
:facts 1
:committed_at 17928498219205432
:ids {}}}C exports: stardust_db_mutation_release
Database.MergePatch
func (d *Database) MergePatch(patch *Document, explain *PatchExplain) (Commit, error)Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
patch | *Document | Borrowed for the call | Required | An 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. |
explain | *PatchExplain | Caller-owned output | Absent skips explain output | Optional explain output. This record contains explain output for merge_patch. |
Errors
| Status | When |
|---|---|
StatusInvalidCommitTime | the #_tx commit time is not later than the last commit |
StatusConflict | an entity revision check fails or a concurrent writer prevents the commit; a revision mismatch reports the entity and expected and actual revisions |
StatusRejected | the database refuses the patch; the code and diagnostic path name the reason and key |
StatusFailed | a reactor fails; the initiating write and all derived changes are rolled back |
StatusUnavailable | the patch sets stardust/history and no enabled plugin purges history |
StatusInvalidArgument | the patch is not an entity-keyed object, or a link names an ID outside the user entity range |
StatusClosed | the database is closed |
StatusOutOfMemory | native memory is exhausted |
Notes
Examples
database/merge_patch
patchText holds this document:
{:#_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"}}patch, err := stardust.Parse(patchText, stardust.EDN)
if err != nil {
return err
}
defer patch.Close()
result, err := db.MergePatch(patch, nil)
if err != nil {
return err
}{:value {:status "committed"
:transaction 4
:facts 12
:committed_at 17928498213555167
:ids {:#_ada 1
:#_bob 2
:#_cy 3}}}Explain patch validation and commit
patchText holds this document:
{:#_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"}}patch, err := stardust.Parse(patchText, stardust.EDN)
if err != nil {
return err
}
defer patch.Close()
var result stardust.PatchExplain
if _, err := db.MergePatch(patch, &result); err != nil {
return err
}{:value {:copy_patch {:cpu 451
:wall 454
:arena_bytes 2520}
:commit {:cpu 197
:wall 33292
:arena_bytes 10056}
:total {:cpu 706
:wall 33805
:arena_bytes 12590}
:arena_capacity 4194304
:stages_completed 2}}Refuse a metadata-only transaction
patchText holds this document:
{:#_tx {:author "x"}}patch, err := stardust.Parse(patchText, stardust.EDN)
if err != nil {
return err
}
defer patch.Close()
_, result := db.MergePatch(patch, nil){:value {:violations nil
: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
futureText holds this document:
{:#_d {:x 1}
:#_tx {:stardust/committedAt #inst "2200-01-01T00:00:00Z"}}patchText holds this document:
{:#_e {:x 2}
:#_tx {:stardust/committedAt #inst "2200-01-01T00:00:00Z"}}future, err := stardust.Parse(futureText, stardust.EDN)
if err != nil {
return err
}
defer future.Close()
if _, err := db.MergePatch(future, nil); err != nil {
return err
}
patch, err := stardust.Parse(patchText, stardust.EDN)
if err != nil {
return err
}
defer patch.Close()
_, result := db.MergePatch(patch, nil){:value {:violations nil
: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.IndexesSync
func (d *Database) IndexesSync(maxWait time.Duration) errorParameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
maxWait | time.Duration | Value | Required | The maximum wait. Zero checks once. |
Errors
| Status | When |
|---|---|
StatusInvalidArgument | max_wait is negative |
StatusTimeout | max_wait passed first |
StatusClosed | the 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
if err := db.IndexesSync(5 * time.Second); err != nil {
return err
}
result, err := db.Definitions(stardust.Queries, "people/.*")
if err != nil {
return err
}
defer result.Close(){:value ["people/by_role"]}C exports: stardust_db_indexes_sync
Database.BulkBegin
func (d *Database) BulkBegin() errorErrors
| Status | When |
|---|---|
StatusInvalidArgument | a bulk build is already in progress on the database |
StatusClosed | the database is closed |
StatusOutOfMemory | native 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
if err := db.BulkBegin(); err != nil {
return err
}
db.BulkAbort()C exports: stardust_db_bulk_begin
Database.BulkAdd
func (d *Database) BulkAdd(patch *Document) errorParameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
patch | *Document | Borrowed for the call | Required | One 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
| Status | When |
|---|---|
StatusInvalidArgument | no bulk build is in progress |
StatusFailed | a reactor fails while committing this patch; earlier fallback patches remain committed |
StatusRejected | the database refuses the patch; the build has failed and later adds report the same status |
StatusClosed | the database is closed |
StatusOutOfMemory | native 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.
Examples
Queue patches in commit order
if err := db.BulkBegin(); err != nil {
return err
}
defer db.BulkAbort()
// The first entity of an empty database is 1, so the second patch updates it.
for _, patch := range []string{`{"#_ada":{"name":"Ada"}}`, `{"1":{"title":"Countess"}}`} {
document, err := stardust.Parse([]byte(patch), stardust.JSON)
if err != nil {
return err
}
err = db.BulkAdd(document)
document.Close()
if err != nil {
return err
}
}
summary, err := db.BulkFinish()
if err != nil {
return err
}
summary.Close()C exports: stardust_db_bulk_add
Database.BulkFinish
func (d *Database) BulkFinish() (*Document, error)Errors
| Status | When |
|---|---|
StatusInvalidArgument | no bulk build is in progress |
StatusRejected | the database refuses a patch; an initial build publishes nothing and fallback keeps earlier commits |
StatusFailed | a reactor failed while adding a fallback patch; earlier patches remain committed |
StatusConflict | another write committed to the database during the build |
StatusClosed | the database is closed |
StatusOutOfMemory | native 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:
| Field | Meaning |
|---|---|
| status | committed, or no_change when nothing was written |
| patches, transactions, facts, entities | Load counts |
| firstTransaction, lastTransaction | Assigned transaction range |
| fallback | Whether patches committed individually |
| threads | Worker count |
| tempBytes | Temporary run bytes |
| memoryBytes, memoryPeakBytes | Reserved memory share and its peak use |
| phases | parse, 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
if err := db.BulkBegin(); err != nil {
return err
}
defer db.BulkAbort()
patch, err := stardust.Parse([]byte(`{"#_ada":{"name":"Ada","title":"Countess"}}`), stardust.JSON)
if err != nil {
return err
}
defer patch.Close()
if err := db.BulkAdd(patch); err != nil {
return err
}
// Finish ends the build also when it fails.
summary, err := db.BulkFinish()
if err != nil {
return err
}
defer summary.Close()
// summary holds status, patches, transactions, facts, entities and phase timings.C exports: stardust_db_bulk_finish, stardust_result_take_document, stardust_result_error, stardust_result_release
Database.BulkAbort
func (d *Database) BulkAbort()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
if err := db.BulkBegin(); err != nil {
return err
}
// Abort writes nothing; without a build it does nothing.
defer db.BulkAbort()
patch, err := stardust.Parse([]byte(`{"#_ada":{"name":"Ada"}}`), stardust.JSON)
if err != nil {
return err
}
defer patch.Close()
if err := db.BulkAdd(patch); err != nil {
return err
}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.
| Field | Type | Unit | Range | Meaning |
|---|---|---|---|---|
page_size | int64 | Count | Host type range | Rows per page. 0 selects the default page size. Queries only. A negative value causes invalid_argument. |
max_cost | time.Duration | Host duration (100 ns ticks at the ABI) | Tick range | Thread CPU duration limit in whole 100 ns ticks. The engine’s automatic work limit always applies as well; 0 adds no CPU limit and a negative value causes invalid_argument. |
as_of | int64 | None | Host type range | A positive transaction runs a stored definition as of that transaction. |
commit
This record contains the result of mutation run, merge_patch and patch_definition.
| Field | Type | Unit | Range | Absent | Meaning |
|---|---|---|---|---|---|
status | CommitStatus | None | Host type range | — | — |
transaction | int64 | None | Host type range | — | Zero when nothing was written. |
facts | int64 | Count | Host type range | — | — |
committed_at | time.Time | UTC instant (100 ns ticks since the Unix epoch at the ABI) | Tick range | The zero time.Time | Recorded commit time as a UTC instant. The call measures this value. Independent calls can differ. |
ids | map[string]int64 | None | Host type range | — | Maps each #_name of a merge patch or mutation 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.
| Field | Type | Unit | Meaning |
|---|---|---|---|
sequence | int64 | Count | Event number. Event 1 is the initial result. |
superseded | int64 | Count | Intermediate 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. |
transaction | int64 | None | Transaction the result was computed at. |
result | *Document | None | The full query result. The event owns it and the consumer closes it. |