The Go SDK runs SurrealQL with generic functions that decode the result into a Go type you choose. Query runs one or more statements, and QueryRaw runs a list of statements with a result for each. Run calls a function, API calls a DEFINE API endpoint, and GQL runs an ISO GQL query. Each takes a *DB, a *Session or a *Transaction. This page covers each of them, and the variables that a session keeps for its queries.
API references
Function | Description |
|---|---|
surrealdb.Query[T](ctx, s, sql, vars) | Runs SurrealQL and returns one result for each statement |
surrealdb.QueryRaw(ctx, s, queries) | Runs a list of statements and gives each its own result |
surrealdb.QueryStream[T](ctx, s, sql, vars) | Runs SurrealQL and yields its results as they arrive |
surrealdb.Run[T](ctx, s, name, args...) | Calls a function and returns its result |
surrealdb.RunVersion[T](ctx, s, name, version, args...) | Calls a function at a given version |
surrealdb.API[T](ctx, s, path, req) | Invokes an endpoint defined with DEFINE API |
surrealdb.GQL[T](ctx, s, query, vars) | Runs an ISO GQL query |
db.Let(ctx, key, val) | Sets a variable in the session |
db.Unset(ctx, key) | Removes a variable from the session |
Running a query
Query takes the SurrealQL to run and a map of variables. It returns a pointer to a slice with one QueryResult for each statement. The type parameter is the Go type of each statement's result:
type Person struct {
ID *models.RecordID `json:"id,omitempty"`
Name string `json:"name"`
Age int `json:"age"`
}
results, err := surrealdb.Query[[]Person](ctx, db,
"SELECT * FROM person WHERE age >= $min_age ORDER BY age",
map[string]any{"min_age": 18},
)
if err != nil {
log.Fatal(err)
}
for _, p := range (*results)[0].Result {
fmt.Printf("%s is %d\n", p.Name, p.Age)
}Jaime is 28
Tobie is 35Each QueryResult holds the Status of its statement, the Time it took, the decoded Result, and an Error when the statement failed. The Status is "OK" or "ERR".
A SELECT returns an array, so its type parameter is a slice. For a statement that returns one value, such as RETURN or SELECT ... FROM ONLY, the type parameter is the type of that value. The SDK matches struct fields by their json tags, as in the Person type above.
Binding variables
Pass values as variables, rather than formatting them into the SurrealQL text. In the query, refer to each variable with $name. The SDK sends each variable as a typed CBOR value. As a result, a record ID, a time.Time or a models.PlainDate keeps its kind, and a variable cannot change the meaning of the query:
results, err := surrealdb.Query[[]Person](ctx, db,
"SELECT * FROM person WHERE name = $name AND age > $age",
map[string]any{
"name": "Tobie",
"age": 25,
},
)Pass nil when the query has no variables:
results, err := surrealdb.Query[[]Person](ctx, db, "SELECT * FROM person", nil)Value types lists the SurrealDB kind that the SDK sends for each Go value.
Reading the results of several statements
A query with several statements returns a result for each of them, in order. A statement can fail while the others succeed, so check the Error field of each result:
results, err := surrealdb.Query[any](ctx, db,
"RETURN 1; THROW 'Not allowed'; RETURN 3;",
nil,
)
for i, qr := range *results {
if qr.Error != nil {
fmt.Printf("statement %d failed: %s\n", i, qr.Error.Message)
continue
}
fmt.Printf("statement %d: %v\n", i, qr.Result)
}statement 0: 1
statement 1 failed: An error occurred: Not allowed
statement 2: 3When any statement fails, Query also returns an error. This error joins the QueryError of each failed statement. Query still returns the results, so you can read the results of the statements that succeeded. errors.Is(err, &surrealdb.QueryError{}) reports whether the error holds a statement failure, as opposed to a transport or decoding failure. See Error handling.
All the results share one type parameter. When the statements return different types, use any, or use QueryRaw, which decodes each result into its own type.
Composing queries with QueryRaw
QueryRaw runs a list of QueryStmt values as one query. Each QueryStmt has its own SurrealQL and variables. After it returns, .GetResult() decodes each statement's result into a type of its own:
stmts := []surrealdb.QueryStmt{
{SQL: "CREATE person:alice SET name = $name, age = 41", Vars: map[string]any{"name": "Alice"}},
{SQL: "SELECT count() AS total FROM person GROUP ALL"},
}
if err := surrealdb.QueryRaw(ctx, db, &stmts); err != nil {
log.Fatal(err)
}
var created []Person
if err := stmts[0].GetResult(&created); err != nil {
log.Fatal(err)
}
var counts []struct {
Total int `json:"total"`
}
if err := stmts[1].GetResult(&counts); err != nil {
log.Fatal(err)
}Each QueryStmt must hold exactly one statement, so that the SDK can match each result to its statement. When a QueryStmt holds several statements or only a comment, QueryRaw returns an error and leaves the results unchanged. The SDK sends the variables of all the statements together, so two statements must not give different values to the same variable name.
QueryRaw can also run a transaction written as statements. Put each of BEGIN, COMMIT and CANCEL in a QueryStmt of its own. With SurrealDB 3.x, QueryRaw returns an error for a transaction that has a RETURN statement. It also returns an error for a transaction that is cancelled after a statement in it failed. This is because those servers do not return one result for each statement. Use Query for these transactions.
The query builder builds the SurrealQL and the variables for a statement.
Calling a function
Run calls a function with arguments and decodes what it returns. The function can be a built-in one, such as string::len, or one defined with DEFINE FUNCTION:
length, err := surrealdb.Run[int](ctx, db, "string::len", "SurrealDB")
if err != nil {
log.Fatal(err)
}
fmt.Println(*length)9DEFINE FUNCTION fn::greet($name: string) -> string {
RETURN 'Hello, ' + $name + '!';
};greeting, err := surrealdb.Run[string](ctx, db, "fn::greet", "Tobie")
if err != nil {
log.Fatal(err)
}
fmt.Println(*greeting)Hello, Tobie!A function name has parts joined by ::. The only names without :: are the built-ins count, not, rand and sleep. Run refuses any other name before it sends anything, with an error such as invalid function name "DELETE".
RunVersion calls a function at a given version. Before SurrealDB 4.0, the version selected a SurrealML model, which 4.0 removed, so this example works only against a server on SurrealDB 3.x or earlier. See Upgrading from 3.x to 4.0.
prediction, err := surrealdb.RunVersion[float64](ctx, db, "ml::house_price", "1.0.0", features)The version has the form 1.0.0. With an empty version, RunVersion does the same as Run.
Defining session variables
.Let() sets a variable in the session. Every later query in that session can use the variable. .Unset() removes the variable:
if err := db.Let(ctx, "min_age", 30); err != nil {
log.Fatal(err)
}
names, err := surrealdb.Query[[]string](ctx, db,
"SELECT VALUE name FROM person WHERE age >= $min_age ORDER BY name",
nil,
)
if err := db.Unset(ctx, "min_age"); err != nil {
log.Fatal(err)
}A variable belongs to the session that set it, so it does not affect other connections or sessions. If you pass a variable with the same name to Query, that variable replaces the session variable for that query.
Over WebSocket, the client keeps a copy of each variable. The client uses this copy to set the variable again when it reconnects, and to copy the variable to a forked session. The client encodes the value once, when you call .Let(). If you change the Go value after that, neither the variable nor its copies change.
Sending statements as one transaction
Statements between BEGIN TRANSACTION and COMMIT TRANSACTION in one query succeed or fail together:
_, err := surrealdb.Query[any](ctx, db, `
BEGIN TRANSACTION;
UPDATE account:one SET balance -= $amount;
UPDATE account:two SET balance += $amount;
COMMIT TRANSACTION;
`, map[string]any{"amount": 40})To run statements one at a time and decide in Go whether to commit, use an interactive transaction.
Calling a DEFINE API endpoint
API calls an endpoint defined with DEFINE API in the namespace and database of the session. The call does not go through the HTTP router of the server:
DEFINE API "/greet/:name" FOR get THEN {
RETURN {
status: 200,
body: { greeting: 'Hello, ' + $request.params.name },
};
};type Greeting struct {
Greeting string `json:"greeting"`
}
res, err := surrealdb.API[Greeting](ctx, db, "/greet/Tobie", nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(res.Status, res.Body.Greeting)200 Hello, TobieA nil request is a GET without a body. Pass an APIRequest to set the method, the body, the headers and the query parameters:
res, err := surrealdb.API[Greeting](ctx, db, "/greetings", &surrealdb.APIRequest{
Method: "post",
Body: map[string]any{"name": "Tobie"},
Headers: map[string]string{"x-request-id": "42"},
Query: map[string]string{"lang": "en"},
})As with net/http, API does not return an error for a response with an unsuccessful status, so check Status. The body of such a response is often a string, for example when the path has no endpoint. When the body does not fit the type parameter, Body is its zero value.
API sends the call as a query to the SurrealQL function api::invoke. As a result, the call fails for a user whom the server does not allow to run arbitrary queries.
Running ISO GQL
GQL runs an ISO GQL query, such as a MATCH pattern, with the gql method of the server. Like Query, it returns one result for each statement:
results, err := surrealdb.GQL[[]map[string]any](ctx, db, "MATCH (p:person) RETURN p.name", nil)
if err != nil {
log.Fatal(err)
}
fmt.Println((*results)[0].Result)[map[p.name:Alice] map[p.name:Ana] map[p.name:Jaime] map[p.name:Tobie]]Reading results as they arrive
Query waits for every statement to finish and holds the whole result in memory. To read the records of a large SELECT as the server sends them, use QueryStream.
Learn more
DB API reference for complete function signatures and parameters
Data manipulation for the typed CRUD functions
Error handling for statement errors and transport errors
Types reference for the
QueryResult,QueryStmt,APIRequestandAPIResponsetypesSurrealQL statements for the query language syntax