~otto/maria/5.5.37-0ubuntu0.14.04.1

« back to all changes in this revision

Viewing changes to .pc/62_sql_yacc.yy_incompatible_with_bison_3_mdev4902.diff/sql/sql_lex.cc

  • Committer: Package Import Robot
  • Author(s): Chris J Arges
  • Date: 2014-01-10 14:16:25 UTC
  • Revision ID: package-import@ubuntu.com-20140110141625-7ztkdqjl2az4v26u
Tags: 5.5.32-1ubuntu1
d/p/62_sql_yacc.yy_incompatible_with_bison_3_mdev4902.diff:
Fix FTBFS due to bison 3.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* Copyright (c) 2000, 2013, Oracle and/or its affiliates.
 
2
   Copyright (c) 2009, 2013, Monty Program Ab.
 
3
 
 
4
   This program is free software; you can redistribute it and/or modify
 
5
   it under the terms of the GNU General Public License as published by
 
6
   the Free Software Foundation; version 2 of the License.
 
7
 
 
8
   This program is distributed in the hope that it will be useful,
 
9
   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
   GNU General Public License for more details.
 
12
 
 
13
   You should have received a copy of the GNU General Public License
 
14
   along with this program; if not, write to the Free Software
 
15
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
 
16
 
 
17
 
 
18
/* A lexical scanner on a temporary buffer with a yacc interface */
 
19
 
 
20
#define MYSQL_LEX 1
 
21
#include "sql_priv.h"
 
22
#include "unireg.h"                    // REQUIRED: for other includes
 
23
#include "sql_class.h"                          // sql_lex.h: SQLCOM_END
 
24
#include "sql_lex.h"
 
25
#include "sql_parse.h"                          // add_to_list
 
26
#include "item_create.h"
 
27
#include <m_ctype.h>
 
28
#include <hash.h>
 
29
#include "sp_head.h"
 
30
#include "sp.h"
 
31
#include "sql_select.h"
 
32
 
 
33
static int lex_one_token(void *arg, void *yythd);
 
34
 
 
35
/*
 
36
  We are using pointer to this variable for distinguishing between assignment
 
37
  to NEW row field (when parsing trigger definition) and structured variable.
 
38
*/
 
39
 
 
40
sys_var *trg_new_row_fake_var= (sys_var*) 0x01;
 
41
 
 
42
/**
 
43
  LEX_STRING constant for null-string to be used in parser and other places.
 
44
*/
 
45
const LEX_STRING null_lex_str= {NULL, 0};
 
46
const LEX_STRING empty_lex_str= {(char *) "", 0};
 
47
/**
 
48
  @note The order of the elements of this array must correspond to
 
49
  the order of elements in enum_binlog_stmt_unsafe.
 
50
*/
 
51
const int
 
52
Query_tables_list::binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT] =
 
53
{
 
54
  ER_BINLOG_UNSAFE_LIMIT,
 
55
  ER_BINLOG_UNSAFE_INSERT_DELAYED,
 
56
  ER_BINLOG_UNSAFE_SYSTEM_TABLE,
 
57
  ER_BINLOG_UNSAFE_AUTOINC_COLUMNS,
 
58
  ER_BINLOG_UNSAFE_UDF,
 
59
  ER_BINLOG_UNSAFE_SYSTEM_VARIABLE,
 
60
  ER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
 
61
  ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS,
 
62
  ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
 
63
  ER_BINLOG_UNSAFE_MIXED_STATEMENT,
 
64
  ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT,
 
65
  ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE,
 
66
  ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT,
 
67
  ER_BINLOG_UNSAFE_REPLACE_SELECT,
 
68
  ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT,
 
69
  ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT,
 
70
  ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC,
 
71
  ER_BINLOG_UNSAFE_UPDATE_IGNORE,
 
72
  ER_BINLOG_UNSAFE_INSERT_TWO_KEYS,
 
73
  ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST
 
74
};
 
75
 
 
76
 
 
77
/* Longest standard keyword name */
 
78
 
 
79
#define TOCK_NAME_LENGTH 24
 
80
 
 
81
/*
 
82
  The following data is based on the latin1 character set, and is only
 
83
  used when comparing keywords
 
84
*/
 
85
 
 
86
static uchar to_upper_lex[]=
 
87
{
 
88
    0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
 
89
   16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
 
90
   32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
 
91
   48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
 
92
   64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
 
93
   80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
 
94
   96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
 
95
   80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127,
 
96
  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
 
97
  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
 
98
  160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
 
99
  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
 
100
  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
 
101
  208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
 
102
  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
 
103
  208,209,210,211,212,213,214,247,216,217,218,219,220,221,222,255
 
104
};
 
105
 
 
106
/* 
 
107
  Names of the index hints (for error messages). Keep in sync with 
 
108
  index_hint_type 
 
109
*/
 
110
 
 
111
const char * index_hint_type_name[] =
 
112
{
 
113
  "IGNORE INDEX", 
 
114
  "USE INDEX", 
 
115
  "FORCE INDEX"
 
116
};
 
117
 
 
118
inline int lex_casecmp(const char *s, const char *t, uint len)
 
119
{
 
120
  while (len-- != 0 &&
 
121
         to_upper_lex[(uchar) *s++] == to_upper_lex[(uchar) *t++]) ;
 
122
  return (int) len+1;
 
123
}
 
124
 
 
125
#include <lex_hash.h>
 
126
 
 
127
 
 
128
void lex_init(void)
 
129
{
 
130
  uint i;
 
131
  DBUG_ENTER("lex_init");
 
132
  for (i=0 ; i < array_elements(symbols) ; i++)
 
133
    symbols[i].length=(uchar) strlen(symbols[i].name);
 
134
  for (i=0 ; i < array_elements(sql_functions) ; i++)
 
135
    sql_functions[i].length=(uchar) strlen(sql_functions[i].name);
 
136
 
 
137
  DBUG_VOID_RETURN;
 
138
}
 
139
 
 
140
 
 
141
void lex_free(void)
 
142
{                                       // Call this when daemon ends
 
143
  DBUG_ENTER("lex_free");
 
144
  DBUG_VOID_RETURN;
 
145
}
 
146
 
 
147
/**
 
148
  Initialize lex object for use in fix_fields and parsing.
 
149
 
 
150
  SYNOPSIS
 
151
    init_lex_with_single_table()
 
152
    @param thd                 The thread object
 
153
    @param table               The table object
 
154
  @return Operation status
 
155
    @retval TRUE                An error occurred, memory allocation error
 
156
    @retval FALSE               Ok
 
157
 
 
158
  DESCRIPTION
 
159
    This function is used to initialize a lex object on the
 
160
    stack for use by fix_fields and for parsing. In order to
 
161
    work properly it also needs to initialize the
 
162
    Name_resolution_context object of the lexer.
 
163
    Finally it needs to set a couple of variables to ensure
 
164
    proper functioning of fix_fields.
 
165
*/
 
166
 
 
167
int
 
168
init_lex_with_single_table(THD *thd, TABLE *table, LEX *lex)
 
169
{
 
170
  TABLE_LIST *table_list;
 
171
  Table_ident *table_ident;
 
172
  SELECT_LEX *select_lex= &lex->select_lex;
 
173
  Name_resolution_context *context= &select_lex->context;
 
174
  /*
 
175
    We will call the parser to create a part_info struct based on the
 
176
    partition string stored in the frm file.
 
177
    We will use a local lex object for this purpose. However we also
 
178
    need to set the Name_resolution_object for this lex object. We
 
179
    do this by using add_table_to_list where we add the table that
 
180
    we're working with to the Name_resolution_context.
 
181
  */
 
182
  thd->lex= lex;
 
183
  lex_start(thd);
 
184
  context->init();
 
185
  if ((!(table_ident= new Table_ident(thd,
 
186
                                      table->s->table_name,
 
187
                                      table->s->db, TRUE))) ||
 
188
      (!(table_list= select_lex->add_table_to_list(thd,
 
189
                                                   table_ident,
 
190
                                                   NULL,
 
191
                                                   0))))
 
192
    return TRUE;
 
193
  context->resolve_in_table_list_only(table_list);
 
194
  lex->use_only_table_context= TRUE;
 
195
  lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VCOL_EXPR;
 
196
  select_lex->cur_pos_in_select_list= UNDEF_POS;
 
197
  table->map= 1; //To ensure correct calculation of const item
 
198
  table->get_fields_in_item_tree= TRUE;
 
199
  table_list->table= table;
 
200
  return FALSE;
 
201
}
 
202
 
 
203
/**
 
204
  End use of local lex with single table
 
205
 
 
206
  SYNOPSIS
 
207
    end_lex_with_single_table()
 
208
    @param thd               The thread object
 
209
    @param table             The table object
 
210
    @param old_lex           The real lex object connected to THD
 
211
 
 
212
  DESCRIPTION
 
213
    This function restores the real lex object after calling
 
214
    init_lex_with_single_table and also restores some table
 
215
    variables temporarily set.
 
216
*/
 
217
 
 
218
void
 
219
end_lex_with_single_table(THD *thd, TABLE *table, LEX *old_lex)
 
220
{
 
221
  LEX *lex= thd->lex;
 
222
  table->map= 0;
 
223
  table->get_fields_in_item_tree= FALSE;
 
224
  lex_end(lex);
 
225
  thd->lex= old_lex;
 
226
}
 
227
 
 
228
 
 
229
void
 
230
st_parsing_options::reset()
 
231
{
 
232
  allows_variable= TRUE;
 
233
  allows_select_into= TRUE;
 
234
  allows_select_procedure= TRUE;
 
235
  allows_derived= TRUE;
 
236
}
 
237
 
 
238
 
 
239
/**
 
240
  Perform initialization of Lex_input_stream instance.
 
241
 
 
242
  Basically, a buffer for pre-processed query. This buffer should be large
 
243
  enough to keep multi-statement query. The allocation is done once in
 
244
  Lex_input_stream::init() in order to prevent memory pollution when
 
245
  the server is processing large multi-statement queries.
 
246
*/
 
247
 
 
248
bool Lex_input_stream::init(THD *thd,
 
249
                            char* buff,
 
250
                            unsigned int length)
 
251
{
 
252
  DBUG_EXECUTE_IF("bug42064_simulate_oom",
 
253
                  DBUG_SET("+d,simulate_out_of_memory"););
 
254
 
 
255
  m_cpp_buf= (char*) thd->alloc(length + 1);
 
256
 
 
257
  DBUG_EXECUTE_IF("bug42064_simulate_oom",
 
258
                  DBUG_SET("-d,bug42064_simulate_oom");); 
 
259
 
 
260
  if (m_cpp_buf == NULL)
 
261
    return TRUE;
 
262
 
 
263
  m_thd= thd;
 
264
  reset(buff, length);
 
265
 
 
266
  return FALSE;
 
267
}
 
268
 
 
269
 
 
270
/**
 
271
  Prepare Lex_input_stream instance state for use for handling next SQL statement.
 
272
 
 
273
  It should be called between two statements in a multi-statement query.
 
274
  The operation resets the input stream to the beginning-of-parse state,
 
275
  but does not reallocate m_cpp_buf.
 
276
*/
 
277
 
 
278
void
 
279
Lex_input_stream::reset(char *buffer, unsigned int length)
 
280
{
 
281
  yylineno= 1;
 
282
  yytoklen= 0;
 
283
  yylval= NULL;
 
284
  lookahead_token= -1;
 
285
  lookahead_yylval= NULL;
 
286
  m_ptr= buffer;
 
287
  m_tok_start= NULL;
 
288
  m_tok_end= NULL;
 
289
  m_end_of_query= buffer + length;
 
290
  m_tok_start_prev= NULL;
 
291
  m_buf= buffer;
 
292
  m_buf_length= length;
 
293
  m_echo= TRUE;
 
294
  m_cpp_tok_start= NULL;
 
295
  m_cpp_tok_start_prev= NULL;
 
296
  m_cpp_tok_end= NULL;
 
297
  m_body_utf8= NULL;
 
298
  m_cpp_utf8_processed_ptr= NULL;
 
299
  next_state= MY_LEX_START;
 
300
  found_semicolon= NULL;
 
301
  ignore_space= test(m_thd->variables.sql_mode & MODE_IGNORE_SPACE);
 
302
  stmt_prepare_mode= FALSE;
 
303
  multi_statements= TRUE;
 
304
  in_comment=NO_COMMENT;
 
305
  m_underscore_cs= NULL;
 
306
  m_cpp_ptr= m_cpp_buf;
 
307
}
 
308
 
 
309
 
 
310
/**
 
311
  The operation is called from the parser in order to
 
312
  1) designate the intention to have utf8 body;
 
313
  1) Indicate to the lexer that we will need a utf8 representation of this
 
314
     statement;
 
315
  2) Determine the beginning of the body.
 
316
 
 
317
  @param thd        Thread context.
 
318
  @param begin_ptr  Pointer to the start of the body in the pre-processed
 
319
                    buffer.
 
320
*/
 
321
 
 
322
void Lex_input_stream::body_utf8_start(THD *thd, const char *begin_ptr)
 
323
{
 
324
  DBUG_ASSERT(begin_ptr);
 
325
  DBUG_ASSERT(m_cpp_buf <= begin_ptr && begin_ptr <= m_cpp_buf + m_buf_length);
 
326
 
 
327
  uint body_utf8_length=
 
328
    (m_buf_length / thd->variables.character_set_client->mbminlen) *
 
329
    my_charset_utf8_bin.mbmaxlen;
 
330
 
 
331
  m_body_utf8= (char *) thd->alloc(body_utf8_length + 1);
 
332
  m_body_utf8_ptr= m_body_utf8;
 
333
  *m_body_utf8_ptr= 0;
 
334
 
 
335
  m_cpp_utf8_processed_ptr= begin_ptr;
 
336
}
 
337
 
 
338
/**
 
339
  @brief The operation appends unprocessed part of pre-processed buffer till
 
340
  the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to end_ptr.
 
341
 
 
342
  The idea is that some tokens in the pre-processed buffer (like character
 
343
  set introducers) should be skipped.
 
344
 
 
345
  Example:
 
346
    CPP buffer: SELECT 'str1', _latin1 'str2';
 
347
    m_cpp_utf8_processed_ptr -- points at the "SELECT ...";
 
348
    In order to skip "_latin1", the following call should be made:
 
349
      body_utf8_append(<pointer to "_latin1 ...">, <pointer to " 'str2'...">)
 
350
 
 
351
  @param ptr      Pointer in the pre-processed buffer, which specifies the
 
352
                  end of the chunk, which should be appended to the utf8
 
353
                  body.
 
354
  @param end_ptr  Pointer in the pre-processed buffer, to which
 
355
                  m_cpp_utf8_processed_ptr will be set in the end of the
 
356
                  operation.
 
357
*/
 
358
 
 
359
void Lex_input_stream::body_utf8_append(const char *ptr,
 
360
                                        const char *end_ptr)
 
361
{
 
362
  DBUG_ASSERT(m_cpp_buf <= ptr && ptr <= m_cpp_buf + m_buf_length);
 
363
  DBUG_ASSERT(m_cpp_buf <= end_ptr && end_ptr <= m_cpp_buf + m_buf_length);
 
364
 
 
365
  if (!m_body_utf8)
 
366
    return;
 
367
 
 
368
  if (m_cpp_utf8_processed_ptr >= ptr)
 
369
    return;
 
370
 
 
371
  int bytes_to_copy= ptr - m_cpp_utf8_processed_ptr;
 
372
 
 
373
  memcpy(m_body_utf8_ptr, m_cpp_utf8_processed_ptr, bytes_to_copy);
 
374
  m_body_utf8_ptr += bytes_to_copy;
 
375
  *m_body_utf8_ptr= 0;
 
376
 
 
377
  m_cpp_utf8_processed_ptr= end_ptr;
 
378
}
 
379
 
 
380
/**
 
381
  The operation appends unprocessed part of the pre-processed buffer till
 
382
  the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to ptr.
 
383
 
 
384
  @param ptr  Pointer in the pre-processed buffer, which specifies the end
 
385
              of the chunk, which should be appended to the utf8 body.
 
386
*/
 
387
 
 
388
void Lex_input_stream::body_utf8_append(const char *ptr)
 
389
{
 
390
  body_utf8_append(ptr, ptr);
 
391
}
 
392
 
 
393
/**
 
394
  The operation converts the specified text literal to the utf8 and appends
 
395
  the result to the utf8-body.
 
396
 
 
397
  @param thd      Thread context.
 
398
  @param txt      Text literal.
 
399
  @param txt_cs   Character set of the text literal.
 
400
  @param end_ptr  Pointer in the pre-processed buffer, to which
 
401
                  m_cpp_utf8_processed_ptr will be set in the end of the
 
402
                  operation.
 
403
*/
 
404
 
 
405
void Lex_input_stream::body_utf8_append_literal(THD *thd,
 
406
                                                const LEX_STRING *txt,
 
407
                                                CHARSET_INFO *txt_cs,
 
408
                                                const char *end_ptr)
 
409
{
 
410
  if (!m_cpp_utf8_processed_ptr)
 
411
    return;
 
412
 
 
413
  LEX_STRING utf_txt;
 
414
 
 
415
  if (!my_charset_same(txt_cs, &my_charset_utf8_general_ci))
 
416
  {
 
417
    thd->convert_string(&utf_txt,
 
418
                        &my_charset_utf8_general_ci,
 
419
                        txt->str, (uint) txt->length,
 
420
                        txt_cs);
 
421
  }
 
422
  else
 
423
  {
 
424
    utf_txt.str= txt->str;
 
425
    utf_txt.length= txt->length;
 
426
  }
 
427
 
 
428
  /* NOTE: utf_txt.length is in bytes, not in symbols. */
 
429
 
 
430
  memcpy(m_body_utf8_ptr, utf_txt.str, utf_txt.length);
 
431
  m_body_utf8_ptr += utf_txt.length;
 
432
  *m_body_utf8_ptr= 0;
 
433
 
 
434
  m_cpp_utf8_processed_ptr= end_ptr;
 
435
}
 
436
 
 
437
 
 
438
/*
 
439
  This is called before every query that is to be parsed.
 
440
  Because of this, it's critical to not do too much things here.
 
441
  (We already do too much here)
 
442
*/
 
443
 
 
444
void lex_start(THD *thd)
 
445
{
 
446
  LEX *lex= thd->lex;
 
447
  DBUG_ENTER("lex_start");
 
448
 
 
449
  lex->thd= lex->unit.thd= thd;
 
450
 
 
451
  lex->context_stack.empty();
 
452
  lex->unit.init_query();
 
453
  lex->unit.init_select();
 
454
  /* 'parent_lex' is used in init_query() so it must be before it. */
 
455
  lex->select_lex.parent_lex= lex;
 
456
  lex->select_lex.init_query();
 
457
  lex->value_list.empty();
 
458
  lex->update_list.empty();
 
459
  lex->set_var_list.empty();
 
460
  lex->param_list.empty();
 
461
  lex->view_list.empty();
 
462
  lex->prepared_stmt_params.empty();
 
463
  lex->auxiliary_table_list.empty();
 
464
  lex->unit.next= lex->unit.master=
 
465
    lex->unit.link_next= lex->unit.return_to= 0;
 
466
  lex->unit.prev= lex->unit.link_prev= 0;
 
467
  lex->unit.slave= lex->unit.global_parameters= lex->current_select=
 
468
    lex->all_selects_list= &lex->select_lex;
 
469
  lex->select_lex.master= &lex->unit;
 
470
  lex->select_lex.prev= &lex->unit.slave;
 
471
  lex->select_lex.link_next= lex->select_lex.slave= lex->select_lex.next= 0;
 
472
  lex->select_lex.link_prev= (st_select_lex_node**)&(lex->all_selects_list);
 
473
  lex->select_lex.options= 0;
 
474
  lex->select_lex.sql_cache= SELECT_LEX::SQL_CACHE_UNSPECIFIED;
 
475
  lex->select_lex.init_order();
 
476
  lex->select_lex.group_list.empty();
 
477
  if (lex->select_lex.group_list_ptrs)
 
478
    lex->select_lex.group_list_ptrs->clear();
 
479
  lex->describe= 0;
 
480
  lex->subqueries= FALSE;
 
481
  lex->context_analysis_only= 0;
 
482
  lex->derived_tables= 0;
 
483
  lex->safe_to_cache_query= 1;
 
484
  lex->parsing_options.reset();
 
485
  lex->empty_field_list_on_rset= 0;
 
486
  lex->select_lex.select_number= 1;
 
487
  lex->length=0;
 
488
  lex->part_info= 0;
 
489
  lex->select_lex.in_sum_expr=0;
 
490
  lex->select_lex.ftfunc_list_alloc.empty();
 
491
  lex->select_lex.ftfunc_list= &lex->select_lex.ftfunc_list_alloc;
 
492
  lex->select_lex.group_list.empty();
 
493
  lex->select_lex.order_list.empty();
 
494
  lex->duplicates= DUP_ERROR;
 
495
  lex->ignore= 0;
 
496
  lex->spname= NULL;
 
497
  lex->sphead= NULL;
 
498
  lex->spcont= NULL;
 
499
  lex->m_stmt= NULL;
 
500
  lex->proc_list.first= 0;
 
501
  lex->escape_used= FALSE;
 
502
  lex->query_tables= 0;
 
503
  lex->reset_query_tables_list(FALSE);
 
504
  lex->expr_allows_subselect= TRUE;
 
505
  lex->use_only_table_context= FALSE;
 
506
  lex->parse_vcol_expr= FALSE;
 
507
 
 
508
  lex->name.str= 0;
 
509
  lex->name.length= 0;
 
510
  lex->event_parse_data= NULL;
 
511
  lex->profile_options= PROFILE_NONE;
 
512
  lex->nest_level=0 ;
 
513
  lex->select_lex.nest_level_base= &lex->unit;
 
514
  lex->allow_sum_func= 0;
 
515
  lex->in_sum_func= NULL;
 
516
  /*
 
517
    ok, there must be a better solution for this, long-term
 
518
    I tried "bzero" in the sql_yacc.yy code, but that for
 
519
    some reason made the values zero, even if they were set
 
520
  */
 
521
  lex->server_options.server_name= 0;
 
522
  lex->server_options.server_name_length= 0;
 
523
  lex->server_options.host= 0;
 
524
  lex->server_options.db= 0;
 
525
  lex->server_options.username= 0;
 
526
  lex->server_options.password= 0;
 
527
  lex->server_options.scheme= 0;
 
528
  lex->server_options.socket= 0;
 
529
  lex->server_options.owner= 0;
 
530
  lex->server_options.port= -1;
 
531
 
 
532
  lex->is_lex_started= TRUE;
 
533
  lex->used_tables= 0;
 
534
  lex->reset_slave_info.all= false;
 
535
  lex->limit_rows_examined= 0;
 
536
  lex->limit_rows_examined_cnt= ULONGLONG_MAX;
 
537
  DBUG_VOID_RETURN;
 
538
}
 
539
 
 
540
void lex_end(LEX *lex)
 
541
{
 
542
  DBUG_ENTER("lex_end");
 
543
  DBUG_PRINT("enter", ("lex: 0x%lx", (long) lex));
 
544
 
 
545
  /* release used plugins */
 
546
  if (lex->plugins.elements) /* No function call and no mutex if no plugins. */
 
547
  {
 
548
    plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer, 
 
549
                       lex->plugins.elements);
 
550
  }
 
551
  reset_dynamic(&lex->plugins);
 
552
 
 
553
  delete lex->sphead;
 
554
  lex->sphead= NULL;
 
555
 
 
556
  lex->mi.reset();
 
557
 
 
558
  DBUG_VOID_RETURN;
 
559
}
 
560
 
 
561
Yacc_state::~Yacc_state()
 
562
{
 
563
  if (yacc_yyss)
 
564
  {
 
565
    my_free(yacc_yyss);
 
566
    my_free(yacc_yyvs);
 
567
  }
 
568
}
 
569
 
 
570
static int find_keyword(Lex_input_stream *lip, uint len, bool function)
 
571
{
 
572
  const char *tok= lip->get_tok_start();
 
573
 
 
574
  SYMBOL *symbol= get_hash_symbol(tok, len, function);
 
575
  if (symbol)
 
576
  {
 
577
    lip->yylval->symbol.symbol=symbol;
 
578
    lip->yylval->symbol.str= (char*) tok;
 
579
    lip->yylval->symbol.length=len;
 
580
 
 
581
    if ((symbol->tok == NOT_SYM) &&
 
582
        (lip->m_thd->variables.sql_mode & MODE_HIGH_NOT_PRECEDENCE))
 
583
      return NOT2_SYM;
 
584
    if ((symbol->tok == OR_OR_SYM) &&
 
585
        !(lip->m_thd->variables.sql_mode & MODE_PIPES_AS_CONCAT))
 
586
      return OR2_SYM;
 
587
 
 
588
    return symbol->tok;
 
589
  }
 
590
  return 0;
 
591
}
 
592
 
 
593
/*
 
594
  Check if name is a keyword
 
595
 
 
596
  SYNOPSIS
 
597
    is_keyword()
 
598
    name      checked name (must not be empty)
 
599
    len       length of checked name
 
600
 
 
601
  RETURN VALUES
 
602
    0         name is a keyword
 
603
    1         name isn't a keyword
 
604
*/
 
605
 
 
606
bool is_keyword(const char *name, uint len)
 
607
{
 
608
  DBUG_ASSERT(len != 0);
 
609
  return get_hash_symbol(name,len,0)!=0;
 
610
}
 
611
 
 
612
/**
 
613
  Check if name is a sql function
 
614
 
 
615
    @param name      checked name
 
616
 
 
617
    @return is this a native function or not
 
618
    @retval 0         name is a function
 
619
    @retval 1         name isn't a function
 
620
*/
 
621
 
 
622
bool is_lex_native_function(const LEX_STRING *name)
 
623
{
 
624
  DBUG_ASSERT(name != NULL);
 
625
  return (get_hash_symbol(name->str, (uint) name->length, 1) != 0);
 
626
}
 
627
 
 
628
/* make a copy of token before ptr and set yytoklen */
 
629
 
 
630
static LEX_STRING get_token(Lex_input_stream *lip, uint skip, uint length)
 
631
{
 
632
  LEX_STRING tmp;
 
633
  lip->yyUnget();                       // ptr points now after last token char
 
634
  tmp.length=lip->yytoklen=length;
 
635
  tmp.str= lip->m_thd->strmake(lip->get_tok_start() + skip, tmp.length);
 
636
 
 
637
  lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
 
638
  lip->m_cpp_text_end= lip->m_cpp_text_start + tmp.length;
 
639
 
 
640
  return tmp;
 
641
}
 
642
 
 
643
/* 
 
644
 todo: 
 
645
   There are no dangerous charsets in mysql for function 
 
646
   get_quoted_token yet. But it should be fixed in the 
 
647
   future to operate multichar strings (like ucs2)
 
648
*/
 
649
 
 
650
static LEX_STRING get_quoted_token(Lex_input_stream *lip,
 
651
                                   uint skip,
 
652
                                   uint length, char quote)
 
653
{
 
654
  LEX_STRING tmp;
 
655
  const char *from, *end;
 
656
  char *to;
 
657
  lip->yyUnget();                       // ptr points now after last token char
 
658
  tmp.length= lip->yytoklen=length;
 
659
  tmp.str=(char*) lip->m_thd->alloc(tmp.length+1);
 
660
  from= lip->get_tok_start() + skip;
 
661
  to= tmp.str;
 
662
  end= to+length;
 
663
 
 
664
  lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
 
665
  lip->m_cpp_text_end= lip->m_cpp_text_start + length;
 
666
 
 
667
  for ( ; to != end; )
 
668
  {
 
669
    if ((*to++= *from++) == quote)
 
670
    {
 
671
      from++;                                   // Skip double quotes
 
672
      lip->m_cpp_text_start++;
 
673
    }
 
674
  }
 
675
  *to= 0;                                       // End null for safety
 
676
  return tmp;
 
677
}
 
678
 
 
679
 
 
680
/*
 
681
  Return an unescaped text literal without quotes
 
682
  Fix sometimes to do only one scan of the string
 
683
*/
 
684
 
 
685
static char *get_text(Lex_input_stream *lip, int pre_skip, int post_skip)
 
686
{
 
687
  reg1 uchar c,sep;
 
688
  uint found_escape=0;
 
689
  CHARSET_INFO *cs= lip->m_thd->charset();
 
690
 
 
691
  lip->tok_bitmap= 0;
 
692
  sep= lip->yyGetLast();                        // String should end with this
 
693
  while (! lip->eof())
 
694
  {
 
695
    c= lip->yyGet();
 
696
    lip->tok_bitmap|= c;
 
697
#ifdef USE_MB
 
698
    {
 
699
      int l;
 
700
      if (use_mb(cs) &&
 
701
          (l = my_ismbchar(cs,
 
702
                           lip->get_ptr() -1,
 
703
                           lip->get_end_of_query()))) {
 
704
        lip->skip_binary(l-1);
 
705
        continue;
 
706
      }
 
707
    }
 
708
#endif
 
709
    if (c == '\\' &&
 
710
        !(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))
 
711
    {                                   // Escaped character
 
712
      found_escape=1;
 
713
      if (lip->eof())
 
714
        return 0;
 
715
      lip->yySkip();
 
716
    }
 
717
    else if (c == sep)
 
718
    {
 
719
      if (c == lip->yyGet())            // Check if two separators in a row
 
720
      {
 
721
        found_escape=1;                 // duplicate. Remember for delete
 
722
        continue;
 
723
      }
 
724
      else
 
725
        lip->yyUnget();
 
726
 
 
727
      /* Found end. Unescape and return string */
 
728
      const char *str, *end;
 
729
      char *start;
 
730
 
 
731
      str= lip->get_tok_start();
 
732
      end= lip->get_ptr();
 
733
      /* Extract the text from the token */
 
734
      str += pre_skip;
 
735
      end -= post_skip;
 
736
      DBUG_ASSERT(end >= str);
 
737
 
 
738
      if (!(start= (char*) lip->m_thd->alloc((uint) (end-str)+1)))
 
739
        return (char*) "";              // Sql_alloc has set error flag
 
740
 
 
741
      lip->m_cpp_text_start= lip->get_cpp_tok_start() + pre_skip;
 
742
      lip->m_cpp_text_end= lip->get_cpp_ptr() - post_skip;
 
743
 
 
744
      if (!found_escape)
 
745
      {
 
746
        lip->yytoklen=(uint) (end-str);
 
747
        memcpy(start,str,lip->yytoklen);
 
748
        start[lip->yytoklen]=0;
 
749
      }
 
750
      else
 
751
      {
 
752
        char *to;
 
753
 
 
754
        for (to=start ; str != end ; str++)
 
755
        {
 
756
#ifdef USE_MB
 
757
          int l;
 
758
          if (use_mb(cs) &&
 
759
              (l = my_ismbchar(cs, str, end))) {
 
760
              while (l--)
 
761
                  *to++ = *str++;
 
762
              str--;
 
763
              continue;
 
764
          }
 
765
#endif
 
766
          if (!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
 
767
              *str == '\\' && str+1 != end)
 
768
          {
 
769
            switch(*++str) {
 
770
            case 'n':
 
771
              *to++='\n';
 
772
              break;
 
773
            case 't':
 
774
              *to++= '\t';
 
775
              break;
 
776
            case 'r':
 
777
              *to++ = '\r';
 
778
              break;
 
779
            case 'b':
 
780
              *to++ = '\b';
 
781
              break;
 
782
            case '0':
 
783
              *to++= 0;                 // Ascii null
 
784
              break;
 
785
            case 'Z':                   // ^Z must be escaped on Win32
 
786
              *to++='\032';
 
787
              break;
 
788
            case '_':
 
789
            case '%':
 
790
              *to++= '\\';              // remember prefix for wildcard
 
791
              /* Fall through */
 
792
            default:
 
793
              *to++= *str;
 
794
              break;
 
795
            }
 
796
          }
 
797
          else if (*str == sep)
 
798
            *to++= *str++;              // Two ' or "
 
799
          else
 
800
            *to++ = *str;
 
801
        }
 
802
        *to=0;
 
803
        lip->yytoklen=(uint) (to-start);
 
804
      }
 
805
      return start;
 
806
    }
 
807
  }
 
808
  return 0;                                     // unexpected end of query
 
809
}
 
810
 
 
811
 
 
812
/*
 
813
** Calc type of integer; long integer, longlong integer or real.
 
814
** Returns smallest type that match the string.
 
815
** When using unsigned long long values the result is converted to a real
 
816
** because else they will be unexpected sign changes because all calculation
 
817
** is done with longlong or double.
 
818
*/
 
819
 
 
820
static const char *long_str="2147483647";
 
821
static const uint long_len=10;
 
822
static const char *signed_long_str="-2147483648";
 
823
static const char *longlong_str="9223372036854775807";
 
824
static const uint longlong_len=19;
 
825
static const char *signed_longlong_str="-9223372036854775808";
 
826
static const uint signed_longlong_len=19;
 
827
static const char *unsigned_longlong_str="18446744073709551615";
 
828
static const uint unsigned_longlong_len=20;
 
829
 
 
830
static inline uint int_token(const char *str,uint length)
 
831
{
 
832
  if (length < long_len)                        // quick normal case
 
833
    return NUM;
 
834
  bool neg=0;
 
835
 
 
836
  if (*str == '+')                              // Remove sign and pre-zeros
 
837
  {
 
838
    str++; length--;
 
839
  }
 
840
  else if (*str == '-')
 
841
  {
 
842
    str++; length--;
 
843
    neg=1;
 
844
  }
 
845
  while (*str == '0' && length)
 
846
  {
 
847
    str++; length --;
 
848
  }
 
849
  if (length < long_len)
 
850
    return NUM;
 
851
 
 
852
  uint smaller,bigger;
 
853
  const char *cmp;
 
854
  if (neg)
 
855
  {
 
856
    if (length == long_len)
 
857
    {
 
858
      cmp= signed_long_str+1;
 
859
      smaller=NUM;                              // If <= signed_long_str
 
860
      bigger=LONG_NUM;                          // If >= signed_long_str
 
861
    }
 
862
    else if (length < signed_longlong_len)
 
863
      return LONG_NUM;
 
864
    else if (length > signed_longlong_len)
 
865
      return DECIMAL_NUM;
 
866
    else
 
867
    {
 
868
      cmp=signed_longlong_str+1;
 
869
      smaller=LONG_NUM;                         // If <= signed_longlong_str
 
870
      bigger=DECIMAL_NUM;
 
871
    }
 
872
  }
 
873
  else
 
874
  {
 
875
    if (length == long_len)
 
876
    {
 
877
      cmp= long_str;
 
878
      smaller=NUM;
 
879
      bigger=LONG_NUM;
 
880
    }
 
881
    else if (length < longlong_len)
 
882
      return LONG_NUM;
 
883
    else if (length > longlong_len)
 
884
    {
 
885
      if (length > unsigned_longlong_len)
 
886
        return DECIMAL_NUM;
 
887
      cmp=unsigned_longlong_str;
 
888
      smaller=ULONGLONG_NUM;
 
889
      bigger=DECIMAL_NUM;
 
890
    }
 
891
    else
 
892
    {
 
893
      cmp=longlong_str;
 
894
      smaller=LONG_NUM;
 
895
      bigger= ULONGLONG_NUM;
 
896
    }
 
897
  }
 
898
  while (*cmp && *cmp++ == *str++) ;
 
899
  return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
 
900
}
 
901
 
 
902
 
 
903
/**
 
904
  Given a stream that is advanced to the first contained character in 
 
905
  an open comment, consume the comment.  Optionally, if we are allowed, 
 
906
  recurse so that we understand comments within this current comment.
 
907
 
 
908
  At this level, we do not support version-condition comments.  We might 
 
909
  have been called with having just passed one in the stream, though.  In 
 
910
  that case, we probably want to tolerate mundane comments inside.  Thus,
 
911
  the case for recursion.
 
912
 
 
913
  @retval  Whether EOF reached before comment is closed.
 
914
*/
 
915
bool consume_comment(Lex_input_stream *lip, int remaining_recursions_permitted)
 
916
{
 
917
  reg1 uchar c;
 
918
  while (! lip->eof())
 
919
  {
 
920
    c= lip->yyGet();
 
921
 
 
922
    if (remaining_recursions_permitted > 0)
 
923
    {
 
924
      if ((c == '/') && (lip->yyPeek() == '*'))
 
925
      {
 
926
        lip->yySkip(); /* Eat asterisk */
 
927
        consume_comment(lip, remaining_recursions_permitted-1);
 
928
        continue;
 
929
      }
 
930
    }
 
931
 
 
932
    if (c == '*')
 
933
    {
 
934
      if (lip->yyPeek() == '/')
 
935
      {
 
936
        lip->yySkip(); /* Eat slash */
 
937
        return FALSE;
 
938
      }
 
939
    }
 
940
 
 
941
    if (c == '\n')
 
942
      lip->yylineno++;
 
943
  }
 
944
 
 
945
  return TRUE;
 
946
}
 
947
 
 
948
 
 
949
/*
 
950
  MYSQLlex remember the following states from the following MYSQLlex()
 
951
 
 
952
  - MY_LEX_EOQ                  Found end of query
 
953
  - MY_LEX_OPERATOR_OR_IDENT    Last state was an ident, text or number
 
954
                                (which can't be followed by a signed number)
 
955
*/
 
956
 
 
957
int MYSQLlex(void *arg, void *yythd)
 
958
{
 
959
  THD *thd= (THD *)yythd;
 
960
  Lex_input_stream *lip= & thd->m_parser_state->m_lip;
 
961
  YYSTYPE *yylval=(YYSTYPE*) arg;
 
962
  int token;
 
963
 
 
964
  if (lip->lookahead_token >= 0)
 
965
  {
 
966
    /*
 
967
      The next token was already parsed in advance,
 
968
      return it.
 
969
    */
 
970
    token= lip->lookahead_token;
 
971
    lip->lookahead_token= -1;
 
972
    *yylval= *(lip->lookahead_yylval);
 
973
    lip->lookahead_yylval= NULL;
 
974
    return token;
 
975
  }
 
976
 
 
977
  token= lex_one_token(arg, yythd);
 
978
 
 
979
  switch(token) {
 
980
  case WITH:
 
981
    /*
 
982
      Parsing 'WITH' 'ROLLUP' or 'WITH' 'CUBE' requires 2 look ups,
 
983
      which makes the grammar LALR(2).
 
984
      Replace by a single 'WITH_ROLLUP' or 'WITH_CUBE' token,
 
985
      to transform the grammar into a LALR(1) grammar,
 
986
      which sql_yacc.yy can process.
 
987
    */
 
988
    token= lex_one_token(arg, yythd);
 
989
    switch(token) {
 
990
    case CUBE_SYM:
 
991
      return WITH_CUBE_SYM;
 
992
    case ROLLUP_SYM:
 
993
      return WITH_ROLLUP_SYM;
 
994
    default:
 
995
      /*
 
996
        Save the token following 'WITH'
 
997
      */
 
998
      lip->lookahead_yylval= lip->yylval;
 
999
      lip->yylval= NULL;
 
1000
      lip->lookahead_token= token;
 
1001
      return WITH;
 
1002
    }
 
1003
    break;
 
1004
  default:
 
1005
    break;
 
1006
  }
 
1007
 
 
1008
  return token;
 
1009
}
 
1010
 
 
1011
int lex_one_token(void *arg, void *yythd)
 
1012
{
 
1013
  reg1  uchar c;
 
1014
  bool comment_closed;
 
1015
  int   tokval, result_state;
 
1016
  uint length;
 
1017
  enum my_lex_states state;
 
1018
  THD *thd= (THD *)yythd;
 
1019
  Lex_input_stream *lip= & thd->m_parser_state->m_lip;
 
1020
  LEX *lex= thd->lex;
 
1021
  YYSTYPE *yylval=(YYSTYPE*) arg;
 
1022
  CHARSET_INFO *const cs= thd->charset();
 
1023
  const uchar *const state_map= cs->state_map;
 
1024
  const uchar *const ident_map= cs->ident_map;
 
1025
 
 
1026
  LINT_INIT(c);
 
1027
  lip->yylval=yylval;                   // The global state
 
1028
 
 
1029
  lip->start_token();
 
1030
  state=lip->next_state;
 
1031
  lip->next_state=MY_LEX_OPERATOR_OR_IDENT;
 
1032
  for (;;)
 
1033
  {
 
1034
    switch (state) {
 
1035
    case MY_LEX_OPERATOR_OR_IDENT:      // Next is operator or keyword
 
1036
    case MY_LEX_START:                  // Start of token
 
1037
      // Skip starting whitespace
 
1038
      while(state_map[c= lip->yyPeek()] == MY_LEX_SKIP)
 
1039
      {
 
1040
        if (c == '\n')
 
1041
          lip->yylineno++;
 
1042
 
 
1043
        lip->yySkip();
 
1044
      }
 
1045
 
 
1046
      /* Start of real token */
 
1047
      lip->restart_token();
 
1048
      c= lip->yyGet();
 
1049
      state= (enum my_lex_states) state_map[c];
 
1050
      break;
 
1051
    case MY_LEX_ESCAPE:
 
1052
      if (lip->yyGet() == 'N')
 
1053
      {                                 // Allow \N as shortcut for NULL
 
1054
        yylval->lex_str.str=(char*) "\\N";
 
1055
        yylval->lex_str.length=2;
 
1056
        return NULL_SYM;
 
1057
      }
 
1058
      /* Fall through */
 
1059
    case MY_LEX_CHAR:                   // Unknown or single char token
 
1060
    case MY_LEX_SKIP:                   // This should not happen
 
1061
      if (c != ')')
 
1062
        lip->next_state= MY_LEX_START;  // Allow signed numbers
 
1063
      return((int) c);
 
1064
 
 
1065
    case MY_LEX_MINUS_OR_COMMENT:
 
1066
      if (lip->yyPeek() == '-' &&
 
1067
          (my_isspace(cs,lip->yyPeekn(1)) ||
 
1068
           my_iscntrl(cs,lip->yyPeekn(1))))
 
1069
      {
 
1070
        state=MY_LEX_COMMENT;
 
1071
        break;
 
1072
      }
 
1073
      lip->next_state= MY_LEX_START;    // Allow signed numbers
 
1074
      return((int) c);
 
1075
 
 
1076
    case MY_LEX_PLACEHOLDER:
 
1077
      /*
 
1078
        Check for a placeholder: it should not precede a possible identifier
 
1079
        because of binlogging: when a placeholder is replaced with
 
1080
        its value in a query for the binlog, the query must stay
 
1081
        grammatically correct.
 
1082
      */
 
1083
      lip->next_state= MY_LEX_START;    // Allow signed numbers
 
1084
      if (lip->stmt_prepare_mode && !ident_map[(uchar) lip->yyPeek()])
 
1085
        return(PARAM_MARKER);
 
1086
      return((int) c);
 
1087
 
 
1088
    case MY_LEX_COMMA:
 
1089
      lip->next_state= MY_LEX_START;    // Allow signed numbers
 
1090
      /*
 
1091
        Warning:
 
1092
        This is a work around, to make the "remember_name" rule in
 
1093
        sql/sql_yacc.yy work properly.
 
1094
        The problem is that, when parsing "select expr1, expr2",
 
1095
        the code generated by bison executes the *pre* action
 
1096
        remember_name (see select_item) *before* actually parsing the
 
1097
        first token of expr2.
 
1098
      */
 
1099
      lip->restart_token();
 
1100
      return((int) c);
 
1101
 
 
1102
    case MY_LEX_IDENT_OR_NCHAR:
 
1103
      if (lip->yyPeek() != '\'')
 
1104
      {
 
1105
        state= MY_LEX_IDENT;
 
1106
        break;
 
1107
      }
 
1108
      /* Found N'string' */
 
1109
      lip->yySkip();                         // Skip '
 
1110
      if (!(yylval->lex_str.str = get_text(lip, 2, 1)))
 
1111
      {
 
1112
        state= MY_LEX_CHAR;             // Read char by char
 
1113
        break;
 
1114
      }
 
1115
      yylval->lex_str.length= lip->yytoklen;
 
1116
      lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
 
1117
      return(NCHAR_STRING);
 
1118
 
 
1119
    case MY_LEX_IDENT_OR_HEX:
 
1120
      if (lip->yyPeek() == '\'')
 
1121
      {                                 // Found x'hex-number'
 
1122
        state= MY_LEX_HEX_NUMBER;
 
1123
        break;
 
1124
      }
 
1125
    case MY_LEX_IDENT_OR_BIN:
 
1126
      if (lip->yyPeek() == '\'')
 
1127
      {                                 // Found b'bin-number'
 
1128
        state= MY_LEX_BIN_NUMBER;
 
1129
        break;
 
1130
      }
 
1131
    case MY_LEX_IDENT:
 
1132
      const char *start;
 
1133
#if defined(USE_MB) && defined(USE_MB_IDENT)
 
1134
      if (use_mb(cs))
 
1135
      {
 
1136
        result_state= IDENT_QUOTED;
 
1137
        if (my_mbcharlen(cs, lip->yyGetLast()) > 1)
 
1138
        {
 
1139
          int l = my_ismbchar(cs,
 
1140
                              lip->get_ptr() -1,
 
1141
                              lip->get_end_of_query());
 
1142
          if (l == 0) {
 
1143
            state = MY_LEX_CHAR;
 
1144
            continue;
 
1145
          }
 
1146
          lip->skip_binary(l - 1);
 
1147
        }
 
1148
        while (ident_map[c=lip->yyGet()])
 
1149
        {
 
1150
          if (my_mbcharlen(cs, c) > 1)
 
1151
          {
 
1152
            int l;
 
1153
            if ((l = my_ismbchar(cs,
 
1154
                                 lip->get_ptr() -1,
 
1155
                                 lip->get_end_of_query())) == 0)
 
1156
              break;
 
1157
            lip->skip_binary(l-1);
 
1158
          }
 
1159
        }
 
1160
      }
 
1161
      else
 
1162
#endif
 
1163
      {
 
1164
        for (result_state= c;
 
1165
             ident_map[(uchar) (c= lip->yyGet())];
 
1166
             result_state|= c)
 
1167
          ;
 
1168
        /* If there were non-ASCII characters, mark that we must convert */
 
1169
        result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
 
1170
      }
 
1171
      length= lip->yyLength();
 
1172
      start= lip->get_ptr();
 
1173
      if (lip->ignore_space)
 
1174
      {
 
1175
        /*
 
1176
          If we find a space then this can't be an identifier. We notice this
 
1177
          below by checking start != lex->ptr.
 
1178
        */
 
1179
        for (; state_map[(uchar) c] == MY_LEX_SKIP ; c= lip->yyGet())
 
1180
          ;
 
1181
      }
 
1182
      if (start == lip->get_ptr() && c == '.' &&
 
1183
          ident_map[(uchar) lip->yyPeek()])
 
1184
        lip->next_state=MY_LEX_IDENT_SEP;
 
1185
      else
 
1186
      {                                 // '(' must follow directly if function
 
1187
        lip->yyUnget();
 
1188
        if ((tokval = find_keyword(lip, length, c == '(')))
 
1189
        {
 
1190
          lip->next_state= MY_LEX_START;        // Allow signed numbers
 
1191
          return(tokval);               // Was keyword
 
1192
        }
 
1193
        lip->yySkip();                  // next state does a unget
 
1194
      }
 
1195
      yylval->lex_str=get_token(lip, 0, length);
 
1196
 
 
1197
      /*
 
1198
         Note: "SELECT _bla AS 'alias'"
 
1199
         _bla should be considered as a IDENT if charset haven't been found.
 
1200
         So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
 
1201
         producing an error.
 
1202
      */
 
1203
 
 
1204
      if (yylval->lex_str.str[0] == '_')
 
1205
      {
 
1206
        CHARSET_INFO *cs= get_charset_by_csname(yylval->lex_str.str + 1,
 
1207
                                                MY_CS_PRIMARY, MYF(0));
 
1208
        if (cs)
 
1209
        {
 
1210
          yylval->charset= cs;
 
1211
          lip->m_underscore_cs= cs;
 
1212
 
 
1213
          lip->body_utf8_append(lip->m_cpp_text_start,
 
1214
                                lip->get_cpp_tok_start() + length);
 
1215
          return(UNDERSCORE_CHARSET);
 
1216
        }
 
1217
      }
 
1218
 
 
1219
      lip->body_utf8_append(lip->m_cpp_text_start);
 
1220
 
 
1221
      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
 
1222
                                    lip->m_cpp_text_end);
 
1223
 
 
1224
      return(result_state);                     // IDENT or IDENT_QUOTED
 
1225
 
 
1226
    case MY_LEX_IDENT_SEP:                  // Found ident and now '.'
 
1227
      yylval->lex_str.str= (char*) lip->get_ptr();
 
1228
      yylval->lex_str.length= 1;
 
1229
      c= lip->yyGet();                          // should be '.'
 
1230
      lip->next_state= MY_LEX_IDENT_START;      // Next is ident (not keyword)
 
1231
      if (!ident_map[(uchar) lip->yyPeek()])    // Probably ` or "
 
1232
        lip->next_state= MY_LEX_START;
 
1233
      return((int) c);
 
1234
 
 
1235
    case MY_LEX_NUMBER_IDENT:           // number or ident which num-start
 
1236
      if (lip->yyGetLast() == '0')
 
1237
      {
 
1238
        c= lip->yyGet();
 
1239
        if (c == 'x')
 
1240
        {
 
1241
          while (my_isxdigit(cs,(c = lip->yyGet()))) ;
 
1242
          if ((lip->yyLength() >= 3) && !ident_map[c])
 
1243
          {
 
1244
            /* skip '0x' */
 
1245
            yylval->lex_str=get_token(lip, 2, lip->yyLength()-2);
 
1246
            return (HEX_NUM);
 
1247
          }
 
1248
          lip->yyUnget();
 
1249
          state= MY_LEX_IDENT_START;
 
1250
          break;
 
1251
        }
 
1252
        else if (c == 'b')
 
1253
        {
 
1254
          while ((c= lip->yyGet()) == '0' || c == '1')
 
1255
            ;
 
1256
          if ((lip->yyLength() >= 3) && !ident_map[c])
 
1257
          {
 
1258
            /* Skip '0b' */
 
1259
            yylval->lex_str= get_token(lip, 2, lip->yyLength()-2);
 
1260
            return (BIN_NUM);
 
1261
          }
 
1262
          lip->yyUnget();
 
1263
          state= MY_LEX_IDENT_START;
 
1264
          break;
 
1265
        }
 
1266
        lip->yyUnget();
 
1267
      }
 
1268
 
 
1269
      while (my_isdigit(cs, (c = lip->yyGet()))) ;
 
1270
      if (!ident_map[c])
 
1271
      {                                 // Can't be identifier
 
1272
        state=MY_LEX_INT_OR_REAL;
 
1273
        break;
 
1274
      }
 
1275
      if (c == 'e' || c == 'E')
 
1276
      {
 
1277
        // The following test is written this way to allow numbers of type 1e1
 
1278
        if (my_isdigit(cs,lip->yyPeek()) ||
 
1279
            (c=(lip->yyGet())) == '+' || c == '-')
 
1280
        {                               // Allow 1E+10
 
1281
          if (my_isdigit(cs,lip->yyPeek()))     // Number must have digit after sign
 
1282
          {
 
1283
            lip->yySkip();
 
1284
            while (my_isdigit(cs,lip->yyGet())) ;
 
1285
            yylval->lex_str=get_token(lip, 0, lip->yyLength());
 
1286
            return(FLOAT_NUM);
 
1287
          }
 
1288
        }
 
1289
        lip->yyUnget();
 
1290
      }
 
1291
      // fall through
 
1292
    case MY_LEX_IDENT_START:                    // We come here after '.'
 
1293
      result_state= IDENT;
 
1294
#if defined(USE_MB) && defined(USE_MB_IDENT)
 
1295
      if (use_mb(cs))
 
1296
      {
 
1297
        result_state= IDENT_QUOTED;
 
1298
        while (ident_map[c=lip->yyGet()])
 
1299
        {
 
1300
          if (my_mbcharlen(cs, c) > 1)
 
1301
          {
 
1302
            int l;
 
1303
            if ((l = my_ismbchar(cs,
 
1304
                                 lip->get_ptr() -1,
 
1305
                                 lip->get_end_of_query())) == 0)
 
1306
              break;
 
1307
            lip->skip_binary(l-1);
 
1308
          }
 
1309
        }
 
1310
      }
 
1311
      else
 
1312
#endif
 
1313
      {
 
1314
        for (result_state=0; ident_map[c= lip->yyGet()]; result_state|= c)
 
1315
          ;
 
1316
        /* If there were non-ASCII characters, mark that we must convert */
 
1317
        result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
 
1318
      }
 
1319
      if (c == '.' && ident_map[(uchar) lip->yyPeek()])
 
1320
        lip->next_state=MY_LEX_IDENT_SEP;// Next is '.'
 
1321
 
 
1322
      yylval->lex_str= get_token(lip, 0, lip->yyLength());
 
1323
 
 
1324
      lip->body_utf8_append(lip->m_cpp_text_start);
 
1325
 
 
1326
      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
 
1327
                                    lip->m_cpp_text_end);
 
1328
 
 
1329
      return(result_state);
 
1330
 
 
1331
    case MY_LEX_USER_VARIABLE_DELIMITER:        // Found quote char
 
1332
    {
 
1333
      uint double_quotes= 0;
 
1334
      char quote_char= c;                       // Used char
 
1335
      while ((c=lip->yyGet()))
 
1336
      {
 
1337
        int var_length;
 
1338
        if ((var_length= my_mbcharlen(cs, c)) == 1)
 
1339
        {
 
1340
          if (c == quote_char)
 
1341
          {
 
1342
            if (lip->yyPeek() != quote_char)
 
1343
              break;
 
1344
            c=lip->yyGet();
 
1345
            double_quotes++;
 
1346
            continue;
 
1347
          }
 
1348
        }
 
1349
#ifdef USE_MB
 
1350
        else if (use_mb(cs))
 
1351
        {
 
1352
          if ((var_length= my_ismbchar(cs, lip->get_ptr() - 1,
 
1353
                                       lip->get_end_of_query())))
 
1354
            lip->skip_binary(var_length-1);
 
1355
        }
 
1356
#endif
 
1357
      }
 
1358
      if (double_quotes)
 
1359
        yylval->lex_str=get_quoted_token(lip, 1,
 
1360
                                         lip->yyLength() - double_quotes -1,
 
1361
                                         quote_char);
 
1362
      else
 
1363
        yylval->lex_str=get_token(lip, 1, lip->yyLength() -1);
 
1364
      if (c == quote_char)
 
1365
        lip->yySkip();                  // Skip end `
 
1366
      lip->next_state= MY_LEX_START;
 
1367
 
 
1368
      lip->body_utf8_append(lip->m_cpp_text_start);
 
1369
 
 
1370
      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
 
1371
                                    lip->m_cpp_text_end);
 
1372
 
 
1373
      return(IDENT_QUOTED);
 
1374
    }
 
1375
    case MY_LEX_INT_OR_REAL:            // Complete int or incomplete real
 
1376
      if (c != '.')
 
1377
      {                                 // Found complete integer number.
 
1378
        yylval->lex_str=get_token(lip, 0, lip->yyLength());
 
1379
        return int_token(yylval->lex_str.str, (uint) yylval->lex_str.length);
 
1380
      }
 
1381
      // fall through
 
1382
    case MY_LEX_REAL:                   // Incomplete real number
 
1383
      while (my_isdigit(cs,c = lip->yyGet())) ;
 
1384
 
 
1385
      if (c == 'e' || c == 'E')
 
1386
      {
 
1387
        c = lip->yyGet();
 
1388
        if (c == '-' || c == '+')
 
1389
          c = lip->yyGet();                     // Skip sign
 
1390
        if (!my_isdigit(cs,c))
 
1391
        {                               // No digit after sign
 
1392
          state= MY_LEX_CHAR;
 
1393
          break;
 
1394
        }
 
1395
        while (my_isdigit(cs,lip->yyGet())) ;
 
1396
        yylval->lex_str=get_token(lip, 0, lip->yyLength());
 
1397
        return(FLOAT_NUM);
 
1398
      }
 
1399
      yylval->lex_str=get_token(lip, 0, lip->yyLength());
 
1400
      return(DECIMAL_NUM);
 
1401
 
 
1402
    case MY_LEX_HEX_NUMBER:             // Found x'hexstring'
 
1403
      lip->yySkip();                    // Accept opening '
 
1404
      while (my_isxdigit(cs, (c= lip->yyGet()))) ;
 
1405
      if (c != '\'')
 
1406
        return(ABORT_SYM);              // Illegal hex constant
 
1407
      lip->yySkip();                    // Accept closing '
 
1408
      length= lip->yyLength();          // Length of hexnum+3
 
1409
      if ((length % 2) == 0)
 
1410
        return(ABORT_SYM);              // odd number of hex digits
 
1411
      yylval->lex_str=get_token(lip,
 
1412
                                2,          // skip x'
 
1413
                                length-3);  // don't count x' and last '
 
1414
      return HEX_STRING;
 
1415
 
 
1416
    case MY_LEX_BIN_NUMBER:           // Found b'bin-string'
 
1417
      lip->yySkip();                  // Accept opening '
 
1418
      while ((c= lip->yyGet()) == '0' || c == '1')
 
1419
        ;
 
1420
      if (c != '\'')
 
1421
        return(ABORT_SYM);            // Illegal hex constant
 
1422
      lip->yySkip();                  // Accept closing '
 
1423
      length= lip->yyLength();        // Length of bin-num + 3
 
1424
      yylval->lex_str= get_token(lip,
 
1425
                                 2,         // skip b'
 
1426
                                 length-3); // don't count b' and last '
 
1427
      return (BIN_NUM);
 
1428
 
 
1429
    case MY_LEX_CMP_OP:                 // Incomplete comparison operator
 
1430
      if (state_map[(uchar) lip->yyPeek()] == MY_LEX_CMP_OP ||
 
1431
          state_map[(uchar) lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
 
1432
        lip->yySkip();
 
1433
      if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
 
1434
      {
 
1435
        lip->next_state= MY_LEX_START;  // Allow signed numbers
 
1436
        return(tokval);
 
1437
      }
 
1438
      state = MY_LEX_CHAR;              // Something fishy found
 
1439
      break;
 
1440
 
 
1441
    case MY_LEX_LONG_CMP_OP:            // Incomplete comparison operator
 
1442
      if (state_map[(uchar) lip->yyPeek()] == MY_LEX_CMP_OP ||
 
1443
          state_map[(uchar) lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
 
1444
      {
 
1445
        lip->yySkip();
 
1446
        if (state_map[(uchar) lip->yyPeek()] == MY_LEX_CMP_OP)
 
1447
          lip->yySkip();
 
1448
      }
 
1449
      if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
 
1450
      {
 
1451
        lip->next_state= MY_LEX_START;  // Found long op
 
1452
        return(tokval);
 
1453
      }
 
1454
      state = MY_LEX_CHAR;              // Something fishy found
 
1455
      break;
 
1456
 
 
1457
    case MY_LEX_BOOL:
 
1458
      if (c != lip->yyPeek())
 
1459
      {
 
1460
        state=MY_LEX_CHAR;
 
1461
        break;
 
1462
      }
 
1463
      lip->yySkip();
 
1464
      tokval = find_keyword(lip,2,0);   // Is a bool operator
 
1465
      lip->next_state= MY_LEX_START;    // Allow signed numbers
 
1466
      return(tokval);
 
1467
 
 
1468
    case MY_LEX_STRING_OR_DELIMITER:
 
1469
      if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
 
1470
      {
 
1471
        state= MY_LEX_USER_VARIABLE_DELIMITER;
 
1472
        break;
 
1473
      }
 
1474
      /* " used for strings */
 
1475
    case MY_LEX_STRING:                 // Incomplete text string
 
1476
      if (!(yylval->lex_str.str = get_text(lip, 1, 1)))
 
1477
      {
 
1478
        state= MY_LEX_CHAR;             // Read char by char
 
1479
        break;
 
1480
      }
 
1481
      yylval->lex_str.length=lip->yytoklen;
 
1482
 
 
1483
      lip->body_utf8_append(lip->m_cpp_text_start);
 
1484
 
 
1485
      lip->body_utf8_append_literal(thd, &yylval->lex_str,
 
1486
        lip->m_underscore_cs ? lip->m_underscore_cs : cs,
 
1487
        lip->m_cpp_text_end);
 
1488
 
 
1489
      lip->m_underscore_cs= NULL;
 
1490
 
 
1491
      lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
 
1492
      return(TEXT_STRING);
 
1493
 
 
1494
    case MY_LEX_COMMENT:                        //  Comment
 
1495
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
 
1496
      while ((c = lip->yyGet()) != '\n' && c) ;
 
1497
      lip->yyUnget();                   // Safety against eof
 
1498
      state = MY_LEX_START;             // Try again
 
1499
      break;
 
1500
    case MY_LEX_LONG_COMMENT:           /* Long C comment? */
 
1501
      if (lip->yyPeek() != '*')
 
1502
      {
 
1503
        state=MY_LEX_CHAR;              // Probable division
 
1504
        break;
 
1505
      }
 
1506
      lex->select_lex.options|= OPTION_FOUND_COMMENT;
 
1507
      /* Reject '/' '*', since we might need to turn off the echo */
 
1508
      lip->yyUnget();
 
1509
 
 
1510
      lip->save_in_comment_state();
 
1511
 
 
1512
      if (lip->yyPeekn(2) == 'M' && lip->yyPeekn(3) == '!')
 
1513
      {
 
1514
        /* Skip MariaDB unique marker */
 
1515
        lip->set_echo(FALSE);
 
1516
        lip->yySkip();
 
1517
        /* The following if will be true */
 
1518
      }
 
1519
      if (lip->yyPeekn(2) == '!')
 
1520
      {
 
1521
        lip->in_comment= DISCARD_COMMENT;
 
1522
        /* Accept '/' '*' '!', but do not keep this marker. */
 
1523
        lip->set_echo(FALSE);
 
1524
        lip->yySkipn(3);
 
1525
 
 
1526
        /*
 
1527
          The special comment format is very strict:
 
1528
          '/' '*' '!', followed by an optional 'M' and exactly
 
1529
          1 digit (major), 2 digits (minor), then 2 digits (dot).
 
1530
          32302 -> 3.23.02
 
1531
          50032 -> 5.0.32
 
1532
          50114 -> 5.1.14
 
1533
        */
 
1534
        if (  my_isdigit(cs, lip->yyPeekn(0))
 
1535
           && my_isdigit(cs, lip->yyPeekn(1))
 
1536
           && my_isdigit(cs, lip->yyPeekn(2))
 
1537
           && my_isdigit(cs, lip->yyPeekn(3))
 
1538
           && my_isdigit(cs, lip->yyPeekn(4))
 
1539
           )
 
1540
        {
 
1541
          ulong version;
 
1542
          char *end_ptr= (char*) lip->get_ptr()+5;
 
1543
          int error;
 
1544
          version= (ulong) my_strtoll10(lip->get_ptr(), &end_ptr, &error);
 
1545
 
 
1546
          if (version <= MYSQL_VERSION_ID)
 
1547
          {
 
1548
            /* Accept 'M' 'm' 'm' 'd' 'd' */
 
1549
            lip->yySkipn(5);
 
1550
            /* Expand the content of the special comment as real code */
 
1551
            lip->set_echo(TRUE);
 
1552
            state=MY_LEX_START;
 
1553
            break;  /* Do not treat contents as a comment.  */
 
1554
          }
 
1555
          else
 
1556
          {
 
1557
            /*
 
1558
              Patch and skip the conditional comment to avoid it
 
1559
              being propagated infinitely (eg. to a slave).
 
1560
            */
 
1561
            char *pcom= lip->yyUnput(' ');
 
1562
            comment_closed= ! consume_comment(lip, 1);
 
1563
            if (! comment_closed)
 
1564
            {
 
1565
              *pcom= '!';
 
1566
            }
 
1567
            /* version allowed to have one level of comment inside. */
 
1568
          }
 
1569
        }
 
1570
        else
 
1571
        {
 
1572
          /* Not a version comment. */
 
1573
          state=MY_LEX_START;
 
1574
          lip->set_echo(TRUE);
 
1575
          break;
 
1576
        }
 
1577
      }
 
1578
      else
 
1579
      {
 
1580
        lip->in_comment= PRESERVE_COMMENT;
 
1581
        lip->yySkip();                  // Accept /
 
1582
        lip->yySkip();                  // Accept *
 
1583
        comment_closed= ! consume_comment(lip, 0);
 
1584
        /* regular comments can have zero comments inside. */
 
1585
      }
 
1586
      /*
 
1587
        Discard:
 
1588
        - regular '/' '*' comments,
 
1589
        - special comments '/' '*' '!' for a future version,
 
1590
        by scanning until we find a closing '*' '/' marker.
 
1591
 
 
1592
        Nesting regular comments isn't allowed.  The first 
 
1593
        '*' '/' returns the parser to the previous state.
 
1594
 
 
1595
        /#!VERSI oned containing /# regular #/ is allowed #/
 
1596
 
 
1597
                Inside one versioned comment, another versioned comment
 
1598
                is treated as a regular discardable comment.  It gets
 
1599
                no special parsing.
 
1600
      */
 
1601
 
 
1602
      /* Unbalanced comments with a missing '*' '/' are a syntax error */
 
1603
      if (! comment_closed)
 
1604
        return (ABORT_SYM);
 
1605
      state = MY_LEX_START;             // Try again
 
1606
      lip->restore_in_comment_state();
 
1607
      break;
 
1608
    case MY_LEX_END_LONG_COMMENT:
 
1609
      if ((lip->in_comment != NO_COMMENT) && lip->yyPeek() == '/')
 
1610
      {
 
1611
        /* Reject '*' '/' */
 
1612
        lip->yyUnget();
 
1613
        /* Accept '*' '/', with the proper echo */
 
1614
        lip->set_echo(lip->in_comment == PRESERVE_COMMENT);
 
1615
        lip->yySkipn(2);
 
1616
        /* And start recording the tokens again */
 
1617
        lip->set_echo(TRUE);
 
1618
        lip->in_comment=NO_COMMENT;
 
1619
        state=MY_LEX_START;
 
1620
      }
 
1621
      else
 
1622
        state=MY_LEX_CHAR;              // Return '*'
 
1623
      break;
 
1624
    case MY_LEX_SET_VAR:                // Check if ':='
 
1625
      if (lip->yyPeek() != '=')
 
1626
      {
 
1627
        state=MY_LEX_CHAR;              // Return ':'
 
1628
        break;
 
1629
      }
 
1630
      lip->yySkip();
 
1631
      return (SET_VAR);
 
1632
    case MY_LEX_SEMICOLON:                      // optional line terminator
 
1633
      state= MY_LEX_CHAR;               // Return ';'
 
1634
      break;
 
1635
    case MY_LEX_EOL:
 
1636
      if (lip->eof())
 
1637
      {
 
1638
        lip->yyUnget();                 // Reject the last '\0'
 
1639
        lip->set_echo(FALSE);
 
1640
        lip->yySkip();
 
1641
        lip->set_echo(TRUE);
 
1642
        /* Unbalanced comments with a missing '*' '/' are a syntax error */
 
1643
        if (lip->in_comment != NO_COMMENT)
 
1644
          return (ABORT_SYM);
 
1645
        lip->next_state=MY_LEX_END;     // Mark for next loop
 
1646
        return(END_OF_INPUT);
 
1647
      }
 
1648
      state=MY_LEX_CHAR;
 
1649
      break;
 
1650
    case MY_LEX_END:
 
1651
      lip->next_state=MY_LEX_END;
 
1652
      return(0);                        // We found end of input last time
 
1653
 
 
1654
      /* Actually real shouldn't start with . but allow them anyhow */
 
1655
    case MY_LEX_REAL_OR_POINT:
 
1656
      if (my_isdigit(cs,lip->yyPeek()))
 
1657
        state = MY_LEX_REAL;            // Real
 
1658
      else
 
1659
      {
 
1660
        state= MY_LEX_IDENT_SEP;        // return '.'
 
1661
        lip->yyUnget();                 // Put back '.'
 
1662
      }
 
1663
      break;
 
1664
    case MY_LEX_USER_END:               // end '@' of user@hostname
 
1665
      switch (state_map[(uchar) lip->yyPeek()]) {
 
1666
      case MY_LEX_STRING:
 
1667
      case MY_LEX_USER_VARIABLE_DELIMITER:
 
1668
      case MY_LEX_STRING_OR_DELIMITER:
 
1669
        break;
 
1670
      case MY_LEX_USER_END:
 
1671
        lip->next_state=MY_LEX_SYSTEM_VAR;
 
1672
        break;
 
1673
      default:
 
1674
        lip->next_state=MY_LEX_HOSTNAME;
 
1675
        break;
 
1676
      }
 
1677
      yylval->lex_str.str=(char*) lip->get_ptr();
 
1678
      yylval->lex_str.length=1;
 
1679
      return((int) '@');
 
1680
    case MY_LEX_HOSTNAME:               // end '@' of user@hostname
 
1681
      for (c=lip->yyGet() ;
 
1682
           my_isalnum(cs,c) || c == '.' || c == '_' ||  c == '$';
 
1683
           c= lip->yyGet()) ;
 
1684
      yylval->lex_str=get_token(lip, 0, lip->yyLength());
 
1685
      return(LEX_HOSTNAME);
 
1686
    case MY_LEX_SYSTEM_VAR:
 
1687
      yylval->lex_str.str=(char*) lip->get_ptr();
 
1688
      yylval->lex_str.length=1;
 
1689
      lip->yySkip();                                    // Skip '@'
 
1690
      lip->next_state= (state_map[(uchar) lip->yyPeek()] ==
 
1691
                        MY_LEX_USER_VARIABLE_DELIMITER ?
 
1692
                        MY_LEX_OPERATOR_OR_IDENT :
 
1693
                        MY_LEX_IDENT_OR_KEYWORD);
 
1694
      return((int) '@');
 
1695
    case MY_LEX_IDENT_OR_KEYWORD:
 
1696
      /*
 
1697
        We come here when we have found two '@' in a row.
 
1698
        We should now be able to handle:
 
1699
        [(global | local | session) .]variable_name
 
1700
      */
 
1701
 
 
1702
      for (result_state= 0; ident_map[c= lip->yyGet()]; result_state|= c)
 
1703
        ;
 
1704
      /* If there were non-ASCII characters, mark that we must convert */
 
1705
      result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
 
1706
 
 
1707
      if (c == '.')
 
1708
        lip->next_state=MY_LEX_IDENT_SEP;
 
1709
      length= lip->yyLength();
 
1710
      if (length == 0)
 
1711
        return(ABORT_SYM);              // Names must be nonempty.
 
1712
      if ((tokval= find_keyword(lip, length,0)))
 
1713
      {
 
1714
        lip->yyUnget();                         // Put back 'c'
 
1715
        return(tokval);                         // Was keyword
 
1716
      }
 
1717
      yylval->lex_str=get_token(lip, 0, length);
 
1718
 
 
1719
      lip->body_utf8_append(lip->m_cpp_text_start);
 
1720
 
 
1721
      lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
 
1722
                                    lip->m_cpp_text_end);
 
1723
 
 
1724
      return(result_state);
 
1725
    }
 
1726
  }
 
1727
}
 
1728
 
 
1729
 
 
1730
/**
 
1731
  Construct a copy of this object to be used for mysql_alter_table
 
1732
  and mysql_create_table.
 
1733
 
 
1734
  Historically, these two functions modify their Alter_info
 
1735
  arguments. This behaviour breaks re-execution of prepared
 
1736
  statements and stored procedures and is compensated by always
 
1737
  supplying a copy of Alter_info to these functions.
 
1738
 
 
1739
  @return You need to use check the error in THD for out
 
1740
  of memory condition after calling this function.
 
1741
*/
 
1742
 
 
1743
Alter_info::Alter_info(const Alter_info &rhs, MEM_ROOT *mem_root)
 
1744
  :drop_list(rhs.drop_list, mem_root),
 
1745
  alter_list(rhs.alter_list, mem_root),
 
1746
  key_list(rhs.key_list, mem_root),
 
1747
  create_list(rhs.create_list, mem_root),
 
1748
  flags(rhs.flags),
 
1749
  keys_onoff(rhs.keys_onoff),
 
1750
  tablespace_op(rhs.tablespace_op),
 
1751
  partition_names(rhs.partition_names, mem_root),
 
1752
  num_parts(rhs.num_parts),
 
1753
  change_level(rhs.change_level),
 
1754
  datetime_field(rhs.datetime_field),
 
1755
  error_if_not_empty(rhs.error_if_not_empty)
 
1756
{
 
1757
  /*
 
1758
    Make deep copies of used objects.
 
1759
    This is not a fully deep copy - clone() implementations
 
1760
    of Alter_drop, Alter_column, Key, foreign_key, Key_part_spec
 
1761
    do not copy string constants. At the same length the only
 
1762
    reason we make a copy currently is that ALTER/CREATE TABLE
 
1763
    code changes input Alter_info definitions, but string
 
1764
    constants never change.
 
1765
  */
 
1766
  list_copy_and_replace_each_value(drop_list, mem_root);
 
1767
  list_copy_and_replace_each_value(alter_list, mem_root);
 
1768
  list_copy_and_replace_each_value(key_list, mem_root);
 
1769
  list_copy_and_replace_each_value(create_list, mem_root);
 
1770
  /* partition_names are not deeply copied currently */
 
1771
}
 
1772
 
 
1773
 
 
1774
void trim_whitespace(CHARSET_INFO *cs, LEX_STRING *str)
 
1775
{
 
1776
  /*
 
1777
    TODO:
 
1778
    This code assumes that there are no multi-bytes characters
 
1779
    that can be considered white-space.
 
1780
  */
 
1781
 
 
1782
  while ((str->length > 0) && (my_isspace(cs, str->str[0])))
 
1783
  {
 
1784
    str->length --;
 
1785
    str->str ++;
 
1786
  }
 
1787
 
 
1788
  /*
 
1789
    FIXME:
 
1790
    Also, parsing backward is not safe with multi bytes characters
 
1791
  */
 
1792
  while ((str->length > 0) && (my_isspace(cs, str->str[str->length-1])))
 
1793
  {
 
1794
    str->length --;
 
1795
  }
 
1796
}
 
1797
 
 
1798
 
 
1799
/*
 
1800
  st_select_lex structures initialisations
 
1801
*/
 
1802
 
 
1803
void st_select_lex_node::init_query()
 
1804
{
 
1805
  options= 0;
 
1806
  sql_cache= SQL_CACHE_UNSPECIFIED;
 
1807
  linkage= UNSPECIFIED_TYPE;
 
1808
  no_table_names_allowed= 0;
 
1809
  uncacheable= 0;
 
1810
}
 
1811
 
 
1812
void st_select_lex_node::init_select()
 
1813
{
 
1814
}
 
1815
 
 
1816
void st_select_lex_unit::init_query()
 
1817
{
 
1818
  st_select_lex_node::init_query();
 
1819
  linkage= GLOBAL_OPTIONS_TYPE;
 
1820
  global_parameters= first_select();
 
1821
  select_limit_cnt= HA_POS_ERROR;
 
1822
  offset_limit_cnt= 0;
 
1823
  union_distinct= 0;
 
1824
  prepared= optimized= executed= 0;
 
1825
  item= 0;
 
1826
  union_result= 0;
 
1827
  table= 0;
 
1828
  fake_select_lex= 0;
 
1829
  cleaned= 0;
 
1830
  item_list.empty();
 
1831
  describe= 0;
 
1832
  found_rows_for_union= 0;
 
1833
  insert_table_with_stored_vcol= 0;
 
1834
  derived= 0;
 
1835
}
 
1836
 
 
1837
void st_select_lex::init_query()
 
1838
{
 
1839
  st_select_lex_node::init_query();
 
1840
  table_list.empty();
 
1841
  top_join_list.empty();
 
1842
  join_list= &top_join_list;
 
1843
  embedding= 0;
 
1844
  leaf_tables_prep.empty();
 
1845
  leaf_tables.empty();
 
1846
  item_list.empty();
 
1847
  join= 0;
 
1848
  having= prep_having= where= prep_where= 0;
 
1849
  olap= UNSPECIFIED_OLAP_TYPE;
 
1850
  having_fix_field= 0;
 
1851
  context.select_lex= this;
 
1852
  context.init();
 
1853
  /*
 
1854
    Add the name resolution context of the current (sub)query to the
 
1855
    stack of contexts for the whole query.
 
1856
    TODO:
 
1857
    push_context may return an error if there is no memory for a new
 
1858
    element in the stack, however this method has no return value,
 
1859
    thus push_context should be moved to a place where query
 
1860
    initialization is checked for failure.
 
1861
  */
 
1862
  parent_lex->push_context(&context);
 
1863
  cond_count= between_count= with_wild= 0;
 
1864
  max_equal_elems= 0;
 
1865
  ref_pointer_array= 0;
 
1866
  ref_pointer_array_size= 0;
 
1867
  select_n_where_fields= 0;
 
1868
  select_n_having_items= 0;
 
1869
  n_sum_items= 0;
 
1870
  n_child_sum_items= 0;
 
1871
  subquery_in_having= explicit_limit= 0;
 
1872
  is_item_list_lookup= 0;
 
1873
  first_execution= 1;
 
1874
  first_natural_join_processing= 1;
 
1875
  first_cond_optimization= 1;
 
1876
  parsing_place= NO_MATTER;
 
1877
  exclude_from_table_unique_test= no_wrap_view_item= FALSE;
 
1878
  nest_level= 0;
 
1879
  link_next= 0;
 
1880
  is_prep_leaf_list_saved= FALSE;
 
1881
  bzero((char*) expr_cache_may_be_used, sizeof(expr_cache_may_be_used));
 
1882
  m_non_agg_field_used= false;
 
1883
  m_agg_func_used= false;
 
1884
}
 
1885
 
 
1886
void st_select_lex::init_select()
 
1887
{
 
1888
  st_select_lex_node::init_select();
 
1889
  sj_nests.empty();
 
1890
  sj_subselects.empty();
 
1891
  group_list.empty();
 
1892
  if (group_list_ptrs)
 
1893
    group_list_ptrs->clear();
 
1894
  type= db= 0;
 
1895
  having= 0;
 
1896
  table_join_options= 0;
 
1897
  in_sum_expr= with_wild= 0;
 
1898
  options= 0;
 
1899
  sql_cache= SQL_CACHE_UNSPECIFIED;
 
1900
  braces= 0;
 
1901
  interval_list.empty();
 
1902
  ftfunc_list_alloc.empty();
 
1903
  inner_sum_func_list= 0;
 
1904
  ftfunc_list= &ftfunc_list_alloc;
 
1905
  linkage= UNSPECIFIED_TYPE;
 
1906
  order_list.elements= 0;
 
1907
  order_list.first= 0;
 
1908
  order_list.next= &order_list.first;
 
1909
  /* Set limit and offset to default values */
 
1910
  select_limit= 0;      /* denotes the default limit = HA_POS_ERROR */
 
1911
  offset_limit= 0;      /* denotes the default offset = 0 */
 
1912
  with_sum_func= 0;
 
1913
  is_correlated= 0;
 
1914
  cur_pos_in_select_list= UNDEF_POS;
 
1915
  non_agg_fields.empty();
 
1916
  cond_value= having_value= Item::COND_UNDEF;
 
1917
  inner_refs_list.empty();
 
1918
  insert_tables= 0;
 
1919
  merged_into= 0;
 
1920
  m_non_agg_field_used= false;
 
1921
  m_agg_func_used= false;
 
1922
  name_visibility_map= 0;
 
1923
}
 
1924
 
 
1925
/*
 
1926
  st_select_lex structures linking
 
1927
*/
 
1928
 
 
1929
/* include on level down */
 
1930
void st_select_lex_node::include_down(st_select_lex_node *upper)
 
1931
{
 
1932
  if ((next= upper->slave))
 
1933
    next->prev= &next;
 
1934
  prev= &upper->slave;
 
1935
  upper->slave= this;
 
1936
  master= upper;
 
1937
  slave= 0;
 
1938
}
 
1939
 
 
1940
 
 
1941
void st_select_lex_node::add_slave(st_select_lex_node *slave_arg)
 
1942
{
 
1943
  for (; slave; slave= slave->next)
 
1944
    if (slave == slave_arg)
 
1945
      return;
 
1946
 
 
1947
  if (slave)
 
1948
  {
 
1949
    st_select_lex_node *slave_arg_slave= slave_arg->slave;
 
1950
    /* Insert in the front of list of slaves if any. */
 
1951
    slave_arg->include_neighbour(slave);
 
1952
    /* include_neighbour() sets slave_arg->slave=0, restore it. */
 
1953
    slave_arg->slave= slave_arg_slave;
 
1954
    /* Count on include_neighbour() setting the master. */
 
1955
    DBUG_ASSERT(slave_arg->master == this);
 
1956
  }
 
1957
  else
 
1958
  {
 
1959
    slave= slave_arg;
 
1960
    slave_arg->master= this;
 
1961
  }
 
1962
}
 
1963
 
 
1964
 
 
1965
/*
 
1966
  include on level down (but do not link)
 
1967
 
 
1968
  SYNOPSYS
 
1969
    st_select_lex_node::include_standalone()
 
1970
    upper - reference on node underr which this node should be included
 
1971
    ref - references on reference on this node
 
1972
*/
 
1973
void st_select_lex_node::include_standalone(st_select_lex_node *upper,
 
1974
                                            st_select_lex_node **ref)
 
1975
{
 
1976
  next= 0;
 
1977
  prev= ref;
 
1978
  master= upper;
 
1979
  slave= 0;
 
1980
}
 
1981
 
 
1982
/* include neighbour (on same level) */
 
1983
void st_select_lex_node::include_neighbour(st_select_lex_node *before)
 
1984
{
 
1985
  if ((next= before->next))
 
1986
    next->prev= &next;
 
1987
  prev= &before->next;
 
1988
  before->next= this;
 
1989
  master= before->master;
 
1990
  slave= 0;
 
1991
}
 
1992
 
 
1993
/* including in global SELECT_LEX list */
 
1994
void st_select_lex_node::include_global(st_select_lex_node **plink)
 
1995
{
 
1996
  if ((link_next= *plink))
 
1997
    link_next->link_prev= &link_next;
 
1998
  link_prev= plink;
 
1999
  *plink= this;
 
2000
}
 
2001
 
 
2002
//excluding from global list (internal function)
 
2003
void st_select_lex_node::fast_exclude()
 
2004
{
 
2005
  if (link_prev)
 
2006
  {
 
2007
    if ((*link_prev= link_next))
 
2008
      link_next->link_prev= link_prev;
 
2009
  }
 
2010
  // Remove slave structure
 
2011
  for (; slave; slave= slave->next)
 
2012
    slave->fast_exclude();
 
2013
  
 
2014
}
 
2015
 
 
2016
 
 
2017
/*
 
2018
  Exclude a node from the tree lex structure, but leave it in the global
 
2019
  list of nodes.
 
2020
*/
 
2021
 
 
2022
void st_select_lex_node::exclude_from_tree()
 
2023
{
 
2024
  if ((*prev= next))
 
2025
    next->prev= prev;
 
2026
}
 
2027
 
 
2028
 
 
2029
/*
 
2030
  Exclude select_lex structure (except first (first select can't be
 
2031
  deleted, because it is most upper select))
 
2032
*/
 
2033
void st_select_lex_node::exclude()
 
2034
{
 
2035
  /* exclude from global list */
 
2036
  fast_exclude();
 
2037
  /* exclude from other structures */
 
2038
  exclude_from_tree();
 
2039
  /* 
 
2040
     We do not need following statements, because prev pointer of first 
 
2041
     list element point to master->slave
 
2042
     if (master->slave == this)
 
2043
       master->slave= next;
 
2044
  */
 
2045
}
 
2046
 
 
2047
 
 
2048
/*
 
2049
  Exclude level of current unit from tree of SELECTs
 
2050
 
 
2051
  SYNOPSYS
 
2052
    st_select_lex_unit::exclude_level()
 
2053
 
 
2054
  NOTE: units which belong to current will be brought up on level of
 
2055
  currernt unit 
 
2056
*/
 
2057
void st_select_lex_unit::exclude_level()
 
2058
{
 
2059
  SELECT_LEX_UNIT *units= 0, **units_last= &units;
 
2060
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
 
2061
  {
 
2062
    // unlink current level from global SELECTs list
 
2063
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
 
2064
      sl->link_next->link_prev= sl->link_prev;
 
2065
 
 
2066
    // bring up underlay levels
 
2067
    SELECT_LEX_UNIT **last= 0;
 
2068
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
 
2069
    {
 
2070
      u->master= master;
 
2071
      last= (SELECT_LEX_UNIT**)&(u->next);
 
2072
    }
 
2073
    if (last)
 
2074
    {
 
2075
      (*units_last)= sl->first_inner_unit();
 
2076
      units_last= last;
 
2077
    }
 
2078
  }
 
2079
  if (units)
 
2080
  {
 
2081
    // include brought up levels in place of current
 
2082
    (*prev)= units;
 
2083
    (*units_last)= (SELECT_LEX_UNIT*)next;
 
2084
    if (next)
 
2085
      next->prev= (SELECT_LEX_NODE**)units_last;
 
2086
    units->prev= prev;
 
2087
  }
 
2088
  else
 
2089
  {
 
2090
    // exclude currect unit from list of nodes
 
2091
    (*prev)= next;
 
2092
    if (next)
 
2093
      next->prev= prev;
 
2094
  }
 
2095
}
 
2096
 
 
2097
 
 
2098
/*
 
2099
  Exclude subtree of current unit from tree of SELECTs
 
2100
 
 
2101
  SYNOPSYS
 
2102
    st_select_lex_unit::exclude_tree()
 
2103
*/
 
2104
void st_select_lex_unit::exclude_tree()
 
2105
{
 
2106
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
 
2107
  {
 
2108
    // unlink current level from global SELECTs list
 
2109
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
 
2110
      sl->link_next->link_prev= sl->link_prev;
 
2111
 
 
2112
    // unlink underlay levels
 
2113
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
 
2114
    {
 
2115
      u->exclude_level();
 
2116
    }
 
2117
  }
 
2118
  // exclude currect unit from list of nodes
 
2119
  (*prev)= next;
 
2120
  if (next)
 
2121
    next->prev= prev;
 
2122
}
 
2123
 
 
2124
 
 
2125
/*
 
2126
  st_select_lex_node::mark_as_dependent mark all st_select_lex struct from 
 
2127
  this to 'last' as dependent
 
2128
 
 
2129
  SYNOPSIS
 
2130
    last - pointer to last st_select_lex struct, before wich all 
 
2131
           st_select_lex have to be marked as dependent
 
2132
 
 
2133
  NOTE
 
2134
    'last' should be reachable from this st_select_lex_node
 
2135
*/
 
2136
 
 
2137
bool st_select_lex::mark_as_dependent(THD *thd, st_select_lex *last, Item *dependency)
 
2138
{
 
2139
 
 
2140
  DBUG_ASSERT(this != last);
 
2141
 
 
2142
  /*
 
2143
    Mark all selects from resolved to 1 before select where was
 
2144
    found table as depended (of select where was found table)
 
2145
  */
 
2146
  SELECT_LEX *s= this;
 
2147
  do
 
2148
  {
 
2149
    if (!(s->uncacheable & UNCACHEABLE_DEPENDENT_GENERATED))
 
2150
    {
 
2151
      // Select is dependent of outer select
 
2152
      s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
 
2153
                       UNCACHEABLE_DEPENDENT_GENERATED;
 
2154
      SELECT_LEX_UNIT *munit= s->master_unit();
 
2155
      munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
 
2156
                       UNCACHEABLE_DEPENDENT_GENERATED;
 
2157
      for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
 
2158
      {
 
2159
        if (sl != s &&
 
2160
            !(sl->uncacheable & (UNCACHEABLE_DEPENDENT_GENERATED |
 
2161
                                 UNCACHEABLE_UNITED)))
 
2162
          sl->uncacheable|= UNCACHEABLE_UNITED;
 
2163
      }
 
2164
    }
 
2165
 
 
2166
    Item_subselect *subquery_expr= s->master_unit()->item;
 
2167
    if (subquery_expr && subquery_expr->mark_as_dependent(thd, last, 
 
2168
                                                          dependency))
 
2169
      return TRUE;
 
2170
  } while ((s= s->outer_select()) != last && s != 0);
 
2171
  is_correlated= TRUE;
 
2172
  this->master_unit()->item->is_correlated= TRUE;
 
2173
  return FALSE;
 
2174
}
 
2175
 
 
2176
bool st_select_lex_node::set_braces(bool value)      { return 1; }
 
2177
bool st_select_lex_node::inc_in_sum_expr()           { return 1; }
 
2178
uint st_select_lex_node::get_in_sum_expr()           { return 0; }
 
2179
TABLE_LIST* st_select_lex_node::get_table_list()     { return 0; }
 
2180
List<Item>* st_select_lex_node::get_item_list()      { return 0; }
 
2181
TABLE_LIST *st_select_lex_node::add_table_to_list (THD *thd, Table_ident *table,
 
2182
                                                  LEX_STRING *alias,
 
2183
                                                  ulong table_join_options,
 
2184
                                                  thr_lock_type flags,
 
2185
                                                  enum_mdl_type mdl_type,
 
2186
                                                  List<Index_hint> *hints,
 
2187
                                                  LEX_STRING *option)
 
2188
{
 
2189
  return 0;
 
2190
}
 
2191
ulong st_select_lex_node::get_table_join_options()
 
2192
{
 
2193
  return 0;
 
2194
}
 
2195
 
 
2196
/*
 
2197
  prohibit using LIMIT clause
 
2198
*/
 
2199
bool st_select_lex::test_limit()
 
2200
{
 
2201
  if (select_limit != 0)
 
2202
  {
 
2203
    my_error(ER_NOT_SUPPORTED_YET, MYF(0),
 
2204
             "LIMIT & IN/ALL/ANY/SOME subquery");
 
2205
    return(1);
 
2206
  }
 
2207
  return(0);
 
2208
}
 
2209
 
 
2210
 
 
2211
st_select_lex_unit* st_select_lex_unit::master_unit()
 
2212
{
 
2213
    return this;
 
2214
}
 
2215
 
 
2216
 
 
2217
st_select_lex* st_select_lex_unit::outer_select()
 
2218
{
 
2219
  return (st_select_lex*) master;
 
2220
}
 
2221
 
 
2222
 
 
2223
bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
 
2224
{
 
2225
  return add_to_list(thd, order_list, item, asc);
 
2226
}
 
2227
 
 
2228
 
 
2229
bool st_select_lex::add_gorder_to_list(THD *thd, Item *item, bool asc)
 
2230
{
 
2231
  return add_to_list(thd, gorder_list, item, asc);
 
2232
}
 
2233
 
 
2234
bool st_select_lex::add_item_to_list(THD *thd, Item *item)
 
2235
{
 
2236
  DBUG_ENTER("st_select_lex::add_item_to_list");
 
2237
  DBUG_PRINT("info", ("Item: 0x%lx", (long) item));
 
2238
  DBUG_RETURN(item_list.push_back(item));
 
2239
}
 
2240
 
 
2241
 
 
2242
bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
 
2243
{
 
2244
  return add_to_list(thd, group_list, item, asc);
 
2245
}
 
2246
 
 
2247
 
 
2248
bool st_select_lex::add_ftfunc_to_list(Item_func_match *func)
 
2249
{
 
2250
  return !func || ftfunc_list->push_back(func); // end of memory?
 
2251
}
 
2252
 
 
2253
 
 
2254
st_select_lex_unit* st_select_lex::master_unit()
 
2255
{
 
2256
  return (st_select_lex_unit*) master;
 
2257
}
 
2258
 
 
2259
 
 
2260
st_select_lex* st_select_lex::outer_select()
 
2261
{
 
2262
  return (st_select_lex*) master->get_master();
 
2263
}
 
2264
 
 
2265
 
 
2266
bool st_select_lex::set_braces(bool value)
 
2267
{
 
2268
  braces= value;
 
2269
  return 0; 
 
2270
}
 
2271
 
 
2272
 
 
2273
bool st_select_lex::inc_in_sum_expr()
 
2274
{
 
2275
  in_sum_expr++;
 
2276
  return 0;
 
2277
}
 
2278
 
 
2279
 
 
2280
uint st_select_lex::get_in_sum_expr()
 
2281
{
 
2282
  return in_sum_expr;
 
2283
}
 
2284
 
 
2285
 
 
2286
TABLE_LIST* st_select_lex::get_table_list()
 
2287
{
 
2288
  return table_list.first;
 
2289
}
 
2290
 
 
2291
List<Item>* st_select_lex::get_item_list()
 
2292
{
 
2293
  return &item_list;
 
2294
}
 
2295
 
 
2296
ulong st_select_lex::get_table_join_options()
 
2297
{
 
2298
  return table_join_options;
 
2299
}
 
2300
 
 
2301
 
 
2302
bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
 
2303
{
 
2304
  // find_order_in_list() may need some extra space, so multiply by two.
 
2305
  order_group_num*= 2;
 
2306
 
 
2307
  /*
 
2308
    We have to create array in prepared statement memory if it is a
 
2309
    prepared statement
 
2310
  */
 
2311
  Query_arena *arena= thd->stmt_arena;
 
2312
  const uint n_elems= (n_sum_items +
 
2313
                       n_child_sum_items +
 
2314
                       item_list.elements +
 
2315
                       select_n_having_items +
 
2316
                       select_n_where_fields +
 
2317
                       order_group_num) * 5;
 
2318
  if (ref_pointer_array != NULL)
 
2319
  {
 
2320
    /*
 
2321
      We need to take 'n_sum_items' into account when allocating the array,
 
2322
      and this may actually increase during the optimization phase due to
 
2323
      MIN/MAX rewrite in Item_in_subselect::single_value_transformer.
 
2324
      In the usual case we can reuse the array from the prepare phase.
 
2325
      If we need a bigger array, we must allocate a new one.
 
2326
    */
 
2327
    if (ref_pointer_array_size >= n_elems)
 
2328
      return false;
 
2329
  }
 
2330
  ref_pointer_array= static_cast<Item**>(arena->alloc(sizeof(Item*) * n_elems));
 
2331
  if (ref_pointer_array != NULL)
 
2332
    ref_pointer_array_size= n_elems;
 
2333
 
 
2334
  return ref_pointer_array == NULL;
 
2335
}
 
2336
 
 
2337
 
 
2338
void st_select_lex_unit::print(String *str, enum_query_type query_type)
 
2339
{
 
2340
  bool union_all= !union_distinct;
 
2341
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
 
2342
  {
 
2343
    if (sl != first_select())
 
2344
    {
 
2345
      str->append(STRING_WITH_LEN(" union "));
 
2346
      if (union_all)
 
2347
        str->append(STRING_WITH_LEN("all "));
 
2348
      else if (union_distinct == sl)
 
2349
        union_all= TRUE;
 
2350
    }
 
2351
    if (sl->braces)
 
2352
      str->append('(');
 
2353
    sl->print(thd, str, query_type);
 
2354
    if (sl->braces)
 
2355
      str->append(')');
 
2356
  }
 
2357
  if (fake_select_lex == global_parameters)
 
2358
  {
 
2359
    if (fake_select_lex->order_list.elements)
 
2360
    {
 
2361
      str->append(STRING_WITH_LEN(" order by "));
 
2362
      fake_select_lex->print_order(str,
 
2363
        fake_select_lex->order_list.first,
 
2364
        query_type);
 
2365
    }
 
2366
    fake_select_lex->print_limit(thd, str, query_type);
 
2367
  }
 
2368
}
 
2369
 
 
2370
 
 
2371
void st_select_lex::print_order(String *str,
 
2372
                                ORDER *order,
 
2373
                                enum_query_type query_type)
 
2374
{
 
2375
  for (; order; order= order->next)
 
2376
  {
 
2377
    if (order->counter_used)
 
2378
    {
 
2379
      if (query_type != QT_VIEW_INTERNAL)
 
2380
      {
 
2381
        char buffer[20];
 
2382
        size_t length= my_snprintf(buffer, 20, "%d", order->counter);
 
2383
        str->append(buffer, (uint) length);
 
2384
      }
 
2385
      else
 
2386
      {
 
2387
        /* replace numeric reference with expression */
 
2388
        if (order->item[0]->type() == Item::INT_ITEM &&
 
2389
            order->item[0]->basic_const_item())
 
2390
        {
 
2391
          char buffer[20];
 
2392
          size_t length= my_snprintf(buffer, 20, "%d", order->counter);
 
2393
          str->append(buffer, (uint) length);
 
2394
          /* make it expression instead of integer constant */
 
2395
          str->append(STRING_WITH_LEN("+0"));
 
2396
        }
 
2397
        else
 
2398
          (*order->item)->print(str, query_type);
 
2399
      }
 
2400
    }
 
2401
    else
 
2402
      (*order->item)->print(str, query_type);
 
2403
    if (!order->asc)
 
2404
      str->append(STRING_WITH_LEN(" desc"));
 
2405
    if (order->next)
 
2406
      str->append(',');
 
2407
  }
 
2408
}
 
2409
 
 
2410
 
 
2411
void st_select_lex::print_limit(THD *thd,
 
2412
                                String *str,
 
2413
                                enum_query_type query_type)
 
2414
{
 
2415
  SELECT_LEX_UNIT *unit= master_unit();
 
2416
  Item_subselect *item= unit->item;
 
2417
 
 
2418
  if (item && unit->global_parameters == this)
 
2419
  {
 
2420
    Item_subselect::subs_type subs_type= item->substype();
 
2421
    if (subs_type == Item_subselect::EXISTS_SUBS ||
 
2422
        subs_type == Item_subselect::IN_SUBS ||
 
2423
        subs_type == Item_subselect::ALL_SUBS)
 
2424
    {
 
2425
      return;
 
2426
    }
 
2427
  }
 
2428
  if (explicit_limit)
 
2429
  {
 
2430
    str->append(STRING_WITH_LEN(" limit "));
 
2431
    if (offset_limit)
 
2432
    {
 
2433
      offset_limit->print(str, query_type);
 
2434
      str->append(',');
 
2435
    }
 
2436
    select_limit->print(str, query_type);
 
2437
  }
 
2438
}
 
2439
 
 
2440
 
 
2441
/**
 
2442
  @brief Restore the LEX and THD in case of a parse error.
 
2443
 
 
2444
  This is a clean up call that is invoked by the Bison generated
 
2445
  parser before returning an error from MYSQLparse. If your
 
2446
  semantic actions manipulate with the global thread state (which
 
2447
  is a very bad practice and should not normally be employed) and
 
2448
  need a clean-up in case of error, and you can not use %destructor
 
2449
  rule in the grammar file itself, this function should be used
 
2450
  to implement the clean up.
 
2451
*/
 
2452
 
 
2453
void LEX::cleanup_lex_after_parse_error(THD *thd)
 
2454
{
 
2455
  /*
 
2456
    Delete sphead for the side effect of restoring of the original
 
2457
    LEX state, thd->lex, thd->mem_root and thd->free_list if they
 
2458
    were replaced when parsing stored procedure statements.  We
 
2459
    will never use sphead object after a parse error, so it's okay
 
2460
    to delete it only for the sake of the side effect.
 
2461
    TODO: make this functionality explicit in sp_head class.
 
2462
    Sic: we must nullify the member of the main lex, not the
 
2463
    current one that will be thrown away
 
2464
  */
 
2465
  if (thd->lex->sphead)
 
2466
  {
 
2467
    thd->lex->sphead->restore_thd_mem_root(thd);
 
2468
    delete thd->lex->sphead;
 
2469
    thd->lex->sphead= NULL;
 
2470
  }
 
2471
}
 
2472
 
 
2473
/*
 
2474
  Initialize (or reset) Query_tables_list object.
 
2475
 
 
2476
  SYNOPSIS
 
2477
    reset_query_tables_list()
 
2478
      init  TRUE  - we should perform full initialization of object with
 
2479
                    allocating needed memory
 
2480
            FALSE - object is already initialized so we should only reset
 
2481
                    its state so it can be used for parsing/processing
 
2482
                    of new statement
 
2483
 
 
2484
  DESCRIPTION
 
2485
    This method initializes Query_tables_list so it can be used as part
 
2486
    of LEX object for parsing/processing of statement. One can also use
 
2487
    this method to reset state of already initialized Query_tables_list
 
2488
    so it can be used for processing of new statement.
 
2489
*/
 
2490
 
 
2491
void Query_tables_list::reset_query_tables_list(bool init)
 
2492
{
 
2493
  sql_command= SQLCOM_END;
 
2494
  if (!init && query_tables)
 
2495
  {
 
2496
    TABLE_LIST *table= query_tables;
 
2497
    for (;;)
 
2498
    {
 
2499
      delete table->view;
 
2500
      if (query_tables_last == &table->next_global ||
 
2501
          !(table= table->next_global))
 
2502
        break;
 
2503
    }
 
2504
  }
 
2505
  query_tables= 0;
 
2506
  query_tables_last= &query_tables;
 
2507
  query_tables_own_last= 0;
 
2508
  if (init)
 
2509
  {
 
2510
    /*
 
2511
      We delay real initialization of hash (and therefore related
 
2512
      memory allocation) until first insertion into this hash.
 
2513
    */
 
2514
    my_hash_clear(&sroutines);
 
2515
  }
 
2516
  else if (sroutines.records)
 
2517
  {
 
2518
    /* Non-zero sroutines.records means that hash was initialized. */
 
2519
    my_hash_reset(&sroutines);
 
2520
  }
 
2521
  sroutines_list.empty();
 
2522
  sroutines_list_own_last= sroutines_list.next;
 
2523
  sroutines_list_own_elements= 0;
 
2524
  binlog_stmt_flags= 0;
 
2525
  stmt_accessed_table_flag= 0;
 
2526
}
 
2527
 
 
2528
 
 
2529
/*
 
2530
  Destroy Query_tables_list object with freeing all resources used by it.
 
2531
 
 
2532
  SYNOPSIS
 
2533
    destroy_query_tables_list()
 
2534
*/
 
2535
 
 
2536
void Query_tables_list::destroy_query_tables_list()
 
2537
{
 
2538
  my_hash_free(&sroutines);
 
2539
}
 
2540
 
 
2541
 
 
2542
/*
 
2543
  Initialize LEX object.
 
2544
 
 
2545
  SYNOPSIS
 
2546
    LEX::LEX()
 
2547
 
 
2548
  NOTE
 
2549
    LEX object initialized with this constructor can be used as part of
 
2550
    THD object for which one can safely call open_tables(), lock_tables()
 
2551
    and close_thread_tables() functions. But it is not yet ready for
 
2552
    statement parsing. On should use lex_start() function to prepare LEX
 
2553
    for this.
 
2554
*/
 
2555
 
 
2556
LEX::LEX()
 
2557
  :result(0), option_type(OPT_DEFAULT), is_lex_started(0),
 
2558
   limit_rows_examined_cnt(ULONGLONG_MAX)
 
2559
{
 
2560
 
 
2561
  my_init_dynamic_array2(&plugins, sizeof(plugin_ref),
 
2562
                         plugins_static_buffer,
 
2563
                         INITIAL_LEX_PLUGIN_LIST_SIZE, 
 
2564
                         INITIAL_LEX_PLUGIN_LIST_SIZE);
 
2565
  reset_query_tables_list(TRUE);
 
2566
  mi.init();
 
2567
}
 
2568
 
 
2569
 
 
2570
/*
 
2571
  Check whether the merging algorithm can be used on this VIEW
 
2572
 
 
2573
  SYNOPSIS
 
2574
    LEX::can_be_merged()
 
2575
 
 
2576
  DESCRIPTION
 
2577
    We can apply merge algorithm if it is single SELECT view  with
 
2578
    subqueries only in WHERE clause (we do not count SELECTs of underlying
 
2579
    views, and second level subqueries) and we have not grpouping, ordering,
 
2580
    HAVING clause, aggregate functions, DISTINCT clause, LIMIT clause and
 
2581
    several underlying tables.
 
2582
 
 
2583
  RETURN
 
2584
    FALSE - only temporary table algorithm can be used
 
2585
    TRUE  - merge algorithm can be used
 
2586
*/
 
2587
 
 
2588
bool LEX::can_be_merged()
 
2589
{
 
2590
  // TODO: do not forget implement case when select_lex.table_list.elements==0
 
2591
 
 
2592
  /* find non VIEW subqueries/unions */
 
2593
  bool selects_allow_merge= select_lex.next_select() == 0;
 
2594
  if (selects_allow_merge)
 
2595
  {
 
2596
    for (SELECT_LEX_UNIT *tmp_unit= select_lex.first_inner_unit();
 
2597
         tmp_unit;
 
2598
         tmp_unit= tmp_unit->next_unit())
 
2599
    {
 
2600
      if (tmp_unit->first_select()->parent_lex == this &&
 
2601
          (tmp_unit->item == 0 ||
 
2602
           (tmp_unit->item->place() != IN_WHERE &&
 
2603
            tmp_unit->item->place() != IN_ON)))
 
2604
      {
 
2605
        selects_allow_merge= 0;
 
2606
        break;
 
2607
      }
 
2608
    }
 
2609
  }
 
2610
 
 
2611
  return (selects_allow_merge &&
 
2612
          select_lex.group_list.elements == 0 &&
 
2613
          select_lex.having == 0 &&
 
2614
          select_lex.with_sum_func == 0 &&
 
2615
          select_lex.table_list.elements >= 1 &&
 
2616
          !(select_lex.options & SELECT_DISTINCT) &&
 
2617
          select_lex.select_limit == 0);
 
2618
}
 
2619
 
 
2620
 
 
2621
/*
 
2622
  check if command can use VIEW with MERGE algorithm (for top VIEWs)
 
2623
 
 
2624
  SYNOPSIS
 
2625
    LEX::can_use_merged()
 
2626
 
 
2627
  DESCRIPTION
 
2628
    Only listed here commands can use merge algorithm in top level
 
2629
    SELECT_LEX (for subqueries will be used merge algorithm if
 
2630
    LEX::can_not_use_merged() is not TRUE).
 
2631
 
 
2632
  RETURN
 
2633
    FALSE - command can't use merged VIEWs
 
2634
    TRUE  - VIEWs with MERGE algorithms can be used
 
2635
*/
 
2636
 
 
2637
bool LEX::can_use_merged()
 
2638
{
 
2639
  switch (sql_command)
 
2640
  {
 
2641
  case SQLCOM_SELECT:
 
2642
  case SQLCOM_CREATE_TABLE:
 
2643
  case SQLCOM_UPDATE:
 
2644
  case SQLCOM_UPDATE_MULTI:
 
2645
  case SQLCOM_DELETE:
 
2646
  case SQLCOM_DELETE_MULTI:
 
2647
  case SQLCOM_INSERT:
 
2648
  case SQLCOM_INSERT_SELECT:
 
2649
  case SQLCOM_REPLACE:
 
2650
  case SQLCOM_REPLACE_SELECT:
 
2651
  case SQLCOM_LOAD:
 
2652
    return TRUE;
 
2653
  default:
 
2654
    return FALSE;
 
2655
  }
 
2656
}
 
2657
 
 
2658
/*
 
2659
  Check if command can't use merged views in any part of command
 
2660
 
 
2661
  SYNOPSIS
 
2662
    LEX::can_not_use_merged()
 
2663
 
 
2664
  DESCRIPTION
 
2665
    Temporary table algorithm will be used on all SELECT levels for queries
 
2666
    listed here (see also LEX::can_use_merged()).
 
2667
 
 
2668
  RETURN
 
2669
    FALSE - command can't use merged VIEWs
 
2670
    TRUE  - VIEWs with MERGE algorithms can be used
 
2671
*/
 
2672
 
 
2673
bool LEX::can_not_use_merged()
 
2674
{
 
2675
  switch (sql_command)
 
2676
  {
 
2677
  case SQLCOM_CREATE_VIEW:
 
2678
  case SQLCOM_SHOW_CREATE:
 
2679
  /*
 
2680
    SQLCOM_SHOW_FIELDS is necessary to make 
 
2681
    information schema tables working correctly with views.
 
2682
    see get_schema_tables_result function
 
2683
  */
 
2684
  case SQLCOM_SHOW_FIELDS:
 
2685
    return TRUE;
 
2686
  default:
 
2687
    return FALSE;
 
2688
  }
 
2689
}
 
2690
 
 
2691
/*
 
2692
  Detect that we need only table structure of derived table/view
 
2693
 
 
2694
  SYNOPSIS
 
2695
    only_view_structure()
 
2696
 
 
2697
  RETURN
 
2698
    TRUE yes, we need only structure
 
2699
    FALSE no, we need data
 
2700
*/
 
2701
 
 
2702
bool LEX::only_view_structure()
 
2703
{
 
2704
  switch (sql_command) {
 
2705
  case SQLCOM_SHOW_CREATE:
 
2706
  case SQLCOM_SHOW_TABLES:
 
2707
  case SQLCOM_SHOW_FIELDS:
 
2708
  case SQLCOM_REVOKE_ALL:
 
2709
  case SQLCOM_REVOKE:
 
2710
  case SQLCOM_GRANT:
 
2711
  case SQLCOM_CREATE_VIEW:
 
2712
    return TRUE;
 
2713
  default:
 
2714
    return FALSE;
 
2715
  }
 
2716
}
 
2717
 
 
2718
 
 
2719
/*
 
2720
  Should Items_ident be printed correctly
 
2721
 
 
2722
  SYNOPSIS
 
2723
    need_correct_ident()
 
2724
 
 
2725
  RETURN
 
2726
    TRUE yes, we need only structure
 
2727
    FALSE no, we need data
 
2728
*/
 
2729
 
 
2730
 
 
2731
bool LEX::need_correct_ident()
 
2732
{
 
2733
  switch(sql_command)
 
2734
  {
 
2735
  case SQLCOM_SHOW_CREATE:
 
2736
  case SQLCOM_SHOW_TABLES:
 
2737
  case SQLCOM_CREATE_VIEW:
 
2738
    return TRUE;
 
2739
  default:
 
2740
    return FALSE;
 
2741
  }
 
2742
}
 
2743
 
 
2744
/*
 
2745
  Get effective type of CHECK OPTION for given view
 
2746
 
 
2747
  SYNOPSIS
 
2748
    get_effective_with_check()
 
2749
    view    given view
 
2750
 
 
2751
  NOTE
 
2752
    It have not sense to set CHECK OPTION for SELECT satement or subqueries,
 
2753
    so we do not.
 
2754
 
 
2755
  RETURN
 
2756
    VIEW_CHECK_NONE      no need CHECK OPTION
 
2757
    VIEW_CHECK_LOCAL     CHECK OPTION LOCAL
 
2758
    VIEW_CHECK_CASCADED  CHECK OPTION CASCADED
 
2759
*/
 
2760
 
 
2761
uint8 LEX::get_effective_with_check(TABLE_LIST *view)
 
2762
{
 
2763
  if (view->select_lex->master_unit() == &unit &&
 
2764
      which_check_option_applicable())
 
2765
    return (uint8)view->with_check;
 
2766
  return VIEW_CHECK_NONE;
 
2767
}
 
2768
 
 
2769
 
 
2770
/**
 
2771
  This method should be called only during parsing.
 
2772
  It is aware of compound statements (stored routine bodies)
 
2773
  and will initialize the destination with the default
 
2774
  database of the stored routine, rather than the default
 
2775
  database of the connection it is parsed in.
 
2776
  E.g. if one has no current database selected, or current database 
 
2777
  set to 'bar' and then issues:
 
2778
 
 
2779
  CREATE PROCEDURE foo.p1() BEGIN SELECT * FROM t1 END//
 
2780
 
 
2781
  t1 is meant to refer to foo.t1, not to bar.t1.
 
2782
 
 
2783
  This method is needed to support this rule.
 
2784
 
 
2785
  @return TRUE in case of error (parsing should be aborted, FALSE in
 
2786
  case of success
 
2787
*/
 
2788
 
 
2789
bool
 
2790
LEX::copy_db_to(char **p_db, size_t *p_db_length) const
 
2791
{
 
2792
  if (sphead)
 
2793
  {
 
2794
    DBUG_ASSERT(sphead->m_db.str && sphead->m_db.length);
 
2795
    /*
 
2796
      It is safe to assign the string by-pointer, both sphead and
 
2797
      its statements reside in the same memory root.
 
2798
    */
 
2799
    *p_db= sphead->m_db.str;
 
2800
    if (p_db_length)
 
2801
      *p_db_length= sphead->m_db.length;
 
2802
    return FALSE;
 
2803
  }
 
2804
  return thd->copy_db_to(p_db, p_db_length);
 
2805
}
 
2806
 
 
2807
/*
 
2808
  initialize limit counters
 
2809
 
 
2810
  SYNOPSIS
 
2811
    st_select_lex_unit::set_limit()
 
2812
    values      - SELECT_LEX with initial values for counters
 
2813
*/
 
2814
 
 
2815
void st_select_lex_unit::set_limit(st_select_lex *sl)
 
2816
{
 
2817
  ha_rows select_limit_val;
 
2818
  ulonglong val;
 
2819
 
 
2820
  DBUG_ASSERT(! thd->stmt_arena->is_stmt_prepare());
 
2821
  if (sl->select_limit)
 
2822
  {
 
2823
    Item *item = sl->select_limit;
 
2824
    /*
 
2825
      fix_fields() has not been called for sl->select_limit. That's due to the
 
2826
      historical reasons -- this item could be only of type Item_int, and
 
2827
      Item_int does not require fix_fields(). Thus, fix_fields() was never
 
2828
      called for sl->select_limit.
 
2829
 
 
2830
      Some time ago, Item_splocal was also allowed for LIMIT / OFFSET clauses.
 
2831
      However, the fix_fields() behavior was not updated, which led to a crash
 
2832
      in some cases.
 
2833
 
 
2834
      There is no single place where to call fix_fields() for LIMIT / OFFSET
 
2835
      items during the fix-fields-phase. Thus, for the sake of readability,
 
2836
      it was decided to do it here, on the evaluation phase (which is a
 
2837
      violation of design, but we chose the lesser of two evils).
 
2838
 
 
2839
      We can call fix_fields() here, because sl->select_limit can be of two
 
2840
      types only: Item_int and Item_splocal. Item_int::fix_fields() is trivial,
 
2841
      and Item_splocal::fix_fields() (or rather Item_sp_variable::fix_fields())
 
2842
      has the following specific:
 
2843
        1) it does not affect other items;
 
2844
        2) it does not fail.
 
2845
 
 
2846
      Nevertheless DBUG_ASSERT was added to catch future changes in
 
2847
      fix_fields() implementation. Also added runtime check against a result
 
2848
      of fix_fields() in order to handle error condition in non-debug build.
 
2849
    */
 
2850
    bool fix_fields_successful= true;
 
2851
    if (!item->fixed)
 
2852
    {
 
2853
      fix_fields_successful= !item->fix_fields(thd, NULL);
 
2854
 
 
2855
      DBUG_ASSERT(fix_fields_successful);
 
2856
    }
 
2857
    val= fix_fields_successful ? item->val_uint() : HA_POS_ERROR;
 
2858
  }
 
2859
  else
 
2860
    val= HA_POS_ERROR;
 
2861
 
 
2862
  select_limit_val= (ha_rows)val;
 
2863
#ifndef BIG_TABLES
 
2864
  /*
 
2865
    Check for overflow : ha_rows can be smaller then ulonglong if
 
2866
    BIG_TABLES is off.
 
2867
    */
 
2868
  if (val != (ulonglong)select_limit_val)
 
2869
    select_limit_val= HA_POS_ERROR;
 
2870
#endif
 
2871
  if (sl->offset_limit)
 
2872
  {
 
2873
    Item *item = sl->offset_limit;
 
2874
    // see comment for sl->select_limit branch.
 
2875
    bool fix_fields_successful= true;
 
2876
    if (!item->fixed)
 
2877
    {
 
2878
      fix_fields_successful= !item->fix_fields(thd, NULL);
 
2879
 
 
2880
      DBUG_ASSERT(fix_fields_successful);
 
2881
    }
 
2882
    val= fix_fields_successful ? item->val_uint() : 0;
 
2883
  }
 
2884
  else
 
2885
    val= ULL(0);
 
2886
 
 
2887
  offset_limit_cnt= (ha_rows)val;
 
2888
#ifndef BIG_TABLES
 
2889
  /* Check for truncation. */
 
2890
  if (val != (ulonglong)offset_limit_cnt)
 
2891
    offset_limit_cnt= HA_POS_ERROR;
 
2892
#endif
 
2893
  select_limit_cnt= select_limit_val + offset_limit_cnt;
 
2894
  if (select_limit_cnt < select_limit_val)
 
2895
    select_limit_cnt= HA_POS_ERROR;             // no limit
 
2896
}
 
2897
 
 
2898
 
 
2899
/**
 
2900
  @brief Set the initial purpose of this TABLE_LIST object in the list of used
 
2901
    tables.
 
2902
 
 
2903
  We need to track this information on table-by-table basis, since when this
 
2904
  table becomes an element of the pre-locked list, it's impossible to identify
 
2905
  which SQL sub-statement it has been originally used in.
 
2906
 
 
2907
  E.g.:
 
2908
 
 
2909
  User request:                 SELECT * FROM t1 WHERE f1();
 
2910
  FUNCTION f1():                DELETE FROM t2; RETURN 1;
 
2911
  BEFORE DELETE trigger on t2:  INSERT INTO t3 VALUES (old.a);
 
2912
 
 
2913
  For this user request, the pre-locked list will contain t1, t2, t3
 
2914
  table elements, each needed for different DML.
 
2915
 
 
2916
  The trigger event map is updated to reflect INSERT, UPDATE, DELETE,
 
2917
  REPLACE, LOAD DATA, CREATE TABLE .. SELECT, CREATE TABLE ..
 
2918
  REPLACE SELECT statements, and additionally ON DUPLICATE KEY UPDATE
 
2919
  clause.
 
2920
*/
 
2921
 
 
2922
void LEX::set_trg_event_type_for_tables()
 
2923
{
 
2924
  uint8 new_trg_event_map= 0;
 
2925
  DBUG_ENTER("LEX::set_trg_event_type_for_tables");
 
2926
 
 
2927
  /*
 
2928
    Some auxiliary operations
 
2929
    (e.g. GRANT processing) create TABLE_LIST instances outside
 
2930
    the parser. Additionally, some commands (e.g. OPTIMIZE) change
 
2931
    the lock type for a table only after parsing is done. Luckily,
 
2932
    these do not fire triggers and do not need to pre-load them.
 
2933
    For these TABLE_LISTs set_trg_event_type is never called, and
 
2934
    trg_event_map is always empty. That means that the pre-locking
 
2935
    algorithm will ignore triggers defined on these tables, if
 
2936
    any, and the execution will either fail with an assert in
 
2937
    sql_trigger.cc or with an error that a used table was not
 
2938
    pre-locked, in case of a production build.
 
2939
 
 
2940
    TODO: this usage pattern creates unnecessary module dependencies
 
2941
    and should be rewritten to go through the parser.
 
2942
    Table list instances created outside the parser in most cases
 
2943
    refer to mysql.* system tables. It is not allowed to have
 
2944
    a trigger on a system table, but keeping track of
 
2945
    initialization provides extra safety in case this limitation
 
2946
    is circumvented.
 
2947
  */
 
2948
 
 
2949
  switch (sql_command) {
 
2950
  case SQLCOM_LOCK_TABLES:
 
2951
  /*
 
2952
    On a LOCK TABLE, all triggers must be pre-loaded for this TABLE_LIST
 
2953
    when opening an associated TABLE.
 
2954
  */
 
2955
    new_trg_event_map= static_cast<uint8>
 
2956
                        (1 << static_cast<int>(TRG_EVENT_INSERT)) |
 
2957
                      static_cast<uint8>
 
2958
                        (1 << static_cast<int>(TRG_EVENT_UPDATE)) |
 
2959
                      static_cast<uint8>
 
2960
                        (1 << static_cast<int>(TRG_EVENT_DELETE));
 
2961
    break;
 
2962
  /*
 
2963
    Basic INSERT. If there is an additional ON DUPLIATE KEY UPDATE
 
2964
    clause, it will be handled later in this method.
 
2965
  */
 
2966
  case SQLCOM_INSERT:                           /* fall through */
 
2967
  case SQLCOM_INSERT_SELECT:
 
2968
  /*
 
2969
    LOAD DATA ... INFILE is expected to fire BEFORE/AFTER INSERT
 
2970
    triggers.
 
2971
    If the statement also has REPLACE clause, it will be
 
2972
    handled later in this method.
 
2973
  */
 
2974
  case SQLCOM_LOAD:                             /* fall through */
 
2975
  /*
 
2976
    REPLACE is semantically equivalent to INSERT. In case
 
2977
    of a primary or unique key conflict, it deletes the old
 
2978
    record and inserts a new one. So we also may need to
 
2979
    fire ON DELETE triggers. This functionality is handled
 
2980
    later in this method.
 
2981
  */
 
2982
  case SQLCOM_REPLACE:                          /* fall through */
 
2983
  case SQLCOM_REPLACE_SELECT:
 
2984
  /*
 
2985
    CREATE TABLE ... SELECT defaults to INSERT if the table or
 
2986
    view already exists. REPLACE option of CREATE TABLE ...
 
2987
    REPLACE SELECT is handled later in this method.
 
2988
  */
 
2989
  case SQLCOM_CREATE_TABLE:
 
2990
    new_trg_event_map|= static_cast<uint8>
 
2991
                          (1 << static_cast<int>(TRG_EVENT_INSERT));
 
2992
    break;
 
2993
  /* Basic update and multi-update */
 
2994
  case SQLCOM_UPDATE:                           /* fall through */
 
2995
  case SQLCOM_UPDATE_MULTI:
 
2996
    new_trg_event_map|= static_cast<uint8>
 
2997
                          (1 << static_cast<int>(TRG_EVENT_UPDATE));
 
2998
    break;
 
2999
  /* Basic delete and multi-delete */
 
3000
  case SQLCOM_DELETE:                           /* fall through */
 
3001
  case SQLCOM_DELETE_MULTI:
 
3002
    new_trg_event_map|= static_cast<uint8>
 
3003
                          (1 << static_cast<int>(TRG_EVENT_DELETE));
 
3004
    break;
 
3005
  default:
 
3006
    break;
 
3007
  }
 
3008
 
 
3009
  switch (duplicates) {
 
3010
  case DUP_UPDATE:
 
3011
    new_trg_event_map|= static_cast<uint8>
 
3012
                          (1 << static_cast<int>(TRG_EVENT_UPDATE));
 
3013
    break;
 
3014
  case DUP_REPLACE:
 
3015
    new_trg_event_map|= static_cast<uint8>
 
3016
                          (1 << static_cast<int>(TRG_EVENT_DELETE));
 
3017
    break;
 
3018
  case DUP_ERROR:
 
3019
  default:
 
3020
    break;
 
3021
  }
 
3022
 
 
3023
 
 
3024
  /*
 
3025
    Do not iterate over sub-selects, only the tables in the outermost
 
3026
    SELECT_LEX can be modified, if any.
 
3027
  */
 
3028
  TABLE_LIST *tables= select_lex.get_table_list();
 
3029
 
 
3030
  while (tables)
 
3031
  {
 
3032
    /*
 
3033
      This is a fast check to filter out statements that do
 
3034
      not change data, or tables  on the right side, in case of
 
3035
      INSERT .. SELECT, CREATE TABLE .. SELECT and so on.
 
3036
      Here we also filter out OPTIMIZE statement and non-updateable
 
3037
      views, for which lock_type is TL_UNLOCK or TL_READ after
 
3038
      parsing.
 
3039
    */
 
3040
    if (static_cast<int>(tables->lock_type) >=
 
3041
        static_cast<int>(TL_WRITE_ALLOW_WRITE))
 
3042
      tables->trg_event_map= new_trg_event_map;
 
3043
    tables= tables->next_local;
 
3044
  }
 
3045
  DBUG_VOID_RETURN;
 
3046
}
 
3047
 
 
3048
 
 
3049
/*
 
3050
  Unlink the first table from the global table list and the first table from
 
3051
  outer select (lex->select_lex) local list
 
3052
 
 
3053
  SYNOPSIS
 
3054
    unlink_first_table()
 
3055
    link_to_local       Set to 1 if caller should link this table to local list
 
3056
 
 
3057
  NOTES
 
3058
    We assume that first tables in both lists is the same table or the local
 
3059
    list is empty.
 
3060
 
 
3061
  RETURN
 
3062
    0   If 'query_tables' == 0
 
3063
    unlinked table
 
3064
      In this case link_to_local is set.
 
3065
 
 
3066
*/
 
3067
TABLE_LIST *LEX::unlink_first_table(bool *link_to_local)
 
3068
{
 
3069
  TABLE_LIST *first;
 
3070
  if ((first= query_tables))
 
3071
  {
 
3072
    /*
 
3073
      Exclude from global table list
 
3074
    */
 
3075
    if ((query_tables= query_tables->next_global))
 
3076
      query_tables->prev_global= &query_tables;
 
3077
    else
 
3078
      query_tables_last= &query_tables;
 
3079
    first->next_global= 0;
 
3080
 
 
3081
    /*
 
3082
      and from local list if it is not empty
 
3083
    */
 
3084
    if ((*link_to_local= test(select_lex.table_list.first)))
 
3085
    {
 
3086
      select_lex.context.table_list= 
 
3087
        select_lex.context.first_name_resolution_table= first->next_local;
 
3088
      select_lex.table_list.first= first->next_local;
 
3089
      select_lex.table_list.elements--; //safety
 
3090
      first->next_local= 0;
 
3091
      /*
 
3092
        Ensure that the global list has the same first table as the local
 
3093
        list.
 
3094
      */
 
3095
      first_lists_tables_same();
 
3096
    }
 
3097
  }
 
3098
  return first;
 
3099
}
 
3100
 
 
3101
 
 
3102
/*
 
3103
  Bring first local table of first most outer select to first place in global
 
3104
  table list
 
3105
 
 
3106
  SYNOPSYS
 
3107
     LEX::first_lists_tables_same()
 
3108
 
 
3109
  NOTES
 
3110
    In many cases (for example, usual INSERT/DELETE/...) the first table of
 
3111
    main SELECT_LEX have special meaning => check that it is the first table
 
3112
    in global list and re-link to be first in the global list if it is
 
3113
    necessary.  We need such re-linking only for queries with sub-queries in
 
3114
    the select list, as only in this case tables of sub-queries will go to
 
3115
    the global list first.
 
3116
*/
 
3117
 
 
3118
void LEX::first_lists_tables_same()
 
3119
{
 
3120
  TABLE_LIST *first_table= select_lex.table_list.first;
 
3121
  if (query_tables != first_table && first_table != 0)
 
3122
  {
 
3123
    TABLE_LIST *next;
 
3124
    if (query_tables_last == &first_table->next_global)
 
3125
      query_tables_last= first_table->prev_global;
 
3126
 
 
3127
    if ((next= *first_table->prev_global= first_table->next_global))
 
3128
      next->prev_global= first_table->prev_global;
 
3129
    /* include in new place */
 
3130
    first_table->next_global= query_tables;
 
3131
    /*
 
3132
       We are sure that query_tables is not 0, because first_table was not
 
3133
       first table in the global list => we can use
 
3134
       query_tables->prev_global without check of query_tables
 
3135
    */
 
3136
    query_tables->prev_global= &first_table->next_global;
 
3137
    first_table->prev_global= &query_tables;
 
3138
    query_tables= first_table;
 
3139
  }
 
3140
}
 
3141
 
 
3142
 
 
3143
/*
 
3144
  Link table back that was unlinked with unlink_first_table()
 
3145
 
 
3146
  SYNOPSIS
 
3147
    link_first_table_back()
 
3148
    link_to_local       do we need link this table to local
 
3149
 
 
3150
  RETURN
 
3151
    global list
 
3152
*/
 
3153
 
 
3154
void LEX::link_first_table_back(TABLE_LIST *first,
 
3155
                                   bool link_to_local)
 
3156
{
 
3157
  if (first)
 
3158
  {
 
3159
    if ((first->next_global= query_tables))
 
3160
      query_tables->prev_global= &first->next_global;
 
3161
    else
 
3162
      query_tables_last= &first->next_global;
 
3163
    query_tables= first;
 
3164
 
 
3165
    if (link_to_local)
 
3166
    {
 
3167
      first->next_local= select_lex.table_list.first;
 
3168
      select_lex.context.table_list= first;
 
3169
      select_lex.table_list.first= first;
 
3170
      select_lex.table_list.elements++; //safety
 
3171
    }
 
3172
  }
 
3173
}
 
3174
 
 
3175
 
 
3176
 
 
3177
/*
 
3178
  cleanup lex for case when we open table by table for processing
 
3179
 
 
3180
  SYNOPSIS
 
3181
    LEX::cleanup_after_one_table_open()
 
3182
 
 
3183
  NOTE
 
3184
    This method is mostly responsible for cleaning up of selects lists and
 
3185
    derived tables state. To rollback changes in Query_tables_list one has
 
3186
    to call Query_tables_list::reset_query_tables_list(FALSE).
 
3187
*/
 
3188
 
 
3189
void LEX::cleanup_after_one_table_open()
 
3190
{
 
3191
  /*
 
3192
    thd->lex->derived_tables & additional units may be set if we open
 
3193
    a view. It is necessary to clear thd->lex->derived_tables flag
 
3194
    to prevent processing of derived tables during next open_and_lock_tables
 
3195
    if next table is a real table and cleanup & remove underlying units
 
3196
    NOTE: all units will be connected to thd->lex->select_lex, because we
 
3197
    have not UNION on most upper level.
 
3198
    */
 
3199
  if (all_selects_list != &select_lex)
 
3200
  {
 
3201
    derived_tables= 0;
 
3202
    select_lex.exclude_from_table_unique_test= false;
 
3203
    /* cleunup underlying units (units of VIEW) */
 
3204
    for (SELECT_LEX_UNIT *un= select_lex.first_inner_unit();
 
3205
         un;
 
3206
         un= un->next_unit())
 
3207
      un->cleanup();
 
3208
    /* reduce all selects list to default state */
 
3209
    all_selects_list= &select_lex;
 
3210
    /* remove underlying units (units of VIEW) subtree */
 
3211
    select_lex.cut_subtree();
 
3212
  }
 
3213
}
 
3214
 
 
3215
 
 
3216
/*
 
3217
  Save current state of Query_tables_list for this LEX, and prepare it
 
3218
  for processing of new statemnt.
 
3219
 
 
3220
  SYNOPSIS
 
3221
    reset_n_backup_query_tables_list()
 
3222
      backup  Pointer to Query_tables_list instance to be used for backup
 
3223
*/
 
3224
 
 
3225
void LEX::reset_n_backup_query_tables_list(Query_tables_list *backup)
 
3226
{
 
3227
  backup->set_query_tables_list(this);
 
3228
  /*
 
3229
    We have to perform full initialization here since otherwise we
 
3230
    will damage backed up state.
 
3231
  */
 
3232
  this->reset_query_tables_list(TRUE);
 
3233
}
 
3234
 
 
3235
 
 
3236
/*
 
3237
  Restore state of Query_tables_list for this LEX from backup.
 
3238
 
 
3239
  SYNOPSIS
 
3240
    restore_backup_query_tables_list()
 
3241
      backup  Pointer to Query_tables_list instance used for backup
 
3242
*/
 
3243
 
 
3244
void LEX::restore_backup_query_tables_list(Query_tables_list *backup)
 
3245
{
 
3246
  this->destroy_query_tables_list();
 
3247
  this->set_query_tables_list(backup);
 
3248
}
 
3249
 
 
3250
 
 
3251
/*
 
3252
  Checks for usage of routines and/or tables in a parsed statement
 
3253
 
 
3254
  SYNOPSIS
 
3255
    LEX:table_or_sp_used()
 
3256
 
 
3257
  RETURN
 
3258
    FALSE  No routines and tables used
 
3259
    TRUE   Either or both routines and tables are used.
 
3260
*/
 
3261
 
 
3262
bool LEX::table_or_sp_used()
 
3263
{
 
3264
  DBUG_ENTER("table_or_sp_used");
 
3265
 
 
3266
  if (sroutines.records || query_tables)
 
3267
    DBUG_RETURN(TRUE);
 
3268
 
 
3269
  DBUG_RETURN(FALSE);
 
3270
}
 
3271
 
 
3272
 
 
3273
/*
 
3274
  Do end-of-prepare fixup for list of tables and their merge-VIEWed tables
 
3275
 
 
3276
  SYNOPSIS
 
3277
    fix_prepare_info_in_table_list()
 
3278
      thd  Thread handle
 
3279
      tbl  List of tables to process
 
3280
 
 
3281
  DESCRIPTION
 
3282
    Perform end-end-of prepare fixup for list of tables, if any of the tables
 
3283
    is a merge-algorithm VIEW, recursively fix up its underlying tables as
 
3284
    well.
 
3285
 
 
3286
*/
 
3287
 
 
3288
static void fix_prepare_info_in_table_list(THD *thd, TABLE_LIST *tbl)
 
3289
{
 
3290
  for (; tbl; tbl= tbl->next_local)
 
3291
  {
 
3292
    if (tbl->on_expr)
 
3293
    {
 
3294
      thd->check_and_register_item_tree(&tbl->prep_on_expr, &tbl->on_expr);
 
3295
      tbl->on_expr= tbl->on_expr->copy_andor_structure(thd);
 
3296
    }
 
3297
    if (tbl->is_view_or_derived() && tbl->is_merged_derived())
 
3298
    {
 
3299
      SELECT_LEX *sel= tbl->get_single_select();
 
3300
      fix_prepare_info_in_table_list(thd, sel->get_table_list());
 
3301
    }
 
3302
  }
 
3303
}
 
3304
 
 
3305
 
 
3306
/*
 
3307
  Save WHERE/HAVING/ON clauses and replace them with disposable copies
 
3308
 
 
3309
  SYNOPSIS
 
3310
    st_select_lex::fix_prepare_information
 
3311
      thd          thread handler
 
3312
      conds        in/out pointer to WHERE condition to be met at execution
 
3313
      having_conds in/out pointer to HAVING condition to be met at execution
 
3314
  
 
3315
  DESCRIPTION
 
3316
    The passed WHERE and HAVING are to be saved for the future executions.
 
3317
    This function saves it, and returns a copy which can be thrashed during
 
3318
    this execution of the statement. By saving/thrashing here we mean only
 
3319
    We also save the chain of ORDER::next in group_list, in case
 
3320
    the list is modified by remove_const().
 
3321
    AND/OR trees.
 
3322
    The function also calls fix_prepare_info_in_table_list that saves all
 
3323
    ON expressions.    
 
3324
*/
 
3325
 
 
3326
void st_select_lex::fix_prepare_information(THD *thd, Item **conds, 
 
3327
                                            Item **having_conds)
 
3328
{
 
3329
  if (!thd->stmt_arena->is_conventional() && first_execution)
 
3330
  {
 
3331
    first_execution= 0;
 
3332
    if (group_list.first)
 
3333
    {
 
3334
      if (!group_list_ptrs)
 
3335
      {
 
3336
        void *mem= thd->stmt_arena->alloc(sizeof(Group_list_ptrs));
 
3337
        group_list_ptrs= new (mem) Group_list_ptrs(thd->stmt_arena->mem_root);
 
3338
      }
 
3339
      group_list_ptrs->reserve(group_list.elements);
 
3340
      for (ORDER *order= group_list.first; order; order= order->next)
 
3341
      {
 
3342
        group_list_ptrs->push_back(order);
 
3343
      }
 
3344
    }
 
3345
    if (*conds)
 
3346
    {
 
3347
      thd->check_and_register_item_tree(&prep_where, conds);
 
3348
      *conds= where= prep_where->copy_andor_structure(thd);
 
3349
    }
 
3350
    if (*having_conds)
 
3351
    {
 
3352
      thd->check_and_register_item_tree(&prep_having, having_conds);
 
3353
      *having_conds= having= prep_having->copy_andor_structure(thd);
 
3354
    }
 
3355
    fix_prepare_info_in_table_list(thd, table_list.first);
 
3356
  }
 
3357
}
 
3358
 
 
3359
 
 
3360
/*
 
3361
  There are st_select_lex::add_table_to_list &
 
3362
  st_select_lex::set_lock_for_tables are in sql_parse.cc
 
3363
 
 
3364
  st_select_lex::print is in sql_select.cc
 
3365
 
 
3366
  st_select_lex_unit::prepare, st_select_lex_unit::exec,
 
3367
  st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
 
3368
  st_select_lex_unit::change_result
 
3369
  are in sql_union.cc
 
3370
*/
 
3371
 
 
3372
/*
 
3373
  Sets the kind of hints to be added by the calls to add_index_hint().
 
3374
 
 
3375
  SYNOPSIS
 
3376
    set_index_hint_type()
 
3377
      type_arg     The kind of hints to be added from now on.
 
3378
      clause       The clause to use for hints to be added from now on.
 
3379
 
 
3380
  DESCRIPTION
 
3381
    Used in filling up the tagged hints list.
 
3382
    This list is filled by first setting the kind of the hint as a 
 
3383
    context variable and then adding hints of the current kind.
 
3384
    Then the context variable index_hint_type can be reset to the
 
3385
    next hint type.
 
3386
*/
 
3387
void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
 
3388
                                        index_clause_map clause)
 
3389
 
3390
  current_index_hint_type= type_arg;
 
3391
  current_index_hint_clause= clause;
 
3392
}
 
3393
 
 
3394
 
 
3395
/*
 
3396
  Makes an array to store index usage hints (ADD/FORCE/IGNORE INDEX).
 
3397
 
 
3398
  SYNOPSIS
 
3399
    alloc_index_hints()
 
3400
      thd         current thread.
 
3401
*/
 
3402
 
 
3403
void st_select_lex::alloc_index_hints (THD *thd)
 
3404
 
3405
  index_hints= new (thd->mem_root) List<Index_hint>(); 
 
3406
}
 
3407
 
 
3408
 
 
3409
 
 
3410
/*
 
3411
  adds an element to the array storing index usage hints 
 
3412
  (ADD/FORCE/IGNORE INDEX).
 
3413
 
 
3414
  SYNOPSIS
 
3415
    add_index_hint()
 
3416
      thd         current thread.
 
3417
      str         name of the index.
 
3418
      length      number of characters in str.
 
3419
 
 
3420
  RETURN VALUE
 
3421
    0 on success, non-zero otherwise
 
3422
*/
 
3423
bool st_select_lex::add_index_hint (THD *thd, char *str, uint length)
 
3424
{
 
3425
  return index_hints->push_front (new (thd->mem_root) 
 
3426
                                 Index_hint(current_index_hint_type,
 
3427
                                            current_index_hint_clause,
 
3428
                                            str, length));
 
3429
}
 
3430
 
 
3431
 
 
3432
/**
 
3433
  Optimize all subqueries that have not been flattened into semi-joins.
 
3434
 
 
3435
  @details
 
3436
  This functionality is a method of SELECT_LEX instead of JOIN because
 
3437
  SQL statements as DELETE/UPDATE do not have a corresponding JOIN object.
 
3438
 
 
3439
  @see JOIN::optimize_unflattened_subqueries
 
3440
 
 
3441
  @param const_only  Restrict subquery optimization to constant subqueries
 
3442
 
 
3443
  @return Operation status
 
3444
  @retval FALSE     success.
 
3445
  @retval TRUE      error occurred.
 
3446
*/
 
3447
 
 
3448
bool st_select_lex::optimize_unflattened_subqueries(bool const_only)
 
3449
{
 
3450
  for (SELECT_LEX_UNIT *un= first_inner_unit(); un; un= un->next_unit())
 
3451
  {
 
3452
    Item_subselect *subquery_predicate= un->item;
 
3453
    
 
3454
    if (subquery_predicate)
 
3455
    {
 
3456
      if (subquery_predicate->substype() == Item_subselect::IN_SUBS)
 
3457
      {
 
3458
        Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;
 
3459
        if (in_subs->is_jtbm_merged)
 
3460
          continue;
 
3461
      }
 
3462
 
 
3463
      if (const_only && !subquery_predicate->const_item())
 
3464
      {
 
3465
        /* Skip non-constant subqueries if the caller asked so. */
 
3466
        continue;
 
3467
      }
 
3468
 
 
3469
      bool empty_union_result= true;
 
3470
      bool is_correlated_unit= false;
 
3471
      /*
 
3472
        If the subquery is a UNION, optimize all the subqueries in the UNION. If
 
3473
        there is no UNION, then the loop will execute once for the subquery.
 
3474
      */
 
3475
      for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
 
3476
      {
 
3477
        JOIN *inner_join= sl->join;
 
3478
        if (!inner_join)
 
3479
          continue;
 
3480
        SELECT_LEX *save_select= un->thd->lex->current_select;
 
3481
        ulonglong save_options;
 
3482
        int res;
 
3483
        /* We need only 1 row to determine existence */
 
3484
        un->set_limit(un->global_parameters);
 
3485
        un->thd->lex->current_select= sl;
 
3486
        save_options= inner_join->select_options;
 
3487
        if (options & SELECT_DESCRIBE)
 
3488
        {
 
3489
          /* Optimize the subquery in the context of EXPLAIN. */
 
3490
          sl->set_explain_type();
 
3491
          sl->options|= SELECT_DESCRIBE;
 
3492
          inner_join->select_options|= SELECT_DESCRIBE;
 
3493
        }
 
3494
        res= inner_join->optimize();
 
3495
        sl->update_correlated_cache();
 
3496
        is_correlated_unit|= sl->is_correlated;
 
3497
        inner_join->select_options= save_options;
 
3498
        un->thd->lex->current_select= save_select;
 
3499
        if (empty_union_result)
 
3500
        {
 
3501
          /*
 
3502
            If at least one subquery in a union is non-empty, the UNION result
 
3503
            is non-empty. If there is no UNION, the only subquery is non-empy.
 
3504
          */
 
3505
          empty_union_result= inner_join->empty_result();
 
3506
        }
 
3507
        if (res)
 
3508
          return TRUE;
 
3509
      }
 
3510
      if (empty_union_result)
 
3511
        subquery_predicate->no_rows_in_result();
 
3512
      if (!is_correlated_unit)
 
3513
        un->uncacheable&= ~UNCACHEABLE_DEPENDENT;
 
3514
      subquery_predicate->is_correlated= is_correlated_unit;
 
3515
    }
 
3516
  }
 
3517
  return FALSE;
 
3518
}
 
3519
 
 
3520
 
 
3521
 
 
3522
/**
 
3523
  @brief Process all derived tables/views of the SELECT.
 
3524
 
 
3525
  @param lex    LEX of this thread
 
3526
  @param phase  phases to run derived tables/views through
 
3527
 
 
3528
  @details
 
3529
  This function runs specified 'phases' on all tables from the
 
3530
  table_list of this select.
 
3531
 
 
3532
  @return FALSE ok.
 
3533
  @return TRUE an error occur.
 
3534
*/
 
3535
 
 
3536
bool st_select_lex::handle_derived(LEX *lex, uint phases)
 
3537
{
 
3538
  for (TABLE_LIST *cursor= (TABLE_LIST*) table_list.first;
 
3539
       cursor;
 
3540
       cursor= cursor->next_local)
 
3541
  {
 
3542
    if (cursor->is_view_or_derived() && cursor->handle_derived(lex, phases))
 
3543
      return TRUE;
 
3544
  }
 
3545
  return FALSE;
 
3546
}
 
3547
 
 
3548
 
 
3549
/**
 
3550
  @brief
 
3551
  Returns first unoccupied table map and table number
 
3552
 
 
3553
  @param map     [out] return found map
 
3554
  @param tablenr [out] return found tablenr
 
3555
 
 
3556
  @details
 
3557
  Returns first unoccupied table map and table number in this select.
 
3558
  Map and table are returned in *'map' and *'tablenr' accordingly.
 
3559
 
 
3560
  @retrun TRUE  no free table map/table number
 
3561
  @return FALSE found free table map/table number
 
3562
*/
 
3563
 
 
3564
bool st_select_lex::get_free_table_map(table_map *map, uint *tablenr)
 
3565
{
 
3566
  *map= 0;
 
3567
  *tablenr= 0;
 
3568
  TABLE_LIST *tl;
 
3569
  List_iterator<TABLE_LIST> ti(leaf_tables);
 
3570
  while ((tl= ti++))
 
3571
  {
 
3572
    if (tl->table->map > *map)
 
3573
      *map= tl->table->map;
 
3574
    if (tl->table->tablenr > *tablenr)
 
3575
      *tablenr= tl->table->tablenr;
 
3576
  }
 
3577
  (*map)<<= 1;
 
3578
  (*tablenr)++;
 
3579
  if (*tablenr >= MAX_TABLES)
 
3580
    return TRUE;
 
3581
  return FALSE;
 
3582
}
 
3583
 
 
3584
 
 
3585
/**
 
3586
  @brief
 
3587
  Append given table to the leaf_tables list.
 
3588
 
 
3589
  @param link  Offset to which list in table structure to use
 
3590
  @param table Table to append
 
3591
 
 
3592
  @details
 
3593
  Append given 'table' to the leaf_tables list using the 'link' offset.
 
3594
  If the 'table' is linked with other tables through next_leaf/next_local
 
3595
  chains then whole list will be appended.
 
3596
*/
 
3597
 
 
3598
void st_select_lex::append_table_to_list(TABLE_LIST *TABLE_LIST::*link,
 
3599
                                         TABLE_LIST *table)
 
3600
{
 
3601
  TABLE_LIST *tl;
 
3602
  for (tl= leaf_tables.head(); tl->*link; tl= tl->*link) ;
 
3603
  tl->*link= table;
 
3604
}
 
3605
 
 
3606
 
 
3607
/*
 
3608
  @brief
 
3609
  Replace given table from the leaf_tables list for a list of tables 
 
3610
 
 
3611
  @param table Table to replace
 
3612
  @param list  List to substititute the table for
 
3613
 
 
3614
  @details
 
3615
  Replace 'table' from the leaf_tables list for a list of tables 'tbl_list'.
 
3616
*/
 
3617
 
 
3618
void st_select_lex::replace_leaf_table(TABLE_LIST *table, List<TABLE_LIST> &tbl_list)
 
3619
{
 
3620
  TABLE_LIST *tl;
 
3621
  List_iterator<TABLE_LIST> ti(leaf_tables);
 
3622
  while ((tl= ti++))
 
3623
  {
 
3624
    if (tl == table)
 
3625
    {
 
3626
      ti.replace(tbl_list);
 
3627
      break;
 
3628
    }
 
3629
  }
 
3630
}
 
3631
 
 
3632
 
 
3633
/**
 
3634
  @brief
 
3635
  Assigns new table maps to tables in the leaf_tables list
 
3636
 
 
3637
  @param derived    Derived table to take initial table map from
 
3638
  @param map        table map to begin with
 
3639
  @param tablenr    table number to begin with
 
3640
  @param parent_lex new parent select_lex
 
3641
 
 
3642
  @details
 
3643
  Assign new table maps/table numbers to all tables in the leaf_tables list.
 
3644
  'map'/'tablenr' are used for the first table and shifted to left/
 
3645
  increased for each consequent table in the leaf_tables list.
 
3646
  If the 'derived' table is given then it's table map/number is used for the
 
3647
  first table in the list and 'map'/'tablenr' are used for the second and
 
3648
  all consequent tables.
 
3649
  The 'parent_lex' is set as the new parent select_lex for all tables in the
 
3650
  list.
 
3651
*/
 
3652
 
 
3653
void st_select_lex::remap_tables(TABLE_LIST *derived, table_map map,
 
3654
                                 uint tablenr, SELECT_LEX *parent_lex)
 
3655
{
 
3656
  bool first_table= TRUE;
 
3657
  TABLE_LIST *tl;
 
3658
  table_map first_map;
 
3659
  uint first_tablenr;
 
3660
 
 
3661
  if (derived && derived->table)
 
3662
  {
 
3663
    first_map= derived->table->map;
 
3664
    first_tablenr= derived->table->tablenr;
 
3665
  }
 
3666
  else
 
3667
  {
 
3668
    first_map= map;
 
3669
    map<<= 1;
 
3670
    first_tablenr= tablenr++;
 
3671
  }
 
3672
  /*
 
3673
    Assign table bit/table number.
 
3674
    To the first table of the subselect the table bit/tablenr of the
 
3675
    derived table is assigned. The rest of tables are getting bits
 
3676
    sequentially, starting from the provided table map/tablenr.
 
3677
  */
 
3678
  List_iterator<TABLE_LIST> ti(leaf_tables);
 
3679
  while ((tl= ti++))
 
3680
  {
 
3681
    if (first_table)
 
3682
    {
 
3683
      first_table= FALSE;
 
3684
      tl->table->set_table_map(first_map, first_tablenr);
 
3685
    }
 
3686
    else
 
3687
    {
 
3688
      tl->table->set_table_map(map, tablenr);
 
3689
      tablenr++;
 
3690
      map<<= 1;
 
3691
    }
 
3692
    SELECT_LEX *old_sl= tl->select_lex;
 
3693
    tl->select_lex= parent_lex;
 
3694
    for(TABLE_LIST *emb= tl->embedding;
 
3695
        emb && emb->select_lex == old_sl;
 
3696
        emb= emb->embedding)
 
3697
      emb->select_lex= parent_lex;
 
3698
  }
 
3699
}
 
3700
 
 
3701
/**
 
3702
  @brief
 
3703
  Merge a subquery into this select.
 
3704
 
 
3705
  @param derived     derived table of the subquery to be merged
 
3706
  @param subq_select select_lex of the subquery
 
3707
  @param map         table map for assigning to merged tables from subquery
 
3708
  @param table_no    table number for assigning to merged tables from subquery
 
3709
 
 
3710
  @details
 
3711
  This function merges a subquery into its parent select. In short the
 
3712
  merge operation appends the subquery FROM table list to the parent's
 
3713
  FROM table list. In more details:
 
3714
    .) the top_join_list of the subquery is wrapped into a join_nest
 
3715
       and attached to 'derived'
 
3716
    .) subquery's leaf_tables list  is merged with the leaf_tables
 
3717
       list of this select_lex
 
3718
    .) the table maps and table numbers of the tables merged from
 
3719
       the subquery are adjusted to reflect their new binding to
 
3720
       this select
 
3721
 
 
3722
  @return TRUE  an error occur
 
3723
  @return FALSE ok
 
3724
*/
 
3725
 
 
3726
bool SELECT_LEX::merge_subquery(THD *thd, TABLE_LIST *derived,
 
3727
                                SELECT_LEX *subq_select,
 
3728
                                uint table_no, table_map map)
 
3729
{
 
3730
  derived->wrap_into_nested_join(subq_select->top_join_list);
 
3731
 
 
3732
  ftfunc_list->concat(subq_select->ftfunc_list);
 
3733
  if (join ||
 
3734
      thd->lex->sql_command == SQLCOM_UPDATE_MULTI ||
 
3735
      thd->lex->sql_command == SQLCOM_DELETE_MULTI)
 
3736
  {
 
3737
    List_iterator_fast<Item_in_subselect> li(subq_select->sj_subselects);
 
3738
    Item_in_subselect *in_subq;
 
3739
    while ((in_subq= li++))
 
3740
    {
 
3741
      sj_subselects.push_back(in_subq);
 
3742
      if (in_subq->emb_on_expr_nest == NO_JOIN_NEST)
 
3743
         in_subq->emb_on_expr_nest= derived;
 
3744
    }
 
3745
  }
 
3746
 
 
3747
  /* Walk through child's tables and adjust table map, tablenr,
 
3748
   * parent_lex */
 
3749
  subq_select->remap_tables(derived, map, table_no, this);
 
3750
  subq_select->merged_into= this;
 
3751
 
 
3752
  replace_leaf_table(derived, subq_select->leaf_tables);
 
3753
 
 
3754
  return FALSE;
 
3755
}
 
3756
 
 
3757
 
 
3758
/**
 
3759
  @brief
 
3760
  Mark tables from the leaf_tables list as belong to a derived table.
 
3761
 
 
3762
  @param derived   tables will be marked as belonging to this derived
 
3763
 
 
3764
  @details
 
3765
  Run through the leaf_list and mark all tables as belonging to the 'derived'.
 
3766
*/
 
3767
 
 
3768
void SELECT_LEX::mark_as_belong_to_derived(TABLE_LIST *derived)
 
3769
{
 
3770
  /* Mark tables as belonging to this DT */
 
3771
  TABLE_LIST *tl;
 
3772
  List_iterator<TABLE_LIST> ti(leaf_tables);
 
3773
  while ((tl= ti++))
 
3774
  {
 
3775
    tl->open_type= OT_BASE_ONLY;
 
3776
    tl->belong_to_derived= derived;
 
3777
  }
 
3778
}
 
3779
 
 
3780
 
 
3781
/**
 
3782
  @brief
 
3783
  Update used_tables cache for this select
 
3784
 
 
3785
  @details
 
3786
  This function updates used_tables cache of ON expressions of all tables
 
3787
  in the leaf_tables list and of the conds expression (if any).
 
3788
*/
 
3789
 
 
3790
void SELECT_LEX::update_used_tables()
 
3791
{
 
3792
  TABLE_LIST *tl;
 
3793
  List_iterator<TABLE_LIST> ti(leaf_tables);
 
3794
 
 
3795
  while ((tl= ti++))
 
3796
  {
 
3797
    if (tl->table && !tl->is_view_or_derived())
 
3798
    {
 
3799
      TABLE_LIST *embedding= tl->embedding;
 
3800
      for (embedding= tl->embedding; embedding; embedding=embedding->embedding)
 
3801
      {
 
3802
        if (embedding->is_view_or_derived())
 
3803
        {
 
3804
          DBUG_ASSERT(embedding->is_merged_derived());
 
3805
          TABLE *tab= tl->table;
 
3806
          tab->covering_keys= tab->s->keys_for_keyread;
 
3807
          tab->covering_keys.intersect(tab->keys_in_use_for_query);
 
3808
          tab->merge_keys.clear_all();
 
3809
          bitmap_clear_all(tab->read_set);
 
3810
          bitmap_clear_all(tab->vcol_set);
 
3811
          break;
 
3812
        }
 
3813
      }
 
3814
    }
 
3815
  }
 
3816
 
 
3817
  ti.rewind();
 
3818
  while ((tl= ti++))
 
3819
  {
 
3820
    TABLE_LIST *embedding= tl;
 
3821
    do
 
3822
    {
 
3823
      bool maybe_null;
 
3824
      if ((maybe_null= test(embedding->outer_join)))
 
3825
      {
 
3826
        tl->table->maybe_null= maybe_null;
 
3827
        break;
 
3828
      }
 
3829
    }
 
3830
    while ((embedding= embedding->embedding));
 
3831
    if (tl->on_expr)
 
3832
    {
 
3833
      tl->on_expr->update_used_tables();
 
3834
      tl->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
 
3835
    }
 
3836
    embedding= tl->embedding;
 
3837
    while (embedding)
 
3838
    {
 
3839
      if (embedding->on_expr && 
 
3840
          embedding->nested_join->join_list.head() == tl)
 
3841
      {
 
3842
        embedding->on_expr->update_used_tables();
 
3843
        embedding->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
 
3844
      }
 
3845
      tl= embedding;
 
3846
      embedding= tl->embedding;
 
3847
    }
 
3848
  }
 
3849
 
 
3850
  if (join->conds)
 
3851
  {
 
3852
    join->conds->update_used_tables();
 
3853
    join->conds->walk(&Item::eval_not_null_tables, 0, NULL);
 
3854
  }
 
3855
  if (join->having)
 
3856
  {
 
3857
    join->having->update_used_tables();
 
3858
  }
 
3859
 
 
3860
  Item *item;
 
3861
  List_iterator_fast<Item> it(join->fields_list);
 
3862
  while ((item= it++))
 
3863
  {
 
3864
    item->update_used_tables();
 
3865
  }
 
3866
  Item_outer_ref *ref;
 
3867
  List_iterator_fast<Item_outer_ref> ref_it(inner_refs_list);
 
3868
  while ((ref= ref_it++))
 
3869
  {
 
3870
    item= ref->outer_ref;
 
3871
    item->update_used_tables();
 
3872
  }
 
3873
  for (ORDER *order= group_list.first; order; order= order->next)
 
3874
    (*order->item)->update_used_tables();
 
3875
  if (!master_unit()->is_union())
 
3876
  {
 
3877
    for (ORDER *order= order_list.first; order; order= order->next)
 
3878
      (*order->item)->update_used_tables();
 
3879
  }
 
3880
  join->result->update_used_tables();
 
3881
}
 
3882
 
 
3883
 
 
3884
/**
 
3885
  @brief
 
3886
  Update is_correlated cache for this select
 
3887
 
 
3888
  @details
 
3889
*/
 
3890
 
 
3891
void st_select_lex::update_correlated_cache()
 
3892
{
 
3893
  TABLE_LIST *tl;
 
3894
  List_iterator<TABLE_LIST> ti(leaf_tables);
 
3895
 
 
3896
  is_correlated= false;
 
3897
 
 
3898
  while ((tl= ti++))
 
3899
  {
 
3900
    if (tl->on_expr)
 
3901
      is_correlated|= test(tl->on_expr->used_tables() & OUTER_REF_TABLE_BIT);
 
3902
    for (TABLE_LIST *embedding= tl->embedding ; embedding ;
 
3903
         embedding= embedding->embedding)
 
3904
    {
 
3905
      if (embedding->on_expr)
 
3906
        is_correlated|= test(embedding->on_expr->used_tables() &
 
3907
                            OUTER_REF_TABLE_BIT);
 
3908
    }
 
3909
  }
 
3910
 
 
3911
  if (join->conds)
 
3912
    is_correlated|= test(join->conds->used_tables() & OUTER_REF_TABLE_BIT);
 
3913
 
 
3914
  if (join->having)
 
3915
    is_correlated|= test(join->having->used_tables() & OUTER_REF_TABLE_BIT);
 
3916
 
 
3917
  if (join->tmp_having)
 
3918
    is_correlated|= test(join->tmp_having->used_tables() & OUTER_REF_TABLE_BIT);
 
3919
 
 
3920
  Item *item;
 
3921
  List_iterator_fast<Item> it(join->fields_list);
 
3922
  while ((item= it++))
 
3923
    is_correlated|= test(item->used_tables() & OUTER_REF_TABLE_BIT);
 
3924
 
 
3925
  for (ORDER *order= group_list.first; order; order= order->next)
 
3926
    is_correlated|= test((*order->item)->used_tables() & OUTER_REF_TABLE_BIT);
 
3927
 
 
3928
  if (!master_unit()->is_union())
 
3929
  {
 
3930
    for (ORDER *order= order_list.first; order; order= order->next)
 
3931
      is_correlated|= test((*order->item)->used_tables() & OUTER_REF_TABLE_BIT);
 
3932
  }
 
3933
 
 
3934
  if (!is_correlated)
 
3935
    uncacheable&= ~UNCACHEABLE_DEPENDENT;
 
3936
}
 
3937
 
 
3938
 
 
3939
/**
 
3940
  Set the EXPLAIN type for this subquery.
 
3941
*/
 
3942
 
 
3943
void st_select_lex::set_explain_type()
 
3944
{
 
3945
  bool is_primary= FALSE;
 
3946
  if (next_select())
 
3947
    is_primary= TRUE;
 
3948
 
 
3949
  if (!is_primary && first_inner_unit())
 
3950
  {
 
3951
    /*
 
3952
      If there is at least one materialized derived|view then it's a PRIMARY select.
 
3953
      Otherwise, all derived tables/views were merged and this select is a SIMPLE one.
 
3954
    */
 
3955
    for (SELECT_LEX_UNIT *un= first_inner_unit(); un; un= un->next_unit())
 
3956
    {
 
3957
      if ((!un->derived || un->derived->is_materialized_derived()))
 
3958
      {
 
3959
        is_primary= TRUE;
 
3960
        break;
 
3961
      }
 
3962
    }
 
3963
  }
 
3964
 
 
3965
  SELECT_LEX *first= master_unit()->first_select();
 
3966
  /* drop UNCACHEABLE_EXPLAIN, because it is for internal usage only */
 
3967
  uint8 is_uncacheable= (uncacheable & ~UNCACHEABLE_EXPLAIN);
 
3968
  
 
3969
  bool using_materialization= FALSE;
 
3970
  Item_subselect *parent_item;
 
3971
  if ((parent_item= master_unit()->item) &&
 
3972
      parent_item->substype() == Item_subselect::IN_SUBS)
 
3973
  {
 
3974
    Item_in_subselect *in_subs= (Item_in_subselect*)parent_item;
 
3975
    /*
 
3976
      Surprisingly, in_subs->is_set_strategy() can return FALSE here,
 
3977
      even for the last invocation of this function for the select.
 
3978
    */
 
3979
    if (in_subs->test_strategy(SUBS_MATERIALIZATION))
 
3980
      using_materialization= TRUE;
 
3981
  }
 
3982
 
 
3983
  if (&master_unit()->thd->lex->select_lex == this)
 
3984
  {
 
3985
     type= is_primary ? "PRIMARY" : "SIMPLE";
 
3986
  }
 
3987
  else
 
3988
  {
 
3989
    if (this == first)
 
3990
    {
 
3991
      /* If we're a direct child of a UNION, we're the first sibling there */
 
3992
      if (linkage == DERIVED_TABLE_TYPE)
 
3993
        type= "DERIVED";
 
3994
      else if (using_materialization)
 
3995
        type= "MATERIALIZED";
 
3996
      else
 
3997
      {
 
3998
         if (is_uncacheable & UNCACHEABLE_DEPENDENT)
 
3999
           type= "DEPENDENT SUBQUERY";
 
4000
         else
 
4001
         {
 
4002
           type= is_uncacheable? "UNCACHEABLE SUBQUERY" :
 
4003
                                 "SUBQUERY";
 
4004
         }
 
4005
      }
 
4006
    }
 
4007
    else
 
4008
    {
 
4009
      /* This a non-first sibling in UNION */
 
4010
      if (is_uncacheable & UNCACHEABLE_DEPENDENT)
 
4011
        type= "DEPENDENT UNION";
 
4012
      else if (using_materialization)
 
4013
        type= "MATERIALIZED UNION";
 
4014
      else
 
4015
      {
 
4016
        type= is_uncacheable ? "UNCACHEABLE UNION": "UNION";
 
4017
      }
 
4018
    }
 
4019
  }
 
4020
  options|= SELECT_DESCRIBE;
 
4021
}
 
4022
 
 
4023
 
 
4024
/**
 
4025
  @brief
 
4026
  Increase estimated number of records for a derived table/view
 
4027
 
 
4028
  @param records  number of records to increase estimate by
 
4029
 
 
4030
  @details
 
4031
  This function increases estimated number of records by the 'records'
 
4032
  for the derived table to which this select belongs to.
 
4033
*/
 
4034
 
 
4035
void SELECT_LEX::increase_derived_records(ha_rows records)
 
4036
{
 
4037
  SELECT_LEX_UNIT *unit= master_unit();
 
4038
  DBUG_ASSERT(unit->derived);
 
4039
 
 
4040
  select_union *result= (select_union*)unit->result;
 
4041
  result->records+= records;
 
4042
}
 
4043
 
 
4044
 
 
4045
/**
 
4046
  @brief
 
4047
  Mark select's derived table as a const one.
 
4048
 
 
4049
  @param empty Whether select has an empty result set
 
4050
 
 
4051
  @details
 
4052
  Mark derived table/view of this select as a constant one (to
 
4053
  materialize it at the optimization phase) unless this select belongs to a
 
4054
  union. Estimated number of rows is incremented if this select has non empty
 
4055
  result set.
 
4056
*/
 
4057
 
 
4058
void SELECT_LEX::mark_const_derived(bool empty)
 
4059
{
 
4060
  TABLE_LIST *derived= master_unit()->derived;
 
4061
  if (!join->thd->lex->describe && derived)
 
4062
  {
 
4063
    if (!empty)
 
4064
      increase_derived_records(1);
 
4065
    if (!master_unit()->is_union() && !derived->is_merged_derived())
 
4066
      derived->fill_me= TRUE;
 
4067
  }
 
4068
}
 
4069
 
 
4070
 
 
4071
bool st_select_lex::save_leaf_tables(THD *thd)
 
4072
{
 
4073
  Query_arena *arena= thd->stmt_arena, backup;
 
4074
  if (arena->is_conventional())
 
4075
    arena= 0;                                  
 
4076
  else
 
4077
    thd->set_n_backup_active_arena(arena, &backup);
 
4078
 
 
4079
  List_iterator_fast<TABLE_LIST> li(leaf_tables);
 
4080
  TABLE_LIST *table;
 
4081
  while ((table= li++))
 
4082
  {
 
4083
    if (leaf_tables_exec.push_back(table))
 
4084
      return 1;
 
4085
    table->tablenr_exec= table->get_tablenr();
 
4086
    table->map_exec= table->get_map();
 
4087
    if (join && (join->select_options & SELECT_DESCRIBE))
 
4088
      table->maybe_null_exec= 0;
 
4089
    else
 
4090
      table->maybe_null_exec= table->table?  table->table->maybe_null: 0;
 
4091
  }
 
4092
  if (arena)
 
4093
    thd->restore_active_arena(arena, &backup);
 
4094
 
 
4095
  return 0;
 
4096
}
 
4097
 
 
4098
 
 
4099
bool st_select_lex::save_prep_leaf_tables(THD *thd)
 
4100
{
 
4101
  if (!thd->save_prep_leaf_list)
 
4102
    return 0;
 
4103
 
 
4104
  Query_arena *arena= thd->stmt_arena, backup;
 
4105
  if (arena->is_conventional())
 
4106
    arena= 0;                                  
 
4107
  else
 
4108
    thd->set_n_backup_active_arena(arena, &backup);
 
4109
 
 
4110
  List_iterator_fast<TABLE_LIST> li(leaf_tables);
 
4111
  TABLE_LIST *table;
 
4112
  while ((table= li++))
 
4113
  {
 
4114
    if (leaf_tables_prep.push_back(table))
 
4115
      return 1;
 
4116
  }
 
4117
  thd->lex->select_lex.is_prep_leaf_list_saved= TRUE; 
 
4118
  thd->save_prep_leaf_list= FALSE;
 
4119
  if (arena)
 
4120
    thd->restore_active_arena(arena, &backup);
 
4121
 
 
4122
  return 0;
 
4123
}
 
4124
 
 
4125
 
 
4126
/*
 
4127
  Return true if this select_lex has been converted into a semi-join nest
 
4128
  within 'ancestor'.
 
4129
 
 
4130
  We need a loop to check this because there could be several nested
 
4131
  subselects, like
 
4132
 
 
4133
    SELECT ... FROM grand_parent 
 
4134
      WHERE expr1 IN (SELECT ... FROM parent 
 
4135
                        WHERE expr2 IN ( SELECT ... FROM child)
 
4136
 
 
4137
  which were converted into:
 
4138
  
 
4139
    SELECT ... 
 
4140
    FROM grand_parent SEMI_JOIN (parent JOIN child) 
 
4141
    WHERE 
 
4142
      expr1 AND expr2
 
4143
 
 
4144
  In this case, both parent and child selects were merged into the parent.
 
4145
*/
 
4146
 
 
4147
bool st_select_lex::is_merged_child_of(st_select_lex *ancestor)
 
4148
{
 
4149
  bool all_merged= TRUE;
 
4150
  for (SELECT_LEX *sl= this; sl && sl!=ancestor;
 
4151
       sl=sl->outer_select())
 
4152
  {
 
4153
    Item *subs= sl->master_unit()->item;
 
4154
    if (subs && subs->type() == Item::SUBSELECT_ITEM && 
 
4155
        ((Item_subselect*)subs)->substype() == Item_subselect::IN_SUBS &&
 
4156
        ((Item_in_subselect*)subs)->test_strategy(SUBS_SEMI_JOIN))
 
4157
    {
 
4158
      continue;
 
4159
    }
 
4160
    all_merged= FALSE;
 
4161
    break;
 
4162
  }
 
4163
  return all_merged;
 
4164
}
 
4165
 
 
4166
 
 
4167
/**
 
4168
  A routine used by the parser to decide whether we are specifying a full
 
4169
  partitioning or if only partitions to add or to split.
 
4170
 
 
4171
  @note  This needs to be outside of WITH_PARTITION_STORAGE_ENGINE since it
 
4172
  is used from the sql parser that doesn't have any ifdef's
 
4173
 
 
4174
  @retval  TRUE    Yes, it is part of a management partition command
 
4175
  @retval  FALSE          No, not a management partition command
 
4176
*/
 
4177
 
 
4178
bool LEX::is_partition_management() const
 
4179
{
 
4180
  return (sql_command == SQLCOM_ALTER_TABLE &&
 
4181
          (alter_info.flags == ALTER_ADD_PARTITION ||
 
4182
           alter_info.flags == ALTER_REORGANIZE_PARTITION));
 
4183
}
 
4184
 
 
4185
#ifdef MYSQL_SERVER
 
4186
uint binlog_unsafe_map[256];
 
4187
 
 
4188
#define UNSAFE(a, b, c) \
 
4189
  { \
 
4190
  DBUG_PRINT("unsafe_mixed_statement", ("SETTING BASE VALUES: %s, %s, %02X\n", \
 
4191
    LEX::stmt_accessed_table_string(a), \
 
4192
    LEX::stmt_accessed_table_string(b), \
 
4193
    c)); \
 
4194
  unsafe_mixed_statement(a, b, c); \
 
4195
  }
 
4196
 
 
4197
/*
 
4198
  Sets the combination given by "a" and "b" and automatically combinations
 
4199
  given by other types of access, i.e. 2^(8 - 2), as unsafe.
 
4200
 
 
4201
  It may happen a colision when automatically defining a combination as unsafe.
 
4202
  For that reason, a combination has its unsafe condition redefined only when
 
4203
  the new_condition is greater then the old. For instance,
 
4204
  
 
4205
     . (BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY) is never overwritten by 
 
4206
     . (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF).
 
4207
*/
 
4208
void unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,
 
4209
                            LEX::enum_stmt_accessed_table b, uint condition)
 
4210
{
 
4211
  int type= 0;
 
4212
  int index= (1U << a) | (1U << b);
 
4213
  
 
4214
  
 
4215
  for (type= 0; type < 256; type++)
 
4216
  {
 
4217
    if ((type & index) == index)
 
4218
    {
 
4219
      binlog_unsafe_map[type] |= condition;
 
4220
    }
 
4221
  }
 
4222
}
 
4223
/*
 
4224
  The BINLOG_* AND TRX_CACHE_* values can be combined by using '&' or '|',
 
4225
  which means that both conditions need to be satisfied or any of them is
 
4226
  enough. For example, 
 
4227
    
 
4228
    . BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY means that the statment is
 
4229
    unsafe when the option is on and trx-cache is not empty;
 
4230
 
 
4231
    . BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF means the statement is unsafe
 
4232
    in all cases.
 
4233
 
 
4234
    . TRX_CACHE_EMPTY | TRX_CACHE_NOT_EMPTY means the statement is unsafe
 
4235
    in all cases. Similar as above.
 
4236
*/
 
4237
void binlog_unsafe_map_init()
 
4238
{
 
4239
  memset((void*) binlog_unsafe_map, 0, sizeof(uint) * 256);
 
4240
 
 
4241
  /*
 
4242
    Classify a statement as unsafe when there is a mixed statement and an
 
4243
    on-going transaction at any point of the execution if:
 
4244
 
 
4245
      1. The mixed statement is about to update a transactional table and
 
4246
      a non-transactional table.
 
4247
 
 
4248
      2. The mixed statement is about to update a transactional table and
 
4249
      read from a non-transactional table.
 
4250
 
 
4251
      3. The mixed statement is about to update a non-transactional table
 
4252
      and temporary transactional table.
 
4253
 
 
4254
      4. The mixed statement is about to update a temporary transactional
 
4255
      table and read from a non-transactional table.
 
4256
 
 
4257
      5. The mixed statement is about to update a transactional table and
 
4258
      a temporary non-transactional table.
 
4259
     
 
4260
      6. The mixed statement is about to update a transactional table and
 
4261
      read from a temporary non-transactional table.
 
4262
 
 
4263
      7. The mixed statement is about to update a temporary transactional
 
4264
      table and temporary non-transactional table.
 
4265
 
 
4266
      8. The mixed statement is about to update a temporary transactional
 
4267
      table and read from a temporary non-transactional table.
 
4268
 
 
4269
    After updating a transactional table if:
 
4270
 
 
4271
      9. The mixed statement is about to update a non-transactional table
 
4272
      and read from a transactional table.
 
4273
 
 
4274
      10. The mixed statement is about to update a non-transactional table
 
4275
      and read from a temporary transactional table.
 
4276
 
 
4277
      11. The mixed statement is about to update a temporary non-transactional
 
4278
      table and read from a transactional table.
 
4279
      
 
4280
      12. The mixed statement is about to update a temporary non-transactional
 
4281
      table and read from a temporary transactional table.
 
4282
 
 
4283
      13. The mixed statement is about to update a temporary non-transactional
 
4284
      table and read from a non-transactional table.
 
4285
 
 
4286
    The reason for this is that locks acquired may not protected a concurrent
 
4287
    transaction of interfering in the current execution and by consequence in
 
4288
    the result.
 
4289
  */
 
4290
  /* Case 1. */
 
4291
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_NON_TRANS_TABLE,
 
4292
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
 
4293
  /* Case 2. */
 
4294
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
 
4295
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
 
4296
  /* Case 3. */
 
4297
  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_WRITES_TEMP_TRANS_TABLE,
 
4298
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
 
4299
  /* Case 4. */
 
4300
  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
 
4301
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
 
4302
  /* Case 5. */
 
4303
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
 
4304
    BINLOG_DIRECT_ON);
 
4305
  /* Case 6. */
 
4306
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
 
4307
    BINLOG_DIRECT_ON);
 
4308
  /* Case 7. */
 
4309
  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
 
4310
    BINLOG_DIRECT_ON);
 
4311
  /* Case 8. */
 
4312
  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
 
4313
    BINLOG_DIRECT_ON);
 
4314
  /* Case 9. */
 
4315
  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
 
4316
    (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
 
4317
  /* Case 10 */
 
4318
  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
 
4319
    (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
 
4320
  /* Case 11. */
 
4321
  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
 
4322
    BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
 
4323
  /* Case 12. */
 
4324
  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
 
4325
    BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
 
4326
  /* Case 13. */
 
4327
  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
 
4328
     BINLOG_DIRECT_OFF & TRX_CACHE_NOT_EMPTY);
 
4329
}
 
4330
#endif
 
4331
 
 
4332
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
 
4333
template class Mem_root_array<ORDER*, true>;
 
4334
#endif