1

I'm using RoR version 4.2.3, and I understand I can set the isolation level of my transactions. However, where do I define setting the isolation level of all transactions? so I only have to define it once and then not worry about it?

I'm using postgreSQL as my database

WhiteTiger
  • 758
  • 1
  • 7
  • 21
  • I believe this is a duplicate of http://stackoverflow.com/questions/29583303/how-to-set-a-ruby-on-rails-4-apps-default-db-isolation-level – phylae Oct 15 '16 at 03:05

2 Answers2

5

There does not seem to be a global isolation option, thus you are left with four options:

  1. Monkeypatch existing transaction implementation, so that it picks your desired isolation level. (Monkeypatching is not desirable)
  2. Use correct isolation level throughout your application.

    SomeModel.transaction(isolation: :read_committed)

  3. Extend ActiveRecord and create your own custom transaction method.

  4. As commented - you may be able to edit the default isolation level in DB configuration. For postgres it's this one

Example code:

#lib/activerecord_extension.rb
module ActiveRecordExtension
  extend ActiveSupport::Concern

  module ClassMethods
    def custom_transaction
      transaction(isolation: :read_committed) do
        yield
      end
    end
  end
end

ActiveRecord::Base.send(:include, ActiveRecordExtension)

Then in your initializers:

#config/initializers/activerecord_extension.rb
require "active_record_extension"

Afterwards you can use:

MyModel.custom_transaction do
  <...>
end

And in the future, this will allow you to change the isolation level in one place.

Magnuss
  • 2,270
  • 19
  • 21
  • 1
    You can also set the default transaction isolation level for the database server. Edit postgresql.conf; look for default_transaction_isolation. This affects all databases under that server. On the one hand, you can't get much more global than that. On the other hand, changing this setting isn't for most people. – Mike Sherrill 'Cat Recall' Dec 24 '15 at 03:36
2

Rails doesn't support setting a global isolation level, but Postgres lets you set one for a session. You can hook into Rails' connection establishment to run a command every time a connection is made, thought the techniques for this all rely on monkeypatching and may be questionable.

Then configure your isolation level with:

SET SESSION CHARACTERISTICS AS TRANSACTION transaction_mode

Though this is interesting, I'd go with something more like Magnuss's answer for maintainability and sanity.

Community
  • 1
  • 1
Kristján
  • 18,165
  • 5
  • 50
  • 62