Runs the given block in a database transaction, and returns the result of the block.
Nested transactions support
Most databases don't support true nested transactions. At the time of writing, the only database that supports true nested transactions that we're aware of, is MS-SQL.
In order to get around this problem, transaction will emulate the effect of nested transactions, by using savepoints: dev.mysql.com/doc/refman/5.0/en/savepoint.html Savepoints are supported by MySQL and PostgreSQL. SQLite3 version >= '3.6.8' supports savepoints.
It is safe to call this method if a database transaction is already open, i.e. if transaction is called within another transaction block. In case of a nested call, transaction will behave as follows:
-
The block will be run without doing anything. All database statements that happen within the block are effectively appended to the already open database transaction.
-
However, if
:requires_new
is set, the block will be wrapped in a database savepoint acting as a sub-transaction.
Caveats
MySQL doesn't support DDL transactions. If you perform a DDL operation, then any created savepoints will be automatically released. For example, if you've created a savepoint, then you execute a CREATE TABLE statement, then the savepoint that was created will be automatically released.
This means that, on MySQL, you shouldn't execute DDL operations inside a transaction call that you know might create a savepoint. Otherwise, transaction will raise exceptions when it tries to release the already-automatically-released savepoints:
Model.connection.transaction do # BEGIN Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1 Model.connection.create_table(...) # active_record_1 now automatically released end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error! end
Transaction isolation
If your database supports setting the isolation level for a transaction, you can set it like so:
Post.transaction(isolation: :serializable) do # ... end
Valid isolation levels are:
-
:read_uncommitted
-
:read_committed
-
:repeatable_read
-
:serializable
You should consult the documentation for your database to understand the semantics of these different levels:
An ActiveRecord::TransactionIsolationError
will be raised if:
-
The adapter does not support setting the isolation level
-
You are joining an existing open transaction
-
You are creating a nested (savepoint) transaction
The mysql, mysql2 and postgresql adapters support setting the transaction isolation level. However, support is disabled for mysql versions below 5, because they are affected by a bug which means the isolation level gets persisted outside the transaction.
Please login to continue.