SDK generation plugin
The sdks plugin generates a language-specific SDK from the database's
exported definitions. This release supports Go.
Configuration
Enable the plugin and set the output directory:
{
"plugins": {
"database": {
"path": "app.db"
},
"sdks": {
"go": {
"directory": "./sdk"
}
}
}
}
| Setting | Requirement | Description |
|---|---|---|
sdks.go | Optional | Enables the Go generator. |
sdks.go.directory | Required when go is enabled; nonempty string | Directory for generated Go source; relative paths are resolved from the process working directory. |
With no language configured, sdks does not generate files. There is no default
output directory. Select stdlib
and database separately if the definitions
or application need them.
An enabled SDK is generated when the database opens and refreshed after definitions
are updated. The output directory contains sdk.go and schemas/schemas.go.
Go configuration
The Go binding can express the same configuration with Go structs:
config := stardust.Config{
Plugins: &stardust.Plugins{
Stdlib: true,
Database: &stardust.DatabaseSettings{Path: "app.db"},
SDKs: &stardust.SDKSettings{
Go: &stardust.GoSDKSettings{Directory: "./sdk"},
},
},
}
db, err := stardust.OpenConfig(config)SDK generation
The configured SDK directory contains these generated files:
sdk.gocontains namespace structs, exported values and methods for exported functions.schemas/schemas.gocontains types for exported schemas.
For example, an exported function add in namespace spice/models produces
this database method:
result, err := db.SpiceModels.Add(20, 22)Fixed arities with simple contracts use Go types. Definitions without a
specific type use sdk.Value, with a closed set of Stardust value variants.
Schema shapes produce Go structs, and other schemas produce Go aliases.
The generated structs contain the schema's declared fields. Literal string,
integer, float, boolean, bytes, list, and map exports become fields on their namespace struct.
Other exported values, including computed values, use sdk.Value.
The generated methods cover exported defquery, defmutation, and defn
forms, and exported def forms whose value is an inline fn. A query with a
simple named find list or a field projection also generates a row struct. A
schema clause or result contract can give the fields their Go types. Generated schema types cover exported
defschema forms. Function names can use ASCII letters, digits, and
_ - ? ! * + < > = ..
Mutation methods return a fixed result with the transaction and created IDs. Mutations that create entities for query rows return slices of IDs. For a checked mutation, a parameter assigned directly to a schema-constrained field uses that field's Go type.
Using the generated Go SDK
Import the generated SDK from your Go module. With the spice/models/add
function saved in app.db, open the database and call its generated method:
db, err := sdk.Open(sdk.Config{Plugins: &sdk.Plugins{
Stdlib: true,
Database: &sdk.DatabaseSettings{Path: "app.db"},
}})
if err != nil {
log.Fatal(err)
}
defer db.Close()
result, err := db.SpiceModels.Add(20, 22)
if err != nil {
log.Fatal(err)
}
fmt.Println(result) // 42Query and mutation methods
Export defquery and defmutation declarations to generate Go methods.
For example, save these forms in spice/models:
[
{
"#invoke": [
"def",
{
"#local": "version"
},
3
]
},
{
"#invoke": [
"defmutation",
{
"#local": "create"
},
[
{
"#local": "name"
}
],
{
"schema": {
"name": {
"#local": "string?"
}
},
"patch": {
"_item": {
"name": {
"#local": "name"
}
}
}
}
]
},
{
"#invoke": [
"defquery",
{
"#local": "people"
},
[],
{
"where": [
[
{
"#local": "schema"
},
{
"name": {
"#local": "string?"
}
},
{
"#local": "?e"
}
]
],
"project": {
"?e": {
"name": true
}
}
}
]
},
{
"#invoke": [
"export",
{
"#local": "version"
},
{
"#local": "create"
},
{
"#local": "people"
}
]
}
]
The generated namespace exposes the literal scalar export and both methods:
fmt.Println(db.SpiceModels.Version) // 3
_, err := db.SpiceModels.Create("Ada")
if err != nil {
log.Fatal(err)
}
people, err := db.SpiceModels.People()
if err != nil {
log.Fatal(err)
}
fmt.Println(people) // [{Ada}]Subscribing to query results
Each exported defquery also generates a SubscribeTo method with the same
parameters. It returns a *stardust.Subscription of the query's row type.
Events returns an iterator over the results, and Next waits for one
result. The first result is the current result.
After each commit that changes a field that the query reads, or the namespace
that defines the query, the subscription delivers a new result. Each result is
complete. When a newer result arrives before Next takes the previous one,
the newer result replaces it:
sub, err := db.SpiceModels.SubscribeToPeople()
if err != nil {
log.Fatal(err)
}
defer sub.Close()
ctx, cancel := context.WithCancel(context.Background())
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for event, err := range sub.Events(ctx) {
if err != nil {
return // context.Canceled after cancel
}
fmt.Println(event.Result) // [{Ada}]
}
}()
// ... write to the database ...
cancel()
wg.Wait()An error from Next is the last step of Events. Close cancels the
subscription. After Close, Next returns
stardust.ErrSubscriptionClosed. When the database closes, Next returns
stardust.ErrClosed. When ctx ends, Next returns its error and the
subscription continues. Without a generated SDK, use
stardust.Subscribe[T](db, "spice/models", "people").
Reading reactor stats
A saved defreactor runs inside each write that changes a field it reads or
writes. The generated SDK has no method for a reactor. Read the facts that it
writes with a query. db.Reactors() returns a []stardust.ReactorStats with
each saved reactor and its work since the database opened:
stats, err := db.Reactors()
if err != nil {
log.Fatal(err)
}
for _, reactor := range stats {
fmt.Printf("%s/%s: %d runs, %d changes\n",
reactor.Namespace, reactor.Name, reactor.Runs, reactor.Changes)
}LastTx is the last transaction that the reactor changed. Failures counts
the writes that it caused to fail, and LastFailure holds the last message.
LastTx and LastFailure are nil until they have a value.
Updating definitions from a directory
On an open *stardust.Database, save the DUST files in a directory as
namespaces. For example, definitions/people/models.dust supplies the forms
for people/models:
response, err := db.UpdateDefinitionsFromDir("./definitions")
if err != nil {
log.Fatal(err)
}
for _, namespace := range response.Namespaces {
fmt.Println(namespace.Path, namespace.Revision)
}The files are saved together in one transaction. Removing a file does not
delete its previously saved namespace. If the SDK plugin is
enabled, it regenerates the SDK after the transaction commits. A
*stardust.DefinitionsError with Outcome set to "committed" means the
definitions were saved but a plugin could not complete its update.
Using the released Go binding
The release archive includes the stardust Go module in abi/bindings/go and
the native libraries in abi/lib. In your application module, point Go at the
extracted release. For example, on Linux x86-64, set STARDUST_RELEASE to the
absolute path of the extracted archive, then run:
go mod edit -require=stardust@v0.0.0 \
-replace=stardust="$STARDUST_RELEASE/abi/bindings/go"The released binding links to the native library in abi/lib on Linux
x86-64 and ARM64. The generated SDK imports this binding as stardust.
Using the Go ABI binding
Import the released binding to send requests directly:
import "stardust"Decode creates a Document. Submit accepts request Documents and returns
their UUIDs. Poll returns response Documents. Close each document when you no longer need it.
A poll wait of -1 waits for a response:
config, err := stardust.Decode(`{workers 1 plugins <stdlib database>}`)
if err != nil {
log.Fatal(err)
}
defer config.Close()
db, err := stardust.Open(config)
if err != nil {
log.Fatal(err)
}
defer db.Close()
request, err := stardust.Decode(`{method "eval" params {code (+ 20 22)}}`)
if err != nil {
log.Fatal(err)
}
defer request.Close()
ids, err := db.Submit(request)
if err != nil {
log.Fatal(err)
}
responses, err := db.Poll(-1)
if err != nil {
for index := range responses {
if closeErr := responses[index].Close(); closeErr != nil {
log.Print(closeErr)
}
}
log.Fatal(err)
}
fmt.Println(ids[0]) // Match this request with the response causation-id.
for index := range responses {
response := responses[index]
text, err := response.Encode()
if err != nil {
log.Fatal(err)
}
fmt.Print(text) // The response has result 42 and UUID message fields.
message, err := response.Message()
if err != nil {
log.Fatal(err)
}
fmt.Println(message.CausationID == ids[0])
if err := response.Close(); err != nil {
log.Fatal(err)
}
}For a saved function, the binding also offers Call and typed CallAs.
Use the same handle for function calls:
result, err := stardust.CallAs[int64](db, "spice/models", "add", 20, 22)Generated calls match their responses by causation ID. Poll raw responses concurrently with large submissions so the bounded queues can make progress.