1 /* Copyright (c) 2000, 2021, Oracle and/or its affiliates.
2 
3    This program is free software; you can redistribute it and/or modify
4    it under the terms of the GNU General Public License, version 2.0,
5    as published by the Free Software Foundation.
6 
7    This program is also distributed with certain software (including
8    but not limited to OpenSSL) that is licensed under separate terms,
9    as designated in a particular file or component or in included license
10    documentation.  The authors of MySQL hereby grant you an additional
11    permission to link the program and your derivative works with the
12    separately licensed software that they have included with MySQL.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License, version 2.0, for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
22 
23 /**
24   @defgroup Semantic_Analysis Semantic Analysis
25 */
26 
27 #ifndef SQL_LEX_INCLUDED
28 #define SQL_LEX_INCLUDED
29 
30 #include "my_global.h"
31 #include "mem_root_array.h"           // Mem_root_array
32 #include "prealloced_array.h"         // Prealloced_array
33 #include "thr_lock.h"                 // thr_lock_type
34 #include "violite.h"                  // SSL_type
35 #include "item.h"                     // Name_resolution_context
36 #include "item_subselect.h"           // chooser_compare_func_creator
37 #include "lex_symbol.h"               // LEX_SYMBOL
38 #include "parse_tree_node_base.h"     // enum_parsing_context
39 #include "query_options.h"            // OPTION_NO_CONST_TABLES
40 #include "sql_alloc.h"                // Sql_alloc
41 #include "sql_chars.h"
42 #include "sql_alter.h"                // Alter_info
43 #include "sql_connect.h"              // USER_RESOURCES
44 #include "sql_data_change.h"          // enum_duplicates
45 #include "sql_get_diagnostics.h"      // Diagnostics_information
46 #include "sql_servers.h"              // Server_options
47 #include "sql_signal.h"               // enum_condition_item_name
48 #include "table.h"                    // TABLE_LIST
49 #include "trigger_def.h"              // enum_trigger_action_time_type
50 #include "xa.h"                       // xa_option_words
51 #include "select_lex_visitor.h"
52 #include "parse_tree_hints.h"
53 #include "sql_admin.h"
54 #include <map>
55 
56 #ifdef MYSQL_SERVER
57 #include "item_func.h"                // Cast_target
58 #endif
59 
60 /* YACC and LEX Definitions */
61 
62 /* These may not be declared yet */
63 class Table_ident;
64 class sql_exchange;
65 class sp_head;
66 class sp_name;
67 class sp_instr;
68 class sp_pcontext;
69 class st_alter_tablespace;
70 class partition_info;
71 class Event_parse_data;
72 class set_var_base;
73 class sys_var;
74 class Item_func_match;
75 class File_parser;
76 class Key_part_spec;
77 class Query_result_interceptor;
78 class Item_func;
79 class Sql_cmd;
80 struct sql_digest_state;
81 typedef class st_select_lex SELECT_LEX;
82 
83 const size_t INITIAL_LEX_PLUGIN_LIST_SIZE = 16;
84 class Opt_hints_global;
85 class Opt_hints_qb;
86 
87 #ifdef MYSQL_SERVER
88 /*
89   There are 8 different type of table access so there is no more than
90   combinations 2^8 = 256:
91 
92   . STMT_READS_TRANS_TABLE
93 
94   . STMT_READS_NON_TRANS_TABLE
95 
96   . STMT_READS_TEMP_TRANS_TABLE
97 
98   . STMT_READS_TEMP_NON_TRANS_TABLE
99 
100   . STMT_WRITES_TRANS_TABLE
101 
102   . STMT_WRITES_NON_TRANS_TABLE
103 
104   . STMT_WRITES_TEMP_TRANS_TABLE
105 
106   . STMT_WRITES_TEMP_NON_TRANS_TABLE
107 
108   The unsafe conditions for each combination is represented within a byte
109   and stores the status of the option --binlog-direct-non-trans-updates,
110   whether the trx-cache is empty or not, and whether the isolation level
111   is lower than ISO_REPEATABLE_READ:
112 
113   . option (OFF/ON)
114   . trx-cache (empty/not empty)
115   . isolation (>= ISO_REPEATABLE_READ / < ISO_REPEATABLE_READ)
116 
117   bits 0 : . OFF, . empty, . >= ISO_REPEATABLE_READ
118   bits 1 : . OFF, . empty, . < ISO_REPEATABLE_READ
119   bits 2 : . OFF, . not empty, . >= ISO_REPEATABLE_READ
120   bits 3 : . OFF, . not empty, . < ISO_REPEATABLE_READ
121   bits 4 : . ON, . empty, . >= ISO_REPEATABLE_READ
122   bits 5 : . ON, . empty, . < ISO_REPEATABLE_READ
123   bits 6 : . ON, . not empty, . >= ISO_REPEATABLE_READ
124   bits 7 : . ON, . not empty, . < ISO_REPEATABLE_READ
125 */
126 extern uint binlog_unsafe_map[256];
127 /*
128   Initializes the array with unsafe combinations and its respective
129   conditions.
130 */
131 void binlog_unsafe_map_init();
132 #endif
133 
134 enum enum_yes_no_unknown
135 {
136   TVL_YES, TVL_NO, TVL_UNKNOWN
137 };
138 
139 enum keytype {
140   KEYTYPE_PRIMARY,
141   KEYTYPE_UNIQUE,
142   KEYTYPE_MULTIPLE,
143   KEYTYPE_FULLTEXT,
144   KEYTYPE_SPATIAL,
145   KEYTYPE_FOREIGN
146 };
147 
148 enum enum_ha_read_modes { RFIRST, RNEXT, RPREV, RLAST, RKEY, RNEXT_SAME };
149 
150 enum enum_filetype { FILETYPE_CSV, FILETYPE_XML };
151 
152 enum fk_match_opt { FK_MATCH_UNDEF, FK_MATCH_FULL,
153                     FK_MATCH_PARTIAL, FK_MATCH_SIMPLE};
154 
155 enum fk_option { FK_OPTION_UNDEF, FK_OPTION_RESTRICT, FK_OPTION_CASCADE,
156                  FK_OPTION_SET_NULL, FK_OPTION_NO_ACTION, FK_OPTION_DEFAULT};
157 
158 
159 /**
160   used by the parser to store internal variable name
161 */
162 struct sys_var_with_base
163 {
164   sys_var *var;
165   LEX_STRING base_name;
166 };
167 
168 
169 #define YYSTYPE_IS_DECLARED 1
170 union YYSTYPE;
171 typedef YYSTYPE *LEX_YYSTYPE;
172 
173 // describe/explain types
174 #define DESCRIBE_NONE		0 // Not explain query
175 #define DESCRIBE_NORMAL		1
176 
177 #ifdef MYSQL_SERVER
178 
179 /*
180   If we encounter a diagnostics statement (GET DIAGNOSTICS, or e.g.
181   the old SHOW WARNINGS|ERRORS, or "diagnostics variables" such as
182   @@warning_count | @@error_count, we'll set some hints so this
183   information is not lost. DA_KEEP_UNSPECIFIED is used in LEX constructor to
184   avoid leaving variables uninitialized.
185  */
186 enum enum_keep_diagnostics
187 {
188   DA_KEEP_NOTHING= 0,   /**< keep nothing */
189   DA_KEEP_DIAGNOSTICS,  /**< keep the diagnostics area */
190   DA_KEEP_COUNTS,       /**< keep @@warning_count / @error_count */
191   DA_KEEP_PARSE_ERROR,  /**< keep diagnostics area after parse error */
192   DA_KEEP_UNSPECIFIED   /**< keep semantics is unspecified */
193 };
194 
195 enum enum_sp_suid_behaviour
196 {
197   SP_IS_DEFAULT_SUID= 0,
198   SP_IS_NOT_SUID,
199   SP_IS_SUID
200 };
201 
202 enum enum_sp_data_access
203 {
204   SP_DEFAULT_ACCESS= 0,
205   SP_CONTAINS_SQL,
206   SP_NO_SQL,
207   SP_READS_SQL_DATA,
208   SP_MODIFIES_SQL_DATA
209 };
210 
211 /**
212   enum_sp_type defines type codes of stored programs.
213 
214   Events have the SP_TYPE_PROCEDURE type code.
215 
216   @note these codes are used when dealing with the mysql.proc system table, so
217   they must not be changed.
218 
219   @note the following macros were used previously for the same purpose. Now they
220   are used for ACL only.
221 */
222 enum enum_sp_type
223 {
224   SP_TYPE_FUNCTION= 1,
225   SP_TYPE_PROCEDURE,
226   SP_TYPE_TRIGGER,
227   SP_TYPE_EVENT
228 };
229 
230 /*
231   Values for the type enum. This reflects the order of the enum declaration
232   in the CREATE TABLE command. These values are used to enumerate object types
233   for the ACL statements.
234 
235   These values were also used for enumerating stored program types. However, now
236   enum_sp_type should be used for that instead of them.
237 */
238 #define TYPE_ENUM_FUNCTION  1
239 #define TYPE_ENUM_PROCEDURE 2
240 #define TYPE_ENUM_TRIGGER   3
241 #define TYPE_ENUM_PROXY     4
242 
243 const LEX_STRING sp_data_access_name[]=
244 {
245   { C_STRING_WITH_LEN("") },
246   { C_STRING_WITH_LEN("CONTAINS SQL") },
247   { C_STRING_WITH_LEN("NO SQL") },
248   { C_STRING_WITH_LEN("READS SQL DATA") },
249   { C_STRING_WITH_LEN("MODIFIES SQL DATA") }
250 };
251 
252 #define DERIVED_SUBQUERY	1
253 #define DERIVED_VIEW		2
254 
255 enum enum_view_create_mode
256 {
257   VIEW_CREATE_NEW,		// check that there are not such VIEW/table
258   VIEW_ALTER,			// check that VIEW .frm with such name exists
259   VIEW_CREATE_OR_REPLACE	// check only that there are not such table
260 };
261 
262 enum enum_drop_mode
263 {
264   DROP_DEFAULT, // mode is not specified
265   DROP_CASCADE, // CASCADE option
266   DROP_RESTRICT // RESTRICT option
267 };
268 
269 /* Options to add_table_to_list() */
270 #define TL_OPTION_UPDATING	1
271 #define TL_OPTION_FORCE_INDEX	2
272 #define TL_OPTION_IGNORE_LEAVES 4
273 #define TL_OPTION_ALIAS         8
274 
275 typedef List<Item> List_item;
276 typedef Mem_root_array<ORDER*, true> Group_list_ptrs;
277 
278 
279 /**
280   Structure to hold parameters for CHANGE MASTER, START SLAVE, and STOP SLAVE.
281 
282   Remark: this should not be confused with Master_info (and perhaps
283   would better be renamed to st_lex_replication_info).  Some fields,
284   e.g., delay, are saved in Relay_log_info, not in Master_info.
285 */
286 typedef struct st_lex_master_info
287 {
288   /*
289     The array of IGNORE_SERVER_IDS has a preallocation, and is not expected
290     to grow to any significant size, so no instrumentation.
291   */
st_lex_master_infost_lex_master_info292   st_lex_master_info()
293     : repl_ignore_server_ids(PSI_NOT_INSTRUMENTED)
294   {
295     initialize();
296   }
297   char *host, *user, *password, *log_file_name, *bind_addr;
298   uint port, connect_retry;
299   float heartbeat_period;
300   int sql_delay;
301   ulonglong pos;
302   ulong server_id, retry_count;
303   char *gtid;
304   char* view_id;
305   const char* channel;  // identifier similar to database name
306   enum {UNTIL_SQL_BEFORE_GTIDS= 0, UNTIL_SQL_AFTER_GTIDS} gtid_until_condition;
307   bool until_after_gaps;
308   bool slave_until;
309   bool for_channel;
310 
311   /*
312     Enum is used for making it possible to detect if the user
313     changed variable or if it should be left at old value
314    */
315   enum {LEX_MI_UNCHANGED= 0, LEX_MI_DISABLE, LEX_MI_ENABLE}
316     ssl, ssl_verify_server_cert, heartbeat_opt, repl_ignore_server_ids_opt,
317     retry_count_opt, auto_position, port_opt;
318   char *ssl_key, *ssl_cert, *ssl_ca, *ssl_capath, *ssl_cipher;
319   char *ssl_crl, *ssl_crlpath, *tls_version;
320   char *relay_log_name;
321   ulong relay_log_pos;
322   Prealloced_array<ulong, 2, true> repl_ignore_server_ids;
323 
324   /// Initializes everything to zero/NULL/empty.
325   void initialize();
326   /// Sets all fields to their "unspecified" value.
327   void set_unspecified();
328 private:
329   // Not copyable or assignable.
330   st_lex_master_info(const st_lex_master_info&);
331   st_lex_master_info &operator=(const st_lex_master_info&);
332 } LEX_MASTER_INFO;
333 
334 typedef struct st_lex_reset_slave
335 {
336   bool all;
337 } LEX_RESET_SLAVE;
338 
339 enum sub_select_type
340 {
341   UNSPECIFIED_TYPE,UNION_TYPE, INTERSECT_TYPE,
342   EXCEPT_TYPE, GLOBAL_OPTIONS_TYPE, DERIVED_TABLE_TYPE, OLAP_TYPE
343 };
344 
345 enum olap_type
346 {
347   UNSPECIFIED_OLAP_TYPE, CUBE_TYPE, ROLLUP_TYPE
348 };
349 
350 /*
351   String names used to print a statement with index hints.
352   Keep in sync with index_hint_type.
353 */
354 extern const char * index_hint_type_name[];
355 typedef uchar index_clause_map;
356 
357 /*
358   Bits in index_clause_map : one for each possible FOR clause in
359   USE/FORCE/IGNORE INDEX index hint specification
360 */
361 #define INDEX_HINT_MASK_JOIN  (1)
362 #define INDEX_HINT_MASK_GROUP (1 << 1)
363 #define INDEX_HINT_MASK_ORDER (1 << 2)
364 
365 #define INDEX_HINT_MASK_ALL (INDEX_HINT_MASK_JOIN | INDEX_HINT_MASK_GROUP | \
366                              INDEX_HINT_MASK_ORDER)
367 
368 /* Single element of an USE/FORCE/IGNORE INDEX list specified as a SQL hint  */
369 class Index_hint : public Sql_alloc
370 {
371 public:
372   /* The type of the hint : USE/FORCE/IGNORE */
373   enum index_hint_type type;
374   /* Where the hit applies to. A bitmask of INDEX_HINT_MASK_<place> values */
375   index_clause_map clause;
376   /*
377     The index name. Empty (str=NULL) name represents an empty list
378     USE INDEX () clause
379   */
380   LEX_STRING key_name;
381 
Index_hint(const char * str,uint length)382   Index_hint (const char *str, uint length)
383   {
384     key_name.str= const_cast<char *>(str);
385     key_name.length= length;
386   }
387 
388   void print(THD *thd, String *str);
389 };
390 
391 /*
392   Class st_select_lex_unit represents a query expression.
393   Class st_select_lex represents a query block.
394   A query expression contains one or more query blocks (more than one means
395   that we have a UNION query).
396   These classes are connected as follows:
397    Both classes have a master, a slave, a next and a prev field.
398    For class st_select_lex, master and slave connect to objects of type
399    st_select_lex_unit, whereas for class st_select_lex_unit, they connect
400    to st_select_lex.
401    master is pointer to outer node.
402    slave is pointer to the first inner node
403 
404    neighbors are two st_select_lex or st_select_lex_unit objects on
405    the same level.
406 
407    The structures are linked with the following pointers:
408    - list of neighbors (next/prev) (prev of first element point to slave
409      pointer of outer structure)
410      - For st_select_lex, this is a list of query blocks.
411      - For st_select_lex_unit, this is a list of subqueries.
412 
413    - pointer to outer node (master), which is
414      If this is st_select_lex_unit
415        - pointer to outer select_lex.
416      If this is st_select_lex
417        - pointer to outer st_select_lex_unit.
418 
419    - pointer to inner objects (slave), which is either:
420      If this is an st_select_lex_unit:
421        - first query block that belong to this query expression.
422      If this is an st_select_lex
423        - first query expression that belong to this query block (subqueries).
424 
425    - list of all st_select_lex objects (link_next/link_prev)
426      This is to be used for things like derived tables creation, where we
427      go through this list and create the derived tables.
428 
429    If query expression contain several query blocks (UNION now,
430    INTERSECT etc later) then it has a special select_lex called
431    fake_select_lex. It used for storing global parameters (like ORDER BY,
432    LIMIT) and executing union.
433    Subqueries used in global ORDER BY clause will be attached to this
434    fake_select_lex, which will allow them to correctly resolve fields of
435    the containing UNION and outer selects.
436 
437    For example for following query:
438 
439    select *
440      from table1
441      where table1.field IN (select * from table1_1_1 union
442                             select * from table1_1_2)
443      union
444    select *
445      from table2
446      where table2.field=(select (select f1 from table2_1_1_1_1
447                                    where table2_1_1_1_1.f2=table2_1_1.f3)
448                            from table2_1_1
449                            where table2_1_1.f1=table2.f2)
450      union
451    select * from table3;
452 
453    we will have following structure:
454 
455    select1: (select * from table1 ...)
456    select2: (select * from table2 ...)
457    select3: (select * from table3)
458    select1.1.1: (select * from table1_1_1)
459    ...
460 
461      main unit
462      fake0
463      select1 select2 select3
464      |^^     |^
465     s|||     ||master
466     l|||     |+---------------------------------+
467     a|||     +---------------------------------+|
468     v|||master                         slave   ||
469     e||+-------------------------+             ||
470      V|            neighbor      |             V|
471      unit1.1<+==================>unit1.2       unit2.1
472      fake1.1
473      select1.1.1 select 1.1.2    select1.2.1   select2.1.1
474                                                |^
475                                                ||
476                                                V|
477                                                unit2.1.1.1
478                                                select2.1.1.1.1
479 
480 
481    relation in main unit will be following:
482    (bigger picture for:
483       main unit
484       fake0
485       select1 select2 select3
486    in the above picture)
487 
488          main unit
489          |^^^^|fake_select_lex
490          |||||+--------------------------------------------+
491          ||||+--------------------------------------------+|
492          |||+------------------------------+              ||
493          ||+--------------+                |              ||
494     slave||master         |                |              ||
495          V|      neighbor |       neighbor |        master|V
496          select1<========>select2<========>select3        fake0
497 
498     list of all select_lex will be following (as it will be constructed by
499     parser):
500 
501     select1->select2->select3->select2.1.1->select 2.1.2->select2.1.1.1.1-+
502                                                                           |
503     +---------------------------------------------------------------------+
504     |
505     +->select1.1.1->select1.1.2
506 
507 */
508 
509 
510 struct LEX;
511 class THD;
512 class Query_result;
513 class JOIN;
514 class Query_result_union;
515 
516 /**
517   This class represents a query expression (one query block or
518   several query blocks combined with UNION).
519 */
520 class st_select_lex_unit: public Sql_alloc
521 {
522   /**
523     Intrusive double-linked list of all query expressions
524     immediately contained within the same query block.
525   */
526   st_select_lex_unit *next;
527   st_select_lex_unit **prev;
528 
529   /**
530     The query block wherein this query expression is contained,
531     NULL if the query block is the outer-most one.
532   */
533   SELECT_LEX *master;
534   /// The first query block in this query expression.
535   SELECT_LEX *slave;
536 private:
537   /**
538     Marker for subqueries in WHERE, HAVING, ORDER BY, GROUP BY and
539     SELECT item lists.
540     Must be read/written when holding LOCK_query_plan.
541 
542    See Item_subselect::explain_subquery_checker
543   */
544   enum_parsing_context explain_marker;
545 
546   bool prepared; ///< All query blocks in query expression are prepared
547   bool optimized; ///< All query blocks in query expression are optimized
548   bool executed; ///< Query expression has been executed
549 
550   TABLE_LIST result_table_list;
551   Query_result_union *union_result;
552   TABLE *table; /* temporary table using for appending UNION results */
553   /// Object to which the result for this query expression is sent
554   Query_result *m_query_result;
555 
556 public:
557   /**
558     result of this query can't be cached, bit field, can be :
559       UNCACHEABLE_DEPENDENT
560       UNCACHEABLE_RAND
561       UNCACHEABLE_SIDEEFFECT
562   */
563   uint8 uncacheable;
564 
565   explicit st_select_lex_unit(enum_parsing_context parsing_context);
566 
567   /// @return true for a query expression without UNION or multi-level ORDER
is_simple()568   bool is_simple() const { return !(is_union() || fake_select_lex); }
569 
570   /// Values for st_select_lex_unit::cleaned
571   enum enum_clean_state
572   {
573     UC_DIRTY,     ///< Unit isn't cleaned
574     UC_PART_CLEAN,///< Unit were cleaned, except JOIN and JOIN_TABs were
575                   ///< kept for possible EXPLAIN
576     UC_CLEAN      ///< Unit completely cleaned, all underlying JOINs were
577                   ///< freed
578   };
579   enum_clean_state cleaned; ///< cleanliness state
580 
581   // list of fields which points to temporary table for union
582   List<Item> item_list;
583   /*
584     list of types of items inside union (used for union & derived tables)
585 
586     Item_type_holders from which this list consist may have pointers to Field,
587     pointers is valid only after preparing SELECTS of this unit and before
588     any SELECT of this unit execution
589 
590     TODO:
591     Possibly this member should be protected, and its direct use replaced
592     by get_unit_column_types(). Check the places where it is used.
593   */
594   List<Item> types;
595   /**
596     Pointer to query block containing global parameters for query.
597     Global parameters may include ORDER BY, LIMIT and OFFSET.
598 
599     If this is a union of multiple query blocks, the global parameters are
600     stored in fake_select_lex. If the union doesn't use a temporary table,
601     st_select_lex_unit::prepare() nulls out fake_select_lex, but saves a copy
602     in saved_fake_select_lex in order to preserve the global parameters.
603 
604     If this is not a union, and the query expression has no multi-level
605     ORDER BY/LIMIT, global parameters are in the single query block.
606 
607     @return query block containing the global parameters
608   */
global_parameters()609   inline st_select_lex *global_parameters() const
610   {
611     if (fake_select_lex != NULL)
612       return fake_select_lex;
613     else if (saved_fake_select_lex != NULL)
614       return saved_fake_select_lex;
615     return first_select();
616   };
617   /* LIMIT clause runtime counters */
618   ha_rows select_limit_cnt, offset_limit_cnt;
619   /// Points to subquery if this query expression is used in one, otherwise NULL
620   Item_subselect *item;
621   THD *thd;                   ///< Thread handler
622   /**
623     Helper query block for query expression with UNION or multi-level
624     ORDER BY/LIMIT
625   */
626   st_select_lex *fake_select_lex;
627   /**
628     SELECT_LEX that stores LIMIT and OFFSET for UNION ALL when no
629     fake_select_lex is used.
630   */
631   st_select_lex *saved_fake_select_lex;
632   /// Points to last query block used by UNION DISTINCT query
633   st_select_lex *union_distinct;
634 
635   /// @return true if query expression can be merged into an outer query
636   bool is_mergeable() const;
637 
638   /// @return the query block this query expression belongs to as subquery
outer_select()639   st_select_lex* outer_select() const { return master; }
640 
641   /// @return the first query block inside this query expression
first_select()642   st_select_lex* first_select() const { return slave; }
643 
644   /// @return the next query expression within same query block (next subquery)
next_unit()645   st_select_lex_unit* next_unit() const { return next; }
646 
647   /// @return the query result object in use for this query expression
query_result()648   Query_result *query_result() const { return m_query_result; }
649 
650   /// Set new query result object for this query expression
set_query_result(Query_result * res)651   void set_query_result(Query_result *res) { m_query_result= res; }
652 
653   bool prepare(THD *thd, Query_result *result, ulonglong added_options,
654                ulonglong removed_options);
655   bool optimize(THD *thd);
656   bool execute(THD *thd);
657   bool explain(THD *ethd);
658   bool cleanup(bool full);
unclean()659   inline void unclean() { cleaned= UC_DIRTY; }
660   void reinit_exec_mechanism();
661 
662   void print(String *str, enum_query_type query_type);
663   bool accept(Select_lex_visitor *visitor);
664 
665   bool add_fake_select_lex(THD *thd);
666   bool prepare_fake_select_lex(THD *thd);
set_prepared()667   void set_prepared() { prepared= true; }
set_optimized()668   void set_optimized() { optimized= true; }
set_executed()669   void set_executed() { executed= true; }
reset_executed()670   void reset_executed() { executed= false; }
is_prepared()671   bool is_prepared() const { return prepared; }
is_optimized()672   bool is_optimized() const { return optimized; }
is_executed()673   bool is_executed() const { return executed; }
674   bool change_query_result(Query_result_interceptor *result,
675                            Query_result_interceptor *old_result);
676   void set_limit(st_select_lex *values);
set_thd(THD * thd_arg)677   void set_thd(THD *thd_arg) { thd= thd_arg; }
678 
679   inline bool is_union () const;
680   bool union_needs_tmp_table();
681 
682   /// Include a query expression below a query block.
683   void include_down(LEX *lex, st_select_lex *outer);
684 
685   /// Include a chain of query expressions below a query block.
686   void include_chain(LEX *lex, st_select_lex *outer);
687 
688   /// Exclude this unit and immediately contained select_lex objects
689   void exclude_level();
690 
691   /// Exclude subtree of current unit from tree of SELECTs
692   void exclude_tree();
693 
694   /// Renumber query blocks of a query expression according to supplied LEX
695   void renumber_selects(LEX *lex);
696 
697   friend class st_select_lex;
698 
699   List<Item> *get_unit_column_types();
700   List<Item> *get_field_list();
701 
702   enum_parsing_context get_explain_marker() const;
703   void set_explain_marker(enum_parsing_context m);
704   void set_explain_marker_from(const st_select_lex_unit *u);
705 
706 #ifndef NDEBUG
707   /**
708      Asserts that none of {this unit and its children units} is fully cleaned
709      up.
710   */
711   void assert_not_fully_clean();
712 #else
assert_not_fully_clean()713   void assert_not_fully_clean() {}
714 #endif
715   void invalidate();
716   /*
717     An exception: this is the only function that needs to adjust
718     explain_marker.
719   */
720   friend bool parse_view_definition(THD *thd, TABLE_LIST *view_ref);
721 };
722 
723 typedef class st_select_lex_unit SELECT_LEX_UNIT;
724 typedef Bounds_checked_array<Item*> Ref_ptr_array;
725 
726 /**
727   This class represents a query block, aka a query specification, which is
728   a query consisting of a SELECT keyword, followed by a table list,
729   optionally followed by a WHERE clause, a GROUP BY, etc.
730 */
731 class st_select_lex: public Sql_alloc
732 {
733 public:
734   /// @returns a slice of ref_pointer_array
ref_ptr_array_slice(size_t slice_num)735   Ref_ptr_array ref_ptr_array_slice(size_t slice_num)
736   {
737     size_t slice_sz= ref_pointer_array.size() / 5U;
738     assert(ref_pointer_array.size() % 5 == 0);
739     assert(slice_num < 5U);
740     return Ref_ptr_array(&ref_pointer_array[slice_num * slice_sz], slice_sz);
741   }
742 
where_cond()743   Item  *where_cond() const { return m_where_cond; }
set_where_cond(Item * cond)744   void   set_where_cond(Item *cond) { m_where_cond= cond; }
where_cond_ref()745   Item **where_cond_ref() { return &m_where_cond; }
having_cond()746   Item  *having_cond() const { return m_having_cond; }
set_having_cond(Item * cond)747   void   set_having_cond(Item *cond) { m_having_cond= cond; }
748 
set_query_result(Query_result * result)749   void set_query_result(Query_result *result) { m_query_result= result; }
query_result()750   Query_result *query_result() const { return m_query_result; }
751   bool change_query_result(Query_result_interceptor *new_result,
752                            Query_result_interceptor *old_result);
753 
754   /// Set base options for a query block (and active options too)
set_base_options(ulonglong options_arg)755   void set_base_options(ulonglong options_arg)
756   {
757     DBUG_EXECUTE_IF("no_const_tables", options_arg|= OPTION_NO_CONST_TABLES;);
758 
759     // Make sure we do not overwrite options by accident
760     assert(m_base_options == 0 && m_active_options == 0);
761     m_base_options= options_arg;
762     m_active_options= options_arg;
763   }
764 
765   /// Add base options to a query block, also update active options
add_base_options(ulonglong options)766   void add_base_options(ulonglong options)
767   {
768     assert(first_execution);
769     m_base_options|= options;
770     m_active_options|= options;
771   }
772 
773   /**
774     Remove base options from a query block.
775     Active options are also updated, and we assume here that "extra" options
776     cannot override removed base options.
777   */
remove_base_options(ulonglong options)778   void remove_base_options(ulonglong options)
779   {
780     assert(first_execution);
781     m_base_options&= ~options;
782     m_active_options&= ~options;
783   }
784 
785   /// Make active options from base options, supplied options and environment:
786   void make_active_options(ulonglong added_options, ulonglong removed_options);
787 
788   /// Adjust the active option set
add_active_options(ulonglong options)789   void add_active_options(ulonglong options)
790   { m_active_options|= options; }
791 
792   /// @return the active query options
active_options()793   ulonglong active_options() const { return m_active_options; }
794 
795 private:
796   /**
797     Intrusive double-linked list of all query blocks within the same
798     query expression.
799   */
800   st_select_lex *next;
801   st_select_lex **prev;
802 
803   /// The query expression containing this query block.
804   st_select_lex_unit *master;
805   /// The first query expression contained within this query block.
806   st_select_lex_unit *slave;
807 
808   /// Intrusive double-linked global list of query blocks.
809   st_select_lex *link_next;
810   st_select_lex **link_prev;
811 
812   /// Result of this query block
813   Query_result *m_query_result;
814 
815   /**
816     Options assigned from parsing and throughout resolving,
817     should not be modified after resolving is done.
818   */
819   ulonglong m_base_options;
820   /**
821     Active options. Derived from base options, modifiers added during
822     resolving and values from session variable option_bits. Since the latter
823     may change, active options are refreshed per execution of a statement.
824   */
825   ulonglong m_active_options;
826 
827 public:
828   /**
829     In sql_cache we store SQL_CACHE flag as specified by user to be
830     able to restore SELECT statement from internal structures.
831   */
832   enum e_sql_cache { SQL_CACHE_UNSPECIFIED, SQL_NO_CACHE, SQL_CACHE };
833   /// Query cache hint (should rather belong in LEX object?)
834   e_sql_cache sql_cache;
835   /**
836     result of this query can't be cached, bit field, can be :
837       UNCACHEABLE_DEPENDENT
838       UNCACHEABLE_RAND
839       UNCACHEABLE_SIDEEFFECT
840   */
841   uint8 uncacheable;
842 
843   /// Describes context of this query block (e.g if it is a derived table).
844   enum sub_select_type linkage;
845   bool no_table_names_allowed; ///< used for global order by
846   /**
847     Context for name resolution for all column references except columns
848     from joined tables.
849   */
850   Name_resolution_context context;
851   /**
852     Pointer to first object in list of Name res context objects that have
853     this query block as the base query block.
854     Includes field "context" which is embedded in this query block.
855   */
856   Name_resolution_context *first_context;
857   /**
858     Three fields used by semi-join transformations to know when semi-join is
859     possible, and in which condition tree the subquery predicate is located.
860   */
861   enum Resolve_place { RESOLVE_NONE, RESOLVE_JOIN_NEST, RESOLVE_CONDITION,
862                        RESOLVE_HAVING, RESOLVE_SELECT_LIST };
863   Resolve_place resolve_place; ///< Indicates part of query being resolved
864   TABLE_LIST *resolve_nest;    ///< Used when resolving outer join condition
865   /**
866     Disables semi-join flattening when resolving a subtree in which flattening
867     is not allowed. The flag should be true while resolving items that are not
868     on the AND-top-level of a condition tree.
869   */
870   bool semijoin_disallowed;
871   char *db;
872 private:
873   /**
874     Condition to be evaluated after all tables in a query block are joined.
875     After all permanent transformations have been conducted by
876     SELECT_LEX::prepare(), this condition is "frozen", any subsequent changes
877     to it must be done with change_item_tree(), unless they only modify AND/OR
878     items and use a copy created by SELECT_LEX::get_optimizable_conditions().
879     Same is true for 'having_cond'.
880   */
881   Item *m_where_cond;
882 
883   /// Condition to be evaluated on grouped rows after grouping.
884   Item *m_having_cond;
885 
886 public:
887 
888   /**
889     Saved values of the WHERE and HAVING clauses. Allowed values are:
890      - COND_UNDEF if the condition was not specified in the query or if it
891        has not been optimized yet
892      - COND_TRUE if the condition is always true
893      - COND_FALSE if the condition is impossible
894      - COND_OK otherwise
895   */
896   Item::cond_result cond_value;
897   Item::cond_result having_value;
898 
899   /// Reference to LEX that this query block belongs to
900   LEX *parent_lex;
901   /// Indicates whether this query block contains the WITH ROLLUP clause
902   enum olap_type olap;
903   /// List of tables in FROM clause - use TABLE_LIST::next_local to traverse
904   SQL_I_List<TABLE_LIST>  table_list;
905 
906   /**
907     GROUP BY clause.
908     This list may be mutated during optimization (by remove_const()),
909     so for prepared statements, we keep a copy of the ORDER.next pointers in
910     group_list_ptrs, and re-establish the original list before each execution.
911   */
912   SQL_I_List<ORDER>       group_list;
913   Group_list_ptrs        *group_list_ptrs;
914 
915   /**
916     List of columns and expressions:
917     SELECT: Columns and expressions in the SELECT list.
918     UPDATE: Columns in the SET clause.
919   */
920   List<Item>          item_list;
921   bool	              is_item_list_lookup;
922 
923   /// Number of GROUP BY expressions added to all_fields
924   int hidden_group_field_count;
925 
926   List<Item> &fields_list; ///< hold field list
927   List<Item> all_fields; ///< to store all expressions used in query
928   /**
929     Usually a pointer to ftfunc_list_alloc, but in UNION this is used to create
930     fake select_lex that consolidates result fields of UNION
931   */
932   List<Item_func_match> *ftfunc_list;
933   List<Item_func_match> ftfunc_list_alloc;
934   /**
935     After optimization it is pointer to corresponding JOIN. This member
936     should be changed only when THD::LOCK_query_plan mutex is taken.
937   */
938   JOIN *join;
939   /// join list of the top level
940   List<TABLE_LIST> top_join_list;
941   /// list for the currently parsed join
942   List<TABLE_LIST> *join_list;
943   /// table embedding the above list
944   TABLE_LIST *embedding;
945   /// List of semi-join nests generated for this query block
946   List<TABLE_LIST> sj_nests;
947   /**
948     Points to first leaf table of query block. After setup_tables() is done,
949     this is a list of base tables and derived tables. After derived tables
950     processing is done, this is a list of base tables only.
951     Use TABLE_LIST::next_leaf to traverse the list.
952   */
953   TABLE_LIST *leaf_tables;
954   /// Number of leaf tables in this query block.
955   uint leaf_table_count;
956   /// Number of derived tables and views in this query block.
957   uint derived_table_count;
958   /// Number of materialized derived tables and views in this query block.
959   uint materialized_derived_table_count;
960   /**
961     True if query block has semi-join nests merged into it. Notice that this
962     is updated earlier than sj_nests, so check this if info is needed
963     before the full resolver process is complete.
964   */
965   bool has_sj_nests;
966   /// Number of partitioned tables
967   uint partitioned_table_count;
968   /**
969     SELECT_LEX type enum
970   */
971   enum type_enum {
972     SLT_NONE= 0,
973     SLT_PRIMARY,
974     SLT_SIMPLE,
975     SLT_DERIVED,
976     SLT_SUBQUERY,
977     SLT_UNION,
978     SLT_UNION_RESULT,
979     SLT_MATERIALIZED,
980   // Total:
981     SLT_total ///< fake type, total number of all valid types
982   // Don't insert new types below this line!
983   };
984 
985   /**
986     ORDER BY clause.
987     This list may be mutated during optimization (by remove_const()),
988     so for prepared statements, we keep a copy of the ORDER.next pointers in
989     order_list_ptrs, and re-establish the original list before each execution.
990   */
991   SQL_I_List<ORDER> order_list;
992   Group_list_ptrs *order_list_ptrs;
993 
994   /// LIMIT clause, NULL if no limit is given
995   Item *select_limit;
996   /// LIMIT ... OFFSET clause, NULL if no offset is given
997   Item *offset_limit;
998 
999   /// The complete ref pointer array, with 5 slices (see class JOIN too)
1000   Ref_ptr_array ref_pointer_array;
1001   /// Slice 0 of array, with pointers to all expressions in all_fields
1002   Ref_ptr_array ref_ptrs;
1003 
1004   /**
1005     number of items in select_list and HAVING clause used to get number
1006     bigger then can be number of entries that will be added to all item
1007     list during split_sum_func
1008   */
1009   uint select_n_having_items;
1010   uint cond_count;    ///< number of arguments of and/or/xor in where/having/on
1011   uint between_count; ///< number of between predicates in where/having/on
1012   uint max_equal_elems; ///< maximal number of elements in multiple equalities
1013   /**
1014     Number of fields used in select list or where clause of current select
1015     and all inner subselects.
1016   */
1017   uint select_n_where_fields;
1018 
1019   /// Parse context: indicates where the current expression is being parsed
1020   enum_parsing_context parsing_place;
1021   /// Parse context: is inside a set function if this is positive
1022   uint in_sum_expr;
1023 
1024   /**
1025     True if contains or aggregates set functions.
1026     @note this is wrong when a locally found set function is aggregated
1027     in an outer query block.
1028   */
1029   bool with_sum_func;
1030   /// Number of Item_sum-derived objects in this SELECT
1031   uint n_sum_items;
1032   /// Number of Item_sum-derived objects in children and descendant SELECTs
1033   uint n_child_sum_items;
1034 
1035   uint select_number; ///< Query block number (used for EXPLAIN)
1036   /**
1037     Nesting level of query block, outer-most query block has level 0,
1038     its subqueries have level 1, etc. @see also sql/item_sum.h.
1039   */
1040   int nest_level;
1041   /// Circular linked list of sum func in nested selects
1042   Item_sum *inner_sum_func_list;
1043   /**
1044     Number of wildcards used in the SELECT list. For example,
1045     SELECT *, t1.*, catalog.t2.* FROM t0, t1, t2;
1046     has 3 wildcards.
1047   */
1048   uint with_wild;
1049   bool  braces;   	///< SELECT ... UNION (SELECT ... ) <- this braces
1050   /// TRUE when having fix field called in processing of this query block
1051   bool having_fix_field;
1052   /// TRUE when GROUP BY fix field called in processing of this query block
1053   bool group_fix_field;
1054   /// List of references to fields referenced from inner query blocks
1055   List<Item_outer_ref> inner_refs_list;
1056 
1057   /// explicit LIMIT clause is used
1058   bool explicit_limit;
1059   /**
1060     HAVING clause contains subquery => we can't close tables before
1061     query processing end even if we use temporary table
1062   */
1063   bool subquery_in_having;
1064   /**
1065     This variable is required to ensure proper work of subqueries and
1066     stored procedures. Generally, one should use the states of
1067     Query_arena to determine if it's a statement prepare or first
1068     execution of a stored procedure. However, in case when there was an
1069     error during the first execution of a stored procedure, the SP body
1070     is not expelled from the SP cache. Therefore, a deeply nested
1071     subquery might be left unoptimized. So we need this per-subquery
1072     variable to inidicate the optimization/execution state of every
1073     subquery. Prepared statements work OK in that regard, as in
1074     case of an error during prepare the PS is not created.
1075   */
1076   bool first_execution;
1077   /// True when semi-join pull-out processing is complete
1078   bool sj_pullout_done;
1079   /// exclude this query block from unique_table() check
1080   bool exclude_from_table_unique_test;
1081   /// Allow merge of immediate unnamed derived tables
1082   bool allow_merge_derived;
1083   /**
1084     This is a copy of the original JOIN USING list that comes from
1085     the parser. The parser :
1086       1. Sets the natural_join of the second TABLE_LIST in the join
1087          and the st_select_lex::prev_join_using.
1088       2. Makes a parent TABLE_LIST and sets its is_natural_join/
1089        join_using_fields members.
1090       3. Uses the wrapper TABLE_LIST as a table in the upper level.
1091     We cannot assign directly to join_using_fields in the parser because
1092     at stage (1.) the parent TABLE_LIST is not constructed yet and
1093     the assignment will override the JOIN USING fields of the lower level
1094     joins on the right.
1095   */
1096   List<String> *prev_join_using;
1097   /**
1098     The set of those tables whose fields are referenced in the select list of
1099     this select level.
1100   */
1101   table_map select_list_tables;
1102   table_map outer_join;       ///< Bitmap of all inner tables from outer joins
1103 
1104   /// Query-block-level hints, for this query block
1105   Opt_hints_qb *opt_hints_qb;
1106 
1107 
1108   /**
1109     @note the group_by and order_by lists below will probably be added to the
1110           constructor when the parser is converted into a true bottom-up design.
1111   */
1112   st_select_lex(TABLE_LIST *table_list, List<Item> *item_list,
1113                 Item *where, Item *having, Item *limit, Item *offset
1114                 //SQL_I_LIST<ORDER> *group_by, SQL_I_LIST<ORDER> order_by
1115                 );
1116 
master_unit()1117   st_select_lex_unit *master_unit() const { return master; }
first_inner_unit()1118   st_select_lex_unit *first_inner_unit() const { return slave; }
outer_select()1119   SELECT_LEX *outer_select() const { return master->outer_select(); }
next_select()1120   SELECT_LEX *next_select() const { return next; }
1121 
last_select()1122   st_select_lex* last_select()
1123   {
1124     st_select_lex* mylast= this;
1125     for (; mylast->next_select(); mylast= mylast->next_select())
1126     {}
1127     return mylast;
1128   }
1129 
next_select_in_list()1130   SELECT_LEX *next_select_in_list() const { return link_next; }
1131 
1132   void mark_as_dependent(st_select_lex *last);
1133 
1134   /// @return true if query block is explicitly grouped (non-empty GROUP BY)
is_explicitly_grouped()1135   bool is_explicitly_grouped() const { return group_list.elements > 0; }
1136 
1137   /**
1138     @return true if this query block is implicitly grouped, ie it is not
1139     explicitly grouped but contains references to set functions.
1140     The query will return max. 1 row (@see also is_single_grouped()).
1141   */
is_implicitly_grouped()1142   bool is_implicitly_grouped() const
1143   { return m_agg_func_used && group_list.elements == 0; }
1144 
1145   /**
1146     @return true if this query block is implicitly grouped and returns exactly
1147     one row, which happens when it does not have a HAVING clause.
1148   */
is_single_grouped()1149   bool is_single_grouped() const
1150   {
1151     return m_agg_func_used &&
1152            group_list.elements == 0 &&
1153            m_having_cond == NULL;
1154   }
1155 
1156   /**
1157     @return true if this query block is explicitly or implicitly grouped.
1158     @note a query with DISTINCT is not considered to be aggregated.
1159     @note in standard SQL, a query with HAVING is defined as grouped, however
1160           MySQL allows HAVING without any aggregation to be the same as WHERE.
1161   */
is_grouped()1162   bool is_grouped() const
1163   { return group_list.elements > 0 || m_agg_func_used; }
1164 
1165   /// @return true if this query block contains DISTINCT at start of select list
is_distinct()1166   bool is_distinct() const
1167   { return active_options() & SELECT_DISTINCT; }
1168 
1169   /**
1170     @return true if this query block contains an ORDER BY clause.
1171 
1172     @note returns false if ORDER BY has been eliminated, e.g if the query
1173           can return max. 1 row.
1174   */
is_ordered()1175   bool is_ordered() const
1176   { return order_list.elements > 0; }
1177 
1178   /// @return true if this query block has a LIMIT clause
has_limit()1179   bool has_limit() const
1180   { return select_limit != NULL; }
1181 
1182   /// @return true if query block references full-text functions
has_ft_funcs()1183   bool has_ft_funcs() const
1184   { return ftfunc_list->elements > 0; }
1185 
1186   void invalidate();
1187 
1188   bool set_braces(bool value);
get_in_sum_expr()1189   uint get_in_sum_expr() const { return in_sum_expr; }
1190 
1191   bool add_item_to_list(THD *thd, Item *item);
1192   void add_group_to_list(ORDER *order);
1193   bool add_ftfunc_to_list(Item_func_match *func);
1194   void add_order_to_list(ORDER *order);
1195   TABLE_LIST* add_table_to_list(THD *thd, Table_ident *table,
1196 				LEX_STRING *alias,
1197 				ulong table_options,
1198 				thr_lock_type flags= TL_UNLOCK,
1199                                 enum_mdl_type mdl_type= MDL_SHARED_READ,
1200 				List<Index_hint> *hints= 0,
1201                                 List<String> *partition_names= 0,
1202                                 LEX_STRING *option= 0);
get_table_list()1203   TABLE_LIST* get_table_list() const { return table_list.first; }
1204   bool init_nested_join(THD *thd);
1205   TABLE_LIST *end_nested_join(THD *thd);
1206   TABLE_LIST *nest_last_join(THD *thd);
1207   void add_joined_table(TABLE_LIST *table);
1208   TABLE_LIST *convert_right_join();
get_item_list()1209   List<Item>* get_item_list() { return &item_list; }
1210 
1211   // Check privileges for views that are merged into query block
1212   bool check_view_privileges(THD *thd,
1213                              ulong want_privilege_first,
1214                              ulong want_privilege_next);
1215 
1216   // Resolve and prepare information about tables for one query block
1217   bool setup_tables(THD *thd, TABLE_LIST *tables, bool select_insert);
1218 
1219   // Resolve derived table and view information for a query block
1220   bool resolve_derived(THD *thd, bool apply_semijoin);
1221 
1222   // Propagate exclusion from table uniqueness test into subqueries
1223   void propagate_unique_test_exclusion();
1224 
1225   // Add full-text function elements from a list into this query block
1226   bool add_ftfunc_list(List<Item_func_match> *ftfuncs);
1227 
1228   void set_lock_for_tables(thr_lock_type lock_type);
init_order()1229   inline void init_order()
1230   {
1231     assert(order_list.elements == 0);
1232     order_list.elements= 0;
1233     order_list.first= 0;
1234     order_list.next= &order_list.first;
1235   }
1236   /*
1237     This method created for reiniting LEX in mysql_admin_table() and can be
1238     used only if you are going remove all SELECT_LEX & units except belonger
1239     to LEX (LEX::unit & LEX::select, for other purposes use
1240     SELECT_LEX_UNIT::exclude_level()
1241   */
cut_subtree()1242   void cut_subtree() { slave= 0; }
1243   bool test_limit();
1244   /**
1245     Get offset for LIMIT.
1246 
1247     Evaluate offset item if necessary.
1248 
1249     @return Number of rows to skip.
1250   */
1251   ha_rows get_offset();
1252   /**
1253    Get limit.
1254 
1255    Evaluate limit item if necessary.
1256 
1257    @return Limit of rows in result.
1258   */
1259   ha_rows get_limit();
1260 
1261   /// Assign a default name resolution object for this query block.
1262   bool set_context(Name_resolution_context *outer_context);
1263 
1264   bool setup_ref_array(THD *thd);
1265   void print(THD *thd, String *str, enum_query_type query_type);
1266   static void print_order(String *str,
1267                           ORDER *order,
1268                           enum_query_type query_type);
1269   void print_limit(THD *thd, String *str, enum_query_type query_type);
1270   void fix_prepare_information(THD *thd);
1271 
1272   virtual bool accept(Select_lex_visitor *visitor);
1273 
1274   /**
1275     Cleanup this subtree (this SELECT_LEX and all nested SELECT_LEXes and
1276     SELECT_LEX_UNITs).
1277     @param full  if false only partial cleanup is done, JOINs and JOIN_TABs are
1278     kept to provide info for EXPLAIN CONNECTION; if true, complete cleanup is
1279     done, all JOINs are freed.
1280   */
1281   bool cleanup(bool full);
1282   /*
1283     Recursively cleanup the join of this select lex and of all nested
1284     select lexes. This is not a full cleanup.
1285   */
1286   void cleanup_all_joins();
1287 
1288   /*
1289    Add a index hint to the tagged list of hints. The type and clause of the
1290    hint will be the current ones (set by set_index_hint())
1291   */
1292   bool add_index_hint (THD *thd, char *str, uint length);
1293 
1294   /* make a list to hold index hints */
1295   void alloc_index_hints (THD *thd);
1296 
1297   /// Return true if this query block is part of a UNION
is_part_of_union()1298   bool is_part_of_union() const { return master_unit()->is_union(); }
1299 
1300   /*
1301     For MODE_ONLY_FULL_GROUP_BY we need to know if
1302     this query block is the aggregation query of at least one aggregate
1303     function.
1304   */
agg_func_used()1305   bool agg_func_used()      const { return m_agg_func_used; }
json_agg_func_used()1306   bool json_agg_func_used() const { return m_json_agg_func_used; }
1307 
set_agg_func_used(bool val)1308   void set_agg_func_used(bool val)      { m_agg_func_used= val; }
1309 
set_json_agg_func_used(bool val)1310   void set_json_agg_func_used(bool val) { m_json_agg_func_used= val; }
1311   /// Lookup for SELECT_LEX type
1312   type_enum type();
1313 
1314   /// Lookup for a type string
get_type_str(const THD * thd)1315   const char *get_type_str(const THD *thd) { return type_str[type()]; }
get_type_str(type_enum type)1316   static const char *get_type_str(type_enum type) { return type_str[type]; }
1317 
is_dependent()1318   bool is_dependent() const { return uncacheable & UNCACHEABLE_DEPENDENT; }
is_cacheable()1319   bool is_cacheable() const
1320   {
1321     return !uncacheable;
1322   }
1323 
1324   /// Include query block inside a query expression.
1325   void include_down(LEX *lex, st_select_lex_unit *outer);
1326 
1327   /// Include a query block next to another query block.
1328   void include_neighbour(LEX *lex, st_select_lex *before);
1329 
1330   /// Include query block inside a query expression, but do not link.
1331   void include_standalone(st_select_lex_unit *sel, st_select_lex **ref);
1332 
1333   /// Include query block into global list.
1334   void include_in_global(st_select_lex **plink);
1335 
1336   /// Include chain of query blocks into global list.
1337   void include_chain_in_global(st_select_lex **start);
1338 
1339   /// Renumber query blocks of contained query expressions
1340   void renumber(LEX *lex);
1341 
1342   /**
1343      Set pointer to corresponding JOIN object.
1344      The function sets the pointer only after acquiring THD::LOCK_query_plan
1345      mutex. This is needed to avoid races when EXPLAIN FOR CONNECTION is used.
1346   */
1347   void set_join(JOIN *join_arg);
1348   /**
1349     Does permanent transformations which are local to a query block (which do
1350     not merge it to another block).
1351   */
1352   bool apply_local_transforms(THD *thd, bool prune);
1353 
1354   bool get_optimizable_conditions(THD *thd,
1355                                   Item **new_where, Item **new_having);
1356 
1357   bool validate_outermost_option(LEX *lex, const char *wrong_option) const;
1358   bool validate_base_options(LEX *lex, ulonglong options) const;
1359 
1360 private:
1361   // Delete unused columns from merged derived tables
1362   void delete_unused_merged_columns(List<TABLE_LIST> *tables);
1363 
1364   bool m_agg_func_used;
1365   bool m_json_agg_func_used;
1366 
1367   /// Helper for fix_prepare_information()
1368   void fix_prepare_information_for_order(THD *thd,
1369                                          SQL_I_List<ORDER> *list,
1370                                          Group_list_ptrs **list_ptrs);
1371   static const char *type_str[SLT_total];
1372 
1373   friend class st_select_lex_unit;
1374 
1375   bool record_join_nest_info(List<TABLE_LIST> *tables);
1376   bool simplify_joins(THD *thd,
1377                       List<TABLE_LIST> *join_list,
1378                       bool top, bool in_sj,
1379                       Item **new_conds,
1380                       uint *changelog= NULL);
1381   /// Merge derived table into query block
1382 public:
1383   bool merge_derived(THD *thd, TABLE_LIST *derived_table);
1384   bool is_in_select_list(Item *cand);
1385 private:
1386   bool convert_subquery_to_semijoin(Item_exists_subselect *subq_pred);
1387   void remap_tables(THD *thd);
1388   bool resolve_subquery(THD *thd);
1389   bool resolve_rollup(THD *thd);
1390   bool change_group_ref(THD *thd, Item_func *expr, bool *changed);
1391   bool flatten_subqueries();
1392   bool setup_wild(THD *thd);
1393   bool setup_order_final(THD *thd);
1394   bool setup_group(THD *thd);
1395   void remove_redundant_subquery_clauses(THD *thd,
1396                                          int hidden_group_field_count);
1397   void repoint_contexts_of_join_nests(List<TABLE_LIST> join_list);
1398   void empty_order_list(SELECT_LEX *sl);
1399   /**
1400     Pointer to collection of subqueries candidate for semijoin
1401     conversion.
1402     Template parameter is "true": no need to run DTORs on pointers.
1403   */
1404   Mem_root_array<Item_exists_subselect*, true> *sj_candidates;
1405 public:
1406   /// How many expressions are part of the order by but not select list.
1407   int hidden_order_field_count;
1408 
1409   bool fix_inner_refs(THD *thd);
1410   bool setup_conds(THD *thd);
1411   bool prepare(THD *thd);
1412   bool optimize(THD *thd);
1413   void reset_nj_counters(List<TABLE_LIST> *join_list= NULL);
1414   bool check_only_full_group_by(THD *thd);
1415 
1416   /// Merge name resolution context objects of a subquery into its parent
1417   void merge_contexts(SELECT_LEX *inner);
1418 
1419   /**
1420     Returns which subquery execution strategies can be used for this query block.
1421 
1422     @param thd  Pointer to THD object for session.
1423                 Used to access optimizer_switch
1424 
1425     @retval EXEC_MATERIALIZATION  Subquery Materialization should be used
1426     @retval EXEC_EXISTS           In-to-exists execution should be used
1427     @retval EXEC_EXISTS_OR_MAT    A cost-based decision should be made
1428   */
1429   Item_exists_subselect::enum_exec_method subquery_strategy(THD *thd) const;
1430 
1431   /**
1432     Returns whether semi-join is enabled for this query block
1433 
1434     @see @c Opt_hints_qb::semijoin_enabled for details on how hints
1435     affect this decision.  If there are no hints for this query block,
1436     optimizer_switch setting determines whether semi-join is used.
1437 
1438     @param thd  Pointer to THD object for session.
1439                 Used to access optimizer_switch
1440 
1441     @return true if semijoin is enabled,
1442             false otherwise
1443   */
1444   bool semijoin_enabled(THD *thd) const;
1445   /**
1446     Update available semijoin strategies for semijoin nests.
1447 
1448     Available semijoin strategies needs to be updated on every execution since
1449     optimizer_switch setting may have changed.
1450 
1451     @param thd  Pointer to THD object for session.
1452                 Used to access optimizer_switch
1453   */
1454   void update_semijoin_strategies(THD *thd);
1455 
1456   /**
1457     Add item to the hidden part of select list
1458 
1459     @param item  item to add
1460 
1461     @return Pointer to ref_ptr for the added item
1462   */
1463   Item **add_hidden_item(Item *item);
1464 };
1465 typedef class st_select_lex SELECT_LEX;
1466 
is_union()1467 inline bool st_select_lex_unit::is_union() const
1468 {
1469   return first_select()->next_select() &&
1470          first_select()->next_select()->linkage == UNION_TYPE;
1471 }
1472 
1473 #ifdef MYSQL_SERVER
1474 
1475 struct Cast_type
1476 {
1477   Cast_target target;
1478   const CHARSET_INFO *charset;
1479   ulong type_flags;
1480   const char *length;
1481   const char *dec;
1482 };
1483 
1484 
1485 struct Limit_options
1486 {
1487   Item *limit;
1488   Item *opt_offset;
1489   /*
1490     true for "LIMIT offset,limit" and false for "LIMIT limit OFFSET offset"
1491   */
1492   bool is_offset_first;
1493 };
1494 
1495 
1496 struct Query_options {
1497   ulonglong query_spec_options;
1498   enum SELECT_LEX::e_sql_cache sql_cache;
1499 
1500   bool merge(const Query_options &a, const Query_options &b);
1501   bool save_to(Parse_context *);
1502 };
1503 
1504 
1505 /**
1506   Argument values for PROCEDURE ANALYSE(...)
1507 */
1508 
1509 struct Proc_analyse_params
1510 {
1511   uint max_tree_elements; //< maximum number of distinct values per column
1512   uint max_treemem; //< maximum amount of memory to allocate per column
1513 
1514   static const uint default_max_tree_elements= 256;
1515   static const uint default_max_treemem= 8192;
1516 };
1517 
1518 
1519 struct Select_lock_type
1520 {
1521   bool is_set;
1522   thr_lock_type lock_type;
1523   bool is_safe_to_cache_query;
1524 };
1525 
1526 
1527 /**
1528   Helper for the sql_exchange class
1529 */
1530 
1531 struct Line_separators
1532 {
1533   const String *line_term;
1534   const String *line_start;
1535 
cleanupLine_separators1536   void cleanup() { line_term= line_start= NULL; }
merge_line_separatorsLine_separators1537   void merge_line_separators(const Line_separators &s)
1538   {
1539     if (s.line_term != NULL)
1540       line_term= s.line_term;
1541     if (s.line_start != NULL)
1542       line_start= s.line_start;
1543   }
1544 };
1545 
1546 
1547 /**
1548   Helper for the sql_exchange class
1549 */
1550 
1551 struct Field_separators
1552 {
1553   const String *field_term;
1554   const String *escaped;
1555   const String *enclosed;
1556   bool opt_enclosed;
1557 
cleanupField_separators1558   void cleanup()
1559   {
1560     field_term= escaped= enclosed= NULL;
1561     opt_enclosed= false;
1562   }
merge_field_separatorsField_separators1563   void merge_field_separators(const Field_separators &s)
1564   {
1565     if (s.field_term != NULL)
1566       field_term= s.field_term;
1567     if (s.escaped != NULL)
1568       escaped= s.escaped;
1569     if (s.enclosed != NULL)
1570       enclosed= s.enclosed;
1571     // TODO: a bug?
1572     // OPTIONALLY ENCLOSED BY x ENCLOSED BY y == OPTIONALLY ENCLOSED BY y
1573     if (s.opt_enclosed)
1574       opt_enclosed= s.opt_enclosed;
1575   }
1576 };
1577 
1578 
1579 enum delete_option_enum {
1580   DELETE_QUICK        = 1 << 0,
1581   DELETE_LOW_PRIORITY = 1 << 1,
1582   DELETE_IGNORE       = 1 << 2
1583 };
1584 
1585 
1586 union YYSTYPE {
1587   /*
1588     Hint parser section (sql_hints.yy)
1589   */
1590   opt_hints_enum hint_type;
1591   LEX_CSTRING hint_string;
1592   class PT_hint *hint;
1593   class PT_hint_list *hint_list;
1594   Hint_param_index_list hint_param_index_list;
1595   Hint_param_table hint_param_table;
1596   Hint_param_table_list hint_param_table_list;
1597 
1598   /*
1599     Main parser section (sql_yacc.yy)
1600   */
1601   int  num;
1602   ulong ulong_num;
1603   ulonglong ulonglong_number;
1604   longlong longlong_number;
1605   LEX_STRING lex_str;
1606   LEX_STRING *lex_str_ptr;
1607   LEX_SYMBOL symbol;
1608   Table_ident *table;
1609   char *simple_string;
1610   Item *item;
1611   Item_num *item_num;
1612   List<Item> *item_list;
1613   List<String> *string_list;
1614   String *string;
1615   Key_part_spec *key_part;
1616   TABLE_LIST *table_list;
1617   udf_func *udf;
1618   LEX_USER *lex_user;
1619   struct sys_var_with_base variable;
1620   enum enum_var_type var_type;
1621   keytype key_type;
1622   enum ha_key_alg key_alg;
1623   handlerton *db_type;
1624   enum row_type row_type;
1625   enum ha_rkey_function ha_rkey_mode;
1626   enum enum_ha_read_modes ha_read_mode;
1627   enum enum_tx_isolation tx_isolation;
1628   const char *c_str;
1629   struct
1630   {
1631     const CHARSET_INFO *charset;
1632     ulong type_flags;
1633   } charset_with_flags;
1634   struct
1635   {
1636     const char *length;
1637     const char *dec;
1638   } precision;
1639   struct Cast_type cast_type;
1640   enum Item_udftype udf_type;
1641   const CHARSET_INFO *charset;
1642   thr_lock_type lock_type;
1643   interval_type interval, interval_time_st;
1644   timestamp_type date_time_type;
1645   st_select_lex *select_lex;
1646   chooser_compare_func_creator boolfunc2creator;
1647   class sp_condition_value *spcondvalue;
1648   struct { int vars, conds, hndlrs, curs; } spblock;
1649   sp_name *spname;
1650   LEX *lex;
1651   sp_head *sphead;
1652   struct p_elem_val *p_elem_value;
1653   enum index_hint_type index_hint;
1654   enum enum_filetype filetype;
1655   enum fk_option m_fk_option;
1656   enum enum_yes_no_unknown m_yes_no_unk;
1657   enum_condition_item_name da_condition_item_name;
1658   Diagnostics_information::Which_area diag_area;
1659   Diagnostics_information *diag_info;
1660   Statement_information_item *stmt_info_item;
1661   Statement_information_item::Name stmt_info_item_name;
1662   List<Statement_information_item> *stmt_info_list;
1663   Condition_information_item *cond_info_item;
1664   Condition_information_item::Name cond_info_item_name;
1665   List<Condition_information_item> *cond_info_list;
1666   bool is_not_empty;
1667   Set_signal_information *signal_item_list;
1668   enum enum_trigger_order_type trigger_action_order_type;
1669   struct
1670   {
1671     enum enum_trigger_order_type ordering_clause;
1672     LEX_STRING anchor_trigger_name;
1673   } trg_characteristics;
1674   class Index_hint *key_usage_element;
1675   List<Index_hint> *key_usage_list;
1676   class PT_subselect *subselect;
1677   class PT_item_list *item_list2;
1678   class PT_order_expr *order_expr;
1679   class PT_order_list *order_list;
1680   struct Limit_options limit_options;
1681   Query_options select_options;
1682   class PT_limit_clause *limit_clause;
1683   Parse_tree_node *node;
1684   class PT_select_part2_derived *select_part2_derived;
1685   enum olap_type olap_type;
1686   class PT_group *group;
1687   class PT_order *order;
1688   struct Proc_analyse_params procedure_analyse_params;
1689   class PT_procedure_analyse *procedure_analyse;
1690   Select_lock_type select_lock_type;
1691   class PT_union_order_or_limit *union_order_or_limit;
1692   class PT_table_expression *table_expression;
1693   class PT_table_list *table_list2;
1694   class PT_join_table_list *join_table_list;
1695   class PT_select_paren_derived *select_paren_derived;
1696   class PT_select_lex *select_lex2;
1697   class PT_internal_variable_name *internal_variable_name;
1698   class PT_option_value_following_option_type *option_value_following_option_type;
1699   class PT_option_value_no_option_type *option_value_no_option_type;
1700   class PT_option_value_list_head *option_value_list;
1701   class PT_start_option_value_list *start_option_value_list;
1702   class PT_transaction_access_mode *transaction_access_mode;
1703   class PT_isolation_level *isolation_level;
1704   class PT_transaction_characteristics *transaction_characteristics;
1705   class PT_start_option_value_list_following_option_type
1706     *start_option_value_list_following_option_type;
1707   class PT_set *set;
1708   class PT_union_list *union_list;
1709   Line_separators line_separators;
1710   Field_separators field_separators;
1711   class PT_into_destination *into_destination;
1712   class PT_select_var *select_var_ident;
1713   class PT_select_var_list *select_var_list;
1714   class PT_select_options_and_item_list *select_options_and_item_list;
1715   class PT_select_part2 *select_part2;
1716   class PT_table_reference_list *table_reference_list;
1717   class PT_select_paren *select_paren;
1718   class PT_select_init *select_init;
1719   class PT_select_init2 *select_init2;
1720   class PT_select *select;
1721   class Item_param *param_marker;
1722   class PTI_text_literal *text_literal;
1723   XID *xid;
1724   enum xa_option_words xa_option_type;
1725   struct {
1726     Item *column;
1727     Item *value;
1728   } column_value_pair;
1729   struct {
1730     class PT_item_list *column_list;
1731     class PT_item_list *value_list;
1732   } column_value_list_pair;
1733   struct {
1734     class PT_item_list *column_list;
1735     class PT_insert_values_list *row_value_list;
1736   } column_row_value_list_pair;
1737   struct {
1738     class PT_item_list *column_list;
1739     class PT_insert_query_expression *insert_query_expression;
1740   } insert_from_subquery;
1741   class PT_create_select *create_select;
1742   class PT_insert_values_list *values_list;
1743   class PT_insert_query_expression *insert_query_expression;
1744   class PT_statement *statement;
1745   class Table_ident *table_ident;
1746   Mem_root_array_YY<Table_ident *> table_ident_list;
1747   delete_option_enum opt_delete_option;
1748   class PT_hint_list *optimizer_hints;
1749   enum alter_instance_action_enum alter_instance_action;
1750 };
1751 
1752 #endif
1753 
1754 
1755 /**
1756   Utility RAII class to save/modify/restore the
1757   semijoin_disallowed flag.
1758 */
1759 class Disable_semijoin_flattening
1760 {
1761 public:
Disable_semijoin_flattening(SELECT_LEX * select_ptr,bool apply)1762   Disable_semijoin_flattening(SELECT_LEX *select_ptr, bool apply)
1763     : select(NULL), saved_value()
1764   {
1765     if (select_ptr && apply)
1766     {
1767       select= select_ptr;
1768       saved_value= select->semijoin_disallowed;
1769       select->semijoin_disallowed= true;
1770     }
1771   }
~Disable_semijoin_flattening()1772   ~Disable_semijoin_flattening()
1773   {
1774     if (select)
1775       select->semijoin_disallowed= saved_value;
1776   }
1777 private:
1778   SELECT_LEX *select;
1779   bool saved_value;
1780 };
1781 
1782 
1783 typedef struct struct_slave_connection
1784 {
1785   char *user;
1786   char *password;
1787   char *plugin_auth;
1788   char *plugin_dir;
1789 
1790   void reset();
1791 } LEX_SLAVE_CONNECTION;
1792 
1793 struct st_sp_chistics
1794 {
1795   LEX_STRING comment;
1796   enum enum_sp_suid_behaviour suid;
1797   bool detistic;
1798   enum enum_sp_data_access daccess;
1799 };
1800 
1801 extern const LEX_STRING null_lex_str;
1802 extern const LEX_STRING empty_lex_str;
1803 
1804 struct st_trg_chistics
1805 {
1806   enum enum_trigger_action_time_type action_time;
1807   enum enum_trigger_event_type event;
1808 
1809   /**
1810     FOLLOWS or PRECEDES as specified in the CREATE TRIGGER statement.
1811   */
1812   enum enum_trigger_order_type ordering_clause;
1813 
1814   /**
1815     Trigger name referenced in the FOLLOWS/PRECEDES clause of the CREATE TRIGGER
1816     statement.
1817   */
1818   LEX_STRING anchor_trigger_name;
1819 };
1820 
1821 extern sys_var *trg_new_row_fake_var;
1822 
1823 extern const LEX_STRING null_lex_str;
1824 
1825 class Sroutine_hash_entry;
1826 
1827 /*
1828   Class representing list of all tables used by statement and other
1829   information which is necessary for opening and locking its tables,
1830   like SQL command for this statement.
1831 
1832   Also contains information about stored functions used by statement
1833   since during its execution we may have to add all tables used by its
1834   stored functions/triggers to this list in order to pre-open and lock
1835   them.
1836 
1837   Also used by LEX::reset_n_backup/restore_backup_query_tables_list()
1838   methods to save and restore this information.
1839 */
1840 
1841 class Query_tables_list
1842 {
1843 public:
1844   /**
1845     SQL command for this statement. Part of this class since the
1846     process of opening and locking tables for the statement needs
1847     this information to determine correct type of lock for some of
1848     the tables.
1849   */
1850   enum_sql_command sql_command;
1851   /* Global list of all tables used by this statement */
1852   TABLE_LIST *query_tables;
1853   /* Pointer to next_global member of last element in the previous list. */
1854   TABLE_LIST **query_tables_last;
1855   /*
1856     If non-0 then indicates that query requires prelocking and points to
1857     next_global member of last own element in query table list (i.e. last
1858     table which was not added to it as part of preparation to prelocking).
1859     0 - indicates that this query does not need prelocking.
1860   */
1861   TABLE_LIST **query_tables_own_last;
1862   /*
1863     Set of stored routines called by statement.
1864     (Note that we use lazy-initialization for this hash).
1865   */
1866   enum { START_SROUTINES_HASH_SIZE= 16 };
1867   HASH sroutines;
1868   /*
1869     List linking elements of 'sroutines' set. Allows you to add new elements
1870     to this set as you iterate through the list of existing elements.
1871     'sroutines_list_own_last' is pointer to ::next member of last element of
1872     this list which represents routine which is explicitly used by query.
1873     'sroutines_list_own_elements' number of explicitly used routines.
1874     We use these two members for restoring of 'sroutines_list' to the state
1875     in which it was right after query parsing.
1876   */
1877   SQL_I_List<Sroutine_hash_entry> sroutines_list;
1878   Sroutine_hash_entry **sroutines_list_own_last;
1879   uint sroutines_list_own_elements;
1880 
1881   /**
1882     Locking state of tables in this particular statement.
1883 
1884     If we under LOCK TABLES or in prelocked mode we consider tables
1885     for the statement to be "locked" if there was a call to lock_tables()
1886     (which called handler::start_stmt()) for tables of this statement
1887     and there was no matching close_thread_tables() call.
1888 
1889     As result this state may differ significantly from one represented
1890     by Open_tables_state::lock/locked_tables_mode more, which are always
1891     "on" under LOCK TABLES or in prelocked mode.
1892   */
1893   enum enum_lock_tables_state {
1894     LTS_NOT_LOCKED = 0,
1895     LTS_LOCKED
1896   };
1897   enum_lock_tables_state lock_tables_state;
is_query_tables_locked()1898   bool is_query_tables_locked()
1899   {
1900     return (lock_tables_state == LTS_LOCKED);
1901   }
1902 
1903   /**
1904     Number of tables which were open by open_tables() and to be locked
1905     by lock_tables().
1906     Note that we set this member only in some cases, when this value
1907     needs to be passed from open_tables() to lock_tables() which are
1908     separated by some amount of code.
1909   */
1910   uint table_count;
1911 
1912   /*
1913     These constructor and destructor serve for creation/destruction
1914     of Query_tables_list instances which are used as backup storage.
1915   */
Query_tables_list()1916   Query_tables_list() {}
~Query_tables_list()1917   ~Query_tables_list() {}
1918 
1919   /* Initializes (or resets) Query_tables_list object for "real" use. */
1920   void reset_query_tables_list(bool init);
1921   void destroy_query_tables_list();
set_query_tables_list(Query_tables_list * state)1922   void set_query_tables_list(Query_tables_list *state)
1923   {
1924     *this= *state;
1925   }
1926 
1927   /*
1928     Direct addition to the list of query tables.
1929     If you are using this function, you must ensure that the table
1930     object, in particular table->db member, is initialized.
1931   */
add_to_query_tables(TABLE_LIST * table)1932   void add_to_query_tables(TABLE_LIST *table)
1933   {
1934     *(table->prev_global= query_tables_last)= table;
1935     query_tables_last= &table->next_global;
1936   }
requires_prelocking()1937   bool requires_prelocking()
1938   {
1939     return MY_TEST(query_tables_own_last);
1940   }
mark_as_requiring_prelocking(TABLE_LIST ** tables_own_last)1941   void mark_as_requiring_prelocking(TABLE_LIST **tables_own_last)
1942   {
1943     query_tables_own_last= tables_own_last;
1944   }
1945   /* Return pointer to first not-own table in query-tables or 0 */
first_not_own_table()1946   TABLE_LIST* first_not_own_table()
1947   {
1948     return ( query_tables_own_last ? *query_tables_own_last : 0);
1949   }
chop_off_not_own_tables()1950   void chop_off_not_own_tables()
1951   {
1952     if (query_tables_own_last)
1953     {
1954       *query_tables_own_last= 0;
1955       query_tables_last= query_tables_own_last;
1956       query_tables_own_last= 0;
1957     }
1958   }
1959 
1960   /** Return a pointer to the last element in query table list. */
last_table()1961   TABLE_LIST *last_table()
1962   {
1963     /* Don't use offsetof() macro in order to avoid warnings. */
1964     return query_tables ?
1965            (TABLE_LIST*) ((char*) query_tables_last -
1966                           ((char*) &(query_tables->next_global) -
1967                            (char*) query_tables)) :
1968            0;
1969   }
1970 
1971   /**
1972     All types of unsafe statements.
1973 
1974     @note The int values of the enum elements are used to point to
1975     bits in two bitmaps in two different places:
1976 
1977     - Query_tables_list::binlog_stmt_flags
1978     - THD::binlog_unsafe_warning_flags
1979 
1980     Hence in practice this is not an enum at all, but a map from
1981     symbols to bit indexes.
1982 
1983     The ordering of elements in this enum must correspond to the order of
1984     elements in the array binlog_stmt_unsafe_errcode.
1985   */
1986   enum enum_binlog_stmt_unsafe {
1987     /**
1988       SELECT..LIMIT is unsafe because the set of rows returned cannot
1989       be predicted.
1990     */
1991     BINLOG_STMT_UNSAFE_LIMIT= 0,
1992     /**
1993       Access to log tables is unsafe because slave and master probably
1994       log different things.
1995     */
1996     BINLOG_STMT_UNSAFE_SYSTEM_TABLE,
1997     /**
1998       Inserting into an autoincrement column in a stored routine is unsafe.
1999       Even with just one autoincrement column, if the routine is invoked more than
2000       once slave is not guaranteed to execute the statement graph same way as
2001       the master.
2002       And since it's impossible to estimate how many times a routine can be invoked at
2003       the query pre-execution phase (see lock_tables), the statement is marked
2004       pessimistically unsafe.
2005     */
2006     BINLOG_STMT_UNSAFE_AUTOINC_COLUMNS,
2007     /**
2008       Using a UDF (user-defined function) is unsafe.
2009     */
2010     BINLOG_STMT_UNSAFE_UDF,
2011     /**
2012       Using most system variables is unsafe, because slave may run
2013       with different options than master.
2014     */
2015     BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE,
2016     /**
2017       Using some functions is unsafe (e.g., UUID).
2018     */
2019     BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION,
2020 
2021     /**
2022       Mixing transactional and non-transactional statements are unsafe if
2023       non-transactional reads or writes are occur after transactional
2024       reads or writes inside a transaction.
2025     */
2026     BINLOG_STMT_UNSAFE_NONTRANS_AFTER_TRANS,
2027 
2028     /**
2029       Mixing self-logging and non-self-logging engines in a statement
2030       is unsafe.
2031     */
2032     BINLOG_STMT_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
2033 
2034     /**
2035       Statements that read from both transactional and non-transactional
2036       tables and write to any of them are unsafe.
2037     */
2038     BINLOG_STMT_UNSAFE_MIXED_STATEMENT,
2039 
2040     /**
2041       INSERT...IGNORE SELECT is unsafe because which rows are ignored depends
2042       on the order that rows are retrieved by SELECT. This order cannot be
2043       predicted and may differ on master and the slave.
2044     */
2045     BINLOG_STMT_UNSAFE_INSERT_IGNORE_SELECT,
2046 
2047     /**
2048       INSERT...SELECT...UPDATE is unsafe because which rows are updated depends
2049       on the order that rows are retrieved by SELECT. This order cannot be
2050       predicted and may differ on master and the slave.
2051     */
2052     BINLOG_STMT_UNSAFE_INSERT_SELECT_UPDATE,
2053 
2054     /**
2055      Query that writes to a table with auto_inc column after selecting from
2056      other tables are unsafe as the order in which the rows are retrieved by
2057      select may differ on master and slave.
2058     */
2059     BINLOG_STMT_UNSAFE_WRITE_AUTOINC_SELECT,
2060 
2061     /**
2062       INSERT...REPLACE SELECT is unsafe because which rows are replaced depends
2063       on the order that rows are retrieved by SELECT. This order cannot be
2064       predicted and may differ on master and the slave.
2065     */
2066     BINLOG_STMT_UNSAFE_REPLACE_SELECT,
2067 
2068     /**
2069       CREATE TABLE... IGNORE... SELECT is unsafe because which rows are ignored
2070       depends on the order that rows are retrieved by SELECT. This order cannot
2071       be predicted and may differ on master and the slave.
2072     */
2073     BINLOG_STMT_UNSAFE_CREATE_IGNORE_SELECT,
2074 
2075     /**
2076       CREATE TABLE...REPLACE... SELECT is unsafe because which rows are replaced
2077       depends on the order that rows are retrieved from SELECT. This order
2078       cannot be predicted and may differ on master and the slave
2079     */
2080     BINLOG_STMT_UNSAFE_CREATE_REPLACE_SELECT,
2081 
2082     /**
2083       CREATE TABLE...SELECT on a table with auto-increment column is unsafe
2084       because which rows are replaced depends on the order that rows are
2085       retrieved from SELECT. This order cannot be predicted and may differ on
2086       master and the slave
2087     */
2088     BINLOG_STMT_UNSAFE_CREATE_SELECT_AUTOINC,
2089 
2090     /**
2091       UPDATE...IGNORE is unsafe because which rows are ignored depends on the
2092       order that rows are updated. This order cannot be predicted and may differ
2093       on master and the slave.
2094     */
2095     BINLOG_STMT_UNSAFE_UPDATE_IGNORE,
2096 
2097     /**
2098       INSERT... ON DUPLICATE KEY UPDATE on a table with more than one
2099       UNIQUE KEYS  is unsafe.
2100     */
2101     BINLOG_STMT_UNSAFE_INSERT_TWO_KEYS,
2102 
2103     /**
2104        INSERT into auto-inc field which is not the first part in composed
2105        primary key.
2106     */
2107     BINLOG_STMT_UNSAFE_AUTOINC_NOT_FIRST,
2108 
2109     /**
2110        Using a plugin is unsafe.
2111     */
2112     BINLOG_STMT_UNSAFE_FULLTEXT_PLUGIN,
2113 
2114     /**
2115       XA transactions and statements.
2116     */
2117     BINLOG_STMT_UNSAFE_XA,
2118 
2119     /* The last element of this enumeration type. */
2120     BINLOG_STMT_UNSAFE_COUNT
2121   };
2122   /**
2123     This has all flags from 0 (inclusive) to BINLOG_STMT_FLAG_COUNT
2124     (exclusive) set.
2125   */
2126   static const int BINLOG_STMT_UNSAFE_ALL_FLAGS=
2127     ((1 << BINLOG_STMT_UNSAFE_COUNT) - 1);
2128 
2129   /**
2130     Maps elements of enum_binlog_stmt_unsafe to error codes.
2131   */
2132   static const int binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT];
2133 
2134   /**
2135     Determine if this statement is marked as unsafe.
2136 
2137     @retval 0 if the statement is not marked as unsafe.
2138     @retval nonzero if the statement is marked as unsafe.
2139   */
is_stmt_unsafe()2140   inline bool is_stmt_unsafe() const {
2141     return get_stmt_unsafe_flags() != 0;
2142   }
2143 
is_stmt_unsafe(enum_binlog_stmt_unsafe unsafe)2144   inline bool is_stmt_unsafe(enum_binlog_stmt_unsafe unsafe)
2145   {
2146     return binlog_stmt_flags & (1 << unsafe);
2147   }
2148 
2149   /**
2150     Flag the current (top-level) statement as unsafe.
2151     The flag will be reset after the statement has finished.
2152 
2153     @param unsafe_type The type of unsafety: one of the @c
2154     BINLOG_STMT_FLAG_UNSAFE_* flags in @c enum_binlog_stmt_flag.
2155   */
set_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type)2156   inline void set_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type) {
2157     DBUG_ENTER("set_stmt_unsafe");
2158     assert(unsafe_type >= 0 && unsafe_type < BINLOG_STMT_UNSAFE_COUNT);
2159     binlog_stmt_flags|= (1U << unsafe_type);
2160     DBUG_VOID_RETURN;
2161   }
2162 
2163   /**
2164     Set the bits of binlog_stmt_flags determining the type of
2165     unsafeness of the current statement.  No existing bits will be
2166     cleared, but new bits may be set.
2167 
2168     @param flags A binary combination of zero or more bits, (1<<flag)
2169     where flag is a member of enum_binlog_stmt_unsafe.
2170   */
set_stmt_unsafe_flags(uint32 flags)2171   inline void set_stmt_unsafe_flags(uint32 flags) {
2172     DBUG_ENTER("set_stmt_unsafe_flags");
2173     assert((flags & ~BINLOG_STMT_UNSAFE_ALL_FLAGS) == 0);
2174     binlog_stmt_flags|= flags;
2175     DBUG_VOID_RETURN;
2176   }
2177 
2178   /**
2179     Return a binary combination of all unsafe warnings for the
2180     statement.  If the statement has been marked as unsafe by the
2181     'flag' member of enum_binlog_stmt_unsafe, then the return value
2182     from this function has bit (1<<flag) set to 1.
2183   */
get_stmt_unsafe_flags()2184   inline uint32 get_stmt_unsafe_flags() const {
2185     DBUG_ENTER("get_stmt_unsafe_flags");
2186     DBUG_RETURN(binlog_stmt_flags & BINLOG_STMT_UNSAFE_ALL_FLAGS);
2187   }
2188 
2189   /**
2190     Mark the current statement as safe; i.e., clear all bits in
2191     binlog_stmt_flags that correspond to elements of
2192     enum_binlog_stmt_unsafe.
2193   */
clear_stmt_unsafe()2194   inline void clear_stmt_unsafe() {
2195     DBUG_ENTER("clear_stmt_unsafe");
2196     binlog_stmt_flags&= ~BINLOG_STMT_UNSAFE_ALL_FLAGS;
2197     DBUG_VOID_RETURN;
2198   }
2199 
2200   /**
2201     Determine if this statement is a row injection.
2202 
2203     @retval 0 if the statement is not a row injection
2204     @retval nonzero if the statement is a row injection
2205   */
is_stmt_row_injection()2206   inline bool is_stmt_row_injection() const {
2207     return binlog_stmt_flags &
2208       (1U << (BINLOG_STMT_UNSAFE_COUNT + BINLOG_STMT_TYPE_ROW_INJECTION));
2209   }
2210 
2211   /**
2212     Flag the statement as a row injection.  A row injection is either
2213     a BINLOG statement, or a row event in the relay log executed by
2214     the slave SQL thread.
2215   */
set_stmt_row_injection()2216   inline void set_stmt_row_injection() {
2217     DBUG_ENTER("set_stmt_row_injection");
2218     binlog_stmt_flags|=
2219       (1U << (BINLOG_STMT_UNSAFE_COUNT + BINLOG_STMT_TYPE_ROW_INJECTION));
2220     DBUG_VOID_RETURN;
2221   }
2222 
2223   enum enum_stmt_accessed_table
2224   {
2225     /*
2226        If a transactional table is about to be read. Note that
2227        a write implies a read.
2228     */
2229     STMT_READS_TRANS_TABLE= 0,
2230     /*
2231        If a non-transactional table is about to be read. Note that
2232        a write implies a read.
2233     */
2234     STMT_READS_NON_TRANS_TABLE,
2235     /*
2236        If a temporary transactional table is about to be read. Note
2237        that a write implies a read.
2238     */
2239     STMT_READS_TEMP_TRANS_TABLE,
2240     /*
2241        If a temporary non-transactional table is about to be read. Note
2242       that a write implies a read.
2243     */
2244     STMT_READS_TEMP_NON_TRANS_TABLE,
2245     /*
2246        If a transactional table is about to be updated.
2247     */
2248     STMT_WRITES_TRANS_TABLE,
2249     /*
2250        If a non-transactional table is about to be updated.
2251     */
2252     STMT_WRITES_NON_TRANS_TABLE,
2253     /*
2254        If a temporary transactional table is about to be updated.
2255     */
2256     STMT_WRITES_TEMP_TRANS_TABLE,
2257     /*
2258        If a temporary non-transactional table is about to be updated.
2259     */
2260     STMT_WRITES_TEMP_NON_TRANS_TABLE,
2261     /*
2262       The last element of the enumeration. Please, if necessary add
2263       anything before this.
2264     */
2265     STMT_ACCESS_TABLE_COUNT
2266   };
2267 
2268 #ifndef NDEBUG
stmt_accessed_table_string(enum_stmt_accessed_table accessed_table)2269   static inline const char *stmt_accessed_table_string(enum_stmt_accessed_table accessed_table)
2270   {
2271     switch (accessed_table)
2272     {
2273       case STMT_READS_TRANS_TABLE:
2274          return "STMT_READS_TRANS_TABLE";
2275       break;
2276       case STMT_READS_NON_TRANS_TABLE:
2277         return "STMT_READS_NON_TRANS_TABLE";
2278       break;
2279       case STMT_READS_TEMP_TRANS_TABLE:
2280         return "STMT_READS_TEMP_TRANS_TABLE";
2281       break;
2282       case STMT_READS_TEMP_NON_TRANS_TABLE:
2283         return "STMT_READS_TEMP_NON_TRANS_TABLE";
2284       break;
2285       case STMT_WRITES_TRANS_TABLE:
2286         return "STMT_WRITES_TRANS_TABLE";
2287       break;
2288       case STMT_WRITES_NON_TRANS_TABLE:
2289         return "STMT_WRITES_NON_TRANS_TABLE";
2290       break;
2291       case STMT_WRITES_TEMP_TRANS_TABLE:
2292         return "STMT_WRITES_TEMP_TRANS_TABLE";
2293       break;
2294       case STMT_WRITES_TEMP_NON_TRANS_TABLE:
2295         return "STMT_WRITES_TEMP_NON_TRANS_TABLE";
2296       break;
2297       case STMT_ACCESS_TABLE_COUNT:
2298       default:
2299         assert(0);
2300       break;
2301     }
2302     MY_ASSERT_UNREACHABLE();
2303     return "";
2304   }
2305 #endif  /* DBUG */
2306 
2307   #define BINLOG_DIRECT_ON 0xF0    /* unsafe when
2308                                       --binlog-direct-non-trans-updates
2309                                       is ON */
2310 
2311   #define BINLOG_DIRECT_OFF 0xF    /* unsafe when
2312                                       --binlog-direct-non-trans-updates
2313                                       is OFF */
2314 
2315   #define TRX_CACHE_EMPTY 0x33     /* unsafe when trx-cache is empty */
2316 
2317   #define TRX_CACHE_NOT_EMPTY 0xCC /* unsafe when trx-cache is not empty */
2318 
2319   #define IL_LT_REPEATABLE 0xAA    /* unsafe when < ISO_REPEATABLE_READ */
2320 
2321   #define IL_GTE_REPEATABLE 0x55   /* unsafe when >= ISO_REPEATABLE_READ */
2322 
2323   /**
2324     Sets the type of table that is about to be accessed while executing a
2325     statement.
2326 
2327     @param accessed_table Enumeration type that defines the type of table,
2328                            e.g. temporary, transactional, non-transactional.
2329   */
set_stmt_accessed_table(enum_stmt_accessed_table accessed_table)2330   inline void set_stmt_accessed_table(enum_stmt_accessed_table accessed_table)
2331   {
2332     DBUG_ENTER("LEX::set_stmt_accessed_table");
2333 
2334     assert(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT);
2335     stmt_accessed_table_flag |= (1U << accessed_table);
2336 
2337     DBUG_VOID_RETURN;
2338   }
2339 
2340   /**
2341     Checks if a type of table is about to be accessed while executing a
2342     statement.
2343 
2344     @param accessed_table Enumeration type that defines the type of table,
2345            e.g. temporary, transactional, non-transactional.
2346 
2347     @return
2348       @retval TRUE  if the type of the table is about to be accessed
2349       @retval FALSE otherwise
2350   */
stmt_accessed_table(enum_stmt_accessed_table accessed_table)2351   inline bool stmt_accessed_table(enum_stmt_accessed_table accessed_table)
2352   {
2353     DBUG_ENTER("LEX::stmt_accessed_table");
2354 
2355     assert(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT);
2356 
2357     DBUG_RETURN((stmt_accessed_table_flag & (1U << accessed_table)) != 0);
2358   }
2359 
2360   /*
2361     Checks if a mixed statement is unsafe.
2362 
2363 
2364     @param in_multi_stmt_transaction_mode defines if there is an on-going
2365            multi-transactional statement.
2366     @param binlog_direct defines if --binlog-direct-non-trans-updates is
2367            active.
2368     @param trx_cache_is_not_empty defines if the trx-cache is empty or not.
2369     @param trx_isolation defines the isolation level.
2370 
2371     @return
2372       @retval TRUE if the mixed statement is unsafe
2373       @retval FALSE otherwise
2374   */
is_mixed_stmt_unsafe(bool in_multi_stmt_transaction_mode,bool binlog_direct,bool trx_cache_is_not_empty,uint tx_isolation)2375   inline bool is_mixed_stmt_unsafe(bool in_multi_stmt_transaction_mode,
2376                                    bool binlog_direct,
2377                                    bool trx_cache_is_not_empty,
2378                                    uint tx_isolation)
2379   {
2380     bool unsafe= FALSE;
2381 
2382     if (in_multi_stmt_transaction_mode)
2383     {
2384        uint condition=
2385          (binlog_direct ? BINLOG_DIRECT_ON : BINLOG_DIRECT_OFF) &
2386          (trx_cache_is_not_empty ? TRX_CACHE_NOT_EMPTY : TRX_CACHE_EMPTY) &
2387          (tx_isolation >= ISO_REPEATABLE_READ ? IL_GTE_REPEATABLE : IL_LT_REPEATABLE);
2388 
2389       unsafe= (binlog_unsafe_map[stmt_accessed_table_flag] & condition);
2390 
2391 #if !defined(NDEBUG)
2392       DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("RESULT %02X %02X %02X\n", condition,
2393               binlog_unsafe_map[stmt_accessed_table_flag],
2394               (binlog_unsafe_map[stmt_accessed_table_flag] & condition)));
2395 
2396       int type_in= 0;
2397       for (; type_in < STMT_ACCESS_TABLE_COUNT; type_in++)
2398       {
2399         if (stmt_accessed_table((enum_stmt_accessed_table) type_in))
2400           DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("ACCESSED %s ",
2401                   stmt_accessed_table_string((enum_stmt_accessed_table) type_in)));
2402       }
2403 #endif
2404     }
2405 
2406     if (stmt_accessed_table(STMT_WRITES_NON_TRANS_TABLE) &&
2407       stmt_accessed_table(STMT_READS_TRANS_TABLE) &&
2408       tx_isolation < ISO_REPEATABLE_READ)
2409       unsafe= TRUE;
2410     else if (stmt_accessed_table(STMT_WRITES_TEMP_NON_TRANS_TABLE) &&
2411       stmt_accessed_table(STMT_READS_TRANS_TABLE) &&
2412       tx_isolation < ISO_REPEATABLE_READ)
2413       unsafe= TRUE;
2414 
2415     return(unsafe);
2416   }
2417 
2418   /**
2419     true if the parsed tree contains references to stored procedures
2420     or functions, false otherwise
2421   */
uses_stored_routines()2422   bool uses_stored_routines() const
2423   { return sroutines_list.elements != 0; }
2424 
set_using_match()2425   void set_using_match() { using_match= TRUE; }
get_using_match()2426   bool get_using_match() { return using_match; }
2427 private:
2428 
2429   /**
2430     Enumeration listing special types of statements.
2431 
2432     Currently, the only possible type is ROW_INJECTION.
2433   */
2434   enum enum_binlog_stmt_type {
2435     /**
2436       The statement is a row injection (i.e., either a BINLOG
2437       statement or a row event executed by the slave SQL thread).
2438     */
2439     BINLOG_STMT_TYPE_ROW_INJECTION = 0,
2440 
2441     /** The last element of this enumeration type. */
2442     BINLOG_STMT_TYPE_COUNT
2443   };
2444 
2445   /**
2446     Bit field indicating the type of statement.
2447 
2448     There are two groups of bits:
2449 
2450     - The low BINLOG_STMT_UNSAFE_COUNT bits indicate the types of
2451       unsafeness that the current statement has.
2452 
2453     - The next BINLOG_STMT_TYPE_COUNT bits indicate if the statement
2454       is of some special type.
2455 
2456     This must be a member of LEX, not of THD: each stored procedure
2457     needs to remember its unsafeness state between calls and each
2458     stored procedure has its own LEX object (but no own THD object).
2459   */
2460   uint32 binlog_stmt_flags;
2461 
2462   /**
2463     Bit field that determines the type of tables that are about to be
2464     be accessed while executing a statement.
2465   */
2466   uint32 stmt_accessed_table_flag;
2467 
2468   /**
2469      It will be set TRUE if 'MATCH () AGAINST' is used in the statement.
2470   */
2471   bool using_match;
2472 };
2473 
2474 
2475 /*
2476   st_parsing_options contains the flags for constructions that are
2477   allowed in the current statement.
2478 */
2479 
2480 struct st_parsing_options
2481 {
2482   bool allows_variable;
2483   bool allows_select_into;
2484   bool allows_select_procedure;
2485 
st_parsing_optionsst_parsing_options2486   st_parsing_options() { reset(); }
2487   void reset();
2488 };
2489 
2490 
2491 /**
2492   The state of the lexical parser, when parsing comments.
2493 */
2494 enum enum_comment_state
2495 {
2496   /**
2497     Not parsing comments.
2498   */
2499   NO_COMMENT,
2500 
2501   /**
2502     Parsing comments that need to be preserved.
2503     (Copy '/' '*' and '*' '/' sequences to the preprocessed buffer.)
2504     Typically, these are user comments '/' '*' ... '*' '/'.
2505   */
2506   PRESERVE_COMMENT,
2507 
2508   /**
2509     Parsing comments that need to be discarded.
2510     (Don't copy '/' '*' '!' and '*' '/' sequences to the preprocessed buffer.)
2511     Typically, these are special comments '/' '*' '!' ... '*' '/',
2512     or '/' '*' '!' 'M' 'M' 'm' 'm' 'm' ... '*' '/', where the comment
2513     markers should not be expanded.
2514   */
2515   DISCARD_COMMENT
2516 };
2517 
2518 
2519 /**
2520   This class represents the character input stream consumed during lexical
2521   analysis.
2522 
2523   In addition to consuming the input stream, this class performs some comment
2524   pre processing, by filtering out out-of-bound special text from the query
2525   input stream.
2526 
2527   Two buffers, with pointers inside each, are maintained in parallel. The
2528   'raw' buffer is the original query text, which may contain out-of-bound
2529   comments. The 'cpp' (for comments pre processor) is the pre-processed buffer
2530   that contains only the query text that should be seen once out-of-bound data
2531   is removed.
2532 */
2533 
2534 class Lex_input_stream
2535 {
2536 public:
2537 
2538   /**
2539      Object initializer. Must be called before usage.
2540 
2541      @retval FALSE OK
2542      @retval TRUE  Error
2543   */
2544   bool init(THD *thd, const char *buff, size_t length);
2545 
2546   void reset(const char *buff, size_t length);
2547 
2548   /**
2549     Set the echo mode.
2550 
2551     When echo is true, characters parsed from the raw input stream are
2552     preserved. When false, characters parsed are silently ignored.
2553     @param echo the echo mode.
2554   */
set_echo(bool echo)2555   void set_echo(bool echo)
2556   {
2557     m_echo= echo;
2558   }
2559 
save_in_comment_state()2560   void save_in_comment_state()
2561   {
2562     m_echo_saved= m_echo;
2563     in_comment_saved= in_comment;
2564   }
2565 
restore_in_comment_state()2566   void restore_in_comment_state()
2567   {
2568     m_echo= m_echo_saved;
2569     in_comment= in_comment_saved;
2570   }
2571 
2572   /**
2573     Skip binary from the input stream.
2574     @param n number of bytes to accept.
2575   */
skip_binary(int n)2576   void skip_binary(int n)
2577   {
2578     assert(m_ptr + n <= m_end_of_query);
2579     if (m_echo)
2580     {
2581       memcpy(m_cpp_ptr, m_ptr, n);
2582       m_cpp_ptr += n;
2583     }
2584     m_ptr += n;
2585   }
2586 
2587   /**
2588     Get a character, and advance in the stream.
2589     @return the next character to parse.
2590   */
yyGet()2591   unsigned char yyGet()
2592   {
2593     assert(m_ptr <= m_end_of_query);
2594     char c= *m_ptr++;
2595     if (m_echo)
2596       *m_cpp_ptr++ = c;
2597     return c;
2598   }
2599 
2600   /**
2601     Get the last character accepted.
2602     @return the last character accepted.
2603   */
yyGetLast()2604   unsigned char yyGetLast()
2605   {
2606     return m_ptr[-1];
2607   }
2608 
2609   /**
2610     Look at the next character to parse, but do not accept it.
2611   */
yyPeek()2612   unsigned char yyPeek()
2613   {
2614     assert(m_ptr <= m_end_of_query);
2615     return m_ptr[0];
2616   }
2617 
2618   /**
2619     Look ahead at some character to parse.
2620     @param n offset of the character to look up
2621   */
yyPeekn(int n)2622   unsigned char yyPeekn(int n)
2623   {
2624     assert(m_ptr + n <= m_end_of_query);
2625     return m_ptr[n];
2626   }
2627 
2628   /**
2629     Cancel the effect of the last yyGet() or yySkip().
2630     Note that the echo mode should not change between calls to yyGet / yySkip
2631     and yyUnget. The caller is responsible for ensuring that.
2632   */
yyUnget()2633   void yyUnget()
2634   {
2635     m_ptr--;
2636     if (m_echo)
2637       m_cpp_ptr--;
2638   }
2639 
2640   /**
2641     Accept a character, by advancing the input stream.
2642   */
yySkip()2643   void yySkip()
2644   {
2645     assert(m_ptr <= m_end_of_query);
2646     if (m_echo)
2647       *m_cpp_ptr++ = *m_ptr++;
2648     else
2649       m_ptr++;
2650   }
2651 
2652   /**
2653     Accept multiple characters at once.
2654     @param n the number of characters to accept.
2655   */
yySkipn(int n)2656   void yySkipn(int n)
2657   {
2658     assert(m_ptr + n <= m_end_of_query);
2659     if (m_echo)
2660     {
2661       memcpy(m_cpp_ptr, m_ptr, n);
2662       m_cpp_ptr += n;
2663     }
2664     m_ptr += n;
2665   }
2666 
2667   /**
2668     Puts a character back into the stream, canceling
2669     the effect of the last yyGet() or yySkip().
2670     Note that the echo mode should not change between calls
2671     to unput, get, or skip from the stream.
2672   */
yyUnput(char ch)2673   char *yyUnput(char ch)
2674   {
2675     *--m_ptr= ch;
2676     if (m_echo)
2677       m_cpp_ptr--;
2678     return m_ptr;
2679   }
2680 
2681   /**
2682     Inject a character into the pre-processed stream.
2683 
2684     Note, this function is used to inject a space instead of multi-character
2685     C-comment. Thus there is no boundary checks here (basically, we replace
2686     N-chars by 1-char here).
2687   */
cpp_inject(char ch)2688   char *cpp_inject(char ch)
2689   {
2690     *m_cpp_ptr= ch;
2691     return ++m_cpp_ptr;
2692   }
2693 
2694   /**
2695     End of file indicator for the query text to parse.
2696     @return true if there are no more characters to parse
2697   */
eof()2698   bool eof()
2699   {
2700     return (m_ptr >= m_end_of_query);
2701   }
2702 
2703   /**
2704     End of file indicator for the query text to parse.
2705     @param n number of characters expected
2706     @return true if there are less than n characters to parse
2707   */
eof(int n)2708   bool eof(int n)
2709   {
2710     return ((m_ptr + n) >= m_end_of_query);
2711   }
2712 
2713   /** Get the raw query buffer. */
get_buf()2714   const char *get_buf()
2715   {
2716     return m_buf;
2717   }
2718 
2719   /** Get the pre-processed query buffer. */
get_cpp_buf()2720   const char *get_cpp_buf()
2721   {
2722     return m_cpp_buf;
2723   }
2724 
2725   /** Get the end of the raw query buffer. */
get_end_of_query()2726   const char *get_end_of_query()
2727   {
2728     return m_end_of_query;
2729   }
2730 
2731   /** Mark the stream position as the start of a new token. */
start_token()2732   void start_token()
2733   {
2734     m_tok_start= m_ptr;
2735     m_tok_end= m_ptr;
2736 
2737     m_cpp_tok_start= m_cpp_ptr;
2738     m_cpp_tok_end= m_cpp_ptr;
2739   }
2740 
2741   /**
2742     Adjust the starting position of the current token.
2743     This is used to compensate for starting whitespace.
2744   */
restart_token()2745   void restart_token()
2746   {
2747     m_tok_start= m_ptr;
2748     m_cpp_tok_start= m_cpp_ptr;
2749   }
2750 
2751   /** Get the token start position, in the raw buffer. */
get_tok_start()2752   const char *get_tok_start()
2753   {
2754     return m_tok_start;
2755   }
2756 
2757   /** Get the token start position, in the pre-processed buffer. */
get_cpp_tok_start()2758   const char *get_cpp_tok_start()
2759   {
2760     return m_cpp_tok_start;
2761   }
2762 
2763   /** Get the token end position, in the raw buffer. */
get_tok_end()2764   const char *get_tok_end()
2765   {
2766     return m_tok_end;
2767   }
2768 
2769   /** Get the token end position, in the pre-processed buffer. */
get_cpp_tok_end()2770   const char *get_cpp_tok_end()
2771   {
2772     return m_cpp_tok_end;
2773   }
2774 
2775   /** Get the current stream pointer, in the raw buffer. */
get_ptr()2776   const char *get_ptr()
2777   {
2778     return m_ptr;
2779   }
2780 
2781   /** Get the current stream pointer, in the pre-processed buffer. */
get_cpp_ptr()2782   const char *get_cpp_ptr()
2783   {
2784     return m_cpp_ptr;
2785   }
2786 
2787   /** Get the length of the current token, in the raw buffer. */
yyLength()2788   uint yyLength()
2789   {
2790     /*
2791       The assumption is that the lexical analyser is always 1 character ahead,
2792       which the -1 account for.
2793     */
2794     assert(m_ptr > m_tok_start);
2795     return (uint) ((m_ptr - m_tok_start) - 1);
2796   }
2797 
2798   /** Get the utf8-body string. */
get_body_utf8_str()2799   const char *get_body_utf8_str()
2800   {
2801     return m_body_utf8;
2802   }
2803 
2804   /** Get the utf8-body length. */
get_body_utf8_length()2805   uint get_body_utf8_length()
2806   {
2807     return (uint) (m_body_utf8_ptr - m_body_utf8);
2808   }
2809 
2810   void body_utf8_start(THD *thd, const char *begin_ptr);
2811   void body_utf8_append(const char *ptr);
2812   void body_utf8_append(const char *ptr, const char *end_ptr);
2813   void body_utf8_append_literal(THD *thd,
2814                                 const LEX_STRING *txt,
2815                                 const CHARSET_INFO *txt_cs,
2816                                 const char *end_ptr);
2817 
2818   uint get_lineno(const char *raw_ptr);
2819 
2820   /** Current thread. */
2821   THD *m_thd;
2822 
2823   /** Current line number. */
2824   uint yylineno;
2825 
2826   /** Length of the last token parsed. */
2827   uint yytoklen;
2828 
2829   /** Interface with bison, value of the last token parsed. */
2830   LEX_YYSTYPE yylval;
2831 
2832   /**
2833     LALR(2) resolution, look ahead token.
2834     Value of the next token to return, if any,
2835     or -1, if no token was parsed in advance.
2836     Note: 0 is a legal token, and represents YYEOF.
2837   */
2838   int lookahead_token;
2839 
2840   /** LALR(2) resolution, value of the look ahead token.*/
2841   LEX_YYSTYPE lookahead_yylval;
2842 
2843   /// Skip adding of the current token's digest since it is already added
2844   ///
2845   /// Usually we calculate a digest token by token at the top-level function
2846   /// of the lexer: MYSQLlex(). However, some complex ("hintable") tokens break
2847   /// that data flow: for example, the `SELECT /*+ HINT(t) */` is the single
2848   /// token from the main parser's point of view, and we add the "SELECT"
2849   /// keyword to the digest buffer right after the lex_one_token() call,
2850   /// but the "/*+ HINT(t) */" is a sequence of separate tokens from the hint
2851   /// parser's point of view, and we add those tokens to the digest buffer
2852   /// *inside* the lex_one_token() call. Thus, the usual data flow adds
2853   /// tokens from the "/*+ HINT(t) */" string first, and only than it appends
2854   /// the "SELECT" keyword token to that stream: "/*+ HINT(t) */ SELECT".
2855   /// This is not acceptable, since we use the digest buffer to restore
2856   /// query strings in their normalized forms, so the order of added tokens is
2857   /// important. Thus, we add tokens of "hintable" keywords to a digest buffer
2858   /// right in the hint parser and skip adding of them at the caller with the
2859   /// help of skip_digest flag.
2860   bool skip_digest;
2861 
2862   void add_digest_token(uint token, LEX_YYSTYPE yylval);
2863 
2864   void reduce_digest_token(uint token_left, uint token_right);
2865 
2866   const CHARSET_INFO *query_charset;
2867 
2868 private:
2869   /** Pointer to the current position in the raw input stream. */
2870   char *m_ptr;
2871 
2872   /** Starting position of the last token parsed, in the raw buffer. */
2873   const char *m_tok_start;
2874 
2875   /** Ending position of the previous token parsed, in the raw buffer. */
2876   const char *m_tok_end;
2877 
2878   /** End of the query text in the input stream, in the raw buffer. */
2879   const char *m_end_of_query;
2880 
2881   /** Begining of the query text in the input stream, in the raw buffer. */
2882   const char *m_buf;
2883 
2884   /** Length of the raw buffer. */
2885   size_t m_buf_length;
2886 
2887   /** Echo the parsed stream to the pre-processed buffer. */
2888   bool m_echo;
2889   bool m_echo_saved;
2890 
2891   /** Pre-processed buffer. */
2892   char *m_cpp_buf;
2893 
2894   /** Pointer to the current position in the pre-processed input stream. */
2895   char *m_cpp_ptr;
2896 
2897   /**
2898     Starting position of the last token parsed,
2899     in the pre-processed buffer.
2900   */
2901   const char *m_cpp_tok_start;
2902 
2903   /**
2904     Ending position of the previous token parsed,
2905     in the pre-processed buffer.
2906   */
2907   const char *m_cpp_tok_end;
2908 
2909   /** UTF8-body buffer created during parsing. */
2910   char *m_body_utf8;
2911 
2912   /** Pointer to the current position in the UTF8-body buffer. */
2913   char *m_body_utf8_ptr;
2914 
2915   /**
2916     Position in the pre-processed buffer. The query from m_cpp_buf to
2917     m_cpp_utf_processed_ptr is converted to UTF8-body.
2918   */
2919   const char *m_cpp_utf8_processed_ptr;
2920 
2921 public:
2922 
2923   /** Current state of the lexical analyser. */
2924   enum my_lex_states next_state;
2925 
2926   /**
2927     Position of ';' in the stream, to delimit multiple queries.
2928     This delimiter is in the raw buffer.
2929   */
2930   const char *found_semicolon;
2931 
2932   /** Token character bitmaps, to detect 7bit strings. */
2933   uchar tok_bitmap;
2934 
2935   /** SQL_MODE = IGNORE_SPACE. */
2936   bool ignore_space;
2937 
2938   /**
2939     TRUE if we're parsing a prepared statement: in this mode
2940     we should allow placeholders.
2941   */
2942   bool stmt_prepare_mode;
2943   /**
2944     TRUE if we should allow multi-statements.
2945   */
2946   bool multi_statements;
2947 
2948   /** State of the lexical analyser for comments. */
2949   enum_comment_state in_comment;
2950   enum_comment_state in_comment_saved;
2951 
2952   /**
2953     Starting position of the TEXT_STRING or IDENT in the pre-processed
2954     buffer.
2955 
2956     NOTE: this member must be used within MYSQLlex() function only.
2957   */
2958   const char *m_cpp_text_start;
2959 
2960   /**
2961     Ending position of the TEXT_STRING or IDENT in the pre-processed
2962     buffer.
2963 
2964     NOTE: this member must be used within MYSQLlex() function only.
2965     */
2966   const char *m_cpp_text_end;
2967 
2968   /**
2969     Character set specified by the character-set-introducer.
2970 
2971     NOTE: this member must be used within MYSQLlex() function only.
2972   */
2973   CHARSET_INFO *m_underscore_cs;
2974 
2975   /**
2976     Current statement digest instrumentation.
2977   */
2978   sql_digest_state* m_digest;
2979 
text_string_is_7bit()2980   bool text_string_is_7bit() const { return !(tok_bitmap & 0x80); }
2981 };
2982 
2983 
2984 class LEX_COLUMN : public Sql_alloc
2985 {
2986 public:
2987   String column;
2988   uint rights;
LEX_COLUMN(const String & x,const uint & y)2989   LEX_COLUMN (const String& x,const  uint& y ): column (x),rights (y) {}
2990 };
2991 
2992 
2993 /* The state of the lex parsing. This is saved in the THD struct */
2994 
2995 struct LEX: public Query_tables_list
2996 {
2997   friend bool lex_start(THD *thd);
2998 
2999   SELECT_LEX_UNIT *unit;                 ///< Outer-most query expression
3000   /// @todo: select_lex can be replaced with unit->first-select()
3001   SELECT_LEX *select_lex;                ///< First query block
3002   SELECT_LEX *all_selects_list;          ///< List of all query blocks
3003 private:
3004   /* current SELECT_LEX in parsing */
3005   SELECT_LEX *m_current_select;
3006 
3007 public:
current_selectLEX3008   inline SELECT_LEX *current_select() { return m_current_select; }
set_current_selectLEX3009   inline void set_current_select(SELECT_LEX *select)
3010   {
3011     // (2) Only owning thread could change m_current_select
3012     // (1) bypass for bootstrap and "new THD"
3013     assert(!current_thd || !thd || //(1)
3014            thd == current_thd);    //(2)
3015     m_current_select= select;
3016   }
3017   /// @return true if this is an EXPLAIN statement
is_explainLEX3018   bool is_explain() const { return (describe & DESCRIBE_NORMAL); }
3019   char *length,*dec,*change;
3020   LEX_STRING name;
3021   char *help_arg;
3022   char* to_log;                                 /* For PURGE MASTER LOGS TO */
3023   char* x509_subject,*x509_issuer,*ssl_cipher;
3024   String *wild;
3025   sql_exchange *exchange;
3026   Query_result *result;
3027   Item *default_value, *on_update_value;
3028   LEX_STRING comment, ident;
3029   LEX_USER *grant_user;
3030   LEX_ALTER alter_password;
3031   THD *thd;
3032   Generated_column *gcol_info;
3033 
3034   /* Optimizer hints */
3035   Opt_hints_global *opt_hints_global;
3036 
3037   /* maintain a list of used plugins for this LEX */
3038   typedef Prealloced_array<plugin_ref,
3039     INITIAL_LEX_PLUGIN_LIST_SIZE, true> Plugins_array;
3040   Plugins_array plugins;
3041 
3042   const CHARSET_INFO *charset;
3043 
3044   /// Table being inserted into (may be a view)
3045   TABLE_LIST *insert_table;
3046   /// Leaf table being inserted into (always a base table)
3047   TABLE_LIST *insert_table_leaf;
3048 
3049   /** SELECT of CREATE VIEW statement */
3050   LEX_STRING create_view_select;
3051 
3052   /** Start of 'ON table', in trigger statements.  */
3053   const char* raw_trg_on_table_name_begin;
3054   /** End of 'ON table', in trigger statements. */
3055   const char* raw_trg_on_table_name_end;
3056 
3057   /** Start of clause FOLLOWS/PRECEDES. */
3058   const char* trg_ordering_clause_begin;
3059   /** End (a char after the end) of clause FOLLOWS/PRECEDES. */
3060   const char* trg_ordering_clause_end;
3061 
3062   /* Partition info structure filled in by PARTITION BY parse part */
3063   partition_info *part_info;
3064 
3065   /*
3066     The definer of the object being created (view, trigger, stored routine).
3067     I.e. the value of DEFINER clause.
3068   */
3069   LEX_USER *definer;
3070 
3071   List<Key_part_spec> col_list;
3072   List<Key_part_spec> ref_list;
3073   List<String>	      interval_list;
3074   List<LEX_USER>      users_list;
3075   List<LEX_COLUMN>    columns;
3076 
3077   ulonglong           bulk_insert_row_cnt;
3078 
3079   // LOAD statement-specific fields:
3080 
3081   List<Item>          load_field_list;
3082   List<Item>          load_update_list;
3083   List<Item>          load_value_list;
3084   /*
3085     A list of strings is maintained to store the SET clause command user strings
3086     which are specified in load data operation.  This list will be used
3087     during the reconstruction of "load data" statement at the time of writing
3088     to binary log.
3089   */
3090   List<String>        load_set_str_list;
3091 
3092   // PURGE statement-specific fields:
3093   List<Item>          purge_value_list;
3094 
3095   // KILL statement-specific fields:
3096   List<Item>          kill_value_list;
3097 
3098   // CALL statement-specific fields:
3099   List<Item>          call_value_list;
3100 
3101   // HANDLER statement-specific fields:
3102   List<Item>          *handler_insert_list;
3103 
3104   // other stuff:
3105   List<set_var_base>  var_list;
3106   List<Item_func_set_user_var> set_var_list; // in-query assignment list
3107   List<Item_param>    param_list;
3108   List<LEX_STRING>    view_list; // view list (list of field names in view)
3109 
insert_values_mapLEX3110   void insert_values_map(Field *f1, Field *f2)
3111   {
3112     if (!insert_update_values_map)
3113       insert_update_values_map= new std::map<Field*, Field*>;
3114     insert_update_values_map->insert(std::make_pair(f1, f2));
3115   }
clear_values_mapLEX3116   void clear_values_map()
3117   {
3118     if (insert_update_values_map)
3119     {
3120       insert_update_values_map->clear();
3121       delete insert_update_values_map;
3122       insert_update_values_map= NULL;
3123     }
3124   }
has_values_mapLEX3125   bool has_values_map() const
3126   {
3127     return insert_update_values_map != NULL;
3128   }
begin_values_mapLEX3129   std::map<Field *, Field *>::iterator begin_values_map()
3130   {
3131     return insert_update_values_map->begin();
3132   }
end_values_mapLEX3133   std::map<Field *, Field *>::iterator end_values_map()
3134   {
3135     return insert_update_values_map->end();
3136   }
3137 
3138 private:
3139   /*
3140     With Visual Studio, an std::map will always allocate two small objects
3141     on the heap. Sometimes we put LEX objects in a MEM_ROOT, and never run
3142     the LEX DTOR. To avoid memory leaks, put this std::map on the heap,
3143     and call clear_values_map() at the end of each statement
3144    */
3145   std::map<Field *,Field *> *insert_update_values_map;
3146 public:
3147 
3148   /*
3149     A stack of name resolution contexts for the query. This stack is used
3150     at parse time to set local name resolution contexts for various parts
3151     of a query. For example, in a JOIN ... ON (some_condition) clause the
3152     Items in 'some_condition' must be resolved only against the operands
3153     of the the join, and not against the whole clause. Similarly, Items in
3154     subqueries should be resolved against the subqueries (and outer queries).
3155     The stack is used in the following way: when the parser detects that
3156     all Items in some clause need a local context, it creates a new context
3157     and pushes it on the stack. All newly created Items always store the
3158     top-most context in the stack. Once the parser leaves the clause that
3159     required a local context, the parser pops the top-most context.
3160   */
3161   List<Name_resolution_context> context_stack;
3162 
3163   /**
3164     Argument values for PROCEDURE ANALYSE(); is NULL for other queries
3165   */
3166   Proc_analyse_params *proc_analyse;
3167   SQL_I_List<TABLE_LIST> auxiliary_table_list, save_list;
3168   Create_field	      *last_field;
3169   Item_sum *in_sum_func;
3170   udf_func udf;
3171   HA_CHECK_OPT   check_opt;			// check/repair options
3172   HA_CREATE_INFO create_info;
3173   KEY_CREATE_INFO key_create_info;
3174   LEX_MASTER_INFO mi;				// used by CHANGE MASTER
3175   LEX_SLAVE_CONNECTION slave_connection;
3176   Server_options server_options;
3177   USER_RESOURCES mqh;
3178   LEX_RESET_SLAVE reset_slave_info;
3179   ulong type;
3180   /*
3181     This variable is used in post-parse stage to declare that sum-functions,
3182     or functions which have sense only if GROUP BY is present, are allowed.
3183     For example in a query
3184     SELECT ... FROM ...WHERE MIN(i) == 1 GROUP BY ... HAVING MIN(i) > 2
3185     MIN(i) in the WHERE clause is not allowed in the opposite to MIN(i)
3186     in the HAVING clause. Due to possible nesting of select construct
3187     the variable can contain 0 or 1 for each nest level.
3188   */
3189   nesting_map allow_sum_func;
3190 
3191   Sql_cmd *m_sql_cmd;
3192 
3193   /*
3194     Usually `expr` rule of yacc is quite reused but some commands better
3195     not support subqueries which comes standard with this rule, like
3196     KILL, HA_READ, CREATE/ALTER EVENT etc. Set this to `false` to get
3197     syntax error back.
3198   */
3199   bool expr_allows_subselect;
3200   /*
3201     A special command "PARSE_VCOL_EXPR" is defined for the parser
3202     to translate an expression statement of a generated column
3203     (stored in the *.frm file as a string) into an Item object.
3204     The following flag is used to prevent other applications to use
3205     this command.
3206   */
3207   bool parse_gcol_expr;
3208 
3209   enum SSL_type ssl_type;			/* defined in violite.h */
3210   enum enum_duplicates duplicates;
3211   enum enum_tx_isolation tx_isolation;
3212   enum enum_var_type option_type;
3213   enum enum_view_create_mode create_view_mode;
3214   enum enum_drop_mode drop_mode;
3215 
3216   /// QUERY ID for SHOW PROFILE and EXPLAIN CONNECTION
3217   my_thread_id query_id;
3218   uint profile_options;
3219   uint uint_geom_type;
3220   uint grant, grant_tot_col, which_columns;
3221   enum fk_match_opt fk_match_option;
3222   enum fk_option fk_update_opt;
3223   enum fk_option fk_delete_opt;
3224   uint slave_thd_opt, start_transaction_opt;
3225   int select_number;                     ///< Number of query block (by EXPLAIN)
3226   uint8 describe;
3227   /*
3228     A flag that indicates what kinds of derived tables are present in the
3229     query (0 if no derived tables, otherwise a combination of flags
3230     DERIVED_SUBQUERY and DERIVED_VIEW).
3231   */
3232   uint8 derived_tables;
3233   uint8 create_view_algorithm;
3234   uint8 create_view_check;
3235   uint8 context_analysis_only;
3236   bool drop_if_exists, drop_temporary, local_file;
3237   bool autocommit;
3238   bool verbose, no_write_to_binlog;
3239 
3240   enum enum_yes_no_unknown tx_chain, tx_release;
3241   bool safe_to_cache_query;
3242   bool subqueries;
3243 private:
3244   bool ignore;
3245 public:
is_ignoreLEX3246   bool is_ignore() const { return ignore; }
set_ignoreLEX3247   void set_ignore(bool ignore_param) { ignore= ignore_param; }
3248   st_parsing_options parsing_options;
3249   Alter_info alter_info;
3250   /*
3251     For CREATE TABLE statement last element of table list which is not
3252     part of SELECT or LIKE part (i.e. either element for table we are
3253     creating or last of tables referenced by foreign keys).
3254   */
3255   TABLE_LIST *create_last_non_select_table;
3256   /* Prepared statements SQL syntax:*/
3257   LEX_CSTRING prepared_stmt_name; /* Statement name (in all queries) */
3258   /*
3259     Prepared statement query text or name of variable that holds the
3260     prepared statement (in PREPARE ... queries)
3261   */
3262   LEX_STRING prepared_stmt_code;
3263   /* If true, prepared_stmt_code is a name of variable that holds the query */
3264   bool prepared_stmt_code_is_varref;
3265   /* Names of user variables holding parameters (in EXECUTE) */
3266   List<LEX_STRING> prepared_stmt_params;
3267   sp_head *sphead;
3268   sp_name *spname;
3269   bool sp_lex_in_use;	/* Keep track on lex usage in SPs for error handling */
3270   bool all_privileges;
3271   bool proxy_priv;
3272   /*
3273     Temporary variable to distinguish SET PASSWORD command from others
3274     SQLCOM_SET_OPTION commands. Should be removed when WL#6409 is
3275     introduced.
3276   */
3277   bool is_set_password_sql;
3278   bool contains_plaintext_password;
3279   enum_keep_diagnostics keep_diagnostics;
3280 
3281 private:
3282   bool m_broken; ///< see mark_broken()
3283   /// Current SP parsing context.
3284   /// @see also sp_head::m_root_parsing_ctx.
3285   sp_pcontext *sp_current_parsing_ctx;
3286 
3287 public:
3288 
is_brokenLEX3289   bool is_broken() const { return m_broken; }
3290   /**
3291      Certain permanent transformations (like in2exists), if they fail, may
3292      leave the LEX in an inconsistent state. They should call the
3293      following function, so that this LEX is not reused by another execution.
3294 
3295      @todo If lex_start () were a member function of LEX, the "broken"
3296      argument could always be "true" and thus could be removed.
3297   */
3298   void mark_broken(bool broken= true)
3299   {
3300     if (broken)
3301     {
3302       /*
3303         "OPEN <cursor>" cannot be re-prepared if the cursor uses no tables
3304         ("SELECT FROM DUAL"). Indeed in that case cursor_query is left empty
3305         in constructions of sp_instr_cpush, and thus
3306         sp_lex_instr::parse_expr() cannot re-prepare. So we mark the statement
3307         as broken only if tables are used.
3308       */
3309       if (is_metadata_used())
3310         m_broken= true;
3311     }
3312     else
3313       m_broken= false;
3314   }
3315 
get_sp_current_parsing_ctxLEX3316   sp_pcontext *get_sp_current_parsing_ctx()
3317   { return sp_current_parsing_ctx; }
3318 
set_sp_current_parsing_ctxLEX3319   void set_sp_current_parsing_ctx(sp_pcontext *ctx)
3320   { sp_current_parsing_ctx= ctx; }
3321 
3322   /// Check if the current statement uses meta-data (uses a table or a stored
3323   /// routine).
is_metadata_usedLEX3324   bool is_metadata_used() const
3325   { return query_tables != NULL || sroutines.records > 0; }
3326 
3327 public:
3328   st_sp_chistics sp_chistics;
3329 
3330   Event_parse_data *event_parse_data;
3331 
3332   bool only_view;       /* used for SHOW CREATE TABLE/VIEW */
3333   /*
3334     view created to be run from definer (standard behaviour)
3335   */
3336   uint8 create_view_suid;
3337 
3338   /**
3339     Intended to point to the next word after DEFINER-clause in the
3340     following statements:
3341 
3342       - CREATE TRIGGER (points to "TRIGGER");
3343       - CREATE PROCEDURE (points to "PROCEDURE");
3344       - CREATE FUNCTION (points to "FUNCTION" or "AGGREGATE");
3345       - CREATE EVENT (points to "EVENT")
3346 
3347     This pointer is required to add possibly omitted DEFINER-clause to the
3348     DDL-statement before dumping it to the binlog.
3349   */
3350   const char *stmt_definition_begin;
3351   const char *stmt_definition_end;
3352 
3353   /**
3354     During name resolution search only in the table list given by
3355     Name_resolution_context::first_name_resolution_table and
3356     Name_resolution_context::last_name_resolution_table
3357     (see Item_field::fix_fields()).
3358   */
3359   bool use_only_table_context;
3360 
3361   /*
3362     Reference to a struct that contains information in various commands
3363     to add/create/drop/change table spaces.
3364   */
3365   st_alter_tablespace *alter_tablespace_info;
3366 
3367   bool is_lex_started; /* If lex_start() did run. For debugging. */
3368   /// Set to true while resolving values in ON DUPLICATE KEY UPDATE clause
3369   bool in_update_value_clause;
3370 
3371   /*
3372     The set of those tables whose fields are referenced in all subqueries
3373     of the query.
3374     TODO: possibly this it is incorrect to have used tables in LEX because
3375     with subquery, it is not clear what does the field mean. To fix this
3376     we should aggregate used tables information for selected expressions
3377     into the select_lex.
3378   */
3379   table_map  used_tables;
3380 
3381   class Explain_format *explain_format;
3382 
3383   // Maximum execution time for a statement.
3384   ulong max_execution_time;
3385   /*
3386     To flag the current statement as dependent for binary logging
3387     on explicit_defaults_for_timestamp
3388   */
3389   bool binlog_need_explicit_defaults_ts;
3390   LEX();
3391 
3392   virtual ~LEX();
3393 
3394   /// Reset query context to initial state
3395   void reset();
3396 
3397   /// Create an empty query block within this LEX object.
3398   st_select_lex *new_empty_query_block();
3399 
3400   /// Create query expression object that contains one query block.
3401   st_select_lex *new_query(st_select_lex *curr_select);
3402 
3403   /// Create query block and attach it to the current query expression.
3404   st_select_lex *new_union_query(st_select_lex *curr_select, bool distinct);
3405 
3406   /// Create top-level query expression and query block.
3407   bool new_top_level_query();
3408 
3409   /// Create query expression and query block in existing memory objects.
3410   void new_static_query(SELECT_LEX_UNIT *sel_unit, SELECT_LEX *select);
3411 
is_ps_or_view_context_analysisLEX3412   inline bool is_ps_or_view_context_analysis()
3413   {
3414     return (context_analysis_only &
3415             (CONTEXT_ANALYSIS_ONLY_PREPARE |
3416              CONTEXT_ANALYSIS_ONLY_VIEW));
3417   }
3418 
3419   /**
3420     Set the current query as uncacheable.
3421 
3422     @param cause why this query is uncacheable.
3423 
3424     @details
3425     All query blocks representing subqueries, from the current one up to
3426     the outer-most one, but excluding the main query block, are also set
3427     as uncacheable.
3428   */
set_uncacheableLEX3429   void set_uncacheable(SELECT_LEX *curr_select, uint8 cause)
3430   {
3431     safe_to_cache_query= false;
3432 
3433     if (m_current_select == NULL)
3434       return;
3435     SELECT_LEX *sl;
3436     SELECT_LEX_UNIT *un;
3437     for (sl= curr_select, un= sl->master_unit();
3438 	 un != unit;
3439 	 sl= sl->outer_select(), un= sl->master_unit())
3440     {
3441       sl->uncacheable|= cause;
3442       un->uncacheable|= cause;
3443     }
3444   }
3445   void set_trg_event_type_for_tables();
3446 
3447   TABLE_LIST *unlink_first_table(bool *link_to_local);
3448   void link_first_table_back(TABLE_LIST *first, bool link_to_local);
3449   void first_lists_tables_same();
3450 
3451   bool can_use_merged();
3452   bool can_not_use_merged();
3453   bool only_view_structure();
3454   bool need_correct_ident();
3455   /*
3456     Is this update command where 'WHITH CHECK OPTION' clause is important
3457 
3458     SYNOPSIS
3459       LEX::which_check_option_applicable()
3460 
3461     RETURN
3462       TRUE   have to take 'WHITH CHECK OPTION' clause into account
3463       FALSE  'WHITH CHECK OPTION' clause do not need
3464   */
which_check_option_applicableLEX3465   inline bool which_check_option_applicable()
3466   {
3467     switch (sql_command) {
3468     case SQLCOM_UPDATE:
3469     case SQLCOM_UPDATE_MULTI:
3470     case SQLCOM_INSERT:
3471     case SQLCOM_INSERT_SELECT:
3472     case SQLCOM_REPLACE:
3473     case SQLCOM_REPLACE_SELECT:
3474     case SQLCOM_LOAD:
3475       return TRUE;
3476     default:
3477       return FALSE;
3478     }
3479   }
3480 
3481   void cleanup_after_one_table_open();
3482 
push_contextLEX3483   bool push_context(Name_resolution_context *context)
3484   {
3485     return context_stack.push_front(context);
3486   }
3487 
pop_contextLEX3488   void pop_context()
3489   {
3490     context_stack.pop();
3491   }
3492 
3493   bool copy_db_to(char **p_db, size_t *p_db_length) const;
3494 
current_contextLEX3495   Name_resolution_context *current_context()
3496   {
3497     return context_stack.head();
3498   }
3499   /*
3500     Restore the LEX and THD in case of a parse error.
3501   */
3502   static void cleanup_lex_after_parse_error(THD *thd);
3503 
3504   void reset_n_backup_query_tables_list(Query_tables_list *backup);
3505   void restore_backup_query_tables_list(Query_tables_list *backup);
3506 
3507   bool table_or_sp_used();
3508   bool is_partition_management() const;
3509 
3510   /**
3511     @brief check if the statement is a single-level join
3512     @return result of the check
3513       @retval TRUE  The statement doesn't contain subqueries, unions and
3514                     stored procedure calls.
3515       @retval FALSE There are subqueries, UNIONs or stored procedure calls.
3516   */
is_single_level_stmtLEX3517   bool is_single_level_stmt()
3518   {
3519     /*
3520       This check exploits the fact that the last added to all_select_list is
3521       on its top. So select_lex (as the first added) will be at the tail
3522       of the list.
3523     */
3524     if (select_lex == all_selects_list && !sroutines.records)
3525     {
3526       assert(!all_selects_list->next_select_in_list());
3527       return TRUE;
3528     }
3529     return FALSE;
3530   }
3531 
3532   void release_plugins();
3533 
3534   bool accept(Select_lex_visitor *visitor);
3535 
3536 };
3537 
3538 
3539 /**
3540   The internal state of the syntax parser.
3541   This object is only available during parsing,
3542   and is private to the syntax parser implementation (sql_yacc.yy).
3543 */
3544 class Yacc_state
3545 {
3546 public:
Yacc_state()3547   Yacc_state() : yacc_yyss(NULL), yacc_yyvs(NULL), yacc_yyls(NULL) { reset(); }
3548 
reset()3549   void reset()
3550   {
3551     if (yacc_yyss != NULL) {
3552       my_free(yacc_yyss);
3553       yacc_yyss = NULL;
3554     }
3555     if (yacc_yyvs != NULL) {
3556       my_free(yacc_yyvs);
3557       yacc_yyvs = NULL;
3558     }
3559     if (yacc_yyls != NULL) {
3560       my_free(yacc_yyls);
3561       yacc_yyls = NULL;
3562     }
3563     m_lock_type= TL_READ_DEFAULT;
3564     m_mdl_type= MDL_SHARED_READ;
3565     m_ha_rkey_mode= HA_READ_KEY_EXACT;
3566   }
3567 
3568   ~Yacc_state();
3569 
3570   /**
3571     Reset part of the state which needs resetting before parsing
3572     substatement.
3573   */
reset_before_substatement()3574   void reset_before_substatement()
3575   {
3576     m_lock_type= TL_READ_DEFAULT;
3577     m_mdl_type= MDL_SHARED_READ;
3578     m_ha_rkey_mode= HA_READ_KEY_EXACT; /* Let us be future-proof. */
3579   }
3580 
3581   /**
3582     Bison internal state stack, yyss, when dynamically allocated using
3583     my_yyoverflow().
3584   */
3585   uchar *yacc_yyss;
3586 
3587   /**
3588     Bison internal semantic value stack, yyvs, when dynamically allocated using
3589     my_yyoverflow().
3590   */
3591   uchar *yacc_yyvs;
3592 
3593   /**
3594     Bison internal location value stack, yyls, when dynamically allocated using
3595     my_yyoverflow().
3596   */
3597   uchar *yacc_yyls;
3598 
3599   /**
3600     Type of lock to be used for tables being added to the statement's
3601     table list in table_factor, table_alias_ref, single_multi and
3602     table_wild_one rules.
3603     Statements which use these rules but require lock type different
3604     from one specified by this member have to override it by using
3605     st_select_lex::set_lock_for_tables() method.
3606 
3607     The default value of this member is TL_READ_DEFAULT. The only two
3608     cases in which we change it are:
3609     - When parsing SELECT HIGH_PRIORITY.
3610     - Rule for DELETE. In which we use this member to pass information
3611       about type of lock from delete to single_multi part of rule.
3612 
3613     We should try to avoid introducing new use cases as we would like
3614     to get rid of this member eventually.
3615   */
3616   thr_lock_type m_lock_type;
3617 
3618   /**
3619     The type of requested metadata lock for tables added to
3620     the statement table list.
3621   */
3622   enum_mdl_type m_mdl_type;
3623 
3624   /** Type of condition for key in HANDLER READ statement. */
3625   enum ha_rkey_function m_ha_rkey_mode;
3626 
3627   /*
3628     TODO: move more attributes from the LEX structure here.
3629   */
3630 };
3631 
3632 /**
3633   Input parameters to the parser.
3634 */
3635 struct Parser_input
3636 {
3637   bool m_compute_digest;
3638 
Parser_inputParser_input3639   Parser_input()
3640     : m_compute_digest(false)
3641   {}
3642 };
3643 
3644 /**
3645   Internal state of the parser.
3646   The complete state consist of:
3647   - input parameters that control the parser behavior
3648   - state data used during lexical parsing,
3649   - state data used during syntactic parsing.
3650 */
3651 class Parser_state
3652 {
3653 public:
Parser_state()3654   Parser_state() :
3655     m_input(), m_lip(), m_yacc(), m_comment(false)
3656   {}
3657 
3658   /**
3659      Object initializer. Must be called before usage.
3660 
3661      @retval FALSE OK
3662      @retval TRUE  Error
3663   */
init(THD * thd,const char * buff,size_t length)3664   bool init(THD *thd, const char *buff, size_t length)
3665   {
3666     return m_lip.init(thd, buff, length);
3667   }
3668 
reset(const char * found_semicolon,size_t length)3669   void reset(const char *found_semicolon, size_t length)
3670   {
3671     m_lip.reset(found_semicolon, length);
3672     m_yacc.reset();
3673   }
3674 
3675   /// Signal that the current query has a comment
add_comment()3676   void add_comment()
3677   {
3678      m_comment= true;
3679   }
3680   /// Check whether the current query has a comment
has_comment()3681   bool has_comment() const
3682   {
3683     return m_comment;
3684   }
3685 
3686 public:
3687   Parser_input m_input;
3688   Lex_input_stream m_lip;
3689   Yacc_state m_yacc;
3690   /**
3691     Current performance digest instrumentation.
3692   */
3693   PSI_digest_locker* m_digest_psi;
3694 
3695 private:
3696   bool m_comment;                ///< True if current query contains comments
3697 };
3698 
3699 extern sql_digest_state *
3700 digest_add_token(sql_digest_state *state, uint token, LEX_YYSTYPE yylval);
3701 
3702 extern sql_digest_state *
3703 digest_reduce_token(sql_digest_state *state, uint token_left, uint token_right);
3704 
3705 struct st_lex_local: public LEX
3706 {
newst_lex_local3707   static void *operator new(size_t size) throw()
3708   {
3709     return sql_alloc(size);
3710   }
newst_lex_local3711   static void *operator new(size_t size, MEM_ROOT *mem_root) throw()
3712   {
3713     return alloc_root(mem_root, size);
3714   }
deletest_lex_local3715   static void operator delete(void *ptr,size_t size)
3716   { TRASH(ptr, size); }
deletest_lex_local3717   static void operator delete(void *ptr, MEM_ROOT *mem_root)
3718   { /* Never called */ }
3719 };
3720 
3721 
3722 extern bool lex_init(void);
3723 extern void lex_free(void);
3724 extern bool lex_start(THD *thd);
3725 extern void lex_end(LEX *lex);
3726 extern int MYSQLlex(union YYSTYPE *yylval, struct YYLTYPE *yylloc,
3727                     class THD *thd);
3728 
3729 extern void trim_whitespace(const CHARSET_INFO *cs, LEX_STRING *str);
3730 
3731 extern bool is_lex_native_function(const LEX_STRING *name);
3732 
3733 /**
3734   @} (End of group Semantic_Analysis)
3735 */
3736 
3737 void my_missing_function_error(const LEX_STRING &token, const char *name);
3738 bool is_keyword(const char *name, size_t len);
3739 bool db_is_default_db(const char *db, size_t db_len, const THD *thd);
3740 
3741 #endif /* MYSQL_SERVER */
3742 #endif /* SQL_LEX_INCLUDED */
3743