今天顺便看了一下,主要流程就是跟踪为什么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。一旦设置了个标示将会不自动提交了。