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