1 /* Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
2 
3    This program is free software; you can redistribute it and/or modify
4    it under the terms of the GNU General Public License, version 2.0,
5    as published by the Free Software Foundation.
6 
7    This program is also distributed with certain software (including
8    but not limited to OpenSSL) that is licensed under separate terms,
9    as designated in a particular file or component or in included license
10    documentation.  The authors of MySQL hereby grant you an additional
11    permission to link the program and your derivative works with the
12    separately licensed software that they have included with MySQL.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License, version 2.0, for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
22 
23 /**
24   @defgroup Semantic_Analysis Semantic Analysis
25 */
26 
27 #ifndef SQL_LEX_INCLUDED
28 #define SQL_LEX_INCLUDED
29 
30 #include "violite.h"                            /* SSL_type */
31 #include "sql_trigger.h"
32 #include "item.h"               /* From item_subselect.h: subselect_union_engine */
33 #include "thr_lock.h"                  /* thr_lock_type, TL_UNLOCK */
34 #include "sql_array.h"
35 #include "mem_root_array.h"
36 #include "sql_alter.h"                // Alter_info
37 
38 /* YACC and LEX Definitions */
39 
40 /* These may not be declared yet */
41 class Table_ident;
42 class sql_exchange;
43 class LEX_COLUMN;
44 class sp_head;
45 class sp_name;
46 class sp_instr;
47 class sp_pcontext;
48 class st_alter_tablespace;
49 class partition_info;
50 class Event_parse_data;
51 class set_var_base;
52 class sys_var;
53 class Item_func_match;
54 class File_parser;
55 class Key_part_spec;
56 struct sql_digest_state;
57 
58 #ifdef MYSQL_SERVER
59 /*
60   There are 8 different type of table access so there is no more than
61   combinations 2^8 = 256:
62 
63   . STMT_READS_TRANS_TABLE
64 
65   . STMT_READS_NON_TRANS_TABLE
66 
67   . STMT_READS_TEMP_TRANS_TABLE
68 
69   . STMT_READS_TEMP_NON_TRANS_TABLE
70 
71   . STMT_WRITES_TRANS_TABLE
72 
73   . STMT_WRITES_NON_TRANS_TABLE
74 
75   . STMT_WRITES_TEMP_TRANS_TABLE
76 
77   . STMT_WRITES_TEMP_NON_TRANS_TABLE
78 
79   The unsafe conditions for each combination is represented within a byte
80   and stores the status of the option --binlog-direct-non-trans-updates,
81   whether the trx-cache is empty or not, and whether the isolation level
82   is lower than ISO_REPEATABLE_READ:
83 
84   . option (OFF/ON)
85   . trx-cache (empty/not empty)
86   . isolation (>= ISO_REPEATABLE_READ / < ISO_REPEATABLE_READ)
87 
88   bits 0 : . OFF, . empty, . >= ISO_REPEATABLE_READ
89   bits 1 : . OFF, . empty, . < ISO_REPEATABLE_READ
90   bits 2 : . OFF, . not empty, . >= ISO_REPEATABLE_READ
91   bits 3 : . OFF, . not empty, . < ISO_REPEATABLE_READ
92   bits 4 : . ON, . empty, . >= ISO_REPEATABLE_READ
93   bits 5 : . ON, . empty, . < ISO_REPEATABLE_READ
94   bits 6 : . ON, . not empty, . >= ISO_REPEATABLE_READ
95   bits 7 : . ON, . not empty, . < ISO_REPEATABLE_READ
96 */
97 extern uint binlog_unsafe_map[256];
98 /*
99   Initializes the array with unsafe combinations and its respective
100   conditions.
101 */
102 void binlog_unsafe_map_init();
103 #endif
104 
105 /**
106   used by the parser to store internal variable name
107 */
108 struct sys_var_with_base
109 {
110   sys_var *var;
111   LEX_STRING base_name;
112 };
113 
114 #ifdef MYSQL_SERVER
115 /*
116   The following hack is needed because mysql_yacc.cc does not define
117   YYSTYPE before including this file
118 */
119 #ifdef MYSQL_YACC
120 #define LEX_YYSTYPE void *
121 #else
122 #include "lex_symbol.h"
123 #if MYSQL_LEX
124 #include "item_func.h"            /* Cast_target used in sql_yacc.h */
125 #include "sql_get_diagnostics.h"  /* Types used in sql_yacc.h */
126 #include "sql_yacc.h"
127 #define LEX_YYSTYPE YYSTYPE *
128 #else
129 #define LEX_YYSTYPE void *
130 #endif
131 #endif
132 #endif
133 
134 #include "sql_cmd.h"
135 
136 // describe/explain types
137 #define DESCRIBE_NONE		0 // Not explain query
138 #define DESCRIBE_NORMAL		1
139 #define DESCRIBE_EXTENDED	2
140 /*
141   This is not within #ifdef because we want "EXPLAIN PARTITIONS ..." to produce
142   additional "partitions" column even if partitioning is not compiled in.
143 */
144 #define DESCRIBE_PARTITIONS	4
145 
146 #ifdef MYSQL_SERVER
147 
148 enum enum_sp_suid_behaviour
149 {
150   SP_IS_DEFAULT_SUID= 0,
151   SP_IS_NOT_SUID,
152   SP_IS_SUID
153 };
154 
155 enum enum_sp_data_access
156 {
157   SP_DEFAULT_ACCESS= 0,
158   SP_CONTAINS_SQL,
159   SP_NO_SQL,
160   SP_READS_SQL_DATA,
161   SP_MODIFIES_SQL_DATA
162 };
163 
164 /**
165   enum_sp_type defines type codes of stored programs.
166 
167   Events have the SP_TYPE_PROCEDURE type code.
168 
169   @note these codes are used when dealing with the mysql.proc system table, so
170   they must not be changed.
171 
172   @note the following macros were used previously for the same purpose. Now they
173   are used for ACL only.
174 */
175 enum enum_sp_type
176 {
177   SP_TYPE_FUNCTION= 1,
178   SP_TYPE_PROCEDURE,
179   SP_TYPE_TRIGGER
180 };
181 
182 /*
183   Values for the type enum. This reflects the order of the enum declaration
184   in the CREATE TABLE command. These values are used to enumerate object types
185   for the ACL statements.
186 
187   These values were also used for enumerating stored program types. However, now
188   enum_sp_type should be used for that instead of them.
189 */
190 #define TYPE_ENUM_FUNCTION  1
191 #define TYPE_ENUM_PROCEDURE 2
192 #define TYPE_ENUM_TRIGGER   3
193 #define TYPE_ENUM_PROXY     4
194 
195 const LEX_STRING sp_data_access_name[]=
196 {
197   { C_STRING_WITH_LEN("") },
198   { C_STRING_WITH_LEN("CONTAINS SQL") },
199   { C_STRING_WITH_LEN("NO SQL") },
200   { C_STRING_WITH_LEN("READS SQL DATA") },
201   { C_STRING_WITH_LEN("MODIFIES SQL DATA") }
202 };
203 
204 #define DERIVED_SUBQUERY	1
205 #define DERIVED_VIEW		2
206 
207 enum enum_view_create_mode
208 {
209   VIEW_CREATE_NEW,		// check that there are not such VIEW/table
210   VIEW_ALTER,			// check that VIEW .frm with such name exists
211   VIEW_CREATE_OR_REPLACE	// check only that there are not such table
212 };
213 
214 enum enum_drop_mode
215 {
216   DROP_DEFAULT, // mode is not specified
217   DROP_CASCADE, // CASCADE option
218   DROP_RESTRICT // RESTRICT option
219 };
220 
221 /* Options to add_table_to_list() */
222 #define TL_OPTION_UPDATING	1
223 #define TL_OPTION_FORCE_INDEX	2
224 #define TL_OPTION_IGNORE_LEAVES 4
225 #define TL_OPTION_ALIAS         8
226 
227 typedef List<Item> List_item;
228 typedef Mem_root_array<ORDER*, true> Group_list_ptrs;
229 
230 /* SERVERS CACHE CHANGES */
231 typedef struct st_lex_server_options
232 {
233   long port;
234   uint server_name_length;
235   char *server_name, *host, *db, *username, *password, *scheme, *socket, *owner;
236 } LEX_SERVER_OPTIONS;
237 
238 
239 /**
240   Structure to hold parameters for CHANGE MASTER, START SLAVE, and STOP SLAVE.
241 
242   Remark: this should not be confused with Master_info (and perhaps
243   would better be renamed to st_lex_replication_info).  Some fields,
244   e.g., delay, are saved in Relay_log_info, not in Master_info.
245 */
246 typedef struct st_lex_master_info
247 {
248   char *host, *user, *password, *log_file_name, *bind_addr;
249   uint port, connect_retry;
250   float heartbeat_period;
251   int sql_delay;
252   ulonglong pos;
253   ulong server_id, retry_count;
254   char *gtid;
255   enum {UNTIL_SQL_BEFORE_GTIDS= 0, UNTIL_SQL_AFTER_GTIDS} gtid_until_condition;
256   bool until_after_gaps;
257 
258   /*
259     Enum is used for making it possible to detect if the user
260     changed variable or if it should be left at old value
261    */
262   enum {LEX_MI_UNCHANGED= 0, LEX_MI_DISABLE, LEX_MI_ENABLE}
263     ssl, ssl_verify_server_cert, heartbeat_opt, repl_ignore_server_ids_opt,
264     retry_count_opt, auto_position;
265   char *ssl_key, *ssl_cert, *ssl_ca, *ssl_capath, *ssl_cipher;
266   char *ssl_crl, *ssl_crlpath;
267   char *relay_log_name;
268   ulong relay_log_pos;
269   DYNAMIC_ARRAY repl_ignore_server_ids;
270   ulong server_ids_buffer[2];
271   void set_unspecified();
272 } LEX_MASTER_INFO;
273 
274 typedef struct st_lex_reset_slave
275 {
276   bool all;
277 } LEX_RESET_SLAVE;
278 
279 enum sub_select_type
280 {
281   UNSPECIFIED_TYPE,UNION_TYPE, INTERSECT_TYPE,
282   EXCEPT_TYPE, GLOBAL_OPTIONS_TYPE, DERIVED_TABLE_TYPE, OLAP_TYPE
283 };
284 
285 enum olap_type
286 {
287   UNSPECIFIED_OLAP_TYPE, CUBE_TYPE, ROLLUP_TYPE
288 };
289 
290 /*
291   String names used to print a statement with index hints.
292   Keep in sync with index_hint_type.
293 */
294 extern const char * index_hint_type_name[];
295 typedef uchar index_clause_map;
296 
297 /*
298   Bits in index_clause_map : one for each possible FOR clause in
299   USE/FORCE/IGNORE INDEX index hint specification
300 */
301 #define INDEX_HINT_MASK_JOIN  (1)
302 #define INDEX_HINT_MASK_GROUP (1 << 1)
303 #define INDEX_HINT_MASK_ORDER (1 << 2)
304 
305 #define INDEX_HINT_MASK_ALL (INDEX_HINT_MASK_JOIN | INDEX_HINT_MASK_GROUP | \
306                              INDEX_HINT_MASK_ORDER)
307 
308 /* Single element of an USE/FORCE/IGNORE INDEX list specified as a SQL hint  */
309 class Index_hint : public Sql_alloc
310 {
311 public:
312   /* The type of the hint : USE/FORCE/IGNORE */
313   enum index_hint_type type;
314   /* Where the hit applies to. A bitmask of INDEX_HINT_MASK_<place> values */
315   index_clause_map clause;
316   /*
317     The index name. Empty (str=NULL) name represents an empty list
318     USE INDEX () clause
319   */
320   LEX_STRING key_name;
321 
Index_hint(enum index_hint_type type_arg,index_clause_map clause_arg,char * str,uint length)322   Index_hint (enum index_hint_type type_arg, index_clause_map clause_arg,
323               char *str, uint length) :
324     type(type_arg), clause(clause_arg)
325   {
326     key_name.str= str;
327     key_name.length= length;
328   }
329 
330   void print(THD *thd, String *str);
331 };
332 
333 /*
334   The state of the lex parsing for selects
335 
336    master and slaves are pointers to select_lex.
337    master is pointer to upper level node.
338    slave is pointer to lower level node
339    select_lex is a SELECT without union
340    unit is container of either
341      - One SELECT
342      - UNION of selects
343    select_lex and unit are both inherited form select_lex_node
344    neighbors are two select_lex or units on the same level
345 
346    All select describing structures linked with following pointers:
347    - list of neighbors (next/prev) (prev of first element point to slave
348      pointer of upper structure)
349      - For select this is a list of UNION's (or one element list)
350      - For units this is a list of sub queries for the upper level select
351 
352    - pointer to master (master), which is
353      If this is a unit
354        - pointer to outer select_lex
355      If this is a select_lex
356        - pointer to outer unit structure for select
357 
358    - pointer to slave (slave), which is either:
359      If this is a unit:
360        - first SELECT that belong to this unit
361      If this is a select_lex
362        - first unit that belong to this SELECT (subquries or derived tables)
363 
364    - list of all select_lex (link_next/link_prev)
365      This is to be used for things like derived tables creation, where we
366      go through this list and create the derived tables.
367 
368    If unit contain several selects (UNION now, INTERSECT etc later)
369    then it have special select_lex called fake_select_lex. It used for
370    storing global parameters (like ORDER BY, LIMIT) and executing union.
371    Subqueries used in global ORDER BY clause will be attached to this
372    fake_select_lex, which will allow them correctly resolve fields of
373    'upper' UNION and outer selects.
374 
375    For example for following query:
376 
377    select *
378      from table1
379      where table1.field IN (select * from table1_1_1 union
380                             select * from table1_1_2)
381      union
382    select *
383      from table2
384      where table2.field=(select (select f1 from table2_1_1_1_1
385                                    where table2_1_1_1_1.f2=table2_1_1.f3)
386                            from table2_1_1
387                            where table2_1_1.f1=table2.f2)
388      union
389    select * from table3;
390 
391    we will have following structure:
392 
393    select1: (select * from table1 ...)
394    select2: (select * from table2 ...)
395    select3: (select * from table3)
396    select1.1.1: (select * from table1_1_1)
397    ...
398 
399      main unit
400      fake0
401      select1 select2 select3
402      |^^     |^
403     s|||     ||master
404     l|||     |+---------------------------------+
405     a|||     +---------------------------------+|
406     v|||master                         slave   ||
407     e||+-------------------------+             ||
408      V|            neighbor      |             V|
409      unit1.1<+==================>unit1.2       unit2.1
410      fake1.1
411      select1.1.1 select 1.1.2    select1.2.1   select2.1.1
412                                                |^
413                                                ||
414                                                V|
415                                                unit2.1.1.1
416                                                select2.1.1.1.1
417 
418 
419    relation in main unit will be following:
420    (bigger picture for:
421       main unit
422       fake0
423       select1 select2 select3
424    in the above picture)
425 
426          main unit
427          |^^^^|fake_select_lex
428          |||||+--------------------------------------------+
429          ||||+--------------------------------------------+|
430          |||+------------------------------+              ||
431          ||+--------------+                |              ||
432     slave||master         |                |              ||
433          V|      neighbor |       neighbor |        master|V
434          select1<========>select2<========>select3        fake0
435 
436     list of all select_lex will be following (as it will be constructed by
437     parser):
438 
439     select1->select2->select3->select2.1.1->select 2.1.2->select2.1.1.1.1-+
440                                                                           |
441     +---------------------------------------------------------------------+
442     |
443     +->select1.1.1->select1.1.2
444 
445 */
446 
447 /*
448     Base class for st_select_lex (SELECT_LEX) &
449     st_select_lex_unit (SELECT_LEX_UNIT)
450 */
451 struct LEX;
452 class st_select_lex;
453 class st_select_lex_unit;
454 
455 
456 class st_select_lex_node {
457 protected:
458   st_select_lex_node *next, **prev,   /* neighbor list */
459     *master, *slave,                  /* vertical links */
460     *link_next, **link_prev;          /* list of whole SELECT_LEX */
461 public:
462 
463   ulonglong options;
464 
465   /*
466     In sql_cache we store SQL_CACHE flag as specified by user to be
467     able to restore SELECT statement from internal structures.
468   */
469   enum e_sql_cache { SQL_CACHE_UNSPECIFIED, SQL_NO_CACHE, SQL_CACHE };
470   e_sql_cache sql_cache;
471 
472   /*
473     result of this query can't be cached, bit field, can be :
474       UNCACHEABLE_DEPENDENT
475       UNCACHEABLE_RAND
476       UNCACHEABLE_SIDEEFFECT
477       UNCACHEABLE_EXPLAIN
478       UNCACHEABLE_PREPARE
479   */
480   uint8 uncacheable;
481   enum sub_select_type linkage;
482   bool no_table_names_allowed; /* used for global order by */
483   bool no_error; /* suppress error message (convert it to warnings) */
484 
new(size_t size)485   static void *operator new(size_t size) throw ()
486   {
487     return sql_alloc(size);
488   }
new(size_t size,MEM_ROOT * mem_root)489   static void *operator new(size_t size, MEM_ROOT *mem_root) throw ()
490   { return (void*) alloc_root(mem_root, (uint) size); }
delete(void * ptr,size_t size)491   static void operator delete(void *ptr,size_t size) { TRASH(ptr, size); }
delete(void * ptr,MEM_ROOT * mem_root)492   static void operator delete(void *ptr, MEM_ROOT *mem_root) {}
493 
494   // Ensures that at least all members used during cleanup() are initialized.
st_select_lex_node()495   st_select_lex_node()
496     : next(NULL), prev(NULL),
497       master(NULL), slave(NULL),
498       link_next(NULL), link_prev(NULL),
499       linkage(UNSPECIFIED_TYPE)
500   {
501   }
~st_select_lex_node()502   virtual ~st_select_lex_node() {}
503 
get_master()504   inline st_select_lex_node* get_master() { return master; }
505   virtual void init_query();
506   virtual void init_select();
507   void include_down(st_select_lex_node *upper);
508   void include_neighbour(st_select_lex_node *before);
509   void include_standalone(st_select_lex_node *sel, st_select_lex_node **ref);
510   void include_global(st_select_lex_node **plink);
511   void exclude();
512 
513   virtual st_select_lex_unit* master_unit()= 0;
514   virtual st_select_lex* outer_select()= 0;
515 
516   virtual bool set_braces(bool value);
517   virtual bool inc_in_sum_expr();
518   virtual uint get_in_sum_expr();
519   virtual TABLE_LIST* get_table_list();
520   virtual List<Item>* get_item_list();
521   virtual ulong get_table_join_options();
522   virtual TABLE_LIST *add_table_to_list(THD *thd, Table_ident *table,
523 					LEX_STRING *alias,
524 					ulong table_options,
525 					thr_lock_type flags= TL_UNLOCK,
526                                         enum_mdl_type mdl_type= MDL_SHARED_READ,
527 					List<Index_hint> *hints= 0,
528                                         List<String> *partition_names= 0,
529                                         LEX_STRING *option= 0);
set_lock_for_tables(thr_lock_type lock_type)530   virtual void set_lock_for_tables(thr_lock_type lock_type) {}
531 
532   friend class st_select_lex_unit;
533   friend bool mysql_new_select(LEX *lex, bool move_down);
534   friend bool mysql_make_view(THD *thd, TABLE_SHARE *share, TABLE_LIST *table,
535                               bool open_view_no_parse);
536 private:
537   void fast_exclude();
538 };
539 typedef class st_select_lex_node SELECT_LEX_NODE;
540 
541 /*
542    SELECT_LEX_UNIT - unit of selects (UNION, INTERSECT, ...) group
543    SELECT_LEXs
544 */
545 class THD;
546 class select_result;
547 class JOIN;
548 class select_union;
549 
550 
551 class st_select_lex_unit: public st_select_lex_node {
552 protected:
553   TABLE_LIST result_table_list;
554   select_union *union_result;
555   TABLE *table; /* temporary table using for appending UNION results */
556 
557   select_result *result;
558   ulonglong found_rows_for_union;
559   bool saved_error;
560 
561 public:
562   // Ensures that at least all members used during cleanup() are initialized.
st_select_lex_unit()563   st_select_lex_unit()
564     : union_result(NULL), table(NULL), result(NULL),
565       cleaned(false),
566       fake_select_lex(NULL),
567       explain_marker(0)
568   {
569   }
570 
571   bool  prepared, // prepare phase already performed for UNION (unit)
572     optimized, // optimize phase already performed for UNION (unit)
573     executed, // already executed
574     cleaned;
575 
576   // list of fields which points to temporary table for union
577   List<Item> item_list;
578   /*
579     list of types of items inside union (used for union & derived tables)
580 
581     Item_type_holders from which this list consist may have pointers to Field,
582     pointers is valid only after preparing SELECTS of this unit and before
583     any SELECT of this unit execution
584 
585     TODO:
586     Possibly this member should be protected, and its direct use replaced
587     by get_unit_column_types(). Check the places where it is used.
588   */
589   List<Item> types;
590   /*
591     Pointer to 'last' select or pointer to unit where stored
592     global parameters for union
593   */
594   st_select_lex *global_parameters;
595   /* LIMIT clause runtime counters */
596   ha_rows select_limit_cnt, offset_limit_cnt;
597   /* not NULL if unit used in subselect, point to subselect item */
598   Item_subselect *item;
599   /* thread handler */
600   THD *thd;
601   /*
602     SELECT_LEX for hidden SELECT in onion which process global
603     ORDER BY and LIMIT
604   */
605   st_select_lex *fake_select_lex;
606 
607   st_select_lex *union_distinct; /* pointer to the last UNION DISTINCT */
608   bool describe; /* union exec() called for EXPLAIN */
609 
610   /**
611     Marker for subqueries in WHERE, HAVING, ORDER BY, GROUP BY and
612     SELECT item lists
613 
614    See Item_subselect::explain_subquery_checker
615 
616    @note Actually, the type of this variable is Explain_context_enum, but .h
617          files are too interlinked to include "opt_format.h" there
618   */
619   int explain_marker;
620 
621   void init_query();
622   st_select_lex_unit* master_unit();
623   st_select_lex* outer_select();
first_select()624   st_select_lex* first_select()
625   {
626     return reinterpret_cast<st_select_lex*>(slave);
627   }
next_unit()628   st_select_lex_unit* next_unit()
629   {
630     return reinterpret_cast<st_select_lex_unit*>(next);
631   }
632   void exclude_level();
633   void exclude_tree();
get_result()634   inline select_result *get_result() { return result; }
635 
636   /* UNION methods */
637   bool prepare(THD *thd, select_result *result, ulong additional_options);
638   bool optimize();
639   bool exec();
640   bool explain();
641   bool cleanup();
642   bool cleanup_level();
unclean()643   inline void unclean() { cleaned= 0; }
644   void reinit_exec_mechanism();
645 
646   void print(String *str, enum_query_type query_type);
647 
648   bool add_fake_select_lex(THD *thd);
649   bool init_prepare_fake_select_lex(THD *thd, bool no_const_tables);
is_prepared()650   inline bool is_prepared() { return prepared; }
651   bool change_result(select_result_interceptor *result,
652                      select_result_interceptor *old_result);
653   void set_limit(st_select_lex *values);
set_thd(THD * thd_arg)654   void set_thd(THD *thd_arg) { thd= thd_arg; }
655   inline bool is_union ();
656 
657   friend void lex_start(THD *thd);
658   friend bool subselect_union_engine::exec();
659 
660   List<Item> *get_unit_column_types();
661   List<Item> *get_field_list();
662 private:
663   void invalidate();
664 };
665 
666 typedef class st_select_lex_unit SELECT_LEX_UNIT;
667 typedef Bounds_checked_array<Item*> Ref_ptr_array;
668 
669 /*
670   SELECT_LEX - store information of parsed SELECT statment
671 */
672 class st_select_lex: public st_select_lex_node
673 {
674 public:
675   Name_resolution_context context;
676   /*
677     Two fields used by semi-join transformations to know when semi-join is
678     possible, and in which condition tree the subquery predicate is located.
679   */
680   enum Resolve_place { RESOLVE_NONE, RESOLVE_JOIN_NEST, RESOLVE_CONDITION,
681                        RESOLVE_HAVING };
682   Resolve_place resolve_place; // Indicates part of query being resolved
683   TABLE_LIST *resolve_nest;    // Used when resolving outer join condition
684   char *db;
685   Item *where, *having;                         /* WHERE & HAVING clauses */
686   Item *prep_where; /* saved WHERE clause for prepared statement processing */
687   Item *prep_having;/* saved HAVING clause for prepared statement processing */
688   /**
689     Saved values of the WHERE and HAVING clauses. Allowed values are:
690      - COND_UNDEF if the condition was not specified in the query or if it
691        has not been optimized yet
692      - COND_TRUE if the condition is always true
693      - COND_FALSE if the condition is impossible
694      - COND_OK otherwise
695   */
696   Item::cond_result cond_value, having_value;
697   /* point on lex in which it was created, used in view subquery detection */
698   LEX *parent_lex;
699   enum olap_type olap;
700   /* FROM clause - points to the beginning of the TABLE_LIST::next_local list. */
701   SQL_I_List<TABLE_LIST>  table_list;
702 
703   /*
704     GROUP BY clause.
705     This list may be mutated during optimization (by remove_const()),
706     so for prepared statements, we keep a copy of the ORDER.next pointers in
707     group_list_ptrs, and re-establish the original list before each execution.
708   */
709   SQL_I_List<ORDER>       group_list;
710   Group_list_ptrs        *group_list_ptrs;
711 
712   /**
713     List of fields & expressions.
714 
715     SELECT: Fields and expressions in the SELECT list.
716     UPDATE: Fields in the SET clause.
717   */
718   List<Item>          item_list;
719   List<String>        interval_list;
720   bool	              is_item_list_lookup;
721   /*
722     Usualy it is pointer to ftfunc_list_alloc, but in union used to create fake
723     select_lex for calling mysql_select under results of union
724   */
725   List<Item_func_match> *ftfunc_list;
726   List<Item_func_match> ftfunc_list_alloc;
727   JOIN *join; /* after JOIN::prepare it is pointer to corresponding JOIN */
728   List<TABLE_LIST> top_join_list; /* join list of the top level          */
729   List<TABLE_LIST> *join_list;    /* list for the currently parsed join  */
730   TABLE_LIST *embedding;          /* table embedding to the above list   */
731   /// List of semi-join nests generated for this query block
732   List<TABLE_LIST> sj_nests;
733   //Dynamic_array<TABLE_LIST*> sj_nests; psergey-5:
734   /*
735     Beginning of the list of leaves in a FROM clause, where the leaves
736     inlcude all base tables including view tables. The tables are connected
737     by TABLE_LIST::next_leaf, so leaf_tables points to the left-most leaf.
738   */
739   TABLE_LIST *leaf_tables;
740   /**
741     SELECT_LEX type enum
742   */
743   enum type_enum {
744     SLT_NONE= 0,
745     SLT_PRIMARY,
746     SLT_SIMPLE,
747     SLT_DERIVED,
748     SLT_SUBQUERY,
749     SLT_UNION,
750     SLT_UNION_RESULT,
751     SLT_MATERIALIZED,
752   // Total:
753     SLT_total ///< fake type, total number of all valid types
754   // Don't insert new types below this line!
755   };
756 
757   /*
758     ORDER BY clause.
759     This list may be mutated during optimization (by remove_const()),
760     so for prepared statements, we keep a copy of the ORDER.next pointers in
761     order_list_ptrs, and re-establish the original list before each execution.
762   */
763   SQL_I_List<ORDER> order_list;
764   Group_list_ptrs *order_list_ptrs;
765 
766   SQL_I_List<ORDER> gorder_list;
767   Item *select_limit, *offset_limit;  /* LIMIT clause parameters */
768 
769   /// Array of pointers to top elements of all_fields list
770   Ref_ptr_array ref_pointer_array;
771 
772   /// Number of derived tables and views
773   uint derived_table_count;
774   /// Number of materialized derived tables and views
775   uint materialized_table_count;
776   /// Number of partitioned tables
777   uint partitioned_table_count;
778   /*
779     number of items in select_list and HAVING clause used to get number
780     bigger then can be number of entries that will be added to all item
781     list during split_sum_func
782   */
783   uint select_n_having_items;
784   uint cond_count;    /* number of arguments of and/or/xor in where/having/on */
785   uint between_count; /* number of between predicates in where/having/on      */
786   uint max_equal_elems; /* maximal number of elements in multiple equalities  */
787   /*
788     Number of fields used in select list or where clause of current select
789     and all inner subselects.
790   */
791   uint select_n_where_fields;
792   enum_parsing_place parsing_place; /* where we are parsing expression */
793   bool with_sum_func;   /* sum function indicator */
794 
795   ulong table_join_options;
796   uint in_sum_expr;
797   uint select_number; /* number of select (used for EXPLAIN) */
798   /**
799     Nesting level of query block, outer-most query block has level 0,
800     its subqueries have level 1, etc. @see also sql/item_sum.h.
801   */
802   int nest_level;
803   /* Circularly linked list of sum func in nested selects */
804   Item_sum *inner_sum_func_list;
805   uint with_wild; /* item list contain '*' */
806   bool  braces;   	/* SELECT ... UNION (SELECT ... ) <- this braces */
807   /* TRUE when having fix field called in processing of this SELECT */
808   bool having_fix_field;
809   /* TRUE when GROUP BY fix field called in processing of this SELECT */
810   bool group_fix_field;
811   /* List of references to fields referenced from inner selects */
812   List<Item_outer_ref> inner_refs_list;
813   /* Number of Item_sum-derived objects in this SELECT */
814   uint n_sum_items;
815   /* Number of Item_sum-derived objects in children and descendant SELECTs */
816   uint n_child_sum_items;
817 
818   /* explicit LIMIT clause was used */
819   bool explicit_limit;
820   /*
821     there are subquery in HAVING clause => we can't close tables before
822     query processing end even if we use temporary table
823   */
824   bool subquery_in_having;
825   /*
826     This variable is required to ensure proper work of subqueries and
827     stored procedures. Generally, one should use the states of
828     Query_arena to determine if it's a statement prepare or first
829     execution of a stored procedure. However, in case when there was an
830     error during the first execution of a stored procedure, the SP body
831     is not expelled from the SP cache. Therefore, a deeply nested
832     subquery might be left unoptimized. So we need this per-subquery
833     variable to inidicate the optimization/execution state of every
834     subquery. Prepared statements work OK in that regard, as in
835     case of an error during prepare the PS is not created.
836   */
837   bool first_execution;
838   bool first_natural_join_processing;
839   bool first_cond_optimization;
840   /* do not wrap view fields with Item_ref */
841   bool no_wrap_view_item;
842   /* exclude this select from check of unique_table() */
843   bool exclude_from_table_unique_test;
844   /* List of table columns which are not under an aggregate function */
845   List<Item_field> non_agg_fields;
846 
847   /// @See cur_pos_in_all_fields below
848   static const int ALL_FIELDS_UNDEF_POS= INT_MIN;
849 
850   /**
851      Used only for ONLY_FULL_GROUP_BY.
852      When we call fix_fields(), this member should be set as follows:
853      - if the item should honour ONLY_FULL_GROUP_BY (i.e. is in the SELECT
854      list or is a hidden ORDER BY item), cur_pos_in_all_fields is the position
855      of the item in join->all_fields with this convention: position of the
856      first item of the SELECT list is 0; item before this (in direction of the
857      front) has position -1, whereas item after has position 1.
858      - otherwise, cur_pos_in_all_fields is ALL_FIELDS_UNDEF_POS.
859   */
860   int cur_pos_in_all_fields;
861 
862   List<udf_func>     udf_list;                  /* udf function calls stack */
863 
864   /*
865     This is a copy of the original JOIN USING list that comes from
866     the parser. The parser :
867       1. Sets the natural_join of the second TABLE_LIST in the join
868          and the st_select_lex::prev_join_using.
869       2. Makes a parent TABLE_LIST and sets its is_natural_join/
870        join_using_fields members.
871       3. Uses the wrapper TABLE_LIST as a table in the upper level.
872     We cannot assign directly to join_using_fields in the parser because
873     at stage (1.) the parent TABLE_LIST is not constructed yet and
874     the assignment will override the JOIN USING fields of the lower level
875     joins on the right.
876   */
877   List<String> *prev_join_using;
878   /**
879     The set of those tables whose fields are referenced in the select list of
880     this select level.
881   */
882   table_map select_list_tables;
883   /// First select_lex removed as part of some transformation, or NULL
884   st_select_lex *removed_select;
885 
886   void init_query();
887   void init_select();
888   st_select_lex_unit* master_unit();
first_inner_unit()889   st_select_lex_unit* first_inner_unit()
890   {
891     return (st_select_lex_unit*) slave;
892   }
893   st_select_lex* outer_select();
next_select()894   st_select_lex* next_select() { return (st_select_lex*) next; }
895 
last_select()896   st_select_lex* last_select()
897   {
898     st_select_lex* mylast= this;
899     for (; mylast->next_select(); mylast= mylast->next_select())
900     {}
901     return mylast;
902   }
903 
next_select_in_list()904   st_select_lex* next_select_in_list()
905   {
906     return (st_select_lex*) link_next;
907   }
next_select_in_list_addr()908   st_select_lex_node** next_select_in_list_addr()
909   {
910     return &link_next;
911   }
912 
913   /// @return true if query block references full-text functions
has_ft_funcs()914   bool has_ft_funcs() const
915   { return ftfunc_list->elements > 0; }
916 
917   void invalidate();
918   void mark_as_dependent(st_select_lex *last);
919 
920   bool set_braces(bool value);
921   bool inc_in_sum_expr();
922   uint get_in_sum_expr();
923 
924   bool add_item_to_list(THD *thd, Item *item);
925   bool add_group_to_list(THD *thd, Item *item, bool asc);
926   bool add_ftfunc_to_list(Item_func_match *func);
927   bool add_order_to_list(THD *thd, Item *item, bool asc);
928   bool add_gorder_to_list(THD *thd, Item *item, bool asc);
929   TABLE_LIST* add_table_to_list(THD *thd, Table_ident *table,
930 				LEX_STRING *alias,
931 				ulong table_options,
932 				thr_lock_type flags= TL_UNLOCK,
933                                 enum_mdl_type mdl_type= MDL_SHARED_READ,
934 				List<Index_hint> *hints= 0,
935                                 List<String> *partition_names= 0,
936                                 LEX_STRING *option= 0);
937   TABLE_LIST* get_table_list();
938   bool init_nested_join(THD *thd);
939   TABLE_LIST *end_nested_join(THD *thd);
940   TABLE_LIST *nest_last_join(THD *thd);
941   void add_joined_table(TABLE_LIST *table);
942   TABLE_LIST *convert_right_join();
943   List<Item>* get_item_list();
944   ulong get_table_join_options();
945   void set_lock_for_tables(thr_lock_type lock_type);
init_order()946   inline void init_order()
947   {
948     order_list.elements= 0;
949     order_list.first= 0;
950     order_list.next= &order_list.first;
951   }
952   /*
953     This method created for reiniting LEX in mysql_admin_table() and can be
954     used only if you are going remove all SELECT_LEX & units except belonger
955     to LEX (LEX::unit & LEX::select, for other purposes there are
956     SELECT_LEX_UNIT::exclude_level & SELECT_LEX_UNIT::exclude_tree
957   */
cut_subtree()958   void cut_subtree() { slave= 0; }
959   bool test_limit();
960 
961   friend void lex_start(THD *thd);
st_select_lex()962   st_select_lex() : group_list_ptrs(NULL), order_list_ptrs(NULL),
963     n_sum_items(0), n_child_sum_items(0),
964     cur_pos_in_all_fields(ALL_FIELDS_UNDEF_POS)
965   {}
make_empty_select()966   void make_empty_select()
967   {
968     init_query();
969     init_select();
970   }
971   bool setup_ref_array(THD *thd, uint order_group_num);
972   void print(THD *thd, String *str, enum_query_type query_type);
973   static void print_order(String *str,
974                           ORDER *order,
975                           enum_query_type query_type);
976   void print_limit(THD *thd, String *str, enum_query_type query_type);
977   void fix_prepare_information(THD *thd, Item **conds, Item **having_conds);
978   /*
979     Destroy the used execution plan (JOIN) of this subtree (this
980     SELECT_LEX and all nested SELECT_LEXes and SELECT_LEX_UNITs).
981   */
982   bool cleanup();
983   bool cleanup_level();
984   /*
985     Recursively cleanup the join of this select lex and of all nested
986     select lexes.
987   */
988   void cleanup_all_joins(bool full);
989 
990   void set_index_hint_type(enum index_hint_type type, index_clause_map clause);
991 
992   /*
993    Add a index hint to the tagged list of hints. The type and clause of the
994    hint will be the current ones (set by set_index_hint())
995   */
996   bool add_index_hint (THD *thd, char *str, uint length);
997 
998   /* make a list to hold index hints */
999   void alloc_index_hints (THD *thd);
1000   /* read and clear the index hints */
pop_index_hints(void)1001   List<Index_hint>* pop_index_hints(void)
1002   {
1003     List<Index_hint> *hints= index_hints;
1004     index_hints= NULL;
1005     return hints;
1006   }
1007 
clear_index_hints(void)1008   void clear_index_hints(void) { index_hints= NULL; }
1009   bool handle_derived(LEX *lex, bool (*processor)(THD*, LEX*, TABLE_LIST*));
is_part_of_union()1010   bool is_part_of_union() { return master_unit()->is_union(); }
1011 
1012   /*
1013     For MODE_ONLY_FULL_GROUP_BY we need to maintain two flags:
1014      - Non-aggregated fields are used in this select.
1015      - Aggregate functions are used in this select.
1016     In MODE_ONLY_FULL_GROUP_BY only one of these may be true.
1017   */
non_agg_field_used()1018   bool non_agg_field_used() const { return m_non_agg_field_used; }
agg_func_used()1019   bool agg_func_used()      const { return m_agg_func_used; }
1020 
set_non_agg_field_used(bool val)1021   void set_non_agg_field_used(bool val) { m_non_agg_field_used= val; }
set_agg_func_used(bool val)1022   void set_agg_func_used(bool val)      { m_agg_func_used= val; }
1023 
1024   /// Lookup for SELECT_LEX type
1025   type_enum type(const THD *thd);
1026 
1027   /// Lookup for a type string
get_type_str(const THD * thd)1028   const char *get_type_str(const THD *thd) { return type_str[type(thd)]; }
get_type_str(type_enum type)1029   static const char *get_type_str(type_enum type) { return type_str[type]; }
1030 
is_dependent()1031   bool is_dependent() const { return uncacheable & UNCACHEABLE_DEPENDENT; }
is_cacheable()1032   bool is_cacheable() const
1033   {
1034     // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
1035     return !(uncacheable & ~UNCACHEABLE_EXPLAIN);
1036   }
1037   bool is_in_select_list(Item *cand);
1038 private:
1039   bool m_non_agg_field_used;
1040   bool m_agg_func_used;
1041 
1042   /* current index hint kind. used in filling up index_hints */
1043   enum index_hint_type current_index_hint_type;
1044   index_clause_map current_index_hint_clause;
1045   /* a list of USE/FORCE/IGNORE INDEX */
1046   List<Index_hint> *index_hints;
1047 
1048   static const char *type_str[SLT_total];
1049 };
1050 typedef class st_select_lex SELECT_LEX;
1051 
is_union()1052 inline bool st_select_lex_unit::is_union ()
1053 {
1054   return first_select()->next_select() &&
1055     first_select()->next_select()->linkage == UNION_TYPE;
1056 }
1057 
1058 /// Utility RAII class to save/modify/restore a Resolve_place
1059 class Switch_resolve_place
1060 {
1061 public:
Switch_resolve_place(SELECT_LEX::Resolve_place * rp_ptr,SELECT_LEX::Resolve_place new_rp,bool apply)1062   Switch_resolve_place(SELECT_LEX::Resolve_place *rp_ptr,
1063                        SELECT_LEX::Resolve_place new_rp,
1064                        bool apply)
1065     : rp(NULL), saved_rp()
1066   {
1067     if (apply)
1068     {
1069       rp= rp_ptr;
1070       saved_rp= *rp;
1071       *rp= new_rp;
1072     }
1073   }
~Switch_resolve_place()1074   ~Switch_resolve_place()
1075   {
1076     if (rp)
1077       *rp= saved_rp;
1078   }
1079 private:
1080   SELECT_LEX::Resolve_place *rp;
1081   SELECT_LEX::Resolve_place saved_rp;
1082 };
1083 
1084 
1085 typedef struct struct_slave_connection
1086 {
1087   char *user;
1088   char *password;
1089   char *plugin_auth;
1090   char *plugin_dir;
1091 
1092   void reset();
1093 } LEX_SLAVE_CONNECTION;
1094 
1095 struct st_sp_chistics
1096 {
1097   LEX_STRING comment;
1098   enum enum_sp_suid_behaviour suid;
1099   bool detistic;
1100   enum enum_sp_data_access daccess;
1101 };
1102 
1103 extern const LEX_STRING null_lex_str;
1104 extern const LEX_STRING empty_lex_str;
1105 extern const LEX_CSTRING null_lex_cstr;
1106 extern const LEX_CSTRING empty_lex_cstr;
1107 
1108 struct st_trg_chistics
1109 {
1110   enum trg_action_time_type action_time;
1111   enum trg_event_type event;
1112 };
1113 
1114 extern sys_var *trg_new_row_fake_var;
1115 
1116 enum xa_option_words {XA_NONE, XA_JOIN, XA_RESUME, XA_ONE_PHASE,
1117                       XA_SUSPEND, XA_FOR_MIGRATE};
1118 
1119 extern const LEX_STRING null_lex_str;
1120 
1121 class Sroutine_hash_entry;
1122 
1123 /*
1124   Class representing list of all tables used by statement and other
1125   information which is necessary for opening and locking its tables,
1126   like SQL command for this statement.
1127 
1128   Also contains information about stored functions used by statement
1129   since during its execution we may have to add all tables used by its
1130   stored functions/triggers to this list in order to pre-open and lock
1131   them.
1132 
1133   Also used by LEX::reset_n_backup/restore_backup_query_tables_list()
1134   methods to save and restore this information.
1135 */
1136 
1137 class Query_tables_list
1138 {
1139 public:
1140   /**
1141     SQL command for this statement. Part of this class since the
1142     process of opening and locking tables for the statement needs
1143     this information to determine correct type of lock for some of
1144     the tables.
1145   */
1146   enum_sql_command sql_command;
1147   /* Global list of all tables used by this statement */
1148   TABLE_LIST *query_tables;
1149   /* Pointer to next_global member of last element in the previous list. */
1150   TABLE_LIST **query_tables_last;
1151   /*
1152     If non-0 then indicates that query requires prelocking and points to
1153     next_global member of last own element in query table list (i.e. last
1154     table which was not added to it as part of preparation to prelocking).
1155     0 - indicates that this query does not need prelocking.
1156   */
1157   TABLE_LIST **query_tables_own_last;
1158   /*
1159     Set of stored routines called by statement.
1160     (Note that we use lazy-initialization for this hash).
1161   */
1162   enum { START_SROUTINES_HASH_SIZE= 16 };
1163   HASH sroutines;
1164   /*
1165     List linking elements of 'sroutines' set. Allows you to add new elements
1166     to this set as you iterate through the list of existing elements.
1167     'sroutines_list_own_last' is pointer to ::next member of last element of
1168     this list which represents routine which is explicitly used by query.
1169     'sroutines_list_own_elements' number of explicitly used routines.
1170     We use these two members for restoring of 'sroutines_list' to the state
1171     in which it was right after query parsing.
1172   */
1173   SQL_I_List<Sroutine_hash_entry> sroutines_list;
1174   Sroutine_hash_entry **sroutines_list_own_last;
1175   uint sroutines_list_own_elements;
1176 
1177   /**
1178     Locking state of tables in this particular statement.
1179 
1180     If we under LOCK TABLES or in prelocked mode we consider tables
1181     for the statement to be "locked" if there was a call to lock_tables()
1182     (which called handler::start_stmt()) for tables of this statement
1183     and there was no matching close_thread_tables() call.
1184 
1185     As result this state may differ significantly from one represented
1186     by Open_tables_state::lock/locked_tables_mode more, which are always
1187     "on" under LOCK TABLES or in prelocked mode.
1188   */
1189   enum enum_lock_tables_state {
1190     LTS_NOT_LOCKED = 0,
1191     LTS_LOCKED
1192   };
1193   enum_lock_tables_state lock_tables_state;
is_query_tables_locked()1194   bool is_query_tables_locked()
1195   {
1196     return (lock_tables_state == LTS_LOCKED);
1197   }
1198 
1199   /**
1200     Number of tables which were open by open_tables() and to be locked
1201     by lock_tables().
1202     Note that we set this member only in some cases, when this value
1203     needs to be passed from open_tables() to lock_tables() which are
1204     separated by some amount of code.
1205   */
1206   uint table_count;
1207 
1208   /*
1209     These constructor and destructor serve for creation/destruction
1210     of Query_tables_list instances which are used as backup storage.
1211   */
Query_tables_list()1212   Query_tables_list() {}
~Query_tables_list()1213   ~Query_tables_list() {}
1214 
1215   /* Initializes (or resets) Query_tables_list object for "real" use. */
1216   void reset_query_tables_list(bool init);
1217   void destroy_query_tables_list();
set_query_tables_list(Query_tables_list * state)1218   void set_query_tables_list(Query_tables_list *state)
1219   {
1220     *this= *state;
1221   }
1222 
1223   /*
1224     Direct addition to the list of query tables.
1225     If you are using this function, you must ensure that the table
1226     object, in particular table->db member, is initialized.
1227   */
add_to_query_tables(TABLE_LIST * table)1228   void add_to_query_tables(TABLE_LIST *table)
1229   {
1230     *(table->prev_global= query_tables_last)= table;
1231     query_tables_last= &table->next_global;
1232   }
requires_prelocking()1233   bool requires_prelocking()
1234   {
1235     return MY_TEST(query_tables_own_last);
1236   }
mark_as_requiring_prelocking(TABLE_LIST ** tables_own_last)1237   void mark_as_requiring_prelocking(TABLE_LIST **tables_own_last)
1238   {
1239     query_tables_own_last= tables_own_last;
1240   }
1241   /* Return pointer to first not-own table in query-tables or 0 */
first_not_own_table()1242   TABLE_LIST* first_not_own_table()
1243   {
1244     return ( query_tables_own_last ? *query_tables_own_last : 0);
1245   }
chop_off_not_own_tables()1246   void chop_off_not_own_tables()
1247   {
1248     if (query_tables_own_last)
1249     {
1250       *query_tables_own_last= 0;
1251       query_tables_last= query_tables_own_last;
1252       query_tables_own_last= 0;
1253     }
1254   }
1255 
1256   /** Return a pointer to the last element in query table list. */
last_table()1257   TABLE_LIST *last_table()
1258   {
1259     /* Don't use offsetof() macro in order to avoid warnings. */
1260     return query_tables ?
1261            (TABLE_LIST*) ((char*) query_tables_last -
1262                           ((char*) &(query_tables->next_global) -
1263                            (char*) query_tables)) :
1264            0;
1265   }
1266 
1267   /**
1268     Enumeration listing of all types of unsafe statement.
1269 
1270     @note The order of elements of this enumeration type must
1271     correspond to the order of the elements of the @c explanations
1272     array defined in the body of @c THD::issue_unsafe_warnings.
1273   */
1274   enum enum_binlog_stmt_unsafe {
1275     /**
1276       SELECT..LIMIT is unsafe because the set of rows returned cannot
1277       be predicted.
1278     */
1279     BINLOG_STMT_UNSAFE_LIMIT= 0,
1280     /**
1281       INSERT DELAYED is unsafe because the time when rows are inserted
1282       cannot be predicted.
1283     */
1284     BINLOG_STMT_UNSAFE_INSERT_DELAYED,
1285     /**
1286       Access to log tables is unsafe because slave and master probably
1287       log different things.
1288     */
1289     BINLOG_STMT_UNSAFE_SYSTEM_TABLE,
1290     /**
1291       Inserting into an autoincrement column in a stored routine is unsafe.
1292       Even with just one autoincrement column, if the routine is invoked more than
1293       once slave is not guaranteed to execute the statement graph same way as
1294       the master.
1295       And since it's impossible to estimate how many times a routine can be invoked at
1296       the query pre-execution phase (see lock_tables), the statement is marked
1297       pessimistically unsafe.
1298     */
1299     BINLOG_STMT_UNSAFE_AUTOINC_COLUMNS,
1300     /**
1301       Using a UDF (user-defined function) is unsafe.
1302     */
1303     BINLOG_STMT_UNSAFE_UDF,
1304     /**
1305       Using most system variables is unsafe, because slave may run
1306       with different options than master.
1307     */
1308     BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE,
1309     /**
1310       Using some functions is unsafe (e.g., UUID).
1311     */
1312     BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION,
1313 
1314     /**
1315       Mixing transactional and non-transactional statements are unsafe if
1316       non-transactional reads or writes are occur after transactional
1317       reads or writes inside a transaction.
1318     */
1319     BINLOG_STMT_UNSAFE_NONTRANS_AFTER_TRANS,
1320 
1321     /**
1322       Mixing self-logging and non-self-logging engines in a statement
1323       is unsafe.
1324     */
1325     BINLOG_STMT_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
1326 
1327     /**
1328       Statements that read from both transactional and non-transactional
1329       tables and write to any of them are unsafe.
1330     */
1331     BINLOG_STMT_UNSAFE_MIXED_STATEMENT,
1332 
1333     /**
1334       INSERT...IGNORE SELECT is unsafe because which rows are ignored depends
1335       on the order that rows are retrieved by SELECT. This order cannot be
1336       predicted and may differ on master and the slave.
1337     */
1338     BINLOG_STMT_UNSAFE_INSERT_IGNORE_SELECT,
1339 
1340     /**
1341       INSERT...SELECT...UPDATE is unsafe because which rows are updated depends
1342       on the order that rows are retrieved by SELECT. This order cannot be
1343       predicted and may differ on master and the slave.
1344     */
1345     BINLOG_STMT_UNSAFE_INSERT_SELECT_UPDATE,
1346 
1347     /**
1348      Query that writes to a table with auto_inc column after selecting from
1349      other tables are unsafe as the order in which the rows are retrieved by
1350      select may differ on master and slave.
1351     */
1352     BINLOG_STMT_UNSAFE_WRITE_AUTOINC_SELECT,
1353 
1354     /**
1355       INSERT...REPLACE SELECT is unsafe because which rows are replaced depends
1356       on the order that rows are retrieved by SELECT. This order cannot be
1357       predicted and may differ on master and the slave.
1358     */
1359     BINLOG_STMT_UNSAFE_REPLACE_SELECT,
1360 
1361     /**
1362       CREATE TABLE... IGNORE... SELECT is unsafe because which rows are ignored
1363       depends on the order that rows are retrieved by SELECT. This order cannot
1364       be predicted and may differ on master and the slave.
1365     */
1366     BINLOG_STMT_UNSAFE_CREATE_IGNORE_SELECT,
1367 
1368     /**
1369       CREATE TABLE...REPLACE... SELECT is unsafe because which rows are replaced
1370       depends on the order that rows are retrieved from SELECT. This order
1371       cannot be predicted and may differ on master and the slave
1372     */
1373     BINLOG_STMT_UNSAFE_CREATE_REPLACE_SELECT,
1374 
1375     /**
1376       CREATE TABLE...SELECT on a table with auto-increment column is unsafe
1377       because which rows are replaced depends on the order that rows are
1378       retrieved from SELECT. This order cannot be predicted and may differ on
1379       master and the slave
1380     */
1381     BINLOG_STMT_UNSAFE_CREATE_SELECT_AUTOINC,
1382 
1383     /**
1384       UPDATE...IGNORE is unsafe because which rows are ignored depends on the
1385       order that rows are updated. This order cannot be predicted and may differ
1386       on master and the slave.
1387     */
1388     BINLOG_STMT_UNSAFE_UPDATE_IGNORE,
1389 
1390     /**
1391       INSERT... ON DUPLICATE KEY UPDATE on a table with more than one
1392       UNIQUE KEYS  is unsafe.
1393     */
1394     BINLOG_STMT_UNSAFE_INSERT_TWO_KEYS,
1395 
1396     /**
1397        INSERT into auto-inc field which is not the first part in composed
1398        primary key.
1399     */
1400     BINLOG_STMT_UNSAFE_AUTOINC_NOT_FIRST,
1401 
1402     /* The last element of this enumeration type. */
1403     BINLOG_STMT_UNSAFE_COUNT
1404   };
1405   /**
1406     This has all flags from 0 (inclusive) to BINLOG_STMT_FLAG_COUNT
1407     (exclusive) set.
1408   */
1409   static const int BINLOG_STMT_UNSAFE_ALL_FLAGS=
1410     ((1 << BINLOG_STMT_UNSAFE_COUNT) - 1);
1411 
1412   /**
1413     Maps elements of enum_binlog_stmt_unsafe to error codes.
1414   */
1415   static const int binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT];
1416 
1417   /**
1418     Determine if this statement is marked as unsafe with
1419     specific type
1420 
1421     @retval false if the statement is not marked as unsafe.
1422     @retval true if it is.
1423   */
is_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type)1424   inline bool is_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type) const {
1425     return ((binlog_stmt_flags & (1U << unsafe_type)) != 0);
1426   }
1427 
1428   /**
1429     Determine if this statement is marked as unsafe.
1430 
1431     @retval 0 if the statement is not marked as unsafe.
1432     @retval nonzero if the statement is marked as unsafe.
1433   */
is_stmt_unsafe()1434   inline bool is_stmt_unsafe() const {
1435     return get_stmt_unsafe_flags() != 0;
1436   }
1437 
is_stmt_unsafe(enum_binlog_stmt_unsafe unsafe)1438   inline bool is_stmt_unsafe(enum_binlog_stmt_unsafe unsafe)
1439   {
1440     return binlog_stmt_flags & (1 << unsafe);
1441   }
1442 
1443   /**
1444     Flag the current (top-level) statement as unsafe.
1445     The flag will be reset after the statement has finished.
1446 
1447     @param unsafe_type The type of unsafety: one of the @c
1448     BINLOG_STMT_FLAG_UNSAFE_* flags in @c enum_binlog_stmt_flag.
1449   */
set_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type)1450   inline void set_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type) {
1451     DBUG_ENTER("set_stmt_unsafe");
1452     DBUG_ASSERT(unsafe_type >= 0 && unsafe_type < BINLOG_STMT_UNSAFE_COUNT);
1453     binlog_stmt_flags|= (1U << unsafe_type);
1454     DBUG_VOID_RETURN;
1455   }
1456 
1457   /**
1458     Set the bits of binlog_stmt_flags determining the type of
1459     unsafeness of the current statement.  No existing bits will be
1460     cleared, but new bits may be set.
1461 
1462     @param flags A binary combination of zero or more bits, (1<<flag)
1463     where flag is a member of enum_binlog_stmt_unsafe.
1464   */
set_stmt_unsafe_flags(uint32 flags)1465   inline void set_stmt_unsafe_flags(uint32 flags) {
1466     DBUG_ENTER("set_stmt_unsafe_flags");
1467     DBUG_ASSERT((flags & ~BINLOG_STMT_UNSAFE_ALL_FLAGS) == 0);
1468     binlog_stmt_flags|= flags;
1469     DBUG_VOID_RETURN;
1470   }
1471 
1472   /**
1473     Return a binary combination of all unsafe warnings for the
1474     statement.  If the statement has been marked as unsafe by the
1475     'flag' member of enum_binlog_stmt_unsafe, then the return value
1476     from this function has bit (1<<flag) set to 1.
1477   */
get_stmt_unsafe_flags()1478   inline uint32 get_stmt_unsafe_flags() const {
1479     DBUG_ENTER("get_stmt_unsafe_flags");
1480     DBUG_RETURN(binlog_stmt_flags & BINLOG_STMT_UNSAFE_ALL_FLAGS);
1481   }
1482 
1483   /**
1484     Mark the current statement as safe; i.e., clear all bits in
1485     binlog_stmt_flags that correspond to elements of
1486     enum_binlog_stmt_unsafe.
1487   */
clear_stmt_unsafe()1488   inline void clear_stmt_unsafe() {
1489     DBUG_ENTER("clear_stmt_unsafe");
1490     binlog_stmt_flags&= ~BINLOG_STMT_UNSAFE_ALL_FLAGS;
1491     DBUG_VOID_RETURN;
1492   }
1493 
1494   /**
1495     Determine if this statement is a row injection.
1496 
1497     @retval 0 if the statement is not a row injection
1498     @retval nonzero if the statement is a row injection
1499   */
is_stmt_row_injection()1500   inline bool is_stmt_row_injection() const {
1501     return binlog_stmt_flags &
1502       (1U << (BINLOG_STMT_UNSAFE_COUNT + BINLOG_STMT_TYPE_ROW_INJECTION));
1503   }
1504 
1505   /**
1506     Flag the statement as a row injection.  A row injection is either
1507     a BINLOG statement, or a row event in the relay log executed by
1508     the slave SQL thread.
1509   */
set_stmt_row_injection()1510   inline void set_stmt_row_injection() {
1511     DBUG_ENTER("set_stmt_row_injection");
1512     binlog_stmt_flags|=
1513       (1U << (BINLOG_STMT_UNSAFE_COUNT + BINLOG_STMT_TYPE_ROW_INJECTION));
1514     DBUG_VOID_RETURN;
1515   }
1516 
1517   enum enum_stmt_accessed_table
1518   {
1519     /*
1520        If a transactional table is about to be read. Note that
1521        a write implies a read.
1522     */
1523     STMT_READS_TRANS_TABLE= 0,
1524     /*
1525        If a non-transactional table is about to be read. Note that
1526        a write implies a read.
1527     */
1528     STMT_READS_NON_TRANS_TABLE,
1529     /*
1530        If a temporary transactional table is about to be read. Note
1531        that a write implies a read.
1532     */
1533     STMT_READS_TEMP_TRANS_TABLE,
1534     /*
1535        If a temporary non-transactional table is about to be read. Note
1536       that a write implies a read.
1537     */
1538     STMT_READS_TEMP_NON_TRANS_TABLE,
1539     /*
1540        If a transactional table is about to be updated.
1541     */
1542     STMT_WRITES_TRANS_TABLE,
1543     /*
1544        If a non-transactional table is about to be updated.
1545     */
1546     STMT_WRITES_NON_TRANS_TABLE,
1547     /*
1548        If a temporary transactional table is about to be updated.
1549     */
1550     STMT_WRITES_TEMP_TRANS_TABLE,
1551     /*
1552        If a temporary non-transactional table is about to be updated.
1553     */
1554     STMT_WRITES_TEMP_NON_TRANS_TABLE,
1555     /*
1556       The last element of the enumeration. Please, if necessary add
1557       anything before this.
1558     */
1559     STMT_ACCESS_TABLE_COUNT
1560   };
1561 
1562 #ifndef DBUG_OFF
stmt_accessed_table_string(enum_stmt_accessed_table accessed_table)1563   static inline const char *stmt_accessed_table_string(enum_stmt_accessed_table accessed_table)
1564   {
1565     switch (accessed_table)
1566     {
1567       case STMT_READS_TRANS_TABLE:
1568          return "STMT_READS_TRANS_TABLE";
1569       break;
1570       case STMT_READS_NON_TRANS_TABLE:
1571         return "STMT_READS_NON_TRANS_TABLE";
1572       break;
1573       case STMT_READS_TEMP_TRANS_TABLE:
1574         return "STMT_READS_TEMP_TRANS_TABLE";
1575       break;
1576       case STMT_READS_TEMP_NON_TRANS_TABLE:
1577         return "STMT_READS_TEMP_NON_TRANS_TABLE";
1578       break;
1579       case STMT_WRITES_TRANS_TABLE:
1580         return "STMT_WRITES_TRANS_TABLE";
1581       break;
1582       case STMT_WRITES_NON_TRANS_TABLE:
1583         return "STMT_WRITES_NON_TRANS_TABLE";
1584       break;
1585       case STMT_WRITES_TEMP_TRANS_TABLE:
1586         return "STMT_WRITES_TEMP_TRANS_TABLE";
1587       break;
1588       case STMT_WRITES_TEMP_NON_TRANS_TABLE:
1589         return "STMT_WRITES_TEMP_NON_TRANS_TABLE";
1590       break;
1591       case STMT_ACCESS_TABLE_COUNT:
1592       default:
1593         DBUG_ASSERT(0);
1594       break;
1595     }
1596     MY_ASSERT_UNREACHABLE();
1597     return "";
1598   }
1599 #endif  /* DBUG */
1600 
1601   #define BINLOG_DIRECT_ON 0xF0    /* unsafe when
1602                                       --binlog-direct-non-trans-updates
1603                                       is ON */
1604 
1605   #define BINLOG_DIRECT_OFF 0xF    /* unsafe when
1606                                       --binlog-direct-non-trans-updates
1607                                       is OFF */
1608 
1609   #define TRX_CACHE_EMPTY 0x33     /* unsafe when trx-cache is empty */
1610 
1611   #define TRX_CACHE_NOT_EMPTY 0xCC /* unsafe when trx-cache is not empty */
1612 
1613   #define IL_LT_REPEATABLE 0xAA    /* unsafe when < ISO_REPEATABLE_READ */
1614 
1615   #define IL_GTE_REPEATABLE 0x55   /* unsafe when >= ISO_REPEATABLE_READ */
1616 
1617   /**
1618     Sets the type of table that is about to be accessed while executing a
1619     statement.
1620 
1621     @param accessed_table Enumeration type that defines the type of table,
1622                            e.g. temporary, transactional, non-transactional.
1623   */
set_stmt_accessed_table(enum_stmt_accessed_table accessed_table)1624   inline void set_stmt_accessed_table(enum_stmt_accessed_table accessed_table)
1625   {
1626     DBUG_ENTER("LEX::set_stmt_accessed_table");
1627 
1628     DBUG_ASSERT(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT);
1629     stmt_accessed_table_flag |= (1U << accessed_table);
1630 
1631     DBUG_VOID_RETURN;
1632   }
1633 
1634   /**
1635     Checks if a type of table is about to be accessed while executing a
1636     statement.
1637 
1638     @param accessed_table Enumeration type that defines the type of table,
1639            e.g. temporary, transactional, non-transactional.
1640 
1641     @return
1642       @retval TRUE  if the type of the table is about to be accessed
1643       @retval FALSE otherwise
1644   */
stmt_accessed_table(enum_stmt_accessed_table accessed_table)1645   inline bool stmt_accessed_table(enum_stmt_accessed_table accessed_table)
1646   {
1647     DBUG_ENTER("LEX::stmt_accessed_table");
1648 
1649     DBUG_ASSERT(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT);
1650 
1651     DBUG_RETURN((stmt_accessed_table_flag & (1U << accessed_table)) != 0);
1652   }
1653 
1654   /*
1655     Checks if a mixed statement is unsafe.
1656 
1657 
1658     @param in_multi_stmt_transaction_mode defines if there is an on-going
1659            multi-transactional statement.
1660     @param binlog_direct defines if --binlog-direct-non-trans-updates is
1661            active.
1662     @param trx_cache_is_not_empty defines if the trx-cache is empty or not.
1663     @param trx_isolation defines the isolation level.
1664 
1665     @return
1666       @retval TRUE if the mixed statement is unsafe
1667       @retval FALSE otherwise
1668   */
is_mixed_stmt_unsafe(bool in_multi_stmt_transaction_mode,bool binlog_direct,bool trx_cache_is_not_empty,uint tx_isolation)1669   inline bool is_mixed_stmt_unsafe(bool in_multi_stmt_transaction_mode,
1670                                    bool binlog_direct,
1671                                    bool trx_cache_is_not_empty,
1672                                    uint tx_isolation)
1673   {
1674     bool unsafe= FALSE;
1675 
1676     if (in_multi_stmt_transaction_mode)
1677     {
1678        uint condition=
1679          (binlog_direct ? BINLOG_DIRECT_ON : BINLOG_DIRECT_OFF) &
1680          (trx_cache_is_not_empty ? TRX_CACHE_NOT_EMPTY : TRX_CACHE_EMPTY) &
1681          (tx_isolation >= ISO_REPEATABLE_READ ? IL_GTE_REPEATABLE : IL_LT_REPEATABLE);
1682 
1683       unsafe= (binlog_unsafe_map[stmt_accessed_table_flag] & condition);
1684 
1685 #if !defined(DBUG_OFF)
1686       DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("RESULT %02X %02X %02X\n", condition,
1687               binlog_unsafe_map[stmt_accessed_table_flag],
1688               (binlog_unsafe_map[stmt_accessed_table_flag] & condition)));
1689 
1690       int type_in= 0;
1691       for (; type_in < STMT_ACCESS_TABLE_COUNT; type_in++)
1692       {
1693         if (stmt_accessed_table((enum_stmt_accessed_table) type_in))
1694           DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("ACCESSED %s ",
1695                   stmt_accessed_table_string((enum_stmt_accessed_table) type_in)));
1696       }
1697 #endif
1698     }
1699 
1700     if (stmt_accessed_table(STMT_WRITES_NON_TRANS_TABLE) &&
1701       stmt_accessed_table(STMT_READS_TRANS_TABLE) &&
1702       tx_isolation < ISO_REPEATABLE_READ)
1703       unsafe= TRUE;
1704     else if (stmt_accessed_table(STMT_WRITES_TEMP_NON_TRANS_TABLE) &&
1705       stmt_accessed_table(STMT_READS_TRANS_TABLE) &&
1706       tx_isolation < ISO_REPEATABLE_READ)
1707       unsafe= TRUE;
1708 
1709     return(unsafe);
1710   }
1711 
1712   /**
1713     true if the parsed tree contains references to stored procedures
1714     or functions, false otherwise
1715   */
uses_stored_routines()1716   bool uses_stored_routines() const
1717   { return sroutines_list.elements != 0; }
1718 
1719 private:
1720 
1721   /**
1722     Enumeration listing special types of statements.
1723 
1724     Currently, the only possible type is ROW_INJECTION.
1725   */
1726   enum enum_binlog_stmt_type {
1727     /**
1728       The statement is a row injection (i.e., either a BINLOG
1729       statement or a row event executed by the slave SQL thread).
1730     */
1731     BINLOG_STMT_TYPE_ROW_INJECTION = 0,
1732 
1733     /** The last element of this enumeration type. */
1734     BINLOG_STMT_TYPE_COUNT
1735   };
1736 
1737   /**
1738     Bit field indicating the type of statement.
1739 
1740     There are two groups of bits:
1741 
1742     - The low BINLOG_STMT_UNSAFE_COUNT bits indicate the types of
1743       unsafeness that the current statement has.
1744 
1745     - The next BINLOG_STMT_TYPE_COUNT bits indicate if the statement
1746       is of some special type.
1747 
1748     This must be a member of LEX, not of THD: each stored procedure
1749     needs to remember its unsafeness state between calls and each
1750     stored procedure has its own LEX object (but no own THD object).
1751   */
1752   uint32 binlog_stmt_flags;
1753 
1754   /**
1755     Bit field that determines the type of tables that are about to be
1756     be accessed while executing a statement.
1757   */
1758   uint32 stmt_accessed_table_flag;
1759 };
1760 
1761 
1762 /*
1763   st_parsing_options contains the flags for constructions that are
1764   allowed in the current statement.
1765 */
1766 
1767 struct st_parsing_options
1768 {
1769   bool allows_variable;
1770   bool allows_select_into;
1771   bool allows_select_procedure;
1772   bool allows_derived;
1773 
st_parsing_optionsst_parsing_options1774   st_parsing_options() { reset(); }
1775   void reset();
1776 };
1777 
1778 
1779 /**
1780   The state of the lexical parser, when parsing comments.
1781 */
1782 enum enum_comment_state
1783 {
1784   /**
1785     Not parsing comments.
1786   */
1787   NO_COMMENT,
1788   /**
1789     Parsing comments that need to be preserved.
1790     Typically, these are user comments '/' '*' ... '*' '/'.
1791   */
1792   PRESERVE_COMMENT,
1793   /**
1794     Parsing comments that need to be discarded.
1795     Typically, these are special comments '/' '*' '!' ... '*' '/',
1796     or '/' '*' '!' 'M' 'M' 'm' 'm' 'm' ... '*' '/', where the comment
1797     markers should not be expanded.
1798   */
1799   DISCARD_COMMENT
1800 };
1801 
1802 
1803 /**
1804   @brief This class represents the character input stream consumed during
1805   lexical analysis.
1806 
1807   In addition to consuming the input stream, this class performs some
1808   comment pre processing, by filtering out out of bound special text
1809   from the query input stream.
1810   Two buffers, with pointers inside each buffers, are maintained in
1811   parallel. The 'raw' buffer is the original query text, which may
1812   contain out-of-bound comments. The 'cpp' (for comments pre processor)
1813   is the pre-processed buffer that contains only the query text that
1814   should be seen once out-of-bound data is removed.
1815 */
1816 
1817 class Lex_input_stream
1818 {
1819 public:
Lex_input_stream()1820   Lex_input_stream()
1821   {
1822   }
1823 
~Lex_input_stream()1824   ~Lex_input_stream()
1825   {
1826   }
1827 
1828   /**
1829      Object initializer. Must be called before usage.
1830 
1831      @retval FALSE OK
1832      @retval TRUE  Error
1833   */
1834   bool init(THD *thd, char *buff, unsigned int length);
1835 
1836   void reset(char *buff, unsigned int length);
1837 
1838   /**
1839     Set the echo mode.
1840 
1841     When echo is true, characters parsed from the raw input stream are
1842     preserved. When false, characters parsed are silently ignored.
1843     @param echo the echo mode.
1844   */
set_echo(bool echo)1845   void set_echo(bool echo)
1846   {
1847     m_echo= echo;
1848   }
1849 
save_in_comment_state()1850   void save_in_comment_state()
1851   {
1852     m_echo_saved= m_echo;
1853     in_comment_saved= in_comment;
1854   }
1855 
restore_in_comment_state()1856   void restore_in_comment_state()
1857   {
1858     m_echo= m_echo_saved;
1859     in_comment= in_comment_saved;
1860   }
1861 
1862   /**
1863     Skip binary from the input stream.
1864     @param n number of bytes to accept.
1865   */
skip_binary(int n)1866   void skip_binary(int n)
1867   {
1868     if (m_echo)
1869     {
1870       memcpy(m_cpp_ptr, m_ptr, n);
1871       m_cpp_ptr += n;
1872     }
1873     m_ptr += n;
1874   }
1875 
1876   /**
1877     Get a character, and advance in the stream.
1878     @return the next character to parse.
1879   */
yyGet()1880   unsigned char yyGet()
1881   {
1882     char c= *m_ptr++;
1883     if (m_echo)
1884       *m_cpp_ptr++ = c;
1885     return c;
1886   }
1887 
1888   /**
1889     Get the last character accepted.
1890     @return the last character accepted.
1891   */
yyGetLast()1892   unsigned char yyGetLast()
1893   {
1894     return m_ptr[-1];
1895   }
1896 
1897   /**
1898     Look at the next character to parse, but do not accept it.
1899   */
yyPeek()1900   unsigned char yyPeek()
1901   {
1902     return m_ptr[0];
1903   }
1904 
1905   /**
1906     Look ahead at some character to parse.
1907     @param n offset of the character to look up
1908   */
yyPeekn(int n)1909   unsigned char yyPeekn(int n)
1910   {
1911     return m_ptr[n];
1912   }
1913 
1914   /**
1915     Cancel the effect of the last yyGet() or yySkip().
1916     Note that the echo mode should not change between calls to yyGet / yySkip
1917     and yyUnget. The caller is responsible for ensuring that.
1918   */
yyUnget()1919   void yyUnget()
1920   {
1921     m_ptr--;
1922     if (m_echo)
1923       m_cpp_ptr--;
1924   }
1925 
1926   /**
1927     Accept a character, by advancing the input stream.
1928   */
yySkip()1929   void yySkip()
1930   {
1931     if (m_echo)
1932       *m_cpp_ptr++ = *m_ptr++;
1933     else
1934       m_ptr++;
1935   }
1936 
1937   /**
1938     Accept multiple characters at once.
1939     @param n the number of characters to accept.
1940   */
yySkipn(int n)1941   void yySkipn(int n)
1942   {
1943     if (m_echo)
1944     {
1945       memcpy(m_cpp_ptr, m_ptr, n);
1946       m_cpp_ptr += n;
1947     }
1948     m_ptr += n;
1949   }
1950 
1951   /**
1952     Puts a character back into the stream, canceling
1953     the effect of the last yyGet() or yySkip().
1954     Note that the echo mode should not change between calls
1955     to unput, get, or skip from the stream.
1956   */
yyUnput(char ch)1957   char *yyUnput(char ch)
1958   {
1959     *--m_ptr= ch;
1960     if (m_echo)
1961       m_cpp_ptr--;
1962     return m_ptr;
1963   }
1964 
1965   /**
1966     Inject a character into the pre-processed stream.
1967 
1968     Note, this function is used to inject a space instead of multi-character
1969     C-comment. Thus there is no boundary checks here (basically, we replace
1970     N-chars by 1-char here).
1971   */
cpp_inject(char ch)1972   char *cpp_inject(char ch)
1973   {
1974     *m_cpp_ptr= ch;
1975     return ++m_cpp_ptr;
1976   }
1977 
1978   /**
1979     End of file indicator for the query text to parse.
1980     @return true if there are no more characters to parse
1981   */
eof()1982   bool eof()
1983   {
1984     return (m_ptr >= m_end_of_query);
1985   }
1986 
1987   /**
1988     End of file indicator for the query text to parse.
1989     @param n number of characters expected
1990     @return true if there are less than n characters to parse
1991   */
eof(int n)1992   bool eof(int n)
1993   {
1994     return ((m_ptr + n) >= m_end_of_query);
1995   }
1996 
1997   /** Get the raw query buffer. */
get_buf()1998   const char *get_buf()
1999   {
2000     return m_buf;
2001   }
2002 
2003   /** Get the pre-processed query buffer. */
get_cpp_buf()2004   const char *get_cpp_buf()
2005   {
2006     return m_cpp_buf;
2007   }
2008 
2009   /** Get the end of the raw query buffer. */
get_end_of_query()2010   const char *get_end_of_query()
2011   {
2012     return m_end_of_query;
2013   }
2014 
2015   /** Mark the stream position as the start of a new token. */
start_token()2016   void start_token()
2017   {
2018     m_tok_start_prev= m_tok_start;
2019     m_tok_start= m_ptr;
2020     m_tok_end= m_ptr;
2021 
2022     m_cpp_tok_start_prev= m_cpp_tok_start;
2023     m_cpp_tok_start= m_cpp_ptr;
2024     m_cpp_tok_end= m_cpp_ptr;
2025   }
2026 
2027   /**
2028     Adjust the starting position of the current token.
2029     This is used to compensate for starting whitespace.
2030   */
restart_token()2031   void restart_token()
2032   {
2033     m_tok_start= m_ptr;
2034     m_cpp_tok_start= m_cpp_ptr;
2035   }
2036 
2037   /** Get the token start position, in the raw buffer. */
get_tok_start()2038   const char *get_tok_start()
2039   {
2040     return m_tok_start;
2041   }
2042 
2043   /** Get the token start position, in the pre-processed buffer. */
get_cpp_tok_start()2044   const char *get_cpp_tok_start()
2045   {
2046     return m_cpp_tok_start;
2047   }
2048 
2049   /** Get the token end position, in the raw buffer. */
get_tok_end()2050   const char *get_tok_end()
2051   {
2052     return m_tok_end;
2053   }
2054 
2055   /** Get the token end position, in the pre-processed buffer. */
get_cpp_tok_end()2056   const char *get_cpp_tok_end()
2057   {
2058     return m_cpp_tok_end;
2059   }
2060 
2061   /** Get the previous token start position, in the raw buffer. */
get_tok_start_prev()2062   const char *get_tok_start_prev()
2063   {
2064     return m_tok_start_prev;
2065   }
2066 
2067   /** Get the current stream pointer, in the raw buffer. */
get_ptr()2068   const char *get_ptr()
2069   {
2070     return m_ptr;
2071   }
2072 
2073   /** Get the current stream pointer, in the pre-processed buffer. */
get_cpp_ptr()2074   const char *get_cpp_ptr()
2075   {
2076     return m_cpp_ptr;
2077   }
2078 
2079   /** Get the length of the current token, in the raw buffer. */
yyLength()2080   uint yyLength()
2081   {
2082     /*
2083       The assumption is that the lexical analyser is always 1 character ahead,
2084       which the -1 account for.
2085     */
2086     DBUG_ASSERT(m_ptr > m_tok_start);
2087     return (uint) ((m_ptr - m_tok_start) - 1);
2088   }
2089 
2090   /** Get the utf8-body string. */
get_body_utf8_str()2091   const char *get_body_utf8_str()
2092   {
2093     return m_body_utf8;
2094   }
2095 
2096   /** Get the utf8-body length. */
get_body_utf8_length()2097   uint get_body_utf8_length()
2098   {
2099     return (uint) (m_body_utf8_ptr - m_body_utf8);
2100   }
2101 
2102   void body_utf8_start(THD *thd, const char *begin_ptr);
2103   void body_utf8_append(const char *ptr);
2104   void body_utf8_append(const char *ptr, const char *end_ptr);
2105   void body_utf8_append_literal(THD *thd,
2106                                 const LEX_STRING *txt,
2107                                 const CHARSET_INFO *txt_cs,
2108                                 const char *end_ptr);
2109 
2110   /** Current thread. */
2111   THD *m_thd;
2112 
2113   /** Current line number. */
2114   uint yylineno;
2115 
2116   /** Length of the last token parsed. */
2117   uint yytoklen;
2118 
2119   /** Interface with bison, value of the last token parsed. */
2120   LEX_YYSTYPE yylval;
2121 
2122   /**
2123     LALR(2) resolution, look ahead token.
2124     Value of the next token to return, if any,
2125     or -1, if no token was parsed in advance.
2126     Note: 0 is a legal token, and represents YYEOF.
2127   */
2128   int lookahead_token;
2129 
2130   /** LALR(2) resolution, value of the look ahead token.*/
2131   LEX_YYSTYPE lookahead_yylval;
2132 
2133   void add_digest_token(uint token, LEX_YYSTYPE yylval);
2134 
2135   void reduce_digest_token(uint token_left, uint token_right);
2136 
2137 private:
2138   /** Pointer to the current position in the raw input stream. */
2139   char *m_ptr;
2140 
2141   /** Starting position of the last token parsed, in the raw buffer. */
2142   const char *m_tok_start;
2143 
2144   /** Ending position of the previous token parsed, in the raw buffer. */
2145   const char *m_tok_end;
2146 
2147   /** End of the query text in the input stream, in the raw buffer. */
2148   const char *m_end_of_query;
2149 
2150   /** Starting position of the previous token parsed, in the raw buffer. */
2151   const char *m_tok_start_prev;
2152 
2153   /** Begining of the query text in the input stream, in the raw buffer. */
2154   const char *m_buf;
2155 
2156   /** Length of the raw buffer. */
2157   uint m_buf_length;
2158 
2159   /** Echo the parsed stream to the pre-processed buffer. */
2160   bool m_echo;
2161   bool m_echo_saved;
2162 
2163   /** Pre-processed buffer. */
2164   char *m_cpp_buf;
2165 
2166   /** Pointer to the current position in the pre-processed input stream. */
2167   char *m_cpp_ptr;
2168 
2169   /**
2170     Starting position of the last token parsed,
2171     in the pre-processed buffer.
2172   */
2173   const char *m_cpp_tok_start;
2174 
2175   /**
2176     Starting position of the previous token parsed,
2177     in the pre-procedded buffer.
2178   */
2179   const char *m_cpp_tok_start_prev;
2180 
2181   /**
2182     Ending position of the previous token parsed,
2183     in the pre-processed buffer.
2184   */
2185   const char *m_cpp_tok_end;
2186 
2187   /** UTF8-body buffer created during parsing. */
2188   char *m_body_utf8;
2189 
2190   /** Pointer to the current position in the UTF8-body buffer. */
2191   char *m_body_utf8_ptr;
2192 
2193   /**
2194     Position in the pre-processed buffer. The query from m_cpp_buf to
2195     m_cpp_utf_processed_ptr is converted to UTF8-body.
2196   */
2197   const char *m_cpp_utf8_processed_ptr;
2198 
2199 public:
2200 
2201   /** Current state of the lexical analyser. */
2202   enum my_lex_states next_state;
2203 
2204   /**
2205     Position of ';' in the stream, to delimit multiple queries.
2206     This delimiter is in the raw buffer.
2207   */
2208   const char *found_semicolon;
2209 
2210   /** Token character bitmaps, to detect 7bit strings. */
2211   uchar tok_bitmap;
2212 
2213   /** SQL_MODE = IGNORE_SPACE. */
2214   bool ignore_space;
2215 
2216   /**
2217     TRUE if we're parsing a prepared statement: in this mode
2218     we should allow placeholders.
2219   */
2220   bool stmt_prepare_mode;
2221   /**
2222     TRUE if we should allow multi-statements.
2223   */
2224   bool multi_statements;
2225 
2226   /** State of the lexical analyser for comments. */
2227   enum_comment_state in_comment;
2228   enum_comment_state in_comment_saved;
2229 
2230   /**
2231     Starting position of the TEXT_STRING or IDENT in the pre-processed
2232     buffer.
2233 
2234     NOTE: this member must be used within MYSQLlex() function only.
2235   */
2236   const char *m_cpp_text_start;
2237 
2238   /**
2239     Ending position of the TEXT_STRING or IDENT in the pre-processed
2240     buffer.
2241 
2242     NOTE: this member must be used within MYSQLlex() function only.
2243     */
2244   const char *m_cpp_text_end;
2245 
2246   /**
2247     Character set specified by the character-set-introducer.
2248 
2249     NOTE: this member must be used within MYSQLlex() function only.
2250   */
2251   CHARSET_INFO *m_underscore_cs;
2252 
2253   /**
2254     Current statement digest instrumentation.
2255   */
2256   sql_digest_state* m_digest;
2257 };
2258 
2259 
2260 /**
2261   Argument values for PROCEDURE ANALYSE(...)
2262 */
2263 
2264 struct Proc_analyse_params: public Sql_alloc
2265 {
2266   uint max_tree_elements; //< maximum number of distinct values per column
2267   uint max_treemem; //< maximum amount of memory to allocate per column
2268 
Proc_analyse_paramsProc_analyse_params2269   Proc_analyse_params()
2270     : max_tree_elements(256),
2271       max_treemem(8192)
2272   {}
2273 };
2274 
2275 
2276 /* The state of the lex parsing. This is saved in the THD struct */
2277 
2278 struct LEX: public Query_tables_list
2279 {
2280   SELECT_LEX_UNIT unit;                         /* most upper unit */
2281   SELECT_LEX select_lex;                        /* first SELECT_LEX */
2282   /* current SELECT_LEX in parsing */
2283   SELECT_LEX *current_select;
2284   /* list of all SELECT_LEX */
2285   SELECT_LEX *all_selects_list;
2286 
2287   char *length,*dec,*change;
2288   LEX_STRING name;
2289   char *help_arg;
2290   char* to_log;                                 /* For PURGE MASTER LOGS TO */
2291   char* x509_subject,*x509_issuer,*ssl_cipher;
2292   String *wild;
2293   sql_exchange *exchange;
2294   select_result *result;
2295   Item *default_value, *on_update_value;
2296   LEX_STRING comment, ident;
2297   LEX_USER *grant_user;
2298   XID *xid;
2299   THD *thd;
2300 
2301   /* maintain a list of used plugins for this LEX */
2302   DYNAMIC_ARRAY plugins;
2303   plugin_ref plugins_static_buffer[INITIAL_LEX_PLUGIN_LIST_SIZE];
2304 
2305   const CHARSET_INFO *charset;
2306   bool text_string_is_7bit;
2307   /* store original leaf_tables for INSERT SELECT and PS/SP */
2308   TABLE_LIST *leaf_tables_insert;
2309 
2310   /** SELECT of CREATE VIEW statement */
2311   LEX_STRING create_view_select;
2312 
2313   /** Start of 'ON table', in trigger statements.  */
2314   const char* raw_trg_on_table_name_begin;
2315   /** End of 'ON table', in trigger statements. */
2316   const char* raw_trg_on_table_name_end;
2317 
2318   /* Partition info structure filled in by PARTITION BY parse part */
2319   partition_info *part_info;
2320 
2321   /*
2322     The definer of the object being created (view, trigger, stored routine).
2323     I.e. the value of DEFINER clause.
2324   */
2325   LEX_USER *definer;
2326 
2327   List<Key_part_spec> col_list;
2328   List<Key_part_spec> ref_list;
2329   /*
2330     A list of strings is maintained to store the SET clause command user strings
2331     which are specified in load data operation.  This list will be used
2332     during the reconstruction of "load data" statement at the time of writing
2333     to binary log.
2334    */
2335   List<String>        load_set_str_list;
2336   List<String>	      interval_list;
2337   List<LEX_USER>      users_list;
2338   List<LEX_COLUMN>    columns;
2339   List<Item>	      *insert_list,field_list,value_list,update_list;
2340   List<List_item>     many_values;
2341   List<set_var_base>  var_list;
2342   List<Item_func_set_user_var> set_var_list; // in-query assignment list
2343   List<Item_param>    param_list;
2344   List<LEX_STRING>    view_list; // view list (list of field names in view)
2345   /*
2346     A stack of name resolution contexts for the query. This stack is used
2347     at parse time to set local name resolution contexts for various parts
2348     of a query. For example, in a JOIN ... ON (some_condition) clause the
2349     Items in 'some_condition' must be resolved only against the operands
2350     of the the join, and not against the whole clause. Similarly, Items in
2351     subqueries should be resolved against the subqueries (and outer queries).
2352     The stack is used in the following way: when the parser detects that
2353     all Items in some clause need a local context, it creates a new context
2354     and pushes it on the stack. All newly created Items always store the
2355     top-most context in the stack. Once the parser leaves the clause that
2356     required a local context, the parser pops the top-most context.
2357   */
2358   List<Name_resolution_context> context_stack;
2359   /* true if SET STATEMENT ... FOR ... statement is use, false otherwise */
2360   bool set_statement;
2361   /**
2362     Argument values for PROCEDURE ANALYSE(); is NULL for other queries
2363   */
2364   Proc_analyse_params *proc_analyse;
2365   SQL_I_List<TABLE_LIST> auxiliary_table_list, save_list;
2366   Create_field	      *last_field;
2367   Item_sum *in_sum_func;
2368   udf_func udf;
2369   HA_CHECK_OPT   check_opt;			// check/repair options
2370   HA_CREATE_INFO create_info;
2371   KEY_CREATE_INFO key_create_info;
2372   LEX_MASTER_INFO mi;				// used by CHANGE MASTER
2373   LEX_SLAVE_CONNECTION slave_connection;
2374   LEX_SERVER_OPTIONS server_options;
2375   USER_RESOURCES mqh;
2376   LEX_RESET_SLAVE reset_slave_info;
2377   ulong type;
2378   /*
2379     This variable is used in post-parse stage to declare that sum-functions,
2380     or functions which have sense only if GROUP BY is present, are allowed.
2381     For example in a query
2382     SELECT ... FROM ...WHERE MIN(i) == 1 GROUP BY ... HAVING MIN(i) > 2
2383     MIN(i) in the WHERE clause is not allowed in the opposite to MIN(i)
2384     in the HAVING clause. Due to possible nesting of select construct
2385     the variable can contain 0 or 1 for each nest level.
2386   */
2387   nesting_map allow_sum_func;
2388 
2389   Sql_cmd *m_sql_cmd;
2390 
2391   /*
2392     Usually `expr` rule of yacc is quite reused but some commands better
2393     not support subqueries which comes standard with this rule, like
2394     KILL, HA_READ, CREATE/ALTER EVENT etc. Set this to `false` to get
2395     syntax error back.
2396   */
2397   bool expr_allows_subselect;
2398 
2399   enum SSL_type ssl_type;			/* defined in violite.h */
2400   enum enum_duplicates duplicates;
2401   enum enum_tx_isolation tx_isolation;
2402   enum xa_option_words xa_opt;
2403   enum enum_var_type option_type;
2404   enum enum_view_create_mode create_view_mode;
2405   enum enum_drop_mode drop_mode;
2406 
2407   uint profile_query_id;
2408   uint profile_options;
2409   uint uint_geom_type;
2410   uint grant, grant_tot_col, which_columns;
2411   enum Foreign_key::fk_match_opt fk_match_option;
2412   enum Foreign_key::fk_option fk_update_opt;
2413   enum Foreign_key::fk_option fk_delete_opt;
2414   uint slave_thd_opt, start_transaction_opt;
2415   int nest_level;
2416   uint8 describe;
2417   /*
2418     A flag that indicates what kinds of derived tables are present in the
2419     query (0 if no derived tables, otherwise a combination of flags
2420     DERIVED_SUBQUERY and DERIVED_VIEW).
2421   */
2422   uint8 derived_tables;
2423   uint8 create_view_algorithm;
2424   uint8 create_view_check;
2425   uint8 context_analysis_only;
2426   bool drop_if_exists, drop_temporary, local_file, one_shot_set;
2427   bool autocommit;
2428   bool verbose, no_write_to_binlog;
2429 
2430   enum enum_yes_no_unknown tx_chain, tx_release;
2431   bool safe_to_cache_query;
2432   bool subqueries, ignore;
2433   st_parsing_options parsing_options;
2434   Alter_info alter_info;
2435   /*
2436     For CREATE TABLE statement last element of table list which is not
2437     part of SELECT or LIKE part (i.e. either element for table we are
2438     creating or last of tables referenced by foreign keys).
2439   */
2440   TABLE_LIST *create_last_non_select_table;
2441   /* Prepared statements SQL syntax:*/
2442   LEX_STRING prepared_stmt_name; /* Statement name (in all queries) */
2443   /*
2444     Prepared statement query text or name of variable that holds the
2445     prepared statement (in PREPARE ... queries)
2446   */
2447   LEX_STRING prepared_stmt_code;
2448   /* If true, prepared_stmt_code is a name of variable that holds the query */
2449   bool prepared_stmt_code_is_varref;
2450   /* Names of user variables holding parameters (in EXECUTE) */
2451   List<LEX_STRING> prepared_stmt_params;
2452   sp_head *sphead;
2453   sp_name *spname;
2454   bool sp_lex_in_use;	/* Keep track on lex usage in SPs for error handling */
2455   bool all_privileges;
2456   bool proxy_priv;
2457   bool is_change_password;
2458   /*
2459     Temporary variable to distinguish SET PASSWORD command from others
2460     SQLCOM_SET_OPTION commands. Should be removed when WL#6409 is
2461     introduced.
2462   */
2463   bool is_set_password_sql;
2464   bool contains_plaintext_password;
2465 
2466   /*
2467     Compression dictionary name (in column definition)
2468     CREATE TABLE t1(
2469       ...
2470       <column_name> BLOB COLUMN_FORMAT COMPRESSED
2471         WITH COMPRESSION_DICTIONARY <dict>
2472       ...
2473     );
2474   */
2475   LEX_CSTRING zip_dict_name;
2476 
2477 private:
2478   bool m_broken; ///< see mark_broken()
2479   /// Current SP parsing context.
2480   /// @see also sp_head::m_root_parsing_ctx.
2481   sp_pcontext *sp_current_parsing_ctx;
2482 
2483 public:
2484 
is_brokenLEX2485   bool is_broken() const { return m_broken; }
2486   /**
2487      Certain permanent transformations (like in2exists), if they fail, may
2488      leave the LEX in an inconsistent state. They should call the
2489      following function, so that this LEX is not reused by another execution.
2490 
2491      @todo If lex_start () were a member function of LEX, the "broken"
2492      argument could always be "true" and thus could be removed.
2493   */
2494   void mark_broken(bool broken= true)
2495   {
2496     if (broken)
2497     {
2498       /*
2499         "OPEN <cursor>" cannot be re-prepared if the cursor uses no tables
2500         ("SELECT FROM DUAL"). Indeed in that case cursor_query is left empty
2501         in constructions of sp_instr_cpush, and thus
2502         sp_lex_instr::parse_expr() cannot re-prepare. So we mark the statement
2503         as broken only if tables are used.
2504       */
2505       if (is_metadata_used())
2506         m_broken= true;
2507     }
2508     else
2509       m_broken= false;
2510   }
2511 
get_sp_current_parsing_ctxLEX2512   sp_pcontext *get_sp_current_parsing_ctx()
2513   { return sp_current_parsing_ctx; }
2514 
set_sp_current_parsing_ctxLEX2515   void set_sp_current_parsing_ctx(sp_pcontext *ctx)
2516   { sp_current_parsing_ctx= ctx; }
2517 
2518   /// Check if the current statement uses meta-data (uses a table or a stored
2519   /// routine).
is_metadata_usedLEX2520   bool is_metadata_used() const
2521   { return query_tables != NULL || sroutines.records > 0; }
2522 
2523 public:
2524   st_sp_chistics sp_chistics;
2525 
2526   Event_parse_data *event_parse_data;
2527 
2528   bool only_view;       /* used for SHOW CREATE TABLE/VIEW */
2529   /*
2530     field_list was created for view and should be removed before PS/SP
2531     rexecuton
2532   */
2533   bool empty_field_list_on_rset;
2534   /*
2535     view created to be run from definer (standard behaviour)
2536   */
2537   uint8 create_view_suid;
2538 
2539   /*
2540     stmt_definition_begin is intended to point to the next word after
2541     DEFINER-clause in the following statements:
2542       - CREATE TRIGGER (points to "TRIGGER");
2543       - CREATE PROCEDURE (points to "PROCEDURE");
2544       - CREATE FUNCTION (points to "FUNCTION" or "AGGREGATE");
2545       - CREATE EVENT (points to "EVENT")
2546 
2547     This pointer is required to add possibly omitted DEFINER-clause to the
2548     DDL-statement before dumping it to the binlog.
2549 
2550     keyword_delayed_begin_offset is the offset to the beginning of the DELAYED
2551     keyword in INSERT DELAYED statement. keyword_delayed_end_offset is the
2552     offset to the character right after the DELAYED keyword.
2553   */
2554   union {
2555     const char *stmt_definition_begin;
2556     uint keyword_delayed_begin_offset;
2557   };
2558 
2559   union {
2560     const char *stmt_definition_end;
2561     uint keyword_delayed_end_offset;
2562   };
2563 
2564   /**
2565     During name resolution search only in the table list given by
2566     Name_resolution_context::first_name_resolution_table and
2567     Name_resolution_context::last_name_resolution_table
2568     (see Item_field::fix_fields()).
2569   */
2570   bool use_only_table_context;
2571 
2572   /*
2573     Reference to a struct that contains information in various commands
2574     to add/create/drop/change table spaces.
2575   */
2576   st_alter_tablespace *alter_tablespace_info;
2577 
2578   bool escape_used;
2579   bool is_lex_started; /* If lex_start() did run. For debugging. */
2580   /// Set to true while resolving values in ON DUPLICATE KEY UPDATE clause
2581   bool in_update_value_clause;
2582 
2583   /*
2584     The set of those tables whose fields are referenced in all subqueries
2585     of the query.
2586     TODO: possibly this it is incorrect to have used tables in LEX because
2587     with subquery, it is not clear what does the field mean. To fix this
2588     we should aggregate used tables information for selected expressions
2589     into the select_lex.
2590   */
2591   table_map  used_tables;
2592 
2593   class Explain_format *explain_format;
2594 
2595   LEX();
2596 
~LEXLEX2597   virtual ~LEX()
2598   {
2599     destroy_query_tables_list();
2600     plugin_unlock_list(NULL, (plugin_ref *)plugins.buffer, plugins.elements);
2601     delete_dynamic(&plugins);
2602   }
2603 
is_ps_or_view_context_analysisLEX2604   inline bool is_ps_or_view_context_analysis()
2605   {
2606     return (context_analysis_only &
2607             (CONTEXT_ANALYSIS_ONLY_PREPARE |
2608              CONTEXT_ANALYSIS_ONLY_VIEW));
2609   }
2610 
uncacheableLEX2611   inline void uncacheable(uint8 cause)
2612   {
2613     safe_to_cache_query= 0;
2614 
2615     /*
2616       There are no sense to mark select_lex and union fields of LEX,
2617       but we should merk all subselects as uncacheable from current till
2618       most upper
2619     */
2620     SELECT_LEX *sl;
2621     SELECT_LEX_UNIT *un;
2622     for (sl= current_select, un= sl->master_unit();
2623 	 un != &unit;
2624 	 sl= sl->outer_select(), un= sl->master_unit())
2625     {
2626       sl->uncacheable|= cause;
2627       un->uncacheable|= cause;
2628     }
2629   }
2630   void set_trg_event_type_for_tables();
2631 
2632   TABLE_LIST *unlink_first_table(bool *link_to_local);
2633   void link_first_table_back(TABLE_LIST *first, bool link_to_local);
2634   void first_lists_tables_same();
2635 
2636   bool can_be_merged();
2637   bool can_use_merged();
2638   bool can_not_use_merged();
2639   bool only_view_structure();
2640   bool need_correct_ident();
2641   uint8 get_effective_with_check(TABLE_LIST *view);
2642   /*
2643     Is this update command where 'WHITH CHECK OPTION' clause is important
2644 
2645     SYNOPSIS
2646       LEX::which_check_option_applicable()
2647 
2648     RETURN
2649       TRUE   have to take 'WHITH CHECK OPTION' clause into account
2650       FALSE  'WHITH CHECK OPTION' clause do not need
2651   */
which_check_option_applicableLEX2652   inline bool which_check_option_applicable()
2653   {
2654     switch (sql_command) {
2655     case SQLCOM_UPDATE:
2656     case SQLCOM_UPDATE_MULTI:
2657     case SQLCOM_INSERT:
2658     case SQLCOM_INSERT_SELECT:
2659     case SQLCOM_REPLACE:
2660     case SQLCOM_REPLACE_SELECT:
2661     case SQLCOM_LOAD:
2662       return TRUE;
2663     default:
2664       return FALSE;
2665     }
2666   }
2667 
2668   void cleanup_after_one_table_open();
2669 
push_contextLEX2670   bool push_context(Name_resolution_context *context)
2671   {
2672     return context_stack.push_front(context);
2673   }
2674 
pop_contextLEX2675   void pop_context()
2676   {
2677     context_stack.pop();
2678   }
2679 
2680   bool copy_db_to(char **p_db, size_t *p_db_length) const;
2681 
current_contextLEX2682   Name_resolution_context *current_context()
2683   {
2684     return context_stack.head();
2685   }
2686   /*
2687     Restore the LEX and THD in case of a parse error.
2688   */
2689   static void cleanup_lex_after_parse_error(THD *thd);
2690 
2691   void reset_n_backup_query_tables_list(Query_tables_list *backup);
2692   void restore_backup_query_tables_list(Query_tables_list *backup);
2693 
2694   bool table_or_sp_used();
2695   bool is_partition_management() const;
2696 
2697   /**
2698     @brief check if the statement is a single-level join
2699     @return result of the check
2700       @retval TRUE  The statement doesn't contain subqueries, unions and
2701                     stored procedure calls.
2702       @retval FALSE There are subqueries, UNIONs or stored procedure calls.
2703   */
is_single_level_stmtLEX2704   bool is_single_level_stmt()
2705   {
2706     /*
2707       This check exploits the fact that the last added to all_select_list is
2708       on its top. So select_lex (as the first added) will be at the tail
2709       of the list.
2710     */
2711     if (&select_lex == all_selects_list && !sroutines.records)
2712     {
2713       DBUG_ASSERT(!all_selects_list->next_select_in_list());
2714       return TRUE;
2715     }
2716     return FALSE;
2717   }
2718 };
2719 
2720 
2721 /**
2722   Set_signal_information is a container used in the parsed tree to represent
2723   the collection of assignments to condition items in the SIGNAL and RESIGNAL
2724   statements.
2725 */
2726 class Set_signal_information
2727 {
2728 public:
2729   /** Empty default constructor, use clear() */
Set_signal_information()2730  Set_signal_information() {}
2731 
2732   /** Copy constructor. */
2733   Set_signal_information(const Set_signal_information& set);
2734 
2735   /** Destructor. */
~Set_signal_information()2736   ~Set_signal_information()
2737   {}
2738 
2739   /** Clear all items. */
2740   void clear();
2741 
2742   /**
2743     For each condition item assignment, m_item[] contains the parsed tree
2744     that represents the expression assigned, if any.
2745     m_item[] is an array indexed by Diag_condition_item_name.
2746   */
2747   Item *m_item[LAST_DIAG_SET_PROPERTY+1];
2748 };
2749 
2750 
2751 /**
2752   The internal state of the syntax parser.
2753   This object is only available during parsing,
2754   and is private to the syntax parser implementation (sql_yacc.yy).
2755 */
2756 class Yacc_state
2757 {
2758 public:
Yacc_state()2759   Yacc_state() : yacc_yyss(NULL), yacc_yyvs(NULL) { reset(); }
2760 
reset()2761   void reset()
2762   {
2763     if (yacc_yyss != NULL) {
2764       my_free(yacc_yyss);
2765       yacc_yyss = NULL;
2766     }
2767     if (yacc_yyvs != NULL) {
2768       my_free(yacc_yyvs);
2769       yacc_yyvs = NULL;
2770     }
2771     m_set_signal_info.clear();
2772     m_lock_type= TL_READ_DEFAULT;
2773     m_mdl_type= MDL_SHARED_READ;
2774     m_ha_rkey_mode= HA_READ_KEY_EXACT;
2775   }
2776 
2777   ~Yacc_state();
2778 
2779   /**
2780     Reset part of the state which needs resetting before parsing
2781     substatement.
2782   */
reset_before_substatement()2783   void reset_before_substatement()
2784   {
2785     m_lock_type= TL_READ_DEFAULT;
2786     m_mdl_type= MDL_SHARED_READ;
2787     m_ha_rkey_mode= HA_READ_KEY_EXACT; /* Let us be future-proof. */
2788   }
2789 
2790   /**
2791     Bison internal state stack, yyss, when dynamically allocated using
2792     my_yyoverflow().
2793   */
2794   uchar *yacc_yyss;
2795 
2796   /**
2797     Bison internal semantic value stack, yyvs, when dynamically allocated using
2798     my_yyoverflow().
2799   */
2800   uchar *yacc_yyvs;
2801 
2802   /**
2803     Fragments of parsed tree,
2804     used during the parsing of SIGNAL and RESIGNAL.
2805   */
2806   Set_signal_information m_set_signal_info;
2807 
2808   /**
2809     Type of lock to be used for tables being added to the statement's
2810     table list in table_factor, table_alias_ref, single_multi and
2811     table_wild_one rules.
2812     Statements which use these rules but require lock type different
2813     from one specified by this member have to override it by using
2814     st_select_lex::set_lock_for_tables() method.
2815 
2816     The default value of this member is TL_READ_DEFAULT. The only two
2817     cases in which we change it are:
2818     - When parsing SELECT HIGH_PRIORITY.
2819     - Rule for DELETE. In which we use this member to pass information
2820       about type of lock from delete to single_multi part of rule.
2821 
2822     We should try to avoid introducing new use cases as we would like
2823     to get rid of this member eventually.
2824   */
2825   thr_lock_type m_lock_type;
2826 
2827   /**
2828     The type of requested metadata lock for tables added to
2829     the statement table list.
2830   */
2831   enum_mdl_type m_mdl_type;
2832 
2833   /** Type of condition for key in HANDLER READ statement. */
2834   enum ha_rkey_function m_ha_rkey_mode;
2835 
2836   /*
2837     TODO: move more attributes from the LEX structure here.
2838   */
2839 };
2840 
2841 /**
2842   Input parameters to the parser.
2843 */
2844 struct Parser_input
2845 {
2846   bool m_compute_digest;
2847 
Parser_inputParser_input2848   Parser_input()
2849     : m_compute_digest(false)
2850   {}
2851 };
2852 
2853 /**
2854   Internal state of the parser.
2855   The complete state consist of:
2856   - state data used during lexical parsing,
2857   - state data used during syntactic parsing.
2858 */
2859 class Parser_state
2860 {
2861 public:
Parser_state()2862   Parser_state()
2863     : m_yacc()
2864   {}
2865 
2866   /**
2867      Object initializer. Must be called before usage.
2868 
2869      @retval FALSE OK
2870      @retval TRUE  Error
2871   */
init(THD * thd,char * buff,unsigned int length)2872   bool init(THD *thd, char *buff, unsigned int length)
2873   {
2874     return m_lip.init(thd, buff, length);
2875   }
2876 
~Parser_state()2877   ~Parser_state()
2878   {}
2879 
2880   Parser_input m_input;
2881   Lex_input_stream m_lip;
2882   Yacc_state m_yacc;
2883 
2884   /**
2885     Current performance digest instrumentation.
2886   */
2887   PSI_digest_locker* m_digest_psi;
2888 
reset(char * found_semicolon,unsigned int length)2889   void reset(char *found_semicolon, unsigned int length)
2890   {
2891     m_lip.reset(found_semicolon, length);
2892     m_yacc.reset();
2893   }
2894 };
2895 
2896 extern sql_digest_state *
2897 digest_add_token(sql_digest_state *state, uint token, LEX_YYSTYPE yylval);
2898 
2899 extern sql_digest_state *
2900 digest_reduce_token(sql_digest_state *state, uint token_left, uint token_right);
2901 
2902 struct st_lex_local: public LEX
2903 {
newst_lex_local2904   static void *operator new(size_t size) throw()
2905   {
2906     return sql_alloc(size);
2907   }
newst_lex_local2908   static void *operator new(size_t size, MEM_ROOT *mem_root) throw()
2909   {
2910     return (void*) alloc_root(mem_root, (uint) size);
2911   }
deletest_lex_local2912   static void operator delete(void *ptr,size_t size)
2913   { TRASH(ptr, size); }
deletest_lex_local2914   static void operator delete(void *ptr, MEM_ROOT *mem_root)
2915   { /* Never called */ }
2916 };
2917 
2918 extern void lex_init(void);
2919 extern void lex_free(void);
2920 extern void lex_start(THD *thd);
2921 extern void lex_end(LEX *lex);
2922 extern int MYSQLlex(union YYSTYPE *yylval, class THD *thd);
2923 
2924 extern void trim_whitespace(const CHARSET_INFO *cs, LEX_STRING *str);
2925 
2926 extern bool is_lex_native_function(const LEX_STRING *name);
2927 
2928 /**
2929   @} (End of group Semantic_Analysis)
2930 */
2931 
2932 void my_missing_function_error(const LEX_STRING &token, const char *name);
2933 bool is_keyword(const char *name, uint len);
2934 bool db_is_default_db(const char *db, size_t db_len, const THD *thd);
2935 
2936 #endif /* MYSQL_SERVER */
2937 #endif /* SQL_LEX_INCLUDED */
2938