Saturday, September 22, 2012

Rails 4 - Transaction isolation level


After long time I am writing small post, as now a days not able manage a time or you can say I am just working ;)

TL;DR - In Rails 4, Jon Leighton has added a support for specifying transaction isolation level. This transaction level we can pass when starting transaction(or you can say while calling transaction method)

Note : This blog post is copied from Jon Leighton commits, which he did in a rails repository

Before continuing reading this post, it will be good if you read about Transaction Isolation over here.

Isolation is a property that defines how/when the changes made by one operation become visible to other concurrent operations. Isolation is one of the ACID (Atomicity, Consistency, Isolation, Durability) properties.

Highlevel of Isolation does affect on Concurrency property of ACID, as it require to use locks or multiversion concurrency control.

Anyways here is a documentation which Jon Leighton has added in rails trank.

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:

* http://www.postgresql.org/docs/9.1/static/transaction-iso.html
* https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html

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 (http://bugs.mysql.com/bug.php?id=39170) which means the isolation level gets persisted outside the transaction.
References :
http://en.wikipedia.org/wiki/Isolation_(database_systems)
http://www.postgresql.org/docs/9.1/static/transaction-iso.html
https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html
https://github.com/rails/rails/commit/392eeecc11a291e406db927a18b75f41b2658253