sql_lex.cc 42.2 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4 5 6
   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
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
unknown's avatar
unknown committed
7

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

unknown's avatar
unknown committed
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
   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 */

#include "mysql_priv.h"
#include "item_create.h"
#include <m_ctype.h>
#include <hash.h>

LEX_STRING tmp_table_alias= {(char*) "tmp-table",8};

/* Macros to look like lex */

#define yyGet()		*(lex->ptr++)
#define yyGetLast()	lex->ptr[-1]
#define yyPeek()	lex->ptr[0]
#define yyPeek2()	lex->ptr[1]
#define yyUnget()	lex->ptr--
#define yySkip()	lex->ptr++
#define yyLength()	((uint) (lex->ptr - lex->tok_start)-1)

#if MYSQL_VERSION_ID < 32300
#define FLOAT_NUM	REAL_NUM
#endif

pthread_key(LEX*,THR_LEX);

43
/* Longest standard keyword name */
unknown's avatar
unknown committed
44 45 46
#define TOCK_NAME_LENGTH 24

/*
47 48 49 50 51 52 53 54
  Map to default keyword characters.  This is used to test if an identifer
  is 'simple', in which case we don't have to do any character set conversions
  on it
*/
uchar *bin_ident_map= my_charset_bin.ident_map;

/*
  The following data is based on the latin1 character set, and is only
unknown's avatar
unknown committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
  used when comparing keywords
*/

uchar to_upper_lex[] = {
    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
};

77

unknown's avatar
unknown committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
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;
}

#include "lex_hash.h"


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

  VOID(pthread_key_create(&THR_LEX,NULL));

  DBUG_VOID_RETURN;
}


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


110 111 112 113 114 115
/*
  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)
*/

unknown's avatar
unknown committed
116 117
LEX *lex_start(THD *thd, uchar *buf,uint length)
{
118
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
119
  lex->thd= thd;
120
  lex->next_state=MY_LEX_START;
unknown's avatar
unknown committed
121 122
  lex->end_of_query=(lex->ptr=buf)+length;
  lex->yylineno = 1;
unknown's avatar
unknown committed
123 124
  lex->select_lex.parsing_place= SELECT_LEX_NODE::NO_MATTER;
  lex->in_comment=0;
unknown's avatar
unknown committed
125
  lex->length=0;
unknown's avatar
unknown committed
126 127
  lex->select_lex.in_sum_expr=0;
  lex->select_lex.expr_list.empty();
unknown's avatar
unknown committed
128
  lex->select_lex.ftfunc_list_alloc.empty();
129
  lex->select_lex.ftfunc_list= &lex->select_lex.ftfunc_list_alloc;
unknown's avatar
unknown committed
130 131
  lex->select_lex.group_list.empty();
  lex->select_lex.order_list.empty();
unknown's avatar
unknown committed
132
  lex->current_select= &lex->select_lex;
unknown's avatar
unknown committed
133
  lex->yacc_yyss=lex->yacc_yyvs=0;
134
  lex->ignore_space=test(thd->variables.sql_mode & MODE_IGNORE_SPACE);
135
  lex->sql_command=SQLCOM_END;
136
  lex->duplicates= DUP_ERROR;
unknown's avatar
unknown committed
137 138 139 140 141
  return lex;
}

void lex_end(LEX *lex)
{
unknown's avatar
unknown committed
142
  lex->select_lex.expr_list.delete_elements();	// If error when parsing sql-varargs
unknown's avatar
unknown committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
  x_free(lex->yacc_yyss);
  x_free(lex->yacc_yyvs);
}


static int find_keyword(LEX *lex, uint len, bool function)
{
  uchar *tok=lex->tok_start;

  SYMBOL *symbol = get_hash_symbol((const char *)tok,len,function);
  if (symbol)
  {
    lex->yylval->symbol.symbol=symbol;
    lex->yylval->symbol.str= (char*) tok;
    lex->yylval->symbol.length=len;
    return symbol->tok;
  }
#ifdef HAVE_DLOPEN
  udf_func *udf;
  if (function && using_udf_functions && (udf=find_udf((char*) tok, len)))
  {
164
    lex->safe_to_cache_query=0;
165
    lex->yylval->udf=udf;
unknown's avatar
unknown committed
166 167 168 169 170 171 172
    switch (udf->returns) {
    case STRING_RESULT:
      return (udf->type == UDFTYPE_FUNCTION) ? UDF_CHAR_FUNC : UDA_CHAR_SUM;
    case REAL_RESULT:
      return (udf->type == UDFTYPE_FUNCTION) ? UDF_FLOAT_FUNC : UDA_FLOAT_SUM;
    case INT_RESULT:
      return (udf->type == UDFTYPE_FUNCTION) ? UDF_INT_FUNC : UDA_INT_SUM;
173
    case ROW_RESULT:
unknown's avatar
unknown committed
174
    default:
unknown's avatar
unknown committed
175 176 177
      // This case should never be choosen
      DBUG_ASSERT(0);
      return 0;
unknown's avatar
unknown committed
178 179 180 181 182 183
    }
  }
#endif
  return 0;
}

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
/*
  Check if name is a keyword

  SYNOPSIS
    is_keyword()
    name      checked name
    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)
{
  return get_hash_symbol(name,len,0)!=0;
}
unknown's avatar
unknown committed
201 202 203

/* make a copy of token before ptr and set yytoklen */

204
static LEX_STRING get_token(LEX *lex,uint length)
unknown's avatar
unknown committed
205 206 207 208
{
  LEX_STRING tmp;
  yyUnget();			// ptr points now after last token char
  tmp.length=lex->yytoklen=length;
209
  tmp.str=(char*) lex->thd->strmake((char*) lex->tok_start,tmp.length);
unknown's avatar
unknown committed
210 211 212
  return tmp;
}

213 214 215 216 217 218 219
/* 
 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)
*/

220 221 222 223 224 225 226
static LEX_STRING get_quoted_token(LEX *lex,uint length, char quote)
{
  LEX_STRING tmp;
  byte *from, *to, *end;
  yyUnget();			// ptr points now after last token char
  tmp.length=lex->yytoklen=length;
  tmp.str=(char*) lex->thd->alloc(tmp.length+1);
unknown's avatar
unknown committed
227 228 229
  for (from= (byte*) lex->tok_start, to= (byte*) tmp.str, end= to+length ;
       to != end ;
       )
230 231 232 233 234 235 236 237 238 239 240 241 242
  {
    if ((*to++= *from++) == quote)
      from++;					// Skip double quotes
  }
  *to= 0;					// End null for safety
  return tmp;
}


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

static char *get_text(LEX *lex)
{
  reg1 uchar c,sep;
  uint found_escape=0;
248
  CHARSET_INFO *cs= lex->thd->charset();
unknown's avatar
unknown committed
249 250 251 252 253 254 255 256

  sep= yyGetLast();			// String should end with this
  //lex->tok_start=lex->ptr-1;		// Remember '
  while (lex->ptr != lex->end_of_query)
  {
    c = yyGet();
#ifdef USE_MB
    int l;
unknown's avatar
unknown committed
257 258
    if (use_mb(cs) &&
        (l = my_ismbchar(cs,
unknown's avatar
unknown committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
                         (const char *)lex->ptr-1,
                         (const char *)lex->end_of_query))) {
	lex->ptr += l-1;
	continue;
    }
#endif
    if (c == '\\')
    {					// Escaped character
      found_escape=1;
      if (lex->ptr == lex->end_of_query)
	return 0;
      yySkip();
    }
    else if (c == sep)
    {
      if (c == yyGet())			// Check if two separators in a row
      {
	found_escape=1;			// dupplicate. Remember for delete
	continue;
      }
      else
	yyUnget();

      /* Found end. Unescape and return string */
      uchar *str,*end,*start;

      str=lex->tok_start+1;
      end=lex->ptr-1;
287
      if (!(start=(uchar*) lex->thd->alloc((uint) (end-str)+1)))
unknown's avatar
unknown committed
288
	return (char*) "";		// Sql_alloc has set error flag
unknown's avatar
unknown committed
289 290 291 292 293 294 295 296 297 298 299 300 301
      if (!found_escape)
      {
	lex->yytoklen=(uint) (end-str);
	memcpy(start,str,lex->yytoklen);
	start[lex->yytoklen]=0;
      }
      else
      {
	uchar *to;
	for (to=start ; str != end ; str++)
	{
#ifdef USE_MB
	  int l;
unknown's avatar
unknown committed
302 303
	  if (use_mb(cs) &&
              (l = my_ismbchar(cs,
unknown's avatar
unknown committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
                               (const char *)str, (const char *)end))) {
	      while (l--)
		  *to++ = *str++;
	      str--;
	      continue;
	  }
#endif
	  if (*str == '\\' && str+1 != end)
	  {
	    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:
	      *to++ = *str;
	      break;
	    }
	  }
	  else if (*str == sep)
	    *to++= *str++;		// Two ' or "
	  else
	    *to++ = *str;

	}
	*to=0;
	lex->yytoklen=(uint) (to-start);
      }
      return (char*) start;
    }
  }
  return 0;					// unexpected end of query
}


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

static const char *long_str="2147483647";
static const uint long_len=10;
static const char *signed_long_str="-2147483648";
static const char *longlong_str="9223372036854775807";
static const uint longlong_len=19;
static const char *signed_longlong_str="-9223372036854775808";
static const uint signed_longlong_len=19;
unknown's avatar
unknown committed
372 373
static const char *unsigned_longlong_str="18446744073709551615";
static const uint unsigned_longlong_len=20;
unknown's avatar
unknown committed
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428

inline static uint int_token(const char *str,uint length)
{
  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)
      return REAL_NUM;
    else
    {
      cmp=signed_longlong_str+1;
      smaller=LONG_NUM;				// If <= signed_longlong_str
      bigger=REAL_NUM;
    }
  }
  else
  {
    if (length == long_len)
    {
      cmp= long_str;
      smaller=NUM;
      bigger=LONG_NUM;
    }
    else if (length < longlong_len)
      return LONG_NUM;
    else if (length > longlong_len)
unknown's avatar
unknown committed
429 430 431 432 433 434 435
    {
      if (length > unsigned_longlong_len)
	return REAL_NUM;
      cmp=unsigned_longlong_str;
      smaller=ULONGLONG_NUM;
      bigger=REAL_NUM;
    }
unknown's avatar
unknown committed
436 437 438 439
    else
    {
      cmp=longlong_str;
      smaller=LONG_NUM;
440
      bigger= ULONGLONG_NUM;
unknown's avatar
unknown committed
441 442 443 444 445 446
    }
  }
  while (*cmp && *cmp++ == *str++) ;
  return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
}

447 448 449 450 451 452 453
/*
  yylex remember the following states from the following yylex()

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

455
int yylex(void *arg, void *yythd)
unknown's avatar
unknown committed
456 457
{
  reg1	uchar c;
458
  int	tokval, result_state;
unknown's avatar
unknown committed
459
  uint length;
unknown's avatar
unknown committed
460
  enum my_lex_states state;
461
  LEX	*lex= ((THD *)yythd)->lex;
unknown's avatar
unknown committed
462
  YYSTYPE *yylval=(YYSTYPE*) arg;
463
  CHARSET_INFO *cs= ((THD *) yythd)->charset();
464 465
  uchar *state_map= cs->state_map;
  uchar *ident_map= cs->ident_map;
unknown's avatar
unknown committed
466 467 468

  lex->yylval=yylval;			// The global state
  lex->tok_start=lex->tok_end=lex->ptr;
unknown's avatar
unknown committed
469
  state=lex->next_state;
470
  lex->next_state=MY_LEX_OPERATOR_OR_IDENT;
unknown's avatar
unknown committed
471 472 473
  LINT_INIT(c);
  for (;;)
  {
474
    switch (state) {
475 476
    case MY_LEX_OPERATOR_OR_IDENT:	// Next is operator or keyword
    case MY_LEX_START:			// Start of token
477
      // Skip startspace
478
      for (c=yyGet() ; (state_map[c] == MY_LEX_SKIP) ; c= yyGet())
unknown's avatar
unknown committed
479 480 481 482 483
      {
	if (c == '\n')
	  lex->yylineno++;
      }
      lex->tok_start=lex->ptr-1;	// Start of real token
484
      state= (enum my_lex_states) state_map[c];
unknown's avatar
unknown committed
485
      break;
486
    case MY_LEX_ESCAPE:
unknown's avatar
unknown committed
487 488 489 490 491 492
      if (yyGet() == 'N')
      {					// Allow \N as shortcut for NULL
	yylval->lex_str.str=(char*) "\\N";
	yylval->lex_str.length=2;
	return NULL_SYM;
      }
493 494
    case MY_LEX_CHAR:			// Unknown or single char token
    case MY_LEX_SKIP:			// This should not happen
495 496 497 498 499 500 501
      if (c == '-' && yyPeek() == '-' &&
          (my_isspace(cs,yyPeek2()) || 
           my_iscntrl(cs,yyPeek2())))
      {
        state=MY_LEX_COMMENT;
        break;
      }
unknown's avatar
unknown committed
502
      yylval->lex_str.str=(char*) (lex->ptr=lex->tok_start);// Set to first chr
unknown's avatar
unknown committed
503 504 505
      yylval->lex_str.length=1;
      c=yyGet();
      if (c != ')')
506
	lex->next_state= MY_LEX_START;	// Allow signed numbers
unknown's avatar
unknown committed
507 508 509 510
      if (c == ',')
	lex->tok_start=lex->ptr;	// Let tok_start point at next item
      return((int) c);

unknown's avatar
unknown committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
    case MY_LEX_IDENT_OR_NCHAR:
      if (yyPeek() != '\'')
      {					// Found x'hex-number'
	state= MY_LEX_IDENT;
	break;
      }
      yyGet();				// Skip '
      while ((c = yyGet()) && (c !='\'')) ;
      length=(lex->ptr - lex->tok_start);	// Length of hexnum+3
      if (c != '\'')
      {
	return(ABORT_SYM);		// Illegal hex constant
      }
      yyGet();				// get_token makes an unget
      yylval->lex_str=get_token(lex,length);
      yylval->lex_str.str+=2;		// Skip x'
      yylval->lex_str.length-=3;	// Don't count x' and last '
      lex->yytoklen-=3;
      return (NCHAR_STRING);

531
    case MY_LEX_IDENT_OR_HEX:
unknown's avatar
unknown committed
532
      if (yyPeek() == '\'')
533
      {					// Found x'hex-number'
534
	state= MY_LEX_HEX_NUMBER;
535 536
	break;
      }
unknown's avatar
unknown committed
537
      /* Fall through */
538 539
    case MY_LEX_IDENT_OR_BIN:		// TODO: Add binary string handling
    case MY_LEX_IDENT:
unknown's avatar
unknown committed
540
#if defined(USE_MB) && defined(USE_MB_IDENT)
541
      if (use_mb(cs))
unknown's avatar
unknown committed
542
      {
543
	result_state= IDENT_QUOTED;
544
        if (my_mbcharlen(cs, yyGetLast()) > 1)
unknown's avatar
unknown committed
545
        {
546
          int l = my_ismbchar(cs,
unknown's avatar
unknown committed
547 548 549
                              (const char *)lex->ptr-1,
                              (const char *)lex->end_of_query);
          if (l == 0) {
550
            state = MY_LEX_CHAR;
unknown's avatar
unknown committed
551 552 553 554
            continue;
          }
          lex->ptr += l - 1;
        }
unknown's avatar
unknown committed
555
        while (ident_map[c=yyGet()])
unknown's avatar
unknown committed
556
        {
557
          if (my_mbcharlen(cs, c) > 1)
unknown's avatar
unknown committed
558 559
          {
            int l;
560
            if ((l = my_ismbchar(cs,
unknown's avatar
unknown committed
561 562 563 564 565 566 567 568 569
                              (const char *)lex->ptr-1,
                              (const char *)lex->end_of_query)) == 0)
              break;
            lex->ptr += l-1;
          }
        }
      }
      else
#endif
570 571 572 573 574 575 576 577 578
      {
	result_state= bin_ident_map[c] ? IDENT : IDENT_QUOTED;
        while (ident_map[c=yyGet()])
	{
	  /* If not simple character, mark that we must convert it */
	  if (!bin_ident_map[c])
	    result_state= IDENT_QUOTED;
	}
      }
unknown's avatar
unknown committed
579 580 581
      length= (uint) (lex->ptr - lex->tok_start)-1;
      if (lex->ignore_space)
      {
582
	for (; state_map[c] == MY_LEX_SKIP ; c= yyGet());
unknown's avatar
unknown committed
583
      }
unknown's avatar
unknown committed
584
      if (c == '.' && ident_map[yyPeek()])
585
	lex->next_state=MY_LEX_IDENT_SEP;
unknown's avatar
unknown committed
586 587 588 589 590
      else
      {					// '(' must follow directly if function
	yyUnget();
	if ((tokval = find_keyword(lex,length,c == '(')))
	{
591
	  lex->next_state= MY_LEX_START;	// Allow signed numbers
unknown's avatar
unknown committed
592 593 594 595 596
	  return(tokval);		// Was keyword
	}
	yySkip();			// next state does a unget
      }
      yylval->lex_str=get_token(lex,length);
597 598 599 600

      /* 
         Note: "SELECT _bla AS 'alias'"
         _bla should be considered as a IDENT if charset haven't been found.
601
         So we don't use MYF(MY_WME) with get_charset_by_csname to avoid 
602 603 604 605
         producing an error.
      */

      if ((yylval->lex_str.str[0]=='_') && 
unknown's avatar
unknown committed
606 607
          (lex->charset=get_charset_by_csname(yylval->lex_str.str+1,
					      MY_CS_PRIMARY,MYF(0))))
608
        return(UNDERSCORE_CHARSET);
609
      return(result_state);			// IDENT or IDENT_QUOTED
unknown's avatar
unknown committed
610

611
    case MY_LEX_IDENT_SEP:		// Found ident and now '.'
unknown's avatar
unknown committed
612 613 614
      yylval->lex_str.str=(char*) lex->ptr;
      yylval->lex_str.length=1;
      c=yyGet();			// should be '.'
615 616 617
      lex->next_state= MY_LEX_IDENT_START;// Next is an ident (not a keyword)
      if (!ident_map[yyPeek()])		// Probably ` or "
	lex->next_state= MY_LEX_START;
unknown's avatar
unknown committed
618 619
      return((int) c);

620 621
    case MY_LEX_NUMBER_IDENT:		// number or ident which num-start
      while (my_isdigit(cs,(c = yyGet()))) ;
unknown's avatar
unknown committed
622
      if (!ident_map[c])
unknown's avatar
unknown committed
623
      {					// Can't be identifier
624
	state=MY_LEX_INT_OR_REAL;
unknown's avatar
unknown committed
625 626 627 628
	break;
      }
      if (c == 'e' || c == 'E')
      {
unknown's avatar
unknown committed
629
	// The following test is written this way to allow numbers of type 1e1
630
	if (my_isdigit(cs,yyPeek()) || 
631
            (c=(yyGet())) == '+' || c == '-')
unknown's avatar
unknown committed
632
	{				// Allow 1E+10
633
	  if (my_isdigit(cs,yyPeek()))	// Number must have digit after sign
unknown's avatar
unknown committed
634 635
	  {
	    yySkip();
636
	    while (my_isdigit(cs,yyGet())) ;
unknown's avatar
unknown committed
637 638 639 640 641 642 643 644 645
	    yylval->lex_str=get_token(lex,yyLength());
	    return(FLOAT_NUM);
	  }
	}
	yyUnget(); /* purecov: inspected */
      }
      else if (c == 'x' && (lex->ptr - lex->tok_start) == 2 &&
	  lex->tok_start[0] == '0' )
      {						// Varbinary
646
	while (my_isxdigit(cs,(c = yyGet()))) ;
unknown's avatar
unknown committed
647
	if ((lex->ptr - lex->tok_start) >= 4 && !ident_map[c])
unknown's avatar
unknown committed
648 649
	{
	  yylval->lex_str=get_token(lex,yyLength());
650
	  yylval->lex_str.str+=2;		// Skip 0x
unknown's avatar
unknown committed
651 652 653 654 655 656 657
	  yylval->lex_str.length-=2;
	  lex->yytoklen-=2;
	  return (HEX_NUM);
	}
	yyUnget();
      }
      // fall through
658
    case MY_LEX_IDENT_START:			// We come here after '.'
659
      result_state= IDENT;
unknown's avatar
unknown committed
660
#if defined(USE_MB) && defined(USE_MB_IDENT)
661
      if (use_mb(cs))
unknown's avatar
unknown committed
662
      {
663
	result_state= IDENT_QUOTED;
unknown's avatar
unknown committed
664
        while (ident_map[c=yyGet()])
unknown's avatar
unknown committed
665
        {
666
          if (my_mbcharlen(cs, c) > 1)
unknown's avatar
unknown committed
667 668
          {
            int l;
669
            if ((l = my_ismbchar(cs,
unknown's avatar
unknown committed
670 671 672 673 674 675 676 677 678
                                 (const char *)lex->ptr-1,
                                 (const char *)lex->end_of_query)) == 0)
              break;
            lex->ptr += l-1;
          }
        }
      }
      else
#endif
679 680 681 682 683 684
        while (ident_map[c = yyGet()])
	{
	  /* If not simple character, mark that we must convert it */
	  if (!bin_ident_map[c])
	    result_state= IDENT_QUOTED;
	}
unknown's avatar
unknown committed
685
      if (c == '.' && ident_map[yyPeek()])
686
	lex->next_state=MY_LEX_IDENT_SEP;// Next is '.'
unknown's avatar
unknown committed
687

688 689
      yylval->lex_str= get_token(lex,yyLength());
      return(result_state);
unknown's avatar
unknown committed
690

691
    case MY_LEX_USER_VARIABLE_DELIMITER:	// Found quote char
692
    {
693 694
      uint double_quotes= 0;
      char quote_char= c;                       // Used char
unknown's avatar
unknown committed
695
      lex->tok_start=lex->ptr;			// Skip first `
696
      while ((c=yyGet()))
unknown's avatar
unknown committed
697
      {
698 699
	int length;
	if ((length= my_mbcharlen(cs, c)) == 1)
700
	{
701 702
	  if (c == (uchar) NAMES_SEP_CHAR)
	    break; /* Old .frm format can't handle this char */
703 704 705 706 707 708 709 710 711
	  if (c == quote_char)
	  {
	    if (yyPeek() != quote_char)
	      break;
	    c=yyGet();
	    double_quotes++;
	    continue;
	  }
	}
712
#ifdef USE_MB
713 714 715
	else if (length < 1)
	  break;				// Error
	lex->ptr+= length-1;
716
#endif
unknown's avatar
unknown committed
717
      }
718 719 720 721 722 723
      if (double_quotes)
	yylval->lex_str=get_quoted_token(lex,yyLength() - double_quotes,
					 quote_char);
      else
	yylval->lex_str=get_token(lex,yyLength());
      if (c == quote_char)
724
	yySkip();			// Skip end `
725
      lex->next_state= MY_LEX_START;
726
      return(IDENT_QUOTED);
727
    }
728
    case MY_LEX_INT_OR_REAL:		// Compleat int or incompleat real
unknown's avatar
unknown committed
729 730 731 732 733 734
      if (c != '.')
      {					// Found complete integer number.
	yylval->lex_str=get_token(lex,yyLength());
	return int_token(yylval->lex_str.str,yylval->lex_str.length);
      }
      // fall through
735 736
    case MY_LEX_REAL:			// Incomplete real number
      while (my_isdigit(cs,c = yyGet())) ;
unknown's avatar
unknown committed
737 738 739 740

      if (c == 'e' || c == 'E')
      {
	c = yyGet();
unknown's avatar
unknown committed
741
	if (c == '-' || c == '+')
742
	  c = yyGet();			// Skip sign
743
	if (!my_isdigit(cs,c))
unknown's avatar
unknown committed
744
	{				// No digit after sign
745
	  state= MY_LEX_CHAR;
unknown's avatar
unknown committed
746 747
	  break;
	}
748
	while (my_isdigit(cs,yyGet())) ;
unknown's avatar
unknown committed
749 750 751 752 753 754
	yylval->lex_str=get_token(lex,yyLength());
	return(FLOAT_NUM);
      }
      yylval->lex_str=get_token(lex,yyLength());
      return(REAL_NUM);

755
    case MY_LEX_HEX_NUMBER:		// Found x'hexstring'
756
      yyGet();				// Skip '
757
      while (my_isxdigit(cs,(c = yyGet()))) ;
758 759 760 761 762 763 764 765 766 767 768 769
      length=(lex->ptr - lex->tok_start);	// Length of hexnum+3
      if (!(length & 1) || c != '\'')
      {
	return(ABORT_SYM);		// Illegal hex constant
      }
      yyGet();				// get_token makes an unget
      yylval->lex_str=get_token(lex,length);
      yylval->lex_str.str+=2;		// Skip x'
      yylval->lex_str.length-=3;	// Don't count x' and last '
      lex->yytoklen-=3;
      return (HEX_NUM);

770 771 772
    case MY_LEX_CMP_OP:			// Incomplete comparison operator
      if (state_map[yyPeek()] == MY_LEX_CMP_OP ||
	  state_map[yyPeek()] == MY_LEX_LONG_CMP_OP)
unknown's avatar
unknown committed
773 774 775
	yySkip();
      if ((tokval = find_keyword(lex,(uint) (lex->ptr - lex->tok_start),0)))
      {
776
	lex->next_state= MY_LEX_START;	// Allow signed numbers
unknown's avatar
unknown committed
777 778
	return(tokval);
      }
779
      state = MY_LEX_CHAR;		// Something fishy found
unknown's avatar
unknown committed
780 781
      break;

782 783 784
    case MY_LEX_LONG_CMP_OP:		// Incomplete comparison operator
      if (state_map[yyPeek()] == MY_LEX_CMP_OP ||
	  state_map[yyPeek()] == MY_LEX_LONG_CMP_OP)
unknown's avatar
unknown committed
785 786
      {
	yySkip();
787
	if (state_map[yyPeek()] == MY_LEX_CMP_OP)
unknown's avatar
unknown committed
788 789 790 791
	  yySkip();
      }
      if ((tokval = find_keyword(lex,(uint) (lex->ptr - lex->tok_start),0)))
      {
792
	lex->next_state= MY_LEX_START;	// Found long op
unknown's avatar
unknown committed
793 794
	return(tokval);
      }
795
      state = MY_LEX_CHAR;		// Something fishy found
unknown's avatar
unknown committed
796 797
      break;

798
    case MY_LEX_BOOL:
unknown's avatar
unknown committed
799 800
      if (c != yyPeek())
      {
801
	state=MY_LEX_CHAR;
unknown's avatar
unknown committed
802 803 804 805
	break;
      }
      yySkip();
      tokval = find_keyword(lex,2,0);	// Is a bool operator
806
      lex->next_state= MY_LEX_START;	// Allow signed numbers
unknown's avatar
unknown committed
807 808
      return(tokval);

809
    case MY_LEX_STRING_OR_DELIMITER:
810 811
      if (((THD *) yythd)->variables.sql_mode & MODE_ANSI_QUOTES)
      {
812
	state= MY_LEX_USER_VARIABLE_DELIMITER;
813 814 815
	break;
      }
      /* " used for strings */
816
    case MY_LEX_STRING:			// Incomplete text string
unknown's avatar
unknown committed
817 818
      if (!(yylval->lex_str.str = get_text(lex)))
      {
819
	state= MY_LEX_CHAR;		// Read char by char
unknown's avatar
unknown committed
820 821 822 823 824
	break;
      }
      yylval->lex_str.length=lex->yytoklen;
      return(TEXT_STRING);

825
    case MY_LEX_COMMENT:			//  Comment
unknown's avatar
unknown committed
826
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
unknown's avatar
unknown committed
827 828
      while ((c = yyGet()) != '\n' && c) ;
      yyUnget();			// Safety against eof
829
      state = MY_LEX_START;		// Try again
unknown's avatar
unknown committed
830
      break;
831
    case MY_LEX_LONG_COMMENT:		/* Long C comment? */
unknown's avatar
unknown committed
832 833
      if (yyPeek() != '*')
      {
834
	state=MY_LEX_CHAR;		// Probable division
unknown's avatar
unknown committed
835 836 837
	break;
      }
      yySkip();				// Skip '*'
unknown's avatar
unknown committed
838
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
unknown's avatar
unknown committed
839 840 841 842
      if (yyPeek() == '!')		// MySQL command in comment
      {
	ulong version=MYSQL_VERSION_ID;
	yySkip();
843 844
	state=MY_LEX_START;
	if (my_isdigit(cs,yyPeek()))
unknown's avatar
unknown committed
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
	{				// Version number
	  version=strtol((char*) lex->ptr,(char**) &lex->ptr,10);
	}
	if (version <= MYSQL_VERSION_ID)
	{
	  lex->in_comment=1;
	  break;
	}
      }
      while (lex->ptr != lex->end_of_query &&
	     ((c=yyGet()) != '*' || yyPeek() != '/'))
      {
	if (c == '\n')
	  lex->yylineno++;
      }
      if (lex->ptr != lex->end_of_query)
	yySkip();			// remove last '/'
862
      state = MY_LEX_START;		// Try again
unknown's avatar
unknown committed
863
      break;
864
    case MY_LEX_END_LONG_COMMENT:
unknown's avatar
unknown committed
865 866 867 868
      if (lex->in_comment && yyPeek() == '/')
      {
	yySkip();
	lex->in_comment=0;
869
	state=MY_LEX_START;
unknown's avatar
unknown committed
870 871
      }
      else
872
	state=MY_LEX_CHAR;		// Return '*'
unknown's avatar
unknown committed
873
      break;
874
    case MY_LEX_SET_VAR:		// Check if ':='
unknown's avatar
unknown committed
875 876
      if (yyPeek() != '=')
      {
877
	state=MY_LEX_CHAR;		// Return ':'
unknown's avatar
unknown committed
878 879 880 881
	break;
      }
      yySkip();
      return (SET_VAR);
882
    case MY_LEX_SEMICOLON:			// optional line terminator
unknown's avatar
unknown committed
883 884
      if (yyPeek())
      {
885 886 887
        THD* thd= (THD*)yythd;
        if ((thd->client_capabilities & CLIENT_MULTI_STATEMENTS) && 
            (thd->command != COM_PREPARE))
888 889
        {
          lex->found_colon=(char*)lex->ptr;
890
          thd->server_status |= SERVER_MORE_RESULTS_EXISTS;
891
          lex->next_state=MY_LEX_END;
892 893 894
          return(END_OF_INPUT);
        }
        else
895
 	  state=MY_LEX_CHAR;		// Return ';'
unknown's avatar
unknown committed
896 897 898
	break;
      }
      /* fall true */
899
    case MY_LEX_EOL:
unknown's avatar
unknown committed
900 901 902 903 904 905 906
      if (lex->ptr >= lex->end_of_query)
      {
	lex->next_state=MY_LEX_END;	// Mark for next loop
	return(END_OF_INPUT);
      }
      state=MY_LEX_CHAR;
      break;
907 908
    case MY_LEX_END:
      lex->next_state=MY_LEX_END;
unknown's avatar
unknown committed
909
      return(0);			// We found end of input last time
910 911
      
      /* Actually real shouldn't start with . but allow them anyhow */
912 913 914
    case MY_LEX_REAL_OR_POINT:
      if (my_isdigit(cs,yyPeek()))
	state = MY_LEX_REAL;		// Real
unknown's avatar
unknown committed
915 916
      else
      {
917 918
	state= MY_LEX_IDENT_SEP;	// return '.'
	yyUnget();			// Put back '.'
unknown's avatar
unknown committed
919 920
      }
      break;
921
    case MY_LEX_USER_END:		// end '@' of user@hostname
unknown's avatar
unknown committed
922
      switch (state_map[yyPeek()]) {
923 924 925
      case MY_LEX_STRING:
      case MY_LEX_USER_VARIABLE_DELIMITER:
      case MY_LEX_STRING_OR_DELIMITER:
unknown's avatar
unknown committed
926
	break;
927 928
      case MY_LEX_USER_END:
	lex->next_state=MY_LEX_SYSTEM_VAR;
unknown's avatar
unknown committed
929 930
	break;
      default:
931
	lex->next_state=MY_LEX_HOSTNAME;
unknown's avatar
unknown committed
932 933
	break;
      }
unknown's avatar
unknown committed
934 935 936
      yylval->lex_str.str=(char*) lex->ptr;
      yylval->lex_str.length=1;
      return((int) '@');
937 938 939
    case MY_LEX_HOSTNAME:		// end '@' of user@hostname
      for (c=yyGet() ; 
	   my_isalnum(cs,c) || c == '.' || c == '_' ||  c == '$';
unknown's avatar
unknown committed
940 941 942
	   c= yyGet()) ;
      yylval->lex_str=get_token(lex,yyLength());
      return(LEX_HOSTNAME);
943
    case MY_LEX_SYSTEM_VAR:
unknown's avatar
unknown committed
944 945 946
      yylval->lex_str.str=(char*) lex->ptr;
      yylval->lex_str.length=1;
      yySkip();					// Skip '@'
947 948 949 950
      lex->next_state= (state_map[yyPeek()] ==
			MY_LEX_USER_VARIABLE_DELIMITER ?
			MY_LEX_OPERATOR_OR_IDENT :
			MY_LEX_IDENT_OR_KEYWORD);
unknown's avatar
unknown committed
951
      return((int) '@');
952
    case MY_LEX_IDENT_OR_KEYWORD:
unknown's avatar
unknown committed
953 954 955 956 957
      /*
	We come here when we have found two '@' in a row.
	We should now be able to handle:
	[(global | local | session) .]variable_name
      */
958 959 960 961 962 963 964
      result_state= IDENT;
      while (ident_map[c=yyGet()])
      {
	/* If not simple character, mark that we must convert it */
	if (!bin_ident_map[c])
	  result_state= IDENT_QUOTED;
      }
unknown's avatar
unknown committed
965
      if (c == '.')
966
	lex->next_state=MY_LEX_IDENT_SEP;
unknown's avatar
unknown committed
967 968 969 970 971 972 973
      length= (uint) (lex->ptr - lex->tok_start)-1;
      if ((tokval= find_keyword(lex,length,0)))
      {
	yyUnget();				// Put back 'c'
	return(tokval);				// Was keyword
      }
      yylval->lex_str=get_token(lex,length);
974
      return(result_state);
unknown's avatar
unknown committed
975 976 977
    }
  }
}
unknown's avatar
unknown committed
978 979 980 981 982 983 984

/*
  st_select_lex structures initialisations
*/

void st_select_lex_node::init_query()
{
985 986
  options= 0;
  linkage= UNSPECIFIED_TYPE;
987 988
  no_error= no_table_names_allowed= 0;
  uncacheable= 0;
unknown's avatar
unknown committed
989 990 991 992 993 994 995 996 997
}

void st_select_lex_node::init_select()
{
}

void st_select_lex_unit::init_query()
{
  st_select_lex_node::init_query();
998
  linkage= GLOBAL_OPTIONS_TYPE;
unknown's avatar
unknown committed
999
  global_parameters= first_select();
1000 1001
  select_limit_cnt= HA_POS_ERROR;
  offset_limit_cnt= 0;
1002
  union_distinct= 0;
unknown's avatar
unknown committed
1003
  prepared= optimized= executed= 0;
unknown's avatar
unknown committed
1004
  item= 0;
1005 1006
  union_result= 0;
  table= 0;
unknown's avatar
unknown committed
1007
  fake_select_lex= 0;
1008
  cleaned= 0;
1009
  item_list.empty();
1010
  describe= 0;
unknown's avatar
unknown committed
1011 1012 1013 1014 1015
}

void st_select_lex::init_query()
{
  st_select_lex_node::init_query();
1016
  table_list.empty();
unknown's avatar
unknown committed
1017
  item_list.empty();
unknown's avatar
unknown committed
1018
  join= 0;
1019
  where= 0;
1020
  olap= UNSPECIFIED_OLAP_TYPE;
1021 1022
  having_fix_field= 0;
  resolve_mode= NOMATTER_MODE;
unknown's avatar
unknown committed
1023 1024
  cond_count= with_wild= 0;
  ref_pointer_array= 0;
unknown's avatar
unknown committed
1025
  select_n_having_items= 0;
1026
  prep_where= 0;
1027
  explicit_limit= 0;
unknown's avatar
unknown committed
1028 1029 1030 1031 1032
}

void st_select_lex::init_select()
{
  st_select_lex_node::init_select();
1033 1034 1035 1036 1037 1038
  group_list.empty();
  type= db= db1= table1= db2= table2= 0;
  having= 0;
  use_index_ptr= ignore_index_ptr= 0;
  table_join_options= 0;
  in_sum_expr= with_wild= 0;
unknown's avatar
unknown committed
1039
  options= 0;
1040
  braces= 0;
unknown's avatar
unknown committed
1041 1042 1043 1044
  when_list.empty(); 
  expr_list.empty();
  interval_list.empty(); 
  use_index.empty();
unknown's avatar
unknown committed
1045 1046
  ftfunc_list_alloc.empty();
  ftfunc_list= &ftfunc_list_alloc;
unknown's avatar
unknown committed
1047
  linkage= UNSPECIFIED_TYPE;
unknown's avatar
unknown committed
1048 1049 1050 1051 1052 1053 1054
  order_list.elements= 0;
  order_list.first= 0;
  order_list.next= (byte**) &order_list.first;
  select_limit= HA_POS_ERROR;
  offset_limit= 0;
  with_sum_func= 0;
  parsing_place= SELECT_LEX_NODE::NO_MATTER;
unknown's avatar
unknown committed
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
}

/*
  st_select_lex structures linking
*/

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

unknown's avatar
unknown committed
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
/*
  include on level down (but do not link)
  
  SYNOPSYS
    st_select_lex_node::include_standalone()
    upper - reference on node underr which this node should be included
    ref - references on reference on this node
*/
void st_select_lex_node::include_standalone(st_select_lex_node *upper,
					    st_select_lex_node **ref)
{
  next= 0;
  prev= ref;
  master= upper;
  slave= 0;
}

unknown's avatar
unknown committed
1089 1090 1091 1092 1093 1094 1095 1096
/* include neighbour (on same level) */
void st_select_lex_node::include_neighbour(st_select_lex_node *before)
{
  if ((next= before->next))
    next->prev= &next;
  prev= &before->next;
  before->next= this;
  master= before->master;
unknown's avatar
unknown committed
1097
  slave= 0;
unknown's avatar
unknown committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
}

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

//excluding from global list (internal function)
void st_select_lex_node::fast_exclude()
{
unknown's avatar
unknown committed
1112
  if (link_prev)
unknown's avatar
unknown committed
1113 1114 1115 1116
  {
    if ((*link_prev= link_next))
      link_next->link_prev= link_prev;
  }
1117 1118 1119 1120
  // Remove slave structure
  for (; slave; slave= slave->next)
    slave->fast_exclude();
  
unknown's avatar
unknown committed
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
}

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

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151

/*
  Exclude level of current unit from tree of SELECTs

  SYNOPSYS
    st_select_lex_unit::exclude_level()

  NOTE: units which belong to current will be brought up on level of
  currernt unit 
*/
unknown's avatar
unknown committed
1152 1153 1154
void st_select_lex_unit::exclude_level()
{
  SELECT_LEX_UNIT *units= 0, **units_last= &units;
unknown's avatar
unknown committed
1155
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
unknown's avatar
unknown committed
1156
  {
unknown's avatar
unknown committed
1157
    // unlink current level from global SELECTs list
unknown's avatar
unknown committed
1158 1159
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
      sl->link_next->link_prev= sl->link_prev;
unknown's avatar
unknown committed
1160 1161

    // bring up underlay levels
unknown's avatar
unknown committed
1162 1163
    SELECT_LEX_UNIT **last= 0;
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
unknown's avatar
unknown committed
1164 1165
    {
      u->master= master;
unknown's avatar
unknown committed
1166
      last= (SELECT_LEX_UNIT**)&(u->next);
unknown's avatar
unknown committed
1167
    }
unknown's avatar
unknown committed
1168 1169 1170 1171 1172 1173 1174 1175
    if (last)
    {
      (*units_last)= sl->first_inner_unit();
      units_last= last;
    }
  }
  if (units)
  {
unknown's avatar
unknown committed
1176
    // include brought up levels in place of current
unknown's avatar
unknown committed
1177 1178
    (*prev)= units;
    (*units_last)= (SELECT_LEX_UNIT*)next;
unknown's avatar
unknown committed
1179 1180 1181
    if (next)
      next->prev= (SELECT_LEX_NODE**)units_last;
    units->prev= prev;
unknown's avatar
unknown committed
1182 1183
  }
  else
unknown's avatar
unknown committed
1184 1185
  {
    // exclude currect unit from list of nodes
unknown's avatar
unknown committed
1186
    (*prev)= next;
unknown's avatar
unknown committed
1187 1188 1189
    if (next)
      next->prev= prev;
  }
unknown's avatar
unknown committed
1190 1191
}

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202

/*
  Exclude subtree of current unit from tree of SELECTs

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

unknown's avatar
unknown committed
1207
    // unlink underlay levels
1208 1209 1210 1211 1212
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
    {
      u->exclude_level();
    }
  }
unknown's avatar
unknown committed
1213
  // exclude currect unit from list of nodes
1214
  (*prev)= next;
unknown's avatar
unknown committed
1215 1216
  if (next)
    next->prev= prev;
1217 1218 1219
}


unknown's avatar
unknown committed
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
/*
  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
*/

unknown's avatar
unknown committed
1232
void st_select_lex::mark_as_dependent(SELECT_LEX *last)
unknown's avatar
unknown committed
1233 1234 1235 1236 1237
{
  /*
    Mark all selects from resolved to 1 before select where was
    found table as depended (of select where was found table)
  */
unknown's avatar
unknown committed
1238
  for (SELECT_LEX *s= this;
1239
       s && s != last;
unknown's avatar
unknown committed
1240
       s= s->outer_select())
1241
    if (!(s->uncacheable & UNCACHEABLE_DEPENDENT))
unknown's avatar
unknown committed
1242 1243
    {
      // Select is dependent of outer select
1244
      s->uncacheable|= UNCACHEABLE_DEPENDENT;
1245
      SELECT_LEX_UNIT *munit= s->master_unit();
1246
      munit->uncacheable|= UNCACHEABLE_DEPENDENT;
unknown's avatar
unknown committed
1247 1248 1249
    }
}

1250 1251 1252 1253 1254 1255 1256
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; }
List<String>* st_select_lex_node::get_use_index()    { return 0; }
List<String>* st_select_lex_node::get_ignore_index() { return 0; }
unknown's avatar
unknown committed
1257
TABLE_LIST *st_select_lex_node::add_table_to_list(THD *thd, Table_ident *table,
1258
						  LEX_STRING *alias,
unknown's avatar
unknown committed
1259
						  ulong table_join_options,
1260 1261
						  thr_lock_type flags,
						  List<String> *use_index,
unknown's avatar
unknown committed
1262 1263
						  List<String> *ignore_index,
                                                  LEX_STRING *option)
1264 1265 1266
{
  return 0;
}
unknown's avatar
unknown committed
1267 1268 1269 1270 1271 1272 1273 1274
ulong st_select_lex_node::get_table_join_options()
{
  return 0;
}

/*
  prohibit using LIMIT clause
*/
unknown's avatar
unknown committed
1275
bool st_select_lex::test_limit()
unknown's avatar
unknown committed
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
{
  if (select_limit != HA_POS_ERROR)
  {
    my_error(ER_NOT_SUPPORTED_YET, MYF(0),
         "LIMIT & IN/ALL/ANY/SOME subquery");
    return(1);
  }
  // We need only 1 row to determinate existence
  select_limit= 1;
  // no sense in ORDER BY without LIMIT
  order_list.empty();
  return(0);
}
1289

1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
/*  
  Interface method of table list creation for query
  
  SYNOPSIS
    st_select_lex_unit::create_total_list()
    thd            THD pointer
    result         pointer on result list of tables pointer
    check_derived  force derived table chacking (used for creating 
                   table list for derived query)
  DESCRIPTION
    This is used for UNION & subselect to create a new table list of all used 
    tables.
    The table_list->table entry in all used tables are set to point
    to the entries in this list.

  RETURN
    0 - OK
    !0 - error
*/
1309
bool st_select_lex_unit::create_total_list(THD *thd_arg, st_lex *lex,
1310
					   TABLE_LIST **result_arg)
1311
{
1312
  *result_arg= 0;
1313
  res= create_total_list_n_last_return(thd_arg, lex, &result_arg);
1314
  return res;
1315 1316
}

1317 1318 1319 1320 1321 1322 1323 1324
/*  
  Table list creation for query
  
  SYNOPSIS
    st_select_lex_unit::create_total_list()
    thd            THD pointer
    lex            pointer on LEX stricture
    result         pointer on pointer on result list of tables pointer
1325

1326 1327 1328
  DESCRIPTION
    This is used for UNION & subselect to create a new table list of all used 
    tables.
unknown's avatar
unknown committed
1329 1330
    The table_list->table_list in all tables of global list are set to point
    to the local SELECT_LEX entries.
1331 1332 1333 1334 1335

  RETURN
    0 - OK
    !0 - error
*/
1336 1337 1338
bool st_select_lex_unit::
create_total_list_n_last_return(THD *thd_arg,
				st_lex *lex,
1339
				TABLE_LIST ***result_arg)
1340 1341
{
  TABLE_LIST *slave_list_first=0, **slave_list_last= &slave_list_first;
1342
  TABLE_LIST **new_table_list= *result_arg, *aux;
1343
  SELECT_LEX *sl= (SELECT_LEX*)slave;
unknown's avatar
unknown committed
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
  
  /*
    iterate all inner selects + fake_select (if exists),
    fake_select->next_select() always is 0
  */
  for (;
       sl;
       sl= (sl->next_select() ?
	    sl->next_select() :
	    (sl == fake_select_lex ?
	     0 :
	     fake_select_lex)))
1356 1357
  {
    // check usage of ORDER BY in union
unknown's avatar
unknown committed
1358 1359
    if (sl->order_list.first && sl->next_select() && !sl->braces &&
	sl->linkage != GLOBAL_OPTIONS_TYPE)
1360
    {
1361
      net_printf(thd_arg,ER_WRONG_USAGE,"UNION","ORDER BY");
1362 1363
      return 1;
    }
unknown's avatar
unknown committed
1364

1365 1366 1367
    for (SELECT_LEX_UNIT *inner=  sl->first_inner_unit();
	 inner;
	 inner= inner->next_unit())
unknown's avatar
unknown committed
1368
    {
1369
      if (inner->create_total_list_n_last_return(thd, lex,
1370
						 &slave_list_last))
1371
	return 1;
unknown's avatar
unknown committed
1372 1373
    }

1374 1375
    if ((aux= (TABLE_LIST*) sl->table_list.first))
    {
1376 1377
      TABLE_LIST *next_table;
      for (; aux; aux= next_table)
1378 1379
      {
	TABLE_LIST *cursor;
1380
	next_table= aux->next;
unknown's avatar
unknown committed
1381
	/* Add to the total table list */
1382 1383
	if (!(cursor= (TABLE_LIST *) thd->memdup((char*) aux,
						 sizeof(*aux))))
1384
	{
1385 1386
	  send_error(thd,0);
	  return 1;
1387
	}
1388 1389 1390 1391
	*new_table_list= cursor;
	cursor->table_list= aux;
	new_table_list= &cursor->next;
	*new_table_list= 0;			// end result list
1392 1393 1394 1395
	aux->table_list= cursor;
      }
    }
  }
unknown's avatar
unknown committed
1396

1397 1398 1399 1400 1401
  if (slave_list_first)
  {
    *new_table_list= slave_list_first;
    new_table_list= slave_list_last;
  }
1402
  *result_arg= new_table_list;
1403 1404
  return 0;
}
1405

1406

1407 1408 1409 1410 1411
st_select_lex_unit* st_select_lex_unit::master_unit()
{
    return this;
}

1412

1413 1414 1415 1416 1417
st_select_lex* st_select_lex_unit::outer_select()
{
  return (st_select_lex*) master;
}

1418

unknown's avatar
unknown committed
1419
bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
unknown's avatar
unknown committed
1420
{
unknown's avatar
unknown committed
1421
  return add_to_list(thd, order_list, item, asc);
unknown's avatar
unknown committed
1422
}
1423

1424

unknown's avatar
unknown committed
1425
bool st_select_lex::add_item_to_list(THD *thd, Item *item)
1426 1427 1428 1429
{
  return item_list.push_back(item);
}

1430

unknown's avatar
unknown committed
1431
bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
1432
{
unknown's avatar
unknown committed
1433
  return add_to_list(thd, group_list, item, asc);
1434 1435
}

1436

1437 1438 1439 1440 1441
bool st_select_lex::add_ftfunc_to_list(Item_func_match *func)
{
  return !func || ftfunc_list->push_back(func); // end of memory?
}

1442

1443 1444 1445 1446 1447
st_select_lex_unit* st_select_lex::master_unit()
{
  return (st_select_lex_unit*) master;
}

1448

1449 1450 1451 1452 1453
st_select_lex* st_select_lex::outer_select()
{
  return (st_select_lex*) master->get_master();
}

1454

1455 1456 1457 1458 1459 1460
bool st_select_lex::set_braces(bool value)
{
  braces= value;
  return 0; 
}

1461

1462 1463 1464 1465 1466 1467
bool st_select_lex::inc_in_sum_expr()
{
  in_sum_expr++;
  return 0;
}

1468

1469 1470 1471 1472 1473
uint st_select_lex::get_in_sum_expr()
{
  return in_sum_expr;
}

1474

1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
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;
}

1485

1486 1487 1488 1489 1490
List<String>* st_select_lex::get_use_index()
{
  return use_index_ptr;
}

1491

1492 1493 1494 1495 1496
List<String>* st_select_lex::get_ignore_index()
{
  return ignore_index_ptr;
}

1497

unknown's avatar
unknown committed
1498 1499 1500 1501 1502
ulong st_select_lex::get_table_join_options()
{
  return table_join_options;
}

1503

unknown's avatar
unknown committed
1504 1505 1506 1507
bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
{
  if (ref_pointer_array)
    return 0;
1508 1509 1510 1511 1512 1513

  /*
    We have to create array in prepared statement memory if it is
    prepared statement
  */
  Statement *stmt= thd->current_statement ? thd->current_statement : thd;
unknown's avatar
unknown committed
1514
  return (ref_pointer_array= 
1515 1516 1517 1518
	  (Item **)stmt->alloc(sizeof(Item*) *
			       (item_list.elements +
				select_n_having_items +
				order_group_num)* 5)) == 0;
unknown's avatar
unknown committed
1519 1520
}

1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535

/*
  Find db.table which will be updated in this unit

  SYNOPSIS
    st_select_lex_unit::check_updateable()
    db		- data base name
    table	- real table name

  RETURN
    1 - found
    0 - OK (table did not found)
*/
bool st_select_lex_unit::check_updateable(char *db, char *table)
{
1536
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
    if (sl->check_updateable(db, table))
      return 1;
  return 0;
}


/*
  Find db.table which will be updated in this select and 
  underlayed ones (except derived tables)

  SYNOPSIS
    st_select_lex::check_updateable()
    db		- data base name
    table	- real table name

  RETURN
    1 - found
    0 - OK (table did not found)
*/
bool st_select_lex::check_updateable(char *db, char *table)
{
  if (find_real_table_in_list(get_table_list(), db, table))
    return 1;

  for (SELECT_LEX_UNIT *un= first_inner_unit();
       un;
       un= un->next_unit())
  {
    if (un->first_select()->linkage != DERIVED_TABLE_TYPE &&
	un->check_updateable(db, table))
      return 1;
  }
  return 0;
}


unknown's avatar
unknown committed
1573 1574 1575 1576 1577 1578
void st_select_lex_unit::print(String *str)
{
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
  {
    if (sl != first_select())
    {
1579
      str->append(" union ", 7);
1580
      if (!union_distinct)
1581
	str->append("all ", 4);
unknown's avatar
unknown committed
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
    }
    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)
    {
1593
      str->append(" order by ", 10);
unknown's avatar
unknown committed
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
      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)
  {
    (*order->item)->print(str);
    if (!order->asc)
1609
      str->append(" desc", 5);
unknown's avatar
unknown committed
1610 1611 1612 1613 1614
    if (order->next)
      str->append(',');
  }
}
 
1615

unknown's avatar
unknown committed
1616 1617 1618 1619 1620
void st_select_lex::print_limit(THD *thd, String *str)
{
  if (!thd)
    thd= current_thd;

1621
  if (explicit_limit)
unknown's avatar
unknown committed
1622
  {
1623 1624 1625 1626 1627 1628
    str->append(" limit ", 7);
    char buff[20];
    // latin1 is good enough for numbers
    String st(buff, sizeof(buff),  &my_charset_latin1);
    st.set((ulonglong)select_limit, &my_charset_latin1);
    str->append(st);
unknown's avatar
unknown committed
1629 1630 1631
    if (offset_limit)
    {
      str->append(',');
1632 1633
      st.set((ulonglong)select_limit, &my_charset_latin1);
      str->append(st);
unknown's avatar
unknown committed
1634 1635 1636 1637
    }
  }
}

unknown's avatar
unknown committed
1638

1639
/*
unknown's avatar
unknown committed
1640 1641
  Unlink first table from global table list and first table from outer select
  list (lex->select_lex)
1642 1643 1644

  SYNOPSIS
    unlink_first_table()
unknown's avatar
unknown committed
1645 1646 1647 1648 1649 1650
    tables		Global table list
    global_first	Save first global table here
    local_first		Save first local table here

  NORES
   global_first & local_first are used to save result for link_first_table_back
1651 1652 1653

  RETURN
    global list without first table
unknown's avatar
unknown committed
1654

1655 1656 1657 1658 1659 1660 1661
*/
TABLE_LIST *st_lex::unlink_first_table(TABLE_LIST *tables,
				       TABLE_LIST **global_first,
				       TABLE_LIST **local_first)
{
  *global_first= tables;
  *local_first= (TABLE_LIST*)select_lex.table_list.first;
unknown's avatar
unknown committed
1662
  /*
unknown's avatar
unknown committed
1663
    Exclude from global table list
unknown's avatar
unknown committed
1664
  */
1665
  tables= tables->next;
unknown's avatar
unknown committed
1666 1667 1668
  /*
    and from local list if it is not the same
  */
unknown's avatar
unknown committed
1669
  select_lex.table_list.first= ((&select_lex != all_selects_list) ?
1670 1671
				(byte*) (*local_first)->next :
				(byte*) tables);
1672 1673 1674 1675
  (*global_first)->next= 0;
  return tables;
}

unknown's avatar
unknown committed
1676

1677
/*
unknown's avatar
unknown committed
1678
  Link table back that was unlinked with unlink_first_table()
1679 1680 1681

  SYNOPSIS
    link_first_table_back()
unknown's avatar
unknown committed
1682 1683 1684
    tables		Global table list
    global_first	Saved first global table
    local_first		Saved first local table
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699

  RETURN
    global list
*/
TABLE_LIST *st_lex::link_first_table_back(TABLE_LIST *tables,
					  TABLE_LIST *global_first,
					  TABLE_LIST *local_first)
{
  global_first->next= tables;
  if (&select_lex != all_selects_list)
  {
    /*
      we do not touch local table 'next' field => we need just
      put the table in the list
    */
1700
    select_lex.table_list.first= (byte*) local_first;
1701 1702
  }
  else
1703
    select_lex.table_list.first= (byte*) global_first;
unknown's avatar
unknown committed
1704
  return global_first;
1705 1706
}

unknown's avatar
unknown committed
1707 1708
/*
  There are st_select_lex::add_table_to_list & 
unknown's avatar
unknown committed
1709
  st_select_lex::set_lock_for_tables are in sql_parse.cc
unknown's avatar
unknown committed
1710 1711

  st_select_lex::print is in sql_select.h
unknown's avatar
unknown committed
1712 1713

  st_select_lex_unit::prepare, st_select_lex_unit::exec,
1714 1715
  st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
  st_select_lex_unit::change_result
unknown's avatar
unknown committed
1716
  are in sql_union.cc
unknown's avatar
unknown committed
1717
*/