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).
db, err := surrealdb.FromEndpointURLString(ctx, connectionURL)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for canceling the connection attempt. |
connectionURL | string | The endpoint URL. Supported schemes: ws://, wss://, http://, https://. |
Returns: (*DB, error)
Examples
db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000")db, err := surrealdb.FromEndpointURLString(ctx, "https://cloud.surrealdb.com") FromConnection
Creates a new *DB from a custom connection.Connection implementation. Calls .Connect(ctx) automatically.
db, err := surrealdb.FromConnection(ctx, conn)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for canceling the connection attempt. |
conn | connection.Connection | A connection implementation (e.g., gorillaws.New(conf)or http.New(conf)). |
Returns: (*DB, error)
Connection methods
.Close()
Closes the underlying connection and releases resources.
err := db.Close(ctx)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the close operation. |
Returns: error
.Use()
Selects the namespace and database to use for subsequent operations.
err := db.Use(ctx, ns, database)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the operation. |
ns | string | The namespace to use. |
database | string | The database to use. |
Returns: error
.Version()
Returns version information about the connected SurrealDB instance.
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).
token, err := db.SignIn(ctx, authData)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the operation. |
authData | any | An Authstruct or map[string]anywith credentials. |
Returns: (string, error) — the JWT token string
Examples
token, err := db.SignIn(ctx, surrealdb.Auth{
Username: "root",
Password: "root",
})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.
tokens, err := db.SignInWithRefresh(ctx, authData)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the operation. |
authData | any | Credentials as map[string]any. Use "refresh"key for token refresh. |
Returns: (*Tokens, error) — see Tokens
Examples
tokens, err := db.SignInWithRefresh(ctx, map[string]any{
"NS": "my_ns", "DB": "my_db", "AC": "user_access",
"user": "tobie", "pass": "s3cret",
})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.
token, err := db.SignUp(ctx, authData)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the operation. |
authData | any | An Authstruct or map[string]anywith 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.
tokens, err := db.SignUpWithRefresh(ctx, authData)Returns: (*Tokens, error) — see Tokens
.Authenticate()
Authenticates the connection with a JWT token.
err := db.Authenticate(ctx, token)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the operation. |
token | string | The JWT token to authenticate with. |
Returns: error
.Invalidate()
Invalidates the current authentication, returning the connection to an unauthenticated state.
err := db.Invalidate(ctx)Returns: error
.Info()
Returns the record of the currently authenticated user.
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.
err := db.Let(ctx, key, val)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the operation. |
key | string | The variable name (without $prefix). |
val | any | The value to assign. |
Returns: error
.Unset()
Removes a previously defined variable from the connection.
err := db.Unset(ctx, key)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the operation. |
key | string | The 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+).
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+).
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.
results, err := surrealdb.Query[TResult](ctx, s, sql, vars)Parameter | Type | Description |
|---|---|---|
TResult | type parameter | The expected result type for each statement. |
ctx | context.Context | Context for the operation. |
s | *DB | *Session | *Transaction | The sender to execute the query on. |
sql | string | The SurrealQL query string. |
vars | map[string]any | Variables to bind into the query. Pass nilfor 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.
err := surrealdb.QueryRaw(ctx, s, queries)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the operation. |
s | *DB | *Session | *Transaction | The sender to execute the query on. |
queries | *[]QueryStmt | A pointer to a slice of QueryStmtobjects. 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.
result, err := surrealdb.Select[TResult](ctx, s, what)Returns: (*TResult, error)
Create
Creates a new record.
result, err := surrealdb.Create[TResult](ctx, s, what, data)Returns: (*TResult, error)
Insert
Inserts one or more records into a table.
results, err := surrealdb.Insert[TResult](ctx, s, table, data)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the operation. |
s | *DB | *Session | *Transaction | The sender. |
table | models.Table | The table to insert into. |
data | any | A single record or slice of records to insert. |
Returns: (*[]TResult, error)
Update
Replaces the entire content of a record (like a PUT).
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.
result, err := surrealdb.Upsert[TResult](ctx, s, what, data)Returns: (*TResult, error)
Merge
Merges data into an existing record, preserving unmentioned fields.
result, err := surrealdb.Merge[TResult](ctx, s, what, data)Returns: (*TResult, error)
Patch
Applies JSON Patch operations to a record or table.
result, err := surrealdb.Patch(ctx, s, what, patches)Returns: (*[]PatchData, error)
Delete
Removes records from the database.
result, err := surrealdb.Delete[TResult](ctx, s, what)Returns: (*TResult, error)
Relate
Creates a relationship between two records with an auto-generated ID.
result, err := surrealdb.Relate[TResult](ctx, s, rel)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the operation. |
s | *DB | *Session | *Transaction | The sender. |
rel | *Relationship | The relationship to create. See Relationship. |
Returns: (*TResult, error)
InsertRelation
Inserts a relation record, optionally with a specified ID.
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.
liveID, err := surrealdb.Live(ctx, s, table, diff)Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context for the operation. |
s | *DB | *Session | The sender (not *Transaction). |
table | models.Table | The table to watch. |
diff | bool | If true, notifications contain JSON Patch diffs. |
Returns: (*models.UUID, error)
Kill
Terminates a live query and closes its notification channel.
err := surrealdb.Kill(ctx, s, id)Returns: error
.LiveNotifications()
Returns the notification channel for a live query.
ch, err := db.LiveNotifications(liveQueryID)Returns: (chan connection.Notification, error)
.CloseLiveNotifications()
Closes the notification channel without killing the server-side live query.
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.
err := surrealdb.Send[Result](ctx, db, res, method, params...)Returns: error
See also
Session for session management reference
Transaction for transaction reference
Types for type definitions used by these methods
Errors for error types
Connecting to SurrealDB for connection patterns