Transactions
The Python SDK supports client-side transactions that group multiple operations into a single atomic unit. All operations within a transaction either succeed together when committed or are rolled back entirely when cancelled. Transactions are scoped to a session and execute over a WebSocket connection.
This page covers how to create, execute, commit, cancel, and handle errors within transactions.
Note
API References
| Method | Description |
|---|---|
session.begin_transaction() | Begins a new transaction within the session |
txn.commit() | Commits all operations in the transaction, making changes permanent |
txn.cancel() | Cancels the transaction and rolls back all changes |
Creating a transaction
To create a transaction, first open a session with .new_session() on the connection, then call .begin_transaction() on the session. The returned transaction object provides the same data manipulation methods as the main connection, but all operations are held until the transaction is committed or cancelled.
Executing operations within a transaction
Once a transaction is created, use its methods — such as .query(), .create(), .select(), .update(), and .delete() — to perform operations. These operations are buffered within the transaction scope and are not visible to other connections or sessions until the transaction is committed.
Refer to the SurrealTransaction API reference for the full list of methods available on the transaction object.
Committing a transaction
Calling .commit() makes all operations in the transaction permanent. After committing, the changes become visible to other connections and sessions.
A transaction can only be committed once. After committing, the transaction object should not be reused.
Cancelling a transaction
Calling .cancel() discards all operations in the transaction and rolls back any changes. The database state is restored to what it was before the transaction began.
Handling errors in transactions
Use a try/except block to ensure that a transaction is cancelled if any operation fails. This prevents partial changes from being committed to the database.
The raise at the end re-raises the original exception after cancelling the transaction, so the error is still visible to the caller.
Learn more
SurrealTransaction API reference for transaction method signatures
SurrealSession API reference for session management
Multiple sessions for session setup
Error handling for error recovery patterns