sql_lex.cc 98.4 KB
Newer Older
1
/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
6

unknown's avatar
unknown committed
7 8 9 10
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
unknown's avatar
unknown committed
11

unknown's avatar
unknown committed
12 13 14 15 16 17 18
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


/* A lexical scanner on a temporary buffer with a yacc interface */

19
#define MYSQL_LEX 1
unknown's avatar
unknown committed
20 21 22 23
#include "mysql_priv.h"
#include "item_create.h"
#include <m_ctype.h>
#include <hash.h>
24 25
#include "sp.h"
#include "sp_head.h"
26
#include "sql_select.h"
unknown's avatar
unknown committed
27

28 29 30 31
/*
  We are using pointer to this variable for distinguishing between assignment
  to NEW row field (when parsing trigger definition) and structured variable.
*/
32 33

sys_var *trg_new_row_fake_var= (sys_var*) 0x01;
34

35
/* Longest standard keyword name */
unknown's avatar
unknown committed
36 37
#define TOCK_NAME_LENGTH 24

38 39
/*
  The following data is based on the latin1 character set, and is only
unknown's avatar
unknown committed
40 41 42
  used when comparing keywords
*/

unknown's avatar
unknown committed
43 44
static uchar to_upper_lex[]=
{
unknown's avatar
unknown committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
   16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
   32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
   48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
   64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
   80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
   96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
   80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127,
  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
  160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  208,209,210,211,212,213,214,247,216,217,218,219,220,221,222,255
};

63 64 65 66 67 68 69 70 71 72 73
/* 
  Names of the index hints (for error messages). Keep in sync with 
  index_hint_type 
*/

const char * index_hint_type_name[] =
{
  "IGNORE INDEX", 
  "USE INDEX", 
  "FORCE INDEX"
};
74

unknown's avatar
unknown committed
75 76 77 78 79 80 81
inline int lex_casecmp(const char *s, const char *t, uint len)
{
  while (len-- != 0 &&
	 to_upper_lex[(uchar) *s++] == to_upper_lex[(uchar) *t++]) ;
  return (int) len+1;
}

unknown's avatar
unknown committed
82
#include <lex_hash.h>
unknown's avatar
unknown committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104


void lex_init(void)
{
  uint i;
  DBUG_ENTER("lex_init");
  for (i=0 ; i < array_elements(symbols) ; i++)
    symbols[i].length=(uchar) strlen(symbols[i].name);
  for (i=0 ; i < array_elements(sql_functions) ; i++)
    sql_functions[i].length=(uchar) strlen(sql_functions[i].name);

  DBUG_VOID_RETURN;
}


void lex_free(void)
{					// Call this when daemon ends
  DBUG_ENTER("lex_free");
  DBUG_VOID_RETURN;
}


105 106 107 108 109 110 111 112 113
void
st_parsing_options::reset()
{
  allows_variable= TRUE;
  allows_select_into= TRUE;
  allows_select_procedure= TRUE;
  allows_derived= TRUE;
}

114

115
bool Lex_input_stream::init(THD *thd, char *buff, unsigned int length)
116
{
117 118 119
  DBUG_EXECUTE_IF("bug42064_simulate_oom",
                  DBUG_SET("+d,simulate_out_of_memory"););

120
  m_cpp_buf= (char*) thd->alloc(length + 1);
121 122 123 124 125

  DBUG_EXECUTE_IF("bug42064_simulate_oom",
                  DBUG_SET("-d,bug42064_simulate_oom");); 

  if (m_cpp_buf == NULL)
126
    return TRUE;
127

128
  m_cpp_ptr= m_cpp_buf;
129 130 131 132 133 134 135 136
  m_thd= thd;
  m_ptr= buff;
  m_end_of_query= buff + length;
  m_buf= buff;
  m_buf_length= length;
  ignore_space= test(thd->variables.sql_mode & MODE_IGNORE_SPACE);

  return FALSE;
137 138 139
}


unknown's avatar
unknown committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
/**
  The operation is called from the parser in order to
  1) designate the intention to have utf8 body;
  1) Indicate to the lexer that we will need a utf8 representation of this
     statement;
  2) Determine the beginning of the body.

  @param thd        Thread context.
  @param begin_ptr  Pointer to the start of the body in the pre-processed
                    buffer.
*/

void Lex_input_stream::body_utf8_start(THD *thd, const char *begin_ptr)
{
  DBUG_ASSERT(begin_ptr);
  DBUG_ASSERT(m_cpp_buf <= begin_ptr && begin_ptr <= m_cpp_buf + m_buf_length);

  uint body_utf8_length=
    (m_buf_length / thd->variables.character_set_client->mbminlen) *
    my_charset_utf8_bin.mbmaxlen;

  m_body_utf8= (char *) thd->alloc(body_utf8_length + 1);
  m_body_utf8_ptr= m_body_utf8;
  *m_body_utf8_ptr= 0;

  m_cpp_utf8_processed_ptr= begin_ptr;
}

/**
unknown's avatar
unknown committed
169
  @brief The operation appends unprocessed part of pre-processed buffer till
unknown's avatar
unknown committed
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
  the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to end_ptr.

  The idea is that some tokens in the pre-processed buffer (like character
  set introducers) should be skipped.

  Example:
    CPP buffer: SELECT 'str1', _latin1 'str2';
    m_cpp_utf8_processed_ptr -- points at the "SELECT ...";
    In order to skip "_latin1", the following call should be made:
      body_utf8_append(<pointer to "_latin1 ...">, <pointer to " 'str2'...">)

  @param ptr      Pointer in the pre-processed buffer, which specifies the
                  end of the chunk, which should be appended to the utf8
                  body.
  @param end_ptr  Pointer in the pre-processed buffer, to which
                  m_cpp_utf8_processed_ptr will be set in the end of the
                  operation.
*/

void Lex_input_stream::body_utf8_append(const char *ptr,
                                        const char *end_ptr)
{
  DBUG_ASSERT(m_cpp_buf <= ptr && ptr <= m_cpp_buf + m_buf_length);
  DBUG_ASSERT(m_cpp_buf <= end_ptr && end_ptr <= m_cpp_buf + m_buf_length);

  if (!m_body_utf8)
    return;

  if (m_cpp_utf8_processed_ptr >= ptr)
    return;

  int bytes_to_copy= ptr - m_cpp_utf8_processed_ptr;

  memcpy(m_body_utf8_ptr, m_cpp_utf8_processed_ptr, bytes_to_copy);
  m_body_utf8_ptr += bytes_to_copy;
  *m_body_utf8_ptr= 0;

  m_cpp_utf8_processed_ptr= end_ptr;
}

/**
  The operation appends unprocessed part of the pre-processed buffer till
  the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to ptr.

  @param ptr  Pointer in the pre-processed buffer, which specifies the end
              of the chunk, which should be appended to the utf8 body.
*/

void Lex_input_stream::body_utf8_append(const char *ptr)
{
  body_utf8_append(ptr, ptr);
}

/**
  The operation converts the specified text literal to the utf8 and appends
  the result to the utf8-body.

  @param thd      Thread context.
  @param txt      Text literal.
  @param txt_cs   Character set of the text literal.
  @param end_ptr  Pointer in the pre-processed buffer, to which
                  m_cpp_utf8_processed_ptr will be set in the end of the
                  operation.
*/

void Lex_input_stream::body_utf8_append_literal(THD *thd,
                                                const LEX_STRING *txt,
                                                CHARSET_INFO *txt_cs,
                                                const char *end_ptr)
{
  if (!m_cpp_utf8_processed_ptr)
    return;

  LEX_STRING utf_txt;

unknown's avatar
unknown committed
245
  if (!my_charset_same(txt_cs, &my_charset_utf8_general_ci))
unknown's avatar
unknown committed
246 247 248
  {
    thd->convert_string(&utf_txt,
                        &my_charset_utf8_general_ci,
249
                        txt->str, (uint) txt->length,
unknown's avatar
unknown committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
                        txt_cs);
  }
  else
  {
    utf_txt.str= txt->str;
    utf_txt.length= txt->length;
  }

  /* NOTE: utf_txt.length is in bytes, not in symbols. */

  memcpy(m_body_utf8_ptr, utf_txt.str, utf_txt.length);
  m_body_utf8_ptr += utf_txt.length;
  *m_body_utf8_ptr= 0;

  m_cpp_utf8_processed_ptr= end_ptr;
}

267

268 269 270 271 272 273
/*
  This is called before every query that is to be parsed.
  Because of this, it's critical to not do too much things here.
  (We already do too much here)
*/

274
void lex_start(THD *thd)
unknown's avatar
unknown committed
275
{
unknown's avatar
unknown committed
276
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
277 278 279 280
  DBUG_ENTER("lex_start");

  lex->thd= lex->unit.thd= thd;

unknown's avatar
unknown committed
281
  lex->context_stack.empty();
282 283
  lex->unit.init_query();
  lex->unit.init_select();
unknown's avatar
unknown committed
284 285
  /* 'parent_lex' is used in init_query() so it must be before it. */
  lex->select_lex.parent_lex= lex;
286 287
  lex->select_lex.init_query();
  lex->value_list.empty();
unknown's avatar
unknown committed
288
  lex->update_list.empty();
289
  lex->set_var_list.empty();
290
  lex->param_list.empty();
unknown's avatar
unknown committed
291
  lex->view_list.empty();
292
  lex->prepared_stmt_params.empty();
293
  lex->auxiliary_table_list.empty();
294 295 296 297 298 299 300 301 302 303
  lex->unit.next= lex->unit.master=
    lex->unit.link_next= lex->unit.return_to= 0;
  lex->unit.prev= lex->unit.link_prev= 0;
  lex->unit.slave= lex->unit.global_parameters= lex->current_select=
    lex->all_selects_list= &lex->select_lex;
  lex->select_lex.master= &lex->unit;
  lex->select_lex.prev= &lex->unit.slave;
  lex->select_lex.link_next= lex->select_lex.slave= lex->select_lex.next= 0;
  lex->select_lex.link_prev= (st_select_lex_node**)&(lex->all_selects_list);
  lex->select_lex.options= 0;
304
  lex->select_lex.sql_cache= SELECT_LEX::SQL_CACHE_UNSPECIFIED;
unknown's avatar
unknown committed
305 306
  lex->select_lex.init_order();
  lex->select_lex.group_list.empty();
307
  lex->describe= 0;
unknown's avatar
unknown committed
308
  lex->subqueries= FALSE;
Sergey Glukhov's avatar
Sergey Glukhov committed
309
  lex->context_analysis_only= 0;
unknown's avatar
unknown committed
310
  lex->derived_tables= 0;
311 312
  lex->lock_option= TL_READ;
  lex->safe_to_cache_query= 1;
313
  lex->parsing_options.reset();
unknown's avatar
unknown committed
314
  lex->empty_field_list_on_rset= 0;
315
  lex->select_lex.select_number= 1;
unknown's avatar
unknown committed
316
  lex->length=0;
317
  lex->part_info= 0;
unknown's avatar
unknown committed
318
  lex->select_lex.in_sum_expr=0;
unknown's avatar
unknown committed
319
  lex->select_lex.ftfunc_list_alloc.empty();
320
  lex->select_lex.ftfunc_list= &lex->select_lex.ftfunc_list_alloc;
unknown's avatar
unknown committed
321 322
  lex->select_lex.group_list.empty();
  lex->select_lex.order_list.empty();
323
  lex->sql_command= SQLCOM_END;
324
  lex->duplicates= DUP_ERROR;
325
  lex->ignore= 0;
unknown's avatar
unknown committed
326
  lex->spname= NULL;
327 328
  lex->sphead= NULL;
  lex->spcont= NULL;
unknown's avatar
unknown committed
329
  lex->proc_list.first= 0;
unknown's avatar
unknown committed
330
  lex->escape_used= FALSE;
unknown's avatar
unknown committed
331
  lex->query_tables= 0;
332
  lex->reset_query_tables_list(FALSE);
333
  lex->expr_allows_subselect= TRUE;
334
  lex->use_only_table_context= FALSE;
335
  lex->parse_vcol_expr= FALSE;
336

337 338
  lex->name.str= 0;
  lex->name.length= 0;
unknown's avatar
unknown committed
339
  lex->event_parse_data= NULL;
unknown's avatar
unknown committed
340
  lex->profile_options= PROFILE_NONE;
unknown's avatar
unknown committed
341 342 343
  lex->nest_level=0 ;
  lex->allow_sum_func= 0;
  lex->in_sum_func= NULL;
344
  lex->protect_against_global_read_lock= FALSE;
unknown's avatar
unknown committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
  /*
    ok, there must be a better solution for this, long-term
    I tried "bzero" in the sql_yacc.yy code, but that for
    some reason made the values zero, even if they were set
  */
  lex->server_options.server_name= 0;
  lex->server_options.server_name_length= 0;
  lex->server_options.host= 0;
  lex->server_options.db= 0;
  lex->server_options.username= 0;
  lex->server_options.password= 0;
  lex->server_options.scheme= 0;
  lex->server_options.socket= 0;
  lex->server_options.owner= 0;
  lex->server_options.port= -1;
unknown's avatar
unknown committed
360

361
  lex->is_lex_started= TRUE;
unknown's avatar
unknown committed
362
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
363 364 365 366
}

void lex_end(LEX *lex)
{
unknown's avatar
unknown committed
367
  DBUG_ENTER("lex_end");
unknown's avatar
unknown committed
368
  DBUG_PRINT("enter", ("lex: 0x%lx", (long) lex));
unknown's avatar
unknown committed
369 370 371 372 373 374

  /* release used plugins */
  plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer, 
                     lex->plugins.elements);
  reset_dynamic(&lex->plugins);

unknown's avatar
unknown committed
375
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
376 377
}

378 379 380 381
Yacc_state::~Yacc_state()
{
  if (yacc_yyss)
  {
382 383
    my_free(yacc_yyss, MYF(0));
    my_free(yacc_yyvs, MYF(0));
384
  }
unknown's avatar
unknown committed
385 386
}

387
static int find_keyword(Lex_input_stream *lip, uint len, bool function)
unknown's avatar
unknown committed
388
{
389
  const char *tok= lip->get_tok_start();
unknown's avatar
unknown committed
390

391
  SYMBOL *symbol= get_hash_symbol(tok, len, function);
unknown's avatar
unknown committed
392 393
  if (symbol)
  {
394 395 396 397
    lip->yylval->symbol.symbol=symbol;
    lip->yylval->symbol.str= (char*) tok;
    lip->yylval->symbol.length=len;

398
    if ((symbol->tok == NOT_SYM) &&
399
        (lip->m_thd->variables.sql_mode & MODE_HIGH_NOT_PRECEDENCE))
400 401
      return NOT2_SYM;
    if ((symbol->tok == OR_OR_SYM) &&
402
	!(lip->m_thd->variables.sql_mode & MODE_PIPES_AS_CONCAT))
403
      return OR2_SYM;
404

unknown's avatar
unknown committed
405 406 407 408 409
    return symbol->tok;
  }
  return 0;
}

410 411 412 413 414
/*
  Check if name is a keyword

  SYNOPSIS
    is_keyword()
415
    name      checked name (must not be empty)
416 417 418 419 420 421 422 423 424
    len       length of checked name

  RETURN VALUES
    0         name is a keyword
    1         name isn't a keyword
*/

bool is_keyword(const char *name, uint len)
{
425
  DBUG_ASSERT(len != 0);
426 427
  return get_hash_symbol(name,len,0)!=0;
}
unknown's avatar
unknown committed
428

429 430 431 432 433
/**
  Check if name is a sql function

    @param name      checked name

434
    @return is this a native function or not
435 436 437 438
    @retval 0         name is a function
    @retval 1         name isn't a function
*/

439 440 441
bool is_lex_native_function(const LEX_STRING *name)
{
  DBUG_ASSERT(name != NULL);
442
  return (get_hash_symbol(name->str, (uint) name->length, 1) != 0);
443 444
}

unknown's avatar
unknown committed
445 446
/* make a copy of token before ptr and set yytoklen */

447
static LEX_STRING get_token(Lex_input_stream *lip, uint skip, uint length)
unknown's avatar
unknown committed
448 449
{
  LEX_STRING tmp;
450
  lip->yyUnget();                       // ptr points now after last token char
451
  tmp.length=lip->yytoklen=length;
452
  tmp.str= lip->m_thd->strmake(lip->get_tok_start() + skip, tmp.length);
unknown's avatar
unknown committed
453 454 455 456

  lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
  lip->m_cpp_text_end= lip->m_cpp_text_start + tmp.length;

unknown's avatar
unknown committed
457 458 459
  return tmp;
}

460 461 462 463 464 465 466
/* 
 todo: 
   There are no dangerous charsets in mysql for function 
   get_quoted_token yet. But it should be fixed in the 
   future to operate multichar strings (like ucs2)
*/

467
static LEX_STRING get_quoted_token(Lex_input_stream *lip,
468
                                   uint skip,
469
                                   uint length, char quote)
470 471
{
  LEX_STRING tmp;
472 473
  const char *from, *end;
  char *to;
474
  lip->yyUnget();                       // ptr points now after last token char
475 476
  tmp.length= lip->yytoklen=length;
  tmp.str=(char*) lip->m_thd->alloc(tmp.length+1);
477
  from= lip->get_tok_start() + skip;
478
  to= tmp.str;
479
  end= to+length;
unknown's avatar
unknown committed
480 481 482 483

  lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
  lip->m_cpp_text_end= lip->m_cpp_text_start + length;

484
  for ( ; to != end; )
485
  {
486
    if ((*to++= *from++) == quote)
unknown's avatar
unknown committed
487
    {
488
      from++;					// Skip double quotes
unknown's avatar
unknown committed
489 490
      lip->m_cpp_text_start++;
    }
491 492 493 494 495 496 497 498 499 500
  }
  *to= 0;					// End null for safety
  return tmp;
}


/*
  Return an unescaped text literal without quotes
  Fix sometimes to do only one scan of the string
*/
unknown's avatar
unknown committed
501

502
static char *get_text(Lex_input_stream *lip, int pre_skip, int post_skip)
unknown's avatar
unknown committed
503 504 505
{
  reg1 uchar c,sep;
  uint found_escape=0;
506
  CHARSET_INFO *cs= lip->m_thd->charset();
unknown's avatar
unknown committed
507

508
  lip->tok_bitmap= 0;
509 510
  sep= lip->yyGetLast();                        // String should end with this
  while (! lip->eof())
unknown's avatar
unknown committed
511
  {
512
    c= lip->yyGet();
513
    lip->tok_bitmap|= c;
unknown's avatar
unknown committed
514
#ifdef USE_MB
515 516 517
    {
      int l;
      if (use_mb(cs) &&
518 519 520 521 522
          (l = my_ismbchar(cs,
                           lip->get_ptr() -1,
                           lip->get_end_of_query()))) {
        lip->skip_binary(l-1);
        continue;
523
      }
unknown's avatar
unknown committed
524 525
    }
#endif
526
    if (c == '\\' &&
527
        !(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))
unknown's avatar
unknown committed
528 529
    {					// Escaped character
      found_escape=1;
530
      if (lip->eof())
unknown's avatar
unknown committed
531
	return 0;
532
      lip->yySkip();
unknown's avatar
unknown committed
533 534 535
    }
    else if (c == sep)
    {
536
      if (c == lip->yyGet())            // Check if two separators in a row
unknown's avatar
unknown committed
537
      {
538
        found_escape=1;                 // duplicate. Remember for delete
unknown's avatar
unknown committed
539 540 541
	continue;
      }
      else
542
        lip->yyUnget();
unknown's avatar
unknown committed
543 544

      /* Found end. Unescape and return string */
545 546
      const char *str, *end;
      char *start;
unknown's avatar
unknown committed
547

548 549 550 551 552 553 554
      str= lip->get_tok_start();
      end= lip->get_ptr();
      /* Extract the text from the token */
      str += pre_skip;
      end -= post_skip;
      DBUG_ASSERT(end >= str);

555
      if (!(start= (char*) lip->m_thd->alloc((uint) (end-str)+1)))
unknown's avatar
unknown committed
556
	return (char*) "";		// Sql_alloc has set error flag
unknown's avatar
unknown committed
557 558 559 560

      lip->m_cpp_text_start= lip->get_cpp_tok_start() + pre_skip;
      lip->m_cpp_text_end= lip->get_cpp_ptr() - post_skip;

unknown's avatar
unknown committed
561 562
      if (!found_escape)
      {
563 564 565
	lip->yytoklen=(uint) (end-str);
	memcpy(start,str,lip->yytoklen);
	start[lip->yytoklen]=0;
unknown's avatar
unknown committed
566 567 568
      }
      else
      {
569
        char *to;
570

unknown's avatar
unknown committed
571 572 573 574
	for (to=start ; str != end ; str++)
	{
#ifdef USE_MB
	  int l;
unknown's avatar
unknown committed
575
	  if (use_mb(cs) &&
576
              (l = my_ismbchar(cs, str, end))) {
unknown's avatar
unknown committed
577 578 579 580 581 582
	      while (l--)
		  *to++ = *str++;
	      str--;
	      continue;
	  }
#endif
583
	  if (!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
584
              *str == '\\' && str+1 != end)
unknown's avatar
unknown committed
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
	  {
	    switch(*++str) {
	    case 'n':
	      *to++='\n';
	      break;
	    case 't':
	      *to++= '\t';
	      break;
	    case 'r':
	      *to++ = '\r';
	      break;
	    case 'b':
	      *to++ = '\b';
	      break;
	    case '0':
	      *to++= 0;			// Ascii null
	      break;
	    case 'Z':			// ^Z must be escaped on Win32
	      *to++='\032';
	      break;
	    case '_':
	    case '%':
	      *to++= '\\';		// remember prefix for wildcard
	      /* Fall through */
	    default:
610
              *to++= *str;
unknown's avatar
unknown committed
611 612 613
	      break;
	    }
	  }
614 615
	  else if (*str == sep)
	    *to++= *str++;		// Two ' or "
unknown's avatar
unknown committed
616 617 618 619
	  else
	    *to++ = *str;
	}
	*to=0;
620
	lip->yytoklen=(uint) (to-start);
unknown's avatar
unknown committed
621
      }
622
      return start;
unknown's avatar
unknown committed
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    }
  }
  return 0;					// unexpected end of query
}


/*
** Calc type of integer; long integer, longlong integer or real.
** Returns smallest type that match the string.
** When using unsigned long long values the result is converted to a real
** because else they will be unexpected sign changes because all calculation
** is done with longlong or double.
*/

static const char *long_str="2147483647";
static const uint long_len=10;
static const char *signed_long_str="-2147483648";
static const char *longlong_str="9223372036854775807";
static const uint longlong_len=19;
static const char *signed_longlong_str="-9223372036854775808";
static const uint signed_longlong_len=19;
unknown's avatar
unknown committed
644 645
static const char *unsigned_longlong_str="18446744073709551615";
static const uint unsigned_longlong_len=20;
unknown's avatar
unknown committed
646

unknown's avatar
unknown committed
647
static inline uint int_token(const char *str,uint length)
unknown's avatar
unknown committed
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
{
  if (length < long_len)			// quick normal case
    return NUM;
  bool neg=0;

  if (*str == '+')				// Remove sign and pre-zeros
  {
    str++; length--;
  }
  else if (*str == '-')
  {
    str++; length--;
    neg=1;
  }
  while (*str == '0' && length)
  {
    str++; length --;
  }
  if (length < long_len)
    return NUM;

  uint smaller,bigger;
  const char *cmp;
  if (neg)
  {
    if (length == long_len)
    {
      cmp= signed_long_str+1;
      smaller=NUM;				// If <= signed_long_str
      bigger=LONG_NUM;				// If >= signed_long_str
    }
    else if (length < signed_longlong_len)
      return LONG_NUM;
    else if (length > signed_longlong_len)
unknown's avatar
unknown committed
682
      return DECIMAL_NUM;
unknown's avatar
unknown committed
683 684 685 686
    else
    {
      cmp=signed_longlong_str+1;
      smaller=LONG_NUM;				// If <= signed_longlong_str
unknown's avatar
unknown committed
687
      bigger=DECIMAL_NUM;
unknown's avatar
unknown committed
688 689 690 691 692 693 694 695 696 697 698 699 700
    }
  }
  else
  {
    if (length == long_len)
    {
      cmp= long_str;
      smaller=NUM;
      bigger=LONG_NUM;
    }
    else if (length < longlong_len)
      return LONG_NUM;
    else if (length > longlong_len)
unknown's avatar
unknown committed
701 702
    {
      if (length > unsigned_longlong_len)
unknown's avatar
unknown committed
703
        return DECIMAL_NUM;
unknown's avatar
unknown committed
704 705
      cmp=unsigned_longlong_str;
      smaller=ULONGLONG_NUM;
unknown's avatar
unknown committed
706
      bigger=DECIMAL_NUM;
unknown's avatar
unknown committed
707
    }
unknown's avatar
unknown committed
708 709 710 711
    else
    {
      cmp=longlong_str;
      smaller=LONG_NUM;
712
      bigger= ULONGLONG_NUM;
unknown's avatar
unknown committed
713 714 715 716 717 718
    }
  }
  while (*cmp && *cmp++ == *str++) ;
  return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
}

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765

/**
  Given a stream that is advanced to the first contained character in 
  an open comment, consume the comment.  Optionally, if we are allowed, 
  recurse so that we understand comments within this current comment.

  At this level, we do not support version-condition comments.  We might 
  have been called with having just passed one in the stream, though.  In 
  that case, we probably want to tolerate mundane comments inside.  Thus,
  the case for recursion.

  @retval  Whether EOF reached before comment is closed.
*/
bool consume_comment(Lex_input_stream *lip, int remaining_recursions_permitted)
{
  reg1 uchar c;
  while (! lip->eof())
  {
    c= lip->yyGet();

    if (remaining_recursions_permitted > 0)
    {
      if ((c == '/') && (lip->yyPeek() == '*'))
      {
        lip->yySkip(); /* Eat asterisk */
        consume_comment(lip, remaining_recursions_permitted-1);
        continue;
      }
    }

    if (c == '*')
    {
      if (lip->yyPeek() == '/')
      {
        lip->yySkip(); /* Eat slash */
        return FALSE;
      }
    }

    if (c == '\n')
      lip->yylineno++;
  }

  return TRUE;
}


766
/*
767
  MYSQLlex remember the following states from the following MYSQLlex()
768 769 770 771 772

  - MY_LEX_EOQ			Found end of query
  - MY_LEX_OPERATOR_OR_IDENT	Last state was an ident, text or number
				(which can't be followed by a signed number)
*/
unknown's avatar
unknown committed
773

774
int MYSQLlex(void *arg, void *yythd)
unknown's avatar
unknown committed
775 776
{
  reg1	uchar c;
777
  bool comment_closed;
778
  int	tokval, result_state;
unknown's avatar
unknown committed
779
  uint length;
unknown's avatar
unknown committed
780
  enum my_lex_states state;
781
  THD *thd= (THD *)yythd;
782
  Lex_input_stream *lip= & thd->m_parser_state->m_lip;
783
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
784
  YYSTYPE *yylval=(YYSTYPE*) arg;
785 786 787
  CHARSET_INFO *const cs= thd->charset();
  const uchar *const state_map= cs->state_map;
  const uchar *const ident_map= cs->ident_map;
unknown's avatar
unknown committed
788

Sergey Petrunya's avatar
Sergey Petrunya committed
789
  LINT_INIT(c);
790
  lip->yylval=yylval;			// The global state
791

792
  lip->start_token();
793 794
  state=lip->next_state;
  lip->next_state=MY_LEX_OPERATOR_OR_IDENT;
unknown's avatar
unknown committed
795 796
  for (;;)
  {
797
    switch (state) {
798 799
    case MY_LEX_OPERATOR_OR_IDENT:	// Next is operator or keyword
    case MY_LEX_START:			// Start of token
800 801
      // Skip starting whitespace
      while(state_map[c= lip->yyPeek()] == MY_LEX_SKIP)
unknown's avatar
unknown committed
802 803
      {
	if (c == '\n')
804
	  lip->yylineno++;
805 806

        lip->yySkip();
unknown's avatar
unknown committed
807
      }
808 809 810 811

      /* Start of real token */
      lip->restart_token();
      c= lip->yyGet();
812
      state= (enum my_lex_states) state_map[c];
unknown's avatar
unknown committed
813
      break;
814
    case MY_LEX_ESCAPE:
815
      if (lip->yyGet() == 'N')
unknown's avatar
unknown committed
816 817 818 819 820
      {					// Allow \N as shortcut for NULL
	yylval->lex_str.str=(char*) "\\N";
	yylval->lex_str.length=2;
	return NULL_SYM;
      }
821
      /* Fall through */
822 823
    case MY_LEX_CHAR:			// Unknown or single char token
    case MY_LEX_SKIP:			// This should not happen
824 825 826 827 828 829
      if (c != ')')
	lip->next_state= MY_LEX_START;	// Allow signed numbers
      return((int) c);

    case MY_LEX_MINUS_OR_COMMENT:
      if (lip->yyPeek() == '-' &&
830 831
          (my_isspace(cs,lip->yyPeekn(1)) ||
           my_iscntrl(cs,lip->yyPeekn(1))))
832 833 834 835
      {
        state=MY_LEX_COMMENT;
        break;
      }
836 837
      lip->next_state= MY_LEX_START;	// Allow signed numbers
      return((int) c);
838

839 840 841 842 843 844 845 846 847
    case MY_LEX_PLACEHOLDER:
      /*
        Check for a placeholder: it should not precede a possible identifier
        because of binlogging: when a placeholder is replaced with
        its value in a query for the binlog, the query must stay
        grammatically correct.
      */
      lip->next_state= MY_LEX_START;	// Allow signed numbers
      if (lip->stmt_prepare_mode && !ident_map[(uchar) lip->yyPeek()])
848
        return(PARAM_MARKER);
849
      return((int) c);
850

851 852 853 854 855 856 857 858 859 860 861 862
    case MY_LEX_COMMA:
      lip->next_state= MY_LEX_START;	// Allow signed numbers
      /*
        Warning:
        This is a work around, to make the "remember_name" rule in
        sql/sql_yacc.yy work properly.
        The problem is that, when parsing "select expr1, expr2",
        the code generated by bison executes the *pre* action
        remember_name (see select_item) *before* actually parsing the
        first token of expr2.
      */
      lip->restart_token();
unknown's avatar
unknown committed
863 864
      return((int) c);

unknown's avatar
unknown committed
865
    case MY_LEX_IDENT_OR_NCHAR:
866 867
      if (lip->yyPeek() != '\'')
      {
unknown's avatar
unknown committed
868 869 870
	state= MY_LEX_IDENT;
	break;
      }
871
      /* Found N'string' */
872 873
      lip->yySkip();                         // Skip '
      if (!(yylval->lex_str.str = get_text(lip, 2, 1)))
unknown's avatar
unknown committed
874
      {
875 876
	state= MY_LEX_CHAR;             // Read char by char
	break;
unknown's avatar
unknown committed
877
      }
878
      yylval->lex_str.length= lip->yytoklen;
879
      lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
880
      return(NCHAR_STRING);
unknown's avatar
unknown committed
881

882
    case MY_LEX_IDENT_OR_HEX:
883
      if (lip->yyPeek() == '\'')
884
      {					// Found x'hex-number'
885
	state= MY_LEX_HEX_NUMBER;
886 887
	break;
      }
unknown's avatar
unknown committed
888
    case MY_LEX_IDENT_OR_BIN:
889
      if (lip->yyPeek() == '\'')
unknown's avatar
unknown committed
890 891 892 893
      {                                 // Found b'bin-number'
        state= MY_LEX_BIN_NUMBER;
        break;
      }
894
    case MY_LEX_IDENT:
895
      const char *start;
unknown's avatar
unknown committed
896
#if defined(USE_MB) && defined(USE_MB_IDENT)
897
      if (use_mb(cs))
unknown's avatar
unknown committed
898
      {
899
	result_state= IDENT_QUOTED;
900
        if (my_mbcharlen(cs, lip->yyGetLast()) > 1)
unknown's avatar
unknown committed
901
        {
902 903 904
          int l = my_ismbchar(cs,
                              lip->get_ptr() -1,
                              lip->get_end_of_query());
unknown's avatar
unknown committed
905
          if (l == 0) {
906
            state = MY_LEX_CHAR;
unknown's avatar
unknown committed
907 908
            continue;
          }
909
          lip->skip_binary(l - 1);
unknown's avatar
unknown committed
910
        }
911
        while (ident_map[c=lip->yyGet()])
unknown's avatar
unknown committed
912
        {
913
          if (my_mbcharlen(cs, c) > 1)
unknown's avatar
unknown committed
914 915
          {
            int l;
916 917 918
            if ((l = my_ismbchar(cs,
                                 lip->get_ptr() -1,
                                 lip->get_end_of_query())) == 0)
unknown's avatar
unknown committed
919
              break;
920
            lip->skip_binary(l-1);
unknown's avatar
unknown committed
921 922 923 924 925
          }
        }
      }
      else
#endif
926
      {
927 928 929 930
        for (result_state= c;
             ident_map[(uchar) (c= lip->yyGet())];
             result_state|= c)
          ;
unknown's avatar
unknown committed
931 932
        /* If there were non-ASCII characters, mark that we must convert */
        result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
933
      }
934 935
      length= lip->yyLength();
      start= lip->get_ptr();
936
      if (lip->ignore_space)
unknown's avatar
unknown committed
937
      {
unknown's avatar
unknown committed
938 939 940 941
        /*
          If we find a space then this can't be an identifier. We notice this
          below by checking start != lex->ptr.
        */
942 943
        for (; state_map[(uchar) c] == MY_LEX_SKIP ; c= lip->yyGet())
          ;
unknown's avatar
unknown committed
944
      }
945 946
      if (start == lip->get_ptr() && c == '.' &&
          ident_map[(uchar) lip->yyPeek()])
947
	lip->next_state=MY_LEX_IDENT_SEP;
unknown's avatar
unknown committed
948 949
      else
      {					// '(' must follow directly if function
950 951
        lip->yyUnget();
	if ((tokval = find_keyword(lip, length, c == '(')))
unknown's avatar
unknown committed
952
	{
953
	  lip->next_state= MY_LEX_START;	// Allow signed numbers
unknown's avatar
unknown committed
954 955
	  return(tokval);		// Was keyword
	}
956
        lip->yySkip();                  // next state does a unget
unknown's avatar
unknown committed
957
      }
958
      yylval->lex_str=get_token(lip, 0, length);
959

unknown's avatar
unknown committed
960
      /*
961 962
         Note: "SELECT _bla AS 'alias'"
         _bla should be considered as a IDENT if charset haven't been found.
unknown's avatar
unknown committed
963
         So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
964 965 966
         producing an error.
      */

unknown's avatar
unknown committed
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
      if (yylval->lex_str.str[0] == '_')
      {
        CHARSET_INFO *cs= get_charset_by_csname(yylval->lex_str.str + 1,
                                                MY_CS_PRIMARY, MYF(0));
        if (cs)
        {
          yylval->charset= cs;
          lip->m_underscore_cs= cs;

          lip->body_utf8_append(lip->m_cpp_text_start,
                                lip->get_cpp_tok_start() + length);
          return(UNDERSCORE_CHARSET);
        }
      }

      lip->body_utf8_append(lip->m_cpp_text_start);

      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
                                    lip->m_cpp_text_end);

987
      return(result_state);			// IDENT or IDENT_QUOTED
unknown's avatar
unknown committed
988

989
    case MY_LEX_IDENT_SEP:                  // Found ident and now '.'
990 991
      yylval->lex_str.str= (char*) lip->get_ptr();
      yylval->lex_str.length= 1;
992 993 994
      c= lip->yyGet();                          // should be '.'
      lip->next_state= MY_LEX_IDENT_START;      // Next is ident (not keyword)
      if (!ident_map[(uchar) lip->yyPeek()])    // Probably ` or "
995
	lip->next_state= MY_LEX_START;
unknown's avatar
unknown committed
996 997
      return((int) c);

998
    case MY_LEX_NUMBER_IDENT:		// number or ident which num-start
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
      if (lip->yyGetLast() == '0')
      {
        c= lip->yyGet();
        if (c == 'x')
        {
          while (my_isxdigit(cs,(c = lip->yyGet()))) ;
          if ((lip->yyLength() >= 3) && !ident_map[c])
          {
            /* skip '0x' */
            yylval->lex_str=get_token(lip, 2, lip->yyLength()-2);
            return (HEX_NUM);
          }
          lip->yyUnget();
          state= MY_LEX_IDENT_START;
          break;
        }
        else if (c == 'b')
        {
1017 1018
          while ((c= lip->yyGet()) == '0' || c == '1')
            ;
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
          if ((lip->yyLength() >= 3) && !ident_map[c])
          {
            /* Skip '0b' */
            yylval->lex_str= get_token(lip, 2, lip->yyLength()-2);
            return (BIN_NUM);
          }
          lip->yyUnget();
          state= MY_LEX_IDENT_START;
          break;
        }
        lip->yyUnget();
      }

      while (my_isdigit(cs, (c = lip->yyGet()))) ;
unknown's avatar
unknown committed
1033
      if (!ident_map[c])
unknown's avatar
unknown committed
1034
      {					// Can't be identifier
1035
	state=MY_LEX_INT_OR_REAL;
unknown's avatar
unknown committed
1036 1037 1038 1039
	break;
      }
      if (c == 'e' || c == 'E')
      {
unknown's avatar
unknown committed
1040
	// The following test is written this way to allow numbers of type 1e1
1041 1042
        if (my_isdigit(cs,lip->yyPeek()) ||
            (c=(lip->yyGet())) == '+' || c == '-')
unknown's avatar
unknown committed
1043
	{				// Allow 1E+10
1044
          if (my_isdigit(cs,lip->yyPeek()))     // Number must have digit after sign
unknown's avatar
unknown committed
1045
	  {
1046 1047 1048
            lip->yySkip();
            while (my_isdigit(cs,lip->yyGet())) ;
            yylval->lex_str=get_token(lip, 0, lip->yyLength());
unknown's avatar
unknown committed
1049 1050 1051
	    return(FLOAT_NUM);
	  }
	}
1052
        lip->yyUnget();
unknown's avatar
unknown committed
1053
      }
unknown's avatar
unknown committed
1054
      // fall through
1055
    case MY_LEX_IDENT_START:			// We come here after '.'
1056
      result_state= IDENT;
unknown's avatar
unknown committed
1057
#if defined(USE_MB) && defined(USE_MB_IDENT)
1058
      if (use_mb(cs))
unknown's avatar
unknown committed
1059
      {
1060
	result_state= IDENT_QUOTED;
1061
        while (ident_map[c=lip->yyGet()])
unknown's avatar
unknown committed
1062
        {
1063
          if (my_mbcharlen(cs, c) > 1)
unknown's avatar
unknown committed
1064 1065
          {
            int l;
1066 1067 1068
            if ((l = my_ismbchar(cs,
                                 lip->get_ptr() -1,
                                 lip->get_end_of_query())) == 0)
unknown's avatar
unknown committed
1069
              break;
1070
            lip->skip_binary(l-1);
unknown's avatar
unknown committed
1071 1072 1073 1074 1075
          }
        }
      }
      else
#endif
unknown's avatar
unknown committed
1076
      {
1077 1078
        for (result_state=0; ident_map[c= lip->yyGet()]; result_state|= c)
          ;
unknown's avatar
unknown committed
1079 1080 1081
        /* If there were non-ASCII characters, mark that we must convert */
        result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
      }
1082
      if (c == '.' && ident_map[(uchar) lip->yyPeek()])
1083
	lip->next_state=MY_LEX_IDENT_SEP;// Next is '.'
unknown's avatar
unknown committed
1084

1085
      yylval->lex_str= get_token(lip, 0, lip->yyLength());
unknown's avatar
unknown committed
1086 1087 1088 1089 1090

      lip->body_utf8_append(lip->m_cpp_text_start);

      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
                                    lip->m_cpp_text_end);
unknown's avatar
unknown committed
1091

1092
      return(result_state);
unknown's avatar
unknown committed
1093

1094
    case MY_LEX_USER_VARIABLE_DELIMITER:	// Found quote char
1095
    {
1096 1097
      uint double_quotes= 0;
      char quote_char= c;                       // Used char
1098
      while ((c=lip->yyGet()))
unknown's avatar
unknown committed
1099
      {
1100 1101
	int var_length;
	if ((var_length= my_mbcharlen(cs, c)) == 1)
1102 1103 1104
	{
	  if (c == quote_char)
	  {
1105
            if (lip->yyPeek() != quote_char)
1106
	      break;
1107
            c=lip->yyGet();
1108 1109 1110
	    double_quotes++;
	    continue;
	  }
1111 1112
	}
#ifdef USE_MB
Davi Arnaut's avatar
Davi Arnaut committed
1113
        else if (use_mb(cs))
1114
        {
Davi Arnaut's avatar
Davi Arnaut committed
1115 1116 1117
          if ((var_length= my_ismbchar(cs, lip->get_ptr() - 1,
                                       lip->get_end_of_query())))
            lip->skip_binary(var_length-1);
1118
        }
1119
#endif
unknown's avatar
unknown committed
1120
      }
1121
      if (double_quotes)
1122
	yylval->lex_str=get_quoted_token(lip, 1,
1123
                                         lip->yyLength() - double_quotes -1,
1124 1125
					 quote_char);
      else
1126
        yylval->lex_str=get_token(lip, 1, lip->yyLength() -1);
1127
      if (c == quote_char)
1128
        lip->yySkip();                  // Skip end `
1129
      lip->next_state= MY_LEX_START;
unknown's avatar
unknown committed
1130 1131 1132 1133 1134 1135

      lip->body_utf8_append(lip->m_cpp_text_start);

      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
                                    lip->m_cpp_text_end);

1136
      return(IDENT_QUOTED);
1137
    }
1138
    case MY_LEX_INT_OR_REAL:		// Complete int or incomplete real
unknown's avatar
unknown committed
1139 1140
      if (c != '.')
      {					// Found complete integer number.
1141
        yylval->lex_str=get_token(lip, 0, lip->yyLength());
1142
	return int_token(yylval->lex_str.str, (uint) yylval->lex_str.length);
unknown's avatar
unknown committed
1143 1144
      }
      // fall through
1145
    case MY_LEX_REAL:			// Incomplete real number
1146
      while (my_isdigit(cs,c = lip->yyGet())) ;
unknown's avatar
unknown committed
1147 1148 1149

      if (c == 'e' || c == 'E')
      {
1150
        c = lip->yyGet();
unknown's avatar
unknown committed
1151
	if (c == '-' || c == '+')
1152
          c = lip->yyGet();                     // Skip sign
1153
	if (!my_isdigit(cs,c))
unknown's avatar
unknown committed
1154
	{				// No digit after sign
1155
	  state= MY_LEX_CHAR;
unknown's avatar
unknown committed
1156 1157
	  break;
	}
1158 1159
        while (my_isdigit(cs,lip->yyGet())) ;
        yylval->lex_str=get_token(lip, 0, lip->yyLength());
unknown's avatar
unknown committed
1160 1161
	return(FLOAT_NUM);
      }
1162
      yylval->lex_str=get_token(lip, 0, lip->yyLength());
unknown's avatar
unknown committed
1163
      return(DECIMAL_NUM);
unknown's avatar
unknown committed
1164

1165
    case MY_LEX_HEX_NUMBER:		// Found x'hexstring'
1166 1167 1168 1169 1170 1171 1172 1173
      lip->yySkip();                    // Accept opening '
      while (my_isxdigit(cs, (c= lip->yyGet()))) ;
      if (c != '\'')
        return(ABORT_SYM);              // Illegal hex constant
      lip->yySkip();                    // Accept closing '
      length= lip->yyLength();          // Length of hexnum+3
      if ((length % 2) == 0)
        return(ABORT_SYM);              // odd number of hex digits
1174 1175 1176
      yylval->lex_str=get_token(lip,
                                2,          // skip x'
                                length-3);  // don't count x' and last '
1177 1178
      return (HEX_NUM);

unknown's avatar
unknown committed
1179
    case MY_LEX_BIN_NUMBER:           // Found b'bin-string'
1180
      lip->yySkip();                  // Accept opening '
1181 1182
      while ((c= lip->yyGet()) == '0' || c == '1')
        ;
unknown's avatar
unknown committed
1183
      if (c != '\'')
1184 1185 1186
        return(ABORT_SYM);            // Illegal hex constant
      lip->yySkip();                  // Accept closing '
      length= lip->yyLength();        // Length of bin-num + 3
1187 1188 1189 1190
      yylval->lex_str= get_token(lip,
                                 2,         // skip b'
                                 length-3); // don't count b' and last '
      return (BIN_NUM);
unknown's avatar
unknown committed
1191

1192
    case MY_LEX_CMP_OP:			// Incomplete comparison operator
1193 1194
      if (state_map[(uchar) lip->yyPeek()] == MY_LEX_CMP_OP ||
          state_map[(uchar) lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
1195 1196
        lip->yySkip();
      if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
unknown's avatar
unknown committed
1197
      {
1198
	lip->next_state= MY_LEX_START;	// Allow signed numbers
unknown's avatar
unknown committed
1199 1200
	return(tokval);
      }
1201
      state = MY_LEX_CHAR;		// Something fishy found
unknown's avatar
unknown committed
1202 1203
      break;

1204
    case MY_LEX_LONG_CMP_OP:		// Incomplete comparison operator
1205 1206
      if (state_map[(uchar) lip->yyPeek()] == MY_LEX_CMP_OP ||
          state_map[(uchar) lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
unknown's avatar
unknown committed
1207
      {
1208
        lip->yySkip();
1209
        if (state_map[(uchar) lip->yyPeek()] == MY_LEX_CMP_OP)
1210
          lip->yySkip();
unknown's avatar
unknown committed
1211
      }
1212
      if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
unknown's avatar
unknown committed
1213
      {
1214
	lip->next_state= MY_LEX_START;	// Found long op
unknown's avatar
unknown committed
1215 1216
	return(tokval);
      }
1217
      state = MY_LEX_CHAR;		// Something fishy found
unknown's avatar
unknown committed
1218 1219
      break;

1220
    case MY_LEX_BOOL:
1221
      if (c != lip->yyPeek())
unknown's avatar
unknown committed
1222
      {
1223
	state=MY_LEX_CHAR;
unknown's avatar
unknown committed
1224 1225
	break;
      }
1226
      lip->yySkip();
1227 1228
      tokval = find_keyword(lip,2,0);	// Is a bool operator
      lip->next_state= MY_LEX_START;	// Allow signed numbers
unknown's avatar
unknown committed
1229 1230
      return(tokval);

1231
    case MY_LEX_STRING_OR_DELIMITER:
1232
      if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
1233
      {
1234
	state= MY_LEX_USER_VARIABLE_DELIMITER;
1235 1236 1237
	break;
      }
      /* " used for strings */
1238
    case MY_LEX_STRING:			// Incomplete text string
1239
      if (!(yylval->lex_str.str = get_text(lip, 1, 1)))
unknown's avatar
unknown committed
1240
      {
1241
	state= MY_LEX_CHAR;		// Read char by char
unknown's avatar
unknown committed
1242 1243
	break;
      }
1244
      yylval->lex_str.length=lip->yytoklen;
unknown's avatar
unknown committed
1245 1246 1247 1248 1249 1250 1251 1252 1253

      lip->body_utf8_append(lip->m_cpp_text_start);

      lip->body_utf8_append_literal(thd, &yylval->lex_str,
        lip->m_underscore_cs ? lip->m_underscore_cs : cs,
        lip->m_cpp_text_end);

      lip->m_underscore_cs= NULL;

1254
      lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
unknown's avatar
unknown committed
1255 1256
      return(TEXT_STRING);

1257
    case MY_LEX_COMMENT:			//  Comment
unknown's avatar
unknown committed
1258
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
1259 1260
      while ((c = lip->yyGet()) != '\n' && c) ;
      lip->yyUnget();                   // Safety against eof
1261
      state = MY_LEX_START;		// Try again
unknown's avatar
unknown committed
1262
      break;
1263
    case MY_LEX_LONG_COMMENT:		/* Long C comment? */
1264
      if (lip->yyPeek() != '*')
unknown's avatar
unknown committed
1265
      {
1266
	state=MY_LEX_CHAR;		// Probable division
unknown's avatar
unknown committed
1267 1268
	break;
      }
unknown's avatar
unknown committed
1269
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
1270 1271 1272
      /* Reject '/' '*', since we might need to turn off the echo */
      lip->yyUnget();

1273 1274
      lip->save_in_comment_state();

1275
      if (lip->yyPeekn(2) == '!')
unknown's avatar
unknown committed
1276
      {
1277 1278
        lip->in_comment= DISCARD_COMMENT;
        /* Accept '/' '*' '!', but do not keep this marker. */
unknown's avatar
unknown committed
1279
        lip->set_echo(FALSE);
1280 1281 1282 1283 1284 1285 1286
        lip->yySkip();
        lip->yySkip();
        lip->yySkip();

        /*
          The special comment format is very strict:
          '/' '*' '!', followed by exactly
1287 1288 1289 1290
          1 digit (major), 2 digits (minor), then 2 digits (dot).
          32302 -> 3.23.02
          50032 -> 5.0.32
          50114 -> 5.1.14
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
        */
        char version_str[6];
        version_str[0]= lip->yyPeekn(0);
        version_str[1]= lip->yyPeekn(1);
        version_str[2]= lip->yyPeekn(2);
        version_str[3]= lip->yyPeekn(3);
        version_str[4]= lip->yyPeekn(4);
        version_str[5]= 0;
        if (  my_isdigit(cs, version_str[0])
           && my_isdigit(cs, version_str[1])
           && my_isdigit(cs, version_str[2])
           && my_isdigit(cs, version_str[3])
           && my_isdigit(cs, version_str[4])
           )
        {
          ulong version;
          version=strtol(version_str, NULL, 10);

          if (version <= MYSQL_VERSION_ID)
          {
1311 1312
            /* Accept 'M' 'm' 'm' 'd' 'd' */
            lip->yySkipn(5);
1313
            /* Expand the content of the special comment as real code */
unknown's avatar
unknown committed
1314
            lip->set_echo(TRUE);
1315
            state=MY_LEX_START;
1316 1317 1318 1319
            break;  /* Do not treat contents as a comment.  */
          }
          else
          {
1320 1321 1322 1323 1324
            /*
              Patch and skip the conditional comment to avoid it
              being propagated infinitely (eg. to a slave).
            */
            char *pcom= lip->yyUnput(' ');
1325
            comment_closed= ! consume_comment(lip, 1);
1326 1327 1328 1329
            if (! comment_closed)
            {
              *pcom= '!';
            }
1330
            /* version allowed to have one level of comment inside. */
1331 1332 1333 1334
          }
        }
        else
        {
1335
          /* Not a version comment. */
1336
          state=MY_LEX_START;
unknown's avatar
unknown committed
1337
          lip->set_echo(TRUE);
1338 1339
          break;
        }
unknown's avatar
unknown committed
1340
      }
1341
      else
unknown's avatar
unknown committed
1342
      {
1343 1344 1345
        lip->in_comment= PRESERVE_COMMENT;
        lip->yySkip();                  // Accept /
        lip->yySkip();                  // Accept *
1346 1347
        comment_closed= ! consume_comment(lip, 0);
        /* regular comments can have zero comments inside. */
unknown's avatar
unknown committed
1348
      }
1349 1350 1351 1352 1353
      /*
        Discard:
        - regular '/' '*' comments,
        - special comments '/' '*' '!' for a future version,
        by scanning until we find a closing '*' '/' marker.
1354 1355 1356 1357 1358 1359 1360 1361 1362

        Nesting regular comments isn't allowed.  The first 
        '*' '/' returns the parser to the previous state.

        /#!VERSI oned containing /# regular #/ is allowed #/

		Inside one versioned comment, another versioned comment
		is treated as a regular discardable comment.  It gets
		no special parsing.
1363
      */
1364

1365 1366 1367
      /* Unbalanced comments with a missing '*' '/' are a syntax error */
      if (! comment_closed)
        return (ABORT_SYM);
1368
      state = MY_LEX_START;             // Try again
1369
      lip->restore_in_comment_state();
unknown's avatar
unknown committed
1370
      break;
1371
    case MY_LEX_END_LONG_COMMENT:
1372
      if ((lip->in_comment != NO_COMMENT) && lip->yyPeek() == '/')
unknown's avatar
unknown committed
1373
      {
1374 1375 1376 1377 1378 1379
        /* Reject '*' '/' */
        lip->yyUnget();
        /* Accept '*' '/', with the proper echo */
        lip->set_echo(lip->in_comment == PRESERVE_COMMENT);
        lip->yySkipn(2);
        /* And start recording the tokens again */
unknown's avatar
unknown committed
1380
        lip->set_echo(TRUE);
1381 1382
        lip->in_comment=NO_COMMENT;
        state=MY_LEX_START;
unknown's avatar
unknown committed
1383 1384
      }
      else
1385
	state=MY_LEX_CHAR;		// Return '*'
unknown's avatar
unknown committed
1386
      break;
1387
    case MY_LEX_SET_VAR:		// Check if ':='
1388
      if (lip->yyPeek() != '=')
unknown's avatar
unknown committed
1389
      {
1390
	state=MY_LEX_CHAR;		// Return ':'
unknown's avatar
unknown committed
1391 1392
	break;
      }
1393
      lip->yySkip();
unknown's avatar
unknown committed
1394
      return (SET_VAR);
1395
    case MY_LEX_SEMICOLON:			// optional line terminator
1396 1397
      state= MY_LEX_CHAR;               // Return ';'
      break;
1398
    case MY_LEX_EOL:
1399
      if (lip->eof())
unknown's avatar
unknown committed
1400
      {
1401
        lip->yyUnget();                 // Reject the last '\0'
unknown's avatar
unknown committed
1402
        lip->set_echo(FALSE);
1403
        lip->yySkip();
unknown's avatar
unknown committed
1404
        lip->set_echo(TRUE);
1405 1406 1407
        /* Unbalanced comments with a missing '*' '/' are a syntax error */
        if (lip->in_comment != NO_COMMENT)
          return (ABORT_SYM);
1408 1409
        lip->next_state=MY_LEX_END;     // Mark for next loop
        return(END_OF_INPUT);
unknown's avatar
unknown committed
1410 1411 1412
      }
      state=MY_LEX_CHAR;
      break;
1413
    case MY_LEX_END:
1414
      lip->next_state=MY_LEX_END;
unknown's avatar
unknown committed
1415
      return(0);			// We found end of input last time
1416

1417
      /* Actually real shouldn't start with . but allow them anyhow */
1418
    case MY_LEX_REAL_OR_POINT:
1419
      if (my_isdigit(cs,lip->yyPeek()))
1420
	state = MY_LEX_REAL;		// Real
unknown's avatar
unknown committed
1421 1422
      else
      {
1423
	state= MY_LEX_IDENT_SEP;	// return '.'
1424
        lip->yyUnget();                 // Put back '.'
unknown's avatar
unknown committed
1425 1426
      }
      break;
1427
    case MY_LEX_USER_END:		// end '@' of user@hostname
1428
      switch (state_map[(uchar) lip->yyPeek()]) {
1429 1430 1431
      case MY_LEX_STRING:
      case MY_LEX_USER_VARIABLE_DELIMITER:
      case MY_LEX_STRING_OR_DELIMITER:
unknown's avatar
unknown committed
1432
	break;
1433
      case MY_LEX_USER_END:
1434
	lip->next_state=MY_LEX_SYSTEM_VAR;
unknown's avatar
unknown committed
1435 1436
	break;
      default:
1437
	lip->next_state=MY_LEX_HOSTNAME;
unknown's avatar
unknown committed
1438 1439
	break;
      }
1440
      yylval->lex_str.str=(char*) lip->get_ptr();
unknown's avatar
unknown committed
1441 1442
      yylval->lex_str.length=1;
      return((int) '@');
1443
    case MY_LEX_HOSTNAME:		// end '@' of user@hostname
1444
      for (c=lip->yyGet() ;
1445
	   my_isalnum(cs,c) || c == '.' || c == '_' ||  c == '$';
1446 1447
           c= lip->yyGet()) ;
      yylval->lex_str=get_token(lip, 0, lip->yyLength());
unknown's avatar
unknown committed
1448
      return(LEX_HOSTNAME);
1449
    case MY_LEX_SYSTEM_VAR:
1450
      yylval->lex_str.str=(char*) lip->get_ptr();
unknown's avatar
unknown committed
1451
      yylval->lex_str.length=1;
1452
      lip->yySkip();                                    // Skip '@'
1453
      lip->next_state= (state_map[(uchar) lip->yyPeek()] ==
1454 1455 1456
			MY_LEX_USER_VARIABLE_DELIMITER ?
			MY_LEX_OPERATOR_OR_IDENT :
			MY_LEX_IDENT_OR_KEYWORD);
unknown's avatar
unknown committed
1457
      return((int) '@');
1458
    case MY_LEX_IDENT_OR_KEYWORD:
unknown's avatar
unknown committed
1459 1460 1461 1462 1463
      /*
	We come here when we have found two '@' in a row.
	We should now be able to handle:
	[(global | local | session) .]variable_name
      */
1464

1465 1466
      for (result_state= 0; ident_map[c= lip->yyGet()]; result_state|= c)
        ;
unknown's avatar
unknown committed
1467 1468
      /* If there were non-ASCII characters, mark that we must convert */
      result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1469

unknown's avatar
unknown committed
1470
      if (c == '.')
1471
	lip->next_state=MY_LEX_IDENT_SEP;
1472 1473
      length= lip->yyLength();
      if (length == 0)
unknown's avatar
unknown committed
1474
        return(ABORT_SYM);              // Names must be nonempty.
1475
      if ((tokval= find_keyword(lip, length,0)))
unknown's avatar
unknown committed
1476
      {
1477
        lip->yyUnget();                         // Put back 'c'
unknown's avatar
unknown committed
1478 1479
	return(tokval);				// Was keyword
      }
1480
      yylval->lex_str=get_token(lip, 0, length);
unknown's avatar
unknown committed
1481 1482 1483 1484 1485 1486

      lip->body_utf8_append(lip->m_cpp_text_start);

      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
                                    lip->m_cpp_text_end);

1487
      return(result_state);
unknown's avatar
unknown committed
1488 1489 1490
    }
  }
}
unknown's avatar
unknown committed
1491

1492

unknown's avatar
unknown committed
1493 1494 1495
/**
  Construct a copy of this object to be used for mysql_alter_table
  and mysql_create_table.
1496

unknown's avatar
unknown committed
1497 1498 1499 1500
  Historically, these two functions modify their Alter_info
  arguments. This behaviour breaks re-execution of prepared
  statements and stored procedures and is compensated by always
  supplying a copy of Alter_info to these functions.
1501

unknown's avatar
unknown committed
1502 1503
  @return You need to use check the error in THD for out
  of memory condition after calling this function.
1504 1505
*/

1506 1507 1508 1509 1510 1511 1512 1513 1514
Alter_info::Alter_info(const Alter_info &rhs, MEM_ROOT *mem_root)
  :drop_list(rhs.drop_list, mem_root),
  alter_list(rhs.alter_list, mem_root),
  key_list(rhs.key_list, mem_root),
  create_list(rhs.create_list, mem_root),
  flags(rhs.flags),
  keys_onoff(rhs.keys_onoff),
  tablespace_op(rhs.tablespace_op),
  partition_names(rhs.partition_names, mem_root),
unknown's avatar
unknown committed
1515 1516 1517 1518
  no_parts(rhs.no_parts),
  change_level(rhs.change_level),
  datetime_field(rhs.datetime_field),
  error_if_not_empty(rhs.error_if_not_empty)
1519
{
1520 1521 1522
  /*
    Make deep copies of used objects.
    This is not a fully deep copy - clone() implementations
unknown's avatar
unknown committed
1523
    of Alter_drop, Alter_column, Key, foreign_key, Key_part_spec
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
    do not copy string constants. At the same length the only
    reason we make a copy currently is that ALTER/CREATE TABLE
    code changes input Alter_info definitions, but string
    constants never change.
  */
  list_copy_and_replace_each_value(drop_list, mem_root);
  list_copy_and_replace_each_value(alter_list, mem_root);
  list_copy_and_replace_each_value(key_list, mem_root);
  list_copy_and_replace_each_value(create_list, mem_root);
  /* partition_names are not deeply copied currently */
}


1537 1538 1539 1540 1541 1542 1543
void trim_whitespace(CHARSET_INFO *cs, LEX_STRING *str)
{
  /*
    TODO:
    This code assumes that there are no multi-bytes characters
    that can be considered white-space.
  */
1544

1545 1546 1547 1548 1549
  while ((str->length > 0) && (my_isspace(cs, str->str[0])))
  {
    str->length --;
    str->str ++;
  }
1550

1551 1552 1553 1554 1555 1556 1557 1558
  /*
    FIXME:
    Also, parsing backward is not safe with multi bytes characters
  */
  while ((str->length > 0) && (my_isspace(cs, str->str[str->length-1])))
  {
    str->length --;
  }
1559 1560
}

1561

unknown's avatar
unknown committed
1562 1563 1564 1565 1566 1567
/*
  st_select_lex structures initialisations
*/

void st_select_lex_node::init_query()
{
1568
  options= 0;
1569
  sql_cache= SQL_CACHE_UNSPECIFIED;
1570
  linkage= UNSPECIFIED_TYPE;
1571 1572
  no_error= no_table_names_allowed= 0;
  uncacheable= 0;
unknown's avatar
unknown committed
1573 1574 1575 1576 1577 1578 1579 1580 1581
}

void st_select_lex_node::init_select()
{
}

void st_select_lex_unit::init_query()
{
  st_select_lex_node::init_query();
1582
  linkage= GLOBAL_OPTIONS_TYPE;
unknown's avatar
unknown committed
1583
  global_parameters= first_select();
1584 1585
  select_limit_cnt= HA_POS_ERROR;
  offset_limit_cnt= 0;
1586
  union_distinct= 0;
unknown's avatar
unknown committed
1587
  prepared= optimized= executed= 0;
unknown's avatar
unknown committed
1588
  item= 0;
1589 1590
  union_result= 0;
  table= 0;
unknown's avatar
unknown committed
1591
  fake_select_lex= 0;
1592
  cleaned= 0;
1593
  item_list.empty();
1594
  describe= 0;
1595
  found_rows_for_union= 0;
Igor Babaev's avatar
Igor Babaev committed
1596
  insert_table_with_stored_vcol= 0;
1597
  derived= 0;
unknown's avatar
unknown committed
1598 1599 1600 1601 1602
}

void st_select_lex::init_query()
{
  st_select_lex_node::init_query();
1603
  table_list.empty();
1604 1605
  top_join_list.empty();
  join_list= &top_join_list;
1606 1607
  embedding= 0;
  leaf_tables.empty();
unknown's avatar
unknown committed
1608
  item_list.empty();
unknown's avatar
unknown committed
1609
  join= 0;
1610
  having= prep_having= where= prep_where= 0;
1611
  olap= UNSPECIFIED_OLAP_TYPE;
1612
  having_fix_field= 0;
1613 1614
  context.select_lex= this;
  context.init();
unknown's avatar
unknown committed
1615 1616 1617
  /*
    Add the name resolution context of the current (sub)query to the
    stack of contexts for the whole query.
1618 1619 1620 1621 1622
    TODO:
    push_context may return an error if there is no memory for a new
    element in the stack, however this method has no return value,
    thus push_context should be moved to a place where query
    initialization is checked for failure.
unknown's avatar
unknown committed
1623 1624
  */
  parent_lex->push_context(&context);
1625
  cond_count= between_count= with_wild= 0;
unknown's avatar
unknown committed
1626
  max_equal_elems= 0;
1627
  conds_processed_with_permanent_arena= 0;
unknown's avatar
unknown committed
1628
  ref_pointer_array= 0;
unknown's avatar
unknown committed
1629
  select_n_where_fields= 0;
unknown's avatar
unknown committed
1630
  select_n_having_items= 0;
1631
  subquery_in_having= explicit_limit= 0;
1632
  is_item_list_lookup= 0;
1633
  first_execution= 1;
1634
  first_natural_join_processing= 1;
unknown's avatar
unknown committed
1635
  first_cond_optimization= 1;
1636
  parsing_place= NO_MATTER;
1637
  exclude_from_table_unique_test= no_wrap_view_item= FALSE;
unknown's avatar
unknown committed
1638
  nest_level= 0;
1639
  link_next= 0;
1640
  lock_option= TL_READ_DEFAULT;
unknown's avatar
unknown committed
1641 1642

  bzero((char*) expr_cache_may_be_used, sizeof(expr_cache_may_be_used));
unknown's avatar
unknown committed
1643 1644 1645 1646 1647
}

void st_select_lex::init_select()
{
  st_select_lex_node::init_select();
1648
  sj_nests.empty();
1649
  group_list.empty();
unknown's avatar
unknown committed
1650
  type= db= 0;
1651 1652 1653
  having= 0;
  table_join_options= 0;
  in_sum_expr= with_wild= 0;
unknown's avatar
unknown committed
1654
  options= 0;
1655
  sql_cache= SQL_CACHE_UNSPECIFIED;
1656
  braces= 0;
unknown's avatar
unknown committed
1657
  interval_list.empty();
unknown's avatar
unknown committed
1658
  ftfunc_list_alloc.empty();
unknown's avatar
unknown committed
1659
  inner_sum_func_list= 0;
unknown's avatar
unknown committed
1660
  ftfunc_list= &ftfunc_list_alloc;
unknown's avatar
unknown committed
1661
  linkage= UNSPECIFIED_TYPE;
unknown's avatar
unknown committed
1662 1663
  order_list.elements= 0;
  order_list.first= 0;
1664
  order_list.next= &order_list.first;
1665 1666 1667
  /* Set limit and offset to default values */
  select_limit= 0;      /* denotes the default limit = HA_POS_ERROR */
  offset_limit= 0;      /* denotes the default offset = 0 */
unknown's avatar
unknown committed
1668
  with_sum_func= 0;
1669
  is_correlated= 0;
1670 1671
  cur_pos_in_select_list= UNDEF_POS;
  non_agg_fields.empty();
1672
  cond_value= having_value= Item::COND_UNDEF;
1673
  inner_refs_list.empty();
1674
  full_group_by_flag= 0;
1675
  insert_tables= 0;
Igor Babaev's avatar
Igor Babaev committed
1676
  merged_into= 0;
unknown's avatar
unknown committed
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
}

/*
  st_select_lex structures linking
*/

/* include on level down */
void st_select_lex_node::include_down(st_select_lex_node *upper)
{
  if ((next= upper->slave))
    next->prev= &next;
  prev= &upper->slave;
  upper->slave= this;
  master= upper;
unknown's avatar
unknown committed
1691
  slave= 0;
unknown's avatar
unknown committed
1692 1693
}

unknown's avatar
unknown committed
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718

void st_select_lex_node::add_slave(st_select_lex_node *slave_arg)
{
  for (; slave; slave= slave->next)
    if (slave == slave_arg)
      return;

  if (slave)
  {
    st_select_lex_node *slave_arg_slave= slave_arg->slave;
    /* Insert in the front of list of slaves if any. */
    slave_arg->include_neighbour(slave);
    /* include_neighbour() sets slave_arg->slave=0, restore it. */
    slave_arg->slave= slave_arg_slave;
    /* Count on include_neighbour() setting the master. */
    DBUG_ASSERT(slave_arg->master == this);
  }
  else
  {
    slave= slave_arg;
    slave_arg->master= this;
  }
}


unknown's avatar
unknown committed
1719 1720
/*
  include on level down (but do not link)
unknown's avatar
unknown committed
1721

unknown's avatar
unknown committed
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
  SYNOPSYS
    st_select_lex_node::include_standalone()
    upper - reference on node underr which this node should be included
    ref - references on reference on this node
*/
void st_select_lex_node::include_standalone(st_select_lex_node *upper,
					    st_select_lex_node **ref)
{
  next= 0;
  prev= ref;
  master= upper;
  slave= 0;
}

unknown's avatar
unknown committed
1736 1737 1738 1739 1740 1741 1742 1743
/* include neighbour (on same level) */
void st_select_lex_node::include_neighbour(st_select_lex_node *before)
{
  if ((next= before->next))
    next->prev= &next;
  prev= &before->next;
  before->next= this;
  master= before->master;
unknown's avatar
unknown committed
1744
  slave= 0;
unknown's avatar
unknown committed
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
}

/* including in global SELECT_LEX list */
void st_select_lex_node::include_global(st_select_lex_node **plink)
{
  if ((link_next= *plink))
    link_next->link_prev= &link_next;
  link_prev= plink;
  *plink= this;
}

//excluding from global list (internal function)
void st_select_lex_node::fast_exclude()
{
unknown's avatar
unknown committed
1759
  if (link_prev)
unknown's avatar
unknown committed
1760 1761 1762 1763
  {
    if ((*link_prev= link_next))
      link_next->link_prev= link_prev;
  }
1764 1765 1766 1767
  // Remove slave structure
  for (; slave; slave= slave->next)
    slave->fast_exclude();
  
unknown's avatar
unknown committed
1768 1769
}

1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782

/*
  Exclude a node from the tree lex structure, but leave it in the global
  list of nodes.
*/

void st_select_lex_node::exclude_from_tree()
{
  if ((*prev= next))
    next->prev= prev;
}


unknown's avatar
unknown committed
1783
/*
1784
  Exclude select_lex structure (except first (first select can't be
unknown's avatar
unknown committed
1785 1786 1787 1788
  deleted, because it is most upper select))
*/
void st_select_lex_node::exclude()
{
1789
  /* exclude from global list */
unknown's avatar
unknown committed
1790
  fast_exclude();
1791 1792
  /* exclude from other structures */
  exclude_from_tree();
unknown's avatar
unknown committed
1793 1794 1795 1796 1797 1798 1799
  /* 
     We do not need following statements, because prev pointer of first 
     list element point to master->slave
     if (master->slave == this)
       master->slave= next;
  */
}
1800

1801 1802 1803 1804 1805 1806 1807 1808 1809 1810

/*
  Exclude level of current unit from tree of SELECTs

  SYNOPSYS
    st_select_lex_unit::exclude_level()

  NOTE: units which belong to current will be brought up on level of
  currernt unit 
*/
unknown's avatar
unknown committed
1811 1812 1813
void st_select_lex_unit::exclude_level()
{
  SELECT_LEX_UNIT *units= 0, **units_last= &units;
unknown's avatar
unknown committed
1814
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
unknown's avatar
unknown committed
1815
  {
unknown's avatar
unknown committed
1816
    // unlink current level from global SELECTs list
unknown's avatar
unknown committed
1817 1818
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
      sl->link_next->link_prev= sl->link_prev;
unknown's avatar
unknown committed
1819 1820

    // bring up underlay levels
unknown's avatar
unknown committed
1821 1822
    SELECT_LEX_UNIT **last= 0;
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
unknown's avatar
unknown committed
1823 1824
    {
      u->master= master;
unknown's avatar
unknown committed
1825
      last= (SELECT_LEX_UNIT**)&(u->next);
unknown's avatar
unknown committed
1826
    }
unknown's avatar
unknown committed
1827 1828 1829 1830 1831 1832 1833 1834
    if (last)
    {
      (*units_last)= sl->first_inner_unit();
      units_last= last;
    }
  }
  if (units)
  {
unknown's avatar
unknown committed
1835
    // include brought up levels in place of current
unknown's avatar
unknown committed
1836 1837
    (*prev)= units;
    (*units_last)= (SELECT_LEX_UNIT*)next;
unknown's avatar
unknown committed
1838 1839 1840
    if (next)
      next->prev= (SELECT_LEX_NODE**)units_last;
    units->prev= prev;
unknown's avatar
unknown committed
1841 1842
  }
  else
unknown's avatar
unknown committed
1843 1844
  {
    // exclude currect unit from list of nodes
unknown's avatar
unknown committed
1845
    (*prev)= next;
unknown's avatar
unknown committed
1846 1847 1848
    if (next)
      next->prev= prev;
  }
unknown's avatar
unknown committed
1849 1850
}

1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861

/*
  Exclude subtree of current unit from tree of SELECTs

  SYNOPSYS
    st_select_lex_unit::exclude_tree()
*/
void st_select_lex_unit::exclude_tree()
{
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
  {
unknown's avatar
unknown committed
1862
    // unlink current level from global SELECTs list
1863 1864 1865
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
      sl->link_next->link_prev= sl->link_prev;

unknown's avatar
unknown committed
1866
    // unlink underlay levels
1867 1868 1869 1870 1871
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
    {
      u->exclude_level();
    }
  }
unknown's avatar
unknown committed
1872
  // exclude currect unit from list of nodes
1873
  (*prev)= next;
unknown's avatar
unknown committed
1874 1875
  if (next)
    next->prev= prev;
1876 1877 1878
}


unknown's avatar
unknown committed
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
/**
  Register reference to an item which the subqueries depends on

  @param def_sel         select against which the item is resolved
  @param dependency      reference to the item

  @details
  This function puts the reference dependency to an item that is either an
  outer field or an aggregate function resolved against an outer select into
  the list 'depends_on'. It adds it to the 'depends_on' lists for each
  subquery between this one and 'def_sel' - the subquery against which the
  item is resolved.
*/

void st_select_lex::register_dependency_item(st_select_lex *def_sel,
                                             Item **dependency)
{
  SELECT_LEX *s= this;
  DBUG_ENTER("st_select_lex::register_dependency_item");
  DBUG_ASSERT(this != def_sel);
  DBUG_ASSERT(*dependency);
Sergey Petrunya's avatar
Sergey Petrunya committed
1900 1901 1902 1903
  //psergey-add-stupid:
  while (def_sel->merged_into)
    def_sel= def_sel->merged_into;
  //:eof
unknown's avatar
unknown committed
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
  do
  {
    /* check duplicates */
    List_iterator_fast<Item*> li(s->master_unit()->item->depends_on);
    Item **dep;
    while ((dep= li++))
    {
      if ((*dep)->eq(*dependency, FALSE))
      {
         DBUG_PRINT("info", ("dependency %s already present",
                             ((*dependency)->name ?
                              (*dependency)->name :
                              "<no name>")));
         DBUG_VOID_RETURN;
      }
    }

    s->master_unit()->item->depends_on.push_back(dependency);
    DBUG_PRINT("info", ("depends_on: Select: %d  added: %s",
                        s->select_number,
                        ((*dependency)->name ?
                         (*dependency)->name :
                         "<no name>")));
  } while ((s= s->outer_select()) != def_sel);
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
/*
  st_select_lex_node::mark_as_dependent mark all st_select_lex struct from 
  this to 'last' as dependent

  SYNOPSIS
    last - pointer to last st_select_lex struct, before wich all 
           st_select_lex have to be marked as dependent

  NOTE
    'last' should be reachable from this st_select_lex_node
*/

1944
bool st_select_lex::mark_as_dependent(THD *thd, st_select_lex *last, Item *dependency)
unknown's avatar
unknown committed
1945
{
1946 1947 1948

  DBUG_ASSERT(this != last);

unknown's avatar
unknown committed
1949 1950 1951 1952
  /*
    Mark all selects from resolved to 1 before select where was
    found table as depended (of select where was found table)
  */
1953 1954
  SELECT_LEX *s= this;
  do
Sergey Petrunya's avatar
Sergey Petrunya committed
1955
  {
1956
    if (!(s->uncacheable & UNCACHEABLE_DEPENDENT_GENERATED))
unknown's avatar
unknown committed
1957 1958
    {
      // Select is dependent of outer select
1959
      s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
1960
                       UNCACHEABLE_DEPENDENT_GENERATED;
1961
      SELECT_LEX_UNIT *munit= s->master_unit();
1962
      munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
1963
                       UNCACHEABLE_DEPENDENT_GENERATED;
1964 1965 1966
      for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
      {
        if (sl != s &&
1967 1968
            !(sl->uncacheable & (UNCACHEABLE_DEPENDENT_GENERATED |
                                 UNCACHEABLE_UNITED)))
1969 1970
          sl->uncacheable|= UNCACHEABLE_UNITED;
      }
unknown's avatar
unknown committed
1971
    }
1972 1973 1974 1975 1976

    Item_subselect *subquery_expr= s->master_unit()->item;
    if (subquery_expr && subquery_expr->mark_as_dependent(thd, last, 
                                                          dependency))
      return TRUE;
1977
  } while ((s= s->outer_select()) != last && s != 0);
1978 1979
  is_correlated= TRUE;
  this->master_unit()->item->is_correlated= TRUE;
1980
  return FALSE;
unknown's avatar
unknown committed
1981 1982
}

1983 1984 1985 1986 1987
bool st_select_lex_node::set_braces(bool value)      { return 1; }
bool st_select_lex_node::inc_in_sum_expr()           { return 1; }
uint st_select_lex_node::get_in_sum_expr()           { return 0; }
TABLE_LIST* st_select_lex_node::get_table_list()     { return 0; }
List<Item>* st_select_lex_node::get_item_list()      { return 0; }
1988
TABLE_LIST *st_select_lex_node::add_table_to_list (THD *thd, Table_ident *table,
1989
						  LEX_STRING *alias,
unknown's avatar
unknown committed
1990
						  ulong table_join_options,
1991
						  thr_lock_type flags,
unknown's avatar
unknown committed
1992
						  List<Index_hint> *hints,
unknown's avatar
unknown committed
1993
                                                  LEX_STRING *option)
1994 1995 1996
{
  return 0;
}
unknown's avatar
unknown committed
1997 1998 1999 2000 2001 2002 2003 2004
ulong st_select_lex_node::get_table_join_options()
{
  return 0;
}

/*
  prohibit using LIMIT clause
*/
unknown's avatar
unknown committed
2005
bool st_select_lex::test_limit()
unknown's avatar
unknown committed
2006
{
2007
  if (select_limit != 0)
unknown's avatar
unknown committed
2008 2009
  {
    my_error(ER_NOT_SUPPORTED_YET, MYF(0),
unknown's avatar
unknown committed
2010
             "LIMIT & IN/ALL/ANY/SOME subquery");
unknown's avatar
unknown committed
2011 2012 2013 2014
    return(1);
  }
  return(0);
}
2015

2016

2017 2018 2019 2020 2021
st_select_lex_unit* st_select_lex_unit::master_unit()
{
    return this;
}

2022

2023 2024 2025 2026 2027
st_select_lex* st_select_lex_unit::outer_select()
{
  return (st_select_lex*) master;
}

2028

unknown's avatar
unknown committed
2029
bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
unknown's avatar
unknown committed
2030
{
unknown's avatar
unknown committed
2031
  return add_to_list(thd, order_list, item, asc);
unknown's avatar
unknown committed
2032
}
2033

2034

unknown's avatar
unknown committed
2035
bool st_select_lex::add_item_to_list(THD *thd, Item *item)
2036
{
2037
  DBUG_ENTER("st_select_lex::add_item_to_list");
unknown's avatar
unknown committed
2038
  DBUG_PRINT("info", ("Item: 0x%lx", (long) item));
2039
  DBUG_RETURN(item_list.push_back(item));
2040 2041
}

2042

unknown's avatar
unknown committed
2043
bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
2044
{
unknown's avatar
unknown committed
2045
  return add_to_list(thd, group_list, item, asc);
2046 2047
}

2048

2049 2050 2051 2052 2053
bool st_select_lex::add_ftfunc_to_list(Item_func_match *func)
{
  return !func || ftfunc_list->push_back(func); // end of memory?
}

2054

2055 2056 2057 2058 2059
st_select_lex_unit* st_select_lex::master_unit()
{
  return (st_select_lex_unit*) master;
}

2060

2061 2062 2063 2064 2065
st_select_lex* st_select_lex::outer_select()
{
  return (st_select_lex*) master->get_master();
}

2066

2067 2068 2069 2070 2071 2072
bool st_select_lex::set_braces(bool value)
{
  braces= value;
  return 0; 
}

2073

2074 2075 2076 2077 2078 2079
bool st_select_lex::inc_in_sum_expr()
{
  in_sum_expr++;
  return 0;
}

2080

2081 2082 2083 2084 2085
uint st_select_lex::get_in_sum_expr()
{
  return in_sum_expr;
}

2086

2087 2088
TABLE_LIST* st_select_lex::get_table_list()
{
2089
  return table_list.first;
2090 2091 2092 2093 2094 2095 2096
}

List<Item>* st_select_lex::get_item_list()
{
  return &item_list;
}

unknown's avatar
unknown committed
2097 2098 2099 2100 2101
ulong st_select_lex::get_table_join_options()
{
  return table_join_options;
}

2102

unknown's avatar
unknown committed
2103 2104
bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
{
2105 2106
  DBUG_ENTER("st_select_lex::setup_ref_array");

unknown's avatar
unknown committed
2107
  if (ref_pointer_array)
2108
    DBUG_RETURN(0);
2109 2110

  /*
2111
    We have to create array in prepared statement memory if it is a
2112 2113
    prepared statement
  */
2114 2115 2116 2117 2118 2119 2120
  ref_pointer_array=
    (Item **)thd->stmt_arena->alloc(sizeof(Item*) * (n_child_sum_items +
                                                     item_list.elements +
                                                     select_n_having_items +
                                                     select_n_where_fields +
                                                     order_group_num)*5);
  DBUG_RETURN(ref_pointer_array == 0);
unknown's avatar
unknown committed
2121 2122
}

2123

2124
void st_select_lex_unit::print(String *str, enum_query_type query_type)
unknown's avatar
unknown committed
2125
{
2126
  bool union_all= !union_distinct;
unknown's avatar
unknown committed
2127 2128 2129 2130
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
  {
    if (sl != first_select())
    {
2131
      str->append(STRING_WITH_LEN(" union "));
2132
      if (union_all)
2133
	str->append(STRING_WITH_LEN("all "));
2134
      else if (union_distinct == sl)
2135
        union_all= TRUE;
unknown's avatar
unknown committed
2136 2137 2138
    }
    if (sl->braces)
      str->append('(');
2139
    sl->print(thd, str, query_type);
unknown's avatar
unknown committed
2140 2141 2142 2143 2144 2145 2146
    if (sl->braces)
      str->append(')');
  }
  if (fake_select_lex == global_parameters)
  {
    if (fake_select_lex->order_list.elements)
    {
2147
      str->append(STRING_WITH_LEN(" order by "));
2148 2149
      fake_select_lex->print_order(str,
        fake_select_lex->order_list.first,
2150
        query_type);
unknown's avatar
unknown committed
2151
    }
2152
    fake_select_lex->print_limit(thd, str, query_type);
unknown's avatar
unknown committed
2153 2154 2155 2156
  }
}


2157 2158 2159
void st_select_lex::print_order(String *str,
                                ORDER *order,
                                enum_query_type query_type)
unknown's avatar
unknown committed
2160 2161 2162
{
  for (; order; order= order->next)
  {
2163 2164
    if (order->counter_used)
    {
2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
      if (query_type != QT_VIEW_INTERNAL)
      {
        char buffer[20];
        size_t length= my_snprintf(buffer, 20, "%d", order->counter);
        str->append(buffer, (uint) length);
      }
      else
      {
        /* replace numeric reference with expression */
        if (order->item[0]->type() == Item::INT_ITEM &&
            order->item[0]->basic_const_item())
        {
          char buffer[20];
          size_t length= my_snprintf(buffer, 20, "%d", order->counter);
          str->append(buffer, (uint) length);
          /* make it expression instead of integer constant */
          str->append(STRING_WITH_LEN("+0"));
        }
        else
          (*order->item)->print(str, query_type);
      }
2186 2187
    }
    else
2188
      (*order->item)->print(str, query_type);
unknown's avatar
unknown committed
2189
    if (!order->asc)
2190
      str->append(STRING_WITH_LEN(" desc"));
unknown's avatar
unknown committed
2191 2192 2193 2194 2195
    if (order->next)
      str->append(',');
  }
}
 
2196

2197 2198 2199
void st_select_lex::print_limit(THD *thd,
                                String *str,
                                enum_query_type query_type)
unknown's avatar
unknown committed
2200
{
2201 2202
  SELECT_LEX_UNIT *unit= master_unit();
  Item_subselect *item= unit->item;
2203 2204

  if (item && unit->global_parameters == this)
unknown's avatar
VIEW  
unknown committed
2205
  {
2206 2207 2208 2209 2210 2211 2212
    Item_subselect::subs_type subs_type= item->substype();
    if (subs_type == Item_subselect::EXISTS_SUBS ||
        subs_type == Item_subselect::IN_SUBS ||
        subs_type == Item_subselect::ALL_SUBS)
    {
      return;
    }
unknown's avatar
VIEW  
unknown committed
2213
  }
2214
  if (explicit_limit)
unknown's avatar
unknown committed
2215
  {
2216
    str->append(STRING_WITH_LEN(" limit "));
unknown's avatar
unknown committed
2217 2218
    if (offset_limit)
    {
2219
      offset_limit->print(str, query_type);
unknown's avatar
unknown committed
2220 2221
      str->append(',');
    }
2222
    select_limit->print(str, query_type);
unknown's avatar
unknown committed
2223 2224 2225
  }
}

2226

2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
/**
  @brief Restore the LEX and THD in case of a parse error.

  This is a clean up call that is invoked by the Bison generated
  parser before returning an error from MYSQLparse. If your
  semantic actions manipulate with the global thread state (which
  is a very bad practice and should not normally be employed) and
  need a clean-up in case of error, and you can not use %destructor
  rule in the grammar file itself, this function should be used
  to implement the clean up.
*/

void st_lex::cleanup_lex_after_parse_error(THD *thd)
{
  /*
    Delete sphead for the side effect of restoring of the original
    LEX state, thd->lex, thd->mem_root and thd->free_list if they
    were replaced when parsing stored procedure statements.  We
    will never use sphead object after a parse error, so it's okay
    to delete it only for the sake of the side effect.
    TODO: make this functionality explicit in sp_head class.
    Sic: we must nullify the member of the main lex, not the
    current one that will be thrown away
  */
2251
  if (thd->lex->sphead)
2252
  {
2253
    thd->lex->sphead->restore_thd_mem_root(thd);
2254 2255 2256 2257
    delete thd->lex->sphead;
    thd->lex->sphead= NULL;
  }
}
unknown's avatar
VIEW  
unknown committed
2258

2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
/*
  Initialize (or reset) Query_tables_list object.

  SYNOPSIS
    reset_query_tables_list()
      init  TRUE  - we should perform full initialization of object with
                    allocating needed memory
            FALSE - object is already initialized so we should only reset
                    its state so it can be used for parsing/processing
                    of new statement

  DESCRIPTION
    This method initializes Query_tables_list so it can be used as part
    of LEX object for parsing/processing of statement. One can also use
    this method to reset state of already initialized Query_tables_list
    so it can be used for processing of new statement.
*/

void Query_tables_list::reset_query_tables_list(bool init)
{
unknown's avatar
unknown committed
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
  if (!init && query_tables)
  {
    TABLE_LIST *table= query_tables;
    for (;;)
    {
      delete table->view;
      if (query_tables_last == &table->next_global ||
          !(table= table->next_global))
        break;
    }
  }
2290 2291 2292 2293
  query_tables= 0;
  query_tables_last= &query_tables;
  query_tables_own_last= 0;
  if (init)
2294 2295 2296 2297 2298 2299 2300
  {
    /*
      We delay real initialization of hash (and therefore related
      memory allocation) until first insertion into this hash.
    */
    hash_clear(&sroutines);
  }
2301
  else if (sroutines.records)
2302 2303
  {
    /* Non-zero sroutines.records means that hash was initialized. */
2304
    my_hash_reset(&sroutines);
2305
  }
2306 2307 2308
  sroutines_list.empty();
  sroutines_list_own_last= sroutines_list.next;
  sroutines_list_own_elements= 0;
2309
  binlog_stmt_flags= 0;
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
}


/*
  Destroy Query_tables_list object with freeing all resources used by it.

  SYNOPSIS
    destroy_query_tables_list()
*/

void Query_tables_list::destroy_query_tables_list()
{
  hash_free(&sroutines);
}


2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
/*
  Initialize LEX object.

  SYNOPSIS
    st_lex::st_lex()

  NOTE
    LEX object initialized with this constructor can be used as part of
    THD object for which one can safely call open_tables(), lock_tables()
    and close_thread_tables() functions. But it is not yet ready for
    statement parsing. On should use lex_start() function to prepare LEX
    for this.
*/

st_lex::st_lex()
2341
  :result(0),
2342
   sql_command(SQLCOM_END), option_type(OPT_DEFAULT), is_lex_started(0)
2343
{
unknown's avatar
unknown committed
2344

unknown's avatar
unknown committed
2345 2346 2347 2348
  my_init_dynamic_array2(&plugins, sizeof(plugin_ref),
                         plugins_static_buffer,
                         INITIAL_LEX_PLUGIN_LIST_SIZE, 
                         INITIAL_LEX_PLUGIN_LIST_SIZE);
2349
  reset_query_tables_list(TRUE);
2350 2351 2352
}


unknown's avatar
VIEW  
unknown committed
2353
/*
2354
  Check whether the merging algorithm can be used on this VIEW
unknown's avatar
VIEW  
unknown committed
2355 2356 2357 2358

  SYNOPSIS
    st_lex::can_be_merged()

2359
  DESCRIPTION
2360 2361 2362
    We can apply merge algorithm if it is single SELECT view  with
    subqueries only in WHERE clause (we do not count SELECTs of underlying
    views, and second level subqueries) and we have not grpouping, ordering,
2363 2364 2365
    HAVING clause, aggregate functions, DISTINCT clause, LIMIT clause and
    several underlying tables.

unknown's avatar
VIEW  
unknown committed
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
  RETURN
    FALSE - only temporary table algorithm can be used
    TRUE  - merge algorithm can be used
*/

bool st_lex::can_be_merged()
{
  // TODO: do not forget implement case when select_lex.table_list.elements==0

  /* find non VIEW subqueries/unions */
2376 2377 2378
  bool selects_allow_merge= select_lex.next_select() == 0;
  if (selects_allow_merge)
  {
2379 2380 2381
    for (SELECT_LEX_UNIT *tmp_unit= select_lex.first_inner_unit();
         tmp_unit;
         tmp_unit= tmp_unit->next_unit())
2382
    {
2383 2384 2385 2386
      if (tmp_unit->first_select()->parent_lex == this &&
          (tmp_unit->item == 0 ||
           (tmp_unit->item->place() != IN_WHERE &&
            tmp_unit->item->place() != IN_ON)))
2387 2388 2389 2390 2391 2392 2393 2394
      {
        selects_allow_merge= 0;
        break;
      }
    }
  }

  return (selects_allow_merge &&
unknown's avatar
VIEW  
unknown committed
2395 2396
	  select_lex.group_list.elements == 0 &&
	  select_lex.having == 0 &&
2397
          select_lex.with_sum_func == 0 &&
2398
	  select_lex.table_list.elements >= 1 &&
unknown's avatar
VIEW  
unknown committed
2399
	  !(select_lex.options & SELECT_DISTINCT) &&
2400
          select_lex.select_limit == 0);
unknown's avatar
VIEW  
unknown committed
2401 2402
}

2403

unknown's avatar
VIEW  
unknown committed
2404
/*
2405
  check if command can use VIEW with MERGE algorithm (for top VIEWs)
unknown's avatar
VIEW  
unknown committed
2406 2407 2408 2409

  SYNOPSIS
    st_lex::can_use_merged()

2410 2411 2412 2413 2414
  DESCRIPTION
    Only listed here commands can use merge algorithm in top level
    SELECT_LEX (for subqueries will be used merge algorithm if
    st_lex::can_not_use_merged() is not TRUE).

unknown's avatar
VIEW  
unknown committed
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433
  RETURN
    FALSE - command can't use merged VIEWs
    TRUE  - VIEWs with MERGE algorithms can be used
*/

bool st_lex::can_use_merged()
{
  switch (sql_command)
  {
  case SQLCOM_SELECT:
  case SQLCOM_CREATE_TABLE:
  case SQLCOM_UPDATE:
  case SQLCOM_UPDATE_MULTI:
  case SQLCOM_DELETE:
  case SQLCOM_DELETE_MULTI:
  case SQLCOM_INSERT:
  case SQLCOM_INSERT_SELECT:
  case SQLCOM_REPLACE:
  case SQLCOM_REPLACE_SELECT:
2434
  case SQLCOM_LOAD:
unknown's avatar
VIEW  
unknown committed
2435 2436 2437 2438 2439 2440
    return TRUE;
  default:
    return FALSE;
  }
}

2441
/*
2442
  Check if command can't use merged views in any part of command
2443 2444 2445 2446

  SYNOPSIS
    st_lex::can_not_use_merged()

2447 2448 2449 2450
  DESCRIPTION
    Temporary table algorithm will be used on all SELECT levels for queries
    listed here (see also st_lex::can_use_merged()).

2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
  RETURN
    FALSE - command can't use merged VIEWs
    TRUE  - VIEWs with MERGE algorithms can be used
*/

bool st_lex::can_not_use_merged()
{
  switch (sql_command)
  {
  case SQLCOM_CREATE_VIEW:
  case SQLCOM_SHOW_CREATE:
2462 2463 2464 2465 2466 2467
  /*
    SQLCOM_SHOW_FIELDS is necessary to make 
    information schema tables working correctly with views.
    see get_schema_tables_result function
  */
  case SQLCOM_SHOW_FIELDS:
2468 2469 2470 2471 2472 2473
    return TRUE;
  default:
    return FALSE;
  }
}

unknown's avatar
VIEW  
unknown committed
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483
/*
  Detect that we need only table structure of derived table/view

  SYNOPSIS
    only_view_structure()

  RETURN
    TRUE yes, we need only structure
    FALSE no, we need data
*/
unknown's avatar
unknown committed
2484

unknown's avatar
VIEW  
unknown committed
2485 2486
bool st_lex::only_view_structure()
{
2487
  switch (sql_command) {
unknown's avatar
VIEW  
unknown committed
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501
  case SQLCOM_SHOW_CREATE:
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_SHOW_FIELDS:
  case SQLCOM_REVOKE_ALL:
  case SQLCOM_REVOKE:
  case SQLCOM_GRANT:
  case SQLCOM_CREATE_VIEW:
    return TRUE;
  default:
    return FALSE;
  }
}


unknown's avatar
unknown committed
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
/*
  Should Items_ident be printed correctly

  SYNOPSIS
    need_correct_ident()

  RETURN
    TRUE yes, we need only structure
    FALSE no, we need data
*/


bool st_lex::need_correct_ident()
{
  switch(sql_command)
  {
  case SQLCOM_SHOW_CREATE:
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_CREATE_VIEW:
    return TRUE;
  default:
    return FALSE;
  }
}

2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543
/*
  Get effective type of CHECK OPTION for given view

  SYNOPSIS
    get_effective_with_check()
    view    given view

  NOTE
    It have not sense to set CHECK OPTION for SELECT satement or subqueries,
    so we do not.

  RETURN
    VIEW_CHECK_NONE      no need CHECK OPTION
    VIEW_CHECK_LOCAL     CHECK OPTION LOCAL
    VIEW_CHECK_CASCADED  CHECK OPTION CASCADED
*/

2544
uint8 st_lex::get_effective_with_check(TABLE_LIST *view)
2545 2546 2547 2548 2549 2550 2551
{
  if (view->select_lex->master_unit() == &unit &&
      which_check_option_applicable())
    return (uint8)view->with_check;
  return VIEW_CHECK_NONE;
}

unknown's avatar
unknown committed
2552

2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
/**
  This method should be called only during parsing.
  It is aware of compound statements (stored routine bodies)
  and will initialize the destination with the default
  database of the stored routine, rather than the default
  database of the connection it is parsed in.
  E.g. if one has no current database selected, or current database 
  set to 'bar' and then issues:

  CREATE PROCEDURE foo.p1() BEGIN SELECT * FROM t1 END//

  t1 is meant to refer to foo.t1, not to bar.t1.

  This method is needed to support this rule.

  @return TRUE in case of error (parsing should be aborted, FALSE in
  case of success
*/

bool
2573
st_lex::copy_db_to(char **p_db, size_t *p_db_length) const
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589
{
  if (sphead)
  {
    DBUG_ASSERT(sphead->m_db.str && sphead->m_db.length);
    /*
      It is safe to assign the string by-pointer, both sphead and
      its statements reside in the same memory root.
    */
    *p_db= sphead->m_db.str;
    if (p_db_length)
      *p_db_length= sphead->m_db.length;
    return FALSE;
  }
  return thd->copy_db_to(p_db, p_db_length);
}

unknown's avatar
unknown committed
2590 2591 2592 2593 2594 2595 2596
/*
  initialize limit counters

  SYNOPSIS
    st_select_lex_unit::set_limit()
    values	- SELECT_LEX with initial values for counters
*/
unknown's avatar
VIEW  
unknown committed
2597

unknown's avatar
unknown committed
2598
void st_select_lex_unit::set_limit(st_select_lex *sl)
2599
{
2600
  ha_rows select_limit_val;
2601
  ulonglong val;
2602

unknown's avatar
unknown committed
2603
  DBUG_ASSERT(! thd->stmt_arena->is_stmt_prepare());
2604 2605 2606
  val= sl->select_limit ? sl->select_limit->val_uint() : HA_POS_ERROR;
  select_limit_val= (ha_rows)val;
#ifndef BIG_TABLES
2607
  /*
2608 2609 2610 2611 2612 2613
    Check for overflow : ha_rows can be smaller then ulonglong if
    BIG_TABLES is off.
    */
  if (val != (ulonglong)select_limit_val)
    select_limit_val= HA_POS_ERROR;
#endif
2614 2615 2616 2617 2618 2619 2620
  val= sl->offset_limit ? sl->offset_limit->val_uint() : ULL(0);
  offset_limit_cnt= (ha_rows)val;
#ifndef BIG_TABLES
  /* Check for truncation. */
  if (val != (ulonglong)offset_limit_cnt)
    offset_limit_cnt= HA_POS_ERROR;
#endif
2621 2622
  select_limit_cnt= select_limit_val + offset_limit_cnt;
  if (select_limit_cnt < select_limit_val)
2623 2624 2625
    select_limit_cnt= HA_POS_ERROR;		// no limit
}

unknown's avatar
unknown committed
2626

2627
/**
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
  @brief Set the initial purpose of this TABLE_LIST object in the list of used
    tables.

  We need to track this information on table-by-table basis, since when this
  table becomes an element of the pre-locked list, it's impossible to identify
  which SQL sub-statement it has been originally used in.

  E.g.:

  User request:                 SELECT * FROM t1 WHERE f1();
  FUNCTION f1():                DELETE FROM t2; RETURN 1;
  BEFORE DELETE trigger on t2:  INSERT INTO t3 VALUES (old.a);

  For this user request, the pre-locked list will contain t1, t2, t3
  table elements, each needed for different DML.

  The trigger event map is updated to reflect INSERT, UPDATE, DELETE,
  REPLACE, LOAD DATA, CREATE TABLE .. SELECT, CREATE TABLE ..
  REPLACE SELECT statements, and additionally ON DUPLICATE KEY UPDATE
  clause.
2648 2649 2650 2651
*/

void st_lex::set_trg_event_type_for_tables()
{
2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
  uint8 new_trg_event_map= 0;

  /*
    Some auxiliary operations
    (e.g. GRANT processing) create TABLE_LIST instances outside
    the parser. Additionally, some commands (e.g. OPTIMIZE) change
    the lock type for a table only after parsing is done. Luckily,
    these do not fire triggers and do not need to pre-load them.
    For these TABLE_LISTs set_trg_event_type is never called, and
    trg_event_map is always empty. That means that the pre-locking
    algorithm will ignore triggers defined on these tables, if
    any, and the execution will either fail with an assert in
    sql_trigger.cc or with an error that a used table was not
    pre-locked, in case of a production build.

    TODO: this usage pattern creates unnecessary module dependencies
    and should be rewritten to go through the parser.
    Table list instances created outside the parser in most cases
    refer to mysql.* system tables. It is not allowed to have
    a trigger on a system table, but keeping track of
    initialization provides extra safety in case this limitation
    is circumvented.
  */

  switch (sql_command) {
  case SQLCOM_LOCK_TABLES:
  /*
    On a LOCK TABLE, all triggers must be pre-loaded for this TABLE_LIST
    when opening an associated TABLE.
  */
    new_trg_event_map= static_cast<uint8>
                        (1 << static_cast<int>(TRG_EVENT_INSERT)) |
                      static_cast<uint8>
                        (1 << static_cast<int>(TRG_EVENT_UPDATE)) |
                      static_cast<uint8>
                        (1 << static_cast<int>(TRG_EVENT_DELETE));
    break;
  /*
    Basic INSERT. If there is an additional ON DUPLIATE KEY UPDATE
    clause, it will be handled later in this method.
  */
  case SQLCOM_INSERT:                           /* fall through */
  case SQLCOM_INSERT_SELECT:
  /*
    LOAD DATA ... INFILE is expected to fire BEFORE/AFTER INSERT
    triggers.
    If the statement also has REPLACE clause, it will be
    handled later in this method.
  */
  case SQLCOM_LOAD:                             /* fall through */
  /*
    REPLACE is semantically equivalent to INSERT. In case
    of a primary or unique key conflict, it deletes the old
    record and inserts a new one. So we also may need to
    fire ON DELETE triggers. This functionality is handled
    later in this method.
  */
  case SQLCOM_REPLACE:                          /* fall through */
  case SQLCOM_REPLACE_SELECT:
  /*
    CREATE TABLE ... SELECT defaults to INSERT if the table or
    view already exists. REPLACE option of CREATE TABLE ...
    REPLACE SELECT is handled later in this method.
  */
  case SQLCOM_CREATE_TABLE:
    new_trg_event_map|= static_cast<uint8>
                          (1 << static_cast<int>(TRG_EVENT_INSERT));
    break;
  /* Basic update and multi-update */
  case SQLCOM_UPDATE:                           /* fall through */
  case SQLCOM_UPDATE_MULTI:
    new_trg_event_map|= static_cast<uint8>
                          (1 << static_cast<int>(TRG_EVENT_UPDATE));
    break;
  /* Basic delete and multi-delete */
  case SQLCOM_DELETE:                           /* fall through */
  case SQLCOM_DELETE_MULTI:
    new_trg_event_map|= static_cast<uint8>
                          (1 << static_cast<int>(TRG_EVENT_DELETE));
    break;
  default:
    break;
  }

  switch (duplicates) {
  case DUP_UPDATE:
    new_trg_event_map|= static_cast<uint8>
                          (1 << static_cast<int>(TRG_EVENT_UPDATE));
    break;
  case DUP_REPLACE:
    new_trg_event_map|= static_cast<uint8>
                          (1 << static_cast<int>(TRG_EVENT_DELETE));
    break;
  case DUP_ERROR:
  default:
    break;
  }


2751 2752 2753 2754 2755 2756 2757 2758
  /*
    Do not iterate over sub-selects, only the tables in the outermost
    SELECT_LEX can be modified, if any.
  */
  TABLE_LIST *tables= select_lex.get_table_list();

  while (tables)
  {
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769
    /*
      This is a fast check to filter out statements that do
      not change data, or tables  on the right side, in case of
      INSERT .. SELECT, CREATE TABLE .. SELECT and so on.
      Here we also filter out OPTIMIZE statement and non-updateable
      views, for which lock_type is TL_UNLOCK or TL_READ after
      parsing.
    */
    if (static_cast<int>(tables->lock_type) >=
        static_cast<int>(TL_WRITE_ALLOW_WRITE))
      tables->trg_event_map= new_trg_event_map;
2770 2771 2772 2773 2774
    tables= tables->next_local;
  }
}


2775
/*
2776 2777
  Unlink the first table from the global table list and the first table from
  outer select (lex->select_lex) local list
2778 2779 2780

  SYNOPSIS
    unlink_first_table()
2781
    link_to_local	Set to 1 if caller should link this table to local list
unknown's avatar
unknown committed
2782

unknown's avatar
VIEW  
unknown committed
2783
  NOTES
2784 2785
    We assume that first tables in both lists is the same table or the local
    list is empty.
2786 2787

  RETURN
2788
    0	If 'query_tables' == 0
unknown's avatar
VIEW  
unknown committed
2789
    unlinked table
2790
      In this case link_to_local is set.
unknown's avatar
unknown committed
2791

2792
*/
unknown's avatar
VIEW  
unknown committed
2793
TABLE_LIST *st_lex::unlink_first_table(bool *link_to_local)
2794
{
unknown's avatar
VIEW  
unknown committed
2795 2796 2797 2798 2799 2800 2801 2802
  TABLE_LIST *first;
  if ((first= query_tables))
  {
    /*
      Exclude from global table list
    */
    if ((query_tables= query_tables->next_global))
      query_tables->prev_global= &query_tables;
2803 2804
    else
      query_tables_last= &query_tables;
unknown's avatar
VIEW  
unknown committed
2805 2806 2807 2808 2809 2810 2811
    first->next_global= 0;

    /*
      and from local list if it is not empty
    */
    if ((*link_to_local= test(select_lex.table_list.first)))
    {
2812 2813
      select_lex.context.table_list= 
        select_lex.context.first_name_resolution_table= first->next_local;
2814
      select_lex.table_list.first= first->next_local;
unknown's avatar
VIEW  
unknown committed
2815 2816 2817
      select_lex.table_list.elements--;	//safety
      first->next_local= 0;
      /*
2818 2819
        Ensure that the global list has the same first table as the local
        list.
unknown's avatar
VIEW  
unknown committed
2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
      */
      first_lists_tables_same();
    }
  }
  return first;
}


/*
  Bring first local table of first most outer select to first place in global
  table list

  SYNOPSYS
     st_lex::first_lists_tables_same()

  NOTES
2836 2837 2838 2839 2840 2841
    In many cases (for example, usual INSERT/DELETE/...) the first table of
    main SELECT_LEX have special meaning => check that it is the first table
    in global list and re-link to be first in the global list if it is
    necessary.  We need such re-linking only for queries with sub-queries in
    the select list, as only in this case tables of sub-queries will go to
    the global list first.
unknown's avatar
VIEW  
unknown committed
2842 2843 2844 2845
*/

void st_lex::first_lists_tables_same()
{
2846
  TABLE_LIST *first_table= select_lex.table_list.first;
unknown's avatar
VIEW  
unknown committed
2847 2848
  if (query_tables != first_table && first_table != 0)
  {
2849
    TABLE_LIST *next;
unknown's avatar
VIEW  
unknown committed
2850 2851
    if (query_tables_last == &first_table->next_global)
      query_tables_last= first_table->prev_global;
2852

2853
    if ((next= *first_table->prev_global= first_table->next_global))
unknown's avatar
VIEW  
unknown committed
2854 2855 2856 2857
      next->prev_global= first_table->prev_global;
    /* include in new place */
    first_table->next_global= query_tables;
    /*
2858 2859 2860
       We are sure that query_tables is not 0, because first_table was not
       first table in the global list => we can use
       query_tables->prev_global without check of query_tables
unknown's avatar
VIEW  
unknown committed
2861 2862 2863 2864 2865
    */
    query_tables->prev_global= &first_table->next_global;
    first_table->prev_global= &query_tables;
    query_tables= first_table;
  }
2866 2867
}

unknown's avatar
unknown committed
2868

2869
/*
unknown's avatar
unknown committed
2870
  Link table back that was unlinked with unlink_first_table()
2871 2872 2873

  SYNOPSIS
    link_first_table_back()
unknown's avatar
VIEW  
unknown committed
2874
    link_to_local	do we need link this table to local
2875 2876 2877 2878

  RETURN
    global list
*/
unknown's avatar
VIEW  
unknown committed
2879 2880 2881

void st_lex::link_first_table_back(TABLE_LIST *first,
				   bool link_to_local)
2882
{
unknown's avatar
VIEW  
unknown committed
2883
  if (first)
2884
  {
unknown's avatar
VIEW  
unknown committed
2885 2886
    if ((first->next_global= query_tables))
      query_tables->prev_global= &first->next_global;
2887 2888
    else
      query_tables_last= &first->next_global;
unknown's avatar
VIEW  
unknown committed
2889 2890 2891 2892
    query_tables= first;

    if (link_to_local)
    {
2893
      first->next_local= select_lex.table_list.first;
unknown's avatar
unknown committed
2894
      select_lex.context.table_list= first;
2895
      select_lex.table_list.first= first;
unknown's avatar
VIEW  
unknown committed
2896 2897 2898 2899 2900 2901
      select_lex.table_list.elements++;	//safety
    }
  }
}


2902 2903 2904 2905 2906 2907

/*
  cleanup lex for case when we open table by table for processing

  SYNOPSIS
    st_lex::cleanup_after_one_table_open()
2908 2909 2910 2911 2912

  NOTE
    This method is mostly responsible for cleaning up of selects lists and
    derived tables state. To rollback changes in Query_tables_list one has
    to call Query_tables_list::reset_query_tables_list(FALSE).
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
*/

void st_lex::cleanup_after_one_table_open()
{
  /*
    thd->lex->derived_tables & additional units may be set if we open
    a view. It is necessary to clear thd->lex->derived_tables flag
    to prevent processing of derived tables during next open_and_lock_tables
    if next table is a real table and cleanup & remove underlying units
    NOTE: all units will be connected to thd->lex->select_lex, because we
    have not UNION on most upper level.
    */
  if (all_selects_list != &select_lex)
  {
    derived_tables= 0;
    /* cleunup underlying units (units of VIEW) */
    for (SELECT_LEX_UNIT *un= select_lex.first_inner_unit();
         un;
         un= un->next_unit())
      un->cleanup();
    /* reduce all selects list to default state */
    all_selects_list= &select_lex;
    /* remove underlying units (units of VIEW) subtree */
    select_lex.cut_subtree();
  }
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972
}


/*
  Save current state of Query_tables_list for this LEX, and prepare it
  for processing of new statemnt.

  SYNOPSIS
    reset_n_backup_query_tables_list()
      backup  Pointer to Query_tables_list instance to be used for backup
*/

void st_lex::reset_n_backup_query_tables_list(Query_tables_list *backup)
{
  backup->set_query_tables_list(this);
  /*
    We have to perform full initialization here since otherwise we
    will damage backed up state.
  */
  this->reset_query_tables_list(TRUE);
}


/*
  Restore state of Query_tables_list for this LEX from backup.

  SYNOPSIS
    restore_backup_query_tables_list()
      backup  Pointer to Query_tables_list instance used for backup
*/

void st_lex::restore_backup_query_tables_list(Query_tables_list *backup)
{
  this->destroy_query_tables_list();
  this->set_query_tables_list(backup);
2973 2974 2975
}


unknown's avatar
unknown committed
2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997
/*
  Checks for usage of routines and/or tables in a parsed statement

  SYNOPSIS
    st_lex:table_or_sp_used()

  RETURN
    FALSE  No routines and tables used
    TRUE   Either or both routines and tables are used.
*/

bool st_lex::table_or_sp_used()
{
  DBUG_ENTER("table_or_sp_used");

  if (sroutines.records || query_tables)
    DBUG_RETURN(TRUE);

  DBUG_RETURN(FALSE);
}


2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018
/*
  Do end-of-prepare fixup for list of tables and their merge-VIEWed tables

  SYNOPSIS
    fix_prepare_info_in_table_list()
      thd  Thread handle
      tbl  List of tables to process

  DESCRIPTION
    Perform end-end-of prepare fixup for list of tables, if any of the tables
    is a merge-algorithm VIEW, recursively fix up its underlying tables as
    well.

*/

static void fix_prepare_info_in_table_list(THD *thd, TABLE_LIST *tbl)
{
  for (; tbl; tbl= tbl->next_local)
  {
    if (tbl->on_expr)
    {
unknown's avatar
unknown committed
3019
      thd->check_and_register_item_tree(&tbl->prep_on_expr, &tbl->on_expr);
3020 3021
      tbl->on_expr= tbl->on_expr->copy_andor_structure(thd);
    }
3022 3023 3024 3025 3026
    if (tbl->is_view_or_derived() && tbl->is_merged_derived())
    {
      SELECT_LEX *sel= tbl->get_single_select();
      fix_prepare_info_in_table_list(thd, sel->get_table_list());
    }
3027 3028 3029 3030
  }
}


unknown's avatar
VIEW  
unknown committed
3031
/*
3032
  Save WHERE/HAVING/ON clauses and replace them with disposable copies
unknown's avatar
VIEW  
unknown committed
3033 3034 3035

  SYNOPSIS
    st_select_lex::fix_prepare_information
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046
      thd          thread handler
      conds        in/out pointer to WHERE condition to be met at execution
      having_conds in/out pointer to HAVING condition to be met at execution
  
  DESCRIPTION
    The passed WHERE and HAVING are to be saved for the future executions.
    This function saves it, and returns a copy which can be thrashed during
    this execution of the statement. By saving/thrashing here we mean only
    AND/OR trees.
    The function also calls fix_prepare_info_in_table_list that saves all
    ON expressions.    
unknown's avatar
VIEW  
unknown committed
3047 3048
*/

3049 3050
void st_select_lex::fix_prepare_information(THD *thd, Item **conds, 
                                            Item **having_conds)
unknown's avatar
VIEW  
unknown committed
3051
{
unknown's avatar
unknown committed
3052
  if (!thd->stmt_arena->is_conventional() && first_execution)
unknown's avatar
VIEW  
unknown committed
3053 3054
  {
    first_execution= 0;
3055 3056
    if (*conds)
    {
unknown's avatar
unknown committed
3057
      thd->check_and_register_item_tree(&prep_where, conds);
3058 3059
      *conds= where= prep_where->copy_andor_structure(thd);
    }
3060 3061
    if (*having_conds)
    {
unknown's avatar
unknown committed
3062
      thd->check_and_register_item_tree(&prep_having, having_conds);
3063 3064
      *having_conds= having= prep_having->copy_andor_structure(thd);
    }
3065
    fix_prepare_info_in_table_list(thd, table_list.first);
3066 3067 3068
  }
}

unknown's avatar
unknown committed
3069

unknown's avatar
unknown committed
3070
/*
unknown's avatar
VIEW  
unknown committed
3071
  There are st_select_lex::add_table_to_list &
unknown's avatar
unknown committed
3072
  st_select_lex::set_lock_for_tables are in sql_parse.cc
unknown's avatar
unknown committed
3073

unknown's avatar
VIEW  
unknown committed
3074
  st_select_lex::print is in sql_select.cc
unknown's avatar
unknown committed
3075 3076

  st_select_lex_unit::prepare, st_select_lex_unit::exec,
3077 3078
  st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
  st_select_lex_unit::change_result
unknown's avatar
unknown committed
3079
  are in sql_union.cc
unknown's avatar
unknown committed
3080
*/
3081

3082 3083 3084 3085 3086
/*
  Sets the kind of hints to be added by the calls to add_index_hint().

  SYNOPSIS
    set_index_hint_type()
3087 3088
      type_arg     The kind of hints to be added from now on.
      clause       The clause to use for hints to be added from now on.
3089 3090 3091 3092 3093 3094 3095 3096

  DESCRIPTION
    Used in filling up the tagged hints list.
    This list is filled by first setting the kind of the hint as a 
    context variable and then adding hints of the current kind.
    Then the context variable index_hint_type can be reset to the
    next hint type.
*/
3097
void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
3098 3099
                                        index_clause_map clause)
{ 
3100
  current_index_hint_type= type_arg;
3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
  current_index_hint_clause= clause;
}


/*
  Makes an array to store index usage hints (ADD/FORCE/IGNORE INDEX).

  SYNOPSIS
    alloc_index_hints()
      thd         current thread.
*/

void st_select_lex::alloc_index_hints (THD *thd)
{ 
unknown's avatar
unknown committed
3115
  index_hints= new (thd->mem_root) List<Index_hint>(); 
3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135
}



/*
  adds an element to the array storing index usage hints 
  (ADD/FORCE/IGNORE INDEX).

  SYNOPSIS
    add_index_hint()
      thd         current thread.
      str         name of the index.
      length      number of characters in str.

  RETURN VALUE
    0 on success, non-zero otherwise
*/
bool st_select_lex::add_index_hint (THD *thd, char *str, uint length)
{
  return index_hints->push_front (new (thd->mem_root) 
unknown's avatar
unknown committed
3136
                                 Index_hint(current_index_hint_type,
3137 3138 3139
                                            current_index_hint_clause,
                                            str, length));
}
3140

3141 3142 3143 3144 3145 3146

bool st_select_lex::optimize_unflattened_subqueries()
{
  for (SELECT_LEX_UNIT *un= first_inner_unit(); un; un= un->next_unit())
  {
    Item_subselect *subquery_predicate= un->item;
Sergey Petrunya's avatar
Sergey Petrunya committed
3147
    
3148 3149
    if (subquery_predicate)
    {
Sergey Petrunya's avatar
Sergey Petrunya committed
3150 3151 3152 3153 3154 3155 3156
      if (subquery_predicate->substype() == Item_subselect::IN_SUBS)
      {
        Item_in_subselect *in_subs=(Item_in_subselect*)subquery_predicate;
        if (in_subs->is_jtbm_merged)
          continue;
      }

3157 3158 3159
      for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
      {
        JOIN *inner_join= sl->join;
3160 3161
        if (!inner_join)
          continue;
3162
        SELECT_LEX *save_select= un->thd->lex->current_select;
3163
        ulonglong save_options;
3164
        int res;
3165
        /* We need only 1 row to determine existence */
3166 3167
        un->set_limit(un->global_parameters);
        un->thd->lex->current_select= sl;
3168
        save_options= inner_join->select_options;
3169
        if (options & SELECT_DESCRIBE)
3170 3171
        {
          /* Optimize the subquery in the context of EXPLAIN. */
unknown's avatar
unknown committed
3172 3173 3174
          sl->set_explain_type();
          sl->options|= SELECT_DESCRIBE;
          inner_join->select_options|= SELECT_DESCRIBE;
3175
        }
3176
        res= inner_join->optimize();
3177
        inner_join->select_options= save_options;
3178 3179 3180 3181 3182 3183 3184
        un->thd->lex->current_select= save_select;
        if (res)
          return TRUE;
      }
    }
  }
  return FALSE;
3185 3186 3187
}


3188

3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
/**
  @brief Process all derived tables/views of the SELECT.

  @param lex    LEX of this thread
  @param phase  phases to run derived tables/views through

  @details
  This function runs specified 'phases' on all tables from the
  table_list of this select.

  @return FALSE ok.
  @return TRUE an error occur.
*/

bool st_select_lex::handle_derived(struct st_lex *lex, uint phases)
{
  for (TABLE_LIST *cursor= (TABLE_LIST*) table_list.first;
       cursor;
       cursor= cursor->next_local)
  {
    if (cursor->is_view_or_derived() && cursor->handle_derived(lex, phases))
      return TRUE;
  }
  return FALSE;
}


/**
  @brief
  Returns first unoccupied table map and table number

  @param map     [out] return found map
  @param tablenr [out] return found tablenr

  @details
  Returns first unoccupied table map and table number in this select.
  Map and table are returned in *'map' and *'tablenr' accordingly.

  @retrun TRUE  no free table map/table number
  @return FALSE found free table map/table number
*/

bool st_select_lex::get_free_table_map(table_map *map, uint *tablenr)
{
  *map= 0;
  *tablenr= 0;
  TABLE_LIST *tl;
  if (!join)
  {
    (*map)= 1<<1;
    (*tablenr)++;
    return FALSE;
  }
  List_iterator<TABLE_LIST> ti(leaf_tables);
  while ((tl= ti++))
  {
    if (tl->table->map > *map)
      *map= tl->table->map;
    if (tl->table->tablenr > *tablenr)
      *tablenr= tl->table->tablenr;
  }
  (*map)<<= 1;
  (*tablenr)++;
  if (*tablenr >= MAX_TABLES)
    return TRUE;
  return FALSE;
}


/**
  @brief
  Append given table to the leaf_tables list.

  @param link  Offset to which list in table structure to use
  @param table Table to append

  @details
  Append given 'table' to the leaf_tables list using the 'link' offset.
  If the 'table' is linked with other tables through next_leaf/next_local
  chains then whole list will be appended.
*/

void st_select_lex::append_table_to_list(TABLE_LIST *TABLE_LIST::*link,
                                         TABLE_LIST *table)
{
  TABLE_LIST *tl;
Igor Babaev's avatar
Igor Babaev committed
3275
  for (tl= leaf_tables.head(); tl->*link; tl= tl->*link) ;
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415
  tl->*link= table;
}

/*
  @brief
  Remove given table from the leaf_tables list.

  @param link  Offset to which list in table structure to use
  @param table Table to remove

  @details
  Remove 'table' from the leaf_tables list using the 'link' offset.
*/

void st_select_lex::remove_table_from_list(TABLE_LIST *table)
{
  TABLE_LIST *tl;
  List_iterator<TABLE_LIST> ti(leaf_tables);
  while ((tl= ti++))
  {
    if (tl == table)
    {
      ti.remove();
      break;
    }
  }
}


/**
  @brief
  Assigns new table maps to tables in the leaf_tables list

  @param derived    Derived table to take initial table map from
  @param map        table map to begin with
  @param tablenr    table number to begin with
  @param parent_lex new parent select_lex

  @details
  Assign new table maps/table numbers to all tables in the leaf_tables list.
  'map'/'tablenr' are used for the first table and shifted to left/
  increased for each consequent table in the leaf_tables list.
  If the 'derived' table is given then it's table map/number is used for the
  first table in the list and 'map'/'tablenr' are used for the second and
  all consequent tables.
  The 'parent_lex' is set as the new parent select_lex for all tables in the
  list.
*/

void st_select_lex::remap_tables(TABLE_LIST *derived, table_map map,
                                 uint tablenr, SELECT_LEX *parent_lex)
{
  bool first_table= TRUE;
  TABLE_LIST *tl;
  table_map first_map;
  uint first_tablenr;

  if (derived && derived->table)
  {
    first_map= derived->table->map;
    first_tablenr= derived->table->tablenr;
  }
  else
  {
    first_map= map;
    map<<= 1;
    first_tablenr= tablenr++;
  }
  /*
    Assign table bit/table number.
    To the first table of the subselect the table bit/tablenr of the
    derived table is assigned. The rest of tables are getting bits
    sequentially, starting from the provided table map/tablenr.
  */
  List_iterator<TABLE_LIST> ti(leaf_tables);
  while ((tl= ti++))
  {
    if (first_table)
    {
      first_table= FALSE;
      tl->table->set_table_map(first_map, first_tablenr);
    }
    else
    {
      tl->table->set_table_map(map, tablenr);
      tablenr++;
      map<<= 1;
    }
    SELECT_LEX *old_sl= tl->select_lex;
    tl->select_lex= parent_lex;
    for(TABLE_LIST *emb= tl->embedding;
        emb && emb->select_lex == old_sl;
        emb= emb->embedding)
      emb->select_lex= parent_lex;
  }
}

/**
  @brief
  Merge a subquery into this select.

  @param derived     derived table of the subquery to be merged
  @param subq_select select_lex of the subquery
  @param map         table map for assigning to merged tables from subquery
  @param table_no    table number for assigning to merged tables from subquery

  @details
  This function merges a subquery into its parent select. In short the
  merge operation appends the subquery FROM table list to the parent's
  FROM table list. In more details:
    .) the top_join_list of the subquery is wrapped into a join_nest
       and attached to 'derived'
    .) subquery's leaf_tables list  is merged with the leaf_tables
       list of this select_lex
    .) the table maps and table numbers of the tables merged from
       the subquery are adjusted to reflect their new binding to
       this select

  @return TRUE  an error occur
  @return FALSE ok
*/

bool SELECT_LEX::merge_subquery(TABLE_LIST *derived, SELECT_LEX *subq_select,
                                uint table_no, table_map map)
{
  derived->wrap_into_nested_join(subq_select->top_join_list);
  /* Reconnect the next_leaf chain. */
  leaf_tables.concat(&subq_select->leaf_tables);

  ftfunc_list->concat(subq_select->ftfunc_list);
  if (join)
  {
    Item_in_subselect **in_subq;
    Item_in_subselect **in_subq_end;
    for (in_subq= subq_select->join->sj_subselects.front(), 
         in_subq_end= subq_select->join->sj_subselects.back(); 
         in_subq != in_subq_end; 
         in_subq++)
    {
      join->sj_subselects.append(join->thd->mem_root, *in_subq);
3416 3417 3418
      DBUG_ASSERT((*in_subq)->emb_on_expr_nest != NULL);
      if ((*in_subq)->emb_on_expr_nest == NO_JOIN_NEST)
        (*in_subq)->emb_on_expr_nest= derived;
3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431
    }
  }
  /*
    Remove merged table from chain.
    When merge_subquery is called at a subquery-to-semijoin transformation
    the derived isn't in the leaf_tables list, so in this case the call of
    remove_table_from_list does not cause any actions.
  */
  remove_table_from_list(derived);

  /* Walk through child's tables and adjust table map, tablenr,
   * parent_lex */
  subq_select->remap_tables(derived, map, table_no, this);
Igor Babaev's avatar
Igor Babaev committed
3432
  subq_select->merged_into= this;
3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474
  return FALSE;
}


/**
  @brief
  Mark tables from the leaf_tables list as belong to a derived table.

  @param derived   tables will be marked as belonging to this derived

  @details
  Run through the leaf_list and mark all tables as belonging to the 'derived'.
*/

void SELECT_LEX::mark_as_belong_to_derived(TABLE_LIST *derived)
{
  /* Mark tables as belonging to this DT */
  TABLE_LIST *tl;
  List_iterator<TABLE_LIST> ti(leaf_tables);
  while ((tl= ti++))
  {
    tl->skip_temporary= 1;
    tl->belong_to_derived= derived;
  }
}


/**
  @brief
  Update used_tables cache for this select

  @details
  This function updates used_tables cache of ON expressions of all tables
  in the leaf_tables list and of the conds expression (if any).
*/

void SELECT_LEX::update_used_tables()
{
  TABLE_LIST *tl;
  List_iterator<TABLE_LIST> ti(leaf_tables);
  while ((tl= ti++))
  {
Igor Babaev's avatar
Igor Babaev committed
3475 3476 3477 3478 3479 3480
    for (embedding= tl;
         !tl->table->maybe_null && embedding;
         embedding= embedding->embedding)
    {
      tl->table->maybe_null= embedding->outer_join;
    }
3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496
    if (tl->on_expr)
    {
      tl->on_expr->update_used_tables();
      tl->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
    }
    TABLE_LIST *embedding= tl->embedding;
    while (embedding)
    {
      if (embedding->on_expr && 
          embedding->nested_join->join_list.head() == tl)
      {
        embedding->on_expr->update_used_tables();
        embedding->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
      }
      tl= embedding;
      embedding= tl->embedding;
3497
    }
3498 3499 3500 3501 3502 3503 3504 3505
  }
  if (join->conds)
  {
    join->conds->update_used_tables();
    join->conds->walk(&Item::eval_not_null_tables, 0, NULL);
  }
}

3506

3507 3508 3509 3510 3511 3512
/**
  Set the EXPLAIN type for this subquery.
*/

void st_select_lex::set_explain_type()
{
3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532
  bool is_primary= FALSE;
  if (next_select())
    is_primary= TRUE;

  if (!is_primary && first_inner_unit())
  {
    /*
      If there is at least one materialized derived|view then it's a PRIMARY select.
      Otherwise, all derived tables/views were merged and this select is a SIMPLE one.
    */
    for (SELECT_LEX_UNIT *un= first_inner_unit(); un; un= un->next_unit())
    {
      if ((!un->derived || un->derived->is_materialized_derived()))
      {
        is_primary= TRUE;
        break;
      }
    }
  }

3533 3534 3535 3536 3537
  SELECT_LEX *first= master_unit()->first_select();
  /* drop UNCACHEABLE_EXPLAIN, because it is for internal usage only */
  uint8 is_uncacheable= (uncacheable & ~UNCACHEABLE_EXPLAIN);

  type= ((&master_unit()->thd->lex->select_lex == this) ?
3538
         (is_primary ? "PRIMARY" : "SIMPLE"):    
3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551
         ((this == first) ?
          ((linkage == DERIVED_TABLE_TYPE) ?
           "DERIVED" :
           ((is_uncacheable & UNCACHEABLE_DEPENDENT) ?
            "DEPENDENT SUBQUERY" :
            (is_uncacheable ? "UNCACHEABLE SUBQUERY" :
             "SUBQUERY"))) :
          ((is_uncacheable & UNCACHEABLE_DEPENDENT) ?
           "DEPENDENT UNION":
           is_uncacheable ? "UNCACHEABLE UNION":
           "UNION")));
  options|= SELECT_DESCRIBE;
}
3552 3553


3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564
/**
  @brief
  Increase estimated number of records for a derived table/view

  @param records  number of records to increase estimate by

  @details
  This function increases estimated number of records by the 'records'
  for the derived table to which this select belongs to.
*/

Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
3565
void SELECT_LEX::increase_derived_records(ha_rows records)
3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
{
  SELECT_LEX_UNIT *unit= master_unit();
  DBUG_ASSERT(unit->derived);

  select_union *result= (select_union*)unit->result;
  result->records+= records;
}


/**
  @brief
  Mark select's derived table as a const one.

  @param empty Whether select has an empty result set

  @details
  Mark derived table/view of this select as a constant one (to
  materialize it at the optimization phase) unless this select belongs to a
  union. Estimated number of rows is incremented if this select has non empty
  result set.
*/

void SELECT_LEX::mark_const_derived(bool empty)
{
  TABLE_LIST *derived= master_unit()->derived;
  if (!join->thd->lex->describe && derived)
  {
    if (!empty)
      increase_derived_records(1);
    if (!master_unit()->is_union() && !derived->is_merged_derived())
      derived->fill_me= TRUE;
  }
}

bool st_select_lex::save_leaf_tables(THD *thd)
{
  Query_arena *arena= thd->stmt_arena, backup;
  if (arena->is_conventional())
    arena= 0;                                  
  else
    thd->set_n_backup_active_arena(arena, &backup);

  List_iterator_fast<TABLE_LIST> li(leaf_tables);
  TABLE_LIST *table;
  while ((table= li++))
  {
    if (leaf_tables_exec.push_back(table))
      return 1;
    table->tablenr_exec= table->table->tablenr;
    table->map_exec= table->table->map;
  }
  if (arena)
    thd->restore_active_arena(arena, &backup);

  return 0;
}

3623

3624 3625 3626 3627 3628
/**
  A routine used by the parser to decide whether we are specifying a full
  partitioning or if only partitions to add or to split.

  @note  This needs to be outside of WITH_PARTITION_STORAGE_ENGINE since it
unknown's avatar
unknown committed
3629
  is used from the sql parser that doesn't have any ifdef's
3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640

  @retval  TRUE    Yes, it is part of a management partition command
  @retval  FALSE          No, not a management partition command
*/

bool st_lex::is_partition_management() const
{
  return (sql_command == SQLCOM_ALTER_TABLE &&
          (alter_info.flags == ALTER_ADD_PARTITION ||
           alter_info.flags == ALTER_REORGANIZE_PARTITION));
}