本文只分析了insert语句执行的主路径,和路径上部分关键函数,很多细节没有深入,留给读者继续分析
create table t1(id int);
insert into t1 values(1)
略过建立连接,从 mysql_parse() 开始分析
void mysql_parse(THD *thd, char *rawbuf, uint length,
Parser_state *parser_state){
/* ...... */ /* 检查query_cache,如果结果存在于cache中,直接返回 */ if (query_cache_send_result_to_client(thd, rawbuf, length) <= 0)
{
LEX *lex= thd->lex;
/* 解析语句 */ bool err= parse_sql(thd, parser_state, NULL);
/* 整理语句格式,记录 general log */ /* ...... */ /* 执行语句 */
error= mysql_execute_command(thd);
/* 提交或回滚没结束的事务(事务可能在mysql_execute_command中提交,用trx_end_by_hint标记事务是否已经提交) */ if (!thd->trx_end_by_hint)
{
if (!error && lex->ci_on_success)
trans_commit(thd);
if (error && lex->rb_on_fail)
trans_rollback(thd);
}
进入 mysql_execute_command()
/* */ /* ...... */ case SQLCOM_INSERT:
{
/* 检查权限 */ if ((res= insert_precheck(thd, all_tables)))
break;
/* 执行insert */
res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
lex->update_list, lex->value_list,
lex->duplicates, lex->ignore);
/* 提交或者回滚事务 */ if (!res)
{
trans_commit_stmt(thd);
trans_commit(thd);
thd->trx_end_by_hint= TRUE;
}
else if (res)
{
trans_rollback_stmt(thd);
trans_rollback(thd);
thd->trx_end_by_hint= TRUE;
}
进入 mysql_insert()
bool mysql_insert(THD *thd,TABLE_LIST *table_list,
List &fields, /* insert 的字段 */ List &values_list, /* insert 的值 */ List &update_fields,
List &update_values,
enum_duplicates duplic,
bool ignore)
{
/*对每条记录调用 write_record */ while ((values= its++))
{
if (lock_type == TL_WRITE_DELAYED)
{
LEX_STRING const st_query = { query, thd->query_length() };
DEBUG_SYNC(thd, "before_write_delayed");
/* insert delay */
error= write_delayed(thd, table, st_query, log_on, &info);
DEBUG_SYNC(thd, "after_write_delayed");
query=0;
}
else /* normal insert */
error= write_record(thd, table, &info, &update);
}
/*
这里还有
thd->binlog_query()写binlog
my_ok()返回ok报文,ok报文中包含影响行数