转载请署名:印风
-----------------------------------------------
在innodb里我们经常可以看到一段代码,以mtr_start()开始,以mtr_commit(&mtr)结束;minitransaction主要用于锁和日志信息.
Mini事务的控制结构体:
struct mtr_struct{
#ifdef UNIV_DEBUG
ulint state; /*!
#endif
dyn_array_t memo; /*!
dyn_array_t log; /*!
ibool inside_ibuf;
/*!
ibool modifications;
/*TRUE if the mtr made modifications to
bufferpool pages */
ulint n_log_recs;
/*count of how many page initial log records
havebeen written to the mtr log */
ulint log_mode; /* specifies whichoperations should be
logged;default value MTR_LOG_ALL */
ib_uint64_t start_lsn;/* start lsn of the possible logentry for
thismtr */
ib_uint64_t end_lsn;/* end lsn of the possible logentry for
thismtr */
#ifdef UNIV_DEBUG
ulint magic_n;
#endif /* UNIV_DEBUG */
};
在每个mtr结构体里,会创建两个动态数组:memo和log,前者用于管理锁信息,后者用于管理事务日志信息。
在涉及到跟表空间或者日志相关的记录时,例如取一条undo log这样的操作。Mtr_start会初始化结构体和分配动态数组,mtr_commit则会将相关的修改写到日志(mtr_log_reserve_and_write)中,并释放锁(mtr_memo_pop_all),最后释放分配的内存
例如在prepare阶段会调用函数trx_prepare_off_kernel设置事务状态:
1. mtr_start(&mtr);
2. trx_undo_set_state_at_prepare 将undo log段由状态TRX_UNDO_ACTIVE修改为TRX_UNDO_PREPARED
这个函数会调用mlog_write_ulint,根据注释的解释,mlog_write_ulint会做如下工作:
--------- Writes 1 - 4 bytes to a file pagebuffered in the buffer pool.
---------- Writes the corresponding logrecord to the mini-transaction log.
1).首先根据byte数调用相应的mach_write_to_[NUM]函数写入到内存中
2)然后调用mlog_open获得在mtr->log中的动态数组
3)将当前page的偏移量写入mtr-
mach_write_to_2(log_ptr, page_offset(ptr));
4). 将事务状态修改记录写入mtr
log_ptr += mach_write_compressed(log_ptr,val);
5)关闭指向log_ptr的mtr->log内存缓冲
mlog_close(mtr, log_ptr);
mlog_close和mlog_open最终都调用了dyn文件夹下的一组函数,在dyn中封装了对动态数组的操作。
3.最后当执行mtr_commit(&mtr)时,会将修改写入到磁盘文件中。