DB

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

Constructors

FromEndpointURLString

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)
ParameterTypeDescription
ctx context.ContextContext for canceling the connection attempt.
connectionURL stringThe endpoint URL. Supported schemes: ws://, wss://, http://, https://.

Returns: (*DB, error)

Examples

WebSocket

db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000")

HTTPS

db, err := surrealdb.FromEndpointURLString(ctx, "https://cloud.surrealdb.com")

FromConnection

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

Syntax

db, err := surrealdb.FromConnection(ctx, conn)
ParameterTypeDescription
ctx context.ContextContext for canceling the connection attempt.
conn connection.ConnectionA connection implementation (e.g., gorillaws.New(conf) or http.New(conf)).

Returns: (*DB, error)

Connection Methods

.Close()

Closes the underlying connection and releases resources.

Syntax

err := db.Close(ctx)
ParameterTypeDescription
ctx context.ContextContext for the close operation.

Returns: error

.Use()

Selects the namespace and database to use for subsequent operations.

Syntax

err := db.Use(ctx, ns, database)
ParameterTypeDescription
ctx context.ContextContext for the operation.
ns stringThe namespace to use.
database stringThe database to use.

Returns: error

.Version()

Returns version information about the connected SurrealDB instance.

Syntax

ver, err := db.Version(ctx)

Returns: (*VersionData, error) — see VersionData

Examples

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

Authentication Methods

.SignIn()

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)
ParameterTypeDescription
ctx context.ContextContext for the operation.
authData anyAn Auth struct or map[string]any with credentials.

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

Examples

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

.SignInWithRefresh()

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)
ParameterTypeDescription
ctx context.ContextContext for the operation.
authData anyCredentials as map[string]any. Use "refresh" key for token refresh.

Returns: (*Tokens, error) — see Tokens

Examples

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

.SignUp()

Signs up a new record user.

Syntax

token, err := db.SignUp(ctx, authData)
ParameterTypeDescription
ctx context.ContextContext for the operation.
authData anyAn Auth struct or map[string]any with signup credentials.

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

.SignUpWithRefresh()

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

.Authenticate()

Authenticates the connection with a JWT token.

Syntax

err := db.Authenticate(ctx, token)
ParameterTypeDescription
ctx context.ContextContext for the operation.
token stringThe JWT token to authenticate with.

Returns: error

.Invalidate()

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

Syntax

err := db.Invalidate(ctx)

Returns: error

.Info()

Returns the record of the currently authenticated user.

Syntax

info, err := db.Info(ctx)

Returns: (map[string]any, error)

Variables

.Let()

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

Syntax

err := db.Let(ctx, key, val)
ParameterTypeDescription
ctx context.ContextContext for the operation.
key stringThe variable name (without $ prefix).
val anyThe value to assign.

Returns: error

.Unset()

Removes a previously defined variable from the connection.

Syntax

err := db.Unset(ctx, key)
ParameterTypeDescription
ctx context.ContextContext for the operation.
key stringThe variable name to remove.

Returns: error

Sessions and Transactions

.Attach()

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

.Begin()

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

Query Functions

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

Query

Executes a SurrealQL query string and returns typed results.

Syntax

results, err := surrealdb.Query[TResult](ctx, s, sql, vars)
ParameterTypeDescription
TResulttype parameterThe expected result type for each statement.
ctx context.ContextContext for the operation.
s *DB | *Session | *TransactionThe sender to execute the query on.
sql stringThe SurrealQL query string.
vars map[string]anyVariables to bind into the query. Pass nil for no variables.

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

Examples

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

QueryRaw

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

Syntax

err := surrealdb.QueryRaw(ctx, s, queries)
ParameterTypeDescription
ctx context.ContextContext for the operation.
s *DB | *Session | *TransactionThe sender to execute the query on.
queries *[]QueryStmtA pointer to a slice of QueryStmt objects. Results are written back to each statement.

Returns: error

Data Functions

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

Select

Retrieves records from the database.

Syntax

result, err := surrealdb.Select[TResult](ctx, s, what)
ParameterTypeDescription
TResulttype parameterUse a slice type for tables, a single type for record IDs.
ctx context.ContextContext for the operation.
s *DB | *Session | *TransactionThe sender.
what string | Table | RecordIDThe table or record to select.

Returns: (*TResult, error)

Create

Creates a new record.

Syntax

result, err := surrealdb.Create[TResult](ctx, s, what, data)
ParameterTypeDescription
ctx context.ContextContext for the operation.
s *DB | *Session | *TransactionThe sender.
what string | Table | RecordIDThe table or record ID to create.
data anyThe record data (struct or map).

Returns: (*TResult, error)

Insert

Inserts one or more records into a table.

Syntax

results, err := surrealdb.Insert[TResult](ctx, s, table, data)
ParameterTypeDescription
ctx context.ContextContext for the operation.
s *DB | *Session | *TransactionThe sender.
table models.TableThe table to insert into.
data anyA single record or slice of records to insert.

Returns: (*[]TResult, error)

Update

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

Syntax

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

Returns: (*TResult, error)

Upsert

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)

Merge

Merges data into an existing record, preserving unmentioned fields.

Syntax

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

Returns: (*TResult, error)

Patch

Applies JSON Patch operations to a record or table.

Syntax

result, err := surrealdb.Patch(ctx, s, what, patches)
ParameterTypeDescription
ctx context.ContextContext for the operation.
s *DB | *Session | *TransactionThe sender.
what string | Table | RecordIDThe table or record to patch.
patches []PatchDataJSON Patch operations. See PatchData.

Returns: (*[]PatchData, error)

Delete

Removes records from the database.

Syntax

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

Returns: (*TResult, error)

Relate

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

Syntax

result, err := surrealdb.Relate[TResult](ctx, s, rel)
ParameterTypeDescription
ctx context.ContextContext for the operation.
s *DB | *Session | *TransactionThe sender.
rel *RelationshipThe relationship to create. See Relationship.

Returns: (*TResult, error)

InsertRelation

Inserts a relation record, optionally with a specified ID.

Syntax

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

Returns: (*TResult, error)

Live Query Methods

Live

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

Syntax

liveID, err := surrealdb.Live(ctx, s, table, diff)
ParameterTypeDescription
ctx context.ContextContext for the operation.
s *DB | *SessionThe sender (not *Transaction).
table models.TableThe table to watch.
diff boolIf true, notifications contain JSON Patch diffs.

Returns: (*models.UUID, error)

Kill

Terminates a live query and closes its notification channel.

Syntax

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

Returns: error

.LiveNotifications()

Returns the notification channel for a live query.

Syntax

ch, err := db.LiveNotifications(liveQueryID)

Returns: (chan connection.Notification, error)

.CloseLiveNotifications()

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

Syntax

err := db.CloseLiveNotifications(liveQueryID)

Returns: error

Low-level RPC

Send

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

See Also