在binlog_format=row模式下,事务中create或drop临时表后,后面再执行DML(影响多行的DML)如果失败,那么失败的DML会回滚,但DML仍然记录了binlog。这个 binlog 应用到备库后会导致主备不一致。
此bug已提给官方bug#76940。 以下是重现的测例:
主库执行
- create table t1(c1 int primary key) engine=innodb;
- insert into t1 values(1),(2),(3),(4),(5);
- create table t2 (c1 int, c2 int, foreign key(c2) references t1(c1)) engine=innodb;
- insert into t2 values(1,1),(2,2),(5,5);
- create temporary table tmp as select * from t1;
- begin;
- drop temporary table if exists tmp;
- delete from t1 where c1 > 2;
- --delete 失败: ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`zy`.`t2`, CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`c2`) REFERENCES `t1` (`c1`))
- commit;
- mysql> select * from t1;
- +----+
- | c1 |
- +----+
- | 1 |
- | 2 |
- | 3 |
- | 4 |
- | 5 |
- +----+
备库结果
- mysql> select * from t1;
- +----+
- | c1 |
- +----+
- | 1 |
- | 2 |
- | 5 |
- +----+
查看主库生成的binlog,
失败了也记入了binlog。
- delete from t1 where c1 > 2
- BEGIN
- /*!*/;
- # at 1226
- #150515 17:27:07 server id 1979399682 end_log_pos 1349 Query thread_id=6263054 exec_time=0 error_code=0
- SET TIMESTAMP=1431682027/*!*/;
- SET @@session.pseudo_thread_id=6263054/*!*/;
- DROP TEMPORARY TABLE IF EXISTS `tmp` /* generated by server */
- /*!*/;
- # at 1349
- # at 1388
- #150515 17:27:07 server id 1979399682 end_log_pos 1388 Table_map: `zy`.`t1` mapped to number 42174
- #150515 17:27:07 server id 1979399682 end_log_pos 1427 Delete_rows: table id 42174 flags: STMT_END_F
- BINLOG '
- 67tVVRMCPvt1JwAAAGwFAAAAAL6kAAAAAAEAAnp5AAJ0MQABAwAA
- 67tVVRkCPvt1JwAAAJMFAAAAAL6kAAAAAAEAAf/+AwAAAP4EAAAA
- '/*!*/;
- ### DELETE FROM zy.t1
- ### WHERE
- ### @1=3 /* INT meta=0 nullable=0 is_null=0 */
- ### DELETE FROM zy.t1
- ### WHERE
- ### @1=4 /* INT meta=0 nullable=0 is_null=0 */
- # at 1427
- #150515 17:27:09 server id 1979399682 end_log_pos 1494 Query thread_id=6263054 exec_time=0 error_code=0
- SET TIMESTAMP=1431682029/*!*/;
- COMMIT
binlog有两个cache用来缓存事务的binlog。
- binlog_cache_data stmt_cache; //存放非事务表和临时表binlog
- binlog_cache_data trx_cache; //存放事务表binlog
事务和语句回滚时应清理相应的cache, 事务提交时cache会刷入binlog文件中。
临时表在 drop 或 create 时不管成功还是失败都会记binlog。
当 drop 或 create 临时表操作和其他DML在一个事务中时,drop 或 create 临时表不管成功还是失败都会记binlog。查看源码中逻辑是只要事务中出现过 drop 或 create 临时表操作,那么事务后来的语句不管成功还是失败binlog cache都不会清理(参考函数
和
- binlog_rollback
)。
- binlog_truncate_trx_cache
对于前面的例子,当事务执行到以下语句时,由于违反引用约束失败语句回滚时trx_cache应该清理。
delete from t1 where c1 > 2;
因此 delete 3,4 两条记录的binlog是应该不记入binlog的。
当 drop 或 create 临时表操作和其他DML在一个事务中时,如果当前执行的语句不是 drop 或 create 临时表并且失败,则 binlog cache 应该清理。如果当前执行的语句是drop或create临时表,不管成功还是失败,cache都不用清理,都应记入binlog。
来源: http://mysql.taobao.org/monthly/2015/05/08/