Mysql 的'start transaction'真的马上开启了一个事务吗?

2018-10-25 21:31:06 +08:00
 bromineMai

定义数据如下:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT ,
  `age` int(11) DEFAULT NULL ,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ;
CREATE TABLE `other_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT ,
  `age` int(11) DEFAULT NULL ,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ;
INSERT other_table VALUE (1,1);
INSERT other_table VALUE (2,1);
INSERT user VALUE (1,1);
INSERT user VALUE (2,1);

案例一--MVCC: Mysql 默认的 RR 隔离级别下,理论上快照读会获取当前事务开启时的数据快照。

AB 事务按以下顺序执行

1A:   start transaction;
2B:   start transaction;
3B    update  user  set age=20 where id =2 ;
4A    select * from other_table where id =2 ;
5B    COMMIT;
6A	  select age from user where id =3 for update;
7A	  select age from user where id =3 ;

语句 6,7 分别返回 age=20 age=2,这个符合我们对 MVCC 的一般认知。 然而将对无关表的查询--语句 4 抽离时

1A:   start transaction;
2B:   start transaction;
3B    update  user  set age=20 where id =2 ;
4B    COMMIT;
5A	  select age from user where id =3 for update;
6A	  select age from user where id =3 ;

这时语句 5,6 返回的都是 age=30。 这现象是在解决线上一个并发 BUG 时无意发现的。 select * from other_table where id =2 ;对表空间的 UNDO 段没有任何影响,却影响了快照读的结果。 一开始我以为这个可能是 Mysql 查询缓存的一个 BUG,直到我做了另外一个实验。

案例二:alter table 导致 table meta change 还是那个两个测试表,

1.A   start transaction;
2.A   select * from other_table where id =2 ;
3.B    ALTER TABLE user ADD  COLUMN    `age2` int(5) DEFAULT NULL ;
4.A   select * from user where id =2 ;

因为同一个事务中表格 meta data 改变,执行语句 4 时 mysql 抛出报错 ERROR 1412 (HY000): Table definition has changed, please retry transaction

这次我们估计重施,将语句 2 抽调

1.A   start transaction;
2.B    ALTER TABLE user ADD  COLUMN    `age3` int(5) DEFAULT NULL ;
3.A   select * from user where id =2 ;

语句 3 成功返回,没有任何报错:

+----+------+------+------+
| id | age  | age2 | age3 |
+----+------+------+------+
|  2 |   30 | NULL | NULL |
+----+------+------+------+

到了这里我开始确认,案例 1 并不是 1 个 BUG,而是 mysql 的'start transaction'并没有真正开启一个事务。 在'start transaction'后,很可能 mysql 在执行第一条查询时,才算完全开启了一个事务。

5108 次点击
所在节点    数据库
2 条回复
bromineMai
2018-10-26 17:30:52 +08:00
居然直接沉了..
HelloAmadeus
2019-03-21 13:00:49 +08:00
alert 难道可以用在事务里了吗?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/501189

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX