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:

dust68 B
query {find  [?e]
       where [[?e name Ada]]}
patch {?e {age 37}}

queryText holds this document:

dust56 B
find  [?age]
where [[?e name Ada]
       [?e age ?age]]
go685 B
birthday, err := stardust.Parse(birthdayText, stardust.DUST)
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.DUST)
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()
Result / 10 B
[{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.ReadEntitydocumentdatabase.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.NextdocumentRead the next page as an owned document.
Rows.Pagespagesrows.pages() iterates the non-empty pages of the cursor.
Rows.AllPagesdocumentrows.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.Alleventssubscription.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.MergePatchcommitdatabase.merge_patch(patch) applies an entity-keyed patch document in one transaction and returns commit information.
Database.IndexesSyncnonedatabase.indexes_sync(max_wait) waits until the database built every exact index that earlier definition commits and inline runs ask for.
Database.BulkBeginnonedatabase.bulk_begin() starts a bulk build of data merge patches held by the database.
Database.BulkAddnonedatabase.bulk_add(patch) copies and queues one merge-patch document in the bulk build.
Database.BulkFinishdocumentdatabase.bulk_finish() publishes the bulk build with one commit, ends it and returns an owned summary document.
Database.BulkAbortnonedatabase.bulk_abort() drops the bulk build in progress without writing it.

Database.ReadEntity

go85 B
func (d *Database) ReadEntity(entity, maxDepth, maxEntities int64) (*Document, error)

Parameters

ParameterTypeOwnershipDefaultMeaning
entityint64ValueRequiredThe decimal user entity ID.
maxDepthint64ValueAbsentLink hops to expand along each path, 0 through 32. 0, the default, leaves every link a {#link id} reference.
maxEntitiesint64ValueAbsentThe 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
StatusInvalidArgumentthe entity ID is outside the user entity range, max_depth is negative or above 32, or max_entities is negative
StatusClosedthe database is closed
StatusOutOfMemorynative 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

go88 B
result, err := db.ReadEntity(2, 1, 0)
if err != nil {
	return err
}
defer result.Close()
Result / 247 B
{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

go62 B
func (d *Database) Query(definition *Document) (*Query, error)
go57 B
func (d *Database) QueryPath(path string) (*Query, error)

Parameters

ParameterTypeOwnershipDefaultMeaning
definition*DocumentBorrowed for the callRequiredThe inline native query definition copied into the query handle.
pathstringValueRequiredThe stored query definition path selected at run time.

Errors

StatusWhen
StatusNotFoundno definition is stored at the path
StatusInvalidDefinitionthe definition is invalid
StatusClosedthe database is closed
StatusOutOfMemorynative 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

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go385 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 33 B
[{name Ada} {name Bob} {name Cy}]

Refuse an invalid query definition

queryText holds this document:

dust10 B
find [?x]
go194 B
definition, err := stardust.Parse(queryText, stardust.DUST)
if err != nil {
	return err
}
defer definition.Close()

query, result := db.Query(definition)
if query != nil {
	defer query.Close()
}
Result / 174 B
{violations null
 code       unbound_variable
 message    Unbound_Variable
 path       null
 field      null
 entity     null
 offset     null
 status     invalid_definition}

Report a missing stored query

go88 B
query, result := db.QueryPath("people/missing")
if query != nil {
	defer query.Close()
}
Result / 178 B
{violations null
 code       not_found
 message    no definition at this path
 path       people/missing
 field      null
 entity     null
 offset     null
 status     not_found}

C exports: stardust_db_query_open, stardust_db_query_error

Database.Mutation

go68 B
func (d *Database) Mutation(definition *Document) (*Mutation, error)
go63 B
func (d *Database) MutationPath(path string) (*Mutation, error)

Parameters

ParameterTypeOwnershipDefaultMeaning
definition*DocumentBorrowed for the callRequiredThe inline native mutation definition copied into the mutation handle.
pathstringValueRequiredThe stored mutation definition path selected at run time.

Errors

StatusWhen
StatusNotFoundno definition is stored at the path
StatusInvalidDefinitionthe definition is invalid
StatusClosedthe database is closed
StatusOutOfMemorynative memory is exhausted

Notes

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

Mutation documents.

Examples

database/mutation

birthdayText holds this document:

dust68 B
query {find  [?e]
       where [[?e name Ada]]}
patch {?e {age 37}}
go292 B
source, err := stardust.Parse(birthdayText, stardust.DUST)
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
}
Result / 105 B
{status       committed
 transaction  5
 facts        1
 committed_at 17928498214997826
 ids          {}}

C exports: stardust_db_mutation_open, stardust_db_mutation_error

Query.Run

go99 B
func (q *Query) Run(parameters *Document, options RunOptions, explain *QueryExplain) (*Rows, error)

Parameters

ParameterTypeOwnershipDefaultMeaning
parameters*DocumentBorrowed 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.
optionsRunOptionsValueRequired options record. See field defaultsThe operation's options record. See its field defaults.
explain*QueryExplainCaller-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
StatusNotFoundthe stored query definition was deleted
StatusInvalidDefinitionthe loaded query definition is invalid
StatusInvalidArgumentthe parameters or run options are invalid
StatusEvaluationFailedthe query fails, exceeds max_cost or exceeds its automatic work limit
StatusClosedthe query is closed
StatusOutOfMemorynative memory is exhausted

Notes

Query documents.

Examples

Open an inline query and read its first page

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go385 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 33 B
[{name Ada} {name Bob} {name Cy}]

Capture the host duration boundary

boundaryText holds this document:

dust20 B
9223372036854775800

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go631 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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.DUST)
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()
Result / 55 B
{page_size 2
 max_cost  92233720368547758
 as_of     0}

Refuse a positive sub-tick duration

boundaryText holds this document:

dust3 B
99

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go676 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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.DUST)
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
}
Result / 239 B
{violations null
 code       inexact_number
 message    The number has no exact form in the target type: duration requires whole 100 ns ticks
 path       null
 field      null
 entity     null
 offset     null
 status     invalid_argument}

Explain query execution

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go343 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 818 B
{load_definition   {cpu         57
                    wall        62
                    arena_bytes 1104}
 parameters        {cpu         5
                    wall        6
                    arena_bytes 0}
 run               {cpu         3112
                    wall        3157
                    arena_bytes 7440}
 total             {cpu         3195
                    wall        3244
                    arena_bytes 8544}
 arena_capacity    12288
 work              955
 rows              3
 compile           176
 plan              313
 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

go56 B
result := stardust.RunOptions{MaxCost: -time.Nanosecond}
Result / 40 B
{page_size 0
 max_cost  -1
 as_of     0}

Run with typed query options

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go356 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 46 B
{page_size 2
 max_cost  10000000
 as_of     0}

C exports: stardust_db_query_run, stardust_db_rows_error

Query.Close

go23 B
func (q *Query) Close()

Consumes the receiver handle.

Examples

Open an inline query and read its first page

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go400 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 33 B
[{name Ada} {name Bob} {name Cy}]

C exports: stardust_db_query_release

Rows.Next

go40 B
func (r *Rows) Next() (*Document, error)

Errors

StatusWhen
StatusEvaluationFailedthe page does not render
StatusClosedthe rows is closed
StatusOutOfMemorynative 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:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go385 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 33 B
[{name Ada} {name Bob} {name Cy}]

C exports: stardust_db_rows_next, stardust_result_take_document, stardust_result_error, stardust_result_release

Rows.Pages

go50 B
func (r *Rows) Pages() iter.Seq2[*Document, error]

Errors

StatusWhen
StatusEvaluationFaileda page does not render
StatusClosedthe rows is closed
StatusOutOfMemorynative 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:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go470 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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++
}
Result / 1 B
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

go44 B
func (r *Rows) AllPages() (*Document, error)

Errors

StatusWhen
StatusEvaluationFaileda page does not render
StatusClosedthe rows is closed
StatusOutOfMemorynative 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:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go400 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 33 B
[{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

go22 B
func (r *Rows) Close()

Consumes the receiver handle.

Examples

Open an inline query and read its first page

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go399 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 33 B
[{name Ada} {name Bob} {name Cy}]

C exports: stardust_db_rows_release

Query.Subscribe

go90 B
func (q *Query) Subscribe(parameters *Document, options RunOptions) (*Subscription, error)

Parameters

ParameterTypeOwnershipDefaultMeaning
parameters*DocumentBorrowed 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.
optionsRunOptionsValueRequired options record. See field defaultsThe operation's options record. See its field defaults.

Errors

StatusWhen
StatusInvalidDefinitionthe query or its callable definitions are invalid
StatusInvalidArgumentthe parameters or subscription options are invalid
StatusClosedthe query is closed
StatusOutOfMemorynative 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.

Query documents.

Examples

query/subscribe

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go505 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 33 B
[{name Ada} {name Bob} {name Cy}]

Read the complete initial subscription event

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go491 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 92 B
{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

go87 B
func (s *Subscription) Next(ctx context.Context, maxWait time.Duration) (*Event, error)

Parameters

ParameterTypeOwnershipDefaultMeaning
ctxcontext.ContextValueRequiredContext controlling cancellation of the call.
maxWaittime.DurationValueRequiredThe maximum wait. Zero checks once.

Errors

StatusWhen
StatusInvalidArgumentmax_wait is negative
StatusCancelledthe subscription is cancelled or closed
StatusEvaluationFaileda rerun of the query failed. Every later call reports this failure
StatusClosedthe subscription is closed
StatusOutOfMemorynative 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:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go505 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 33 B
[{name Ada} {name Bob} {name Cy}]

C exports: stardust_db_subscription_next, stardust_db_subscription_error, stardust_document_release

Subscription.All

go72 B
func (s *Subscription) All(ctx context.Context) iter.Seq2[*Event, error]

Parameters

ParameterTypeOwnershipDefaultMeaning
ctxcontext.ContextValueRequiredContext controlling cancellation of the call.

Errors

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

StatusWhen
StatusEvaluationFaileda rerun of the query failed
StatusOutOfMemorynative 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:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go505 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 33 B
[{name Ada} {name Bob} {name Cy}]

C exports: stardust_db_subscription_next, stardust_db_subscription_error

Subscription.Cancel

go31 B
func (s *Subscription) Cancel()

Notes

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

Examples

subscription/cancel

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go528 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 33 B
[{name Ada} {name Bob} {name Cy}]

C exports: stardust_db_subscription_cancel

Subscription.Close

go30 B
func (s *Subscription) Close()

Consumes the receiver handle.

Examples

subscription/close

queryText holds this document:

dust58 B
find    [?name]
where   [[?e name ?name]]
orderBy [?name]
go527 B
definition, err := stardust.Parse(queryText, stardust.DUST)
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()
Result / 33 B
[{name Ada} {name Bob} {name Cy}]

C exports: stardust_db_subscription_release

Mutation.Run

go106 B
func (m *Mutation) Run(parameters *Document, options RunOptions, explain *MutationExplain) (Commit, error)

Parameters

ParameterTypeOwnershipDefaultMeaning
parameters*DocumentBorrowed 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.
optionsRunOptionsValueRequired options record. See field defaultsThe operation's options record. See its field defaults.
explain*MutationExplainCaller-owned outputAbsent skips explain outputOptional explain output. This record contains explain output for mutation run.

Errors

StatusWhen
StatusInvalidDefinitionthe mutation selection or definition is invalid
StatusInvalidArgumentthe parameters or run options are invalid, or a required parameter has no value
StatusSchemaViolationthe write breaks a schema
StatusConflictconcurrent writes prevent the commit
StatusRejecteda mutation target or write guard refuses the write
StatusUnavailablethe patch sets stardust/history and no enabled plugin purges history
StatusEvaluationFailedthe mutation fails
StatusFaileda reactor fails; the initiating write and all derived changes are rolled back
StatusClosedthe mutation is closed
StatusOutOfMemorynative memory is exhausted

Notes

Mutation documents.

Examples

mutation/run

birthdayText holds this document:

dust68 B
query {find  [?e]
       where [[?e name Ada]]}
patch {?e {age 37}}
go292 B
source, err := stardust.Parse(birthdayText, stardust.DUST)
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
}
Result / 105 B
{status       committed
 transaction  5
 facts        1
 committed_at 17928498219511057
 ids          {}}

Explain mutation execution

birthdayText holds this document:

dust68 B
query {find  [?e]
       where [[?e name Ada]]}
patch {?e {age 37}}
go328 B
source, err := stardust.Parse(birthdayText, stardust.DUST)
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
}
Result / 499 B
{load_definition  {cpu         1051
                   wall        1054
                   arena_bytes 1744}
 parameters       {cpu         6
                   wall        8
                   arena_bytes 0}
 run              {cpu         16730
                   wall        47999
                   arena_bytes 43984}
 total            {cpu         17874
                   wall        49150
                   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

go26 B
func (m *Mutation) Close()

Consumes the receiver handle.

Examples

mutation/close

birthdayText holds this document:

dust68 B
query {find  [?e]
       where [[?e name Ada]]}
patch {?e {age 37}}
go309 B
source, err := stardust.Parse(birthdayText, stardust.DUST)
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()
Result / 105 B
{status       committed
 transaction  5
 facts        1
 committed_at 17928498218882243
 ids          {}}

C exports: stardust_db_mutation_release

Database.MergePatch

go85 B
func (d *Database) MergePatch(patch *Document, explain *PatchExplain) (Commit, error)

Parameters

ParameterTypeOwnershipDefaultMeaning
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.
explain*PatchExplainCaller-owned outputAbsent skips explain outputOptional explain output. This record contains explain output for merge_patch.

Errors

StatusWhen
StatusInvalidCommitTimethe #_tx commit time is not later than the last commit
StatusConflictan entity revision check fails or a concurrent writer prevents the commit; a revision mismatch reports the entity and expected and actual revisions
StatusRejectedthe database refuses the patch; the code and diagnostic path name the reason and key
StatusFaileda reactor fails; the initiating write and all derived changes are rolled back
StatusUnavailablethe patch sets stardust/history and no enabled plugin purges history
StatusInvalidArgumentthe patch is not an entity-keyed object, or a link names an ID outside the user entity range
StatusClosedthe database is closed
StatusOutOfMemorynative memory is exhausted

Notes

Patch documents.

Examples

database/merge_patch

patchText holds this document:

dust232 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}
go176 B
patch, err := stardust.Parse(patchText, stardust.DUST)
if err != nil {
	return err
}
defer patch.Close()

result, err := db.MergePatch(patch, nil)
if err != nil {
	return err
}
Result / 159 B
{status       committed
 transaction  4
 facts        12
 committed_at 17928498213356295
 ids          {#_ada 1
               #_bob 2
               #_cy  3}}

Explain patch validation and commit

patchText holds this document:

dust232 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}
go209 B
patch, err := stardust.Parse(patchText, stardust.DUST)
if err != nil {
	return err
}
defer patch.Close()

var result stardust.PatchExplain
if _, err := db.MergePatch(patch, &result); err != nil {
	return err
}
Result / 373 B
{copy_patch       {cpu         392
                   wall        402
                   arena_bytes 2520}
 commit           {cpu         187
                   wall        28880
                   arena_bytes 10056}
 total            {cpu         645
                   wall        29350
                   arena_bytes 12590}
 arena_capacity   4194304
 stages_completed 2}

Refuse a metadata-only transaction

patchText holds this document:

dust16 B
#_tx {author x}
go144 B
patch, err := stardust.Parse(patchText, stardust.DUST)
if err != nil {
	return err
}
defer patch.Close()

_, result := db.MergePatch(patch, nil)
Result / 203 B
{violations null
 code       transaction_only
 message    a patch of only #_tx is refused: #_tx annotates a write
 path       #_tx
 field      null
 entity     null
 offset     null
 status     rejected}

Refuse a repeated commit time

futureText holds this document:

dust67 B
#_d  {x 1}
#_tx {stardust/committedAt {#utc 2200-01-01T00:00:00Z}}

patchText holds this document:

dust67 B
#_e  {x 2}
#_tx {stardust/committedAt {#utc 2200-01-01T00:00:00Z}}
go322 B
future, err := stardust.Parse(futureText, stardust.DUST)
if err != nil {
	return err
}
defer future.Close()

if _, err := db.MergePatch(future, nil); err != nil {
	return err
}

patch, err := stardust.Parse(patchText, stardust.DUST)
if err != nil {
	return err
}
defer patch.Close()

_, result := db.MergePatch(patch, nil)
Result / 233 B
{violations null
 code       invalid_commit_time
 message    stardust/committedAt must be strictly newer than the latest commit time
 path       null
 field      null
 entity     null
 offset     null
 status     invalid_commit_time}

C exports: stardust_db_merge_patch, stardust_db_result_commit_info, stardust_result_error, stardust_result_release

Database.IndexesSync

go59 B
func (d *Database) IndexesSync(maxWait time.Duration) error

Parameters

ParameterTypeOwnershipDefaultMeaning
maxWaittime.DurationValueRequiredThe maximum wait. Zero checks once.

Errors

StatusWhen
StatusInvalidArgumentmax_wait is negative
StatusTimeoutmax_wait passed first
StatusClosedthe 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

go182 B
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()
Result / 16 B
[people/by_role]

C exports: stardust_db_indexes_sync

Database.BulkBegin

go36 B
func (d *Database) BulkBegin() error

Errors

StatusWhen
StatusInvalidArgumenta bulk build is already in progress on the database
StatusClosedthe database is closed
StatusOutOfMemorynative 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

go67 B
if err := db.BulkBegin(); err != nil {
	return err
}
db.BulkAbort()

C exports: stardust_db_bulk_begin

Database.BulkAdd

go49 B
func (d *Database) BulkAdd(patch *Document) error

Parameters

ParameterTypeOwnershipDefaultMeaning
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
StatusInvalidArgumentno bulk build is in progress
StatusFaileda reactor fails while committing this patch; earlier fallback patches remain committed
StatusRejectedthe database refuses the patch; the build has failed and later adds report the same status
StatusClosedthe database is closed
StatusOutOfMemorynative 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

go500 B
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

go50 B
func (d *Database) BulkFinish() (*Document, error)

Errors

StatusWhen
StatusInvalidArgumentno bulk build is in progress
StatusRejectedthe database refuses a patch; an initial build publishes nothing and fallback keeps earlier commits
StatusFaileda reactor failed while adding a fallback patch; earlier patches remain committed
StatusConflictanother write committed to the database during the build
StatusClosedthe database is closed
StatusOutOfMemorynative 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

go492 B
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

go30 B
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

go319 B
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.

FieldTypeUnitRangeMeaning
page_sizeint64CountHost type rangeRows per page. 0 selects the default page size. Queries only. A negative value causes invalid_argument.
max_costtime.DurationHost duration (100 ns ticks at the ABI)Tick rangeThread 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_ofint64NoneHost 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——
transactionint64NoneHost type range—Zero when nothing was written.
factsint64CountHost type range——
committed_attime.TimeUTC instant (100 ns ticks since the Unix epoch at the ABI)Tick rangeThe zero time.TimeRecorded commit time as a UTC instant. The call measures this value. Independent calls can differ.
idsmap[string]int64NoneHost 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.

FieldTypeUnitMeaning
sequenceint64CountEvent number. Event 1 is the initial result.
supersededint64CountIntermediate 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.
transactionint64NoneTransaction the result was computed at.
result*DocumentNoneThe full query result. The event owns it and the consumer closes it.