Skip to content

Statements

CANCEL

Each statement within SurrealDB is run within its own transaction. If a set of changes need to be made together, then groups of statements can be run together as a single transaction, either succeeding as a whole, or failing without leaving any residual data modifications. While a transaction will fail if any of its statements encounters an error, the CANCEL statement can also be used to cancel a transaction manually.

SurrealQL Syntax
CANCEL [ TRANSACTION ];

The following query shows example usage of this statement.

BEGIN TRANSACTION;

-- Setup accounts
CREATE account:one SET balance = 135605.16;
CREATE account:two SET balance = 91031.31;

-- Move money
UPDATE account:one SET balance += 300.00;
UPDATE account:two SET balance -= 300.00;

-- Rollback all changes
CANCEL TRANSACTION;

CANCEL is not used to automatically cancel a transaction based on a condition such as inside an IF..ELSE block. Instead, a THROW statement is used. THROW can be followed by any value, usually a string containing context behind the error.

Warning

CANCEL only takes effect as a top-level statement. Inside a block, such as an IF or FOR body, a bare { } block or a DEFINE FUNCTION body, it is ignored without an error, and the transaction still commits. The same applies to BEGIN and COMMIT. In the following query both records are created.

BEGIN TRANSACTION;

-- Setup accounts
CREATE account:one SET balance = 135605.16;
CREATE account:two SET balance = 200.31;

-- Move money
UPDATE account:one SET balance += 300.00;
UPDATE account:two SET balance -= 300.00;

IF account:two.balance < 0 {
    THROW "Not enough funds";
};

COMMIT TRANSACTION;

Was this page helpful?