MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
sql_lex.cc
1 /*
2  Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; version 2 of the License.
7 
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12 
13  You should have received a copy of the GNU General Public License
14  along with this program; if not, write to the Free Software
15  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
16 
17 
18 /* A lexical scanner on a temporary buffer with a yacc interface */
19 
20 #define MYSQL_LEX 1
21 #include "sql_priv.h"
22 #include "unireg.h" // REQUIRED: for other includes
23 #include "sql_class.h" // sql_lex.h: SQLCOM_END
24 #include "sql_lex.h"
25 #include "sql_parse.h" // add_to_list
26 #include "item_create.h"
27 #include <m_ctype.h>
28 #include <hash.h>
29 #include "sp.h"
30 #include "sp_head.h"
31 #include "sql_table.h" // primary_key_name
32 #include "sql_show.h" // append_identifier
33 #include "sql_select.h" // JOIN
34 #include "sql_optimizer.h" // JOIN
36 
37 static int lex_one_token(void *arg, void *yythd);
38 
39 /*
40  We are using pointer to this variable for distinguishing between assignment
41  to NEW row field (when parsing trigger definition) and structured variable.
42 */
43 
44 sys_var *trg_new_row_fake_var= (sys_var*) 0x01;
45 
49 const LEX_STRING null_lex_str= {NULL, 0};
50 const LEX_STRING empty_lex_str= {(char *) "", 0};
55 const int
56 Query_tables_list::binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT] =
57 {
58  ER_BINLOG_UNSAFE_LIMIT,
59  ER_BINLOG_UNSAFE_INSERT_DELAYED,
60  ER_BINLOG_UNSAFE_SYSTEM_TABLE,
61  ER_BINLOG_UNSAFE_AUTOINC_COLUMNS,
62  ER_BINLOG_UNSAFE_UDF,
63  ER_BINLOG_UNSAFE_SYSTEM_VARIABLE,
64  ER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
65  ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS,
66  ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
67  ER_BINLOG_UNSAFE_MIXED_STATEMENT,
68  ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT,
69  ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE,
70  ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT,
71  ER_BINLOG_UNSAFE_REPLACE_SELECT,
72  ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT,
73  ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT,
74  ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC,
75  ER_BINLOG_UNSAFE_UPDATE_IGNORE,
76  ER_BINLOG_UNSAFE_INSERT_TWO_KEYS,
77  ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST
78 };
79 
80 
81 /* Longest standard keyword name */
82 
83 #define TOCK_NAME_LENGTH 24
84 
85 /*
86  The following data is based on the latin1 character set, and is only
87  used when comparing keywords
88 */
89 
90 static uchar to_upper_lex[]=
91 {
92  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
93  16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
94  32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
95  48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
96  64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
97  80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
98  96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
99  80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127,
100  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
101  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
102  160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
103  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
104  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
105  208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
106  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
107  208,209,210,211,212,213,214,247,216,217,218,219,220,221,222,255
108 };
109 
110 /*
111  Names of the index hints (for error messages). Keep in sync with
112  index_hint_type
113 */
114 
115 const char * index_hint_type_name[] =
116 {
117  "IGNORE INDEX",
118  "USE INDEX",
119  "FORCE INDEX"
120 };
121 
122 
127 const char *st_select_lex::type_str[SLT_total]=
128 { "NONE",
129  "PRIMARY",
130  "SIMPLE",
131  "DERIVED",
132  "SUBQUERY",
133  "UNION",
134  "UNION RESULT",
135  "MATERIALIZED"
136 };
137 
138 
139 inline int lex_casecmp(const char *s, const char *t, uint len)
140 {
141  while (len-- != 0 &&
142  to_upper_lex[(uchar) *s++] == to_upper_lex[(uchar) *t++]) ;
143  return (int) len+1;
144 }
145 
146 #include <lex_hash.h>
147 
148 
149 void lex_init(void)
150 {
151  uint i;
152  DBUG_ENTER("lex_init");
153  for (i=0 ; i < array_elements(symbols) ; i++)
154  symbols[i].length=(uchar) strlen(symbols[i].name);
155  for (i=0 ; i < array_elements(sql_functions) ; i++)
156  sql_functions[i].length=(uchar) strlen(sql_functions[i].name);
157 
158  DBUG_VOID_RETURN;
159 }
160 
161 
162 void lex_free(void)
163 { // Call this when daemon ends
164  DBUG_ENTER("lex_free");
165  DBUG_VOID_RETURN;
166 }
167 
168 
169 void
170 st_parsing_options::reset()
171 {
172  allows_variable= TRUE;
173  allows_select_into= TRUE;
174  allows_select_procedure= TRUE;
175  allows_derived= TRUE;
176 }
177 
181 void struct_slave_connection::reset()
182 {
183  user= 0;
184  password= 0;
185  plugin_auth= 0;
186  plugin_dir= 0;
187 }
188 
198 bool Lex_input_stream::init(THD *thd,
199  char* buff,
200  unsigned int length)
201 {
202  DBUG_EXECUTE_IF("bug42064_simulate_oom",
203  DBUG_SET("+d,simulate_out_of_memory"););
204 
205  m_cpp_buf= (char*) thd->alloc(length + 1);
206 
207  DBUG_EXECUTE_IF("bug42064_simulate_oom",
208  DBUG_SET("-d,bug42064_simulate_oom"););
209 
210  if (m_cpp_buf == NULL)
211  return TRUE;
212 
213  m_thd= thd;
214  reset(buff, length);
215 
216  return FALSE;
217 }
218 
219 
228 void
229 Lex_input_stream::reset(char *buffer, unsigned int length)
230 {
231  yylineno= 1;
232  yytoklen= 0;
233  yylval= NULL;
234  lookahead_token= -1;
235  lookahead_yylval= NULL;
236  m_ptr= buffer;
237  m_tok_start= NULL;
238  m_tok_end= NULL;
239  m_end_of_query= buffer + length;
240  m_tok_start_prev= NULL;
241  m_buf= buffer;
242  m_buf_length= length;
243  m_echo= TRUE;
244  m_cpp_tok_start= NULL;
245  m_cpp_tok_start_prev= NULL;
246  m_cpp_tok_end= NULL;
247  m_body_utf8= NULL;
248  m_cpp_utf8_processed_ptr= NULL;
249  next_state= MY_LEX_START;
250  found_semicolon= NULL;
251  ignore_space= test(m_thd->variables.sql_mode & MODE_IGNORE_SPACE);
252  stmt_prepare_mode= FALSE;
253  multi_statements= TRUE;
254  in_comment=NO_COMMENT;
255  m_underscore_cs= NULL;
256  m_cpp_ptr= m_cpp_buf;
257 }
258 
259 
272 void Lex_input_stream::body_utf8_start(THD *thd, const char *begin_ptr)
273 {
274  DBUG_ASSERT(begin_ptr);
275  DBUG_ASSERT(m_cpp_buf <= begin_ptr && begin_ptr <= m_cpp_buf + m_buf_length);
276 
277  uint body_utf8_length=
278  (m_buf_length / thd->variables.character_set_client->mbminlen) *
279  my_charset_utf8_bin.mbmaxlen;
280 
281  m_body_utf8= (char *) thd->alloc(body_utf8_length + 1);
282  m_body_utf8_ptr= m_body_utf8;
283  *m_body_utf8_ptr= 0;
284 
285  m_cpp_utf8_processed_ptr= begin_ptr;
286 }
287 
309 void Lex_input_stream::body_utf8_append(const char *ptr,
310  const char *end_ptr)
311 {
312  DBUG_ASSERT(m_cpp_buf <= ptr && ptr <= m_cpp_buf + m_buf_length);
313  DBUG_ASSERT(m_cpp_buf <= end_ptr && end_ptr <= m_cpp_buf + m_buf_length);
314 
315  if (!m_body_utf8)
316  return;
317 
318  if (m_cpp_utf8_processed_ptr >= ptr)
319  return;
320 
321  int bytes_to_copy= ptr - m_cpp_utf8_processed_ptr;
322 
323  memcpy(m_body_utf8_ptr, m_cpp_utf8_processed_ptr, bytes_to_copy);
324  m_body_utf8_ptr += bytes_to_copy;
325  *m_body_utf8_ptr= 0;
326 
327  m_cpp_utf8_processed_ptr= end_ptr;
328 }
329 
338 void Lex_input_stream::body_utf8_append(const char *ptr)
339 {
340  body_utf8_append(ptr, ptr);
341 }
342 
355 void Lex_input_stream::body_utf8_append_literal(THD *thd,
356  const LEX_STRING *txt,
357  const CHARSET_INFO *txt_cs,
358  const char *end_ptr)
359 {
360  if (!m_cpp_utf8_processed_ptr)
361  return;
362 
363  LEX_STRING utf_txt;
364 
365  if (!my_charset_same(txt_cs, &my_charset_utf8_general_ci))
366  {
367  thd->convert_string(&utf_txt,
368  &my_charset_utf8_general_ci,
369  txt->str, (uint) txt->length,
370  txt_cs);
371  }
372  else
373  {
374  utf_txt.str= txt->str;
375  utf_txt.length= txt->length;
376  }
377 
378  /* NOTE: utf_txt.length is in bytes, not in symbols. */
379 
380  memcpy(m_body_utf8_ptr, utf_txt.str, utf_txt.length);
381  m_body_utf8_ptr += utf_txt.length;
382  *m_body_utf8_ptr= 0;
383 
384  m_cpp_utf8_processed_ptr= end_ptr;
385 }
386 
387 
388 /*
389  This is called before every query that is to be parsed.
390  Because of this, it's critical to not do too much things here.
391  (We already do too much here)
392 */
393 
394 void lex_start(THD *thd)
395 {
396  LEX *lex= thd->lex;
397  DBUG_ENTER("lex_start");
398 
399  lex->thd= lex->unit.thd= thd;
400 
401  lex->context_stack.empty();
402  lex->unit.init_query();
403  lex->unit.init_select();
404  /* 'parent_lex' is used in init_query() so it must be before it. */
405  lex->select_lex.parent_lex= lex;
406  lex->select_lex.init_query();
407  lex->load_set_str_list.empty();
408  lex->value_list.empty();
409  lex->update_list.empty();
410  lex->set_var_list.empty();
411  lex->param_list.empty();
412  lex->view_list.empty();
413  lex->prepared_stmt_params.empty();
414  lex->auxiliary_table_list.empty();
415  lex->unit.next= lex->unit.master= lex->unit.link_next= 0;
416  lex->unit.prev= lex->unit.link_prev= 0;
417  lex->unit.slave= lex->unit.global_parameters= lex->current_select=
418  lex->all_selects_list= &lex->select_lex;
419  lex->select_lex.master= &lex->unit;
420  lex->select_lex.prev= &lex->unit.slave;
421  lex->select_lex.link_next= lex->select_lex.slave= lex->select_lex.next= 0;
422  lex->select_lex.link_prev= (st_select_lex_node**)&(lex->all_selects_list);
423  lex->select_lex.options= 0;
424  lex->select_lex.sql_cache= SELECT_LEX::SQL_CACHE_UNSPECIFIED;
425  lex->select_lex.init_order();
426  lex->select_lex.group_list.empty();
427  if (lex->select_lex.group_list_ptrs)
428  lex->select_lex.group_list_ptrs->clear();
429  lex->describe= DESCRIBE_NONE;
430  lex->subqueries= FALSE;
431  lex->context_analysis_only= 0;
432  lex->derived_tables= 0;
433  lex->safe_to_cache_query= 1;
434  lex->leaf_tables_insert= 0;
435  lex->parsing_options.reset();
436  lex->empty_field_list_on_rset= 0;
437  lex->select_lex.select_number= 1;
438  lex->length=0;
439  lex->part_info= 0;
440  lex->select_lex.in_sum_expr=0;
441  lex->select_lex.ftfunc_list_alloc.empty();
442  lex->select_lex.ftfunc_list= &lex->select_lex.ftfunc_list_alloc;
443  lex->select_lex.group_list.empty();
444  lex->select_lex.order_list.empty();
445  if (lex->select_lex.order_list_ptrs)
446  lex->select_lex.order_list_ptrs->clear();
447  lex->duplicates= DUP_ERROR;
448  lex->ignore= 0;
449  lex->spname= NULL;
450  lex->sphead= NULL;
451  lex->set_sp_current_parsing_ctx(NULL);
452  lex->m_sql_cmd= NULL;
453  lex->proc_analyse= NULL;
454  lex->escape_used= FALSE;
455  lex->query_tables= 0;
456  lex->reset_query_tables_list(FALSE);
457  lex->expr_allows_subselect= TRUE;
458  lex->use_only_table_context= FALSE;
459  lex->contains_plaintext_password= false;
460 
461  lex->name.str= 0;
462  lex->name.length= 0;
463  lex->event_parse_data= NULL;
464  lex->profile_options= PROFILE_NONE;
465  lex->nest_level=0 ;
466  lex->allow_sum_func= 0;
467  lex->in_sum_func= NULL;
468  /*
469  ok, there must be a better solution for this, long-term
470  I tried "bzero" in the sql_yacc.yy code, but that for
471  some reason made the values zero, even if they were set
472  */
473  lex->server_options.server_name= 0;
474  lex->server_options.server_name_length= 0;
475  lex->server_options.host= 0;
476  lex->server_options.db= 0;
477  lex->server_options.username= 0;
478  lex->server_options.password= 0;
479  lex->server_options.scheme= 0;
480  lex->server_options.socket= 0;
481  lex->server_options.owner= 0;
482  lex->server_options.port= -1;
483  lex->explain_format= NULL;
484  lex->is_lex_started= TRUE;
485  lex->used_tables= 0;
486  lex->reset_slave_info.all= false;
487  lex->is_change_password= false;
488  lex->is_set_password_sql= false;
489  lex->mark_broken(false);
490  DBUG_VOID_RETURN;
491 }
492 
493 void lex_end(LEX *lex)
494 {
495  DBUG_ENTER("lex_end");
496  DBUG_PRINT("enter", ("lex: 0x%lx", (long) lex));
497 
498  /* release used plugins */
499  if (lex->plugins.elements) /* No function call and no mutex if no plugins. */
500  {
501  plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer,
502  lex->plugins.elements);
503  }
504  reset_dynamic(&lex->plugins);
505 
506  delete lex->sphead;
507  lex->sphead= NULL;
508 
509  DBUG_VOID_RETURN;
510 }
511 
512 Yacc_state::~Yacc_state()
513 {
514  if (yacc_yyss)
515  {
516  my_free(yacc_yyss);
517  my_free(yacc_yyvs);
518  }
519 }
520 
521 static int find_keyword(Lex_input_stream *lip, uint len, bool function)
522 {
523  const char *tok= lip->get_tok_start();
524 
525  SYMBOL *symbol= get_hash_symbol(tok, len, function);
526  if (symbol)
527  {
528  lip->yylval->symbol.symbol=symbol;
529  lip->yylval->symbol.str= (char*) tok;
530  lip->yylval->symbol.length=len;
531 
532  if ((symbol->tok == NOT_SYM) &&
533  (lip->m_thd->variables.sql_mode & MODE_HIGH_NOT_PRECEDENCE))
534  return NOT2_SYM;
535  if ((symbol->tok == OR_OR_SYM) &&
536  !(lip->m_thd->variables.sql_mode & MODE_PIPES_AS_CONCAT))
537  return OR2_SYM;
538 
539  return symbol->tok;
540  }
541  return 0;
542 }
543 
544 /*
545  Check if name is a keyword
546 
547  SYNOPSIS
548  is_keyword()
549  name checked name (must not be empty)
550  len length of checked name
551 
552  RETURN VALUES
553  0 name is a keyword
554  1 name isn't a keyword
555 */
556 
557 bool is_keyword(const char *name, uint len)
558 {
559  DBUG_ASSERT(len != 0);
560  return get_hash_symbol(name,len,0)!=0;
561 }
562 
573 bool is_lex_native_function(const LEX_STRING *name)
574 {
575  DBUG_ASSERT(name != NULL);
576  return (get_hash_symbol(name->str, (uint) name->length, 1) != 0);
577 }
578 
579 /* make a copy of token before ptr and set yytoklen */
580 
581 static LEX_STRING get_token(Lex_input_stream *lip, uint skip, uint length)
582 {
583  LEX_STRING tmp;
584  lip->yyUnget(); // ptr points now after last token char
585  tmp.length=lip->yytoklen=length;
586  tmp.str= lip->m_thd->strmake(lip->get_tok_start() + skip, tmp.length);
587 
588  lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
589  lip->m_cpp_text_end= lip->m_cpp_text_start + tmp.length;
590 
591  return tmp;
592 }
593 
594 /*
595  todo:
596  There are no dangerous charsets in mysql for function
597  get_quoted_token yet. But it should be fixed in the
598  future to operate multichar strings (like ucs2)
599 */
600 
601 static LEX_STRING get_quoted_token(Lex_input_stream *lip,
602  uint skip,
603  uint length, char quote)
604 {
605  LEX_STRING tmp;
606  const char *from, *end;
607  char *to;
608  lip->yyUnget(); // ptr points now after last token char
609  tmp.length= lip->yytoklen=length;
610  tmp.str=(char*) lip->m_thd->alloc(tmp.length+1);
611  from= lip->get_tok_start() + skip;
612  to= tmp.str;
613  end= to+length;
614 
615  lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
616  lip->m_cpp_text_end= lip->m_cpp_text_start + length;
617 
618  for ( ; to != end; )
619  {
620  if ((*to++= *from++) == quote)
621  {
622  from++; // Skip double quotes
623  lip->m_cpp_text_start++;
624  }
625  }
626  *to= 0; // End null for safety
627  return tmp;
628 }
629 
630 
631 /*
632  Return an unescaped text literal without quotes
633  Fix sometimes to do only one scan of the string
634 */
635 
636 static char *get_text(Lex_input_stream *lip, int pre_skip, int post_skip)
637 {
638  reg1 uchar c,sep;
639  uint found_escape=0;
640  const CHARSET_INFO *cs= lip->m_thd->charset();
641 
642  lip->tok_bitmap= 0;
643  sep= lip->yyGetLast(); // String should end with this
644  while (! lip->eof())
645  {
646  c= lip->yyGet();
647  lip->tok_bitmap|= c;
648 #ifdef USE_MB
649  {
650  int l;
651  if (use_mb(cs) &&
652  (l = my_ismbchar(cs,
653  lip->get_ptr() -1,
654  lip->get_end_of_query()))) {
655  lip->skip_binary(l-1);
656  continue;
657  }
658  }
659 #endif
660  if (c == '\\' &&
661  !(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))
662  { // Escaped character
663  found_escape=1;
664  if (lip->eof())
665  return 0;
666  lip->yySkip();
667  }
668  else if (c == sep)
669  {
670  if (c == lip->yyGet()) // Check if two separators in a row
671  {
672  found_escape=1; // duplicate. Remember for delete
673  continue;
674  }
675  else
676  lip->yyUnget();
677 
678  /* Found end. Unescape and return string */
679  const char *str, *end;
680  char *start;
681 
682  str= lip->get_tok_start();
683  end= lip->get_ptr();
684  /* Extract the text from the token */
685  str += pre_skip;
686  end -= post_skip;
687  DBUG_ASSERT(end >= str);
688 
689  if (!(start= (char*) lip->m_thd->alloc((uint) (end-str)+1)))
690  return (char*) ""; // Sql_alloc has set error flag
691 
692  lip->m_cpp_text_start= lip->get_cpp_tok_start() + pre_skip;
693  lip->m_cpp_text_end= lip->get_cpp_ptr() - post_skip;
694 
695  if (!found_escape)
696  {
697  lip->yytoklen=(uint) (end-str);
698  memcpy(start,str,lip->yytoklen);
699  start[lip->yytoklen]=0;
700  }
701  else
702  {
703  char *to;
704 
705  for (to=start ; str != end ; str++)
706  {
707 #ifdef USE_MB
708  int l;
709  if (use_mb(cs) &&
710  (l = my_ismbchar(cs, str, end))) {
711  while (l--)
712  *to++ = *str++;
713  str--;
714  continue;
715  }
716 #endif
717  if (!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
718  *str == '\\' && str+1 != end)
719  {
720  switch(*++str) {
721  case 'n':
722  *to++='\n';
723  break;
724  case 't':
725  *to++= '\t';
726  break;
727  case 'r':
728  *to++ = '\r';
729  break;
730  case 'b':
731  *to++ = '\b';
732  break;
733  case '0':
734  *to++= 0; // Ascii null
735  break;
736  case 'Z': // ^Z must be escaped on Win32
737  *to++='\032';
738  break;
739  case '_':
740  case '%':
741  *to++= '\\'; // remember prefix for wildcard
742  /* Fall through */
743  default:
744  *to++= *str;
745  break;
746  }
747  }
748  else if (*str == sep)
749  *to++= *str++; // Two ' or "
750  else
751  *to++ = *str;
752  }
753  *to=0;
754  lip->yytoklen=(uint) (to-start);
755  }
756  return start;
757  }
758  }
759  return 0; // unexpected end of query
760 }
761 
762 
763 /*
764 ** Calc type of integer; long integer, longlong integer or real.
765 ** Returns smallest type that match the string.
766 ** When using unsigned long long values the result is converted to a real
767 ** because else they will be unexpected sign changes because all calculation
768 ** is done with longlong or double.
769 */
770 
771 static const char *long_str="2147483647";
772 static const uint long_len=10;
773 static const char *signed_long_str="-2147483648";
774 static const char *longlong_str="9223372036854775807";
775 static const uint longlong_len=19;
776 static const char *signed_longlong_str="-9223372036854775808";
777 static const uint signed_longlong_len=19;
778 static const char *unsigned_longlong_str="18446744073709551615";
779 static const uint unsigned_longlong_len=20;
780 
781 static inline uint int_token(const char *str,uint length)
782 {
783  if (length < long_len) // quick normal case
784  return NUM;
785  bool neg=0;
786 
787  if (*str == '+') // Remove sign and pre-zeros
788  {
789  str++; length--;
790  }
791  else if (*str == '-')
792  {
793  str++; length--;
794  neg=1;
795  }
796  while (*str == '0' && length)
797  {
798  str++; length --;
799  }
800  if (length < long_len)
801  return NUM;
802 
803  uint smaller,bigger;
804  const char *cmp;
805  if (neg)
806  {
807  if (length == long_len)
808  {
809  cmp= signed_long_str+1;
810  smaller=NUM; // If <= signed_long_str
811  bigger=LONG_NUM; // If >= signed_long_str
812  }
813  else if (length < signed_longlong_len)
814  return LONG_NUM;
815  else if (length > signed_longlong_len)
816  return DECIMAL_NUM;
817  else
818  {
819  cmp=signed_longlong_str+1;
820  smaller=LONG_NUM; // If <= signed_longlong_str
821  bigger=DECIMAL_NUM;
822  }
823  }
824  else
825  {
826  if (length == long_len)
827  {
828  cmp= long_str;
829  smaller=NUM;
830  bigger=LONG_NUM;
831  }
832  else if (length < longlong_len)
833  return LONG_NUM;
834  else if (length > longlong_len)
835  {
836  if (length > unsigned_longlong_len)
837  return DECIMAL_NUM;
838  cmp=unsigned_longlong_str;
839  smaller=ULONGLONG_NUM;
840  bigger=DECIMAL_NUM;
841  }
842  else
843  {
844  cmp=longlong_str;
845  smaller=LONG_NUM;
846  bigger= ULONGLONG_NUM;
847  }
848  }
849  while (*cmp && *cmp++ == *str++) ;
850  return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
851 }
852 
853 
866 bool consume_comment(Lex_input_stream *lip, int remaining_recursions_permitted)
867 {
868  reg1 uchar c;
869  while (! lip->eof())
870  {
871  c= lip->yyGet();
872 
873  if (remaining_recursions_permitted > 0)
874  {
875  if ((c == '/') && (lip->yyPeek() == '*'))
876  {
877  lip->yySkip(); /* Eat asterisk */
878  consume_comment(lip, remaining_recursions_permitted-1);
879  continue;
880  }
881  }
882 
883  if (c == '*')
884  {
885  if (lip->yyPeek() == '/')
886  {
887  lip->yySkip(); /* Eat slash */
888  return FALSE;
889  }
890  }
891 
892  if (c == '\n')
893  lip->yylineno++;
894  }
895 
896  return TRUE;
897 }
898 
899 
900 /*
901  MYSQLlex remember the following states from the following MYSQLlex()
902 
903  - MY_LEX_EOQ Found end of query
904  - MY_LEX_OPERATOR_OR_IDENT Last state was an ident, text or number
905  (which can't be followed by a signed number)
906 */
907 
908 int MYSQLlex(void *arg, void *yythd)
909 {
910  THD *thd= (THD *)yythd;
911  Lex_input_stream *lip= & thd->m_parser_state->m_lip;
912  YYSTYPE *yylval=(YYSTYPE*) arg;
913  int token;
914 
915  if (lip->lookahead_token >= 0)
916  {
917  /*
918  The next token was already parsed in advance,
919  return it.
920  */
921  token= lip->lookahead_token;
922  lip->lookahead_token= -1;
923  *yylval= *(lip->lookahead_yylval);
924  lip->lookahead_yylval= NULL;
925  lip->m_digest_psi= MYSQL_ADD_TOKEN(lip->m_digest_psi, token, yylval);
926  return token;
927  }
928 
929  token= lex_one_token(arg, yythd);
930 
931  switch(token) {
932  case WITH:
933  /*
934  Parsing 'WITH' 'ROLLUP' or 'WITH' 'CUBE' requires 2 look ups,
935  which makes the grammar LALR(2).
936  Replace by a single 'WITH_ROLLUP' or 'WITH_CUBE' token,
937  to transform the grammar into a LALR(1) grammar,
938  which sql_yacc.yy can process.
939  */
940  token= lex_one_token(arg, yythd);
941  switch(token) {
942  case CUBE_SYM:
943  lip->m_digest_psi= MYSQL_ADD_TOKEN(lip->m_digest_psi, WITH_CUBE_SYM,
944  yylval);
945  return WITH_CUBE_SYM;
946  case ROLLUP_SYM:
947  lip->m_digest_psi= MYSQL_ADD_TOKEN(lip->m_digest_psi, WITH_ROLLUP_SYM,
948  yylval);
949  return WITH_ROLLUP_SYM;
950  default:
951  /*
952  Save the token following 'WITH'
953  */
954  lip->lookahead_yylval= lip->yylval;
955  lip->yylval= NULL;
956  lip->lookahead_token= token;
957  lip->m_digest_psi= MYSQL_ADD_TOKEN(lip->m_digest_psi, WITH, yylval);
958  return WITH;
959  }
960  break;
961  default:
962  break;
963  }
964 
965  lip->m_digest_psi= MYSQL_ADD_TOKEN(lip->m_digest_psi, token, yylval);
966  return token;
967 }
968 
969 int lex_one_token(void *arg, void *yythd)
970 {
971  reg1 uchar c= 0;
972  bool comment_closed;
973  int tokval, result_state;
974  uint length;
975  enum my_lex_states state;
976  THD *thd= (THD *)yythd;
977  Lex_input_stream *lip= & thd->m_parser_state->m_lip;
978  LEX *lex= thd->lex;
979  YYSTYPE *yylval=(YYSTYPE*) arg;
980  const CHARSET_INFO *cs= thd->charset();
981  uchar *state_map= cs->state_map;
982  uchar *ident_map= cs->ident_map;
983 
984  lip->yylval=yylval; // The global state
985 
986  lip->start_token();
987  state=lip->next_state;
988  lip->next_state=MY_LEX_OPERATOR_OR_IDENT;
989  for (;;)
990  {
991  switch (state) {
992  case MY_LEX_OPERATOR_OR_IDENT: // Next is operator or keyword
993  case MY_LEX_START: // Start of token
994  // Skip starting whitespace
995  while(state_map[c= lip->yyPeek()] == MY_LEX_SKIP)
996  {
997  if (c == '\n')
998  lip->yylineno++;
999 
1000  lip->yySkip();
1001  }
1002 
1003  /* Start of real token */
1004  lip->restart_token();
1005  c= lip->yyGet();
1006  state= (enum my_lex_states) state_map[c];
1007  break;
1008  case MY_LEX_ESCAPE:
1009  if (lip->yyGet() == 'N')
1010  { // Allow \N as shortcut for NULL
1011  yylval->lex_str.str=(char*) "\\N";
1012  yylval->lex_str.length=2;
1013  return NULL_SYM;
1014  }
1015  case MY_LEX_CHAR: // Unknown or single char token
1016  case MY_LEX_SKIP: // This should not happen
1017  if (c == '-' && lip->yyPeek() == '-' &&
1018  (my_isspace(cs,lip->yyPeekn(1)) ||
1019  my_iscntrl(cs,lip->yyPeekn(1))))
1020  {
1021  state=MY_LEX_COMMENT;
1022  break;
1023  }
1024 
1025  if (c != ')')
1026  lip->next_state= MY_LEX_START; // Allow signed numbers
1027 
1028  if (c == ',')
1029  {
1030  /*
1031  Warning:
1032  This is a work around, to make the "remember_name" rule in
1033  sql/sql_yacc.yy work properly.
1034  The problem is that, when parsing "select expr1, expr2",
1035  the code generated by bison executes the *pre* action
1036  remember_name (see select_item) *before* actually parsing the
1037  first token of expr2.
1038  */
1039  lip->restart_token();
1040  }
1041  else
1042  {
1043  /*
1044  Check for a placeholder: it should not precede a possible identifier
1045  because of binlogging: when a placeholder is replaced with
1046  its value in a query for the binlog, the query must stay
1047  grammatically correct.
1048  */
1049  if (c == '?' && lip->stmt_prepare_mode && !ident_map[lip->yyPeek()])
1050  return(PARAM_MARKER);
1051  }
1052 
1053  return((int) c);
1054 
1055  case MY_LEX_IDENT_OR_NCHAR:
1056  if (lip->yyPeek() != '\'')
1057  {
1058  state= MY_LEX_IDENT;
1059  break;
1060  }
1061  /* Found N'string' */
1062  lip->yySkip(); // Skip '
1063  if (!(yylval->lex_str.str = get_text(lip, 2, 1)))
1064  {
1065  state= MY_LEX_CHAR; // Read char by char
1066  break;
1067  }
1068  yylval->lex_str.length= lip->yytoklen;
1069  lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
1070  return(NCHAR_STRING);
1071 
1072  case MY_LEX_IDENT_OR_HEX:
1073  if (lip->yyPeek() == '\'')
1074  { // Found x'hex-number'
1075  state= MY_LEX_HEX_NUMBER;
1076  break;
1077  }
1078  case MY_LEX_IDENT_OR_BIN:
1079  if (lip->yyPeek() == '\'')
1080  { // Found b'bin-number'
1081  state= MY_LEX_BIN_NUMBER;
1082  break;
1083  }
1084  case MY_LEX_IDENT:
1085  const char *start;
1086 #if defined(USE_MB) && defined(USE_MB_IDENT)
1087  if (use_mb(cs))
1088  {
1089  result_state= IDENT_QUOTED;
1090  if (my_mbcharlen(cs, lip->yyGetLast()) > 1)
1091  {
1092  int l = my_ismbchar(cs,
1093  lip->get_ptr() -1,
1094  lip->get_end_of_query());
1095  if (l == 0) {
1096  state = MY_LEX_CHAR;
1097  continue;
1098  }
1099  lip->skip_binary(l - 1);
1100  }
1101  while (ident_map[c=lip->yyGet()])
1102  {
1103  if (my_mbcharlen(cs, c) > 1)
1104  {
1105  int l;
1106  if ((l = my_ismbchar(cs,
1107  lip->get_ptr() -1,
1108  lip->get_end_of_query())) == 0)
1109  break;
1110  lip->skip_binary(l-1);
1111  }
1112  }
1113  }
1114  else
1115 #endif
1116  {
1117  for (result_state= c; ident_map[c= lip->yyGet()]; result_state|= c) ;
1118  /* If there were non-ASCII characters, mark that we must convert */
1119  result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1120  }
1121  length= lip->yyLength();
1122  start= lip->get_ptr();
1123  if (lip->ignore_space)
1124  {
1125  /*
1126  If we find a space then this can't be an identifier. We notice this
1127  below by checking start != lex->ptr.
1128  */
1129  for (; state_map[c] == MY_LEX_SKIP ; c= lip->yyGet()) ;
1130  }
1131  if (start == lip->get_ptr() && c == '.' && ident_map[lip->yyPeek()])
1132  lip->next_state=MY_LEX_IDENT_SEP;
1133  else
1134  { // '(' must follow directly if function
1135  lip->yyUnget();
1136  if ((tokval = find_keyword(lip, length, c == '(')))
1137  {
1138  lip->next_state= MY_LEX_START; // Allow signed numbers
1139  return(tokval); // Was keyword
1140  }
1141  lip->yySkip(); // next state does a unget
1142  }
1143  yylval->lex_str=get_token(lip, 0, length);
1144 
1145  /*
1146  Note: "SELECT _bla AS 'alias'"
1147  _bla should be considered as a IDENT if charset haven't been found.
1148  So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
1149  producing an error.
1150  */
1151 
1152  if (yylval->lex_str.str[0] == '_')
1153  {
1154  CHARSET_INFO *cs= get_charset_by_csname(yylval->lex_str.str + 1,
1155  MY_CS_PRIMARY, MYF(0));
1156  if (cs)
1157  {
1158  yylval->charset= cs;
1159  lip->m_underscore_cs= cs;
1160 
1161  lip->body_utf8_append(lip->m_cpp_text_start,
1162  lip->get_cpp_tok_start() + length);
1163  return(UNDERSCORE_CHARSET);
1164  }
1165  }
1166 
1167  lip->body_utf8_append(lip->m_cpp_text_start);
1168 
1169  lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1170  lip->m_cpp_text_end);
1171 
1172  return(result_state); // IDENT or IDENT_QUOTED
1173 
1174  case MY_LEX_IDENT_SEP: // Found ident and now '.'
1175  yylval->lex_str.str= (char*) lip->get_ptr();
1176  yylval->lex_str.length= 1;
1177  c= lip->yyGet(); // should be '.'
1178  lip->next_state= MY_LEX_IDENT_START;// Next is an ident (not a keyword)
1179  if (!ident_map[lip->yyPeek()]) // Probably ` or "
1180  lip->next_state= MY_LEX_START;
1181  return((int) c);
1182 
1183  case MY_LEX_NUMBER_IDENT: // number or ident which num-start
1184  if (lip->yyGetLast() == '0')
1185  {
1186  c= lip->yyGet();
1187  if (c == 'x')
1188  {
1189  while (my_isxdigit(cs,(c = lip->yyGet()))) ;
1190  if ((lip->yyLength() >= 3) && !ident_map[c])
1191  {
1192  /* skip '0x' */
1193  yylval->lex_str=get_token(lip, 2, lip->yyLength()-2);
1194  return (HEX_NUM);
1195  }
1196  lip->yyUnget();
1197  state= MY_LEX_IDENT_START;
1198  break;
1199  }
1200  else if (c == 'b')
1201  {
1202  while ((c= lip->yyGet()) == '0' || c == '1') ;
1203  if ((lip->yyLength() >= 3) && !ident_map[c])
1204  {
1205  /* Skip '0b' */
1206  yylval->lex_str= get_token(lip, 2, lip->yyLength()-2);
1207  return (BIN_NUM);
1208  }
1209  lip->yyUnget();
1210  state= MY_LEX_IDENT_START;
1211  break;
1212  }
1213  lip->yyUnget();
1214  }
1215 
1216  while (my_isdigit(cs, (c = lip->yyGet()))) ;
1217  if (!ident_map[c])
1218  { // Can't be identifier
1219  state=MY_LEX_INT_OR_REAL;
1220  break;
1221  }
1222  if (c == 'e' || c == 'E')
1223  {
1224  // The following test is written this way to allow numbers of type 1e1
1225  if (my_isdigit(cs,lip->yyPeek()) ||
1226  (c=(lip->yyGet())) == '+' || c == '-')
1227  { // Allow 1E+10
1228  if (my_isdigit(cs,lip->yyPeek())) // Number must have digit after sign
1229  {
1230  lip->yySkip();
1231  while (my_isdigit(cs,lip->yyGet())) ;
1232  yylval->lex_str=get_token(lip, 0, lip->yyLength());
1233  return(FLOAT_NUM);
1234  }
1235  }
1236  lip->yyUnget();
1237  }
1238  // fall through
1239  case MY_LEX_IDENT_START: // We come here after '.'
1240  result_state= IDENT;
1241 #if defined(USE_MB) && defined(USE_MB_IDENT)
1242  if (use_mb(cs))
1243  {
1244  result_state= IDENT_QUOTED;
1245  while (ident_map[c=lip->yyGet()])
1246  {
1247  if (my_mbcharlen(cs, c) > 1)
1248  {
1249  int l;
1250  if ((l = my_ismbchar(cs,
1251  lip->get_ptr() -1,
1252  lip->get_end_of_query())) == 0)
1253  break;
1254  lip->skip_binary(l-1);
1255  }
1256  }
1257  }
1258  else
1259 #endif
1260  {
1261  for (result_state=0; ident_map[c= lip->yyGet()]; result_state|= c) ;
1262  /* If there were non-ASCII characters, mark that we must convert */
1263  result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1264  }
1265  if (c == '.' && ident_map[lip->yyPeek()])
1266  lip->next_state=MY_LEX_IDENT_SEP;// Next is '.'
1267 
1268  yylval->lex_str= get_token(lip, 0, lip->yyLength());
1269 
1270  lip->body_utf8_append(lip->m_cpp_text_start);
1271 
1272  lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1273  lip->m_cpp_text_end);
1274 
1275  return(result_state);
1276 
1277  case MY_LEX_USER_VARIABLE_DELIMITER: // Found quote char
1278  {
1279  uint double_quotes= 0;
1280  char quote_char= c; // Used char
1281  for(;;)
1282  {
1283  c= lip->yyGet();
1284  if (c == 0)
1285  {
1286  lip->yyUnget();
1287  return ABORT_SYM; // Unmatched quotes
1288  }
1289 
1290  int var_length;
1291  if ((var_length= my_mbcharlen(cs, c)) == 1)
1292  {
1293  if (c == quote_char)
1294  {
1295  if (lip->yyPeek() != quote_char)
1296  break;
1297  c=lip->yyGet();
1298  double_quotes++;
1299  continue;
1300  }
1301  }
1302 #ifdef USE_MB
1303  else if (use_mb(cs))
1304  {
1305  if ((var_length= my_ismbchar(cs, lip->get_ptr() - 1,
1306  lip->get_end_of_query())))
1307  lip->skip_binary(var_length-1);
1308  }
1309 #endif
1310  }
1311  if (double_quotes)
1312  yylval->lex_str=get_quoted_token(lip, 1,
1313  lip->yyLength() - double_quotes -1,
1314  quote_char);
1315  else
1316  yylval->lex_str=get_token(lip, 1, lip->yyLength() -1);
1317  if (c == quote_char)
1318  lip->yySkip(); // Skip end `
1319  lip->next_state= MY_LEX_START;
1320 
1321  lip->body_utf8_append(lip->m_cpp_text_start);
1322 
1323  lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1324  lip->m_cpp_text_end);
1325 
1326  return(IDENT_QUOTED);
1327  }
1328  case MY_LEX_INT_OR_REAL: // Complete int or incomplete real
1329  if (c != '.')
1330  { // Found complete integer number.
1331  yylval->lex_str=get_token(lip, 0, lip->yyLength());
1332  return int_token(yylval->lex_str.str, (uint) yylval->lex_str.length);
1333  }
1334  // fall through
1335  case MY_LEX_REAL: // Incomplete real number
1336  while (my_isdigit(cs,c = lip->yyGet())) ;
1337 
1338  if (c == 'e' || c == 'E')
1339  {
1340  c = lip->yyGet();
1341  if (c == '-' || c == '+')
1342  c = lip->yyGet(); // Skip sign
1343  if (!my_isdigit(cs,c))
1344  { // No digit after sign
1345  state= MY_LEX_CHAR;
1346  break;
1347  }
1348  while (my_isdigit(cs,lip->yyGet())) ;
1349  yylval->lex_str=get_token(lip, 0, lip->yyLength());
1350  return(FLOAT_NUM);
1351  }
1352  yylval->lex_str=get_token(lip, 0, lip->yyLength());
1353  return(DECIMAL_NUM);
1354 
1355  case MY_LEX_HEX_NUMBER: // Found x'hexstring'
1356  lip->yySkip(); // Accept opening '
1357  while (my_isxdigit(cs, (c= lip->yyGet()))) ;
1358  if (c != '\'')
1359  return(ABORT_SYM); // Illegal hex constant
1360  lip->yySkip(); // Accept closing '
1361  length= lip->yyLength(); // Length of hexnum+3
1362  if ((length % 2) == 0)
1363  return(ABORT_SYM); // odd number of hex digits
1364  yylval->lex_str=get_token(lip,
1365  2, // skip x'
1366  length-3); // don't count x' and last '
1367  return (HEX_NUM);
1368 
1369  case MY_LEX_BIN_NUMBER: // Found b'bin-string'
1370  lip->yySkip(); // Accept opening '
1371  while ((c= lip->yyGet()) == '0' || c == '1') ;
1372  if (c != '\'')
1373  return(ABORT_SYM); // Illegal hex constant
1374  lip->yySkip(); // Accept closing '
1375  length= lip->yyLength(); // Length of bin-num + 3
1376  yylval->lex_str= get_token(lip,
1377  2, // skip b'
1378  length-3); // don't count b' and last '
1379  return (BIN_NUM);
1380 
1381  case MY_LEX_CMP_OP: // Incomplete comparison operator
1382  if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP ||
1383  state_map[lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
1384  lip->yySkip();
1385  if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
1386  {
1387  lip->next_state= MY_LEX_START; // Allow signed numbers
1388  return(tokval);
1389  }
1390  state = MY_LEX_CHAR; // Something fishy found
1391  break;
1392 
1393  case MY_LEX_LONG_CMP_OP: // Incomplete comparison operator
1394  if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP ||
1395  state_map[lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
1396  {
1397  lip->yySkip();
1398  if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP)
1399  lip->yySkip();
1400  }
1401  if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
1402  {
1403  lip->next_state= MY_LEX_START; // Found long op
1404  return(tokval);
1405  }
1406  state = MY_LEX_CHAR; // Something fishy found
1407  break;
1408 
1409  case MY_LEX_BOOL:
1410  if (c != lip->yyPeek())
1411  {
1412  state=MY_LEX_CHAR;
1413  break;
1414  }
1415  lip->yySkip();
1416  tokval = find_keyword(lip,2,0); // Is a bool operator
1417  lip->next_state= MY_LEX_START; // Allow signed numbers
1418  return(tokval);
1419 
1420  case MY_LEX_STRING_OR_DELIMITER:
1421  if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
1422  {
1423  state= MY_LEX_USER_VARIABLE_DELIMITER;
1424  break;
1425  }
1426  /* " used for strings */
1427  case MY_LEX_STRING: // Incomplete text string
1428  if (!(yylval->lex_str.str = get_text(lip, 1, 1)))
1429  {
1430  state= MY_LEX_CHAR; // Read char by char
1431  break;
1432  }
1433  yylval->lex_str.length=lip->yytoklen;
1434 
1435  lip->body_utf8_append(lip->m_cpp_text_start);
1436 
1437  lip->body_utf8_append_literal(thd, &yylval->lex_str,
1438  lip->m_underscore_cs ? lip->m_underscore_cs : cs,
1439  lip->m_cpp_text_end);
1440 
1441  lip->m_underscore_cs= NULL;
1442 
1443  lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
1444  return(TEXT_STRING);
1445 
1446  case MY_LEX_COMMENT: // Comment
1447  lex->select_lex.options|= OPTION_FOUND_COMMENT;
1448  while ((c = lip->yyGet()) != '\n' && c) ;
1449  lip->yyUnget(); // Safety against eof
1450  state = MY_LEX_START; // Try again
1451  break;
1452  case MY_LEX_LONG_COMMENT: /* Long C comment? */
1453  if (lip->yyPeek() != '*')
1454  {
1455  state=MY_LEX_CHAR; // Probable division
1456  break;
1457  }
1458  lex->select_lex.options|= OPTION_FOUND_COMMENT;
1459  /* Reject '/' '*', since we might need to turn off the echo */
1460  lip->yyUnget();
1461 
1462  lip->save_in_comment_state();
1463 
1464  if (lip->yyPeekn(2) == '!')
1465  {
1466  lip->in_comment= DISCARD_COMMENT;
1467  /* Accept '/' '*' '!', but do not keep this marker. */
1468  lip->set_echo(FALSE);
1469  lip->yySkip();
1470  lip->yySkip();
1471  lip->yySkip();
1472 
1473  /*
1474  The special comment format is very strict:
1475  '/' '*' '!', followed by exactly
1476  1 digit (major), 2 digits (minor), then 2 digits (dot).
1477  32302 -> 3.23.02
1478  50032 -> 5.0.32
1479  50114 -> 5.1.14
1480  */
1481  char version_str[6];
1482  version_str[0]= lip->yyPeekn(0);
1483  version_str[1]= lip->yyPeekn(1);
1484  version_str[2]= lip->yyPeekn(2);
1485  version_str[3]= lip->yyPeekn(3);
1486  version_str[4]= lip->yyPeekn(4);
1487  version_str[5]= 0;
1488  if ( my_isdigit(cs, version_str[0])
1489  && my_isdigit(cs, version_str[1])
1490  && my_isdigit(cs, version_str[2])
1491  && my_isdigit(cs, version_str[3])
1492  && my_isdigit(cs, version_str[4])
1493  )
1494  {
1495  ulong version;
1496  version=strtol(version_str, NULL, 10);
1497 
1498  if (version <= MYSQL_VERSION_ID)
1499  {
1500  /* Accept 'M' 'm' 'm' 'd' 'd' */
1501  lip->yySkipn(5);
1502  /* Expand the content of the special comment as real code */
1503  lip->set_echo(TRUE);
1504  state=MY_LEX_START;
1505  break; /* Do not treat contents as a comment. */
1506  }
1507  else
1508  {
1509  /*
1510  Patch and skip the conditional comment to avoid it
1511  being propagated infinitely (eg. to a slave).
1512  */
1513  char *pcom= lip->yyUnput(' ');
1514  comment_closed= ! consume_comment(lip, 1);
1515  if (! comment_closed)
1516  {
1517  *pcom= '!';
1518  }
1519  /* version allowed to have one level of comment inside. */
1520  }
1521  }
1522  else
1523  {
1524  /* Not a version comment. */
1525  state=MY_LEX_START;
1526  lip->set_echo(TRUE);
1527  break;
1528  }
1529  }
1530  else
1531  {
1532  lip->in_comment= PRESERVE_COMMENT;
1533  lip->yySkip(); // Accept /
1534  lip->yySkip(); // Accept *
1535  comment_closed= ! consume_comment(lip, 0);
1536  /* regular comments can have zero comments inside. */
1537  }
1538  /*
1539  Discard:
1540  - regular '/' '*' comments,
1541  - special comments '/' '*' '!' for a future version,
1542  by scanning until we find a closing '*' '/' marker.
1543 
1544  Nesting regular comments isn't allowed. The first
1545  '*' '/' returns the parser to the previous state.
1546 
1547  /#!VERSI oned containing /# regular #/ is allowed #/
1548 
1549  Inside one versioned comment, another versioned comment
1550  is treated as a regular discardable comment. It gets
1551  no special parsing.
1552  */
1553 
1554  /* Unbalanced comments with a missing '*' '/' are a syntax error */
1555  if (! comment_closed)
1556  return (ABORT_SYM);
1557  state = MY_LEX_START; // Try again
1558  lip->restore_in_comment_state();
1559  break;
1560  case MY_LEX_END_LONG_COMMENT:
1561  if ((lip->in_comment != NO_COMMENT) && lip->yyPeek() == '/')
1562  {
1563  /* Reject '*' '/' */
1564  lip->yyUnget();
1565  /* Accept '*' '/', with the proper echo */
1566  lip->set_echo(lip->in_comment == PRESERVE_COMMENT);
1567  lip->yySkipn(2);
1568  /* And start recording the tokens again */
1569  lip->set_echo(TRUE);
1570 
1571  /*
1572  C-style comments are replaced with a single space (as it
1573  is in C and C++). If there is already a whitespace
1574  character at this point in the stream, the space is
1575  not inserted.
1576 
1577  See also ISO/IEC 9899:1999 §5.1.1.2
1578  ("Programming languages — C")
1579  */
1580  if (!my_isspace(cs, lip->yyPeek()) &&
1581  lip->get_cpp_ptr() != lip->get_cpp_buf() &&
1582  !my_isspace(cs, *(lip->get_cpp_ptr() - 1)))
1583  lip->cpp_inject(' ');
1584 
1585  lip->in_comment=NO_COMMENT;
1586  state=MY_LEX_START;
1587  }
1588  else
1589  state=MY_LEX_CHAR; // Return '*'
1590  break;
1591  case MY_LEX_SET_VAR: // Check if ':='
1592  if (lip->yyPeek() != '=')
1593  {
1594  state=MY_LEX_CHAR; // Return ':'
1595  break;
1596  }
1597  lip->yySkip();
1598  return (SET_VAR);
1599  case MY_LEX_SEMICOLON: // optional line terminator
1600  state= MY_LEX_CHAR; // Return ';'
1601  break;
1602  case MY_LEX_EOL:
1603  if (lip->eof())
1604  {
1605  lip->yyUnget(); // Reject the last '\0'
1606  lip->set_echo(FALSE);
1607  lip->yySkip();
1608  lip->set_echo(TRUE);
1609  /* Unbalanced comments with a missing '*' '/' are a syntax error */
1610  if (lip->in_comment != NO_COMMENT)
1611  return (ABORT_SYM);
1612  lip->next_state=MY_LEX_END; // Mark for next loop
1613  return(END_OF_INPUT);
1614  }
1615  state=MY_LEX_CHAR;
1616  break;
1617  case MY_LEX_END:
1618  lip->next_state=MY_LEX_END;
1619  return(0); // We found end of input last time
1620 
1621  /* Actually real shouldn't start with . but allow them anyhow */
1622  case MY_LEX_REAL_OR_POINT:
1623  if (my_isdigit(cs,lip->yyPeek()))
1624  state = MY_LEX_REAL; // Real
1625  else
1626  {
1627  state= MY_LEX_IDENT_SEP; // return '.'
1628  lip->yyUnget(); // Put back '.'
1629  }
1630  break;
1631  case MY_LEX_USER_END: // end '@' of user@hostname
1632  switch (state_map[lip->yyPeek()]) {
1633  case MY_LEX_STRING:
1634  case MY_LEX_USER_VARIABLE_DELIMITER:
1635  case MY_LEX_STRING_OR_DELIMITER:
1636  break;
1637  case MY_LEX_USER_END:
1638  lip->next_state=MY_LEX_SYSTEM_VAR;
1639  break;
1640  default:
1641  lip->next_state=MY_LEX_HOSTNAME;
1642  break;
1643  }
1644  yylval->lex_str.str=(char*) lip->get_ptr();
1645  yylval->lex_str.length=1;
1646  return((int) '@');
1647  case MY_LEX_HOSTNAME: // end '@' of user@hostname
1648  for (c=lip->yyGet() ;
1649  my_isalnum(cs,c) || c == '.' || c == '_' || c == '$';
1650  c= lip->yyGet()) ;
1651  yylval->lex_str=get_token(lip, 0, lip->yyLength());
1652  return(LEX_HOSTNAME);
1653  case MY_LEX_SYSTEM_VAR:
1654  yylval->lex_str.str=(char*) lip->get_ptr();
1655  yylval->lex_str.length=1;
1656  lip->yySkip(); // Skip '@'
1657  lip->next_state= (state_map[lip->yyPeek()] ==
1658  MY_LEX_USER_VARIABLE_DELIMITER ?
1659  MY_LEX_OPERATOR_OR_IDENT :
1660  MY_LEX_IDENT_OR_KEYWORD);
1661  return((int) '@');
1662  case MY_LEX_IDENT_OR_KEYWORD:
1663  /*
1664  We come here when we have found two '@' in a row.
1665  We should now be able to handle:
1666  [(global | local | session) .]variable_name
1667  */
1668 
1669  for (result_state= 0; ident_map[c= lip->yyGet()]; result_state|= c) ;
1670  /* If there were non-ASCII characters, mark that we must convert */
1671  result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1672 
1673  if (c == '.')
1674  lip->next_state=MY_LEX_IDENT_SEP;
1675  length= lip->yyLength();
1676  if (length == 0)
1677  return(ABORT_SYM); // Names must be nonempty.
1678  if ((tokval= find_keyword(lip, length,0)))
1679  {
1680  lip->yyUnget(); // Put back 'c'
1681  return(tokval); // Was keyword
1682  }
1683  yylval->lex_str=get_token(lip, 0, length);
1684 
1685  lip->body_utf8_append(lip->m_cpp_text_start);
1686 
1687  lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1688  lip->m_cpp_text_end);
1689 
1690  return(result_state);
1691  }
1692  }
1693 }
1694 
1695 
1696 void trim_whitespace(const CHARSET_INFO *cs, LEX_STRING *str)
1697 {
1698  /*
1699  TODO:
1700  This code assumes that there are no multi-bytes characters
1701  that can be considered white-space.
1702  */
1703 
1704  while ((str->length > 0) && (my_isspace(cs, str->str[0])))
1705  {
1706  str->length --;
1707  str->str ++;
1708  }
1709 
1710  /*
1711  FIXME:
1712  Also, parsing backward is not safe with multi bytes characters
1713  */
1714  while ((str->length > 0) && (my_isspace(cs, str->str[str->length-1])))
1715  {
1716  str->length --;
1717  /* set trailing spaces to 0 as there're places that don't respect length */
1718  str->str[str->length]= 0;
1719  }
1720 }
1721 
1722 
1723 /*
1724  st_select_lex structures initialisations
1725 */
1726 
1727 void st_select_lex_node::init_query()
1728 {
1729  options= 0;
1730  sql_cache= SQL_CACHE_UNSPECIFIED;
1731  linkage= UNSPECIFIED_TYPE;
1732  no_error= no_table_names_allowed= 0;
1733  uncacheable= 0;
1734 }
1735 
1736 void st_select_lex_node::init_select()
1737 {
1738 }
1739 
1740 void st_select_lex_unit::init_query()
1741 {
1742  st_select_lex_node::init_query();
1743  linkage= GLOBAL_OPTIONS_TYPE;
1744  global_parameters= first_select();
1745  select_limit_cnt= HA_POS_ERROR;
1746  offset_limit_cnt= 0;
1747  union_distinct= 0;
1748  prepared= optimized= executed= 0;
1749  item= 0;
1750  union_result= 0;
1751  table= 0;
1752  fake_select_lex= 0;
1753  cleaned= 0;
1754  item_list.empty();
1755  describe= 0;
1756  found_rows_for_union= 0;
1757  result= NULL;
1758 }
1759 
1760 void st_select_lex::init_query()
1761 {
1762  st_select_lex_node::init_query();
1763  resolve_place= RESOLVE_NONE;
1764  resolve_nest= NULL;
1765  table_list.empty();
1766  top_join_list.empty();
1767  join_list= &top_join_list;
1768  embedding= leaf_tables= 0;
1769  item_list.empty();
1770  join= 0;
1771  having= prep_having= where= prep_where= 0;
1772  olap= UNSPECIFIED_OLAP_TYPE;
1773  having_fix_field= 0;
1774  group_fix_field= 0;
1775  context.select_lex= this;
1776  context.init();
1777  /*
1778  Add the name resolution context of the current (sub)query to the
1779  stack of contexts for the whole query.
1780  TODO:
1781  push_context may return an error if there is no memory for a new
1782  element in the stack, however this method has no return value,
1783  thus push_context should be moved to a place where query
1784  initialization is checked for failure.
1785  */
1786  parent_lex->push_context(&context);
1787  cond_count= between_count= with_wild= 0;
1788  max_equal_elems= 0;
1789  ref_pointer_array.reset();
1790  select_n_where_fields= 0;
1791  select_n_having_items= 0;
1792  n_sum_items= 0;
1793  n_child_sum_items= 0;
1794  subquery_in_having= explicit_limit= 0;
1795  is_item_list_lookup= 0;
1796  first_execution= 1;
1797  first_natural_join_processing= 1;
1798  first_cond_optimization= 1;
1799  parsing_place= NO_MATTER;
1800  exclude_from_table_unique_test= no_wrap_view_item= FALSE;
1801  nest_level= 0;
1802  link_next= 0;
1803  select_list_tables= 0;
1804  m_non_agg_field_used= false;
1805  m_agg_func_used= false;
1806  with_sum_func= false;
1807  removed_select= NULL;
1808 }
1809 
1810 void st_select_lex::init_select()
1811 {
1812  st_select_lex_node::init_select();
1813  sj_nests.empty();
1814  group_list.empty();
1815  if (group_list_ptrs)
1816  group_list_ptrs->clear();
1817  db= 0;
1818  having= 0;
1819  table_join_options= 0;
1820  in_sum_expr= with_wild= 0;
1821  options= 0;
1822  sql_cache= SQL_CACHE_UNSPECIFIED;
1823  braces= 0;
1824  interval_list.empty();
1825  ftfunc_list_alloc.empty();
1826  inner_sum_func_list= 0;
1827  ftfunc_list= &ftfunc_list_alloc;
1828  linkage= UNSPECIFIED_TYPE;
1829  order_list.elements= 0;
1830  order_list.first= 0;
1831  order_list.next= &order_list.first;
1832  if (order_list_ptrs)
1833  order_list_ptrs->clear();
1834  /* Set limit and offset to default values */
1835  select_limit= 0; /* denotes the default limit = HA_POS_ERROR */
1836  offset_limit= 0; /* denotes the default offset = 0 */
1837  with_sum_func= 0;
1838  cur_pos_in_all_fields= ALL_FIELDS_UNDEF_POS;
1839  non_agg_fields.empty();
1840  cond_value= having_value= Item::COND_UNDEF;
1841  inner_refs_list.empty();
1842  m_non_agg_field_used= false;
1843  m_agg_func_used= false;
1844 }
1845 
1846 /*
1847  st_select_lex structures linking
1848 */
1849 
1850 /* include on level down */
1851 void st_select_lex_node::include_down(st_select_lex_node *upper)
1852 {
1853  if ((next= upper->slave))
1854  next->prev= &next;
1855  prev= &upper->slave;
1856  upper->slave= this;
1857  master= upper;
1858  slave= 0;
1859 }
1860 
1861 /*
1862  include on level down (but do not link)
1863 
1864  SYNOPSYS
1865  st_select_lex_node::include_standalone()
1866  upper - reference on node underr which this node should be included
1867  ref - references on reference on this node
1868 */
1869 void st_select_lex_node::include_standalone(st_select_lex_node *upper,
1870  st_select_lex_node **ref)
1871 {
1872  next= 0;
1873  prev= ref;
1874  master= upper;
1875  slave= 0;
1876 }
1877 
1878 /* include neighbour (on same level) */
1879 void st_select_lex_node::include_neighbour(st_select_lex_node *before)
1880 {
1881  if ((next= before->next))
1882  next->prev= &next;
1883  prev= &before->next;
1884  before->next= this;
1885  master= before->master;
1886  slave= 0;
1887 }
1888 
1889 /* including in global SELECT_LEX list */
1890 void st_select_lex_node::include_global(st_select_lex_node **plink)
1891 {
1892  if ((link_next= *plink))
1893  link_next->link_prev= &link_next;
1894  link_prev= plink;
1895  *plink= this;
1896 }
1897 
1898 //excluding from global list (internal function)
1899 void st_select_lex_node::fast_exclude()
1900 {
1901  if (link_prev)
1902  {
1903  if ((*link_prev= link_next))
1904  link_next->link_prev= link_prev;
1905  }
1906  // Remove slave structure
1907  for (; slave; slave= slave->next)
1908  slave->fast_exclude();
1909 
1910 }
1911 
1912 /*
1913  excluding select_lex structure (except first (first select can't be
1914  deleted, because it is most upper select))
1915 */
1916 void st_select_lex_node::exclude()
1917 {
1918  //exclude from global list
1919  fast_exclude();
1920  //exclude from other structures
1921  if ((*prev= next))
1922  next->prev= prev;
1923  /*
1924  We do not need following statements, because prev pointer of first
1925  list element point to master->slave
1926  if (master->slave == this)
1927  master->slave= next;
1928  */
1929 }
1930 
1931 
1932 /*
1933  Exclude level of current unit from tree of SELECTs
1934 
1935  SYNOPSYS
1936  st_select_lex_unit::exclude_level()
1937 
1938  NOTE: units which belong to current will be brought up on level of
1939  currernt unit
1940 */
1941 void st_select_lex_unit::exclude_level()
1942 {
1943  SELECT_LEX_UNIT *units= NULL;
1944  SELECT_LEX_UNIT **units_last= &units;
1945  SELECT_LEX *sl= first_select();
1946  while (sl)
1947  {
1948  SELECT_LEX *next_select= sl->next_select();
1949 
1950  // unlink current level from global SELECTs list
1951  if (sl->link_prev && (*sl->link_prev= sl->link_next))
1952  sl->link_next->link_prev= sl->link_prev;
1953 
1954  // bring up underlay levels
1955  SELECT_LEX_UNIT **last= NULL;
1956  for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
1957  {
1958  /*
1959  We are excluding a SELECT_LEX from the hierarchy of
1960  SELECT_LEX_UNITs and SELECT_LEXes. Since this level is
1961  removed, we must also exclude the Name_resolution_context
1962  belonging to this level. Do this by looping through inner
1963  subqueries and changing their contexts' outer context pointers
1964  to point to the outer context of the removed SELECT_LEX.
1965  */
1966  for (SELECT_LEX *s= u->first_select(); s; s= s->next_select())
1967  {
1968  if (s->context.outer_context == &sl->context)
1969  s->context.outer_context= sl->context.outer_context;
1970  }
1971  u->master= master;
1972  last= (SELECT_LEX_UNIT**)&(u->next);
1973  }
1974  if (last)
1975  {
1976  (*units_last)= sl->first_inner_unit();
1977  units_last= last;
1978  }
1979 
1980  // clean up and destroy join
1981  sl->cleanup_level();
1982 
1983  sl->invalidate();
1984  sl= next_select;
1985  }
1986  if (units)
1987  {
1988  // include brought up levels in place of current
1989  (*prev)= units;
1990  (*units_last)= (SELECT_LEX_UNIT*)next;
1991  if (next)
1992  next->prev= (SELECT_LEX_NODE**)units_last;
1993  units->prev= prev;
1994  }
1995  else
1996  {
1997  // exclude currect unit from list of nodes
1998  if (prev)
1999  (*prev)= next;
2000  if (next)
2001  next->prev= prev;
2002  }
2003 
2004  // clean up fake_select_lex and global_parameters
2005  cleanup_level();
2006 
2007  invalidate();
2008 }
2009 
2010 
2011 /*
2012  Exclude subtree of current unit from tree of SELECTs
2013 
2014  SYNOPSYS
2015  st_select_lex_unit::exclude_tree()
2016 */
2017 void st_select_lex_unit::exclude_tree()
2018 {
2019  SELECT_LEX *sl= first_select();
2020  while (sl)
2021  {
2022  SELECT_LEX *next_select= sl->next_select();
2023 
2024  // unlink current level from global SELECTs list
2025  if (sl->link_prev && (*sl->link_prev= sl->link_next))
2026  sl->link_next->link_prev= sl->link_prev;
2027 
2028  // unlink underlay levels
2029  for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
2030  {
2031  u->exclude_level();
2032  }
2033 
2034  // clean up and destroy join
2035  sl->cleanup();
2036 
2037  sl->invalidate();
2038  sl= next_select;
2039  }
2040  // exclude currect unit from list of nodes
2041  if (prev)
2042  (*prev)= next;
2043  if (next)
2044  next->prev= prev;
2045 
2046  // clean up fake_select_lex and global_parameters
2047  cleanup();
2048 
2049  invalidate();
2050 }
2051 
2052 
2057 void st_select_lex_unit::invalidate()
2058 {
2059  next= NULL;
2060  prev= NULL;
2061  master= NULL;
2062  slave= NULL;
2063  link_next= NULL;
2064  link_prev= NULL;
2065 }
2066 
2067 
2068 /*
2069  st_select_lex_node::mark_as_dependent mark all st_select_lex struct from
2070  this to 'last' as dependent
2071 
2072  SYNOPSIS
2073  last - pointer to last st_select_lex struct, before wich all
2074  st_select_lex have to be marked as dependent
2075 
2076  NOTE
2077  'last' should be reachable from this st_select_lex_node
2078 */
2079 
2080 void st_select_lex::mark_as_dependent(st_select_lex *last)
2081 {
2082  /*
2083  Mark all selects from resolved to 1 before select where was
2084  found table as depended (of select where was found table)
2085  */
2086  for (SELECT_LEX *s= this;
2087  s && s != last;
2088  s= s->outer_select())
2089  {
2090  if (!(s->uncacheable & UNCACHEABLE_DEPENDENT))
2091  {
2092  // Select is dependent of outer select
2093  s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
2094  UNCACHEABLE_DEPENDENT;
2095  SELECT_LEX_UNIT *munit= s->master_unit();
2096  munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
2097  UNCACHEABLE_DEPENDENT;
2098  for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
2099  {
2100  if (sl != s &&
2101  !(sl->uncacheable & (UNCACHEABLE_DEPENDENT | UNCACHEABLE_UNITED)))
2102  sl->uncacheable|= UNCACHEABLE_UNITED;
2103  }
2104  }
2105  }
2106 }
2107 
2108 bool st_select_lex_node::set_braces(bool value) { return 1; }
2109 bool st_select_lex_node::inc_in_sum_expr() { return 1; }
2110 uint st_select_lex_node::get_in_sum_expr() { return 0; }
2111 TABLE_LIST* st_select_lex_node::get_table_list() { return 0; }
2112 List<Item>* st_select_lex_node::get_item_list() { return 0; }
2113 TABLE_LIST *st_select_lex_node::add_table_to_list(THD *thd, Table_ident *table,
2114  LEX_STRING *alias,
2115  ulong table_join_options,
2116  thr_lock_type flags,
2117  enum_mdl_type mdl_type,
2118  List<Index_hint> *hints,
2119  List<String> *partition_names,
2120  LEX_STRING *option)
2121 {
2122  return 0;
2123 }
2124 ulong st_select_lex_node::get_table_join_options()
2125 {
2126  return 0;
2127 }
2128 
2129 /*
2130  prohibit using LIMIT clause
2131 */
2132 bool st_select_lex::test_limit()
2133 {
2134  if (select_limit != 0)
2135  {
2136  my_error(ER_NOT_SUPPORTED_YET, MYF(0),
2137  "LIMIT & IN/ALL/ANY/SOME subquery");
2138  return(1);
2139  }
2140  return(0);
2141 }
2142 
2143 
2144 st_select_lex_unit* st_select_lex_unit::master_unit()
2145 {
2146  return this;
2147 }
2148 
2149 
2150 st_select_lex* st_select_lex_unit::outer_select()
2151 {
2152  return (st_select_lex*) master;
2153 }
2154 
2155 
2156 bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
2157 {
2158  return add_to_list(thd, order_list, item, asc);
2159 }
2160 
2161 
2162 bool st_select_lex::add_gorder_to_list(THD *thd, Item *item, bool asc)
2163 {
2164  return add_to_list(thd, gorder_list, item, asc);
2165 }
2166 
2167 bool st_select_lex::add_item_to_list(THD *thd, Item *item)
2168 {
2169  DBUG_ENTER("st_select_lex::add_item_to_list");
2170  DBUG_PRINT("info", ("Item: 0x%lx", (long) item));
2171  DBUG_RETURN(item_list.push_back(item));
2172 }
2173 
2174 
2175 bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
2176 {
2177  return add_to_list(thd, group_list, item, asc);
2178 }
2179 
2180 
2181 bool st_select_lex::add_ftfunc_to_list(Item_func_match *func)
2182 {
2183  return !func || ftfunc_list->push_back(func); // end of memory?
2184 }
2185 
2186 
2187 st_select_lex_unit* st_select_lex::master_unit()
2188 {
2189  return (st_select_lex_unit*) master;
2190 }
2191 
2192 
2193 st_select_lex* st_select_lex::outer_select()
2194 {
2195  return (st_select_lex*) master->get_master();
2196 }
2197 
2198 
2203 void st_select_lex::invalidate()
2204 {
2205  next= NULL;
2206  prev= NULL;
2207  master= NULL;
2208  slave= NULL;
2209  link_next= NULL;
2210  link_prev= NULL;
2211 }
2212 
2213 
2214 bool st_select_lex::set_braces(bool value)
2215 {
2216  braces= value;
2217  return 0;
2218 }
2219 
2220 
2221 bool st_select_lex::inc_in_sum_expr()
2222 {
2223  in_sum_expr++;
2224  return 0;
2225 }
2226 
2227 
2228 uint st_select_lex::get_in_sum_expr()
2229 {
2230  return in_sum_expr;
2231 }
2232 
2233 
2234 TABLE_LIST* st_select_lex::get_table_list()
2235 {
2236  return table_list.first;
2237 }
2238 
2239 List<Item>* st_select_lex::get_item_list()
2240 {
2241  return &item_list;
2242 }
2243 
2244 ulong st_select_lex::get_table_join_options()
2245 {
2246  return table_join_options;
2247 }
2248 
2249 
2250 bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
2251 {
2252  // find_order_in_list() may need some extra space, so multiply by two.
2253  order_group_num*= 2;
2254 
2255  /*
2256  We have to create array in prepared statement memory if it is
2257  prepared statement
2258  */
2259  Query_arena *arena= thd->stmt_arena;
2260  const uint n_elems= (n_sum_items +
2261  n_child_sum_items +
2262  item_list.elements +
2263  select_n_having_items +
2264  select_n_where_fields +
2265  order_group_num) * 5;
2266  DBUG_PRINT("info", ("setup_ref_array this %p %4u : %4u %4u %4u %4u %4u %4u",
2267  this,
2268  n_elems, // :
2269  n_sum_items,
2270  n_child_sum_items,
2271  item_list.elements,
2272  select_n_having_items,
2273  select_n_where_fields,
2274  order_group_num));
2275  if (!ref_pointer_array.is_null())
2276  {
2277  /*
2278  The Query may have been permanently transformed by removal of
2279  ORDER BY or GROUP BY. Memory has already been allocated, but by
2280  reducing the size of ref_pointer_array a tight bound is
2281  maintained by Bounds_checked_array
2282  */
2283  if (ref_pointer_array.size() > n_elems)
2284  ref_pointer_array.resize(n_elems);
2285 
2286  /*
2287  We need to take 'n_sum_items' into account when allocating the array,
2288  and this may actually increase during the optimization phase due to
2289  MIN/MAX rewrite in Item_in_subselect::single_value_transformer.
2290  In the usual case we can reuse the array from the prepare phase.
2291  If we need a bigger array, we must allocate a new one.
2292  */
2293  if (ref_pointer_array.size() == n_elems)
2294  return false;
2295  }
2296  Item **array= static_cast<Item**>(arena->alloc(sizeof(Item*) * n_elems));
2297  if (array != NULL)
2298  ref_pointer_array= Ref_ptr_array(array, n_elems);
2299 
2300  return array == NULL;
2301 }
2302 
2303 
2304 void st_select_lex_unit::print(String *str, enum_query_type query_type)
2305 {
2306  bool union_all= !union_distinct;
2307  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
2308  {
2309  if (sl != first_select())
2310  {
2311  str->append(STRING_WITH_LEN(" union "));
2312  if (union_all)
2313  str->append(STRING_WITH_LEN("all "));
2314  else if (union_distinct == sl)
2315  union_all= TRUE;
2316  }
2317  if (sl->braces)
2318  str->append('(');
2319  sl->print(thd, str, query_type);
2320  if (sl->braces)
2321  str->append(')');
2322  }
2323  if (fake_select_lex == global_parameters)
2324  {
2325  if (fake_select_lex->order_list.elements)
2326  {
2327  str->append(STRING_WITH_LEN(" order by "));
2328  fake_select_lex->print_order(str,
2329  fake_select_lex->order_list.first,
2330  query_type);
2331  }
2332  fake_select_lex->print_limit(thd, str, query_type);
2333  }
2334 }
2335 
2336 
2337 void st_select_lex::print_order(String *str,
2338  ORDER *order,
2339  enum_query_type query_type)
2340 {
2341  for (; order; order= order->next)
2342  {
2343  if (order->counter_used)
2344  {
2345  char buffer[20];
2346  size_t length= my_snprintf(buffer, 20, "%d", order->counter);
2347  str->append(buffer, (uint) length);
2348  }
2349  else
2350  (*order->item)->print_for_order(str, query_type, order->used_alias);
2351  if (order->direction == ORDER::ORDER_DESC)
2352  str->append(STRING_WITH_LEN(" desc"));
2353  if (order->next)
2354  str->append(',');
2355  }
2356 }
2357 
2358 
2359 void st_select_lex::print_limit(THD *thd,
2360  String *str,
2361  enum_query_type query_type)
2362 {
2363  SELECT_LEX_UNIT *unit= master_unit();
2364  Item_subselect *item= unit->item;
2365 
2366  if (item && unit->global_parameters == this)
2367  {
2368  Item_subselect::subs_type subs_type= item->substype();
2369  if (subs_type == Item_subselect::EXISTS_SUBS ||
2370  subs_type == Item_subselect::IN_SUBS ||
2371  subs_type == Item_subselect::ALL_SUBS)
2372  return;
2373  }
2374  if (explicit_limit)
2375  {
2376  str->append(STRING_WITH_LEN(" limit "));
2377  if (offset_limit)
2378  {
2379  offset_limit->print(str, query_type);
2380  str->append(',');
2381  }
2382  select_limit->print(str, query_type);
2383  }
2384 }
2385 
2386 
2400 void
2401 Index_hint::print(THD *thd, String *str)
2402 {
2403  switch (type)
2404  {
2405  case INDEX_HINT_IGNORE: str->append(STRING_WITH_LEN("IGNORE INDEX")); break;
2406  case INDEX_HINT_USE: str->append(STRING_WITH_LEN("USE INDEX")); break;
2407  case INDEX_HINT_FORCE: str->append(STRING_WITH_LEN("FORCE INDEX")); break;
2408  }
2409  str->append (STRING_WITH_LEN(" ("));
2410  if (key_name.length)
2411  {
2412  if (thd && !my_strnncoll(system_charset_info,
2413  (const uchar *)key_name.str, key_name.length,
2414  (const uchar *)primary_key_name,
2415  strlen(primary_key_name)))
2416  str->append(primary_key_name);
2417  else
2418  append_identifier(thd, str, key_name.str, key_name.length);
2419  }
2420  str->append(')');
2421 }
2422 
2423 
2424 static void print_table_array(THD *thd, String *str, TABLE_LIST **table,
2425  TABLE_LIST **end, enum_query_type query_type)
2426 {
2427  (*table)->print(thd, str, query_type);
2428 
2429  for (TABLE_LIST **tbl= table + 1; tbl < end; tbl++)
2430  {
2431  TABLE_LIST *curr= *tbl;
2432  // Print the join operator which relates this table to the previous one
2433  if (curr->outer_join)
2434  {
2435  /* MySQL converts right to left joins */
2436  str->append(STRING_WITH_LEN(" left join "));
2437  }
2438  else if (curr->straight)
2439  str->append(STRING_WITH_LEN(" straight_join "));
2440  else if (curr->sj_on_expr)
2441  str->append(STRING_WITH_LEN(" semi join "));
2442  else
2443  str->append(STRING_WITH_LEN(" join "));
2444  curr->print(thd, str, query_type); // Print table
2445  if (curr->join_cond()) // Print join condition
2446  {
2447  str->append(STRING_WITH_LEN(" on("));
2448  curr->join_cond()->print(str, query_type);
2449  str->append(')');
2450  }
2451  }
2452 }
2453 
2454 
2464 static void print_join(THD *thd,
2465  String *str,
2466  List<TABLE_LIST> *tables,
2467  enum_query_type query_type)
2468 {
2469  /* List is reversed => we should reverse it before using */
2470  List_iterator_fast<TABLE_LIST> ti(*tables);
2471  TABLE_LIST **table;
2472  uint non_const_tables= 0;
2473 
2474  for (TABLE_LIST *t= ti++; t ; t= ti++)
2475  if (!t->optimized_away)
2476  non_const_tables++;
2477  if (!non_const_tables)
2478  {
2479  str->append(STRING_WITH_LEN("dual"));
2480  return; // all tables were optimized away
2481  }
2482  ti.rewind();
2483 
2484  if (!(table= (TABLE_LIST **)thd->alloc(sizeof(TABLE_LIST*) *
2485  non_const_tables)))
2486  return; // out of memory
2487 
2488  TABLE_LIST *tmp, **t= table + (non_const_tables - 1);
2489  while ((tmp= ti++))
2490  {
2491  if (tmp->optimized_away)
2492  continue;
2493  *t--= tmp;
2494  }
2495 
2496  /*
2497  If the first table is a semi-join nest, swap it with something that is
2498  not a semi-join nest. This is necessary because "A SEMIJOIN B" is not the
2499  same as "B SEMIJOIN A".
2500  */
2501  if ((*table)->sj_on_expr)
2502  {
2503  TABLE_LIST **end= table + non_const_tables;
2504  for (TABLE_LIST **t2= table; t2!=end; t2++)
2505  {
2506  if (!(*t2)->sj_on_expr)
2507  {
2508  TABLE_LIST *tmp= *t2;
2509  *t2= *table;
2510  *table= tmp;
2511  break;
2512  }
2513  }
2514  }
2515  DBUG_ASSERT(non_const_tables >= 1);
2516  print_table_array(thd, str, table, table + non_const_tables, query_type);
2517 }
2518 
2519 
2523 bool db_is_default_db(const char *db, size_t db_len, const THD *thd)
2524 {
2525  return thd != NULL && thd->db != NULL &&
2526  thd->db_length == db_len && !memcmp(db, thd->db, db_len);
2527 }
2528 
2529 
2536 void TABLE_LIST::print(THD *thd, String *str, enum_query_type query_type)
2537 {
2538  if (nested_join)
2539  {
2540  str->append('(');
2541  print_join(thd, str, &nested_join->join_list, query_type);
2542  str->append(')');
2543  }
2544  else
2545  {
2546  const char *cmp_name; // Name to compare with alias
2547  if (view_name.str)
2548  {
2549  // A view
2550  if (!(belong_to_view &&
2551  belong_to_view->compact_view_format) &&
2552  !((query_type & QT_NO_DEFAULT_DB) &&
2553  db_is_default_db(view_db.str, view_db.length, thd)))
2554  {
2555  append_identifier(thd, str, view_db.str, view_db.length);
2556  str->append('.');
2557  }
2558  append_identifier(thd, str, view_name.str, view_name.length);
2559  cmp_name= view_name.str;
2560  }
2561  else if (derived)
2562  {
2563  // A derived table
2564  if (!(query_type & QT_DERIVED_TABLE_ONLY_ALIAS))
2565  {
2566  str->append('(');
2567  derived->print(str, query_type);
2568  str->append(')');
2569  }
2570  cmp_name= ""; // Force printing of alias
2571  }
2572  else
2573  {
2574  // A normal table
2575 
2576  if (!(belong_to_view &&
2577  belong_to_view->compact_view_format) &&
2578  !((query_type & QT_NO_DEFAULT_DB) &&
2579  db_is_default_db(db, db_length, thd)))
2580  {
2581  append_identifier(thd, str, db, db_length);
2582  str->append('.');
2583  }
2584  if (schema_table)
2585  {
2586  append_identifier(thd, str, schema_table_name,
2587  strlen(schema_table_name));
2588  cmp_name= schema_table_name;
2589  }
2590  else
2591  {
2592  append_identifier(thd, str, table_name, table_name_length);
2593  cmp_name= table_name;
2594  }
2595 #ifdef WITH_PARTITION_STORAGE_ENGINE
2596  if (partition_names && partition_names->elements)
2597  {
2598  int i, num_parts= partition_names->elements;
2599  List_iterator<String> name_it(*(partition_names));
2600  str->append(STRING_WITH_LEN(" PARTITION ("));
2601  for (i= 1; i <= num_parts; i++)
2602  {
2603  String *name= name_it++;
2604  append_identifier(thd, str, name->c_ptr(), name->length());
2605  if (i != num_parts)
2606  str->append(',');
2607  }
2608  str->append(')');
2609  }
2610 #endif /* WITH_PARTITION_STORAGE_ENGINE */
2611  }
2612  if (my_strcasecmp(table_alias_charset, cmp_name, alias))
2613  {
2614  char t_alias_buff[MAX_ALIAS_NAME];
2615  const char *t_alias= alias;
2616 
2617  str->append(' ');
2618  if (lower_case_table_names== 1)
2619  {
2620  if (alias && alias[0])
2621  {
2622  strmov(t_alias_buff, alias);
2623  my_casedn_str(files_charset_info, t_alias_buff);
2624  t_alias= t_alias_buff;
2625  }
2626  }
2627 
2628  append_identifier(thd, str, t_alias, strlen(t_alias));
2629  }
2630 
2631  if (index_hints)
2632  {
2633  List_iterator<Index_hint> it(*index_hints);
2634  Index_hint *hint;
2635 
2636  while ((hint= it++))
2637  {
2638  str->append (STRING_WITH_LEN(" "));
2639  hint->print (thd, str);
2640  }
2641  }
2642  }
2643 }
2644 
2645 
2646 void st_select_lex::print(THD *thd, String *str, enum_query_type query_type)
2647 {
2648  /* QQ: thd may not be set for sub queries, but this should be fixed */
2649  if (!thd)
2650  thd= current_thd;
2651 
2652  if (query_type & QT_SHOW_SELECT_NUMBER)
2653  {
2654  /* it makes EXPLAIN's "id" column understandable */
2655  str->append("/* select#");
2656  if (unlikely(select_number >= INT_MAX))
2657  str->append("fake");
2658  else
2659  str->append_ulonglong(select_number);
2660  str->append(" */ select ");
2661  }
2662  else
2663  str->append(STRING_WITH_LEN("select "));
2664 
2665  if (!thd->lex->describe && join && join->need_tmp)
2666  {
2667  /*
2668  Items have been repointed to columns of an internal temporary table, it
2669  is possible that the JOIN has gone through exec() and join_free(),
2670  so items may have been freed by [tmp_JOIN_TAB]::cleanup(full=true),
2671  and thus may not be printable. Unless this is EXPLAIN, in which case the
2672  freeing is delayed by JOIN::join_free().
2673  */
2674  str->append(STRING_WITH_LEN("<already_cleaned_up>"));
2675  return;
2676  }
2677 
2678  /* First add options */
2679  if (options & SELECT_STRAIGHT_JOIN)
2680  str->append(STRING_WITH_LEN("straight_join "));
2681  if (options & SELECT_HIGH_PRIORITY)
2682  str->append(STRING_WITH_LEN("high_priority "));
2683  if (options & SELECT_DISTINCT)
2684  str->append(STRING_WITH_LEN("distinct "));
2685  if (options & SELECT_SMALL_RESULT)
2686  str->append(STRING_WITH_LEN("sql_small_result "));
2687  if (options & SELECT_BIG_RESULT)
2688  str->append(STRING_WITH_LEN("sql_big_result "));
2689  if (options & OPTION_BUFFER_RESULT)
2690  str->append(STRING_WITH_LEN("sql_buffer_result "));
2691  if (options & OPTION_FOUND_ROWS)
2692  str->append(STRING_WITH_LEN("sql_calc_found_rows "));
2693  switch (sql_cache)
2694  {
2695  case SQL_NO_CACHE:
2696  str->append(STRING_WITH_LEN("sql_no_cache "));
2697  break;
2698  case SQL_CACHE:
2699  str->append(STRING_WITH_LEN("sql_cache "));
2700  break;
2701  case SQL_CACHE_UNSPECIFIED:
2702  break;
2703  default:
2704  DBUG_ASSERT(0);
2705  }
2706 
2707  //Item List
2708  bool first= 1;
2709  List_iterator_fast<Item> it(item_list);
2710  Item *item;
2711  while ((item= it++))
2712  {
2713  if (first)
2714  first= 0;
2715  else
2716  str->append(',');
2717 
2718  if (master_unit()->item && item->item_name.is_autogenerated())
2719  {
2720  /*
2721  Do not print auto-generated aliases in subqueries. It has no purpose
2722  in a view definition or other contexts where the query is printed.
2723  */
2724  item->print(str, query_type);
2725  }
2726  else
2727  item->print_item_w_name(str, query_type);
2729  }
2730 
2731  /*
2732  from clause
2733  TODO: support USING/FORCE/IGNORE index
2734  */
2735  if (table_list.elements)
2736  {
2737  str->append(STRING_WITH_LEN(" from "));
2738  /* go through join tree */
2739  print_join(thd, str, &top_join_list, query_type);
2740  }
2741  else if (where)
2742  {
2743  /*
2744  "SELECT 1 FROM DUAL WHERE 2" should not be printed as
2745  "SELECT 1 WHERE 2": the 1st syntax is valid, but the 2nd is not.
2746  */
2747  str->append(STRING_WITH_LEN(" from DUAL "));
2748  }
2749 
2750  // Where
2751  Item *cur_where= where;
2752  if (join)
2753  cur_where= join->conds;
2754  if (cur_where || cond_value != Item::COND_UNDEF)
2755  {
2756  str->append(STRING_WITH_LEN(" where "));
2757  if (cur_where)
2758  cur_where->print(str, query_type);
2759  else
2760  str->append(cond_value != Item::COND_FALSE ? "1" : "0");
2761  }
2762 
2763  // group by & olap
2764  if (group_list.elements)
2765  {
2766  str->append(STRING_WITH_LEN(" group by "));
2767  print_order(str, group_list.first, query_type);
2768  switch (olap)
2769  {
2770  case CUBE_TYPE:
2771  str->append(STRING_WITH_LEN(" with cube"));
2772  break;
2773  case ROLLUP_TYPE:
2774  str->append(STRING_WITH_LEN(" with rollup"));
2775  break;
2776  default:
2777  ; //satisfy compiler
2778  }
2779  }
2780 
2781  // having
2782  Item *cur_having= having;
2783  if (join)
2784  cur_having= join->having_for_explain;
2785 
2786  if (cur_having || having_value != Item::COND_UNDEF)
2787  {
2788  str->append(STRING_WITH_LEN(" having "));
2789  if (cur_having)
2790  cur_having->print(str, query_type);
2791  else
2792  str->append(having_value != Item::COND_FALSE ? "1" : "0");
2793  }
2794 
2795  if (order_list.elements)
2796  {
2797  str->append(STRING_WITH_LEN(" order by "));
2798  print_order(str, order_list.first, query_type);
2799  }
2800 
2801  // limit
2802  print_limit(thd, str, query_type);
2803 
2804  // PROCEDURE unsupported here
2805 }
2806 
2807 
2820 void LEX::cleanup_lex_after_parse_error(THD *thd)
2821 {
2822  /*
2823  Delete sphead for the side effect of restoring of the original
2824  LEX state, thd->lex, thd->mem_root and thd->free_list if they
2825  were replaced when parsing stored procedure statements. We
2826  will never use sphead object after a parse error, so it's okay
2827  to delete it only for the sake of the side effect.
2828  TODO: make this functionality explicit in sp_head class.
2829  Sic: we must nullify the member of the main lex, not the
2830  current one that will be thrown away
2831  */
2832  sp_head *sp= thd->lex->sphead;
2833 
2834  if (sp)
2835  {
2837  delete sp;
2838 
2839  thd->lex->sphead= NULL;
2840  }
2841 }
2842 
2843 /*
2844  Initialize (or reset) Query_tables_list object.
2845 
2846  SYNOPSIS
2847  reset_query_tables_list()
2848  init TRUE - we should perform full initialization of object with
2849  allocating needed memory
2850  FALSE - object is already initialized so we should only reset
2851  its state so it can be used for parsing/processing
2852  of new statement
2853 
2854  DESCRIPTION
2855  This method initializes Query_tables_list so it can be used as part
2856  of LEX object for parsing/processing of statement. One can also use
2857  this method to reset state of already initialized Query_tables_list
2858  so it can be used for processing of new statement.
2859 */
2860 
2861 void Query_tables_list::reset_query_tables_list(bool init)
2862 {
2863  sql_command= SQLCOM_END;
2864  if (!init && query_tables)
2865  {
2866  TABLE_LIST *table= query_tables;
2867  for (;;)
2868  {
2869  delete table->view;
2870  if (query_tables_last == &table->next_global ||
2871  !(table= table->next_global))
2872  break;
2873  }
2874  }
2875  query_tables= 0;
2876  query_tables_last= &query_tables;
2877  query_tables_own_last= 0;
2878  if (init)
2879  {
2880  /*
2881  We delay real initialization of hash (and therefore related
2882  memory allocation) until first insertion into this hash.
2883  */
2884  my_hash_clear(&sroutines);
2885  }
2886  else if (sroutines.records)
2887  {
2888  /* Non-zero sroutines.records means that hash was initialized. */
2889  my_hash_reset(&sroutines);
2890  }
2891  sroutines_list.empty();
2892  sroutines_list_own_last= sroutines_list.next;
2893  sroutines_list_own_elements= 0;
2894  binlog_stmt_flags= 0;
2895  stmt_accessed_table_flag= 0;
2896  lock_tables_state= LTS_NOT_LOCKED;
2897  table_count= 0;
2898 }
2899 
2900 
2901 /*
2902  Destroy Query_tables_list object with freeing all resources used by it.
2903 
2904  SYNOPSIS
2905  destroy_query_tables_list()
2906 */
2907 
2908 void Query_tables_list::destroy_query_tables_list()
2909 {
2910  my_hash_free(&sroutines);
2911 }
2912 
2913 
2914 /*
2915  Initialize LEX object.
2916 
2917  SYNOPSIS
2918  LEX::LEX()
2919 
2920  NOTE
2921  LEX object initialized with this constructor can be used as part of
2922  THD object for which one can safely call open_tables(), lock_tables()
2923  and close_thread_tables() functions. But it is not yet ready for
2924  statement parsing. On should use lex_start() function to prepare LEX
2925  for this.
2926 */
2927 
2928 LEX::LEX()
2929  :result(0), option_type(OPT_DEFAULT), is_change_password(false),
2930  is_set_password_sql(false), is_lex_started(0)
2931 {
2932 
2933  my_init_dynamic_array2(&plugins, sizeof(plugin_ref),
2934  plugins_static_buffer,
2935  INITIAL_LEX_PLUGIN_LIST_SIZE,
2936  INITIAL_LEX_PLUGIN_LIST_SIZE);
2937  memset(&mi, 0, sizeof(LEX_MASTER_INFO));
2938  reset_query_tables_list(TRUE);
2939 }
2940 
2941 
2942 /*
2943  Check whether the merging algorithm can be used on this VIEW
2944 
2945  SYNOPSIS
2946  LEX::can_be_merged()
2947 
2948  DESCRIPTION
2949  We can apply merge algorithm if it is single SELECT view with
2950  subqueries only in WHERE clause (we do not count SELECTs of underlying
2951  views, and second level subqueries) and we have not grpouping, ordering,
2952  HAVING clause, aggregate functions, DISTINCT clause, LIMIT clause and
2953  several underlying tables.
2954 
2955  RETURN
2956  FALSE - only temporary table algorithm can be used
2957  TRUE - merge algorithm can be used
2958 */
2959 
2960 bool LEX::can_be_merged()
2961 {
2962  // TODO: do not forget implement case when select_lex.table_list.elements==0
2963 
2964  /* find non VIEW subqueries/unions */
2965  bool selects_allow_merge= select_lex.next_select() == 0;
2966  if (selects_allow_merge)
2967  {
2968  for (SELECT_LEX_UNIT *tmp_unit= select_lex.first_inner_unit();
2969  tmp_unit;
2970  tmp_unit= tmp_unit->next_unit())
2971  {
2972  if (tmp_unit->first_select()->parent_lex == this &&
2973  (tmp_unit->item == 0 ||
2974  (tmp_unit->item->place() != IN_WHERE &&
2975  tmp_unit->item->place() != IN_ON)))
2976  {
2977  selects_allow_merge= 0;
2978  break;
2979  }
2980  }
2981  }
2982 
2983  return (selects_allow_merge &&
2984  select_lex.group_list.elements == 0 &&
2985  select_lex.having == 0 &&
2986  select_lex.with_sum_func == 0 &&
2987  select_lex.table_list.elements >= 1 &&
2988  !(select_lex.options & SELECT_DISTINCT) &&
2989  select_lex.select_limit == 0);
2990 }
2991 
2992 
2993 /*
2994  check if command can use VIEW with MERGE algorithm (for top VIEWs)
2995 
2996  SYNOPSIS
2997  LEX::can_use_merged()
2998 
2999  DESCRIPTION
3000  Only listed here commands can use merge algorithm in top level
3001  SELECT_LEX (for subqueries will be used merge algorithm if
3002  LEX::can_not_use_merged() is not TRUE).
3003 
3004  RETURN
3005  FALSE - command can't use merged VIEWs
3006  TRUE - VIEWs with MERGE algorithms can be used
3007 */
3008 
3009 bool LEX::can_use_merged()
3010 {
3011  switch (sql_command)
3012  {
3013  case SQLCOM_SELECT:
3014  case SQLCOM_CREATE_TABLE:
3015  case SQLCOM_UPDATE:
3016  case SQLCOM_UPDATE_MULTI:
3017  case SQLCOM_DELETE:
3018  case SQLCOM_DELETE_MULTI:
3019  case SQLCOM_INSERT:
3020  case SQLCOM_INSERT_SELECT:
3021  case SQLCOM_REPLACE:
3022  case SQLCOM_REPLACE_SELECT:
3023  case SQLCOM_LOAD:
3024  return TRUE;
3025  default:
3026  return FALSE;
3027  }
3028 }
3029 
3030 /*
3031  Check if command can't use merged views in any part of command
3032 
3033  SYNOPSIS
3034  LEX::can_not_use_merged()
3035 
3036  DESCRIPTION
3037  Temporary table algorithm will be used on all SELECT levels for queries
3038  listed here (see also LEX::can_use_merged()).
3039 
3040  RETURN
3041  FALSE - command can't use merged VIEWs
3042  TRUE - VIEWs with MERGE algorithms can be used
3043 */
3044 
3045 bool LEX::can_not_use_merged()
3046 {
3047  switch (sql_command)
3048  {
3049  case SQLCOM_CREATE_VIEW:
3050  case SQLCOM_SHOW_CREATE:
3051  /*
3052  SQLCOM_SHOW_FIELDS is necessary to make
3053  information schema tables working correctly with views.
3054  see get_schema_tables_result function
3055  */
3056  case SQLCOM_SHOW_FIELDS:
3057  return TRUE;
3058  default:
3059  return FALSE;
3060  }
3061 }
3062 
3063 /*
3064  Detect that we need only table structure of derived table/view
3065 
3066  SYNOPSIS
3067  only_view_structure()
3068 
3069  RETURN
3070  TRUE yes, we need only structure
3071  FALSE no, we need data
3072 */
3073 
3074 bool LEX::only_view_structure()
3075 {
3076  switch (sql_command) {
3077  case SQLCOM_SHOW_CREATE:
3078  case SQLCOM_SHOW_TABLES:
3079  case SQLCOM_SHOW_FIELDS:
3080  case SQLCOM_REVOKE_ALL:
3081  case SQLCOM_REVOKE:
3082  case SQLCOM_GRANT:
3083  case SQLCOM_CREATE_VIEW:
3084  return TRUE;
3085  default:
3086  return FALSE;
3087  }
3088 }
3089 
3090 
3091 /*
3092  Should Items_ident be printed correctly
3093 
3094  SYNOPSIS
3095  need_correct_ident()
3096 
3097  RETURN
3098  TRUE yes, we need only structure
3099  FALSE no, we need data
3100 */
3101 
3102 
3103 bool LEX::need_correct_ident()
3104 {
3105  switch(sql_command)
3106  {
3107  case SQLCOM_SHOW_CREATE:
3108  case SQLCOM_SHOW_TABLES:
3109  case SQLCOM_CREATE_VIEW:
3110  return TRUE;
3111  default:
3112  return FALSE;
3113  }
3114 }
3115 
3116 /*
3117  Get effective type of CHECK OPTION for given view
3118 
3119  SYNOPSIS
3120  get_effective_with_check()
3121  view given view
3122 
3123  NOTE
3124  It have not sense to set CHECK OPTION for SELECT satement or subqueries,
3125  so we do not.
3126 
3127  RETURN
3128  VIEW_CHECK_NONE no need CHECK OPTION
3129  VIEW_CHECK_LOCAL CHECK OPTION LOCAL
3130  VIEW_CHECK_CASCADED CHECK OPTION CASCADED
3131 */
3132 
3133 uint8 LEX::get_effective_with_check(TABLE_LIST *view)
3134 {
3135  if (view->select_lex->master_unit() == &unit &&
3136  which_check_option_applicable())
3137  return (uint8)view->with_check;
3138  return VIEW_CHECK_NONE;
3139 }
3140 
3141 
3161 bool
3162 LEX::copy_db_to(char **p_db, size_t *p_db_length) const
3163 {
3164  if (sphead)
3165  {
3166  DBUG_ASSERT(sphead->m_db.str && sphead->m_db.length);
3167  /*
3168  It is safe to assign the string by-pointer, both sphead and
3169  its statements reside in the same memory root.
3170  */
3171  *p_db= sphead->m_db.str;
3172  if (p_db_length)
3173  *p_db_length= sphead->m_db.length;
3174  return FALSE;
3175  }
3176  return thd->copy_db_to(p_db, p_db_length);
3177 }
3178 
3179 /*
3180  initialize limit counters
3181 
3182  SYNOPSIS
3183  st_select_lex_unit::set_limit()
3184  values - SELECT_LEX with initial values for counters
3185 */
3186 
3187 void st_select_lex_unit::set_limit(st_select_lex *sl)
3188 {
3189  ha_rows select_limit_val;
3190  ulonglong val;
3191 
3192  DBUG_ASSERT(! thd->stmt_arena->is_stmt_prepare());
3193  if (sl->select_limit)
3194  {
3195  Item *item = sl->select_limit;
3196  /*
3197  fix_fields() has not been called for sl->select_limit. That's due to the
3198  historical reasons -- this item could be only of type Item_int, and
3199  Item_int does not require fix_fields(). Thus, fix_fields() was never
3200  called for sl->select_limit.
3201 
3202  Some time ago, Item_splocal was also allowed for LIMIT / OFFSET clauses.
3203  However, the fix_fields() behavior was not updated, which led to a crash
3204  in some cases.
3205 
3206  There is no single place where to call fix_fields() for LIMIT / OFFSET
3207  items during the fix-fields-phase. Thus, for the sake of readability,
3208  it was decided to do it here, on the evaluation phase (which is a
3209  violation of design, but we chose the lesser of two evils).
3210 
3211  We can call fix_fields() here, because sl->select_limit can be of two
3212  types only: Item_int and Item_splocal. Item_int::fix_fields() is trivial,
3213  and Item_splocal::fix_fields() (or rather Item_sp_variable::fix_fields())
3214  has the following specific:
3215  1) it does not affect other items;
3216  2) it does not fail.
3217 
3218  Nevertheless DBUG_ASSERT was added to catch future changes in
3219  fix_fields() implementation. Also added runtime check against a result
3220  of fix_fields() in order to handle error condition in non-debug build.
3221  */
3222  bool fix_fields_successful= true;
3223  if (!item->fixed)
3224  {
3225  fix_fields_successful= !item->fix_fields(thd, NULL);
3226 
3227  DBUG_ASSERT(fix_fields_successful);
3228  }
3229  val= fix_fields_successful ? item->val_uint() : HA_POS_ERROR;
3230  }
3231  else
3232  val= HA_POS_ERROR;
3233 
3234  select_limit_val= (ha_rows)val;
3235 #ifndef BIG_TABLES
3236  /*
3237  Check for overflow : ha_rows can be smaller then ulonglong if
3238  BIG_TABLES is off.
3239  */
3240  if (val != (ulonglong)select_limit_val)
3241  select_limit_val= HA_POS_ERROR;
3242 #endif
3243  if (sl->offset_limit)
3244  {
3245  Item *item = sl->offset_limit;
3246  // see comment for sl->select_limit branch.
3247  bool fix_fields_successful= true;
3248  if (!item->fixed)
3249  {
3250  fix_fields_successful= !item->fix_fields(thd, NULL);
3251 
3252  DBUG_ASSERT(fix_fields_successful);
3253  }
3254  val= fix_fields_successful ? item->val_uint() : HA_POS_ERROR;
3255  }
3256  else
3257  val= ULL(0);
3258 
3259  offset_limit_cnt= (ha_rows)val;
3260 #ifndef BIG_TABLES
3261  /* Check for truncation. */
3262  if (val != (ulonglong)offset_limit_cnt)
3263  offset_limit_cnt= HA_POS_ERROR;
3264 #endif
3265  select_limit_cnt= select_limit_val + offset_limit_cnt;
3266  if (select_limit_cnt < select_limit_val)
3267  select_limit_cnt= HA_POS_ERROR; // no limit
3268 }
3269 
3270 
3294 void LEX::set_trg_event_type_for_tables()
3295 {
3296  uint8 new_trg_event_map= 0;
3297 
3298  /*
3299  Some auxiliary operations
3300  (e.g. GRANT processing) create TABLE_LIST instances outside
3301  the parser. Additionally, some commands (e.g. OPTIMIZE) change
3302  the lock type for a table only after parsing is done. Luckily,
3303  these do not fire triggers and do not need to pre-load them.
3304  For these TABLE_LISTs set_trg_event_type is never called, and
3305  trg_event_map is always empty. That means that the pre-locking
3306  algorithm will ignore triggers defined on these tables, if
3307  any, and the execution will either fail with an assert in
3308  sql_trigger.cc or with an error that a used table was not
3309  pre-locked, in case of a production build.
3310 
3311  TODO: this usage pattern creates unnecessary module dependencies
3312  and should be rewritten to go through the parser.
3313  Table list instances created outside the parser in most cases
3314  refer to mysql.* system tables. It is not allowed to have
3315  a trigger on a system table, but keeping track of
3316  initialization provides extra safety in case this limitation
3317  is circumvented.
3318  */
3319 
3320  switch (sql_command) {
3321  case SQLCOM_LOCK_TABLES:
3322  /*
3323  On a LOCK TABLE, all triggers must be pre-loaded for this TABLE_LIST
3324  when opening an associated TABLE.
3325  */
3326  new_trg_event_map= static_cast<uint8>
3327  (1 << static_cast<int>(TRG_EVENT_INSERT)) |
3328  static_cast<uint8>
3329  (1 << static_cast<int>(TRG_EVENT_UPDATE)) |
3330  static_cast<uint8>
3331  (1 << static_cast<int>(TRG_EVENT_DELETE));
3332  break;
3333  /*
3334  Basic INSERT. If there is an additional ON DUPLIATE KEY UPDATE
3335  clause, it will be handled later in this method.
3336  */
3337  case SQLCOM_INSERT: /* fall through */
3338  case SQLCOM_INSERT_SELECT:
3339  /*
3340  LOAD DATA ... INFILE is expected to fire BEFORE/AFTER INSERT
3341  triggers.
3342  If the statement also has REPLACE clause, it will be
3343  handled later in this method.
3344  */
3345  case SQLCOM_LOAD: /* fall through */
3346  /*
3347  REPLACE is semantically equivalent to INSERT. In case
3348  of a primary or unique key conflict, it deletes the old
3349  record and inserts a new one. So we also may need to
3350  fire ON DELETE triggers. This functionality is handled
3351  later in this method.
3352  */
3353  case SQLCOM_REPLACE: /* fall through */
3354  case SQLCOM_REPLACE_SELECT:
3355  /*
3356  CREATE TABLE ... SELECT defaults to INSERT if the table or
3357  view already exists. REPLACE option of CREATE TABLE ...
3358  REPLACE SELECT is handled later in this method.
3359  */
3360  case SQLCOM_CREATE_TABLE:
3361  new_trg_event_map|= static_cast<uint8>
3362  (1 << static_cast<int>(TRG_EVENT_INSERT));
3363  break;
3364  /* Basic update and multi-update */
3365  case SQLCOM_UPDATE: /* fall through */
3366  case SQLCOM_UPDATE_MULTI:
3367  new_trg_event_map|= static_cast<uint8>
3368  (1 << static_cast<int>(TRG_EVENT_UPDATE));
3369  break;
3370  /* Basic delete and multi-delete */
3371  case SQLCOM_DELETE: /* fall through */
3372  case SQLCOM_DELETE_MULTI:
3373  new_trg_event_map|= static_cast<uint8>
3374  (1 << static_cast<int>(TRG_EVENT_DELETE));
3375  break;
3376  default:
3377  break;
3378  }
3379 
3380  switch (duplicates) {
3381  case DUP_UPDATE:
3382  new_trg_event_map|= static_cast<uint8>
3383  (1 << static_cast<int>(TRG_EVENT_UPDATE));
3384  break;
3385  case DUP_REPLACE:
3386  new_trg_event_map|= static_cast<uint8>
3387  (1 << static_cast<int>(TRG_EVENT_DELETE));
3388  break;
3389  case DUP_ERROR:
3390  default:
3391  break;
3392  }
3393 
3394 
3395  /*
3396  Do not iterate over sub-selects, only the tables in the outermost
3397  SELECT_LEX can be modified, if any.
3398  */
3399  TABLE_LIST *tables= select_lex.get_table_list();
3400 
3401  while (tables)
3402  {
3403  /*
3404  This is a fast check to filter out statements that do
3405  not change data, or tables on the right side, in case of
3406  INSERT .. SELECT, CREATE TABLE .. SELECT and so on.
3407  Here we also filter out OPTIMIZE statement and non-updateable
3408  views, for which lock_type is TL_UNLOCK or TL_READ after
3409  parsing.
3410  */
3411  if (static_cast<int>(tables->lock_type) >=
3412  static_cast<int>(TL_WRITE_ALLOW_WRITE))
3413  tables->trg_event_map= new_trg_event_map;
3414  tables= tables->next_local;
3415  }
3416 }
3417 
3418 
3419 /*
3420  Unlink the first table from the global table list and the first table from
3421  outer select (lex->select_lex) local list
3422 
3423  SYNOPSIS
3424  unlink_first_table()
3425  link_to_local Set to 1 if caller should link this table to local list
3426 
3427  NOTES
3428  We assume that first tables in both lists is the same table or the local
3429  list is empty.
3430 
3431  RETURN
3432  0 If 'query_tables' == 0
3433  unlinked table
3434  In this case link_to_local is set.
3435 
3436 */
3437 TABLE_LIST *LEX::unlink_first_table(bool *link_to_local)
3438 {
3439  TABLE_LIST *first;
3440  if ((first= query_tables))
3441  {
3442  /*
3443  Exclude from global table list
3444  */
3445  if ((query_tables= query_tables->next_global))
3446  query_tables->prev_global= &query_tables;
3447  else
3448  query_tables_last= &query_tables;
3449  first->next_global= 0;
3450 
3451  if (query_tables_own_last == &first->next_global)
3452  query_tables_own_last= &query_tables;
3453 
3454  /*
3455  and from local list if it is not empty
3456  */
3457  if ((*link_to_local= test(select_lex.table_list.first)))
3458  {
3459  select_lex.context.table_list=
3460  select_lex.context.first_name_resolution_table= first->next_local;
3461  select_lex.table_list.first= first->next_local;
3462  select_lex.table_list.elements--; //safety
3463  first->next_local= 0;
3464  /*
3465  Ensure that the global list has the same first table as the local
3466  list.
3467  */
3468  first_lists_tables_same();
3469  }
3470  }
3471  return first;
3472 }
3473 
3474 
3475 /*
3476  Bring first local table of first most outer select to first place in global
3477  table list
3478 
3479  SYNOPSYS
3480  LEX::first_lists_tables_same()
3481 
3482  NOTES
3483  In many cases (for example, usual INSERT/DELETE/...) the first table of
3484  main SELECT_LEX have special meaning => check that it is the first table
3485  in global list and re-link to be first in the global list if it is
3486  necessary. We need such re-linking only for queries with sub-queries in
3487  the select list, as only in this case tables of sub-queries will go to
3488  the global list first.
3489 */
3490 
3491 void LEX::first_lists_tables_same()
3492 {
3493  TABLE_LIST *first_table= select_lex.table_list.first;
3494  if (query_tables != first_table && first_table != 0)
3495  {
3496  TABLE_LIST *next;
3497  if (query_tables_last == &first_table->next_global)
3498  query_tables_last= first_table->prev_global;
3499 
3500  if ((next= *first_table->prev_global= first_table->next_global))
3501  next->prev_global= first_table->prev_global;
3502  /* include in new place */
3503  first_table->next_global= query_tables;
3504  /*
3505  We are sure that query_tables is not 0, because first_table was not
3506  first table in the global list => we can use
3507  query_tables->prev_global without check of query_tables
3508  */
3509  query_tables->prev_global= &first_table->next_global;
3510  first_table->prev_global= &query_tables;
3511  query_tables= first_table;
3512  }
3513 }
3514 
3515 
3516 /*
3517  Link table back that was unlinked with unlink_first_table()
3518 
3519  SYNOPSIS
3520  link_first_table_back()
3521  link_to_local do we need link this table to local
3522 
3523  RETURN
3524  global list
3525 */
3526 
3527 void LEX::link_first_table_back(TABLE_LIST *first,
3528  bool link_to_local)
3529 {
3530  if (first)
3531  {
3532  if ((first->next_global= query_tables))
3533  query_tables->prev_global= &first->next_global;
3534  else
3535  query_tables_last= &first->next_global;
3536 
3537  if (query_tables_own_last == &query_tables)
3538  query_tables_own_last= &first->next_global;
3539 
3540  query_tables= first;
3541 
3542  if (link_to_local)
3543  {
3544  first->next_local= select_lex.table_list.first;
3545  select_lex.context.table_list= first;
3546  select_lex.table_list.first= first;
3547  select_lex.table_list.elements++; //safety
3548  }
3549  }
3550 }
3551 
3552 
3553 
3554 /*
3555  cleanup lex for case when we open table by table for processing
3556 
3557  SYNOPSIS
3558  LEX::cleanup_after_one_table_open()
3559 
3560  NOTE
3561  This method is mostly responsible for cleaning up of selects lists and
3562  derived tables state. To rollback changes in Query_tables_list one has
3563  to call Query_tables_list::reset_query_tables_list(FALSE).
3564 */
3565 
3566 void LEX::cleanup_after_one_table_open()
3567 {
3568  /*
3569  thd->lex->derived_tables & additional units may be set if we open
3570  a view. It is necessary to clear thd->lex->derived_tables flag
3571  to prevent processing of derived tables during next open_and_lock_tables
3572  if next table is a real table and cleanup & remove underlying units
3573  NOTE: all units will be connected to thd->lex->select_lex, because we
3574  have not UNION on most upper level.
3575  */
3576  if (all_selects_list != &select_lex)
3577  {
3578  derived_tables= 0;
3579  /* cleunup underlying units (units of VIEW) */
3580  for (SELECT_LEX_UNIT *un= select_lex.first_inner_unit();
3581  un;
3582  un= un->next_unit())
3583  un->cleanup();
3584  /* reduce all selects list to default state */
3585  all_selects_list= &select_lex;
3586  /* remove underlying units (units of VIEW) subtree */
3587  select_lex.cut_subtree();
3588  }
3589 }
3590 
3591 
3592 /*
3593  Save current state of Query_tables_list for this LEX, and prepare it
3594  for processing of new statemnt.
3595 
3596  SYNOPSIS
3597  reset_n_backup_query_tables_list()
3598  backup Pointer to Query_tables_list instance to be used for backup
3599 */
3600 
3601 void LEX::reset_n_backup_query_tables_list(Query_tables_list *backup)
3602 {
3603  backup->set_query_tables_list(this);
3604  /*
3605  We have to perform full initialization here since otherwise we
3606  will damage backed up state.
3607  */
3608  this->reset_query_tables_list(TRUE);
3609 }
3610 
3611 
3612 /*
3613  Restore state of Query_tables_list for this LEX from backup.
3614 
3615  SYNOPSIS
3616  restore_backup_query_tables_list()
3617  backup Pointer to Query_tables_list instance used for backup
3618 */
3619 
3620 void LEX::restore_backup_query_tables_list(Query_tables_list *backup)
3621 {
3622  this->destroy_query_tables_list();
3623  this->set_query_tables_list(backup);
3624 }
3625 
3626 
3627 /*
3628  Checks for usage of routines and/or tables in a parsed statement
3629 
3630  SYNOPSIS
3631  LEX:table_or_sp_used()
3632 
3633  RETURN
3634  FALSE No routines and tables used
3635  TRUE Either or both routines and tables are used.
3636 */
3637 
3638 bool LEX::table_or_sp_used()
3639 {
3640  DBUG_ENTER("table_or_sp_used");
3641 
3642  if (sroutines.records || query_tables)
3643  DBUG_RETURN(TRUE);
3644 
3645  DBUG_RETURN(FALSE);
3646 }
3647 
3648 
3649 /*
3650  Do end-of-prepare fixup for list of tables and their merge-VIEWed tables
3651 
3652  SYNOPSIS
3653  fix_prepare_info_in_table_list()
3654  thd Thread handle
3655  tbl List of tables to process
3656 
3657  DESCRIPTION
3658  Perform end-end-of prepare fixup for list of tables, if any of the tables
3659  is a merge-algorithm VIEW, recursively fix up its underlying tables as
3660  well.
3661 
3662 */
3663 
3664 static void fix_prepare_info_in_table_list(THD *thd, TABLE_LIST *tbl)
3665 {
3666  for (; tbl; tbl= tbl->next_local)
3667  {
3668  if (tbl->join_cond())
3669  {
3670  tbl->prep_join_cond= tbl->join_cond();
3671  tbl->set_join_cond(tbl->join_cond()->copy_andor_structure(thd));
3672  }
3673  fix_prepare_info_in_table_list(thd, tbl->merge_underlying_list);
3674  }
3675 }
3676 
3677 
3678 /*
3679  Save WHERE/HAVING/ON clauses and replace them with disposable copies
3680 
3681  SYNOPSIS
3682  st_select_lex::fix_prepare_information
3683  thd thread handler
3684  conds in/out pointer to WHERE condition to be met at execution
3685  having_conds in/out pointer to HAVING condition to be met at execution
3686 
3687  DESCRIPTION
3688  The passed WHERE and HAVING are to be saved for the future executions.
3689  This function saves it, and returns a copy which can be thrashed during
3690  this execution of the statement. By saving/thrashing here we mean only
3691  AND/OR trees.
3692  We also save the chain of ORDER::next in group_list and order_list, in
3693  case the list is modified by remove_const().
3694  The function also calls fix_prepare_info_in_table_list that saves all
3695  ON expressions.
3696 */
3697 
3698 void st_select_lex::fix_prepare_information(THD *thd, Item **conds,
3699  Item **having_conds)
3700 {
3701  if (!thd->stmt_arena->is_conventional() && first_execution)
3702  {
3703  first_execution= 0;
3704  if (group_list.first)
3705  {
3706  if (!group_list_ptrs)
3707  {
3708  void *mem= thd->stmt_arena->alloc(sizeof(Group_list_ptrs));
3709  group_list_ptrs= new (mem) Group_list_ptrs(thd->stmt_arena->mem_root);
3710  }
3711  group_list_ptrs->reserve(group_list.elements);
3712  for (ORDER *order= group_list.first; order; order= order->next)
3713  {
3714  group_list_ptrs->push_back(order);
3715  }
3716  }
3717  if (order_list.first)
3718  {
3719  if (!order_list_ptrs)
3720  {
3721  void *mem= thd->stmt_arena->alloc(sizeof(Group_list_ptrs));
3722  order_list_ptrs= new (mem) Group_list_ptrs(thd->stmt_arena->mem_root);
3723  }
3724  order_list_ptrs->reserve(order_list.elements);
3725  for (ORDER *order= order_list.first; order; order= order->next)
3726  {
3727  order_list_ptrs->push_back(order);
3728  }
3729  }
3730  if (*conds)
3731  {
3732  /*
3733  In "WHERE outer_field", *conds may be an Item_outer_ref allocated in
3734  the execution memroot.
3735  @todo change this line in WL#7082. Currently, when we execute a SP,
3736  containing "SELECT (SELECT ... WHERE t1.col) FROM t1",
3737  resolution may make *conds equal to an Item_outer_ref, then below
3738  *conds becomes Item_field, which then goes straight on to execution,
3739  undoing the effects of putting Item_outer_ref in the first place...
3740  With a PS the problem is not as severe, as after the code below we
3741  don't go to execution: a next execution will do a new name resolution
3742  which will create Item_outer_ref again.
3743  */
3744  prep_where= (*conds)->real_item();
3745  *conds= where= prep_where->copy_andor_structure(thd);
3746  }
3747  if (*having_conds)
3748  {
3749  prep_having= *having_conds;
3750  *having_conds= having= prep_having->copy_andor_structure(thd);
3751  }
3752  fix_prepare_info_in_table_list(thd, table_list.first);
3753  }
3754 }
3755 
3756 
3757 /*
3758  There are st_select_lex::add_table_to_list &
3759  st_select_lex::set_lock_for_tables are in sql_parse.cc
3760 
3761  st_select_lex::print is in sql_select.cc
3762 
3763  st_select_lex_unit::prepare, st_select_lex_unit::exec,
3764  st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
3765  st_select_lex_unit::change_result
3766  are in sql_union.cc
3767 */
3768 
3769 /*
3770  Sets the kind of hints to be added by the calls to add_index_hint().
3771 
3772  SYNOPSIS
3773  set_index_hint_type()
3774  type_arg The kind of hints to be added from now on.
3775  clause The clause to use for hints to be added from now on.
3776 
3777  DESCRIPTION
3778  Used in filling up the tagged hints list.
3779  This list is filled by first setting the kind of the hint as a
3780  context variable and then adding hints of the current kind.
3781  Then the context variable index_hint_type can be reset to the
3782  next hint type.
3783 */
3784 void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
3785  index_clause_map clause)
3786 {
3787  current_index_hint_type= type_arg;
3788  current_index_hint_clause= clause;
3789 }
3790 
3791 
3792 /*
3793  Makes an array to store index usage hints (ADD/FORCE/IGNORE INDEX).
3794 
3795  SYNOPSIS
3796  alloc_index_hints()
3797  thd current thread.
3798 */
3799 
3800 void st_select_lex::alloc_index_hints (THD *thd)
3801 {
3802  index_hints= new (thd->mem_root) List<Index_hint>();
3803 }
3804 
3805 
3806 
3807 /*
3808  adds an element to the array storing index usage hints
3809  (ADD/FORCE/IGNORE INDEX).
3810 
3811  SYNOPSIS
3812  add_index_hint()
3813  thd current thread.
3814  str name of the index.
3815  length number of characters in str.
3816 
3817  RETURN VALUE
3818  0 on success, non-zero otherwise
3819 */
3820 bool st_select_lex::add_index_hint (THD *thd, char *str, uint length)
3821 {
3822  return index_hints->push_front (new (thd->mem_root)
3823  Index_hint(current_index_hint_type,
3824  current_index_hint_clause,
3825  str, length));
3826 }
3827 
3828 
3848 bool st_select_lex::handle_derived(LEX *lex,
3849  bool (*processor)(THD*, LEX*, TABLE_LIST*))
3850 {
3851  for (TABLE_LIST *table_ref= leaf_tables;
3852  table_ref;
3853  table_ref= table_ref->next_leaf)
3854  {
3855  if (table_ref->is_view_or_derived() &&
3856  table_ref->handle_derived(lex, processor))
3857  return TRUE;
3858  }
3859  return FALSE;
3860 }
3861 
3862 
3863 st_select_lex::type_enum st_select_lex::type(const THD *thd)
3864 {
3865  if (master_unit()->fake_select_lex == this)
3866  return SLT_UNION_RESULT;
3867  else if (&thd->lex->select_lex == this)
3868  {
3869  if (first_inner_unit() || next_select())
3870  return SLT_PRIMARY;
3871  else
3872  return SLT_SIMPLE;
3873  }
3874  else if (this == master_unit()->first_select())
3875  {
3876  if (linkage == DERIVED_TABLE_TYPE)
3877  return SLT_DERIVED;
3878  else
3879  return SLT_SUBQUERY;
3880  }
3881  else
3882  return SLT_UNION;
3883 }
3884 
3885 
3897 bool LEX::is_partition_management() const
3898 {
3899  return (sql_command == SQLCOM_ALTER_TABLE &&
3900  (alter_info.flags == Alter_info::ALTER_ADD_PARTITION ||
3901  alter_info.flags == Alter_info::ALTER_REORGANIZE_PARTITION));
3902 }
3903 
3904 
3908 void st_lex_master_info::set_unspecified()
3909 {
3910  memset(this, 0, sizeof(*this));
3911  sql_delay= -1;
3912 }
3913 
3914 #ifdef MYSQL_SERVER
3915 uint binlog_unsafe_map[256];
3916 
3917 #define UNSAFE(a, b, c) \
3918  { \
3919  DBUG_PRINT("unsafe_mixed_statement", ("SETTING BASE VALUES: %s, %s, %02X\n", \
3920  LEX::stmt_accessed_table_string(a), \
3921  LEX::stmt_accessed_table_string(b), \
3922  c)); \
3923  unsafe_mixed_statement(a, b, c); \
3924  }
3925 
3926 /*
3927  Sets the combination given by "a" and "b" and automatically combinations
3928  given by other types of access, i.e. 2^(8 - 2), as unsafe.
3929 
3930  It may happen a colision when automatically defining a combination as unsafe.
3931  For that reason, a combination has its unsafe condition redefined only when
3932  the new_condition is greater then the old. For instance,
3933 
3934  . (BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY) is never overwritten by
3935  . (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF).
3936 */
3937 void unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,
3938  LEX::enum_stmt_accessed_table b, uint condition)
3939 {
3940  int type= 0;
3941  int index= (1U << a) | (1U << b);
3942 
3943 
3944  for (type= 0; type < 256; type++)
3945  {
3946  if ((type & index) == index)
3947  {
3948  binlog_unsafe_map[type] |= condition;
3949  }
3950  }
3951 }
3952 /*
3953  The BINLOG_* AND TRX_CACHE_* values can be combined by using '&' or '|',
3954  which means that both conditions need to be satisfied or any of them is
3955  enough. For example,
3956 
3957  . BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY means that the statment is
3958  unsafe when the option is on and trx-cache is not empty;
3959 
3960  . BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF means the statement is unsafe
3961  in all cases.
3962 
3963  . TRX_CACHE_EMPTY | TRX_CACHE_NOT_EMPTY means the statement is unsafe
3964  in all cases. Similar as above.
3965 */
3966 void binlog_unsafe_map_init()
3967 {
3968  memset((void*) binlog_unsafe_map, 0, sizeof(uint) * 256);
3969 
3970  /*
3971  Classify a statement as unsafe when there is a mixed statement and an
3972  on-going transaction at any point of the execution if:
3973 
3974  1. The mixed statement is about to update a transactional table and
3975  a non-transactional table.
3976 
3977  2. The mixed statement is about to update a transactional table and
3978  read from a non-transactional table.
3979 
3980  3. The mixed statement is about to update a non-transactional table
3981  and temporary transactional table.
3982 
3983  4. The mixed statement is about to update a temporary transactional
3984  table and read from a non-transactional table.
3985 
3986  5. The mixed statement is about to update a transactional table and
3987  a temporary non-transactional table.
3988 
3989  6. The mixed statement is about to update a transactional table and
3990  read from a temporary non-transactional table.
3991 
3992  7. The mixed statement is about to update a temporary transactional
3993  table and temporary non-transactional table.
3994 
3995  8. The mixed statement is about to update a temporary transactional
3996  table and read from a temporary non-transactional table.
3997  After updating a transactional table if:
3998 
3999  9. The mixed statement is about to update a non-transactional table
4000  and read from a transactional table.
4001 
4002  10. The mixed statement is about to update a non-transactional table
4003  and read from a temporary transactional table.
4004 
4005  11. The mixed statement is about to update a temporary non-transactional
4006  table and read from a transactional table.
4007 
4008  12. The mixed statement is about to update a temporary non-transactional
4009  table and read from a temporary transactional table.
4010 
4011  13. The mixed statement is about to update a temporary non-transactional
4012  table and read from a non-transactional table.
4013 
4014  The reason for this is that locks acquired may not protected a concurrent
4015  transaction of interfering in the current execution and by consequence in
4016  the result.
4017  */
4018  /* Case 1. */
4019  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_NON_TRANS_TABLE,
4020  BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4021  /* Case 2. */
4022  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
4023  BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4024  /* Case 3. */
4025  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_WRITES_TEMP_TRANS_TABLE,
4026  BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4027  /* Case 4. */
4028  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
4029  BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
4030  /* Case 5. */
4031  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
4032  BINLOG_DIRECT_ON);
4033  /* Case 6. */
4034  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
4035  BINLOG_DIRECT_ON);
4036  /* Case 7. */
4037  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
4038  BINLOG_DIRECT_ON);
4039  /* Case 8. */
4040  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
4041  BINLOG_DIRECT_ON);
4042  /* Case 9. */
4043  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
4044  (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
4045  /* Case 10 */
4046  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
4047  (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
4048  /* Case 11. */
4049  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
4050  BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
4051  /* Case 12. */
4052  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
4053  BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
4054  /* Case 13. */
4055  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
4056  BINLOG_DIRECT_OFF & TRX_CACHE_NOT_EMPTY);
4057 }
4058 #endif