DB is the client of the Go SDK. It holds the connection and the default session, and has methods for connecting, authentication, variables, sessions, transactions, and import and export. Queries and record operations are generic package functions, such as surrealdb.Query[T], that take a *DB, a *Session or a *Transaction as their s argument. This page is the reference for both. For explanations and longer examples, follow the links to the concept pages.
import surrealdb "github.com/surrealdb/surrealdb.go/v2"Source: db.go
Constructors
FromEndpointURLString
Creates a client and connects it. The scheme of the URL chooses the connection: ws:// and wss:// for WebSocket, http:// and https:// for HTTP.
db, err := surrealdb.FromEndpointURLString(ctx, connectionURL)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Bounds the connection attempt. |
connectionURL | string | The address of the server, such as ws://localhost:8000. |
Returns: (*DB, error)
db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000")
if err != nil {
log.Fatal(err)
}
defer db.Close(ctx)A URL with another scheme returns invalid connection url. For mem://, memory and surrealkv://, the function returns embedded database not enabled. See Connecting to SurrealDB.
FromEndpointURLStringWithOptions
Creates a client and connects it, configured by options. With no options, it does what FromEndpointURLString does.
db, err := surrealdb.FromEndpointURLStringWithOptions(ctx, connectionURL, opts...)Returns: (*DB, error)
db, err := surrealdb.FromEndpointURLStringWithOptions(ctx, "ws://localhost:8000",
surrealdb.WithVersionCheck(true),
surrealdb.WithTokenRenewal(true),
) FromConnection
Creates a client from a connection you built, such as gorillaws.New(conf), gws.New(conf) or http.New(conf), and calls .Connect(ctx) on it.
db, err := surrealdb.FromConnection(ctx, conn)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Bounds the connection attempt. |
conn | connection.Connection | The connection. See Using a custom connection . |
Returns: (*DB, error)
FromConnectionWithOptions
Creates a client from a connection you built, configured by options.
db, err := surrealdb.FromConnectionWithOptions(ctx, conn, opts...)Returns: (*DB, error)
Connect, New and .WithContext() are deprecated. Use FromEndpointURLString, and pass a context to each call.
Options
An Option configures a client created with FromEndpointURLStringWithOptions or FromConnectionWithOptions.
WithVersionCheck
Turns the check of the server version on or off. It is off by default. When it is on, the client sends a version request each time it connects. Connecting fails with an UnsupportedVersionError when the server version is outside MinimumServerVersion to MaximumServerVersion. Connecting also fails when the server does not answer the version request.
surrealdb.WithVersionCheck(enabled bool) Option WithReconnect
Turns reconnection on or off. It is on by default for WebSocket connections. When the client loses the connection, it connects again, with backoff. Before it sends any other request, it restores the sessions, authentication, namespaces, databases, variables and live queries. See Reliable connections.
surrealdb.WithReconnect(enabled bool) Option WithReconnectAttempts
Sets how many consecutive attempts the client makes to reconnect before it gives up and closes. It defaults to DefaultReconnectAttempts, which is 5. Zero or less means no limit.
surrealdb.WithReconnectAttempts(attempts int) Option WithReconnectDelay
Sets the wait before each attempt to reconnect. The wait is minDelay times 2 to the power of the attempt's number, counting from 1. It has up to 10% jitter, and is at most maxDelay. minDelay and maxDelay default to DefaultReconnectMinDelay (1s) and DefaultReconnectMaxDelay (1m).
surrealdb.WithReconnectDelay(minDelay, maxDelay time.Duration) Option WithTokenRenewal
Turns automatic token renewal on or off. It is off by default. When it is on, a session that holds a token pair exchanges the pair for a new one shortly before the access token expires. A session gets a token pair from .SignInWithRefresh(), .SignUpWithRefresh() or .Refresh(). .Tokens() returns the current pair. See Automatic token renewal.
surrealdb.WithTokenRenewal(enabled bool) Option WithTokenExpiryMargin
Sets the margin: the session renews an access token this long before the token expires. It defaults to DefaultTokenExpiryMargin, which is 1m. When an access token lives for less than twice the margin, the session renews it halfway through its life.
surrealdb.WithTokenExpiryMargin(margin time.Duration) OptionConnection methods
.Close()
Closes the connection and releases its resources. Later requests return ErrClientClosed.
err := db.Close(ctx)Returns: error
.Use()
Selects the namespace and database of the default session.
err := db.Use(ctx, ns, database)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Bounds the request. |
ns | string | The namespace to use. |
database | string | The database to use. |
Returns: error
.Version()
Returns the version, build and timestamp of the server.
ver, err := db.Version(ctx)Returns: (*VersionData, error). See VersionData.
.Health()
Checks that the server is up. It sends GET /health over HTTP, whichever transport the client uses, and needs no authentication. It returns nil when the server answers with a 2xx status. Otherwise, it returns a *HealthError with the status and the body.
err := db.Health(ctx)Returns: error
.CBORVersion()
Returns the CBOR version the connection uses: connection.CBORv2 (cbor.2, with SurrealDB 4.0) or connection.CBORv1 (plain CBOR). Its String() method returns cbor.2 or cbor. See cbor.2 and plain CBOR.
v := db.CBORVersion()Returns: connection.CBORVersion
.Status()
Returns the state of the connection. A client that does not reconnect stays StatusConnected until it closes.
status := db.Status()Returns: ConnectionStatus
.OnStatus()
Calls fn with a StatusEvent each time the state of the connection changes. The calls stop when you call the function that .OnStatus() returns. The client passes events one at a time, in order, on a goroutine other than the one that reconnects. Only a client that reconnects reports changes.
stop := db.OnStatus(fn func(StatusEvent))Returns: func(), which stops the calls
Authentication methods
.SignIn()
Signs in a user. The fields of authData decide the level: root, namespace, database, record, or a bearer key with the key field.
token, err := db.SignIn(ctx, authData)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Bounds the request. |
authData | any | An Authstruct, or a map[string]anywith the keys NS, DB, AC, user, pass, key, or the fields an access method reads. |
Returns: (string, error), where the string is the JWT
token, err := db.SignIn(ctx, surrealdb.Auth{
Username: "root",
Password: "secret",
})token, err := db.SignIn(ctx, map[string]any{
"NS": "surrealdb",
"DB": "docs",
"AC": "account",
"email": "tobie@example.com",
"pass": "hunter123",
})For an access method defined WITH REFRESH, use .SignInWithRefresh().
.SignInWithRefresh()
Signs in through a TYPE RECORD access method defined WITH REFRESH, and returns an access token and a refresh token. To exchange a refresh token for a new pair, pass a refresh key in place of the credentials.
tokens, err := db.SignInWithRefresh(ctx, authData)Returns: (*Tokens, error). See Tokens.
.SignUp()
Signs up a record user through the SIGNUP clause of an access method, and signs them in.
token, err := db.SignUp(ctx, authData)Returns: (string, error), where the string is the JWT
.SignUpWithRefresh()
Signs up a record user through an access method defined WITH REFRESH, and returns an access token and a refresh token.
tokens, err := db.SignUpWithRefresh(ctx, authData)Returns: (*Tokens, error)
.Refresh()
Exchanges a token pair for a new one, and authenticates the session with it. The server revokes the refresh token that you pass. After that, you can refresh only the returned pair.
newTokens, err := db.Refresh(ctx, tokens)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Bounds the request. |
tokens | Tokens | The pair to exchange. |
Returns: (*Tokens, error)
.Revoke()
Revokes the refresh token of a pair. After that, you cannot refresh the pair. The session stays signed in.
err := db.Revoke(ctx, tokens)Returns: error
.Tokens()
Returns the token pair that the session holds. The pair changes at each renewal. It returns nil when the session holds no pair or when token renewal is off.
pair := db.Tokens()Returns: *Tokens
.Authenticate()
Authenticates the connection with a JWT, such as a token from an earlier sign-in or one that a TYPE JWT access method verifies.
err := db.Authenticate(ctx, token)Returns: error
.Invalidate()
Signs the session out. The namespace, database and variables stay as they are.
err := db.Invalidate(ctx)Returns: error
.Reset()
Returns the default session to the state it had when the client connected. It signs the session out, clears its namespace, database and variables, and kills its live queries. Over HTTP, it clears the state that the client keeps, without calling the server.
err := db.Reset(ctx)Returns: error
.Info()
Returns the record of the signed-in record user, as SELECT * FROM $auth does. Table permissions apply.
info, err := db.Info(ctx)Returns: (map[string]any, error)
Variables
.Let()
Sets a variable in the default session, which later queries can use as $key. Over WebSocket, the client keeps a copy of the variable, encoded once. It uses this copy to set the variable again when it reconnects, and to copy the variable to a fork.
err := db.Let(ctx, key, val)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Bounds the request. |
key | string | The name of the variable, without $. |
val | any | The value. |
Returns: error
.Unset()
Removes a variable from the default session.
err := db.Unset(ctx, key)Returns: error
Sessions and transactions
.Attach()
Attaches a new session to the connection. The new session starts signed out, with no namespace or database. Needs a WebSocket connection, and returns constants.ErrSessionsNotSupported otherwise. See Multiple sessions.
session, err := db.Attach(ctx)Returns: (*Session, error). See Session.
.Fork()
Attaches a new session that starts as a copy of the default session. The new session has the same namespace, database and variables, and is signed in with the same access token. After that token expires, .Fork() returns an error that wraps constants.ErrForkTokenExpired. .Fork() does not copy a token pair. Needs a WebSocket connection.
session, err := db.Fork(ctx)Returns: (*Session, error)
.Sessions()
Lists the sessions attached to the connection, other than the default one, including sessions that this client did not attach. Needs a WebSocket connection.
sessions, err := db.Sessions(ctx)Returns: ([]*Session, error)
.Begin()
Starts an interactive transaction in the default session. Needs a WebSocket connection, and returns constants.ErrTransactionsNotSupported otherwise. See Transactions.
tx, err := db.Begin(ctx)Returns: (*Transaction, error). See Transaction.
Import and export
.Export()
Writes the namespace and database of the default session as a SurrealQL document to w, with POST /export. Works over WebSocket and HTTP, and authenticates with the token the client last received. See Import and export.
err := db.Export(ctx, w, options)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Bounds the request. |
w | io.Writer | Where the method writes the document. The method does not close it. |
options | *ExportOptions | What to export. nilexports everything. |
Returns: error
.Import()
Runs a SurrealQL document in the namespace and database of the default session, with POST /import. The document must start with OPTION IMPORT;. The server does not roll back the statements that succeed. When statements fail, the method returns an *ImportError.
err := db.Import(ctx, document)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Bounds the request. |
document | io.Reader | The SurrealQL to run. The method does not close it. |
Returns: error
Query functions
These are generic package functions. Their s argument is a *DB, a *Session or a *Transaction.
Query
Runs SurrealQL and returns one result for each statement. When any statement fails, the error joins the QueryError of each failed statement. The function still returns the results. See Executing queries.
results, err := surrealdb.Query[TResult](ctx, s, sql, vars)Parameter | Type | Description |
|---|---|---|
TResult | type parameter | The Go type of each statement's result. |
ctx | context.Context | Bounds the request. |
s | *DB | *Session | *Transaction | Where the query runs. |
sql | string | The SurrealQL. |
vars | map[string]any | The variables of the query. Pass nilfor none. |
Returns: (*[]QueryResult[TResult], error). See QueryResult.
results, err := surrealdb.Query[[]Person](ctx, db,
"SELECT * FROM person WHERE age > $min",
map[string]any{"min": 18},
) QueryRaw
Runs a list of statements as one query, and writes each result to its QueryStmt. Each QueryStmt must hold exactly one statement.
err := surrealdb.QueryRaw(ctx, s, queries)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Bounds the request. |
s | *DB | *Session | *Transaction | Where the query runs. |
queries | *[]QueryStmt | The statements. The function writes their results back to them. |
Returns: error
QueryStream
Runs SurrealQL and yields its result frame by frame while it runs, with the query_stream method over WebSocket. Leaving the loop early cancels the query on the server. Over HTTP, or when the server refuses query_stream, the function runs the query with the query method. It then yields the result as frames of the same form. See Streaming results.
for frame, err := range surrealdb.QueryStream[T](ctx, s, sql, vars) {
// ...
}Returns: iter.Seq2[StreamFrame[T], error]. See StreamFrame.
QueryStreamVersion is the revision of the streaming protocol that the SDK reads. When a server announces a later revision, the stream fails with ErrStreamProtocol.
Run
Calls a function with arguments and returns its result. The name has parts joined by ::, such as string::len or fn::greet. It can also be one of the built-ins count, not, rand and sleep. The SDK refuses any other name before it sends a request.
result, err := surrealdb.Run[TResult](ctx, s, name, args...)Returns: (*TResult, error)
length, err := surrealdb.Run[int](ctx, db, "string::len", "SurrealDB") RunVersion
Calls a function at a version, such as the machine learning model ml::house_price at 1.0.0. An empty version is the same as Run.
SurrealDB 4.0 removed SurrealML, so a call with a model name works only against a server on SurrealDB 3.x or earlier. See Upgrading from 3.x to 4.0.
result, err := surrealdb.RunVersion[TResult](ctx, s, name, version, args...)Returns: (*TResult, error)
API
Calls an endpoint defined with DEFINE API, at a path such as /users/123, in the namespace and database of the session. A nil request is a GET without a body. A response with an unsuccessful status is not an error, so check Status. When the body of such a response does not fit TBody, Body is its zero value.
res, err := surrealdb.API[TBody](ctx, s, path, req)Parameter | Type | Description |
|---|---|---|
TBody | type parameter | The Go type of the response body. |
path | string | The path of the endpoint. |
req | *APIRequest | The method, body, headers and query parameters. |
Returns: (*APIResponse[TBody], error). See APIResponse.
GQL
Runs an ISO GQL query with the gql method of the server, and returns one result for each statement, as Query does.
results, err := surrealdb.GQL[TResult](ctx, s, query, vars)Returns: (*[]QueryResult[TResult], error)
Data functions
These generic package functions send a SurrealQL statement with the query RPC method. Their s argument is a *DB, a *Session or a *Transaction. Their what argument is a TableOrRecord: a models.RecordID, a models.Table, a string, or a slice of record IDs or tables. A string is always a table name. A record ID gives one record, or nil when the record does not exist. A table, a range or a slice gives a slice. See Data manipulation.
A failed statement returns an *RPCError that unwraps to a *ServerError.
Select
Selects records.
result, err := surrealdb.Select[TResult](ctx, s, what)Parameter | Type | Description |
|---|---|---|
TResult | type parameter | A record type for a record ID, and a slice for a table, a range or a slice. |
what | TableOrRecord | The record, table or range to select. |
Returns: (*TResult, error)
Create
Creates a record. A record ID, or a table name as a string, gives the created record. A models.Table or a slice gives a slice.
result, err := surrealdb.Create[TResult](ctx, s, what, data)Parameter | Type | Description |
|---|---|---|
what | TableOrRecord | The record ID to create, or the table to create a record in. |
data | any | The content, as a struct or a map. nilcreates a record with no other fields. |
Returns: (*TResult, error)
Insert
Inserts one record or a slice of records into a table. It cannot create a relation.
results, err := surrealdb.Insert[TResult](ctx, s, table, data)Parameter | Type | Description |
|---|---|---|
TResult | type parameter | The type of one record. |
table | models.Table | The table to insert into. |
data | any | One record or a slice of records. |
Returns: (*[]TResult, error)
Update
Replaces the content of existing records, as UPDATE ... CONTENT does. It removes the fields that the data leaves out.
result, err := surrealdb.Update[TResult](ctx, s, what, data)Returns: (*TResult, error)
Upsert
Creates records, or replaces their content when they exist, as UPSERT ... CONTENT does.
result, err := surrealdb.Upsert[TResult](ctx, s, what, data)Returns: (*TResult, error)
Merge
Merges data into existing records, as UPDATE ... MERGE does, and keeps the fields it does not mention.
result, err := surrealdb.Merge[TResult](ctx, s, what, data)Returns: (*TResult, error)
Patch
Applies JSON Patch operations to records, and returns the operations that changed them, as PatchWithResult does with ReturnDiff. Its result fits one record. For a table, use PatchWithResult with a TResult of [][]PatchData.
result, err := surrealdb.Patch(ctx, s, what, patches)Parameter | Type | Description |
|---|---|---|
what | TableOrRecord | The records to patch. |
patches | []PatchData | The JSON Patch operations. |
Returns: (*[]PatchData, error)
PatchWithResult
Applies JSON Patch operations to records. It returns what output asks for: the records after or before the change, the operations that changed them, or nothing. With ReturnNone, the result is nil.
result, err := surrealdb.PatchWithResult[TResult](ctx, s, what, patches, output)Parameter | Type | Description |
|---|---|---|
TResult | type parameter | A record type, a slice of records, []PatchDataor [][]PatchData, to match whatand output. |
patches | []PatchData | The JSON Patch operations. |
output | ReturnMode | ReturnAfter, ReturnBefore, ReturnDiffor ReturnNone. |
Returns: (*TResult, error)
patched, err := surrealdb.PatchWithResult[Person](ctx, db,
models.NewRecordID("person", "tobie"),
[]surrealdb.PatchData{{Op: "replace", Path: "/age", Value: 38}},
surrealdb.ReturnAfter,
) Delete
Deletes records, and returns them as they were before the delete.
result, err := surrealdb.Delete[TResult](ctx, s, what)Returns: (*TResult, error)
Relate
Creates an edge from rel.In to rel.Out in the relation table rel.Relation, with a generated ID and the fields in rel.Data. It ignores the ID of the Relationship. Returns the edge.
result, err := surrealdb.Relate[TResult](ctx, s, rel)Parameter | Type | Description |
|---|---|---|
rel | *Relationship | The edge to create. |
Returns: (*TResult, error)
InsertRelation
Inserts an edge, as INSERT RELATION does. It uses rel.ID if you set it, and generates an ID otherwise. Returns a slice, so pass a slice type, such as []map[string]any or []connection.ResponseID[models.RecordID].
result, err := surrealdb.InsertRelation[TResult](ctx, s, rel)Returns: (*TResult, error)
Live query functions
Live and Kill take a *DB or a *Session, but not a *Transaction, because a live query belongs to a session. Live queries need a WebSocket connection. See Live queries.
Live
Starts a live query on a table, and returns its UUID. When the client reconnects, the live query starts again under the same UUID, in its original namespace and database. When the session is no longer signed in as it was before, the live query ends with ErrLiveQueryEnded instead.
liveID, err := surrealdb.Live(ctx, s, table, diff)Parameter | Type | Description |
|---|---|---|
s | *DB | *Session | The session the live query belongs to. |
table | models.Table | The table to watch. |
diff | bool | With true, each notification holds the JSON Patch operations that changed the record, instead of the record. |
Returns: (*models.UUID, error). See UUID.
Kill
Stops a live query and closes its notification channel.
err := surrealdb.Kill(ctx, s, id)Returns: error
.LiveNotifications()
Returns the notification channel of a live query of the default session. For a live query that the client ended on a reconnect, it returns ErrLiveQueryEnded.
ch, err := db.LiveNotifications(liveQueryID)Returns: (chan connection.Notification, error). See Notification.
.CloseLiveNotifications()
Closes the notification channel of a live query, without stopping the live query on the server.
err := db.CloseLiveNotifications(liveQueryID)Returns: error
Version helpers
MinimumServerVersion and MaximumServerVersion
MinimumServerVersion is "3.3.0", the oldest SurrealDB version the SDK supports, pre-releases included. MaximumServerVersion is "5.0.0", the first version it does not support.
IsVersionSupported
Reports whether the SDK supports a server of the given version, such as "4.0.0", "surrealdb-4.1.2" or "4.1.0-nightly+20261014". It compares only the major, minor and patch numbers.
ok := surrealdb.IsVersionSupported(version)Returns: bool
IsVersionInRange
Reports whether a version is at least minimum and below maximum. Use it, for example, to check whether a server has a feature that a later release added. When the function cannot parse the version or a bound, it returns false.
ok := surrealdb.IsVersionInRange(version, minimum, maximum)Returns: bool
ver, err := db.Version(ctx)
if err == nil && surrealdb.IsVersionInRange(ver.Version, "4.1.0", surrealdb.MaximumServerVersion) {
// use a feature that SurrealDB 4.1 added
}Low-level RPC
Send
Sends an RPC request and decodes the response into res. It accepts only the methods select, create, insert, insert_relation, kill, live, merge, relate, update, upsert, patch, delete and query. It refuses other methods before it sends anything. The res argument is a *connection.RPCResponse[Result].
err := surrealdb.Send[Result](ctx, db, res, method, params...)Returns: error
Availability by connection type
| Feature | WebSocket | HTTP |
|---|---|---|
Query, QueryRaw, Run, API, GQL, the CRUD functions | Yes | Yes |
Authentication, .Use(), .Let(), .Unset(), .Reset() | Yes, kept by the server | Yes, kept by the client |
.Health(), .Version(), .Export(), .Import() | Yes | Yes |
QueryStream | Yes, streamed | Yes, the whole result at once |
Live, Kill, .LiveNotifications() | Yes | No |
.Attach(), .Fork(), .Sessions() | Yes | No: ErrSessionsNotSupported |
.Begin() | Yes | No: ErrTransactionsNotSupported |
Reconnection and .OnStatus() | Yes | Not needed |
See also
Session for the methods of a session
Transaction for the methods of a transaction
Types for the types these functions use
Errors for the error types
Connecting to SurrealDB for connection patterns