Transactions
Interactive transactions let you group multiple operations into an atomic unit. Unlike text-based transactions (BEGIN TRANSACTION; ... COMMIT; — see the query builder for composing those), interactive transactions allow you to execute statements one at a time, inspect results, and conditionally decide whether to commit or cancel.
Transactions require a WebSocket connection (ws:// or wss://) and SurrealDB v3 or later.
API References
| Method | Description |
|---|---|
db.Begin(ctx) | Starts a transaction on the default session |
session.Begin(ctx) | Starts a transaction within a session |
tx.Commit(ctx) | Commits the transaction, applying all changes |
tx.Cancel(ctx) | Cancels the transaction, discarding all changes |
tx.ID() | Returns the transaction's UUID |
tx.IsClosed() | Returns whether the transaction has been committed or canceled |
Starting a transaction
Call .Begin() on a *DB or *Session to start a transaction. The transaction inherits the authentication and namespace context from the connection or session that started it.
Note
Executing operations within a transaction
Transactions satisfy the sendable constraint, so all generic functions like Query, Select, Create, Update, and Delete accept a *Transaction.
Changes made within a transaction are not visible to other connections or sessions until the transaction is committed.
Conditional commit or cancel
Because interactive transactions let you inspect results between operations, you can decide whether to commit based on runtime conditions.
Transaction limitations
Transactions do not support session state changes. The following operations are not available on a *Transaction:
Live queries (
Live,Kill)
The namespace, database, authentication, and variables are inherited from the *DB or *Session that started the transaction.
Learn more
Transaction API reference for complete method signatures
Multiple sessions for session-scoped transactions
Error handling for transaction error types
SurrealQL transactions for text-based transaction syntax