Skip to content

API Reference

/

Core

DB

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
import surrealdb "github.com/surrealdb/surrealdb.go/v2"

Source: db.go

Creates a client and connects it. The scheme of the URL chooses the connection: ws:// and wss:// for WebSocket, http:// and https:// for HTTP.

Syntax
db, err := surrealdb.FromEndpointURLString(ctx, connectionURL)

Parameter

Type

Description

ctxcontext.Context

Bounds the connection attempt.

connectionURLstring

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.

Creates a client and connects it, configured by options. With no options, it does what FromEndpointURLString does.

Syntax
db, err := surrealdb.FromEndpointURLStringWithOptions(ctx, connectionURL, opts...)

Returns: (*DB, error)

db, err := surrealdb.FromEndpointURLStringWithOptions(ctx, "ws://localhost:8000",
	surrealdb.WithVersionCheck(true),
	surrealdb.WithTokenRenewal(true),
)

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.

Syntax
db, err := surrealdb.FromConnection(ctx, conn)

Parameter

Type

Description

ctxcontext.Context

Bounds the connection attempt.

connconnection.Connection

The connection. See

Using a custom connection

.

Returns: (*DB, error)

Creates a client from a connection you built, configured by options.

Syntax
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.

An Option configures a client created with FromEndpointURLStringWithOptions or FromConnectionWithOptions.

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.

Syntax
surrealdb.WithVersionCheck(enabled bool) Option

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.

Syntax
surrealdb.WithReconnect(enabled bool) Option

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.

Syntax
surrealdb.WithReconnectAttempts(attempts int) Option

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).

Syntax
surrealdb.WithReconnectDelay(minDelay, maxDelay time.Duration) Option

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.

Syntax
surrealdb.WithTokenRenewal(enabled bool) Option

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.

Syntax
surrealdb.WithTokenExpiryMargin(margin time.Duration) Option

Closes the connection and releases its resources. Later requests return ErrClientClosed.

Syntax
err := db.Close(ctx)

Returns: error

Selects the namespace and database of the default session.

Syntax
err := db.Use(ctx, ns, database)

Parameter

Type

Description

ctxcontext.Context

Bounds the request.

nsstring

The namespace to use.

databasestring

The database to use.

Returns: error

Returns the version, build and timestamp of the server.

Syntax
ver, err := db.Version(ctx)

Returns: (*VersionData, error). See VersionData.

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.

Syntax
err := db.Health(ctx)

Returns: error

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.

Syntax
v := db.CBORVersion()

Returns: connection.CBORVersion

Returns the state of the connection. A client that does not reconnect stays StatusConnected until it closes.

Syntax
status := db.Status()

Returns: ConnectionStatus

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.

Syntax
stop := db.OnStatus(fn func(StatusEvent))

Returns: func(), which stops the calls

Signs in a user. The fields of authData decide the level: root, namespace, database, record, or a bearer key with the key field.

Syntax
token, err := db.SignIn(ctx, authData)

Parameter

Type

Description

ctxcontext.Context

Bounds the request.

authDataany

An

Auth

struct, or a

map[string]any

with the keys

NS

,

DB

,

AC

,

user

,

pass

,

key

, or the fields an access method reads.

Returns: (string, error), where the string is the JWT

Root user
token, err := db.SignIn(ctx, surrealdb.Auth{
	Username: "root",
	Password: "secret",
})
Record user
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().

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.

Syntax
tokens, err := db.SignInWithRefresh(ctx, authData)

Returns: (*Tokens, error). See Tokens.

Signs up a record user through the SIGNUP clause of an access method, and signs them in.

Syntax
token, err := db.SignUp(ctx, authData)

Returns: (string, error), where the string is the JWT

Signs up a record user through an access method defined WITH REFRESH, and returns an access token and a refresh token.

Syntax
tokens, err := db.SignUpWithRefresh(ctx, authData)

Returns: (*Tokens, error)

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.

Syntax
newTokens, err := db.Refresh(ctx, tokens)

Parameter

Type

Description

ctxcontext.Context

Bounds the request.

tokensTokens

The pair to exchange.

Returns: (*Tokens, error)

Revokes the refresh token of a pair. After that, you cannot refresh the pair. The session stays signed in.

Syntax
err := db.Revoke(ctx, tokens)

Returns: error

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.

Syntax
pair := db.Tokens()

Returns: *Tokens

Authenticates the connection with a JWT, such as a token from an earlier sign-in or one that a TYPE JWT access method verifies.

Syntax
err := db.Authenticate(ctx, token)

Returns: error

Signs the session out. The namespace, database and variables stay as they are.

Syntax
err := db.Invalidate(ctx)

Returns: error

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.

Syntax
err := db.Reset(ctx)

Returns: error

Returns the record of the signed-in record user, as SELECT * FROM $auth does. Table permissions apply.

Syntax
info, err := db.Info(ctx)

Returns: (map[string]any, error)

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.

Syntax
err := db.Let(ctx, key, val)

Parameter

Type

Description

ctxcontext.Context

Bounds the request.

keystring

The name of the variable, without

$

.

valany

The value.

Returns: error

Removes a variable from the default session.

Syntax
err := db.Unset(ctx, key)

Returns: error

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.

Syntax
session, err := db.Attach(ctx)

Returns: (*Session, error). See Session.

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.

Syntax
session, err := db.Fork(ctx)

Returns: (*Session, error)

Lists the sessions attached to the connection, other than the default one, including sessions that this client did not attach. Needs a WebSocket connection.

Syntax
sessions, err := db.Sessions(ctx)

Returns: ([]*Session, error)

Starts an interactive transaction in the default session. Needs a WebSocket connection, and returns constants.ErrTransactionsNotSupported otherwise. See Transactions.

Syntax
tx, err := db.Begin(ctx)

Returns: (*Transaction, error). See Transaction.

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.

Syntax
err := db.Export(ctx, w, options)

Parameter

Type

Description

ctxcontext.Context

Bounds the request.

wio.Writer

Where the method writes the document. The method does not close it.

options*ExportOptions

What to export.

nil

exports everything.

Returns: error

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.

Syntax
err := db.Import(ctx, document)

Parameter

Type

Description

ctxcontext.Context

Bounds the request.

documentio.Reader

The SurrealQL to run. The method does not close it.

Returns: error

These are generic package functions. Their s argument is a *DB, a *Session or a *Transaction.

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.

Syntax
results, err := surrealdb.Query[TResult](ctx, s, sql, vars)

Parameter

Type

Description

TResult

type parameter

The Go type of each statement's result.

ctxcontext.Context

Bounds the request.

s*DB | *Session | *Transaction

Where the query runs.

sqlstring

The SurrealQL.

varsmap[string]any

The variables of the query. Pass

nil

for 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},
)

Runs a list of statements as one query, and writes each result to its QueryStmt. Each QueryStmt must hold exactly one statement.

Syntax
err := surrealdb.QueryRaw(ctx, s, queries)

Parameter

Type

Description

ctxcontext.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

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.

Syntax
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.

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.

Syntax
result, err := surrealdb.Run[TResult](ctx, s, name, args...)

Returns: (*TResult, error)

length, err := surrealdb.Run[int](ctx, db, "string::len", "SurrealDB")

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.

Note

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.

Syntax
result, err := surrealdb.RunVersion[TResult](ctx, s, name, version, args...)

Returns: (*TResult, error)

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.

Syntax
res, err := surrealdb.API[TBody](ctx, s, path, req)

Parameter

Type

Description

TBody

type parameter

The Go type of the response body.

pathstring

The path of the endpoint.

req*APIRequest

The method, body, headers and query parameters.

Returns: (*APIResponse[TBody], error). See APIResponse.

Runs an ISO GQL query with the gql method of the server, and returns one result for each statement, as Query does.

Syntax
results, err := surrealdb.GQL[TResult](ctx, s, query, vars)

Returns: (*[]QueryResult[TResult], error)

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.

Selects records.

Syntax
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.

whatTableOrRecord

The record, table or range to select.

Returns: (*TResult, error)

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.

Syntax
result, err := surrealdb.Create[TResult](ctx, s, what, data)

Parameter

Type

Description

whatTableOrRecord

The record ID to create, or the table to create a record in.

dataany

The content, as a struct or a map.

nil

creates a record with no other fields.

Returns: (*TResult, error)

Inserts one record or a slice of records into a table. It cannot create a relation.

Syntax
results, err := surrealdb.Insert[TResult](ctx, s, table, data)

Parameter

Type

Description

TResult

type parameter

The type of one record.

tablemodels.Table

The table to insert into.

dataany

One record or a slice of records.

Returns: (*[]TResult, error)

Replaces the content of existing records, as UPDATE ... CONTENT does. It removes the fields that the data leaves out.

Syntax
result, err := surrealdb.Update[TResult](ctx, s, what, data)

Returns: (*TResult, error)

Creates records, or replaces their content when they exist, as UPSERT ... CONTENT does.

Syntax
result, err := surrealdb.Upsert[TResult](ctx, s, what, data)

Returns: (*TResult, error)

Merges data into existing records, as UPDATE ... MERGE does, and keeps the fields it does not mention.

Syntax
result, err := surrealdb.Merge[TResult](ctx, s, what, data)

Returns: (*TResult, error)

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.

Syntax
result, err := surrealdb.Patch(ctx, s, what, patches)

Parameter

Type

Description

whatTableOrRecord

The records to patch.

patches[]PatchData

The JSON Patch operations.

Returns: (*[]PatchData, error)

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.

Syntax
result, err := surrealdb.PatchWithResult[TResult](ctx, s, what, patches, output)

Parameter

Type

Description

TResult

type parameter

A record type, a slice of records,

[]PatchData

or

[][]PatchData

, to match

what

and

output

.

patches[]PatchData

The JSON Patch operations.

outputReturnModeReturnAfter

,

ReturnBefore

,

ReturnDiff

or

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,
)

Deletes records, and returns them as they were before the delete.

Syntax
result, err := surrealdb.Delete[TResult](ctx, s, what)

Returns: (*TResult, error)

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.

Syntax
result, err := surrealdb.Relate[TResult](ctx, s, rel)

Parameter

Type

Description

rel*Relationship

The edge to create.

Returns: (*TResult, error)

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].

Syntax
result, err := surrealdb.InsertRelation[TResult](ctx, s, rel)

Returns: (*TResult, error)

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.

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.

Syntax
liveID, err := surrealdb.Live(ctx, s, table, diff)

Parameter

Type

Description

s*DB | *Session

The session the live query belongs to.

tablemodels.Table

The table to watch.

diffbool

With

true

, each notification holds the JSON Patch operations that changed the record, instead of the record.

Returns: (*models.UUID, error). See UUID.

Stops a live query and closes its notification channel.

Syntax
err := surrealdb.Kill(ctx, s, id)

Returns: error

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.

Syntax
ch, err := db.LiveNotifications(liveQueryID)

Returns: (chan connection.Notification, error). See Notification.

Closes the notification channel of a live query, without stopping the live query on the server.

Syntax
err := db.CloseLiveNotifications(liveQueryID)

Returns: error

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.

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.

Syntax
ok := surrealdb.IsVersionSupported(version)

Returns: bool

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.

Syntax
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
}

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].

Syntax
err := surrealdb.Send[Result](ctx, db, res, method, params...)

Returns: error

FeatureWebSocketHTTP
Query, QueryRaw, Run, API, GQL, the CRUD functionsYesYes
Authentication, .Use(), .Let(), .Unset(), .Reset()Yes, kept by the serverYes, kept by the client
.Health(), .Version(), .Export(), .Import()YesYes
QueryStreamYes, streamedYes, the whole result at once
Live, Kill, .LiveNotifications()YesNo
.Attach(), .Fork(), .Sessions()YesNo: ErrSessionsNotSupported
.Begin()YesNo: ErrTransactionsNotSupported
Reconnection and .OnStatus()YesNot needed

Was this page helpful?

Last updated