~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2006 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
16
17
/* A lexical scanner on a temporary buffer with a yacc interface */
18
19
#define MYSQL_LEX 1
20
#include "mysql_priv.h"
21
#include "item_create.h"
212.5.17 by Monty Taylor
Moved queues and hash.
22
#include <mysys/hash.h>
1 by brian
clean slate
23
24
static int lex_one_token(void *arg, void *yythd);
25
26
/*
27
  We are using pointer to this variable for distinguishing between assignment
28
  to NEW row field (when parsing trigger definition) and structured variable.
29
*/
30
31
sys_var *trg_new_row_fake_var= (sys_var*) 0x01;
32
33
/**
34
  LEX_STRING constant for null-string to be used in parser and other places.
35
*/
36
const LEX_STRING null_lex_str= {NULL, 0};
37
38
/* Longest standard keyword name */
39
40
#define TOCK_NAME_LENGTH 24
41
42
/*
43
  The following data is based on the latin1 character set, and is only
44
  used when comparing keywords
45
*/
46
47
static uchar to_upper_lex[]=
48
{
49
    0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
50
   16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
51
   32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
52
   48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
53
   64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
54
   80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
55
   96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
56
   80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127,
57
  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
58
  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
59
  160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
60
  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
61
  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
62
  208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
63
  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
64
  208,209,210,211,212,213,214,247,216,217,218,219,220,221,222,255
65
};
66
67
/* 
68
  Names of the index hints (for error messages). Keep in sync with 
69
  index_hint_type 
70
*/
71
72
const char * index_hint_type_name[] =
73
{
74
  "IGNORE INDEX", 
75
  "USE INDEX", 
76
  "FORCE INDEX"
77
};
78
79
inline int lex_casecmp(const char *s, const char *t, uint len)
80
{
81
  while (len-- != 0 &&
82
	 to_upper_lex[(uchar) *s++] == to_upper_lex[(uchar) *t++]) ;
83
  return (int) len+1;
84
}
85
86
#include <lex_hash.h>
87
88
89
void lex_init(void)
90
{
91
  uint i;
92
  for (i=0 ; i < array_elements(symbols) ; i++)
93
    symbols[i].length=(uchar) strlen(symbols[i].name);
94
  for (i=0 ; i < array_elements(sql_functions) ; i++)
95
    sql_functions[i].length=(uchar) strlen(sql_functions[i].name);
96
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
97
  return;
1 by brian
clean slate
98
}
99
100
101
void lex_free(void)
102
{					// Call this when daemon ends
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
103
  return;
1 by brian
clean slate
104
}
105
106
107
void
108
st_parsing_options::reset()
109
{
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
110
  allows_variable= true;
111
  allows_select_into= true;
112
  allows_select_procedure= true;
113
  allows_derived= true;
1 by brian
clean slate
114
}
115
116
Lex_input_stream::Lex_input_stream(THD *thd,
117
                                   const char* buffer,
118
                                   unsigned int length)
119
: m_thd(thd),
120
  yylineno(1),
121
  yytoklen(0),
122
  yylval(NULL),
123
  lookahead_token(END_OF_INPUT),
124
  lookahead_yylval(NULL),
125
  m_ptr(buffer),
126
  m_tok_start(NULL),
127
  m_tok_end(NULL),
128
  m_end_of_query(buffer + length),
129
  m_tok_start_prev(NULL),
130
  m_buf(buffer),
131
  m_buf_length(length),
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
132
  m_echo(true),
1 by brian
clean slate
133
  m_cpp_tok_start(NULL),
134
  m_cpp_tok_start_prev(NULL),
135
  m_cpp_tok_end(NULL),
136
  m_body_utf8(NULL),
137
  m_cpp_utf8_processed_ptr(NULL),
138
  next_state(MY_LEX_START),
139
  found_semicolon(NULL),
140
  ignore_space(1),
141
  in_comment(NO_COMMENT),
142
  m_underscore_cs(NULL)
143
{
144
  m_cpp_buf= (char*) thd->alloc(length + 1);
145
  m_cpp_ptr= m_cpp_buf;
146
}
147
148
Lex_input_stream::~Lex_input_stream()
149
{}
150
151
/**
152
  The operation is called from the parser in order to
153
  1) designate the intention to have utf8 body;
154
  1) Indicate to the lexer that we will need a utf8 representation of this
155
     statement;
156
  2) Determine the beginning of the body.
157
158
  @param thd        Thread context.
159
  @param begin_ptr  Pointer to the start of the body in the pre-processed
160
                    buffer.
161
*/
162
163
void Lex_input_stream::body_utf8_start(THD *thd, const char *begin_ptr)
164
{
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
165
  assert(begin_ptr);
166
  assert(m_cpp_buf <= begin_ptr && begin_ptr <= m_cpp_buf + m_buf_length);
1 by brian
clean slate
167
168
  uint body_utf8_length=
169
    (m_buf_length / thd->variables.character_set_client->mbminlen) *
170
    my_charset_utf8_bin.mbmaxlen;
171
172
  m_body_utf8= (char *) thd->alloc(body_utf8_length + 1);
173
  m_body_utf8_ptr= m_body_utf8;
174
  *m_body_utf8_ptr= 0;
175
176
  m_cpp_utf8_processed_ptr= begin_ptr;
177
}
178
179
/**
180
  @brief The operation appends unprocessed part of pre-processed buffer till
181
  the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to end_ptr.
182
183
  The idea is that some tokens in the pre-processed buffer (like character
184
  set introducers) should be skipped.
185
186
  Example:
187
    CPP buffer: SELECT 'str1', _latin1 'str2';
188
    m_cpp_utf8_processed_ptr -- points at the "SELECT ...";
189
    In order to skip "_latin1", the following call should be made:
190
      body_utf8_append(<pointer to "_latin1 ...">, <pointer to " 'str2'...">)
191
192
  @param ptr      Pointer in the pre-processed buffer, which specifies the
193
                  end of the chunk, which should be appended to the utf8
194
                  body.
195
  @param end_ptr  Pointer in the pre-processed buffer, to which
196
                  m_cpp_utf8_processed_ptr will be set in the end of the
197
                  operation.
198
*/
199
200
void Lex_input_stream::body_utf8_append(const char *ptr,
201
                                        const char *end_ptr)
202
{
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
203
  assert(m_cpp_buf <= ptr && ptr <= m_cpp_buf + m_buf_length);
204
  assert(m_cpp_buf <= end_ptr && end_ptr <= m_cpp_buf + m_buf_length);
1 by brian
clean slate
205
206
  if (!m_body_utf8)
207
    return;
208
209
  if (m_cpp_utf8_processed_ptr >= ptr)
210
    return;
211
212
  int bytes_to_copy= ptr - m_cpp_utf8_processed_ptr;
213
214
  memcpy(m_body_utf8_ptr, m_cpp_utf8_processed_ptr, bytes_to_copy);
215
  m_body_utf8_ptr += bytes_to_copy;
216
  *m_body_utf8_ptr= 0;
217
218
  m_cpp_utf8_processed_ptr= end_ptr;
219
}
220
221
/**
222
  The operation appends unprocessed part of the pre-processed buffer till
223
  the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to ptr.
224
225
  @param ptr  Pointer in the pre-processed buffer, which specifies the end
226
              of the chunk, which should be appended to the utf8 body.
227
*/
228
229
void Lex_input_stream::body_utf8_append(const char *ptr)
230
{
231
  body_utf8_append(ptr, ptr);
232
}
233
234
/**
235
  The operation converts the specified text literal to the utf8 and appends
236
  the result to the utf8-body.
237
238
  @param thd      Thread context.
239
  @param txt      Text literal.
240
  @param txt_cs   Character set of the text literal.
241
  @param end_ptr  Pointer in the pre-processed buffer, to which
242
                  m_cpp_utf8_processed_ptr will be set in the end of the
243
                  operation.
244
*/
245
246
void Lex_input_stream::body_utf8_append_literal(THD *thd,
247
                                                const LEX_STRING *txt,
248
                                                CHARSET_INFO *txt_cs,
249
                                                const char *end_ptr)
250
{
251
  if (!m_cpp_utf8_processed_ptr)
252
    return;
253
254
  LEX_STRING utf_txt;
255
256
  if (!my_charset_same(txt_cs, &my_charset_utf8_general_ci))
257
  {
258
    thd->convert_string(&utf_txt,
259
                        &my_charset_utf8_general_ci,
260
                        txt->str, txt->length,
261
                        txt_cs);
262
  }
263
  else
264
  {
265
    utf_txt.str= txt->str;
266
    utf_txt.length= txt->length;
267
  }
268
269
  /* NOTE: utf_txt.length is in bytes, not in symbols. */
270
271
  memcpy(m_body_utf8_ptr, utf_txt.str, utf_txt.length);
272
  m_body_utf8_ptr += utf_txt.length;
273
  *m_body_utf8_ptr= 0;
274
275
  m_cpp_utf8_processed_ptr= end_ptr;
276
}
277
278
279
/*
280
  This is called before every query that is to be parsed.
281
  Because of this, it's critical to not do too much things here.
282
  (We already do too much here)
283
*/
284
285
void lex_start(THD *thd)
286
{
287
  LEX *lex= thd->lex;
288
289
  lex->thd= lex->unit.thd= thd;
290
291
  lex->context_stack.empty();
292
  lex->unit.init_query();
293
  lex->unit.init_select();
294
  /* 'parent_lex' is used in init_query() so it must be before it. */
295
  lex->select_lex.parent_lex= lex;
296
  lex->select_lex.init_query();
297
  lex->value_list.empty();
298
  lex->update_list.empty();
299
  lex->param_list.empty();
300
  lex->auxiliary_table_list.empty();
301
  lex->unit.next= lex->unit.master=
302
    lex->unit.link_next= lex->unit.return_to= 0;
303
  lex->unit.prev= lex->unit.link_prev= 0;
304
  lex->unit.slave= lex->unit.global_parameters= lex->current_select=
305
    lex->all_selects_list= &lex->select_lex;
306
  lex->select_lex.master= &lex->unit;
307
  lex->select_lex.prev= &lex->unit.slave;
308
  lex->select_lex.link_next= lex->select_lex.slave= lex->select_lex.next= 0;
309
  lex->select_lex.link_prev= (st_select_lex_node**)&(lex->all_selects_list);
310
  lex->select_lex.options= 0;
311
  lex->select_lex.init_order();
312
  lex->select_lex.group_list.empty();
313
  lex->describe= 0;
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
314
  lex->subqueries= false;
1 by brian
clean slate
315
  lex->derived_tables= 0;
316
  lex->lock_option= TL_READ;
317
  lex->leaf_tables_insert= 0;
318
  lex->parsing_options.reset();
319
  lex->empty_field_list_on_rset= 0;
320
  lex->select_lex.select_number= 1;
321
  lex->length=0;
322
  lex->select_lex.in_sum_expr=0;
323
  lex->select_lex.ftfunc_list_alloc.empty();
324
  lex->select_lex.ftfunc_list= &lex->select_lex.ftfunc_list_alloc;
325
  lex->select_lex.group_list.empty();
326
  lex->select_lex.order_list.empty();
327
  lex->sql_command= SQLCOM_END;
328
  lex->duplicates= DUP_ERROR;
329
  lex->ignore= 0;
330
  lex->proc_list.first= 0;
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
331
  lex->escape_used= false;
1 by brian
clean slate
332
  lex->query_tables= 0;
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
333
  lex->reset_query_tables_list(false);
334
  lex->expr_allows_subselect= true;
335
  lex->use_only_table_context= false;
1 by brian
clean slate
336
337
  lex->name.str= 0;
338
  lex->name.length= 0;
339
  lex->nest_level=0 ;
340
  lex->allow_sum_func= 0;
341
  lex->in_sum_func= NULL;
342
  /*
343
    ok, there must be a better solution for this, long-term
212.6.1 by Mats Kindahl
Replacing all bzero() calls with memset() calls and removing the bzero.c file.
344
    I tried "memset" in the sql_yacc.yy code, but that for
1 by brian
clean slate
345
    some reason made the values zero, even if they were set
346
  */
347
  lex->server_options.server_name= 0;
348
  lex->server_options.server_name_length= 0;
349
  lex->server_options.host= 0;
350
  lex->server_options.db= 0;
351
  lex->server_options.username= 0;
352
  lex->server_options.password= 0;
353
  lex->server_options.scheme= 0;
354
  lex->server_options.owner= 0;
355
  lex->server_options.port= -1;
356
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
357
  lex->is_lex_started= true;
358
  return;
1 by brian
clean slate
359
}
360
361
void lex_end(LEX *lex)
362
{
363
  if (lex->yacc_yyss)
364
  {
365
    my_free(lex->yacc_yyss, MYF(0));
366
    my_free(lex->yacc_yyvs, MYF(0));
367
    lex->yacc_yyss= 0;
368
    lex->yacc_yyvs= 0;
369
  }
370
371
  /* release used plugins */
372
  plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer, 
373
                     lex->plugins.elements);
374
  reset_dynamic(&lex->plugins);
375
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
376
  return;
1 by brian
clean slate
377
}
378
379
380
static int find_keyword(Lex_input_stream *lip, uint len, bool function)
381
{
382
  const char *tok= lip->get_tok_start();
383
384
  SYMBOL *symbol= get_hash_symbol(tok, len, function);
385
  if (symbol)
386
  {
387
    lip->yylval->symbol.symbol=symbol;
388
    lip->yylval->symbol.str= (char*) tok;
389
    lip->yylval->symbol.length=len;
390
391
    return symbol->tok;
392
  }
393
  return 0;
394
}
395
396
/*
397
  Check if name is a keyword
398
399
  SYNOPSIS
400
    is_keyword()
401
    name      checked name (must not be empty)
402
    len       length of checked name
403
404
  RETURN VALUES
405
    0         name is a keyword
406
    1         name isn't a keyword
407
*/
408
409
bool is_keyword(const char *name, uint len)
410
{
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
411
  assert(len != 0);
1 by brian
clean slate
412
  return get_hash_symbol(name,len,0)!=0;
413
}
414
415
bool is_lex_native_function(const LEX_STRING *name)
416
{
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
417
  assert(name != NULL);
1 by brian
clean slate
418
  return (get_hash_symbol(name->str, name->length, 1) != 0);
419
}
420
421
/* make a copy of token before ptr and set yytoklen */
422
423
static LEX_STRING get_token(Lex_input_stream *lip, uint skip, uint length)
424
{
425
  LEX_STRING tmp;
426
  lip->yyUnget();                       // ptr points now after last token char
427
  tmp.length=lip->yytoklen=length;
428
  tmp.str= lip->m_thd->strmake(lip->get_tok_start() + skip, tmp.length);
429
430
  lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
431
  lip->m_cpp_text_end= lip->m_cpp_text_start + tmp.length;
432
433
  return tmp;
434
}
435
436
/* 
437
 todo: 
438
   There are no dangerous charsets in mysql for function 
439
   get_quoted_token yet. But it should be fixed in the 
440
   future to operate multichar strings (like ucs2)
441
*/
442
443
static LEX_STRING get_quoted_token(Lex_input_stream *lip,
444
                                   uint skip,
445
                                   uint length, char quote)
446
{
447
  LEX_STRING tmp;
448
  const char *from, *end;
449
  char *to;
450
  lip->yyUnget();                       // ptr points now after last token char
451
  tmp.length= lip->yytoklen=length;
452
  tmp.str=(char*) lip->m_thd->alloc(tmp.length+1);
453
  from= lip->get_tok_start() + skip;
454
  to= tmp.str;
455
  end= to+length;
456
457
  lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
458
  lip->m_cpp_text_end= lip->m_cpp_text_start + length;
459
460
  for ( ; to != end; )
461
  {
462
    if ((*to++= *from++) == quote)
463
    {
464
      from++;					// Skip double quotes
465
      lip->m_cpp_text_start++;
466
    }
467
  }
468
  *to= 0;					// End null for safety
469
  return tmp;
470
}
471
472
473
/*
474
  Return an unescaped text literal without quotes
475
  Fix sometimes to do only one scan of the string
476
*/
477
478
static char *get_text(Lex_input_stream *lip, int pre_skip, int post_skip)
479
{
480
  register uchar c,sep;
481
  uint found_escape=0;
482
  CHARSET_INFO *cs= lip->m_thd->charset();
483
484
  lip->tok_bitmap= 0;
485
  sep= lip->yyGetLast();                        // String should end with this
486
  while (! lip->eof())
487
  {
488
    c= lip->yyGet();
489
    lip->tok_bitmap|= c;
490
#ifdef USE_MB
491
    {
492
      int l;
493
      if (use_mb(cs) &&
494
          (l = my_ismbchar(cs,
495
                           lip->get_ptr() -1,
496
                           lip->get_end_of_query()))) {
497
        lip->skip_binary(l-1);
498
        continue;
499
      }
500
    }
501
#endif
502
    if (c == '\\')
503
    {					// Escaped character
504
      found_escape=1;
505
      if (lip->eof())
506
	return 0;
507
      lip->yySkip();
508
    }
509
    else if (c == sep)
510
    {
511
      if (c == lip->yyGet())            // Check if two separators in a row
512
      {
513
        found_escape=1;                 // duplicate. Remember for delete
514
	continue;
515
      }
516
      else
517
        lip->yyUnget();
518
519
      /* Found end. Unescape and return string */
520
      const char *str, *end;
521
      char *start;
522
523
      str= lip->get_tok_start();
524
      end= lip->get_ptr();
525
      /* Extract the text from the token */
526
      str += pre_skip;
527
      end -= post_skip;
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
528
      assert(end >= str);
1 by brian
clean slate
529
530
      if (!(start= (char*) lip->m_thd->alloc((uint) (end-str)+1)))
531
	return (char*) "";		// Sql_alloc has set error flag
532
533
      lip->m_cpp_text_start= lip->get_cpp_tok_start() + pre_skip;
534
      lip->m_cpp_text_end= lip->get_cpp_ptr() - post_skip;
535
536
      if (!found_escape)
537
      {
538
	lip->yytoklen=(uint) (end-str);
539
	memcpy(start,str,lip->yytoklen);
540
	start[lip->yytoklen]=0;
541
      }
542
      else
543
      {
544
        char *to;
545
546
	for (to=start ; str != end ; str++)
547
	{
548
#ifdef USE_MB
549
	  int l;
550
	  if (use_mb(cs) &&
551
              (l = my_ismbchar(cs, str, end))) {
552
	      while (l--)
553
		  *to++ = *str++;
554
	      str--;
555
	      continue;
556
	  }
557
#endif
558
	  if (!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
559
              *str == '\\' && str+1 != end)
560
	  {
561
	    switch(*++str) {
562
	    case 'n':
563
	      *to++='\n';
564
	      break;
565
	    case 't':
566
	      *to++= '\t';
567
	      break;
568
	    case 'r':
569
	      *to++ = '\r';
570
	      break;
571
	    case 'b':
572
	      *to++ = '\b';
573
	      break;
574
	    case '0':
575
	      *to++= 0;			// Ascii null
576
	      break;
577
	    case 'Z':			// ^Z must be escaped on Win32
578
	      *to++='\032';
579
	      break;
580
	    case '_':
581
	    case '%':
582
	      *to++= '\\';		// remember prefix for wildcard
583
	      /* Fall through */
584
	    default:
585
              *to++= *str;
586
	      break;
587
	    }
588
	  }
589
	  else if (*str == sep)
590
	    *to++= *str++;		// Two ' or "
591
	  else
592
	    *to++ = *str;
593
	}
594
	*to=0;
595
	lip->yytoklen=(uint) (to-start);
596
      }
597
      return start;
598
    }
599
  }
600
  return 0;					// unexpected end of query
601
}
602
603
604
/*
152 by Brian Aker
longlong replacement
605
** Calc type of integer; long integer, int64_t integer or real.
1 by brian
clean slate
606
** Returns smallest type that match the string.
607
** When using unsigned long long values the result is converted to a real
608
** because else they will be unexpected sign changes because all calculation
152 by Brian Aker
longlong replacement
609
** is done with int64_t or double.
1 by brian
clean slate
610
*/
611
612
static const char *long_str="2147483647";
613
static const uint long_len=10;
614
static const char *signed_long_str="-2147483648";
152 by Brian Aker
longlong replacement
615
static const char *int64_t_str="9223372036854775807";
616
static const uint int64_t_len=19;
617
static const char *signed_int64_t_str="-9223372036854775808";
618
static const uint signed_int64_t_len=19;
619
static const char *unsigned_int64_t_str="18446744073709551615";
620
static const uint unsigned_int64_t_len=20;
1 by brian
clean slate
621
622
static inline uint int_token(const char *str,uint length)
623
{
624
  if (length < long_len)			// quick normal case
625
    return NUM;
626
  bool neg=0;
627
628
  if (*str == '+')				// Remove sign and pre-zeros
629
  {
630
    str++; length--;
631
  }
632
  else if (*str == '-')
633
  {
634
    str++; length--;
635
    neg=1;
636
  }
637
  while (*str == '0' && length)
638
  {
639
    str++; length --;
640
  }
641
  if (length < long_len)
642
    return NUM;
643
644
  uint smaller,bigger;
645
  const char *cmp;
646
  if (neg)
647
  {
648
    if (length == long_len)
649
    {
650
      cmp= signed_long_str+1;
651
      smaller=NUM;				// If <= signed_long_str
652
      bigger=LONG_NUM;				// If >= signed_long_str
653
    }
152 by Brian Aker
longlong replacement
654
    else if (length < signed_int64_t_len)
1 by brian
clean slate
655
      return LONG_NUM;
152 by Brian Aker
longlong replacement
656
    else if (length > signed_int64_t_len)
1 by brian
clean slate
657
      return DECIMAL_NUM;
658
    else
659
    {
152 by Brian Aker
longlong replacement
660
      cmp=signed_int64_t_str+1;
661
      smaller=LONG_NUM;				// If <= signed_int64_t_str
1 by brian
clean slate
662
      bigger=DECIMAL_NUM;
663
    }
664
  }
665
  else
666
  {
667
    if (length == long_len)
668
    {
669
      cmp= long_str;
670
      smaller=NUM;
671
      bigger=LONG_NUM;
672
    }
152 by Brian Aker
longlong replacement
673
    else if (length < int64_t_len)
1 by brian
clean slate
674
      return LONG_NUM;
152 by Brian Aker
longlong replacement
675
    else if (length > int64_t_len)
1 by brian
clean slate
676
    {
152 by Brian Aker
longlong replacement
677
      if (length > unsigned_int64_t_len)
1 by brian
clean slate
678
        return DECIMAL_NUM;
152 by Brian Aker
longlong replacement
679
      cmp=unsigned_int64_t_str;
1 by brian
clean slate
680
      smaller=ULONGLONG_NUM;
681
      bigger=DECIMAL_NUM;
682
    }
683
    else
684
    {
152 by Brian Aker
longlong replacement
685
      cmp=int64_t_str;
1 by brian
clean slate
686
      smaller=LONG_NUM;
687
      bigger= ULONGLONG_NUM;
688
    }
689
  }
690
  while (*cmp && *cmp++ == *str++) ;
691
  return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
692
}
693
694
695
/*
696
  MYSQLlex remember the following states from the following MYSQLlex()
697
698
  - MY_LEX_EOQ			Found end of query
699
  - MY_LEX_OPERATOR_OR_IDENT	Last state was an ident, text or number
700
				(which can't be followed by a signed number)
701
*/
702
703
int MYSQLlex(void *arg, void *yythd)
704
{
705
  THD *thd= (THD *)yythd;
706
  Lex_input_stream *lip= thd->m_lip;
707
  YYSTYPE *yylval=(YYSTYPE*) arg;
708
  int token;
709
710
  if (lip->lookahead_token != END_OF_INPUT)
711
  {
712
    /*
713
      The next token was already parsed in advance,
714
      return it.
715
    */
716
    token= lip->lookahead_token;
717
    lip->lookahead_token= END_OF_INPUT;
718
    *yylval= *(lip->lookahead_yylval);
719
    lip->lookahead_yylval= NULL;
720
    return token;
721
  }
722
723
  token= lex_one_token(arg, yythd);
724
725
  switch(token) {
726
  case WITH:
727
    /*
728
      Parsing 'WITH' 'ROLLUP' or 'WITH' 'CUBE' requires 2 look ups,
729
      which makes the grammar LALR(2).
730
      Replace by a single 'WITH_ROLLUP' or 'WITH_CUBE' token,
731
      to transform the grammar into a LALR(1) grammar,
732
      which sql_yacc.yy can process.
733
    */
734
    token= lex_one_token(arg, yythd);
735
    switch(token) {
736
    case CUBE_SYM:
737
      return WITH_CUBE_SYM;
738
    case ROLLUP_SYM:
739
      return WITH_ROLLUP_SYM;
740
    default:
741
      /*
742
        Save the token following 'WITH'
743
      */
744
      lip->lookahead_yylval= lip->yylval;
745
      lip->yylval= NULL;
746
      lip->lookahead_token= token;
747
      return WITH;
748
    }
749
    break;
750
  default:
751
    break;
752
  }
753
754
  return token;
755
}
756
757
int lex_one_token(void *arg, void *yythd)
758
{
759
  register unsigned char c= 0; /* Just set to shutup GCC */
760
  bool comment_closed;
761
  int	tokval, result_state;
762
  unsigned int length;
763
  enum my_lex_states state;
764
  THD *thd= (THD *)yythd;
765
  Lex_input_stream *lip= thd->m_lip;
766
  LEX *lex= thd->lex;
767
  YYSTYPE *yylval=(YYSTYPE*) arg;
768
  CHARSET_INFO *cs= thd->charset();
769
  uchar *state_map= cs->state_map;
770
  uchar *ident_map= cs->ident_map;
771
772
  lip->yylval=yylval;			// The global state
773
774
  lip->start_token();
775
  state=lip->next_state;
776
  lip->next_state=MY_LEX_OPERATOR_OR_IDENT;
777
  for (;;)
778
  {
779
    switch (state) {
780
    case MY_LEX_OPERATOR_OR_IDENT:	// Next is operator or keyword
781
    case MY_LEX_START:			// Start of token
782
      // Skip starting whitespace
783
      while(state_map[c= lip->yyPeek()] == MY_LEX_SKIP)
784
      {
785
	if (c == '\n')
786
	  lip->yylineno++;
787
788
        lip->yySkip();
789
      }
790
791
      /* Start of real token */
792
      lip->restart_token();
793
      c= lip->yyGet();
794
      state= (enum my_lex_states) state_map[c];
795
      break;
796
    case MY_LEX_ESCAPE:
797
      if (lip->yyGet() == 'N')
798
      {					// Allow \N as shortcut for NULL
799
	yylval->lex_str.str=(char*) "\\N";
800
	yylval->lex_str.length=2;
801
	return NULL_SYM;
802
      }
803
    case MY_LEX_CHAR:			// Unknown or single char token
804
    case MY_LEX_SKIP:			// This should not happen
805
      if (c == '-' && lip->yyPeek() == '-' &&
806
          (my_isspace(cs,lip->yyPeekn(1)) ||
807
           my_iscntrl(cs,lip->yyPeekn(1))))
808
      {
809
        state=MY_LEX_COMMENT;
810
        break;
811
      }
812
813
      if (c != ')')
814
	lip->next_state= MY_LEX_START;	// Allow signed numbers
815
816
      if (c == ',')
817
      {
818
        /*
819
          Warning:
820
          This is a work around, to make the "remember_name" rule in
821
          sql/sql_yacc.yy work properly.
822
          The problem is that, when parsing "select expr1, expr2",
823
          the code generated by bison executes the *pre* action
824
          remember_name (see select_item) *before* actually parsing the
825
          first token of expr2.
826
        */
827
        lip->restart_token();
828
      }
829
830
      return((int) c);
831
832
    case MY_LEX_IDENT_OR_HEX:
833
      if (lip->yyPeek() == '\'')
834
      {					// Found x'hex-number'
835
	state= MY_LEX_HEX_NUMBER;
836
	break;
837
      }
838
    case MY_LEX_IDENT_OR_BIN:
839
      if (lip->yyPeek() == '\'')
840
      {                                 // Found b'bin-number'
841
        state= MY_LEX_BIN_NUMBER;
842
        break;
843
      }
844
    case MY_LEX_IDENT:
845
      const char *start;
846
#if defined(USE_MB) && defined(USE_MB_IDENT)
847
      if (use_mb(cs))
848
      {
849
	result_state= IDENT_QUOTED;
850
        if (my_mbcharlen(cs, lip->yyGetLast()) > 1)
851
        {
852
          int l = my_ismbchar(cs,
853
                              lip->get_ptr() -1,
854
                              lip->get_end_of_query());
855
          if (l == 0) {
856
            state = MY_LEX_CHAR;
857
            continue;
858
          }
859
          lip->skip_binary(l - 1);
860
        }
861
        while (ident_map[c=lip->yyGet()])
862
        {
863
          if (my_mbcharlen(cs, c) > 1)
864
          {
865
            int l;
866
            if ((l = my_ismbchar(cs,
867
                                 lip->get_ptr() -1,
868
                                 lip->get_end_of_query())) == 0)
869
              break;
870
            lip->skip_binary(l-1);
871
          }
872
        }
873
      }
874
      else
875
#endif
876
      {
877
        for (result_state= c; ident_map[c= lip->yyGet()]; result_state|= c) {};
878
        /* If there were non-ASCII characters, mark that we must convert */
879
        result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
880
      }
881
      length= lip->yyLength();
882
      start= lip->get_ptr();
883
      if (lip->ignore_space)
884
      {
885
        /*
886
          If we find a space then this can't be an identifier. We notice this
887
          below by checking start != lex->ptr.
888
        */
889
        for (; state_map[c] == MY_LEX_SKIP ; c= lip->yyGet()) {};
890
      }
891
      if (start == lip->get_ptr() && c == '.' && ident_map[(uint8_t)lip->yyPeek()])
892
	lip->next_state=MY_LEX_IDENT_SEP;
893
      else
894
      {					// '(' must follow directly if function
895
        lip->yyUnget();
896
	if ((tokval = find_keyword(lip, length, c == '(')))
897
	{
898
	  lip->next_state= MY_LEX_START;	// Allow signed numbers
899
	  return(tokval);		// Was keyword
900
	}
901
        lip->yySkip();                  // next state does a unget
902
      }
903
      yylval->lex_str=get_token(lip, 0, length);
904
905
      /*
906
         Note: "SELECT _bla AS 'alias'"
907
         _bla should be considered as a IDENT if charset haven't been found.
908
         So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
909
         producing an error.
910
      */
911
912
      if (yylval->lex_str.str[0] == '_')
913
      {
914
        CHARSET_INFO *cs= get_charset_by_csname(yylval->lex_str.str + 1,
915
                                                MY_CS_PRIMARY, MYF(0));
916
        if (cs)
917
        {
918
          yylval->charset= cs;
919
          lip->m_underscore_cs= cs;
920
921
          lip->body_utf8_append(lip->m_cpp_text_start,
922
                                lip->get_cpp_tok_start() + length);
923
          return(UNDERSCORE_CHARSET);
924
        }
925
      }
926
927
      lip->body_utf8_append(lip->m_cpp_text_start);
928
929
      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
930
                                    lip->m_cpp_text_end);
931
932
      return(result_state);			// IDENT or IDENT_QUOTED
933
934
    case MY_LEX_IDENT_SEP:		// Found ident and now '.'
935
      yylval->lex_str.str= (char*) lip->get_ptr();
936
      yylval->lex_str.length= 1;
937
      c= lip->yyGet();                  // should be '.'
938
      lip->next_state= MY_LEX_IDENT_START;// Next is an ident (not a keyword)
939
      if (!ident_map[(uint8_t)lip->yyPeek()])            // Probably ` or "
940
	lip->next_state= MY_LEX_START;
941
      return((int) c);
942
943
    case MY_LEX_NUMBER_IDENT:		// number or ident which num-start
944
      if (lip->yyGetLast() == '0')
945
      {
946
        c= lip->yyGet();
947
        if (c == 'x')
948
        {
949
          while (my_isxdigit(cs,(c = lip->yyGet()))) ;
950
          if ((lip->yyLength() >= 3) && !ident_map[c])
951
          {
952
            /* skip '0x' */
953
            yylval->lex_str=get_token(lip, 2, lip->yyLength()-2);
954
            return (HEX_NUM);
955
          }
956
          lip->yyUnget();
957
          state= MY_LEX_IDENT_START;
958
          break;
959
        }
960
        else if (c == 'b')
961
        {
962
          while ((c= lip->yyGet()) == '0' || c == '1') {};
963
          if ((lip->yyLength() >= 3) && !ident_map[c])
964
          {
965
            /* Skip '0b' */
966
            yylval->lex_str= get_token(lip, 2, lip->yyLength()-2);
967
            return (BIN_NUM);
968
          }
969
          lip->yyUnget();
970
          state= MY_LEX_IDENT_START;
971
          break;
972
        }
973
        lip->yyUnget();
974
      }
975
976
      while (my_isdigit(cs, (c = lip->yyGet()))) ;
977
      if (!ident_map[c])
978
      {					// Can't be identifier
979
	state=MY_LEX_INT_OR_REAL;
980
	break;
981
      }
982
      if (c == 'e' || c == 'E')
983
      {
984
	// The following test is written this way to allow numbers of type 1e1
985
        if (my_isdigit(cs,lip->yyPeek()) ||
986
            (c=(lip->yyGet())) == '+' || c == '-')
987
	{				// Allow 1E+10
988
          if (my_isdigit(cs,lip->yyPeek()))     // Number must have digit after sign
989
	  {
990
            lip->yySkip();
991
            while (my_isdigit(cs,lip->yyGet())) ;
992
            yylval->lex_str=get_token(lip, 0, lip->yyLength());
993
	    return(FLOAT_NUM);
994
	  }
995
	}
996
        lip->yyUnget();
997
      }
998
      // fall through
999
    case MY_LEX_IDENT_START:			// We come here after '.'
1000
      result_state= IDENT;
1001
#if defined(USE_MB) && defined(USE_MB_IDENT)
1002
      if (use_mb(cs))
1003
      {
1004
	result_state= IDENT_QUOTED;
1005
        while (ident_map[c=lip->yyGet()])
1006
        {
1007
          if (my_mbcharlen(cs, c) > 1)
1008
          {
1009
            int l;
1010
            if ((l = my_ismbchar(cs,
1011
                                 lip->get_ptr() -1,
1012
                                 lip->get_end_of_query())) == 0)
1013
              break;
1014
            lip->skip_binary(l-1);
1015
          }
1016
        }
1017
      }
1018
      else
1019
#endif
1020
      {
1021
        for (result_state=0; ident_map[c= lip->yyGet()]; result_state|= c) {};
1022
        /* If there were non-ASCII characters, mark that we must convert */
1023
        result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1024
      }
1025
      if (c == '.' && ident_map[(uint8_t)lip->yyPeek()])
1026
	lip->next_state=MY_LEX_IDENT_SEP;// Next is '.'
1027
1028
      yylval->lex_str= get_token(lip, 0, lip->yyLength());
1029
1030
      lip->body_utf8_append(lip->m_cpp_text_start);
1031
1032
      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1033
                                    lip->m_cpp_text_end);
1034
1035
      return(result_state);
1036
1037
    case MY_LEX_USER_VARIABLE_DELIMITER:	// Found quote char
1038
    {
1039
      uint double_quotes= 0;
1040
      char quote_char= c;                       // Used char
1041
      while ((c=lip->yyGet()))
1042
      {
1043
	int var_length;
1044
	if ((var_length= my_mbcharlen(cs, c)) == 1)
1045
	{
1046
	  if (c == quote_char)
1047
	  {
1048
            if (lip->yyPeek() != quote_char)
1049
	      break;
1050
            c=lip->yyGet();
1051
	    double_quotes++;
1052
	    continue;
1053
	  }
1054
	}
1055
#ifdef USE_MB
1056
	else if (var_length < 1)
1057
	  break;				// Error
1058
        lip->skip_binary(var_length-1);
1059
#endif
1060
      }
1061
      if (double_quotes)
1062
	yylval->lex_str=get_quoted_token(lip, 1,
1063
                                         lip->yyLength() - double_quotes -1,
1064
					 quote_char);
1065
      else
1066
        yylval->lex_str=get_token(lip, 1, lip->yyLength() -1);
1067
      if (c == quote_char)
1068
        lip->yySkip();                  // Skip end `
1069
      lip->next_state= MY_LEX_START;
1070
1071
      lip->body_utf8_append(lip->m_cpp_text_start);
1072
1073
      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1074
                                    lip->m_cpp_text_end);
1075
1076
      return(IDENT_QUOTED);
1077
    }
1078
    case MY_LEX_INT_OR_REAL:		// Complete int or incomplete real
1079
      if (c != '.')
1080
      {					// Found complete integer number.
1081
        yylval->lex_str=get_token(lip, 0, lip->yyLength());
1082
	return int_token(yylval->lex_str.str,yylval->lex_str.length);
1083
      }
1084
      // fall through
1085
    case MY_LEX_REAL:			// Incomplete real number
1086
      while (my_isdigit(cs,c = lip->yyGet())) ;
1087
1088
      if (c == 'e' || c == 'E')
1089
      {
1090
        c = lip->yyGet();
1091
	if (c == '-' || c == '+')
1092
          c = lip->yyGet();                     // Skip sign
1093
	if (!my_isdigit(cs,c))
1094
	{				// No digit after sign
1095
	  state= MY_LEX_CHAR;
1096
	  break;
1097
	}
1098
        while (my_isdigit(cs,lip->yyGet())) ;
1099
        yylval->lex_str=get_token(lip, 0, lip->yyLength());
1100
	return(FLOAT_NUM);
1101
      }
1102
      yylval->lex_str=get_token(lip, 0, lip->yyLength());
1103
      return(DECIMAL_NUM);
1104
1105
    case MY_LEX_HEX_NUMBER:		// Found x'hexstring'
1106
      lip->yySkip();                    // Accept opening '
1107
      while (my_isxdigit(cs, (c= lip->yyGet()))) ;
1108
      if (c != '\'')
1109
        return(ABORT_SYM);              // Illegal hex constant
1110
      lip->yySkip();                    // Accept closing '
1111
      length= lip->yyLength();          // Length of hexnum+3
1112
      if ((length % 2) == 0)
1113
        return(ABORT_SYM);              // odd number of hex digits
1114
      yylval->lex_str=get_token(lip,
1115
                                2,          // skip x'
1116
                                length-3);  // don't count x' and last '
1117
      return (HEX_NUM);
1118
1119
    case MY_LEX_BIN_NUMBER:           // Found b'bin-string'
1120
      lip->yySkip();                  // Accept opening '
1121
      while ((c= lip->yyGet()) == '0' || c == '1') {};
1122
      if (c != '\'')
1123
        return(ABORT_SYM);            // Illegal hex constant
1124
      lip->yySkip();                  // Accept closing '
1125
      length= lip->yyLength();        // Length of bin-num + 3
1126
      yylval->lex_str= get_token(lip,
1127
                                 2,         // skip b'
1128
                                 length-3); // don't count b' and last '
1129
      return (BIN_NUM);
1130
1131
    case MY_LEX_CMP_OP:			// Incomplete comparison operator
1132
      if (state_map[(uint8_t)lip->yyPeek()] == MY_LEX_CMP_OP ||
1133
          state_map[(uint8_t)lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
1134
        lip->yySkip();
1135
      if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
1136
      {
1137
	lip->next_state= MY_LEX_START;	// Allow signed numbers
1138
	return(tokval);
1139
      }
1140
      state = MY_LEX_CHAR;		// Something fishy found
1141
      break;
1142
1143
    case MY_LEX_LONG_CMP_OP:		// Incomplete comparison operator
1144
      if (state_map[(uint8_t)lip->yyPeek()] == MY_LEX_CMP_OP ||
1145
          state_map[(uint8_t)lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
1146
      {
1147
        lip->yySkip();
1148
        if (state_map[(uint8_t)lip->yyPeek()] == MY_LEX_CMP_OP)
1149
          lip->yySkip();
1150
      }
1151
      if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
1152
      {
1153
	lip->next_state= MY_LEX_START;	// Found long op
1154
	return(tokval);
1155
      }
1156
      state = MY_LEX_CHAR;		// Something fishy found
1157
      break;
1158
1159
    case MY_LEX_BOOL:
1160
      if (c != lip->yyPeek())
1161
      {
1162
	state=MY_LEX_CHAR;
1163
	break;
1164
      }
1165
      lip->yySkip();
1166
      tokval = find_keyword(lip,2,0);	// Is a bool operator
1167
      lip->next_state= MY_LEX_START;	// Allow signed numbers
1168
      return(tokval);
1169
1170
    case MY_LEX_STRING_OR_DELIMITER:
1171
      if (0)
1172
      {
1173
        state= MY_LEX_USER_VARIABLE_DELIMITER;
1174
        break;
1175
      }
1176
      /* " used for strings */
1177
    case MY_LEX_STRING:			// Incomplete text string
1178
      if (!(yylval->lex_str.str = get_text(lip, 1, 1)))
1179
      {
1180
	state= MY_LEX_CHAR;		// Read char by char
1181
	break;
1182
      }
1183
      yylval->lex_str.length=lip->yytoklen;
1184
1185
      lip->body_utf8_append(lip->m_cpp_text_start);
1186
1187
      lip->body_utf8_append_literal(thd, &yylval->lex_str,
1188
        lip->m_underscore_cs ? lip->m_underscore_cs : cs,
1189
        lip->m_cpp_text_end);
1190
1191
      lip->m_underscore_cs= NULL;
1192
1193
      lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
1194
      return(TEXT_STRING);
1195
1196
    case MY_LEX_COMMENT:			//  Comment
1197
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
1198
      while ((c = lip->yyGet()) != '\n' && c) ;
1199
      lip->yyUnget();                   // Safety against eof
1200
      state = MY_LEX_START;		// Try again
1201
      break;
1202
    case MY_LEX_LONG_COMMENT:		/* Long C comment? */
1203
      if (lip->yyPeek() != '*')
1204
      {
1205
	state=MY_LEX_CHAR;		// Probable division
1206
	break;
1207
      }
1208
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
1209
      /* Reject '/' '*', since we might need to turn off the echo */
1210
      lip->yyUnget();
1211
1212
      if (lip->yyPeekn(2) == '!')
1213
      {
1214
        lip->in_comment= DISCARD_COMMENT;
1215
        /* Accept '/' '*' '!', but do not keep this marker. */
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1216
        lip->set_echo(false);
1 by brian
clean slate
1217
        lip->yySkip();
1218
        lip->yySkip();
1219
        lip->yySkip();
1220
1221
        /*
1222
          The special comment format is very strict:
1223
          '/' '*' '!', followed by exactly
1224
          1 digit (major), 2 digits (minor), then 2 digits (dot).
1225
          32302 -> 3.23.02
1226
          50032 -> 5.0.32
1227
          50114 -> 5.1.14
1228
        */
1229
        char version_str[6];
1230
        version_str[0]= lip->yyPeekn(0);
1231
        version_str[1]= lip->yyPeekn(1);
1232
        version_str[2]= lip->yyPeekn(2);
1233
        version_str[3]= lip->yyPeekn(3);
1234
        version_str[4]= lip->yyPeekn(4);
1235
        version_str[5]= 0;
1236
        if (  my_isdigit(cs, version_str[0])
1237
           && my_isdigit(cs, version_str[1])
1238
           && my_isdigit(cs, version_str[2])
1239
           && my_isdigit(cs, version_str[3])
1240
           && my_isdigit(cs, version_str[4])
1241
           )
1242
        {
1243
          ulong version;
1244
          version=strtol(version_str, NULL, 10);
1245
1246
          /* Accept 'M' 'm' 'm' 'd' 'd' */
1247
          lip->yySkipn(5);
1248
1249
          if (version <= MYSQL_VERSION_ID)
1250
          {
1251
            /* Expand the content of the special comment as real code */
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1252
            lip->set_echo(true);
1 by brian
clean slate
1253
            state=MY_LEX_START;
1254
            break;
1255
          }
1256
        }
1257
        else
1258
        {
1259
          state=MY_LEX_START;
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1260
          lip->set_echo(true);
1 by brian
clean slate
1261
          break;
1262
        }
1263
      }
1264
      else
1265
      {
1266
        lip->in_comment= PRESERVE_COMMENT;
1267
        lip->yySkip();                  // Accept /
1268
        lip->yySkip();                  // Accept *
1269
      }
1270
      /*
1271
        Discard:
1272
        - regular '/' '*' comments,
1273
        - special comments '/' '*' '!' for a future version,
1274
        by scanning until we find a closing '*' '/' marker.
1275
        Note: There is no such thing as nesting comments,
1276
        the first '*' '/' sequence seen will mark the end.
1277
      */
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1278
      comment_closed= false;
1 by brian
clean slate
1279
      while (! lip->eof())
1280
      {
1281
        c= lip->yyGet();
1282
        if (c == '*')
1283
        {
1284
          if (lip->yyPeek() == '/')
1285
          {
1286
            lip->yySkip();
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1287
            comment_closed= true;
1 by brian
clean slate
1288
            state = MY_LEX_START;
1289
            break;
1290
          }
1291
        }
1292
        else if (c == '\n')
1293
          lip->yylineno++;
1294
      }
1295
      /* Unbalanced comments with a missing '*' '/' are a syntax error */
1296
      if (! comment_closed)
1297
        return (ABORT_SYM);
1298
      state = MY_LEX_START;             // Try again
1299
      lip->in_comment= NO_COMMENT;
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1300
      lip->set_echo(true);
1 by brian
clean slate
1301
      break;
1302
    case MY_LEX_END_LONG_COMMENT:
1303
      if ((lip->in_comment != NO_COMMENT) && lip->yyPeek() == '/')
1304
      {
1305
        /* Reject '*' '/' */
1306
        lip->yyUnget();
1307
        /* Accept '*' '/', with the proper echo */
1308
        lip->set_echo(lip->in_comment == PRESERVE_COMMENT);
1309
        lip->yySkipn(2);
1310
        /* And start recording the tokens again */
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1311
        lip->set_echo(true);
1 by brian
clean slate
1312
        lip->in_comment=NO_COMMENT;
1313
        state=MY_LEX_START;
1314
      }
1315
      else
1316
	state=MY_LEX_CHAR;		// Return '*'
1317
      break;
1318
    case MY_LEX_SET_VAR:		// Check if ':='
1319
      if (lip->yyPeek() != '=')
1320
      {
1321
	state=MY_LEX_CHAR;		// Return ':'
1322
	break;
1323
      }
1324
      lip->yySkip();
1325
      return (SET_VAR);
1326
    case MY_LEX_SEMICOLON:			// optional line terminator
1327
      if (lip->yyPeek())
1328
      {
177.1.5 by brian
Removed dead ? operator.
1329
        if ((thd->client_capabilities & CLIENT_MULTI_STATEMENTS))
1 by brian
clean slate
1330
        {
1331
          lip->found_semicolon= lip->get_ptr();
1332
          thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
1333
          lip->next_state= MY_LEX_END;
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1334
          lip->set_echo(true);
1 by brian
clean slate
1335
          return (END_OF_INPUT);
1336
        }
1337
        state= MY_LEX_CHAR;		// Return ';'
1338
	break;
1339
      }
1340
      lip->next_state=MY_LEX_END;       // Mark for next loop
1341
      return(END_OF_INPUT);
1342
    case MY_LEX_EOL:
1343
      if (lip->eof())
1344
      {
1345
        lip->yyUnget();                 // Reject the last '\0'
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1346
        lip->set_echo(false);
1 by brian
clean slate
1347
        lip->yySkip();
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1348
        lip->set_echo(true);
1 by brian
clean slate
1349
        /* Unbalanced comments with a missing '*' '/' are a syntax error */
1350
        if (lip->in_comment != NO_COMMENT)
1351
          return (ABORT_SYM);
1352
        lip->next_state=MY_LEX_END;     // Mark for next loop
1353
        return(END_OF_INPUT);
1354
      }
1355
      state=MY_LEX_CHAR;
1356
      break;
1357
    case MY_LEX_END:
1358
      lip->next_state=MY_LEX_END;
1359
      return(0);			// We found end of input last time
1360
      
1361
      /* Actually real shouldn't start with . but allow them anyhow */
1362
    case MY_LEX_REAL_OR_POINT:
1363
      if (my_isdigit(cs,lip->yyPeek()))
1364
	state = MY_LEX_REAL;		// Real
1365
      else
1366
      {
1367
	state= MY_LEX_IDENT_SEP;	// return '.'
1368
        lip->yyUnget();                 // Put back '.'
1369
      }
1370
      break;
1371
    case MY_LEX_USER_END:		// end '@' of user@hostname
1372
      switch (state_map[(uint8_t)lip->yyPeek()]) {
1373
      case MY_LEX_STRING:
1374
      case MY_LEX_USER_VARIABLE_DELIMITER:
1375
      case MY_LEX_STRING_OR_DELIMITER:
1376
	break;
1377
      case MY_LEX_USER_END:
1378
	lip->next_state=MY_LEX_SYSTEM_VAR;
1379
	break;
1380
      default:
1381
	lip->next_state=MY_LEX_HOSTNAME;
1382
	break;
1383
      }
1384
      yylval->lex_str.str=(char*) lip->get_ptr();
1385
      yylval->lex_str.length=1;
1386
      return((int) '@');
1387
    case MY_LEX_HOSTNAME:		// end '@' of user@hostname
1388
      for (c=lip->yyGet() ;
1389
	   my_isalnum(cs,c) || c == '.' || c == '_' ||  c == '$';
1390
           c= lip->yyGet()) ;
1391
      yylval->lex_str=get_token(lip, 0, lip->yyLength());
1392
      return(LEX_HOSTNAME);
1393
    case MY_LEX_SYSTEM_VAR:
1394
      yylval->lex_str.str=(char*) lip->get_ptr();
1395
      yylval->lex_str.length=1;
1396
      lip->yySkip();                                    // Skip '@'
1397
      lip->next_state= (state_map[(uint8_t)lip->yyPeek()] ==
1398
			MY_LEX_USER_VARIABLE_DELIMITER ?
1399
			MY_LEX_OPERATOR_OR_IDENT :
1400
			MY_LEX_IDENT_OR_KEYWORD);
1401
      return((int) '@');
1402
    case MY_LEX_IDENT_OR_KEYWORD:
1403
      /*
1404
	We come here when we have found two '@' in a row.
1405
	We should now be able to handle:
1406
	[(global | local | session) .]variable_name
1407
      */
1408
1409
      for (result_state= 0; ident_map[c= lip->yyGet()]; result_state|= c) {};
1410
      /* If there were non-ASCII characters, mark that we must convert */
1411
      result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
1412
1413
      if (c == '.')
1414
	lip->next_state=MY_LEX_IDENT_SEP;
1415
      length= lip->yyLength();
1416
      if (length == 0)
1417
        return(ABORT_SYM);              // Names must be nonempty.
1418
      if ((tokval= find_keyword(lip, length,0)))
1419
      {
1420
        lip->yyUnget();                         // Put back 'c'
1421
	return(tokval);				// Was keyword
1422
      }
1423
      yylval->lex_str=get_token(lip, 0, length);
1424
1425
      lip->body_utf8_append(lip->m_cpp_text_start);
1426
1427
      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
1428
                                    lip->m_cpp_text_end);
1429
1430
      return(result_state);
1431
    }
1432
  }
1433
}
1434
1435
1436
/**
1437
  Construct a copy of this object to be used for mysql_alter_table
1438
  and mysql_create_table.
1439
1440
  Historically, these two functions modify their Alter_info
1441
  arguments. This behaviour breaks re-execution of prepared
1442
  statements and stored procedures and is compensated by always
1443
  supplying a copy of Alter_info to these functions.
1444
1445
  @return You need to use check the error in THD for out
1446
  of memory condition after calling this function.
1447
*/
1448
1449
Alter_info::Alter_info(const Alter_info &rhs, MEM_ROOT *mem_root)
1450
  :drop_list(rhs.drop_list, mem_root),
1451
  alter_list(rhs.alter_list, mem_root),
1452
  key_list(rhs.key_list, mem_root),
1453
  create_list(rhs.create_list, mem_root),
1454
  flags(rhs.flags),
1455
  keys_onoff(rhs.keys_onoff),
1456
  tablespace_op(rhs.tablespace_op),
1457
  no_parts(rhs.no_parts),
1458
  build_method(rhs.build_method),
1459
  datetime_field(rhs.datetime_field),
1460
  error_if_not_empty(rhs.error_if_not_empty)
1461
{
1462
  /*
1463
    Make deep copies of used objects.
1464
    This is not a fully deep copy - clone() implementations
1465
    of Alter_drop, Alter_column, Key, foreign_key, Key_part_spec
1466
    do not copy string constants. At the same length the only
1467
    reason we make a copy currently is that ALTER/CREATE TABLE
1468
    code changes input Alter_info definitions, but string
1469
    constants never change.
1470
  */
1471
  list_copy_and_replace_each_value(drop_list, mem_root);
1472
  list_copy_and_replace_each_value(alter_list, mem_root);
1473
  list_copy_and_replace_each_value(key_list, mem_root);
1474
  list_copy_and_replace_each_value(create_list, mem_root);
1475
}
1476
1477
1478
void trim_whitespace(CHARSET_INFO *cs, LEX_STRING *str)
1479
{
1480
  /*
1481
    TODO:
1482
    This code assumes that there are no multi-bytes characters
1483
    that can be considered white-space.
1484
  */
1485
1486
  while ((str->length > 0) && (my_isspace(cs, str->str[0])))
1487
  {
1488
    str->length --;
1489
    str->str ++;
1490
  }
1491
1492
  /*
1493
    FIXME:
1494
    Also, parsing backward is not safe with multi bytes characters
1495
  */
1496
  while ((str->length > 0) && (my_isspace(cs, str->str[str->length-1])))
1497
  {
1498
    str->length --;
1499
  }
1500
}
1501
1502
1503
/*
1504
  st_select_lex structures initialisations
1505
*/
1506
1507
void st_select_lex_node::init_query()
1508
{
1509
  options= 0;
1510
  linkage= UNSPECIFIED_TYPE;
1511
  no_error= no_table_names_allowed= 0;
1512
  uncacheable= 0;
1513
}
1514
1515
void st_select_lex_node::init_select()
1516
{
1517
}
1518
1519
void st_select_lex_unit::init_query()
1520
{
1521
  st_select_lex_node::init_query();
1522
  linkage= GLOBAL_OPTIONS_TYPE;
1523
  global_parameters= first_select();
1524
  select_limit_cnt= HA_POS_ERROR;
1525
  offset_limit_cnt= 0;
1526
  union_distinct= 0;
1527
  prepared= optimized= executed= 0;
1528
  item= 0;
1529
  union_result= 0;
1530
  table= 0;
1531
  fake_select_lex= 0;
1532
  cleaned= 0;
1533
  item_list.empty();
1534
  describe= 0;
1535
  found_rows_for_union= 0;
1536
}
1537
1538
void st_select_lex::init_query()
1539
{
1540
  st_select_lex_node::init_query();
1541
  table_list.empty();
1542
  top_join_list.empty();
1543
  join_list= &top_join_list;
1544
  embedding= leaf_tables= 0;
1545
  item_list.empty();
1546
  join= 0;
177.1.1 by brian
Removed dead code around prep.
1547
  having= where= 0;
1 by brian
clean slate
1548
  olap= UNSPECIFIED_OLAP_TYPE;
1549
  having_fix_field= 0;
1550
  context.select_lex= this;
1551
  context.init();
1552
  /*
1553
    Add the name resolution context of the current (sub)query to the
1554
    stack of contexts for the whole query.
1555
    TODO:
1556
    push_context may return an error if there is no memory for a new
1557
    element in the stack, however this method has no return value,
1558
    thus push_context should be moved to a place where query
1559
    initialization is checked for failure.
1560
  */
1561
  parent_lex->push_context(&context);
1562
  cond_count= between_count= with_wild= 0;
1563
  max_equal_elems= 0;
1564
  conds_processed_with_permanent_arena= 0;
1565
  ref_pointer_array= 0;
1566
  select_n_where_fields= 0;
1567
  select_n_having_items= 0;
1568
  subquery_in_having= explicit_limit= 0;
1569
  is_item_list_lookup= 0;
1570
  first_execution= 1;
1571
  first_cond_optimization= 1;
1572
  parsing_place= NO_MATTER;
177.1.2 by brian
Removed dead variable, sorted authors file.
1573
  exclude_from_table_unique_test= false;
1 by brian
clean slate
1574
  nest_level= 0;
1575
  link_next= 0;
1576
}
1577
1578
void st_select_lex::init_select()
1579
{
1580
  st_select_lex_node::init_select();
1581
  sj_nests.empty();
1582
  group_list.empty();
1583
  type= db= 0;
1584
  having= 0;
1585
  table_join_options= 0;
1586
  in_sum_expr= with_wild= 0;
1587
  options= 0;
1588
  braces= 0;
1589
  interval_list.empty();
1590
  ftfunc_list_alloc.empty();
1591
  inner_sum_func_list= 0;
1592
  ftfunc_list= &ftfunc_list_alloc;
1593
  linkage= UNSPECIFIED_TYPE;
1594
  order_list.elements= 0;
1595
  order_list.first= 0;
1596
  order_list.next= (uchar**) &order_list.first;
1597
  /* Set limit and offset to default values */
1598
  select_limit= 0;      /* denotes the default limit = HA_POS_ERROR */
1599
  offset_limit= 0;      /* denotes the default offset = 0 */
1600
  with_sum_func= 0;
1601
  is_correlated= 0;
1602
  cur_pos_in_select_list= UNDEF_POS;
1603
  non_agg_fields.empty();
1604
  cond_value= having_value= Item::COND_UNDEF;
1605
  inner_refs_list.empty();
1606
  full_group_by_flag= 0;
1607
}
1608
1609
/*
1610
  st_select_lex structures linking
1611
*/
1612
1613
/* include on level down */
1614
void st_select_lex_node::include_down(st_select_lex_node *upper)
1615
{
1616
  if ((next= upper->slave))
1617
    next->prev= &next;
1618
  prev= &upper->slave;
1619
  upper->slave= this;
1620
  master= upper;
1621
  slave= 0;
1622
}
1623
1624
/*
1625
  include on level down (but do not link)
1626
1627
  SYNOPSYS
1628
    st_select_lex_node::include_standalone()
1629
    upper - reference on node underr which this node should be included
1630
    ref - references on reference on this node
1631
*/
1632
void st_select_lex_node::include_standalone(st_select_lex_node *upper,
1633
					    st_select_lex_node **ref)
1634
{
1635
  next= 0;
1636
  prev= ref;
1637
  master= upper;
1638
  slave= 0;
1639
}
1640
1641
/* include neighbour (on same level) */
1642
void st_select_lex_node::include_neighbour(st_select_lex_node *before)
1643
{
1644
  if ((next= before->next))
1645
    next->prev= &next;
1646
  prev= &before->next;
1647
  before->next= this;
1648
  master= before->master;
1649
  slave= 0;
1650
}
1651
1652
/* including in global SELECT_LEX list */
1653
void st_select_lex_node::include_global(st_select_lex_node **plink)
1654
{
1655
  if ((link_next= *plink))
1656
    link_next->link_prev= &link_next;
1657
  link_prev= plink;
1658
  *plink= this;
1659
}
1660
1661
//excluding from global list (internal function)
1662
void st_select_lex_node::fast_exclude()
1663
{
1664
  if (link_prev)
1665
  {
1666
    if ((*link_prev= link_next))
1667
      link_next->link_prev= link_prev;
1668
  }
1669
  // Remove slave structure
1670
  for (; slave; slave= slave->next)
1671
    slave->fast_exclude();
1672
  
1673
}
1674
1675
/*
1676
  excluding select_lex structure (except first (first select can't be
1677
  deleted, because it is most upper select))
1678
*/
1679
void st_select_lex_node::exclude()
1680
{
1681
  //exclude from global list
1682
  fast_exclude();
1683
  //exclude from other structures
1684
  if ((*prev= next))
1685
    next->prev= prev;
1686
  /* 
1687
     We do not need following statements, because prev pointer of first 
1688
     list element point to master->slave
1689
     if (master->slave == this)
1690
       master->slave= next;
1691
  */
1692
}
1693
1694
1695
/*
1696
  Exclude level of current unit from tree of SELECTs
1697
1698
  SYNOPSYS
1699
    st_select_lex_unit::exclude_level()
1700
1701
  NOTE: units which belong to current will be brought up on level of
1702
  currernt unit 
1703
*/
1704
void st_select_lex_unit::exclude_level()
1705
{
1706
  SELECT_LEX_UNIT *units= 0, **units_last= &units;
1707
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
1708
  {
1709
    // unlink current level from global SELECTs list
1710
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
1711
      sl->link_next->link_prev= sl->link_prev;
1712
1713
    // bring up underlay levels
1714
    SELECT_LEX_UNIT **last= 0;
1715
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
1716
    {
1717
      u->master= master;
1718
      last= (SELECT_LEX_UNIT**)&(u->next);
1719
    }
1720
    if (last)
1721
    {
1722
      (*units_last)= sl->first_inner_unit();
1723
      units_last= last;
1724
    }
1725
  }
1726
  if (units)
1727
  {
1728
    // include brought up levels in place of current
1729
    (*prev)= units;
1730
    (*units_last)= (SELECT_LEX_UNIT*)next;
1731
    if (next)
1732
      next->prev= (SELECT_LEX_NODE**)units_last;
1733
    units->prev= prev;
1734
  }
1735
  else
1736
  {
1737
    // exclude currect unit from list of nodes
1738
    (*prev)= next;
1739
    if (next)
1740
      next->prev= prev;
1741
  }
1742
}
1743
1744
1745
/*
1746
  Exclude subtree of current unit from tree of SELECTs
1747
1748
  SYNOPSYS
1749
    st_select_lex_unit::exclude_tree()
1750
*/
1751
void st_select_lex_unit::exclude_tree()
1752
{
1753
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
1754
  {
1755
    // unlink current level from global SELECTs list
1756
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
1757
      sl->link_next->link_prev= sl->link_prev;
1758
1759
    // unlink underlay levels
1760
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
1761
    {
1762
      u->exclude_level();
1763
    }
1764
  }
1765
  // exclude currect unit from list of nodes
1766
  (*prev)= next;
1767
  if (next)
1768
    next->prev= prev;
1769
}
1770
1771
1772
/*
1773
  st_select_lex_node::mark_as_dependent mark all st_select_lex struct from 
1774
  this to 'last' as dependent
1775
1776
  SYNOPSIS
1777
    last - pointer to last st_select_lex struct, before wich all 
1778
           st_select_lex have to be marked as dependent
1779
1780
  NOTE
1781
    'last' should be reachable from this st_select_lex_node
1782
*/
1783
1784
void st_select_lex::mark_as_dependent(st_select_lex *last)
1785
{
1786
  /*
1787
    Mark all selects from resolved to 1 before select where was
1788
    found table as depended (of select where was found table)
1789
  */
1790
  for (SELECT_LEX *s= this;
1791
       s && s != last;
1792
       s= s->outer_select())
1793
  {
1794
    if (!(s->uncacheable & UNCACHEABLE_DEPENDENT))
1795
    {
1796
      // Select is dependent of outer select
1797
      s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
1798
                       UNCACHEABLE_DEPENDENT;
1799
      SELECT_LEX_UNIT *munit= s->master_unit();
1800
      munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
1801
                       UNCACHEABLE_DEPENDENT;
1802
      for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
1803
      {
1804
        if (sl != s &&
1805
            !(sl->uncacheable & (UNCACHEABLE_DEPENDENT | UNCACHEABLE_UNITED)))
1806
          sl->uncacheable|= UNCACHEABLE_UNITED;
1807
      }
1808
    }
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1809
    s->is_correlated= true;
1 by brian
clean slate
1810
    Item_subselect *subquery_predicate= s->master_unit()->item;
1811
    if (subquery_predicate)
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1812
      subquery_predicate->is_correlated= true;
1 by brian
clean slate
1813
  }
1814
}
1815
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
1816
bool st_select_lex_node::set_braces(bool value __attribute__((unused)))
77.1.15 by Monty Taylor
Bunch of warning cleanups.
1817
{ return 1; }
1 by brian
clean slate
1818
bool st_select_lex_node::inc_in_sum_expr()           { return 1; }
1819
uint st_select_lex_node::get_in_sum_expr()           { return 0; }
1820
TABLE_LIST* st_select_lex_node::get_table_list()     { return 0; }
1821
List<Item>* st_select_lex_node::get_item_list()      { return 0; }
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
1822
TABLE_LIST *st_select_lex_node::add_table_to_list (THD *thd __attribute__((unused)),
1823
                                                   Table_ident *table __attribute__((unused)),
1824
						  LEX_STRING *alias __attribute__((unused)),
1825
						  uint32_t table_join_options __attribute__((unused)),
1826
						  thr_lock_type flags __attribute__((unused)),
1827
						  List<Index_hint> *hints __attribute__((unused)),
1828
                                                  LEX_STRING *option __attribute__((unused)))
1 by brian
clean slate
1829
{
1830
  return 0;
1831
}
202 by Brian Aker
Cleanup sql_lex to modern types.
1832
uint32_t st_select_lex_node::get_table_join_options()
1 by brian
clean slate
1833
{
1834
  return 0;
1835
}
1836
1837
/*
1838
  prohibit using LIMIT clause
1839
*/
1840
bool st_select_lex::test_limit()
1841
{
1842
  if (select_limit != 0)
1843
  {
1844
    my_error(ER_NOT_SUPPORTED_YET, MYF(0),
1845
             "LIMIT & IN/ALL/ANY/SOME subquery");
1846
    return(1);
1847
  }
1848
  return(0);
1849
}
1850
1851
1852
st_select_lex_unit* st_select_lex_unit::master_unit()
1853
{
1854
    return this;
1855
}
1856
1857
1858
st_select_lex* st_select_lex_unit::outer_select()
1859
{
1860
  return (st_select_lex*) master;
1861
}
1862
1863
1864
bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
1865
{
1866
  return add_to_list(thd, order_list, item, asc);
1867
}
1868
1869
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
1870
bool st_select_lex::add_item_to_list(THD *thd __attribute__((unused)),
77.1.15 by Monty Taylor
Bunch of warning cleanups.
1871
                                     Item *item)
1 by brian
clean slate
1872
{
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1873
  return(item_list.push_back(item));
1 by brian
clean slate
1874
}
1875
1876
1877
bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
1878
{
1879
  return add_to_list(thd, group_list, item, asc);
1880
}
1881
1882
1883
st_select_lex_unit* st_select_lex::master_unit()
1884
{
1885
  return (st_select_lex_unit*) master;
1886
}
1887
1888
1889
st_select_lex* st_select_lex::outer_select()
1890
{
1891
  return (st_select_lex*) master->get_master();
1892
}
1893
1894
1895
bool st_select_lex::set_braces(bool value)
1896
{
1897
  braces= value;
1898
  return 0; 
1899
}
1900
1901
1902
bool st_select_lex::inc_in_sum_expr()
1903
{
1904
  in_sum_expr++;
1905
  return 0;
1906
}
1907
1908
1909
uint st_select_lex::get_in_sum_expr()
1910
{
1911
  return in_sum_expr;
1912
}
1913
1914
1915
TABLE_LIST* st_select_lex::get_table_list()
1916
{
1917
  return (TABLE_LIST*) table_list.first;
1918
}
1919
1920
List<Item>* st_select_lex::get_item_list()
1921
{
1922
  return &item_list;
1923
}
1924
202 by Brian Aker
Cleanup sql_lex to modern types.
1925
uint32_t st_select_lex::get_table_join_options()
1 by brian
clean slate
1926
{
1927
  return table_join_options;
1928
}
1929
1930
1931
bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
1932
{
1933
  if (ref_pointer_array)
1934
    return 0;
1935
1936
  /*
1937
    We have to create array in prepared statement memory if it is
1938
    prepared statement
1939
  */
1940
  Query_arena *arena= thd->stmt_arena;
1941
  return (ref_pointer_array=
1942
          (Item **)arena->alloc(sizeof(Item*) * (n_child_sum_items +
1943
                                                 item_list.elements +
1944
                                                 select_n_having_items +
1945
                                                 select_n_where_fields +
1946
                                                 order_group_num)*5)) == 0;
1947
}
1948
1949
1950
void st_select_lex_unit::print(String *str, enum_query_type query_type)
1951
{
1952
  bool union_all= !union_distinct;
1953
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
1954
  {
1955
    if (sl != first_select())
1956
    {
1957
      str->append(STRING_WITH_LEN(" union "));
1958
      if (union_all)
1959
	str->append(STRING_WITH_LEN("all "));
1960
      else if (union_distinct == sl)
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1961
        union_all= true;
1 by brian
clean slate
1962
    }
1963
    if (sl->braces)
1964
      str->append('(');
1965
    sl->print(thd, str, query_type);
1966
    if (sl->braces)
1967
      str->append(')');
1968
  }
1969
  if (fake_select_lex == global_parameters)
1970
  {
1971
    if (fake_select_lex->order_list.elements)
1972
    {
1973
      str->append(STRING_WITH_LEN(" order by "));
1974
      fake_select_lex->print_order(
1975
        str,
1976
        (ORDER *) fake_select_lex->order_list.first,
1977
        query_type);
1978
    }
1979
    fake_select_lex->print_limit(thd, str, query_type);
1980
  }
1981
}
1982
1983
1984
void st_select_lex::print_order(String *str,
1985
                                ORDER *order,
1986
                                enum_query_type query_type)
1987
{
1988
  for (; order; order= order->next)
1989
  {
1990
    if (order->counter_used)
1991
    {
1992
      char buffer[20];
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
1993
      uint length= snprintf(buffer, 20, "%d", order->counter);
1 by brian
clean slate
1994
      str->append(buffer, length);
1995
    }
1996
    else
1997
      (*order->item)->print(str, query_type);
1998
    if (!order->asc)
1999
      str->append(STRING_WITH_LEN(" desc"));
2000
    if (order->next)
2001
      str->append(',');
2002
  }
2003
}
2004
 
2005
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
2006
void st_select_lex::print_limit(THD *thd __attribute__((unused)),
1 by brian
clean slate
2007
                                String *str,
2008
                                enum_query_type query_type)
2009
{
2010
  SELECT_LEX_UNIT *unit= master_unit();
2011
  Item_subselect *item= unit->item;
2012
2013
  if (item && unit->global_parameters == this)
2014
  {
2015
    Item_subselect::subs_type subs_type= item->substype();
2016
    if (subs_type == Item_subselect::EXISTS_SUBS ||
2017
        subs_type == Item_subselect::IN_SUBS ||
2018
        subs_type == Item_subselect::ALL_SUBS)
2019
    {
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2020
      assert(!item->fixed ||
1 by brian
clean slate
2021
                  /*
2022
                    If not using materialization both:
2023
                    select_limit == 1, and there should be no offset_limit.
2024
                  */
2025
                  (((subs_type == Item_subselect::IN_SUBS) &&
2026
                    ((Item_in_subselect*)item)->exec_method ==
2027
                    Item_in_subselect::MATERIALIZATION) ?
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2028
                   true :
80.1.1 by Brian Aker
LL() cleanup
2029
                   (select_limit->val_int() == 1LL) &&
1 by brian
clean slate
2030
                   offset_limit == 0));
2031
      return;
2032
    }
2033
  }
2034
  if (explicit_limit)
2035
  {
2036
    str->append(STRING_WITH_LEN(" limit "));
2037
    if (offset_limit)
2038
    {
2039
      offset_limit->print(str, query_type);
2040
      str->append(',');
2041
    }
2042
    select_limit->print(str, query_type);
2043
  }
2044
}
2045
2046
/**
2047
  @brief Restore the LEX and THD in case of a parse error.
2048
2049
  This is a clean up call that is invoked by the Bison generated
2050
  parser before returning an error from MYSQLparse. If your
2051
  semantic actions manipulate with the global thread state (which
2052
  is a very bad practice and should not normally be employed) and
2053
  need a clean-up in case of error, and you can not use %destructor
2054
  rule in the grammar file itself, this function should be used
2055
  to implement the clean up.
2056
*/
2057
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
2058
void st_lex::cleanup_lex_after_parse_error(THD *thd __attribute__((unused)))
1 by brian
clean slate
2059
{
2060
}
2061
2062
/*
2063
  Initialize (or reset) Query_tables_list object.
2064
2065
  SYNOPSIS
2066
    reset_query_tables_list()
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2067
      init  true  - we should perform full initialization of object with
1 by brian
clean slate
2068
                    allocating needed memory
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2069
            false - object is already initialized so we should only reset
1 by brian
clean slate
2070
                    its state so it can be used for parsing/processing
2071
                    of new statement
2072
2073
  DESCRIPTION
2074
    This method initializes Query_tables_list so it can be used as part
2075
    of LEX object for parsing/processing of statement. One can also use
2076
    this method to reset state of already initialized Query_tables_list
2077
    so it can be used for processing of new statement.
2078
*/
2079
2080
void Query_tables_list::reset_query_tables_list(bool init)
2081
{
2082
  if (!init && query_tables)
2083
  {
2084
    TABLE_LIST *table= query_tables;
2085
    for (;;)
2086
    {
2087
      if (query_tables_last == &table->next_global ||
2088
          !(table= table->next_global))
2089
        break;
2090
    }
2091
  }
2092
  query_tables= 0;
2093
  query_tables_last= &query_tables;
2094
  query_tables_own_last= 0;
2095
  if (init)
2096
  {
2097
    /*
2098
      We delay real initialization of hash (and therefore related
2099
      memory allocation) until first insertion into this hash.
2100
    */
2101
    hash_clear(&sroutines);
2102
  }
2103
  else if (sroutines.records)
2104
  {
2105
    /* Non-zero sroutines.records means that hash was initialized. */
2106
    my_hash_reset(&sroutines);
2107
  }
2108
  sroutines_list.empty();
2109
  sroutines_list_own_last= sroutines_list.next;
2110
  sroutines_list_own_elements= 0;
2111
  binlog_stmt_flags= 0;
2112
}
2113
2114
2115
/*
2116
  Destroy Query_tables_list object with freeing all resources used by it.
2117
2118
  SYNOPSIS
2119
    destroy_query_tables_list()
2120
*/
2121
2122
void Query_tables_list::destroy_query_tables_list()
2123
{
2124
  hash_free(&sroutines);
2125
}
2126
2127
2128
/*
2129
  Initialize LEX object.
2130
2131
  SYNOPSIS
2132
    st_lex::st_lex()
2133
2134
  NOTE
2135
    LEX object initialized with this constructor can be used as part of
2136
    THD object for which one can safely call open_tables(), lock_tables()
2137
    and close_thread_tables() functions. But it is not yet ready for
2138
    statement parsing. On should use lex_start() function to prepare LEX
2139
    for this.
2140
*/
2141
2142
st_lex::st_lex()
2143
  :result(0), yacc_yyss(0), yacc_yyvs(0),
2144
   sql_command(SQLCOM_END), option_type(OPT_DEFAULT), is_lex_started(0)
2145
{
2146
2147
  my_init_dynamic_array2(&plugins, sizeof(plugin_ref),
2148
                         plugins_static_buffer,
2149
                         INITIAL_LEX_PLUGIN_LIST_SIZE, 
2150
                         INITIAL_LEX_PLUGIN_LIST_SIZE);
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2151
  reset_query_tables_list(true);
1 by brian
clean slate
2152
}
2153
2154
2155
/*
2156
  Check whether the merging algorithm can be used on this VIEW
2157
2158
  SYNOPSIS
2159
    st_lex::can_be_merged()
2160
2161
  DESCRIPTION
2162
    We can apply merge algorithm if it is single SELECT view  with
2163
    subqueries only in WHERE clause (we do not count SELECTs of underlying
2164
    views, and second level subqueries) and we have not grpouping, ordering,
2165
    HAVING clause, aggregate functions, DISTINCT clause, LIMIT clause and
2166
    several underlying tables.
2167
2168
  RETURN
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2169
    false - only temporary table algorithm can be used
2170
    true  - merge algorithm can be used
1 by brian
clean slate
2171
*/
2172
2173
bool st_lex::can_be_merged()
2174
{
2175
  // TODO: do not forget implement case when select_lex.table_list.elements==0
2176
2177
  /* find non VIEW subqueries/unions */
2178
  bool selects_allow_merge= select_lex.next_select() == 0;
2179
  if (selects_allow_merge)
2180
  {
2181
    for (SELECT_LEX_UNIT *tmp_unit= select_lex.first_inner_unit();
2182
         tmp_unit;
2183
         tmp_unit= tmp_unit->next_unit())
2184
    {
2185
      if (tmp_unit->first_select()->parent_lex == this &&
2186
          (tmp_unit->item == 0 ||
2187
           (tmp_unit->item->place() != IN_WHERE &&
2188
            tmp_unit->item->place() != IN_ON)))
2189
      {
2190
        selects_allow_merge= 0;
2191
        break;
2192
      }
2193
    }
2194
  }
2195
2196
  return (selects_allow_merge &&
2197
	  select_lex.group_list.elements == 0 &&
2198
	  select_lex.having == 0 &&
2199
          select_lex.with_sum_func == 0 &&
2200
	  select_lex.table_list.elements >= 1 &&
2201
	  !(select_lex.options & SELECT_DISTINCT) &&
2202
          select_lex.select_limit == 0);
2203
}
2204
2205
2206
/*
2207
  check if command can use VIEW with MERGE algorithm (for top VIEWs)
2208
2209
  SYNOPSIS
2210
    st_lex::can_use_merged()
2211
2212
  DESCRIPTION
2213
    Only listed here commands can use merge algorithm in top level
2214
    SELECT_LEX (for subqueries will be used merge algorithm if
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2215
    st_lex::can_not_use_merged() is not true).
1 by brian
clean slate
2216
2217
  RETURN
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2218
    false - command can't use merged VIEWs
2219
    true  - VIEWs with MERGE algorithms can be used
1 by brian
clean slate
2220
*/
2221
2222
bool st_lex::can_use_merged()
2223
{
2224
  switch (sql_command)
2225
  {
2226
  case SQLCOM_SELECT:
2227
  case SQLCOM_CREATE_TABLE:
2228
  case SQLCOM_UPDATE:
2229
  case SQLCOM_UPDATE_MULTI:
2230
  case SQLCOM_DELETE:
2231
  case SQLCOM_DELETE_MULTI:
2232
  case SQLCOM_INSERT:
2233
  case SQLCOM_INSERT_SELECT:
2234
  case SQLCOM_REPLACE:
2235
  case SQLCOM_REPLACE_SELECT:
2236
  case SQLCOM_LOAD:
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2237
    return true;
1 by brian
clean slate
2238
  default:
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2239
    return false;
1 by brian
clean slate
2240
  }
2241
}
2242
2243
/*
2244
  Check if command can't use merged views in any part of command
2245
2246
  SYNOPSIS
2247
    st_lex::can_not_use_merged()
2248
2249
  DESCRIPTION
2250
    Temporary table algorithm will be used on all SELECT levels for queries
2251
    listed here (see also st_lex::can_use_merged()).
2252
2253
  RETURN
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2254
    false - command can't use merged VIEWs
2255
    true  - VIEWs with MERGE algorithms can be used
1 by brian
clean slate
2256
*/
2257
2258
bool st_lex::can_not_use_merged()
2259
{
2260
  switch (sql_command)
2261
  {
2262
  /*
2263
    SQLCOM_SHOW_FIELDS is necessary to make 
2264
    information schema tables working correctly with views.
2265
    see get_schema_tables_result function
2266
  */
2267
  case SQLCOM_SHOW_FIELDS:
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2268
    return true;
1 by brian
clean slate
2269
  default:
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2270
    return false;
1 by brian
clean slate
2271
  }
2272
}
2273
2274
/*
2275
  Detect that we need only table structure of derived table/view
2276
2277
  SYNOPSIS
2278
    only_view_structure()
2279
2280
  RETURN
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2281
    true yes, we need only structure
2282
    false no, we need data
1 by brian
clean slate
2283
*/
2284
2285
bool st_lex::only_view_structure()
2286
{
2287
  switch (sql_command) {
2288
  case SQLCOM_SHOW_CREATE:
2289
  case SQLCOM_SHOW_TABLES:
2290
  case SQLCOM_SHOW_FIELDS:
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2291
    return true;
1 by brian
clean slate
2292
  default:
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2293
    return false;
1 by brian
clean slate
2294
  }
2295
}
2296
2297
2298
/*
2299
  Should Items_ident be printed correctly
2300
2301
  SYNOPSIS
2302
    need_correct_ident()
2303
2304
  RETURN
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2305
    true yes, we need only structure
2306
    false no, we need data
1 by brian
clean slate
2307
*/
2308
2309
2310
bool st_lex::need_correct_ident()
2311
{
2312
  switch(sql_command)
2313
  {
2314
  case SQLCOM_SHOW_CREATE:
2315
  case SQLCOM_SHOW_TABLES:
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2316
    return true;
1 by brian
clean slate
2317
  default:
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2318
    return false;
1 by brian
clean slate
2319
  }
2320
}
2321
2322
2323
/**
2324
  This method should be called only during parsing.
2325
  It is aware of compound statements (stored routine bodies)
2326
  and will initialize the destination with the default
2327
  database of the stored routine, rather than the default
2328
  database of the connection it is parsed in.
2329
  E.g. if one has no current database selected, or current database 
2330
  set to 'bar' and then issues:
2331
2332
  CREATE PROCEDURE foo.p1() BEGIN SELECT * FROM t1 END//
2333
2334
  t1 is meant to refer to foo.t1, not to bar.t1.
2335
2336
  This method is needed to support this rule.
2337
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2338
  @return true in case of error (parsing should be aborted, false in
1 by brian
clean slate
2339
  case of success
2340
*/
2341
2342
bool
2343
st_lex::copy_db_to(char **p_db, size_t *p_db_length) const
2344
{
2345
  return thd->copy_db_to(p_db, p_db_length);
2346
}
2347
2348
/*
2349
  initialize limit counters
2350
2351
  SYNOPSIS
2352
    st_select_lex_unit::set_limit()
2353
    values	- SELECT_LEX with initial values for counters
2354
*/
2355
2356
void st_select_lex_unit::set_limit(st_select_lex *sl)
2357
{
2358
  ha_rows select_limit_val;
151 by Brian Aker
Ulonglong to uint64_t
2359
  uint64_t val;
1 by brian
clean slate
2360
2361
  val= sl->select_limit ? sl->select_limit->val_uint() : HA_POS_ERROR;
2362
  select_limit_val= (ha_rows)val;
2363
#ifndef BIG_TABLES
2364
  /* 
151 by Brian Aker
Ulonglong to uint64_t
2365
    Check for overflow : ha_rows can be smaller then uint64_t if
1 by brian
clean slate
2366
    BIG_TABLES is off.
2367
    */
151 by Brian Aker
Ulonglong to uint64_t
2368
  if (val != (uint64_t)select_limit_val)
1 by brian
clean slate
2369
    select_limit_val= HA_POS_ERROR;
2370
#endif
2371
  offset_limit_cnt= (ha_rows)(sl->offset_limit ? sl->offset_limit->val_uint() :
80.1.1 by Brian Aker
LL() cleanup
2372
                                                 0ULL);
1 by brian
clean slate
2373
  select_limit_cnt= select_limit_val + offset_limit_cnt;
2374
  if (select_limit_cnt < select_limit_val)
2375
    select_limit_cnt= HA_POS_ERROR;		// no limit
2376
}
2377
2378
2379
/*
2380
  Unlink the first table from the global table list and the first table from
2381
  outer select (lex->select_lex) local list
2382
2383
  SYNOPSIS
2384
    unlink_first_table()
2385
    link_to_local	Set to 1 if caller should link this table to local list
2386
2387
  NOTES
2388
    We assume that first tables in both lists is the same table or the local
2389
    list is empty.
2390
2391
  RETURN
2392
    0	If 'query_tables' == 0
2393
    unlinked table
2394
      In this case link_to_local is set.
2395
2396
*/
2397
TABLE_LIST *st_lex::unlink_first_table(bool *link_to_local)
2398
{
2399
  TABLE_LIST *first;
2400
  if ((first= query_tables))
2401
  {
2402
    /*
2403
      Exclude from global table list
2404
    */
2405
    if ((query_tables= query_tables->next_global))
2406
      query_tables->prev_global= &query_tables;
2407
    else
2408
      query_tables_last= &query_tables;
2409
    first->next_global= 0;
2410
2411
    /*
2412
      and from local list if it is not empty
2413
    */
2414
    if ((*link_to_local= test(select_lex.table_list.first)))
2415
    {
2416
      select_lex.context.table_list= 
2417
        select_lex.context.first_name_resolution_table= first->next_local;
2418
      select_lex.table_list.first= (uchar*) (first->next_local);
2419
      select_lex.table_list.elements--;	//safety
2420
      first->next_local= 0;
2421
      /*
2422
        Ensure that the global list has the same first table as the local
2423
        list.
2424
      */
2425
      first_lists_tables_same();
2426
    }
2427
  }
2428
  return first;
2429
}
2430
2431
2432
/*
2433
  Bring first local table of first most outer select to first place in global
2434
  table list
2435
2436
  SYNOPSYS
2437
     st_lex::first_lists_tables_same()
2438
2439
  NOTES
2440
    In many cases (for example, usual INSERT/DELETE/...) the first table of
2441
    main SELECT_LEX have special meaning => check that it is the first table
2442
    in global list and re-link to be first in the global list if it is
2443
    necessary.  We need such re-linking only for queries with sub-queries in
2444
    the select list, as only in this case tables of sub-queries will go to
2445
    the global list first.
2446
*/
2447
2448
void st_lex::first_lists_tables_same()
2449
{
2450
  TABLE_LIST *first_table= (TABLE_LIST*) select_lex.table_list.first;
2451
  if (query_tables != first_table && first_table != 0)
2452
  {
2453
    TABLE_LIST *next;
2454
    if (query_tables_last == &first_table->next_global)
2455
      query_tables_last= first_table->prev_global;
2456
2457
    if ((next= *first_table->prev_global= first_table->next_global))
2458
      next->prev_global= first_table->prev_global;
2459
    /* include in new place */
2460
    first_table->next_global= query_tables;
2461
    /*
2462
       We are sure that query_tables is not 0, because first_table was not
2463
       first table in the global list => we can use
2464
       query_tables->prev_global without check of query_tables
2465
    */
2466
    query_tables->prev_global= &first_table->next_global;
2467
    first_table->prev_global= &query_tables;
2468
    query_tables= first_table;
2469
  }
2470
}
2471
2472
2473
/*
2474
  Link table back that was unlinked with unlink_first_table()
2475
2476
  SYNOPSIS
2477
    link_first_table_back()
2478
    link_to_local	do we need link this table to local
2479
2480
  RETURN
2481
    global list
2482
*/
2483
2484
void st_lex::link_first_table_back(TABLE_LIST *first,
2485
				   bool link_to_local)
2486
{
2487
  if (first)
2488
  {
2489
    if ((first->next_global= query_tables))
2490
      query_tables->prev_global= &first->next_global;
2491
    else
2492
      query_tables_last= &first->next_global;
2493
    query_tables= first;
2494
2495
    if (link_to_local)
2496
    {
2497
      first->next_local= (TABLE_LIST*) select_lex.table_list.first;
2498
      select_lex.context.table_list= first;
2499
      select_lex.table_list.first= (uchar*) first;
2500
      select_lex.table_list.elements++;	//safety
2501
    }
2502
  }
2503
}
2504
2505
2506
2507
/*
2508
  cleanup lex for case when we open table by table for processing
2509
2510
  SYNOPSIS
2511
    st_lex::cleanup_after_one_table_open()
2512
2513
  NOTE
2514
    This method is mostly responsible for cleaning up of selects lists and
2515
    derived tables state. To rollback changes in Query_tables_list one has
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2516
    to call Query_tables_list::reset_query_tables_list(false).
1 by brian
clean slate
2517
*/
2518
2519
void st_lex::cleanup_after_one_table_open()
2520
{
2521
  /*
2522
    thd->lex->derived_tables & additional units may be set if we open
2523
    a view. It is necessary to clear thd->lex->derived_tables flag
2524
    to prevent processing of derived tables during next open_and_lock_tables
2525
    if next table is a real table and cleanup & remove underlying units
2526
    NOTE: all units will be connected to thd->lex->select_lex, because we
2527
    have not UNION on most upper level.
2528
    */
2529
  if (all_selects_list != &select_lex)
2530
  {
2531
    derived_tables= 0;
2532
    /* cleunup underlying units (units of VIEW) */
2533
    for (SELECT_LEX_UNIT *un= select_lex.first_inner_unit();
2534
         un;
2535
         un= un->next_unit())
2536
      un->cleanup();
2537
    /* reduce all selects list to default state */
2538
    all_selects_list= &select_lex;
2539
    /* remove underlying units (units of VIEW) subtree */
2540
    select_lex.cut_subtree();
2541
  }
2542
}
2543
2544
2545
/*
2546
  Save current state of Query_tables_list for this LEX, and prepare it
2547
  for processing of new statemnt.
2548
2549
  SYNOPSIS
2550
    reset_n_backup_query_tables_list()
2551
      backup  Pointer to Query_tables_list instance to be used for backup
2552
*/
2553
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
2554
void st_lex::reset_n_backup_query_tables_list(Query_tables_list *backup __attribute__((unused)))
1 by brian
clean slate
2555
{
2556
}
2557
2558
2559
/*
2560
  Restore state of Query_tables_list for this LEX from backup.
2561
2562
  SYNOPSIS
2563
    restore_backup_query_tables_list()
2564
      backup  Pointer to Query_tables_list instance used for backup
2565
*/
2566
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
2567
void st_lex::restore_backup_query_tables_list(Query_tables_list *backup __attribute__((unused)))
1 by brian
clean slate
2568
{
2569
}
2570
2571
2572
/*
2573
  Checks for usage of routines and/or tables in a parsed statement
2574
2575
  SYNOPSIS
2576
    st_lex:table_or_sp_used()
2577
2578
  RETURN
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2579
    false  No routines and tables used
2580
    true   Either or both routines and tables are used.
1 by brian
clean slate
2581
*/
2582
2583
bool st_lex::table_or_sp_used()
2584
{
2585
  if (sroutines.records || query_tables)
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2586
    return(true);
1 by brian
clean slate
2587
51.1.52 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2588
  return(false);
1 by brian
clean slate
2589
}
2590
2591
2592
/*
2593
  Do end-of-prepare fixup for list of tables and their merge-VIEWed tables
2594
2595
  SYNOPSIS
2596
    fix_prepare_info_in_table_list()
2597
      thd  Thread handle
2598
      tbl  List of tables to process
2599
2600
  DESCRIPTION
2601
    Perform end-end-of prepare fixup for list of tables, if any of the tables
2602
    is a merge-algorithm VIEW, recursively fix up its underlying tables as
2603
    well.
2604
2605
*/
2606
2607
static void fix_prepare_info_in_table_list(THD *thd, TABLE_LIST *tbl)
2608
{
2609
  for (; tbl; tbl= tbl->next_local)
2610
  {
2611
    if (tbl->on_expr)
2612
    {
2613
      tbl->prep_on_expr= tbl->on_expr;
2614
      tbl->on_expr= tbl->on_expr->copy_andor_structure(thd);
2615
    }
2616
    fix_prepare_info_in_table_list(thd, tbl->merge_underlying_list);
2617
  }
2618
}
2619
2620
2621
/*
2622
  There are st_select_lex::add_table_to_list &
2623
  st_select_lex::set_lock_for_tables are in sql_parse.cc
2624
2625
  st_select_lex::print is in sql_select.cc
2626
2627
  st_select_lex_unit::prepare, st_select_lex_unit::exec,
2628
  st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
2629
  st_select_lex_unit::change_result
2630
  are in sql_union.cc
2631
*/
2632
2633
/*
2634
  Sets the kind of hints to be added by the calls to add_index_hint().
2635
2636
  SYNOPSIS
2637
    set_index_hint_type()
2638
      type_arg     The kind of hints to be added from now on.
2639
      clause       The clause to use for hints to be added from now on.
2640
2641
  DESCRIPTION
2642
    Used in filling up the tagged hints list.
2643
    This list is filled by first setting the kind of the hint as a 
2644
    context variable and then adding hints of the current kind.
2645
    Then the context variable index_hint_type can be reset to the
2646
    next hint type.
2647
*/
2648
void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
2649
                                        index_clause_map clause)
2650
{ 
2651
  current_index_hint_type= type_arg;
2652
  current_index_hint_clause= clause;
2653
}
2654
2655
2656
/*
2657
  Makes an array to store index usage hints (ADD/FORCE/IGNORE INDEX).
2658
2659
  SYNOPSIS
2660
    alloc_index_hints()
2661
      thd         current thread.
2662
*/
2663
2664
void st_select_lex::alloc_index_hints (THD *thd)
2665
{ 
2666
  index_hints= new (thd->mem_root) List<Index_hint>(); 
2667
}
2668
2669
2670
2671
/*
2672
  adds an element to the array storing index usage hints 
2673
  (ADD/FORCE/IGNORE INDEX).
2674
2675
  SYNOPSIS
2676
    add_index_hint()
2677
      thd         current thread.
2678
      str         name of the index.
2679
      length      number of characters in str.
2680
2681
  RETURN VALUE
2682
    0 on success, non-zero otherwise
2683
*/
2684
bool st_select_lex::add_index_hint (THD *thd, char *str, uint length)
2685
{
2686
  return index_hints->push_front (new (thd->mem_root) 
2687
                                 Index_hint(current_index_hint_type,
2688
                                            current_index_hint_clause,
2689
                                            str, length));
2690
}