SurrealDB transactions: default per-statement scope and manual BEGIN, COMMIT and CANCEL for atomic multi-step changes.
Each statement within SurrealDB is run within its own transaction by default. This includes side effects such as defined events.
Manual transactions
If a set of changes need to be made together, then groups of statements can be run together as a single transaction. If all of the statements within a transaction succeed, and the transaction is successful, then all of the data modifications made during the transaction are committed and become a permanent part of the database. If a transaction encounters errors and must be cancelled or rolled back, then any data modification made within the transaction is rolled back, and will not become a permanent part of the database.
Starting a manual transaction
The BEGIN or BEGIN TRANSACTION statement starts a transaction in which multiple statements can be run together.
Starting a transaction
BEGIN[TRANSACTION];
The following query shows example usage of this statement.
Example usage of BEGIN TRANSACTION
-- Create two accounts for bank customers CREATEaccount:oneSETbalance=135605.16; CREATEaccount:twoSETbalance=91031.31;
-- Start a manual database transaction BEGINTRANSACTION;
-- Update the balances of each customer involved in the wire transfer UPDATEaccount:oneSETbalance+=300.00; UPDATEaccount:twoSETbalance-=300.00;
-- Finalise the transaction. This will apply the changes to the database. If there was an error -- during any of the previous steps within the transaction, all changes would be rolled back and -- the database would remain in its initial state. COMMITTRANSACTION;
Committing a manual transaction
The COMMIT statement is used to commit a set of statements within a transaction, ensuring that all data modifications become a permanent part of the database.
Committing a transaction
COMMIT[TRANSACTION];
The following query shows example usage of this statement.
The CANCEL statement can be used to cancel a set of statements within a transaction, reverting or rolling back any data modification made within the transaction as a whole.
Cancelling a transaction
CANCEL[TRANSACTION];
The following query shows example usage of this statement.
While transactions are automatically rolled back if an error occurs in any of its statements, THROW can also be used to explicitly break out of a transaction at any point. THROW can be followed by any value which serves as the error message, usually a string.
UPDATEaccount:oneSETdollars-=$transfer_amount; UPDATEaccount:twoSETdollars+=$transfer_amount; IFaccount:one.dollars<0{ THROW"Insufficient funds, would have $"+<string>account:one.dollars+" after transfer" }; COMMITTRANSACTION; SELECT * FROMaccount;
Output when $transfer_amount set to 150
'An error occurred: Insufficient funds, would have $-50 after transfer'