# SurrealDB documentation - Go SDK

> Quickstart, concepts and API reference. This is one of the bundles the SurrealDB documentation is split into. The page index at https://surrealdb.com/docs/llms.txt lists every bundle, and https://surrealdb.com/docs/llms-full.txt holds every page. Each page starts with a "Source:" line naming its canonical URL, and every page is also available individually by appending `.md` to its URL. In code examples, a fenced block whose title contains "output" holds the result of the block above it rather than runnable code, and a qualifier such as "Example output" or "Possible output" means the value shown is one of several possible ones. Inside a block, a "//-" comment marks a value the statement above it returned, while "--" is an ordinary comment.

---

Source: https://surrealdb.com/docs/reference/golang

# Go SDK

The official SurrealDB SDK for Go 1.24 and later, version 2, which supports SurrealDB 3.3 to 4.x. Generic query and CRUD functions over WebSocket or HTTP, cbor.2, automatic reconnection, token renewal, live queries, sessions, interactive transactions, streaming results, and import and export.

The SurrealDB SDK for Go lets you connect to SurrealDB from servers, command-line tools, APIs and other Go programs. It connects to a remote instance over WebSocket or HTTP and sends SurrealQL as CBOR.

Queries and record operations are generic functions, such as `surrealdb.Query[T]` and `surrealdb.Select[T]`. Each one decodes the result into the Go type that you give.

Use the SDK to run queries, read and write records, and sign users in. You can also keep their tokens fresh, receive changes with live queries, and group statements in interactive transactions.

> [!IMPORTANT]
> The SDK requires Go `1.24` or later. It is available as a [Go module](https://pkg.go.dev/github.com/surrealdb/surrealdb.go/v2), and its module path is `github.com/surrealdb/surrealdb.go/v2`.

> [!NOTE]
> The latest version of the SDK is `v2.0.1`. It works with SurrealDB 3.3 and later 3.x releases, and with SurrealDB 4.x. The current SurrealDB release is `v4.0.1`.

Before you upgrade a project from version 1 of the SDK, read [Migrating to Go SDK 2.x](/docs/reference/golang/migrating-to-2x.md). Version 2 changes the module path, the supported server versions, and how the SDK sends some Go values to the server.

## Getting started

- [Installation](/docs/reference/golang/installation.md) - Add the SDK to your Go module.

- [Getting started guide](/docs/languages/golang.md) - Connect to SurrealDB and run your first queries.

- [Migrating to 2.x](/docs/reference/golang/migrating-to-2x.md) - Move a project from version 1 of the SDK to version 2.

## Learn

- [Concepts](/docs/reference/golang/concepts/connecting-to-surrealdb.md) - Guides for connecting, authenticating, querying, and working with data.

- [API reference](/docs/reference/golang/api/core/db.md) - Complete reference for the SDK's functions, methods, types, and errors.

## Concepts

- [Connecting to SurrealDB](/docs/reference/golang/concepts/connecting-to-surrealdb.md) - open a connection over WebSocket or HTTP, with options and a version check
- [Authentication](/docs/reference/golang/concepts/authentication.md) - sign up, sign in, and keep a token fresh
- [Executing queries](/docs/reference/golang/concepts/executing-queries.md) - send SurrealQL, call functions and `DEFINE API` endpoints
- [Data manipulation](/docs/reference/golang/concepts/data-manipulation.md) - create, select, update, upsert, patch, relate and delete records
- [Live queries](/docs/reference/golang/concepts/live-queries.md) - receive changes as they happen
- [Error handling](/docs/reference/golang/concepts/error-handling.md) - what a failure looks like, and how to check it
- [Value types](/docs/reference/golang/concepts/value-types.md) - how SurrealDB's types map onto Go ones
- [Multiple sessions](/docs/reference/golang/concepts/multiple-sessions.md) - run isolated sessions over a single connection
- [Transactions](/docs/reference/golang/concepts/transactions.md) - run statements one at a time, then commit or cancel
- [Reliable connections](/docs/reference/golang/concepts/reliable-connections.md) - reconnect automatically and restore the session
- [Query builder](/docs/reference/golang/concepts/query-builder.md) - build SurrealQL with bound parameters
- [Streaming results](/docs/reference/golang/concepts/streaming.md) - read the records of a large query as they arrive
- [Import and export](/docs/reference/golang/concepts/import-and-export.md) - back up and restore a database as SurrealQL

## Contributing

To contribute to the SDK code, submit an Issue or Pull Request in the [surrealdb.go](https://github.com/surrealdb/surrealdb.go) repository. To contribute to this documentation, submit an Issue or Pull Request in the [docs.surrealdb.com](https://github.com/surrealdb/docs.surrealdb.com) repository.

## Sources

- [GitHub repository](https://github.com/surrealdb/surrealdb.go)
- [Go package documentation](https://pkg.go.dev/github.com/surrealdb/surrealdb.go/v2)
- [Releases](https://github.com/surrealdb/surrealdb.go/releases)

---

Source: https://surrealdb.com/docs/reference/golang/api/core/db

# DB

Reference for the DB client of the SurrealDB Go SDK 2.x and the package functions that take it - constructors and options, connection, authentication, variables, sessions, transactions, import and export, Query, QueryRaw, QueryStream, Run, API, GQL, the CRUD functions, PatchWithResult, live queries, version helpers and Send.

`DB` is the client of the Go SDK. It holds the connection and the default session, and has methods for connecting, [authentication](/docs/reference/golang/concepts/authentication.md), 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`](/docs/reference/golang/api/core/session.md) or a [`*Transaction`](/docs/reference/golang/api/core/transaction.md) as their `s` argument. This page is the reference for both. For explanations and longer examples, follow the links to the concept pages.

```go title="Import"
import surrealdb "github.com/surrealdb/surrealdb.go/v2"
```

**Source:** [db.go](https://github.com/surrealdb/surrealdb.go/blob/main/db.go)

---

## Constructors

### `FromEndpointURLString` {#fromendpointurlstring}

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

```go title="Syntax"
db, err := surrealdb.FromEndpointURLString(ctx, connectionURL)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>ctx</code> _(required)_</td>
            <td><code>context.Context</code></td>
            <td>Bounds the connection attempt.</td>
        </tr>
        <tr>
            <td><code>connectionURL</code> _(required)_</td>
            <td><code>string</code></td>
            <td>The address of the server, such as <code>ws://localhost:8000</code>.</td>
        </tr>
    </tbody>
</table>

**Returns:** `(*DB, error)`

```go
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](/docs/reference/golang/concepts/connecting-to-surrealdb.md).

### `FromEndpointURLStringWithOptions` {#fromendpointurlstringwithoptions}

Creates a client and connects it, configured by [options](#options). With no options, it does what `FromEndpointURLString` does.

```go title="Syntax"
db, err := surrealdb.FromEndpointURLStringWithOptions(ctx, connectionURL, opts...)
```

**Returns:** `(*DB, error)`

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

### `FromConnection` {#fromconnection}

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.

```go title="Syntax"
db, err := surrealdb.FromConnection(ctx, conn)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>ctx</code> _(required)_</td>
            <td><code>context.Context</code></td>
            <td>Bounds the connection attempt.</td>
        </tr>
        <tr>
            <td><code>conn</code> _(required)_</td>
            <td><code>connection.Connection</code></td>
            <td>The connection. See <a href="/docs/reference/golang/concepts/connecting-to-surrealdb.md#using-a-custom-connection">Using a custom connection</a>.</td>
        </tr>
    </tbody>
</table>

**Returns:** `(*DB, error)`

### `FromConnectionWithOptions` {#fromconnectionwithoptions}

Creates a client from a connection you built, configured by [options](#options).

```go title="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.

---

## Options {#options}

An `Option` configures a client created with `FromEndpointURLStringWithOptions` or `FromConnectionWithOptions`.

### `WithVersionCheck` {#withversioncheck}

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`](/docs/reference/golang/api/errors.md#unsupportedversionerror) when the server version is outside [`MinimumServerVersion`](#version-constants) to `MaximumServerVersion`. Connecting also fails when the server does not answer the version request.

```go title="Syntax"
surrealdb.WithVersionCheck(enabled bool) Option
```

### `WithReconnect` {#withreconnect}

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](/docs/reference/golang/concepts/reliable-connections.md).

```go title="Syntax"
surrealdb.WithReconnect(enabled bool) Option
```

### `WithReconnectAttempts` {#withreconnectattempts}

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.

```go title="Syntax"
surrealdb.WithReconnectAttempts(attempts int) Option
```

### `WithReconnectDelay` {#withreconnectdelay}

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

```go title="Syntax"
surrealdb.WithReconnectDelay(minDelay, maxDelay time.Duration) Option
```

### `WithTokenRenewal` {#withtokenrenewal}

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()`](#tokens) returns the current pair. See [Automatic token renewal](/docs/reference/golang/concepts/authentication.md#automatic-token-renewal).

```go title="Syntax"
surrealdb.WithTokenRenewal(enabled bool) Option
```

### `WithTokenExpiryMargin` {#withtokenexpirymargin}

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.

```go title="Syntax"
surrealdb.WithTokenExpiryMargin(margin time.Duration) Option
```

---

## Connection methods

### `.Close()` {#close}

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

```go title="Syntax"
err := db.Close(ctx)
```

**Returns:** `error`

### `.Use()` {#use}

Selects the namespace and database of the default session.

```go title="Syntax"
err := db.Use(ctx, ns, database)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>ctx</code> _(required)_</td>
            <td><code>context.Context</code></td>
            <td>Bounds the request.</td>
        </tr>
        <tr>
            <td><code>ns</code> _(required)_</td>
            <td><code>string</code></td>
            <td>The namespace to use.</td>
        </tr>
        <tr>
            <td><code>database</code> _(required)_</td>
            <td><code>string</code></td>
            <td>The database to use.</td>
        </tr>
    </tbody>
</table>

**Returns:** `error`

### `.Version()` {#version}

Returns the version, build and timestamp of the server.

```go title="Syntax"
ver, err := db.Version(ctx)
```

**Returns:** `(*VersionData, error)`. See [`VersionData`](/docs/reference/golang/api/types.md#versiondata).

### `.Health()` {#health}

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`](/docs/reference/golang/api/errors.md#healtherror) with the status and the body.

```go title="Syntax"
err := db.Health(ctx)
```

**Returns:** `error`

### `.CBORVersion()` {#cborversion}

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](/docs/reference/golang/concepts/value-types.md#cbor2-and-plain-cbor).

```go title="Syntax"
v := db.CBORVersion()
```

**Returns:** `connection.CBORVersion`

### `.Status()` {#status}

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

```go title="Syntax"
status := db.Status()
```

**Returns:** [`ConnectionStatus`](/docs/reference/golang/api/types.md#connectionstatus)

### `.OnStatus()` {#onstatus}

Calls `fn` with a [`StatusEvent`](/docs/reference/golang/api/types.md#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.

```go title="Syntax"
stop := db.OnStatus(fn func(StatusEvent))
```

**Returns:** `func()`, which stops the calls

---

## Authentication methods

### `.SignIn()` {#signin}

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

```go title="Syntax"
token, err := db.SignIn(ctx, authData)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>ctx</code> _(required)_</td>
            <td><code>context.Context</code></td>
            <td>Bounds the request.</td>
        </tr>
        <tr>
            <td><code>authData</code> _(required)_</td>
            <td><code>any</code></td>
            <td>An <a href="/docs/reference/golang/api/types.md#auth"><code>Auth</code></a> struct, or a <code>map[string]any</code> with the keys <code>NS</code>, <code>DB</code>, <code>AC</code>, <code>user</code>, <code>pass</code>, <code>key</code>, or the fields an access method reads.</td>
        </tr>
    </tbody>
</table>

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

```go title="Root user"
token, err := db.SignIn(ctx, surrealdb.Auth{
	Username: "root",
	Password: "secret",
})
```

```go title="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()`.

### `.SignInWithRefresh()` {#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.

```go title="Syntax"
tokens, err := db.SignInWithRefresh(ctx, authData)
```

**Returns:** `(*Tokens, error)`. See [`Tokens`](/docs/reference/golang/api/types.md#tokens).

### `.SignUp()` {#signup}

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

```go title="Syntax"
token, err := db.SignUp(ctx, authData)
```

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

### `.SignUpWithRefresh()` {#signupwithrefresh}

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

```go title="Syntax"
tokens, err := db.SignUpWithRefresh(ctx, authData)
```

**Returns:** `(*Tokens, error)`

### `.Refresh()` {#refresh}

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.

```go title="Syntax"
newTokens, err := db.Refresh(ctx, tokens)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>ctx</code> _(required)_</td>
            <td><code>context.Context</code></td>
            <td>Bounds the request.</td>
        </tr>
        <tr>
            <td><code>tokens</code> _(required)_</td>
            <td><a href="/docs/reference/golang/api/types.md#tokens"><code>Tokens</code></a></td>
            <td>The pair to exchange.</td>
        </tr>
    </tbody>
</table>

**Returns:** `(*Tokens, error)`

### `.Revoke()` {#revoke}

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

```go title="Syntax"
err := db.Revoke(ctx, tokens)
```

**Returns:** `error`

### `.Tokens()` {#tokens}

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.

```go title="Syntax"
pair := db.Tokens()
```

**Returns:** `*Tokens`

### `.Authenticate()` {#authenticate}

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

```go title="Syntax"
err := db.Authenticate(ctx, token)
```

**Returns:** `error`

### `.Invalidate()` {#invalidate}

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

```go title="Syntax"
err := db.Invalidate(ctx)
```

**Returns:** `error`

### `.Reset()` {#reset}

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.

```go title="Syntax"
err := db.Reset(ctx)
```

**Returns:** `error`

### `.Info()` {#info}

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

```go title="Syntax"
info, err := db.Info(ctx)
```

**Returns:** `(map[string]any, error)`

---

## Variables

### `.Let()` {#let}

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.

```go title="Syntax"
err := db.Let(ctx, key, val)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>ctx</code> _(required)_</td>
            <td><code>context.Context</code></td>
            <td>Bounds the request.</td>
        </tr>
        <tr>
            <td><code>key</code> _(required)_</td>
            <td><code>string</code></td>
            <td>The name of the variable, without <code>$</code>.</td>
        </tr>
        <tr>
            <td><code>val</code> _(required)_</td>
            <td><code>any</code></td>
            <td>The value.</td>
        </tr>
    </tbody>
</table>

**Returns:** `error`

### `.Unset()` {#unset}

Removes a variable from the default session.

```go title="Syntax"
err := db.Unset(ctx, key)
```

**Returns:** `error`

---

## Sessions and transactions

### `.Attach()` {#attach}

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](/docs/reference/golang/concepts/multiple-sessions.md).

```go title="Syntax"
session, err := db.Attach(ctx)
```

**Returns:** `(*Session, error)`. See [`Session`](/docs/reference/golang/api/core/session.md).

### `.Fork()` {#fork}

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.

```go title="Syntax"
session, err := db.Fork(ctx)
```

**Returns:** `(*Session, error)`

### `.Sessions()` {#sessions}

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

```go title="Syntax"
sessions, err := db.Sessions(ctx)
```

**Returns:** `([]*Session, error)`

### `.Begin()` {#begin}

Starts an interactive transaction in the default session. Needs a WebSocket connection, and returns `constants.ErrTransactionsNotSupported` otherwise. See [Transactions](/docs/reference/golang/concepts/transactions.md).

```go title="Syntax"
tx, err := db.Begin(ctx)
```

**Returns:** `(*Transaction, error)`. See [`Transaction`](/docs/reference/golang/api/core/transaction.md).

---

## Import and export

### `.Export()` {#export}

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](/docs/reference/golang/concepts/import-and-export.md).

```go title="Syntax"
err := db.Export(ctx, w, options)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>ctx</code> _(required)_</td>
            <td><code>context.Context</code></td>
            <td>Bounds the request.</td>
        </tr>
        <tr>
            <td><code>w</code> _(required)_</td>
            <td><code>io.Writer</code></td>
            <td>Where the method writes the document. The method does not close it.</td>
        </tr>
        <tr>
            <td><code>options</code> _(optional)_</td>
            <td><a href="/docs/reference/golang/api/types.md#exportoptions"><code>*ExportOptions</code></a></td>
            <td>What to export. <code>nil</code> exports everything.</td>
        </tr>
    </tbody>
</table>

**Returns:** `error`

### `.Import()` {#import}

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`](/docs/reference/golang/api/errors.md#importerror).

```go title="Syntax"
err := db.Import(ctx, document)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>ctx</code> _(required)_</td>
            <td><code>context.Context</code></td>
            <td>Bounds the request.</td>
        </tr>
        <tr>
            <td><code>document</code> _(required)_</td>
            <td><code>io.Reader</code></td>
            <td>The SurrealQL to run. The method does not close it.</td>
        </tr>
    </tbody>
</table>

**Returns:** `error`

---

## Query functions

These are generic package functions. Their `s` argument is a `*DB`, a [`*Session`](/docs/reference/golang/api/core/session.md) or a [`*Transaction`](/docs/reference/golang/api/core/transaction.md).

### `Query` {#query}

Runs SurrealQL and returns one result for each statement. When any statement fails, the error joins the [`QueryError`](/docs/reference/golang/api/errors.md#queryerror) of each failed statement. The function still returns the results. See [Executing queries](/docs/reference/golang/concepts/executing-queries.md).

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

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>TResult</code></td>
            <td>type parameter</td>
            <td>The Go type of each statement's result.</td>
        </tr>
        <tr>
            <td><code>ctx</code> _(required)_</td>
            <td><code>context.Context</code></td>
            <td>Bounds the request.</td>
        </tr>
        <tr>
            <td><code>s</code> _(required)_</td>
            <td><code>*DB | *Session | *Transaction</code></td>
            <td>Where the query runs.</td>
        </tr>
        <tr>
            <td><code>sql</code> _(required)_</td>
            <td><code>string</code></td>
            <td>The SurrealQL.</td>
        </tr>
        <tr>
            <td><code>vars</code> _(required)_</td>
            <td><code>map[string]any</code></td>
            <td>The variables of the query. Pass <code>nil</code> for none.</td>
        </tr>
    </tbody>
</table>

**Returns:** `(*[]QueryResult[TResult], error)`. See [`QueryResult`](/docs/reference/golang/api/types.md#queryresult).

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

### `QueryRaw` {#queryraw}

Runs a list of statements as one query, and writes each result to its [`QueryStmt`](/docs/reference/golang/api/types.md#querystmt). Each `QueryStmt` must hold exactly one statement.

```go title="Syntax"
err := surrealdb.QueryRaw(ctx, s, queries)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>ctx</code> _(required)_</td>
            <td><code>context.Context</code></td>
            <td>Bounds the request.</td>
        </tr>
        <tr>
            <td><code>s</code> _(required)_</td>
            <td><code>*DB | *Session | *Transaction</code></td>
            <td>Where the query runs.</td>
        </tr>
        <tr>
            <td><code>queries</code> _(required)_</td>
            <td><code>*[]QueryStmt</code></td>
            <td>The statements. The function writes their results back to them.</td>
        </tr>
    </tbody>
</table>

**Returns:** `error`

### `QueryStream` {#querystream}

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](/docs/reference/golang/concepts/streaming.md).

```go title="Syntax"
for frame, err := range surrealdb.QueryStream[T](ctx, s, sql, vars) {
	// ...
}
```

**Returns:** `iter.Seq2[StreamFrame[T], error]`. See [`StreamFrame`](/docs/reference/golang/api/types.md#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`.

### `Run` {#run}

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.

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

**Returns:** `(*TResult, error)`

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

### `RunVersion` {#runversion}

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

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

**Returns:** `(*TResult, error)`

### `API` {#api}

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.

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

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>TBody</code></td>
            <td>type parameter</td>
            <td>The Go type of the response body.</td>
        </tr>
        <tr>
            <td><code>path</code> _(required)_</td>
            <td><code>string</code></td>
            <td>The path of the endpoint.</td>
        </tr>
        <tr>
            <td><code>req</code> _(optional)_</td>
            <td><a href="/docs/reference/golang/api/types.md#apirequest"><code>*APIRequest</code></a></td>
            <td>The method, body, headers and query parameters.</td>
        </tr>
    </tbody>
</table>

**Returns:** `(*APIResponse[TBody], error)`. See [`APIResponse`](/docs/reference/golang/api/types.md#apiresponse).

### `GQL` {#gql}

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

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

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

---

## Data functions

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`](/docs/reference/golang/api/types.md#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](/docs/reference/golang/concepts/data-manipulation.md).

A failed statement returns an `*RPCError` that unwraps to a [`*ServerError`](/docs/reference/golang/api/errors.md#servererror).

### `Select` {#select}

Selects records.

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

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>TResult</code></td>
            <td>type parameter</td>
            <td>A record type for a record ID, and a slice for a table, a range or a slice.</td>
        </tr>
        <tr>
            <td><code>what</code> _(required)_</td>
            <td><code>TableOrRecord</code></td>
            <td>The record, table or range to select.</td>
        </tr>
    </tbody>
</table>

**Returns:** `(*TResult, error)`

### `Create` {#create}

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.

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

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>what</code> _(required)_</td>
            <td><code>TableOrRecord</code></td>
            <td>The record ID to create, or the table to create a record in.</td>
        </tr>
        <tr>
            <td><code>data</code> _(required)_</td>
            <td><code>any</code></td>
            <td>The content, as a struct or a map. <code>nil</code> creates a record with no other fields.</td>
        </tr>
    </tbody>
</table>

**Returns:** `(*TResult, error)`

### `Insert` {#insert}

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

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

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>TResult</code></td>
            <td>type parameter</td>
            <td>The type of one record.</td>
        </tr>
        <tr>
            <td><code>table</code> _(required)_</td>
            <td><a href="/docs/reference/golang/api/values/table.md"><code>models.Table</code></a></td>
            <td>The table to insert into.</td>
        </tr>
        <tr>
            <td><code>data</code> _(required)_</td>
            <td><code>any</code></td>
            <td>One record or a slice of records.</td>
        </tr>
    </tbody>
</table>

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

### `Update` {#update}

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

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

**Returns:** `(*TResult, error)`

### `Upsert` {#upsert}

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

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

**Returns:** `(*TResult, error)`

### `Merge` {#merge}

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

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

**Returns:** `(*TResult, error)`

### `Patch` {#patch}

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

```go title="Syntax"
result, err := surrealdb.Patch(ctx, s, what, patches)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>what</code> _(required)_</td>
            <td><code>TableOrRecord</code></td>
            <td>The records to patch.</td>
        </tr>
        <tr>
            <td><code>patches</code> _(required)_</td>
            <td><a href="/docs/reference/golang/api/types.md#patchdata"><code>[]PatchData</code></a></td>
            <td>The JSON Patch operations.</td>
        </tr>
    </tbody>
</table>

**Returns:** `(*[]PatchData, error)`

### `PatchWithResult` {#patchwithresult}

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

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

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>TResult</code></td>
            <td>type parameter</td>
            <td>A record type, a slice of records, <code>[]PatchData</code> or <code>[][]PatchData</code>, to match <code>what</code> and <code>output</code>.</td>
        </tr>
        <tr>
            <td><code>patches</code> _(required)_</td>
            <td><code>[]PatchData</code></td>
            <td>The JSON Patch operations.</td>
        </tr>
        <tr>
            <td><code>output</code> _(required)_</td>
            <td><a href="/docs/reference/golang/api/types.md#returnmode"><code>ReturnMode</code></a></td>
            <td><code>ReturnAfter</code>, <code>ReturnBefore</code>, <code>ReturnDiff</code> or <code>ReturnNone</code>.</td>
        </tr>
    </tbody>
</table>

**Returns:** `(*TResult, error)`

```go
patched, err := surrealdb.PatchWithResult[Person](ctx, db,
	models.NewRecordID("person", "tobie"),
	[]surrealdb.PatchData{{Op: "replace", Path: "/age", Value: 38}},
	surrealdb.ReturnAfter,
)
```

### `Delete` {#delete}

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

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

**Returns:** `(*TResult, error)`

### `Relate` {#relate}

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.

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

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>rel</code> _(required)_</td>
            <td><a href="/docs/reference/golang/api/types.md#relationship"><code>*Relationship</code></a></td>
            <td>The edge to create.</td>
        </tr>
    </tbody>
</table>

**Returns:** `(*TResult, error)`

### `InsertRelation` {#insertrelation}

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

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

**Returns:** `(*TResult, error)`

---

## Live query functions

`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](/docs/reference/golang/concepts/live-queries.md).

### `Live` {#live}

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.

```go title="Syntax"
liveID, err := surrealdb.Live(ctx, s, table, diff)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>s</code> _(required)_</td>
            <td><code>*DB | *Session</code></td>
            <td>The session the live query belongs to.</td>
        </tr>
        <tr>
            <td><code>table</code> _(required)_</td>
            <td><a href="/docs/reference/golang/api/values/table.md"><code>models.Table</code></a></td>
            <td>The table to watch.</td>
        </tr>
        <tr>
            <td><code>diff</code> _(required)_</td>
            <td><code>bool</code></td>
            <td>With <code>true</code>, each notification holds the JSON Patch operations that changed the record, instead of the record.</td>
        </tr>
    </tbody>
</table>

**Returns:** `(*models.UUID, error)`. See [`UUID`](/docs/reference/golang/api/values/uuid.md).

### `Kill` {#kill}

Stops a live query and closes its notification channel.

```go title="Syntax"
err := surrealdb.Kill(ctx, s, id)
```

**Returns:** `error`

### `.LiveNotifications()` {#livenotifications}

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

```go title="Syntax"
ch, err := db.LiveNotifications(liveQueryID)
```

**Returns:** `(chan connection.Notification, error)`. See [`Notification`](/docs/reference/golang/api/types.md#notification).

### `.CloseLiveNotifications()` {#closelivenotifications}

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

```go title="Syntax"
err := db.CloseLiveNotifications(liveQueryID)
```

**Returns:** `error`

---

## Version helpers

### `MinimumServerVersion` and `MaximumServerVersion` {#version-constants}

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

### `IsVersionSupported` {#isversionsupported}

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.

```go title="Syntax"
ok := surrealdb.IsVersionSupported(version)
```

**Returns:** `bool`

### `IsVersionInRange` {#isversioninrange}

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

```go title="Syntax"
ok := surrealdb.IsVersionInRange(version, minimum, maximum)
```

**Returns:** `bool`

```go
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
}
```

---

## Low-level RPC

### `Send` {#send}

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

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

**Returns:** `error`

---

## Availability by connection type {#availability}

| Feature | WebSocket | HTTP |
| --- | --- | --- |
| `Query`, `QueryRaw`, `Run`, `API`, `GQL`, the CRUD functions | Yes | Yes |
| Authentication, `.Use()`, `.Let()`, `.Unset()`, `.Reset()` | Yes, kept by the server | Yes, kept by the client |
| `.Health()`, `.Version()`, `.Export()`, `.Import()` | Yes | Yes |
| `QueryStream` | Yes, streamed | Yes, the whole result at once |
| `Live`, `Kill`, `.LiveNotifications()` | Yes | No |
| `.Attach()`, `.Fork()`, `.Sessions()` | Yes | No: `ErrSessionsNotSupported` |
| `.Begin()` | Yes | No: `ErrTransactionsNotSupported` |
| Reconnection and `.OnStatus()` | Yes | Not needed |

---

## See also

- [Session](/docs/reference/golang/api/core/session.md) for the methods of a session
- [Transaction](/docs/reference/golang/api/core/transaction.md) for the methods of a transaction
- [Types](/docs/reference/golang/api/types.md) for the types these functions use
- [Errors](/docs/reference/golang/api/errors.md) for the error types
- [Connecting to SurrealDB](/docs/reference/golang/concepts/connecting-to-surrealdb.md) for connection patterns

---

Source: https://surrealdb.com/docs/reference/golang/api/core/session

# Session

Reference for the Session type of the SurrealDB Go SDK - a session attached to a WebSocket connection with its own authentication, namespace, database and variables - and its methods for signing in, refresh tokens, Fork, Reset, Detach, Begin and live queries.

A `Session` is an extra session on a WebSocket connection, with its own authentication, namespace and database, and variables. [`db.Attach()`](/docs/reference/golang/api/core/db.md#attach) and [`db.Fork()`](/docs/reference/golang/api/core/db.md#fork) return one, and [`db.Sessions()`](/docs/reference/golang/api/core/db.md#sessions) lists them. Every query and CRUD function, such as [`Query`](/docs/reference/golang/api/core/db.md#query) and [`Select`](/docs/reference/golang/api/core/db.md#select), takes a `*Session` in place of a `*DB`. See [Multiple sessions](/docs/reference/golang/concepts/multiple-sessions.md) for explanations and examples.

Sessions need a WebSocket connection. When the client reconnects, it attaches each session again under the same UUID and restores its state.

**Source:** [session.go](https://github.com/surrealdb/surrealdb.go/blob/main/session.go)

---

## Creating a session

### `db.Attach()` {#attach}

Attaches a new session to the connection. The new session starts signed out, with no namespace or database selected.

```go title="Syntax"
session, err := db.Attach(ctx)
```

**Returns:** `(*Session, error)`. On an HTTP connection, the error is `constants.ErrSessionsNotSupported`.

```go
session, err := db.Attach(ctx)
if err != nil {
	log.Fatal(err)
}
defer session.Detach(ctx)

if _, err := session.SignIn(ctx, surrealdb.Auth{Username: "root", Password: "secret"}); err != nil {
	log.Fatal(err)
}
if err := session.Use(ctx, "surrealdb", "docs"); err != nil {
	log.Fatal(err)
}

people, err := surrealdb.Query[[]Person](ctx, session, "SELECT * FROM person", nil)
```

### `.Fork()` {#fork}

Attaches a new session that starts as a copy of this one. The new session has the same namespace, database and variables, and is signed in with the same access token. After that, the two sessions are independent. `.Fork()` does not copy a token pair.

```go title="Syntax"
fork, err := session.Fork(ctx)
```

**Returns:** `(*Session, error)`

After the access token of the session expires, `.Fork()` returns an error that wraps `constants.ErrForkTokenExpired`. For a session that `db.Sessions()` lists but this client did not attach, it returns `constants.ErrForkUntracked`.

---

## Properties

### `.ID()` {#id}

Returns the UUID of the session.

```go title="Syntax"
id := session.ID()
```

**Returns:** [`*models.UUID`](/docs/reference/golang/api/values/uuid.md)

---

## Authentication methods

These methods work like the methods with the same name on [`DB`](/docs/reference/golang/api/core/db.md#authentication-methods), but only for this session.

### `.SignIn()` {#signin}

Signs a user in to this session.

```go title="Syntax"
token, err := session.SignIn(ctx, authData)
```

**Returns:** `(string, error)`

### `.SignInWithRefresh()` {#signinwithrefresh}

Signs in through a `TYPE RECORD` access method defined `WITH REFRESH`, and returns an access token and a refresh token.

```go title="Syntax"
tokens, err := session.SignInWithRefresh(ctx, authData)
```

**Returns:** [`(*Tokens, error)`](/docs/reference/golang/api/types.md#tokens)

### `.SignUp()` {#signup}

Signs up a record user, and signs them in to this session.

```go title="Syntax"
token, err := session.SignUp(ctx, authData)
```

**Returns:** `(string, error)`

### `.SignUpWithRefresh()` {#signupwithrefresh}

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

```go title="Syntax"
tokens, err := session.SignUpWithRefresh(ctx, authData)
```

**Returns:** [`(*Tokens, error)`](/docs/reference/golang/api/types.md#tokens)

### `.Refresh()` {#refresh}

Exchanges a token pair for a new one, and authenticates this session with it.

```go title="Syntax"
newTokens, err := session.Refresh(ctx, tokens)
```

**Returns:** `(*Tokens, error)`

### `.Revoke()` {#revoke}

Revokes the refresh token of a pair. The session stays signed in.

```go title="Syntax"
err := session.Revoke(ctx, tokens)
```

**Returns:** `error`

### `.Tokens()` {#tokens}

Returns the token pair that this session holds. It returns `nil` when the session holds no pair or when token renewal is off.

```go title="Syntax"
pair := session.Tokens()
```

**Returns:** `*Tokens`

### `.Authenticate()` {#authenticate}

Authenticates this session with a JWT.

```go title="Syntax"
err := session.Authenticate(ctx, token)
```

**Returns:** `error`

### `.Invalidate()` {#invalidate}

Signs this session out.

```go title="Syntax"
err := session.Invalidate(ctx)
```

**Returns:** `error`

### `.Info()` {#info}

Returns the record of the record user signed in to this session.

```go title="Syntax"
info, err := session.Info(ctx)
```

**Returns:** `(map[string]any, error)`

---

## Session state

### `.Use()` {#use}

Selects the namespace and database of this session.

```go title="Syntax"
err := session.Use(ctx, ns, database)
```

**Returns:** `error`

### `.Let()` {#let}

Sets a variable in this session. 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.

```go title="Syntax"
err := session.Let(ctx, key, val)
```

**Returns:** `error`

### `.Unset()` {#unset}

Removes a variable from this session.

```go title="Syntax"
err := session.Unset(ctx, key)
```

**Returns:** `error`

### `.Reset()` {#reset}

Returns this session to the state it had when the client attached it. It signs the session out, clears its namespace, database and variables, and kills its live queries. The session stays attached.

```go title="Syntax"
err := session.Reset(ctx)
```

**Returns:** `error`

### `.Version()` {#version}

Returns the version of the server.

```go title="Syntax"
ver, err := session.Version(ctx)
```

**Returns:** [`(*VersionData, error)`](/docs/reference/golang/api/types.md#versiondata)

---

## Transactions and live queries

### `.Begin()` {#begin}

Starts an interactive transaction in this session.

```go title="Syntax"
tx, err := session.Begin(ctx)
```

**Returns:** `(*Transaction, error)`. See [`Transaction`](/docs/reference/golang/api/core/transaction.md). After `.Detach()`, the error is `constants.ErrSessionClosed`.

### `.LiveNotifications()` {#livenotifications}

Returns the notification channel of a live query that this session started with [`Live`](/docs/reference/golang/api/core/db.md#live).

```go title="Syntax"
ch, err := session.LiveNotifications(liveQueryID)
```

**Returns:** `(chan` [`connection.Notification`](/docs/reference/golang/api/types.md#notification)`, error)`

### `.CloseLiveNotifications()` {#closelivenotifications}

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

```go title="Syntax"
err := session.CloseLiveNotifications(liveQueryID)
```

**Returns:** `error`

---

## Closing a session

### `.Detach()` {#detach}

Removes the session from the server and closes the channels of its live queries. After `.Detach()`, you cannot use the session, and its methods return `constants.ErrSessionClosed`.

```go title="Syntax"
err := session.Detach(ctx)
```

**Returns:** `error`

---

## See also

- [DB](/docs/reference/golang/api/core/db.md) for the client and the query functions
- [Transaction](/docs/reference/golang/api/core/transaction.md) for transactions in a session
- [Multiple sessions](/docs/reference/golang/concepts/multiple-sessions.md) for session usage patterns
- [Errors](/docs/reference/golang/api/errors.md#sentinel-errors) for `ErrSessionClosed` and the other session errors

---

Source: https://surrealdb.com/docs/reference/golang/api/core/transaction

# Transaction

Reference for the Transaction type of the SurrealDB Go SDK - an interactive transaction on a WebSocket connection, started with Begin on a DB or a Session - and its methods Commit, Cancel, ID, SessionID and IsClosed.

A `Transaction` is an interactive transaction on a WebSocket connection. Unlike a text transaction, it runs statements one at a time, so your code can read each result and then commit or cancel. Every query and CRUD function, such as [`Query`](/docs/reference/golang/api/core/db.md#query), [`Select`](/docs/reference/golang/api/core/db.md#select) and [`QueryStream`](/docs/reference/golang/api/core/db.md#querystream), takes a `*Transaction` in place of a `*DB`. See [Transactions](/docs/reference/golang/concepts/transactions.md) for explanations and examples.

A transaction runs as the signed-in user of its session, in the namespace and database of that session. A transaction cannot change that state. For this reason, it has no `SignIn`, `Use` or `Let` methods, and `Live` and `Kill` do not take it. When the client loses the connection, it also loses any open transaction.

**Source:** [transaction.go](https://github.com/surrealdb/surrealdb.go/blob/main/transaction.go)

---

## Creating a transaction

### `db.Begin()` {#db-begin}

Starts a transaction in the default session.

```go title="Syntax"
tx, err := db.Begin(ctx)
```

**Returns:** `(*Transaction, error)`. On an HTTP connection, the error is [`constants.ErrTransactionsNotSupported`](/docs/reference/golang/api/errors.md#sentinel-errors).

### `session.Begin()` {#session-begin}

Starts a transaction in a [session](/docs/reference/golang/api/core/session.md).

```go title="Syntax"
tx, err := session.Begin(ctx)
```

**Returns:** `(*Transaction, error)`. After `session.Detach()`, the error is [`constants.ErrSessionClosed`](/docs/reference/golang/api/errors.md#sentinel-errors).

```go
tx, err := db.Begin(ctx)
if err != nil {
	log.Fatal(err)
}
defer tx.Cancel(ctx)

if _, err := surrealdb.Create[any](ctx, tx, "event", map[string]any{
	"type":   "transfer",
	"amount": 100,
}); err != nil {
	log.Fatal(err)
}

if err := tx.Commit(ctx); err != nil {
	log.Fatal(err)
}
```

---

## Properties

### `.ID()` {#id}

Returns the UUID of the transaction.

```go title="Syntax"
id := tx.ID()
```

**Returns:** [`*models.UUID`](/docs/reference/golang/api/values/uuid.md)

### `.SessionID()` {#sessionid}

Returns the UUID of the session that started the transaction, or `nil` for a transaction in the default session.

```go title="Syntax"
sessionID := tx.SessionID()
```

**Returns:** [`*models.UUID`](/docs/reference/golang/api/values/uuid.md)

### `.IsClosed()` {#isclosed}

Reports whether the transaction was committed or cancelled.

```go title="Syntax"
closed := tx.IsClosed()
```

**Returns:** `bool`

---

## Methods

### `.Commit()` {#commit}

Commits the transaction, and makes its changes permanent. After that, you cannot use the transaction.

```go title="Syntax"
err := tx.Commit(ctx)
```

**Returns:** `error`. For a transaction that was already committed or cancelled, the error is [`constants.ErrTransactionClosed`](/docs/reference/golang/api/errors.md#sentinel-errors). When another transaction changed the same data, [`surrealdb.IsTransactionConflict`](/docs/reference/golang/api/errors.md#kind-helpers) reports the conflict, and you can run the transaction again.

### `.Cancel()` {#cancel}

Cancels the transaction, and discards its changes. After that, you cannot use the transaction.

```go title="Syntax"
err := tx.Cancel(ctx)
```

**Returns:** `error`

On a transaction that was already committed or cancelled, `.Cancel()` returns `constants.ErrTransactionClosed` and changes nothing. This makes `defer tx.Cancel(ctx)` safe directly after `.Begin()`.

---

## See also

- [DB](/docs/reference/golang/api/core/db.md#begin) for starting a transaction in the default session
- [Session](/docs/reference/golang/api/core/session.md#begin) for starting a transaction in a session
- [Transactions](/docs/reference/golang/concepts/transactions.md) for transaction usage patterns
- [Errors](/docs/reference/golang/api/errors.md) for `ErrTransactionClosed` and `ErrTransactionsNotSupported`

---

Source: https://surrealdb.com/docs/reference/golang/api/errors

# Errors

Reference for the errors of the SurrealDB Go SDK 2.x - ServerError and its Kind constants, the IsNotFound and other Is helpers, QueryError, RPCError, UnsupportedVersionError, HealthError, ImportError, and the sentinel errors of the surrealdb, connection and constants packages.

The Go SDK returns errors that you inspect with `errors.As` and `errors.Is`. This page lists each error type, the kinds of a server error and the helpers that match them, and the sentinel errors. For patterns that check and retry these errors, see [Error handling](/docs/reference/golang/concepts/error-handling.md).

**Packages:**

- `github.com/surrealdb/surrealdb.go/v2`, which re-exports the error types of `pkg/connection`
- `github.com/surrealdb/surrealdb.go/v2/pkg/connection`, which defines `ServerError`, `RPCError` and `HealthError`
- `github.com/surrealdb/surrealdb.go/v2/pkg/constants`, which defines most sentinel errors

---

## Error types

### `ServerError` {#servererror}

An error that the server reports for a request, such as a sign-in, a CRUD function or a query that does not parse. Use `errors.As` to read it from any error the SDK returns.

```go
type ServerError struct {
	Code    int
	Message string
	Kind    string
	Details any
	Cause   *ServerError
}
```

| Field | Description |
| --- | --- |
| `Code` | The JSON-RPC error code, such as `-32000` |
| `Message` | The message of the error |
| `Kind` | The kind of the error, one of the [`Kind` constants](#kind-constants) |
| `Details` | Details for the kind, as `{ kind, details }`, or `nil` |
| `Cause` | The next error in the chain, or `nil` |

**Methods:**

- `.Error()` returns the message, with the messages of the cause chain joined by `": "`
- `.Unwrap()` returns `Cause`, so that `errors.Unwrap`, `errors.Is` and `errors.As` walk the chain

**Available as:** `surrealdb.ServerError`, an alias of `connection.ServerError`

```go
_, err := surrealdb.Create[Person](ctx, db, models.NewRecordID("person", "tobie"), person)

var se *surrealdb.ServerError
if errors.As(err, &se) {
	fmt.Println(se.Kind, se.Message)
}
```

```text title="Output when person:tobie exists"
AlreadyExists Database record `person:tobie` already exists
```

### `Kind` constants {#kind-constants}

The `surrealdb` package re-exports the known values of `ServerError.Kind`:

| Constant | Value |
| --- | --- |
| `KindValidation` | `"Validation"` |
| `KindConfiguration` | `"Configuration"` |
| `KindThrown` | `"Thrown"` |
| `KindQuery` | `"Query"` |
| `KindSerialization` | `"Serialization"` |
| `KindNotAllowed` | `"NotAllowed"` |
| `KindNotFound` | `"NotFound"` |
| `KindAlreadyExists` | `"AlreadyExists"` |
| `KindConnection` | `"Connection"` |
| `KindInternal` | `"Internal"` |

[Errors](/docs/reference/protocols/errors.md) documents the kinds and their details for every SDK.

### `Is` helpers {#kind-helpers}

Each helper reports whether an error is, or wraps, a `*ServerError` that matches its entry in the table below. It returns `false` for `nil` and for other errors.

| Helper | Kind and detail |
| --- | --- |
| `IsNotFound(err)` | `NotFound` |
| `IsNotAllowed(err)` | `NotAllowed` |
| `IsInvalidAuth(err)` | `NotAllowed`, `Auth`, `InvalidAuth` |
| `IsTokenExpired(err)` | `NotAllowed`, `Auth`, `TokenExpired` |
| `IsScriptingBlocked(err)` | `NotAllowed`, `Scripting` |
| `IsParseError(err)` | `Validation`, `Parse` |
| `IsTimedOut(err)` | `Query`, `TimedOut` |
| `IsCancelled(err)` | `Query`, `Cancelled` |
| `IsNotExecuted(err)` | `Query`, `NotExecuted` |
| `IsTransactionConflict(err)` | `Query`, `TransactionConflict`, which is safe to retry |
| `IsDeserialization(err)` | `Serialization`, `Deserialization` |
| `IsLiveQueryNotSupported(err)` | `Configuration`, `LiveQueryNotSupported` |

```go
if surrealdb.IsNotFound(err) {
	fmt.Println("no such table")
}
```

### `QueryError` {#queryerror}

The error of one failed statement of a query. It is the `Error` field of a [`QueryResult`](/docs/reference/golang/api/types.md#queryresult), and the `Err` field of the `Done` frame of a [`StreamFrame`](/docs/reference/golang/api/types.md#streamframe). The error that `Query` returns joins the `QueryError` of each failed statement.

```go
type QueryError struct {
	Message string
}
```

**Methods:**

- `.Error()` returns the message
- `.Is(target)` returns `true` when `target` is a `*QueryError`, so `errors.Is(err, &surrealdb.QueryError{})` reports whether `err` holds one

A `QueryError` holds the message only, so the `Is` helpers do not match it.

```go
results, err := surrealdb.Query[any](ctx, db, "RETURN 1; THROW 'Not allowed';", nil)

if errors.Is(err, &surrealdb.QueryError{}) {
	for _, qr := range *results {
		if qr.Error != nil {
			fmt.Println(qr.Error.Message)
		}
	}
}
```

```text title="Output"
An error occurred: Not allowed
```

### `RPCError` {#rpcerror}

The JSON-RPC error of a failed request, with `Code` and `Message` fields. It unwraps to a `*ServerError`, which has more information. Use `errors.As` with a `*ServerError` instead.

**Available as:** `surrealdb.RPCError`, an alias of `connection.RPCError`. It is deprecated.

### `UnsupportedVersionError` {#unsupportedversionerror}

The client returns this error when it connects to a server whose version is outside the range that the SDK supports. It does this only with [`WithVersionCheck(true)`](/docs/reference/golang/api/core/db.md#withversioncheck).

```go
type UnsupportedVersionError struct {
	Version string
	Minimum string
	Maximum string
}
```

| Field | Description |
| --- | --- |
| `Version` | The version the server reported |
| `Minimum` | The oldest version supported, `MinimumServerVersion` |
| `Maximum` | The first version not supported, `MaximumServerVersion` |

### `HealthError` {#healtherror}

[`db.Health()`](/docs/reference/golang/api/core/db.md#health) returns this error when the server answers its health check with a status other than `2xx`. The server does this, for example, when it cannot reach its datastore.

```go
type HealthError struct {
	StatusCode int
	Status     string
	Body       string
}
```

| Field | Description |
| --- | --- |
| `StatusCode` | The HTTP status code, such as `503` |
| `Status` | The HTTP status, such as `503 Service Unavailable` |
| `Body` | The start of the body, at most 4 KiB, with surrounding white space removed |

**Available as:** `surrealdb.HealthError`, an alias of `connection.HealthError`

### `ImportError` {#importerror}

[`db.Import()`](/docs/reference/golang/api/core/db.md#import) returns this error when statements of the document fail. The server does not roll back the statements that succeed.

```go
type ImportError struct {
	Failures []error
}
```

`Failures` holds the error of each failed statement, in order. Each error is an `*RPCError` that unwraps to a `*ServerError`.

**Methods:**

- `.Error()` describes the first failure and the number of failures
- `.Unwrap()` returns `Failures`, so `errors.Is` and `errors.As` look through each of them

---

## Sentinel errors {#sentinel-errors}

Check these with `errors.Is`, because the SDK wraps some of them.

### In `pkg/constants`

| Error | Returned when |
| --- | --- |
| `ErrSessionsNotSupported` | You call `Attach`, `Fork` or `Sessions` on an HTTP connection |
| `ErrTransactionsNotSupported` | You call `Begin` on an HTTP connection |
| `ErrSessionClosed` | You use a session after `.Detach()` |
| `ErrTransactionClosed` | You use a transaction after `.Commit()` or `.Cancel()` |
| `ErrForkTokenExpired` | You call `Fork` after the access token of the session has expired |
| `ErrForkUntracked` | You call `Fork` on a session that this client did not attach |
| `ErrNeedsCBOR2` | The SDK tries to encode a value with no plain CBOR form, such as a `models.Regex`, for plain CBOR |
| `ErrMethodNotAvailable` | A method is not available on the connection |

`ErrNoNamespaceOrDB` is deprecated. The HTTP connection no longer needs a namespace and database for every request, and does not return it.

### In the `surrealdb` package

| Error | Returned when |
| --- | --- |
| `ErrClientClosed` | You use the client after `.Close()`, or after it gave up reconnecting |
| `ErrLiveQueryEnded` | The client ended a live query, instead of restarting it, when it reconnected |
| `ErrStreamProtocol` | The frames of a streamed query break the streaming protocol |

### In `pkg/connection`

| Error | Returned when |
| --- | --- |
| `ErrConnectionClosed` | The client lost the connection while a request waited for its answer |

A request that times out returns an error that wraps `context.DeadlineExceeded`.

```go
import "github.com/surrealdb/surrealdb.go/v2/pkg/constants"

session, err := db.Attach(ctx)
if errors.Is(err, constants.ErrSessionsNotSupported) {
	log.Fatal("sessions need a WebSocket connection")
}
```

---

## See also

- [Error handling](/docs/reference/golang/concepts/error-handling.md) for patterns that check errors, and for retry guidance
- [Types reference](/docs/reference/golang/api/types.md) for `QueryResult` and `StreamFrame`
- [DB reference](/docs/reference/golang/api/core/db.md) for the functions that return these errors
- [Errors](/docs/reference/protocols/errors.md) for the error kinds that every SDK shares

---

Source: https://surrealdb.com/docs/reference/golang/api/types

# Types

Reference for the types of the SurrealDB Go SDK 2.x - Auth, Tokens, QueryResult, QueryStmt, StreamFrame, PatchData, ReturnMode, Relationship, APIRequest, APIResponse, ExportOptions, VersionData, Notification and Action, Option, ConnectionStatus, StatusEvent, CBORVersion, and the TableOrRecord, sendable and liveQueryable constraints.

The Go SDK defines types for the arguments and results of its functions. Most are in the `surrealdb` package, and a few are in `pkg/connection`. The value types, such as `RecordID`, are in the [`models` package](/docs/reference/golang/api/values.md).

**Package:** `github.com/surrealdb/surrealdb.go/v2`

**Source:** [types.go](https://github.com/surrealdb/surrealdb.go/blob/main/types.go)

---

## Authentication

### `Auth` {#auth}

Holds the credentials of a sign-in. The fields you set decide the level of the user.

```go
type Auth struct {
	Namespace string `json:"NS,omitempty"`
	Database  string `json:"DB,omitempty"`
	Scope     string `json:"SC,omitempty"`
	Access    string `json:"AC,omitempty"`
	Username  string `json:"user,omitempty"`
	Password  string `json:"pass,omitempty"`
}
```

| Field | Key | When to use |
| --- | --- | --- |
| `Namespace` | `NS` | A namespace, database or record user |
| `Database` | `DB` | A database or record user |
| `Access` | `AC` | A record user, through an access method |
| `Username` | `user` | Every level |
| `Password` | `pass` | Every level |
| `Scope` | `SC` | Scopes from SurrealDB 1.x, which current servers do not have |

A `map[string]any` with the same keys works too. The map can also hold the other fields that an access method reads, such as `email`, `key` for a bearer key, or `refresh` for a refresh token.

### `Tokens` {#tokens}

The access token and the refresh token that `.SignInWithRefresh()`, `.SignUpWithRefresh()` and `.Refresh()` return, for a `TYPE RECORD` access method defined `WITH REFRESH`.

```go
type Tokens struct {
	Access  string `cbor:"access"`
	Refresh string `cbor:"refresh"`
}
```

| Field | Description |
| --- | --- |
| `Access` | The JWT that authenticates requests. Use it with `.Authenticate()` on a new connection. |
| `Refresh` | The refresh token, of the form `surreal-refresh-...`. Use it with `.Refresh()` to get a new pair. It works only once. |

**Available as:** `surrealdb.Tokens`, an alias of `connection.Tokens`

---

## Query results

### `QueryResult` {#queryresult}

The result of one statement of a `Query` or `GQL` call. `T` is the type parameter of the call.

```go
type QueryResult[T any] struct {
	Status string      `json:"status"`
	Time   string      `json:"time"`
	Result T           `json:"result"`
	Error  *QueryError `json:"-"`
}
```

| Field | Description |
| --- | --- |
| `Status` | `"OK"` when the statement succeeded, `"ERR"` when it failed |
| `Time` | How long the statement took |
| `Result` | The decoded result |
| `Error` | The [`QueryError`](/docs/reference/golang/api/errors.md#queryerror) of a failed statement, or `nil` |

### `QueryStmt` {#querystmt}

One statement of a `QueryRaw` call. After the call, `Result` holds the statement's result undecoded, and `.GetResult()` decodes it.

```go
type QueryStmt struct {
	SQL    string
	Vars   map[string]any
	Result QueryResult[cbor.RawMessage]
}
```

**Methods:**

- `.GetResult(dest any) error` decodes the result into `dest`. It does not report a failed statement: check `Result.Error` for that.

### `StreamFrame` {#streamframe}

One step of the result of a `QueryStream` call, received while the query runs. `T` is the type of one element of `Rows`.

```go
type StreamFrame[T any] struct {
	Statement int
	Rows      []T
	Done      bool
	Err       error
	Single    bool
	Value     T
	Time      string
}
```

| Field | Description |
| --- | --- |
| `Statement` | The index of the statement, from 0 |
| `Rows` | Results of the statement, such as records. More frames can follow. |
| `Done` | `true` on the last frame of the statement |
| `Err` | The statement's error, as a `*QueryError`, on its `Done` frame. Every element of `Rows` that the statement delivered is then retracted. |
| `Single` | `true` on the `Done` frame of a statement that returns one value |
| `Value` | The value of a `Single` statement |
| `Time` | How long the statement took, on its `Done` frame |

See [Streaming results](/docs/reference/golang/concepts/streaming.md).

---

## Data types

### `PatchData` {#patchdata}

One JSON Patch operation, for `Patch` and `PatchWithResult`, and the operations they return.

```go
type PatchData struct {
	Op    string `json:"op"`
	Path  string `json:"path"`
	Value any    `json:"value"`
}
```

`Op` is `add`, `remove`, `replace`, `move`, `copy` or `test`.

### `ReturnMode` {#returnmode}

Chooses what `PatchWithResult` returns for the records it changes.

```go
type ReturnMode string

const (
	ReturnAfter  ReturnMode = "AFTER"
	ReturnBefore ReturnMode = "BEFORE"
	ReturnDiff   ReturnMode = "DIFF"
	ReturnNone   ReturnMode = "NONE"
)
```

| Value | Returns |
| --- | --- |
| `ReturnAfter` | Each record as it is after the change |
| `ReturnBefore` | Each record as it was before the change |
| `ReturnDiff` | The JSON Patch operations that made the change |
| `ReturnNone` | Nothing |

### `Relationship` {#relationship}

An edge between two records, for `Relate` and `InsertRelation`.

```go
type Relationship struct {
	ID       *models.RecordID `json:"id"`
	In       models.RecordID  `json:"in"`
	Out      models.RecordID  `json:"out"`
	Relation models.Table     `json:"relation"`
	Data     map[string]any   `json:"data"`
}
```

| Field | Type | Description |
| --- | --- | --- |
| `ID` | [`*models.RecordID`](/docs/reference/golang/api/values/record-id.md) | The ID of the edge. `InsertRelation` uses it if you set it, and `Relate` ignores it. |
| `In` | `models.RecordID` | The record the edge starts from |
| `Out` | `models.RecordID` | The record the edge points to |
| `Relation` | [`models.Table`](/docs/reference/golang/api/values/table.md) | The relation table |
| `Data` | `map[string]any` | Other fields to store on the edge |

### `APIRequest` {#apirequest}

A request to an endpoint defined with `DEFINE API`, for `API`.

```go
type APIRequest struct {
	Method  string
	Body    any
	Headers map[string]string
	Query   map[string]string
}
```

| Field | Description |
| --- | --- |
| `Method` | The HTTP method, such as `"post"`. Empty means `"get"`. |
| `Body` | The request body, which can be any value |
| `Headers` | The request headers |
| `Query` | The query parameters |

### `APIResponse` {#apiresponse}

The response of an endpoint defined with `DEFINE API`. `T` is the type of the body.

```go
type APIResponse[T any] struct {
	Status  int               `json:"status"`
	Headers map[string]string `json:"headers,omitempty"`
	Body    T                 `json:"body"`
}
```

A response with an unsuccessful status is not an error. When its body does not fit `T`, `Body` is the zero value.

### `ExportOptions` {#exportoptions}

Chooses what `db.Export()` writes. The zero value exports every definition and every record.

```go
type ExportOptions struct {
	ExcludeUsers     bool
	ExcludeAccesses  bool
	ExcludeParams    bool
	ExcludeFunctions bool
	ExcludeAnalyzers bool
	ExcludeRecords   bool
	Tables           []string
}
```

`ExcludeRecords` exports the definitions of tables without their records. When `Tables` is not empty, it limits the export to those tables. See [Import and export](/docs/reference/golang/concepts/import-and-export.md#choosing-what-to-export).

### `VersionData` {#versiondata}

The version information that `.Version()` returns.

```go
type VersionData struct {
	Version   string `json:"version"`
	Build     string `json:"build"`
	Timestamp string `json:"timestamp"`
}
```

### `Notification` {#notification}

One live query notification, received on the channel from `.LiveNotifications()`.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/connection`

```go
type Notification struct {
	ID     *models.UUID `json:"id,omitempty"`
	Action Action       `json:"action"`
	Result interface{}  `json:"result"`
}
```

| Field | Type | Description |
| --- | --- | --- |
| `ID` | [`*models.UUID`](/docs/reference/golang/api/values/uuid.md) | The UUID of the live query |
| `Action` | `Action` | What happened |
| `Result` | `any` | The record, as a `map[string]any`, or the JSON Patch operations |

`Action` is one of these constants:

| Constant | Value | Meaning |
| --- | --- | --- |
| `connection.CreateAction` | `"CREATE"` | A record was created |
| `connection.UpdateAction` | `"UPDATE"` | A record was updated |
| `connection.DeleteAction` | `"DELETE"` | A record was deleted |
| `connection.KilledAction` | `"KILLED"` | The live query was stopped |

---

## Client configuration

### `Option` {#option}

Configures a client created with `FromEndpointURLStringWithOptions` or `FromConnectionWithOptions`. [Options](/docs/reference/golang/api/core/db.md#options) lists the functions that return an `Option`.

```go
type Option func(*options)
```

### `ConnectionStatus` {#connectionstatus}

The state of a client's connection, from `.Status()` and in a `StatusEvent`. Its `String()` method returns the name in lower case, such as `connected`.

| Constant | Meaning |
| --- | --- |
| `StatusConnected` | The client sends requests to the server |
| `StatusDisconnected` | The client lost the connection, or an attempt to reconnect failed. Requests wait. |
| `StatusReconnecting` | The client is trying to reconnect |
| `StatusClosed` | The client was closed, or gave up reconnecting. Requests fail. |

### `StatusEvent` {#statusevent}

A change of the state of a client's connection. The client passes it to the function that you give to `.OnStatus()`.

```go
type StatusEvent struct {
	Status  ConnectionStatus
	Attempt int
	Err     error
}
```

| Field | Description |
| --- | --- |
| `Status` | The new state |
| `Attempt` | The number of the attempt to reconnect since the client lost the connection, from 1. It is 0 for the event that reports the loss. |
| `Err` | Why the client lost the connection, or why an attempt failed. On `StatusConnected` after a reconnect, what the client could not restore, or `nil`. On `StatusClosed`, why the client gave up. |

### `CBORVersion` {#cborversion}

The CBOR version a connection uses, from `db.CBORVersion()`.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/connection`

| Constant | `String()` | Meaning |
| --- | --- | --- |
| `connection.CBORv2` | `"cbor.2"` | cbor.2, with SurrealDB 4.0 |
| `connection.CBORv1` | `"cbor"` | Plain CBOR, with earlier servers |

---

## Type constraints

### `TableOrRecord` {#tableorrecord}

The types that the `what` argument of the CRUD functions accepts. A `string` is always a table name.

```go
type TableOrRecord interface {
	string | models.Table | models.RecordID | []models.Table | []models.RecordID
}
```

See [`Table`](/docs/reference/golang/api/values/table.md) and [`RecordID`](/docs/reference/golang/api/values/record-id.md).

### `sendable` {#sendable}

The types that the `s` argument of the query and CRUD functions accepts.

```go
type sendable interface {
	*DB | *Session | *Transaction
}
```

### `liveQueryable` {#livequeryable}

The types that the `s` argument of `Live` and `Kill` accepts. A live query belongs to a session, so a `*Transaction` is not one of them.

```go
type liveQueryable interface {
	*DB | *Session
}
```

---

## See also

- [DB reference](/docs/reference/golang/api/core/db.md) for the functions that use these types
- [Errors reference](/docs/reference/golang/api/errors.md) for the error types
- [Values reference](/docs/reference/golang/api/values.md) for value types such as `RecordID` and `Table`

---

Source: https://surrealdb.com/docs/reference/golang/api/values

# Go values

Value types in the models package of the Go SDK and the SurrealDB types they map to: RecordID, Table, CustomDateTime, CustomDuration, UUID, Set, Range, geometry, File, Float16, DecimalString, BigDecimal, PlainDate, PlainTime, Timestamp, Interval, Regex and None, with the type mapping table.

The Go SDK maps most SurrealDB values onto Go's own types, such as `string`, `bool`, `int64`, `time.Time` and `map[string]any`. Go has no type for some values, such as record IDs, geometry and the SurrealDB 4.0 kinds. For these values, the SDK has types in the `models` package, and this section has a page for each type. This page lists the types and maps each SurrealDB type onto its Go type. For a guide to how values convert, with examples, see [Value types](/docs/reference/golang/concepts/value-types.md).

```go title="Import"
import "github.com/surrealdb/surrealdb.go/v2/pkg/models"
```

## Value types {#value-types}

- **[CustomDateTime](/docs/reference/golang/api/values/datetime.md):** `CustomDateTime` wraps `time.Time` for a datetime. The SDK also sends a `time.Time` as a datetime.
- **[CustomDuration](/docs/reference/golang/api/values/duration.md):** `CustomDuration` wraps `time.Duration` for a duration. The SDK also sends a `time.Duration` as a duration.
- **[Geometry](/docs/reference/golang/api/values/geometry.md):** `GeometryPoint` and six other types for GeoJSON geometry.
- **[Range](/docs/reference/golang/api/values/range.md):** `Range` with `BoundIncluded` and `BoundExcluded`, for a span of values or of record IDs.
- **[RecordID](/docs/reference/golang/api/values/record-id.md):** `RecordID` names one record by its table and ID.
- **[Table](/docs/reference/golang/api/values/table.md):** `Table` names a table.
- **[UUID](/docs/reference/golang/api/values/uuid.md):** `UUID` holds a UUID.
- **[Set](/docs/reference/golang/api/values/set.md):** `Set` holds the distinct values of a set.
- **[Numbers](/docs/reference/golang/api/values/numbers.md):** `Float16`, `DecimalString` and `BigDecimal`, and the Go types for the sized numbers of SurrealDB 4.0.
- **[Dates, times and intervals](/docs/reference/golang/api/values/temporal.md):** `PlainDate`, `PlainTime`, `Timestamp` and `Interval`, for the calendar kinds of SurrealDB 4.0.
- **[Regex](/docs/reference/golang/api/values/regex.md):** `Regex` holds a pattern for the `regex` kind of SurrealDB 4.0.
- **[File](/docs/reference/golang/api/values/file.md):** `File` points to a file in a bucket.

## Type mapping {#type-mapping}

| SurrealDB | Go | Page |
| --- | --- | --- |
| `NONE` | `models.None` to send; `nil` when decoded | [Value types](/docs/reference/golang/concepts/value-types.md#none-and-null) |
| `NULL` | `nil` | [Value types](/docs/reference/golang/concepts/value-types.md#none-and-null) |
| `bool` | `bool` | |
| `int` | `int`, `int64`, and the other integer types | [Numbers](/docs/reference/golang/api/values/numbers.md) |
| `float` | `float64` | [Numbers](/docs/reference/golang/api/values/numbers.md) |
| `decimal` | `models.DecimalString` | [Numbers](/docs/reference/golang/api/values/numbers.md#decimalstring) |
| `string` | `string` | |
| `bytes` | `[]byte` | |
| `datetime` | `time.Time`, `models.CustomDateTime` | [CustomDateTime](/docs/reference/golang/api/values/datetime.md) |
| `duration` | `time.Duration`, `models.CustomDuration` | [CustomDuration](/docs/reference/golang/api/values/duration.md) |
| `uuid` | `models.UUID` | [UUID](/docs/reference/golang/api/values/uuid.md) |
| `record` | `models.RecordID` | [RecordID](/docs/reference/golang/api/values/record-id.md) |
| `table` | `models.Table` | [Table](/docs/reference/golang/api/values/table.md) |
| `array` | `[]any` or a typed slice | |
| `object` | `map[string]any` or a struct | |
| `set` | `models.Set` | [Set](/docs/reference/golang/api/values/set.md) |
| `range` | `models.Range` | [Range](/docs/reference/golang/api/values/range.md) |
| `geometry` | `models.GeometryPoint` and the other geometry types | [Geometry](/docs/reference/golang/api/values/geometry.md) |
| `file` | `models.File` | [File](/docs/reference/golang/api/values/file.md) |
| `i8`, `u8`, `i16`, `u16`, `i32`, `u32`, `u64` | `int8`, `uint8`, `int16`, `uint16`, `int32`, `uint32`, `uint64` | [Numbers](/docs/reference/golang/api/values/numbers.md#sized-numbers) |
| `f16`, `f32` | `models.Float16`, `float32` | [Numbers](/docs/reference/golang/api/values/numbers.md#sized-numbers) |
| `bigdecimal` | `models.BigDecimal` | [Numbers](/docs/reference/golang/api/values/numbers.md#bigdecimal) |
| `date`, `time`, `timestamp`, `interval` | `models.PlainDate`, `PlainTime`, `Timestamp`, `Interval` | [Dates, times and intervals](/docs/reference/golang/api/values/temporal.md) |
| `regex` | `models.Regex` | [Regex](/docs/reference/golang/api/values/regex.md) |

The SurrealDB 4.0 kinds, from `i8` to `regex`, keep their type over cbor.2 only. With a server before 4.0, the SDK and the server send them as the nearest older kind, as [Value types](/docs/reference/golang/concepts/value-types.md#surrealdb-40-kinds) describes.

## See also

- [Value types](/docs/reference/golang/concepts/value-types.md) for how values convert, with examples
- [SurrealQL data types](/docs/reference/query-language/language-primitives/data-types.md) for the type system of SurrealDB

---

Source: https://surrealdb.com/docs/reference/golang/api/values/datetime

# CustomDateTime

The CustomDateTime type of the Go SDK wraps time.Time for the SurrealDB datetime kind, with nanosecond precision. A time.Time is sent the same way, and a zero time is sent as NONE.

`CustomDateTime` wraps Go's `time.Time` for the SurrealDB `datetime` kind, an instant in UTC with nanosecond precision. You can send a `time.Time` as it is, and the SDK sends it as a `datetime` in the same way. A datetime decodes into a `time.Time` field, or into a `CustomDateTime` when the target is `any`.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [pkg/models/datetime.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/datetime.go)

---

## Definition

```go
type CustomDateTime struct {
	time.Time
}
```

`CustomDateTime` embeds `time.Time`, so every method of `time.Time` is available on it.

---

## How datetimes convert {#conversion}

The SDK sends a `time.Time`, a `*time.Time` and a `CustomDateTime` as a CBOR datetime that holds seconds and nanoseconds. It sends a zero time as `NONE`, and a `nil` `*time.Time` as `NULL`.

```go
type Event struct {
	ID        *models.RecordID `json:"id,omitempty"`
	StartedAt time.Time        `json:"started_at"`
	EndedAt   *time.Time       `json:"ended_at"`
}
```

With this struct, the record has no `started_at` field while `StartedAt` holds the zero time, and `ended_at` is `NULL` while `EndedAt` is `nil`.

A `CustomDateTime` also decodes a SurrealDB 4.0 `date` as its midnight UTC, and a `timestamp` as its wall clock read as UTC. This is how plain CBOR carries these two kinds. For those kinds, use [`PlainDate` and `Timestamp`](/docs/reference/golang/api/values/temporal.md) instead.

---

## Methods

### `.String()` {#string}

Returns the datetime in UTC, formatted as `2006-01-02T15:04:05Z`.

```go title="Syntax"
s := dt.String()
```

**Returns:** `string`

### `.SurrealString()` {#surrealstring}

Returns the datetime as a SurrealQL value: `<datetime> '2006-01-02T15:04:05Z'`.

```go title="Syntax"
s := dt.SurrealString()
```

**Returns:** `string`

### `.IsZero()` {#iszero}

Reports whether the datetime is `nil` or the zero time.

```go title="Syntax"
zero := dt.IsZero()
```

**Returns:** `bool`

---

## Usage

```go
import "github.com/surrealdb/surrealdb.go/v2/pkg/models"

now := models.CustomDateTime{Time: time.Now()}

results, err := surrealdb.Query[[]any](ctx, db, "RETURN [$now, type::of($now)]", map[string]any{
	"now": now,
})
```

---

## See also

- [Duration](/docs/reference/golang/api/values/duration.md) for fixed lengths of time
- [Dates, times and intervals](/docs/reference/golang/api/values/temporal.md) for the calendar kinds of SurrealDB 4.0
- [Value types](/docs/reference/golang/concepts/value-types.md#datetimes) for how values convert
- [SurrealQL datetime type](/docs/reference/query-language/language-primitives/data-types/datetimes.md) for the underlying data model

---

Source: https://surrealdb.com/docs/reference/golang/api/values/duration

# CustomDuration

The CustomDuration type of the Go SDK wraps time.Duration for the SurrealDB duration kind, with SurrealDB formatting such as 1d2h30m. A time.Duration is sent the same way, and CustomDurationString, FormatDuration and ParseDuration handle duration text.

`CustomDuration` wraps Go's `time.Duration` for the SurrealDB `duration` kind, and formats it in the syntax of SurrealDB, such as `1d2h30m`. You can send a `time.Duration` as it is, and the SDK sends it as a `duration` in the same way. A duration decodes into a `time.Duration` field, or into a `CustomDuration` when the target is `any`.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [pkg/models/duration.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/duration.go)

---

## Definition

```go
type CustomDuration struct {
	time.Duration
}
```

`CustomDuration` embeds `time.Duration`, so every method of `time.Duration` is available on it.

---

## How durations convert {#conversion}

The SDK sends a `time.Duration` and a `CustomDuration` as a CBOR duration that holds seconds and nanoseconds. Version 1 of the SDK sent a `time.Duration` as an `int` of nanoseconds. Such integers still decode into a `time.Duration` field.

A `CustomDuration` also decodes a SurrealDB 4.0 `time` as the duration since midnight. This is how plain CBOR carries a `time`. For a time of day, use [`PlainTime`](/docs/reference/golang/api/values/temporal.md#plaintime) instead.

```go
type Job struct {
	ID      *models.RecordID `json:"id,omitempty"`
	Timeout time.Duration    `json:"timeout"`
}

_, err := surrealdb.Create[Job](ctx, db, "job", Job{Timeout: 90 * time.Second})
```

---

## Methods

### `.String()` {#string}

Returns the duration in the syntax of SurrealDB, such as `2h30m`, `1d12h` or `500ms`.

```go title="Syntax"
s := dur.String()
```

**Returns:** `string`

### `.ToCustomDurationString()` {#tocustomdurationstring}

Converts the duration to a `CustomDurationString`.

```go title="Syntax"
ds := dur.ToCustomDurationString()
```

**Returns:** `CustomDurationString`

---

## Related types

### `CustomDurationString` {#customdurationstring}

A duration as text in the syntax of SurrealDB, such as `"1d2h30m"`. The SDK sends it as a duration. Encoding a `CustomDurationString` that is not a valid duration fails with an error, such as `invalid duration "nonsense"`.

```go
type CustomDurationString string
```

#### Methods

- `.String()` returns the text
- `.ToDuration()` parses it into a `time.Duration`
- `.ToCustomDuration()` converts it to a `CustomDuration`

---

## Helper functions

### `FormatDuration` {#formatduration}

Formats nanoseconds in the syntax of SurrealDB.

```go title="Syntax"
s := models.FormatDuration(ns)
```

**Returns:** `string`

### `ParseDuration` {#parseduration}

Parses a duration in the syntax of SurrealDB into nanoseconds.

```go title="Syntax"
ns, err := models.ParseDuration("1d2h30m")
```

**Returns:** `(int64, error)`

The units are `y`, `w`, `d`, `h`, `m`, `s`, `ms`, `us` or `µs`, and `ns`.

---

## Usage

```go
import "github.com/surrealdb/surrealdb.go/v2/pkg/models"

dur := models.CustomDuration{Duration: 2*time.Hour + 30*time.Minute}
fmt.Println(dur.String())
```

```text title="Output"
2h30m
```

---

## See also

- [CustomDateTime](/docs/reference/golang/api/values/datetime.md) for instants
- [Dates, times and intervals](/docs/reference/golang/api/values/temporal.md) for calendar periods, which a duration cannot hold
- [Value types](/docs/reference/golang/concepts/value-types.md#durations) for how values convert
- [SurrealQL duration type](/docs/reference/query-language/language-primitives/data-types/durations.md) for the underlying data model

---

Source: https://surrealdb.com/docs/reference/golang/api/values/file

# File

models.File in the Go SDK for the SurrealDB file kind: a pointer to a file in a bucket, written f"bucket:/key" in SurrealQL, NewFile, the Bucket and Key fields, sending a file as a query variable, and its String form.

A `models.File` points to a file in a SurrealDB bucket, as the SurrealQL value `f"bucket:/key"` does. It holds the name of the bucket and the key of the file, not the content of the file. This page documents the type and how to send one. Files are an experimental feature of SurrealDB. A server turns the feature on with `--allow-experimental files`, but the SDK always decodes `File` values.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [pkg/models/file.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/file.go)

---

## Definition {#definition}

```go
type File struct {
	Bucket string
	Key    string
}
```

| Field | Description |
| --- | --- |
| `Bucket` | The name of the bucket the file is in |
| `Key` | The path of the file in the bucket, starting with a slash |

---

## Constructor {#constructor}

### `NewFile` {#newfile}

Returns a `File` for the file at `key` in `bucket`. It adds a leading slash to `key` when `key` has none.

```go title="Syntax"
f := models.NewFile(bucket, key)
```

**Returns:** `File`

```go
f := models.NewFile("docs", "report.pdf")
fmt.Println(f.Bucket, f.Key)
```

```text title="Output"
docs /report.pdf
```

---

## Files in queries {#queries}

Send a `File` as a query variable. The SDK sends it as its own kind, so any bucket and key work:

```go
results, err := surrealdb.Query[[]byte](ctx, db, "RETURN $file.get()", map[string]any{
	"file": models.NewFile("docs", "report.pdf"),
})
```

A file that the server returns, such as one stored in a field of a record, decodes into a `File`, including from `any`. See [Files](/docs/reference/query-language/language-primitives/data-types/files.md) for the functions that read and write the content of a file.

---

## Text form {#string}

`.String()` returns the file as a file string, such as `f"docs:/report.pdf"`. It puts a backslash before each character that is not an ASCII letter or digit, `_`, `-`, `.`, or a `/` in the key. For example, `models.NewFile("docs", "my report.pdf")` gives `f"docs:/my\ report.pdf"`. A file string has no escape syntax, so SurrealDB reads the result back as the same file only when no character needed a backslash. Send a `File` as a variable rather than writing its text into a query.

---

## See also

- [Value types](/docs/reference/golang/concepts/value-types.md#files) for how values convert
- [Files](/docs/reference/query-language/language-primitives/data-types/files.md) for the SurrealQL kind

---

Source: https://surrealdb.com/docs/reference/golang/api/values/geometry

# Geometry

The Go SDK provides typed geometry types for all SurrealDB geometry values including points, lines, polygons, and collections.

The geometry types of SurrealDB are based on GeoJSON, and the SDK has a Go type for each one. The SDK encodes each Go type with its own CBOR tag, which this page gives under the type.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [pkg/models/geometry.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/geometry.go)

---

## Types

### `GeometryPoint` {#geometrypoint}

A geographic point with longitude and latitude coordinates.

```go
type GeometryPoint struct {
    Longitude float64
    Latitude  float64
}
```

CBOR tag: 88

#### Methods

- `.GetCoordinates()` - returns `[2]float64{Longitude, Latitude}`

#### Examples

```go
point := models.GeometryPoint{Longitude: -0.118, Latitude: 51.509}
```

### `GeometryLine` {#geometryline}

A line consisting of two or more points.

```go
type GeometryLine []GeometryPoint
```

CBOR tag: 89

### `GeometryPolygon` {#geometrypolygon}

A polygon consisting of one or more closed line rings.

```go
type GeometryPolygon []GeometryLine
```

CBOR tag: 90

### `GeometryMultiPoint` {#geometrymultipoint}

A collection of points.

```go
type GeometryMultiPoint []GeometryPoint
```

CBOR tag: 91

### `GeometryMultiLine` {#geometrymultiline}

A collection of lines.

```go
type GeometryMultiLine []GeometryLine
```

CBOR tag: 92

### `GeometryMultiPolygon` {#geometrymultipolygon}

A collection of polygons.

```go
type GeometryMultiPolygon []GeometryPolygon
```

CBOR tag: 93

### `GeometryCollection` {#geometrycollection}

A collection of geometry values, which can be of different types.

```go
type GeometryCollection []any
```

CBOR tag: 94

---

## Usage

```go
import "github.com/surrealdb/surrealdb.go/v2/pkg/models"

type Location struct {
    ID       *models.RecordID      `json:"id,omitempty"`
    Name     string                `json:"name"`
    Position models.GeometryPoint  `json:"position"`
    Boundary models.GeometryPolygon `json:"boundary"`
}

line := models.GeometryLine{
    {Longitude: -0.118, Latitude: 51.509},
    {Longitude: -0.076, Latitude: 51.508},
}

polygon := models.GeometryPolygon{
    models.GeometryLine{
        {Longitude: -0.12, Latitude: 51.50},
        {Longitude: -0.08, Latitude: 51.50},
        {Longitude: -0.08, Latitude: 51.52},
        {Longitude: -0.12, Latitude: 51.52},
        {Longitude: -0.12, Latitude: 51.50},
    },
}
```

---

## See also

- [RecordID](/docs/reference/golang/api/values/record-id.md) for the record identifier type
- [Value types](/docs/reference/golang/concepts/value-types.md) for the full type mapping
- [Data manipulation](/docs/reference/golang/concepts/data-manipulation.md) for using geometry values in CRUD operations
- [SurrealQL geometry types](/docs/reference/query-language/language-primitives/data-types/geometries.md) for the underlying data model

---

Source: https://surrealdb.com/docs/reference/golang/api/values/numbers

# Numbers

Numbers in the Go SDK: Go integers and floats as SurrealDB int and float, the SurrealDB 4.0 sized numbers i8 to u64, f16 and f32 as Go's sized types and models.Float16, decimals as models.DecimalString, and bigdecimal as models.BigDecimal, with how each converts over cbor.2 and plain CBOR.

SurrealDB has the number kinds `int`, `float` and `decimal`. SurrealDB 4.0 adds sized numbers, which are the integers `i8` to `u64` and the floats `f16` and `f32`. It also adds `bigdecimal`, a decimal of any precision. The Go SDK maps most of these kinds onto Go's own number types. For the three that Go has no type for, the SDK has a type in the `models` package: `Float16`, `DecimalString` and `BigDecimal`. This page covers each.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [sized.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/sized.go), [big_decimal.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/big_decimal.go)

---

## Plain numbers {#plain-numbers}

The SDK sends a Go `int`, `int64` or `uint64` up to `math.MaxInt64` as a SurrealDB `int`, and a `float64` as a `float`. When the target is `any`, an `int` of zero or more decodes into a `uint64`, and a negative `int` into an `int64`. A `float` decodes into a `float64`. A struct field of any Go number type takes any number that fits it.

---

## Sized numbers {#sized-numbers}

Over cbor.2, which SurrealDB 4.0 speaks, the SDK sends Go's sized number types as the sized numbers of SurrealDB 4.0. These numbers decode back into the same Go types, including from `any`. Over plain CBOR, which earlier servers speak, the SDK sends them as the older kinds in the last column:

| Go type | Over cbor.2 (SurrealDB 4.0) | Over plain CBOR |
| --- | --- | --- |
| `int8`, `uint8` | `i8`, `u8` | `int` |
| `int16`, `uint16` | `i16`, `u16` | `int` |
| `int32`, `uint32` | `i32`, `u32` | `int` |
| `uint64` above `math.MaxInt64` | `u64` | `decimal` |
| [`models.Float16`](#float16) | `f16` | `float` |
| `float32` | `f32` | `float` |

```go
results, err := surrealdb.Query[[]any](ctx, db,
	"RETURN [type::of($level), type::of($score), type::of($big)]",
	map[string]any{
		"level": int8(5),
		"score": float32(1.5),
		"big":   uint64(math.MaxUint64),
	},
)
fmt.Println((*results)[0].Result)
```

```text title="Output with SurrealDB 4.0"
[i8 f32 u64]
```

When you send a value as a sized type, the server stores it as that type. A later read into `any` then gives the sized Go type back. Code that asserts a decoded number to `int64` or `uint64` has to allow for these types.

`models.Float32Exact(f)` reports whether a `float64` converts to a `float32` without losing precision. `0.1` does not, and `1.5` does.

### `Float16` {#float16}

Go has no half-precision float, so `models.Float16` holds the 16 bits of an IEEE 754 binary16 value. Its zero value is `+0`.

| Function or method | Description |
| --- | --- |
| `NewFloat16(f)` | Returns `f` as a `Float16`, or an error when a `Float16` cannot hold it exactly, such as `0.1` or `65536`. It accepts NaN and the infinities. |
| `MustFloat16(f)` | As `NewFloat16`, but panics on an error |
| `Float16FromBits(bits)` | The `Float16` with the given bits |
| `.Float64()`, `.Float32()` | The value, converted exactly |
| `.Bits()` | The 16 bits |
| `.String()` | The value in its shortest form |

```go
h := models.MustFloat16(1.5)
fmt.Println(h, h.Float64())

_, err := models.NewFloat16(0.1)
fmt.Println(err)
```

```text title="Output"
1.5 1.5
float 0.1 cannot be losslessly represented as f16
```

---

## `DecimalString` {#decimalstring}

A SurrealDB `decimal` holds up to 28 digits after the point without rounding. Go has no decimal type, so `models.DecimalString` keeps the decimal as text:

```go
type DecimalString string
```

A `decimal` decodes into a `DecimalString`, including from `any`. The SDK sends a `DecimalString` as a `decimal`:

```go
type Price struct {
	Amount models.DecimalString `json:"amount"`
}

results, err := surrealdb.Query[Price](ctx, db, "RETURN { amount: 19.99dec }", nil)
fmt.Println((*results)[0].Result.Amount)
```

```text title="Output"
19.99
```

For arithmetic, read the text with `math/big` or a decimal library, such as `new(big.Rat).SetString(string(amount))`.

---

## `BigDecimal` {#bigdecimal}

A `models.BigDecimal` is a decimal of any precision, for the SurrealDB 4.0 `bigdecimal` kind. It holds what a `decimal` cannot: more than 28 digits after the point, or a coefficient of 2^96 or more. It keeps the digits as the server writes them, so `1.50` stays `1.50`. The zero value is `0`, a real number rather than `NONE`, so use a `*BigDecimal` with `omitempty` for a field that may be absent.

### Constructors {#bigdecimal-constructors}

| Function | Description |
| --- | --- |
| `ParseBigDecimal(s)` | Parses a decimal as the server does: an optional sign, digits with an optional point, and an optional exponent. It applies the exponent to the value, so `1.5e3` gives `1500`. It refuses spaces, NaN and the infinities. |
| `MustParseBigDecimal(s)` | As `ParseBigDecimal`, but panics on an error |

### Methods {#bigdecimal-methods}

| Method | Returns |
| --- | --- |
| `.Equal(o)` | Whether the values are equal, so `1.50` equals `1.5`. `==` compares the digits as written. |
| `.Compare(o)` | `-1`, `0` or `+1`, comparing the values |
| `.FitsDecimal()` | Whether a SurrealDB `decimal` holds the value exactly |
| `.String()` | The value as the server writes it, such as `1.50` |
| `.SurrealString()` | The value as a SurrealQL literal, such as `1.50bigdec` |

```go
price := models.MustParseBigDecimal("79228162514264337593543950336.50")
fmt.Println(price, price.FitsDecimal())
fmt.Println(models.MustParseBigDecimal("1.5e3"))
fmt.Println(models.MustParseBigDecimal("1.50").Equal(models.MustParseBigDecimal("1.5")))
```

```text title="Output"
79228162514264337593543950336.50 false
1500
true
```

For arithmetic, read `.String()` with `math/big` or a decimal library, such as `new(big.Rat).SetString(price.String())`.

### Sending and reading big decimals {#bigdecimal-conversion}

Over cbor.2, the SDK sends a `BigDecimal` as a `bigdecimal`, and a `bigdecimal` decodes into a `BigDecimal`, including from `any`. Over plain CBOR, the SDK sends a `BigDecimal` as a `decimal` when the value fits one, and as text when it does not. A `BigDecimal` decodes from either form.

---

## See also

- [Value types](/docs/reference/golang/concepts/value-types.md#surrealdb-40-kinds) for every SurrealDB 4.0 kind
- [Numbers](/docs/reference/query-language/language-primitives/data-types/numbers.md) for the SurrealQL number kinds

---

Source: https://surrealdb.com/docs/reference/golang/api/values/range

# Range

The generic Range type of the Go SDK for SurrealDB ranges, with BoundIncluded and BoundExcluded bounds, open sides, RecordRangeID, the range helpers of the surrealql package, and ranges of record IDs for Select.

`Range` is a generic type for a SurrealDB range, such as `1..=10`. Each of its two bounds can include its value in the range or exclude it. Its main use is as the ID of a [`RecordID`](/docs/reference/golang/api/values/record-id.md), to work on a range of records.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [pkg/models/range.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/range.go)

---

## Definitions

### `Range` {#range-struct}

```go
type Range[T any, TBeg Bound[T], TEnd Bound[T]] struct {
	Begin *TBeg
	End   *TEnd
}
```

A `nil` `Begin` or `End` leaves that side of the range open. CBOR tag: 49.

### `BoundIncluded` {#boundincluded}

A bound whose value is in the range.

```go
type BoundIncluded[T any] struct {
	Value T
}
```

CBOR tag: 50.

### `BoundExcluded` {#boundexcluded}

A bound whose value is not in the range.

```go
type BoundExcluded[T any] struct {
	Value T
}
```

CBOR tag: 51.

### `Bound` {#bound}

The constraint for the two bound types.

```go
type Bound[T any] interface {
	BoundIncluded[T] | BoundExcluded[T]
}
```

### `RecordRangeID` {#recordrangeid}

A range of record IDs in one table.

```go
type RecordRangeID[T any, TBeg Bound[T], TEnd Bound[T]] struct {
	Range[T, TBeg, TEnd]
	Table Table
}
```

---

## Selecting a range of records {#record-ranges}

Use a `Range` as the ID of a `RecordID` to select, update or delete the records in the range. This example selects `reading:2` and `reading:3`:

```go
readings := models.RecordID{
	Table: "reading",
	ID: models.Range[int, models.BoundIncluded[int], models.BoundExcluded[int]]{
		Begin: &models.BoundIncluded[int]{Value: 2},
		End:   &models.BoundExcluded[int]{Value: 4},
	},
}

results, err := surrealdb.Select[[]map[string]any](ctx, db, readings)
```

In a record ID range, the value of a bound cannot be `nil` or `models.None`. Encoding such a range returns an error. For an array ID, use `models.None` inside the array as the lowest value of a part, as in `[]any{"London", models.None}`.

The [query builder](/docs/reference/golang/concepts/query-builder.md#selecting-a-range-of-records) has helpers that build a range, such as `surrealql.RangeBeginInclusiveEndExclusive(2, 4)`, `surrealql.RangeOpenBeginInclusive(2)` and `surrealql.RangeOpen()`.

---

## Methods

### `.String()` {#string}

Returns the range as text for display, such as `2..4` or `1>..=10`. An open side is empty, so a range open on both sides is `..`. The text is not always valid SurrealQL, so do not send it in a query.

**Returns:** `string`

### `.GetJoinString()` {#getjoinstring}

Returns the operator between the bounds: `..`, `..=`, `>..` or `>..=`.

**Returns:** `string`

---

## See also

- [RecordID](/docs/reference/golang/api/values/record-id.md) for record IDs whose ID is a range
- [Data manipulation](/docs/reference/golang/concepts/data-manipulation.md#selecting-a-range-of-records) for selecting a range of records
- [SurrealQL ranges](/docs/reference/query-language/language-primitives/data-types/ranges.md) for the underlying data model

---

Source: https://surrealdb.com/docs/reference/golang/api/values/record-id

# RecordID

The RecordID type of the Go SDK names a SurrealDB record by its table and ID, with NewRecordID, ParseRecordID, String and SurrealString, and IDs that are strings, numbers, arrays, objects or ranges.

A `RecordID` names one SurrealDB record by its table name and its ID, without the ambiguity of parsing text such as `person:tobie`. Use it as the target of a CRUD function, as a query variable, and as the `id` field of a struct.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [pkg/models/record_id.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/record_id.go)

---

## Definition

```go
type RecordID struct {
	Table string
	ID    any
}
```

`Table` must not be empty. `ID` can be any value that SurrealDB accepts as a record ID: a string, an integer, an array, an object, or a [`Range`](/docs/reference/golang/api/values/range.md) for a range of records.

---

## Constructors

### `NewRecordID` {#newrecordid}

Returns a `RecordID` with the given table name and ID.

```go title="Syntax"
id := models.NewRecordID(tableName, id)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>tableName</code> _(required)_</td>
            <td><code>string</code></td>
            <td>The table name.</td>
        </tr>
        <tr>
            <td><code>id</code> _(required)_</td>
            <td><code>any</code></td>
            <td>The ID of the record.</td>
        </tr>
    </tbody>
</table>

**Returns:** `RecordID`

```go
person := models.NewRecordID("person", "tobie")
event := models.NewRecordID("event", 42)
reading := models.NewRecordID("temperature", []any{"London", 2026})
```

### `ParseRecordID` {#parserecordid}

Parses text of the form `table:id` into a `RecordID`. The ID is always a string, so `ParseRecordID("event:42")` names the record `event:⟨42⟩`, not `event:42`. The result never matches a record whose ID is a number. The text must hold exactly one colon.

```go title="Syntax"
id, err := models.ParseRecordID(idStr)
```

**Returns:** `(*RecordID, error)`. For text without exactly one colon, it returns an error that wraps `ErrBadRecordID`.

For an ID that is not a string, build the `RecordID` with `NewRecordID`, or let the server parse the text with `type::record()` in a query.

---

## Methods

### `.String()` {#string}

Returns the record ID as text, such as `person:tobie`. It writes a part that needs escaping between `⟨` and `⟩`, as SurrealDB 2.x displayed it. For example, `models.NewRecordID("user", "john-doe")` gives `user:⟨john-doe⟩`. The text is for display and logs. To send a record ID, pass the `RecordID` itself.

```go title="Syntax"
s := id.String()
```

**Returns:** `string`

### `.SurrealString()` {#surrealstring}

Returns the record ID as a SurrealQL record string, such as `r'person:tobie'`.

```go title="Syntax"
s := id.SurrealString()
```

**Returns:** `string`

---

## In structs

Use `*models.RecordID` with `omitempty` for the `id` field of a struct. You can then send the struct without an ID and read it back with one:

```go
type Person struct {
	ID   *models.RecordID `json:"id,omitempty"`
	Name string           `json:"name"`
}
```

The SDK sends a record ID as CBOR tag 8, which holds the table and the ID. A record ID decodes into a `RecordID`, including from `any`.

---

## Record ranges

A `RecordID` whose `ID` is a [`Range`](/docs/reference/golang/api/values/range.md) names the records in that range, for [`Select`](/docs/reference/golang/concepts/data-manipulation.md#selecting-a-range-of-records) and the other CRUD functions:

```go
readings := models.RecordID{
	Table: "reading",
	ID: models.Range[int, models.BoundIncluded[int], models.BoundExcluded[int]]{
		Begin: &models.BoundIncluded[int]{Value: 2},
		End:   &models.BoundExcluded[int]{Value: 4},
	},
}
```

---

## See also

- [Table](/docs/reference/golang/api/values/table.md) for the table name type
- [Value types](/docs/reference/golang/concepts/value-types.md#record-ids-and-tables) for how values convert
- [Data manipulation](/docs/reference/golang/concepts/data-manipulation.md) for record IDs in CRUD functions
- [SurrealQL record IDs](/docs/reference/query-language/language-primitives/data-types/record-ids.md) for the underlying data model

---

Source: https://surrealdb.com/docs/reference/golang/api/values/regex

# Regex

models.Regex in the Go SDK for the SurrealDB 4.0 regex kind: a pattern in Rust regex syntax, sending a regex as a query variable to match strings, String and SurrealString, why a *regexp.Regexp is refused, and why servers before 4.0 cannot receive a regex.

A `models.Regex` holds the text of a regular expression for the SurrealDB `regex` kind. SurrealDB compiles a regex with the syntax of the Rust `regex` crate, not with Go's `regexp` package. The SDK therefore keeps the pattern as text and never compiles it. This page documents the type and when you can send a regex. Sending a `Regex` needs SurrealDB 4.0.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [pkg/models/regex.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/regex.go)

---

## Definition {#definition}

```go
type Regex struct {
	Pattern string
}
```

`Pattern` is the text of the regex, without the slashes around it. The zero value is the empty pattern, which matches any text.

---

## Matching in a query {#matching}

Send a `Regex` as a query variable, and use the SurrealQL `=` operator to compare a string with it. With a regex, `=` checks whether the string matches the pattern:

```go
results, err := surrealdb.Query[[]string](ctx, db,
	"SELECT VALUE name FROM person WHERE name = $pattern",
	map[string]any{"pattern": models.Regex{Pattern: "^[A-J]"}},
)
```

A regex that the server returns, such as one stored in a field, decodes into a `Regex`, including from `any`.

---

## Methods {#methods}

### `.String()` {#string}

Returns the regex as the server writes it: the pattern between slashes, with each slash in it escaped, as in `/a\/b/`.

**Returns:** `string`

### `.SurrealString()` {#surrealstring}

Returns the regex as a SurrealQL literal, such as `/a+/`. It escapes each slash that the pattern does not escape already. For the empty pattern, it writes a cast of the empty string instead, because `//` starts a comment in SurrealQL.

**Returns:** `string`

```go
path := models.Regex{Pattern: "^/api/v[0-9]+/"}
fmt.Println(path.SurrealString())
```

```text title="Output"
/^\/api\/v[0-9]+\//
```

Send a regex as a variable rather than writing its literal into a query.

---

## Rust syntax and Go's regexp {#go-regexp}

The Rust syntax is close to the RE2 syntax of Go's `regexp`, but not the same. In Rust, `\d`, `\w`, `\s` and `\b` match Unicode text, while in Go they match ASCII only. The class set operations of Rust, such as `[a-z&&[^aeiou]]`, mean something else in Go. `regexp.Compile(r.Pattern)` gives Go's reading of a pattern, which can differ from the server's.

For this reason, the SDK never converts a `*regexp.Regexp` into a `Regex` or back. Sending a `regexp.Regexp` or a `*regexp.Regexp` fails with the error `cannot encode a *regexp.Regexp, as Go's regular expression syntax is not SurrealQL's: use models.Regex`.

---

## Servers before SurrealDB 4.0 {#earlier-servers}

Plain CBOR, which servers before 4.0 speak, has no form for a regex. Encoding a `Regex` for plain CBOR fails with an error that wraps `constants.ErrNeedsCBOR2`, and the SDK sends nothing:

```text title="Error output with SurrealDB 3.x"
cborwire: a regex (CBOR tag 193) has no plain CBOR form: the value can only be sent over cbor.2
```

To match on an earlier server, send the pattern as a string and cast it in the query. This works on both SurrealDB 3.x and 4.0:

```go
results, err := surrealdb.Query[bool](ctx, db, "RETURN $name = <regex>$pattern", map[string]any{
	"name":    "tobie",
	"pattern": "^[a-z]+$",
})
```

An HTTP connection sends plain CBOR until the server answers it in cbor.2. A `Regex` in the first request of a new HTTP connection therefore fails, even with SurrealDB 4.0. Connect with `WithVersionCheck(true)`, or sign in first, so that the connection uses cbor.2 from the start.

---

## See also

- [Value types](/docs/reference/golang/concepts/value-types.md#regular-expressions) for how values convert
- [Regex](/docs/reference/query-language/language-primitives/data-types/regex.md) for the SurrealQL kind

---

Source: https://surrealdb.com/docs/reference/golang/api/values/set

# Set

models.Set in the Go SDK for the SurrealDB set kind: a collection of distinct values that the server keeps sorted, NewSet, decoding a set into any or into a typed slice, writing a set back, and why a nil Set is NULL.

A `models.Set` holds the values of a SurrealDB `set`, a collection of distinct values that the server keeps sorted. This page documents the type and how a set converts.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [pkg/models/set.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/set.go)

---

## Definition {#definition}

```go
type Set []any
```

---

## Constructor {#constructor}

### `NewSet` {#newset}

Returns a `Set` of the given values. The result is never `nil`, so `NewSet()` returns an empty set.

```go title="Syntax"
s := models.NewSet(values...)
```

**Returns:** `Set`

---

## How sets convert {#conversion}

The SDK sends a `Set` as a SurrealDB `set`. The server sorts the values and removes duplicates, so you do not need to sort a `Set` or remove its duplicates before you send it:

```go
results, err := surrealdb.Query[models.Set](ctx, db, "RETURN $tags", map[string]any{
	"tags": models.NewSet("go", "db", "go"),
})
fmt.Println((*results)[0].Result)
```

```text title="Output"
[db go]
```

A set decodes into `any` as a `Set`, rather than a `[]any`, so a set that you read and write back stays a set. A set also decodes into a slice of a concrete type, such as a `[]string` field:

```go
type Post struct {
	Tags []string `json:"tags"`
}
```

The SDK sends a `[]string` or `[]any` as an `array`, not as a set. To write a set from a slice, wrap the slice in a `Set`. On SurrealDB 4.0, a field defined as `set<string>` also turns an array into a set. SurrealDB 3.x refuses an array for such a field.

---

## A nil set is NULL {#nil}

The SDK sends a `nil` `Set` as `NULL`, as it does any `nil` slice, and not as an empty set. Use `models.NewSet()` or `models.Set{}` for an empty set, and a `*Set` or `omitempty` for a field that may be absent.

---

## See also

- [Value types](/docs/reference/golang/concepts/value-types.md#sets) for how values convert
- [Sets](/docs/reference/query-language/language-primitives/data-types/sets.md) for the SurrealQL kind

---

Source: https://surrealdb.com/docs/reference/golang/api/values/table

# Table

The Table type represents a SurrealDB table name used to scope data operations to an entire table.

The `Table` type is a named string type that holds the name of a SurrealDB table. Pass a `Table` to `Select`, `Update` or `Delete` to work on every record in the table, or to `Create` and `Insert` to add records to it.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [pkg/models/table.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/table.go)

---

## Definition

```go
type Table string
```

---

## Methods

### `.String()` {#string}

Returns the table name as a plain string.

```go title="Syntax"
s := table.String()
```

**Returns:** `string`

---

## Usage

```go
import "github.com/surrealdb/surrealdb.go/v2/pkg/models"

persons, err := surrealdb.Select[[]Person](ctx, db, models.Table("persons"))

_, err = surrealdb.Insert[Person](ctx, db, models.Table("persons"), data)
```

The SDK sends a `Table` as CBOR tag 7.

---

## See also

- [RecordID](/docs/reference/golang/api/values/record-id.md) for targeting specific records
- [Data manipulation](/docs/reference/golang/concepts/data-manipulation.md) for using tables in CRUD operations

---

Source: https://surrealdb.com/docs/reference/golang/api/values/temporal

# Dates, times and intervals

PlainDate, PlainTime, Timestamp and Interval in the Go SDK for the SurrealDB 4.0 date, time, timestamp and interval kinds: constructors, parsing, infinity, conversion to and from time.Time, comparison, zero values, and what each becomes over cbor.2 and plain CBOR.

SurrealDB 4.0 adds four kinds for calendar and clock values that are not an instant. The Go SDK has a type for each kind in the `models` package:

- `PlainDate` for `date`, a calendar day
- `PlainTime` for `time`, a time of day
- `Timestamp` for `timestamp`, a date and a time of day with no time zone
- `Interval` for `interval`, a calendar period, such as one month and two days

This page documents the four types and how they convert. For an instant, use a `time.Time`, which the SDK sends as a [`datetime`](/docs/reference/golang/api/values/datetime.md). For a fixed length of time, use a `time.Duration`, which the SDK sends as a [`duration`](/docs/reference/golang/api/values/duration.md).

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [plain_date.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/plain_date.go), [plain_time.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/plain_time.go), [timestamp.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/timestamp.go), [interval.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/interval.go)

---

## How the types convert {#conversion}

Over cbor.2, which SurrealDB 4.0 speaks, the SDK sends each type as its own kind. Each kind decodes back into the same type, including from `any`. Servers before 4.0 speak plain CBOR and have none of these kinds, so the SDK and the server send the nearest older kind:

| Go type | Over cbor.2 (SurrealDB 4.0) | Over plain CBOR (earlier servers) |
| --- | --- | --- |
| `PlainDate` | `date` | A `datetime` at midnight UTC |
| `PlainTime` | `time` | The `duration` since midnight |
| `Timestamp` | `timestamp` | A `datetime`, with the wall clock read as UTC |
| `Interval` | `interval` | Its ISO 8601 text, as a `string` |

When the target is a Go type other than its own, a value decodes in the form that plain CBOR carries. A `date` decodes into a `time.Time` field as its midnight UTC, and a `time` decodes into a `models.CustomDuration` as the time since midnight.

```go
type Booking struct {
	ID     *models.RecordID `json:"id,omitempty"`
	Day    models.PlainDate `json:"day"`
	Opens  models.PlainTime `json:"opens"`
	Local  models.Timestamp `json:"local"`
	Length models.Interval  `json:"length"`
}

day, err := models.NewPlainDate(2026, time.March, 14)
if err != nil {
	log.Fatal(err)
}
opens, err := models.NewPlainTime(9, 30, 0, 0)
if err != nil {
	log.Fatal(err)
}

b, err := surrealdb.Create[Booking](ctx, db, models.NewRecordID("booking", 1), Booking{
	Day:    day,
	Opens:  opens,
	Local:  models.MustParseTimestamp("2026-03-14T09:30:00"),
	Length: models.Interval{Months: 1, Days: 2},
})
fmt.Println(b.Day, b.Opens, b.Local, b.Length)
```

```text title="Output with SurrealDB 4.0"
2026-03-14 09:30:00 2026-03-14T09:30:00 P1M2D
```

### Zero values and optional fields {#zero-values}

The zero value of each type is a real value: `PlainDate` is 1970-01-01, `PlainTime` is 00:00:00, `Timestamp` is 1970-01-01T00:00:00, and `Interval` is `PT0S`. None of them is `NONE`, and `omitempty` never leaves them out. For a field that may be absent, use a pointer with `omitempty`:

```go
type Subscription struct {
	Starts models.PlainDate  `json:"starts"`
	Ends   *models.PlainDate `json:"ends,omitempty"`
}
```

---

## `PlainDate` {#plaindate}

A calendar date with no time of day and no time zone, such as 2024-02-29, for the SurrealDB `date` kind. It holds the days since 1970-01-01 in the proleptic Gregorian calendar, from -262143-01-01 to +262142-12-31. These two dates stand for `-infinity` and `infinity`. You can compare `PlainDate` values with `==`.

### Constructors {#plaindate-constructors}

| Function | Description |
| --- | --- |
| `NewPlainDate(year, month, day)` | The date `year-month-day`, where year 0 is 1 BCE. It refuses a day that does not exist, such as February 30. |
| `ParsePlainDate(s)` | Parses `YYYY-MM-DD` as the server does, and `infinity`, `-infinity` and `epoch` |
| `MustParsePlainDate(s)` | As `ParsePlainDate`, but panics on an error |
| `PlainDateOf(t)` | The date on which a `time.Time` falls, in its own location |
| `PlainDateFromDays(days)` | The date `days` after 1970-01-01 |

`PlainDateInfinity` and `PlainDateNegInfinity` are the two infinities.

### Methods {#plaindate-methods}

| Method | Returns |
| --- | --- |
| `.Date()` | The year, month and day |
| `.Days()` | The days since 1970-01-01, negative before it |
| `.In(loc)` | The `time.Time` at the start of the date in `loc` |
| `.Compare(o)` | `-1`, `0` or `+1`. `-infinity` is before every date, and `infinity` after. |
| `.IsInfinite()` | Whether the date is `infinity` or `-infinity` |
| `.String()` | The date as the server writes it, such as `2024-02-29` or `infinity` |
| `.SurrealString()` | The date as a SurrealQL literal, such as `pd'2024-02-29'` |

```go
due := models.MustParsePlainDate("2024-02-29")
year, month, day := due.Date()
fmt.Println(year, month, day)
fmt.Println(due.SurrealString())
fmt.Println(models.PlainDateInfinity, models.PlainDateInfinity.Compare(due))
```

```text title="Output"
2024 February 29
pd'2024-02-29'
infinity 1
```

SurrealQL adds intervals and durations to dates. This query adds one month:

```go
results, err := surrealdb.Query[models.PlainDate](ctx, db, "RETURN $day + $length", map[string]any{
	"day":    models.MustParsePlainDate("2026-03-14"),
	"length": models.Interval{Months: 1},
})
fmt.Println((*results)[0].Result)
```

```text title="Output"
2026-04-14
```

---

## `PlainTime` {#plaintime}

A time of day with no date and no time zone, such as 12:34:56.789, for the SurrealDB `time` kind. It holds the nanoseconds since midnight, from 00:00:00 up to and including 24:00:00, the end of the day. You can compare `PlainTime` values with `==`.

### Constructors {#plaintime-constructors}

| Function | Description |
| --- | --- |
| `NewPlainTime(hour, minute, sec, nsec)` | The time `hour:minute:sec` and `nsec` nanoseconds. The only time past 23:59:59.999999999 is 24:00:00. |
| `ParsePlainTime(s)` | Parses `H:MM`, `H:MM:SS` or `H:MM:SS.fraction`, with up to nine digits in the fraction |
| `MustParsePlainTime(s)` | As `ParsePlainTime`, but panics on an error |
| `PlainTimeOf(t)` | The time of day of a `time.Time`, in its own location |
| `PlainTimeFromDuration(d)` | The time `d` after midnight, for `d` from 0 to 24 hours |

### Methods {#plaintime-methods}

| Method | Returns |
| --- | --- |
| `.Clock()` | The hour, minute and second. The hour is 24 for 24:00:00. |
| `.Nanosecond()` | The nanoseconds within the second |
| `.SinceMidnight()` | The time since midnight, as a `time.Duration` |
| `.Compare(o)` | `-1`, `0` or `+1` |
| `.String()` | The time as the server writes it, such as `09:30:00` |
| `.SurrealString()` | The time as a SurrealQL literal, such as `pt'09:30:00'` |

```go
fmt.Println(models.PlainTimeOf(time.Date(2026, 1, 1, 18, 45, 0, 0, time.UTC)))
fmt.Println(models.MustParsePlainTime("24:00"))
```

```text title="Output"
18:45:00
24:00:00
```

---

## `Timestamp` {#timestamp}

A date and a time of day with no time zone, such as 2024-02-29T12:34:56.789, for the SurrealDB `timestamp` kind. A `Timestamp` is the reading of a wall clock, not an instant: the same reading is a different instant in each time zone. For an instant, use a `time.Time`. A `Timestamp` holds the seconds and nanoseconds since 1970-01-01T00:00:00 of that reading. Like a `PlainDate`, it has an `infinity` and a `-infinity`. You can compare `Timestamp` values with `==`.

### Constructors {#timestamp-constructors}

| Function | Description |
| --- | --- |
| `ParseTimestamp(s)` | Parses a date, `T` or a space, and a time of day before 24:00:00, and `infinity`, `-infinity` and `epoch` |
| `MustParseTimestamp(s)` | As `ParseTimestamp`, but panics on an error |
| `TimestampOf(t)` | The reading of the wall clock of a `time.Time`, in its own location. Call `t.UTC()` first for the reading in UTC. |
| `TimestampFromUnix(sec, nsec)` | The timestamp `sec` seconds and `nsec` nanoseconds after 1970-01-01T00:00:00 |

`TimestampInfinity` and `TimestampNegInfinity` are the two infinities.

### Methods {#timestamp-methods}

| Method | Returns |
| --- | --- |
| `.In(loc)` | The instant at which a clock in `loc` shows the reading |
| `.Unix()` | The whole seconds since 1970-01-01T00:00:00 |
| `.Nanosecond()` | The nanoseconds within the second |
| `.Compare(o)` | `-1`, `0` or `+1` |
| `.IsInfinite()` | Whether the timestamp is `infinity` or `-infinity` |
| `.String()` | The timestamp as the server writes it, such as `2024-01-15T09:30:00` |
| `.SurrealString()` | The timestamp as a SurrealQL literal, such as `ts'2024-01-15T09:30:00'` |

A timestamp keeps the reading of the clock, whatever the time zone of the `time.Time` it came from:

```go
opens := time.Date(2024, 1, 15, 9, 30, 0, 0, time.FixedZone("UTC-5", -5*3600))

ts, err := models.TimestampOf(opens)
if err != nil {
	log.Fatal(err)
}
fmt.Println(ts)
fmt.Println(ts.In(time.UTC))
```

```text title="Output"
2024-01-15T09:30:00
2024-01-15 09:30:00 +0000 UTC
```

---

## `Interval` {#interval}

A span of months, days and microseconds, such as P1Y2M3DT4H5M6.5S, for the SurrealDB `interval` kind, as in PostgreSQL. An `Interval` keeps the three parts apart, because a month and a day have no fixed length. For example, a month after January 31 is not 30 days after it. Each part can be negative on its own.

```go
type Interval struct {
	Months       int32
	Days         int32
	Microseconds int64
}
```

### Methods {#interval-methods}

| Method | Returns |
| --- | --- |
| `.Equal(o)` | Whether the totals are equal, where a month is 30 days and a day is 24 hours |
| `.Compare(o)` | `-1`, `0` or `+1`, comparing the totals |
| `.String()` | The interval in ISO 8601, as the server writes it, such as `P1Y2M3DT4H5M6.5S`, and `PT0S` for zero |
| `.SurrealString()` | The interval as a SurrealQL literal, such as `ivl'P1D'` |

Like the server, `.Equal()` and `.Compare()` use the total, so one month equals 30 days. `==` compares the parts, as it does for `time.Time`, so a Go map keeps `P1M` and `P30D` apart:

```go
month := models.Interval{Months: 1}
days := models.Interval{Days: 30}
fmt.Println(month, days)
fmt.Println(month.Equal(days), month == days)
```

```text title="Output"
P1M P30D
true false
```

To read an interval from text, use `.UnmarshalText()`, which reads the form that `.String()` writes.

---

## See also

- [Value types](/docs/reference/golang/concepts/value-types.md#surrealdb-40-kinds) for every SurrealDB 4.0 kind
- [CustomDateTime](/docs/reference/golang/api/values/datetime.md) for instants
- [CustomDuration](/docs/reference/golang/api/values/duration.md) for fixed lengths of time
- [Dates and times](/docs/reference/query-language/language-primitives/data-types/dates-and-times.md) for the SurrealQL kinds

---

Source: https://surrealdb.com/docs/reference/golang/api/values/uuid

# UUID

The UUID type represents a UUID v4 or v7 value with CBOR tag 37 encoding for SurrealDB.

The `UUID` struct wraps the UUID type of the `github.com/gofrs/uuid` package. The SDK encodes a `UUID` as CBOR tag 37, the tag that SurrealDB specifies for a UUID. A `UUID` can hold a UUID v4 or v7 value.

**Package:** `github.com/surrealdb/surrealdb.go/v2/pkg/models`

**Source:** [pkg/models/uuid.go](https://github.com/surrealdb/surrealdb.go/blob/main/pkg/models/uuid.go)

---

## Definition

```go
type UUID struct {
    uuid.UUID
}
```

`UUID` embeds `github.com/gofrs/uuid.UUID`, so every method of `uuid.UUID` is available on it.

---

## Related types

### `UUIDString` {#uuidstring}

A string type that holds a UUID as text. The SDK encodes it as CBOR tag 9.

```go
type UUIDString string
```

---

## CBOR encoding

The SDK encodes a `UUID` as CBOR tag 37, which holds the UUID as 16 bytes. It encodes a `UUIDString` as CBOR tag 9, which holds the UUID as text.

---

## Usage

Live query functions return a `UUID`, and a new session or transaction has a `UUID` as its ID. You usually get a `UUID` from the SDK instead of making one yourself.

```go
liveID, err := surrealdb.Live(ctx, db, models.Table("persons"), false)
fmt.Println(liveID.String())
```

---

## See also

- [Live queries](/docs/reference/golang/concepts/live-queries.md) for live query UUIDs
- [Session](/docs/reference/golang/api/core/session.md#id) for session UUIDs
- [Transaction](/docs/reference/golang/api/core/transaction.md#id) for transaction UUIDs
- [Value types](/docs/reference/golang/concepts/value-types.md) for the full type mapping
- [SurrealQL UUID type](/docs/reference/query-language/language-primitives/data-types/uuids.md) for the underlying data model

---

Source: https://surrealdb.com/docs/reference/golang/concepts/authentication

# Authentication

Sign in with the Go SDK as a root, namespace, database or record user, sign up record users, use bearer keys, exchange and revoke refresh tokens, renew token pairs automatically with WithTokenRenewal, and sign out or reset a session.

The Go SDK signs in system users and record users, signs up record users, and manages the tokens that the server returns. The credentials that you pass decide which user the connection signs in as, and so which data it can read and change. This page covers each way to sign in, refresh tokens and their automatic renewal, and how to sign out.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#signin"><code>db.SignIn(ctx, authData)</code></a></td>
			<td scope="row" data-label="Description">Signs in an existing user and returns a JWT</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#signup"><code>db.SignUp(ctx, authData)</code></a></td>
			<td scope="row" data-label="Description">Signs up a new record user and returns a JWT</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#signinwithrefresh"><code>db.SignInWithRefresh(ctx, authData)</code></a></td>
			<td scope="row" data-label="Description">Signs in and returns an access token and a refresh token</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#signupwithrefresh"><code>db.SignUpWithRefresh(ctx, authData)</code></a></td>
			<td scope="row" data-label="Description">Signs up and returns an access token and a refresh token</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#refresh"><code>db.Refresh(ctx, tokens)</code></a></td>
			<td scope="row" data-label="Description">Exchanges a token pair for a new one</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#revoke"><code>db.Revoke(ctx, tokens)</code></a></td>
			<td scope="row" data-label="Description">Revokes the refresh token of a token pair</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#tokens"><code>db.Tokens()</code></a></td>
			<td scope="row" data-label="Description">Returns the token pair the session holds</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#authenticate"><code>db.Authenticate(ctx, token)</code></a></td>
			<td scope="row" data-label="Description">Authenticates the connection with a JWT</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#info"><code>db.Info(ctx)</code></a></td>
			<td scope="row" data-label="Description">Returns the record of the signed-in record user</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#invalidate"><code>db.Invalidate(ctx)</code></a></td>
			<td scope="row" data-label="Description">Signs the session out</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#reset"><code>db.Reset(ctx)</code></a></td>
			<td scope="row" data-label="Description">Signs the session out and clears its namespace, database and variables</td>
		</tr>
	</tbody>
</table>

## Authentication levels

SurrealDB has four levels of user. The fields you set in the authentication data decide which level a sign-in uses:

| Level | Required fields | Access to |
| --- | --- | --- |
| Root | `Username`, `Password` | All namespaces and databases |
| Namespace | `Namespace`, `Username`, `Password` | All databases in the namespace |
| Database | `Namespace`, `Database`, `Username`, `Password` | A single database |
| Record | `Namespace`, `Database`, `Access`, and the fields the access method reads | Records that the access method and table permissions allow |

Pass the credentials as an [`Auth`](/docs/reference/golang/api/types.md#auth) struct or as a `map[string]any`. A map uses the keys `NS`, `DB`, `AC`, `user` and `pass`. It can also hold any other field that an access method reads, such as `email`.

## Signing in as a system user

To sign in as a root, namespace or database user, set the fields for that level:

```go
token, err := db.SignIn(ctx, surrealdb.Auth{
	Username: "root",
	Password: "secret",
})
```

```go
token, err := db.SignIn(ctx, surrealdb.Auth{
	Namespace: "surrealdb",
	Database:  "docs",
	Username:  "db_user",
	Password:  "hunter123",
})
```

`.SignIn()` returns the JWT that the server issued. On a WebSocket connection, the session stays signed in after the token expires, until the session itself expires. Over HTTP, the client sends the token with each request, so requests fail after the token expires.

## Signing in as a record user

A record user signs in through an access method that a [`DEFINE ACCESS ... TYPE RECORD`](/docs/reference/query-language/statements/define/access/record.md) statement defines. The access method decides which fields it reads:

```surql
DEFINE ACCESS account ON DATABASE TYPE RECORD
	SIGNUP (CREATE user SET email = $email, pass = crypto::argon2::generate($pass))
	SIGNIN (SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass))
	DURATION FOR TOKEN 15m, FOR SESSION 12h;
```

Pass the namespace, database and access method, and the fields that the `SIGNIN` clause reads, in a map:

```go
token, err := db.SignIn(ctx, map[string]any{
	"NS":    "surrealdb",
	"DB":    "docs",
	"AC":    "account",
	"email": "tobie@example.com",
	"pass":  "hunter123",
})
```

When the access method reads `$user` and `$pass`, the `Access`, `Username` and `Password` fields of an `Auth` struct also work.

## Signing up record users

`.SignUp()` runs the `SIGNUP` clause of an access method. This clause usually creates the user record. `.SignUp()` then signs the new user in:

```go
token, err := db.SignUp(ctx, map[string]any{
	"NS":    "surrealdb",
	"DB":    "docs",
	"AC":    "account",
	"email": "jaime@example.com",
	"pass":  "hunter123",
})
```

## Using refresh tokens

For an access method defined `WITH REFRESH`, the server returns a refresh token with each access token. Add `WITH REFRESH` to the definition:

```surql
DEFINE ACCESS account ON DATABASE TYPE RECORD
	SIGNUP (CREATE user SET email = $email, pass = crypto::argon2::generate($pass))
	SIGNIN (SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass))
	WITH REFRESH
	DURATION FOR TOKEN 15m, FOR SESSION 12h;
```

Then sign in or sign up with `.SignInWithRefresh()` or `.SignUpWithRefresh()`. Both return [`Tokens`](/docs/reference/golang/api/types.md#tokens), which hold the `Access` token and the `Refresh` token:

```go
tokens, err := db.SignInWithRefresh(ctx, map[string]any{
	"NS":    "surrealdb",
	"DB":    "docs",
	"AC":    "account",
	"email": "tobie@example.com",
	"pass":  "hunter123",
})
```

> [!WARNING]
> On an access method defined `WITH REFRESH`, `.SignIn()` and `.SignUp()` sign the session in, but return the error `cannot decode map into string`. This happens because the server answers with two tokens instead of one. Use the `WithRefresh` methods for these access methods.

`.Refresh()` exchanges a pair for a new pair, without the user's credentials. It then authenticates the session with the new access token:

```go
tokens, err = db.Refresh(ctx, *tokens)
if err != nil {
	log.Fatal(err)
}
```

The server revokes a refresh token after its first use, so keep the pair that `.Refresh()` returns. A second refresh with the same refresh token fails with `There was a problem with authentication`.

`.Revoke()` revokes the refresh token of a pair. After that, a refresh with that pair fails. Use it, for example, when a user signs out, so that a stored copy of the pair cannot be refreshed. `.Revoke()` leaves the session signed in:

```go
if err := db.Revoke(ctx, *tokens); err != nil {
	log.Fatal(err)
}
```

`.SignInWithRefresh()` can also exchange a refresh token for a new pair. Pass the refresh token in the `refresh` key, in place of the credentials:

```go
tokens, err = db.SignInWithRefresh(ctx, map[string]any{
	"NS":      "surrealdb",
	"DB":      "docs",
	"AC":      "account",
	"refresh": tokens.Refresh,
})
```

## Automatic token renewal

With [`WithTokenRenewal(true)`](/docs/reference/golang/api/core/db.md#withtokenrenewal), the client renews a token pair by itself. A session gets a pair from `.SignInWithRefresh()`, `.SignUpWithRefresh()` or `.Refresh()`. After that, the client exchanges the pair for a new pair shortly before the access token expires. The client then does the same for each new pair:

```go
db, err := surrealdb.FromEndpointURLStringWithOptions(ctx, "ws://localhost:8000",
	surrealdb.WithTokenRenewal(true),
)
if err != nil {
	log.Fatal(err)
}

_, err = db.SignInWithRefresh(ctx, map[string]any{
	"NS":    "surrealdb",
	"DB":    "docs",
	"AC":    "account",
	"email": "tobie@example.com",
	"pass":  "hunter123",
})
```

By default, the client renews an access token one minute before it expires. [`WithTokenExpiryMargin`](/docs/reference/golang/api/core/db.md#withtokenexpirymargin) changes the margin. If an access token lives for less than twice the margin, the client renews it halfway through its life.

Each renewal uses up the refresh token of the pair it replaces. A program can store a pair to sign in again on its next run. Such a program must store the pair that `.Tokens()` returns, because that pair changes at each renewal:

```go
if pair := db.Tokens(); pair != nil {
	saveTokens(pair.Access, pair.Refresh)
}
```

`.Tokens()` returns `nil` when renewal is off or the session holds no pair. Renewal is off by default.

## Using bearer access

A [`TYPE BEARER`](/docs/reference/query-language/statements/define/access/bearer.md) access method signs in with a key that an `ACCESS ... GRANT` statement issued. Pass the key in the `key` field, with no username or password:

```go
token, err := db.SignIn(ctx, map[string]any{
	"NS":  "surrealdb",
	"DB":  "docs",
	"AC":  "api",
	"key": bearerKey,
})
```

A bearer key has the form `surreal-bearer-...`. The `key` field is for bearer access methods only. A refresh token goes in the `refresh` field.

## Authenticating with an existing token

`.Authenticate()` signs the connection in with a JWT that you already have. The JWT can be a token from an earlier sign-in. It can also be a token that your own identity provider issued for a [`TYPE JWT`](/docs/reference/query-language/statements/define/access/jwt.md) access method:

```go
if err := db.Authenticate(ctx, token); err != nil {
	log.Fatal(err)
}
```

On a WebSocket connection, a session that authenticated with a token ends when the token expires.

## Reading the signed-in user

`.Info()` returns the record of the signed-in record user, as `SELECT * FROM $auth` would:

```go
info, err := db.Info(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(info["email"])
```

The table permissions apply. If the permissions do not let the user select its own record, the map is empty.

## Signing out and resetting a session

`.Invalidate()` signs the session out. The namespace, database and variables stay as they are:

```go
if err := db.Invalidate(ctx); err != nil {
	log.Fatal(err)
}
```

`.Reset()` returns the session to the state that it had when the connection opened. The session is then signed out and has no namespace, database or variables. `.Reset()` also kills the live queries of the session. Over HTTP, the client keeps this state itself, so `.Reset()` clears it without calling the server:

```go
if err := db.Reset(ctx); err != nil {
	log.Fatal(err)
}
```

## Authentication over HTTP and WebSocket

Over WebSocket, the server keeps the authentication in the session. A connection to another server must sign in again. When the client [reconnects](/docs/reference/golang/concepts/reliable-connections.md), it authenticates the new connection with the last token it received. If token renewal is on and the access token has expired, the client first exchanges the pair for a new pair. Without renewal, a session that signed in with a username and password can last longer than its token. The reconnect then cannot restore the sign-in. The [status event](/docs/reference/golang/concepts/reliable-connections.md#watching-the-connection-status) reports the error, and the session needs to sign in again.

Over HTTP, the client keeps the token and sends it in the `Authorization` header of each request. [`DB.Import` and `DB.Export`](/docs/reference/golang/concepts/import-and-export.md) use the token on WebSocket connections too. After the token expires, they fail with `401 Unauthorized`, even while queries still work. Sign in again to get a new token.

## Learn more

- [DB API reference](/docs/reference/golang/api/core/db.md) for complete method signatures and parameters
- [Types reference](/docs/reference/golang/api/types.md) for the `Auth` and `Tokens` types
- [Connecting to SurrealDB](/docs/reference/golang/concepts/connecting-to-surrealdb.md#effect-of-connection-protocol-on-token-and-session-duration) for how the protocol changes token and session duration
- [DEFINE ACCESS statement](/docs/reference/query-language/statements/define/access.md) for configuring access methods
- [Security best practices](/docs/learn/security/best-practices/security-best-practices.md) for token and session duration configuration

---

Source: https://surrealdb.com/docs/reference/golang/concepts/connecting-to-surrealdb

# Connecting to SurrealDB

Connect the Go SDK to SurrealDB over WebSocket or HTTP with FromEndpointURLString, pass options for the version check, reconnection and token renewal, check server health, read the CBOR version, and build a custom gorillaws, gws or HTTP connection.

The Go SDK connects to SurrealDB over WebSocket or HTTP. [`FromEndpointURLString`](/docs/reference/golang/api/core/db.md#fromendpointurlstring) reads the scheme of a URL, creates the matching connection, and connects it. This page covers opening and closing a connection, the options that change how a client behaves, the health and version checks, and custom connections.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Function</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#fromendpointurlstring"><code>surrealdb.FromEndpointURLString(ctx, url)</code></a></td>
			<td scope="row" data-label="Description">Creates a client from a URL and connects it</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#fromendpointurlstringwithoptions"><code>surrealdb.FromEndpointURLStringWithOptions(ctx, url, opts...)</code></a></td>
			<td scope="row" data-label="Description">Creates a client from a URL, configured by options</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#fromconnection"><code>surrealdb.FromConnection(ctx, conn)</code></a></td>
			<td scope="row" data-label="Description">Creates a client from a connection you build yourself</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#use"><code>db.Use(ctx, ns, db)</code></a></td>
			<td scope="row" data-label="Description">Selects a namespace and database</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#health"><code>db.Health(ctx)</code></a></td>
			<td scope="row" data-label="Description">Checks that the server is up</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#version"><code>db.Version(ctx)</code></a></td>
			<td scope="row" data-label="Description">Returns the version of the server</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#cborversion"><code>db.CBORVersion()</code></a></td>
			<td scope="row" data-label="Description">Returns the CBOR version the connection uses</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#close"><code>db.Close(ctx)</code></a></td>
			<td scope="row" data-label="Description">Closes the connection and releases its resources</td>
		</tr>
	</tbody>
</table>

## Opening a connection

Call `FromEndpointURLString` with a `context.Context` and the address of the server. It returns a [`*DB`](/docs/reference/golang/api/core/db.md) that is already connected:

```go
ctx := context.Background()

db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000")
if err != nil {
	log.Fatal(err)
}
defer db.Close(ctx)
```

The context limits the connection attempt. Use `context.WithTimeout` to set how long the attempt can block on an unreliable network:

```go
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

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

## Connection URLs

The scheme of the URL chooses the connection type:

| Scheme | Connection type | Description |
| --- | --- | --- |
| `ws://` | WebSocket | Unencrypted stateful connection |
| `wss://` | WebSocket | TLS-encrypted stateful connection |
| `http://` | HTTP | Unencrypted stateless connection |
| `https://` | HTTP | TLS-encrypted stateless connection |

A WebSocket connection is long-lived and stateful. It supports every feature of the SDK, including [live queries](/docs/reference/golang/concepts/live-queries.md), [sessions](/docs/reference/golang/concepts/multiple-sessions.md), [interactive transactions](/docs/reference/golang/concepts/transactions.md), [streaming results](/docs/reference/golang/concepts/streaming.md) and [automatic reconnection](/docs/reference/golang/concepts/reliable-connections.md).

An HTTP connection is stateless. The client keeps the namespace, database, variables and token itself, and sends them with each request. Live queries, sessions and interactive transactions are not available over HTTP. Over HTTP, `QueryStream` returns the whole result at once.

A connection to a `mem://`, `memory` or `surrealkv://` URL fails with the error `embedded database not enabled`. To run SurrealDB inside a Go program, use the separate [surrealdb.c.go module](/docs/reference/golang/embedding.md).

## Selecting a namespace and database

After connecting, call `.Use()` to select the namespace and database that later requests work in:

```go
if err := db.Use(ctx, "surrealdb", "docs"); err != nil {
	log.Fatal(err)
}
```

You can call `.Use()` again at any time to switch to another namespace or database on the same connection.

## Connection options

`FromEndpointURLStringWithOptions` and `FromConnectionWithOptions` take options that change how the client behaves. With no options, they do what `FromEndpointURLString` and `FromConnection` do.

| Option | Default | What it does |
| --- | --- | --- |
| [`WithVersionCheck(enabled)`](/docs/reference/golang/api/core/db.md#withversioncheck) | Off | Makes connecting fail on a server outside the supported versions. |
| [`WithReconnect(enabled)`](/docs/reference/golang/api/core/db.md#withreconnect) | On, for WebSocket | Reconnects when the connection is lost, and restores the session. |
| [`WithReconnectAttempts(attempts)`](/docs/reference/golang/api/core/db.md#withreconnectattempts) | `5` | Sets how many consecutive attempts the client makes to reconnect. |
| [`WithReconnectDelay(min, max)`](/docs/reference/golang/api/core/db.md#withreconnectdelay) | `1s`, `1m` | Sets the wait before each attempt to reconnect. |
| [`WithTokenRenewal(enabled)`](/docs/reference/golang/api/core/db.md#withtokenrenewal) | Off | Renews a token pair before the access token expires. |
| [`WithTokenExpiryMargin(margin)`](/docs/reference/golang/api/core/db.md#withtokenexpirymargin) | `1m` | Sets how long before expiry the client renews a token. |

```go
db, err := surrealdb.FromEndpointURLStringWithOptions(ctx, "wss://example.surrealdb.cloud",
	surrealdb.WithVersionCheck(true),
	surrealdb.WithReconnectAttempts(10),
	surrealdb.WithTokenRenewal(true),
)
```

[Reliable connections](/docs/reference/golang/concepts/reliable-connections.md) explains reconnection, and [Authentication](/docs/reference/golang/concepts/authentication.md#automatic-token-renewal) explains token renewal.

### Server version check

The SDK supports SurrealDB 3.3.0 and later versions before 5.0.0. With `WithVersionCheck(true)`, the client asks the server for its version when it connects. If the version is outside that range, connecting fails with an [`UnsupportedVersionError`](/docs/reference/golang/api/errors.md#unsupportedversionerror):

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

var uv *surrealdb.UnsupportedVersionError
if errors.As(err, &uv) {
	log.Fatalf("SurrealDB %s is not supported", uv.Version)
}
```

The check is off by default, because it adds a request to every connection. This extra request matters to code that opens a new connection for each request. The check also fails on a server that does not answer the version request, such as one started with `--deny-rpc version`.

To check a version without connecting, use [`IsVersionSupported`](/docs/reference/golang/api/core/db.md#isversionsupported). Use [`IsVersionInRange`](/docs/reference/golang/api/core/db.md#isversioninrange) to check for a feature that a later release added:

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

if surrealdb.IsVersionInRange(ver.Version, "4.1.0", surrealdb.MaximumServerVersion) {
	// use a feature that SurrealDB 4.1 added
}
```

### Request timeouts

Each request waits for its answer until its context ends or the connection's timeout passes. The timeout is 30 seconds for a WebSocket connection and 10 seconds for an HTTP connection. A request that times out returns an error that wraps `context.DeadlineExceeded`. You can check for this error with `errors.Is`.

Pass a context with a deadline to limit a single request:

```go
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

results, err := surrealdb.Query[[]Person](ctx, db, "SELECT * FROM person", nil)
```

To change the timeout of every request, build the connection yourself, as shown in [Using a custom connection](#using-a-custom-connection). Then call `SetTimeOut` on a `gorillaws` connection, or `SetTimeout` on an `http` connection. A WebSocket timeout of `0` turns the timeout off. The context is then the only limit on a request.

## Checking server health

`.Health()` sends `GET /health` to the server over HTTP, whichever transport the client uses. The request needs no authentication. `.Health()` returns `nil` when the server answers with a `2xx` status:

```go
if err := db.Health(ctx); err != nil {
	var he *surrealdb.HealthError
	if errors.As(err, &he) {
		log.Printf("unhealthy: %d %s", he.StatusCode, he.Body)
	}
}
```

The server answers with another status when it cannot reach its datastore. The [`HealthError`](/docs/reference/golang/api/errors.md#healtherror) then holds the status and the start of the body. On a network failure, `.Health()` returns the error of the HTTP request.

## Server version and CBOR version

`.Version()` returns the version, build and timestamp that the server reports:

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

```text title="Possible output"
4.0.0
```

The SDK sends requests as CBOR. SurrealDB 4.0 adds cbor.2, a version of the CBOR protocol. Over cbor.2, the sized numbers and the date, time, timestamp, interval, bigdecimal and regex kinds of SurrealDB 4.0 keep their types. The SDK offers cbor.2 when it connects. If the server does not accept cbor.2, the SDK uses plain CBOR. Servers before 4.0 do not accept cbor.2. `.CBORVersion()` returns the version the connection uses:

```go
fmt.Println(db.CBORVersion())
```

```text title="Output with SurrealDB 4.0"
cbor.2
```

A WebSocket connection chooses the version in its handshake. An HTTP connection sends plain CBOR until the server first answers in cbor.2. As a result, a new HTTP client reports `cbor` until the server answers its first request, such as `.SignIn()`. With `WithVersionCheck(true)`, the version request is the first request, so with SurrealDB 4.0 the client uses cbor.2 from the start. [Value types](/docs/reference/golang/concepts/value-types.md#cbor2-and-plain-cbor) lists what changes between the two.

## Connection status

A WebSocket client that reconnects reports the state of its connection. `.Status()` returns the state, and `.OnStatus()` calls a function at each change:

```go
stop := db.OnStatus(func(ev surrealdb.StatusEvent) {
	log.Printf("connection %s (attempt %d): %v", ev.Status, ev.Attempt, ev.Err)
})
defer stop()
```

See [Reliable connections](/docs/reference/golang/concepts/reliable-connections.md#watching-the-connection-status) for the states and events.

## Using a custom connection

To configure the connection itself, create it yourself. Then pass it to [`FromConnection`](/docs/reference/golang/api/core/db.md#fromconnection) or [`FromConnectionWithOptions`](/docs/reference/golang/api/core/db.md#fromconnectionwithoptions). The module has three connection packages:

| Package | Connection |
| --- | --- |
| `pkg/connection/gorillaws` | WebSocket, with [gorilla/websocket](https://github.com/gorilla/websocket). `FromEndpointURLString` uses it for `ws://` and `wss://`. |
| `pkg/connection/gws` | WebSocket, with [lxzan/gws](https://github.com/lxzan/gws). |
| `pkg/connection/http` | HTTP. `FromEndpointURLString` uses it for `http://` and `https://`. |

```go
import (
	"net/url"
	"time"

	surrealdb "github.com/surrealdb/surrealdb.go/v2"
	"github.com/surrealdb/surrealdb.go/v2/pkg/connection"
	"github.com/surrealdb/surrealdb.go/v2/pkg/connection/gorillaws"
)

u, err := url.ParseRequestURI("ws://localhost:8000")
if err != nil {
	log.Fatal(err)
}

conf := connection.NewConfig(u)
conn := gorillaws.New(conf).SetTimeOut(time.Minute)

db, err := surrealdb.FromConnectionWithOptions(ctx, conn,
	surrealdb.WithVersionCheck(true),
)
```

`FromConnection` calls `.Connect(ctx)` on the connection for you. A `gorillaws` or `gws` connection reconnects in the same way as a connection from `FromEndpointURLString`. For a connection with its own retry strategies, see [the rews package](/docs/reference/golang/concepts/reliable-connections.md#using-the-rews-package).

`connection.NewConfig` sets the CBOR codec to `surrealcbor`. Set the fields of the configuration before you create the connection:

| Field | What it sets |
| --- | --- |
| `Marshaler`, `Unmarshaler` | The CBOR codec. The deprecated `models.CborMarshaler` and `models.CborUnmarshaler` support plain CBOR only. |
| `Logger` | The logger for the connection. `nil` turns logging off. |
| `DisableCBORv2` | Offers plain CBOR only, even to a SurrealDB 4.0 server. |

## Effect of connection protocol on token and session duration

WebSocket connections (`ws://`, `wss://`) are long-lived and stateful. After authentication, the session persists for the lifetime of the connection. The session duration defaults to `NONE`, meaning it never expires unless configured otherwise.

HTTP connections (`http://`, `https://`) are short-lived and stateless. The SDK sends the access token from the sign-in with each request, so requests fail when the token expires. The token duration defaults to 1 hour.

The figure below shows which duration ends the session in each case, with the default durations.

<img src="~/assets/img/diagrams/light/conn-token-session-light.webp" darkSrc="~/assets/img/diagrams/conn-token-session.webp" alt="A timeline over two hours shows which duration ends a session when the token duration is the default of one hour. A WebSocket connection that signed in with credentials keeps one session, and with the default session duration of NONE it keeps working after the token that signin returned has expired. A WebSocket connection that authenticated with a token has its session end when the token expires, and later queries fail with 'The session has expired'. Over HTTP, requests that send the token in an Authorization Bearer header succeed until the token expires and then fail with 401, while requests that send Basic credentials sign in again each time and keep succeeding. Over HTTP, the JavaScript, Python and Go SDKs send the token; the Rust, Java and .NET SDKs send a system user's username and password with every request, and a token for record users." />

You can configure token and session durations using the `DURATION` clause in [`DEFINE ACCESS METHOD`](/docs/reference/query-language/statements/define/access.md) or [`DEFINE USER`](/docs/reference/query-language/statements/define/user.md) statements.

> [!NOTE]
> Learn more about token and session duration in the [security best practices](/docs/learn/security/best-practices/security-best-practices.md#expiration) documentation.

## Closing a connection

Call `.Close()` to close the connection and release its resources:

```go
db.Close(ctx)
```

Call `defer db.Close(ctx)` directly after you create the connection. The connection then closes even when a later step fails. After `.Close()`, requests return `surrealdb.ErrClientClosed`.

## Learn more

- [DB API reference](/docs/reference/golang/api/core/db.md) for complete method signatures and parameters
- [Authentication](/docs/reference/golang/concepts/authentication.md) for signing in and managing tokens
- [Reliable connections](/docs/reference/golang/concepts/reliable-connections.md) for reconnection and the connection status
- [Error handling](/docs/reference/golang/concepts/error-handling.md) for connection and authentication errors

---

Source: https://surrealdb.com/docs/reference/golang/concepts/data-manipulation

# Data manipulation

Create, select, insert, update, upsert, merge, patch, relate and delete records with the Go SDK's generic CRUD functions, target a table, a record or a range of records, choose what a patch returns with PatchWithResult and ReturnMode, and pick the result type for each target.

The Go SDK has a generic function for each common operation on records: [`Select`](/docs/reference/golang/api/core/db.md#select), [`Create`](/docs/reference/golang/api/core/db.md#create), [`Insert`](/docs/reference/golang/api/core/db.md#insert), [`Update`](/docs/reference/golang/api/core/db.md#update), [`Upsert`](/docs/reference/golang/api/core/db.md#upsert), [`Merge`](/docs/reference/golang/api/core/db.md#merge), [`Patch`](/docs/reference/golang/api/core/db.md#patch), [`Delete`](/docs/reference/golang/api/core/db.md#delete), [`Relate`](/docs/reference/golang/api/core/db.md#relate) and [`InsertRelation`](/docs/reference/golang/api/core/db.md#insertrelation). Each one sends a SurrealQL statement and decodes the result into the Go type that you pass as its type parameter. All of them work with a [`*DB`](/docs/reference/golang/api/core/db.md), a [`*Session`](/docs/reference/golang/api/core/session.md) or a [`*Transaction`](/docs/reference/golang/api/core/transaction.md). This page covers how to target records and how to use each function.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Function</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#select"><code>surrealdb.Select[T](ctx, s, what)</code></a></td>
			<td scope="row" data-label="Description">Selects a record, the records of a table, or a range of records</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#create"><code>surrealdb.Create[T](ctx, s, what, data)</code></a></td>
			<td scope="row" data-label="Description">Creates a record</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#insert"><code>surrealdb.Insert[T](ctx, s, table, data)</code></a></td>
			<td scope="row" data-label="Description">Inserts one or more records into a table</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#update"><code>surrealdb.Update[T](ctx, s, what, data)</code></a></td>
			<td scope="row" data-label="Description">Replaces the content of existing records</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#upsert"><code>surrealdb.Upsert[T](ctx, s, what, data)</code></a></td>
			<td scope="row" data-label="Description">Creates records, or replaces their content when they exist</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#merge"><code>surrealdb.Merge[T](ctx, s, what, data)</code></a></td>
			<td scope="row" data-label="Description">Merges data into existing records</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#patch"><code>surrealdb.Patch(ctx, s, what, patches)</code></a></td>
			<td scope="row" data-label="Description">Applies JSON Patch operations and returns the changes</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#patchwithresult"><code>surrealdb.PatchWithResult[T](ctx, s, what, patches, output)</code></a></td>
			<td scope="row" data-label="Description">Applies JSON Patch operations and returns what you choose</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#delete"><code>surrealdb.Delete[T](ctx, s, what)</code></a></td>
			<td scope="row" data-label="Description">Deletes records and returns them as they were</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#relate"><code>surrealdb.Relate[T](ctx, s, rel)</code></a></td>
			<td scope="row" data-label="Description">Creates a relation with a generated ID</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#insertrelation"><code>surrealdb.InsertRelation[T](ctx, s, rel)</code></a></td>
			<td scope="row" data-label="Description">Inserts a relation, with an ID you can choose</td>
		</tr>
	</tbody>
</table>

## Targeting records and tables

The functions that take a `what` argument accept a [`models.RecordID`](/docs/reference/golang/api/values/record-id.md), a [`models.Table`](/docs/reference/golang/api/values/table.md), a `string`, or a slice of record IDs or tables. The value that you pass decides what the statement works on and the shape of its result:

| `what` | Works on | Result |
| --- | --- | --- |
| `models.NewRecordID("person", "tobie")` | One record | The record, or `nil` when it does not exist |
| `models.Table("person")` | Every record in the table | A slice of records |
| `"person"` | Every record in the table, or one new record for `Create` | A slice of records, or the created record for `Create` |
| A `models.RecordID` whose ID is a [`models.Range`](/docs/reference/golang/api/values/range.md) | The records in the range | A slice of records |
| `[]models.RecordID`, `[]models.Table` | Each record or table in the slice | A slice of records |

A string is always a table name. The SDK never reads a string as a record ID. `"person:tobie"` names a table called `person:tobie`, so `Select` returns the error `The table 'person:tobie' does not exist`. Use `models.NewRecordID` for a record. When the ID arrives as text, [`models.ParseRecordID`](/docs/reference/golang/api/values/record-id.md#parserecordid) parses it. But `ParseRecordID` always makes a string ID, so the ID does not match a record whose ID is a number.

Match the type parameter to the result. For a single record, pass the record type, such as `Person`. For a table, a range or a slice, pass a slice, such as `[]Person`. If the types do not match, the SDK cannot decode the result and returns an error such as `cannot decode array into main.Person`. The examples on this page use this type:

```go
type Person struct {
	ID      *models.RecordID `json:"id,omitempty"`
	Name    string           `json:"name"`
	Surname string           `json:"surname,omitempty"`
	Age     int              `json:"age,omitempty"`
}
```

Use `*models.RecordID` with `omitempty` for the `id` field. You can then send the struct without an ID, and read it back with one.

## Selecting records

`Select` reads one record, the records of a table, or the records in a range:

```go
people, err := surrealdb.Select[[]Person](ctx, db, models.Table("person"))
if err != nil {
	log.Fatal(err)
}

tobie, err := surrealdb.Select[Person](ctx, db, models.NewRecordID("person", "tobie"))
if err != nil {
	log.Fatal(err)
}
if tobie == nil {
	fmt.Println("no such person")
}
```

When the record does not exist, `Select` returns `nil` and no error.

## Selecting a range of records

To select the records whose IDs fall in a range, pass a `models.RecordID` whose ID is a [`models.Range`](/docs/reference/golang/api/values/range.md). The example below selects `reading:2` and `reading:3`, from `2` included to `4` excluded:

```go
rng := models.RecordID{
	Table: "reading",
	ID: models.Range[int, models.BoundIncluded[int], models.BoundExcluded[int]]{
		Begin: &models.BoundIncluded[int]{Value: 2},
		End:   &models.BoundExcluded[int]{Value: 4},
	},
}

readings, err := surrealdb.Select[[]map[string]any](ctx, db, rng)
```

A `nil` `Begin` or `End` leaves that side of the range open. The [query builder](/docs/reference/golang/concepts/query-builder.md) has helpers that build the range for you, such as `surrealql.RangeBeginInclusiveEndExclusive(2, 4)`. For an array ID such as `temp:['London', 'West', 1]`, use `models.None` as the lowest value of a part, as in `[]any{"London", models.None, models.None}`.

## Creating records

`Create` creates a record from a struct or a map. To choose the ID, pass a `models.RecordID`. To let SurrealDB generate the ID, pass the table name as a string. Both forms return the created record:

```go
tobie, err := surrealdb.Create[Person](ctx, db, models.NewRecordID("person", "tobie"), Person{
	Name:    "Tobie",
	Surname: "Morgan Hitchcock",
	Age:     35,
})

jaime, err := surrealdb.Create[Person](ctx, db, "person", Person{Name: "Jaime"})
fmt.Println(jaime.ID)
```

```text title="Example output"
person:1wxlej6yf7cvn3t27m0f
```

With a `models.Table`, `Create` returns a slice, so pass `[]Person` as the type parameter. If you pass `nil` data, `Create` creates a record with no fields other than its ID.

To ignore the result, pass `struct{}` as the type parameter:

```go
_, err := surrealdb.Create[struct{}](ctx, db, "person", Person{Name: "Ana"})
```

## Inserting records

`Insert` inserts one record or a slice of records into a table, and always returns a slice:

```go
inserted, err := surrealdb.Insert[Person](ctx, db, models.Table("person"), []Person{
	{Name: "Alice", Age: 30},
	{Name: "Bob", Age: 25},
})
fmt.Println(len(*inserted))
```

```text title="Output"
2
```

The type parameter of `Insert` is the type of one record. The function returns `*[]T`. A record in the data can have its own `id`. `Insert` cannot create a relation: use [`InsertRelation`](#inserting-relations) for that.

## Replacing records

`Update` replaces the whole content of existing records with the data you pass. It removes the fields that the data leaves out:

```go
updated, err := surrealdb.Update[Person](ctx, db, models.NewRecordID("person", "tobie"), Person{
	Name: "Tobie",
})
```

> [!NOTE]
> `Update` performs a full replacement, so it removes the `surname` and `age` of `person:tobie`. Use [`Merge`](#merging-data-into-records) to change some fields and keep the others.

`Update` changes only records that exist, and creates nothing. On a table, it updates every record. Use `Upsert` to create the record when it is missing.

## Upserting records

`Upsert` creates a record when it does not exist, and replaces its content when it does:

```go
ana, err := surrealdb.Upsert[Person](ctx, db, models.NewRecordID("person", "ana"), Person{
	Name: "Ana",
	Age:  16,
})
```

## Merging data into records

`Merge` merges the data you pass into existing records, and keeps the fields that the data does not mention:

```go
merged, err := surrealdb.Merge[Person](ctx, db, models.NewRecordID("person", "tobie"), map[string]any{
	"age": 36,
})
```

A merge into a table changes every record in the table, and returns a slice:

```go
everyone, err := surrealdb.Merge[[]Person](ctx, db, models.Table("person"), map[string]any{
	"active": true,
})
```

## Applying JSON Patch operations

`Patch` applies [JSON Patch](https://jsonpatch.com/) operations to a record, and returns the operations that changed it. Each operation is a [`PatchData`](/docs/reference/golang/api/types.md#patchdata) with an `Op`, a `Path` and a `Value`:

```go
changes, err := surrealdb.Patch(ctx, db, models.NewRecordID("person", "tobie"), []surrealdb.PatchData{
	{Op: "replace", Path: "/age", Value: 37},
	{Op: "add", Path: "/verified", Value: true},
})
```

The operations are `add`, `remove`, `replace`, `move`, `copy` and `test`. `Patch` returns `*[]PatchData`, which fits the result for one record. For a table, the result holds the changes of each record, so use `PatchWithResult`.

## Choosing what a patch returns

`PatchWithResult` applies JSON Patch operations in the same way as `Patch`. It returns what its last argument asks for:

| `ReturnMode` | Returns |
| --- | --- |
| `surrealdb.ReturnAfter` | The records after the change |
| `surrealdb.ReturnBefore` | The records before the change |
| `surrealdb.ReturnDiff` | The JSON Patch operations that changed each record |
| `surrealdb.ReturnNone` | Nothing: the result is `nil` |

```go
patched, err := surrealdb.PatchWithResult[Person](ctx, db,
	models.NewRecordID("person", "tobie"),
	[]surrealdb.PatchData{{Op: "replace", Path: "/age", Value: 38}},
	surrealdb.ReturnAfter,
)
fmt.Println(patched.Age)
```

```text title="Output"
38
```

For a table, use a slice as the type parameter, such as `[]Person` for `ReturnAfter`, or `[][]surrealdb.PatchData` for `ReturnDiff`:

```go
diffs, err := surrealdb.PatchWithResult[[][]surrealdb.PatchData](ctx, db,
	models.Table("person"),
	[]surrealdb.PatchData{{Op: "replace", Path: "/active", Value: false}},
	surrealdb.ReturnDiff,
)
```

## Deleting records

`Delete` deletes a record, the records of a table, or a range of records. It returns the records as they were before the delete:

```go
deleted, err := surrealdb.Delete[Person](ctx, db, models.NewRecordID("person", "ana"))

everyone, err := surrealdb.Delete[[]Person](ctx, db, models.Table("person"))
```

## Relating records

`Relate` creates an edge in a relation table, from one record to another, with a generated ID. Describe the edge with a [`Relationship`](/docs/reference/golang/api/types.md#relationship):

```go
edge, err := surrealdb.Relate[map[string]any](ctx, db, &surrealdb.Relationship{
	In:       models.NewRecordID("person", "tobie"),
	Out:      models.NewRecordID("person", "jaime"),
	Relation: models.Table("knows"),
	Data:     map[string]any{"since": 2020},
})
```

`Relate` ignores the `ID` field of the `Relationship`. This field exists so that the SDK can decode an edge into the struct.

## Inserting relations

`InsertRelation` inserts an edge, as `INSERT RELATION` does. If the `Relationship` has an `ID`, `InsertRelation` uses that ID. Otherwise, it generates an ID. It returns a slice:

```go
id := models.NewRecordID("knows", "tobie_jaime")

edges, err := surrealdb.InsertRelation[[]map[string]any](ctx, db, &surrealdb.Relationship{
	ID:       &id,
	In:       models.NewRecordID("person", "tobie"),
	Out:      models.NewRecordID("person", "jaime"),
	Relation: models.Table("knows"),
})
```

When you only need the ID of the edge, decode into `[]connection.ResponseID[models.RecordID]`.

## Learn more

- [DB API reference](/docs/reference/golang/api/core/db.md) for complete function signatures and parameters
- [Executing queries](/docs/reference/golang/concepts/executing-queries.md) for running SurrealQL statements directly
- [Value types](/docs/reference/golang/concepts/value-types.md) for the Go types that each SurrealDB kind uses
- [RecordID reference](/docs/reference/golang/api/values/record-id.md) for building record IDs
- [SurrealQL statements](/docs/reference/query-language/statements/overview.md) for the statements these functions send

---

Source: https://surrealdb.com/docs/reference/golang/concepts/error-handling

# Error handling

Handle errors from the Go SDK with errors.As and errors.Is - ServerError and its kinds, the IsNotFound and other Is helpers, QueryError for failed statements, UnsupportedVersionError, HealthError, ImportError, sentinel errors such as ErrSessionClosed and ErrClientClosed, and which errors are safe to retry.

The Go SDK returns ordinary Go errors, which you inspect with `errors.As` and `errors.Is`. A failure belongs to one of three groups:

- An error that the server reports for a request
- The error of one statement in a query
- A failure in the client or the network

This page shows how to tell the groups apart and how to match on the kind of a server error. It also shows which errors are safe to retry.

The [Errors](/docs/reference/protocols/errors.md) page documents the error kinds, wire codes and structured shape behind these errors once, for every SDK and protocol.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Error</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Error"><a href="/docs/reference/golang/api/errors.md#servererror"><code>ServerError</code></a></td>
			<td scope="row" data-label="Description">An error from the server, with a kind, details and a cause chain</td>
		</tr>
		<tr>
			<td scope="row" data-label="Error"><a href="/docs/reference/golang/api/errors.md#queryerror"><code>QueryError</code></a></td>
			<td scope="row" data-label="Description">The error of one failed statement in a query</td>
		</tr>
		<tr>
			<td scope="row" data-label="Error"><a href="/docs/reference/golang/api/errors.md#kind-helpers"><code>IsNotFound</code>, <code>IsNotAllowed</code> and others</a></td>
			<td scope="row" data-label="Description">Report whether an error is a server error of a given kind</td>
		</tr>
		<tr>
			<td scope="row" data-label="Error"><a href="/docs/reference/golang/api/errors.md#unsupportedversionerror"><code>UnsupportedVersionError</code></a></td>
			<td scope="row" data-label="Description">The server version is outside the range the SDK supports</td>
		</tr>
		<tr>
			<td scope="row" data-label="Error"><a href="/docs/reference/golang/api/errors.md#healtherror"><code>HealthError</code></a></td>
			<td scope="row" data-label="Description">The server answered the health check with an unsuccessful status</td>
		</tr>
		<tr>
			<td scope="row" data-label="Error"><a href="/docs/reference/golang/api/errors.md#importerror"><code>ImportError</code></a></td>
			<td scope="row" data-label="Description">Statements of an imported document failed</td>
		</tr>
		<tr>
			<td scope="row" data-label="Error"><a href="/docs/reference/golang/api/errors.md#sentinel-errors">Sentinel errors</a></td>
			<td scope="row" data-label="Description">Fixed errors, such as <code>ErrSessionClosed</code> and <code>ErrClientClosed</code></td>
		</tr>
	</tbody>
</table>

## Where an error surfaces

The SDK reports each kind of failure in its own way:

| Failure | How it surfaces |
| --- | --- |
| The server refuses a request, such as a sign-in, a CRUD function, or a whole query that does not parse | The returned error is an `*RPCError` that unwraps to a `*ServerError` |
| One statement of a query fails | The statement's `QueryResult.Error` is a `*QueryError`, and the returned error joins them |
| The connection is lost, or a request times out | The returned error wraps `connection.ErrConnectionClosed` or `context.DeadlineExceeded` |
| The result does not fit the type parameter | The returned error starts with `Send: error unmarshaling result` |
| A call is not possible on this client, such as a session over HTTP | A [sentinel error](#checking-sentinel-errors), such as `constants.ErrSessionsNotSupported` |

## Handling server errors

Use `errors.As` to read the [`ServerError`](/docs/reference/golang/api/errors.md#servererror) of a failed request. It holds the `Kind` of the error, a `Message`, kind-specific `Details`, and an optional `Cause`:

```go
_, err := surrealdb.Create[Person](ctx, db, models.NewRecordID("person", "tobie"), person)
if err != nil {
	var se *surrealdb.ServerError
	if errors.As(err, &se) {
		fmt.Println(se.Kind, se.Details)
	}
}
```

```text title="Output when person:tobie exists"
AlreadyExists map[details:map[id:person:tobie] kind:Record]
```

`Cause` is the next error in the chain, and is itself a `*ServerError`. `.Error()` joins the messages of the chain with `": "`. To go through the chain one error at a time, use `errors.Unwrap`.

## Matching on the kind

Compare `Kind` with the `Kind` constants, such as `surrealdb.KindAlreadyExists`. You can also use one of the `Is` helpers, which find the `*ServerError` for you:

```go
_, err := surrealdb.Select[[]Person](ctx, db, models.Table("person"))
switch {
case surrealdb.IsNotFound(err):
	fmt.Println("the table does not exist yet")
case surrealdb.IsNotAllowed(err):
	fmt.Println("not allowed to read the table")
case err != nil:
	log.Fatal(err)
}
```

| Helper | Matches |
| --- | --- |
| `IsNotFound` | A table, record, namespace, database, session or transaction that does not exist |
| `IsNotAllowed` | Any `NotAllowed` error, such as a permission or an authentication failure |
| `IsInvalidAuth` | Credentials that the server refused |
| `IsTokenExpired` | An access token that has expired |
| `IsScriptingBlocked` | A script that the server's capabilities do not allow |
| `IsParseError` | A query that does not parse |
| `IsTimedOut` | A query that passed its `TIMEOUT` |
| `IsCancelled` | A query that was cancelled |
| `IsNotExecuted` | A statement that never ran, usually because an earlier statement in its transaction failed |
| `IsTransactionConflict` | A transaction that conflicted with another one, which is safe to retry |
| `IsDeserialization` | A value that the server could not decode |
| `IsLiveQueryNotSupported` | A live query on a connection or server that cannot run one |

Match on the kind rather than the message. The text of a message can change between SurrealDB versions. Also, from version 2 of the SDK, the CRUD functions run as queries, which changed some of their messages.

## Handling statement errors

`Query` returns a result for each statement, and a statement can fail while the others succeed. The `QueryResult.Error` of the failed statement is then a [`*QueryError`](/docs/reference/golang/api/errors.md#queryerror):

```go
results, err := surrealdb.Query[any](ctx, db,
	"CREATE person:tobie; CREATE person:tobie;",
	nil,
)

for i, qr := range *results {
	if qr.Error != nil {
		fmt.Printf("statement %d failed: %s\n", i, qr.Error.Message)
	}
}
```

```text title="Output"
statement 1 failed: Database record `person:tobie` already exists
```

The returned `err` joins the `*QueryError` of every failed statement. `errors.Is(err, &surrealdb.QueryError{})` reports whether `err` holds one. Use it to tell a statement failure apart from a transport or decoding failure:

```go
if errors.Is(err, &surrealdb.QueryError{}) {
	fmt.Println("one or more statements failed")
}
```

A `QueryError` holds the message only, so the `Is` helpers do not match it. To get the kind of a failure, run the operation with a CRUD function, which returns a `*ServerError`. You can also check the message of the statement.

## Errors from connecting

Connecting can fail before the client sends any request:

| Error | Cause |
| --- | --- |
| `invalid connection url` | The URL has no scheme, or a scheme other than `ws`, `wss`, `http` or `https` |
| `embedded database not enabled` | The URL uses `mem://`, `memory` or `surrealkv://`. See [Embedding](/docs/reference/golang/embedding.md). |
| [`*UnsupportedVersionError`](/docs/reference/golang/api/errors.md#unsupportedversionerror) | With `WithVersionCheck(true)`, the server version is outside the supported range |
| A network error, such as `connection refused` | The server cannot be reached |

`.Health()` returns a [`*HealthError`](/docs/reference/golang/api/errors.md#healtherror) when the server answers its health check with a status other than `2xx`:

```go
var he *surrealdb.HealthError
if err := db.Health(ctx); errors.As(err, &he) {
	log.Printf("server unhealthy: %d %s", he.StatusCode, he.Body)
}
```

## Errors from an import

`DB.Import` keeps every statement of a document that succeeds, even when other statements fail. When some fail, it returns an [`*ImportError`](/docs/reference/golang/api/errors.md#importerror), which lists the error of each failed statement:

```go
err := db.Import(ctx, file)

var ie *surrealdb.ImportError
if errors.As(err, &ie) {
	for _, failure := range ie.Failures {
		log.Println(failure)
	}
}
```

Each failure unwraps to a `*ServerError`, so the `Is` helpers work on it. See [Import and export](/docs/reference/golang/concepts/import-and-export.md#handling-statements-that-fail).

## Checking sentinel errors

The SDK returns fixed errors for conditions that do not come from the server. Check them with `errors.Is`:

```go
import "github.com/surrealdb/surrealdb.go/v2/pkg/constants"

session, err := db.Attach(ctx)
if errors.Is(err, constants.ErrSessionsNotSupported) {
	log.Fatal("sessions need a WebSocket connection")
}
```

| Error | Returned when |
| --- | --- |
| `constants.ErrSessionsNotSupported` | `Attach`, `Fork` or `Sessions` is called on an HTTP connection |
| `constants.ErrTransactionsNotSupported` | `Begin` is called on an HTTP connection |
| `constants.ErrSessionClosed` | A session is used after `.Detach()` |
| `constants.ErrTransactionClosed` | A transaction is used after `.Commit()` or `.Cancel()` |
| `constants.ErrForkTokenExpired` | `Fork` is called after the session's access token has expired |
| `constants.ErrForkUntracked` | `Fork` is called on a session that this client did not attach |
| `constants.ErrNeedsCBOR2` | A value with no plain CBOR form, such as a `models.Regex`, is sent to a server before SurrealDB 4.0 |
| `surrealdb.ErrClientClosed` | The client is used after `.Close()` |
| `surrealdb.ErrLiveQueryEnded` | A live query was ended, instead of restarted, when the client reconnected |
| `surrealdb.ErrStreamProtocol` | The frames of a streamed query break the streaming protocol |
| `connection.ErrConnectionClosed` | The connection was lost while a request waited for its answer |

The SDK wraps the errors in `constants` in some cases, so use `errors.Is` rather than `==`.

## Deciding whether to retry

Retry only a request that failed for a reason that does not depend on the request itself:

| Error | Retry | Reason |
| --- | --- | --- |
| `IsTransactionConflict` | Yes | Another transaction changed the same data. Running it again usually succeeds. |
| `context.DeadlineExceeded` | Yes, with care | The request timed out, and may or may not have run. Retry only work that is safe to repeat. |
| `connection.ErrConnectionClosed` | Yes, with care | The connection was lost while the request was in flight, so it may or may not have run. A reconnecting client sends later requests on the new connection. |
| `QueryError` | No | The statement itself failed, for example because of its data or a `THROW`. |
| Another `ServerError` kind, such as `NotAllowed` or `AlreadyExists` | No | The request is refused, and sending it again gives the same answer. |
| A decoding error | No | The type parameter does not match the result. |

## SurrealDB 3.x servers

SurrealDB 3.x reports some errors with less precise kinds than 4.0. For example, a value that does not match the type of a field gives an `Internal` error with code `-32000` on 3.x. On 4.0, it gives a `Validation` error with code `-32600`. Code that has to work with both versions should not depend on `Kind` or `Details` having the 4.0 values.

## Learn more

- [Errors API reference](/docs/reference/golang/api/errors.md) for every error type and sentinel
- [Executing queries](/docs/reference/golang/concepts/executing-queries.md#reading-the-results-of-several-statements) for statement results
- [Reliable connections](/docs/reference/golang/concepts/reliable-connections.md) for requests during a reconnect
- [Errors](/docs/reference/protocols/errors.md) for the error kinds that every SDK shares

---

Source: https://surrealdb.com/docs/reference/golang/concepts/executing-queries

# Executing queries

Run SurrealQL with the Go SDK using Query, decode each statement's result into a Go type, bind variables, compose statements with QueryRaw, call functions with Run and RunVersion, invoke DEFINE API endpoints with API, run ISO GQL with GQL, and set session variables.

The Go SDK runs SurrealQL with generic functions that decode the result into a Go type you choose. [`Query`](/docs/reference/golang/api/core/db.md#query) runs one or more statements, and [`QueryRaw`](/docs/reference/golang/api/core/db.md#queryraw) runs a list of statements with a result for each. [`Run`](/docs/reference/golang/api/core/db.md#run) calls a function, [`API`](/docs/reference/golang/api/core/db.md#api) calls a `DEFINE API` endpoint, and [`GQL`](/docs/reference/golang/api/core/db.md#gql) runs an ISO GQL query. Each takes a [`*DB`](/docs/reference/golang/api/core/db.md), a [`*Session`](/docs/reference/golang/api/core/session.md) or a [`*Transaction`](/docs/reference/golang/api/core/transaction.md). This page covers each of them, and the variables that a session keeps for its queries.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Function</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#query"><code>surrealdb.Query[T](ctx, s, sql, vars)</code></a></td>
			<td scope="row" data-label="Description">Runs SurrealQL and returns one result for each statement</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#queryraw"><code>surrealdb.QueryRaw(ctx, s, queries)</code></a></td>
			<td scope="row" data-label="Description">Runs a list of statements and gives each its own result</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#querystream"><code>surrealdb.QueryStream[T](ctx, s, sql, vars)</code></a></td>
			<td scope="row" data-label="Description">Runs SurrealQL and yields its results as they arrive</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#run"><code>surrealdb.Run[T](ctx, s, name, args...)</code></a></td>
			<td scope="row" data-label="Description">Calls a function and returns its result</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#runversion"><code>surrealdb.RunVersion[T](ctx, s, name, version, args...)</code></a></td>
			<td scope="row" data-label="Description">Calls a function at a given version</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#api"><code>surrealdb.API[T](ctx, s, path, req)</code></a></td>
			<td scope="row" data-label="Description">Invokes an endpoint defined with <code>DEFINE API</code></td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#gql"><code>surrealdb.GQL[T](ctx, s, query, vars)</code></a></td>
			<td scope="row" data-label="Description">Runs an ISO GQL query</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#let"><code>db.Let(ctx, key, val)</code></a></td>
			<td scope="row" data-label="Description">Sets a variable in the session</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#unset"><code>db.Unset(ctx, key)</code></a></td>
			<td scope="row" data-label="Description">Removes a variable from the session</td>
		</tr>
	</tbody>
</table>

## Running a query

`Query` takes the SurrealQL to run and a map of variables. It returns a pointer to a slice with one [`QueryResult`](/docs/reference/golang/api/types.md#queryresult) for each statement. The type parameter is the Go type of each statement's result:

```go
type Person struct {
	ID   *models.RecordID `json:"id,omitempty"`
	Name string           `json:"name"`
	Age  int              `json:"age"`
}

results, err := surrealdb.Query[[]Person](ctx, db,
	"SELECT * FROM person WHERE age >= $min_age ORDER BY age",
	map[string]any{"min_age": 18},
)
if err != nil {
	log.Fatal(err)
}

for _, p := range (*results)[0].Result {
	fmt.Printf("%s is %d\n", p.Name, p.Age)
}
```

```text title="Output"
Jaime is 28
Tobie is 35
```

Each `QueryResult` holds the `Status` of its statement, the `Time` it took, the decoded `Result`, and an `Error` when the statement failed. The `Status` is `"OK"` or `"ERR"`.

A `SELECT` returns an array, so its type parameter is a slice. For a statement that returns one value, such as `RETURN` or `SELECT ... FROM ONLY`, the type parameter is the type of that value. The SDK matches struct fields by their `json` tags, as in the `Person` type above.

## Binding variables

Pass values as variables, rather than formatting them into the SurrealQL text. In the query, refer to each variable with `$name`. The SDK sends each variable as a typed CBOR value. As a result, a [record ID](/docs/reference/golang/api/values/record-id.md), a `time.Time` or a [`models.PlainDate`](/docs/reference/golang/api/values/temporal.md) keeps its kind, and a variable cannot change the meaning of the query:

```go
results, err := surrealdb.Query[[]Person](ctx, db,
	"SELECT * FROM person WHERE name = $name AND age > $age",
	map[string]any{
		"name": "Tobie",
		"age":  25,
	},
)
```

Pass `nil` when the query has no variables:

```go
results, err := surrealdb.Query[[]Person](ctx, db, "SELECT * FROM person", nil)
```

[Value types](/docs/reference/golang/concepts/value-types.md) lists the SurrealDB kind that the SDK sends for each Go value.

## Reading the results of several statements

A query with several statements returns a result for each of them, in order. A statement can fail while the others succeed, so check the `Error` field of each result:

```go
results, err := surrealdb.Query[any](ctx, db,
	"RETURN 1; THROW 'Not allowed'; RETURN 3;",
	nil,
)

for i, qr := range *results {
	if qr.Error != nil {
		fmt.Printf("statement %d failed: %s\n", i, qr.Error.Message)
		continue
	}
	fmt.Printf("statement %d: %v\n", i, qr.Result)
}
```

```text title="Output"
statement 0: 1
statement 1 failed: An error occurred: Not allowed
statement 2: 3
```

When any statement fails, `Query` also returns an error. This error joins the [`QueryError`](/docs/reference/golang/api/errors.md#queryerror) of each failed statement. `Query` still returns the results, so you can read the results of the statements that succeeded. `errors.Is(err, &surrealdb.QueryError{})` reports whether the error holds a statement failure, as opposed to a transport or decoding failure. See [Error handling](/docs/reference/golang/concepts/error-handling.md#handling-statement-errors).

All the results share one type parameter. When the statements return different types, use `any`, or use `QueryRaw`, which decodes each result into its own type.

## Composing queries with QueryRaw

`QueryRaw` runs a list of [`QueryStmt`](/docs/reference/golang/api/types.md#querystmt) values as one query. Each `QueryStmt` has its own SurrealQL and variables. After it returns, `.GetResult()` decodes each statement's result into a type of its own:

```go
stmts := []surrealdb.QueryStmt{
	{SQL: "CREATE person:alice SET name = $name, age = 41", Vars: map[string]any{"name": "Alice"}},
	{SQL: "SELECT count() AS total FROM person GROUP ALL"},
}

if err := surrealdb.QueryRaw(ctx, db, &stmts); err != nil {
	log.Fatal(err)
}

var created []Person
if err := stmts[0].GetResult(&created); err != nil {
	log.Fatal(err)
}

var counts []struct {
	Total int `json:"total"`
}
if err := stmts[1].GetResult(&counts); err != nil {
	log.Fatal(err)
}
```

Each `QueryStmt` must hold exactly one statement, so that the SDK can match each result to its statement. When a `QueryStmt` holds several statements or only a comment, `QueryRaw` returns an error and leaves the results unchanged. The SDK sends the variables of all the statements together, so two statements must not give different values to the same variable name.

`QueryRaw` can also run a transaction written as statements. Put each of `BEGIN`, `COMMIT` and `CANCEL` in a `QueryStmt` of its own. With SurrealDB 3.x, `QueryRaw` returns an error for a transaction that has a `RETURN` statement. It also returns an error for a transaction that is cancelled after a statement in it failed. This is because those servers do not return one result for each statement. Use `Query` for these transactions.

The [query builder](/docs/reference/golang/concepts/query-builder.md) builds the SurrealQL and the variables for a statement.

## Calling a function

`Run` calls a function with arguments and decodes what it returns. The function can be a built-in one, such as `string::len`, or one defined with [`DEFINE FUNCTION`](/docs/reference/query-language/statements/define/function.md):

```go
length, err := surrealdb.Run[int](ctx, db, "string::len", "SurrealDB")
if err != nil {
	log.Fatal(err)
}
fmt.Println(*length)
```

```text title="Output"
9
```

```surql
DEFINE FUNCTION fn::greet($name: string) -> string {
	RETURN 'Hello, ' + $name + '!';
};
```

```go
greeting, err := surrealdb.Run[string](ctx, db, "fn::greet", "Tobie")
if err != nil {
	log.Fatal(err)
}
fmt.Println(*greeting)
```

```text title="Output"
Hello, Tobie!
```

A function name has parts joined by `::`. The only names without `::` are the built-ins `count`, `not`, `rand` and `sleep`. `Run` refuses any other name before it sends anything, with an error such as `invalid function name "DELETE"`.

`RunVersion` calls a function, such as a machine learning model, at a given version:

```go
prediction, err := surrealdb.RunVersion[float64](ctx, db, "ml::house_price", "1.0.0", features)
```

The version has the form `1.0.0`. With an empty version, `RunVersion` does the same as `Run`.

## Defining session variables

`.Let()` sets a variable in the session. Every later query in that session can use the variable. `.Unset()` removes the variable:

```go
if err := db.Let(ctx, "min_age", 30); err != nil {
	log.Fatal(err)
}

names, err := surrealdb.Query[[]string](ctx, db,
	"SELECT VALUE name FROM person WHERE age >= $min_age ORDER BY name",
	nil,
)

if err := db.Unset(ctx, "min_age"); err != nil {
	log.Fatal(err)
}
```

A variable belongs to the session that set it, so it does not affect other connections or [sessions](/docs/reference/golang/concepts/multiple-sessions.md). If you pass a variable with the same name to `Query`, that variable replaces the session variable for that query.

Over WebSocket, the client keeps a copy of each variable. The client uses this copy to set the variable again when it [reconnects](/docs/reference/golang/concepts/reliable-connections.md), and to copy the variable to a [forked session](/docs/reference/golang/concepts/multiple-sessions.md#copying-a-session). The client encodes the value once, when you call `.Let()`. If you change the Go value after that, neither the variable nor its copies change.

## Sending statements as one transaction

Statements between `BEGIN TRANSACTION` and `COMMIT TRANSACTION` in one query succeed or fail together:

```go
_, err := surrealdb.Query[any](ctx, db, `
	BEGIN TRANSACTION;
	UPDATE account:one SET balance -= $amount;
	UPDATE account:two SET balance += $amount;
	COMMIT TRANSACTION;
`, map[string]any{"amount": 40})
```

To run statements one at a time and decide in Go whether to commit, use an [interactive transaction](/docs/reference/golang/concepts/transactions.md).

## Calling a DEFINE API endpoint

`API` calls an endpoint defined with [`DEFINE API`](/docs/reference/query-language/statements/define/api.md) in the namespace and database of the session. The call does not go through the HTTP router of the server:

```surql
DEFINE API "/greet/:name" FOR get THEN {
	RETURN {
		status: 200,
		body: { greeting: 'Hello, ' + $request.params.name },
	};
};
```

```go
type Greeting struct {
	Greeting string `json:"greeting"`
}

res, err := surrealdb.API[Greeting](ctx, db, "/greet/Tobie", nil)
if err != nil {
	log.Fatal(err)
}
fmt.Println(res.Status, res.Body.Greeting)
```

```text title="Output"
200 Hello, Tobie
```

A `nil` request is a `GET` without a body. Pass an [`APIRequest`](/docs/reference/golang/api/types.md#apirequest) to set the method, the body, the headers and the query parameters:

```go
res, err := surrealdb.API[Greeting](ctx, db, "/greetings", &surrealdb.APIRequest{
	Method:  "post",
	Body:    map[string]any{"name": "Tobie"},
	Headers: map[string]string{"x-request-id": "42"},
	Query:   map[string]string{"lang": "en"},
})
```

As with `net/http`, `API` does not return an error for a response with an unsuccessful status, so check `Status`. The body of such a response is often a string, for example when the path has no endpoint. When the body does not fit the type parameter, `Body` is its zero value.

`API` sends the call as a query to the SurrealQL function `api::invoke`. As a result, the call fails for a user whom the server does not allow to run arbitrary queries.

## Running ISO GQL

`GQL` runs an [ISO GQL](/docs/learn/querying/gql/overview.md) query, such as a `MATCH` pattern, with the `gql` method of the server. Like `Query`, it returns one result for each statement:

```go
results, err := surrealdb.GQL[[]map[string]any](ctx, db, "MATCH (p:person) RETURN p.name", nil)
if err != nil {
	log.Fatal(err)
}
fmt.Println((*results)[0].Result)
```

```text title="Output"
[map[p.name:Alice] map[p.name:Ana] map[p.name:Jaime] map[p.name:Tobie]]
```

## Reading results as they arrive

`Query` waits for every statement to finish and holds the whole result in memory. To read the records of a large `SELECT` as the server sends them, use [`QueryStream`](/docs/reference/golang/concepts/streaming.md).

## Learn more

- [DB API reference](/docs/reference/golang/api/core/db.md) for complete function signatures and parameters
- [Data manipulation](/docs/reference/golang/concepts/data-manipulation.md) for the typed CRUD functions
- [Error handling](/docs/reference/golang/concepts/error-handling.md) for statement errors and transport errors
- [Types reference](/docs/reference/golang/api/types.md) for the `QueryResult`, `QueryStmt`, `APIRequest` and `APIResponse` types
- [SurrealQL statements](/docs/reference/query-language/statements/overview.md) for the query language syntax

---

Source: https://surrealdb.com/docs/reference/golang/concepts/import-and-export

# Import and export

Back up and restore a SurrealDB database from Go with DB.Export and DB.Import - write SurrealQL to any io.Writer, choose what to export with ExportOptions, import a document that starts with OPTION IMPORT, handle ImportError for failed statements, and know which token the requests use.

[`DB.Export`](/docs/reference/golang/api/core/db.md#export) writes the namespace and database of the default session as a SurrealQL document. [`DB.Import`](/docs/reference/golang/api/core/db.md#import) runs such a document. Use the two methods together to back up and restore a database, or to copy a database to another server. This page covers how to export a database, and how to choose what to export. It also covers how to import a document, and what to do when some of its statements fail.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#export"><code>db.Export(ctx, w, options)</code></a></td>
			<td scope="row" data-label="Description">Writes the database as SurrealQL to an <code>io.Writer</code></td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#import"><code>db.Import(ctx, document)</code></a></td>
			<td scope="row" data-label="Description">Runs a SurrealQL document from an <code>io.Reader</code></td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/types.md#exportoptions"><code>ExportOptions</code></a></td>
			<td scope="row" data-label="Description">Chooses what an export holds</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/errors.md#importerror"><code>ImportError</code></a></td>
			<td scope="row" data-label="Description">Lists the statements of an import that failed</td>
		</tr>
	</tbody>
</table>

## How import and export work

Both methods send an HTTP request to the server, whichever transport the client uses: `Export` sends `POST /export`, and `Import` sends `POST /import`. They work on WebSocket and HTTP connections alike, in the namespace and database of the default session.

Both methods authenticate with the token that the client last received, and do not use the WebSocket session. That token comes from `.SignIn()`, `.SignUp()`, `.Authenticate()` or a renewal. A WebSocket session can outlive its token. By default, the token of a system user lasts one hour. After the token expires, `Export` and `Import` fail with `401 Unauthorized`, but queries still work. Sign in again to get a new token. A client that has not signed in gets `403 Forbidden`.

## Exporting a database

`Export` writes the document to any `io.Writer`, such as a file, a buffer or an HTTP response. With a `nil` options value, `Export` exports every definition and every record:

```go
f, err := os.Create("backup.surql")
if err != nil {
	log.Fatal(err)
}
defer f.Close()

if err := db.Export(ctx, f, nil); err != nil {
	log.Fatal(err)
}
```

The document starts with `OPTION IMPORT;`. After that statement, it holds the definitions and the records of each table. For a database with one `person` record, the document looks like this:

```surql title="Example output"
-- ------------------------------
-- OPTION
-- ------------------------------

OPTION IMPORT;

-- ------------------------------
-- TABLE: person
-- ------------------------------

DEFINE TABLE person TYPE NORMAL SCHEMAFULL PERMISSIONS NONE;

DEFINE FIELD OVERWRITE name ON person TYPE string PERMISSIONS FULL;

-- ------------------------------
-- TABLE DATA: person
-- ------------------------------

INSERT [ { id: person:tobie, name: 'Tobie' } ];
```

`Export` writes the document as the server produces it, and does not close the writer.

## Choosing what to export

Pass [`ExportOptions`](/docs/reference/golang/api/types.md#exportoptions) to leave parts out. The zero value of `ExportOptions` exports what the server exports by default:

```go
err := db.Export(ctx, f, &surrealdb.ExportOptions{
	Tables:         []string{"person", "post"},
	ExcludeUsers:   true,
	ExcludeRecords: false,
})
```

| Field | What it does |
| --- | --- |
| `Tables` | Limits the export to these tables, when it is not empty |
| `ExcludeRecords` | Exports the definitions of tables, without their records |
| `ExcludeUsers` | Leaves out `DEFINE USER` statements |
| `ExcludeAccesses` | Leaves out `DEFINE ACCESS` statements |
| `ExcludeParams` | Leaves out `DEFINE PARAM` statements |
| `ExcludeFunctions` | Leaves out `DEFINE FUNCTION` statements |
| `ExcludeAnalyzers` | Leaves out `DEFINE ANALYZER` statements |

An export over HTTP cannot hold the history of a versioned table, because the server refuses that option over HTTP.

## Importing SurrealQL

`Import` runs a SurrealQL document from any `io.Reader`, in the namespace and database of the default session:

```go
f, err := os.Open("backup.surql")
if err != nil {
	log.Fatal(err)
}
defer f.Close()

if err := db.Use(ctx, "surrealdb", "restored"); err != nil {
	log.Fatal(err)
}

if err := db.Import(ctx, f); err != nil {
	log.Fatal(err)
}
```

`Import` does not close the reader, so close it yourself.

## The OPTION IMPORT statement

The server requires an imported document to start with `OPTION IMPORT;`. An exported document already starts with that statement. Without it, `Import` fails with `400 Bad Request` and the message ``Import requires `OPTION IMPORT;` as the first statement``. To import a document of your own, add the statement at the start:

```go
document := strings.NewReader(`OPTION IMPORT;
CREATE person:jaime SET name = 'Jaime';
CREATE person:ana SET name = 'Ana';`)

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

`OPTION IMPORT` turns off events, live queries, field processing and the output of each statement, so that the import runs fast. The server does not check field types and assertions. It stores a value unchanged, even when a `DEFINE FIELD` statement would refuse that value. To run statements with every side effect, use [`Query`](/docs/reference/golang/concepts/executing-queries.md) instead.

## Handling statements that fail

The server keeps the changes of the statements that succeed, even when other statements in the document fail. When statements fail, `Import` returns an [`*ImportError`](/docs/reference/golang/api/errors.md#importerror) that lists their errors in order:

```go
err := db.Import(ctx, document)

var ie *surrealdb.ImportError
if errors.As(err, &ie) {
	for _, failure := range ie.Failures {
		var se *surrealdb.ServerError
		if errors.As(failure, &se) {
			log.Printf("%s: %s", se.Kind, se.Message)
		}
	}
}
```

```text title="Output when person:tobie already exists"
AlreadyExists: Database record `person:tobie` already exists
```

Each failure unwraps to a [`*ServerError`](/docs/reference/golang/api/errors.md#servererror), so the [`Is` helpers](/docs/reference/golang/api/errors.md#kind-helpers) work on it. The server does not roll back the statements that succeeded. To import all or nothing, import into an empty database. If the import fails, remove that database.

## Learn more

- [DB API reference](/docs/reference/golang/api/core/db.md#export) for the signatures of `Export` and `Import`
- [Error handling](/docs/reference/golang/concepts/error-handling.md#errors-from-an-import) for `ImportError`
- [surreal db export](/docs/reference/cli/db/commands/export.md) and [surreal db import](/docs/reference/cli/db/commands/import.md) for the same operations from the command line

---

Source: https://surrealdb.com/docs/reference/golang/concepts/live-queries

# Live queries

Receive changes to a SurrealDB table in Go with Live and LiveNotifications, read CREATE, UPDATE, DELETE and KILLED notifications from a channel, receive JSON Patch diffs, start a LIVE SELECT with Query, stop a live query with Kill, and understand how live queries restart after a reconnect.

A live query sends your program a notification each time a record in a table is created, updated or deleted. The Go SDK delivers the notifications on a Go channel, so a goroutine can read them while the rest of the program continues to run. This page shows how to start a live query, read its notifications and stop it. It also explains what happens to a live query when the client reconnects.

Live queries need a WebSocket connection (`ws://` or `wss://`). They are available on a [`*DB`](/docs/reference/golang/api/core/db.md) and a [`*Session`](/docs/reference/golang/api/core/session.md), but not on a [`*Transaction`](/docs/reference/golang/api/core/transaction.md). Over HTTP, `Live` fails with `Unable to perform the realtime query`.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Function</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#live"><code>surrealdb.Live(ctx, s, table, diff)</code></a></td>
			<td scope="row" data-label="Description">Starts a live query on a table and returns its UUID</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#livenotifications"><code>db.LiveNotifications(id)</code></a></td>
			<td scope="row" data-label="Description">Returns the notification channel of a live query</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#kill"><code>surrealdb.Kill(ctx, s, id)</code></a></td>
			<td scope="row" data-label="Description">Stops a live query and closes its channel</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#closelivenotifications"><code>db.CloseLiveNotifications(id)</code></a></td>
			<td scope="row" data-label="Description">Closes the channel without stopping the live query on the server</td>
		</tr>
	</tbody>
</table>

## Starting a live query

`Live` starts a live query on a table and returns a [`*models.UUID`](/docs/reference/golang/api/values/uuid.md) that identifies it. The table must exist, so define it first:

```go
if _, err := surrealdb.Query[any](ctx, db, "DEFINE TABLE IF NOT EXISTS person", nil); err != nil {
	log.Fatal(err)
}

liveID, err := surrealdb.Live(ctx, db, models.Table("person"), false)
if err != nil {
	log.Fatal(err)
}
```

The last argument chooses what each notification holds. With `false`, it holds the record. With `true`, it holds the [JSON Patch](#receiving-changes-as-json-patch) operations that changed the record.

## Reading notifications

`.LiveNotifications()` returns the channel that receives the live query's [`Notification`](/docs/reference/golang/api/types.md#notification) values. Read it in a goroutine:

```go
notifications, err := db.LiveNotifications(liveID.String())
if err != nil {
	log.Fatal(err)
}

go func() {
	for n := range notifications {
		switch n.Action {
		case connection.CreateAction:
			fmt.Println("created:", n.Result)
		case connection.UpdateAction:
			fmt.Println("updated:", n.Result)
		case connection.DeleteAction:
			fmt.Println("deleted:", n.Result)
		}
	}
	fmt.Println("live query ended")
}()
```

Each notification holds three fields:

| Field | Type | Description |
| --- | --- | --- |
| `ID` | `*models.UUID` | The UUID of the live query |
| `Action` | `connection.Action` | `CREATE`, `UPDATE`, `DELETE` or `KILLED` |
| `Result` | `any` | The record, as a `map[string]any`, or the JSON Patch operations |

The SDK decodes `Result` into `any`, so a record arrives as a `map[string]any`, with its `id` as a `models.RecordID`. The `connection` package is `github.com/surrealdb/surrealdb.go/v2/pkg/connection`.

When several changes happen quickly, one after another, their notifications can arrive in a different order from the changes.

## Stopping a live query

`Kill` stops the live query on the server:

```go
if err := surrealdb.Kill(ctx, db, liveID.String()); err != nil {
	log.Fatal(err)
}
```

The server then sends a notification with the action `KILLED`. After that, the channel closes and the `for ... range` loop ends.

`.CloseLiveNotifications()` closes the channel without stopping the live query on the server. The server can also end a live query itself, for example when its table is removed. The channel then receives a `KILLED` notification but stays open, so call `.CloseLiveNotifications()` to close it.

## Receiving changes as JSON Patch

With `diff` set to `true`, each notification holds the JSON Patch operations that changed the record. `Result` is then a `[]any` of maps with `op`, `path` and `value` keys:

```go
liveID, err := surrealdb.Live(ctx, db, models.Table("person"), true)
if err != nil {
	log.Fatal(err)
}

notifications, err := db.LiveNotifications(liveID.String())
if err != nil {
	log.Fatal(err)
}

for n := range notifications {
	if ops, ok := n.Result.([]any); ok {
		for _, op := range ops {
			fmt.Println(op)
		}
	}
}
```

A diff is smaller than the whole record, which matters for large records that change one field at a time.

## Live queries from SurrealQL

A [`LIVE SELECT`](/docs/reference/query-language/statements/live-select.md) statement sent with `Query` starts a live query too, and returns its UUID. It can filter the records and choose the fields that notifications hold:

```go
result, err := surrealdb.Query[models.UUID](ctx, db,
	"LIVE SELECT * FROM product WHERE stock < 10",
	nil,
)
if err != nil {
	log.Fatal(err)
}

liveID := (*result)[0].Result.String()
notifications, err := db.LiveNotifications(liveID)
```

Read and stop it as you would one that `Live` started. When the client reconnects, it cannot restart a live query that a `LIVE SELECT` statement started: see [Reconnecting](#reconnecting).

## Live queries in sessions

A live query belongs to the session that started it. Start it on a [`*Session`](/docs/reference/golang/concepts/multiple-sessions.md) and read it with that session's `.LiveNotifications()`:

```go
liveID, err := surrealdb.Live(ctx, session, models.Table("person"), false)
if err != nil {
	log.Fatal(err)
}

notifications, err := session.LiveNotifications(liveID.String())
```

The live query runs with the permissions of the user that the session is signed in as. `.Reset()` and `.Detach()` on a session kill its live queries.

## Reconnecting

When the client [reconnects](/docs/reference/golang/concepts/reliable-connections.md), it starts each live query that `Live` started again on the new connection. The query keeps its UUID, so the channel from `.LiveNotifications()` keeps receiving notifications. The live query restarts in the namespace and database that its session had selected when you called `Live`. It uses these even if the session has selected others since then.

The client ends a live query instead of restarting it in two cases:

- The session is no longer signed in as the same user as when the query started. This makes sure that a live query never runs as someone else.
- The server refuses to start the live query again.

When the client ends a live query, its channel closes. The status event of the reconnect reports `surrealdb.ErrLiveQueryEnded`, and `.LiveNotifications()` returns that error for the query.

The client does not receive notifications for changes that happen while it is disconnected. A reconnect loses a live query that a `LIVE SELECT` statement started, so use `Live` for a live query that must survive a reconnect.

## Learn more

- [DB API reference](/docs/reference/golang/api/core/db.md#live) for complete function signatures and parameters
- [Reliable connections](/docs/reference/golang/concepts/reliable-connections.md) for what a reconnect restores
- [Multiple sessions](/docs/reference/golang/concepts/multiple-sessions.md) for live queries in a session
- [LIVE SELECT statement](/docs/reference/query-language/statements/live-select.md) for the query language syntax

---

Source: https://surrealdb.com/docs/reference/golang/concepts/multiple-sessions

# Multiple sessions

Run isolated sessions over one WebSocket connection with the Go SDK - attach a session with Attach, sign it in and select its namespace, copy a session with Fork, list sessions with Sessions, reset or detach a session, and start transactions and live queries in it.

A session holds its own authentication, namespace and database, and variables. The Go SDK can run several sessions over one WebSocket connection. This lets one program act as several users or tenants without a separate connection for each one. This page covers attaching, copying, listing, resetting and detaching sessions.

Sessions need a WebSocket connection (`ws://` or `wss://`). On an HTTP connection, `Attach`, `Fork` and `Sessions` return `constants.ErrSessionsNotSupported`.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#attach"><code>db.Attach(ctx)</code></a></td>
			<td scope="row" data-label="Description">Attaches a new session to the connection</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#fork"><code>db.Fork(ctx)</code></a></td>
			<td scope="row" data-label="Description">Attaches a session that starts as a copy of the default session</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/session.md#fork"><code>session.Fork(ctx)</code></a></td>
			<td scope="row" data-label="Description">Attaches a session that starts as a copy of this one</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#sessions"><code>db.Sessions(ctx)</code></a></td>
			<td scope="row" data-label="Description">Lists the sessions attached to the connection</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/session.md#reset"><code>session.Reset(ctx)</code></a></td>
			<td scope="row" data-label="Description">Returns a session to the state it had when it was attached</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/session.md#detach"><code>session.Detach(ctx)</code></a></td>
			<td scope="row" data-label="Description">Removes the session from the server</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/session.md#id"><code>session.ID()</code></a></td>
			<td scope="row" data-label="Description">Returns the UUID of the session</td>
		</tr>
	</tbody>
</table>

## Creating a session

`.Attach()` attaches a new session to the connection and returns a [`*Session`](/docs/reference/golang/api/core/session.md). The session starts signed out, with no namespace or database selected. Before you query, sign the session in and select a namespace and database:

```go
session, err := db.Attach(ctx)
if err != nil {
	log.Fatal(err)
}
defer session.Detach(ctx)

if _, err := session.SignIn(ctx, surrealdb.Auth{
	Username: "root",
	Password: "secret",
}); err != nil {
	log.Fatal(err)
}

if err := session.Use(ctx, "surrealdb", "docs"); err != nil {
	log.Fatal(err)
}
```

## Querying with a session

Every query and CRUD function takes a `*Session` in place of the `*DB`:

```go
people, err := surrealdb.Query[[]Person](ctx, session, "SELECT * FROM person", nil)

tobie, err := surrealdb.Select[Person](ctx, session, models.NewRecordID("person", "tobie"))
```

The request runs as the signed-in user of the session. It uses the namespace and database that the session selected, and the variables of the session.

## Session isolation

Sessions do not share state with each other, or with the default session of the `*DB`:

- Signing in on a session does not change who the other sessions are signed in as.
- `.Use()` on a session does not change the namespace or database of the others.
- Variables set with `.Let()` belong to the session that set them.
- [Live queries](/docs/reference/golang/concepts/live-queries.md) started on a session belong to it, and run with its permissions.

```go
admin, err := db.Attach(ctx)
if err != nil {
	log.Fatal(err)
}
defer admin.Detach(ctx)

customer, err := db.Attach(ctx)
if err != nil {
	log.Fatal(err)
}
defer customer.Detach(ctx)

_, err = admin.SignIn(ctx, surrealdb.Auth{Username: "root", Password: "secret"})
_ = admin.Use(ctx, "shop", "main")

_, err = customer.SignIn(ctx, map[string]any{
	"NS":    "shop",
	"DB":    "main",
	"AC":    "account",
	"email": "tobie@example.com",
	"pass":  "hunter123",
})
_ = customer.Use(ctx, "shop", "main")
```

## Copying a session

`.Fork()` attaches a new session that starts as a copy of another session. The copy has the same namespace and database and the same variables, and it is signed in with the same access token. `db.Fork()` copies the default session, and `session.Fork()` copies that session. After the copy, the two sessions are independent:

```go
if err := db.Let(ctx, "tenant", "acme"); err != nil {
	log.Fatal(err)
}

fork, err := db.Fork(ctx)
if err != nil {
	log.Fatal(err)
}
defer fork.Detach(ctx)

tenant, err := surrealdb.Query[string](ctx, fork, "RETURN $tenant", nil)
fmt.Println((*tenant)[0].Result)
```

```text title="Output"
acme
```

The server cannot copy the authentication of a session, so the fork signs in with the access token of the original. A session that signed in with a username and password can outlive that token, which lasts one hour by default. After the token expires, `.Fork()` attaches nothing and returns an error that wraps `constants.ErrForkTokenExpired`. In that case, attach a new session with `.Attach()`. Then sign in the new session yourself.

A fork does not copy a token pair, because a refresh token works only once. As a result, a fork does not [renew its access token](/docs/reference/golang/concepts/authentication.md#automatic-token-renewal) by itself.

## Listing sessions

`.Sessions()` returns the sessions attached to the connection, other than the default one:

```go
sessions, err := db.Sessions(ctx)
if err != nil {
	log.Fatal(err)
}
for _, s := range sessions {
	fmt.Println(s.ID())
}
```

The list holds every other session on the connection. It also includes sessions that this client did not attach, such as a session from a direct call on the connection. The client does not know the state of such a session, so `.Fork()` on it returns `constants.ErrForkUntracked`.

## Resetting a session

`.Reset()` returns a session to the state it had when it was attached. The session is then signed out and has no namespace, database or variables. `.Reset()` also kills its live queries. The session stays attached, so it can sign in again as another user:

```go
if err := session.Reset(ctx); err != nil {
	log.Fatal(err)
}
```

## Starting transactions from a session

A session can start its own [interactive transactions](/docs/reference/golang/concepts/transactions.md) with `.Begin()`. The transaction runs as the signed-in user of the session, in the namespace and database of the session:

```go
tx, err := session.Begin(ctx)
if err != nil {
	log.Fatal(err)
}
defer tx.Cancel(ctx)

if _, err := surrealdb.Create[any](ctx, tx, "event", map[string]any{"type": "login"}); err != nil {
	log.Fatal(err)
}

if err := tx.Commit(ctx); err != nil {
	log.Fatal(err)
}
```

## Detaching a session

`.Detach()` removes the session from the server and kills its live queries. After that, a call on the session returns [`constants.ErrSessionClosed`](/docs/reference/golang/api/errors.md#sentinel-errors):

```go
if err := session.Detach(ctx); err != nil {
	log.Fatal(err)
}
```

Call `defer session.Detach(ctx)` directly after `.Attach()` or `.Fork()`, so that `.Detach()` removes the session even when a later step fails.

## Sessions and reconnection

When the client [reconnects](/docs/reference/golang/concepts/reliable-connections.md), it attaches each session again under the same UUID. It also restores the authentication, namespace, database, variables and live queries of each session. A reconnect loses the transactions that were open in a session.

## Learn more

- [Session API reference](/docs/reference/golang/api/core/session.md) for complete method signatures
- [Transactions](/docs/reference/golang/concepts/transactions.md) for interactive transactions
- [Authentication](/docs/reference/golang/concepts/authentication.md) for signing a session in
- [Errors reference](/docs/reference/golang/api/errors.md) for the session errors

---

Source: https://surrealdb.com/docs/reference/golang/concepts/query-builder

# Query builder

Build SurrealQL with the Go SDK's contrib/surrealql package - SELECT, CREATE, UPDATE, UPSERT, DELETE, INSERT and RELATE with bound parameters, expressions, return clauses, record ranges, SHOW CHANGES, and text transactions - and run the result with surrealdb.Query.

> [!WARNING]
> The `contrib/surrealql` package that provides this feature is outside the backward compatibility guarantee of the SDK. Its API can change in a minor release.

The `surrealql` package builds SurrealQL statements with Go method calls. It binds each value as a parameter, and does not write the value into the text of the query. It returns the SurrealQL and a map of variables, which you pass to [`surrealdb.Query`](/docs/reference/golang/api/core/db.md#query). This page covers each kind of statement that the package builds. The comment below each example shows the SurrealQL that the example builds.

## Importing the package

The query builder is part of the SDK module, so it needs no other `go get`:

```go
import "github.com/surrealdb/surrealdb.go/v2/contrib/surrealql"
```

## Building and running queries

Every builder has a `.Build()` method that returns the SurrealQL and a `map[string]any` of variables. Pass both to `surrealdb.Query`:

```go
q := surrealql.Select("user").Where("age > ?", 18).OrderBy("name").Limit(10)
sql, vars := q.Build()
// SELECT * FROM user WHERE (age > $param_1) ORDER BY name LIMIT 10

results, err := surrealdb.Query[[]User](ctx, db, sql, vars)
```

The builder writes a table name that you give as a string into the SurrealQL as it is. Only pass names that your own code chooses. To bind the target as a parameter too, pass a [`models.RecordID`](/docs/reference/golang/api/values/record-id.md) or a [`models.Table`](/docs/reference/golang/api/values/table.md).

## Selecting records

`Select` starts a `SELECT` statement. Chain `.Fields()`, `.Field()`, `.Where()`, `.GroupBy()`, `.OrderBy()`, `.Limit()` and the other methods to refine it:

```go
surrealql.Select("user")
// SELECT * FROM user

surrealql.Select("user").Fields("name", "email").Where("active = ?", true)
// SELECT name, email FROM user WHERE (active = $param_1)

surrealql.Select("user").
	Field(surrealql.Expr("count()").As("total")).
	GroupBy("department")
// SELECT count() AS total FROM user GROUP BY department
```

`SelectOnly` builds `SELECT ... FROM ONLY`, which returns one record instead of an array:

```go
surrealql.SelectOnly(models.NewRecordID("user", "tobie")).Fields("name")
// SELECT name FROM ONLY $from_id_1
```

### Filtering with Where

`.Where()` takes a condition with `?` placeholders, and binds each value as a parameter. Each further call to `.Where()` adds another condition with `AND`:

```go
surrealql.Select("product").
	Where("price < ?", 100).
	Where("category = ?", "electronics")
// SELECT * FROM product WHERE (price < $param_1) AND (category = $param_2)
```

The builder puts each condition in brackets, so an `OR` inside one condition stays within that condition.

### Ordering and pagination

```go
surrealql.Select("user").
	OrderByDesc("created_at").
	Limit(20).
	Start(40)
// SELECT * FROM user ORDER BY created_at DESC LIMIT 20 START 40
```

### Selecting a range of records

The package has helpers that build a [`models.Range`](/docs/reference/golang/api/values/range.md), such as `RangeBeginInclusiveEndExclusive` and `RangeOpen`. To select a range of records, use a range as the `ID` of a `models.RecordID`:

```go
surrealql.Select(models.RecordID{
	Table: "reading",
	ID:    surrealql.RangeBeginInclusiveEndExclusive(2, 4),
})
// SELECT * FROM $from_id_1, where $from_id_1 is reading:2..4
```

The same value works as the target of [`surrealdb.Select`](/docs/reference/golang/concepts/data-manipulation.md#selecting-a-range-of-records).

## Creating records

`Create` builds a `CREATE` statement. Set fields with `.Set()`, or give the whole content with `.Content()`:

```go
surrealql.Create("user").
	Set("name", "Alice").
	Set("age", 30)
// CREATE user SET name = $param_1, age = $param_2

surrealql.Create("user").Content(map[string]any{
	"name": "Alice",
	"age":  30,
})
// CREATE user CONTENT $content_1
```

`CreateOnly` builds `CREATE ONLY`, which returns one record:

```go
surrealql.CreateOnly("user").Set("name", "Alice").ReturnNone()
// CREATE ONLY user SET name = $param_1 RETURN NONE
```

## Updating records

`Update` builds an `UPDATE` statement, with `.Set()` and `.Where()`:

```go
surrealql.Update("user").
	Set("active", false).
	Where("last_login < ?", "2025-01-01")
// UPDATE user SET active = $param_1 WHERE (last_login < $param_2)
```

`.Set()` also takes a compound operation, such as `-=` or `+=`, with a placeholder:

```go
surrealql.Update(models.NewRecordID("product", "apple")).Set("stock -= ?", 1)
// UPDATE $id_1 SET stock -= $param_1
```

## Upserting records

`Upsert` builds an `UPSERT` statement, which creates a record when it does not exist and updates it when it does. Choose how to give the data with `.Set()`, `.Content()`, `.Merge()`, `.Patch()` or `.Replace()`:

```go
surrealql.Upsert(models.NewRecordID("user", "tobie")).
	Set("name", "Tobie").
	Set("active", true)
// UPSERT $id_1 SET name = $param_1, active = $param_2

surrealql.Upsert("user:tobie").Content(map[string]any{
	"name":   "Tobie",
	"active": true,
})
// UPSERT user:tobie CONTENT $upsert_content_1

surrealql.Upsert("user:tobie").Merge(map[string]any{"active": false})
// UPSERT user:tobie MERGE $upsert_merge_1
```

The `Upsert` builder also has `.Where()`, `.Timeout()`, `.Parallel()` and `.Explain()`.

## Deleting records

`Delete` builds a `DELETE` statement:

```go
surrealql.Delete("session").Where("expired_at < ?", "2025-01-01")
// DELETE session WHERE (expired_at < $param_1)
```

## Inserting records

`Insert` builds an `INSERT` statement, for one record, several records, or lists of values:

```go
surrealql.Insert("user").Value(map[string]any{
	"name": "Alice",
	"age":  30,
})
// INSERT INTO user $insert_data_1

surrealql.Insert("user").
	Fields("name", "age").
	Values("Alice", 30).
	Values("Bob", 25)
// INSERT INTO user (name, age) VALUES ($insert_0_0_1, $insert_0_1_1), ($insert_1_0_1, $insert_1_1_1)
```

`.Relation()` builds `INSERT RELATION`, for edges between records:

```go
surrealql.Insert("knows").Relation().Value(map[string]any{
	"in":  models.NewRecordID("user", "tobie"),
	"out": models.NewRecordID("user", "jaime"),
})
// INSERT RELATION INTO knows $insert_data_1
```

To update a record that already exists, add `ON DUPLICATE KEY UPDATE`:

```go
surrealql.Insert("product").
	Fields("id", "stock").
	Values(models.NewRecordID("product", "apple"), 10).
	OnDuplicateKeyUpdateRaw("stock += $input.stock")
// INSERT INTO product (id, stock) VALUES ($insert_0_0_1, $insert_0_1_1) ON DUPLICATE KEY UPDATE stock += $input.stock
```

## Creating relations

`Relate` builds a `RELATE` statement between two records:

```go
surrealql.Relate(
	models.NewRecordID("user", "tobie"),
	"wrote",
	models.NewRecordID("post", "first"),
).Set("created_at", "2026-01-01")
// RELATE $id_1->wrote->$id_2 SET created_at = $param_1
```

## Using expressions

`Expr` builds an expression with `?` placeholders, for a function call, a graph traversal, or any expression that needs bound values:

```go
surrealql.Select("user").
	Field(surrealql.Expr("math::mean([?, ?, ?])", 1, 2, 3).As("avg"))
// SELECT math::mean([$param_1, $param_2, $param_3]) AS avg FROM user

surrealql.Select(surrealql.Expr("?->knows->user", models.NewRecordID("user", "tobie")))
// SELECT * FROM $from_param_1->knows->user
```

## Return clauses

The statements that change records take a return clause:

```go
surrealql.Create("user").Set("name", "Alice").ReturnNone()
// CREATE user SET name = $param_1 RETURN NONE

surrealql.Update("user").Set("active", true).Return("AFTER")
// UPDATE user SET active = $param_1 RETURN AFTER

surrealql.Delete("session").ReturnBefore()
// DELETE session RETURN BEFORE
```

## Reading changes with SHOW CHANGES

`ShowChangesForTable` builds a [`SHOW CHANGES`](/docs/reference/query-language/statements/show.md) statement, for a table defined with a change feed. `.SinceVersionstamp()` starts from a versionstamp, and `.Limit()` sets the maximum number of changes:

```go
surrealql.ShowChangesForTable("reading").SinceVersionstamp(versionstamp).Limit(10)
// SHOW CHANGES FOR TABLE reading SINCE 65536 LIMIT 10, for a versionstamp of 65536
```

Pass a versionstamp exactly as `SHOW CHANGES` returned it. `SINCE` is inclusive. When you continue from the last change that you received, the server returns that change again. Version 1 of the SDK shifted the versionstamp right by 16 bits, as [the migration guide](/docs/reference/golang/migrating-to-2x.md#6-update-sinceversionstamp-in-the-query-builder) describes.

## Building text transactions

`Begin` builds a text transaction, which runs its statements in one request and commits them together. Add statements with `.Do()`, variables with `.Let()`, and raw SurrealQL with `.Raw()`:

```go
q := surrealql.Begin().
	Let("amount", 100).
	Do(surrealql.Update(models.NewRecordID("account", "one")).Set("balance -= $amount")).
	Do(surrealql.Update(models.NewRecordID("account", "two")).Set("balance += $amount"))

sql, vars := q.Build()
```

```surql title="Output"
BEGIN TRANSACTION;
LET $amount = 100;
UPDATE $id_1 SET balance -= $amount;
UPDATE $id_2 SET balance += $amount;
COMMIT TRANSACTION;
```

> [!NOTE]
> A text transaction is not an [interactive transaction](/docs/reference/golang/concepts/transactions.md). A text transaction runs every statement in a single request, so your code cannot read a result before the next statement runs. An interactive transaction runs one statement at a time.

## Learn more

- [Executing queries](/docs/reference/golang/concepts/executing-queries.md) for running the built queries with `surrealdb.Query`
- [Data manipulation](/docs/reference/golang/concepts/data-manipulation.md) for the typed CRUD functions, which need no builder
- [SurrealQL statements](/docs/reference/query-language/statements/overview.md) for the query language reference

---

Source: https://surrealdb.com/docs/reference/golang/concepts/reliable-connections

# Reliable connections

How a Go SDK WebSocket client reconnects by itself - backoff with WithReconnectAttempts and WithReconnectDelay, what it restores and what it loses, watching the connection with Status and OnStatus, and the contrib/rews package for custom retry strategies.

A client can lose its WebSocket connection, for example when the network changes or the server restarts. A Go SDK client that uses WebSocket then reconnects by itself. Before it sends anything else on the new connection, it restores what it held on the old one. This page covers how reconnection works, and what the client restores and loses. It also covers how to watch the state of the connection, and the `contrib/rews` package for custom retry strategies.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Function</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#withreconnect"><code>surrealdb.WithReconnect(enabled)</code></a></td>
			<td scope="row" data-label="Description">Turns reconnection on or off</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#withreconnectattempts"><code>surrealdb.WithReconnectAttempts(attempts)</code></a></td>
			<td scope="row" data-label="Description">Sets how many consecutive attempts the client makes</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#withreconnectdelay"><code>surrealdb.WithReconnectDelay(min, max)</code></a></td>
			<td scope="row" data-label="Description">Sets the wait before each attempt</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#status"><code>db.Status()</code></a></td>
			<td scope="row" data-label="Description">Returns the state of the connection</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#onstatus"><code>db.OnStatus(fn)</code></a></td>
			<td scope="row" data-label="Description">Calls a function at each change of the state</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><code>rews.New(newConn, interval, unmarshaler, logger)</code></td>
			<td scope="row" data-label="Description">Creates a reconnecting WebSocket connection with its own retry strategy</td>
		</tr>
	</tbody>
</table>

## How reconnection works

Reconnection is on by default for WebSocket connections. When the client loses the connection, it connects again, with backoff between attempts. The wait before attempt *n* is the minimum delay times 2 to the power of *n*, counting attempts from 1. Each wait also has up to 10% random jitter in either direction, and no wait is longer than the maximum delay. With the default delays of `1s` and `1m`, the client waits about 2, 4, 8, 16 and 32 seconds before its five attempts. When the last attempt fails, the client gives up and closes.

While the client reconnects:

- A request made in that time waits until the client has reconnected and restored the session. If the request's context ends first, the request fails with `waiting to reconnect: context deadline exceeded`.
- A request that was waiting for its response when the client lost the connection fails with an error that wraps `connection.ErrConnectionClosed`. The server may or may not have run that request.
- After the client gives up, every request fails with an error that wraps `surrealdb.ErrClientClosed`.

Pass options to change the number of attempts and the delays:

```go
db, err := surrealdb.FromEndpointURLStringWithOptions(ctx, "wss://example.surrealdb.cloud",
	surrealdb.WithReconnectAttempts(10),
	surrealdb.WithReconnectDelay(500*time.Millisecond, 30*time.Second),
)
```

`WithReconnectAttempts(0)`, or any number below 1, removes the limit, so the client tries until it reconnects or you close it. `WithReconnect(false)` turns reconnection off: a lost connection then closes the client, and later requests fail.

HTTP connections are stateless, so they have nothing to reconnect. Each HTTP request opens what it needs.

## What gets restored

Before it sends any other request on the new connection, the client restores what it held on the old one:

1. The **sessions** attached with `Attach` or `Fork`, under the same UUIDs.
2. The **authentication** of the default session and of each session, with the last token that the session received. With [token renewal](/docs/reference/golang/concepts/authentication.md#automatic-token-renewal) on, the client first exchanges an expired pair for a new one.
3. The **namespace and database** of each session.
4. The **variables** that each session set with `.Let()`.
5. The **live queries** started with `Live`, under the same UUIDs, each in the namespace and database where it started. Their channels keep receiving notifications.

The client ends a live query, instead of restoring it, when its session is no longer signed in as the same user. The client also ends a live query when the server refuses to start it again. In both cases, the channel of the live query closes, and the status event reports `surrealdb.ErrLiveQueryEnded`.

## What is lost

The client cannot restore some state on a new connection:

- **Open transactions.** A transaction that was open is gone, and calls on it fail. Run the transaction again from the start.
- **Live queries started with a `LIVE SELECT` statement.** The client does not know their definition, so it cannot start them again. Use `Live` for a live query that must survive a reconnect.
- **Changes made while the client was disconnected.** Live queries that restart do not receive notifications for those changes.
- **A sign-in whose token has expired.** A session that signed in with a username and password can outlive its token. By default, the token lasts one hour. Without token renewal, the client cannot authenticate the session again on the new connection, and the status event reports the error.
- **A sign-in on a server that restarted with a new datastore.** A server that runs in memory starts empty after a restart. It does not accept the tokens that it issued before the restart. The status event reports `authenticate: There was a problem with authentication`. The session is signed out, and its live queries end. A server with a persistent datastore accepts the old token, so the client restores the session.

If the client cannot restore the sign-in, sign the session in again. You can do this in the function that you pass to `.OnStatus()`.

## Watching the connection status

`.Status()` returns the state of the connection, as a `surrealdb.ConnectionStatus`:

| Status | Meaning |
| --- | --- |
| `StatusConnected` | The client sends requests to the server. |
| `StatusDisconnected` | The client lost the connection, or an attempt to reconnect failed. Requests wait. |
| `StatusReconnecting` | The client is trying to reconnect. |
| `StatusClosed` | The client was closed, or gave up reconnecting. Requests fail. |

`.OnStatus()` calls a function with a [`StatusEvent`](/docs/reference/golang/api/types.md#statusevent) at each change of state, until you call the function that `.OnStatus()` returns:

```go
stop := db.OnStatus(func(ev surrealdb.StatusEvent) {
	switch ev.Status {
	case surrealdb.StatusDisconnected:
		log.Printf("connection lost (attempt %d): %v", ev.Attempt, ev.Err)
	case surrealdb.StatusConnected:
		if ev.Err != nil {
			log.Printf("reconnected, but could not restore: %v", ev.Err)
		}
	case surrealdb.StatusClosed:
		log.Printf("gave up: %v", ev.Err)
	}
})
defer stop()
```

`Attempt` counts the attempts since the client lost the connection, from 1. It is 0 for the event that reports the loss. On a `StatusConnected` event after a reconnect, `Err` holds what the client could not restore, such as an expired token. `Err` is `nil` when the client restored everything.

The client calls the function with one event at a time, in order, on a goroutine of its own. The function can make requests on the client, or close the client. The next events wait until the function returns. Only a client that reconnects reports changes. A client without reconnection reports `StatusConnected` until it is closed.

## Custom connections

A `gorillaws` or `gws` connection that you pass to [`FromConnection`](/docs/reference/golang/api/core/db.md#fromconnection) reconnects in the same way. Both connection types implement `connection.Redialer` and `connection.CloseNotifier`. A connection of your own reconnects when it implements those two interfaces.

## Using the rews package

> [!WARNING]
> The `contrib/rews` package is outside the backward compatibility guarantee of the SDK. Its API can change in a minor release.

The `rews` package provides a reconnecting WebSocket connection with its own retry strategies. For example, it can use exponential backoff without a limit on attempts, or a strategy that you write yourself. Use it when the built-in reconnection options do not fit.

Create a `rews.Connection` with `rews.New`. It takes these arguments, in this order:

- A function that builds the underlying WebSocket connection
- An interval for checking the connection
- A CBOR unmarshaler
- An optional logger

The example below uses a `gorillaws` connection, checks it every 5 seconds, and passes no logger:

```go
import (
	"context"
	"net/url"
	"time"

	surrealdb "github.com/surrealdb/surrealdb.go/v2"
	"github.com/surrealdb/surrealdb.go/v2/contrib/rews"
	"github.com/surrealdb/surrealdb.go/v2/pkg/connection"
	"github.com/surrealdb/surrealdb.go/v2/pkg/connection/gorillaws"
)

u, err := url.ParseRequestURI("ws://localhost:8000")
if err != nil {
	log.Fatal(err)
}
conf := connection.NewConfig(u)

conn := rews.New(
	func(ctx context.Context) (*gorillaws.Connection, error) {
		return gorillaws.New(conf), nil
	},
	5*time.Second,
	conf.Unmarshaler,
	nil,
)

db, err := surrealdb.FromConnection(ctx, conn)
if err != nil {
	log.Fatal(err)
}
defer db.Close(ctx)
```

A `rews` connection reconnects by itself. The client does not use its built-in reconnection on this connection.

### Configuring retry behaviour

By default, `rews` does not retry a failed attempt to connect. To retry, set the `Retryer` field of the connection. `ExponentialBackoffRetryer` makes the delay between attempts grow exponentially, with jitter:

```go
retryer := rews.NewExponentialBackoffRetryer()
retryer.MaxRetries = 10
retryer.InitialDelay = time.Second
retryer.MaxDelay = 30 * time.Second
conn.Retryer = retryer
```

| Field | Default | Description |
| --- | --- | --- |
| `InitialDelay` | `1s` | The delay before the first retry |
| `MaxDelay` | `30s` | The longest delay between retries |
| `Multiplier` | `2.0` | The factor by which the delay grows |
| `MaxRetries` | `0` | The number of retries, where `0` means no limit |
| `Jitter` | `true` | Adds randomness to each delay |
| `JitterFactor` | `0.3` | The largest jitter, as a fraction of the delay |

`FixedDelayRetryer` waits the same time before each attempt:

```go
conn.Retryer = rews.NewFixedDelayRetryer(2*time.Second, 5)
```

A strategy of your own implements the `Retryer` interface:

```go
type Retryer interface {
	NextDelay(attempt int, lastErr error) (time.Duration, bool)
	Reset()
}
```

### What rews restores

When `rews` reconnects, it restores the namespace and database, the authentication, the variables and the live queries. The figure below shows the states of a `rews` connection and the order in which it restores the session.

<img src="~/assets/img/diagrams/light/conn-reconnect-go-light.webp" darkSrc="~/assets/img/diagrams/conn-reconnect-go.webp" alt="The rews connection of the Go SDK moves from Disconnected to Connecting to Connected, and to Closing and Closed after Close(). At each CheckInterval it checks the socket, and if the socket has closed it reconnects and restores the session; a failed attempt is tried again at the next check. The session is restored in this order: the namespace and database from the last Use(), the authentication with the last token or, if the server refuses it, with the refresh token from SignInWithRefresh, the variables set with Let(), and the live queries from Live() or from a Query() call that starts with LIVE SELECT, whose notifications keep their original IDs. With an expired token and no refresh token the reconnect fails, and a LIVE SELECT that is not at the start of its query is not restored." />

> [!NOTE]
> When the server refuses the last token on a reconnect, and the session signed in with `.SignInWithRefresh()` or `.SignUpWithRefresh()`, `rews` signs in with the refresh token and keeps the new pair. The server revokes a refresh token once it is used, so set `OnTokensRefreshed` to receive the new pair, or read it with `conn.Tokens(ctx)`. Without a refresh token, the sign-in fails and the reconnect is tried again at the next check.

A `rews.Connection` moves through the states `Disconnected`, `Connecting`, `Connected`, `Closing` and `Closed`. After `Closed`, it cannot be used again.

## Learn more

- [Connecting to SurrealDB](/docs/reference/golang/concepts/connecting-to-surrealdb.md) for the connection options
- [Live queries](/docs/reference/golang/concepts/live-queries.md#reconnecting) for live queries across a reconnect
- [Authentication](/docs/reference/golang/concepts/authentication.md#automatic-token-renewal) for token renewal
- [DB API reference](/docs/reference/golang/api/core/db.md#withreconnect) for the reconnection options

---

Source: https://surrealdb.com/docs/reference/golang/concepts/streaming

# Streaming results

Read query results with the Go SDK as SurrealDB streams them, using QueryStream and a range-over-func loop - StreamFrame rows, Done frames, single values, provisional rows, several statements, stopping early to cancel the query, timeouts, memory, and the fallback over HTTP.

[`Query`](/docs/reference/golang/api/core/db.md#query) waits until every statement has finished, and holds the whole result in memory before it returns. [`QueryStream`](/docs/reference/golang/api/core/db.md#querystream) yields the result in frames while the query runs. Your code can use the records of a large `SELECT` as they arrive, and can stop the query before it finishes. This page covers reading frames, what each frame holds, and how streaming behaves on each transport.

Streaming uses the `query_stream` method over WebSocket. Over HTTP, or when the server refuses the method, `QueryStream` runs the query with `Query` instead. It then yields the whole result as frames of the same form.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Function</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/core/db.md#querystream"><code>surrealdb.QueryStream[T](ctx, s, sql, vars)</code></a></td>
			<td scope="row" data-label="Description">Runs a query and yields its result frame by frame</td>
		</tr>
		<tr>
			<td scope="row" data-label="Function"><a href="/docs/reference/golang/api/types.md#streamframe"><code>StreamFrame[T]</code></a></td>
			<td scope="row" data-label="Description">One step of a query's result</td>
		</tr>
	</tbody>
</table>

## Reading records as they arrive

`QueryStream` returns an `iter.Seq2[StreamFrame[T], error]`, which a `for ... range` loop reads. The type parameter is the type of one row in `Rows`:

```go
type Reading struct {
	ID    *models.RecordID `json:"id,omitempty"`
	Value int              `json:"value"`
}

for frame, err := range surrealdb.QueryStream[Reading](ctx, db, "SELECT * FROM reading", nil) {
	if err != nil {
		log.Fatal(err)
	}
	for _, r := range frame.Rows {
		process(r)
	}
	if frame.Done {
		fmt.Println("finished in", frame.Time)
	}
}
```

A `SELECT` of 20,000 records arrives in about 80 frames, with a few hundred records in each frame. As a result, the program can use the first records before the last ones arrive.

## What a frame holds

Each [`StreamFrame`](/docs/reference/golang/api/types.md#streamframe) belongs to one statement of the query:

| Field | Description |
| --- | --- |
| `Statement` | The index of the statement, from 0 |
| `Rows` | Rows of the statement. More frames can follow with more rows. |
| `Done` | `true` on the last frame of the statement. No frame follows it for that statement. |
| `Err` | The statement's error, as a `*QueryError`, on its `Done` frame |
| `Single` | `true` on the `Done` frame of a statement that returns one value rather than a list |
| `Value` | The value of a `Single` statement |
| `Time` | How long the statement took, on its `Done` frame |

A statement that returns one value, such as `RETURN 42` or `SELECT * FROM ONLY person:tobie`, has no rows. Its `Done` frame sets `Single` and holds the result in `Value`.

## Rows are provisional until Done

The rows of a statement are not final until its `Done` frame. When that frame carries an `Err`, the statement failed, and every row delivered for that statement is retracted. Your code can act on rows as they arrive, for example by writing them to a file. In that case, be ready to undo the work when the statement fails. Alternatively, collect the rows and act on them at the `Done` frame.

## Reading several statements

For a query with several statements, `QueryStream` yields the frames of each statement in turn. Use the `Statement` field to find which statement a frame belongs to:

```go
sql := "RETURN 42; THROW 'boom'; SELECT id FROM reading LIMIT 2"

for frame, err := range surrealdb.QueryStream[any](ctx, db, sql, nil) {
	if err != nil {
		log.Fatal(err)
	}
	if frame.Done && frame.Err != nil {
		fmt.Printf("statement %d failed: %v\n", frame.Statement, frame.Err)
	}
}
```

```text title="Output"
statement 1 failed: An error occurred: boom
```

All the statements share one type parameter. When the statements return different types, use `any`. A row that does not decode into the type parameter is an error, and that error ends the iteration.

Some errors belong to no single statement, such as a query that does not parse or a lost connection. `QueryStream` yields such an error as the loop's `err`, and the error ends the iteration. The error retracts every statement that has no `Done` frame yet.

## Stopping early

Leave the loop with `break` or `return` to stop reading. The SDK then cancels the query on the server, so the server stops producing records:

```go
count := 0
for frame, err := range surrealdb.QueryStream[Reading](ctx, db, "SELECT * FROM reading", nil) {
	if err != nil {
		log.Fatal(err)
	}
	count += len(frame.Rows)
	if count >= 1000 {
		break
	}
}
```

In a [transaction](/docs/reference/golang/concepts/transactions.md#streaming-in-a-transaction), when you leave the loop, the SDK waits for the server to end the cancelled query. This makes sure that a later `.Commit()` or `.Cancel()` comes after the end of that query. The statements that ran before you left the loop stay in the transaction.

## Timeouts and memory

The timeout of the connection limits only the wait for the first frame, which the server sends at once. After that, the context that you pass is the only limit on the wait. This is because a statement can send nothing for a long time before it has rows or finishes. To limit the whole query, pass a context with a deadline.

The server does not wait for your loop. The SDK buffers the frames that arrive faster than the loop reads them, and this buffer has no size limit. A loop that reads slowly can therefore still hold the whole result in memory, as `Query` does.

## Learn more

- [Executing queries](/docs/reference/golang/concepts/executing-queries.md) for `Query` and the other ways to run SurrealQL
- [DB API reference](/docs/reference/golang/api/core/db.md#querystream) for the signature of `QueryStream`
- [Types reference](/docs/reference/golang/api/types.md#streamframe) for the `StreamFrame` type

---

Source: https://surrealdb.com/docs/reference/golang/concepts/transactions

# Transactions

Run interactive transactions with the Go SDK - start one with Begin on a DB or a Session, run queries, CRUD functions and QueryStream in it, read results before you decide, then Commit or Cancel, and know what a transaction cannot do.

An interactive transaction groups statements into one unit that succeeds or fails as a whole. A text transaction puts all its statements in one query (`BEGIN TRANSACTION; ... COMMIT TRANSACTION;`), and the [query builder](/docs/reference/golang/concepts/query-builder.md#building-text-transactions) can build one. An interactive transaction lets your Go code run statements one at a time and read their results. Your code can then decide whether to commit or cancel.

This page shows how to start a transaction and run statements in it. It also lists the limits of a transaction.

Interactive transactions need a WebSocket connection (`ws://` or `wss://`). On an HTTP connection, `Begin` returns `constants.ErrTransactionsNotSupported`.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/db.md#begin"><code>db.Begin(ctx)</code></a></td>
			<td scope="row" data-label="Description">Starts a transaction in the default session</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/session.md#begin"><code>session.Begin(ctx)</code></a></td>
			<td scope="row" data-label="Description">Starts a transaction in a session</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/transaction.md#commit"><code>tx.Commit(ctx)</code></a></td>
			<td scope="row" data-label="Description">Commits the transaction, applying its changes</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/transaction.md#cancel"><code>tx.Cancel(ctx)</code></a></td>
			<td scope="row" data-label="Description">Cancels the transaction, discarding its changes</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/transaction.md#id"><code>tx.ID()</code></a></td>
			<td scope="row" data-label="Description">Returns the UUID of the transaction</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/golang/api/core/transaction.md#isclosed"><code>tx.IsClosed()</code></a></td>
			<td scope="row" data-label="Description">Reports whether the transaction was committed or cancelled</td>
		</tr>
	</tbody>
</table>

## Starting a transaction

Call `.Begin()` on a [`*DB`](/docs/reference/golang/api/core/db.md) or a [`*Session`](/docs/reference/golang/api/core/session.md). The transaction runs as the signed-in user of the session, in the namespace and database of the session:

```go
tx, err := db.Begin(ctx)
if err != nil {
	log.Fatal(err)
}
defer tx.Cancel(ctx)
```

> [!NOTE]
> Call `defer tx.Cancel(ctx)` directly after `.Begin()`, so that `.Cancel()` discards the transaction when a later step fails or returns early. After a commit, `.Cancel()` returns [`constants.ErrTransactionClosed`](/docs/reference/golang/api/errors.md#sentinel-errors) and changes nothing.

## Running statements in a transaction

Every query and CRUD function takes a [`*Transaction`](/docs/reference/golang/api/core/transaction.md) in place of the `*DB`:

```go
tx, err := db.Begin(ctx)
if err != nil {
	log.Fatal(err)
}
defer tx.Cancel(ctx)

if _, err := surrealdb.Create[any](ctx, tx, models.NewRecordID("account", "alice"), map[string]any{
	"balance": 1000,
}); err != nil {
	log.Fatal(err)
}

if _, err := surrealdb.Create[any](ctx, tx, models.NewRecordID("account", "bob"), map[string]any{
	"balance": 500,
}); err != nil {
	log.Fatal(err)
}

if err := tx.Commit(ctx); err != nil {
	log.Fatal(err)
}
```

Other sessions and connections cannot see the changes in a transaction until you commit it.

## Deciding whether to commit

Because each statement returns before the next one runs, your code can read a result and decide what to do. This transfer reads a balance first. When the balance is too low, the code cancels the transaction:

```go
type Account struct {
	ID      *models.RecordID `json:"id,omitempty"`
	Balance int              `json:"balance"`
}

tx, err := db.Begin(ctx)
if err != nil {
	log.Fatal(err)
}
defer tx.Cancel(ctx)

alice, err := surrealdb.Select[Account](ctx, tx, models.NewRecordID("account", "alice"))
if err != nil {
	log.Fatal(err)
}

amount := 100
if alice == nil || alice.Balance < amount {
	fmt.Println("insufficient balance")
	return
}

if _, err := surrealdb.Query[any](ctx, tx, `
	UPDATE account:alice SET balance -= $amount;
	UPDATE account:bob SET balance += $amount;
`, map[string]any{"amount": amount}); err != nil {
	log.Fatal(err)
}

if err := tx.Commit(ctx); err != nil {
	log.Fatal(err)
}
```

When `return` runs, the deferred `.Cancel()` discards the transaction.

## Streaming in a transaction

[`QueryStream`](/docs/reference/golang/concepts/streaming.md) works in a transaction too. When you leave the loop early, the SDK waits for the server to end the cancelled query. This makes sure that a later `.Commit()` or `.Cancel()` comes after the end of that query. The statements that ran before you left the loop stay in the transaction. To discard them, call `.Cancel()` rather than `.Commit()`.

## Transaction limitations

A transaction cannot change the state of its session. A `*Transaction` has none of these methods:

- `.SignIn()`, `.SignUp()`, `.Authenticate()` and `.Invalidate()`
- `.Use()`
- `.Let()` and `.Unset()`

[Live queries](/docs/reference/golang/concepts/live-queries.md) belong to a session, so `Live` and `Kill` do not take a `*Transaction`.

An open transaction is lost when the connection is lost. When the client [reconnects](/docs/reference/golang/concepts/reliable-connections.md), it does not start the transaction again, and later calls on it fail. In that case, retry the whole transaction.

A transaction can fail to commit because another transaction changed the same data. [`surrealdb.IsTransactionConflict`](/docs/reference/golang/api/errors.md#kind-helpers) reports this failure. Running the transaction again usually succeeds.

## Learn more

- [Transaction API reference](/docs/reference/golang/api/core/transaction.md) for complete method signatures
- [Multiple sessions](/docs/reference/golang/concepts/multiple-sessions.md) for transactions in a session
- [Error handling](/docs/reference/golang/concepts/error-handling.md) for transaction errors
- [BEGIN statement](/docs/reference/query-language/statements/begin.md) for text transactions in SurrealQL

---

Source: https://surrealdb.com/docs/reference/golang/concepts/value-types

# Value types

How the Go SDK maps SurrealDB types onto Go values over CBOR - record IDs, tables, NONE and NULL, time.Time and datetimes, time.Duration and durations, sized numbers, decimals and bigdecimals, sets, files, regexes, geometry, and the SurrealDB 4.0 date, time, timestamp and interval kinds over cbor.2 and plain CBOR.

The Go SDK sends values to SurrealDB as CBOR, and decodes the values it receives into the Go types you choose. Most SurrealDB types map onto ordinary Go types, such as `string`, `int64` and `map[string]any`. The others have a type in the `models` package, such as [`models.RecordID`](/docs/reference/golang/api/values/record-id.md) and [`models.PlainDate`](/docs/reference/golang/api/values/temporal.md). This page lists how each type converts, and covers the types that need care.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Type</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/record-id.md"><code>models.RecordID</code></a></td>
			<td scope="row" data-label="Description">A record ID, with a table name and an ID</td>
		</tr>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/table.md"><code>models.Table</code></a></td>
			<td scope="row" data-label="Description">A table name</td>
		</tr>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/datetime.md"><code>models.CustomDateTime</code></a></td>
			<td scope="row" data-label="Description">A datetime, which wraps <code>time.Time</code></td>
		</tr>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/duration.md"><code>models.CustomDuration</code></a></td>
			<td scope="row" data-label="Description">A duration, which wraps <code>time.Duration</code></td>
		</tr>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/temporal.md"><code>models.PlainDate</code>, <code>PlainTime</code>, <code>Timestamp</code>, <code>Interval</code></a></td>
			<td scope="row" data-label="Description">The date, time, timestamp and interval kinds of SurrealDB 4.0</td>
		</tr>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/numbers.md"><code>models.BigDecimal</code>, <code>Float16</code>, <code>DecimalString</code></a></td>
			<td scope="row" data-label="Description">Decimals and the numbers Go has no type for</td>
		</tr>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/uuid.md"><code>models.UUID</code></a></td>
			<td scope="row" data-label="Description">A UUID</td>
		</tr>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/set.md"><code>models.Set</code></a></td>
			<td scope="row" data-label="Description">A set of distinct values</td>
		</tr>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/regex.md"><code>models.Regex</code></a></td>
			<td scope="row" data-label="Description">A regular expression</td>
		</tr>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/file.md"><code>models.File</code></a></td>
			<td scope="row" data-label="Description">A pointer to a file in a bucket</td>
		</tr>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/geometry.md"><code>models.GeometryPoint</code> and the other geometry types</a></td>
			<td scope="row" data-label="Description">GeoJSON geometry values</td>
		</tr>
		<tr>
			<td scope="row" data-label="Type"><a href="/docs/reference/golang/api/values/range.md"><code>models.Range</code></a></td>
			<td scope="row" data-label="Description">A range with included or excluded bounds</td>
		</tr>
	</tbody>
</table>

## How values convert

The first column is what you send. The last column is what a value decodes into when the target is `any`, as it is in a `map[string]any` or a `[]any`. A struct field of a concrete type, such as `Age int`, takes any value that converts to it.

| Go value | SurrealDB type | Decoded into `any` as |
| --- | --- | --- |
| `nil`, a `nil` pointer | `NULL` | `nil` |
| [`models.None`](#none-and-null) | `NONE` | `nil` |
| `bool` | `bool` | `bool` |
| `int`, `int64` | `int` | `uint64` for a value of zero or more, `int64` for a negative one |
| `float64` | `float` | `float64` |
| `string` | `string` | `string` |
| `[]byte` | `bytes` | `[]byte` |
| `[]T`, `[]any` | `array` | `[]any` |
| `map[string]any`, a struct | `object` | `map[string]any` |
| `time.Time`, `models.CustomDateTime` | `datetime`, or `NONE` for a zero time | `models.CustomDateTime` |
| `time.Duration`, `models.CustomDuration` | `duration` | `models.CustomDuration` |
| `models.DecimalString` | `decimal` | `models.DecimalString` |
| `models.UUID` | `uuid` | `models.UUID` |
| `models.RecordID` | `record` | `models.RecordID` |
| `models.Table` | `table` | `models.Table` |
| `models.Set` | `set` | `models.Set` |
| `models.File` | `file` | `models.File` |
| `models.GeometryPoint` and the other geometry types | `geometry` | The same type |
| `models.Range` | `range` | |
| `regexp.Regexp`, `*regexp.Regexp` | Not sent: encoding fails. Use `models.Regex`. | |

The kinds that SurrealDB 4.0 adds, such as sized numbers and dates, are in [SurrealDB 4.0 kinds](#surrealdb-40-kinds). The SDK matches struct fields by their `json` tags, and `omitempty` leaves a field out when it holds its zero value.

## cbor.2 and plain CBOR

The SDK uses one of two versions of the CBOR protocol: cbor.2 with SurrealDB 4.0, and plain CBOR with earlier servers. It offers cbor.2 when it connects. [`db.CBORVersion()`](/docs/reference/golang/api/core/db.md#cborversion) reports which version a connection uses. The two versions differ only for the kinds that SurrealDB 4.0 adds, which plain CBOR cannot carry. Over plain CBOR, the SDK and the server send each of these kinds as the nearest older kind. They cannot send a regex at all.

To keep plain CBOR with a SurrealDB 4.0 server, set `DisableCBORv2` in the [connection configuration](/docs/reference/golang/concepts/connecting-to-surrealdb.md#using-a-custom-connection).

## Record IDs and tables

A [`models.RecordID`](/docs/reference/golang/api/values/record-id.md) holds a table name and an ID. Build one with `models.NewRecordID`, or receive one in a result. The ID can be a string, a number, an array or an object:

```go
import "github.com/surrealdb/surrealdb.go/v2/pkg/models"

id := models.NewRecordID("person", "tobie")
numeric := models.NewRecordID("event", 42)
compound := models.NewRecordID("temperature", []any{"London", 2026})
```

To read a record ID from text such as `"person:tobie"`, use `models.ParseRecordID`. It always makes a string ID, so `"event:42"` becomes `event:⟨42⟩` rather than `event:42`. In a struct, use `*models.RecordID` with `omitempty` for the `id` field, so that you can send the struct without an ID:

```go
type Person struct {
	ID   *models.RecordID `json:"id,omitempty"`
	Name string           `json:"name"`
}
```

A plain `string` given as the target of a CRUD function is always a table name, even when it holds a `:`. See [Targeting records and tables](/docs/reference/golang/concepts/data-manipulation.md#targeting-records-and-tables).

## NONE and NULL

SurrealDB keeps `NONE` and `NULL` apart. `NONE` is a value that does not exist, and `NULL` is a value that exists and is empty. The SDK sends `nil` and a `nil` pointer as `NULL`, and `models.None` as `NONE`. Both decode into `nil`:

```go
_, err := surrealdb.Create[map[string]any](ctx, db, models.NewRecordID("person", "tobie"), map[string]any{
	"nickname": models.None,
	"manager":  nil,
})
```

Here the server does not store `nickname` at all, and it stores `manager` as `NULL`. A field defined as `option<string>` accepts `NONE`, and one defined as `string | null` accepts `NULL`.

The SDK sends a zero `time.Time` as `NONE`, so a struct field of type `time.Time` that you never set leaves the field out. The new `models` types of SurrealDB 4.0 work differently. Their zero value is a real value, such as the date 1970-01-01, rather than `NONE`. For an optional field of one of those types, use a pointer with `omitempty`.

## Datetimes

Send a `time.Time` as it is. The SDK sends it as a SurrealDB `datetime` with its nanoseconds, and a zero `time.Time` as `NONE`:

```go
type Event struct {
	ID        *models.RecordID `json:"id,omitempty"`
	StartedAt time.Time        `json:"started_at"`
}

_, err := surrealdb.Create[Event](ctx, db, "event", Event{StartedAt: time.Now()})
```

A datetime decodes into a `time.Time` field, or into a [`models.CustomDateTime`](/docs/reference/golang/api/values/datetime.md) when the target is `any`. `CustomDateTime` embeds `time.Time`, so it has the same methods. To store `NULL` rather than `NONE` for a missing time, use a `*time.Time` that is `nil`.

## Durations

Send a `time.Duration` as it is. The SDK sends it as a SurrealDB `duration`:

```go
type Job struct {
	ID      *models.RecordID `json:"id,omitempty"`
	Timeout time.Duration    `json:"timeout"`
}

_, err := surrealdb.Create[Job](ctx, db, "job", Job{Timeout: 90 * time.Second})
```

A duration decodes into a `time.Duration` field, or into a [`models.CustomDuration`](/docs/reference/golang/api/values/duration.md) when the target is `any`. Version 1 of the SDK stored a `time.Duration` as an `int` of nanoseconds. A value stored this way also decodes into a `time.Duration` field.

## Numbers and decimals

The SDK sends a Go `int`, `int64` or `float64` as a SurrealDB `int` or `float`. It sends a `uint64` above `math.MaxInt64` as a `u64` over cbor.2, and as a `decimal` over plain CBOR. A SurrealDB `decimal` decodes into a [`models.DecimalString`](/docs/reference/golang/api/values/numbers.md#decimalstring), which keeps its digits as text. The next section and the [Numbers](/docs/reference/golang/api/values/numbers.md) page cover the sized numbers and `bigdecimal` of SurrealDB 4.0.

## SurrealDB 4.0 kinds

SurrealDB 4.0 adds sized numbers, `bigdecimal`, the calendar kinds `date`, `time`, `timestamp` and `interval`, and `regex`. Over cbor.2, each kind keeps its type when you send it and when you receive it. It decodes into `any` as the Go type in the second column. Over plain CBOR, the SDK and the server send the nearest older kind:

| SurrealQL | Go type | Over plain CBOR |
| --- | --- | --- |
| `i8`, `u8`, `i16`, `u16`, `i32`, `u32` | `int8`, `uint8`, `int16`, `uint16`, `int32`, `uint32` | `int` |
| `u64` | `uint64` above `math.MaxInt64` | `decimal` |
| `f16` | [`models.Float16`](/docs/reference/golang/api/values/numbers.md#float16) | `float` |
| `f32` | `float32` | `float` |
| `bigdecimal` | [`models.BigDecimal`](/docs/reference/golang/api/values/numbers.md#bigdecimal) | `decimal` when the value fits one, otherwise its text |
| `date` | [`models.PlainDate`](/docs/reference/golang/api/values/temporal.md#plaindate) | A `datetime` at midnight UTC |
| `time` | [`models.PlainTime`](/docs/reference/golang/api/values/temporal.md#plaintime) | The `duration` since midnight |
| `timestamp` | [`models.Timestamp`](/docs/reference/golang/api/values/temporal.md#timestamp) | A `datetime`, with the wall clock read as UTC |
| `interval` | [`models.Interval`](/docs/reference/golang/api/values/temporal.md#interval) | Its ISO 8601 text |
| `regex` | [`models.Regex`](/docs/reference/golang/api/values/regex.md) | Not sent: encoding fails with `constants.ErrNeedsCBOR2` |

```go
results, err := surrealdb.Query[[]any](ctx, db,
	"RETURN [type::of($level), type::of($score), type::of($due)]",
	map[string]any{
		"level": int8(5),
		"score": float32(1.5),
		"due":   models.MustParsePlainDate("2024-02-29"),
	},
)
fmt.Println((*results)[0].Result)
```

```text title="Output with SurrealDB 4.0"
[i8 f32 date]
```

Against a SurrealDB 3.x server, the same query prints `[int float datetime]`. You can also decode a value of one of these kinds into a Go type other than its own. The value then decodes in the form that plain CBOR carries. For example, a `date` decodes into a `time.Time` as midnight UTC on that date.

When you send a Go `int8`, the server stores it as an `i8`, so a later read into `any` gives an `int8` back. Code that asserts the type of a decoded number, such as `v.(uint64)`, has to allow for the sized types. Decoding into a struct field of a concrete type converts every numeric kind.

## Sets

A SurrealDB `set` holds distinct values in order. To send a set, build a [`models.Set`](/docs/reference/golang/api/values/set.md) with `models.NewSet`. The server sorts it and removes duplicates:

```go
results, err := surrealdb.Query[models.Set](ctx, db, "RETURN $tags", map[string]any{
	"tags": models.NewSet("go", "db", "go"),
})
fmt.Println((*results)[0].Result)
```

```text title="Output"
[db go]
```

A set decodes into `any` as a `models.Set`, so a set that you read and write back stays a set. It also decodes into a slice of a concrete type, such as `[]string`.

## Regular expressions

A [`models.Regex`](/docs/reference/golang/api/values/regex.md) holds the text of a pattern, which the server compiles with the syntax of the Rust `regex` crate:

```go
results, err := surrealdb.Query[bool](ctx, db, "RETURN $name = $pattern", map[string]any{
	"name":    "tobie",
	"pattern": models.Regex{Pattern: "^[a-z]+$"},
})
```

The SDK never compiles a pattern. It also refuses to send a Go `*regexp.Regexp`, because the Go syntax is not the same. A regex needs SurrealDB 4.0.

## Geometry

The SDK has a type for each GeoJSON geometry. [`models.GeometryPoint`](/docs/reference/golang/api/values/geometry.md) holds a longitude and a latitude, and you build the other types from points:

```go
point := models.GeometryPoint{Longitude: -0.118, Latitude: 51.509}

line := models.GeometryLine{
	{Longitude: -0.118, Latitude: 51.509},
	{Longitude: -0.076, Latitude: 51.508},
}
```

## Files

A [`models.File`](/docs/reference/golang/api/values/file.md) points to a file in a bucket, as the SurrealQL value `f"bucket:/key"` does. Build one with `models.NewFile("docs", "/report.pdf")`. Send it as a variable.

## Ranges

A [`models.Range`](/docs/reference/golang/api/values/range.md) holds two bounds, each included or excluded. Use it as the ID of a `models.RecordID` to [select a range of records](/docs/reference/golang/concepts/data-manipulation.md#selecting-a-range-of-records).

## Learn more

- [Values reference](/docs/reference/golang/api/values.md) for each type, its constructors and its methods
- [Data manipulation](/docs/reference/golang/concepts/data-manipulation.md) for using these values in CRUD functions
- [Migrating to Go SDK 2.x](/docs/reference/golang/migrating-to-2x.md#3-check-the-go-values-your-code-sends) for the values that version 2 sends differently
- [SurrealQL data types](/docs/reference/query-language/language-primitives/data-types.md) for the type system of SurrealDB

---

Source: https://surrealdb.com/docs/reference/golang/embedding

# Embedding

The surrealdb.c C FFI library contains Go bindings that can be used to access an embedded SurrealDB instance.

The Go bindings in `surrealdb.c` let a Go program run SurrealDB in-process instead of connecting to a server. This page covers building the C library, setting up CGO, and connecting to an embedded instance.

The bindings are a separate module, `github.com/surrealdb/surrealdb.c.go`, with an API of their own. The Go SDK, `github.com/surrealdb/surrealdb.go/v2`, connects only to a server, and returns `embedded database not enabled` for an embedded URL such as `mem://`.

## Setup

1. Build surrealdb.c and set up CGO
2. Run the command `go get github.com/surrealdb/surrealdb.c.go`
3. Write code to connect to an embedded instance of SurrealDB.

> [!NOTE]
> This module links against a C static library (libsurrealdb_c.a) at compile time. You must build surrealdb.c and set CGO_LDFLAGS to its location before go build or go test will work. Without this, the Go linker cannot find the SurrealDB symbols and the build will fail. See docs/build.md for step-by-step instructions - or use the provided Makefile which handles everything automatically (make build).

The following code shows a simple example that opens up an embedded instance in memory, defines a table and then creates and selects a `person` record that matches the `Person` struct that the output deserializes into.

```go
package main

import (
    "context"
    "fmt"
    "log"

    surrealdb "github.com/surrealdb/surrealdb.c.go"
)

type Person struct {
    ID   surrealdb.RecordID[string] `cbor:"id,omitempty"`
    Name string                     `cbor:"name"`
    Age  int64                      `cbor:"age"`
}

func main() {
    ctx := context.Background()

    db, err := surrealdb.Open(ctx, "mem://")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    db.Use(ctx, "main", "main")
    db.Query(ctx, "DEFINE TABLE person SCHEMALESS", nil)
    db.Query(ctx, "CREATE $rid CONTENT $content", map[string]any{
        "rid":     surrealdb.NewRecordID("person", "alice"),
        "content": Person{Name: "Alice", Age: 30},
    })

    results, _ := surrealdb.Query[Person](ctx, db, "SELECT * FROM person", nil)
    for _, p := range results[0].Values() {
        fmt.Printf("%s: %s (age %d)\n", p.ID, p.Name, p.Age)
    }
}
```

## More information

For more information on the Go bindings used for an embedded SurrealDB instance, see [this page](https://github.com/surrealdb/surrealdb.c.go/tree/main/docs) for the surrealdb.c.go repo.

Pages of particular note are:

* [Storage backends](https://github.com/surrealdb/surrealdb.c.go/blob/main/docs/rocksdb.md): how to use other endpoints like `rocksdb://`.
* [Linking strategy](https://github.com/surrealdb/surrealdb.c.go/blob/main/docs/internals.md)

---

Source: https://surrealdb.com/docs/reference/golang/installation

# Installation

Install the SurrealDB Go SDK 2.x with go get github.com/surrealdb/surrealdb.go/v2, import the surrealdb and models packages, and check the Go and SurrealDB versions it supports.

This page shows how to add the Go SDK to a module and which packages to import. It also lists the versions of Go and SurrealDB that the SDK works with.

## Install the SDK

Add the [SDK](https://pkg.go.dev/github.com/surrealdb/surrealdb.go/v2) to your module with `go get`:

```bash
go get github.com/surrealdb/surrealdb.go/v2
```

The module path ends in `/v2`. Without it, `go get` installs the latest 1.x release, which is a different module. To install a specific release, add the version:

```bash
go get github.com/surrealdb/surrealdb.go/v2@v2.0.1
```

To check which version of the SDK a module uses, run this command:

```bash
go list -m github.com/surrealdb/surrealdb.go/v2
```

## Import the SDK into your project

Import the `surrealdb` package and its `models` package:

```go
import (
	surrealdb "github.com/surrealdb/surrealdb.go/v2"
	"github.com/surrealdb/surrealdb.go/v2/pkg/models"
)
```

The `surrealdb` package contains the client, the query and CRUD functions, the options and the errors. The `models` package contains the value types, such as [`RecordID`](/docs/reference/golang/api/values/record-id.md), [`Table`](/docs/reference/golang/api/values/table.md) and [`PlainDate`](/docs/reference/golang/api/values/temporal.md).

Other packages in the module cover more specialised needs:

| Package | What it contains |
| --- | --- |
| `github.com/surrealdb/surrealdb.go/v2/pkg/connection` | The connection configuration, live query notifications, and the error types that the `surrealdb` package re-exports. |
| `github.com/surrealdb/surrealdb.go/v2/pkg/connection/gorillaws`, `.../gws`, `.../http` | The WebSocket and HTTP connections, for [a custom connection](/docs/reference/golang/concepts/connecting-to-surrealdb.md#using-a-custom-connection). |
| `github.com/surrealdb/surrealdb.go/v2/pkg/constants` | Sentinel errors, such as `ErrSessionClosed`. |
| `github.com/surrealdb/surrealdb.go/v2/contrib/surrealql` | The [query builder](/docs/reference/golang/concepts/query-builder.md). |
| `github.com/surrealdb/surrealdb.go/v2/contrib/rews` | A [reconnecting WebSocket connection](/docs/reference/golang/concepts/reliable-connections.md#using-the-rews-package) with its own retry strategies. |
| `github.com/surrealdb/surrealdb.go/v2/memory` | The [Agent Memory client](/docs/agent-memory/integrations/sdks/go.md). |

The packages under `contrib/` are outside the backward compatibility guarantee of the SDK. Their API can change in a minor release.

## Requirements

- Go `1.24` or later
- SurrealDB `3.3.0` or later, before `5.0.0`. SurrealDB 4.0 is the recommended version. The kinds that it adds, such as sized numbers, dates and regexes, work only with SurrealDB 4.0. See [Value types](/docs/reference/golang/concepts/value-types.md).

The SDK does not check the server version unless you ask it to. To make the connection fail on a server outside the supported range, pass [`WithVersionCheck(true)`](/docs/reference/golang/api/core/db.md#withversioncheck).

## Next steps

- [Getting started](/docs/languages/golang.md) for a complete working example
- [Connecting to SurrealDB](/docs/reference/golang/concepts/connecting-to-surrealdb.md) for connection options and protocols
- [Authentication](/docs/reference/golang/concepts/authentication.md) for signing in and managing tokens
- [Migrating to Go SDK 2.x](/docs/reference/golang/migrating-to-2x.md) for upgrading a project from version 1

---

Source: https://surrealdb.com/docs/reference/golang/migrating-to-2x

# Migrating to Go SDK 2.x

Move a Go project from SDK 1.x to 2.x, which supports SurrealDB 3.3 to 4.x. Covers the /v2 module path, the supported server versions, zero time.Time as NONE, time.Duration as a duration, models.Regex, uint64, cbor.2 and exact Go kinds, CRUD functions that run as queries, and SinceVersionstamp.

Version 2 of the Go SDK supports SurrealDB 4.0. It changes the module path, the supported server versions, and how the SDK sends some Go values to the server. This guide lists each change that can break a project written for version 1, with the 1.x code and the 2.x code that replaces it. The sections are in order of how much code each change usually affects, so work through them from the top.

> [!IMPORTANT]
> Version 1 cannot write a `time.Time` to SurrealDB 4.0. It sends a bare `time.Time` as text, which SurrealDB 4.0 refuses with `CBOR tag 0 (a datetime as text) is not accepted: send tag 12 [seconds, nanos]`. Version 2 works with SurrealDB 3.3.0 and later. If the server is older than 3.3, upgrade it to 3.3 or later first. Then move to version 2 while the server runs 3.3 or a later 3.x release. After that, upgrade the server to 4.0.

## What changed

- The module path is `github.com/surrealdb/surrealdb.go/v2`, so every import changes.
- The SDK supports SurrealDB 3.3.0 and later, before 5.0.0. Version 1 supported 2.1.0 and later.
- The SDK sends a zero `time.Time` as `NONE` and a `time.Duration` as a `duration`, and refuses a `regexp.Regexp`.
- On SurrealDB 4.0 the SDK uses cbor.2. Sized numbers keep their kind when the SDK sends them and when it receives them, and decoding into `any` gives the exact Go type.
- The CRUD functions run SurrealQL through the `query` RPC method, so the text of some errors is different.
- `surrealql.SinceVersionstamp` sends the versionstamp unchanged.

## 1. Install version 2 and update imports

Add the new module:

```bash
go get github.com/surrealdb/surrealdb.go/v2
```

Then change every import of the SDK, including `pkg/...`, `contrib/...` and `memory`, to the `/v2` path:

```go title="1.x"
import (
	surrealdb "github.com/surrealdb/surrealdb.go"
	"github.com/surrealdb/surrealdb.go/pkg/models"
)
```

```go title="2.x"
import (
	surrealdb "github.com/surrealdb/surrealdb.go/v2"
	"github.com/surrealdb/surrealdb.go/v2/pkg/models"
)
```

The package names do not change, so the code that uses them stays as it is. To rewrite the imports in every Go file of a module at once, run this command from the module root:

```bash
perl -pi -e 's#"github\.com/surrealdb/surrealdb\.go(?!/v2)#"github.com/surrealdb/surrealdb.go/v2#g' $(grep -rl --include='*.go' 'github.com/surrealdb/surrealdb.go' .)
```

Then remove the version 1 requirement from `go.mod`:

```bash
go mod tidy
```

Version 2 needs Go 1.24 or later, as the later 1.x releases do.

## 2. Check the server version

Version 2 supports SurrealDB 3.3.0 and later versions before 5.0.0, pre-releases included. SurrealDB 4.0 is the recommended version. With a 3.x server, the kinds that 4.0 adds are not available, and error kinds are less precise.

The SDK does not check the version unless you ask it to. With [`WithVersionCheck(true)`](/docs/reference/golang/api/core/db.md#withversioncheck), connecting to a 2.x, 3.0, 3.1 or 3.2 server now fails with an [`UnsupportedVersionError`](/docs/reference/golang/api/errors.md#unsupportedversionerror):

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

```text title="Error output with SurrealDB 3.2"
SurrealDB server version "3.2.4+20260803.93ab219" is not supported by this SDK (supported: >= 3.3.0, < 5.0.0); to connect anyway, turn the check off with surrealdb.WithVersionCheck(false)
```

`surrealdb.MinimumServerVersion` is now `"3.3.0"`, and [`IsVersionSupported`](/docs/reference/golang/api/core/db.md#isversionsupported) returns `false` for versions before it. Code that compares a version with `MinimumServerVersion` itself, for example in a health check, now refuses servers that version 1 accepted.

## 3. Check the Go values your code sends

Version 2 sends some standard library values as different SurrealDB kinds:

| Go value | 1.x sent | 2.x sends |
| --- | --- | --- |
| A zero `time.Time` | `NULL` | `NONE` |
| A `time.Time` that is not zero | Its text, which SurrealDB 4.0 refuses | A `datetime`, with its nanoseconds |
| `time.Duration` | An `int` of nanoseconds | A `duration` |
| `regexp.Regexp`, `*regexp.Regexp` | An empty object `{}` | An encoding error. Use [`models.Regex`](/docs/reference/golang/api/values/regex.md). |
| A `uint64` above `math.MaxInt64` | An integer that SurrealDB refuses | A `decimal`, or a `u64` on SurrealDB 4.0 |
| A `models.CustomDurationString` that is not a valid duration | A string | An encoding error |

The SDK converts these values wherever they are: in a struct field, a map, a slice, or a variable of [`Query`](/docs/reference/golang/api/core/db.md#query).

Then check the schema for the fields that your code writes these values to:

- A field of `TYPE datetime | null` refuses a zero `time.Time`, because the SDK now sends that value as `NONE`. The error is ``Expected `datetime | null` but found `NONE` ``. Define the field as `option<datetime>`, or send a `nil` `*time.Time` to store `NULL`.
- A field of `TYPE int` that stores a `time.Duration` refuses the new values, with ``Expected `int` but found `1m` ``. A query that compares such a field with an integer also stops matching. Give the field a type that accepts a `duration`, such as `int | duration`. Integers that are already stored still decode into a `time.Duration`.
- Use a `models.Regex` for a regular expression. A `models.Regex` holds the pattern as text. SurrealDB compiles the pattern with the syntax of the Rust `regex` crate, which is close to Go's but not the same.

```go title="1.x"
pattern := regexp.MustCompile(`^[a-z]+$`)
db.Let(ctx, "pattern", pattern)
```

```go title="2.x"
pattern := models.Regex{Pattern: `^[a-z]+$`}
db.Let(ctx, "pattern", pattern)
```

A `models.Regex` needs SurrealDB 4.0. Over plain CBOR, which earlier servers use, it fails to encode. See [Value types](/docs/reference/golang/concepts/value-types.md) for every kind.

## 4. Check values that you read into `any`

On WebSocket and HTTP, the SDK now offers cbor.2, the CBOR dialect of SurrealDB 4.0. The SDK uses cbor.2 when the server accepts it. Over cbor.2:

- The SDK sends `int8`, `uint8`, `int16`, `uint16`, `int32`, `uint32` and `float32` values as the sized numbers `i8` to `u32` and `f32`, and `models.Float16` as `f16`.
- A sized number decodes into `any` as the exact Go type, such as `int8` or `float32`. Version 1 gave a widened `uint64`, `int64` or `float64`. The new kinds of SurrealDB 4.0 decode into `any` as their `models` types, such as `models.PlainDate` and `models.Regex`.

Code that decodes into `any` or `map[string]any` and then asserts the type can stop matching. In this example, the program wrote the `level` field from a Go `int32`. Version 1 stored the value as an `int`, which read back as a `uint64`. Version 2 stores it as an `i32`, which reads back as an `int32`:

```go title="1.x"
level := row["level"].(uint64)
```

```go title="2.x"
level := row["level"].(int32)
```

If you decode into a struct field of a concrete type, such as `Level int`, the SDK converts every numeric kind. This works the same in both versions. It is the simpler fix when you know the shape of the data.

To keep plain CBOR, set `DisableCBORv2` in the [connection configuration](/docs/reference/golang/concepts/connecting-to-surrealdb.md#using-a-custom-connection). [`db.CBORVersion()`](/docs/reference/golang/api/core/db.md#cborversion) reports which version a connection uses. A connection that uses the deprecated `models.CborMarshaler` and `models.CborUnmarshaler` stays on plain CBOR.

## 5. Allow for CRUD functions that run as queries

[`Select`](/docs/reference/golang/api/core/db.md#select), [`Create`](/docs/reference/golang/api/core/db.md#create), [`Update`](/docs/reference/golang/api/core/db.md#update), [`Upsert`](/docs/reference/golang/api/core/db.md#upsert), [`Merge`](/docs/reference/golang/api/core/db.md#merge), [`Patch`](/docs/reference/golang/api/core/db.md#patch), [`Delete`](/docs/reference/golang/api/core/db.md#delete), [`Insert`](/docs/reference/golang/api/core/db.md#insert), [`InsertRelation`](/docs/reference/golang/api/core/db.md#insertrelation), [`Relate`](/docs/reference/golang/api/core/db.md#relate), [`Live`](/docs/reference/golang/api/core/db.md#live) and [`Kill`](/docs/reference/golang/api/core/db.md#kill) now send a SurrealQL statement with the `query` RPC method. In version 1, each of these functions called its own RPC method, such as `select` or `insert_relation`. Results have the same shape, and a failure is still an `*RPCError` that unwraps to a [`*ServerError`](/docs/reference/golang/api/errors.md#servererror).

Two things can be different:

- The text of an error message. Match on the error kind rather than on the message. Use `errors.As` or an `Is*` helper, such as [`surrealdb.IsNotFound`](/docs/reference/golang/api/errors.md#kind-helpers).
- Server settings that limit the `query` method now apply to these functions too.

## 6. Update `SinceVersionstamp` in the query builder

In the [query builder](/docs/reference/golang/concepts/query-builder.md), `ShowChangesForTableQuery.SinceVersionstamp` now sends the versionstamp as it is. Version 1 shifted it right by 16 bits first. Pass a versionstamp exactly as `SHOW CHANGES` returned it:

```go title="2.x"
q := surrealql.ShowChangesForTable("reading").SinceVersionstamp(versionstamp).Limit(10)
```

`SINCE` is inclusive. When you continue from the last change that you received, the server returns that change again.

## 7. Upgrading from a release before 1.8

Releases 1.6 to 1.8 added features that change how a client behaves by default. A project that moves to version 2 from an earlier 1.x release gets them too:

- **A WebSocket client reconnects by itself.** When the connection drops, the client connects again and restores the namespace, database, variables, authentication, sessions and live queries. A request that you send during the reconnect waits until the reconnect finishes or its context ends. It does not fail at once. Pass [`WithReconnect(false)`](/docs/reference/golang/api/core/db.md#withreconnect) for the earlier behaviour. See [Reliable connections](/docs/reference/golang/concepts/reliable-connections.md).
- **Package `spectron` is now `memory`.** Import the Agent Memory client from `github.com/surrealdb/surrealdb.go/v2/memory`.
- **A live query channel closes when the server kills the query.** A notification with the action `KILLED` ends it.
- **New methods and types** for [`Health`](/docs/reference/golang/api/core/db.md#health), [`Refresh`](/docs/reference/golang/api/core/db.md#refresh), [`Revoke`](/docs/reference/golang/api/core/db.md#revoke), [`Reset`](/docs/reference/golang/api/core/db.md#reset), [token renewal](/docs/reference/golang/concepts/authentication.md#automatic-token-renewal), selecting [a range of records](/docs/reference/golang/concepts/data-manipulation.md#selecting-a-range-of-records), the [error kind helpers](/docs/reference/golang/api/errors.md#kind-helpers), and the [`Set`](/docs/reference/golang/api/values/set.md) and [`File`](/docs/reference/golang/api/values/file.md) values.

## Import path mapping

| 1.x import | 2.x import |
| --- | --- |
| `github.com/surrealdb/surrealdb.go` | `github.com/surrealdb/surrealdb.go/v2` |
| `github.com/surrealdb/surrealdb.go/pkg/models` | `github.com/surrealdb/surrealdb.go/v2/pkg/models` |
| `github.com/surrealdb/surrealdb.go/pkg/connection` | `github.com/surrealdb/surrealdb.go/v2/pkg/connection` |
| `github.com/surrealdb/surrealdb.go/pkg/constants` | `github.com/surrealdb/surrealdb.go/v2/pkg/constants` |
| `github.com/surrealdb/surrealdb.go/surrealcbor` | `github.com/surrealdb/surrealdb.go/v2/surrealcbor` |
| `github.com/surrealdb/surrealdb.go/contrib/rews` | `github.com/surrealdb/surrealdb.go/v2/contrib/rews` |
| `github.com/surrealdb/surrealdb.go/contrib/surrealql` | `github.com/surrealdb/surrealdb.go/v2/contrib/surrealql` |
| `github.com/surrealdb/surrealdb.go/memory` | `github.com/surrealdb/surrealdb.go/v2/memory` |

## New in version 2

- The kinds that SurrealDB 4.0 adds: [`models.PlainDate`, `PlainTime`, `Timestamp` and `Interval`](/docs/reference/golang/api/values/temporal.md), [`BigDecimal` and `Float16`](/docs/reference/golang/api/values/numbers.md), and [`Regex`](/docs/reference/golang/api/values/regex.md).
- [`QueryStream`](/docs/reference/golang/concepts/streaming.md), to read the results of a query as the server sends them.
- [`Run` and `RunVersion`](/docs/reference/golang/concepts/executing-queries.md#calling-a-function), [`API`](/docs/reference/golang/concepts/executing-queries.md#calling-a-define-api-endpoint) and [`GQL`](/docs/reference/golang/concepts/executing-queries.md#running-iso-gql).
- [`DB.Import` and `DB.Export`](/docs/reference/golang/concepts/import-and-export.md).
- [`DB.Sessions`, `DB.Fork` and `Session.Fork`](/docs/reference/golang/concepts/multiple-sessions.md#copying-a-session).
- [`PatchWithResult`](/docs/reference/golang/concepts/data-manipulation.md#choosing-what-a-patch-returns), to choose what a patch returns.
- After a reconnect, a live query restarts in the namespace and database where it started.
- The context of each WebSocket request bounds the write of that request.

## Migration checklist

1. Run `go get github.com/surrealdb/surrealdb.go/v2`. Rewrite the imports. Then run `go mod tidy`.
2. Check that the server runs SurrealDB 3.3.0 or later. Upgrade the server to 4.0 after you upgrade the SDK.
3. Find the fields that store a zero `time.Time` or a `time.Duration`. Update their types in the schema.
4. Replace every `regexp.Regexp` that your code sends to the server with a `models.Regex`.
5. Find type assertions on values that your code decodes into `any`. Change them to allow for the sized Go types.
6. Replace checks on error message text with checks on the error kind.
7. Pass versionstamps to `SinceVersionstamp` as `SHOW CHANGES` returns them.
8. Run your tests against SurrealDB 4.0.

## Learn more

- [Go SDK 2.0.0 release notes](https://github.com/surrealdb/surrealdb.go/releases/tag/v2.0.0) for the full list of changes
- [Value types](/docs/reference/golang/concepts/value-types.md) for how each SurrealDB kind maps onto Go
- [Connecting to SurrealDB](/docs/reference/golang/concepts/connecting-to-surrealdb.md) for the connection options
- [Error handling](/docs/reference/golang/concepts/error-handling.md) for matching on error kinds

---

Source: https://surrealdb.com/docs/languages/golang

# Go quickstart

Connect to SurrealDB and run your first queries with the Go SDK 2.x - install github.com/surrealdb/surrealdb.go/v2, connect, sign in, create and select records, and run SurrealQL.

The Go SDK for SurrealDB lets you connect to a database and query it from your application. This guide covers installing the SDK, connecting, signing in, and running your first queries. When you finish, you will have code that connects to SurrealDB, creates records and reads them back.

To follow this guide, you need Go 1.24 or later and SurrealDB 3.3 or later.

## 1. Install the SDK

Add the SDK to your module. Its module path ends in `/v2`:

```bash
go get github.com/surrealdb/surrealdb.go/v2
```

Then import the SDK and its `models` package. The [installation guide](/docs/reference/golang/installation.md) covers the other packages of the module.

```go
import (
	"context"
	"fmt"
	"log"

	surrealdb "github.com/surrealdb/surrealdb.go/v2"
	"github.com/surrealdb/surrealdb.go/v2/pkg/models"
)
```

The `surrealdb` package contains the client, the query functions and the authentication types. The `models` package contains value types such as [`RecordID`](/docs/reference/golang/api/values/record-id.md) and [`Table`](/docs/reference/golang/api/values/table.md), which map to SurrealDB's data model.

## 2. Connect to SurrealDB

Use [`FromEndpointURLString`](/docs/reference/golang/api/core/db.md#fromendpointurlstring) to create a client and connect it to a SurrealDB instance. It takes a `context.Context`, which bounds the connection attempt, and a URL. The scheme of the URL chooses the type of connection:

- **WebSocket** (`ws://`, `wss://`) for long-lived stateful connections, which live queries, sessions and transactions need. A WebSocket client reconnects by itself when the connection drops.
- **HTTP** (`http://`, `https://`) for short-lived stateless connections.

```go
ctx := context.Background()

db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000")
if err != nil {
	log.Fatal(err)
}
defer db.Close(ctx)
```

After you connect, use [`.SignIn()`](/docs/reference/golang/api/core/db.md#signin) to authenticate. Then use [`.Use()`](/docs/reference/golang/api/core/db.md#use) to select the namespace and database to work with. Most operations need both.

```go
_, err = db.SignIn(ctx, surrealdb.Auth{
	Username: "root",
	Password: "secret",
})
if err != nil {
	log.Fatal(err)
}

if err := db.Use(ctx, "main", "main"); err != nil {
	log.Fatal(err)
}
```

`defer db.Close(ctx)` closes the connection when your function returns, as you would close a file in Go.

## 3. Inserting data into SurrealDB

Use the [`Create`](/docs/reference/golang/api/core/db.md#create) function to create records. To let SurrealDB generate an ID, pass the table name as a string. To choose the ID yourself, pass a [`RecordID`](/docs/reference/golang/api/values/record-id.md). The data can be a struct or a map.

```go
type User struct {
	ID    *models.RecordID `json:"id,omitempty"`
	Name  string           `json:"name"`
	Email string           `json:"email"`
	Age   int              `json:"age"`
}

user, err := surrealdb.Create[User](ctx, db, "users", User{
	Name:  "John",
	Email: "john@example.com",
	Age:   32,
})
if err != nil {
	log.Fatal(err)
}
fmt.Printf("%+v\n", user)
```

To create a record with a specific ID, use a `RecordID`:

```go
type Product struct {
	ID       *models.RecordID `json:"id,omitempty"`
	Name     string           `json:"name"`
	Price    float64          `json:"price"`
	Category string           `json:"category"`
}

product, err := surrealdb.Create[Product](ctx, db, models.NewRecordID("products", "apple"), Product{
	Name:     "Apple",
	Price:    1.50,
	Category: "fruit",
})
if err != nil {
	log.Fatal(err)
}
fmt.Printf("%+v\n", product)
```

The Go SDK uses generic functions, such as `surrealdb.Create[User](...)`, rather than methods on `db`. The type parameter tells the SDK which Go type to decode the result into.

## 4. Retrieving data from SurrealDB

### Selecting records

The [`Select`](/docs/reference/golang/api/core/db.md#select) function reads all the records of a [`Table`](/docs/reference/golang/api/values/table.md), or a single record by its [`RecordID`](/docs/reference/golang/api/values/record-id.md). Use a slice as the type parameter for a table, and a single type for a record.

```go
users, err := surrealdb.Select[[]User](ctx, db, models.Table("users"))
if err != nil {
	log.Fatal(err)
}
fmt.Printf("All users: %+v\n", users)

apple, err := surrealdb.Select[Product](ctx, db, models.NewRecordID("products", "apple"))
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Apple: %+v\n", apple)
```

### Running SurrealQL queries

For more advanced queries, use the [`Query`](/docs/reference/golang/api/core/db.md#query) function to run [SurrealQL](/docs/reference/query-language.md) statements directly. Pass values as [parameters](/docs/reference/query-language/language-primitives/parameters.md) rather than writing them into the query.

```go
results, err := surrealdb.Query[[]Product](ctx, db,
	"SELECT name, price FROM products WHERE price < $max_price ORDER BY price",
	map[string]any{"max_price": 5.00},
)
if err != nil {
	log.Fatal(err)
}

for _, qr := range *results {
	fmt.Printf("%+v\n", qr.Result)
}
```

`Query` returns one result for each statement in the query.

## 5. Closing the connection

Close the connection when your application no longer needs it, to release its resources. In Go, the usual way is to `defer` the close directly after you create the connection, as in step 2. If you do not use `defer`, call `.Close()` yourself when you are done:

```go
db.Close(ctx)
```

## Next steps

You have installed the SDK, connected to SurrealDB, created records and read them back. Other features of the SDK include updating and deleting records, authentication, live queries and transactions.

- [Connection management](/docs/reference/golang/concepts/connecting-to-surrealdb.md) - Learn how to manage your database connections, including protocols and configuration.

- [Authentication](/docs/reference/golang/concepts/authentication.md) - Read more about authentication levels and how to integrate them into your application.

- [Data manipulation](/docs/reference/golang/concepts/data-manipulation.md) - Learn how to create, read, update, and delete records using the SDK.

- [API reference](/docs/reference/golang/api/core/db.md) - Complete reference for all functions, methods, types, and errors.

> [!NOTE]
> This guide covers the essentials. For the complete reference to the methods, the API and the concepts, see the [Go SDK reference](/docs/reference/golang.md). To upgrade a project from version 1 of the SDK, see [Migrating to Go SDK 2.x](/docs/reference/golang/migrating-to-2x.md).
