ActiveRecord、MySQL 和嵌套事务——行为是什么?

发布于 2024-10-16 18:23:34 字数 309 浏览 3 评论 0原文

Rails 使用 保存点 来实现与 MySQL 的嵌套事务,并且我的据了解,就原子数据更改而言,其语义与实际嵌套事务相同。

  1. 这是真的吗?
  2. 在代码中任意时间调用“save”怎么样?交易仍然保持开放状态直到区块结束,对吗?使用嵌套事务/保存点时行为是否有任何差异?
  3. 还有什么需要注意的吗?
  4. [故意煽动口水战]我应该改用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.

  1. Is this true?
  2. 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?
  3. Anything else to be aware of?
  4. [intentionally inciting flame-war] Should I switch to PostgresSQL?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

牵你的手,一向走下去 2024-10-23 18:23:34
  1. 是的,这是真的,唯一具有真正嵌套事务的数据库是 MS SQL Server

  2. 是的,即使在您可以在任意时间调用 save,但是,如果在嵌套事务内部引发回滚异常,则它不会导致外部事务的全局回滚(另请参阅#3 以了解保存点管理)。

  3. 您可以传递 Model.transaction(:requires_new => true) 来创建子事务,这可能是您期望的行为,否则您将无法控制嵌套事务,因为它不会服从嵌套回滚。此外,人们有时会忘记模型回调全部在 1 个事务中执行,因此回调内的任何事务都是嵌套事务。

  4. 你并没有真正煽动一场口水战,PostgresSQL也没有嵌套事务(它也使用保存点),它们都是很棒的数据库。

  1. Yes this is true, the only DB with true nested transactions is MS SQL Server

  2. 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).

  3. 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.

  4. 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.

幸福%小乖 2024-10-23 18:23:34

据我所知,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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文