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