简体   繁体   English

MySQL竞赛条件

[英]MySQL Race Conditions

Does this cause a race condition with MySQL (InnoDB): 这是否会导致与MySQL(InnoDB)发生竞争的情况:

  1. Start Transaction. 开始交易。

  2. Try to get record. 尝试获取记录。

  3. If record doesn't exist, return. 如果记录不存在,则返回。

  4. If record exists, delete it and add a log entry saying that is was deleted. 如果记录存在,请将其删除并添加一条日志条目,指出该条目已被删除。

  5. End Transaction (commit/rollback). 结束交易(提交/回滚)。

Is it possible for another process to start just before the delete step in 2b, detect the presence of the record and then have both processes enter item delete entries into the log? 是否有可能另一个过程刚好在2b中的删除步骤之前开始,检测到记录的存在,然后让两个过程都将项目删除条目输入日志?

Are there any precautions that I need to take? 我需要采取什么预防措施吗?

Thanks. 谢谢。

在第2步中使用“选择更新”。只有一个进程能够锁定该行,从而避免了您描述的情况。

Start Transaction. 开始交易。

Delete record /* using the very same criteria you use for 'try to get record' */ 使用与“尝试获取记录”相同的条件删除记录/ * * /

if response indicates record was indeed deleted, add a log entry. 如果响应指示确实删除了记录,请添加一个日志条目。

End Transaction (commit/rollback). 结束交易(提交/回滚)。

No more race condition. 没有更多的比赛条件。

Journeyman Programmer, I believe, has the correct solution. 我相信Journeyman Programmer拥有正确的解决方案。 Since you've indicated you are using a broken ORM tool (one that will not allow you to query for update) I'd suggest that you move your INSERT into the log table into a trigger on the delete operation so you will avoid the duplicate entry. 既然您已经表明您正在使用损坏的ORM工具(该工具将不允许您查询更新),建议您将INSERT移至日志表中的删除操作触发器中,以免重复条目。

Yes, it's possible for another transaction to check the table after you've read it. 是的,读取后,另一笔交易可能会检查该表。

Worse yet, because of how transactions work, even after you delete the row, any new transactions that start will see the row because you haven't yet committed the delete. 更糟糕的是,由于事务的工作原理,即使您删除了该行,由于您尚未提交删除操作,因此任何开始的新事务都将看到该行。

SELECT ... FOR UPDATE is one way to prevent it. SELECT ... FOR UPDATE是防止它的一种方法。

LOCK TABLE tablename is another. LOCK TABLE tablename是另一个。

Unfortunately, since you're using an ORM, I couldn't say whether it has the ability to do either of these. 不幸的是,由于您使用的是ORM,因此无法确定它是否具有执行这两种功能的能力。

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

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