1/* Copyright (c) 2000, 2015, Oracle and/or its affiliates.
2 Copyright (c) 2010, 2018, MariaDB Corporation
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; version 2 of the License.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
16
17/**
18 @defgroup Semantic_Analysis Semantic Analysis
19*/
20
21#ifndef SQL_LEX_INCLUDED
22#define SQL_LEX_INCLUDED
23
24#include "violite.h" /* SSL_type */
25#include "sql_trigger.h"
26#include "thr_lock.h" /* thr_lock_type, TL_UNLOCK */
27#include "mem_root_array.h"
28#include "sql_cmd.h"
29#include "sql_alter.h" // Alter_info
30#include "sql_window.h"
31#include "sql_trigger.h"
32#include "sp.h" // enum stored_procedure_type
33#include "sql_tvc.h"
34#include "item.h"
35
36/* YACC and LEX Definitions */
37
38
39/**
40 A string with metadata. Usually points to a string in the client
41 character set, but unlike Lex_ident_cli_st (see below) it does not
42 necessarily point to a query fragment. It can also point to memory
43 of other kinds (e.g. an additional THD allocated memory buffer
44 not overlapping with the current query text).
45
46 We'll add more flags here eventually, to know if the string has, e.g.:
47 - multi-byte characters
48 - bad byte sequences
49 - backslash escapes: 'a\nb'
50 and reuse the original query fragments instead of making the string
51 copy too early, in Lex_input_stream::get_text().
52 This will allow to avoid unnecessary copying, as well as
53 create more optimal Item types in sql_yacc.yy
54*/
55struct Lex_string_with_metadata_st: public LEX_CSTRING
56{
57private:
58 bool m_is_8bit; // True if the string has 8bit characters
59 char m_quote; // Quote character, or 0 if not quoted
60public:
61 void set_8bit(bool is_8bit) { m_is_8bit= is_8bit; }
62 void set_metadata(bool is_8bit, char quote)
63 {
64 m_is_8bit= is_8bit;
65 m_quote= quote;
66 }
67 void set(const char *s, size_t len, bool is_8bit, char quote)
68 {
69 str= s;
70 length= len;
71 set_metadata(is_8bit, quote);
72 }
73 void set(const LEX_CSTRING *s, bool is_8bit, char quote)
74 {
75 ((LEX_CSTRING &)*this)= *s;
76 set_metadata(is_8bit, quote);
77 }
78 bool is_8bit() const { return m_is_8bit; }
79 bool is_quoted() const { return m_quote != '\0'; }
80 char quote() const { return m_quote; }
81 // Get string repertoire by the 8-bit flag and the character set
82 uint repertoire(CHARSET_INFO *cs) const
83 {
84 return !m_is_8bit && my_charset_is_ascii_based(cs) ?
85 MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30;
86 }
87 // Get string repertoire by the 8-bit flag, for ASCII-based character sets
88 uint repertoire() const
89 {
90 return !m_is_8bit ? MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30;
91 }
92};
93
94
95/*
96 Used to store identifiers in the client character set.
97 Points to a query fragment.
98*/
99struct Lex_ident_cli_st: public Lex_string_with_metadata_st
100{
101public:
102 void set_keyword(const char *s, size_t len)
103 {
104 set(s, len, false, '\0');
105 }
106 void set_ident(const char *s, size_t len, bool is_8bit)
107 {
108 set(s, len, is_8bit, '\0');
109 }
110 void set_ident_quoted(const char *s, size_t len, bool is_8bit, char quote)
111 {
112 set(s, len, is_8bit, quote);
113 }
114 void set_unquoted(const LEX_CSTRING *s, bool is_8bit)
115 {
116 set(s, is_8bit, '\0');
117 }
118 const char *pos() const { return str - is_quoted(); }
119 const char *end() const { return str + length + is_quoted(); }
120};
121
122
123class Lex_ident_cli: public Lex_ident_cli_st
124{
125public:
126 Lex_ident_cli(const LEX_CSTRING *s, bool is_8bit)
127 {
128 set_unquoted(s, is_8bit);
129 }
130 Lex_ident_cli(const char *s, size_t len)
131 {
132 set_ident(s, len, false);
133 }
134};
135
136
137struct Lex_ident_sys_st: public LEX_CSTRING
138{
139public:
140 bool copy_ident_cli(THD *thd, const Lex_ident_cli_st *str);
141 bool copy_keyword(THD *thd, const Lex_ident_cli_st *str);
142 bool copy_sys(THD *thd, const LEX_CSTRING *str);
143 bool convert(THD *thd, const LEX_CSTRING *str, CHARSET_INFO *cs);
144 bool copy_or_convert(THD *thd, const Lex_ident_cli_st *str, CHARSET_INFO *cs);
145 bool is_null() const { return str == NULL; }
146 bool to_size_number(ulonglong *to) const;
147};
148
149
150class Lex_ident_sys: public Lex_ident_sys_st
151{
152public:
153 Lex_ident_sys(THD *thd, const Lex_ident_cli_st *str)
154 {
155 if (copy_ident_cli(thd, str))
156 ((LEX_CSTRING &) *this)= null_clex_str;
157 }
158 Lex_ident_sys()
159 {
160 ((LEX_CSTRING &) *this)= null_clex_str;
161 }
162};
163
164
165enum sub_select_type
166{
167 UNSPECIFIED_TYPE,
168 /* following 3 enums should be as they are*/
169 UNION_TYPE, INTERSECT_TYPE, EXCEPT_TYPE,
170 GLOBAL_OPTIONS_TYPE, DERIVED_TABLE_TYPE, OLAP_TYPE
171};
172enum unit_common_op {OP_MIX, OP_UNION, OP_INTERSECT, OP_EXCEPT};
173
174enum enum_view_suid
175{
176 VIEW_SUID_INVOKER= 0,
177 VIEW_SUID_DEFINER= 1,
178 VIEW_SUID_DEFAULT= 2
179};
180
181/* These may not be declared yet */
182class Table_ident;
183class sql_exchange;
184class LEX_COLUMN;
185class sp_head;
186class sp_name;
187class sp_instr;
188class sp_pcontext;
189class sp_variable;
190class sp_assignment_lex;
191class st_alter_tablespace;
192class partition_info;
193class Event_parse_data;
194class set_var_base;
195class sys_var;
196class Item_func_match;
197class File_parser;
198class Key_part_spec;
199class Item_window_func;
200struct sql_digest_state;
201class With_clause;
202class my_var;
203
204#define ALLOC_ROOT_SET 1024
205
206#ifdef MYSQL_SERVER
207/*
208 There are 8 different type of table access so there is no more than
209 combinations 2^8 = 256:
210
211 . STMT_READS_TRANS_TABLE
212
213 . STMT_READS_NON_TRANS_TABLE
214
215 . STMT_READS_TEMP_TRANS_TABLE
216
217 . STMT_READS_TEMP_NON_TRANS_TABLE
218
219 . STMT_WRITES_TRANS_TABLE
220
221 . STMT_WRITES_NON_TRANS_TABLE
222
223 . STMT_WRITES_TEMP_TRANS_TABLE
224
225 . STMT_WRITES_TEMP_NON_TRANS_TABLE
226
227 The unsafe conditions for each combination is represented within a byte
228 and stores the status of the option --binlog-direct-non-trans-updates,
229 whether the trx-cache is empty or not, and whether the isolation level
230 is lower than ISO_REPEATABLE_READ:
231
232 . option (OFF/ON)
233 . trx-cache (empty/not empty)
234 . isolation (>= ISO_REPEATABLE_READ / < ISO_REPEATABLE_READ)
235
236 bits 0 : . OFF, . empty, . >= ISO_REPEATABLE_READ
237 bits 1 : . OFF, . empty, . < ISO_REPEATABLE_READ
238 bits 2 : . OFF, . not empty, . >= ISO_REPEATABLE_READ
239 bits 3 : . OFF, . not empty, . < ISO_REPEATABLE_READ
240 bits 4 : . ON, . empty, . >= ISO_REPEATABLE_READ
241 bits 5 : . ON, . empty, . < ISO_REPEATABLE_READ
242 bits 6 : . ON, . not empty, . >= ISO_REPEATABLE_READ
243 bits 7 : . ON, . not empty, . < ISO_REPEATABLE_READ
244*/
245extern uint binlog_unsafe_map[256];
246/*
247 Initializes the array with unsafe combinations and its respective
248 conditions.
249*/
250void binlog_unsafe_map_init();
251#endif
252
253struct LEX_TYPE
254{
255 enum enum_field_types type;
256 char *length, *dec;
257 CHARSET_INFO *charset;
258 void set(int t, char *l, char *d, CHARSET_INFO *cs)
259 { type= (enum_field_types)t; length= l; dec= d; charset= cs; }
260};
261
262#ifdef MYSQL_SERVER
263/*
264 The following hack is needed because mysql_yacc.cc does not define
265 YYSTYPE before including this file
266*/
267#ifdef MYSQL_YACC
268#define LEX_YYSTYPE void *
269#else
270#include "lex_symbol.h"
271#ifdef MYSQL_LEX
272#include "item_func.h" /* Cast_target used in sql_yacc.h */
273#include "sql_get_diagnostics.h" /* Types used in sql_yacc.h */
274#include "sp_pcontext.h"
275#include "sql_yacc.h"
276#define LEX_YYSTYPE YYSTYPE *
277#else
278#define LEX_YYSTYPE void *
279#endif
280#endif
281#endif
282
283// describe/explain types
284#define DESCRIBE_NORMAL 1
285#define DESCRIBE_EXTENDED 2
286/*
287 This is not within #ifdef because we want "EXPLAIN PARTITIONS ..." to produce
288 additional "partitions" column even if partitioning is not compiled in.
289*/
290#define DESCRIBE_PARTITIONS 4
291
292#ifdef MYSQL_SERVER
293
294extern const LEX_STRING empty_lex_str;
295extern MYSQL_PLUGIN_IMPORT const LEX_CSTRING empty_clex_str;
296extern const LEX_CSTRING star_clex_str;
297extern const LEX_CSTRING param_clex_str;
298
299enum enum_sp_suid_behaviour
300{
301 SP_IS_DEFAULT_SUID= 0,
302 SP_IS_NOT_SUID,
303 SP_IS_SUID
304};
305
306enum enum_sp_data_access
307{
308 SP_DEFAULT_ACCESS= 0,
309 SP_CONTAINS_SQL,
310 SP_NO_SQL,
311 SP_READS_SQL_DATA,
312 SP_MODIFIES_SQL_DATA
313};
314
315enum enum_sp_aggregate_type
316{
317 DEFAULT_AGGREGATE= 0,
318 NOT_AGGREGATE,
319 GROUP_AGGREGATE
320};
321
322const LEX_CSTRING sp_data_access_name[]=
323{
324 { STRING_WITH_LEN("") },
325 { STRING_WITH_LEN("CONTAINS SQL") },
326 { STRING_WITH_LEN("NO SQL") },
327 { STRING_WITH_LEN("READS SQL DATA") },
328 { STRING_WITH_LEN("MODIFIES SQL DATA") }
329};
330
331#define DERIVED_SUBQUERY 1
332#define DERIVED_VIEW 2
333#define DERIVED_WITH 4
334
335enum enum_view_create_mode
336{
337 VIEW_CREATE_NEW, // check that there are not such VIEW/table
338 VIEW_ALTER, // check that VIEW .frm with such name exists
339 VIEW_CREATE_OR_REPLACE // check only that there are not such table
340};
341
342
343class Create_view_info: public Sql_alloc
344{
345public:
346 LEX_CSTRING select; // The SELECT statement of CREATE VIEW
347 enum enum_view_create_mode mode;
348 uint16 algorithm;
349 uint8 check;
350 enum enum_view_suid suid;
351 Create_view_info(enum_view_create_mode mode_arg,
352 uint16 algorithm_arg,
353 enum_view_suid suid_arg)
354 :select(null_clex_str),
355 mode(mode_arg),
356 algorithm(algorithm_arg),
357 check(VIEW_CHECK_NONE),
358 suid(suid_arg)
359 { }
360};
361
362
363enum enum_drop_mode
364{
365 DROP_DEFAULT, // mode is not specified
366 DROP_CASCADE, // CASCADE option
367 DROP_RESTRICT // RESTRICT option
368};
369
370/* Options to add_table_to_list() */
371#define TL_OPTION_UPDATING 1
372#define TL_OPTION_FORCE_INDEX 2
373#define TL_OPTION_IGNORE_LEAVES 4
374#define TL_OPTION_ALIAS 8
375#define TL_OPTION_SEQUENCE 16
376
377typedef List<Item> List_item;
378typedef Mem_root_array<ORDER*, true> Group_list_ptrs;
379
380/* SERVERS CACHE CHANGES */
381typedef struct st_lex_server_options
382{
383 long port;
384 LEX_CSTRING server_name, host, db, username, password, scheme, socket, owner;
385 void reset(LEX_CSTRING name)
386 {
387 server_name= name;
388 host= db= username= password= scheme= socket= owner= null_clex_str;
389 port= -1;
390 }
391} LEX_SERVER_OPTIONS;
392
393
394/**
395 Structure to hold parameters for CHANGE MASTER, START SLAVE, and STOP SLAVE.
396
397 Remark: this should not be confused with Master_info (and perhaps
398 would better be renamed to st_lex_replication_info). Some fields,
399 e.g., delay, are saved in Relay_log_info, not in Master_info.
400*/
401struct LEX_MASTER_INFO
402{
403 DYNAMIC_ARRAY repl_ignore_server_ids;
404 DYNAMIC_ARRAY repl_do_domain_ids;
405 DYNAMIC_ARRAY repl_ignore_domain_ids;
406 const char *host, *user, *password, *log_file_name;
407 const char *ssl_key, *ssl_cert, *ssl_ca, *ssl_capath, *ssl_cipher;
408 const char *ssl_crl, *ssl_crlpath;
409 const char *relay_log_name;
410 LEX_CSTRING connection_name;
411 /* Value in START SLAVE UNTIL master_gtid_pos=xxx */
412 LEX_CSTRING gtid_pos_str;
413 ulonglong pos;
414 ulong relay_log_pos;
415 ulong server_id;
416 uint port, connect_retry;
417 float heartbeat_period;
418 int sql_delay;
419 /*
420 Enum is used for making it possible to detect if the user
421 changed variable or if it should be left at old value
422 */
423 enum {LEX_MI_UNCHANGED= 0, LEX_MI_DISABLE, LEX_MI_ENABLE}
424 ssl, ssl_verify_server_cert, heartbeat_opt, repl_ignore_server_ids_opt,
425 repl_do_domain_ids_opt, repl_ignore_domain_ids_opt;
426 enum {
427 LEX_GTID_UNCHANGED, LEX_GTID_NO, LEX_GTID_CURRENT_POS, LEX_GTID_SLAVE_POS
428 } use_gtid_opt;
429
430 void init()
431 {
432 bzero(this, sizeof(*this));
433 my_init_dynamic_array(&repl_ignore_server_ids,
434 sizeof(::server_id), 0, 16, MYF(0));
435 my_init_dynamic_array(&repl_do_domain_ids,
436 sizeof(ulong), 0, 16, MYF(0));
437 my_init_dynamic_array(&repl_ignore_domain_ids,
438 sizeof(ulong), 0, 16, MYF(0));
439 sql_delay= -1;
440 }
441 void reset(bool is_change_master)
442 {
443 if (unlikely(is_change_master))
444 {
445 delete_dynamic(&repl_ignore_server_ids);
446 /* Free all the array elements. */
447 delete_dynamic(&repl_do_domain_ids);
448 delete_dynamic(&repl_ignore_domain_ids);
449 }
450
451 host= user= password= log_file_name= ssl_key= ssl_cert= ssl_ca=
452 ssl_capath= ssl_cipher= relay_log_name= 0;
453 pos= relay_log_pos= server_id= port= connect_retry= 0;
454 heartbeat_period= 0;
455 ssl= ssl_verify_server_cert= heartbeat_opt=
456 repl_ignore_server_ids_opt= repl_do_domain_ids_opt=
457 repl_ignore_domain_ids_opt= LEX_MI_UNCHANGED;
458 gtid_pos_str= null_clex_str;
459 use_gtid_opt= LEX_GTID_UNCHANGED;
460 sql_delay= -1;
461 }
462};
463
464typedef struct st_lex_reset_slave
465{
466 bool all;
467} LEX_RESET_SLAVE;
468
469enum olap_type
470{
471 UNSPECIFIED_OLAP_TYPE, CUBE_TYPE, ROLLUP_TYPE
472};
473
474/*
475 String names used to print a statement with index hints.
476 Keep in sync with index_hint_type.
477*/
478extern const char * index_hint_type_name[];
479typedef uchar index_clause_map;
480
481/*
482 Bits in index_clause_map : one for each possible FOR clause in
483 USE/FORCE/IGNORE INDEX index hint specification
484*/
485#define INDEX_HINT_MASK_JOIN (1)
486#define INDEX_HINT_MASK_GROUP (1 << 1)
487#define INDEX_HINT_MASK_ORDER (1 << 2)
488
489#define INDEX_HINT_MASK_ALL (INDEX_HINT_MASK_JOIN | INDEX_HINT_MASK_GROUP | \
490 INDEX_HINT_MASK_ORDER)
491
492class select_result_sink;
493
494/* Single element of an USE/FORCE/IGNORE INDEX list specified as a SQL hint */
495class Index_hint : public Sql_alloc
496{
497public:
498 /* The type of the hint : USE/FORCE/IGNORE */
499 enum index_hint_type type;
500 /* Where the hit applies to. A bitmask of INDEX_HINT_MASK_<place> values */
501 index_clause_map clause;
502 /*
503 The index name. Empty (str=NULL) name represents an empty list
504 USE INDEX () clause
505 */
506 LEX_CSTRING key_name;
507
508 Index_hint (enum index_hint_type type_arg, index_clause_map clause_arg,
509 const char *str, size_t length) :
510 type(type_arg), clause(clause_arg)
511 {
512 key_name.str= str;
513 key_name.length= length;
514 }
515
516 void print(THD *thd, String *str);
517};
518
519/*
520 The state of the lex parsing for selects
521
522 master and slaves are pointers to select_lex.
523 master is pointer to upper level node.
524 slave is pointer to lower level node
525 select_lex is a SELECT without union
526 unit is container of either
527 - One SELECT
528 - UNION of selects
529 select_lex and unit are both inherited form select_lex_node
530 neighbors are two select_lex or units on the same level
531
532 All select describing structures linked with following pointers:
533 - list of neighbors (next/prev) (prev of first element point to slave
534 pointer of upper structure)
535 - For select this is a list of UNION's (or one element list)
536 - For units this is a list of sub queries for the upper level select
537
538 - pointer to master (master), which is
539 If this is a unit
540 - pointer to outer select_lex
541 If this is a select_lex
542 - pointer to outer unit structure for select
543
544 - pointer to slave (slave), which is either:
545 If this is a unit:
546 - first SELECT that belong to this unit
547 If this is a select_lex
548 - first unit that belong to this SELECT (subquries or derived tables)
549
550 - list of all select_lex (link_next/link_prev)
551 This is to be used for things like derived tables creation, where we
552 go through this list and create the derived tables.
553
554 If unit contain several selects (UNION now, INTERSECT etc later)
555 then it have special select_lex called fake_select_lex. It used for
556 storing global parameters (like ORDER BY, LIMIT) and executing union.
557 Subqueries used in global ORDER BY clause will be attached to this
558 fake_select_lex, which will allow them correctly resolve fields of
559 'upper' UNION and outer selects.
560
561 For example for following query:
562
563 select *
564 from table1
565 where table1.field IN (select * from table1_1_1 union
566 select * from table1_1_2)
567 union
568 select *
569 from table2
570 where table2.field=(select (select f1 from table2_1_1_1_1
571 where table2_1_1_1_1.f2=table2_1_1.f3)
572 from table2_1_1
573 where table2_1_1.f1=table2.f2)
574 union
575 select * from table3;
576
577 we will have following structure:
578
579 select1: (select * from table1 ...)
580 select2: (select * from table2 ...)
581 select3: (select * from table3)
582 select1.1.1: (select * from table1_1_1)
583 ...
584
585 main unit
586 fake0
587 select1 select2 select3
588 |^^ |^
589 s||| ||master
590 l||| |+---------------------------------+
591 a||| +---------------------------------+|
592 v|||master slave ||
593 e||+-------------------------+ ||
594 V| neighbor | V|
595 unit1.1<+==================>unit1.2 unit2.1
596 fake1.1
597 select1.1.1 select 1.1.2 select1.2.1 select2.1.1
598 |^
599 ||
600 V|
601 unit2.1.1.1
602 select2.1.1.1.1
603
604
605 relation in main unit will be following:
606 (bigger picture for:
607 main unit
608 fake0
609 select1 select2 select3
610 in the above picture)
611
612 main unit
613 |^^^^|fake_select_lex
614 |||||+--------------------------------------------+
615 ||||+--------------------------------------------+|
616 |||+------------------------------+ ||
617 ||+--------------+ | ||
618 slave||master | | ||
619 V| neighbor | neighbor | master|V
620 select1<========>select2<========>select3 fake0
621
622 list of all select_lex will be following (as it will be constructed by
623 parser):
624
625 select1->select2->select3->select2.1.1->select 2.1.2->select2.1.1.1.1-+
626 |
627 +---------------------------------------------------------------------+
628 |
629 +->select1.1.1->select1.1.2
630
631*/
632
633/*
634 Base class for st_select_lex (SELECT_LEX) &
635 st_select_lex_unit (SELECT_LEX_UNIT)
636*/
637struct LEX;
638class st_select_lex;
639class st_select_lex_unit;
640
641
642class st_select_lex_node {
643protected:
644 st_select_lex_node *next, **prev, /* neighbor list */
645 *master, *slave, /* vertical links */
646 *link_next, **link_prev; /* list of whole SELECT_LEX */
647
648 void init_query_common();
649public:
650
651 ulonglong options;
652
653 /*
654 In sql_cache we store SQL_CACHE flag as specified by user to be
655 able to restore SELECT statement from internal structures.
656 */
657 enum e_sql_cache { SQL_CACHE_UNSPECIFIED, SQL_NO_CACHE, SQL_CACHE };
658 e_sql_cache sql_cache;
659
660 /*
661 result of this query can't be cached, bit field, can be :
662 UNCACHEABLE_DEPENDENT_GENERATED
663 UNCACHEABLE_DEPENDENT_INJECTED
664 UNCACHEABLE_RAND
665 UNCACHEABLE_SIDEEFFECT
666 UNCACHEABLE_EXPLAIN
667 UNCACHEABLE_PREPARE
668 */
669 uint8 uncacheable;
670 enum sub_select_type linkage;
671 bool is_linkage_set() const
672 {
673 return linkage == UNION_TYPE || linkage == INTERSECT_TYPE || linkage == EXCEPT_TYPE;
674 }
675 bool no_table_names_allowed; /* used for global order by */
676
677 static void *operator new(size_t size, MEM_ROOT *mem_root) throw ()
678 { return (void*) alloc_root(mem_root, (uint) size); }
679 static void operator delete(void *ptr,size_t size) { TRASH_FREE(ptr, size); }
680 static void operator delete(void *ptr, MEM_ROOT *mem_root) {}
681
682 // Ensures that at least all members used during cleanup() are initialized.
683 st_select_lex_node()
684 : next(NULL), prev(NULL),
685 master(NULL), slave(NULL),
686 link_next(NULL), link_prev(NULL),
687 linkage(UNSPECIFIED_TYPE)
688 {
689 }
690
691 inline st_select_lex_node* get_master() { return master; }
692 void include_down(st_select_lex_node *upper);
693 void add_slave(st_select_lex_node *slave_arg);
694 void include_neighbour(st_select_lex_node *before);
695 void include_standalone(st_select_lex_node *sel, st_select_lex_node **ref);
696 void include_global(st_select_lex_node **plink);
697 void exclude();
698 void exclude_from_tree();
699
700 void set_slave(st_select_lex_node *slave_arg) { slave= slave_arg; }
701 void move_node(st_select_lex_node *where_to_move)
702 {
703 if (where_to_move == this)
704 return;
705 if (next)
706 next->prev= prev;
707 *prev= next;
708 *where_to_move->prev= this;
709 next= where_to_move;
710 }
711 st_select_lex_node *insert_chain_before(st_select_lex_node **ptr_pos_to_insert,
712 st_select_lex_node *end_chain_node);
713 void move_as_slave(st_select_lex_node *new_master);
714 friend class st_select_lex_unit;
715 friend bool mysql_new_select(LEX *lex, bool move_down, SELECT_LEX *sel);
716 friend bool mysql_make_view(THD *thd, TABLE_SHARE *share, TABLE_LIST *table,
717 bool open_view_no_parse);
718 friend bool mysql_derived_prepare(THD *thd, LEX *lex,
719 TABLE_LIST *orig_table_list);
720 friend bool mysql_derived_merge(THD *thd, LEX *lex,
721 TABLE_LIST *orig_table_list);
722 friend bool TABLE_LIST::init_derived(THD *thd, bool init_view);
723private:
724 void fast_exclude();
725};
726typedef class st_select_lex_node SELECT_LEX_NODE;
727
728/*
729 SELECT_LEX_UNIT - unit of selects (UNION, INTERSECT, ...) group
730 SELECT_LEXs
731*/
732class THD;
733class select_result;
734class JOIN;
735class select_unit;
736class Procedure;
737class Explain_query;
738
739void delete_explain_query(LEX *lex);
740void create_explain_query(LEX *lex, MEM_ROOT *mem_root);
741void create_explain_query_if_not_exists(LEX *lex, MEM_ROOT *mem_root);
742bool print_explain_for_slow_log(LEX *lex, THD *thd, String *str);
743
744class st_select_lex_unit: public st_select_lex_node {
745protected:
746 TABLE_LIST result_table_list;
747 select_unit *union_result;
748 ulonglong found_rows_for_union;
749 bool saved_error;
750
751 bool prepare_join(THD *thd, SELECT_LEX *sl, select_result *result,
752 ulong additional_options,
753 bool is_union_select);
754 bool join_union_item_types(THD *thd, List<Item> &types, uint count);
755 bool join_union_type_handlers(THD *thd,
756 class Type_holder *holders, uint count);
757 bool join_union_type_attributes(THD *thd,
758 class Type_holder *holders, uint count);
759public:
760 // Ensures that at least all members used during cleanup() are initialized.
761 st_select_lex_unit()
762 : union_result(NULL), table(NULL), result(NULL),
763 cleaned(false),
764 fake_select_lex(NULL)
765 {
766 }
767
768
769 TABLE *table; /* temporary table using for appending UNION results */
770 select_result *result;
771 bool prepared, // prepare phase already performed for UNION (unit)
772 optimized, // optimize phase already performed for UNION (unit)
773 optimized_2,
774 executed, // already executed
775 cleaned;
776
777 bool optimize_started;
778
779 // list of fields which points to temporary table for union
780 List<Item> item_list;
781 /*
782 list of types of items inside union (used for union & derived tables)
783
784 Item_type_holders from which this list consist may have pointers to Field,
785 pointers is valid only after preparing SELECTS of this unit and before
786 any SELECT of this unit execution
787 */
788 List<Item> types;
789 /**
790 There is INTERSECT and it is item used in creating temporary
791 table for it
792 */
793 Item_int *intersect_mark;
794 /**
795 Pointer to 'last' select, or pointer to select where we stored
796 global parameters for union.
797
798 If this is a union of multiple selects, the parser puts the global
799 parameters in fake_select_lex. If the union doesn't use a
800 temporary table, st_select_lex_unit::prepare() nulls out
801 fake_select_lex, but saves a copy in saved_fake_select_lex in
802 order to preserve the global parameters.
803
804 If it is not a union, first_select() is the last select.
805
806 @return select containing the global parameters
807 */
808 inline st_select_lex *global_parameters()
809 {
810 if (fake_select_lex != NULL)
811 return fake_select_lex;
812 else if (saved_fake_select_lex != NULL)
813 return saved_fake_select_lex;
814 return first_select();
815 };
816 //node on which we should return current_select pointer after parsing subquery
817 st_select_lex *return_to;
818 /* LIMIT clause runtime counters */
819 ha_rows select_limit_cnt, offset_limit_cnt;
820 /* not NULL if unit used in subselect, point to subselect item */
821 Item_subselect *item;
822 /*
823 TABLE_LIST representing this union in the embedding select. Used for
824 derived tables/views handling.
825 */
826 TABLE_LIST *derived;
827 bool is_view;
828 /* With clause attached to this unit (if any) */
829 With_clause *with_clause;
830 /* With element where this unit is used as the specification (if any) */
831 With_element *with_element;
832 /* thread handler */
833 THD *thd;
834 /*
835 SELECT_LEX for hidden SELECT in union which process global
836 ORDER BY and LIMIT
837 */
838 st_select_lex *fake_select_lex;
839 /**
840 SELECT_LEX that stores LIMIT and OFFSET for UNION ALL when noq
841 fake_select_lex is used.
842 */
843 st_select_lex *saved_fake_select_lex;
844
845 st_select_lex *union_distinct; /* pointer to the last UNION DISTINCT */
846 bool describe; /* union exec() called for EXPLAIN */
847 Procedure *last_procedure; /* Pointer to procedure, if such exists */
848
849 bool columns_are_renamed;
850
851 void init_query();
852 st_select_lex* outer_select();
853 st_select_lex* first_select()
854 {
855 return reinterpret_cast<st_select_lex*>(slave);
856 }
857 inline void set_with_clause(With_clause *with_cl);
858 st_select_lex_unit* next_unit()
859 {
860 return reinterpret_cast<st_select_lex_unit*>(next);
861 }
862 st_select_lex* return_after_parsing() { return return_to; }
863 void exclude_level();
864 // void exclude_tree(); // it is not used for long time
865 bool is_excluded() { return prev == NULL; }
866
867 /* UNION methods */
868 bool prepare(TABLE_LIST *derived_arg, select_result *sel_result,
869 ulong additional_options);
870 bool optimize();
871 bool exec();
872 bool exec_recursive();
873 bool cleanup();
874 inline void unclean() { cleaned= 0; }
875 void reinit_exec_mechanism();
876
877 void print(String *str, enum_query_type query_type);
878
879 bool add_fake_select_lex(THD *thd);
880 void init_prepare_fake_select_lex(THD *thd, bool first_execution);
881 inline bool is_prepared() { return prepared; }
882 bool change_result(select_result_interceptor *result,
883 select_result_interceptor *old_result);
884 void set_limit(st_select_lex *values);
885 void set_thd(THD *thd_arg) { thd= thd_arg; }
886 inline bool is_unit_op ();
887 bool union_needs_tmp_table();
888
889 void set_unique_exclude();
890
891 friend struct LEX;
892 friend int subselect_union_engine::exec();
893
894 List<Item> *get_column_types(bool for_cursor);
895
896 select_unit *get_union_result() { return union_result; }
897 int save_union_explain(Explain_query *output);
898 int save_union_explain_part2(Explain_query *output);
899 unit_common_op common_op();
900};
901
902typedef class st_select_lex_unit SELECT_LEX_UNIT;
903typedef Bounds_checked_array<Item*> Ref_ptr_array;
904
905
906/*
907 Structure which consists of the field and the item which
908 produces this field.
909*/
910
911class Grouping_tmp_field :public Sql_alloc
912{
913public:
914 Field *tmp_field;
915 Item *producing_item;
916 Grouping_tmp_field(Field *fld, Item *item)
917 :tmp_field(fld), producing_item(item) {}
918};
919
920/*
921 SELECT_LEX - store information of parsed SELECT statment
922*/
923class st_select_lex: public st_select_lex_node
924{
925public:
926 Name_resolution_context context;
927 LEX_CSTRING db;
928 Item *where, *having; /* WHERE & HAVING clauses */
929 Item *prep_where; /* saved WHERE clause for prepared statement processing */
930 Item *prep_having;/* saved HAVING clause for prepared statement processing */
931 Item *cond_pushed_into_where; /* condition pushed into the select's WHERE */
932 Item *cond_pushed_into_having; /* condition pushed into the select's HAVING */
933 /* Saved values of the WHERE and HAVING clauses*/
934 Item::cond_result cond_value, having_value;
935 /*
936 Point to the LEX in which it was created, used in view subquery detection.
937
938 TODO: make also st_select_lex::parent_stmt_lex (see LEX::stmt_lex)
939 and use st_select_lex::parent_lex & st_select_lex::parent_stmt_lex
940 instead of global (from THD) references where it is possible.
941 */
942 LEX *parent_lex;
943 enum olap_type olap;
944 /* FROM clause - points to the beginning of the TABLE_LIST::next_local list. */
945 SQL_I_List<TABLE_LIST> table_list;
946
947 /*
948 GROUP BY clause.
949 This list may be mutated during optimization (by remove_const()),
950 so for prepared statements, we keep a copy of the ORDER.next pointers in
951 group_list_ptrs, and re-establish the original list before each execution.
952 */
953 SQL_I_List<ORDER> group_list;
954 Group_list_ptrs *group_list_ptrs;
955
956 List<Item> item_list; /* list of fields & expressions */
957 List<Item> pre_fix; /* above list before fix_fields */
958 bool is_item_list_lookup;
959 /*
960 Usualy it is pointer to ftfunc_list_alloc, but in union used to create fake
961 select_lex for calling mysql_select under results of union
962 */
963 List<Item_func_match> *ftfunc_list;
964 List<Item_func_match> ftfunc_list_alloc;
965 /*
966 The list of items to which MIN/MAX optimizations of opt_sum_query()
967 have been applied. Used to rollback those optimizations if it's needed.
968 */
969 List<Item_sum> min_max_opt_list;
970 JOIN *join; /* after JOIN::prepare it is pointer to corresponding JOIN */
971 List<TABLE_LIST> top_join_list; /* join list of the top level */
972 List<TABLE_LIST> *join_list; /* list for the currently parsed join */
973 TABLE_LIST *embedding; /* table embedding to the above list */
974 List<TABLE_LIST> sj_nests; /* Semi-join nests within this join */
975 /*
976 Beginning of the list of leaves in a FROM clause, where the leaves
977 inlcude all base tables including view tables. The tables are connected
978 by TABLE_LIST::next_leaf, so leaf_tables points to the left-most leaf.
979
980 List of all base tables local to a subquery including all view
981 tables. Unlike 'next_local', this in this list views are *not*
982 leaves. Created in setup_tables() -> make_leaves_list().
983 */
984 /*
985 Subqueries that will need to be converted to semi-join nests, including
986 those converted to jtbm nests. The list is emptied when conversion is done.
987 */
988 List<Item_in_subselect> sj_subselects;
989 /*
990 List of IN-predicates in this st_select_lex that
991 can be transformed into IN-subselect defined with TVC.
992 */
993 List<Item_func_in> in_funcs;
994 /*
995 Number of current derived table made with TVC during the
996 transformation of IN-predicate into IN-subquery for this
997 st_select_lex.
998 */
999 uint curr_tvc_name;
1000
1001 /*
1002 Needed to correctly generate 'PRIMARY' or 'SIMPLE' for select_type column
1003 of EXPLAIN
1004 */
1005 bool have_merged_subqueries;
1006
1007 List<TABLE_LIST> leaf_tables;
1008 List<TABLE_LIST> leaf_tables_exec;
1009 List<TABLE_LIST> leaf_tables_prep;
1010 enum leaf_list_state {UNINIT, READY, SAVED};
1011 enum leaf_list_state prep_leaf_list_state;
1012 uint insert_tables;
1013 st_select_lex *merged_into; /* select which this select is merged into */
1014 /* (not 0 only for views/derived tables) */
1015
1016 const char *type; /* type of select for EXPLAIN */
1017
1018 SQL_I_List<ORDER> order_list; /* ORDER clause */
1019 SQL_I_List<ORDER> gorder_list;
1020 Item *select_limit, *offset_limit; /* LIMIT clause parameters */
1021
1022 /// Array of pointers to top elements of all_fields list
1023 Ref_ptr_array ref_pointer_array;
1024
1025 /*
1026 number of items in select_list and HAVING clause used to get number
1027 bigger then can be number of entries that will be added to all item
1028 list during split_sum_func
1029 */
1030 uint select_n_having_items;
1031 uint cond_count; /* number of sargable Items in where/having/on */
1032 uint between_count; /* number of between predicates in where/having/on */
1033 uint max_equal_elems; /* maximal number of elements in multiple equalities */
1034 /*
1035 Number of fields used in select list or where clause of current select
1036 and all inner subselects.
1037 */
1038 uint select_n_where_fields;
1039 /* reserved for exists 2 in */
1040 uint select_n_reserved;
1041 /*
1042 it counts the number of bit fields in the SELECT list. These are used when DISTINCT is
1043 converted to a GROUP BY involving BIT fields.
1044 */
1045 uint hidden_bit_fields;
1046 enum_parsing_place parsing_place; /* where we are parsing expression */
1047 enum_parsing_place context_analysis_place; /* where we are in prepare */
1048 bool with_sum_func; /* sum function indicator */
1049
1050 ulong table_join_options;
1051 uint in_sum_expr;
1052 uint select_number; /* number of select (used for EXPLAIN) */
1053
1054 /*
1055 nest_levels are local to the query or VIEW,
1056 and that view merge procedure does not re-calculate them.
1057 So we also have to remember unit against which we count levels.
1058 */
1059 SELECT_LEX_UNIT *nest_level_base;
1060 int nest_level; /* nesting level of select */
1061 Item_sum *inner_sum_func_list; /* list of sum func in nested selects */
1062 uint with_wild; /* item list contain '*' */
1063 bool braces; /* SELECT ... UNION (SELECT ... ) <- this braces */
1064 bool automatic_brackets; /* dummy select for INTERSECT precedence */
1065 /* TRUE when having fix field called in processing of this SELECT */
1066 bool having_fix_field;
1067 /* List of references to fields referenced from inner selects */
1068 List<Item_outer_ref> inner_refs_list;
1069 /* Number of Item_sum-derived objects in this SELECT */
1070 uint n_sum_items;
1071 /* Number of Item_sum-derived objects in children and descendant SELECTs */
1072 uint n_child_sum_items;
1073
1074 /* explicit LIMIT clause was used */
1075 bool explicit_limit;
1076 /*
1077 This array is used to note whether we have any candidates for
1078 expression caching in the corresponding clauses
1079 */
1080 bool expr_cache_may_be_used[PARSING_PLACE_SIZE];
1081 /*
1082 there are subquery in HAVING clause => we can't close tables before
1083 query processing end even if we use temporary table
1084 */
1085 bool subquery_in_having;
1086 /* TRUE <=> this SELECT is correlated w.r.t. some ancestor select */
1087 bool with_all_modifier; /* used for selects in union */
1088 bool is_correlated;
1089 /*
1090 This variable is required to ensure proper work of subqueries and
1091 stored procedures. Generally, one should use the states of
1092 Query_arena to determine if it's a statement prepare or first
1093 execution of a stored procedure. However, in case when there was an
1094 error during the first execution of a stored procedure, the SP body
1095 is not expelled from the SP cache. Therefore, a deeply nested
1096 subquery might be left unoptimized. So we need this per-subquery
1097 variable to inidicate the optimization/execution state of every
1098 subquery. Prepared statements work OK in that regard, as in
1099 case of an error during prepare the PS is not created.
1100 */
1101 bool first_execution;
1102 bool first_natural_join_processing;
1103 bool first_cond_optimization;
1104 /* do not wrap view fields with Item_ref */
1105 bool no_wrap_view_item;
1106 /* exclude this select from check of unique_table() */
1107 bool exclude_from_table_unique_test;
1108 /* index in the select list of the expression currently being fixed */
1109 int cur_pos_in_select_list;
1110
1111 List<udf_func> udf_list; /* udf function calls stack */
1112
1113 /*
1114 This is a copy of the original JOIN USING list that comes from
1115 the parser. The parser :
1116 1. Sets the natural_join of the second TABLE_LIST in the join
1117 and the st_select_lex::prev_join_using.
1118 2. Makes a parent TABLE_LIST and sets its is_natural_join/
1119 join_using_fields members.
1120 3. Uses the wrapper TABLE_LIST as a table in the upper level.
1121 We cannot assign directly to join_using_fields in the parser because
1122 at stage (1.) the parent TABLE_LIST is not constructed yet and
1123 the assignment will override the JOIN USING fields of the lower level
1124 joins on the right.
1125 */
1126 List<String> *prev_join_using;
1127
1128 /**
1129 The set of those tables whose fields are referenced in the select list of
1130 this select level.
1131 */
1132 table_map select_list_tables;
1133
1134 /* namp of nesting SELECT visibility (for aggregate functions check) */
1135 nesting_map name_visibility_map;
1136
1137 table_map with_dep;
1138 List<Grouping_tmp_field> grouping_tmp_fields;
1139
1140 /* it is for correct printing SELECT options */
1141 thr_lock_type lock_type;
1142
1143 table_value_constr *tvc;
1144 bool in_tvc;
1145
1146 /** System Versioning */
1147public:
1148 uint versioned_tables;
1149 int vers_setup_conds(THD *thd, TABLE_LIST *tables);
1150 /* push new Item_field into item_list */
1151 bool vers_push_field(THD *thd, TABLE_LIST *table, const LEX_CSTRING field_name);
1152
1153 void init_query();
1154 void init_select();
1155 st_select_lex_unit* master_unit() { return (st_select_lex_unit*) master; }
1156 st_select_lex_unit* first_inner_unit()
1157 {
1158 return (st_select_lex_unit*) slave;
1159 }
1160 st_select_lex* outer_select();
1161 st_select_lex* next_select() { return (st_select_lex*) next; }
1162 st_select_lex* next_select_in_list()
1163 {
1164 return (st_select_lex*) link_next;
1165 }
1166 st_select_lex_node** next_select_in_list_addr()
1167 {
1168 return &link_next;
1169 }
1170 st_select_lex* return_after_parsing()
1171 {
1172 return master_unit()->return_after_parsing();
1173 }
1174 inline bool is_subquery_function() { return master_unit()->item != 0; }
1175
1176 bool mark_as_dependent(THD *thd, st_select_lex *last, Item *dependency);
1177
1178 void set_braces(bool value)
1179 {
1180 braces= value;
1181 }
1182 bool inc_in_sum_expr();
1183 uint get_in_sum_expr();
1184
1185 bool add_item_to_list(THD *thd, Item *item);
1186 bool add_group_to_list(THD *thd, Item *item, bool asc);
1187 bool add_ftfunc_to_list(THD *thd, Item_func_match *func);
1188 bool add_order_to_list(THD *thd, Item *item, bool asc);
1189 bool add_gorder_to_list(THD *thd, Item *item, bool asc);
1190 TABLE_LIST* add_table_to_list(THD *thd, Table_ident *table,
1191 LEX_CSTRING *alias,
1192 ulong table_options,
1193 thr_lock_type flags= TL_UNLOCK,
1194 enum_mdl_type mdl_type= MDL_SHARED_READ,
1195 List<Index_hint> *hints= 0,
1196 List<String> *partition_names= 0,
1197 LEX_STRING *option= 0);
1198 TABLE_LIST* get_table_list();
1199 bool init_nested_join(THD *thd);
1200 TABLE_LIST *end_nested_join(THD *thd);
1201 TABLE_LIST *nest_last_join(THD *thd);
1202 void add_joined_table(TABLE_LIST *table);
1203 TABLE_LIST *convert_right_join();
1204 List<Item>* get_item_list();
1205 ulong get_table_join_options();
1206 void set_lock_for_tables(thr_lock_type lock_type);
1207 inline void init_order()
1208 {
1209 order_list.elements= 0;
1210 order_list.first= 0;
1211 order_list.next= &order_list.first;
1212 }
1213 /*
1214 This method created for reiniting LEX in mysql_admin_table() and can be
1215 used only if you are going remove all SELECT_LEX & units except belonger
1216 to LEX (LEX::unit & LEX::select, for other purposes there are
1217 SELECT_LEX_UNIT::exclude_level & SELECT_LEX_UNIT::exclude_tree
1218 */
1219 void cut_subtree() { slave= 0; }
1220 bool test_limit();
1221 /**
1222 Get offset for LIMIT.
1223
1224 Evaluate offset item if necessary.
1225
1226 @return Number of rows to skip.
1227 */
1228 ha_rows get_offset();
1229 /**
1230 Get limit.
1231
1232 Evaluate limit item if necessary.
1233
1234 @return Limit of rows in result.
1235 */
1236 ha_rows get_limit();
1237
1238 friend struct LEX;
1239 st_select_lex() : group_list_ptrs(NULL), braces(0), automatic_brackets(0),
1240 n_sum_items(0), n_child_sum_items(0)
1241 {}
1242 void make_empty_select()
1243 {
1244 init_query();
1245 init_select();
1246 }
1247 bool setup_ref_array(THD *thd, uint order_group_num);
1248 void print(THD *thd, String *str, enum_query_type query_type);
1249 static void print_order(String *str,
1250 ORDER *order,
1251 enum_query_type query_type);
1252 void print_limit(THD *thd, String *str, enum_query_type query_type);
1253 void fix_prepare_information(THD *thd, Item **conds, Item **having_conds);
1254 /*
1255 Destroy the used execution plan (JOIN) of this subtree (this
1256 SELECT_LEX and all nested SELECT_LEXes and SELECT_LEX_UNITs).
1257 */
1258 bool cleanup();
1259 /*
1260 Recursively cleanup the join of this select lex and of all nested
1261 select lexes.
1262 */
1263 void cleanup_all_joins(bool full);
1264
1265 void set_index_hint_type(enum index_hint_type type, index_clause_map clause);
1266
1267 /*
1268 Add a index hint to the tagged list of hints. The type and clause of the
1269 hint will be the current ones (set by set_index_hint())
1270 */
1271 bool add_index_hint (THD *thd, const char *str, size_t length);
1272
1273 /* make a list to hold index hints */
1274 void alloc_index_hints (THD *thd);
1275 /* read and clear the index hints */
1276 List<Index_hint>* pop_index_hints(void)
1277 {
1278 List<Index_hint> *hints= index_hints;
1279 index_hints= NULL;
1280 return hints;
1281 }
1282
1283 void clear_index_hints(void) { index_hints= NULL; }
1284 bool is_part_of_union() { return master_unit()->is_unit_op(); }
1285 bool is_top_level_node()
1286 {
1287 return (select_number == 1) && !is_part_of_union();
1288 }
1289 bool optimize_unflattened_subqueries(bool const_only);
1290 /* Set the EXPLAIN type for this subquery. */
1291 void set_explain_type(bool on_the_fly);
1292 bool handle_derived(LEX *lex, uint phases);
1293 void append_table_to_list(TABLE_LIST *TABLE_LIST::*link, TABLE_LIST *table);
1294 bool get_free_table_map(table_map *map, uint *tablenr);
1295 void replace_leaf_table(TABLE_LIST *table, List<TABLE_LIST> &tbl_list);
1296 void remap_tables(TABLE_LIST *derived, table_map map,
1297 uint tablenr, st_select_lex *parent_lex);
1298 bool merge_subquery(THD *thd, TABLE_LIST *derived, st_select_lex *subq_lex,
1299 uint tablenr, table_map map);
1300 inline bool is_mergeable()
1301 {
1302 return (next_select() == 0 && group_list.elements == 0 &&
1303 having == 0 && with_sum_func == 0 &&
1304 table_list.elements >= 1 && !(options & SELECT_DISTINCT) &&
1305 select_limit == 0);
1306 }
1307 void mark_as_belong_to_derived(TABLE_LIST *derived);
1308 void increase_derived_records(ha_rows records);
1309 void update_used_tables();
1310 void update_correlated_cache();
1311 void mark_const_derived(bool empty);
1312
1313 bool save_leaf_tables(THD *thd);
1314 bool save_prep_leaf_tables(THD *thd);
1315
1316 bool is_merged_child_of(st_select_lex *ancestor);
1317
1318 /*
1319 For MODE_ONLY_FULL_GROUP_BY we need to maintain two flags:
1320 - Non-aggregated fields are used in this select.
1321 - Aggregate functions are used in this select.
1322 In MODE_ONLY_FULL_GROUP_BY only one of these may be true.
1323 */
1324 bool non_agg_field_used() const { return m_non_agg_field_used; }
1325 bool agg_func_used() const { return m_agg_func_used; }
1326 bool custom_agg_func_used() const { return m_custom_agg_func_used; }
1327
1328 void set_non_agg_field_used(bool val) { m_non_agg_field_used= val; }
1329 void set_agg_func_used(bool val) { m_agg_func_used= val; }
1330 void set_custom_agg_func_used(bool val) { m_custom_agg_func_used= val; }
1331 inline void set_with_clause(With_clause *with_clause);
1332 With_clause *get_with_clause()
1333 {
1334 return master_unit()->with_clause;
1335 }
1336 With_element *get_with_element()
1337 {
1338 return master_unit()->with_element;
1339 }
1340 With_element *find_table_def_in_with_clauses(TABLE_LIST *table);
1341 bool check_unrestricted_recursive(bool only_standard_compliant);
1342 bool check_subqueries_with_recursive_references();
1343 void collect_grouping_fields(THD *thd, ORDER *grouping_list);
1344 void check_cond_extraction_for_grouping_fields(Item *cond,
1345 TABLE_LIST *derived);
1346 Item *build_cond_for_grouping_fields(THD *thd, Item *cond,
1347 bool no_to_clones);
1348
1349 List<Window_spec> window_specs;
1350 void prepare_add_window_spec(THD *thd);
1351 bool add_window_def(THD *thd, LEX_CSTRING *win_name, LEX_CSTRING *win_ref,
1352 SQL_I_List<ORDER> win_partition_list,
1353 SQL_I_List<ORDER> win_order_list,
1354 Window_frame *win_frame);
1355 bool add_window_spec(THD *thd, LEX_CSTRING *win_ref,
1356 SQL_I_List<ORDER> win_partition_list,
1357 SQL_I_List<ORDER> win_order_list,
1358 Window_frame *win_frame);
1359 List<Item_window_func> window_funcs;
1360 bool add_window_func(Item_window_func *win_func)
1361 {
1362 return window_funcs.push_back(win_func);
1363 }
1364
1365 bool have_window_funcs() const { return (window_funcs.elements !=0); }
1366 ORDER *find_common_window_func_partition_fields(THD *thd);
1367
1368 bool cond_pushdown_is_allowed() const
1369 { return !olap && !explicit_limit && !tvc; }
1370
1371private:
1372 bool m_non_agg_field_used;
1373 bool m_agg_func_used;
1374 bool m_custom_agg_func_used;
1375
1376 /* current index hint kind. used in filling up index_hints */
1377 enum index_hint_type current_index_hint_type;
1378 index_clause_map current_index_hint_clause;
1379 /* a list of USE/FORCE/IGNORE INDEX */
1380 List<Index_hint> *index_hints;
1381
1382public:
1383 inline void add_where_field(st_select_lex *sel)
1384 {
1385 DBUG_ASSERT(this != sel);
1386 select_n_where_fields+= sel->select_n_where_fields;
1387 }
1388};
1389typedef class st_select_lex SELECT_LEX;
1390
1391inline bool st_select_lex_unit::is_unit_op ()
1392{
1393 if (!first_select()->next_select())
1394 {
1395 if (first_select()->tvc)
1396 return 1;
1397 else
1398 return 0;
1399 }
1400
1401 enum sub_select_type linkage= first_select()->next_select()->linkage;
1402 return linkage == UNION_TYPE || linkage == INTERSECT_TYPE ||
1403 linkage == EXCEPT_TYPE;
1404}
1405
1406
1407struct st_sp_chistics
1408{
1409 LEX_CSTRING comment;
1410 enum enum_sp_suid_behaviour suid;
1411 bool detistic;
1412 enum enum_sp_data_access daccess;
1413 enum enum_sp_aggregate_type agg_type;
1414 void init() { bzero(this, sizeof(*this)); }
1415 void set(const st_sp_chistics &other) { *this= other; }
1416 bool read_from_mysql_proc_row(THD *thd, TABLE *table);
1417};
1418
1419
1420class Sp_chistics: public st_sp_chistics
1421{
1422public:
1423 Sp_chistics() { init(); }
1424};
1425
1426
1427struct st_trg_chistics: public st_trg_execution_order
1428{
1429 enum trg_action_time_type action_time;
1430 enum trg_event_type event;
1431
1432 const char *ordering_clause_begin;
1433 const char *ordering_clause_end;
1434
1435};
1436
1437enum xa_option_words {XA_NONE, XA_JOIN, XA_RESUME, XA_ONE_PHASE,
1438 XA_SUSPEND, XA_FOR_MIGRATE};
1439
1440class Sroutine_hash_entry;
1441
1442/*
1443 Class representing list of all tables used by statement and other
1444 information which is necessary for opening and locking its tables,
1445 like SQL command for this statement.
1446
1447 Also contains information about stored functions used by statement
1448 since during its execution we may have to add all tables used by its
1449 stored functions/triggers to this list in order to pre-open and lock
1450 them.
1451
1452 Also used by LEX::reset_n_backup/restore_backup_query_tables_list()
1453 methods to save and restore this information.
1454*/
1455
1456class Query_tables_list
1457{
1458public:
1459 /**
1460 SQL command for this statement. Part of this class since the
1461 process of opening and locking tables for the statement needs
1462 this information to determine correct type of lock for some of
1463 the tables.
1464 */
1465 enum_sql_command sql_command;
1466 /* Global list of all tables used by this statement */
1467 TABLE_LIST *query_tables;
1468 /* Pointer to next_global member of last element in the previous list. */
1469 TABLE_LIST **query_tables_last;
1470 /*
1471 If non-0 then indicates that query requires prelocking and points to
1472 next_global member of last own element in query table list (i.e. last
1473 table which was not added to it as part of preparation to prelocking).
1474 0 - indicates that this query does not need prelocking.
1475 */
1476 TABLE_LIST **query_tables_own_last;
1477 /*
1478 Set of stored routines called by statement.
1479 (Note that we use lazy-initialization for this hash).
1480 */
1481 enum { START_SROUTINES_HASH_SIZE= 16 };
1482 HASH sroutines;
1483 /*
1484 List linking elements of 'sroutines' set. Allows you to add new elements
1485 to this set as you iterate through the list of existing elements.
1486 'sroutines_list_own_last' is pointer to ::next member of last element of
1487 this list which represents routine which is explicitly used by query.
1488 'sroutines_list_own_elements' number of explicitly used routines.
1489 We use these two members for restoring of 'sroutines_list' to the state
1490 in which it was right after query parsing.
1491 */
1492 SQL_I_List<Sroutine_hash_entry> sroutines_list;
1493 Sroutine_hash_entry **sroutines_list_own_last;
1494 uint sroutines_list_own_elements;
1495
1496 /**
1497 Locking state of tables in this particular statement.
1498
1499 If we under LOCK TABLES or in prelocked mode we consider tables
1500 for the statement to be "locked" if there was a call to lock_tables()
1501 (which called handler::start_stmt()) for tables of this statement
1502 and there was no matching close_thread_tables() call.
1503
1504 As result this state may differ significantly from one represented
1505 by Open_tables_state::lock/locked_tables_mode more, which are always
1506 "on" under LOCK TABLES or in prelocked mode.
1507 */
1508 enum enum_lock_tables_state {
1509 LTS_NOT_LOCKED = 0,
1510 LTS_LOCKED
1511 };
1512 enum_lock_tables_state lock_tables_state;
1513 bool is_query_tables_locked()
1514 {
1515 return (lock_tables_state == LTS_LOCKED);
1516 }
1517
1518 /**
1519 Number of tables which were open by open_tables() and to be locked
1520 by lock_tables().
1521 Note that we set this member only in some cases, when this value
1522 needs to be passed from open_tables() to lock_tables() which are
1523 separated by some amount of code.
1524 */
1525 uint table_count;
1526
1527 /*
1528 These constructor and destructor serve for creation/destruction
1529 of Query_tables_list instances which are used as backup storage.
1530 */
1531 Query_tables_list() {}
1532 ~Query_tables_list() {}
1533
1534 /* Initializes (or resets) Query_tables_list object for "real" use. */
1535 void reset_query_tables_list(bool init);
1536 void destroy_query_tables_list();
1537 void set_query_tables_list(Query_tables_list *state)
1538 {
1539 *this= *state;
1540 }
1541
1542 /*
1543 Direct addition to the list of query tables.
1544 If you are using this function, you must ensure that the table
1545 object, in particular table->db member, is initialized.
1546 */
1547 void add_to_query_tables(TABLE_LIST *table)
1548 {
1549 *(table->prev_global= query_tables_last)= table;
1550 query_tables_last= &table->next_global;
1551 }
1552 bool requires_prelocking()
1553 {
1554 return MY_TEST(query_tables_own_last);
1555 }
1556 void mark_as_requiring_prelocking(TABLE_LIST **tables_own_last)
1557 {
1558 query_tables_own_last= tables_own_last;
1559 }
1560 /* Return pointer to first not-own table in query-tables or 0 */
1561 TABLE_LIST* first_not_own_table()
1562 {
1563 return ( query_tables_own_last ? *query_tables_own_last : 0);
1564 }
1565 void chop_off_not_own_tables()
1566 {
1567 if (query_tables_own_last)
1568 {
1569 *query_tables_own_last= 0;
1570 query_tables_last= query_tables_own_last;
1571 query_tables_own_last= 0;
1572 }
1573 }
1574
1575 /** Return a pointer to the last element in query table list. */
1576 TABLE_LIST *last_table()
1577 {
1578 /* Don't use offsetof() macro in order to avoid warnings. */
1579 return query_tables ?
1580 (TABLE_LIST*) ((char*) query_tables_last -
1581 ((char*) &(query_tables->next_global) -
1582 (char*) query_tables)) :
1583 0;
1584 }
1585
1586 /**
1587 Enumeration listing of all types of unsafe statement.
1588
1589 @note The order of elements of this enumeration type must
1590 correspond to the order of the elements of the @c explanations
1591 array defined in the body of @c THD::issue_unsafe_warnings.
1592 */
1593 enum enum_binlog_stmt_unsafe {
1594 /**
1595 SELECT..LIMIT is unsafe because the set of rows returned cannot
1596 be predicted.
1597 */
1598 BINLOG_STMT_UNSAFE_LIMIT= 0,
1599 /**
1600 INSERT DELAYED is unsafe because the time when rows are inserted
1601 cannot be predicted.
1602 */
1603 BINLOG_STMT_UNSAFE_INSERT_DELAYED,
1604 /**
1605 Access to log tables is unsafe because slave and master probably
1606 log different things.
1607 */
1608 BINLOG_STMT_UNSAFE_SYSTEM_TABLE,
1609 /**
1610 Inserting into an autoincrement column in a stored routine is unsafe.
1611 Even with just one autoincrement column, if the routine is invoked more than
1612 once slave is not guaranteed to execute the statement graph same way as
1613 the master.
1614 And since it's impossible to estimate how many times a routine can be invoked at
1615 the query pre-execution phase (see lock_tables), the statement is marked
1616 pessimistically unsafe.
1617 */
1618 BINLOG_STMT_UNSAFE_AUTOINC_COLUMNS,
1619 /**
1620 Using a UDF (user-defined function) is unsafe.
1621 */
1622 BINLOG_STMT_UNSAFE_UDF,
1623 /**
1624 Using most system variables is unsafe, because slave may run
1625 with different options than master.
1626 */
1627 BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE,
1628 /**
1629 Using some functions is unsafe (e.g., UUID).
1630 */
1631 BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION,
1632
1633 /**
1634 Mixing transactional and non-transactional statements are unsafe if
1635 non-transactional reads or writes are occur after transactional
1636 reads or writes inside a transaction.
1637 */
1638 BINLOG_STMT_UNSAFE_NONTRANS_AFTER_TRANS,
1639
1640 /**
1641 Mixing self-logging and non-self-logging engines in a statement
1642 is unsafe.
1643 */
1644 BINLOG_STMT_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
1645
1646 /**
1647 Statements that read from both transactional and non-transactional
1648 tables and write to any of them are unsafe.
1649 */
1650 BINLOG_STMT_UNSAFE_MIXED_STATEMENT,
1651
1652 /**
1653 INSERT...IGNORE SELECT is unsafe because which rows are ignored depends
1654 on the order that rows are retrieved by SELECT. This order cannot be
1655 predicted and may differ on master and the slave.
1656 */
1657 BINLOG_STMT_UNSAFE_INSERT_IGNORE_SELECT,
1658
1659 /**
1660 INSERT...SELECT...UPDATE is unsafe because which rows are updated depends
1661 on the order that rows are retrieved by SELECT. This order cannot be
1662 predicted and may differ on master and the slave.
1663 */
1664 BINLOG_STMT_UNSAFE_INSERT_SELECT_UPDATE,
1665
1666 /**
1667 Query that writes to a table with auto_inc column after selecting from
1668 other tables are unsafe as the order in which the rows are retrieved by
1669 select may differ on master and slave.
1670 */
1671 BINLOG_STMT_UNSAFE_WRITE_AUTOINC_SELECT,
1672
1673 /**
1674 INSERT...REPLACE SELECT is unsafe because which rows are replaced depends
1675 on the order that rows are retrieved by SELECT. This order cannot be
1676 predicted and may differ on master and the slave.
1677 */
1678 BINLOG_STMT_UNSAFE_REPLACE_SELECT,
1679
1680 /**
1681 CREATE TABLE... IGNORE... SELECT is unsafe because which rows are ignored
1682 depends on the order that rows are retrieved by SELECT. This order cannot
1683 be predicted and may differ on master and the slave.
1684 */
1685 BINLOG_STMT_UNSAFE_CREATE_IGNORE_SELECT,
1686
1687 /**
1688 CREATE TABLE...REPLACE... SELECT is unsafe because which rows are replaced
1689 depends on the order that rows are retrieved from SELECT. This order
1690 cannot be predicted and may differ on master and the slave
1691 */
1692 BINLOG_STMT_UNSAFE_CREATE_REPLACE_SELECT,
1693
1694 /**
1695 CREATE TABLE...SELECT on a table with auto-increment column is unsafe
1696 because which rows are replaced depends on the order that rows are
1697 retrieved from SELECT. This order cannot be predicted and may differ on
1698 master and the slave
1699 */
1700 BINLOG_STMT_UNSAFE_CREATE_SELECT_AUTOINC,
1701
1702 /**
1703 UPDATE...IGNORE is unsafe because which rows are ignored depends on the
1704 order that rows are updated. This order cannot be predicted and may differ
1705 on master and the slave.
1706 */
1707 BINLOG_STMT_UNSAFE_UPDATE_IGNORE,
1708
1709 /**
1710 INSERT... ON DUPLICATE KEY UPDATE on a table with more than one
1711 UNIQUE KEYS is unsafe.
1712 */
1713 BINLOG_STMT_UNSAFE_INSERT_TWO_KEYS,
1714
1715 /**
1716 INSERT into auto-inc field which is not the first part of composed
1717 primary key.
1718 */
1719 BINLOG_STMT_UNSAFE_AUTOINC_NOT_FIRST,
1720
1721 /* The last element of this enumeration type. */
1722 BINLOG_STMT_UNSAFE_COUNT
1723 };
1724 /**
1725 This has all flags from 0 (inclusive) to BINLOG_STMT_FLAG_COUNT
1726 (exclusive) set.
1727 */
1728 static const uint32 BINLOG_STMT_UNSAFE_ALL_FLAGS=
1729 ((1U << BINLOG_STMT_UNSAFE_COUNT) - 1);
1730
1731 /**
1732 Maps elements of enum_binlog_stmt_unsafe to error codes.
1733 */
1734 static const int binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT];
1735
1736 /**
1737 Determine if this statement is marked as unsafe.
1738
1739 @retval 0 if the statement is not marked as unsafe.
1740 @retval nonzero if the statement is marked as unsafe.
1741 */
1742 inline bool is_stmt_unsafe() const {
1743 return get_stmt_unsafe_flags() != 0;
1744 }
1745
1746 inline bool is_stmt_unsafe(enum_binlog_stmt_unsafe unsafe)
1747 {
1748 return binlog_stmt_flags & (1 << unsafe);
1749 }
1750
1751 /**
1752 Flag the current (top-level) statement as unsafe.
1753 The flag will be reset after the statement has finished.
1754
1755 @param unsafe_type The type of unsafety: one of the @c
1756 BINLOG_STMT_FLAG_UNSAFE_* flags in @c enum_binlog_stmt_flag.
1757 */
1758 inline void set_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type) {
1759 DBUG_ENTER("set_stmt_unsafe");
1760 DBUG_ASSERT(unsafe_type >= 0 && unsafe_type < BINLOG_STMT_UNSAFE_COUNT);
1761 binlog_stmt_flags|= (1U << unsafe_type);
1762 DBUG_VOID_RETURN;
1763 }
1764
1765 /**
1766 Set the bits of binlog_stmt_flags determining the type of
1767 unsafeness of the current statement. No existing bits will be
1768 cleared, but new bits may be set.
1769
1770 @param flags A binary combination of zero or more bits, (1<<flag)
1771 where flag is a member of enum_binlog_stmt_unsafe.
1772 */
1773 inline void set_stmt_unsafe_flags(uint32 flags) {
1774 DBUG_ENTER("set_stmt_unsafe_flags");
1775 DBUG_ASSERT((flags & ~BINLOG_STMT_UNSAFE_ALL_FLAGS) == 0);
1776 binlog_stmt_flags|= flags;
1777 DBUG_VOID_RETURN;
1778 }
1779
1780 /**
1781 Return a binary combination of all unsafe warnings for the
1782 statement. If the statement has been marked as unsafe by the
1783 'flag' member of enum_binlog_stmt_unsafe, then the return value
1784 from this function has bit (1<<flag) set to 1.
1785 */
1786 inline uint32 get_stmt_unsafe_flags() const {
1787 DBUG_ENTER("get_stmt_unsafe_flags");
1788 DBUG_RETURN(binlog_stmt_flags & BINLOG_STMT_UNSAFE_ALL_FLAGS);
1789 }
1790
1791 /**
1792 Mark the current statement as safe; i.e., clear all bits in
1793 binlog_stmt_flags that correspond to elements of
1794 enum_binlog_stmt_unsafe.
1795 */
1796 inline void clear_stmt_unsafe() {
1797 DBUG_ENTER("clear_stmt_unsafe");
1798 binlog_stmt_flags&= ~BINLOG_STMT_UNSAFE_ALL_FLAGS;
1799 DBUG_VOID_RETURN;
1800 }
1801
1802 /**
1803 Determine if this statement is a row injection.
1804
1805 @retval 0 if the statement is not a row injection
1806 @retval nonzero if the statement is a row injection
1807 */
1808 inline bool is_stmt_row_injection() const {
1809 return binlog_stmt_flags &
1810 (1U << (BINLOG_STMT_UNSAFE_COUNT + BINLOG_STMT_TYPE_ROW_INJECTION));
1811 }
1812
1813 /**
1814 Flag the statement as a row injection. A row injection is either
1815 a BINLOG statement, or a row event in the relay log executed by
1816 the slave SQL thread.
1817 */
1818 inline void set_stmt_row_injection() {
1819 DBUG_ENTER("set_stmt_row_injection");
1820 binlog_stmt_flags|=
1821 (1U << (BINLOG_STMT_UNSAFE_COUNT + BINLOG_STMT_TYPE_ROW_INJECTION));
1822 DBUG_VOID_RETURN;
1823 }
1824
1825 enum enum_stmt_accessed_table
1826 {
1827 /*
1828 If a transactional table is about to be read. Note that
1829 a write implies a read.
1830 */
1831 STMT_READS_TRANS_TABLE= 0,
1832 /*
1833 If a non-transactional table is about to be read. Note that
1834 a write implies a read.
1835 */
1836 STMT_READS_NON_TRANS_TABLE,
1837 /*
1838 If a temporary transactional table is about to be read. Note
1839 that a write implies a read.
1840 */
1841 STMT_READS_TEMP_TRANS_TABLE,
1842 /*
1843 If a temporary non-transactional table is about to be read. Note
1844 that a write implies a read.
1845 */
1846 STMT_READS_TEMP_NON_TRANS_TABLE,
1847 /*
1848 If a transactional table is about to be updated.
1849 */
1850 STMT_WRITES_TRANS_TABLE,
1851 /*
1852 If a non-transactional table is about to be updated.
1853 */
1854 STMT_WRITES_NON_TRANS_TABLE,
1855 /*
1856 If a temporary transactional table is about to be updated.
1857 */
1858 STMT_WRITES_TEMP_TRANS_TABLE,
1859 /*
1860 If a temporary non-transactional table is about to be updated.
1861 */
1862 STMT_WRITES_TEMP_NON_TRANS_TABLE,
1863 /*
1864 The last element of the enumeration. Please, if necessary add
1865 anything before this.
1866 */
1867 STMT_ACCESS_TABLE_COUNT
1868 };
1869
1870#ifndef DBUG_OFF
1871 static inline const char *stmt_accessed_table_string(enum_stmt_accessed_table accessed_table)
1872 {
1873 switch (accessed_table)
1874 {
1875 case STMT_READS_TRANS_TABLE:
1876 return "STMT_READS_TRANS_TABLE";
1877 break;
1878 case STMT_READS_NON_TRANS_TABLE:
1879 return "STMT_READS_NON_TRANS_TABLE";
1880 break;
1881 case STMT_READS_TEMP_TRANS_TABLE:
1882 return "STMT_READS_TEMP_TRANS_TABLE";
1883 break;
1884 case STMT_READS_TEMP_NON_TRANS_TABLE:
1885 return "STMT_READS_TEMP_NON_TRANS_TABLE";
1886 break;
1887 case STMT_WRITES_TRANS_TABLE:
1888 return "STMT_WRITES_TRANS_TABLE";
1889 break;
1890 case STMT_WRITES_NON_TRANS_TABLE:
1891 return "STMT_WRITES_NON_TRANS_TABLE";
1892 break;
1893 case STMT_WRITES_TEMP_TRANS_TABLE:
1894 return "STMT_WRITES_TEMP_TRANS_TABLE";
1895 break;
1896 case STMT_WRITES_TEMP_NON_TRANS_TABLE:
1897 return "STMT_WRITES_TEMP_NON_TRANS_TABLE";
1898 break;
1899 case STMT_ACCESS_TABLE_COUNT:
1900 default:
1901 DBUG_ASSERT(0);
1902 break;
1903 }
1904 MY_ASSERT_UNREACHABLE();
1905 return "";
1906 }
1907#endif /* DBUG */
1908
1909 #define BINLOG_DIRECT_ON 0xF0 /* unsafe when
1910 --binlog-direct-non-trans-updates
1911 is ON */
1912
1913 #define BINLOG_DIRECT_OFF 0xF /* unsafe when
1914 --binlog-direct-non-trans-updates
1915 is OFF */
1916
1917 #define TRX_CACHE_EMPTY 0x33 /* unsafe when trx-cache is empty */
1918
1919 #define TRX_CACHE_NOT_EMPTY 0xCC /* unsafe when trx-cache is not empty */
1920
1921 #define IL_LT_REPEATABLE 0xAA /* unsafe when < ISO_REPEATABLE_READ */
1922
1923 #define IL_GTE_REPEATABLE 0x55 /* unsafe when >= ISO_REPEATABLE_READ */
1924
1925 /**
1926 Sets the type of table that is about to be accessed while executing a
1927 statement.
1928
1929 @param accessed_table Enumeration type that defines the type of table,
1930 e.g. temporary, transactional, non-transactional.
1931 */
1932 inline void set_stmt_accessed_table(enum_stmt_accessed_table accessed_table)
1933 {
1934 DBUG_ENTER("LEX::set_stmt_accessed_table");
1935
1936 DBUG_ASSERT(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT);
1937 stmt_accessed_table_flag |= (1U << accessed_table);
1938
1939 DBUG_VOID_RETURN;
1940 }
1941
1942 /**
1943 Checks if a type of table is about to be accessed while executing a
1944 statement.
1945
1946 @param accessed_table Enumeration type that defines the type of table,
1947 e.g. temporary, transactional, non-transactional.
1948
1949 @return
1950 @retval TRUE if the type of the table is about to be accessed
1951 @retval FALSE otherwise
1952 */
1953 inline bool stmt_accessed_table(enum_stmt_accessed_table accessed_table)
1954 {
1955 DBUG_ENTER("LEX::stmt_accessed_table");
1956
1957 DBUG_ASSERT(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT);
1958
1959 DBUG_RETURN((stmt_accessed_table_flag & (1U << accessed_table)) != 0);
1960 }
1961
1962 /**
1963 Checks if a temporary non-transactional table is about to be accessed
1964 while executing a statement.
1965
1966 @return
1967 @retval TRUE if a temporary non-transactional table is about to be
1968 accessed
1969 @retval FALSE otherwise
1970 */
1971 inline bool stmt_accessed_non_trans_temp_table()
1972 {
1973 DBUG_ENTER("THD::stmt_accessed_non_trans_temp_table");
1974
1975 DBUG_RETURN((stmt_accessed_table_flag &
1976 ((1U << STMT_READS_TEMP_NON_TRANS_TABLE) |
1977 (1U << STMT_WRITES_TEMP_NON_TRANS_TABLE))) != 0);
1978 }
1979
1980 /*
1981 Checks if a mixed statement is unsafe.
1982
1983
1984 @param in_multi_stmt_transaction_mode defines if there is an on-going
1985 multi-transactional statement.
1986 @param binlog_direct defines if --binlog-direct-non-trans-updates is
1987 active.
1988 @param trx_cache_is_not_empty defines if the trx-cache is empty or not.
1989 @param trx_isolation defines the isolation level.
1990
1991 @return
1992 @retval TRUE if the mixed statement is unsafe
1993 @retval FALSE otherwise
1994 */
1995 inline bool is_mixed_stmt_unsafe(bool in_multi_stmt_transaction_mode,
1996 bool binlog_direct,
1997 bool trx_cache_is_not_empty,
1998 uint tx_isolation)
1999 {
2000 bool unsafe= FALSE;
2001
2002 if (in_multi_stmt_transaction_mode)
2003 {
2004 uint condition=
2005 (binlog_direct ? BINLOG_DIRECT_ON : BINLOG_DIRECT_OFF) &
2006 (trx_cache_is_not_empty ? TRX_CACHE_NOT_EMPTY : TRX_CACHE_EMPTY) &
2007 (tx_isolation >= ISO_REPEATABLE_READ ? IL_GTE_REPEATABLE : IL_LT_REPEATABLE);
2008
2009 unsafe= (binlog_unsafe_map[stmt_accessed_table_flag] & condition);
2010
2011#if !defined(DBUG_OFF)
2012 DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("RESULT %02X %02X %02X\n", condition,
2013 binlog_unsafe_map[stmt_accessed_table_flag],
2014 (binlog_unsafe_map[stmt_accessed_table_flag] & condition)));
2015
2016 int type_in= 0;
2017 for (; type_in < STMT_ACCESS_TABLE_COUNT; type_in++)
2018 {
2019 if (stmt_accessed_table((enum_stmt_accessed_table) type_in))
2020 DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("ACCESSED %s ",
2021 stmt_accessed_table_string((enum_stmt_accessed_table) type_in)));
2022 }
2023#endif
2024 }
2025
2026 if (stmt_accessed_table(STMT_WRITES_NON_TRANS_TABLE) &&
2027 stmt_accessed_table(STMT_READS_TRANS_TABLE) &&
2028 tx_isolation < ISO_REPEATABLE_READ)
2029 unsafe= TRUE;
2030 else if (stmt_accessed_table(STMT_WRITES_TEMP_NON_TRANS_TABLE) &&
2031 stmt_accessed_table(STMT_READS_TRANS_TABLE) &&
2032 tx_isolation < ISO_REPEATABLE_READ)
2033 unsafe= TRUE;
2034
2035 return(unsafe);
2036 }
2037
2038 /**
2039 true if the parsed tree contains references to stored procedures
2040 or functions, false otherwise
2041 */
2042 bool uses_stored_routines() const
2043 { return sroutines_list.elements != 0; }
2044
2045private:
2046
2047 /**
2048 Enumeration listing special types of statements.
2049
2050 Currently, the only possible type is ROW_INJECTION.
2051 */
2052 enum enum_binlog_stmt_type {
2053 /**
2054 The statement is a row injection (i.e., either a BINLOG
2055 statement or a row event executed by the slave SQL thread).
2056 */
2057 BINLOG_STMT_TYPE_ROW_INJECTION = 0,
2058
2059 /** The last element of this enumeration type. */
2060 BINLOG_STMT_TYPE_COUNT
2061 };
2062
2063 /**
2064 Bit field indicating the type of statement.
2065
2066 There are two groups of bits:
2067
2068 - The low BINLOG_STMT_UNSAFE_COUNT bits indicate the types of
2069 unsafeness that the current statement has.
2070
2071 - The next BINLOG_STMT_TYPE_COUNT bits indicate if the statement
2072 is of some special type.
2073
2074 This must be a member of LEX, not of THD: each stored procedure
2075 needs to remember its unsafeness state between calls and each
2076 stored procedure has its own LEX object (but no own THD object).
2077 */
2078 uint32 binlog_stmt_flags;
2079
2080 /**
2081 Bit field that determines the type of tables that are about to be
2082 be accessed while executing a statement.
2083 */
2084 uint32 stmt_accessed_table_flag;
2085};
2086
2087
2088/*
2089 st_parsing_options contains the flags for constructions that are
2090 allowed in the current statement.
2091*/
2092
2093struct st_parsing_options
2094{
2095 bool allows_variable;
2096
2097 st_parsing_options() { reset(); }
2098 void reset();
2099};
2100
2101
2102/**
2103 The state of the lexical parser, when parsing comments.
2104*/
2105enum enum_comment_state
2106{
2107 /**
2108 Not parsing comments.
2109 */
2110 NO_COMMENT,
2111 /**
2112 Parsing comments that need to be preserved.
2113 Typically, these are user comments '/' '*' ... '*' '/'.
2114 */
2115 PRESERVE_COMMENT,
2116 /**
2117 Parsing comments that need to be discarded.
2118 Typically, these are special comments '/' '*' '!' ... '*' '/',
2119 or '/' '*' '!' 'M' 'M' 'm' 'm' 'm' ... '*' '/', where the comment
2120 markers should not be expanded.
2121 */
2122 DISCARD_COMMENT
2123};
2124
2125
2126/**
2127 @brief This class represents the character input stream consumed during
2128 lexical analysis.
2129
2130 In addition to consuming the input stream, this class performs some
2131 comment pre processing, by filtering out out of bound special text
2132 from the query input stream.
2133 Two buffers, with pointers inside each buffers, are maintained in
2134 parallel. The 'raw' buffer is the original query text, which may
2135 contain out-of-bound comments. The 'cpp' (for comments pre processor)
2136 is the pre-processed buffer that contains only the query text that
2137 should be seen once out-of-bound data is removed.
2138*/
2139
2140class Lex_input_stream
2141{
2142 size_t unescape(CHARSET_INFO *cs, char *to,
2143 const char *str, const char *end, int sep);
2144 my_charset_conv_wc_mb get_escape_func(THD *thd, my_wc_t sep) const;
2145public:
2146 Lex_input_stream()
2147 {
2148 }
2149
2150 ~Lex_input_stream()
2151 {
2152 }
2153
2154 /**
2155 Object initializer. Must be called before usage.
2156
2157 @retval FALSE OK
2158 @retval TRUE Error
2159 */
2160 bool init(THD *thd, char *buff, size_t length);
2161
2162 void reset(char *buff, size_t length);
2163
2164 /**
2165 The main method to scan the next token, with token contraction processing
2166 for LALR(2) resolution, e.g. translate "WITH" followed by "ROLLUP"
2167 to a single token WITH_ROLLUP_SYM.
2168 */
2169 int lex_token(union YYSTYPE *yylval, THD *thd);
2170
2171 void reduce_digest_token(uint token_left, uint token_right);
2172
2173private:
2174 /**
2175 Set the echo mode.
2176
2177 When echo is true, characters parsed from the raw input stream are
2178 preserved. When false, characters parsed are silently ignored.
2179 @param echo the echo mode.
2180 */
2181 void set_echo(bool echo)
2182 {
2183 m_echo= echo;
2184 }
2185
2186 void save_in_comment_state()
2187 {
2188 m_echo_saved= m_echo;
2189 in_comment_saved= in_comment;
2190 }
2191
2192 void restore_in_comment_state()
2193 {
2194 m_echo= m_echo_saved;
2195 in_comment= in_comment_saved;
2196 }
2197
2198 /**
2199 Skip binary from the input stream.
2200 @param n number of bytes to accept.
2201 */
2202 void skip_binary(int n)
2203 {
2204 if (m_echo)
2205 {
2206 memcpy(m_cpp_ptr, m_ptr, n);
2207 m_cpp_ptr += n;
2208 }
2209 m_ptr += n;
2210 }
2211
2212 /**
2213 Get a character, and advance in the stream.
2214 @return the next character to parse.
2215 */
2216 unsigned char yyGet()
2217 {
2218 char c= *m_ptr++;
2219 if (m_echo)
2220 *m_cpp_ptr++ = c;
2221 return c;
2222 }
2223
2224 /**
2225 Get the last character accepted.
2226 @return the last character accepted.
2227 */
2228 unsigned char yyGetLast()
2229 {
2230 return m_ptr[-1];
2231 }
2232
2233 /**
2234 Look at the next character to parse, but do not accept it.
2235 */
2236 unsigned char yyPeek()
2237 {
2238 return m_ptr[0];
2239 }
2240
2241 /**
2242 Look ahead at some character to parse.
2243 @param n offset of the character to look up
2244 */
2245 unsigned char yyPeekn(int n)
2246 {
2247 return m_ptr[n];
2248 }
2249
2250 /**
2251 Cancel the effect of the last yyGet() or yySkip().
2252 Note that the echo mode should not change between calls to yyGet / yySkip
2253 and yyUnget. The caller is responsible for ensuring that.
2254 */
2255 void yyUnget()
2256 {
2257 m_ptr--;
2258 if (m_echo)
2259 m_cpp_ptr--;
2260 }
2261
2262 /**
2263 Accept a character, by advancing the input stream.
2264 */
2265 void yySkip()
2266 {
2267 if (m_echo)
2268 *m_cpp_ptr++ = *m_ptr++;
2269 else
2270 m_ptr++;
2271 }
2272
2273 /**
2274 Accept multiple characters at once.
2275 @param n the number of characters to accept.
2276 */
2277 void yySkipn(int n)
2278 {
2279 if (m_echo)
2280 {
2281 memcpy(m_cpp_ptr, m_ptr, n);
2282 m_cpp_ptr += n;
2283 }
2284 m_ptr += n;
2285 }
2286
2287 /**
2288 Puts a character back into the stream, canceling
2289 the effect of the last yyGet() or yySkip().
2290 Note that the echo mode should not change between calls
2291 to unput, get, or skip from the stream.
2292 */
2293 char *yyUnput(char ch)
2294 {
2295 *--m_ptr= ch;
2296 if (m_echo)
2297 m_cpp_ptr--;
2298 return m_ptr;
2299 }
2300
2301 /**
2302 End of file indicator for the query text to parse.
2303 @param n number of characters expected
2304 @return true if there are less than n characters to parse
2305 */
2306 bool eof(int n)
2307 {
2308 return ((m_ptr + n) >= m_end_of_query);
2309 }
2310
2311 /** Mark the stream position as the start of a new token. */
2312 void start_token()
2313 {
2314 m_tok_start_prev= m_tok_start;
2315 m_tok_start= m_ptr;
2316 m_tok_end= m_ptr;
2317
2318 m_cpp_tok_start_prev= m_cpp_tok_start;
2319 m_cpp_tok_start= m_cpp_ptr;
2320 m_cpp_tok_end= m_cpp_ptr;
2321 }
2322
2323 /**
2324 Adjust the starting position of the current token.
2325 This is used to compensate for starting whitespace.
2326 */
2327 void restart_token()
2328 {
2329 m_tok_start= m_ptr;
2330 m_cpp_tok_start= m_cpp_ptr;
2331 }
2332
2333 /**
2334 Get the maximum length of the utf8-body buffer.
2335 The utf8 body can grow because of the character set conversion and escaping.
2336 */
2337 size_t get_body_utf8_maximum_length(THD *thd);
2338
2339 /** Get the length of the current token, in the raw buffer. */
2340 uint yyLength()
2341 {
2342 /*
2343 The assumption is that the lexical analyser is always 1 character ahead,
2344 which the -1 account for.
2345 */
2346 DBUG_ASSERT(m_ptr > m_tok_start);
2347 return (uint) ((m_ptr - m_tok_start) - 1);
2348 }
2349
2350 /**
2351 Test if a lookahead token was already scanned by lex_token(),
2352 for LALR(2) resolution.
2353 */
2354 bool has_lookahead() const
2355 {
2356 return lookahead_token >= 0;
2357 }
2358
2359public:
2360
2361 /**
2362 End of file indicator for the query text to parse.
2363 @return true if there are no more characters to parse
2364 */
2365 bool eof()
2366 {
2367 return (m_ptr >= m_end_of_query);
2368 }
2369
2370 /** Get the raw query buffer. */
2371 const char *get_buf()
2372 {
2373 return m_buf;
2374 }
2375
2376 /** Get the pre-processed query buffer. */
2377 const char *get_cpp_buf()
2378 {
2379 return m_cpp_buf;
2380 }
2381
2382 /** Get the end of the raw query buffer. */
2383 const char *get_end_of_query()
2384 {
2385 return m_end_of_query;
2386 }
2387
2388 /** Get the token start position, in the raw buffer. */
2389 const char *get_tok_start()
2390 {
2391 return has_lookahead() ? m_tok_start_prev : m_tok_start;
2392 }
2393
2394 void set_cpp_tok_start(const char *pos)
2395 {
2396 m_cpp_tok_start= pos;
2397 }
2398
2399 /** Get the token end position, in the raw buffer. */
2400 const char *get_tok_end()
2401 {
2402 return m_tok_end;
2403 }
2404
2405 /** Get the current stream pointer, in the raw buffer. */
2406 const char *get_ptr()
2407 {
2408 return m_ptr;
2409 }
2410
2411 /** Get the token start position, in the pre-processed buffer. */
2412 const char *get_cpp_tok_start()
2413 {
2414 return has_lookahead() ? m_cpp_tok_start_prev : m_cpp_tok_start;
2415 }
2416
2417 /** Get the token end position, in the pre-processed buffer. */
2418 const char *get_cpp_tok_end()
2419 {
2420 return m_cpp_tok_end;
2421 }
2422
2423 /**
2424 Get the token end position in the pre-processed buffer,
2425 with trailing spaces removed.
2426 */
2427 const char *get_cpp_tok_end_rtrim()
2428 {
2429 const char *p;
2430 for (p= m_cpp_tok_end;
2431 p > m_cpp_buf && my_isspace(system_charset_info, p[-1]);
2432 p--)
2433 { }
2434 return p;
2435 }
2436
2437 /** Get the current stream pointer, in the pre-processed buffer. */
2438 const char *get_cpp_ptr()
2439 {
2440 return m_cpp_ptr;
2441 }
2442
2443 /**
2444 Get the current stream pointer, in the pre-processed buffer,
2445 with traling spaces removed.
2446 */
2447 const char *get_cpp_ptr_rtrim()
2448 {
2449 const char *p;
2450 for (p= m_cpp_ptr;
2451 p > m_cpp_buf && my_isspace(system_charset_info, p[-1]);
2452 p--)
2453 { }
2454 return p;
2455 }
2456 /** Get the utf8-body string. */
2457 const char *get_body_utf8_str()
2458 {
2459 return m_body_utf8;
2460 }
2461
2462 /** Get the utf8-body length. */
2463 size_t get_body_utf8_length()
2464 {
2465 return (size_t) (m_body_utf8_ptr - m_body_utf8);
2466 }
2467
2468 void body_utf8_start(THD *thd, const char *begin_ptr);
2469 void body_utf8_append(const char *ptr);
2470 void body_utf8_append(const char *ptr, const char *end_ptr);
2471 void body_utf8_append_ident(THD *thd,
2472 const Lex_string_with_metadata_st *txt,
2473 const char *end_ptr);
2474 void body_utf8_append_escape(THD *thd,
2475 const LEX_CSTRING *txt,
2476 CHARSET_INFO *txt_cs,
2477 const char *end_ptr,
2478 my_wc_t sep);
2479
2480private:
2481 /**
2482 LALR(2) resolution, look ahead token.
2483 Value of the next token to return, if any,
2484 or -1, if no token was parsed in advance.
2485 Note: 0 is a legal token, and represents YYEOF.
2486 */
2487 int lookahead_token;
2488
2489 /** LALR(2) resolution, value of the look ahead token.*/
2490 LEX_YYSTYPE lookahead_yylval;
2491
2492 bool get_text(Lex_string_with_metadata_st *to,
2493 uint sep, int pre_skip, int post_skip);
2494
2495 void add_digest_token(uint token, LEX_YYSTYPE yylval);
2496
2497 bool consume_comment(int remaining_recursions_permitted);
2498 int lex_one_token(union YYSTYPE *yylval, THD *thd);
2499 int find_keyword(Lex_ident_cli_st *str, uint len, bool function);
2500 LEX_CSTRING get_token(uint skip, uint length);
2501 int scan_ident_sysvar(THD *thd, Lex_ident_cli_st *str);
2502 int scan_ident_start(THD *thd, Lex_ident_cli_st *str);
2503 int scan_ident_middle(THD *thd, Lex_ident_cli_st *str,
2504 CHARSET_INFO **cs, my_lex_states *);
2505 int scan_ident_delimited(THD *thd, Lex_ident_cli_st *str);
2506 bool get_7bit_or_8bit_ident(THD *thd, uchar *last_char);
2507
2508 /** Current thread. */
2509 THD *m_thd;
2510
2511 /** Pointer to the current position in the raw input stream. */
2512 char *m_ptr;
2513
2514 /** Starting position of the last token parsed, in the raw buffer. */
2515 const char *m_tok_start;
2516
2517 /** Ending position of the previous token parsed, in the raw buffer. */
2518 const char *m_tok_end;
2519
2520 /** End of the query text in the input stream, in the raw buffer. */
2521 const char *m_end_of_query;
2522
2523 /** Starting position of the previous token parsed, in the raw buffer. */
2524 const char *m_tok_start_prev;
2525
2526 /** Begining of the query text in the input stream, in the raw buffer. */
2527 const char *m_buf;
2528
2529 /** Length of the raw buffer. */
2530 size_t m_buf_length;
2531
2532 /** Echo the parsed stream to the pre-processed buffer. */
2533 bool m_echo;
2534 bool m_echo_saved;
2535
2536 /** Pre-processed buffer. */
2537 char *m_cpp_buf;
2538
2539 /** Pointer to the current position in the pre-processed input stream. */
2540 char *m_cpp_ptr;
2541
2542 /**
2543 Starting position of the last token parsed,
2544 in the pre-processed buffer.
2545 */
2546 const char *m_cpp_tok_start;
2547
2548 /**
2549 Starting position of the previous token parsed,
2550 in the pre-procedded buffer.
2551 */
2552 const char *m_cpp_tok_start_prev;
2553
2554 /**
2555 Ending position of the previous token parsed,
2556 in the pre-processed buffer.
2557 */
2558 const char *m_cpp_tok_end;
2559
2560 /** UTF8-body buffer created during parsing. */
2561 char *m_body_utf8;
2562
2563 /** Pointer to the current position in the UTF8-body buffer. */
2564 char *m_body_utf8_ptr;
2565
2566 /**
2567 Position in the pre-processed buffer. The query from m_cpp_buf to
2568 m_cpp_utf_processed_ptr is converted to UTF8-body.
2569 */
2570 const char *m_cpp_utf8_processed_ptr;
2571
2572public:
2573
2574 /** Current state of the lexical analyser. */
2575 enum my_lex_states next_state;
2576
2577 /**
2578 Position of ';' in the stream, to delimit multiple queries.
2579 This delimiter is in the raw buffer.
2580 */
2581 const char *found_semicolon;
2582
2583 /** SQL_MODE = IGNORE_SPACE. */
2584 bool ignore_space;
2585
2586 /**
2587 TRUE if we're parsing a prepared statement: in this mode
2588 we should allow placeholders.
2589 */
2590 bool stmt_prepare_mode;
2591 /**
2592 TRUE if we should allow multi-statements.
2593 */
2594 bool multi_statements;
2595
2596 /** Current line number. */
2597 uint yylineno;
2598
2599 /**
2600 Current statement digest instrumentation.
2601 */
2602 sql_digest_state* m_digest;
2603
2604private:
2605 /** State of the lexical analyser for comments. */
2606 enum_comment_state in_comment;
2607 enum_comment_state in_comment_saved;
2608
2609 /**
2610 Starting position of the TEXT_STRING or IDENT in the pre-processed
2611 buffer.
2612
2613 NOTE: this member must be used within MYSQLlex() function only.
2614 */
2615 const char *m_cpp_text_start;
2616
2617 /**
2618 Ending position of the TEXT_STRING or IDENT in the pre-processed
2619 buffer.
2620
2621 NOTE: this member must be used within MYSQLlex() function only.
2622 */
2623 const char *m_cpp_text_end;
2624
2625 /**
2626 Character set specified by the character-set-introducer.
2627
2628 NOTE: this member must be used within MYSQLlex() function only.
2629 */
2630 CHARSET_INFO *m_underscore_cs;
2631};
2632
2633
2634/**
2635 Abstract representation of a statement.
2636 This class is an interface between the parser and the runtime.
2637 The parser builds the appropriate sub classes of Sql_statement
2638 to represent a SQL statement in the parsed tree.
2639 The execute() method in the sub classes contain the runtime implementation.
2640 Note that this interface is used for SQL statement recently implemented,
2641 the code for older statements tend to load the LEX structure with more
2642 attributes instead.
2643 The recommended way to implement new statements is to sub-class
2644 Sql_statement, as this improves code modularity (see the 'big switch' in
2645 dispatch_command()), and decrease the total size of the LEX structure
2646 (therefore saving memory in stored programs).
2647*/
2648class Sql_statement : public Sql_alloc
2649{
2650public:
2651 /**
2652 Execute this SQL statement.
2653 @param thd the current thread.
2654 @return 0 on success.
2655 */
2656 virtual bool execute(THD *thd) = 0;
2657
2658protected:
2659 /**
2660 Constructor.
2661 @param lex the LEX structure that represents parts of this statement.
2662 */
2663 Sql_statement(LEX *lex)
2664 : m_lex(lex)
2665 {}
2666
2667 /** Destructor. */
2668 virtual ~Sql_statement()
2669 {
2670 /*
2671 Sql_statement objects are allocated in thd->mem_root.
2672 In MySQL, the C++ destructor is never called, the underlying MEM_ROOT is
2673 simply destroyed instead.
2674 Do not rely on the destructor for any cleanup.
2675 */
2676 DBUG_ASSERT(FALSE);
2677 }
2678
2679protected:
2680 /**
2681 The legacy LEX structure for this statement.
2682 The LEX structure contains the existing properties of the parsed tree.
2683 TODO: with time, attributes from LEX should move to sub classes of
2684 Sql_statement, so that the parser only builds Sql_statement objects
2685 with the minimum set of attributes, instead of a LEX structure that
2686 contains the collection of every possible attribute.
2687 */
2688 LEX *m_lex;
2689};
2690
2691
2692class Delete_plan;
2693class SQL_SELECT;
2694
2695class Explain_query;
2696class Explain_update;
2697class Explain_delete;
2698
2699/*
2700 Query plan of a single-table UPDATE.
2701 (This is actually a plan for single-table DELETE also)
2702*/
2703
2704class Update_plan
2705{
2706protected:
2707 bool impossible_where;
2708 bool no_partitions;
2709public:
2710 /*
2711 When single-table UPDATE updates a VIEW, that VIEW's select is still
2712 listed as the first child. When we print EXPLAIN, it looks like a
2713 subquery.
2714 In order to get rid of it, updating_a_view=TRUE means that first child
2715 select should not be shown when printing EXPLAIN.
2716 */
2717 bool updating_a_view;
2718
2719 /* Allocate things there */
2720 MEM_ROOT *mem_root;
2721
2722 TABLE *table;
2723 SQL_SELECT *select;
2724 uint index;
2725 ha_rows scanned_rows;
2726 /*
2727 Top-level select_lex. Most of its fields are not used, we need it only to
2728 get to the subqueries.
2729 */
2730 SELECT_LEX *select_lex;
2731
2732 key_map possible_keys;
2733 bool using_filesort;
2734 bool using_io_buffer;
2735
2736 /* Set this plan to be a plan to do nothing because of impossible WHERE */
2737 void set_impossible_where() { impossible_where= true; }
2738 void set_no_partitions() { no_partitions= true; }
2739
2740 Explain_update* save_explain_update_data(MEM_ROOT *mem_root, THD *thd);
2741protected:
2742 bool save_explain_data_intern(MEM_ROOT *mem_root, Explain_update *eu, bool is_analyze);
2743public:
2744 virtual ~Update_plan() {}
2745
2746 Update_plan(MEM_ROOT *mem_root_arg) :
2747 impossible_where(false), no_partitions(false),
2748 mem_root(mem_root_arg),
2749 using_filesort(false), using_io_buffer(false)
2750 {}
2751};
2752
2753
2754/* Query plan of a single-table DELETE */
2755class Delete_plan : public Update_plan
2756{
2757 bool deleting_all_rows;
2758public:
2759
2760 /* Construction functions */
2761 Delete_plan(MEM_ROOT *mem_root_arg) :
2762 Update_plan(mem_root_arg),
2763 deleting_all_rows(false)
2764 {}
2765
2766 /* Set this query plan to be a plan to make a call to h->delete_all_rows() */
2767 void set_delete_all_rows(ha_rows rows_arg)
2768 {
2769 deleting_all_rows= true;
2770 scanned_rows= rows_arg;
2771 }
2772 void cancel_delete_all_rows()
2773 {
2774 deleting_all_rows= false;
2775 }
2776
2777 Explain_delete* save_explain_delete_data(MEM_ROOT *mem_root, THD *thd);
2778};
2779
2780
2781class Query_arena_memroot;
2782/* The state of the lex parsing. This is saved in the THD struct */
2783
2784struct LEX: public Query_tables_list
2785{
2786 SELECT_LEX_UNIT unit; /* most upper unit */
2787 SELECT_LEX select_lex; /* first SELECT_LEX */
2788 /* current SELECT_LEX in parsing */
2789 SELECT_LEX *current_select;
2790 /* list of all SELECT_LEX */
2791 SELECT_LEX *all_selects_list;
2792 /* current with clause in parsing if any, otherwise 0*/
2793 With_clause *curr_with_clause;
2794 /* pointer to the first with clause in the current statement */
2795 With_clause *with_clauses_list;
2796 /*
2797 (*with_clauses_list_last_next) contains a pointer to the last
2798 with clause in the current statement
2799 */
2800 With_clause **with_clauses_list_last_next;
2801
2802 Create_view_info *create_view;
2803
2804 /* Query Plan Footprint of a currently running select */
2805 Explain_query *explain;
2806
2807 // type information
2808 CHARSET_INFO *charset;
2809 /*
2810 LEX which represents current statement (conventional, SP or PS)
2811
2812 For example during view parsing THD::lex will point to the views LEX and
2813 lex::stmt_lex will point to LEX of the statement where the view will be
2814 included
2815
2816 Currently it is used to have always correct select numbering inside
2817 statement (LEX::current_select_number) without storing and restoring a
2818 global counter which was THD::select_number.
2819
2820 TODO: make some unified statement representation (now SP has different)
2821 to store such data like LEX::current_select_number.
2822 */
2823 LEX *stmt_lex;
2824
2825 LEX_CSTRING name;
2826 const char *help_arg;
2827 const char *backup_dir; /* For RESTORE/BACKUP */
2828 const char* to_log; /* For PURGE MASTER LOGS TO */
2829 const char* x509_subject,*x509_issuer,*ssl_cipher;
2830 String *wild; /* Wildcard in SHOW {something} LIKE 'wild'*/
2831 sql_exchange *exchange;
2832 select_result *result;
2833 LEX_CSTRING comment, ident;
2834 LEX_USER *grant_user;
2835 XID *xid;
2836 THD *thd;
2837
2838 /* maintain a list of used plugins for this LEX */
2839 DYNAMIC_ARRAY plugins;
2840 plugin_ref plugins_static_buffer[INITIAL_LEX_PLUGIN_LIST_SIZE];
2841
2842 /** SELECT of CREATE VIEW statement */
2843 LEX_STRING create_view_select;
2844
2845 uint current_select_number; // valid for statment LEX (not view)
2846
2847 /** Start of 'ON table', in trigger statements. */
2848 const char* raw_trg_on_table_name_begin;
2849 /** End of 'ON table', in trigger statements. */
2850 const char* raw_trg_on_table_name_end;
2851
2852 /* Partition info structure filled in by PARTITION BY parse part */
2853 partition_info *part_info;
2854
2855 /*
2856 The definer of the object being created (view, trigger, stored routine).
2857 I.e. the value of DEFINER clause.
2858 */
2859 LEX_USER *definer;
2860
2861 Table_type table_type; /* Used for SHOW CREATE */
2862 List<Key_part_spec> ref_list;
2863 List<LEX_USER> users_list;
2864 List<LEX_COLUMN> columns;
2865 List<Item> *insert_list,field_list,value_list,update_list;
2866 List<List_item> many_values;
2867 List<set_var_base> var_list;
2868 List<set_var_base> stmt_var_list; //SET_STATEMENT values
2869 List<set_var_base> old_var_list; // SET STATEMENT old values
2870private:
2871 Query_arena_memroot *arena_for_set_stmt;
2872 MEM_ROOT *mem_root_for_set_stmt;
2873 bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
2874 class sp_label **splabel);
2875 bool sp_change_context(THD *thd, const sp_pcontext *ctx, bool exclusive);
2876 bool sp_exit_block(THD *thd, sp_label *lab);
2877 bool sp_exit_block(THD *thd, sp_label *lab, Item *when);
2878
2879 bool sp_continue_loop(THD *thd, sp_label *lab);
2880 bool sp_continue_loop(THD *thd, sp_label *lab, Item *when);
2881
2882 bool sp_for_loop_condition(THD *thd, const Lex_for_loop_st &loop);
2883 bool sp_for_loop_increment(THD *thd, const Lex_for_loop_st &loop);
2884
2885public:
2886 void parse_error(uint err_number= ER_SYNTAX_ERROR);
2887 inline bool is_arena_for_set_stmt() {return arena_for_set_stmt != 0;}
2888 bool set_arena_for_set_stmt(Query_arena *backup);
2889 void reset_arena_for_set_stmt(Query_arena *backup);
2890 void free_arena_for_set_stmt();
2891
2892 List<Item_func_set_user_var> set_var_list; // in-query assignment list
2893 List<Item_param> param_list;
2894 List<LEX_CSTRING> view_list; // view list (list of field names in view)
2895 List<LEX_CSTRING> with_column_list; // list of column names in with_list_element
2896 List<LEX_STRING> *column_list; // list of column names (in ANALYZE)
2897 List<LEX_STRING> *index_list; // list of index names (in ANALYZE)
2898 /*
2899 A stack of name resolution contexts for the query. This stack is used
2900 at parse time to set local name resolution contexts for various parts
2901 of a query. For example, in a JOIN ... ON (some_condition) clause the
2902 Items in 'some_condition' must be resolved only against the operands
2903 of the the join, and not against the whole clause. Similarly, Items in
2904 subqueries should be resolved against the subqueries (and outer queries).
2905 The stack is used in the following way: when the parser detects that
2906 all Items in some clause need a local context, it creates a new context
2907 and pushes it on the stack. All newly created Items always store the
2908 top-most context in the stack. Once the parser leaves the clause that
2909 required a local context, the parser pops the top-most context.
2910 */
2911 List<Name_resolution_context> context_stack;
2912
2913 SQL_I_List<ORDER> proc_list;
2914 SQL_I_List<TABLE_LIST> auxiliary_table_list, save_list;
2915 Column_definition *last_field;
2916 Item_sum *in_sum_func;
2917 udf_func udf;
2918 HA_CHECK_OPT check_opt; // check/repair options
2919 Table_specification_st create_info;
2920 Key *last_key;
2921 LEX_MASTER_INFO mi; // used by CHANGE MASTER
2922 LEX_SERVER_OPTIONS server_options;
2923 LEX_CSTRING relay_log_connection_name;
2924 USER_RESOURCES mqh;
2925 LEX_RESET_SLAVE reset_slave_info;
2926 ulonglong type;
2927 ulong next_binlog_file_number;
2928 /* The following is used by KILL */
2929 killed_state kill_signal;
2930 killed_type kill_type;
2931 /*
2932 This variable is used in post-parse stage to declare that sum-functions,
2933 or functions which have sense only if GROUP BY is present, are allowed.
2934 For example in a query
2935 SELECT ... FROM ...WHERE MIN(i) == 1 GROUP BY ... HAVING MIN(i) > 2
2936 MIN(i) in the WHERE clause is not allowed in the opposite to MIN(i)
2937 in the HAVING clause. Due to possible nesting of select construct
2938 the variable can contain 0 or 1 for each nest level.
2939 */
2940 nesting_map allow_sum_func;
2941
2942 Sql_cmd *m_sql_cmd;
2943
2944 /*
2945 Usually `expr` rule of yacc is quite reused but some commands better
2946 not support subqueries which comes standard with this rule, like
2947 KILL, HA_READ, CREATE/ALTER EVENT etc. Set this to `false` to get
2948 syntax error back.
2949 */
2950 bool expr_allows_subselect;
2951 /*
2952 A special command "PARSE_VCOL_EXPR" is defined for the parser
2953 to translate a defining expression of a virtual column into an
2954 Item object.
2955 The following flag is used to prevent other applications to use
2956 this command.
2957 */
2958 bool parse_vcol_expr;
2959
2960 enum SSL_type ssl_type; // defined in violite.h
2961 enum enum_duplicates duplicates;
2962 enum enum_tx_isolation tx_isolation;
2963 enum enum_ha_read_modes ha_read_mode;
2964 union {
2965 enum ha_rkey_function ha_rkey_mode;
2966 enum xa_option_words xa_opt;
2967 bool with_admin_option; // GRANT role
2968 bool with_persistent_for_clause; // uses PERSISTENT FOR clause (in ANALYZE)
2969 };
2970 enum enum_var_type option_type;
2971 enum enum_drop_mode drop_mode;
2972
2973 uint profile_query_id;
2974 uint profile_options;
2975 uint grant, grant_tot_col, which_columns;
2976 enum Foreign_key::fk_match_opt fk_match_option;
2977 enum_fk_option fk_update_opt;
2978 enum_fk_option fk_delete_opt;
2979 uint slave_thd_opt, start_transaction_opt;
2980 int nest_level;
2981 /*
2982 In LEX representing update which were transformed to multi-update
2983 stores total number of tables. For LEX representing multi-delete
2984 holds number of tables from which we will delete records.
2985 */
2986 uint table_count;
2987 uint8 describe;
2988 bool analyze_stmt; /* TRUE<=> this is "ANALYZE $stmt" */
2989 bool explain_json;
2990 /*
2991 A flag that indicates what kinds of derived tables are present in the
2992 query (0 if no derived tables, otherwise a combination of flags
2993 DERIVED_SUBQUERY and DERIVED_VIEW).
2994 */
2995 uint8 derived_tables;
2996 uint8 context_analysis_only;
2997 bool local_file;
2998 bool check_exists;
2999 bool autocommit;
3000 bool verbose, no_write_to_binlog;
3001
3002 enum enum_yes_no_unknown tx_chain, tx_release;
3003 bool safe_to_cache_query;
3004 bool subqueries, ignore;
3005 st_parsing_options parsing_options;
3006 Alter_info alter_info;
3007 /*
3008 For CREATE TABLE statement last element of table list which is not
3009 part of SELECT or LIKE part (i.e. either element for table we are
3010 creating or last of tables referenced by foreign keys).
3011 */
3012 TABLE_LIST *create_last_non_select_table;
3013 /* Prepared statements SQL syntax:*/
3014 LEX_CSTRING prepared_stmt_name; /* Statement name (in all queries) */
3015 /* PREPARE or EXECUTE IMMEDIATE source expression */
3016 Item *prepared_stmt_code;
3017 /* Names of user variables holding parameters (in EXECUTE) */
3018 List<Item> prepared_stmt_params;
3019 sp_head *sphead;
3020 sp_name *spname;
3021 bool sp_lex_in_use; // Keep track on lex usage in SPs for error handling
3022 bool all_privileges;
3023 bool proxy_priv;
3024
3025 sp_pcontext *spcont;
3026
3027 st_sp_chistics sp_chistics;
3028
3029 Event_parse_data *event_parse_data;
3030
3031 /*
3032 field_list was created for view and should be removed before PS/SP
3033 rexecuton
3034 */
3035 bool empty_field_list_on_rset;
3036 /* Characterstics of trigger being created */
3037 st_trg_chistics trg_chistics;
3038 /*
3039 List of all items (Item_trigger_field objects) representing fields in
3040 old/new version of row in trigger. We use this list for checking whenever
3041 all such fields are valid at trigger creation time and for binding these
3042 fields to TABLE object at table open (altough for latter pointer to table
3043 being opened is probably enough).
3044 */
3045 SQL_I_List<Item_trigger_field> trg_table_fields;
3046
3047 /*
3048 stmt_definition_begin is intended to point to the next word after
3049 DEFINER-clause in the following statements:
3050 - CREATE TRIGGER (points to "TRIGGER");
3051 - CREATE PROCEDURE (points to "PROCEDURE");
3052 - CREATE FUNCTION (points to "FUNCTION" or "AGGREGATE");
3053 - CREATE EVENT (points to "EVENT")
3054
3055 This pointer is required to add possibly omitted DEFINER-clause to the
3056 DDL-statement before dumping it to the binlog.
3057
3058 keyword_delayed_begin_offset is the offset to the beginning of the DELAYED
3059 keyword in INSERT DELAYED statement. keyword_delayed_end_offset is the
3060 offset to the character right after the DELAYED keyword.
3061 */
3062 union {
3063 const char *stmt_definition_begin;
3064 uint keyword_delayed_begin_offset;
3065 };
3066
3067 union {
3068 const char *stmt_definition_end;
3069 uint keyword_delayed_end_offset;
3070 };
3071
3072 /**
3073 Collects create options for KEY
3074 */
3075 engine_option_value *option_list;
3076
3077 /**
3078 Helper pointer to the end of the list when parsing options for
3079 LEX::create_info.option_list (for table)
3080 LEX::last_field->option_list (for fields)
3081 LEX::option_list (for indexes)
3082 */
3083 engine_option_value *option_list_last;
3084
3085 /**
3086 During name resolution search only in the table list given by
3087 Name_resolution_context::first_name_resolution_table and
3088 Name_resolution_context::last_name_resolution_table
3089 (see Item_field::fix_fields()).
3090 */
3091 bool use_only_table_context;
3092
3093 /*
3094 Reference to a struct that contains information in various commands
3095 to add/create/drop/change table spaces.
3096 */
3097 st_alter_tablespace *alter_tablespace_info;
3098
3099 bool escape_used;
3100 bool default_used; /* using default() function */
3101 bool is_lex_started; /* If lex_start() did run. For debugging. */
3102
3103 /*
3104 The set of those tables whose fields are referenced in all subqueries
3105 of the query.
3106 TODO: possibly this it is incorrect to have used tables in LEX because
3107 with subquery, it is not clear what does the field mean. To fix this
3108 we should aggregate used tables information for selected expressions
3109 into the select_lex.
3110 */
3111 table_map used_tables;
3112 /**
3113 Maximum number of rows and/or keys examined by the query, both read,
3114 changed or written. This is the argument of LIMIT ROWS EXAMINED.
3115 The limit is represented by two variables - the Item is needed because
3116 in case of parameters we have to delay its evaluation until execution.
3117 Once evaluated, its value is stored in examined_rows_limit_cnt.
3118 */
3119 Item *limit_rows_examined;
3120 ulonglong limit_rows_examined_cnt;
3121 /**
3122 Holds a set of domain_ids for deletion at FLUSH..DELETE_DOMAIN_ID
3123 */
3124 DYNAMIC_ARRAY delete_gtid_domain;
3125 static const ulong initial_gtid_domain_buffer_size= 16;
3126 ulong gtid_domain_static_buffer[initial_gtid_domain_buffer_size];
3127
3128 inline void set_limit_rows_examined()
3129 {
3130 if (limit_rows_examined)
3131 limit_rows_examined_cnt= limit_rows_examined->val_uint();
3132 else
3133 limit_rows_examined_cnt= ULONGLONG_MAX;
3134 }
3135
3136
3137 SQL_I_List<ORDER> save_group_list;
3138 SQL_I_List<ORDER> save_order_list;
3139 LEX_CSTRING *win_ref;
3140 Window_frame *win_frame;
3141 Window_frame_bound *frame_top_bound;
3142 Window_frame_bound *frame_bottom_bound;
3143 Window_spec *win_spec;
3144
3145 /* System Versioning */
3146 vers_select_conds_t vers_conditions;
3147
3148 inline void free_set_stmt_mem_root()
3149 {
3150 DBUG_ASSERT(!is_arena_for_set_stmt());
3151 if (mem_root_for_set_stmt)
3152 {
3153 free_root(mem_root_for_set_stmt, MYF(0));
3154 delete mem_root_for_set_stmt;
3155 mem_root_for_set_stmt= 0;
3156 }
3157 }
3158
3159 LEX();
3160
3161 virtual ~LEX()
3162 {
3163 free_set_stmt_mem_root();
3164 destroy_query_tables_list();
3165 plugin_unlock_list(NULL, (plugin_ref *)plugins.buffer, plugins.elements);
3166 delete_dynamic(&plugins);
3167 }
3168
3169 virtual class Query_arena *query_arena()
3170 {
3171 DBUG_ASSERT(0);
3172 return NULL;
3173 }
3174
3175 virtual const LEX_CSTRING *cursor_name() const { return &null_clex_str; }
3176
3177 void start(THD *thd);
3178
3179 inline bool is_ps_or_view_context_analysis()
3180 {
3181 return (context_analysis_only &
3182 (CONTEXT_ANALYSIS_ONLY_PREPARE |
3183 CONTEXT_ANALYSIS_ONLY_VCOL_EXPR |
3184 CONTEXT_ANALYSIS_ONLY_VIEW));
3185 }
3186
3187 inline bool is_view_context_analysis()
3188 {
3189 return (context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW);
3190 }
3191
3192 inline void uncacheable(uint8 cause)
3193 {
3194 safe_to_cache_query= 0;
3195
3196 if (current_select) // initialisation SP variables has no SELECT
3197 {
3198 /*
3199 There are no sense to mark select_lex and union fields of LEX,
3200 but we should merk all subselects as uncacheable from current till
3201 most upper
3202 */
3203 SELECT_LEX *sl;
3204 SELECT_LEX_UNIT *un;
3205 for (sl= current_select, un= sl->master_unit();
3206 un != &unit;
3207 sl= sl->outer_select(), un= sl->master_unit())
3208 {
3209 sl->uncacheable|= cause;
3210 un->uncacheable|= cause;
3211 }
3212 select_lex.uncacheable|= cause;
3213 }
3214 }
3215 void set_trg_event_type_for_tables();
3216
3217 TABLE_LIST *unlink_first_table(bool *link_to_local);
3218 void link_first_table_back(TABLE_LIST *first, bool link_to_local);
3219 void first_lists_tables_same();
3220
3221 bool can_be_merged();
3222 bool can_use_merged();
3223 bool can_not_use_merged();
3224 bool only_view_structure();
3225 bool need_correct_ident();
3226 uint8 get_effective_with_check(TABLE_LIST *view);
3227 /*
3228 Is this update command where 'WHITH CHECK OPTION' clause is important
3229
3230 SYNOPSIS
3231 LEX::which_check_option_applicable()
3232
3233 RETURN
3234 TRUE have to take 'WHITH CHECK OPTION' clause into account
3235 FALSE 'WHITH CHECK OPTION' clause do not need
3236 */
3237 inline bool which_check_option_applicable()
3238 {
3239 switch (sql_command) {
3240 case SQLCOM_UPDATE:
3241 case SQLCOM_UPDATE_MULTI:
3242 case SQLCOM_DELETE:
3243 case SQLCOM_DELETE_MULTI:
3244 case SQLCOM_INSERT:
3245 case SQLCOM_INSERT_SELECT:
3246 case SQLCOM_REPLACE:
3247 case SQLCOM_REPLACE_SELECT:
3248 case SQLCOM_LOAD:
3249 return TRUE;
3250 default:
3251 return FALSE;
3252 }
3253 }
3254
3255 void cleanup_after_one_table_open();
3256
3257 bool push_context(Name_resolution_context *context, MEM_ROOT *mem_root)
3258 {
3259 return context_stack.push_front(context, mem_root);
3260 }
3261
3262 void pop_context()
3263 {
3264 context_stack.pop();
3265 }
3266
3267 bool copy_db_to(LEX_CSTRING *to);
3268
3269 Name_resolution_context *current_context()
3270 {
3271 return context_stack.head();
3272 }
3273 /*
3274 Restore the LEX and THD in case of a parse error.
3275 */
3276 static void cleanup_lex_after_parse_error(THD *thd);
3277
3278 void reset_n_backup_query_tables_list(Query_tables_list *backup);
3279 void restore_backup_query_tables_list(Query_tables_list *backup);
3280
3281 bool table_or_sp_used();
3282
3283 bool is_partition_management() const;
3284 bool part_values_current(THD *thd);
3285 bool part_values_history(THD *thd);
3286
3287 /**
3288 @brief check if the statement is a single-level join
3289 @return result of the check
3290 @retval TRUE The statement doesn't contain subqueries, unions and
3291 stored procedure calls.
3292 @retval FALSE There are subqueries, UNIONs or stored procedure calls.
3293 */
3294 bool is_single_level_stmt()
3295 {
3296 /*
3297 This check exploits the fact that the last added to all_select_list is
3298 on its top. So select_lex (as the first added) will be at the tail
3299 of the list.
3300 */
3301 if (&select_lex == all_selects_list && !sroutines.records)
3302 {
3303 DBUG_ASSERT(!all_selects_list->next_select_in_list());
3304 return TRUE;
3305 }
3306 return FALSE;
3307 }
3308
3309 bool save_prep_leaf_tables();
3310
3311 int print_explain(select_result_sink *output, uint8 explain_flags,
3312 bool is_analyze, bool *printed_anything);
3313 void restore_set_statement_var();
3314
3315 void init_last_field(Column_definition *field, const LEX_CSTRING *name,
3316 const CHARSET_INFO *cs);
3317 bool last_field_generated_always_as_row_start_or_end(Lex_ident *p,
3318 const char *type,
3319 uint flags);
3320 bool last_field_generated_always_as_row_start();
3321 bool last_field_generated_always_as_row_end();
3322 bool set_bincmp(CHARSET_INFO *cs, bool bin);
3323
3324 bool get_dynamic_sql_string(LEX_CSTRING *dst, String *buffer);
3325 bool prepared_stmt_params_fix_fields(THD *thd)
3326 {
3327 // Fix Items in the EXECUTE..USING list
3328 List_iterator_fast<Item> param_it(prepared_stmt_params);
3329 while (Item *param= param_it++)
3330 {
3331 if (param->fix_fields(thd, 0) || param->check_cols(1))
3332 return true;
3333 }
3334 return false;
3335 }
3336 sp_variable *sp_param_init(LEX_CSTRING *name);
3337 bool sp_param_fill_definition(sp_variable *spvar);
3338
3339 int case_stmt_action_expr(Item* expr);
3340 int case_stmt_action_when(Item *when, bool simple);
3341 int case_stmt_action_then();
3342 bool add_select_to_union_list(bool is_union_distinct,
3343 enum sub_select_type type,
3344 bool is_top_level);
3345 bool setup_select_in_parentheses();
3346 bool set_trigger_new_row(const LEX_CSTRING *name, Item *val);
3347 bool set_trigger_field(const LEX_CSTRING *name1, const LEX_CSTRING *name2,
3348 Item *val);
3349 bool set_system_variable(enum_var_type var_type, sys_var *var,
3350 const LEX_CSTRING *base_name, Item *val);
3351 bool set_system_variable(enum_var_type var_type, const LEX_CSTRING *name,
3352 Item *val);
3353 bool set_system_variable(THD *thd, enum_var_type var_type,
3354 const LEX_CSTRING *name1,
3355 const LEX_CSTRING *name2,
3356 Item *val);
3357 bool set_default_system_variable(enum_var_type var_type,
3358 const LEX_CSTRING *name,
3359 Item *val);
3360 bool set_user_variable(THD *thd, const LEX_CSTRING *name, Item *val);
3361 void set_stmt_init();
3362 sp_name *make_sp_name(THD *thd, const LEX_CSTRING *name);
3363 sp_name *make_sp_name(THD *thd, const LEX_CSTRING *name1,
3364 const LEX_CSTRING *name2);
3365 sp_name *make_sp_name_package_routine(THD *thd, const LEX_CSTRING *name);
3366 sp_head *make_sp_head(THD *thd, const sp_name *name, const Sp_handler *sph);
3367 sp_head *make_sp_head_no_recursive(THD *thd, const sp_name *name,
3368 const Sp_handler *sph);
3369 sp_head *make_sp_head_no_recursive(THD *thd,
3370 DDL_options_st options, sp_name *name,
3371 const Sp_handler *sph)
3372 {
3373 if (add_create_options_with_check(options))
3374 return NULL;
3375 return make_sp_head_no_recursive(thd, name, sph);
3376 }
3377 bool sp_body_finalize_function(THD *);
3378 bool sp_body_finalize_procedure(THD *);
3379 sp_package *create_package_start(THD *thd,
3380 enum_sql_command command,
3381 const Sp_handler *sph,
3382 const sp_name *name,
3383 DDL_options_st options);
3384 bool create_package_finalize(THD *thd,
3385 const sp_name *name,
3386 const sp_name *name2,
3387 const char *body_start,
3388 const char *body_end);
3389 bool call_statement_start(THD *thd, sp_name *name);
3390 bool call_statement_start(THD *thd, const LEX_CSTRING *name);
3391 bool call_statement_start(THD *thd, const LEX_CSTRING *name1,
3392 const LEX_CSTRING *name2);
3393 sp_variable *find_variable(const LEX_CSTRING *name,
3394 sp_pcontext **ctx,
3395 const Sp_rcontext_handler **rh) const;
3396 sp_variable *find_variable(const LEX_CSTRING *name,
3397 const Sp_rcontext_handler **rh) const
3398 {
3399 sp_pcontext *not_used_ctx;
3400 return find_variable(name, &not_used_ctx, rh);
3401 }
3402 bool set_variable(const LEX_CSTRING *name, Item *item);
3403 bool set_variable(const LEX_CSTRING *name1, const LEX_CSTRING *name2,
3404 Item *item);
3405 void sp_variable_declarations_init(THD *thd, int nvars);
3406 bool sp_variable_declarations_finalize(THD *thd, int nvars,
3407 const Column_definition *cdef,
3408 Item *def);
3409 bool sp_variable_declarations_set_default(THD *thd, int nvars, Item *def);
3410 bool sp_variable_declarations_row_finalize(THD *thd, int nvars,
3411 Row_definition_list *row,
3412 Item *def);
3413 bool sp_variable_declarations_with_ref_finalize(THD *thd, int nvars,
3414 Qualified_column_ident *col,
3415 Item *def);
3416 bool sp_variable_declarations_rowtype_finalize(THD *thd, int nvars,
3417 Qualified_column_ident *,
3418 Item *def);
3419 bool sp_variable_declarations_cursor_rowtype_finalize(THD *thd, int nvars,
3420 uint offset,
3421 Item *def);
3422 bool sp_variable_declarations_table_rowtype_finalize(THD *thd, int nvars,
3423 const LEX_CSTRING &db,
3424 const LEX_CSTRING &table,
3425 Item *def);
3426 bool sp_variable_declarations_column_type_finalize(THD *thd, int nvars,
3427 Qualified_column_ident *ref,
3428 Item *def);
3429 bool sp_variable_declarations_vartype_finalize(THD *thd, int nvars,
3430 const LEX_CSTRING &name,
3431 Item *def);
3432 bool sp_variable_declarations_copy_type_finalize(THD *thd, int nvars,
3433 const Column_definition &ref,
3434 Row_definition_list *fields,
3435 Item *def);
3436 bool sp_handler_declaration_init(THD *thd, int type);
3437 bool sp_handler_declaration_finalize(THD *thd, int type);
3438
3439 bool sp_declare_cursor(THD *thd, const LEX_CSTRING *name,
3440 class sp_lex_cursor *cursor_stmt,
3441 sp_pcontext *param_ctx, bool add_cpush_instr);
3442
3443 bool sp_open_cursor(THD *thd, const LEX_CSTRING *name,
3444 List<sp_assignment_lex> *parameters);
3445 Item_splocal *create_item_for_sp_var(const Lex_ident_cli_st *name,
3446 sp_variable *spvar);
3447
3448 Item *create_item_qualified_asterisk(THD *thd, const Lex_ident_sys_st *name);
3449 Item *create_item_qualified_asterisk(THD *thd,
3450 const Lex_ident_sys_st *a,
3451 const Lex_ident_sys_st *b);
3452 Item *create_item_qualified_asterisk(THD *thd, const Lex_ident_cli_st *cname)
3453 {
3454 Lex_ident_sys name(thd, cname);
3455 if (name.is_null())
3456 return NULL; // EOM
3457 return create_item_qualified_asterisk(thd, &name);
3458 }
3459 Item *create_item_qualified_asterisk(THD *thd,
3460 const Lex_ident_cli_st *ca,
3461 const Lex_ident_cli_st *cb)
3462 {
3463 Lex_ident_sys a(thd, ca), b(thd, cb);
3464 if (a.is_null() || b.is_null())
3465 return NULL; // EOM
3466 return create_item_qualified_asterisk(thd, &a, &b);
3467 }
3468
3469 Item *create_item_ident_nosp(THD *thd, Lex_ident_sys_st *name);
3470 Item *create_item_ident_sp(THD *thd, Lex_ident_sys_st *name,
3471 const char *start, const char *end);
3472 Item *create_item_ident(THD *thd, Lex_ident_cli_st *cname)
3473 {
3474 Lex_ident_sys name(thd, cname);
3475 if (name.is_null())
3476 return NULL; // EOM
3477 return sphead ?
3478 create_item_ident_sp(thd, &name, cname->pos(), cname->end()) :
3479 create_item_ident_nosp(thd, &name);
3480 }
3481 /*
3482 Create an Item corresponding to a qualified name: a.b
3483 when the parser is out of an SP context.
3484 @param THD - THD, for mem_root
3485 @param a - the first name
3486 @param b - the second name
3487 @retval - a pointer to a created item, or NULL on error.
3488
3489 Possible Item types that can be created:
3490 - Item_trigger_field
3491 - Item_field
3492 - Item_ref
3493 */
3494 Item *create_item_ident_nospvar(THD *thd,
3495 const Lex_ident_sys_st *a,
3496 const Lex_ident_sys_st *b);
3497 /*
3498 Create an Item corresponding to a ROW field valiable: var.field
3499 @param THD - THD, for mem_root
3500 @param rh [OUT] - the rcontext handler (local vs package variables)
3501 @param var - the ROW variable name
3502 @param field - the ROW variable field name
3503 @param spvar - the variable that was previously found by name
3504 using "var_name".
3505 @param start - position in the query (for binary log)
3506 @param end - end in the query (for binary log)
3507 */
3508 Item_splocal *create_item_spvar_row_field(THD *thd,
3509 const Sp_rcontext_handler *rh,
3510 const Lex_ident_sys *var,
3511 const Lex_ident_sys *field,
3512 sp_variable *spvar,
3513 const char *start,
3514 const char *end);
3515 /*
3516 Create an item from its qualified name.
3517 Depending on context, it can be either a ROW variable field,
3518 or trigger, table field, table field reference.
3519 See comments to create_item_spvar_row_field() and
3520 create_item_ident_nospvar().
3521 @param thd - THD, for mem_root
3522 @param a - the first name
3523 @param b - the second name
3524 @retval - NULL on error, or a pointer to a new Item.
3525 */
3526 Item *create_item_ident(THD *thd,
3527 const Lex_ident_cli_st *a,
3528 const Lex_ident_cli_st *b);
3529 /*
3530 Create an item from its qualified name.
3531 Depending on context, it can be a table field, a table field reference,
3532 or a sequence NEXTVAL and CURRVAL.
3533 @param thd - THD, for mem_root
3534 @param a - the first name
3535 @param b - the second name
3536 @param c - the third name
3537 @retval - NULL on error, or a pointer to a new Item.
3538 */
3539 Item *create_item_ident(THD *thd,
3540 const Lex_ident_sys_st *a,
3541 const Lex_ident_sys_st *b,
3542 const Lex_ident_sys_st *c);
3543
3544 Item *create_item_ident(THD *thd,
3545 const Lex_ident_cli_st *ca,
3546 const Lex_ident_cli_st *cb,
3547 const Lex_ident_cli_st *cc)
3548 {
3549 Lex_ident_sys b(thd, cb), c(thd, cc);
3550 if (b.is_null() || c.is_null())
3551 return NULL;
3552 if (ca->pos() == cb->pos()) // SELECT .t1.col1
3553 {
3554 DBUG_ASSERT(ca->length == 0);
3555 Lex_ident_sys none;
3556 return create_item_ident(thd, &none, &b, &c);
3557 }
3558 Lex_ident_sys a(thd, ca);
3559 return a.is_null() ? NULL : create_item_ident(thd, &a, &b, &c);
3560 }
3561
3562 /*
3563 Create an item for "NEXT VALUE FOR sequence_name"
3564 */
3565 Item *create_item_func_nextval(THD *thd, Table_ident *ident);
3566 Item *create_item_func_nextval(THD *thd, const LEX_CSTRING *db,
3567 const LEX_CSTRING *name);
3568 /*
3569 Create an item for "PREVIOUS VALUE FOR sequence_name"
3570 */
3571 Item *create_item_func_lastval(THD *thd, Table_ident *ident);
3572 Item *create_item_func_lastval(THD *thd, const LEX_CSTRING *db,
3573 const LEX_CSTRING *name);
3574
3575 /*
3576 Create an item for "SETVAL(sequence_name, value [, is_used [, round]])
3577 */
3578 Item *create_item_func_setval(THD *thd, Table_ident *ident, longlong value,
3579 ulonglong round, bool is_used);
3580
3581 /*
3582 Create an item for a name in LIMIT clause: LIMIT var
3583 @param THD - THD, for mem_root
3584 @param var_name - the variable name
3585 @retval - a new Item corresponding to the SP variable,
3586 or NULL on error
3587 (non in SP, unknown variable, wrong data type).
3588 */
3589 Item *create_item_limit(THD *thd, const Lex_ident_cli_st *var_name);
3590
3591 /*
3592 Create an item for a qualified name in LIMIT clause: LIMIT var.field
3593 @param THD - THD, for mem_root
3594 @param var_name - the variable name
3595 @param field_name - the variable field name
3596 @param start - start in the query (for binary log)
3597 @param end - end in the query (for binary log)
3598 @retval - a new Item corresponding to the SP variable,
3599 or NULL on error
3600 (non in SP, unknown variable, unknown ROW field,
3601 wrong data type).
3602 */
3603 Item *create_item_limit(THD *thd,
3604 const Lex_ident_cli_st *var_name,
3605 const Lex_ident_cli_st *field_name);
3606
3607 Item *make_item_func_replace(THD *thd, Item *org, Item *find, Item *replace);
3608 Item *make_item_func_substr(THD *thd, Item *a, Item *b, Item *c);
3609 Item *make_item_func_substr(THD *thd, Item *a, Item *b);
3610 Item *make_item_func_call_generic(THD *thd, Lex_ident_cli_st *db,
3611 Lex_ident_cli_st *name, List<Item> *args);
3612 my_var *create_outvar(THD *thd, const LEX_CSTRING *name);
3613
3614 /*
3615 Create a my_var instance for a ROW field variable that was used
3616 as an OUT SP parameter: CALL p1(var.field);
3617 @param THD - THD, for mem_root
3618 @param var_name - the variable name
3619 @param field_name - the variable field name
3620 */
3621 my_var *create_outvar(THD *thd,
3622 const LEX_CSTRING *var_name,
3623 const LEX_CSTRING *field_name);
3624
3625 bool is_trigger_new_or_old_reference(const LEX_CSTRING *name) const;
3626
3627 Item *create_and_link_Item_trigger_field(THD *thd, const LEX_CSTRING *name,
3628 bool new_row);
3629 // For syntax with colon, e.g. :NEW.a or :OLD.a
3630 Item *make_item_colon_ident_ident(THD *thd,
3631 const Lex_ident_cli_st *a,
3632 const Lex_ident_cli_st *b);
3633 // For "SELECT @@var", "SELECT @@var.field"
3634 Item *make_item_sysvar(THD *thd,
3635 enum_var_type type,
3636 const LEX_CSTRING *name)
3637 {
3638 return make_item_sysvar(thd, type, name, &null_clex_str);
3639 }
3640 Item *make_item_sysvar(THD *thd,
3641 enum_var_type type,
3642 const LEX_CSTRING *name,
3643 const LEX_CSTRING *component);
3644 void sp_block_init(THD *thd, const LEX_CSTRING *label);
3645 void sp_block_init(THD *thd)
3646 {
3647 // Unlabeled blocks get an empty label
3648 sp_block_init(thd, &empty_clex_str);
3649 }
3650 bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock)
3651 {
3652 class sp_label *tmp;
3653 return sp_block_finalize(thd, spblock, &tmp);
3654 }
3655 bool sp_block_finalize(THD *thd)
3656 {
3657 return sp_block_finalize(thd, Lex_spblock());
3658 }
3659 bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
3660 const LEX_CSTRING *end_label);
3661 bool sp_block_finalize(THD *thd, const LEX_CSTRING *end_label)
3662 {
3663 return sp_block_finalize(thd, Lex_spblock(), end_label);
3664 }
3665 bool sp_declarations_join(Lex_spblock_st *res,
3666 const Lex_spblock_st b1,
3667 const Lex_spblock_st b2) const
3668 {
3669 if ((b2.vars || b2.conds) && (b1.curs || b1.hndlrs))
3670 {
3671 my_error(ER_SP_VARCOND_AFTER_CURSHNDLR, MYF(0));
3672 return true;
3673 }
3674 if (b2.curs && b1.hndlrs)
3675 {
3676 my_error(ER_SP_CURSOR_AFTER_HANDLER, MYF(0));
3677 return true;
3678 }
3679 res->join(b1, b2);
3680 return false;
3681 }
3682 bool sp_block_with_exceptions_finalize_declarations(THD *thd);
3683 bool sp_block_with_exceptions_finalize_executable_section(THD *thd,
3684 uint executable_section_ip);
3685 bool sp_block_with_exceptions_finalize_exceptions(THD *thd,
3686 uint executable_section_ip,
3687 uint exception_count);
3688 bool sp_block_with_exceptions_add_empty(THD *thd);
3689 bool sp_exit_statement(THD *thd, Item *when);
3690 bool sp_exit_statement(THD *thd, const LEX_CSTRING *label_name, Item *item);
3691 bool sp_leave_statement(THD *thd, const LEX_CSTRING *label_name);
3692 bool sp_goto_statement(THD *thd, const LEX_CSTRING *label_name);
3693
3694 bool sp_continue_statement(THD *thd, Item *when);
3695 bool sp_continue_statement(THD *thd, const LEX_CSTRING *label_name, Item *when);
3696 bool sp_iterate_statement(THD *thd, const LEX_CSTRING *label_name);
3697
3698 bool maybe_start_compound_statement(THD *thd);
3699 bool sp_push_loop_label(THD *thd, const LEX_CSTRING *label_name);
3700 bool sp_push_loop_empty_label(THD *thd);
3701 bool sp_pop_loop_label(THD *thd, const LEX_CSTRING *label_name);
3702 void sp_pop_loop_empty_label(THD *thd);
3703 bool sp_while_loop_expression(THD *thd, Item *expr);
3704 bool sp_while_loop_finalize(THD *thd);
3705 bool sp_push_goto_label(THD *thd, const LEX_CSTRING *label_name);
3706
3707 Item_param *add_placeholder(THD *thd, const LEX_CSTRING *name,
3708 const char *start, const char *end);
3709
3710 /* Integer range FOR LOOP methods */
3711 sp_variable *sp_add_for_loop_variable(THD *thd, const LEX_CSTRING *name,
3712 Item *value);
3713 sp_variable *sp_add_for_loop_upper_bound(THD *thd, Item *value)
3714 {
3715 LEX_CSTRING name= { STRING_WITH_LEN("[upper_bound]") };
3716 return sp_add_for_loop_variable(thd, &name, value);
3717 }
3718 bool sp_for_loop_intrange_declarations(THD *thd, Lex_for_loop_st *loop,
3719 const LEX_CSTRING *index,
3720 const Lex_for_loop_bounds_st &bounds);
3721 bool sp_for_loop_intrange_condition_test(THD *thd, const Lex_for_loop_st &loop);
3722 bool sp_for_loop_intrange_finalize(THD *thd, const Lex_for_loop_st &loop);
3723
3724 /* Cursor FOR LOOP methods */
3725 bool sp_for_loop_cursor_declarations(THD *thd, Lex_for_loop_st *loop,
3726 const LEX_CSTRING *index,
3727 const Lex_for_loop_bounds_st &bounds);
3728 sp_variable *sp_add_for_loop_cursor_variable(THD *thd,
3729 const LEX_CSTRING *name,
3730 const class sp_pcursor *cur,
3731 uint coffset,
3732 sp_assignment_lex *param_lex,
3733 Item_args *parameters);
3734 bool sp_for_loop_implicit_cursor_statement(THD *thd,
3735 Lex_for_loop_bounds_st *bounds,
3736 sp_lex_cursor *cur);
3737 bool sp_for_loop_cursor_condition_test(THD *thd, const Lex_for_loop_st &loop);
3738 bool sp_for_loop_cursor_finalize(THD *thd, const Lex_for_loop_st &);
3739
3740 /* Generic FOR LOOP methods*/
3741
3742 /*
3743 Generate FOR loop declarations and
3744 initialize "loop" from "index" and "bounds".
3745
3746 @param [IN] thd - current THD, for mem_root and error reporting
3747 @param [OUT] loop - the loop generated SP variables are stored here,
3748 together with additional loop characteristics.
3749 @param [IN] index - the loop index variable name
3750 @param [IN] bounds - the loop bounds (in sp_assignment_lex format)
3751 and additional loop characteristics,
3752 as created by the sp_for_loop_bounds rule.
3753 @retval true - on error
3754 @retval false - on success
3755
3756 This methods adds declarations:
3757 - An explicit integer or cursor%ROWTYPE "index" variable
3758 - An implicit integer upper bound variable, in case of integer range loops
3759 - A CURSOR, in case of an implicit CURSOR loops
3760 The generated variables are stored into "loop".
3761 Additional loop characteristics are copied from "bounds" to "loop".
3762 */
3763 bool sp_for_loop_declarations(THD *thd, Lex_for_loop_st *loop,
3764 const LEX_CSTRING *index,
3765 const Lex_for_loop_bounds_st &bounds)
3766 {
3767 return bounds.is_for_loop_cursor() ?
3768 sp_for_loop_cursor_declarations(thd, loop, index, bounds) :
3769 sp_for_loop_intrange_declarations(thd, loop, index, bounds);
3770 }
3771
3772 /*
3773 Generate a conditional jump instruction to leave the loop,
3774 using a proper condition depending on the loop type:
3775 - Item_func_le -- integer range loops
3776 - Item_func_ge -- integer range reverse loops
3777 - Item_func_cursor_found -- cursor loops
3778 */
3779 bool sp_for_loop_condition_test(THD *thd, const Lex_for_loop_st &loop)
3780 {
3781 return loop.is_for_loop_cursor() ?
3782 sp_for_loop_cursor_condition_test(thd, loop) :
3783 sp_for_loop_intrange_condition_test(thd, loop);
3784 }
3785
3786 /*
3787 Generate "increment" instructions followed by a jump to the
3788 condition test in the beginnig of the loop.
3789 "Increment" depends on the loop type and can be:
3790 - index:= index + 1; -- integer range loops
3791 - index:= index - 1; -- integer range reverse loops
3792 - FETCH cursor INTO index; -- cursor loops
3793 */
3794 bool sp_for_loop_finalize(THD *thd, const Lex_for_loop_st &loop)
3795 {
3796 return loop.is_for_loop_cursor() ?
3797 sp_for_loop_cursor_finalize(thd, loop) :
3798 sp_for_loop_intrange_finalize(thd, loop);
3799 }
3800 /* End of FOR LOOP methods */
3801
3802 bool add_signal_statement(THD *thd, const class sp_condition_value *value);
3803 bool add_resignal_statement(THD *thd, const class sp_condition_value *value);
3804
3805 // Check if "KEY IF NOT EXISTS name" used outside of ALTER context
3806 bool check_add_key(DDL_options_st ddl)
3807 {
3808 if (ddl.if_not_exists() && sql_command != SQLCOM_ALTER_TABLE)
3809 {
3810 parse_error();
3811 return true;
3812 }
3813 return false;
3814 }
3815 // Add a key as a part of CREATE TABLE or ALTER TABLE
3816 bool add_key(Key::Keytype key_type, const LEX_CSTRING *key_name,
3817 ha_key_alg algorithm, DDL_options_st ddl)
3818 {
3819 if (check_add_key(ddl) ||
3820 !(last_key= new Key(key_type, key_name, algorithm, false, ddl)))
3821 return true;
3822 alter_info.key_list.push_back(last_key);
3823 return false;
3824 }
3825 // Add a key for a CREATE INDEX statement
3826 bool add_create_index(Key::Keytype key_type, const LEX_CSTRING *key_name,
3827 ha_key_alg algorithm, DDL_options_st ddl)
3828 {
3829 if (check_create_options(ddl) ||
3830 !(last_key= new Key(key_type, key_name, algorithm, false, ddl)))
3831 return true;
3832 alter_info.key_list.push_back(last_key);
3833 return false;
3834 }
3835 bool add_create_index_prepare(Table_ident *table)
3836 {
3837 sql_command= SQLCOM_CREATE_INDEX;
3838 if (!current_select->add_table_to_list(thd, table, NULL,
3839 TL_OPTION_UPDATING,
3840 TL_READ_NO_INSERT,
3841 MDL_SHARED_UPGRADABLE))
3842 return true;
3843 alter_info.reset();
3844 alter_info.flags= ALTER_ADD_INDEX;
3845 option_list= NULL;
3846 return false;
3847 }
3848 /*
3849 Add an UNIQUE or PRIMARY key which is a part of a column definition:
3850 CREATE TABLE t1 (a INT PRIMARY KEY);
3851 */
3852 void add_key_to_list(LEX_CSTRING *field_name,
3853 enum Key::Keytype type, bool check_exists);
3854 // Add a constraint as a part of CREATE TABLE or ALTER TABLE
3855 bool add_constraint(LEX_CSTRING *name, Virtual_column_info *constr,
3856 bool if_not_exists)
3857 {
3858 constr->name= *name;
3859 constr->flags= if_not_exists ?
3860 Alter_info::CHECK_CONSTRAINT_IF_NOT_EXISTS : 0;
3861 alter_info.check_constraint_list.push_back(constr);
3862 return false;
3863 }
3864 bool add_alter_list(const char *par_name, Virtual_column_info *expr,
3865 bool par_exists);
3866 void set_command(enum_sql_command command,
3867 DDL_options_st options)
3868 {
3869 sql_command= command;
3870 create_info.set(options);
3871 }
3872 void set_command(enum_sql_command command,
3873 uint scope,
3874 DDL_options_st options)
3875 {
3876 set_command(command, options);
3877 create_info.options|= scope; // HA_LEX_CREATE_TMP_TABLE or 0
3878 }
3879 bool check_create_options(DDL_options_st options)
3880 {
3881 if (options.or_replace() && options.if_not_exists())
3882 {
3883 my_error(ER_WRONG_USAGE, MYF(0), "OR REPLACE", "IF NOT EXISTS");
3884 return true;
3885 }
3886 return false;
3887 }
3888 bool set_create_options_with_check(DDL_options_st options)
3889 {
3890 create_info.set(options);
3891 return check_create_options(create_info);
3892 }
3893 bool add_create_options_with_check(DDL_options_st options)
3894 {
3895 create_info.add(options);
3896 return check_create_options(create_info);
3897 }
3898 bool sp_add_cfetch(THD *thd, const LEX_CSTRING *name);
3899
3900 bool set_command_with_check(enum_sql_command command,
3901 uint scope,
3902 DDL_options_st options)
3903 {
3904 set_command(command, scope, options);
3905 return check_create_options(options);
3906 }
3907 bool set_command_with_check(enum_sql_command command, DDL_options_st options)
3908 {
3909 set_command(command, options);
3910 return check_create_options(options);
3911 }
3912 /*
3913 DROP shares lex->create_info to store TEMPORARY and IF EXISTS options
3914 to save on extra initialization in lex_start().
3915 Add some wrappers, to avoid direct use of lex->create_info in the
3916 caller code processing DROP statements (which might look confusing).
3917 */
3918 bool tmp_table() const { return create_info.tmp_table(); }
3919 bool if_exists() const { return create_info.if_exists(); }
3920
3921 SELECT_LEX *exclude_last_select();
3922 bool add_unit_in_brackets(SELECT_LEX *nselect);
3923 void check_automatic_up(enum sub_select_type type);
3924 bool create_or_alter_view_finalize(THD *thd, Table_ident *table_ident);
3925 bool add_alter_view(THD *thd, uint16 algorithm, enum_view_suid suid,
3926 Table_ident *table_ident);
3927 bool add_create_view(THD *thd, DDL_options_st ddl,
3928 uint16 algorithm, enum_view_suid suid,
3929 Table_ident *table_ident);
3930
3931 bool add_grant_command(THD *thd, enum_sql_command sql_command_arg,
3932 stored_procedure_type type_arg);
3933
3934 Vers_parse_info &vers_get_info()
3935 {
3936 return create_info.vers_info;
3937 }
3938 sp_package *get_sp_package() const;
3939
3940 /**
3941 Check if the select is a simple select (not an union).
3942 @retval
3943 0 ok
3944 @retval
3945 1 error ; In this case the error messege is sent to the client
3946 */
3947 bool check_simple_select(const LEX_CSTRING *option)
3948 {
3949 if (current_select != &select_lex)
3950 {
3951 char command[80];
3952 strmake(command, option->str, MY_MIN(option->length, sizeof(command)-1));
3953 my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
3954 return true;
3955 }
3956 return false;
3957 }
3958
3959 void tvc_start()
3960 {
3961 field_list.empty();
3962 many_values.empty();
3963 insert_list= 0;
3964 }
3965 bool tvc_finalize();
3966 bool tvc_finalize_derived();
3967};
3968
3969
3970/**
3971 Set_signal_information is a container used in the parsed tree to represent
3972 the collection of assignments to condition items in the SIGNAL and RESIGNAL
3973 statements.
3974*/
3975class Set_signal_information
3976{
3977public:
3978 /** Empty default constructor, use clear() */
3979 Set_signal_information() {}
3980
3981 /** Copy constructor. */
3982 Set_signal_information(const Set_signal_information& set);
3983
3984 /** Destructor. */
3985 ~Set_signal_information()
3986 {}
3987
3988 /** Clear all items. */
3989 void clear();
3990
3991 /**
3992 For each condition item assignment, m_item[] contains the parsed tree
3993 that represents the expression assigned, if any.
3994 m_item[] is an array indexed by Diag_condition_item_name.
3995 */
3996 Item *m_item[LAST_DIAG_SET_PROPERTY+1];
3997};
3998
3999
4000/**
4001 The internal state of the syntax parser.
4002 This object is only available during parsing,
4003 and is private to the syntax parser implementation (sql_yacc.yy).
4004*/
4005class Yacc_state
4006{
4007public:
4008 Yacc_state()
4009 {
4010 reset();
4011 }
4012
4013 void reset()
4014 {
4015 yacc_yyss= NULL;
4016 yacc_yyvs= NULL;
4017 m_set_signal_info.clear();
4018 m_lock_type= TL_READ_DEFAULT;
4019 m_mdl_type= MDL_SHARED_READ;
4020 }
4021
4022 ~Yacc_state();
4023
4024 /**
4025 Reset part of the state which needs resetting before parsing
4026 substatement.
4027 */
4028 void reset_before_substatement()
4029 {
4030 m_lock_type= TL_READ_DEFAULT;
4031 m_mdl_type= MDL_SHARED_READ;
4032 }
4033
4034 /**
4035 Bison internal state stack, yyss, when dynamically allocated using
4036 my_yyoverflow().
4037 */
4038 uchar *yacc_yyss;
4039
4040 /**
4041 Bison internal semantic value stack, yyvs, when dynamically allocated using
4042 my_yyoverflow().
4043 */
4044 uchar *yacc_yyvs;
4045
4046 /**
4047 Fragments of parsed tree,
4048 used during the parsing of SIGNAL and RESIGNAL.
4049 */
4050 Set_signal_information m_set_signal_info;
4051
4052 /**
4053 Type of lock to be used for tables being added to the statement's
4054 table list in table_factor, table_alias_ref, single_multi and
4055 table_wild_one rules.
4056 Statements which use these rules but require lock type different
4057 from one specified by this member have to override it by using
4058 st_select_lex::set_lock_for_tables() method.
4059
4060 The default value of this member is TL_READ_DEFAULT. The only two
4061 cases in which we change it are:
4062 - When parsing SELECT HIGH_PRIORITY.
4063 - Rule for DELETE. In which we use this member to pass information
4064 about type of lock from delete to single_multi part of rule.
4065
4066 We should try to avoid introducing new use cases as we would like
4067 to get rid of this member eventually.
4068 */
4069 thr_lock_type m_lock_type;
4070
4071 /**
4072 The type of requested metadata lock for tables added to
4073 the statement table list.
4074 */
4075 enum_mdl_type m_mdl_type;
4076
4077 /*
4078 TODO: move more attributes from the LEX structure here.
4079 */
4080};
4081
4082/**
4083 Input parameters to the parser.
4084*/
4085struct Parser_input
4086{
4087 bool m_compute_digest;
4088
4089 Parser_input()
4090 : m_compute_digest(false)
4091 {}
4092};
4093
4094/**
4095 Internal state of the parser.
4096 The complete state consist of:
4097 - state data used during lexical parsing,
4098 - state data used during syntactic parsing.
4099*/
4100class Parser_state
4101{
4102public:
4103 Parser_state()
4104 : m_yacc()
4105 {}
4106
4107 /**
4108 Object initializer. Must be called before usage.
4109
4110 @retval FALSE OK
4111 @retval TRUE Error
4112 */
4113 bool init(THD *thd, char *buff, size_t length)
4114 {
4115 return m_lip.init(thd, buff, length);
4116 }
4117
4118 ~Parser_state()
4119 {}
4120
4121 Parser_input m_input;
4122 Lex_input_stream m_lip;
4123 Yacc_state m_yacc;
4124
4125 /**
4126 Current performance digest instrumentation.
4127 */
4128 PSI_digest_locker* m_digest_psi;
4129
4130 void reset(char *found_semicolon, unsigned int length)
4131 {
4132 m_lip.reset(found_semicolon, length);
4133 m_yacc.reset();
4134 }
4135};
4136
4137
4138extern sql_digest_state *
4139digest_add_token(sql_digest_state *state, uint token, LEX_YYSTYPE yylval);
4140
4141extern sql_digest_state *
4142digest_reduce_token(sql_digest_state *state, uint token_left, uint token_right);
4143
4144struct st_lex_local: public LEX, public Sql_alloc
4145{
4146};
4147
4148
4149/**
4150 An st_lex_local extension with automatic initialization for SP purposes.
4151 Used to parse sub-expressions and SP sub-statements.
4152
4153 This class is reused for:
4154 1. sp_head::reset_lex() based constructs
4155 - SP variable assignments (e.g. SET x=10;)
4156 - FOR loop conditions and index variable increments
4157 - Cursor statements
4158 - SP statements
4159 - SP function RETURN statements
4160 - CASE statements
4161 - REPEAT..UNTIL expressions
4162 - WHILE expressions
4163 - EXIT..WHEN and CONTINUE..WHEN statements
4164 2. sp_assignment_lex based constructs:
4165 - CURSOR parameter assignments
4166*/
4167class sp_lex_local: public st_lex_local
4168{
4169public:
4170 sp_lex_local(THD *thd, const LEX *oldlex)
4171 {
4172 /* Reset most stuff. */
4173 start(thd);
4174 /* Keep the parent SP stuff */
4175 sphead= oldlex->sphead;
4176 spcont= oldlex->spcont;
4177 /* Keep the parent trigger stuff too */
4178 trg_chistics= oldlex->trg_chistics;
4179 trg_table_fields.empty();
4180 sp_lex_in_use= false;
4181 }
4182};
4183
4184
4185/**
4186 An assignment specific LEX, which additionally has an Item (an expression)
4187 and an associated with the Item free_list, which is usually freed
4188 after the expression is calculated.
4189
4190 Note, consider changing some of sp_lex_local to sp_assignment_lex,
4191 as the latter allows to use a simpler grammar in sql_yacc.yy (IMO).
4192
4193 If the expression is simple (e.g. does not have function calls),
4194 then m_item and m_free_list point to the same Item.
4195
4196 If the expressions is complex (e.g. have function calls),
4197 then m_item points to the leftmost Item, while m_free_list points
4198 to the rightmost item.
4199 For example:
4200 f1(COALESCE(f2(10), f2(20)))
4201 - m_item points to Item_func_sp for f1 (the leftmost Item)
4202 - m_free_list points to Item_int for 20 (the rightmost Item)
4203
4204 Note, we could avoid storing m_item at all, as we can always reach
4205 the leftmost item from the rightmost item by iterating through m_free_list.
4206 But with a separate m_item the code should be faster.
4207*/
4208class sp_assignment_lex: public sp_lex_local
4209{
4210 Item *m_item; // The expression
4211 Item *m_free_list; // The associated free_list (sub-expressions)
4212public:
4213 sp_assignment_lex(THD *thd, LEX *oldlex)
4214 :sp_lex_local(thd, oldlex),
4215 m_item(NULL),
4216 m_free_list(NULL)
4217 { }
4218 void set_item_and_free_list(Item *item, Item *free_list)
4219 {
4220 m_item= item;
4221 m_free_list= free_list;
4222 }
4223 Item *get_item() const
4224 {
4225 return m_item;
4226 }
4227 Item *get_free_list() const
4228 {
4229 return m_free_list;
4230 }
4231};
4232
4233
4234extern void lex_init(void);
4235extern void lex_free(void);
4236extern void lex_start(THD *thd);
4237extern void lex_end(LEX *lex);
4238extern void lex_end_stage1(LEX *lex);
4239extern void lex_end_stage2(LEX *lex);
4240void end_lex_with_single_table(THD *thd, TABLE *table, LEX *old_lex);
4241int init_lex_with_single_table(THD *thd, TABLE *table, LEX *lex);
4242extern int MYSQLlex(union YYSTYPE *yylval, THD *thd);
4243extern int ORAlex(union YYSTYPE *yylval, THD *thd);
4244
4245extern void trim_whitespace(CHARSET_INFO *cs, LEX_CSTRING *str, size_t * prefix_length = 0);
4246
4247extern bool is_lex_native_function(const LEX_CSTRING *name);
4248extern bool is_native_function(THD *thd, const LEX_CSTRING *name);
4249extern bool is_native_function_with_warn(THD *thd, const LEX_CSTRING *name);
4250
4251/**
4252 @} (End of group Semantic_Analysis)
4253*/
4254
4255void my_missing_function_error(const LEX_CSTRING &token, const char *name);
4256bool is_keyword(const char *name, uint len);
4257int set_statement_var_if_exists(THD *thd, const char *var_name,
4258 size_t var_name_length, ulonglong value);
4259
4260Virtual_column_info *add_virtual_expression(THD *thd, Item *expr);
4261Item* handle_sql2003_note184_exception(THD *thd, Item* left, bool equal,
4262 Item *expr);
4263
4264void sp_create_assignment_lex(THD *thd, bool no_lookahead);
4265bool sp_create_assignment_instr(THD *thd, bool no_lookahead);
4266
4267#endif /* MYSQL_SERVER */
4268#endif /* SQL_LEX_INCLUDED */
4269