Transactions
Transactions guarantee that all operations within a transaction are either executed successfully or none of them are executed. They are useful for maintaining data consistency in more complex operations.
Basic Usage
The simplest way to use transactions looks like this:
You can achieve the same result more elegantly with the transaction()
method:
The transaction()
method can also return values:
Nested Transactions
Nette Database supports nested transactions using SQL savepoints. This means you can start a transaction inside another transaction. Here's a simple example:
Internally, only a single database transaction is used, and nested transactions are simulated using savepoints. This behavior is consistent across all databases and is completely transparent to the developer.
Auto-commit Mode
Auto-commit determines whether each query is automatically executed in a separate transaction. By default, auto-commit is enabled, meaning every query forms a separate transaction.
You can disable auto-commit in the configuration:
Or in the code:
When auto-commit is disabled, a new transaction automatically starts in the following cases:
- When connecting to the database.
- After the previous transaction is completed (commit or rollback).
If you change the auto-commit setting while a transaction is active, the current transaction will be automatically committed to maintain consistency.