MySQL中begin后事务为什么不提交

54次阅读
没有评论

共计 2311 个字符,预计需要花费 6 分钟才能阅读完成。

这篇文章主要介绍“MySQL 中 begin 后事务为什么不提交”,在日常操作中,相信很多人在 MySQL 中 begin 后事务为什么不提交问题上存在疑惑,丸趣 TV 小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”MySQL 中 begin 后事务为什么不提交”的疑惑有所帮助!接下来,请跟着丸趣 TV 小编一起来学习吧!

今天顺便看了一下,主要流程就是跟踪为什么 begin 后事物不会提交,最后发现在:
MYSQL_BIN_LOG::commit 函数中包含这个判断

if (!cache_mngr- trx_cache.is_binlog_empty()  
 ending_trans(thd, all)   !trx_stuff_logged)

如果 begin 的话 ending_trans(thd, all) 将会返回为 false,也就不会调用 order_commit 流程了。
那么其主要判断就是:

bool ending_single_stmt_trans(THD* thd, const bool all){ return (!all   !thd- in_multi_stmt_transaction_mode());
}

下面是源码注释和函数:

 Returns TRUE if session is in a multi-statement transaction mode.
 OPTION_NOT_AUTOCOMMIT: When autocommit is off, a multi-statement
 transaction is implicitly started on the first statement after a
 previous transaction has been ended.
 OPTION_BEGIN: Regardless of the autocommit status, a multi-statement
 transaction can be explicitly started with the statements  START
 TRANSACTION ,  BEGIN [WORK] ,  [COMMIT | ROLLBACK] AND CHAIN , etc.
 Note: this doesn t tell you whether a transaction is active.
 A session can be in multi-statement transaction mode, and yet
 have no active transaction, e.g., in case of:
 set @@autocommit=0;
 set @a= 3;  -- these statements don t
 set transaction isolation level serializable;  -- start an active
 flush tables;  -- transaction
 I.e. for the above scenario this function returns TRUE, even
 though no active transaction has begun.
 @sa in_active_multi_stmt_transaction()
 */ inline bool in_multi_stmt_transaction_mode() const
 { return variables.option_bits   (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN);
 }

其实就是在判断是都 option_bits 的对应位上为 1。因此简单了我们就看看什么时候设置 OPTION_BEGIN 位就好了。

实际上是函数 trans_begin 设置的下面是这段代码:

 thd- variables.option_bits|= OPTION_BEGIN;
 thd- server_status|= SERVER_STATUS_IN_TRANS; if (thd- tx_read_only)
 thd- server_status|= SERVER_STATUS_IN_TRANS_READONLY;
 DBUG_PRINT(info , ( setting SERVER_STATUS_IN_TRANS)); if (tst)
 tst- add_trx_state(thd, TX_EXPLICIT); /* ha_start_consistent_snapshot() relies on OPTION_BEGIN flag set. */
 if (flags   MYSQL_START_TRANS_OPT_WITH_CONS_SNAPSHOT)
 { if (tst)
 tst- add_trx_state(thd, TX_WITH_SNAPSHOT);
 res= ha_start_consistent_snapshot(thd);
 }

实际上就是在 MySQL 层设置一些标示,如果是 START TRANSACTION WITH CONSISTENT SNAPSHOT 还会开启一个一致性快照,就是一个 readview。一旦设置了个标示将会不自动提交了。

到此,关于“MySQL 中 begin 后事务为什么不提交”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注丸趣 TV 网站,丸趣 TV 小编会继续努力为大家带来更多实用的文章!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-07-26发表,共计2311字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)