sql_lex.cc 90.2 KB
Newer Older
1
/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2

bk@work.mysql.com's avatar
bk@work.mysql.com 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
5
   the Free Software Foundation; version 2 of the License.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
11

bk@work.mysql.com's avatar
bk@work.mysql.com 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
20 21 22 23 24
#include "sql_priv.h"
#include "unireg.h"                    // REQUIRED: for other includes
#include "sql_class.h"                          // sql_lex.h: SQLCOM_END
#include "sql_lex.h"
#include "sql_parse.h"                          // add_to_list
bk@work.mysql.com's avatar
bk@work.mysql.com committed
25 26 27
#include "item_create.h"
#include <m_ctype.h>
#include <hash.h>
28 29
#include "sp.h"
#include "sp_head.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
30

31 32
static int lex_one_token(void *arg, void *yythd);

33 34 35 36
/*
  We are using pointer to this variable for distinguishing between assignment
  to NEW row field (when parsing trigger definition) and structured variable.
*/
37 38

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

40 41 42 43
/**
  LEX_STRING constant for null-string to be used in parser and other places.
*/
const LEX_STRING null_lex_str= {NULL, 0};
44
const LEX_STRING empty_lex_str= {(char *) "", 0};
45 46 47 48 49 50 51 52 53 54
/**
  @note The order of the elements of this array must correspond to
  the order of elements in enum_binlog_stmt_unsafe.
*/
const int
Query_tables_list::binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT] =
{
  ER_BINLOG_UNSAFE_LIMIT,
  ER_BINLOG_UNSAFE_INSERT_DELAYED,
  ER_BINLOG_UNSAFE_SYSTEM_TABLE,
55
  ER_BINLOG_UNSAFE_AUTOINC_COLUMNS,
56 57
  ER_BINLOG_UNSAFE_UDF,
  ER_BINLOG_UNSAFE_SYSTEM_VARIABLE,
58
  ER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
59
  ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS,
60 61
  ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
  ER_BINLOG_UNSAFE_MIXED_STATEMENT,
62 63
};

64

65
/* Longest standard keyword name */
66

bk@work.mysql.com's avatar
bk@work.mysql.com committed
67 68
#define TOCK_NAME_LENGTH 24

69 70
/*
  The following data is based on the latin1 character set, and is only
bk@work.mysql.com's avatar
bk@work.mysql.com committed
71 72 73
  used when comparing keywords
*/

monty@mysql.com's avatar
monty@mysql.com committed
74 75
static uchar to_upper_lex[]=
{
bk@work.mysql.com's avatar
bk@work.mysql.com committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    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
};

94 95 96 97 98 99 100 101 102 103 104
/* 
  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"
};
105

bk@work.mysql.com's avatar
bk@work.mysql.com committed
106 107 108 109 110 111 112
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;
}

serg@serg.mylan's avatar
serg@serg.mylan committed
113
#include <lex_hash.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135


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;
}


136 137 138 139 140 141 142 143 144
void
st_parsing_options::reset()
{
  allows_variable= TRUE;
  allows_select_into= TRUE;
  allows_select_procedure= TRUE;
  allows_derived= TRUE;
}

145 146 147 148 149

/**
  Perform initialization of Lex_input_stream instance.

  Basically, a buffer for pre-processed query. This buffer should be large
150 151
  enough to keep multi-statement query. The allocation is done once in
  Lex_input_stream::init() in order to prevent memory pollution when
152 153 154
  the server is processing large multi-statement queries.
*/

155
bool Lex_input_stream::init(THD *thd,
's avatar
committed
156
			    char* buff,
157
			    unsigned int length)
158
{
159 160 161
  DBUG_EXECUTE_IF("bug42064_simulate_oom",
                  DBUG_SET("+d,simulate_out_of_memory"););

162
  m_cpp_buf= (char*) thd->alloc(length + 1);
163 164 165 166 167

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

  if (m_cpp_buf == NULL)
168
    return TRUE;
169 170

  m_thd= thd;
171
  reset(buff, length);
172 173

  return FALSE;
174 175 176 177 178 179 180 181 182 183 184 185
}


/**
  Prepare Lex_input_stream instance state for use for handling next SQL statement.

  It should be called between two statements in a multi-statement query.
  The operation resets the input stream to the beginning-of-parse state,
  but does not reallocate m_cpp_buf.
*/

void
's avatar
committed
186
Lex_input_stream::reset(char *buffer, unsigned int length)
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
{
  yylineno= 1;
  yytoklen= 0;
  yylval= NULL;
  lookahead_token= -1;
  lookahead_yylval= NULL;
  m_ptr= buffer;
  m_tok_start= NULL;
  m_tok_end= NULL;
  m_end_of_query= buffer + length;
  m_tok_start_prev= NULL;
  m_buf= buffer;
  m_buf_length= length;
  m_echo= TRUE;
  m_cpp_tok_start= NULL;
  m_cpp_tok_start_prev= NULL;
  m_cpp_tok_end= NULL;
  m_body_utf8= NULL;
  m_cpp_utf8_processed_ptr= NULL;
  next_state= MY_LEX_START;
  found_semicolon= NULL;
  ignore_space= test(m_thd->variables.sql_mode & MODE_IGNORE_SPACE);
  stmt_prepare_mode= FALSE;
  multi_statements= TRUE;
  in_comment=NO_COMMENT;
  m_underscore_cs= NULL;
213
  m_cpp_ptr= m_cpp_buf;
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 245
/**
  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;
}

/**
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
246
  @brief The operation appends unprocessed part of pre-processed buffer till
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
  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;

anozdrin/alik@ibm's avatar
anozdrin/alik@ibm committed
322
  if (!my_charset_same(txt_cs, &my_charset_utf8_general_ci))
323 324 325
  {
    thd->convert_string(&utf_txt,
                        &my_charset_utf8_general_ci,
326
                        txt->str, (uint) txt->length,
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
                        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;
}

344

345 346 347 348 349 350
/*
  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)
*/

351
void lex_start(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
352
{
353
  LEX *lex= thd->lex;
354 355 356 357
  DBUG_ENTER("lex_start");

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

358
  lex->context_stack.empty();
359 360
  lex->unit.init_query();
  lex->unit.init_select();
361 362
  /* 'parent_lex' is used in init_query() so it must be before it. */
  lex->select_lex.parent_lex= lex;
363 364
  lex->select_lex.init_query();
  lex->value_list.empty();
365
  lex->update_list.empty();
366
  lex->set_var_list.empty();
367
  lex->param_list.empty();
monty@mysql.com's avatar
monty@mysql.com committed
368
  lex->view_list.empty();
369
  lex->prepared_stmt_params.empty();
370
  lex->auxiliary_table_list.empty();
371 372 373 374 375 376 377 378 379 380
  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;
381
  lex->select_lex.sql_cache= SELECT_LEX::SQL_CACHE_UNSPECIFIED;
monty@mysql.com's avatar
monty@mysql.com committed
382 383
  lex->select_lex.init_order();
  lex->select_lex.group_list.empty();
384
  lex->describe= 0;
monty@mysql.com's avatar
monty@mysql.com committed
385
  lex->subqueries= FALSE;
monty@mysql.com's avatar
monty@mysql.com committed
386
  lex->view_prepare_mode= FALSE;
monty@mysql.com's avatar
monty@mysql.com committed
387
  lex->derived_tables= 0;
388
  lex->safe_to_cache_query= 1;
389
  lex->leaf_tables_insert= 0;
390
  lex->parsing_options.reset();
monty@mysql.com's avatar
monty@mysql.com committed
391
  lex->empty_field_list_on_rset= 0;
392
  lex->select_lex.select_number= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
393
  lex->length=0;
394
  lex->part_info= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
395
  lex->select_lex.in_sum_expr=0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
396
  lex->select_lex.ftfunc_list_alloc.empty();
397
  lex->select_lex.ftfunc_list= &lex->select_lex.ftfunc_list_alloc;
398 399
  lex->select_lex.group_list.empty();
  lex->select_lex.order_list.empty();
400
  lex->duplicates= DUP_ERROR;
401
  lex->ignore= 0;
402
  lex->spname= NULL;
403 404
  lex->sphead= NULL;
  lex->spcont= NULL;
405
  lex->m_stmt= NULL;
406
  lex->proc_list.first= 0;
407
  lex->escape_used= FALSE;
antony@ppcg5.local's avatar
antony@ppcg5.local committed
408
  lex->query_tables= 0;
409
  lex->reset_query_tables_list(FALSE);
410
  lex->expr_allows_subselect= TRUE;
411
  lex->use_only_table_context= FALSE;
412

413 414
  lex->name.str= 0;
  lex->name.length= 0;
415
  lex->event_parse_data= NULL;
416
  lex->profile_options= PROFILE_NONE;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
417 418 419
  lex->nest_level=0 ;
  lex->allow_sum_func= 0;
  lex->in_sum_func= NULL;
patg@radha.tangent.org's avatar
patg@radha.tangent.org committed
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
  /*
    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;
435

436
  lex->is_lex_started= TRUE;
437
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
438 439 440 441
}

void lex_end(LEX *lex)
{
monty@mysql.com's avatar
monty@mysql.com committed
442
  DBUG_ENTER("lex_end");
443
  DBUG_PRINT("enter", ("lex: 0x%lx", (long) lex));
antony@ppcg5.local's avatar
antony@ppcg5.local committed
444 445

  /* release used plugins */
446 447 448 449 450
  if (lex->plugins.elements) /* No function call and no mutex if no plugins. */
  {
    plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer, 
                       lex->plugins.elements);
  }
antony@ppcg5.local's avatar
antony@ppcg5.local committed
451 452
  reset_dynamic(&lex->plugins);

453 454 455
  delete lex->sphead;
  lex->sphead= NULL;

monty@mysql.com's avatar
monty@mysql.com committed
456
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
457 458
}

459 460 461 462
Yacc_state::~Yacc_state()
{
  if (yacc_yyss)
  {
463 464
    my_free(yacc_yyss);
    my_free(yacc_yyvs);
465
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
466 467
}

468
static int find_keyword(Lex_input_stream *lip, uint len, bool function)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
469
{
470
  const char *tok= lip->get_tok_start();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
471

472
  SYMBOL *symbol= get_hash_symbol(tok, len, function);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
473 474
  if (symbol)
  {
475 476 477 478
    lip->yylval->symbol.symbol=symbol;
    lip->yylval->symbol.str= (char*) tok;
    lip->yylval->symbol.length=len;

479
    if ((symbol->tok == NOT_SYM) &&
480
        (lip->m_thd->variables.sql_mode & MODE_HIGH_NOT_PRECEDENCE))
481 482
      return NOT2_SYM;
    if ((symbol->tok == OR_OR_SYM) &&
483
	!(lip->m_thd->variables.sql_mode & MODE_PIPES_AS_CONCAT))
484
      return OR2_SYM;
485

bk@work.mysql.com's avatar
bk@work.mysql.com committed
486 487 488 489 490
    return symbol->tok;
  }
  return 0;
}

491 492 493 494 495
/*
  Check if name is a keyword

  SYNOPSIS
    is_keyword()
496
    name      checked name (must not be empty)
497 498 499 500 501 502 503 504 505
    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)
{
506
  DBUG_ASSERT(len != 0);
507 508
  return get_hash_symbol(name,len,0)!=0;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
509

510 511 512 513 514
/**
  Check if name is a sql function

    @param name      checked name

515
    @return is this a native function or not
516 517 518 519
    @retval 0         name is a function
    @retval 1         name isn't a function
*/

520 521 522
bool is_lex_native_function(const LEX_STRING *name)
{
  DBUG_ASSERT(name != NULL);
523
  return (get_hash_symbol(name->str, (uint) name->length, 1) != 0);
524 525
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
526 527
/* make a copy of token before ptr and set yytoklen */

528
static LEX_STRING get_token(Lex_input_stream *lip, uint skip, uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
529 530
{
  LEX_STRING tmp;
531
  lip->yyUnget();                       // ptr points now after last token char
532
  tmp.length=lip->yytoklen=length;
533
  tmp.str= lip->m_thd->strmake(lip->get_tok_start() + skip, tmp.length);
534 535 536 537

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
538 539 540
  return tmp;
}

541 542 543 544 545 546 547
/* 
 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)
*/

548
static LEX_STRING get_quoted_token(Lex_input_stream *lip,
549
                                   uint skip,
550
                                   uint length, char quote)
551 552
{
  LEX_STRING tmp;
553 554
  const char *from, *end;
  char *to;
555
  lip->yyUnget();                       // ptr points now after last token char
556 557
  tmp.length= lip->yytoklen=length;
  tmp.str=(char*) lip->m_thd->alloc(tmp.length+1);
558
  from= lip->get_tok_start() + skip;
559
  to= tmp.str;
560
  end= to+length;
561 562 563 564

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

565
  for ( ; to != end; )
566
  {
567
    if ((*to++= *from++) == quote)
568
    {
569
      from++;					// Skip double quotes
570 571
      lip->m_cpp_text_start++;
    }
572 573 574 575 576 577 578 579 580 581
  }
  *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
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
582

583
static char *get_text(Lex_input_stream *lip, int pre_skip, int post_skip)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
584 585 586
{
  reg1 uchar c,sep;
  uint found_escape=0;
587
  CHARSET_INFO *cs= lip->m_thd->charset();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
588

589
  lip->tok_bitmap= 0;
590 591
  sep= lip->yyGetLast();                        // String should end with this
  while (! lip->eof())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
592
  {
593
    c= lip->yyGet();
594
    lip->tok_bitmap|= c;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
595
#ifdef USE_MB
596 597 598
    {
      int l;
      if (use_mb(cs) &&
599 600 601 602 603
          (l = my_ismbchar(cs,
                           lip->get_ptr() -1,
                           lip->get_end_of_query()))) {
        lip->skip_binary(l-1);
        continue;
604
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
605 606
    }
#endif
607
    if (c == '\\' &&
608
        !(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
609 610
    {					// Escaped character
      found_escape=1;
611
      if (lip->eof())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
612
	return 0;
613
      lip->yySkip();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
614 615 616
    }
    else if (c == sep)
    {
617
      if (c == lip->yyGet())            // Check if two separators in a row
bk@work.mysql.com's avatar
bk@work.mysql.com committed
618
      {
619
        found_escape=1;                 // duplicate. Remember for delete
bk@work.mysql.com's avatar
bk@work.mysql.com committed
620 621 622
	continue;
      }
      else
623
        lip->yyUnget();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
624 625

      /* Found end. Unescape and return string */
626 627
      const char *str, *end;
      char *start;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
628

629 630 631 632 633 634 635
      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);

636
      if (!(start= (char*) lip->m_thd->alloc((uint) (end-str)+1)))
637
	return (char*) "";		// Sql_alloc has set error flag
638 639 640 641

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
642 643
      if (!found_escape)
      {
644 645 646
	lip->yytoklen=(uint) (end-str);
	memcpy(start,str,lip->yytoklen);
	start[lip->yytoklen]=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
647 648 649
      }
      else
      {
650
        char *to;
651

bk@work.mysql.com's avatar
bk@work.mysql.com committed
652 653 654 655
	for (to=start ; str != end ; str++)
	{
#ifdef USE_MB
	  int l;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
656
	  if (use_mb(cs) &&
657
              (l = my_ismbchar(cs, str, end))) {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
658 659 660 661 662 663
	      while (l--)
		  *to++ = *str++;
	      str--;
	      continue;
	  }
#endif
664
	  if (!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
665
              *str == '\\' && str+1 != end)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
	  {
	    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:
691
              *to++= *str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
692 693 694
	      break;
	    }
	  }
695 696
	  else if (*str == sep)
	    *to++= *str++;		// Two ' or "
bk@work.mysql.com's avatar
bk@work.mysql.com committed
697 698 699 700
	  else
	    *to++ = *str;
	}
	*to=0;
701
	lip->yytoklen=(uint) (to-start);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
702
      }
703
      return start;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
    }
  }
  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;
725 726
static const char *unsigned_longlong_str="18446744073709551615";
static const uint unsigned_longlong_len=20;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
727

monty@mysql.com's avatar
monty@mysql.com committed
728
static inline uint int_token(const char *str,uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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
{
  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)
763
      return DECIMAL_NUM;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
764 765 766 767
    else
    {
      cmp=signed_longlong_str+1;
      smaller=LONG_NUM;				// If <= signed_longlong_str
768
      bigger=DECIMAL_NUM;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
769 770 771 772 773 774 775 776 777 778 779 780 781
    }
  }
  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)
782 783
    {
      if (length > unsigned_longlong_len)
784
        return DECIMAL_NUM;
785 786
      cmp=unsigned_longlong_str;
      smaller=ULONGLONG_NUM;
787
      bigger=DECIMAL_NUM;
788
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
789 790 791 792
    else
    {
      cmp=longlong_str;
      smaller=LONG_NUM;
793
      bigger= ULONGLONG_NUM;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
794 795 796 797 798 799
    }
  }
  while (*cmp && *cmp++ == *str++) ;
  return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
}

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846

/**
  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;
}


847
/*
848
  MYSQLlex remember the following states from the following MYSQLlex()
849 850 851 852 853

  - 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)
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
854

855
int MYSQLlex(void *arg, void *yythd)
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
{
  THD *thd= (THD *)yythd;
  Lex_input_stream *lip= & thd->m_parser_state->m_lip;
  YYSTYPE *yylval=(YYSTYPE*) arg;
  int token;

  if (lip->lookahead_token >= 0)
  {
    /*
      The next token was already parsed in advance,
      return it.
    */
    token= lip->lookahead_token;
    lip->lookahead_token= -1;
    *yylval= *(lip->lookahead_yylval);
    lip->lookahead_yylval= NULL;
    return token;
  }

  token= lex_one_token(arg, yythd);

  switch(token) {
  case WITH:
    /*
      Parsing 'WITH' 'ROLLUP' or 'WITH' 'CUBE' requires 2 look ups,
      which makes the grammar LALR(2).
      Replace by a single 'WITH_ROLLUP' or 'WITH_CUBE' token,
      to transform the grammar into a LALR(1) grammar,
      which sql_yacc.yy can process.
    */
    token= lex_one_token(arg, yythd);
    switch(token) {
    case CUBE_SYM:
      return WITH_CUBE_SYM;
    case ROLLUP_SYM:
      return WITH_ROLLUP_SYM;
    default:
      /*
        Save the token following 'WITH'
      */
      lip->lookahead_yylval= lip->yylval;
      lip->yylval= NULL;
      lip->lookahead_token= token;
      return WITH;
    }
    break;
  default:
    break;
  }

  return token;
}

int lex_one_token(void *arg, void *yythd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
910
{
Staale Smedseng's avatar
Staale Smedseng committed
911
  reg1	uchar c= 0;
912
  bool comment_closed;
913
  int	tokval, result_state;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
914
  uint length;
915
  enum my_lex_states state;
916
  THD *thd= (THD *)yythd;
917
  Lex_input_stream *lip= & thd->m_parser_state->m_lip;
918
  LEX *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
919
  YYSTYPE *yylval=(YYSTYPE*) arg;
920
  CHARSET_INFO *cs= thd->charset();
921 922
  uchar *state_map= cs->state_map;
  uchar *ident_map= cs->ident_map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
923

924
  lip->yylval=yylval;			// The global state
925

926
  lip->start_token();
927 928
  state=lip->next_state;
  lip->next_state=MY_LEX_OPERATOR_OR_IDENT;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
929 930
  for (;;)
  {
931
    switch (state) {
932 933
    case MY_LEX_OPERATOR_OR_IDENT:	// Next is operator or keyword
    case MY_LEX_START:			// Start of token
934 935
      // Skip starting whitespace
      while(state_map[c= lip->yyPeek()] == MY_LEX_SKIP)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
936 937
      {
	if (c == '\n')
938
	  lip->yylineno++;
939 940

        lip->yySkip();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
941
      }
942 943 944 945

      /* Start of real token */
      lip->restart_token();
      c= lip->yyGet();
946
      state= (enum my_lex_states) state_map[c];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
947
      break;
948
    case MY_LEX_ESCAPE:
949
      if (lip->yyGet() == 'N')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
950 951 952 953 954
      {					// Allow \N as shortcut for NULL
	yylval->lex_str.str=(char*) "\\N";
	yylval->lex_str.length=2;
	return NULL_SYM;
      }
955 956
    case MY_LEX_CHAR:			// Unknown or single char token
    case MY_LEX_SKIP:			// This should not happen
957 958 959
      if (c == '-' && lip->yyPeek() == '-' &&
          (my_isspace(cs,lip->yyPeekn(1)) ||
           my_iscntrl(cs,lip->yyPeekn(1))))
960 961 962 963
      {
        state=MY_LEX_COMMENT;
        break;
      }
964

bk@work.mysql.com's avatar
bk@work.mysql.com committed
965
      if (c != ')')
966
	lip->next_state= MY_LEX_START;	// Allow signed numbers
967

bk@work.mysql.com's avatar
bk@work.mysql.com committed
968
      if (c == ',')
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
      {
        /*
          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();
      }
      else
      {
        /*
          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.
        */
        if (c == '?' && lip->stmt_prepare_mode && !ident_map[lip->yyPeek()])
990
        return(PARAM_MARKER);
991 992
      }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
993 994
      return((int) c);

bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
995
    case MY_LEX_IDENT_OR_NCHAR:
996 997
      if (lip->yyPeek() != '\'')
      {
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
998 999 1000
	state= MY_LEX_IDENT;
	break;
      }
1001
      /* Found N'string' */
1002 1003
      lip->yySkip();                         // Skip '
      if (!(yylval->lex_str.str = get_text(lip, 2, 1)))
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1004
      {
1005 1006
	state= MY_LEX_CHAR;             // Read char by char
	break;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1007
      }
1008
      yylval->lex_str.length= lip->yytoklen;
1009
      lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
1010
      return(NCHAR_STRING);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1011

1012
    case MY_LEX_IDENT_OR_HEX:
1013
      if (lip->yyPeek() == '\'')
1014
      {					// Found x'hex-number'
1015
	state= MY_LEX_HEX_NUMBER;
1016 1017
	break;
      }
ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
1018
    case MY_LEX_IDENT_OR_BIN:
1019
      if (lip->yyPeek() == '\'')
ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
1020 1021 1022 1023
      {                                 // Found b'bin-number'
        state= MY_LEX_BIN_NUMBER;
        break;
      }
1024
    case MY_LEX_IDENT:
1025
      const char *start;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1026
#if defined(USE_MB) && defined(USE_MB_IDENT)
1027
      if (use_mb(cs))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1028
      {
1029
	result_state= IDENT_QUOTED;
1030
        if (my_mbcharlen(cs, lip->yyGetLast()) > 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1031
        {
1032 1033 1034
          int l = my_ismbchar(cs,
                              lip->get_ptr() -1,
                              lip->get_end_of_query());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1035
          if (l == 0) {
1036
            state = MY_LEX_CHAR;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1037 1038
            continue;
          }
1039
          lip->skip_binary(l - 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1040
        }
1041
        while (ident_map[c=lip->yyGet()])
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1042
        {
1043
          if (my_mbcharlen(cs, c) > 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1044 1045
          {
            int l;
1046 1047 1048
            if ((l = my_ismbchar(cs,
                                 lip->get_ptr() -1,
                                 lip->get_end_of_query())) == 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1049
              break;
1050
            lip->skip_binary(l-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1051 1052 1053 1054 1055
          }
        }
      }
      else
#endif
1056
      {
Staale Smedseng's avatar
Staale Smedseng committed
1057
        for (result_state= c; ident_map[c= lip->yyGet()]; result_state|= c) ;
1058 1059
        /* If there were non-ASCII characters, mark that we must convert */
        result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1060
      }
1061 1062
      length= lip->yyLength();
      start= lip->get_ptr();
1063
      if (lip->ignore_space)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1064
      {
1065 1066 1067 1068
        /*
          If we find a space then this can't be an identifier. We notice this
          below by checking start != lex->ptr.
        */
Staale Smedseng's avatar
Staale Smedseng committed
1069
        for (; state_map[c] == MY_LEX_SKIP ; c= lip->yyGet()) ;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1070
      }
1071
      if (start == lip->get_ptr() && c == '.' && ident_map[lip->yyPeek()])
1072
	lip->next_state=MY_LEX_IDENT_SEP;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1073 1074
      else
      {					// '(' must follow directly if function
1075 1076
        lip->yyUnget();
	if ((tokval = find_keyword(lip, length, c == '(')))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1077
	{
1078
	  lip->next_state= MY_LEX_START;	// Allow signed numbers
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1079 1080
	  return(tokval);		// Was keyword
	}
1081
        lip->yySkip();                  // next state does a unget
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1082
      }
1083
      yylval->lex_str=get_token(lip, 0, length);
1084

1085
      /*
1086 1087
         Note: "SELECT _bla AS 'alias'"
         _bla should be considered as a IDENT if charset haven't been found.
1088
         So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
1089 1090 1091
         producing an error.
      */

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
      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);

1112
      return(result_state);			// IDENT or IDENT_QUOTED
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1113

1114
    case MY_LEX_IDENT_SEP:		// Found ident and now '.'
1115 1116 1117
      yylval->lex_str.str= (char*) lip->get_ptr();
      yylval->lex_str.length= 1;
      c= lip->yyGet();                  // should be '.'
1118
      lip->next_state= MY_LEX_IDENT_START;// Next is an ident (not a keyword)
1119
      if (!ident_map[lip->yyPeek()])            // Probably ` or "
1120
	lip->next_state= MY_LEX_START;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1121 1122
      return((int) c);

1123
    case MY_LEX_NUMBER_IDENT:		// number or ident which num-start
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
      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')
        {
Staale Smedseng's avatar
Staale Smedseng committed
1142
          while ((c= lip->yyGet()) == '0' || c == '1') ;
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
          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()))) ;
1157
      if (!ident_map[c])
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1158
      {					// Can't be identifier
1159
	state=MY_LEX_INT_OR_REAL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1160 1161 1162 1163
	break;
      }
      if (c == 'e' || c == 'E')
      {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1164
	// The following test is written this way to allow numbers of type 1e1
1165 1166
        if (my_isdigit(cs,lip->yyPeek()) ||
            (c=(lip->yyGet())) == '+' || c == '-')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1167
	{				// Allow 1E+10
1168
          if (my_isdigit(cs,lip->yyPeek()))     // Number must have digit after sign
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1169
	  {
1170 1171 1172
            lip->yySkip();
            while (my_isdigit(cs,lip->yyGet())) ;
            yylval->lex_str=get_token(lip, 0, lip->yyLength());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1173 1174 1175
	    return(FLOAT_NUM);
	  }
	}
1176
        lip->yyUnget();
ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
1177
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1178
      // fall through
1179
    case MY_LEX_IDENT_START:			// We come here after '.'
1180
      result_state= IDENT;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1181
#if defined(USE_MB) && defined(USE_MB_IDENT)
1182
      if (use_mb(cs))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1183
      {
1184
	result_state= IDENT_QUOTED;
1185
        while (ident_map[c=lip->yyGet()])
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1186
        {
1187
          if (my_mbcharlen(cs, c) > 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1188 1189
          {
            int l;
1190 1191 1192
            if ((l = my_ismbchar(cs,
                                 lip->get_ptr() -1,
                                 lip->get_end_of_query())) == 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1193
              break;
1194
            lip->skip_binary(l-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1195 1196 1197 1198 1199
          }
        }
      }
      else
#endif
1200
      {
Staale Smedseng's avatar
Staale Smedseng committed
1201
        for (result_state=0; ident_map[c= lip->yyGet()]; result_state|= c) ;
1202 1203 1204
        /* If there were non-ASCII characters, mark that we must convert */
        result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
      }
1205
      if (c == '.' && ident_map[lip->yyPeek()])
1206
	lip->next_state=MY_LEX_IDENT_SEP;// Next is '.'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1207

1208
      yylval->lex_str= get_token(lip, 0, lip->yyLength());
1209 1210 1211 1212 1213

      lip->body_utf8_append(lip->m_cpp_text_start);

      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
                                    lip->m_cpp_text_end);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1214

1215
      return(result_state);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1216

1217
    case MY_LEX_USER_VARIABLE_DELIMITER:	// Found quote char
1218
    {
1219 1220
      uint double_quotes= 0;
      char quote_char= c;                       // Used char
1221
      while ((c=lip->yyGet()))
1222
      {
1223 1224
	int var_length;
	if ((var_length= my_mbcharlen(cs, c)) == 1)
1225 1226 1227
	{
	  if (c == quote_char)
	  {
1228
            if (lip->yyPeek() != quote_char)
1229
	      break;
1230
            c=lip->yyGet();
1231 1232 1233
	    double_quotes++;
	    continue;
	  }
1234 1235
	}
#ifdef USE_MB
Davi Arnaut's avatar
Davi Arnaut committed
1236
        else if (use_mb(cs))
1237
        {
Davi Arnaut's avatar
Davi Arnaut committed
1238 1239 1240
          if ((var_length= my_ismbchar(cs, lip->get_ptr() - 1,
                                       lip->get_end_of_query())))
            lip->skip_binary(var_length-1);
1241
        }
1242
#endif
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1243
      }
1244
      if (double_quotes)
1245
	yylval->lex_str=get_quoted_token(lip, 1,
1246
                                         lip->yyLength() - double_quotes -1,
1247 1248
					 quote_char);
      else
1249
        yylval->lex_str=get_token(lip, 1, lip->yyLength() -1);
1250
      if (c == quote_char)
1251
        lip->yySkip();                  // Skip end `
1252
      lip->next_state= MY_LEX_START;
1253 1254 1255 1256 1257 1258

      lip->body_utf8_append(lip->m_cpp_text_start);

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

1259
      return(IDENT_QUOTED);
1260
    }
1261
    case MY_LEX_INT_OR_REAL:		// Complete int or incomplete real
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1262 1263
      if (c != '.')
      {					// Found complete integer number.
1264
        yylval->lex_str=get_token(lip, 0, lip->yyLength());
1265
	return int_token(yylval->lex_str.str, (uint) yylval->lex_str.length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1266 1267
      }
      // fall through
1268
    case MY_LEX_REAL:			// Incomplete real number
1269
      while (my_isdigit(cs,c = lip->yyGet())) ;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1270 1271 1272

      if (c == 'e' || c == 'E')
      {
1273
        c = lip->yyGet();
1274
	if (c == '-' || c == '+')
1275
          c = lip->yyGet();                     // Skip sign
1276
	if (!my_isdigit(cs,c))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1277
	{				// No digit after sign
1278
	  state= MY_LEX_CHAR;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1279 1280
	  break;
	}
1281 1282
        while (my_isdigit(cs,lip->yyGet())) ;
        yylval->lex_str=get_token(lip, 0, lip->yyLength());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1283 1284
	return(FLOAT_NUM);
      }
1285
      yylval->lex_str=get_token(lip, 0, lip->yyLength());
1286
      return(DECIMAL_NUM);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1287

1288
    case MY_LEX_HEX_NUMBER:		// Found x'hexstring'
1289 1290 1291 1292 1293 1294 1295 1296
      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
1297 1298 1299
      yylval->lex_str=get_token(lip,
                                2,          // skip x'
                                length-3);  // don't count x' and last '
1300 1301
      return (HEX_NUM);

ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
1302
    case MY_LEX_BIN_NUMBER:           // Found b'bin-string'
1303
      lip->yySkip();                  // Accept opening '
Staale Smedseng's avatar
Staale Smedseng committed
1304
      while ((c= lip->yyGet()) == '0' || c == '1') ;
ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
1305
      if (c != '\'')
1306 1307 1308
        return(ABORT_SYM);            // Illegal hex constant
      lip->yySkip();                  // Accept closing '
      length= lip->yyLength();        // Length of bin-num + 3
1309 1310 1311 1312
      yylval->lex_str= get_token(lip,
                                 2,         // skip b'
                                 length-3); // don't count b' and last '
      return (BIN_NUM);
ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
1313

1314
    case MY_LEX_CMP_OP:			// Incomplete comparison operator
1315 1316 1317 1318
      if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP ||
          state_map[lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
        lip->yySkip();
      if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1319
      {
1320
	lip->next_state= MY_LEX_START;	// Allow signed numbers
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1321 1322
	return(tokval);
      }
1323
      state = MY_LEX_CHAR;		// Something fishy found
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1324 1325
      break;

1326
    case MY_LEX_LONG_CMP_OP:		// Incomplete comparison operator
1327 1328
      if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP ||
          state_map[lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1329
      {
1330 1331 1332
        lip->yySkip();
        if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP)
          lip->yySkip();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1333
      }
1334
      if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1335
      {
1336
	lip->next_state= MY_LEX_START;	// Found long op
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1337 1338
	return(tokval);
      }
1339
      state = MY_LEX_CHAR;		// Something fishy found
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1340 1341
      break;

1342
    case MY_LEX_BOOL:
1343
      if (c != lip->yyPeek())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1344
      {
1345
	state=MY_LEX_CHAR;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1346 1347
	break;
      }
1348
      lip->yySkip();
1349 1350
      tokval = find_keyword(lip,2,0);	// Is a bool operator
      lip->next_state= MY_LEX_START;	// Allow signed numbers
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1351 1352
      return(tokval);

1353
    case MY_LEX_STRING_OR_DELIMITER:
1354
      if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
1355
      {
1356
	state= MY_LEX_USER_VARIABLE_DELIMITER;
1357 1358 1359
	break;
      }
      /* " used for strings */
1360
    case MY_LEX_STRING:			// Incomplete text string
1361
      if (!(yylval->lex_str.str = get_text(lip, 1, 1)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1362
      {
1363
	state= MY_LEX_CHAR;		// Read char by char
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1364 1365
	break;
      }
1366
      yylval->lex_str.length=lip->yytoklen;
1367 1368 1369 1370 1371 1372 1373 1374 1375

      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;

1376
      lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1377 1378
      return(TEXT_STRING);

1379
    case MY_LEX_COMMENT:			//  Comment
1380
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
1381 1382
      while ((c = lip->yyGet()) != '\n' && c) ;
      lip->yyUnget();                   // Safety against eof
1383
      state = MY_LEX_START;		// Try again
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1384
      break;
1385
    case MY_LEX_LONG_COMMENT:		/* Long C comment? */
1386
      if (lip->yyPeek() != '*')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1387
      {
1388
	state=MY_LEX_CHAR;		// Probable division
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1389 1390
	break;
      }
1391
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
1392 1393 1394
      /* Reject '/' '*', since we might need to turn off the echo */
      lip->yyUnget();

1395 1396
      lip->save_in_comment_state();

1397
      if (lip->yyPeekn(2) == '!')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1398
      {
1399 1400
        lip->in_comment= DISCARD_COMMENT;
        /* Accept '/' '*' '!', but do not keep this marker. */
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1401
        lip->set_echo(FALSE);
1402 1403 1404 1405 1406 1407 1408
        lip->yySkip();
        lip->yySkip();
        lip->yySkip();

        /*
          The special comment format is very strict:
          '/' '*' '!', followed by exactly
1409 1410 1411 1412
          1 digit (major), 2 digits (minor), then 2 digits (dot).
          32302 -> 3.23.02
          50032 -> 5.0.32
          50114 -> 5.1.14
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
        */
        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)
          {
1433 1434
            /* Accept 'M' 'm' 'm' 'd' 'd' */
            lip->yySkipn(5);
1435
            /* Expand the content of the special comment as real code */
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1436
            lip->set_echo(TRUE);
1437
            state=MY_LEX_START;
1438 1439 1440 1441
            break;  /* Do not treat contents as a comment.  */
          }
          else
          {
1442 1443 1444 1445 1446
            /*
              Patch and skip the conditional comment to avoid it
              being propagated infinitely (eg. to a slave).
            */
            char *pcom= lip->yyUnput(' ');
1447
            comment_closed= ! consume_comment(lip, 1);
1448 1449 1450 1451
            if (! comment_closed)
            {
              *pcom= '!';
            }
1452
            /* version allowed to have one level of comment inside. */
1453 1454 1455 1456
          }
        }
        else
        {
1457
          /* Not a version comment. */
1458
          state=MY_LEX_START;
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1459
          lip->set_echo(TRUE);
1460 1461
          break;
        }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1462
      }
1463
      else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1464
      {
1465 1466 1467
        lip->in_comment= PRESERVE_COMMENT;
        lip->yySkip();                  // Accept /
        lip->yySkip();                  // Accept *
1468 1469
        comment_closed= ! consume_comment(lip, 0);
        /* regular comments can have zero comments inside. */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1470
      }
1471 1472 1473 1474 1475
      /*
        Discard:
        - regular '/' '*' comments,
        - special comments '/' '*' '!' for a future version,
        by scanning until we find a closing '*' '/' marker.
1476 1477 1478 1479 1480 1481 1482 1483 1484

        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.
1485
      */
1486

1487 1488 1489
      /* Unbalanced comments with a missing '*' '/' are a syntax error */
      if (! comment_closed)
        return (ABORT_SYM);
1490
      state = MY_LEX_START;             // Try again
1491
      lip->restore_in_comment_state();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1492
      break;
1493
    case MY_LEX_END_LONG_COMMENT:
1494
      if ((lip->in_comment != NO_COMMENT) && lip->yyPeek() == '/')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1495
      {
1496 1497 1498 1499 1500 1501
        /* 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 */
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1502
        lip->set_echo(TRUE);
1503 1504
        lip->in_comment=NO_COMMENT;
        state=MY_LEX_START;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1505 1506
      }
      else
1507
	state=MY_LEX_CHAR;		// Return '*'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1508
      break;
1509
    case MY_LEX_SET_VAR:		// Check if ':='
1510
      if (lip->yyPeek() != '=')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1511
      {
1512
	state=MY_LEX_CHAR;		// Return ':'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1513 1514
	break;
      }
1515
      lip->yySkip();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1516
      return (SET_VAR);
1517
    case MY_LEX_SEMICOLON:			// optional line terminator
1518 1519
      state= MY_LEX_CHAR;               // Return ';'
      break;
1520
    case MY_LEX_EOL:
1521
      if (lip->eof())
1522
      {
1523
        lip->yyUnget();                 // Reject the last '\0'
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1524
        lip->set_echo(FALSE);
1525
        lip->yySkip();
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1526
        lip->set_echo(TRUE);
1527 1528 1529
        /* Unbalanced comments with a missing '*' '/' are a syntax error */
        if (lip->in_comment != NO_COMMENT)
          return (ABORT_SYM);
1530 1531
        lip->next_state=MY_LEX_END;     // Mark for next loop
        return(END_OF_INPUT);
1532 1533 1534
      }
      state=MY_LEX_CHAR;
      break;
1535
    case MY_LEX_END:
1536
      lip->next_state=MY_LEX_END;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1537
      return(0);			// We found end of input last time
1538

1539
      /* Actually real shouldn't start with . but allow them anyhow */
1540
    case MY_LEX_REAL_OR_POINT:
1541
      if (my_isdigit(cs,lip->yyPeek()))
1542
	state = MY_LEX_REAL;		// Real
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1543 1544
      else
      {
1545
	state= MY_LEX_IDENT_SEP;	// return '.'
1546
        lip->yyUnget();                 // Put back '.'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1547 1548
      }
      break;
1549
    case MY_LEX_USER_END:		// end '@' of user@hostname
1550
      switch (state_map[lip->yyPeek()]) {
1551 1552 1553
      case MY_LEX_STRING:
      case MY_LEX_USER_VARIABLE_DELIMITER:
      case MY_LEX_STRING_OR_DELIMITER:
1554
	break;
1555
      case MY_LEX_USER_END:
1556
	lip->next_state=MY_LEX_SYSTEM_VAR;
1557 1558
	break;
      default:
1559
	lip->next_state=MY_LEX_HOSTNAME;
1560 1561
	break;
      }
1562
      yylval->lex_str.str=(char*) lip->get_ptr();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1563 1564
      yylval->lex_str.length=1;
      return((int) '@');
1565
    case MY_LEX_HOSTNAME:		// end '@' of user@hostname
1566
      for (c=lip->yyGet() ;
1567
	   my_isalnum(cs,c) || c == '.' || c == '_' ||  c == '$';
1568 1569
           c= lip->yyGet()) ;
      yylval->lex_str=get_token(lip, 0, lip->yyLength());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1570
      return(LEX_HOSTNAME);
1571
    case MY_LEX_SYSTEM_VAR:
1572
      yylval->lex_str.str=(char*) lip->get_ptr();
1573
      yylval->lex_str.length=1;
1574 1575
      lip->yySkip();                                    // Skip '@'
      lip->next_state= (state_map[lip->yyPeek()] ==
1576 1577 1578
			MY_LEX_USER_VARIABLE_DELIMITER ?
			MY_LEX_OPERATOR_OR_IDENT :
			MY_LEX_IDENT_OR_KEYWORD);
1579
      return((int) '@');
1580
    case MY_LEX_IDENT_OR_KEYWORD:
1581 1582 1583 1584 1585
      /*
	We come here when we have found two '@' in a row.
	We should now be able to handle:
	[(global | local | session) .]variable_name
      */
1586

Staale Smedseng's avatar
Staale Smedseng committed
1587
      for (result_state= 0; ident_map[c= lip->yyGet()]; result_state|= c) ;
1588 1589
      /* If there were non-ASCII characters, mark that we must convert */
      result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1590

1591
      if (c == '.')
1592
	lip->next_state=MY_LEX_IDENT_SEP;
1593 1594
      length= lip->yyLength();
      if (length == 0)
1595
        return(ABORT_SYM);              // Names must be nonempty.
1596
      if ((tokval= find_keyword(lip, length,0)))
1597
      {
1598
        lip->yyUnget();                         // Put back 'c'
1599 1600
	return(tokval);				// Was keyword
      }
1601
      yylval->lex_str=get_token(lip, 0, length);
1602 1603 1604 1605 1606 1607

      lip->body_utf8_append(lip->m_cpp_text_start);

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

1608
      return(result_state);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1609 1610 1611
    }
  }
}
1612

1613

kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1614 1615 1616
/**
  Construct a copy of this object to be used for mysql_alter_table
  and mysql_create_table.
1617

kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1618 1619 1620 1621
  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.
1622

kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1623 1624
  @return You need to use check the error in THD for out
  of memory condition after calling this function.
1625 1626
*/

1627 1628 1629 1630 1631 1632 1633 1634 1635
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),
1636
  num_parts(rhs.num_parts),
igor@olga.mysql.com's avatar
igor@olga.mysql.com committed
1637 1638 1639
  change_level(rhs.change_level),
  datetime_field(rhs.datetime_field),
  error_if_not_empty(rhs.error_if_not_empty)
1640
{
1641 1642 1643
  /*
    Make deep copies of used objects.
    This is not a fully deep copy - clone() implementations
1644
    of Alter_drop, Alter_column, Key, foreign_key, Key_part_spec
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
    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 */
}


1658 1659 1660 1661 1662 1663 1664
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.
  */
1665

1666 1667 1668 1669 1670
  while ((str->length > 0) && (my_isspace(cs, str->str[0])))
  {
    str->length --;
    str->str ++;
  }
1671

1672 1673 1674 1675 1676 1677 1678 1679
  /*
    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 --;
  }
1680 1681
}

1682

1683 1684 1685 1686 1687 1688
/*
  st_select_lex structures initialisations
*/

void st_select_lex_node::init_query()
{
1689
  options= 0;
1690
  sql_cache= SQL_CACHE_UNSPECIFIED;
1691
  linkage= UNSPECIFIED_TYPE;
1692 1693
  no_error= no_table_names_allowed= 0;
  uncacheable= 0;
1694 1695 1696 1697 1698 1699 1700 1701 1702
}

void st_select_lex_node::init_select()
{
}

void st_select_lex_unit::init_query()
{
  st_select_lex_node::init_query();
1703
  linkage= GLOBAL_OPTIONS_TYPE;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1704
  global_parameters= first_select();
1705 1706
  select_limit_cnt= HA_POS_ERROR;
  offset_limit_cnt= 0;
1707
  union_distinct= 0;
1708
  prepared= optimized= executed= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1709
  item= 0;
1710 1711
  union_result= 0;
  table= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1712
  fake_select_lex= 0;
1713
  cleaned= 0;
1714
  item_list.empty();
1715
  describe= 0;
1716
  found_rows_for_union= 0;
1717 1718 1719 1720 1721
}

void st_select_lex::init_query()
{
  st_select_lex_node::init_query();
1722
  table_list.empty();
1723 1724
  top_join_list.empty();
  join_list= &top_join_list;
1725
  embedding= leaf_tables= 0;
1726
  item_list.empty();
1727
  join= 0;
1728
  having= prep_having= where= prep_where= 0;
1729
  olap= UNSPECIFIED_OLAP_TYPE;
1730
  having_fix_field= 0;
1731
  group_fix_field= 0;
1732 1733
  context.select_lex= this;
  context.init();
1734 1735 1736
  /*
    Add the name resolution context of the current (sub)query to the
    stack of contexts for the whole query.
1737 1738 1739 1740 1741
    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.
1742 1743
  */
  parent_lex->push_context(&context);
1744
  cond_count= between_count= with_wild= 0;
igor@olga.mysql.com's avatar
igor@olga.mysql.com committed
1745
  max_equal_elems= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1746
  ref_pointer_array= 0;
evgen@moonbone.local's avatar
evgen@moonbone.local committed
1747
  select_n_where_fields= 0;
bell@laptop.sanja.is.com.ua's avatar
bell@laptop.sanja.is.com.ua committed
1748
  select_n_having_items= 0;
1749
  subquery_in_having= explicit_limit= 0;
1750
  is_item_list_lookup= 0;
1751
  first_execution= 1;
1752
  first_natural_join_processing= 1;
1753
  first_cond_optimization= 1;
1754
  parsing_place= NO_MATTER;
1755
  exclude_from_table_unique_test= no_wrap_view_item= FALSE;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
1756
  nest_level= 0;
1757
  link_next= 0;
1758 1759 1760 1761 1762
}

void st_select_lex::init_select()
{
  st_select_lex_node::init_select();
1763
  group_list.empty();
1764
  type= db= 0;
1765 1766 1767
  having= 0;
  table_join_options= 0;
  in_sum_expr= with_wild= 0;
1768
  options= 0;
1769
  sql_cache= SQL_CACHE_UNSPECIFIED;
1770
  braces= 0;
1771
  interval_list.empty();
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1772
  ftfunc_list_alloc.empty();
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
1773
  inner_sum_func_list= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1774
  ftfunc_list= &ftfunc_list_alloc;
1775
  linkage= UNSPECIFIED_TYPE;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1776 1777
  order_list.elements= 0;
  order_list.first= 0;
1778
  order_list.next= &order_list.first;
1779 1780 1781
  /* 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 */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1782
  with_sum_func= 0;
1783
  is_correlated= 0;
1784 1785
  cur_pos_in_select_list= UNDEF_POS;
  non_agg_fields.empty();
1786
  cond_value= having_value= Item::COND_UNDEF;
1787
  inner_refs_list.empty();
1788
  full_group_by_flag= 0;
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
}

/*
  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;
1803
  slave= 0;
1804 1805
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1806 1807
/*
  include on level down (but do not link)
1808

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
  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;
}

1823 1824 1825 1826 1827 1828 1829 1830
/* 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;
1831
  slave= 0;
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
}

/* 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()
{
1846
  if (link_prev)
1847 1848 1849 1850
  {
    if ((*link_prev= link_next))
      link_next->link_prev= link_prev;
  }
1851 1852 1853 1854
  // Remove slave structure
  for (; slave; slave= slave->next)
    slave->fast_exclude();
  
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
}

/*
  excluding select_lex structure (except first (first select can't be
  deleted, because it is most upper select))
*/
void st_select_lex_node::exclude()
{
  //exclude from global list
  fast_exclude();
  //exclude from other structures
  if ((*prev= next))
    next->prev= prev;
  /* 
     We do not need following statements, because prev pointer of first 
     list element point to master->slave
     if (master->slave == this)
       master->slave= next;
  */
}
1875

1876 1877 1878 1879 1880 1881 1882 1883 1884 1885

/*
  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 
*/
1886 1887 1888
void st_select_lex_unit::exclude_level()
{
  SELECT_LEX_UNIT *units= 0, **units_last= &units;
1889
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
1890
  {
1891
    // unlink current level from global SELECTs list
1892 1893
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
      sl->link_next->link_prev= sl->link_prev;
1894 1895

    // bring up underlay levels
1896 1897
    SELECT_LEX_UNIT **last= 0;
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
1898 1899
    {
      u->master= master;
1900
      last= (SELECT_LEX_UNIT**)&(u->next);
1901
    }
1902 1903 1904 1905 1906 1907 1908 1909
    if (last)
    {
      (*units_last)= sl->first_inner_unit();
      units_last= last;
    }
  }
  if (units)
  {
1910
    // include brought up levels in place of current
1911 1912
    (*prev)= units;
    (*units_last)= (SELECT_LEX_UNIT*)next;
1913 1914 1915
    if (next)
      next->prev= (SELECT_LEX_NODE**)units_last;
    units->prev= prev;
1916 1917
  }
  else
1918 1919
  {
    // exclude currect unit from list of nodes
1920
    (*prev)= next;
1921 1922 1923
    if (next)
      next->prev= prev;
  }
1924 1925
}

1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936

/*
  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())
  {
1937
    // unlink current level from global SELECTs list
1938 1939 1940
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
      sl->link_next->link_prev= sl->link_prev;

1941
    // unlink underlay levels
1942 1943 1944 1945 1946
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
    {
      u->exclude_level();
    }
  }
1947
  // exclude currect unit from list of nodes
1948
  (*prev)= next;
1949 1950
  if (next)
    next->prev= prev;
1951 1952 1953
}


1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
/*
  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
*/

kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1966
void st_select_lex::mark_as_dependent(st_select_lex *last)
1967 1968 1969 1970 1971
{
  /*
    Mark all selects from resolved to 1 before select where was
    found table as depended (of select where was found table)
  */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1972
  for (SELECT_LEX *s= this;
1973
       s && s != last;
1974
       s= s->outer_select())
1975
    if (!(s->uncacheable & UNCACHEABLE_DEPENDENT))
1976 1977
    {
      // Select is dependent of outer select
1978 1979
      s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
                       UNCACHEABLE_DEPENDENT;
1980
      SELECT_LEX_UNIT *munit= s->master_unit();
1981 1982 1983 1984 1985 1986 1987 1988
      munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
                       UNCACHEABLE_DEPENDENT;
      for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
      {
        if (sl != s &&
            !(sl->uncacheable & (UNCACHEABLE_DEPENDENT | UNCACHEABLE_UNITED)))
          sl->uncacheable|= UNCACHEABLE_UNITED;
      }
1989
    }
1990 1991
  is_correlated= TRUE;
  this->master_unit()->item->is_correlated= TRUE;
1992 1993
}

1994 1995 1996 1997 1998
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; }
1999
TABLE_LIST *st_select_lex_node::add_table_to_list (THD *thd, Table_ident *table,
2000
						  LEX_STRING *alias,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2001
						  ulong table_join_options,
2002
						  thr_lock_type flags,
2003
                                                  enum_mdl_type mdl_type,
2004
						  List<Index_hint> *hints,
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2005
                                                  LEX_STRING *option)
2006 2007 2008
{
  return 0;
}
2009 2010 2011 2012 2013 2014 2015 2016
ulong st_select_lex_node::get_table_join_options()
{
  return 0;
}

/*
  prohibit using LIMIT clause
*/
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2017
bool st_select_lex::test_limit()
2018
{
2019
  if (select_limit != 0)
2020 2021
  {
    my_error(ER_NOT_SUPPORTED_YET, MYF(0),
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2022
             "LIMIT & IN/ALL/ANY/SOME subquery");
2023 2024 2025 2026
    return(1);
  }
  return(0);
}
2027

2028

2029 2030 2031 2032 2033
st_select_lex_unit* st_select_lex_unit::master_unit()
{
    return this;
}

2034

2035 2036 2037 2038 2039
st_select_lex* st_select_lex_unit::outer_select()
{
  return (st_select_lex*) master;
}

2040

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2041
bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
2042
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2043
  return add_to_list(thd, order_list, item, asc);
2044
}
2045

2046

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2047
bool st_select_lex::add_item_to_list(THD *thd, Item *item)
2048
{
2049
  DBUG_ENTER("st_select_lex::add_item_to_list");
2050
  DBUG_PRINT("info", ("Item: 0x%lx", (long) item));
2051
  DBUG_RETURN(item_list.push_back(item));
2052 2053
}

2054

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2055
bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
2056
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2057
  return add_to_list(thd, group_list, item, asc);
2058 2059
}

2060

2061 2062 2063 2064 2065
bool st_select_lex::add_ftfunc_to_list(Item_func_match *func)
{
  return !func || ftfunc_list->push_back(func); // end of memory?
}

2066

2067 2068 2069 2070 2071
st_select_lex_unit* st_select_lex::master_unit()
{
  return (st_select_lex_unit*) master;
}

2072

2073 2074 2075 2076 2077
st_select_lex* st_select_lex::outer_select()
{
  return (st_select_lex*) master->get_master();
}

2078

2079 2080 2081 2082 2083 2084
bool st_select_lex::set_braces(bool value)
{
  braces= value;
  return 0; 
}

2085

2086 2087 2088 2089 2090 2091
bool st_select_lex::inc_in_sum_expr()
{
  in_sum_expr++;
  return 0;
}

2092

2093 2094 2095 2096 2097
uint st_select_lex::get_in_sum_expr()
{
  return in_sum_expr;
}

2098

2099 2100
TABLE_LIST* st_select_lex::get_table_list()
{
2101
  return table_list.first;
2102 2103 2104 2105 2106 2107 2108
}

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2109 2110 2111 2112 2113
ulong st_select_lex::get_table_join_options()
{
  return table_join_options;
}

2114

bell@laptop.sanja.is.com.ua's avatar
bell@laptop.sanja.is.com.ua committed
2115 2116 2117 2118
bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
{
  if (ref_pointer_array)
    return 0;
2119 2120 2121 2122 2123

  /*
    We have to create array in prepared statement memory if it is
    prepared statement
  */
konstantin@mysql.com's avatar
konstantin@mysql.com committed
2124
  Query_arena *arena= thd->stmt_arena;
serg@serg.mylan's avatar
serg@serg.mylan committed
2125
  return (ref_pointer_array=
2126 2127 2128
          (Item **)arena->alloc(sizeof(Item*) * (n_child_sum_items +
                                                 item_list.elements +
                                                 select_n_having_items +
evgen@moonbone.local's avatar
evgen@moonbone.local committed
2129
                                                 select_n_where_fields +
2130
                                                 order_group_num)*5)) == 0;
bell@laptop.sanja.is.com.ua's avatar
bell@laptop.sanja.is.com.ua committed
2131 2132
}

2133

2134
void st_select_lex_unit::print(String *str, enum_query_type query_type)
2135
{
2136
  bool union_all= !union_distinct;
2137 2138 2139 2140
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
  {
    if (sl != first_select())
    {
2141
      str->append(STRING_WITH_LEN(" union "));
2142
      if (union_all)
2143
	str->append(STRING_WITH_LEN("all "));
2144
      else if (union_distinct == sl)
2145
        union_all= TRUE;
2146 2147 2148
    }
    if (sl->braces)
      str->append('(');
2149
    sl->print(thd, str, query_type);
2150 2151 2152 2153 2154 2155 2156
    if (sl->braces)
      str->append(')');
  }
  if (fake_select_lex == global_parameters)
  {
    if (fake_select_lex->order_list.elements)
    {
2157
      str->append(STRING_WITH_LEN(" order by "));
2158 2159
      fake_select_lex->print_order(str,
        fake_select_lex->order_list.first,
2160
        query_type);
2161
    }
2162
    fake_select_lex->print_limit(thd, str, query_type);
2163 2164 2165 2166
  }
}


2167 2168 2169
void st_select_lex::print_order(String *str,
                                ORDER *order,
                                enum_query_type query_type)
2170 2171 2172
{
  for (; order; order= order->next)
  {
2173 2174 2175
    if (order->counter_used)
    {
      char buffer[20];
2176 2177
      size_t length= my_snprintf(buffer, 20, "%d", order->counter);
      str->append(buffer, (uint) length);
2178 2179
    }
    else
2180
      (*order->item)->print(str, query_type);
2181
    if (!order->asc)
2182
      str->append(STRING_WITH_LEN(" desc"));
2183 2184 2185 2186 2187
    if (order->next)
      str->append(',');
  }
}
 
2188

2189 2190 2191
void st_select_lex::print_limit(THD *thd,
                                String *str,
                                enum_query_type query_type)
2192
{
2193 2194 2195
  SELECT_LEX_UNIT *unit= master_unit();
  Item_subselect *item= unit->item;
  if (item && unit->global_parameters == this &&
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2196 2197 2198 2199
      (item->substype() == Item_subselect::EXISTS_SUBS ||
       item->substype() == Item_subselect::IN_SUBS ||
       item->substype() == Item_subselect::ALL_SUBS))
  {
2200
    DBUG_ASSERT(!item->fixed ||
2201
                (select_limit->val_int() == LL(1) && offset_limit == 0));
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2202 2203 2204
    return;
  }

2205
  if (explicit_limit)
2206
  {
2207
    str->append(STRING_WITH_LEN(" limit "));
2208 2209
    if (offset_limit)
    {
2210
      offset_limit->print(str, query_type);
2211 2212
      str->append(',');
    }
2213
    select_limit->print(str, query_type);
2214 2215 2216
  }
}

2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
/**
  @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.
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2229
void LEX::cleanup_lex_after_parse_error(THD *thd)
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
{
  /*
    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
  */
2241
  if (thd->lex->sphead)
2242
  {
2243
    thd->lex->sphead->restore_thd_mem_root(thd);
2244 2245 2246 2247
    delete thd->lex->sphead;
    thd->lex->sphead= NULL;
  }
}
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2248

2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
/*
  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)
{
2269
  sql_command= SQLCOM_END;
antony@ppcg5.local's avatar
antony@ppcg5.local committed
2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
  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;
    }
  }
2281 2282 2283 2284
  query_tables= 0;
  query_tables_last= &query_tables;
  query_tables_own_last= 0;
  if (init)
2285 2286 2287 2288 2289
  {
    /*
      We delay real initialization of hash (and therefore related
      memory allocation) until first insertion into this hash.
    */
Konstantin Osipov's avatar
Konstantin Osipov committed
2290
    my_hash_clear(&sroutines);
2291
  }
2292
  else if (sroutines.records)
2293 2294
  {
    /* Non-zero sroutines.records means that hash was initialized. */
2295
    my_hash_reset(&sroutines);
2296
  }
2297 2298 2299
  sroutines_list.empty();
  sroutines_list_own_last= sroutines_list.next;
  sroutines_list_own_elements= 0;
2300
  binlog_stmt_flags= 0;
2301
  stmt_accessed_table_flag= 0;
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
}


/*
  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()
{
Konstantin Osipov's avatar
Konstantin Osipov committed
2314
  my_hash_free(&sroutines);
2315 2316 2317
}


2318 2319 2320 2321
/*
  Initialize LEX object.

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
2322
    LEX::LEX()
2323 2324 2325 2326 2327 2328 2329 2330 2331

  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.
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2332
LEX::LEX()
2333
  :result(0), option_type(OPT_DEFAULT), is_lex_started(0)
2334
{
antony@ppcg5.local's avatar
antony@ppcg5.local committed
2335

antony@ppcg5.local's avatar
antony@ppcg5.local committed
2336 2337 2338 2339
  my_init_dynamic_array2(&plugins, sizeof(plugin_ref),
                         plugins_static_buffer,
                         INITIAL_LEX_PLUGIN_LIST_SIZE, 
                         INITIAL_LEX_PLUGIN_LIST_SIZE);
2340
  reset_query_tables_list(TRUE);
2341 2342 2343
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2344
/*
2345
  Check whether the merging algorithm can be used on this VIEW
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2346 2347

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
2348
    LEX::can_be_merged()
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2349

2350
  DESCRIPTION
2351 2352 2353
    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,
2354 2355 2356
    HAVING clause, aggregate functions, DISTINCT clause, LIMIT clause and
    several underlying tables.

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2357 2358 2359 2360 2361
  RETURN
    FALSE - only temporary table algorithm can be used
    TRUE  - merge algorithm can be used
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2362
bool LEX::can_be_merged()
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2363 2364 2365 2366
{
  // TODO: do not forget implement case when select_lex.table_list.elements==0

  /* find non VIEW subqueries/unions */
2367 2368 2369
  bool selects_allow_merge= select_lex.next_select() == 0;
  if (selects_allow_merge)
  {
2370 2371 2372
    for (SELECT_LEX_UNIT *tmp_unit= select_lex.first_inner_unit();
         tmp_unit;
         tmp_unit= tmp_unit->next_unit())
2373
    {
2374 2375 2376 2377
      if (tmp_unit->first_select()->parent_lex == this &&
          (tmp_unit->item == 0 ||
           (tmp_unit->item->place() != IN_WHERE &&
            tmp_unit->item->place() != IN_ON)))
2378 2379 2380 2381 2382 2383 2384 2385
      {
        selects_allow_merge= 0;
        break;
      }
    }
  }

  return (selects_allow_merge &&
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2386 2387
	  select_lex.group_list.elements == 0 &&
	  select_lex.having == 0 &&
2388
          select_lex.with_sum_func == 0 &&
2389
	  select_lex.table_list.elements >= 1 &&
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2390
	  !(select_lex.options & SELECT_DISTINCT) &&
2391
          select_lex.select_limit == 0);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2392 2393
}

2394

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2395
/*
2396
  check if command can use VIEW with MERGE algorithm (for top VIEWs)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2397 2398

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
2399
    LEX::can_use_merged()
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2400

2401 2402 2403
  DESCRIPTION
    Only listed here commands can use merge algorithm in top level
    SELECT_LEX (for subqueries will be used merge algorithm if
Konstantin Osipov's avatar
Konstantin Osipov committed
2404
    LEX::can_not_use_merged() is not TRUE).
2405

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2406 2407 2408 2409 2410
  RETURN
    FALSE - command can't use merged VIEWs
    TRUE  - VIEWs with MERGE algorithms can be used
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2411
bool LEX::can_use_merged()
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
{
  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:
2425
  case SQLCOM_LOAD:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2426 2427 2428 2429 2430 2431
    return TRUE;
  default:
    return FALSE;
  }
}

2432
/*
2433
  Check if command can't use merged views in any part of command
2434 2435

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
2436
    LEX::can_not_use_merged()
2437

2438 2439
  DESCRIPTION
    Temporary table algorithm will be used on all SELECT levels for queries
Konstantin Osipov's avatar
Konstantin Osipov committed
2440
    listed here (see also LEX::can_use_merged()).
2441

2442 2443 2444 2445 2446
  RETURN
    FALSE - command can't use merged VIEWs
    TRUE  - VIEWs with MERGE algorithms can be used
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2447
bool LEX::can_not_use_merged()
2448 2449 2450 2451 2452
{
  switch (sql_command)
  {
  case SQLCOM_CREATE_VIEW:
  case SQLCOM_SHOW_CREATE:
2453 2454 2455 2456 2457 2458
  /*
    SQLCOM_SHOW_FIELDS is necessary to make 
    information schema tables working correctly with views.
    see get_schema_tables_result function
  */
  case SQLCOM_SHOW_FIELDS:
2459 2460 2461 2462 2463 2464
    return TRUE;
  default:
    return FALSE;
  }
}

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
/*
  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
*/
2475

Konstantin Osipov's avatar
Konstantin Osipov committed
2476
bool LEX::only_view_structure()
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2477
{
2478
  switch (sql_command) {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
  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;
  }
}


2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
/*
  Should Items_ident be printed correctly

  SYNOPSIS
    need_correct_ident()

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


Konstantin Osipov's avatar
Konstantin Osipov committed
2505
bool LEX::need_correct_ident()
2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
{
  switch(sql_command)
  {
  case SQLCOM_SHOW_CREATE:
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_CREATE_VIEW:
    return TRUE;
  default:
    return FALSE;
  }
}

2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534
/*
  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
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2535
uint8 LEX::get_effective_with_check(TABLE_LIST *view)
2536 2537 2538 2539 2540 2541 2542
{
  if (view->select_lex->master_unit() == &unit &&
      which_check_option_applicable())
    return (uint8)view->with_check;
  return VIEW_CHECK_NONE;
}

2543

2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563
/**
  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
Konstantin Osipov's avatar
Konstantin Osipov committed
2564
LEX::copy_db_to(char **p_db, size_t *p_db_length) const
2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
{
  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);
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2581 2582 2583 2584 2585 2586 2587
/*
  initialize limit counters

  SYNOPSIS
    st_select_lex_unit::set_limit()
    values	- SELECT_LEX with initial values for counters
*/
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2588

kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
2589
void st_select_lex_unit::set_limit(st_select_lex *sl)
2590
{
2591
  ha_rows select_limit_val;
2592
  ulonglong val;
2593

konstantin@mysql.com's avatar
konstantin@mysql.com committed
2594
  DBUG_ASSERT(! thd->stmt_arena->is_stmt_prepare());
2595 2596 2597
  val= sl->select_limit ? sl->select_limit->val_uint() : HA_POS_ERROR;
  select_limit_val= (ha_rows)val;
#ifndef BIG_TABLES
2598
  /*
2599 2600 2601 2602 2603 2604
    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
2605 2606 2607 2608 2609 2610 2611
  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
2612 2613
  select_limit_cnt= select_limit_val + offset_limit_cnt;
  if (select_limit_cnt < select_limit_val)
2614 2615 2616
    select_limit_cnt= HA_POS_ERROR;		// no limit
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2617

2618
/**
2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
  @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.
2639 2640
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2641
void LEX::set_trg_event_type_for_tables()
2642
{
2643 2644 2645 2646 2647 2648 2649 2650 2651 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
  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;
  }


2742 2743 2744 2745 2746 2747 2748 2749
  /*
    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)
  {
2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760
    /*
      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;
2761 2762 2763 2764 2765
    tables= tables->next_local;
  }
}


2766
/*
2767 2768
  Unlink the first table from the global table list and the first table from
  outer select (lex->select_lex) local list
2769 2770 2771

  SYNOPSIS
    unlink_first_table()
2772
    link_to_local	Set to 1 if caller should link this table to local list
2773

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2774
  NOTES
2775 2776
    We assume that first tables in both lists is the same table or the local
    list is empty.
2777 2778

  RETURN
2779
    0	If 'query_tables' == 0
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2780
    unlinked table
2781
      In this case link_to_local is set.
2782

2783
*/
Konstantin Osipov's avatar
Konstantin Osipov committed
2784
TABLE_LIST *LEX::unlink_first_table(bool *link_to_local)
2785
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2786 2787 2788 2789 2790 2791 2792 2793
  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;
2794 2795
    else
      query_tables_last= &query_tables;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2796 2797 2798 2799 2800 2801 2802
    first->next_global= 0;

    /*
      and from local list if it is not empty
    */
    if ((*link_to_local= test(select_lex.table_list.first)))
    {
2803 2804
      select_lex.context.table_list= 
        select_lex.context.first_name_resolution_table= first->next_local;
2805
      select_lex.table_list.first= first->next_local;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2806 2807 2808
      select_lex.table_list.elements--;	//safety
      first->next_local= 0;
      /*
2809 2810
        Ensure that the global list has the same first table as the local
        list.
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
      */
      first_lists_tables_same();
    }
  }
  return first;
}


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

  SYNOPSYS
Konstantin Osipov's avatar
Konstantin Osipov committed
2824
     LEX::first_lists_tables_same()
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2825 2826

  NOTES
2827 2828 2829 2830 2831 2832
    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.
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2833 2834
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2835
void LEX::first_lists_tables_same()
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2836
{
2837
  TABLE_LIST *first_table= select_lex.table_list.first;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2838 2839
  if (query_tables != first_table && first_table != 0)
  {
2840
    TABLE_LIST *next;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2841 2842
    if (query_tables_last == &first_table->next_global)
      query_tables_last= first_table->prev_global;
2843

2844
    if ((next= *first_table->prev_global= first_table->next_global))
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2845 2846 2847 2848
      next->prev_global= first_table->prev_global;
    /* include in new place */
    first_table->next_global= query_tables;
    /*
2849 2850 2851
       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
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2852 2853 2854 2855 2856
    */
    query_tables->prev_global= &first_table->next_global;
    first_table->prev_global= &query_tables;
    query_tables= first_table;
  }
2857 2858
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2859

2860
/*
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2861
  Link table back that was unlinked with unlink_first_table()
2862 2863 2864

  SYNOPSIS
    link_first_table_back()
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2865
    link_to_local	do we need link this table to local
2866 2867 2868 2869

  RETURN
    global list
*/
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2870

Konstantin Osipov's avatar
Konstantin Osipov committed
2871
void LEX::link_first_table_back(TABLE_LIST *first,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2872
				   bool link_to_local)
2873
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2874
  if (first)
2875
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2876 2877
    if ((first->next_global= query_tables))
      query_tables->prev_global= &first->next_global;
2878 2879
    else
      query_tables_last= &first->next_global;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2880 2881 2882 2883
    query_tables= first;

    if (link_to_local)
    {
2884
      first->next_local= select_lex.table_list.first;
2885
      select_lex.context.table_list= first;
2886
      select_lex.table_list.first= first;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2887 2888 2889 2890 2891 2892
      select_lex.table_list.elements++;	//safety
    }
  }
}


2893 2894 2895 2896 2897

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

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
2898
    LEX::cleanup_after_one_table_open()
2899 2900 2901 2902 2903

  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).
2904 2905
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2906
void LEX::cleanup_after_one_table_open()
2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928
{
  /*
    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();
  }
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
}


/*
  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
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2941
void LEX::reset_n_backup_query_tables_list(Query_tables_list *backup)
2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959
{
  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
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2960
void LEX::restore_backup_query_tables_list(Query_tables_list *backup)
2961 2962 2963
{
  this->destroy_query_tables_list();
  this->set_query_tables_list(backup);
2964 2965 2966
}


2967 2968 2969 2970
/*
  Checks for usage of routines and/or tables in a parsed statement

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
2971
    LEX:table_or_sp_used()
2972 2973 2974 2975 2976 2977

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

Konstantin Osipov's avatar
Konstantin Osipov committed
2978
bool LEX::table_or_sp_used()
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988
{
  DBUG_ENTER("table_or_sp_used");

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

  DBUG_RETURN(FALSE);
}


2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017
/*
  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)
    {
      tbl->prep_on_expr= tbl->on_expr;
      tbl->on_expr= tbl->on_expr->copy_andor_structure(thd);
    }
    fix_prepare_info_in_table_list(thd, tbl->merge_underlying_list);
  }
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3018
/*
3019
  Save WHERE/HAVING/ON clauses and replace them with disposable copies
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3020 3021 3022

  SYNOPSIS
    st_select_lex::fix_prepare_information
3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033
      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.    
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3034 3035
*/

3036 3037
void st_select_lex::fix_prepare_information(THD *thd, Item **conds, 
                                            Item **having_conds)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3038
{
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3039
  if (!thd->stmt_arena->is_conventional() && first_execution)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3040 3041
  {
    first_execution= 0;
3042 3043 3044 3045 3046
    if (*conds)
    {
      prep_where= *conds;
      *conds= where= prep_where->copy_andor_structure(thd);
    }
3047 3048 3049 3050 3051
    if (*having_conds)
    {
      prep_having= *having_conds;
      *having_conds= having= prep_having->copy_andor_structure(thd);
    }
3052
    fix_prepare_info_in_table_list(thd, table_list.first);
3053 3054 3055
  }
}

3056

3057
/*
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3058
  There are st_select_lex::add_table_to_list &
3059
  st_select_lex::set_lock_for_tables are in sql_parse.cc
3060

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3061
  st_select_lex::print is in sql_select.cc
3062 3063

  st_select_lex_unit::prepare, st_select_lex_unit::exec,
3064 3065
  st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
  st_select_lex_unit::change_result
3066
  are in sql_union.cc
3067
*/
3068

3069 3070 3071 3072 3073
/*
  Sets the kind of hints to be added by the calls to add_index_hint().

  SYNOPSIS
    set_index_hint_type()
3074 3075
      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.
3076 3077 3078 3079 3080 3081 3082 3083

  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.
*/
3084
void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
3085 3086
                                        index_clause_map clause)
{ 
3087
  current_index_hint_type= type_arg;
3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101
  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)
{ 
3102
  index_hints= new (thd->mem_root) List<Index_hint>(); 
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122
}



/*
  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) 
3123
                                 Index_hint(current_index_hint_type,
3124 3125 3126
                                            current_index_hint_clause,
                                            str, length));
}
3127 3128 3129 3130 3131 3132

/**
  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
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
3133
  is used from the sql parser that doesn't have any ifdef's
3134 3135 3136 3137 3138

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

Konstantin Osipov's avatar
Konstantin Osipov committed
3139
bool LEX::is_partition_management() const
3140 3141 3142 3143 3144 3145
{
  return (sql_command == SQLCOM_ALTER_TABLE &&
          (alter_info.flags == ALTER_ADD_PARTITION ||
           alter_info.flags == ALTER_REORGANIZE_PARTITION));
}

3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 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 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292

#ifdef MYSQL_SERVER
uint binlog_unsafe_map[256];

#define UNSAFE(a, b, c) \
  { \
  DBUG_PRINT("unsafe_mixed_statement", ("SETTING BASE VALUES: %s, %s, %02X\n", \
    LEX::stmt_accessed_table_string(a), \
    LEX::stmt_accessed_table_string(b), \
    c)); \
  unsafe_mixed_statement(a, b, c); \
  }

/*
  Sets the combination given by "a" and "b" and automatically combinations
  given by other types of access, i.e. 2^(8 - 2), as unsafe.

  It may happen a colision when automatically defining a combination as unsafe.
  For that reason, a combination has its unsafe condition redefined only when
  the new_condition is greater then the old. For instance,
  
     . (BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY) is never overwritten by 
     . (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF).
*/
void unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,
                            LEX::enum_stmt_accessed_table b, uint condition)
{
  int type= 0;
  int index= (1U << a) | (1U << b);
  
  
  for (type= 0; type < 256; type++)
  {
    if ((type & index) == index)
    {
      binlog_unsafe_map[type] |= condition;
    }
  }
}
/*
  The BINLOG_* AND TRX_CACHE_* values can be combined by using '&' or '|',
  which means that both conditions need to be satisfied or any of them is
  enough. For example, 
    
    . BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY means that the statment is
    unsafe when the option is on and trx-cache is not empty;

    . BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF means the statement is unsafe
    in all cases.

    . TRX_CACHE_EMPTY | TRX_CACHE_NOT_EMPTY means the statement is unsafe
    in all cases. Similar as above.
*/
void binlog_unsafe_map_init()
{
  memset((void*) binlog_unsafe_map, 0, sizeof(uint) * 256);

  /*
    Classify a statement as unsafe when there is a mixed statement and an
    on-going transaction at any point of the execution if:

      1. The mixed statement is about to update a transactional table and
      a non-transactional table.

      2. The mixed statement is about to update a transactional table and
      read from a non-transactional table.

      3. The mixed statement is about to update a non-transactional table
      and temporary transactional table.

      4. The mixed statement is about to update a temporary transactional
      table and read from a non-transactional table.

      5. The mixed statement is about to update a transactional table and
      a temporary non-transactional table.
     
      6. The mixed statement is about to update a transactional table and
      read from a temporary non-transactional table.

      7. The mixed statement is about to update a temporary transactional
      table and temporary non-transactional table.

      8. The mixed statement is about to update a temporary transactional
      table and read from a temporary non-transactional table.

    After updating a transactional table if:

      9. The mixed statement is about to update a non-transactional table
      and read from a transactional table.

      10. The mixed statement is about to update a non-transactional table
      and read from a temporary transactional table.

      11. The mixed statement is about to update a temporary non-transactional
      table and read from a transactional table.
      
      12. The mixed statement is about to update a temporary non-transactional
      table and read from a temporary transactional table.

      13. The mixed statement is about to update a temporary non-transactional
      table and read from a non-transactional table.

    The reason for this is that locks acquired may not protected a concurrent
    transaction of interfering in the current execution and by consequence in
    the result.
  */
  /* Case 1. */
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
  /* Case 2. */
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
  /* Case 3. */
  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_WRITES_TEMP_TRANS_TABLE,
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
  /* Case 4. */
  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
  /* Case 5. */
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON);
  /* Case 6. */
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON);
  /* Case 7. */
  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON);
  /* Case 8. */
  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON);
  /* Case 9. */
  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
    (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
  /* Case 10 */
  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
    (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
  /* Case 11. */
  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
    BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
  /* Case 12. */
  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
    BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
  /* Case 13. */
  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
     BINLOG_DIRECT_OFF & TRX_CACHE_NOT_EMPTY);
}
#endif