如何使用ActiveRecord连接设置事务隔离级别?
我需要以跨数据库(至少是 SQLite、PostgreSQL、MySQL)可移植的方式在每个事务的基础上管理事务隔离级别。
我知道我可以手动完成,就像这样:
User.connection.execute('SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE')
...但我期望类似的东西:
User.isolation_level( :serializable ) do
# ...
end
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ActiveRecord 本身支持此功能:
它支持 ANSI SQL 隔离级别:
:read_uncommissed
:read_commissed
:repeatable_read
:serializing
代码>此方法可用自Rails 4以来,当OP提出问题时,它不可用。但对于任何相当现代的 Rails 应用程序来说,这应该是正确的选择。
This functionality is supported by ActiveRecord itself:
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.
没有可用的 gem,所以我开发了一个(麻省理工学院): https://github.com/qertoip/transaction_isolation
There was no gem available so I developed one (MIT): https://github.com/qertoip/transaction_isolation
看起来 Rails4 将具有开箱即用的功能:
https://github.com/rails/rails/commit/392eeecc11a291e406db927a18b75f41b2658253
Looks Rails4 would have the feature out of box:
https://github.com/rails/rails/commit/392eeecc11a291e406db927a18b75f41b2658253