Transaction

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

Creating a Transaction

db.Begin()

Starts a transaction on the default session.

Syntax

tx, err := db.Begin(ctx)

Returns: (*Transaction, error)

Returns ErrTransactionsNotSupported if the connection is not WebSocket.

session.Begin()

Starts a transaction within a specific session.

Syntax

tx, err := session.Begin(ctx)

Returns: (*Transaction, error)

Returns ErrSessionClosed if the session has been detached.

Examples

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

Properties

.ID()

Returns the transaction's UUID.

Syntax

id := tx.ID()

Returns: *models.UUID

.SessionID()

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

.IsClosed()

Returns whether the transaction has been committed or canceled.

Syntax

closed := tx.IsClosed()

Returns: bool

Methods

.Commit()

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

Syntax

err := tx.Commit(ctx)
ParameterTypeDescription
ctx context.ContextContext for the operation.

Returns: error

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

.Cancel()

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)
ParameterTypeDescription
ctx context.ContextContext for the operation.

Returns: error

See Also

  • DB for starting transactions from the main client

  • Session for starting transactions from sessions

  • Transactions for transaction usage patterns

  • Errors for ErrTransactionClosed and ErrTransactionsNotSupported