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