19

I need to manage transaction isolation level on a per-transaction basis in a way portable across databases (SQLite, PostgreSQL, MySQL at least).

I know I can do it manually, like that:

User.connection.execute('SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE')

...but I would expect something like:

User.isolation_level( :serializable ) do
  # ...
end
steel
  • 11,883
  • 7
  • 72
  • 109
qertoip
  • 1,870
  • 1
  • 17
  • 29

3 Answers3

39

This functionality is supported by ActiveRecord itself:

MyRecord.transaction(isolation: :read_committed) do
  # do your transaction work
end

It supports the ANSI SQL isolation levels:

  • :read_uncommitted
  • :read_committed
  • :repeatable_read
  • :serializable

This method is available since Rails 4, it was unavailable when the OP asked the question. But for any decently modern Rails application this should be the way to go.

NobodysNightmare
  • 2,992
  • 2
  • 22
  • 33
12

Looks Rails4 would have the feature out of box:

https://github.com/rails/rails/commit/392eeecc11a291e406db927a18b75f41b2658253

Shree
  • 798
  • 5
  • 13
12

There was no gem available so I developed one (MIT): https://github.com/qertoip/transaction_isolation

qertoip
  • 1,870
  • 1
  • 17
  • 29