search
HomeDatabaseMysql Tutorial探索MySQL源代码之SQL历险记

本文从一个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>

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>

进入dispatch_command, 我们可见

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

这个就是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>

是的开始解析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>

可以看到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>

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>

结束了优化,我们要具体执行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>

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

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

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

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


Statement
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
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use