sql_lex.cc 78.3 KB
Newer Older
1
/* Copyright (C) 2000-2006 MySQL AB
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
bk@work.mysql.com's avatar
bk@work.mysql.com committed
20 21 22 23
#include "mysql_priv.h"
#include "item_create.h"
#include <m_ctype.h>
#include <hash.h>
24 25
#include "sp.h"
#include "sp_head.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
26

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

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

34
/* Longest standard keyword name */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
35 36
#define TOCK_NAME_LENGTH 24

37 38
/*
  The following data is based on the latin1 character set, and is only
bk@work.mysql.com's avatar
bk@work.mysql.com committed
39 40 41
  used when comparing keywords
*/

monty@mysql.com's avatar
monty@mysql.com committed
42 43
static uchar to_upper_lex[]=
{
bk@work.mysql.com's avatar
bk@work.mysql.com committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    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
};

62 63 64 65 66 67 68 69 70 71 72
/* 
  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"
};
73

bk@work.mysql.com's avatar
bk@work.mysql.com committed
74 75 76 77 78 79 80
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
81
#include <lex_hash.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103


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


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

113 114 115 116 117 118 119
Lex_input_stream::Lex_input_stream(THD *thd,
                                   const char* buffer,
                                   unsigned int length)
: m_thd(thd),
  yylineno(1),
  yytoklen(0),
  yylval(NULL),
120 121 122 123 124 125
  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),
126
  m_buf_length(length),
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
127
  m_echo(TRUE),
128 129 130
  m_cpp_tok_start(NULL),
  m_cpp_tok_start_prev(NULL),
  m_cpp_tok_end(NULL),
131 132
  m_body_utf8(NULL),
  m_cpp_utf8_processed_ptr(NULL),
133 134
  next_state(MY_LEX_START),
  found_semicolon(NULL),
135
  ignore_space(test(thd->variables.sql_mode & MODE_IGNORE_SPACE)),
136
  stmt_prepare_mode(FALSE),
137 138
  in_comment(NO_COMMENT),
  m_underscore_cs(NULL)
139
{
140 141
  m_cpp_buf= (char*) thd->alloc(length + 1);
  m_cpp_ptr= m_cpp_buf;
142 143 144 145 146
}

Lex_input_stream::~Lex_input_stream()
{}

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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
/**
  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;
}

/**
  The operation appends unprocessed part of pre-processed buffer till
  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
252
  if (!my_charset_same(txt_cs, &my_charset_utf8_general_ci))
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  {
    thd->convert_string(&utf_txt,
                        &my_charset_utf8_general_ci,
                        txt->str, txt->length,
                        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;
}

274

275 276 277 278 279 280
/*
  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)
*/

281
void lex_start(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
282
{
283
  LEX *lex= thd->lex;
284 285 286 287
  DBUG_ENTER("lex_start");

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

288
  lex->context_stack.empty();
289 290
  lex->unit.init_query();
  lex->unit.init_select();
291 292
  /* 'parent_lex' is used in init_query() so it must be before it. */
  lex->select_lex.parent_lex= lex;
293 294
  lex->select_lex.init_query();
  lex->value_list.empty();
295
  lex->update_list.empty();
296
  lex->param_list.empty();
monty@mysql.com's avatar
monty@mysql.com committed
297
  lex->view_list.empty();
298
  lex->prepared_stmt_params.empty();
299
  lex->auxiliary_table_list.empty();
300 301 302 303 304 305 306 307 308 309
  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;
310
  lex->select_lex.sql_cache= SELECT_LEX::SQL_CACHE_UNSPECIFIED;
monty@mysql.com's avatar
monty@mysql.com committed
311 312
  lex->select_lex.init_order();
  lex->select_lex.group_list.empty();
313
  lex->describe= 0;
monty@mysql.com's avatar
monty@mysql.com committed
314
  lex->subqueries= FALSE;
monty@mysql.com's avatar
monty@mysql.com committed
315
  lex->view_prepare_mode= FALSE;
monty@mysql.com's avatar
monty@mysql.com committed
316
  lex->derived_tables= 0;
317 318
  lex->lock_option= TL_READ;
  lex->safe_to_cache_query= 1;
319
  lex->leaf_tables_insert= 0;
320
  lex->parsing_options.reset();
monty@mysql.com's avatar
monty@mysql.com committed
321
  lex->empty_field_list_on_rset= 0;
322
  lex->select_lex.select_number= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
323
  lex->length=0;
324
  lex->part_info= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
325 326
  lex->select_lex.in_sum_expr=0;
  lex->select_lex.expr_list.empty();
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
327
  lex->select_lex.ftfunc_list_alloc.empty();
328
  lex->select_lex.ftfunc_list= &lex->select_lex.ftfunc_list_alloc;
329 330
  lex->select_lex.group_list.empty();
  lex->select_lex.order_list.empty();
331
  lex->sql_command= SQLCOM_END;
332
  lex->duplicates= DUP_ERROR;
333
  lex->ignore= 0;
334
  lex->spname= NULL;
335 336
  lex->sphead= NULL;
  lex->spcont= NULL;
337
  lex->proc_list.first= 0;
338
  lex->escape_used= FALSE;
antony@ppcg5.local's avatar
antony@ppcg5.local committed
339
  lex->query_tables= 0;
340
  lex->reset_query_tables_list(FALSE);
341
  lex->expr_allows_subselect= TRUE;
342

343 344
  lex->name.str= 0;
  lex->name.length= 0;
345
  lex->event_parse_data= NULL;
346

igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
347 348 349
  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
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
  /*
    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;
365

366
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
367 368 369 370
}

void lex_end(LEX *lex)
{
monty@mysql.com's avatar
monty@mysql.com committed
371
  DBUG_ENTER("lex_end");
372
  DBUG_PRINT("enter", ("lex: 0x%lx", (long) lex));
monty@mysql.com's avatar
monty@mysql.com committed
373 374 375 376 377 378 379
  if (lex->yacc_yyss)
  {
    my_free(lex->yacc_yyss, MYF(0));
    my_free(lex->yacc_yyvs, MYF(0));
    lex->yacc_yyss= 0;
    lex->yacc_yyvs= 0;
  }
antony@ppcg5.local's avatar
antony@ppcg5.local committed
380 381 382 383 384 385

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

monty@mysql.com's avatar
monty@mysql.com committed
386
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
387 388 389
}


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

394
  SYMBOL *symbol= get_hash_symbol(tok, len, function);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
395 396
  if (symbol)
  {
397 398 399 400
    lip->yylval->symbol.symbol=symbol;
    lip->yylval->symbol.str= (char*) tok;
    lip->yylval->symbol.length=len;

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
408 409 410 411 412
    return symbol->tok;
  }
  return 0;
}

413 414 415 416 417
/*
  Check if name is a keyword

  SYNOPSIS
    is_keyword()
418
    name      checked name (must not be empty)
419 420 421 422 423 424 425 426 427
    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)
{
428
  DBUG_ASSERT(len != 0);
429 430
  return get_hash_symbol(name,len,0)!=0;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
431

432 433 434 435 436 437
bool is_lex_native_function(const LEX_STRING *name)
{
  DBUG_ASSERT(name != NULL);
  return (get_hash_symbol(name->str, name->length, 1) != 0);
}

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

440
static LEX_STRING get_token(Lex_input_stream *lip, uint skip, uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
441 442
{
  LEX_STRING tmp;
443
  lip->yyUnget();                       // ptr points now after last token char
444
  tmp.length=lip->yytoklen=length;
445
  tmp.str= lip->m_thd->strmake(lip->get_tok_start() + skip, tmp.length);
446 447 448 449

  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
450 451 452
  return tmp;
}

453 454 455 456 457 458 459
/* 
 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)
*/

460
static LEX_STRING get_quoted_token(Lex_input_stream *lip,
461
                                   uint skip,
462
                                   uint length, char quote)
463 464
{
  LEX_STRING tmp;
465 466
  const char *from, *end;
  char *to;
467
  lip->yyUnget();                       // ptr points now after last token char
468 469
  tmp.length= lip->yytoklen=length;
  tmp.str=(char*) lip->m_thd->alloc(tmp.length+1);
470
  from= lip->get_tok_start() + skip;
471
  to= tmp.str;
472
  end= to+length;
473 474 475 476

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

477
  for ( ; to != end; )
478
  {
479
    if ((*to++= *from++) == quote)
480
    {
481
      from++;					// Skip double quotes
482 483
      lip->m_cpp_text_start++;
    }
484 485 486 487 488 489 490 491 492 493
  }
  *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
494

495
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
496 497 498
{
  reg1 uchar c,sep;
  uint found_escape=0;
499
  CHARSET_INFO *cs= lip->m_thd->charset();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
500

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

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

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

548
      if (!(start= (char*) lip->m_thd->alloc((uint) (end-str)+1)))
549
	return (char*) "";		// Sql_alloc has set error flag
550 551 552 553

      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
554 555
      if (!found_escape)
      {
556 557 558
	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
559 560 561
      }
      else
      {
562
        char *to;
563

bk@work.mysql.com's avatar
bk@work.mysql.com committed
564 565 566 567
	for (to=start ; str != end ; str++)
	{
#ifdef USE_MB
	  int l;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
568
	  if (use_mb(cs) &&
569
              (l = my_ismbchar(cs, str, end))) {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
570 571 572 573 574 575
	      while (l--)
		  *to++ = *str++;
	      str--;
	      continue;
	  }
#endif
576
	  if (!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
577
              *str == '\\' && str+1 != end)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
	  {
	    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:
603
              *to++= *str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
604 605 606
	      break;
	    }
	  }
607 608
	  else if (*str == sep)
	    *to++= *str++;		// Two ' or "
bk@work.mysql.com's avatar
bk@work.mysql.com committed
609 610 611 612
	  else
	    *to++ = *str;
	}
	*to=0;
613
	lip->yytoklen=(uint) (to-start);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
614
      }
615
      return start;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    }
  }
  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;
637 638
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
639

monty@mysql.com's avatar
monty@mysql.com committed
640
static inline uint int_token(const char *str,uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
{
  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)
675
      return DECIMAL_NUM;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
676 677 678 679
    else
    {
      cmp=signed_longlong_str+1;
      smaller=LONG_NUM;				// If <= signed_longlong_str
680
      bigger=DECIMAL_NUM;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
681 682 683 684 685 686 687 688 689 690 691 692 693
    }
  }
  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)
694 695
    {
      if (length > unsigned_longlong_len)
696
        return DECIMAL_NUM;
697 698
      cmp=unsigned_longlong_str;
      smaller=ULONGLONG_NUM;
699
      bigger=DECIMAL_NUM;
700
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
701 702 703 704
    else
    {
      cmp=longlong_str;
      smaller=LONG_NUM;
705
      bigger= ULONGLONG_NUM;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
706 707 708 709 710 711
    }
  }
  while (*cmp && *cmp++ == *str++) ;
  return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
}

712
/*
713
  MYSQLlex remember the following states from the following MYSQLlex()
714 715 716 717 718

  - 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
719

720
int MYSQLlex(void *arg, void *yythd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
721 722
{
  reg1	uchar c;
723
  int	tokval, result_state;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
724
  uint length;
725
  enum my_lex_states state;
726 727 728
  THD *thd= (THD *)yythd;
  Lex_input_stream *lip= thd->m_lip;
  LEX *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
729
  YYSTYPE *yylval=(YYSTYPE*) arg;
730
  CHARSET_INFO *cs= thd->charset();
731 732
  uchar *state_map= cs->state_map;
  uchar *ident_map= cs->ident_map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
733

734
  lip->yylval=yylval;			// The global state
735

736
  lip->start_token();
737 738
  state=lip->next_state;
  lip->next_state=MY_LEX_OPERATOR_OR_IDENT;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
739 740 741
  LINT_INIT(c);
  for (;;)
  {
742
    switch (state) {
743 744
    case MY_LEX_OPERATOR_OR_IDENT:	// Next is operator or keyword
    case MY_LEX_START:			// Start of token
745 746
      // Skip starting whitespace
      while(state_map[c= lip->yyPeek()] == MY_LEX_SKIP)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
747 748
      {
	if (c == '\n')
749
	  lip->yylineno++;
750 751

        lip->yySkip();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
752
      }
753 754 755 756

      /* Start of real token */
      lip->restart_token();
      c= lip->yyGet();
757
      state= (enum my_lex_states) state_map[c];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
758
      break;
759
    case MY_LEX_ESCAPE:
760
      if (lip->yyGet() == 'N')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
761 762 763 764 765
      {					// Allow \N as shortcut for NULL
	yylval->lex_str.str=(char*) "\\N";
	yylval->lex_str.length=2;
	return NULL_SYM;
      }
766 767
    case MY_LEX_CHAR:			// Unknown or single char token
    case MY_LEX_SKIP:			// This should not happen
768 769 770
      if (c == '-' && lip->yyPeek() == '-' &&
          (my_isspace(cs,lip->yyPeekn(1)) ||
           my_iscntrl(cs,lip->yyPeekn(1))))
771 772 773 774
      {
        state=MY_LEX_COMMENT;
        break;
      }
775

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
779
      if (c == ',')
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
      {
        /*
          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()])
801
        return(PARAM_MARKER);
802 803
      }

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

bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
806
    case MY_LEX_IDENT_OR_NCHAR:
807 808
      if (lip->yyPeek() != '\'')
      {
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
809 810 811
	state= MY_LEX_IDENT;
	break;
      }
812
      /* Found N'string' */
813 814
      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
815
      {
816 817
	state= MY_LEX_CHAR;             // Read char by char
	break;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
818
      }
819
      yylval->lex_str.length= lip->yytoklen;
820
      lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
821
      return(NCHAR_STRING);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
822

823
    case MY_LEX_IDENT_OR_HEX:
824
      if (lip->yyPeek() == '\'')
825
      {					// Found x'hex-number'
826
	state= MY_LEX_HEX_NUMBER;
827 828
	break;
      }
ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
829
    case MY_LEX_IDENT_OR_BIN:
830
      if (lip->yyPeek() == '\'')
ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
831 832 833 834
      {                                 // Found b'bin-number'
        state= MY_LEX_BIN_NUMBER;
        break;
      }
835
    case MY_LEX_IDENT:
836
      const char *start;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
837
#if defined(USE_MB) && defined(USE_MB_IDENT)
838
      if (use_mb(cs))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
839
      {
840
	result_state= IDENT_QUOTED;
841
        if (my_mbcharlen(cs, lip->yyGetLast()) > 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
842
        {
843 844 845
          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
846
          if (l == 0) {
847
            state = MY_LEX_CHAR;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
848 849
            continue;
          }
850
          lip->skip_binary(l - 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
851
        }
852
        while (ident_map[c=lip->yyGet()])
bk@work.mysql.com's avatar
bk@work.mysql.com committed
853
        {
854
          if (my_mbcharlen(cs, c) > 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
855 856
          {
            int l;
857 858 859
            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
860
              break;
861
            lip->skip_binary(l-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
862 863 864 865 866
          }
        }
      }
      else
#endif
867
      {
868
        for (result_state= c; ident_map[c= lip->yyGet()]; result_state|= c);
869 870
        /* If there were non-ASCII characters, mark that we must convert */
        result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
871
      }
872 873
      length= lip->yyLength();
      start= lip->get_ptr();
874
      if (lip->ignore_space)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
875
      {
876 877 878 879
        /*
          If we find a space then this can't be an identifier. We notice this
          below by checking start != lex->ptr.
        */
880
        for (; state_map[c] == MY_LEX_SKIP ; c= lip->yyGet());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
881
      }
882
      if (start == lip->get_ptr() && c == '.' && ident_map[lip->yyPeek()])
883
	lip->next_state=MY_LEX_IDENT_SEP;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
884 885
      else
      {					// '(' must follow directly if function
886 887
        lip->yyUnget();
	if ((tokval = find_keyword(lip, length, c == '(')))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
888
	{
889
	  lip->next_state= MY_LEX_START;	// Allow signed numbers
bk@work.mysql.com's avatar
bk@work.mysql.com committed
890 891
	  return(tokval);		// Was keyword
	}
892
        lip->yySkip();                  // next state does a unget
bk@work.mysql.com's avatar
bk@work.mysql.com committed
893
      }
894
      yylval->lex_str=get_token(lip, 0, length);
895

896
      /*
897 898
         Note: "SELECT _bla AS 'alias'"
         _bla should be considered as a IDENT if charset haven't been found.
899
         So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
900 901 902
         producing an error.
      */

903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
      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);

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

925
    case MY_LEX_IDENT_SEP:		// Found ident and now '.'
926 927 928
      yylval->lex_str.str= (char*) lip->get_ptr();
      yylval->lex_str.length= 1;
      c= lip->yyGet();                  // should be '.'
929
      lip->next_state= MY_LEX_IDENT_START;// Next is an ident (not a keyword)
930
      if (!ident_map[lip->yyPeek()])            // Probably ` or "
931
	lip->next_state= MY_LEX_START;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
932 933
      return((int) c);

934
    case MY_LEX_NUMBER_IDENT:		// number or ident which num-start
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
      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')
        {
          while ((c= lip->yyGet()) == '0' || c == '1');
          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()))) ;
968
      if (!ident_map[c])
bk@work.mysql.com's avatar
bk@work.mysql.com committed
969
      {					// Can't be identifier
970
	state=MY_LEX_INT_OR_REAL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
971 972 973 974
	break;
      }
      if (c == 'e' || c == 'E')
      {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
975
	// The following test is written this way to allow numbers of type 1e1
976 977
        if (my_isdigit(cs,lip->yyPeek()) ||
            (c=(lip->yyGet())) == '+' || c == '-')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
978
	{				// Allow 1E+10
979
          if (my_isdigit(cs,lip->yyPeek()))     // Number must have digit after sign
bk@work.mysql.com's avatar
bk@work.mysql.com committed
980
	  {
981 982 983
            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
984 985 986
	    return(FLOAT_NUM);
	  }
	}
987
        lip->yyUnget();
ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
988
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
989
      // fall through
990
    case MY_LEX_IDENT_START:			// We come here after '.'
991
      result_state= IDENT;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
992
#if defined(USE_MB) && defined(USE_MB_IDENT)
993
      if (use_mb(cs))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
994
      {
995
	result_state= IDENT_QUOTED;
996
        while (ident_map[c=lip->yyGet()])
bk@work.mysql.com's avatar
bk@work.mysql.com committed
997
        {
998
          if (my_mbcharlen(cs, c) > 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
999 1000
          {
            int l;
1001 1002 1003
            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
1004
              break;
1005
            lip->skip_binary(l-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1006 1007 1008 1009 1010
          }
        }
      }
      else
#endif
1011
      {
1012
        for (result_state=0; ident_map[c= lip->yyGet()]; result_state|= c);
1013 1014 1015
        /* If there were non-ASCII characters, mark that we must convert */
        result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
      }
1016
      if (c == '.' && ident_map[lip->yyPeek()])
1017
	lip->next_state=MY_LEX_IDENT_SEP;// Next is '.'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1018

1019
      yylval->lex_str= get_token(lip, 0, lip->yyLength());
1020 1021 1022 1023 1024 1025

      lip->body_utf8_append(lip->m_cpp_text_start);

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

1026
      return(result_state);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1027

1028
    case MY_LEX_USER_VARIABLE_DELIMITER:	// Found quote char
1029
    {
1030 1031
      uint double_quotes= 0;
      char quote_char= c;                       // Used char
1032
      while ((c=lip->yyGet()))
1033
      {
1034 1035
	int var_length;
	if ((var_length= my_mbcharlen(cs, c)) == 1)
1036 1037 1038
	{
	  if (c == quote_char)
	  {
1039
            if (lip->yyPeek() != quote_char)
1040
	      break;
1041
            c=lip->yyGet();
1042 1043 1044
	    double_quotes++;
	    continue;
	  }
1045 1046
	}
#ifdef USE_MB
1047
	else if (var_length < 1)
1048
	  break;				// Error
1049
        lip->skip_binary(var_length-1);
1050
#endif
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1051
      }
1052
      if (double_quotes)
1053
	yylval->lex_str=get_quoted_token(lip, 1,
1054
                                         lip->yyLength() - double_quotes -1,
1055 1056
					 quote_char);
      else
1057
        yylval->lex_str=get_token(lip, 1, lip->yyLength() -1);
1058
      if (c == quote_char)
1059
        lip->yySkip();                  // Skip end `
1060
      lip->next_state= MY_LEX_START;
1061 1062 1063 1064 1065 1066

      lip->body_utf8_append(lip->m_cpp_text_start);

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

1067
      return(IDENT_QUOTED);
1068
    }
1069
    case MY_LEX_INT_OR_REAL:		// Complete int or incomplete real
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1070 1071
      if (c != '.')
      {					// Found complete integer number.
1072
        yylval->lex_str=get_token(lip, 0, lip->yyLength());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1073 1074 1075
	return int_token(yylval->lex_str.str,yylval->lex_str.length);
      }
      // fall through
1076
    case MY_LEX_REAL:			// Incomplete real number
1077
      while (my_isdigit(cs,c = lip->yyGet())) ;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1078 1079 1080

      if (c == 'e' || c == 'E')
      {
1081
        c = lip->yyGet();
1082
	if (c == '-' || c == '+')
1083
          c = lip->yyGet();                     // Skip sign
1084
	if (!my_isdigit(cs,c))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1085
	{				// No digit after sign
1086
	  state= MY_LEX_CHAR;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1087 1088
	  break;
	}
1089 1090
        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
1091 1092
	return(FLOAT_NUM);
      }
1093
      yylval->lex_str=get_token(lip, 0, lip->yyLength());
1094
      return(DECIMAL_NUM);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1095

1096
    case MY_LEX_HEX_NUMBER:		// Found x'hexstring'
1097 1098 1099 1100 1101 1102 1103 1104
      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
1105 1106 1107
      yylval->lex_str=get_token(lip,
                                2,          // skip x'
                                length-3);  // don't count x' and last '
1108 1109
      return (HEX_NUM);

ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
1110
    case MY_LEX_BIN_NUMBER:           // Found b'bin-string'
1111 1112
      lip->yySkip();                  // Accept opening '
      while ((c= lip->yyGet()) == '0' || c == '1');
ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
1113
      if (c != '\'')
1114 1115 1116
        return(ABORT_SYM);            // Illegal hex constant
      lip->yySkip();                  // Accept closing '
      length= lip->yyLength();        // Length of bin-num + 3
1117 1118 1119 1120
      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
1121

1122
    case MY_LEX_CMP_OP:			// Incomplete comparison operator
1123 1124 1125 1126
      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
1127
      {
1128
	lip->next_state= MY_LEX_START;	// Allow signed numbers
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1129 1130
	return(tokval);
      }
1131
      state = MY_LEX_CHAR;		// Something fishy found
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1132 1133
      break;

1134
    case MY_LEX_LONG_CMP_OP:		// Incomplete comparison operator
1135 1136
      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
1137
      {
1138 1139 1140
        lip->yySkip();
        if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP)
          lip->yySkip();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1141
      }
1142
      if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1143
      {
1144
	lip->next_state= MY_LEX_START;	// Found long op
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1145 1146
	return(tokval);
      }
1147
      state = MY_LEX_CHAR;		// Something fishy found
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1148 1149
      break;

1150
    case MY_LEX_BOOL:
1151
      if (c != lip->yyPeek())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1152
      {
1153
	state=MY_LEX_CHAR;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1154 1155
	break;
      }
1156
      lip->yySkip();
1157 1158
      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
1159 1160
      return(tokval);

1161
    case MY_LEX_STRING_OR_DELIMITER:
1162
      if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
1163
      {
1164
	state= MY_LEX_USER_VARIABLE_DELIMITER;
1165 1166 1167
	break;
      }
      /* " used for strings */
1168
    case MY_LEX_STRING:			// Incomplete text string
1169
      if (!(yylval->lex_str.str = get_text(lip, 1, 1)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1170
      {
1171
	state= MY_LEX_CHAR;		// Read char by char
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1172 1173
	break;
      }
1174
      yylval->lex_str.length=lip->yytoklen;
1175 1176 1177 1178 1179 1180 1181 1182 1183

      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;

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

1187
    case MY_LEX_COMMENT:			//  Comment
1188
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
1189 1190
      while ((c = lip->yyGet()) != '\n' && c) ;
      lip->yyUnget();                   // Safety against eof
1191
      state = MY_LEX_START;		// Try again
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1192
      break;
1193
    case MY_LEX_LONG_COMMENT:		/* Long C comment? */
1194
      if (lip->yyPeek() != '*')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1195
      {
1196
	state=MY_LEX_CHAR;		// Probable division
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1197 1198
	break;
      }
1199
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
1200 1201 1202 1203
      /* Reject '/' '*', since we might need to turn off the echo */
      lip->yyUnget();

      if (lip->yyPeekn(2) == '!')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1204
      {
1205 1206
        lip->in_comment= DISCARD_COMMENT;
        /* Accept '/' '*' '!', but do not keep this marker. */
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1207
        lip->set_echo(FALSE);
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
        lip->yySkip();
        lip->yySkip();
        lip->yySkip();

        /*
          The special comment format is very strict:
          '/' '*' '!', followed by exactly
          2 digits (major), then 3 digits (minor).
        */
        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);

          /* Accept 'M' 'M' 'm' 'm' 'm' */
          lip->yySkipn(5);

          if (version <= MYSQL_VERSION_ID)
          {
            /* Expand the content of the special comment as real code */
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1240
            lip->set_echo(TRUE);
1241 1242 1243 1244 1245 1246 1247
            state=MY_LEX_START;
            break;
          }
        }
        else
        {
          state=MY_LEX_START;
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1248
          lip->set_echo(TRUE);
1249 1250
          break;
        }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1251
      }
1252
      else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1253
      {
1254 1255 1256
        lip->in_comment= PRESERVE_COMMENT;
        lip->yySkip();                  // Accept /
        lip->yySkip();                  // Accept *
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1257
      }
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267

      while (! lip->eof() &&
            ((c=lip->yyGet()) != '*' || lip->yyPeek() != '/'))
      {
        if (c == '\n')
          lip->yylineno++;
      }
      if (! lip->eof())
        lip->yySkip();                  // remove last '/'
      state = MY_LEX_START;             // Try again
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1268
      lip->set_echo(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1269
      break;
1270
    case MY_LEX_END_LONG_COMMENT:
1271
      if ((lip->in_comment != NO_COMMENT) && lip->yyPeek() == '/')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1272
      {
1273 1274 1275 1276 1277 1278
        /* 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
1279
        lip->set_echo(TRUE);
1280 1281
        lip->in_comment=NO_COMMENT;
        state=MY_LEX_START;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1282 1283
      }
      else
1284
	state=MY_LEX_CHAR;		// Return '*'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1285
      break;
1286
    case MY_LEX_SET_VAR:		// Check if ':='
1287
      if (lip->yyPeek() != '=')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1288
      {
1289
	state=MY_LEX_CHAR;		// Return ':'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1290 1291
	break;
      }
1292
      lip->yySkip();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1293
      return (SET_VAR);
1294
    case MY_LEX_SEMICOLON:			// optional line terminator
1295
      if (lip->yyPeek())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1296
      {
1297
        if ((thd->client_capabilities & CLIENT_MULTI_STATEMENTS) && 
1298
            !lip->stmt_prepare_mode)
1299
        {
monty@mysql.com's avatar
monty@mysql.com committed
1300
	  lex->safe_to_cache_query= 0;
1301
          lip->found_semicolon= lip->get_ptr();
monty@mysql.com's avatar
monty@mysql.com committed
1302
          thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
1303
          lip->next_state= MY_LEX_END;
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1304
          lip->set_echo(TRUE);
monty@mysql.com's avatar
monty@mysql.com committed
1305
          return (END_OF_INPUT);
1306
        }
monty@mysql.com's avatar
monty@mysql.com committed
1307
        state= MY_LEX_CHAR;		// Return ';'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1308 1309
	break;
      }
1310 1311
      lip->next_state=MY_LEX_END;       // Mark for next loop
      return(END_OF_INPUT);
1312
    case MY_LEX_EOL:
1313
      if (lip->eof())
1314
      {
1315
        lip->yyUnget();                 // Reject the last '\0'
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1316
        lip->set_echo(FALSE);
1317
        lip->yySkip();
kostja@bodhi.(none)'s avatar
kostja@bodhi.(none) committed
1318
        lip->set_echo(TRUE);
1319 1320
        lip->next_state=MY_LEX_END;     // Mark for next loop
        return(END_OF_INPUT);
1321 1322 1323
      }
      state=MY_LEX_CHAR;
      break;
1324
    case MY_LEX_END:
1325
      lip->next_state=MY_LEX_END;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1326
      return(0);			// We found end of input last time
1327 1328
      
      /* Actually real shouldn't start with . but allow them anyhow */
1329
    case MY_LEX_REAL_OR_POINT:
1330
      if (my_isdigit(cs,lip->yyPeek()))
1331
	state = MY_LEX_REAL;		// Real
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1332 1333
      else
      {
1334
	state= MY_LEX_IDENT_SEP;	// return '.'
1335
        lip->yyUnget();                 // Put back '.'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1336 1337
      }
      break;
1338
    case MY_LEX_USER_END:		// end '@' of user@hostname
1339
      switch (state_map[lip->yyPeek()]) {
1340 1341 1342
      case MY_LEX_STRING:
      case MY_LEX_USER_VARIABLE_DELIMITER:
      case MY_LEX_STRING_OR_DELIMITER:
1343
	break;
1344
      case MY_LEX_USER_END:
1345
	lip->next_state=MY_LEX_SYSTEM_VAR;
1346 1347
	break;
      default:
1348
	lip->next_state=MY_LEX_HOSTNAME;
1349 1350
	break;
      }
1351
      yylval->lex_str.str=(char*) lip->get_ptr();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1352 1353
      yylval->lex_str.length=1;
      return((int) '@');
1354
    case MY_LEX_HOSTNAME:		// end '@' of user@hostname
1355
      for (c=lip->yyGet() ;
1356
	   my_isalnum(cs,c) || c == '.' || c == '_' ||  c == '$';
1357 1358
           c= lip->yyGet()) ;
      yylval->lex_str=get_token(lip, 0, lip->yyLength());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1359
      return(LEX_HOSTNAME);
1360
    case MY_LEX_SYSTEM_VAR:
1361
      yylval->lex_str.str=(char*) lip->get_ptr();
1362
      yylval->lex_str.length=1;
1363 1364
      lip->yySkip();                                    // Skip '@'
      lip->next_state= (state_map[lip->yyPeek()] ==
1365 1366 1367
			MY_LEX_USER_VARIABLE_DELIMITER ?
			MY_LEX_OPERATOR_OR_IDENT :
			MY_LEX_IDENT_OR_KEYWORD);
1368
      return((int) '@');
1369
    case MY_LEX_IDENT_OR_KEYWORD:
1370 1371 1372 1373 1374
      /*
	We come here when we have found two '@' in a row.
	We should now be able to handle:
	[(global | local | session) .]variable_name
      */
1375 1376

      for (result_state= 0; ident_map[c= lip->yyGet()]; result_state|= c);
1377 1378
      /* If there were non-ASCII characters, mark that we must convert */
      result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1379

1380
      if (c == '.')
1381
	lip->next_state=MY_LEX_IDENT_SEP;
1382 1383
      length= lip->yyLength();
      if (length == 0)
1384
        return(ABORT_SYM);              // Names must be nonempty.
1385
      if ((tokval= find_keyword(lip, length,0)))
1386
      {
1387
        lip->yyUnget();                         // Put back 'c'
1388 1389
	return(tokval);				// Was keyword
      }
1390
      yylval->lex_str=get_token(lip, 0, length);
1391 1392 1393 1394 1395 1396

      lip->body_utf8_append(lip->m_cpp_text_start);

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

1397
      return(result_state);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1398 1399 1400
    }
  }
}
1401

1402

1403 1404 1405 1406 1407 1408 1409 1410 1411
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),
igor@olga.mysql.com's avatar
igor@olga.mysql.com committed
1412 1413 1414 1415
  no_parts(rhs.no_parts),
  change_level(rhs.change_level),
  datetime_field(rhs.datetime_field),
  error_if_not_empty(rhs.error_if_not_empty)
1416 1417 1418 1419
{
  /*
    Make deep copies of used objects.
    This is not a fully deep copy - clone() implementations
1420
    of Alter_drop, Alter_column, Key, foreign_key, Key_part_spec
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
    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 */
}


1434 1435 1436 1437 1438 1439 1440
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.
  */
1441

1442 1443 1444 1445 1446
  while ((str->length > 0) && (my_isspace(cs, str->str[0])))
  {
    str->length --;
    str->str ++;
  }
1447

1448 1449 1450 1451 1452 1453 1454 1455
  /*
    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 --;
  }
1456 1457
}

1458

1459 1460 1461 1462 1463 1464
/*
  st_select_lex structures initialisations
*/

void st_select_lex_node::init_query()
{
1465
  options= 0;
1466
  sql_cache= SQL_CACHE_UNSPECIFIED;
1467
  linkage= UNSPECIFIED_TYPE;
1468 1469
  no_error= no_table_names_allowed= 0;
  uncacheable= 0;
1470 1471 1472 1473 1474 1475 1476 1477 1478
}

void st_select_lex_node::init_select()
{
}

void st_select_lex_unit::init_query()
{
  st_select_lex_node::init_query();
1479
  linkage= GLOBAL_OPTIONS_TYPE;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1480
  global_parameters= first_select();
1481 1482
  select_limit_cnt= HA_POS_ERROR;
  offset_limit_cnt= 0;
1483
  union_distinct= 0;
1484
  prepared= optimized= executed= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1485
  item= 0;
1486 1487
  union_result= 0;
  table= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1488
  fake_select_lex= 0;
1489
  cleaned= 0;
1490
  item_list.empty();
1491
  describe= 0;
1492
  found_rows_for_union= 0;
1493 1494 1495 1496 1497
}

void st_select_lex::init_query()
{
  st_select_lex_node::init_query();
1498
  table_list.empty();
1499 1500
  top_join_list.empty();
  join_list= &top_join_list;
1501
  embedding= leaf_tables= 0;
1502
  item_list.empty();
1503
  join= 0;
1504
  having= prep_having= where= prep_where= 0;
1505
  olap= UNSPECIFIED_OLAP_TYPE;
1506
  having_fix_field= 0;
1507 1508
  context.select_lex= this;
  context.init();
1509 1510 1511
  /*
    Add the name resolution context of the current (sub)query to the
    stack of contexts for the whole query.
1512 1513 1514 1515 1516
    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.
1517 1518
  */
  parent_lex->push_context(&context);
1519
  cond_count= between_count= with_wild= 0;
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1520
  max_equal_elems= 0;
1521
  conds_processed_with_permanent_arena= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1522
  ref_pointer_array= 0;
evgen@moonbone.local's avatar
evgen@moonbone.local committed
1523
  select_n_where_fields= 0;
bell@laptop.sanja.is.com.ua's avatar
bell@laptop.sanja.is.com.ua committed
1524
  select_n_having_items= 0;
1525
  subquery_in_having= explicit_limit= 0;
1526
  is_item_list_lookup= 0;
1527
  first_execution= 1;
1528
  first_cond_optimization= 1;
1529
  parsing_place= NO_MATTER;
1530
  exclude_from_table_unique_test= no_wrap_view_item= FALSE;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
1531
  nest_level= 0;
1532
  link_next= 0;
1533 1534 1535 1536 1537
}

void st_select_lex::init_select()
{
  st_select_lex_node::init_select();
1538
  group_list.empty();
1539
  type= db= 0;
1540 1541 1542
  having= 0;
  table_join_options= 0;
  in_sum_expr= with_wild= 0;
1543
  options= 0;
1544
  sql_cache= SQL_CACHE_UNSPECIFIED;
1545
  braces= 0;
1546
  expr_list.empty();
1547
  interval_list.empty();
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1548
  ftfunc_list_alloc.empty();
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
1549
  inner_sum_func_list= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1550
  ftfunc_list= &ftfunc_list_alloc;
1551
  linkage= UNSPECIFIED_TYPE;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1552 1553
  order_list.elements= 0;
  order_list.first= 0;
1554
  order_list.next= (uchar**) &order_list.first;
1555 1556 1557
  /* 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
1558
  with_sum_func= 0;
1559
  is_correlated= 0;
1560 1561
  cur_pos_in_select_list= UNDEF_POS;
  non_agg_fields.empty();
1562
  cond_value= having_value= Item::COND_UNDEF;
1563
  inner_refs_list.empty();
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
}

/*
  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;
1578
  slave= 0;
1579 1580
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1581 1582
/*
  include on level down (but do not link)
1583

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
  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;
}

1598 1599 1600 1601 1602 1603 1604 1605
/* 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;
1606
  slave= 0;
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
}

/* 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()
{
1621
  if (link_prev)
1622 1623 1624 1625
  {
    if ((*link_prev= link_next))
      link_next->link_prev= link_prev;
  }
1626 1627 1628 1629
  // Remove slave structure
  for (; slave; slave= slave->next)
    slave->fast_exclude();
  
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
}

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

1651 1652 1653 1654 1655 1656 1657 1658 1659 1660

/*
  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 
*/
1661 1662 1663
void st_select_lex_unit::exclude_level()
{
  SELECT_LEX_UNIT *units= 0, **units_last= &units;
1664
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
1665
  {
1666
    // unlink current level from global SELECTs list
1667 1668
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
      sl->link_next->link_prev= sl->link_prev;
1669 1670

    // bring up underlay levels
1671 1672
    SELECT_LEX_UNIT **last= 0;
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
1673 1674
    {
      u->master= master;
1675
      last= (SELECT_LEX_UNIT**)&(u->next);
1676
    }
1677 1678 1679 1680 1681 1682 1683 1684
    if (last)
    {
      (*units_last)= sl->first_inner_unit();
      units_last= last;
    }
  }
  if (units)
  {
1685
    // include brought up levels in place of current
1686 1687
    (*prev)= units;
    (*units_last)= (SELECT_LEX_UNIT*)next;
1688 1689 1690
    if (next)
      next->prev= (SELECT_LEX_NODE**)units_last;
    units->prev= prev;
1691 1692
  }
  else
1693 1694
  {
    // exclude currect unit from list of nodes
1695
    (*prev)= next;
1696 1697 1698
    if (next)
      next->prev= prev;
  }
1699 1700
}

1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711

/*
  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())
  {
1712
    // unlink current level from global SELECTs list
1713 1714 1715
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
      sl->link_next->link_prev= sl->link_prev;

1716
    // unlink underlay levels
1717 1718 1719 1720 1721
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
    {
      u->exclude_level();
    }
  }
1722
  // exclude currect unit from list of nodes
1723
  (*prev)= next;
1724 1725
  if (next)
    next->prev= prev;
1726 1727 1728
}


1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
/*
  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
*/

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1741
void st_select_lex::mark_as_dependent(SELECT_LEX *last)
1742 1743 1744 1745 1746
{
  /*
    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
1747
  for (SELECT_LEX *s= this;
1748
       s && s != last;
1749
       s= s->outer_select())
1750
    if (!(s->uncacheable & UNCACHEABLE_DEPENDENT))
1751 1752
    {
      // Select is dependent of outer select
1753 1754
      s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
                       UNCACHEABLE_DEPENDENT;
1755
      SELECT_LEX_UNIT *munit= s->master_unit();
1756 1757 1758 1759 1760 1761 1762 1763
      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;
      }
1764
    }
1765 1766
  is_correlated= TRUE;
  this->master_unit()->item->is_correlated= TRUE;
1767 1768
}

1769 1770 1771 1772 1773
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; }
1774
TABLE_LIST *st_select_lex_node::add_table_to_list (THD *thd, Table_ident *table,
1775
						  LEX_STRING *alias,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1776
						  ulong table_join_options,
1777
						  thr_lock_type flags,
1778
						  List<Index_hint> *hints,
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
1779
                                                  LEX_STRING *option)
1780 1781 1782
{
  return 0;
}
1783 1784 1785 1786 1787 1788 1789 1790
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
1791
bool st_select_lex::test_limit()
1792
{
1793
  if (select_limit != 0)
1794 1795
  {
    my_error(ER_NOT_SUPPORTED_YET, MYF(0),
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1796
             "LIMIT & IN/ALL/ANY/SOME subquery");
1797 1798 1799 1800 1801 1802
    return(1);
  }
  // no sense in ORDER BY without LIMIT
  order_list.empty();
  return(0);
}
1803

1804

1805 1806 1807 1808 1809
st_select_lex_unit* st_select_lex_unit::master_unit()
{
    return this;
}

1810

1811 1812 1813 1814 1815
st_select_lex* st_select_lex_unit::outer_select()
{
  return (st_select_lex*) master;
}

1816

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1817
bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
1818
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1819
  return add_to_list(thd, order_list, item, asc);
1820
}
1821

1822

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1823
bool st_select_lex::add_item_to_list(THD *thd, Item *item)
1824
{
1825
  DBUG_ENTER("st_select_lex::add_item_to_list");
1826
  DBUG_PRINT("info", ("Item: 0x%lx", (long) item));
1827
  DBUG_RETURN(item_list.push_back(item));
1828 1829
}

1830

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1831
bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
1832
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1833
  return add_to_list(thd, group_list, item, asc);
1834 1835
}

1836

1837 1838 1839 1840 1841
bool st_select_lex::add_ftfunc_to_list(Item_func_match *func)
{
  return !func || ftfunc_list->push_back(func); // end of memory?
}

1842

1843 1844 1845 1846 1847
st_select_lex_unit* st_select_lex::master_unit()
{
  return (st_select_lex_unit*) master;
}

1848

1849 1850 1851 1852 1853
st_select_lex* st_select_lex::outer_select()
{
  return (st_select_lex*) master->get_master();
}

1854

1855 1856 1857 1858 1859 1860
bool st_select_lex::set_braces(bool value)
{
  braces= value;
  return 0; 
}

1861

1862 1863 1864 1865 1866 1867
bool st_select_lex::inc_in_sum_expr()
{
  in_sum_expr++;
  return 0;
}

1868

1869 1870 1871 1872 1873
uint st_select_lex::get_in_sum_expr()
{
  return in_sum_expr;
}

1874

1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
TABLE_LIST* st_select_lex::get_table_list()
{
  return (TABLE_LIST*) table_list.first;
}

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1885 1886 1887 1888 1889
ulong st_select_lex::get_table_join_options()
{
  return table_join_options;
}

1890

bell@laptop.sanja.is.com.ua's avatar
bell@laptop.sanja.is.com.ua committed
1891 1892 1893 1894
bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
{
  if (ref_pointer_array)
    return 0;
1895 1896 1897 1898 1899

  /*
    We have to create array in prepared statement memory if it is
    prepared statement
  */
konstantin@mysql.com's avatar
konstantin@mysql.com committed
1900
  Query_arena *arena= thd->stmt_arena;
serg@serg.mylan's avatar
serg@serg.mylan committed
1901
  return (ref_pointer_array=
1902 1903 1904
          (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
1905
                                                 select_n_where_fields +
1906
                                                 order_group_num)*5)) == 0;
bell@laptop.sanja.is.com.ua's avatar
bell@laptop.sanja.is.com.ua committed
1907 1908
}

1909

1910 1911
void st_select_lex_unit::print(String *str)
{
1912
  bool union_all= !union_distinct;
1913 1914 1915 1916
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
  {
    if (sl != first_select())
    {
1917
      str->append(STRING_WITH_LEN(" union "));
1918
      if (union_all)
1919
	str->append(STRING_WITH_LEN("all "));
1920
      else if (union_distinct == sl)
1921
        union_all= TRUE;
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
    }
    if (sl->braces)
      str->append('(');
    sl->print(thd, str);
    if (sl->braces)
      str->append(')');
  }
  if (fake_select_lex == global_parameters)
  {
    if (fake_select_lex->order_list.elements)
    {
1933
      str->append(STRING_WITH_LEN(" order by "));
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
      fake_select_lex->print_order(str,
				   (ORDER *) fake_select_lex->
				   order_list.first);
    }
    fake_select_lex->print_limit(thd, str);
  }
}


void st_select_lex::print_order(String *str, ORDER *order)
{
  for (; order; order= order->next)
  {
1947 1948 1949
    if (order->counter_used)
    {
      char buffer[20];
monty@mysql.com's avatar
monty@mysql.com committed
1950 1951
      uint length= my_snprintf(buffer, 20, "%d", order->counter);
      str->append(buffer, length);
1952 1953 1954
    }
    else
      (*order->item)->print(str);
1955
    if (!order->asc)
1956
      str->append(STRING_WITH_LEN(" desc"));
1957 1958 1959 1960 1961
    if (order->next)
      str->append(',');
  }
}
 
1962

1963 1964
void st_select_lex::print_limit(THD *thd, String *str)
{
1965 1966 1967
  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
1968 1969 1970 1971
      (item->substype() == Item_subselect::EXISTS_SUBS ||
       item->substype() == Item_subselect::IN_SUBS ||
       item->substype() == Item_subselect::ALL_SUBS))
  {
1972 1973
    DBUG_ASSERT(!item->fixed ||
                select_limit->val_int() == LL(1) && offset_limit == 0);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1974 1975 1976
    return;
  }

1977
  if (explicit_limit)
1978
  {
1979
    str->append(STRING_WITH_LEN(" limit "));
1980 1981
    if (offset_limit)
    {
1982
      offset_limit->print(str);
1983 1984
      str->append(',');
    }
1985
    select_limit->print(str);
1986 1987 1988
  }
}

1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
/**
  @brief Restore the LEX and THD in case of a parse error.

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

void st_lex::cleanup_lex_after_parse_error(THD *thd)
{
  /*
    Delete sphead for the side effect of restoring of the original
    LEX state, thd->lex, thd->mem_root and thd->free_list if they
    were replaced when parsing stored procedure statements.  We
    will never use sphead object after a parse error, so it's okay
    to delete it only for the sake of the side effect.
    TODO: make this functionality explicit in sp_head class.
    Sic: we must nullify the member of the main lex, not the
    current one that will be thrown away
  */
2013
  if (thd->lex->sphead)
2014 2015 2016 2017 2018
  {
    delete thd->lex->sphead;
    thd->lex->sphead= NULL;
  }
}
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2019

2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
/*
  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)
{
antony@ppcg5.local's avatar
antony@ppcg5.local committed
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
  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;
    }
  }
2051 2052 2053 2054
  query_tables= 0;
  query_tables_last= &query_tables;
  query_tables_own_last= 0;
  if (init)
2055 2056 2057 2058 2059 2060 2061
  {
    /*
      We delay real initialization of hash (and therefore related
      memory allocation) until first insertion into this hash.
    */
    hash_clear(&sroutines);
  }
2062
  else if (sroutines.records)
2063 2064
  {
    /* Non-zero sroutines.records means that hash was initialized. */
2065
    my_hash_reset(&sroutines);
2066
  }
2067 2068 2069
  sroutines_list.empty();
  sroutines_list_own_last= sroutines_list.next;
  sroutines_list_own_elements= 0;
2070
  binlog_stmt_flags= 0;
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
}


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

  SYNOPSIS
    destroy_query_tables_list()
*/

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


2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
/*
  Initialize LEX object.

  SYNOPSIS
    st_lex::st_lex()

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

st_lex::st_lex()
monty@mysql.com's avatar
monty@mysql.com committed
2102
  :result(0), yacc_yyss(0), yacc_yyvs(0),
2103
   sql_command(SQLCOM_END), option_type(OPT_DEFAULT)
2104
{
antony@ppcg5.local's avatar
antony@ppcg5.local committed
2105

antony@ppcg5.local's avatar
antony@ppcg5.local committed
2106 2107 2108 2109
  my_init_dynamic_array2(&plugins, sizeof(plugin_ref),
                         plugins_static_buffer,
                         INITIAL_LEX_PLUGIN_LIST_SIZE, 
                         INITIAL_LEX_PLUGIN_LIST_SIZE);
2110
  reset_query_tables_list(TRUE);
2111 2112 2113
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2114
/*
2115
  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
2116 2117 2118 2119

  SYNOPSIS
    st_lex::can_be_merged()

2120
  DESCRIPTION
2121 2122 2123
    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,
2124 2125 2126
    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
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
  RETURN
    FALSE - only temporary table algorithm can be used
    TRUE  - merge algorithm can be used
*/

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

  /* find non VIEW subqueries/unions */
2137 2138 2139
  bool selects_allow_merge= select_lex.next_select() == 0;
  if (selects_allow_merge)
  {
2140 2141 2142
    for (SELECT_LEX_UNIT *tmp_unit= select_lex.first_inner_unit();
         tmp_unit;
         tmp_unit= tmp_unit->next_unit())
2143
    {
2144 2145 2146 2147
      if (tmp_unit->first_select()->parent_lex == this &&
          (tmp_unit->item == 0 ||
           (tmp_unit->item->place() != IN_WHERE &&
            tmp_unit->item->place() != IN_ON)))
2148 2149 2150 2151 2152 2153 2154 2155
      {
        selects_allow_merge= 0;
        break;
      }
    }
  }

  return (selects_allow_merge &&
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2156 2157
	  select_lex.group_list.elements == 0 &&
	  select_lex.having == 0 &&
2158
          select_lex.with_sum_func == 0 &&
2159
	  select_lex.table_list.elements >= 1 &&
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2160
	  !(select_lex.options & SELECT_DISTINCT) &&
2161
          select_lex.select_limit == 0);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2162 2163
}

2164

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2165
/*
2166
  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
2167 2168 2169 2170

  SYNOPSIS
    st_lex::can_use_merged()

2171 2172 2173 2174 2175
  DESCRIPTION
    Only listed here commands can use merge algorithm in top level
    SELECT_LEX (for subqueries will be used merge algorithm if
    st_lex::can_not_use_merged() is not TRUE).

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
  RETURN
    FALSE - command can't use merged VIEWs
    TRUE  - VIEWs with MERGE algorithms can be used
*/

bool st_lex::can_use_merged()
{
  switch (sql_command)
  {
  case SQLCOM_SELECT:
  case SQLCOM_CREATE_TABLE:
  case SQLCOM_UPDATE:
  case SQLCOM_UPDATE_MULTI:
  case SQLCOM_DELETE:
  case SQLCOM_DELETE_MULTI:
  case SQLCOM_INSERT:
  case SQLCOM_INSERT_SELECT:
  case SQLCOM_REPLACE:
  case SQLCOM_REPLACE_SELECT:
2195
  case SQLCOM_LOAD:
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2196 2197 2198 2199 2200 2201
    return TRUE;
  default:
    return FALSE;
  }
}

2202
/*
2203
  Check if command can't use merged views in any part of command
2204 2205 2206 2207

  SYNOPSIS
    st_lex::can_not_use_merged()

2208 2209 2210 2211
  DESCRIPTION
    Temporary table algorithm will be used on all SELECT levels for queries
    listed here (see also st_lex::can_use_merged()).

2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
  RETURN
    FALSE - command can't use merged VIEWs
    TRUE  - VIEWs with MERGE algorithms can be used
*/

bool st_lex::can_not_use_merged()
{
  switch (sql_command)
  {
  case SQLCOM_CREATE_VIEW:
  case SQLCOM_SHOW_CREATE:
2223 2224 2225 2226 2227 2228
  /*
    SQLCOM_SHOW_FIELDS is necessary to make 
    information schema tables working correctly with views.
    see get_schema_tables_result function
  */
  case SQLCOM_SHOW_FIELDS:
2229 2230 2231 2232 2233 2234
    return TRUE;
  default:
    return FALSE;
  }
}

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
/*
  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
*/
2245

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2246 2247
bool st_lex::only_view_structure()
{
2248
  switch (sql_command) {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
  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;
  }
}


2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
/*
  Should Items_ident be printed correctly

  SYNOPSIS
    need_correct_ident()

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


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

2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
/*
  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
*/

2305
uint8 st_lex::get_effective_with_check(TABLE_LIST *view)
2306 2307 2308 2309 2310 2311 2312
{
  if (view->select_lex->master_unit() == &unit &&
      which_check_option_applicable())
    return (uint8)view->with_check;
  return VIEW_CHECK_NONE;
}

2313

2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
/**
  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
2334
st_lex::copy_db_to(char **p_db, size_t *p_db_length) const
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
{
  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
2351 2352 2353 2354 2355 2356 2357
/*
  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
2358

2359
void st_select_lex_unit::set_limit(SELECT_LEX *sl)
2360
{
2361
  ha_rows select_limit_val;
2362

konstantin@mysql.com's avatar
konstantin@mysql.com committed
2363
  DBUG_ASSERT(! thd->stmt_arena->is_stmt_prepare());
2364 2365 2366 2367
  select_limit_val= (ha_rows)(sl->select_limit ? sl->select_limit->val_uint() :
                                                 HA_POS_ERROR);
  offset_limit_cnt= (ha_rows)(sl->offset_limit ? sl->offset_limit->val_uint() :
                                                 ULL(0));
2368 2369
  select_limit_cnt= select_limit_val + offset_limit_cnt;
  if (select_limit_cnt < select_limit_val)
2370 2371 2372
    select_limit_cnt= HA_POS_ERROR;		// no limit
}

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

2374
/**
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
  @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.
2395 2396 2397 2398
*/

void st_lex::set_trg_event_type_for_tables()
{
2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497
  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;
  }


2498 2499 2500 2501 2502 2503 2504 2505
  /*
    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)
  {
2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
    /*
      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;
2517 2518 2519 2520 2521
    tables= tables->next_local;
  }
}


2522
/*
2523 2524
  Unlink the first table from the global table list and the first table from
  outer select (lex->select_lex) local list
2525 2526 2527

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2530
  NOTES
2531 2532
    We assume that first tables in both lists is the same table or the local
    list is empty.
2533 2534

  RETURN
2535
    0	If 'query_tables' == 0
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2536
    unlinked table
2537
      In this case link_to_local is set.
2538

2539
*/
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2540
TABLE_LIST *st_lex::unlink_first_table(bool *link_to_local)
2541
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2542 2543 2544 2545 2546 2547 2548 2549
  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;
2550 2551
    else
      query_tables_last= &query_tables;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2552 2553 2554 2555 2556 2557 2558
    first->next_global= 0;

    /*
      and from local list if it is not empty
    */
    if ((*link_to_local= test(select_lex.table_list.first)))
    {
2559 2560
      select_lex.context.table_list= 
        select_lex.context.first_name_resolution_table= first->next_local;
2561
      select_lex.table_list.first= (uchar*) (first->next_local);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2562 2563 2564
      select_lex.table_list.elements--;	//safety
      first->next_local= 0;
      /*
2565 2566
        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
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582
      */
      first_lists_tables_same();
    }
  }
  return first;
}


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

  SYNOPSYS
     st_lex::first_lists_tables_same()

  NOTES
2583 2584 2585 2586 2587 2588
    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
2589 2590 2591 2592 2593 2594 2595
*/

void st_lex::first_lists_tables_same()
{
  TABLE_LIST *first_table= (TABLE_LIST*) select_lex.table_list.first;
  if (query_tables != first_table && first_table != 0)
  {
2596
    TABLE_LIST *next;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2597 2598
    if (query_tables_last == &first_table->next_global)
      query_tables_last= first_table->prev_global;
2599

2600
    if ((next= *first_table->prev_global= first_table->next_global))
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2601 2602 2603 2604
      next->prev_global= first_table->prev_global;
    /* include in new place */
    first_table->next_global= query_tables;
    /*
2605 2606 2607
       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
2608 2609 2610 2611 2612
    */
    query_tables->prev_global= &first_table->next_global;
    first_table->prev_global= &query_tables;
    query_tables= first_table;
  }
2613 2614
}

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

2616
/*
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2617
  Link table back that was unlinked with unlink_first_table()
2618 2619 2620

  SYNOPSIS
    link_first_table_back()
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2621
    link_to_local	do we need link this table to local
2622 2623 2624 2625

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

void st_lex::link_first_table_back(TABLE_LIST *first,
				   bool link_to_local)
2629
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2630
  if (first)
2631
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2632 2633
    if ((first->next_global= query_tables))
      query_tables->prev_global= &first->next_global;
2634 2635
    else
      query_tables_last= &first->next_global;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2636 2637 2638 2639 2640
    query_tables= first;

    if (link_to_local)
    {
      first->next_local= (TABLE_LIST*) select_lex.table_list.first;
2641
      select_lex.context.table_list= first;
2642
      select_lex.table_list.first= (uchar*) first;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2643 2644 2645 2646 2647 2648
      select_lex.table_list.elements++;	//safety
    }
  }
}


2649 2650 2651 2652 2653 2654

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

  SYNOPSIS
    st_lex::cleanup_after_one_table_open()
2655 2656 2657 2658 2659

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

void st_lex::cleanup_after_one_table_open()
{
  /*
    thd->lex->derived_tables & additional units may be set if we open
    a view. It is necessary to clear thd->lex->derived_tables flag
    to prevent processing of derived tables during next open_and_lock_tables
    if next table is a real table and cleanup & remove underlying units
    NOTE: all units will be connected to thd->lex->select_lex, because we
    have not UNION on most upper level.
    */
  if (all_selects_list != &select_lex)
  {
    derived_tables= 0;
    /* cleunup underlying units (units of VIEW) */
    for (SELECT_LEX_UNIT *un= select_lex.first_inner_unit();
         un;
         un= un->next_unit())
      un->cleanup();
    /* reduce all selects list to default state */
    all_selects_list= &select_lex;
    /* remove underlying units (units of VIEW) subtree */
    select_lex.cut_subtree();
  }
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
}


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

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

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


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

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

void st_lex::restore_backup_query_tables_list(Query_tables_list *backup)
{
  this->destroy_query_tables_list();
  this->set_query_tables_list(backup);
2720 2721 2722
}


2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
/*
  Checks for usage of routines and/or tables in a parsed statement

  SYNOPSIS
    st_lex:table_or_sp_used()

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

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

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

  DBUG_RETURN(FALSE);
}


2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773
/*
  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
2774
/*
2775
  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
2776 2777 2778

  SYNOPSIS
    st_select_lex::fix_prepare_information
2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789
      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
2790 2791
*/

2792 2793
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
2794
{
konstantin@mysql.com's avatar
konstantin@mysql.com committed
2795
  if (!thd->stmt_arena->is_conventional() && first_execution)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2796 2797
  {
    first_execution= 0;
2798 2799 2800 2801 2802
    if (*conds)
    {
      prep_where= *conds;
      *conds= where= prep_where->copy_andor_structure(thd);
    }
2803 2804 2805 2806 2807
    if (*having_conds)
    {
      prep_having= *having_conds;
      *having_conds= having= prep_having->copy_andor_structure(thd);
    }
2808
    fix_prepare_info_in_table_list(thd, (TABLE_LIST *)table_list.first);
2809 2810 2811
  }
}

2812

2813
/*
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2814
  There are st_select_lex::add_table_to_list &
2815
  st_select_lex::set_lock_for_tables are in sql_parse.cc
2816

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2817
  st_select_lex::print is in sql_select.cc
2818 2819

  st_select_lex_unit::prepare, st_select_lex_unit::exec,
2820 2821
  st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
  st_select_lex_unit::change_result
2822
  are in sql_union.cc
2823
*/
2824

2825 2826 2827 2828 2829
/*
  Sets the kind of hints to be added by the calls to add_index_hint().

  SYNOPSIS
    set_index_hint_type()
2830 2831
      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.
2832 2833 2834 2835 2836 2837 2838 2839

  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.
*/
2840
void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
2841 2842
                                        index_clause_map clause)
{ 
2843
  current_index_hint_type= type_arg;
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857
  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)
{ 
2858
  index_hints= new (thd->mem_root) List<Index_hint>(); 
2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
}



/*
  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) 
2879
                                 Index_hint(current_index_hint_type,
2880 2881 2882
                                            current_index_hint_clause,
                                            str, length));
}
2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901

/**
  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
  is used from the sql parser that doesn't have any #ifdef's

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

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