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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for canceling the connection attempt. |
connectionURL required | string | The 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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for canceling the connection attempt. |
conn required | 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.
Syntax
err := db.Close(ctx)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the close operation. |
Returns: error
.Use()
Selects the namespace and database to use for subsequent operations.
Syntax
err := db.Use(ctx, ns, database)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
ns required | string | The namespace to use. |
database required | string | The 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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
authData required | any | An 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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
authData required | any | Credentials 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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
authData required | any | An 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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
token required | string | The 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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
key required | string | The variable name (without $ prefix). |
val required | any | The value to assign. |
Returns: error
.Unset()
Removes a previously defined variable from the connection.
Syntax
err := db.Unset(ctx, key)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
key required | 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+).
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)
| Parameter | Type | Description |
|---|
TResult | type parameter | The expected result type for each statement. |
ctx required | context.Context | Context for the operation. |
s required | *DB | *Session | *Transaction | The sender to execute the query on. |
sql required | string | The SurrealQL query string. |
vars required | map[string]any | Variables 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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
s required | *DB | *Session | *Transaction | The sender to execute the query on. |
queries required | *[]QueryStmt | A 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)
| Parameter | Type | Description |
|---|
TResult | type parameter | Use a slice type for tables, a single type for record IDs. |
ctx required | context.Context | Context for the operation. |
s required | *DB | *Session | *Transaction | The sender. |
what required | string | Table | RecordID | The table or record to select. |
Returns: (*TResult, error)
Create
Creates a new record.
Syntax
result, err := surrealdb.Create[TResult](ctx, s, what, data)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
s required | *DB | *Session | *Transaction | The sender. |
what required | string | Table | RecordID | The table or record ID to create. |
data required | any | The 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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
s required | *DB | *Session | *Transaction | The sender. |
table required | models.Table | The table to insert into. |
data required | any | A 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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
s required | *DB | *Session | *Transaction | The sender. |
what required | string | Table | RecordID | The table or record to patch. |
patches required | []PatchData | JSON 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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
s required | *DB | *Session | *Transaction | The sender. |
rel required | *Relationship | The 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)
| Parameter | Type | Description |
|---|
ctx required | context.Context | Context for the operation. |
s required | *DB | *Session | The sender (not *Transaction). |
table required | models.Table | The table to watch. |
diff required | bool | If 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