1/* Copyright (c) 2000, 2014, Oracle and/or its affiliates.
2 Copyright (c) 2009, 2018, MariaDB Corporation
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; version 2 of the License.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
16
17
18/* 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_partition.h"
35
36
37void LEX::parse_error(uint err_number)
38{
39 thd->parse_error(err_number);
40}
41
42
43/**
44 LEX_STRING constant for null-string to be used in parser and other places.
45*/
46const LEX_STRING empty_lex_str= {(char *) "", 0};
47const LEX_CSTRING null_clex_str= {NULL, 0};
48const LEX_CSTRING empty_clex_str= {"", 0};
49const LEX_CSTRING star_clex_str= {"*", 1};
50const LEX_CSTRING param_clex_str= {"?", 1};
51
52/**
53 @note The order of the elements of this array must correspond to
54 the order of elements in enum_binlog_stmt_unsafe.
55*/
56const int
57Query_tables_list::binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT] =
58{
59 ER_BINLOG_UNSAFE_LIMIT,
60 ER_BINLOG_UNSAFE_INSERT_DELAYED,
61 ER_BINLOG_UNSAFE_SYSTEM_TABLE,
62 ER_BINLOG_UNSAFE_AUTOINC_COLUMNS,
63 ER_BINLOG_UNSAFE_UDF,
64 ER_BINLOG_UNSAFE_SYSTEM_VARIABLE,
65 ER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
66 ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS,
67 ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
68 ER_BINLOG_UNSAFE_MIXED_STATEMENT,
69 ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT,
70 ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE,
71 ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT,
72 ER_BINLOG_UNSAFE_REPLACE_SELECT,
73 ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT,
74 ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT,
75 ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC,
76 ER_BINLOG_UNSAFE_UPDATE_IGNORE,
77 ER_BINLOG_UNSAFE_INSERT_TWO_KEYS,
78 ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST
79};
80
81
82/* Longest standard keyword name */
83
84#define TOCK_NAME_LENGTH 24
85
86/*
87 The following data is based on the latin1 character set, and is only
88 used when comparing keywords
89*/
90
91static uchar to_upper_lex[]=
92{
93 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
94 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
95 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
96 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
97 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
98 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
99 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
100 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127,
101 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
102 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
103 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
104 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
105 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
106 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
107 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
108 208,209,210,211,212,213,214,247,216,217,218,219,220,221,222,255
109};
110
111/*
112 Names of the index hints (for error messages). Keep in sync with
113 index_hint_type
114*/
115
116const char * index_hint_type_name[] =
117{
118 "IGNORE INDEX",
119 "USE INDEX",
120 "FORCE INDEX"
121};
122
123inline int lex_casecmp(const char *s, const char *t, uint len)
124{
125 while (len-- != 0 &&
126 to_upper_lex[(uchar) *s++] == to_upper_lex[(uchar) *t++]) ;
127 return (int) len+1;
128}
129
130#include <lex_hash.h>
131
132
133void lex_init(void)
134{
135 uint i;
136 DBUG_ENTER("lex_init");
137 for (i=0 ; i < array_elements(symbols) ; i++)
138 symbols[i].length=(uchar) strlen(symbols[i].name);
139 for (i=0 ; i < array_elements(sql_functions) ; i++)
140 sql_functions[i].length=(uchar) strlen(sql_functions[i].name);
141
142 DBUG_VOID_RETURN;
143}
144
145
146void lex_free(void)
147{ // Call this when daemon ends
148 DBUG_ENTER("lex_free");
149 DBUG_VOID_RETURN;
150}
151
152/**
153 Initialize lex object for use in fix_fields and parsing.
154
155 SYNOPSIS
156 init_lex_with_single_table()
157 @param thd The thread object
158 @param table The table object
159 @return Operation status
160 @retval TRUE An error occurred, memory allocation error
161 @retval FALSE Ok
162
163 DESCRIPTION
164 This function is used to initialize a lex object on the
165 stack for use by fix_fields and for parsing. In order to
166 work properly it also needs to initialize the
167 Name_resolution_context object of the lexer.
168 Finally it needs to set a couple of variables to ensure
169 proper functioning of fix_fields.
170*/
171
172int
173init_lex_with_single_table(THD *thd, TABLE *table, LEX *lex)
174{
175 TABLE_LIST *table_list;
176 Table_ident *table_ident;
177 SELECT_LEX *select_lex= &lex->select_lex;
178 Name_resolution_context *context= &select_lex->context;
179 /*
180 We will call the parser to create a part_info struct based on the
181 partition string stored in the frm file.
182 We will use a local lex object for this purpose. However we also
183 need to set the Name_resolution_object for this lex object. We
184 do this by using add_table_to_list where we add the table that
185 we're working with to the Name_resolution_context.
186 */
187 thd->lex= lex;
188 lex_start(thd);
189 context->init();
190 if (unlikely((!(table_ident= new Table_ident(thd,
191 &table->s->db,
192 &table->s->table_name,
193 TRUE)))) ||
194 (unlikely(!(table_list= select_lex->add_table_to_list(thd,
195 table_ident,
196 NULL,
197 0)))))
198 return TRUE;
199 context->resolve_in_table_list_only(table_list);
200 lex->use_only_table_context= TRUE;
201 lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VCOL_EXPR;
202 select_lex->cur_pos_in_select_list= UNDEF_POS;
203 table->map= 1; //To ensure correct calculation of const item
204 table_list->table= table;
205 table_list->cacheable_table= false;
206 return FALSE;
207}
208
209/**
210 End use of local lex with single table
211
212 SYNOPSIS
213 end_lex_with_single_table()
214 @param thd The thread object
215 @param table The table object
216 @param old_lex The real lex object connected to THD
217
218 DESCRIPTION
219 This function restores the real lex object after calling
220 init_lex_with_single_table and also restores some table
221 variables temporarily set.
222*/
223
224void
225end_lex_with_single_table(THD *thd, TABLE *table, LEX *old_lex)
226{
227 LEX *lex= thd->lex;
228 table->map= 0;
229 table->get_fields_in_item_tree= FALSE;
230 lex_end(lex);
231 thd->lex= old_lex;
232}
233
234
235void
236st_parsing_options::reset()
237{
238 allows_variable= TRUE;
239}
240
241
242/**
243 Perform initialization of Lex_input_stream instance.
244
245 Basically, a buffer for pre-processed query. This buffer should be large
246 enough to keep multi-statement query. The allocation is done once in
247 Lex_input_stream::init() in order to prevent memory pollution when
248 the server is processing large multi-statement queries.
249*/
250
251bool Lex_input_stream::init(THD *thd,
252 char* buff,
253 size_t length)
254{
255 DBUG_EXECUTE_IF("bug42064_simulate_oom",
256 DBUG_SET("+d,simulate_out_of_memory"););
257
258 m_cpp_buf= (char*) thd->alloc(length + 1);
259
260 DBUG_EXECUTE_IF("bug42064_simulate_oom",
261 DBUG_SET("-d,bug42064_simulate_oom"););
262
263 if (m_cpp_buf == NULL)
264 return true;
265
266 m_thd= thd;
267 reset(buff, length);
268
269 return false;
270}
271
272
273/**
274 Prepare Lex_input_stream instance state for use for handling next SQL statement.
275
276 It should be called between two statements in a multi-statement query.
277 The operation resets the input stream to the beginning-of-parse state,
278 but does not reallocate m_cpp_buf.
279*/
280
281void
282Lex_input_stream::reset(char *buffer, size_t length)
283{
284 yylineno= 1;
285 lookahead_token= -1;
286 lookahead_yylval= NULL;
287 m_ptr= buffer;
288 m_tok_start= NULL;
289 m_tok_end= NULL;
290 m_end_of_query= buffer + length;
291 m_tok_start_prev= NULL;
292 m_buf= buffer;
293 m_buf_length= length;
294 m_echo= TRUE;
295 m_cpp_tok_start= NULL;
296 m_cpp_tok_start_prev= NULL;
297 m_cpp_tok_end= NULL;
298 m_body_utf8= NULL;
299 m_cpp_utf8_processed_ptr= NULL;
300 next_state= MY_LEX_START;
301 found_semicolon= NULL;
302 ignore_space= MY_TEST(m_thd->variables.sql_mode & MODE_IGNORE_SPACE);
303 stmt_prepare_mode= FALSE;
304 multi_statements= TRUE;
305 in_comment=NO_COMMENT;
306 m_underscore_cs= NULL;
307 m_cpp_ptr= m_cpp_buf;
308}
309
310
311/**
312 The operation is called from the parser in order to
313 1) designate the intention to have utf8 body;
314 1) Indicate to the lexer that we will need a utf8 representation of this
315 statement;
316 2) Determine the beginning of the body.
317
318 @param thd Thread context.
319 @param begin_ptr Pointer to the start of the body in the pre-processed
320 buffer.
321*/
322
323void Lex_input_stream::body_utf8_start(THD *thd, const char *begin_ptr)
324{
325 DBUG_ASSERT(begin_ptr);
326 DBUG_ASSERT(m_cpp_buf <= begin_ptr && begin_ptr <= m_cpp_buf + m_buf_length);
327
328 size_t body_utf8_length= get_body_utf8_maximum_length(thd);
329
330 m_body_utf8= (char *) thd->alloc(body_utf8_length + 1);
331 m_body_utf8_ptr= m_body_utf8;
332 *m_body_utf8_ptr= 0;
333
334 m_cpp_utf8_processed_ptr= begin_ptr;
335}
336
337
338size_t Lex_input_stream::get_body_utf8_maximum_length(THD *thd)
339{
340 /*
341 String literals can grow during escaping:
342 1a. Character string '<TAB>' can grow to '\t', 3 bytes to 4 bytes growth.
343 1b. Character string '1000 times <TAB>' grows from
344 1002 to 2002 bytes (including quotes), which gives a little bit
345 less than 2 times growth.
346 "2" should be a reasonable multiplier that safely covers escaping needs.
347 */
348 return (m_buf_length / thd->variables.character_set_client->mbminlen) *
349 my_charset_utf8_bin.mbmaxlen * 2/*for escaping*/;
350}
351
352
353/**
354 @brief The operation appends unprocessed part of pre-processed buffer till
355 the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to end_ptr.
356
357 The idea is that some tokens in the pre-processed buffer (like character
358 set introducers) should be skipped.
359
360 Example:
361 CPP buffer: SELECT 'str1', _latin1 'str2';
362 m_cpp_utf8_processed_ptr -- points at the "SELECT ...";
363 In order to skip "_latin1", the following call should be made:
364 body_utf8_append(<pointer to "_latin1 ...">, <pointer to " 'str2'...">)
365
366 @param ptr Pointer in the pre-processed buffer, which specifies the
367 end of the chunk, which should be appended to the utf8
368 body.
369 @param end_ptr Pointer in the pre-processed buffer, to which
370 m_cpp_utf8_processed_ptr will be set in the end of the
371 operation.
372*/
373
374void Lex_input_stream::body_utf8_append(const char *ptr,
375 const char *end_ptr)
376{
377 DBUG_ASSERT(m_cpp_buf <= ptr && ptr <= m_cpp_buf + m_buf_length);
378 DBUG_ASSERT(m_cpp_buf <= end_ptr && end_ptr <= m_cpp_buf + m_buf_length);
379
380 if (!m_body_utf8)
381 return;
382
383 if (m_cpp_utf8_processed_ptr >= ptr)
384 return;
385
386 size_t bytes_to_copy= ptr - m_cpp_utf8_processed_ptr;
387
388 memcpy(m_body_utf8_ptr, m_cpp_utf8_processed_ptr, bytes_to_copy);
389 m_body_utf8_ptr += bytes_to_copy;
390 *m_body_utf8_ptr= 0;
391
392 m_cpp_utf8_processed_ptr= end_ptr;
393}
394
395/**
396 The operation appends unprocessed part of the pre-processed buffer till
397 the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to ptr.
398
399 @param ptr Pointer in the pre-processed buffer, which specifies the end
400 of the chunk, which should be appended to the utf8 body.
401*/
402
403void Lex_input_stream::body_utf8_append(const char *ptr)
404{
405 body_utf8_append(ptr, ptr);
406}
407
408/**
409 The operation converts the specified text literal to the utf8 and appends
410 the result to the utf8-body.
411
412 @param thd Thread context.
413 @param txt Text literal.
414 @param txt_cs Character set of the text literal.
415 @param end_ptr Pointer in the pre-processed buffer, to which
416 m_cpp_utf8_processed_ptr will be set in the end of the
417 operation.
418*/
419
420void
421Lex_input_stream::body_utf8_append_ident(THD *thd,
422 const Lex_string_with_metadata_st *txt,
423 const char *end_ptr)
424{
425 if (!m_cpp_utf8_processed_ptr)
426 return;
427
428 LEX_CSTRING utf_txt;
429 thd->make_text_string_sys(&utf_txt, txt); // QQ: check return value?
430
431 /* NOTE: utf_txt.length is in bytes, not in symbols. */
432 memcpy(m_body_utf8_ptr, utf_txt.str, utf_txt.length);
433 m_body_utf8_ptr += utf_txt.length;
434 *m_body_utf8_ptr= 0;
435
436 m_cpp_utf8_processed_ptr= end_ptr;
437}
438
439
440
441
442extern "C" {
443
444/**
445 Escape a character. Consequently puts "escape" and "wc" characters into
446 the destination utf8 string.
447 @param cs - the character set (utf8)
448 @param escape - the escape character (backslash, single quote, double quote)
449 @param wc - the character to be escaped
450 @param str - the destination string
451 @param end - the end of the destination string
452 @returns - a code according to the wc_mb() convension.
453*/
454int my_wc_mb_utf8_with_escape(CHARSET_INFO *cs, my_wc_t escape, my_wc_t wc,
455 uchar *str, uchar *end)
456{
457 DBUG_ASSERT(escape > 0);
458 if (str + 1 >= end)
459 return MY_CS_TOOSMALL2; // Not enough space, need at least two bytes.
460 *str= (uchar)escape;
461 int cnvres= my_charset_utf8_handler.wc_mb(cs, wc, str + 1, end);
462 if (cnvres > 0)
463 return cnvres + 1; // The character was normally put
464 if (cnvres == MY_CS_ILUNI)
465 return MY_CS_ILUNI; // Could not encode "wc" (e.g. non-BMP character)
466 DBUG_ASSERT(cnvres <= MY_CS_TOOSMALL);
467 return cnvres - 1; // Not enough space
468}
469
470
471/**
472 Optionally escape a character.
473 If "escape" is non-zero, then both "escape" and "wc" are put to
474 the destination string. Otherwise, only "wc" is put.
475 @param cs - the character set (utf8)
476 @param wc - the character to be optionally escaped
477 @param escape - the escape character, or 0
478 @param ewc - the escaped replacement of "wc" (e.g. 't' for '\t')
479 @param str - the destination string
480 @param end - the end of the destination string
481 @returns - a code according to the wc_mb() conversion.
482*/
483int my_wc_mb_utf8_opt_escape(CHARSET_INFO *cs,
484 my_wc_t wc, my_wc_t escape, my_wc_t ewc,
485 uchar *str, uchar *end)
486{
487 return escape ? my_wc_mb_utf8_with_escape(cs, escape, ewc, str, end) :
488 my_charset_utf8_handler.wc_mb(cs, wc, str, end);
489}
490
491/**
492 Encode a character with optional backlash escaping and quote escaping.
493 Quote marks are escaped using another quote mark.
494 Additionally, if "escape" is non-zero, then special characters are
495 also escaped using "escape".
496 Otherwise (if "escape" is zero, e.g. in case of MODE_NO_BACKSLASH_ESCAPES),
497 then special characters are not escaped and handled as normal characters.
498
499 @param cs - the character set (utf8)
500 @param wc - the character to be encoded
501 @param str - the destination string
502 @param end - the end of the destination string
503 @param sep - the string delimiter (e.g. ' or ")
504 @param escape - the escape character (backslash, or 0)
505 @returns - a code according to the wc_mb() convension.
506*/
507int my_wc_mb_utf8_escape(CHARSET_INFO *cs, my_wc_t wc, uchar *str, uchar *end,
508 my_wc_t sep, my_wc_t escape)
509{
510 DBUG_ASSERT(escape == 0 || escape == '\\');
511 DBUG_ASSERT(sep == '"' || sep == '\'');
512 switch (wc) {
513 case 0: return my_wc_mb_utf8_opt_escape(cs, wc, escape, '0', str, end);
514 case '\t': return my_wc_mb_utf8_opt_escape(cs, wc, escape, 't', str, end);
515 case '\r': return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'r', str, end);
516 case '\n': return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'n', str, end);
517 case '\032': return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'Z', str, end);
518 case '\'':
519 case '\"':
520 if (wc == sep)
521 return my_wc_mb_utf8_with_escape(cs, wc, wc, str, end);
522 }
523 return my_charset_utf8_handler.wc_mb(cs, wc, str, end); // No escaping needed
524}
525
526
527/** wc_mb() compatible routines for all sql_mode and delimiter combinations */
528int my_wc_mb_utf8_escape_single_quote_and_backslash(CHARSET_INFO *cs,
529 my_wc_t wc,
530 uchar *str, uchar *end)
531{
532 return my_wc_mb_utf8_escape(cs, wc, str, end, '\'', '\\');
533}
534
535
536int my_wc_mb_utf8_escape_double_quote_and_backslash(CHARSET_INFO *cs,
537 my_wc_t wc,
538 uchar *str, uchar *end)
539{
540 return my_wc_mb_utf8_escape(cs, wc, str, end, '"', '\\');
541}
542
543
544int my_wc_mb_utf8_escape_single_quote(CHARSET_INFO *cs, my_wc_t wc,
545 uchar *str, uchar *end)
546{
547 return my_wc_mb_utf8_escape(cs, wc, str, end, '\'', 0);
548}
549
550
551int my_wc_mb_utf8_escape_double_quote(CHARSET_INFO *cs, my_wc_t wc,
552 uchar *str, uchar *end)
553{
554 return my_wc_mb_utf8_escape(cs, wc, str, end, '"', 0);
555}
556
557}; // End of extern "C"
558
559
560/**
561 Get an escaping function, depending on the current sql_mode and the
562 string separator.
563*/
564my_charset_conv_wc_mb
565Lex_input_stream::get_escape_func(THD *thd, my_wc_t sep) const
566{
567 return thd->backslash_escapes() ?
568 (sep == '"' ? my_wc_mb_utf8_escape_double_quote_and_backslash:
569 my_wc_mb_utf8_escape_single_quote_and_backslash) :
570 (sep == '"' ? my_wc_mb_utf8_escape_double_quote:
571 my_wc_mb_utf8_escape_single_quote);
572}
573
574
575/**
576 Append a text literal to the end of m_body_utf8.
577 The string is escaped according to the current sql_mode and the
578 string delimiter (e.g. ' or ").
579
580 @param thd - current THD
581 @param txt - the string to be appended to m_body_utf8.
582 Note, the string must be already unescaped.
583 @param cs - the character set of the string
584 @param end_ptr - m_cpp_utf8_processed_ptr will be set to this value
585 (see body_utf8_append_ident for details)
586 @param sep - the string delimiter (single or double quote)
587*/
588void Lex_input_stream::body_utf8_append_escape(THD *thd,
589 const LEX_CSTRING *txt,
590 CHARSET_INFO *cs,
591 const char *end_ptr,
592 my_wc_t sep)
593{
594 DBUG_ASSERT(sep == '\'' || sep == '"');
595 if (!m_cpp_utf8_processed_ptr)
596 return;
597 uint errors;
598 /**
599 We previously alloced m_body_utf8 to be able to store the query with all
600 strings properly escaped. See get_body_utf8_maximum_length().
601 So here we have guaranteedly enough space to append any string literal
602 with escaping. Passing txt->length*2 as "available space" is always safe.
603 For better safety purposes we could calculate get_body_utf8_maximum_length()
604 every time we append a string, but this would affect performance negatively,
605 so let's check that we don't get beyond the allocated buffer in
606 debug build only.
607 */
608 DBUG_ASSERT(m_body_utf8 + get_body_utf8_maximum_length(thd) >=
609 m_body_utf8_ptr + txt->length * 2);
610 uint32 cnv_length= my_convert_using_func(m_body_utf8_ptr, txt->length * 2,
611 &my_charset_utf8_general_ci,
612 get_escape_func(thd, sep),
613 txt->str, txt->length,
614 cs, cs->cset->mb_wc,
615 &errors);
616 m_body_utf8_ptr+= cnv_length;
617 *m_body_utf8_ptr= 0;
618 m_cpp_utf8_processed_ptr= end_ptr;
619}
620
621
622void Lex_input_stream::add_digest_token(uint token, LEX_YYSTYPE yylval)
623{
624 if (m_digest != NULL)
625 {
626 m_digest= digest_add_token(m_digest, token, yylval);
627 }
628}
629
630void Lex_input_stream::reduce_digest_token(uint token_left, uint token_right)
631{
632 if (m_digest != NULL)
633 {
634 m_digest= digest_reduce_token(m_digest, token_left, token_right);
635 }
636}
637
638void lex_start(THD *thd)
639{
640 DBUG_ENTER("lex_start");
641 thd->lex->start(thd);
642 DBUG_VOID_RETURN;
643}
644
645
646/*
647 This is called before every query that is to be parsed.
648 Because of this, it's critical to not do too much things here.
649 (We already do too much here)
650*/
651
652void LEX::start(THD *thd_arg)
653{
654 DBUG_ENTER("LEX::start");
655 DBUG_PRINT("info", ("This: %p thd_arg->lex: %p", this, thd_arg->lex));
656
657 thd= unit.thd= thd_arg;
658 stmt_lex= this; // default, should be rewritten for VIEWs And CTEs
659
660 DBUG_ASSERT(!explain);
661
662 context_stack.empty();
663 unit.init_query();
664 current_select_number= 1;
665 select_lex.linkage= UNSPECIFIED_TYPE;
666 /* 'parent_lex' is used in init_query() so it must be before it. */
667 select_lex.parent_lex= this;
668 select_lex.init_query();
669 curr_with_clause= 0;
670 with_clauses_list= 0;
671 with_clauses_list_last_next= &with_clauses_list;
672 create_view= NULL;
673 value_list.empty();
674 update_list.empty();
675 set_var_list.empty();
676 param_list.empty();
677 view_list.empty();
678 with_column_list.empty();
679 with_persistent_for_clause= FALSE;
680 column_list= NULL;
681 index_list= NULL;
682 prepared_stmt_params.empty();
683 auxiliary_table_list.empty();
684 unit.next= unit.master= unit.link_next= unit.return_to= 0;
685 unit.prev= unit.link_prev= 0;
686 unit.slave= current_select= all_selects_list= &select_lex;
687 select_lex.master= &unit;
688 select_lex.prev= &unit.slave;
689 select_lex.link_next= select_lex.slave= select_lex.next= 0;
690 select_lex.link_prev= (st_select_lex_node**)&(all_selects_list);
691 select_lex.options= 0;
692 select_lex.sql_cache= SELECT_LEX::SQL_CACHE_UNSPECIFIED;
693 select_lex.init_order();
694 select_lex.group_list.empty();
695 if (select_lex.group_list_ptrs)
696 select_lex.group_list_ptrs->clear();
697 describe= 0;
698 analyze_stmt= 0;
699 explain_json= false;
700 subqueries= FALSE;
701 context_analysis_only= 0;
702 derived_tables= 0;
703 safe_to_cache_query= 1;
704 parsing_options.reset();
705 empty_field_list_on_rset= 0;
706 select_lex.select_number= 1;
707 part_info= 0;
708 select_lex.in_sum_expr=0;
709 select_lex.ftfunc_list_alloc.empty();
710 select_lex.ftfunc_list= &select_lex.ftfunc_list_alloc;
711 select_lex.group_list.empty();
712 select_lex.order_list.empty();
713 select_lex.gorder_list.empty();
714 m_sql_cmd= NULL;
715 duplicates= DUP_ERROR;
716 ignore= 0;
717 spname= NULL;
718 spcont= NULL;
719 proc_list.first= 0;
720 escape_used= FALSE;
721 default_used= FALSE;
722 query_tables= 0;
723 reset_query_tables_list(FALSE);
724 expr_allows_subselect= TRUE;
725 use_only_table_context= FALSE;
726 parse_vcol_expr= FALSE;
727 check_exists= FALSE;
728 create_info.lex_start();
729 verbose= 0;
730
731 name= null_clex_str;
732 event_parse_data= NULL;
733 profile_options= PROFILE_NONE;
734 nest_level=0 ;
735 select_lex.nest_level_base= &unit;
736 allow_sum_func= 0;
737 in_sum_func= NULL;
738
739 used_tables= 0;
740 table_type= TABLE_TYPE_UNKNOWN;
741 reset_slave_info.all= false;
742 limit_rows_examined= 0;
743 limit_rows_examined_cnt= ULONGLONG_MAX;
744 var_list.empty();
745 stmt_var_list.empty();
746 proc_list.elements=0;
747
748 save_group_list.empty();
749 save_order_list.empty();
750 win_ref= NULL;
751 win_frame= NULL;
752 frame_top_bound= NULL;
753 frame_bottom_bound= NULL;
754 win_spec= NULL;
755
756 vers_conditions.empty();
757
758 is_lex_started= TRUE;
759 DBUG_VOID_RETURN;
760}
761
762void lex_end(LEX *lex)
763{
764 DBUG_ENTER("lex_end");
765 DBUG_PRINT("enter", ("lex: %p", lex));
766
767 lex_end_stage1(lex);
768 lex_end_stage2(lex);
769
770 DBUG_VOID_RETURN;
771}
772
773void lex_end_stage1(LEX *lex)
774{
775 DBUG_ENTER("lex_end_stage1");
776
777 /* release used plugins */
778 if (lex->plugins.elements) /* No function call and no mutex if no plugins. */
779 {
780 plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer,
781 lex->plugins.elements);
782 }
783 reset_dynamic(&lex->plugins);
784
785 if (lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_PREPARE)
786 {
787 /*
788 Don't delete lex->sphead, it'll be needed for EXECUTE.
789 Note that of all statements that populate lex->sphead
790 only SQLCOM_COMPOUND can be PREPAREd
791 */
792 DBUG_ASSERT(lex->sphead == 0 || lex->sql_command == SQLCOM_COMPOUND);
793 }
794 else
795 {
796 delete lex->sphead;
797 lex->sphead= NULL;
798 }
799
800 DBUG_VOID_RETURN;
801}
802
803/*
804 MASTER INFO parameters (or state) is normally cleared towards the end
805 of a statement. But in case of PS, the state needs to be preserved during
806 its lifetime and should only be cleared on PS close or deallocation.
807*/
808void lex_end_stage2(LEX *lex)
809{
810 DBUG_ENTER("lex_end_stage2");
811
812 /* Reset LEX_MASTER_INFO */
813 lex->mi.reset(lex->sql_command == SQLCOM_CHANGE_MASTER);
814 delete_dynamic(&lex->delete_gtid_domain);
815
816 DBUG_VOID_RETURN;
817}
818
819Yacc_state::~Yacc_state()
820{
821 if (yacc_yyss)
822 {
823 my_free(yacc_yyss);
824 my_free(yacc_yyvs);
825 }
826}
827
828int Lex_input_stream::find_keyword(Lex_ident_cli_st *kwd,
829 uint len, bool function)
830{
831 const char *tok= m_tok_start;
832
833 SYMBOL *symbol= get_hash_symbol(tok, len, function);
834 if (symbol)
835 {
836 kwd->set_keyword(tok, len);
837 DBUG_ASSERT(tok >= get_buf());
838 DBUG_ASSERT(tok < get_end_of_query());
839
840 if ((symbol->tok == NOT_SYM) &&
841 (m_thd->variables.sql_mode & MODE_HIGH_NOT_PRECEDENCE))
842 return NOT2_SYM;
843 if ((symbol->tok == OR2_SYM) &&
844 (m_thd->variables.sql_mode & MODE_PIPES_AS_CONCAT))
845 {
846 return (m_thd->variables.sql_mode & MODE_ORACLE) ?
847 ORACLE_CONCAT_SYM : MYSQL_CONCAT_SYM;
848 }
849
850 return symbol->tok;
851 }
852 return 0;
853}
854
855/*
856 Check if name is a keyword
857
858 SYNOPSIS
859 is_keyword()
860 name checked name (must not be empty)
861 len length of checked name
862
863 RETURN VALUES
864 0 name is a keyword
865 1 name isn't a keyword
866*/
867
868bool is_keyword(const char *name, uint len)
869{
870 DBUG_ASSERT(len != 0);
871 return get_hash_symbol(name,len,0)!=0;
872}
873
874/**
875 Check if name is a sql function
876
877 @param name checked name
878
879 @return is this a native function or not
880 @retval 0 name is a function
881 @retval 1 name isn't a function
882*/
883
884bool is_lex_native_function(const LEX_CSTRING *name)
885{
886 DBUG_ASSERT(name != NULL);
887 return (get_hash_symbol(name->str, (uint) name->length, 1) != 0);
888}
889
890
891bool is_native_function(THD *thd, const LEX_CSTRING *name)
892{
893 if (find_native_function_builder(thd, name))
894 return true;
895
896 if (is_lex_native_function(name))
897 return true;
898
899 return false;
900}
901
902
903bool is_native_function_with_warn(THD *thd, const LEX_CSTRING *name)
904{
905 if (!is_native_function(thd, name))
906 return false;
907 /*
908 This warning will be printed when
909 [1] A client query is parsed,
910 [2] A stored function is loaded by db_load_routine.
911 Printing the warning for [2] is intentional, to cover the
912 following scenario:
913 - A user define a SF 'foo' using MySQL 5.N
914 - An application uses select foo(), and works.
915 - MySQL 5.{N+1} defines a new native function 'foo', as
916 part of a new feature.
917 - MySQL 5.{N+1} documentation is updated, and should mention
918 that there is a potential incompatible change in case of
919 existing stored function named 'foo'.
920 - The user deploys 5.{N+1}. At this point, 'select foo()'
921 means something different, and the user code is most likely
922 broken (it's only safe if the code is 'select db.foo()').
923 With a warning printed when the SF is loaded (which has to
924 occur before the call), the warning will provide a hint
925 explaining the root cause of a later failure of 'select foo()'.
926 With no warning printed, the user code will fail with no
927 apparent reason.
928 Printing a warning each time db_load_routine is executed for
929 an ambiguous function is annoying, since that can happen a lot,
930 but in practice should not happen unless there *are* name
931 collisions.
932 If a collision exists, it should not be silenced but fixed.
933 */
934 push_warning_printf(thd,
935 Sql_condition::WARN_LEVEL_NOTE,
936 ER_NATIVE_FCT_NAME_COLLISION,
937 ER_THD(thd, ER_NATIVE_FCT_NAME_COLLISION),
938 name->str);
939 return true;
940}
941
942
943/* make a copy of token before ptr and set yytoklen */
944
945LEX_CSTRING Lex_input_stream::get_token(uint skip, uint length)
946{
947 LEX_CSTRING tmp;
948 yyUnget(); // ptr points now after last token char
949 tmp.length= length;
950 tmp.str= m_thd->strmake(m_tok_start + skip, tmp.length);
951
952 m_cpp_text_start= m_cpp_tok_start + skip;
953 m_cpp_text_end= m_cpp_text_start + tmp.length;
954
955 return tmp;
956}
957
958
959static size_t
960my_unescape(CHARSET_INFO *cs, char *to, const char *str, const char *end,
961 int sep, bool backslash_escapes)
962{
963 char *start= to;
964 for ( ; str != end ; str++)
965 {
966#ifdef USE_MB
967 int l;
968 if (use_mb(cs) && (l= my_ismbchar(cs, str, end)))
969 {
970 while (l--)
971 *to++ = *str++;
972 str--;
973 continue;
974 }
975#endif
976 if (backslash_escapes && *str == '\\' && str + 1 != end)
977 {
978 switch(*++str) {
979 case 'n':
980 *to++='\n';
981 break;
982 case 't':
983 *to++= '\t';
984 break;
985 case 'r':
986 *to++ = '\r';
987 break;
988 case 'b':
989 *to++ = '\b';
990 break;
991 case '0':
992 *to++= 0; // Ascii null
993 break;
994 case 'Z': // ^Z must be escaped on Win32
995 *to++='\032';
996 break;
997 case '_':
998 case '%':
999 *to++= '\\'; // remember prefix for wildcard
1000 /* Fall through */
1001 default:
1002 *to++= *str;
1003 break;
1004 }
1005 }
1006 else if (*str == sep)
1007 *to++= *str++; // Two ' or "
1008 else
1009 *to++ = *str;
1010 }
1011 *to= 0;
1012 return to - start;
1013}
1014
1015
1016size_t
1017Lex_input_stream::unescape(CHARSET_INFO *cs, char *to,
1018 const char *str, const char *end,
1019 int sep)
1020{
1021 return my_unescape(cs, to, str, end, sep, m_thd->backslash_escapes());
1022}
1023
1024
1025/*
1026 Return an unescaped text literal without quotes
1027 Fix sometimes to do only one scan of the string
1028*/
1029
1030bool Lex_input_stream::get_text(Lex_string_with_metadata_st *dst, uint sep,
1031 int pre_skip, int post_skip)
1032{
1033 uchar c;
1034 uint found_escape=0;
1035 CHARSET_INFO *cs= m_thd->charset();
1036 bool is_8bit= false;
1037
1038 while (! eof())
1039 {
1040 c= yyGet();
1041 if (c & 0x80)
1042 is_8bit= true;
1043#ifdef USE_MB
1044 {
1045 int l;
1046 if (use_mb(cs) &&
1047 (l = my_ismbchar(cs,
1048 get_ptr() -1,
1049 get_end_of_query()))) {
1050 skip_binary(l-1);
1051 continue;
1052 }
1053 }
1054#endif
1055 if (c == '\\' &&
1056 !(m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))
1057 { // Escaped character
1058 found_escape=1;
1059 if (eof())
1060 return true;
1061 yySkip();
1062 }
1063 else if (c == sep)
1064 {
1065 if (c == yyGet()) // Check if two separators in a row
1066 {
1067 found_escape=1; // duplicate. Remember for delete
1068 continue;
1069 }
1070 else
1071 yyUnget();
1072
1073 /* Found end. Unescape and return string */
1074 const char *str, *end;
1075 char *to;
1076
1077 str= m_tok_start;
1078 end= get_ptr();
1079 /* Extract the text from the token */
1080 str += pre_skip;
1081 end -= post_skip;
1082 DBUG_ASSERT(end >= str);
1083
1084 if (!(to= (char*) m_thd->alloc((uint) (end - str) + 1)))
1085 {
1086 dst->set(&empty_clex_str, 0, '\0');
1087 return true; // Sql_alloc has set error flag
1088 }
1089
1090 m_cpp_text_start= m_cpp_tok_start + pre_skip;
1091 m_cpp_text_end= get_cpp_ptr() - post_skip;
1092
1093 if (!found_escape)
1094 {
1095 size_t len= (end - str);
1096 memcpy(to, str, len);
1097 to[len]= '\0';
1098 dst->set(to, len, is_8bit, '\0');
1099 }
1100 else
1101 {
1102 size_t len= unescape(cs, to, str, end, sep);
1103 dst->set(to, len, is_8bit, '\0');
1104 }
1105 return false;
1106 }
1107 }
1108 return true; // unexpected end of query
1109}
1110
1111
1112/*
1113** Calc type of integer; long integer, longlong integer or real.
1114** Returns smallest type that match the string.
1115** When using unsigned long long values the result is converted to a real
1116** because else they will be unexpected sign changes because all calculation
1117** is done with longlong or double.
1118*/
1119
1120static const char *long_str="2147483647";
1121static const uint long_len=10;
1122static const char *signed_long_str="-2147483648";
1123static const char *longlong_str="9223372036854775807";
1124static const uint longlong_len=19;
1125static const char *signed_longlong_str="-9223372036854775808";
1126static const uint signed_longlong_len=19;
1127static const char *unsigned_longlong_str="18446744073709551615";
1128static const uint unsigned_longlong_len=20;
1129
1130static inline uint int_token(const char *str,uint length)
1131{
1132 if (length < long_len) // quick normal case
1133 return NUM;
1134 bool neg=0;
1135
1136 if (*str == '+') // Remove sign and pre-zeros
1137 {
1138 str++; length--;
1139 }
1140 else if (*str == '-')
1141 {
1142 str++; length--;
1143 neg=1;
1144 }
1145 while (*str == '0' && length)
1146 {
1147 str++; length --;
1148 }
1149 if (length < long_len)
1150 return NUM;
1151
1152 uint smaller,bigger;
1153 const char *cmp;
1154 if (neg)
1155 {
1156 if (length == long_len)
1157 {
1158 cmp= signed_long_str + 1;
1159 smaller= NUM; // If <= signed_long_str
1160 bigger= LONG_NUM; // If >= signed_long_str
1161 }
1162 else if (length < signed_longlong_len)
1163 return LONG_NUM;
1164 else if (length > signed_longlong_len)
1165 return DECIMAL_NUM;
1166 else
1167 {
1168 cmp= signed_longlong_str + 1;
1169 smaller= LONG_NUM; // If <= signed_longlong_str
1170 bigger=DECIMAL_NUM;
1171 }
1172 }
1173 else
1174 {
1175 if (length == long_len)
1176 {
1177 cmp= long_str;
1178 smaller=NUM;
1179 bigger=LONG_NUM;
1180 }
1181 else if (length < longlong_len)
1182 return LONG_NUM;
1183 else if (length > longlong_len)
1184 {
1185 if (length > unsigned_longlong_len)
1186 return DECIMAL_NUM;
1187 cmp=unsigned_longlong_str;
1188 smaller=ULONGLONG_NUM;
1189 bigger=DECIMAL_NUM;
1190 }
1191 else
1192 {
1193 cmp=longlong_str;
1194 smaller=LONG_NUM;
1195 bigger= ULONGLONG_NUM;
1196 }
1197 }
1198 while (*cmp && *cmp++ == *str++) ;
1199 return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
1200}
1201
1202
1203/**
1204 Given a stream that is advanced to the first contained character in
1205 an open comment, consume the comment. Optionally, if we are allowed,
1206 recurse so that we understand comments within this current comment.
1207
1208 At this level, we do not support version-condition comments. We might
1209 have been called with having just passed one in the stream, though. In
1210 that case, we probably want to tolerate mundane comments inside. Thus,
1211 the case for recursion.
1212
1213 @retval Whether EOF reached before comment is closed.
1214*/
1215bool Lex_input_stream::consume_comment(int remaining_recursions_permitted)
1216{
1217 uchar c;
1218 while (!eof())
1219 {
1220 c= yyGet();
1221
1222 if (remaining_recursions_permitted > 0)
1223 {
1224 if ((c == '/') && (yyPeek() == '*'))
1225 {
1226 yySkip(); // Eat asterisk
1227 consume_comment(remaining_recursions_permitted - 1);
1228 continue;
1229 }
1230 }
1231
1232 if (c == '*')
1233 {
1234 if (yyPeek() == '/')
1235 {
1236 yySkip(); // Eat slash
1237 return FALSE;
1238 }
1239 }
1240
1241 if (c == '\n')
1242 yylineno++;
1243 }
1244
1245 return TRUE;
1246}
1247
1248
1249/*
1250 MYSQLlex remember the following states from the following MYSQLlex()
1251
1252 @param yylval [out] semantic value of the token being parsed (yylval)
1253 @param thd THD
1254
1255 - MY_LEX_EOQ Found end of query
1256 - MY_LEX_OPERATOR_OR_IDENT Last state was an ident, text or number
1257 (which can't be followed by a signed number)
1258*/
1259
1260int MYSQLlex(YYSTYPE *yylval, THD *thd)
1261{
1262 return thd->m_parser_state->m_lip.lex_token(yylval, thd);
1263}
1264
1265
1266int ORAlex(YYSTYPE *yylval, THD *thd)
1267{
1268 return thd->m_parser_state->m_lip.lex_token(yylval, thd);
1269}
1270
1271
1272int Lex_input_stream::lex_token(YYSTYPE *yylval, THD *thd)
1273{
1274 int token;
1275
1276 if (lookahead_token >= 0)
1277 {
1278 /*
1279 The next token was already parsed in advance,
1280 return it.
1281 */
1282 token= lookahead_token;
1283 lookahead_token= -1;
1284 *yylval= *(lookahead_yylval);
1285 lookahead_yylval= NULL;
1286 return token;
1287 }
1288
1289 token= lex_one_token(yylval, thd);
1290 add_digest_token(token, yylval);
1291
1292 switch(token) {
1293 case WITH:
1294 /*
1295 Parsing 'WITH' 'ROLLUP' or 'WITH' 'CUBE' requires 2 look ups,
1296 which makes the grammar LALR(2).
1297 Replace by a single 'WITH_ROLLUP' or 'WITH_CUBE' token,
1298 to transform the grammar into a LALR(1) grammar,
1299 which sql_yacc.yy can process.
1300 */
1301 token= lex_one_token(yylval, thd);
1302 add_digest_token(token, yylval);
1303 switch(token) {
1304 case CUBE_SYM:
1305 return WITH_CUBE_SYM;
1306 case ROLLUP_SYM:
1307 return WITH_ROLLUP_SYM;
1308 case SYSTEM:
1309 return WITH_SYSTEM_SYM;
1310 default:
1311 /*
1312 Save the token following 'WITH'
1313 */
1314 lookahead_yylval= yylval;
1315 lookahead_token= token;
1316 return WITH;
1317 }
1318 break;
1319 case FOR_SYM:
1320 /*
1321 * Additional look-ahead to resolve doubtful cases like:
1322 * SELECT ... FOR UPDATE
1323 * SELECT ... FOR SYSTEM_TIME ... .
1324 */
1325 token= lex_one_token(yylval, thd);
1326 add_digest_token(token, yylval);
1327 switch(token) {
1328 case SYSTEM_TIME_SYM:
1329 return FOR_SYSTEM_TIME_SYM;
1330 default:
1331 /*
1332 Save the token following 'FOR_SYM'
1333 */
1334 lookahead_yylval= yylval;
1335 lookahead_token= token;
1336 return FOR_SYM;
1337 }
1338 break;
1339 case VALUES:
1340 if (thd->lex->current_select->parsing_place == IN_UPDATE_ON_DUP_KEY ||
1341 thd->lex->current_select->parsing_place == IN_PART_FUNC)
1342 return VALUE_SYM;
1343 token= lex_one_token(yylval, thd);
1344 add_digest_token(token, yylval);
1345 switch(token) {
1346 case LESS_SYM:
1347 return VALUES_LESS_SYM;
1348 case IN_SYM:
1349 return VALUES_IN_SYM;
1350 default:
1351 lookahead_yylval= yylval;
1352 lookahead_token= token;
1353 return VALUES;
1354 }
1355 break;
1356 default:
1357 break;
1358 }
1359 return token;
1360}
1361
1362
1363int Lex_input_stream::lex_one_token(YYSTYPE *yylval, THD *thd)
1364{
1365 uchar UNINIT_VAR(c);
1366 bool comment_closed;
1367 int tokval;
1368 uint length;
1369 enum my_lex_states state;
1370 LEX *lex= thd->lex;
1371 CHARSET_INFO *const cs= thd->charset();
1372 const uchar *const state_map= cs->state_map;
1373 const uchar *const ident_map= cs->ident_map;
1374
1375 start_token();
1376 state= next_state;
1377 next_state= MY_LEX_OPERATOR_OR_IDENT;
1378 for (;;)
1379 {
1380 switch (state) {
1381 case MY_LEX_OPERATOR_OR_IDENT: // Next is operator or keyword
1382 case MY_LEX_START: // Start of token
1383 // Skip starting whitespace
1384 while(state_map[c= yyPeek()] == MY_LEX_SKIP)
1385 {
1386 if (c == '\n')
1387 yylineno++;
1388
1389 yySkip();
1390 }
1391
1392 /* Start of real token */
1393 restart_token();
1394 c= yyGet();
1395 state= (enum my_lex_states) state_map[c];
1396 break;
1397 case MY_LEX_ESCAPE:
1398 if (!eof() && yyGet() == 'N')
1399 { // Allow \N as shortcut for NULL
1400 yylval->lex_str.str= (char*) "\\N";
1401 yylval->lex_str.length= 2;
1402 return NULL_SYM;
1403 }
1404 /* Fall through */
1405 case MY_LEX_CHAR: // Unknown or single char token
1406 case MY_LEX_SKIP: // This should not happen
1407 if (c != ')')
1408 next_state= MY_LEX_START; // Allow signed numbers
1409 return((int) c);
1410
1411 case MY_LEX_MINUS_OR_COMMENT:
1412 if (yyPeek() == '-' &&
1413 (my_isspace(cs,yyPeekn(1)) ||
1414 my_iscntrl(cs,yyPeekn(1))))
1415 {
1416 state=MY_LEX_COMMENT;
1417 break;
1418 }
1419 next_state= MY_LEX_START; // Allow signed numbers
1420 return((int) c);
1421
1422 case MY_LEX_PLACEHOLDER:
1423 /*
1424 Check for a placeholder: it should not precede a possible identifier
1425 because of binlogging: when a placeholder is replaced with
1426 its value in a query for the binlog, the query must stay
1427 grammatically correct.
1428 */
1429 next_state= MY_LEX_START; // Allow signed numbers
1430 if (stmt_prepare_mode && !ident_map[(uchar) yyPeek()])
1431 return(PARAM_MARKER);
1432 return((int) c);
1433
1434 case MY_LEX_COMMA:
1435 next_state= MY_LEX_START; // Allow signed numbers
1436 /*
1437 Warning:
1438 This is a work around, to make the "remember_name" rule in
1439 sql/sql_yacc.yy work properly.
1440 The problem is that, when parsing "select expr1, expr2",
1441 the code generated by bison executes the *pre* action
1442 remember_name (see select_item) *before* actually parsing the
1443 first token of expr2.
1444 */
1445 restart_token();
1446 return((int) c);
1447
1448 case MY_LEX_IDENT_OR_NCHAR:
1449 {
1450 uint sep;
1451 if (yyPeek() != '\'')
1452 {
1453 state= MY_LEX_IDENT;
1454 break;
1455 }
1456 /* Found N'string' */
1457 yySkip(); // Skip '
1458 if (get_text(&yylval->lex_string_with_metadata, (sep= yyGetLast()), 2, 1))
1459 {
1460 state= MY_LEX_CHAR; // Read char by char
1461 break;
1462 }
1463
1464 body_utf8_append(m_cpp_text_start);
1465 body_utf8_append_escape(thd, &yylval->lex_string_with_metadata,
1466 national_charset_info,
1467 m_cpp_text_end, sep);
1468 return(NCHAR_STRING);
1469 }
1470 case MY_LEX_IDENT_OR_HEX:
1471 if (yyPeek() == '\'')
1472 { // Found x'hex-number'
1473 state= MY_LEX_HEX_NUMBER;
1474 break;
1475 }
1476 /* fall through */
1477 case MY_LEX_IDENT_OR_BIN:
1478 if (yyPeek() == '\'')
1479 { // Found b'bin-number'
1480 state= MY_LEX_BIN_NUMBER;
1481 break;
1482 }
1483 /* fall through */
1484 case MY_LEX_IDENT:
1485 {
1486 tokval= scan_ident_middle(thd, &yylval->ident_cli,
1487 &yylval->charset, &state);
1488 if (!tokval)
1489 continue;
1490 if (tokval == UNDERSCORE_CHARSET)
1491 m_underscore_cs= yylval->charset;
1492 return tokval;
1493 }
1494
1495 case MY_LEX_IDENT_SEP: // Found ident and now '.'
1496 yylval->lex_str.str= (char*) get_ptr();
1497 yylval->lex_str.length= 1;
1498 c= yyGet(); // should be '.'
1499 next_state= MY_LEX_IDENT_START; // Next is ident (not keyword)
1500 if (!ident_map[(uchar) yyPeek()]) // Probably ` or "
1501 next_state= MY_LEX_START;
1502 return((int) c);
1503
1504 case MY_LEX_NUMBER_IDENT: // number or ident which num-start
1505 if (yyGetLast() == '0')
1506 {
1507 c= yyGet();
1508 if (c == 'x')
1509 {
1510 while (my_isxdigit(cs, (c = yyGet()))) ;
1511 if ((yyLength() >= 3) && !ident_map[c])
1512 {
1513 /* skip '0x' */
1514 yylval->lex_str= get_token(2, yyLength() - 2);
1515 return (HEX_NUM);
1516 }
1517 yyUnget();
1518 state= MY_LEX_IDENT_START;
1519 break;
1520 }
1521 else if (c == 'b')
1522 {
1523 while ((c= yyGet()) == '0' || c == '1')
1524 ;
1525 if ((yyLength() >= 3) && !ident_map[c])
1526 {
1527 /* Skip '0b' */
1528 yylval->lex_str= get_token(2, yyLength() - 2);
1529 return (BIN_NUM);
1530 }
1531 yyUnget();
1532 state= MY_LEX_IDENT_START;
1533 break;
1534 }
1535 yyUnget();
1536 }
1537
1538 while (my_isdigit(cs, (c= yyGet()))) ;
1539 if (!ident_map[c])
1540 { // Can't be identifier
1541 state=MY_LEX_INT_OR_REAL;
1542 break;
1543 }
1544 if (c == 'e' || c == 'E')
1545 {
1546 // The following test is written this way to allow numbers of type 1e1
1547 if (my_isdigit(cs, yyPeek()) ||
1548 (c=(yyGet())) == '+' || c == '-')
1549 { // Allow 1E+10
1550 if (my_isdigit(cs, yyPeek())) // Number must have digit after sign
1551 {
1552 yySkip();
1553 while (my_isdigit(cs, yyGet())) ;
1554 yylval->lex_str= get_token(0, yyLength());
1555 return(FLOAT_NUM);
1556 }
1557 }
1558 yyUnget();
1559 }
1560 // fall through
1561 case MY_LEX_IDENT_START: // We come here after '.'
1562 return scan_ident_start(thd, &yylval->ident_cli);
1563
1564 case MY_LEX_USER_VARIABLE_DELIMITER: // Found quote char
1565 return scan_ident_delimited(thd, &yylval->ident_cli);
1566
1567 case MY_LEX_INT_OR_REAL: // Complete int or incomplete real
1568 if (c != '.' || yyPeek() == '.')
1569 {
1570 /*
1571 Found a complete integer number:
1572 - the number is either not followed by a dot at all, or
1573 - the number is followed by a double dot as in: FOR i IN 1..10
1574 */
1575 yylval->lex_str= get_token(0, yyLength());
1576 return int_token(yylval->lex_str.str, (uint) yylval->lex_str.length);
1577 }
1578 // fall through
1579 case MY_LEX_REAL: // Incomplete real number
1580 while (my_isdigit(cs, c= yyGet())) ;
1581
1582 if (c == 'e' || c == 'E')
1583 {
1584 c= yyGet();
1585 if (c == '-' || c == '+')
1586 c= yyGet(); // Skip sign
1587 if (!my_isdigit(cs, c))
1588 { // No digit after sign
1589 state= MY_LEX_CHAR;
1590 break;
1591 }
1592 while (my_isdigit(cs, yyGet())) ;
1593 yylval->lex_str= get_token(0, yyLength());
1594 return(FLOAT_NUM);
1595 }
1596 yylval->lex_str= get_token(0, yyLength());
1597 return(DECIMAL_NUM);
1598
1599 case MY_LEX_HEX_NUMBER: // Found x'hexstring'
1600 yySkip(); // Accept opening '
1601 while (my_isxdigit(cs, (c= yyGet()))) ;
1602 if (c != '\'')
1603 return(ABORT_SYM); // Illegal hex constant
1604 yySkip(); // Accept closing '
1605 length= yyLength(); // Length of hexnum+3
1606 if ((length % 2) == 0)
1607 return(ABORT_SYM); // odd number of hex digits
1608 yylval->lex_str= get_token(2, // skip x'
1609 length - 3); // don't count x' and last '
1610 return HEX_STRING;
1611
1612 case MY_LEX_BIN_NUMBER: // Found b'bin-string'
1613 yySkip(); // Accept opening '
1614 while ((c= yyGet()) == '0' || c == '1')
1615 ;
1616 if (c != '\'')
1617 return(ABORT_SYM); // Illegal hex constant
1618 yySkip(); // Accept closing '
1619 length= yyLength(); // Length of bin-num + 3
1620 yylval->lex_str= get_token(2, // skip b'
1621 length - 3); // don't count b' and last '
1622 return (BIN_NUM);
1623
1624 case MY_LEX_CMP_OP: // Incomplete comparison operator
1625 next_state= MY_LEX_START; // Allow signed numbers
1626 if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP ||
1627 state_map[(uchar) yyPeek()] == MY_LEX_LONG_CMP_OP)
1628 {
1629 yySkip();
1630 if ((tokval= find_keyword(&yylval->kwd, 2, 0)))
1631 return(tokval);
1632 yyUnget();
1633 }
1634 return(c);
1635
1636 case MY_LEX_LONG_CMP_OP: // Incomplete comparison operator
1637 next_state= MY_LEX_START;
1638 if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP ||
1639 state_map[(uchar) yyPeek()] == MY_LEX_LONG_CMP_OP)
1640 {
1641 yySkip();
1642 if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP)
1643 {
1644 yySkip();
1645 if ((tokval= find_keyword(&yylval->kwd, 3, 0)))
1646 return(tokval);
1647 yyUnget();
1648 }
1649 if ((tokval= find_keyword(&yylval->kwd, 2, 0)))
1650 return(tokval);
1651 yyUnget();
1652 }
1653 return(c);
1654
1655 case MY_LEX_BOOL:
1656 if (c != yyPeek())
1657 {
1658 state= MY_LEX_CHAR;
1659 break;
1660 }
1661 yySkip();
1662 tokval= find_keyword(&yylval->kwd, 2, 0); // Is a bool operator
1663 next_state= MY_LEX_START; // Allow signed numbers
1664 return(tokval);
1665
1666 case MY_LEX_STRING_OR_DELIMITER:
1667 if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
1668 {
1669 state= MY_LEX_USER_VARIABLE_DELIMITER;
1670 break;
1671 }
1672 /* " used for strings */
1673 /* fall through */
1674 case MY_LEX_STRING: // Incomplete text string
1675 {
1676 uint sep;
1677 if (get_text(&yylval->lex_string_with_metadata, (sep= yyGetLast()), 1, 1))
1678 {
1679 state= MY_LEX_CHAR; // Read char by char
1680 break;
1681 }
1682 CHARSET_INFO *strcs= m_underscore_cs ? m_underscore_cs : cs;
1683 body_utf8_append(m_cpp_text_start);
1684
1685 body_utf8_append_escape(thd, &yylval->lex_string_with_metadata,
1686 strcs, m_cpp_text_end, sep);
1687 m_underscore_cs= NULL;
1688 return(TEXT_STRING);
1689 }
1690 case MY_LEX_COMMENT: // Comment
1691 lex->select_lex.options|= OPTION_FOUND_COMMENT;
1692 while ((c= yyGet()) != '\n' && c) ;
1693 yyUnget(); // Safety against eof
1694 state= MY_LEX_START; // Try again
1695 break;
1696 case MY_LEX_LONG_COMMENT: // Long C comment?
1697 if (yyPeek() != '*')
1698 {
1699 state= MY_LEX_CHAR; // Probable division
1700 break;
1701 }
1702 lex->select_lex.options|= OPTION_FOUND_COMMENT;
1703 /* Reject '/' '*', since we might need to turn off the echo */
1704 yyUnget();
1705
1706 save_in_comment_state();
1707
1708 if (yyPeekn(2) == '!' ||
1709 (yyPeekn(2) == 'M' && yyPeekn(3) == '!'))
1710 {
1711 bool maria_comment_syntax= yyPeekn(2) == 'M';
1712 in_comment= DISCARD_COMMENT;
1713 /* Accept '/' '*' '!', but do not keep this marker. */
1714 set_echo(FALSE);
1715 yySkipn(maria_comment_syntax ? 4 : 3);
1716
1717 /*
1718 The special comment format is very strict:
1719 '/' '*' '!', followed by an optional 'M' and exactly
1720 1-2 digits (major), 2 digits (minor), then 2 digits (dot).
1721 32302 -> 3.23.02
1722 50032 -> 5.0.32
1723 50114 -> 5.1.14
1724 100000 -> 10.0.0
1725 */
1726 if ( my_isdigit(cs, yyPeekn(0))
1727 && my_isdigit(cs, yyPeekn(1))
1728 && my_isdigit(cs, yyPeekn(2))
1729 && my_isdigit(cs, yyPeekn(3))
1730 && my_isdigit(cs, yyPeekn(4))
1731 )
1732 {
1733 ulong version;
1734 uint length= 5;
1735 char *end_ptr= (char*) get_ptr() + length;
1736 int error;
1737 if (my_isdigit(cs, yyPeekn(5)))
1738 {
1739 end_ptr++; // 6 digit number
1740 length++;
1741 }
1742
1743 version= (ulong) my_strtoll10(get_ptr(), &end_ptr, &error);
1744
1745 /*
1746 MySQL-5.7 has new features and might have new SQL syntax that
1747 MariaDB-10.0 does not understand. Ignore all versioned comments
1748 with MySQL versions in the range 50700-999999, but
1749 do not ignore MariaDB specific comments for the same versions.
1750 */
1751 if (version <= MYSQL_VERSION_ID &&
1752 (version < 50700 || version > 99999 || maria_comment_syntax))
1753 {
1754 /* Accept 'M' 'm' 'm' 'd' 'd' */
1755 yySkipn(length);
1756 /* Expand the content of the special comment as real code */
1757 set_echo(TRUE);
1758 state=MY_LEX_START;
1759 break; /* Do not treat contents as a comment. */
1760 }
1761 else
1762 {
1763#ifdef WITH_WSREP
1764 if (WSREP(thd) && version == 99997 && thd->wsrep_exec_mode == LOCAL_STATE)
1765 {
1766 WSREP_DEBUG("consistency check: %s", thd->query());
1767 thd->wsrep_consistency_check= CONSISTENCY_CHECK_DECLARED;
1768 yySkipn(5);
1769 set_echo(TRUE);
1770 state= MY_LEX_START;
1771 break; /* Do not treat contents as a comment. */
1772 }
1773#endif /* WITH_WSREP */
1774 /*
1775 Patch and skip the conditional comment to avoid it
1776 being propagated infinitely (eg. to a slave).
1777 */
1778 char *pcom= yyUnput(' ');
1779 comment_closed= ! consume_comment(1);
1780 if (! comment_closed)
1781 {
1782 *pcom= '!';
1783 }
1784 /* version allowed to have one level of comment inside. */
1785 }
1786 }
1787 else
1788 {
1789 /* Not a version comment. */
1790 state=MY_LEX_START;
1791 set_echo(TRUE);
1792 break;
1793 }
1794 }
1795 else
1796 {
1797 in_comment= PRESERVE_COMMENT;
1798 yySkip(); // Accept /
1799 yySkip(); // Accept *
1800 comment_closed= ! consume_comment(0);
1801 /* regular comments can have zero comments inside. */
1802 }
1803 /*
1804 Discard:
1805 - regular '/' '*' comments,
1806 - special comments '/' '*' '!' for a future version,
1807 by scanning until we find a closing '*' '/' marker.
1808
1809 Nesting regular comments isn't allowed. The first
1810 '*' '/' returns the parser to the previous state.
1811
1812 /#!VERSI oned containing /# regular #/ is allowed #/
1813
1814 Inside one versioned comment, another versioned comment
1815 is treated as a regular discardable comment. It gets
1816 no special parsing.
1817 */
1818
1819 /* Unbalanced comments with a missing '*' '/' are a syntax error */
1820 if (! comment_closed)
1821 return (ABORT_SYM);
1822 state = MY_LEX_START; // Try again
1823 restore_in_comment_state();
1824 break;
1825 case MY_LEX_END_LONG_COMMENT:
1826 if ((in_comment != NO_COMMENT) && yyPeek() == '/')
1827 {
1828 /* Reject '*' '/' */
1829 yyUnget();
1830 /* Accept '*' '/', with the proper echo */
1831 set_echo(in_comment == PRESERVE_COMMENT);
1832 yySkipn(2);
1833 /* And start recording the tokens again */
1834 set_echo(TRUE);
1835 in_comment= NO_COMMENT;
1836 state=MY_LEX_START;
1837 }
1838 else
1839 state= MY_LEX_CHAR; // Return '*'
1840 break;
1841 case MY_LEX_SET_VAR: // Check if ':='
1842 if (yyPeek() != '=')
1843 {
1844 state= MY_LEX_CHAR; // Return ':'
1845 break;
1846 }
1847 yySkip();
1848 return (SET_VAR);
1849 case MY_LEX_SEMICOLON: // optional line terminator
1850 state= MY_LEX_CHAR; // Return ';'
1851 break;
1852 case MY_LEX_EOL:
1853 if (eof())
1854 {
1855 yyUnget(); // Reject the last '\0'
1856 set_echo(FALSE);
1857 yySkip();
1858 set_echo(TRUE);
1859 /* Unbalanced comments with a missing '*' '/' are a syntax error */
1860 if (in_comment != NO_COMMENT)
1861 return (ABORT_SYM);
1862 next_state= MY_LEX_END; // Mark for next loop
1863 return(END_OF_INPUT);
1864 }
1865 state=MY_LEX_CHAR;
1866 break;
1867 case MY_LEX_END:
1868 next_state= MY_LEX_END;
1869 return(0); // We found end of input last time
1870
1871 /* Actually real shouldn't start with . but allow them anyhow */
1872 case MY_LEX_REAL_OR_POINT:
1873 if (my_isdigit(cs, (c= yyPeek())))
1874 state = MY_LEX_REAL; // Real
1875 else if (c == '.')
1876 {
1877 yySkip();
1878 return DOT_DOT_SYM;
1879 }
1880 else
1881 {
1882 state= MY_LEX_IDENT_SEP; // return '.'
1883 yyUnget(); // Put back '.'
1884 }
1885 break;
1886 case MY_LEX_USER_END: // end '@' of user@hostname
1887 switch (state_map[(uchar) yyPeek()]) {
1888 case MY_LEX_STRING:
1889 case MY_LEX_USER_VARIABLE_DELIMITER:
1890 case MY_LEX_STRING_OR_DELIMITER:
1891 break;
1892 case MY_LEX_USER_END:
1893 next_state= MY_LEX_SYSTEM_VAR;
1894 break;
1895 default:
1896 next_state= MY_LEX_HOSTNAME;
1897 break;
1898 }
1899 yylval->lex_str.str= (char*) get_ptr();
1900 yylval->lex_str.length= 1;
1901 return((int) '@');
1902 case MY_LEX_HOSTNAME: // end '@' of user@hostname
1903 for (c= yyGet() ;
1904 my_isalnum(cs, c) || c == '.' || c == '_' || c == '$';
1905 c= yyGet()) ;
1906 yylval->lex_str= get_token(0, yyLength());
1907 return(LEX_HOSTNAME);
1908 case MY_LEX_SYSTEM_VAR:
1909 yylval->lex_str.str= (char*) get_ptr();
1910 yylval->lex_str.length= 1;
1911 yySkip(); // Skip '@'
1912 next_state= (state_map[(uchar) yyPeek()] ==
1913 MY_LEX_USER_VARIABLE_DELIMITER ?
1914 MY_LEX_OPERATOR_OR_IDENT :
1915 MY_LEX_IDENT_OR_KEYWORD);
1916 return((int) '@');
1917 case MY_LEX_IDENT_OR_KEYWORD:
1918 /*
1919 We come here when we have found two '@' in a row.
1920 We should now be able to handle:
1921 [(global | local | session) .]variable_name
1922 */
1923 return scan_ident_sysvar(thd, &yylval->ident_cli);
1924 }
1925 }
1926}
1927
1928
1929bool Lex_input_stream::get_7bit_or_8bit_ident(THD *thd, uchar *last_char)
1930{
1931 uchar c;
1932 CHARSET_INFO *const cs= thd->charset();
1933 const uchar *const ident_map= cs->ident_map;
1934 bool is_8bit= false;
1935 for ( ; ident_map[c= yyGet()]; )
1936 {
1937 if (c & 0x80)
1938 is_8bit= true; // will convert
1939 }
1940 *last_char= c;
1941 return is_8bit;
1942}
1943
1944
1945int Lex_input_stream::scan_ident_sysvar(THD *thd, Lex_ident_cli_st *str)
1946{
1947 uchar last_char;
1948 uint length;
1949 int tokval;
1950 bool is_8bit;
1951 DBUG_ASSERT(m_tok_start == m_ptr);
1952
1953 is_8bit= get_7bit_or_8bit_ident(thd, &last_char);
1954
1955 if (last_char == '.')
1956 next_state= MY_LEX_IDENT_SEP;
1957 if (!(length= yyLength()))
1958 return ABORT_SYM; // Names must be nonempty.
1959 if ((tokval= find_keyword(str, length, 0)))
1960 {
1961 yyUnget(); // Put back 'c'
1962 return tokval; // Was keyword
1963 }
1964
1965 yyUnget(); // ptr points now after last token char
1966 str->set_ident(m_tok_start, length, is_8bit);
1967
1968 m_cpp_text_start= m_cpp_tok_start;
1969 m_cpp_text_end= m_cpp_text_start + length;
1970 body_utf8_append(m_cpp_text_start);
1971 body_utf8_append_ident(thd, str, m_cpp_text_end);
1972
1973 return is_8bit ? IDENT_QUOTED : IDENT;
1974}
1975
1976
1977/*
1978 We can come here if different parsing stages:
1979 - In an identifier chain:
1980 SELECT t1.cccc FROM t1;
1981 (when the "cccc" part starts)
1982 In this case both m_tok_start and m_ptr point to "cccc".
1983 - When a sequence of digits has changed to something else,
1984 therefore the token becomes an identifier rather than a number:
1985 SELECT 12345_6 FROM t1;
1986 In this case m_tok_start points to the entire "12345_678",
1987 while m_ptr points to "678".
1988*/
1989int Lex_input_stream::scan_ident_start(THD *thd, Lex_ident_cli_st *str)
1990{
1991 uchar c;
1992 bool is_8bit;
1993 CHARSET_INFO *const cs= thd->charset();
1994 const uchar *const ident_map= cs->ident_map;
1995 DBUG_ASSERT(m_tok_start <= m_ptr);
1996
1997 if (use_mb(cs))
1998 {
1999 is_8bit= true;
2000 while (ident_map[c= yyGet()])
2001 {
2002 int char_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
2003 if (char_length <= 0)
2004 break;
2005 skip_binary(char_length - 1);
2006 }
2007 }
2008 else
2009 {
2010 is_8bit= get_7bit_or_8bit_ident(thd, &c);
2011 }
2012 if (c == '.' && ident_map[(uchar) yyPeek()])
2013 next_state= MY_LEX_IDENT_SEP;// Next is '.'
2014
2015 uint length= yyLength();
2016 yyUnget(); // ptr points now after last token char
2017 str->set_ident(m_tok_start, length, is_8bit);
2018 m_cpp_text_start= m_cpp_tok_start;
2019 m_cpp_text_end= m_cpp_text_start + length;
2020 body_utf8_append(m_cpp_text_start);
2021 body_utf8_append_ident(thd, str, m_cpp_text_end);
2022 return is_8bit ? IDENT_QUOTED : IDENT;
2023}
2024
2025
2026int Lex_input_stream::scan_ident_middle(THD *thd, Lex_ident_cli_st *str,
2027 CHARSET_INFO **introducer,
2028 my_lex_states *st)
2029{
2030 CHARSET_INFO *const cs= thd->charset();
2031 const uchar *const ident_map= cs->ident_map;
2032 const uchar *const state_map= cs->state_map;
2033 const char *start;
2034 uint length;
2035 uchar c;
2036 bool is_8bit;
2037 bool resolve_introducer= true;
2038 DBUG_ASSERT(m_ptr == m_tok_start + 1); // m_ptr points to the second byte
2039
2040 if (use_mb(cs))
2041 {
2042 is_8bit= true;
2043 int char_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
2044 if (char_length <= 0)
2045 {
2046 *st= MY_LEX_CHAR;
2047 return 0;
2048 }
2049 skip_binary(char_length - 1);
2050
2051 while (ident_map[c= yyGet()])
2052 {
2053 char_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
2054 if (char_length <= 0)
2055 break;
2056 if (char_length > 1 || (c & 0x80))
2057 resolve_introducer= false;
2058 skip_binary(char_length - 1);
2059 }
2060 }
2061 else
2062 {
2063 is_8bit= get_7bit_or_8bit_ident(thd, &c) || (m_tok_start[0] & 0x80);
2064 resolve_introducer= !is_8bit;
2065 }
2066 length= yyLength();
2067 start= get_ptr();
2068 if (ignore_space)
2069 {
2070 /*
2071 If we find a space then this can't be an identifier. We notice this
2072 below by checking start != lex->ptr.
2073 */
2074 for (; state_map[(uchar) c] == MY_LEX_SKIP ; c= yyGet())
2075 {
2076 if (c == '\n')
2077 yylineno++;
2078 }
2079 }
2080 if (start == get_ptr() && c == '.' && ident_map[(uchar) yyPeek()])
2081 next_state= MY_LEX_IDENT_SEP;
2082 else
2083 { // '(' must follow directly if function
2084 int tokval;
2085 yyUnget();
2086 if ((tokval= find_keyword(str, length, c == '(')))
2087 {
2088 next_state= MY_LEX_START; // Allow signed numbers
2089 return(tokval); // Was keyword
2090 }
2091 yySkip(); // next state does a unget
2092 }
2093
2094 /*
2095 Note: "SELECT _bla AS 'alias'"
2096 _bla should be considered as a IDENT if charset haven't been found.
2097 So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
2098 producing an error.
2099 */
2100 DBUG_ASSERT(length > 0);
2101 if (resolve_introducer && m_tok_start[0] == '_')
2102 {
2103
2104 yyUnget(); // ptr points now after last token char
2105 str->set_ident(m_tok_start, length, false);
2106
2107 m_cpp_text_start= m_cpp_tok_start;
2108 m_cpp_text_end= m_cpp_text_start + length;
2109 body_utf8_append(m_cpp_text_start, m_cpp_tok_start + length);
2110 ErrConvString csname(str->str + 1, str->length - 1, &my_charset_bin);
2111 CHARSET_INFO *cs= get_charset_by_csname(csname.ptr(),
2112 MY_CS_PRIMARY, MYF(0));
2113 if (cs)
2114 {
2115 *introducer= cs;
2116 return UNDERSCORE_CHARSET;
2117 }
2118 return IDENT;
2119 }
2120
2121 yyUnget(); // ptr points now after last token char
2122 str->set_ident(m_tok_start, length, is_8bit);
2123 m_cpp_text_start= m_cpp_tok_start;
2124 m_cpp_text_end= m_cpp_text_start + length;
2125 body_utf8_append(m_cpp_text_start);
2126 body_utf8_append_ident(thd, str, m_cpp_text_end);
2127 return is_8bit ? IDENT_QUOTED : IDENT;
2128}
2129
2130
2131int Lex_input_stream::scan_ident_delimited(THD *thd,
2132 Lex_ident_cli_st *str)
2133{
2134 CHARSET_INFO *const cs= thd->charset();
2135 uint double_quotes= 0;
2136 uchar c, quote_char= m_tok_start[0];
2137 DBUG_ASSERT(m_ptr == m_tok_start + 1);
2138
2139 while ((c= yyGet()))
2140 {
2141 int var_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
2142 if (var_length == 1)
2143 {
2144 if (c == quote_char)
2145 {
2146 if (yyPeek() != quote_char)
2147 break;
2148 c= yyGet();
2149 double_quotes++;
2150 continue;
2151 }
2152 }
2153 else if (var_length > 1)
2154 {
2155 skip_binary(var_length - 1);
2156 }
2157 }
2158
2159 str->set_ident_quoted(m_tok_start + 1, yyLength() - 1, true, quote_char);
2160 yyUnget(); // ptr points now after last token char
2161
2162 m_cpp_text_start= m_cpp_tok_start + 1;
2163 m_cpp_text_end= m_cpp_text_start + str->length;
2164
2165 if (c == quote_char)
2166 yySkip(); // Skip end `
2167 next_state= MY_LEX_START;
2168 body_utf8_append(m_cpp_text_start);
2169 // QQQ: shouldn't it add unescaped version ????
2170 body_utf8_append_ident(thd, str, m_cpp_text_end);
2171 return IDENT_QUOTED;
2172}
2173
2174
2175void trim_whitespace(CHARSET_INFO *cs, LEX_CSTRING *str, size_t * prefix_length)
2176{
2177 /*
2178 TODO:
2179 This code assumes that there are no multi-bytes characters
2180 that can be considered white-space.
2181 */
2182
2183 size_t plen= 0;
2184 while ((str->length > 0) && (my_isspace(cs, str->str[0])))
2185 {
2186 plen++;
2187 str->length --;
2188 str->str ++;
2189 }
2190 if (prefix_length)
2191 *prefix_length= plen;
2192 /*
2193 FIXME:
2194 Also, parsing backward is not safe with multi bytes characters
2195 */
2196 while ((str->length > 0) && (my_isspace(cs, str->str[str->length-1])))
2197 {
2198 str->length --;
2199 }
2200}
2201
2202
2203/*
2204 st_select_lex structures initialisations
2205*/
2206
2207void st_select_lex_node::init_query_common()
2208{
2209 options= 0;
2210 sql_cache= SQL_CACHE_UNSPECIFIED;
2211 linkage= UNSPECIFIED_TYPE;
2212 no_table_names_allowed= 0;
2213 uncacheable= 0;
2214}
2215
2216void st_select_lex_unit::init_query()
2217{
2218 init_query_common();
2219 linkage= GLOBAL_OPTIONS_TYPE;
2220 select_limit_cnt= HA_POS_ERROR;
2221 offset_limit_cnt= 0;
2222 union_distinct= 0;
2223 prepared= optimized= optimized_2= executed= 0;
2224 optimize_started= 0;
2225 item= 0;
2226 union_result= 0;
2227 table= 0;
2228 fake_select_lex= 0;
2229 saved_fake_select_lex= 0;
2230 cleaned= 0;
2231 item_list.empty();
2232 describe= 0;
2233 found_rows_for_union= 0;
2234 derived= 0;
2235 is_view= false;
2236 with_clause= 0;
2237 with_element= 0;
2238 columns_are_renamed= false;
2239 intersect_mark= NULL;
2240}
2241
2242void st_select_lex::init_query()
2243{
2244 init_query_common();
2245 table_list.empty();
2246 top_join_list.empty();
2247 join_list= &top_join_list;
2248 embedding= 0;
2249 leaf_tables_prep.empty();
2250 leaf_tables.empty();
2251 item_list.empty();
2252 min_max_opt_list.empty();
2253 join= 0;
2254 having= prep_having= where= prep_where= 0;
2255 cond_pushed_into_where= cond_pushed_into_having= 0;
2256 olap= UNSPECIFIED_OLAP_TYPE;
2257 having_fix_field= 0;
2258 context.select_lex= this;
2259 context.init();
2260 /*
2261 Add the name resolution context of the current (sub)query to the
2262 stack of contexts for the whole query.
2263 TODO:
2264 push_context may return an error if there is no memory for a new
2265 element in the stack, however this method has no return value,
2266 thus push_context should be moved to a place where query
2267 initialization is checked for failure.
2268 */
2269 parent_lex->push_context(&context, parent_lex->thd->mem_root);
2270 cond_count= between_count= with_wild= 0;
2271 max_equal_elems= 0;
2272 ref_pointer_array.reset();
2273 select_n_where_fields= 0;
2274 select_n_reserved= 0;
2275 select_n_having_items= 0;
2276 n_sum_items= 0;
2277 n_child_sum_items= 0;
2278 hidden_bit_fields= 0;
2279 subquery_in_having= explicit_limit= 0;
2280 is_item_list_lookup= 0;
2281 first_execution= 1;
2282 first_natural_join_processing= 1;
2283 first_cond_optimization= 1;
2284 parsing_place= NO_MATTER;
2285 exclude_from_table_unique_test= no_wrap_view_item= FALSE;
2286 nest_level= 0;
2287 link_next= 0;
2288 prep_leaf_list_state= UNINIT;
2289 have_merged_subqueries= FALSE;
2290 bzero((char*) expr_cache_may_be_used, sizeof(expr_cache_may_be_used));
2291 select_list_tables= 0;
2292 m_non_agg_field_used= false;
2293 m_agg_func_used= false;
2294 m_custom_agg_func_used= false;
2295 window_specs.empty();
2296 window_funcs.empty();
2297 tvc= 0;
2298 in_tvc= false;
2299 versioned_tables= 0;
2300}
2301
2302void st_select_lex::init_select()
2303{
2304 sj_nests.empty();
2305 sj_subselects.empty();
2306 group_list.empty();
2307 if (group_list_ptrs)
2308 group_list_ptrs->clear();
2309 type= 0;
2310 db= null_clex_str;
2311 having= 0;
2312 table_join_options= 0;
2313 in_sum_expr= with_wild= 0;
2314 options= 0;
2315 sql_cache= SQL_CACHE_UNSPECIFIED;
2316 ftfunc_list_alloc.empty();
2317 inner_sum_func_list= 0;
2318 ftfunc_list= &ftfunc_list_alloc;
2319 order_list.elements= 0;
2320 order_list.first= 0;
2321 order_list.next= &order_list.first;
2322 /* Set limit and offset to default values */
2323 select_limit= 0; /* denotes the default limit = HA_POS_ERROR */
2324 offset_limit= 0; /* denotes the default offset = 0 */
2325 with_sum_func= 0;
2326 with_all_modifier= 0;
2327 is_correlated= 0;
2328 cur_pos_in_select_list= UNDEF_POS;
2329 cond_value= having_value= Item::COND_UNDEF;
2330 inner_refs_list.empty();
2331 insert_tables= 0;
2332 merged_into= 0;
2333 m_non_agg_field_used= false;
2334 m_agg_func_used= false;
2335 m_custom_agg_func_used= false;
2336 name_visibility_map= 0;
2337 with_dep= 0;
2338 join= 0;
2339 lock_type= TL_READ_DEFAULT;
2340 tvc= 0;
2341 in_funcs.empty();
2342 curr_tvc_name= 0;
2343 in_tvc= false;
2344 versioned_tables= 0;
2345}
2346
2347/*
2348 st_select_lex structures linking
2349*/
2350
2351/* include on level down */
2352void st_select_lex_node::include_down(st_select_lex_node *upper)
2353{
2354 if ((next= upper->slave))
2355 next->prev= &next;
2356 prev= &upper->slave;
2357 upper->slave= this;
2358 master= upper;
2359 slave= 0;
2360}
2361
2362
2363void st_select_lex_node::add_slave(st_select_lex_node *slave_arg)
2364{
2365 for (; slave; slave= slave->next)
2366 if (slave == slave_arg)
2367 return;
2368
2369 if (slave)
2370 {
2371 st_select_lex_node *slave_arg_slave= slave_arg->slave;
2372 /* Insert in the front of list of slaves if any. */
2373 slave_arg->include_neighbour(slave);
2374 /* include_neighbour() sets slave_arg->slave=0, restore it. */
2375 slave_arg->slave= slave_arg_slave;
2376 /* Count on include_neighbour() setting the master. */
2377 DBUG_ASSERT(slave_arg->master == this);
2378 }
2379 else
2380 {
2381 slave= slave_arg;
2382 slave_arg->master= this;
2383 }
2384}
2385
2386
2387/*
2388 include on level down (but do not link)
2389
2390 SYNOPSYS
2391 st_select_lex_node::include_standalone()
2392 upper - reference on node underr which this node should be included
2393 ref - references on reference on this node
2394*/
2395void st_select_lex_node::include_standalone(st_select_lex_node *upper,
2396 st_select_lex_node **ref)
2397{
2398 next= 0;
2399 prev= ref;
2400 master= upper;
2401 slave= 0;
2402}
2403
2404/* include neighbour (on same level) */
2405void st_select_lex_node::include_neighbour(st_select_lex_node *before)
2406{
2407 if ((next= before->next))
2408 next->prev= &next;
2409 prev= &before->next;
2410 before->next= this;
2411 master= before->master;
2412 slave= 0;
2413}
2414
2415/* including in global SELECT_LEX list */
2416void st_select_lex_node::include_global(st_select_lex_node **plink)
2417{
2418 if ((link_next= *plink))
2419 link_next->link_prev= &link_next;
2420 link_prev= plink;
2421 *plink= this;
2422}
2423
2424//excluding from global list (internal function)
2425void st_select_lex_node::fast_exclude()
2426{
2427 if (link_prev)
2428 {
2429 if ((*link_prev= link_next))
2430 link_next->link_prev= link_prev;
2431 }
2432 // Remove slave structure
2433 for (; slave; slave= slave->next)
2434 slave->fast_exclude();
2435
2436}
2437
2438
2439/**
2440 @brief
2441 Insert a new chain of nodes into another chain before a particular link
2442
2443 @param in/out
2444 ptr_pos_to_insert the address of the chain pointer pointing to the link
2445 before which the subchain has to be inserted
2446 @param
2447 end_chain_node the last link of the subchain to be inserted
2448
2449 @details
2450 The method inserts the chain of nodes starting from this node and ending
2451 with the node nd_chain_node into another chain of nodes before the node
2452 pointed to by *ptr_pos_to_insert.
2453 It is assumed that ptr_pos_to_insert belongs to the chain where we insert.
2454 So it must be updated.
2455
2456 @retval
2457 The method returns the pointer to the first link of the inserted chain
2458*/
2459
2460st_select_lex_node *st_select_lex_node:: insert_chain_before(
2461 st_select_lex_node **ptr_pos_to_insert,
2462 st_select_lex_node *end_chain_node)
2463{
2464 end_chain_node->link_next= *ptr_pos_to_insert;
2465 (*ptr_pos_to_insert)->link_prev= &end_chain_node->link_next;
2466 this->link_prev= ptr_pos_to_insert;
2467 return this;
2468}
2469
2470
2471/*
2472 Detach the node from its master and attach it to a new master
2473*/
2474
2475void st_select_lex_node::move_as_slave(st_select_lex_node *new_master)
2476{
2477 exclude_from_tree();
2478 if (new_master->slave)
2479 {
2480 st_select_lex_node *curr= new_master->slave;
2481 for ( ; curr->next ; curr= curr->next) ;
2482 prev= &curr->next;
2483 }
2484 else
2485 prev= &new_master->slave;
2486 *prev= this;
2487 next= 0;
2488 master= new_master;
2489}
2490
2491
2492/*
2493 Exclude a node from the tree lex structure, but leave it in the global
2494 list of nodes.
2495*/
2496
2497void st_select_lex_node::exclude_from_tree()
2498{
2499 if ((*prev= next))
2500 next->prev= prev;
2501}
2502
2503
2504/*
2505 Exclude select_lex structure (except first (first select can't be
2506 deleted, because it is most upper select))
2507*/
2508void st_select_lex_node::exclude()
2509{
2510 /* exclude from global list */
2511 fast_exclude();
2512 /* exclude from other structures */
2513 exclude_from_tree();
2514 /*
2515 We do not need following statements, because prev pointer of first
2516 list element point to master->slave
2517 if (master->slave == this)
2518 master->slave= next;
2519 */
2520}
2521
2522
2523/*
2524 Exclude level of current unit from tree of SELECTs
2525
2526 SYNOPSYS
2527 st_select_lex_unit::exclude_level()
2528
2529 NOTE: units which belong to current will be brought up on level of
2530 currernt unit
2531*/
2532void st_select_lex_unit::exclude_level()
2533{
2534 SELECT_LEX_UNIT *units= 0, **units_last= &units;
2535 for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
2536 {
2537 // unlink current level from global SELECTs list
2538 if (sl->link_prev && (*sl->link_prev= sl->link_next))
2539 sl->link_next->link_prev= sl->link_prev;
2540
2541 // bring up underlay levels
2542 SELECT_LEX_UNIT **last= 0;
2543 for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
2544 {
2545 u->master= master;
2546 last= (SELECT_LEX_UNIT**)&(u->next);
2547 }
2548 if (last)
2549 {
2550 (*units_last)= sl->first_inner_unit();
2551 units_last= last;
2552 }
2553 }
2554 if (units)
2555 {
2556 // include brought up levels in place of current
2557 (*prev)= units;
2558 (*units_last)= (SELECT_LEX_UNIT*)next;
2559 if (next)
2560 next->prev= (SELECT_LEX_NODE**)units_last;
2561 units->prev= prev;
2562 }
2563 else
2564 {
2565 // exclude currect unit from list of nodes
2566 (*prev)= next;
2567 if (next)
2568 next->prev= prev;
2569 }
2570 // Mark it excluded
2571 prev= NULL;
2572}
2573
2574
2575#if 0
2576/*
2577 Exclude subtree of current unit from tree of SELECTs
2578
2579 SYNOPSYS
2580 st_select_lex_unit::exclude_tree()
2581*/
2582void st_select_lex_unit::exclude_tree()
2583{
2584 for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
2585 {
2586 // unlink current level from global SELECTs list
2587 if (sl->link_prev && (*sl->link_prev= sl->link_next))
2588 sl->link_next->link_prev= sl->link_prev;
2589
2590 // unlink underlay levels
2591 for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
2592 {
2593 u->exclude_level();
2594 }
2595 }
2596 // exclude currect unit from list of nodes
2597 (*prev)= next;
2598 if (next)
2599 next->prev= prev;
2600}
2601#endif
2602
2603
2604/*
2605 st_select_lex_node::mark_as_dependent mark all st_select_lex struct from
2606 this to 'last' as dependent
2607
2608 SYNOPSIS
2609 last - pointer to last st_select_lex struct, before which all
2610 st_select_lex have to be marked as dependent
2611
2612 NOTE
2613 'last' should be reachable from this st_select_lex_node
2614*/
2615
2616bool st_select_lex::mark_as_dependent(THD *thd, st_select_lex *last,
2617 Item *dependency)
2618{
2619
2620 DBUG_ASSERT(this != last);
2621
2622 /*
2623 Mark all selects from resolved to 1 before select where was
2624 found table as depended (of select where was found table)
2625 */
2626 SELECT_LEX *s= this;
2627 do
2628 {
2629 if (!(s->uncacheable & UNCACHEABLE_DEPENDENT_GENERATED))
2630 {
2631 // Select is dependent of outer select
2632 s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
2633 UNCACHEABLE_DEPENDENT_GENERATED;
2634 SELECT_LEX_UNIT *munit= s->master_unit();
2635 munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
2636 UNCACHEABLE_DEPENDENT_GENERATED;
2637 for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
2638 {
2639 if (sl != s &&
2640 !(sl->uncacheable & (UNCACHEABLE_DEPENDENT_GENERATED |
2641 UNCACHEABLE_UNITED)))
2642 sl->uncacheable|= UNCACHEABLE_UNITED;
2643 }
2644 }
2645
2646 Item_subselect *subquery_expr= s->master_unit()->item;
2647 if (subquery_expr && subquery_expr->mark_as_dependent(thd, last,
2648 dependency))
2649 return TRUE;
2650 } while ((s= s->outer_select()) != last && s != 0);
2651 is_correlated= TRUE;
2652 this->master_unit()->item->is_correlated= TRUE;
2653 return FALSE;
2654}
2655
2656/*
2657 prohibit using LIMIT clause
2658*/
2659bool st_select_lex::test_limit()
2660{
2661 if (select_limit != 0)
2662 {
2663 my_error(ER_NOT_SUPPORTED_YET, MYF(0),
2664 "LIMIT & IN/ALL/ANY/SOME subquery");
2665 return(1);
2666 }
2667 return(0);
2668}
2669
2670
2671
2672st_select_lex* st_select_lex_unit::outer_select()
2673{
2674 return (st_select_lex*) master;
2675}
2676
2677
2678ha_rows st_select_lex::get_offset()
2679{
2680 ulonglong val= 0;
2681
2682 if (offset_limit)
2683 {
2684 // see comment for st_select_lex::get_limit()
2685 bool fix_fields_successful= true;
2686 if (!offset_limit->fixed)
2687 {
2688 fix_fields_successful= !offset_limit->fix_fields(master_unit()->thd,
2689 NULL);
2690
2691 DBUG_ASSERT(fix_fields_successful);
2692 }
2693 val= fix_fields_successful ? offset_limit->val_uint() : HA_POS_ERROR;
2694 }
2695
2696 return (ha_rows)val;
2697}
2698
2699
2700ha_rows st_select_lex::get_limit()
2701{
2702 ulonglong val= HA_POS_ERROR;
2703
2704 if (select_limit)
2705 {
2706 /*
2707 fix_fields() has not been called for select_limit. That's due to the
2708 historical reasons -- this item could be only of type Item_int, and
2709 Item_int does not require fix_fields(). Thus, fix_fields() was never
2710 called for select_limit.
2711
2712 Some time ago, Item_splocal was also allowed for LIMIT / OFFSET clauses.
2713 However, the fix_fields() behavior was not updated, which led to a crash
2714 in some cases.
2715
2716 There is no single place where to call fix_fields() for LIMIT / OFFSET
2717 items during the fix-fields-phase. Thus, for the sake of readability,
2718 it was decided to do it here, on the evaluation phase (which is a
2719 violation of design, but we chose the lesser of two evils).
2720
2721 We can call fix_fields() here, because select_limit can be of two
2722 types only: Item_int and Item_splocal. Item_int::fix_fields() is trivial,
2723 and Item_splocal::fix_fields() (or rather Item_sp_variable::fix_fields())
2724 has the following properties:
2725 1) it does not affect other items;
2726 2) it does not fail.
2727
2728 Nevertheless DBUG_ASSERT was added to catch future changes in
2729 fix_fields() implementation. Also added runtime check against a result
2730 of fix_fields() in order to handle error condition in non-debug build.
2731 */
2732 bool fix_fields_successful= true;
2733 if (!select_limit->fixed)
2734 {
2735 fix_fields_successful= !select_limit->fix_fields(master_unit()->thd,
2736 NULL);
2737
2738 DBUG_ASSERT(fix_fields_successful);
2739 }
2740 val= fix_fields_successful ? select_limit->val_uint() : HA_POS_ERROR;
2741 }
2742
2743 return (ha_rows)val;
2744}
2745
2746
2747bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
2748{
2749 return add_to_list(thd, order_list, item, asc);
2750}
2751
2752
2753bool st_select_lex::add_gorder_to_list(THD *thd, Item *item, bool asc)
2754{
2755 return add_to_list(thd, gorder_list, item, asc);
2756}
2757
2758
2759bool st_select_lex::add_item_to_list(THD *thd, Item *item)
2760{
2761 DBUG_ENTER("st_select_lex::add_item_to_list");
2762 DBUG_PRINT("info", ("Item: %p", item));
2763 DBUG_RETURN(item_list.push_back(item, thd->mem_root));
2764}
2765
2766
2767bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
2768{
2769 return add_to_list(thd, group_list, item, asc);
2770}
2771
2772
2773bool st_select_lex::add_ftfunc_to_list(THD *thd, Item_func_match *func)
2774{
2775 return !func || ftfunc_list->push_back(func, thd->mem_root); // end of memory?
2776}
2777
2778
2779st_select_lex* st_select_lex::outer_select()
2780{
2781 return (st_select_lex*) master->get_master();
2782}
2783
2784
2785bool st_select_lex::inc_in_sum_expr()
2786{
2787 in_sum_expr++;
2788 return 0;
2789}
2790
2791
2792uint st_select_lex::get_in_sum_expr()
2793{
2794 return in_sum_expr;
2795}
2796
2797
2798TABLE_LIST* st_select_lex::get_table_list()
2799{
2800 return table_list.first;
2801}
2802
2803List<Item>* st_select_lex::get_item_list()
2804{
2805 return &item_list;
2806}
2807
2808ulong st_select_lex::get_table_join_options()
2809{
2810 return table_join_options;
2811}
2812
2813
2814bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
2815{
2816
2817 if (!((options & SELECT_DISTINCT) && !group_list.elements))
2818 hidden_bit_fields= 0;
2819
2820 // find_order_in_list() may need some extra space, so multiply by two.
2821 order_group_num*= 2;
2822
2823 /*
2824 We have to create array in prepared statement memory if it is a
2825 prepared statement
2826 */
2827 Query_arena *arena= thd->stmt_arena;
2828 const uint n_elems= (n_sum_items +
2829 n_child_sum_items +
2830 item_list.elements +
2831 select_n_reserved +
2832 select_n_having_items +
2833 select_n_where_fields +
2834 order_group_num +
2835 hidden_bit_fields) * 5;
2836 if (!ref_pointer_array.is_null())
2837 {
2838 /*
2839 We need to take 'n_sum_items' into account when allocating the array,
2840 and this may actually increase during the optimization phase due to
2841 MIN/MAX rewrite in Item_in_subselect::single_value_transformer.
2842 In the usual case we can reuse the array from the prepare phase.
2843 If we need a bigger array, we must allocate a new one.
2844 */
2845 if (ref_pointer_array.size() >= n_elems)
2846 return false;
2847 }
2848 Item **array= static_cast<Item**>(arena->alloc(sizeof(Item*) * n_elems));
2849 if (likely(array != NULL))
2850 ref_pointer_array= Ref_ptr_array(array, n_elems);
2851
2852 return array == NULL;
2853}
2854
2855
2856void st_select_lex_unit::print(String *str, enum_query_type query_type)
2857{
2858 bool union_all= !union_distinct;
2859 if (with_clause)
2860 with_clause->print(str, query_type);
2861 for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
2862 {
2863 if (sl != first_select())
2864 {
2865 switch (sl->linkage)
2866 {
2867 default:
2868 DBUG_ASSERT(0);
2869 case UNION_TYPE:
2870 str->append(STRING_WITH_LEN(" union "));
2871 if (union_all)
2872 str->append(STRING_WITH_LEN("all "));
2873 else if (union_distinct == sl)
2874 union_all= TRUE;
2875 break;
2876 case INTERSECT_TYPE:
2877 str->append(STRING_WITH_LEN(" intersect "));
2878 break;
2879 case EXCEPT_TYPE:
2880 str->append(STRING_WITH_LEN(" except "));
2881 break;
2882 }
2883 }
2884 if (sl->braces)
2885 str->append('(');
2886 sl->print(thd, str, query_type);
2887 if (sl->braces)
2888 str->append(')');
2889 }
2890 if (fake_select_lex)
2891 {
2892 if (fake_select_lex->order_list.elements)
2893 {
2894 str->append(STRING_WITH_LEN(" order by "));
2895 fake_select_lex->print_order(str,
2896 fake_select_lex->order_list.first,
2897 query_type);
2898 }
2899 fake_select_lex->print_limit(thd, str, query_type);
2900 }
2901 else if (saved_fake_select_lex)
2902 saved_fake_select_lex->print_limit(thd, str, query_type);
2903}
2904
2905
2906void st_select_lex::print_order(String *str,
2907 ORDER *order,
2908 enum_query_type query_type)
2909{
2910 for (; order; order= order->next)
2911 {
2912 if (order->counter_used)
2913 {
2914 char buffer[20];
2915 size_t length= my_snprintf(buffer, 20, "%d", order->counter);
2916 str->append(buffer, (uint) length);
2917 }
2918 else
2919 {
2920 /* replace numeric reference with equivalent for ORDER constant */
2921 if (order->item[0]->type() == Item::INT_ITEM &&
2922 order->item[0]->basic_const_item())
2923 {
2924 /* make it expression instead of integer constant */
2925 str->append(STRING_WITH_LEN("''"));
2926 }
2927 else
2928 (*order->item)->print(str, query_type);
2929 }
2930 if (order->direction == ORDER::ORDER_DESC)
2931 str->append(STRING_WITH_LEN(" desc"));
2932 if (order->next)
2933 str->append(',');
2934 }
2935}
2936
2937
2938void st_select_lex::print_limit(THD *thd,
2939 String *str,
2940 enum_query_type query_type)
2941{
2942 SELECT_LEX_UNIT *unit= master_unit();
2943 Item_subselect *item= unit->item;
2944
2945 if (item && unit->global_parameters() == this)
2946 {
2947 Item_subselect::subs_type subs_type= item->substype();
2948 if (subs_type == Item_subselect::EXISTS_SUBS ||
2949 subs_type == Item_subselect::IN_SUBS ||
2950 subs_type == Item_subselect::ALL_SUBS)
2951 {
2952 return;
2953 }
2954 }
2955 if (explicit_limit)
2956 {
2957 str->append(STRING_WITH_LEN(" limit "));
2958 if (offset_limit)
2959 {
2960 offset_limit->print(str, query_type);
2961 str->append(',');
2962 }
2963 select_limit->print(str, query_type);
2964 }
2965}
2966
2967
2968/**
2969 @brief Restore the LEX and THD in case of a parse error.
2970
2971 This is a clean up call that is invoked by the Bison generated
2972 parser before returning an error from MYSQLparse. If your
2973 semantic actions manipulate with the global thread state (which
2974 is a very bad practice and should not normally be employed) and
2975 need a clean-up in case of error, and you can not use %destructor
2976 rule in the grammar file itself, this function should be used
2977 to implement the clean up.
2978*/
2979
2980void LEX::cleanup_lex_after_parse_error(THD *thd)
2981{
2982 /*
2983 Delete sphead for the side effect of restoring of the original
2984 LEX state, thd->lex, thd->mem_root and thd->free_list if they
2985 were replaced when parsing stored procedure statements. We
2986 will never use sphead object after a parse error, so it's okay
2987 to delete it only for the sake of the side effect.
2988 TODO: make this functionality explicit in sp_head class.
2989 Sic: we must nullify the member of the main lex, not the
2990 current one that will be thrown away
2991 */
2992 if (thd->lex->sphead)
2993 {
2994 sp_package *pkg;
2995 thd->lex->sphead->restore_thd_mem_root(thd);
2996 if ((pkg= thd->lex->sphead->m_parent))
2997 {
2998 /*
2999 If a syntax error happened inside a package routine definition,
3000 then thd->lex points to the routine sublex. We need to restore to
3001 the top level LEX.
3002 */
3003 DBUG_ASSERT(pkg->m_top_level_lex);
3004 DBUG_ASSERT(pkg == pkg->m_top_level_lex->sphead);
3005 pkg->restore_thd_mem_root(thd);
3006 LEX *top= pkg->m_top_level_lex;
3007 delete pkg;
3008 thd->lex= top;
3009 thd->lex->sphead= NULL;
3010 }
3011 else
3012 {
3013 delete thd->lex->sphead;
3014 thd->lex->sphead= NULL;
3015 }
3016 }
3017}
3018
3019/*
3020 Initialize (or reset) Query_tables_list object.
3021
3022 SYNOPSIS
3023 reset_query_tables_list()
3024 init TRUE - we should perform full initialization of object with
3025 allocating needed memory
3026 FALSE - object is already initialized so we should only reset
3027 its state so it can be used for parsing/processing
3028 of new statement
3029
3030 DESCRIPTION
3031 This method initializes Query_tables_list so it can be used as part
3032 of LEX object for parsing/processing of statement. One can also use
3033 this method to reset state of already initialized Query_tables_list
3034 so it can be used for processing of new statement.
3035*/
3036
3037void Query_tables_list::reset_query_tables_list(bool init)
3038{
3039 sql_command= SQLCOM_END;
3040 if (!init && query_tables)
3041 {
3042 TABLE_LIST *table= query_tables;
3043 for (;;)
3044 {
3045 delete table->view;
3046 if (query_tables_last == &table->next_global ||
3047 !(table= table->next_global))
3048 break;
3049 }
3050 }
3051 query_tables= 0;
3052 query_tables_last= &query_tables;
3053 query_tables_own_last= 0;
3054 if (init)
3055 {
3056 /*
3057 We delay real initialization of hash (and therefore related
3058 memory allocation) until first insertion into this hash.
3059 */
3060 my_hash_clear(&sroutines);
3061 }
3062 else if (sroutines.records)
3063 {
3064 /* Non-zero sroutines.records means that hash was initialized. */
3065 my_hash_reset(&sroutines);
3066 }
3067 sroutines_list.empty();
3068 sroutines_list_own_last= sroutines_list.next;
3069 sroutines_list_own_elements= 0;
3070 binlog_stmt_flags= 0;
3071 stmt_accessed_table_flag= 0;
3072}
3073
3074
3075/*
3076 Destroy Query_tables_list object with freeing all resources used by it.
3077
3078 SYNOPSIS
3079 destroy_query_tables_list()
3080*/
3081
3082void Query_tables_list::destroy_query_tables_list()
3083{
3084 my_hash_free(&sroutines);
3085}
3086
3087
3088/*
3089 Initialize LEX object.
3090
3091 SYNOPSIS
3092 LEX::LEX()
3093
3094 NOTE
3095 LEX object initialized with this constructor can be used as part of
3096 THD object for which one can safely call open_tables(), lock_tables()
3097 and close_thread_tables() functions. But it is not yet ready for
3098 statement parsing. On should use lex_start() function to prepare LEX
3099 for this.
3100*/
3101
3102LEX::LEX()
3103 : explain(NULL), result(0), arena_for_set_stmt(0), mem_root_for_set_stmt(0),
3104 option_type(OPT_DEFAULT), context_analysis_only(0), sphead(0),
3105 default_used(0), is_lex_started(0), limit_rows_examined_cnt(ULONGLONG_MAX)
3106{
3107
3108 init_dynamic_array2(&plugins, sizeof(plugin_ref), plugins_static_buffer,
3109 INITIAL_LEX_PLUGIN_LIST_SIZE,
3110 INITIAL_LEX_PLUGIN_LIST_SIZE, 0);
3111 reset_query_tables_list(TRUE);
3112 mi.init();
3113 init_dynamic_array2(&delete_gtid_domain, sizeof(ulong*),
3114 gtid_domain_static_buffer,
3115 initial_gtid_domain_buffer_size,
3116 initial_gtid_domain_buffer_size, 0);
3117}
3118
3119
3120/*
3121 Check whether the merging algorithm can be used on this VIEW
3122
3123 SYNOPSIS
3124 LEX::can_be_merged()
3125
3126 DESCRIPTION
3127 We can apply merge algorithm if it is single SELECT view with
3128 subqueries only in WHERE clause (we do not count SELECTs of underlying
3129 views, and second level subqueries) and we have not grpouping, ordering,
3130 HAVING clause, aggregate functions, DISTINCT clause, LIMIT clause and
3131 several underlying tables.
3132
3133 RETURN
3134 FALSE - only temporary table algorithm can be used
3135 TRUE - merge algorithm can be used
3136*/
3137
3138bool LEX::can_be_merged()
3139{
3140 // TODO: do not forget implement case when select_lex.table_list.elements==0
3141
3142 /* find non VIEW subqueries/unions */
3143 bool selects_allow_merge= (select_lex.next_select() == 0 &&
3144 !(select_lex.uncacheable &
3145 UNCACHEABLE_RAND));
3146 if (selects_allow_merge)
3147 {
3148 for (SELECT_LEX_UNIT *tmp_unit= select_lex.first_inner_unit();
3149 tmp_unit;
3150 tmp_unit= tmp_unit->next_unit())
3151 {
3152 if (tmp_unit->first_select()->parent_lex == this &&
3153 (tmp_unit->item != 0 &&
3154 (tmp_unit->item->place() != IN_WHERE &&
3155 tmp_unit->item->place() != IN_ON &&
3156 tmp_unit->item->place() != SELECT_LIST)))
3157 {
3158 selects_allow_merge= 0;
3159 break;
3160 }
3161 }
3162 }
3163
3164 return (selects_allow_merge &&
3165 select_lex.group_list.elements == 0 &&
3166 select_lex.having == 0 &&
3167 select_lex.with_sum_func == 0 &&
3168 select_lex.table_list.elements >= 1 &&
3169 !(select_lex.options & SELECT_DISTINCT) &&
3170 select_lex.select_limit == 0);
3171}
3172
3173
3174/*
3175 check if command can use VIEW with MERGE algorithm (for top VIEWs)
3176
3177 SYNOPSIS
3178 LEX::can_use_merged()
3179
3180 DESCRIPTION
3181 Only listed here commands can use merge algorithm in top level
3182 SELECT_LEX (for subqueries will be used merge algorithm if
3183 LEX::can_not_use_merged() is not TRUE).
3184
3185 RETURN
3186 FALSE - command can't use merged VIEWs
3187 TRUE - VIEWs with MERGE algorithms can be used
3188*/
3189
3190bool LEX::can_use_merged()
3191{
3192 switch (sql_command)
3193 {
3194 case SQLCOM_SELECT:
3195 case SQLCOM_CREATE_TABLE:
3196 case SQLCOM_UPDATE:
3197 case SQLCOM_UPDATE_MULTI:
3198 case SQLCOM_DELETE:
3199 case SQLCOM_DELETE_MULTI:
3200 case SQLCOM_INSERT:
3201 case SQLCOM_INSERT_SELECT:
3202 case SQLCOM_REPLACE:
3203 case SQLCOM_REPLACE_SELECT:
3204 case SQLCOM_LOAD:
3205 return TRUE;
3206 default:
3207 return FALSE;
3208 }
3209}
3210
3211/*
3212 Check if command can't use merged views in any part of command
3213
3214 SYNOPSIS
3215 LEX::can_not_use_merged()
3216
3217 DESCRIPTION
3218 Temporary table algorithm will be used on all SELECT levels for queries
3219 listed here (see also LEX::can_use_merged()).
3220
3221 RETURN
3222 FALSE - command can't use merged VIEWs
3223 TRUE - VIEWs with MERGE algorithms can be used
3224*/
3225
3226bool LEX::can_not_use_merged()
3227{
3228 switch (sql_command)
3229 {
3230 case SQLCOM_CREATE_VIEW:
3231 case SQLCOM_SHOW_CREATE:
3232 /*
3233 SQLCOM_SHOW_FIELDS is necessary to make
3234 information schema tables working correctly with views.
3235 see get_schema_tables_result function
3236 */
3237 case SQLCOM_SHOW_FIELDS:
3238 return TRUE;
3239 default:
3240 return FALSE;
3241 }
3242}
3243
3244/*
3245 Detect that we need only table structure of derived table/view
3246
3247 SYNOPSIS
3248 only_view_structure()
3249
3250 RETURN
3251 TRUE yes, we need only structure
3252 FALSE no, we need data
3253*/
3254
3255bool LEX::only_view_structure()
3256{
3257 switch (sql_command) {
3258 case SQLCOM_SHOW_CREATE:
3259 case SQLCOM_SHOW_TABLES:
3260 case SQLCOM_SHOW_FIELDS:
3261 case SQLCOM_REVOKE_ALL:
3262 case SQLCOM_REVOKE:
3263 case SQLCOM_GRANT:
3264 case SQLCOM_CREATE_VIEW:
3265 return TRUE;
3266 default:
3267 return FALSE;
3268 }
3269}
3270
3271
3272/*
3273 Should Items_ident be printed correctly
3274
3275 SYNOPSIS
3276 need_correct_ident()
3277
3278 RETURN
3279 TRUE yes, we need only structure
3280 FALSE no, we need data
3281*/
3282
3283
3284bool LEX::need_correct_ident()
3285{
3286 switch(sql_command)
3287 {
3288 case SQLCOM_SHOW_CREATE:
3289 case SQLCOM_SHOW_TABLES:
3290 case SQLCOM_CREATE_VIEW:
3291 return TRUE;
3292 default:
3293 return FALSE;
3294 }
3295}
3296
3297/*
3298 Get effective type of CHECK OPTION for given view
3299
3300 SYNOPSIS
3301 get_effective_with_check()
3302 view given view
3303
3304 NOTE
3305 It have not sense to set CHECK OPTION for SELECT satement or subqueries,
3306 so we do not.
3307
3308 RETURN
3309 VIEW_CHECK_NONE no need CHECK OPTION
3310 VIEW_CHECK_LOCAL CHECK OPTION LOCAL
3311 VIEW_CHECK_CASCADED CHECK OPTION CASCADED
3312*/
3313
3314uint8 LEX::get_effective_with_check(TABLE_LIST *view)
3315{
3316 if (view->select_lex->master_unit() == &unit &&
3317 which_check_option_applicable())
3318 return (uint8)view->with_check;
3319 return VIEW_CHECK_NONE;
3320}
3321
3322
3323/**
3324 This method should be called only during parsing.
3325 It is aware of compound statements (stored routine bodies)
3326 and will initialize the destination with the default
3327 database of the stored routine, rather than the default
3328 database of the connection it is parsed in.
3329 E.g. if one has no current database selected, or current database
3330 set to 'bar' and then issues:
3331
3332 CREATE PROCEDURE foo.p1() BEGIN SELECT * FROM t1 END//
3333
3334 t1 is meant to refer to foo.t1, not to bar.t1.
3335
3336 This method is needed to support this rule.
3337
3338 @return TRUE in case of error (parsing should be aborted, FALSE in
3339 case of success
3340*/
3341
3342bool LEX::copy_db_to(LEX_CSTRING *to)
3343{
3344 if (sphead && sphead->m_name.str)
3345 {
3346 DBUG_ASSERT(sphead->m_db.str && sphead->m_db.length);
3347 /*
3348 It is safe to assign the string by-pointer, both sphead and
3349 its statements reside in the same memory root.
3350 */
3351 *to= sphead->m_db;
3352 return FALSE;
3353 }
3354 return thd->copy_db_to(to);
3355}
3356
3357/**
3358 Initialize offset and limit counters.
3359
3360 @param sl SELECT_LEX to get offset and limit from.
3361*/
3362
3363void st_select_lex_unit::set_limit(st_select_lex *sl)
3364{
3365 DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
3366
3367 offset_limit_cnt= sl->get_offset();
3368 select_limit_cnt= sl->get_limit();
3369 if (select_limit_cnt + offset_limit_cnt >= select_limit_cnt)
3370 select_limit_cnt+= offset_limit_cnt;
3371 else
3372 select_limit_cnt= HA_POS_ERROR;
3373}
3374
3375
3376/**
3377 Decide if a temporary table is needed for the UNION.
3378
3379 @retval true A temporary table is needed.
3380 @retval false A temporary table is not needed.
3381 */
3382
3383bool st_select_lex_unit::union_needs_tmp_table()
3384{
3385 if (with_element && with_element->is_recursive)
3386 return true;
3387 return union_distinct != NULL ||
3388 global_parameters()->order_list.elements != 0 ||
3389 thd->lex->sql_command == SQLCOM_INSERT_SELECT ||
3390 thd->lex->sql_command == SQLCOM_REPLACE_SELECT;
3391}
3392
3393/**
3394 @brief Set the initial purpose of this TABLE_LIST object in the list of used
3395 tables.
3396
3397 We need to track this information on table-by-table basis, since when this
3398 table becomes an element of the pre-locked list, it's impossible to identify
3399 which SQL sub-statement it has been originally used in.
3400
3401 E.g.:
3402
3403 User request: SELECT * FROM t1 WHERE f1();
3404 FUNCTION f1(): DELETE FROM t2; RETURN 1;
3405 BEFORE DELETE trigger on t2: INSERT INTO t3 VALUES (old.a);
3406
3407 For this user request, the pre-locked list will contain t1, t2, t3
3408 table elements, each needed for different DML.
3409
3410 The trigger event map is updated to reflect INSERT, UPDATE, DELETE,
3411 REPLACE, LOAD DATA, CREATE TABLE .. SELECT, CREATE TABLE ..
3412 REPLACE SELECT statements, and additionally ON DUPLICATE KEY UPDATE
3413 clause.
3414*/
3415
3416void LEX::set_trg_event_type_for_tables()
3417{
3418 uint8 new_trg_event_map= 0;
3419 DBUG_ENTER("LEX::set_trg_event_type_for_tables");
3420
3421 /*
3422 Some auxiliary operations
3423 (e.g. GRANT processing) create TABLE_LIST instances outside
3424 the parser. Additionally, some commands (e.g. OPTIMIZE) change
3425 the lock type for a table only after parsing is done. Luckily,
3426 these do not fire triggers and do not need to pre-load them.
3427 For these TABLE_LISTs set_trg_event_type is never called, and
3428 trg_event_map is always empty. That means that the pre-locking
3429 algorithm will ignore triggers defined on these tables, if
3430 any, and the execution will either fail with an assert in
3431 sql_trigger.cc or with an error that a used table was not
3432 pre-locked, in case of a production build.
3433
3434 TODO: this usage pattern creates unnecessary module dependencies
3435 and should be rewritten to go through the parser.
3436 Table list instances created outside the parser in most cases
3437 refer to mysql.* system tables. It is not allowed to have
3438 a trigger on a system table, but keeping track of
3439 initialization provides extra safety in case this limitation
3440 is circumvented.
3441 */
3442
3443 switch (sql_command) {
3444 case SQLCOM_LOCK_TABLES:
3445 /*
3446 On a LOCK TABLE, all triggers must be pre-loaded for this TABLE_LIST
3447 when opening an associated TABLE.
3448 */
3449 new_trg_event_map= static_cast<uint8>
3450 (1 << static_cast<int>(TRG_EVENT_INSERT)) |
3451 static_cast<uint8>
3452 (1 << static_cast<int>(TRG_EVENT_UPDATE)) |
3453 static_cast<uint8>
3454 (1 << static_cast<int>(TRG_EVENT_DELETE));
3455 break;
3456 /*
3457 Basic INSERT. If there is an additional ON DUPLIATE KEY UPDATE
3458 clause, it will be handled later in this method.
3459 */
3460 case SQLCOM_INSERT: /* fall through */
3461 case SQLCOM_INSERT_SELECT:
3462 /*
3463 LOAD DATA ... INFILE is expected to fire BEFORE/AFTER INSERT
3464 triggers.
3465 If the statement also has REPLACE clause, it will be
3466 handled later in this method.
3467 */
3468 case SQLCOM_LOAD: /* fall through */
3469 /*
3470 REPLACE is semantically equivalent to INSERT. In case
3471 of a primary or unique key conflict, it deletes the old
3472 record and inserts a new one. So we also may need to
3473 fire ON DELETE triggers. This functionality is handled
3474 later in this method.
3475 */
3476 case SQLCOM_REPLACE: /* fall through */
3477 case SQLCOM_REPLACE_SELECT:
3478 /*
3479 CREATE TABLE ... SELECT defaults to INSERT if the table or
3480 view already exists. REPLACE option of CREATE TABLE ...
3481 REPLACE SELECT is handled later in this method.
3482 */
3483 case SQLCOM_CREATE_TABLE:
3484 case SQLCOM_CREATE_SEQUENCE:
3485 new_trg_event_map|= static_cast<uint8>
3486 (1 << static_cast<int>(TRG_EVENT_INSERT));
3487 break;
3488 /* Basic update and multi-update */
3489 case SQLCOM_UPDATE: /* fall through */
3490 case SQLCOM_UPDATE_MULTI:
3491 new_trg_event_map|= static_cast<uint8>
3492 (1 << static_cast<int>(TRG_EVENT_UPDATE));
3493 break;
3494 /* Basic delete and multi-delete */
3495 case SQLCOM_DELETE: /* fall through */
3496 case SQLCOM_DELETE_MULTI:
3497 new_trg_event_map|= static_cast<uint8>
3498 (1 << static_cast<int>(TRG_EVENT_DELETE));
3499 break;
3500 default:
3501 break;
3502 }
3503
3504 switch (duplicates) {
3505 case DUP_UPDATE:
3506 new_trg_event_map|= static_cast<uint8>
3507 (1 << static_cast<int>(TRG_EVENT_UPDATE));
3508 break;
3509 case DUP_REPLACE:
3510 new_trg_event_map|= static_cast<uint8>
3511 (1 << static_cast<int>(TRG_EVENT_DELETE));
3512 break;
3513 case DUP_ERROR:
3514 default:
3515 break;
3516 }
3517
3518
3519 /*
3520 Do not iterate over sub-selects, only the tables in the outermost
3521 SELECT_LEX can be modified, if any.
3522 */
3523 TABLE_LIST *tables= select_lex.get_table_list();
3524
3525 while (tables)
3526 {
3527 /*
3528 This is a fast check to filter out statements that do
3529 not change data, or tables on the right side, in case of
3530 INSERT .. SELECT, CREATE TABLE .. SELECT and so on.
3531 Here we also filter out OPTIMIZE statement and non-updateable
3532 views, for which lock_type is TL_UNLOCK or TL_READ after
3533 parsing.
3534 */
3535 if (static_cast<int>(tables->lock_type) >=
3536 static_cast<int>(TL_WRITE_ALLOW_WRITE))
3537 tables->trg_event_map= new_trg_event_map;
3538 tables= tables->next_local;
3539 }
3540 DBUG_VOID_RETURN;
3541}
3542
3543
3544/*
3545 Unlink the first table from the global table list and the first table from
3546 outer select (lex->select_lex) local list
3547
3548 SYNOPSIS
3549 unlink_first_table()
3550 link_to_local Set to 1 if caller should link this table to local list
3551
3552 NOTES
3553 We assume that first tables in both lists is the same table or the local
3554 list is empty.
3555
3556 RETURN
3557 0 If 'query_tables' == 0
3558 unlinked table
3559 In this case link_to_local is set.
3560
3561*/
3562TABLE_LIST *LEX::unlink_first_table(bool *link_to_local)
3563{
3564 TABLE_LIST *first;
3565 if ((first= query_tables))
3566 {
3567 /*
3568 Exclude from global table list
3569 */
3570 if ((query_tables= query_tables->next_global))
3571 query_tables->prev_global= &query_tables;
3572 else
3573 query_tables_last= &query_tables;
3574 first->next_global= 0;
3575
3576 /*
3577 and from local list if it is not empty
3578 */
3579 if ((*link_to_local= MY_TEST(select_lex.table_list.first)))
3580 {
3581 select_lex.context.table_list=
3582 select_lex.context.first_name_resolution_table= first->next_local;
3583 select_lex.table_list.first= first->next_local;
3584 select_lex.table_list.elements--; //safety
3585 first->next_local= 0;
3586 /*
3587 Ensure that the global list has the same first table as the local
3588 list.
3589 */
3590 first_lists_tables_same();
3591 }
3592 }
3593 return first;
3594}
3595
3596
3597/*
3598 Bring first local table of first most outer select to first place in global
3599 table list
3600
3601 SYNOPSYS
3602 LEX::first_lists_tables_same()
3603
3604 NOTES
3605 In many cases (for example, usual INSERT/DELETE/...) the first table of
3606 main SELECT_LEX have special meaning => check that it is the first table
3607 in global list and re-link to be first in the global list if it is
3608 necessary. We need such re-linking only for queries with sub-queries in
3609 the select list, as only in this case tables of sub-queries will go to
3610 the global list first.
3611*/
3612
3613void LEX::first_lists_tables_same()
3614{
3615 TABLE_LIST *first_table= select_lex.table_list.first;
3616 if (query_tables != first_table && first_table != 0)
3617 {
3618 TABLE_LIST *next;
3619 if (query_tables_last == &first_table->next_global)
3620 query_tables_last= first_table->prev_global;
3621
3622 if (query_tables_own_last == &first_table->next_global)
3623 query_tables_own_last= first_table->prev_global;
3624
3625 if ((next= *first_table->prev_global= first_table->next_global))
3626 next->prev_global= first_table->prev_global;
3627 /* include in new place */
3628 first_table->next_global= query_tables;
3629 /*
3630 We are sure that query_tables is not 0, because first_table was not
3631 first table in the global list => we can use
3632 query_tables->prev_global without check of query_tables
3633 */
3634 query_tables->prev_global= &first_table->next_global;
3635 first_table->prev_global= &query_tables;
3636 query_tables= first_table;
3637 }
3638}
3639
3640
3641/*
3642 Link table back that was unlinked with unlink_first_table()
3643
3644 SYNOPSIS
3645 link_first_table_back()
3646 link_to_local do we need link this table to local
3647
3648 RETURN
3649 global list
3650*/
3651
3652void LEX::link_first_table_back(TABLE_LIST *first,
3653 bool link_to_local)
3654{
3655 if (first)
3656 {
3657 if ((first->next_global= query_tables))
3658 query_tables->prev_global= &first->next_global;
3659 else
3660 query_tables_last= &first->next_global;
3661 query_tables= first;
3662
3663 if (link_to_local)
3664 {
3665 first->next_local= select_lex.table_list.first;
3666 select_lex.context.table_list= first;
3667 select_lex.table_list.first= first;
3668 select_lex.table_list.elements++; //safety
3669 }
3670 }
3671}
3672
3673
3674
3675/*
3676 cleanup lex for case when we open table by table for processing
3677
3678 SYNOPSIS
3679 LEX::cleanup_after_one_table_open()
3680
3681 NOTE
3682 This method is mostly responsible for cleaning up of selects lists and
3683 derived tables state. To rollback changes in Query_tables_list one has
3684 to call Query_tables_list::reset_query_tables_list(FALSE).
3685*/
3686
3687void LEX::cleanup_after_one_table_open()
3688{
3689 /*
3690 thd->lex->derived_tables & additional units may be set if we open
3691 a view. It is necessary to clear thd->lex->derived_tables flag
3692 to prevent processing of derived tables during next open_and_lock_tables
3693 if next table is a real table and cleanup & remove underlying units
3694 NOTE: all units will be connected to thd->lex->select_lex, because we
3695 have not UNION on most upper level.
3696 */
3697 if (all_selects_list != &select_lex)
3698 {
3699 derived_tables= 0;
3700 select_lex.exclude_from_table_unique_test= false;
3701 /* cleunup underlying units (units of VIEW) */
3702 for (SELECT_LEX_UNIT *un= select_lex.first_inner_unit();
3703 un;
3704 un= un->next_unit())
3705 un->cleanup();
3706 /* reduce all selects list to default state */
3707 all_selects_list= &select_lex;
3708 /* remove underlying units (units of VIEW) subtree */
3709 select_lex.cut_subtree();
3710 }
3711}
3712
3713
3714/*
3715 Save current state of Query_tables_list for this LEX, and prepare it
3716 for processing of new statemnt.
3717
3718 SYNOPSIS
3719 reset_n_backup_query_tables_list()
3720 backup Pointer to Query_tables_list instance to be used for backup
3721*/
3722
3723void LEX::reset_n_backup_query_tables_list(Query_tables_list *backup)
3724{
3725 backup->set_query_tables_list(this);
3726 /*
3727 We have to perform full initialization here since otherwise we
3728 will damage backed up state.
3729 */
3730 this->reset_query_tables_list(TRUE);
3731}
3732
3733
3734/*
3735 Restore state of Query_tables_list for this LEX from backup.
3736
3737 SYNOPSIS
3738 restore_backup_query_tables_list()
3739 backup Pointer to Query_tables_list instance used for backup
3740*/
3741
3742void LEX::restore_backup_query_tables_list(Query_tables_list *backup)
3743{
3744 this->destroy_query_tables_list();
3745 this->set_query_tables_list(backup);
3746}
3747
3748
3749/*
3750 Checks for usage of routines and/or tables in a parsed statement
3751
3752 SYNOPSIS
3753 LEX:table_or_sp_used()
3754
3755 RETURN
3756 FALSE No routines and tables used
3757 TRUE Either or both routines and tables are used.
3758*/
3759
3760bool LEX::table_or_sp_used()
3761{
3762 DBUG_ENTER("table_or_sp_used");
3763
3764 if (sroutines.records || query_tables)
3765 DBUG_RETURN(TRUE);
3766
3767 DBUG_RETURN(FALSE);
3768}
3769
3770
3771/*
3772 Do end-of-prepare fixup for list of tables and their merge-VIEWed tables
3773
3774 SYNOPSIS
3775 fix_prepare_info_in_table_list()
3776 thd Thread handle
3777 tbl List of tables to process
3778
3779 DESCRIPTION
3780 Perform end-end-of prepare fixup for list of tables, if any of the tables
3781 is a merge-algorithm VIEW, recursively fix up its underlying tables as
3782 well.
3783
3784*/
3785
3786static void fix_prepare_info_in_table_list(THD *thd, TABLE_LIST *tbl)
3787{
3788 for (; tbl; tbl= tbl->next_local)
3789 {
3790 if (tbl->on_expr && !tbl->prep_on_expr)
3791 {
3792 thd->check_and_register_item_tree(&tbl->prep_on_expr, &tbl->on_expr);
3793 tbl->on_expr= tbl->on_expr->copy_andor_structure(thd);
3794 }
3795 if (tbl->is_view_or_derived() && tbl->is_merged_derived())
3796 {
3797 SELECT_LEX *sel= tbl->get_single_select();
3798 fix_prepare_info_in_table_list(thd, sel->get_table_list());
3799 }
3800 }
3801}
3802
3803
3804/*
3805 Save WHERE/HAVING/ON clauses and replace them with disposable copies
3806
3807 SYNOPSIS
3808 st_select_lex::fix_prepare_information
3809 thd thread handler
3810 conds in/out pointer to WHERE condition to be met at execution
3811 having_conds in/out pointer to HAVING condition to be met at execution
3812
3813 DESCRIPTION
3814 The passed WHERE and HAVING are to be saved for the future executions.
3815 This function saves it, and returns a copy which can be thrashed during
3816 this execution of the statement. By saving/thrashing here we mean only
3817 We also save the chain of ORDER::next in group_list, in case
3818 the list is modified by remove_const().
3819 AND/OR trees.
3820 The function also calls fix_prepare_info_in_table_list that saves all
3821 ON expressions.
3822*/
3823
3824void st_select_lex::fix_prepare_information(THD *thd, Item **conds,
3825 Item **having_conds)
3826{
3827 DBUG_ENTER("st_select_lex::fix_prepare_information");
3828 if (!thd->stmt_arena->is_conventional() && first_execution)
3829 {
3830 Query_arena_stmt on_stmt_arena(thd);
3831 first_execution= 0;
3832 if (group_list.first)
3833 {
3834 if (!group_list_ptrs)
3835 {
3836 void *mem= thd->stmt_arena->alloc(sizeof(Group_list_ptrs));
3837 group_list_ptrs= new (mem) Group_list_ptrs(thd->stmt_arena->mem_root);
3838 }
3839 group_list_ptrs->reserve(group_list.elements);
3840 for (ORDER *order= group_list.first; order; order= order->next)
3841 {
3842 group_list_ptrs->push_back(order);
3843 }
3844 }
3845 if (*conds)
3846 {
3847 thd->check_and_register_item_tree(&prep_where, conds);
3848 *conds= where= prep_where->copy_andor_structure(thd);
3849 }
3850 if (*having_conds)
3851 {
3852 thd->check_and_register_item_tree(&prep_having, having_conds);
3853 *having_conds= having= prep_having->copy_andor_structure(thd);
3854 }
3855 fix_prepare_info_in_table_list(thd, table_list.first);
3856 }
3857 DBUG_VOID_RETURN;
3858}
3859
3860
3861/*
3862 There are st_select_lex::add_table_to_list &
3863 st_select_lex::set_lock_for_tables are in sql_parse.cc
3864
3865 st_select_lex::print is in sql_select.cc
3866
3867 st_select_lex_unit::prepare, st_select_lex_unit::exec,
3868 st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
3869 st_select_lex_unit::change_result
3870 are in sql_union.cc
3871*/
3872
3873/*
3874 Sets the kind of hints to be added by the calls to add_index_hint().
3875
3876 SYNOPSIS
3877 set_index_hint_type()
3878 type_arg The kind of hints to be added from now on.
3879 clause The clause to use for hints to be added from now on.
3880
3881 DESCRIPTION
3882 Used in filling up the tagged hints list.
3883 This list is filled by first setting the kind of the hint as a
3884 context variable and then adding hints of the current kind.
3885 Then the context variable index_hint_type can be reset to the
3886 next hint type.
3887*/
3888void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
3889 index_clause_map clause)
3890{
3891 current_index_hint_type= type_arg;
3892 current_index_hint_clause= clause;
3893}
3894
3895
3896/*
3897 Makes an array to store index usage hints (ADD/FORCE/IGNORE INDEX).
3898
3899 SYNOPSIS
3900 alloc_index_hints()
3901 thd current thread.
3902*/
3903
3904void st_select_lex::alloc_index_hints (THD *thd)
3905{
3906 index_hints= new (thd->mem_root) List<Index_hint>();
3907}
3908
3909
3910
3911/*
3912 adds an element to the array storing index usage hints
3913 (ADD/FORCE/IGNORE INDEX).
3914
3915 SYNOPSIS
3916 add_index_hint()
3917 thd current thread.
3918 str name of the index.
3919 length number of characters in str.
3920
3921 RETURN VALUE
3922 0 on success, non-zero otherwise
3923*/
3924bool st_select_lex::add_index_hint (THD *thd, const char *str, size_t length)
3925{
3926 return index_hints->push_front(new (thd->mem_root)
3927 Index_hint(current_index_hint_type,
3928 current_index_hint_clause,
3929 str, length), thd->mem_root);
3930}
3931
3932
3933/**
3934 Optimize all subqueries that have not been flattened into semi-joins.
3935
3936 @details
3937 This functionality is a method of SELECT_LEX instead of JOIN because
3938 SQL statements as DELETE/UPDATE do not have a corresponding JOIN object.
3939
3940 @see JOIN::optimize_unflattened_subqueries
3941
3942 @param const_only Restrict subquery optimization to constant subqueries
3943
3944 @return Operation status
3945 @retval FALSE success.
3946 @retval TRUE error occurred.
3947*/
3948
3949bool st_select_lex::optimize_unflattened_subqueries(bool const_only)
3950{
3951 SELECT_LEX_UNIT *next_unit= NULL;
3952 for (SELECT_LEX_UNIT *un= first_inner_unit();
3953 un;
3954 un= next_unit ? next_unit : un->next_unit())
3955 {
3956 Item_subselect *subquery_predicate= un->item;
3957 next_unit= NULL;
3958
3959 if (subquery_predicate)
3960 {
3961 if (!subquery_predicate->fixed)
3962 {
3963 /*
3964 This subquery was excluded as part of some expression so it is
3965 invisible from all prepared expression.
3966 */
3967 next_unit= un->next_unit();
3968 un->exclude_level();
3969 if (next_unit)
3970 continue;
3971 break;
3972 }
3973 if (subquery_predicate->substype() == Item_subselect::IN_SUBS)
3974 {
3975 Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;
3976 if (in_subs->is_jtbm_merged)
3977 continue;
3978 }
3979
3980 if (const_only && !subquery_predicate->const_item())
3981 {
3982 /* Skip non-constant subqueries if the caller asked so. */
3983 continue;
3984 }
3985
3986 bool empty_union_result= true;
3987 bool is_correlated_unit= false;
3988 bool first= true;
3989 bool union_plan_saved= false;
3990 /*
3991 If the subquery is a UNION, optimize all the subqueries in the UNION. If
3992 there is no UNION, then the loop will execute once for the subquery.
3993 */
3994 for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
3995 {
3996 JOIN *inner_join= sl->join;
3997 if (first)
3998 first= false;
3999 else
4000 {
4001 if (!union_plan_saved)
4002 {
4003 union_plan_saved= true;
4004 if (un->save_union_explain(un->thd->lex->explain))
4005 return true; /* Failure */
4006 }
4007 }
4008 if (!inner_join)
4009 continue;
4010 SELECT_LEX *save_select= un->thd->lex->current_select;
4011 ulonglong save_options;
4012 int res;
4013 /* We need only 1 row to determine existence */
4014 un->set_limit(un->global_parameters());
4015 un->thd->lex->current_select= sl;
4016 save_options= inner_join->select_options;
4017 if (options & SELECT_DESCRIBE)
4018 {
4019 /* Optimize the subquery in the context of EXPLAIN. */
4020 sl->set_explain_type(FALSE);
4021 sl->options|= SELECT_DESCRIBE;
4022 inner_join->select_options|= SELECT_DESCRIBE;
4023 }
4024 res= inner_join->optimize();
4025 sl->update_correlated_cache();
4026 is_correlated_unit|= sl->is_correlated;
4027 inner_join->select_options= save_options;
4028 un->thd->lex->current_select= save_select;
4029
4030 Explain_query *eq;
4031 if ((eq= inner_join->thd->lex->explain))
4032 {
4033 Explain_select *expl_sel;
4034 if ((expl_sel= eq->get_select(inner_join->select_lex->select_number)))
4035 {
4036 sl->set_explain_type(TRUE);
4037 expl_sel->select_type= sl->type;
4038 }
4039 }
4040
4041 if (empty_union_result)
4042 {
4043 /*
4044 If at least one subquery in a union is non-empty, the UNION result
4045 is non-empty. If there is no UNION, the only subquery is non-empy.
4046 */
4047 empty_union_result= inner_join->empty_result();
4048 }
4049 if (res)
4050 return TRUE;
4051 }
4052 if (empty_union_result)
4053 subquery_predicate->no_rows_in_result();
4054 if (!is_correlated_unit)
4055 un->uncacheable&= ~UNCACHEABLE_DEPENDENT;
4056 subquery_predicate->is_correlated= is_correlated_unit;
4057 }
4058 }
4059 return FALSE;
4060}
4061
4062
4063
4064/**
4065 @brief Process all derived tables/views of the SELECT.
4066
4067 @param lex LEX of this thread
4068 @param phase phases to run derived tables/views through
4069
4070 @details
4071 This function runs specified 'phases' on all tables from the
4072 table_list of this select.
4073
4074 @return FALSE ok.
4075 @return TRUE an error occur.
4076*/
4077
4078bool st_select_lex::handle_derived(LEX *lex, uint phases)
4079{
4080 for (TABLE_LIST *cursor= (TABLE_LIST*) table_list.first;
4081 cursor;
4082 cursor= cursor->next_local)
4083 {
4084 if (cursor->is_view_or_derived() && cursor->handle_derived(lex, phases))
4085 return TRUE;
4086 }
4087 return FALSE;
4088}
4089
4090
4091/**
4092 @brief
4093 Returns first unoccupied table map and table number
4094
4095 @param map [out] return found map
4096 @param tablenr [out] return found tablenr
4097
4098 @details
4099 Returns first unoccupied table map and table number in this select.
4100 Map and table are returned in *'map' and *'tablenr' accordingly.
4101
4102 @retrun TRUE no free table map/table number
4103 @return FALSE found free table map/table number
4104*/
4105
4106bool st_select_lex::get_free_table_map(table_map *map, uint *tablenr)
4107{
4108 *map= 0;
4109 *tablenr= 0;
4110 TABLE_LIST *tl;
4111 List_iterator<TABLE_LIST> ti(leaf_tables);
4112 while ((tl= ti++))
4113 {
4114 if (tl->table->map > *map)
4115 *map= tl->table->map;
4116 if (tl->table->tablenr > *tablenr)
4117 *tablenr= tl->table->tablenr;
4118 }
4119 (*map)<<= 1;
4120 (*tablenr)++;
4121 if (*tablenr >= MAX_TABLES)
4122 return TRUE;
4123 return FALSE;
4124}
4125
4126
4127/**
4128 @brief
4129 Append given table to the leaf_tables list.
4130
4131 @param link Offset to which list in table structure to use
4132 @param table Table to append
4133
4134 @details
4135 Append given 'table' to the leaf_tables list using the 'link' offset.
4136 If the 'table' is linked with other tables through next_leaf/next_local
4137 chains then whole list will be appended.
4138*/
4139
4140void st_select_lex::append_table_to_list(TABLE_LIST *TABLE_LIST::*link,
4141 TABLE_LIST *table)
4142{
4143 TABLE_LIST *tl;
4144 for (tl= leaf_tables.head(); tl->*link; tl= tl->*link) ;
4145 tl->*link= table;
4146}
4147
4148
4149/*
4150 @brief
4151 Replace given table from the leaf_tables list for a list of tables
4152
4153 @param table Table to replace
4154 @param list List to substititute the table for
4155
4156 @details
4157 Replace 'table' from the leaf_tables list for a list of tables 'tbl_list'.
4158*/
4159
4160void st_select_lex::replace_leaf_table(TABLE_LIST *table, List<TABLE_LIST> &tbl_list)
4161{
4162 TABLE_LIST *tl;
4163 List_iterator<TABLE_LIST> ti(leaf_tables);
4164 while ((tl= ti++))
4165 {
4166 if (tl == table)
4167 {
4168 ti.replace(tbl_list);
4169 break;
4170 }
4171 }
4172}
4173
4174
4175/**
4176 @brief
4177 Assigns new table maps to tables in the leaf_tables list
4178
4179 @param derived Derived table to take initial table map from
4180 @param map table map to begin with
4181 @param tablenr table number to begin with
4182 @param parent_lex new parent select_lex
4183
4184 @details
4185 Assign new table maps/table numbers to all tables in the leaf_tables list.
4186 'map'/'tablenr' are used for the first table and shifted to left/
4187 increased for each consequent table in the leaf_tables list.
4188 If the 'derived' table is given then it's table map/number is used for the
4189 first table in the list and 'map'/'tablenr' are used for the second and
4190 all consequent tables.
4191 The 'parent_lex' is set as the new parent select_lex for all tables in the
4192 list.
4193*/
4194
4195void st_select_lex::remap_tables(TABLE_LIST *derived, table_map map,
4196 uint tablenr, SELECT_LEX *parent_lex)
4197{
4198 bool first_table= TRUE;
4199 TABLE_LIST *tl;
4200 table_map first_map;
4201 uint first_tablenr;
4202
4203 if (derived && derived->table)
4204 {
4205 first_map= derived->table->map;
4206 first_tablenr= derived->table->tablenr;
4207 }
4208 else
4209 {
4210 first_map= map;
4211 map<<= 1;
4212 first_tablenr= tablenr++;
4213 }
4214 /*
4215 Assign table bit/table number.
4216 To the first table of the subselect the table bit/tablenr of the
4217 derived table is assigned. The rest of tables are getting bits
4218 sequentially, starting from the provided table map/tablenr.
4219 */
4220 List_iterator<TABLE_LIST> ti(leaf_tables);
4221 while ((tl= ti++))
4222 {
4223 if (first_table)
4224 {
4225 first_table= FALSE;
4226 tl->table->set_table_map(first_map, first_tablenr);
4227 }
4228 else
4229 {
4230 tl->table->set_table_map(map, tablenr);
4231 tablenr++;
4232 map<<= 1;
4233 }
4234 SELECT_LEX *old_sl= tl->select_lex;
4235 tl->select_lex= parent_lex;
4236 for(TABLE_LIST *emb= tl->embedding;
4237 emb && emb->select_lex == old_sl;
4238 emb= emb->embedding)
4239 emb->select_lex= parent_lex;
4240 }
4241}
4242
4243/**
4244 @brief
4245 Merge a subquery into this select.
4246
4247 @param derived derived table of the subquery to be merged
4248 @param subq_select select_lex of the subquery
4249 @param map table map for assigning to merged tables from subquery
4250 @param table_no table number for assigning to merged tables from subquery
4251
4252 @details
4253 This function merges a subquery into its parent select. In short the
4254 merge operation appends the subquery FROM table list to the parent's
4255 FROM table list. In more details:
4256 .) the top_join_list of the subquery is wrapped into a join_nest
4257 and attached to 'derived'
4258 .) subquery's leaf_tables list is merged with the leaf_tables
4259 list of this select_lex
4260 .) the table maps and table numbers of the tables merged from
4261 the subquery are adjusted to reflect their new binding to
4262 this select
4263
4264 @return TRUE an error occur
4265 @return FALSE ok
4266*/
4267
4268bool SELECT_LEX::merge_subquery(THD *thd, TABLE_LIST *derived,
4269 SELECT_LEX *subq_select,
4270 uint table_no, table_map map)
4271{
4272 derived->wrap_into_nested_join(subq_select->top_join_list);
4273
4274 ftfunc_list->append(subq_select->ftfunc_list);
4275 if (join ||
4276 thd->lex->sql_command == SQLCOM_UPDATE_MULTI ||
4277 thd->lex->sql_command == SQLCOM_DELETE_MULTI)
4278 {
4279 List_iterator_fast<Item_in_subselect> li(subq_select->sj_subselects);
4280 Item_in_subselect *in_subq;
4281 while ((in_subq= li++))
4282 {
4283 sj_subselects.push_back(in_subq, thd->mem_root);
4284 if (in_subq->emb_on_expr_nest == NO_JOIN_NEST)
4285 in_subq->emb_on_expr_nest= derived;
4286 }
4287
4288 uint cnt= sizeof(expr_cache_may_be_used)/sizeof(bool);
4289 for (uint i= 0; i < cnt; i++)
4290 {
4291 if (subq_select->expr_cache_may_be_used[i])
4292 expr_cache_may_be_used[i]= true;
4293 }
4294
4295 List_iterator_fast<Item_func_in> it(subq_select->in_funcs);
4296 Item_func_in *in_func;
4297 while ((in_func= it++))
4298 {
4299 in_funcs.push_back(in_func, thd->mem_root);
4300 if (in_func->emb_on_expr_nest == NO_JOIN_NEST)
4301 in_func->emb_on_expr_nest= derived;
4302 }
4303 }
4304
4305 /* Walk through child's tables and adjust table map, tablenr,
4306 * parent_lex */
4307 subq_select->remap_tables(derived, map, table_no, this);
4308 subq_select->merged_into= this;
4309
4310 replace_leaf_table(derived, subq_select->leaf_tables);
4311
4312 return FALSE;
4313}
4314
4315
4316/**
4317 @brief
4318 Mark tables from the leaf_tables list as belong to a derived table.
4319
4320 @param derived tables will be marked as belonging to this derived
4321
4322 @details
4323 Run through the leaf_list and mark all tables as belonging to the 'derived'.
4324*/
4325
4326void SELECT_LEX::mark_as_belong_to_derived(TABLE_LIST *derived)
4327{
4328 /* Mark tables as belonging to this DT */
4329 TABLE_LIST *tl;
4330 List_iterator<TABLE_LIST> ti(leaf_tables);
4331 while ((tl= ti++))
4332 tl->belong_to_derived= derived;
4333}
4334
4335
4336/**
4337 @brief
4338 Update used_tables cache for this select
4339
4340 @details
4341 This function updates used_tables cache of ON expressions of all tables
4342 in the leaf_tables list and of the conds expression (if any).
4343*/
4344
4345void SELECT_LEX::update_used_tables()
4346{
4347 TABLE_LIST *tl;
4348 List_iterator<TABLE_LIST> ti(leaf_tables);
4349
4350 while ((tl= ti++))
4351 {
4352 if (tl->table && !tl->is_view_or_derived())
4353 {
4354 TABLE_LIST *embedding= tl->embedding;
4355 for (embedding= tl->embedding; embedding; embedding=embedding->embedding)
4356 {
4357 if (embedding->is_view_or_derived())
4358 {
4359 DBUG_ASSERT(embedding->is_merged_derived());
4360 TABLE *tab= tl->table;
4361 tab->covering_keys= tab->s->keys_for_keyread;
4362 tab->covering_keys.intersect(tab->keys_in_use_for_query);
4363 /*
4364 View/derived was merged. Need to recalculate read_set/vcol_set
4365 bitmaps here. For example:
4366 CREATE VIEW v1 AS SELECT f1,f2,f3 FROM t1;
4367 SELECT f1 FROM v1;
4368 Initially, the view definition will put all f1,f2,f3 in the
4369 read_set for t1. But after the view is merged, only f1 should
4370 be in the read_set.
4371 */
4372 bitmap_clear_all(tab->read_set);
4373 if (tab->vcol_set)
4374 bitmap_clear_all(tab->vcol_set);
4375 break;
4376 }
4377 }
4378 }
4379 }
4380
4381 ti.rewind();
4382 while ((tl= ti++))
4383 {
4384 TABLE_LIST *embedding= tl;
4385 do
4386 {
4387 bool maybe_null;
4388 if ((maybe_null= MY_TEST(embedding->outer_join)))
4389 {
4390 tl->table->maybe_null= maybe_null;
4391 break;
4392 }
4393 }
4394 while ((embedding= embedding->embedding));
4395 if (tl->on_expr)
4396 {
4397 tl->on_expr->update_used_tables();
4398 tl->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
4399 }
4400 /*
4401 - There is no need to check sj_on_expr, because merged semi-joins inject
4402 sj_on_expr into the parent's WHERE clase.
4403 - For non-merged semi-joins (aka JTBMs), we need to check their
4404 left_expr. There is no need to check the rest of the subselect, we know
4405 it is uncorrelated and so cannot refer to any tables in this select.
4406 */
4407 if (tl->jtbm_subselect)
4408 {
4409 Item *left_expr= tl->jtbm_subselect->left_expr;
4410 left_expr->walk(&Item::update_table_bitmaps_processor, FALSE, NULL);
4411 }
4412
4413 embedding= tl->embedding;
4414 while (embedding)
4415 {
4416 if (embedding->on_expr &&
4417 embedding->nested_join->join_list.head() == tl)
4418 {
4419 embedding->on_expr->update_used_tables();
4420 embedding->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
4421 }
4422 tl= embedding;
4423 embedding= tl->embedding;
4424 }
4425 }
4426
4427 if (join->conds)
4428 {
4429 join->conds->update_used_tables();
4430 join->conds->walk(&Item::eval_not_null_tables, 0, NULL);
4431 }
4432 if (join->having)
4433 {
4434 join->having->update_used_tables();
4435 }
4436
4437 Item *item;
4438 List_iterator_fast<Item> it(join->fields_list);
4439 select_list_tables= 0;
4440 while ((item= it++))
4441 {
4442 item->update_used_tables();
4443 select_list_tables|= item->used_tables();
4444 }
4445 Item_outer_ref *ref;
4446 List_iterator_fast<Item_outer_ref> ref_it(inner_refs_list);
4447 while ((ref= ref_it++))
4448 {
4449 item= ref->outer_ref;
4450 item->update_used_tables();
4451 }
4452 for (ORDER *order= group_list.first; order; order= order->next)
4453 (*order->item)->update_used_tables();
4454 if (!master_unit()->is_unit_op() ||
4455 master_unit()->global_parameters() != this)
4456 {
4457 for (ORDER *order= order_list.first; order; order= order->next)
4458 (*order->item)->update_used_tables();
4459 }
4460 join->result->update_used_tables();
4461}
4462
4463
4464/**
4465 @brief
4466 Update is_correlated cache for this select
4467
4468 @details
4469*/
4470
4471void st_select_lex::update_correlated_cache()
4472{
4473 TABLE_LIST *tl;
4474 List_iterator<TABLE_LIST> ti(leaf_tables);
4475
4476 is_correlated= false;
4477
4478 while ((tl= ti++))
4479 {
4480 // is_correlated|= tl->is_with_table_recursive_reference();
4481 if (tl->on_expr)
4482 is_correlated|= MY_TEST(tl->on_expr->used_tables() & OUTER_REF_TABLE_BIT);
4483 for (TABLE_LIST *embedding= tl->embedding ; embedding ;
4484 embedding= embedding->embedding)
4485 {
4486 if (embedding->on_expr)
4487 is_correlated|= MY_TEST(embedding->on_expr->used_tables() &
4488 OUTER_REF_TABLE_BIT);
4489 }
4490 }
4491
4492 if (join->conds)
4493 is_correlated|= MY_TEST(join->conds->used_tables() & OUTER_REF_TABLE_BIT);
4494
4495 is_correlated|= join->having_is_correlated;
4496
4497 if (join->having)
4498 is_correlated|= MY_TEST(join->having->used_tables() & OUTER_REF_TABLE_BIT);
4499
4500 if (join->tmp_having)
4501 is_correlated|= MY_TEST(join->tmp_having->used_tables() &
4502 OUTER_REF_TABLE_BIT);
4503
4504 Item *item;
4505 List_iterator_fast<Item> it(join->fields_list);
4506 while ((item= it++))
4507 is_correlated|= MY_TEST(item->used_tables() & OUTER_REF_TABLE_BIT);
4508
4509 for (ORDER *order= group_list.first; order; order= order->next)
4510 is_correlated|= MY_TEST((*order->item)->used_tables() &
4511 OUTER_REF_TABLE_BIT);
4512
4513 if (!master_unit()->is_unit_op())
4514 {
4515 for (ORDER *order= order_list.first; order; order= order->next)
4516 is_correlated|= MY_TEST((*order->item)->used_tables() &
4517 OUTER_REF_TABLE_BIT);
4518 }
4519
4520 if (!is_correlated)
4521 uncacheable&= ~UNCACHEABLE_DEPENDENT;
4522}
4523
4524
4525/**
4526 Set the EXPLAIN type for this subquery.
4527
4528 @param on_the_fly TRUE<=> We're running a SHOW EXPLAIN command, so we must
4529 not change any variables
4530*/
4531
4532void st_select_lex::set_explain_type(bool on_the_fly)
4533{
4534 bool is_primary= FALSE;
4535 if (next_select())
4536 is_primary= TRUE;
4537
4538 if (!is_primary && first_inner_unit())
4539 {
4540 /*
4541 If there is at least one materialized derived|view then it's a PRIMARY select.
4542 Otherwise, all derived tables/views were merged and this select is a SIMPLE one.
4543 */
4544 for (SELECT_LEX_UNIT *un= first_inner_unit(); un; un= un->next_unit())
4545 {
4546 if ((!un->derived || un->derived->is_materialized_derived()))
4547 {
4548 is_primary= TRUE;
4549 break;
4550 }
4551 }
4552 }
4553
4554 if (on_the_fly && !is_primary && have_merged_subqueries)
4555 is_primary= TRUE;
4556
4557 SELECT_LEX *first= master_unit()->first_select();
4558 /* drop UNCACHEABLE_EXPLAIN, because it is for internal usage only */
4559 uint8 is_uncacheable= (uncacheable & ~UNCACHEABLE_EXPLAIN);
4560
4561 bool using_materialization= FALSE;
4562 Item_subselect *parent_item;
4563 if ((parent_item= master_unit()->item) &&
4564 parent_item->substype() == Item_subselect::IN_SUBS)
4565 {
4566 Item_in_subselect *in_subs= (Item_in_subselect*)parent_item;
4567 /*
4568 Surprisingly, in_subs->is_set_strategy() can return FALSE here,
4569 even for the last invocation of this function for the select.
4570 */
4571 if (in_subs->test_strategy(SUBS_MATERIALIZATION))
4572 using_materialization= TRUE;
4573 }
4574
4575 if (&master_unit()->thd->lex->select_lex == this)
4576 {
4577 type= is_primary ? "PRIMARY" : "SIMPLE";
4578 }
4579 else
4580 {
4581 if (this == first)
4582 {
4583 /* If we're a direct child of a UNION, we're the first sibling there */
4584 if (linkage == DERIVED_TABLE_TYPE)
4585 {
4586 if (is_uncacheable & UNCACHEABLE_DEPENDENT)
4587 type= "LATERAL DERIVED";
4588 else
4589 type= "DERIVED";
4590 }
4591 else if (using_materialization)
4592 type= "MATERIALIZED";
4593 else
4594 {
4595 if (is_uncacheable & UNCACHEABLE_DEPENDENT)
4596 type= "DEPENDENT SUBQUERY";
4597 else
4598 {
4599 type= is_uncacheable? "UNCACHEABLE SUBQUERY" :
4600 "SUBQUERY";
4601 }
4602 }
4603 }
4604 else
4605 {
4606 switch (linkage)
4607 {
4608 case INTERSECT_TYPE:
4609 type= "INTERSECT";
4610 break;
4611 case EXCEPT_TYPE:
4612 type= "EXCEPT";
4613 break;
4614 default:
4615 /* This a non-first sibling in UNION */
4616 if (is_uncacheable & UNCACHEABLE_DEPENDENT)
4617 type= "DEPENDENT UNION";
4618 else if (using_materialization)
4619 type= "MATERIALIZED UNION";
4620 else
4621 {
4622 type= is_uncacheable ? "UNCACHEABLE UNION": "UNION";
4623 if (this == master_unit()->fake_select_lex)
4624 type= unit_operation_text[master_unit()->common_op()];
4625 /*
4626 join below may be =NULL when this functions is called at an early
4627 stage. It will be later called again and we will set the correct
4628 value.
4629 */
4630 if (join)
4631 {
4632 bool uses_cte= false;
4633 for (JOIN_TAB *tab= first_linear_tab(join, WITHOUT_BUSH_ROOTS,
4634 WITH_CONST_TABLES);
4635 tab;
4636 tab= next_linear_tab(join, tab, WITHOUT_BUSH_ROOTS))
4637 {
4638 /*
4639 pos_in_table_list=NULL for e.g. post-join aggregation JOIN_TABs.
4640 */
4641 if (tab->table && tab->table->pos_in_table_list &&
4642 tab->table->pos_in_table_list->with &&
4643 tab->table->pos_in_table_list->with->is_recursive)
4644 {
4645 uses_cte= true;
4646 break;
4647 }
4648 }
4649 if (uses_cte)
4650 type= "RECURSIVE UNION";
4651 }
4652 }
4653 break;
4654 }
4655 }
4656 }
4657
4658 if (!on_the_fly)
4659 options|= SELECT_DESCRIBE;
4660}
4661
4662
4663/**
4664 @brief
4665 Increase estimated number of records for a derived table/view
4666
4667 @param records number of records to increase estimate by
4668
4669 @details
4670 This function increases estimated number of records by the 'records'
4671 for the derived table to which this select belongs to.
4672*/
4673
4674void SELECT_LEX::increase_derived_records(ha_rows records)
4675{
4676 SELECT_LEX_UNIT *unit= master_unit();
4677 DBUG_ASSERT(unit->derived);
4678
4679 if (unit->with_element && unit->with_element->is_recursive)
4680 {
4681 st_select_lex *first_recursive= unit->with_element->first_recursive;
4682 st_select_lex *sl= unit->first_select();
4683 for ( ; sl != first_recursive; sl= sl->next_select())
4684 {
4685 if (sl == this)
4686 break;
4687 }
4688 if (sl == first_recursive)
4689 return;
4690 }
4691
4692 select_unit *result= (select_unit*)unit->result;
4693 switch (linkage)
4694 {
4695 case INTERSECT_TYPE:
4696 // result of intersect can't be more then one of components
4697 set_if_smaller(result->records, records);
4698 case EXCEPT_TYPE:
4699 // in worse case none of record will be removed
4700 break;
4701 default:
4702 // usual UNION
4703 result->records+= records;
4704 break;
4705 }
4706}
4707
4708
4709/**
4710 @brief
4711 Mark select's derived table as a const one.
4712
4713 @param empty Whether select has an empty result set
4714
4715 @details
4716 Mark derived table/view of this select as a constant one (to
4717 materialize it at the optimization phase) unless this select belongs to a
4718 union. Estimated number of rows is incremented if this select has non empty
4719 result set.
4720*/
4721
4722void SELECT_LEX::mark_const_derived(bool empty)
4723{
4724 TABLE_LIST *derived= master_unit()->derived;
4725 /* join == NULL in DELETE ... RETURNING */
4726 if (!(join && join->thd->lex->describe) && derived)
4727 {
4728 if (!empty)
4729 increase_derived_records(1);
4730 if (!master_unit()->is_unit_op() && !derived->is_merged_derived() &&
4731 !(join && join->with_two_phase_optimization))
4732 derived->fill_me= TRUE;
4733 }
4734}
4735
4736
4737bool st_select_lex::save_leaf_tables(THD *thd)
4738{
4739 Query_arena *arena, backup;
4740 arena= thd->activate_stmt_arena_if_needed(&backup);
4741
4742 List_iterator_fast<TABLE_LIST> li(leaf_tables);
4743 TABLE_LIST *table;
4744 while ((table= li++))
4745 {
4746 if (leaf_tables_exec.push_back(table, thd->mem_root))
4747 return 1;
4748 table->tablenr_exec= table->get_tablenr();
4749 table->map_exec= table->get_map();
4750 if (join && (join->select_options & SELECT_DESCRIBE))
4751 table->maybe_null_exec= 0;
4752 else
4753 table->maybe_null_exec= table->table? table->table->maybe_null: 0;
4754 }
4755 if (arena)
4756 thd->restore_active_arena(arena, &backup);
4757
4758 return 0;
4759}
4760
4761
4762bool LEX::save_prep_leaf_tables()
4763{
4764 if (!thd->save_prep_leaf_list)
4765 return FALSE;
4766
4767 Query_arena *arena= thd->stmt_arena, backup;
4768 arena= thd->activate_stmt_arena_if_needed(&backup);
4769 //It is used for DETETE/UPDATE so top level has only one SELECT
4770 DBUG_ASSERT(select_lex.next_select() == NULL);
4771 bool res= select_lex.save_prep_leaf_tables(thd);
4772
4773 if (arena)
4774 thd->restore_active_arena(arena, &backup);
4775
4776 if (res)
4777 return TRUE;
4778
4779 thd->save_prep_leaf_list= FALSE;
4780 return FALSE;
4781}
4782
4783
4784bool st_select_lex::save_prep_leaf_tables(THD *thd)
4785{
4786 List_iterator_fast<TABLE_LIST> li(leaf_tables);
4787 TABLE_LIST *table;
4788
4789 /*
4790 Check that the SELECT_LEX was really prepared and so tables are setup.
4791
4792 It can be subquery in SET clause of UPDATE which was not prepared yet, so
4793 its tables are not yet setup and ready for storing.
4794 */
4795 if (prep_leaf_list_state != READY)
4796 return FALSE;
4797
4798 while ((table= li++))
4799 {
4800 if (leaf_tables_prep.push_back(table))
4801 return TRUE;
4802 }
4803 prep_leaf_list_state= SAVED;
4804 for (SELECT_LEX_UNIT *u= first_inner_unit(); u; u= u->next_unit())
4805 {
4806 for (SELECT_LEX *sl= u->first_select(); sl; sl= sl->next_select())
4807 {
4808 if (sl->save_prep_leaf_tables(thd))
4809 return TRUE;
4810 }
4811 }
4812
4813 return FALSE;
4814}
4815
4816
4817/*
4818 Return true if this select_lex has been converted into a semi-join nest
4819 within 'ancestor'.
4820
4821 We need a loop to check this because there could be several nested
4822 subselects, like
4823
4824 SELECT ... FROM grand_parent
4825 WHERE expr1 IN (SELECT ... FROM parent
4826 WHERE expr2 IN ( SELECT ... FROM child)
4827
4828 which were converted into:
4829
4830 SELECT ...
4831 FROM grand_parent SEMI_JOIN (parent JOIN child)
4832 WHERE
4833 expr1 AND expr2
4834
4835 In this case, both parent and child selects were merged into the parent.
4836*/
4837
4838bool st_select_lex::is_merged_child_of(st_select_lex *ancestor)
4839{
4840 bool all_merged= TRUE;
4841 for (SELECT_LEX *sl= this; sl && sl!=ancestor;
4842 sl=sl->outer_select())
4843 {
4844 Item *subs= sl->master_unit()->item;
4845 if (subs && subs->type() == Item::SUBSELECT_ITEM &&
4846 ((Item_subselect*)subs)->substype() == Item_subselect::IN_SUBS &&
4847 ((Item_in_subselect*)subs)->test_strategy(SUBS_SEMI_JOIN))
4848 {
4849 continue;
4850 }
4851
4852 if (sl->master_unit()->derived &&
4853 sl->master_unit()->derived->is_merged_derived())
4854 {
4855 continue;
4856 }
4857 all_merged= FALSE;
4858 break;
4859 }
4860 return all_merged;
4861}
4862
4863/*
4864 This is used by SHOW EXPLAIN. It assuses query plan has been already
4865 collected into QPF structures and we only need to print it out.
4866*/
4867
4868int LEX::print_explain(select_result_sink *output, uint8 explain_flags,
4869 bool is_analyze, bool *printed_anything)
4870{
4871 int res;
4872 if (explain && explain->have_query_plan())
4873 {
4874 res= explain->print_explain(output, explain_flags, is_analyze);
4875 *printed_anything= true;
4876 }
4877 else
4878 {
4879 res= 0;
4880 *printed_anything= false;
4881 }
4882 return res;
4883}
4884
4885
4886/**
4887 Allocates and set arena for SET STATEMENT old values.
4888
4889 @param backup where to save backup of arena.
4890
4891 @retval 1 Error
4892 @retval 0 OK
4893*/
4894
4895bool LEX::set_arena_for_set_stmt(Query_arena *backup)
4896{
4897 DBUG_ENTER("LEX::set_arena_for_set_stmt");
4898 DBUG_ASSERT(arena_for_set_stmt== 0);
4899 if (!mem_root_for_set_stmt)
4900 {
4901 mem_root_for_set_stmt= new MEM_ROOT();
4902 if (unlikely(!(mem_root_for_set_stmt)))
4903 DBUG_RETURN(1);
4904 init_sql_alloc(mem_root_for_set_stmt, "set_stmt",
4905 ALLOC_ROOT_SET, ALLOC_ROOT_SET, MYF(MY_THREAD_SPECIFIC));
4906 }
4907 if (unlikely(!(arena_for_set_stmt= new(mem_root_for_set_stmt)
4908 Query_arena_memroot(mem_root_for_set_stmt,
4909 Query_arena::STMT_INITIALIZED))))
4910 DBUG_RETURN(1);
4911 DBUG_PRINT("info", ("mem_root: %p arena: %p",
4912 mem_root_for_set_stmt,
4913 arena_for_set_stmt));
4914 thd->set_n_backup_active_arena(arena_for_set_stmt, backup);
4915 DBUG_RETURN(0);
4916}
4917
4918
4919void LEX::reset_arena_for_set_stmt(Query_arena *backup)
4920{
4921 DBUG_ENTER("LEX::reset_arena_for_set_stmt");
4922 DBUG_ASSERT(arena_for_set_stmt);
4923 thd->restore_active_arena(arena_for_set_stmt, backup);
4924 DBUG_PRINT("info", ("mem_root: %p arena: %p",
4925 arena_for_set_stmt->mem_root,
4926 arena_for_set_stmt));
4927 DBUG_VOID_RETURN;
4928}
4929
4930
4931void LEX::free_arena_for_set_stmt()
4932{
4933 DBUG_ENTER("LEX::free_arena_for_set_stmt");
4934 if (!arena_for_set_stmt)
4935 return;
4936 DBUG_PRINT("info", ("mem_root: %p arena: %p",
4937 arena_for_set_stmt->mem_root,
4938 arena_for_set_stmt));
4939 arena_for_set_stmt->free_items();
4940 delete(arena_for_set_stmt);
4941 free_root(mem_root_for_set_stmt, MYF(MY_KEEP_PREALLOC));
4942 arena_for_set_stmt= 0;
4943 DBUG_VOID_RETURN;
4944}
4945
4946void LEX::restore_set_statement_var()
4947{
4948 DBUG_ENTER("LEX::restore_set_statement_var");
4949 if (!old_var_list.is_empty())
4950 {
4951 DBUG_PRINT("info", ("vars: %d", old_var_list.elements));
4952 sql_set_variables(thd, &old_var_list, false);
4953 old_var_list.empty();
4954 free_arena_for_set_stmt();
4955 }
4956 DBUG_ASSERT(!is_arena_for_set_stmt());
4957 DBUG_VOID_RETURN;
4958}
4959
4960unit_common_op st_select_lex_unit::common_op()
4961{
4962 SELECT_LEX *first= first_select();
4963 bool first_op= TRUE;
4964 unit_common_op operation= OP_MIX; // if no op
4965 for (SELECT_LEX *sl= first; sl; sl= sl->next_select())
4966 {
4967 if (sl != first)
4968 {
4969 unit_common_op op;
4970 switch (sl->linkage)
4971 {
4972 case INTERSECT_TYPE:
4973 op= OP_INTERSECT;
4974 break;
4975 case EXCEPT_TYPE:
4976 op= OP_EXCEPT;
4977 break;
4978 default:
4979 op= OP_UNION;
4980 break;
4981 }
4982 if (first_op)
4983 {
4984 operation= op;
4985 first_op= FALSE;
4986 }
4987 else
4988 {
4989 if (operation != op)
4990 operation= OP_MIX;
4991 }
4992 }
4993 }
4994 return operation;
4995}
4996/*
4997 Save explain structures of a UNION. The only variable member is whether the
4998 union has "Using filesort".
4999
5000 There is also save_union_explain_part2() function, which is called before we read
5001 UNION's output.
5002
5003 The reason for it is examples like this:
5004
5005 SELECT col1 FROM t1 UNION SELECT col2 FROM t2 ORDER BY (select ... from t3 ...)
5006
5007 Here, the (select ... from t3 ...) subquery must be a child of UNION's
5008 st_select_lex. However, it is not connected as child until a very late
5009 stage in execution.
5010*/
5011
5012int st_select_lex_unit::save_union_explain(Explain_query *output)
5013{
5014 SELECT_LEX *first= first_select();
5015
5016 if (output->get_union(first->select_number))
5017 return 0; /* Already added */
5018
5019 Explain_union *eu=
5020 new (output->mem_root) Explain_union(output->mem_root,
5021 thd->lex->analyze_stmt);
5022 if (unlikely(!eu))
5023 return 0;
5024
5025 if (with_element && with_element->is_recursive)
5026 eu->is_recursive_cte= true;
5027
5028 if (derived)
5029 eu->connection_type= Explain_node::EXPLAIN_NODE_DERIVED;
5030 /*
5031 Note: Non-merged semi-joins cannot be made out of UNIONs currently, so we
5032 dont ever set EXPLAIN_NODE_NON_MERGED_SJ.
5033 */
5034 for (SELECT_LEX *sl= first; sl; sl= sl->next_select())
5035 eu->add_select(sl->select_number);
5036
5037 eu->fake_select_type= unit_operation_text[eu->operation= common_op()];
5038 eu->using_filesort= MY_TEST(global_parameters()->order_list.first);
5039 eu->using_tmp= union_needs_tmp_table();
5040
5041 // Save the UNION node
5042 output->add_node(eu);
5043
5044 if (eu->get_select_id() == 1)
5045 output->query_plan_ready();
5046
5047 return 0;
5048}
5049
5050
5051/*
5052 @see st_select_lex_unit::save_union_explain
5053*/
5054
5055int st_select_lex_unit::save_union_explain_part2(Explain_query *output)
5056{
5057 Explain_union *eu= output->get_union(first_select()->select_number);
5058 if (fake_select_lex)
5059 {
5060 for (SELECT_LEX_UNIT *unit= fake_select_lex->first_inner_unit();
5061 unit; unit= unit->next_unit())
5062 {
5063 if (!(unit->item && unit->item->eliminated))
5064 {
5065 eu->add_child(unit->first_select()->select_number);
5066 }
5067 }
5068 fake_select_lex->join->explain= &eu->fake_select_lex_explain;
5069 }
5070 return 0;
5071}
5072
5073
5074/**
5075 A routine used by the parser to decide whether we are specifying a full
5076 partitioning or if only partitions to add or to split.
5077
5078 @note This needs to be outside of WITH_PARTITION_STORAGE_ENGINE since it
5079 is used from the sql parser that doesn't have any ifdef's
5080
5081 @retval TRUE Yes, it is part of a management partition command
5082 @retval FALSE No, not a management partition command
5083*/
5084
5085bool LEX::is_partition_management() const
5086{
5087 return (sql_command == SQLCOM_ALTER_TABLE &&
5088 (alter_info.partition_flags == ALTER_PARTITION_ADD ||
5089 alter_info.partition_flags == ALTER_PARTITION_REORGANIZE));
5090}
5091
5092
5093/**
5094 Exclude last added SELECT_LEX (current) in the UNIT and return pointer in it
5095 (previous become currect)
5096
5097 @return detached SELECT_LEX or NULL in case of error
5098*/
5099
5100SELECT_LEX *LEX::exclude_last_select()
5101{
5102 DBUG_ENTER("SELECT_LEX::exclude_last_select");
5103 SELECT_LEX *exclude= current_select;
5104 SELECT_LEX_UNIT *unit= exclude->master_unit();
5105 SELECT_LEX *sl;
5106 DBUG_ASSERT(unit->first_select() != exclude);
5107 /* we should go through the list to correctly set current_select */
5108 for(sl= unit->first_select();
5109 sl->next_select() && sl->next_select() != exclude;
5110 sl= sl->next_select());
5111 DBUG_PRINT("info", ("excl: %p unit: %p prev: %p", exclude, unit, sl));
5112 if (!sl)
5113 DBUG_RETURN(NULL);
5114 DBUG_ASSERT(exclude->next_select() == NULL);
5115 exclude->exclude_from_tree();
5116 current_select= sl;
5117 DBUG_RETURN(exclude);
5118}
5119
5120
5121/**
5122 Put given (new) SELECT_LEX level below after currect (last) SELECT
5123
5124 LAST SELECT -> DUMMY SELECT
5125 |
5126 V
5127 NEW UNIT
5128 |
5129 V
5130 NEW SELECT
5131
5132 SELECT (*LAST*) ... FROM (SELECT (*NEW*) ... )
5133
5134 @param nselect Select to put one level below
5135
5136 @retval TRUE Error
5137 @retval FALSE OK
5138*/
5139
5140bool LEX::add_unit_in_brackets(SELECT_LEX *nselect)
5141{
5142 DBUG_ENTER("LEX::add_unit_in_brackets");
5143 bool distinct= nselect->master_unit()->union_distinct == nselect;
5144 bool rc= add_select_to_union_list(distinct, nselect->linkage, 0);
5145 if (rc)
5146 DBUG_RETURN(TRUE);
5147 SELECT_LEX* dummy_select= current_select;
5148 dummy_select->automatic_brackets= TRUE;
5149 dummy_select->linkage= nselect->linkage;
5150
5151 /* stuff dummy SELECT * FROM (...) */
5152 Name_resolution_context *context= &dummy_select->context;
5153 context->init();
5154
5155 /* add SELECT list*/
5156 Item *item= new (thd->mem_root)
5157 Item_field(thd, context, NULL, NULL, &star_clex_str);
5158 if (unlikely(item == NULL))
5159 DBUG_RETURN(TRUE);
5160 if (unlikely(add_item_to_list(thd, item)))
5161 DBUG_RETURN(TRUE);
5162 (dummy_select->with_wild)++;
5163
5164 rc= mysql_new_select(this, 1, nselect);
5165 nselect->linkage= DERIVED_TABLE_TYPE;
5166 DBUG_ASSERT(nselect->outer_select() == dummy_select);
5167
5168 current_select= dummy_select;
5169 current_select->nest_level--;
5170
5171 SELECT_LEX_UNIT *unit= nselect->master_unit();
5172 Table_ident *ti= new (thd->mem_root) Table_ident(unit);
5173 if (unlikely(ti == NULL))
5174 DBUG_RETURN(TRUE);
5175 char buff[10];
5176 LEX_CSTRING alias;
5177 alias.length= my_snprintf(buff, sizeof(buff),
5178 "__%u", dummy_select->select_number);
5179 alias.str= thd->strmake(buff, alias.length);
5180 if (unlikely(!alias.str))
5181 DBUG_RETURN(TRUE);
5182
5183 TABLE_LIST *table_list;
5184 if (unlikely(!(table_list=
5185 dummy_select->add_table_to_list(thd, ti, &alias,
5186 0, TL_READ,
5187 MDL_SHARED_READ))))
5188 DBUG_RETURN(TRUE);
5189 context->resolve_in_table_list_only(table_list);
5190 dummy_select->add_joined_table(table_list);
5191
5192 derived_tables|= DERIVED_SUBQUERY;
5193
5194 current_select= nselect;
5195 current_select->nest_level++;
5196 DBUG_RETURN(rc);
5197}
5198
5199
5200/**
5201 Checks if we need finish "automatic brackets" mode
5202
5203 INTERSECT has higher priority then UNION and EXCEPT, so when it is need we
5204 automatically create lower layer for INTERSECT (automatic brackets) and
5205 here we check if we should return back one level up during parsing procedure.
5206*/
5207
5208void LEX::check_automatic_up(enum sub_select_type type)
5209{
5210 if (type != INTERSECT_TYPE &&
5211 current_select->linkage == INTERSECT_TYPE &&
5212 current_select->outer_select() &&
5213 current_select->outer_select()->automatic_brackets)
5214 {
5215 nest_level--;
5216 current_select= current_select->outer_select();
5217 }
5218}
5219
5220
5221sp_variable *LEX::sp_param_init(LEX_CSTRING *name)
5222{
5223 if (spcont->find_variable(name, true))
5224 {
5225 my_error(ER_SP_DUP_PARAM, MYF(0), name->str);
5226 return NULL;
5227 }
5228 sp_variable *spvar= spcont->add_variable(thd, name);
5229 init_last_field(&spvar->field_def, name,
5230 thd->variables.collation_database);
5231 return spvar;
5232}
5233
5234
5235bool LEX::sp_param_fill_definition(sp_variable *spvar)
5236{
5237 return sphead->fill_spvar_definition(thd, last_field, &spvar->name);
5238}
5239
5240
5241void LEX::set_stmt_init()
5242{
5243 sql_command= SQLCOM_SET_OPTION;
5244 mysql_init_select(this);
5245 option_type= OPT_SESSION;
5246 autocommit= 0;
5247};
5248
5249
5250/**
5251 Find a local or a package body variable by name.
5252 @param IN name - the variable name
5253 @param OUT ctx - NULL, if the variable was not found,
5254 or LEX::spcont (if a local variable was found)
5255 or the package top level context
5256 (if a package variable was found)
5257 @param OUT handler - NULL, if the variable was not found,
5258 or a pointer to rcontext handler
5259 @retval - the variable (if found), or NULL otherwise.
5260*/
5261sp_variable *
5262LEX::find_variable(const LEX_CSTRING *name,
5263 sp_pcontext **ctx,
5264 const Sp_rcontext_handler **rh) const
5265{
5266 sp_variable *spv;
5267 if (spcont && (spv= spcont->find_variable(name, false)))
5268 {
5269 *ctx= spcont;
5270 *rh= &sp_rcontext_handler_local;
5271 return spv;
5272 }
5273 sp_package *pkg= sphead ? sphead->m_parent : NULL;
5274 if (pkg && (spv= pkg->find_package_variable(name)))
5275 {
5276 *ctx= pkg->get_parse_context()->child_context(0);
5277 *rh= &sp_rcontext_handler_package_body;
5278 return spv;
5279 }
5280 *ctx= NULL;
5281 *rh= NULL;
5282 return NULL;
5283}
5284
5285
5286static bool is_new(const char *str)
5287{
5288 return (str[0] == 'n' || str[0] == 'N') &&
5289 (str[1] == 'e' || str[1] == 'E') &&
5290 (str[2] == 'w' || str[2] == 'W');
5291}
5292
5293static bool is_old(const char *str)
5294{
5295 return (str[0] == 'o' || str[0] == 'O') &&
5296 (str[1] == 'l' || str[1] == 'L') &&
5297 (str[2] == 'd' || str[2] == 'D');
5298}
5299
5300
5301bool LEX::is_trigger_new_or_old_reference(const LEX_CSTRING *name) const
5302{
5303 // "name" is not necessarily NULL-terminated!
5304 return sphead && sphead->m_handler->type() == TYPE_ENUM_TRIGGER &&
5305 name->length == 3 && (is_new(name->str) || is_old(name->str));
5306}
5307
5308
5309void LEX::sp_variable_declarations_init(THD *thd, int nvars)
5310{
5311 sp_variable *spvar= spcont->get_last_context_variable();
5312
5313 sphead->reset_lex(thd);
5314 spcont->declare_var_boundary(nvars);
5315 thd->lex->init_last_field(&spvar->field_def, &spvar->name,
5316 thd->variables.collation_database);
5317}
5318
5319
5320bool LEX::sp_variable_declarations_set_default(THD *thd, int nvars,
5321 Item *dflt_value_item)
5322{
5323 if (!dflt_value_item &&
5324 unlikely(!(dflt_value_item= new (thd->mem_root) Item_null(thd))))
5325 return true;
5326
5327 for (uint i= 0 ; i < (uint) nvars ; i++)
5328 {
5329 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5330 bool last= i + 1 == (uint) nvars;
5331 spvar->default_value= dflt_value_item;
5332 /* The last instruction is responsible for freeing LEX. */
5333 sp_instr_set *is= new (this->thd->mem_root)
5334 sp_instr_set(sphead->instructions(),
5335 spcont, &sp_rcontext_handler_local,
5336 spvar->offset, dflt_value_item,
5337 this, last);
5338 if (unlikely(is == NULL || sphead->add_instr(is)))
5339 return true;
5340 }
5341 return false;
5342}
5343
5344
5345bool
5346LEX::sp_variable_declarations_copy_type_finalize(THD *thd, int nvars,
5347 const Column_definition &ref,
5348 Row_definition_list *fields,
5349 Item *default_value)
5350{
5351 for (uint i= 0 ; i < (uint) nvars; i++)
5352 {
5353 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5354 spvar->field_def.set_type(ref);
5355 if (fields)
5356 {
5357 DBUG_ASSERT(ref.type_handler() == &type_handler_row);
5358 spvar->field_def.set_row_field_definitions(fields);
5359 }
5360 spvar->field_def.field_name= spvar->name;
5361 }
5362 if (unlikely(sp_variable_declarations_set_default(thd, nvars,
5363 default_value)))
5364 return true;
5365 spcont->declare_var_boundary(0);
5366 return sphead->restore_lex(thd);
5367}
5368
5369
5370bool LEX::sp_variable_declarations_finalize(THD *thd, int nvars,
5371 const Column_definition *cdef,
5372 Item *dflt_value_item)
5373{
5374 DBUG_ASSERT(cdef);
5375 Column_definition tmp(*cdef);
5376 if (sphead->fill_spvar_definition(thd, &tmp))
5377 return true;
5378 return sp_variable_declarations_copy_type_finalize(thd, nvars, tmp, NULL,
5379 dflt_value_item);
5380}
5381
5382
5383bool LEX::sp_variable_declarations_row_finalize(THD *thd, int nvars,
5384 Row_definition_list *row,
5385 Item *dflt_value_item)
5386{
5387 DBUG_ASSERT(row);
5388 /*
5389 Prepare all row fields.
5390 Note, we do it only one time outside of the below loop.
5391 The converted list in "row" is further reused by all variable
5392 declarations processed by the current call.
5393 Example:
5394 DECLARE
5395 a, b, c ROW(x VARCHAR(10) CHARACTER SET utf8);
5396 BEGIN
5397 ...
5398 END;
5399 */
5400 if (sphead->row_fill_field_definitions(thd, row))
5401 return true;
5402
5403 for (uint i= 0 ; i < (uint) nvars ; i++)
5404 {
5405 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5406 spvar->field_def.set_row_field_definitions(row);
5407 if (sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name))
5408 return true;
5409 }
5410
5411 if (sp_variable_declarations_set_default(thd, nvars, dflt_value_item))
5412 return true;
5413 spcont->declare_var_boundary(0);
5414 return sphead->restore_lex(thd);
5415}
5416
5417
5418/**
5419 Finalize a %ROWTYPE declaration, e.g.:
5420 DECLARE a,b,c,d t1%ROWTYPE := ROW(1,2,3);
5421
5422 @param thd - the current thd
5423 @param nvars - the number of variables in the declaration
5424 @param ref - the table or cursor name (see comments below)
5425 @param def - the default value, e.g., ROW(1,2,3), or NULL (no default).
5426*/
5427bool
5428LEX::sp_variable_declarations_rowtype_finalize(THD *thd, int nvars,
5429 Qualified_column_ident *ref,
5430 Item *def)
5431{
5432 uint coffp;
5433 const sp_pcursor *pcursor= ref->table.str && ref->db.str ? NULL :
5434 spcont->find_cursor(&ref->m_column, &coffp,
5435 false);
5436 if (pcursor)
5437 return sp_variable_declarations_cursor_rowtype_finalize(thd, nvars,
5438 coffp, def);
5439 /*
5440 When parsing a qualified identifier chain, the parser does not know yet
5441 if it's going to be a qualified column name (for %TYPE),
5442 or a qualified table name (for %ROWTYPE). So it collects the chain
5443 into Qualified_column_ident.
5444 Now we know that it was actually a qualified table name (%ROWTYPE).
5445 Create a new Table_ident from Qualified_column_ident,
5446 shifting fields as follows:
5447 - ref->m_column becomes table_ref->table
5448 - ref->table becomes table_ref->db
5449 */
5450 return sp_variable_declarations_table_rowtype_finalize(thd, nvars,
5451 ref->table,
5452 ref->m_column,
5453 def);
5454}
5455
5456
5457bool
5458LEX::sp_variable_declarations_table_rowtype_finalize(THD *thd, int nvars,
5459 const LEX_CSTRING &db,
5460 const LEX_CSTRING &table,
5461 Item *def)
5462{
5463 Table_ident *table_ref;
5464 if (unlikely(!(table_ref=
5465 new (thd->mem_root) Table_ident(thd, &db, &table, false))))
5466 return true;
5467 // Loop through all variables in the same declaration
5468 for (uint i= 0 ; i < (uint) nvars; i++)
5469 {
5470 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5471 spvar->field_def.set_table_rowtype_ref(table_ref);
5472 sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
5473 }
5474 if (sp_variable_declarations_set_default(thd, nvars, def))
5475 return true;
5476 // Make sure sp_rcontext is created using the invoker security context:
5477 sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
5478 spcont->declare_var_boundary(0);
5479 return sphead->restore_lex(thd);
5480}
5481
5482
5483bool
5484LEX::sp_variable_declarations_cursor_rowtype_finalize(THD *thd, int nvars,
5485 uint offset,
5486 Item *def)
5487{
5488 const sp_pcursor *pcursor= spcont->find_cursor(offset);
5489
5490 // Loop through all variables in the same declaration
5491 for (uint i= 0 ; i < (uint) nvars; i++)
5492 {
5493 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5494
5495 spvar->field_def.set_cursor_rowtype_ref(offset);
5496 sp_instr_cursor_copy_struct *instr=
5497 new (thd->mem_root) sp_instr_cursor_copy_struct(sphead->instructions(),
5498 spcont, pcursor->lex(),
5499 spvar->offset);
5500 if (instr == NULL || sphead->add_instr(instr))
5501 return true;
5502
5503 sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
5504 }
5505 if (unlikely(sp_variable_declarations_set_default(thd, nvars, def)))
5506 return true;
5507 // Make sure sp_rcontext is created using the invoker security context:
5508 sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
5509 spcont->declare_var_boundary(0);
5510 return sphead->restore_lex(thd);
5511}
5512
5513
5514/*
5515 Add declarations for table column and SP variable anchor types:
5516 - DECLARE spvar1 TYPE OF db1.table1.column1;
5517 - DECLARE spvar1 TYPE OF table1.column1;
5518 - DECLARE spvar1 TYPE OF spvar0;
5519*/
5520bool
5521LEX::sp_variable_declarations_with_ref_finalize(THD *thd, int nvars,
5522 Qualified_column_ident *ref,
5523 Item *def)
5524{
5525 return ref->db.length == 0 && ref->table.length == 0 ?
5526 sp_variable_declarations_vartype_finalize(thd, nvars, ref->m_column, def) :
5527 sp_variable_declarations_column_type_finalize(thd, nvars, ref, def);
5528}
5529
5530
5531bool
5532LEX::sp_variable_declarations_column_type_finalize(THD *thd, int nvars,
5533 Qualified_column_ident *ref,
5534 Item *def)
5535{
5536 for (uint i= 0 ; i < (uint) nvars; i++)
5537 {
5538 sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5539 spvar->field_def.set_column_type_ref(ref);
5540 spvar->field_def.field_name= spvar->name;
5541 }
5542 sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
5543 if (sp_variable_declarations_set_default(thd, nvars, def))
5544 return true;
5545 spcont->declare_var_boundary(0);
5546 return sphead->restore_lex(thd);
5547}
5548
5549
5550bool
5551LEX::sp_variable_declarations_vartype_finalize(THD *thd, int nvars,
5552 const LEX_CSTRING &ref,
5553 Item *default_value)
5554{
5555 sp_variable *t;
5556 if (!spcont || !(t= spcont->find_variable(&ref, false)))
5557 {
5558 my_error(ER_SP_UNDECLARED_VAR, MYF(0), ref.str);
5559 return true;
5560 }
5561
5562 if (t->field_def.is_cursor_rowtype_ref())
5563 {
5564 uint offset= t->field_def.cursor_rowtype_offset();
5565 return sp_variable_declarations_cursor_rowtype_finalize(thd, nvars,
5566 offset,
5567 default_value);
5568 }
5569
5570 if (t->field_def.is_column_type_ref())
5571 {
5572 Qualified_column_ident *tmp= t->field_def.column_type_ref();
5573 return sp_variable_declarations_column_type_finalize(thd, nvars, tmp,
5574 default_value);
5575 }
5576
5577 if (t->field_def.is_table_rowtype_ref())
5578 {
5579 const Table_ident *tmp= t->field_def.table_rowtype_ref();
5580 return sp_variable_declarations_table_rowtype_finalize(thd, nvars,
5581 tmp->db,
5582 tmp->table,
5583 default_value);
5584 }
5585
5586 // A reference to a scalar or a row variable with an explicit data type
5587 return sp_variable_declarations_copy_type_finalize(thd, nvars,
5588 t->field_def,
5589 t->field_def.
5590 row_field_definitions(),
5591 default_value);
5592}
5593
5594
5595/**********************************************************************
5596 The FOR LOOP statement
5597
5598 This syntax:
5599 FOR i IN lower_bound .. upper_bound
5600 LOOP
5601 statements;
5602 END LOOP;
5603
5604 is translated into:
5605
5606 DECLARE
5607 i INT := lower_bound;
5608 j INT := upper_bound;
5609 BEGIN
5610 WHILE i <= j
5611 LOOP
5612 statements;
5613 i:= i + 1;
5614 END LOOP;
5615 END;
5616*/
5617
5618
5619sp_variable *LEX::sp_add_for_loop_variable(THD *thd, const LEX_CSTRING *name,
5620 Item *value)
5621{
5622 sp_variable *spvar= spcont->add_variable(thd, name);
5623 spcont->declare_var_boundary(1);
5624 spvar->field_def.field_name= spvar->name;
5625 spvar->field_def.set_handler(&type_handler_longlong);
5626 type_handler_longlong.Column_definition_prepare_stage2(&spvar->field_def,
5627 NULL, HA_CAN_GEOMETRY);
5628 if (!value && unlikely(!(value= new (thd->mem_root) Item_null(thd))))
5629 return NULL;
5630
5631 spvar->default_value= value;
5632 sp_instr_set *is= new (this->thd->mem_root)
5633 sp_instr_set(sphead->instructions(),
5634 spcont, &sp_rcontext_handler_local,
5635 spvar->offset, value,
5636 this, true);
5637 if (unlikely(is == NULL || sphead->add_instr(is)))
5638 return NULL;
5639 spcont->declare_var_boundary(0);
5640 return spvar;
5641}
5642
5643
5644bool LEX::sp_for_loop_implicit_cursor_statement(THD *thd,
5645 Lex_for_loop_bounds_st *bounds,
5646 sp_lex_cursor *cur)
5647{
5648 Item *item;
5649 DBUG_ASSERT(sphead);
5650 LEX_CSTRING name= {STRING_WITH_LEN("[implicit_cursor]") };
5651 if (sp_declare_cursor(thd, &name, cur, NULL, true))
5652 return true;
5653 DBUG_ASSERT(thd->lex == this);
5654 if (unlikely(!(bounds->m_index=
5655 new (thd->mem_root) sp_assignment_lex(thd, this))))
5656 return true;
5657 bounds->m_index->sp_lex_in_use= true;
5658 sphead->reset_lex(thd, bounds->m_index);
5659 DBUG_ASSERT(thd->lex != this);
5660 if (unlikely(!(item=
5661 new (thd->mem_root) Item_field(thd,
5662 thd->lex->current_context(),
5663 NullS, NullS, &name))))
5664 return true;
5665 bounds->m_index->set_item_and_free_list(item, NULL);
5666 if (thd->lex->sphead->restore_lex(thd))
5667 return true;
5668 DBUG_ASSERT(thd->lex == this);
5669 bounds->m_direction= 1;
5670 bounds->m_upper_bound= NULL;
5671 bounds->m_implicit_cursor= true;
5672 return false;
5673}
5674
5675sp_variable *
5676LEX::sp_add_for_loop_cursor_variable(THD *thd,
5677 const LEX_CSTRING *name,
5678 const sp_pcursor *pcursor,
5679 uint coffset,
5680 sp_assignment_lex *param_lex,
5681 Item_args *parameters)
5682{
5683 sp_variable *spvar= spcont->add_variable(thd, name);
5684 if (!spvar)
5685 return NULL;
5686 spcont->declare_var_boundary(1);
5687 sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
5688 if (unlikely(!(spvar->default_value= new (thd->mem_root) Item_null(thd))))
5689 return NULL;
5690
5691 spvar->field_def.set_cursor_rowtype_ref(coffset);
5692
5693 if (unlikely(sphead->add_for_loop_open_cursor(thd, spcont, spvar, pcursor,
5694 coffset,
5695 param_lex, parameters)))
5696 return NULL;
5697
5698 spcont->declare_var_boundary(0);
5699 return spvar;
5700}
5701
5702
5703/**
5704 Generate a code for a FOR loop condition:
5705 - Make Item_splocal for the FOR loop index variable
5706 - Make Item_splocal for the FOR loop upper bound variable
5707 - Make a comparison function item on top of these two variables
5708*/
5709bool LEX::sp_for_loop_condition(THD *thd, const Lex_for_loop_st &loop)
5710{
5711 Item_splocal *args[2];
5712 for (uint i= 0 ; i < 2; i++)
5713 {
5714 sp_variable *src= i == 0 ? loop.m_index : loop.m_upper_bound;
5715 args[i]= new (thd->mem_root)
5716 Item_splocal(thd, &sp_rcontext_handler_local,
5717 &src->name, src->offset, src->type_handler());
5718 if (unlikely(args[i] == NULL))
5719 return true;
5720#ifdef DBUG_ASSERT_EXISTS
5721 args[i]->m_sp= sphead;
5722#endif
5723 }
5724
5725 Item *expr= loop.m_direction > 0 ?
5726 (Item *) new (thd->mem_root) Item_func_le(thd, args[0], args[1]) :
5727 (Item *) new (thd->mem_root) Item_func_ge(thd, args[0], args[1]);
5728 return unlikely(!expr) || unlikely(sp_while_loop_expression(thd, expr));
5729}
5730
5731
5732/**
5733 Generate the FOR LOOP condition code in its own lex
5734*/
5735bool LEX::sp_for_loop_intrange_condition_test(THD *thd,
5736 const Lex_for_loop_st &loop)
5737{
5738 spcont->set_for_loop(loop);
5739 sphead->reset_lex(thd);
5740 if (unlikely(thd->lex->sp_for_loop_condition(thd, loop)))
5741 return true;
5742 return thd->lex->sphead->restore_lex(thd);
5743}
5744
5745
5746bool LEX::sp_for_loop_cursor_condition_test(THD *thd,
5747 const Lex_for_loop_st &loop)
5748{
5749 const LEX_CSTRING *cursor_name;
5750 Item *expr;
5751 spcont->set_for_loop(loop);
5752 sphead->reset_lex(thd);
5753 cursor_name= spcont->find_cursor(loop.m_cursor_offset);
5754 DBUG_ASSERT(cursor_name);
5755 if (unlikely(!(expr=
5756 new (thd->mem_root)
5757 Item_func_cursor_found(thd, cursor_name,
5758 loop.m_cursor_offset))))
5759 return true;
5760 if (thd->lex->sp_while_loop_expression(thd, expr))
5761 return true;
5762 return thd->lex->sphead->restore_lex(thd);
5763}
5764
5765
5766bool LEX::sp_for_loop_intrange_declarations(THD *thd, Lex_for_loop_st *loop,
5767 const LEX_CSTRING *index,
5768 const Lex_for_loop_bounds_st &bounds)
5769{
5770 if (unlikely(!(loop->m_index=
5771 bounds.m_index->
5772 sp_add_for_loop_variable(thd, index,
5773 bounds.m_index->get_item()))))
5774 return true;
5775 if (unlikely(!(loop->m_upper_bound=
5776 bounds.m_upper_bound->
5777 sp_add_for_loop_upper_bound(thd,
5778 bounds.
5779 m_upper_bound->get_item()))))
5780 return true;
5781 loop->m_direction= bounds.m_direction;
5782 loop->m_implicit_cursor= 0;
5783 return false;
5784}
5785
5786
5787bool LEX::sp_for_loop_cursor_declarations(THD *thd,
5788 Lex_for_loop_st *loop,
5789 const LEX_CSTRING *index,
5790 const Lex_for_loop_bounds_st &bounds)
5791{
5792 Item *item= bounds.m_index->get_item();
5793 Item_splocal *item_splocal;
5794 Item_field *item_field;
5795 Item_func_sp *item_func_sp= NULL;
5796 LEX_CSTRING name;
5797 uint coffs, param_count= 0;
5798 const sp_pcursor *pcursor;
5799
5800 if ((item_splocal= item->get_item_splocal()))
5801 name= item_splocal->m_name;
5802 else if ((item_field= item->type() == Item::FIELD_ITEM ?
5803 static_cast<Item_field *>(item) : NULL) &&
5804 item_field->table_name == NULL)
5805 name= item_field->field_name;
5806 else if (item->type() == Item::FUNC_ITEM &&
5807 static_cast<Item_func*>(item)->functype() == Item_func::FUNC_SP &&
5808 !static_cast<Item_func_sp*>(item)->get_sp_name()->m_explicit_name)
5809 {
5810 /*
5811 When a FOR LOOP for a cursor with parameters is parsed:
5812 FOR index IN cursor(1,2,3) LOOP
5813 statements;
5814 END LOOP;
5815 the parser scans "cursor(1,2,3)" using the "expr" rule,
5816 so it thinks that cursor(1,2,3) is a stored function call.
5817 It's not easy to implement this without using "expr" because
5818 of grammar conflicts.
5819 As a side effect, the Item_func_sp and its arguments in the parentheses
5820 belong to the same LEX. This is different from an explicit
5821 "OPEN cursor(1,2,3)" where every expression belongs to a separate LEX.
5822 */
5823 item_func_sp= static_cast<Item_func_sp*>(item);
5824 name= item_func_sp->get_sp_name()->m_name;
5825 param_count= item_func_sp->argument_count();
5826 }
5827 else
5828 {
5829 thd->parse_error();
5830 return true;
5831 }
5832 if (unlikely(!(pcursor= spcont->find_cursor_with_error(&name, &coffs,
5833 false)) ||
5834 pcursor->check_param_count_with_error(param_count)))
5835 return true;
5836
5837 if (!(loop->m_index= sp_add_for_loop_cursor_variable(thd, index,
5838 pcursor, coffs,
5839 bounds.m_index,
5840 item_func_sp)))
5841 return true;
5842 loop->m_upper_bound= NULL;
5843 loop->m_direction= bounds.m_direction;
5844 loop->m_cursor_offset= coffs;
5845 loop->m_implicit_cursor= bounds.m_implicit_cursor;
5846 return false;
5847}
5848
5849
5850/**
5851 Generate a code for a FOR loop index increment
5852*/
5853bool LEX::sp_for_loop_increment(THD *thd, const Lex_for_loop_st &loop)
5854{
5855 Item_splocal *splocal= new (thd->mem_root)
5856 Item_splocal(thd, &sp_rcontext_handler_local,
5857 &loop.m_index->name, loop.m_index->offset,
5858 loop.m_index->type_handler());
5859 if (unlikely(splocal == NULL))
5860 return true;
5861#ifdef DBUG_ASSERT_EXISTS
5862 splocal->m_sp= sphead;
5863#endif
5864 Item_int *inc= new (thd->mem_root) Item_int(thd, loop.m_direction);
5865 if (unlikely(!inc))
5866 return true;
5867 Item *expr= new (thd->mem_root) Item_func_plus(thd, splocal, inc);
5868 if (unlikely(!expr) ||
5869 unlikely(sphead->set_local_variable(thd, spcont,
5870 &sp_rcontext_handler_local,
5871 loop.m_index, expr, this, true)))
5872 return true;
5873 return false;
5874}
5875
5876
5877bool LEX::sp_for_loop_intrange_finalize(THD *thd, const Lex_for_loop_st &loop)
5878{
5879 sphead->reset_lex(thd);
5880
5881 // Generate FOR LOOP index increment in its own lex
5882 DBUG_ASSERT(this != thd->lex);
5883 if (unlikely(thd->lex->sp_for_loop_increment(thd, loop) ||
5884 thd->lex->sphead->restore_lex(thd)))
5885 return true;
5886
5887 // Generate a jump to the beginning of the loop
5888 DBUG_ASSERT(this == thd->lex);
5889 return sp_while_loop_finalize(thd);
5890}
5891
5892
5893bool LEX::sp_for_loop_cursor_finalize(THD *thd, const Lex_for_loop_st &loop)
5894{
5895 sp_instr_cfetch *instr=
5896 new (thd->mem_root) sp_instr_cfetch(sphead->instructions(),
5897 spcont, loop.m_cursor_offset, false);
5898 if (unlikely(instr == NULL) || unlikely(sphead->add_instr(instr)))
5899 return true;
5900 instr->add_to_varlist(loop.m_index);
5901 // Generate a jump to the beginning of the loop
5902 return sp_while_loop_finalize(thd);
5903}
5904
5905/***************************************************************************/
5906
5907bool LEX::sp_declare_cursor(THD *thd, const LEX_CSTRING *name,
5908 sp_lex_cursor *cursor_stmt,
5909 sp_pcontext *param_ctx, bool add_cpush_instr)
5910{
5911 uint offp;
5912 sp_instr_cpush *i;
5913
5914 if (spcont->find_cursor(name, &offp, true))
5915 {
5916 my_error(ER_SP_DUP_CURS, MYF(0), name->str);
5917 return true;
5918 }
5919 cursor_stmt->set_cursor_name(name);
5920
5921 if (unlikely(spcont->add_cursor(name, param_ctx, cursor_stmt)))
5922 return true;
5923
5924 if (add_cpush_instr)
5925 {
5926 i= new (thd->mem_root)
5927 sp_instr_cpush(sphead->instructions(), spcont, cursor_stmt,
5928 spcont->current_cursor_count() - 1);
5929 return unlikely(i == NULL) || unlikely(sphead->add_instr(i));
5930 }
5931 return false;
5932}
5933
5934
5935/**
5936 Generate an SP code for an "OPEN cursor_name" statement.
5937 @param thd
5938 @param name - Name of the cursor
5939 @param parameters - Cursor parameters, e.g. OPEN c(1,2,3)
5940 @returns - false on success, true on error
5941*/
5942bool LEX::sp_open_cursor(THD *thd, const LEX_CSTRING *name,
5943 List<sp_assignment_lex> *parameters)
5944{
5945 uint offset;
5946 const sp_pcursor *pcursor;
5947 uint param_count= parameters ? parameters->elements : 0;
5948 return !(pcursor= spcont->find_cursor_with_error(name, &offset, false)) ||
5949 pcursor->check_param_count_with_error(param_count) ||
5950 sphead->add_open_cursor(thd, spcont, offset,
5951 pcursor->param_context(), parameters);
5952}
5953
5954
5955bool LEX::sp_handler_declaration_init(THD *thd, int type)
5956{
5957 sp_handler *h= spcont->add_handler(thd, (sp_handler::enum_type) type);
5958
5959 spcont= spcont->push_context(thd, sp_pcontext::HANDLER_SCOPE);
5960
5961 sp_instr_hpush_jump *i=
5962 new (thd->mem_root) sp_instr_hpush_jump(sphead->instructions(), spcont, h);
5963
5964 if (unlikely(i == NULL) || unlikely(sphead->add_instr(i)))
5965 return true;
5966
5967 /* For continue handlers, mark end of handler scope. */
5968 if (type == sp_handler::CONTINUE &&
5969 unlikely(sphead->push_backpatch(thd, i, spcont->last_label())))
5970 return true;
5971
5972 if (unlikely(sphead->push_backpatch(thd, i,
5973 spcont->push_label(thd, &empty_clex_str,
5974 0))))
5975 return true;
5976
5977 return false;
5978}
5979
5980
5981bool LEX::sp_handler_declaration_finalize(THD *thd, int type)
5982{
5983 sp_label *hlab= spcont->pop_label(); /* After this hdlr */
5984 sp_instr_hreturn *i;
5985
5986 if (type == sp_handler::CONTINUE)
5987 {
5988 i= new (thd->mem_root) sp_instr_hreturn(sphead->instructions(), spcont);
5989 if (unlikely(i == NULL) ||
5990 unlikely(sphead->add_instr(i)))
5991 return true;
5992 }
5993 else
5994 { /* EXIT or UNDO handler, just jump to the end of the block */
5995 i= new (thd->mem_root) sp_instr_hreturn(sphead->instructions(), spcont);
5996 if (unlikely(i == NULL) ||
5997 unlikely(sphead->add_instr(i)) ||
5998 unlikely(sphead->push_backpatch(thd, i, spcont->last_label()))) /* Block end */
5999 return true;
6000 }
6001 sphead->backpatch(hlab);
6002 spcont= spcont->pop_context();
6003 return false;
6004}
6005
6006
6007void LEX::sp_block_init(THD *thd, const LEX_CSTRING *label)
6008{
6009 spcont->push_label(thd, label, sphead->instructions(), sp_label::BEGIN);
6010 spcont= spcont->push_context(thd, sp_pcontext::REGULAR_SCOPE);
6011}
6012
6013
6014bool LEX::sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
6015 class sp_label **splabel)
6016{
6017 sp_head *sp= sphead;
6018 sp_pcontext *ctx= spcont;
6019 sp_instr *i;
6020
6021 sp->backpatch(ctx->last_label()); /* We always have a label */
6022 if (spblock.hndlrs)
6023 {
6024 i= new (thd->mem_root)
6025 sp_instr_hpop(sp->instructions(), ctx, spblock.hndlrs);
6026 if (unlikely(i == NULL) ||
6027 unlikely(sp->add_instr(i)))
6028 return true;
6029 }
6030 if (spblock.curs)
6031 {
6032 i= new (thd->mem_root)
6033 sp_instr_cpop(sp->instructions(), ctx, spblock.curs);
6034 if (unlikely(i == NULL) ||
6035 unlikely(sp->add_instr(i)))
6036 return true;
6037 }
6038 spcont= ctx->pop_context();
6039 *splabel= spcont->pop_label();
6040 return false;
6041}
6042
6043
6044bool LEX::sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
6045 const LEX_CSTRING *end_label)
6046{
6047 sp_label *splabel;
6048 if (unlikely(sp_block_finalize(thd, spblock, &splabel)))
6049 return true;
6050 if (unlikely(end_label->str &&
6051 lex_string_cmp(system_charset_info,
6052 end_label, &splabel->name) != 0))
6053 {
6054 my_error(ER_SP_LABEL_MISMATCH, MYF(0), end_label->str);
6055 return true;
6056 }
6057 return false;
6058}
6059
6060
6061sp_name *LEX::make_sp_name(THD *thd, const LEX_CSTRING *name)
6062{
6063 sp_name *res;
6064 LEX_CSTRING db;
6065 if (unlikely(check_routine_name(name)) ||
6066 unlikely(copy_db_to(&db)) ||
6067 unlikely((!(res= new (thd->mem_root) sp_name(&db, name, false)))))
6068 return NULL;
6069 return res;
6070}
6071
6072
6073/**
6074 When a package routine name is stored in memory in Database_qualified_name,
6075 the dot character is used to delimit package name from the routine name,
6076 e.g.:
6077 m_db= 'test'; -- database 'test'
6078 m_name= 'p1.p1'; -- package 'p1', routine 'p1'
6079 See database_qualified_name::make_package_routine_name() for details.
6080 Disallow package routine names with dots,
6081 to avoid ambiguity when interpreting m_name='p1.p1.p1', between:
6082 a. package 'p1.p1' + routine 'p1'
6083 b. package 'p1' + routine 'p1.p1'
6084 m_name='p1.p1.p1' will always mean (a).
6085*/
6086sp_name *LEX::make_sp_name_package_routine(THD *thd, const LEX_CSTRING *name)
6087{
6088 sp_name *res= make_sp_name(thd, name);
6089 if (likely(res) && unlikely(strchr(res->m_name.str, '.')))
6090 {
6091 my_error(ER_SP_WRONG_NAME, MYF(0), res->m_name.str);
6092 res= NULL;
6093 }
6094 return res;
6095}
6096
6097
6098sp_name *LEX::make_sp_name(THD *thd, const LEX_CSTRING *name1,
6099 const LEX_CSTRING *name2)
6100{
6101 sp_name *res;
6102 LEX_CSTRING norm_name1;
6103 if (unlikely(!name1->str) ||
6104 unlikely(!thd->make_lex_string(&norm_name1, name1->str,
6105 name1->length)) ||
6106 unlikely(check_db_name((LEX_STRING *) &norm_name1)))
6107 {
6108 my_error(ER_WRONG_DB_NAME, MYF(0), name1->str);
6109 return NULL;
6110 }
6111 if (unlikely(check_routine_name(name2)) ||
6112 unlikely(!(res= new (thd->mem_root) sp_name(&norm_name1, name2, true))))
6113 return NULL;
6114 return res;
6115}
6116
6117
6118sp_head *LEX::make_sp_head(THD *thd, const sp_name *name,
6119 const Sp_handler *sph)
6120{
6121 sp_package *package= get_sp_package();
6122 sp_head *sp;
6123
6124 /* Order is important here: new - reset - init */
6125 if (likely((sp= new sp_head(package, sph))))
6126 {
6127 sp->reset_thd_mem_root(thd);
6128 sp->init(this);
6129 if (name)
6130 {
6131 if (package)
6132 sp->make_package_routine_name(sp->get_main_mem_root(),
6133 package->m_db,
6134 package->m_name,
6135 name->m_name);
6136 else
6137 sp->init_sp_name(name);
6138 sp->make_qname(sp->get_main_mem_root(), &sp->m_qname);
6139 }
6140 sphead= sp;
6141 }
6142 sp_chistics.init();
6143 return sp;
6144}
6145
6146
6147sp_head *LEX::make_sp_head_no_recursive(THD *thd, const sp_name *name,
6148 const Sp_handler *sph)
6149{
6150 sp_package *package= thd->lex->get_sp_package();
6151 /*
6152 Sp_handler::sp_clone_and_link_routine() generates a standalone-alike
6153 statement to clone package routines for recursion, e.g.:
6154 CREATE PROCEDURE p1 AS BEGIN NULL; END;
6155 Translate a standalone routine handler to the corresponding
6156 package routine handler if we're cloning a package routine, e.g.:
6157 sp_handler_procedure -> sp_handler_package_procedure
6158 sp_handler_function -> sp_handler_package_function
6159 */
6160 if (package && package->m_is_cloning_routine)
6161 sph= sph->package_routine_handler();
6162 if (!sphead ||
6163 (package &&
6164 (sph == &sp_handler_package_procedure ||
6165 sph == &sp_handler_package_function)))
6166 return make_sp_head(thd, name, sph);
6167 my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), sph->type_str());
6168 return NULL;
6169}
6170
6171
6172bool LEX::sp_body_finalize_procedure(THD *thd)
6173{
6174 if (sphead->check_unresolved_goto())
6175 return true;
6176 sphead->set_stmt_end(thd);
6177 sphead->restore_thd_mem_root(thd);
6178 return false;
6179}
6180
6181
6182bool LEX::sp_body_finalize_function(THD *thd)
6183{
6184 if (sphead->is_not_allowed_in_function("function"))
6185 return true;
6186 if (!(sphead->m_flags & sp_head::HAS_RETURN))
6187 {
6188 my_error(ER_SP_NORETURN, MYF(0), ErrConvDQName(sphead).ptr());
6189 return true;
6190 }
6191 if (sp_body_finalize_procedure(thd))
6192 return true;
6193 (void) is_native_function_with_warn(thd, &sphead->m_name);
6194 return false;
6195}
6196
6197
6198bool LEX::sp_block_with_exceptions_finalize_declarations(THD *thd)
6199{
6200 /*
6201 [ DECLARE declarations ]
6202 BEGIN executable_section
6203 [ EXCEPTION exceptions ]
6204 END
6205
6206 We are now at the "BEGIN" keyword.
6207 We have collected all declarations, including DECLARE HANDLER directives.
6208 But there will be possibly more handlers in the EXCEPTION section.
6209
6210 Generate a forward jump from the end of the DECLARE section to the
6211 beginning of the EXCEPTION section, over the executable section.
6212 */
6213 return sphead->add_instr_jump(thd, spcont);
6214}
6215
6216
6217bool
6218LEX::sp_block_with_exceptions_finalize_executable_section(THD *thd,
6219 uint executable_section_ip)
6220{
6221 /*
6222 We're now at the end of "executable_section" of the block,
6223 near the "EXCEPTION" or the "END" keyword.
6224 Generate a jump to the END of the block over the EXCEPTION section.
6225 */
6226 if (sphead->add_instr_jump_forward_with_backpatch(thd, spcont))
6227 return true;
6228 /*
6229 Set the destination for the jump that we added in
6230 sp_block_with_exceptions_finalize_declarations().
6231 */
6232 sp_instr *instr= sphead->get_instr(executable_section_ip - 1);
6233 instr->backpatch(sphead->instructions(), spcont);
6234 return false;
6235}
6236
6237
6238bool
6239LEX::sp_block_with_exceptions_finalize_exceptions(THD *thd,
6240 uint executable_section_ip,
6241 uint exception_count)
6242{
6243 if (!exception_count)
6244 {
6245 /*
6246 The jump from the end of DECLARE section to
6247 the beginning of the EXCEPTION section that we added in
6248 sp_block_with_exceptions_finalize_declarations() is useless
6249 if there were no exceptions.
6250 Replace it to "no operation".
6251 */
6252 return sphead->replace_instr_to_nop(thd, executable_section_ip - 1);
6253 }
6254 /*
6255 Generate a jump from the end of the EXCEPTION code
6256 to the executable section.
6257 */
6258 return sphead->add_instr_jump(thd, spcont, executable_section_ip);
6259}
6260
6261
6262bool LEX::sp_block_with_exceptions_add_empty(THD *thd)
6263{
6264 uint ip= sphead->instructions();
6265 return sp_block_with_exceptions_finalize_executable_section(thd, ip) ||
6266 sp_block_with_exceptions_finalize_exceptions(thd, ip, 0);
6267}
6268
6269
6270bool LEX::sp_change_context(THD *thd, const sp_pcontext *ctx, bool exclusive)
6271{
6272 uint n;
6273 uint ip= sphead->instructions();
6274 if ((n= spcont->diff_handlers(ctx, exclusive)))
6275 {
6276 sp_instr_hpop *hpop= new (thd->mem_root) sp_instr_hpop(ip++, spcont, n);
6277 if (unlikely(hpop == NULL) || unlikely(sphead->add_instr(hpop)))
6278 return true;
6279 }
6280 if ((n= spcont->diff_cursors(ctx, exclusive)))
6281 {
6282 sp_instr_cpop *cpop= new (thd->mem_root) sp_instr_cpop(ip++, spcont, n);
6283 if (unlikely(cpop == NULL) || unlikely(sphead->add_instr(cpop)))
6284 return true;
6285 }
6286 return false;
6287}
6288
6289
6290bool LEX::sp_leave_statement(THD *thd, const LEX_CSTRING *label_name)
6291{
6292 sp_label *lab= spcont->find_label(label_name);
6293 if (unlikely(!lab))
6294 {
6295 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "LEAVE", label_name->str);
6296 return true;
6297 }
6298 return sp_exit_block(thd, lab, NULL);
6299}
6300
6301bool LEX::sp_goto_statement(THD *thd, const LEX_CSTRING *label_name)
6302{
6303 sp_label *lab= spcont->find_goto_label(label_name);
6304 if (!lab || lab->ip == 0)
6305 {
6306 sp_label *delayedlabel;
6307 if (!lab)
6308 {
6309 // Label not found --> add forward jump to an unknown label
6310 spcont->push_goto_label(thd, label_name, 0, sp_label::GOTO);
6311 delayedlabel= spcont->last_goto_label();
6312 }
6313 else
6314 {
6315 delayedlabel= lab;
6316 }
6317 return sphead->push_backpatch_goto(thd, spcont, delayedlabel);
6318 }
6319 else
6320 {
6321 // Label found (backward goto)
6322 return sp_change_context(thd, lab->ctx, false) ||
6323 sphead->add_instr_jump(thd, spcont, lab->ip); /* Jump back */
6324 }
6325 return false;
6326}
6327
6328bool LEX::sp_push_goto_label(THD *thd, const LEX_CSTRING *label_name)
6329{
6330 sp_label *lab= spcont->find_goto_label(label_name, false);
6331 if (lab)
6332 {
6333 if (unlikely(lab->ip != 0))
6334 {
6335 my_error(ER_SP_LABEL_REDEFINE, MYF(0), label_name->str);
6336 return true;
6337 }
6338 lab->ip= sphead->instructions();
6339
6340 sp_label *beginblocklabel= spcont->find_label(&empty_clex_str);
6341 sphead->backpatch_goto(thd, lab, beginblocklabel);
6342 }
6343 else
6344 {
6345 spcont->push_goto_label(thd, label_name, sphead->instructions());
6346 }
6347 return false;
6348}
6349
6350bool LEX::sp_exit_block(THD *thd, sp_label *lab)
6351{
6352 /*
6353 When jumping to a BEGIN-END block end, the target jump
6354 points to the block hpop/cpop cleanup instructions,
6355 so we should exclude the block context here.
6356 When jumping to something else (i.e., SP_LAB_ITER),
6357 there are no hpop/cpop at the jump destination,
6358 so we should include the block context here for cleanup.
6359 */
6360 bool exclusive= (lab->type == sp_label::BEGIN);
6361 return sp_change_context(thd, lab->ctx, exclusive) ||
6362 sphead->add_instr_jump_forward_with_backpatch(thd, spcont, lab);
6363}
6364
6365
6366bool LEX::sp_exit_block(THD *thd, sp_label *lab, Item *when)
6367{
6368 if (!when)
6369 return sp_exit_block(thd, lab);
6370
6371 DBUG_ASSERT(sphead == thd->lex->sphead);
6372 DBUG_ASSERT(spcont == thd->lex->spcont);
6373 sp_instr_jump_if_not *i= new (thd->mem_root)
6374 sp_instr_jump_if_not(sphead->instructions(),
6375 spcont,
6376 when, thd->lex);
6377 if (unlikely(i == NULL) ||
6378 unlikely(sphead->add_instr(i)) ||
6379 unlikely(sp_exit_block(thd, lab)))
6380 return true;
6381 i->backpatch(sphead->instructions(), spcont);
6382 return false;
6383}
6384
6385
6386bool LEX::sp_exit_statement(THD *thd, Item *item)
6387{
6388 sp_label *lab= spcont->find_label_current_loop_start();
6389 if (unlikely(!lab))
6390 {
6391 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "EXIT", "");
6392 return true;
6393 }
6394 DBUG_ASSERT(lab->type == sp_label::ITERATION);
6395 return sp_exit_block(thd, lab, item);
6396}
6397
6398
6399bool LEX::sp_exit_statement(THD *thd, const LEX_CSTRING *label_name, Item *item)
6400{
6401 sp_label *lab= spcont->find_label(label_name);
6402 if (unlikely(!lab || lab->type != sp_label::ITERATION))
6403 {
6404 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "EXIT", label_name->str);
6405 return true;
6406 }
6407 return sp_exit_block(thd, lab, item);
6408}
6409
6410
6411bool LEX::sp_iterate_statement(THD *thd, const LEX_CSTRING *label_name)
6412{
6413 sp_label *lab= spcont->find_label(label_name);
6414 if (unlikely(!lab || lab->type != sp_label::ITERATION))
6415 {
6416 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "ITERATE", label_name->str);
6417 return true;
6418 }
6419 return sp_continue_loop(thd, lab);
6420}
6421
6422
6423bool LEX::sp_continue_loop(THD *thd, sp_label *lab)
6424{
6425 if (lab->ctx->for_loop().m_index)
6426 {
6427 // We're in a FOR loop, increment the index variable before backward jump
6428 sphead->reset_lex(thd);
6429 DBUG_ASSERT(this != thd->lex);
6430 if (thd->lex->sp_for_loop_increment(thd, lab->ctx->for_loop()) ||
6431 thd->lex->sphead->restore_lex(thd))
6432 return true;
6433 }
6434 return sp_change_context(thd, lab->ctx, false) ||
6435 sphead->add_instr_jump(thd, spcont, lab->ip); /* Jump back */
6436}
6437
6438
6439bool LEX::sp_continue_loop(THD *thd, sp_label *lab, Item *when)
6440{
6441 if (!when)
6442 return sp_continue_loop(thd, lab);
6443
6444 DBUG_ASSERT(sphead == thd->lex->sphead);
6445 DBUG_ASSERT(spcont == thd->lex->spcont);
6446 sp_instr_jump_if_not *i= new (thd->mem_root)
6447 sp_instr_jump_if_not(sphead->instructions(),
6448 spcont,
6449 when, thd->lex);
6450 if (unlikely(i == NULL) ||
6451 unlikely(sphead->add_instr(i)) ||
6452 unlikely(sp_continue_loop(thd, lab)))
6453 return true;
6454 i->backpatch(sphead->instructions(), spcont);
6455 return false;
6456}
6457
6458
6459bool LEX::sp_continue_statement(THD *thd, Item *when)
6460{
6461 sp_label *lab= spcont->find_label_current_loop_start();
6462 if (unlikely(!lab))
6463 {
6464 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "CONTINUE", "");
6465 return true;
6466 }
6467 DBUG_ASSERT(lab->type == sp_label::ITERATION);
6468 return sp_continue_loop(thd, lab, when);
6469}
6470
6471
6472bool LEX::sp_continue_statement(THD *thd, const LEX_CSTRING *label_name,
6473 Item *when)
6474{
6475 sp_label *lab= spcont->find_label(label_name);
6476 if (!lab || lab->type != sp_label::ITERATION)
6477 {
6478 my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "CONTINUE", label_name->str);
6479 return true;
6480 }
6481 return sp_continue_loop(thd, lab, when);
6482}
6483
6484
6485bool LEX::maybe_start_compound_statement(THD *thd)
6486{
6487 if (!sphead)
6488 {
6489 if (!make_sp_head(thd, NULL, &sp_handler_procedure))
6490 return true;
6491 sphead->set_suid(SP_IS_NOT_SUID);
6492 sphead->set_body_start(thd, thd->m_parser_state->m_lip.get_cpp_ptr());
6493 }
6494 return false;
6495}
6496
6497
6498bool LEX::sp_push_loop_label(THD *thd, const LEX_CSTRING *label_name)
6499{
6500 sp_label *lab= spcont->find_label(label_name);
6501 if (lab)
6502 {
6503 my_error(ER_SP_LABEL_REDEFINE, MYF(0), label_name->str);
6504 return true;
6505 }
6506 spcont->push_label(thd, label_name, sphead->instructions(),
6507 sp_label::ITERATION);
6508 return false;
6509}
6510
6511
6512bool LEX::sp_push_loop_empty_label(THD *thd)
6513{
6514 if (maybe_start_compound_statement(thd))
6515 return true;
6516 /* Unlabeled controls get an empty label. */
6517 spcont->push_label(thd, &empty_clex_str, sphead->instructions(),
6518 sp_label::ITERATION);
6519 return false;
6520}
6521
6522
6523bool LEX::sp_pop_loop_label(THD *thd, const LEX_CSTRING *label_name)
6524{
6525 sp_label *lab= spcont->pop_label();
6526 sphead->backpatch(lab);
6527 if (label_name->str &&
6528 lex_string_cmp(system_charset_info, label_name,
6529 &lab->name) != 0)
6530 {
6531 my_error(ER_SP_LABEL_MISMATCH, MYF(0), label_name->str);
6532 return true;
6533 }
6534 return false;
6535}
6536
6537
6538void LEX::sp_pop_loop_empty_label(THD *thd)
6539{
6540 sp_label *lab= spcont->pop_label();
6541 sphead->backpatch(lab);
6542 DBUG_ASSERT(lab->name.length == 0);
6543}
6544
6545
6546bool LEX::sp_while_loop_expression(THD *thd, Item *expr)
6547{
6548 sp_instr_jump_if_not *i= new (thd->mem_root)
6549 sp_instr_jump_if_not(sphead->instructions(), spcont, expr, this);
6550 return (unlikely(i == NULL) ||
6551 /* Jumping forward */
6552 unlikely(sphead->push_backpatch(thd, i, spcont->last_label())) ||
6553 unlikely(sphead->new_cont_backpatch(i)) ||
6554 unlikely(sphead->add_instr(i)));
6555}
6556
6557
6558bool LEX::sp_while_loop_finalize(THD *thd)
6559{
6560 sp_label *lab= spcont->last_label(); /* Jumping back */
6561 sp_instr_jump *i= new (thd->mem_root)
6562 sp_instr_jump(sphead->instructions(), spcont, lab->ip);
6563 if (unlikely(i == NULL) ||
6564 unlikely(sphead->add_instr(i)))
6565 return true;
6566 sphead->do_cont_backpatch();
6567 return false;
6568}
6569
6570
6571Item *LEX::create_and_link_Item_trigger_field(THD *thd,
6572 const LEX_CSTRING *name,
6573 bool new_row)
6574{
6575 Item_trigger_field *trg_fld;
6576
6577 if (unlikely(trg_chistics.event == TRG_EVENT_INSERT && !new_row))
6578 {
6579 my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "OLD", "on INSERT");
6580 return NULL;
6581 }
6582
6583 if (unlikely(trg_chistics.event == TRG_EVENT_DELETE && new_row))
6584 {
6585 my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "NEW", "on DELETE");
6586 return NULL;
6587 }
6588
6589 DBUG_ASSERT(!new_row ||
6590 (trg_chistics.event == TRG_EVENT_INSERT ||
6591 trg_chistics.event == TRG_EVENT_UPDATE));
6592
6593 const bool tmp_read_only=
6594 !(new_row && trg_chistics.action_time == TRG_ACTION_BEFORE);
6595 trg_fld= new (thd->mem_root)
6596 Item_trigger_field(thd, current_context(),
6597 new_row ?
6598 Item_trigger_field::NEW_ROW:
6599 Item_trigger_field::OLD_ROW,
6600 name, SELECT_ACL, tmp_read_only);
6601 /*
6602 Let us add this item to list of all Item_trigger_field objects
6603 in trigger.
6604 */
6605 if (likely(trg_fld))
6606 trg_table_fields.link_in_list(trg_fld, &trg_fld->next_trg_field);
6607
6608 return trg_fld;
6609}
6610
6611
6612Item *LEX::make_item_colon_ident_ident(THD *thd,
6613 const Lex_ident_cli_st *ca,
6614 const Lex_ident_cli_st *cb)
6615{
6616 Lex_ident_sys a(thd, ca), b(thd, cb);
6617 if (a.is_null() || b.is_null())
6618 return NULL; // OEM
6619 if (!is_trigger_new_or_old_reference(&a))
6620 {
6621 thd->parse_error();
6622 return NULL;
6623 }
6624 bool new_row= (a.str[0] == 'N' || a.str[0] == 'n');
6625 return create_and_link_Item_trigger_field(thd, &b, new_row);
6626}
6627
6628
6629Item *LEX::make_item_sysvar(THD *thd,
6630 enum_var_type type,
6631 const LEX_CSTRING *name,
6632 const LEX_CSTRING *component)
6633
6634{
6635 Item *item;
6636 DBUG_ASSERT(name->str);
6637 /*
6638 "SELECT @@global.global.variable" is not allowed
6639 Note, "global" can come through TEXT_STRING_sys.
6640 */
6641 if (component->str && unlikely(check_reserved_words(name)))
6642 {
6643 thd->parse_error();
6644 return NULL;
6645 }
6646 if (unlikely(!(item= get_system_var(thd, type, name, component))))
6647 return NULL;
6648 if (!((Item_func_get_system_var*) item)->is_written_to_binlog())
6649 set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE);
6650 return item;
6651}
6652
6653
6654Item_param *LEX::add_placeholder(THD *thd, const LEX_CSTRING *name,
6655 const char *start, const char *end)
6656{
6657 if (unlikely(!thd->m_parser_state->m_lip.stmt_prepare_mode))
6658 {
6659 thd->parse_error(ER_SYNTAX_ERROR, start);
6660 return NULL;
6661 }
6662 if (unlikely(!parsing_options.allows_variable))
6663 {
6664 my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
6665 return NULL;
6666 }
6667
6668 Query_fragment pos(thd, sphead, start, end);
6669 Item_param *item= new (thd->mem_root) Item_param(thd, name,
6670 pos.pos(), pos.length());
6671 if (unlikely(!item) || unlikely(param_list.push_back(item, thd->mem_root)))
6672 {
6673 my_error(ER_OUT_OF_RESOURCES, MYF(0));
6674 return NULL;
6675 }
6676 return item;
6677}
6678
6679
6680bool LEX::add_signal_statement(THD *thd, const sp_condition_value *v)
6681{
6682 Yacc_state *state= &thd->m_parser_state->m_yacc;
6683 sql_command= SQLCOM_SIGNAL;
6684 m_sql_cmd= new (thd->mem_root) Sql_cmd_signal(v, state->m_set_signal_info);
6685 return m_sql_cmd == NULL;
6686}
6687
6688
6689bool LEX::add_resignal_statement(THD *thd, const sp_condition_value *v)
6690{
6691 Yacc_state *state= &thd->m_parser_state->m_yacc;
6692 sql_command= SQLCOM_RESIGNAL;
6693 m_sql_cmd= new (thd->mem_root) Sql_cmd_resignal(v, state->m_set_signal_info);
6694 return m_sql_cmd == NULL;
6695}
6696
6697
6698Item *LEX::create_item_ident_nospvar(THD *thd,
6699 const Lex_ident_sys_st *a,
6700 const Lex_ident_sys_st *b)
6701{
6702 DBUG_ASSERT(this == thd->lex);
6703 /*
6704 FIXME This will work ok in simple_ident_nospvar case because
6705 we can't meet simple_ident_nospvar in trigger now. But it
6706 should be changed in future.
6707 */
6708 if (is_trigger_new_or_old_reference(a))
6709 {
6710 bool new_row= (a->str[0]=='N' || a->str[0]=='n');
6711
6712 return create_and_link_Item_trigger_field(thd, b, new_row);
6713 }
6714
6715 if (unlikely(current_select->no_table_names_allowed))
6716 {
6717 my_error(ER_TABLENAME_NOT_ALLOWED_HERE, MYF(0), a->str, thd->where);
6718 return NULL;
6719 }
6720 if ((current_select->parsing_place != IN_HAVING) ||
6721 (current_select->get_in_sum_expr() > 0))
6722 return new (thd->mem_root) Item_field(thd, current_context(),
6723 NullS, a->str, b);
6724 return new (thd->mem_root) Item_ref(thd, current_context(),
6725 NullS, a->str, b);
6726}
6727
6728
6729Item_splocal *LEX::create_item_spvar_row_field(THD *thd,
6730 const Sp_rcontext_handler *rh,
6731 const Lex_ident_sys *a,
6732 const Lex_ident_sys *b,
6733 sp_variable *spv,
6734 const char *start,
6735 const char *end)
6736{
6737 if (unlikely(!parsing_options.allows_variable))
6738 {
6739 my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
6740 return NULL;
6741 }
6742
6743 Query_fragment pos(thd, sphead, start, end);
6744 Item_splocal *item;
6745 if (spv->field_def.is_table_rowtype_ref() ||
6746 spv->field_def.is_cursor_rowtype_ref())
6747 {
6748 if (unlikely(!(item= new (thd->mem_root)
6749 Item_splocal_row_field_by_name(thd, rh, a, b, spv->offset,
6750 &type_handler_null,
6751 pos.pos(), pos.length()))))
6752 return NULL;
6753 }
6754 else
6755 {
6756 uint row_field_offset;
6757 const Spvar_definition *def;
6758 if (unlikely(!(def= spv->find_row_field(a, b, &row_field_offset))))
6759 return NULL;
6760
6761 if (unlikely(!(item= new (thd->mem_root)
6762 Item_splocal_row_field(thd, rh, a, b,
6763 spv->offset, row_field_offset,
6764 def->type_handler(),
6765 pos.pos(), pos.length()))))
6766 return NULL;
6767 }
6768#ifdef DBUG_ASSERT_EXISTS
6769 item->m_sp= sphead;
6770#endif
6771 safe_to_cache_query=0;
6772 return item;
6773}
6774
6775
6776my_var *LEX::create_outvar(THD *thd, const LEX_CSTRING *name)
6777{
6778 const Sp_rcontext_handler *rh;
6779 sp_variable *spv;
6780 if (likely((spv= find_variable(name, &rh))))
6781 return result ? new (thd->mem_root)
6782 my_var_sp(rh, name, spv->offset,
6783 spv->type_handler(), sphead) :
6784 NULL /* EXPLAIN */;
6785 my_error(ER_SP_UNDECLARED_VAR, MYF(0), name->str);
6786 return NULL;
6787}
6788
6789
6790my_var *LEX::create_outvar(THD *thd,
6791 const LEX_CSTRING *a,
6792 const LEX_CSTRING *b)
6793{
6794 const Sp_rcontext_handler *rh;
6795 sp_variable *t;
6796 if (unlikely(!(t= find_variable(a, &rh))))
6797 {
6798 my_error(ER_SP_UNDECLARED_VAR, MYF(0), a->str);
6799 return NULL;
6800 }
6801 uint row_field_offset;
6802 if (!t->find_row_field(a, b, &row_field_offset))
6803 return NULL;
6804 return result ?
6805 new (thd->mem_root) my_var_sp_row_field(rh, a, b, t->offset,
6806 row_field_offset, sphead) :
6807 NULL /* EXPLAIN */;
6808}
6809
6810
6811Item *LEX::create_item_func_nextval(THD *thd, Table_ident *table_ident)
6812{
6813 TABLE_LIST *table;
6814 if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
6815 TL_OPTION_SEQUENCE,
6816 TL_WRITE_ALLOW_WRITE,
6817 MDL_SHARED_WRITE))))
6818 return NULL;
6819 thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
6820 return new (thd->mem_root) Item_func_nextval(thd, table);
6821}
6822
6823
6824Item *LEX::create_item_func_lastval(THD *thd, Table_ident *table_ident)
6825{
6826 TABLE_LIST *table;
6827 if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
6828 TL_OPTION_SEQUENCE,
6829 TL_READ,
6830 MDL_SHARED_READ))))
6831 return NULL;
6832 thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
6833 return new (thd->mem_root) Item_func_lastval(thd, table);
6834}
6835
6836
6837Item *LEX::create_item_func_nextval(THD *thd,
6838 const LEX_CSTRING *db,
6839 const LEX_CSTRING *name)
6840{
6841 Table_ident *table_ident;
6842 if (unlikely(!(table_ident=
6843 new (thd->mem_root) Table_ident(thd, db, name, false))))
6844 return NULL;
6845 return create_item_func_nextval(thd, table_ident);
6846}
6847
6848
6849Item *LEX::create_item_func_lastval(THD *thd,
6850 const LEX_CSTRING *db,
6851 const LEX_CSTRING *name)
6852{
6853 Table_ident *table_ident;
6854 if (unlikely(!(table_ident=
6855 new (thd->mem_root) Table_ident(thd, db, name, false))))
6856 return NULL;
6857 return create_item_func_lastval(thd, table_ident);
6858}
6859
6860
6861Item *LEX::create_item_func_setval(THD *thd, Table_ident *table_ident,
6862 longlong nextval, ulonglong round,
6863 bool is_used)
6864{
6865 TABLE_LIST *table;
6866 if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
6867 TL_OPTION_SEQUENCE,
6868 TL_WRITE_ALLOW_WRITE,
6869 MDL_SHARED_WRITE))))
6870 return NULL;
6871 return new (thd->mem_root) Item_func_setval(thd, table, nextval, round,
6872 is_used);
6873}
6874
6875
6876Item *LEX::create_item_ident(THD *thd,
6877 const Lex_ident_cli_st *ca,
6878 const Lex_ident_cli_st *cb)
6879{
6880 const char *start= ca->pos();
6881 const char *end= cb->end();
6882 const Sp_rcontext_handler *rh;
6883 sp_variable *spv;
6884 DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= start);
6885 DBUG_ASSERT(start <= end);
6886 DBUG_ASSERT(end <= thd->m_parser_state->m_lip.get_end_of_query());
6887 Lex_ident_sys a(thd, ca), b(thd, cb);
6888 if (a.is_null() || b.is_null())
6889 return NULL; // OEM
6890 if ((spv= find_variable(&a, &rh)) &&
6891 (spv->field_def.is_row() ||
6892 spv->field_def.is_table_rowtype_ref() ||
6893 spv->field_def.is_cursor_rowtype_ref()))
6894 return create_item_spvar_row_field(thd, rh, &a, &b, spv, start, end);
6895
6896 if ((thd->variables.sql_mode & MODE_ORACLE) && b.length == 7)
6897 {
6898 if (!my_strnncoll(system_charset_info,
6899 (const uchar *) b.str, 7,
6900 (const uchar *) "NEXTVAL", 7))
6901 return create_item_func_nextval(thd, &null_clex_str, &a);
6902 else if (!my_strnncoll(system_charset_info,
6903 (const uchar *) b.str, 7,
6904 (const uchar *) "CURRVAL", 7))
6905 return create_item_func_lastval(thd, &null_clex_str, &a);
6906 }
6907
6908 return create_item_ident_nospvar(thd, &a, &b);
6909}
6910
6911
6912Item *LEX::create_item_ident(THD *thd,
6913 const Lex_ident_sys_st *a,
6914 const Lex_ident_sys_st *b,
6915 const Lex_ident_sys_st *c)
6916{
6917 const char *schema= (thd->client_capabilities & CLIENT_NO_SCHEMA ?
6918 NullS : a->str);
6919
6920 if ((thd->variables.sql_mode & MODE_ORACLE) && c->length == 7)
6921 {
6922 if (!my_strnncoll(system_charset_info,
6923 (const uchar *) c->str, 7,
6924 (const uchar *) "NEXTVAL", 7))
6925 return create_item_func_nextval(thd, a, b);
6926 else if (!my_strnncoll(system_charset_info,
6927 (const uchar *) c->str, 7,
6928 (const uchar *) "CURRVAL", 7))
6929 return create_item_func_lastval(thd, a, b);
6930 }
6931
6932 if (current_select->no_table_names_allowed)
6933 {
6934 my_error(ER_TABLENAME_NOT_ALLOWED_HERE, MYF(0), b->str, thd->where);
6935 return NULL;
6936 }
6937 if (current_select->parsing_place != IN_HAVING ||
6938 current_select->get_in_sum_expr() > 0)
6939 return new (thd->mem_root) Item_field(thd, current_context(),
6940 schema, b->str, c);
6941 return new (thd->mem_root) Item_ref(thd, current_context(),
6942 schema, b->str, c);
6943}
6944
6945
6946Item *LEX::create_item_limit(THD *thd, const Lex_ident_cli_st *ca)
6947{
6948 DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= ca->pos());
6949 DBUG_ASSERT(ca->pos() <= ca->end());
6950 DBUG_ASSERT(ca->end() <= thd->m_parser_state->m_lip.get_end_of_query());
6951
6952 const Sp_rcontext_handler *rh;
6953 sp_variable *spv;
6954 Lex_ident_sys sa(thd, ca);
6955 if (sa.is_null())
6956 return NULL; // EOM
6957 if (!(spv= find_variable(&sa, &rh)))
6958 {
6959 my_error(ER_SP_UNDECLARED_VAR, MYF(0), sa.str);
6960 return NULL;
6961 }
6962
6963 Query_fragment pos(thd, sphead, ca->pos(), ca->end());
6964 Item_splocal *item;
6965 if (unlikely(!(item= new (thd->mem_root)
6966 Item_splocal(thd, rh, &sa,
6967 spv->offset, spv->type_handler(),
6968 pos.pos(), pos.length()))))
6969 return NULL;
6970#ifdef DBUG_ASSERT_EXISTS
6971 item->m_sp= sphead;
6972#endif
6973 safe_to_cache_query= 0;
6974
6975 if (unlikely(item->type() != Item::INT_ITEM))
6976 {
6977 my_error(ER_WRONG_SPVAR_TYPE_IN_LIMIT, MYF(0));
6978 return NULL;
6979 }
6980 item->limit_clause_param= true;
6981 return item;
6982}
6983
6984
6985Item *LEX::create_item_limit(THD *thd,
6986 const Lex_ident_cli_st *ca,
6987 const Lex_ident_cli_st *cb)
6988{
6989 DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= ca->pos());
6990 DBUG_ASSERT(ca->pos() <= cb->end());
6991 DBUG_ASSERT(cb->end() <= thd->m_parser_state->m_lip.get_end_of_query());
6992
6993 const Sp_rcontext_handler *rh;
6994 sp_variable *spv;
6995 Lex_ident_sys sa(thd, ca), sb(thd, cb);
6996 if (unlikely(sa.is_null() || sb.is_null()))
6997 return NULL; // EOM
6998 if (!(spv= find_variable(&sa, &rh)))
6999 {
7000 my_error(ER_SP_UNDECLARED_VAR, MYF(0), sa.str);
7001 return NULL;
7002 }
7003 // Qualified %TYPE variables are not possible
7004 DBUG_ASSERT(!spv->field_def.column_type_ref());
7005 Item_splocal *item;
7006 if (unlikely(!(item= create_item_spvar_row_field(thd, rh, &sa, &sb, spv,
7007 ca->pos(), cb->end()))))
7008 return NULL;
7009 if (unlikely(item->type() != Item::INT_ITEM))
7010 {
7011 my_error(ER_WRONG_SPVAR_TYPE_IN_LIMIT, MYF(0));
7012 return NULL;
7013 }
7014 item->limit_clause_param= true;
7015 return item;
7016}
7017
7018
7019bool LEX::set_user_variable(THD *thd, const LEX_CSTRING *name, Item *val)
7020{
7021 Item_func_set_user_var *item;
7022 set_var_user *var;
7023 if (unlikely(!(item= new (thd->mem_root) Item_func_set_user_var(thd, name,
7024 val))) ||
7025 unlikely(!(var= new (thd->mem_root) set_var_user(item))))
7026 return true;
7027 if (unlikely(var_list.push_back(var, thd->mem_root)))
7028 return true;
7029 return false;
7030}
7031
7032
7033Item *LEX::create_item_ident_nosp(THD *thd, Lex_ident_sys_st *name)
7034{
7035 if (current_select->parsing_place != IN_HAVING ||
7036 current_select->get_in_sum_expr() > 0)
7037 return new (thd->mem_root) Item_field(thd, current_context(),
7038 NullS, NullS, name);
7039
7040 return new (thd->mem_root) Item_ref(thd, current_context(),
7041 NullS, NullS, name);
7042}
7043
7044
7045Item *LEX::create_item_ident_sp(THD *thd, Lex_ident_sys_st *name,
7046 const char *start,
7047 const char *end)
7048{
7049 DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= start);
7050 DBUG_ASSERT(start <= end);
7051 DBUG_ASSERT(end <= thd->m_parser_state->m_lip.get_end_of_query());
7052
7053 const Sp_rcontext_handler *rh;
7054 sp_variable *spv;
7055 DBUG_ASSERT(spcont);
7056 DBUG_ASSERT(sphead);
7057 if ((spv= find_variable(name, &rh)))
7058 {
7059 /* We're compiling a stored procedure and found a variable */
7060 if (!parsing_options.allows_variable)
7061 {
7062 my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
7063 return NULL;
7064 }
7065
7066 Query_fragment pos(thd, sphead, start, end);
7067 Item_splocal *splocal= spv->field_def.is_column_type_ref() ?
7068 new (thd->mem_root) Item_splocal_with_delayed_data_type(thd, rh, name,
7069 spv->offset,
7070 pos.pos(),
7071 pos.length()) :
7072 new (thd->mem_root) Item_splocal(thd, rh, name,
7073 spv->offset, spv->type_handler(),
7074 pos.pos(), pos.length());
7075 if (unlikely(splocal == NULL))
7076 return NULL;
7077#ifdef DBUG_ASSERT_EXISTS
7078 splocal->m_sp= sphead;
7079#endif
7080 safe_to_cache_query= 0;
7081 return splocal;
7082 }
7083
7084 if (thd->variables.sql_mode & MODE_ORACLE)
7085 {
7086 if (lex_string_eq(name, STRING_WITH_LEN("SQLCODE")))
7087 return new (thd->mem_root) Item_func_sqlcode(thd);
7088 if (lex_string_eq(name, STRING_WITH_LEN("SQLERRM")))
7089 return new (thd->mem_root) Item_func_sqlerrm(thd);
7090 }
7091 return create_item_ident_nosp(thd, name);
7092}
7093
7094
7095
7096bool LEX::set_variable(const LEX_CSTRING *name, Item *item)
7097{
7098 sp_pcontext *ctx;
7099 const Sp_rcontext_handler *rh;
7100 sp_variable *spv= find_variable(name, &ctx, &rh);
7101 return spv ? sphead->set_local_variable(thd, ctx, rh, spv, item, this, true) :
7102 set_system_variable(option_type, name, item);
7103}
7104
7105
7106/**
7107 Generate instructions for:
7108 SET x.y= expr;
7109*/
7110bool LEX::set_variable(const LEX_CSTRING *name1,
7111 const LEX_CSTRING *name2,
7112 Item *item)
7113{
7114 const Sp_rcontext_handler *rh;
7115 sp_pcontext *ctx;
7116 sp_variable *spv;
7117 if (spcont && (spv= find_variable(name1, &ctx, &rh)))
7118 {
7119 if (spv->field_def.is_table_rowtype_ref() ||
7120 spv->field_def.is_cursor_rowtype_ref())
7121 return sphead->set_local_variable_row_field_by_name(thd, ctx,
7122 rh,
7123 spv, name2,
7124 item, this);
7125 // A field of a ROW variable
7126 uint row_field_offset;
7127 return !spv->find_row_field(name1, name2, &row_field_offset) ||
7128 sphead->set_local_variable_row_field(thd, ctx, rh,
7129 spv, row_field_offset,
7130 item, this);
7131 }
7132
7133 if (is_trigger_new_or_old_reference(name1))
7134 return set_trigger_field(name1, name2, item);
7135
7136 return set_system_variable(thd, option_type, name1, name2, item);
7137}
7138
7139
7140bool LEX::set_default_system_variable(enum_var_type var_type,
7141 const LEX_CSTRING *name,
7142 Item *val)
7143{
7144 static LEX_CSTRING default_base_name= {STRING_WITH_LEN("default")};
7145 sys_var *var= find_sys_var(thd, name->str, name->length);
7146 if (!var)
7147 return true;
7148 if (unlikely(!var->is_struct()))
7149 {
7150 my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), name->str);
7151 return true;
7152 }
7153 return set_system_variable(var_type, var, &default_base_name, val);
7154}
7155
7156
7157bool LEX::set_system_variable(enum_var_type var_type,
7158 const LEX_CSTRING *name,
7159 Item *val)
7160{
7161 sys_var *var= find_sys_var(thd, name->str, name->length);
7162 DBUG_ASSERT(thd->is_error() || var != NULL);
7163 return likely(var) ? set_system_variable(var_type, var, &null_clex_str, val) : true;
7164}
7165
7166
7167bool LEX::set_system_variable(THD *thd, enum_var_type var_type,
7168 const LEX_CSTRING *name1,
7169 const LEX_CSTRING *name2,
7170 Item *val)
7171{
7172 sys_var *tmp;
7173 if (unlikely(check_reserved_words(name1)) ||
7174 unlikely(!(tmp= find_sys_var_ex(thd, name2->str, name2->length, true,
7175 false))))
7176 {
7177 my_error(ER_UNKNOWN_STRUCTURED_VARIABLE, MYF(0),
7178 (int) name1->length, name1->str);
7179 return true;
7180 }
7181 if (unlikely(!tmp->is_struct()))
7182 {
7183 my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), name2->str);
7184 return true;
7185 }
7186 return set_system_variable(var_type, tmp, name1, val);
7187}
7188
7189
7190bool LEX::set_trigger_field(const LEX_CSTRING *name1, const LEX_CSTRING *name2,
7191 Item *val)
7192{
7193 DBUG_ASSERT(is_trigger_new_or_old_reference(name1));
7194 if (unlikely(name1->str[0]=='O' || name1->str[0]=='o'))
7195 {
7196 my_error(ER_TRG_CANT_CHANGE_ROW, MYF(0), "OLD", "");
7197 return true;
7198 }
7199 if (unlikely(trg_chistics.event == TRG_EVENT_DELETE))
7200 {
7201 my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "NEW", "on DELETE");
7202 return true;
7203 }
7204 if (unlikely(trg_chistics.action_time == TRG_ACTION_AFTER))
7205 {
7206 my_error(ER_TRG_CANT_CHANGE_ROW, MYF(0), "NEW", "after ");
7207 return true;
7208 }
7209 return set_trigger_new_row(name2, val);
7210}
7211
7212
7213#ifdef MYSQL_SERVER
7214uint binlog_unsafe_map[256];
7215
7216#define UNSAFE(a, b, c) \
7217 { \
7218 DBUG_PRINT("unsafe_mixed_statement", ("SETTING BASE VALUES: %s, %s, %02X\n", \
7219 LEX::stmt_accessed_table_string(a), \
7220 LEX::stmt_accessed_table_string(b), \
7221 c)); \
7222 unsafe_mixed_statement(a, b, c); \
7223 }
7224
7225/*
7226 Sets the combination given by "a" and "b" and automatically combinations
7227 given by other types of access, i.e. 2^(8 - 2), as unsafe.
7228
7229 It may happen a colision when automatically defining a combination as unsafe.
7230 For that reason, a combination has its unsafe condition redefined only when
7231 the new_condition is greater then the old. For instance,
7232
7233 . (BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY) is never overwritten by
7234 . (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF).
7235*/
7236void unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,
7237 LEX::enum_stmt_accessed_table b, uint condition)
7238{
7239 int type= 0;
7240 int index= (1U << a) | (1U << b);
7241
7242
7243 for (type= 0; type < 256; type++)
7244 {
7245 if ((type & index) == index)
7246 {
7247 binlog_unsafe_map[type] |= condition;
7248 }
7249 }
7250}
7251/*
7252 The BINLOG_* AND TRX_CACHE_* values can be combined by using '&' or '|',
7253 which means that both conditions need to be satisfied or any of them is
7254 enough. For example,
7255
7256 . BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY means that the statment is
7257 unsafe when the option is on and trx-cache is not empty;
7258
7259 . BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF means the statement is unsafe
7260 in all cases.
7261
7262 . TRX_CACHE_EMPTY | TRX_CACHE_NOT_EMPTY means the statement is unsafe
7263 in all cases. Similar as above.
7264*/
7265void binlog_unsafe_map_init()
7266{
7267 memset((void*) binlog_unsafe_map, 0, sizeof(uint) * 256);
7268
7269 /*
7270 Classify a statement as unsafe when there is a mixed statement and an
7271 on-going transaction at any point of the execution if:
7272
7273 1. The mixed statement is about to update a transactional table and
7274 a non-transactional table.
7275
7276 2. The mixed statement is about to update a transactional table and
7277 read from a non-transactional table.
7278
7279 3. The mixed statement is about to update a non-transactional table
7280 and temporary transactional table.
7281
7282 4. The mixed statement is about to update a temporary transactional
7283 table and read from a non-transactional table.
7284
7285 5. The mixed statement is about to update a transactional table and
7286 a temporary non-transactional table.
7287
7288 6. The mixed statement is about to update a transactional table and
7289 read from a temporary non-transactional table.
7290
7291 7. The mixed statement is about to update a temporary transactional
7292 table and temporary non-transactional table.
7293
7294 8. The mixed statement is about to update a temporary transactional
7295 table and read from a temporary non-transactional table.
7296
7297 After updating a transactional table if:
7298
7299 9. The mixed statement is about to update a non-transactional table
7300 and read from a transactional table.
7301
7302 10. The mixed statement is about to update a non-transactional table
7303 and read from a temporary transactional table.
7304
7305 11. The mixed statement is about to update a temporary non-transactional
7306 table and read from a transactional table.
7307
7308 12. The mixed statement is about to update a temporary non-transactional
7309 table and read from a temporary transactional table.
7310
7311 13. The mixed statement is about to update a temporary non-transactional
7312 table and read from a non-transactional table.
7313
7314 The reason for this is that locks acquired may not protected a concurrent
7315 transaction of interfering in the current execution and by consequence in
7316 the result.
7317 */
7318 /* Case 1. */
7319 UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_NON_TRANS_TABLE,
7320 BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
7321 /* Case 2. */
7322 UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
7323 BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
7324 /* Case 3. */
7325 UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_WRITES_TEMP_TRANS_TABLE,
7326 BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
7327 /* Case 4. */
7328 UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
7329 BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
7330 /* Case 5. */
7331 UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
7332 BINLOG_DIRECT_ON);
7333 /* Case 6. */
7334 UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
7335 BINLOG_DIRECT_ON);
7336 /* Case 7. */
7337 UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
7338 BINLOG_DIRECT_ON);
7339 /* Case 8. */
7340 UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
7341 BINLOG_DIRECT_ON);
7342 /* Case 9. */
7343 UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
7344 (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
7345 /* Case 10 */
7346 UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
7347 (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
7348 /* Case 11. */
7349 UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
7350 BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
7351 /* Case 12. */
7352 UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
7353 BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
7354 /* Case 13. */
7355 UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
7356 BINLOG_DIRECT_OFF & TRX_CACHE_NOT_EMPTY);
7357}
7358#endif
7359
7360
7361/**
7362 @brief
7363 Finding fiels that are used in the GROUP BY of this st_select_lex
7364
7365 @param thd The thread handle
7366
7367 @details
7368 This method looks through the fields which are used in the GROUP BY of this
7369 st_select_lex and saves this fields.
7370*/
7371
7372void st_select_lex::collect_grouping_fields(THD *thd,
7373 ORDER *grouping_list)
7374{
7375 grouping_tmp_fields.empty();
7376 List_iterator<Item> li(join->fields_list);
7377 Item *item= li++;
7378 for (uint i= 0; i < master_unit()->derived->table->s->fields; i++, (item=li++))
7379 {
7380 for (ORDER *ord= grouping_list; ord; ord= ord->next)
7381 {
7382 if ((*ord->item)->eq((Item*)item, 0))
7383 {
7384 Grouping_tmp_field *grouping_tmp_field=
7385 new Grouping_tmp_field(master_unit()->derived->table->field[i], item);
7386 grouping_tmp_fields.push_back(grouping_tmp_field);
7387 }
7388 }
7389 }
7390}
7391
7392/**
7393 @brief
7394 For a condition check possibility of exraction a formula over grouping fields
7395
7396 @param cond The condition whose subformulas are to be analyzed
7397
7398 @details
7399 This method traverses the AND-OR condition cond and for each subformula of
7400 the condition it checks whether it can be usable for the extraction of a
7401 condition over the grouping fields of this select. The method uses
7402 the call-back parameter check_processor to ckeck whether a primary formula
7403 depends only on grouping fields.
7404 The subformulas that are not usable are marked with the flag NO_EXTRACTION_FL.
7405 The subformulas that can be entierly extracted are marked with the flag
7406 FULL_EXTRACTION_FL.
7407 @note
7408 This method is called before any call of extract_cond_for_grouping_fields.
7409 The flag NO_EXTRACTION_FL set in a subformula allows to avoid building clone
7410 for the subformula when extracting the pushable condition.
7411 The flag FULL_EXTRACTION_FL allows to delete later all top level conjuncts
7412 from cond.
7413*/
7414
7415void
7416st_select_lex::check_cond_extraction_for_grouping_fields(Item *cond,
7417 TABLE_LIST *derived)
7418{
7419 cond->clear_extraction_flag();
7420 if (cond->type() == Item::COND_ITEM)
7421 {
7422 bool and_cond= ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC;
7423 List<Item> *arg_list= ((Item_cond*) cond)->argument_list();
7424 List_iterator<Item> li(*arg_list);
7425 uint count= 0; // to count items not containing NO_EXTRACTION_FL
7426 uint count_full= 0; // to count items with FULL_EXTRACTION_FL
7427 Item *item;
7428 while ((item=li++))
7429 {
7430 check_cond_extraction_for_grouping_fields(item, derived);
7431 if (item->get_extraction_flag() != NO_EXTRACTION_FL)
7432 {
7433 count++;
7434 if (item->get_extraction_flag() == FULL_EXTRACTION_FL)
7435 count_full++;
7436 }
7437 else if (!and_cond)
7438 break;
7439 }
7440 if ((and_cond && count == 0) || item)
7441 cond->set_extraction_flag(NO_EXTRACTION_FL);
7442 if (count_full == arg_list->elements)
7443 cond->set_extraction_flag(FULL_EXTRACTION_FL);
7444 if (cond->get_extraction_flag() != 0)
7445 {
7446 li.rewind();
7447 while ((item=li++))
7448 item->clear_extraction_flag();
7449 }
7450 }
7451 else
7452 {
7453 int fl= cond->excl_dep_on_grouping_fields(this) ?
7454 FULL_EXTRACTION_FL : NO_EXTRACTION_FL;
7455 cond->set_extraction_flag(fl);
7456 }
7457}
7458
7459
7460/**
7461 @brief
7462 Build condition extractable from the given one depended on grouping fields
7463
7464 @param thd The thread handle
7465 @param cond The condition from which the condition depended
7466 on grouping fields is to be extracted
7467 @param no_top_clones If it's true then no clones for the top fully
7468 extractable conjuncts are built
7469
7470 @details
7471 For the given condition cond this method finds out what condition depended
7472 only on the grouping fields can be extracted from cond. If such condition C
7473 exists the method builds the item for it.
7474 This method uses the flags NO_EXTRACTION_FL and FULL_EXTRACTION_FL set by the
7475 preliminary call of st_select_lex::check_cond_extraction_for_grouping_fields
7476 to figure out whether a subformula depends only on these fields or not.
7477 @note
7478 The built condition C is always implied by the condition cond
7479 (cond => C). The method tries to build the most restictive such
7480 condition (i.e. for any other condition C' such that cond => C'
7481 we have C => C').
7482 @note
7483 The build item is not ready for usage: substitution for the field items
7484 has to be done and it has to be re-fixed.
7485
7486 @retval
7487 the built condition depended only on grouping fields if such a condition exists
7488 NULL if there is no such a condition
7489*/
7490
7491Item *st_select_lex::build_cond_for_grouping_fields(THD *thd, Item *cond,
7492 bool no_top_clones)
7493{
7494 if (cond->get_extraction_flag() == FULL_EXTRACTION_FL)
7495 {
7496 if (no_top_clones)
7497 return cond;
7498 cond->clear_extraction_flag();
7499 return cond->build_clone(thd);
7500 }
7501 if (cond->type() == Item::COND_ITEM)
7502 {
7503 bool cond_and= false;
7504 Item_cond *new_cond;
7505 if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
7506 {
7507 cond_and= true;
7508 new_cond= new (thd->mem_root) Item_cond_and(thd);
7509 }
7510 else
7511 new_cond= new (thd->mem_root) Item_cond_or(thd);
7512 if (unlikely(!new_cond))
7513 return 0;
7514 List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
7515 Item *item;
7516 while ((item=li++))
7517 {
7518 if (item->get_extraction_flag() == NO_EXTRACTION_FL)
7519 {
7520 DBUG_ASSERT(cond_and);
7521 item->clear_extraction_flag();
7522 continue;
7523 }
7524 Item *fix= build_cond_for_grouping_fields(thd, item,
7525 no_top_clones & cond_and);
7526 if (unlikely(!fix))
7527 {
7528 if (cond_and)
7529 continue;
7530 break;
7531 }
7532 new_cond->argument_list()->push_back(fix, thd->mem_root);
7533 }
7534
7535 if (!cond_and && item)
7536 {
7537 while((item= li++))
7538 item->clear_extraction_flag();
7539 return 0;
7540 }
7541 switch (new_cond->argument_list()->elements)
7542 {
7543 case 0:
7544 return 0;
7545 case 1:
7546 return new_cond->argument_list()->head();
7547 default:
7548 return new_cond;
7549 }
7550 }
7551 return 0;
7552}
7553
7554
7555int set_statement_var_if_exists(THD *thd, const char *var_name,
7556 size_t var_name_length, ulonglong value)
7557{
7558 sys_var *sysvar;
7559 if (unlikely(thd->lex->sql_command == SQLCOM_CREATE_VIEW))
7560 {
7561 my_error(ER_VIEW_SELECT_CLAUSE, MYF(0), "[NO]WAIT");
7562 return 1;
7563 }
7564 if (unlikely(thd->lex->sphead))
7565 {
7566 my_error(ER_SP_BADSTATEMENT, MYF(0), "[NO]WAIT");
7567 return 1;
7568 }
7569 if ((sysvar= find_sys_var_ex(thd, var_name, var_name_length, true, false)))
7570 {
7571 Item *item= new (thd->mem_root) Item_uint(thd, value);
7572 set_var *var= new (thd->mem_root) set_var(thd, OPT_SESSION, sysvar,
7573 &null_clex_str, item);
7574
7575 if (unlikely(!item) || unlikely(!var) ||
7576 unlikely(thd->lex->stmt_var_list.push_back(var, thd->mem_root)))
7577 {
7578 my_error(ER_OUT_OF_RESOURCES, MYF(0));
7579 return 1;
7580 }
7581 }
7582 return 0;
7583}
7584
7585
7586bool LEX::sp_add_cfetch(THD *thd, const LEX_CSTRING *name)
7587{
7588 uint offset;
7589 sp_instr_cfetch *i;
7590
7591 if (!spcont->find_cursor(name, &offset, false))
7592 {
7593 my_error(ER_SP_CURSOR_MISMATCH, MYF(0), name->str);
7594 return true;
7595 }
7596 i= new (thd->mem_root)
7597 sp_instr_cfetch(sphead->instructions(), spcont, offset,
7598 !(thd->variables.sql_mode & MODE_ORACLE));
7599 if (unlikely(i == NULL) || unlikely(sphead->add_instr(i)))
7600 return true;
7601 return false;
7602}
7603
7604
7605bool LEX::create_or_alter_view_finalize(THD *thd, Table_ident *table_ident)
7606{
7607 sql_command= SQLCOM_CREATE_VIEW;
7608 /* first table in list is target VIEW name */
7609 if (unlikely(!select_lex.add_table_to_list(thd, table_ident, NULL,
7610 TL_OPTION_UPDATING,
7611 TL_IGNORE,
7612 MDL_EXCLUSIVE)))
7613 return true;
7614 query_tables->open_strategy= TABLE_LIST::OPEN_STUB;
7615 return false;
7616}
7617
7618
7619bool LEX::add_alter_view(THD *thd, uint16 algorithm,
7620 enum_view_suid suid,
7621 Table_ident *table_ident)
7622{
7623 if (unlikely(sphead))
7624 {
7625 my_error(ER_SP_BADSTATEMENT, MYF(0), "ALTER VIEW");
7626 return true;
7627 }
7628 if (unlikely(!(create_view= new (thd->mem_root)
7629 Create_view_info(VIEW_ALTER, algorithm, suid))))
7630 return true;
7631 return create_or_alter_view_finalize(thd, table_ident);
7632}
7633
7634
7635bool LEX::add_create_view(THD *thd, DDL_options_st ddl,
7636 uint16 algorithm, enum_view_suid suid,
7637 Table_ident *table_ident)
7638{
7639 if (unlikely(set_create_options_with_check(ddl)))
7640 return true;
7641 if (unlikely(!(create_view= new (thd->mem_root)
7642 Create_view_info(ddl.or_replace() ?
7643 VIEW_CREATE_OR_REPLACE :
7644 VIEW_CREATE_NEW,
7645 algorithm, suid))))
7646 return true;
7647 return create_or_alter_view_finalize(thd, table_ident);
7648}
7649
7650
7651bool LEX::call_statement_start(THD *thd, sp_name *name)
7652{
7653 Database_qualified_name pkgname(&null_clex_str, &null_clex_str);
7654 const Sp_handler *sph= &sp_handler_procedure;
7655 sql_command= SQLCOM_CALL;
7656 value_list.empty();
7657 if (unlikely(sph->sp_resolve_package_routine(thd, thd->lex->sphead,
7658 name, &sph, &pkgname)))
7659 return true;
7660 if (unlikely(!(m_sql_cmd= new (thd->mem_root) Sql_cmd_call(name, sph))))
7661 return true;
7662 sph->add_used_routine(this, thd, name);
7663 if (pkgname.m_name.length)
7664 sp_handler_package_body.add_used_routine(this, thd, &pkgname);
7665 return false;
7666}
7667
7668
7669bool LEX::call_statement_start(THD *thd, const LEX_CSTRING *name)
7670{
7671 sp_name *spname= make_sp_name(thd, name);
7672 return unlikely(!spname) || call_statement_start(thd, spname);
7673}
7674
7675
7676bool LEX::call_statement_start(THD *thd, const LEX_CSTRING *name1,
7677 const LEX_CSTRING *name2)
7678{
7679 sp_name *spname= make_sp_name(thd, name1, name2);
7680 return unlikely(!spname) || call_statement_start(thd, spname);
7681}
7682
7683
7684sp_package *LEX::get_sp_package() const
7685{
7686 return sphead ? sphead->get_package() : NULL;
7687}
7688
7689
7690sp_package *LEX::create_package_start(THD *thd,
7691 enum_sql_command command,
7692 const Sp_handler *sph,
7693 const sp_name *name_arg,
7694 DDL_options_st options)
7695{
7696 sp_package *pkg;
7697
7698 if (unlikely(sphead))
7699 {
7700 my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), sph->type_str());
7701 return NULL;
7702 }
7703 if (unlikely(set_command_with_check(command, options)))
7704 return NULL;
7705 if (sph->type() == TYPE_ENUM_PACKAGE_BODY)
7706 {
7707 /*
7708 If we start parsing a "CREATE PACKAGE BODY", we need to load
7709 the corresponding "CREATE PACKAGE", for the following reasons:
7710 1. "CREATE PACKAGE BODY" is allowed only if "CREATE PACKAGE"
7711 was done earlier for the same package name.
7712 So if "CREATE PACKAGE" does not exist, we throw an error here.
7713 2. When parsing "CREATE PACKAGE BODY", we need to know all package
7714 public and private routine names, to translate procedure and
7715 function calls correctly.
7716 For example, this statement inside a package routine:
7717 CALL p;
7718 can be translated to:
7719 CALL db.pkg.p; -- p is a known (public or private) package routine
7720 CALL db.p; -- p is not a known package routine
7721 */
7722 sp_head *spec;
7723 int ret= sp_handler_package_spec.
7724 sp_cache_routine_reentrant(thd, name_arg, &spec);
7725 if (unlikely(!spec))
7726 {
7727 if (!ret)
7728 my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
7729 "PACKAGE", ErrConvDQName(name_arg).ptr());
7730 return 0;
7731 }
7732 }
7733 if (unlikely(!(pkg= new sp_package(this, name_arg, sph))))
7734 return NULL;
7735 pkg->reset_thd_mem_root(thd);
7736 pkg->init(this);
7737 pkg->make_qname(pkg->get_main_mem_root(), &pkg->m_qname);
7738 sphead= pkg;
7739 return pkg;
7740}
7741
7742
7743bool LEX::create_package_finalize(THD *thd,
7744 const sp_name *name,
7745 const sp_name *name2,
7746 const char *body_start,
7747 const char *body_end)
7748{
7749 if (name2 &&
7750 (name2->m_explicit_name != name->m_explicit_name ||
7751 strcmp(name2->m_db.str, name->m_db.str) ||
7752 !Sp_handler::eq_routine_name(name2->m_name, name->m_name)))
7753 {
7754 bool exp= name2->m_explicit_name || name->m_explicit_name;
7755 my_error(ER_END_IDENTIFIER_DOES_NOT_MATCH, MYF(0),
7756 exp ? ErrConvDQName(name2).ptr() : name2->m_name.str,
7757 exp ? ErrConvDQName(name).ptr() : name->m_name.str);
7758 return true;
7759 }
7760 sphead->m_body.length= body_end - body_start;
7761 if (unlikely(!(sphead->m_body.str= thd->strmake(body_start,
7762 sphead->m_body.length))))
7763 return true;
7764
7765 size_t not_used;
7766 Lex_input_stream *lip= & thd->m_parser_state->m_lip;
7767 sphead->m_defstr.length= lip->get_cpp_ptr() - lip->get_cpp_buf();
7768 sphead->m_defstr.str= thd->strmake(lip->get_cpp_buf(), sphead->m_defstr.length);
7769 trim_whitespace(thd->charset(), &sphead->m_defstr, &not_used);
7770
7771 sphead->restore_thd_mem_root(thd);
7772 sp_package *pkg= sphead->get_package();
7773 DBUG_ASSERT(pkg);
7774 return pkg->validate_after_parser(thd);
7775}
7776
7777
7778bool LEX::add_grant_command(THD *thd, enum_sql_command sql_command_arg,
7779 stored_procedure_type type_arg)
7780{
7781 if (columns.elements)
7782 {
7783 thd->parse_error();
7784 return true;
7785 }
7786 sql_command= sql_command_arg,
7787 type= type_arg;
7788 return false;
7789}
7790
7791
7792Item *LEX::make_item_func_substr(THD *thd, Item *a, Item *b, Item *c)
7793{
7794 return (thd->variables.sql_mode & MODE_ORACLE) ?
7795 new (thd->mem_root) Item_func_substr_oracle(thd, a, b, c) :
7796 new (thd->mem_root) Item_func_substr(thd, a, b, c);
7797}
7798
7799
7800Item *LEX::make_item_func_substr(THD *thd, Item *a, Item *b)
7801{
7802 return (thd->variables.sql_mode & MODE_ORACLE) ?
7803 new (thd->mem_root) Item_func_substr_oracle(thd, a, b) :
7804 new (thd->mem_root) Item_func_substr(thd, a, b);
7805}
7806
7807
7808Item *LEX::make_item_func_replace(THD *thd,
7809 Item *org,
7810 Item *find,
7811 Item *replace)
7812{
7813 return (thd->variables.sql_mode & MODE_ORACLE) ?
7814 new (thd->mem_root) Item_func_replace_oracle(thd, org, find, replace) :
7815 new (thd->mem_root) Item_func_replace(thd, org, find, replace);
7816}
7817
7818
7819bool SELECT_LEX::vers_push_field(THD *thd, TABLE_LIST *table,
7820 const LEX_CSTRING field_name)
7821{
7822 DBUG_ASSERT(field_name.str);
7823 Item_field *fld= new (thd->mem_root) Item_field(thd, &context,
7824 table->db.str,
7825 table->alias.str,
7826 &field_name);
7827 if (unlikely(!fld) || unlikely(item_list.push_back(fld)))
7828 return true;
7829
7830 if (thd->lex->view_list.elements)
7831 {
7832 LEX_CSTRING *l;
7833 if (unlikely(!(l= thd->make_clex_string(field_name.str,
7834 field_name.length))) ||
7835 unlikely(thd->lex->view_list.push_back(l)))
7836 return true;
7837 }
7838
7839 return false;
7840}
7841
7842
7843Item *Lex_trim_st::make_item_func_trim_std(THD *thd) const
7844{
7845 if (m_remove)
7846 {
7847 switch (m_spec) {
7848 case TRIM_BOTH:
7849 return new (thd->mem_root) Item_func_trim(thd, m_source, m_remove);
7850 case TRIM_LEADING:
7851 return new (thd->mem_root) Item_func_ltrim(thd, m_source, m_remove);
7852 case TRIM_TRAILING:
7853 return new (thd->mem_root) Item_func_rtrim(thd, m_source, m_remove);
7854 }
7855 }
7856
7857 switch (m_spec) {
7858 case TRIM_BOTH:
7859 return new (thd->mem_root) Item_func_trim(thd, m_source);
7860 case TRIM_LEADING:
7861 return new (thd->mem_root) Item_func_ltrim(thd, m_source);
7862 case TRIM_TRAILING:
7863 return new (thd->mem_root) Item_func_rtrim(thd, m_source);
7864 }
7865 DBUG_ASSERT(0);
7866 return NULL;
7867}
7868
7869
7870Item *Lex_trim_st::make_item_func_trim_oracle(THD *thd) const
7871{
7872 if (m_remove)
7873 {
7874 switch (m_spec) {
7875 case TRIM_BOTH:
7876 return new (thd->mem_root) Item_func_trim_oracle(thd, m_source, m_remove);
7877 case TRIM_LEADING:
7878 return new (thd->mem_root) Item_func_ltrim_oracle(thd, m_source, m_remove);
7879 case TRIM_TRAILING:
7880 return new (thd->mem_root) Item_func_rtrim_oracle(thd, m_source, m_remove);
7881 }
7882 }
7883
7884 switch (m_spec) {
7885 case TRIM_BOTH:
7886 return new (thd->mem_root) Item_func_trim_oracle(thd, m_source);
7887 case TRIM_LEADING:
7888 return new (thd->mem_root) Item_func_ltrim_oracle(thd, m_source);
7889 case TRIM_TRAILING:
7890 return new (thd->mem_root) Item_func_rtrim_oracle(thd, m_source);
7891 }
7892 DBUG_ASSERT(0);
7893 return NULL;
7894}
7895
7896
7897Item *Lex_trim_st::make_item_func_trim(THD *thd) const
7898{
7899 return (thd->variables.sql_mode & MODE_ORACLE) ?
7900 make_item_func_trim_oracle(thd) :
7901 make_item_func_trim_std(thd);
7902}
7903
7904
7905Item *LEX::make_item_func_call_generic(THD *thd, Lex_ident_cli_st *cdb,
7906 Lex_ident_cli_st *cname, List<Item> *args)
7907{
7908 Lex_ident_sys db(thd, cdb), name(thd, cname);
7909 if (db.is_null() || name.is_null())
7910 return NULL; // EOM
7911 /*
7912 The following in practice calls:
7913 <code>Create_sp_func::create()</code>
7914 and builds a stored function.
7915
7916 However, it's important to maintain the interface between the
7917 parser and the implementation in item_create.cc clean,
7918 since this will change with WL#2128 (SQL PATH):
7919 - INFORMATION_SCHEMA.version() is the SQL 99 syntax for the native
7920 function version(),
7921 - MySQL.version() is the SQL 2003 syntax for the native function
7922 version() (a vendor can specify any schema).
7923 */
7924
7925 if (!name.str || check_db_name((LEX_STRING*) static_cast<LEX_CSTRING*>(&db)))
7926 {
7927 my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
7928 return NULL;
7929 }
7930 if (check_routine_name(&name))
7931 return NULL;
7932
7933 Create_qfunc *builder= find_qualified_function_builder(thd);
7934 DBUG_ASSERT(builder);
7935 return builder->create_with_db(thd, &db, &name, true, args);
7936}
7937
7938
7939Item *LEX::create_item_qualified_asterisk(THD *thd,
7940 const Lex_ident_sys_st *name)
7941{
7942 Item *item;
7943 if (!(item= new (thd->mem_root) Item_field(thd, current_context(),
7944 NullS, name->str,
7945 &star_clex_str)))
7946 return NULL;
7947 current_select->with_wild++;
7948 return item;
7949}
7950
7951
7952Item *LEX::create_item_qualified_asterisk(THD *thd,
7953 const Lex_ident_sys_st *a,
7954 const Lex_ident_sys_st *b)
7955{
7956 Item *item;
7957 const char* schema= thd->client_capabilities & CLIENT_NO_SCHEMA ?
7958 NullS : a->str;
7959 if (!(item= new (thd->mem_root) Item_field(thd, current_context(),
7960 schema, b->str,
7961 &star_clex_str)))
7962 return NULL;
7963 current_select->with_wild++;
7964 return item;
7965}
7966
7967
7968bool Lex_ident_sys_st::copy_ident_cli(THD *thd, const Lex_ident_cli_st *str)
7969{
7970 return thd->to_ident_sys_alloc(this, str);
7971}
7972
7973bool Lex_ident_sys_st::copy_keyword(THD *thd, const Lex_ident_cli_st *str)
7974{
7975 return thd->make_lex_string(static_cast<LEX_CSTRING*>(this),
7976 str->str, str->length) == NULL;
7977}
7978
7979bool Lex_ident_sys_st::copy_or_convert(THD *thd,
7980 const Lex_ident_cli_st *src,
7981 CHARSET_INFO *cs)
7982{
7983 if (!src->is_8bit())
7984 return copy_keyword(thd, src); // 7bit string makes a wellformed identifier
7985 return convert(thd, src, cs);
7986}
7987
7988
7989bool Lex_ident_sys_st::copy_sys(THD *thd, const LEX_CSTRING *src)
7990{
7991 if (thd->check_string_for_wellformedness(src->str, src->length,
7992 system_charset_info))
7993 return true;
7994 return thd->make_lex_string(this, src->str, src->length) == NULL;
7995}
7996
7997
7998bool Lex_ident_sys_st::convert(THD *thd,
7999 const LEX_CSTRING *src, CHARSET_INFO *cs)
8000{
8001 LEX_STRING tmp;
8002 if (thd->convert_with_error(system_charset_info, &tmp, cs,
8003 src->str, src->length))
8004 return true;
8005 str= tmp.str;
8006 length= tmp.length;
8007 return false;
8008}
8009
8010
8011bool Lex_ident_sys_st::to_size_number(ulonglong *to) const
8012{
8013 ulonglong number;
8014 uint text_shift_number= 0;
8015 longlong prefix_number;
8016 const char *start_ptr= str;
8017 size_t str_len= length;
8018 const char *end_ptr= start_ptr + str_len;
8019 int error;
8020 prefix_number= my_strtoll10(start_ptr, (char**) &end_ptr, &error);
8021 if (likely((start_ptr + str_len - 1) == end_ptr))
8022 {
8023 switch (end_ptr[0])
8024 {
8025 case 'g':
8026 case 'G': text_shift_number+=30; break;
8027 case 'm':
8028 case 'M': text_shift_number+=20; break;
8029 case 'k':
8030 case 'K': text_shift_number+=10; break;
8031 default:
8032 my_error(ER_WRONG_SIZE_NUMBER, MYF(0));
8033 return true;
8034 }
8035 if (unlikely(prefix_number >> 31))
8036 {
8037 my_error(ER_SIZE_OVERFLOW_ERROR, MYF(0));
8038 return true;
8039 }
8040 number= prefix_number << text_shift_number;
8041 }
8042 else
8043 {
8044 my_error(ER_WRONG_SIZE_NUMBER, MYF(0));
8045 return true;
8046 }
8047 *to= number;
8048 return false;
8049}
8050
8051
8052bool LEX::part_values_current(THD *thd)
8053{
8054 partition_element *elem= part_info->curr_part_elem;
8055 if (!is_partition_management())
8056 {
8057 if (unlikely(part_info->part_type != VERSIONING_PARTITION))
8058 {
8059 my_error(ER_PARTITION_WRONG_TYPE, MYF(0), "SYSTEM_TIME");
8060 return true;
8061 }
8062 }
8063 else
8064 {
8065 DBUG_ASSERT(create_last_non_select_table);
8066 DBUG_ASSERT(create_last_non_select_table->table_name.str);
8067 // FIXME: other ALTER commands?
8068 my_error(ER_VERS_WRONG_PARTS, MYF(0),
8069 create_last_non_select_table->table_name.str);
8070 return true;
8071 }
8072 elem->type(partition_element::CURRENT);
8073 DBUG_ASSERT(part_info->vers_info);
8074 part_info->vers_info->now_part= elem;
8075 if (unlikely(part_info->init_column_part(thd)))
8076 return true;
8077 return false;
8078}
8079
8080
8081bool LEX::part_values_history(THD *thd)
8082{
8083 partition_element *elem= part_info->curr_part_elem;
8084 if (!is_partition_management())
8085 {
8086 if (unlikely(part_info->part_type != VERSIONING_PARTITION))
8087 {
8088 my_error(ER_PARTITION_WRONG_TYPE, MYF(0), "SYSTEM_TIME");
8089 return true;
8090 }
8091 }
8092 else
8093 {
8094 part_info->vers_init_info(thd);
8095 elem->id= UINT_MAX32;
8096 }
8097 DBUG_ASSERT(part_info->vers_info);
8098 if (unlikely(part_info->vers_info->now_part))
8099 {
8100 DBUG_ASSERT(create_last_non_select_table);
8101 DBUG_ASSERT(create_last_non_select_table->table_name.str);
8102 my_error(ER_VERS_WRONG_PARTS, MYF(0),
8103 create_last_non_select_table->table_name.str);
8104 return true;
8105 }
8106 elem->type(partition_element::HISTORY);
8107 if (unlikely(part_info->init_column_part(thd)))
8108 return true;
8109 return false;
8110}
8111
8112
8113bool LEX::last_field_generated_always_as_row_start_or_end(Lex_ident *p,
8114 const char *type,
8115 uint flag)
8116{
8117 if (unlikely(p->str))
8118 {
8119 my_error(ER_VERS_DUPLICATE_ROW_START_END, MYF(0), type,
8120 last_field->field_name.str);
8121 return true;
8122 }
8123 last_field->flags|= (flag | NOT_NULL_FLAG);
8124 DBUG_ASSERT(p);
8125 *p= last_field->field_name;
8126 return false;
8127}
8128
8129
8130
8131bool LEX::last_field_generated_always_as_row_start()
8132{
8133 Vers_parse_info &info= vers_get_info();
8134 Lex_ident *p= &info.as_row.start;
8135 return last_field_generated_always_as_row_start_or_end(p, "START",
8136 VERS_SYS_START_FLAG);
8137}
8138
8139
8140bool LEX::last_field_generated_always_as_row_end()
8141{
8142 Vers_parse_info &info= vers_get_info();
8143 Lex_ident *p= &info.as_row.end;
8144 return last_field_generated_always_as_row_start_or_end(p, "END",
8145 VERS_SYS_END_FLAG);
8146}
8147
8148
8149bool LEX::tvc_finalize()
8150{
8151 mysql_init_select(this);
8152 if (unlikely(!(current_select->tvc=
8153 new (thd->mem_root)
8154 table_value_constr(many_values,
8155 current_select,
8156 current_select->options))))
8157 return true;
8158 many_values.empty();
8159 return false;
8160}
8161
8162
8163bool LEX::tvc_finalize_derived()
8164{
8165 derived_tables|= DERIVED_SUBQUERY;
8166 if (unlikely(!expr_allows_subselect || sql_command == (int)SQLCOM_PURGE))
8167 {
8168 thd->parse_error();
8169 return true;
8170 }
8171 if (current_select->linkage == GLOBAL_OPTIONS_TYPE ||
8172 unlikely(mysql_new_select(this, 1, NULL)))
8173 return true;
8174 current_select->linkage= DERIVED_TABLE_TYPE;
8175 return tvc_finalize();
8176}
8177