简体   繁体   English

归因于隔离级别可序列化的SQL事务失败的一般处理

[英]Generalized handling of SQL transaction failures due to isolation level serializable

The PostgreSQL documentation 13.2.3. PostgreSQL文档13.2.3。 Serializable Isolation Level states: 可序列化的隔离级别状态:

It is important that an environment which uses this technique have a generalized way of handling serialization failures (which always return with a SQLSTATE value of '40001'), because it will be very hard to predict exactly which transactions might contribute to the read/write dependencies and need to be rolled back to prevent serialization anomalies. 使用这种技术的环境必须具有通用的方式来处理序列化失败(该错误总是以SQLSTATE值“ 40001”返回),这一点很重要,因为很难准确地预测哪些事务可能会导致读/写。依赖项,需要回滚以防止序列化异常。

Is this as simple as always immediately retrying the transaction until it succeeds? 是否像往常一样立即重试事务直到成功,是否一样简单? Pseudocode: 伪代码:

while (true) {
    try {
        BEGIN TRANSACTION
        ...
        COMMIT TRANSACTION
    }
    catch (SQLSTATE == '40001') {
        continue; // retry
    }
    break; // succeed
}

Is it guaranteed to succeed at some point? 是否可以保证在某个时候成功? Are there situations where it's impossible that this will ever succeed after failing once? 是否有可能在一次失败之后就不可能成功的情况? What else can / should one do? 一个人还能/应该做什么? Does it depend on the scenario? 是否取决于场景? Maybe sometimes earlier query transactions must be repeated too? 有时有时也必须重复先前的查询事务吗? In that case, how is a generalized solution possible? 在那种情况下,怎么可能有一个广义的解决方案?

Are there any open source examples of such a generalized handling mechanism? 是否有任何开放源代码示例说明这种通用处理机制? Or any good resources (books, articles, ...) describing different approaches? 还是描述不同方法的任何好的资源(书籍,文章等)?

Your code sample shows exactly how it should be done. 您的代码示例准确显示了应如何进行。

Serialization failures should happen rarely; 序列化失败应该很少发生; if they don't, something in your database or application design is unsound. 如果不这样做,则数据库或应用程序设计中的某些内容是不正确的。

I guess it it possible to construct a scenario where a transaction can never succeed, but that is no problem in practice. 我猜有可能构建一个交易永远不会成功的场景,但这在实践中没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM