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