我应该在事务中包含SELECT吗?

编程入门 行业动态 更新时间:2024-10-27 16:25:52
本文介绍了我应该在事务中包含SELECT吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当使用数据库事务对多个更新进行分组时,是否应该在事务中包含SELECTs?例如,让我说:

When using a database transaction to group multiple updates, should I include SELECTs inside the transaction as well? For instance, lets say I:

  • 获取记录
  • 检查该记录的编辑权限,
  • 更新一些记录
  • 更新其他记录
  • get a record
  • check edit permissions for that record, using data from the record
  • update some records
  • update some other records
  • 我应该在获取记录阶段之前开始事务,还是只是在更新周围?

    Should I start the transaction before the "get a record" stage, or just around the updates?

    我使用Postgres / Django transaction.atomic()但我认为这不重要。

    I'm using Postgres/Django transaction.atomic() but I don't think it matters here.

    推荐答案

    p>简短版本:这取决于。

    The short version: "It depends".

    长版本:

    一个读 - 修改 - 写循环,那么不仅必须在事务中,而且必须 SELECT ... FOR UPDATE 您以后打算修改的任何记录。否则,你将面临失去写作的风险,在那里你覆盖了你在读取记录时和写入更新时所做的更新。

    If you're doing a read-modify-write cycle, then not only must it be in a transaction, but you must SELECT ... FOR UPDATE any records you later intend to modify. Otherwise you're going to risk lost writes, where you overwrite an update someone else made between when you read the record and when you wrote the update.

    SERIALIZABLE 事务隔离也可以帮助这个。

    SERIALIZABLE transaction isolation can also help with this.

    你真的需要理解并发和隔离。不幸的是,唯一的简单,容易的只是做X的答案没有理解它是通过锁定所有的表涉及到开始每个事务。大多数人不想这样做。

    You really need to understand concurrency and isolation. Unfortunately the only simple, easy "just do X" answer without understanding it is to begin every transaction by locking all the tables involved. Most people don't want to do that.

    我建议阅读(或两,三或四 - 这是硬的材料) tx隔离文档。尝试使用并发的 psql 会话(多个终端)来创建竞争条件和冲突。

    I suggest a read (or two, or three, or four - it's hard material) of the tx isolation docs. Experiment with concurrent psql sessions (multiple terminals) to create race conditions and conflicts.

    更多推荐

    我应该在事务中包含SELECT吗?

    本文发布于:2023-10-27 18:24:12,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1534171.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:事务   SELECT

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!