ActiveRecord、MySQL 和嵌套事务——行为是什么?
Rails 使用 保存点 来实现与 MySQL 的嵌套事务,并且我的据了解,就原子数据更改而言,其语义与实际嵌套事务相同。
- 这是真的吗?
- 在代码中任意时间调用“save”怎么样?交易仍然保持开放状态直到区块结束,对吗?使用嵌套事务/保存点时行为是否有任何差异?
- 还有什么需要注意的吗?
- [故意煽动口水战]我应该改用PostgresSQL吗?
Rails uses savepoints to achieve nested transactions with MySQL, and to my understanding, the semantics of this are identical to actual nested transactions, in terms of atomic data changes.
- Is this true?
- What about calling "save" at arbitrary times within the code? The transaction still stays open until the end of the block, right? Are there any differences in behavior when using nested transactions/savepoints?
- Anything else to be aware of?
- [intentionally inciting flame-war] Should I switch to PostgresSQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是真的,唯一具有真正嵌套事务的数据库是 MS SQL Server
是的,即使在您可以在任意时间调用 save,但是,如果在嵌套事务内部引发回滚异常,则它不会导致外部事务的全局回滚(另请参阅#3 以了解保存点管理)。
您可以传递 Model.transaction(:requires_new => true) 来创建子事务,这可能是您期望的行为,否则您将无法控制嵌套事务,因为它不会服从嵌套回滚。此外,人们有时会忘记模型回调全部在 1 个事务中执行,因此回调内的任何事务都是嵌套事务。
你并没有真正煽动一场口水战,PostgresSQL也没有嵌套事务(它也使用保存点),它们都是很棒的数据库。
Yes this is true, the only DB with true nested transactions is MS SQL Server
Yes, the transaction stays open even if you call save at arbitrary times, however, if a rollback exception is raised inside the nested transaction then it will not cause a global rollback of the outer transaction (see #3 for savepoint management as well).
You can pass Model.transaction(:requires_new => true) to a create a sub-transaction, this is probably the behavior you are expecting as otherwise you won't have control over the nested transaction as it will not obey nested rollbacks. Also, people sometimes forget that model callbacks are all executed in 1 transaction so any transaction inside of a callback is a nested transaction.
You aren't really inciting a flame-war, PostgresSQL doesn't have nested transactions either (it uses savepoints as well), they are both great databases.
据我所知,Mysql 的嵌套事务依赖于 MySQL 5+ 中的 Savepoints 功能。如果您是 Rails 2.3.2+ 和 Mysql 5+,看起来它应该可以正常工作。
然而,嵌套事务的管理可能会非常混乱。如果您依靠它来清理您正在做的事情并将工作流程分解为更简单的东西(恕我直言),您可能需要考虑您的设计选择。
As far as I know, nested transactions for Mysql rely on the Savepoints feature in MySQL 5+. Looks like it should work correctly if you're Rails 2.3.2+ and Mysql 5+.
However, nested transactions can be very messy to manage. You may want to consider your design choices if you're relying on this to cleanup what you're doing and decompose the work-flow into something simpler (IMHO).