githubEdit

Transactions

Learn transaction management with bx-orm

A transaction is any discrete unit of work used to pool database queries and statements to execute at once. This helps us to prevent a failed update from leaving the database in a broken state.

To denote a transaction, we wrap it in the transaction{} tag:

transaction{
    // queries go here
}

The transaction will automatically commit (persist) at the end of the transaction block.

Transaction Rollback

A transaction rollback undoes all changes made within the transaction block and prevents them from being persisted to the database. This is useful when an error occurs or business rules are violated.

Automatic Rollback on Error

If an exception occurs within a transaction block, the transaction is automatically rolled back:

try {
    transaction {
        var user = entityNew( "User" );
        user.setUsername( "johndoe" );
        entitySave( user );
        
        // This will throw an exception and trigger automatic rollback
        var invalid = entityLoadByPK( "NonExistentEntity", 1 );
    }
} catch ( any e ) {
    // Transaction has been rolled back, user was not saved
    writeOutput( "Error: #e.message#" );
}

Manual Rollback

You can manually trigger a rollback using transactionRollback():

The alternative syntax action="rollback" is also supported.

Transaction Commit

A transaction commit persists all changes made within the transaction block to the database. By default, transactions automatically commit when the transaction block completes successfully.

Automatic Commit

When a transaction block completes without errors or explicit rollback, it will be automatically committed:

Manual Commit

You can manually commit a transaction using transactionCommit() when you need to persist changes before the end of the block:

The alternative syntax action="commit" is also supported.

circle-exclamation

Named Transactions

Named transactions allow you to commit or rollback specific transactions when dealing with nested transactions:

Transaction Savepoint

Savepoints are not currently supported on ORM transactions.

Last updated

Was this helpful?