1
/* Copyright (c) 2000, 2013, Oracle and/or its affiliates.
2
Copyright (c) 2009, 2013, Monty Program Ab.
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.
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.
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 */
18
/* A lexical scanner on a temporary buffer with a yacc interface */
22
#include "unireg.h" // REQUIRED: for other includes
23
#include "sql_class.h" // sql_lex.h: SQLCOM_END
25
#include "sql_parse.h" // add_to_list
26
#include "item_create.h"
31
#include "sql_select.h"
33
static int lex_one_token(void *arg, void *yythd);
36
We are using pointer to this variable for distinguishing between assignment
37
to NEW row field (when parsing trigger definition) and structured variable.
40
sys_var *trg_new_row_fake_var= (sys_var*) 0x01;
43
LEX_STRING constant for null-string to be used in parser and other places.
45
const LEX_STRING null_lex_str= {NULL, 0};
46
const LEX_STRING empty_lex_str= {(char *) "", 0};
48
@note The order of the elements of this array must correspond to
49
the order of elements in enum_binlog_stmt_unsafe.
52
Query_tables_list::binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT] =
54
ER_BINLOG_UNSAFE_LIMIT,
55
ER_BINLOG_UNSAFE_INSERT_DELAYED,
56
ER_BINLOG_UNSAFE_SYSTEM_TABLE,
57
ER_BINLOG_UNSAFE_AUTOINC_COLUMNS,
59
ER_BINLOG_UNSAFE_SYSTEM_VARIABLE,
60
ER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
61
ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS,
62
ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
63
ER_BINLOG_UNSAFE_MIXED_STATEMENT,
64
ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT,
65
ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE,
66
ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT,
67
ER_BINLOG_UNSAFE_REPLACE_SELECT,
68
ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT,
69
ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT,
70
ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC,
71
ER_BINLOG_UNSAFE_UPDATE_IGNORE,
72
ER_BINLOG_UNSAFE_INSERT_TWO_KEYS,
73
ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST
77
/* Longest standard keyword name */
79
#define TOCK_NAME_LENGTH 24
82
The following data is based on the latin1 character set, and is only
83
used when comparing keywords
86
static uchar to_upper_lex[]=
88
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
89
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
90
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
91
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
92
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
93
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
94
96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
95
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127,
96
128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
97
144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
98
160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
99
176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
100
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
101
208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
102
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
103
208,209,210,211,212,213,214,247,216,217,218,219,220,221,222,255
107
Names of the index hints (for error messages). Keep in sync with
111
const char * index_hint_type_name[] =
118
inline int lex_casecmp(const char *s, const char *t, uint len)
121
to_upper_lex[(uchar) *s++] == to_upper_lex[(uchar) *t++]) ;
125
#include <lex_hash.h>
131
DBUG_ENTER("lex_init");
132
for (i=0 ; i < array_elements(symbols) ; i++)
133
symbols[i].length=(uchar) strlen(symbols[i].name);
134
for (i=0 ; i < array_elements(sql_functions) ; i++)
135
sql_functions[i].length=(uchar) strlen(sql_functions[i].name);
142
{ // Call this when daemon ends
143
DBUG_ENTER("lex_free");
148
Initialize lex object for use in fix_fields and parsing.
151
init_lex_with_single_table()
152
@param thd The thread object
153
@param table The table object
154
@return Operation status
155
@retval TRUE An error occurred, memory allocation error
159
This function is used to initialize a lex object on the
160
stack for use by fix_fields and for parsing. In order to
161
work properly it also needs to initialize the
162
Name_resolution_context object of the lexer.
163
Finally it needs to set a couple of variables to ensure
164
proper functioning of fix_fields.
168
init_lex_with_single_table(THD *thd, TABLE *table, LEX *lex)
170
TABLE_LIST *table_list;
171
Table_ident *table_ident;
172
SELECT_LEX *select_lex= &lex->select_lex;
173
Name_resolution_context *context= &select_lex->context;
175
We will call the parser to create a part_info struct based on the
176
partition string stored in the frm file.
177
We will use a local lex object for this purpose. However we also
178
need to set the Name_resolution_object for this lex object. We
179
do this by using add_table_to_list where we add the table that
180
we're working with to the Name_resolution_context.
185
if ((!(table_ident= new Table_ident(thd,
186
table->s->table_name,
187
table->s->db, TRUE))) ||
188
(!(table_list= select_lex->add_table_to_list(thd,
193
context->resolve_in_table_list_only(table_list);
194
lex->use_only_table_context= TRUE;
195
lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VCOL_EXPR;
196
select_lex->cur_pos_in_select_list= UNDEF_POS;
197
table->map= 1; //To ensure correct calculation of const item
198
table->get_fields_in_item_tree= TRUE;
199
table_list->table= table;
204
End use of local lex with single table
207
end_lex_with_single_table()
208
@param thd The thread object
209
@param table The table object
210
@param old_lex The real lex object connected to THD
213
This function restores the real lex object after calling
214
init_lex_with_single_table and also restores some table
215
variables temporarily set.
219
end_lex_with_single_table(THD *thd, TABLE *table, LEX *old_lex)
223
table->get_fields_in_item_tree= FALSE;
230
st_parsing_options::reset()
232
allows_variable= TRUE;
233
allows_select_into= TRUE;
234
allows_select_procedure= TRUE;
235
allows_derived= TRUE;
240
Perform initialization of Lex_input_stream instance.
242
Basically, a buffer for pre-processed query. This buffer should be large
243
enough to keep multi-statement query. The allocation is done once in
244
Lex_input_stream::init() in order to prevent memory pollution when
245
the server is processing large multi-statement queries.
248
bool Lex_input_stream::init(THD *thd,
252
DBUG_EXECUTE_IF("bug42064_simulate_oom",
253
DBUG_SET("+d,simulate_out_of_memory"););
255
m_cpp_buf= (char*) thd->alloc(length + 1);
257
DBUG_EXECUTE_IF("bug42064_simulate_oom",
258
DBUG_SET("-d,bug42064_simulate_oom"););
260
if (m_cpp_buf == NULL)
271
Prepare Lex_input_stream instance state for use for handling next SQL statement.
273
It should be called between two statements in a multi-statement query.
274
The operation resets the input stream to the beginning-of-parse state,
275
but does not reallocate m_cpp_buf.
279
Lex_input_stream::reset(char *buffer, unsigned int length)
285
lookahead_yylval= NULL;
289
m_end_of_query= buffer + length;
290
m_tok_start_prev= NULL;
292
m_buf_length= length;
294
m_cpp_tok_start= NULL;
295
m_cpp_tok_start_prev= NULL;
298
m_cpp_utf8_processed_ptr= NULL;
299
next_state= MY_LEX_START;
300
found_semicolon= NULL;
301
ignore_space= test(m_thd->variables.sql_mode & MODE_IGNORE_SPACE);
302
stmt_prepare_mode= FALSE;
303
multi_statements= TRUE;
304
in_comment=NO_COMMENT;
305
m_underscore_cs= NULL;
306
m_cpp_ptr= m_cpp_buf;
311
The operation is called from the parser in order to
312
1) designate the intention to have utf8 body;
313
1) Indicate to the lexer that we will need a utf8 representation of this
315
2) Determine the beginning of the body.
317
@param thd Thread context.
318
@param begin_ptr Pointer to the start of the body in the pre-processed
322
void Lex_input_stream::body_utf8_start(THD *thd, const char *begin_ptr)
324
DBUG_ASSERT(begin_ptr);
325
DBUG_ASSERT(m_cpp_buf <= begin_ptr && begin_ptr <= m_cpp_buf + m_buf_length);
327
uint body_utf8_length=
328
(m_buf_length / thd->variables.character_set_client->mbminlen) *
329
my_charset_utf8_bin.mbmaxlen;
331
m_body_utf8= (char *) thd->alloc(body_utf8_length + 1);
332
m_body_utf8_ptr= m_body_utf8;
335
m_cpp_utf8_processed_ptr= begin_ptr;
339
@brief The operation appends unprocessed part of pre-processed buffer till
340
the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to end_ptr.
342
The idea is that some tokens in the pre-processed buffer (like character
343
set introducers) should be skipped.
346
CPP buffer: SELECT 'str1', _latin1 'str2';
347
m_cpp_utf8_processed_ptr -- points at the "SELECT ...";
348
In order to skip "_latin1", the following call should be made:
349
body_utf8_append(<pointer to "_latin1 ...">, <pointer to " 'str2'...">)
351
@param ptr Pointer in the pre-processed buffer, which specifies the
352
end of the chunk, which should be appended to the utf8
354
@param end_ptr Pointer in the pre-processed buffer, to which
355
m_cpp_utf8_processed_ptr will be set in the end of the
359
void Lex_input_stream::body_utf8_append(const char *ptr,
362
DBUG_ASSERT(m_cpp_buf <= ptr && ptr <= m_cpp_buf + m_buf_length);
363
DBUG_ASSERT(m_cpp_buf <= end_ptr && end_ptr <= m_cpp_buf + m_buf_length);
368
if (m_cpp_utf8_processed_ptr >= ptr)
371
int bytes_to_copy= ptr - m_cpp_utf8_processed_ptr;
373
memcpy(m_body_utf8_ptr, m_cpp_utf8_processed_ptr, bytes_to_copy);
374
m_body_utf8_ptr += bytes_to_copy;
377
m_cpp_utf8_processed_ptr= end_ptr;
381
The operation appends unprocessed part of the pre-processed buffer till
382
the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to ptr.
384
@param ptr Pointer in the pre-processed buffer, which specifies the end
385
of the chunk, which should be appended to the utf8 body.
388
void Lex_input_stream::body_utf8_append(const char *ptr)
390
body_utf8_append(ptr, ptr);
394
The operation converts the specified text literal to the utf8 and appends
395
the result to the utf8-body.
397
@param thd Thread context.
398
@param txt Text literal.
399
@param txt_cs Character set of the text literal.
400
@param end_ptr Pointer in the pre-processed buffer, to which
401
m_cpp_utf8_processed_ptr will be set in the end of the
405
void Lex_input_stream::body_utf8_append_literal(THD *thd,
406
const LEX_STRING *txt,
407
CHARSET_INFO *txt_cs,
410
if (!m_cpp_utf8_processed_ptr)
415
if (!my_charset_same(txt_cs, &my_charset_utf8_general_ci))
417
thd->convert_string(&utf_txt,
418
&my_charset_utf8_general_ci,
419
txt->str, (uint) txt->length,
424
utf_txt.str= txt->str;
425
utf_txt.length= txt->length;
428
/* NOTE: utf_txt.length is in bytes, not in symbols. */
430
memcpy(m_body_utf8_ptr, utf_txt.str, utf_txt.length);
431
m_body_utf8_ptr += utf_txt.length;
434
m_cpp_utf8_processed_ptr= end_ptr;
439
This is called before every query that is to be parsed.
440
Because of this, it's critical to not do too much things here.
441
(We already do too much here)
444
void lex_start(THD *thd)
447
DBUG_ENTER("lex_start");
449
lex->thd= lex->unit.thd= thd;
451
lex->context_stack.empty();
452
lex->unit.init_query();
453
lex->unit.init_select();
454
/* 'parent_lex' is used in init_query() so it must be before it. */
455
lex->select_lex.parent_lex= lex;
456
lex->select_lex.init_query();
457
lex->value_list.empty();
458
lex->update_list.empty();
459
lex->set_var_list.empty();
460
lex->param_list.empty();
461
lex->view_list.empty();
462
lex->prepared_stmt_params.empty();
463
lex->auxiliary_table_list.empty();
464
lex->unit.next= lex->unit.master=
465
lex->unit.link_next= lex->unit.return_to= 0;
466
lex->unit.prev= lex->unit.link_prev= 0;
467
lex->unit.slave= lex->unit.global_parameters= lex->current_select=
468
lex->all_selects_list= &lex->select_lex;
469
lex->select_lex.master= &lex->unit;
470
lex->select_lex.prev= &lex->unit.slave;
471
lex->select_lex.link_next= lex->select_lex.slave= lex->select_lex.next= 0;
472
lex->select_lex.link_prev= (st_select_lex_node**)&(lex->all_selects_list);
473
lex->select_lex.options= 0;
474
lex->select_lex.sql_cache= SELECT_LEX::SQL_CACHE_UNSPECIFIED;
475
lex->select_lex.init_order();
476
lex->select_lex.group_list.empty();
477
if (lex->select_lex.group_list_ptrs)
478
lex->select_lex.group_list_ptrs->clear();
480
lex->subqueries= FALSE;
481
lex->context_analysis_only= 0;
482
lex->derived_tables= 0;
483
lex->safe_to_cache_query= 1;
484
lex->parsing_options.reset();
485
lex->empty_field_list_on_rset= 0;
486
lex->select_lex.select_number= 1;
489
lex->select_lex.in_sum_expr=0;
490
lex->select_lex.ftfunc_list_alloc.empty();
491
lex->select_lex.ftfunc_list= &lex->select_lex.ftfunc_list_alloc;
492
lex->select_lex.group_list.empty();
493
lex->select_lex.order_list.empty();
494
lex->duplicates= DUP_ERROR;
500
lex->proc_list.first= 0;
501
lex->escape_used= FALSE;
502
lex->query_tables= 0;
503
lex->reset_query_tables_list(FALSE);
504
lex->expr_allows_subselect= TRUE;
505
lex->use_only_table_context= FALSE;
506
lex->parse_vcol_expr= FALSE;
510
lex->event_parse_data= NULL;
511
lex->profile_options= PROFILE_NONE;
513
lex->select_lex.nest_level_base= &lex->unit;
514
lex->allow_sum_func= 0;
515
lex->in_sum_func= NULL;
517
ok, there must be a better solution for this, long-term
518
I tried "bzero" in the sql_yacc.yy code, but that for
519
some reason made the values zero, even if they were set
521
lex->server_options.server_name= 0;
522
lex->server_options.server_name_length= 0;
523
lex->server_options.host= 0;
524
lex->server_options.db= 0;
525
lex->server_options.username= 0;
526
lex->server_options.password= 0;
527
lex->server_options.scheme= 0;
528
lex->server_options.socket= 0;
529
lex->server_options.owner= 0;
530
lex->server_options.port= -1;
532
lex->is_lex_started= TRUE;
534
lex->reset_slave_info.all= false;
535
lex->limit_rows_examined= 0;
536
lex->limit_rows_examined_cnt= ULONGLONG_MAX;
540
void lex_end(LEX *lex)
542
DBUG_ENTER("lex_end");
543
DBUG_PRINT("enter", ("lex: 0x%lx", (long) lex));
545
/* release used plugins */
546
if (lex->plugins.elements) /* No function call and no mutex if no plugins. */
548
plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer,
549
lex->plugins.elements);
551
reset_dynamic(&lex->plugins);
561
Yacc_state::~Yacc_state()
570
static int find_keyword(Lex_input_stream *lip, uint len, bool function)
572
const char *tok= lip->get_tok_start();
574
SYMBOL *symbol= get_hash_symbol(tok, len, function);
577
lip->yylval->symbol.symbol=symbol;
578
lip->yylval->symbol.str= (char*) tok;
579
lip->yylval->symbol.length=len;
581
if ((symbol->tok == NOT_SYM) &&
582
(lip->m_thd->variables.sql_mode & MODE_HIGH_NOT_PRECEDENCE))
584
if ((symbol->tok == OR_OR_SYM) &&
585
!(lip->m_thd->variables.sql_mode & MODE_PIPES_AS_CONCAT))
594
Check if name is a keyword
598
name checked name (must not be empty)
599
len length of checked name
603
1 name isn't a keyword
606
bool is_keyword(const char *name, uint len)
608
DBUG_ASSERT(len != 0);
609
return get_hash_symbol(name,len,0)!=0;
613
Check if name is a sql function
615
@param name checked name
617
@return is this a native function or not
618
@retval 0 name is a function
619
@retval 1 name isn't a function
622
bool is_lex_native_function(const LEX_STRING *name)
624
DBUG_ASSERT(name != NULL);
625
return (get_hash_symbol(name->str, (uint) name->length, 1) != 0);
628
/* make a copy of token before ptr and set yytoklen */
630
static LEX_STRING get_token(Lex_input_stream *lip, uint skip, uint length)
633
lip->yyUnget(); // ptr points now after last token char
634
tmp.length=lip->yytoklen=length;
635
tmp.str= lip->m_thd->strmake(lip->get_tok_start() + skip, tmp.length);
637
lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
638
lip->m_cpp_text_end= lip->m_cpp_text_start + tmp.length;
645
There are no dangerous charsets in mysql for function
646
get_quoted_token yet. But it should be fixed in the
647
future to operate multichar strings (like ucs2)
650
static LEX_STRING get_quoted_token(Lex_input_stream *lip,
652
uint length, char quote)
655
const char *from, *end;
657
lip->yyUnget(); // ptr points now after last token char
658
tmp.length= lip->yytoklen=length;
659
tmp.str=(char*) lip->m_thd->alloc(tmp.length+1);
660
from= lip->get_tok_start() + skip;
664
lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
665
lip->m_cpp_text_end= lip->m_cpp_text_start + length;
669
if ((*to++= *from++) == quote)
671
from++; // Skip double quotes
672
lip->m_cpp_text_start++;
675
*to= 0; // End null for safety
681
Return an unescaped text literal without quotes
682
Fix sometimes to do only one scan of the string
685
static char *get_text(Lex_input_stream *lip, int pre_skip, int post_skip)
689
CHARSET_INFO *cs= lip->m_thd->charset();
692
sep= lip->yyGetLast(); // String should end with this
703
lip->get_end_of_query()))) {
704
lip->skip_binary(l-1);
710
!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))
711
{ // Escaped character
719
if (c == lip->yyGet()) // Check if two separators in a row
721
found_escape=1; // duplicate. Remember for delete
727
/* Found end. Unescape and return string */
728
const char *str, *end;
731
str= lip->get_tok_start();
733
/* Extract the text from the token */
736
DBUG_ASSERT(end >= str);
738
if (!(start= (char*) lip->m_thd->alloc((uint) (end-str)+1)))
739
return (char*) ""; // Sql_alloc has set error flag
741
lip->m_cpp_text_start= lip->get_cpp_tok_start() + pre_skip;
742
lip->m_cpp_text_end= lip->get_cpp_ptr() - post_skip;
746
lip->yytoklen=(uint) (end-str);
747
memcpy(start,str,lip->yytoklen);
748
start[lip->yytoklen]=0;
754
for (to=start ; str != end ; str++)
759
(l = my_ismbchar(cs, str, end))) {
766
if (!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
767
*str == '\\' && str+1 != end)
783
*to++= 0; // Ascii null
785
case 'Z': // ^Z must be escaped on Win32
790
*to++= '\\'; // remember prefix for wildcard
797
else if (*str == sep)
798
*to++= *str++; // Two ' or "
803
lip->yytoklen=(uint) (to-start);
808
return 0; // unexpected end of query
813
** Calc type of integer; long integer, longlong integer or real.
814
** Returns smallest type that match the string.
815
** When using unsigned long long values the result is converted to a real
816
** because else they will be unexpected sign changes because all calculation
817
** is done with longlong or double.
820
static const char *long_str="2147483647";
821
static const uint long_len=10;
822
static const char *signed_long_str="-2147483648";
823
static const char *longlong_str="9223372036854775807";
824
static const uint longlong_len=19;
825
static const char *signed_longlong_str="-9223372036854775808";
826
static const uint signed_longlong_len=19;
827
static const char *unsigned_longlong_str="18446744073709551615";
828
static const uint unsigned_longlong_len=20;
830
static inline uint int_token(const char *str,uint length)
832
if (length < long_len) // quick normal case
836
if (*str == '+') // Remove sign and pre-zeros
840
else if (*str == '-')
845
while (*str == '0' && length)
849
if (length < long_len)
856
if (length == long_len)
858
cmp= signed_long_str+1;
859
smaller=NUM; // If <= signed_long_str
860
bigger=LONG_NUM; // If >= signed_long_str
862
else if (length < signed_longlong_len)
864
else if (length > signed_longlong_len)
868
cmp=signed_longlong_str+1;
869
smaller=LONG_NUM; // If <= signed_longlong_str
875
if (length == long_len)
881
else if (length < longlong_len)
883
else if (length > longlong_len)
885
if (length > unsigned_longlong_len)
887
cmp=unsigned_longlong_str;
888
smaller=ULONGLONG_NUM;
895
bigger= ULONGLONG_NUM;
898
while (*cmp && *cmp++ == *str++) ;
899
return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
904
Given a stream that is advanced to the first contained character in
905
an open comment, consume the comment. Optionally, if we are allowed,
906
recurse so that we understand comments within this current comment.
908
At this level, we do not support version-condition comments. We might
909
have been called with having just passed one in the stream, though. In
910
that case, we probably want to tolerate mundane comments inside. Thus,
911
the case for recursion.
913
@retval Whether EOF reached before comment is closed.
915
bool consume_comment(Lex_input_stream *lip, int remaining_recursions_permitted)
922
if (remaining_recursions_permitted > 0)
924
if ((c == '/') && (lip->yyPeek() == '*'))
926
lip->yySkip(); /* Eat asterisk */
927
consume_comment(lip, remaining_recursions_permitted-1);
934
if (lip->yyPeek() == '/')
936
lip->yySkip(); /* Eat slash */
950
MYSQLlex remember the following states from the following MYSQLlex()
952
- MY_LEX_EOQ Found end of query
953
- MY_LEX_OPERATOR_OR_IDENT Last state was an ident, text or number
954
(which can't be followed by a signed number)
957
int MYSQLlex(void *arg, void *yythd)
959
THD *thd= (THD *)yythd;
960
Lex_input_stream *lip= & thd->m_parser_state->m_lip;
961
YYSTYPE *yylval=(YYSTYPE*) arg;
964
if (lip->lookahead_token >= 0)
967
The next token was already parsed in advance,
970
token= lip->lookahead_token;
971
lip->lookahead_token= -1;
972
*yylval= *(lip->lookahead_yylval);
973
lip->lookahead_yylval= NULL;
977
token= lex_one_token(arg, yythd);
982
Parsing 'WITH' 'ROLLUP' or 'WITH' 'CUBE' requires 2 look ups,
983
which makes the grammar LALR(2).
984
Replace by a single 'WITH_ROLLUP' or 'WITH_CUBE' token,
985
to transform the grammar into a LALR(1) grammar,
986
which sql_yacc.yy can process.
988
token= lex_one_token(arg, yythd);
991
return WITH_CUBE_SYM;
993
return WITH_ROLLUP_SYM;
996
Save the token following 'WITH'
998
lip->lookahead_yylval= lip->yylval;
1000
lip->lookahead_token= token;
1011
int lex_one_token(void *arg, void *yythd)
1014
bool comment_closed;
1015
int tokval, result_state;
1017
enum my_lex_states state;
1018
THD *thd= (THD *)yythd;
1019
Lex_input_stream *lip= & thd->m_parser_state->m_lip;
1021
YYSTYPE *yylval=(YYSTYPE*) arg;
1022
CHARSET_INFO *const cs= thd->charset();
1023
const uchar *const state_map= cs->state_map;
1024
const uchar *const ident_map= cs->ident_map;
1027
lip->yylval=yylval; // The global state
1030
state=lip->next_state;
1031
lip->next_state=MY_LEX_OPERATOR_OR_IDENT;
1035
case MY_LEX_OPERATOR_OR_IDENT: // Next is operator or keyword
1036
case MY_LEX_START: // Start of token
1037
// Skip starting whitespace
1038
while(state_map[c= lip->yyPeek()] == MY_LEX_SKIP)
1046
/* Start of real token */
1047
lip->restart_token();
1049
state= (enum my_lex_states) state_map[c];
1052
if (lip->yyGet() == 'N')
1053
{ // Allow \N as shortcut for NULL
1054
yylval->lex_str.str=(char*) "\\N";
1055
yylval->lex_str.length=2;
1059
case MY_LEX_CHAR: // Unknown or single char token
1060
case MY_LEX_SKIP: // This should not happen
1062
lip->next_state= MY_LEX_START; // Allow signed numbers
1065
case MY_LEX_MINUS_OR_COMMENT:
1066
if (lip->yyPeek() == '-' &&
1067
(my_isspace(cs,lip->yyPeekn(1)) ||
1068
my_iscntrl(cs,lip->yyPeekn(1))))
1070
state=MY_LEX_COMMENT;
1073
lip->next_state= MY_LEX_START; // Allow signed numbers
1076
case MY_LEX_PLACEHOLDER:
1078
Check for a placeholder: it should not precede a possible identifier
1079
because of binlogging: when a placeholder is replaced with
1080
its value in a query for the binlog, the query must stay
1081
grammatically correct.
1083
lip->next_state= MY_LEX_START; // Allow signed numbers
1084
if (lip->stmt_prepare_mode && !ident_map[(uchar) lip->yyPeek()])
1085
return(PARAM_MARKER);
1089
lip->next_state= MY_LEX_START; // Allow signed numbers
1092
This is a work around, to make the "remember_name" rule in
1093
sql/sql_yacc.yy work properly.
1094
The problem is that, when parsing "select expr1, expr2",
1095
the code generated by bison executes the *pre* action
1096
remember_name (see select_item) *before* actually parsing the
1097
first token of expr2.
1099
lip->restart_token();
1102
case MY_LEX_IDENT_OR_NCHAR:
1103
if (lip->yyPeek() != '\'')
1105
state= MY_LEX_IDENT;
1108
/* Found N'string' */
1109
lip->yySkip(); // Skip '
1110
if (!(yylval->lex_str.str = get_text(lip, 2, 1)))
1112
state= MY_LEX_CHAR; // Read char by char
1115
yylval->lex_str.length= lip->yytoklen;
1116
lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
1117
return(NCHAR_STRING);
1119
case MY_LEX_IDENT_OR_HEX:
1120
if (lip->yyPeek() == '\'')
1121
{ // Found x'hex-number'
1122
state= MY_LEX_HEX_NUMBER;
1125
case MY_LEX_IDENT_OR_BIN:
1126
if (lip->yyPeek() == '\'')
1127
{ // Found b'bin-number'
1128
state= MY_LEX_BIN_NUMBER;
1133
#if defined(USE_MB) && defined(USE_MB_IDENT)
1136
result_state= IDENT_QUOTED;
1137
if (my_mbcharlen(cs, lip->yyGetLast()) > 1)
1139
int l = my_ismbchar(cs,
1141
lip->get_end_of_query());
1143
state = MY_LEX_CHAR;
1146
lip->skip_binary(l - 1);
1148
while (ident_map[c=lip->yyGet()])
1150
if (my_mbcharlen(cs, c) > 1)
1153
if ((l = my_ismbchar(cs,
1155
lip->get_end_of_query())) == 0)
1157
lip->skip_binary(l-1);
1164
for (result_state= c;
1165
ident_map[(uchar) (c= lip->yyGet())];
1168
/* If there were non-ASCII characters, mark that we must convert */
1169
result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1171
length= lip->yyLength();
1172
start= lip->get_ptr();
1173
if (lip->ignore_space)
1176
If we find a space then this can't be an identifier. We notice this
1177
below by checking start != lex->ptr.
1179
for (; state_map[(uchar) c] == MY_LEX_SKIP ; c= lip->yyGet())
1182
if (start == lip->get_ptr() && c == '.' &&
1183
ident_map[(uchar) lip->yyPeek()])
1184
lip->next_state=MY_LEX_IDENT_SEP;
1186
{ // '(' must follow directly if function
1188
if ((tokval = find_keyword(lip, length, c == '(')))
1190
lip->next_state= MY_LEX_START; // Allow signed numbers
1191
return(tokval); // Was keyword
1193
lip->yySkip(); // next state does a unget
1195
yylval->lex_str=get_token(lip, 0, length);
1198
Note: "SELECT _bla AS 'alias'"
1199
_bla should be considered as a IDENT if charset haven't been found.
1200
So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
1204
if (yylval->lex_str.str[0] == '_')
1206
CHARSET_INFO *cs= get_charset_by_csname(yylval->lex_str.str + 1,
1207
MY_CS_PRIMARY, MYF(0));
1210
yylval->charset= cs;
1211
lip->m_underscore_cs= cs;
1213
lip->body_utf8_append(lip->m_cpp_text_start,
1214
lip->get_cpp_tok_start() + length);
1215
return(UNDERSCORE_CHARSET);
1219
lip->body_utf8_append(lip->m_cpp_text_start);
1221
lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1222
lip->m_cpp_text_end);
1224
return(result_state); // IDENT or IDENT_QUOTED
1226
case MY_LEX_IDENT_SEP: // Found ident and now '.'
1227
yylval->lex_str.str= (char*) lip->get_ptr();
1228
yylval->lex_str.length= 1;
1229
c= lip->yyGet(); // should be '.'
1230
lip->next_state= MY_LEX_IDENT_START; // Next is ident (not keyword)
1231
if (!ident_map[(uchar) lip->yyPeek()]) // Probably ` or "
1232
lip->next_state= MY_LEX_START;
1235
case MY_LEX_NUMBER_IDENT: // number or ident which num-start
1236
if (lip->yyGetLast() == '0')
1241
while (my_isxdigit(cs,(c = lip->yyGet()))) ;
1242
if ((lip->yyLength() >= 3) && !ident_map[c])
1245
yylval->lex_str=get_token(lip, 2, lip->yyLength()-2);
1249
state= MY_LEX_IDENT_START;
1254
while ((c= lip->yyGet()) == '0' || c == '1')
1256
if ((lip->yyLength() >= 3) && !ident_map[c])
1259
yylval->lex_str= get_token(lip, 2, lip->yyLength()-2);
1263
state= MY_LEX_IDENT_START;
1269
while (my_isdigit(cs, (c = lip->yyGet()))) ;
1271
{ // Can't be identifier
1272
state=MY_LEX_INT_OR_REAL;
1275
if (c == 'e' || c == 'E')
1277
// The following test is written this way to allow numbers of type 1e1
1278
if (my_isdigit(cs,lip->yyPeek()) ||
1279
(c=(lip->yyGet())) == '+' || c == '-')
1281
if (my_isdigit(cs,lip->yyPeek())) // Number must have digit after sign
1284
while (my_isdigit(cs,lip->yyGet())) ;
1285
yylval->lex_str=get_token(lip, 0, lip->yyLength());
1292
case MY_LEX_IDENT_START: // We come here after '.'
1293
result_state= IDENT;
1294
#if defined(USE_MB) && defined(USE_MB_IDENT)
1297
result_state= IDENT_QUOTED;
1298
while (ident_map[c=lip->yyGet()])
1300
if (my_mbcharlen(cs, c) > 1)
1303
if ((l = my_ismbchar(cs,
1305
lip->get_end_of_query())) == 0)
1307
lip->skip_binary(l-1);
1314
for (result_state=0; ident_map[c= lip->yyGet()]; result_state|= c)
1316
/* If there were non-ASCII characters, mark that we must convert */
1317
result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1319
if (c == '.' && ident_map[(uchar) lip->yyPeek()])
1320
lip->next_state=MY_LEX_IDENT_SEP;// Next is '.'
1322
yylval->lex_str= get_token(lip, 0, lip->yyLength());
1324
lip->body_utf8_append(lip->m_cpp_text_start);
1326
lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1327
lip->m_cpp_text_end);
1329
return(result_state);
1331
case MY_LEX_USER_VARIABLE_DELIMITER: // Found quote char
1333
uint double_quotes= 0;
1334
char quote_char= c; // Used char
1335
while ((c=lip->yyGet()))
1338
if ((var_length= my_mbcharlen(cs, c)) == 1)
1340
if (c == quote_char)
1342
if (lip->yyPeek() != quote_char)
1350
else if (use_mb(cs))
1352
if ((var_length= my_ismbchar(cs, lip->get_ptr() - 1,
1353
lip->get_end_of_query())))
1354
lip->skip_binary(var_length-1);
1359
yylval->lex_str=get_quoted_token(lip, 1,
1360
lip->yyLength() - double_quotes -1,
1363
yylval->lex_str=get_token(lip, 1, lip->yyLength() -1);
1364
if (c == quote_char)
1365
lip->yySkip(); // Skip end `
1366
lip->next_state= MY_LEX_START;
1368
lip->body_utf8_append(lip->m_cpp_text_start);
1370
lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1371
lip->m_cpp_text_end);
1373
return(IDENT_QUOTED);
1375
case MY_LEX_INT_OR_REAL: // Complete int or incomplete real
1377
{ // Found complete integer number.
1378
yylval->lex_str=get_token(lip, 0, lip->yyLength());
1379
return int_token(yylval->lex_str.str, (uint) yylval->lex_str.length);
1382
case MY_LEX_REAL: // Incomplete real number
1383
while (my_isdigit(cs,c = lip->yyGet())) ;
1385
if (c == 'e' || c == 'E')
1388
if (c == '-' || c == '+')
1389
c = lip->yyGet(); // Skip sign
1390
if (!my_isdigit(cs,c))
1391
{ // No digit after sign
1395
while (my_isdigit(cs,lip->yyGet())) ;
1396
yylval->lex_str=get_token(lip, 0, lip->yyLength());
1399
yylval->lex_str=get_token(lip, 0, lip->yyLength());
1400
return(DECIMAL_NUM);
1402
case MY_LEX_HEX_NUMBER: // Found x'hexstring'
1403
lip->yySkip(); // Accept opening '
1404
while (my_isxdigit(cs, (c= lip->yyGet()))) ;
1406
return(ABORT_SYM); // Illegal hex constant
1407
lip->yySkip(); // Accept closing '
1408
length= lip->yyLength(); // Length of hexnum+3
1409
if ((length % 2) == 0)
1410
return(ABORT_SYM); // odd number of hex digits
1411
yylval->lex_str=get_token(lip,
1413
length-3); // don't count x' and last '
1416
case MY_LEX_BIN_NUMBER: // Found b'bin-string'
1417
lip->yySkip(); // Accept opening '
1418
while ((c= lip->yyGet()) == '0' || c == '1')
1421
return(ABORT_SYM); // Illegal hex constant
1422
lip->yySkip(); // Accept closing '
1423
length= lip->yyLength(); // Length of bin-num + 3
1424
yylval->lex_str= get_token(lip,
1426
length-3); // don't count b' and last '
1429
case MY_LEX_CMP_OP: // Incomplete comparison operator
1430
if (state_map[(uchar) lip->yyPeek()] == MY_LEX_CMP_OP ||
1431
state_map[(uchar) lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
1433
if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
1435
lip->next_state= MY_LEX_START; // Allow signed numbers
1438
state = MY_LEX_CHAR; // Something fishy found
1441
case MY_LEX_LONG_CMP_OP: // Incomplete comparison operator
1442
if (state_map[(uchar) lip->yyPeek()] == MY_LEX_CMP_OP ||
1443
state_map[(uchar) lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
1446
if (state_map[(uchar) lip->yyPeek()] == MY_LEX_CMP_OP)
1449
if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
1451
lip->next_state= MY_LEX_START; // Found long op
1454
state = MY_LEX_CHAR; // Something fishy found
1458
if (c != lip->yyPeek())
1464
tokval = find_keyword(lip,2,0); // Is a bool operator
1465
lip->next_state= MY_LEX_START; // Allow signed numbers
1468
case MY_LEX_STRING_OR_DELIMITER:
1469
if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
1471
state= MY_LEX_USER_VARIABLE_DELIMITER;
1474
/* " used for strings */
1475
case MY_LEX_STRING: // Incomplete text string
1476
if (!(yylval->lex_str.str = get_text(lip, 1, 1)))
1478
state= MY_LEX_CHAR; // Read char by char
1481
yylval->lex_str.length=lip->yytoklen;
1483
lip->body_utf8_append(lip->m_cpp_text_start);
1485
lip->body_utf8_append_literal(thd, &yylval->lex_str,
1486
lip->m_underscore_cs ? lip->m_underscore_cs : cs,
1487
lip->m_cpp_text_end);
1489
lip->m_underscore_cs= NULL;
1491
lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
1492
return(TEXT_STRING);
1494
case MY_LEX_COMMENT: // Comment
1495
lex->select_lex.options|= OPTION_FOUND_COMMENT;
1496
while ((c = lip->yyGet()) != '\n' && c) ;
1497
lip->yyUnget(); // Safety against eof
1498
state = MY_LEX_START; // Try again
1500
case MY_LEX_LONG_COMMENT: /* Long C comment? */
1501
if (lip->yyPeek() != '*')
1503
state=MY_LEX_CHAR; // Probable division
1506
lex->select_lex.options|= OPTION_FOUND_COMMENT;
1507
/* Reject '/' '*', since we might need to turn off the echo */
1510
lip->save_in_comment_state();
1512
if (lip->yyPeekn(2) == 'M' && lip->yyPeekn(3) == '!')
1514
/* Skip MariaDB unique marker */
1515
lip->set_echo(FALSE);
1517
/* The following if will be true */
1519
if (lip->yyPeekn(2) == '!')
1521
lip->in_comment= DISCARD_COMMENT;
1522
/* Accept '/' '*' '!', but do not keep this marker. */
1523
lip->set_echo(FALSE);
1527
The special comment format is very strict:
1528
'/' '*' '!', followed by an optional 'M' and exactly
1529
1 digit (major), 2 digits (minor), then 2 digits (dot).
1534
if ( my_isdigit(cs, lip->yyPeekn(0))
1535
&& my_isdigit(cs, lip->yyPeekn(1))
1536
&& my_isdigit(cs, lip->yyPeekn(2))
1537
&& my_isdigit(cs, lip->yyPeekn(3))
1538
&& my_isdigit(cs, lip->yyPeekn(4))
1542
char *end_ptr= (char*) lip->get_ptr()+5;
1544
version= (ulong) my_strtoll10(lip->get_ptr(), &end_ptr, &error);
1546
if (version <= MYSQL_VERSION_ID)
1548
/* Accept 'M' 'm' 'm' 'd' 'd' */
1550
/* Expand the content of the special comment as real code */
1551
lip->set_echo(TRUE);
1553
break; /* Do not treat contents as a comment. */
1558
Patch and skip the conditional comment to avoid it
1559
being propagated infinitely (eg. to a slave).
1561
char *pcom= lip->yyUnput(' ');
1562
comment_closed= ! consume_comment(lip, 1);
1563
if (! comment_closed)
1567
/* version allowed to have one level of comment inside. */
1572
/* Not a version comment. */
1574
lip->set_echo(TRUE);
1580
lip->in_comment= PRESERVE_COMMENT;
1581
lip->yySkip(); // Accept /
1582
lip->yySkip(); // Accept *
1583
comment_closed= ! consume_comment(lip, 0);
1584
/* regular comments can have zero comments inside. */
1588
- regular '/' '*' comments,
1589
- special comments '/' '*' '!' for a future version,
1590
by scanning until we find a closing '*' '/' marker.
1592
Nesting regular comments isn't allowed. The first
1593
'*' '/' returns the parser to the previous state.
1595
/#!VERSI oned containing /# regular #/ is allowed #/
1597
Inside one versioned comment, another versioned comment
1598
is treated as a regular discardable comment. It gets
1602
/* Unbalanced comments with a missing '*' '/' are a syntax error */
1603
if (! comment_closed)
1605
state = MY_LEX_START; // Try again
1606
lip->restore_in_comment_state();
1608
case MY_LEX_END_LONG_COMMENT:
1609
if ((lip->in_comment != NO_COMMENT) && lip->yyPeek() == '/')
1611
/* Reject '*' '/' */
1613
/* Accept '*' '/', with the proper echo */
1614
lip->set_echo(lip->in_comment == PRESERVE_COMMENT);
1616
/* And start recording the tokens again */
1617
lip->set_echo(TRUE);
1618
lip->in_comment=NO_COMMENT;
1622
state=MY_LEX_CHAR; // Return '*'
1624
case MY_LEX_SET_VAR: // Check if ':='
1625
if (lip->yyPeek() != '=')
1627
state=MY_LEX_CHAR; // Return ':'
1632
case MY_LEX_SEMICOLON: // optional line terminator
1633
state= MY_LEX_CHAR; // Return ';'
1638
lip->yyUnget(); // Reject the last '\0'
1639
lip->set_echo(FALSE);
1641
lip->set_echo(TRUE);
1642
/* Unbalanced comments with a missing '*' '/' are a syntax error */
1643
if (lip->in_comment != NO_COMMENT)
1645
lip->next_state=MY_LEX_END; // Mark for next loop
1646
return(END_OF_INPUT);
1651
lip->next_state=MY_LEX_END;
1652
return(0); // We found end of input last time
1654
/* Actually real shouldn't start with . but allow them anyhow */
1655
case MY_LEX_REAL_OR_POINT:
1656
if (my_isdigit(cs,lip->yyPeek()))
1657
state = MY_LEX_REAL; // Real
1660
state= MY_LEX_IDENT_SEP; // return '.'
1661
lip->yyUnget(); // Put back '.'
1664
case MY_LEX_USER_END: // end '@' of user@hostname
1665
switch (state_map[(uchar) lip->yyPeek()]) {
1667
case MY_LEX_USER_VARIABLE_DELIMITER:
1668
case MY_LEX_STRING_OR_DELIMITER:
1670
case MY_LEX_USER_END:
1671
lip->next_state=MY_LEX_SYSTEM_VAR;
1674
lip->next_state=MY_LEX_HOSTNAME;
1677
yylval->lex_str.str=(char*) lip->get_ptr();
1678
yylval->lex_str.length=1;
1680
case MY_LEX_HOSTNAME: // end '@' of user@hostname
1681
for (c=lip->yyGet() ;
1682
my_isalnum(cs,c) || c == '.' || c == '_' || c == '$';
1684
yylval->lex_str=get_token(lip, 0, lip->yyLength());
1685
return(LEX_HOSTNAME);
1686
case MY_LEX_SYSTEM_VAR:
1687
yylval->lex_str.str=(char*) lip->get_ptr();
1688
yylval->lex_str.length=1;
1689
lip->yySkip(); // Skip '@'
1690
lip->next_state= (state_map[(uchar) lip->yyPeek()] ==
1691
MY_LEX_USER_VARIABLE_DELIMITER ?
1692
MY_LEX_OPERATOR_OR_IDENT :
1693
MY_LEX_IDENT_OR_KEYWORD);
1695
case MY_LEX_IDENT_OR_KEYWORD:
1697
We come here when we have found two '@' in a row.
1698
We should now be able to handle:
1699
[(global | local | session) .]variable_name
1702
for (result_state= 0; ident_map[c= lip->yyGet()]; result_state|= c)
1704
/* If there were non-ASCII characters, mark that we must convert */
1705
result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1708
lip->next_state=MY_LEX_IDENT_SEP;
1709
length= lip->yyLength();
1711
return(ABORT_SYM); // Names must be nonempty.
1712
if ((tokval= find_keyword(lip, length,0)))
1714
lip->yyUnget(); // Put back 'c'
1715
return(tokval); // Was keyword
1717
yylval->lex_str=get_token(lip, 0, length);
1719
lip->body_utf8_append(lip->m_cpp_text_start);
1721
lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1722
lip->m_cpp_text_end);
1724
return(result_state);
1731
Construct a copy of this object to be used for mysql_alter_table
1732
and mysql_create_table.
1734
Historically, these two functions modify their Alter_info
1735
arguments. This behaviour breaks re-execution of prepared
1736
statements and stored procedures and is compensated by always
1737
supplying a copy of Alter_info to these functions.
1739
@return You need to use check the error in THD for out
1740
of memory condition after calling this function.
1743
Alter_info::Alter_info(const Alter_info &rhs, MEM_ROOT *mem_root)
1744
:drop_list(rhs.drop_list, mem_root),
1745
alter_list(rhs.alter_list, mem_root),
1746
key_list(rhs.key_list, mem_root),
1747
create_list(rhs.create_list, mem_root),
1749
keys_onoff(rhs.keys_onoff),
1750
tablespace_op(rhs.tablespace_op),
1751
partition_names(rhs.partition_names, mem_root),
1752
num_parts(rhs.num_parts),
1753
change_level(rhs.change_level),
1754
datetime_field(rhs.datetime_field),
1755
error_if_not_empty(rhs.error_if_not_empty)
1758
Make deep copies of used objects.
1759
This is not a fully deep copy - clone() implementations
1760
of Alter_drop, Alter_column, Key, foreign_key, Key_part_spec
1761
do not copy string constants. At the same length the only
1762
reason we make a copy currently is that ALTER/CREATE TABLE
1763
code changes input Alter_info definitions, but string
1764
constants never change.
1766
list_copy_and_replace_each_value(drop_list, mem_root);
1767
list_copy_and_replace_each_value(alter_list, mem_root);
1768
list_copy_and_replace_each_value(key_list, mem_root);
1769
list_copy_and_replace_each_value(create_list, mem_root);
1770
/* partition_names are not deeply copied currently */
1774
void trim_whitespace(CHARSET_INFO *cs, LEX_STRING *str)
1778
This code assumes that there are no multi-bytes characters
1779
that can be considered white-space.
1782
while ((str->length > 0) && (my_isspace(cs, str->str[0])))
1790
Also, parsing backward is not safe with multi bytes characters
1792
while ((str->length > 0) && (my_isspace(cs, str->str[str->length-1])))
1800
st_select_lex structures initialisations
1803
void st_select_lex_node::init_query()
1806
sql_cache= SQL_CACHE_UNSPECIFIED;
1807
linkage= UNSPECIFIED_TYPE;
1808
no_table_names_allowed= 0;
1812
void st_select_lex_node::init_select()
1816
void st_select_lex_unit::init_query()
1818
st_select_lex_node::init_query();
1819
linkage= GLOBAL_OPTIONS_TYPE;
1820
global_parameters= first_select();
1821
select_limit_cnt= HA_POS_ERROR;
1822
offset_limit_cnt= 0;
1824
prepared= optimized= executed= 0;
1832
found_rows_for_union= 0;
1833
insert_table_with_stored_vcol= 0;
1837
void st_select_lex::init_query()
1839
st_select_lex_node::init_query();
1841
top_join_list.empty();
1842
join_list= &top_join_list;
1844
leaf_tables_prep.empty();
1845
leaf_tables.empty();
1848
having= prep_having= where= prep_where= 0;
1849
olap= UNSPECIFIED_OLAP_TYPE;
1850
having_fix_field= 0;
1851
context.select_lex= this;
1854
Add the name resolution context of the current (sub)query to the
1855
stack of contexts for the whole query.
1857
push_context may return an error if there is no memory for a new
1858
element in the stack, however this method has no return value,
1859
thus push_context should be moved to a place where query
1860
initialization is checked for failure.
1862
parent_lex->push_context(&context);
1863
cond_count= between_count= with_wild= 0;
1865
ref_pointer_array= 0;
1866
ref_pointer_array_size= 0;
1867
select_n_where_fields= 0;
1868
select_n_having_items= 0;
1870
n_child_sum_items= 0;
1871
subquery_in_having= explicit_limit= 0;
1872
is_item_list_lookup= 0;
1874
first_natural_join_processing= 1;
1875
first_cond_optimization= 1;
1876
parsing_place= NO_MATTER;
1877
exclude_from_table_unique_test= no_wrap_view_item= FALSE;
1880
is_prep_leaf_list_saved= FALSE;
1881
bzero((char*) expr_cache_may_be_used, sizeof(expr_cache_may_be_used));
1882
m_non_agg_field_used= false;
1883
m_agg_func_used= false;
1886
void st_select_lex::init_select()
1888
st_select_lex_node::init_select();
1890
sj_subselects.empty();
1892
if (group_list_ptrs)
1893
group_list_ptrs->clear();
1896
table_join_options= 0;
1897
in_sum_expr= with_wild= 0;
1899
sql_cache= SQL_CACHE_UNSPECIFIED;
1901
interval_list.empty();
1902
ftfunc_list_alloc.empty();
1903
inner_sum_func_list= 0;
1904
ftfunc_list= &ftfunc_list_alloc;
1905
linkage= UNSPECIFIED_TYPE;
1906
order_list.elements= 0;
1907
order_list.first= 0;
1908
order_list.next= &order_list.first;
1909
/* Set limit and offset to default values */
1910
select_limit= 0; /* denotes the default limit = HA_POS_ERROR */
1911
offset_limit= 0; /* denotes the default offset = 0 */
1914
cur_pos_in_select_list= UNDEF_POS;
1915
non_agg_fields.empty();
1916
cond_value= having_value= Item::COND_UNDEF;
1917
inner_refs_list.empty();
1920
m_non_agg_field_used= false;
1921
m_agg_func_used= false;
1922
name_visibility_map= 0;
1926
st_select_lex structures linking
1929
/* include on level down */
1930
void st_select_lex_node::include_down(st_select_lex_node *upper)
1932
if ((next= upper->slave))
1934
prev= &upper->slave;
1941
void st_select_lex_node::add_slave(st_select_lex_node *slave_arg)
1943
for (; slave; slave= slave->next)
1944
if (slave == slave_arg)
1949
st_select_lex_node *slave_arg_slave= slave_arg->slave;
1950
/* Insert in the front of list of slaves if any. */
1951
slave_arg->include_neighbour(slave);
1952
/* include_neighbour() sets slave_arg->slave=0, restore it. */
1953
slave_arg->slave= slave_arg_slave;
1954
/* Count on include_neighbour() setting the master. */
1955
DBUG_ASSERT(slave_arg->master == this);
1960
slave_arg->master= this;
1966
include on level down (but do not link)
1969
st_select_lex_node::include_standalone()
1970
upper - reference on node underr which this node should be included
1971
ref - references on reference on this node
1973
void st_select_lex_node::include_standalone(st_select_lex_node *upper,
1974
st_select_lex_node **ref)
1982
/* include neighbour (on same level) */
1983
void st_select_lex_node::include_neighbour(st_select_lex_node *before)
1985
if ((next= before->next))
1987
prev= &before->next;
1989
master= before->master;
1993
/* including in global SELECT_LEX list */
1994
void st_select_lex_node::include_global(st_select_lex_node **plink)
1996
if ((link_next= *plink))
1997
link_next->link_prev= &link_next;
2002
//excluding from global list (internal function)
2003
void st_select_lex_node::fast_exclude()
2007
if ((*link_prev= link_next))
2008
link_next->link_prev= link_prev;
2010
// Remove slave structure
2011
for (; slave; slave= slave->next)
2012
slave->fast_exclude();
2018
Exclude a node from the tree lex structure, but leave it in the global
2022
void st_select_lex_node::exclude_from_tree()
2030
Exclude select_lex structure (except first (first select can't be
2031
deleted, because it is most upper select))
2033
void st_select_lex_node::exclude()
2035
/* exclude from global list */
2037
/* exclude from other structures */
2038
exclude_from_tree();
2040
We do not need following statements, because prev pointer of first
2041
list element point to master->slave
2042
if (master->slave == this)
2043
master->slave= next;
2049
Exclude level of current unit from tree of SELECTs
2052
st_select_lex_unit::exclude_level()
2054
NOTE: units which belong to current will be brought up on level of
2057
void st_select_lex_unit::exclude_level()
2059
SELECT_LEX_UNIT *units= 0, **units_last= &units;
2060
for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
2062
// unlink current level from global SELECTs list
2063
if (sl->link_prev && (*sl->link_prev= sl->link_next))
2064
sl->link_next->link_prev= sl->link_prev;
2066
// bring up underlay levels
2067
SELECT_LEX_UNIT **last= 0;
2068
for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
2071
last= (SELECT_LEX_UNIT**)&(u->next);
2075
(*units_last)= sl->first_inner_unit();
2081
// include brought up levels in place of current
2083
(*units_last)= (SELECT_LEX_UNIT*)next;
2085
next->prev= (SELECT_LEX_NODE**)units_last;
2090
// exclude currect unit from list of nodes
2099
Exclude subtree of current unit from tree of SELECTs
2102
st_select_lex_unit::exclude_tree()
2104
void st_select_lex_unit::exclude_tree()
2106
for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
2108
// unlink current level from global SELECTs list
2109
if (sl->link_prev && (*sl->link_prev= sl->link_next))
2110
sl->link_next->link_prev= sl->link_prev;
2112
// unlink underlay levels
2113
for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
2118
// exclude currect unit from list of nodes
2126
st_select_lex_node::mark_as_dependent mark all st_select_lex struct from
2127
this to 'last' as dependent
2130
last - pointer to last st_select_lex struct, before wich all
2131
st_select_lex have to be marked as dependent
2134
'last' should be reachable from this st_select_lex_node
2137
bool st_select_lex::mark_as_dependent(THD *thd, st_select_lex *last, Item *dependency)
2140
DBUG_ASSERT(this != last);
2143
Mark all selects from resolved to 1 before select where was
2144
found table as depended (of select where was found table)
2146
SELECT_LEX *s= this;
2149
if (!(s->uncacheable & UNCACHEABLE_DEPENDENT_GENERATED))
2151
// Select is dependent of outer select
2152
s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
2153
UNCACHEABLE_DEPENDENT_GENERATED;
2154
SELECT_LEX_UNIT *munit= s->master_unit();
2155
munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
2156
UNCACHEABLE_DEPENDENT_GENERATED;
2157
for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
2160
!(sl->uncacheable & (UNCACHEABLE_DEPENDENT_GENERATED |
2161
UNCACHEABLE_UNITED)))
2162
sl->uncacheable|= UNCACHEABLE_UNITED;
2166
Item_subselect *subquery_expr= s->master_unit()->item;
2167
if (subquery_expr && subquery_expr->mark_as_dependent(thd, last,
2170
} while ((s= s->outer_select()) != last && s != 0);
2171
is_correlated= TRUE;
2172
this->master_unit()->item->is_correlated= TRUE;
2176
bool st_select_lex_node::set_braces(bool value) { return 1; }
2177
bool st_select_lex_node::inc_in_sum_expr() { return 1; }
2178
uint st_select_lex_node::get_in_sum_expr() { return 0; }
2179
TABLE_LIST* st_select_lex_node::get_table_list() { return 0; }
2180
List<Item>* st_select_lex_node::get_item_list() { return 0; }
2181
TABLE_LIST *st_select_lex_node::add_table_to_list (THD *thd, Table_ident *table,
2183
ulong table_join_options,
2184
thr_lock_type flags,
2185
enum_mdl_type mdl_type,
2186
List<Index_hint> *hints,
2191
ulong st_select_lex_node::get_table_join_options()
2197
prohibit using LIMIT clause
2199
bool st_select_lex::test_limit()
2201
if (select_limit != 0)
2203
my_error(ER_NOT_SUPPORTED_YET, MYF(0),
2204
"LIMIT & IN/ALL/ANY/SOME subquery");
2211
st_select_lex_unit* st_select_lex_unit::master_unit()
2217
st_select_lex* st_select_lex_unit::outer_select()
2219
return (st_select_lex*) master;
2223
bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
2225
return add_to_list(thd, order_list, item, asc);
2229
bool st_select_lex::add_gorder_to_list(THD *thd, Item *item, bool asc)
2231
return add_to_list(thd, gorder_list, item, asc);
2234
bool st_select_lex::add_item_to_list(THD *thd, Item *item)
2236
DBUG_ENTER("st_select_lex::add_item_to_list");
2237
DBUG_PRINT("info", ("Item: 0x%lx", (long) item));
2238
DBUG_RETURN(item_list.push_back(item));
2242
bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
2244
return add_to_list(thd, group_list, item, asc);
2248
bool st_select_lex::add_ftfunc_to_list(Item_func_match *func)
2250
return !func || ftfunc_list->push_back(func); // end of memory?
2254
st_select_lex_unit* st_select_lex::master_unit()
2256
return (st_select_lex_unit*) master;
2260
st_select_lex* st_select_lex::outer_select()
2262
return (st_select_lex*) master->get_master();
2266
bool st_select_lex::set_braces(bool value)
2273
bool st_select_lex::inc_in_sum_expr()
2280
uint st_select_lex::get_in_sum_expr()
2286
TABLE_LIST* st_select_lex::get_table_list()
2288
return table_list.first;
2291
List<Item>* st_select_lex::get_item_list()
2296
ulong st_select_lex::get_table_join_options()
2298
return table_join_options;
2302
bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
2304
// find_order_in_list() may need some extra space, so multiply by two.
2305
order_group_num*= 2;
2308
We have to create array in prepared statement memory if it is a
2311
Query_arena *arena= thd->stmt_arena;
2312
const uint n_elems= (n_sum_items +
2314
item_list.elements +
2315
select_n_having_items +
2316
select_n_where_fields +
2317
order_group_num) * 5;
2318
if (ref_pointer_array != NULL)
2321
We need to take 'n_sum_items' into account when allocating the array,
2322
and this may actually increase during the optimization phase due to
2323
MIN/MAX rewrite in Item_in_subselect::single_value_transformer.
2324
In the usual case we can reuse the array from the prepare phase.
2325
If we need a bigger array, we must allocate a new one.
2327
if (ref_pointer_array_size >= n_elems)
2330
ref_pointer_array= static_cast<Item**>(arena->alloc(sizeof(Item*) * n_elems));
2331
if (ref_pointer_array != NULL)
2332
ref_pointer_array_size= n_elems;
2334
return ref_pointer_array == NULL;
2338
void st_select_lex_unit::print(String *str, enum_query_type query_type)
2340
bool union_all= !union_distinct;
2341
for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
2343
if (sl != first_select())
2345
str->append(STRING_WITH_LEN(" union "));
2347
str->append(STRING_WITH_LEN("all "));
2348
else if (union_distinct == sl)
2353
sl->print(thd, str, query_type);
2357
if (fake_select_lex == global_parameters)
2359
if (fake_select_lex->order_list.elements)
2361
str->append(STRING_WITH_LEN(" order by "));
2362
fake_select_lex->print_order(str,
2363
fake_select_lex->order_list.first,
2366
fake_select_lex->print_limit(thd, str, query_type);
2371
void st_select_lex::print_order(String *str,
2373
enum_query_type query_type)
2375
for (; order; order= order->next)
2377
if (order->counter_used)
2379
if (query_type != QT_VIEW_INTERNAL)
2382
size_t length= my_snprintf(buffer, 20, "%d", order->counter);
2383
str->append(buffer, (uint) length);
2387
/* replace numeric reference with expression */
2388
if (order->item[0]->type() == Item::INT_ITEM &&
2389
order->item[0]->basic_const_item())
2392
size_t length= my_snprintf(buffer, 20, "%d", order->counter);
2393
str->append(buffer, (uint) length);
2394
/* make it expression instead of integer constant */
2395
str->append(STRING_WITH_LEN("+0"));
2398
(*order->item)->print(str, query_type);
2402
(*order->item)->print(str, query_type);
2404
str->append(STRING_WITH_LEN(" desc"));
2411
void st_select_lex::print_limit(THD *thd,
2413
enum_query_type query_type)
2415
SELECT_LEX_UNIT *unit= master_unit();
2416
Item_subselect *item= unit->item;
2418
if (item && unit->global_parameters == this)
2420
Item_subselect::subs_type subs_type= item->substype();
2421
if (subs_type == Item_subselect::EXISTS_SUBS ||
2422
subs_type == Item_subselect::IN_SUBS ||
2423
subs_type == Item_subselect::ALL_SUBS)
2430
str->append(STRING_WITH_LEN(" limit "));
2433
offset_limit->print(str, query_type);
2436
select_limit->print(str, query_type);
2442
@brief Restore the LEX and THD in case of a parse error.
2444
This is a clean up call that is invoked by the Bison generated
2445
parser before returning an error from MYSQLparse. If your
2446
semantic actions manipulate with the global thread state (which
2447
is a very bad practice and should not normally be employed) and
2448
need a clean-up in case of error, and you can not use %destructor
2449
rule in the grammar file itself, this function should be used
2450
to implement the clean up.
2453
void LEX::cleanup_lex_after_parse_error(THD *thd)
2456
Delete sphead for the side effect of restoring of the original
2457
LEX state, thd->lex, thd->mem_root and thd->free_list if they
2458
were replaced when parsing stored procedure statements. We
2459
will never use sphead object after a parse error, so it's okay
2460
to delete it only for the sake of the side effect.
2461
TODO: make this functionality explicit in sp_head class.
2462
Sic: we must nullify the member of the main lex, not the
2463
current one that will be thrown away
2465
if (thd->lex->sphead)
2467
thd->lex->sphead->restore_thd_mem_root(thd);
2468
delete thd->lex->sphead;
2469
thd->lex->sphead= NULL;
2474
Initialize (or reset) Query_tables_list object.
2477
reset_query_tables_list()
2478
init TRUE - we should perform full initialization of object with
2479
allocating needed memory
2480
FALSE - object is already initialized so we should only reset
2481
its state so it can be used for parsing/processing
2485
This method initializes Query_tables_list so it can be used as part
2486
of LEX object for parsing/processing of statement. One can also use
2487
this method to reset state of already initialized Query_tables_list
2488
so it can be used for processing of new statement.
2491
void Query_tables_list::reset_query_tables_list(bool init)
2493
sql_command= SQLCOM_END;
2494
if (!init && query_tables)
2496
TABLE_LIST *table= query_tables;
2500
if (query_tables_last == &table->next_global ||
2501
!(table= table->next_global))
2506
query_tables_last= &query_tables;
2507
query_tables_own_last= 0;
2511
We delay real initialization of hash (and therefore related
2512
memory allocation) until first insertion into this hash.
2514
my_hash_clear(&sroutines);
2516
else if (sroutines.records)
2518
/* Non-zero sroutines.records means that hash was initialized. */
2519
my_hash_reset(&sroutines);
2521
sroutines_list.empty();
2522
sroutines_list_own_last= sroutines_list.next;
2523
sroutines_list_own_elements= 0;
2524
binlog_stmt_flags= 0;
2525
stmt_accessed_table_flag= 0;
2530
Destroy Query_tables_list object with freeing all resources used by it.
2533
destroy_query_tables_list()
2536
void Query_tables_list::destroy_query_tables_list()
2538
my_hash_free(&sroutines);
2543
Initialize LEX object.
2549
LEX object initialized with this constructor can be used as part of
2550
THD object for which one can safely call open_tables(), lock_tables()
2551
and close_thread_tables() functions. But it is not yet ready for
2552
statement parsing. On should use lex_start() function to prepare LEX
2557
:result(0), option_type(OPT_DEFAULT), is_lex_started(0),
2558
limit_rows_examined_cnt(ULONGLONG_MAX)
2561
my_init_dynamic_array2(&plugins, sizeof(plugin_ref),
2562
plugins_static_buffer,
2563
INITIAL_LEX_PLUGIN_LIST_SIZE,
2564
INITIAL_LEX_PLUGIN_LIST_SIZE);
2565
reset_query_tables_list(TRUE);
2571
Check whether the merging algorithm can be used on this VIEW
2574
LEX::can_be_merged()
2577
We can apply merge algorithm if it is single SELECT view with
2578
subqueries only in WHERE clause (we do not count SELECTs of underlying
2579
views, and second level subqueries) and we have not grpouping, ordering,
2580
HAVING clause, aggregate functions, DISTINCT clause, LIMIT clause and
2581
several underlying tables.
2584
FALSE - only temporary table algorithm can be used
2585
TRUE - merge algorithm can be used
2588
bool LEX::can_be_merged()
2590
// TODO: do not forget implement case when select_lex.table_list.elements==0
2592
/* find non VIEW subqueries/unions */
2593
bool selects_allow_merge= select_lex.next_select() == 0;
2594
if (selects_allow_merge)
2596
for (SELECT_LEX_UNIT *tmp_unit= select_lex.first_inner_unit();
2598
tmp_unit= tmp_unit->next_unit())
2600
if (tmp_unit->first_select()->parent_lex == this &&
2601
(tmp_unit->item == 0 ||
2602
(tmp_unit->item->place() != IN_WHERE &&
2603
tmp_unit->item->place() != IN_ON)))
2605
selects_allow_merge= 0;
2611
return (selects_allow_merge &&
2612
select_lex.group_list.elements == 0 &&
2613
select_lex.having == 0 &&
2614
select_lex.with_sum_func == 0 &&
2615
select_lex.table_list.elements >= 1 &&
2616
!(select_lex.options & SELECT_DISTINCT) &&
2617
select_lex.select_limit == 0);
2622
check if command can use VIEW with MERGE algorithm (for top VIEWs)
2625
LEX::can_use_merged()
2628
Only listed here commands can use merge algorithm in top level
2629
SELECT_LEX (for subqueries will be used merge algorithm if
2630
LEX::can_not_use_merged() is not TRUE).
2633
FALSE - command can't use merged VIEWs
2634
TRUE - VIEWs with MERGE algorithms can be used
2637
bool LEX::can_use_merged()
2639
switch (sql_command)
2642
case SQLCOM_CREATE_TABLE:
2644
case SQLCOM_UPDATE_MULTI:
2646
case SQLCOM_DELETE_MULTI:
2648
case SQLCOM_INSERT_SELECT:
2649
case SQLCOM_REPLACE:
2650
case SQLCOM_REPLACE_SELECT:
2659
Check if command can't use merged views in any part of command
2662
LEX::can_not_use_merged()
2665
Temporary table algorithm will be used on all SELECT levels for queries
2666
listed here (see also LEX::can_use_merged()).
2669
FALSE - command can't use merged VIEWs
2670
TRUE - VIEWs with MERGE algorithms can be used
2673
bool LEX::can_not_use_merged()
2675
switch (sql_command)
2677
case SQLCOM_CREATE_VIEW:
2678
case SQLCOM_SHOW_CREATE:
2680
SQLCOM_SHOW_FIELDS is necessary to make
2681
information schema tables working correctly with views.
2682
see get_schema_tables_result function
2684
case SQLCOM_SHOW_FIELDS:
2692
Detect that we need only table structure of derived table/view
2695
only_view_structure()
2698
TRUE yes, we need only structure
2699
FALSE no, we need data
2702
bool LEX::only_view_structure()
2704
switch (sql_command) {
2705
case SQLCOM_SHOW_CREATE:
2706
case SQLCOM_SHOW_TABLES:
2707
case SQLCOM_SHOW_FIELDS:
2708
case SQLCOM_REVOKE_ALL:
2711
case SQLCOM_CREATE_VIEW:
2720
Should Items_ident be printed correctly
2723
need_correct_ident()
2726
TRUE yes, we need only structure
2727
FALSE no, we need data
2731
bool LEX::need_correct_ident()
2735
case SQLCOM_SHOW_CREATE:
2736
case SQLCOM_SHOW_TABLES:
2737
case SQLCOM_CREATE_VIEW:
2745
Get effective type of CHECK OPTION for given view
2748
get_effective_with_check()
2752
It have not sense to set CHECK OPTION for SELECT satement or subqueries,
2756
VIEW_CHECK_NONE no need CHECK OPTION
2757
VIEW_CHECK_LOCAL CHECK OPTION LOCAL
2758
VIEW_CHECK_CASCADED CHECK OPTION CASCADED
2761
uint8 LEX::get_effective_with_check(TABLE_LIST *view)
2763
if (view->select_lex->master_unit() == &unit &&
2764
which_check_option_applicable())
2765
return (uint8)view->with_check;
2766
return VIEW_CHECK_NONE;
2771
This method should be called only during parsing.
2772
It is aware of compound statements (stored routine bodies)
2773
and will initialize the destination with the default
2774
database of the stored routine, rather than the default
2775
database of the connection it is parsed in.
2776
E.g. if one has no current database selected, or current database
2777
set to 'bar' and then issues:
2779
CREATE PROCEDURE foo.p1() BEGIN SELECT * FROM t1 END//
2781
t1 is meant to refer to foo.t1, not to bar.t1.
2783
This method is needed to support this rule.
2785
@return TRUE in case of error (parsing should be aborted, FALSE in
2790
LEX::copy_db_to(char **p_db, size_t *p_db_length) const
2794
DBUG_ASSERT(sphead->m_db.str && sphead->m_db.length);
2796
It is safe to assign the string by-pointer, both sphead and
2797
its statements reside in the same memory root.
2799
*p_db= sphead->m_db.str;
2801
*p_db_length= sphead->m_db.length;
2804
return thd->copy_db_to(p_db, p_db_length);
2808
initialize limit counters
2811
st_select_lex_unit::set_limit()
2812
values - SELECT_LEX with initial values for counters
2815
void st_select_lex_unit::set_limit(st_select_lex *sl)
2817
ha_rows select_limit_val;
2820
DBUG_ASSERT(! thd->stmt_arena->is_stmt_prepare());
2821
if (sl->select_limit)
2823
Item *item = sl->select_limit;
2825
fix_fields() has not been called for sl->select_limit. That's due to the
2826
historical reasons -- this item could be only of type Item_int, and
2827
Item_int does not require fix_fields(). Thus, fix_fields() was never
2828
called for sl->select_limit.
2830
Some time ago, Item_splocal was also allowed for LIMIT / OFFSET clauses.
2831
However, the fix_fields() behavior was not updated, which led to a crash
2834
There is no single place where to call fix_fields() for LIMIT / OFFSET
2835
items during the fix-fields-phase. Thus, for the sake of readability,
2836
it was decided to do it here, on the evaluation phase (which is a
2837
violation of design, but we chose the lesser of two evils).
2839
We can call fix_fields() here, because sl->select_limit can be of two
2840
types only: Item_int and Item_splocal. Item_int::fix_fields() is trivial,
2841
and Item_splocal::fix_fields() (or rather Item_sp_variable::fix_fields())
2842
has the following specific:
2843
1) it does not affect other items;
2844
2) it does not fail.
2846
Nevertheless DBUG_ASSERT was added to catch future changes in
2847
fix_fields() implementation. Also added runtime check against a result
2848
of fix_fields() in order to handle error condition in non-debug build.
2850
bool fix_fields_successful= true;
2853
fix_fields_successful= !item->fix_fields(thd, NULL);
2855
DBUG_ASSERT(fix_fields_successful);
2857
val= fix_fields_successful ? item->val_uint() : HA_POS_ERROR;
2862
select_limit_val= (ha_rows)val;
2865
Check for overflow : ha_rows can be smaller then ulonglong if
2868
if (val != (ulonglong)select_limit_val)
2869
select_limit_val= HA_POS_ERROR;
2871
if (sl->offset_limit)
2873
Item *item = sl->offset_limit;
2874
// see comment for sl->select_limit branch.
2875
bool fix_fields_successful= true;
2878
fix_fields_successful= !item->fix_fields(thd, NULL);
2880
DBUG_ASSERT(fix_fields_successful);
2882
val= fix_fields_successful ? item->val_uint() : 0;
2887
offset_limit_cnt= (ha_rows)val;
2889
/* Check for truncation. */
2890
if (val != (ulonglong)offset_limit_cnt)
2891
offset_limit_cnt= HA_POS_ERROR;
2893
select_limit_cnt= select_limit_val + offset_limit_cnt;
2894
if (select_limit_cnt < select_limit_val)
2895
select_limit_cnt= HA_POS_ERROR; // no limit
2900
@brief Set the initial purpose of this TABLE_LIST object in the list of used
2903
We need to track this information on table-by-table basis, since when this
2904
table becomes an element of the pre-locked list, it's impossible to identify
2905
which SQL sub-statement it has been originally used in.
2909
User request: SELECT * FROM t1 WHERE f1();
2910
FUNCTION f1(): DELETE FROM t2; RETURN 1;
2911
BEFORE DELETE trigger on t2: INSERT INTO t3 VALUES (old.a);
2913
For this user request, the pre-locked list will contain t1, t2, t3
2914
table elements, each needed for different DML.
2916
The trigger event map is updated to reflect INSERT, UPDATE, DELETE,
2917
REPLACE, LOAD DATA, CREATE TABLE .. SELECT, CREATE TABLE ..
2918
REPLACE SELECT statements, and additionally ON DUPLICATE KEY UPDATE
2922
void LEX::set_trg_event_type_for_tables()
2924
uint8 new_trg_event_map= 0;
2925
DBUG_ENTER("LEX::set_trg_event_type_for_tables");
2928
Some auxiliary operations
2929
(e.g. GRANT processing) create TABLE_LIST instances outside
2930
the parser. Additionally, some commands (e.g. OPTIMIZE) change
2931
the lock type for a table only after parsing is done. Luckily,
2932
these do not fire triggers and do not need to pre-load them.
2933
For these TABLE_LISTs set_trg_event_type is never called, and
2934
trg_event_map is always empty. That means that the pre-locking
2935
algorithm will ignore triggers defined on these tables, if
2936
any, and the execution will either fail with an assert in
2937
sql_trigger.cc or with an error that a used table was not
2938
pre-locked, in case of a production build.
2940
TODO: this usage pattern creates unnecessary module dependencies
2941
and should be rewritten to go through the parser.
2942
Table list instances created outside the parser in most cases
2943
refer to mysql.* system tables. It is not allowed to have
2944
a trigger on a system table, but keeping track of
2945
initialization provides extra safety in case this limitation
2949
switch (sql_command) {
2950
case SQLCOM_LOCK_TABLES:
2952
On a LOCK TABLE, all triggers must be pre-loaded for this TABLE_LIST
2953
when opening an associated TABLE.
2955
new_trg_event_map= static_cast<uint8>
2956
(1 << static_cast<int>(TRG_EVENT_INSERT)) |
2958
(1 << static_cast<int>(TRG_EVENT_UPDATE)) |
2960
(1 << static_cast<int>(TRG_EVENT_DELETE));
2963
Basic INSERT. If there is an additional ON DUPLIATE KEY UPDATE
2964
clause, it will be handled later in this method.
2966
case SQLCOM_INSERT: /* fall through */
2967
case SQLCOM_INSERT_SELECT:
2969
LOAD DATA ... INFILE is expected to fire BEFORE/AFTER INSERT
2971
If the statement also has REPLACE clause, it will be
2972
handled later in this method.
2974
case SQLCOM_LOAD: /* fall through */
2976
REPLACE is semantically equivalent to INSERT. In case
2977
of a primary or unique key conflict, it deletes the old
2978
record and inserts a new one. So we also may need to
2979
fire ON DELETE triggers. This functionality is handled
2980
later in this method.
2982
case SQLCOM_REPLACE: /* fall through */
2983
case SQLCOM_REPLACE_SELECT:
2985
CREATE TABLE ... SELECT defaults to INSERT if the table or
2986
view already exists. REPLACE option of CREATE TABLE ...
2987
REPLACE SELECT is handled later in this method.
2989
case SQLCOM_CREATE_TABLE:
2990
new_trg_event_map|= static_cast<uint8>
2991
(1 << static_cast<int>(TRG_EVENT_INSERT));
2993
/* Basic update and multi-update */
2994
case SQLCOM_UPDATE: /* fall through */
2995
case SQLCOM_UPDATE_MULTI:
2996
new_trg_event_map|= static_cast<uint8>
2997
(1 << static_cast<int>(TRG_EVENT_UPDATE));
2999
/* Basic delete and multi-delete */
3000
case SQLCOM_DELETE: /* fall through */
3001
case SQLCOM_DELETE_MULTI:
3002
new_trg_event_map|= static_cast<uint8>
3003
(1 << static_cast<int>(TRG_EVENT_DELETE));
3009
switch (duplicates) {
3011
new_trg_event_map|= static_cast<uint8>
3012
(1 << static_cast<int>(TRG_EVENT_UPDATE));
3015
new_trg_event_map|= static_cast<uint8>
3016
(1 << static_cast<int>(TRG_EVENT_DELETE));
3025
Do not iterate over sub-selects, only the tables in the outermost
3026
SELECT_LEX can be modified, if any.
3028
TABLE_LIST *tables= select_lex.get_table_list();
3033
This is a fast check to filter out statements that do
3034
not change data, or tables on the right side, in case of
3035
INSERT .. SELECT, CREATE TABLE .. SELECT and so on.
3036
Here we also filter out OPTIMIZE statement and non-updateable
3037
views, for which lock_type is TL_UNLOCK or TL_READ after
3040
if (static_cast<int>(tables->lock_type) >=
3041
static_cast<int>(TL_WRITE_ALLOW_WRITE))
3042
tables->trg_event_map= new_trg_event_map;
3043
tables= tables->next_local;
3050
Unlink the first table from the global table list and the first table from
3051
outer select (lex->select_lex) local list
3054
unlink_first_table()
3055
link_to_local Set to 1 if caller should link this table to local list
3058
We assume that first tables in both lists is the same table or the local
3062
0 If 'query_tables' == 0
3064
In this case link_to_local is set.
3067
TABLE_LIST *LEX::unlink_first_table(bool *link_to_local)
3070
if ((first= query_tables))
3073
Exclude from global table list
3075
if ((query_tables= query_tables->next_global))
3076
query_tables->prev_global= &query_tables;
3078
query_tables_last= &query_tables;
3079
first->next_global= 0;
3082
and from local list if it is not empty
3084
if ((*link_to_local= test(select_lex.table_list.first)))
3086
select_lex.context.table_list=
3087
select_lex.context.first_name_resolution_table= first->next_local;
3088
select_lex.table_list.first= first->next_local;
3089
select_lex.table_list.elements--; //safety
3090
first->next_local= 0;
3092
Ensure that the global list has the same first table as the local
3095
first_lists_tables_same();
3103
Bring first local table of first most outer select to first place in global
3107
LEX::first_lists_tables_same()
3110
In many cases (for example, usual INSERT/DELETE/...) the first table of
3111
main SELECT_LEX have special meaning => check that it is the first table
3112
in global list and re-link to be first in the global list if it is
3113
necessary. We need such re-linking only for queries with sub-queries in
3114
the select list, as only in this case tables of sub-queries will go to
3115
the global list first.
3118
void LEX::first_lists_tables_same()
3120
TABLE_LIST *first_table= select_lex.table_list.first;
3121
if (query_tables != first_table && first_table != 0)
3124
if (query_tables_last == &first_table->next_global)
3125
query_tables_last= first_table->prev_global;
3127
if ((next= *first_table->prev_global= first_table->next_global))
3128
next->prev_global= first_table->prev_global;
3129
/* include in new place */
3130
first_table->next_global= query_tables;
3132
We are sure that query_tables is not 0, because first_table was not
3133
first table in the global list => we can use
3134
query_tables->prev_global without check of query_tables
3136
query_tables->prev_global= &first_table->next_global;
3137
first_table->prev_global= &query_tables;
3138
query_tables= first_table;
3144
Link table back that was unlinked with unlink_first_table()
3147
link_first_table_back()
3148
link_to_local do we need link this table to local
3154
void LEX::link_first_table_back(TABLE_LIST *first,
3159
if ((first->next_global= query_tables))
3160
query_tables->prev_global= &first->next_global;
3162
query_tables_last= &first->next_global;
3163
query_tables= first;
3167
first->next_local= select_lex.table_list.first;
3168
select_lex.context.table_list= first;
3169
select_lex.table_list.first= first;
3170
select_lex.table_list.elements++; //safety
3178
cleanup lex for case when we open table by table for processing
3181
LEX::cleanup_after_one_table_open()
3184
This method is mostly responsible for cleaning up of selects lists and
3185
derived tables state. To rollback changes in Query_tables_list one has
3186
to call Query_tables_list::reset_query_tables_list(FALSE).
3189
void LEX::cleanup_after_one_table_open()
3192
thd->lex->derived_tables & additional units may be set if we open
3193
a view. It is necessary to clear thd->lex->derived_tables flag
3194
to prevent processing of derived tables during next open_and_lock_tables
3195
if next table is a real table and cleanup & remove underlying units
3196
NOTE: all units will be connected to thd->lex->select_lex, because we
3197
have not UNION on most upper level.
3199
if (all_selects_list != &select_lex)
3202
select_lex.exclude_from_table_unique_test= false;
3203
/* cleunup underlying units (units of VIEW) */
3204
for (SELECT_LEX_UNIT *un= select_lex.first_inner_unit();
3206
un= un->next_unit())
3208
/* reduce all selects list to default state */
3209
all_selects_list= &select_lex;
3210
/* remove underlying units (units of VIEW) subtree */
3211
select_lex.cut_subtree();
3217
Save current state of Query_tables_list for this LEX, and prepare it
3218
for processing of new statemnt.
3221
reset_n_backup_query_tables_list()
3222
backup Pointer to Query_tables_list instance to be used for backup
3225
void LEX::reset_n_backup_query_tables_list(Query_tables_list *backup)
3227
backup->set_query_tables_list(this);
3229
We have to perform full initialization here since otherwise we
3230
will damage backed up state.
3232
this->reset_query_tables_list(TRUE);
3237
Restore state of Query_tables_list for this LEX from backup.
3240
restore_backup_query_tables_list()
3241
backup Pointer to Query_tables_list instance used for backup
3244
void LEX::restore_backup_query_tables_list(Query_tables_list *backup)
3246
this->destroy_query_tables_list();
3247
this->set_query_tables_list(backup);
3252
Checks for usage of routines and/or tables in a parsed statement
3255
LEX:table_or_sp_used()
3258
FALSE No routines and tables used
3259
TRUE Either or both routines and tables are used.
3262
bool LEX::table_or_sp_used()
3264
DBUG_ENTER("table_or_sp_used");
3266
if (sroutines.records || query_tables)
3274
Do end-of-prepare fixup for list of tables and their merge-VIEWed tables
3277
fix_prepare_info_in_table_list()
3279
tbl List of tables to process
3282
Perform end-end-of prepare fixup for list of tables, if any of the tables
3283
is a merge-algorithm VIEW, recursively fix up its underlying tables as
3288
static void fix_prepare_info_in_table_list(THD *thd, TABLE_LIST *tbl)
3290
for (; tbl; tbl= tbl->next_local)
3294
thd->check_and_register_item_tree(&tbl->prep_on_expr, &tbl->on_expr);
3295
tbl->on_expr= tbl->on_expr->copy_andor_structure(thd);
3297
if (tbl->is_view_or_derived() && tbl->is_merged_derived())
3299
SELECT_LEX *sel= tbl->get_single_select();
3300
fix_prepare_info_in_table_list(thd, sel->get_table_list());
3307
Save WHERE/HAVING/ON clauses and replace them with disposable copies
3310
st_select_lex::fix_prepare_information
3312
conds in/out pointer to WHERE condition to be met at execution
3313
having_conds in/out pointer to HAVING condition to be met at execution
3316
The passed WHERE and HAVING are to be saved for the future executions.
3317
This function saves it, and returns a copy which can be thrashed during
3318
this execution of the statement. By saving/thrashing here we mean only
3319
We also save the chain of ORDER::next in group_list, in case
3320
the list is modified by remove_const().
3322
The function also calls fix_prepare_info_in_table_list that saves all
3326
void st_select_lex::fix_prepare_information(THD *thd, Item **conds,
3327
Item **having_conds)
3329
if (!thd->stmt_arena->is_conventional() && first_execution)
3332
if (group_list.first)
3334
if (!group_list_ptrs)
3336
void *mem= thd->stmt_arena->alloc(sizeof(Group_list_ptrs));
3337
group_list_ptrs= new (mem) Group_list_ptrs(thd->stmt_arena->mem_root);
3339
group_list_ptrs->reserve(group_list.elements);
3340
for (ORDER *order= group_list.first; order; order= order->next)
3342
group_list_ptrs->push_back(order);
3347
thd->check_and_register_item_tree(&prep_where, conds);
3348
*conds= where= prep_where->copy_andor_structure(thd);
3352
thd->check_and_register_item_tree(&prep_having, having_conds);
3353
*having_conds= having= prep_having->copy_andor_structure(thd);
3355
fix_prepare_info_in_table_list(thd, table_list.first);
3361
There are st_select_lex::add_table_to_list &
3362
st_select_lex::set_lock_for_tables are in sql_parse.cc
3364
st_select_lex::print is in sql_select.cc
3366
st_select_lex_unit::prepare, st_select_lex_unit::exec,
3367
st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
3368
st_select_lex_unit::change_result
3373
Sets the kind of hints to be added by the calls to add_index_hint().
3376
set_index_hint_type()
3377
type_arg The kind of hints to be added from now on.
3378
clause The clause to use for hints to be added from now on.
3381
Used in filling up the tagged hints list.
3382
This list is filled by first setting the kind of the hint as a
3383
context variable and then adding hints of the current kind.
3384
Then the context variable index_hint_type can be reset to the
3387
void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
3388
index_clause_map clause)
3390
current_index_hint_type= type_arg;
3391
current_index_hint_clause= clause;
3396
Makes an array to store index usage hints (ADD/FORCE/IGNORE INDEX).
3403
void st_select_lex::alloc_index_hints (THD *thd)
3405
index_hints= new (thd->mem_root) List<Index_hint>();
3411
adds an element to the array storing index usage hints
3412
(ADD/FORCE/IGNORE INDEX).
3417
str name of the index.
3418
length number of characters in str.
3421
0 on success, non-zero otherwise
3423
bool st_select_lex::add_index_hint (THD *thd, char *str, uint length)
3425
return index_hints->push_front (new (thd->mem_root)
3426
Index_hint(current_index_hint_type,
3427
current_index_hint_clause,
3433
Optimize all subqueries that have not been flattened into semi-joins.
3436
This functionality is a method of SELECT_LEX instead of JOIN because
3437
SQL statements as DELETE/UPDATE do not have a corresponding JOIN object.
3439
@see JOIN::optimize_unflattened_subqueries
3441
@param const_only Restrict subquery optimization to constant subqueries
3443
@return Operation status
3444
@retval FALSE success.
3445
@retval TRUE error occurred.
3448
bool st_select_lex::optimize_unflattened_subqueries(bool const_only)
3450
for (SELECT_LEX_UNIT *un= first_inner_unit(); un; un= un->next_unit())
3452
Item_subselect *subquery_predicate= un->item;
3454
if (subquery_predicate)
3456
if (subquery_predicate->substype() == Item_subselect::IN_SUBS)
3458
Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;
3459
if (in_subs->is_jtbm_merged)
3463
if (const_only && !subquery_predicate->const_item())
3465
/* Skip non-constant subqueries if the caller asked so. */
3469
bool empty_union_result= true;
3470
bool is_correlated_unit= false;
3472
If the subquery is a UNION, optimize all the subqueries in the UNION. If
3473
there is no UNION, then the loop will execute once for the subquery.
3475
for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
3477
JOIN *inner_join= sl->join;
3480
SELECT_LEX *save_select= un->thd->lex->current_select;
3481
ulonglong save_options;
3483
/* We need only 1 row to determine existence */
3484
un->set_limit(un->global_parameters);
3485
un->thd->lex->current_select= sl;
3486
save_options= inner_join->select_options;
3487
if (options & SELECT_DESCRIBE)
3489
/* Optimize the subquery in the context of EXPLAIN. */
3490
sl->set_explain_type();
3491
sl->options|= SELECT_DESCRIBE;
3492
inner_join->select_options|= SELECT_DESCRIBE;
3494
res= inner_join->optimize();
3495
sl->update_correlated_cache();
3496
is_correlated_unit|= sl->is_correlated;
3497
inner_join->select_options= save_options;
3498
un->thd->lex->current_select= save_select;
3499
if (empty_union_result)
3502
If at least one subquery in a union is non-empty, the UNION result
3503
is non-empty. If there is no UNION, the only subquery is non-empy.
3505
empty_union_result= inner_join->empty_result();
3510
if (empty_union_result)
3511
subquery_predicate->no_rows_in_result();
3512
if (!is_correlated_unit)
3513
un->uncacheable&= ~UNCACHEABLE_DEPENDENT;
3514
subquery_predicate->is_correlated= is_correlated_unit;
3523
@brief Process all derived tables/views of the SELECT.
3525
@param lex LEX of this thread
3526
@param phase phases to run derived tables/views through
3529
This function runs specified 'phases' on all tables from the
3530
table_list of this select.
3533
@return TRUE an error occur.
3536
bool st_select_lex::handle_derived(LEX *lex, uint phases)
3538
for (TABLE_LIST *cursor= (TABLE_LIST*) table_list.first;
3540
cursor= cursor->next_local)
3542
if (cursor->is_view_or_derived() && cursor->handle_derived(lex, phases))
3551
Returns first unoccupied table map and table number
3553
@param map [out] return found map
3554
@param tablenr [out] return found tablenr
3557
Returns first unoccupied table map and table number in this select.
3558
Map and table are returned in *'map' and *'tablenr' accordingly.
3560
@retrun TRUE no free table map/table number
3561
@return FALSE found free table map/table number
3564
bool st_select_lex::get_free_table_map(table_map *map, uint *tablenr)
3569
List_iterator<TABLE_LIST> ti(leaf_tables);
3572
if (tl->table->map > *map)
3573
*map= tl->table->map;
3574
if (tl->table->tablenr > *tablenr)
3575
*tablenr= tl->table->tablenr;
3579
if (*tablenr >= MAX_TABLES)
3587
Append given table to the leaf_tables list.
3589
@param link Offset to which list in table structure to use
3590
@param table Table to append
3593
Append given 'table' to the leaf_tables list using the 'link' offset.
3594
If the 'table' is linked with other tables through next_leaf/next_local
3595
chains then whole list will be appended.
3598
void st_select_lex::append_table_to_list(TABLE_LIST *TABLE_LIST::*link,
3602
for (tl= leaf_tables.head(); tl->*link; tl= tl->*link) ;
3609
Replace given table from the leaf_tables list for a list of tables
3611
@param table Table to replace
3612
@param list List to substititute the table for
3615
Replace 'table' from the leaf_tables list for a list of tables 'tbl_list'.
3618
void st_select_lex::replace_leaf_table(TABLE_LIST *table, List<TABLE_LIST> &tbl_list)
3621
List_iterator<TABLE_LIST> ti(leaf_tables);
3626
ti.replace(tbl_list);
3635
Assigns new table maps to tables in the leaf_tables list
3637
@param derived Derived table to take initial table map from
3638
@param map table map to begin with
3639
@param tablenr table number to begin with
3640
@param parent_lex new parent select_lex
3643
Assign new table maps/table numbers to all tables in the leaf_tables list.
3644
'map'/'tablenr' are used for the first table and shifted to left/
3645
increased for each consequent table in the leaf_tables list.
3646
If the 'derived' table is given then it's table map/number is used for the
3647
first table in the list and 'map'/'tablenr' are used for the second and
3648
all consequent tables.
3649
The 'parent_lex' is set as the new parent select_lex for all tables in the
3653
void st_select_lex::remap_tables(TABLE_LIST *derived, table_map map,
3654
uint tablenr, SELECT_LEX *parent_lex)
3656
bool first_table= TRUE;
3658
table_map first_map;
3661
if (derived && derived->table)
3663
first_map= derived->table->map;
3664
first_tablenr= derived->table->tablenr;
3670
first_tablenr= tablenr++;
3673
Assign table bit/table number.
3674
To the first table of the subselect the table bit/tablenr of the
3675
derived table is assigned. The rest of tables are getting bits
3676
sequentially, starting from the provided table map/tablenr.
3678
List_iterator<TABLE_LIST> ti(leaf_tables);
3684
tl->table->set_table_map(first_map, first_tablenr);
3688
tl->table->set_table_map(map, tablenr);
3692
SELECT_LEX *old_sl= tl->select_lex;
3693
tl->select_lex= parent_lex;
3694
for(TABLE_LIST *emb= tl->embedding;
3695
emb && emb->select_lex == old_sl;
3696
emb= emb->embedding)
3697
emb->select_lex= parent_lex;
3703
Merge a subquery into this select.
3705
@param derived derived table of the subquery to be merged
3706
@param subq_select select_lex of the subquery
3707
@param map table map for assigning to merged tables from subquery
3708
@param table_no table number for assigning to merged tables from subquery
3711
This function merges a subquery into its parent select. In short the
3712
merge operation appends the subquery FROM table list to the parent's
3713
FROM table list. In more details:
3714
.) the top_join_list of the subquery is wrapped into a join_nest
3715
and attached to 'derived'
3716
.) subquery's leaf_tables list is merged with the leaf_tables
3717
list of this select_lex
3718
.) the table maps and table numbers of the tables merged from
3719
the subquery are adjusted to reflect their new binding to
3722
@return TRUE an error occur
3726
bool SELECT_LEX::merge_subquery(THD *thd, TABLE_LIST *derived,
3727
SELECT_LEX *subq_select,
3728
uint table_no, table_map map)
3730
derived->wrap_into_nested_join(subq_select->top_join_list);
3732
ftfunc_list->concat(subq_select->ftfunc_list);
3734
thd->lex->sql_command == SQLCOM_UPDATE_MULTI ||
3735
thd->lex->sql_command == SQLCOM_DELETE_MULTI)
3737
List_iterator_fast<Item_in_subselect> li(subq_select->sj_subselects);
3738
Item_in_subselect *in_subq;
3739
while ((in_subq= li++))
3741
sj_subselects.push_back(in_subq);
3742
if (in_subq->emb_on_expr_nest == NO_JOIN_NEST)
3743
in_subq->emb_on_expr_nest= derived;
3747
/* Walk through child's tables and adjust table map, tablenr,
3749
subq_select->remap_tables(derived, map, table_no, this);
3750
subq_select->merged_into= this;
3752
replace_leaf_table(derived, subq_select->leaf_tables);
3760
Mark tables from the leaf_tables list as belong to a derived table.
3762
@param derived tables will be marked as belonging to this derived
3765
Run through the leaf_list and mark all tables as belonging to the 'derived'.
3768
void SELECT_LEX::mark_as_belong_to_derived(TABLE_LIST *derived)
3770
/* Mark tables as belonging to this DT */
3772
List_iterator<TABLE_LIST> ti(leaf_tables);
3775
tl->open_type= OT_BASE_ONLY;
3776
tl->belong_to_derived= derived;
3783
Update used_tables cache for this select
3786
This function updates used_tables cache of ON expressions of all tables
3787
in the leaf_tables list and of the conds expression (if any).
3790
void SELECT_LEX::update_used_tables()
3793
List_iterator<TABLE_LIST> ti(leaf_tables);
3797
if (tl->table && !tl->is_view_or_derived())
3799
TABLE_LIST *embedding= tl->embedding;
3800
for (embedding= tl->embedding; embedding; embedding=embedding->embedding)
3802
if (embedding->is_view_or_derived())
3804
DBUG_ASSERT(embedding->is_merged_derived());
3805
TABLE *tab= tl->table;
3806
tab->covering_keys= tab->s->keys_for_keyread;
3807
tab->covering_keys.intersect(tab->keys_in_use_for_query);
3808
tab->merge_keys.clear_all();
3809
bitmap_clear_all(tab->read_set);
3810
bitmap_clear_all(tab->vcol_set);
3820
TABLE_LIST *embedding= tl;
3824
if ((maybe_null= test(embedding->outer_join)))
3826
tl->table->maybe_null= maybe_null;
3830
while ((embedding= embedding->embedding));
3833
tl->on_expr->update_used_tables();
3834
tl->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
3836
embedding= tl->embedding;
3839
if (embedding->on_expr &&
3840
embedding->nested_join->join_list.head() == tl)
3842
embedding->on_expr->update_used_tables();
3843
embedding->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
3846
embedding= tl->embedding;
3852
join->conds->update_used_tables();
3853
join->conds->walk(&Item::eval_not_null_tables, 0, NULL);
3857
join->having->update_used_tables();
3861
List_iterator_fast<Item> it(join->fields_list);
3862
while ((item= it++))
3864
item->update_used_tables();
3866
Item_outer_ref *ref;
3867
List_iterator_fast<Item_outer_ref> ref_it(inner_refs_list);
3868
while ((ref= ref_it++))
3870
item= ref->outer_ref;
3871
item->update_used_tables();
3873
for (ORDER *order= group_list.first; order; order= order->next)
3874
(*order->item)->update_used_tables();
3875
if (!master_unit()->is_union())
3877
for (ORDER *order= order_list.first; order; order= order->next)
3878
(*order->item)->update_used_tables();
3880
join->result->update_used_tables();
3886
Update is_correlated cache for this select
3891
void st_select_lex::update_correlated_cache()
3894
List_iterator<TABLE_LIST> ti(leaf_tables);
3896
is_correlated= false;
3901
is_correlated|= test(tl->on_expr->used_tables() & OUTER_REF_TABLE_BIT);
3902
for (TABLE_LIST *embedding= tl->embedding ; embedding ;
3903
embedding= embedding->embedding)
3905
if (embedding->on_expr)
3906
is_correlated|= test(embedding->on_expr->used_tables() &
3907
OUTER_REF_TABLE_BIT);
3912
is_correlated|= test(join->conds->used_tables() & OUTER_REF_TABLE_BIT);
3915
is_correlated|= test(join->having->used_tables() & OUTER_REF_TABLE_BIT);
3917
if (join->tmp_having)
3918
is_correlated|= test(join->tmp_having->used_tables() & OUTER_REF_TABLE_BIT);
3921
List_iterator_fast<Item> it(join->fields_list);
3922
while ((item= it++))
3923
is_correlated|= test(item->used_tables() & OUTER_REF_TABLE_BIT);
3925
for (ORDER *order= group_list.first; order; order= order->next)
3926
is_correlated|= test((*order->item)->used_tables() & OUTER_REF_TABLE_BIT);
3928
if (!master_unit()->is_union())
3930
for (ORDER *order= order_list.first; order; order= order->next)
3931
is_correlated|= test((*order->item)->used_tables() & OUTER_REF_TABLE_BIT);
3935
uncacheable&= ~UNCACHEABLE_DEPENDENT;
3940
Set the EXPLAIN type for this subquery.
3943
void st_select_lex::set_explain_type()
3945
bool is_primary= FALSE;
3949
if (!is_primary && first_inner_unit())
3952
If there is at least one materialized derived|view then it's a PRIMARY select.
3953
Otherwise, all derived tables/views were merged and this select is a SIMPLE one.
3955
for (SELECT_LEX_UNIT *un= first_inner_unit(); un; un= un->next_unit())
3957
if ((!un->derived || un->derived->is_materialized_derived()))
3965
SELECT_LEX *first= master_unit()->first_select();
3966
/* drop UNCACHEABLE_EXPLAIN, because it is for internal usage only */
3967
uint8 is_uncacheable= (uncacheable & ~UNCACHEABLE_EXPLAIN);
3969
bool using_materialization= FALSE;
3970
Item_subselect *parent_item;
3971
if ((parent_item= master_unit()->item) &&
3972
parent_item->substype() == Item_subselect::IN_SUBS)
3974
Item_in_subselect *in_subs= (Item_in_subselect*)parent_item;
3976
Surprisingly, in_subs->is_set_strategy() can return FALSE here,
3977
even for the last invocation of this function for the select.
3979
if (in_subs->test_strategy(SUBS_MATERIALIZATION))
3980
using_materialization= TRUE;
3983
if (&master_unit()->thd->lex->select_lex == this)
3985
type= is_primary ? "PRIMARY" : "SIMPLE";
3991
/* If we're a direct child of a UNION, we're the first sibling there */
3992
if (linkage == DERIVED_TABLE_TYPE)
3994
else if (using_materialization)
3995
type= "MATERIALIZED";
3998
if (is_uncacheable & UNCACHEABLE_DEPENDENT)
3999
type= "DEPENDENT SUBQUERY";
4002
type= is_uncacheable? "UNCACHEABLE SUBQUERY" :
4009
/* This a non-first sibling in UNION */
4010
if (is_uncacheable & UNCACHEABLE_DEPENDENT)
4011
type= "DEPENDENT UNION";
4012
else if (using_materialization)
4013
type= "MATERIALIZED UNION";
4016
type= is_uncacheable ? "UNCACHEABLE UNION": "UNION";
4020
options|= SELECT_DESCRIBE;
4026
Increase estimated number of records for a derived table/view
4028
@param records number of records to increase estimate by
4031
This function increases estimated number of records by the 'records'
4032
for the derived table to which this select belongs to.
4035
void SELECT_LEX::increase_derived_records(ha_rows records)
4037
SELECT_LEX_UNIT *unit= master_unit();
4038
DBUG_ASSERT(unit->derived);
4040
select_union *result= (select_union*)unit->result;
4041
result->records+= records;
4047
Mark select's derived table as a const one.
4049
@param empty Whether select has an empty result set
4052
Mark derived table/view of this select as a constant one (to
4053
materialize it at the optimization phase) unless this select belongs to a
4054
union. Estimated number of rows is incremented if this select has non empty
4058
void SELECT_LEX::mark_const_derived(bool empty)
4060
TABLE_LIST *derived= master_unit()->derived;
4061
if (!join->thd->lex->describe && derived)
4064
increase_derived_records(1);
4065
if (!master_unit()->is_union() && !derived->is_merged_derived())
4066
derived->fill_me= TRUE;
4071
bool st_select_lex::save_leaf_tables(THD *thd)
4073
Query_arena *arena= thd->stmt_arena, backup;
4074
if (arena->is_conventional())
4077
thd->set_n_backup_active_arena(arena, &backup);
4079
List_iterator_fast<TABLE_LIST> li(leaf_tables);
4081
while ((table= li++))
4083
if (leaf_tables_exec.push_back(table))
4085
table->tablenr_exec= table->get_tablenr();
4086
table->map_exec= table->get_map();
4087
if (join && (join->select_options & SELECT_DESCRIBE))
4088
table->maybe_null_exec= 0;
4090
table->maybe_null_exec= table->table? table->table->maybe_null: 0;
4093
thd->restore_active_arena(arena, &backup);
4099
bool st_select_lex::save_prep_leaf_tables(THD *thd)
4101
if (!thd->save_prep_leaf_list)
4104
Query_arena *arena= thd->stmt_arena, backup;
4105
if (arena->is_conventional())
4108
thd->set_n_backup_active_arena(arena, &backup);
4110
List_iterator_fast<TABLE_LIST> li(leaf_tables);
4112
while ((table= li++))
4114
if (leaf_tables_prep.push_back(table))
4117
thd->lex->select_lex.is_prep_leaf_list_saved= TRUE;
4118
thd->save_prep_leaf_list= FALSE;
4120
thd->restore_active_arena(arena, &backup);
4127
Return true if this select_lex has been converted into a semi-join nest
4130
We need a loop to check this because there could be several nested
4133
SELECT ... FROM grand_parent
4134
WHERE expr1 IN (SELECT ... FROM parent
4135
WHERE expr2 IN ( SELECT ... FROM child)
4137
which were converted into:
4140
FROM grand_parent SEMI_JOIN (parent JOIN child)
4144
In this case, both parent and child selects were merged into the parent.
4147
bool st_select_lex::is_merged_child_of(st_select_lex *ancestor)
4149
bool all_merged= TRUE;
4150
for (SELECT_LEX *sl= this; sl && sl!=ancestor;
4151
sl=sl->outer_select())
4153
Item *subs= sl->master_unit()->item;
4154
if (subs && subs->type() == Item::SUBSELECT_ITEM &&
4155
((Item_subselect*)subs)->substype() == Item_subselect::IN_SUBS &&
4156
((Item_in_subselect*)subs)->test_strategy(SUBS_SEMI_JOIN))
4168
A routine used by the parser to decide whether we are specifying a full
4169
partitioning or if only partitions to add or to split.
4171
@note This needs to be outside of WITH_PARTITION_STORAGE_ENGINE since it
4172
is used from the sql parser that doesn't have any ifdef's
4174
@retval TRUE Yes, it is part of a management partition command
4175
@retval FALSE No, not a management partition command
4178
bool LEX::is_partition_management() const
4180
return (sql_command == SQLCOM_ALTER_TABLE &&
4181
(alter_info.flags == ALTER_ADD_PARTITION ||
4182
alter_info.flags == ALTER_REORGANIZE_PARTITION));
4186
uint binlog_unsafe_map[256];
4188
#define UNSAFE(a, b, c) \
4190
DBUG_PRINT("unsafe_mixed_statement", ("SETTING BASE VALUES: %s, %s, %02X\n", \
4191
LEX::stmt_accessed_table_string(a), \
4192
LEX::stmt_accessed_table_string(b), \
4194
unsafe_mixed_statement(a, b, c); \
4198
Sets the combination given by "a" and "b" and automatically combinations
4199
given by other types of access, i.e. 2^(8 - 2), as unsafe.
4201
It may happen a colision when automatically defining a combination as unsafe.
4202
For that reason, a combination has its unsafe condition redefined only when
4203
the new_condition is greater then the old. For instance,
4205
. (BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY) is never overwritten by
4206
. (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF).
4208
void unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,
4209
LEX::enum_stmt_accessed_table b, uint condition)
4212
int index= (1U << a) | (1U << b);
4215
for (type= 0; type < 256; type++)
4217
if ((type & index) == index)
4219
binlog_unsafe_map[type] |= condition;
4224
The BINLOG_* AND TRX_CACHE_* values can be combined by using '&' or '|',
4225
which means that both conditions need to be satisfied or any of them is
4226
enough. For example,
4228
. BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY means that the statment is
4229
unsafe when the option is on and trx-cache is not empty;
4231
. BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF means the statement is unsafe
4234
. TRX_CACHE_EMPTY | TRX_CACHE_NOT_EMPTY means the statement is unsafe
4235
in all cases. Similar as above.
4237
void binlog_unsafe_map_init()
4239
memset((void*) binlog_unsafe_map, 0, sizeof(uint) * 256);
4242
Classify a statement as unsafe when there is a mixed statement and an
4243
on-going transaction at any point of the execution if:
4245
1. The mixed statement is about to update a transactional table and
4246
a non-transactional table.
4248
2. The mixed statement is about to update a transactional table and
4249
read from a non-transactional table.
4251
3. The mixed statement is about to update a non-transactional table
4252
and temporary transactional table.
4254
4. The mixed statement is about to update a temporary transactional
4255
table and read from a non-transactional table.
4257
5. The mixed statement is about to update a transactional table and
4258
a temporary non-transactional table.
4260
6. The mixed statement is about to update a transactional table and
4261
read from a temporary non-transactional table.
4263
7. The mixed statement is about to update a temporary transactional
4264
table and temporary non-transactional table.
4266
8. The mixed statement is about to update a temporary transactional
4267
table and read from a temporary non-transactional table.
4269
After updating a transactional table if:
4271
9. The mixed statement is about to update a non-transactional table
4272
and read from a transactional table.
4274
10. The mixed statement is about to update a non-transactional table
4275
and read from a temporary transactional table.
4277
11. The mixed statement is about to update a temporary non-transactional
4278
table and read from a transactional table.
4280
12. The mixed statement is about to update a temporary non-transactional
4281
table and read from a temporary transactional table.
4283
13. The mixed statement is about to update a temporary non-transactional
4284
table and read from a non-transactional table.
4286
The reason for this is that locks acquired may not protected a concurrent
4287
transaction of interfering in the current execution and by consequence in
4291
UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_NON_TRANS_TABLE,
4292
BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4294
UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
4295
BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4297
UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_WRITES_TEMP_TRANS_TABLE,
4298
BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4300
UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
4301
BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4303
UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
4306
UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
4309
UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
4312
UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
4315
UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
4316
(BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
4318
UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
4319
(BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
4321
UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
4322
BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
4324
UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
4325
BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
4327
UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
4328
BINLOG_DIRECT_OFF & TRX_CACHE_NOT_EMPTY);
4332
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
4333
template class Mem_root_array<ORDER*, true>;