天天看點

MySQL:begin後事務為什麼不送出

今天順便看了一下,主要流程就是跟蹤為什麼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。一旦設定了個标示将會不自動送出了。

繼續閱讀