Rails postgresql如何将事务隔离级别设置为可序列化
我有一个属于主题模型的评论模型。在 Comment 模型上,我有一个 before_create 回调。
def on_create
Topic.transaction(:require_new => true) do
Topic.connection.execute('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
self.topic.increment!(:comment_counter) if conditions
end
end
问题是我得到一个 ActiveRecord::StatementInvalid: PGError: ERROR: SET TRANSACTION ISOLATION LEVEL Must be call before any query
。
有没有其他方法来设置事务隔离级别?
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 => true) do
Topic.connection.execute('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
self.topic.increment!(:comment_counter) if conditions
end
end
The problem is that I get a ActiveRecord::StatementInvalid: PGError: ERROR: SET TRANSACTION ISOLATION LEVEL must be called before any query
.
Is there another way to set the transaction isolation level?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 Rails 4 开始,
#transaction
提供:isolation
选项:As of Rails 4,
#transaction
provides an:isolation
option:PostgreSQL 要求在事务开始之后、任何 DML(SELECT、INSERT、DELETE 等)语句之前执行 SET TRANSACTION 语句。从文档来看,所有这些事情似乎都必须通过连接对象完成,而不是事务对象。像(未经测试)的东西
我真的希望我是错的。
一种令人讨厌的替代方法是更改 PostgreSQL 服务器上所有事务的默认隔离级别。 (搜索http://www.postgresql.org/docs/current/static/runtime- config-client.html 表示“default_transaction_isolation”。)但这感觉就像用大炮杀死苍蝇一样。
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)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.
您可能会发现 transaction_isolation gem 很有帮助: https://github.com/qertoip/transaction_isolation
You may find transaction_isolation gem helpful: https://github.com/qertoip/transaction_isolation