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