Home Database Mysql Tutorial 探索MySQL源代码之SQL历险记

探索MySQL源代码之SQL历险记

Jun 07, 2016 pm 04:05 PM
mysql sql explore source code

本文从一个select语句的执行过程出发,遍历MySQL的多个几子系统。 先放图一张, 按图索骥开始我们的历险. 当客户端连接上MySQL服务端之后,发出请求之前,服务端的线程是阻塞在do_command(sql/parse.cc)里的my_net_read函数中(就是socket里的read). 当客户端键

本文从一个select语句的执行过程出发,遍历MySQL的多个几子系统。

先放图一张, 按图索骥开始我们的历险.

当客户端连接上MySQL服务端之后,发出请求之前,服务端的线程是阻塞在do_command(sql/parse.cc)里的my_net_read函数中(就是socket里的read).

当客户端键入sql语句(本文例子select * from zzz)发送到服务端之后, my_net_read返回, 并从tcpbuffer中读取数据写入到packet这个字符串.

<ol class="dp-sql"><li class="alt"><span><span>packet_length= my_net_read(net); </span></span></li></ol>
Copy after login

packet的第一个字节是个标志位, 决定数据包是查询还是命令,成功,或者出错。

接下来就进入dispatch_command(sql/sql/parse.cc)这个函数, 数据类型不再需要.

<ol class="dp-sql"><li class="alt"><span><span>return_value= dispatch_command(command, thd, packet+1, (uint) (packet_length-1)); </span></span></li></ol>
Copy after login

进入dispatch_command, 我们可见

<ol class="dp-sql"><li class="alt"><span><span>statistic_increment(thd->status_var.questions, &LOCK_status); </span></span></li></ol>
Copy after login

这个就是show status questions的值累加.

接下的mysql_parse(sql/sql_parse.cc), 该函数是sql语句解析的总路口.

进入该函数后首先碰到的是query_cache_send_result_to_client,故名思义这个函数是在QCache里查询是否有相同的语句, 有则立即从QCache返回结果, 于是整个sql就结束了.

QCache里不存在的sql则继续前进来到parse_sql(sql/sql_parse.cc),这个函数主要就是调用了MYSQLparse. 而MYSQLparse其实就是bison/yacc里的yyparse(^_^),

<ol class="dp-sql"><li class="alt"><span><span>#define yyparse MYSQLparse </span></span></li></ol>
Copy after login

是的开始解析sql了. 关于词法分析和语法匹配简单说几下.

对于一条像select * from zzz的语句首先进入词法分析,找到2个token(select, from), 然后根据token进行语法匹配, 规则在sql/yacc.yy里, 我把几个匹配到的pattern和action贴出来.

<ol class="dp-sql">
<li class="alt"><span><span class="keyword">select</span><span>: </span></span></li>
<li><span>select_init </span></li>
<li class="alt"><span>{ </span></li>
<li><span>LEX *lex= Lex; </span></li>
<li class="alt"><span>lex->sql_command= SQLCOM_SELECT; </span></li>
<li><span>} </span></li>
<li class="alt"><span>; </span></li>
<li><span>/* Need select_init2 <span class="keyword">for</span><span> subselects. */ </span></span></li>
<li class="alt"><span>select_init: </span></li>
<li><span>SELECT_SYM select_init2 </span></li>
<li class="alt"><span>| <span class="string">'('</span><span> select_paren </span><span class="string">')'</span><span> union_opt </span></span></li>
<li><span>; </span></li>
<li class="alt"><span>select_paren: </span></li>
<li><span>SELECT_SYM select_part2 </span></li>
<li class="alt"><span>{ </span></li>
<li><span>LEX *lex= Lex; </span></li>
<li class="alt"><span>SELECT_LEX * sel= lex->current_select; </span></li>
<li><span>..... </span></li>
<li class="alt"><span>select_from: </span></li>
<li><span><span class="keyword">FROM</span><span> join_table_list where_clause group_clause having_clause </span></span></li>
<li class="alt"><span>opt_order_clause opt_limit_clause procedure_clause </span></li>
<li><span>{ </span></li>
<li class="alt"><span><span class="keyword">Select</span><span>->context.table_list= </span></span></li>
<li><span><span class="keyword">Select</span><span>->context.first_name_resolution_table= </span></span></li>
<li class="alt"><span>(TABLE_LIST *) <span class="keyword">Select</span><span>->table_list.</span><span class="keyword">first</span><span>; </span></span></li>
<li><span>} </span></li>
<li class="alt"><span>.... </span></li>
<li><span>select_item_list: </span></li>
<li class="alt"><span>select_item_list <span class="string">','</span><span> select_item </span></span></li>
<li><span>| select_item </span></li>
<li class="alt"><span>| <span class="string">'*'</span><span> </span></span></li>
<li><span>{ </span></li>
<li class="alt"><span>THD *thd= YYTHD; </span></li>
<li><span>Item *item= new (thd->mem_root) </span></li>
<li class="alt"><span>Item_field(&thd->lex->current_select->context, </span></li>
<li><span><span class="op">NULL</span><span>, </span><span class="op">NULL</span><span>, </span><span class="string">"*"</span><span>); </span></span></li>
<li class="alt"><span>if (item == <span class="op">NULL</span><span>) </span></span></li>
<li><span>MYSQL_YYABORT; </span></li>
<li class="alt"><span>if (add_item_to_list(thd, item)) </span></li>
<li><span>MYSQL_YYABORT; </span></li>
<li class="alt"><span>(thd->lex->current_select->with_wild)++; </span></li>
<li><span>} </span></li>
<li class="alt"><span>; </span></li>
<li><span>select_item: </span></li>
<li class="alt"><span>remember_name select_item2 remember_end select_alias </span></li>
<li><span>{ </span></li>
<li class="alt"><span>THD *thd= YYTHD; </span></li>
<li><span>DBUG_ASSERT($1 </span></li>
<li class="alt"><span>if (add_item_to_list(thd, $2)) </span></li>
<li><span>MYSQL_YYABORT; </span></li>
<li class="alt"><span>if ($4.str) </span></li>
<li><span>... </span></li>
</ol>
Copy after login

可以看到action里最关键的就是add_item_to_list 和table_list的赋值.

解析后对于需要查询的表(zzz)和字段(*)这些信息都写入到thd->lex这个结构体里了.

例如其中thd->lex->query_tables就是表(zzz)的状况, thd->lex->current_select->with_wild 是表示该语句是否使用了*等等.

<ol class="dp-sql">
<li class="alt"><span><span>(gdb) p *thd->lex->query_tables </span></span></li>
<li><span>$7 = {next_local = 0x0, next_global = 0x0, prev_global = 0x855a458, db = 0x85a16b8 <span class="string">"test"</span><span>, alias = 0x85a16e0 </span><span class="string">"zzz"</span><span>, </span></span></li>
<li class="alt"><span>table_name = 0x85a16c0 <span class="string">"zzz"</span><span>, schema_table_name = 0x0, </span><span class="keyword">option</span><span> = 0x0, on_expr = 0x0, prep_on_expr = 0x0, cond_equal = 0x0, </span></span></li>
</ol>
Copy after login

sql解析完了, 优化呢? 别急接着往下看.

接着进入mysql_execute_command函数,这个函数是所有sql命令的总入口.

由于是这个sql是一个select, 于是execute_sqlcom_select就是我们下个要执行的函数,又然后进入了mysql_select(^_^怒了如此复杂).

mysql_select 就是优化器的模块, 这个模块代码比较复杂. 我们可以清楚看到创建优化器,优化,执行的3个步骤, 优化细节不表.

<ol class="dp-sql">
<li class="alt"><span><span>if (!(</span><span class="op">join</span><span>= new </span><span class="op">JOIN</span><span>(thd, fields, select_options, result))) </span></span></li>
<li><span>... </span></li>
<li class="alt"><span>if ((err= <span class="op">join</span><span>->optimize())) </span></span></li>
<li><span>... </span></li>
<li class="alt"><span><span class="op">join</span><span>-></span><span class="keyword">exec</span><span>(); </span></span></li>
</ol>
Copy after login

结束了优化,我们要具体执行join->exec(),该函数实际进入的是JOIN::exec()(sql_select.cc)。

exec()首先向客户端发送字段title的函数send_fields, 没数据但字段也是要的。

然后再进入do_select(),根据表的存储引擎跳入到引擎具体的实现(zzz是myisam表)。

这里mi_scan就是myisam引擎扫描文件的函数,再看到

<ol class="dp-sql">
<li class="alt"><span><span>(gdb) p info->filename </span></span></li>
<li><span>./test/zzz </span></li>
</ol>
Copy after login

这不就是zzz表对应的物理文件吗。

通过一系列的mi函数访问磁盘拿到数据之后,会通过send_data发送数据给client,并从dispatch_command返回.最后在net_end_statement结束整个sql。

一个简单的select语句背后的执行过程是非常复杂的,上面的步骤都只是点到就止。

ps: 在sql_yacc.yy可见MySQL对于Oracle中常用的dual表的嘲讽。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

phpmyadmin connection mysql phpmyadmin connection mysql Apr 10, 2025 pm 10:57 PM

How to connect to MySQL using phpMyAdmin? The URL to access phpMyAdmin is usually http://localhost/phpmyadmin or http://[your server IP address]/phpmyadmin. Enter your MySQL username and password. Select the database you want to connect to. Click the "Connection" button to establish a connection.

Solution to MySQL encounters 'Access denied for user' problem Solution to MySQL encounters 'Access denied for user' problem Apr 11, 2025 pm 05:36 PM

How to solve the MySQL "Access denied for user" error: 1. Check the user's permission to connect to the database; 2. Reset the password; 3. Allow remote connections; 4. Refresh permissions; 5. Check the database server configuration (bind-address, skip-grant-tables); 6. Check the firewall rules; 7. Restart the MySQL service. Tip: Make changes after backing up the database.

See all articles