1 /* Copyright (c) 2000, 2019, Oracle and/or its affiliates.
2    Copyright (c) 2010, 2021, MariaDB Corporation
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 as published by
6    the Free Software Foundation; version 2 of the License.
7 
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12 
13    You should have received a copy of the GNU General Public License
14    along with this program; if not, write to the Free Software
15    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335  USA */
16 
17 /**
18   @defgroup Semantic_Analysis Semantic Analysis
19 */
20 
21 #ifndef SQL_LEX_INCLUDED
22 #define SQL_LEX_INCLUDED
23 
24 #include "violite.h"                            /* SSL_type */
25 #include "sql_trigger.h"
26 #include "thr_lock.h"                  /* thr_lock_type, TL_UNLOCK */
27 #include "mem_root_array.h"
28 #include "sql_cmd.h"
29 #include "sql_alter.h"                // Alter_info
30 #include "sql_window.h"
31 #include "sql_trigger.h"
32 #include "sp.h"                       // enum stored_procedure_type
33 #include "sql_tvc.h"
34 #include "item.h"
35 #include "sql_schema.h"
36 
37 /* Used for flags of nesting constructs */
38 #define SELECT_NESTING_MAP_SIZE 64
39 typedef Bitmap<SELECT_NESTING_MAP_SIZE> nesting_map;
40 
41 /* YACC and LEX Definitions */
42 
43 
44 /**
45   A string with metadata. Usually points to a string in the client
46   character set, but unlike Lex_ident_cli_st (see below) it does not
47   necessarily point to a query fragment. It can also point to memory
48   of other kinds (e.g. an additional THD allocated memory buffer
49   not overlapping with the current query text).
50 
51   We'll add more flags here eventually, to know if the string has, e.g.:
52   - multi-byte characters
53   - bad byte sequences
54   - backslash escapes:   'a\nb'
55   and reuse the original query fragments instead of making the string
56   copy too early, in Lex_input_stream::get_text().
57   This will allow to avoid unnecessary copying, as well as
58   create more optimal Item types in sql_yacc.yy
59 */
60 struct Lex_string_with_metadata_st: public LEX_CSTRING
61 {
62 private:
63   bool m_is_8bit; // True if the string has 8bit characters
64   char m_quote;   // Quote character, or 0 if not quoted
65 public:
66   void set_8bit(bool is_8bit) { m_is_8bit= is_8bit; }
67   void set_metadata(bool is_8bit, char quote)
68   {
69     m_is_8bit= is_8bit;
70     m_quote= quote;
71   }
72   void set(const char *s, size_t len, bool is_8bit, char quote)
73   {
74     str= s;
75     length= len;
76     set_metadata(is_8bit, quote);
77   }
78   void set(const LEX_CSTRING *s, bool is_8bit, char quote)
79   {
80     ((LEX_CSTRING &)*this)= *s;
81     set_metadata(is_8bit, quote);
82   }
83   bool is_8bit() const { return m_is_8bit; }
84   bool is_quoted() const { return m_quote != '\0'; }
85   char quote() const { return m_quote; }
86   // Get string repertoire by the 8-bit flag and the character set
87   uint repertoire(CHARSET_INFO *cs) const
88   {
89     return !m_is_8bit && my_charset_is_ascii_based(cs) ?
90            MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30;
91   }
92   // Get string repertoire by the 8-bit flag, for ASCII-based character sets
93   uint repertoire() const
94   {
95     return !m_is_8bit ? MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30;
96   }
97 };
98 
99 
100 /*
101   Used to store identifiers in the client character set.
102   Points to a query fragment.
103 */
104 struct Lex_ident_cli_st: public Lex_string_with_metadata_st
105 {
106 public:
107   void set_keyword(const char *s, size_t len)
108   {
109     set(s, len, false, '\0');
110   }
111   void set_ident(const char *s, size_t len, bool is_8bit)
112   {
113     set(s, len, is_8bit, '\0');
114   }
115   void set_ident_quoted(const char *s, size_t len, bool is_8bit, char quote)
116   {
117     set(s, len, is_8bit, quote);
118   }
119   void set_unquoted(const LEX_CSTRING *s, bool is_8bit)
120   {
121     set(s, is_8bit, '\0');
122   }
123   const char *pos() const { return str - is_quoted(); }
124   const char *end() const { return str + length + is_quoted(); }
125 };
126 
127 
128 class Lex_ident_cli: public Lex_ident_cli_st
129 {
130 public:
131   Lex_ident_cli(const LEX_CSTRING *s, bool is_8bit)
132   {
133     set_unquoted(s, is_8bit);
134   }
135   Lex_ident_cli(const char *s, size_t len)
136   {
137     set_ident(s, len, false);
138   }
139 };
140 
141 
142 struct Lex_ident_sys_st: public LEX_CSTRING
143 {
144 public:
145   bool copy_ident_cli(THD *thd, const Lex_ident_cli_st *str);
146   bool copy_keyword(THD *thd, const Lex_ident_cli_st *str);
147   bool copy_sys(THD *thd, const LEX_CSTRING *str);
148   bool convert(THD *thd, const LEX_CSTRING *str, CHARSET_INFO *cs);
149   bool copy_or_convert(THD *thd, const Lex_ident_cli_st *str, CHARSET_INFO *cs);
150   bool is_null() const { return str == NULL; }
151   bool to_size_number(ulonglong *to) const;
152   void set_valid_utf8(const LEX_CSTRING *name)
153   {
154     DBUG_ASSERT(Well_formed_prefix(system_charset_info, name->str,
155                                    name->length).length() == name->length);
156     str= name->str ; length= name->length;
157   }
158 };
159 
160 
161 class Lex_ident_sys: public Lex_ident_sys_st
162 {
163 public:
164   Lex_ident_sys(THD *thd, const Lex_ident_cli_st *str)
165   {
166     if (copy_ident_cli(thd, str))
167       ((LEX_CSTRING &) *this)= null_clex_str;
168   }
169   Lex_ident_sys()
170   {
171     ((LEX_CSTRING &) *this)= null_clex_str;
172   }
173   Lex_ident_sys(const char *name, size_t length)
174   {
175     LEX_CSTRING tmp= {name, length};
176     set_valid_utf8(&tmp);
177   }
178   Lex_ident_sys & operator=(const Lex_ident_sys_st &name)
179   {
180     Lex_ident_sys_st::operator=(name);
181     return *this;
182   }
183 };
184 
185 
186 /**
187   ORDER BY ... LIMIT parameters;
188 */
189 class Lex_order_limit_lock: public Sql_alloc
190 {
191 public:
192   SQL_I_List<st_order> *order_list;   /* ORDER clause */
193   Lex_select_lock lock;
194   Lex_select_limit limit;
195 
196   Lex_order_limit_lock() :order_list(NULL)
197   {}
198 
199   bool set_to(st_select_lex *sel);
200 };
201 
202 
203 enum sub_select_type
204 {
205   UNSPECIFIED_TYPE,
206   /* following 3 enums should be as they are*/
207   UNION_TYPE, INTERSECT_TYPE, EXCEPT_TYPE,
208   GLOBAL_OPTIONS_TYPE, DERIVED_TABLE_TYPE, OLAP_TYPE
209 };
210 
211 inline int cmp_unit_op(enum sub_select_type op1, enum sub_select_type op2)
212 {
213   DBUG_ASSERT(op1 >= UNION_TYPE && op1 <= EXCEPT_TYPE);
214   DBUG_ASSERT(op2 >= UNION_TYPE && op2 <= EXCEPT_TYPE);
215   return (op1 == INTERSECT_TYPE ? 1 : 0) - (op2 == INTERSECT_TYPE ? 1 : 0);
216 }
217 
218 enum unit_common_op {OP_MIX, OP_UNION, OP_INTERSECT, OP_EXCEPT};
219 
220 enum enum_view_suid
221 {
222   VIEW_SUID_INVOKER= 0,
223   VIEW_SUID_DEFINER= 1,
224   VIEW_SUID_DEFAULT= 2
225 };
226 
227 
228 enum plsql_cursor_attr_t
229 {
230   PLSQL_CURSOR_ATTR_ISOPEN,
231   PLSQL_CURSOR_ATTR_FOUND,
232   PLSQL_CURSOR_ATTR_NOTFOUND,
233   PLSQL_CURSOR_ATTR_ROWCOUNT
234 };
235 
236 
237 enum enum_sp_suid_behaviour
238 {
239   SP_IS_DEFAULT_SUID= 0,
240   SP_IS_NOT_SUID,
241   SP_IS_SUID
242 };
243 
244 
245 enum enum_sp_aggregate_type
246 {
247   DEFAULT_AGGREGATE= 0,
248   NOT_AGGREGATE,
249   GROUP_AGGREGATE
250 };
251 
252 
253 /* These may not be declared yet */
254 class Table_ident;
255 class sql_exchange;
256 class LEX_COLUMN;
257 class sp_head;
258 class sp_name;
259 class sp_instr;
260 class sp_pcontext;
261 class sp_variable;
262 class sp_assignment_lex;
263 class st_alter_tablespace;
264 class partition_info;
265 class Event_parse_data;
266 class set_var_base;
267 class sys_var;
268 class Item_func_match;
269 class File_parser;
270 class Key_part_spec;
271 class Item_window_func;
272 struct sql_digest_state;
273 class With_clause;
274 class my_var;
275 class select_handler;
276 class Pushdown_select;
277 
278 #define ALLOC_ROOT_SET 1024
279 
280 #ifdef MYSQL_SERVER
281 /*
282   There are 8 different type of table access so there is no more than
283   combinations 2^8 = 256:
284 
285   . STMT_READS_TRANS_TABLE
286 
287   . STMT_READS_NON_TRANS_TABLE
288 
289   . STMT_READS_TEMP_TRANS_TABLE
290 
291   . STMT_READS_TEMP_NON_TRANS_TABLE
292 
293   . STMT_WRITES_TRANS_TABLE
294 
295   . STMT_WRITES_NON_TRANS_TABLE
296 
297   . STMT_WRITES_TEMP_TRANS_TABLE
298 
299   . STMT_WRITES_TEMP_NON_TRANS_TABLE
300 
301   The unsafe conditions for each combination is represented within a byte
302   and stores the status of the option --binlog-direct-non-trans-updates,
303   whether the trx-cache is empty or not, and whether the isolation level
304   is lower than ISO_REPEATABLE_READ:
305 
306   . option (OFF/ON)
307   . trx-cache (empty/not empty)
308   . isolation (>= ISO_REPEATABLE_READ / < ISO_REPEATABLE_READ)
309 
310   bits 0 : . OFF, . empty, . >= ISO_REPEATABLE_READ
311   bits 1 : . OFF, . empty, . < ISO_REPEATABLE_READ
312   bits 2 : . OFF, . not empty, . >= ISO_REPEATABLE_READ
313   bits 3 : . OFF, . not empty, . < ISO_REPEATABLE_READ
314   bits 4 : . ON, . empty, . >= ISO_REPEATABLE_READ
315   bits 5 : . ON, . empty, . < ISO_REPEATABLE_READ
316   bits 6 : . ON, . not empty, . >= ISO_REPEATABLE_READ
317   bits 7 : . ON, . not empty, . < ISO_REPEATABLE_READ
318 */
319 extern uint binlog_unsafe_map[256];
320 /*
321   Initializes the array with unsafe combinations and its respective
322   conditions.
323 */
324 void binlog_unsafe_map_init();
325 #endif
326 
327 #ifdef MYSQL_SERVER
328 /*
329   The following hack is needed because mysql_yacc.cc does not define
330   YYSTYPE before including this file
331 */
332 #ifdef MYSQL_YACC
333 #define LEX_YYSTYPE void *
334 #else
335 #include "lex_symbol.h"
336 #ifdef MYSQL_LEX
337 #include "item_func.h"            /* Cast_target used in sql_yacc.hh */
338 #include "sql_get_diagnostics.h"  /* Types used in sql_yacc.hh */
339 #include "sp_pcontext.h"
340 #include "sql_yacc.hh"
341 #define LEX_YYSTYPE YYSTYPE *
342 #else
343 #define LEX_YYSTYPE void *
344 #endif
345 #endif
346 #endif
347 
348 // describe/explain types
349 #define DESCRIBE_NORMAL         1
350 #define DESCRIBE_EXTENDED       2
351 /*
352   This is not within #ifdef because we want "EXPLAIN PARTITIONS ..." to produce
353   additional "partitions" column even if partitioning is not compiled in.
354 */
355 #define DESCRIBE_PARTITIONS	4
356 #define DESCRIBE_EXTENDED2	8
357 
358 #ifdef MYSQL_SERVER
359 
360 extern const LEX_STRING  empty_lex_str;
361 extern MYSQL_PLUGIN_IMPORT const LEX_CSTRING empty_clex_str;
362 extern const LEX_CSTRING star_clex_str;
363 extern const LEX_CSTRING param_clex_str;
364 
365 enum enum_sp_data_access
366 {
367   SP_DEFAULT_ACCESS= 0,
368   SP_CONTAINS_SQL,
369   SP_NO_SQL,
370   SP_READS_SQL_DATA,
371   SP_MODIFIES_SQL_DATA
372 };
373 
374 const LEX_CSTRING sp_data_access_name[]=
375 {
376   { STRING_WITH_LEN("") },
377   { STRING_WITH_LEN("CONTAINS SQL") },
378   { STRING_WITH_LEN("NO SQL") },
379   { STRING_WITH_LEN("READS SQL DATA") },
380   { STRING_WITH_LEN("MODIFIES SQL DATA") }
381 };
382 
383 #define DERIVED_SUBQUERY        1
384 #define DERIVED_VIEW            2
385 #define DERIVED_WITH            4
386 
387 enum enum_view_create_mode
388 {
389   VIEW_CREATE_NEW,              // check that there are not such VIEW/table
390   VIEW_ALTER,                   // check that VIEW .frm with such name exists
391   VIEW_CREATE_OR_REPLACE        // check only that there are not such table
392 };
393 
394 
395 class Create_view_info: public Sql_alloc
396 {
397 public:
398   LEX_CSTRING select;              // The SELECT statement of CREATE VIEW
399   enum enum_view_create_mode mode;
400   uint16 algorithm;
401   uint8 check;
402   enum enum_view_suid suid;
403   Create_view_info(enum_view_create_mode mode_arg,
404                    uint16 algorithm_arg,
405                    enum_view_suid suid_arg)
406    :select(null_clex_str),
407     mode(mode_arg),
408     algorithm(algorithm_arg),
409     check(VIEW_CHECK_NONE),
410     suid(suid_arg)
411   { }
412 };
413 
414 
415 enum enum_drop_mode
416 {
417   DROP_DEFAULT, // mode is not specified
418   DROP_CASCADE, // CASCADE option
419   DROP_RESTRICT // RESTRICT option
420 };
421 
422 /* Options to add_table_to_list() */
423 #define TL_OPTION_UPDATING      1
424 #define TL_OPTION_FORCE_INDEX   2
425 #define TL_OPTION_IGNORE_LEAVES 4
426 #define TL_OPTION_ALIAS         8
427 #define TL_OPTION_SEQUENCE      16
428 
429 typedef List<Item> List_item;
430 typedef Mem_root_array<ORDER*, true> Group_list_ptrs;
431 
432 /* SERVERS CACHE CHANGES */
433 typedef struct st_lex_server_options
434 {
435   long port;
436   LEX_CSTRING server_name, host, db, username, password, scheme, socket, owner;
437   void reset(LEX_CSTRING name)
438   {
439     server_name= name;
440     host= db= username= password= scheme= socket= owner= null_clex_str;
441     port= -1;
442   }
443 } LEX_SERVER_OPTIONS;
444 
445 
446 /**
447   Structure to hold parameters for CHANGE MASTER, START SLAVE, and STOP SLAVE.
448 
449   Remark: this should not be confused with Master_info (and perhaps
450   would better be renamed to st_lex_replication_info).  Some fields,
451   e.g., delay, are saved in Relay_log_info, not in Master_info.
452 */
453 struct LEX_MASTER_INFO
454 {
455   DYNAMIC_ARRAY repl_ignore_server_ids;
456   DYNAMIC_ARRAY repl_do_domain_ids;
457   DYNAMIC_ARRAY repl_ignore_domain_ids;
458   const char *host, *user, *password, *log_file_name;
459   const char *ssl_key, *ssl_cert, *ssl_ca, *ssl_capath, *ssl_cipher;
460   const char *ssl_crl, *ssl_crlpath;
461   const char *relay_log_name;
462   LEX_CSTRING connection_name;
463   /* Value in START SLAVE UNTIL master_gtid_pos=xxx */
464   LEX_CSTRING gtid_pos_str;
465   ulonglong pos;
466   ulong relay_log_pos;
467   ulong server_id;
468   uint port, connect_retry;
469   float heartbeat_period;
470   int sql_delay;
471   /*
472     Enum is used for making it possible to detect if the user
473     changed variable or if it should be left at old value
474    */
475   enum {LEX_MI_UNCHANGED= 0, LEX_MI_DISABLE, LEX_MI_ENABLE}
476     ssl, ssl_verify_server_cert, heartbeat_opt, repl_ignore_server_ids_opt,
477     repl_do_domain_ids_opt, repl_ignore_domain_ids_opt;
478   enum {
479     LEX_GTID_UNCHANGED, LEX_GTID_NO, LEX_GTID_CURRENT_POS, LEX_GTID_SLAVE_POS
480   } use_gtid_opt;
481 
482   void init()
483   {
484     bzero(this, sizeof(*this));
485     my_init_dynamic_array(&repl_ignore_server_ids,
486                           sizeof(::server_id), 0, 16, MYF(0));
487     my_init_dynamic_array(&repl_do_domain_ids,
488                           sizeof(ulong), 0, 16, MYF(0));
489     my_init_dynamic_array(&repl_ignore_domain_ids,
490                           sizeof(ulong), 0, 16, MYF(0));
491     sql_delay= -1;
492   }
493   void reset(bool is_change_master)
494   {
495     if (unlikely(is_change_master))
496     {
497       delete_dynamic(&repl_ignore_server_ids);
498       /* Free all the array elements. */
499       delete_dynamic(&repl_do_domain_ids);
500       delete_dynamic(&repl_ignore_domain_ids);
501     }
502 
503     host= user= password= log_file_name= ssl_key= ssl_cert= ssl_ca=
504       ssl_capath= ssl_cipher= ssl_crl= ssl_crlpath= relay_log_name= NULL;
505     pos= relay_log_pos= server_id= port= connect_retry= 0;
506     heartbeat_period= 0;
507     ssl= ssl_verify_server_cert= heartbeat_opt=
508       repl_ignore_server_ids_opt= repl_do_domain_ids_opt=
509       repl_ignore_domain_ids_opt= LEX_MI_UNCHANGED;
510     gtid_pos_str= null_clex_str;
511     use_gtid_opt= LEX_GTID_UNCHANGED;
512     sql_delay= -1;
513   }
514 };
515 
516 typedef struct st_lex_reset_slave
517 {
518   bool all;
519 } LEX_RESET_SLAVE;
520 
521 enum olap_type
522 {
523   UNSPECIFIED_OLAP_TYPE, CUBE_TYPE, ROLLUP_TYPE
524 };
525 
526 /*
527   String names used to print a statement with index hints.
528   Keep in sync with index_hint_type.
529 */
530 extern const char * index_hint_type_name[];
531 typedef uchar index_clause_map;
532 
533 /*
534   Bits in index_clause_map : one for each possible FOR clause in
535   USE/FORCE/IGNORE INDEX index hint specification
536 */
537 #define INDEX_HINT_MASK_JOIN  (1)
538 #define INDEX_HINT_MASK_GROUP (1 << 1)
539 #define INDEX_HINT_MASK_ORDER (1 << 2)
540 
541 #define INDEX_HINT_MASK_ALL (INDEX_HINT_MASK_JOIN | INDEX_HINT_MASK_GROUP | \
542                              INDEX_HINT_MASK_ORDER)
543 
544 class select_result_sink;
545 
546 /* Single element of an USE/FORCE/IGNORE INDEX list specified as a SQL hint  */
547 class Index_hint : public Sql_alloc
548 {
549 public:
550   /* The type of the hint : USE/FORCE/IGNORE */
551   enum index_hint_type type;
552   /* Where the hit applies to. A bitmask of INDEX_HINT_MASK_<place> values */
553   index_clause_map clause;
554   /*
555     The index name. Empty (str=NULL) name represents an empty list
556     USE INDEX () clause
557   */
558   LEX_CSTRING key_name;
559 
560   Index_hint (enum index_hint_type type_arg, index_clause_map clause_arg,
561               const char *str, size_t length) :
562     type(type_arg), clause(clause_arg)
563   {
564     key_name.str= str;
565     key_name.length= length;
566   }
567 
568   void print(THD *thd, String *str);
569 };
570 
571 /*
572   The state of the lex parsing for selects
573 
574    master and slaves are pointers to select_lex.
575    master is pointer to upper level node.
576    slave is pointer to lower level node
577    select_lex is a SELECT without union
578    unit is container of either
579      - One SELECT
580      - UNION of selects
581    select_lex and unit are both inherited form st_select_lex_node
582    neighbors are two select_lex or units on the same level
583 
584    All select describing structures linked with following pointers:
585    - list of neighbors (next/prev) (prev of first element point to slave
586      pointer of upper structure)
587      - For select this is a list of UNION's (or one element list)
588      - For units this is a list of sub queries for the upper level select
589 
590    - pointer to master (master), which is
591      If this is a unit
592        - pointer to outer select_lex
593      If this is a select_lex
594        - pointer to outer unit structure for select
595 
596    - pointer to slave (slave), which is either:
597      If this is a unit:
598        - first SELECT that belong to this unit
599      If this is a select_lex
600        - first unit that belong to this SELECT (subquries or derived tables)
601 
602    - list of all select_lex (link_next/link_prev)
603      This is to be used for things like derived tables creation, where we
604      go through this list and create the derived tables.
605 
606    If unit contain several selects (UNION now, INTERSECT etc later)
607    then it have special select_lex called fake_select_lex. It used for
608    storing global parameters (like ORDER BY, LIMIT) and executing union.
609    Subqueries used in global ORDER BY clause will be attached to this
610    fake_select_lex, which will allow them correctly resolve fields of
611    'upper' UNION and outer selects.
612 
613    For example for following query:
614 
615    select *
616      from table1
617      where table1.field IN (select * from table1_1_1 union
618                             select * from table1_1_2)
619      union
620    select *
621      from table2
622      where table2.field=(select (select f1 from table2_1_1_1_1
623                                    where table2_1_1_1_1.f2=table2_1_1.f3)
624                            from table2_1_1
625                            where table2_1_1.f1=table2.f2)
626      union
627    select * from table3;
628 
629    we will have following structure:
630 
631    select1: (select * from table1 ...)
632    select2: (select * from table2 ...)
633    select3: (select * from table3)
634    select1.1.1: (select * from table1_1_1)
635    ...
636 
637      main unit
638      fake0
639      select1 select2 select3
640      |^^     |^
641     s|||     ||master
642     l|||     |+---------------------------------+
643     a|||     +---------------------------------+|
644     v|||master                         slave   ||
645     e||+-------------------------+             ||
646      V|            neighbor      |             V|
647      unit1.1<+==================>unit1.2       unit2.1
648      fake1.1
649      select1.1.1 select 1.1.2    select1.2.1   select2.1.1
650                                                |^
651                                                ||
652                                                V|
653                                                unit2.1.1.1
654                                                select2.1.1.1.1
655 
656 
657    relation in main unit will be following:
658    (bigger picture for:
659       main unit
660       fake0
661       select1 select2 select3
662    in the above picture)
663 
664          main unit
665          |^^^^|fake_select_lex
666          |||||+--------------------------------------------+
667          ||||+--------------------------------------------+|
668          |||+------------------------------+              ||
669          ||+--------------+                |              ||
670     slave||master         |                |              ||
671          V|      neighbor |       neighbor |        master|V
672          select1<========>select2<========>select3        fake0
673 
674     list of all select_lex will be following (as it will be constructed by
675     parser):
676 
677     select1->select2->select3->select2.1.1->select 2.1.2->select2.1.1.1.1-+
678                                                                           |
679     +---------------------------------------------------------------------+
680     |
681     +->select1.1.1->select1.1.2
682 
683 */
684 
685 /*
686     Base class for st_select_lex (SELECT_LEX) &
687     st_select_lex_unit (SELECT_LEX_UNIT)
688 */
689 struct LEX;
690 class st_select_lex;
691 class st_select_lex_unit;
692 
693 
694 class st_select_lex_node {
695 protected:
696   st_select_lex_node *next, **prev,   /* neighbor list */
697     *master, *slave,                  /* vertical links */
698     *link_next, **link_prev;          /* list of whole SELECT_LEX */
699 
700   void init_query_common();
701 public:
702 
703   ulonglong options;
704 
705   /*
706     result of this query can't be cached, bit field, can be :
707       UNCACHEABLE_DEPENDENT_GENERATED
708       UNCACHEABLE_DEPENDENT_INJECTED
709       UNCACHEABLE_RAND
710       UNCACHEABLE_SIDEEFFECT
711       UNCACHEABLE_EXPLAIN
712       UNCACHEABLE_PREPARE
713   */
714   uint8 uncacheable;
715 private:
716   enum sub_select_type linkage;
717 public:
718   bool is_linkage_set() const
719   {
720     return linkage == UNION_TYPE || linkage == INTERSECT_TYPE || linkage == EXCEPT_TYPE;
721   }
722   enum sub_select_type get_linkage() { return linkage; }
723   bool distinct;
724   bool no_table_names_allowed; /* used for global order by */
725 
726   static void *operator new(size_t size, MEM_ROOT *mem_root) throw ()
727   { return (void*) alloc_root(mem_root, (uint) size); }
728   static void operator delete(void *ptr,size_t size) { TRASH_FREE(ptr, size); }
729   static void operator delete(void *ptr, MEM_ROOT *mem_root) {}
730 
731   // Ensures that at least all members used during cleanup() are initialized.
732   st_select_lex_node()
733     : next(NULL), prev(NULL),
734       master(NULL), slave(NULL),
735       link_next(NULL), link_prev(NULL),
736       linkage(UNSPECIFIED_TYPE)
737   {
738   }
739 
740   inline st_select_lex_node* get_master() { return master; }
741   inline st_select_lex_node* get_slave() { return slave; }
742   void include_down(st_select_lex_node *upper);
743   void add_slave(st_select_lex_node *slave_arg);
744   void include_neighbour(st_select_lex_node *before);
745   void link_chain_down(st_select_lex_node *first);
746   void link_neighbour(st_select_lex_node *neighbour)
747   {
748     DBUG_ASSERT(next == NULL);
749     DBUG_ASSERT(neighbour != NULL);
750     next= neighbour;
751     neighbour->prev= &next;
752   }
753   void cut_next() { next= NULL; }
754   void include_standalone(st_select_lex_node *sel, st_select_lex_node **ref);
755   void include_global(st_select_lex_node **plink);
756   void exclude();
757   void exclude_from_tree();
758   void exclude_from_global()
759   {
760     if (!link_prev)
761       return;
762     if (((*link_prev)= link_next))
763       link_next->link_prev= link_prev;
764     link_next= NULL;
765     link_prev= NULL;
766   }
767   void substitute_in_tree(st_select_lex_node *subst);
768 
769   void set_slave(st_select_lex_node *slave_arg) { slave= slave_arg; }
770   void move_node(st_select_lex_node *where_to_move)
771   {
772     if (where_to_move == this)
773       return;
774     if (next)
775       next->prev= prev;
776     *prev= next;
777     *where_to_move->prev= this;
778     next= where_to_move;
779   }
780   st_select_lex_node *insert_chain_before(st_select_lex_node **ptr_pos_to_insert,
781                                           st_select_lex_node *end_chain_node);
782   void move_as_slave(st_select_lex_node *new_master);
783   void set_linkage(enum sub_select_type l)
784   {
785     DBUG_ENTER("st_select_lex_node::set_linkage");
786     DBUG_PRINT("info", ("node: %p  linkage: %d->%d", this, linkage, l));
787     linkage= l;
788     DBUG_VOID_RETURN;
789   }
790   /*
791     This method created for reiniting LEX in mysql_admin_table() and can be
792     used only if you are going remove all SELECT_LEX & units except belonger
793     to LEX (LEX::unit & LEX::select, for other purposes there are
794     SELECT_LEX_UNIT::exclude_level & SELECT_LEX_UNIT::exclude_tree.
795 
796     It is also used in parsing to detach builtin select.
797   */
798   void cut_subtree() { slave= 0; }
799   friend class st_select_lex_unit;
800   friend bool mysql_new_select(LEX *lex, bool move_down, SELECT_LEX *sel);
801   friend bool mysql_make_view(THD *thd, TABLE_SHARE *share, TABLE_LIST *table,
802                               bool open_view_no_parse);
803   friend class st_select_lex;
804 private:
805   void fast_exclude();
806 };
807 typedef class st_select_lex_node SELECT_LEX_NODE;
808 
809 /*
810    SELECT_LEX_UNIT - unit of selects (UNION, INTERSECT, ...) group
811    SELECT_LEXs
812 */
813 class THD;
814 class select_result;
815 class JOIN;
816 class select_unit;
817 class Procedure;
818 class Explain_query;
819 
820 void delete_explain_query(LEX *lex);
821 void create_explain_query(LEX *lex, MEM_ROOT *mem_root);
822 void create_explain_query_if_not_exists(LEX *lex, MEM_ROOT *mem_root);
823 bool print_explain_for_slow_log(LEX *lex, THD *thd, String *str);
824 
825 class st_select_lex_unit: public st_select_lex_node {
826 protected:
827   TABLE_LIST result_table_list;
828   select_unit *union_result;
829   ulonglong found_rows_for_union;
830   bool saved_error;
831 
832   bool prepare_join(THD *thd, SELECT_LEX *sl, select_result *result,
833                     ulong additional_options,
834                     bool is_union_select);
835   bool join_union_type_handlers(THD *thd,
836                                 class Type_holder *holders, uint count);
837   bool join_union_type_attributes(THD *thd,
838                                   class Type_holder *holders, uint count);
839 public:
840   bool join_union_item_types(THD *thd, List<Item> &types, uint count);
841 public:
842   // Ensures that at least all members used during cleanup() are initialized.
843   st_select_lex_unit()
844     : union_result(NULL), table(NULL), result(NULL),
845       cleaned(false),
846       fake_select_lex(NULL)
847   {
848   }
849 
850   TABLE *table; /* temporary table using for appending UNION results */
851   select_result *result;
852   st_select_lex *pre_last_parse;
853   bool  prepared, // prepare phase already performed for UNION (unit)
854     optimized, // optimize phase already performed for UNION (unit)
855     optimized_2,
856     executed, // already executed
857     cleaned;
858 
859   bool optimize_started;
860 
861   // list of fields which points to temporary table for union
862   List<Item> item_list;
863   /*
864     list of types of items inside union (used for union & derived tables)
865 
866     Item_type_holders from which this list consist may have pointers to Field,
867     pointers is valid only after preparing SELECTS of this unit and before
868     any SELECT of this unit execution
869   */
870   List<Item> types;
871   /**
872     There is INTERSECT and it is item used in creating temporary
873     table for it
874   */
875   Item_int *intersect_mark;
876   /**
877      TRUE if the unit contained TVC at the top level that has been wrapped
878      into SELECT:
879      VALUES (v1) ... (vn) => SELECT * FROM (VALUES (v1) ... (vn)) as tvc
880   */
881   bool with_wrapped_tvc;
882   /**
883     Pointer to 'last' select, or pointer to select where we stored
884     global parameters for union.
885 
886     If this is a union of multiple selects, the parser puts the global
887     parameters in fake_select_lex. If the union doesn't use a
888     temporary table, st_select_lex_unit::prepare() nulls out
889     fake_select_lex, but saves a copy in saved_fake_select_lex in
890     order to preserve the global parameters.
891 
892     If it is not a union, first_select() is the last select.
893 
894     @return select containing the global parameters
895   */
896   inline st_select_lex *global_parameters()
897   {
898     if (fake_select_lex != NULL)
899       return fake_select_lex;
900     else if (saved_fake_select_lex != NULL)
901       return saved_fake_select_lex;
902     return first_select();
903   };
904   //node on which we should return current_select pointer after parsing subquery
905   st_select_lex *return_to;
906   /* LIMIT clause runtime counters */
907   ha_rows select_limit_cnt, offset_limit_cnt;
908   /* not NULL if unit used in subselect, point to subselect item */
909   Item_subselect *item;
910   /*
911     TABLE_LIST representing this union in the embedding select. Used for
912     derived tables/views handling.
913   */
914   TABLE_LIST *derived;
915   bool is_view;
916   /* With clause attached to this unit (if any) */
917   With_clause *with_clause;
918   /* With element where this unit is used as the specification (if any) */
919   With_element *with_element;
920   /* The unit used as a CTE specification from which this unit is cloned */
921   st_select_lex_unit *cloned_from;
922   /* thread handler */
923   THD *thd;
924   /*
925     SELECT_LEX for hidden SELECT in union which process global
926     ORDER BY and LIMIT
927   */
928   st_select_lex *fake_select_lex;
929   /**
930     SELECT_LEX that stores LIMIT and OFFSET for UNION ALL when noq
931     fake_select_lex is used.
932   */
933   st_select_lex *saved_fake_select_lex;
934 
935   st_select_lex *union_distinct; /* pointer to the last UNION DISTINCT */
936   bool describe; /* union exec() called for EXPLAIN */
937   Procedure *last_procedure;     /* Pointer to procedure, if such exists */
938 
939   bool columns_are_renamed;
940 
941   void init_query();
942   st_select_lex* outer_select();
943   const st_select_lex* first_select() const
944   {
945     return reinterpret_cast<const st_select_lex*>(slave);
946   }
947   st_select_lex* first_select()
948   {
949     return reinterpret_cast<st_select_lex*>(slave);
950   }
951   void set_with_clause(With_clause *with_cl);
952   st_select_lex_unit* next_unit()
953   {
954     return reinterpret_cast<st_select_lex_unit*>(next);
955   }
956   st_select_lex* return_after_parsing() { return return_to; }
957   void exclude_level();
958   // void exclude_tree(); // it is not used for long time
959   bool is_excluded() { return prev == NULL; }
960 
961   /* UNION methods */
962   bool prepare(TABLE_LIST *derived_arg, select_result *sel_result,
963                ulong additional_options);
964   bool optimize();
965   bool exec();
966   bool exec_recursive();
967   bool cleanup();
968   inline void unclean() { cleaned= 0; }
969   void reinit_exec_mechanism();
970 
971   void print(String *str, enum_query_type query_type);
972 
973   bool add_fake_select_lex(THD *thd);
974   void init_prepare_fake_select_lex(THD *thd, bool first_execution);
975   inline bool is_prepared() { return prepared; }
976   bool change_result(select_result_interceptor *result,
977                      select_result_interceptor *old_result);
978   void set_limit(st_select_lex *values);
979   void set_thd(THD *thd_arg) { thd= thd_arg; }
980   inline bool is_unit_op ();
981   bool union_needs_tmp_table();
982 
983   void set_unique_exclude();
984   bool check_distinct_in_union();
985 
986   friend struct LEX;
987   friend int subselect_union_engine::exec();
988 
989   List<Item> *get_column_types(bool for_cursor);
990 
991   select_unit *get_union_result() { return union_result; }
992   int save_union_explain(Explain_query *output);
993   int save_union_explain_part2(Explain_query *output);
994   unit_common_op common_op();
995 
996   void reset_distinct();
997   void fix_distinct();
998 
999   void register_select_chain(SELECT_LEX *first_sel);
1000 
1001   bool set_nest_level(int new_nest_level);
1002   bool check_parameters(SELECT_LEX *main_select);
1003 
1004   bool set_lock_to_the_last_select(Lex_select_lock l);
1005 
1006   friend class st_select_lex;
1007 };
1008 
1009 typedef class st_select_lex_unit SELECT_LEX_UNIT;
1010 typedef Bounds_checked_array<Item*> Ref_ptr_array;
1011 
1012 
1013 /**
1014   Structure which consists of the field and the item that
1015   corresponds to this field.
1016 */
1017 
1018 class Field_pair :public Sql_alloc
1019 {
1020 public:
1021   Field *field;
1022   Item *corresponding_item;
1023   Field_pair(Field *fld, Item *item)
1024     :field(fld), corresponding_item(item) {}
1025 };
1026 
1027 Field_pair *get_corresponding_field_pair(Item *item,
1028                                          List<Field_pair> pair_list);
1029 Field_pair *find_matching_field_pair(Item *item, List<Field_pair> pair_list);
1030 
1031 
1032 #define TOUCHED_SEL_COND 1/* WHERE/HAVING/ON should be reinited before use */
1033 #define TOUCHED_SEL_DERIVED (1<<1)/* derived should be reinited before use */
1034 
1035 
1036 /*
1037   SELECT_LEX - store information of parsed SELECT statment
1038 */
1039 class st_select_lex: public st_select_lex_node
1040 {
1041 public:
1042   /*
1043     Currently the field first_nested is used only by parser.
1044     It containa either a reference to the first select
1045     of the nest of selects to which 'this' belongs to, or
1046     in the case of priority jump it contains a reference to
1047     the select to which the priority nest has to be attached to.
1048     If there is no priority jump then the first select of the
1049     nest contains the reference to itself in first_nested.
1050     Example:
1051       select1 union select2 intersect select
1052     Here we have a priority jump at select2.
1053     So select2->first_nested points to select1,
1054     while select3->first_nested points to select2 and
1055     select1->first_nested points to select1.
1056   */
1057   st_select_lex *first_nested;
1058 
1059   Name_resolution_context context;
1060   LEX_CSTRING db;
1061   Item *where, *having;                         /* WHERE & HAVING clauses */
1062   Item *prep_where; /* saved WHERE clause for prepared statement processing */
1063   Item *prep_having;/* saved HAVING clause for prepared statement processing */
1064   Item *cond_pushed_into_where;  /* condition pushed into the select's WHERE  */
1065   Item *cond_pushed_into_having; /* condition pushed into the select's HAVING */
1066   List<Item> attach_to_conds;
1067   /* Saved values of the WHERE and HAVING clauses*/
1068   Item::cond_result cond_value, having_value;
1069   /*
1070     Point to the LEX in which it was created, used in view subquery detection.
1071 
1072     TODO: make also st_select_lex::parent_stmt_lex (see LEX::stmt_lex)
1073     and use st_select_lex::parent_lex & st_select_lex::parent_stmt_lex
1074     instead of global (from THD) references where it is possible.
1075   */
1076   LEX *parent_lex;
1077   enum olap_type olap;
1078   /* FROM clause - points to the beginning of the TABLE_LIST::next_local list. */
1079   SQL_I_List<TABLE_LIST>  table_list;
1080 
1081   /*
1082     GROUP BY clause.
1083     This list may be mutated during optimization (by remove_const()),
1084     so for prepared statements, we keep a copy of the ORDER.next pointers in
1085     group_list_ptrs, and re-establish the original list before each execution.
1086   */
1087   SQL_I_List<ORDER>       group_list;
1088   Group_list_ptrs        *group_list_ptrs;
1089 
1090   List<Item>          item_list;  /* list of fields & expressions */
1091   List<Item>          pre_fix; /* above list before fix_fields */
1092   bool                is_item_list_lookup;
1093   /*
1094     Usualy it is pointer to ftfunc_list_alloc, but in union used to create fake
1095     select_lex for calling mysql_select under results of union
1096   */
1097   List<Item_func_match> *ftfunc_list;
1098   List<Item_func_match> ftfunc_list_alloc;
1099   /*
1100     The list of items to which MIN/MAX optimizations of opt_sum_query()
1101     have been applied. Used to rollback those optimizations if it's needed.
1102   */
1103   List<Item_sum> min_max_opt_list;
1104   JOIN *join; /* after JOIN::prepare it is pointer to corresponding JOIN */
1105   List<TABLE_LIST> top_join_list; /* join list of the top level          */
1106   List<TABLE_LIST> *join_list;    /* list for the currently parsed join  */
1107   TABLE_LIST *embedding;          /* table embedding to the above list   */
1108   List<TABLE_LIST> sj_nests;      /* Semi-join nests within this join */
1109   /*
1110     Beginning of the list of leaves in a FROM clause, where the leaves
1111     inlcude all base tables including view tables. The tables are connected
1112     by TABLE_LIST::next_leaf, so leaf_tables points to the left-most leaf.
1113 
1114     List of all base tables local to a subquery including all view
1115     tables. Unlike 'next_local', this in this list views are *not*
1116     leaves. Created in setup_tables() -> make_leaves_list().
1117   */
1118   /*
1119     Subqueries that will need to be converted to semi-join nests, including
1120     those converted to jtbm nests. The list is emptied when conversion is done.
1121   */
1122   List<Item_in_subselect> sj_subselects;
1123   /*
1124     List of IN-predicates in this st_select_lex that
1125     can be transformed into IN-subselect defined with TVC.
1126   */
1127   List<Item_func_in> in_funcs;
1128   /*
1129     Number of current derived table made with TVC during the
1130     transformation of IN-predicate into IN-subquery for this
1131     st_select_lex.
1132   */
1133   uint curr_tvc_name;
1134 
1135   /*
1136     Needed to correctly generate 'PRIMARY' or 'SIMPLE' for select_type column
1137     of EXPLAIN
1138   */
1139   bool have_merged_subqueries;
1140 
1141   List<TABLE_LIST> leaf_tables;
1142   List<TABLE_LIST> leaf_tables_exec;
1143   List<TABLE_LIST> leaf_tables_prep;
1144   enum leaf_list_state {UNINIT, READY, SAVED};
1145   enum leaf_list_state prep_leaf_list_state;
1146   uint insert_tables;
1147   st_select_lex *merged_into; /* select which this select is merged into */
1148                               /* (not 0 only for views/derived tables)   */
1149 
1150   const char *type;               /* type of select for EXPLAIN          */
1151 
1152   SQL_I_List<ORDER> order_list;   /* ORDER clause */
1153   SQL_I_List<ORDER> gorder_list;
1154   Item *select_limit, *offset_limit;  /* LIMIT clause parameters */
1155   bool is_set_query_expr_tail;
1156 
1157   /// Array of pointers to top elements of all_fields list
1158   Ref_ptr_array ref_pointer_array;
1159 
1160   /*
1161     number of items in select_list and HAVING clause used to get number
1162     bigger then can be number of entries that will be added to all item
1163     list during split_sum_func
1164   */
1165   uint select_n_having_items;
1166   uint cond_count;    /* number of sargable Items in where/having/on          */
1167   uint between_count; /* number of between predicates in where/having/on      */
1168   uint max_equal_elems; /* maximal number of elements in multiple equalities  */
1169   /*
1170     Number of fields used in select list or where clause of current select
1171     and all inner subselects.
1172   */
1173   uint select_n_where_fields;
1174   /* reserved for exists 2 in */
1175   uint select_n_reserved;
1176   /*
1177    it counts the number of bit fields in the SELECT list. These are used when DISTINCT is
1178    converted to a GROUP BY involving BIT fields.
1179   */
1180   uint hidden_bit_fields;
1181   /*
1182     Number of fields used in the definition of all the windows functions.
1183     This includes:
1184       1) Fields in the arguments
1185       2) Fields in the PARTITION BY clause
1186       3) Fields in the ORDER BY clause
1187   */
1188   uint fields_in_window_functions;
1189   enum_parsing_place parsing_place; /* where we are parsing expression */
1190   enum_parsing_place save_parsing_place;
1191   enum_parsing_place context_analysis_place; /* where we are in prepare */
1192   bool with_sum_func;   /* sum function indicator */
1193 
1194   ulong table_join_options;
1195   uint in_sum_expr;
1196   uint select_number; /* number of select (used for EXPLAIN) */
1197 
1198   /*
1199     nest_levels are local to the query or VIEW,
1200     and that view merge procedure does not re-calculate them.
1201     So we also have to remember unit against which we count levels.
1202   */
1203   SELECT_LEX_UNIT *nest_level_base;
1204   int nest_level;     /* nesting level of select */
1205   Item_sum *inner_sum_func_list; /* list of sum func in nested selects */
1206   uint with_wild; /* item list contain '*' */
1207   bool braces;    /* SELECT ... UNION (SELECT ... ) <- this braces */
1208   bool automatic_brackets; /* dummy select for INTERSECT precedence */
1209   /* TRUE when having fix field called in processing of this SELECT */
1210   bool having_fix_field;
1211   /*
1212     TRUE when fix field is called for a new condition pushed into the
1213     HAVING clause of this SELECT
1214   */
1215   bool having_fix_field_for_pushed_cond;
1216   /* List of references to fields referenced from inner selects */
1217   List<Item_outer_ref> inner_refs_list;
1218   /* Number of Item_sum-derived objects in this SELECT */
1219   uint n_sum_items;
1220   /* Number of Item_sum-derived objects in children and descendant SELECTs */
1221   uint n_child_sum_items;
1222 
1223   /* explicit LIMIT clause was used */
1224   bool explicit_limit;
1225   /*
1226     This array is used to note  whether we have any candidates for
1227     expression caching in the corresponding clauses
1228   */
1229   bool expr_cache_may_be_used[PARSING_PLACE_SIZE];
1230   /*
1231     there are subquery in HAVING clause => we can't close tables before
1232     query processing end even if we use temporary table
1233   */
1234   bool subquery_in_having;
1235   /* TRUE <=> this SELECT is correlated w.r.t. some ancestor select */
1236   bool with_all_modifier;  /* used for selects in union */
1237   bool is_correlated;
1238   /*
1239     This variable is required to ensure proper work of subqueries and
1240     stored procedures. Generally, one should use the states of
1241     Query_arena to determine if it's a statement prepare or first
1242     execution of a stored procedure. However, in case when there was an
1243     error during the first execution of a stored procedure, the SP body
1244     is not expelled from the SP cache. Therefore, a deeply nested
1245     subquery might be left unoptimized. So we need this per-subquery
1246     variable to inidicate the optimization/execution state of every
1247     subquery. Prepared statements work OK in that regard, as in
1248     case of an error during prepare the PS is not created.
1249   */
1250   uint8 changed_elements; // see TOUCHED_SEL_*
1251   /* TODO: add foloowing first_* to bitmap above */
1252   bool first_natural_join_processing;
1253   bool first_cond_optimization;
1254   /* do not wrap view fields with Item_ref */
1255   bool no_wrap_view_item;
1256   /* exclude this select from check of unique_table() */
1257   bool exclude_from_table_unique_test;
1258   /* the select is "service-select" and can not have tables*/
1259   bool is_service_select;
1260   /* index in the select list of the expression currently being fixed */
1261   int cur_pos_in_select_list;
1262 
1263   List<udf_func>     udf_list;                  /* udf function calls stack */
1264 
1265   /*
1266     This is a copy of the original JOIN USING list that comes from
1267     the parser. The parser :
1268       1. Sets the natural_join of the second TABLE_LIST in the join
1269          and the st_select_lex::prev_join_using.
1270       2. Makes a parent TABLE_LIST and sets its is_natural_join/
1271        join_using_fields members.
1272       3. Uses the wrapper TABLE_LIST as a table in the upper level.
1273     We cannot assign directly to join_using_fields in the parser because
1274     at stage (1.) the parent TABLE_LIST is not constructed yet and
1275     the assignment will override the JOIN USING fields of the lower level
1276     joins on the right.
1277   */
1278   List<String> *prev_join_using;
1279 
1280   /**
1281     The set of those tables whose fields are referenced in the select list of
1282     this select level.
1283   */
1284   table_map select_list_tables;
1285 
1286   /* namp of nesting SELECT visibility (for aggregate functions check) */
1287   nesting_map name_visibility_map;
1288 
1289   table_map with_dep;
1290   /* the structure to store fields that are used in the GROUP BY of this select */
1291   List<Field_pair> grouping_tmp_fields;
1292 
1293   /* it is for correct printing SELECT options */
1294   thr_lock_type lock_type;
1295 
1296   List<List_item> save_many_values;
1297   List<Item> *save_insert_list;
1298   table_value_constr *tvc;
1299   bool in_tvc;
1300 
1301   /* The interface employed to execute the select query by a foreign engine */
1302   select_handler *select_h;
1303   /* The object used to organize execution of the query by a foreign engine */
1304   Pushdown_select *pushdown_select;
1305 
1306   /** System Versioning */
1307 public:
1308   uint versioned_tables;
1309   int vers_setup_conds(THD *thd, TABLE_LIST *tables);
1310   /* push new Item_field into item_list */
1311   bool vers_push_field(THD *thd, TABLE_LIST *table, const LEX_CSTRING field_name);
1312 
1313   int period_setup_conds(THD *thd, TABLE_LIST *table);
1314   void init_query();
1315   void init_select();
1316   st_select_lex_unit* master_unit() { return (st_select_lex_unit*) master; }
1317   inline void set_master_unit(st_select_lex_unit *master_unit)
1318   {
1319     master= (st_select_lex_node *)master_unit;
1320   }
1321   void set_master(st_select_lex *master_arg)
1322   {
1323     master= master_arg;
1324   }
1325   st_select_lex_unit* first_inner_unit()
1326   {
1327     return (st_select_lex_unit*) slave;
1328   }
1329   st_select_lex* outer_select();
1330   st_select_lex* next_select() { return (st_select_lex*) next; }
1331   st_select_lex* next_select_in_list()
1332   {
1333     return (st_select_lex*) link_next;
1334   }
1335   st_select_lex_node** next_select_in_list_addr()
1336   {
1337     return &link_next;
1338   }
1339   st_select_lex* return_after_parsing()
1340   {
1341     return master_unit()->return_after_parsing();
1342   }
1343   inline bool is_subquery_function() { return master_unit()->item != 0; }
1344 
1345   bool mark_as_dependent(THD *thd, st_select_lex *last,
1346                          Item_ident *dependency);
1347 
1348   void set_braces(bool value)
1349   {
1350     braces= value;
1351   }
1352   bool inc_in_sum_expr();
1353   uint get_in_sum_expr();
1354 
1355   bool add_item_to_list(THD *thd, Item *item);
1356   bool add_group_to_list(THD *thd, Item *item, bool asc);
1357   bool add_ftfunc_to_list(THD *thd, Item_func_match *func);
1358   bool add_order_to_list(THD *thd, Item *item, bool asc);
1359   bool add_gorder_to_list(THD *thd, Item *item, bool asc);
1360   TABLE_LIST* add_table_to_list(THD *thd, Table_ident *table,
1361                                 LEX_CSTRING *alias,
1362                                 ulong table_options,
1363                                 thr_lock_type flags= TL_UNLOCK,
1364                                 enum_mdl_type mdl_type= MDL_SHARED_READ,
1365                                 List<Index_hint> *hints= 0,
1366                                 List<String> *partition_names= 0,
1367                                 LEX_STRING *option= 0);
1368   TABLE_LIST* get_table_list();
1369   bool init_nested_join(THD *thd);
1370   TABLE_LIST *end_nested_join(THD *thd);
1371   TABLE_LIST *nest_last_join(THD *thd);
1372   void add_joined_table(TABLE_LIST *table);
1373   bool add_cross_joined_table(TABLE_LIST *left_op, TABLE_LIST *right_op,
1374                               bool straight_fl);
1375   TABLE_LIST *convert_right_join();
1376   List<Item>* get_item_list();
1377   ulong get_table_join_options();
1378   void set_lock_for_tables(thr_lock_type lock_type, bool for_update);
1379   /*
1380     This method created for reiniting LEX in mysql_admin_table() and can be
1381     used only if you are going remove all SELECT_LEX & units except belonger
1382     to LEX (LEX::unit & LEX::select, for other purposes there are
1383     SELECT_LEX_UNIT::exclude_level & SELECT_LEX_UNIT::exclude_tree
1384   */
1385   void cut_subtree() { slave= 0; }
1386   bool test_limit();
1387   /**
1388     Get offset for LIMIT.
1389 
1390     Evaluate offset item if necessary.
1391 
1392     @return Number of rows to skip.
1393   */
1394   ha_rows get_offset();
1395   /**
1396    Get limit.
1397 
1398    Evaluate limit item if necessary.
1399 
1400    @return Limit of rows in result.
1401   */
1402   ha_rows get_limit();
1403 
1404   friend struct LEX;
1405   st_select_lex() : group_list_ptrs(NULL), braces(0), automatic_brackets(0),
1406   n_sum_items(0), n_child_sum_items(0)
1407   {}
1408   void make_empty_select()
1409   {
1410     init_query();
1411     init_select();
1412   }
1413   bool setup_ref_array(THD *thd, uint order_group_num);
1414   void print(THD *thd, String *str, enum_query_type query_type);
1415   static void print_order(String *str,
1416                           ORDER *order,
1417                           enum_query_type query_type);
1418   void print_limit(THD *thd, String *str, enum_query_type query_type);
1419   void fix_prepare_information(THD *thd, Item **conds, Item **having_conds);
1420   /*
1421     Destroy the used execution plan (JOIN) of this subtree (this
1422     SELECT_LEX and all nested SELECT_LEXes and SELECT_LEX_UNITs).
1423   */
1424   bool cleanup();
1425   /*
1426     Recursively cleanup the join of this select lex and of all nested
1427     select lexes.
1428   */
1429   void cleanup_all_joins(bool full);
1430 
1431   void set_index_hint_type(enum index_hint_type type, index_clause_map clause);
1432 
1433   /*
1434    Add a index hint to the tagged list of hints. The type and clause of the
1435    hint will be the current ones (set by set_index_hint())
1436   */
1437   bool add_index_hint (THD *thd, const char *str, size_t length);
1438 
1439   /* make a list to hold index hints */
1440   void alloc_index_hints (THD *thd);
1441   /* read and clear the index hints */
1442   List<Index_hint>* pop_index_hints(void)
1443   {
1444     List<Index_hint> *hints= index_hints;
1445     index_hints= NULL;
1446     return hints;
1447   }
1448 
1449   void clear_index_hints(void) { index_hints= NULL; }
1450   bool is_part_of_union() { return master_unit()->is_unit_op(); }
1451   bool is_top_level_node()
1452   {
1453     return (select_number == 1) && !is_part_of_union();
1454   }
1455   bool optimize_unflattened_subqueries(bool const_only);
1456   /* Set the EXPLAIN type for this subquery. */
1457   void set_explain_type(bool on_the_fly);
1458   bool handle_derived(LEX *lex, uint phases);
1459   void append_table_to_list(TABLE_LIST *TABLE_LIST::*link, TABLE_LIST *table);
1460   bool get_free_table_map(table_map *map, uint *tablenr);
1461   void replace_leaf_table(TABLE_LIST *table, List<TABLE_LIST> &tbl_list);
1462   void remap_tables(TABLE_LIST *derived, table_map map,
1463                     uint tablenr, st_select_lex *parent_lex);
1464   bool merge_subquery(THD *thd, TABLE_LIST *derived, st_select_lex *subq_lex,
1465                       uint tablenr, table_map map);
1466   inline bool is_mergeable()
1467   {
1468     return (next_select() == 0 && group_list.elements == 0 &&
1469             having == 0 && with_sum_func == 0 &&
1470             table_list.elements >= 1 && !(options & SELECT_DISTINCT) &&
1471             select_limit == 0);
1472   }
1473   void mark_as_belong_to_derived(TABLE_LIST *derived);
1474   void increase_derived_records(ha_rows records);
1475   void update_used_tables();
1476   void update_correlated_cache();
1477   void mark_const_derived(bool empty);
1478 
1479   bool save_leaf_tables(THD *thd);
1480   bool save_prep_leaf_tables(THD *thd);
1481 
1482   void set_unique_exclude();
1483 
1484   bool is_merged_child_of(st_select_lex *ancestor);
1485 
1486   /*
1487     For MODE_ONLY_FULL_GROUP_BY we need to maintain two flags:
1488      - Non-aggregated fields are used in this select.
1489      - Aggregate functions are used in this select.
1490     In MODE_ONLY_FULL_GROUP_BY only one of these may be true.
1491   */
1492   bool non_agg_field_used() const { return m_non_agg_field_used; }
1493   bool agg_func_used()      const { return m_agg_func_used; }
1494   bool custom_agg_func_used() const { return m_custom_agg_func_used; }
1495 
1496   void set_non_agg_field_used(bool val) { m_non_agg_field_used= val; }
1497   void set_agg_func_used(bool val)      { m_agg_func_used= val; }
1498   void set_custom_agg_func_used(bool val) { m_custom_agg_func_used= val; }
1499   inline void set_with_clause(With_clause *with_clause);
1500   With_clause *get_with_clause()
1501   {
1502     return master_unit()->with_clause;
1503   }
1504   With_element *get_with_element()
1505   {
1506     return master_unit()->cloned_from ?
1507            master_unit()->cloned_from->with_element :
1508            master_unit()->with_element;
1509   }
1510   With_element *find_table_def_in_with_clauses(TABLE_LIST *table);
1511   bool check_unrestricted_recursive(bool only_standard_compliant);
1512   bool check_subqueries_with_recursive_references();
1513   void collect_grouping_fields_for_derived(THD *thd, ORDER *grouping_list);
1514   bool collect_grouping_fields(THD *thd);
1515   bool collect_fields_equal_to_grouping(THD *thd);
1516   void check_cond_extraction_for_grouping_fields(THD *thd, Item *cond);
1517   Item *build_cond_for_grouping_fields(THD *thd, Item *cond,
1518                                        bool no_to_clones);
1519 
1520   List<Window_spec> window_specs;
1521   void prepare_add_window_spec(THD *thd);
1522   bool add_window_def(THD *thd, LEX_CSTRING *win_name, LEX_CSTRING *win_ref,
1523                       SQL_I_List<ORDER> win_partition_list,
1524                       SQL_I_List<ORDER> win_order_list,
1525                       Window_frame *win_frame);
1526   bool add_window_spec(THD *thd, LEX_CSTRING *win_ref,
1527                        SQL_I_List<ORDER> win_partition_list,
1528                        SQL_I_List<ORDER> win_order_list,
1529                        Window_frame *win_frame);
1530   List<Item_window_func> window_funcs;
1531   bool add_window_func(Item_window_func *win_func);
1532 
1533   bool have_window_funcs() const { return (window_funcs.elements !=0); }
1534   ORDER *find_common_window_func_partition_fields(THD *thd);
1535 
1536   bool cond_pushdown_is_allowed() const
1537   { return !olap && !explicit_limit && !tvc; }
1538 
1539   bool build_pushable_cond_for_having_pushdown(THD *thd, Item *cond);
1540   void pushdown_cond_into_where_clause(THD *thd, Item *extracted_cond,
1541                                        Item **remaining_cond,
1542                                        Item_transformer transformer,
1543                                        uchar *arg);
1544   Item *pushdown_from_having_into_where(THD *thd, Item *having);
1545 
1546   select_handler *find_select_handler(THD *thd);
1547 
1548 private:
1549   bool m_non_agg_field_used;
1550   bool m_agg_func_used;
1551   bool m_custom_agg_func_used;
1552 
1553   /* current index hint kind. used in filling up index_hints */
1554   enum index_hint_type current_index_hint_type;
1555   index_clause_map current_index_hint_clause;
1556   /* a list of USE/FORCE/IGNORE INDEX */
1557   List<Index_hint> *index_hints;
1558 
1559 public:
1560   inline void add_where_field(st_select_lex *sel)
1561   {
1562     DBUG_ASSERT(this != sel);
1563     select_n_where_fields+= sel->select_n_where_fields;
1564   }
1565   inline void set_linkage_and_distinct(enum sub_select_type l, bool d)
1566   {
1567     DBUG_ENTER("SELECT_LEX::set_linkage_and_distinct");
1568     DBUG_PRINT("info", ("select: %p  distinct %d", this, d));
1569     set_linkage(l);
1570     DBUG_ASSERT(l == UNION_TYPE ||
1571                 l == INTERSECT_TYPE ||
1572                 l == EXCEPT_TYPE);
1573     if (d && master_unit() && master_unit()->union_distinct != this)
1574       master_unit()->union_distinct= this;
1575     distinct= d;
1576     with_all_modifier= !distinct;
1577     DBUG_VOID_RETURN;
1578   }
1579   bool set_nest_level(int new_nest_level);
1580   bool check_parameters(SELECT_LEX *main_select);
1581   void mark_select()
1582   {
1583     DBUG_ENTER("st_select_lex::mark_select()");
1584     DBUG_PRINT("info", ("Select #%d", select_number));
1585     DBUG_VOID_RETURN;
1586   }
1587   void register_unit(SELECT_LEX_UNIT *unit,
1588                      Name_resolution_context *outer_context);
1589   SELECT_LEX_UNIT *attach_selects_chain(SELECT_LEX *sel,
1590                                         Name_resolution_context *context);
1591   void add_statistics(SELECT_LEX_UNIT *unit);
1592   bool make_unique_derived_name(THD *thd, LEX_CSTRING *alias);
1593   void lex_start(LEX *plex);
1594 };
1595 typedef class st_select_lex SELECT_LEX;
1596 
1597 inline bool st_select_lex_unit::is_unit_op ()
1598 {
1599   if (!first_select()->next_select())
1600   {
1601     if (first_select()->tvc)
1602       return 1;
1603     else
1604       return 0;
1605   }
1606 
1607   enum sub_select_type linkage= first_select()->next_select()->linkage;
1608   return linkage == UNION_TYPE || linkage == INTERSECT_TYPE ||
1609     linkage == EXCEPT_TYPE;
1610 }
1611 
1612 
1613 struct st_sp_chistics
1614 {
1615   LEX_CSTRING comment;
1616   enum enum_sp_suid_behaviour suid;
1617   bool detistic;
1618   enum enum_sp_data_access daccess;
1619   enum enum_sp_aggregate_type agg_type;
1620   void init() { bzero(this, sizeof(*this)); }
1621   void set(const st_sp_chistics &other) { *this= other; }
1622   bool read_from_mysql_proc_row(THD *thd, TABLE *table);
1623 };
1624 
1625 
1626 class Sp_chistics: public st_sp_chistics
1627 {
1628 public:
1629   Sp_chistics() { init(); }
1630 };
1631 
1632 
1633 struct st_trg_chistics: public st_trg_execution_order
1634 {
1635   enum trg_action_time_type action_time;
1636   enum trg_event_type event;
1637 
1638   const char *ordering_clause_begin;
1639   const char *ordering_clause_end;
1640 
1641 };
1642 
1643 enum xa_option_words {XA_NONE, XA_JOIN, XA_RESUME, XA_ONE_PHASE,
1644                       XA_SUSPEND, XA_FOR_MIGRATE};
1645 
1646 class Sroutine_hash_entry;
1647 
1648 /*
1649   Class representing list of all tables used by statement and other
1650   information which is necessary for opening and locking its tables,
1651   like SQL command for this statement.
1652 
1653   Also contains information about stored functions used by statement
1654   since during its execution we may have to add all tables used by its
1655   stored functions/triggers to this list in order to pre-open and lock
1656   them.
1657 
1658   Also used by LEX::reset_n_backup/restore_backup_query_tables_list()
1659   methods to save and restore this information.
1660 */
1661 
1662 class Query_tables_list
1663 {
1664 public:
1665   /**
1666     SQL command for this statement. Part of this class since the
1667     process of opening and locking tables for the statement needs
1668     this information to determine correct type of lock for some of
1669     the tables.
1670   */
1671   enum_sql_command sql_command;
1672   /* Global list of all tables used by this statement */
1673   TABLE_LIST *query_tables;
1674   /* Pointer to next_global member of last element in the previous list. */
1675   TABLE_LIST **query_tables_last;
1676   /*
1677     If non-0 then indicates that query requires prelocking and points to
1678     next_global member of last own element in query table list (i.e. last
1679     table which was not added to it as part of preparation to prelocking).
1680     0 - indicates that this query does not need prelocking.
1681   */
1682   TABLE_LIST **query_tables_own_last;
1683   /*
1684     Set of stored routines called by statement.
1685     (Note that we use lazy-initialization for this hash).
1686   */
1687   enum { START_SROUTINES_HASH_SIZE= 16 };
1688   HASH sroutines;
1689   /*
1690     List linking elements of 'sroutines' set. Allows you to add new elements
1691     to this set as you iterate through the list of existing elements.
1692     'sroutines_list_own_last' is pointer to ::next member of last element of
1693     this list which represents routine which is explicitly used by query.
1694     'sroutines_list_own_elements' number of explicitly used routines.
1695     We use these two members for restoring of 'sroutines_list' to the state
1696     in which it was right after query parsing.
1697   */
1698   SQL_I_List<Sroutine_hash_entry> sroutines_list;
1699   Sroutine_hash_entry **sroutines_list_own_last;
1700   uint sroutines_list_own_elements;
1701 
1702   /**
1703     Number of tables which were open by open_tables() and to be locked
1704     by lock_tables().
1705     Note that we set this member only in some cases, when this value
1706     needs to be passed from open_tables() to lock_tables() which are
1707     separated by some amount of code.
1708   */
1709   uint table_count;
1710 
1711    /*
1712     These constructor and destructor serve for creation/destruction
1713     of Query_tables_list instances which are used as backup storage.
1714   */
1715   Query_tables_list() {}
1716   ~Query_tables_list() {}
1717 
1718   /* Initializes (or resets) Query_tables_list object for "real" use. */
1719   void reset_query_tables_list(bool init);
1720   void destroy_query_tables_list();
1721   void set_query_tables_list(Query_tables_list *state)
1722   {
1723     *this= *state;
1724   }
1725 
1726   /*
1727     Direct addition to the list of query tables.
1728     If you are using this function, you must ensure that the table
1729     object, in particular table->db member, is initialized.
1730   */
1731   void add_to_query_tables(TABLE_LIST *table)
1732   {
1733     *(table->prev_global= query_tables_last)= table;
1734     query_tables_last= &table->next_global;
1735   }
1736   bool requires_prelocking()
1737   {
1738     return MY_TEST(query_tables_own_last);
1739   }
1740   void mark_as_requiring_prelocking(TABLE_LIST **tables_own_last)
1741   {
1742     query_tables_own_last= tables_own_last;
1743   }
1744   /* Return pointer to first not-own table in query-tables or 0 */
1745   TABLE_LIST* first_not_own_table()
1746   {
1747     return ( query_tables_own_last ? *query_tables_own_last : 0);
1748   }
1749   void chop_off_not_own_tables()
1750   {
1751     if (query_tables_own_last)
1752     {
1753       *query_tables_own_last= 0;
1754       query_tables_last= query_tables_own_last;
1755       query_tables_own_last= 0;
1756     }
1757   }
1758 
1759   /** Return a pointer to the last element in query table list. */
1760   TABLE_LIST *last_table()
1761   {
1762     /* Don't use offsetof() macro in order to avoid warnings. */
1763     return query_tables ?
1764            (TABLE_LIST*) ((char*) query_tables_last -
1765                           ((char*) &(query_tables->next_global) -
1766                            (char*) query_tables)) :
1767            0;
1768   }
1769 
1770   /**
1771     Enumeration listing of all types of unsafe statement.
1772 
1773     @note The order of elements of this enumeration type must
1774     correspond to the order of the elements of the @c explanations
1775     array defined in the body of @c THD::issue_unsafe_warnings.
1776   */
1777   enum enum_binlog_stmt_unsafe {
1778     /**
1779       SELECT..LIMIT is unsafe because the set of rows returned cannot
1780       be predicted.
1781     */
1782     BINLOG_STMT_UNSAFE_LIMIT= 0,
1783     /**
1784       INSERT DELAYED is unsafe because the time when rows are inserted
1785       cannot be predicted.
1786     */
1787     BINLOG_STMT_UNSAFE_INSERT_DELAYED,
1788     /**
1789       Access to log tables is unsafe because slave and master probably
1790       log different things.
1791     */
1792     BINLOG_STMT_UNSAFE_SYSTEM_TABLE,
1793     /**
1794       Inserting into an autoincrement column in a stored routine is unsafe.
1795       Even with just one autoincrement column, if the routine is invoked more than
1796       once slave is not guaranteed to execute the statement graph same way as
1797       the master.
1798       And since it's impossible to estimate how many times a routine can be invoked at
1799       the query pre-execution phase (see lock_tables), the statement is marked
1800       pessimistically unsafe.
1801     */
1802     BINLOG_STMT_UNSAFE_AUTOINC_COLUMNS,
1803     /**
1804       Using a UDF (user-defined function) is unsafe.
1805     */
1806     BINLOG_STMT_UNSAFE_UDF,
1807     /**
1808       Using most system variables is unsafe, because slave may run
1809       with different options than master.
1810     */
1811     BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE,
1812     /**
1813       Using some functions is unsafe (e.g., UUID).
1814     */
1815     BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION,
1816 
1817     /**
1818       Mixing transactional and non-transactional statements are unsafe if
1819       non-transactional reads or writes are occur after transactional
1820       reads or writes inside a transaction.
1821     */
1822     BINLOG_STMT_UNSAFE_NONTRANS_AFTER_TRANS,
1823 
1824     /**
1825       Mixing self-logging and non-self-logging engines in a statement
1826       is unsafe.
1827     */
1828     BINLOG_STMT_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
1829 
1830     /**
1831       Statements that read from both transactional and non-transactional
1832       tables and write to any of them are unsafe.
1833     */
1834     BINLOG_STMT_UNSAFE_MIXED_STATEMENT,
1835 
1836     /**
1837       INSERT...IGNORE SELECT is unsafe because which rows are ignored depends
1838       on the order that rows are retrieved by SELECT. This order cannot be
1839       predicted and may differ on master and the slave.
1840     */
1841     BINLOG_STMT_UNSAFE_INSERT_IGNORE_SELECT,
1842 
1843     /**
1844       INSERT...SELECT...UPDATE is unsafe because which rows are updated depends
1845       on the order that rows are retrieved by SELECT. This order cannot be
1846       predicted and may differ on master and the slave.
1847     */
1848     BINLOG_STMT_UNSAFE_INSERT_SELECT_UPDATE,
1849 
1850     /**
1851      Query that writes to a table with auto_inc column after selecting from
1852      other tables are unsafe as the order in which the rows are retrieved by
1853      select may differ on master and slave.
1854     */
1855     BINLOG_STMT_UNSAFE_WRITE_AUTOINC_SELECT,
1856 
1857     /**
1858       INSERT...REPLACE SELECT is unsafe because which rows are replaced depends
1859       on the order that rows are retrieved by SELECT. This order cannot be
1860       predicted and may differ on master and the slave.
1861     */
1862     BINLOG_STMT_UNSAFE_REPLACE_SELECT,
1863 
1864     /**
1865       CREATE TABLE... IGNORE... SELECT is unsafe because which rows are ignored
1866       depends on the order that rows are retrieved by SELECT. This order cannot
1867       be predicted and may differ on master and the slave.
1868     */
1869     BINLOG_STMT_UNSAFE_CREATE_IGNORE_SELECT,
1870 
1871     /**
1872       CREATE TABLE...REPLACE... SELECT is unsafe because which rows are replaced
1873       depends on the order that rows are retrieved from SELECT. This order
1874       cannot be predicted and may differ on master and the slave
1875     */
1876     BINLOG_STMT_UNSAFE_CREATE_REPLACE_SELECT,
1877 
1878     /**
1879       CREATE TABLE...SELECT on a table with auto-increment column is unsafe
1880       because which rows are replaced depends on the order that rows are
1881       retrieved from SELECT. This order cannot be predicted and may differ on
1882       master and the slave
1883     */
1884     BINLOG_STMT_UNSAFE_CREATE_SELECT_AUTOINC,
1885 
1886     /**
1887       UPDATE...IGNORE is unsafe because which rows are ignored depends on the
1888       order that rows are updated. This order cannot be predicted and may differ
1889       on master and the slave.
1890     */
1891     BINLOG_STMT_UNSAFE_UPDATE_IGNORE,
1892 
1893     /**
1894       INSERT... ON DUPLICATE KEY UPDATE on a table with more than one
1895       UNIQUE KEYS  is unsafe.
1896     */
1897     BINLOG_STMT_UNSAFE_INSERT_TWO_KEYS,
1898 
1899     /**
1900        INSERT into auto-inc field which is not the first part of composed
1901        primary key.
1902     */
1903     BINLOG_STMT_UNSAFE_AUTOINC_NOT_FIRST,
1904 
1905     /* The last element of this enumeration type. */
1906     BINLOG_STMT_UNSAFE_COUNT
1907   };
1908   /**
1909     This has all flags from 0 (inclusive) to BINLOG_STMT_FLAG_COUNT
1910     (exclusive) set.
1911   */
1912   static const uint32 BINLOG_STMT_UNSAFE_ALL_FLAGS=
1913     ((1U << BINLOG_STMT_UNSAFE_COUNT) - 1);
1914 
1915   /**
1916     Maps elements of enum_binlog_stmt_unsafe to error codes.
1917   */
1918   static const int binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT];
1919 
1920   /**
1921     Determine if this statement is marked as unsafe.
1922 
1923     @retval 0 if the statement is not marked as unsafe.
1924     @retval nonzero if the statement is marked as unsafe.
1925   */
1926   inline bool is_stmt_unsafe() const {
1927     return get_stmt_unsafe_flags() != 0;
1928   }
1929 
1930   inline bool is_stmt_unsafe(enum_binlog_stmt_unsafe unsafe)
1931   {
1932     return binlog_stmt_flags & (1 << unsafe);
1933   }
1934 
1935   /**
1936     Flag the current (top-level) statement as unsafe.
1937     The flag will be reset after the statement has finished.
1938 
1939     @param unsafe_type The type of unsafety: one of the @c
1940     BINLOG_STMT_FLAG_UNSAFE_* flags in @c enum_binlog_stmt_flag.
1941   */
1942   inline void set_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type) {
1943     DBUG_ENTER("set_stmt_unsafe");
1944     DBUG_ASSERT(unsafe_type >= 0 && unsafe_type < BINLOG_STMT_UNSAFE_COUNT);
1945     binlog_stmt_flags|= (1U << unsafe_type);
1946     DBUG_VOID_RETURN;
1947   }
1948 
1949   /**
1950     Set the bits of binlog_stmt_flags determining the type of
1951     unsafeness of the current statement.  No existing bits will be
1952     cleared, but new bits may be set.
1953 
1954     @param flags A binary combination of zero or more bits, (1<<flag)
1955     where flag is a member of enum_binlog_stmt_unsafe.
1956   */
1957   inline void set_stmt_unsafe_flags(uint32 flags) {
1958     DBUG_ENTER("set_stmt_unsafe_flags");
1959     DBUG_ASSERT((flags & ~BINLOG_STMT_UNSAFE_ALL_FLAGS) == 0);
1960     binlog_stmt_flags|= flags;
1961     DBUG_VOID_RETURN;
1962   }
1963 
1964   /**
1965     Return a binary combination of all unsafe warnings for the
1966     statement.  If the statement has been marked as unsafe by the
1967     'flag' member of enum_binlog_stmt_unsafe, then the return value
1968     from this function has bit (1<<flag) set to 1.
1969   */
1970   inline uint32 get_stmt_unsafe_flags() const {
1971     DBUG_ENTER("get_stmt_unsafe_flags");
1972     DBUG_RETURN(binlog_stmt_flags & BINLOG_STMT_UNSAFE_ALL_FLAGS);
1973   }
1974 
1975   /**
1976     Mark the current statement as safe; i.e., clear all bits in
1977     binlog_stmt_flags that correspond to elements of
1978     enum_binlog_stmt_unsafe.
1979   */
1980   inline void clear_stmt_unsafe() {
1981     DBUG_ENTER("clear_stmt_unsafe");
1982     binlog_stmt_flags&= ~BINLOG_STMT_UNSAFE_ALL_FLAGS;
1983     DBUG_VOID_RETURN;
1984   }
1985 
1986   /**
1987     Determine if this statement is a row injection.
1988 
1989     @retval 0 if the statement is not a row injection
1990     @retval nonzero if the statement is a row injection
1991   */
1992   inline bool is_stmt_row_injection() const {
1993     return binlog_stmt_flags &
1994       (1U << (BINLOG_STMT_UNSAFE_COUNT + BINLOG_STMT_TYPE_ROW_INJECTION));
1995   }
1996 
1997   /**
1998     Flag the statement as a row injection.  A row injection is either
1999     a BINLOG statement, or a row event in the relay log executed by
2000     the slave SQL thread.
2001   */
2002   inline void set_stmt_row_injection() {
2003     DBUG_ENTER("set_stmt_row_injection");
2004     binlog_stmt_flags|=
2005       (1U << (BINLOG_STMT_UNSAFE_COUNT + BINLOG_STMT_TYPE_ROW_INJECTION));
2006     DBUG_VOID_RETURN;
2007   }
2008 
2009   enum enum_stmt_accessed_table
2010   {
2011     /*
2012        If a transactional table is about to be read. Note that
2013        a write implies a read.
2014     */
2015     STMT_READS_TRANS_TABLE= 0,
2016     /*
2017        If a non-transactional table is about to be read. Note that
2018        a write implies a read.
2019     */
2020     STMT_READS_NON_TRANS_TABLE,
2021     /*
2022        If a temporary transactional table is about to be read. Note
2023        that a write implies a read.
2024     */
2025     STMT_READS_TEMP_TRANS_TABLE,
2026     /*
2027        If a temporary non-transactional table is about to be read. Note
2028       that a write implies a read.
2029     */
2030     STMT_READS_TEMP_NON_TRANS_TABLE,
2031     /*
2032        If a transactional table is about to be updated.
2033     */
2034     STMT_WRITES_TRANS_TABLE,
2035     /*
2036        If a non-transactional table is about to be updated.
2037     */
2038     STMT_WRITES_NON_TRANS_TABLE,
2039     /*
2040        If a temporary transactional table is about to be updated.
2041     */
2042     STMT_WRITES_TEMP_TRANS_TABLE,
2043     /*
2044        If a temporary non-transactional table is about to be updated.
2045     */
2046     STMT_WRITES_TEMP_NON_TRANS_TABLE,
2047     /*
2048       The last element of the enumeration. Please, if necessary add
2049       anything before this.
2050     */
2051     STMT_ACCESS_TABLE_COUNT
2052   };
2053 
2054 #ifndef DBUG_OFF
2055   static inline const char *stmt_accessed_table_string(enum_stmt_accessed_table accessed_table)
2056   {
2057     switch (accessed_table)
2058     {
2059       case STMT_READS_TRANS_TABLE:
2060          return "STMT_READS_TRANS_TABLE";
2061       break;
2062       case STMT_READS_NON_TRANS_TABLE:
2063         return "STMT_READS_NON_TRANS_TABLE";
2064       break;
2065       case STMT_READS_TEMP_TRANS_TABLE:
2066         return "STMT_READS_TEMP_TRANS_TABLE";
2067       break;
2068       case STMT_READS_TEMP_NON_TRANS_TABLE:
2069         return "STMT_READS_TEMP_NON_TRANS_TABLE";
2070       break;
2071       case STMT_WRITES_TRANS_TABLE:
2072         return "STMT_WRITES_TRANS_TABLE";
2073       break;
2074       case STMT_WRITES_NON_TRANS_TABLE:
2075         return "STMT_WRITES_NON_TRANS_TABLE";
2076       break;
2077       case STMT_WRITES_TEMP_TRANS_TABLE:
2078         return "STMT_WRITES_TEMP_TRANS_TABLE";
2079       break;
2080       case STMT_WRITES_TEMP_NON_TRANS_TABLE:
2081         return "STMT_WRITES_TEMP_NON_TRANS_TABLE";
2082       break;
2083       case STMT_ACCESS_TABLE_COUNT:
2084       default:
2085         DBUG_ASSERT(0);
2086       break;
2087     }
2088     MY_ASSERT_UNREACHABLE();
2089     return "";
2090   }
2091 #endif  /* DBUG */
2092 
2093   #define BINLOG_DIRECT_ON 0xF0    /* unsafe when
2094                                       --binlog-direct-non-trans-updates
2095                                       is ON */
2096 
2097   #define BINLOG_DIRECT_OFF 0xF    /* unsafe when
2098                                       --binlog-direct-non-trans-updates
2099                                       is OFF */
2100 
2101   #define TRX_CACHE_EMPTY 0x33     /* unsafe when trx-cache is empty */
2102 
2103   #define TRX_CACHE_NOT_EMPTY 0xCC /* unsafe when trx-cache is not empty */
2104 
2105   #define IL_LT_REPEATABLE 0xAA    /* unsafe when < ISO_REPEATABLE_READ */
2106 
2107   #define IL_GTE_REPEATABLE 0x55   /* unsafe when >= ISO_REPEATABLE_READ */
2108 
2109   /**
2110     Sets the type of table that is about to be accessed while executing a
2111     statement.
2112 
2113     @param accessed_table Enumeration type that defines the type of table,
2114                            e.g. temporary, transactional, non-transactional.
2115   */
2116   inline void set_stmt_accessed_table(enum_stmt_accessed_table accessed_table)
2117   {
2118     DBUG_ENTER("LEX::set_stmt_accessed_table");
2119 
2120     DBUG_ASSERT(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT);
2121     stmt_accessed_table_flag |= (1U << accessed_table);
2122 
2123     DBUG_VOID_RETURN;
2124   }
2125 
2126   /**
2127     Checks if a type of table is about to be accessed while executing a
2128     statement.
2129 
2130     @param accessed_table Enumeration type that defines the type of table,
2131            e.g. temporary, transactional, non-transactional.
2132 
2133     @return
2134       @retval TRUE  if the type of the table is about to be accessed
2135       @retval FALSE otherwise
2136   */
2137   inline bool stmt_accessed_table(enum_stmt_accessed_table accessed_table)
2138   {
2139     DBUG_ENTER("LEX::stmt_accessed_table");
2140 
2141     DBUG_ASSERT(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT);
2142 
2143     DBUG_RETURN((stmt_accessed_table_flag & (1U << accessed_table)) != 0);
2144   }
2145 
2146   /**
2147     Checks either a trans/non trans temporary table is being accessed while
2148     executing a statement.
2149 
2150     @return
2151       @retval TRUE  if a temporary table is being accessed
2152       @retval FALSE otherwise
2153   */
2154   inline bool stmt_accessed_temp_table()
2155   {
2156     DBUG_ENTER("THD::stmt_accessed_temp_table");
2157     DBUG_RETURN(stmt_accessed_non_trans_temp_table() ||
2158                 stmt_accessed_trans_temp_table());
2159   }
2160 
2161   /**
2162     Checks if a temporary transactional table is being accessed while executing
2163     a statement.
2164 
2165     @return
2166       @retval TRUE  if a temporary transactional table is being accessed
2167       @retval FALSE otherwise
2168   */
2169   inline bool stmt_accessed_trans_temp_table()
2170   {
2171     DBUG_ENTER("THD::stmt_accessed_trans_temp_table");
2172 
2173     DBUG_RETURN((stmt_accessed_table_flag &
2174                 ((1U << STMT_READS_TEMP_TRANS_TABLE) |
2175                  (1U << STMT_WRITES_TEMP_TRANS_TABLE))) != 0);
2176   }
2177   inline bool stmt_writes_to_non_temp_table()
2178   {
2179     DBUG_ENTER("THD::stmt_writes_to_non_temp_table");
2180 
2181     DBUG_RETURN((stmt_accessed_table_flag &
2182                 ((1U << STMT_WRITES_TRANS_TABLE) |
2183                  (1U << STMT_WRITES_NON_TRANS_TABLE))));
2184   }
2185 
2186   /**
2187     Checks if a temporary non-transactional table is about to be accessed
2188     while executing a statement.
2189 
2190     @return
2191       @retval TRUE  if a temporary non-transactional table is about to be
2192                     accessed
2193       @retval FALSE otherwise
2194   */
2195   inline bool stmt_accessed_non_trans_temp_table()
2196   {
2197     DBUG_ENTER("THD::stmt_accessed_non_trans_temp_table");
2198 
2199     DBUG_RETURN((stmt_accessed_table_flag &
2200                 ((1U << STMT_READS_TEMP_NON_TRANS_TABLE) |
2201                  (1U << STMT_WRITES_TEMP_NON_TRANS_TABLE))) != 0);
2202   }
2203 
2204   /*
2205     Checks if a mixed statement is unsafe.
2206 
2207 
2208     @param in_multi_stmt_transaction_mode defines if there is an on-going
2209            multi-transactional statement.
2210     @param binlog_direct defines if --binlog-direct-non-trans-updates is
2211            active.
2212     @param trx_cache_is_not_empty defines if the trx-cache is empty or not.
2213     @param trx_isolation defines the isolation level.
2214 
2215     @return
2216       @retval TRUE if the mixed statement is unsafe
2217       @retval FALSE otherwise
2218   */
2219   inline bool is_mixed_stmt_unsafe(bool in_multi_stmt_transaction_mode,
2220                                    bool binlog_direct,
2221                                    bool trx_cache_is_not_empty,
2222                                    uint tx_isolation)
2223   {
2224     bool unsafe= FALSE;
2225 
2226     if (in_multi_stmt_transaction_mode)
2227     {
2228        uint condition=
2229          (binlog_direct ? BINLOG_DIRECT_ON : BINLOG_DIRECT_OFF) &
2230          (trx_cache_is_not_empty ? TRX_CACHE_NOT_EMPTY : TRX_CACHE_EMPTY) &
2231          (tx_isolation >= ISO_REPEATABLE_READ ? IL_GTE_REPEATABLE : IL_LT_REPEATABLE);
2232 
2233       unsafe= (binlog_unsafe_map[stmt_accessed_table_flag] & condition);
2234 
2235 #if !defined(DBUG_OFF)
2236       DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("RESULT %02X %02X %02X", condition,
2237               binlog_unsafe_map[stmt_accessed_table_flag],
2238               (binlog_unsafe_map[stmt_accessed_table_flag] & condition)));
2239 
2240       int type_in= 0;
2241       for (; type_in < STMT_ACCESS_TABLE_COUNT; type_in++)
2242       {
2243         if (stmt_accessed_table((enum_stmt_accessed_table) type_in))
2244           DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("ACCESSED %s ",
2245                   stmt_accessed_table_string((enum_stmt_accessed_table) type_in)));
2246       }
2247 #endif
2248     }
2249 
2250     if (stmt_accessed_table(STMT_WRITES_NON_TRANS_TABLE) &&
2251       stmt_accessed_table(STMT_READS_TRANS_TABLE) &&
2252       tx_isolation < ISO_REPEATABLE_READ)
2253       unsafe= TRUE;
2254     else if (stmt_accessed_table(STMT_WRITES_TEMP_NON_TRANS_TABLE) &&
2255       stmt_accessed_table(STMT_READS_TRANS_TABLE) &&
2256       tx_isolation < ISO_REPEATABLE_READ)
2257       unsafe= TRUE;
2258 
2259     return(unsafe);
2260   }
2261 
2262   /**
2263     true if the parsed tree contains references to stored procedures
2264     or functions, false otherwise
2265   */
2266   bool uses_stored_routines() const
2267   { return sroutines_list.elements != 0; }
2268 
2269 private:
2270 
2271   /**
2272     Enumeration listing special types of statements.
2273 
2274     Currently, the only possible type is ROW_INJECTION.
2275   */
2276   enum enum_binlog_stmt_type {
2277     /**
2278       The statement is a row injection (i.e., either a BINLOG
2279       statement or a row event executed by the slave SQL thread).
2280     */
2281     BINLOG_STMT_TYPE_ROW_INJECTION = 0,
2282 
2283     /** The last element of this enumeration type. */
2284     BINLOG_STMT_TYPE_COUNT
2285   };
2286 
2287   /**
2288     Bit field indicating the type of statement.
2289 
2290     There are two groups of bits:
2291 
2292     - The low BINLOG_STMT_UNSAFE_COUNT bits indicate the types of
2293       unsafeness that the current statement has.
2294 
2295     - The next BINLOG_STMT_TYPE_COUNT bits indicate if the statement
2296       is of some special type.
2297 
2298     This must be a member of LEX, not of THD: each stored procedure
2299     needs to remember its unsafeness state between calls and each
2300     stored procedure has its own LEX object (but no own THD object).
2301   */
2302   uint32 binlog_stmt_flags;
2303 
2304   /**
2305     Bit field that determines the type of tables that are about to be
2306     be accessed while executing a statement.
2307   */
2308   uint32 stmt_accessed_table_flag;
2309 };
2310 
2311 
2312 /*
2313   st_parsing_options contains the flags for constructions that are
2314   allowed in the current statement.
2315 */
2316 
2317 struct st_parsing_options
2318 {
2319   bool allows_variable;
2320   bool lookup_keywords_after_qualifier;
2321 
2322   st_parsing_options() { reset(); }
2323   void reset();
2324 };
2325 
2326 
2327 /**
2328   The state of the lexical parser, when parsing comments.
2329 */
2330 enum enum_comment_state
2331 {
2332   /**
2333     Not parsing comments.
2334   */
2335   NO_COMMENT,
2336   /**
2337     Parsing comments that need to be preserved.
2338     Typically, these are user comments '/' '*' ... '*' '/'.
2339   */
2340   PRESERVE_COMMENT,
2341   /**
2342     Parsing comments that need to be discarded.
2343     Typically, these are special comments '/' '*' '!' ... '*' '/',
2344     or '/' '*' '!' 'M' 'M' 'm' 'm' 'm' ... '*' '/', where the comment
2345     markers should not be expanded.
2346   */
2347   DISCARD_COMMENT
2348 };
2349 
2350 
2351 /**
2352   @brief This class represents the character input stream consumed during
2353   lexical analysis.
2354 
2355   In addition to consuming the input stream, this class performs some
2356   comment pre processing, by filtering out out of bound special text
2357   from the query input stream.
2358   Two buffers, with pointers inside each buffers, are maintained in
2359   parallel. The 'raw' buffer is the original query text, which may
2360   contain out-of-bound comments. The 'cpp' (for comments pre processor)
2361   is the pre-processed buffer that contains only the query text that
2362   should be seen once out-of-bound data is removed.
2363 */
2364 
2365 class Lex_input_stream
2366 {
2367   size_t unescape(CHARSET_INFO *cs, char *to,
2368                   const char *str, const char *end, int sep);
2369   my_charset_conv_wc_mb get_escape_func(THD *thd, my_wc_t sep) const;
2370 public:
2371   Lex_input_stream()
2372   {
2373   }
2374 
2375   ~Lex_input_stream()
2376   {
2377   }
2378 
2379   /**
2380      Object initializer. Must be called before usage.
2381 
2382      @retval FALSE OK
2383      @retval TRUE  Error
2384   */
2385   bool init(THD *thd, char *buff, size_t length);
2386 
2387   void reset(char *buff, size_t length);
2388 
2389   /**
2390     The main method to scan the next token, with token contraction processing
2391     for LALR(2) resolution, e.g. translate "WITH" followed by "ROLLUP"
2392     to a single token WITH_ROLLUP_SYM.
2393   */
2394   int lex_token(union YYSTYPE *yylval, THD *thd);
2395 
2396   void reduce_digest_token(uint token_left, uint token_right);
2397 
2398 private:
2399   /**
2400     Set the echo mode.
2401 
2402     When echo is true, characters parsed from the raw input stream are
2403     preserved. When false, characters parsed are silently ignored.
2404     @param echo the echo mode.
2405   */
2406   void set_echo(bool echo)
2407   {
2408     m_echo= echo;
2409   }
2410 
2411   void save_in_comment_state()
2412   {
2413     m_echo_saved= m_echo;
2414     in_comment_saved= in_comment;
2415   }
2416 
2417   void restore_in_comment_state()
2418   {
2419     m_echo= m_echo_saved;
2420     in_comment= in_comment_saved;
2421   }
2422 
2423   /**
2424     Skip binary from the input stream.
2425     @param n number of bytes to accept.
2426   */
2427   void skip_binary(int n)
2428   {
2429     if (m_echo)
2430     {
2431       memcpy(m_cpp_ptr, m_ptr, n);
2432       m_cpp_ptr += n;
2433     }
2434     m_ptr += n;
2435   }
2436 
2437   /**
2438     Get a character, and advance in the stream.
2439     @return the next character to parse.
2440   */
2441   unsigned char yyGet()
2442   {
2443     char c= *m_ptr++;
2444     if (m_echo)
2445       *m_cpp_ptr++ = c;
2446     return c;
2447   }
2448 
2449   /**
2450     Get the last character accepted.
2451     @return the last character accepted.
2452   */
2453   unsigned char yyGetLast()
2454   {
2455     return m_ptr[-1];
2456   }
2457 
2458   /**
2459     Look at the next character to parse, but do not accept it.
2460   */
2461   unsigned char yyPeek()
2462   {
2463     return m_ptr[0];
2464   }
2465 
2466   /**
2467     Look ahead at some character to parse.
2468     @param n offset of the character to look up
2469   */
2470   unsigned char yyPeekn(int n)
2471   {
2472     return m_ptr[n];
2473   }
2474 
2475   /**
2476     Cancel the effect of the last yyGet() or yySkip().
2477     Note that the echo mode should not change between calls to yyGet / yySkip
2478     and yyUnget. The caller is responsible for ensuring that.
2479   */
2480   void yyUnget()
2481   {
2482     m_ptr--;
2483     if (m_echo)
2484       m_cpp_ptr--;
2485   }
2486 
2487   /**
2488     Accept a character, by advancing the input stream.
2489   */
2490   void yySkip()
2491   {
2492     if (m_echo)
2493       *m_cpp_ptr++ = *m_ptr++;
2494     else
2495       m_ptr++;
2496   }
2497 
2498   /**
2499     Accept multiple characters at once.
2500     @param n the number of characters to accept.
2501   */
2502   void yySkipn(int n)
2503   {
2504     if (m_echo)
2505     {
2506       memcpy(m_cpp_ptr, m_ptr, n);
2507       m_cpp_ptr += n;
2508     }
2509     m_ptr += n;
2510   }
2511 
2512   /**
2513     Puts a character back into the stream, canceling
2514     the effect of the last yyGet() or yySkip().
2515     Note that the echo mode should not change between calls
2516     to unput, get, or skip from the stream.
2517   */
2518   char *yyUnput(char ch)
2519   {
2520     *--m_ptr= ch;
2521     if (m_echo)
2522       m_cpp_ptr--;
2523     return m_ptr;
2524   }
2525 
2526   /**
2527     End of file indicator for the query text to parse.
2528     @param n number of characters expected
2529     @return true if there are less than n characters to parse
2530   */
2531   bool eof(int n)
2532   {
2533     return ((m_ptr + n) >= m_end_of_query);
2534   }
2535 
2536   /** Mark the stream position as the start of a new token. */
2537   void start_token()
2538   {
2539     m_tok_start_prev= m_tok_start;
2540     m_tok_start= m_ptr;
2541     m_tok_end= m_ptr;
2542 
2543     m_cpp_tok_start_prev= m_cpp_tok_start;
2544     m_cpp_tok_start= m_cpp_ptr;
2545     m_cpp_tok_end= m_cpp_ptr;
2546   }
2547 
2548   /**
2549     Adjust the starting position of the current token.
2550     This is used to compensate for starting whitespace.
2551   */
2552   void restart_token()
2553   {
2554     m_tok_start= m_ptr;
2555     m_cpp_tok_start= m_cpp_ptr;
2556   }
2557 
2558   /**
2559     Get the maximum length of the utf8-body buffer.
2560     The utf8 body can grow because of the character set conversion and escaping.
2561   */
2562   size_t get_body_utf8_maximum_length(THD *thd);
2563 
2564   /** Get the length of the current token, in the raw buffer. */
2565   uint yyLength()
2566   {
2567     /*
2568       The assumption is that the lexical analyser is always 1 character ahead,
2569       which the -1 account for.
2570     */
2571     DBUG_ASSERT(m_ptr > m_tok_start);
2572     return (uint) ((m_ptr - m_tok_start) - 1);
2573   }
2574 
2575   /**
2576     Test if a lookahead token was already scanned by lex_token(),
2577     for LALR(2) resolution.
2578   */
2579   bool has_lookahead() const
2580   {
2581     return lookahead_token >= 0;
2582   }
2583 
2584 public:
2585 
2586   /**
2587     End of file indicator for the query text to parse.
2588     @return true if there are no more characters to parse
2589   */
2590   bool eof()
2591   {
2592     return (m_ptr >= m_end_of_query);
2593   }
2594 
2595   /** Get the raw query buffer. */
2596   const char *get_buf()
2597   {
2598     return m_buf;
2599   }
2600 
2601   /** Get the pre-processed query buffer. */
2602   const char *get_cpp_buf()
2603   {
2604     return m_cpp_buf;
2605   }
2606 
2607   /** Get the end of the raw query buffer. */
2608   const char *get_end_of_query()
2609   {
2610     return m_end_of_query;
2611   }
2612 
2613   /** Get the token start position, in the raw buffer. */
2614   const char *get_tok_start()
2615   {
2616     return has_lookahead() ? m_tok_start_prev : m_tok_start;
2617   }
2618 
2619   void set_cpp_tok_start(const char *pos)
2620   {
2621     m_cpp_tok_start= pos;
2622   }
2623 
2624   /** Get the token end position, in the raw buffer. */
2625   const char *get_tok_end()
2626   {
2627     return m_tok_end;
2628   }
2629 
2630   /** Get the current stream pointer, in the raw buffer. */
2631   const char *get_ptr()
2632   {
2633     return m_ptr;
2634   }
2635 
2636   /** Get the token start position, in the pre-processed buffer. */
2637   const char *get_cpp_tok_start()
2638   {
2639     return has_lookahead() ? m_cpp_tok_start_prev : m_cpp_tok_start;
2640   }
2641 
2642   /** Get the token end position, in the pre-processed buffer. */
2643   const char *get_cpp_tok_end()
2644   {
2645     return m_cpp_tok_end;
2646   }
2647 
2648   /**
2649     Get the token end position in the pre-processed buffer,
2650     with trailing spaces removed.
2651   */
2652   const char *get_cpp_tok_end_rtrim()
2653   {
2654     const char *p;
2655     for (p= m_cpp_tok_end;
2656          p > m_cpp_buf && my_isspace(system_charset_info, p[-1]);
2657          p--)
2658     { }
2659     return p;
2660   }
2661 
2662   /** Get the current stream pointer, in the pre-processed buffer. */
2663   const char *get_cpp_ptr()
2664   {
2665     return m_cpp_ptr;
2666   }
2667 
2668   /**
2669     Get the current stream pointer, in the pre-processed buffer,
2670     with traling spaces removed.
2671   */
2672   const char *get_cpp_ptr_rtrim()
2673   {
2674     const char *p;
2675     for (p= m_cpp_ptr;
2676          p > m_cpp_buf && my_isspace(system_charset_info, p[-1]);
2677          p--)
2678     { }
2679     return p;
2680   }
2681   /** Get the utf8-body string. */
2682   const char *get_body_utf8_str()
2683   {
2684     return m_body_utf8;
2685   }
2686 
2687   /** Get the utf8-body length. */
2688   size_t get_body_utf8_length()
2689   {
2690     return (size_t) (m_body_utf8_ptr - m_body_utf8);
2691   }
2692 
2693   void body_utf8_start(THD *thd, const char *begin_ptr);
2694   void body_utf8_append(const char *ptr);
2695   void body_utf8_append(const char *ptr, const char *end_ptr);
2696   void body_utf8_append_ident(THD *thd,
2697                               const Lex_string_with_metadata_st *txt,
2698                               const char *end_ptr);
2699   void body_utf8_append_escape(THD *thd,
2700                                const LEX_CSTRING *txt,
2701                                CHARSET_INFO *txt_cs,
2702                                const char *end_ptr,
2703                                my_wc_t sep);
2704 
2705 private:
2706   /**
2707     LALR(2) resolution, look ahead token.
2708     Value of the next token to return, if any,
2709     or -1, if no token was parsed in advance.
2710     Note: 0 is a legal token, and represents YYEOF.
2711   */
2712   int lookahead_token;
2713 
2714   /** LALR(2) resolution, value of the look ahead token.*/
2715   LEX_YYSTYPE lookahead_yylval;
2716 
2717   bool get_text(Lex_string_with_metadata_st *to,
2718                 uint sep, int pre_skip, int post_skip);
2719 
2720   void add_digest_token(uint token, LEX_YYSTYPE yylval);
2721 
2722   bool consume_comment(int remaining_recursions_permitted);
2723   int lex_one_token(union YYSTYPE *yylval, THD *thd);
2724   int find_keyword(Lex_ident_cli_st *str, uint len, bool function);
2725   LEX_CSTRING get_token(uint skip, uint length);
2726   int scan_ident_sysvar(THD *thd, Lex_ident_cli_st *str);
2727   int scan_ident_start(THD *thd, Lex_ident_cli_st *str);
2728   int scan_ident_middle(THD *thd, Lex_ident_cli_st *str,
2729                         CHARSET_INFO **cs, my_lex_states *);
2730   int scan_ident_delimited(THD *thd, Lex_ident_cli_st *str, uchar quote_char);
2731   bool get_7bit_or_8bit_ident(THD *thd, uchar *last_char);
2732 
2733   /** Current thread. */
2734   THD *m_thd;
2735 
2736   /** Pointer to the current position in the raw input stream. */
2737   char *m_ptr;
2738 
2739   /** Starting position of the last token parsed, in the raw buffer. */
2740   const char *m_tok_start;
2741 
2742   /** Ending position of the previous token parsed, in the raw buffer. */
2743   const char *m_tok_end;
2744 
2745   /** End of the query text in the input stream, in the raw buffer. */
2746   const char *m_end_of_query;
2747 
2748   /** Starting position of the previous token parsed, in the raw buffer. */
2749   const char *m_tok_start_prev;
2750 
2751   /** Begining of the query text in the input stream, in the raw buffer. */
2752   const char *m_buf;
2753 
2754   /** Length of the raw buffer. */
2755   size_t m_buf_length;
2756 
2757   /** Echo the parsed stream to the pre-processed buffer. */
2758   bool m_echo;
2759   bool m_echo_saved;
2760 
2761   /** Pre-processed buffer. */
2762   char *m_cpp_buf;
2763 
2764   /** Pointer to the current position in the pre-processed input stream. */
2765   char *m_cpp_ptr;
2766 
2767   /**
2768     Starting position of the last token parsed,
2769     in the pre-processed buffer.
2770   */
2771   const char *m_cpp_tok_start;
2772 
2773   /**
2774     Starting position of the previous token parsed,
2775     in the pre-procedded buffer.
2776   */
2777   const char *m_cpp_tok_start_prev;
2778 
2779   /**
2780     Ending position of the previous token parsed,
2781     in the pre-processed buffer.
2782   */
2783   const char *m_cpp_tok_end;
2784 
2785   /** UTF8-body buffer created during parsing. */
2786   char *m_body_utf8;
2787 
2788   /** Pointer to the current position in the UTF8-body buffer. */
2789   char *m_body_utf8_ptr;
2790 
2791   /**
2792     Position in the pre-processed buffer. The query from m_cpp_buf to
2793     m_cpp_utf_processed_ptr is converted to UTF8-body.
2794   */
2795   const char *m_cpp_utf8_processed_ptr;
2796 
2797 public:
2798 
2799   /** Current state of the lexical analyser. */
2800   enum my_lex_states next_state;
2801 
2802   /**
2803     Position of ';' in the stream, to delimit multiple queries.
2804     This delimiter is in the raw buffer.
2805   */
2806   const char *found_semicolon;
2807 
2808   /** SQL_MODE = IGNORE_SPACE. */
2809   bool ignore_space;
2810 
2811   /**
2812     TRUE if we're parsing a prepared statement: in this mode
2813     we should allow placeholders.
2814   */
2815   bool stmt_prepare_mode;
2816   /**
2817     TRUE if we should allow multi-statements.
2818   */
2819   bool multi_statements;
2820 
2821   /** Current line number. */
2822   uint yylineno;
2823 
2824   /**
2825     Current statement digest instrumentation.
2826   */
2827   sql_digest_state* m_digest;
2828 
2829 private:
2830   /** State of the lexical analyser for comments. */
2831   enum_comment_state in_comment;
2832   enum_comment_state in_comment_saved;
2833 
2834   /**
2835     Starting position of the TEXT_STRING or IDENT in the pre-processed
2836     buffer.
2837 
2838     NOTE: this member must be used within MYSQLlex() function only.
2839   */
2840   const char *m_cpp_text_start;
2841 
2842   /**
2843     Ending position of the TEXT_STRING or IDENT in the pre-processed
2844     buffer.
2845 
2846     NOTE: this member must be used within MYSQLlex() function only.
2847     */
2848   const char *m_cpp_text_end;
2849 
2850   /**
2851     Character set specified by the character-set-introducer.
2852 
2853     NOTE: this member must be used within MYSQLlex() function only.
2854   */
2855   CHARSET_INFO *m_underscore_cs;
2856 };
2857 
2858 
2859 /**
2860   Abstract representation of a statement.
2861   This class is an interface between the parser and the runtime.
2862   The parser builds the appropriate sub classes of Sql_statement
2863   to represent a SQL statement in the parsed tree.
2864   The execute() method in the sub classes contain the runtime implementation.
2865   Note that this interface is used for SQL statement recently implemented,
2866   the code for older statements tend to load the LEX structure with more
2867   attributes instead.
2868   The recommended way to implement new statements is to sub-class
2869   Sql_statement, as this improves code modularity (see the 'big switch' in
2870   dispatch_command()), and decrease the total size of the LEX structure
2871   (therefore saving memory in stored programs).
2872 */
2873 class Sql_statement : public Sql_alloc
2874 {
2875 public:
2876   /**
2877     Execute this SQL statement.
2878     @param thd the current thread.
2879     @return 0 on success.
2880   */
2881   virtual bool execute(THD *thd) = 0;
2882 
2883 protected:
2884   /**
2885     Constructor.
2886     @param lex the LEX structure that represents parts of this statement.
2887   */
2888   Sql_statement(LEX *lex)
2889     : m_lex(lex)
2890   {}
2891 
2892   /** Destructor. */
2893   virtual ~Sql_statement()
2894   {
2895     /*
2896       Sql_statement objects are allocated in thd->mem_root.
2897       In MySQL, the C++ destructor is never called, the underlying MEM_ROOT is
2898       simply destroyed instead.
2899       Do not rely on the destructor for any cleanup.
2900     */
2901     DBUG_ASSERT(FALSE);
2902   }
2903 
2904 protected:
2905   /**
2906     The legacy LEX structure for this statement.
2907     The LEX structure contains the existing properties of the parsed tree.
2908     TODO: with time, attributes from LEX should move to sub classes of
2909     Sql_statement, so that the parser only builds Sql_statement objects
2910     with the minimum set of attributes, instead of a LEX structure that
2911     contains the collection of every possible attribute.
2912   */
2913   LEX *m_lex;
2914 };
2915 
2916 
2917 class Delete_plan;
2918 class SQL_SELECT;
2919 
2920 class Explain_query;
2921 class Explain_update;
2922 class Explain_delete;
2923 
2924 /*
2925   Query plan of a single-table UPDATE.
2926   (This is actually a plan for single-table DELETE also)
2927 */
2928 
2929 class Update_plan
2930 {
2931 protected:
2932   bool impossible_where;
2933   bool no_partitions;
2934 public:
2935   /*
2936     When single-table UPDATE updates a VIEW, that VIEW's select is still
2937     listed as the first child.  When we print EXPLAIN, it looks like a
2938     subquery.
2939     In order to get rid of it, updating_a_view=TRUE means that first child
2940     select should not be shown when printing EXPLAIN.
2941   */
2942   bool updating_a_view;
2943 
2944   /* Allocate things there */
2945   MEM_ROOT *mem_root;
2946 
2947   TABLE *table;
2948   SQL_SELECT *select;
2949   uint index;
2950   ha_rows scanned_rows;
2951   /*
2952     Top-level select_lex. Most of its fields are not used, we need it only to
2953     get to the subqueries.
2954   */
2955   SELECT_LEX *select_lex;
2956 
2957   key_map possible_keys;
2958   bool using_filesort;
2959   bool using_io_buffer;
2960 
2961   /* Set this plan to be a plan to do nothing because of impossible WHERE */
2962   void set_impossible_where() { impossible_where= true; }
2963   void set_no_partitions() { no_partitions= true; }
2964 
2965   Explain_update* save_explain_update_data(MEM_ROOT *mem_root, THD *thd);
2966 protected:
2967   bool save_explain_data_intern(MEM_ROOT *mem_root, Explain_update *eu, bool is_analyze);
2968 public:
2969   virtual ~Update_plan() {}
2970 
2971   Update_plan(MEM_ROOT *mem_root_arg) :
2972     impossible_where(false), no_partitions(false),
2973     mem_root(mem_root_arg),
2974     using_filesort(false), using_io_buffer(false)
2975   {}
2976 };
2977 
2978 
2979 /* Query plan of a single-table DELETE */
2980 class Delete_plan : public Update_plan
2981 {
2982   bool deleting_all_rows;
2983 public:
2984 
2985   /* Construction functions */
2986   Delete_plan(MEM_ROOT *mem_root_arg) :
2987     Update_plan(mem_root_arg),
2988     deleting_all_rows(false)
2989   {}
2990 
2991   /* Set this query plan to be a plan to make a call to h->delete_all_rows() */
2992   void set_delete_all_rows(ha_rows rows_arg)
2993   {
2994     deleting_all_rows= true;
2995     scanned_rows= rows_arg;
2996   }
2997   void cancel_delete_all_rows()
2998   {
2999     deleting_all_rows= false;
3000   }
3001 
3002   Explain_delete* save_explain_delete_data(MEM_ROOT *mem_root, THD *thd);
3003 };
3004 
3005 enum account_lock_type
3006 {
3007   ACCOUNTLOCK_UNSPECIFIED= 0,
3008   ACCOUNTLOCK_LOCKED,
3009   ACCOUNTLOCK_UNLOCKED
3010 };
3011 
3012 enum password_exp_type
3013 {
3014   PASSWORD_EXPIRE_UNSPECIFIED= 0,
3015   PASSWORD_EXPIRE_NOW,
3016   PASSWORD_EXPIRE_NEVER,
3017   PASSWORD_EXPIRE_DEFAULT,
3018   PASSWORD_EXPIRE_INTERVAL
3019 };
3020 
3021 struct Account_options: public USER_RESOURCES
3022 {
3023   Account_options() { }
3024 
3025   void reset()
3026   {
3027     bzero(this, sizeof(*this));
3028     ssl_type= SSL_TYPE_NOT_SPECIFIED;
3029   }
3030 
3031   enum SSL_type ssl_type;                       // defined in violite.h
3032   LEX_CSTRING x509_subject, x509_issuer, ssl_cipher;
3033   account_lock_type account_locked;
3034   password_exp_type password_expire;
3035   longlong num_expiration_days;
3036 };
3037 
3038 class Query_arena_memroot;
3039 /* The state of the lex parsing. This is saved in the THD struct */
3040 
3041 
3042 class Lex_prepared_stmt
3043 {
3044   Lex_ident_sys m_name; // Statement name (in all queries)
3045   Item *m_code;         // PREPARE or EXECUTE IMMEDIATE source expression
3046   List<Item> m_params;  // List of parameters for EXECUTE [IMMEDIATE]
3047 public:
3048 
3049   Lex_prepared_stmt()
3050    :m_code(NULL)
3051   { }
3052   const Lex_ident_sys &name() const
3053   {
3054     return m_name;
3055   }
3056   uint param_count() const
3057   {
3058     return m_params.elements;
3059   }
3060   List<Item> &params()
3061   {
3062     return m_params;
3063   }
3064   void set(const Lex_ident_sys_st &ident, Item *code, List<Item> *params)
3065   {
3066     DBUG_ASSERT(m_params.elements == 0);
3067     m_name= ident;
3068     m_code= code;
3069     if (params)
3070       m_params= *params;
3071   }
3072   bool params_fix_fields(THD *thd)
3073   {
3074     // Fix Items in the EXECUTE..USING list
3075     List_iterator_fast<Item> param_it(m_params);
3076     while (Item *param= param_it++)
3077     {
3078       if (param->fix_fields_if_needed_for_scalar(thd, 0))
3079         return true;
3080     }
3081     return false;
3082   }
3083   bool get_dynamic_sql_string(THD *thd, LEX_CSTRING *dst, String *buffer);
3084   void lex_start()
3085   {
3086     m_params.empty();
3087   }
3088 };
3089 
3090 
3091 struct LEX: public Query_tables_list
3092 {
3093   SELECT_LEX_UNIT unit;                         /* most upper unit */
3094   SELECT_LEX *first_select_lex() { return unit.first_select(); }
3095   const SELECT_LEX *first_select_lex() const { return unit.first_select(); }
3096 
3097 private:
3098   SELECT_LEX builtin_select;
3099   /* current SELECT_LEX in parsing */
3100 
3101 public:
3102   SELECT_LEX *current_select;
3103   /* list of all SELECT_LEX */
3104   SELECT_LEX *all_selects_list;
3105   /* current with clause in parsing if any, otherwise 0*/
3106   With_clause *curr_with_clause;
3107   /* pointer to the first with clause in the current statement */
3108   With_clause *with_clauses_list;
3109   /*
3110     (*with_clauses_list_last_next) contains a pointer to the last
3111      with clause in the current statement
3112   */
3113   With_clause **with_clauses_list_last_next;
3114   /*
3115     When a copy of a with element is parsed this is set to the offset of
3116     the with element in the input string, otherwise it's set to 0
3117   */
3118   my_ptrdiff_t clone_spec_offset;
3119 
3120   Create_view_info *create_view;
3121 
3122   /* Query Plan Footprint of a currently running select  */
3123   Explain_query *explain;
3124 
3125   // type information
3126   CHARSET_INFO *charset;
3127   /*
3128     LEX which represents current statement (conventional, SP or PS)
3129 
3130     For example during view parsing THD::lex will point to the views LEX and
3131     lex::stmt_lex will point to LEX of the statement where the view will be
3132     included
3133 
3134     Currently it is used to have always correct select numbering inside
3135     statement (LEX::current_select_number) without storing and restoring a
3136     global counter which was THD::select_number.
3137 
3138     TODO: make some unified statement representation (now SP has different)
3139     to store such data like LEX::current_select_number.
3140   */
3141   LEX *stmt_lex;
3142 
3143   LEX_CSTRING name;
3144   const char *help_arg;
3145   const char *backup_dir;                       /* For RESTORE/BACKUP */
3146   const char* to_log;                           /* For PURGE MASTER LOGS TO */
3147   String *wild; /* Wildcard in SHOW {something} LIKE 'wild'*/
3148   sql_exchange *exchange;
3149   select_result *result;
3150   /**
3151     @c the two may also hold BINLOG arguments: either comment holds a
3152     base64-char string or both represent the BINLOG fragment user variables.
3153   */
3154   LEX_CSTRING comment, ident;
3155   LEX_USER *grant_user;
3156   XID *xid;
3157   THD *thd;
3158 
3159   /* maintain a list of used plugins for this LEX */
3160   DYNAMIC_ARRAY plugins;
3161   plugin_ref plugins_static_buffer[INITIAL_LEX_PLUGIN_LIST_SIZE];
3162 
3163   /** SELECT of CREATE VIEW statement */
3164   LEX_STRING create_view_select;
3165 
3166   uint current_select_number; // valid for statment LEX (not view)
3167 
3168   /** Start of 'ON table', in trigger statements.  */
3169   const char* raw_trg_on_table_name_begin;
3170   /** End of 'ON table', in trigger statements. */
3171   const char* raw_trg_on_table_name_end;
3172 
3173   /* Partition info structure filled in by PARTITION BY parse part */
3174   partition_info *part_info;
3175 
3176   /*
3177     The definer of the object being created (view, trigger, stored routine).
3178     I.e. the value of DEFINER clause.
3179   */
3180   LEX_USER *definer;
3181 
3182   /* Used in ALTER/CREATE user to store account locking options */
3183   Account_options account_options;
3184 
3185   Table_type table_type;                        /* Used for SHOW CREATE */
3186   List<Key_part_spec> ref_list;
3187   List<LEX_USER>      users_list;
3188   List<LEX_COLUMN>    columns;
3189   List<Item>          *insert_list,field_list,value_list,update_list;
3190   List<List_item>     many_values;
3191   List<set_var_base>  var_list;
3192   List<set_var_base>  stmt_var_list; //SET_STATEMENT values
3193   List<set_var_base>  old_var_list; // SET STATEMENT old values
3194 private:
3195   Query_arena_memroot *arena_for_set_stmt;
3196   MEM_ROOT *mem_root_for_set_stmt;
3197   bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
3198                                    class sp_label **splabel);
3199   bool sp_change_context(THD *thd, const sp_pcontext *ctx, bool exclusive);
3200   bool sp_exit_block(THD *thd, sp_label *lab);
3201   bool sp_exit_block(THD *thd, sp_label *lab, Item *when);
3202 
3203   bool sp_continue_loop(THD *thd, sp_label *lab);
3204   bool sp_continue_loop(THD *thd, sp_label *lab, Item *when);
3205 
3206   bool sp_for_loop_condition(THD *thd, const Lex_for_loop_st &loop);
3207   bool sp_for_loop_increment(THD *thd, const Lex_for_loop_st &loop);
3208 
3209   /*
3210     Check if Item_field and Item_ref are allowed in the current statement.
3211     @retval false OK (fields are allowed)
3212     @retval true  ERROR (fields are not allowed). Error is raised.
3213   */
3214   bool check_expr_allows_fields_or_error(THD *thd, const char *name) const;
3215 public:
3216   void parse_error(uint err_number= ER_SYNTAX_ERROR);
3217   inline bool is_arena_for_set_stmt() {return arena_for_set_stmt != 0;}
3218   bool set_arena_for_set_stmt(Query_arena *backup);
3219   void reset_arena_for_set_stmt(Query_arena *backup);
3220   void free_arena_for_set_stmt();
3221 
3222   List<Item_func_set_user_var> set_var_list; // in-query assignment list
3223   List<Item_param>    param_list;
3224   List<LEX_CSTRING>   view_list; // view list (list of field names in view)
3225   List<LEX_CSTRING>   with_column_list; // list of column names in with_list_element
3226   List<LEX_STRING>   *column_list; // list of column names (in ANALYZE)
3227   List<LEX_STRING>   *index_list;  // list of index names (in ANALYZE)
3228   /*
3229     A stack of name resolution contexts for the query. This stack is used
3230     at parse time to set local name resolution contexts for various parts
3231     of a query. For example, in a JOIN ... ON (some_condition) clause the
3232     Items in 'some_condition' must be resolved only against the operands
3233     of the the join, and not against the whole clause. Similarly, Items in
3234     subqueries should be resolved against the subqueries (and outer queries).
3235     The stack is used in the following way: when the parser detects that
3236     all Items in some clause need a local context, it creates a new context
3237     and pushes it on the stack. All newly created Items always store the
3238     top-most context in the stack. Once the parser leaves the clause that
3239     required a local context, the parser pops the top-most context.
3240   */
3241   List<Name_resolution_context> context_stack;
3242   SELECT_LEX *select_stack[MAX_SELECT_NESTING + 1];
3243   uint select_stack_top;
3244 
3245   SQL_I_List<ORDER> proc_list;
3246   SQL_I_List<TABLE_LIST> auxiliary_table_list, save_list;
3247   Column_definition *last_field;
3248   Item_sum *in_sum_func;
3249   udf_func udf;
3250   HA_CHECK_OPT   check_opt;                        // check/repair options
3251   Table_specification_st create_info;
3252   Key *last_key;
3253   LEX_MASTER_INFO mi;                              // used by CHANGE MASTER
3254   LEX_SERVER_OPTIONS server_options;
3255   LEX_CSTRING relay_log_connection_name;
3256   LEX_RESET_SLAVE reset_slave_info;
3257   ulonglong type;
3258   ulong next_binlog_file_number;
3259   /* The following is used by KILL */
3260   killed_state kill_signal;
3261   killed_type  kill_type;
3262   bool is_shutdown_wait_for_slaves;
3263   /*
3264     This variable is used in post-parse stage to declare that sum-functions,
3265     or functions which have sense only if GROUP BY is present, are allowed.
3266     For example in a query
3267     SELECT ... FROM ...WHERE MIN(i) == 1 GROUP BY ... HAVING MIN(i) > 2
3268     MIN(i) in the WHERE clause is not allowed in the opposite to MIN(i)
3269     in the HAVING clause. Due to possible nesting of select construct
3270     the variable can contain 0 or 1 for each nest level.
3271   */
3272   nesting_map allow_sum_func;
3273 
3274   Sql_cmd *m_sql_cmd;
3275 
3276   /*
3277     Usually `expr` rule of yacc is quite reused but some commands better
3278     not support subqueries which comes standard with this rule, like
3279     KILL, HA_READ, CREATE/ALTER EVENT etc. Set this to a non-NULL
3280     clause name to get an error.
3281   */
3282   const char *clause_that_disallows_subselect;
3283   bool selects_allow_into;
3284   bool selects_allow_procedure;
3285   /*
3286     A special command "PARSE_VCOL_EXPR" is defined for the parser
3287     to translate a defining expression of a virtual column into an
3288     Item object.
3289     The following flag is used to prevent other applications to use
3290     this command.
3291   */
3292   bool parse_vcol_expr;
3293 
3294   enum enum_duplicates duplicates;
3295   enum enum_tx_isolation tx_isolation;
3296   enum enum_ha_read_modes ha_read_mode;
3297   union {
3298     enum ha_rkey_function ha_rkey_mode;
3299     enum xa_option_words xa_opt;
3300     bool with_admin_option;                     // GRANT role
3301     bool with_persistent_for_clause; // uses PERSISTENT FOR clause (in ANALYZE)
3302   };
3303   enum enum_var_type option_type;
3304   enum enum_drop_mode drop_mode;
3305 
3306   uint profile_query_id;
3307   uint profile_options;
3308   uint grant, grant_tot_col, which_columns;
3309   enum backup_stages backup_stage;
3310   enum Foreign_key::fk_match_opt fk_match_option;
3311   enum_fk_option fk_update_opt;
3312   enum_fk_option fk_delete_opt;
3313   uint slave_thd_opt, start_transaction_opt;
3314   int nest_level;
3315   /*
3316     In LEX representing update which were transformed to multi-update
3317     stores total number of tables. For LEX representing multi-delete
3318     holds number of tables from which we will delete records.
3319   */
3320   uint table_count;
3321   uint8 describe;
3322   bool  analyze_stmt; /* TRUE<=> this is "ANALYZE $stmt" */
3323   bool  explain_json;
3324   /*
3325     A flag that indicates what kinds of derived tables are present in the
3326     query (0 if no derived tables, otherwise a combination of flags
3327     DERIVED_SUBQUERY and DERIVED_VIEW).
3328   */
3329   uint8 derived_tables;
3330   uint8 context_analysis_only;
3331   /*
3332     true <=> The parsed fragment requires resolution of references to CTE
3333     at the end of parsing. This name resolution process involves searching
3334     for possible dependencies between CTE defined in the parsed fragment and
3335     detecting possible recursive references.
3336     The flag is set to true if the fragment contains CTE definitions.
3337   */
3338   bool with_cte_resolution;
3339   /*
3340     true <=> only resolution of references to CTE are required in the parsed
3341     fragment, no checking of dependencies between CTE is required.
3342     This flag is used only when parsing clones of CTE specifications.
3343   */
3344   bool only_cte_resolution;
3345   bool local_file;
3346   bool check_exists;
3347   bool autocommit;
3348   bool verbose, no_write_to_binlog;
3349 
3350   enum enum_yes_no_unknown tx_chain, tx_release;
3351   bool safe_to_cache_query;
3352   bool ignore;
3353   bool next_is_main; // use "main" SELECT_LEX for nrxt allocation;
3354   bool next_is_down; // use "main" SELECT_LEX for nrxt allocation;
3355   st_parsing_options parsing_options;
3356   uint8 lex_options; // see OPTION_LEX_*
3357   /*
3358     In sql_cache we store SQL_CACHE flag as specified by user to be
3359     able to restore SELECT statement from internal structures.
3360   */
3361   enum e_sql_cache { SQL_CACHE_UNSPECIFIED, SQL_NO_CACHE, SQL_CACHE };
3362   e_sql_cache sql_cache;
3363 
3364   Alter_info alter_info;
3365   /*
3366     For CREATE TABLE statement last element of table list which is not
3367     part of SELECT or LIKE part (i.e. either element for table we are
3368     creating or last of tables referenced by foreign keys).
3369   */
3370   TABLE_LIST *create_last_non_select_table;
3371   Lex_prepared_stmt prepared_stmt;
3372   sp_head *sphead;
3373   sp_name *spname;
3374   bool sp_lex_in_use;   // Keep track on lex usage in SPs for error handling
3375   bool all_privileges;
3376 
3377   sp_pcontext *spcont;
3378 
3379   st_sp_chistics sp_chistics;
3380 
3381   Event_parse_data *event_parse_data;
3382 
3383   /*
3384     field_list was created for view and should be removed before PS/SP
3385     rexecuton
3386   */
3387   bool empty_field_list_on_rset;
3388   /* Characterstics of trigger being created */
3389   st_trg_chistics trg_chistics;
3390   /*
3391     List of all items (Item_trigger_field objects) representing fields in
3392     old/new version of row in trigger. We use this list for checking whenever
3393     all such fields are valid at trigger creation time and for binding these
3394     fields to TABLE object at table open (altough for latter pointer to table
3395     being opened is probably enough).
3396   */
3397   SQL_I_List<Item_trigger_field> trg_table_fields;
3398 
3399   /*
3400     stmt_definition_begin is intended to point to the next word after
3401     DEFINER-clause in the following statements:
3402       - CREATE TRIGGER (points to "TRIGGER");
3403       - CREATE PROCEDURE (points to "PROCEDURE");
3404       - CREATE FUNCTION (points to "FUNCTION" or "AGGREGATE");
3405       - CREATE EVENT (points to "EVENT")
3406 
3407     This pointer is required to add possibly omitted DEFINER-clause to the
3408     DDL-statement before dumping it to the binlog.
3409 
3410     keyword_delayed_begin_offset is the offset to the beginning of the DELAYED
3411     keyword in INSERT DELAYED statement. keyword_delayed_end_offset is the
3412     offset to the character right after the DELAYED keyword.
3413   */
3414   union {
3415     const char *stmt_definition_begin;
3416     uint keyword_delayed_begin_offset;
3417   };
3418 
3419   union {
3420     const char *stmt_definition_end;
3421     uint keyword_delayed_end_offset;
3422   };
3423 
3424   /**
3425     Collects create options for KEY
3426   */
3427   engine_option_value *option_list;
3428 
3429   /**
3430     Helper pointer to the end of the list when parsing options for
3431       LEX::create_info.option_list (for table)
3432       LEX::last_field->option_list (for fields)
3433       LEX::option_list             (for indexes)
3434   */
3435   engine_option_value *option_list_last;
3436 
3437   /**
3438     During name resolution search only in the table list given by
3439     Name_resolution_context::first_name_resolution_table and
3440     Name_resolution_context::last_name_resolution_table
3441     (see Item_field::fix_fields()).
3442   */
3443   bool use_only_table_context;
3444 
3445   /*
3446     Reference to a struct that contains information in various commands
3447     to add/create/drop/change table spaces.
3448   */
3449   st_alter_tablespace *alter_tablespace_info;
3450 
3451   bool escape_used;
3452   bool default_used;    /* using default() function */
3453   bool is_lex_started; /* If lex_start() did run. For debugging. */
3454 
3455   /*
3456     The set of those tables whose fields are referenced in all subqueries
3457     of the query.
3458     TODO: possibly this it is incorrect to have used tables in LEX because
3459     with subquery, it is not clear what does the field mean. To fix this
3460     we should aggregate used tables information for selected expressions
3461     into the select_lex.
3462   */
3463   table_map  used_tables;
3464   /**
3465     Maximum number of rows and/or keys examined by the query, both read,
3466     changed or written. This is the argument of LIMIT ROWS EXAMINED.
3467     The limit is represented by two variables - the Item is needed because
3468     in case of parameters we have to delay its evaluation until execution.
3469     Once evaluated, its value is stored in examined_rows_limit_cnt.
3470   */
3471   Item *limit_rows_examined;
3472   ulonglong limit_rows_examined_cnt;
3473   /**
3474     Holds a set of domain_ids for deletion at FLUSH..DELETE_DOMAIN_ID
3475   */
3476   DYNAMIC_ARRAY delete_gtid_domain;
3477   static const ulong initial_gtid_domain_buffer_size= 16;
3478   uint32 gtid_domain_static_buffer[initial_gtid_domain_buffer_size];
3479 
3480   inline void set_limit_rows_examined()
3481   {
3482     if (limit_rows_examined)
3483       limit_rows_examined_cnt= limit_rows_examined->val_uint();
3484     else
3485       limit_rows_examined_cnt= ULONGLONG_MAX;
3486   }
3487 
3488 
3489   SQL_I_List<ORDER> save_group_list;
3490   SQL_I_List<ORDER> save_order_list;
3491   LEX_CSTRING *win_ref;
3492   Window_frame *win_frame;
3493   Window_frame_bound *frame_top_bound;
3494   Window_frame_bound *frame_bottom_bound;
3495   Window_spec *win_spec;
3496 
3497   /* System Versioning */
3498   vers_select_conds_t vers_conditions;
3499   vers_select_conds_t period_conditions;
3500 
3501   inline void free_set_stmt_mem_root()
3502   {
3503     DBUG_ASSERT(!is_arena_for_set_stmt());
3504     if (mem_root_for_set_stmt)
3505     {
3506       free_root(mem_root_for_set_stmt, MYF(0));
3507       delete mem_root_for_set_stmt;
3508       mem_root_for_set_stmt= 0;
3509     }
3510   }
3511 
3512   LEX();
3513 
3514   virtual ~LEX()
3515   {
3516     free_set_stmt_mem_root();
3517     destroy_query_tables_list();
3518     plugin_unlock_list(NULL, (plugin_ref *)plugins.buffer, plugins.elements);
3519     delete_dynamic(&plugins);
3520   }
3521 
3522   virtual class Query_arena *query_arena()
3523   {
3524     DBUG_ASSERT(0);
3525     return NULL;
3526   }
3527 
3528   void start(THD *thd);
3529 
3530   inline bool is_ps_or_view_context_analysis()
3531   {
3532     return (context_analysis_only &
3533             (CONTEXT_ANALYSIS_ONLY_PREPARE |
3534              CONTEXT_ANALYSIS_ONLY_VCOL_EXPR |
3535              CONTEXT_ANALYSIS_ONLY_VIEW));
3536   }
3537 
3538   inline bool is_view_context_analysis()
3539   {
3540     return (context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW);
3541   }
3542 
3543   inline void uncacheable(uint8 cause)
3544   {
3545     safe_to_cache_query= 0;
3546 
3547     if (current_select) // initialisation SP variables has no SELECT
3548     {
3549       /*
3550         There are no sense to mark select_lex and union fields of LEX,
3551         but we should merk all subselects as uncacheable from current till
3552         most upper
3553       */
3554       SELECT_LEX *sl;
3555       SELECT_LEX_UNIT *un;
3556       for (sl= current_select, un= sl->master_unit();
3557            un && un != &unit;
3558            sl= sl->outer_select(), un= (sl ? sl->master_unit() : NULL))
3559       {
3560        sl->uncacheable|= cause;
3561        un->uncacheable|= cause;
3562       }
3563       if (sl)
3564         sl->uncacheable|= cause;
3565     }
3566     if (first_select_lex())
3567       first_select_lex()->uncacheable|= cause;
3568   }
3569   void set_trg_event_type_for_tables();
3570 
3571   TABLE_LIST *unlink_first_table(bool *link_to_local);
3572   void link_first_table_back(TABLE_LIST *first, bool link_to_local);
3573   void first_lists_tables_same();
3574   void fix_first_select_number();
3575 
3576   bool can_be_merged();
3577   bool can_use_merged();
3578   bool can_not_use_merged();
3579   bool only_view_structure();
3580   bool need_correct_ident();
3581   uint8 get_effective_with_check(TABLE_LIST *view);
3582   /*
3583     Is this update command where 'WHITH CHECK OPTION' clause is important
3584 
3585     SYNOPSIS
3586       LEX::which_check_option_applicable()
3587 
3588     RETURN
3589       TRUE   have to take 'WHITH CHECK OPTION' clause into account
3590       FALSE  'WHITH CHECK OPTION' clause do not need
3591   */
3592   inline bool which_check_option_applicable()
3593   {
3594     switch (sql_command) {
3595     case SQLCOM_UPDATE:
3596     case SQLCOM_UPDATE_MULTI:
3597     case SQLCOM_DELETE:
3598     case SQLCOM_DELETE_MULTI:
3599     case SQLCOM_INSERT:
3600     case SQLCOM_INSERT_SELECT:
3601     case SQLCOM_REPLACE:
3602     case SQLCOM_REPLACE_SELECT:
3603     case SQLCOM_LOAD:
3604       return TRUE;
3605     default:
3606       return FALSE;
3607     }
3608   }
3609 
3610   void cleanup_after_one_table_open();
3611 
3612   bool push_context(Name_resolution_context *context);
3613 
3614   Name_resolution_context *pop_context();
3615 
3616   SELECT_LEX *select_stack_head()
3617   {
3618     if (likely(select_stack_top))
3619       return select_stack[select_stack_top - 1];
3620     return NULL;
3621   }
3622 
3623   bool push_select(SELECT_LEX *select_lex)
3624   {
3625     DBUG_ENTER("LEX::push_select");
3626     DBUG_PRINT("info", ("Top Select was %p (%d)  depth: %u  pushed: %p (%d)",
3627                         select_stack_head(),
3628                         select_stack_top,
3629                         (select_stack_top ?
3630                          select_stack_head()->select_number :
3631                          0),
3632                         select_lex, select_lex->select_number));
3633     if (unlikely(select_stack_top > MAX_SELECT_NESTING))
3634     {
3635       my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT, MYF(0));
3636       DBUG_RETURN(TRUE);
3637     }
3638     if (push_context(&select_lex->context))
3639       DBUG_RETURN(TRUE);
3640     select_stack[select_stack_top++]= select_lex;
3641     current_select= select_lex;
3642     DBUG_RETURN(FALSE);
3643   }
3644 
3645   SELECT_LEX *pop_select()
3646   {
3647     DBUG_ENTER("LEX::pop_select");
3648     SELECT_LEX *select_lex;
3649     if (likely(select_stack_top))
3650       select_lex= select_stack[--select_stack_top];
3651     else
3652       select_lex= 0;
3653     DBUG_PRINT("info", ("Top Select is %p (%d)  depth: %u  poped: %p (%d)",
3654                         select_stack_head(),
3655                         select_stack_top,
3656                         (select_stack_top ?
3657                          select_stack_head()->select_number :
3658                          0),
3659                         select_lex,
3660                         (select_lex ? select_lex->select_number : 0)));
3661     DBUG_ASSERT(select_lex);
3662 
3663     pop_context();
3664 
3665     if (unlikely(!select_stack_top))
3666     {
3667       current_select= &builtin_select;
3668       DBUG_PRINT("info", ("Top Select is empty -> sel builtin: %p",
3669                           current_select));
3670     }
3671     else
3672       current_select= select_stack[select_stack_top - 1];
3673 
3674     DBUG_RETURN(select_lex);
3675   }
3676 
3677   SELECT_LEX *current_select_or_default()
3678   {
3679     return current_select ? current_select : &builtin_select;
3680   }
3681 
3682   bool copy_db_to(LEX_CSTRING *to);
3683 
3684   Name_resolution_context *current_context()
3685   {
3686     return context_stack.head();
3687   }
3688 
3689   /*
3690     Restore the LEX and THD in case of a parse error.
3691   */
3692   static void cleanup_lex_after_parse_error(THD *thd);
3693 
3694   void reset_n_backup_query_tables_list(Query_tables_list *backup);
3695   void restore_backup_query_tables_list(Query_tables_list *backup);
3696 
3697   bool table_or_sp_used();
3698 
3699   bool is_partition_management() const;
3700   bool part_values_current(THD *thd);
3701   bool part_values_history(THD *thd);
3702 
3703   /**
3704     @brief check if the statement is a single-level join
3705     @return result of the check
3706       @retval TRUE  The statement doesn't contain subqueries, unions and
3707                     stored procedure calls.
3708       @retval FALSE There are subqueries, UNIONs or stored procedure calls.
3709   */
3710   bool is_single_level_stmt()
3711   {
3712     /*
3713       This check exploits the fact that the last added to all_select_list is
3714       on its top. So select_lex (as the first added) will be at the tail
3715       of the list.
3716     */
3717     if (first_select_lex() == all_selects_list && !sroutines.records)
3718     {
3719       return TRUE;
3720     }
3721     return FALSE;
3722   }
3723 
3724   bool save_prep_leaf_tables();
3725 
3726   int print_explain(select_result_sink *output, uint8 explain_flags,
3727                     bool is_analyze, bool *printed_anything);
3728   bool restore_set_statement_var();
3729 
3730   void init_last_field(Column_definition *field, const LEX_CSTRING *name,
3731                        const CHARSET_INFO *cs);
3732   bool last_field_generated_always_as_row_start_or_end(Lex_ident *p,
3733                                                        const char *type,
3734                                                        uint flags);
3735   bool last_field_generated_always_as_row_start();
3736   bool last_field_generated_always_as_row_end();
3737   bool set_bincmp(CHARSET_INFO *cs, bool bin);
3738 
3739   bool new_sp_instr_stmt(THD *, const LEX_CSTRING &prefix,
3740                          const LEX_CSTRING &suffix);
3741   bool sp_proc_stmt_statement_finalize_buf(THD *, const LEX_CSTRING &qbuf);
3742   bool sp_proc_stmt_statement_finalize(THD *, bool no_lookahead);
3743 
3744   sp_variable *sp_param_init(LEX_CSTRING *name);
3745   bool sp_param_fill_definition(sp_variable *spvar);
3746 
3747   int case_stmt_action_expr(Item* expr);
3748   int case_stmt_action_when(Item *when, bool simple);
3749   int case_stmt_action_then();
3750   bool setup_select_in_parentheses();
3751   bool set_trigger_new_row(const LEX_CSTRING *name, Item *val);
3752   bool set_trigger_field(const LEX_CSTRING *name1, const LEX_CSTRING *name2,
3753                          Item *val);
3754   bool set_system_variable(enum_var_type var_type, sys_var *var,
3755                            const LEX_CSTRING *base_name, Item *val);
3756   bool set_system_variable(enum_var_type var_type, const LEX_CSTRING *name,
3757                            Item *val);
3758   bool set_system_variable(THD *thd, enum_var_type var_type,
3759                            const LEX_CSTRING *name1,
3760                            const LEX_CSTRING *name2,
3761                            Item *val);
3762   bool set_default_system_variable(enum_var_type var_type,
3763                                    const LEX_CSTRING *name,
3764                                    Item *val);
3765   bool set_user_variable(THD *thd, const LEX_CSTRING *name, Item *val);
3766   void set_stmt_init();
3767   sp_name *make_sp_name(THD *thd, const LEX_CSTRING *name);
3768   sp_name *make_sp_name(THD *thd, const LEX_CSTRING *name1,
3769                                   const LEX_CSTRING *name2);
3770   sp_name *make_sp_name_package_routine(THD *thd, const LEX_CSTRING *name);
3771   sp_head *make_sp_head(THD *thd, const sp_name *name, const Sp_handler *sph,
3772                         enum_sp_aggregate_type agg_type);
3773   sp_head *make_sp_head_no_recursive(THD *thd, const sp_name *name,
3774                                      const Sp_handler *sph,
3775                                      enum_sp_aggregate_type agg_type);
3776   bool sp_body_finalize_routine(THD *);
3777   bool sp_body_finalize_trigger(THD *);
3778   bool sp_body_finalize_event(THD *);
3779   bool sp_body_finalize_function(THD *);
3780   bool sp_body_finalize_procedure(THD *);
3781   bool sp_body_finalize_procedure_standalone(THD *, const sp_name *end_name);
3782   sp_package *create_package_start(THD *thd,
3783                                    enum_sql_command command,
3784                                    const Sp_handler *sph,
3785                                    const sp_name *name,
3786                                    DDL_options_st options);
3787   bool create_package_finalize(THD *thd,
3788                                const sp_name *name,
3789                                const sp_name *name2,
3790                                const char *body_start,
3791                                const char *body_end);
3792   bool call_statement_start(THD *thd, sp_name *name);
3793   bool call_statement_start(THD *thd, const LEX_CSTRING *name);
3794   bool call_statement_start(THD *thd, const LEX_CSTRING *name1,
3795                                       const LEX_CSTRING *name2);
3796   sp_variable *find_variable(const LEX_CSTRING *name,
3797                              sp_pcontext **ctx,
3798                              const Sp_rcontext_handler **rh) const;
3799   sp_variable *find_variable(const LEX_CSTRING *name,
3800                              const Sp_rcontext_handler **rh) const
3801   {
3802     sp_pcontext *not_used_ctx;
3803     return find_variable(name, &not_used_ctx, rh);
3804   }
3805   bool set_variable(const LEX_CSTRING *name, Item *item);
3806   bool set_variable(const LEX_CSTRING *name1, const LEX_CSTRING *name2,
3807                     Item *item);
3808   void sp_variable_declarations_init(THD *thd, int nvars);
3809   bool sp_variable_declarations_finalize(THD *thd, int nvars,
3810                                          const Column_definition *cdef,
3811                                          Item *def);
3812   bool sp_variable_declarations_set_default(THD *thd, int nvars, Item *def);
3813   bool sp_variable_declarations_row_finalize(THD *thd, int nvars,
3814                                              Row_definition_list *row,
3815                                              Item *def);
3816   bool sp_variable_declarations_with_ref_finalize(THD *thd, int nvars,
3817                                                   Qualified_column_ident *col,
3818                                                   Item *def);
3819   bool sp_variable_declarations_rowtype_finalize(THD *thd, int nvars,
3820                                                  Qualified_column_ident *,
3821                                                  Item *def);
3822   bool sp_variable_declarations_cursor_rowtype_finalize(THD *thd, int nvars,
3823                                                         uint offset,
3824                                                         Item *def);
3825   bool sp_variable_declarations_table_rowtype_finalize(THD *thd, int nvars,
3826                                                        const LEX_CSTRING &db,
3827                                                        const LEX_CSTRING &table,
3828                                                        Item *def);
3829   bool sp_variable_declarations_column_type_finalize(THD *thd, int nvars,
3830                                                      Qualified_column_ident *ref,
3831                                                      Item *def);
3832   bool sp_variable_declarations_vartype_finalize(THD *thd, int nvars,
3833                                                  const LEX_CSTRING &name,
3834                                                  Item *def);
3835   bool sp_variable_declarations_copy_type_finalize(THD *thd, int nvars,
3836                                                    const Column_definition &ref,
3837                                                    Row_definition_list *fields,
3838                                                    Item *def);
3839   bool sp_handler_declaration_init(THD *thd, int type);
3840   bool sp_handler_declaration_finalize(THD *thd, int type);
3841 
3842   bool sp_declare_cursor(THD *thd, const LEX_CSTRING *name,
3843                          class sp_lex_cursor *cursor_stmt,
3844                          sp_pcontext *param_ctx, bool add_cpush_instr);
3845 
3846   bool sp_open_cursor(THD *thd, const LEX_CSTRING *name,
3847                       List<sp_assignment_lex> *parameters);
3848   Item_splocal *create_item_for_sp_var(const Lex_ident_cli_st *name,
3849                                        sp_variable *spvar);
3850 
3851   Item *create_item_qualified_asterisk(THD *thd, const Lex_ident_sys_st *name);
3852   Item *create_item_qualified_asterisk(THD *thd,
3853                                        const Lex_ident_sys_st *a,
3854                                        const Lex_ident_sys_st *b);
3855   Item *create_item_qualified_asterisk(THD *thd, const Lex_ident_cli_st *cname)
3856   {
3857     Lex_ident_sys name(thd, cname);
3858     if (name.is_null())
3859       return NULL; // EOM
3860     return create_item_qualified_asterisk(thd, &name);
3861   }
3862   Item *create_item_qualified_asterisk(THD *thd,
3863                                        const Lex_ident_cli_st *ca,
3864                                        const Lex_ident_cli_st *cb)
3865   {
3866     Lex_ident_sys a(thd, ca), b(thd, cb);
3867     if (a.is_null() || b.is_null())
3868       return NULL; // EOM
3869     return create_item_qualified_asterisk(thd, &a, &b);
3870   }
3871 
3872   Item *create_item_ident_field(THD *thd, const char *db, const char *table,
3873                                 const Lex_ident_sys_st *name);
3874   Item *create_item_ident_nosp(THD *thd, Lex_ident_sys_st *name)
3875   {
3876     return create_item_ident_field(thd, NullS, NullS, name);
3877   }
3878   Item *create_item_ident_sp(THD *thd, Lex_ident_sys_st *name,
3879                              const char *start, const char *end);
3880   Item *create_item_ident(THD *thd, Lex_ident_cli_st *cname)
3881   {
3882     Lex_ident_sys name(thd, cname);
3883     if (name.is_null())
3884       return NULL; // EOM
3885     return sphead ?
3886            create_item_ident_sp(thd, &name, cname->pos(), cname->end()) :
3887            create_item_ident_nosp(thd, &name);
3888   }
3889   /*
3890     Create an Item corresponding to a qualified name: a.b
3891     when the parser is out of an SP context.
3892       @param THD        - THD, for mem_root
3893       @param a          - the first name
3894       @param b          - the second name
3895       @retval           - a pointer to a created item, or NULL on error.
3896 
3897     Possible Item types that can be created:
3898     - Item_trigger_field
3899     - Item_field
3900     - Item_ref
3901   */
3902   Item *create_item_ident_nospvar(THD *thd,
3903                                   const Lex_ident_sys_st *a,
3904                                   const Lex_ident_sys_st *b);
3905   /*
3906     Create an Item corresponding to a ROW field valiable:  var.field
3907       @param THD        - THD, for mem_root
3908       @param rh [OUT]   - the rcontext handler (local vs package variables)
3909       @param var        - the ROW variable name
3910       @param field      - the ROW variable field name
3911       @param spvar      - the variable that was previously found by name
3912                           using "var_name".
3913       @param start      - position in the query (for binary log)
3914       @param end        - end in the query (for binary log)
3915   */
3916   Item_splocal *create_item_spvar_row_field(THD *thd,
3917                                             const Sp_rcontext_handler *rh,
3918                                             const Lex_ident_sys *var,
3919                                             const Lex_ident_sys *field,
3920                                             sp_variable *spvar,
3921                                             const char *start,
3922                                             const char *end);
3923   /*
3924     Create an item from its qualified name.
3925     Depending on context, it can be either a ROW variable field,
3926     or trigger, table field, table field reference.
3927     See comments to create_item_spvar_row_field() and
3928     create_item_ident_nospvar().
3929       @param thd         - THD, for mem_root
3930       @param a           - the first name
3931       @param b           - the second name
3932       @retval            - NULL on error, or a pointer to a new Item.
3933   */
3934   Item *create_item_ident(THD *thd,
3935                           const Lex_ident_cli_st *a,
3936                           const Lex_ident_cli_st *b);
3937   /*
3938     Create an item from its qualified name.
3939     Depending on context, it can be a table field, a table field reference,
3940     or a sequence NEXTVAL and CURRVAL.
3941       @param thd         - THD, for mem_root
3942       @param a           - the first name
3943       @param b           - the second name
3944       @param c           - the third name
3945       @retval            - NULL on error, or a pointer to a new Item.
3946   */
3947   Item *create_item_ident(THD *thd,
3948                           const Lex_ident_sys_st *a,
3949                           const Lex_ident_sys_st *b,
3950                           const Lex_ident_sys_st *c);
3951 
3952   Item *create_item_ident(THD *thd,
3953                           const Lex_ident_cli_st *ca,
3954                           const Lex_ident_cli_st *cb,
3955                           const Lex_ident_cli_st *cc)
3956   {
3957     Lex_ident_sys b(thd, cb), c(thd, cc);
3958     if (b.is_null() || c.is_null())
3959       return NULL;
3960     if (ca->pos() == cb->pos())  // SELECT .t1.col1
3961     {
3962       DBUG_ASSERT(ca->length == 0);
3963       Lex_ident_sys none;
3964       return create_item_ident(thd, &none, &b, &c);
3965     }
3966     Lex_ident_sys a(thd, ca);
3967     return a.is_null() ? NULL : create_item_ident(thd, &a, &b, &c);
3968   }
3969 
3970   /*
3971     Create an item for "NEXT VALUE FOR sequence_name"
3972   */
3973   Item *create_item_func_nextval(THD *thd, Table_ident *ident);
3974   Item *create_item_func_nextval(THD *thd, const LEX_CSTRING *db,
3975                                            const LEX_CSTRING *name);
3976   /*
3977     Create an item for "PREVIOUS VALUE FOR sequence_name"
3978   */
3979   Item *create_item_func_lastval(THD *thd, Table_ident *ident);
3980   Item *create_item_func_lastval(THD *thd, const LEX_CSTRING *db,
3981                                            const LEX_CSTRING *name);
3982 
3983   /*
3984     Create an item for "SETVAL(sequence_name, value [, is_used [, round]])
3985   */
3986   Item *create_item_func_setval(THD *thd, Table_ident *ident, longlong value,
3987                                 ulonglong round, bool is_used);
3988 
3989   /*
3990     Create an item for a name in LIMIT clause: LIMIT var
3991       @param THD         - THD, for mem_root
3992       @param var_name    - the variable name
3993       @retval            - a new Item corresponding to the SP variable,
3994                            or NULL on error
3995                            (non in SP, unknown variable, wrong data type).
3996   */
3997   Item *create_item_limit(THD *thd, const Lex_ident_cli_st *var_name);
3998 
3999   /*
4000     Create an item for a qualified name in LIMIT clause: LIMIT var.field
4001       @param THD         - THD, for mem_root
4002       @param var_name    - the variable name
4003       @param field_name  - the variable field name
4004       @param start       - start in the query (for binary log)
4005       @param end         - end in the query (for binary log)
4006       @retval            - a new Item corresponding to the SP variable,
4007                            or NULL on error
4008                            (non in SP, unknown variable, unknown ROW field,
4009                             wrong data type).
4010   */
4011   Item *create_item_limit(THD *thd,
4012                           const Lex_ident_cli_st *var_name,
4013                           const Lex_ident_cli_st *field_name);
4014 
4015   Item *create_item_query_expression(THD *thd, st_select_lex_unit *unit);
4016 
4017   Item *make_item_func_replace(THD *thd, Item *org, Item *find, Item *replace);
4018   Item *make_item_func_substr(THD *thd, Item *a, Item *b, Item *c);
4019   Item *make_item_func_substr(THD *thd, Item *a, Item *b);
4020   Item *make_item_func_call_generic(THD *thd, Lex_ident_cli_st *db,
4021                                     Lex_ident_cli_st *name, List<Item> *args);
4022   my_var *create_outvar(THD *thd, const LEX_CSTRING *name);
4023 
4024   /*
4025     Create a my_var instance for a ROW field variable that was used
4026     as an OUT SP parameter: CALL p1(var.field);
4027       @param THD        - THD, for mem_root
4028       @param var_name   - the variable name
4029       @param field_name - the variable field name
4030   */
4031   my_var *create_outvar(THD *thd,
4032                         const LEX_CSTRING *var_name,
4033                         const LEX_CSTRING *field_name);
4034 
4035   bool is_trigger_new_or_old_reference(const LEX_CSTRING *name) const;
4036 
4037   Item *create_and_link_Item_trigger_field(THD *thd, const LEX_CSTRING *name,
4038                                            bool new_row);
4039   // For syntax with colon, e.g. :NEW.a  or :OLD.a
4040   Item *make_item_colon_ident_ident(THD *thd,
4041                                     const Lex_ident_cli_st *a,
4042                                     const Lex_ident_cli_st *b);
4043   // PLSQL: cursor%ISOPEN etc
4044   Item *make_item_plsql_cursor_attr(THD *thd, const LEX_CSTRING *name,
4045                                     plsql_cursor_attr_t attr);
4046 
4047   // For "SELECT @@var", "SELECT @@var.field"
4048   Item *make_item_sysvar(THD *thd,
4049                          enum_var_type type,
4050                          const LEX_CSTRING *name)
4051   {
4052     return make_item_sysvar(thd, type, name, &null_clex_str);
4053   }
4054   Item *make_item_sysvar(THD *thd,
4055                          enum_var_type type,
4056                          const LEX_CSTRING *name,
4057                          const LEX_CSTRING *component);
4058   void sp_block_init(THD *thd, const LEX_CSTRING *label);
4059   void sp_block_init(THD *thd)
4060   {
4061     // Unlabeled blocks get an empty label
4062     sp_block_init(thd, &empty_clex_str);
4063   }
4064   bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock)
4065   {
4066     class sp_label *tmp;
4067     return sp_block_finalize(thd, spblock, &tmp);
4068   }
4069   bool sp_block_finalize(THD *thd)
4070   {
4071     return sp_block_finalize(thd, Lex_spblock());
4072   }
4073   bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
4074                                    const LEX_CSTRING *end_label);
4075   bool sp_block_finalize(THD *thd, const LEX_CSTRING *end_label)
4076   {
4077     return sp_block_finalize(thd, Lex_spblock(), end_label);
4078   }
4079   bool sp_declarations_join(Lex_spblock_st *res,
4080                             const Lex_spblock_st b1,
4081                             const Lex_spblock_st b2) const
4082   {
4083     if ((b2.vars || b2.conds) && (b1.curs || b1.hndlrs))
4084     {
4085       my_error(ER_SP_VARCOND_AFTER_CURSHNDLR, MYF(0));
4086       return true;
4087     }
4088     if (b2.curs && b1.hndlrs)
4089     {
4090       my_error(ER_SP_CURSOR_AFTER_HANDLER, MYF(0));
4091       return true;
4092     }
4093     res->join(b1, b2);
4094     return false;
4095   }
4096   bool sp_block_with_exceptions_finalize_declarations(THD *thd);
4097   bool sp_block_with_exceptions_finalize_executable_section(THD *thd,
4098                                                   uint executable_section_ip);
4099   bool sp_block_with_exceptions_finalize_exceptions(THD *thd,
4100                                                   uint executable_section_ip,
4101                                                   uint exception_count);
4102   bool sp_block_with_exceptions_add_empty(THD *thd);
4103   bool sp_exit_statement(THD *thd, Item *when);
4104   bool sp_exit_statement(THD *thd, const LEX_CSTRING *label_name, Item *item);
4105   bool sp_leave_statement(THD *thd, const LEX_CSTRING *label_name);
4106   bool sp_goto_statement(THD *thd, const LEX_CSTRING *label_name);
4107 
4108   bool sp_continue_statement(THD *thd, Item *when);
4109   bool sp_continue_statement(THD *thd, const LEX_CSTRING *label_name, Item *when);
4110   bool sp_iterate_statement(THD *thd, const LEX_CSTRING *label_name);
4111 
4112   bool maybe_start_compound_statement(THD *thd);
4113   bool sp_push_loop_label(THD *thd, const LEX_CSTRING *label_name);
4114   bool sp_push_loop_empty_label(THD *thd);
4115   bool sp_pop_loop_label(THD *thd, const LEX_CSTRING *label_name);
4116   void sp_pop_loop_empty_label(THD *thd);
4117   bool sp_while_loop_expression(THD *thd, Item *expr);
4118   bool sp_while_loop_finalize(THD *thd);
4119   bool sp_push_goto_label(THD *thd, const LEX_CSTRING *label_name);
4120 
4121   Item_param *add_placeholder(THD *thd, const LEX_CSTRING *name,
4122                               const char *start, const char *end);
4123 
4124   /* Integer range FOR LOOP methods */
4125   sp_variable *sp_add_for_loop_variable(THD *thd, const LEX_CSTRING *name,
4126                                         Item *value);
4127   sp_variable *sp_add_for_loop_target_bound(THD *thd, Item *value)
4128   {
4129     LEX_CSTRING name= { STRING_WITH_LEN("[target_bound]") };
4130     return sp_add_for_loop_variable(thd, &name, value);
4131   }
4132   bool sp_for_loop_intrange_declarations(THD *thd, Lex_for_loop_st *loop,
4133                                         const LEX_CSTRING *index,
4134                                         const Lex_for_loop_bounds_st &bounds);
4135   bool sp_for_loop_intrange_condition_test(THD *thd, const Lex_for_loop_st &loop);
4136   bool sp_for_loop_intrange_finalize(THD *thd, const Lex_for_loop_st &loop);
4137 
4138   /* Cursor FOR LOOP methods */
4139   bool sp_for_loop_cursor_declarations(THD *thd, Lex_for_loop_st *loop,
4140                                        const LEX_CSTRING *index,
4141                                        const Lex_for_loop_bounds_st &bounds);
4142   sp_variable *sp_add_for_loop_cursor_variable(THD *thd,
4143                                                const LEX_CSTRING *name,
4144                                                const class sp_pcursor *cur,
4145                                                uint coffset,
4146                                                sp_assignment_lex *param_lex,
4147                                                Item_args *parameters);
4148   bool sp_for_loop_implicit_cursor_statement(THD *thd,
4149                                              Lex_for_loop_bounds_st *bounds,
4150                                              sp_lex_cursor *cur);
4151   bool sp_for_loop_cursor_condition_test(THD *thd, const Lex_for_loop_st &loop);
4152   bool sp_for_loop_cursor_finalize(THD *thd, const Lex_for_loop_st &);
4153 
4154   /* Generic FOR LOOP methods*/
4155 
4156   /*
4157     Generate FOR loop declarations and
4158     initialize "loop" from "index" and "bounds".
4159 
4160     @param [IN]  thd    - current THD, for mem_root and error reporting
4161     @param [OUT] loop   - the loop generated SP variables are stored here,
4162                           together with additional loop characteristics.
4163     @param [IN]  index  - the loop index variable name
4164     @param [IN]  bounds - the loop bounds (in sp_assignment_lex format)
4165                           and additional loop characteristics,
4166                           as created by the sp_for_loop_bounds rule.
4167     @retval true        - on error
4168     @retval false       - on success
4169 
4170     This methods adds declarations:
4171     - An explicit integer or cursor%ROWTYPE "index" variable
4172     - An implicit integer upper bound variable, in case of integer range loops
4173     - A CURSOR, in case of an implicit CURSOR loops
4174     The generated variables are stored into "loop".
4175     Additional loop characteristics are copied from "bounds" to "loop".
4176   */
4177   bool sp_for_loop_declarations(THD *thd, Lex_for_loop_st *loop,
4178                                 const LEX_CSTRING *index,
4179                                 const Lex_for_loop_bounds_st &bounds)
4180   {
4181     return bounds.is_for_loop_cursor() ?
4182            sp_for_loop_cursor_declarations(thd, loop, index, bounds) :
4183            sp_for_loop_intrange_declarations(thd, loop, index, bounds);
4184   }
4185 
4186   /*
4187     Generate a conditional jump instruction to leave the loop,
4188     using a proper condition depending on the loop type:
4189     - Item_func_le            -- integer range loops
4190     - Item_func_ge            -- integer range reverse loops
4191     - Item_func_cursor_found  -- cursor loops
4192   */
4193   bool sp_for_loop_condition_test(THD *thd, const Lex_for_loop_st &loop)
4194   {
4195     return loop.is_for_loop_cursor() ?
4196            sp_for_loop_cursor_condition_test(thd, loop) :
4197            sp_for_loop_intrange_condition_test(thd, loop);
4198   }
4199 
4200   /*
4201     Generate "increment" instructions followed by a jump to the
4202     condition test in the beginnig of the loop.
4203     "Increment" depends on the loop type and can be:
4204     - index:= index + 1;       -- integer range loops
4205     - index:= index - 1;       -- integer range reverse loops
4206     - FETCH cursor INTO index; -- cursor loops
4207   */
4208   bool sp_for_loop_finalize(THD *thd, const Lex_for_loop_st &loop)
4209   {
4210     return loop.is_for_loop_cursor() ?
4211            sp_for_loop_cursor_finalize(thd, loop) :
4212            sp_for_loop_intrange_finalize(thd, loop);
4213   }
4214   bool sp_for_loop_outer_block_finalize(THD *thd, const Lex_for_loop_st &loop);
4215 
4216   /*
4217     Make an Item when an identifier is found in the FOR loop bounds:
4218       FOR rec IN cursor
4219       FOR rec IN var1 .. var2
4220       FOR rec IN row1.field1 .. xxx
4221   */
4222   Item *create_item_for_loop_bound(THD *thd,
4223                                    const LEX_CSTRING *a,
4224                                    const LEX_CSTRING *b,
4225                                    const LEX_CSTRING *c);
4226   /* End of FOR LOOP methods */
4227 
4228   bool add_signal_statement(THD *thd, const class sp_condition_value *value);
4229   bool add_resignal_statement(THD *thd, const class sp_condition_value *value);
4230 
4231   // Check if "KEY IF NOT EXISTS name" used outside of ALTER context
4232   bool check_add_key(DDL_options_st ddl)
4233   {
4234     if (ddl.if_not_exists() && sql_command != SQLCOM_ALTER_TABLE)
4235     {
4236       parse_error();
4237       return true;
4238     }
4239     return false;
4240   }
4241   // Add a key as a part of CREATE TABLE or ALTER TABLE
4242   bool add_key(Key::Keytype key_type, const LEX_CSTRING *key_name,
4243                ha_key_alg algorithm, DDL_options_st ddl)
4244   {
4245     if (check_add_key(ddl) ||
4246         !(last_key= new Key(key_type, key_name, algorithm, false, ddl)))
4247       return true;
4248     alter_info.key_list.push_back(last_key);
4249     return false;
4250   }
4251   // Add a key for a CREATE INDEX statement
4252   bool add_create_index(Key::Keytype key_type, const LEX_CSTRING *key_name,
4253                         ha_key_alg algorithm, DDL_options_st ddl)
4254   {
4255     if (check_create_options(ddl) ||
4256        !(last_key= new Key(key_type, key_name, algorithm, false, ddl)))
4257       return true;
4258     alter_info.key_list.push_back(last_key);
4259     return false;
4260   }
4261   bool add_create_index_prepare(Table_ident *table)
4262   {
4263     sql_command= SQLCOM_CREATE_INDEX;
4264     if (!current_select->add_table_to_list(thd, table, NULL,
4265                                            TL_OPTION_UPDATING,
4266                                            TL_READ_NO_INSERT,
4267                                            MDL_SHARED_UPGRADABLE))
4268       return true;
4269     alter_info.reset();
4270     alter_info.flags= ALTER_ADD_INDEX;
4271     option_list= NULL;
4272     return false;
4273   }
4274   /*
4275     Add an UNIQUE or PRIMARY key which is a part of a column definition:
4276       CREATE TABLE t1 (a INT PRIMARY KEY);
4277   */
4278   void add_key_to_list(LEX_CSTRING *field_name,
4279                        enum Key::Keytype type, bool check_exists);
4280   // Add a constraint as a part of CREATE TABLE or ALTER TABLE
4281   bool add_constraint(const LEX_CSTRING &name, Virtual_column_info *constr,
4282                       bool if_not_exists)
4283   {
4284     constr->name= name;
4285     constr->flags= if_not_exists ?
4286                    Alter_info::CHECK_CONSTRAINT_IF_NOT_EXISTS : 0;
4287     alter_info.check_constraint_list.push_back(constr);
4288     return false;
4289   }
4290   bool add_alter_list(const char *par_name, Virtual_column_info *expr,
4291                       bool par_exists);
4292   void set_command(enum_sql_command command,
4293                    DDL_options_st options)
4294   {
4295     sql_command= command;
4296     create_info.set(options);
4297   }
4298   void set_command(enum_sql_command command,
4299                    uint scope,
4300                    DDL_options_st options)
4301   {
4302     set_command(command, options);
4303     create_info.options|= scope; // HA_LEX_CREATE_TMP_TABLE or 0
4304   }
4305   bool check_create_options(DDL_options_st options)
4306   {
4307     if (options.or_replace() && options.if_not_exists())
4308     {
4309       my_error(ER_WRONG_USAGE, MYF(0), "OR REPLACE", "IF NOT EXISTS");
4310       return true;
4311     }
4312     return false;
4313   }
4314   bool set_create_options_with_check(DDL_options_st options)
4315   {
4316     create_info.set(options);
4317     return check_create_options(create_info);
4318   }
4319   bool add_create_options_with_check(DDL_options_st options)
4320   {
4321     create_info.add(options);
4322     return check_create_options(create_info);
4323   }
4324   bool sp_add_cfetch(THD *thd, const LEX_CSTRING *name);
4325   bool sp_add_agg_cfetch();
4326 
4327   bool set_command_with_check(enum_sql_command command,
4328                               uint scope,
4329                               DDL_options_st options)
4330   {
4331     set_command(command, scope, options);
4332     return check_create_options(options);
4333   }
4334   bool set_command_with_check(enum_sql_command command, DDL_options_st options)
4335   {
4336     set_command(command, options);
4337     return check_create_options(options);
4338   }
4339   /*
4340     DROP shares lex->create_info to store TEMPORARY and IF EXISTS options
4341     to save on extra initialization in lex_start().
4342     Add some wrappers, to avoid direct use of lex->create_info in the
4343     caller code processing DROP statements (which might look confusing).
4344   */
4345   bool tmp_table() const { return create_info.tmp_table(); }
4346   bool if_exists() const { return create_info.if_exists(); }
4347 
4348   /*
4349     Run specified phases for derived tables/views in the given list
4350 
4351     @param table_list - list of derived tables/view to handle
4352     @param phase      - phases to process tables/views through
4353 
4354     @details
4355     This method runs phases specified by the 'phases' on derived
4356     tables/views found in the 'table_list' with help of the
4357     TABLE_LIST::handle_derived function.
4358     'this' is passed as an argument to the TABLE_LIST::handle_derived.
4359 
4360     @return false -  ok
4361     @return true  -  error
4362   */
4363   bool handle_list_of_derived(TABLE_LIST *table_list, uint phases)
4364   {
4365     for (TABLE_LIST *tl= table_list; tl; tl= tl->next_local)
4366     {
4367       if (tl->is_view_or_derived() && tl->handle_derived(this, phases))
4368         return true;
4369     }
4370     return false;
4371   }
4372 
4373   bool create_like() const
4374   {
4375     DBUG_ASSERT(!create_info.like() ||
4376                 !first_select_lex()->item_list.elements);
4377     return create_info.like();
4378   }
4379 
4380   bool create_select() const
4381   {
4382     DBUG_ASSERT(!create_info.like() ||
4383                 !first_select_lex()->item_list.elements);
4384     return first_select_lex()->item_list.elements;
4385   }
4386 
4387   bool create_simple() const
4388   {
4389     return !create_like() && !create_select();
4390   }
4391 
4392   SELECT_LEX *exclude_last_select();
4393   SELECT_LEX *exclude_not_first_select(SELECT_LEX *exclude);
4394   void check_automatic_up(enum sub_select_type type);
4395   bool create_or_alter_view_finalize(THD *thd, Table_ident *table_ident);
4396   bool add_alter_view(THD *thd, uint16 algorithm, enum_view_suid suid,
4397                       Table_ident *table_ident);
4398   bool add_create_view(THD *thd, DDL_options_st ddl,
4399                        uint16 algorithm, enum_view_suid suid,
4400                        Table_ident *table_ident);
4401   bool add_grant_command(THD *thd, enum_sql_command sql_command_arg,
4402                          stored_procedure_type type_arg);
4403 
4404   Vers_parse_info &vers_get_info()
4405   {
4406     return create_info.vers_info;
4407   }
4408 
4409   int add_period(Lex_ident name, Lex_ident_sys_st start, Lex_ident_sys_st end)
4410   {
4411     if (lex_string_cmp(system_charset_info, &start, &end) == 0)
4412     {
4413       my_error(ER_FIELD_SPECIFIED_TWICE, MYF(0), start.str);
4414       return 1;
4415     }
4416 
4417     Table_period_info &info= create_info.period_info;
4418 
4419     if (check_exists && info.name.streq(name))
4420       return 0;
4421 
4422     if (info.is_set())
4423     {
4424        my_error(ER_MORE_THAN_ONE_PERIOD, MYF(0));
4425        return 1;
4426     }
4427     info.set_period(start, end);
4428     info.name= name;
4429 
4430     info.constr= new Virtual_column_info();
4431     info.constr->expr= lt_creator.create(thd,
4432                                          create_item_ident_nosp(thd, &start),
4433                                          create_item_ident_nosp(thd, &end));
4434     add_constraint(null_clex_str, info.constr, false);
4435     return 0;
4436   }
4437 
4438   sp_package *get_sp_package() const;
4439 
4440   /**
4441     Check if the select is a simple select (not an union).
4442     @retval
4443       0 ok
4444     @retval
4445       1 error   ; In this case the error messege is sent to the client
4446   */
4447   bool check_simple_select(const LEX_CSTRING *option)
4448   {
4449     if (current_select != &builtin_select)
4450     {
4451       char command[80];
4452       strmake(command, option->str, MY_MIN(option->length, sizeof(command)-1));
4453       my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
4454       return true;
4455     }
4456     return false;
4457   }
4458 
4459   SELECT_LEX_UNIT *alloc_unit();
4460   SELECT_LEX *alloc_select(bool is_select);
4461   SELECT_LEX_UNIT *create_unit(SELECT_LEX*);
4462   SELECT_LEX *wrap_unit_into_derived(SELECT_LEX_UNIT *unit);
4463   SELECT_LEX *wrap_select_chain_into_derived(SELECT_LEX *sel);
4464   bool main_select_push(bool service= false);
4465   bool insert_select_hack(SELECT_LEX *sel);
4466   SELECT_LEX *create_priority_nest(SELECT_LEX *first_in_nest);
4467 
4468   bool set_main_unit(st_select_lex_unit *u)
4469   {
4470     unit.options= u->options;
4471     unit.uncacheable= u->uncacheable;
4472     unit.register_select_chain(u->first_select());
4473     unit.first_select()->options|= builtin_select.options;
4474     unit.fake_select_lex= u->fake_select_lex;
4475     unit.union_distinct= u->union_distinct;
4476     unit.set_with_clause(u->with_clause);
4477     builtin_select.exclude_from_global();
4478     return false;
4479   }
4480   bool check_main_unit_semantics();
4481 
4482   SELECT_LEX_UNIT *parsed_select_expr_start(SELECT_LEX *s1, SELECT_LEX *s2,
4483                                             enum sub_select_type unit_type,
4484                                             bool distinct);
4485   SELECT_LEX_UNIT *parsed_select_expr_cont(SELECT_LEX_UNIT *unit,
4486                                            SELECT_LEX *s2,
4487                                            enum sub_select_type unit_type,
4488                                            bool distinct, bool oracle);
4489   bool parsed_multi_operand_query_expression_body(SELECT_LEX_UNIT *unit);
4490   SELECT_LEX_UNIT *add_tail_to_query_expression_body(SELECT_LEX_UNIT *unit,
4491 						     Lex_order_limit_lock *l);
4492   SELECT_LEX_UNIT *
4493   add_tail_to_query_expression_body_ext_parens(SELECT_LEX_UNIT *unit,
4494 					       Lex_order_limit_lock *l);
4495   SELECT_LEX_UNIT *parsed_body_ext_parens_primary(SELECT_LEX_UNIT *unit,
4496                                                   SELECT_LEX *primary,
4497                                               enum sub_select_type unit_type,
4498                                               bool distinct);
4499   SELECT_LEX_UNIT *
4500   add_primary_to_query_expression_body(SELECT_LEX_UNIT *unit,
4501                                        SELECT_LEX *sel,
4502                                        enum sub_select_type unit_type,
4503                                        bool distinct,
4504                                        bool oracle);
4505   SELECT_LEX_UNIT *
4506   add_primary_to_query_expression_body_ext_parens(
4507                                        SELECT_LEX_UNIT *unit,
4508                                        SELECT_LEX *sel,
4509                                        enum sub_select_type unit_type,
4510                                        bool distinct);
4511   SELECT_LEX *parsed_subselect(SELECT_LEX_UNIT *unit);
4512   bool parsed_insert_select(SELECT_LEX *firs_select);
4513   void save_values_list_state();
4514   void restore_values_list_state();
4515   bool parsed_TVC_start();
4516   SELECT_LEX *parsed_TVC_end();
4517   TABLE_LIST *parsed_derived_table(SELECT_LEX_UNIT *unit,
4518                                    int for_system_time,
4519                                    LEX_CSTRING *alias);
4520   bool parsed_create_view(SELECT_LEX_UNIT *unit, int check);
4521   bool select_finalize(st_select_lex_unit *expr);
4522   bool select_finalize(st_select_lex_unit *expr, Lex_select_lock l);
4523   void relink_hack(st_select_lex *select_lex);
4524 
4525   bool stmt_install_plugin(const DDL_options_st &opt,
4526                            const Lex_ident_sys_st &name,
4527                            const LEX_CSTRING &soname);
4528   void stmt_install_plugin(const LEX_CSTRING &soname);
4529 
4530   bool stmt_uninstall_plugin_by_name(const DDL_options_st &opt,
4531                                      const Lex_ident_sys_st &name);
4532   bool stmt_uninstall_plugin_by_soname(const DDL_options_st &opt,
4533                                        const LEX_CSTRING &soname);
4534   bool stmt_prepare_validate(const char *stmt_type);
4535   bool stmt_prepare(const Lex_ident_sys_st &ident, Item *code);
4536   bool stmt_execute(const Lex_ident_sys_st &ident, List<Item> *params);
4537   bool stmt_execute_immediate(Item *code, List<Item> *params);
4538   void stmt_deallocate_prepare(const Lex_ident_sys_st &ident);
4539 
4540   bool stmt_alter_table_exchange_partition(Table_ident *table);
4541 
4542   void stmt_purge_to(const LEX_CSTRING &to);
4543   bool stmt_purge_before(Item *item);
4544 
4545 private:
4546   bool stmt_create_routine_start(const DDL_options_st &options)
4547   {
4548     create_info.set(options);
4549     return main_select_push() || check_create_options(options);
4550   }
4551 public:
4552   bool stmt_create_function_start(const DDL_options_st &options)
4553   {
4554     sql_command= SQLCOM_CREATE_SPFUNCTION;
4555     return stmt_create_routine_start(options);
4556   }
4557   bool stmt_create_procedure_start(const DDL_options_st &options)
4558   {
4559     sql_command= SQLCOM_CREATE_PROCEDURE;
4560     return stmt_create_routine_start(options);
4561   }
4562   void stmt_create_routine_finalize()
4563   {
4564     pop_select(); // main select
4565   }
4566 
4567   bool stmt_create_stored_function_start(const DDL_options_st &options,
4568                                          enum_sp_aggregate_type,
4569                                          const sp_name *name);
4570   bool stmt_create_stored_function_finalize_standalone(const sp_name *end_name);
4571 
4572   bool stmt_create_udf_function(const DDL_options_st &options,
4573                                 enum_sp_aggregate_type agg_type,
4574                                 const Lex_ident_sys_st &name,
4575                                 Item_result return_type,
4576                                 const LEX_CSTRING &soname);
4577   Spvar_definition *row_field_name(THD *thd, const Lex_ident_sys_st &name);
4578 
4579   bool map_data_type(const Lex_ident_sys_st &schema,
4580                      Lex_field_type_st *type) const;
4581 
4582   void mark_first_table_as_inserting();
4583 
4584   bool fields_are_impossible()
4585   {
4586     // no select or it is last select with no tables (service select)
4587     return !select_stack_head() ||
4588            (select_stack_top == 1 &&
4589             select_stack[0]->is_service_select);
4590   }
4591 
4592   bool check_dependencies_in_with_clauses();
4593   bool resolve_references_to_cte_in_hanging_cte();
4594   bool check_cte_dependencies_and_resolve_references();
4595   bool resolve_references_to_cte(TABLE_LIST *tables,
4596                                  TABLE_LIST **tables_last);
4597 
4598 };
4599 
4600 
4601 /**
4602   Set_signal_information is a container used in the parsed tree to represent
4603   the collection of assignments to condition items in the SIGNAL and RESIGNAL
4604   statements.
4605 */
4606 class Set_signal_information
4607 {
4608 public:
4609   /** Empty default constructor, use clear() */
4610  Set_signal_information() {}
4611 
4612   /** Copy constructor. */
4613   Set_signal_information(const Set_signal_information& set);
4614 
4615   /** Destructor. */
4616   ~Set_signal_information()
4617   {}
4618 
4619   /** Clear all items. */
4620   void clear();
4621 
4622   /**
4623     For each condition item assignment, m_item[] contains the parsed tree
4624     that represents the expression assigned, if any.
4625     m_item[] is an array indexed by Diag_condition_item_name.
4626   */
4627   Item *m_item[LAST_DIAG_SET_PROPERTY+1];
4628 };
4629 
4630 
4631 /**
4632   The internal state of the syntax parser.
4633   This object is only available during parsing,
4634   and is private to the syntax parser implementation (sql_yacc.yy).
4635 */
4636 class Yacc_state
4637 {
4638 public:
4639   Yacc_state() : yacc_yyss(NULL), yacc_yyvs(NULL) { reset(); }
4640 
4641   void reset()
4642   {
4643     if (yacc_yyss != NULL) {
4644       my_free(yacc_yyss);
4645       yacc_yyss = NULL;
4646     }
4647     if (yacc_yyvs != NULL) {
4648       my_free(yacc_yyvs);
4649       yacc_yyvs = NULL;
4650     }
4651     m_set_signal_info.clear();
4652     m_lock_type= TL_READ_DEFAULT;
4653     m_mdl_type= MDL_SHARED_READ;
4654   }
4655 
4656   ~Yacc_state();
4657 
4658   /**
4659     Reset part of the state which needs resetting before parsing
4660     substatement.
4661   */
4662   void reset_before_substatement()
4663   {
4664     m_lock_type= TL_READ_DEFAULT;
4665     m_mdl_type= MDL_SHARED_READ;
4666   }
4667 
4668   /**
4669     Bison internal state stack, yyss, when dynamically allocated using
4670     my_yyoverflow().
4671   */
4672   uchar *yacc_yyss;
4673 
4674   /**
4675     Bison internal semantic value stack, yyvs, when dynamically allocated using
4676     my_yyoverflow().
4677   */
4678   uchar *yacc_yyvs;
4679 
4680   /**
4681     Fragments of parsed tree,
4682     used during the parsing of SIGNAL and RESIGNAL.
4683   */
4684   Set_signal_information m_set_signal_info;
4685 
4686   /**
4687     Type of lock to be used for tables being added to the statement's
4688     table list in table_factor, table_alias_ref, single_multi and
4689     table_wild_one rules.
4690     Statements which use these rules but require lock type different
4691     from one specified by this member have to override it by using
4692     st_select_lex::set_lock_for_tables() method.
4693 
4694     The default value of this member is TL_READ_DEFAULT. The only two
4695     cases in which we change it are:
4696     - When parsing SELECT HIGH_PRIORITY.
4697     - Rule for DELETE. In which we use this member to pass information
4698       about type of lock from delete to single_multi part of rule.
4699 
4700     We should try to avoid introducing new use cases as we would like
4701     to get rid of this member eventually.
4702   */
4703   thr_lock_type m_lock_type;
4704 
4705   /**
4706     The type of requested metadata lock for tables added to
4707     the statement table list.
4708   */
4709   enum_mdl_type m_mdl_type;
4710 
4711   /*
4712     TODO: move more attributes from the LEX structure here.
4713   */
4714 };
4715 
4716 /**
4717   Internal state of the parser.
4718   The complete state consist of:
4719   - state data used during lexical parsing,
4720   - state data used during syntactic parsing.
4721 */
4722 class Parser_state
4723 {
4724 public:
4725   Parser_state()
4726     : m_yacc()
4727   {}
4728 
4729   /**
4730      Object initializer. Must be called before usage.
4731 
4732      @retval FALSE OK
4733      @retval TRUE  Error
4734   */
4735   bool init(THD *thd, char *buff, size_t length)
4736   {
4737     return m_lip.init(thd, buff, length);
4738   }
4739 
4740   ~Parser_state()
4741   {}
4742 
4743   Lex_input_stream m_lip;
4744   Yacc_state m_yacc;
4745 
4746   /**
4747     Current performance digest instrumentation.
4748   */
4749   PSI_digest_locker* m_digest_psi;
4750 
4751   void reset(char *found_semicolon, unsigned int length)
4752   {
4753     m_lip.reset(found_semicolon, length);
4754     m_yacc.reset();
4755   }
4756 };
4757 
4758 
4759 extern sql_digest_state *
4760 digest_add_token(sql_digest_state *state, uint token, LEX_YYSTYPE yylval);
4761 
4762 extern sql_digest_state *
4763 digest_reduce_token(sql_digest_state *state, uint token_left, uint token_right);
4764 
4765 struct st_lex_local: public LEX, public Sql_alloc
4766 {
4767 };
4768 
4769 
4770 /**
4771   An st_lex_local extension with automatic initialization for SP purposes.
4772   Used to parse sub-expressions and SP sub-statements.
4773 
4774   This class is reused for:
4775   1. sp_head::reset_lex() based constructs
4776     - SP variable assignments (e.g. SET x=10;)
4777     - FOR loop conditions and index variable increments
4778     - Cursor statements
4779     - SP statements
4780     - SP function RETURN statements
4781     - CASE statements
4782     - REPEAT..UNTIL expressions
4783     - WHILE expressions
4784     - EXIT..WHEN and CONTINUE..WHEN statements
4785   2. sp_assignment_lex based constructs:
4786     - CURSOR parameter assignments
4787 */
4788 class sp_lex_local: public st_lex_local
4789 {
4790 public:
4791   sp_lex_local(THD *thd, const LEX *oldlex)
4792   {
4793     /* Reset most stuff. */
4794     start(thd);
4795     /* Keep the parent SP stuff */
4796     sphead= oldlex->sphead;
4797     spcont= oldlex->spcont;
4798     /* Keep the parent trigger stuff too */
4799     trg_chistics= oldlex->trg_chistics;
4800     trg_table_fields.empty();
4801     sp_lex_in_use= false;
4802   }
4803 };
4804 
4805 
4806 /**
4807   An assignment specific LEX, which additionally has an Item (an expression)
4808   and an associated with the Item free_list, which is usually freed
4809   after the expression is calculated.
4810 
4811   Note, consider changing some of sp_lex_local to sp_assignment_lex,
4812   as the latter allows to use a simpler grammar in sql_yacc.yy (IMO).
4813 
4814   If the expression is simple (e.g. does not have function calls),
4815   then m_item and m_free_list point to the same Item.
4816 
4817   If the expressions is complex (e.g. have function calls),
4818   then m_item points to the leftmost Item, while m_free_list points
4819   to the rightmost item.
4820   For example:
4821       f1(COALESCE(f2(10), f2(20)))
4822   - m_item points to Item_func_sp for f1 (the leftmost Item)
4823   - m_free_list points to Item_int for 20 (the rightmost Item)
4824 
4825   Note, we could avoid storing m_item at all, as we can always reach
4826   the leftmost item from the rightmost item by iterating through m_free_list.
4827   But with a separate m_item the code should be faster.
4828 */
4829 class sp_assignment_lex: public sp_lex_local
4830 {
4831   Item *m_item;       // The expression
4832   Item *m_free_list;  // The associated free_list (sub-expressions)
4833 public:
4834   sp_assignment_lex(THD *thd, LEX *oldlex)
4835    :sp_lex_local(thd, oldlex),
4836     m_item(NULL),
4837     m_free_list(NULL)
4838   { }
4839   void set_item_and_free_list(Item *item, Item *free_list)
4840   {
4841     m_item= item;
4842     m_free_list= free_list;
4843   }
4844   Item *get_item() const
4845   {
4846     return m_item;
4847   }
4848   Item *get_free_list() const
4849   {
4850     return m_free_list;
4851   }
4852 };
4853 
4854 
4855 extern void lex_init(void);
4856 extern void lex_free(void);
4857 extern void lex_start(THD *thd);
4858 extern void lex_end(LEX *lex);
4859 extern void lex_end_nops(LEX *lex);
4860 extern void lex_unlock_plugins(LEX *lex);
4861 void end_lex_with_single_table(THD *thd, TABLE *table, LEX *old_lex);
4862 int init_lex_with_single_table(THD *thd, TABLE *table, LEX *lex);
4863 extern int MYSQLlex(union YYSTYPE *yylval, THD *thd);
4864 extern int ORAlex(union YYSTYPE *yylval, THD *thd);
4865 
4866 extern void trim_whitespace(CHARSET_INFO *cs, LEX_CSTRING *str, size_t * prefix_length = 0);
4867 
4868 extern bool is_lex_native_function(const LEX_CSTRING *name);
4869 extern bool is_native_function(THD *thd, const LEX_CSTRING *name);
4870 extern bool is_native_function_with_warn(THD *thd, const LEX_CSTRING *name);
4871 
4872 /**
4873   @} (End of group Semantic_Analysis)
4874 */
4875 
4876 void my_missing_function_error(const LEX_CSTRING &token, const char *name);
4877 bool is_keyword(const char *name, uint len);
4878 int set_statement_var_if_exists(THD *thd, const char *var_name,
4879                                 size_t var_name_length, ulonglong value);
4880 
4881 Virtual_column_info *add_virtual_expression(THD *thd, Item *expr);
4882 Item* handle_sql2003_note184_exception(THD *thd, Item* left, bool equal,
4883                                        Item *expr);
4884 
4885 bool sp_create_assignment_lex(THD *thd, bool no_lookahead);
4886 bool sp_create_assignment_instr(THD *thd, bool no_lookahead);
4887 
4888 void mark_or_conds_to_avoid_pushdown(Item *cond);
4889 
4890 #endif /* MYSQL_SERVER */
4891 #endif /* SQL_LEX_INCLUDED */
4892