• Start

API Reference

/

Core

DB

The DB struct is the main entry point for connecting to and interacting with a SurrealDB instance from Go.

The DB struct is the main client for interacting with SurrealDB. It holds the underlying connection and provides methods for authentication, namespace selection, and live query management. Data operations are performed through generic top-level functions that accept *DB as a parameter.

Source: db.go

Creates a new *DB and connects to a SurrealDB instance. The URL scheme determines the connection type (WebSocket or HTTP).

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

Parameter

Type

Description

ctxcontext.Context

Context for canceling the connection attempt.

connectionURLstring

The endpoint URL. Supported schemes:

ws://

,

wss://

,

http://

,

https://

.

Returns: (*DB, error)

WebSocket
db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000")
HTTPS
db, err := surrealdb.FromEndpointURLString(ctx, "https://cloud.surrealdb.com")

Creates a new *DB from a custom connection.Connection implementation. Calls .Connect(ctx) automatically.

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

Parameter

Type

Description

ctxcontext.Context

Context for canceling the connection attempt.

connconnection.Connection

A connection implementation (e.g.,

gorillaws.New(conf)

or

http.New(conf)

).

Returns: (*DB, error)

Closes the underlying connection and releases resources.

Syntax
err := db.Close(ctx)

Parameter

Type

Description

ctxcontext.Context

Context for the close operation.

Returns: error

Selects the namespace and database to use for subsequent operations.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

nsstring

The namespace to use.

databasestring

The database to use.

Returns: error

Returns version information about the connected SurrealDB instance.

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

Returns: (*VersionData, error), see VersionData

ver, err := db.Version(ctx)
if err != nil {
    log.Fatal(err)
}
fmt.Println(ver.Version)

Signs in an existing user. The fields provided in authData determine the authentication level (root, namespace, database, or record).

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

authDataany

An

Auth

struct or

map[string]any

with credentials.

Returns: (string, error) — the JWT token string

Root signin
token, err := db.SignIn(ctx, surrealdb.Auth{
    Username: "root",
    Password: "root",
})
Record signin
token, err := db.SignIn(ctx, map[string]any{
    "NS": "my_ns", "DB": "my_db", "AC": "user_access",
    "user": "tobie", "pass": "s3cret",
})

Signs in using a TYPE RECORD access method with WITH REFRESH enabled. Returns both an access token and a refresh token. SurrealDB v3+ only.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

authDataany

Credentials as

map[string]any

. Use

"refresh"

key for token refresh.

Returns: (*Tokens, error) — see Tokens

Initial signin
tokens, err := db.SignInWithRefresh(ctx, map[string]any{
    "NS": "my_ns", "DB": "my_db", "AC": "user_access",
    "user": "tobie", "pass": "s3cret",
})
Refresh
newTokens, err := db.SignInWithRefresh(ctx, map[string]any{
    "NS": "my_ns", "DB": "my_db", "AC": "user_access",
    "refresh": tokens.Refresh,
})

Signs up a new record user.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

authDataany

An

Auth

struct or

map[string]any

with signup credentials.

Returns: (string, error) — the JWT token string

Signs up using a TYPE RECORD access method with WITH REFRESH enabled. SurrealDB v3+ only.

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

Returns: (*Tokens, error) — see Tokens

Authenticates the connection with a JWT token.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

tokenstring

The JWT token to authenticate with.

Returns: error

Invalidates the current authentication, returning the connection to an unauthenticated state.

Syntax
err := db.Invalidate(ctx)

Returns: error

Returns the record of the currently authenticated user.

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

Returns: (map[string]any, error)

Defines a variable on the connection that can be used in subsequent queries.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

keystring

The variable name (without

$

prefix).

valany

The value to assign.

Returns: error

Removes a previously defined variable from the connection.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

keystring

The variable name to remove.

Returns: error

Creates a new session on the WebSocket connection. Sessions are only supported on WebSocket connections (SurrealDB v3+).

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

Returns: (*Session, error) — see Session

Starts a new interactive transaction on the default session. Transactions are only supported on WebSocket connections (SurrealDB v3+).

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

Returns: (*Transaction, error) — see Transaction

These are top-level generic functions that accept *DB, *Session, or *Transaction as the s parameter.

Executes a SurrealQL query string and returns typed results.

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

Parameter

Type

Description

TResult

type parameter

The expected result type for each statement.

ctxcontext.Context

Context for the operation.

s*DB | *Session | *Transaction

The sender to execute the query on.

sqlstring

The SurrealQL query string.

varsmap[string]any

Variables to bind into the query. Pass

nil

for no variables.

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

results, err := surrealdb.Query[[]Person](ctx, db,
    "SELECT * FROM persons WHERE age > $min",
    map[string]any{"min": 18},
)

Composes and executes a batch of query statements with per-statement results.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

s*DB | *Session | *Transaction

The sender to execute the query on.

queries*[]QueryStmt

A pointer to a slice of

QueryStmt

objects. Results are written back to each statement.

Returns: error

These are top-level generic functions that accept *DB, *Session, or *Transaction as the s parameter.

Retrieves records from the database.

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

Parameter

Type

Description

TResult

type parameter

Use a slice type for tables, a single type for record IDs.

ctxcontext.Context

Context for the operation.

s*DB | *Session | *Transaction

The sender.

whatstring |Table|RecordID

The table or record to select.

Returns: (*TResult, error)

Creates a new record.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

s*DB | *Session | *Transaction

The sender.

whatstring |Table|RecordID

The table or record ID to create.

dataany

The record data (struct or map).

Returns: (*TResult, error)

Inserts one or more records into a table.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

s*DB | *Session | *Transaction

The sender.

tablemodels.Table

The table to insert into.

dataany

A single record or slice of records to insert.

Returns: (*[]TResult, error)

Replaces the entire content of a record (like a PUT).

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

Returns: (*TResult, error)

Creates a record if it does not exist, or replaces it entirely.

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

Returns: (*TResult, error)

Merges data into an existing record, preserving unmentioned fields.

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

Returns: (*TResult, error)

Applies JSON Patch operations to a record or table.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

s*DB | *Session | *Transaction

The sender.

whatstring |Table|RecordID

The table or record to patch.

patches[]PatchData

JSON Patch operations. See

PatchData

.

Returns: (*[]PatchData, error)

Removes records from the database.

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

Returns: (*TResult, error)

Creates a relationship between two records with an auto-generated ID.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

s*DB | *Session | *Transaction

The sender.

rel*Relationship

The relationship to create. See

Relationship

.

Returns: (*TResult, error)

Inserts a relation record, optionally with a specified ID.

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

Returns: (*TResult, error)

Starts a live query on a table. Only available on *DB and *Session.

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

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

s*DB | *Session

The sender (not

*Transaction

).

tablemodels.Table

The table to watch.

diffbool

If

true

, notifications contain JSON Patch diffs.

Returns: (*models.UUID, error)

Terminates a live query and closes its notification channel.

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

Returns: error

Returns the notification channel for a live query.

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

Returns: (chan connection.Notification, error)

Closes the notification channel without killing the server-side live query.

Syntax
err := db.CloseLiveNotifications(liveQueryID)

Returns: error

Sends a raw RPC request to SurrealDB. Limited to data methods: select, create, insert, insert_relation, kill, live, merge, relate, update, upsert, patch, delete, query.

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

Returns: error

Was this page helpful?