Mysql source code learning-creating exclusive syntaxes _ MySQL

Source: Internet
Author: User
Mysql source code learning-creating the exclusive syntax bitsCN.com

Syntax analysis-YACC

Anyone who has been familiar with SQL statements will have read this or that SQL Manual. Its Syntax Standard should start with SQL92. when reading the SQL92 standard, you will find that the bucos paradigm (BNF) is defined as a standard of syntax definition. Both the cool ORACLE and the unfortunately acquired Mysql will follow the standard syntax in it, except of course some extended syntax, for example, today we will extend a simple syntax ^-^.

Okay. you know the source of SQL syntax. how can you parse the syntax? YACC !! (Yet Another Compiler), which is written in BNF, a powerful syntax parsing tool. YACC receives tokens from the lexical analysis phase and then matches those BNF. Today, I will unveil it. (For the basic usage of YACC, you can refer to the link I mentioned in the previous article. you must first understand it)

Continue with the statement SELECT @ VERSION_COMMET in the previous section. for simplicity, the suffix limit 1 is omitted here. The Mysql syntax file is SQL _yacc.yy. First, the syntax nodes involved in this statement are provided. (you can click here for a general view ):

?

Query:

END_OF_INPUT

{...}

| Verb_clause

{...}

| Verb_clause END_OF_INPUT

{

/* Single query, not terminated .*/

YYLIP-> found_semicolon = NULL;

}

Verb_clause:

Statement

| Begin

;

Statement:

Alter

| Analyze

| Backup

| Binlog_base64_event

| Call

| Change

| Check

| Checksum

| Commit

| Create

| Deallocate

| Delete

| Describe

| Do

| Drop

| Execute

| Flush

| Grant

| Handler

| Help

| Insert

| Install

| Kill

| Load

| Lock

| Optimize

| Keycache

| Partition_entry

| Preload

| Prepare

| Purge

| Release

| Rename

| Repair

| Replace

| Reset

| Restore

| Revoke

| Rollback

| Savepoint

| Select

| Set

| Show

| Slave

| Start

| Truncate

| Uninstall

| Unlock

| Update

| Use

| Xa

;

Select:

Select_init

{

LEX * lex = Lex;

Lex-> SQL _command = SQLCOM_SELECT;

}

;

Select_init:

SELECT_SYM select_init2

| '('Select_paren')' union_opt

;

Select_init2:

Select_part2

{

LEX * lex = Lex;

SELECT_LEX * sel = lex-> current_select;

If (lex-> current_select-> set_braces (0 ))

{

My_parse_error (ER (ER_SYNTAX_ERROR ));

MYSQL_YYABORT;

}

If (sel-> linkage = UNION_TYPE &&

Sel-> master_unit ()-> first_select ()-> braces)

{

My_parse_error (ER (ER_SYNTAX_ERROR ));

MYSQL_YYABORT;

}

}

Union_clause

;

Select_part2:

{

LEX * lex = Lex;

SELECT_LEX * sel = lex-> current_select;

If (sel-> linkage! = UNION_TYPE)

Mysql_init_select (lex );

Lex-> current_select-> parsing_place = SELECT_LIST;

}

Select_options select_item_list

{

Select-> parsing_place = NO_MATTER;

}

Select_into select_lock_type

;

?

Select_item_list:

Select_item_list ', 'select_item

| Select_item

| '*'

{

THD * thd = YYTHD;

Item * item = new (thd-> mem_root)

Item_field (& thd-> lex-> current_select-> context,

NULL, NULL ,"*");

If (item = NULL)

MYSQL_YYABORT;

If (add_item_to_list (thd, item ))

MYSQL_YYABORT;

(Thd-> lex-> current_select-> with_wild) ++;

}

;

Select_item:

Remember_name select_item2 remember_end select_alias

{

THD * thd = YYTHD;

DBUG_ASSERT ($1 <$3 );

If (add_item_to_list (thd, $2 ))

MYSQL_YYABORT;

If ($ 4.str)

{

If (Lex-> SQL _command = SQLCOM_CREATE_VIEW &&

Check_column_name ($ 4.str ))

{

My_error (ER_WRONG_COLUMN_NAME, MYF (0), $ 4.str );

MYSQL_YYABORT;

}

$2-> is_autogenerated_name = FALSE;

$2-> set_name ($ 4.str, $4. length, system_charset_info );

}

Else if (! $2-> name)

{

$2-> set_name ($1, (uint) ($3-$1), thd-> charset ());

}

}

;

Variable:

'@'

{

If (! Lex-> parsing_options.allows_variable)

{

My_error (ER_VIEW_SELECT_VARIABLE, MYF (0 ));

MYSQL_YYABORT;

}

}

Variable_aux

{

$ = $3;

}

;

Variable_aux:

Ident_or_text SET_VAR expr

{

Item_func_set_user_var * item;

$ = Item = new (YYTHD-> mem_root) Item_func_set_user_var ($1, $3 );

If ($ = NULL)

MYSQL_YYABORT;

LEX * lex = Lex;

Lex-> uncacheable (UNCACHEABLE_RAND );

Lex-> set_var_list.push_back (item );

}

| Ident_or_text

{

$ = New (YYTHD-> mem_root) Item_func_get_user_var ($1 );

If ($ = NULL)

MYSQL_YYABORT;

LEX * lex = Lex;

Lex-> uncacheable (UNCACHEABLE_RAND );

}

| '@' Opt_var_ident_type ident_or_text opt_component

{

/* Disallow "SELECT @ global. global. variable "*/

If ($ 3.str & $ 4.str & check_reserved_words (& $3 ))

{

My_parse_error (ER (ER_SYNTAX_ERROR ));

MYSQL_YYABORT;

}

If (! ($ = Get_system_var (YYTHD, $2, $3, $4 )))

MYSQL_YYABORT;

If (! (Item_func_get_system_var *) $)-> is_written_to_binlog ())

Lex-> set_stmt_unsafe ();

}

;

Next, let's take a closer look at the execution process of the entire SELECT syntax node:

?

Query-> verb_clause-> statement-> select-> select_init-> select_init2-> select_part2-> select_item_list-> select_item... -> Variable

The syntax is top-down, and the actual parsing process is a bottom-up matching process. For lexical analysis, yacc sends the SELECT keyword first. why is the SELECT keyword described in the previous section?

Let's take a look at SQL _yacc.yy and find the following definition:

?

% Token SELECT_SYM/* SQL-2003-R */

A macro SELECT_SYM is defined to represent a keyword. the macro is defined as follows:

?

# Define SELECT_SYM 687

How are the strings "SELECT" and SELECT_SYM associated? Let's look back at the find_keyword function in MYSQLlex:

?

Static int find_keyword (Lex_input_stream * lip, uint len, bool function)

{

Const char * tok = lip-> get_tok_start ();

SYMBOL * symbol = get_hash_symbol (tok, len, function );

If (symbol)

{

Lip-> yylval-> symbol. symbol = symbol;

Lip-> yylval-> symbol. str = (char *) tok;

Lip-> yylval-> symbol. length = len;

If (symbol-> tok = NOT_SYM )&&

(Lip-> m_thd-> variables. SQL _mode & MODE_HIGH_NOT_PRECEDENCE ))

Return NOT2_SYM;

If (symbol-> tok = OR_OR_SYM )&&

! (Lip-> m_thd-> variables. SQL _mode & MODE_PIPES_AS_CONCAT ))

Return OR2_SYM;

Return symbol-> tok;

}

Return 0;

}

Static SYMBOL * get_hash_symbol (const char * s,

Unsigned int len, bool function)

{

Register uchar * hash_map;

Register const char * cur_str = s;

If (len = 0 ){

DBUG_PRINT ("warning", ("get_hash_symbol () received a request for a zero-length symbol, which is probably a mistake ."));

?

Return (NULL );

}

If (function ){

If (len> SQL _functions_max_len) return 0;

Hash_map = SQL _functions_map;

Register uint32 cur_struct = uint4korr (hash_map + (len-1) * 4 ));

For (;;){

Register uchar first_char = (uchar) cur_struct;

If (first_char = 0)

{

Register int16 ires = (int16) (cur_struct> 16 );

If (ires = array_elements (symbols) return 0;

Register SYMBOL * res;

If (ires> = 0)

Res = symbols + ires;

Else

Res = SQL _functions-ires-1;

Register uint count = (uint) (cur_str-s );

Return lex_casecmp (cur_str, res-> name + count, len-count )? 0: res;

}

Register uchar cur_char = (uchar) to_upper_lex [(uchar) * cur_str];

If (cur_char

Cur_struct >>= 8;

If (cur_char> (uchar) cur_struct) return 0;

Cur_struct >>= 8;

Cur_struct = uint4korr (hash_map +

(Uint16) cur_struct + cur_char-first_char) * 4 ));

Cur_str ++;

}

} Else {

If (len> symbols_max_len) return 0;

Hash_map = symbols_map;

Register uint32 cur_struct = uint4korr (hash_map + (len-1) * 4 ));

For (;;){

Register uchar first_char = (uchar) cur_struct;

If (first_char = 0 ){

Register int16 ires = (int16) (cur_struct> 16 );

If (ires = array_elements (symbols) return 0;

Register SYMBOL * res = symbols + ires;

Register uint count = (uint) (cur_str-s );

Return lex_casecmp (cur_str, res-> name + count, len-count )! = 0? 0: res;

}

Register uchar cur_char = (uchar) to_upper_lex [(uchar) * cur_str];

If (cur_char

Cur_struct >>= 8;

If (cur_char> (uchar) cur_struct) return 0;

Cur_struct >>= 8;

Cur_struct = uint4korr (hash_map +

(Uint16) cur_struct + cur_char-first_char) * 4 ));

Cur_str ++;

}

}

}

Get_hash_symbol is used to search for keywords in the system. The third parameter function indicates whether to search for system functions. here, it is a system variable, not a function, so it is FALSE. All the keywords are mounted on hash_map, that is, symbols_map. Symbols_maps is a bunch of processed data:

?

Static uchar symbols_map [11828] = {

'<', '>', 29, 0,

'! ',' | ', 32, 0,

'<', 'X', 150, 0,

'B', 'y', 11, 1,

'A', 'W', 147, 2,

'A', 'V', 0, 4,

...

Let's take a look at the top comments of this file to see what useful information is found:

?

1

2

/* Do not edit this file! This is generated by gen_lex_hash.cc

That seeks for a perfect hash function */

When I saw this comment, my mind was very open. Previously, lex_hash.h was generated by gen_lex_hash.cc. do not edit this file by yourself !!

Let's take a look at gen_lex_hash.cc. we can see a main function, which contains some file generation operations. in the generate_find_structs function, we found insert_symbols,

This should be the initialization of our symbols_map array.

?

Void insert_symbols ()

{

Size_t I = 0;

SYMBOL * cur;

For (cur = symbols; I

Hash_lex_struct * root =

Get_hash_struct_by_len (& root_by_len, cur-> length, & max_len );

Insert_cmd_hash (root, cur-> name, 0, (uint) I, 0 );

}

}

We can see that the implementation of the function is to take the array symbols cyclically and find the symbols definition. in the file lex. h, we can see this array, and I think you will understand it:

?

1

{"SELECT", SYM (SELECT_SYM )},

This is where the SELECT string is associated with SELECT_SYM, bingo!

Let's look at the concept of SELECT parsing. after the lexical analysis is parsed to SELECT, execute find_keyword to find out if it is a keyword and find that SELECT is a keyword,

Returns SELECT_SYM to yacc for syntax analysis. Note: To add a keyword, add % token xxx to SQL _yacc.yy,

Then add the corresponding string and SYM to lex. h.

Next, let's take a look at how to resolve the system variable @ version_comment. First, let's give its syntax node:

?

Variable_aux:

...

| '@' Opt_var_ident_type ident_or_text opt_component

{

/* Disallow "SELECT @ global. global. variable "*/

If ($ 3.str & $ 4.str & check_reserved_words (& $3 ))

{

My_parse_error (ER (ER_SYNTAX_ERROR ));

MYSQL_YYABORT;

}

If (! ($ = Get_system_var (YYTHD, $2, $3, $4 )))

MYSQL_YYABORT;

If (! (Item_func_get_system_var *) $)-> is_written_to_binlog ())

Lex-> set_stmt_unsafe ();

}

;

Here is where the system variable is located: get_system_var. let's take a look:

?

Item * get_system_var (THD * thd, enum_var_type var_type, LEX_STRING name,

LEX_STRING component)

{

Sys_var * var;

LEX_STRING * base_name, * component_name;

If (component. str)

{

Base_name = & component;

Component_name = & name;

}

Else

{

Base_name = & name;

Component_name = & component; // Empty string

}

If (! (Var = find_sys_var (thd, base_name-> str, base_name-> length )))

Return 0;

If (component. str)

{

If (! Var-> is_struct ())

{

My_error (ER_VARIABLE_IS_NOT_STRUCT, MYF (0), base_name-> str );

Return 0;

}

}

Thd-> lex-> uncacheable (UNCACHEABLE_SIDEEFFECT );

Set_if_smaller (component_name-> length, MAX_SYS_VAR_LENGTH );

Return new Item_func_get_system_var (var, var_type, component_name,

NULL, 0 );

}

The find_sys_var function keeps following. we followed set_var.cc and found the following definition:

?

1

Static sys_var_chain vars = {NULL, NULL };

System variables are mounted on the secondary chain. Find version_comment in the file:

?

Static sys_var_const_str sys_version_comment (& vars, "version_comment ",

MYSQL_COMPILATION_COMMENT );

?

1

# Define MYSQL_COMPILATION_COMMENT "Source distribution"

This is to load version_comment to the vars linked list.

OK. We can also add our own system variables:

?

Static sys_var_const_str sys_version_comment (& vars, "version_comment ",

MYSQL_COMPILATION_COMMENT );

/** Add by nocode */

Static sys_var_const_str sys_version_comment_test (& vars, "nocode_test_sysvar ",

MYSQL_COMPILATION_NOCODE_TEST_SYSVAR );

# Define MYSQL_COMPILATION_COMMENT "Source distribution"

# Define MYSQL_COMPILATION_NOCODE_TEST_SYSVAR "No code in heart"/* add by nocode */

?

1

Comment out the add by nocode, that is, the newly added system variables and MACRO Definitions. our system variables are called @ nocode_test_sysvar, whose value is No code in heartOK. re-compile the code and execute the SELECT statement, OK.

?

Mysql> select @ nocode_test_sysvar;

+ ---------------------- +

| @ Nocode_test_sysvar |

+ ---------------------- +

| No code in heart |

+ ---------------------- +

1 row in set (0.01 sec)

We added a system variable and didn't modify the syntax file SQL _yacc.yy. to better understand it, we added our own syntax: nocode. to simplify the implementation, our goal is very simple, after the client inputs no_code, the string "make by nocode" is displayed ".

Define keywords

First, add the corresponding SYMBOL to the SQL _yacc.yy file.

?

% Token NO_SYM/* SQL-2003-R */

% Token NO_CODE_SYM/* add by nocode */

% Token NO_WAIT_SYM

Then add the correspondence between nocode strings and symbols to the symblos array in lex. h:

?

{"NO", SYM (NO_SYM )},

{"NO_CODE", SYM (NO_CODE_SYM)},/* add by nocode */

{"NO_WAIT", SYM (NO_WAIT_SYM )},

OK. Now we have added the keyword.

Add a syntax node

We name the syntax branch node nocode as follows:

?

/** Add by nocode */

Nocode:

NO_CODE_SYM

{

THD * thd = YYTHD;

LEX * lex = Lex;

SELECT_LEX * sel = lex-> current_select;

Item_string * field;

LEX_STRING tmp;

CHARSET_INFO * cs_con = thd-> variables. collation_connection;

CHARSET_INFO * cs_cli = thd-> variables. character_set_client;

If (sel-> linkage! = UNION_TYPE)

Mysql_init_select (lex );

Lex-> current_select-> parsing_place = SELECT_LIST;

Uint repertoire = thd-> lex-> text_string_is_7bit &&

My_charset_is_ascii_based (cs_cli )? MY_REPERTOIRE_ASCII: MY_REPERTOIRE_UNICODE30;

Tmp. str = "make by nocode ";

Tmp. length = strlen (tmp. str );

Field = new (thd-> mem_root) Item_string (tmp. str, tmp. length, cs_con,

DERIVATION_COERCIBLE,

Repertoire );

If (field = NULL)

MYSQL_YYABORT;

If (add_item_to_list (thd, field ))

MYSQL_YYABORT;

Select-> parsing_place = NO_MATTER;

Lex-> SQL _command = SQLCOM_SELECT;

}

;

I will add the nocode branch to the syntax node of statement. As long as you read "no_code", it will enter the syntax branch. In this branch, some operations are performed. first, a SELECT statement is constructed and a column is added to it. the column name is "make by nocode "... Let's take a look at the details. this is not the focus of this article.

After adding the syntax, we re-compile the project. it is worth noting that Mysql is still very well organized in the project. after the syntax file is modified, we do not need to compile it by ourselves with bison, the project is automatically compiled for us, which is really good. Restart the server and enter no_code on the client. The result is as follows:

?

Mysql> no_code;

+ ---------------- +

| Make by nocode |

+ ---------------- +

| Make by nocode |

+ ---------------- +

1 row in set (3.02 sec)

Syntax analysis ends here. Here, we only add a very simple syntax branch, which is useless. it mainly introduces the steps for adding a branch. when adding a branch, we should try to use the existing branch to reduce labor volume, it also reduces syntax conflicts. The project is too tight recently and the pressure is high. it is awakened by a nightmare every night. in this nightmare, I always think of various bugs in algorithms, and I am so worried about writing code, IT is a sad reminder. PS finally updated another article, oh yeah,-_-ps again: it is much easier to write a blog with windows live writer for the first time than to write a blog on a webpage ~~, Like


From the innocent bitsCN.com

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.