1 /*
2    Copyright (c) 2000, 2021, Oracle and/or its affiliates.
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License, version 2.0,
6    as published by the Free Software Foundation.
7 
8    This program is also distributed with certain software (including
9    but not limited to OpenSSL) that is licensed under separate terms,
10    as designated in a particular file or component or in included license
11    documentation.  The authors of MySQL hereby grant you an additional
12    permission to link the program and your derivative works with the
13    separately licensed software that they have included with MySQL.
14 
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License, version 2.0, for more details.
19 
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
23 
24 
25 /* A lexical scanner on a temporary buffer with a yacc interface */
26 
27 #include "sql_lex.h"
28 
29 #include "mysql_version.h"             // MYSQL_VERSION_ID
30 #include "sp_head.h"                   // sp_head
31 #include "sql_class.h"                 // THD
32 #include "sql_parse.h"                 // add_to_list
33 #include "parse_tree_helpers.h"
34 #include "sql_hints.yy.h"
35 #include "sql_lex_hints.h"
36 #include "sql_yacc.h"
37 #include "sql_optimizer.h"             // JOIN
38 #include "sql_plugin.h"                // plugin_unlock_list
39 #include "sql_show.h"                  // append_identifier
40 #include "sql_table.h"                 // primary_key_name
41 #include "sql_insert.h"                // Sql_cmd_insert_base
42 #include "lex_token.h"
43 
44 
45 extern int HINT_PARSER_parse(THD *thd,
46                              Hint_scanner *scanner,
47                              PT_hint_list **ret);
48 
49 static int lex_one_token(YYSTYPE *yylval, THD *thd);
50 
51 /*
52   We are using pointer to this variable for distinguishing between assignment
53   to NEW row field (when parsing trigger definition) and structured variable.
54 */
55 
56 sys_var *trg_new_row_fake_var= (sys_var*) 0x01;
57 
58 /**
59   LEX_STRING constant for null-string to be used in parser and other places.
60 */
61 const LEX_STRING null_lex_str= {NULL, 0};
62 const LEX_STRING empty_lex_str= {(char *) "", 0};
63 /**
64   Mapping from enum values in enum_binlog_stmt_unsafe to error codes.
65 
66   @note The order of the elements of this array must correspond to
67   the order of elements in enum_binlog_stmt_unsafe.
68 
69   Todo/fixme Bug#22860121 ER_BINLOG_UNSAFE_* FAMILY OF ERROR CODES IS UNUSED
70     suggests to turn ER_BINLOG_UNSAFE* to private consts/messages.
71 */
72 const int
73 Query_tables_list::binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT] =
74 {
75   ER_BINLOG_UNSAFE_LIMIT,
76   ER_BINLOG_UNSAFE_SYSTEM_TABLE,
77   ER_BINLOG_UNSAFE_AUTOINC_COLUMNS,
78   ER_BINLOG_UNSAFE_UDF,
79   ER_BINLOG_UNSAFE_SYSTEM_VARIABLE,
80   ER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
81   ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS,
82   ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
83   ER_BINLOG_UNSAFE_MIXED_STATEMENT,
84   ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT,
85   ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE,
86   ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT,
87   ER_BINLOG_UNSAFE_REPLACE_SELECT,
88   ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT,
89   ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT,
90   ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC,
91   ER_BINLOG_UNSAFE_UPDATE_IGNORE,
92   ER_BINLOG_UNSAFE_INSERT_TWO_KEYS,
93   ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST,
94   ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN,
95   ER_BINLOG_UNSAFE_XA
96 };
97 
98 
99 /* Longest standard keyword name */
100 
101 #define TOCK_NAME_LENGTH 24
102 
103 /*
104   Names of the index hints (for error messages). Keep in sync with
105   index_hint_type
106 */
107 
108 const char * index_hint_type_name[] =
109 {
110   "IGNORE INDEX",
111   "USE INDEX",
112   "FORCE INDEX"
113 };
114 
115 
116 /**
117   @note The order of the elements of this array must correspond to
118   the order of elements in type_enum
119 */
120 const char *st_select_lex::type_str[SLT_total]=
121 { "NONE",
122   "PRIMARY",
123   "SIMPLE",
124   "DERIVED",
125   "SUBQUERY",
126   "UNION",
127   "UNION RESULT",
128   "MATERIALIZED"
129 };
130 
131 
lex_init(void)132 bool lex_init(void)
133 {
134   DBUG_ENTER("lex_init");
135 
136   for (CHARSET_INFO **cs= all_charsets;
137        cs < all_charsets + array_elements(all_charsets) - 1 ;
138        cs++)
139   {
140     if (*cs && (*cs)->ctype && is_supported_parser_charset(*cs))
141     {
142       if (init_state_maps(*cs))
143         DBUG_RETURN(true); // OOM
144     }
145   }
146 
147   DBUG_RETURN(false);
148 }
149 
150 
lex_free(void)151 void lex_free(void)
152 {					// Call this when daemon ends
153   DBUG_ENTER("lex_free");
154   DBUG_VOID_RETURN;
155 }
156 
157 
158 void
reset()159 st_parsing_options::reset()
160 {
161   allows_variable= TRUE;
162   allows_select_into= TRUE;
163   allows_select_procedure= TRUE;
164 }
165 
166 /**
167  Cleans slave connection info.
168 */
reset()169 void struct_slave_connection::reset()
170 {
171   user= 0;
172   password= 0;
173   plugin_auth= 0;
174   plugin_dir= 0;
175 }
176 
177 /**
178   Perform initialization of Lex_input_stream instance.
179 
180   Basically, a buffer for a pre-processed query. This buffer should be large
181   enough to keep a multi-statement query. The allocation is done once in
182   Lex_input_stream::init() in order to prevent memory pollution when
183   the server is processing large multi-statement queries.
184 */
185 
init(THD * thd,const char * buff,size_t length)186 bool Lex_input_stream::init(THD *thd, const char* buff, size_t length)
187 {
188   DBUG_EXECUTE_IF("bug42064_simulate_oom",
189                   DBUG_SET("+d,simulate_out_of_memory"););
190 
191   query_charset= thd->charset();
192 
193   m_cpp_buf= (char*) thd->alloc(length + 1);
194 
195   DBUG_EXECUTE_IF("bug42064_simulate_oom",
196                   DBUG_SET("-d,bug42064_simulate_oom"););
197 
198   if (m_cpp_buf == NULL)
199     return TRUE;
200 
201   m_thd= thd;
202   reset(buff, length);
203 
204   return FALSE;
205 }
206 
207 
208 /**
209   Prepare Lex_input_stream instance state for use for handling next SQL statement.
210 
211   It should be called between two statements in a multi-statement query.
212   The operation resets the input stream to the beginning-of-parse state,
213   but does not reallocate m_cpp_buf.
214 */
215 
216 void
reset(const char * buffer,size_t length)217 Lex_input_stream::reset(const char *buffer, size_t length)
218 {
219   yylineno= 1;
220   yytoklen= 0;
221   yylval= NULL;
222   lookahead_token= -1;
223   lookahead_yylval= NULL;
224   skip_digest= false;
225   /*
226     Lex_input_stream modifies the query string in one special case (sic!).
227     yyUnput() modifises the string when patching version comments.
228     This is done to prevent newer slaves from executing a different
229     statement than older masters.
230 
231     For now, cast away const here. This means that e.g. SHOW PROCESSLIST
232     can see partially patched query strings. It would be better if we
233     could replicate the query string as is and have the slave take the
234     master version into account.
235   */
236   m_ptr= const_cast<char*>(buffer);
237   m_tok_start= NULL;
238   m_tok_end= NULL;
239   m_end_of_query= buffer + length;
240   m_buf= buffer;
241   m_buf_length= length;
242   m_echo= TRUE;
243   m_cpp_tok_start= NULL;
244   m_cpp_tok_end= NULL;
245   m_body_utf8= NULL;
246   m_cpp_utf8_processed_ptr= NULL;
247   next_state= MY_LEX_START;
248   found_semicolon= NULL;
249   ignore_space= MY_TEST(m_thd->variables.sql_mode & MODE_IGNORE_SPACE);
250   stmt_prepare_mode= FALSE;
251   multi_statements= TRUE;
252   in_comment=NO_COMMENT;
253   m_underscore_cs= NULL;
254   m_cpp_ptr= m_cpp_buf;
255 }
256 
257 
258 /**
259   The operation is called from the parser in order to
260   1) designate the intention to have utf8 body;
261   1) Indicate to the lexer that we will need a utf8 representation of this
262      statement;
263   2) Determine the beginning of the body.
264 
265   @param thd        Thread context.
266   @param begin_ptr  Pointer to the start of the body in the pre-processed
267                     buffer.
268 */
269 
body_utf8_start(THD * thd,const char * begin_ptr)270 void Lex_input_stream::body_utf8_start(THD *thd, const char *begin_ptr)
271 {
272   assert(begin_ptr);
273   assert(m_cpp_buf <= begin_ptr && begin_ptr <= m_cpp_buf + m_buf_length);
274 
275   size_t body_utf8_length=
276     (m_buf_length / thd->variables.character_set_client->mbminlen) *
277     my_charset_utf8_bin.mbmaxlen;
278 
279   m_body_utf8= (char *) thd->alloc(body_utf8_length + 1);
280   m_body_utf8_ptr= m_body_utf8;
281   *m_body_utf8_ptr= 0;
282 
283   m_cpp_utf8_processed_ptr= begin_ptr;
284 }
285 
286 /**
287   @brief The operation appends unprocessed part of pre-processed buffer till
288   the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to end_ptr.
289 
290   The idea is that some tokens in the pre-processed buffer (like character
291   set introducers) should be skipped.
292 
293   Example:
294     CPP buffer: SELECT 'str1', _latin1 'str2';
295     m_cpp_utf8_processed_ptr -- points at the "SELECT ...";
296     In order to skip "_latin1", the following call should be made:
297       body_utf8_append(<pointer to "_latin1 ...">, <pointer to " 'str2'...">)
298 
299   @param ptr      Pointer in the pre-processed buffer, which specifies the
300                   end of the chunk, which should be appended to the utf8
301                   body.
302   @param end_ptr  Pointer in the pre-processed buffer, to which
303                   m_cpp_utf8_processed_ptr will be set in the end of the
304                   operation.
305 */
306 
body_utf8_append(const char * ptr,const char * end_ptr)307 void Lex_input_stream::body_utf8_append(const char *ptr,
308                                         const char *end_ptr)
309 {
310   assert(m_cpp_buf <= ptr && ptr <= m_cpp_buf + m_buf_length);
311   assert(m_cpp_buf <= end_ptr && end_ptr <= m_cpp_buf + m_buf_length);
312 
313   if (!m_body_utf8)
314     return;
315 
316   if (m_cpp_utf8_processed_ptr >= ptr)
317     return;
318 
319   size_t bytes_to_copy= ptr - m_cpp_utf8_processed_ptr;
320 
321   memcpy(m_body_utf8_ptr, m_cpp_utf8_processed_ptr, bytes_to_copy);
322   m_body_utf8_ptr += bytes_to_copy;
323   *m_body_utf8_ptr= 0;
324 
325   m_cpp_utf8_processed_ptr= end_ptr;
326 }
327 
328 
329 /**
330   The operation appends unprocessed part of the pre-processed buffer till
331   the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to ptr.
332 
333   @param ptr  Pointer in the pre-processed buffer, which specifies the end
334               of the chunk, which should be appended to the utf8 body.
335 */
336 
body_utf8_append(const char * ptr)337 void Lex_input_stream::body_utf8_append(const char *ptr)
338 {
339   body_utf8_append(ptr, ptr);
340 }
341 
342 /**
343   The operation converts the specified text literal to the utf8 and appends
344   the result to the utf8-body.
345 
346   @param thd      Thread context.
347   @param txt      Text literal.
348   @param txt_cs   Character set of the text literal.
349   @param end_ptr  Pointer in the pre-processed buffer, to which
350                   m_cpp_utf8_processed_ptr will be set in the end of the
351                   operation.
352 */
353 
body_utf8_append_literal(THD * thd,const LEX_STRING * txt,const CHARSET_INFO * txt_cs,const char * end_ptr)354 void Lex_input_stream::body_utf8_append_literal(THD *thd,
355                                                 const LEX_STRING *txt,
356                                                 const CHARSET_INFO *txt_cs,
357                                                 const char *end_ptr)
358 {
359   if (!m_cpp_utf8_processed_ptr)
360     return;
361 
362   LEX_STRING utf_txt;
363 
364   if (!my_charset_same(txt_cs, &my_charset_utf8_general_ci))
365   {
366     thd->convert_string(&utf_txt,
367                         &my_charset_utf8_general_ci,
368                         txt->str, txt->length,
369                         txt_cs);
370   }
371   else
372   {
373     utf_txt.str= txt->str;
374     utf_txt.length= txt->length;
375   }
376 
377   /* NOTE: utf_txt.length is in bytes, not in symbols. */
378 
379   memcpy(m_body_utf8_ptr, utf_txt.str, utf_txt.length);
380   m_body_utf8_ptr += utf_txt.length;
381   *m_body_utf8_ptr= 0;
382 
383   m_cpp_utf8_processed_ptr= end_ptr;
384 }
385 
add_digest_token(uint token,LEX_YYSTYPE yylval)386 void Lex_input_stream::add_digest_token(uint token, LEX_YYSTYPE yylval)
387 {
388   if (m_digest != NULL)
389   {
390     m_digest= digest_add_token(m_digest, token, yylval);
391   }
392 }
393 
reduce_digest_token(uint token_left,uint token_right)394 void Lex_input_stream::reduce_digest_token(uint token_left, uint token_right)
395 {
396   if (m_digest != NULL)
397   {
398     m_digest= digest_reduce_token(m_digest, token_left, token_right);
399   }
400 }
401 
402 
~LEX()403 LEX::~LEX()
404 {
405   destroy_query_tables_list();
406   plugin_unlock_list(NULL, plugins.begin(), plugins.size());
407   unit= NULL;                     // Created in mem_root - no destructor
408   select_lex= NULL;
409   m_current_select= NULL;
410 }
411 
412 /**
413   Reset a LEX object so that it is ready for a new query preparation
414   and execution.
415   Pointers to query expression and query block objects are set to NULL.
416   This is correct, as they point into a mem_root that has been recycled.
417 */
418 
reset()419 void LEX::reset()
420 {
421   context_stack.empty();
422   unit= NULL;
423   select_lex= NULL;
424   m_current_select= NULL;
425   all_selects_list= NULL;
426   load_set_str_list.empty();
427 
428   bulk_insert_row_cnt= 0;
429 
430   load_update_list.empty();
431   load_value_list.empty();
432 
433   call_value_list.empty();
434 
435   purge_value_list.empty();
436 
437   kill_value_list.empty();
438 
439   set_var_list.empty();
440   param_list.empty();
441   view_list.empty();
442   prepared_stmt_params.empty();
443   auxiliary_table_list.empty();
444   describe= DESCRIBE_NONE;
445   subqueries= false;
446   context_analysis_only= 0;
447   derived_tables= 0;
448   safe_to_cache_query= true;
449   insert_table= NULL;
450   insert_table_leaf= NULL;
451   parsing_options.reset();
452   length= 0;
453   part_info= NULL;
454   duplicates= DUP_ERROR;
455   ignore= false;
456   spname= NULL;
457   sphead= NULL;
458   set_sp_current_parsing_ctx(NULL);
459   m_sql_cmd= NULL;
460   proc_analyse= NULL;
461   query_tables= NULL;
462   reset_query_tables_list(false);
463   expr_allows_subselect= true;
464   use_only_table_context= false;
465   contains_plaintext_password= false;
466   keep_diagnostics= DA_KEEP_NOTHING;
467 
468   name.str= NULL;
469   name.length= 0;
470   event_parse_data= NULL;
471   profile_options= PROFILE_NONE;
472   select_number= 0;
473   allow_sum_func= 0;
474   in_sum_func= NULL;
475   server_options.reset();
476   explain_format= NULL;
477   is_lex_started= true;
478   used_tables= 0;
479   reset_slave_info.all= false;
480   alter_tablespace_info= NULL;
481   mi.channel= NULL;
482 
483   wild= NULL;
484   exchange= NULL;
485   is_set_password_sql= false;
486   mark_broken(false);
487   max_execution_time= 0;
488   parse_gcol_expr= false;
489   opt_hints_global= NULL;
490   binlog_need_explicit_defaults_ts= false;
491 }
492 
493 
494 /**
495   Call lex_start() before every query that is to be prepared and executed.
496   Because of this, it's critical not to do too many things here.  (We already
497   do too much)
498 
499   The function creates a select_lex and a select_lex_unit object.
500   These objects should rather be created by the parser bottom-up.
501 */
502 
lex_start(THD * thd)503 bool lex_start(THD *thd)
504 {
505   DBUG_ENTER("lex_start");
506 
507   LEX *lex= thd->lex;
508 
509   lex->thd= thd;
510   lex->reset();
511   // Initialize the cost model to be used for this query
512   thd->init_cost_model();
513 
514   const bool status= lex->new_top_level_query();
515   assert(lex->current_select() == NULL);
516   lex->m_current_select= lex->select_lex;
517 
518   DBUG_RETURN(status);
519 }
520 
521 
522 /**
523   Call this function after preparation and execution of a query.
524 */
525 
lex_end(LEX * lex)526 void lex_end(LEX *lex)
527 {
528   DBUG_ENTER("lex_end");
529   DBUG_PRINT("enter", ("lex: 0x%lx", (long) lex));
530 
531   /* release used plugins */
532   lex->release_plugins();
533 
534   delete lex->sphead;
535   lex->sphead= NULL;
536 
537   DBUG_VOID_RETURN;
538 }
539 
540 
release_plugins()541 void LEX::release_plugins()
542 {
543   if (!plugins.empty()) /* No function call and no mutex if no plugins. */
544   {
545     plugin_unlock_list(0, plugins.begin(), plugins.size());
546     plugins.clear();
547   }
548 }
549 
550 
551 
new_empty_query_block()552 st_select_lex *LEX::new_empty_query_block()
553 {
554   st_select_lex *select=
555     new (thd->mem_root) st_select_lex(NULL, NULL, NULL, NULL, NULL, NULL);
556   if (select == NULL)
557     return NULL;             /* purecov: inspected */
558 
559   select->parent_lex= this;
560 
561   return select;
562 }
563 
564 
565 /**
566   Create new select_lex_unit and select_lex objects for a query block,
567   which can be either a top-level query or a subquery.
568   For the second and subsequent query block of a UNION query, use
569   LEX::new_union_query() instead.
570   Set the new select_lex as the current select_lex of the LEX object.
571 
572   @param curr_select    current query specification
573 
574   @return new query specification if successful, NULL if error
575 */
new_query(st_select_lex * curr_select)576 st_select_lex *LEX::new_query(st_select_lex *curr_select)
577 {
578   DBUG_ENTER("LEX::new_query");
579 
580   if (curr_select != NULL &&
581       curr_select->nest_level >= (int) MAX_SELECT_NESTING)
582   {
583     my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
584     DBUG_RETURN(NULL);
585   }
586 
587   Name_resolution_context *outer_context= current_context();
588 
589   SELECT_LEX *const select= new_empty_query_block();
590   if (!select)
591     DBUG_RETURN(NULL);       /* purecov: inspected */
592 
593   SELECT_LEX_UNIT *const sel_unit=
594     new (thd->mem_root) SELECT_LEX_UNIT(curr_select ?
595                                         curr_select->parsing_place :
596                                         CTX_NONE);
597   if (!sel_unit)
598     DBUG_RETURN(NULL);       /* purecov: inspected */
599 
600   sel_unit->thd= thd;
601 
602   // Link the new "unit" below the current select_lex, if any
603   if (curr_select != NULL)
604     sel_unit->include_down(this, curr_select);
605 
606   select->include_down(this, sel_unit);
607 
608   select->include_in_global(&all_selects_list);
609 
610   if (select->set_context(NULL))
611     DBUG_RETURN(NULL);        /* purecov: inspected */
612   /*
613     Assume that a subquery has an outer name resolution context.
614     If not (ie. if this is a derived table), set it to NULL later
615   */
616   if (select_lex == NULL)    // Outer-most query block
617   {
618   }
619   else if (select->outer_select()->parsing_place == CTX_ON)
620   {
621     /*
622       This subquery is part of an ON clause, so we need to link the
623       name resolution context for this subquery with the ON context.
624 
625       @todo outer_context is not the same as
626       &select_lex->outer_select()->context in one case:
627         (SELECT 1 as a) UNION (SELECT 2) ORDER BY (SELECT a);
628       When we create the select_lex for the subquery in ORDER BY,
629       1) outer_context is the context of the second SELECT of the UNION
630       2) select_lex->outer_select() is the fake select_lex, which context
631          is the one of the first SELECT of the UNION (see
632          st_select_lex_unit::add_fake_select_lex()).
633       2) is the correct context, per the documentation. 1) is not, and using
634       it leads to a resolving error for the query above.
635       We should fix 1) and then use it unconditionally here.
636     */
637     select->context.outer_context= outer_context;
638   }
639   else if (select->outer_select()->parsing_place == CTX_DERIVED)
640   {
641     // Currently, outer references are not allowed for a derived table
642     assert(select->context.outer_context == NULL);
643   }
644   else
645   {
646     select->context.outer_context= &select->outer_select()->context;
647   }
648   /*
649     in subquery is SELECT query and we allow resolution of names in SELECT
650     list
651   */
652   select->context.resolve_in_select_list= true;
653 
654   DBUG_RETURN(select);
655 }
656 
657 
658 /**
659   Create new select_lex object for all branches of a UNION except the left-most
660   one.
661   Set the new select_lex as the current select_lex of the LEX object.
662 
663   @param curr_select current query specification
664   @param distinct True if part of UNION DISTINCT query
665 
666   @return new query specification if successful, NULL if an error occurred.
667 */
668 
new_union_query(st_select_lex * curr_select,bool distinct)669 st_select_lex *LEX::new_union_query(st_select_lex *curr_select, bool distinct)
670 {
671   DBUG_ENTER("LEX::new_union_query");
672 
673   assert(unit != NULL && select_lex != NULL);
674 
675   // Is this the outer-most query expression?
676   bool const outer_most= curr_select->master_unit() == unit;
677   /*
678      Only the last SELECT can have INTO. Since the grammar won't allow INTO in
679      a nested SELECT, we make this check only when creating a query block on
680      the outer-most level:
681   */
682   if (outer_most && result)
683   {
684     my_error(ER_WRONG_USAGE, MYF(0), "UNION", "INTO");
685     DBUG_RETURN(NULL);
686   }
687   if (proc_analyse)
688   {
689     my_error(ER_WRONG_USAGE, MYF(0), "UNION", "SELECT ... PROCEDURE ANALYSE()");
690     DBUG_RETURN(NULL);
691   }
692 
693   if (curr_select->order_list.first && !curr_select->braces)
694   {
695     my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
696     DBUG_RETURN(NULL);
697   }
698 
699   if (curr_select->explicit_limit && !curr_select->braces)
700   {
701     my_error(ER_WRONG_USAGE, MYF(0), "UNION", "LIMIT");
702     DBUG_RETURN(NULL);
703   }
704 
705   SELECT_LEX *const select= new_empty_query_block();
706   if (!select)
707     DBUG_RETURN(NULL);       /* purecov: inspected */
708 
709   select->include_neighbour(this, curr_select);
710 
711   SELECT_LEX_UNIT *const sel_unit= select->master_unit();
712 
713   if (!sel_unit->fake_select_lex && sel_unit->add_fake_select_lex(thd))
714     DBUG_RETURN(NULL);       /* purecov: inspected */
715 
716   if (select->set_context(sel_unit->first_select()->context.outer_context))
717     DBUG_RETURN(NULL);       /* purecov: inspected */
718 
719   select->include_in_global(&all_selects_list);
720 
721   select->linkage= UNION_TYPE;
722 
723   if (distinct)           /* UNION DISTINCT - remember position */
724     sel_unit->union_distinct= select;
725 
726   /*
727     By default we assume that this is a regular subquery, in which resolution
728     of names in SELECT list is allowed.
729   */
730   select->context.resolve_in_select_list= true;
731 
732   DBUG_RETURN(select);
733 }
734 
735 
736 /**
737   Given a LEX object, create a query expression object (select_lex_unit) and
738   a query block object (select_lex).
739 
740   @return false if successful, true if error
741 */
742 
new_top_level_query()743 bool LEX::new_top_level_query()
744 {
745   DBUG_ENTER("LEX::new_top_level_query");
746 
747   // Assure that the LEX does not contain any query expression already
748   assert(unit == NULL &&
749          select_lex == NULL);
750 
751   // Check for the special situation when using INTO OUTFILE and LOAD DATA.
752   assert(result == 0);
753 
754   select_lex= new_query(NULL);
755   if (select_lex == NULL)
756     DBUG_RETURN(true);     /* purecov: inspected */
757 
758   unit= select_lex->master_unit();
759 
760   DBUG_RETURN(false);
761 }
762 
763 
764 /**
765   Initialize a LEX object, a query expression object (select_lex_unit) and
766   a query block object (select_lex).
767   All objects are passed as pointers so they can be stack-allocated.
768   The purpose of this structure is for short-lived procedures that need a
769   LEX and a query block object.
770 
771   Do not extend the struct with more query objects after creation.
772 
773   The struct can be abandoned after use, no cleanup is needed.
774 
775   @param sel_unit  Pointer to the query expression object
776   @param select    Pointer to the query block object
777 */
778 
new_static_query(SELECT_LEX_UNIT * sel_unit,SELECT_LEX * select)779 void LEX::new_static_query(SELECT_LEX_UNIT *sel_unit, SELECT_LEX *select)
780 
781 {
782   DBUG_ENTER("LEX::new_static_query");
783 
784   reset();
785 
786   assert(unit == NULL && select_lex == NULL && current_select() == NULL);
787 
788   select->parent_lex= this;
789 
790   sel_unit->thd= thd;
791   select->include_down(this, sel_unit);
792 
793   select->include_in_global(&all_selects_list);
794 
795   (void)select->set_context(NULL);
796 
797   select_lex= select;
798   unit= sel_unit;
799 
800   set_current_select(select);
801 
802   select->context.resolve_in_select_list= true;
803 
804   DBUG_VOID_RETURN;
805 }
806 
807 
~Yacc_state()808 Yacc_state::~Yacc_state()
809 {
810   if (yacc_yyss)
811   {
812     my_free(yacc_yyss);
813     my_free(yacc_yyvs);
814     my_free(yacc_yyls);
815   }
816 }
817 
818 
consume_optimizer_hints(Lex_input_stream * lip)819 static bool consume_optimizer_hints(Lex_input_stream *lip)
820 {
821   const my_lex_states *state_map= lip->query_charset->state_maps->main_map;
822   int whitespace= 0;
823   uchar c= lip->yyPeek();
824   size_t newlines= 0;
825 
826   for (; state_map[c] == MY_LEX_SKIP; whitespace++, c= lip->yyPeekn(whitespace))
827   {
828     if (c == '\n')
829       newlines++;
830   }
831 
832   if (lip->yyPeekn(whitespace) == '/' && lip->yyPeekn(whitespace + 1) == '*' &&
833       lip->yyPeekn(whitespace + 2) == '+')
834   {
835     lip->yylineno+= newlines;
836     lip->yySkipn(whitespace); // skip whitespace
837 
838     Hint_scanner hint_scanner(lip->m_thd, lip->yylineno, lip->get_ptr(),
839                               lip->get_end_of_query() - lip->get_ptr(),
840                               lip->m_digest);
841     PT_hint_list *hint_list= NULL;
842     int rc= HINT_PARSER_parse(lip->m_thd, &hint_scanner, &hint_list);
843     if (rc == 2)
844       return true; // Bison's internal OOM error
845     else if (rc == 1)
846     {
847       /*
848         This branch is for 2 cases:
849         1. YYABORT in the hint parser grammar (we use it to process OOM errors),
850         2. open commentary error.
851       */
852       lip->start_token(); // adjust error message text pointer to "/*+"
853       return true;
854     }
855     else
856     {
857       lip->yylineno= hint_scanner.get_lineno();
858       lip->yySkipn(hint_scanner.get_ptr() - lip->get_ptr());
859       lip->yylval->optimizer_hints= hint_list; // NULL in case of syntax error
860       lip->m_digest= hint_scanner.get_digest(); // NULL is digest buf. is full.
861       return false;
862     }
863   }
864   else
865     return false;
866 }
867 
868 
find_keyword(Lex_input_stream * lip,uint len,bool function)869 static int find_keyword(Lex_input_stream *lip, uint len, bool function)
870 {
871   const char *tok= lip->get_tok_start();
872 
873   const SYMBOL *symbol= function ?
874     Lex_hash::sql_keywords_and_funcs.get_hash_symbol(tok, len) :
875     Lex_hash::sql_keywords.get_hash_symbol(tok, len);
876 
877   if (symbol)
878   {
879     lip->yylval->symbol.symbol=symbol;
880     lip->yylval->symbol.str= (char*) tok;
881     lip->yylval->symbol.length=len;
882 
883     if ((symbol->tok == NOT_SYM) &&
884         (lip->m_thd->variables.sql_mode & MODE_HIGH_NOT_PRECEDENCE))
885       return NOT2_SYM;
886     if ((symbol->tok == OR_OR_SYM) &&
887 	!(lip->m_thd->variables.sql_mode & MODE_PIPES_AS_CONCAT))
888       return OR2_SYM;
889 
890     lip->yylval->optimizer_hints= NULL;
891     if (symbol->group & SG_HINTABLE_KEYWORDS)
892     {
893       lip->add_digest_token(symbol->tok, lip->yylval);
894       if (consume_optimizer_hints(lip))
895         return ABORT_SYM;
896       lip->skip_digest= true;
897     }
898 
899     return symbol->tok;
900   }
901   return 0;
902 }
903 
904 /*
905   Check if name is a keyword
906 
907   SYNOPSIS
908     is_keyword()
909     name      checked name (must not be empty)
910     len       length of checked name
911 
912   RETURN VALUES
913     0         name is a keyword
914     1         name isn't a keyword
915 */
916 
is_keyword(const char * name,size_t len)917 bool is_keyword(const char *name, size_t len)
918 {
919   assert(len != 0);
920   return Lex_hash::sql_keywords.get_hash_symbol(name, len) != NULL;
921 }
922 
923 /**
924   Check if name is a sql function
925 
926     @param name      checked name
927 
928     @return is this a native function or not
929     @retval 0         name is a function
930     @retval 1         name isn't a function
931 */
932 
is_lex_native_function(const LEX_STRING * name)933 bool is_lex_native_function(const LEX_STRING *name)
934 {
935   assert(name != NULL);
936   return Lex_hash::sql_keywords_and_funcs.get_hash_symbol(name->str,
937       (uint) name->length) != NULL;
938 }
939 
940 /* make a copy of token before ptr and set yytoklen */
941 
get_token(Lex_input_stream * lip,uint skip,uint length)942 static LEX_STRING get_token(Lex_input_stream *lip, uint skip, uint length)
943 {
944   LEX_STRING tmp;
945   lip->yyUnget();                       // ptr points now after last token char
946   tmp.length=lip->yytoklen=length;
947   tmp.str= lip->m_thd->strmake(lip->get_tok_start() + skip, tmp.length);
948 
949   lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
950   lip->m_cpp_text_end= lip->m_cpp_text_start + tmp.length;
951 
952   return tmp;
953 }
954 
955 /*
956  todo:
957    There are no dangerous charsets in mysql for function
958    get_quoted_token yet. But it should be fixed in the
959    future to operate multichar strings (like ucs2)
960 */
961 
get_quoted_token(Lex_input_stream * lip,uint skip,uint length,char quote)962 static LEX_STRING get_quoted_token(Lex_input_stream *lip,
963                                    uint skip,
964                                    uint length, char quote)
965 {
966   LEX_STRING tmp;
967   const char *from, *end;
968   char *to;
969   lip->yyUnget();                       // ptr points now after last token char
970   tmp.length= lip->yytoklen=length;
971   tmp.str=(char*) lip->m_thd->alloc(tmp.length+1);
972   from= lip->get_tok_start() + skip;
973   to= tmp.str;
974   end= to+length;
975 
976   lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
977   lip->m_cpp_text_end= lip->m_cpp_text_start + length;
978 
979   for ( ; to != end; )
980   {
981     if ((*to++= *from++) == quote)
982     {
983       from++;					// Skip double quotes
984       lip->m_cpp_text_start++;
985     }
986   }
987   *to= 0;					// End null for safety
988   return tmp;
989 }
990 
991 
992 /*
993   Return an unescaped text literal without quotes
994   Fix sometimes to do only one scan of the string
995 */
996 
get_text(Lex_input_stream * lip,int pre_skip,int post_skip)997 static char *get_text(Lex_input_stream *lip, int pre_skip, int post_skip)
998 {
999   uchar c,sep;
1000   uint found_escape=0;
1001   const CHARSET_INFO *cs= lip->m_thd->charset();
1002 
1003   lip->tok_bitmap= 0;
1004   sep= lip->yyGetLast();                        // String should end with this
1005   while (! lip->eof())
1006   {
1007     c= lip->yyGet();
1008     lip->tok_bitmap|= c;
1009     {
1010       int l;
1011       if (use_mb(cs) &&
1012           (l = my_ismbchar(cs,
1013                            lip->get_ptr() -1,
1014                            lip->get_end_of_query()))) {
1015         lip->skip_binary(l-1);
1016         continue;
1017       }
1018     }
1019     if (c == '\\' &&
1020         !(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))
1021     {					// Escaped character
1022       found_escape=1;
1023       if (lip->eof())
1024 	return 0;
1025       lip->yySkip();
1026     }
1027     else if (c == sep)
1028     {
1029       if (c == lip->yyGet())            // Check if two separators in a row
1030       {
1031         found_escape=1;                 // duplicate. Remember for delete
1032 	continue;
1033       }
1034       else
1035         lip->yyUnget();
1036 
1037       /* Found end. Unescape and return string */
1038       const char *str, *end;
1039       char *start;
1040 
1041       str= lip->get_tok_start();
1042       end= lip->get_ptr();
1043       /* Extract the text from the token */
1044       str += pre_skip;
1045       end -= post_skip;
1046       assert(end >= str);
1047 
1048       if (!(start= static_cast<char *>(lip->m_thd->alloc((uint) (end-str)+1))))
1049 	return (char*) "";		// Sql_alloc has set error flag
1050 
1051       lip->m_cpp_text_start= lip->get_cpp_tok_start() + pre_skip;
1052       lip->m_cpp_text_end= lip->get_cpp_ptr() - post_skip;
1053 
1054       if (!found_escape)
1055       {
1056 	lip->yytoklen=(uint) (end-str);
1057 	memcpy(start,str,lip->yytoklen);
1058 	start[lip->yytoklen]=0;
1059       }
1060       else
1061       {
1062         char *to;
1063 
1064 	for (to=start ; str != end ; str++)
1065 	{
1066 	  int l;
1067 	  if (use_mb(cs) &&
1068               (l = my_ismbchar(cs, str, end))) {
1069 	      while (l--)
1070 		  *to++ = *str++;
1071 	      str--;
1072 	      continue;
1073 	  }
1074 	  if (!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
1075               *str == '\\' && str+1 != end)
1076 	  {
1077 	    switch(*++str) {
1078 	    case 'n':
1079 	      *to++='\n';
1080 	      break;
1081 	    case 't':
1082 	      *to++= '\t';
1083 	      break;
1084 	    case 'r':
1085 	      *to++ = '\r';
1086 	      break;
1087 	    case 'b':
1088 	      *to++ = '\b';
1089 	      break;
1090 	    case '0':
1091 	      *to++= 0;			// Ascii null
1092 	      break;
1093 	    case 'Z':			// ^Z must be escaped on Win32
1094 	      *to++='\032';
1095 	      break;
1096 	    case '_':
1097 	    case '%':
1098 	      *to++= '\\';		// remember prefix for wildcard
1099 	      /* Fall through */
1100 	    default:
1101               *to++= *str;
1102 	      break;
1103 	    }
1104 	  }
1105 	  else if (*str == sep)
1106 	    *to++= *str++;		// Two ' or "
1107 	  else
1108 	    *to++ = *str;
1109 	}
1110 	*to=0;
1111 	lip->yytoklen=(uint) (to-start);
1112       }
1113       return start;
1114     }
1115   }
1116   return 0;					// unexpected end of query
1117 }
1118 
1119 
get_lineno(const char * raw_ptr)1120 uint Lex_input_stream::get_lineno(const char *raw_ptr)
1121 {
1122   assert(m_buf <= raw_ptr && raw_ptr < m_end_of_query);
1123   if (!(m_buf <= raw_ptr && raw_ptr < m_end_of_query))
1124     return 1;
1125 
1126   uint ret= 1;
1127   const CHARSET_INFO *cs= m_thd->charset();
1128   for (const char *c= m_buf; c < raw_ptr; c++)
1129   {
1130     uint mb_char_len;
1131     if (use_mb(cs) && (mb_char_len= my_ismbchar(cs, c, m_end_of_query)))
1132     {
1133       c+= mb_char_len - 1; // skip the rest of the multibyte character
1134       continue; // we don't expect '\n' there
1135     }
1136     if (*c == '\n')
1137       ret++;
1138   }
1139   return ret;
1140 }
1141 
1142 
1143 /*
1144 ** Calc type of integer; long integer, longlong integer or real.
1145 ** Returns smallest type that match the string.
1146 ** When using unsigned long long values the result is converted to a real
1147 ** because else they will be unexpected sign changes because all calculation
1148 ** is done with longlong or double.
1149 */
1150 
1151 static const char *long_str="2147483647";
1152 static const uint long_len=10;
1153 static const char *signed_long_str="-2147483648";
1154 static const char *longlong_str="9223372036854775807";
1155 static const uint longlong_len=19;
1156 static const char *signed_longlong_str="-9223372036854775808";
1157 static const uint signed_longlong_len=19;
1158 static const char *unsigned_longlong_str="18446744073709551615";
1159 static const uint unsigned_longlong_len=20;
1160 
int_token(const char * str,uint length)1161 static inline uint int_token(const char *str,uint length)
1162 {
1163   if (length < long_len)			// quick normal case
1164     return NUM;
1165   bool neg=0;
1166 
1167   if (*str == '+')				// Remove sign and pre-zeros
1168   {
1169     str++; length--;
1170   }
1171   else if (*str == '-')
1172   {
1173     str++; length--;
1174     neg=1;
1175   }
1176   while (*str == '0' && length)
1177   {
1178     str++; length --;
1179   }
1180   if (length < long_len)
1181     return NUM;
1182 
1183   uint smaller,bigger;
1184   const char *cmp;
1185   if (neg)
1186   {
1187     if (length == long_len)
1188     {
1189       cmp= signed_long_str+1;
1190       smaller=NUM;				// If <= signed_long_str
1191       bigger=LONG_NUM;				// If >= signed_long_str
1192     }
1193     else if (length < signed_longlong_len)
1194       return LONG_NUM;
1195     else if (length > signed_longlong_len)
1196       return DECIMAL_NUM;
1197     else
1198     {
1199       cmp=signed_longlong_str+1;
1200       smaller=LONG_NUM;				// If <= signed_longlong_str
1201       bigger=DECIMAL_NUM;
1202     }
1203   }
1204   else
1205   {
1206     if (length == long_len)
1207     {
1208       cmp= long_str;
1209       smaller=NUM;
1210       bigger=LONG_NUM;
1211     }
1212     else if (length < longlong_len)
1213       return LONG_NUM;
1214     else if (length > longlong_len)
1215     {
1216       if (length > unsigned_longlong_len)
1217         return DECIMAL_NUM;
1218       cmp=unsigned_longlong_str;
1219       smaller=ULONGLONG_NUM;
1220       bigger=DECIMAL_NUM;
1221     }
1222     else
1223     {
1224       cmp=longlong_str;
1225       smaller=LONG_NUM;
1226       bigger= ULONGLONG_NUM;
1227     }
1228   }
1229   while (*cmp && *cmp++ == *str++) ;
1230   return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
1231 }
1232 
1233 
1234 /**
1235   Given a stream that is advanced to the first contained character in
1236   an open comment, consume the comment.  Optionally, if we are allowed,
1237   recurse so that we understand comments within this current comment.
1238 
1239   At this level, we do not support version-condition comments.  We might
1240   have been called with having just passed one in the stream, though.  In
1241   that case, we probably want to tolerate mundane comments inside.  Thus,
1242   the case for recursion.
1243 
1244   @retval  Whether EOF reached before comment is closed.
1245 */
consume_comment(Lex_input_stream * lip,int remaining_recursions_permitted)1246 bool consume_comment(Lex_input_stream *lip, int remaining_recursions_permitted)
1247 {
1248   // only one level of nested comments are allowed
1249   assert(remaining_recursions_permitted == 0 ||
1250          remaining_recursions_permitted == 1);
1251   uchar c;
1252   while (! lip->eof())
1253   {
1254     c= lip->yyGet();
1255 
1256     if (remaining_recursions_permitted == 1)
1257     {
1258       if ((c == '/') && (lip->yyPeek() == '*'))
1259       {
1260         lip->yyUnput('(');  // Replace nested "/*..." with "(*..."
1261         lip->yySkip();      // and skip "("
1262 
1263         lip->yySkip(); /* Eat asterisk */
1264         if (consume_comment(lip, 0))
1265           return true;
1266 
1267         lip->yyUnput(')');  // Replace "...*/" with "...*)"
1268         lip->yySkip();      // and skip ")"
1269         continue;
1270       }
1271     }
1272 
1273     if (c == '*')
1274     {
1275       if (lip->yyPeek() == '/')
1276       {
1277         lip->yySkip(); /* Eat slash */
1278         return FALSE;
1279       }
1280     }
1281 
1282     if (c == '\n')
1283       lip->yylineno++;
1284   }
1285 
1286   return TRUE;
1287 }
1288 
1289 
1290 /*
1291   yylex() function implementation for the main parser
1292 
1293   @param yylval         [out]  semantic value of the token being parsed (yylval)
1294   @param yylloc         [out]  "location" of the token being parsed (yylloc)
1295   @param thd            THD
1296 
1297   @return               token number
1298 
1299   @note
1300   MYSQLlex remember the following states from the following MYSQLlex():
1301 
1302   - MY_LEX_EOQ			Found end of query
1303   - MY_LEX_OPERATOR_OR_IDENT	Last state was an ident, text or number
1304 				(which can't be followed by a signed number)
1305 */
1306 
MYSQLlex(YYSTYPE * yylval,YYLTYPE * yylloc,THD * thd)1307 int MYSQLlex(YYSTYPE *yylval, YYLTYPE *yylloc, THD *thd)
1308 {
1309   Lex_input_stream *lip= & thd->m_parser_state->m_lip;
1310   int token;
1311 
1312   if (thd->is_error())
1313   {
1314     if (thd->get_parser_da()->has_sql_condition(ER_CAPACITY_EXCEEDED))
1315       return ABORT_SYM;
1316   }
1317 
1318   if (lip->lookahead_token >= 0)
1319   {
1320     /*
1321       The next token was already parsed in advance,
1322       return it.
1323     */
1324     token= lip->lookahead_token;
1325     lip->lookahead_token= -1;
1326     *yylval= *(lip->lookahead_yylval);
1327     yylloc->cpp.start= lip->get_cpp_tok_start();
1328     yylloc->cpp.end= lip->get_cpp_ptr();
1329     yylloc->raw.start= lip->get_tok_start();
1330     yylloc->raw.end= lip->get_ptr();
1331     lip->lookahead_yylval= NULL;
1332     lip->add_digest_token(token, yylval);
1333     return token;
1334   }
1335 
1336   token= lex_one_token(yylval, thd);
1337   yylloc->cpp.start= lip->get_cpp_tok_start();
1338   yylloc->raw.start= lip->get_tok_start();
1339 
1340   switch(token) {
1341   case WITH:
1342     /*
1343       Parsing 'WITH' 'ROLLUP' or 'WITH' 'CUBE' requires 2 look ups,
1344       which makes the grammar LALR(2).
1345       Replace by a single 'WITH_ROLLUP' or 'WITH_CUBE' token,
1346       to transform the grammar into a LALR(1) grammar,
1347       which sql_yacc.yy can process.
1348     */
1349     token= lex_one_token(yylval, thd);
1350     switch(token) {
1351     case CUBE_SYM:
1352       yylloc->cpp.end= lip->get_cpp_ptr();
1353       yylloc->raw.end= lip->get_ptr();
1354       lip->add_digest_token(WITH_CUBE_SYM, yylval);
1355       return WITH_CUBE_SYM;
1356     case ROLLUP_SYM:
1357       yylloc->cpp.end= lip->get_cpp_ptr();
1358       yylloc->raw.end= lip->get_ptr();
1359       lip->add_digest_token(WITH_ROLLUP_SYM, yylval);
1360       return WITH_ROLLUP_SYM;
1361     default:
1362       /*
1363         Save the token following 'WITH'
1364       */
1365       lip->lookahead_yylval= lip->yylval;
1366       lip->yylval= NULL;
1367       lip->lookahead_token= token;
1368       yylloc->cpp.end= lip->get_cpp_ptr();
1369       yylloc->raw.end= lip->get_ptr();
1370       lip->add_digest_token(WITH, yylval);
1371       return WITH;
1372     }
1373     break;
1374   }
1375 
1376   yylloc->cpp.end= lip->get_cpp_ptr();
1377   yylloc->raw.end= lip->get_ptr();
1378   if (!lip->skip_digest)
1379     lip->add_digest_token(token, yylval);
1380   lip->skip_digest= false;
1381   return token;
1382 }
1383 
lex_one_token(YYSTYPE * yylval,THD * thd)1384 static int lex_one_token(YYSTYPE *yylval, THD *thd)
1385 {
1386   uchar c= 0;
1387   bool comment_closed;
1388   int tokval, result_state;
1389   uint length;
1390   enum my_lex_states state;
1391   Lex_input_stream *lip= & thd->m_parser_state->m_lip;
1392   const CHARSET_INFO *cs= thd->charset();
1393   const my_lex_states *state_map= cs->state_maps->main_map;
1394   const uchar *ident_map= cs->ident_map;
1395 
1396   lip->yylval=yylval;			// The global state
1397 
1398   lip->start_token();
1399   state=lip->next_state;
1400   lip->next_state=MY_LEX_OPERATOR_OR_IDENT;
1401   for (;;)
1402   {
1403     switch (state) {
1404     case MY_LEX_OPERATOR_OR_IDENT:	// Next is operator or keyword
1405     case MY_LEX_START:			// Start of token
1406       // Skip starting whitespace
1407       while(state_map[c= lip->yyPeek()] == MY_LEX_SKIP)
1408       {
1409 	if (c == '\n')
1410 	  lip->yylineno++;
1411 
1412         lip->yySkip();
1413       }
1414 
1415       /* Start of real token */
1416       lip->restart_token();
1417       c= lip->yyGet();
1418       state= state_map[c];
1419       break;
1420     case MY_LEX_ESCAPE:
1421       if (lip->yyGet() == 'N')
1422       {					// Allow \N as shortcut for NULL
1423         push_deprecated_warn(thd, "\\N", "NULL");
1424 	yylval->lex_str.str=(char*) "\\N";
1425 	yylval->lex_str.length=2;
1426 	return NULL_SYM;
1427       }
1428       // Fall through.
1429     case MY_LEX_CHAR:			// Unknown or single char token
1430     case MY_LEX_SKIP:			// This should not happen
1431       if (c == '-' && lip->yyPeek() == '-' &&
1432           (my_isspace(cs,lip->yyPeekn(1)) ||
1433            my_iscntrl(cs,lip->yyPeekn(1))))
1434       {
1435         state=MY_LEX_COMMENT;
1436         break;
1437       }
1438 
1439       if (c == '-' && lip->yyPeek() == '>')    // '->'
1440       {
1441         lip->yySkip();
1442         lip->next_state= MY_LEX_START;
1443         if (lip->yyPeek() == '>')
1444         {
1445           lip->yySkip();
1446           return JSON_UNQUOTED_SEPARATOR_SYM;
1447         }
1448         return JSON_SEPARATOR_SYM;
1449       }
1450 
1451       if (c != ')')
1452 	lip->next_state= MY_LEX_START;	// Allow signed numbers
1453 
1454       if (c == ',')
1455       {
1456         /*
1457           Warning:
1458           This is a work around, to make the "remember_name" rule in
1459           sql/sql_yacc.yy work properly.
1460           The problem is that, when parsing "select expr1, expr2",
1461           the code generated by bison executes the *pre* action
1462           remember_name (see select_item) *before* actually parsing the
1463           first token of expr2.
1464         */
1465         lip->restart_token();
1466       }
1467       else
1468       {
1469         /*
1470           Check for a placeholder: it should not precede a possible identifier
1471           because of binlogging: when a placeholder is replaced with
1472           its value in a query for the binlog, the query must stay
1473           grammatically correct.
1474         */
1475         if (c == '?' && lip->stmt_prepare_mode && !ident_map[lip->yyPeek()])
1476         return(PARAM_MARKER);
1477       }
1478 
1479       return((int) c);
1480 
1481     case MY_LEX_IDENT_OR_NCHAR:
1482       if (lip->yyPeek() != '\'')
1483       {
1484 	state= MY_LEX_IDENT;
1485 	break;
1486       }
1487       /* Found N'string' */
1488       lip->yySkip();                         // Skip '
1489       if (!(yylval->lex_str.str = get_text(lip, 2, 1)))
1490       {
1491 	state= MY_LEX_CHAR;             // Read char by char
1492 	break;
1493       }
1494       yylval->lex_str.length= lip->yytoklen;
1495       return(NCHAR_STRING);
1496 
1497     case MY_LEX_IDENT_OR_HEX:
1498       if (lip->yyPeek() == '\'')
1499       {					// Found x'hex-number'
1500 	state= MY_LEX_HEX_NUMBER;
1501 	break;
1502       }
1503       // Fall through.
1504     case MY_LEX_IDENT_OR_BIN:
1505       if (lip->yyPeek() == '\'')
1506       {                                 // Found b'bin-number'
1507         state= MY_LEX_BIN_NUMBER;
1508         break;
1509       }
1510       // Fall through.
1511     case MY_LEX_IDENT:
1512       const char *start;
1513       if (use_mb(cs))
1514       {
1515 	result_state= IDENT_QUOTED;
1516         switch (my_mbcharlen(cs, lip->yyGetLast()))
1517         {
1518         case 1:
1519           break;
1520         case 0:
1521           if (my_mbmaxlenlen(cs) < 2)
1522             break;
1523           /* else fall through */
1524         default:
1525           int l = my_ismbchar(cs,
1526                               lip->get_ptr() -1,
1527                               lip->get_end_of_query());
1528           if (l == 0) {
1529             state = MY_LEX_CHAR;
1530             continue;
1531           }
1532           lip->skip_binary(l - 1);
1533         }
1534         while (ident_map[c=lip->yyGet()])
1535         {
1536           switch (my_mbcharlen(cs, c))
1537           {
1538           case 1:
1539             break;
1540           case 0:
1541             if (my_mbmaxlenlen(cs) < 2)
1542               break;
1543             /* else fall through */
1544           default:
1545             int l;
1546             if ((l = my_ismbchar(cs,
1547                                  lip->get_ptr() -1,
1548                                  lip->get_end_of_query())) == 0)
1549               break;
1550             lip->skip_binary(l-1);
1551           }
1552         }
1553       }
1554       else
1555       {
1556         for (result_state= c; ident_map[c= lip->yyGet()]; result_state|= c) ;
1557         /* If there were non-ASCII characters, mark that we must convert */
1558         result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1559       }
1560       length= lip->yyLength();
1561       start= lip->get_ptr();
1562       if (lip->ignore_space)
1563       {
1564         /*
1565           If we find a space then this can't be an identifier. We notice this
1566           below by checking start != lex->ptr.
1567         */
1568         for (; state_map[c] == MY_LEX_SKIP ; c= lip->yyGet()) ;
1569       }
1570       if (start == lip->get_ptr() && c == '.' && ident_map[lip->yyPeek()])
1571 	lip->next_state=MY_LEX_IDENT_SEP;
1572       else
1573       {					// '(' must follow directly if function
1574         lip->yyUnget();
1575 	if ((tokval = find_keyword(lip, length, c == '(')))
1576 	{
1577 	  lip->next_state= MY_LEX_START;	// Allow signed numbers
1578 	  return(tokval);		// Was keyword
1579 	}
1580         lip->yySkip();                  // next state does a unget
1581       }
1582       yylval->lex_str=get_token(lip, 0, length);
1583 
1584       /*
1585          Note: "SELECT _bla AS 'alias'"
1586          _bla should be considered as a IDENT if charset haven't been found.
1587          So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
1588          producing an error.
1589       */
1590 
1591       if (yylval->lex_str.str[0] == '_')
1592       {
1593         CHARSET_INFO *cs= get_charset_by_csname(yylval->lex_str.str + 1,
1594                                                 MY_CS_PRIMARY, MYF(0));
1595         if (cs)
1596         {
1597           yylval->charset= cs;
1598           lip->m_underscore_cs= cs;
1599 
1600           lip->body_utf8_append(lip->m_cpp_text_start,
1601                                 lip->get_cpp_tok_start() + length);
1602           return(UNDERSCORE_CHARSET);
1603         }
1604       }
1605 
1606       lip->body_utf8_append(lip->m_cpp_text_start);
1607 
1608       lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1609                                     lip->m_cpp_text_end);
1610 
1611       return(result_state);			// IDENT or IDENT_QUOTED
1612 
1613     case MY_LEX_IDENT_SEP:		// Found ident and now '.'
1614       yylval->lex_str.str= (char*) lip->get_ptr();
1615       yylval->lex_str.length= 1;
1616       c= lip->yyGet();                  // should be '.'
1617       lip->next_state= MY_LEX_IDENT_START;// Next is an ident (not a keyword)
1618       if (!ident_map[lip->yyPeek()])            // Probably ` or "
1619 	lip->next_state= MY_LEX_START;
1620       return((int) c);
1621 
1622     case MY_LEX_NUMBER_IDENT:		// number or ident which num-start
1623       if (lip->yyGetLast() == '0')
1624       {
1625         c= lip->yyGet();
1626         if (c == 'x')
1627         {
1628           while (my_isxdigit(cs,(c = lip->yyGet()))) ;
1629           if ((lip->yyLength() >= 3) && !ident_map[c])
1630           {
1631             /* skip '0x' */
1632             yylval->lex_str=get_token(lip, 2, lip->yyLength()-2);
1633             return (HEX_NUM);
1634           }
1635           lip->yyUnget();
1636           state= MY_LEX_IDENT_START;
1637           break;
1638         }
1639         else if (c == 'b')
1640         {
1641           while ((c= lip->yyGet()) == '0' || c == '1') ;
1642           if ((lip->yyLength() >= 3) && !ident_map[c])
1643           {
1644             /* Skip '0b' */
1645             yylval->lex_str= get_token(lip, 2, lip->yyLength()-2);
1646             return (BIN_NUM);
1647           }
1648           lip->yyUnget();
1649           state= MY_LEX_IDENT_START;
1650           break;
1651         }
1652         lip->yyUnget();
1653       }
1654 
1655       while (my_isdigit(cs, (c = lip->yyGet()))) ;
1656       if (!ident_map[c])
1657       {					// Can't be identifier
1658 	state=MY_LEX_INT_OR_REAL;
1659 	break;
1660       }
1661       if (c == 'e' || c == 'E')
1662       {
1663 	// The following test is written this way to allow numbers of type 1e1
1664         if (my_isdigit(cs,lip->yyPeek()) ||
1665             (c=(lip->yyGet())) == '+' || c == '-')
1666 	{				// Allow 1E+10
1667           if (my_isdigit(cs,lip->yyPeek()))     // Number must have digit after sign
1668 	  {
1669             lip->yySkip();
1670             while (my_isdigit(cs,lip->yyGet())) ;
1671             yylval->lex_str=get_token(lip, 0, lip->yyLength());
1672 	    return(FLOAT_NUM);
1673 	  }
1674 	}
1675         lip->yyUnget();
1676       }
1677       // fall through
1678     case MY_LEX_IDENT_START:			// We come here after '.'
1679       result_state= IDENT;
1680       if (use_mb(cs))
1681       {
1682 	result_state= IDENT_QUOTED;
1683         while (ident_map[c=lip->yyGet()])
1684         {
1685           switch (my_mbcharlen(cs, c))
1686           {
1687           case 1:
1688             break;
1689           case 0:
1690             if (my_mbmaxlenlen(cs) < 2)
1691               break;
1692             /* else fall through */
1693           default:
1694             int l;
1695             if ((l = my_ismbchar(cs,
1696                                  lip->get_ptr() -1,
1697                                  lip->get_end_of_query())) == 0)
1698               break;
1699             lip->skip_binary(l-1);
1700           }
1701         }
1702       }
1703       else
1704       {
1705         for (result_state=0; ident_map[c= lip->yyGet()]; result_state|= c) ;
1706         /* If there were non-ASCII characters, mark that we must convert */
1707         result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1708       }
1709       if (c == '.' && ident_map[lip->yyPeek()])
1710 	lip->next_state=MY_LEX_IDENT_SEP;// Next is '.'
1711 
1712       yylval->lex_str= get_token(lip, 0, lip->yyLength());
1713 
1714       lip->body_utf8_append(lip->m_cpp_text_start);
1715 
1716       lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1717                                     lip->m_cpp_text_end);
1718 
1719       return(result_state);
1720 
1721     case MY_LEX_USER_VARIABLE_DELIMITER:	// Found quote char
1722     {
1723       uint double_quotes= 0;
1724       char quote_char= c;                       // Used char
1725       for(;;)
1726       {
1727         c= lip->yyGet();
1728         if (c == 0)
1729         {
1730           lip->yyUnget();
1731           return ABORT_SYM;                     // Unmatched quotes
1732         }
1733 
1734 	int var_length;
1735 	if ((var_length= my_mbcharlen(cs, c)) == 1)
1736 	{
1737 	  if (c == quote_char)
1738 	  {
1739             if (lip->yyPeek() != quote_char)
1740 	      break;
1741             c=lip->yyGet();
1742 	    double_quotes++;
1743 	    continue;
1744 	  }
1745 	}
1746         else if (use_mb(cs))
1747         {
1748           if ((var_length= my_ismbchar(cs, lip->get_ptr() - 1,
1749                                        lip->get_end_of_query())))
1750             lip->skip_binary(var_length-1);
1751         }
1752       }
1753       if (double_quotes)
1754 	yylval->lex_str=get_quoted_token(lip, 1,
1755                                          lip->yyLength() - double_quotes -1,
1756 					 quote_char);
1757       else
1758         yylval->lex_str=get_token(lip, 1, lip->yyLength() -1);
1759       if (c == quote_char)
1760         lip->yySkip();                  // Skip end `
1761       lip->next_state= MY_LEX_START;
1762 
1763       lip->body_utf8_append(lip->m_cpp_text_start);
1764 
1765       lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1766                                     lip->m_cpp_text_end);
1767 
1768       return(IDENT_QUOTED);
1769     }
1770     case MY_LEX_INT_OR_REAL:		// Complete int or incomplete real
1771       if (c != '.')
1772       {					// Found complete integer number.
1773         yylval->lex_str=get_token(lip, 0, lip->yyLength());
1774 	return int_token(yylval->lex_str.str, (uint) yylval->lex_str.length);
1775       }
1776       // fall through
1777     case MY_LEX_REAL:			// Incomplete real number
1778       while (my_isdigit(cs,c = lip->yyGet())) ;
1779 
1780       if (c == 'e' || c == 'E')
1781       {
1782         c = lip->yyGet();
1783 	if (c == '-' || c == '+')
1784           c = lip->yyGet();                     // Skip sign
1785 	if (!my_isdigit(cs,c))
1786 	{				// No digit after sign
1787 	  state= MY_LEX_CHAR;
1788 	  break;
1789 	}
1790         while (my_isdigit(cs,lip->yyGet())) ;
1791         yylval->lex_str=get_token(lip, 0, lip->yyLength());
1792 	return(FLOAT_NUM);
1793       }
1794       yylval->lex_str=get_token(lip, 0, lip->yyLength());
1795       return(DECIMAL_NUM);
1796 
1797     case MY_LEX_HEX_NUMBER:		// Found x'hexstring'
1798       lip->yySkip();                    // Accept opening '
1799       while (my_isxdigit(cs, (c= lip->yyGet()))) ;
1800       if (c != '\'')
1801         return(ABORT_SYM);              // Illegal hex constant
1802       lip->yySkip();                    // Accept closing '
1803       length= lip->yyLength();          // Length of hexnum+3
1804       if ((length % 2) == 0)
1805         return(ABORT_SYM);              // odd number of hex digits
1806       yylval->lex_str=get_token(lip,
1807                                 2,          // skip x'
1808                                 length-3);  // don't count x' and last '
1809       return (HEX_NUM);
1810 
1811     case MY_LEX_BIN_NUMBER:           // Found b'bin-string'
1812       lip->yySkip();                  // Accept opening '
1813       while ((c= lip->yyGet()) == '0' || c == '1') ;
1814       if (c != '\'')
1815         return(ABORT_SYM);            // Illegal hex constant
1816       lip->yySkip();                  // Accept closing '
1817       length= lip->yyLength();        // Length of bin-num + 3
1818       yylval->lex_str= get_token(lip,
1819                                  2,         // skip b'
1820                                  length-3); // don't count b' and last '
1821       return (BIN_NUM);
1822 
1823     case MY_LEX_CMP_OP:			// Incomplete comparison operator
1824       if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP ||
1825           state_map[lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
1826         lip->yySkip();
1827       if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
1828       {
1829 	lip->next_state= MY_LEX_START;	// Allow signed numbers
1830 	return(tokval);
1831       }
1832       state = MY_LEX_CHAR;		// Something fishy found
1833       break;
1834 
1835     case MY_LEX_LONG_CMP_OP:		// Incomplete comparison operator
1836       if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP ||
1837           state_map[lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
1838       {
1839         lip->yySkip();
1840         if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP)
1841           lip->yySkip();
1842       }
1843       if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
1844       {
1845 	lip->next_state= MY_LEX_START;	// Found long op
1846 	return(tokval);
1847       }
1848       state = MY_LEX_CHAR;		// Something fishy found
1849       break;
1850 
1851     case MY_LEX_BOOL:
1852       if (c != lip->yyPeek())
1853       {
1854 	state=MY_LEX_CHAR;
1855 	break;
1856       }
1857       lip->yySkip();
1858       tokval = find_keyword(lip,2,0);	// Is a bool operator
1859       lip->next_state= MY_LEX_START;	// Allow signed numbers
1860       return(tokval);
1861 
1862     case MY_LEX_STRING_OR_DELIMITER:
1863       if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
1864       {
1865 	state= MY_LEX_USER_VARIABLE_DELIMITER;
1866 	break;
1867       }
1868       /* " used for strings */
1869       // Fall through.
1870     case MY_LEX_STRING:			// Incomplete text string
1871       if (!(yylval->lex_str.str = get_text(lip, 1, 1)))
1872       {
1873 	state= MY_LEX_CHAR;		// Read char by char
1874 	break;
1875       }
1876       yylval->lex_str.length=lip->yytoklen;
1877 
1878       lip->body_utf8_append(lip->m_cpp_text_start);
1879 
1880       lip->body_utf8_append_literal(thd, &yylval->lex_str,
1881         lip->m_underscore_cs ? lip->m_underscore_cs : cs,
1882         lip->m_cpp_text_end);
1883 
1884       lip->m_underscore_cs= NULL;
1885 
1886       return(TEXT_STRING);
1887 
1888     case MY_LEX_COMMENT:			//  Comment
1889       thd->m_parser_state->add_comment();
1890       while ((c = lip->yyGet()) != '\n' && c) ;
1891       lip->yyUnget();                   // Safety against eof
1892       state = MY_LEX_START;		// Try again
1893       break;
1894     case MY_LEX_LONG_COMMENT:		/* Long C comment? */
1895       if (lip->yyPeek() != '*')
1896       {
1897 	state=MY_LEX_CHAR;		// Probable division
1898 	break;
1899       }
1900       thd->m_parser_state->add_comment();
1901       /* Reject '/' '*', since we might need to turn off the echo */
1902       lip->yyUnget();
1903 
1904       lip->save_in_comment_state();
1905 
1906       if (lip->yyPeekn(2) == '!')
1907       {
1908         lip->in_comment= DISCARD_COMMENT;
1909         /* Accept '/' '*' '!', but do not keep this marker. */
1910         lip->set_echo(FALSE);
1911         lip->yySkip();
1912         lip->yySkip();
1913         lip->yySkip();
1914 
1915         /*
1916           The special comment format is very strict:
1917           '/' '*' '!', followed by exactly
1918           1 digit (major), 2 digits (minor), then 2 digits (dot).
1919           32302 -> 3.23.02
1920           50032 -> 5.0.32
1921           50114 -> 5.1.14
1922         */
1923         char version_str[6];
1924         if (  my_isdigit(cs, (version_str[0]= lip->yyPeekn(0)))
1925            && my_isdigit(cs, (version_str[1]= lip->yyPeekn(1)))
1926            && my_isdigit(cs, (version_str[2]= lip->yyPeekn(2)))
1927            && my_isdigit(cs, (version_str[3]= lip->yyPeekn(3)))
1928            && my_isdigit(cs, (version_str[4]= lip->yyPeekn(4)))
1929            )
1930         {
1931           version_str[5]= 0;
1932           ulong version;
1933           version=strtol(version_str, NULL, 10);
1934 
1935           if (version <= MYSQL_VERSION_ID)
1936           {
1937             /* Accept 'M' 'm' 'm' 'd' 'd' */
1938             lip->yySkipn(5);
1939             /* Expand the content of the special comment as real code */
1940             lip->set_echo(TRUE);
1941             state=MY_LEX_START;
1942             break;  /* Do not treat contents as a comment.  */
1943           }
1944           else
1945           {
1946 #ifdef WITH_WSREP
1947 	    if (version == 99997 && thd->wsrep_exec_mode == LOCAL_STATE)
1948 	    {
1949 	      WSREP_DEBUG("consistency check: %s", thd->query().str);
1950 	      thd->wsrep_consistency_check= CONSISTENCY_CHECK_DECLARED;
1951 	      lip->yySkipn(5);
1952 	      lip->set_echo(TRUE);
1953 	      state=MY_LEX_START;
1954 	      break;  /* Do not treat contents as a comment.  */
1955 	    }
1956 #endif /* WITH_WSREP */
1957             /*
1958               Patch and skip the conditional comment to avoid it
1959               being propagated infinitely (eg. to a slave).
1960             */
1961             char *pcom= lip->yyUnput(' ');
1962             comment_closed= ! consume_comment(lip, 1);
1963             if (! comment_closed)
1964             {
1965               *pcom= '!';
1966             }
1967             /* version allowed to have one level of comment inside. */
1968           }
1969         }
1970         else
1971         {
1972           /* Not a version comment. */
1973           state=MY_LEX_START;
1974           lip->set_echo(TRUE);
1975           break;
1976         }
1977       }
1978       else
1979       {
1980         lip->in_comment= PRESERVE_COMMENT;
1981         lip->yySkip();                  // Accept /
1982         lip->yySkip();                  // Accept *
1983         comment_closed= ! consume_comment(lip, 0);
1984         /* regular comments can have zero comments inside. */
1985       }
1986       /*
1987         Discard:
1988         - regular '/' '*' comments,
1989         - special comments '/' '*' '!' for a future version,
1990         by scanning until we find a closing '*' '/' marker.
1991 
1992         Nesting regular comments isn't allowed.  The first
1993         '*' '/' returns the parser to the previous state.
1994 
1995         /#!VERSI oned containing /# regular #/ is allowed #/
1996 
1997 		Inside one versioned comment, another versioned comment
1998 		is treated as a regular discardable comment.  It gets
1999 		no special parsing.
2000       */
2001 
2002       /* Unbalanced comments with a missing '*' '/' are a syntax error */
2003       if (! comment_closed)
2004         return (ABORT_SYM);
2005       state = MY_LEX_START;             // Try again
2006       lip->restore_in_comment_state();
2007       break;
2008     case MY_LEX_END_LONG_COMMENT:
2009       if ((lip->in_comment != NO_COMMENT) && lip->yyPeek() == '/')
2010       {
2011         /* Reject '*' '/' */
2012         lip->yyUnget();
2013         /* Accept '*' '/', with the proper echo */
2014         lip->set_echo(lip->in_comment == PRESERVE_COMMENT);
2015         lip->yySkipn(2);
2016         /* And start recording the tokens again */
2017         lip->set_echo(TRUE);
2018 
2019         /*
2020           C-style comments are replaced with a single space (as it
2021           is in C and C++).  If there is already a whitespace
2022           character at this point in the stream, the space is
2023           not inserted.
2024 
2025           See also ISO/IEC 9899:1999 §5.1.1.2
2026           ("Programming languages — C")
2027         */
2028         if (!my_isspace(cs, lip->yyPeek()) &&
2029             lip->get_cpp_ptr() != lip->get_cpp_buf() &&
2030             !my_isspace(cs, *(lip->get_cpp_ptr() - 1)))
2031           lip->cpp_inject(' ');
2032 
2033         lip->in_comment=NO_COMMENT;
2034         state=MY_LEX_START;
2035       }
2036       else
2037 	state=MY_LEX_CHAR;		// Return '*'
2038       break;
2039     case MY_LEX_SET_VAR:		// Check if ':='
2040       if (lip->yyPeek() != '=')
2041       {
2042 	state=MY_LEX_CHAR;		// Return ':'
2043 	break;
2044       }
2045       lip->yySkip();
2046       return (SET_VAR);
2047     case MY_LEX_SEMICOLON:			// optional line terminator
2048       state= MY_LEX_CHAR;               // Return ';'
2049       break;
2050     case MY_LEX_EOL:
2051       if (lip->eof())
2052       {
2053         lip->yyUnget();                 // Reject the last '\0'
2054         lip->set_echo(FALSE);
2055         lip->yySkip();
2056         lip->set_echo(TRUE);
2057         /* Unbalanced comments with a missing '*' '/' are a syntax error */
2058         if (lip->in_comment != NO_COMMENT)
2059           return (ABORT_SYM);
2060         lip->next_state=MY_LEX_END;     // Mark for next loop
2061         return(END_OF_INPUT);
2062       }
2063       state=MY_LEX_CHAR;
2064       break;
2065     case MY_LEX_END:
2066       lip->next_state=MY_LEX_END;
2067       return(0);			// We found end of input last time
2068 
2069       /* Actually real shouldn't start with . but allow them anyhow */
2070     case MY_LEX_REAL_OR_POINT:
2071       if (my_isdigit(cs,lip->yyPeek()))
2072 	state = MY_LEX_REAL;		// Real
2073       else
2074       {
2075 	state= MY_LEX_IDENT_SEP;	// return '.'
2076         lip->yyUnget();                 // Put back '.'
2077       }
2078       break;
2079     case MY_LEX_USER_END:		// end '@' of user@hostname
2080       switch (state_map[lip->yyPeek()]) {
2081       case MY_LEX_STRING:
2082       case MY_LEX_USER_VARIABLE_DELIMITER:
2083       case MY_LEX_STRING_OR_DELIMITER:
2084         break;
2085       case MY_LEX_USER_END:
2086 	lip->next_state=MY_LEX_SYSTEM_VAR;
2087 	break;
2088       default:
2089 	lip->next_state=MY_LEX_HOSTNAME;
2090 	break;
2091       }
2092       yylval->lex_str.str=(char*) lip->get_ptr();
2093       yylval->lex_str.length=1;
2094       return((int) '@');
2095     case MY_LEX_HOSTNAME:		// end '@' of user@hostname
2096       for (c=lip->yyGet() ;
2097 	   my_isalnum(cs,c) || c == '.' || c == '_' ||  c == '$';
2098            c= lip->yyGet()) ;
2099       yylval->lex_str=get_token(lip, 0, lip->yyLength());
2100       return(LEX_HOSTNAME);
2101     case MY_LEX_SYSTEM_VAR:
2102       yylval->lex_str.str=(char*) lip->get_ptr();
2103       yylval->lex_str.length=1;
2104       lip->yySkip();                                    // Skip '@'
2105       lip->next_state= (state_map[lip->yyPeek()] ==
2106 			MY_LEX_USER_VARIABLE_DELIMITER ?
2107 			MY_LEX_OPERATOR_OR_IDENT :
2108 			MY_LEX_IDENT_OR_KEYWORD);
2109       return((int) '@');
2110     case MY_LEX_IDENT_OR_KEYWORD:
2111       /*
2112 	We come here when we have found two '@' in a row.
2113 	We should now be able to handle:
2114 	[(global | local | session) .]variable_name
2115       */
2116 
2117       for (result_state= 0; ident_map[c= lip->yyGet()]; result_state|= c) ;
2118       /* If there were non-ASCII characters, mark that we must convert */
2119       result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
2120 
2121       if (c == '.')
2122 	lip->next_state=MY_LEX_IDENT_SEP;
2123       length= lip->yyLength();
2124       if (length == 0)
2125         return(ABORT_SYM);              // Names must be nonempty.
2126       if ((tokval= find_keyword(lip, length,0)))
2127       {
2128         lip->yyUnget();                         // Put back 'c'
2129 	return(tokval);				// Was keyword
2130       }
2131       yylval->lex_str=get_token(lip, 0, length);
2132 
2133       lip->body_utf8_append(lip->m_cpp_text_start);
2134 
2135       lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
2136                                     lip->m_cpp_text_end);
2137 
2138       return(result_state);
2139     }
2140   }
2141 }
2142 
2143 
trim_whitespace(const CHARSET_INFO * cs,LEX_STRING * str)2144 void trim_whitespace(const CHARSET_INFO *cs, LEX_STRING *str)
2145 {
2146   /*
2147     TODO:
2148     This code assumes that there are no multi-bytes characters
2149     that can be considered white-space.
2150   */
2151 
2152   while ((str->length > 0) && (my_isspace(cs, str->str[0])))
2153   {
2154     str->length --;
2155     str->str ++;
2156   }
2157 
2158   /*
2159     FIXME:
2160     Also, parsing backward is not safe with multi bytes characters
2161   */
2162   while ((str->length > 0) && (my_isspace(cs, str->str[str->length-1])))
2163   {
2164     str->length --;
2165     /* set trailing spaces to 0 as there're places that don't respect length */
2166     str->str[str->length]= 0;
2167   }
2168 }
2169 
2170 
2171 /**
2172   Construct and initialize st_select_lex_unit object.
2173 */
2174 
st_select_lex_unit(enum_parsing_context parsing_context)2175 st_select_lex_unit::st_select_lex_unit(enum_parsing_context parsing_context) :
2176   next(NULL),
2177   prev(NULL),
2178   master(NULL),
2179   slave(NULL),
2180   explain_marker(CTX_NONE),
2181   prepared(false),
2182   optimized(false),
2183   executed(false),
2184   result_table_list(),
2185   union_result(NULL),
2186   table(NULL),
2187   m_query_result(NULL),
2188   uncacheable(0),
2189   cleaned(UC_DIRTY),
2190   item_list(),
2191   types(),
2192   select_limit_cnt(HA_POS_ERROR),
2193   offset_limit_cnt(0),
2194   item(NULL),
2195   thd(NULL),
2196   fake_select_lex(NULL),
2197   saved_fake_select_lex(NULL),
2198   union_distinct(NULL)
2199 {
2200   switch (parsing_context)
2201   {
2202     case CTX_ORDER_BY:
2203       explain_marker= CTX_ORDER_BY_SQ; // A subquery in ORDER BY
2204       break;
2205     case CTX_GROUP_BY:
2206       explain_marker= CTX_GROUP_BY_SQ; // A subquery in GROUP BY
2207       break;
2208     case CTX_ON:
2209       explain_marker= CTX_WHERE;
2210       break;
2211     case CTX_HAVING:                         // A subquery elsewhere
2212     case CTX_SELECT_LIST:
2213     case CTX_UPDATE_VALUE_LIST:
2214     case CTX_WHERE:
2215     case CTX_DERIVED:
2216     case CTX_NONE:                           // A subquery in a non-select
2217       explain_marker= parsing_context;
2218       break;
2219     default:
2220       /* Subquery can't happen outside of those ^. */
2221       assert(false); /* purecov: inspected */
2222       break;
2223   }
2224 }
2225 
2226 
2227 /**
2228   Construct and initialize st_select_lex object.
2229 */
2230 
st_select_lex(TABLE_LIST * table_list,List<Item> * item_list_arg,Item * where,Item * having,Item * limit,Item * offset)2231 st_select_lex::st_select_lex
2232                (TABLE_LIST *table_list,
2233                 List<Item> *item_list_arg,       // unused
2234                 Item *where, Item *having, Item *limit, Item *offset)
2235                 //SQL_I_LIST<ORDER> *group_by, SQL_I_LIST<ORDER> order_by)
2236   :
2237   next(NULL),
2238   prev(NULL),
2239   master(NULL),
2240   slave(NULL),
2241   link_next(NULL),
2242   link_prev(NULL),
2243   m_query_result(NULL),
2244   m_base_options(0),
2245   m_active_options(0),
2246   sql_cache(SQL_CACHE_UNSPECIFIED),
2247   uncacheable(0),
2248   linkage(UNSPECIFIED_TYPE),
2249   no_table_names_allowed(false),
2250   context(),
2251   first_context(&context),
2252   resolve_place(RESOLVE_NONE),
2253   resolve_nest(NULL),
2254   semijoin_disallowed(false),
2255   db(NULL),
2256   m_where_cond(where),
2257   m_having_cond(having),
2258   cond_value(Item::COND_UNDEF),
2259   having_value(Item::COND_UNDEF),
2260   parent_lex(NULL),
2261   olap(UNSPECIFIED_OLAP_TYPE),
2262   table_list(),
2263   group_list(),
2264   group_list_ptrs(NULL),
2265   item_list(),
2266   is_item_list_lookup(false),
2267   fields_list(item_list),
2268   all_fields(),
2269   ftfunc_list(&ftfunc_list_alloc),
2270   ftfunc_list_alloc(),
2271   join(NULL),
2272   top_join_list(),
2273   join_list(&top_join_list),
2274   embedding(NULL),
2275   sj_nests(),
2276   leaf_tables(NULL),
2277   leaf_table_count(0),
2278   derived_table_count(0),
2279   materialized_derived_table_count(0),
2280   has_sj_nests(false),
2281   partitioned_table_count(0),
2282   order_list(),
2283   order_list_ptrs(NULL),
2284   select_limit(NULL),
2285   offset_limit(NULL),
2286   ref_pointer_array(),
2287   select_n_having_items(0),
2288   cond_count(0),
2289   between_count(0),
2290   max_equal_elems(0),
2291   select_n_where_fields(0),
2292   parsing_place(CTX_NONE),
2293   in_sum_expr(0),
2294   with_sum_func(false),
2295   n_sum_items(0),
2296   n_child_sum_items(0),
2297   select_number(0),
2298   nest_level(0),
2299   inner_sum_func_list(NULL),
2300   with_wild(0),
2301   braces(false),
2302   having_fix_field(false),
2303   group_fix_field(false),
2304   inner_refs_list(),
2305   explicit_limit(false),
2306   subquery_in_having(false),
2307   first_execution(true),
2308   sj_pullout_done(false),
2309   exclude_from_table_unique_test(false),
2310   allow_merge_derived(true),
2311   prev_join_using(NULL),
2312   select_list_tables(0),
2313   outer_join(0),
2314   opt_hints_qb(NULL),
2315   m_agg_func_used(false),
2316   m_json_agg_func_used(false),
2317   sj_candidates(NULL),
2318   hidden_order_field_count(0)
2319 {
2320 }
2321 
2322 
2323 /**
2324   Set the name resolution context for the specified query block.
2325 
2326   @param outer_context Outer name resolution context.
2327                        NULL if none or it will be set later.
2328 */
2329 
set_context(Name_resolution_context * outer_context)2330 bool st_select_lex::set_context(Name_resolution_context *outer_context)
2331 {
2332   context.init();
2333   context.select_lex= this;
2334   context.outer_context= outer_context;
2335   /*
2336     Add the name resolution context of this query block to the
2337     stack of contexts for the whole query.
2338   */
2339   return parent_lex->push_context(&context);
2340 }
2341 
2342 
2343 /**
2344   Exclude this unit and its immediately contained select_lex objects
2345   from query expression / query block chain.
2346 
2347   @note
2348     Units that belong to the select_lex objects of the current unit will be
2349     brought up one level and will replace the current unit in the list of units.
2350 */
exclude_level()2351 void st_select_lex_unit::exclude_level()
2352 {
2353   /*
2354     Changing unit tree should be done only when LOCK_query_plan mutex is
2355     taken. This is needed to provide stable tree for EXPLAIN FOR CONNECTION.
2356   */
2357   thd->lock_query_plan();
2358   SELECT_LEX_UNIT *units= NULL;
2359   SELECT_LEX_UNIT **units_last= &units;
2360   SELECT_LEX *sl= first_select();
2361   while (sl)
2362   {
2363     SELECT_LEX *next_select= sl->next_select();
2364 
2365     // unlink current level from global SELECTs list
2366     if (sl->link_prev && (*sl->link_prev= sl->link_next))
2367       sl->link_next->link_prev= sl->link_prev;
2368 
2369     // bring up underlay levels
2370     SELECT_LEX_UNIT **last= NULL;
2371     for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
2372     {
2373       /*
2374         We are excluding a SELECT_LEX from the hierarchy of
2375         SELECT_LEX_UNITs and SELECT_LEXes. Since this level is
2376         removed, we must also exclude the Name_resolution_context
2377         belonging to this level. Do this by looping through inner
2378         subqueries and changing their contexts' outer context pointers
2379         to point to the outer select's context.
2380       */
2381       for (SELECT_LEX *s= u->first_select(); s; s= s->next_select())
2382       {
2383         if (s->context.outer_context == &sl->context)
2384           s->context.outer_context= &sl->outer_select()->context;
2385       }
2386       if (u->fake_select_lex &&
2387           u->fake_select_lex->context.outer_context == &sl->context)
2388         u->fake_select_lex->context.outer_context= &sl->outer_select()->context;
2389       u->master= master;
2390       last= &(u->next);
2391     }
2392     if (last)
2393     {
2394       (*units_last)= sl->first_inner_unit();
2395       units_last= last;
2396     }
2397 
2398     sl->invalidate();
2399     sl= next_select;
2400   }
2401   if (units)
2402   {
2403     // include brought up levels in place of current
2404     (*prev)= units;
2405     (*units_last)= next;
2406     if (next)
2407       next->prev= units_last;
2408     units->prev= prev;
2409   }
2410   else
2411   {
2412     // exclude currect unit from list of nodes
2413     if (prev)
2414       (*prev)= next;
2415     if (next)
2416       next->prev= prev;
2417   }
2418 
2419   invalidate();
2420   thd->unlock_query_plan();
2421 }
2422 
2423 
2424 /**
2425   Exclude subtree of current unit from tree of SELECTs
2426 */
exclude_tree()2427 void st_select_lex_unit::exclude_tree()
2428 {
2429   SELECT_LEX *sl= first_select();
2430   while (sl)
2431   {
2432     SELECT_LEX *next_select= sl->next_select();
2433 
2434     // unlink current level from global SELECTs list
2435     if (sl->link_prev && (*sl->link_prev= sl->link_next))
2436       sl->link_next->link_prev= sl->link_prev;
2437 
2438     // unlink underlay levels
2439     for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
2440     {
2441       u->exclude_level();
2442     }
2443 
2444     sl->invalidate();
2445     sl= next_select;
2446   }
2447   // exclude currect unit from list of nodes
2448   if (prev)
2449     (*prev)= next;
2450   if (next)
2451     next->prev= prev;
2452 
2453   invalidate();
2454 }
2455 
2456 
2457 /**
2458   Invalidate by nulling out pointers to other st_select_lex_units and
2459   st_select_lexes.
2460 */
invalidate()2461 void st_select_lex_unit::invalidate()
2462 {
2463   next= NULL;
2464   prev= NULL;
2465   master= NULL;
2466   slave= NULL;
2467 }
2468 
2469 
2470 /**
2471   Make active options from base options, supplied options and environment:
2472 
2473   @param added_options   Options that are added to the active options
2474   @param removed_options Options that are removed from the active options
2475 */
2476 
make_active_options(ulonglong added_options,ulonglong removed_options)2477 void st_select_lex::make_active_options(ulonglong added_options,
2478                                         ulonglong removed_options)
2479 {
2480   m_active_options= (m_base_options | added_options |
2481                      parent_lex->thd->variables.option_bits) &
2482                     ~removed_options;
2483 }
2484 
2485 /**
2486   Mark all query blocks from this to 'last' as dependent
2487 
2488   @param last Pointer to last st_select_lex struct, before which all
2489               st_select_lex are marked as as dependent.
2490 
2491   @note
2492     last should be reachable from this st_select_lex
2493 */
2494 
mark_as_dependent(st_select_lex * last)2495 void st_select_lex::mark_as_dependent(st_select_lex *last)
2496 {
2497   /*
2498     Mark all selects from resolved to 1 before select where was
2499     found table as depended (of select where was found table)
2500   */
2501   for (SELECT_LEX *s= this;
2502        s && s != last;
2503        s= s->outer_select())
2504   {
2505     if (!(s->uncacheable & UNCACHEABLE_DEPENDENT))
2506     {
2507       // Select is dependent of outer select
2508       s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
2509                        UNCACHEABLE_DEPENDENT;
2510       SELECT_LEX_UNIT *munit= s->master_unit();
2511       munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
2512                        UNCACHEABLE_DEPENDENT;
2513       for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
2514       {
2515         if (sl != s &&
2516             !(sl->uncacheable & (UNCACHEABLE_DEPENDENT | UNCACHEABLE_UNITED)))
2517           sl->uncacheable|= UNCACHEABLE_UNITED;
2518       }
2519     }
2520   }
2521 }
2522 
2523 
2524 /*
2525   prohibit using LIMIT clause
2526 */
test_limit()2527 bool st_select_lex::test_limit()
2528 {
2529   if (select_limit != 0)
2530   {
2531     my_error(ER_NOT_SUPPORTED_YET, MYF(0),
2532              "LIMIT & IN/ALL/ANY/SOME subquery");
2533     return(1);
2534   }
2535   return(0);
2536 }
2537 
2538 
get_explain_marker() const2539 enum_parsing_context st_select_lex_unit::get_explain_marker() const
2540 {
2541   thd->query_plan.assert_plan_is_locked_if_other();
2542   return explain_marker;
2543 }
2544 
2545 
set_explain_marker(enum_parsing_context m)2546 void st_select_lex_unit::set_explain_marker(enum_parsing_context m)
2547 {
2548   thd->lock_query_plan();
2549   explain_marker= m;
2550   thd->unlock_query_plan();
2551 }
2552 
2553 
2554 void st_select_lex_unit::
set_explain_marker_from(const st_select_lex_unit * u)2555 set_explain_marker_from(const st_select_lex_unit *u)
2556 {
2557   thd->lock_query_plan();
2558   explain_marker= u->explain_marker;
2559   thd->unlock_query_plan();
2560 }
2561 
2562 
get_offset()2563 ha_rows st_select_lex::get_offset()
2564 {
2565   ulonglong val= 0;
2566 
2567   if (offset_limit)
2568   {
2569     // see comment for st_select_lex::get_limit()
2570     bool fix_fields_successful= true;
2571     if (!offset_limit->fixed)
2572     {
2573       fix_fields_successful= !offset_limit->fix_fields(master->thd, NULL);
2574 
2575       assert(fix_fields_successful);
2576     }
2577     val= fix_fields_successful ? offset_limit->val_uint() : HA_POS_ERROR;
2578   }
2579 
2580   return (ha_rows)val;
2581 }
2582 
2583 
get_limit()2584 ha_rows st_select_lex::get_limit()
2585 {
2586   ulonglong val= HA_POS_ERROR;
2587 
2588   if (select_limit)
2589   {
2590     /*
2591       fix_fields() has not been called for select_limit. That's due to the
2592       historical reasons -- this item could be only of type Item_int, and
2593       Item_int does not require fix_fields(). Thus, fix_fields() was never
2594       called for select_limit.
2595 
2596       Some time ago, Item_splocal was also allowed for LIMIT / OFFSET clauses.
2597       However, the fix_fields() behavior was not updated, which led to a crash
2598       in some cases.
2599 
2600       There is no single place where to call fix_fields() for LIMIT / OFFSET
2601       items during the fix-fields-phase. Thus, for the sake of readability,
2602       it was decided to do it here, on the evaluation phase (which is a
2603       violation of design, but we chose the lesser of two evils).
2604 
2605       We can call fix_fields() here, because select_limit can be of two
2606       types only: Item_int and Item_splocal. Item_int::fix_fields() is trivial,
2607       and Item_splocal::fix_fields() (or rather Item_sp_variable::fix_fields())
2608       has the following properties:
2609         1) it does not affect other items;
2610         2) it does not fail.
2611 
2612         Nevertheless assert was added to catch future changes in
2613       fix_fields() implementation. Also added runtime check against a result
2614       of fix_fields() in order to handle error condition in non-debug build.
2615     */
2616     bool fix_fields_successful= true;
2617     if (!select_limit->fixed)
2618     {
2619       fix_fields_successful= !select_limit->fix_fields(master->thd, NULL);
2620 
2621       assert(fix_fields_successful);
2622     }
2623     val= fix_fields_successful ? select_limit->val_uint() : HA_POS_ERROR;
2624   }
2625 
2626   return (ha_rows)val;
2627 }
2628 
2629 
add_order_to_list(ORDER * order)2630 void st_select_lex::add_order_to_list(ORDER *order)
2631 {
2632   add_to_list(order_list, order);
2633 }
2634 
2635 
add_item_to_list(THD * thd,Item * item)2636 bool st_select_lex::add_item_to_list(THD *thd, Item *item)
2637 {
2638   DBUG_ENTER("st_select_lex::add_item_to_list");
2639   DBUG_PRINT("info", ("Item: 0x%lx", (long) item));
2640   DBUG_RETURN(item_list.push_back(item));
2641 }
2642 
2643 
add_group_to_list(ORDER * order)2644 void st_select_lex::add_group_to_list(ORDER *order)
2645 {
2646   add_to_list(group_list, order);
2647 }
2648 
2649 
add_ftfunc_to_list(Item_func_match * func)2650 bool st_select_lex::add_ftfunc_to_list(Item_func_match *func)
2651 {
2652   return !func || ftfunc_list->push_back(func); // end of memory?
2653 }
2654 
2655 
2656 /**
2657   Invalidate by nulling out pointers to other st_select_lex_units and
2658   st_select_lexes.
2659 */
invalidate()2660 void st_select_lex::invalidate()
2661 {
2662   next= NULL;
2663   prev= NULL;
2664   master= NULL;
2665   slave= NULL;
2666   link_next= NULL;
2667   link_prev= NULL;
2668 }
2669 
2670 
set_braces(bool value)2671 bool st_select_lex::set_braces(bool value)
2672 {
2673   braces= value;
2674   return 0;
2675 }
2676 
2677 
setup_ref_array(THD * thd)2678 bool st_select_lex::setup_ref_array(THD *thd)
2679 {
2680   uint order_group_num= order_list.elements + group_list.elements;
2681 
2682   // find_order_in_list() may need some extra space, so multiply by two.
2683   order_group_num*= 2;
2684 
2685   // create_distinct_group() may need some extra space
2686   if (is_distinct())
2687   {
2688     uint bitcount= 0;
2689     Item *item;
2690     List_iterator<Item> li(item_list);
2691     while ((item= li++))
2692     {
2693       /*
2694         Same test as in create_distinct_group, when it pushes new items to the
2695         end of ref_pointer_array. An extra test for 'fixed' which, at this
2696         stage, will be true only for columns inserted for a '*' wildcard.
2697       */
2698       if (item->fixed &&
2699           item->type() == Item::FIELD_ITEM &&
2700           item->field_type() == MYSQL_TYPE_BIT)
2701         ++bitcount;
2702     }
2703     order_group_num+= bitcount;
2704   }
2705 
2706   /*
2707     We have to create array in prepared statement memory if it is
2708     prepared statement
2709   */
2710   Query_arena *arena= thd->stmt_arena;
2711   const uint n_elems= (n_sum_items +
2712                        n_child_sum_items +
2713                        item_list.elements +
2714                        select_n_having_items +
2715                        select_n_where_fields +
2716                        order_group_num) * 5;
2717   DBUG_PRINT("info", ("setup_ref_array this %p %4u : %4u %4u %4u %4u %4u %4u",
2718                       this,
2719                       n_elems, // :
2720                       n_sum_items,
2721                       n_child_sum_items,
2722                       item_list.elements,
2723                       select_n_having_items,
2724                       select_n_where_fields,
2725                       order_group_num));
2726   if (!ref_pointer_array.is_null())
2727   {
2728     /*
2729       We need to take 'n_sum_items' into account when allocating the array,
2730       and this may actually increase during the optimization phase due to
2731       MIN/MAX rewrite in Item_in_subselect::single_value_transformer.
2732       In the usual case we can reuse the array from the prepare phase.
2733       If we need a bigger array, we must allocate a new one.
2734      */
2735     if (ref_pointer_array.size() >= n_elems)
2736       return false;
2737   }
2738   /*
2739     ref_pointer_array could become bigger when a subquery gets transformed
2740     into a MIN/MAX subquery. Reallocate array in this case.
2741   */
2742   Item **array= static_cast<Item**>(arena->alloc(sizeof(Item*) * n_elems));
2743   if (array != NULL)
2744   {
2745     ref_pointer_array= Ref_ptr_array(array, n_elems);
2746     ref_ptrs= ref_ptr_array_slice(0);
2747   }
2748   return array == NULL;
2749 }
2750 
2751 
print(String * str,enum_query_type query_type)2752 void st_select_lex_unit::print(String *str, enum_query_type query_type)
2753 {
2754   bool union_all= !union_distinct;
2755   for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
2756   {
2757     if (sl != first_select())
2758     {
2759       str->append(STRING_WITH_LEN(" union "));
2760       if (union_all)
2761 	str->append(STRING_WITH_LEN("all "));
2762       else if (union_distinct == sl)
2763         union_all= TRUE;
2764     }
2765     if (sl->braces)
2766       str->append('(');
2767     sl->print(thd, str, query_type);
2768     if (sl->braces)
2769       str->append(')');
2770   }
2771   if (fake_select_lex)
2772   {
2773     if (fake_select_lex->order_list.elements)
2774     {
2775       str->append(STRING_WITH_LEN(" order by "));
2776       fake_select_lex->print_order(str,
2777         fake_select_lex->order_list.first,
2778         query_type);
2779     }
2780     fake_select_lex->print_limit(thd, str, query_type);
2781   }
2782   else if (saved_fake_select_lex)
2783     saved_fake_select_lex->print_limit(thd, str, query_type);
2784 }
2785 
2786 
print_order(String * str,ORDER * order,enum_query_type query_type)2787 void st_select_lex::print_order(String *str,
2788                                 ORDER *order,
2789                                 enum_query_type query_type)
2790 {
2791   for (; order; order= order->next)
2792   {
2793     (*order->item)->print_for_order(str, query_type, order->used_alias);
2794     if (order->direction == ORDER::ORDER_DESC)
2795       str->append(STRING_WITH_LEN(" desc"));
2796     if (order->next)
2797       str->append(',');
2798   }
2799 }
2800 
2801 
print_limit(THD * thd,String * str,enum_query_type query_type)2802 void st_select_lex::print_limit(THD *thd,
2803                                 String *str,
2804                                 enum_query_type query_type)
2805 {
2806   SELECT_LEX_UNIT *unit= master_unit();
2807   Item_subselect *item= unit->item;
2808 
2809   if (item && unit->global_parameters() == this)
2810   {
2811     Item_subselect::subs_type subs_type= item->substype();
2812     if (subs_type == Item_subselect::EXISTS_SUBS ||
2813         subs_type == Item_subselect::IN_SUBS ||
2814         subs_type == Item_subselect::ALL_SUBS)
2815       return;
2816   }
2817   if (explicit_limit)
2818   {
2819     str->append(STRING_WITH_LEN(" limit "));
2820     if (offset_limit)
2821     {
2822       offset_limit->print(str, query_type);
2823       str->append(',');
2824     }
2825     select_limit->print(str, query_type);
2826   }
2827 }
2828 
2829 
2830 /**
2831   @brief Print an index hint
2832 
2833   @details Prints out the USE|FORCE|IGNORE index hint.
2834 
2835   @param      thd         the current thread
2836   @param[out] str         appends the index hint here
2837   @param      hint        what the hint is (as string : "USE INDEX"|
2838                           "FORCE INDEX"|"IGNORE INDEX")
2839   @param      hint_length the length of the string in 'hint'
2840   @param      indexes     a list of index names for the hint
2841 */
2842 
2843 void
print(THD * thd,String * str)2844 Index_hint::print(THD *thd, String *str)
2845 {
2846   switch (type)
2847   {
2848     case INDEX_HINT_IGNORE: str->append(STRING_WITH_LEN("IGNORE INDEX")); break;
2849     case INDEX_HINT_USE:    str->append(STRING_WITH_LEN("USE INDEX")); break;
2850     case INDEX_HINT_FORCE:  str->append(STRING_WITH_LEN("FORCE INDEX")); break;
2851   }
2852   switch (clause)
2853   {
2854     case INDEX_HINT_MASK_ALL:
2855       break;
2856     case INDEX_HINT_MASK_JOIN:
2857       str->append(STRING_WITH_LEN(" FOR JOIN"));
2858       break;
2859     case INDEX_HINT_MASK_ORDER:
2860       str->append(STRING_WITH_LEN(" FOR ORDER BY"));
2861       break;
2862     case INDEX_HINT_MASK_GROUP:
2863       str->append(STRING_WITH_LEN(" FOR GROUP BY"));
2864       break;
2865   }
2866 
2867   str->append (STRING_WITH_LEN(" ("));
2868   if (key_name.length)
2869   {
2870     if (thd && !my_strnncoll(system_charset_info,
2871                              (const uchar *)key_name.str, key_name.length,
2872                              (const uchar *)primary_key_name,
2873                              strlen(primary_key_name)))
2874       str->append(primary_key_name);
2875     else
2876       append_identifier(thd, str, key_name.str, key_name.length);
2877   }
2878   str->append(')');
2879 }
2880 
2881 
print_table_array(THD * thd,String * str,TABLE_LIST ** table,TABLE_LIST ** end,enum_query_type query_type)2882 static void print_table_array(THD *thd, String *str, TABLE_LIST **table,
2883                               TABLE_LIST **end, enum_query_type query_type)
2884 {
2885   (*table)->print(thd, str, query_type);
2886 
2887   for (TABLE_LIST **tbl= table + 1; tbl < end; tbl++)
2888   {
2889     TABLE_LIST *curr= *tbl;
2890     // Print the join operator which relates this table to the previous one
2891     if (curr->outer_join)
2892     {
2893       /* MySQL converts right to left joins */
2894       str->append(STRING_WITH_LEN(" left join "));
2895     }
2896     else if (curr->straight)
2897       str->append(STRING_WITH_LEN(" straight_join "));
2898     else if (curr->sj_cond())
2899       str->append(STRING_WITH_LEN(" semi join "));
2900     else
2901       str->append(STRING_WITH_LEN(" join "));
2902     curr->print(thd, str, query_type);          // Print table
2903 
2904     // Print join condition
2905     Item *const cond=
2906       (curr->select_lex->join && curr->select_lex->join->is_optimized()) ?
2907       curr->join_cond_optim() : curr->join_cond();
2908     if (cond)
2909     {
2910       str->append(STRING_WITH_LEN(" on("));
2911       cond->print(str, query_type);
2912       str->append(')');
2913     }
2914   }
2915 }
2916 
2917 
2918 /**
2919   Print joins from the FROM clause.
2920 
2921   @param thd     thread handler
2922   @param str     string where table should be printed
2923   @param tables  list of tables in join
2924   @query_type    type of the query is being generated
2925 */
2926 
print_join(THD * thd,String * str,List<TABLE_LIST> * tables,enum_query_type query_type)2927 static void print_join(THD *thd,
2928                        String *str,
2929                        List<TABLE_LIST> *tables,
2930                        enum_query_type query_type)
2931 {
2932   /* List is reversed => we should reverse it before using */
2933   List_iterator_fast<TABLE_LIST> ti(*tables);
2934   TABLE_LIST **table;
2935 
2936   /*
2937     If the QT_NO_DATA_EXPANSION flag is specified, we print the
2938     original table list, including constant tables that have been
2939     optimized away, as the constant tables may be referenced in the
2940     expression printed by Item_field::print() when this flag is given.
2941     Otherwise, only non-const tables are printed.
2942 
2943     Example:
2944 
2945     Original SQL:
2946     select * from (select 1) t
2947 
2948     Printed without QT_NO_DATA_EXPANSION:
2949     select '1' AS `1` from dual
2950 
2951     Printed with QT_NO_DATA_EXPANSION:
2952     select `t`.`1` from (select 1 AS `1`) `t`
2953   */
2954   const bool print_const_tables= (query_type & QT_NO_DATA_EXPANSION);
2955   size_t tables_to_print= 0;
2956 
2957   for (TABLE_LIST *t= ti++; t ; t= ti++)
2958     if (print_const_tables || !t->optimized_away)
2959       tables_to_print++;
2960   if (tables_to_print == 0)
2961   {
2962     str->append(STRING_WITH_LEN("dual"));
2963     return; // all tables were optimized away
2964   }
2965   ti.rewind();
2966 
2967   if (!(table= static_cast<TABLE_LIST **>(thd->alloc(sizeof(TABLE_LIST*) *
2968                                                      tables_to_print))))
2969     return;  // out of memory
2970 
2971   TABLE_LIST *tmp, **t= table + (tables_to_print - 1);
2972   while ((tmp= ti++))
2973   {
2974     if (tmp->optimized_away && !print_const_tables)
2975       continue;
2976     *t--= tmp;
2977   }
2978 
2979   /*
2980     If the first table is a semi-join nest, swap it with something that is
2981     not a semi-join nest. This is necessary because "A SEMIJOIN B" is not the
2982     same as "B SEMIJOIN A".
2983   */
2984   if ((*table)->sj_cond())
2985   {
2986     TABLE_LIST **end= table + tables_to_print;
2987     for (TABLE_LIST **t2= table; t2!=end; t2++)
2988     {
2989       if (!(*t2)->sj_cond())
2990       {
2991         TABLE_LIST *tmp= *t2;
2992         *t2= *table;
2993         *table= tmp;
2994         break;
2995       }
2996     }
2997   }
2998   assert(tables_to_print >= 1);
2999   print_table_array(thd, str, table, table + tables_to_print, query_type);
3000 }
3001 
3002 
3003 /**
3004   @returns whether a database is equal to the connection's default database
3005 */
db_is_default_db(const char * db,size_t db_len,const THD * thd)3006 bool db_is_default_db(const char *db, size_t db_len, const THD *thd)
3007 {
3008   return thd != NULL && thd->db().str != NULL &&
3009     thd->db().length == db_len && !memcmp(db, thd->db().str, db_len);
3010 }
3011 
3012 
3013 /*.*
3014   Print table as it should be in join list.
3015 
3016   @param str   string where table should be printed
3017 */
3018 
print(THD * thd,String * str,enum_query_type query_type) const3019 void TABLE_LIST::print(THD *thd, String *str, enum_query_type query_type) const
3020 {
3021   if (nested_join)
3022   {
3023     str->append('(');
3024     print_join(thd, str, &nested_join->join_list, query_type);
3025     str->append(')');
3026   }
3027   else
3028   {
3029     const char *cmp_name;                         // Name to compare with alias
3030     if (view_name.str)
3031     {
3032       // A view
3033       if (!(query_type & QT_NO_DB) &&
3034           !((query_type & QT_NO_DEFAULT_DB) &&
3035             db_is_default_db(view_db.str, view_db.length, thd)))
3036       {
3037         append_identifier(thd, str, view_db.str, view_db.length);
3038         str->append('.');
3039       }
3040       append_identifier(thd, str, view_name.str, view_name.length);
3041       cmp_name= view_name.str;
3042     }
3043     else if (is_derived() && !is_merged())
3044     {
3045       // A derived table that is materialized or without specified algorithm
3046       if (!(query_type & QT_DERIVED_TABLE_ONLY_ALIAS))
3047       {
3048         str->append('(');
3049         derived->print(str, query_type);
3050         str->append(')');
3051       }
3052       cmp_name= "";                               // Force printing of alias
3053     }
3054     else
3055     {
3056       // A normal table
3057 
3058       if (!(query_type & QT_NO_DB) &&
3059           !((query_type & QT_NO_DEFAULT_DB) &&
3060             db_is_default_db(db, db_length, thd)))
3061       {
3062         append_identifier(thd, str, db, db_length);
3063         str->append('.');
3064       }
3065       if (schema_table)
3066       {
3067         append_identifier(thd, str, schema_table_name,
3068                           strlen(schema_table_name));
3069         cmp_name= schema_table_name;
3070       }
3071       else
3072       {
3073         /**
3074          Fix for printing empty string when internal_table_name is
3075          used. Actual length of internal_table_name cannot be reduced
3076          as server expects a valid string of length atleast 1 for any
3077          table. So while printing we use the correct length of the
3078          table_name i.e 0 when internal_table_name is used.
3079         */
3080         if (table_name != internal_table_name)
3081           append_identifier(thd, str, table_name, table_name_length);
3082         else
3083           append_identifier(thd, str, table_name, 0);
3084         cmp_name= table_name;
3085       }
3086       if (partition_names && partition_names->elements)
3087       {
3088         int i, num_parts= partition_names->elements;
3089         List_iterator<String> name_it(*(partition_names));
3090         str->append(STRING_WITH_LEN(" PARTITION ("));
3091         for (i= 1; i <= num_parts; i++)
3092         {
3093           String *name= name_it++;
3094           append_identifier(thd, str, name->c_ptr(), name->length());
3095           if (i != num_parts)
3096             str->append(',');
3097         }
3098         str->append(')');
3099       }
3100     }
3101     if (my_strcasecmp(table_alias_charset, cmp_name, alias))
3102     {
3103       char t_alias_buff[MAX_ALIAS_NAME];
3104       const char *t_alias= alias;
3105 
3106       str->append(' ');
3107       if (lower_case_table_names== 1)
3108       {
3109         if (alias && alias[0])
3110         {
3111           my_stpcpy(t_alias_buff, alias);
3112           my_casedn_str(files_charset_info, t_alias_buff);
3113           t_alias= t_alias_buff;
3114         }
3115       }
3116 
3117       append_identifier(thd, str, t_alias, strlen(t_alias));
3118     }
3119 
3120     if (index_hints)
3121     {
3122       List_iterator<Index_hint> it(*index_hints);
3123       Index_hint *hint;
3124 
3125       while ((hint= it++))
3126       {
3127         str->append (STRING_WITH_LEN(" "));
3128         hint->print (thd, str);
3129       }
3130     }
3131   }
3132 }
3133 
3134 
print(THD * thd,String * str,enum_query_type query_type)3135 void st_select_lex::print(THD *thd, String *str, enum_query_type query_type)
3136 {
3137   /* QQ: thd may not be set for sub queries, but this should be fixed */
3138   if (!thd)
3139     thd= current_thd;
3140 
3141   if (query_type & QT_SHOW_SELECT_NUMBER)
3142   {
3143     /* it makes EXPLAIN's "id" column understandable */
3144     str->append("/* select#");
3145     if (unlikely(select_number >= INT_MAX))
3146       str->append("fake");
3147     else
3148       str->append_ulonglong(select_number);
3149     str->append(" */ select ");
3150   }
3151   else
3152     str->append(STRING_WITH_LEN("select "));
3153 
3154   if (thd->lex->opt_hints_global)
3155   {
3156     char buff[NAME_LEN];
3157     String hint_str(buff, sizeof(buff), system_charset_info);
3158     hint_str.length(0);
3159 
3160     if (select_number == 1)
3161     {
3162       if (opt_hints_qb)
3163         opt_hints_qb->append_qb_hint(thd, &hint_str);
3164       thd->lex->opt_hints_global->print(thd, &hint_str, query_type);
3165     }
3166     else if (opt_hints_qb)
3167       opt_hints_qb->append_qb_hint(thd, &hint_str);
3168 
3169     if (hint_str.length() > 0)
3170     {
3171       str->append(STRING_WITH_LEN("/*+ "));
3172       str->append(hint_str.ptr(), hint_str.length());
3173       str->append(STRING_WITH_LEN("*/ "));
3174     }
3175   }
3176 
3177   if (thd->is_error())
3178   {
3179     /*
3180       It is possible that this query block had an optimization error, but the
3181       caller didn't notice (caller evaluted this as a subquery and
3182       Item::val*() don't have an error status). In this case the query block
3183       may be broken and printing it may crash.
3184     */
3185     str->append(STRING_WITH_LEN("had some error"));
3186     return;
3187   }
3188   /*
3189    In order to provide info for EXPLAIN FOR CONNECTION units shouldn't
3190    be completely cleaned till the end of the query. This is valid only for
3191    explainable commands.
3192   */
3193   assert(!(master_unit()->cleaned == SELECT_LEX_UNIT::UC_CLEAN &&
3194            is_explainable_query(thd->lex->sql_command)));
3195 
3196   /* First add options */
3197   if (active_options() & SELECT_STRAIGHT_JOIN)
3198     str->append(STRING_WITH_LEN("straight_join "));
3199   if (active_options() & SELECT_HIGH_PRIORITY)
3200     str->append(STRING_WITH_LEN("high_priority "));
3201   if (active_options() & SELECT_DISTINCT)
3202     str->append(STRING_WITH_LEN("distinct "));
3203   if (active_options() & SELECT_SMALL_RESULT)
3204     str->append(STRING_WITH_LEN("sql_small_result "));
3205   if (active_options() & SELECT_BIG_RESULT)
3206     str->append(STRING_WITH_LEN("sql_big_result "));
3207   if (active_options() & OPTION_BUFFER_RESULT)
3208     str->append(STRING_WITH_LEN("sql_buffer_result "));
3209   if (active_options() & OPTION_FOUND_ROWS)
3210     str->append(STRING_WITH_LEN("sql_calc_found_rows "));
3211   switch (sql_cache)
3212   {
3213     case SQL_NO_CACHE:
3214       str->append(STRING_WITH_LEN("sql_no_cache "));
3215       break;
3216     case SQL_CACHE:
3217       str->append(STRING_WITH_LEN("sql_cache "));
3218       break;
3219     case SQL_CACHE_UNSPECIFIED:
3220       break;
3221     default:
3222       assert(0);
3223   }
3224 
3225   //Item List
3226   bool first= 1;
3227   List_iterator_fast<Item> it(item_list);
3228   Item *item;
3229   while ((item= it++))
3230   {
3231     if (first)
3232       first= 0;
3233     else
3234       str->append(',');
3235 
3236     if (master_unit()->item && item->item_name.is_autogenerated())
3237     {
3238       /*
3239         Do not print auto-generated aliases in subqueries. It has no purpose
3240         in a view definition or other contexts where the query is printed.
3241       */
3242       item->print(str, query_type);
3243     }
3244     else
3245       item->print_item_w_name(str, query_type);
3246     /** @note that 'INTO variable' clauses are not printed */
3247   }
3248 
3249   /*
3250     from clause
3251     TODO: support USING/FORCE/IGNORE index
3252   */
3253   if (table_list.elements)
3254   {
3255     str->append(STRING_WITH_LEN(" from "));
3256     /* go through join tree */
3257     print_join(thd, str, &top_join_list, query_type);
3258   }
3259   else if (m_where_cond)
3260   {
3261     /*
3262       "SELECT 1 FROM DUAL WHERE 2" should not be printed as
3263       "SELECT 1 WHERE 2": the 1st syntax is valid, but the 2nd is not.
3264     */
3265     str->append(STRING_WITH_LEN(" from DUAL "));
3266   }
3267 
3268   // Where
3269   Item *const cur_where=
3270     (join && join->is_optimized()) ? join->where_cond : m_where_cond;
3271 
3272   if (cur_where || cond_value != Item::COND_UNDEF)
3273   {
3274     str->append(STRING_WITH_LEN(" where "));
3275     if (cur_where)
3276       cur_where->print(str, query_type);
3277     else
3278       str->append(cond_value != Item::COND_FALSE ? "1" : "0");
3279   }
3280 
3281   // group by & olap
3282   if (group_list.elements)
3283   {
3284     str->append(STRING_WITH_LEN(" group by "));
3285     print_order(str, group_list.first, query_type);
3286     switch (olap)
3287     {
3288       case CUBE_TYPE:
3289 	str->append(STRING_WITH_LEN(" with cube"));
3290 	break;
3291       case ROLLUP_TYPE:
3292 	str->append(STRING_WITH_LEN(" with rollup"));
3293 	break;
3294       default:
3295 	;  //satisfy compiler
3296     }
3297   }
3298 
3299   // having
3300   Item *const cur_having= (join && join->having_for_explain != (Item*)1) ?
3301     join->having_for_explain : m_having_cond;
3302 
3303   if (cur_having || having_value != Item::COND_UNDEF)
3304   {
3305     str->append(STRING_WITH_LEN(" having "));
3306     if (cur_having)
3307       cur_having->print(str, query_type);
3308     else
3309       str->append(having_value != Item::COND_FALSE ? "1" : "0");
3310   }
3311 
3312   if (order_list.elements)
3313   {
3314     str->append(STRING_WITH_LEN(" order by "));
3315     print_order(str, order_list.first, query_type);
3316   }
3317 
3318   // limit
3319   print_limit(thd, str, query_type);
3320 
3321   // PROCEDURE unsupported here
3322 }
3323 
3324 
get_walk_flags(const Select_lex_visitor * visitor)3325 Item::enum_walk get_walk_flags(const Select_lex_visitor *visitor)
3326 {
3327   if (visitor->visits_in_prefix_order())
3328     return Item::WALK_SUBQUERY_PREFIX;
3329   else
3330     return Item::WALK_SUBQUERY_POSTFIX;
3331 }
3332 
3333 
walk_item(Item * item,Select_lex_visitor * visitor)3334 bool walk_item(Item *item, Select_lex_visitor *visitor)
3335 {
3336   if (item == NULL)
3337     return false;
3338   return item->walk(&Item::visitor_processor, get_walk_flags(visitor),
3339                     pointer_cast<uchar*>(visitor));
3340 }
3341 
3342 
accept_for_order(SQL_I_List<ORDER> orders,Select_lex_visitor * visitor)3343 static bool accept_for_order(SQL_I_List<ORDER> orders,
3344                              Select_lex_visitor *visitor)
3345 {
3346   if (orders.elements == 0)
3347     return false;
3348 
3349   for (ORDER *order= orders.first; order != NULL; order= order->next)
3350     if (walk_item(*order->item, visitor))
3351       return true;
3352   return false;
3353 }
3354 
accept(Select_lex_visitor * visitor)3355 bool st_select_lex_unit::accept(Select_lex_visitor *visitor)
3356 {
3357   SELECT_LEX *end= NULL;
3358   for (SELECT_LEX *sl= first_select(); sl != end; sl= sl->next_select())
3359     if (sl->accept(visitor))
3360       return true;
3361 
3362   if (fake_select_lex &&
3363       accept_for_order(fake_select_lex->order_list, visitor))
3364     return true;
3365 
3366   return visitor->visit(this);
3367 }
3368 
3369 
accept_for_join(List<TABLE_LIST> * tables,Select_lex_visitor * visitor)3370 static bool accept_for_join(List<TABLE_LIST> *tables,
3371                             Select_lex_visitor *visitor)
3372 {
3373   List_iterator<TABLE_LIST> ti(*tables);
3374   TABLE_LIST *end= NULL;
3375   for (TABLE_LIST *t= ti++; t != end; t= ti++)
3376   {
3377     if (t->nested_join && accept_for_join(&t->nested_join->join_list, visitor))
3378       return true;
3379     else if (t->is_derived())
3380       t->derived_unit()->accept(visitor);
3381     if (walk_item(t->join_cond(), visitor))
3382         return true;
3383   }
3384   return false;
3385 }
3386 
3387 
accept(Select_lex_visitor * visitor)3388 bool st_select_lex::accept(Select_lex_visitor *visitor)
3389 {
3390   // Select clause
3391   List_iterator<Item> it(item_list);
3392   Item *end= NULL;
3393   for (Item *item= it++; item != end; item= it++)
3394     if (walk_item(item, visitor))
3395       return true;
3396 
3397   // From clause
3398   if (table_list.elements != 0 && accept_for_join(join_list, visitor))
3399       return true;
3400 
3401   // Where clause
3402   Item *where_condition= join != NULL ? join->where_cond : m_where_cond;
3403   if (where_condition != NULL && walk_item(where_condition, visitor))
3404     return true;
3405 
3406   // Group by and olap clauses
3407   if (accept_for_order(group_list, visitor))
3408     return true;
3409 
3410   // Having clause
3411   Item *having_condition=
3412     join != NULL ? join->having_for_explain : m_having_cond;
3413   if (walk_item(having_condition, visitor))
3414     return true;
3415 
3416   // Order clause
3417   if (accept_for_order(order_list, visitor))
3418     return true;
3419 
3420   // Limit clause
3421   if (explicit_limit)
3422     if (walk_item(offset_limit, visitor) || walk_item(select_limit, visitor))
3423       return true;
3424 
3425   return visitor->visit(this);
3426 }
3427 
3428 
3429 /**
3430   @brief Restore the LEX and THD in case of a parse error.
3431 
3432   This is a clean up call that is invoked by the Bison generated
3433   parser before returning an error from MYSQLparse. If your
3434   semantic actions manipulate with the global thread state (which
3435   is a very bad practice and should not normally be employed) and
3436   need a clean-up in case of error, and you can not use %destructor
3437   rule in the grammar file itself, this function should be used
3438   to implement the clean up.
3439 */
3440 
cleanup_lex_after_parse_error(THD * thd)3441 void LEX::cleanup_lex_after_parse_error(THD *thd)
3442 {
3443   sp_head *sp= thd->lex->sphead;
3444 
3445   if (sp)
3446   {
3447     sp->m_parser_data.finish_parsing_sp_body(thd);
3448     //  Do not delete sp_head if is invoked in the context of sp execution.
3449     if (thd->sp_runtime_ctx == NULL)
3450     {
3451       delete sp;
3452       thd->lex->sphead= NULL;
3453     }
3454   }
3455 }
3456 
3457 /*
3458   Initialize (or reset) Query_tables_list object.
3459 
3460   SYNOPSIS
3461     reset_query_tables_list()
3462       init  TRUE  - we should perform full initialization of object with
3463                     allocating needed memory
3464             FALSE - object is already initialized so we should only reset
3465                     its state so it can be used for parsing/processing
3466                     of new statement
3467 
3468   DESCRIPTION
3469     This method initializes Query_tables_list so it can be used as part
3470     of LEX object for parsing/processing of statement. One can also use
3471     this method to reset state of already initialized Query_tables_list
3472     so it can be used for processing of new statement.
3473 */
3474 
reset_query_tables_list(bool init)3475 void Query_tables_list::reset_query_tables_list(bool init)
3476 {
3477   sql_command= SQLCOM_END;
3478   if (!init && query_tables)
3479   {
3480     TABLE_LIST *table= query_tables;
3481     for (;;)
3482     {
3483       delete table->view_query();
3484       if (query_tables_last == &table->next_global ||
3485           !(table= table->next_global))
3486         break;
3487     }
3488   }
3489   query_tables= 0;
3490   query_tables_last= &query_tables;
3491   query_tables_own_last= 0;
3492   if (init)
3493   {
3494     /*
3495       We delay real initialization of hash (and therefore related
3496       memory allocation) until first insertion into this hash.
3497     */
3498     my_hash_clear(&sroutines);
3499   }
3500   else if (sroutines.records)
3501   {
3502     /* Non-zero sroutines.records means that hash was initialized. */
3503     my_hash_reset(&sroutines);
3504   }
3505   sroutines_list.empty();
3506   sroutines_list_own_last= sroutines_list.next;
3507   sroutines_list_own_elements= 0;
3508   binlog_stmt_flags= 0;
3509   stmt_accessed_table_flag= 0;
3510   lock_tables_state= LTS_NOT_LOCKED;
3511   table_count= 0;
3512   using_match= FALSE;
3513 
3514   /* Check the max size of the enum to control new enum values definitions. */
3515   compile_time_assert(BINLOG_STMT_UNSAFE_COUNT <= 32);
3516 }
3517 
3518 
3519 /*
3520   Destroy Query_tables_list object with freeing all resources used by it.
3521 
3522   SYNOPSIS
3523     destroy_query_tables_list()
3524 */
3525 
destroy_query_tables_list()3526 void Query_tables_list::destroy_query_tables_list()
3527 {
3528   my_hash_free(&sroutines);
3529 }
3530 
3531 
3532 /*
3533   Initialize LEX object.
3534 
3535   SYNOPSIS
3536     LEX::LEX()
3537 
3538   NOTE
3539     LEX object initialized with this constructor can be used as part of
3540     THD object for which one can safely call open_tables(), lock_tables()
3541     and close_thread_tables() functions. But it is not yet ready for
3542     statement parsing. On should use lex_start() function to prepare LEX
3543     for this.
3544 */
3545 
LEX()3546 LEX::LEX()
3547   :result(0), thd(NULL), opt_hints_global(NULL),
3548    // Quite unlikely to overflow initial allocation, so no instrumentation.
3549    plugins(PSI_NOT_INSTRUMENTED),
3550    insert_update_values_map(NULL),
3551    option_type(OPT_DEFAULT),
3552    sphead(NULL),
3553    is_set_password_sql(false),
3554    // Initialize here to avoid uninitialized variable warnings.
3555    contains_plaintext_password(false),
3556    keep_diagnostics(DA_KEEP_UNSPECIFIED),
3557    is_lex_started(0),
3558   in_update_value_clause(false)
3559 {
3560   reset_query_tables_list(TRUE);
3561 }
3562 
3563 
3564 /**
3565   check if command can use VIEW with MERGE algorithm (for top VIEWs)
3566 
3567   @details
3568     Only listed here commands can use merge algorithm in top level
3569     SELECT_LEX (for subqueries will be used merge algorithm if
3570     LEX::can_not_use_merged() is not TRUE).
3571 
3572   @todo - Add SET as a command that can use merged views. Due to how
3573           all uses would be embedded in subqueries, this test is worthless
3574           for the SET command anyway.
3575 
3576   @returns true if command can use merged VIEWs, false otherwise
3577 */
3578 
can_use_merged()3579 bool LEX::can_use_merged()
3580 {
3581   switch (sql_command)
3582   {
3583   case SQLCOM_SELECT:
3584   case SQLCOM_CREATE_TABLE:
3585   case SQLCOM_UPDATE:
3586   case SQLCOM_UPDATE_MULTI:
3587   case SQLCOM_DELETE:
3588   case SQLCOM_DELETE_MULTI:
3589   case SQLCOM_INSERT:
3590   case SQLCOM_INSERT_SELECT:
3591   case SQLCOM_REPLACE:
3592   case SQLCOM_REPLACE_SELECT:
3593   case SQLCOM_LOAD:
3594     return TRUE;
3595   default:
3596     return FALSE;
3597   }
3598 }
3599 
3600 /**
3601   Check if command can't use merged views in any part of command
3602 
3603   @details
3604     Temporary table algorithm will be used on all SELECT levels for queries
3605     listed here (see also LEX::can_use_merged()).
3606 
3607   @returns true if command cannot use merged view, false otherwise
3608 */
3609 
can_not_use_merged()3610 bool LEX::can_not_use_merged()
3611 {
3612   switch (sql_command)
3613   {
3614   case SQLCOM_CREATE_VIEW:
3615   case SQLCOM_SHOW_CREATE:
3616   /*
3617     SQLCOM_SHOW_FIELDS is necessary to make
3618     information schema tables working correctly with views.
3619     see get_schema_tables_result function
3620   */
3621   case SQLCOM_SHOW_FIELDS:
3622     return TRUE;
3623   default:
3624     return FALSE;
3625   }
3626 }
3627 
3628 /*
3629   Detect that we need only table structure of derived table/view
3630 
3631   SYNOPSIS
3632     only_view_structure()
3633 
3634   RETURN
3635     TRUE yes, we need only structure
3636     FALSE no, we need data
3637 */
3638 
only_view_structure()3639 bool LEX::only_view_structure()
3640 {
3641   switch (sql_command) {
3642   case SQLCOM_SHOW_CREATE:
3643   case SQLCOM_SHOW_TABLES:
3644   case SQLCOM_SHOW_FIELDS:
3645   case SQLCOM_REVOKE_ALL:
3646   case SQLCOM_REVOKE:
3647   case SQLCOM_GRANT:
3648   case SQLCOM_CREATE_VIEW:
3649     return TRUE;
3650   default:
3651     return FALSE;
3652   }
3653 }
3654 
3655 
3656 /*
3657   Should Items_ident be printed correctly
3658 
3659   SYNOPSIS
3660     need_correct_ident()
3661 
3662   RETURN
3663     TRUE yes, we need only structure
3664     FALSE no, we need data
3665 */
3666 
3667 
need_correct_ident()3668 bool LEX::need_correct_ident()
3669 {
3670   switch(sql_command)
3671   {
3672   case SQLCOM_SHOW_CREATE:
3673   case SQLCOM_SHOW_TABLES:
3674   case SQLCOM_CREATE_VIEW:
3675     return TRUE;
3676   default:
3677     return FALSE;
3678   }
3679 }
3680 
3681 
3682 /**
3683   This method should be called only during parsing.
3684   It is aware of compound statements (stored routine bodies)
3685   and will initialize the destination with the default
3686   database of the stored routine, rather than the default
3687   database of the connection it is parsed in.
3688   E.g. if one has no current database selected, or current database
3689   set to 'bar' and then issues:
3690 
3691   CREATE PROCEDURE foo.p1() BEGIN SELECT * FROM t1 END//
3692 
3693   t1 is meant to refer to foo.t1, not to bar.t1.
3694 
3695   This method is needed to support this rule.
3696 
3697   @return TRUE in case of error (parsing should be aborted, FALSE in
3698   case of success
3699 */
3700 
3701 bool
copy_db_to(char ** p_db,size_t * p_db_length) const3702 LEX::copy_db_to(char **p_db, size_t *p_db_length) const
3703 {
3704   if (sphead)
3705   {
3706     assert(sphead->m_db.str && sphead->m_db.length);
3707     /*
3708       It is safe to assign the string by-pointer, both sphead and
3709       its statements reside in the same memory root.
3710     */
3711     *p_db= sphead->m_db.str;
3712     if (p_db_length)
3713       *p_db_length= sphead->m_db.length;
3714     return FALSE;
3715   }
3716   return thd->copy_db_to(p_db, p_db_length);
3717 }
3718 
3719 
3720 /**
3721   Initialize offset and limit counters.
3722 
3723   @param sl SELECT_LEX to get offset and limit from.
3724 */
set_limit(st_select_lex * sl)3725 void st_select_lex_unit::set_limit(st_select_lex *sl)
3726 {
3727   assert(!thd->stmt_arena->is_stmt_prepare());
3728 
3729   offset_limit_cnt= sl->get_offset();
3730   select_limit_cnt= sl->get_limit();
3731   if (select_limit_cnt + offset_limit_cnt >= select_limit_cnt)
3732     select_limit_cnt+= offset_limit_cnt;
3733   else
3734     select_limit_cnt= HA_POS_ERROR;
3735 }
3736 
3737 
3738 /**
3739   Decide if a temporary table is needed for the UNION.
3740 
3741   @retval true  A temporary table is needed.
3742   @retval false A temporary table is not needed.
3743  */
union_needs_tmp_table()3744 bool st_select_lex_unit::union_needs_tmp_table()
3745 {
3746   return union_distinct != NULL ||
3747     global_parameters()->order_list.elements != 0 ||
3748     thd->lex->sql_command == SQLCOM_INSERT_SELECT ||
3749     thd->lex->sql_command == SQLCOM_REPLACE_SELECT;
3750 }
3751 
3752 
3753 /**
3754   Include a query expression below a query block.
3755 
3756   @param lex:   Containing LEX object
3757   @param outer: The query block that this query expression is included below.
3758 */
include_down(LEX * lex,st_select_lex * outer)3759 void st_select_lex_unit::include_down(LEX *lex, st_select_lex *outer)
3760 {
3761   if ((next= outer->slave))
3762     next->prev= &next;
3763   prev= &outer->slave;
3764   outer->slave= this;
3765   master= outer;
3766 
3767   renumber_selects(lex);
3768 }
3769 
3770 
3771 /**
3772   Include a complete chain of query expressions below a query block.
3773 
3774   @param lex:   Containing LEX object
3775   @param outer: The query block that the chain is included below.
3776 
3777   @note
3778     "this" is pointer to the first query expression in the chain.
3779 */
include_chain(LEX * lex,st_select_lex * outer)3780 void st_select_lex_unit::include_chain(LEX *lex, st_select_lex *outer)
3781 {
3782   st_select_lex_unit *last_unit= this; // Initialization needed for gcc
3783   for (st_select_lex_unit *unit= this; unit != NULL; unit= unit->next)
3784   {
3785     unit->master= outer; // Link to the outer query block
3786     unit->renumber_selects(lex);
3787     last_unit= unit;
3788   }
3789 
3790   if ((last_unit->next= outer->slave))
3791     last_unit->next->prev= &last_unit->next;
3792   prev= &outer->slave;
3793   outer->slave= this;
3794 }
3795 
3796 
3797 /**
3798   Return true if query expression can be merged into an outer query.
3799   Being mergeable also means that derived table/view is updatable.
3800 
3801   A view/derived table is not mergeable if it is one of the following:
3802    - A union (implementation restriction).
3803    - An aggregated query, or has HAVING, or has DISTINCT
3804      (A general aggregated query cannot be merged with a non-aggregated one).
3805    - A table-less query (unimportant special case).
3806    - A query with a LIMIT (limit applies to subquery, so the implementation
3807      strategy is to materialize this subquery, including row count constraint).
3808    - A query that modifies variables (When variables are modified, try to
3809      preserve the original structure of the query. This is less likely to cause
3810      changes in variable assignment order).
3811 
3812   A view/derived table will also not be merged if it contains subqueries
3813   in the SELECT list that depend on columns from itself.
3814   Merging such objects is possible, but we assume they are made derived
3815   tables because the user wants them to be materialized, for performance
3816   reasons.
3817 
3818   One possible case is a derived table with dependent subqueries in the select
3819   list, used as the inner table of a left outer join. Such tables will always
3820   be read as many times as there are qualifying rows in the outer table,
3821   and the select list subqueries are evaluated for each row combination.
3822   The select list subqueries are evaluated the same number of times also with
3823   join buffering enabled, even though the table then only will be read once.
3824 
3825   When materialization hints are implemented, this decision may be reconsidered.
3826 */
3827 
is_mergeable() const3828 bool st_select_lex_unit::is_mergeable() const
3829 {
3830   if (is_union())
3831     return false;
3832 
3833   SELECT_LEX *const select= first_select();
3834   Item *item;
3835   List_iterator<Item> it(select->fields_list);
3836   while ((item= it++))
3837   {
3838     if (item->has_subquery() && item->used_tables())
3839       return false;
3840   }
3841   return !select->is_grouped() &&
3842          !select->having_cond() &&
3843          !select->is_distinct() &&
3844          select->table_list.elements > 0 &&
3845          !select->has_limit() &&
3846          thd->lex->set_var_list.elements == 0;
3847 }
3848 
3849 /**
3850   Renumber contained select_lex objects.
3851 
3852   @param  lex   Containing LEX object
3853 */
3854 
renumber_selects(LEX * lex)3855 void st_select_lex_unit::renumber_selects(LEX *lex)
3856 {
3857   for (SELECT_LEX *select= first_select(); select; select= select->next_select())
3858     select->renumber(lex);
3859   if (fake_select_lex)
3860     fake_select_lex->renumber(lex);
3861 }
3862 
3863 /**
3864   @brief Set the initial purpose of this TABLE_LIST object in the list of used
3865     tables.
3866 
3867   We need to track this information on table-by-table basis, since when this
3868   table becomes an element of the pre-locked list, it's impossible to identify
3869   which SQL sub-statement it has been originally used in.
3870 
3871   E.g.:
3872 
3873   User request:                 SELECT * FROM t1 WHERE f1();
3874   FUNCTION f1():                DELETE FROM t2; RETURN 1;
3875   BEFORE DELETE trigger on t2:  INSERT INTO t3 VALUES (old.a);
3876 
3877   For this user request, the pre-locked list will contain t1, t2, t3
3878   table elements, each needed for different DML.
3879 
3880   The trigger event map is updated to reflect INSERT, UPDATE, DELETE,
3881   REPLACE, LOAD DATA, CREATE TABLE .. SELECT, CREATE TABLE ..
3882   REPLACE SELECT statements, and additionally ON DUPLICATE KEY UPDATE
3883   clause.
3884 */
3885 
set_trg_event_type_for_tables()3886 void LEX::set_trg_event_type_for_tables()
3887 {
3888   uint8 new_trg_event_map= 0;
3889 
3890   /*
3891     Some auxiliary operations
3892     (e.g. GRANT processing) create TABLE_LIST instances outside
3893     the parser. Additionally, some commands (e.g. OPTIMIZE) change
3894     the lock type for a table only after parsing is done. Luckily,
3895     these do not fire triggers and do not need to pre-load them.
3896     For these TABLE_LISTs set_trg_event_type is never called, and
3897     trg_event_map is always empty. That means that the pre-locking
3898     algorithm will ignore triggers defined on these tables, if
3899     any, and the execution will either fail with an assert in
3900     sql_trigger.cc or with an error that a used table was not
3901     pre-locked, in case of a production build.
3902 
3903     TODO: this usage pattern creates unnecessary module dependencies
3904     and should be rewritten to go through the parser.
3905     Table list instances created outside the parser in most cases
3906     refer to mysql.* system tables. It is not allowed to have
3907     a trigger on a system table, but keeping track of
3908     initialization provides extra safety in case this limitation
3909     is circumvented.
3910   */
3911 
3912   switch (sql_command) {
3913   case SQLCOM_LOCK_TABLES:
3914   /*
3915     On a LOCK TABLE, all triggers must be pre-loaded for this TABLE_LIST
3916     when opening an associated TABLE.
3917   */
3918     new_trg_event_map= static_cast<uint8>
3919                         (1 << static_cast<int>(TRG_EVENT_INSERT)) |
3920                       static_cast<uint8>
3921                         (1 << static_cast<int>(TRG_EVENT_UPDATE)) |
3922                       static_cast<uint8>
3923                         (1 << static_cast<int>(TRG_EVENT_DELETE));
3924     break;
3925   /*
3926     Basic INSERT. If there is an additional ON DUPLIATE KEY UPDATE
3927     clause, it will be handled later in this method.
3928   */
3929   case SQLCOM_INSERT:                           /* fall through */
3930   case SQLCOM_INSERT_SELECT:
3931   /*
3932     LOAD DATA ... INFILE is expected to fire BEFORE/AFTER INSERT
3933     triggers.
3934     If the statement also has REPLACE clause, it will be
3935     handled later in this method.
3936   */
3937   case SQLCOM_LOAD:                             /* fall through */
3938   /*
3939     REPLACE is semantically equivalent to INSERT. In case
3940     of a primary or unique key conflict, it deletes the old
3941     record and inserts a new one. So we also may need to
3942     fire ON DELETE triggers. This functionality is handled
3943     later in this method.
3944   */
3945   case SQLCOM_REPLACE:                          /* fall through */
3946   case SQLCOM_REPLACE_SELECT:
3947   /*
3948     CREATE TABLE ... SELECT defaults to INSERT if the table or
3949     view already exists. REPLACE option of CREATE TABLE ...
3950     REPLACE SELECT is handled later in this method.
3951   */
3952   case SQLCOM_CREATE_TABLE:
3953     new_trg_event_map|= static_cast<uint8>
3954                           (1 << static_cast<int>(TRG_EVENT_INSERT));
3955     break;
3956   /* Basic update and multi-update */
3957   case SQLCOM_UPDATE:                           /* fall through */
3958   case SQLCOM_UPDATE_MULTI:
3959     new_trg_event_map|= static_cast<uint8>
3960                           (1 << static_cast<int>(TRG_EVENT_UPDATE));
3961     break;
3962   /* Basic delete and multi-delete */
3963   case SQLCOM_DELETE:                           /* fall through */
3964   case SQLCOM_DELETE_MULTI:
3965     new_trg_event_map|= static_cast<uint8>
3966                           (1 << static_cast<int>(TRG_EVENT_DELETE));
3967     break;
3968   default:
3969     break;
3970   }
3971 
3972   switch (duplicates) {
3973   case DUP_UPDATE:
3974     new_trg_event_map|= static_cast<uint8>
3975                           (1 << static_cast<int>(TRG_EVENT_UPDATE));
3976     break;
3977   case DUP_REPLACE:
3978     new_trg_event_map|= static_cast<uint8>
3979                           (1 << static_cast<int>(TRG_EVENT_DELETE));
3980     break;
3981   case DUP_ERROR:
3982   default:
3983     break;
3984   }
3985 
3986 
3987   /*
3988     Do not iterate over sub-selects, only the tables in the outermost
3989     SELECT_LEX can be modified, if any.
3990   */
3991   TABLE_LIST *tables= select_lex ? select_lex->get_table_list() : NULL;
3992   while (tables)
3993   {
3994     /*
3995       This is a fast check to filter out statements that do
3996       not change data, or tables  on the right side, in case of
3997       INSERT .. SELECT, CREATE TABLE .. SELECT and so on.
3998       Here we also filter out OPTIMIZE statement and non-updateable
3999       views, for which lock_type is TL_UNLOCK or TL_READ after
4000       parsing.
4001     */
4002     if (static_cast<int>(tables->lock_type) >=
4003         static_cast<int>(TL_WRITE_ALLOW_WRITE))
4004       tables->trg_event_map= new_trg_event_map;
4005     tables= tables->next_local;
4006   }
4007 }
4008 
4009 
4010 /*
4011   Unlink the first table from the global table list and the first table from
4012   outer select (lex->select_lex) local list
4013 
4014   SYNOPSIS
4015     unlink_first_table()
4016     link_to_local	Set to 1 if caller should link this table to local list
4017 
4018   NOTES
4019     We assume that first tables in both lists is the same table or the local
4020     list is empty.
4021 
4022   RETURN
4023     0	If 'query_tables' == 0
4024     unlinked table
4025       In this case link_to_local is set.
4026 
4027 */
unlink_first_table(bool * link_to_local)4028 TABLE_LIST *LEX::unlink_first_table(bool *link_to_local)
4029 {
4030   TABLE_LIST *first;
4031   if ((first= query_tables))
4032   {
4033     /*
4034       Exclude from global table list
4035     */
4036     if ((query_tables= query_tables->next_global))
4037       query_tables->prev_global= &query_tables;
4038     else
4039       query_tables_last= &query_tables;
4040     first->next_global= 0;
4041 
4042     if (query_tables_own_last == &first->next_global)
4043       query_tables_own_last= &query_tables;
4044 
4045     /*
4046       and from local list if it is not empty
4047     */
4048     if ((*link_to_local= MY_TEST(select_lex->get_table_list())))
4049     {
4050       select_lex->context.table_list=
4051         select_lex->context.first_name_resolution_table= first->next_local;
4052       select_lex->table_list.first= first->next_local;
4053       select_lex->table_list.elements--; //safety
4054       first->next_local= 0;
4055       /*
4056         Ensure that the global list has the same first table as the local
4057         list.
4058       */
4059       first_lists_tables_same();
4060     }
4061   }
4062   return first;
4063 }
4064 
4065 
4066 /*
4067   Bring first local table of first most outer select to first place in global
4068   table list
4069 
4070   SYNOPSYS
4071      LEX::first_lists_tables_same()
4072 
4073   NOTES
4074     In many cases (for example, usual INSERT/DELETE/...) the first table of
4075     main SELECT_LEX have special meaning => check that it is the first table
4076     in global list and re-link to be first in the global list if it is
4077     necessary.  We need such re-linking only for queries with sub-queries in
4078     the select list, as only in this case tables of sub-queries will go to
4079     the global list first.
4080 */
4081 
first_lists_tables_same()4082 void LEX::first_lists_tables_same()
4083 {
4084   TABLE_LIST *first_table= select_lex->get_table_list();
4085   if (query_tables != first_table && first_table != 0)
4086   {
4087     TABLE_LIST *next;
4088     if (query_tables_last == &first_table->next_global)
4089       query_tables_last= first_table->prev_global;
4090 
4091     if (query_tables_own_last == &first_table->next_global)
4092       query_tables_own_last= first_table->prev_global;
4093 
4094     if ((next= *first_table->prev_global= first_table->next_global))
4095       next->prev_global= first_table->prev_global;
4096     /* include in new place */
4097     first_table->next_global= query_tables;
4098     /*
4099        We are sure that query_tables is not 0, because first_table was not
4100        first table in the global list => we can use
4101        query_tables->prev_global without check of query_tables
4102     */
4103     query_tables->prev_global= &first_table->next_global;
4104     first_table->prev_global= &query_tables;
4105     query_tables= first_table;
4106   }
4107 }
4108 
4109 
4110 /*
4111   Link table back that was unlinked with unlink_first_table()
4112 
4113   SYNOPSIS
4114     link_first_table_back()
4115     link_to_local	do we need link this table to local
4116 
4117   RETURN
4118     global list
4119 */
4120 
link_first_table_back(TABLE_LIST * first,bool link_to_local)4121 void LEX::link_first_table_back(TABLE_LIST *first,
4122 				   bool link_to_local)
4123 {
4124   if (first)
4125   {
4126     if ((first->next_global= query_tables))
4127       query_tables->prev_global= &first->next_global;
4128     else
4129       query_tables_last= &first->next_global;
4130 
4131     if (query_tables_own_last == &query_tables)
4132       query_tables_own_last= &first->next_global;
4133 
4134     query_tables= first;
4135 
4136     if (link_to_local)
4137     {
4138       first->next_local= select_lex->table_list.first;
4139       select_lex->context.table_list= first;
4140       select_lex->table_list.first= first;
4141       select_lex->table_list.elements++; //safety
4142     }
4143   }
4144 }
4145 
4146 
4147 
4148 /*
4149   cleanup lex for case when we open table by table for processing
4150 
4151   SYNOPSIS
4152     LEX::cleanup_after_one_table_open()
4153 
4154   NOTE
4155     This method is mostly responsible for cleaning up of selects lists and
4156     derived tables state. To rollback changes in Query_tables_list one has
4157     to call Query_tables_list::reset_query_tables_list(FALSE).
4158 */
4159 
cleanup_after_one_table_open()4160 void LEX::cleanup_after_one_table_open()
4161 {
4162   /*
4163     thd->lex->derived_tables & additional units may be set if we open
4164     a view. It is necessary to clear thd->lex->derived_tables flag
4165     to prevent processing of derived tables during next open_and_lock_tables
4166     if next table is a real table and cleanup & remove underlying units
4167     NOTE: all units will be connected to thd->lex->select_lex, because we
4168     have not UNION on most upper level.
4169     */
4170   if (all_selects_list != select_lex)
4171   {
4172     derived_tables= 0;
4173     /* cleunup underlying units (units of VIEW) */
4174     for (SELECT_LEX_UNIT *un= select_lex->first_inner_unit();
4175          un;
4176          un= un->next_unit())
4177       un->cleanup(true);
4178     /* reduce all selects list to default state */
4179     all_selects_list= select_lex;
4180     /* remove underlying units (units of VIEW) subtree */
4181     select_lex->cut_subtree();
4182   }
4183 }
4184 
4185 
4186 /*
4187   Save current state of Query_tables_list for this LEX, and prepare it
4188   for processing of new statemnt.
4189 
4190   SYNOPSIS
4191     reset_n_backup_query_tables_list()
4192       backup  Pointer to Query_tables_list instance to be used for backup
4193 */
4194 
reset_n_backup_query_tables_list(Query_tables_list * backup)4195 void LEX::reset_n_backup_query_tables_list(Query_tables_list *backup)
4196 {
4197   backup->set_query_tables_list(this);
4198   /*
4199     We have to perform full initialization here since otherwise we
4200     will damage backed up state.
4201   */
4202   this->reset_query_tables_list(TRUE);
4203 }
4204 
4205 
4206 /*
4207   Restore state of Query_tables_list for this LEX from backup.
4208 
4209   SYNOPSIS
4210     restore_backup_query_tables_list()
4211       backup  Pointer to Query_tables_list instance used for backup
4212 */
4213 
restore_backup_query_tables_list(Query_tables_list * backup)4214 void LEX::restore_backup_query_tables_list(Query_tables_list *backup)
4215 {
4216   this->destroy_query_tables_list();
4217   this->set_query_tables_list(backup);
4218 }
4219 
4220 
4221 /*
4222   Checks for usage of routines and/or tables in a parsed statement
4223 
4224   SYNOPSIS
4225     LEX:table_or_sp_used()
4226 
4227   RETURN
4228     FALSE  No routines and tables used
4229     TRUE   Either or both routines and tables are used.
4230 */
4231 
table_or_sp_used()4232 bool LEX::table_or_sp_used()
4233 {
4234   DBUG_ENTER("table_or_sp_used");
4235 
4236   if (sroutines.records || query_tables)
4237     DBUG_RETURN(TRUE);
4238 
4239   DBUG_RETURN(FALSE);
4240 }
4241 
4242 
4243 void
fix_prepare_information_for_order(THD * thd,SQL_I_List<ORDER> * list,Group_list_ptrs ** list_ptrs)4244 st_select_lex::fix_prepare_information_for_order(THD *thd,
4245                                                  SQL_I_List<ORDER> *list,
4246                                                  Group_list_ptrs **list_ptrs)
4247 {
4248   Group_list_ptrs *p= *list_ptrs;
4249   if (!p)
4250   {
4251     void *mem= thd->stmt_arena->alloc(sizeof(Group_list_ptrs));
4252     *list_ptrs= p= new (mem) Group_list_ptrs(thd->stmt_arena->mem_root);
4253   }
4254   p->reserve(list->elements);
4255   for (ORDER *order= list->first; order; order= order->next)
4256     p->push_back(order);
4257 }
4258 
4259 
4260 /*
4261   Saves the chain of ORDER::next in group_list and order_list, in
4262   case the list is modified by remove_const().
4263 
4264   @param thd          thread handler
4265 */
4266 
fix_prepare_information(THD * thd)4267 void st_select_lex::fix_prepare_information(THD *thd)
4268 {
4269   if (!first_execution)
4270     return;
4271   first_execution= false;
4272   if (thd->stmt_arena->is_conventional())
4273     return;
4274   if (group_list.first)
4275     fix_prepare_information_for_order(thd, &group_list, &group_list_ptrs);
4276   if (order_list.first)
4277     fix_prepare_information_for_order(thd, &order_list, &order_list_ptrs);
4278 }
4279 
4280 
4281 /*
4282   There are st_select_lex::add_table_to_list &
4283   st_select_lex::set_lock_for_tables are in sql_parse.cc
4284 
4285   st_select_lex::print is in sql_select.cc
4286 
4287   st_select_lex_unit::prepare, st_select_lex_unit::exec,
4288   st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
4289   st_select_lex_unit::change_query_result
4290   are in sql_union.cc
4291 */
4292 
4293 
type()4294 st_select_lex::type_enum st_select_lex::type()
4295 {
4296   if (master_unit()->fake_select_lex == this)
4297     return SLT_UNION_RESULT;
4298   else if (!master_unit()->outer_select() &&
4299            master_unit()->first_select() == this)
4300   {
4301     if (first_inner_unit() || next_select())
4302       return SLT_PRIMARY;
4303     else
4304       return SLT_SIMPLE;
4305   }
4306   else if (this == master_unit()->first_select())
4307   {
4308     if (linkage == DERIVED_TABLE_TYPE)
4309       return SLT_DERIVED;
4310     else
4311       return SLT_SUBQUERY;
4312   }
4313   else
4314     return SLT_UNION;
4315 }
4316 
4317 
4318 
4319 /**
4320   Add this query block below the specified query expression.
4321 
4322   @param lex   Containing LEX object
4323   @param outer Query expression that query block is added to.
4324 
4325   @note that this query block can never have any underlying query expressions,
4326         hence it is not necessary to e.g. renumber those, like e.g.
4327         st_select_lex_unit::include_down() does.
4328 */
include_down(LEX * lex,st_select_lex_unit * outer)4329 void st_select_lex::include_down(LEX *lex, st_select_lex_unit *outer)
4330 {
4331   assert(slave == NULL);
4332 
4333   if ((next= outer->slave))
4334     next->prev= &next;
4335   prev= &outer->slave;
4336   outer->slave= this;
4337   master= outer;
4338 
4339   select_number= ++lex->select_number;
4340 
4341   nest_level= outer_select() == NULL ? 0 : outer_select()->nest_level + 1;
4342 }
4343 
4344 
4345 /**
4346   Add this query block after the specified query block.
4347 
4348   @param lex    Containing LEX object
4349   @param before Query block that this object is added after.
4350 */
include_neighbour(LEX * lex,st_select_lex * before)4351 void st_select_lex::include_neighbour(LEX *lex, st_select_lex *before)
4352 {
4353   if ((next= before->next))
4354     next->prev= &next;
4355   prev= &before->next;
4356   before->next= this;
4357   master= before->master;
4358 
4359   select_number= ++lex->select_number;
4360   nest_level= before->nest_level;
4361 }
4362 
4363 
4364 /**
4365   Include query block within the supplied unit.
4366 
4367   Do not link the query block into the global chain of query blocks.
4368 
4369   This function is exclusive for st_select_lex_unit::add_fake_select_lex() -
4370   use it with caution.
4371 
4372   @param  outer - Query expression this node is included below.
4373   @param  ref - Handle to the caller's pointer to this node.
4374 */
include_standalone(st_select_lex_unit * outer,st_select_lex ** ref)4375 void st_select_lex::include_standalone(st_select_lex_unit *outer,
4376                                        st_select_lex **ref)
4377 {
4378   next= NULL;
4379   prev= ref;
4380   master= outer;
4381   nest_level= master->first_select()->nest_level;
4382 }
4383 
4384 
4385 /**
4386   Renumber select_lex object, and apply renumbering recursively to
4387   contained objects.
4388 
4389   @param  lex   Containing LEX object
4390 */
renumber(LEX * lex)4391 void st_select_lex::renumber(LEX *lex)
4392 {
4393   select_number= ++lex->select_number;
4394 
4395   nest_level= outer_select() == NULL ? 0 : outer_select()->nest_level + 1;
4396 
4397   for (SELECT_LEX_UNIT *u= first_inner_unit(); u; u= u->next_unit())
4398     u->renumber_selects(lex);
4399 }
4400 
4401 /**
4402   Include query block into global list.
4403 
4404   @param plink - Pointer to start of list
4405 */
include_in_global(st_select_lex ** plink)4406 void st_select_lex::include_in_global(st_select_lex **plink)
4407 {
4408   if ((link_next= *plink))
4409     link_next->link_prev= &link_next;
4410   link_prev= plink;
4411   *plink= this;
4412 }
4413 
4414 
4415 /**
4416   Include chain of query blocks into global list.
4417 
4418   @param start - Pointer to start of list
4419 */
include_chain_in_global(st_select_lex ** start)4420 void st_select_lex::include_chain_in_global(st_select_lex **start)
4421 {
4422   st_select_lex *last_select;
4423   for (last_select= this;
4424        last_select->link_next != NULL;
4425        last_select= last_select->link_next)
4426   {}
4427   last_select->link_next= *start;
4428   last_select->link_next->link_prev= &last_select->link_next;
4429   link_prev= start;
4430   *start= this;
4431 }
4432 
4433 
set_join(JOIN * join_arg)4434 void st_select_lex::set_join(JOIN *join_arg)
4435 {
4436   master_unit()->thd->lock_query_plan();
4437   join= join_arg;
4438   master_unit()->thd->unlock_query_plan();
4439 }
4440 
4441 
4442 /**
4443    Helper function which handles the "ON conditions" part of
4444    SELECT_LEX::get_optimizable_conditions().
4445    @returns true if OOM
4446 */
get_optimizable_join_conditions(THD * thd,List<TABLE_LIST> & join_list)4447 static bool get_optimizable_join_conditions(THD *thd,
4448                                             List<TABLE_LIST> &join_list)
4449 {
4450   TABLE_LIST *table;
4451   List_iterator<TABLE_LIST> li(join_list);
4452   while((table= li++))
4453   {
4454     NESTED_JOIN *const nested_join= table->nested_join;
4455     if (nested_join &&
4456         get_optimizable_join_conditions(thd, nested_join->join_list))
4457       return true;
4458     Item *const jc= table->join_cond();
4459     if (jc && !thd->stmt_arena->is_conventional())
4460     {
4461       table->set_join_cond_optim(jc->copy_andor_structure(thd));
4462       if (!table->join_cond_optim())
4463         return true;
4464     }
4465     else
4466       table->set_join_cond_optim(jc);
4467   }
4468   return false;
4469 }
4470 
4471 
4472 /**
4473    Returns disposable copies of WHERE/HAVING/ON conditions.
4474 
4475    This function returns a copy which can be thrashed during
4476    this execution of the statement. Only AND/OR items are trashable!
4477    If in conventional execution, no copy is created, the permanent clauses are
4478    returned instead, as trashing them is no problem.
4479 
4480    @param      thd        thread handle
4481    @param[out] new_where  copy of WHERE
4482    @param[out] new_having copy of HAVING (if passed pointer is not NULL)
4483 
4484    Copies of join (ON) conditions are placed in TABLE_LIST::m_join_cond_optim.
4485 
4486    @returns true if OOM
4487 */
get_optimizable_conditions(THD * thd,Item ** new_where,Item ** new_having)4488 bool SELECT_LEX::get_optimizable_conditions(THD *thd,
4489                                             Item **new_where,
4490                                             Item **new_having)
4491 {
4492   /*
4493     We want to guarantee that
4494     join->optimized is true => conditions are ready for reading.
4495     So if we are here, this should hold:
4496   */
4497   assert(!(join && join->is_optimized()));
4498   if (m_where_cond && !thd->stmt_arena->is_conventional())
4499   {
4500     *new_where= m_where_cond->copy_andor_structure(thd);
4501     if (!*new_where)
4502       return true;
4503   }
4504   else
4505     *new_where= m_where_cond;
4506   if (new_having)
4507   {
4508     if (m_having_cond && !thd->stmt_arena->is_conventional())
4509     {
4510       *new_having= m_having_cond->copy_andor_structure(thd);
4511       if (!*new_having)
4512         return true;
4513     }
4514     else
4515       *new_having= m_having_cond;
4516   }
4517   return get_optimizable_join_conditions(thd, top_join_list);
4518 }
4519 
4520 Item_exists_subselect::enum_exec_method
subquery_strategy(THD * thd) const4521 st_select_lex::subquery_strategy(THD *thd) const
4522 {
4523   if (opt_hints_qb)
4524   {
4525     Item_exists_subselect::enum_exec_method strategy=
4526       opt_hints_qb->subquery_strategy();
4527     if (strategy != Item_exists_subselect::EXEC_UNSPECIFIED)
4528       return strategy;
4529   }
4530 
4531   // No SUBQUERY hint given, base possible strategies on optimizer_switch
4532   if (thd->optimizer_switch_flag(OPTIMIZER_SWITCH_MATERIALIZATION))
4533     return thd->optimizer_switch_flag(OPTIMIZER_SWITCH_SUBQ_MAT_COST_BASED) ?
4534       Item_exists_subselect::EXEC_EXISTS_OR_MAT :
4535       Item_exists_subselect::EXEC_MATERIALIZATION;
4536 
4537   return Item_exists_subselect::EXEC_EXISTS;
4538 }
4539 
semijoin_enabled(THD * thd) const4540 bool st_select_lex::semijoin_enabled(THD *thd) const
4541 {
4542   return opt_hints_qb ?
4543     opt_hints_qb->semijoin_enabled(thd) :
4544     thd->optimizer_switch_flag(OPTIMIZER_SWITCH_SEMIJOIN);
4545 }
4546 
update_semijoin_strategies(THD * thd)4547 void st_select_lex::update_semijoin_strategies(THD *thd)
4548 {
4549   uint sj_strategy_mask= OPTIMIZER_SWITCH_FIRSTMATCH |
4550     OPTIMIZER_SWITCH_LOOSE_SCAN | OPTIMIZER_SWITCH_MATERIALIZATION |
4551     OPTIMIZER_SWITCH_DUPSWEEDOUT;
4552 
4553   uint opt_switches= thd->variables.optimizer_switch & sj_strategy_mask;
4554 
4555   List_iterator<TABLE_LIST> sj_list_it(sj_nests);
4556   TABLE_LIST *sj_nest;
4557   while ((sj_nest= sj_list_it++))
4558   {
4559     /*
4560       After semi-join transformation, original SELECT_LEX with hints is lost.
4561       Fetch hints from first table in semijoin nest.
4562     */
4563     List_iterator<TABLE_LIST> table_list(sj_nest->nested_join->join_list);
4564     TABLE_LIST *table= table_list++;
4565     sj_nest->nested_join->sj_enabled_strategies= table->opt_hints_qb ?
4566       table->opt_hints_qb->sj_enabled_strategies(opt_switches) : opt_switches;
4567   }
4568 }
4569 
4570 
4571 /**
4572   Check if an option that can be used only for an outer-most query block is
4573   applicable to this query block.
4574 
4575   @param lex    LEX of current statement
4576   @param option option name to output within the error message
4577 
4578   @returns      false if valid, true if invalid, error is sent to client
4579 */
4580 
validate_outermost_option(LEX * lex,const char * option) const4581 bool st_select_lex::validate_outermost_option(LEX *lex,
4582                                               const char *option) const
4583 {
4584   if (this != lex->select_lex)
4585   {
4586     my_error(ER_CANT_USE_OPTION_HERE, MYF(0), option);
4587     return true;
4588   }
4589   return false;
4590 }
4591 
4592 
4593 /**
4594   Validate base options for a query block.
4595 
4596   @param lex                LEX of current statement
4597   @param options_arg        base options for a SELECT statement.
4598 
4599   @returns false if success, true if validation failed
4600 
4601   These options are supported, per DML statement:
4602 
4603   SELECT: SELECT_STRAIGHT_JOIN
4604           SELECT_HIGH_PRIORITY
4605           SELECT_DISTINCT
4606           SELECT_ALL
4607           SELECT_SMALL_RESULT
4608           SELECT_BIG_RESULT
4609           OPTION_BUFFER_RESULT
4610           OPTION_FOUND_ROWS
4611           OPTION_TO_QUERY_CACHE
4612   DELETE: OPTION_QUICK
4613           LOW_PRIORITY
4614   INSERT: LOW_PRIORITY
4615           HIGH_PRIORITY
4616   UPDATE: LOW_PRIORITY
4617 
4618   Note that validation is only performed for SELECT statements.
4619 */
4620 
validate_base_options(LEX * lex,ulonglong options_arg) const4621 bool st_select_lex::validate_base_options(LEX *lex, ulonglong options_arg) const
4622 {
4623   assert(!(options_arg & ~(SELECT_STRAIGHT_JOIN |
4624                            SELECT_HIGH_PRIORITY |
4625                            SELECT_DISTINCT |
4626                            SELECT_ALL |
4627                            SELECT_SMALL_RESULT |
4628                            SELECT_BIG_RESULT |
4629                            OPTION_BUFFER_RESULT |
4630                            OPTION_FOUND_ROWS |
4631                            OPTION_TO_QUERY_CACHE)));
4632 
4633   if (options_arg & SELECT_DISTINCT &&
4634       options_arg & SELECT_ALL)
4635   {
4636     my_error(ER_WRONG_USAGE, MYF(0), "ALL", "DISTINCT");
4637     return true;
4638   }
4639   if (options_arg & SELECT_HIGH_PRIORITY &&
4640       validate_outermost_option(lex, "HIGH_PRIORITY"))
4641     return true;
4642   if (options_arg & OPTION_BUFFER_RESULT &&
4643       validate_outermost_option(lex, "SQL_BUFFER_RESULT"))
4644     return true;
4645   if (options_arg & OPTION_FOUND_ROWS &&
4646       validate_outermost_option(lex, "SQL_CALC_FOUND_ROWS"))
4647     return true;
4648 
4649   return false;
4650 }
4651 
4652 
merge(const Query_options & a,const Query_options & b)4653 bool Query_options::merge(const Query_options &a,
4654                           const Query_options &b)
4655 {
4656   query_spec_options= a.query_spec_options | b.query_spec_options;
4657 
4658   if (b.sql_cache == SELECT_LEX::SQL_NO_CACHE)
4659   {
4660     if (a.sql_cache == SELECT_LEX::SQL_NO_CACHE)
4661     {
4662       my_error(ER_DUP_ARGUMENT, MYF(0), "SQL_NO_CACHE");
4663       return true;
4664     }
4665     else if (a.sql_cache == SELECT_LEX::SQL_CACHE)
4666     {
4667       my_error(ER_WRONG_USAGE, MYF(0), "SQL_CACHE", "SQL_NO_CACHE");
4668       return true;
4669     }
4670   }
4671   else if (b.sql_cache == SELECT_LEX::SQL_CACHE)
4672   {
4673     if (a.sql_cache == SELECT_LEX::SQL_CACHE)
4674     {
4675       my_error(ER_DUP_ARGUMENT, MYF(0), "SQL_CACHE");
4676       return true;
4677     }
4678     else if (a.sql_cache == SELECT_LEX::SQL_NO_CACHE)
4679     {
4680       my_error(ER_WRONG_USAGE, MYF(0), "SQL_NO_CACHE", "SQL_CACHE");
4681       return true;
4682     }
4683   }
4684   sql_cache= b.sql_cache;
4685   return false;
4686 }
4687 
4688 
save_to(Parse_context * pc)4689 bool Query_options::save_to(Parse_context *pc)
4690 {
4691   LEX *lex= pc->thd->lex;
4692   ulonglong options= query_spec_options;
4693 
4694   switch (sql_cache) {
4695   case SELECT_LEX::SQL_CACHE_UNSPECIFIED:
4696     break;
4697   case SELECT_LEX::SQL_NO_CACHE:
4698     if (pc->select != lex->select_lex)
4699     {
4700       my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_NO_CACHE");
4701       return true;
4702     }
4703     assert(pc->select->sql_cache == SELECT_LEX::SQL_CACHE_UNSPECIFIED);
4704     lex->safe_to_cache_query= false;
4705     options&= ~OPTION_TO_QUERY_CACHE;
4706     pc->select->sql_cache= SELECT_LEX::SQL_NO_CACHE;
4707     break;
4708   case SELECT_LEX::SQL_CACHE:
4709     if (pc->select != lex->select_lex)
4710     {
4711       my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_CACHE");
4712       return true;
4713     }
4714     assert(pc->select->sql_cache == SELECT_LEX::SQL_CACHE_UNSPECIFIED);
4715     lex->safe_to_cache_query= true;
4716     options|= OPTION_TO_QUERY_CACHE;
4717     pc->select->sql_cache= SELECT_LEX::SQL_CACHE;
4718     break;
4719   default:
4720     assert(!"Unexpected cache option!");
4721   }
4722   if (pc->select->validate_base_options(lex, options))
4723     return true;
4724   pc->select->set_base_options(options);
4725 
4726   return false;
4727 }
4728 
4729 
4730 /**
4731   A routine used by the parser to decide whether we are specifying a full
4732   partitioning or if only partitions to add or to split.
4733 
4734   @retval  TRUE    Yes, it is part of a management partition command
4735   @retval  FALSE          No, not a management partition command
4736 */
4737 
is_partition_management() const4738 bool LEX::is_partition_management() const
4739 {
4740   return (sql_command == SQLCOM_ALTER_TABLE &&
4741           (alter_info.flags == Alter_info::ALTER_ADD_PARTITION ||
4742            alter_info.flags == Alter_info::ALTER_REORGANIZE_PARTITION));
4743 }
4744 
4745 
4746 /**
4747   @todo This function is obviously incomplete. It does not walk update lists,
4748   for instance. At the time of writing, however, this function has only a
4749   single use, to walk all parts of select statements. If more functionality is
4750   needed, it should be added here, in the same fashion as for SQLCOM_INSERT
4751   below.
4752 */
accept(Select_lex_visitor * visitor)4753 bool LEX::accept(Select_lex_visitor *visitor)
4754 {
4755   if (unit->accept(visitor))
4756     return true;
4757   if (sql_command == SQLCOM_INSERT)
4758   {
4759     List_iterator<List_item> row_it(
4760         static_cast<Sql_cmd_insert_base *>(m_sql_cmd)->insert_many_values);
4761     for (List_item *row= row_it++; row != NULL; row= row_it++)
4762     {
4763       List_iterator<Item> col_it(*row);
4764       for (Item *item= col_it++; item != NULL; item= col_it++)
4765         if (walk_item(item, visitor))
4766           return true;
4767     }
4768   }
4769   return false;
4770 }
4771 
4772 
initialize()4773 void st_lex_master_info::initialize()
4774 {
4775   host= user= password= log_file_name= bind_addr = NULL;
4776   port= connect_retry= 0;
4777   heartbeat_period= 0;
4778   sql_delay= 0;
4779   pos= 0;
4780   server_id= retry_count= 0;
4781   gtid= NULL;
4782   gtid_until_condition= UNTIL_SQL_BEFORE_GTIDS;
4783   view_id= NULL;
4784   until_after_gaps= false;
4785   ssl= ssl_verify_server_cert= heartbeat_opt= repl_ignore_server_ids_opt=
4786     retry_count_opt= auto_position= port_opt= LEX_MI_UNCHANGED;
4787   ssl_key= ssl_cert= ssl_ca= ssl_capath= ssl_cipher= NULL;
4788   ssl_crl= ssl_crlpath= NULL;
4789   tls_version= NULL;
4790   relay_log_name= NULL;
4791   relay_log_pos= 0;
4792   repl_ignore_server_ids.clear();
4793   channel= NULL;
4794   for_channel= false;
4795 }
4796 
set_unspecified()4797 void st_lex_master_info::set_unspecified()
4798 {
4799   initialize();
4800   sql_delay= -1;
4801 }
4802 
4803 #ifdef MYSQL_SERVER
4804 uint binlog_unsafe_map[256];
4805 
4806 #define UNSAFE(a, b, c) \
4807   { \
4808   DBUG_PRINT("unsafe_mixed_statement", ("SETTING BASE VALUES: %s, %s, %02X\n", \
4809     LEX::stmt_accessed_table_string(a), \
4810     LEX::stmt_accessed_table_string(b), \
4811     c)); \
4812   unsafe_mixed_statement(a, b, c); \
4813   }
4814 
4815 /*
4816   Sets the combination given by "a" and "b" and automatically combinations
4817   given by other types of access, i.e. 2^(8 - 2), as unsafe.
4818 
4819   It may happen a colision when automatically defining a combination as unsafe.
4820   For that reason, a combination has its unsafe condition redefined only when
4821   the new_condition is greater then the old. For instance,
4822 
4823      . (BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY) is never overwritten by
4824      . (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF).
4825 */
unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,LEX::enum_stmt_accessed_table b,uint condition)4826 void unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,
4827                             LEX::enum_stmt_accessed_table b, uint condition)
4828 {
4829   int type= 0;
4830   int index= (1U << a) | (1U << b);
4831 
4832 
4833   for (type= 0; type < 256; type++)
4834   {
4835     if ((type & index) == index)
4836     {
4837       binlog_unsafe_map[type] |= condition;
4838     }
4839   }
4840 }
4841 /*
4842   The BINLOG_* AND TRX_CACHE_* values can be combined by using '&' or '|',
4843   which means that both conditions need to be satisfied or any of them is
4844   enough. For example,
4845 
4846     . BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY means that the statment is
4847     unsafe when the option is on and trx-cache is not empty;
4848 
4849     . BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF means the statement is unsafe
4850     in all cases.
4851 
4852     . TRX_CACHE_EMPTY | TRX_CACHE_NOT_EMPTY means the statement is unsafe
4853     in all cases. Similar as above.
4854 */
binlog_unsafe_map_init()4855 void binlog_unsafe_map_init()
4856 {
4857   memset((void*) binlog_unsafe_map, 0, sizeof(uint) * 256);
4858 
4859   /*
4860     Classify a statement as unsafe when there is a mixed statement and an
4861     on-going transaction at any point of the execution if:
4862 
4863       1. The mixed statement is about to update a transactional table and
4864       a non-transactional table.
4865 
4866       2. The mixed statement is about to update a transactional table and
4867       read from a non-transactional table.
4868 
4869       3. The mixed statement is about to update a non-transactional table
4870       and temporary transactional table.
4871 
4872       4. The mixed statement is about to update a temporary transactional
4873       table and read from a non-transactional table.
4874 
4875       5. The mixed statement is about to update a transactional table and
4876       a temporary non-transactional table.
4877 
4878       6. The mixed statement is about to update a transactional table and
4879       read from a temporary non-transactional table.
4880 
4881       7. The mixed statement is about to update a temporary transactional
4882       table and temporary non-transactional table.
4883 
4884       8. The mixed statement is about to update a temporary transactional
4885       table and read from a temporary non-transactional table.
4886     After updating a transactional table if:
4887 
4888       9. The mixed statement is about to update a non-transactional table
4889       and read from a transactional table.
4890 
4891       10. The mixed statement is about to update a non-transactional table
4892       and read from a temporary transactional table.
4893 
4894       11. The mixed statement is about to update a temporary non-transactional
4895       table and read from a transactional table.
4896 
4897       12. The mixed statement is about to update a temporary non-transactional
4898       table and read from a temporary transactional table.
4899 
4900       13. The mixed statement is about to update a temporary non-transactional
4901       table and read from a non-transactional table.
4902 
4903     The reason for this is that locks acquired may not protected a concurrent
4904     transaction of interfering in the current execution and by consequence in
4905     the result.
4906   */
4907   /* Case 1. */
4908   UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_NON_TRANS_TABLE,
4909     BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4910   /* Case 2. */
4911   UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
4912     BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4913   /* Case 3. */
4914   UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_WRITES_TEMP_TRANS_TABLE,
4915     BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4916   /* Case 4. */
4917   UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
4918     BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4919   /* Case 5. */
4920   UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
4921     BINLOG_DIRECT_ON);
4922   /* Case 6. */
4923   UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
4924     BINLOG_DIRECT_ON);
4925   /* Case 7. */
4926   UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
4927     BINLOG_DIRECT_ON);
4928   /* Case 8. */
4929   UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
4930     BINLOG_DIRECT_ON);
4931   /* Case 9. */
4932   UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
4933     (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
4934   /* Case 10 */
4935   UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
4936     (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
4937   /* Case 11. */
4938   UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
4939     BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
4940   /* Case 12. */
4941   UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
4942     BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
4943   /* Case 13. */
4944   UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
4945      BINLOG_DIRECT_OFF & TRX_CACHE_NOT_EMPTY);
4946 }
4947 #endif
4948