MySQL  8.0.16
Source Code Documentation
sql_lex.h
Go to the documentation of this file.
1 /* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License, version 2.0,
5  as published by the Free Software Foundation.
6 
7  This program is also distributed with certain software (including
8  but not limited to OpenSSL) that is licensed under separate terms,
9  as designated in a particular file or component or in included license
10  documentation. The authors of MySQL hereby grant you an additional
11  permission to link the program and your derivative works with the
12  separately licensed software that they have included with MySQL.
13 
14  This program is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  GNU General Public License, version 2.0, for more details.
18 
19  You should have received a copy of the GNU General Public License
20  along with this program; if not, write to the Free Software
21  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
22 
23 /**
24  @defgroup GROUP_PARSER Parser
25  @{
26 */
27 
28 #ifndef SQL_LEX_INCLUDED
29 #define SQL_LEX_INCLUDED
30 
31 #include <string.h>
32 #include <sys/types.h>
33 #include <algorithm>
34 #include <map>
35 #include <memory>
36 #include <new>
37 #include <string>
38 #include <type_traits>
39 #include <utility>
40 
41 #include "lex_string.h"
42 #include "m_ctype.h"
43 #include "m_string.h"
44 #include "map_helpers.h"
45 #include "memory_debugging.h"
46 #include "my_base.h"
47 #include "my_compiler.h"
48 #include "my_dbug.h"
49 #include "my_inttypes.h"
50 #include "my_sqlcommand.h"
51 #include "my_sys.h"
52 #include "my_table_map.h"
53 #include "my_thread_local.h"
54 #include "my_time.h"
56 #include "mysql/psi/psi_base.h"
57 #include "mysql_com.h"
58 #include "mysqld_error.h"
59 #include "prealloced_array.h" // Prealloced_array
60 #include "sql/dd/info_schema/table_stats.h" // dd::info_schema::Table_stati...
61 #include "sql/dd/info_schema/tablespace_stats.h" // dd::info_schema::Tablesp...
62 #include "sql/enum_query_type.h"
63 #include "sql/field.h"
64 #include "sql/handler.h"
65 #include "sql/item.h" // Name_resolution_context
66 #include "sql/item_create.h" // Cast_target
67 #include "sql/item_subselect.h" // chooser_compare_func_creator
68 #include "sql/key_spec.h" // KEY_CREATE_INFO
69 #include "sql/lex_symbol.h" // LEX_SYMBOL
70 #include "sql/lexer_yystype.h" // Lexer_yystype
71 #include "sql/mdl.h"
72 #include "sql/mem_root_array.h" // Mem_root_array
73 #include "sql/opt_hints.h"
74 #include "sql/parse_tree_hints.h"
75 #include "sql/parse_tree_node_base.h" // enum_parsing_context
76 #include "sql/query_options.h" // OPTION_NO_CONST_TABLES
79 #include "sql/set_var.h"
80 #include "sql/sql_admin.h"
81 #include "sql/sql_alter.h" // Alter_info
82 #include "sql/sql_array.h"
83 #include "sql/sql_connect.h" // USER_RESOURCES
84 #include "sql/sql_const.h"
85 #include "sql/sql_data_change.h" // enum_duplicates
86 #include "sql/sql_exchange.h"
87 #include "sql/sql_get_diagnostics.h" // Diagnostics_information
88 #include "sql/sql_list.h"
89 #include "sql/sql_plugin_ref.h"
90 #include "sql/sql_servers.h" // Server_options
91 #include "sql/sql_signal.h" // enum_condition_item_name
92 #include "sql/sql_udf.h" // Item_udftype
93 #include "sql/table.h" // TABLE_LIST
94 #include "sql/thr_malloc.h"
95 #include "sql/trigger_def.h" // enum_trigger_action_time_type
96 #include "sql/window_lex.h"
97 #include "sql/xa.h" // xa_option_words
98 #include "sql_chars.h"
99 #include "sql_string.h"
100 #include "thr_lock.h" // thr_lock_type
101 #include "violite.h" // SSL_type
102 
103 class Item_cond;
105 class Item_sum;
106 class Parse_tree_root;
109 class PT_column_attr_base;
111 class PT_ddl_table_option;
112 class PT_item_list;
115 class PT_part_definition;
116 class PT_part_value_item;
118 class PT_part_values;
119 class PT_partition;
120 class PT_partition_option;
121 class PT_preload_keys;
122 class PT_query_expression;
124 class PT_subpartition;
125 class PT_subquery;
126 class PT_table_element;
127 class PT_table_reference;
128 class Protocol;
129 class SELECT_LEX_UNIT;
130 class Select_lex_visitor;
131 class THD;
132 class Window;
133 struct MEM_ROOT;
135 
136 enum class enum_jt_column;
137 enum class enum_jtc_on : uint16;
138 typedef Parse_tree_node_tmpl<struct Alter_tablespace_parse_context>
140 
141 /* YACC and LEX Definitions */
142 
143 class Event_parse_data;
144 class Item_func;
145 class Item_func_match;
147 class SELECT_LEX;
148 class Sql_cmd;
149 class partition_info;
150 class sp_head;
151 class sp_name;
152 class sp_pcontext;
153 struct sql_digest_state;
154 
156 
157 enum class partition_type; // from partition_element.h
158 enum class enum_key_algorithm; // from partition_info.h
159 
160 /*
161  There are 8 different type of table access so there is no more than
162  combinations 2^8 = 256:
163 
164  . STMT_READS_TRANS_TABLE
165 
166  . STMT_READS_NON_TRANS_TABLE
167 
168  . STMT_READS_TEMP_TRANS_TABLE
169 
170  . STMT_READS_TEMP_NON_TRANS_TABLE
171 
172  . STMT_WRITES_TRANS_TABLE
173 
174  . STMT_WRITES_NON_TRANS_TABLE
175 
176  . STMT_WRITES_TEMP_TRANS_TABLE
177 
178  . STMT_WRITES_TEMP_NON_TRANS_TABLE
179 
180  The unsafe conditions for each combination is represented within a byte
181  and stores the status of the option --binlog-direct-non-trans-updates,
182  whether the trx-cache is empty or not, and whether the isolation level
183  is lower than ISO_REPEATABLE_READ:
184 
185  . option (OFF/ON)
186  . trx-cache (empty/not empty)
187  . isolation (>= ISO_REPEATABLE_READ / < ISO_REPEATABLE_READ)
188 
189  bits 0 : . OFF, . empty, . >= ISO_REPEATABLE_READ
190  bits 1 : . OFF, . empty, . < ISO_REPEATABLE_READ
191  bits 2 : . OFF, . not empty, . >= ISO_REPEATABLE_READ
192  bits 3 : . OFF, . not empty, . < ISO_REPEATABLE_READ
193  bits 4 : . ON, . empty, . >= ISO_REPEATABLE_READ
194  bits 5 : . ON, . empty, . < ISO_REPEATABLE_READ
195  bits 6 : . ON, . not empty, . >= ISO_REPEATABLE_READ
196  bits 7 : . ON, . not empty, . < ISO_REPEATABLE_READ
197 */
198 extern uint binlog_unsafe_map[256];
199 /*
200  Initializes the array with unsafe combinations and its respective
201  conditions.
202 */
204 
206 
207 enum class enum_ha_read_modes;
208 
209 /**
210  used by the parser to store internal variable name
211 */
215 };
216 
217 #define YYSTYPE_IS_DECLARED 1
218 union YYSTYPE;
219 
220 /*
221  If we encounter a diagnostics statement (GET DIAGNOSTICS, or e.g.
222  the old SHOW WARNINGS|ERRORS, or "diagnostics variables" such as
223  @@warning_count | @@error_count, we'll set some hints so this
224  information is not lost. DA_KEEP_UNSPECIFIED is used in LEX constructor to
225  avoid leaving variables uninitialized.
226  */
228  DA_KEEP_NOTHING = 0, /**< keep nothing */
229  DA_KEEP_DIAGNOSTICS, /**< keep the diagnostics area */
230  DA_KEEP_COUNTS, /**< keep \@warning_count / \@error_count */
231  DA_KEEP_PARSE_ERROR, /**< keep diagnostics area after parse error */
232  DA_KEEP_UNSPECIFIED /**< keep semantics is unspecified */
233 };
234 
239 };
240 
247 };
248 
249 /**
250  enum_sp_type defines type codes of stored programs.
251 
252  @note these codes are used when dealing with the mysql.routines system table,
253  so they must not be changed.
254 
255  @note the following macros were used previously for the same purpose. Now they
256  are used for ACL only.
257 */
259 
261  DBUG_ASSERT(val >= 1 && val <= 4);
262  return static_cast<enum_sp_type>(val);
263 }
264 
266  return static_cast<longlong>(val);
267 }
268 
269 inline uint to_uint(enum_sp_type val) { return static_cast<uint>(val); }
270 
271 /*
272  Values for the type enum. This reflects the order of the enum declaration
273  in the CREATE TABLE command. These values are used to enumerate object types
274  for the ACL statements.
275 
276  These values were also used for enumerating stored program types. However, now
277  enum_sp_type should be used for that instead of them.
278 */
279 #define TYPE_ENUM_FUNCTION 1
280 #define TYPE_ENUM_PROCEDURE 2
281 #define TYPE_ENUM_TRIGGER 3
282 #define TYPE_ENUM_PROXY 4
283 
284 enum class Acl_type {
285  TABLE = 0,
288 };
289 
291  {C_STRING_WITH_LEN("")},
292  {C_STRING_WITH_LEN("CONTAINS SQL")},
293  {C_STRING_WITH_LEN("NO SQL")},
294  {C_STRING_WITH_LEN("READS SQL DATA")},
295  {C_STRING_WITH_LEN("MODIFIES SQL DATA")}};
296 
298  VIEW_CREATE_NEW, // check that there are not such VIEW/table
299  VIEW_ALTER, // check that VIEW with such name exists
300  VIEW_CREATE_OR_REPLACE // check only that there are not such table
301 };
302 
304  DROP_DEFAULT, // mode is not specified
305  DROP_CASCADE, // CASCADE option
306  DROP_RESTRICT // RESTRICT option
307 };
308 
309 /* Options to add_table_to_list() */
310 #define TL_OPTION_UPDATING 1
311 #define TL_OPTION_FORCE_INDEX 2
312 #define TL_OPTION_IGNORE_LEAVES 4
313 #define TL_OPTION_ALIAS 8
314 
315 /* Structure for db & table in sql_yacc */
316 extern LEX_CSTRING EMPTY_CSTR;
317 extern LEX_CSTRING NULL_CSTR;
318 
319 class Table_function;
320 
321 class Table_ident {
322  public:
327 
328  Table_ident(Protocol *protocol, const LEX_CSTRING &db_arg,
329  const LEX_CSTRING &table_arg, bool force);
330  Table_ident(const LEX_CSTRING &db_arg, const LEX_CSTRING &table_arg)
331  : db(db_arg), table(table_arg), sel(NULL), table_function(NULL) {}
332  Table_ident(const LEX_CSTRING &table_arg)
333  : table(table_arg), sel(NULL), table_function(NULL) {
334  db = NULL_CSTR;
335  }
336  /**
337  This constructor is used only for the case when we create a derived
338  table. A derived table has no name and doesn't belong to any database.
339  Later, if there was an alias specified for the table, it will be set
340  by add_table_to_list.
341  */
343  db = EMPTY_CSTR; /* a subject to casedn_str */
344  table = EMPTY_CSTR;
345  }
346  /*
347  This constructor is used only for the case when we create a table function.
348  It has no name and doesn't belong to any database as it exists only
349  during query execution. Later, if there was an alias specified for the
350  table, it will be set by add_table_to_list.
351  */
352  Table_ident(LEX_CSTRING &table_arg, Table_function *table_func_arg)
353  : table(table_arg), sel(NULL), table_function(table_func_arg) {
354  /* We must have a table name here as this is used with add_table_to_list */
355  db = EMPTY_CSTR; /* a subject to casedn_str */
356  }
357  // True if we can tell from syntax that this is a table function.
358  bool is_table_function() const { return (table_function != nullptr); }
359  // True if we can tell from syntax that this is an unnamed derived table.
360  bool is_derived_table() const { return sel; }
361  void change_db(const char *db_name) {
362  db.str = db_name;
363  db.length = strlen(db_name);
364  }
365 };
366 
369 
370 /**
371  Structure to hold parameters for CHANGE MASTER, START SLAVE, and STOP SLAVE.
372 
373  Remark: this should not be confused with Master_info (and perhaps
374  would better be renamed to st_lex_replication_info). Some fields,
375  e.g., delay, are saved in Relay_log_info, not in Master_info.
376 */
378  /*
379  The array of IGNORE_SERVER_IDS has a preallocation, and is not expected
380  to grow to any significant size, so no instrumentation.
381  */
383  initialize();
384  }
391  char *gtid;
392  char *view_id;
393  const char *channel; // identifier similar to database name
394  enum {
401 
402  /*
403  Enum is used for making it possible to detect if the user
404  changed variable or if it should be left at old value
405  */
406  enum {
410  } ssl,
419 
420  /// Initializes everything to zero/NULL/empty.
421  void initialize();
422  /// Sets all fields to their "unspecified" value.
423  void set_unspecified();
424 
425  private:
426  // Not copyable or assignable.
429 };
430 
432  bool all;
433 };
434 
443 };
444 
446 
447 /*
448  String names used to print a statement with index hints.
449  Keep in sync with index_hint_type.
450 */
451 extern const char *index_hint_type_name[];
453 
454 /*
455  Bits in index_clause_map : one for each possible FOR clause in
456  USE/FORCE/IGNORE INDEX index hint specification
457 */
458 #define INDEX_HINT_MASK_JOIN (1)
459 #define INDEX_HINT_MASK_GROUP (1 << 1)
460 #define INDEX_HINT_MASK_ORDER (1 << 2)
461 
462 #define INDEX_HINT_MASK_ALL \
463  (INDEX_HINT_MASK_JOIN | INDEX_HINT_MASK_GROUP | INDEX_HINT_MASK_ORDER)
464 
465 /* Single element of an USE/FORCE/IGNORE INDEX list specified as a SQL hint */
466 class Index_hint {
467  public:
468  /* The type of the hint : USE/FORCE/IGNORE */
470  /* Where the hit applies to. A bitmask of INDEX_HINT_MASK_<place> values */
472  /*
473  The index name. Empty (str=NULL) name represents an empty list
474  USE INDEX () clause
475  */
477 
478  Index_hint(const char *str, uint length) {
479  key_name.str = str;
481  }
482 
483  void print(const THD *thd, String *str);
484 };
485 
486 /*
487  Class SELECT_LEX_UNIT represents a query expression.
488  Class SELECT_LEX represents a query block.
489  A query expression contains one or more query blocks (more than one means
490  that we have a UNION query).
491  These classes are connected as follows:
492  Both classes have a master, a slave, a next and a prev field.
493  For class SELECT_LEX, master and slave connect to objects of type
494  SELECT_LEX_UNIT, whereas for class SELECT_LEX_UNIT, they connect
495  to SELECT_LEX.
496  master is pointer to outer node.
497  slave is pointer to the first inner node
498 
499  neighbors are two SELECT_LEX or SELECT_LEX_UNIT objects on
500  the same level.
501 
502  The structures are linked with the following pointers:
503  - list of neighbors (next/prev) (prev of first element point to slave
504  pointer of outer structure)
505  - For SELECT_LEX, this is a list of query blocks.
506  - For SELECT_LEX_UNIT, this is a list of subqueries.
507 
508  - pointer to outer node (master), which is
509  If this is SELECT_LEX_UNIT
510  - pointer to outer select_lex.
511  If this is SELECT_LEX
512  - pointer to outer SELECT_LEX_UNIT.
513 
514  - pointer to inner objects (slave), which is either:
515  If this is an SELECT_LEX_UNIT:
516  - first query block that belong to this query expression.
517  If this is an SELECT_LEX
518  - first query expression that belong to this query block (subqueries).
519 
520  - list of all SELECT_LEX objects (link_next/link_prev)
521  This is to be used for things like derived tables creation, where we
522  go through this list and create the derived tables.
523 
524  If query expression contain several query blocks (UNION now,
525  INTERSECT etc later) then it has a special select_lex called
526  fake_select_lex. It used for storing global parameters (like ORDER BY,
527  LIMIT) and executing union.
528  Subqueries used in global ORDER BY clause will be attached to this
529  fake_select_lex, which will allow them to correctly resolve fields of
530  the containing UNION and outer selects.
531 
532  For example for following query:
533 
534  select *
535  from table1
536  where table1.field IN (select * from table1_1_1 union
537  select * from table1_1_2)
538  union
539  select *
540  from table2
541  where table2.field=(select (select f1 from table2_1_1_1_1
542  where table2_1_1_1_1.f2=table2_1_1.f3)
543  from table2_1_1
544  where table2_1_1.f1=table2.f2)
545  union
546  select * from table3;
547 
548  we will have following structure:
549 
550  select1: (select * from table1 ...)
551  select2: (select * from table2 ...)
552  select3: (select * from table3)
553  select1.1.1: (select * from table1_1_1)
554  ...
555 
556  main unit
557  fake0
558  select1 select2 select3
559  |^^ |^
560  s||| ||master
561  l||| |+---------------------------------+
562  a||| +---------------------------------+|
563  v|||master slave ||
564  e||+-------------------------+ ||
565  V| neighbor | V|
566  unit1.1<+==================>unit1.2 unit2.1
567  fake1.1
568  select1.1.1 select 1.1.2 select1.2.1 select2.1.1
569  |^
570  ||
571  V|
572  unit2.1.1.1
573  select2.1.1.1.1
574 
575 
576  relation in main unit will be following:
577  (bigger picture for:
578  main unit
579  fake0
580  select1 select2 select3
581  in the above picture)
582 
583  main unit
584  |^^^^|fake_select_lex
585  |||||+--------------------------------------------+
586  ||||+--------------------------------------------+|
587  |||+------------------------------+ ||
588  ||+--------------+ | ||
589  slave||master | | ||
590  V| neighbor | neighbor | master|V
591  select1<========>select2<========>select3 fake0
592 
593  list of all select_lex will be following (as it will be constructed by
594  parser):
595 
596  select1->select2->select3->select2.1.1->select 2.1.2->select2.1.1.1.1-+
597  |
598  +---------------------------------------------------------------------+
599  |
600  +->select1.1.1->select1.1.2
601 
602 */
603 
604 class JOIN;
605 class PT_with_clause;
606 class Query_result;
607 class Query_result_union;
608 struct LEX;
609 
610 /**
611  This class represents a query expression (one query block or
612  several query blocks combined with UNION).
613 */
615  /**
616  Intrusive double-linked list of all query expressions
617  immediately contained within the same query block.
618  */
621 
622  /**
623  The query block wherein this query expression is contained,
624  NULL if the query block is the outer-most one.
625  */
627  /// The first query block in this query expression.
629 
630  private:
631  /**
632  Marker for subqueries in WHERE, HAVING, ORDER BY, GROUP BY and
633  SELECT item lists.
634  Must be read/written when holding LOCK_query_plan.
635 
636  See Item_subselect::explain_subquery_checker
637  */
639 
640  bool prepared; ///< All query blocks in query expression are prepared
641  bool optimized; ///< All query blocks in query expression are optimized
642  bool executed; ///< Query expression has been executed
643 
646  TABLE *table; /* temporary table using for appending UNION results */
647  /// Object to which the result for this query expression is sent
649 
650  public:
651  /**
652  result of this query can't be cached, bit field, can be :
653  UNCACHEABLE_DEPENDENT
654  UNCACHEABLE_RAND
655  UNCACHEABLE_SIDEEFFECT
656  */
658 
659  explicit SELECT_LEX_UNIT(enum_parsing_context parsing_context);
660 
661  /// @return true for a query expression without UNION or multi-level ORDER
662  bool is_simple() const { return !(is_union() || fake_select_lex); }
663 
664  /// Values for SELECT_LEX_UNIT::cleaned
666  UC_DIRTY, ///< Unit isn't cleaned
667  UC_PART_CLEAN, ///< Unit were cleaned, except JOIN and JOIN_TABs were
668  ///< kept for possible EXPLAIN
669  UC_CLEAN ///< Unit completely cleaned, all underlying JOINs were
670  ///< freed
671  };
672  enum_clean_state cleaned; ///< cleanliness state
673 
674  // list of fields which points to temporary table for union
676  /*
677  list of types of items inside union (used for union & derived tables)
678 
679  Item_type_holders from which this list consist may have pointers to Field,
680  pointers is valid only after preparing SELECTS of this unit and before
681  any SELECT of this unit execution
682 
683  TODO:
684  Possibly this member should be protected, and its direct use replaced
685  by get_unit_column_types(). Check the places where it is used.
686  */
688 
689  /**
690  Pointer to query block containing global parameters for query.
691  Global parameters may include ORDER BY, LIMIT and OFFSET.
692 
693  If this is a union of multiple query blocks, the global parameters are
694  stored in fake_select_lex. If the union doesn't use a temporary table,
695  SELECT_LEX_UNIT::prepare() nulls out fake_select_lex, but saves a copy
696  in saved_fake_select_lex in order to preserve the global parameters.
697 
698  If this is not a union, and the query expression has no multi-level
699  ORDER BY/LIMIT, global parameters are in the single query block.
700 
701  @return query block containing the global parameters
702  */
703  inline SELECT_LEX *global_parameters() const {
704  if (fake_select_lex != NULL)
705  return fake_select_lex;
706  else if (saved_fake_select_lex != NULL)
707  return saved_fake_select_lex;
708  return first_select();
709  }
710  /* LIMIT clause runtime counters */
712  /// Points to subquery if this query expression is used in one, otherwise NULL
714  /**
715  Helper query block for query expression with UNION or multi-level
716  ORDER BY/LIMIT
717  */
719  /**
720  SELECT_LEX that stores LIMIT and OFFSET for UNION ALL when no
721  fake_select_lex is used.
722  */
724  /**
725  Points to last query block which has UNION DISTINCT on its left.
726  In a list of UNIONed blocks, UNION is left-associative; so UNION DISTINCT
727  eliminates duplicates in all blocks up to the first one on its right
728  included. Which is why we only need to remember that query block.
729  */
731 
732  /**
733  The WITH clause which is the first part of this query expression. NULL if
734  none.
735  */
737  /**
738  If this query expression is underlying of a derived table, the derived
739  table. NULL if none.
740  */
742  /**
743  First query block (in this UNION) which references the CTE.
744  NULL if not the query expression of a recursive CTE.
745  */
747 
748  /**
749  If 'this' is body of lateral derived table:
750  map of tables in the same FROM clause as this derived table, and to which
751  the derived table's body makes references.
752  In pre-resolution stages, this is OUTER_REF_TABLE_BIT, just to indicate
753  that this has LATERAL; after resolution, which has found references in the
754  body, this is the proper map (with no PSEUDO_TABLE_BITS anymore).
755  */
757  /**
758  True if the with-recursive algorithm has produced the complete result.
759  In a recursive CTE, a JOIN is executed several times in a loop, and
760  should not be cleaned up (e.g. by join_free()) before all iterations of
761  the loop are done (i.e. before the CTE's result is complete).
762  */
764 
765  /// @return true if query expression can be merged into an outer query
766  bool is_mergeable() const;
767 
768  /// @return true if query expression is recommended to be merged
769  bool merge_heuristic(const LEX *lex) const;
770 
771  /// @return the query block this query expression belongs to as subquery
772  SELECT_LEX *outer_select() const { return master; }
773 
774  /// @return the first query block inside this query expression
775  SELECT_LEX *first_select() const { return slave; }
776 
777  /// @return the next query expression within same query block (next subquery)
778  SELECT_LEX_UNIT *next_unit() const { return next; }
779 
780  /// @return the query result object in use for this query expression
782 
783  /**
784  If this unit is recursive, then this returns the Query_result which holds
785  the rows of the recursive reference read by 'reader':
786  - fake_select_lex reads rows from the union's result
787  - other recursive query blocks read rows from the derived table's result.
788  @param reader Recursive query block belonging to this unit
789  */
790  const Query_result *recursive_result(SELECT_LEX *reader) const;
791 
792  /// Set new query result object for this query expression
794 
795  bool prepare(THD *thd, Query_result *result, ulonglong added_options,
796  ulonglong removed_options);
797  bool optimize(THD *thd);
798  bool execute(THD *thd);
799  bool explain(THD *explain_thd, const THD *query_thd);
800  bool cleanup(THD *thd, bool full);
801  inline void unclean() { cleaned = UC_DIRTY; }
802  void reinit_exec_mechanism();
803 
804  void print(const THD *thd, String *str, enum_query_type query_type);
805  bool accept(Select_lex_visitor *visitor);
806 
807  bool add_fake_select_lex(THD *thd);
808  bool prepare_fake_select_lex(THD *thd);
809  void set_prepared() { prepared = true; }
810  void set_optimized() { optimized = true; }
811  void set_executed() { executed = true; }
812  void reset_executed() { executed = false; }
813  bool is_prepared() const { return prepared; }
814  bool is_optimized() const { return optimized; }
815  bool is_executed() const { return executed; }
817  Query_result_interceptor *old_result);
818  bool prepare_limit(THD *thd, SELECT_LEX *provider);
819  bool set_limit(THD *thd, SELECT_LEX *provider);
820 
821  inline bool is_union() const;
822  bool union_needs_tmp_table(LEX *lex);
823  /// @returns true if mixes UNION DISTINCT and UNION ALL
824  bool mixed_union_operators() const;
825 
826  /// Include a query expression below a query block.
827  void include_down(LEX *lex, SELECT_LEX *outer);
828 
829  /// Exclude this unit and immediately contained select_lex objects
830  void exclude_level();
831 
832  /// Exclude subtree of current unit from tree of SELECTs
833  void exclude_tree(THD *thd);
834 
835  /// Renumber query blocks of a query expression according to supplied LEX
836  void renumber_selects(LEX *lex);
837 
838  friend class SELECT_LEX;
839 
842 
843  enum_parsing_context get_explain_marker(const THD *thd) const;
845  void set_explain_marker_from(THD *thd, const SELECT_LEX_UNIT *u);
846 
847 #ifndef DBUG_OFF
848  /**
849  Asserts that none of {this unit and its children units} is fully cleaned
850  up.
851  */
852  void assert_not_fully_clean();
853 #else
854  void assert_not_fully_clean() {}
855 #endif
856  void invalidate();
857 
858  bool is_recursive() const { return first_recursive != nullptr; }
859 
861 
862  bool clear_corr_ctes();
863 
864  void fix_after_pullout(SELECT_LEX *parent_select, SELECT_LEX *removed_select);
865 
866  /**
867  If unit is a subquery, which forms an object of the upper level (an
868  Item_subselect, a derived TABLE_LIST), adds to this object a map
869  of tables of the upper level which the unit references.
870  */
873  if (item)
875  else if (m_lateral_deps)
876  m_lateral_deps |= map;
877  }
878 
879  /**
880  If unit is a subquery, which forms an object of the upper level (an
881  Item_subselect, a derived TABLE_LIST), returns the place of this object
882  in the upper level query block.
883  */
886  return item ? item->place() : CTX_DERIVED;
887  }
888 
889  bool walk(Item_processor processor, enum_walk walk, uchar *arg);
890 
891  /*
892  An exception: this is the only function that needs to adjust
893  explain_marker.
894  */
895  friend bool parse_view_definition(THD *thd, TABLE_LIST *view_ref);
896 };
897 
899 
900 /**
901  SELECT_LEX type enum
902 */
903 enum class enum_explain_type {
904  EXPLAIN_NONE = 0,
912  // Total:
913  EXPLAIN_total ///< fake type, total number of all valid types
914  // Don't insert new types below this line!
915 };
916 
917 /**
918  This class represents a query block, aka a query specification, which is
919  a query consisting of a SELECT keyword, followed by a table list,
920  optionally followed by a WHERE clause, a GROUP BY, etc.
921 */
922 class SELECT_LEX {
923  public:
924  Item *where_cond() const { return m_where_cond; }
925  void set_where_cond(Item *cond) { m_where_cond = cond; }
926  Item *having_cond() const { return m_having_cond; }
927  void set_having_cond(Item *cond) { m_having_cond = cond; }
928  void set_query_result(Query_result *result) { m_query_result = result; }
930  bool change_query_result(THD *thd, Query_result_interceptor *new_result,
931  Query_result_interceptor *old_result);
932 
933  /// Set base options for a query block (and active options too)
934  void set_base_options(ulonglong options_arg) {
935  DBUG_EXECUTE_IF("no_const_tables", options_arg |= OPTION_NO_CONST_TABLES;);
936 
937  // Make sure we do not overwrite options by accident
939  m_base_options = options_arg;
940  m_active_options = options_arg;
941  }
942 
943  /// Add base options to a query block, also update active options
948  }
949 
950  /**
951  Remove base options from a query block.
952  Active options are also updated, and we assume here that "extra" options
953  cannot override removed base options.
954  */
959  }
960 
961  /// Make active options from base options, supplied options and environment:
962  void make_active_options(ulonglong added_options, ulonglong removed_options);
963 
964  /// Adjust the active option set
966 
967  /// @return the active query options
969 
970  /**
971  Set associated tables as read_only, ie. they cannot be inserted into,
972  updated or deleted from during this statement.
973  Commonly used for query blocks that are part of derived tables or
974  views that are materialized.
975  */
977  // Set all referenced base tables as read only.
978  for (TABLE_LIST *tr = leaf_tables; tr != nullptr; tr = tr->next_leaf)
979  tr->set_readonly();
980  }
981 
982  /// @returns a map of all tables references in the query block
983  table_map all_tables_map() const { return (1ULL << leaf_table_count) - 1; }
984 
985  private:
986  /**
987  Intrusive double-linked list of all query blocks within the same
988  query expression.
989  */
992 
993  /// The query expression containing this query block.
995  /// The first query expression contained within this query block.
997 
998  /// Intrusive double-linked global list of query blocks.
1001 
1002  /// Result of this query block
1004 
1005  /**
1006  Options assigned from parsing and throughout resolving,
1007  should not be modified after resolving is done.
1008  */
1010  /**
1011  Active options. Derived from base options, modifiers added during
1012  resolving and values from session variable option_bits. Since the latter
1013  may change, active options are refreshed per execution of a statement.
1014  */
1016 
1017  public:
1018  /**
1019  result of this query can't be cached, bit field, can be :
1020  UNCACHEABLE_DEPENDENT
1021  UNCACHEABLE_RAND
1022  UNCACHEABLE_SIDEEFFECT
1023  */
1025 
1026  /// True: skip local transformations during prepare() call (used by INSERT)
1028 
1029  /// Describes context of this query block (e.g if it is a derived table).
1031  bool no_table_names_allowed; ///< used for global order by
1032  /**
1033  Context for name resolution for all column references except columns
1034  from joined tables.
1035  */
1037  /**
1038  Pointer to first object in list of Name res context objects that have
1039  this query block as the base query block.
1040  Includes field "context" which is embedded in this query block.
1041  */
1043  /**
1044  Three fields used by semi-join transformations to know when semi-join is
1045  possible, and in which condition tree the subquery predicate is located.
1046  */
1053  };
1054  Resolve_place resolve_place; ///< Indicates part of query being resolved
1055  TABLE_LIST *resolve_nest; ///< Used when resolving outer join condition
1056  /**
1057  Disables semi-join flattening when resolving a subtree in which flattening
1058  is not allowed. The flag should be true while resolving items that are not
1059  on the AND-top-level of a condition tree.
1060  */
1062  char *db;
1063 
1064  private:
1065  /**
1066  Condition to be evaluated after all tables in a query block are joined.
1067  After all permanent transformations have been conducted by
1068  SELECT_LEX::prepare(), this condition is "frozen", any subsequent changes
1069  to it must be done with change_item_tree(), unless they only modify AND/OR
1070  items and use a copy created by SELECT_LEX::get_optimizable_conditions().
1071  Same is true for 'having_cond'.
1072  */
1074 
1075  /// Condition to be evaluated on grouped rows after grouping.
1077 
1078  public:
1079  /**
1080  Saved values of the WHERE and HAVING clauses. Allowed values are:
1081  - COND_UNDEF if the condition was not specified in the query or if it
1082  has not been optimized yet
1083  - COND_TRUE if the condition is always true
1084  - COND_FALSE if the condition is impossible
1085  - COND_OK otherwise
1086  */
1089 
1090  /// Reference to LEX that this query block belongs to
1092  /// Indicates whether this query block contains the WITH ROLLUP clause
1094  /// List of tables in FROM clause - use TABLE_LIST::next_local to traverse
1096 
1097  /**
1098  GROUP BY clause.
1099  This list may be mutated during optimization (by remove_const()),
1100  so for prepared statements, we keep a copy of the ORDER.next pointers in
1101  group_list_ptrs, and re-establish the original list before each execution.
1102  */
1105 
1106  /**
1107  All windows defined on the select, both named and inlined
1108  */
1110 
1111  /**
1112  List of columns and expressions:
1113  SELECT: Columns and expressions in the SELECT list.
1114  UPDATE: Columns in the SET clause.
1115  */
1118 
1119  /// Number of GROUP BY expressions added to all_fields
1121 
1122  List<Item> &fields_list; ///< hold field list
1123  List<Item> all_fields; ///< to store all expressions used in query
1124  /**
1125  Usually a pointer to ftfunc_list_alloc, but in UNION this is used to create
1126  fake select_lex that consolidates result fields of UNION
1127  */
1130  /**
1131  After optimization it is pointer to corresponding JOIN. This member
1132  should be changed only when THD::LOCK_query_plan mutex is taken.
1133  */
1135  /// join list of the top level
1137  /// list for the currently parsed join
1139  /// table embedding the above list
1141  /// List of semi-join nests generated for this query block
1143  /**
1144  Points to first leaf table of query block. After setup_tables() is done,
1145  this is a list of base tables and derived tables. After derived tables
1146  processing is done, this is a list of base tables only.
1147  Use TABLE_LIST::next_leaf to traverse the list.
1148  */
1150  /// Number of leaf tables in this query block.
1152  /// Number of derived tables and views in this query block.
1154  /// Number of table functions in this query block
1156  /// Number of materialized derived tables and views in this query block.
1158  /**
1159  True if query block has semi-join nests merged into it. Notice that this
1160  is updated earlier than sj_nests, so check this if info is needed
1161  before the full resolver process is complete.
1162  */
1164  /// Number of partitioned tables
1166 
1167  /**
1168  ORDER BY clause.
1169  This list may be mutated during optimization (by remove_const()),
1170  so for prepared statements, we keep a copy of the ORDER.next pointers in
1171  order_list_ptrs, and re-establish the original list before each execution.
1172  */
1175 
1176  /// LIMIT clause, NULL if no limit is given
1178  /// LIMIT ... OFFSET clause, NULL if no offset is given
1180 
1181  /**
1182  Array of pointers to "base" items; one each for every selected expression
1183  and referenced item in the query block. All references to fields are to
1184  buffers associated with the primary input tables.
1185  */
1187 
1188  /**
1189  number of items in select_list and HAVING clause used to get number
1190  bigger then can be number of entries that will be added to all item
1191  list during split_sum_func
1192  */
1194  uint cond_count; ///< number of arguments of and/or/xor in where/having/on
1195  uint between_count; ///< number of between predicates in where/having/on
1196  uint max_equal_elems; ///< maximal number of elements in multiple equalities
1197  /**
1198  Number of fields used in select list or where clause of current select
1199  and all inner subselects.
1200  */
1202 
1203  /// Parse context: indicates where the current expression is being parsed
1205  /// Parse context: is inside a set function if this is positive
1207 
1208  /**
1209  True if contains or aggregates set functions.
1210  @note this is wrong when a locally found set function is aggregated
1211  in an outer query block.
1212  */
1214  /// Number of Item_sum-derived objects in this SELECT
1216  /// Number of Item_sum-derived objects in children and descendant SELECTs
1218 
1219  uint select_number; ///< Query block number (used for EXPLAIN)
1220  /**
1221  Nesting level of query block, outer-most query block has level 0,
1222  its subqueries have level 1, etc. @see also sql/item_sum.h.
1223  */
1225  /// Circular linked list of sum func in nested selects
1227  /**
1228  Number of wildcards used in the SELECT list. For example,
1229  SELECT *, t1.*, catalog.t2.* FROM t0, t1, t2;
1230  has 3 wildcards.
1231  */
1233  bool braces; ///< SELECT ... UNION (SELECT ... ) <- this braces
1234  /// true when having fix field called in processing of this query block
1236  /// true when GROUP BY fix field called in processing of this query block
1238 
1239  /// explicit LIMIT clause is used
1241  /**
1242  HAVING clause contains subquery => we can't close tables before
1243  query processing end even if we use temporary table
1244  */
1246  /**
1247  This variable is required to ensure proper work of subqueries and
1248  stored procedures. Generally, one should use the states of
1249  Query_arena to determine if it's a statement prepare or first
1250  execution of a stored procedure. However, in case when there was an
1251  error during the first execution of a stored procedure, the SP body
1252  is not expelled from the SP cache. Therefore, a deeply nested
1253  subquery might be left unoptimized. So we need this per-subquery
1254  variable to inidicate the optimization/execution state of every
1255  subquery. Prepared statements work OK in that regard, as in
1256  case of an error during prepare the PS is not created.
1257  */
1259  /// True when semi-join pull-out processing is complete
1261  /// exclude this query block from unique_table() check
1263  /// Allow merge of immediate unnamed derived tables
1265  /**
1266  If this query block is a recursive member of a recursive unit: the
1267  TABLE_LIST, in this recursive member, referencing the query
1268  name.
1269  */
1271  /**
1272  To pass the first steps of resolution, a recursive reference is made to
1273  be a dummy derived table; after the temporary table is created based on
1274  the non-recursive members' types, the recursive reference is made to be a
1275  reference to the tmp table. Its dummy-derived-table unit is saved in this
1276  member, so that when the statement's execution ends, the reference can be
1277  restored to be a dummy derived table for the next execution, which is
1278  necessary if we have a prepared statement.
1279  WL#6570 should allow to remove this.
1280  */
1282  /**
1283  The set of those tables whose fields are referenced in the select list of
1284  this select level.
1285  */
1287  table_map outer_join; ///< Bitmap of all inner tables from outer joins
1288 
1289  /// Query-block-level hints, for this query block
1291 
1292  // Last table for LATERAL join, used by table functions
1294  /**
1295  @note the group_by and order_by lists below will probably be added to the
1296  constructor when the parser is converted into a true bottom-up design.
1297 
1298  //SQL_I_LIST<ORDER> *group_by, SQL_I_LIST<ORDER> order_by
1299  */
1300  SELECT_LEX(Item *where, Item *having);
1301 
1302  SELECT_LEX_UNIT *master_unit() const { return master; }
1304  SELECT_LEX *outer_select() const { return master->outer_select(); }
1305  SELECT_LEX *next_select() const { return next; }
1306 
1307  /**
1308  @return true If STRAIGHT_JOIN applies to all tables.
1309  @return false Else.
1310  */
1312  bool straight_join = true;
1313  /// false for exmaple in t1 STRAIGHT_JOIN t2 JOIN t3.
1314  for (TABLE_LIST *tbl = leaf_tables->next_leaf; tbl; tbl = tbl->next_leaf)
1315  straight_join &= tbl->straight;
1316  return straight_join || (active_options() & SELECT_STRAIGHT_JOIN);
1317  }
1318 
1320  SELECT_LEX *mylast = this;
1321  for (; mylast->next_select(); mylast = mylast->next_select()) {
1322  }
1323  return mylast;
1324  }
1325 
1327 
1328  void mark_as_dependent(SELECT_LEX *last, bool aggregate);
1329 
1330  /// @return true if query block is explicitly grouped (non-empty GROUP BY)
1331  bool is_explicitly_grouped() const { return group_list.elements > 0; }
1332 
1333  /**
1334  @return true if this query block is implicitly grouped, ie it is not
1335  explicitly grouped but contains references to set functions.
1336  The query will return max. 1 row (@see also is_single_grouped()).
1337  */
1338  bool is_implicitly_grouped() const {
1339  return m_agg_func_used && group_list.elements == 0;
1340  }
1341 
1342  /**
1343  True if this query block is implicitly grouped.
1344 
1345  @note Not reliable before name resolution.
1346 
1347  @return true if this query block is implicitly grouped and returns exactly
1348  one row, which happens when it does not have a HAVING clause.
1349 
1350  @remark This function is currently unused.
1351  */
1352  bool is_single_grouped() const {
1353  return m_agg_func_used && group_list.elements == 0 && m_having_cond == NULL;
1354  }
1355 
1356  /**
1357  @return true if this query block is explicitly or implicitly grouped.
1358  @note a query with DISTINCT is not considered to be aggregated.
1359  @note in standard SQL, a query with HAVING is defined as grouped, however
1360  MySQL allows HAVING without any aggregation to be the same as WHERE.
1361  */
1362  bool is_grouped() const { return group_list.elements > 0 || m_agg_func_used; }
1363 
1364  /// @return true if this query block contains DISTINCT at start of select list
1365  bool is_distinct() const { return active_options() & SELECT_DISTINCT; }
1366 
1367  /**
1368  @return true if this query block contains an ORDER BY clause.
1369 
1370  @note returns false if ORDER BY has been eliminated, e.g if the query
1371  can return max. 1 row.
1372  */
1373  bool is_ordered() const { return order_list.elements > 0; }
1374 
1375  /// @return true if this query block has a LIMIT clause
1376  bool has_limit() const { return select_limit != NULL; }
1377 
1378  /// @return true if query block references full-text functions
1379  bool has_ft_funcs() const { return ftfunc_list->elements > 0; }
1380 
1381  /// @returns true if query block is a recursive member of a recursive unit
1382  bool is_recursive() const { return recursive_reference != nullptr; }
1383 
1384  /// @returns true if query block contains window functions
1385  bool has_windows() const { return m_windows.elements > 0; }
1386 
1387  void invalidate();
1388 
1389  bool set_braces(bool value);
1390  uint get_in_sum_expr() const { return in_sum_expr; }
1391 
1392  bool add_item_to_list(Item *item);
1393  bool add_ftfunc_to_list(Item_func_match *func);
1394  void add_order_to_list(ORDER *order);
1396  THD *thd, Table_ident *table, const char *alias, ulong table_options,
1398  List<Index_hint> *hints = 0, List<String> *partition_names = 0,
1399  LEX_STRING *option = 0, Parse_context *pc = NULL);
1401  bool init_nested_join(THD *thd);
1403  TABLE_LIST *nest_last_join(THD *thd, size_t table_cnt = 2);
1404  bool add_joined_table(TABLE_LIST *table);
1407 
1408  // Check privileges for views that are merged into query block
1409  bool check_view_privileges(THD *thd, ulong want_privilege_first,
1410  ulong want_privilege_next);
1411 
1412  // Resolve and prepare information about tables for one query block
1413  bool setup_tables(THD *thd, TABLE_LIST *tables, bool select_insert);
1414 
1415  // Resolve derived table, view, table function information for a query block
1416  bool resolve_placeholder_tables(THD *thd, bool apply_semijoin);
1417 
1418  // Propagate exclusion from table uniqueness test into subqueries
1420 
1421  // Add full-text function elements from a list into this query block
1422  bool add_ftfunc_list(List<Item_func_match> *ftfuncs);
1423 
1425 
1426  void set_lock_for_tables(thr_lock_type lock_type);
1427 
1428  inline void init_order() {
1430  order_list.elements = 0;
1431  order_list.first = 0;
1433  }
1434  /*
1435  This method created for reiniting LEX in mysql_admin_table() and can be
1436  used only if you are going remove all SELECT_LEX & units except belonger
1437  to LEX (LEX::unit & LEX::select, for other purposes use
1438  SELECT_LEX_UNIT::exclude_level()
1439  */
1440  void cut_subtree() { slave = 0; }
1441  bool test_limit();
1442  /**
1443  Get offset for LIMIT.
1444 
1445  Evaluate offset item if necessary.
1446 
1447  @return Number of rows to skip.
1448 
1449  @todo Integrate better with SELECT_LEX_UNIT::set_limit()
1450  */
1451  ha_rows get_offset(THD *thd);
1452  /**
1453  Get limit.
1454 
1455  Evaluate limit item if necessary.
1456 
1457  @return Limit of rows in result.
1458 
1459  @todo Integrate better with SELECT_LEX_UNIT::set_limit()
1460  */
1461  ha_rows get_limit(THD *thd);
1462 
1463  /// Assign a default name resolution object for this query block.
1464  bool set_context(Name_resolution_context *outer_context);
1465 
1466  /// Setup the array containing references to base items
1467  bool setup_base_ref_items(THD *thd);
1468  void print(const THD *thd, String *str, enum_query_type query_type);
1469 
1470  /**
1471  Print detail of the SELECT_LEX object.
1472 
1473  @param thd Thread handler
1474  @param query_type Options to print out string output
1475  @param[out] str String of output.
1476  */
1477  void print_select(const THD *thd, String *str, enum_query_type query_type);
1478 
1479  /**
1480  Print detail of the UPDATE statement.
1481 
1482  @param thd Thread handler
1483  @param[out] str String of output
1484  @param query_type Options to print out string output
1485  */
1486  void print_update(const THD *thd, String *str, enum_query_type query_type);
1487 
1488  /**
1489  Print detail of the DELETE statement.
1490 
1491  @param thd Thread handler
1492  @param[out] str String of output
1493  @param query_type Options to print out string output
1494  */
1495  void print_delete(const THD *thd, String *str, enum_query_type query_type);
1496 
1497  /**
1498  Print detail of the INSERT statement.
1499 
1500  @param thd Thread handler
1501  @param[out] str String of output
1502  @param query_type Options to print out string output
1503  */
1504  void print_insert(const THD *thd, String *str, enum_query_type query_type);
1505 
1506  /**
1507  Print detail of Hints.
1508 
1509  @param thd Thread handler
1510  @param[out] str String of output
1511  @param query_type Options to print out string output
1512  */
1513  void print_hints(const THD *thd, String *str, enum_query_type query_type);
1514 
1515  /**
1516  Print error.
1517 
1518  @param thd Thread handler
1519  @param[out] str String of output
1520 
1521  @return
1522  @retval false If there is no error
1523  @retval true else
1524  */
1525  bool print_error(const THD *thd, String *str);
1526 
1527  /**
1528  Print select options.
1529 
1530  @param[out] str String of output
1531  */
1532  void print_select_options(String *str);
1533 
1534  /**
1535  Print UPDATE options.
1536 
1537  @param[out] str String of output
1538  */
1539  void print_update_options(String *str);
1540 
1541  /**
1542  Print DELETE options.
1543 
1544  @param[out] str String of output
1545  */
1546  void print_delete_options(String *str);
1547 
1548  /**
1549  Print INSERT options.
1550 
1551  @param[out] str String of output
1552  */
1553  void print_insert_options(String *str);
1554 
1555  /**
1556  Print list of tables.
1557 
1558  @param thd Thread handler
1559  @param[out] str String of output
1560  @param table_list TABLE_LIST object
1561  @param query_type Options to print out string output
1562  */
1563  void print_table_references(const THD *thd, String *str,
1565  enum_query_type query_type);
1566 
1567  /**
1568  Print list of items in SELECT_LEX object.
1569 
1570  @param thd Thread handle
1571  @param[out] str String of output
1572  @param query_type Options to print out string output
1573  */
1574  void print_item_list(const THD *thd, String *str, enum_query_type query_type);
1575 
1576  /**
1577  Print assignments list. Used in UPDATE and
1578  INSERT ... ON DUPLICATE KEY UPDATE ...
1579 
1580  @param thd Thread handle
1581  @param[out] str String of output
1582  @param query_type Options to print out string output
1583  @param fields List columns to be assigned.
1584  @param values List of values.
1585  */
1586  void print_update_list(const THD *thd, String *str,
1587  enum_query_type query_type, List<Item> fields,
1588  List<Item> values);
1589 
1590  /**
1591  Print column list to be inserted into. Used in INSERT.
1592 
1593  @param thd Thread handle
1594  @param[out] str String of output
1595  @param query_type Options to print out string output
1596  */
1597  void print_insert_fields(const THD *thd, String *str,
1598  enum_query_type query_type);
1599 
1600  /**
1601  Print list of values to be inserted. Used in INSERT.
1602 
1603  @param thd Thread handle
1604  @param[out] str String of output
1605  @param query_type Options to print out string output
1606  */
1607  void print_insert_values(const THD *thd, String *str,
1608  enum_query_type query_type);
1609 
1610  /**
1611  Print list of tables in FROM clause.
1612 
1613  @param thd Thread handler
1614  @param[out] str String of output
1615  @param query_type Options to print out string output
1616  */
1617  void print_from_clause(const THD *thd, String *str,
1618  enum_query_type query_type);
1619 
1620  /**
1621  Print list of conditions in WHERE clause.
1622 
1623  @param thd Thread handle
1624  @param[out] str String of output
1625  @param query_type Options to print out string output
1626  */
1627  void print_where_cond(const THD *thd, String *str,
1628  enum_query_type query_type);
1629 
1630  /**
1631  Print list of items in GROUP BY clause.
1632 
1633  @param thd Thread handle
1634  @param[out] str String of output
1635  @param query_type Options to print out string output
1636  */
1637  void print_group_by(const THD *thd, String *str, enum_query_type query_type);
1638 
1639  /**
1640  Print list of items in HAVING clause.
1641 
1642  @param thd Thread handle
1643  @param[out] str String of output
1644  @param query_type Options to print out string output
1645  */
1646  void print_having(const THD *thd, String *str, enum_query_type query_type);
1647 
1648  /**
1649  Print details of Windowing functions.
1650 
1651  @param thd Thread handler
1652  @param[out] str String of output
1653  @param query_type Options to print out string output
1654  */
1655  void print_windows(const THD *thd, String *str, enum_query_type query_type);
1656 
1657  /**
1658  Print list of items in ORDER BY clause.
1659 
1660  @param thd Thread handle
1661  @param[out] str String of output
1662  @param query_type Options to print out string output
1663  */
1664  void print_order_by(const THD *thd, String *str, enum_query_type query_type);
1665 
1666  static void print_order(const THD *thd, String *str, ORDER *order,
1667  enum_query_type query_type);
1668  void print_limit(const THD *thd, String *str, enum_query_type query_type);
1669  void fix_prepare_information(THD *thd);
1670 
1671  /**
1672  Accept function for SELECT and DELETE.
1673 
1674  @param visitor Select_lex_visitor Object
1675  */
1676  bool accept(Select_lex_visitor *visitor);
1677 
1678  /**
1679  Cleanup this subtree (this SELECT_LEX and all nested SELECT_LEXes and
1680  SELECT_LEX_UNITs).
1681  @param thd thread handle
1682  @param full if false only partial cleanup is done, JOINs and JOIN_TABs are
1683  kept to provide info for EXPLAIN CONNECTION; if true, complete cleanup is
1684  done, all JOINs are freed.
1685  */
1686  bool cleanup(THD *thd, bool full);
1687  /*
1688  Recursively cleanup the join of this select lex and of all nested
1689  select lexes. This is not a full cleanup.
1690  */
1691  void cleanup_all_joins();
1692 
1693  /// Return true if this query block is part of a UNION
1694  bool is_part_of_union() const { return master_unit()->is_union(); }
1695 
1696  /**
1697  @return true if query block is found during preparation to produce no data.
1698  Notice that if query is implicitly grouped, an aggregation row will
1699  still be returned.
1700  */
1701  bool is_empty_query() const { return m_empty_query; }
1702 
1703  /// Set query block as returning no data
1704  /// @todo This may also be set when we have an always false WHERE clause
1706  DBUG_ASSERT(join == NULL);
1707  m_empty_query = true;
1708  }
1709  /*
1710  For MODE_ONLY_FULL_GROUP_BY we need to know if
1711  this query block is the aggregation query of at least one aggregate
1712  function.
1713  */
1714  bool agg_func_used() const { return m_agg_func_used; }
1715  bool json_agg_func_used() const { return m_json_agg_func_used; }
1716 
1717  void set_agg_func_used(bool val) { m_agg_func_used = val; }
1718 
1720 
1721  /// Lookup for SELECT_LEX type
1723 
1724  /// Lookup for a type string
1725  const char *get_type_str() { return type_str[static_cast<int>(type())]; }
1726  static const char *get_type_str(enum_explain_type type) {
1727  return type_str[static_cast<int>(type)];
1728  }
1729 
1731  bool is_cacheable() const { return !uncacheable; }
1732 
1733  /// Include query block inside a query expression.
1734  void include_down(LEX *lex, SELECT_LEX_UNIT *outer);
1735 
1736  /// Include a query block next to another query block.
1737  void include_neighbour(LEX *lex, SELECT_LEX *before);
1738 
1739  /// Include query block inside a query expression, but do not link.
1740  void include_standalone(SELECT_LEX_UNIT *sel, SELECT_LEX **ref);
1741 
1742  /// Include query block into global list.
1743  void include_in_global(SELECT_LEX **plink);
1744 
1745  /// Include chain of query blocks into global list.
1747 
1748  /// Renumber query blocks of contained query expressions
1749  void renumber(LEX *lex);
1750 
1751  /**
1752  Does permanent transformations which are local to a query block (which do
1753  not merge it to another block).
1754  */
1755  bool apply_local_transforms(THD *thd, bool prune);
1756 
1757  bool get_optimizable_conditions(THD *thd, Item **new_where,
1758  Item **new_having);
1759 
1760  bool validate_outermost_option(LEX *lex, const char *wrong_option) const;
1761  bool validate_base_options(LEX *lex, ulonglong options) const;
1762 
1763  bool walk(Item_processor processor, enum_walk walk, uchar *arg);
1764 
1765  private:
1766  // Delete unused columns from merged derived tables
1768 
1771 
1772  /**
1773  True if query block does not generate any rows before aggregation,
1774  determined during preparation (not optimization).
1775  */
1777 
1778  /// Helper for fix_prepare_information()
1780  Group_list_ptrs **list_ptrs);
1781  static const char
1783 
1784  friend class SELECT_LEX_UNIT;
1786  bool simplify_joins(THD *thd, List<TABLE_LIST> *join_list, bool top,
1787  bool in_sj, Item **new_conds, uint *changelog = NULL);
1788  /// Merge derived table into query block
1789  public:
1791  /// Remove semijoin condition for this query block
1792  void clear_sj_expressions(NESTED_JOIN *nested_join);
1793  /// Build semijoin condition for th query block
1794  bool build_sj_cond(THD *thd, NESTED_JOIN *nested_join,
1795  SELECT_LEX *subq_select, table_map outer_tables_map,
1796  Item **sj_cond);
1797  bool decorrelate_where_cond(TABLE_LIST *sj_nest);
1798 
1799  private:
1801  void remap_tables(THD *thd);
1802  bool resolve_subquery(THD *thd);
1803  bool resolve_rollup_item(THD *thd, Item *item);
1804  bool resolve_rollup(THD *thd);
1805 
1806  public:
1807  bool resolve_rollup_wfs(THD *thd);
1808  bool change_group_ref_for_func(THD *thd, Item *func, bool *changed);
1809  bool change_group_ref_for_cond(THD *thd, Item_cond *cond, bool *changed);
1810  bool flatten_subqueries(THD *thd);
1812  sj_candidates = sj_cand;
1813  }
1814 
1815  bool has_sj_candidates() const {
1816  return sj_candidates != NULL && !sj_candidates->empty();
1817  }
1818  bool is_in_select_list(Item *i);
1819 
1820  private:
1821  bool setup_wild(THD *thd);
1822  bool setup_order_final(THD *thd);
1823  bool setup_group(THD *thd);
1827  void empty_order_list(SELECT_LEX *sl);
1828  bool setup_join_cond(THD *thd, List<TABLE_LIST> *tables, bool in_update);
1829  bool find_common_table_expr(THD *thd, Table_ident *table_id, TABLE_LIST *tl,
1830  Parse_context *pc, bool *found);
1831 
1832  /**
1833  Pointer to collection of subqueries candidate for semijoin
1834  conversion.
1835  Template parameter is "true": no need to run DTORs on pointers.
1836  */
1838 
1839  public:
1840  /// How many expressions are part of the order by but not select list.
1842 
1843  bool setup_conds(THD *thd);
1844  bool prepare(THD *thd);
1845  bool optimize(THD *thd);
1847  bool check_only_full_group_by(THD *thd);
1848 
1849  /// Merge name resolution context objects of a subquery into its parent
1850  void merge_contexts(SELECT_LEX *inner);
1851 
1852  /**
1853  Returns which subquery execution strategies can be used for this query
1854  block.
1855 
1856  @param thd Pointer to THD object for session.
1857  Used to access optimizer_switch
1858 
1859  @retval EXEC_MATERIALIZATION Subquery Materialization should be used
1860  @retval EXEC_EXISTS In-to-exists execution should be used
1861  @retval EXEC_EXISTS_OR_MAT A cost-based decision should be made
1862  */
1864 
1865  /**
1866  Returns whether semi-join is enabled for this query block
1867 
1868  @see @c Opt_hints_qb::semijoin_enabled for details on how hints
1869  affect this decision. If there are no hints for this query block,
1870  optimizer_switch setting determines whether semi-join is used.
1871 
1872  @param thd Pointer to THD object for session.
1873  Used to access optimizer_switch
1874 
1875  @return true if semijoin is enabled,
1876  false otherwise
1877  */
1878  bool semijoin_enabled(THD *thd) const;
1879  /**
1880  Update available semijoin strategies for semijoin nests.
1881 
1882  Available semijoin strategies needs to be updated on every execution since
1883  optimizer_switch setting may have changed.
1884 
1885  @param thd Pointer to THD object for session.
1886  Used to access optimizer_switch
1887  */
1888  void update_semijoin_strategies(THD *thd);
1890 
1891  /**
1892  Add item to the hidden part of select list
1893 
1894  @param item item to add
1895 
1896  @return Pointer to reference of the added item
1897  */
1899 
1900  bool add_tables(THD *thd, const Mem_root_array<Table_ident *> *tables,
1901  ulong table_options, thr_lock_type lock_type,
1902  enum_mdl_type mdl_type);
1903 
1904  TABLE_LIST *find_table_by_name(const Table_ident *ident);
1905 };
1906 
1907 inline bool SELECT_LEX_UNIT::is_union() const {
1908  return first_select()->next_select() &&
1910 }
1911 
1912 struct Cast_type {
1915  const char *length;
1916  const char *dec;
1917 };
1918 
1922  /*
1923  true for "LIMIT offset,limit" and false for "LIMIT limit OFFSET offset"
1924  */
1926 };
1927 
1930 
1931  bool merge(const Query_options &a, const Query_options &b);
1932  bool save_to(Parse_context *);
1933 };
1934 
1936  DELETE_QUICK = 1 << 0,
1938  DELETE_IGNORE = 1 << 2
1939 };
1940 
1941 enum class Lock_strength { UPDATE, SHARE };
1942 
1943 /// We will static_cast this one to thr_lock_type.
1944 enum class Locked_row_action {
1945  DEFAULT = THR_DEFAULT,
1946  WAIT = THR_WAIT,
1947  NOWAIT = THR_NOWAIT,
1948  SKIP = THR_SKIP
1949 };
1950 
1951 /**
1952  Internally there is no CROSS JOIN join type, as cross joins are just a
1953  special case of inner joins with a join condition that is always true. The
1954  only difference is the nesting, and that is handled by the parser.
1955 */
1957  JTT_INNER = 0x01,
1959  JTT_NATURAL = 0x04,
1960  JTT_LEFT = 0x08,
1961  JTT_RIGHT = 0x10,
1962 
1967 };
1968 
1970 
1971 enum class Ternary_option { DEFAULT, ON, OFF };
1972 
1974 
1976 
1977 enum class Field_option : ulong {
1978  NONE = 0,
1981 };
1982 
1983 enum class Int_type : ulong {
1984  INT = MYSQL_TYPE_LONG,
1989 };
1990 
1991 enum class Numeric_type : ulong {
1995 };
1996 
1997 enum class Show_cmd_type {
1998  STANDARD,
1999  FULL_SHOW,
2000  EXTENDED_SHOW,
2002 };
2003 
2004 /**
2005  std::optional-like wrapper for simple bitmaps (usually enums of binary flags)
2006 
2007  This template wraps trivial bitmap implementations to add two features:
2008 
2009  * std::optional-like behavior -- the "unset" flag, so we don't have
2010  to inject a special "invalid" value into existent enum types, this
2011  wrapper class does that for us.
2012 
2013  * the merge() function to merge two bitmap values in a type-safe way.
2014 
2015  @tparam Enum Usually a enum type which simulates a bit set.
2016  @tparam Default_value A default Enum value for "unset" variables.
2017 
2018 */
2019 template <typename Enum, Enum Default_value>
2021  public:
2022  /// Constructor-like function
2023  ///
2024  /// The Enum_parser<> class is designed for use as a field of restricted
2025  /// unions, so it can't have C++ constructors.
2026  void init() { m_is_set = false; }
2027 
2028  /// False if the wrapped Enum value is not assigned.
2029  bool is_set() const { return m_is_set; }
2030 
2031  /// Return the wrapped Enum value.
2032  ///
2033  /// @note The wrapped value must be assigned.
2034  Enum get() const {
2035  DBUG_ASSERT(is_set());
2036  return m_enum;
2037  }
2038 
2039  /// Return the wrapped Enum value (if any) or the Default_value.
2040  Enum get_or_default() const { return is_set() ? get() : Default_value; }
2041 
2042  /// Assign the wrapped Enum value.
2043  void set(Enum value) {
2044  m_is_set = true;
2045  m_enum = value;
2046  }
2047 
2048  /// Merge the x bit set into the wrapped Enum value (if any), or replace it
2049  void merge(const Enum_parser &x) {
2050  if (x.is_set()) set(x.get());
2051  }
2052 
2053  private:
2054  bool m_is_set; ///< True if m_enum is assigned with some value
2055  Enum m_enum; ///< The wrapped Enum value.
2056 };
2057 
2058 template <typename T>
2061  T value; ///< undefined if is_default is true
2062 };
2063 
2065 
2066 union YYSTYPE {
2067  Lexer_yystype lexer; // terminal values from the lexical scanner
2068  /*
2069  Hint parser section (sql_hints.yy)
2070  */
2072  class PT_hint *hint;
2077 
2078  /*
2079  Main parser section (sql_yacc.yy)
2080  */
2081  int num;
2105  const char *c_str;
2106  struct {
2110  struct {
2111  const char *length;
2112  const char *dec;
2113  } precision;
2121  struct {
2123  } spblock;
2143  struct {
2149  class PT_subselect *subselect;
2158  class PT_group *group;
2169  class PT_order *order;
2184  class PT_set *set;
2199 
2202  struct {
2206  struct {
2210  struct {
2211  class PT_item_list *column_list;
2214  struct {
2215  class PT_item_list *column_list;
2218  struct {
2219  class Item *offset;
2221  } lead_lag_info;
2231  struct {
2252  struct {
2255  } opt_part_values;
2258  List<char> *name_list; // TODO: merge with string_list
2263  class PT_add_partition *add_partition_rule;
2264  struct {
2267  } mi_type;
2281  class PT_type *type;
2283  struct {
2284  const char *expr_start;
2286  } sp_default;
2288  struct {
2291  } fk_options;
2294  struct {
2300  } fk_references;
2304  struct {
2318  } jt_on_response;
2319  struct {
2325  struct {
2328  } wild_or_where;
2330  struct {
2334  } histogram;
2345  struct Algo_and_lock {
2352  void init() {
2353  algo.init();
2354  lock.init();
2355  }
2367  void init() {
2368  algo.init();
2369  lock.init();
2370  validation.init();
2371  }
2373  algo.merge(x.algo);
2374  lock.merge(x.lock);
2376  }
2378  struct {
2381  } alter_list;
2382  struct {
2383  Algo_and_lock_and_validation flags;
2393  struct {
2396  } vcpu_range_type;
2404  struct {
2408  } load_set_element;
2409  struct {
2413  } load_set_list;
2416 };
2417 
2418 static_assert(sizeof(YYSTYPE) <= 32, "YYSTYPE is too big");
2419 
2420 /**
2421  Utility RAII class to save/modify/restore the
2422  semijoin_disallowed flag.
2423 */
2425  public:
2426  Disable_semijoin_flattening(SELECT_LEX *select_ptr, bool apply)
2427  : select(NULL), saved_value() {
2428  if (select_ptr && apply) {
2429  select = select_ptr;
2431  select->semijoin_disallowed = true;
2432  }
2433  }
2436  }
2437 
2438  private:
2441 };
2442 
2443 /**
2444  Base class for secondary engine execution context objects. Secondary
2445  storage engines may create classes derived from this one which
2446  contain state they need to preserve between optimization and
2447  execution of statements. The context objects should be allocated on
2448  the execution MEM_ROOT.
2449 */
2451  public:
2452  /**
2453  Destructs the secondary engine execution context object. It is
2454  called after the query execution has completed. Secondary engines
2455  may override the destructor in subclasses and add code that
2456  performs cleanup tasks that are needed after query execution.
2457  */
2458  virtual ~Secondary_engine_execution_context() = default;
2459 };
2460 
2461 typedef struct struct_slave_connection {
2462  char *user;
2463  char *password;
2465  char *plugin_dir;
2466 
2467  void reset();
2469 
2473  bool detistic;
2475 };
2476 
2477 extern const LEX_STRING null_lex_str;
2478 extern const LEX_STRING empty_lex_str;
2479 
2483 
2484  /**
2485  FOLLOWS or PRECEDES as specified in the CREATE TRIGGER statement.
2486  */
2488 
2489  /**
2490  Trigger name referenced in the FOLLOWS/PRECEDES clause of the CREATE TRIGGER
2491  statement.
2492  */
2494 };
2495 
2497 
2498 class Sroutine_hash_entry;
2499 
2500 /*
2501  Class representing list of all tables used by statement and other
2502  information which is necessary for opening and locking its tables,
2503  like SQL command for this statement.
2504 
2505  Also contains information about stored functions used by statement
2506  since during its execution we may have to add all tables used by its
2507  stored functions/triggers to this list in order to pre-open and lock
2508  them.
2509 
2510  Also used by LEX::reset_n_backup/restore_backup_query_tables_list()
2511  methods to save and restore this information.
2512 */
2513 
2515  public:
2517 
2518  /**
2519  SQL command for this statement. Part of this class since the
2520  process of opening and locking tables for the statement needs
2521  this information to determine correct type of lock for some of
2522  the tables.
2523  */
2525  /* Global list of all tables used by this statement */
2527  /* Pointer to next_global member of last element in the previous list. */
2529  /*
2530  If non-0 then indicates that query requires prelocking and points to
2531  next_global member of last own element in query table list (i.e. last
2532  table which was not added to it as part of preparation to prelocking).
2533  0 - indicates that this query does not need prelocking.
2534  */
2536  /*
2537  Set of stored routines called by statement.
2538  (Note that we use lazy-initialization for this hash).
2539 
2540  See Sroutine_hash_entry for explanation why this hash uses binary
2541  key comparison.
2542  */
2544  std::unique_ptr<malloc_unordered_map<std::string, Sroutine_hash_entry *>>
2546  /*
2547  List linking elements of 'sroutines' set. Allows you to add new elements
2548  to this set as you iterate through the list of existing elements.
2549  'sroutines_list_own_last' is pointer to ::next member of last element of
2550  this list which represents routine which is explicitly used by query.
2551  'sroutines_list_own_elements' number of explicitly used routines.
2552  We use these two members for restoring of 'sroutines_list' to the state
2553  in which it was right after query parsing.
2554  */
2558 
2559  /**
2560  Locking state of tables in this particular statement.
2561 
2562  If we under LOCK TABLES or in prelocked mode we consider tables
2563  for the statement to be "locked" if there was a call to lock_tables()
2564  (which called handler::start_stmt()) for tables of this statement
2565  and there was no matching close_thread_tables() call.
2566 
2567  As result this state may differ significantly from one represented
2568  by Open_tables_state::lock/locked_tables_mode more, which are always
2569  "on" under LOCK TABLES or in prelocked mode.
2570  */
2574 
2575  /**
2576  Number of tables which were open by open_tables() and to be locked
2577  by lock_tables().
2578  Note that we set this member only in some cases, when this value
2579  needs to be passed from open_tables() to lock_tables() which are
2580  separated by some amount of code.
2581  */
2583 
2584  /*
2585  These constructor and destructor serve for creation/destruction
2586  of Query_tables_list instances which are used as backup storage.
2587  */
2590 
2591  /* Initializes (or resets) Query_tables_list object for "real" use. */
2592  void reset_query_tables_list(bool init);
2595  *this = std::move(*state);
2596  }
2597 
2598  /*
2599  Direct addition to the list of query tables.
2600  If you are using this function, you must ensure that the table
2601  object, in particular table->db member, is initialized.
2602  */
2604  *(table->prev_global = query_tables_last) = table;
2605  query_tables_last = &table->next_global;
2606  }
2608  void mark_as_requiring_prelocking(TABLE_LIST **tables_own_last) {
2609  query_tables_own_last = tables_own_last;
2610  }
2611  /* Return pointer to first not-own table in query-tables or 0 */
2614  }
2616  if (query_tables_own_last) {
2617  *query_tables_own_last = 0;
2620  }
2621  }
2622 
2623  /**
2624  All types of unsafe statements.
2625 
2626  @note The int values of the enum elements are used to point to
2627  bits in two bitmaps in two different places:
2628 
2629  - Query_tables_list::binlog_stmt_flags
2630  - THD::binlog_unsafe_warning_flags
2631 
2632  Hence in practice this is not an enum at all, but a map from
2633  symbols to bit indexes.
2634 
2635  The ordering of elements in this enum must correspond to the order of
2636  elements in the array binlog_stmt_unsafe_errcode.
2637  */
2639  /**
2640  SELECT..LIMIT is unsafe because the set of rows returned cannot
2641  be predicted.
2642  */
2644  /**
2645  Access to log tables is unsafe because slave and master probably
2646  log different things.
2647  */
2649  /**
2650  Inserting into an autoincrement column in a stored routine is unsafe.
2651  Even with just one autoincrement column, if the routine is invoked more
2652  than once slave is not guaranteed to execute the statement graph same way
2653  as the master. And since it's impossible to estimate how many times a
2654  routine can be invoked at the query pre-execution phase (see lock_tables),
2655  the statement is marked pessimistically unsafe.
2656  */
2658  /**
2659  Using a UDF (user-defined function) is unsafe.
2660  */
2662  /**
2663  Using most system variables is unsafe, because slave may run
2664  with different options than master.
2665  */
2667  /**
2668  Using some functions is unsafe (e.g., UUID).
2669  */
2671 
2672  /**
2673  Mixing transactional and non-transactional statements are unsafe if
2674  non-transactional reads or writes are occur after transactional
2675  reads or writes inside a transaction.
2676  */
2678 
2679  /**
2680  Mixing self-logging and non-self-logging engines in a statement
2681  is unsafe.
2682  */
2684 
2685  /**
2686  Statements that read from both transactional and non-transactional
2687  tables and write to any of them are unsafe.
2688  */
2690 
2691  /**
2692  INSERT...IGNORE SELECT is unsafe because which rows are ignored depends
2693  on the order that rows are retrieved by SELECT. This order cannot be
2694  predicted and may differ on master and the slave.
2695  */
2697 
2698  /**
2699  INSERT...SELECT...UPDATE is unsafe because which rows are updated depends
2700  on the order that rows are retrieved by SELECT. This order cannot be
2701  predicted and may differ on master and the slave.
2702  */
2704 
2705  /**
2706  Query that writes to a table with auto_inc column after selecting from
2707  other tables are unsafe as the order in which the rows are retrieved by
2708  select may differ on master and slave.
2709  */
2711 
2712  /**
2713  INSERT...REPLACE SELECT is unsafe because which rows are replaced depends
2714  on the order that rows are retrieved by SELECT. This order cannot be
2715  predicted and may differ on master and the slave.
2716  */
2718 
2719  /**
2720  CREATE TABLE... IGNORE... SELECT is unsafe because which rows are ignored
2721  depends on the order that rows are retrieved by SELECT. This order cannot
2722  be predicted and may differ on master and the slave.
2723  */
2725 
2726  /**
2727  CREATE TABLE...REPLACE... SELECT is unsafe because which rows are replaced
2728  depends on the order that rows are retrieved from SELECT. This order
2729  cannot be predicted and may differ on master and the slave
2730  */
2732 
2733  /**
2734  CREATE TABLE...SELECT on a table with auto-increment column is unsafe
2735  because which rows are replaced depends on the order that rows are
2736  retrieved from SELECT. This order cannot be predicted and may differ on
2737  master and the slave
2738  */
2740 
2741  /**
2742  UPDATE...IGNORE is unsafe because which rows are ignored depends on the
2743  order that rows are updated. This order cannot be predicted and may differ
2744  on master and the slave.
2745  */
2747 
2748  /**
2749  INSERT... ON DUPLICATE KEY UPDATE on a table with more than one
2750  UNIQUE KEYS is unsafe.
2751  */
2753 
2754  /**
2755  INSERT into auto-inc field which is not the first part in composed
2756  primary key.
2757  */
2759 
2760  /**
2761  Using a plugin is unsafe.
2762  */
2766 
2767  /**
2768  XA transactions and statements.
2769  */
2771 
2772  /* the last element of this enumeration type. */
2774  };
2775  /**
2776  This has all flags from 0 (inclusive) to BINLOG_STMT_FLAG_COUNT
2777  (exclusive) set.
2778  */
2779  static const int BINLOG_STMT_UNSAFE_ALL_FLAGS =
2780  ((1 << BINLOG_STMT_UNSAFE_COUNT) - 1);
2781 
2782  /**
2783  Maps elements of enum_binlog_stmt_unsafe to error codes.
2784  */
2786 
2787  /**
2788  Determine if this statement is marked as unsafe.
2789 
2790  @retval 0 if the statement is not marked as unsafe.
2791  @retval nonzero if the statement is marked as unsafe.
2792  */
2793  inline bool is_stmt_unsafe() const { return get_stmt_unsafe_flags() != 0; }
2794 
2796  return binlog_stmt_flags & (1 << unsafe);
2797  }
2798 
2799  /**
2800  Flag the current (top-level) statement as unsafe.
2801  The flag will be reset after the statement has finished.
2802 
2803  @param unsafe_type The type of unsafety: one of the @c
2804  BINLOG_STMT_FLAG_UNSAFE_* flags in @c enum_binlog_stmt_flag.
2805  */
2806  inline void set_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type) {
2807  DBUG_ENTER("set_stmt_unsafe");
2808  DBUG_ASSERT(unsafe_type >= 0 && unsafe_type < BINLOG_STMT_UNSAFE_COUNT);
2809  binlog_stmt_flags |= (1U << unsafe_type);
2811  }
2812 
2813  /**
2814  Set the bits of binlog_stmt_flags determining the type of
2815  unsafeness of the current statement. No existing bits will be
2816  cleared, but new bits may be set.
2817 
2818  @param flags A binary combination of zero or more bits, (1<<flag)
2819  where flag is a member of enum_binlog_stmt_unsafe.
2820  */
2821  inline void set_stmt_unsafe_flags(uint32 flags) {
2822  DBUG_ENTER("set_stmt_unsafe_flags");
2826  }
2827 
2828  /**
2829  Return a binary combination of all unsafe warnings for the
2830  statement. If the statement has been marked as unsafe by the
2831  'flag' member of enum_binlog_stmt_unsafe, then the return value
2832  from this function has bit (1<<flag) set to 1.
2833  */
2834  inline uint32 get_stmt_unsafe_flags() const {
2835  DBUG_ENTER("get_stmt_unsafe_flags");
2837  }
2838 
2839  /**
2840  Determine if this statement is a row injection.
2841 
2842  @retval 0 if the statement is not a row injection
2843  @retval nonzero if the statement is a row injection
2844  */
2845  inline bool is_stmt_row_injection() const {
2846  return binlog_stmt_flags &
2848  }
2849 
2850  /**
2851  Flag the statement as a row injection. A row injection is either
2852  a BINLOG statement, or a row event in the relay log executed by
2853  the slave SQL thread.
2854  */
2855  inline void set_stmt_row_injection() {
2856  DBUG_ENTER("set_stmt_row_injection");
2860  }
2861 
2863  /*
2864  If a transactional table is about to be read. Note that
2865  a write implies a read.
2866  */
2868  /*
2869  If a non-transactional table is about to be read. Note that
2870  a write implies a read.
2871  */
2873  /*
2874  If a temporary transactional table is about to be read. Note
2875  that a write implies a read.
2876  */
2878  /*
2879  If a temporary non-transactional table is about to be read. Note
2880  that a write implies a read.
2881  */
2883  /*
2884  If a transactional table is about to be updated.
2885  */
2887  /*
2888  If a non-transactional table is about to be updated.
2889  */
2891  /*
2892  If a temporary transactional table is about to be updated.
2893  */
2895  /*
2896  If a temporary non-transactional table is about to be updated.
2897  */
2899  /*
2900  The last element of the enumeration. Please, if necessary add
2901  anything before this.
2902  */
2904  };
2905 
2906 #ifndef DBUG_OFF
2907  static inline const char *stmt_accessed_table_string(
2908  enum_stmt_accessed_table accessed_table) {
2909  switch (accessed_table) {
2911  return "STMT_READS_TRANS_TABLE";
2912  break;
2914  return "STMT_READS_NON_TRANS_TABLE";
2915  break;
2917  return "STMT_READS_TEMP_TRANS_TABLE";
2918  break;
2920  return "STMT_READS_TEMP_NON_TRANS_TABLE";
2921  break;
2923  return "STMT_WRITES_TRANS_TABLE";
2924  break;
2926  return "STMT_WRITES_NON_TRANS_TABLE";
2927  break;
2929  return "STMT_WRITES_TEMP_TRANS_TABLE";
2930  break;
2932  return "STMT_WRITES_TEMP_NON_TRANS_TABLE";
2933  break;
2935  default:
2936  DBUG_ASSERT(0);
2937  break;
2938  }
2940  return "";
2941  }
2942 #endif /* DBUG */
2943 
2944 #define BINLOG_DIRECT_ON \
2945  0xF0 /* unsafe when \
2946  --binlog-direct-non-trans-updates \
2947  is ON */
2948 
2949 #define BINLOG_DIRECT_OFF \
2950  0xF /* unsafe when \
2951  --binlog-direct-non-trans-updates \
2952  is OFF */
2953 
2954 #define TRX_CACHE_EMPTY 0x33 /* unsafe when trx-cache is empty */
2955 
2956 #define TRX_CACHE_NOT_EMPTY 0xCC /* unsafe when trx-cache is not empty */
2957 
2958 #define IL_LT_REPEATABLE 0xAA /* unsafe when < ISO_REPEATABLE_READ */
2959 
2960 #define IL_GTE_REPEATABLE 0x55 /* unsafe when >= ISO_REPEATABLE_READ */
2961 
2962  /**
2963  Sets the type of table that is about to be accessed while executing a
2964  statement.
2965 
2966  @param accessed_table Enumeration type that defines the type of table,
2967  e.g. temporary, transactional, non-transactional.
2968  */
2970  DBUG_ENTER("LEX::set_stmt_accessed_table");
2971 
2972  DBUG_ASSERT(accessed_table >= 0 &&
2973  accessed_table < STMT_ACCESS_TABLE_COUNT);
2974  stmt_accessed_table_flag |= (1U << accessed_table);
2975 
2977  }
2978 
2979  /**
2980  Checks if a type of table is about to be accessed while executing a
2981  statement.
2982 
2983  @param accessed_table Enumeration type that defines the type of table,
2984  e.g. temporary, transactional, non-transactional.
2985 
2986  @return
2987  @retval true if the type of the table is about to be accessed
2988  @retval false otherwise
2989  */
2990  inline bool stmt_accessed_table(enum_stmt_accessed_table accessed_table) {
2991  DBUG_ENTER("LEX::stmt_accessed_table");
2992 
2993  DBUG_ASSERT(accessed_table >= 0 &&
2994  accessed_table < STMT_ACCESS_TABLE_COUNT);
2995 
2996  DBUG_RETURN((stmt_accessed_table_flag & (1U << accessed_table)) != 0);
2997  }
2998 
2999  /*
3000  Checks if a mixed statement is unsafe.
3001 
3002 
3003  @param in_multi_stmt_transaction_mode defines if there is an on-going
3004  multi-transactional statement.
3005  @param binlog_direct defines if --binlog-direct-non-trans-updates is
3006  active.
3007  @param trx_cache_is_not_empty defines if the trx-cache is empty or not.
3008  @param trx_isolation defines the isolation level.
3009 
3010  @return
3011  @retval true if the mixed statement is unsafe
3012  @retval false otherwise
3013  */
3014  inline bool is_mixed_stmt_unsafe(bool in_multi_stmt_transaction_mode,
3015  bool binlog_direct,
3016  bool trx_cache_is_not_empty,
3017  uint tx_isolation) {
3018  bool unsafe = false;
3019 
3020  if (in_multi_stmt_transaction_mode) {
3021  uint condition =
3022  (binlog_direct ? BINLOG_DIRECT_ON : BINLOG_DIRECT_OFF) &
3023  (trx_cache_is_not_empty ? TRX_CACHE_NOT_EMPTY : TRX_CACHE_EMPTY) &
3024  (tx_isolation >= ISO_REPEATABLE_READ ? IL_GTE_REPEATABLE
3025  : IL_LT_REPEATABLE);
3026 
3027  unsafe = (binlog_unsafe_map[stmt_accessed_table_flag] & condition);
3028 
3029 #if !defined(DBUG_OFF)
3030  DBUG_PRINT("LEX::is_mixed_stmt_unsafe",
3031  ("RESULT %02X %02X %02X\n", condition,
3034 
3035  int type_in = 0;
3036  for (; type_in < STMT_ACCESS_TABLE_COUNT; type_in++) {
3038  DBUG_PRINT("LEX::is_mixed_stmt_unsafe",
3039  ("ACCESSED %s ", stmt_accessed_table_string(
3040  (enum_stmt_accessed_table)type_in)));
3041  }
3042 #endif
3043  }
3044 
3047  tx_isolation < ISO_REPEATABLE_READ)
3048  unsafe = true;
3051  tx_isolation < ISO_REPEATABLE_READ)
3052  unsafe = true;
3053 
3054  return (unsafe);
3055  }
3056 
3057  /**
3058  true if the parsed tree contains references to stored procedures
3059  or functions, false otherwise
3060  */
3061  bool uses_stored_routines() const { return sroutines_list.elements != 0; }
3062 
3063  void set_using_match() { using_match = true; }
3064  bool get_using_match() { return using_match; }
3065 
3066  private:
3067  /**
3068  Enumeration listing special types of statements.
3069 
3070  Currently, the only possible type is ROW_INJECTION.
3071  */
3073  /**
3074  The statement is a row injection (i.e., either a BINLOG
3075  statement or a row event executed by the slave SQL thread).
3076  */
3078 
3079  /** The last element of this enumeration type. */
3081  };
3082 
3083  /**
3084  Bit field indicating the type of statement.
3085 
3086  There are two groups of bits:
3087 
3088  - The low BINLOG_STMT_UNSAFE_COUNT bits indicate the types of
3089  unsafeness that the current statement has.
3090 
3091  - The next BINLOG_STMT_TYPE_COUNT bits indicate if the statement
3092  is of some special type.
3093 
3094  This must be a member of LEX, not of THD: each stored procedure
3095  needs to remember its unsafeness state between calls and each
3096  stored procedure has its own LEX object (but no own THD object).
3097  */
3099 
3100  /**
3101  Bit field that determines the type of tables that are about to be
3102  be accessed while executing a statement.
3103  */
3105 
3106  /**
3107  It will be set true if 'MATCH () AGAINST' is used in the statement.
3108  */
3110 };
3111 
3112 /*
3113  st_parsing_options contains the flags for constructions that are
3114  allowed in the current statement.
3115 */
3116 
3120 
3122  void reset();
3123 };
3124 
3125 /**
3126  The state of the lexical parser, when parsing comments.
3127 */
3129  /**
3130  Not parsing comments.
3131  */
3133 
3134  /**
3135  Parsing comments that need to be preserved.
3136  (Copy '/' '*' and '*' '/' sequences to the preprocessed buffer.)
3137  Typically, these are user comments '/' '*' ... '*' '/'.
3138  */
3140 
3141  /**
3142  Parsing comments that need to be discarded.
3143  (Don't copy '/' '*' '!' and '*' '/' sequences to the preprocessed buffer.)
3144  Typically, these are special comments '/' '*' '!' ... '*' '/',
3145  or '/' '*' '!' 'M' 'M' 'm' 'm' 'm' ... '*' '/', where the comment
3146  markers should not be expanded.
3147  */
3149 };
3150 
3151 /**
3152  This class represents the character input stream consumed during lexical
3153  analysis.
3154 
3155  In addition to consuming the input stream, this class performs some comment
3156  pre processing, by filtering out out-of-bound special text from the query
3157  input stream.
3158 
3159  Two buffers, with pointers inside each, are maintained in parallel. The
3160  'raw' buffer is the original query text, which may contain out-of-bound
3161  comments. The 'cpp' (for comments pre processor) is the pre-processed buffer
3162  that contains only the query text that should be seen once out-of-bound data
3163  is removed.
3164 */
3165 
3167  public:
3168  /**
3169  Constructor
3170 
3171  @param grammar_selector_token_arg See grammar_selector_token.
3172  */
3173 
3174  explicit Lex_input_stream(uint grammar_selector_token_arg)
3175  : grammar_selector_token(grammar_selector_token_arg) {}
3176 
3177  /**
3178  Object initializer. Must be called before usage.
3179 
3180  @retval false OK
3181  @retval true Error
3182  */
3183  bool init(THD *thd, const char *buff, size_t length);
3184 
3185  void reset(const char *buff, size_t length);
3186 
3187  /**
3188  Set the echo mode.
3189 
3190  When echo is true, characters parsed from the raw input stream are
3191  preserved. When false, characters parsed are silently ignored.
3192  @param echo the echo mode.
3193  */
3194  void set_echo(bool echo) { m_echo = echo; }
3195 
3197  m_echo_saved = m_echo;
3199  }
3200 
3202  m_echo = m_echo_saved;
3204  }
3205 
3206  /**
3207  Skip binary from the input stream.
3208  @param n number of bytes to accept.
3209  */
3210  void skip_binary(int n) {
3212  if (m_echo) {
3213  memcpy(m_cpp_ptr, m_ptr, n);
3214  m_cpp_ptr += n;
3215  }
3216  m_ptr += n;
3217  }
3218 
3219  /**
3220  Get a character, and advance in the stream.
3221  @return the next character to parse.
3222  */
3223  unsigned char yyGet() {
3225  char c = *m_ptr++;
3226  if (m_echo) *m_cpp_ptr++ = c;
3227  return c;
3228  }
3229 
3230  /**
3231  Get the last character accepted.
3232  @return the last character accepted.
3233  */
3234  unsigned char yyGetLast() const { return m_ptr[-1]; }
3235 
3236  /**
3237  Look at the next character to parse, but do not accept it.
3238  */
3239  unsigned char yyPeek() const {
3241  return m_ptr[0];
3242  }
3243 
3244  /**
3245  Look ahead at some character to parse.
3246  @param n offset of the character to look up
3247  */
3248  unsigned char yyPeekn(int n) const {
3250  return m_ptr[n];
3251  }
3252 
3253  /**
3254  Cancel the effect of the last yyGet() or yySkip().
3255  Note that the echo mode should not change between calls to yyGet / yySkip
3256  and yyUnget. The caller is responsible for ensuring that.
3257  */
3258  void yyUnget() {
3259  m_ptr--;
3260  if (m_echo) m_cpp_ptr--;
3261  }
3262 
3263  /**
3264  Accept a character, by advancing the input stream.
3265  */
3266  void yySkip() {
3268  if (m_echo)
3269  *m_cpp_ptr++ = *m_ptr++;
3270  else
3271  m_ptr++;
3272  }
3273 
3274  /**
3275  Accept multiple characters at once.
3276  @param n the number of characters to accept.
3277  */
3278  void yySkipn(int n) {
3280  if (m_echo) {
3281  memcpy(m_cpp_ptr, m_ptr, n);
3282  m_cpp_ptr += n;
3283  }
3284  m_ptr += n;
3285  }
3286 
3287  /**
3288  Puts a character back into the stream, canceling
3289  the effect of the last yyGet() or yySkip().
3290  Note that the echo mode should not change between calls
3291  to unput, get, or skip from the stream.
3292  */
3293  char *yyUnput(char ch) {
3294  *--m_ptr = ch;
3295  if (m_echo) m_cpp_ptr--;
3296  return m_ptr;
3297  }
3298 
3299  /**
3300  Inject a character into the pre-processed stream.
3301 
3302  Note, this function is used to inject a space instead of multi-character
3303  C-comment. Thus there is no boundary checks here (basically, we replace
3304  N-chars by 1-char here).
3305  */
3306  char *cpp_inject(char ch) {
3307  *m_cpp_ptr = ch;
3308  return ++m_cpp_ptr;
3309  }
3310 
3311  /**
3312  End of file indicator for the query text to parse.
3313  @return true if there are no more characters to parse
3314  */
3315  bool eof() const { return (m_ptr >= m_end_of_query); }
3316 
3317  /**
3318  End of file indicator for the query text to parse.
3319  @param n number of characters expected
3320  @return true if there are less than n characters to parse
3321  */
3322  bool eof(int n) const { return ((m_ptr + n) >= m_end_of_query); }
3323 
3324  /** Get the raw query buffer. */
3325  const char *get_buf() const { return m_buf; }
3326 
3327  /** Get the pre-processed query buffer. */
3328  const char *get_cpp_buf() const { return m_cpp_buf; }
3329 
3330  /** Get the end of the raw query buffer. */
3331  const char *get_end_of_query() const { return m_end_of_query; }
3332 
3333  /** Mark the stream position as the start of a new token. */
3334  void start_token() {
3335  m_tok_start = m_ptr;
3336  m_tok_end = m_ptr;
3337 
3340  }
3341 
3342  /**
3343  Adjust the starting position of the current token.
3344  This is used to compensate for starting whitespace.
3345  */
3346  void restart_token() {
3347  m_tok_start = m_ptr;
3349  }
3350 
3351  /** Get the token start position, in the raw buffer. */
3352  const char *get_tok_start() const { return m_tok_start; }
3353 
3354  /** Get the token start position, in the pre-processed buffer. */
3355  const char *get_cpp_tok_start() const { return m_cpp_tok_start; }
3356 
3357  /** Get the token end position, in the raw buffer. */
3358  const char *get_tok_end() const { return m_tok_end; }
3359 
3360  /** Get the token end position, in the pre-processed buffer. */
3361  const char *get_cpp_tok_end() const { return m_cpp_tok_end; }
3362 
3363  /** Get the current stream pointer, in the raw buffer. */
3364  const char *get_ptr() const { return m_ptr; }
3365 
3366  /** Get the current stream pointer, in the pre-processed buffer. */
3367  const char *get_cpp_ptr() const { return m_cpp_ptr; }
3368 
3369  /** Get the length of the current token, in the raw buffer. */
3370  uint yyLength() const {
3371  /*
3372  The assumption is that the lexical analyser is always 1 character ahead,
3373  which the -1 account for.
3374  */
3376  return (uint)((m_ptr - m_tok_start) - 1);
3377  }
3378 
3379  /** Get the utf8-body string. */
3380  const char *get_body_utf8_str() const { return m_body_utf8; }
3381 
3382  /** Get the utf8-body length. */
3384  return (uint)(m_body_utf8_ptr - m_body_utf8);
3385  }
3386 
3387  void body_utf8_start(THD *thd, const char *begin_ptr);
3388  void body_utf8_append(const char *ptr);
3389  void body_utf8_append(const char *ptr, const char *end_ptr);
3390  void body_utf8_append_literal(THD *thd, const LEX_STRING *txt,
3391  const CHARSET_INFO *txt_cs,
3392  const char *end_ptr);
3393 
3394  uint get_lineno(const char *raw_ptr) const;
3395 
3396  /** Current thread. */
3398 
3399  /** Current line number. */
3401 
3402  /** Length of the last token parsed. */
3404 
3405  /** Interface with bison, value of the last token parsed. */
3407 
3408  /**
3409  LALR(2) resolution, look ahead token.
3410  Value of the next token to return, if any,
3411  or -1, if no token was parsed in advance.
3412  Note: 0 is a legal token, and represents YYEOF.
3413  */
3415 
3416  /** LALR(2) resolution, value of the look ahead token.*/
3418 
3419  /// Skip adding of the current token's digest since it is already added
3420  ///
3421  /// Usually we calculate a digest token by token at the top-level function
3422  /// of the lexer: MYSQLlex(). However, some complex ("hintable") tokens break
3423  /// that data flow: for example, the `SELECT /*+ HINT(t) */` is the single
3424  /// token from the main parser's point of view, and we add the "SELECT"
3425  /// keyword to the digest buffer right after the lex_one_token() call,
3426  /// but the "/*+ HINT(t) */" is a sequence of separate tokens from the hint
3427  /// parser's point of view, and we add those tokens to the digest buffer
3428  /// *inside* the lex_one_token() call. Thus, the usual data flow adds
3429  /// tokens from the "/*+ HINT(t) */" string first, and only than it appends
3430  /// the "SELECT" keyword token to that stream: "/*+ HINT(t) */ SELECT".
3431  /// This is not acceptable, since we use the digest buffer to restore
3432  /// query strings in their normalized forms, so the order of added tokens is
3433  /// important. Thus, we add tokens of "hintable" keywords to a digest buffer
3434  /// right in the hint parser and skip adding of them at the caller with the
3435  /// help of skip_digest flag.
3436  bool skip_digest;
3437 
3438  void add_digest_token(uint token, Lexer_yystype *yylval);
3439 
3440  void reduce_digest_token(uint token_left, uint token_right);
3441 
3442  /**
3443  True if this scanner tokenizes a partial query (partition expression,
3444  generated column expression etc.)
3445 
3446  @return true if parsing a partial query, otherwise false.
3447  */
3448  bool is_partial_parser() const { return grammar_selector_token >= 0; }
3449 
3450  /**
3451  Outputs warnings on deprecated charsets in complete SQL statements
3452 
3453  @param [in] cs The character set/collation to check for a deprecation.
3454  @param [in] alias The name/alias of @p cs.
3455  */
3457  const char *alias) const {
3458  if (!is_partial_parser()) {
3459  ::warn_on_deprecated_charset(m_thd, cs, alias);
3460  }
3461  }
3462 
3463  /**
3464  Outputs warnings on deprecated collations in complete SQL statements
3465 
3466  @param [in] collation The collation to check for a deprecation.
3467  */
3468  void warn_on_deprecated_collation(const CHARSET_INFO *collation) const {
3469  if (!is_partial_parser()) {
3471  }
3472  }
3473 
3475 
3476  private:
3477  /** Pointer to the current position in the raw input stream. */
3478  char *m_ptr;
3479 
3480  /** Starting position of the last token parsed, in the raw buffer. */
3481  const char *m_tok_start;
3482 
3483  /** Ending position of the previous token parsed, in the raw buffer. */
3484  const char *m_tok_end;
3485 
3486  /** End of the query text in the input stream, in the raw buffer. */
3487  const char *m_end_of_query;
3488 
3489  /** Begining of the query text in the input stream, in the raw buffer. */
3490  const char *m_buf;
3491 
3492  /** Length of the raw buffer. */
3494 
3495  /** Echo the parsed stream to the pre-processed buffer. */
3496  bool m_echo;
3498 
3499  /** Pre-processed buffer. */
3500  char *m_cpp_buf;
3501 
3502  /** Pointer to the current position in the pre-processed input stream. */
3503  char *m_cpp_ptr;
3504 
3505  /**
3506  Starting position of the last token parsed,
3507  in the pre-processed buffer.
3508  */
3509  const char *m_cpp_tok_start;
3510 
3511  /**
3512  Ending position of the previous token parsed,
3513  in the pre-processed buffer.
3514  */
3515  const char *m_cpp_tok_end;
3516 
3517  /** UTF8-body buffer created during parsing. */
3519 
3520  /** Pointer to the current position in the UTF8-body buffer. */
3522 
3523  /**
3524  Position in the pre-processed buffer. The query from m_cpp_buf to
3525  m_cpp_utf_processed_ptr is converted to UTF8-body.
3526  */
3528 
3529  public:
3530  /** Current state of the lexical analyser. */
3532 
3533  /**
3534  Position of ';' in the stream, to delimit multiple queries.
3535  This delimiter is in the raw buffer.
3536  */
3537  const char *found_semicolon;
3538 
3539  /** Token character bitmaps, to detect 7bit strings. */
3541 
3542  /** SQL_MODE = IGNORE_SPACE. */
3544 
3545  /**
3546  true if we're parsing a prepared statement: in this mode
3547  we should allow placeholders.
3548  */
3550  /**
3551  true if we should allow multi-statements.
3552  */
3554 
3555  /** State of the lexical analyser for comments. */
3558 
3559  /**
3560  Starting position of the TEXT_STRING or IDENT in the pre-processed
3561  buffer.
3562 
3563  NOTE: this member must be used within MYSQLlex() function only.
3564  */
3565  const char *m_cpp_text_start;
3566 
3567  /**
3568  Ending position of the TEXT_STRING or IDENT in the pre-processed
3569  buffer.
3570 
3571  NOTE: this member must be used within MYSQLlex() function only.
3572  */
3573  const char *m_cpp_text_end;
3574 
3575  /**
3576  Character set specified by the character-set-introducer.
3577 
3578  NOTE: this member must be used within MYSQLlex() function only.
3579  */
3581 
3582  /**
3583  Current statement digest instrumentation.
3584  */
3586 
3587  /**
3588  The synthetic 1st token to prepend token stream with.
3589 
3590  This token value tricks parser to simulate multiple %start-ing points.
3591  Currently the grammar is aware of 4 such synthetic tokens:
3592  1. GRAMMAR_SELECTOR_PART for partitioning stuff from DD,
3593  2. GRAMMAR_SELECTOR_GCOL for generated column stuff from DD,
3594  3. GRAMMAR_SELECTOR_EXPR for generic single expressions from DD/.frm.
3595  4. GRAMMAR_SELECTOR_CTE for generic subquery expressions from CTEs.
3596  5. -1 when parsing with the main grammar (no grammar selector available).
3597 
3598  @note yylex() is expected to return the value of type int:
3599  0 is for EOF and everything else for real token numbers.
3600  Bison, in its turn, generates positive token numbers.
3601  So, the negative grammar_selector_token means "not a token".
3602  In other words, -1 is "empty value".
3603  */
3605 
3606  bool text_string_is_7bit() const { return !(tok_bitmap & 0x80); }
3607 };
3608 
3609 class LEX_COLUMN {
3610  public:
3613  LEX_COLUMN(const String &x, const uint &y) : column(x), rights(y) {}
3614 };
3615 
3616 enum class role_enum;
3617 
3618 /*
3619  This structure holds information about grantor's context
3620 */
3622  public:
3623  LEX_GRANT_AS();
3624  void cleanup();
3625 
3626  public:
3631 };
3632 
3633 /* The state of the lex parsing. This is saved in the THD struct */
3634 
3635 struct LEX : public Query_tables_list {
3636  friend bool lex_start(THD *thd);
3637 
3638  SELECT_LEX_UNIT *unit; ///< Outer-most query expression
3639  /// @todo: select_lex can be replaced with unit->first-select()
3640  SELECT_LEX *select_lex; ///< First query block
3641  SELECT_LEX *all_selects_list; ///< List of all query blocks
3642  private:
3643  /* current SELECT_LEX in parsing */
3645 
3646  public:
3647  inline SELECT_LEX *current_select() const { return m_current_select; }
3648 
3649  /*
3650  We want to keep current_thd out of header files, so the debug assert
3651  is moved to the .cc file.
3652  */
3654  inline void set_current_select(SELECT_LEX *select) {
3655 #ifndef DBUG_OFF
3657 #endif
3658  m_current_select = select;
3659  }
3660  /// @return true if this is an EXPLAIN statement
3661  bool is_explain() const { return explain_format != nullptr; }
3663  char *help_arg;
3664  char *to_log; /* For PURGE MASTER LOGS TO */
3666  // Widcard from SHOW ... LIKE <wildcard> statements.
3669  LEX_STRING binlog_stmt_arg; ///< Argument of the BINLOG event statement.
3676 
3677  /* Optimizer hints */
3679 
3680  /* maintain a list of used plugins for this LEX */
3684 
3685  /// Table being inserted into (may be a view)
3687  /// Leaf table being inserted into (always a base table)
3689 
3690  /** SELECT of CREATE VIEW statement */
3692 
3693  /* Partition info structure filled in by PARTITION BY parse part */
3695 
3696  /*
3697  The definer of the object being created (view, trigger, stored routine).
3698  I.e. the value of DEFINER clause.
3699  */
3701 
3706 
3708 
3709  // PURGE statement-specific fields:
3711 
3712  // KILL statement-specific fields:
3714 
3715  // other stuff:
3717  List<Item_func_set_user_var> set_var_list; // in-query assignment list
3718  /**
3719  List of placeholders ('?') for parameters of a prepared statement. Because
3720  we append to this list during parsing, it is naturally sorted by
3721  position of the '?' in the query string. The code which fills placeholders
3722  with user-supplied values, and the code which writes a query for
3723  statement-based logging, rely on this order.
3724  This list contains only real placeholders, not the clones which originate
3725  in a re-parsed CTE definition.
3726  */
3728 
3729  bool locate_var_assignment(const Name_string &name);
3730 
3731  void insert_values_map(Field *f1, Field *f2) {
3733  insert_update_values_map = new std::map<Field *, Field *>;
3734  insert_update_values_map->insert(std::make_pair(f1, f2));
3735  }
3738  insert_update_values_map->clear();
3739  delete insert_update_values_map;
3741  }
3742  }
3743  bool has_values_map() const { return insert_update_values_map != NULL; }
3744  std::map<Field *, Field *>::iterator begin_values_map() {
3745  return insert_update_values_map->begin();
3746  }
3747  std::map<Field *, Field *>::iterator end_values_map() {
3748  return insert_update_values_map->end();
3749  }
3750 
3751  private:
3752  /*
3753  With Visual Studio, an std::map will always allocate two small objects
3754  on the heap. Sometimes we put LEX objects in a MEM_ROOT, and never run
3755  the LEX DTOR. To avoid memory leaks, put this std::map on the heap,
3756  and call clear_values_map() at the end of each statement.
3757  */
3758  std::map<Field *, Field *> *insert_update_values_map;
3759 
3760  public:
3761  /*
3762  A stack of name resolution contexts for the query. This stack is used
3763  at parse time to set local name resolution contexts for various parts
3764  of a query. For example, in a JOIN ... ON (some_condition) clause the
3765  Items in 'some_condition' must be resolved only against the operands
3766  of the the join, and not against the whole clause. Similarly, Items in
3767  subqueries should be resolved against the subqueries (and outer queries).
3768  The stack is used in the following way: when the parser detects that
3769  all Items in some clause need a local context, it creates a new context
3770  and pushes it on the stack. All newly created Items always store the
3771  top-most context in the stack. Once the parser leaves the clause that
3772  required a local context, the parser pops the top-most context.
3773  */
3775 
3778  HA_CHECK_OPT check_opt; // check/repair options
3781  LEX_MASTER_INFO mi; // used by CHANGE MASTER
3787  /**
3788  This field is used as a work field during resolving to validate
3789  the use of aggregate functions. For example in a query
3790  SELECT ... FROM ...WHERE MIN(i) == 1 GROUP BY ... HAVING MIN(i) > 2
3791  MIN(i) in the WHERE clause is not allowed since only non-aggregated data
3792  is present, whereas MIN(i) in the HAVING clause is allowed because HAVING
3793  operates on the output of a grouping operation.
3794  Each query block is assigned a nesting level. This field is a bit field
3795  that contains the value one in the position of that nesting level if
3796  aggregate functions are allowed for that query block.
3797  */
3799  /**
3800  Windowing functions are not allowed in HAVING - in contrast to group
3801  aggregates - then we need to be stricter than allow_sum_func.
3802  One bit per query block, as allow_sum_func.
3803  */
3805 
3807 
3808  /*
3809  Usually `expr` rule of yacc is quite reused but some commands better
3810  not support subqueries which comes standard with this rule, like
3811  KILL, HA_READ, CREATE/ALTER EVENT etc. Set this to `false` to get
3812  syntax error back.
3813  */
3815  /**
3816  If currently re-parsing a CTE's definition, this is the offset in bytes
3817  of that definition in the original statement which had the WITH
3818  clause. Otherwise this is 0.
3819  */
3821 
3822  enum SSL_type ssl_type; /* defined in violite.h */
3827 
3828  /// QUERY ID for SHOW PROFILE
3834  int select_number; ///< Number of query block (by EXPLAIN)
3837  /**
3838  @todo ensure that correct CONTEXT_ANALYSIS_ONLY is set for all preparation
3839  code, so we can fully rely on this field.
3840  */
3846  // For show commands to show hidden columns and indexes.
3848 
3850 
3851  /**
3852  Whether this query will return the same answer every time, given unchanged
3853  data. Used to be for the query cache, but is now used to find out if an
3854  expression is usable for partitioning.
3855  */
3858 
3859  private:
3860  bool ignore;
3861 
3862  public:
3863  bool is_ignore() const { return ignore; }
3864  void set_ignore(bool ignore_param) { ignore = ignore_param; }
3867  /* Prepared statements SQL syntax:*/
3868  LEX_CSTRING prepared_stmt_name; /* Statement name (in all queries) */
3869  /*
3870  Prepared statement query text or name of variable that holds the
3871  prepared statement (in PREPARE ... queries)
3872  */
3874  /* If true, prepared_stmt_code is a name of variable that holds the query */
3876  /* Names of user variables holding parameters (in EXECUTE) */
3880  bool sp_lex_in_use; /* Keep track on lex usage in SPs for error handling */
3885 
3886  private:
3887  bool m_broken; ///< see mark_broken()
3888  /**
3889  Set to true when execution has started (after parsing, tables opened and
3890  query preparation is complete. Used to track arena state for SPs).
3891  */
3893  /// Current SP parsing context.
3894  /// @see also sp_head::m_root_parsing_ctx.
3896 
3897  /**
3898  Statement context for SELECT_LEX::make_active_options.
3899  */
3901 
3902  public:
3903  /// @return a bit set of options set for this statement
3905  /**
3906  Add options to values of m_statement_options. options is an ORed
3907  bit set of options defined in query_options.h
3908 
3909  @param options Add this set of options to the set already in
3910  m_statement_options
3911  */
3914  }
3915  bool is_broken() const { return m_broken; }
3916  /**
3917  Certain permanent transformations (like in2exists), if they fail, may
3918  leave the LEX in an inconsistent state. They should call the
3919  following function, so that this LEX is not reused by another execution.
3920 
3921  @todo If lex_start () were a member function of LEX, the "broken"
3922  argument could always be "true" and thus could be removed.
3923  */
3924  void mark_broken(bool broken = true) {
3925  if (broken) {
3926  /*
3927  "OPEN <cursor>" cannot be re-prepared if the cursor uses no tables
3928  ("SELECT FROM DUAL"). Indeed in that case cursor_query is left empty
3929  in constructions of sp_instr_cpush, and thus
3930  sp_lex_instr::parse_expr() cannot re-prepare. So we mark the statement
3931  as broken only if tables are used.
3932  */
3933  if (is_metadata_used()) m_broken = true;
3934  } else
3935  m_broken = false;
3936  }
3937 
3938  bool is_exec_started() const { return m_exec_started; }
3939 
3943 
3945  sp_current_parsing_ctx = ctx;
3946  }
3947 
3948  /// Check if the current statement uses meta-data (uses a table or a stored
3949  /// routine).
3950  bool is_metadata_used() const {
3951  return query_tables != NULL ||
3952  (sroutines != nullptr && !sroutines->empty());
3953  }
3954 
3955  public:
3957 
3959 
3960  bool only_view; /* used for SHOW CREATE TABLE/VIEW */
3961  /*
3962  view created to be run from definer (standard behaviour)
3963  */
3965 
3966  /**
3967  Intended to point to the next word after DEFINER-clause in the
3968  following statements:
3969 
3970  - CREATE TRIGGER (points to "TRIGGER");
3971  - CREATE PROCEDURE (points to "PROCEDURE");
3972  - CREATE FUNCTION (points to "FUNCTION" or "AGGREGATE");
3973  - CREATE EVENT (points to "EVENT")
3974 
3975  This pointer is required to add possibly omitted DEFINER-clause to the
3976  DDL-statement before dumping it to the binlog.
3977  */
3979  const char *stmt_definition_end;
3980 
3981  /**
3982  During name resolution search only in the table list given by
3983  Name_resolution_context::first_name_resolution_table and
3984  Name_resolution_context::last_name_resolution_table
3985  (see Item_field::fix_fields()).
3986  */
3988 
3989  bool is_lex_started; /* If lex_start() did run. For debugging. */
3990  /// Set to true while resolving values in ON DUPLICATE KEY UPDATE clause
3992 
3994 
3995  // Maximum execution time for a statement.
3997 
3998  /*
3999  To flag the current statement as dependent for binary logging
4000  on explicit_defaults_for_timestamp
4001  */
4003 
4004  /**
4005  Used to inform the parser whether it should contextualize the parse
4006  tree. When we get a pure parser this will not be needed.
4007  */
4009 
4010  LEX();
4011 
4012  virtual ~LEX();
4013 
4014  /// Reset query context to initial state
4015  void reset();
4016 
4017  /// Create an empty query block within this LEX object.
4019 
4020  /// Create query expression object that contains one query block.
4021  SELECT_LEX *new_query(SELECT_LEX *curr_select);
4022 
4023  /// Create query block and attach it to the current query expression.
4024  SELECT_LEX *new_union_query(SELECT_LEX *curr_select, bool distinct,
4025  bool check_syntax = true);
4026 
4027  /// Create top-level query expression and query block.
4028  bool new_top_level_query();
4029 
4030  /// Create query expression and query block in existing memory objects.
4031  void new_static_query(SELECT_LEX_UNIT *sel_unit, SELECT_LEX *select);
4032 
4034  return (context_analysis_only &
4036  }
4037 
4040  }
4041 
4042  /**
4043  Set the current query as uncacheable.
4044 
4045  @param curr_select Current select query block
4046  @param cause Why this query is uncacheable.
4047 
4048  @details
4049  All query blocks representing subqueries, from the current one up to
4050  the outer-most one, but excluding the main query block, are also set
4051  as uncacheable.
4052  */
4053  void set_uncacheable(SELECT_LEX *curr_select, uint8 cause) {
4054  safe_to_cache_query = false;
4055 
4056  if (m_current_select == NULL) return;
4057  SELECT_LEX *sl;
4058  SELECT_LEX_UNIT *un;
4059  for (sl = curr_select, un = sl->master_unit(); un != unit;
4060  sl = sl->outer_select(), un = sl->master_unit()) {
4061  sl->uncacheable |= cause;
4062  un->uncacheable |= cause;
4063  }
4064  }
4066 
4067  TABLE_LIST *unlink_first_table(bool *link_to_local);
4068  void link_first_table_back(TABLE_LIST *first, bool link_to_local);
4069  void first_lists_tables_same();
4070 
4071  bool can_use_merged();
4072  bool can_not_use_merged();
4073  bool need_correct_ident();
4074  /*
4075  Is this update command where 'WHITH CHECK OPTION' clause is important
4076 
4077  SYNOPSIS
4078  LEX::which_check_option_applicable()
4079 
4080  RETURN
4081  true have to take 'WHITH CHECK OPTION' clause into account
4082  false 'WHITH CHECK OPTION' clause do not need
4083  */
4085  switch (sql_command) {
4086  case SQLCOM_UPDATE:
4087  case SQLCOM_UPDATE_MULTI:
4088  case SQLCOM_INSERT:
4089  case SQLCOM_INSERT_SELECT:
4090  case SQLCOM_REPLACE:
4091  case SQLCOM_REPLACE_SELECT:
4092  case SQLCOM_LOAD:
4093  return true;
4094  default:
4095  return false;
4096  }
4097  }
4098 
4100 
4102  return context_stack.push_front(context);
4103  }
4104 
4106 
4107  bool copy_db_to(char const **p_db, size_t *p_db_length) const;
4108 
4109  bool copy_db_to(char **p_db, size_t *p_db_length) const {
4110  return copy_db_to(const_cast<const char **>(p_db), p_db_length);
4111  }
4112 
4114 
4117 
4118  bool table_or_sp_used();
4119 
4120  /**
4121  @brief check if the statement is a single-level join
4122  @return result of the check
4123  @retval true The statement doesn't contain subqueries, unions and
4124  stored procedure calls.
4125  @retval false There are subqueries, UNIONs or stored procedure calls.
4126  */
4128  /*
4129  This check exploits the fact that the last added to all_select_list is
4130  on its top. So select_lex (as the first added) will be at the tail
4131  of the list.
4132  */
4133  if (select_lex == all_selects_list &&
4134  (sroutines == nullptr || sroutines->empty())) {
4136  return true;
4137  }
4138  return false;
4139  }
4140 
4141  /**
4142  IS schema queries read some dynamic table statistics from SE.
4143  These statistics are cached, to avoid opening of table more
4144  than once while preparing a single output record buffer.
4145  */
4148 
4149  bool accept(Select_lex_visitor *visitor);
4150 
4151  bool set_wild(LEX_STRING);
4152  void clear_privileges();
4153 
4154  bool make_sql_cmd(Parse_tree_root *parse_tree);
4155 
4156  private:
4157  /**
4158  Context object used by secondary storage engines to store query
4159  state during optimization and execution.
4160  */
4162 
4163  public:
4164  /**
4165  Gets the secondary engine execution context for this statement.
4166  */
4168  const {
4170  }
4171 
4172  /**
4173  Sets the secondary engine execution context for this statement.
4174  The old context object is destroyed, if there is one. Can be set
4175  to nullptr to destroy the old context object and clear the
4176  pointer.
4177 
4178  The supplied context object should be allocated on the execution
4179  MEM_ROOT, so that its memory doesn't have to be manually freed
4180  after query execution.
4181  */
4184 };
4185 
4186 /**
4187  The internal state of the syntax parser.
4188  This object is only available during parsing,
4189  and is private to the syntax parser implementation (sql_yacc.yy).
4190 */
4191 class Yacc_state {
4192  public:
4194 
4195  void reset() {
4196  yacc_yyss = NULL;
4197  yacc_yyvs = NULL;
4198  yacc_yyls = NULL;
4201  }
4202 
4203  ~Yacc_state();
4204 
4205  /**
4206  Reset part of the state which needs resetting before parsing
4207  substatement.
4208  */
4212  }
4213 
4214  /**
4215  Bison internal state stack, yyss, when dynamically allocated using
4216  my_yyoverflow().
4217  */
4219 
4220  /**
4221  Bison internal semantic value stack, yyvs, when dynamically allocated using
4222  my_yyoverflow().
4223  */
4225 
4226  /**
4227  Bison internal location value stack, yyls, when dynamically allocated using
4228  my_yyoverflow().
4229  */
4231 
4232  /**
4233  Type of lock to be used for tables being added to the statement's
4234  table list in table_factor, table_alias_ref, single_multi and
4235  table_wild_one rules.
4236  Statements which use these rules but require lock type different
4237  from one specified by this member have to override it by using
4238  SELECT_LEX::set_lock_for_tables() method.
4239 
4240  The default value of this member is TL_READ_DEFAULT. The only two
4241  cases in which we change it are:
4242  - When parsing SELECT HIGH_PRIORITY.
4243  - Rule for DELETE. In which we use this member to pass information
4244  about type of lock from delete to single_multi part of rule.
4245 
4246  We should try to avoid introducing new use cases as we would like
4247  to get rid of this member eventually.
4248  */
4250 
4251  /**
4252  The type of requested metadata lock for tables added to
4253  the statement table list.
4254  */
4256 
4257  /*
4258  TODO: move more attributes from the LEX structure here.
4259  */
4260 };
4261 
4262 /**
4263  Input parameters to the parser.
4264 */
4267 
4269 };
4270 
4271 /**
4272  Internal state of the parser.
4273  The complete state consist of:
4274  - input parameters that control the parser behavior
4275  - state data used during lexical parsing,
4276  - state data used during syntactic parsing.
4277 */
4279  protected:
4280  /**
4281  Constructor for special parsers of partial SQL clauses (DD)
4282 
4283  @param grammar_selector_token See Lex_input_stream::grammar_selector_token
4284  */
4285  explicit Parser_state(int grammar_selector_token)
4286  : m_input(), m_lip(grammar_selector_token), m_yacc(), m_comment(false) {}
4287 
4288  public:
4290 
4291  /**
4292  Object initializer. Must be called before usage.
4293 
4294  @retval false OK
4295  @retval true Error
4296  */
4297  bool init(THD *thd, const char *buff, size_t length) {
4298  return m_lip.init(thd, buff, length);
4299  }
4300 
4301  void reset(const char *found_semicolon, size_t length) {
4302  m_lip.reset(found_semicolon, length);
4303  m_yacc.reset();
4304  }
4305 
4306  /// Signal that the current query has a comment
4307  void add_comment() { m_comment = true; }
4308  /// Check whether the current query has a comment
4309  bool has_comment() const { return m_comment; }
4310 
4311  public:
4315  /**
4316  Current performance digest instrumentation.
4317  */
4319 
4320  private:
4321  bool m_comment; ///< True if current query contains comments
4322 };
4323 
4324 /**
4325  Parser state for partition expression parser (.frm/DD stuff)
4326 */
4328  public:
4330 
4332 };
4333 
4334 /**
4335  Parser state for generated column expression parser (.frm/DD stuff)
4336 */
4338  public:
4340 
4342 };
4343 
4344 /**
4345  Parser state for single expression parser (.frm/DD stuff)
4346 */
4348  public:
4350 
4352 };
4353 
4354 /**
4355  Parser state for CTE subquery parser
4356 */
4358  public:
4360 
4362 };
4363 
4364 struct st_lex_local : public LEX {
4365  static void *operator new(size_t size) noexcept { return sql_alloc(size); }
4366  static void *operator new(size_t size, MEM_ROOT *mem_root,
4367  const std::nothrow_t &arg MY_ATTRIBUTE((unused)) =
4368  std::nothrow) noexcept {
4369  return alloc_root(mem_root, size);
4370  }
4371  static void operator delete(void *ptr MY_ATTRIBUTE((unused)),
4372  size_t size MY_ATTRIBUTE((unused))) {
4373  TRASH(ptr, size);
4374  }
4375  static void operator delete(
4376  void *, MEM_ROOT *, const std::nothrow_t &)noexcept { /* Never called */
4377  }
4378 };
4379 
4380 extern bool lex_init(void);
4381 extern void lex_free(void);
4382 extern bool lex_start(THD *thd);
4383 extern void lex_end(LEX *lex);
4384 extern int MYSQLlex(union YYSTYPE *, struct YYLTYPE *, class THD *);
4385 
4386 extern void trim_whitespace(const CHARSET_INFO *cs, LEX_STRING *str);
4387 
4388 extern bool is_lex_native_function(const LEX_STRING *name);
4389 
4390 bool is_keyword(const char *name, size_t len);
4391 bool db_is_default_db(const char *db, size_t db_len, const THD *thd);
4392 
4394 
4395 void print_derived_column_names(const THD *thd, String *str,
4397 
4398 /**
4399  @} (End of group GROUP_PARSER)
4400 */
4401 
4402 /**
4403  Check if the given string is invalid using the system charset.
4404 
4405  @param string_val Reference to the string.
4406  @param charset_info Pointer to charset info.
4407 
4408  @return true if the string has an invalid encoding using
4409  the system charset else false.
4410 */
4411 
4412 inline bool is_invalid_string(const LEX_CSTRING &string_val,
4413  const CHARSET_INFO *charset_info) {
4414  size_t valid_len;
4415  bool len_error;
4416 
4417  if (validate_string(charset_info, string_val.str, string_val.length,
4418  &valid_len, &len_error)) {
4419  char hexbuf[7];
4420  octet2hex(
4421  hexbuf, string_val.str + valid_len,
4422  static_cast<uint>(std::min<size_t>(string_val.length - valid_len, 3)));
4423  my_error(ER_INVALID_CHARACTER_STRING, MYF(0), charset_info->csname, hexbuf);
4424  return true;
4425  }
4426  return false;
4427 }
4428 
4429 bool walk_item(Item *item, Select_lex_visitor *visitor);
4431 bool accept_table(TABLE_LIST *t, Select_lex_visitor *visitor);
4432 bool accept_for_join(List<TABLE_LIST> *tables, Select_lex_visitor *visitor);
4433 #endif /* SQL_LEX_INCLUDED */
TABLE_LIST * leaf_tables
Points to first leaf table of query block.
Definition: sql_lex.h:1149
int hndlrs
Definition: sql_lex.h:2122
Definition: sql_udf.h:42
static const char * stmt_accessed_table_string(enum_stmt_accessed_table accessed_table)
Definition: sql_lex.h:2907
class PT_part_value_item * part_value_item
Definition: sql_lex.h:2247
#define TRASH(A, B)
Put bad content in memory to be sure it will segfault if dereferenced.
Definition: memory_debugging.h:70
TABLE * table
Definition: sql_lex.h:646
SELECT_LEX * union_distinct
Points to last query block which has UNION DISTINCT on its left.
Definition: sql_lex.h:730
Parser_input m_input
Definition: sql_lex.h:4312
INSERT into auto-inc field which is not the first part in composed primary key.
Definition: sql_lex.h:2758
bool prepare_fake_select_lex(THD *thd)
Prepare the fake_select_lex query block.
Definition: sql_union.cc:381
Builder for SQL functions.
Definition: sql_lex.h:2059
char * ssl_cipher
Definition: sql_lex.h:3665
SELECT_LEX * global_parameters() const
Pointer to query block containing global parameters for query.
Definition: sql_lex.h:703
Statement_information_item::Name stmt_info_item_name
Definition: sql_lex.h:2135
bool check_view_privileges(THD *thd, ulong want_privilege_first, ulong want_privilege_next)
Check privileges for the view tables merged into a query block.
Definition: sql_resolver.cc:853
bool db_is_default_db(const char *db, size_t db_len, const THD *thd)
Definition: sql_lex.cc:2756
unsigned long long int ulonglong
Definition: my_inttypes.h:69
Representation of an SQL command.
Definition: sql_cmd.h:62
bool validate_outermost_option(LEX *lex, const char *wrong_option) const
Check if an option that can be used only for an outer-most query block is applicable to this query bl...
Definition: sql_lex.cc:4477
List< PT_key_part_specification > * index_column_list
Definition: sql_lex.h:2230
#define DBUG_RETURN(a1)
Definition: my_dbug.h:84
char * relay_log_name
Definition: sql_lex.h:416
struct jt_on_response empty
Definition: sql_lex.h:2321
Definition: partition_info.h:208
Item ** add_hidden_item(Item *item)
Add item to the hidden part of select list.
Definition: sql_resolver.cc:4312
class PT_key_part_specification * key_part
Definition: sql_lex.h:2198
Condition_information_item * cond_info_item
Definition: sql_lex.h:2137
Definition: sql_lex.h:243
char * ssl_cert
Definition: sql_lex.h:413
bool change_group_ref_for_cond(THD *thd, Item_cond *cond, bool *changed)
Similar to change_group_ref_for_func, except we are looking into an AND or OR conditions instead of f...
Definition: sql_resolver.cc:4045
LEX_CSTRING prepared_stmt_name
Definition: sql_lex.h:3868
This file defines all base public constants related to triggers in MySQL.
enum index_hint_type index_hint
Definition: sql_lex.h:2127
List< Item_param > param_list
List of placeholders (&#39;?&#39;) for parameters of a prepared statement.
Definition: sql_lex.h:3727
struct YYSTYPE::@98 vcpu_range_type
Definition: sql_lex.h:2345
bool add_ftfunc_list(List< Item_func_match > *ftfuncs)
Add a list of full-text function elements into a query block.
Definition: sql_resolver.cc:3300
Definition: sql_cmd_srs.h:40
static bool column_names
Definition: mysql.cc:155
bool optimize(THD *thd)
Optimize all query blocks of a query expression, including fake_select_lex.
Definition: sql_union.cc:707
bool add_joined_table(TABLE_LIST *table)
Add a table to the current join list.
Definition: sql_parse.cc:6089
void remove_base_options(ulonglong options)
Remove base options from a query block.
Definition: sql_lex.h:955
bool has_values_map() const
Definition: sql_lex.h:3743
class PT_column_attr_base * col_attr
Definition: sql_lex.h:2274
void print_update_options(String *str)
Print UPDATE options.
Definition: sql_lex.cc:3096
bool is_union() const
Definition: sql_lex.h:1907
unsigned char uchar
Definition: my_inttypes.h:49
bool cleanup(THD *thd, bool full)
Cleanup this query expression object after preparation or one round of execution. ...
Definition: sql_union.cc:1266
~Yacc_state()
Definition: sql_lex.cc:757
#define SELECT_DISTINCT
Definition: query_options.h:51
SQL_I_List< ORDER > group_list
GROUP BY clause.
Definition: sql_lex.h:1103
Definition: sql_optimizer.h:177
ts_alter_tablespace_type alter_tablespace_type
Definition: sql_lex.h:2414
Item * limit
Definition: sql_lex.h:1920
Definition: parse_tree_nodes.h:226
Structure to hold parameters for CHANGE MASTER, START SLAVE, and STOP SLAVE.
Definition: sql_lex.h:377
enum_from_first_last
Cf.
Definition: window_lex.h:62
enum_condition_item_name da_condition_item_name
Definition: sql_lex.h:2131
void print_from_clause(const THD *thd, String *str, enum_query_type query_type)
Print list of tables in FROM clause.
Definition: sql_lex.cc:3250
Our own string classes, used pervasively throughout the executor.
table_map select_list_tables
The set of those tables whose fields are referenced in the select list of this select level...
Definition: sql_lex.h:1286
bool safe_to_cache_query
Whether this query will return the same answer every time, given unchanged data.
Definition: sql_lex.h:3856
enum fk_option m_fk_option
Definition: sql_lex.h:2129
Item * item
Definition: sql_lex.h:2088
The internal state of the syntax parser.
Definition: sql_lex.h:4191
class PT_subselect * subselect
Definition: sql_lex.h:2149
uint reparse_common_table_expr_at
If currently re-parsing a CTE&#39;s definition, this is the offset in bytes of that definition in the ori...
Definition: sql_lex.h:3820
LEX_CSTRING key_name
Definition: sql_lex.h:476
void destroy_query_tables_list()
Definition: sql_lex.cc:3503
bool optimize(THD *thd)
Optimize a query block and all inner query expressions.
Definition: sql_select.cc:1721
Utility RAII class to save/modify/restore the semijoin_disallowed flag.
Definition: sql_lex.h:2424
static void * alloc_root(MEM_ROOT *root, size_t length)
Definition: my_alloc.h:314
void trim_whitespace(const CHARSET_INFO *cs, LEX_STRING *str)
Definition: sql_lex.cc:1932
"public" interface to sys_var - server configuration variables.
class Table_ident * table_ident
Definition: sql_lex.h:2224
Alter_info::enum_alter_table_lock alter_table_lock
Definition: sql_lex.h:2344
Set_signal_information * signal_item_list
Definition: sql_lex.h:2141
enum LEX_MASTER_INFO::@76 get_public_key
sp_name * spname
Definition: sql_lex.h:3879
bool merge_derived(THD *thd, TABLE_LIST *derived_table)
Merge derived table into query block.
Definition: sql_resolver.cc:2730
Parser_state()
Definition: sql_lex.h:4289
Definition: sql_lex.h:246
struct YYSTYPE::@94 wild_or_where
class PT_border * bound
Definition: sql_lex.h:2164
const char * db_name
Definition: rules_table_service.cc:54
class PT_internal_variable_name * internal_variable_name
Definition: sql_lex.h:2173
ulonglong table_map
Definition: my_table_map.h:32
char * host
Definition: sql_lex.h:385
bool resolve_rollup_wfs(THD *thd)
Replace group by field references inside window functions with references in the the presence of ROLL...
Definition: sql_resolver.cc:4160
char * x509_issuer
Definition: sql_lex.h:3665
char * password
Definition: sql_lex.h:385
char * plugin_dir
Definition: sql_lex.h:2465
void set_base_options(ulonglong options_arg)
Set base options for a query block (and active options too)
Definition: sql_lex.h:934
Lock_strength
Definition: sql_lex.h:1941
enum_order
Definition: key_spec.h:64
Definition: mysql_lex_string.h:34
The class hold dynamic table statistics for a table.
Definition: table_stats.h:102
void set_where_cond(Item *cond)
Definition: sql_lex.h:925
Histogram_command
Specifies which (if any) of the commands UPDATE HISTOGRAM or DROP HISTOGRAM that is specified after A...
Definition: sql_admin.h:68
interval_type interval_time_st
Definition: sql_lex.h:2116
Definition: parse_tree_nodes.h:3287
bool expr_allows_subselect
Definition: sql_lex.h:3814
List< Item > * get_unit_column_types()
Get column type information for this query expression.
Definition: sql_union.cc:1383
bool grant_as_used
Definition: sql_lex.h:3627
ha_rows get_limit(THD *thd)
Get limit.
Definition: sql_lex.cc:2406
Definition: parse_tree_nodes.h:4768
const char * m_cpp_text_end
Ending position of the TEXT_STRING or IDENT in the pre-processed buffer.
Definition: sql_lex.h:3573
static const int BINLOG_STMT_UNSAFE_ALL_FLAGS
This has all flags from 0 (inclusive) to BINLOG_STMT_FLAG_COUNT (exclusive) set.
Definition: sql_lex.h:2779
Group_list_ptrs * group_list_ptrs
Definition: sql_lex.h:1104
#define ZEROFILL_FLAG
Field is zerofill.
Definition: mysql_com.h:155
enum LEX_MASTER_INFO::@76 heartbeat_opt
TABLE_LIST * next_global
Definition: table.h:3017
bool build_sj_cond(THD *thd, NESTED_JOIN *nested_join, SELECT_LEX *subq_select, table_map outer_tables_map, Item **sj_cond)
Build semijoin condition for th query block.
Definition: sql_resolver.cc:2037
bool allows_variable
Definition: sql_lex.h:3118
bool prepared
All query blocks in query expression are prepared.
Definition: sql_lex.h:640
Definition: handler.h:3099
Access to log tables is unsafe because slave and master probably log different things.
Definition: sql_lex.h:2648
bool setup_join_cond(THD *thd, List< TABLE_LIST > *tables, bool in_update)
Resolve join conditions for a join nest.
Definition: sql_resolver.cc:1398
bool no_write_to_binlog
Definition: sql_lex.h:3845
Definition: sql_lex.h:3635
void make_active_options(ulonglong added_options, ulonglong removed_options)
Make active options from base options, supplied options and environment:
Definition: sql_lex.cc:2293
bool is_explain() const
Definition: sql_lex.h:3661
Query_tables_list & operator=(Query_tables_list &&)=default
Definition: sql_lex.h:438
Set_signal_information is a container used in the parsed tree to represent the collection of assignme...
Definition: sql_signal.h:67
decltype(HA_CHECK_OPT::flags) flags
Definition: sql_lex.h:2265
bool in_update_value_clause
Set to true while resolving values in ON DUPLICATE KEY UPDATE clause.
Definition: sql_lex.h:3991
Event_parse_data * event_parse_data
Definition: sql_lex.h:3958
CREATE TABLE...SELECT on a table with auto-increment column is unsafe because which rows are replaced...
Definition: sql_lex.h:2739
bool set_braces(bool value)
Definition: sql_lex.cc:2472
void restore_in_comment_state()
Definition: sql_lex.h:3201
bool saved_value
Definition: sql_lex.h:2440
bool accept(Select_lex_visitor *visitor)
Definition: sql_lex.cc:3365
Definition: sql_lex.h:244
static const char * type_str[static_cast< int >(enum_explain_type::EXPLAIN_total)]
Definition: sql_lex.h:1782
Definition: parse_tree_nodes.h:920
Definition: parse_tree_nodes.h:1322
Definition: sql_lex.h:1966
SELECT_LEX * last_select()
Definition: sql_lex.h:1319
const string name("\ame\)
T ** next
A reference to the next element in the list.
Definition: sql_list.h:51
bool visibility
Definition: sql_lex.h:2238
Order clause list element.
Definition: table.h:269
LEX_USER * grant_user
Definition: sql_lex.h:3671
Enum m_enum
The wrapped Enum value.
Definition: sql_lex.h:2055
bool setup_base_ref_items(THD *thd)
Setup the array containing references to base items.
Definition: sql_lex.cc:2477
TABLE_LIST * unlink_first_table(bool *link_to_local)
Definition: sql_lex.cc:3978
struct YYSTYPE::jt_on_response jt_on_response
void body_utf8_append_literal(THD *thd, const LEX_STRING *txt, const CHARSET_INFO *txt_cs, const char *end_ptr)
The operation converts the specified text literal to the utf8 and appends the result to the utf8-body...
Definition: sql_lex.cc:348
Int_type
Definition: sql_lex.h:1983
Definition: sql_lex.h:2514
void propagate_unique_test_exclusion()
Propagate exclusion from unique table check into all subqueries belonging to this query block...
Definition: sql_resolver.cc:3283
SELECT_LEX * m_current_select
Definition: sql_lex.h:3644
enum enum_yes_no_unknown m_yes_no_unk
Definition: sql_lex.h:2130
SELECT_LEX_UNIT * sel
Definition: sql_lex.h:325
class sp_condition_value * spcondvalue
Definition: sql_lex.h:2120
T value
undefined if is_default is true
Definition: sql_lex.h:2061
Using a UDF (user-defined function) is unsafe.
Definition: sql_lex.h:2661
Item::cond_result cond_value
Saved values of the WHERE and HAVING clauses.
Definition: sql_lex.h:1087
class Item * default_value
Definition: sql_lex.h:2220
Acl_type acl_type
Definition: sql_lex.h:2335
LEX_STRING prepared_stmt_code
Definition: sql_lex.h:3873
ulonglong m_base_options
Options assigned from parsing and throughout resolving, should not be modified after resolving is don...
Definition: sql_lex.h:1009
Node for a list of partitioning values in VALUES clauses.
Definition: parse_tree_partitions.h:325
enum_explain_type type()
Lookup for SELECT_LEX type.
Definition: sql_lex.cc:4219
File containing constants that can be used throughout the server.
bool check_only_full_group_by(THD *thd)
Runs checks mandated by ONLY_FULL_GROUP_BY.
Definition: sql_resolver.cc:3766
const char * get_cpp_ptr() const
Get the current stream pointer, in the pre-processed buffer.
Definition: sql_lex.h:3367
Definition: my_sqlcommand.h:52
Inserting into an autoincrement column in a stored routine is unsafe.
Definition: sql_lex.h:2657
enum_parsing_context
Names for different query parse tree parts.
Definition: parse_tree_node_base.h:55
#define IL_LT_REPEATABLE
Definition: sql_lex.h:2958
Default value, used when it&#39;s not specified in the statement.
Definition: sql_alter.h:362
Definition: sql_lex.h:2461
SELECT_LEX * saved_fake_select_lex
SELECT_LEX that stores LIMIT and OFFSET for UNION ALL when no fake_select_lex is used.
Definition: sql_lex.h:723
Lexer_yystype * lookahead_yylval
LALR(2) resolution, value of the look ahead token.
Definition: sql_lex.h:3417
fk_option fk_update_opt
Definition: sql_lex.h:2289
List< Item > * get_field_list()
Get field list for this query expression.
Definition: sql_union.cc:1399
bool has_sj_candidates() const
Definition: sql_lex.h:1815
partition_info * part_info
Definition: sql_lex.h:3694
Some integer typedefs for easier portability.
TABLE_LIST * get_table_list() const
Definition: sql_lex.h:1400
void my_error(int nr, myf MyFlags,...)
Fill in and print a previously registered error message.
Definition: my_error.cc:215
enum_ha_read_modes ha_read_mode
Definition: sql_lex.h:2103
Prealloced_array< ulong, 2 > repl_ignore_server_ids
Definition: sql_lex.h:418
List< String > * set_expr_str_list
Definition: sql_lex.h:2412
void print_limit(const THD *thd, String *str, enum_query_type query_type)
Definition: sql_lex.cc:2572
enum enum_trigger_action_time_type action_time
Definition: sql_lex.h:2481
class PT_alter_table_action * alter_table_action
Definition: sql_lex.h:2341
bool accept(Select_lex_visitor *visitor)
Accept function for SELECT and DELETE.
Definition: sql_lex.cc:3394
KEY_CREATE_INFO key_create_info
Definition: sql_lex.h:3780
Hint_param_table_list hint_param_table_list
Definition: sql_lex.h:2076
void set_sj_candidates(Mem_root_array< Item_exists_subselect *> *sj_cand)
Definition: sql_lex.h:1811
Mem_root_array< PT_assign_to_keycache * > * keycache_list
Definition: sql_lex.h:2387
enum_keep_diagnostics
Definition: sql_lex.h:227
is the single *token from the main parser s point of and we add the SELECT *keyword to the digest buffer right after the *but the is a sequence of separate tokens from the hint *parser s point of and we add those tokens to the digest buffer **inside *the the usual data flow adds *tokens from the string and only than it appends *the SELECT keyword token to that since we use the digest buffer to restore *query strings in their normalized so the order of added tokens is *important we add tokens of hintable keywords to a digest buffer *right in the hint parser and skip adding of them at the caller with the *help of skip_digest flag *bool skip_digest
Definition: sql_lex.h:3429
enum enum_null_treatment null_treatment
Definition: sql_lex.h:2166
Definition: field_types.h:59
void fix_after_pullout(SELECT_LEX *parent_select, SELECT_LEX *removed_select)
Fix used tables information for a subquery after query transformations.
Definition: sql_union.cc:1429
Parser_state(int grammar_selector_token)
Constructor for special parsers of partial SQL clauses (DD)
Definition: sql_lex.h:4285
bool check_materialized_derived_query_blocks(THD *thd)
Sets up query blocks belonging to the query expression of a materialized derived table.
Definition: sql_derived.cc:584
INSERT...REPLACE SELECT is unsafe because which rows are replaced depends on the order that rows are ...
Definition: sql_lex.h:2717
bool is_partial_parser() const
True if this scanner tokenizes a partial query (partition expression, generated column expression etc...
Definition: sql_lex.h:3448
void set_empty_query()
Set query block as returning no data.
Definition: sql_lex.h:1705
char * yyUnput(char ch)
Puts a character back into the stream, canceling the effect of the last yyGet() or yySkip()...
Definition: sql_lex.h:3293
bool subquery_in_having
HAVING clause contains subquery => we can&#39;t close tables before query processing end even if we use t...
Definition: sql_lex.h:1245
SELECT_LEX * fake_select_lex
Helper query block for query expression with UNION or multi-level ORDER BY/LIMIT. ...
Definition: sql_lex.h:718
Definition: parse_tree_nodes.h:240
void set_optimized()
Definition: sql_lex.h:810
bool print_error(const THD *thd, String *str)
Print error.
Definition: sql_lex.cc:3057
const char * m_tok_start
Starting position of the last token parsed, in the raw buffer.
Definition: sql_lex.h:3481
uint binlog_unsafe_map[256]
Definition: sql_lex.cc:4703
sp_pcontext * sp_current_parsing_ctx
Current SP parsing context.
Definition: sql_lex.h:3895
Item * opt_offset
Definition: sql_lex.h:1921
void include_standalone(SELECT_LEX_UNIT *sel, SELECT_LEX **ref)
Include query block inside a query expression, but do not link.
Definition: sql_lex.cc:4287
Cast_target
Definition: item_create.h:53
Definition: parse_tree_nodes.h:1202
INSERT...IGNORE SELECT is unsafe because which rows are ignored depends on the order that rows are re...
Definition: sql_lex.h:2696
PT_alter_tablespace_option_base * ts_option
Definition: sql_lex.h:2391
void print_windows(const THD *thd, String *str, enum_query_type query_type)
Print details of Windowing functions.
Definition: sql_lex.cc:3314
void mark_as_requiring_prelocking(TABLE_LIST **tables_own_last)
Definition: sql_lex.h:2608
bool mixed_union_operators() const
Definition: sql_union.cc:1414
uint sroutines_list_own_elements
Definition: sql_lex.h:2557
Definition: sql_lex.h:1957
ulong type
Definition: sql_lex.h:3786
bool test_limit()
Definition: sql_lex.cc:2364
ulonglong pos
Definition: sql_lex.h:389
void insert_values_map(Field *f1, Field *f2)
Definition: sql_lex.h:3731
bool grant_privilege
Definition: sql_lex.h:3832
void reset(const char *found_semicolon, size_t length)
Definition: sql_lex.h:4301
Table_ident(const LEX_CSTRING &db_arg, const LEX_CSTRING &table_arg)
Definition: sql_lex.h:330
bool is_set() const
False if the wrapped Enum value is not assigned.
Definition: sql_lex.h:2029
const char * str
Definition: mysql_lex_string.h:40
Table_function * table_function
Definition: sql_lex.h:326
List< TABLE_LIST > top_join_list
join list of the top level
Definition: sql_lex.h:1136
char * network_namespace
Definition: sql_lex.h:385
float heartbeat_period
Definition: sql_lex.h:387
struct module_t * m
Definition: dbug_analyze.cc:469
Definition: sql_lex.h:1963
bool first_execution
This variable is required to ensure proper work of subqueries and stored procedures.
Definition: sql_lex.h:1258
bool apply_local_transforms(THD *thd, bool prune)
Does permanent transformations which are local to a query block (which do not merge it to another blo...
Definition: sql_resolver.cc:533
This class represents a query block, aka a query specification, which is a query consisting of a SELE...
Definition: sql_lex.h:922
void body_utf8_append(const char *ptr)
The operation appends unprocessed part of the pre-processed buffer till the given pointer (ptr) and s...
Definition: sql_lex.cc:332
keep diagnostics area after parse error
Definition: sql_lex.h:231
Query_result * result
Definition: sql_lex.h:3668
void invalidate()
Invalidate by nulling out pointers to other SELECT_LEX_UNITs and SELECT_LEXes.
Definition: sql_lex.cc:2278
ulong retry_count
Definition: sql_lex.h:390
class PT_item_list * item_list2
Definition: sql_lex.h:2150
Mem_root_array_YY< PT_base_index_option * > index_options
Definition: sql_lex.h:2236
Definition: field.h:707
enum_comment_state in_comment
State of the lexical analyser for comments.
Definition: sql_lex.h:3556
bool change_query_result(THD *thd, Query_result_interceptor *result, Query_result_interceptor *old_result)
Change the query result object used to return the final result of the unit, replacing occurences of o...
Definition: sql_union.cc:1354
enum_duplicates
Definition: sql_data_change.h:45
Server_options server_options
Definition: sql_lex.h:3783
Mem_root_array< resourcegroups::Range > * resource_group_vcpu_list_type
Definition: sql_lex.h:2397
Definition: my_sqlcommand.h:86