1. 程式人生 > >MySQL的InnoDB的幻讀問題

MySQL的InnoDB的幻讀問題

sha 存儲 action sca sele 就是 沒有 默認 err

MySQL InnoDB事務的隔離級別有四級,默認是“可重復讀”(REPEATABLE READ)。

  • 未提交讀(READ UNCOMMITTED)。另一個事務修改了數據,但尚未提交,而本事務中的SELECT會讀到這些未被提交的數據(臟讀)。
  • 提交讀(READ COMMITTED)。本事務讀取到的是最新的數據(其他事務提交後的)。問題是,在同一個事務裏,前後兩次相同的SELECT會讀到不同的結果(不重復讀)。
  • 可重復讀(REPEATABLE READ)。在同一個事務裏,SELECT的結果是事務開始時時間點的狀態,因此,同樣的SELECT操作讀到的結果會是一致的。但是,會有幻讀現象(稍後解釋)。
  • 串行化(SERIALIZABLE)。讀操作會隱式獲取共享鎖,可以保證不同事務間的互斥。

四個級別逐漸增強,每個級別解決一個問題。

  • 臟讀,最容易理解。另一個事務修改了數據,但尚未提交,而本事務中的SELECT會讀到這些未被提交的數據。
  • 不重復讀。解決了臟讀後,會遇到,同一個事務執行過程中,另外一個事務提交了新數據,因此本事務先後兩次讀到的數據結果會不一致。
  • 幻讀。解決了不重復讀,保證了同一個事務裏,查詢的結果都是事務開始時的狀態(一致性)。但是,如果另一個事務同時提交了新數據,本事務再更新時,就會“驚奇的”發現了這些新數據,貌似之前讀到的數據是“鬼影”一樣的幻覺。

借鑒並改造了一個搞笑的比喻:

  • 臟讀。假如,中午去食堂打飯吃,看到一個座位被同學小Q占上了,就認為這個座位被占去了,就轉身去找其他的座位。不料,這個同學小Q起身走了。事實:該同學小Q只是臨時坐了一小下,並未“提交”。
  • 不重復讀。假如,中午去食堂打飯吃,看到一個座位是空的,便屁顛屁顛的去打飯,回來後卻發現這個座位卻被同學小Q占去了。
  • 幻讀。假如,中午去食堂打飯吃,看到一個座位是空的,便屁顛屁顛的去打飯,回來後,發現這些座位都還是空的(重復讀),竊喜。走到跟前剛準備坐下時,卻驚現一個恐龍妹,嚴重影響食欲。仿佛之前看到的空座位是“幻影”一樣。

------

一些文章寫到InnoDB的可重復讀避免了“幻讀”(phantom read),這個說法並不準確。

做個試驗:(以下所有試驗要註意存儲引擎和隔離級別)

mysql> show create table t_bitfly\G;
CREATE TABLE `t_bitfly` (
`id` bigint(20) NOT NULL default ‘0‘,
`value` varchar(32) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk

mysql> select @@global.tx_isolation, @@tx_isolation;
+-----------------------+-----------------+
| @@global.tx_isolation | @@tx_isolation |
+-----------------------+-----------------+
| REPEATABLE-READ | REPEATABLE-READ |
+-----------------------+-----------------+

試驗一:

t Session A Session B
|
| START TRANSACTION; START TRANSACTION;
|
| SELECT * FROM t_bitfly;
| empty set
| INSERT INTO t_bitfly
| VALUES (1, ‘a‘);
|
| SELECT * FROM t_bitfly;
| empty set
| COMMIT;
|
| SELECT * FROM t_bitfly;
| empty set
|
| INSERT INTO t_bitfly VALUES (1, ‘a‘);
| ERROR 1062 (23000):
| Duplicate entry ‘1‘ for key 1
v (shit, 剛剛明明告訴我沒有這條記錄的)

如此就出現了幻讀,以為表裏沒有數據,其實數據已經存在了,傻乎乎的提交後,才發現數據沖突了。

試驗二:

t Session A Session B
|
| START TRANSACTION; START TRANSACTION;
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
| INSERT INTO t_bitfly
| VALUES (2, ‘b‘);
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
| COMMIT;
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
|
| UPDATE t_bitfly SET value=‘z‘;
| Rows matched: 2 Changed: 2 Warnings: 0
| (怎麽多出來一行)
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | z |
| | 2 | z |
| +------+-------+
|
v

本事務中第一次讀取出一行,做了一次更新後,另一個事務裏提交的數據就出現了。也可以看做是一種幻讀。

------

那麽,InnoDB指出的可以避免幻讀是怎麽回事呢?

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

By default, InnoDB operates in REPEATABLE READ transaction isolation level and with the innodb_locks_unsafe_for_binlog system variable disabled. In this case, InnoDB uses next-key locks for searches and index scans, which prevents phantom rows (see Section 13.6.8.5, “Avoiding the Phantom Problem Using Next-Key Locking”).

準備的理解是,當隔離級別是可重復讀,且禁用innodb_locks_unsafe_for_binlog的情況下,在搜索和掃描index的時候使用的next-key locks可以避免幻讀。

關鍵點在於,是InnoDB默認對一個普通的查詢也會加next-key locks,還是說需要應用自己來加鎖呢?如果單看這一句,可能會以為InnoDB對普通的查詢也加了鎖,如果是,那和序列化(SERIALIZABLE)的區別又在哪裏呢?

MySQL manual裏還有一段:

13.2.8.5. Avoiding the Phantom Problem Using Next-Key Locking (http://dev.mysql.com/doc/refman/5.0/en/innodb-next-key-locking.html)

To prevent phantoms, InnoDB uses an algorithm called next-key locking that combines index-row locking with gap locking.

You can use next-key locking to implement a uniqueness check in your application: If you read your data in share mode and do not see a duplicate for a row you are going to insert, then you can safely insert your row and know that the next-key lock set on the successor of your row during the read prevents anyone meanwhile inserting a duplicate for your row. Thus, the next-key locking enables you to “lock” the nonexistence of something in your table.

我的理解是說,InnoDB提供了next-key locks,但需要應用程序自己去加鎖。manual裏提供一個例子:

SELECT * FROM child WHERE id > 100 FOR UPDATE;

這樣,InnoDB會給id大於100的行(假如child表裏有一行id為102),以及100-102,102+的gap都加上鎖。

可以使用show innodb status來查看是否給表加上了鎖。

再看一個實驗,要註意,表t_bitfly裏的id為主鍵字段。實驗三:

t Session A Session B
|
| START TRANSACTION; START TRANSACTION;
|
| SELECT * FROM t_bitfly
| WHERE id<=1
| FOR UPDATE;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
| INSERT INTO t_bitfly
| VALUES (2, ‘b‘);
| Query OK, 1 row affected
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
| INSERT INTO t_bitfly
| VALUES (0, ‘0‘);
| (waiting for lock ...
| then timeout)
| ERROR 1205 (HY000):
| Lock wait timeout exceeded;
| try restarting transaction
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
| COMMIT;
|
| SELECT * FROM t_bitfly;
| +------+-------+
| | id | value |
| +------+-------+
| | 1 | a |
| +------+-------+
v

可以看到,用id<=1加的鎖,只鎖住了id<=1的範圍,可以成功添加id為2的記錄,添加id為0的記錄時就會等待鎖的釋放。

MySQL manual裏對可重復讀裏的鎖的詳細解釋:

http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read

For locking reads (SELECT with FOR UPDATE or LOCK IN SHARE MODE),UPDATE, and DELETE statements, locking depends on whether the statement uses a unique index with a unique search condition, or a range-type search condition. For a unique index with a unique search condition, InnoDB locks only the index record found, not the gap before it. For other search conditions, InnoDB locks the index range scanned, using gap locks or next-key (gap plus index-record) locks to block insertions by other sessions into the gaps covered by the range.

------

一致性讀和提交讀,先看實驗,實驗四:

t Session A Session B
|
| START TRANSACTION; START TRANSACTION;
|
| SELECT * FROM t_bitfly;
| +----+-------+
| | id | value |
| +----+-------+
| | 1 | a |
| +----+-------+
| INSERT INTO t_bitfly
| VALUES (2, ‘b‘);
| COMMIT;
|
| SELECT * FROM t_bitfly;
| +----+-------+
| | id | value |
| +----+-------+
| | 1 | a |
| +----+-------+
|
| SELECT * FROM t_bitfly LOCK IN SHARE MODE;
| +----+-------+
| | id | value |
| +----+-------+
| | 1 | a |
| | 2 | b |
| +----+-------+
|
| SELECT * FROM t_bitfly FOR UPDATE;
| +----+-------+
| | id | value |
| +----+-------+
| | 1 | a |
| | 2 | b |
| +----+-------+
|
| SELECT * FROM t_bitfly;
| +----+-------+
| | id | value |
| +----+-------+
| | 1 | a |
| +----+-------+
v

如果使用普通的讀,會得到一致性的結果,如果使用了加鎖的讀,就會讀到“最新的”“提交”讀的結果。

本身,可重復讀和提交讀是矛盾的。在同一個事務裏,如果保證了可重復讀,就會看不到其他事務的提交,違背了提交讀;如果保證了提交讀,就會導致前後兩次讀到的結果不一致,違背了可重復讀。

可以這麽講,InnoDB提供了這樣的機制,在默認的可重復讀的隔離級別裏,可以使用加鎖讀去查詢最新的數據。

http://dev.mysql.com/doc/refman/5.0/en/innodb-consistent-read.html

If you want to see the “freshest” state of the database, you should use either the READ COMMITTED isolation level or a locking read:
SELECT * FROM t_bitfly LOCK IN SHARE MODE;

------

結論:MySQL InnoDB的可重復讀並不保證避免幻讀,需要應用使用加鎖讀來保證。而這個加鎖度使用到的機制就是next-key locks。

MySQL的InnoDB的幻讀問題