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.
Returns: (*Transaction, error)
Returns ErrTransactionsNotSupported if the connection is not WebSocket.
session.Begin()
Starts a transaction within a specific session.
Returns: (*Transaction, error)
Returns ErrSessionClosed if the session has been detached.
Examples
Properties
.ID()
Returns the transaction's UUID.
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.
Returns: *models.UUID
.IsClosed()
Returns whether the transaction has been committed or canceled.
Returns: bool
Methods
.Commit()
Commits the transaction, making all changes permanent. After calling .Commit(), the transaction cannot be used.
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context 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.
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | Context 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
ErrTransactionClosedandErrTransactionsNotSupported