MySQL duplicate key error causes a shared lock set on the duplicate index record?

瘦欲@ 提交于 2021-02-07 20:52:43

问题


I've read the document of MySQL 14.2.7.6. Locks Set by Different SQL Statements in InnoDB

http://dev.mysql.com/doc/refman/5.0/en/innodb-locks-set.html

My questions:

  1. I don't understand why documentation states:

    If a duplicate-key error occurs, a shared lock on the duplicate index record is set. This use of a shared lock can result in deadlock should there be multiple sessions trying to insert the same row if another session already has an exclusive lock. This can occur if another session deletes the row.

    Why does it set a lock on the row since the INSERT operation has failed. It acquires the lock for what?

  2. Is an Intention shared (IS) lock set when "SELECT ... LOCK IN SHARE MODE" is executing? Is an Intention exclusive (IX) Lock set when "UPDATE, INSERT, DELETE" or "SELECT ... FOR UPDATE" are executing?


回答1:


.1. It requires a lock on the existing entry so that subsequent attempts to insert a duplicate record fail consistently:

-- Transaction A
BEGIN TRANSACTION;
INSERT INTO mytable VALUE(1); -- fails as "duplicate"

-- Transaction B
BEGIN;
DELETE FROM mytable WHERE field = 1; -- must be put on hold, see below

-- Transaction A
-- transaction is still in progress
INSERT INTO mytable VALUE(1); -- must fail to stay consistent with the previous attempt

.2. Yes, and yes:

The intention locking protocol is as follows:

  • Before a transaction can acquire an S lock on a row in table t, it must first acquire an IS or stronger lock on t.
  • Before a transaction can acquire an X lock on a row, it must first acquire an IX lock on t.


来源:https://stackoverflow.com/questions/21111676/mysql-duplicate-key-error-causes-a-shared-lock-set-on-the-duplicate-index-record

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!