MySQL中一條SQL的加鎖分析


MySQL中一條SQL的加鎖分析

 

id主鍵 + RC

id唯一索引 + RC

id非唯一索引 + RC

id無索引 + RC

id主鍵 + RR

id唯一索引 + RR

id非唯一索引 + RR

id無索引 + RR

Serializable

一條復雜的SQL

死鎖原理與分析

 

SQL1:
select * from t1 where id = 10;(不加鎖。因為MySQL是使用多版本並發控制的,讀不加鎖。)

SQL2:
delete from t1 where id = 10;(需根據多種情況進行分析)

假設t1表上有索引,執行計划一定會選擇使用索引進行過濾 (索引掃描),根據以下組合,來進行分析。

注:在前面八種組合下,也就是RC,RR隔離級別下,SQL1:select操作均不加鎖,采用的是快照讀,因此在下面的討論中就忽略了,主要討論SQL2:delete操作的加鎖。

1. id主鍵 + RC

id主鍵Read Committed 隔離級別,給定SQL:delete from t1 where id = 10; 只需要將主鍵上,id = 10的記錄加上X鎖即可。如下圖所示:

結論:id是主鍵時,此SQL只需要在id=10這條記錄上加X鎖即可。

示例

#准備數據
mysql> create table t1 (id int,name varchar(10));

mysql> alter table t1 add primary key (id);

mysql> insert into t1 values(1,'a'),(4,'c'),(7,'b'),(10,'a'),(20,'d'),(30,'b');

mysql> select * from t1;
+----+------+
| id | name |
+----+------+
|  1 | a    |
|  4 | c    |
|  7 | b    |
| 10 | a    |
| 20 | d    |
| 30 | b    |
+----+------+
6 rows in set (0.00 sec)



會話1

mysql> select @@tx_isolation;
+----------------+
| @@tx_isolation |
+----------------+
| READ-COMMITTED |
+----------------+
1 row in set, 1 warning (0.00 sec)

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> delete from t1 where id=10;
Query OK, 1 row affected (0.00 sec)


會話2

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from t1;
+----+------+
| id | name |
+----+------+
|  1 | a    |
|  4 | c    |
|  7 | b    |
| 10 | a    |
| 20 | d    |
| 30 | b    |
+----+------+
6 rows in set (0.00 sec)

mysql> update t1 set name='a1' where id=10;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> update t1 set name='a1' where id=11;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0  Changed: 0  Warnings: 0

mysql> update t1 set name='a1' where id=7;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

從示例中可以看到會話1執行的delete操作,只對id=10加了X鎖。

 

2. id唯一索引 + RC

id不是主鍵,而是一個Unique的二級索引鍵值。那么在RC隔離級別下,delete from t1 where id = 10; 需要加什么鎖呢?見下圖:

此組合中,id是unique索引,而主鍵是name列。此時,加鎖的情況由於組合一有所不同。由於id是unique索引,因此delete語句會選擇走id列的索引進行where條件的過濾,在找到id=10的記錄后,首先會將unique索引上的id=10索引記錄加上X鎖,同時,會根據讀取到的name列,回主鍵索引(聚簇索引),然后將聚簇索引上的name = ‘d’ 對應的主鍵索引項加X鎖。

為什么聚簇索引上的記錄也要加鎖?試想一下,如果並發的一個SQL,是通過主鍵索引來更新:update t1 set id = 100 where name = 'd';此時,如果delete語句沒有將主鍵索引上的記錄加鎖,那么並發的update就會感知不到delete語句的存在,違背了同一記錄上的更新/刪除需要串行執行的約束。

結論:若id列是unique列,其上有unique索引。那么SQL需要加兩個X鎖,一個對應於id unique索引上的id = 10的記錄,另一把鎖對應於聚簇索引上的[name=’d’,id=10]的記錄。

示例

准備數據
mysql> create table t1 (id int,name varchar(10));
Query OK, 0 rows affected (0.06 sec)

mysql> ALTER TABLE test.t1 ADD UNIQUE INDEX idx_id (id);
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE test.t1 ADD PRIMARY KEY (name);
Query OK, 0 rows affected (0.11 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> insert into t1 values(1,'f'),(2,'zz'),(3,'b'),(5,'a'),(6,'c'),(10,'d');
Query OK, 6 rows affected (0.01 sec)
Records: 6  Duplicates: 0  Warnings: 0


會話1

mysql> begin;
Query OK, 0 rows affected (0.01 sec)

mysql> delete from t1 where id=10;
Query OK, 1 row affected (0.00 sec)



會話2
mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from t1;
+------+------+
| id   | name |
+------+------+
|    1 | f    |
|    2 | zz   |
|    3 | b    |
|    5 | a    |
|    6 | c    |
|   10 | d    |
+------+------+
6 rows in set (0.00 sec)

mysql> update t1 set id =100 where name='d';
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> update t1 set id =100 where name='c';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update t1 set id =101 where name='a';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

 

3. id非唯一索引 + RC

id列是一個普通索引。假設delete from t1 where id = 10; 語句,仍舊選擇id列上的索引進行過濾where條件,那么此時會持有哪些鎖?同樣見下圖:

根據此圖,可以看到,首先,id列索引上,滿足id = 10查詢條件的記錄,均已加鎖。同時,這些記錄對應的主鍵索引上的記錄也都加上了鎖。與組合二唯一的區別在於,組合二最多只有一個滿足等值查詢的記錄,而組合三會將所有滿足查詢條件的記錄都加鎖。

結論:若id列上有非唯一索引,那么對應的所有滿足SQL查詢條件的記錄,都會被加鎖。同時,這些記錄在主鍵索引上的記錄,也會被加鎖。

示例

准備數據
mysql> create table t1 (id int,name varchar(10));

mysql> ALTER TABLE test.t1 ADD PRIMARY KEY (name);

mysql> alter table t1 add index idx_id (id);

mysql> insert into t1 values(2,'zz'),(6,'c'),(10,'b'),(10,'d'),(11,'f'),(15,'a');


會話1

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> delete from t1 where id=10;
Query OK, 2 rows affected (0.00 sec)


會話2

mysql> select * from t1;
+------+------+
| id   | name |
+------+------+
|    2 | zz   |
|    6 | c    |
|   10 | b    |
|   10 | d    |
|   11 | f    |
|   15 | a    |
+------+------+
6 rows in set (0.00 sec)

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> update t1 set id=11 where name='b';
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> update t1 set id=11 where name='d';
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> update t1 set id=11 where name='f';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

mysql> update t1 set id=11 where name='c';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

 

4. id無索引 + RC

id列上沒有索引,where id = 10;這個過濾條件,沒法通過索引進行過濾,那么只能走全表掃描做過濾。
對應於這個組合,SQL會加什么鎖?或者是換句話說,全表掃描時,會加什么鎖?這個答案也有很多:有人說會在表上加X鎖;有人說會將聚簇索引上,選擇出來的id = 10;的記錄加上X鎖。那么實際情況呢?請看下圖:

由於id列上沒有索引,因此只能走聚簇索引,進行全部掃描。從圖中可以看到,滿足刪除條件的記錄有兩條,但是,聚簇索引上所有的記錄,都被加上了X鎖。無論記錄是否滿足條件,全部被加上X鎖。既不是加表鎖,也不是在滿足條件的記錄上加行鎖。

為什么不是只在滿足條件的記錄上加鎖呢?這是由於MySQL的實現決定的。如果一個條件無法通過索引快速過濾,那么存儲引擎層面就會將所有記錄加鎖后返回,然后由MySQL Server層進行過濾。因此也就把所有的記錄,都鎖上了。

注:在實際的實現中,MySQL有一些改進,在MySQL Server過濾條件,發現不滿足后,會調用unlock_row方法,把不滿足條件的記錄放鎖 (違背了2PL的約束)。這樣做,保證了最后只會持有滿足條件記錄上的鎖,但是每條記錄的加鎖操作還是不能省略的。

結論:若id列上沒有索引,SQL會走聚簇索引的全掃描進行過濾,由於過濾是由MySQL Server層面進行的。因此每條記錄,無論是否滿足條件,都會被加上X鎖。但是,為了效率考量,MySQL做了優化,對於不滿足條件的記錄,會在判斷后放鎖,最終持有的,是滿足條件的記錄上的鎖,但是不滿足條件的記錄上的加鎖/放鎖動作不會省略。同時,優化也違背了2PL的約束。

示例

准備數據
mysql> create table t1 (id int,name varchar(10));

mysql> ALTER TABLE test.t1 ADD PRIMARY KEY (name);

mysql> insert into t1 values(5,'a'),(3,'b'),(10,'d'),(2,'f'),(10,'g'),(9,'zz');


會話1
mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> delete from t1 where id=10;
Query OK, 2 rows affected (0.00 sec)


會話2
mysql> select * from t1;
+------+------+
| id   | name |
+------+------+
|    5 | a    |
|    3 | b    |
|   10 | d    |
|    2 | f    |
|   10 | g    |
|    9 | zz   |
+------+------+
6 rows in set (0.00 sec)

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> update t1 set id=6 where name='a';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update t1 set id=6 where name='b';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update t1 set id=6 where name='d';
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql> update t1 set id=6 where name='f';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update t1 set id=6 where name='g';
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> update t1 set id=6 where name='zz';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update t1 set id=6 where name='zzf';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0  Changed: 0  Warnings: 0


實驗結果與推倒的結論不一致,

實驗結果看出只鎖住了id=10的兩行。

 

5. id主鍵 + RR

id列是主鍵列,Repeatable Read隔離級別,針對delete from t1 where id = 10; 這條SQL,加鎖與組合一:"id主鍵 + RC"一致。

示例:

mysql> create table t1 (id int,name varchar(10));

mysql> alter table t1 add primary key (id);

mysql> insert into t1 values(1,'a'),(4,'c'),(7,'b'),(10,'a'),(20,'d'),(30,'b');

mysql> select * from t1;
+----+------+
| id | name |
+----+------+
|  1 | a    |
|  4 | c    |
|  7 | b    |
| 10 | a    |
| 20 | d    |
| 30 | b    |
+----+------+
6 rows in set (0.00 sec)

mysql> select @@tx_isolation;
+-----------------+
| @@tx_isolation  |
+-----------------+
| REPEATABLE-READ |
+-----------------+
1 row in set, 1 warning (0.00 sec)


會話1

mysql> begin;
Query OK, 0 rows affected (0.01 sec)

mysql> delete from t1 where id=10;
Query OK, 1 row affected (0.00 sec)



會話2

mysql> select * from t1;
+----+------+
| id | name |
+----+------+
|  1 | a    |
|  4 | c    |
|  7 | b    |
| 10 | a    |
| 20 | d    |
| 30 | b    |
+----+------+
6 rows in set (0.00 sec)

mysql> update t1 set name='a1' where id=10;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> update t1 set name='a1' where id=11;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0  Changed: 0  Warnings: 0

mysql> update t1 set name='a1' where id=7;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

 

6. id唯一索引 + RR

id唯一索引 + RR的加鎖與id唯一索引,RC一致。兩個X鎖,id唯一索引滿足條件的記錄上一個,對應的聚簇索引上的記錄一個。

示例:

准備數據
mysql> create table t1 (id int,name varchar(10));

mysql> ALTER TABLE test.t1 ADD UNIQUE INDEX idx_id (id);

mysql> ALTER TABLE test.t1 ADD PRIMARY KEY (name);

mysql> insert into t1 values(1,'f'),(2,'zz'),(3,'b'),(5,'a'),(6,'c'),(10,'d');


會話1

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> delete from t1 where id=10;
Query OK, 1 row affected (0.01 sec)


會話2

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from t1;
+------+------+
| id   | name |
+------+------+
|    1 | f    |
|    2 | zz   |
|    3 | b    |
|    5 | a    |
|    6 | c    |
|   10 | d    |
+------+------+
6 rows in set (0.00 sec)

mysql> update t1 set id =100 where name='d';
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> update t1 set id =100 where name='c';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update t1 set id =101 where name='a';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

 

7. id非唯一索引 + RR

在Repeatable Read隔離級別,id上有一個非唯一索引,執行delete from t1 where id = 10; 假設選擇id列上的索引進行條件過濾,最后的加鎖行為,是怎么樣的呢?同樣看下面這幅圖:

此圖,相對於組合三:[id列上非唯一鎖,Read Committed]看似相同,其實卻有很大的區別。最大的區別在於,這幅圖中多了一個GAP鎖,而且GAP鎖看起來也不是加在記錄上的,倒像是加載兩條記錄之間的位置,GAP鎖有何用?

其實這個多出來的GAP鎖,就是RR隔離級別,相對於RC隔離級別,不會出現幻讀的關鍵。確實,GAP鎖鎖住的位置,也不是記錄本身,而是兩條記錄之間的GAP。所謂幻讀,就是同一個事務,連續做兩次當前讀 (例如:select * from t1 where id = 10 for update;),那么這兩次當前讀返回的是完全相同的記錄 (記錄數量一致,記錄本身也一致),第二次的當前讀,不會比第一次返回更多的記錄 (幻象)。

如何保證兩次當前讀返回一致的記錄,那就需要在第一次當前讀與第二次當前讀之間,其他的事務不會插入新的滿足條件的記錄並提交。為了實現這個功能,GAP鎖應運而生。

如圖中所示,有哪些位置可以插入新的滿足條件的項 (id = 10),考慮到B+樹索引的有序性,滿足條件的項一定是連續存放的。記錄[6,c]之前,不會插入id=10的記錄;[6,c]與[10,b]間可以插入[10, aa];[10,b]與[10,d]間,可以插入新的[10,bb],[10,c]等;[10,d]與[11,f]間可以插入滿足條件的[10,e],[10,z]等;而[11,f]之后也不會插入滿足條件的記錄。因此,為了保證[6,c]與[10,b]間,[10,b]與[10,d]間,[10,d]與[11,f]不會插入新的滿足條件的記錄,MySQL選擇了用GAP鎖,將這三個GAP給鎖起來。

Insert操作,如insert [10,aa],首先會定位到[6,c]與[10,b]間,然后在插入前,會檢查這個GAP是否已經被鎖上,如果被鎖上,則Insert不能插入記錄。因此,通過第一遍的當前讀,不僅將滿足條件的記錄鎖上 (X鎖),與組合三類似。同時還是增加3把GAP鎖,將可能插入滿足條件記錄的3個GAP給鎖上,保證后續的Insert不能插入新的id=10的記錄,也就杜絕了同一事務的第二次當前讀,出現幻象的情況。

既然防止幻讀,需要靠GAP鎖的保護,為什么組合五、組合六,也是RR隔離級別,卻不需要加GAP鎖呢?

GAP鎖的目的,是為了防止同一事務的兩次當前讀,出現幻讀的情況。而組合五,id是主鍵;組合六,id是unique鍵,都能夠保證唯一性。一個等值查詢,最多只能返回一條記錄,而且新的相同取值的記錄,一定不會在新插入進來,因此也就避免了GAP鎖的使用。

其實,針對此問題,還有一個更深入的問題:如果組合五、組合六下,針對SQL:select * from t1 where id = 10 for update; 第一次查詢,沒有找到滿足查詢條件的記錄,那么GAP鎖是否還能夠省略?


結論:Repeatable Read隔離級別下,id列上有一個非唯一索引,對應SQL:delete from t1 where id = 10; 首先,通過id索引定位到第一條滿足查詢條件的記錄,加記錄上的X鎖,加GAP上的GAP鎖,然后加主鍵聚簇索引上的記錄X鎖,然后返回;然后讀取下一條,重復進行。直至進行到第一條不滿足條件的記錄[11,f],此時,不需要加記錄X鎖,但是仍舊需要加GAP鎖,最后返回結束。

示例

准備數據
mysql> create table t1 (id int,name varchar(10));

mysql> ALTER TABLE test.t1 ADD PRIMARY KEY (name);

mysql> alter table t1 add index idx_id (id);

mysql> insert into t1 values(2,'zz'),(6,'c'),(10,'b'),(10,'d'),(11,'f'),(15,'a');


會話1

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> delete from t1 where id=10;
Query OK, 2 rows affected (0.00 sec)


會話2

mysql> select * from t1;
+------+------+
| id   | name |
+------+------+
|    2 | zz   |
|    6 | c    |
|   10 | b    |
|   10 | d    |
|   11 | f    |
|   15 | a    |
+------+------+
6 rows in set (0.00 sec)

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> insert into t1 values(6,'aa');
Query OK, 1 row affected (0.00 sec)
mysql> insert into t1 values(6,'bb');
Query OK, 1 row affected (0.01 sec)

mysql> insert into t1 values(6,'cc');
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql> insert into t1 values(7,'cc');
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql> insert into t1 values(8,'cc');
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql> insert into t1 values(9,'cc');
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql> insert into t1 values(10,'cc');
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql> insert into t1 values(11,'cc');
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> insert into t1 values(11,'ff');
Query OK, 1 row affected (0.00 sec)
mysql> insert into t1 values(11,'g');
Query OK, 1 row affected (0.00 sec)

 

8. id無索引 + RR

Repeatable Read隔離級別下,id列上沒有索引。此時SQL:delete from t1 where id = 10; 只能進行全表掃描。最終的加鎖情況,如下圖所示:

如圖,這是一個很恐怖的現象。首先,聚簇索引上的所有記錄,都被加上了X鎖。其次,聚簇索引每條記錄間的間隙(GAP),也同時被加上了GAP鎖。這個示例表,只有6條記錄,一共需要6個記錄鎖,7個GAP鎖。試想,如果表上有1000萬條記錄呢?

在這種情況下,這個表上,除了不加鎖的快照度,其他任何加鎖的並發SQL,均不能執行,不能更新,不能刪除,不能插入,全表被鎖死。

當然,跟id無索引, Read Committed類似,這個情況下,MySQL也做了一些優化,就是所謂的semi-consistent read

semi-consistent read開啟的情況下,對於不滿足查詢條件的記錄,MySQL會提前放鎖。

針對上面的這個用例,就是除了記錄[d,10],[g,10]之外,所有的記錄鎖都會被釋放,同時不加GAP鎖。

semi-consistent read如何觸發:1)read committed隔離級別;2)Repeatable Read隔離級別,同時設置了 innodb_locks_unsafe_for_binlog 參數。
更詳細的關於semi-consistent read的介紹,可參考博客:MySQL+InnoDB semi-consitent read原理及實現分析 。

結論:在Repeatable Read隔離級別下,如果進行全表掃描的當前讀,那么會鎖上表中的所有記錄,同時會鎖上聚簇索引內的所有GAP,杜絕所有的並發 更新/刪除/插入 操作。當然,也可以通過觸發semi-consistent read,來緩解加鎖開銷與並發影響,但是semi-consistent read本身也會帶來其他問題,不建議使用。

示例

准備數據
mysql> create table t1 (id int,name varchar(10));

mysql> ALTER TABLE test.t1 ADD PRIMARY KEY (name);

mysql> insert into t1 values(5,'a'),(3,'b'),(10,'d'),(2,'f'),(10,'g'),(9,'zz');


會話1
mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> delete from t1 where id=10;
Query OK, 2 rows affected (0.00 sec)


會話2
mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from t1;
+------+------+
| id   | name |
+------+------+
|    5 | a    |
|    3 | b    |
|   10 | d    |
|    2 | f    |
|   10 | g    |
|    9 | zz   |
+------+------+
6 rows in set (0.00 sec)

mysql> insert into t1 values(1,'j');
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql> insert into t1 values(2,'j');
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql> insert into t1 values(100,'j');
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

 

9. Serializable

Serializable隔離級別。對於SQL2:delete from t1 where id = 10; 來說,Serializable隔離級別與Repeatable Read隔離級別完全一致,因此不做介紹。

Serializable隔離級別,影響的是SQL1:select * from t1 where id = 10; 這條SQL,在RC,RR隔離級別下,都是快照讀,不加鎖。但是在Serializable隔離級別,SQL1會加讀鎖,也就是說快照讀不復存在,MVCC並發控制降級為Lock-Based CC。

結論:在MySQL/InnoDB中,所謂的讀不加鎖,並不適用於所有的情況,而是隔離級別相關的。Serializable隔離級別,讀不加鎖就不再成立,所有的讀操作,都是當前讀。

10. 一條復雜的SQL

再來看一個稍微復雜點的SQL,用於說明MySQL加鎖的另外一個邏輯。SQL用例如下:

如圖中的SQL,會加什么鎖?假定在Repeatable Read隔離級別下 ,同時,假設SQL走的是idx_t1_pu索引。

在詳細分析這條SQL的加鎖情況前,還需要有一個知識儲備,那就是一個SQL中的where條件如何拆分?具體的介紹,建議閱讀文章:SQL中的where條件,在數據庫中提取與應用淺析 。分析結果:

  • Index key:pubtime > 1 and puptime < 20。此條件,用於確定SQL在idx_t1_pu索引上的查詢范圍。

  • Index Filter:userid = 'hdc' 。此條件,可以在idx_t1_pu索引上進行過濾,但不屬於Index Key。

  • Table Filter:comment is not NULL。此條件,在idx_t1_pu索引上無法過濾,只能在聚簇索引上過濾。

在分析出SQL where條件的構成之后,再來看看這條SQL的加鎖情況 (RR隔離級別),如下圖所示:

從圖中可以看出,在Repeatable Read隔離級別下,由Index Key所確定的范圍,被加上了GAP鎖;Index Filter鎖給定的條件 (userid = ‘hdc’)何時過濾,視MySQL的版本而定,在MySQL 5.6版本之前,不支持Index Condition Pushdown(ICP),因此Index Filter在MySQL Server層過濾,在5.6后支持了Index Condition Pushdown,則在index上過濾。若不支持ICP,不滿足Index Filter的記錄,也需要加上記錄X鎖,若支持ICP,則不滿足Index Filter的記錄,無需加記錄X鎖 (圖中,用紅色箭頭標出的X鎖,是否要加,視是否支持ICP而定);而Table Filter對應的過濾條件,則在聚簇索引中讀取后,在MySQL Server層面過濾,因此聚簇索引上也需要X鎖。最后,選取出了一條滿足條件的記錄[8,hdc,d,5,good],但是加鎖的數量,要遠遠大於滿足條件的記錄數量。

結論:Repeatable Read隔離級別下,針對一個復雜的SQL,首先需要提取其where條件。Index Key確定的范圍,需要加上GAP鎖;Index Filter過濾條件,視MySQL版本是否支持ICP,若支持ICP,則不滿足Index Filter的記錄,不加X鎖,否則需要X鎖;Table Filter過濾條件,無論是否滿足,都需要加X鎖。

示例:

准備數據
mysql> create table t1(id int,userid varchar(10),blogid varchar(10),pubtime int,comment varchar(10));
mysql> alter table t1 add index idx_t1_pu (pubtime,userid);
mysql> alter table t1 add primary key (id);

mysql> insert into t1 values(1,'hdc','a',10,null),(4,'yyy','b',3,null),(6,'hdc','c',100,null),(8,'hdc','d',5,'good'),(10,'hdc','e',1,null),(100,'bbb','f',20,null);

mysql> select * from t1;
+-----+--------+--------+---------+---------+
| id  | userid | blogid | pubtime | comment |
+-----+--------+--------+---------+---------+
|   1 | hdc    | a      |      10 | NULL    |
|   4 | yyy    | b      |       3 | NULL    |
|   6 | hdc    | c      |     100 | NULL    |
|   8 | hdc    | d      |       5 | good    |
|  10 | hdc    | e      |       1 | NULL    |
| 100 | bbb    | f      |      20 | NULL    |
+-----+--------+--------+---------+---------+
6 rows in set (0.00 sec)


會話1

mysql> begin;
Query OK, 0 rows affected (0.00 sec)


mysql>  select * from t1 force index (idx_t1_pu) where pubtime > 1 and pubtime < 20 and userid = 'hdc' and comment is not null for update;
+----+--------+--------+---------+---------+
| id | userid | blogid | pubtime | comment |
+----+--------+--------+---------+---------+
|  8 | hdc    | d      |       5 | good    |
+----+--------+--------+---------+---------+
1 row in set (0.00 sec)

會話2
mysql> delete from t1 where pubtime > 1 and pubtime < 20 and userid = 'hdc' and comment is not null;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> delete from t1 where pubtime=1;
Query OK, 1 row affected (0.01 sec)

mysql> delete from t1 where pubtime=3;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> delete from t1 where pubtime=5;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> delete from t1 where pubtime=10;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> delete from t1 where pubtime=20;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

mysql> delete from t1 where pubtime=100;
Query OK, 1 row affected (0.00 sec)

 

11. 死鎖原理與分析

下面,來看看兩個死鎖的例子

兩個Session的兩條SQL產生死鎖

每個事務執行兩條SQL,分別持有了一把鎖,然后加另一把鎖,產生死鎖。

示例

 create table t1 (id int,name varchar(10));
 alter table t1 add primary key (id);
 alter table t1 add index idx_name (name);
 insert into t1 values(1,'aaa'),(2,'ccc'),(3,'aaa'),(4,'bbb'),(5,'ccc'),(6,'zzz');


會話1

mysql> begin;
Query OK, 0 rows affected (0.01 sec)

mysql> select * from t1 where id=1 for update;
+----+------+
| id | name |
+----+------+
|  1 | aaa  |
+----+------+
1 row in set (0.00 sec)

mysql> update t1 set name='qqq' where id=5;
ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction


會話2
mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> delete from t1 where id=5;
Query OK, 1 row affected (0.00 sec)

mysql> delete from t1 where id=1;
Query OK, 1 row affected (0.03 sec)



error日志

2018-09-07T08:55:27.931528Z 17 [Note] InnoDB: *** WE ROLL BACK TRANSACTION (1)

2018-09-07T08:59:43.321054Z 17 [Note] InnoDB: Transactions deadlock detected, dumping detailed information.
2018-09-07T08:59:43.321129Z 17 [Note] InnoDB: 
*** (1) TRANSACTION:

TRANSACTION 448141, ACTIVE 32 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 3 lock struct(s), heap size 1136, 2 row lock(s)
MySQL thread id 16, OS thread handle 139708911650560, query id 238 localhost root updating
update t1 set name='qqq' where id=5
2018-09-07T08:59:43.321178Z 17 [Note] InnoDB: *** (1) WAITING FOR THIS LOCK TO BE GRANTED:

RECORD LOCKS space id 574 page no 3 n bits 80 index PRIMARY of table `test`.`t1` trx id 448141 lock_mode X locks rec but not gap waiting
Record lock, heap no 6 PHYSICAL RECORD: n_fields 4; compact format; info bits 32
 0: len 4; hex 80000005; asc     ;;
 1: len 6; hex 00000006d68e; asc       ;;
 2: len 7; hex 300000000606cd; asc 0      ;;
 3: len 3; hex 636363; asc ccc;;

2018-09-07T08:59:43.321659Z 17 [Note] InnoDB: *** (2) TRANSACTION:

TRANSACTION 448142, ACTIVE 17 sec starting index read
mysql tables in use 1, locked 1
3 lock struct(s), heap size 1136, 2 row lock(s), undo log entries 1
MySQL thread id 17, OS thread handle 139708912715520, query id 239 localhost root updating
delete from t1 where id=1
2018-09-07T08:59:43.321700Z 17 [Note] InnoDB: *** (2) HOLDS THE LOCK(S):

RECORD LOCKS space id 574 page no 3 n bits 80 index PRIMARY of table `test`.`t1` trx id 448142 lock_mode X locks rec but not gap
Record lock, heap no 6 PHYSICAL RECORD: n_fields 4; compact format; info bits 32
 0: len 4; hex 80000005; asc     ;;
 1: len 6; hex 00000006d68e; asc       ;;
 2: len 7; hex 300000000606cd; asc 0      ;;
 3: len 3; hex 636363; asc ccc;;

2018-09-07T08:59:43.322123Z 17 [Note] InnoDB: *** (2) WAITING FOR THIS LOCK TO BE GRANTED:

RECORD LOCKS space id 574 page no 3 n bits 80 index PRIMARY of table `test`.`t1` trx id 448142 lock_mode X locks rec but not gap waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 4; compact format; info bits 0
 0: len 4; hex 80000001; asc     ;;
 1: len 6; hex 00000006d663; asc      c;;
 2: len 7; hex f4000000060110; asc        ;;
 3: len 3; hex 616161; asc aaa;;

2018-09-07T08:59:43.347673Z 17 [Note] InnoDB: *** WE ROLL BACK TRANSACTION (1)

 

兩個Session的一條SQL,產生死鎖

雖然每個Session都只有一條語句,仍舊會產生死鎖。要分析這個死鎖,首先必須用到本文前面提到的MySQL加鎖的規則。針對Session 1,從name索引出發,讀到的[hdc, 1],[hdc, 6]均滿足條件,不僅會加name索引上的記錄X鎖,而且會加聚簇索引上的記錄X鎖,加鎖順序為先[1,hdc,100],后[6,hdc,10]。而Session 2,從pubtime索引出發,[10,6],[100,1]均滿足過濾條件,同樣也會加聚簇索引上的記錄X鎖,加鎖順序為[6,hdc,10],后[1,hdc,100]。發現沒有,跟Session 1的加鎖順序正好相反,如果兩個Session恰好都持有了第一把鎖,請求加第二把鎖,死鎖就發生了。

結論:死鎖的發生與否,並不在於事務中有多少條SQL語句,死鎖的關鍵在於:兩個(或以上)的Session加鎖的順序不一致。而使用本文上面提到的,分析MySQL每條SQL語句的加鎖規則,分析出每條語句的加鎖順序,然后檢查多個並發SQL間是否存在以相反的順序加鎖的情況,就可以分析出各種潛在的死鎖情況,也可以分析出線上死鎖發生的原因。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM