1 /* Copyright (c) 2000, 2019, Oracle and/or its affiliates.
2 Copyright (c) 2009, 2021, 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-1335 USA */
16
17
18 /* A lexical scanner on a temporary buffer with a yacc interface */
19
20 #define MYSQL_LEX 1
21 #include "mariadb.h"
22 #include "sql_priv.h"
23 #include "sql_class.h" // sql_lex.h: SQLCOM_END
24 #include "sql_lex.h"
25 #include "sql_parse.h" // add_to_list
26 #include "item_create.h"
27 #include <m_ctype.h>
28 #include <hash.h>
29 #include "sp_head.h"
30 #include "sp.h"
31 #include "sql_select.h"
32 #include "sql_cte.h"
33 #include "sql_signal.h"
34 #include "sql_derived.h"
35 #include "sql_truncate.h" // Sql_cmd_truncate_table
36 #include "sql_admin.h" // Sql_cmd_analyze/Check..._table
37 #include "sql_partition.h"
38 #include "sql_partition_admin.h" // Sql_cmd_alter_table_*_part
39 #include "event_parse_data.h"
40
parse_error(uint err_number)41 void LEX::parse_error(uint err_number)
42 {
43 thd->parse_error(err_number);
44 }
45
46
47 /**
48 LEX_STRING constant for null-string to be used in parser and other places.
49 */
50 const LEX_STRING empty_lex_str= {(char *) "", 0};
51 const LEX_CSTRING null_clex_str= {NULL, 0};
52 const LEX_CSTRING empty_clex_str= {"", 0};
53 const LEX_CSTRING star_clex_str= {"*", 1};
54 const LEX_CSTRING param_clex_str= {"?", 1};
55
56 /**
57 @note The order of the elements of this array must correspond to
58 the order of elements in enum_binlog_stmt_unsafe.
59 */
60 const int
61 Query_tables_list::binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT] =
62 {
63 ER_BINLOG_UNSAFE_LIMIT,
64 ER_BINLOG_UNSAFE_INSERT_DELAYED,
65 ER_BINLOG_UNSAFE_SYSTEM_TABLE,
66 ER_BINLOG_UNSAFE_AUTOINC_COLUMNS,
67 ER_BINLOG_UNSAFE_UDF,
68 ER_BINLOG_UNSAFE_SYSTEM_VARIABLE,
69 ER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
70 ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS,
71 ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
72 ER_BINLOG_UNSAFE_MIXED_STATEMENT,
73 ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT,
74 ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE,
75 ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT,
76 ER_BINLOG_UNSAFE_REPLACE_SELECT,
77 ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT,
78 ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT,
79 ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC,
80 ER_BINLOG_UNSAFE_UPDATE_IGNORE,
81 ER_BINLOG_UNSAFE_INSERT_TWO_KEYS,
82 ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST
83 };
84
85
86 /* Longest standard keyword name */
87
88 #define TOCK_NAME_LENGTH 24
89
90 /*
91 The following data is based on the latin1 character set, and is only
92 used when comparing keywords
93 */
94
95 static uchar to_upper_lex[]=
96 {
97 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
98 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
99 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
100 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
101 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
102 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
103 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
104 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127,
105 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
106 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
107 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
108 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
109 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
110 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
111 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
112 208,209,210,211,212,213,214,247,216,217,218,219,220,221,222,255
113 };
114
115 /*
116 Names of the index hints (for error messages). Keep in sync with
117 index_hint_type
118 */
119
120 const char * index_hint_type_name[] =
121 {
122 "IGNORE INDEX",
123 "USE INDEX",
124 "FORCE INDEX"
125 };
126
lex_casecmp(const char * s,const char * t,uint len)127 inline int lex_casecmp(const char *s, const char *t, uint len)
128 {
129 while (len-- != 0 &&
130 to_upper_lex[(uchar) *s++] == to_upper_lex[(uchar) *t++]) ;
131 return (int) len+1;
132 }
133
134 #include <lex_hash.h>
135
136
lex_init(void)137 void lex_init(void)
138 {
139 uint i;
140 DBUG_ENTER("lex_init");
141 for (i=0 ; i < array_elements(symbols) ; i++)
142 symbols[i].length=(uchar) strlen(symbols[i].name);
143 for (i=0 ; i < array_elements(sql_functions) ; i++)
144 sql_functions[i].length=(uchar) strlen(sql_functions[i].name);
145
146 DBUG_VOID_RETURN;
147 }
148
149
lex_free(void)150 void lex_free(void)
151 { // Call this when daemon ends
152 DBUG_ENTER("lex_free");
153 DBUG_VOID_RETURN;
154 }
155
156 /**
157 Initialize lex object for use in fix_fields and parsing.
158
159 SYNOPSIS
160 init_lex_with_single_table()
161 @param thd The thread object
162 @param table The table object
163 @return Operation status
164 @retval TRUE An error occurred, memory allocation error
165 @retval FALSE Ok
166
167 DESCRIPTION
168 This function is used to initialize a lex object on the
169 stack for use by fix_fields and for parsing. In order to
170 work properly it also needs to initialize the
171 Name_resolution_context object of the lexer.
172 Finally it needs to set a couple of variables to ensure
173 proper functioning of fix_fields.
174 */
175
176 int
init_lex_with_single_table(THD * thd,TABLE * table,LEX * lex)177 init_lex_with_single_table(THD *thd, TABLE *table, LEX *lex)
178 {
179 TABLE_LIST *table_list;
180 Table_ident *table_ident;
181 SELECT_LEX *select_lex= lex->first_select_lex();
182 Name_resolution_context *context= &select_lex->context;
183 /*
184 We will call the parser to create a part_info struct based on the
185 partition string stored in the frm file.
186 We will use a local lex object for this purpose. However we also
187 need to set the Name_resolution_object for this lex object. We
188 do this by using add_table_to_list where we add the table that
189 we're working with to the Name_resolution_context.
190 */
191 thd->lex= lex;
192 lex_start(thd);
193 context->init();
194 if (unlikely((!(table_ident= new Table_ident(thd,
195 &table->s->db,
196 &table->s->table_name,
197 TRUE)))) ||
198 (unlikely(!(table_list= select_lex->add_table_to_list(thd,
199 table_ident,
200 NULL,
201 0)))))
202 return TRUE;
203 context->resolve_in_table_list_only(table_list);
204 lex->use_only_table_context= TRUE;
205 lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VCOL_EXPR;
206 select_lex->cur_pos_in_select_list= UNDEF_POS;
207 table->map= 1; //To ensure correct calculation of const item
208 table_list->table= table;
209 table_list->cacheable_table= false;
210 lex->create_last_non_select_table= table_list;
211 return FALSE;
212 }
213
214 /**
215 End use of local lex with single table
216
217 SYNOPSIS
218 end_lex_with_single_table()
219 @param thd The thread object
220 @param table The table object
221 @param old_lex The real lex object connected to THD
222
223 DESCRIPTION
224 This function restores the real lex object after calling
225 init_lex_with_single_table and also restores some table
226 variables temporarily set.
227 */
228
229 void
end_lex_with_single_table(THD * thd,TABLE * table,LEX * old_lex)230 end_lex_with_single_table(THD *thd, TABLE *table, LEX *old_lex)
231 {
232 LEX *lex= thd->lex;
233 table->map= 0;
234 table->get_fields_in_item_tree= FALSE;
235 lex_end(lex);
236 thd->lex= old_lex;
237 }
238
239
240 void
reset()241 st_parsing_options::reset()
242 {
243 allows_variable= TRUE;
244 lookup_keywords_after_qualifier= false;
245 }
246
247
248 /**
249 Perform initialization of Lex_input_stream instance.
250
251 Basically, a buffer for pre-processed query. This buffer should be large
252 enough to keep multi-statement query. The allocation is done once in
253 Lex_input_stream::init() in order to prevent memory pollution when
254 the server is processing large multi-statement queries.
255 */
256
init(THD * thd,char * buff,size_t length)257 bool Lex_input_stream::init(THD *thd,
258 char* buff,
259 size_t length)
260 {
261 DBUG_EXECUTE_IF("bug42064_simulate_oom",
262 DBUG_SET("+d,simulate_out_of_memory"););
263
264 m_cpp_buf= (char*) thd->alloc(length + 1);
265
266 DBUG_EXECUTE_IF("bug42064_simulate_oom",
267 DBUG_SET("-d,bug42064_simulate_oom"););
268
269 if (m_cpp_buf == NULL)
270 return true;
271
272 m_thd= thd;
273 reset(buff, length);
274
275 return false;
276 }
277
278
279 /**
280 Prepare Lex_input_stream instance state for use for handling next SQL statement.
281
282 It should be called between two statements in a multi-statement query.
283 The operation resets the input stream to the beginning-of-parse state,
284 but does not reallocate m_cpp_buf.
285 */
286
287 void
reset(char * buffer,size_t length)288 Lex_input_stream::reset(char *buffer, size_t length)
289 {
290 yylineno= 1;
291 lookahead_token= -1;
292 lookahead_yylval= NULL;
293 m_ptr= buffer;
294 m_tok_start= NULL;
295 m_tok_end= NULL;
296 m_end_of_query= buffer + length;
297 m_tok_start_prev= NULL;
298 m_buf= buffer;
299 m_buf_length= length;
300 m_echo= TRUE;
301 m_cpp_tok_start= NULL;
302 m_cpp_tok_start_prev= NULL;
303 m_cpp_tok_end= NULL;
304 m_body_utf8= NULL;
305 m_cpp_utf8_processed_ptr= NULL;
306 next_state= MY_LEX_START;
307 found_semicolon= NULL;
308 ignore_space= MY_TEST(m_thd->variables.sql_mode & MODE_IGNORE_SPACE);
309 stmt_prepare_mode= FALSE;
310 multi_statements= TRUE;
311 in_comment=NO_COMMENT;
312 m_underscore_cs= NULL;
313 m_cpp_ptr= m_cpp_buf;
314 }
315
316
317 /**
318 The operation is called from the parser in order to
319 1) designate the intention to have utf8 body;
320 1) Indicate to the lexer that we will need a utf8 representation of this
321 statement;
322 2) Determine the beginning of the body.
323
324 @param thd Thread context.
325 @param begin_ptr Pointer to the start of the body in the pre-processed
326 buffer.
327 */
328
body_utf8_start(THD * thd,const char * begin_ptr)329 void Lex_input_stream::body_utf8_start(THD *thd, const char *begin_ptr)
330 {
331 DBUG_ASSERT(begin_ptr);
332 DBUG_ASSERT(m_cpp_buf <= begin_ptr && begin_ptr <= m_cpp_buf + m_buf_length);
333
334 size_t body_utf8_length= get_body_utf8_maximum_length(thd);
335
336 m_body_utf8= (char *) thd->alloc(body_utf8_length + 1);
337 m_body_utf8_ptr= m_body_utf8;
338 *m_body_utf8_ptr= 0;
339
340 m_cpp_utf8_processed_ptr= begin_ptr;
341 }
342
343
get_body_utf8_maximum_length(THD * thd)344 size_t Lex_input_stream::get_body_utf8_maximum_length(THD *thd)
345 {
346 /*
347 String literals can grow during escaping:
348 1a. Character string '<TAB>' can grow to '\t', 3 bytes to 4 bytes growth.
349 1b. Character string '1000 times <TAB>' grows from
350 1002 to 2002 bytes (including quotes), which gives a little bit
351 less than 2 times growth.
352 "2" should be a reasonable multiplier that safely covers escaping needs.
353 */
354 return (m_buf_length / thd->variables.character_set_client->mbminlen) *
355 my_charset_utf8_bin.mbmaxlen * 2/*for escaping*/;
356 }
357
358
359 /**
360 @brief The operation appends unprocessed part of pre-processed buffer till
361 the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to end_ptr.
362
363 The idea is that some tokens in the pre-processed buffer (like character
364 set introducers) should be skipped.
365
366 Example:
367 CPP buffer: SELECT 'str1', _latin1 'str2';
368 m_cpp_utf8_processed_ptr -- points at the "SELECT ...";
369 In order to skip "_latin1", the following call should be made:
370 body_utf8_append(<pointer to "_latin1 ...">, <pointer to " 'str2'...">)
371
372 @param ptr Pointer in the pre-processed buffer, which specifies the
373 end of the chunk, which should be appended to the utf8
374 body.
375 @param end_ptr Pointer in the pre-processed buffer, to which
376 m_cpp_utf8_processed_ptr will be set in the end of the
377 operation.
378 */
379
body_utf8_append(const char * ptr,const char * end_ptr)380 void Lex_input_stream::body_utf8_append(const char *ptr,
381 const char *end_ptr)
382 {
383 DBUG_ASSERT(m_cpp_buf <= ptr && ptr <= m_cpp_buf + m_buf_length);
384 DBUG_ASSERT(m_cpp_buf <= end_ptr && end_ptr <= m_cpp_buf + m_buf_length);
385
386 if (!m_body_utf8)
387 return;
388
389 if (m_cpp_utf8_processed_ptr >= ptr)
390 return;
391
392 size_t bytes_to_copy= ptr - m_cpp_utf8_processed_ptr;
393
394 memcpy(m_body_utf8_ptr, m_cpp_utf8_processed_ptr, bytes_to_copy);
395 m_body_utf8_ptr += bytes_to_copy;
396 *m_body_utf8_ptr= 0;
397
398 m_cpp_utf8_processed_ptr= end_ptr;
399 }
400
401 /**
402 The operation appends unprocessed part of the pre-processed buffer till
403 the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to ptr.
404
405 @param ptr Pointer in the pre-processed buffer, which specifies the end
406 of the chunk, which should be appended to the utf8 body.
407 */
408
body_utf8_append(const char * ptr)409 void Lex_input_stream::body_utf8_append(const char *ptr)
410 {
411 body_utf8_append(ptr, ptr);
412 }
413
414 /**
415 The operation converts the specified text literal to the utf8 and appends
416 the result to the utf8-body.
417
418 @param thd Thread context.
419 @param txt Text literal.
420 @param txt_cs Character set of the text literal.
421 @param end_ptr Pointer in the pre-processed buffer, to which
422 m_cpp_utf8_processed_ptr will be set in the end of the
423 operation.
424 */
425
426 void
body_utf8_append_ident(THD * thd,const Lex_string_with_metadata_st * txt,const char * end_ptr)427 Lex_input_stream::body_utf8_append_ident(THD *thd,
428 const Lex_string_with_metadata_st *txt,
429 const char *end_ptr)
430 {
431 if (!m_cpp_utf8_processed_ptr)
432 return;
433
434 LEX_CSTRING utf_txt;
435 thd->make_text_string_sys(&utf_txt, txt); // QQ: check return value?
436
437 /* NOTE: utf_txt.length is in bytes, not in symbols. */
438 memcpy(m_body_utf8_ptr, utf_txt.str, utf_txt.length);
439 m_body_utf8_ptr += utf_txt.length;
440 *m_body_utf8_ptr= 0;
441
442 m_cpp_utf8_processed_ptr= end_ptr;
443 }
444
445
446
447
448 extern "C" {
449
450 /**
451 Escape a character. Consequently puts "escape" and "wc" characters into
452 the destination utf8 string.
453 @param cs - the character set (utf8)
454 @param escape - the escape character (backslash, single quote, double quote)
455 @param wc - the character to be escaped
456 @param str - the destination string
457 @param end - the end of the destination string
458 @returns - a code according to the wc_mb() convension.
459 */
my_wc_mb_utf8_with_escape(CHARSET_INFO * cs,my_wc_t escape,my_wc_t wc,uchar * str,uchar * end)460 int my_wc_mb_utf8_with_escape(CHARSET_INFO *cs, my_wc_t escape, my_wc_t wc,
461 uchar *str, uchar *end)
462 {
463 DBUG_ASSERT(escape > 0);
464 if (str + 1 >= end)
465 return MY_CS_TOOSMALL2; // Not enough space, need at least two bytes.
466 *str= (uchar)escape;
467 int cnvres= my_charset_utf8_handler.wc_mb(cs, wc, str + 1, end);
468 if (cnvres > 0)
469 return cnvres + 1; // The character was normally put
470 if (cnvres == MY_CS_ILUNI)
471 return MY_CS_ILUNI; // Could not encode "wc" (e.g. non-BMP character)
472 DBUG_ASSERT(cnvres <= MY_CS_TOOSMALL);
473 return cnvres - 1; // Not enough space
474 }
475
476
477 /**
478 Optionally escape a character.
479 If "escape" is non-zero, then both "escape" and "wc" are put to
480 the destination string. Otherwise, only "wc" is put.
481 @param cs - the character set (utf8)
482 @param wc - the character to be optionally escaped
483 @param escape - the escape character, or 0
484 @param ewc - the escaped replacement of "wc" (e.g. 't' for '\t')
485 @param str - the destination string
486 @param end - the end of the destination string
487 @returns - a code according to the wc_mb() conversion.
488 */
my_wc_mb_utf8_opt_escape(CHARSET_INFO * cs,my_wc_t wc,my_wc_t escape,my_wc_t ewc,uchar * str,uchar * end)489 int my_wc_mb_utf8_opt_escape(CHARSET_INFO *cs,
490 my_wc_t wc, my_wc_t escape, my_wc_t ewc,
491 uchar *str, uchar *end)
492 {
493 return escape ? my_wc_mb_utf8_with_escape(cs, escape, ewc, str, end) :
494 my_charset_utf8_handler.wc_mb(cs, wc, str, end);
495 }
496
497 /**
498 Encode a character with optional backlash escaping and quote escaping.
499 Quote marks are escaped using another quote mark.
500 Additionally, if "escape" is non-zero, then special characters are
501 also escaped using "escape".
502 Otherwise (if "escape" is zero, e.g. in case of MODE_NO_BACKSLASH_ESCAPES),
503 then special characters are not escaped and handled as normal characters.
504
505 @param cs - the character set (utf8)
506 @param wc - the character to be encoded
507 @param str - the destination string
508 @param end - the end of the destination string
509 @param sep - the string delimiter (e.g. ' or ")
510 @param escape - the escape character (backslash, or 0)
511 @returns - a code according to the wc_mb() convension.
512 */
my_wc_mb_utf8_escape(CHARSET_INFO * cs,my_wc_t wc,uchar * str,uchar * end,my_wc_t sep,my_wc_t escape)513 int my_wc_mb_utf8_escape(CHARSET_INFO *cs, my_wc_t wc, uchar *str, uchar *end,
514 my_wc_t sep, my_wc_t escape)
515 {
516 DBUG_ASSERT(escape == 0 || escape == '\\');
517 DBUG_ASSERT(sep == '"' || sep == '\'');
518 switch (wc) {
519 case 0: return my_wc_mb_utf8_opt_escape(cs, wc, escape, '0', str, end);
520 case '\t': return my_wc_mb_utf8_opt_escape(cs, wc, escape, 't', str, end);
521 case '\r': return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'r', str, end);
522 case '\n': return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'n', str, end);
523 case '\032': return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'Z', str, end);
524 case '\'':
525 case '\"':
526 if (wc == sep)
527 return my_wc_mb_utf8_with_escape(cs, wc, wc, str, end);
528 }
529 return my_charset_utf8_handler.wc_mb(cs, wc, str, end); // No escaping needed
530 }
531
532
533 /** wc_mb() compatible routines for all sql_mode and delimiter combinations */
my_wc_mb_utf8_escape_single_quote_and_backslash(CHARSET_INFO * cs,my_wc_t wc,uchar * str,uchar * end)534 int my_wc_mb_utf8_escape_single_quote_and_backslash(CHARSET_INFO *cs,
535 my_wc_t wc,
536 uchar *str, uchar *end)
537 {
538 return my_wc_mb_utf8_escape(cs, wc, str, end, '\'', '\\');
539 }
540
541
my_wc_mb_utf8_escape_double_quote_and_backslash(CHARSET_INFO * cs,my_wc_t wc,uchar * str,uchar * end)542 int my_wc_mb_utf8_escape_double_quote_and_backslash(CHARSET_INFO *cs,
543 my_wc_t wc,
544 uchar *str, uchar *end)
545 {
546 return my_wc_mb_utf8_escape(cs, wc, str, end, '"', '\\');
547 }
548
549
my_wc_mb_utf8_escape_single_quote(CHARSET_INFO * cs,my_wc_t wc,uchar * str,uchar * end)550 int my_wc_mb_utf8_escape_single_quote(CHARSET_INFO *cs, my_wc_t wc,
551 uchar *str, uchar *end)
552 {
553 return my_wc_mb_utf8_escape(cs, wc, str, end, '\'', 0);
554 }
555
556
my_wc_mb_utf8_escape_double_quote(CHARSET_INFO * cs,my_wc_t wc,uchar * str,uchar * end)557 int my_wc_mb_utf8_escape_double_quote(CHARSET_INFO *cs, my_wc_t wc,
558 uchar *str, uchar *end)
559 {
560 return my_wc_mb_utf8_escape(cs, wc, str, end, '"', 0);
561 }
562
563 }; // End of extern "C"
564
565
566 /**
567 Get an escaping function, depending on the current sql_mode and the
568 string separator.
569 */
570 my_charset_conv_wc_mb
get_escape_func(THD * thd,my_wc_t sep) const571 Lex_input_stream::get_escape_func(THD *thd, my_wc_t sep) const
572 {
573 return thd->backslash_escapes() ?
574 (sep == '"' ? my_wc_mb_utf8_escape_double_quote_and_backslash:
575 my_wc_mb_utf8_escape_single_quote_and_backslash) :
576 (sep == '"' ? my_wc_mb_utf8_escape_double_quote:
577 my_wc_mb_utf8_escape_single_quote);
578 }
579
580
581 /**
582 Append a text literal to the end of m_body_utf8.
583 The string is escaped according to the current sql_mode and the
584 string delimiter (e.g. ' or ").
585
586 @param thd - current THD
587 @param txt - the string to be appended to m_body_utf8.
588 Note, the string must be already unescaped.
589 @param cs - the character set of the string
590 @param end_ptr - m_cpp_utf8_processed_ptr will be set to this value
591 (see body_utf8_append_ident for details)
592 @param sep - the string delimiter (single or double quote)
593 */
body_utf8_append_escape(THD * thd,const LEX_CSTRING * txt,CHARSET_INFO * cs,const char * end_ptr,my_wc_t sep)594 void Lex_input_stream::body_utf8_append_escape(THD *thd,
595 const LEX_CSTRING *txt,
596 CHARSET_INFO *cs,
597 const char *end_ptr,
598 my_wc_t sep)
599 {
600 DBUG_ASSERT(sep == '\'' || sep == '"');
601 if (!m_cpp_utf8_processed_ptr)
602 return;
603 uint errors;
604 /**
605 We previously alloced m_body_utf8 to be able to store the query with all
606 strings properly escaped. See get_body_utf8_maximum_length().
607 So here we have guaranteedly enough space to append any string literal
608 with escaping. Passing txt->length*2 as "available space" is always safe.
609 For better safety purposes we could calculate get_body_utf8_maximum_length()
610 every time we append a string, but this would affect performance negatively,
611 so let's check that we don't get beyond the allocated buffer in
612 debug build only.
613 */
614 DBUG_ASSERT(m_body_utf8 + get_body_utf8_maximum_length(thd) >=
615 m_body_utf8_ptr + txt->length * 2);
616 uint32 cnv_length= my_convert_using_func(m_body_utf8_ptr, txt->length * 2,
617 &my_charset_utf8_general_ci,
618 get_escape_func(thd, sep),
619 txt->str, txt->length,
620 cs, cs->cset->mb_wc,
621 &errors);
622 m_body_utf8_ptr+= cnv_length;
623 *m_body_utf8_ptr= 0;
624 m_cpp_utf8_processed_ptr= end_ptr;
625 }
626
627
add_digest_token(uint token,LEX_YYSTYPE yylval)628 void Lex_input_stream::add_digest_token(uint token, LEX_YYSTYPE yylval)
629 {
630 if (m_digest != NULL)
631 {
632 m_digest= digest_add_token(m_digest, token, yylval);
633 }
634 }
635
reduce_digest_token(uint token_left,uint token_right)636 void Lex_input_stream::reduce_digest_token(uint token_left, uint token_right)
637 {
638 if (m_digest != NULL)
639 {
640 m_digest= digest_reduce_token(m_digest, token_left, token_right);
641 }
642 }
643
644 /**
645 lex starting operations for builtin select collected together
646 */
647
lex_start(LEX * plex)648 void SELECT_LEX::lex_start(LEX *plex)
649 {
650 SELECT_LEX_UNIT *unit= &plex->unit;
651 /* 'parent_lex' is used in init_query() so it must be before it. */
652 parent_lex= plex;
653 init_query();
654 master= unit;
655 prev= &unit->slave;
656 link_next= slave= next= 0;
657 link_prev= (st_select_lex_node**)&(plex->all_selects_list);
658 DBUG_ASSERT(!group_list_ptrs);
659 select_number= 1;
660 in_sum_expr=0;
661 ftfunc_list_alloc.empty();
662 ftfunc_list= &ftfunc_list_alloc;
663 group_list.empty();
664 order_list.empty();
665 gorder_list.empty();
666 }
667
lex_start(THD * thd)668 void lex_start(THD *thd)
669 {
670 DBUG_ENTER("lex_start");
671 thd->lex->start(thd);
672 DBUG_VOID_RETURN;
673 }
674
675
676 /*
677 This is called before every query that is to be parsed.
678 Because of this, it's critical to not do too much things here.
679 (We already do too much here)
680 */
681
start(THD * thd_arg)682 void LEX::start(THD *thd_arg)
683 {
684 DBUG_ENTER("LEX::start");
685 DBUG_PRINT("info", ("This: %p thd_arg->lex: %p", this, thd_arg->lex));
686
687 thd= unit.thd= thd_arg;
688 stmt_lex= this; // default, should be rewritten for VIEWs And CTEs
689
690 DBUG_ASSERT(!explain);
691
692 builtin_select.lex_start(this);
693 lex_options= 0;
694 context_stack.empty();
695 //empty select_stack
696 select_stack_top= 0;
697 unit.init_query();
698 current_select_number= 0;
699 curr_with_clause= 0;
700 with_clauses_list= 0;
701 with_clauses_list_last_next= &with_clauses_list;
702 clone_spec_offset= 0;
703 create_view= NULL;
704 field_list.empty();
705 value_list.empty();
706 update_list.empty();
707 set_var_list.empty();
708 param_list.empty();
709 view_list.empty();
710 with_column_list.empty();
711 with_persistent_for_clause= FALSE;
712 column_list= NULL;
713 index_list= NULL;
714 prepared_stmt.lex_start();
715 auxiliary_table_list.empty();
716 unit.next= unit.master= unit.link_next= unit.return_to= 0;
717 unit.prev= unit.link_prev= 0;
718 unit.slave= current_select= all_selects_list= &builtin_select;
719 sql_cache= LEX::SQL_CACHE_UNSPECIFIED;
720 describe= 0;
721 analyze_stmt= 0;
722 explain_json= false;
723 context_analysis_only= 0;
724 derived_tables= 0;
725 with_cte_resolution= false;
726 only_cte_resolution= false;
727 safe_to_cache_query= 1;
728 parsing_options.reset();
729 empty_field_list_on_rset= 0;
730 part_info= 0;
731 m_sql_cmd= NULL;
732 duplicates= DUP_ERROR;
733 ignore= 0;
734 spname= NULL;
735 spcont= NULL;
736 proc_list.first= 0;
737 escape_used= FALSE;
738 default_used= FALSE;
739 query_tables= 0;
740 reset_query_tables_list(FALSE);
741 clause_that_disallows_subselect= NULL;
742 selects_allow_into= FALSE;
743 selects_allow_procedure= FALSE;
744 use_only_table_context= FALSE;
745 parse_vcol_expr= FALSE;
746 check_exists= FALSE;
747 create_info.lex_start();
748 verbose= 0;
749
750 name= null_clex_str;
751 event_parse_data= NULL;
752 profile_options= PROFILE_NONE;
753 nest_level= 0;
754 builtin_select.nest_level_base= &unit;
755 allow_sum_func.clear_all();
756 in_sum_func= NULL;
757
758 used_tables= 0;
759 table_type= TABLE_TYPE_UNKNOWN;
760 reset_slave_info.all= false;
761 limit_rows_examined= 0;
762 limit_rows_examined_cnt= ULONGLONG_MAX;
763 var_list.empty();
764 stmt_var_list.empty();
765 proc_list.elements=0;
766
767 save_group_list.empty();
768 save_order_list.empty();
769 win_ref= NULL;
770 win_frame= NULL;
771 frame_top_bound= NULL;
772 frame_bottom_bound= NULL;
773 win_spec= NULL;
774
775 vers_conditions.empty();
776 period_conditions.empty();
777
778 is_lex_started= TRUE;
779
780 next_is_main= FALSE;
781 next_is_down= FALSE;
782
783 wild= 0;
784 exchange= 0;
785
786 DBUG_VOID_RETURN;
787 }
788
lex_end(LEX * lex)789 void lex_end(LEX *lex)
790 {
791 DBUG_ENTER("lex_end");
792 DBUG_PRINT("enter", ("lex: %p", lex));
793
794 lex_unlock_plugins(lex);
795 lex_end_nops(lex);
796
797 DBUG_VOID_RETURN;
798 }
799
lex_unlock_plugins(LEX * lex)800 void lex_unlock_plugins(LEX *lex)
801 {
802 DBUG_ENTER("lex_unlock_plugins");
803
804 /* release used plugins */
805 if (lex->plugins.elements) /* No function call and no mutex if no plugins. */
806 {
807 plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer,
808 lex->plugins.elements);
809 }
810 reset_dynamic(&lex->plugins);
811 DBUG_VOID_RETURN;
812 }
813
814 /*
815 Don't delete lex->sphead, it'll be needed for EXECUTE.
816 Note that of all statements that populate lex->sphead
817 only SQLCOM_COMPOUND can be PREPAREd
818
819 MASTER INFO parameters (or state) is normally cleared towards the end
820 of a statement. But in case of PS, the state needs to be preserved during
821 its lifetime and should only be cleared on PS close or deallocation.
822 */
lex_end_nops(LEX * lex)823 void lex_end_nops(LEX *lex)
824 {
825 DBUG_ENTER("lex_end_nops");
826 sp_head::destroy(lex->sphead);
827 lex->sphead= NULL;
828
829 /* Reset LEX_MASTER_INFO */
830 lex->mi.reset(lex->sql_command == SQLCOM_CHANGE_MASTER);
831 delete_dynamic(&lex->delete_gtid_domain);
832
833 DBUG_VOID_RETURN;
834 }
835
~Yacc_state()836 Yacc_state::~Yacc_state()
837 {
838 if (yacc_yyss)
839 {
840 my_free(yacc_yyss);
841 my_free(yacc_yyvs);
842 }
843 }
844
find_keyword(Lex_ident_cli_st * kwd,uint len,bool function)845 int Lex_input_stream::find_keyword(Lex_ident_cli_st *kwd,
846 uint len, bool function)
847 {
848 const char *tok= m_tok_start;
849
850 SYMBOL *symbol= get_hash_symbol(tok, len, function);
851 if (symbol)
852 {
853 kwd->set_keyword(tok, len);
854 DBUG_ASSERT(tok >= get_buf());
855 DBUG_ASSERT(tok < get_end_of_query());
856
857 if (m_thd->variables.sql_mode & MODE_ORACLE)
858 {
859 switch (symbol->tok) {
860 case BEGIN_MARIADB_SYM: return BEGIN_ORACLE_SYM;
861 case BLOB_MARIADB_SYM: return BLOB_ORACLE_SYM;
862 case BODY_MARIADB_SYM: return BODY_ORACLE_SYM;
863 case CLOB_MARIADB_SYM: return CLOB_ORACLE_SYM;
864 case CONTINUE_MARIADB_SYM: return CONTINUE_ORACLE_SYM;
865 case DECLARE_MARIADB_SYM: return DECLARE_ORACLE_SYM;
866 case DECODE_MARIADB_SYM: return DECODE_ORACLE_SYM;
867 case ELSEIF_MARIADB_SYM: return ELSEIF_ORACLE_SYM;
868 case ELSIF_MARIADB_SYM: return ELSIF_ORACLE_SYM;
869 case EXCEPTION_MARIADB_SYM: return EXCEPTION_ORACLE_SYM;
870 case EXIT_MARIADB_SYM: return EXIT_ORACLE_SYM;
871 case GOTO_MARIADB_SYM: return GOTO_ORACLE_SYM;
872 case NUMBER_MARIADB_SYM: return NUMBER_ORACLE_SYM;
873 case OTHERS_MARIADB_SYM: return OTHERS_ORACLE_SYM;
874 case PACKAGE_MARIADB_SYM: return PACKAGE_ORACLE_SYM;
875 case RAISE_MARIADB_SYM: return RAISE_ORACLE_SYM;
876 case RAW_MARIADB_SYM: return RAW_ORACLE_SYM;
877 case RETURN_MARIADB_SYM: return RETURN_ORACLE_SYM;
878 case ROWTYPE_MARIADB_SYM: return ROWTYPE_ORACLE_SYM;
879 case VARCHAR2_MARIADB_SYM: return VARCHAR2_ORACLE_SYM;
880 }
881 }
882
883 if ((symbol->tok == NOT_SYM) &&
884 (m_thd->variables.sql_mode & MODE_HIGH_NOT_PRECEDENCE))
885 return NOT2_SYM;
886 if ((symbol->tok == OR2_SYM) &&
887 (m_thd->variables.sql_mode & MODE_PIPES_AS_CONCAT))
888 {
889 return (m_thd->variables.sql_mode & MODE_ORACLE) ?
890 ORACLE_CONCAT_SYM : MYSQL_CONCAT_SYM;
891 }
892
893 return symbol->tok;
894 }
895 return 0;
896 }
897
898 /*
899 Check if name is a keyword
900
901 SYNOPSIS
902 is_keyword()
903 name checked name (must not be empty)
904 len length of checked name
905
906 RETURN VALUES
907 0 name is a keyword
908 1 name isn't a keyword
909 */
910
is_keyword(const char * name,uint len)911 bool is_keyword(const char *name, uint len)
912 {
913 DBUG_ASSERT(len != 0);
914 return get_hash_symbol(name,len,0)!=0;
915 }
916
917 /**
918 Check if name is a sql function
919
920 @param name checked name
921
922 @return is this a native function or not
923 @retval 0 name is a function
924 @retval 1 name isn't a function
925 */
926
is_lex_native_function(const LEX_CSTRING * name)927 bool is_lex_native_function(const LEX_CSTRING *name)
928 {
929 DBUG_ASSERT(name != NULL);
930 return (get_hash_symbol(name->str, (uint) name->length, 1) != 0);
931 }
932
933
is_native_function(THD * thd,const LEX_CSTRING * name)934 bool is_native_function(THD *thd, const LEX_CSTRING *name)
935 {
936 if (find_native_function_builder(thd, name))
937 return true;
938
939 if (is_lex_native_function(name))
940 return true;
941
942 return false;
943 }
944
945
is_native_function_with_warn(THD * thd,const LEX_CSTRING * name)946 bool is_native_function_with_warn(THD *thd, const LEX_CSTRING *name)
947 {
948 if (!is_native_function(thd, name))
949 return false;
950 /*
951 This warning will be printed when
952 [1] A client query is parsed,
953 [2] A stored function is loaded by db_load_routine.
954 Printing the warning for [2] is intentional, to cover the
955 following scenario:
956 - A user define a SF 'foo' using MySQL 5.N
957 - An application uses select foo(), and works.
958 - MySQL 5.{N+1} defines a new native function 'foo', as
959 part of a new feature.
960 - MySQL 5.{N+1} documentation is updated, and should mention
961 that there is a potential incompatible change in case of
962 existing stored function named 'foo'.
963 - The user deploys 5.{N+1}. At this point, 'select foo()'
964 means something different, and the user code is most likely
965 broken (it's only safe if the code is 'select db.foo()').
966 With a warning printed when the SF is loaded (which has to
967 occur before the call), the warning will provide a hint
968 explaining the root cause of a later failure of 'select foo()'.
969 With no warning printed, the user code will fail with no
970 apparent reason.
971 Printing a warning each time db_load_routine is executed for
972 an ambiguous function is annoying, since that can happen a lot,
973 but in practice should not happen unless there *are* name
974 collisions.
975 If a collision exists, it should not be silenced but fixed.
976 */
977 push_warning_printf(thd,
978 Sql_condition::WARN_LEVEL_NOTE,
979 ER_NATIVE_FCT_NAME_COLLISION,
980 ER_THD(thd, ER_NATIVE_FCT_NAME_COLLISION),
981 name->str);
982 return true;
983 }
984
985
986 /* make a copy of token before ptr and set yytoklen */
987
get_token(uint skip,uint length)988 LEX_CSTRING Lex_input_stream::get_token(uint skip, uint length)
989 {
990 LEX_CSTRING tmp;
991 yyUnget(); // ptr points now after last token char
992 tmp.length= length;
993 tmp.str= m_thd->strmake(m_tok_start + skip, tmp.length);
994
995 m_cpp_text_start= m_cpp_tok_start + skip;
996 m_cpp_text_end= m_cpp_text_start + tmp.length;
997
998 return tmp;
999 }
1000
1001
1002 static size_t
my_unescape(CHARSET_INFO * cs,char * to,const char * str,const char * end,int sep,bool backslash_escapes)1003 my_unescape(CHARSET_INFO *cs, char *to, const char *str, const char *end,
1004 int sep, bool backslash_escapes)
1005 {
1006 char *start= to;
1007 for ( ; str != end ; str++)
1008 {
1009 #ifdef USE_MB
1010 int l;
1011 if (use_mb(cs) && (l= my_ismbchar(cs, str, end)))
1012 {
1013 while (l--)
1014 *to++ = *str++;
1015 str--;
1016 continue;
1017 }
1018 #endif
1019 if (backslash_escapes && *str == '\\' && str + 1 != end)
1020 {
1021 switch(*++str) {
1022 case 'n':
1023 *to++='\n';
1024 break;
1025 case 't':
1026 *to++= '\t';
1027 break;
1028 case 'r':
1029 *to++ = '\r';
1030 break;
1031 case 'b':
1032 *to++ = '\b';
1033 break;
1034 case '0':
1035 *to++= 0; // Ascii null
1036 break;
1037 case 'Z': // ^Z must be escaped on Win32
1038 *to++='\032';
1039 break;
1040 case '_':
1041 case '%':
1042 *to++= '\\'; // remember prefix for wildcard
1043 /* Fall through */
1044 default:
1045 *to++= *str;
1046 break;
1047 }
1048 }
1049 else if (*str == sep)
1050 *to++= *str++; // Two ' or "
1051 else
1052 *to++ = *str;
1053 }
1054 *to= 0;
1055 return to - start;
1056 }
1057
1058
1059 size_t
unescape(CHARSET_INFO * cs,char * to,const char * str,const char * end,int sep)1060 Lex_input_stream::unescape(CHARSET_INFO *cs, char *to,
1061 const char *str, const char *end,
1062 int sep)
1063 {
1064 return my_unescape(cs, to, str, end, sep, m_thd->backslash_escapes());
1065 }
1066
1067
1068 /*
1069 Return an unescaped text literal without quotes
1070 Fix sometimes to do only one scan of the string
1071 */
1072
get_text(Lex_string_with_metadata_st * dst,uint sep,int pre_skip,int post_skip)1073 bool Lex_input_stream::get_text(Lex_string_with_metadata_st *dst, uint sep,
1074 int pre_skip, int post_skip)
1075 {
1076 uchar c;
1077 uint found_escape=0;
1078 CHARSET_INFO *cs= m_thd->charset();
1079 bool is_8bit= false;
1080
1081 while (! eof())
1082 {
1083 c= yyGet();
1084 if (c & 0x80)
1085 is_8bit= true;
1086 #ifdef USE_MB
1087 {
1088 int l;
1089 if (use_mb(cs) &&
1090 (l = my_ismbchar(cs,
1091 get_ptr() -1,
1092 get_end_of_query()))) {
1093 skip_binary(l-1);
1094 continue;
1095 }
1096 }
1097 #endif
1098 if (c == '\\' &&
1099 !(m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))
1100 { // Escaped character
1101 found_escape=1;
1102 if (eof())
1103 return true;
1104 yySkip();
1105 }
1106 else if (c == sep)
1107 {
1108 if (c == yyGet()) // Check if two separators in a row
1109 {
1110 found_escape=1; // duplicate. Remember for delete
1111 continue;
1112 }
1113 else
1114 yyUnget();
1115
1116 /* Found end. Unescape and return string */
1117 const char *str, *end;
1118 char *to;
1119
1120 str= m_tok_start;
1121 end= get_ptr();
1122 /* Extract the text from the token */
1123 str += pre_skip;
1124 end -= post_skip;
1125 DBUG_ASSERT(end >= str);
1126
1127 if (!(to= (char*) m_thd->alloc((uint) (end - str) + 1)))
1128 {
1129 dst->set(&empty_clex_str, 0, '\0');
1130 return true; // Sql_alloc has set error flag
1131 }
1132
1133 m_cpp_text_start= m_cpp_tok_start + pre_skip;
1134 m_cpp_text_end= get_cpp_ptr() - post_skip;
1135
1136 if (!found_escape)
1137 {
1138 size_t len= (end - str);
1139 memcpy(to, str, len);
1140 to[len]= '\0';
1141 dst->set(to, len, is_8bit, '\0');
1142 }
1143 else
1144 {
1145 size_t len= unescape(cs, to, str, end, sep);
1146 dst->set(to, len, is_8bit, '\0');
1147 }
1148 return false;
1149 }
1150 }
1151 return true; // unexpected end of query
1152 }
1153
1154
1155 /*
1156 ** Calc type of integer; long integer, longlong integer or real.
1157 ** Returns smallest type that match the string.
1158 ** When using unsigned long long values the result is converted to a real
1159 ** because else they will be unexpected sign changes because all calculation
1160 ** is done with longlong or double.
1161 */
1162
1163 static const char *long_str="2147483647";
1164 static const uint long_len=10;
1165 static const char *signed_long_str="-2147483648";
1166 static const char *longlong_str="9223372036854775807";
1167 static const uint longlong_len=19;
1168 static const char *signed_longlong_str="-9223372036854775808";
1169 static const uint signed_longlong_len=19;
1170 static const char *unsigned_longlong_str="18446744073709551615";
1171 static const uint unsigned_longlong_len=20;
1172
int_token(const char * str,uint length)1173 static inline uint int_token(const char *str,uint length)
1174 {
1175 if (length < long_len) // quick normal case
1176 return NUM;
1177 bool neg=0;
1178
1179 if (*str == '+') // Remove sign and pre-zeros
1180 {
1181 str++; length--;
1182 }
1183 else if (*str == '-')
1184 {
1185 str++; length--;
1186 neg=1;
1187 }
1188 while (*str == '0' && length)
1189 {
1190 str++; length --;
1191 }
1192 if (length < long_len)
1193 return NUM;
1194
1195 uint smaller,bigger;
1196 const char *cmp;
1197 if (neg)
1198 {
1199 if (length == long_len)
1200 {
1201 cmp= signed_long_str + 1;
1202 smaller= NUM; // If <= signed_long_str
1203 bigger= LONG_NUM; // If >= signed_long_str
1204 }
1205 else if (length < signed_longlong_len)
1206 return LONG_NUM;
1207 else if (length > signed_longlong_len)
1208 return DECIMAL_NUM;
1209 else
1210 {
1211 cmp= signed_longlong_str + 1;
1212 smaller= LONG_NUM; // If <= signed_longlong_str
1213 bigger=DECIMAL_NUM;
1214 }
1215 }
1216 else
1217 {
1218 if (length == long_len)
1219 {
1220 cmp= long_str;
1221 smaller=NUM;
1222 bigger=LONG_NUM;
1223 }
1224 else if (length < longlong_len)
1225 return LONG_NUM;
1226 else if (length > longlong_len)
1227 {
1228 if (length > unsigned_longlong_len)
1229 return DECIMAL_NUM;
1230 cmp=unsigned_longlong_str;
1231 smaller=ULONGLONG_NUM;
1232 bigger=DECIMAL_NUM;
1233 }
1234 else
1235 {
1236 cmp=longlong_str;
1237 smaller=LONG_NUM;
1238 bigger= ULONGLONG_NUM;
1239 }
1240 }
1241 while (*cmp && *cmp++ == *str++) ;
1242 return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
1243 }
1244
1245
1246 /**
1247 Given a stream that is advanced to the first contained character in
1248 an open comment, consume the comment. Optionally, if we are allowed,
1249 recurse so that we understand comments within this current comment.
1250
1251 At this level, we do not support version-condition comments. We might
1252 have been called with having just passed one in the stream, though. In
1253 that case, we probably want to tolerate mundane comments inside. Thus,
1254 the case for recursion.
1255
1256 @retval Whether EOF reached before comment is closed.
1257 */
consume_comment(int remaining_recursions_permitted)1258 bool Lex_input_stream::consume_comment(int remaining_recursions_permitted)
1259 {
1260 // only one level of nested comments are allowed
1261 DBUG_ASSERT(remaining_recursions_permitted == 0 ||
1262 remaining_recursions_permitted == 1);
1263 uchar c;
1264 while (!eof())
1265 {
1266 c= yyGet();
1267
1268 if (remaining_recursions_permitted == 1)
1269 {
1270 if ((c == '/') && (yyPeek() == '*'))
1271 {
1272 yyUnput('('); // Replace nested "/*..." with "(*..."
1273 yySkip(); // and skip "("
1274
1275 yySkip(); /* Eat asterisk */
1276 if (consume_comment(0))
1277 return true;
1278
1279 yyUnput(')'); // Replace "...*/" with "...*)"
1280 yySkip(); // and skip ")"
1281 continue;
1282 }
1283 }
1284
1285 if (c == '*')
1286 {
1287 if (yyPeek() == '/')
1288 {
1289 yySkip(); // Eat slash
1290 return FALSE;
1291 }
1292 }
1293
1294 if (c == '\n')
1295 yylineno++;
1296 }
1297
1298 return TRUE;
1299 }
1300
1301
1302 /*
1303 MYSQLlex remember the following states from the following MYSQLlex()
1304
1305 @param yylval [out] semantic value of the token being parsed (yylval)
1306 @param thd THD
1307
1308 - MY_LEX_EOQ Found end of query
1309 - MY_LEX_OPERATOR_OR_IDENT Last state was an ident, text or number
1310 (which can't be followed by a signed number)
1311 */
1312
MYSQLlex(YYSTYPE * yylval,THD * thd)1313 int MYSQLlex(YYSTYPE *yylval, THD *thd)
1314 {
1315 return thd->m_parser_state->m_lip.lex_token(yylval, thd);
1316 }
1317
1318
ORAlex(YYSTYPE * yylval,THD * thd)1319 int ORAlex(YYSTYPE *yylval, THD *thd)
1320 {
1321 return thd->m_parser_state->m_lip.lex_token(yylval, thd);
1322 }
1323
1324
lex_token(YYSTYPE * yylval,THD * thd)1325 int Lex_input_stream::lex_token(YYSTYPE *yylval, THD *thd)
1326 {
1327 int token;
1328 const int left_paren= (int) '(';
1329
1330 if (lookahead_token >= 0)
1331 {
1332 /*
1333 The next token was already parsed in advance,
1334 return it.
1335 */
1336 token= lookahead_token;
1337 lookahead_token= -1;
1338 *yylval= *(lookahead_yylval);
1339 lookahead_yylval= NULL;
1340 return token;
1341 }
1342
1343 token= lex_one_token(yylval, thd);
1344 add_digest_token(token, yylval);
1345
1346 SELECT_LEX *curr_sel= thd->lex->current_select;
1347
1348 switch(token) {
1349 case WITH:
1350 /*
1351 Parsing 'WITH' 'ROLLUP' or 'WITH' 'CUBE' requires 2 look ups,
1352 which makes the grammar LALR(2).
1353 Replace by a single 'WITH_ROLLUP' or 'WITH_CUBE' token,
1354 to transform the grammar into a LALR(1) grammar,
1355 which sql_yacc.yy can process.
1356 */
1357 token= lex_one_token(yylval, thd);
1358 add_digest_token(token, yylval);
1359 switch(token) {
1360 case CUBE_SYM:
1361 return WITH_CUBE_SYM;
1362 case ROLLUP_SYM:
1363 return WITH_ROLLUP_SYM;
1364 case SYSTEM:
1365 return WITH_SYSTEM_SYM;
1366 default:
1367 /*
1368 Save the token following 'WITH'
1369 */
1370 lookahead_yylval= yylval;
1371 lookahead_token= token;
1372 return WITH;
1373 }
1374 break;
1375 case FOR_SYM:
1376 /*
1377 * Additional look-ahead to resolve doubtful cases like:
1378 * SELECT ... FOR UPDATE
1379 * SELECT ... FOR SYSTEM_TIME ... .
1380 */
1381 token= lex_one_token(yylval, thd);
1382 add_digest_token(token, yylval);
1383 switch(token) {
1384 case SYSTEM_TIME_SYM:
1385 return FOR_SYSTEM_TIME_SYM;
1386 default:
1387 /*
1388 Save the token following 'FOR_SYM'
1389 */
1390 lookahead_yylval= yylval;
1391 lookahead_token= token;
1392 return FOR_SYM;
1393 }
1394 break;
1395 case VALUES:
1396 if (curr_sel &&
1397 (curr_sel->parsing_place == BEFORE_OPT_LIST ||
1398 curr_sel->parsing_place == AFTER_LIST))
1399 {
1400 curr_sel->parsing_place= NO_MATTER;
1401 break;
1402 }
1403 if (curr_sel &&
1404 (curr_sel->parsing_place == IN_UPDATE_ON_DUP_KEY ||
1405 curr_sel->parsing_place == IN_PART_FUNC))
1406 return VALUE_SYM;
1407 token= lex_one_token(yylval, thd);
1408 add_digest_token(token, yylval);
1409 switch(token) {
1410 case LESS_SYM:
1411 return VALUES_LESS_SYM;
1412 case IN_SYM:
1413 return VALUES_IN_SYM;
1414 default:
1415 lookahead_yylval= yylval;
1416 lookahead_token= token;
1417 return VALUES;
1418 }
1419 case VALUE_SYM:
1420 if (curr_sel &&
1421 (curr_sel->parsing_place == BEFORE_OPT_LIST ||
1422 curr_sel->parsing_place == AFTER_LIST))
1423 {
1424 curr_sel->parsing_place= NO_MATTER;
1425 return VALUES;
1426 }
1427 break;
1428 case PARTITION_SYM:
1429 case SELECT_SYM:
1430 case UNION_SYM:
1431 if (curr_sel &&
1432 (curr_sel->parsing_place == BEFORE_OPT_LIST ||
1433 curr_sel->parsing_place == AFTER_LIST))
1434 {
1435 curr_sel->parsing_place= NO_MATTER;
1436 }
1437 break;
1438 case left_paren:
1439 if (!curr_sel ||
1440 curr_sel->parsing_place != BEFORE_OPT_LIST)
1441 return token;
1442 token= lex_one_token(yylval, thd);
1443 add_digest_token(token, yylval);
1444 lookahead_yylval= yylval;
1445 yylval= NULL;
1446 lookahead_token= token;
1447 curr_sel->parsing_place= NO_MATTER;
1448 if (token == LIKE)
1449 return LEFT_PAREN_LIKE;
1450 if (token == WITH)
1451 return LEFT_PAREN_WITH;
1452 if (token != left_paren && token != SELECT_SYM && token != VALUES)
1453 return LEFT_PAREN_ALT;
1454 else
1455 return left_paren;
1456 break;
1457 default:
1458 break;
1459 }
1460 return token;
1461 }
1462
1463
lex_one_token(YYSTYPE * yylval,THD * thd)1464 int Lex_input_stream::lex_one_token(YYSTYPE *yylval, THD *thd)
1465 {
1466 uchar UNINIT_VAR(c);
1467 bool comment_closed;
1468 int tokval;
1469 uint length;
1470 enum my_lex_states state;
1471 LEX *lex= thd->lex;
1472 CHARSET_INFO *const cs= thd->charset();
1473 const uchar *const state_map= cs->state_map;
1474 const uchar *const ident_map= cs->ident_map;
1475
1476 start_token();
1477 state= next_state;
1478 next_state= MY_LEX_OPERATOR_OR_IDENT;
1479 for (;;)
1480 {
1481 switch (state) {
1482 case MY_LEX_OPERATOR_OR_IDENT: // Next is operator or keyword
1483 case MY_LEX_START: // Start of token
1484 // Skip starting whitespace
1485 while(state_map[c= yyPeek()] == MY_LEX_SKIP)
1486 {
1487 if (c == '\n')
1488 yylineno++;
1489
1490 yySkip();
1491 }
1492
1493 /* Start of real token */
1494 restart_token();
1495 c= yyGet();
1496 state= (enum my_lex_states) state_map[c];
1497 break;
1498 case MY_LEX_ESCAPE:
1499 if (!eof() && yyGet() == 'N')
1500 { // Allow \N as shortcut for NULL
1501 yylval->lex_str.str= (char*) "\\N";
1502 yylval->lex_str.length= 2;
1503 return NULL_SYM;
1504 }
1505 /* Fall through */
1506 case MY_LEX_CHAR: // Unknown or single char token
1507 if (c == '%' && (m_thd->variables.sql_mode & MODE_ORACLE))
1508 {
1509 next_state= MY_LEX_START;
1510 return PERCENT_ORACLE_SYM;
1511 }
1512 if (c == '[' && (m_thd->variables.sql_mode & MODE_MSSQL))
1513 return scan_ident_delimited(thd, &yylval->ident_cli, ']');
1514 /* Fall through */
1515 case MY_LEX_SKIP: // This should not happen
1516 if (c != ')')
1517 next_state= MY_LEX_START; // Allow signed numbers
1518 yylval->kwd.set_keyword(m_tok_start, 1);
1519 return((int) c);
1520
1521 case MY_LEX_MINUS_OR_COMMENT:
1522 if (yyPeek() == '-' &&
1523 (my_isspace(cs,yyPeekn(1)) ||
1524 my_iscntrl(cs,yyPeekn(1))))
1525 {
1526 state=MY_LEX_COMMENT;
1527 break;
1528 }
1529 next_state= MY_LEX_START; // Allow signed numbers
1530 return((int) c);
1531
1532 case MY_LEX_PLACEHOLDER:
1533 /*
1534 Check for a placeholder: it should not precede a possible identifier
1535 because of binlogging: when a placeholder is replaced with
1536 its value in a query for the binlog, the query must stay
1537 grammatically correct.
1538 */
1539 next_state= MY_LEX_START; // Allow signed numbers
1540 if (stmt_prepare_mode && !ident_map[(uchar) yyPeek()])
1541 return(PARAM_MARKER);
1542 return((int) c);
1543
1544 case MY_LEX_COMMA:
1545 next_state= MY_LEX_START; // Allow signed numbers
1546 /*
1547 Warning:
1548 This is a work around, to make the "remember_name" rule in
1549 sql/sql_yacc.yy work properly.
1550 The problem is that, when parsing "select expr1, expr2",
1551 the code generated by bison executes the *pre* action
1552 remember_name (see select_item) *before* actually parsing the
1553 first token of expr2.
1554 */
1555 restart_token();
1556 return((int) c);
1557
1558 case MY_LEX_IDENT_OR_NCHAR:
1559 {
1560 uint sep;
1561 if (yyPeek() != '\'')
1562 {
1563 state= MY_LEX_IDENT;
1564 break;
1565 }
1566 /* Found N'string' */
1567 yySkip(); // Skip '
1568 if (get_text(&yylval->lex_string_with_metadata, (sep= yyGetLast()), 2, 1))
1569 {
1570 state= MY_LEX_CHAR; // Read char by char
1571 break;
1572 }
1573
1574 body_utf8_append(m_cpp_text_start);
1575 body_utf8_append_escape(thd, &yylval->lex_string_with_metadata,
1576 national_charset_info,
1577 m_cpp_text_end, sep);
1578 return(NCHAR_STRING);
1579 }
1580 case MY_LEX_IDENT_OR_HEX:
1581 if (yyPeek() == '\'')
1582 { // Found x'hex-number'
1583 state= MY_LEX_HEX_NUMBER;
1584 break;
1585 }
1586 /* fall through */
1587 case MY_LEX_IDENT_OR_BIN:
1588 if (yyPeek() == '\'')
1589 { // Found b'bin-number'
1590 state= MY_LEX_BIN_NUMBER;
1591 break;
1592 }
1593 /* fall through */
1594 case MY_LEX_IDENT:
1595 {
1596 tokval= scan_ident_middle(thd, &yylval->ident_cli,
1597 &yylval->charset, &state);
1598 if (!tokval)
1599 continue;
1600 if (tokval == UNDERSCORE_CHARSET)
1601 m_underscore_cs= yylval->charset;
1602 return tokval;
1603 }
1604
1605 case MY_LEX_IDENT_SEP: // Found ident and now '.'
1606 yylval->lex_str.str= (char*) get_ptr();
1607 yylval->lex_str.length= 1;
1608 c= yyGet(); // should be '.'
1609 if (lex->parsing_options.lookup_keywords_after_qualifier)
1610 next_state= MY_LEX_IDENT_OR_KEYWORD;
1611 else
1612 next_state= MY_LEX_IDENT_START; // Next is ident (not keyword)
1613 if (!ident_map[(uchar) yyPeek()]) // Probably ` or "
1614 next_state= MY_LEX_START;
1615 return((int) c);
1616
1617 case MY_LEX_NUMBER_IDENT: // number or ident which num-start
1618 if (yyGetLast() == '0')
1619 {
1620 c= yyGet();
1621 if (c == 'x')
1622 {
1623 while (my_isxdigit(cs, (c = yyGet()))) ;
1624 if ((yyLength() >= 3) && !ident_map[c])
1625 {
1626 /* skip '0x' */
1627 yylval->lex_str= get_token(2, yyLength() - 2);
1628 return (HEX_NUM);
1629 }
1630 yyUnget();
1631 state= MY_LEX_IDENT_START;
1632 break;
1633 }
1634 else if (c == 'b')
1635 {
1636 while ((c= yyGet()) == '0' || c == '1')
1637 ;
1638 if ((yyLength() >= 3) && !ident_map[c])
1639 {
1640 /* Skip '0b' */
1641 yylval->lex_str= get_token(2, yyLength() - 2);
1642 return (BIN_NUM);
1643 }
1644 yyUnget();
1645 state= MY_LEX_IDENT_START;
1646 break;
1647 }
1648 yyUnget();
1649 }
1650
1651 while (my_isdigit(cs, (c= yyGet()))) ;
1652 if (!ident_map[c])
1653 { // Can't be identifier
1654 state=MY_LEX_INT_OR_REAL;
1655 break;
1656 }
1657 if (c == 'e' || c == 'E')
1658 {
1659 // The following test is written this way to allow numbers of type 1e1
1660 if (my_isdigit(cs, yyPeek()) ||
1661 (c=(yyGet())) == '+' || c == '-')
1662 { // Allow 1E+10
1663 if (my_isdigit(cs, yyPeek())) // Number must have digit after sign
1664 {
1665 yySkip();
1666 while (my_isdigit(cs, yyGet())) ;
1667 yylval->lex_str= get_token(0, yyLength());
1668 return(FLOAT_NUM);
1669 }
1670 }
1671 /*
1672 We've found:
1673 - A sequence of digits
1674 - Followed by 'e' or 'E'
1675 - Followed by some byte XX which is not a known mantissa start,
1676 and it's known to be a valid identifier part.
1677 XX can be either a 8bit identifier character, or a multi-byte head.
1678 */
1679 yyUnget();
1680 return scan_ident_start(thd, &yylval->ident_cli);
1681 }
1682 /*
1683 We've found:
1684 - A sequence of digits
1685 - Followed by some character XX, which is neither 'e' nor 'E',
1686 and it's known to be a valid identifier part.
1687 XX can be a 8bit identifier character, or a multi-byte head.
1688 */
1689 yyUnget();
1690 return scan_ident_start(thd, &yylval->ident_cli);
1691
1692 case MY_LEX_IDENT_START: // We come here after '.'
1693 return scan_ident_start(thd, &yylval->ident_cli);
1694
1695 case MY_LEX_USER_VARIABLE_DELIMITER: // Found quote char
1696 return scan_ident_delimited(thd, &yylval->ident_cli, m_tok_start[0]);
1697
1698 case MY_LEX_INT_OR_REAL: // Complete int or incomplete real
1699 if (c != '.' || yyPeek() == '.')
1700 {
1701 /*
1702 Found a complete integer number:
1703 - the number is either not followed by a dot at all, or
1704 - the number is followed by a double dot as in: FOR i IN 1..10
1705 */
1706 yylval->lex_str= get_token(0, yyLength());
1707 return int_token(yylval->lex_str.str, (uint) yylval->lex_str.length);
1708 }
1709 // fall through
1710 case MY_LEX_REAL: // Incomplete real number
1711 while (my_isdigit(cs, c= yyGet())) ;
1712
1713 if (c == 'e' || c == 'E')
1714 {
1715 c= yyGet();
1716 if (c == '-' || c == '+')
1717 c= yyGet(); // Skip sign
1718 if (!my_isdigit(cs, c))
1719 return ABORT_SYM; // No digit after sign
1720 while (my_isdigit(cs, yyGet())) ;
1721 yylval->lex_str= get_token(0, yyLength());
1722 return(FLOAT_NUM);
1723 }
1724 yylval->lex_str= get_token(0, yyLength());
1725 return(DECIMAL_NUM);
1726
1727 case MY_LEX_HEX_NUMBER: // Found x'hexstring'
1728 yySkip(); // Accept opening '
1729 while (my_isxdigit(cs, (c= yyGet()))) ;
1730 if (c != '\'')
1731 return(ABORT_SYM); // Illegal hex constant
1732 yySkip(); // Accept closing '
1733 length= yyLength(); // Length of hexnum+3
1734 if ((length % 2) == 0)
1735 return(ABORT_SYM); // odd number of hex digits
1736 yylval->lex_str= get_token(2, // skip x'
1737 length - 3); // don't count x' and last '
1738 return HEX_STRING;
1739
1740 case MY_LEX_BIN_NUMBER: // Found b'bin-string'
1741 yySkip(); // Accept opening '
1742 while ((c= yyGet()) == '0' || c == '1')
1743 ;
1744 if (c != '\'')
1745 return(ABORT_SYM); // Illegal hex constant
1746 yySkip(); // Accept closing '
1747 length= yyLength(); // Length of bin-num + 3
1748 yylval->lex_str= get_token(2, // skip b'
1749 length - 3); // don't count b' and last '
1750 return (BIN_NUM);
1751
1752 case MY_LEX_CMP_OP: // Incomplete comparison operator
1753 next_state= MY_LEX_START; // Allow signed numbers
1754 if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP ||
1755 state_map[(uchar) yyPeek()] == MY_LEX_LONG_CMP_OP)
1756 {
1757 yySkip();
1758 if ((tokval= find_keyword(&yylval->kwd, 2, 0)))
1759 return(tokval);
1760 yyUnget();
1761 }
1762 return(c);
1763
1764 case MY_LEX_LONG_CMP_OP: // Incomplete comparison operator
1765 next_state= MY_LEX_START;
1766 if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP ||
1767 state_map[(uchar) yyPeek()] == MY_LEX_LONG_CMP_OP)
1768 {
1769 yySkip();
1770 if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP)
1771 {
1772 yySkip();
1773 if ((tokval= find_keyword(&yylval->kwd, 3, 0)))
1774 return(tokval);
1775 yyUnget();
1776 }
1777 if ((tokval= find_keyword(&yylval->kwd, 2, 0)))
1778 return(tokval);
1779 yyUnget();
1780 }
1781 return(c);
1782
1783 case MY_LEX_BOOL:
1784 if (c != yyPeek())
1785 {
1786 state= MY_LEX_CHAR;
1787 break;
1788 }
1789 yySkip();
1790 tokval= find_keyword(&yylval->kwd, 2, 0); // Is a bool operator
1791 next_state= MY_LEX_START; // Allow signed numbers
1792 return(tokval);
1793
1794 case MY_LEX_STRING_OR_DELIMITER:
1795 if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
1796 {
1797 state= MY_LEX_USER_VARIABLE_DELIMITER;
1798 break;
1799 }
1800 /* " used for strings */
1801 /* fall through */
1802 case MY_LEX_STRING: // Incomplete text string
1803 {
1804 uint sep;
1805 if (get_text(&yylval->lex_string_with_metadata, (sep= yyGetLast()), 1, 1))
1806 {
1807 state= MY_LEX_CHAR; // Read char by char
1808 break;
1809 }
1810 CHARSET_INFO *strcs= m_underscore_cs ? m_underscore_cs : cs;
1811 body_utf8_append(m_cpp_text_start);
1812
1813 body_utf8_append_escape(thd, &yylval->lex_string_with_metadata,
1814 strcs, m_cpp_text_end, sep);
1815 m_underscore_cs= NULL;
1816 return(TEXT_STRING);
1817 }
1818 case MY_LEX_COMMENT: // Comment
1819 lex->lex_options|= OPTION_LEX_FOUND_COMMENT;
1820 while ((c= yyGet()) != '\n' && c) ;
1821 yyUnget(); // Safety against eof
1822 state= MY_LEX_START; // Try again
1823 break;
1824 case MY_LEX_LONG_COMMENT: // Long C comment?
1825 if (yyPeek() != '*')
1826 {
1827 state= MY_LEX_CHAR; // Probable division
1828 break;
1829 }
1830 lex->lex_options|= OPTION_LEX_FOUND_COMMENT;
1831 /* Reject '/' '*', since we might need to turn off the echo */
1832 yyUnget();
1833
1834 save_in_comment_state();
1835
1836 if (yyPeekn(2) == '!' ||
1837 (yyPeekn(2) == 'M' && yyPeekn(3) == '!'))
1838 {
1839 bool maria_comment_syntax= yyPeekn(2) == 'M';
1840 in_comment= DISCARD_COMMENT;
1841 /* Accept '/' '*' '!', but do not keep this marker. */
1842 set_echo(FALSE);
1843 yySkipn(maria_comment_syntax ? 4 : 3);
1844
1845 /*
1846 The special comment format is very strict:
1847 '/' '*' '!', followed by an optional 'M' and exactly
1848 1-2 digits (major), 2 digits (minor), then 2 digits (dot).
1849 32302 -> 3.23.02
1850 50032 -> 5.0.32
1851 50114 -> 5.1.14
1852 100000 -> 10.0.0
1853 */
1854 if ( my_isdigit(cs, yyPeekn(0))
1855 && my_isdigit(cs, yyPeekn(1))
1856 && my_isdigit(cs, yyPeekn(2))
1857 && my_isdigit(cs, yyPeekn(3))
1858 && my_isdigit(cs, yyPeekn(4))
1859 )
1860 {
1861 ulong version;
1862 uint length= 5;
1863 char *end_ptr= (char*) get_ptr() + length;
1864 int error;
1865 if (my_isdigit(cs, yyPeekn(5)))
1866 {
1867 end_ptr++; // 6 digit number
1868 length++;
1869 }
1870
1871 version= (ulong) my_strtoll10(get_ptr(), &end_ptr, &error);
1872
1873 /*
1874 MySQL-5.7 has new features and might have new SQL syntax that
1875 MariaDB-10.0 does not understand. Ignore all versioned comments
1876 with MySQL versions in the range 50700-999999, but
1877 do not ignore MariaDB specific comments for the same versions.
1878 */
1879 if (version <= MYSQL_VERSION_ID &&
1880 (version < 50700 || version > 99999 || maria_comment_syntax))
1881 {
1882 /* Accept 'M' 'm' 'm' 'd' 'd' */
1883 yySkipn(length);
1884 /* Expand the content of the special comment as real code */
1885 set_echo(TRUE);
1886 state=MY_LEX_START;
1887 break; /* Do not treat contents as a comment. */
1888 }
1889 else
1890 {
1891 #ifdef WITH_WSREP
1892 if (WSREP(thd) && version == 99997 && wsrep_thd_is_local(thd))
1893 {
1894 WSREP_DEBUG("consistency check: %s", thd->query());
1895 thd->wsrep_consistency_check= CONSISTENCY_CHECK_DECLARED;
1896 yySkipn(5);
1897 set_echo(TRUE);
1898 state= MY_LEX_START;
1899 break; /* Do not treat contents as a comment. */
1900 }
1901 #endif /* WITH_WSREP */
1902 /*
1903 Patch and skip the conditional comment to avoid it
1904 being propagated infinitely (eg. to a slave).
1905 */
1906 char *pcom= yyUnput(' ');
1907 comment_closed= ! consume_comment(1);
1908 if (! comment_closed)
1909 {
1910 *pcom= '!';
1911 }
1912 /* version allowed to have one level of comment inside. */
1913 }
1914 }
1915 else
1916 {
1917 /* Not a version comment. */
1918 state=MY_LEX_START;
1919 set_echo(TRUE);
1920 break;
1921 }
1922 }
1923 else
1924 {
1925 in_comment= PRESERVE_COMMENT;
1926 yySkip(); // Accept /
1927 yySkip(); // Accept *
1928 comment_closed= ! consume_comment(0);
1929 /* regular comments can have zero comments inside. */
1930 }
1931 /*
1932 Discard:
1933 - regular '/' '*' comments,
1934 - special comments '/' '*' '!' for a future version,
1935 by scanning until we find a closing '*' '/' marker.
1936
1937 Nesting regular comments isn't allowed. The first
1938 '*' '/' returns the parser to the previous state.
1939
1940 /#!VERSI oned containing /# regular #/ is allowed #/
1941
1942 Inside one versioned comment, another versioned comment
1943 is treated as a regular discardable comment. It gets
1944 no special parsing.
1945 */
1946
1947 /* Unbalanced comments with a missing '*' '/' are a syntax error */
1948 if (! comment_closed)
1949 return (ABORT_SYM);
1950 state = MY_LEX_START; // Try again
1951 restore_in_comment_state();
1952 break;
1953 case MY_LEX_END_LONG_COMMENT:
1954 if ((in_comment != NO_COMMENT) && yyPeek() == '/')
1955 {
1956 /* Reject '*' '/' */
1957 yyUnget();
1958 /* Accept '*' '/', with the proper echo */
1959 set_echo(in_comment == PRESERVE_COMMENT);
1960 yySkipn(2);
1961 /* And start recording the tokens again */
1962 set_echo(TRUE);
1963 in_comment= NO_COMMENT;
1964 state=MY_LEX_START;
1965 }
1966 else
1967 state= MY_LEX_CHAR; // Return '*'
1968 break;
1969 case MY_LEX_SET_VAR: // Check if ':='
1970 if (yyPeek() != '=')
1971 {
1972 next_state= MY_LEX_START;
1973 if (m_thd->variables.sql_mode & MODE_ORACLE)
1974 {
1975 yylval->kwd.set_keyword(m_tok_start, 1);
1976 return COLON_ORACLE_SYM;
1977 }
1978 return (int) ':';
1979 }
1980 yySkip();
1981 return (SET_VAR);
1982 case MY_LEX_SEMICOLON: // optional line terminator
1983 state= MY_LEX_CHAR; // Return ';'
1984 break;
1985 case MY_LEX_EOL:
1986 if (eof())
1987 {
1988 yyUnget(); // Reject the last '\0'
1989 set_echo(FALSE);
1990 yySkip();
1991 set_echo(TRUE);
1992 /* Unbalanced comments with a missing '*' '/' are a syntax error */
1993 if (in_comment != NO_COMMENT)
1994 return (ABORT_SYM);
1995 next_state= MY_LEX_END; // Mark for next loop
1996 return(END_OF_INPUT);
1997 }
1998 state=MY_LEX_CHAR;
1999 break;
2000 case MY_LEX_END:
2001 next_state= MY_LEX_END;
2002 return(0); // We found end of input last time
2003
2004 /* Actually real shouldn't start with . but allow them anyhow */
2005 case MY_LEX_REAL_OR_POINT:
2006 if (my_isdigit(cs, (c= yyPeek())))
2007 state = MY_LEX_REAL; // Real
2008 else if (c == '.')
2009 {
2010 yySkip();
2011 return DOT_DOT_SYM;
2012 }
2013 else
2014 {
2015 state= MY_LEX_IDENT_SEP; // return '.'
2016 yyUnget(); // Put back '.'
2017 }
2018 break;
2019 case MY_LEX_USER_END: // end '@' of user@hostname
2020 switch (state_map[(uchar) yyPeek()]) {
2021 case MY_LEX_STRING:
2022 case MY_LEX_USER_VARIABLE_DELIMITER:
2023 case MY_LEX_STRING_OR_DELIMITER:
2024 break;
2025 case MY_LEX_USER_END:
2026 next_state= MY_LEX_SYSTEM_VAR;
2027 break;
2028 default:
2029 next_state= MY_LEX_HOSTNAME;
2030 break;
2031 }
2032 yylval->lex_str.str= (char*) get_ptr();
2033 yylval->lex_str.length= 1;
2034 return((int) '@');
2035 case MY_LEX_HOSTNAME: // end '@' of user@hostname
2036 for (c= yyGet() ;
2037 my_isalnum(cs, c) || c == '.' || c == '_' || c == '$';
2038 c= yyGet()) ;
2039 yylval->lex_str= get_token(0, yyLength());
2040 return(LEX_HOSTNAME);
2041 case MY_LEX_SYSTEM_VAR:
2042 yylval->lex_str.str= (char*) get_ptr();
2043 yylval->lex_str.length= 1;
2044 yySkip(); // Skip '@'
2045 next_state= (state_map[(uchar) yyPeek()] ==
2046 MY_LEX_USER_VARIABLE_DELIMITER ?
2047 MY_LEX_OPERATOR_OR_IDENT :
2048 MY_LEX_IDENT_OR_KEYWORD);
2049 return((int) '@');
2050 case MY_LEX_IDENT_OR_KEYWORD:
2051 /*
2052 We come here when we have found two '@' in a row.
2053 We should now be able to handle:
2054 [(global | local | session) .]variable_name
2055 */
2056 return scan_ident_sysvar(thd, &yylval->ident_cli);
2057 }
2058 }
2059 }
2060
2061
get_7bit_or_8bit_ident(THD * thd,uchar * last_char)2062 bool Lex_input_stream::get_7bit_or_8bit_ident(THD *thd, uchar *last_char)
2063 {
2064 uchar c;
2065 CHARSET_INFO *const cs= thd->charset();
2066 const uchar *const ident_map= cs->ident_map;
2067 bool is_8bit= false;
2068 for ( ; ident_map[c= yyGet()]; )
2069 {
2070 if (c & 0x80)
2071 is_8bit= true; // will convert
2072 }
2073 *last_char= c;
2074 return is_8bit;
2075 }
2076
2077
scan_ident_sysvar(THD * thd,Lex_ident_cli_st * str)2078 int Lex_input_stream::scan_ident_sysvar(THD *thd, Lex_ident_cli_st *str)
2079 {
2080 uchar last_char;
2081 uint length;
2082 int tokval;
2083 bool is_8bit;
2084 DBUG_ASSERT(m_tok_start == m_ptr);
2085
2086 is_8bit= get_7bit_or_8bit_ident(thd, &last_char);
2087
2088 if (last_char == '.')
2089 next_state= MY_LEX_IDENT_SEP;
2090 if (!(length= yyLength()))
2091 return ABORT_SYM; // Names must be nonempty.
2092 if ((tokval= find_keyword(str, length, 0)))
2093 {
2094 yyUnget(); // Put back 'c'
2095 return tokval; // Was keyword
2096 }
2097
2098 yyUnget(); // ptr points now after last token char
2099 str->set_ident(m_tok_start, length, is_8bit);
2100
2101 m_cpp_text_start= m_cpp_tok_start;
2102 m_cpp_text_end= m_cpp_text_start + length;
2103 body_utf8_append(m_cpp_text_start);
2104 body_utf8_append_ident(thd, str, m_cpp_text_end);
2105
2106 return is_8bit ? IDENT_QUOTED : IDENT;
2107 }
2108
2109
2110 /*
2111 We can come here if different parsing stages:
2112 - In an identifier chain:
2113 SELECT t1.cccc FROM t1;
2114 (when the "cccc" part starts)
2115 In this case both m_tok_start and m_ptr point to "cccc".
2116 - When a sequence of digits has changed to something else,
2117 therefore the token becomes an identifier rather than a number:
2118 SELECT 12345_6 FROM t1;
2119 In this case m_tok_start points to the entire "12345_678",
2120 while m_ptr points to "678".
2121 */
scan_ident_start(THD * thd,Lex_ident_cli_st * str)2122 int Lex_input_stream::scan_ident_start(THD *thd, Lex_ident_cli_st *str)
2123 {
2124 uchar c;
2125 bool is_8bit;
2126 CHARSET_INFO *const cs= thd->charset();
2127 const uchar *const ident_map= cs->ident_map;
2128 DBUG_ASSERT(m_tok_start <= m_ptr);
2129
2130 if (use_mb(cs))
2131 {
2132 is_8bit= true;
2133 while (ident_map[c= yyGet()])
2134 {
2135 int char_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
2136 if (char_length <= 0)
2137 break;
2138 skip_binary(char_length - 1);
2139 }
2140 }
2141 else
2142 {
2143 is_8bit= get_7bit_or_8bit_ident(thd, &c);
2144 }
2145 if (c == '.' && ident_map[(uchar) yyPeek()])
2146 next_state= MY_LEX_IDENT_SEP;// Next is '.'
2147
2148 uint length= yyLength();
2149 yyUnget(); // ptr points now after last token char
2150 str->set_ident(m_tok_start, length, is_8bit);
2151 m_cpp_text_start= m_cpp_tok_start;
2152 m_cpp_text_end= m_cpp_text_start + length;
2153 body_utf8_append(m_cpp_text_start);
2154 body_utf8_append_ident(thd, str, m_cpp_text_end);
2155 return is_8bit ? IDENT_QUOTED : IDENT;
2156 }
2157
2158
scan_ident_middle(THD * thd,Lex_ident_cli_st * str,CHARSET_INFO ** introducer,my_lex_states * st)2159 int Lex_input_stream::scan_ident_middle(THD *thd, Lex_ident_cli_st *str,
2160 CHARSET_INFO **introducer,
2161 my_lex_states *st)
2162 {
2163 CHARSET_INFO *const cs= thd->charset();
2164 const uchar *const ident_map= cs->ident_map;
2165 const uchar *const state_map= cs->state_map;
2166 const char *start;
2167 uint length;
2168 uchar c;
2169 bool is_8bit;
2170 bool resolve_introducer= true;
2171 DBUG_ASSERT(m_ptr == m_tok_start + 1); // m_ptr points to the second byte
2172
2173 if (use_mb(cs))
2174 {
2175 is_8bit= true;
2176 int char_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
2177 if (char_length <= 0)
2178 {
2179 *st= MY_LEX_CHAR;
2180 return 0;
2181 }
2182 skip_binary(char_length - 1);
2183
2184 while (ident_map[c= yyGet()])
2185 {
2186 char_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
2187 if (char_length <= 0)
2188 break;
2189 if (char_length > 1 || (c & 0x80))
2190 resolve_introducer= false;
2191 skip_binary(char_length - 1);
2192 }
2193 }
2194 else
2195 {
2196 is_8bit= get_7bit_or_8bit_ident(thd, &c) || (m_tok_start[0] & 0x80);
2197 resolve_introducer= !is_8bit;
2198 }
2199 length= yyLength();
2200 start= get_ptr();
2201 if (ignore_space)
2202 {
2203 /*
2204 If we find a space then this can't be an identifier. We notice this
2205 below by checking start != lex->ptr.
2206 */
2207 for (; state_map[(uchar) c] == MY_LEX_SKIP ; c= yyGet())
2208 {
2209 if (c == '\n')
2210 yylineno++;
2211 }
2212 }
2213 if (start == get_ptr() && c == '.' && ident_map[(uchar) yyPeek()])
2214 next_state= MY_LEX_IDENT_SEP;
2215 else
2216 { // '(' must follow directly if function
2217 int tokval;
2218 yyUnget();
2219 if ((tokval= find_keyword(str, length, c == '(')))
2220 {
2221 next_state= MY_LEX_START; // Allow signed numbers
2222 return(tokval); // Was keyword
2223 }
2224 yySkip(); // next state does a unget
2225 }
2226
2227 yyUnget(); // ptr points now after last token char
2228 str->set_ident(m_tok_start, length, is_8bit);
2229 m_cpp_text_start= m_cpp_tok_start;
2230 m_cpp_text_end= m_cpp_text_start + length;
2231
2232 /*
2233 Note: "SELECT _bla AS 'alias'"
2234 _bla should be considered as a IDENT if charset haven't been found.
2235 So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
2236 producing an error.
2237 */
2238 DBUG_ASSERT(length > 0);
2239 if (resolve_introducer && m_tok_start[0] == '_')
2240 {
2241 ErrConvString csname(str->str + 1, str->length - 1, &my_charset_bin);
2242 CHARSET_INFO *cs= get_charset_by_csname(csname.ptr(),
2243 MY_CS_PRIMARY, MYF(0));
2244 if (cs)
2245 {
2246 body_utf8_append(m_cpp_text_start, m_cpp_tok_start + length);
2247 *introducer= cs;
2248 return UNDERSCORE_CHARSET;
2249 }
2250 }
2251
2252 body_utf8_append(m_cpp_text_start);
2253 body_utf8_append_ident(thd, str, m_cpp_text_end);
2254 return is_8bit ? IDENT_QUOTED : IDENT;
2255 }
2256
2257
scan_ident_delimited(THD * thd,Lex_ident_cli_st * str,uchar quote_char)2258 int Lex_input_stream::scan_ident_delimited(THD *thd,
2259 Lex_ident_cli_st *str,
2260 uchar quote_char)
2261 {
2262 CHARSET_INFO *const cs= thd->charset();
2263 uint double_quotes= 0;
2264 uchar c;
2265 DBUG_ASSERT(m_ptr == m_tok_start + 1);
2266
2267 for ( ; ; )
2268 {
2269 if (!(c= yyGet()))
2270 {
2271 /*
2272 End-of-query or straight 0x00 inside a delimited identifier.
2273 Return the quote character, to have the parser fail on syntax error.
2274 */
2275 m_ptr= (char *) m_tok_start + 1;
2276 if (m_echo)
2277 m_cpp_ptr= (char *) m_cpp_tok_start + 1;
2278 return quote_char;
2279 }
2280 int var_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
2281 if (var_length == 1)
2282 {
2283 if (c == quote_char)
2284 {
2285 if (yyPeek() != quote_char)
2286 break;
2287 c= yyGet();
2288 double_quotes++;
2289 continue;
2290 }
2291 }
2292 else if (var_length > 1)
2293 {
2294 skip_binary(var_length - 1);
2295 }
2296 }
2297
2298 str->set_ident_quoted(m_tok_start + 1, yyLength() - 1, true, quote_char);
2299 yyUnget(); // ptr points now after last token char
2300
2301 m_cpp_text_start= m_cpp_tok_start + 1;
2302 m_cpp_text_end= m_cpp_text_start + str->length;
2303
2304 if (c == quote_char)
2305 yySkip(); // Skip end `
2306 next_state= MY_LEX_START;
2307 body_utf8_append(m_cpp_text_start);
2308 // QQQ: shouldn't it add unescaped version ????
2309 body_utf8_append_ident(thd, str, m_cpp_text_end);
2310 return IDENT_QUOTED;
2311 }
2312
2313
trim_whitespace(CHARSET_INFO * cs,LEX_CSTRING * str,size_t * prefix_length)2314 void trim_whitespace(CHARSET_INFO *cs, LEX_CSTRING *str, size_t * prefix_length)
2315 {
2316 /*
2317 TODO:
2318 This code assumes that there are no multi-bytes characters
2319 that can be considered white-space.
2320 */
2321
2322 size_t plen= 0;
2323 while ((str->length > 0) && (my_isspace(cs, str->str[0])))
2324 {
2325 plen++;
2326 str->length --;
2327 str->str ++;
2328 }
2329 if (prefix_length)
2330 *prefix_length= plen;
2331 /*
2332 FIXME:
2333 Also, parsing backward is not safe with multi bytes characters
2334 */
2335 while ((str->length > 0) && (my_isspace(cs, str->str[str->length-1])))
2336 {
2337 str->length --;
2338 }
2339 }
2340
2341
2342 /*
2343 st_select_lex structures initialisations
2344 */
2345
init_query_common()2346 void st_select_lex_node::init_query_common()
2347 {
2348 options= 0;
2349 set_linkage(UNSPECIFIED_TYPE);
2350 distinct= TRUE;
2351 no_table_names_allowed= 0;
2352 uncacheable= 0;
2353 }
2354
init_query()2355 void st_select_lex_unit::init_query()
2356 {
2357 init_query_common();
2358 set_linkage(GLOBAL_OPTIONS_TYPE);
2359 select_limit_cnt= HA_POS_ERROR;
2360 offset_limit_cnt= 0;
2361 union_distinct= 0;
2362 prepared= optimized= optimized_2= executed= 0;
2363 optimize_started= 0;
2364 item= 0;
2365 union_result= 0;
2366 table= 0;
2367 fake_select_lex= 0;
2368 saved_fake_select_lex= 0;
2369 cleaned= 0;
2370 item_list.empty();
2371 describe= 0;
2372 found_rows_for_union= 0;
2373 derived= 0;
2374 is_view= false;
2375 with_clause= 0;
2376 with_element= 0;
2377 cloned_from= 0;
2378 columns_are_renamed= false;
2379 intersect_mark= NULL;
2380 with_wrapped_tvc= false;
2381 }
2382
init_query()2383 void st_select_lex::init_query()
2384 {
2385 init_query_common();
2386 table_list.empty();
2387 top_join_list.empty();
2388 join_list= &top_join_list;
2389 embedding= 0;
2390 leaf_tables_prep.empty();
2391 leaf_tables.empty();
2392 item_list.empty();
2393 min_max_opt_list.empty();
2394 join= 0;
2395 having= prep_having= where= prep_where= 0;
2396 cond_pushed_into_where= cond_pushed_into_having= 0;
2397 attach_to_conds.empty();
2398 olap= UNSPECIFIED_OLAP_TYPE;
2399 having_fix_field= 0;
2400 having_fix_field_for_pushed_cond= 0;
2401 context.select_lex= this;
2402 context.init();
2403 cond_count= between_count= with_wild= 0;
2404 max_equal_elems= 0;
2405 ref_pointer_array.reset();
2406 select_n_where_fields= 0;
2407 select_n_reserved= 0;
2408 select_n_having_items= 0;
2409 n_sum_items= 0;
2410 n_child_sum_items= 0;
2411 hidden_bit_fields= 0;
2412 fields_in_window_functions= 0;
2413 subquery_in_having= explicit_limit= 0;
2414 is_item_list_lookup= 0;
2415 changed_elements= 0;
2416 first_natural_join_processing= 1;
2417 first_cond_optimization= 1;
2418 is_service_select= 0;
2419 parsing_place= NO_MATTER;
2420 save_parsing_place= NO_MATTER;
2421 context_analysis_place= NO_MATTER;
2422 exclude_from_table_unique_test= no_wrap_view_item= FALSE;
2423 nest_level= 0;
2424 link_next= 0;
2425 prep_leaf_list_state= UNINIT;
2426 have_merged_subqueries= FALSE;
2427 bzero((char*) expr_cache_may_be_used, sizeof(expr_cache_may_be_used));
2428 select_list_tables= 0;
2429 m_non_agg_field_used= false;
2430 m_agg_func_used= false;
2431 m_custom_agg_func_used= false;
2432 window_specs.empty();
2433 window_funcs.empty();
2434 tvc= 0;
2435 in_tvc= false;
2436 versioned_tables= 0;
2437 pushdown_select= 0;
2438 }
2439
init_select()2440 void st_select_lex::init_select()
2441 {
2442 sj_nests.empty();
2443 sj_subselects.empty();
2444 group_list.empty();
2445 if (group_list_ptrs)
2446 group_list_ptrs->clear();
2447 type= 0;
2448 db= null_clex_str;
2449 having= 0;
2450 table_join_options= 0;
2451 in_sum_expr= with_wild= 0;
2452 options= 0;
2453 ftfunc_list_alloc.empty();
2454 inner_sum_func_list= 0;
2455 ftfunc_list= &ftfunc_list_alloc;
2456 order_list.empty();
2457 /* Set limit and offset to default values */
2458 select_limit= 0; /* denotes the default limit = HA_POS_ERROR */
2459 offset_limit= 0; /* denotes the default offset = 0 */
2460 is_set_query_expr_tail= false;
2461 with_sum_func= 0;
2462 with_all_modifier= 0;
2463 is_correlated= 0;
2464 cur_pos_in_select_list= UNDEF_POS;
2465 cond_value= having_value= Item::COND_UNDEF;
2466 inner_refs_list.empty();
2467 insert_tables= 0;
2468 merged_into= 0;
2469 m_non_agg_field_used= false;
2470 m_agg_func_used= false;
2471 m_custom_agg_func_used= false;
2472 name_visibility_map.clear_all();
2473 with_dep= 0;
2474 join= 0;
2475 lock_type= TL_READ_DEFAULT;
2476 save_many_values.empty();
2477 save_insert_list= 0;
2478 tvc= 0;
2479 in_funcs.empty();
2480 curr_tvc_name= 0;
2481 in_tvc= false;
2482 versioned_tables= 0;
2483 }
2484
2485 /*
2486 st_select_lex structures linking
2487 */
2488
2489 /* include on level down */
include_down(st_select_lex_node * upper)2490 void st_select_lex_node::include_down(st_select_lex_node *upper)
2491 {
2492 if ((next= upper->slave))
2493 next->prev= &next;
2494 prev= &upper->slave;
2495 upper->slave= this;
2496 master= upper;
2497 slave= 0;
2498 }
2499
2500
add_slave(st_select_lex_node * slave_arg)2501 void st_select_lex_node::add_slave(st_select_lex_node *slave_arg)
2502 {
2503 for (; slave; slave= slave->next)
2504 if (slave == slave_arg)
2505 return;
2506
2507 if (slave)
2508 {
2509 st_select_lex_node *slave_arg_slave= slave_arg->slave;
2510 /* Insert in the front of list of slaves if any. */
2511 slave_arg->include_neighbour(slave);
2512 /* include_neighbour() sets slave_arg->slave=0, restore it. */
2513 slave_arg->slave= slave_arg_slave;
2514 /* Count on include_neighbour() setting the master. */
2515 DBUG_ASSERT(slave_arg->master == this);
2516 }
2517 else
2518 {
2519 slave= slave_arg;
2520 slave_arg->master= this;
2521 slave->prev= &master->slave;
2522 slave->next= 0;
2523 }
2524 }
2525
link_chain_down(st_select_lex_node * first)2526 void st_select_lex_node::link_chain_down(st_select_lex_node *first)
2527 {
2528 st_select_lex_node *last_node;
2529 st_select_lex_node *node= first;
2530 do
2531 {
2532 last_node= node;
2533 node->master= this;
2534 node= node->next;
2535 } while (node);
2536 if ((last_node->next= slave))
2537 {
2538 slave->prev= &last_node->next;
2539 }
2540 first->prev= &slave;
2541 slave= first;
2542 }
2543
2544 /*
2545 @brief
2546 Substitute this node in select tree for a newly creates node
2547
2548 @param subst the node to substitute for
2549
2550 @details
2551 The function substitute this node in the select tree for a newly
2552 created node subst. This node is just removed from the tree but all
2553 its link fields and the attached sub-tree remain untouched.
2554 */
2555
substitute_in_tree(st_select_lex_node * subst)2556 void st_select_lex_node::substitute_in_tree(st_select_lex_node *subst)
2557 {
2558 if ((subst->next= next))
2559 next->prev= &subst->next;
2560 subst->prev= prev;
2561 (*prev)= subst;
2562 subst->master= master;
2563 }
2564
2565 /*
2566 include on level down (but do not link)
2567
2568 SYNOPSYS
2569 st_select_lex_node::include_standalone()
2570 upper - reference on node underr which this node should be included
2571 ref - references on reference on this node
2572 */
include_standalone(st_select_lex_node * upper,st_select_lex_node ** ref)2573 void st_select_lex_node::include_standalone(st_select_lex_node *upper,
2574 st_select_lex_node **ref)
2575 {
2576 next= 0;
2577 prev= ref;
2578 master= upper;
2579 slave= 0;
2580 }
2581
2582 /* include neighbour (on same level) */
include_neighbour(st_select_lex_node * before)2583 void st_select_lex_node::include_neighbour(st_select_lex_node *before)
2584 {
2585 if ((next= before->next))
2586 next->prev= &next;
2587 prev= &before->next;
2588 before->next= this;
2589 master= before->master;
2590 slave= 0;
2591 }
2592
2593 /* including in global SELECT_LEX list */
include_global(st_select_lex_node ** plink)2594 void st_select_lex_node::include_global(st_select_lex_node **plink)
2595 {
2596 if ((link_next= *plink))
2597 link_next->link_prev= &link_next;
2598 link_prev= plink;
2599 *plink= this;
2600 }
2601
2602 //excluding from global list (internal function)
fast_exclude()2603 void st_select_lex_node::fast_exclude()
2604 {
2605 if (link_prev)
2606 {
2607 if ((*link_prev= link_next))
2608 link_next->link_prev= link_prev;
2609 }
2610 // Remove slave structure
2611 for (; slave; slave= slave->next)
2612 slave->fast_exclude();
2613
2614 }
2615
2616
2617 /**
2618 @brief
2619 Insert a new chain of nodes into another chain before a particular link
2620
2621 @param in/out
2622 ptr_pos_to_insert the address of the chain pointer pointing to the link
2623 before which the subchain has to be inserted
2624 @param
2625 end_chain_node the last link of the subchain to be inserted
2626
2627 @details
2628 The method inserts the chain of nodes starting from this node and ending
2629 with the node nd_chain_node into another chain of nodes before the node
2630 pointed to by *ptr_pos_to_insert.
2631 It is assumed that ptr_pos_to_insert belongs to the chain where we insert.
2632 So it must be updated.
2633
2634 @retval
2635 The method returns the pointer to the first link of the inserted chain
2636 */
2637
insert_chain_before(st_select_lex_node ** ptr_pos_to_insert,st_select_lex_node * end_chain_node)2638 st_select_lex_node *st_select_lex_node:: insert_chain_before(
2639 st_select_lex_node **ptr_pos_to_insert,
2640 st_select_lex_node *end_chain_node)
2641 {
2642 end_chain_node->link_next= *ptr_pos_to_insert;
2643 (*ptr_pos_to_insert)->link_prev= &end_chain_node->link_next;
2644 this->link_prev= ptr_pos_to_insert;
2645 return this;
2646 }
2647
2648
2649 /*
2650 Detach the node from its master and attach it to a new master
2651 */
2652
move_as_slave(st_select_lex_node * new_master)2653 void st_select_lex_node::move_as_slave(st_select_lex_node *new_master)
2654 {
2655 exclude_from_tree();
2656 if (new_master->slave)
2657 {
2658 st_select_lex_node *curr= new_master->slave;
2659 for ( ; curr->next ; curr= curr->next) ;
2660 prev= &curr->next;
2661 }
2662 else
2663 prev= &new_master->slave;
2664 *prev= this;
2665 next= 0;
2666 master= new_master;
2667 }
2668
2669
2670 /*
2671 Exclude a node from the tree lex structure, but leave it in the global
2672 list of nodes.
2673 */
2674
exclude_from_tree()2675 void st_select_lex_node::exclude_from_tree()
2676 {
2677 if ((*prev= next))
2678 next->prev= prev;
2679 }
2680
2681
2682 /*
2683 Exclude select_lex structure (except first (first select can't be
2684 deleted, because it is most upper select))
2685 */
exclude()2686 void st_select_lex_node::exclude()
2687 {
2688 /* exclude from global list */
2689 fast_exclude();
2690 /* exclude from other structures */
2691 exclude_from_tree();
2692 /*
2693 We do not need following statements, because prev pointer of first
2694 list element point to master->slave
2695 if (master->slave == this)
2696 master->slave= next;
2697 */
2698 }
2699
2700
2701 /*
2702 Exclude level of current unit from tree of SELECTs
2703
2704 SYNOPSYS
2705 st_select_lex_unit::exclude_level()
2706
2707 NOTE: units which belong to current will be brought up on level of
2708 currernt unit
2709 */
exclude_level()2710 void st_select_lex_unit::exclude_level()
2711 {
2712 SELECT_LEX_UNIT *units= 0, **units_last= &units;
2713 for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
2714 {
2715 // unlink current level from global SELECTs list
2716 if (sl->link_prev && (*sl->link_prev= sl->link_next))
2717 sl->link_next->link_prev= sl->link_prev;
2718
2719 // bring up underlay levels
2720 SELECT_LEX_UNIT **last= 0;
2721 for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
2722 {
2723 u->master= master;
2724 last= (SELECT_LEX_UNIT**)&(u->next);
2725 }
2726 if (last)
2727 {
2728 (*units_last)= sl->first_inner_unit();
2729 units_last= last;
2730 }
2731 }
2732 if (units)
2733 {
2734 // include brought up levels in place of current
2735 (*prev)= units;
2736 (*units_last)= (SELECT_LEX_UNIT*)next;
2737 if (next)
2738 next->prev= (SELECT_LEX_NODE**)units_last;
2739 units->prev= prev;
2740 }
2741 else
2742 {
2743 // exclude currect unit from list of nodes
2744 (*prev)= next;
2745 if (next)
2746 next->prev= prev;
2747 }
2748 // Mark it excluded
2749 prev= NULL;
2750 }
2751
2752
2753 #if 0
2754 /*
2755 Exclude subtree of current unit from tree of SELECTs
2756
2757 SYNOPSYS
2758 st_select_lex_unit::exclude_tree()
2759 */
2760 void st_select_lex_unit::exclude_tree()
2761 {
2762 for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
2763 {
2764 // unlink current level from global SELECTs list
2765 if (sl->link_prev && (*sl->link_prev= sl->link_next))
2766 sl->link_next->link_prev= sl->link_prev;
2767
2768 // unlink underlay levels
2769 for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
2770 {
2771 u->exclude_level();
2772 }
2773 }
2774 // exclude currect unit from list of nodes
2775 (*prev)= next;
2776 if (next)
2777 next->prev= prev;
2778 }
2779 #endif
2780
2781
2782 /*
2783 st_select_lex_node::mark_as_dependent mark all st_select_lex struct from
2784 this to 'last' as dependent
2785
2786 SYNOPSIS
2787 last - pointer to last st_select_lex struct, before which all
2788 st_select_lex have to be marked as dependent
2789
2790 NOTE
2791 'last' should be reachable from this st_select_lex_node
2792 */
2793
mark_as_dependent(THD * thd,st_select_lex * last,Item_ident * dependency)2794 bool st_select_lex::mark_as_dependent(THD *thd, st_select_lex *last,
2795 Item_ident *dependency)
2796 {
2797
2798 DBUG_ASSERT(this != last);
2799
2800 /*
2801 Mark all selects from resolved to 1 before select where was
2802 found table as depended (of select where was found table)
2803
2804 We move by name resolution context, bacause during merge can some select
2805 be excleded from SELECT tree
2806 */
2807 Name_resolution_context *c= &this->context;
2808 do
2809 {
2810 SELECT_LEX *s= c->select_lex;
2811 if (!(s->uncacheable & UNCACHEABLE_DEPENDENT_GENERATED))
2812 {
2813 // Select is dependent of outer select
2814 s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
2815 UNCACHEABLE_DEPENDENT_GENERATED;
2816 SELECT_LEX_UNIT *munit= s->master_unit();
2817 munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
2818 UNCACHEABLE_DEPENDENT_GENERATED;
2819 for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
2820 {
2821 if (sl != s &&
2822 !(sl->uncacheable & (UNCACHEABLE_DEPENDENT_GENERATED |
2823 UNCACHEABLE_UNITED)))
2824 sl->uncacheable|= UNCACHEABLE_UNITED;
2825 }
2826 }
2827
2828 Item_subselect *subquery_expr= s->master_unit()->item;
2829 if (subquery_expr && subquery_expr->mark_as_dependent(thd, last,
2830 dependency))
2831 return TRUE;
2832 } while ((c= c->outer_context) != NULL && (c->select_lex != last));
2833 is_correlated= TRUE;
2834 this->master_unit()->item->is_correlated= TRUE;
2835 return FALSE;
2836 }
2837
2838 /*
2839 prohibit using LIMIT clause
2840 */
test_limit()2841 bool st_select_lex::test_limit()
2842 {
2843 if (select_limit != 0)
2844 {
2845 my_error(ER_NOT_SUPPORTED_YET, MYF(0),
2846 "LIMIT & IN/ALL/ANY/SOME subquery");
2847 return(1);
2848 }
2849 return(0);
2850 }
2851
2852
2853
outer_select()2854 st_select_lex* st_select_lex_unit::outer_select()
2855 {
2856 return (st_select_lex*) master;
2857 }
2858
2859
get_offset()2860 ha_rows st_select_lex::get_offset()
2861 {
2862 ulonglong val= 0;
2863
2864 if (offset_limit)
2865 {
2866 // see comment for st_select_lex::get_limit()
2867 bool err= offset_limit->fix_fields_if_needed(master_unit()->thd, NULL);
2868 DBUG_ASSERT(!err);
2869 val= err ? HA_POS_ERROR : offset_limit->val_uint();
2870 }
2871
2872 return (ha_rows)val;
2873 }
2874
2875
get_limit()2876 ha_rows st_select_lex::get_limit()
2877 {
2878 ulonglong val= HA_POS_ERROR;
2879
2880 if (select_limit)
2881 {
2882 /*
2883 fix_fields() has not been called for select_limit. That's due to the
2884 historical reasons -- this item could be only of type Item_int, and
2885 Item_int does not require fix_fields(). Thus, fix_fields() was never
2886 called for select_limit.
2887
2888 Some time ago, Item_splocal was also allowed for LIMIT / OFFSET clauses.
2889 However, the fix_fields() behavior was not updated, which led to a crash
2890 in some cases.
2891
2892 There is no single place where to call fix_fields() for LIMIT / OFFSET
2893 items during the fix-fields-phase. Thus, for the sake of readability,
2894 it was decided to do it here, on the evaluation phase (which is a
2895 violation of design, but we chose the lesser of two evils).
2896
2897 We can call fix_fields() here, because select_limit can be of two
2898 types only: Item_int and Item_splocal. Item_int::fix_fields() is trivial,
2899 and Item_splocal::fix_fields() (or rather Item_sp_variable::fix_fields())
2900 has the following properties:
2901 1) it does not affect other items;
2902 2) it does not fail.
2903
2904 Nevertheless DBUG_ASSERT was added to catch future changes in
2905 fix_fields() implementation. Also added runtime check against a result
2906 of fix_fields() in order to handle error condition in non-debug build.
2907 */
2908 bool err= select_limit->fix_fields_if_needed(master_unit()->thd, NULL);
2909 DBUG_ASSERT(!err);
2910 val= err ? HA_POS_ERROR : select_limit->val_uint();
2911 }
2912
2913 return (ha_rows)val;
2914 }
2915
2916
add_order_to_list(THD * thd,Item * item,bool asc)2917 bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
2918 {
2919 return add_to_list(thd, order_list, item, asc);
2920 }
2921
2922
add_gorder_to_list(THD * thd,Item * item,bool asc)2923 bool st_select_lex::add_gorder_to_list(THD *thd, Item *item, bool asc)
2924 {
2925 return add_to_list(thd, gorder_list, item, asc);
2926 }
2927
2928
add_item_to_list(THD * thd,Item * item)2929 bool st_select_lex::add_item_to_list(THD *thd, Item *item)
2930 {
2931 DBUG_ENTER("st_select_lex::add_item_to_list");
2932 DBUG_PRINT("info", ("Item: %p", item));
2933 DBUG_RETURN(item_list.push_back(item, thd->mem_root));
2934 }
2935
2936
add_group_to_list(THD * thd,Item * item,bool asc)2937 bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
2938 {
2939 return add_to_list(thd, group_list, item, asc);
2940 }
2941
2942
add_ftfunc_to_list(THD * thd,Item_func_match * func)2943 bool st_select_lex::add_ftfunc_to_list(THD *thd, Item_func_match *func)
2944 {
2945 return !func || ftfunc_list->push_back(func, thd->mem_root); // end of memory?
2946 }
2947
2948
outer_select()2949 st_select_lex* st_select_lex::outer_select()
2950 {
2951 return (st_select_lex*) master->get_master();
2952 }
2953
2954
inc_in_sum_expr()2955 bool st_select_lex::inc_in_sum_expr()
2956 {
2957 in_sum_expr++;
2958 return 0;
2959 }
2960
2961
get_in_sum_expr()2962 uint st_select_lex::get_in_sum_expr()
2963 {
2964 return in_sum_expr;
2965 }
2966
2967
get_table_list()2968 TABLE_LIST* st_select_lex::get_table_list()
2969 {
2970 return table_list.first;
2971 }
2972
get_item_list()2973 List<Item>* st_select_lex::get_item_list()
2974 {
2975 return &item_list;
2976 }
2977
get_table_join_options()2978 ulong st_select_lex::get_table_join_options()
2979 {
2980 return table_join_options;
2981 }
2982
2983
setup_ref_array(THD * thd,uint order_group_num)2984 bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
2985 {
2986
2987 if (!((options & SELECT_DISTINCT) && !group_list.elements))
2988 hidden_bit_fields= 0;
2989
2990 // find_order_in_list() may need some extra space, so multiply by two.
2991 order_group_num*= 2;
2992
2993 /*
2994 We have to create array in prepared statement memory if it is a
2995 prepared statement
2996 */
2997 Query_arena *arena= thd->stmt_arena;
2998 const size_t n_elems= (n_sum_items +
2999 n_child_sum_items +
3000 item_list.elements +
3001 select_n_reserved +
3002 select_n_having_items +
3003 select_n_where_fields +
3004 order_group_num +
3005 hidden_bit_fields +
3006 fields_in_window_functions) * (size_t) 5;
3007 DBUG_ASSERT(n_elems % 5 == 0);
3008 if (!ref_pointer_array.is_null())
3009 {
3010 /*
3011 We need to take 'n_sum_items' into account when allocating the array,
3012 and this may actually increase during the optimization phase due to
3013 MIN/MAX rewrite in Item_in_subselect::single_value_transformer.
3014 In the usual case we can reuse the array from the prepare phase.
3015 If we need a bigger array, we must allocate a new one.
3016 */
3017 if (ref_pointer_array.size() >= n_elems)
3018 return false;
3019 }
3020 Item **array= static_cast<Item**>(arena->alloc(sizeof(Item*) * n_elems));
3021 if (likely(array != NULL))
3022 ref_pointer_array= Ref_ptr_array(array, n_elems);
3023
3024 return array == NULL;
3025 }
3026
3027
print(String * str,enum_query_type query_type)3028 void st_select_lex_unit::print(String *str, enum_query_type query_type)
3029 {
3030 bool union_all= !union_distinct;
3031 if (with_clause)
3032 with_clause->print(str, query_type);
3033 for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
3034 {
3035 if (sl != first_select())
3036 {
3037 switch (sl->linkage)
3038 {
3039 default:
3040 DBUG_ASSERT(0);
3041 /* fall through */
3042 case UNION_TYPE:
3043 str->append(STRING_WITH_LEN(" union "));
3044 if (union_all)
3045 str->append(STRING_WITH_LEN("all "));
3046 break;
3047 case INTERSECT_TYPE:
3048 str->append(STRING_WITH_LEN(" intersect "));
3049 break;
3050 case EXCEPT_TYPE:
3051 str->append(STRING_WITH_LEN(" except "));
3052 break;
3053 }
3054 if (sl == union_distinct)
3055 union_all= TRUE;
3056 }
3057 if (sl->braces)
3058 str->append('(');
3059 sl->print(thd, str, query_type);
3060 if (sl->braces)
3061 str->append(')');
3062 }
3063 if (fake_select_lex)
3064 {
3065 if (fake_select_lex->order_list.elements)
3066 {
3067 str->append(STRING_WITH_LEN(" order by "));
3068 fake_select_lex->print_order(str,
3069 fake_select_lex->order_list.first,
3070 query_type);
3071 }
3072 fake_select_lex->print_limit(thd, str, query_type);
3073 }
3074 else if (saved_fake_select_lex)
3075 saved_fake_select_lex->print_limit(thd, str, query_type);
3076 }
3077
3078
print_order(String * str,ORDER * order,enum_query_type query_type)3079 void st_select_lex::print_order(String *str,
3080 ORDER *order,
3081 enum_query_type query_type)
3082 {
3083 for (; order; order= order->next)
3084 {
3085 if (order->counter_used)
3086 {
3087 char buffer[20];
3088 size_t length= my_snprintf(buffer, 20, "%d", order->counter);
3089 str->append(buffer, (uint) length);
3090 }
3091 else
3092 {
3093 /* replace numeric reference with equivalent for ORDER constant */
3094 if (order->item[0]->is_order_clause_position())
3095 {
3096 /* make it expression instead of integer constant */
3097 str->append(STRING_WITH_LEN("''"));
3098 }
3099 else
3100 (*order->item)->print(str, query_type);
3101 }
3102 if (order->direction == ORDER::ORDER_DESC)
3103 str->append(STRING_WITH_LEN(" desc"));
3104 if (order->next)
3105 str->append(',');
3106 }
3107 }
3108
3109
print_limit(THD * thd,String * str,enum_query_type query_type)3110 void st_select_lex::print_limit(THD *thd,
3111 String *str,
3112 enum_query_type query_type)
3113 {
3114 SELECT_LEX_UNIT *unit= master_unit();
3115 Item_subselect *item= unit->item;
3116
3117 if (item && unit->global_parameters() == this)
3118 {
3119 Item_subselect::subs_type subs_type= item->substype();
3120 if (subs_type == Item_subselect::IN_SUBS ||
3121 subs_type == Item_subselect::ALL_SUBS)
3122 {
3123 return;
3124 }
3125 }
3126 if (explicit_limit && select_limit)
3127 {
3128 str->append(STRING_WITH_LEN(" limit "));
3129 if (offset_limit)
3130 {
3131 offset_limit->print(str, query_type);
3132 str->append(',');
3133 }
3134 select_limit->print(str, query_type);
3135 }
3136 }
3137
3138
3139 /**
3140 @brief Restore the LEX and THD in case of a parse error.
3141
3142 This is a clean up call that is invoked by the Bison generated
3143 parser before returning an error from MYSQLparse. If your
3144 semantic actions manipulate with the global thread state (which
3145 is a very bad practice and should not normally be employed) and
3146 need a clean-up in case of error, and you can not use %destructor
3147 rule in the grammar file itself, this function should be used
3148 to implement the clean up.
3149 */
3150
cleanup_lex_after_parse_error(THD * thd)3151 void LEX::cleanup_lex_after_parse_error(THD *thd)
3152 {
3153 /*
3154 Delete sphead for the side effect of restoring of the original
3155 LEX state, thd->lex, thd->mem_root and thd->free_list if they
3156 were replaced when parsing stored procedure statements. We
3157 will never use sphead object after a parse error, so it's okay
3158 to delete it only for the sake of the side effect.
3159 TODO: make this functionality explicit in sp_head class.
3160 Sic: we must nullify the member of the main lex, not the
3161 current one that will be thrown away
3162 */
3163 if (thd->lex->sphead)
3164 {
3165 sp_package *pkg;
3166 thd->lex->sphead->restore_thd_mem_root(thd);
3167 if ((pkg= thd->lex->sphead->m_parent))
3168 {
3169 /*
3170 If a syntax error happened inside a package routine definition,
3171 then thd->lex points to the routine sublex. We need to restore to
3172 the top level LEX.
3173 */
3174 DBUG_ASSERT(pkg->m_top_level_lex);
3175 DBUG_ASSERT(pkg == pkg->m_top_level_lex->sphead);
3176 pkg->restore_thd_mem_root(thd);
3177 LEX *top= pkg->m_top_level_lex;
3178 sp_package::destroy(pkg);
3179 thd->lex= top;
3180 thd->lex->sphead= NULL;
3181 }
3182 else
3183 {
3184 sp_head::destroy(thd->lex->sphead);
3185 thd->lex->sphead= NULL;
3186 }
3187 }
3188 }
3189
3190 /*
3191 Initialize (or reset) Query_tables_list object.
3192
3193 SYNOPSIS
3194 reset_query_tables_list()
3195 init TRUE - we should perform full initialization of object with
3196 allocating needed memory
3197 FALSE - object is already initialized so we should only reset
3198 its state so it can be used for parsing/processing
3199 of new statement
3200
3201 DESCRIPTION
3202 This method initializes Query_tables_list so it can be used as part
3203 of LEX object for parsing/processing of statement. One can also use
3204 this method to reset state of already initialized Query_tables_list
3205 so it can be used for processing of new statement.
3206 */
3207
reset_query_tables_list(bool init)3208 void Query_tables_list::reset_query_tables_list(bool init)
3209 {
3210 sql_command= SQLCOM_END;
3211 if (!init && query_tables)
3212 {
3213 TABLE_LIST *table= query_tables;
3214 for (;;)
3215 {
3216 delete table->view;
3217 if (query_tables_last == &table->next_global ||
3218 !(table= table->next_global))
3219 break;
3220 }
3221 }
3222 query_tables= 0;
3223 query_tables_last= &query_tables;
3224 query_tables_own_last= 0;
3225 if (init)
3226 {
3227 /*
3228 We delay real initialization of hash (and therefore related
3229 memory allocation) until first insertion into this hash.
3230 */
3231 my_hash_clear(&sroutines);
3232 }
3233 else if (sroutines.records)
3234 {
3235 /* Non-zero sroutines.records means that hash was initialized. */
3236 my_hash_reset(&sroutines);
3237 }
3238 sroutines_list.empty();
3239 sroutines_list_own_last= sroutines_list.next;
3240 sroutines_list_own_elements= 0;
3241 binlog_stmt_flags= 0;
3242 stmt_accessed_table_flag= 0;
3243 }
3244
3245
3246 /*
3247 Destroy Query_tables_list object with freeing all resources used by it.
3248
3249 SYNOPSIS
3250 destroy_query_tables_list()
3251 */
3252
destroy_query_tables_list()3253 void Query_tables_list::destroy_query_tables_list()
3254 {
3255 my_hash_free(&sroutines);
3256 }
3257
3258
3259 /*
3260 Initialize LEX object.
3261
3262 SYNOPSIS
3263 LEX::LEX()
3264
3265 NOTE
3266 LEX object initialized with this constructor can be used as part of
3267 THD object for which one can safely call open_tables(), lock_tables()
3268 and close_thread_tables() functions. But it is not yet ready for
3269 statement parsing. On should use lex_start() function to prepare LEX
3270 for this.
3271 */
3272
LEX()3273 LEX::LEX()
3274 : explain(NULL), result(0), part_info(NULL), arena_for_set_stmt(0), mem_root_for_set_stmt(0),
3275 option_type(OPT_DEFAULT), context_analysis_only(0), sphead(0),
3276 default_used(0), is_lex_started(0), limit_rows_examined_cnt(ULONGLONG_MAX)
3277 {
3278
3279 init_dynamic_array2(&plugins, sizeof(plugin_ref), plugins_static_buffer,
3280 INITIAL_LEX_PLUGIN_LIST_SIZE,
3281 INITIAL_LEX_PLUGIN_LIST_SIZE, 0);
3282 reset_query_tables_list(TRUE);
3283 mi.init();
3284 init_dynamic_array2(&delete_gtid_domain, sizeof(uint32),
3285 gtid_domain_static_buffer,
3286 initial_gtid_domain_buffer_size,
3287 initial_gtid_domain_buffer_size, 0);
3288 unit.slave= &builtin_select;
3289 }
3290
3291
3292 /*
3293 Check whether the merging algorithm can be used on this VIEW
3294
3295 SYNOPSIS
3296 LEX::can_be_merged()
3297
3298 DESCRIPTION
3299 We can apply merge algorithm if it is single SELECT view with
3300 subqueries only in WHERE clause (we do not count SELECTs of underlying
3301 views, and second level subqueries) and we have not grpouping, ordering,
3302 HAVING clause, aggregate functions, DISTINCT clause, LIMIT clause and
3303 several underlying tables.
3304
3305 RETURN
3306 FALSE - only temporary table algorithm can be used
3307 TRUE - merge algorithm can be used
3308 */
3309
can_be_merged()3310 bool LEX::can_be_merged()
3311 {
3312 // TODO: do not forget implement case when select_lex.table_list.elements==0
3313
3314 /* find non VIEW subqueries/unions */
3315 bool selects_allow_merge= (first_select_lex()->next_select() == 0 &&
3316 !(first_select_lex()->uncacheable &
3317 UNCACHEABLE_RAND));
3318 if (selects_allow_merge)
3319 {
3320 for (SELECT_LEX_UNIT *tmp_unit= first_select_lex()->first_inner_unit();
3321 tmp_unit;
3322 tmp_unit= tmp_unit->next_unit())
3323 {
3324 if (tmp_unit->first_select()->parent_lex == this &&
3325 (tmp_unit->item != 0 &&
3326 (tmp_unit->item->place() != IN_WHERE &&
3327 tmp_unit->item->place() != IN_ON &&
3328 tmp_unit->item->place() != SELECT_LIST)))
3329 {
3330 selects_allow_merge= 0;
3331 break;
3332 }
3333 }
3334 }
3335
3336 return (selects_allow_merge &&
3337 first_select_lex()->group_list.elements == 0 &&
3338 first_select_lex()->having == 0 &&
3339 first_select_lex()->with_sum_func == 0 &&
3340 first_select_lex()->table_list.elements >= 1 &&
3341 !(first_select_lex()->options & SELECT_DISTINCT) &&
3342 first_select_lex()->select_limit == 0);
3343 }
3344
3345
3346 /*
3347 check if command can use VIEW with MERGE algorithm (for top VIEWs)
3348
3349 SYNOPSIS
3350 LEX::can_use_merged()
3351
3352 DESCRIPTION
3353 Only listed here commands can use merge algorithm in top level
3354 SELECT_LEX (for subqueries will be used merge algorithm if
3355 LEX::can_not_use_merged() is not TRUE).
3356
3357 RETURN
3358 FALSE - command can't use merged VIEWs
3359 TRUE - VIEWs with MERGE algorithms can be used
3360 */
3361
can_use_merged()3362 bool LEX::can_use_merged()
3363 {
3364 switch (sql_command)
3365 {
3366 case SQLCOM_SELECT:
3367 case SQLCOM_CREATE_TABLE:
3368 case SQLCOM_UPDATE:
3369 case SQLCOM_UPDATE_MULTI:
3370 case SQLCOM_DELETE:
3371 case SQLCOM_DELETE_MULTI:
3372 case SQLCOM_INSERT:
3373 case SQLCOM_INSERT_SELECT:
3374 case SQLCOM_REPLACE:
3375 case SQLCOM_REPLACE_SELECT:
3376 case SQLCOM_LOAD:
3377 return TRUE;
3378 default:
3379 return FALSE;
3380 }
3381 }
3382
3383 /*
3384 Check if command can't use merged views in any part of command
3385
3386 SYNOPSIS
3387 LEX::can_not_use_merged()
3388
3389 DESCRIPTION
3390 Temporary table algorithm will be used on all SELECT levels for queries
3391 listed here (see also LEX::can_use_merged()).
3392
3393 RETURN
3394 FALSE - command can't use merged VIEWs
3395 TRUE - VIEWs with MERGE algorithms can be used
3396 */
3397
can_not_use_merged()3398 bool LEX::can_not_use_merged()
3399 {
3400 switch (sql_command)
3401 {
3402 case SQLCOM_CREATE_VIEW:
3403 case SQLCOM_SHOW_CREATE:
3404 /*
3405 SQLCOM_SHOW_FIELDS is necessary to make
3406 information schema tables working correctly with views.
3407 see get_schema_tables_result function
3408 */
3409 case SQLCOM_SHOW_FIELDS:
3410 return TRUE;
3411 default:
3412 return FALSE;
3413 }
3414 }
3415
3416 /**
3417 Detect that we need only table structure of derived table/view.
3418
3419 Also used by I_S tables (@see create_schema_table) to detect that
3420 they need a full table structure and cannot optimize unused columns away
3421
3422 @retval TRUE yes, we need only structure
3423 @retval FALSE no, we need data
3424 */
3425
only_view_structure()3426 bool LEX::only_view_structure()
3427 {
3428 switch (sql_command) {
3429 case SQLCOM_SHOW_CREATE:
3430 case SQLCOM_CHECKSUM:
3431 case SQLCOM_SHOW_TABLES:
3432 case SQLCOM_SHOW_FIELDS:
3433 case SQLCOM_REVOKE_ALL:
3434 case SQLCOM_REVOKE:
3435 case SQLCOM_GRANT:
3436 case SQLCOM_CREATE_VIEW:
3437 return TRUE;
3438 case SQLCOM_CREATE_TABLE:
3439 return create_info.like();
3440 default:
3441 return FALSE;
3442 }
3443 }
3444
3445
3446 /*
3447 Should Items_ident be printed correctly
3448
3449 SYNOPSIS
3450 need_correct_ident()
3451
3452 RETURN
3453 TRUE yes, we need only structure
3454 FALSE no, we need data
3455 */
3456
3457
need_correct_ident()3458 bool LEX::need_correct_ident()
3459 {
3460 switch(sql_command)
3461 {
3462 case SQLCOM_SHOW_CREATE:
3463 case SQLCOM_SHOW_TABLES:
3464 case SQLCOM_CREATE_VIEW:
3465 return TRUE;
3466 default:
3467 return FALSE;
3468 }
3469 }
3470
3471 /*
3472 Get effective type of CHECK OPTION for given view
3473
3474 SYNOPSIS
3475 get_effective_with_check()
3476 view given view
3477
3478 NOTE
3479 It have not sense to set CHECK OPTION for SELECT satement or subqueries,
3480 so we do not.
3481
3482 RETURN
3483 VIEW_CHECK_NONE no need CHECK OPTION
3484 VIEW_CHECK_LOCAL CHECK OPTION LOCAL
3485 VIEW_CHECK_CASCADED CHECK OPTION CASCADED
3486 */
3487
get_effective_with_check(TABLE_LIST * view)3488 uint8 LEX::get_effective_with_check(TABLE_LIST *view)
3489 {
3490 if (view->select_lex->master_unit() == &unit &&
3491 which_check_option_applicable())
3492 return (uint8)view->with_check;
3493 return VIEW_CHECK_NONE;
3494 }
3495
3496
3497 /**
3498 This method should be called only during parsing.
3499 It is aware of compound statements (stored routine bodies)
3500 and will initialize the destination with the default
3501 database of the stored routine, rather than the default
3502 database of the connection it is parsed in.
3503 E.g. if one has no current database selected, or current database
3504 set to 'bar' and then issues:
3505
3506 CREATE PROCEDURE foo.p1() BEGIN SELECT * FROM t1 END//
3507
3508 t1 is meant to refer to foo.t1, not to bar.t1.
3509
3510 This method is needed to support this rule.
3511
3512 @return TRUE in case of error (parsing should be aborted, FALSE in
3513 case of success
3514 */
3515
copy_db_to(LEX_CSTRING * to)3516 bool LEX::copy_db_to(LEX_CSTRING *to)
3517 {
3518 if (sphead && sphead->m_name.str)
3519 {
3520 DBUG_ASSERT(sphead->m_db.str && sphead->m_db.length);
3521 /*
3522 It is safe to assign the string by-pointer, both sphead and
3523 its statements reside in the same memory root.
3524 */
3525 *to= sphead->m_db;
3526 return FALSE;
3527 }
3528 return thd->copy_db_to(to);
3529 }
3530
3531 /**
3532 Initialize offset and limit counters.
3533
3534 @param sl SELECT_LEX to get offset and limit from.
3535 */
3536
set_limit(st_select_lex * sl)3537 void st_select_lex_unit::set_limit(st_select_lex *sl)
3538 {
3539 DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
3540
3541 offset_limit_cnt= sl->get_offset();
3542 select_limit_cnt= sl->get_limit();
3543 if (select_limit_cnt + offset_limit_cnt >= select_limit_cnt)
3544 select_limit_cnt+= offset_limit_cnt;
3545 else
3546 select_limit_cnt= HA_POS_ERROR;
3547 }
3548
3549
3550 /**
3551 Decide if a temporary table is needed for the UNION.
3552
3553 @retval true A temporary table is needed.
3554 @retval false A temporary table is not needed.
3555 */
3556
union_needs_tmp_table()3557 bool st_select_lex_unit::union_needs_tmp_table()
3558 {
3559 if (with_element && with_element->is_recursive)
3560 return true;
3561 if (!with_wrapped_tvc)
3562 {
3563 for (st_select_lex *sl= first_select(); sl; sl=sl->next_select())
3564 {
3565 if (sl->tvc && sl->tvc->to_be_wrapped_as_with_tail())
3566 {
3567 with_wrapped_tvc= true;
3568 break;
3569 }
3570 }
3571 }
3572 if (with_wrapped_tvc)
3573 return true;
3574 return union_distinct != NULL ||
3575 global_parameters()->order_list.elements != 0 ||
3576 thd->lex->sql_command == SQLCOM_INSERT_SELECT ||
3577 thd->lex->sql_command == SQLCOM_REPLACE_SELECT;
3578 }
3579
3580 /**
3581 @brief Set the initial purpose of this TABLE_LIST object in the list of used
3582 tables.
3583
3584 We need to track this information on table-by-table basis, since when this
3585 table becomes an element of the pre-locked list, it's impossible to identify
3586 which SQL sub-statement it has been originally used in.
3587
3588 E.g.:
3589
3590 User request: SELECT * FROM t1 WHERE f1();
3591 FUNCTION f1(): DELETE FROM t2; RETURN 1;
3592 BEFORE DELETE trigger on t2: INSERT INTO t3 VALUES (old.a);
3593
3594 For this user request, the pre-locked list will contain t1, t2, t3
3595 table elements, each needed for different DML.
3596
3597 The trigger event map is updated to reflect INSERT, UPDATE, DELETE,
3598 REPLACE, LOAD DATA, CREATE TABLE .. SELECT, CREATE TABLE ..
3599 REPLACE SELECT statements, and additionally ON DUPLICATE KEY UPDATE
3600 clause.
3601 */
3602
set_trg_event_type_for_tables()3603 void LEX::set_trg_event_type_for_tables()
3604 {
3605 uint8 new_trg_event_map= 0;
3606 DBUG_ENTER("LEX::set_trg_event_type_for_tables");
3607
3608 /*
3609 Some auxiliary operations
3610 (e.g. GRANT processing) create TABLE_LIST instances outside
3611 the parser. Additionally, some commands (e.g. OPTIMIZE) change
3612 the lock type for a table only after parsing is done. Luckily,
3613 these do not fire triggers and do not need to pre-load them.
3614 For these TABLE_LISTs set_trg_event_type is never called, and
3615 trg_event_map is always empty. That means that the pre-locking
3616 algorithm will ignore triggers defined on these tables, if
3617 any, and the execution will either fail with an assert in
3618 sql_trigger.cc or with an error that a used table was not
3619 pre-locked, in case of a production build.
3620
3621 TODO: this usage pattern creates unnecessary module dependencies
3622 and should be rewritten to go through the parser.
3623 Table list instances created outside the parser in most cases
3624 refer to mysql.* system tables. It is not allowed to have
3625 a trigger on a system table, but keeping track of
3626 initialization provides extra safety in case this limitation
3627 is circumvented.
3628 */
3629
3630 switch (sql_command) {
3631 case SQLCOM_LOCK_TABLES:
3632 /*
3633 On a LOCK TABLE, all triggers must be pre-loaded for this TABLE_LIST
3634 when opening an associated TABLE.
3635 */
3636 new_trg_event_map= trg2bit(TRG_EVENT_INSERT) | trg2bit(TRG_EVENT_UPDATE) |
3637 trg2bit(TRG_EVENT_DELETE);
3638 break;
3639 /*
3640 Basic INSERT. If there is an additional ON DUPLIATE KEY UPDATE
3641 clause, it will be handled later in this method.
3642 */
3643 case SQLCOM_INSERT: /* fall through */
3644 case SQLCOM_INSERT_SELECT:
3645 /*
3646 LOAD DATA ... INFILE is expected to fire BEFORE/AFTER INSERT
3647 triggers.
3648 If the statement also has REPLACE clause, it will be
3649 handled later in this method.
3650 */
3651 case SQLCOM_LOAD: /* fall through */
3652 /*
3653 REPLACE is semantically equivalent to INSERT. In case
3654 of a primary or unique key conflict, it deletes the old
3655 record and inserts a new one. So we also may need to
3656 fire ON DELETE triggers. This functionality is handled
3657 later in this method.
3658 */
3659 case SQLCOM_REPLACE: /* fall through */
3660 case SQLCOM_REPLACE_SELECT:
3661 /*
3662 CREATE TABLE ... SELECT defaults to INSERT if the table or
3663 view already exists. REPLACE option of CREATE TABLE ...
3664 REPLACE SELECT is handled later in this method.
3665 */
3666 case SQLCOM_CREATE_TABLE:
3667 case SQLCOM_CREATE_SEQUENCE:
3668 new_trg_event_map|= trg2bit(TRG_EVENT_INSERT);
3669 break;
3670 /* Basic update and multi-update */
3671 case SQLCOM_UPDATE: /* fall through */
3672 case SQLCOM_UPDATE_MULTI:
3673 new_trg_event_map|= trg2bit(TRG_EVENT_UPDATE);
3674 break;
3675 /* Basic delete and multi-delete */
3676 case SQLCOM_DELETE: /* fall through */
3677 case SQLCOM_DELETE_MULTI:
3678 new_trg_event_map|= trg2bit(TRG_EVENT_DELETE);
3679 break;
3680 default:
3681 break;
3682 }
3683
3684 switch (duplicates) {
3685 case DUP_UPDATE:
3686 new_trg_event_map|= trg2bit(TRG_EVENT_UPDATE);
3687 break;
3688 case DUP_REPLACE:
3689 new_trg_event_map|= trg2bit(TRG_EVENT_DELETE);
3690 break;
3691 case DUP_ERROR:
3692 default:
3693 break;
3694 }
3695
3696 if (period_conditions.is_set())
3697 {
3698 switch (sql_command)
3699 {
3700 case SQLCOM_DELETE:
3701 case SQLCOM_UPDATE:
3702 case SQLCOM_REPLACE:
3703 new_trg_event_map |= trg2bit(TRG_EVENT_INSERT);
3704 default:
3705 break;
3706 }
3707 }
3708
3709
3710 /*
3711 Do not iterate over sub-selects, only the tables in the outermost
3712 SELECT_LEX can be modified, if any.
3713 */
3714 TABLE_LIST *tables= first_select_lex()->get_table_list();
3715
3716 while (tables)
3717 {
3718 /*
3719 This is a fast check to filter out statements that do
3720 not change data, or tables on the right side, in case of
3721 INSERT .. SELECT, CREATE TABLE .. SELECT and so on.
3722 Here we also filter out OPTIMIZE statement and non-updateable
3723 views, for which lock_type is TL_UNLOCK or TL_READ after
3724 parsing.
3725 */
3726 if (static_cast<int>(tables->lock_type) >=
3727 static_cast<int>(TL_WRITE_ALLOW_WRITE))
3728 tables->trg_event_map= new_trg_event_map;
3729 tables= tables->next_local;
3730 }
3731 DBUG_VOID_RETURN;
3732 }
3733
3734
3735 /*
3736 Unlink the first table from the global table list and the first table from
3737 outer select (lex->select_lex) local list
3738
3739 SYNOPSIS
3740 unlink_first_table()
3741 link_to_local Set to 1 if caller should link this table to local list
3742
3743 NOTES
3744 We assume that first tables in both lists is the same table or the local
3745 list is empty.
3746
3747 RETURN
3748 0 If 'query_tables' == 0
3749 unlinked table
3750 In this case link_to_local is set.
3751
3752 */
unlink_first_table(bool * link_to_local)3753 TABLE_LIST *LEX::unlink_first_table(bool *link_to_local)
3754 {
3755 TABLE_LIST *first;
3756 if ((first= query_tables))
3757 {
3758 /*
3759 Exclude from global table list
3760 */
3761 if ((query_tables= query_tables->next_global))
3762 query_tables->prev_global= &query_tables;
3763 else
3764 query_tables_last= &query_tables;
3765 first->next_global= 0;
3766
3767 /*
3768 and from local list if it is not empty
3769 */
3770 if ((*link_to_local= MY_TEST(first_select_lex()->table_list.first)))
3771 {
3772 first_select_lex()->context.table_list=
3773 first_select_lex()->context.first_name_resolution_table=
3774 first->next_local;
3775 first_select_lex()->table_list.first= first->next_local;
3776 first_select_lex()->table_list.elements--; //safety
3777 first->next_local= 0;
3778 /*
3779 Ensure that the global list has the same first table as the local
3780 list.
3781 */
3782 first_lists_tables_same();
3783 }
3784 }
3785 return first;
3786 }
3787
3788
3789 /*
3790 Bring first local table of first most outer select to first place in global
3791 table list
3792
3793 SYNOPSYS
3794 LEX::first_lists_tables_same()
3795
3796 NOTES
3797 In many cases (for example, usual INSERT/DELETE/...) the first table of
3798 main SELECT_LEX have special meaning => check that it is the first table
3799 in global list and re-link to be first in the global list if it is
3800 necessary. We need such re-linking only for queries with sub-queries in
3801 the select list, as only in this case tables of sub-queries will go to
3802 the global list first.
3803 */
3804
first_lists_tables_same()3805 void LEX::first_lists_tables_same()
3806 {
3807 TABLE_LIST *first_table= first_select_lex()->table_list.first;
3808 if (query_tables != first_table && first_table != 0)
3809 {
3810 TABLE_LIST *next;
3811 if (query_tables_last == &first_table->next_global)
3812 query_tables_last= first_table->prev_global;
3813
3814 if (query_tables_own_last == &first_table->next_global)
3815 query_tables_own_last= first_table->prev_global;
3816
3817 if ((next= *first_table->prev_global= first_table->next_global))
3818 next->prev_global= first_table->prev_global;
3819 /* include in new place */
3820 first_table->next_global= query_tables;
3821 /*
3822 We are sure that query_tables is not 0, because first_table was not
3823 first table in the global list => we can use
3824 query_tables->prev_global without check of query_tables
3825 */
3826 query_tables->prev_global= &first_table->next_global;
3827 first_table->prev_global= &query_tables;
3828 query_tables= first_table;
3829 }
3830 }
3831
fix_first_select_number()3832 void LEX::fix_first_select_number()
3833 {
3834 SELECT_LEX *first= first_select_lex();
3835 if (first && first->select_number != 1)
3836 {
3837 uint num= first->select_number;
3838 for (SELECT_LEX *sel= all_selects_list;
3839 sel;
3840 sel= sel->next_select_in_list())
3841 {
3842 if (sel->select_number < num)
3843 sel->select_number++;
3844 }
3845 first->select_number= 1;
3846 }
3847 }
3848
3849
3850 /*
3851 Link table back that was unlinked with unlink_first_table()
3852
3853 SYNOPSIS
3854 link_first_table_back()
3855 link_to_local do we need link this table to local
3856
3857 RETURN
3858 global list
3859 */
3860
link_first_table_back(TABLE_LIST * first,bool link_to_local)3861 void LEX::link_first_table_back(TABLE_LIST *first,
3862 bool link_to_local)
3863 {
3864 if (first)
3865 {
3866 if ((first->next_global= query_tables))
3867 query_tables->prev_global= &first->next_global;
3868 else
3869 query_tables_last= &first->next_global;
3870 query_tables= first;
3871
3872 if (link_to_local)
3873 {
3874 first->next_local= first_select_lex()->table_list.first;
3875 first_select_lex()->context.table_list= first;
3876 first_select_lex()->table_list.first= first;
3877 first_select_lex()->table_list.elements++; //safety
3878 }
3879 }
3880 }
3881
3882
3883
3884 /*
3885 cleanup lex for case when we open table by table for processing
3886
3887 SYNOPSIS
3888 LEX::cleanup_after_one_table_open()
3889
3890 NOTE
3891 This method is mostly responsible for cleaning up of selects lists and
3892 derived tables state. To rollback changes in Query_tables_list one has
3893 to call Query_tables_list::reset_query_tables_list(FALSE).
3894 */
3895
cleanup_after_one_table_open()3896 void LEX::cleanup_after_one_table_open()
3897 {
3898 /*
3899 thd->lex->derived_tables & additional units may be set if we open
3900 a view. It is necessary to clear thd->lex->derived_tables flag
3901 to prevent processing of derived tables during next open_and_lock_tables
3902 if next table is a real table and cleanup & remove underlying units
3903 NOTE: all units will be connected to thd->lex->select_lex, because we
3904 have not UNION on most upper level.
3905 */
3906 if (all_selects_list != first_select_lex())
3907 {
3908 derived_tables= 0;
3909 first_select_lex()->exclude_from_table_unique_test= false;
3910 /* cleunup underlying units (units of VIEW) */
3911 for (SELECT_LEX_UNIT *un= first_select_lex()->first_inner_unit();
3912 un;
3913 un= un->next_unit())
3914 un->cleanup();
3915 /* reduce all selects list to default state */
3916 all_selects_list= first_select_lex();
3917 /* remove underlying units (units of VIEW) subtree */
3918 first_select_lex()->cut_subtree();
3919 }
3920 }
3921
3922
3923 /*
3924 Save current state of Query_tables_list for this LEX, and prepare it
3925 for processing of new statemnt.
3926
3927 SYNOPSIS
3928 reset_n_backup_query_tables_list()
3929 backup Pointer to Query_tables_list instance to be used for backup
3930 */
3931
reset_n_backup_query_tables_list(Query_tables_list * backup)3932 void LEX::reset_n_backup_query_tables_list(Query_tables_list *backup)
3933 {
3934 backup->set_query_tables_list(this);
3935 /*
3936 We have to perform full initialization here since otherwise we
3937 will damage backed up state.
3938 */
3939 this->reset_query_tables_list(TRUE);
3940 }
3941
3942
3943 /*
3944 Restore state of Query_tables_list for this LEX from backup.
3945
3946 SYNOPSIS
3947 restore_backup_query_tables_list()
3948 backup Pointer to Query_tables_list instance used for backup
3949 */
3950
restore_backup_query_tables_list(Query_tables_list * backup)3951 void LEX::restore_backup_query_tables_list(Query_tables_list *backup)
3952 {
3953 this->destroy_query_tables_list();
3954 this->set_query_tables_list(backup);
3955 }
3956
3957
3958 /*
3959 Checks for usage of routines and/or tables in a parsed statement
3960
3961 SYNOPSIS
3962 LEX:table_or_sp_used()
3963
3964 RETURN
3965 FALSE No routines and tables used
3966 TRUE Either or both routines and tables are used.
3967 */
3968
table_or_sp_used()3969 bool LEX::table_or_sp_used()
3970 {
3971 DBUG_ENTER("table_or_sp_used");
3972
3973 if (sroutines.records || query_tables)
3974 DBUG_RETURN(TRUE);
3975
3976 DBUG_RETURN(FALSE);
3977 }
3978
3979
3980 /*
3981 Do end-of-prepare fixup for list of tables and their merge-VIEWed tables
3982
3983 SYNOPSIS
3984 fix_prepare_info_in_table_list()
3985 thd Thread handle
3986 tbl List of tables to process
3987
3988 DESCRIPTION
3989 Perform end-end-of prepare fixup for list of tables, if any of the tables
3990 is a merge-algorithm VIEW, recursively fix up its underlying tables as
3991 well.
3992
3993 */
3994
fix_prepare_info_in_table_list(THD * thd,TABLE_LIST * tbl)3995 static void fix_prepare_info_in_table_list(THD *thd, TABLE_LIST *tbl)
3996 {
3997 for (; tbl; tbl= tbl->next_local)
3998 {
3999 if (tbl->on_expr && !tbl->prep_on_expr)
4000 {
4001 thd->check_and_register_item_tree(&tbl->prep_on_expr, &tbl->on_expr);
4002 tbl->on_expr= tbl->on_expr->copy_andor_structure(thd);
4003 }
4004 if (tbl->is_view_or_derived() && tbl->is_merged_derived())
4005 {
4006 SELECT_LEX *sel= tbl->get_single_select();
4007 fix_prepare_info_in_table_list(thd, sel->get_table_list());
4008 }
4009 }
4010 }
4011
4012
4013 /*
4014 Save WHERE/HAVING/ON clauses and replace them with disposable copies
4015
4016 SYNOPSIS
4017 st_select_lex::fix_prepare_information
4018 thd thread handler
4019 conds in/out pointer to WHERE condition to be met at execution
4020 having_conds in/out pointer to HAVING condition to be met at execution
4021
4022 DESCRIPTION
4023 The passed WHERE and HAVING are to be saved for the future executions.
4024 This function saves it, and returns a copy which can be thrashed during
4025 this execution of the statement. By saving/thrashing here we mean only
4026 We also save the chain of ORDER::next in group_list, in case
4027 the list is modified by remove_const().
4028 AND/OR trees.
4029 The function also calls fix_prepare_info_in_table_list that saves all
4030 ON expressions.
4031 */
4032
fix_prepare_information(THD * thd,Item ** conds,Item ** having_conds)4033 void st_select_lex::fix_prepare_information(THD *thd, Item **conds,
4034 Item **having_conds)
4035 {
4036 DBUG_ENTER("st_select_lex::fix_prepare_information");
4037 if (!thd->stmt_arena->is_conventional() &&
4038 !(changed_elements & TOUCHED_SEL_COND))
4039 {
4040 Query_arena_stmt on_stmt_arena(thd);
4041 changed_elements|= TOUCHED_SEL_COND;
4042 if (group_list.first)
4043 {
4044 if (!group_list_ptrs)
4045 {
4046 void *mem= thd->stmt_arena->alloc(sizeof(Group_list_ptrs));
4047 group_list_ptrs= new (mem) Group_list_ptrs(thd->stmt_arena->mem_root);
4048 }
4049 group_list_ptrs->reserve(group_list.elements);
4050 for (ORDER *order= group_list.first; order; order= order->next)
4051 {
4052 group_list_ptrs->push_back(order);
4053 }
4054 }
4055 if (*conds)
4056 {
4057 thd->check_and_register_item_tree(&prep_where, conds);
4058 *conds= where= prep_where->copy_andor_structure(thd);
4059 }
4060 if (*having_conds)
4061 {
4062 thd->check_and_register_item_tree(&prep_having, having_conds);
4063 *having_conds= having= prep_having->copy_andor_structure(thd);
4064 }
4065 fix_prepare_info_in_table_list(thd, table_list.first);
4066 }
4067 DBUG_VOID_RETURN;
4068 }
4069
4070
4071 /*
4072 There are st_select_lex::add_table_to_list &
4073 st_select_lex::set_lock_for_tables are in sql_parse.cc
4074
4075 st_select_lex::print is in sql_select.cc
4076
4077 st_select_lex_unit::prepare, st_select_lex_unit::exec,
4078 st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
4079 st_select_lex_unit::change_result
4080 are in sql_union.cc
4081 */
4082
4083 /*
4084 Sets the kind of hints to be added by the calls to add_index_hint().
4085
4086 SYNOPSIS
4087 set_index_hint_type()
4088 type_arg The kind of hints to be added from now on.
4089 clause The clause to use for hints to be added from now on.
4090
4091 DESCRIPTION
4092 Used in filling up the tagged hints list.
4093 This list is filled by first setting the kind of the hint as a
4094 context variable and then adding hints of the current kind.
4095 Then the context variable index_hint_type can be reset to the
4096 next hint type.
4097 */
set_index_hint_type(enum index_hint_type type_arg,index_clause_map clause)4098 void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
4099 index_clause_map clause)
4100 {
4101 current_index_hint_type= type_arg;
4102 current_index_hint_clause= clause;
4103 }
4104
4105
4106 /*
4107 Makes an array to store index usage hints (ADD/FORCE/IGNORE INDEX).
4108
4109 SYNOPSIS
4110 alloc_index_hints()
4111 thd current thread.
4112 */
4113
alloc_index_hints(THD * thd)4114 void st_select_lex::alloc_index_hints (THD *thd)
4115 {
4116 index_hints= new (thd->mem_root) List<Index_hint>();
4117 }
4118
4119
4120
4121 /*
4122 adds an element to the array storing index usage hints
4123 (ADD/FORCE/IGNORE INDEX).
4124
4125 SYNOPSIS
4126 add_index_hint()
4127 thd current thread.
4128 str name of the index.
4129 length number of characters in str.
4130
4131 RETURN VALUE
4132 0 on success, non-zero otherwise
4133 */
add_index_hint(THD * thd,const char * str,size_t length)4134 bool st_select_lex::add_index_hint (THD *thd, const char *str, size_t length)
4135 {
4136 return index_hints->push_front(new (thd->mem_root)
4137 Index_hint(current_index_hint_type,
4138 current_index_hint_clause,
4139 str, length), thd->mem_root);
4140 }
4141
4142
4143 /**
4144 Optimize all subqueries that have not been flattened into semi-joins.
4145
4146 @details
4147 This functionality is a method of SELECT_LEX instead of JOIN because
4148 SQL statements as DELETE/UPDATE do not have a corresponding JOIN object.
4149
4150 @see JOIN::optimize_unflattened_subqueries
4151
4152 @param const_only Restrict subquery optimization to constant subqueries
4153
4154 @return Operation status
4155 @retval FALSE success.
4156 @retval TRUE error occurred.
4157 */
4158
optimize_unflattened_subqueries(bool const_only)4159 bool st_select_lex::optimize_unflattened_subqueries(bool const_only)
4160 {
4161 SELECT_LEX_UNIT *next_unit= NULL;
4162 for (SELECT_LEX_UNIT *un= first_inner_unit();
4163 un;
4164 un= next_unit ? next_unit : un->next_unit())
4165 {
4166 Item_subselect *subquery_predicate= un->item;
4167 next_unit= NULL;
4168
4169 if (subquery_predicate)
4170 {
4171 if (!subquery_predicate->fixed)
4172 {
4173 /*
4174 This subquery was excluded as part of some expression so it is
4175 invisible from all prepared expression.
4176 */
4177 next_unit= un->next_unit();
4178 un->exclude_level();
4179 if (next_unit)
4180 continue;
4181 break;
4182 }
4183 if (subquery_predicate->substype() == Item_subselect::IN_SUBS)
4184 {
4185 Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;
4186 if (in_subs->is_jtbm_merged)
4187 continue;
4188 }
4189
4190 if (const_only && !subquery_predicate->const_item())
4191 {
4192 /* Skip non-constant subqueries if the caller asked so. */
4193 continue;
4194 }
4195
4196 bool empty_union_result= true;
4197 bool is_correlated_unit= false;
4198 bool first= true;
4199 bool union_plan_saved= false;
4200 /*
4201 If the subquery is a UNION, optimize all the subqueries in the UNION. If
4202 there is no UNION, then the loop will execute once for the subquery.
4203 */
4204 for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
4205 {
4206 JOIN *inner_join= sl->join;
4207 if (first)
4208 first= false;
4209 else
4210 {
4211 if (!union_plan_saved)
4212 {
4213 union_plan_saved= true;
4214 if (un->save_union_explain(un->thd->lex->explain))
4215 return true; /* Failure */
4216 }
4217 }
4218 if (!inner_join)
4219 continue;
4220 SELECT_LEX *save_select= un->thd->lex->current_select;
4221 ulonglong save_options;
4222 int res;
4223 /* We need only 1 row to determine existence */
4224 un->set_limit(un->global_parameters());
4225 un->thd->lex->current_select= sl;
4226 save_options= inner_join->select_options;
4227 if (options & SELECT_DESCRIBE)
4228 {
4229 /* Optimize the subquery in the context of EXPLAIN. */
4230 sl->set_explain_type(FALSE);
4231 sl->options|= SELECT_DESCRIBE;
4232 inner_join->select_options|= SELECT_DESCRIBE;
4233 }
4234 if ((res= inner_join->optimize()))
4235 return TRUE;
4236 if (!inner_join->cleaned)
4237 sl->update_used_tables();
4238 sl->update_correlated_cache();
4239 is_correlated_unit|= sl->is_correlated;
4240 inner_join->select_options= save_options;
4241 un->thd->lex->current_select= save_select;
4242
4243 Explain_query *eq;
4244 if ((eq= inner_join->thd->lex->explain))
4245 {
4246 Explain_select *expl_sel;
4247 if ((expl_sel= eq->get_select(inner_join->select_lex->select_number)))
4248 {
4249 sl->set_explain_type(TRUE);
4250 expl_sel->select_type= sl->type;
4251 }
4252 }
4253
4254 if (empty_union_result)
4255 {
4256 /*
4257 If at least one subquery in a union is non-empty, the UNION result
4258 is non-empty. If there is no UNION, the only subquery is non-empy.
4259 */
4260 empty_union_result= inner_join->empty_result();
4261 }
4262 if (res)
4263 return TRUE;
4264 }
4265 if (empty_union_result)
4266 subquery_predicate->no_rows_in_result();
4267
4268 if (is_correlated_unit)
4269 {
4270 /*
4271 Some parts of UNION are not correlated. This means we will need to
4272 re-execute the whole UNION every time. Mark all parts of the UNION
4273 as correlated so that they are prepared to be executed multiple
4274 times (if we don't do that, some part of the UNION may free its
4275 execution data at the end of first execution and crash on the second
4276 execution)
4277 */
4278 for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
4279 sl->uncacheable |= UNCACHEABLE_DEPENDENT;
4280 }
4281 else
4282 un->uncacheable&= ~UNCACHEABLE_DEPENDENT;
4283 subquery_predicate->is_correlated= is_correlated_unit;
4284 }
4285 }
4286 return FALSE;
4287 }
4288
4289
4290
4291 /**
4292 @brief Process all derived tables/views of the SELECT.
4293
4294 @param lex LEX of this thread
4295 @param phase phases to run derived tables/views through
4296
4297 @details
4298 This function runs specified 'phases' on all tables from the
4299 table_list of this select.
4300
4301 @return FALSE ok.
4302 @return TRUE an error occur.
4303 */
4304
handle_derived(LEX * lex,uint phases)4305 bool st_select_lex::handle_derived(LEX *lex, uint phases)
4306 {
4307 return lex->handle_list_of_derived(table_list.first, phases);
4308 }
4309
4310
4311 /**
4312 @brief
4313 Returns first unoccupied table map and table number
4314
4315 @param map [out] return found map
4316 @param tablenr [out] return found tablenr
4317
4318 @details
4319 Returns first unoccupied table map and table number in this select.
4320 Map and table are returned in *'map' and *'tablenr' accordingly.
4321
4322 @retrun TRUE no free table map/table number
4323 @return FALSE found free table map/table number
4324 */
4325
get_free_table_map(table_map * map,uint * tablenr)4326 bool st_select_lex::get_free_table_map(table_map *map, uint *tablenr)
4327 {
4328 *map= 0;
4329 *tablenr= 0;
4330 TABLE_LIST *tl;
4331 List_iterator<TABLE_LIST> ti(leaf_tables);
4332 while ((tl= ti++))
4333 {
4334 if (tl->table->map > *map)
4335 *map= tl->table->map;
4336 if (tl->table->tablenr > *tablenr)
4337 *tablenr= tl->table->tablenr;
4338 }
4339 (*map)<<= 1;
4340 (*tablenr)++;
4341 if (*tablenr >= MAX_TABLES)
4342 return TRUE;
4343 return FALSE;
4344 }
4345
4346
4347 /**
4348 @brief
4349 Append given table to the leaf_tables list.
4350
4351 @param link Offset to which list in table structure to use
4352 @param table Table to append
4353
4354 @details
4355 Append given 'table' to the leaf_tables list using the 'link' offset.
4356 If the 'table' is linked with other tables through next_leaf/next_local
4357 chains then whole list will be appended.
4358 */
4359
append_table_to_list(TABLE_LIST * TABLE_LIST::* link,TABLE_LIST * table)4360 void st_select_lex::append_table_to_list(TABLE_LIST *TABLE_LIST::*link,
4361 TABLE_LIST *table)
4362 {
4363 TABLE_LIST *tl;
4364 for (tl= leaf_tables.head(); tl->*link; tl= tl->*link) ;
4365 tl->*link= table;
4366 }
4367
4368
4369 /*
4370 @brief
4371 Replace given table from the leaf_tables list for a list of tables
4372
4373 @param table Table to replace
4374 @param list List to substititute the table for
4375
4376 @details
4377 Replace 'table' from the leaf_tables list for a list of tables 'tbl_list'.
4378 */
4379
replace_leaf_table(TABLE_LIST * table,List<TABLE_LIST> & tbl_list)4380 void st_select_lex::replace_leaf_table(TABLE_LIST *table, List<TABLE_LIST> &tbl_list)
4381 {
4382 TABLE_LIST *tl;
4383 List_iterator<TABLE_LIST> ti(leaf_tables);
4384 while ((tl= ti++))
4385 {
4386 if (tl == table)
4387 {
4388 ti.replace(tbl_list);
4389 break;
4390 }
4391 }
4392 }
4393
4394
4395 /**
4396 @brief
4397 Assigns new table maps to tables in the leaf_tables list
4398
4399 @param derived Derived table to take initial table map from
4400 @param map table map to begin with
4401 @param tablenr table number to begin with
4402 @param parent_lex new parent select_lex
4403
4404 @details
4405 Assign new table maps/table numbers to all tables in the leaf_tables list.
4406 'map'/'tablenr' are used for the first table and shifted to left/
4407 increased for each consequent table in the leaf_tables list.
4408 If the 'derived' table is given then it's table map/number is used for the
4409 first table in the list and 'map'/'tablenr' are used for the second and
4410 all consequent tables.
4411 The 'parent_lex' is set as the new parent select_lex for all tables in the
4412 list.
4413 */
4414
remap_tables(TABLE_LIST * derived,table_map map,uint tablenr,SELECT_LEX * parent_lex)4415 void st_select_lex::remap_tables(TABLE_LIST *derived, table_map map,
4416 uint tablenr, SELECT_LEX *parent_lex)
4417 {
4418 bool first_table= TRUE;
4419 TABLE_LIST *tl;
4420 table_map first_map;
4421 uint first_tablenr;
4422
4423 if (derived && derived->table)
4424 {
4425 first_map= derived->table->map;
4426 first_tablenr= derived->table->tablenr;
4427 }
4428 else
4429 {
4430 first_map= map;
4431 map<<= 1;
4432 first_tablenr= tablenr++;
4433 }
4434 /*
4435 Assign table bit/table number.
4436 To the first table of the subselect the table bit/tablenr of the
4437 derived table is assigned. The rest of tables are getting bits
4438 sequentially, starting from the provided table map/tablenr.
4439 */
4440 List_iterator<TABLE_LIST> ti(leaf_tables);
4441 while ((tl= ti++))
4442 {
4443 if (first_table)
4444 {
4445 first_table= FALSE;
4446 tl->table->set_table_map(first_map, first_tablenr);
4447 }
4448 else
4449 {
4450 tl->table->set_table_map(map, tablenr);
4451 tablenr++;
4452 map<<= 1;
4453 }
4454 SELECT_LEX *old_sl= tl->select_lex;
4455 tl->select_lex= parent_lex;
4456 for(TABLE_LIST *emb= tl->embedding;
4457 emb && emb->select_lex == old_sl;
4458 emb= emb->embedding)
4459 emb->select_lex= parent_lex;
4460 }
4461 }
4462
4463 /**
4464 @brief
4465 Merge a subquery into this select.
4466
4467 @param derived derived table of the subquery to be merged
4468 @param subq_select select_lex of the subquery
4469 @param map table map for assigning to merged tables from subquery
4470 @param table_no table number for assigning to merged tables from subquery
4471
4472 @details
4473 This function merges a subquery into its parent select. In short the
4474 merge operation appends the subquery FROM table list to the parent's
4475 FROM table list. In more details:
4476 .) the top_join_list of the subquery is wrapped into a join_nest
4477 and attached to 'derived'
4478 .) subquery's leaf_tables list is merged with the leaf_tables
4479 list of this select_lex
4480 .) the table maps and table numbers of the tables merged from
4481 the subquery are adjusted to reflect their new binding to
4482 this select
4483
4484 @return TRUE an error occur
4485 @return FALSE ok
4486 */
4487
merge_subquery(THD * thd,TABLE_LIST * derived,SELECT_LEX * subq_select,uint table_no,table_map map)4488 bool SELECT_LEX::merge_subquery(THD *thd, TABLE_LIST *derived,
4489 SELECT_LEX *subq_select,
4490 uint table_no, table_map map)
4491 {
4492 derived->wrap_into_nested_join(subq_select->top_join_list);
4493
4494 ftfunc_list->append(subq_select->ftfunc_list);
4495 if (join ||
4496 thd->lex->sql_command == SQLCOM_UPDATE_MULTI ||
4497 thd->lex->sql_command == SQLCOM_DELETE_MULTI)
4498 {
4499 List_iterator_fast<Item_in_subselect> li(subq_select->sj_subselects);
4500 Item_in_subselect *in_subq;
4501 while ((in_subq= li++))
4502 {
4503 sj_subselects.push_back(in_subq, thd->mem_root);
4504 if (in_subq->emb_on_expr_nest == NO_JOIN_NEST)
4505 in_subq->emb_on_expr_nest= derived;
4506 }
4507
4508 uint cnt= sizeof(expr_cache_may_be_used)/sizeof(bool);
4509 for (uint i= 0; i < cnt; i++)
4510 {
4511 if (subq_select->expr_cache_may_be_used[i])
4512 expr_cache_may_be_used[i]= true;
4513 }
4514
4515 List_iterator_fast<Item_func_in> it(subq_select->in_funcs);
4516 Item_func_in *in_func;
4517 while ((in_func= it++))
4518 {
4519 in_funcs.push_back(in_func, thd->mem_root);
4520 if (in_func->emb_on_expr_nest == NO_JOIN_NEST)
4521 in_func->emb_on_expr_nest= derived;
4522 }
4523 }
4524
4525 /* Walk through child's tables and adjust table map, tablenr,
4526 * parent_lex */
4527 subq_select->remap_tables(derived, map, table_no, this);
4528 subq_select->merged_into= this;
4529
4530 replace_leaf_table(derived, subq_select->leaf_tables);
4531
4532 return FALSE;
4533 }
4534
4535
4536 /**
4537 @brief
4538 Mark tables from the leaf_tables list as belong to a derived table.
4539
4540 @param derived tables will be marked as belonging to this derived
4541
4542 @details
4543 Run through the leaf_list and mark all tables as belonging to the 'derived'.
4544 */
4545
mark_as_belong_to_derived(TABLE_LIST * derived)4546 void SELECT_LEX::mark_as_belong_to_derived(TABLE_LIST *derived)
4547 {
4548 /* Mark tables as belonging to this DT */
4549 TABLE_LIST *tl;
4550 List_iterator<TABLE_LIST> ti(leaf_tables);
4551 while ((tl= ti++))
4552 tl->belong_to_derived= derived;
4553 }
4554
4555
4556 /**
4557 @brief
4558 Update used_tables cache for this select
4559
4560 @details
4561 This function updates used_tables cache of ON expressions of all tables
4562 in the leaf_tables list and of the conds expression (if any).
4563 */
4564
update_used_tables()4565 void SELECT_LEX::update_used_tables()
4566 {
4567 TABLE_LIST *tl;
4568 List_iterator<TABLE_LIST> ti(leaf_tables);
4569
4570 while ((tl= ti++))
4571 {
4572 if (tl->table && !tl->is_view_or_derived())
4573 {
4574 TABLE_LIST *embedding= tl->embedding;
4575 for (embedding= tl->embedding; embedding; embedding=embedding->embedding)
4576 {
4577 if (embedding->is_view_or_derived())
4578 {
4579 DBUG_ASSERT(embedding->is_merged_derived());
4580 TABLE *tab= tl->table;
4581 tab->covering_keys= tab->s->keys_for_keyread;
4582 tab->covering_keys.intersect(tab->keys_in_use_for_query);
4583 /*
4584 View/derived was merged. Need to recalculate read_set
4585 bitmaps here. For example:
4586 CREATE VIEW v1 AS SELECT f1,f2,f3 FROM t1;
4587 SELECT f1 FROM v1;
4588 Initially, the view definition will put all f1,f2,f3 in the
4589 read_set for t1. But after the view is merged, only f1 should
4590 be in the read_set.
4591 */
4592 bitmap_clear_all(tab->read_set);
4593 break;
4594 }
4595 }
4596 }
4597 }
4598
4599 ti.rewind();
4600 while ((tl= ti++))
4601 {
4602 TABLE_LIST *embedding= tl;
4603 do
4604 {
4605 bool maybe_null;
4606 if ((maybe_null= MY_TEST(embedding->outer_join)))
4607 {
4608 tl->table->maybe_null= maybe_null;
4609 break;
4610 }
4611 }
4612 while ((embedding= embedding->embedding));
4613 if (tl->on_expr)
4614 {
4615 tl->on_expr->update_used_tables();
4616 tl->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
4617 }
4618 /*
4619 - There is no need to check sj_on_expr, because merged semi-joins inject
4620 sj_on_expr into the parent's WHERE clase.
4621 - For non-merged semi-joins (aka JTBMs), we need to check their
4622 left_expr. There is no need to check the rest of the subselect, we know
4623 it is uncorrelated and so cannot refer to any tables in this select.
4624 */
4625 if (tl->jtbm_subselect)
4626 {
4627 Item *left_expr= tl->jtbm_subselect->left_expr;
4628 left_expr->walk(&Item::update_table_bitmaps_processor, FALSE, NULL);
4629 }
4630
4631 embedding= tl->embedding;
4632 while (embedding)
4633 {
4634 if (embedding->on_expr &&
4635 embedding->nested_join->join_list.head() == tl)
4636 {
4637 embedding->on_expr->update_used_tables();
4638 embedding->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
4639 }
4640 tl= embedding;
4641 embedding= tl->embedding;
4642 }
4643 }
4644
4645 if (join->conds)
4646 {
4647 join->conds->update_used_tables();
4648 join->conds->walk(&Item::eval_not_null_tables, 0, NULL);
4649 }
4650 if (join->having)
4651 {
4652 join->having->update_used_tables();
4653 }
4654
4655 Item *item;
4656 List_iterator_fast<Item> it(join->all_fields);
4657 select_list_tables= 0;
4658 while ((item= it++))
4659 {
4660 item->update_used_tables();
4661 select_list_tables|= item->used_tables();
4662 }
4663 Item_outer_ref *ref;
4664 List_iterator_fast<Item_outer_ref> ref_it(inner_refs_list);
4665 while ((ref= ref_it++))
4666 {
4667 item= ref->outer_ref;
4668 item->update_used_tables();
4669 }
4670 for (ORDER *order= group_list.first; order; order= order->next)
4671 (*order->item)->update_used_tables();
4672 if (!master_unit()->is_unit_op() ||
4673 master_unit()->global_parameters() != this)
4674 {
4675 for (ORDER *order= order_list.first; order; order= order->next)
4676 (*order->item)->update_used_tables();
4677 }
4678 join->result->update_used_tables();
4679 }
4680
4681
4682 /**
4683 @brief
4684 Update is_correlated cache for this select
4685
4686 @details
4687 */
4688
update_correlated_cache()4689 void st_select_lex::update_correlated_cache()
4690 {
4691 TABLE_LIST *tl;
4692 List_iterator<TABLE_LIST> ti(leaf_tables);
4693
4694 is_correlated= false;
4695
4696 while ((tl= ti++))
4697 {
4698 // is_correlated|= tl->is_with_table_recursive_reference();
4699 if (tl->on_expr)
4700 is_correlated|= MY_TEST(tl->on_expr->used_tables() & OUTER_REF_TABLE_BIT);
4701 for (TABLE_LIST *embedding= tl->embedding ; embedding ;
4702 embedding= embedding->embedding)
4703 {
4704 if (embedding->on_expr)
4705 is_correlated|= MY_TEST(embedding->on_expr->used_tables() &
4706 OUTER_REF_TABLE_BIT);
4707 }
4708 }
4709
4710 if (join->conds)
4711 is_correlated|= MY_TEST(join->conds->used_tables() & OUTER_REF_TABLE_BIT);
4712
4713 is_correlated|= join->having_is_correlated;
4714
4715 if (join->having)
4716 is_correlated|= MY_TEST(join->having->used_tables() & OUTER_REF_TABLE_BIT);
4717
4718 if (join->tmp_having)
4719 is_correlated|= MY_TEST(join->tmp_having->used_tables() &
4720 OUTER_REF_TABLE_BIT);
4721
4722 Item *item;
4723 List_iterator_fast<Item> it(join->fields_list);
4724 while ((item= it++))
4725 is_correlated|= MY_TEST(item->used_tables() & OUTER_REF_TABLE_BIT);
4726
4727 for (ORDER *order= group_list.first; order; order= order->next)
4728 is_correlated|= MY_TEST((*order->item)->used_tables() &
4729 OUTER_REF_TABLE_BIT);
4730
4731 if (!master_unit()->is_unit_op())
4732 {
4733 for (ORDER *order= order_list.first; order; order= order->next)
4734 is_correlated|= MY_TEST((*order->item)->used_tables() &
4735 OUTER_REF_TABLE_BIT);
4736 }
4737
4738 if (!is_correlated)
4739 uncacheable&= ~UNCACHEABLE_DEPENDENT;
4740 }
4741
4742
4743 /**
4744 Set the EXPLAIN type for this subquery.
4745
4746 @param on_the_fly TRUE<=> We're running a SHOW EXPLAIN command, so we must
4747 not change any variables
4748 */
4749
set_explain_type(bool on_the_fly)4750 void st_select_lex::set_explain_type(bool on_the_fly)
4751 {
4752 bool is_primary= FALSE;
4753 if (next_select())
4754 is_primary= TRUE;
4755
4756 if (!is_primary && first_inner_unit())
4757 {
4758 /*
4759 If there is at least one materialized derived|view then it's a PRIMARY select.
4760 Otherwise, all derived tables/views were merged and this select is a SIMPLE one.
4761 */
4762 for (SELECT_LEX_UNIT *un= first_inner_unit(); un; un= un->next_unit())
4763 {
4764 if ((!un->derived || un->derived->is_materialized_derived()))
4765 {
4766 is_primary= TRUE;
4767 break;
4768 }
4769 }
4770 }
4771
4772 if (on_the_fly && !is_primary && have_merged_subqueries)
4773 is_primary= TRUE;
4774
4775 SELECT_LEX *first= master_unit()->first_select();
4776 /* drop UNCACHEABLE_EXPLAIN, because it is for internal usage only */
4777 uint8 is_uncacheable= (uncacheable & ~UNCACHEABLE_EXPLAIN);
4778
4779 bool using_materialization= FALSE;
4780 Item_subselect *parent_item;
4781 if ((parent_item= master_unit()->item) &&
4782 parent_item->substype() == Item_subselect::IN_SUBS)
4783 {
4784 Item_in_subselect *in_subs= (Item_in_subselect*)parent_item;
4785 /*
4786 Surprisingly, in_subs->is_set_strategy() can return FALSE here,
4787 even for the last invocation of this function for the select.
4788 */
4789 if (in_subs->test_strategy(SUBS_MATERIALIZATION))
4790 using_materialization= TRUE;
4791 }
4792
4793 if (master_unit()->thd->lex->first_select_lex() == this)
4794 {
4795 if (pushdown_select)
4796 type= pushed_select_text;
4797 else
4798 type= is_primary ? "PRIMARY" : "SIMPLE";
4799 }
4800 else
4801 {
4802 if (this == first)
4803 {
4804 /* If we're a direct child of a UNION, we're the first sibling there */
4805 if (linkage == DERIVED_TABLE_TYPE)
4806 {
4807 bool is_pushed_master_unit= master_unit()->derived &&
4808 master_unit()->derived->pushdown_derived;
4809 if (is_pushed_master_unit)
4810 type= pushed_derived_text;
4811 else if (is_uncacheable & UNCACHEABLE_DEPENDENT)
4812 type= "LATERAL DERIVED";
4813 else
4814 type= "DERIVED";
4815 }
4816 else if (using_materialization)
4817 type= "MATERIALIZED";
4818 else
4819 {
4820 if (is_uncacheable & UNCACHEABLE_DEPENDENT)
4821 type= "DEPENDENT SUBQUERY";
4822 else
4823 {
4824 type= is_uncacheable? "UNCACHEABLE SUBQUERY" :
4825 "SUBQUERY";
4826 }
4827 }
4828 }
4829 else
4830 {
4831 switch (linkage)
4832 {
4833 case INTERSECT_TYPE:
4834 type= "INTERSECT";
4835 break;
4836 case EXCEPT_TYPE:
4837 type= "EXCEPT";
4838 break;
4839 default:
4840 /* This a non-first sibling in UNION */
4841 if (is_uncacheable & UNCACHEABLE_DEPENDENT)
4842 type= "DEPENDENT UNION";
4843 else if (using_materialization)
4844 type= "MATERIALIZED UNION";
4845 else
4846 {
4847 type= is_uncacheable ? "UNCACHEABLE UNION": "UNION";
4848 if (this == master_unit()->fake_select_lex)
4849 type= unit_operation_text[master_unit()->common_op()];
4850 /*
4851 join below may be =NULL when this functions is called at an early
4852 stage. It will be later called again and we will set the correct
4853 value.
4854 */
4855 if (join)
4856 {
4857 bool uses_cte= false;
4858 for (JOIN_TAB *tab= first_linear_tab(join, WITHOUT_BUSH_ROOTS,
4859 WITH_CONST_TABLES);
4860 tab;
4861 tab= next_linear_tab(join, tab, WITHOUT_BUSH_ROOTS))
4862 {
4863 /*
4864 pos_in_table_list=NULL for e.g. post-join aggregation JOIN_TABs.
4865 */
4866 if (!(tab->table && tab->table->pos_in_table_list))
4867 continue;
4868 TABLE_LIST *tbl= tab->table->pos_in_table_list;
4869 if (tbl->with && tbl->with->is_recursive &&
4870 tbl->is_with_table_recursive_reference())
4871 {
4872 uses_cte= true;
4873 break;
4874 }
4875 }
4876 if (uses_cte)
4877 type= "RECURSIVE UNION";
4878 }
4879 }
4880 break;
4881 }
4882 }
4883 }
4884
4885 if (!on_the_fly)
4886 options|= SELECT_DESCRIBE;
4887 }
4888
4889
4890 /**
4891 @brief
4892 Increase estimated number of records for a derived table/view
4893
4894 @param records number of records to increase estimate by
4895
4896 @details
4897 This function increases estimated number of records by the 'records'
4898 for the derived table to which this select belongs to.
4899 */
4900
increase_derived_records(ha_rows records)4901 void SELECT_LEX::increase_derived_records(ha_rows records)
4902 {
4903 SELECT_LEX_UNIT *unit= master_unit();
4904 DBUG_ASSERT(unit->derived);
4905
4906 if (unit->with_element && unit->with_element->is_recursive)
4907 {
4908 st_select_lex *first_recursive= unit->with_element->first_recursive;
4909 st_select_lex *sl= unit->first_select();
4910 for ( ; sl != first_recursive; sl= sl->next_select())
4911 {
4912 if (sl == this)
4913 break;
4914 }
4915 if (sl == first_recursive)
4916 return;
4917 }
4918
4919 select_result *result= unit->result;
4920 switch (linkage)
4921 {
4922 case INTERSECT_TYPE:
4923 // result of intersect can't be more then one of components
4924 set_if_smaller(result->est_records, records);
4925 case EXCEPT_TYPE:
4926 // in worse case none of record will be removed
4927 break;
4928 default:
4929 // usual UNION
4930 if (HA_ROWS_MAX - records > result->est_records)
4931 result->est_records+= records;
4932 else
4933 result->est_records= HA_ROWS_MAX;
4934 break;
4935 }
4936 }
4937
4938
4939 /**
4940 @brief
4941 Mark select's derived table as a const one.
4942
4943 @param empty Whether select has an empty result set
4944
4945 @details
4946 Mark derived table/view of this select as a constant one (to
4947 materialize it at the optimization phase) unless this select belongs to a
4948 union. Estimated number of rows is incremented if this select has non empty
4949 result set.
4950 */
4951
mark_const_derived(bool empty)4952 void SELECT_LEX::mark_const_derived(bool empty)
4953 {
4954 TABLE_LIST *derived= master_unit()->derived;
4955 /* join == NULL in DELETE ... RETURNING */
4956 if (!(join && join->thd->lex->describe) && derived)
4957 {
4958 if (!empty)
4959 increase_derived_records(1);
4960 if (!master_unit()->is_unit_op() && !derived->is_merged_derived() &&
4961 !(join && join->with_two_phase_optimization))
4962 derived->fill_me= TRUE;
4963 }
4964 }
4965
4966
save_leaf_tables(THD * thd)4967 bool st_select_lex::save_leaf_tables(THD *thd)
4968 {
4969 Query_arena *arena, backup;
4970 arena= thd->activate_stmt_arena_if_needed(&backup);
4971
4972 List_iterator_fast<TABLE_LIST> li(leaf_tables);
4973 TABLE_LIST *table;
4974 while ((table= li++))
4975 {
4976 if (leaf_tables_exec.push_back(table, thd->mem_root))
4977 return 1;
4978 table->tablenr_exec= table->get_tablenr();
4979 table->map_exec= table->get_map();
4980 if (join && (join->select_options & SELECT_DESCRIBE))
4981 table->maybe_null_exec= 0;
4982 else
4983 table->maybe_null_exec= table->table? table->table->maybe_null: 0;
4984 }
4985 if (arena)
4986 thd->restore_active_arena(arena, &backup);
4987
4988 return 0;
4989 }
4990
4991
save_prep_leaf_tables()4992 bool LEX::save_prep_leaf_tables()
4993 {
4994 if (!thd->save_prep_leaf_list)
4995 return FALSE;
4996
4997 Query_arena *arena= thd->stmt_arena, backup;
4998 arena= thd->activate_stmt_arena_if_needed(&backup);
4999 //It is used for DETETE/UPDATE so top level has only one SELECT
5000 DBUG_ASSERT(first_select_lex()->next_select() == NULL);
5001 bool res= first_select_lex()->save_prep_leaf_tables(thd);
5002
5003 if (arena)
5004 thd->restore_active_arena(arena, &backup);
5005
5006 if (res)
5007 return TRUE;
5008
5009 thd->save_prep_leaf_list= FALSE;
5010 return FALSE;
5011 }
5012
5013
save_prep_leaf_tables(THD * thd)5014 bool st_select_lex::save_prep_leaf_tables(THD *thd)
5015 {
5016 if (prep_leaf_list_state == SAVED)
5017 return FALSE;
5018
5019 List_iterator_fast<TABLE_LIST> li(leaf_tables);
5020 TABLE_LIST *table;
5021
5022 /*
5023 Check that the SELECT_LEX was really prepared and so tables are setup.
5024
5025 It can be subquery in SET clause of UPDATE which was not prepared yet, so
5026 its tables are not yet setup and ready for storing.
5027 */
5028 if (prep_leaf_list_state != READY)
5029 return FALSE;
5030
5031 while ((table= li++))
5032 {
5033 if (leaf_tables_prep.push_back(table))
5034 return TRUE;
5035 }
5036 prep_leaf_list_state= SAVED;
5037 for (SELECT_LEX_UNIT *u= first_inner_unit(); u; u= u->next_unit())
5038 {
5039 for (SELECT_LEX *sl= u->first_select(); sl; sl= sl->next_select())
5040 {
5041 if (sl->save_prep_leaf_tables(thd))
5042 return TRUE;
5043 }
5044 }
5045
5046 return FALSE;
5047 }
5048
5049
5050 /**
5051 Set exclude_from_table_unique_test for selects of this select and all selects
5052 belonging to the underlying units of derived tables or views
5053 */
5054
set_unique_exclude()5055 void st_select_lex::set_unique_exclude()
5056 {
5057 exclude_from_table_unique_test= TRUE;
5058 for (SELECT_LEX_UNIT *unit= first_inner_unit();
5059 unit;
5060 unit= unit->next_unit())
5061 {
5062 if (unit->derived && unit->derived->is_view_or_derived())
5063 {
5064 for (SELECT_LEX *sl= unit->first_select(); sl; sl= sl->next_select())
5065 sl->set_unique_exclude();
5066 }
5067 }
5068 }
5069
5070
5071 /*
5072 Return true if this select_lex has been converted into a semi-join nest
5073 within 'ancestor'.
5074
5075 We need a loop to check this because there could be several nested
5076 subselects, like
5077
5078 SELECT ... FROM grand_parent
5079 WHERE expr1 IN (SELECT ... FROM parent
5080 WHERE expr2 IN ( SELECT ... FROM child)
5081
5082 which were converted into:
5083
5084 SELECT ...
5085 FROM grand_parent SEMI_JOIN (parent JOIN child)
5086 WHERE
5087 expr1 AND expr2
5088
5089 In this case, both parent and child selects were merged into the parent.
5090 */
5091
is_merged_child_of(st_select_lex * ancestor)5092 bool st_select_lex::is_merged_child_of(st_select_lex *ancestor)
5093 {
5094 bool all_merged= TRUE;
5095 for (SELECT_LEX *sl= this; sl && sl!=ancestor;
5096 sl=sl->outer_select())
5097 {
5098 Item *subs= sl->master_unit()->item;
5099 if (subs && subs->type() == Item::SUBSELECT_ITEM &&
5100 ((Item_subselect*)subs)->substype() == Item_subselect::IN_SUBS &&
5101 ((Item_in_subselect*)subs)->test_strategy(SUBS_SEMI_JOIN))
5102 {
5103 continue;
5104 }
5105
5106 if (sl->master_unit()->derived &&
5107 sl->master_unit()->derived->is_merged_derived())
5108 {
5109 continue;
5110 }
5111 all_merged= FALSE;
5112 break;
5113 }
5114 return all_merged;
5115 }
5116
5117 /*
5118 This is used by SHOW EXPLAIN. It assuses query plan has been already
5119 collected into QPF structures and we only need to print it out.
5120 */
5121
print_explain(select_result_sink * output,uint8 explain_flags,bool is_analyze,bool * printed_anything)5122 int LEX::print_explain(select_result_sink *output, uint8 explain_flags,
5123 bool is_analyze, bool *printed_anything)
5124 {
5125 int res;
5126 if (explain && explain->have_query_plan())
5127 {
5128 res= explain->print_explain(output, explain_flags, is_analyze);
5129 *printed_anything= true;
5130 }
5131 else
5132 {
5133 res= 0;
5134 *printed_anything= false;
5135 }
5136 return res;
5137 }
5138
5139
5140 /**
5141 Allocates and set arena for SET STATEMENT old values.
5142
5143 @param backup where to save backup of arena.
5144
5145 @retval 1 Error
5146 @retval 0 OK
5147 */
5148
set_arena_for_set_stmt(Query_arena * backup)5149 bool LEX::set_arena_for_set_stmt(Query_arena *backup)
5150 {
5151 DBUG_ENTER("LEX::set_arena_for_set_stmt");
5152 DBUG_ASSERT(arena_for_set_stmt== 0);
5153 if (!mem_root_for_set_stmt)
5154 {
5155 mem_root_for_set_stmt= new MEM_ROOT();
5156 if (unlikely(!(mem_root_for_set_stmt)))
5157 DBUG_RETURN(1);
5158 init_sql_alloc(mem_root_for_set_stmt, "set_stmt",
5159 ALLOC_ROOT_SET, ALLOC_ROOT_SET, MYF(MY_THREAD_SPECIFIC));
5160 }
5161 if (unlikely(!(arena_for_set_stmt= new(mem_root_for_set_stmt)
5162 Query_arena_memroot(mem_root_for_set_stmt,
5163 Query_arena::STMT_INITIALIZED))))
5164 DBUG_RETURN(1);
5165 DBUG_PRINT("info", ("mem_root: %p arena: %p",
5166 mem_root_for_set_stmt,
5167 arena_for_set_stmt));
5168 thd->set_n_backup_active_arena(arena_for_set_stmt, backup);
5169 DBUG_RETURN(0);
5170 }
5171
5172
reset_arena_for_set_stmt(Query_arena * backup)5173 void LEX::reset_arena_for_set_stmt(Query_arena *backup)
5174 {
5175 DBUG_ENTER("LEX::reset_arena_for_set_stmt");
5176 DBUG_ASSERT(arena_for_set_stmt);
5177 thd->restore_active_arena(arena_for_set_stmt, backup);
5178 DBUG_PRINT("info", ("mem_root: %p arena: %p",
5179 arena_for_set_stmt->mem_root,
5180 arena_for_set_stmt));
5181 DBUG_VOID_RETURN;
5182 }
5183
5184
free_arena_for_set_stmt()5185 void LEX::free_arena_for_set_stmt()
5186 {
5187 DBUG_ENTER("LEX::free_arena_for_set_stmt");
5188 if (!arena_for_set_stmt)
5189 return;
5190 DBUG_PRINT("info", ("mem_root: %p arena: %p",
5191 arena_for_set_stmt->mem_root,
5192 arena_for_set_stmt));
5193 arena_for_set_stmt->free_items();
5194 delete(arena_for_set_stmt);
5195 free_root(mem_root_for_set_stmt, MYF(MY_KEEP_PREALLOC));
5196 arena_for_set_stmt= 0;
5197 DBUG_VOID_RETURN;
5198 }
5199
restore_set_statement_var()5200 bool LEX::restore_set_statement_var()
5201 {
5202 bool err= false;
5203 DBUG_ENTER("LEX::restore_set_statement_var");
5204 if (!old_var_list.is_empty())
5205 {
5206 DBUG_PRINT("info", ("vars: %d", old_var_list.elements));
5207 err= sql_set_variables(thd, &old_var_list, false);
5208 old_var_list.empty();
5209 free_arena_for_set_stmt();
5210 }
5211 DBUG_ASSERT(!is_arena_for_set_stmt());
5212 DBUG_RETURN(err);
5213 }
5214
common_op()5215 unit_common_op st_select_lex_unit::common_op()
5216 {
5217 SELECT_LEX *first= first_select();
5218 bool first_op= TRUE;
5219 unit_common_op operation= OP_MIX; // if no op
5220 for (SELECT_LEX *sl= first; sl; sl= sl->next_select())
5221 {
5222 if (sl != first)
5223 {
5224 unit_common_op op;
5225 switch (sl->linkage)
5226 {
5227 case INTERSECT_TYPE:
5228 op= OP_INTERSECT;
5229 break;
5230 case EXCEPT_TYPE:
5231 op= OP_EXCEPT;
5232 break;
5233 default:
5234 op= OP_UNION;
5235 break;
5236 }
5237 if (first_op)
5238 {
5239 operation= op;
5240 first_op= FALSE;
5241 }
5242 else
5243 {
5244 if (operation != op)
5245 operation= OP_MIX;
5246 }
5247 }
5248 }
5249 return operation;
5250 }
5251 /*
5252 Save explain structures of a UNION. The only variable member is whether the
5253 union has "Using filesort".
5254
5255 There is also save_union_explain_part2() function, which is called before we read
5256 UNION's output.
5257
5258 The reason for it is examples like this:
5259
5260 SELECT col1 FROM t1 UNION SELECT col2 FROM t2 ORDER BY (select ... from t3 ...)
5261
5262 Here, the (select ... from t3 ...) subquery must be a child of UNION's
5263 st_select_lex. However, it is not connected as child until a very late
5264 stage in execution.
5265 */
5266
save_union_explain(Explain_query * output)5267 int st_select_lex_unit::save_union_explain(Explain_query *output)
5268 {
5269 SELECT_LEX *first= first_select();
5270
5271 if (output->get_union(first->select_number))
5272 return 0; /* Already added */
5273
5274 Explain_union *eu=
5275 new (output->mem_root) Explain_union(output->mem_root,
5276 thd->lex->analyze_stmt);
5277 if (unlikely(!eu))
5278 return 0;
5279
5280 if (with_element && with_element->is_recursive)
5281 eu->is_recursive_cte= true;
5282
5283 if (derived)
5284 eu->connection_type= Explain_node::EXPLAIN_NODE_DERIVED;
5285 /*
5286 Note: Non-merged semi-joins cannot be made out of UNIONs currently, so we
5287 dont ever set EXPLAIN_NODE_NON_MERGED_SJ.
5288 */
5289 for (SELECT_LEX *sl= first; sl; sl= sl->next_select())
5290 eu->add_select(sl->select_number);
5291
5292 eu->fake_select_type= unit_operation_text[eu->operation= common_op()];
5293 eu->using_filesort= MY_TEST(global_parameters()->order_list.first);
5294 eu->using_tmp= union_needs_tmp_table();
5295
5296 // Save the UNION node
5297 output->add_node(eu);
5298
5299 if (eu->get_select_id() == 1)
5300 output->query_plan_ready();
5301
5302 return 0;
5303 }
5304
5305
5306 /*
5307 @see st_select_lex_unit::save_union_explain
5308 */
5309
save_union_explain_part2(Explain_query * output)5310 int st_select_lex_unit::save_union_explain_part2(Explain_query *output)
5311 {
5312 Explain_union *eu= output->get_union(first_select()->select_number);
5313 if (fake_select_lex)
5314 {
5315 for (SELECT_LEX_UNIT *unit= fake_select_lex->first_inner_unit();
5316 unit; unit= unit->next_unit())
5317 {
5318 if (!(unit->item && unit->item->eliminated))
5319 {
5320 eu->add_child(unit->first_select()->select_number);
5321 }
5322 }
5323 fake_select_lex->join->explain= &eu->fake_select_lex_explain;
5324 }
5325 return 0;
5326 }
5327
5328
5329 /**
5330 A routine used by the parser to decide whether we are specifying a full
5331 partitioning or if only partitions to add or to split.
5332
5333 @note This needs to be outside of WITH_PARTITION_STORAGE_ENGINE since it
5334 is used from the sql parser that doesn't have any ifdef's
5335
5336 @retval TRUE Yes, it is part of a management partition command
5337 @retval FALSE No, not a management partition command
5338 */
5339
is_partition_management() const5340 bool LEX::is_partition_management() const
5341 {
5342 return (sql_command == SQLCOM_ALTER_TABLE &&
5343 (alter_info.partition_flags == ALTER_PARTITION_ADD ||
5344 alter_info.partition_flags == ALTER_PARTITION_REORGANIZE));
5345 }
5346
5347
5348 /**
5349 Exclude last added SELECT_LEX (current) in the UNIT and return pointer in it
5350 (previous become currect)
5351
5352 @return detached SELECT_LEX or NULL in case of error
5353 */
5354
exclude_last_select()5355 SELECT_LEX *LEX::exclude_last_select()
5356 {
5357 return exclude_not_first_select(current_select);
5358 }
5359
exclude_not_first_select(SELECT_LEX * exclude)5360 SELECT_LEX *LEX::exclude_not_first_select(SELECT_LEX *exclude)
5361 {
5362 DBUG_ENTER("LEX::exclude_not_first_select");
5363 DBUG_PRINT("enter", ("exclude %p #%u", exclude, exclude->select_number));
5364 SELECT_LEX_UNIT *unit= exclude->master_unit();
5365 SELECT_LEX *sl;
5366 DBUG_ASSERT(unit->first_select() != exclude);
5367 /* we should go through the list to correctly set current_select */
5368 for(sl= unit->first_select();
5369 sl->next_select() && sl->next_select() != exclude;
5370 sl= sl->next_select());
5371 DBUG_PRINT("info", ("excl: %p unit: %p prev: %p", exclude, unit, sl));
5372 if (!sl)
5373 DBUG_RETURN(NULL);
5374 DBUG_ASSERT(&sl->next == exclude->prev);
5375
5376 exclude->prev= NULL;
5377
5378 current_select= sl;
5379 DBUG_RETURN(exclude);
5380 }
5381
5382
alloc_unit()5383 SELECT_LEX_UNIT *LEX::alloc_unit()
5384 {
5385 SELECT_LEX_UNIT *unit;
5386 DBUG_ENTER("LEX::alloc_unit");
5387 if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
5388 DBUG_RETURN(NULL);
5389
5390 unit->init_query();
5391 /* TODO: reentrant problem */
5392 unit->thd= thd;
5393 unit->link_next= 0;
5394 unit->link_prev= 0;
5395 /* TODO: remove return_to */
5396 unit->return_to= NULL;
5397 DBUG_RETURN(unit);
5398 }
5399
5400
alloc_select(bool select)5401 SELECT_LEX *LEX::alloc_select(bool select)
5402 {
5403 SELECT_LEX *select_lex;
5404 DBUG_ENTER("LEX::alloc_select");
5405 if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
5406 DBUG_RETURN(NULL);
5407 DBUG_PRINT("info", ("Allocate select: %p #%u statement lex: %p",
5408 select_lex, thd->lex->stmt_lex->current_select_number,
5409 thd->lex->stmt_lex));
5410 /*
5411 TODO: move following init to constructor when we get rid of builtin
5412 select
5413 */
5414 select_lex->select_number= ++thd->lex->stmt_lex->current_select_number;
5415 select_lex->parent_lex= this; /* Used in init_query. */
5416 select_lex->init_query();
5417 if (select)
5418 select_lex->init_select();
5419 select_lex->nest_level_base= &this->unit;
5420 select_lex->include_global((st_select_lex_node**)&all_selects_list);
5421 select_lex->context.resolve_in_select_list= TRUE;
5422 DBUG_RETURN(select_lex);
5423 }
5424
5425 SELECT_LEX_UNIT *
create_unit(SELECT_LEX * first_sel)5426 LEX::create_unit(SELECT_LEX *first_sel)
5427 {
5428 SELECT_LEX_UNIT *unit;
5429 DBUG_ENTER("LEX::create_unit");
5430
5431 unit = first_sel->master_unit();
5432
5433 if (!unit && !(unit= alloc_unit()))
5434 DBUG_RETURN(NULL);
5435
5436 unit->register_select_chain(first_sel);
5437 if (first_sel->next_select())
5438 {
5439 unit->reset_distinct();
5440 DBUG_ASSERT(!unit->fake_select_lex);
5441 if (unit->add_fake_select_lex(thd))
5442 DBUG_RETURN(NULL);
5443 }
5444 DBUG_RETURN(unit);
5445 }
5446
5447 SELECT_LEX_UNIT *
attach_selects_chain(SELECT_LEX * first_sel,Name_resolution_context * context)5448 SELECT_LEX::attach_selects_chain(SELECT_LEX *first_sel,
5449 Name_resolution_context *context)
5450 {
5451 SELECT_LEX_UNIT *unit;
5452 DBUG_ENTER("SELECT_LEX::attach_select_chain");
5453
5454 if (!(unit= parent_lex->alloc_unit()))
5455 DBUG_RETURN(NULL);
5456
5457 unit->register_select_chain(first_sel);
5458 register_unit(unit, context);
5459 if (first_sel->next_select())
5460 {
5461 unit->reset_distinct();
5462 DBUG_ASSERT(!unit->fake_select_lex);
5463 if (unit->add_fake_select_lex(parent_lex->thd))
5464 DBUG_RETURN(NULL);
5465 }
5466
5467 DBUG_RETURN(unit);
5468 }
5469
5470 SELECT_LEX *
wrap_unit_into_derived(SELECT_LEX_UNIT * unit)5471 LEX::wrap_unit_into_derived(SELECT_LEX_UNIT *unit)
5472 {
5473 SELECT_LEX *wrapping_sel;
5474 Table_ident *ti;
5475 DBUG_ENTER("LEX::wrap_unit_into_derived");
5476
5477 if (!(wrapping_sel= alloc_select(TRUE)))
5478 DBUG_RETURN(NULL);
5479 Name_resolution_context *context= &wrapping_sel->context;
5480 context->init();
5481 wrapping_sel->automatic_brackets= FALSE;
5482
5483 wrapping_sel->register_unit(unit, context);
5484
5485 /* stuff dummy SELECT * FROM (...) */
5486
5487 if (push_select(wrapping_sel)) // for Items & TABLE_LIST
5488 DBUG_RETURN(NULL);
5489
5490 /* add SELECT list*/
5491 {
5492 Item *item= new (thd->mem_root)
5493 Item_field(thd, context, NULL, NULL, &star_clex_str);
5494 if (item == NULL)
5495 goto err;
5496 if (add_item_to_list(thd, item))
5497 goto err;
5498 (wrapping_sel->with_wild)++;
5499 }
5500
5501 unit->first_select()->set_linkage(DERIVED_TABLE_TYPE);
5502
5503 ti= new (thd->mem_root) Table_ident(unit);
5504 if (ti == NULL)
5505 goto err;
5506 {
5507 TABLE_LIST *table_list;
5508 LEX_CSTRING alias;
5509 if (wrapping_sel->make_unique_derived_name(thd, &alias))
5510 goto err;
5511
5512 if (!(table_list= wrapping_sel->add_table_to_list(thd, ti, &alias,
5513 0, TL_READ,
5514 MDL_SHARED_READ)))
5515 goto err;
5516
5517 context->resolve_in_table_list_only(table_list);
5518 wrapping_sel->add_joined_table(table_list);
5519 }
5520
5521 pop_select();
5522
5523 derived_tables|= DERIVED_SUBQUERY;
5524
5525 DBUG_RETURN(wrapping_sel);
5526
5527 err:
5528 pop_select();
5529 DBUG_RETURN(NULL);
5530 }
5531
wrap_select_chain_into_derived(SELECT_LEX * sel)5532 SELECT_LEX *LEX::wrap_select_chain_into_derived(SELECT_LEX *sel)
5533 {
5534 SELECT_LEX *dummy_select;
5535 SELECT_LEX_UNIT *unit;
5536 Table_ident *ti;
5537 DBUG_ENTER("LEX::wrap_select_chain_into_derived");
5538
5539 if (!(dummy_select= alloc_select(TRUE)))
5540 DBUG_RETURN(NULL);
5541 Name_resolution_context *context= &dummy_select->context;
5542 dummy_select->automatic_brackets= FALSE;
5543 sel->distinct= TRUE; // First select has not this attribute (safety)
5544
5545 if (!(unit= dummy_select->attach_selects_chain(sel, context)))
5546 DBUG_RETURN(NULL);
5547
5548 /* stuff dummy SELECT * FROM (...) */
5549
5550 if (push_select(dummy_select)) // for Items & TABLE_LIST
5551 DBUG_RETURN(NULL);
5552
5553 /* add SELECT list*/
5554 {
5555 Item *item= new (thd->mem_root)
5556 Item_field(thd, context, NULL, NULL, &star_clex_str);
5557 if (item == NULL)
5558 goto err;
5559 if (add_item_to_list(thd, item))
5560 goto err;
5561 (dummy_select->with_wild)++;
5562 }
5563
5564 sel->set_linkage(DERIVED_TABLE_TYPE);
5565
5566 ti= new (thd->mem_root) Table_ident(unit);
5567 if (ti == NULL)
5568 goto err;
5569 {
5570 TABLE_LIST *table_list;
5571 LEX_CSTRING alias;
5572 if (dummy_select->make_unique_derived_name(thd, &alias))
5573 goto err;
5574
5575 if (!(table_list= dummy_select->add_table_to_list(thd, ti, &alias,
5576 0, TL_READ,
5577 MDL_SHARED_READ)))
5578 goto err;
5579
5580 context->resolve_in_table_list_only(table_list);
5581 dummy_select->add_joined_table(table_list);
5582 }
5583
5584 pop_select();
5585
5586 derived_tables|= DERIVED_SUBQUERY;
5587
5588 DBUG_RETURN(dummy_select);
5589
5590 err:
5591 pop_select();
5592 DBUG_RETURN(NULL);
5593 }
5594
push_context(Name_resolution_context * context)5595 bool LEX::push_context(Name_resolution_context *context)
5596 {
5597 DBUG_ENTER("LEX::push_context");
5598 DBUG_PRINT("info", ("Context: %p Select: %p (%d)",
5599 context, context->select_lex,
5600 (context->select_lex ?
5601 context->select_lex->select_number:
5602 0)));
5603 bool res= context_stack.push_front(context, thd->mem_root);
5604 DBUG_RETURN(res);
5605 }
5606
5607
pop_context()5608 Name_resolution_context *LEX::pop_context()
5609 {
5610 DBUG_ENTER("LEX::pop_context");
5611 Name_resolution_context *context= context_stack.pop();
5612 DBUG_PRINT("info", ("Context: %p Select: %p (%d)",
5613 context, context->select_lex,
5614 (context->select_lex ?
5615 context->select_lex->select_number:
5616 0)));
5617 DBUG_RETURN(context);
5618 }
5619
5620
create_priority_nest(SELECT_LEX * first_in_nest)5621 SELECT_LEX *LEX::create_priority_nest(SELECT_LEX *first_in_nest)
5622 {
5623 DBUG_ENTER("LEX::create_priority_nest");
5624 DBUG_ASSERT(first_in_nest->first_nested);
5625 enum sub_select_type wr_unit_type= first_in_nest->get_linkage();
5626 bool wr_distinct= first_in_nest->distinct;
5627 SELECT_LEX *attach_to= first_in_nest->first_nested;
5628 attach_to->cut_next();
5629 SELECT_LEX *wrapper= wrap_select_chain_into_derived(first_in_nest);
5630 if (wrapper)
5631 {
5632 first_in_nest->first_nested= NULL;
5633 wrapper->set_linkage_and_distinct(wr_unit_type, wr_distinct);
5634 wrapper->first_nested= attach_to->first_nested;
5635 wrapper->set_master_unit(attach_to->master_unit());
5636 attach_to->link_neighbour(wrapper);
5637 }
5638 DBUG_RETURN(wrapper);
5639 }
5640
5641
5642 /**
5643 Checks if we need finish "automatic brackets" mode
5644
5645 INTERSECT has higher priority then UNION and EXCEPT, so when it is need we
5646 automatically create lower layer for INTERSECT (automatic brackets) and
5647 here we check if we should return back one level up during parsing procedure.
5648 */
5649
check_automatic_up(enum sub_select_type type)5650 void LEX::check_automatic_up(enum sub_select_type type)
5651 {
5652 if (type != INTERSECT_TYPE &&
5653 current_select->get_linkage() == INTERSECT_TYPE &&
5654 current_select->outer_select() &&
5655 current_select->outer_select()->automatic_brackets)
5656 {
5657 nest_level--;
5658 current_select= current_select->outer_select();
5659 }
5660 }
5661
5662
sp_param_init(LEX_CSTRING * name)5663 sp_variable *LEX::sp_param_init(LEX_CSTRING *name)
5664 {
5665 if (spcont->find_variable(name, true))
5666 {
5667 my_error(ER_SP_DUP_PARAM, MYF(0), name->str);
5668 return NULL;
5669 }
5670 sp_variable *spvar= spcont->add_variable(thd, name);
5671 init_last_field(&spvar->field_def, name,
5672 thd->variables.collation_database);
5673 return spvar;
5674 }
5675
5676
sp_param_fill_definition(sp_variable * spvar)5677 bool LEX::sp_param_fill_definition(sp_variable *spvar)
5678 {
5679 return sphead->fill_spvar_definition(thd, last_field, &spvar->name);
5680 }
5681
5682
set_stmt_init()5683 void LEX::set_stmt_init()
5684 {
5685 sql_command= SQLCOM_SET_OPTION;
5686 mysql_init_select(this);
5687 option_type= OPT_SESSION;
5688 autocommit= 0;
5689 };
5690
5691
5692 /**
5693 Find a local or a package body variable by name.
5694 @param IN name - the variable name
5695 @param OUT ctx - NULL, if the variable was not found,
5696 or LEX::spcont (if a local variable was found)
5697 or the package top level context
5698 (if a package variable was found)
5699 @param OUT handler - NULL, if the variable was not found,
5700 or a pointer to rcontext handler
5701 @retval - the variable (if found), or NULL otherwise.
5702 */
5703 sp_variable *
find_variable(const LEX_CSTRING * name,sp_pcontext ** ctx,const Sp_rcontext_handler ** rh) const5704 LEX::find_variable(const LEX_CSTRING *name,
5705 sp_pcontext **ctx,
5706 const Sp_rcontext_handler **rh) const
5707 {
5708 sp_variable *spv;
5709 if (spcont && (spv= spcont->find_variable(name, false)))
5710 {
5711 *ctx= spcont;
5712 *rh= &sp_rcontext_handler_local;
5713 return spv;
5714 }
5715 sp_package *pkg= sphead ? sphead->m_parent : NULL;
5716 if (pkg && (spv= pkg->find_package_variable(name)))
5717 {
5718 *ctx= pkg->get_parse_context()->child_context(0);
5719 *rh= &sp_rcontext_handler_package_body;
5720 return spv;
5721 }
5722 *ctx= NULL;
5723 *rh= NULL;
5724 return NULL;
5725 }
5726
5727
is_new(const char * str)5728 static bool is_new(const char *str)
5729 {
5730 return (str[0] == 'n' || str[0] == 'N') &&
5731 (str[1] == 'e' || str[1] == 'E') &&
5732 (str[2] == 'w' || str[2] == 'W');
5733 }
5734
is_old(const char * str)5735 static bool is_old(const char *str)
5736 {
5737 return (str[0] == 'o' || str[0] == 'O') &&
5738 (str[1] == 'l' || str[1] == 'L') &&
5739 (str[2] == 'd' || str[2] == 'D');
5740 }
5741
5742
is_trigger_new_or_old_reference(const LEX_CSTRING * name) const5743 bool LEX::is_trigger_new_or_old_reference(const LEX_CSTRING *name) const
5744 {
5745 // "name" is not necessarily NULL-terminated!
5746 return sphead && sphead->m_handler->type() == TYPE_ENUM_TRIGGER &&
5747 name->length == 3 && (is_new(name->str) || is_old(name->str));
5748 }
5749
5750
sp_variable_declarations_init(THD * thd,int nvars)5751 void LEX::sp_variable_declarations_init(THD *thd, int nvars)
5752 {
5753 sp_variable *spvar= spcont->get_last_context_variable();
5754
5755 sphead->reset_lex(thd);
5756 spcont->declare_var_boundary(nvars);
5757 thd->lex->init_last_field(&spvar->field_def, &spvar->name,
5758 thd->variables.collation_database);
5759 }
5760
5761
sp_variable_declarations_set_default(THD * thd,int nvars,Item * dflt_value_item)5762 bool LEX::sp_variable_declarations_set_default(THD *thd, int nvars,
5763 Item *dflt_value_item)
5764 {
5765 bool has_default_clause= dflt_value_item != NULL;
5766 if (!has_default_clause &&
5767 unlikely(!(dflt_value_item= new (thd->mem_root) Item_null(thd))))
5768 return true;
5769
5770 sp_variable *first_spvar = NULL;
5771
5772 for (uint i= 0 ; i < (uint) nvars ; i++)
5773 {
5774 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5775
5776 if (i == 0) {
5777 first_spvar = spvar;
5778 } else if (has_default_clause) {
5779 Item_splocal *item =
5780 new (thd->mem_root)
5781 Item_splocal(thd, &sp_rcontext_handler_local,
5782 &first_spvar->name, first_spvar->offset,
5783 first_spvar->type_handler(), 0, 0);
5784 if (item == NULL)
5785 return true; // OOM
5786 #ifndef DBUG_OFF
5787 item->m_sp = sphead;
5788 #endif
5789 dflt_value_item = item;
5790 }
5791
5792 bool last= i + 1 == (uint) nvars;
5793 spvar->default_value= dflt_value_item;
5794 /* The last instruction is responsible for freeing LEX. */
5795 sp_instr_set *is= new (this->thd->mem_root)
5796 sp_instr_set(sphead->instructions(),
5797 spcont, &sp_rcontext_handler_local,
5798 spvar->offset, dflt_value_item,
5799 this, last);
5800 if (unlikely(is == NULL || sphead->add_instr(is)))
5801 return true;
5802 }
5803 return false;
5804 }
5805
5806
5807 bool
sp_variable_declarations_copy_type_finalize(THD * thd,int nvars,const Column_definition & ref,Row_definition_list * fields,Item * default_value)5808 LEX::sp_variable_declarations_copy_type_finalize(THD *thd, int nvars,
5809 const Column_definition &ref,
5810 Row_definition_list *fields,
5811 Item *default_value)
5812 {
5813 for (uint i= 0 ; i < (uint) nvars; i++)
5814 {
5815 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5816 spvar->field_def.set_type(ref);
5817 if (fields)
5818 {
5819 DBUG_ASSERT(ref.type_handler() == &type_handler_row);
5820 spvar->field_def.set_row_field_definitions(fields);
5821 }
5822 spvar->field_def.field_name= spvar->name;
5823 }
5824 if (unlikely(sp_variable_declarations_set_default(thd, nvars,
5825 default_value)))
5826 return true;
5827 spcont->declare_var_boundary(0);
5828 return sphead->restore_lex(thd);
5829 }
5830
5831
sp_variable_declarations_finalize(THD * thd,int nvars,const Column_definition * cdef,Item * dflt_value_item)5832 bool LEX::sp_variable_declarations_finalize(THD *thd, int nvars,
5833 const Column_definition *cdef,
5834 Item *dflt_value_item)
5835 {
5836 DBUG_ASSERT(cdef);
5837 Column_definition tmp(*cdef);
5838 if (sphead->fill_spvar_definition(thd, &tmp))
5839 return true;
5840 return sp_variable_declarations_copy_type_finalize(thd, nvars, tmp, NULL,
5841 dflt_value_item);
5842 }
5843
5844
sp_variable_declarations_row_finalize(THD * thd,int nvars,Row_definition_list * row,Item * dflt_value_item)5845 bool LEX::sp_variable_declarations_row_finalize(THD *thd, int nvars,
5846 Row_definition_list *row,
5847 Item *dflt_value_item)
5848 {
5849 DBUG_ASSERT(row);
5850 /*
5851 Prepare all row fields.
5852 Note, we do it only one time outside of the below loop.
5853 The converted list in "row" is further reused by all variable
5854 declarations processed by the current call.
5855 Example:
5856 DECLARE
5857 a, b, c ROW(x VARCHAR(10) CHARACTER SET utf8);
5858 BEGIN
5859 ...
5860 END;
5861 */
5862 if (sphead->row_fill_field_definitions(thd, row))
5863 return true;
5864
5865 for (uint i= 0 ; i < (uint) nvars ; i++)
5866 {
5867 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5868 spvar->field_def.set_row_field_definitions(row);
5869 if (sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name))
5870 return true;
5871 }
5872
5873 if (sp_variable_declarations_set_default(thd, nvars, dflt_value_item))
5874 return true;
5875 spcont->declare_var_boundary(0);
5876 return sphead->restore_lex(thd);
5877 }
5878
5879
5880 /**
5881 Finalize a %ROWTYPE declaration, e.g.:
5882 DECLARE a,b,c,d t1%ROWTYPE := ROW(1,2,3);
5883
5884 @param thd - the current thd
5885 @param nvars - the number of variables in the declaration
5886 @param ref - the table or cursor name (see comments below)
5887 @param def - the default value, e.g., ROW(1,2,3), or NULL (no default).
5888 */
5889 bool
sp_variable_declarations_rowtype_finalize(THD * thd,int nvars,Qualified_column_ident * ref,Item * def)5890 LEX::sp_variable_declarations_rowtype_finalize(THD *thd, int nvars,
5891 Qualified_column_ident *ref,
5892 Item *def)
5893 {
5894 uint coffp;
5895 const sp_pcursor *pcursor= ref->table.str && ref->db.str ? NULL :
5896 spcont->find_cursor(&ref->m_column, &coffp,
5897 false);
5898 if (pcursor)
5899 return sp_variable_declarations_cursor_rowtype_finalize(thd, nvars,
5900 coffp, def);
5901 /*
5902 When parsing a qualified identifier chain, the parser does not know yet
5903 if it's going to be a qualified column name (for %TYPE),
5904 or a qualified table name (for %ROWTYPE). So it collects the chain
5905 into Qualified_column_ident.
5906 Now we know that it was actually a qualified table name (%ROWTYPE).
5907 Create a new Table_ident from Qualified_column_ident,
5908 shifting fields as follows:
5909 - ref->m_column becomes table_ref->table
5910 - ref->table becomes table_ref->db
5911 */
5912 return sp_variable_declarations_table_rowtype_finalize(thd, nvars,
5913 ref->table,
5914 ref->m_column,
5915 def);
5916 }
5917
5918
5919 bool
sp_variable_declarations_table_rowtype_finalize(THD * thd,int nvars,const LEX_CSTRING & db,const LEX_CSTRING & table,Item * def)5920 LEX::sp_variable_declarations_table_rowtype_finalize(THD *thd, int nvars,
5921 const LEX_CSTRING &db,
5922 const LEX_CSTRING &table,
5923 Item *def)
5924 {
5925 Table_ident *table_ref;
5926 if (unlikely(!(table_ref=
5927 new (thd->mem_root) Table_ident(thd, &db, &table, false))))
5928 return true;
5929 // Loop through all variables in the same declaration
5930 for (uint i= 0 ; i < (uint) nvars; i++)
5931 {
5932 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5933 spvar->field_def.set_table_rowtype_ref(table_ref);
5934 sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
5935 }
5936 if (sp_variable_declarations_set_default(thd, nvars, def))
5937 return true;
5938 // Make sure sp_rcontext is created using the invoker security context:
5939 sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
5940 spcont->declare_var_boundary(0);
5941 return sphead->restore_lex(thd);
5942 }
5943
5944
5945 bool
sp_variable_declarations_cursor_rowtype_finalize(THD * thd,int nvars,uint offset,Item * def)5946 LEX::sp_variable_declarations_cursor_rowtype_finalize(THD *thd, int nvars,
5947 uint offset,
5948 Item *def)
5949 {
5950 const sp_pcursor *pcursor= spcont->find_cursor(offset);
5951
5952 // Loop through all variables in the same declaration
5953 for (uint i= 0 ; i < (uint) nvars; i++)
5954 {
5955 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5956
5957 spvar->field_def.set_cursor_rowtype_ref(offset);
5958 sp_instr_cursor_copy_struct *instr=
5959 new (thd->mem_root) sp_instr_cursor_copy_struct(sphead->instructions(),
5960 spcont, offset,
5961 pcursor->lex(),
5962 spvar->offset);
5963 if (instr == NULL || sphead->add_instr(instr))
5964 return true;
5965
5966 sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
5967 }
5968 if (unlikely(sp_variable_declarations_set_default(thd, nvars, def)))
5969 return true;
5970 // Make sure sp_rcontext is created using the invoker security context:
5971 sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
5972 spcont->declare_var_boundary(0);
5973 return sphead->restore_lex(thd);
5974 }
5975
5976
5977 /*
5978 Add declarations for table column and SP variable anchor types:
5979 - DECLARE spvar1 TYPE OF db1.table1.column1;
5980 - DECLARE spvar1 TYPE OF table1.column1;
5981 - DECLARE spvar1 TYPE OF spvar0;
5982 */
5983 bool
sp_variable_declarations_with_ref_finalize(THD * thd,int nvars,Qualified_column_ident * ref,Item * def)5984 LEX::sp_variable_declarations_with_ref_finalize(THD *thd, int nvars,
5985 Qualified_column_ident *ref,
5986 Item *def)
5987 {
5988 return ref->db.length == 0 && ref->table.length == 0 ?
5989 sp_variable_declarations_vartype_finalize(thd, nvars, ref->m_column, def) :
5990 sp_variable_declarations_column_type_finalize(thd, nvars, ref, def);
5991 }
5992
5993
5994 bool
sp_variable_declarations_column_type_finalize(THD * thd,int nvars,Qualified_column_ident * ref,Item * def)5995 LEX::sp_variable_declarations_column_type_finalize(THD *thd, int nvars,
5996 Qualified_column_ident *ref,
5997 Item *def)
5998 {
5999 for (uint i= 0 ; i < (uint) nvars; i++)
6000 {
6001 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
6002 spvar->field_def.set_column_type_ref(ref);
6003 spvar->field_def.field_name= spvar->name;
6004 }
6005 sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
6006 if (sp_variable_declarations_set_default(thd, nvars, def))
6007 return true;
6008 spcont->declare_var_boundary(0);
6009 return sphead->restore_lex(thd);
6010 }
6011
6012
6013 bool
sp_variable_declarations_vartype_finalize(THD * thd,int nvars,const LEX_CSTRING & ref,Item * default_value)6014 LEX::sp_variable_declarations_vartype_finalize(THD *thd, int nvars,
6015 const LEX_CSTRING &ref,
6016 Item *default_value)
6017 {
6018 sp_variable *t;
6019 if (!spcont || !(t= spcont->find_variable(&ref, false)))
6020 {
6021 my_error(ER_SP_UNDECLARED_VAR, MYF(0), ref.str);
6022 return true;
6023 }
6024
6025 if (t->field_def.is_cursor_rowtype_ref())
6026 {
6027 uint offset= t->field_def.cursor_rowtype_offset();
6028 return sp_variable_declarations_cursor_rowtype_finalize(thd, nvars,
6029 offset,
6030 default_value);
6031 }
6032
6033 if (t->field_def.is_column_type_ref())
6034 {
6035 Qualified_column_ident *tmp= t->field_def.column_type_ref();
6036 return sp_variable_declarations_column_type_finalize(thd, nvars, tmp,
6037 default_value);
6038 }
6039
6040 if (t->field_def.is_table_rowtype_ref())
6041 {
6042 const Table_ident *tmp= t->field_def.table_rowtype_ref();
6043 return sp_variable_declarations_table_rowtype_finalize(thd, nvars,
6044 tmp->db,
6045 tmp->table,
6046 default_value);
6047 }
6048
6049 // A reference to a scalar or a row variable with an explicit data type
6050 return sp_variable_declarations_copy_type_finalize(thd, nvars,
6051 t->field_def,
6052 t->field_def.
6053 row_field_definitions(),
6054 default_value);
6055 }
6056
6057
6058 /**********************************************************************
6059 The FOR LOOP statement
6060
6061 This syntax:
6062 FOR i IN lower_bound .. upper_bound
6063 LOOP
6064 statements;
6065 END LOOP;
6066
6067 is translated into:
6068
6069 DECLARE
6070 i INT := lower_bound;
6071 j INT := upper_bound;
6072 BEGIN
6073 WHILE i <= j
6074 LOOP
6075 statements;
6076 i:= i + 1;
6077 END LOOP;
6078 END;
6079 */
6080
6081
sp_add_for_loop_variable(THD * thd,const LEX_CSTRING * name,Item * value)6082 sp_variable *LEX::sp_add_for_loop_variable(THD *thd, const LEX_CSTRING *name,
6083 Item *value)
6084 {
6085 sp_variable *spvar= spcont->add_variable(thd, name);
6086 spcont->declare_var_boundary(1);
6087 spvar->field_def.field_name= spvar->name;
6088 spvar->field_def.set_handler(&type_handler_longlong);
6089 type_handler_longlong.Column_definition_prepare_stage2(&spvar->field_def,
6090 NULL, HA_CAN_GEOMETRY);
6091 if (!value && unlikely(!(value= new (thd->mem_root) Item_null(thd))))
6092 return NULL;
6093
6094 spvar->default_value= value;
6095 sp_instr_set *is= new (this->thd->mem_root)
6096 sp_instr_set(sphead->instructions(),
6097 spcont, &sp_rcontext_handler_local,
6098 spvar->offset, value,
6099 this, true);
6100 if (unlikely(is == NULL || sphead->add_instr(is)))
6101 return NULL;
6102 spcont->declare_var_boundary(0);
6103 return spvar;
6104 }
6105
6106
sp_for_loop_implicit_cursor_statement(THD * thd,Lex_for_loop_bounds_st * bounds,sp_lex_cursor * cur)6107 bool LEX::sp_for_loop_implicit_cursor_statement(THD *thd,
6108 Lex_for_loop_bounds_st *bounds,
6109 sp_lex_cursor *cur)
6110 {
6111 Item *item;
6112 DBUG_ASSERT(sphead);
6113 LEX_CSTRING name= {STRING_WITH_LEN("[implicit_cursor]") };
6114 if (sp_declare_cursor(thd, &name, cur, NULL, true))
6115 return true;
6116 DBUG_ASSERT(thd->lex == this);
6117 if (unlikely(!(bounds->m_index=
6118 new (thd->mem_root) sp_assignment_lex(thd, this))))
6119 return true;
6120 bounds->m_index->sp_lex_in_use= true;
6121 sphead->reset_lex(thd, bounds->m_index);
6122 DBUG_ASSERT(thd->lex != this);
6123 /*
6124 We pass NULL as Name_resolution_context here.
6125 It's OK, fix_fields() will not be called for this Item_field created.
6126 Item_field is only needed for LEX::sp_for_loop_cursor_declarations()
6127 and is used to transfer the loop index variable name, "rec" in this example:
6128 FOR rec IN (SELECT * FROM t1)
6129 DO
6130 SELECT rec.a, rec.b;
6131 END FOR;
6132 */
6133 if (!(item= new (thd->mem_root) Item_field(thd, NULL, NullS, NullS, &name)))
6134 return true;
6135 bounds->m_index->set_item_and_free_list(item, NULL);
6136 if (thd->lex->sphead->restore_lex(thd))
6137 return true;
6138 DBUG_ASSERT(thd->lex == this);
6139 bounds->m_direction= 1;
6140 bounds->m_target_bound= NULL;
6141 bounds->m_implicit_cursor= true;
6142 return false;
6143 }
6144
6145 sp_variable *
sp_add_for_loop_cursor_variable(THD * thd,const LEX_CSTRING * name,const sp_pcursor * pcursor,uint coffset,sp_assignment_lex * param_lex,Item_args * parameters)6146 LEX::sp_add_for_loop_cursor_variable(THD *thd,
6147 const LEX_CSTRING *name,
6148 const sp_pcursor *pcursor,
6149 uint coffset,
6150 sp_assignment_lex *param_lex,
6151 Item_args *parameters)
6152 {
6153 sp_variable *spvar= spcont->add_variable(thd, name);
6154 if (!spvar)
6155 return NULL;
6156 spcont->declare_var_boundary(1);
6157 sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
6158 if (unlikely(!(spvar->default_value= new (thd->mem_root) Item_null(thd))))
6159 return NULL;
6160
6161 spvar->field_def.set_cursor_rowtype_ref(coffset);
6162
6163 if (unlikely(sphead->add_for_loop_open_cursor(thd, spcont, spvar, pcursor,
6164 coffset,
6165 param_lex, parameters)))
6166 return NULL;
6167
6168 spcont->declare_var_boundary(0);
6169 return spvar;
6170 }
6171
6172
6173 /**
6174 Generate a code for a FOR loop condition:
6175 - Make Item_splocal for the FOR loop index variable
6176 - Make Item_splocal for the FOR loop upper bound variable
6177 - Make a comparison function item on top of these two variables
6178 */
sp_for_loop_condition(THD * thd,const Lex_for_loop_st & loop)6179 bool LEX::sp_for_loop_condition(THD *thd, const Lex_for_loop_st &loop)
6180 {
6181 Item_splocal *args[2];
6182 for (uint i= 0 ; i < 2; i++)
6183 {
6184 sp_variable *src= i == 0 ? loop.m_index : loop.m_target_bound;
6185 args[i]= new (thd->mem_root)
6186 Item_splocal(thd, &sp_rcontext_handler_local,
6187 &src->name, src->offset, src->type_handler());
6188 if (unlikely(args[i] == NULL))
6189 return true;
6190 #ifdef DBUG_ASSERT_EXISTS
6191 args[i]->m_sp= sphead;
6192 #endif
6193 }
6194
6195 Item *expr= loop.m_direction > 0 ?
6196 (Item *) new (thd->mem_root) Item_func_le(thd, args[0], args[1]) :
6197 (Item *) new (thd->mem_root) Item_func_ge(thd, args[0], args[1]);
6198 return unlikely(!expr) || unlikely(sp_while_loop_expression(thd, expr));
6199 }
6200
6201
6202 /**
6203 Generate the FOR LOOP condition code in its own lex
6204 */
sp_for_loop_intrange_condition_test(THD * thd,const Lex_for_loop_st & loop)6205 bool LEX::sp_for_loop_intrange_condition_test(THD *thd,
6206 const Lex_for_loop_st &loop)
6207 {
6208 spcont->set_for_loop(loop);
6209 sphead->reset_lex(thd);
6210 if (unlikely(thd->lex->sp_for_loop_condition(thd, loop)))
6211 return true;
6212 return thd->lex->sphead->restore_lex(thd);
6213 }
6214
6215
sp_for_loop_cursor_condition_test(THD * thd,const Lex_for_loop_st & loop)6216 bool LEX::sp_for_loop_cursor_condition_test(THD *thd,
6217 const Lex_for_loop_st &loop)
6218 {
6219 const LEX_CSTRING *cursor_name;
6220 Item *expr;
6221 spcont->set_for_loop(loop);
6222 sphead->reset_lex(thd);
6223 cursor_name= spcont->find_cursor(loop.m_cursor_offset);
6224 DBUG_ASSERT(cursor_name);
6225 if (unlikely(!(expr=
6226 new (thd->mem_root)
6227 Item_func_cursor_found(thd, cursor_name,
6228 loop.m_cursor_offset))))
6229 return true;
6230 if (thd->lex->sp_while_loop_expression(thd, expr))
6231 return true;
6232 return thd->lex->sphead->restore_lex(thd);
6233 }
6234
6235
sp_for_loop_intrange_declarations(THD * thd,Lex_for_loop_st * loop,const LEX_CSTRING * index,const Lex_for_loop_bounds_st & bounds)6236 bool LEX::sp_for_loop_intrange_declarations(THD *thd, Lex_for_loop_st *loop,
6237 const LEX_CSTRING *index,
6238 const Lex_for_loop_bounds_st &bounds)
6239 {
6240 Item *item;
6241 if ((item= bounds.m_index->get_item())->type() == Item::FIELD_ITEM)
6242 {
6243 // We're here is the lower bound is unknown identifier
6244 my_error(ER_SP_UNDECLARED_VAR, MYF(0), item->full_name());
6245 return true;
6246 }
6247 if ((item= bounds.m_target_bound->get_item())->type() == Item::FIELD_ITEM)
6248 {
6249 // We're here is the upper bound is unknown identifier
6250 my_error(ER_SP_UNDECLARED_VAR, MYF(0), item->full_name());
6251 return true;
6252 }
6253 if (!(loop->m_index=
6254 bounds.m_index->sp_add_for_loop_variable(thd, index,
6255 bounds.m_index->get_item())))
6256 return true;
6257 if (unlikely(!(loop->m_target_bound=
6258 bounds.m_target_bound->
6259 sp_add_for_loop_target_bound(thd,
6260 bounds.
6261 m_target_bound->get_item()))))
6262 return true;
6263 loop->m_direction= bounds.m_direction;
6264 loop->m_implicit_cursor= 0;
6265 return false;
6266 }
6267
6268
sp_for_loop_cursor_declarations(THD * thd,Lex_for_loop_st * loop,const LEX_CSTRING * index,const Lex_for_loop_bounds_st & bounds)6269 bool LEX::sp_for_loop_cursor_declarations(THD *thd,
6270 Lex_for_loop_st *loop,
6271 const LEX_CSTRING *index,
6272 const Lex_for_loop_bounds_st &bounds)
6273 {
6274 Item *item= bounds.m_index->get_item();
6275 Item_splocal *item_splocal;
6276 Item_field *item_field;
6277 Item_func_sp *item_func_sp= NULL;
6278 LEX_CSTRING name;
6279 uint coffs, param_count= 0;
6280 const sp_pcursor *pcursor;
6281 DBUG_ENTER("LEX::sp_for_loop_cursor_declarations");
6282
6283 if ((item_splocal= item->get_item_splocal()))
6284 name= item_splocal->m_name;
6285 else if ((item_field= item->type() == Item::FIELD_ITEM ?
6286 static_cast<Item_field *>(item) : NULL) &&
6287 item_field->table_name == NULL)
6288 name= item_field->field_name;
6289 else if (item->type() == Item::FUNC_ITEM &&
6290 static_cast<Item_func*>(item)->functype() == Item_func::FUNC_SP &&
6291 !static_cast<Item_func_sp*>(item)->get_sp_name()->m_explicit_name)
6292 {
6293 /*
6294 When a FOR LOOP for a cursor with parameters is parsed:
6295 FOR index IN cursor(1,2,3) LOOP
6296 statements;
6297 END LOOP;
6298 the parser scans "cursor(1,2,3)" using the "expr" rule,
6299 so it thinks that cursor(1,2,3) is a stored function call.
6300 It's not easy to implement this without using "expr" because
6301 of grammar conflicts.
6302 As a side effect, the Item_func_sp and its arguments in the parentheses
6303 belong to the same LEX. This is different from an explicit
6304 "OPEN cursor(1,2,3)" where every expression belongs to a separate LEX.
6305 */
6306 item_func_sp= static_cast<Item_func_sp*>(item);
6307 name= item_func_sp->get_sp_name()->m_name;
6308 param_count= item_func_sp->argument_count();
6309 }
6310 else
6311 {
6312 thd->parse_error();
6313 DBUG_RETURN(true);
6314 }
6315 if (unlikely(!(pcursor= spcont->find_cursor_with_error(&name, &coffs,
6316 false)) ||
6317 pcursor->check_param_count_with_error(param_count)))
6318 DBUG_RETURN(true);
6319
6320 if (!(loop->m_index= sp_add_for_loop_cursor_variable(thd, index,
6321 pcursor, coffs,
6322 bounds.m_index,
6323 item_func_sp)))
6324 DBUG_RETURN(true);
6325 loop->m_target_bound= NULL;
6326 loop->m_direction= bounds.m_direction;
6327 loop->m_cursor_offset= coffs;
6328 loop->m_implicit_cursor= bounds.m_implicit_cursor;
6329 DBUG_RETURN(false);
6330 }
6331
6332
6333 /**
6334 Generate a code for a FOR loop index increment
6335 */
sp_for_loop_increment(THD * thd,const Lex_for_loop_st & loop)6336 bool LEX::sp_for_loop_increment(THD *thd, const Lex_for_loop_st &loop)
6337 {
6338 Item_splocal *splocal= new (thd->mem_root)
6339 Item_splocal(thd, &sp_rcontext_handler_local,
6340 &loop.m_index->name, loop.m_index->offset,
6341 loop.m_index->type_handler());
6342 if (unlikely(splocal == NULL))
6343 return true;
6344 #ifdef DBUG_ASSERT_EXISTS
6345 splocal->m_sp= sphead;
6346 #endif
6347 Item_int *inc= new (thd->mem_root) Item_int(thd, loop.m_direction);
6348 if (unlikely(!inc))
6349 return true;
6350 Item *expr= new (thd->mem_root) Item_func_plus(thd, splocal, inc);
6351 if (unlikely(!expr) ||
6352 unlikely(sphead->set_local_variable(thd, spcont,
6353 &sp_rcontext_handler_local,
6354 loop.m_index, expr, this, true)))
6355 return true;
6356 return false;
6357 }
6358
6359
sp_for_loop_intrange_finalize(THD * thd,const Lex_for_loop_st & loop)6360 bool LEX::sp_for_loop_intrange_finalize(THD *thd, const Lex_for_loop_st &loop)
6361 {
6362 sphead->reset_lex(thd);
6363
6364 // Generate FOR LOOP index increment in its own lex
6365 DBUG_ASSERT(this != thd->lex);
6366 if (unlikely(thd->lex->sp_for_loop_increment(thd, loop) ||
6367 thd->lex->sphead->restore_lex(thd)))
6368 return true;
6369
6370 // Generate a jump to the beginning of the loop
6371 DBUG_ASSERT(this == thd->lex);
6372 return sp_while_loop_finalize(thd);
6373 }
6374
6375
sp_for_loop_cursor_finalize(THD * thd,const Lex_for_loop_st & loop)6376 bool LEX::sp_for_loop_cursor_finalize(THD *thd, const Lex_for_loop_st &loop)
6377 {
6378 sp_instr_cfetch *instr=
6379 new (thd->mem_root) sp_instr_cfetch(sphead->instructions(),
6380 spcont, loop.m_cursor_offset, false);
6381 if (unlikely(instr == NULL) || unlikely(sphead->add_instr(instr)))
6382 return true;
6383 instr->add_to_varlist(loop.m_index);
6384 // Generate a jump to the beginning of the loop
6385 return sp_while_loop_finalize(thd);
6386 }
6387
sp_for_loop_outer_block_finalize(THD * thd,const Lex_for_loop_st & loop)6388 bool LEX::sp_for_loop_outer_block_finalize(THD *thd,
6389 const Lex_for_loop_st &loop)
6390 {
6391 Lex_spblock tmp;
6392 tmp.curs= MY_TEST(loop.m_implicit_cursor);
6393 if (unlikely(sp_block_finalize(thd, tmp))) // The outer DECLARE..BEGIN..END
6394 return true;
6395 if (!loop.is_for_loop_explicit_cursor())
6396 return false;
6397 /*
6398 Explicit cursor FOR loop must close the cursor automatically.
6399 Note, implicit cursor FOR loop does not need to close the cursor,
6400 it's closed by sp_instr_cpop.
6401 */
6402 sp_instr_cclose *ic= new (thd->mem_root)
6403 sp_instr_cclose(sphead->instructions(), spcont,
6404 loop.m_cursor_offset);
6405 return ic == NULL || sphead->add_instr(ic);
6406 }
6407
6408 /***************************************************************************/
6409
sp_declare_cursor(THD * thd,const LEX_CSTRING * name,sp_lex_cursor * cursor_stmt,sp_pcontext * param_ctx,bool add_cpush_instr)6410 bool LEX::sp_declare_cursor(THD *thd, const LEX_CSTRING *name,
6411 sp_lex_cursor *cursor_stmt,
6412 sp_pcontext *param_ctx, bool add_cpush_instr)
6413 {
6414 uint offp;
6415 sp_instr_cpush *i;
6416
6417 if (spcont->find_cursor(name, &offp, true))
6418 {
6419 my_error(ER_SP_DUP_CURS, MYF(0), name->str);
6420 return true;
6421 }
6422
6423 if (unlikely(spcont->add_cursor(name, param_ctx, cursor_stmt)))
6424 return true;
6425
6426 if (add_cpush_instr)
6427 {
6428 i= new (thd->mem_root)
6429 sp_instr_cpush(sphead->instructions(), spcont, cursor_stmt,
6430 spcont->current_cursor_count() - 1);
6431 return unlikely(i == NULL) || unlikely(sphead->add_instr(i));
6432 }
6433 return false;
6434 }
6435
6436
6437 /**
6438 Generate an SP code for an "OPEN cursor_name" statement.
6439 @param thd
6440 @param name - Name of the cursor
6441 @param parameters - Cursor parameters, e.g. OPEN c(1,2,3)
6442 @returns - false on success, true on error
6443 */
sp_open_cursor(THD * thd,const LEX_CSTRING * name,List<sp_assignment_lex> * parameters)6444 bool LEX::sp_open_cursor(THD *thd, const LEX_CSTRING *name,
6445 List<sp_assignment_lex> *parameters)
6446 {
6447 uint offset;
6448 const sp_pcursor *pcursor;
6449 uint param_count= parameters ? parameters->elements : 0;
6450 return !(pcursor= spcont->find_cursor_with_error(name, &offset, false)) ||
6451 pcursor->check_param_count_with_error(param_count) ||
6452 sphead->add_open_cursor(thd, spcont, offset,
6453 pcursor->param_context(), parameters);
6454 }
6455
6456
sp_handler_declaration_init(THD * thd,int type)6457 bool LEX::sp_handler_declaration_init(THD *thd, int type)
6458 {
6459 sp_handler *h= spcont->add_handler(thd, (sp_handler::enum_type) type);
6460
6461 spcont= spcont->push_context(thd, sp_pcontext::HANDLER_SCOPE);
6462
6463 sp_instr_hpush_jump *i=
6464 new (thd->mem_root) sp_instr_hpush_jump(sphead->instructions(), spcont, h);
6465
6466 if (unlikely(i == NULL) || unlikely(sphead->add_instr(i)))
6467 return true;
6468
6469 /* For continue handlers, mark end of handler scope. */
6470 if (type == sp_handler::CONTINUE &&
6471 unlikely(sphead->push_backpatch(thd, i, spcont->last_label())))
6472 return true;
6473
6474 if (unlikely(sphead->push_backpatch(thd, i,
6475 spcont->push_label(thd, &empty_clex_str,
6476 0))))
6477 return true;
6478
6479 return false;
6480 }
6481
6482
sp_handler_declaration_finalize(THD * thd,int type)6483 bool LEX::sp_handler_declaration_finalize(THD *thd, int type)
6484 {
6485 sp_label *hlab= spcont->pop_label(); /* After this hdlr */
6486 sp_instr_hreturn *i;
6487
6488 if (type == sp_handler::CONTINUE)
6489 {
6490 i= new (thd->mem_root) sp_instr_hreturn(sphead->instructions(), spcont);
6491 if (unlikely(i == NULL) ||
6492 unlikely(sphead->add_instr(i)))
6493 return true;
6494 }
6495 else
6496 { /* EXIT or UNDO handler, just jump to the end of the block */
6497 i= new (thd->mem_root) sp_instr_hreturn(sphead->instructions(), spcont);
6498 if (unlikely(i == NULL) ||
6499 unlikely(sphead->add_instr(i)) ||
6500 unlikely(sphead->push_backpatch(thd, i, spcont->last_label()))) /* Block end */
6501 return true;
6502 }
6503 sphead->backpatch(hlab);
6504 spcont= spcont->pop_context();
6505 return false;
6506 }
6507
6508
sp_block_init(THD * thd,const LEX_CSTRING * label)6509 void LEX::sp_block_init(THD *thd, const LEX_CSTRING *label)
6510 {
6511 spcont->push_label(thd, label, sphead->instructions(), sp_label::BEGIN);
6512 spcont= spcont->push_context(thd, sp_pcontext::REGULAR_SCOPE);
6513 }
6514
6515
sp_block_finalize(THD * thd,const Lex_spblock_st spblock,class sp_label ** splabel)6516 bool LEX::sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
6517 class sp_label **splabel)
6518 {
6519 sp_head *sp= sphead;
6520 sp_pcontext *ctx= spcont;
6521 sp_instr *i;
6522
6523 sp->backpatch(ctx->last_label()); /* We always have a label */
6524 if (spblock.hndlrs)
6525 {
6526 i= new (thd->mem_root)
6527 sp_instr_hpop(sp->instructions(), ctx, spblock.hndlrs);
6528 if (unlikely(i == NULL) ||
6529 unlikely(sp->add_instr(i)))
6530 return true;
6531 }
6532 if (spblock.curs)
6533 {
6534 i= new (thd->mem_root)
6535 sp_instr_cpop(sp->instructions(), ctx, spblock.curs);
6536 if (unlikely(i == NULL) ||
6537 unlikely(sp->add_instr(i)))
6538 return true;
6539 }
6540 spcont= ctx->pop_context();
6541 *splabel= spcont->pop_label();
6542 return false;
6543 }
6544
6545
sp_block_finalize(THD * thd,const Lex_spblock_st spblock,const LEX_CSTRING * end_label)6546 bool LEX::sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
6547 const LEX_CSTRING *end_label)
6548 {
6549 sp_label *splabel;
6550 if (unlikely(sp_block_finalize(thd, spblock, &splabel)))
6551 return true;
6552 if (unlikely(end_label->str &&
6553 lex_string_cmp(system_charset_info,
6554 end_label, &splabel->name) != 0))
6555 {
6556 my_error(ER_SP_LABEL_MISMATCH, MYF(0), end_label->str);
6557 return true;
6558 }
6559 return false;
6560 }
6561
6562
make_sp_name(THD * thd,const LEX_CSTRING * name)6563 sp_name *LEX::make_sp_name(THD *thd, const LEX_CSTRING *name)
6564 {
6565 sp_name *res;
6566 LEX_CSTRING db;
6567 if (unlikely(check_routine_name(name)) ||
6568 unlikely(copy_db_to(&db)) ||
6569 unlikely((!(res= new (thd->mem_root) sp_name(&db, name, false)))))
6570 return NULL;
6571 return res;
6572 }
6573
6574
6575 /**
6576 When a package routine name is stored in memory in Database_qualified_name,
6577 the dot character is used to delimit package name from the routine name,
6578 e.g.:
6579 m_db= 'test'; -- database 'test'
6580 m_name= 'p1.p1'; -- package 'p1', routine 'p1'
6581 See database_qualified_name::make_package_routine_name() for details.
6582 Disallow package routine names with dots,
6583 to avoid ambiguity when interpreting m_name='p1.p1.p1', between:
6584 a. package 'p1.p1' + routine 'p1'
6585 b. package 'p1' + routine 'p1.p1'
6586 m_name='p1.p1.p1' will always mean (a).
6587 */
make_sp_name_package_routine(THD * thd,const LEX_CSTRING * name)6588 sp_name *LEX::make_sp_name_package_routine(THD *thd, const LEX_CSTRING *name)
6589 {
6590 sp_name *res= make_sp_name(thd, name);
6591 if (likely(res) && unlikely(strchr(res->m_name.str, '.')))
6592 {
6593 my_error(ER_SP_WRONG_NAME, MYF(0), res->m_name.str);
6594 res= NULL;
6595 }
6596 return res;
6597 }
6598
6599
make_sp_name(THD * thd,const LEX_CSTRING * name1,const LEX_CSTRING * name2)6600 sp_name *LEX::make_sp_name(THD *thd, const LEX_CSTRING *name1,
6601 const LEX_CSTRING *name2)
6602 {
6603 sp_name *res;
6604 LEX_CSTRING norm_name1;
6605 if (unlikely(!name1->str) ||
6606 unlikely(!thd->make_lex_string(&norm_name1, name1->str,
6607 name1->length)) ||
6608 unlikely(check_db_name((LEX_STRING *) &norm_name1)))
6609 {
6610 my_error(ER_WRONG_DB_NAME, MYF(0), name1->str);
6611 return NULL;
6612 }
6613 if (unlikely(check_routine_name(name2)) ||
6614 unlikely(!(res= new (thd->mem_root) sp_name(&norm_name1, name2, true))))
6615 return NULL;
6616 return res;
6617 }
6618
6619
make_sp_head(THD * thd,const sp_name * name,const Sp_handler * sph,enum_sp_aggregate_type agg_type)6620 sp_head *LEX::make_sp_head(THD *thd, const sp_name *name,
6621 const Sp_handler *sph,
6622 enum_sp_aggregate_type agg_type)
6623 {
6624 sp_package *package= get_sp_package();
6625 sp_head *sp;
6626
6627 /* Order is important here: new - reset - init */
6628 if (likely((sp= sp_head::create(package, sph, agg_type))))
6629 {
6630 sp->reset_thd_mem_root(thd);
6631 sp->init(this);
6632 if (name)
6633 {
6634 if (package)
6635 sp->make_package_routine_name(sp->get_main_mem_root(),
6636 package->m_db,
6637 package->m_name,
6638 name->m_name);
6639 else
6640 sp->init_sp_name(name);
6641 sp->make_qname(sp->get_main_mem_root(), &sp->m_qname);
6642 }
6643 sphead= sp;
6644 }
6645 sp_chistics.init();
6646 return sp;
6647 }
6648
6649
make_sp_head_no_recursive(THD * thd,const sp_name * name,const Sp_handler * sph,enum_sp_aggregate_type agg_type)6650 sp_head *LEX::make_sp_head_no_recursive(THD *thd, const sp_name *name,
6651 const Sp_handler *sph,
6652 enum_sp_aggregate_type agg_type)
6653 {
6654 sp_package *package= thd->lex->get_sp_package();
6655 /*
6656 Sp_handler::sp_clone_and_link_routine() generates a standalone-alike
6657 statement to clone package routines for recursion, e.g.:
6658 CREATE PROCEDURE p1 AS BEGIN NULL; END;
6659 Translate a standalone routine handler to the corresponding
6660 package routine handler if we're cloning a package routine, e.g.:
6661 sp_handler_procedure -> sp_handler_package_procedure
6662 sp_handler_function -> sp_handler_package_function
6663 */
6664 if (package && package->m_is_cloning_routine)
6665 sph= sph->package_routine_handler();
6666 if (!sphead ||
6667 (package &&
6668 (sph == &sp_handler_package_procedure ||
6669 sph == &sp_handler_package_function)))
6670 return make_sp_head(thd, name, sph, agg_type);
6671 my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), sph->type_str());
6672 return NULL;
6673 }
6674
6675
sp_body_finalize_routine(THD * thd)6676 bool LEX::sp_body_finalize_routine(THD *thd)
6677 {
6678 if (sphead->check_unresolved_goto())
6679 return true;
6680 sphead->set_stmt_end(thd);
6681 sphead->restore_thd_mem_root(thd);
6682 return false;
6683 }
6684
6685
sp_body_finalize_procedure(THD * thd)6686 bool LEX::sp_body_finalize_procedure(THD *thd)
6687 {
6688 return sphead->check_group_aggregate_instructions_forbid() ||
6689 sp_body_finalize_routine(thd);
6690 }
6691
6692
sp_body_finalize_procedure_standalone(THD * thd,const sp_name * end_name)6693 bool LEX::sp_body_finalize_procedure_standalone(THD *thd,
6694 const sp_name *end_name)
6695 {
6696 return sp_body_finalize_procedure(thd) ||
6697 sphead->check_standalone_routine_end_name(end_name);
6698 }
6699
6700
sp_body_finalize_function(THD * thd)6701 bool LEX::sp_body_finalize_function(THD *thd)
6702 {
6703 if (sphead->is_not_allowed_in_function("function") ||
6704 sphead->check_group_aggregate_instructions_function())
6705 return true;
6706 if (!(sphead->m_flags & sp_head::HAS_RETURN))
6707 {
6708 my_error(ER_SP_NORETURN, MYF(0), ErrConvDQName(sphead).ptr());
6709 return true;
6710 }
6711 if (sp_body_finalize_routine(thd))
6712 return true;
6713 (void) is_native_function_with_warn(thd, &sphead->m_name);
6714 return false;
6715 }
6716
6717
sp_body_finalize_trigger(THD * thd)6718 bool LEX::sp_body_finalize_trigger(THD *thd)
6719 {
6720 return sphead->is_not_allowed_in_function("trigger") ||
6721 sp_body_finalize_procedure(thd);
6722 }
6723
6724
sp_body_finalize_event(THD * thd)6725 bool LEX::sp_body_finalize_event(THD *thd)
6726 {
6727 event_parse_data->body_changed= true;
6728 return sp_body_finalize_procedure(thd);
6729 }
6730
6731
stmt_create_stored_function_finalize_standalone(const sp_name * end_name)6732 bool LEX::stmt_create_stored_function_finalize_standalone(const sp_name *end_name)
6733 {
6734 if (sphead->check_standalone_routine_end_name(end_name))
6735 return true;
6736 stmt_create_routine_finalize();
6737 return false;
6738 }
6739
6740
sp_block_with_exceptions_finalize_declarations(THD * thd)6741 bool LEX::sp_block_with_exceptions_finalize_declarations(THD *thd)
6742 {
6743 /*
6744 [ DECLARE declarations ]
6745 BEGIN executable_section
6746 [ EXCEPTION exceptions ]
6747 END
6748
6749 We are now at the "BEGIN" keyword.
6750 We have collected all declarations, including DECLARE HANDLER directives.
6751 But there will be possibly more handlers in the EXCEPTION section.
6752
6753 Generate a forward jump from the end of the DECLARE section to the
6754 beginning of the EXCEPTION section, over the executable section.
6755 */
6756 return sphead->add_instr_jump(thd, spcont);
6757 }
6758
6759
6760 bool
sp_block_with_exceptions_finalize_executable_section(THD * thd,uint executable_section_ip)6761 LEX::sp_block_with_exceptions_finalize_executable_section(THD *thd,
6762 uint executable_section_ip)
6763 {
6764 /*
6765 We're now at the end of "executable_section" of the block,
6766 near the "EXCEPTION" or the "END" keyword.
6767 Generate a jump to the END of the block over the EXCEPTION section.
6768 */
6769 if (sphead->add_instr_jump_forward_with_backpatch(thd, spcont))
6770 return true;
6771 /*
6772 Set the destination for the jump that we added in
6773 sp_block_with_exceptions_finalize_declarations().
6774 */
6775 sp_instr *instr= sphead->get_instr(executable_section_ip - 1);
6776 instr->backpatch(sphead->instructions(), spcont);
6777 return false;
6778 }
6779
6780
6781 bool
sp_block_with_exceptions_finalize_exceptions(THD * thd,uint executable_section_ip,uint exception_count)6782 LEX::sp_block_with_exceptions_finalize_exceptions(THD *thd,
6783 uint executable_section_ip,
6784 uint exception_count)
6785 {
6786 if (!exception_count)
6787 {
6788 /*
6789 The jump from the end of DECLARE section to
6790 the beginning of the EXCEPTION section that we added in
6791 sp_block_with_exceptions_finalize_declarations() is useless
6792 if there were no exceptions.
6793 Replace it to "no operation".
6794 */
6795 return sphead->replace_instr_to_nop(thd, executable_section_ip - 1);
6796 }
6797 /*
6798 Generate a jump from the end of the EXCEPTION code
6799 to the executable section.
6800 */
6801 return sphead->add_instr_jump(thd, spcont, executable_section_ip);
6802 }
6803
6804
sp_block_with_exceptions_add_empty(THD * thd)6805 bool LEX::sp_block_with_exceptions_add_empty(THD *thd)
6806 {
6807 uint ip= sphead->instructions();
6808 return sp_block_with_exceptions_finalize_executable_section(thd, ip) ||
6809 sp_block_with_exceptions_finalize_exceptions(thd, ip, 0);
6810 }
6811
6812
sp_change_context(THD * thd,const sp_pcontext * ctx,bool exclusive)6813 bool LEX::sp_change_context(THD *thd, const sp_pcontext *ctx, bool exclusive)
6814 {
6815 uint n;
6816 uint ip= sphead->instructions();
6817 if ((n= spcont->diff_handlers(ctx, exclusive)))
6818 {
6819 sp_instr_hpop *hpop= new (thd->mem_root) sp_instr_hpop(ip++, spcont, n);
6820 if (unlikely(hpop == NULL) || unlikely(sphead->add_instr(hpop)))
6821 return true;
6822 }
6823 if ((n= spcont->diff_cursors(ctx, exclusive)))
6824 {
6825 sp_instr_cpop *cpop= new (thd->mem_root) sp_instr_cpop(ip++, spcont, n);
6826 if (unlikely(cpop == NULL) || unlikely(sphead->add_instr(cpop)))
6827 return true;
6828 }
6829 return false;
6830 }
6831
6832
sp_leave_statement(THD * thd,const LEX_CSTRING * label_name)6833 bool LEX::sp_leave_statement(THD *thd, const LEX_CSTRING *label_name)
6834 {
6835 sp_label *lab= spcont->find_label(label_name);
6836 if (unlikely(!lab))
6837 {
6838 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "LEAVE", label_name->str);
6839 return true;
6840 }
6841 return sp_exit_block(thd, lab, NULL);
6842 }
6843
sp_goto_statement(THD * thd,const LEX_CSTRING * label_name)6844 bool LEX::sp_goto_statement(THD *thd, const LEX_CSTRING *label_name)
6845 {
6846 sp_label *lab= spcont->find_goto_label(label_name);
6847 if (!lab || lab->ip == 0)
6848 {
6849 sp_label *delayedlabel;
6850 if (!lab)
6851 {
6852 // Label not found --> add forward jump to an unknown label
6853 spcont->push_goto_label(thd, label_name, 0, sp_label::GOTO);
6854 delayedlabel= spcont->last_goto_label();
6855 }
6856 else
6857 {
6858 delayedlabel= lab;
6859 }
6860 return sphead->push_backpatch_goto(thd, spcont, delayedlabel);
6861 }
6862 else
6863 {
6864 // Label found (backward goto)
6865 return sp_change_context(thd, lab->ctx, false) ||
6866 sphead->add_instr_jump(thd, spcont, lab->ip); /* Jump back */
6867 }
6868 return false;
6869 }
6870
sp_push_goto_label(THD * thd,const LEX_CSTRING * label_name)6871 bool LEX::sp_push_goto_label(THD *thd, const LEX_CSTRING *label_name)
6872 {
6873 sp_label *lab= spcont->find_goto_label(label_name, false);
6874 if (lab)
6875 {
6876 if (unlikely(lab->ip != 0))
6877 {
6878 my_error(ER_SP_LABEL_REDEFINE, MYF(0), label_name->str);
6879 return true;
6880 }
6881 lab->ip= sphead->instructions();
6882
6883 sp_label *beginblocklabel= spcont->find_label(&empty_clex_str);
6884 sphead->backpatch_goto(thd, lab, beginblocklabel);
6885 }
6886 else
6887 {
6888 spcont->push_goto_label(thd, label_name, sphead->instructions());
6889 }
6890 return false;
6891 }
6892
sp_exit_block(THD * thd,sp_label * lab)6893 bool LEX::sp_exit_block(THD *thd, sp_label *lab)
6894 {
6895 /*
6896 When jumping to a BEGIN-END block end, the target jump
6897 points to the block hpop/cpop cleanup instructions,
6898 so we should exclude the block context here.
6899 When jumping to something else (i.e., SP_LAB_ITER),
6900 there are no hpop/cpop at the jump destination,
6901 so we should include the block context here for cleanup.
6902 */
6903 bool exclusive= (lab->type == sp_label::BEGIN);
6904 return sp_change_context(thd, lab->ctx, exclusive) ||
6905 sphead->add_instr_jump_forward_with_backpatch(thd, spcont, lab);
6906 }
6907
6908
sp_exit_block(THD * thd,sp_label * lab,Item * when)6909 bool LEX::sp_exit_block(THD *thd, sp_label *lab, Item *when)
6910 {
6911 if (!when)
6912 return sp_exit_block(thd, lab);
6913
6914 DBUG_ASSERT(sphead == thd->lex->sphead);
6915 DBUG_ASSERT(spcont == thd->lex->spcont);
6916 sp_instr_jump_if_not *i= new (thd->mem_root)
6917 sp_instr_jump_if_not(sphead->instructions(),
6918 spcont,
6919 when, thd->lex);
6920 if (unlikely(i == NULL) ||
6921 unlikely(sphead->add_instr(i)) ||
6922 unlikely(sp_exit_block(thd, lab)))
6923 return true;
6924 i->backpatch(sphead->instructions(), spcont);
6925 return false;
6926 }
6927
6928
sp_exit_statement(THD * thd,Item * item)6929 bool LEX::sp_exit_statement(THD *thd, Item *item)
6930 {
6931 sp_label *lab= spcont->find_label_current_loop_start();
6932 if (unlikely(!lab))
6933 {
6934 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "EXIT", "");
6935 return true;
6936 }
6937 DBUG_ASSERT(lab->type == sp_label::ITERATION);
6938 return sp_exit_block(thd, lab, item);
6939 }
6940
6941
sp_exit_statement(THD * thd,const LEX_CSTRING * label_name,Item * item)6942 bool LEX::sp_exit_statement(THD *thd, const LEX_CSTRING *label_name, Item *item)
6943 {
6944 sp_label *lab= spcont->find_label(label_name);
6945 if (unlikely(!lab || lab->type != sp_label::ITERATION))
6946 {
6947 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "EXIT", label_name->str);
6948 return true;
6949 }
6950 return sp_exit_block(thd, lab, item);
6951 }
6952
6953
sp_iterate_statement(THD * thd,const LEX_CSTRING * label_name)6954 bool LEX::sp_iterate_statement(THD *thd, const LEX_CSTRING *label_name)
6955 {
6956 sp_label *lab= spcont->find_label(label_name);
6957 if (unlikely(!lab || lab->type != sp_label::ITERATION))
6958 {
6959 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "ITERATE", label_name->str);
6960 return true;
6961 }
6962 return sp_continue_loop(thd, lab);
6963 }
6964
6965
sp_continue_loop(THD * thd,sp_label * lab)6966 bool LEX::sp_continue_loop(THD *thd, sp_label *lab)
6967 {
6968 if (lab->ctx->for_loop().m_index)
6969 {
6970 // We're in a FOR loop, increment the index variable before backward jump
6971 sphead->reset_lex(thd);
6972 DBUG_ASSERT(this != thd->lex);
6973 if (thd->lex->sp_for_loop_increment(thd, lab->ctx->for_loop()) ||
6974 thd->lex->sphead->restore_lex(thd))
6975 return true;
6976 }
6977 return sp_change_context(thd, lab->ctx, false) ||
6978 sphead->add_instr_jump(thd, spcont, lab->ip); /* Jump back */
6979 }
6980
6981
sp_continue_loop(THD * thd,sp_label * lab,Item * when)6982 bool LEX::sp_continue_loop(THD *thd, sp_label *lab, Item *when)
6983 {
6984 if (!when)
6985 return sp_continue_loop(thd, lab);
6986
6987 DBUG_ASSERT(sphead == thd->lex->sphead);
6988 DBUG_ASSERT(spcont == thd->lex->spcont);
6989 sp_instr_jump_if_not *i= new (thd->mem_root)
6990 sp_instr_jump_if_not(sphead->instructions(),
6991 spcont,
6992 when, thd->lex);
6993 if (unlikely(i == NULL) ||
6994 unlikely(sphead->add_instr(i)) ||
6995 unlikely(sp_continue_loop(thd, lab)))
6996 return true;
6997 i->backpatch(sphead->instructions(), spcont);
6998 return false;
6999 }
7000
7001
sp_continue_statement(THD * thd,Item * when)7002 bool LEX::sp_continue_statement(THD *thd, Item *when)
7003 {
7004 sp_label *lab= spcont->find_label_current_loop_start();
7005 if (unlikely(!lab))
7006 {
7007 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "CONTINUE", "");
7008 return true;
7009 }
7010 DBUG_ASSERT(lab->type == sp_label::ITERATION);
7011 return sp_continue_loop(thd, lab, when);
7012 }
7013
7014
sp_continue_statement(THD * thd,const LEX_CSTRING * label_name,Item * when)7015 bool LEX::sp_continue_statement(THD *thd, const LEX_CSTRING *label_name,
7016 Item *when)
7017 {
7018 sp_label *lab= spcont->find_label(label_name);
7019 if (!lab || lab->type != sp_label::ITERATION)
7020 {
7021 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "CONTINUE", label_name->str);
7022 return true;
7023 }
7024 return sp_continue_loop(thd, lab, when);
7025 }
7026
7027
maybe_start_compound_statement(THD * thd)7028 bool LEX::maybe_start_compound_statement(THD *thd)
7029 {
7030 if (!sphead)
7031 {
7032 if (!make_sp_head(thd, NULL, &sp_handler_procedure, DEFAULT_AGGREGATE))
7033 return true;
7034 sphead->set_suid(SP_IS_NOT_SUID);
7035 sphead->set_body_start(thd, thd->m_parser_state->m_lip.get_cpp_ptr());
7036 }
7037 return false;
7038 }
7039
7040
sp_push_loop_label(THD * thd,const LEX_CSTRING * label_name)7041 bool LEX::sp_push_loop_label(THD *thd, const LEX_CSTRING *label_name)
7042 {
7043 sp_label *lab= spcont->find_label(label_name);
7044 if (lab)
7045 {
7046 my_error(ER_SP_LABEL_REDEFINE, MYF(0), label_name->str);
7047 return true;
7048 }
7049 spcont->push_label(thd, label_name, sphead->instructions(),
7050 sp_label::ITERATION);
7051 return false;
7052 }
7053
7054
sp_push_loop_empty_label(THD * thd)7055 bool LEX::sp_push_loop_empty_label(THD *thd)
7056 {
7057 if (maybe_start_compound_statement(thd))
7058 return true;
7059 /* Unlabeled controls get an empty label. */
7060 spcont->push_label(thd, &empty_clex_str, sphead->instructions(),
7061 sp_label::ITERATION);
7062 return false;
7063 }
7064
7065
sp_pop_loop_label(THD * thd,const LEX_CSTRING * label_name)7066 bool LEX::sp_pop_loop_label(THD *thd, const LEX_CSTRING *label_name)
7067 {
7068 sp_label *lab= spcont->pop_label();
7069 sphead->backpatch(lab);
7070 if (label_name->str &&
7071 lex_string_cmp(system_charset_info, label_name,
7072 &lab->name) != 0)
7073 {
7074 my_error(ER_SP_LABEL_MISMATCH, MYF(0), label_name->str);
7075 return true;
7076 }
7077 return false;
7078 }
7079
7080
sp_pop_loop_empty_label(THD * thd)7081 void LEX::sp_pop_loop_empty_label(THD *thd)
7082 {
7083 sp_label *lab= spcont->pop_label();
7084 sphead->backpatch(lab);
7085 DBUG_ASSERT(lab->name.length == 0);
7086 }
7087
7088
sp_while_loop_expression(THD * thd,Item * expr)7089 bool LEX::sp_while_loop_expression(THD *thd, Item *expr)
7090 {
7091 sp_instr_jump_if_not *i= new (thd->mem_root)
7092 sp_instr_jump_if_not(sphead->instructions(), spcont, expr, this);
7093 return (unlikely(i == NULL) ||
7094 /* Jumping forward */
7095 unlikely(sphead->push_backpatch(thd, i, spcont->last_label())) ||
7096 unlikely(sphead->new_cont_backpatch(i)) ||
7097 unlikely(sphead->add_instr(i)));
7098 }
7099
7100
sp_while_loop_finalize(THD * thd)7101 bool LEX::sp_while_loop_finalize(THD *thd)
7102 {
7103 sp_label *lab= spcont->last_label(); /* Jumping back */
7104 sp_instr_jump *i= new (thd->mem_root)
7105 sp_instr_jump(sphead->instructions(), spcont, lab->ip);
7106 if (unlikely(i == NULL) ||
7107 unlikely(sphead->add_instr(i)))
7108 return true;
7109 sphead->do_cont_backpatch();
7110 return false;
7111 }
7112
7113
create_and_link_Item_trigger_field(THD * thd,const LEX_CSTRING * name,bool new_row)7114 Item *LEX::create_and_link_Item_trigger_field(THD *thd,
7115 const LEX_CSTRING *name,
7116 bool new_row)
7117 {
7118 Item_trigger_field *trg_fld;
7119
7120 if (unlikely(trg_chistics.event == TRG_EVENT_INSERT && !new_row))
7121 {
7122 my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "OLD", "on INSERT");
7123 return NULL;
7124 }
7125
7126 if (unlikely(trg_chistics.event == TRG_EVENT_DELETE && new_row))
7127 {
7128 my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "NEW", "on DELETE");
7129 return NULL;
7130 }
7131
7132 DBUG_ASSERT(!new_row ||
7133 (trg_chistics.event == TRG_EVENT_INSERT ||
7134 trg_chistics.event == TRG_EVENT_UPDATE));
7135
7136 const bool tmp_read_only=
7137 !(new_row && trg_chistics.action_time == TRG_ACTION_BEFORE);
7138 trg_fld= new (thd->mem_root)
7139 Item_trigger_field(thd, current_context(),
7140 new_row ?
7141 Item_trigger_field::NEW_ROW:
7142 Item_trigger_field::OLD_ROW,
7143 name, SELECT_ACL, tmp_read_only);
7144 /*
7145 Let us add this item to list of all Item_trigger_field objects
7146 in trigger.
7147 */
7148 if (likely(trg_fld))
7149 trg_table_fields.link_in_list(trg_fld, &trg_fld->next_trg_field);
7150
7151 return trg_fld;
7152 }
7153
7154
make_item_colon_ident_ident(THD * thd,const Lex_ident_cli_st * ca,const Lex_ident_cli_st * cb)7155 Item *LEX::make_item_colon_ident_ident(THD *thd,
7156 const Lex_ident_cli_st *ca,
7157 const Lex_ident_cli_st *cb)
7158 {
7159 Lex_ident_sys a(thd, ca), b(thd, cb);
7160 if (a.is_null() || b.is_null())
7161 return NULL; // OEM
7162 if (!is_trigger_new_or_old_reference(&a))
7163 {
7164 thd->parse_error();
7165 return NULL;
7166 }
7167 bool new_row= (a.str[0] == 'N' || a.str[0] == 'n');
7168 return create_and_link_Item_trigger_field(thd, &b, new_row);
7169 }
7170
7171
make_item_plsql_cursor_attr(THD * thd,const LEX_CSTRING * name,plsql_cursor_attr_t attr)7172 Item *LEX::make_item_plsql_cursor_attr(THD *thd, const LEX_CSTRING *name,
7173 plsql_cursor_attr_t attr)
7174 {
7175 uint offset;
7176 if (unlikely(!spcont || !spcont->find_cursor(name, &offset, false)))
7177 {
7178 my_error(ER_SP_CURSOR_MISMATCH, MYF(0), name->str);
7179 return NULL;
7180 }
7181 switch (attr) {
7182 case PLSQL_CURSOR_ATTR_ISOPEN:
7183 return new (thd->mem_root) Item_func_cursor_isopen(thd, name, offset);
7184 case PLSQL_CURSOR_ATTR_FOUND:
7185 return new (thd->mem_root) Item_func_cursor_found(thd, name, offset);
7186 case PLSQL_CURSOR_ATTR_NOTFOUND:
7187 return new (thd->mem_root) Item_func_cursor_notfound(thd, name, offset);
7188 case PLSQL_CURSOR_ATTR_ROWCOUNT:
7189 return new (thd->mem_root) Item_func_cursor_rowcount(thd, name, offset);
7190 }
7191 DBUG_ASSERT(0);
7192 return NULL;
7193 }
7194
7195
make_item_sysvar(THD * thd,enum_var_type type,const LEX_CSTRING * name,const LEX_CSTRING * component)7196 Item *LEX::make_item_sysvar(THD *thd,
7197 enum_var_type type,
7198 const LEX_CSTRING *name,
7199 const LEX_CSTRING *component)
7200
7201 {
7202 Item *item;
7203 DBUG_ASSERT(name->str);
7204 /*
7205 "SELECT @@global.global.variable" is not allowed
7206 Note, "global" can come through TEXT_STRING_sys.
7207 */
7208 if (component->str && unlikely(check_reserved_words(name)))
7209 {
7210 thd->parse_error();
7211 return NULL;
7212 }
7213 if (unlikely(!(item= get_system_var(thd, type, name, component))))
7214 return NULL;
7215 if (!((Item_func_get_system_var*) item)->is_written_to_binlog())
7216 set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE);
7217 return item;
7218 }
7219
7220
param_push_or_clone(THD * thd,LEX * lex,Item_param * item)7221 static bool param_push_or_clone(THD *thd, LEX *lex, Item_param *item)
7222 {
7223 return !lex->clone_spec_offset ?
7224 lex->param_list.push_back(item, thd->mem_root) :
7225 item->add_as_clone(thd);
7226 }
7227
7228
add_placeholder(THD * thd,const LEX_CSTRING * name,const char * start,const char * end)7229 Item_param *LEX::add_placeholder(THD *thd, const LEX_CSTRING *name,
7230 const char *start, const char *end)
7231 {
7232 if (unlikely(!thd->m_parser_state->m_lip.stmt_prepare_mode))
7233 {
7234 thd->parse_error(ER_SYNTAX_ERROR, start);
7235 return NULL;
7236 }
7237 if (unlikely(!parsing_options.allows_variable))
7238 {
7239 my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
7240 return NULL;
7241 }
7242 Query_fragment pos(thd, sphead, start, end);
7243 Item_param *item= new (thd->mem_root) Item_param(thd, name,
7244 pos.pos(), pos.length());
7245 if (unlikely(!item) || unlikely(param_push_or_clone(thd, this, item)))
7246 {
7247 my_error(ER_OUT_OF_RESOURCES, MYF(0));
7248 return NULL;
7249 }
7250 return item;
7251 }
7252
7253
add_signal_statement(THD * thd,const sp_condition_value * v)7254 bool LEX::add_signal_statement(THD *thd, const sp_condition_value *v)
7255 {
7256 Yacc_state *state= &thd->m_parser_state->m_yacc;
7257 sql_command= SQLCOM_SIGNAL;
7258 m_sql_cmd= new (thd->mem_root) Sql_cmd_signal(v, state->m_set_signal_info);
7259 return m_sql_cmd == NULL;
7260 }
7261
7262
add_resignal_statement(THD * thd,const sp_condition_value * v)7263 bool LEX::add_resignal_statement(THD *thd, const sp_condition_value *v)
7264 {
7265 Yacc_state *state= &thd->m_parser_state->m_yacc;
7266 sql_command= SQLCOM_RESIGNAL;
7267 m_sql_cmd= new (thd->mem_root) Sql_cmd_resignal(v, state->m_set_signal_info);
7268 return m_sql_cmd == NULL;
7269 }
7270
7271
7272 /*
7273 Make an Item when an identifier is found in the FOR loop bounds:
7274 FOR rec IN cursor
7275 FOR var IN var1 .. xxx
7276 FOR var IN row1.field1 .. xxx
7277 When we parse the first expression after the "IN" keyword,
7278 we don't know yet if it's a cursor name, or a scalar SP variable name,
7279 or a field of a ROW SP variable. Here we create Item_field to remember
7280 the fully qualified name. Later sp_for_loop_cursor_declarations()
7281 detects how to treat this name properly.
7282 */
create_item_for_loop_bound(THD * thd,const LEX_CSTRING * a,const LEX_CSTRING * b,const LEX_CSTRING * c)7283 Item *LEX::create_item_for_loop_bound(THD *thd,
7284 const LEX_CSTRING *a,
7285 const LEX_CSTRING *b,
7286 const LEX_CSTRING *c)
7287 {
7288 /*
7289 Pass NULL as the name resolution context.
7290 This is OK, fix_fields() won't be called for this Item_field.
7291 */
7292 return new (thd->mem_root) Item_field(thd, NULL, a->str, b->str, c);
7293 }
7294
7295
check_expr_allows_fields_or_error(THD * thd,const char * name) const7296 bool LEX::check_expr_allows_fields_or_error(THD *thd, const char *name) const
7297 {
7298 if (select_stack_top > 0)
7299 return false; // OK, fields are allowed
7300 my_error(ER_BAD_FIELD_ERROR, MYF(0), name, thd->where);
7301 return true; // Error, fields are not allowed
7302 }
7303
create_item_ident_nospvar(THD * thd,const Lex_ident_sys_st * a,const Lex_ident_sys_st * b)7304 Item *LEX::create_item_ident_nospvar(THD *thd,
7305 const Lex_ident_sys_st *a,
7306 const Lex_ident_sys_st *b)
7307 {
7308 DBUG_ASSERT(this == thd->lex);
7309 /*
7310 FIXME This will work ok in simple_ident_nospvar case because
7311 we can't meet simple_ident_nospvar in trigger now. But it
7312 should be changed in future.
7313 */
7314 if (is_trigger_new_or_old_reference(a))
7315 {
7316 bool new_row= (a->str[0]=='N' || a->str[0]=='n');
7317
7318 return create_and_link_Item_trigger_field(thd, b, new_row);
7319 }
7320
7321 if (unlikely(current_select->no_table_names_allowed))
7322 {
7323 my_error(ER_TABLENAME_NOT_ALLOWED_HERE, MYF(0), a->str, thd->where);
7324 return NULL;
7325 }
7326
7327 if (current_select->parsing_place == FOR_LOOP_BOUND)
7328 return create_item_for_loop_bound(thd, &null_clex_str, a, b);
7329
7330 return create_item_ident_field(thd, NullS, a->str, b);
7331 }
7332
7333
create_item_spvar_row_field(THD * thd,const Sp_rcontext_handler * rh,const Lex_ident_sys * a,const Lex_ident_sys * b,sp_variable * spv,const char * start,const char * end)7334 Item_splocal *LEX::create_item_spvar_row_field(THD *thd,
7335 const Sp_rcontext_handler *rh,
7336 const Lex_ident_sys *a,
7337 const Lex_ident_sys *b,
7338 sp_variable *spv,
7339 const char *start,
7340 const char *end)
7341 {
7342 if (unlikely(!parsing_options.allows_variable))
7343 {
7344 my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
7345 return NULL;
7346 }
7347
7348 Query_fragment pos(thd, sphead, start, end);
7349 Item_splocal *item;
7350 if (spv->field_def.is_table_rowtype_ref() ||
7351 spv->field_def.is_cursor_rowtype_ref())
7352 {
7353 if (unlikely(!(item= new (thd->mem_root)
7354 Item_splocal_row_field_by_name(thd, rh, a, b, spv->offset,
7355 &type_handler_null,
7356 pos.pos(), pos.length()))))
7357 return NULL;
7358 }
7359 else
7360 {
7361 uint row_field_offset;
7362 const Spvar_definition *def;
7363 if (unlikely(!(def= spv->find_row_field(a, b, &row_field_offset))))
7364 return NULL;
7365
7366 if (unlikely(!(item= new (thd->mem_root)
7367 Item_splocal_row_field(thd, rh, a, b,
7368 spv->offset, row_field_offset,
7369 def->type_handler(),
7370 pos.pos(), pos.length()))))
7371 return NULL;
7372 }
7373 #ifdef DBUG_ASSERT_EXISTS
7374 item->m_sp= sphead;
7375 #endif
7376 safe_to_cache_query=0;
7377 return item;
7378 }
7379
7380
create_outvar(THD * thd,const LEX_CSTRING * name)7381 my_var *LEX::create_outvar(THD *thd, const LEX_CSTRING *name)
7382 {
7383 const Sp_rcontext_handler *rh;
7384 sp_variable *spv;
7385 if (likely((spv= find_variable(name, &rh))))
7386 return result ? new (thd->mem_root)
7387 my_var_sp(rh, name, spv->offset,
7388 spv->type_handler(), sphead) :
7389 NULL /* EXPLAIN */;
7390 my_error(ER_SP_UNDECLARED_VAR, MYF(0), name->str);
7391 return NULL;
7392 }
7393
7394
create_outvar(THD * thd,const LEX_CSTRING * a,const LEX_CSTRING * b)7395 my_var *LEX::create_outvar(THD *thd,
7396 const LEX_CSTRING *a,
7397 const LEX_CSTRING *b)
7398 {
7399 const Sp_rcontext_handler *rh;
7400 sp_variable *t;
7401 if (unlikely(!(t= find_variable(a, &rh))))
7402 {
7403 my_error(ER_SP_UNDECLARED_VAR, MYF(0), a->str);
7404 return NULL;
7405 }
7406 uint row_field_offset;
7407 if (!t->find_row_field(a, b, &row_field_offset))
7408 return NULL;
7409 return result ?
7410 new (thd->mem_root) my_var_sp_row_field(rh, a, b, t->offset,
7411 row_field_offset, sphead) :
7412 NULL /* EXPLAIN */;
7413 }
7414
7415
create_item_func_nextval(THD * thd,Table_ident * table_ident)7416 Item *LEX::create_item_func_nextval(THD *thd, Table_ident *table_ident)
7417 {
7418 TABLE_LIST *table;
7419 if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
7420 TL_OPTION_SEQUENCE,
7421 TL_WRITE_ALLOW_WRITE,
7422 MDL_SHARED_WRITE))))
7423 return NULL;
7424 thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
7425 return new (thd->mem_root) Item_func_nextval(thd, table);
7426 }
7427
7428
create_item_func_lastval(THD * thd,Table_ident * table_ident)7429 Item *LEX::create_item_func_lastval(THD *thd, Table_ident *table_ident)
7430 {
7431 TABLE_LIST *table;
7432 if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
7433 TL_OPTION_SEQUENCE,
7434 TL_READ,
7435 MDL_SHARED_READ))))
7436 return NULL;
7437 thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
7438 return new (thd->mem_root) Item_func_lastval(thd, table);
7439 }
7440
7441
create_item_func_nextval(THD * thd,const LEX_CSTRING * db,const LEX_CSTRING * name)7442 Item *LEX::create_item_func_nextval(THD *thd,
7443 const LEX_CSTRING *db,
7444 const LEX_CSTRING *name)
7445 {
7446 Table_ident *table_ident;
7447 if (unlikely(!(table_ident=
7448 new (thd->mem_root) Table_ident(thd, db, name, false))))
7449 return NULL;
7450 return create_item_func_nextval(thd, table_ident);
7451 }
7452
7453
create_item_func_lastval(THD * thd,const LEX_CSTRING * db,const LEX_CSTRING * name)7454 Item *LEX::create_item_func_lastval(THD *thd,
7455 const LEX_CSTRING *db,
7456 const LEX_CSTRING *name)
7457 {
7458 Table_ident *table_ident;
7459 if (unlikely(!(table_ident=
7460 new (thd->mem_root) Table_ident(thd, db, name, false))))
7461 return NULL;
7462 return create_item_func_lastval(thd, table_ident);
7463 }
7464
7465
create_item_func_setval(THD * thd,Table_ident * table_ident,longlong nextval,ulonglong round,bool is_used)7466 Item *LEX::create_item_func_setval(THD *thd, Table_ident *table_ident,
7467 longlong nextval, ulonglong round,
7468 bool is_used)
7469 {
7470 TABLE_LIST *table;
7471 if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
7472 TL_OPTION_SEQUENCE,
7473 TL_WRITE_ALLOW_WRITE,
7474 MDL_SHARED_WRITE))))
7475 return NULL;
7476 return new (thd->mem_root) Item_func_setval(thd, table, nextval, round,
7477 is_used);
7478 }
7479
7480
create_item_ident(THD * thd,const Lex_ident_cli_st * ca,const Lex_ident_cli_st * cb)7481 Item *LEX::create_item_ident(THD *thd,
7482 const Lex_ident_cli_st *ca,
7483 const Lex_ident_cli_st *cb)
7484 {
7485 const char *start= ca->pos();
7486 const char *end= cb->end();
7487 const Sp_rcontext_handler *rh;
7488 sp_variable *spv;
7489 DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= start);
7490 DBUG_ASSERT(start <= end);
7491 DBUG_ASSERT(end <= thd->m_parser_state->m_lip.get_end_of_query());
7492 Lex_ident_sys a(thd, ca), b(thd, cb);
7493 if (a.is_null() || b.is_null())
7494 return NULL; // OEM
7495 if ((spv= find_variable(&a, &rh)) &&
7496 (spv->field_def.is_row() ||
7497 spv->field_def.is_table_rowtype_ref() ||
7498 spv->field_def.is_cursor_rowtype_ref()))
7499 return create_item_spvar_row_field(thd, rh, &a, &b, spv, start, end);
7500
7501 if ((thd->variables.sql_mode & MODE_ORACLE) && b.length == 7)
7502 {
7503 if (!my_strnncoll(system_charset_info,
7504 (const uchar *) b.str, 7,
7505 (const uchar *) "NEXTVAL", 7))
7506 return create_item_func_nextval(thd, &null_clex_str, &a);
7507 else if (!my_strnncoll(system_charset_info,
7508 (const uchar *) b.str, 7,
7509 (const uchar *) "CURRVAL", 7))
7510 return create_item_func_lastval(thd, &null_clex_str, &a);
7511 }
7512
7513 return create_item_ident_nospvar(thd, &a, &b);
7514 }
7515
7516
create_item_ident(THD * thd,const Lex_ident_sys_st * a,const Lex_ident_sys_st * b,const Lex_ident_sys_st * c)7517 Item *LEX::create_item_ident(THD *thd,
7518 const Lex_ident_sys_st *a,
7519 const Lex_ident_sys_st *b,
7520 const Lex_ident_sys_st *c)
7521 {
7522 const char *schema= (thd->client_capabilities & CLIENT_NO_SCHEMA ?
7523 NullS : a->str);
7524
7525 if ((thd->variables.sql_mode & MODE_ORACLE) && c->length == 7)
7526 {
7527 if (!my_strnncoll(system_charset_info,
7528 (const uchar *) c->str, 7,
7529 (const uchar *) "NEXTVAL", 7))
7530 return create_item_func_nextval(thd, a, b);
7531 else if (!my_strnncoll(system_charset_info,
7532 (const uchar *) c->str, 7,
7533 (const uchar *) "CURRVAL", 7))
7534 return create_item_func_lastval(thd, a, b);
7535 }
7536
7537 if (current_select->no_table_names_allowed)
7538 {
7539 my_error(ER_TABLENAME_NOT_ALLOWED_HERE, MYF(0), b->str, thd->where);
7540 return NULL;
7541 }
7542
7543 if (current_select->parsing_place == FOR_LOOP_BOUND)
7544 return create_item_for_loop_bound(thd, &null_clex_str, b, c);
7545
7546 return create_item_ident_field(thd, schema, b->str, c);
7547 }
7548
7549
create_item_limit(THD * thd,const Lex_ident_cli_st * ca)7550 Item *LEX::create_item_limit(THD *thd, const Lex_ident_cli_st *ca)
7551 {
7552 DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= ca->pos());
7553 DBUG_ASSERT(ca->pos() <= ca->end());
7554 DBUG_ASSERT(ca->end() <= thd->m_parser_state->m_lip.get_end_of_query());
7555
7556 const Sp_rcontext_handler *rh;
7557 sp_variable *spv;
7558 Lex_ident_sys sa(thd, ca);
7559 if (sa.is_null())
7560 return NULL; // EOM
7561 if (!(spv= find_variable(&sa, &rh)))
7562 {
7563 my_error(ER_SP_UNDECLARED_VAR, MYF(0), sa.str);
7564 return NULL;
7565 }
7566
7567 Query_fragment pos(thd, sphead, ca->pos(), ca->end());
7568 Item_splocal *item;
7569 if (unlikely(!(item= new (thd->mem_root)
7570 Item_splocal(thd, rh, &sa,
7571 spv->offset, spv->type_handler(),
7572 clone_spec_offset ? 0 : pos.pos(),
7573 clone_spec_offset ? 0 : pos.length()))))
7574 return NULL;
7575 #ifdef DBUG_ASSERT_EXISTS
7576 item->m_sp= sphead;
7577 #endif
7578 safe_to_cache_query= 0;
7579
7580 if (!item->is_valid_limit_clause_variable_with_error())
7581 return NULL;
7582
7583 item->limit_clause_param= true;
7584 return item;
7585 }
7586
7587
create_item_limit(THD * thd,const Lex_ident_cli_st * ca,const Lex_ident_cli_st * cb)7588 Item *LEX::create_item_limit(THD *thd,
7589 const Lex_ident_cli_st *ca,
7590 const Lex_ident_cli_st *cb)
7591 {
7592 DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= ca->pos());
7593 DBUG_ASSERT(ca->pos() <= cb->end());
7594 DBUG_ASSERT(cb->end() <= thd->m_parser_state->m_lip.get_end_of_query());
7595
7596 const Sp_rcontext_handler *rh;
7597 sp_variable *spv;
7598 Lex_ident_sys sa(thd, ca), sb(thd, cb);
7599 if (unlikely(sa.is_null() || sb.is_null()))
7600 return NULL; // EOM
7601 if (!(spv= find_variable(&sa, &rh)))
7602 {
7603 my_error(ER_SP_UNDECLARED_VAR, MYF(0), sa.str);
7604 return NULL;
7605 }
7606 // Qualified %TYPE variables are not possible
7607 DBUG_ASSERT(!spv->field_def.column_type_ref());
7608 Item_splocal *item;
7609 if (unlikely(!(item= create_item_spvar_row_field(thd, rh, &sa, &sb, spv,
7610 ca->pos(), cb->end()))))
7611 return NULL;
7612 if (!item->is_valid_limit_clause_variable_with_error())
7613 return NULL;
7614 item->limit_clause_param= true;
7615 return item;
7616 }
7617
7618
set_user_variable(THD * thd,const LEX_CSTRING * name,Item * val)7619 bool LEX::set_user_variable(THD *thd, const LEX_CSTRING *name, Item *val)
7620 {
7621 Item_func_set_user_var *item;
7622 set_var_user *var;
7623 if (unlikely(!(item= new (thd->mem_root) Item_func_set_user_var(thd, name,
7624 val))) ||
7625 unlikely(!(var= new (thd->mem_root) set_var_user(item))))
7626 return true;
7627 if (unlikely(var_list.push_back(var, thd->mem_root)))
7628 return true;
7629 return false;
7630 }
7631
7632
create_item_ident_field(THD * thd,const char * db,const char * table,const Lex_ident_sys_st * name)7633 Item *LEX::create_item_ident_field(THD *thd, const char *db,
7634 const char *table,
7635 const Lex_ident_sys_st *name)
7636 {
7637 if (check_expr_allows_fields_or_error(thd, name->str))
7638 return NULL;
7639
7640 if (current_select->parsing_place != IN_HAVING ||
7641 current_select->get_in_sum_expr() > 0)
7642 return new (thd->mem_root) Item_field(thd, current_context(),
7643 db, table, name);
7644
7645 return new (thd->mem_root) Item_ref(thd, current_context(),
7646 db, table, name);
7647 }
7648
7649
create_item_ident_sp(THD * thd,Lex_ident_sys_st * name,const char * start,const char * end)7650 Item *LEX::create_item_ident_sp(THD *thd, Lex_ident_sys_st *name,
7651 const char *start,
7652 const char *end)
7653 {
7654 DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= start);
7655 DBUG_ASSERT(start <= end);
7656 DBUG_ASSERT(end <= thd->m_parser_state->m_lip.get_end_of_query());
7657
7658 const Sp_rcontext_handler *rh;
7659 sp_variable *spv;
7660 uint unused_off;
7661 DBUG_ASSERT(spcont);
7662 DBUG_ASSERT(sphead);
7663 if ((spv= find_variable(name, &rh)))
7664 {
7665 /* We're compiling a stored procedure and found a variable */
7666 if (!parsing_options.allows_variable)
7667 {
7668 my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
7669 return NULL;
7670 }
7671
7672 Query_fragment pos(thd, sphead, start, end);
7673 uint f_pos= clone_spec_offset ? 0 : pos.pos();
7674 uint f_length= clone_spec_offset ? 0 : pos.length();
7675 Item_splocal *splocal= spv->field_def.is_column_type_ref() ?
7676 new (thd->mem_root) Item_splocal_with_delayed_data_type(thd, rh, name,
7677 spv->offset,
7678 f_pos, f_length) :
7679 new (thd->mem_root) Item_splocal(thd, rh, name,
7680 spv->offset, spv->type_handler(),
7681 f_pos, f_length);
7682 if (unlikely(splocal == NULL))
7683 return NULL;
7684 #ifdef DBUG_ASSERT_EXISTS
7685 splocal->m_sp= sphead;
7686 #endif
7687 safe_to_cache_query= 0;
7688 return splocal;
7689 }
7690
7691 if (thd->variables.sql_mode & MODE_ORACLE)
7692 {
7693 if (lex_string_eq(name, STRING_WITH_LEN("SQLCODE")))
7694 return new (thd->mem_root) Item_func_sqlcode(thd);
7695 if (lex_string_eq(name, STRING_WITH_LEN("SQLERRM")))
7696 return new (thd->mem_root) Item_func_sqlerrm(thd);
7697 }
7698
7699 if (fields_are_impossible() &&
7700 (current_select->parsing_place != FOR_LOOP_BOUND ||
7701 spcont->find_cursor(name, &unused_off, false) == NULL))
7702 {
7703 // we are out of SELECT or FOR so it is syntax error
7704 my_error(ER_SP_UNDECLARED_VAR, MYF(0), name->str);
7705 return NULL;
7706 }
7707
7708 if (current_select->parsing_place == FOR_LOOP_BOUND)
7709 return create_item_for_loop_bound(thd, &null_clex_str, &null_clex_str,
7710 name);
7711
7712 return create_item_ident_nosp(thd, name);
7713 }
7714
7715
7716
set_variable(const LEX_CSTRING * name,Item * item)7717 bool LEX::set_variable(const LEX_CSTRING *name, Item *item)
7718 {
7719 sp_pcontext *ctx;
7720 const Sp_rcontext_handler *rh;
7721 sp_variable *spv= find_variable(name, &ctx, &rh);
7722 return spv ? sphead->set_local_variable(thd, ctx, rh, spv, item, this, true) :
7723 set_system_variable(option_type, name, item);
7724 }
7725
7726
7727 /**
7728 Generate instructions for:
7729 SET x.y= expr;
7730 */
set_variable(const LEX_CSTRING * name1,const LEX_CSTRING * name2,Item * item)7731 bool LEX::set_variable(const LEX_CSTRING *name1,
7732 const LEX_CSTRING *name2,
7733 Item *item)
7734 {
7735 const Sp_rcontext_handler *rh;
7736 sp_pcontext *ctx;
7737 sp_variable *spv;
7738 if (spcont && (spv= find_variable(name1, &ctx, &rh)))
7739 {
7740 if (spv->field_def.is_table_rowtype_ref() ||
7741 spv->field_def.is_cursor_rowtype_ref())
7742 return sphead->set_local_variable_row_field_by_name(thd, ctx,
7743 rh,
7744 spv, name2,
7745 item, this);
7746 // A field of a ROW variable
7747 uint row_field_offset;
7748 return !spv->find_row_field(name1, name2, &row_field_offset) ||
7749 sphead->set_local_variable_row_field(thd, ctx, rh,
7750 spv, row_field_offset,
7751 item, this);
7752 }
7753
7754 if (is_trigger_new_or_old_reference(name1))
7755 return set_trigger_field(name1, name2, item);
7756
7757 return set_system_variable(thd, option_type, name1, name2, item);
7758 }
7759
7760
set_default_system_variable(enum_var_type var_type,const LEX_CSTRING * name,Item * val)7761 bool LEX::set_default_system_variable(enum_var_type var_type,
7762 const LEX_CSTRING *name,
7763 Item *val)
7764 {
7765 static LEX_CSTRING default_base_name= {STRING_WITH_LEN("default")};
7766 sys_var *var= find_sys_var(thd, name->str, name->length);
7767 if (!var)
7768 return true;
7769 if (unlikely(!var->is_struct()))
7770 {
7771 my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), name->str);
7772 return true;
7773 }
7774 return set_system_variable(var_type, var, &default_base_name, val);
7775 }
7776
7777
set_system_variable(enum_var_type var_type,const LEX_CSTRING * name,Item * val)7778 bool LEX::set_system_variable(enum_var_type var_type,
7779 const LEX_CSTRING *name,
7780 Item *val)
7781 {
7782 sys_var *var= find_sys_var(thd, name->str, name->length);
7783 DBUG_ASSERT(thd->is_error() || var != NULL);
7784 return likely(var) ? set_system_variable(var_type, var, &null_clex_str, val) : true;
7785 }
7786
7787
set_system_variable(THD * thd,enum_var_type var_type,const LEX_CSTRING * name1,const LEX_CSTRING * name2,Item * val)7788 bool LEX::set_system_variable(THD *thd, enum_var_type var_type,
7789 const LEX_CSTRING *name1,
7790 const LEX_CSTRING *name2,
7791 Item *val)
7792 {
7793 sys_var *tmp;
7794 if (unlikely(check_reserved_words(name1)) ||
7795 unlikely(!(tmp= find_sys_var(thd, name2->str, name2->length, true))))
7796 {
7797 my_error(ER_UNKNOWN_STRUCTURED_VARIABLE, MYF(0),
7798 (int) name1->length, name1->str);
7799 return true;
7800 }
7801 if (unlikely(!tmp->is_struct()))
7802 {
7803 my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), name2->str);
7804 return true;
7805 }
7806 return set_system_variable(var_type, tmp, name1, val);
7807 }
7808
7809
set_trigger_field(const LEX_CSTRING * name1,const LEX_CSTRING * name2,Item * val)7810 bool LEX::set_trigger_field(const LEX_CSTRING *name1, const LEX_CSTRING *name2,
7811 Item *val)
7812 {
7813 DBUG_ASSERT(is_trigger_new_or_old_reference(name1));
7814 if (unlikely(name1->str[0]=='O' || name1->str[0]=='o'))
7815 {
7816 my_error(ER_TRG_CANT_CHANGE_ROW, MYF(0), "OLD", "");
7817 return true;
7818 }
7819 if (unlikely(trg_chistics.event == TRG_EVENT_DELETE))
7820 {
7821 my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "NEW", "on DELETE");
7822 return true;
7823 }
7824 if (unlikely(trg_chistics.action_time == TRG_ACTION_AFTER))
7825 {
7826 my_error(ER_TRG_CANT_CHANGE_ROW, MYF(0), "NEW", "after ");
7827 return true;
7828 }
7829 return set_trigger_new_row(name2, val);
7830 }
7831
7832
7833 #ifdef MYSQL_SERVER
7834 uint binlog_unsafe_map[256];
7835
7836 #define UNSAFE(a, b, c) \
7837 { \
7838 DBUG_PRINT("unsafe_mixed_statement", ("SETTING BASE VALUES: %s, %s, %02X", \
7839 LEX::stmt_accessed_table_string(a), \
7840 LEX::stmt_accessed_table_string(b), \
7841 c)); \
7842 unsafe_mixed_statement(a, b, c); \
7843 }
7844
7845 /*
7846 Sets the combination given by "a" and "b" and automatically combinations
7847 given by other types of access, i.e. 2^(8 - 2), as unsafe.
7848
7849 It may happen a colision when automatically defining a combination as unsafe.
7850 For that reason, a combination has its unsafe condition redefined only when
7851 the new_condition is greater then the old. For instance,
7852
7853 . (BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY) is never overwritten by
7854 . (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF).
7855 */
unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,LEX::enum_stmt_accessed_table b,uint condition)7856 void unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,
7857 LEX::enum_stmt_accessed_table b, uint condition)
7858 {
7859 int type= 0;
7860 int index= (1U << a) | (1U << b);
7861
7862
7863 for (type= 0; type < 256; type++)
7864 {
7865 if ((type & index) == index)
7866 {
7867 binlog_unsafe_map[type] |= condition;
7868 }
7869 }
7870 }
7871 /*
7872 The BINLOG_* AND TRX_CACHE_* values can be combined by using '&' or '|',
7873 which means that both conditions need to be satisfied or any of them is
7874 enough. For example,
7875
7876 . BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY means that the statment is
7877 unsafe when the option is on and trx-cache is not empty;
7878
7879 . BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF means the statement is unsafe
7880 in all cases.
7881
7882 . TRX_CACHE_EMPTY | TRX_CACHE_NOT_EMPTY means the statement is unsafe
7883 in all cases. Similar as above.
7884 */
binlog_unsafe_map_init()7885 void binlog_unsafe_map_init()
7886 {
7887 memset((void*) binlog_unsafe_map, 0, sizeof(uint) * 256);
7888
7889 /*
7890 Classify a statement as unsafe when there is a mixed statement and an
7891 on-going transaction at any point of the execution if:
7892
7893 1. The mixed statement is about to update a transactional table and
7894 a non-transactional table.
7895
7896 2. The mixed statement is about to update a transactional table and
7897 read from a non-transactional table.
7898
7899 3. The mixed statement is about to update a non-transactional table
7900 and temporary transactional table.
7901
7902 4. The mixed statement is about to update a temporary transactional
7903 table and read from a non-transactional table.
7904
7905 5. The mixed statement is about to update a transactional table and
7906 a temporary non-transactional table.
7907
7908 6. The mixed statement is about to update a transactional table and
7909 read from a temporary non-transactional table.
7910
7911 7. The mixed statement is about to update a temporary transactional
7912 table and temporary non-transactional table.
7913
7914 8. The mixed statement is about to update a temporary transactional
7915 table and read from a temporary non-transactional table.
7916
7917 After updating a transactional table if:
7918
7919 9. The mixed statement is about to update a non-transactional table
7920 and read from a transactional table.
7921
7922 10. The mixed statement is about to update a non-transactional table
7923 and read from a temporary transactional table.
7924
7925 11. The mixed statement is about to update a temporary non-transactional
7926 table and read from a transactional table.
7927
7928 12. The mixed statement is about to update a temporary non-transactional
7929 table and read from a temporary transactional table.
7930
7931 13. The mixed statement is about to update a temporary non-transactional
7932 table and read from a non-transactional table.
7933
7934 The reason for this is that locks acquired may not protected a concurrent
7935 transaction of interfering in the current execution and by consequence in
7936 the result.
7937 */
7938 /* Case 1. */
7939 UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_NON_TRANS_TABLE,
7940 BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
7941 /* Case 2. */
7942 UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
7943 BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
7944 /* Case 3. */
7945 UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_WRITES_TEMP_TRANS_TABLE,
7946 BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
7947 /* Case 4. */
7948 UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
7949 BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
7950 /* Case 5. */
7951 UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
7952 BINLOG_DIRECT_ON);
7953 /* Case 6. */
7954 UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
7955 BINLOG_DIRECT_ON);
7956 /* Case 7. */
7957 UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
7958 BINLOG_DIRECT_ON);
7959 /* Case 8. */
7960 UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
7961 BINLOG_DIRECT_ON);
7962 /* Case 9. */
7963 UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
7964 (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
7965 /* Case 10 */
7966 UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
7967 (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
7968 /* Case 11. */
7969 UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
7970 BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
7971 /* Case 12. */
7972 UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
7973 BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
7974 /* Case 13. */
7975 UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
7976 BINLOG_DIRECT_OFF & TRX_CACHE_NOT_EMPTY);
7977 }
7978 #endif
7979
7980
7981 /**
7982 @brief
7983 Collect fiels that are used in the GROUP BY of this st_select_lex
7984
7985 @param thd The thread handle
7986
7987 @details
7988 This method looks through the fields that are used in the GROUP BY of this
7989 st_select_lex and saves info on these fields.
7990 */
7991
collect_grouping_fields_for_derived(THD * thd,ORDER * grouping_list)7992 void st_select_lex::collect_grouping_fields_for_derived(THD *thd,
7993 ORDER *grouping_list)
7994 {
7995 grouping_tmp_fields.empty();
7996 List_iterator<Item> li(join->fields_list);
7997 Item *item= li++;
7998 for (uint i= 0; i < master_unit()->derived->table->s->fields;
7999 i++, (item=li++))
8000 {
8001 for (ORDER *ord= grouping_list; ord; ord= ord->next)
8002 {
8003 if ((*ord->item)->eq((Item*)item, 0))
8004 {
8005 Field_pair *grouping_tmp_field=
8006 new Field_pair(master_unit()->derived->table->field[i], item);
8007 grouping_tmp_fields.push_back(grouping_tmp_field);
8008 }
8009 }
8010 }
8011 }
8012
8013
8014 /**
8015 Collect fields that are used in the GROUP BY of this SELECT
8016 */
8017
collect_grouping_fields(THD * thd)8018 bool st_select_lex::collect_grouping_fields(THD *thd)
8019 {
8020 grouping_tmp_fields.empty();
8021
8022 for (ORDER *ord= group_list.first; ord; ord= ord->next)
8023 {
8024 Item *item= *ord->item;
8025 if (item->type() != Item::FIELD_ITEM &&
8026 !(item->type() == Item::REF_ITEM &&
8027 item->real_type() == Item::FIELD_ITEM &&
8028 ((((Item_ref *) item)->ref_type() == Item_ref::VIEW_REF) ||
8029 (((Item_ref *) item)->ref_type() == Item_ref::REF))))
8030 continue;
8031
8032 Field_pair *grouping_tmp_field=
8033 new Field_pair(((Item_field *)item->real_item())->field, item);
8034 if (grouping_tmp_fields.push_back(grouping_tmp_field, thd->mem_root))
8035 return false;
8036 }
8037 if (grouping_tmp_fields.elements)
8038 return false;
8039 return true;
8040 }
8041
8042
8043 /**
8044 @brief
8045 For a condition check possibility of exraction a formula over grouping fields
8046
8047 @param thd The thread handle
8048 @param cond The condition whose subformulas are to be analyzed
8049 @param checker The checker callback function to be applied to the nodes
8050 of the tree of the object
8051
8052 @details
8053 This method traverses the AND-OR condition cond and for each subformula of
8054 the condition it checks whether it can be usable for the extraction of a
8055 condition over the grouping fields of this select. The method uses
8056 the call-back parameter checker to check whether a primary formula
8057 depends only on grouping fields.
8058 The subformulas that are not usable are marked with the flag NO_EXTRACTION_FL.
8059 The subformulas that can be entierly extracted are marked with the flag
8060 FULL_EXTRACTION_FL.
8061 @note
8062 This method is called before any call of extract_cond_for_grouping_fields.
8063 The flag NO_EXTRACTION_FL set in a subformula allows to avoid building clone
8064 for the subformula when extracting the pushable condition.
8065 The flag FULL_EXTRACTION_FL allows to delete later all top level conjuncts
8066 from cond.
8067 */
8068
8069 void
check_cond_extraction_for_grouping_fields(THD * thd,Item * cond)8070 st_select_lex::check_cond_extraction_for_grouping_fields(THD *thd, Item *cond)
8071 {
8072 if (cond->get_extraction_flag() == NO_EXTRACTION_FL)
8073 return;
8074 cond->clear_extraction_flag();
8075 if (cond->type() == Item::COND_ITEM)
8076 {
8077 Item_cond_and *and_cond=
8078 (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC) ?
8079 ((Item_cond_and*) cond) : 0;
8080
8081 List<Item> *arg_list= ((Item_cond*) cond)->argument_list();
8082 List_iterator<Item> li(*arg_list);
8083 uint count= 0; // to count items not containing NO_EXTRACTION_FL
8084 uint count_full= 0; // to count items with FULL_EXTRACTION_FL
8085 Item *item;
8086 while ((item=li++))
8087 {
8088 check_cond_extraction_for_grouping_fields(thd, item);
8089 if (item->get_extraction_flag() != NO_EXTRACTION_FL)
8090 {
8091 count++;
8092 if (item->get_extraction_flag() == FULL_EXTRACTION_FL)
8093 count_full++;
8094 }
8095 else if (!and_cond)
8096 break;
8097 }
8098 if ((and_cond && count == 0) || item)
8099 cond->set_extraction_flag(NO_EXTRACTION_FL);
8100 if (count_full == arg_list->elements)
8101 {
8102 cond->set_extraction_flag(FULL_EXTRACTION_FL);
8103 }
8104 if (cond->get_extraction_flag() != 0)
8105 {
8106 li.rewind();
8107 while ((item=li++))
8108 item->clear_extraction_flag();
8109 }
8110 }
8111 else
8112 {
8113 int fl= cond->excl_dep_on_grouping_fields(this) && !cond->is_expensive() ?
8114 FULL_EXTRACTION_FL : NO_EXTRACTION_FL;
8115 cond->set_extraction_flag(fl);
8116 }
8117 }
8118
8119
8120 /**
8121 @brief
8122 Build condition extractable from the given one depended on grouping fields
8123
8124 @param thd The thread handle
8125 @param cond The condition from which the condition depended
8126 on grouping fields is to be extracted
8127 @param no_top_clones If it's true then no clones for the top fully
8128 extractable conjuncts are built
8129
8130 @details
8131 For the given condition cond this method finds out what condition depended
8132 only on the grouping fields can be extracted from cond. If such condition C
8133 exists the method builds the item for it.
8134 This method uses the flags NO_EXTRACTION_FL and FULL_EXTRACTION_FL set by the
8135 preliminary call of st_select_lex::check_cond_extraction_for_grouping_fields
8136 to figure out whether a subformula depends only on these fields or not.
8137 @note
8138 The built condition C is always implied by the condition cond
8139 (cond => C). The method tries to build the least restictive such
8140 condition (i.e. for any other condition C' such that cond => C'
8141 we have C => C').
8142 @note
8143 The build item is not ready for usage: substitution for the field items
8144 has to be done and it has to be re-fixed.
8145
8146 @retval
8147 the built condition depended only on grouping fields if such a condition exists
8148 NULL if there is no such a condition
8149 */
8150
build_cond_for_grouping_fields(THD * thd,Item * cond,bool no_top_clones)8151 Item *st_select_lex::build_cond_for_grouping_fields(THD *thd, Item *cond,
8152 bool no_top_clones)
8153 {
8154 if (cond->get_extraction_flag() == FULL_EXTRACTION_FL)
8155 {
8156 if (no_top_clones)
8157 return cond;
8158 cond->clear_extraction_flag();
8159 return cond->build_clone(thd);
8160 }
8161 if (cond->type() == Item::COND_ITEM)
8162 {
8163 bool cond_and= false;
8164 Item_cond *new_cond;
8165 if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
8166 {
8167 cond_and= true;
8168 new_cond= new (thd->mem_root) Item_cond_and(thd);
8169 }
8170 else
8171 new_cond= new (thd->mem_root) Item_cond_or(thd);
8172 if (unlikely(!new_cond))
8173 return 0;
8174 List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
8175 Item *item;
8176 while ((item=li++))
8177 {
8178 if (item->get_extraction_flag() == NO_EXTRACTION_FL)
8179 {
8180 DBUG_ASSERT(cond_and);
8181 item->clear_extraction_flag();
8182 continue;
8183 }
8184 Item *fix= build_cond_for_grouping_fields(thd, item,
8185 no_top_clones & cond_and);
8186 if (unlikely(!fix))
8187 {
8188 if (cond_and)
8189 continue;
8190 break;
8191 }
8192 new_cond->argument_list()->push_back(fix, thd->mem_root);
8193 }
8194
8195 if (!cond_and && item)
8196 {
8197 while((item= li++))
8198 item->clear_extraction_flag();
8199 return 0;
8200 }
8201 switch (new_cond->argument_list()->elements)
8202 {
8203 case 0:
8204 return 0;
8205 case 1:
8206 return new_cond->argument_list()->head();
8207 default:
8208 return new_cond;
8209 }
8210 }
8211 return 0;
8212 }
8213
8214
set_nest_level(int new_nest_level)8215 bool st_select_lex::set_nest_level(int new_nest_level)
8216 {
8217 DBUG_ENTER("st_select_lex::set_nest_level");
8218 DBUG_PRINT("enter", ("select #%d %p nest level: %d",
8219 select_number, this, new_nest_level));
8220 if (new_nest_level > (int) MAX_SELECT_NESTING)
8221 {
8222 my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT, MYF(0));
8223 DBUG_RETURN(TRUE);
8224 }
8225 nest_level= new_nest_level;
8226 new_nest_level++;
8227 for (SELECT_LEX_UNIT *u= first_inner_unit(); u; u= u->next_unit())
8228 {
8229 if (u->set_nest_level(new_nest_level))
8230 DBUG_RETURN(TRUE);
8231 }
8232 DBUG_RETURN(FALSE);
8233 }
8234
set_nest_level(int new_nest_level)8235 bool st_select_lex_unit::set_nest_level(int new_nest_level)
8236 {
8237 DBUG_ENTER("st_select_lex_unit::set_nest_level");
8238 for(SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
8239 {
8240 if (sl->set_nest_level(new_nest_level))
8241 DBUG_RETURN(TRUE);
8242 }
8243 if (fake_select_lex &&
8244 fake_select_lex->set_nest_level(new_nest_level))
8245 DBUG_RETURN(TRUE);
8246 DBUG_RETURN(FALSE);
8247 }
8248
8249
check_parameters(SELECT_LEX * main_select)8250 bool st_select_lex::check_parameters(SELECT_LEX *main_select)
8251 {
8252 DBUG_ENTER("st_select_lex::check_parameters");
8253 DBUG_PRINT("enter", ("select #%d %p nest level: %d",
8254 select_number, this, nest_level));
8255
8256
8257 if ((options & OPTION_PROCEDURE_CLAUSE) &&
8258 (!parent_lex->selects_allow_procedure ||
8259 next_select() != NULL ||
8260 this != master_unit()->first_select() ||
8261 nest_level != 0))
8262 {
8263 my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "PROCEDURE");
8264 DBUG_RETURN(TRUE);
8265 }
8266
8267 if ((options & SELECT_HIGH_PRIORITY) && this != main_select)
8268 {
8269 my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "HIGH_PRIORITY");
8270 DBUG_RETURN(TRUE);
8271 }
8272 if ((options & OPTION_BUFFER_RESULT) && this != main_select)
8273 {
8274 my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_BUFFER_RESULT");
8275 DBUG_RETURN(TRUE);
8276 }
8277 if ((options & OPTION_FOUND_ROWS) && this != main_select)
8278 {
8279 my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_CALC_FOUND_ROWS");
8280 DBUG_RETURN(TRUE);
8281 }
8282 if (options & OPTION_NO_QUERY_CACHE)
8283 {
8284 /*
8285 Allow this flag only on the first top-level SELECT statement, if
8286 SQL_CACHE wasn't specified.
8287 */
8288 if (this != main_select)
8289 {
8290 my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_NO_CACHE");
8291 DBUG_RETURN(TRUE);
8292 }
8293 if (parent_lex->sql_cache == LEX::SQL_CACHE)
8294 {
8295 my_error(ER_WRONG_USAGE, MYF(0), "SQL_CACHE", "SQL_NO_CACHE");
8296 DBUG_RETURN(TRUE);
8297 }
8298 parent_lex->safe_to_cache_query=0;
8299 parent_lex->sql_cache= LEX::SQL_NO_CACHE;
8300 }
8301 if (options & OPTION_TO_QUERY_CACHE)
8302 {
8303 /*
8304 Allow this flag only on the first top-level SELECT statement, if
8305 SQL_NO_CACHE wasn't specified.
8306 */
8307 if (this != main_select)
8308 {
8309 my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_CACHE");
8310 DBUG_RETURN(TRUE);
8311 }
8312 if (parent_lex->sql_cache == LEX::SQL_NO_CACHE)
8313 {
8314 my_error(ER_WRONG_USAGE, MYF(0), "SQL_NO_CACHE", "SQL_CACHE");
8315 DBUG_RETURN(TRUE);
8316 }
8317 parent_lex->safe_to_cache_query=1;
8318 parent_lex->sql_cache= LEX::SQL_CACHE;
8319 }
8320
8321 for (SELECT_LEX_UNIT *u= first_inner_unit(); u; u= u->next_unit())
8322 {
8323 if (u->check_parameters(main_select))
8324 DBUG_RETURN(TRUE);
8325 }
8326 DBUG_RETURN(FALSE);
8327 }
8328
8329
check_parameters(SELECT_LEX * main_select)8330 bool st_select_lex_unit::check_parameters(SELECT_LEX *main_select)
8331 {
8332 for(SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
8333 {
8334 if (sl->check_parameters(main_select))
8335 return TRUE;
8336 }
8337 return fake_select_lex && fake_select_lex->check_parameters(main_select);
8338 }
8339
8340
check_main_unit_semantics()8341 bool LEX::check_main_unit_semantics()
8342 {
8343 if (unit.set_nest_level(0) ||
8344 unit.check_parameters(first_select_lex()))
8345 return TRUE;
8346 if (check_cte_dependencies_and_resolve_references())
8347 return TRUE;
8348 return FALSE;
8349 }
8350
set_statement_var_if_exists(THD * thd,const char * var_name,size_t var_name_length,ulonglong value)8351 int set_statement_var_if_exists(THD *thd, const char *var_name,
8352 size_t var_name_length, ulonglong value)
8353 {
8354 sys_var *sysvar;
8355 if (unlikely(thd->lex->sql_command == SQLCOM_CREATE_VIEW))
8356 {
8357 my_error(ER_VIEW_SELECT_CLAUSE, MYF(0), "[NO]WAIT");
8358 return 1;
8359 }
8360 if (unlikely(thd->lex->sphead))
8361 {
8362 my_error(ER_SP_BADSTATEMENT, MYF(0), "[NO]WAIT");
8363 return 1;
8364 }
8365 if ((sysvar= find_sys_var(thd, var_name, var_name_length, true)))
8366 {
8367 Item *item= new (thd->mem_root) Item_uint(thd, value);
8368 set_var *var= new (thd->mem_root) set_var(thd, OPT_SESSION, sysvar,
8369 &null_clex_str, item);
8370
8371 if (unlikely(!item) || unlikely(!var) ||
8372 unlikely(thd->lex->stmt_var_list.push_back(var, thd->mem_root)))
8373 {
8374 my_error(ER_OUT_OF_RESOURCES, MYF(0));
8375 return 1;
8376 }
8377 }
8378 return 0;
8379 }
8380
8381
sp_add_cfetch(THD * thd,const LEX_CSTRING * name)8382 bool LEX::sp_add_cfetch(THD *thd, const LEX_CSTRING *name)
8383 {
8384 uint offset;
8385 sp_instr_cfetch *i;
8386
8387 if (!spcont->find_cursor(name, &offset, false))
8388 {
8389 my_error(ER_SP_CURSOR_MISMATCH, MYF(0), name->str);
8390 return true;
8391 }
8392 i= new (thd->mem_root)
8393 sp_instr_cfetch(sphead->instructions(), spcont, offset,
8394 !(thd->variables.sql_mode & MODE_ORACLE));
8395 if (unlikely(i == NULL) || unlikely(sphead->add_instr(i)))
8396 return true;
8397 return false;
8398 }
8399
8400
sp_add_agg_cfetch()8401 bool LEX::sp_add_agg_cfetch()
8402 {
8403 sphead->m_flags|= sp_head::HAS_AGGREGATE_INSTR;
8404 sp_instr_agg_cfetch *i=
8405 new (thd->mem_root) sp_instr_agg_cfetch(sphead->instructions(), spcont);
8406 return i == NULL || sphead->add_instr(i);
8407 }
8408
8409
create_or_alter_view_finalize(THD * thd,Table_ident * table_ident)8410 bool LEX::create_or_alter_view_finalize(THD *thd, Table_ident *table_ident)
8411 {
8412 sql_command= SQLCOM_CREATE_VIEW;
8413 /* first table in list is target VIEW name */
8414 if (!first_select_lex()->add_table_to_list(thd, table_ident, NULL,
8415 TL_OPTION_UPDATING,
8416 TL_IGNORE,
8417 MDL_EXCLUSIVE))
8418 return true;
8419 query_tables->open_strategy= TABLE_LIST::OPEN_STUB;
8420 return false;
8421 }
8422
8423
add_alter_view(THD * thd,uint16 algorithm,enum_view_suid suid,Table_ident * table_ident)8424 bool LEX::add_alter_view(THD *thd, uint16 algorithm,
8425 enum_view_suid suid,
8426 Table_ident *table_ident)
8427 {
8428 if (unlikely(sphead))
8429 {
8430 my_error(ER_SP_BADSTATEMENT, MYF(0), "ALTER VIEW");
8431 return true;
8432 }
8433 if (unlikely(!(create_view= new (thd->mem_root)
8434 Create_view_info(VIEW_ALTER, algorithm, suid))))
8435 return true;
8436 return create_or_alter_view_finalize(thd, table_ident);
8437 }
8438
8439
add_create_view(THD * thd,DDL_options_st ddl,uint16 algorithm,enum_view_suid suid,Table_ident * table_ident)8440 bool LEX::add_create_view(THD *thd, DDL_options_st ddl,
8441 uint16 algorithm, enum_view_suid suid,
8442 Table_ident *table_ident)
8443 {
8444 if (unlikely(set_create_options_with_check(ddl)))
8445 return true;
8446 if (unlikely(!(create_view= new (thd->mem_root)
8447 Create_view_info(ddl.or_replace() ?
8448 VIEW_CREATE_OR_REPLACE :
8449 VIEW_CREATE_NEW,
8450 algorithm, suid))))
8451 return true;
8452 return create_or_alter_view_finalize(thd, table_ident);
8453 }
8454
8455
call_statement_start(THD * thd,sp_name * name)8456 bool LEX::call_statement_start(THD *thd, sp_name *name)
8457 {
8458 Database_qualified_name pkgname(&null_clex_str, &null_clex_str);
8459 const Sp_handler *sph= &sp_handler_procedure;
8460 sql_command= SQLCOM_CALL;
8461 value_list.empty();
8462 if (unlikely(sph->sp_resolve_package_routine(thd, thd->lex->sphead,
8463 name, &sph, &pkgname)))
8464 return true;
8465 if (unlikely(!(m_sql_cmd= new (thd->mem_root) Sql_cmd_call(name, sph))))
8466 return true;
8467 sph->add_used_routine(this, thd, name);
8468 if (pkgname.m_name.length)
8469 sp_handler_package_body.add_used_routine(this, thd, &pkgname);
8470 return false;
8471 }
8472
8473
call_statement_start(THD * thd,const LEX_CSTRING * name)8474 bool LEX::call_statement_start(THD *thd, const LEX_CSTRING *name)
8475 {
8476 sp_name *spname= make_sp_name(thd, name);
8477 return unlikely(!spname) || call_statement_start(thd, spname);
8478 }
8479
8480
call_statement_start(THD * thd,const LEX_CSTRING * name1,const LEX_CSTRING * name2)8481 bool LEX::call_statement_start(THD *thd, const LEX_CSTRING *name1,
8482 const LEX_CSTRING *name2)
8483 {
8484 sp_name *spname= make_sp_name(thd, name1, name2);
8485 return unlikely(!spname) || call_statement_start(thd, spname);
8486 }
8487
8488
get_sp_package() const8489 sp_package *LEX::get_sp_package() const
8490 {
8491 return sphead ? sphead->get_package() : NULL;
8492 }
8493
8494
create_package_start(THD * thd,enum_sql_command command,const Sp_handler * sph,const sp_name * name_arg,DDL_options_st options)8495 sp_package *LEX::create_package_start(THD *thd,
8496 enum_sql_command command,
8497 const Sp_handler *sph,
8498 const sp_name *name_arg,
8499 DDL_options_st options)
8500 {
8501 sp_package *pkg;
8502
8503 if (unlikely(sphead))
8504 {
8505 my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), sph->type_str());
8506 return NULL;
8507 }
8508 if (unlikely(set_command_with_check(command, options)))
8509 return NULL;
8510 if (sph->type() == TYPE_ENUM_PACKAGE_BODY)
8511 {
8512 /*
8513 If we start parsing a "CREATE PACKAGE BODY", we need to load
8514 the corresponding "CREATE PACKAGE", for the following reasons:
8515 1. "CREATE PACKAGE BODY" is allowed only if "CREATE PACKAGE"
8516 was done earlier for the same package name.
8517 So if "CREATE PACKAGE" does not exist, we throw an error here.
8518 2. When parsing "CREATE PACKAGE BODY", we need to know all package
8519 public and private routine names, to translate procedure and
8520 function calls correctly.
8521 For example, this statement inside a package routine:
8522 CALL p;
8523 can be translated to:
8524 CALL db.pkg.p; -- p is a known (public or private) package routine
8525 CALL db.p; -- p is not a known package routine
8526 */
8527 sp_head *spec;
8528 int ret= sp_handler_package_spec.
8529 sp_cache_routine_reentrant(thd, name_arg, &spec);
8530 if (unlikely(!spec))
8531 {
8532 if (!ret)
8533 my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
8534 "PACKAGE", ErrConvDQName(name_arg).ptr());
8535 return 0;
8536 }
8537 }
8538 if (unlikely(!(pkg= sp_package::create(this, name_arg, sph))))
8539 return NULL;
8540 pkg->reset_thd_mem_root(thd);
8541 pkg->init(this);
8542 pkg->make_qname(pkg->get_main_mem_root(), &pkg->m_qname);
8543 sphead= pkg;
8544 return pkg;
8545 }
8546
8547
create_package_finalize(THD * thd,const sp_name * name,const sp_name * name2,const char * body_start,const char * body_end)8548 bool LEX::create_package_finalize(THD *thd,
8549 const sp_name *name,
8550 const sp_name *name2,
8551 const char *body_start,
8552 const char *body_end)
8553 {
8554 if (name2 &&
8555 (name2->m_explicit_name != name->m_explicit_name ||
8556 strcmp(name2->m_db.str, name->m_db.str) ||
8557 !Sp_handler::eq_routine_name(name2->m_name, name->m_name)))
8558 {
8559 bool exp= name2->m_explicit_name || name->m_explicit_name;
8560 my_error(ER_END_IDENTIFIER_DOES_NOT_MATCH, MYF(0),
8561 exp ? ErrConvDQName(name2).ptr() : name2->m_name.str,
8562 exp ? ErrConvDQName(name).ptr() : name->m_name.str);
8563 return true;
8564 }
8565 // TODO: reuse code in LEX::create_package_finalize and sp_head::set_stmt_end
8566 sphead->m_body.length= body_end - body_start;
8567 if (unlikely(!(sphead->m_body.str= thd->strmake(body_start,
8568 sphead->m_body.length))))
8569 return true;
8570
8571 size_t not_used;
8572 Lex_input_stream *lip= & thd->m_parser_state->m_lip;
8573 sphead->m_defstr.length= lip->get_cpp_ptr() - lip->get_cpp_buf();
8574 sphead->m_defstr.str= thd->strmake(lip->get_cpp_buf(), sphead->m_defstr.length);
8575 trim_whitespace(thd->charset(), &sphead->m_defstr, ¬_used);
8576
8577 sphead->restore_thd_mem_root(thd);
8578 sp_package *pkg= sphead->get_package();
8579 DBUG_ASSERT(pkg);
8580 return sphead->check_group_aggregate_instructions_forbid() ||
8581 pkg->validate_after_parser(thd);
8582 }
8583
8584
add_grant_command(THD * thd,enum_sql_command sql_command_arg,stored_procedure_type type_arg)8585 bool LEX::add_grant_command(THD *thd, enum_sql_command sql_command_arg,
8586 stored_procedure_type type_arg)
8587 {
8588 if (columns.elements)
8589 {
8590 thd->parse_error();
8591 return true;
8592 }
8593 sql_command= sql_command_arg,
8594 type= type_arg;
8595 return false;
8596 }
8597
8598
make_item_func_substr(THD * thd,Item * a,Item * b,Item * c)8599 Item *LEX::make_item_func_substr(THD *thd, Item *a, Item *b, Item *c)
8600 {
8601 return (thd->variables.sql_mode & MODE_ORACLE) ?
8602 new (thd->mem_root) Item_func_substr_oracle(thd, a, b, c) :
8603 new (thd->mem_root) Item_func_substr(thd, a, b, c);
8604 }
8605
8606
make_item_func_substr(THD * thd,Item * a,Item * b)8607 Item *LEX::make_item_func_substr(THD *thd, Item *a, Item *b)
8608 {
8609 return (thd->variables.sql_mode & MODE_ORACLE) ?
8610 new (thd->mem_root) Item_func_substr_oracle(thd, a, b) :
8611 new (thd->mem_root) Item_func_substr(thd, a, b);
8612 }
8613
8614
make_item_func_replace(THD * thd,Item * org,Item * find,Item * replace)8615 Item *LEX::make_item_func_replace(THD *thd,
8616 Item *org,
8617 Item *find,
8618 Item *replace)
8619 {
8620 return (thd->variables.sql_mode & MODE_ORACLE) ?
8621 new (thd->mem_root) Item_func_replace_oracle(thd, org, find, replace) :
8622 new (thd->mem_root) Item_func_replace(thd, org, find, replace);
8623 }
8624
8625
vers_push_field(THD * thd,TABLE_LIST * table,const LEX_CSTRING field_name)8626 bool SELECT_LEX::vers_push_field(THD *thd, TABLE_LIST *table,
8627 const LEX_CSTRING field_name)
8628 {
8629 DBUG_ASSERT(field_name.str);
8630 Item_field *fld= new (thd->mem_root) Item_field(thd, &context,
8631 table->db.str,
8632 table->alias.str,
8633 &field_name);
8634 if (unlikely(!fld) || unlikely(item_list.push_back(fld)))
8635 return true;
8636
8637 if (thd->lex->view_list.elements)
8638 {
8639 LEX_CSTRING *l;
8640 if (unlikely(!(l= thd->make_clex_string(field_name.str,
8641 field_name.length))) ||
8642 unlikely(thd->lex->view_list.push_back(l)))
8643 return true;
8644 }
8645
8646 return false;
8647 }
8648
8649
make_item_func_trim_std(THD * thd) const8650 Item *Lex_trim_st::make_item_func_trim_std(THD *thd) const
8651 {
8652 if (m_remove)
8653 {
8654 switch (m_spec) {
8655 case TRIM_BOTH:
8656 return new (thd->mem_root) Item_func_trim(thd, m_source, m_remove);
8657 case TRIM_LEADING:
8658 return new (thd->mem_root) Item_func_ltrim(thd, m_source, m_remove);
8659 case TRIM_TRAILING:
8660 return new (thd->mem_root) Item_func_rtrim(thd, m_source, m_remove);
8661 }
8662 }
8663
8664 switch (m_spec) {
8665 case TRIM_BOTH:
8666 return new (thd->mem_root) Item_func_trim(thd, m_source);
8667 case TRIM_LEADING:
8668 return new (thd->mem_root) Item_func_ltrim(thd, m_source);
8669 case TRIM_TRAILING:
8670 return new (thd->mem_root) Item_func_rtrim(thd, m_source);
8671 }
8672 DBUG_ASSERT(0);
8673 return NULL;
8674 }
8675
8676
make_item_func_trim_oracle(THD * thd) const8677 Item *Lex_trim_st::make_item_func_trim_oracle(THD *thd) const
8678 {
8679 if (m_remove)
8680 {
8681 switch (m_spec) {
8682 case TRIM_BOTH:
8683 return new (thd->mem_root) Item_func_trim_oracle(thd, m_source, m_remove);
8684 case TRIM_LEADING:
8685 return new (thd->mem_root) Item_func_ltrim_oracle(thd, m_source, m_remove);
8686 case TRIM_TRAILING:
8687 return new (thd->mem_root) Item_func_rtrim_oracle(thd, m_source, m_remove);
8688 }
8689 }
8690
8691 switch (m_spec) {
8692 case TRIM_BOTH:
8693 return new (thd->mem_root) Item_func_trim_oracle(thd, m_source);
8694 case TRIM_LEADING:
8695 return new (thd->mem_root) Item_func_ltrim_oracle(thd, m_source);
8696 case TRIM_TRAILING:
8697 return new (thd->mem_root) Item_func_rtrim_oracle(thd, m_source);
8698 }
8699 DBUG_ASSERT(0);
8700 return NULL;
8701 }
8702
8703
make_item_func_trim(THD * thd) const8704 Item *Lex_trim_st::make_item_func_trim(THD *thd) const
8705 {
8706 return (thd->variables.sql_mode & MODE_ORACLE) ?
8707 make_item_func_trim_oracle(thd) :
8708 make_item_func_trim_std(thd);
8709 }
8710
8711
make_item_func_call_generic(THD * thd,Lex_ident_cli_st * cdb,Lex_ident_cli_st * cname,List<Item> * args)8712 Item *LEX::make_item_func_call_generic(THD *thd, Lex_ident_cli_st *cdb,
8713 Lex_ident_cli_st *cname, List<Item> *args)
8714 {
8715 Lex_ident_sys db(thd, cdb), name(thd, cname);
8716 if (db.is_null() || name.is_null())
8717 return NULL; // EOM
8718 /*
8719 The following in practice calls:
8720 <code>Create_sp_func::create()</code>
8721 and builds a stored function.
8722
8723 However, it's important to maintain the interface between the
8724 parser and the implementation in item_create.cc clean,
8725 since this will change with WL#2128 (SQL PATH):
8726 - INFORMATION_SCHEMA.version() is the SQL 99 syntax for the native
8727 function version(),
8728 - MySQL.version() is the SQL 2003 syntax for the native function
8729 version() (a vendor can specify any schema).
8730 */
8731
8732 if (!name.str || check_db_name((LEX_STRING*) static_cast<LEX_CSTRING*>(&db)))
8733 {
8734 my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
8735 return NULL;
8736 }
8737 if (check_routine_name(&name))
8738 return NULL;
8739
8740 Create_qfunc *builder= find_qualified_function_builder(thd);
8741 DBUG_ASSERT(builder);
8742 return builder->create_with_db(thd, &db, &name, true, args);
8743 }
8744
8745
create_item_qualified_asterisk(THD * thd,const Lex_ident_sys_st * name)8746 Item *LEX::create_item_qualified_asterisk(THD *thd,
8747 const Lex_ident_sys_st *name)
8748 {
8749 Item *item;
8750 if (!(item= new (thd->mem_root) Item_field(thd, current_context(),
8751 NullS, name->str,
8752 &star_clex_str)))
8753 return NULL;
8754 current_select->with_wild++;
8755 return item;
8756 }
8757
8758
create_item_qualified_asterisk(THD * thd,const Lex_ident_sys_st * a,const Lex_ident_sys_st * b)8759 Item *LEX::create_item_qualified_asterisk(THD *thd,
8760 const Lex_ident_sys_st *a,
8761 const Lex_ident_sys_st *b)
8762 {
8763 Item *item;
8764 const char* schema= thd->client_capabilities & CLIENT_NO_SCHEMA ?
8765 NullS : a->str;
8766 if (!(item= new (thd->mem_root) Item_field(thd, current_context(),
8767 schema, b->str,
8768 &star_clex_str)))
8769 return NULL;
8770 current_select->with_wild++;
8771 return item;
8772 }
8773
8774
copy_ident_cli(THD * thd,const Lex_ident_cli_st * str)8775 bool Lex_ident_sys_st::copy_ident_cli(THD *thd, const Lex_ident_cli_st *str)
8776 {
8777 return thd->to_ident_sys_alloc(this, str);
8778 }
8779
copy_keyword(THD * thd,const Lex_ident_cli_st * str)8780 bool Lex_ident_sys_st::copy_keyword(THD *thd, const Lex_ident_cli_st *str)
8781 {
8782 return thd->make_lex_string(static_cast<LEX_CSTRING*>(this),
8783 str->str, str->length) == NULL;
8784 }
8785
copy_or_convert(THD * thd,const Lex_ident_cli_st * src,CHARSET_INFO * cs)8786 bool Lex_ident_sys_st::copy_or_convert(THD *thd,
8787 const Lex_ident_cli_st *src,
8788 CHARSET_INFO *cs)
8789 {
8790 if (!src->is_8bit())
8791 return copy_keyword(thd, src); // 7bit string makes a wellformed identifier
8792 return convert(thd, src, cs);
8793 }
8794
8795
copy_sys(THD * thd,const LEX_CSTRING * src)8796 bool Lex_ident_sys_st::copy_sys(THD *thd, const LEX_CSTRING *src)
8797 {
8798 if (thd->check_string_for_wellformedness(src->str, src->length,
8799 system_charset_info))
8800 return true;
8801 return thd->make_lex_string(this, src->str, src->length) == NULL;
8802 }
8803
8804
convert(THD * thd,const LEX_CSTRING * src,CHARSET_INFO * cs)8805 bool Lex_ident_sys_st::convert(THD *thd,
8806 const LEX_CSTRING *src, CHARSET_INFO *cs)
8807 {
8808 LEX_STRING tmp;
8809 if (thd->convert_with_error(system_charset_info, &tmp, cs,
8810 src->str, src->length))
8811 return true;
8812 str= tmp.str;
8813 length= tmp.length;
8814 return false;
8815 }
8816
8817
to_size_number(ulonglong * to) const8818 bool Lex_ident_sys_st::to_size_number(ulonglong *to) const
8819 {
8820 ulonglong number;
8821 uint text_shift_number= 0;
8822 longlong prefix_number;
8823 const char *start_ptr= str;
8824 size_t str_len= length;
8825 const char *end_ptr= start_ptr + str_len;
8826 int error;
8827 prefix_number= my_strtoll10(start_ptr, (char**) &end_ptr, &error);
8828 if (likely((start_ptr + str_len - 1) == end_ptr))
8829 {
8830 switch (end_ptr[0])
8831 {
8832 case 'g':
8833 case 'G': text_shift_number+=30; break;
8834 case 'm':
8835 case 'M': text_shift_number+=20; break;
8836 case 'k':
8837 case 'K': text_shift_number+=10; break;
8838 default:
8839 my_error(ER_WRONG_SIZE_NUMBER, MYF(0));
8840 return true;
8841 }
8842 if (unlikely(prefix_number >> 31))
8843 {
8844 my_error(ER_SIZE_OVERFLOW_ERROR, MYF(0));
8845 return true;
8846 }
8847 number= prefix_number << text_shift_number;
8848 }
8849 else
8850 {
8851 my_error(ER_WRONG_SIZE_NUMBER, MYF(0));
8852 return true;
8853 }
8854 *to= number;
8855 return false;
8856 }
8857
8858
part_values_current(THD * thd)8859 bool LEX::part_values_current(THD *thd)
8860 {
8861 partition_element *elem= part_info->curr_part_elem;
8862 if (!is_partition_management())
8863 {
8864 if (unlikely(part_info->part_type != VERSIONING_PARTITION))
8865 {
8866 my_error(ER_PARTITION_WRONG_TYPE, MYF(0), "SYSTEM_TIME");
8867 return true;
8868 }
8869 }
8870 else
8871 {
8872 DBUG_ASSERT(create_last_non_select_table);
8873 DBUG_ASSERT(create_last_non_select_table->table_name.str);
8874 // FIXME: other ALTER commands?
8875 my_error(ER_VERS_WRONG_PARTS, MYF(0),
8876 create_last_non_select_table->table_name.str);
8877 return true;
8878 }
8879 elem->type= partition_element::CURRENT;
8880 DBUG_ASSERT(part_info->vers_info);
8881 part_info->vers_info->now_part= elem;
8882 return false;
8883 }
8884
8885
part_values_history(THD * thd)8886 bool LEX::part_values_history(THD *thd)
8887 {
8888 partition_element *elem= part_info->curr_part_elem;
8889 if (!is_partition_management())
8890 {
8891 if (unlikely(part_info->part_type != VERSIONING_PARTITION))
8892 {
8893 my_error(ER_PARTITION_WRONG_TYPE, MYF(0), "SYSTEM_TIME");
8894 return true;
8895 }
8896 }
8897 else
8898 {
8899 part_info->vers_init_info(thd);
8900 elem->id= UINT_MAX32;
8901 }
8902 DBUG_ASSERT(part_info->vers_info);
8903 if (unlikely(part_info->vers_info->now_part))
8904 {
8905 DBUG_ASSERT(create_last_non_select_table);
8906 DBUG_ASSERT(create_last_non_select_table->table_name.str);
8907 my_error(ER_VERS_WRONG_PARTS, MYF(0),
8908 create_last_non_select_table->table_name.str);
8909 return true;
8910 }
8911 elem->type= partition_element::HISTORY;
8912 return false;
8913 }
8914
8915
last_field_generated_always_as_row_start_or_end(Lex_ident * p,const char * type,uint flag)8916 bool LEX::last_field_generated_always_as_row_start_or_end(Lex_ident *p,
8917 const char *type,
8918 uint flag)
8919 {
8920 if (unlikely(p->str))
8921 {
8922 my_error(ER_VERS_DUPLICATE_ROW_START_END, MYF(0), type,
8923 last_field->field_name.str);
8924 return true;
8925 }
8926 last_field->flags|= (flag | NOT_NULL_FLAG);
8927 DBUG_ASSERT(p);
8928 *p= last_field->field_name;
8929 return false;
8930 }
8931
8932
8933
last_field_generated_always_as_row_start()8934 bool LEX::last_field_generated_always_as_row_start()
8935 {
8936 Vers_parse_info &info= vers_get_info();
8937 Lex_ident *p= &info.as_row.start;
8938 return last_field_generated_always_as_row_start_or_end(p, "START",
8939 VERS_ROW_START);
8940 }
8941
8942
last_field_generated_always_as_row_end()8943 bool LEX::last_field_generated_always_as_row_end()
8944 {
8945 Vers_parse_info &info= vers_get_info();
8946 Lex_ident *p= &info.as_row.end;
8947 return last_field_generated_always_as_row_start_or_end(p, "END",
8948 VERS_ROW_END);
8949 }
8950
reset_distinct()8951 void st_select_lex_unit::reset_distinct()
8952 {
8953 union_distinct= NULL;
8954 for(SELECT_LEX *sl= first_select()->next_select();
8955 sl;
8956 sl= sl->next_select())
8957 {
8958 if (sl->distinct)
8959 {
8960 union_distinct= sl;
8961 }
8962 }
8963 }
8964
8965
save_values_list_state()8966 void LEX::save_values_list_state()
8967 {
8968 current_select->save_many_values= many_values;
8969 current_select->save_insert_list= insert_list;
8970 }
8971
8972
restore_values_list_state()8973 void LEX::restore_values_list_state()
8974 {
8975 many_values= current_select->save_many_values;
8976 insert_list= current_select->save_insert_list;
8977 }
8978
8979
fix_distinct()8980 void st_select_lex_unit::fix_distinct()
8981 {
8982 if (union_distinct && this != union_distinct->master_unit())
8983 reset_distinct();
8984 }
8985
8986
register_select_chain(SELECT_LEX * first_sel)8987 void st_select_lex_unit::register_select_chain(SELECT_LEX *first_sel)
8988 {
8989 DBUG_ASSERT(first_sel != 0);
8990 slave= first_sel;
8991 first_sel->prev= &slave;
8992 for(SELECT_LEX *sel=first_sel; sel; sel= sel->next_select())
8993 {
8994 sel->master= (st_select_lex_node *)this;
8995 uncacheable|= sel->uncacheable;
8996 }
8997 }
8998
8999
register_unit(SELECT_LEX_UNIT * unit,Name_resolution_context * outer_context)9000 void st_select_lex::register_unit(SELECT_LEX_UNIT *unit,
9001 Name_resolution_context *outer_context)
9002 {
9003 if ((unit->next= slave))
9004 slave->prev= &unit->next;
9005 unit->prev= &slave;
9006 slave= unit;
9007 unit->master= this;
9008 uncacheable|= unit->uncacheable;
9009
9010 for(SELECT_LEX *sel= unit->first_select();sel; sel= sel->next_select())
9011 {
9012 sel->context.outer_context= outer_context;
9013 }
9014 }
9015
9016
add_statistics(SELECT_LEX_UNIT * unit)9017 void st_select_lex::add_statistics(SELECT_LEX_UNIT *unit)
9018 {
9019 for (;
9020 unit;
9021 unit= unit->next_unit())
9022 for(SELECT_LEX *child= unit->first_select();
9023 child;
9024 child= child->next_select())
9025 {
9026 /*
9027 A subselect can add fields to an outer select.
9028 Reserve space for them.
9029 */
9030 select_n_where_fields+= child->select_n_where_fields;
9031 /*
9032 Aggregate functions in having clause may add fields
9033 to an outer select. Count them also.
9034 */
9035 select_n_having_items+= child->select_n_having_items;
9036 }
9037 }
9038
9039
main_select_push(bool service)9040 bool LEX::main_select_push(bool service)
9041 {
9042 DBUG_ENTER("LEX::main_select_push");
9043 current_select_number= ++thd->lex->stmt_lex->current_select_number;
9044 builtin_select.select_number= current_select_number;
9045 builtin_select.is_service_select= service;
9046 if (push_select(&builtin_select))
9047 DBUG_RETURN(TRUE);
9048 DBUG_RETURN(FALSE);
9049 }
9050
set_to(SELECT_LEX * sel)9051 void Lex_select_lock::set_to(SELECT_LEX *sel)
9052 {
9053 if (defined_lock)
9054 {
9055 if (sel->master_unit() &&
9056 sel == sel->master_unit()->fake_select_lex)
9057 sel->master_unit()->set_lock_to_the_last_select(*this);
9058 else
9059 {
9060 sel->parent_lex->safe_to_cache_query= 0;
9061 if (update_lock)
9062 {
9063 sel->lock_type= TL_WRITE;
9064 sel->set_lock_for_tables(TL_WRITE, false);
9065 }
9066 else
9067 {
9068 sel->lock_type= TL_READ_WITH_SHARED_LOCKS;
9069 sel->set_lock_for_tables(TL_READ_WITH_SHARED_LOCKS, false);
9070 }
9071 }
9072 }
9073 }
9074
set_to(SELECT_LEX * sel)9075 bool Lex_order_limit_lock::set_to(SELECT_LEX *sel)
9076 {
9077 /*TODO: lock */
9078 //if (lock.defined_lock && sel == sel->master_unit()->fake_select_lex)
9079 // return TRUE;
9080 if (lock.defined_timeout)
9081 {
9082 THD *thd= sel->parent_lex->thd;
9083 if (set_statement_var_if_exists(thd,
9084 C_STRING_WITH_LEN("lock_wait_timeout"),
9085 lock.timeout) ||
9086 set_statement_var_if_exists(thd,
9087 C_STRING_WITH_LEN("innodb_lock_wait_timeout"),
9088 lock.timeout))
9089 return TRUE;
9090 }
9091 lock.set_to(sel);
9092 sel->explicit_limit= limit.explicit_limit;
9093 sel->select_limit= limit.select_limit;
9094 sel->offset_limit= limit.offset_limit;
9095 if (order_list)
9096 {
9097 if (sel->get_linkage() != GLOBAL_OPTIONS_TYPE &&
9098 sel->olap != UNSPECIFIED_OLAP_TYPE &&
9099 (sel->get_linkage() != UNION_TYPE || sel->braces))
9100 {
9101 my_error(ER_WRONG_USAGE, MYF(0),
9102 "CUBE/ROLLUP", "ORDER BY");
9103 return TRUE;
9104 }
9105 sel->order_list= *(order_list);
9106 }
9107 sel->is_set_query_expr_tail= true;
9108 return FALSE;
9109 }
9110
9111
change_item_list_context(List<Item> * list,Name_resolution_context * context)9112 static void change_item_list_context(List<Item> *list,
9113 Name_resolution_context *context)
9114 {
9115 List_iterator_fast<Item> it (*list);
9116 Item *item;
9117 while((item= it++))
9118 {
9119 item->walk(&Item::change_context_processor, FALSE, (void *)context);
9120 }
9121 }
9122
9123
insert_select_hack(SELECT_LEX * sel)9124 bool LEX::insert_select_hack(SELECT_LEX *sel)
9125 {
9126 DBUG_ENTER("LEX::insert_select_hack");
9127
9128 DBUG_ASSERT(first_select_lex() == &builtin_select);
9129 DBUG_ASSERT(sel != NULL);
9130
9131 DBUG_ASSERT(builtin_select.first_inner_unit() == NULL);
9132
9133 if (builtin_select.link_prev)
9134 {
9135 if ((*builtin_select.link_prev= builtin_select.link_next))
9136 ((st_select_lex *)builtin_select.link_next)->link_prev=
9137 builtin_select.link_prev;
9138 builtin_select.link_prev= NULL; // indicator of removal
9139 }
9140
9141 if (set_main_unit(sel->master_unit()))
9142 return true;
9143
9144 DBUG_ASSERT(builtin_select.table_list.elements == 1);
9145 TABLE_LIST *insert_table= builtin_select.table_list.first;
9146
9147 if (!(insert_table->next_local= sel->table_list.first))
9148 {
9149 sel->table_list.next= &insert_table->next_local;
9150 }
9151 sel->table_list.first= insert_table;
9152 sel->table_list.elements++;
9153 insert_table->select_lex= sel;
9154
9155 sel->context.first_name_resolution_table= insert_table;
9156 builtin_select.context= sel->context;
9157 change_item_list_context(&field_list, &sel->context);
9158
9159 if (sel->tvc && !sel->next_select() &&
9160 (sql_command == SQLCOM_INSERT_SELECT ||
9161 sql_command == SQLCOM_REPLACE_SELECT))
9162 {
9163 DBUG_PRINT("info", ("'Usual' INSERT detected"));
9164 many_values= sel->tvc->lists_of_values;
9165 sel->options= sel->tvc->select_options;
9166 sel->tvc= NULL;
9167 if (sql_command == SQLCOM_INSERT_SELECT)
9168 sql_command= SQLCOM_INSERT;
9169 else
9170 sql_command= SQLCOM_REPLACE;
9171 }
9172
9173
9174 for (SELECT_LEX *sel= all_selects_list;
9175 sel;
9176 sel= sel->next_select_in_list())
9177 {
9178 if (sel->select_number != 1)
9179 sel->select_number--;
9180 };
9181
9182 DBUG_RETURN(FALSE);
9183 }
9184
9185
9186 /**
9187 Create an Item_singlerow_subselect for a query expression.
9188 */
9189
create_item_query_expression(THD * thd,st_select_lex_unit * unit)9190 Item *LEX::create_item_query_expression(THD *thd,
9191 st_select_lex_unit *unit)
9192 {
9193 if (clause_that_disallows_subselect)
9194 {
9195 my_error(ER_SUBQUERIES_NOT_SUPPORTED, MYF(0),
9196 clause_that_disallows_subselect);
9197 return NULL;
9198 }
9199
9200 // Add the subtree of subquery to the current SELECT_LEX
9201 SELECT_LEX *curr_sel= select_stack_head();
9202 DBUG_ASSERT(current_select == curr_sel ||
9203 (curr_sel == NULL && current_select == &builtin_select));
9204 if (!curr_sel)
9205 {
9206 curr_sel= &builtin_select;
9207 curr_sel->register_unit(unit, &curr_sel->context);
9208 curr_sel->add_statistics(unit);
9209 }
9210
9211 return new (thd->mem_root)
9212 Item_singlerow_subselect(thd, unit->first_select());
9213 }
9214
9215
parsed_select_expr_start(SELECT_LEX * s1,SELECT_LEX * s2,enum sub_select_type unit_type,bool distinct)9216 SELECT_LEX_UNIT *LEX::parsed_select_expr_start(SELECT_LEX *s1, SELECT_LEX *s2,
9217 enum sub_select_type unit_type,
9218 bool distinct)
9219 {
9220 SELECT_LEX_UNIT *res;
9221 SELECT_LEX *sel1;
9222 SELECT_LEX *sel2;
9223 if (!s1->next_select())
9224 sel1= s1;
9225 else
9226 {
9227 sel1= wrap_unit_into_derived(s1->master_unit());
9228 if (!sel1)
9229 return NULL;
9230 }
9231 if (!s2->next_select())
9232 sel2= s2;
9233 else
9234 {
9235 sel2= wrap_unit_into_derived(s2->master_unit());
9236 if (!sel2)
9237 return NULL;
9238 }
9239 sel1->link_neighbour(sel2);
9240 sel2->set_linkage_and_distinct(unit_type, distinct);
9241 sel2->first_nested= sel1->first_nested= sel1;
9242 res= create_unit(sel1);
9243 if (res == NULL)
9244 return NULL;
9245 res->pre_last_parse= sel1;
9246 push_select(res->fake_select_lex);
9247 return res;
9248 }
9249
9250
parsed_select_expr_cont(SELECT_LEX_UNIT * unit,SELECT_LEX * s2,enum sub_select_type unit_type,bool distinct,bool oracle)9251 SELECT_LEX_UNIT *LEX::parsed_select_expr_cont(SELECT_LEX_UNIT *unit,
9252 SELECT_LEX *s2,
9253 enum sub_select_type unit_type,
9254 bool distinct, bool oracle)
9255 {
9256 DBUG_ASSERT(!s2->next_select());
9257 SELECT_LEX *sel1= s2;
9258 SELECT_LEX *last= unit->pre_last_parse->next_select();
9259
9260 int cmp= oracle? 0 : cmp_unit_op(unit_type, last->get_linkage());
9261 if (cmp == 0)
9262 {
9263 sel1->first_nested= last->first_nested;
9264 }
9265 else if (cmp > 0)
9266 {
9267 last->first_nested= unit->pre_last_parse;
9268 sel1->first_nested= last;
9269 }
9270 else /* cmp < 0 */
9271 {
9272 SELECT_LEX *first_in_nest= last->first_nested;
9273 if (first_in_nest->first_nested != first_in_nest)
9274 {
9275 /* There is a priority jump starting from first_in_nest */
9276 if ((last= create_priority_nest(first_in_nest)) == NULL)
9277 return NULL;
9278 unit->fix_distinct();
9279 }
9280 sel1->first_nested= last->first_nested;
9281 }
9282 last->link_neighbour(sel1);
9283 sel1->set_master_unit(unit);
9284 sel1->set_linkage_and_distinct(unit_type, distinct);
9285 unit->pre_last_parse= last;
9286 return unit;
9287 }
9288
9289
9290 /**
9291 Add primary expression as the next term in a given query expression body
9292 pruducing a new query expression body
9293 */
9294
9295 SELECT_LEX_UNIT *
add_primary_to_query_expression_body(SELECT_LEX_UNIT * unit,SELECT_LEX * sel,enum sub_select_type unit_type,bool distinct,bool oracle)9296 LEX::add_primary_to_query_expression_body(SELECT_LEX_UNIT *unit,
9297 SELECT_LEX *sel,
9298 enum sub_select_type unit_type,
9299 bool distinct,
9300 bool oracle)
9301 {
9302 SELECT_LEX *sel2= sel;
9303 if (sel->master_unit() && sel->master_unit()->first_select()->next_select())
9304 {
9305 sel2= wrap_unit_into_derived(sel->master_unit());
9306 if (!sel2)
9307 return NULL;
9308 }
9309 SELECT_LEX *sel1= unit->first_select();
9310 if (!sel1->next_select())
9311 unit= parsed_select_expr_start(sel1, sel2, unit_type, distinct);
9312 else
9313 unit= parsed_select_expr_cont(unit, sel2, unit_type, distinct, oracle);
9314 return unit;
9315 }
9316
9317
9318 /**
9319 Add query primary to a parenthesized query primary
9320 pruducing a new query expression body
9321 */
9322
9323 SELECT_LEX_UNIT *
add_primary_to_query_expression_body_ext_parens(SELECT_LEX_UNIT * unit,SELECT_LEX * sel,enum sub_select_type unit_type,bool distinct)9324 LEX::add_primary_to_query_expression_body_ext_parens(
9325 SELECT_LEX_UNIT *unit,
9326 SELECT_LEX *sel,
9327 enum sub_select_type unit_type,
9328 bool distinct)
9329 {
9330 SELECT_LEX *sel1= unit->first_select();
9331 if (unit->first_select()->next_select())
9332 {
9333 sel1= wrap_unit_into_derived(unit);
9334 if (!sel1)
9335 return NULL;
9336 if (!create_unit(sel1))
9337 return NULL;
9338 }
9339 SELECT_LEX *sel2= sel;
9340 if (sel->master_unit() && sel->master_unit()->first_select()->next_select())
9341 {
9342 sel2= wrap_unit_into_derived(sel->master_unit());
9343 if (!sel2)
9344 return NULL;
9345 }
9346 unit= parsed_select_expr_start(sel1, sel2, unit_type, distinct);
9347 return unit;
9348 }
9349
9350
9351 /**
9352 Process multi-operand query expression body
9353 */
9354
parsed_multi_operand_query_expression_body(SELECT_LEX_UNIT * unit)9355 bool LEX::parsed_multi_operand_query_expression_body(SELECT_LEX_UNIT *unit)
9356 {
9357 SELECT_LEX *first_in_nest=
9358 unit->pre_last_parse->next_select()->first_nested;
9359 if (first_in_nest->first_nested != first_in_nest)
9360 {
9361 /* There is a priority jump starting from first_in_nest */
9362 if (create_priority_nest(first_in_nest) == NULL)
9363 return true;
9364 unit->fix_distinct();
9365 }
9366 return false;
9367 }
9368
9369
9370 /**
9371 Add non-empty tail to a query expression body
9372 */
9373
add_tail_to_query_expression_body(SELECT_LEX_UNIT * unit,Lex_order_limit_lock * l)9374 SELECT_LEX_UNIT *LEX::add_tail_to_query_expression_body(SELECT_LEX_UNIT *unit,
9375 Lex_order_limit_lock *l)
9376 {
9377 DBUG_ASSERT(l != NULL);
9378 pop_select();
9379 SELECT_LEX *sel= unit->first_select()->next_select() ? unit->fake_select_lex :
9380 unit->first_select();
9381 l->set_to(sel);
9382 return unit;
9383 }
9384
9385
9386 /**
9387 Add non-empty tail to a parenthesized query primary
9388 */
9389
9390 SELECT_LEX_UNIT *
add_tail_to_query_expression_body_ext_parens(SELECT_LEX_UNIT * unit,Lex_order_limit_lock * l)9391 LEX::add_tail_to_query_expression_body_ext_parens(SELECT_LEX_UNIT *unit,
9392 Lex_order_limit_lock *l)
9393 {
9394 SELECT_LEX *sel= unit->first_select()->next_select() ? unit->fake_select_lex :
9395 unit->first_select();
9396
9397 DBUG_ASSERT(l != NULL);
9398
9399 pop_select();
9400 if (sel->is_set_query_expr_tail)
9401 {
9402 if (!l->order_list && !sel->explicit_limit)
9403 l->order_list= &sel->order_list;
9404 else
9405 {
9406 if (!unit)
9407 return NULL;
9408 sel= wrap_unit_into_derived(unit);
9409 if (!sel)
9410 return NULL;
9411 if (!create_unit(sel))
9412 return NULL;
9413 }
9414 }
9415 l->set_to(sel);
9416 return sel->master_unit();
9417 }
9418
9419
9420 /**
9421 Process subselect parsing
9422 */
9423
parsed_subselect(SELECT_LEX_UNIT * unit)9424 SELECT_LEX *LEX::parsed_subselect(SELECT_LEX_UNIT *unit)
9425 {
9426 if (clause_that_disallows_subselect)
9427 {
9428 my_error(ER_SUBQUERIES_NOT_SUPPORTED, MYF(0),
9429 clause_that_disallows_subselect);
9430 return NULL;
9431 }
9432
9433 // Add the subtree of subquery to the current SELECT_LEX
9434 SELECT_LEX *curr_sel= select_stack_head();
9435 DBUG_ASSERT(current_select == curr_sel ||
9436 (curr_sel == NULL && current_select == &builtin_select));
9437 if (curr_sel)
9438 {
9439 curr_sel->register_unit(unit, context_stack.head());
9440 curr_sel->add_statistics(unit);
9441 }
9442
9443 return unit->first_select();
9444 }
9445
9446
9447 /**
9448 Process INSERT-like select
9449 */
9450
parsed_insert_select(SELECT_LEX * first_select)9451 bool LEX::parsed_insert_select(SELECT_LEX *first_select)
9452 {
9453 if (sql_command == SQLCOM_INSERT ||
9454 sql_command == SQLCOM_REPLACE)
9455 {
9456 if (sql_command == SQLCOM_INSERT)
9457 sql_command= SQLCOM_INSERT_SELECT;
9458 else
9459 sql_command= SQLCOM_REPLACE_SELECT;
9460 }
9461 insert_select_hack(first_select);
9462 if (check_main_unit_semantics())
9463 return true;
9464
9465 // fix "main" select
9466 SELECT_LEX *blt __attribute__((unused))= pop_select();
9467 DBUG_ASSERT(blt == &builtin_select);
9468 push_select(first_select);
9469 return false;
9470 }
9471
9472
parsed_TVC_start()9473 bool LEX::parsed_TVC_start()
9474 {
9475 SELECT_LEX *sel;
9476 save_values_list_state();
9477 many_values.empty();
9478 insert_list= 0;
9479 if (!(sel= alloc_select(TRUE)) ||
9480 push_select(sel))
9481 return true;
9482 sel->init_select();
9483 sel->braces= FALSE; // just initialisation
9484 return false;
9485 }
9486
9487
parsed_TVC_end()9488 SELECT_LEX *LEX::parsed_TVC_end()
9489 {
9490 SELECT_LEX *res= pop_select(); // above TVC select
9491 if (!(res->tvc=
9492 new (thd->mem_root) table_value_constr(many_values,
9493 res,
9494 res->options)))
9495 return NULL;
9496 restore_values_list_state();
9497 return res;
9498 }
9499
9500
9501
parsed_derived_table(SELECT_LEX_UNIT * unit,int for_system_time,LEX_CSTRING * alias)9502 TABLE_LIST *LEX::parsed_derived_table(SELECT_LEX_UNIT *unit,
9503 int for_system_time,
9504 LEX_CSTRING *alias)
9505 {
9506 TABLE_LIST *res;
9507 derived_tables|= DERIVED_SUBQUERY;
9508 unit->first_select()->set_linkage(DERIVED_TABLE_TYPE);
9509
9510 // Add the subtree of subquery to the current SELECT_LEX
9511 SELECT_LEX *curr_sel= select_stack_head();
9512 DBUG_ASSERT(current_select == curr_sel ||
9513 (curr_sel == NULL && current_select == &builtin_select));
9514
9515 Table_ident *ti= new (thd->mem_root) Table_ident(unit);
9516 if (ti == NULL)
9517 return NULL;
9518 if (!(res= curr_sel->add_table_to_list(thd, ti, alias, 0,
9519 TL_READ, MDL_SHARED_READ)))
9520 return NULL;
9521 if (for_system_time)
9522 {
9523 res->vers_conditions= vers_conditions;
9524 }
9525 return res;
9526 }
9527
parsed_create_view(SELECT_LEX_UNIT * unit,int check)9528 bool LEX::parsed_create_view(SELECT_LEX_UNIT *unit, int check)
9529 {
9530 SQL_I_List<TABLE_LIST> *save= &first_select_lex()->table_list;
9531 if (set_main_unit(unit))
9532 return true;
9533 if (check_main_unit_semantics())
9534 return true;
9535 first_select_lex()->table_list.push_front(save);
9536 current_select= first_select_lex();
9537 size_t len= thd->m_parser_state->m_lip.get_cpp_ptr() -
9538 create_view->select.str;
9539 void *create_view_select= thd->memdup(create_view->select.str, len);
9540 create_view->select.length= len;
9541 create_view->select.str= (char *) create_view_select;
9542 size_t not_used;
9543 trim_whitespace(thd->charset(),
9544 &create_view->select, ¬_used);
9545 create_view->check= check;
9546 parsing_options.allows_variable= TRUE;
9547 return false;
9548 }
9549
select_finalize(st_select_lex_unit * expr)9550 bool LEX::select_finalize(st_select_lex_unit *expr)
9551 {
9552 sql_command= SQLCOM_SELECT;
9553 selects_allow_into= TRUE;
9554 selects_allow_procedure= TRUE;
9555 if (set_main_unit(expr))
9556 return true;
9557 return check_main_unit_semantics();
9558 }
9559
9560
select_finalize(st_select_lex_unit * expr,Lex_select_lock l)9561 bool LEX::select_finalize(st_select_lex_unit *expr, Lex_select_lock l)
9562 {
9563 return expr->set_lock_to_the_last_select(l) ||
9564 select_finalize(expr);
9565 }
9566
9567
9568 /*
9569 "IN" and "EXISTS" subselect can appear in two statement types:
9570
9571 1. Statements that can have table columns, such as SELECT, DELETE, UPDATE
9572 2. Statements that cannot have table columns, e.g:
9573 RETURN ((1) IN (SELECT * FROM t1))
9574 IF ((1) IN (SELECT * FROM t1))
9575
9576 Statements of the first type call master_select_push() in the beginning.
9577 In such case everything is properly linked.
9578
9579 Statements of the second type do not call mastr_select_push().
9580 Here we catch the second case and relink thd->lex->builtin_select and
9581 select_lex to properly point to each other.
9582
9583 QQ: Shouldn't subselects of other type also call relink_hack()?
9584 QQ: Can we do it at constructor time instead?
9585 */
9586
relink_hack(st_select_lex * select_lex)9587 void LEX::relink_hack(st_select_lex *select_lex)
9588 {
9589 if (!select_stack_top) // Statements of the second type
9590 {
9591 if (!select_lex->get_master()->get_master())
9592 ((st_select_lex *) select_lex->get_master())->
9593 set_master(&builtin_select);
9594 if (!builtin_select.get_slave())
9595 builtin_select.set_slave(select_lex->get_master());
9596 }
9597 }
9598
9599
set_lock_to_the_last_select(Lex_select_lock l)9600 bool SELECT_LEX_UNIT::set_lock_to_the_last_select(Lex_select_lock l)
9601 {
9602 if (l.defined_lock)
9603 {
9604 SELECT_LEX *sel= first_select();
9605 while (sel->next_select())
9606 sel= sel->next_select();
9607 if (sel->braces)
9608 {
9609 my_error(ER_WRONG_USAGE, MYF(0), "lock options",
9610 "SELECT in brackets");
9611 return TRUE;
9612 }
9613 l.set_to(sel);
9614 }
9615 return FALSE;
9616 }
9617
9618 /**
9619 Generate unique name for generated derived table for this SELECT
9620 */
9621
make_unique_derived_name(THD * thd,LEX_CSTRING * alias)9622 bool SELECT_LEX::make_unique_derived_name(THD *thd, LEX_CSTRING *alias)
9623 {
9624 // uint32 digits + two underscores + trailing '\0'
9625 char buff[MAX_INT_WIDTH + 2 + 1];
9626 alias->length= my_snprintf(buff, sizeof(buff), "__%u", select_number);
9627 alias->str= thd->strmake(buff, alias->length);
9628 return !alias->str;
9629 }
9630
9631
9632 /*
9633 Make a new sp_instr_stmt and set its m_query to a concatenation
9634 of two strings.
9635 */
new_sp_instr_stmt(THD * thd,const LEX_CSTRING & prefix,const LEX_CSTRING & suffix)9636 bool LEX::new_sp_instr_stmt(THD *thd,
9637 const LEX_CSTRING &prefix,
9638 const LEX_CSTRING &suffix)
9639 {
9640 LEX_STRING qbuff;
9641 sp_instr_stmt *i;
9642
9643 if (!(i= new (thd->mem_root) sp_instr_stmt(sphead->instructions(),
9644 spcont, this)))
9645 return true;
9646
9647 qbuff.length= prefix.length + suffix.length;
9648 if (!(qbuff.str= (char*) alloc_root(thd->mem_root, qbuff.length + 1)))
9649 return true;
9650 if (prefix.length)
9651 memcpy(qbuff.str, prefix.str, prefix.length);
9652 strmake(qbuff.str + prefix.length, suffix.str, suffix.length);
9653 i->m_query= qbuff;
9654 return sphead->add_instr(i);
9655 }
9656
9657
sp_proc_stmt_statement_finalize_buf(THD * thd,const LEX_CSTRING & qbuf)9658 bool LEX::sp_proc_stmt_statement_finalize_buf(THD *thd, const LEX_CSTRING &qbuf)
9659 {
9660 sphead->m_flags|= sp_get_flags_for_command(this);
9661 /* "USE db" doesn't work in a procedure */
9662 if (unlikely(sql_command == SQLCOM_CHANGE_DB))
9663 {
9664 my_error(ER_SP_BADSTATEMENT, MYF(0), "USE");
9665 return true;
9666 }
9667 /*
9668 Don't add an instruction for SET statements, since all
9669 instructions for them were already added during processing
9670 of "set" rule.
9671 */
9672 DBUG_ASSERT(sql_command != SQLCOM_SET_OPTION || var_list.is_empty());
9673 if (sql_command != SQLCOM_SET_OPTION)
9674 return new_sp_instr_stmt(thd, empty_clex_str, qbuf);
9675 return false;
9676 }
9677
9678
sp_proc_stmt_statement_finalize(THD * thd,bool no_lookahead)9679 bool LEX::sp_proc_stmt_statement_finalize(THD *thd, bool no_lookahead)
9680 {
9681 // Extract the query statement from the tokenizer
9682 Lex_input_stream *lip= &thd->m_parser_state->m_lip;
9683 Lex_cstring qbuf(sphead->m_tmp_query, no_lookahead ? lip->get_ptr() :
9684 lip->get_tok_start());
9685 return LEX::sp_proc_stmt_statement_finalize_buf(thd, qbuf);
9686 }
9687
9688
9689 /**
9690 @brief
9691 Extract the condition that can be pushed into WHERE clause
9692
9693 @param thd the thread handle
9694 @param cond the condition from which to extract a pushed condition
9695 @param remaining_cond IN/OUT the condition that will remain of cond after
9696 the extraction
9697 @param transformer the transformer callback function to be
9698 applied to the fields of the condition so it
9699 can be pushed`
9700 @param arg parameter to be passed to the transformer
9701
9702 @details
9703 This function builds the most restrictive condition depending only on
9704 the fields used in the GROUP BY of this SELECT. These fields were
9705 collected before in grouping_tmp_fields list of this SELECT.
9706
9707 First this method checks if this SELECT doesn't have any aggregation
9708 functions and has no GROUP BY clause. If so cond can be entirely pushed
9709 into WHERE.
9710
9711 Otherwise the method checks if there is a condition depending only on
9712 grouping fields that can be extracted from cond.
9713
9714 The condition that can be pushed into WHERE should be transformed.
9715 It is done by transformer.
9716
9717 The extracted condition is saved in cond_pushed_into_where of this select.
9718 cond can remain un empty after the extraction of the condition that can be
9719 pushed into WHERE. It is saved in remaining_cond.
9720
9721 @note
9722 This method is called for pushdown conditions into materialized
9723 derived tables/views optimization.
9724 Item::derived_field_transformer_for_where is passed as the actual
9725 callback function.
9726 Also it is called for pushdown into materialized IN subqueries.
9727 Item::in_subq_field_transformer_for_where is passed as the actual
9728 callback function.
9729 */
9730
pushdown_cond_into_where_clause(THD * thd,Item * cond,Item ** remaining_cond,Item_transformer transformer,uchar * arg)9731 void st_select_lex::pushdown_cond_into_where_clause(THD *thd, Item *cond,
9732 Item **remaining_cond,
9733 Item_transformer transformer,
9734 uchar *arg)
9735 {
9736 if (!cond_pushdown_is_allowed())
9737 return;
9738 thd->lex->current_select= this;
9739 if (have_window_funcs())
9740 {
9741 Item *cond_over_partition_fields;
9742 check_cond_extraction_for_grouping_fields(thd, cond);
9743 cond_over_partition_fields=
9744 build_cond_for_grouping_fields(thd, cond, true);
9745 if (cond_over_partition_fields)
9746 cond_over_partition_fields= cond_over_partition_fields->transform(thd,
9747 &Item::grouping_field_transformer_for_where,
9748 (uchar*) this);
9749 if (cond_over_partition_fields)
9750 {
9751 cond_over_partition_fields->walk(
9752 &Item::cleanup_excluding_const_fields_processor, 0, 0);
9753 cond_pushed_into_where= cond_over_partition_fields;
9754 }
9755
9756 return;
9757 }
9758
9759 if (!join->group_list && !with_sum_func)
9760 {
9761 cond= transform_condition_or_part(thd, cond, transformer, arg);
9762 if (cond)
9763 {
9764 cond->walk(
9765 &Item::cleanup_excluding_const_fields_processor, 0, 0);
9766 cond_pushed_into_where= cond;
9767 }
9768
9769 return;
9770 }
9771
9772 /*
9773 Figure out what can be extracted from cond and pushed into
9774 the WHERE clause of this select.
9775 */
9776 Item *cond_over_grouping_fields;
9777 check_cond_extraction_for_grouping_fields(thd, cond);
9778 cond_over_grouping_fields=
9779 build_cond_for_grouping_fields(thd, cond, true);
9780
9781 /*
9782 Transform references to the columns of condition that can be pushed
9783 into WHERE so it can be pushed.
9784 */
9785 if (cond_over_grouping_fields)
9786 {
9787 cond_over_grouping_fields=
9788 transform_condition_or_part(thd, cond_over_grouping_fields,
9789 &Item::grouping_field_transformer_for_where,
9790 (uchar*) this);
9791 }
9792
9793 if (cond_over_grouping_fields)
9794 {
9795
9796 /*
9797 Remove top conjuncts in cond that has been pushed into the WHERE
9798 clause of this select
9799 */
9800 cond= remove_pushed_top_conjuncts(thd, cond);
9801
9802 cond_over_grouping_fields->walk(
9803 &Item::cleanup_excluding_const_fields_processor, 0, 0);
9804 cond_pushed_into_where= cond_over_grouping_fields;
9805 }
9806
9807 *remaining_cond= cond;
9808 }
9809
9810
9811 /**
9812 @brief
9813 Mark OR-conditions as non-pushable to avoid repeatable pushdown
9814
9815 @param cond the processed condition
9816
9817 @details
9818 Consider pushdown into the materialized derived table/view.
9819 Consider OR condition that can be pushed into HAVING and some
9820 parts of this OR condition that can be pushed into WHERE.
9821
9822 On example:
9823
9824 SELECT *
9825 FROM t1,
9826 (
9827 SELECT a,MAX(c) AS m_c
9828 GROUP BY a
9829 ) AS dt
9830 WHERE ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3)) AND
9831 (t1.a=v1.a);
9832
9833
9834 Here ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3)) or1
9835 can be pushed down into the HAVING of the materialized
9836 derived table dt.
9837
9838 (dt.a>2) OR (dt.a<3) part of or1 depends only on grouping fields
9839 of dt and can be pushed into WHERE.
9840
9841 As a result:
9842
9843 SELECT *
9844 FROM t1,
9845 (
9846 SELECT a,MAX(c) AS m_c
9847 WHERE (dt.a>2) OR (dt.a<3)
9848 GROUP BY a
9849 HAVING ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3))
9850 ) AS dt
9851 WHERE ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3)) AND
9852 (t1.a=v1.a);
9853
9854
9855 Here (dt.a>2) OR (dt.a<3) also remains in HAVING of dt.
9856 When SELECT that defines df is processed HAVING pushdown optimization
9857 is made. In HAVING pushdown optimization it will extract
9858 (dt.a>2) OR (dt.a<3) condition from or1 again and push it into WHERE.
9859 This will cause duplicate conditions in WHERE of dt.
9860
9861 To avoid repeatable pushdown such OR conditions as or1 describen
9862 above are marked with NO_EXTRACTION_FL.
9863
9864 @note
9865 This method is called for pushdown into materialized
9866 derived tables/views/IN subqueries optimization.
9867 */
9868
mark_or_conds_to_avoid_pushdown(Item * cond)9869 void mark_or_conds_to_avoid_pushdown(Item *cond)
9870 {
9871 if (cond->type() == Item::COND_ITEM &&
9872 ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
9873 {
9874 List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
9875 Item *item;
9876 while ((item=li++))
9877 {
9878 if (item->type() == Item::COND_ITEM &&
9879 ((Item_cond*) item)->functype() == Item_func::COND_OR_FUNC)
9880 item->set_extraction_flag(NO_EXTRACTION_FL);
9881 }
9882 }
9883 else if (cond->type() == Item::COND_ITEM &&
9884 ((Item_cond*) cond)->functype() == Item_func::COND_OR_FUNC)
9885 cond->set_extraction_flag(NO_EXTRACTION_FL);
9886 }
9887
9888 /**
9889 @brief
9890 Get condition that can be pushed from HAVING into WHERE
9891
9892 @param thd the thread handle
9893 @param cond the condition from which to extract the condition
9894
9895 @details
9896 The method collects in attach_to_conds list conditions from cond
9897 that can be pushed from HAVING into WHERE.
9898
9899 Conditions that can be pushed were marked with FULL_EXTRACTION_FL in
9900 check_cond_extraction_for_grouping_fields() method.
9901 Conditions that can't be pushed were marked with NO_EXTRACTION_FL.
9902 Conditions which parts can be pushed weren't marked.
9903
9904 There are two types of conditions that can be pushed:
9905 1. Condition that can be simply moved from HAVING
9906 (if cond is marked with FULL_EXTRACTION_FL or
9907 cond is an AND condition and some of its parts are marked with
9908 FULL_EXTRACTION_FL)
9909 In this case condition is transformed and pushed into attach_to_conds
9910 list.
9911 2. Part of some other condition c1 that can't be entirely pushed
9912 (if с1 isn't marked with any flag).
9913
9914 For example:
9915
9916 SELECT t1.a,MAX(t1.b),t1.c
9917 FROM t1
9918 GROUP BY t1.a
9919 HAVING ((t1.a > 5) AND (t1.c < 3)) OR (t1.a = 3);
9920
9921 Here (t1.a > 5) OR (t1.a = 3) from HAVING can be pushed into WHERE.
9922
9923 In this case build_pushable_cond() is called for c1.
9924 This method builds a clone of the c1 part that can be pushed.
9925
9926 Transformation mentioned above is made with multiple_equality_transformer
9927 transformer. It transforms all multiple equalities in the extracted
9928 condition into the set of equalities.
9929
9930 @note
9931 Conditions that can be pushed are collected in attach_to_conds in this way:
9932 1. if cond is an AND condition its parts that can be pushed into WHERE
9933 are added to attach_to_conds list separately.
9934 2. in all other cases conditions are pushed into the list entirely.
9935
9936 @retval
9937 true - if an error occurs
9938 false - otherwise
9939 */
9940
9941 bool
build_pushable_cond_for_having_pushdown(THD * thd,Item * cond)9942 st_select_lex::build_pushable_cond_for_having_pushdown(THD *thd, Item *cond)
9943 {
9944 List<Item> equalities;
9945
9946 /* Condition can't be pushed */
9947 if (cond->get_extraction_flag() == NO_EXTRACTION_FL)
9948 return false;
9949
9950 /**
9951 Condition can be pushed entirely.
9952 Transform its multiple equalities and add to attach_to_conds list.
9953 */
9954 if (cond->get_extraction_flag() == FULL_EXTRACTION_FL)
9955 {
9956 Item *result= cond->transform(thd,
9957 &Item::multiple_equality_transformer,
9958 (uchar *)this);
9959 if (!result)
9960 return true;
9961 if (result->type() == Item::COND_ITEM &&
9962 ((Item_cond*) result)->functype() == Item_func::COND_AND_FUNC)
9963 {
9964 List_iterator<Item> li(*((Item_cond*) result)->argument_list());
9965 Item *item;
9966 while ((item= li++))
9967 {
9968 if (attach_to_conds.push_back(item, thd->mem_root))
9969 return true;
9970 }
9971 }
9972 else
9973 {
9974 if (attach_to_conds.push_back(result, thd->mem_root))
9975 return true;
9976 }
9977 return false;
9978 }
9979
9980 /**
9981 There is no flag set for this condition. It means that some
9982 part of this condition can be pushed.
9983 */
9984 if (cond->type() != Item::COND_ITEM)
9985 return false;
9986
9987 if (((Item_cond *)cond)->functype() != Item_cond::COND_AND_FUNC)
9988 {
9989 /*
9990 cond is not a conjunctive formula and it cannot be pushed into WHERE.
9991 Try to extract a formula that can be pushed.
9992 */
9993 Item *fix= cond->build_pushable_cond(thd, 0, 0);
9994 if (!fix)
9995 return false;
9996 if (attach_to_conds.push_back(fix, thd->mem_root))
9997 return true;
9998 }
9999 else
10000 {
10001 List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
10002 Item *item;
10003 while ((item=li++))
10004 {
10005 if (item->get_extraction_flag() == NO_EXTRACTION_FL)
10006 continue;
10007 else if (item->get_extraction_flag() == FULL_EXTRACTION_FL)
10008 {
10009 Item *result= item->transform(thd,
10010 &Item::multiple_equality_transformer,
10011 (uchar *)item);
10012 if (!result)
10013 return true;
10014 if (result->type() == Item::COND_ITEM &&
10015 ((Item_cond*) result)->functype() == Item_func::COND_AND_FUNC)
10016 {
10017 List_iterator<Item> li(*((Item_cond*) result)->argument_list());
10018 Item *item;
10019 while ((item=li++))
10020 {
10021 if (attach_to_conds.push_back(item, thd->mem_root))
10022 return true;
10023 }
10024 }
10025 else
10026 {
10027 if (attach_to_conds.push_back(result, thd->mem_root))
10028 return true;
10029 }
10030 }
10031 else
10032 {
10033 Item *fix= item->build_pushable_cond(thd, 0, 0);
10034 if (!fix)
10035 continue;
10036 if (attach_to_conds.push_back(fix, thd->mem_root))
10037 return true;
10038 }
10039 }
10040 }
10041 return false;
10042 }
10043
10044
10045 /**
10046 Check if item is equal to some field in Field_pair 'field_pair'
10047 from 'pair_list' and return found 'field_pair' if it exists.
10048 */
10049
get_corresponding_field_pair(Item * item,List<Field_pair> pair_list)10050 Field_pair *get_corresponding_field_pair(Item *item,
10051 List<Field_pair> pair_list)
10052 {
10053 DBUG_ASSERT(item->type() == Item::FIELD_ITEM ||
10054 (item->type() == Item::REF_ITEM &&
10055 ((((Item_ref *) item)->ref_type() == Item_ref::VIEW_REF) ||
10056 (((Item_ref *) item)->ref_type() == Item_ref::REF))));
10057
10058 List_iterator<Field_pair> it(pair_list);
10059 Field_pair *field_pair;
10060 Item_field *field_item= (Item_field *) (item->real_item());
10061 while ((field_pair= it++))
10062 {
10063 if (field_item->field == field_pair->field)
10064 return field_pair;
10065 }
10066 return NULL;
10067 }
10068
10069
10070 /**
10071 @brief
10072 Collect fields from multiple equalities which are equal to grouping
10073
10074 @param thd the thread handle
10075
10076 @details
10077 This method checks if multiple equalities of the WHERE clause contain
10078 fields from GROUP BY of this SELECT. If so all fields of such multiple
10079 equalities are collected in grouping_tmp_fields list without repetitions.
10080
10081 @retval
10082 true - if an error occurs
10083 false - otherwise
10084 */
10085
collect_fields_equal_to_grouping(THD * thd)10086 bool st_select_lex::collect_fields_equal_to_grouping(THD *thd)
10087 {
10088 if (!join->cond_equal || join->cond_equal->is_empty())
10089 return false;
10090
10091 List_iterator_fast<Item_equal> li(join->cond_equal->current_level);
10092 Item_equal *item_equal;
10093
10094 while ((item_equal= li++))
10095 {
10096 Item_equal_fields_iterator it(*item_equal);
10097 Item *item;
10098 while ((item= it++))
10099 {
10100 if (get_corresponding_field_pair(item, grouping_tmp_fields))
10101 break;
10102 }
10103 if (!item)
10104 break;
10105
10106 it.rewind();
10107 while ((item= it++))
10108 {
10109 if (get_corresponding_field_pair(item, grouping_tmp_fields))
10110 continue;
10111 Field_pair *grouping_tmp_field=
10112 new Field_pair(((Item_field *)item->real_item())->field, item);
10113 if (grouping_tmp_fields.push_back(grouping_tmp_field, thd->mem_root))
10114 return true;
10115 }
10116 }
10117 return false;
10118 }
10119
10120
10121 /**
10122 @brief
10123 Remove marked top conjuncts of HAVING for having pushdown
10124
10125 @param thd the thread handle
10126 @param cond the condition which subformulas are to be removed
10127
10128 @details
10129 This method removes from cond all subformulas that can be moved from HAVING
10130 into WHERE.
10131
10132 @retval
10133 condition without removed subformulas
10134 0 if the whole 'cond' is removed
10135 */
10136
remove_pushed_top_conjuncts_for_having(THD * thd,Item * cond)10137 Item *remove_pushed_top_conjuncts_for_having(THD *thd, Item *cond)
10138 {
10139 /* Nothing to extract */
10140 if (cond->get_extraction_flag() == NO_EXTRACTION_FL)
10141 {
10142 cond->clear_extraction_flag();
10143 return cond;
10144 }
10145 /* cond can be pushed in WHERE entirely */
10146 if (cond->get_extraction_flag() == FULL_EXTRACTION_FL)
10147 {
10148 cond->clear_extraction_flag();
10149 return 0;
10150 }
10151
10152 /* Some parts of cond can be pushed */
10153 if (cond->type() == Item::COND_ITEM &&
10154 ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
10155 {
10156 List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
10157 Item *item;
10158 while ((item=li++))
10159 {
10160 if (item->get_extraction_flag() == NO_EXTRACTION_FL)
10161 item->clear_extraction_flag();
10162 else if (item->get_extraction_flag() == FULL_EXTRACTION_FL)
10163 {
10164 if (item->type() == Item::FUNC_ITEM &&
10165 ((Item_func*) item)->functype() == Item_func::MULT_EQUAL_FUNC)
10166 item->set_extraction_flag(DELETION_FL);
10167 else
10168 {
10169 item->clear_extraction_flag();
10170 li.remove();
10171 }
10172 }
10173 }
10174 switch (((Item_cond*) cond)->argument_list()->elements)
10175 {
10176 case 0:
10177 return 0;
10178 case 1:
10179 return (((Item_cond*) cond)->argument_list()->head());
10180 default:
10181 return cond;
10182 }
10183 }
10184 return cond;
10185 }
10186
10187
10188 /**
10189 @brief
10190 Extract condition that can be pushed from HAVING into WHERE
10191
10192 @param thd the thread handle
10193 @param having the HAVING clause of this select
10194 @param having_equal multiple equalities of HAVING
10195
10196 @details
10197 This method builds a set of conditions dependent only on
10198 fields used in the GROUP BY of this select (directly or indirectly
10199 through equalities). These conditions are extracted from the HAVING
10200 clause of this select.
10201 The method saves these conditions into attach_to_conds list and removes
10202 from HAVING conditions that can be entirely pushed into WHERE.
10203
10204 Example of the HAVING pushdown transformation:
10205
10206 SELECT t1.a,MAX(t1.b)
10207 FROM t1
10208 GROUP BY t1.a
10209 HAVING (t1.a>2) AND (MAX(c)>12);
10210
10211 =>
10212
10213 SELECT t1.a,MAX(t1.b)
10214 FROM t1
10215 WHERE (t1.a>2)
10216 GROUP BY t1.a
10217 HAVING (MAX(c)>12);
10218
10219 In this method (t1.a>2) is not attached to the WHERE clause.
10220 It is pushed into the attach_to_conds list to be attached to
10221 the WHERE clause later.
10222
10223 In details:
10224 1. Collect fields used in the GROUP BY grouping_fields of this SELECT
10225 2. Collect fields equal to grouping_fields from the WHERE clause
10226 of this SELECT and add them to the grouping_fields list.
10227 3. Extract the most restrictive condition from the HAVING clause of this
10228 select that depends only on the grouping fields (directly or indirectly
10229 through equality).
10230 If the extracted condition is an AND condition it is transformed into a
10231 list of all its conjuncts saved in attach_to_conds. Otherwise,
10232 the condition is put into attach_to_conds as the only its element.
10233 4. Remove conditions from HAVING clause that can be entirely pushed
10234 into WHERE.
10235 Multiple equalities are not removed but marked with DELETION_FL flag.
10236 They will be deleted later in substitite_for_best_equal_field() called
10237 for the HAVING condition.
10238 5. Unwrap fields wrapped in Item_ref wrappers contained in the condition
10239 of attach_to_conds so the condition could be pushed into WHERE.
10240
10241 @note
10242 This method is similar to st_select_lex::pushdown_cond_into_where_clause().
10243
10244 @retval TRUE if an error occurs
10245 @retval FALSE otherwise
10246 */
10247
pushdown_from_having_into_where(THD * thd,Item * having)10248 Item *st_select_lex::pushdown_from_having_into_where(THD *thd, Item *having)
10249 {
10250 if (!having || !group_list.first)
10251 return having;
10252 if (!cond_pushdown_is_allowed())
10253 return having;
10254
10255 st_select_lex *save_curr_select= thd->lex->current_select;
10256 thd->lex->current_select= this;
10257
10258 /*
10259 1. Collect fields used in the GROUP BY grouping fields of this SELECT
10260 2. Collect fields equal to grouping_fields from the WHERE clause
10261 of this SELECT and add them to the grouping fields list.
10262 */
10263 if (collect_grouping_fields(thd) ||
10264 collect_fields_equal_to_grouping(thd))
10265 return having;
10266
10267 /*
10268 3. Extract the most restrictive condition from the HAVING clause of this
10269 select that depends only on the grouping fields (directly or indirectly
10270 through equality).
10271 If the extracted condition is an AND condition it is transformed into a
10272 list of all its conjuncts saved in attach_to_conds. Otherwise,
10273 the condition is put into attach_to_conds as the only its element.
10274 */
10275 List_iterator_fast<Item> it(attach_to_conds);
10276 Item *item;
10277 check_cond_extraction_for_grouping_fields(thd, having);
10278 if (build_pushable_cond_for_having_pushdown(thd, having))
10279 {
10280 attach_to_conds.empty();
10281 goto exit;
10282 }
10283 if (!attach_to_conds.elements)
10284 goto exit;
10285
10286 /*
10287 4. Remove conditions from HAVING clause that can be entirely pushed
10288 into WHERE.
10289 Multiple equalities are not removed but marked with DELETION_FL flag.
10290 They will be deleted later in substitite_for_best_equal_field() called
10291 for the HAVING condition.
10292 */
10293 having= remove_pushed_top_conjuncts_for_having(thd, having);
10294
10295 /*
10296 Change join->cond_equal which points to the multiple equalities of
10297 the top level of HAVING.
10298 Removal of AND conditions may leave only one conjunct in HAVING.
10299
10300 Example 1:
10301 SELECT *
10302 FROM t1
10303 GROUP BY t1.a
10304 (t1.a < 2) AND (t1.b = 2)
10305
10306 (t1.a < 2) is pushed into WHERE.
10307 join->cond_equal should point on (t1.b = 2) multiple equality now.
10308
10309 Example 2:
10310 SELECT *
10311 FROM t1
10312 GROUP BY t1.a
10313 (t1.a = 2) AND (t1.b < 2)
10314
10315 (t1.a = 2) is pushed into WHERE.
10316 join->cond_equal should be NULL now.
10317 */
10318 if (having &&
10319 having->type() == Item::FUNC_ITEM &&
10320 ((Item_func*) having)->functype() == Item_func::MULT_EQUAL_FUNC)
10321 join->having_equal= new (thd->mem_root) COND_EQUAL((Item_equal *)having,
10322 thd->mem_root);
10323 else if (!having ||
10324 having->type() != Item::COND_ITEM ||
10325 ((Item_cond *)having)->functype() != Item_cond::COND_AND_FUNC)
10326 join->having_equal= 0;
10327
10328 /*
10329 5. Unwrap fields wrapped in Item_ref wrappers contained in the condition
10330 of attach_to_conds so the condition could be pushed into WHERE.
10331 */
10332 it.rewind();
10333 while ((item=it++))
10334 {
10335 item= item->transform(thd,
10336 &Item::field_transformer_for_having_pushdown,
10337 (uchar *)this);
10338
10339 if (item->walk(&Item::cleanup_excluding_immutables_processor, 0, STOP_PTR)
10340 || item->fix_fields(thd, NULL))
10341 {
10342 attach_to_conds.empty();
10343 goto exit;
10344 }
10345 }
10346 exit:
10347 thd->lex->current_select= save_curr_select;
10348 return having;
10349 }
10350
10351
stmt_install_plugin(const DDL_options_st & opt,const Lex_ident_sys_st & name,const LEX_CSTRING & soname)10352 bool LEX::stmt_install_plugin(const DDL_options_st &opt,
10353 const Lex_ident_sys_st &name,
10354 const LEX_CSTRING &soname)
10355 {
10356 create_info.init();
10357 if (add_create_options_with_check(opt))
10358 return true;
10359 sql_command= SQLCOM_INSTALL_PLUGIN;
10360 comment= name;
10361 ident= soname;
10362 return false;
10363 }
10364
10365
stmt_install_plugin(const LEX_CSTRING & soname)10366 void LEX::stmt_install_plugin(const LEX_CSTRING &soname)
10367 {
10368 sql_command= SQLCOM_INSTALL_PLUGIN;
10369 comment= null_clex_str;
10370 ident= soname;
10371 }
10372
10373
stmt_uninstall_plugin_by_name(const DDL_options_st & opt,const Lex_ident_sys_st & name)10374 bool LEX::stmt_uninstall_plugin_by_name(const DDL_options_st &opt,
10375 const Lex_ident_sys_st &name)
10376 {
10377 check_opt.init();
10378 if (add_create_options_with_check(opt))
10379 return true;
10380 sql_command= SQLCOM_UNINSTALL_PLUGIN;
10381 comment= name;
10382 ident= null_clex_str;
10383 return false;
10384 }
10385
10386
stmt_uninstall_plugin_by_soname(const DDL_options_st & opt,const LEX_CSTRING & soname)10387 bool LEX::stmt_uninstall_plugin_by_soname(const DDL_options_st &opt,
10388 const LEX_CSTRING &soname)
10389 {
10390 check_opt.init();
10391 if (add_create_options_with_check(opt))
10392 return true;
10393 sql_command= SQLCOM_UNINSTALL_PLUGIN;
10394 comment= null_clex_str;
10395 ident= soname;
10396 return false;
10397 }
10398
10399
stmt_prepare_validate(const char * stmt_type)10400 bool LEX::stmt_prepare_validate(const char *stmt_type)
10401 {
10402 if (unlikely(table_or_sp_used()))
10403 {
10404 my_error(ER_SUBQUERIES_NOT_SUPPORTED, MYF(0), stmt_type);
10405 return true;
10406 }
10407 return check_main_unit_semantics();
10408 }
10409
10410
stmt_prepare(const Lex_ident_sys_st & ident,Item * code)10411 bool LEX::stmt_prepare(const Lex_ident_sys_st &ident, Item *code)
10412 {
10413 sql_command= SQLCOM_PREPARE;
10414 if (stmt_prepare_validate("PREPARE..FROM"))
10415 return true;
10416 prepared_stmt.set(ident, code, NULL);
10417 return false;
10418 }
10419
10420
stmt_execute_immediate(Item * code,List<Item> * params)10421 bool LEX::stmt_execute_immediate(Item *code, List<Item> *params)
10422 {
10423 sql_command= SQLCOM_EXECUTE_IMMEDIATE;
10424 if (stmt_prepare_validate("EXECUTE IMMEDIATE"))
10425 return true;
10426 static const Lex_ident_sys immediate(STRING_WITH_LEN("IMMEDIATE"));
10427 prepared_stmt.set(immediate, code, params);
10428 return false;
10429 }
10430
10431
stmt_execute(const Lex_ident_sys_st & ident,List<Item> * params)10432 bool LEX::stmt_execute(const Lex_ident_sys_st &ident, List<Item> *params)
10433 {
10434 sql_command= SQLCOM_EXECUTE;
10435 prepared_stmt.set(ident, NULL, params);
10436 return stmt_prepare_validate("EXECUTE..USING");
10437 }
10438
10439
stmt_deallocate_prepare(const Lex_ident_sys_st & ident)10440 void LEX::stmt_deallocate_prepare(const Lex_ident_sys_st &ident)
10441 {
10442 sql_command= SQLCOM_DEALLOCATE_PREPARE;
10443 prepared_stmt.set(ident, NULL, NULL);
10444 }
10445
10446
stmt_alter_table_exchange_partition(Table_ident * table)10447 bool LEX::stmt_alter_table_exchange_partition(Table_ident *table)
10448 {
10449 DBUG_ASSERT(sql_command == SQLCOM_ALTER_TABLE);
10450 first_select_lex()->db= table->db;
10451 if (first_select_lex()->db.str == NULL &&
10452 copy_db_to(&first_select_lex()->db))
10453 return true;
10454 name= table->table;
10455 alter_info.partition_flags|= ALTER_PARTITION_EXCHANGE;
10456 if (!first_select_lex()->add_table_to_list(thd, table, NULL,
10457 TL_OPTION_UPDATING,
10458 TL_READ_NO_INSERT,
10459 MDL_SHARED_NO_WRITE))
10460 return true;
10461 DBUG_ASSERT(!m_sql_cmd);
10462 m_sql_cmd= new (thd->mem_root) Sql_cmd_alter_table_exchange_partition();
10463 return m_sql_cmd == NULL;
10464 }
10465
10466
stmt_purge_to(const LEX_CSTRING & to)10467 void LEX::stmt_purge_to(const LEX_CSTRING &to)
10468 {
10469 type= 0;
10470 sql_command= SQLCOM_PURGE;
10471 to_log= to.str;
10472 }
10473
10474
stmt_purge_before(Item * item)10475 bool LEX::stmt_purge_before(Item *item)
10476 {
10477 type= 0;
10478 sql_command= SQLCOM_PURGE_BEFORE;
10479 value_list.empty();
10480 value_list.push_front(item, thd->mem_root);
10481 return check_main_unit_semantics();
10482 }
10483
10484
stmt_create_udf_function(const DDL_options_st & options,enum_sp_aggregate_type agg_type,const Lex_ident_sys_st & name,Item_result return_type,const LEX_CSTRING & soname)10485 bool LEX::stmt_create_udf_function(const DDL_options_st &options,
10486 enum_sp_aggregate_type agg_type,
10487 const Lex_ident_sys_st &name,
10488 Item_result return_type,
10489 const LEX_CSTRING &soname)
10490 {
10491 if (stmt_create_function_start(options))
10492 return true;
10493
10494 if (unlikely(is_native_function(thd, &name)))
10495 {
10496 my_error(ER_NATIVE_FCT_NAME_COLLISION, MYF(0), name.str);
10497 return true;
10498 }
10499 sql_command= SQLCOM_CREATE_FUNCTION;
10500 udf.name= name;
10501 udf.returns= return_type;
10502 udf.dl= soname.str;
10503 udf.type= agg_type == GROUP_AGGREGATE ? UDFTYPE_AGGREGATE :
10504 UDFTYPE_FUNCTION;
10505 stmt_create_routine_finalize();
10506 return false;
10507 }
10508
10509
stmt_create_stored_function_start(const DDL_options_st & options,enum_sp_aggregate_type agg_type,const sp_name * spname)10510 bool LEX::stmt_create_stored_function_start(const DDL_options_st &options,
10511 enum_sp_aggregate_type agg_type,
10512 const sp_name *spname)
10513 {
10514 if (stmt_create_function_start(options) ||
10515 unlikely(!make_sp_head_no_recursive(thd, spname,
10516 &sp_handler_function, agg_type)))
10517 return true;
10518 return false;
10519 }
10520
10521
row_field_name(THD * thd,const Lex_ident_sys_st & name)10522 Spvar_definition *LEX::row_field_name(THD *thd, const Lex_ident_sys_st &name)
10523 {
10524 Spvar_definition *res;
10525 if (unlikely(check_string_char_length(&name, 0, NAME_CHAR_LEN,
10526 system_charset_info, 1)))
10527 {
10528 my_error(ER_TOO_LONG_IDENT, MYF(0), name.str);
10529 return NULL;
10530 }
10531 if (unlikely(!(res= new (thd->mem_root) Spvar_definition())))
10532 return NULL;
10533 init_last_field(res, &name, thd->variables.collation_database);
10534 return res;
10535 }
10536
10537
map_data_type(const Lex_ident_sys_st & schema_name,Lex_field_type_st * type) const10538 bool LEX::map_data_type(const Lex_ident_sys_st &schema_name,
10539 Lex_field_type_st *type) const
10540 {
10541 const Schema *schema= schema_name.str ?
10542 Schema::find_by_name(schema_name) :
10543 Schema::find_implied(thd);
10544 if (!schema)
10545 {
10546 char buf[128];
10547 const Name type_name= type->type_handler()->name();
10548 my_snprintf(buf, sizeof(buf), "%.*s.%.*s",
10549 (int) schema_name.length, schema_name.str,
10550 (int) type_name.length(), type_name.ptr());
10551 #if MYSQL_VERSION_ID > 100500
10552 #error Please remove the old code
10553 my_error(ER_UNKNOWN_DATA_TYPE, MYF(0), buf);
10554 #else
10555 my_printf_error(ER_UNKNOWN_ERROR, "Unknown data type: '%-.64s'",
10556 MYF(0), buf);
10557 #endif
10558 return true;
10559 }
10560 const Type_handler *mapped= schema->map_data_type(thd, type->type_handler());
10561 type->set_handler(mapped);
10562 return false;
10563 }
10564