Rails postgresql how to set transaction isolation level to serializable

后端 未结 3 689
醉话见心
醉话见心 2021-01-06 18:08

I have a Comment model which belongs_to a Topic model. On the Comment model, I have a before_create callback

def on_create
  Topic.transaction(:require_new =         


        
相关标签:
3条回答
  • 2021-01-06 18:39

    PostgreSQL requires SET TRANSACTION statements to be executed after a transaction starts and before any DML (SELECT, INSERT, DELETE, etc.) statement. From the documentation, it looks like all that stuff will have to be done through the connection object, not the transaction object. Something like (untested)

    Topic.connection.begin_db_transaction
      Topic.connection.execute('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
      # Other things go here. I'd test with another literal SQL statement to make
      # sure it works like I'd hope it does. Then possibly try rewriting in Rails.
    Topic.connection.commit_db_transaction
    

    I really hope I'm wrong about that.

    One distasteful alternative is to change the default isolation level for all transactions on the PostgreSQL server. (Search http://www.postgresql.org/docs/current/static/runtime-config-client.html for "default_transaction_isolation ".) But that feels like using a cannon to kill a fly.

    0 讨论(0)
  • 2021-01-06 18:48

    You may find transaction_isolation gem helpful: https://github.com/qertoip/transaction_isolation

    0 讨论(0)
  • 2021-01-06 18:58

    As of Rails 4, #transaction provides an :isolation option:

    If your database supports setting the isolation level for a transaction, you can set it like so:

    Post.transaction(isolation: :serializable) do
      # ...
    end
    
    0 讨论(0)
提交回复
热议问题