Transactions
Transactions allow you to execute a group of queries atomically, meaning either all changes are applied or none are. This is essential for maintaining data consistency when performing related operations that must not be partially applied.
API References
| Method | Description |
|---|---|
db.beginTransaction() | Starts a new transaction |
txn.commit() | Commits the transaction, applying all changes |
txn.cancel() | Cancels the transaction, discarding all changes |
Starting a transaction
Call .beginTransaction() on any Surreal or SurrealSession instance to start a new transaction. The returned SurrealTransaction object provides all the same query methods as a regular session, but every operation is executed within the transaction scope.
Executing queries within a transaction
Use the transaction object to execute queries just as you would on the Surreal instance. All operations are held in a pending state until you commit or cancel.
Committing changes
Call .commit() to apply all pending changes to the database. After committing, the transaction cannot be used again.
Cancelling and rolling back
Call .cancel() to discard all pending changes. This is typically done when an error occurs during the transaction. After cancelling, the transaction cannot be used again.
Handling errors in transactions
Always wrap transaction logic in a try-catch block to ensure the transaction is cancelled if any operation fails. This prevents partial changes from being committed.
Best practices
Keep transactions short
Execute transactions quickly to avoid holding resources longer than necessary. Perform any validation or external API calls before starting the transaction.
Do not reuse transactions
Once a transaction is committed or cancelled, create a new one for subsequent operations.
Learn more
SurrealTransaction API reference for the complete transaction interface
Executing queries for the query methods available on transactions
Multiple sessions for running transactions on isolated sessions