• Start

API Reference

/

Core

Transaction

The Transaction struct represents an interactive SurrealDB transaction that allows executing statements one at a time with commit or cancel control.

The Transaction struct represents an interactive SurrealDB transaction on a WebSocket connection. Unlike text-based transactions, interactive transactions allow executing statements one at a time and conditionally committing or canceling based on results. Transactions require SurrealDB v3+ and a WebSocket connection.

Transaction satisfies the sendable constraint, so all generic functions like Query, Select, Create, etc. accept *Transaction directly. However, transactions do not support session state changes (authentication, namespace selection, variables) or live queries.

Source: transaction.go

Starts a transaction on the default session.

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

Returns: (*Transaction, error)

Returns ErrTransactionsNotSupported if the connection is not WebSocket.

Starts a transaction within a specific session.

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

Returns: (*Transaction, error)

Returns ErrSessionClosed if the session has been detached.

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

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

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

Returns the transaction's UUID.

Syntax
id := tx.ID()

Returns: *models.UUID

Returns the session UUID if the transaction was started within a Session. Returns nil for transactions started on the default session.

Syntax
sessionID := tx.SessionID()

Returns: *models.UUID

Returns whether the transaction has been committed or canceled.

Syntax
closed := tx.IsClosed()

Returns: bool

Commits the transaction, making all changes permanent. After calling .Commit(), the transaction cannot be used.

Syntax
err := tx.Commit(ctx)

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

Returns: error

Returns ErrTransactionClosed if the transaction has already been committed or canceled.

Cancels the transaction, discarding all changes. After calling .Cancel(), the transaction cannot be used.

It is safe to call .Cancel() on an already committed or canceled transaction. It returns ErrTransactionClosed but causes no harm, making it safe for use with defer.

Syntax
err := tx.Cancel(ctx)

Parameter

Type

Description

ctxcontext.Context

Context for the operation.

Returns: error

  • DB for starting transactions from the main client

  • Session for starting transactions from sessions

  • Transactions for transaction usage patterns

  • Errors for ErrTransactionClosed and ErrTransactionsNotSupported

Was this page helpful?