Language values and documents

Your application keeps its own structs, records, dataclasses and maps. The typed layer copies them into native documents and copies documents back into them. The native document API stays available beside it for work that needs native fidelity or no conversion.

Choose an interface

UseWhen you want to
Language values (encode, decode, typed rows)Write and read ordinary application data in the types of your language.
DocumentsReuse a value in several calls without converting it again, keep duplicate keys and member order exactly, or batch native work.
Parse and serializeRead or write text or bytes at a file or network boundary. See Formats and conversion.
Builders and node readsConstruct or walk documents node by node. See Documents and Building documents.

Example

The example stores three people from language values, runs a query written in the selected format, and decodes each row into a value of the language. The captured result is the decoded rows, encoded again for display.

Store Python dataclasses and read typed rows

query_text holds this document:

edn66 B
{:find    [?name]
 :where   [[?e "name" ?name]]
 :orderBy [?name]}
python634 B
@dataclass
class Person:
    name: str
    role: str
    age: int


@dataclass
class Name:
    name: str


people = {
    "#_ada": Person("Ada", "engineer", 36),
    "#_bob": Person("Bob", "engineer", 41),
    "#_cy": Person("Cy", "designer", 29),
}
async with (await stardust.open(database_path)) as database:
    (await stardust.merge_patch_value(database, people))
    async with (await stardust.parse(query_text, "edn")) as definition, (await database.query(definition)) as query, \
            (await query.run()) as rows:
        names = [row async for row in stardust.values(rows, Name)]
result = (await stardust.encode(names))
Result / 51 B
{:value [{:name "Ada"} {:name "Bob"} {:name "Cy"}]}

Standard JSON values

Any value that the standard JSON encoder of your language accepts also converts here, and decode reads back what encode writes: encoding/json in Go, json.dumps in Python, serde_json in Rust, cheshire or data.json in Clojure and core:encoding/json in Odin. Native tags come first, so instants, durations and links become #utc, #dur and #link values instead of JSON text. Several languages accept more, such as Python sets and UUIDs, or Clojure java.time values. A value is refused only where that encoder refuses it, or where a document cannot hold it: a non-finite number, an integer outside i64, a decimal, instant or duration without an exact native form, or a cycle. The host mapping gives each type.

Ownership and errors

Encode returns a new owned document that holds a snapshot of the value. Close it as you close any document. Decode borrows a document only for the call and returns independent values. It never closes or keeps the document. Typed row iteration borrows the rows and reads one page at a time. Close the rows yourself. Every page of one cursor reads the same store snapshot, so iteration never repeats the query.

A value-argument operation accepts a language value or a document. It passes a document through unchanged. It encodes a language value into a temporary document, calls the native operation once, and closes the temporary document on success and failure.

Await encode, decode and value-argument operations. Use async with for document owners and async for for typed rows. Conversion also accepts dataclasses, sets, Enum, UUID, exact Decimal and standard date and time types. We welcome Python developer feedback on which interface works best in applications.

A conversion failure is invalid_argument with a code and a value path such as people[1].age. A failed decode returns no partly filled value.

Costs

Encode and decode copy every value. A document that you pass directly is not copied. Type inspection belongs only to the typed layer, and each language keeps per-type plans where it inspects types at run time. No conversion writes or reads DUST, EDN or TRON text, and JSON text appears only where a Go value supplies its own MarshalJSON or UnmarshalJSON method. Those formats are optional boundaries, not an intermediate transport.

The conversion rules and the host mapping below give each type, the null and missing-field rules and the strict mode.

Operations

OperationReturnsSummary
from_valuedocumentfrom_value(value) copies host values into an owned document.
Document.to_valuevaluedocument.to_value() copies a document into host values.

from_value

python64 B
def from_value(value, *, library: str | None = None) -> Document

Parameters

ParameterTypeOwnershipDefaultMeaning
valueValueValueRequiredA host value to copy into native document nodes.
librarystr | NoneValueNoneLoaded native library used by this call.

Errors

StatusWhen
"invalid_argument"the value has a host type with no document form (one the language's standard JSON encoder also refuses), a number outside i64 or finite f64, a decimal or time with no exact native form, a failing conversion method, or a cycle
"out_of_memory"native memory is exhausted

Notes

Host maps cannot preserve duplicate keys. Use native documents when member order or duplicate keys matter.

Examples

Copy a host integer into a native document

python40 B
result = (await stardust.from_value(41))
Result / 11 B
{:value 41}

C exports: stardust_document_builder_create, stardust_document_builder_add_many, stardust_document_builder_seal, stardust_document_builder_error, stardust_document_builder_release

Document.to_value

python18 B
def to_value(self)

Parameters

ParameterTypeOwnershipDefaultMeaning
selfDocumentBorrowed for the callRequiredThe document owner for this operation. Keep it alive during the call.

Errors

StatusWhen
"closed"the document is closed

Notes

Host map semantics determine how duplicate keys are represented. The copied value survives document closure.

Examples

Copy a native input into a host value

input_text holds this document:

edn7 B
{:x 41}
python143 B
async with (await stardust.parse(input_text, "edn")) as input:
    value = (await input.to_value())
result = (await stardust.from_value(value))
Result / 16 B
{:value {:x 41}}

C exports: stardust_document_count, stardust_document_read_many, stardust_document_i64, stardust_document_f64

Typed operations

These helpers convert language values or call native operations. The nesting limit for typed documents is 128 levels.

duration_from_ticks

python49 B
def duration_from_ticks(ticks: int) -> timedelta:

duration_from_ticks(ticks) converts signed native 100 ns ticks to the language's standard duration. This conversion performs no native call. Precision loss and values outside the host range fail. Failures: invalid_argument when the value has the wrong type, loses precision or exceeds the target range.

duration_to_ticks

python47 B
def duration_to_ticks(value: timedelta) -> int:

duration_to_ticks(duration) converts a standard duration to signed native 100 ns ticks. This conversion performs no native call. Precision loss and values outside the native range fail instead of truncating or saturating. Failures: invalid_argument when the value has the wrong type, loses precision or exceeds the target range.

instant_from_ticks

python47 B
def instant_from_ticks(ticks: int) -> datetime:

instant_from_ticks(ticks) converts signed native 100 ns ticks since the Unix epoch to the language's standard timestamp. This conversion performs no native call. Precision loss and values outside the host range fail. Failures: invalid_argument when the value has the wrong type, loses precision or exceeds the target range.

instant_to_ticks

python45 B
def instant_to_ticks(value: datetime) -> int:

instant_to_ticks(instant) converts a standard timestamp to signed native 100 ns ticks since the Unix epoch. This conversion performs no native call. Precision loss and values outside the native range fail. The datetime must be timezone-aware. Failures: invalid_argument when the value has the wrong type, loses precision or exceeds the target range.

encode

python61 B
def encode(value, *, library: str | None = None) -> Document:

encode(value) copies a language value into a new owned document that holds an immutable snapshot. The caller closes it. Conversion walks the value directly into one preorder builder batch and serializes no text; only a Go json.Marshaler's JSON output is parsed, by the native JSON codec. Failures carry the value path, such as people[3].age, and leave no document: the temporary builder always closes. Failures: invalid_argument when the value has no document form (a type the language's standard JSON encoder also refuses), a number is outside i64 or finite f64, a decimal, instant or duration has no exact native form, a conversion method of the value fails, the nesting exceeds the depth limit, or the value contains a cycle. out_of_memory when native memory is exhausted.

decode

python68 B
def decode(document: Document, type_=None, *, strict: bool = False):

decode(document, type) copies a document into an independent language value of the requested type. It borrows the document only for the call and never closes or retains it. Reads use bounded bulk node reads. A failure reports the value path and returns no partially filled value. Typed objects refuse duplicate keys; unknown keys are ignored unless strict mode is on. A missing field keeps the language default; explicit null needs a nullable target. Failures: invalid_argument when a node does not match the target type, a number is outside the target range or, as an integer, has no exact form in it, a text does not parse as the target or its key type, a union has several matching variants, a conversion method of the target fails, an object repeats a key or, where a strict mode is offered and on, has an undeclared key. Narrow floating targets round to nearest. closed when the source is closed.

values

python60 B
def values(rows: Rows, type_=None, *, strict: bool = False):

values(rows, type) lazily decodes the rows of a query cursor one at a time, reading one native page at a time. It borrows the rows and never closes them: close the rows yourself. Each internally read page closes when iteration advances, ends, fails or stops early. All pages read the snapshot of the run that created the cursor, so typed iteration never requeries between pages. A failure is reported once, and then iteration ends. Failures: invalid_argument when a node does not match the target type, a number is outside the target range or, as an integer, has no exact form in it, a text does not parse as the target or its key type, a union has several matching variants, a conversion method of the target fails, an object repeats a key or, where a strict mode is offered and on, has an undeclared key. Narrow floating targets round to nearest. closed when the source is closed.

build_value

python84 B
def build_value(expression, explain=None, *, library: str | None = None) -> Program:

build_value(expression) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level build operation. Failures: those of encode for a language value, then those of the low-level operation.

evaluate_value

python75 B
def evaluate_value(program: Program, input=None, explain=None) -> Document:

evaluate_value(program, input) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level evaluate operation. Failures: those of encode for a language value, then those of the low-level operation.

query_value

python57 B
def query_value(database: Database, definition) -> Query:

query_value(database, definition) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level query operation. Failures: those of encode for a language value, then those of the low-level operation.

expression_value

python78 B
def expression_value(database: Database, definition, explain=None) -> Program:

expression_value(database, definition) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level expression operation. Failures: those of encode for a language value, then those of the low-level operation.

run_query_value

python196 B
def run_query_value(query: Query, parameters=None, *, page_size: int | None = None, max_cost: timedelta | None = None, as_of: int | None = None, explain: _core.QueryExplain | None = None) -> Rows:

run_query_value(query, parameters, options) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level run operation. Failures: those of encode for a language value, then those of the low-level operation.

mutation_value

python63 B
def mutation_value(database: Database, definition) -> Mutation:

mutation_value(database, definition) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level mutation operation. Failures: those of encode for a language value, then those of the low-level operation.

run_mutation_value

python216 B
def run_mutation_value(mutation: Mutation, parameters=None, *, page_size: int | None = None, max_cost: timedelta | None = None, as_of: int | None = None, explain: _core.MutationExplain | None = None) -> _core.Commit:

run_mutation_value(mutation, parameters, options) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level run operation. Failures: those of encode for a language value, then those of the low-level operation.

merge_patch_value

python79 B
def merge_patch_value(database: Database, patch, explain=None) -> _core.Commit:

merge_patch_value(database, patch) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level merge_patch operation. Failures: those of encode for a language value, then those of the low-level operation.

patch_definition_value

python92 B
def patch_definition_value(database: Database, kind: str, path: str, patch) -> _core.Commit:

patch_definition_value(database, kind, path, patch) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level patch_definition operation. Failures: those of encode for a language value, then those of the low-level operation.

Conversion rules

ValueRule
standardEvery value that the language's standard JSON encoder accepts converts: encoding/json in Go, json.dumps in Python, serde_json in Rust, cheshire or data.json in Clojure and core:encoding/json in Odin. Decode reads back what encode writes. Refusals remain only where that encoder refuses, or where a document cannot hold the value: a non-finite number, an integer outside i64, an inexact decimal, instant or duration, and a cycle.
nullA nullable target (pointer, option, Maybe, nil slice or map, None, nil) accepts null. A non-nullable target refuses it with wrong_kind. Explicit null is not a missing field.
booleanOnly booleans: no truthiness and no number or string coercion.
integerNumbers are i64 or f64. A host integer of any width or signedness converts when it fits i64; a larger one fails with out_of_range, in both directions. Narrower targets are range-checked (out_of_range).
realFinite f64 only; NaN and infinities are refused. An integer decodes into a floating target only when exactly representable, and a real into an integer target only when finite, integral and in range. f32 narrowing refuses overflow and rounds to nearest. An exact decimal (Python Decimal, Clojure BigDecimal) is an i64 when integral and in range, otherwise the f64 of its shortest spelling; any other decimal fails with inexact_number.
textValid UTF-8, copied without normalization. Invalid UTF-8 and unpaired surrogates are refused. A string argument is a string value; it is never parsed as document text. Values that the standard JSON encoder writes as text stay text: UUIDs, dates and times that are not instants, Go TextMarshaler values, and Go and Clojure byte arrays as base64. Text that does not parse as a typed target fails with invalid_value.
arrayOrdered collections, including tuples, sets and Java collections. A fixed-length target needs the exact length (length_mismatch). A nil slice or list encodes null; an allocated empty one encodes an empty array.
objectStruct, record or dataclass fields and maps. Field names follow the standard encoder's tags and embedding rules; Go also matches a key case-insensitively after an exact match, as encoding/json does. Map keys that are not strings become member keys as the standard encoder spells them (decimal integers, true, false, enum names, MarshalText text) and parse back into typed keys. Typed decode refuses a repeated key (duplicate_field); native documents keep both members. Unknown keys are ignored unless strict mode refuses them (unknown_field). A missing field keeps the language default or fails as required (missing_field).
enumEnums use the standard encoder's form: Rust variants as serde represents them, Python Enum members as their value, Odin enums by name. Odin unions write their active variant and decode into the one variant whose shape matches (ambiguous_variant otherwise).
taggedNative tags take priority over any JSON spelling. Links, UTC instants and durations use the native {#link id}, {#utc text} and {#dur text} objects through the Link type and standard-library instant and duration types. Rust uses #[serde(with = "stardust::Utc")] and #[serde(with = "stardust::Dur")] field adapters to select native tags without guessing from record names. Extra types are only for native values that the standard library cannot represent, such as signed Rust durations. An ordinary object is never reinterpreted as a tagged value. A time value that is not a whole number of 100 ns ticks is refused. Direct converters report inexact_number; Rust Serde adapter errors use the custom-hook codes unsupported_type on encode and wrong_kind on decode, with the field path.
hooksConversion methods run as the standard encoder runs them: Go Encoder and Decoder hooks first, then json.Marshaler, encoding.TextMarshaler and their decode methods; Rust Serialize and Deserialize; Odin registered converters. A failing Go JSON or text method fails with hook_failed; other hooks return their own error. Only Go's JSON methods exchange JSON text, through the native JSON codec.
limitsRecursive conversions refuse nesting beyond the depth limit with too_deep. Go and Python untyped decode traverse iteratively and accept deeper documents. Cyclic host values fail with cycle, or too_deep in Clojure. Every failure has status invalid_argument, a code and a value path such as people[3].age or tags["a.b"]. Failed conversions return no partial value or document.

Host mapping

Typed encode and decode, and the untyped from_value and to_value where the language offers them, use this mapping. Each conversion walks values directly; no text format is involved.

ValueHostDocumentBackMeaning
nullNonenullNoneNone becomes null.
integerinti64intThe conversion refuses integers outside the i64 range.
floatfloatf64floatThe conversion refuses non-finite numbers.
textstrUTF-8 stringstrThe conversion encodes strings as UTF-8.
arraylistarraylistThe conversion preserves list order.
objectdict with str keysobjectdictThe conversion preserves input key order.
map_keysint, float, bool or None dict keysmember key textstr keys, or the annotated key type (typed decode)Keys use json.dumps spelling: true, false, null and the repr of numbers. Enum, UUID, date and time keys are their value or text.
bytesbytes or bytearrayrefusednot producedjson.dumps refuses bytes, so the conversion does too.
enumEnum, IntEnum or StrEnum memberits valuethe Enum type (typed decode)json.dumps writes IntEnum and StrEnum values; every Enum member is its value.
text_valuesUUID, date and timetheir textUUID, date or time (typed decode)datetime and timedelta are native tags instead.
decimalDecimali64 or f64Decimal (typed decode)Exact only: an integral value in range is an i64, another must equal the f64 of its shortest spelling (inexact_number).
collectionstuple, NamedTuple, set or frozensetarraylist, or the annotated type (typed decode)Tuples are arrays as json.dumps writes them; sets are sorted arrays when their items sort.
unsigned———Python integers are signed.
non_finitenan or inf floatrefusednot producedjson.dumps writes non-standard NaN and Infinity; documents refuse them.
timeaware datetime or timedeltaUTC or duration tagged objectdatetime or timedelta (typed decode)encode, from_value and value-argument wrappers convert these types. A naive datetime has no UTC instant, so conversion fails. Typed decode refuses sub-microsecond ticks instead of losing precision.
to_value_numbersdocument numberi64 or f64int or floatThe conversion tries typed i64 reads before f64.
duplicate_keysdocument objectduplicate membersfirst valueThe conversion keeps the first duplicate value.