MySQL代码使用了大量Opt_trace相关结构,先看代码中的一段注释:
This optimizer trace is aimed at producing output, which is readable by
humans and by programs, to aid understanding of decisions and actions taken
by the MySQL Optimizer.
可以看出Opt_trace是用来记录相关操作的,以便帮助开发人员进行调试。其并不具有功能性作用。先来看一下MySQL中是怎么使用Opt_trace的。在主执行函数mysql_execute_command中(位于sql_parse.cc):
Opt_trace_start ots(thd, all_tables, lex->sql_command, &lex->var_list,
thd->query().str, thd->query().length, NULL,
thd->variables.character_set_client);
Opt_trace_object trace_command(&thd->opt_trace);
Opt_trace_array trace_command_steps(&thd->opt_trace, "steps");
...
case SQLCOM_SELECT:
{
if (!res)
res= execute_sqlcom_select(thd, all_tables);
break;
}
在执行sql操作(如SELECT)前,基于thd->opt_trace创建出trace_command和trace_command_steps。注意:当执行完毕后,这两个变量自动销毁。
那么Opt_trace_context是什么呢?直接看注释:
A per-session context which is always available at any point of execution,
It maintains properties of the session's regarding tracing: enabled/disabled
state, style (all trace on one line, or not, etc), a list of all remembered
traces of previous and current SQL statement (as restricted by OFFSET/LIMIT),
and a pointer to the current (being-generated) trace (which itself has a
pointer to its current open object/array).
简单来说就是thd->opt_trace存了很多上下文信息。这些信息在整个query执行过程中都是需要的。最上面的代码中:
Opt_trace_start ots(thd, all_tables, lex->sql_command, &lex->var_list,
thd->query().str, thd->query().length, NULL,
thd->variables.character_set_client);
就是用来初始化和赋值thd->opt_trace的。当执行完毕后,ots所在的函数体mysql_execute_command退出时就自动销毁了,thd->opt_trace在ots的析构函数中被销毁。除了
基类为Opt_trace_struct定义在opt_trace.h中。代码用的最多的是两个派生类Opt_trace_object和Opt_trace_array,以及Opt_trace_context