sql_lex.cc 298 KB
Newer Older
Sergei Golubchik's avatar
Sergei Golubchik committed
1
/* Copyright (c) 2000, 2014, Oracle and/or its affiliates.
Marko Mäkelä's avatar
Marko Mäkelä committed
2
   Copyright (c) 2009, 2019, MariaDB Corporation
unknown's avatar
unknown committed
3

unknown's avatar
unknown committed
4 5
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
6
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
7

unknown's avatar
unknown committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
unknown's avatar
unknown committed
12

unknown's avatar
unknown committed
13 14
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
Vicențiu Ciorbaru's avatar
Vicențiu Ciorbaru committed
15
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335  USA */
unknown's avatar
unknown committed
16 17 18 19


/* A lexical scanner on a temporary buffer with a yacc interface */

20
#define MYSQL_LEX 1
21
#include "mariadb.h"
22 23 24 25
#include "sql_priv.h"
#include "sql_class.h"                          // sql_lex.h: SQLCOM_END
#include "sql_lex.h"
#include "sql_parse.h"                          // add_to_list
unknown's avatar
unknown committed
26 27 28
#include "item_create.h"
#include <m_ctype.h>
#include <hash.h>
29
#include "sp_head.h"
30
#include "sp.h"
31
#include "sql_select.h"
32
#include "sql_cte.h"
33
#include "sql_signal.h"
34 35
#include "sql_truncate.h"                      // Sql_cmd_truncate_table
#include "sql_admin.h"                         // Sql_cmd_analyze/Check..._table
36
#include "sql_partition.h"
37
#include "sql_partition_admin.h"               // Sql_cmd_alter_table_*_part
38
#include "event_parse_data.h"
39

40
void LEX::parse_error(uint err_number)
41
{
42
  thd->parse_error(err_number);
43 44
}

unknown's avatar
unknown committed
45

46 47 48
/**
  LEX_STRING constant for null-string to be used in parser and other places.
*/
49 50 51 52 53 54
const LEX_STRING empty_lex_str=   {(char *) "", 0};
const LEX_CSTRING null_clex_str=  {NULL, 0};
const LEX_CSTRING empty_clex_str= {"", 0};
const LEX_CSTRING star_clex_str=  {"*", 1};
const LEX_CSTRING param_clex_str= {"?", 1};

55 56 57 58 59 60 61 62 63 64
/**
  @note The order of the elements of this array must correspond to
  the order of elements in enum_binlog_stmt_unsafe.
*/
const int
Query_tables_list::binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT] =
{
  ER_BINLOG_UNSAFE_LIMIT,
  ER_BINLOG_UNSAFE_INSERT_DELAYED,
  ER_BINLOG_UNSAFE_SYSTEM_TABLE,
65
  ER_BINLOG_UNSAFE_AUTOINC_COLUMNS,
66 67
  ER_BINLOG_UNSAFE_UDF,
  ER_BINLOG_UNSAFE_SYSTEM_VARIABLE,
68
  ER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
69
  ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS,
70 71
  ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
  ER_BINLOG_UNSAFE_MIXED_STATEMENT,
72 73
  ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT,
  ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE,
74
  ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT,
75 76 77
  ER_BINLOG_UNSAFE_REPLACE_SELECT,
  ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT,
  ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT,
78
  ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC,
79
  ER_BINLOG_UNSAFE_UPDATE_IGNORE,
80 81
  ER_BINLOG_UNSAFE_INSERT_TWO_KEYS,
  ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST
82 83
};

84

85
/* Longest standard keyword name */
86

unknown's avatar
unknown committed
87 88
#define TOCK_NAME_LENGTH 24

89 90
/*
  The following data is based on the latin1 character set, and is only
unknown's avatar
unknown committed
91 92 93
  used when comparing keywords
*/

unknown's avatar
unknown committed
94 95
static uchar to_upper_lex[]=
{
unknown's avatar
unknown committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
   16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
   32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
   48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
   64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
   80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
   96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
   80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127,
  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
  160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  208,209,210,211,212,213,214,247,216,217,218,219,220,221,222,255
};

114 115 116 117 118 119 120 121 122 123 124
/* 
  Names of the index hints (for error messages). Keep in sync with 
  index_hint_type 
*/

const char * index_hint_type_name[] =
{
  "IGNORE INDEX", 
  "USE INDEX", 
  "FORCE INDEX"
};
125

unknown's avatar
unknown committed
126 127 128
inline int lex_casecmp(const char *s, const char *t, uint len)
{
  while (len-- != 0 &&
129
         to_upper_lex[(uchar) *s++] == to_upper_lex[(uchar) *t++]) ;
unknown's avatar
unknown committed
130 131 132
  return (int) len+1;
}

unknown's avatar
unknown committed
133
#include <lex_hash.h>
unknown's avatar
unknown committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149


void lex_init(void)
{
  uint i;
  DBUG_ENTER("lex_init");
  for (i=0 ; i < array_elements(symbols) ; i++)
    symbols[i].length=(uchar) strlen(symbols[i].name);
  for (i=0 ; i < array_elements(sql_functions) ; i++)
    sql_functions[i].length=(uchar) strlen(sql_functions[i].name);

  DBUG_VOID_RETURN;
}


void lex_free(void)
150
{                                        // Call this when daemon ends
unknown's avatar
unknown committed
151 152 153 154
  DBUG_ENTER("lex_free");
  DBUG_VOID_RETURN;
}

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
/**
  Initialize lex object for use in fix_fields and parsing.

  SYNOPSIS
    init_lex_with_single_table()
    @param thd                 The thread object
    @param table               The table object
  @return Operation status
    @retval TRUE                An error occurred, memory allocation error
    @retval FALSE               Ok

  DESCRIPTION
    This function is used to initialize a lex object on the
    stack for use by fix_fields and for parsing. In order to
    work properly it also needs to initialize the
    Name_resolution_context object of the lexer.
    Finally it needs to set a couple of variables to ensure
    proper functioning of fix_fields.
*/

int
init_lex_with_single_table(THD *thd, TABLE *table, LEX *lex)
{
  TABLE_LIST *table_list;
  Table_ident *table_ident;
180
  SELECT_LEX *select_lex= lex->first_select_lex();
181 182 183 184 185 186 187 188 189 190 191 192
  Name_resolution_context *context= &select_lex->context;
  /*
    We will call the parser to create a part_info struct based on the
    partition string stored in the frm file.
    We will use a local lex object for this purpose. However we also
    need to set the Name_resolution_object for this lex object. We
    do this by using add_table_to_list where we add the table that
    we're working with to the Name_resolution_context.
  */
  thd->lex= lex;
  lex_start(thd);
  context->init();
193 194 195 196 197 198 199 200
  if (unlikely((!(table_ident= new Table_ident(thd,
                                               &table->s->db,
                                               &table->s->table_name,
                                               TRUE)))) ||
      (unlikely(!(table_list= select_lex->add_table_to_list(thd,
                                                            table_ident,
                                                            NULL,
                                                            0)))))
201 202 203
    return TRUE;
  context->resolve_in_table_list_only(table_list);
  lex->use_only_table_context= TRUE;
Sergei Golubchik's avatar
Sergei Golubchik committed
204
  lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VCOL_EXPR;
205 206 207
  select_lex->cur_pos_in_select_list= UNDEF_POS;
  table->map= 1; //To ensure correct calculation of const item
  table_list->table= table;
Sergei Golubchik's avatar
Sergei Golubchik committed
208
  table_list->cacheable_table= false;
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
  return FALSE;
}

/**
  End use of local lex with single table

  SYNOPSIS
    end_lex_with_single_table()
    @param thd               The thread object
    @param table             The table object
    @param old_lex           The real lex object connected to THD

  DESCRIPTION
    This function restores the real lex object after calling
    init_lex_with_single_table and also restores some table
    variables temporarily set.
*/

void
end_lex_with_single_table(THD *thd, TABLE *table, LEX *old_lex)
{
  LEX *lex= thd->lex;
  table->map= 0;
  table->get_fields_in_item_tree= FALSE;
  lex_end(lex);
  thd->lex= old_lex;
}

unknown's avatar
unknown committed
237

238 239 240 241 242 243
void
st_parsing_options::reset()
{
  allows_variable= TRUE;
}

244 245 246 247 248

/**
  Perform initialization of Lex_input_stream instance.

  Basically, a buffer for pre-processed query. This buffer should be large
249 250
  enough to keep multi-statement query. The allocation is done once in
  Lex_input_stream::init() in order to prevent memory pollution when
251 252 253
  the server is processing large multi-statement queries.
*/

254
bool Lex_input_stream::init(THD *thd,
255 256
                            char* buff,
                            size_t length)
257
{
258 259 260
  DBUG_EXECUTE_IF("bug42064_simulate_oom",
                  DBUG_SET("+d,simulate_out_of_memory"););

261
  m_cpp_buf= (char*) thd->alloc(length + 1);
262 263 264 265 266

  DBUG_EXECUTE_IF("bug42064_simulate_oom",
                  DBUG_SET("-d,bug42064_simulate_oom");); 

  if (m_cpp_buf == NULL)
267
    return true;
268 269

  m_thd= thd;
270
  reset(buff, length);
271

272
  return false;
273 274 275 276 277 278 279 280 281 282 283 284
}


/**
  Prepare Lex_input_stream instance state for use for handling next SQL statement.

  It should be called between two statements in a multi-statement query.
  The operation resets the input stream to the beginning-of-parse state,
  but does not reallocate m_cpp_buf.
*/

void
285
Lex_input_stream::reset(char *buffer, size_t length)
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
{
  yylineno= 1;
  lookahead_token= -1;
  lookahead_yylval= NULL;
  m_ptr= buffer;
  m_tok_start= NULL;
  m_tok_end= NULL;
  m_end_of_query= buffer + length;
  m_tok_start_prev= NULL;
  m_buf= buffer;
  m_buf_length= length;
  m_echo= TRUE;
  m_cpp_tok_start= NULL;
  m_cpp_tok_start_prev= NULL;
  m_cpp_tok_end= NULL;
  m_body_utf8= NULL;
  m_cpp_utf8_processed_ptr= NULL;
  next_state= MY_LEX_START;
  found_semicolon= NULL;
305
  ignore_space= MY_TEST(m_thd->variables.sql_mode & MODE_IGNORE_SPACE);
306 307 308 309
  stmt_prepare_mode= FALSE;
  multi_statements= TRUE;
  in_comment=NO_COMMENT;
  m_underscore_cs= NULL;
310
  m_cpp_ptr= m_cpp_buf;
311 312 313
}


unknown's avatar
unknown committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
/**
  The operation is called from the parser in order to
  1) designate the intention to have utf8 body;
  1) Indicate to the lexer that we will need a utf8 representation of this
     statement;
  2) Determine the beginning of the body.

  @param thd        Thread context.
  @param begin_ptr  Pointer to the start of the body in the pre-processed
                    buffer.
*/

void Lex_input_stream::body_utf8_start(THD *thd, const char *begin_ptr)
{
  DBUG_ASSERT(begin_ptr);
  DBUG_ASSERT(m_cpp_buf <= begin_ptr && begin_ptr <= m_cpp_buf + m_buf_length);

331
  size_t body_utf8_length= get_body_utf8_maximum_length(thd);
unknown's avatar
unknown committed
332 333 334 335 336 337 338 339

  m_body_utf8= (char *) thd->alloc(body_utf8_length + 1);
  m_body_utf8_ptr= m_body_utf8;
  *m_body_utf8_ptr= 0;

  m_cpp_utf8_processed_ptr= begin_ptr;
}

340

341
size_t Lex_input_stream::get_body_utf8_maximum_length(THD *thd)
342 343 344 345 346 347 348 349 350 351 352 353 354 355
{
  /*
    String literals can grow during escaping:
    1a. Character string '<TAB>' can grow to '\t', 3 bytes to 4 bytes growth.
    1b. Character string '1000 times <TAB>' grows from
        1002 to 2002 bytes (including quotes), which gives a little bit
        less than 2 times growth.
    "2" should be a reasonable multiplier that safely covers escaping needs.
  */
  return (m_buf_length / thd->variables.character_set_client->mbminlen) *
          my_charset_utf8_bin.mbmaxlen * 2/*for escaping*/;
}


unknown's avatar
unknown committed
356
/**
unknown's avatar
unknown committed
357
  @brief The operation appends unprocessed part of pre-processed buffer till
unknown's avatar
unknown committed
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
  the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to end_ptr.

  The idea is that some tokens in the pre-processed buffer (like character
  set introducers) should be skipped.

  Example:
    CPP buffer: SELECT 'str1', _latin1 'str2';
    m_cpp_utf8_processed_ptr -- points at the "SELECT ...";
    In order to skip "_latin1", the following call should be made:
      body_utf8_append(<pointer to "_latin1 ...">, <pointer to " 'str2'...">)

  @param ptr      Pointer in the pre-processed buffer, which specifies the
                  end of the chunk, which should be appended to the utf8
                  body.
  @param end_ptr  Pointer in the pre-processed buffer, to which
                  m_cpp_utf8_processed_ptr will be set in the end of the
                  operation.
*/

void Lex_input_stream::body_utf8_append(const char *ptr,
                                        const char *end_ptr)
{
  DBUG_ASSERT(m_cpp_buf <= ptr && ptr <= m_cpp_buf + m_buf_length);
  DBUG_ASSERT(m_cpp_buf <= end_ptr && end_ptr <= m_cpp_buf + m_buf_length);

  if (!m_body_utf8)
    return;

  if (m_cpp_utf8_processed_ptr >= ptr)
    return;

389
  size_t bytes_to_copy= ptr - m_cpp_utf8_processed_ptr;
unknown's avatar
unknown committed
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422

  memcpy(m_body_utf8_ptr, m_cpp_utf8_processed_ptr, bytes_to_copy);
  m_body_utf8_ptr += bytes_to_copy;
  *m_body_utf8_ptr= 0;

  m_cpp_utf8_processed_ptr= end_ptr;
}

/**
  The operation appends unprocessed part of the pre-processed buffer till
  the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to ptr.

  @param ptr  Pointer in the pre-processed buffer, which specifies the end
              of the chunk, which should be appended to the utf8 body.
*/

void Lex_input_stream::body_utf8_append(const char *ptr)
{
  body_utf8_append(ptr, ptr);
}

/**
  The operation converts the specified text literal to the utf8 and appends
  the result to the utf8-body.

  @param thd      Thread context.
  @param txt      Text literal.
  @param txt_cs   Character set of the text literal.
  @param end_ptr  Pointer in the pre-processed buffer, to which
                  m_cpp_utf8_processed_ptr will be set in the end of the
                  operation.
*/

423 424 425 426
void
Lex_input_stream::body_utf8_append_ident(THD *thd,
                                         const Lex_string_with_metadata_st *txt,
                                         const char *end_ptr)
unknown's avatar
unknown committed
427 428 429 430
{
  if (!m_cpp_utf8_processed_ptr)
    return;

431
  LEX_CSTRING utf_txt;
432
  thd->make_text_string_sys(&utf_txt, txt); // QQ: check return value?
unknown's avatar
unknown committed
433 434 435 436 437 438 439 440 441

  /* NOTE: utf_txt.length is in bytes, not in symbols. */
  memcpy(m_body_utf8_ptr, utf_txt.str, utf_txt.length);
  m_body_utf8_ptr += utf_txt.length;
  *m_body_utf8_ptr= 0;

  m_cpp_utf8_processed_ptr= end_ptr;
}

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462



extern "C" {

/**
  Escape a character. Consequently puts "escape" and "wc" characters into
  the destination utf8 string.
  @param cs     - the character set (utf8)
  @param escape - the escape character (backslash, single quote, double quote)
  @param wc     - the character to be escaped
  @param str    - the destination string
  @param end    - the end of the destination string
  @returns      - a code according to the wc_mb() convension.
*/
int my_wc_mb_utf8_with_escape(CHARSET_INFO *cs, my_wc_t escape, my_wc_t wc,
                              uchar *str, uchar *end)
{
  DBUG_ASSERT(escape > 0);
  if (str + 1 >= end)
    return MY_CS_TOOSMALL2;  // Not enough space, need at least two bytes.
463
  *str= (uchar)escape;
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
  int cnvres= my_charset_utf8_handler.wc_mb(cs, wc, str + 1, end);
  if (cnvres > 0)
    return cnvres + 1;       // The character was normally put
  if (cnvres == MY_CS_ILUNI)
    return MY_CS_ILUNI;      // Could not encode "wc" (e.g. non-BMP character)
  DBUG_ASSERT(cnvres <= MY_CS_TOOSMALL);
  return cnvres - 1;         // Not enough space
}


/**
  Optionally escape a character.
  If "escape" is non-zero, then both "escape" and "wc" are put to
  the destination string. Otherwise, only "wc" is put.
  @param cs     - the character set (utf8)
  @param wc     - the character to be optionally escaped
  @param escape - the escape character, or 0
  @param ewc    - the escaped replacement of "wc" (e.g. 't' for '\t')
  @param str    - the destination string
  @param end    - the end of the destination string
  @returns      - a code according to the wc_mb() conversion.
*/
int my_wc_mb_utf8_opt_escape(CHARSET_INFO *cs,
                             my_wc_t wc, my_wc_t escape, my_wc_t ewc,
                             uchar *str, uchar *end)
{
  return escape ? my_wc_mb_utf8_with_escape(cs, escape, ewc, str, end) :
                  my_charset_utf8_handler.wc_mb(cs, wc, str, end);
}

/**
  Encode a character with optional backlash escaping and quote escaping.
  Quote marks are escaped using another quote mark.
  Additionally, if "escape" is non-zero, then special characters are
  also escaped using "escape".
  Otherwise (if "escape" is zero, e.g. in case of MODE_NO_BACKSLASH_ESCAPES),
  then special characters are not escaped and handled as normal characters.

  @param cs        - the character set (utf8)
  @param wc        - the character to be encoded
  @param str       - the destination string
  @param end       - the end of the destination string
  @param sep       - the string delimiter (e.g. ' or ")
  @param escape    - the escape character (backslash, or 0)
  @returns         - a code according to the wc_mb() convension.
*/
int my_wc_mb_utf8_escape(CHARSET_INFO *cs, my_wc_t wc, uchar *str, uchar *end,
                         my_wc_t sep, my_wc_t escape)
{
  DBUG_ASSERT(escape == 0 || escape == '\\');
  DBUG_ASSERT(sep == '"' || sep == '\'');
  switch (wc) {
  case 0:      return my_wc_mb_utf8_opt_escape(cs, wc, escape, '0', str, end);
  case '\t':   return my_wc_mb_utf8_opt_escape(cs, wc, escape, 't', str, end);
  case '\r':   return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'r', str, end);
  case '\n':   return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'n', str, end);
  case '\032': return my_wc_mb_utf8_opt_escape(cs, wc, escape, 'Z', str, end);
  case '\'':
  case '\"':
    if (wc == sep)
      return my_wc_mb_utf8_with_escape(cs, wc, wc, str, end);
  }
  return my_charset_utf8_handler.wc_mb(cs, wc, str, end); // No escaping needed
}


/** wc_mb() compatible routines for all sql_mode and delimiter combinations */
int my_wc_mb_utf8_escape_single_quote_and_backslash(CHARSET_INFO *cs,
                                                    my_wc_t wc,
                                                    uchar *str, uchar *end)
{
  return my_wc_mb_utf8_escape(cs, wc, str, end, '\'', '\\');
}


int my_wc_mb_utf8_escape_double_quote_and_backslash(CHARSET_INFO *cs,
                                                    my_wc_t wc,
                                                    uchar *str, uchar *end)
{
  return my_wc_mb_utf8_escape(cs, wc, str, end, '"', '\\');
}


int my_wc_mb_utf8_escape_single_quote(CHARSET_INFO *cs, my_wc_t wc,
                                      uchar *str, uchar *end)
{
  return my_wc_mb_utf8_escape(cs, wc, str, end, '\'', 0);
}


int my_wc_mb_utf8_escape_double_quote(CHARSET_INFO *cs, my_wc_t wc,
                                      uchar *str, uchar *end)
{
  return my_wc_mb_utf8_escape(cs, wc, str, end, '"', 0);
}

}; // End of extern "C"


/**
  Get an escaping function, depending on the current sql_mode and the
  string separator.
*/
my_charset_conv_wc_mb
Lex_input_stream::get_escape_func(THD *thd, my_wc_t sep) const
{
  return thd->backslash_escapes() ?
         (sep == '"' ? my_wc_mb_utf8_escape_double_quote_and_backslash:
                       my_wc_mb_utf8_escape_single_quote_and_backslash) :
         (sep == '"' ? my_wc_mb_utf8_escape_double_quote:
                       my_wc_mb_utf8_escape_single_quote);
}


/**
  Append a text literal to the end of m_body_utf8.
  The string is escaped according to the current sql_mode and the
  string delimiter (e.g. ' or ").

  @param thd       - current THD
  @param txt       - the string to be appended to m_body_utf8.
                     Note, the string must be already unescaped.
  @param cs        - the character set of the string
  @param end_ptr   - m_cpp_utf8_processed_ptr will be set to this value
                     (see body_utf8_append_ident for details)
  @param sep       - the string delimiter (single or double quote)
*/
void Lex_input_stream::body_utf8_append_escape(THD *thd,
592
                                               const LEX_CSTRING *txt,
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
                                               CHARSET_INFO *cs,
                                               const char *end_ptr,
                                               my_wc_t sep)
{
  DBUG_ASSERT(sep == '\'' || sep == '"');
  if (!m_cpp_utf8_processed_ptr)
    return;
  uint errors;
  /**
    We previously alloced m_body_utf8 to be able to store the query with all
    strings properly escaped. See get_body_utf8_maximum_length().
    So here we have guaranteedly enough space to append any string literal
    with escaping. Passing txt->length*2 as "available space" is always safe.
    For better safety purposes we could calculate get_body_utf8_maximum_length()
    every time we append a string, but this would affect performance negatively,
    so let's check that we don't get beyond the allocated buffer in
    debug build only.
  */
  DBUG_ASSERT(m_body_utf8 + get_body_utf8_maximum_length(thd) >=
              m_body_utf8_ptr + txt->length * 2);
  uint32 cnv_length= my_convert_using_func(m_body_utf8_ptr, txt->length * 2,
                                           &my_charset_utf8_general_ci,
                                           get_escape_func(thd, sep),
                                           txt->str, txt->length,
                                           cs, cs->cset->mb_wc,
                                           &errors);
  m_body_utf8_ptr+= cnv_length;
  *m_body_utf8_ptr= 0;
  m_cpp_utf8_processed_ptr= end_ptr;
}


Sergei Golubchik's avatar
Sergei Golubchik committed
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
void Lex_input_stream::add_digest_token(uint token, LEX_YYSTYPE yylval)
{
  if (m_digest != NULL)
  {
    m_digest= digest_add_token(m_digest, token, yylval);
  }
}

void Lex_input_stream::reduce_digest_token(uint token_left, uint token_right)
{
  if (m_digest != NULL)
  {
    m_digest= digest_reduce_token(m_digest, token_left, token_right);
  }
}
640

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
/**
  lex starting operations for builtin select collected together
*/

void SELECT_LEX::lex_start(LEX *plex)
{
  SELECT_LEX_UNIT *unit= &plex->unit;
  /* 'parent_lex' is used in init_query() so it must be before it. */
  parent_lex= plex;
  init_query();
  master= unit;
  prev= &unit->slave;
  link_next= slave= next= 0;
  link_prev= (st_select_lex_node**)&(plex->all_selects_list);
  DBUG_ASSERT(!group_list_ptrs);
  select_number= 1;
  in_sum_expr=0;
  ftfunc_list_alloc.empty();
  ftfunc_list= &ftfunc_list_alloc;
  group_list.empty();
  order_list.empty();
  gorder_list.empty();
}

665 666 667 668 669 670 671 672
void lex_start(THD *thd)
{
  DBUG_ENTER("lex_start");
  thd->lex->start(thd);
  DBUG_VOID_RETURN;
}


673 674 675 676 677 678
/*
  This is called before every query that is to be parsed.
  Because of this, it's critical to not do too much things here.
  (We already do too much here)
*/

679
void LEX::start(THD *thd_arg)
unknown's avatar
unknown committed
680
{
681
  DBUG_ENTER("LEX::start");
682
  DBUG_PRINT("info", ("This: %p thd_arg->lex: %p", this, thd_arg->lex));
unknown's avatar
unknown committed
683

684
  thd= unit.thd= thd_arg;
685
  stmt_lex= this; // default, should be rewritten for VIEWs And CTEs
686

687
  DBUG_ASSERT(!explain);
unknown's avatar
unknown committed
688

689 690
  builtin_select.lex_start(this);
  lex_options= 0;
691
  context_stack.empty();
692 693
  //empty select_stack
  select_stack_top= 0;
694
  unit.init_query();
695
  current_select_number= 0;
696 697 698
  curr_with_clause= 0;
  with_clauses_list= 0;
  with_clauses_list_last_next= &with_clauses_list;
699
  clone_spec_offset= 0;
700
  create_view= NULL;
701
  field_list.empty();
702 703 704 705 706 707 708 709 710
  value_list.empty();
  update_list.empty();
  set_var_list.empty();
  param_list.empty();
  view_list.empty();
  with_column_list.empty();
  with_persistent_for_clause= FALSE;
  column_list= NULL;
  index_list= NULL;
711
  prepared_stmt.lex_start();
712 713 714
  auxiliary_table_list.empty();
  unit.next= unit.master= unit.link_next= unit.return_to= 0;
  unit.prev= unit.link_prev= 0;
715 716
  unit.slave= current_select= all_selects_list= &builtin_select;
  sql_cache= LEX::SQL_CACHE_UNSPECIFIED;
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
  describe= 0;
  analyze_stmt= 0;
  explain_json= false;
  context_analysis_only= 0;
  derived_tables= 0;
  safe_to_cache_query= 1;
  parsing_options.reset();
  empty_field_list_on_rset= 0;
  part_info= 0;
  m_sql_cmd= NULL;
  duplicates= DUP_ERROR;
  ignore= 0;
  spname= NULL;
  spcont= NULL;
  proc_list.first= 0;
  escape_used= FALSE;
733
  default_used= FALSE;
734 735 736
  query_tables= 0;
  reset_query_tables_list(FALSE);
  expr_allows_subselect= TRUE;
737 738
  selects_allow_into= FALSE;
  selects_allow_procedure= FALSE;
739 740 741 742 743 744
  use_only_table_context= FALSE;
  parse_vcol_expr= FALSE;
  check_exists= FALSE;
  create_info.lex_start();
  verbose= 0;

745
  name= null_clex_str;
746 747
  event_parse_data= NULL;
  profile_options= PROFILE_NONE;
748 749
  nest_level= 0;
  builtin_select.nest_level_base= &unit;
750
  allow_sum_func.clear_all();
751 752 753
  in_sum_func= NULL;

  used_tables= 0;
754
  table_type= TABLE_TYPE_UNKNOWN;
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
  reset_slave_info.all= false;
  limit_rows_examined= 0;
  limit_rows_examined_cnt= ULONGLONG_MAX;
  var_list.empty();
  stmt_var_list.empty();
  proc_list.elements=0;

  save_group_list.empty();
  save_order_list.empty();
  win_ref= NULL;
  win_frame= NULL;
  frame_top_bound= NULL;
  frame_bottom_bound= NULL;
  win_spec= NULL;

770
  vers_conditions.empty();
771
  period_conditions.empty();
772

773
  is_lex_started= TRUE;
774 775 776 777 778 779 780

  next_is_main= FALSE;
  next_is_down= FALSE;

  wild= 0;
  exchange= 0;

unknown's avatar
unknown committed
781
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
782 783 784 785
}

void lex_end(LEX *lex)
{
unknown's avatar
unknown committed
786
  DBUG_ENTER("lex_end");
787
  DBUG_PRINT("enter", ("lex: %p", lex));
unknown's avatar
unknown committed
788

789 790 791 792 793 794 795 796 797 798
  lex_end_stage1(lex);
  lex_end_stage2(lex);

  DBUG_VOID_RETURN;
}

void lex_end_stage1(LEX *lex)
{
  DBUG_ENTER("lex_end_stage1");

unknown's avatar
unknown committed
799
  /* release used plugins */
800 801 802 803 804
  if (lex->plugins.elements) /* No function call and no mutex if no plugins. */
  {
    plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer, 
                       lex->plugins.elements);
  }
unknown's avatar
unknown committed
805 806
  reset_dynamic(&lex->plugins);

807 808 809 810 811 812 813 814 815 816 817 818 819 820
  if (lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_PREPARE)
  {
    /*
      Don't delete lex->sphead, it'll be needed for EXECUTE.
      Note that of all statements that populate lex->sphead
      only SQLCOM_COMPOUND can be PREPAREd
    */
    DBUG_ASSERT(lex->sphead == 0 || lex->sql_command == SQLCOM_COMPOUND);
  }
  else
  {
    delete lex->sphead;
    lex->sphead= NULL;
  }
821

822 823 824 825 826 827 828 829 830 831 832 833 834
  DBUG_VOID_RETURN;
}

/*
  MASTER INFO parameters (or state) is normally cleared towards the end
  of a statement. But in case of PS, the state needs to be preserved during
  its lifetime and should only be cleared on PS close or deallocation.
*/
void lex_end_stage2(LEX *lex)
{
  DBUG_ENTER("lex_end_stage2");

  /* Reset LEX_MASTER_INFO */
835
  lex->mi.reset(lex->sql_command == SQLCOM_CHANGE_MASTER);
836
  delete_dynamic(&lex->delete_gtid_domain);
837

unknown's avatar
unknown committed
838
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
839 840
}

841 842 843 844
Yacc_state::~Yacc_state()
{
  if (yacc_yyss)
  {
845 846
    my_free(yacc_yyss);
    my_free(yacc_yyvs);
847
  }
unknown's avatar
unknown committed
848 849
}

850 851
int Lex_input_stream::find_keyword(Lex_ident_cli_st *kwd,
                                   uint len, bool function)
unknown's avatar
unknown committed
852
{
853
  const char *tok= m_tok_start;
unknown's avatar
unknown committed
854

855
  SYMBOL *symbol= get_hash_symbol(tok, len, function);
unknown's avatar
unknown committed
856 857
  if (symbol)
  {
858 859 860
    kwd->set_keyword(tok, len);
    DBUG_ASSERT(tok >= get_buf());
    DBUG_ASSERT(tok < get_end_of_query());
861

862 863 864 865
    if (m_thd->variables.sql_mode & MODE_ORACLE)
    {
      switch (symbol->tok) {
      case BEGIN_MARIADB_SYM:          return BEGIN_ORACLE_SYM;
866
      case BLOB_MARIADB_SYM:           return BLOB_ORACLE_SYM;
867
      case BODY_MARIADB_SYM:           return BODY_ORACLE_SYM;
868
      case CLOB_MARIADB_SYM:           return CLOB_ORACLE_SYM;
869
      case CONTINUE_MARIADB_SYM:       return CONTINUE_ORACLE_SYM;
870
      case DECLARE_MARIADB_SYM:        return DECLARE_ORACLE_SYM;
871
      case DECODE_MARIADB_SYM:         return DECODE_ORACLE_SYM;
872
      case ELSEIF_MARIADB_SYM:         return ELSEIF_ORACLE_SYM;
873 874 875 876
      case ELSIF_MARIADB_SYM:          return ELSIF_ORACLE_SYM;
      case EXCEPTION_MARIADB_SYM:      return EXCEPTION_ORACLE_SYM;
      case EXIT_MARIADB_SYM:           return EXIT_ORACLE_SYM;
      case GOTO_MARIADB_SYM:           return GOTO_ORACLE_SYM;
877
      case NUMBER_MARIADB_SYM:         return NUMBER_ORACLE_SYM;
878 879 880
      case OTHERS_MARIADB_SYM:         return OTHERS_ORACLE_SYM;
      case PACKAGE_MARIADB_SYM:        return PACKAGE_ORACLE_SYM;
      case RAISE_MARIADB_SYM:          return RAISE_ORACLE_SYM;
881
      case RAW_MARIADB_SYM:            return RAW_ORACLE_SYM;
882 883
      case RETURN_MARIADB_SYM:         return RETURN_ORACLE_SYM;
      case ROWTYPE_MARIADB_SYM:        return ROWTYPE_ORACLE_SYM;
884
      case VARCHAR2_MARIADB_SYM:       return VARCHAR2_ORACLE_SYM;
885 886 887
      }
    }

888
    if ((symbol->tok == NOT_SYM) &&
889
        (m_thd->variables.sql_mode & MODE_HIGH_NOT_PRECEDENCE))
890
      return NOT2_SYM;
891 892 893 894 895 896
    if ((symbol->tok == OR2_SYM) &&
        (m_thd->variables.sql_mode & MODE_PIPES_AS_CONCAT))
    {
      return (m_thd->variables.sql_mode & MODE_ORACLE) ?
             ORACLE_CONCAT_SYM : MYSQL_CONCAT_SYM;
    }
897

unknown's avatar
unknown committed
898 899 900 901 902
    return symbol->tok;
  }
  return 0;
}

903 904 905 906 907
/*
  Check if name is a keyword

  SYNOPSIS
    is_keyword()
908
    name      checked name (must not be empty)
909 910 911 912 913 914 915 916 917
    len       length of checked name

  RETURN VALUES
    0         name is a keyword
    1         name isn't a keyword
*/

bool is_keyword(const char *name, uint len)
{
918
  DBUG_ASSERT(len != 0);
919 920
  return get_hash_symbol(name,len,0)!=0;
}
unknown's avatar
unknown committed
921

922 923 924 925 926
/**
  Check if name is a sql function

    @param name      checked name

927
    @return is this a native function or not
928 929 930 931
    @retval 0         name is a function
    @retval 1         name isn't a function
*/

932
bool is_lex_native_function(const LEX_CSTRING *name)
933 934
{
  DBUG_ASSERT(name != NULL);
935
  return (get_hash_symbol(name->str, (uint) name->length, 1) != 0);
936 937
}

938

939
bool is_native_function(THD *thd, const LEX_CSTRING *name)
940
{
941
  if (find_native_function_builder(thd, name))
942 943 944 945 946 947 948 949 950
    return true;

  if (is_lex_native_function(name))
    return true;

  return false;
}


951
bool is_native_function_with_warn(THD *thd, const LEX_CSTRING *name)
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
{
  if (!is_native_function(thd, name))
    return false;
  /*
    This warning will be printed when
    [1] A client query is parsed,
    [2] A stored function is loaded by db_load_routine.
    Printing the warning for [2] is intentional, to cover the
    following scenario:
    - A user define a SF 'foo' using MySQL 5.N
    - An application uses select foo(), and works.
    - MySQL 5.{N+1} defines a new native function 'foo', as
    part of a new feature.
    - MySQL 5.{N+1} documentation is updated, and should mention
    that there is a potential incompatible change in case of
    existing stored function named 'foo'.
    - The user deploys 5.{N+1}. At this point, 'select foo()'
    means something different, and the user code is most likely
    broken (it's only safe if the code is 'select db.foo()').
    With a warning printed when the SF is loaded (which has to
    occur before the call), the warning will provide a hint
    explaining the root cause of a later failure of 'select foo()'.
    With no warning printed, the user code will fail with no
    apparent reason.
    Printing a warning each time db_load_routine is executed for
    an ambiguous function is annoying, since that can happen a lot,
    but in practice should not happen unless there *are* name
    collisions.
    If a collision exists, it should not be silenced but fixed.
  */
  push_warning_printf(thd,
                      Sql_condition::WARN_LEVEL_NOTE,
                      ER_NATIVE_FCT_NAME_COLLISION,
                      ER_THD(thd, ER_NATIVE_FCT_NAME_COLLISION),
                      name->str);
  return true;
}


unknown's avatar
unknown committed
991 992
/* make a copy of token before ptr and set yytoklen */

993
LEX_CSTRING Lex_input_stream::get_token(uint skip, uint length)
unknown's avatar
unknown committed
994
{
995
  LEX_CSTRING tmp;
996
  yyUnget();                       // ptr points now after last token char
997
  tmp.length= length;
998
  tmp.str= m_thd->strmake(m_tok_start + skip, tmp.length);
unknown's avatar
unknown committed
999

1000
  m_cpp_text_start= m_cpp_tok_start + skip;
1001
  m_cpp_text_end= m_cpp_text_start + tmp.length;
unknown's avatar
unknown committed
1002

unknown's avatar
unknown committed
1003 1004 1005
  return tmp;
}

1006

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
static size_t
my_unescape(CHARSET_INFO *cs, char *to, const char *str, const char *end,
            int sep, bool backslash_escapes)
{
  char *start= to;
  for ( ; str != end ; str++)
  {
#ifdef USE_MB
    int l;
    if (use_mb(cs) && (l= my_ismbchar(cs, str, end)))
    {
      while (l--)
        *to++ = *str++;
      str--;
      continue;
    }
#endif
    if (backslash_escapes && *str == '\\' && str + 1 != end)
    {
      switch(*++str) {
      case 'n':
        *to++='\n';
        break;
      case 't':
        *to++= '\t';
        break;
      case 'r':
        *to++ = '\r';
        break;
      case 'b':
        *to++ = '\b';
        break;
      case '0':
        *to++= 0;                      // Ascii null
        break;
      case 'Z':                        // ^Z must be escaped on Win32
        *to++='\032';
        break;
      case '_':
      case '%':
        *to++= '\\';                   // remember prefix for wildcard
        /* Fall through */
      default:
        *to++= *str;
        break;
      }
    }
    else if (*str == sep)
      *to++= *str++;                // Two ' or "
    else
      *to++ = *str;
  }
  *to= 0;
  return to - start;
}


size_t
Lex_input_stream::unescape(CHARSET_INFO *cs, char *to,
                           const char *str, const char *end,
                           int sep)
{
  return my_unescape(cs, to, str, end, sep, m_thd->backslash_escapes());
}


1073 1074 1075 1076
/*
  Return an unescaped text literal without quotes
  Fix sometimes to do only one scan of the string
*/
unknown's avatar
unknown committed
1077

1078
bool Lex_input_stream::get_text(Lex_string_with_metadata_st *dst, uint sep,
1079
                                int pre_skip, int post_skip)
unknown's avatar
unknown committed
1080
{
1081
  uchar c;
unknown's avatar
unknown committed
1082
  uint found_escape=0;
1083
  CHARSET_INFO *cs= m_thd->charset();
1084
  bool is_8bit= false;
unknown's avatar
unknown committed
1085

1086
  while (! eof())
unknown's avatar
unknown committed
1087
  {
1088
    c= yyGet();
1089
    if (c & 0x80)
1090
      is_8bit= true;
unknown's avatar
unknown committed
1091
#ifdef USE_MB
1092 1093 1094
    {
      int l;
      if (use_mb(cs) &&
1095
          (l = my_ismbchar(cs,
1096 1097 1098
                           get_ptr() -1,
                           get_end_of_query()))) {
        skip_binary(l-1);
1099
        continue;
1100
      }
unknown's avatar
unknown committed
1101 1102
    }
#endif
1103
    if (c == '\\' &&
1104
        !(m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))
1105
    {                                        // Escaped character
unknown's avatar
unknown committed
1106
      found_escape=1;
1107
      if (eof())
1108
        return true;
1109
      yySkip();
unknown's avatar
unknown committed
1110 1111 1112
    }
    else if (c == sep)
    {
1113
      if (c == yyGet())                 // Check if two separators in a row
unknown's avatar
unknown committed
1114
      {
1115
        found_escape=1;                 // duplicate. Remember for delete
1116
        continue;
unknown's avatar
unknown committed
1117 1118
      }
      else
1119
        yyUnget();
unknown's avatar
unknown committed
1120 1121

      /* Found end. Unescape and return string */
1122
      const char *str, *end;
1123
      char *to;
unknown's avatar
unknown committed
1124

1125
      str= m_tok_start;
1126
      end= get_ptr();
1127 1128 1129 1130 1131
      /* Extract the text from the token */
      str += pre_skip;
      end -= post_skip;
      DBUG_ASSERT(end >= str);

1132
      if (!(to= (char*) m_thd->alloc((uint) (end - str) + 1)))
1133
      {
1134 1135
        dst->set(&empty_clex_str, 0, '\0');
        return true;                   // Sql_alloc has set error flag
1136
      }
unknown's avatar
unknown committed
1137

1138
      m_cpp_text_start= m_cpp_tok_start + pre_skip;
1139
      m_cpp_text_end= get_cpp_ptr() - post_skip;
unknown's avatar
unknown committed
1140

unknown's avatar
unknown committed
1141 1142
      if (!found_escape)
      {
1143 1144 1145 1146
        size_t len= (end - str);
        memcpy(to, str, len);
        to[len]= '\0';
        dst->set(to, len, is_8bit, '\0');
unknown's avatar
unknown committed
1147 1148 1149
      }
      else
      {
1150 1151
        size_t len= unescape(cs, to, str, end, sep);
        dst->set(to, len, is_8bit, '\0');
unknown's avatar
unknown committed
1152
      }
1153
      return false;
unknown's avatar
unknown committed
1154 1155
    }
  }
1156
  return true;                         // unexpected end of query
unknown's avatar
unknown committed
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
}


/*
** Calc type of integer; long integer, longlong integer or real.
** Returns smallest type that match the string.
** When using unsigned long long values the result is converted to a real
** because else they will be unexpected sign changes because all calculation
** is done with longlong or double.
*/

static const char *long_str="2147483647";
static const uint long_len=10;
static const char *signed_long_str="-2147483648";
static const char *longlong_str="9223372036854775807";
static const uint longlong_len=19;
static const char *signed_longlong_str="-9223372036854775808";
static const uint signed_longlong_len=19;
unknown's avatar
unknown committed
1175 1176
static const char *unsigned_longlong_str="18446744073709551615";
static const uint unsigned_longlong_len=20;
unknown's avatar
unknown committed
1177

unknown's avatar
unknown committed
1178
static inline uint int_token(const char *str,uint length)
unknown's avatar
unknown committed
1179
{
1180
  if (length < long_len)                        // quick normal case
unknown's avatar
unknown committed
1181 1182 1183
    return NUM;
  bool neg=0;

1184
  if (*str == '+')                              // Remove sign and pre-zeros
unknown's avatar
unknown committed
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
  {
    str++; length--;
  }
  else if (*str == '-')
  {
    str++; length--;
    neg=1;
  }
  while (*str == '0' && length)
  {
    str++; length --;
  }
  if (length < long_len)
    return NUM;

  uint smaller,bigger;
  const char *cmp;
  if (neg)
  {
    if (length == long_len)
    {
1206 1207 1208
      cmp= signed_long_str + 1;
      smaller= NUM;                                   // If <= signed_long_str
      bigger= LONG_NUM;                               // If >= signed_long_str
unknown's avatar
unknown committed
1209 1210 1211 1212
    }
    else if (length < signed_longlong_len)
      return LONG_NUM;
    else if (length > signed_longlong_len)
unknown's avatar
unknown committed
1213
      return DECIMAL_NUM;
unknown's avatar
unknown committed
1214 1215
    else
    {
1216 1217
      cmp= signed_longlong_str + 1;
      smaller= LONG_NUM;                              // If <= signed_longlong_str
unknown's avatar
unknown committed
1218
      bigger=DECIMAL_NUM;
unknown's avatar
unknown committed
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    }
  }
  else
  {
    if (length == long_len)
    {
      cmp= long_str;
      smaller=NUM;
      bigger=LONG_NUM;
    }
    else if (length < longlong_len)
      return LONG_NUM;
    else if (length > longlong_len)
unknown's avatar
unknown committed
1232 1233
    {
      if (length > unsigned_longlong_len)
unknown's avatar
unknown committed
1234
        return DECIMAL_NUM;
unknown's avatar
unknown committed
1235 1236
      cmp=unsigned_longlong_str;
      smaller=ULONGLONG_NUM;
unknown's avatar
unknown committed
1237
      bigger=DECIMAL_NUM;
unknown's avatar
unknown committed
1238
    }
unknown's avatar
unknown committed
1239 1240 1241 1242
    else
    {
      cmp=longlong_str;
      smaller=LONG_NUM;
1243
      bigger= ULONGLONG_NUM;
unknown's avatar
unknown committed
1244 1245 1246 1247 1248 1249
    }
  }
  while (*cmp && *cmp++ == *str++) ;
  return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
}

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262

/**
  Given a stream that is advanced to the first contained character in 
  an open comment, consume the comment.  Optionally, if we are allowed, 
  recurse so that we understand comments within this current comment.

  At this level, we do not support version-condition comments.  We might 
  have been called with having just passed one in the stream, though.  In 
  that case, we probably want to tolerate mundane comments inside.  Thus,
  the case for recursion.

  @retval  Whether EOF reached before comment is closed.
*/
1263
bool Lex_input_stream::consume_comment(int remaining_recursions_permitted)
1264
{
1265
  uchar c;
1266
  while (!eof())
1267
  {
1268
    c= yyGet();
1269 1270 1271

    if (remaining_recursions_permitted > 0)
    {
1272
      if ((c == '/') && (yyPeek() == '*'))
1273
      {
1274 1275
        yySkip(); // Eat asterisk
        consume_comment(remaining_recursions_permitted - 1);
1276 1277 1278 1279 1280 1281
        continue;
      }
    }

    if (c == '*')
    {
1282
      if (yyPeek() == '/')
1283
      {
1284
        yySkip(); // Eat slash
1285 1286 1287 1288 1289
        return FALSE;
      }
    }

    if (c == '\n')
1290
      yylineno++;
1291 1292 1293 1294 1295 1296
  }

  return TRUE;
}


1297
/*
1298
  MYSQLlex remember the following states from the following MYSQLlex()
1299

1300 1301 1302
  @param yylval         [out]  semantic value of the token being parsed (yylval)
  @param thd            THD

1303 1304 1305
  - MY_LEX_EOQ                  Found end of query
  - MY_LEX_OPERATOR_OR_IDENT    Last state was an ident, text or number
                                (which can't be followed by a signed number)
1306
*/
unknown's avatar
unknown committed
1307

1308
int MYSQLlex(YYSTYPE *yylval, THD *thd)
1309
{
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
  return thd->m_parser_state->m_lip.lex_token(yylval, thd);
}


int ORAlex(YYSTYPE *yylval, THD *thd)
{
  return thd->m_parser_state->m_lip.lex_token(yylval, thd);
}


int Lex_input_stream::lex_token(YYSTYPE *yylval, THD *thd)
{
1322
  int token;
1323 1324
  const int left_paren= (int) '(';

1325
  if (lookahead_token >= 0)
1326 1327 1328 1329 1330
  {
    /*
      The next token was already parsed in advance,
      return it.
    */
1331 1332 1333 1334
    token= lookahead_token;
    lookahead_token= -1;
    *yylval= *(lookahead_yylval);
    lookahead_yylval= NULL;
1335 1336 1337
    return token;
  }

1338
  token= lex_one_token(yylval, thd);
1339
  add_digest_token(token, yylval);
1340

1341 1342
  SELECT_LEX *curr_sel= thd->lex->current_select;

1343 1344 1345 1346 1347 1348 1349 1350 1351
  switch(token) {
  case WITH:
    /*
      Parsing 'WITH' 'ROLLUP' or 'WITH' 'CUBE' requires 2 look ups,
      which makes the grammar LALR(2).
      Replace by a single 'WITH_ROLLUP' or 'WITH_CUBE' token,
      to transform the grammar into a LALR(1) grammar,
      which sql_yacc.yy can process.
    */
1352
    token= lex_one_token(yylval, thd);
1353
    add_digest_token(token, yylval);
1354 1355 1356 1357 1358
    switch(token) {
    case CUBE_SYM:
      return WITH_CUBE_SYM;
    case ROLLUP_SYM:
      return WITH_ROLLUP_SYM;
1359 1360
    case SYSTEM:
      return WITH_SYSTEM_SYM;
1361 1362 1363 1364
    default:
      /*
        Save the token following 'WITH'
      */
1365 1366
      lookahead_yylval= yylval;
      lookahead_token= token;
1367 1368 1369
      return WITH;
    }
    break;
1370 1371 1372 1373 1374 1375 1376
  case FOR_SYM:
    /*
     * Additional look-ahead to resolve doubtful cases like:
     * SELECT ... FOR UPDATE
     * SELECT ... FOR SYSTEM_TIME ... .
     */
    token= lex_one_token(yylval, thd);
1377
    add_digest_token(token, yylval);
1378 1379 1380 1381 1382 1383 1384
    switch(token) {
    case SYSTEM_TIME_SYM:
      return FOR_SYSTEM_TIME_SYM;
    default:
      /*
        Save the token following 'FOR_SYM'
      */
1385 1386
      lookahead_yylval= yylval;
      lookahead_token= token;
1387 1388 1389
      return FOR_SYM;
    }
    break;
Galina Shalygina's avatar
Galina Shalygina committed
1390
  case VALUES:
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
    if (curr_sel &&
        (curr_sel->parsing_place == BEFORE_OPT_LIST ||
         curr_sel->parsing_place == AFTER_LIST))
    {
      curr_sel->parsing_place= NO_MATTER;
      break;
    }
    if (curr_sel &&
        (curr_sel->parsing_place == IN_UPDATE_ON_DUP_KEY ||
         curr_sel->parsing_place == IN_PART_FUNC))
Galina Shalygina's avatar
Galina Shalygina committed
1401 1402
      return VALUE_SYM;
    token= lex_one_token(yylval, thd);
1403
    add_digest_token(token, yylval);
Galina Shalygina's avatar
Galina Shalygina committed
1404 1405 1406 1407 1408 1409
    switch(token) {
    case LESS_SYM:
      return VALUES_LESS_SYM;
    case IN_SYM:
      return VALUES_IN_SYM;
    default:
1410 1411
      lookahead_yylval= yylval;
      lookahead_token= token;
Galina Shalygina's avatar
Galina Shalygina committed
1412 1413
      return VALUES;
    }
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
  case VALUE_SYM:
    if (curr_sel &&
        (curr_sel->parsing_place == BEFORE_OPT_LIST ||
         curr_sel->parsing_place == AFTER_LIST))
    {
      curr_sel->parsing_place= NO_MATTER;
      return VALUES;
    }
    break;
  case PARTITION_SYM:
  case SELECT_SYM:
  case UNION_SYM:
    if (curr_sel &&
        (curr_sel->parsing_place == BEFORE_OPT_LIST ||
         curr_sel->parsing_place == AFTER_LIST))
    {
      curr_sel->parsing_place= NO_MATTER;
    }
    break;
  case left_paren:
    if (!curr_sel ||
        curr_sel->parsing_place != BEFORE_OPT_LIST)
      return token;
    token= lex_one_token(yylval, thd);
    add_digest_token(token, yylval);
    lookahead_yylval= yylval;
    yylval= NULL;
    lookahead_token= token;
    curr_sel->parsing_place= NO_MATTER;
    if (token == LIKE)
      return LEFT_PAREN_LIKE;
    if (token == WITH)
      return LEFT_PAREN_WITH;
    if (token != left_paren && token != SELECT_SYM)
      return LEFT_PAREN_ALT;
    else
      return left_paren;
Galina Shalygina's avatar
Galina Shalygina committed
1451
    break;
1452 1453 1454 1455 1456 1457
  default:
    break;
  }
  return token;
}

1458

1459
int Lex_input_stream::lex_one_token(YYSTYPE *yylval, THD *thd)
unknown's avatar
unknown committed
1460
{
1461
  uchar UNINIT_VAR(c);
1462
  bool comment_closed;
1463
  int tokval;
unknown's avatar
unknown committed
1464
  uint length;
unknown's avatar
unknown committed
1465
  enum my_lex_states state;
1466
  LEX *lex= thd->lex;
1467 1468 1469
  CHARSET_INFO *const cs= thd->charset();
  const uchar *const state_map= cs->state_map;
  const uchar *const ident_map= cs->ident_map;
unknown's avatar
unknown committed
1470

1471 1472 1473
  start_token();
  state= next_state;
  next_state= MY_LEX_OPERATOR_OR_IDENT;
unknown's avatar
unknown committed
1474 1475
  for (;;)
  {
1476
    switch (state) {
1477 1478
    case MY_LEX_OPERATOR_OR_IDENT:        // Next is operator or keyword
    case MY_LEX_START:                    // Start of token
1479
      // Skip starting whitespace
1480
      while(state_map[c= yyPeek()] == MY_LEX_SKIP)
unknown's avatar
unknown committed
1481
      {
1482
        if (c == '\n')
1483
          yylineno++;
1484

1485
        yySkip();
unknown's avatar
unknown committed
1486
      }
1487 1488

      /* Start of real token */
1489 1490
      restart_token();
      c= yyGet();
1491
      state= (enum my_lex_states) state_map[c];
unknown's avatar
unknown committed
1492
      break;
1493
    case MY_LEX_ESCAPE:
1494
      if (!eof() && yyGet() == 'N')
1495 1496 1497 1498
      {                                        // Allow \N as shortcut for NULL
        yylval->lex_str.str= (char*) "\\N";
        yylval->lex_str.length= 2;
        return NULL_SYM;
unknown's avatar
unknown committed
1499
      }
1500
      /* Fall through */
1501
    case MY_LEX_CHAR:                          // Unknown or single char token
1502 1503 1504 1505 1506
      if (c == '%' && (m_thd->variables.sql_mode & MODE_ORACLE))
      {
        next_state= MY_LEX_START;
        return PERCENT_ORACLE_SYM;
      }
1507 1508
      if (c == '[' && (m_thd->variables.sql_mode & MODE_MSSQL))
        return scan_ident_delimited(thd, &yylval->ident_cli, ']');
1509
      /* Fall through */
1510
    case MY_LEX_SKIP:                          // This should not happen
1511
      if (c != ')')
1512
        next_state= MY_LEX_START;         // Allow signed numbers
1513 1514 1515
      return((int) c);

    case MY_LEX_MINUS_OR_COMMENT:
1516 1517 1518
      if (yyPeek() == '-' &&
          (my_isspace(cs,yyPeekn(1)) ||
           my_iscntrl(cs,yyPeekn(1))))
1519 1520 1521 1522
      {
        state=MY_LEX_COMMENT;
        break;
      }
1523
      next_state= MY_LEX_START;        // Allow signed numbers
1524
      return((int) c);
1525

1526 1527 1528 1529 1530 1531 1532
    case MY_LEX_PLACEHOLDER:
      /*
        Check for a placeholder: it should not precede a possible identifier
        because of binlogging: when a placeholder is replaced with
        its value in a query for the binlog, the query must stay
        grammatically correct.
      */
1533 1534
      next_state= MY_LEX_START;        // Allow signed numbers
      if (stmt_prepare_mode && !ident_map[(uchar) yyPeek()])
1535
        return(PARAM_MARKER);
1536
      return((int) c);
1537

1538
    case MY_LEX_COMMA:
1539
      next_state= MY_LEX_START;        // Allow signed numbers
1540 1541 1542 1543 1544 1545 1546 1547 1548
      /*
        Warning:
        This is a work around, to make the "remember_name" rule in
        sql/sql_yacc.yy work properly.
        The problem is that, when parsing "select expr1, expr2",
        the code generated by bison executes the *pre* action
        remember_name (see select_item) *before* actually parsing the
        first token of expr2.
      */
1549
      restart_token();
unknown's avatar
unknown committed
1550 1551
      return((int) c);

unknown's avatar
unknown committed
1552
    case MY_LEX_IDENT_OR_NCHAR:
1553 1554
    {
      uint sep;
1555
      if (yyPeek() != '\'')
1556
      {
1557 1558
        state= MY_LEX_IDENT;
        break;
unknown's avatar
unknown committed
1559
      }
1560
      /* Found N'string' */
1561 1562
      yySkip();                         // Skip '
      if (get_text(&yylval->lex_string_with_metadata, (sep= yyGetLast()), 2, 1))
unknown's avatar
unknown committed
1563
      {
1564 1565
        state= MY_LEX_CHAR;                    // Read char by char
        break;
unknown's avatar
unknown committed
1566
      }
1567

1568 1569
      body_utf8_append(m_cpp_text_start);
      body_utf8_append_escape(thd, &yylval->lex_string_with_metadata,
1570
                                   national_charset_info,
1571
                                   m_cpp_text_end, sep);
1572
      return(NCHAR_STRING);
1573
    }
1574
    case MY_LEX_IDENT_OR_HEX:
1575
      if (yyPeek() == '\'')
1576 1577 1578
      {                                      // Found x'hex-number'
        state= MY_LEX_HEX_NUMBER;
        break;
1579
      }
1580
      /* fall through */
unknown's avatar
unknown committed
1581
    case MY_LEX_IDENT_OR_BIN:
1582
      if (yyPeek() == '\'')
unknown's avatar
unknown committed
1583 1584 1585 1586
      {                                 // Found b'bin-number'
        state= MY_LEX_BIN_NUMBER;
        break;
      }
1587
      /* fall through */
1588
    case MY_LEX_IDENT:
1589
    {
1590 1591
      tokval= scan_ident_middle(thd, &yylval->ident_cli,
                                &yylval->charset, &state);
1592 1593 1594
      if (!tokval)
        continue;
      if (tokval == UNDERSCORE_CHARSET)
1595
        m_underscore_cs= yylval->charset;
1596 1597
      return tokval;
    }
unknown's avatar
unknown committed
1598

1599
    case MY_LEX_IDENT_SEP:                  // Found ident and now '.'
1600
      yylval->lex_str.str= (char*) get_ptr();
1601
      yylval->lex_str.length= 1;
1602 1603 1604 1605
      c= yyGet();                          // should be '.'
      next_state= MY_LEX_IDENT_START;      // Next is ident (not keyword)
      if (!ident_map[(uchar) yyPeek()])    // Probably ` or "
        next_state= MY_LEX_START;
unknown's avatar
unknown committed
1606 1607
      return((int) c);

1608
    case MY_LEX_NUMBER_IDENT:                   // number or ident which num-start
1609
      if (yyGetLast() == '0')
1610
      {
1611
        c= yyGet();
1612 1613
        if (c == 'x')
        {
1614 1615
          while (my_isxdigit(cs, (c = yyGet()))) ;
          if ((yyLength() >= 3) && !ident_map[c])
1616 1617
          {
            /* skip '0x' */
1618
            yylval->lex_str= get_token(2, yyLength() - 2);
1619 1620
            return (HEX_NUM);
          }
1621
          yyUnget();
1622 1623 1624 1625 1626
          state= MY_LEX_IDENT_START;
          break;
        }
        else if (c == 'b')
        {
1627
          while ((c= yyGet()) == '0' || c == '1')
1628
            ;
1629
          if ((yyLength() >= 3) && !ident_map[c])
1630 1631
          {
            /* Skip '0b' */
1632
            yylval->lex_str= get_token(2, yyLength() - 2);
1633 1634
            return (BIN_NUM);
          }
1635
          yyUnget();
1636 1637 1638
          state= MY_LEX_IDENT_START;
          break;
        }
1639
        yyUnget();
1640 1641
      }

1642
      while (my_isdigit(cs, (c= yyGet()))) ;
unknown's avatar
unknown committed
1643
      if (!ident_map[c])
1644 1645 1646
      {                                        // Can't be identifier
        state=MY_LEX_INT_OR_REAL;
        break;
unknown's avatar
unknown committed
1647 1648 1649
      }
      if (c == 'e' || c == 'E')
      {
1650
        // The following test is written this way to allow numbers of type 1e1
1651 1652
        if (my_isdigit(cs, yyPeek()) ||
            (c=(yyGet())) == '+' || c == '-')
1653
        {                                       // Allow 1E+10
1654
          if (my_isdigit(cs, yyPeek()))         // Number must have digit after sign
1655
          {
1656 1657 1658
            yySkip();
            while (my_isdigit(cs, yyGet())) ;
            yylval->lex_str= get_token(0, yyLength());
1659 1660
            return(FLOAT_NUM);
          }
1661
        }
1662 1663 1664 1665 1666 1667 1668 1669
        /*
          We've found:
          - A sequence of digits
          - Followed by 'e' or 'E'
          - Followed by some byte XX which is not a known mantissa start,
            and it's known to be a valid identifier part.
            XX can be either a 8bit identifier character, or a multi-byte head.
        */
1670
        yyUnget();
1671
        return scan_ident_start(thd, &yylval->ident_cli);
unknown's avatar
unknown committed
1672
      }
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
      /*
        We've found:
        - A sequence of digits
        - Followed by some character XX, which is neither 'e' nor 'E',
          and it's known to be a valid identifier part.
          XX can be a 8bit identifier character, or a multi-byte head.
      */
      yyUnget();
      return scan_ident_start(thd, &yylval->ident_cli);

1683
    case MY_LEX_IDENT_START:                    // We come here after '.'
1684
      return scan_ident_start(thd, &yylval->ident_cli);
unknown's avatar
unknown committed
1685

1686
    case MY_LEX_USER_VARIABLE_DELIMITER:        // Found quote char
1687
      return scan_ident_delimited(thd, &yylval->ident_cli, m_tok_start[0]);
unknown's avatar
unknown committed
1688

1689
    case MY_LEX_INT_OR_REAL:                    // Complete int or incomplete real
1690
      if (c != '.' || yyPeek() == '.')
1691 1692 1693 1694 1695 1696
      {
        /*
          Found a complete integer number:
          - the number is either not followed by a dot at all, or
          - the number is followed by a double dot as in: FOR i IN 1..10
        */
1697
        yylval->lex_str= get_token(0, yyLength());
1698
        return int_token(yylval->lex_str.str, (uint) yylval->lex_str.length);
unknown's avatar
unknown committed
1699 1700
      }
      // fall through
1701
    case MY_LEX_REAL:                           // Incomplete real number
1702
      while (my_isdigit(cs, c= yyGet())) ;
unknown's avatar
unknown committed
1703 1704 1705

      if (c == 'e' || c == 'E')
      {
1706
        c= yyGet();
1707
        if (c == '-' || c == '+')
1708
          c= yyGet();                           // Skip sign
1709 1710 1711 1712 1713
        if (!my_isdigit(cs, c))
        {                                       // No digit after sign
          state= MY_LEX_CHAR;
          break;
        }
1714 1715
        while (my_isdigit(cs, yyGet())) ;
        yylval->lex_str= get_token(0, yyLength());
1716
        return(FLOAT_NUM);
unknown's avatar
unknown committed
1717
      }
1718
      yylval->lex_str= get_token(0, yyLength());
unknown's avatar
unknown committed
1719
      return(DECIMAL_NUM);
unknown's avatar
unknown committed
1720

1721
    case MY_LEX_HEX_NUMBER:             // Found x'hexstring'
1722 1723
      yySkip();                    // Accept opening '
      while (my_isxdigit(cs, (c= yyGet()))) ;
1724 1725
      if (c != '\'')
        return(ABORT_SYM);              // Illegal hex constant
1726 1727
      yySkip();                    // Accept closing '
      length= yyLength();          // Length of hexnum+3
1728 1729
      if ((length % 2) == 0)
        return(ABORT_SYM);              // odd number of hex digits
1730 1731
      yylval->lex_str= get_token(2,            // skip x'
                                 length - 3);  // don't count x' and last '
Alexander Barkov's avatar
Alexander Barkov committed
1732
      return HEX_STRING;
1733

unknown's avatar
unknown committed
1734
    case MY_LEX_BIN_NUMBER:           // Found b'bin-string'
1735 1736
      yySkip();                  // Accept opening '
      while ((c= yyGet()) == '0' || c == '1')
1737
        ;
unknown's avatar
unknown committed
1738
      if (c != '\'')
1739
        return(ABORT_SYM);            // Illegal hex constant
1740 1741 1742 1743
      yySkip();                  // Accept closing '
      length= yyLength();        // Length of bin-num + 3
      yylval->lex_str= get_token(2,           // skip b'
                                 length - 3); // don't count b' and last '
1744
      return (BIN_NUM);
unknown's avatar
unknown committed
1745

1746
    case MY_LEX_CMP_OP:                     // Incomplete comparison operator
1747 1748 1749
      next_state= MY_LEX_START;        // Allow signed numbers
      if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP ||
          state_map[(uchar) yyPeek()] == MY_LEX_LONG_CMP_OP)
unknown's avatar
unknown committed
1750
      {
1751 1752
        yySkip();
        if ((tokval= find_keyword(&yylval->kwd, 2, 0)))
1753
          return(tokval);
1754
        yyUnget();
unknown's avatar
unknown committed
1755
      }
1756
      return(c);
unknown's avatar
unknown committed
1757

1758
    case MY_LEX_LONG_CMP_OP:                // Incomplete comparison operator
1759 1760 1761
      next_state= MY_LEX_START;
      if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP ||
          state_map[(uchar) yyPeek()] == MY_LEX_LONG_CMP_OP)
unknown's avatar
unknown committed
1762
      {
1763 1764
        yySkip();
        if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP)
1765
        {
1766 1767
          yySkip();
          if ((tokval= find_keyword(&yylval->kwd, 3, 0)))
1768
            return(tokval);
1769
          yyUnget();
1770
        }
1771
        if ((tokval= find_keyword(&yylval->kwd, 2, 0)))
1772
          return(tokval);
1773
        yyUnget();
unknown's avatar
unknown committed
1774
      }
1775
      return(c);
unknown's avatar
unknown committed
1776

1777
    case MY_LEX_BOOL:
1778
      if (c != yyPeek())
unknown's avatar
unknown committed
1779
      {
1780 1781
        state= MY_LEX_CHAR;
        break;
unknown's avatar
unknown committed
1782
      }
1783 1784 1785
      yySkip();
      tokval= find_keyword(&yylval->kwd, 2, 0);  // Is a bool operator
      next_state= MY_LEX_START;                  // Allow signed numbers
unknown's avatar
unknown committed
1786 1787
      return(tokval);

1788
    case MY_LEX_STRING_OR_DELIMITER:
1789
      if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
1790
      {
1791 1792
        state= MY_LEX_USER_VARIABLE_DELIMITER;
        break;
1793 1794
      }
      /* " used for strings */
1795
      /* fall through */
1796
    case MY_LEX_STRING:                        // Incomplete text string
1797 1798
    {
      uint sep;
1799
      if (get_text(&yylval->lex_string_with_metadata, (sep= yyGetLast()), 1, 1))
unknown's avatar
unknown committed
1800
      {
1801 1802
        state= MY_LEX_CHAR;                     // Read char by char
        break;
unknown's avatar
unknown committed
1803
      }
1804 1805
      CHARSET_INFO *strcs= m_underscore_cs ? m_underscore_cs : cs;
      body_utf8_append(m_cpp_text_start);
unknown's avatar
unknown committed
1806

1807 1808 1809
      body_utf8_append_escape(thd, &yylval->lex_string_with_metadata,
                                   strcs, m_cpp_text_end, sep);
      m_underscore_cs= NULL;
unknown's avatar
unknown committed
1810
      return(TEXT_STRING);
1811
    }
1812
    case MY_LEX_COMMENT:                       //  Comment
1813
      lex->lex_options|= OPTION_LEX_FOUND_COMMENT;
1814 1815
      while ((c= yyGet()) != '\n' && c) ;
      yyUnget();                          // Safety against eof
1816
      state= MY_LEX_START;                     // Try again
unknown's avatar
unknown committed
1817
      break;
1818
    case MY_LEX_LONG_COMMENT:                  // Long C comment?
1819
      if (yyPeek() != '*')
unknown's avatar
unknown committed
1820
      {
1821 1822
        state= MY_LEX_CHAR;                     // Probable division
        break;
unknown's avatar
unknown committed
1823
      }
1824
      lex->lex_options|= OPTION_LEX_FOUND_COMMENT;
1825
      /* Reject '/' '*', since we might need to turn off the echo */
1826
      yyUnget();
1827

1828
      save_in_comment_state();
1829

1830 1831
      if (yyPeekn(2) == '!' ||
          (yyPeekn(2) == 'M' && yyPeekn(3) == '!'))
unknown's avatar
unknown committed
1832
      {
1833 1834
        bool maria_comment_syntax= yyPeekn(2) == 'M';
        in_comment= DISCARD_COMMENT;
1835
        /* Accept '/' '*' '!', but do not keep this marker. */
1836 1837
        set_echo(FALSE);
        yySkipn(maria_comment_syntax ? 4 : 3);
1838 1839 1840

        /*
          The special comment format is very strict:
1841
          '/' '*' '!', followed by an optional 'M' and exactly
Michael Widenius's avatar
Michael Widenius committed
1842 1843 1844 1845 1846
          1-2 digits (major), 2 digits (minor), then 2 digits (dot).
          32302  -> 3.23.02
          50032  -> 5.0.32
          50114  -> 5.1.14
          100000 -> 10.0.0
1847
        */
1848 1849 1850 1851 1852
        if (  my_isdigit(cs, yyPeekn(0))
           && my_isdigit(cs, yyPeekn(1))
           && my_isdigit(cs, yyPeekn(2))
           && my_isdigit(cs, yyPeekn(3))
           && my_isdigit(cs, yyPeekn(4))
1853 1854 1855
           )
        {
          ulong version;
1856
          uint length= 5;
1857
          char *end_ptr= (char*) get_ptr() + length;
1858
          int error;
1859
          if (my_isdigit(cs, yyPeekn(5)))
1860 1861 1862 1863 1864
          {
            end_ptr++;                          // 6 digit number
            length++;
          }

1865
          version= (ulong) my_strtoll10(get_ptr(), &end_ptr, &error);
1866

1867 1868 1869
          /*
            MySQL-5.7 has new features and might have new SQL syntax that
            MariaDB-10.0 does not understand. Ignore all versioned comments
1870
            with MySQL versions in the range 50700-999999, but
1871 1872 1873
            do not ignore MariaDB specific comments for the same versions.
          */ 
          if (version <= MYSQL_VERSION_ID &&
1874
              (version < 50700 || version > 99999 || maria_comment_syntax))
1875
          {
1876
            /* Accept 'M' 'm' 'm' 'd' 'd' */
1877
            yySkipn(length);
1878
            /* Expand the content of the special comment as real code */
1879
            set_echo(TRUE);
1880
            state=MY_LEX_START;
1881 1882 1883 1884
            break;  /* Do not treat contents as a comment.  */
          }
          else
          {
1885
#ifdef WITH_WSREP
Brave Galera Crew's avatar
Brave Galera Crew committed
1886
            if (WSREP(thd) && version == 99997 && wsrep_thd_is_local(thd))
1887 1888 1889
            {
              WSREP_DEBUG("consistency check: %s", thd->query());
              thd->wsrep_consistency_check= CONSISTENCY_CHECK_DECLARED;
1890 1891
              yySkipn(5);
              set_echo(TRUE);
1892 1893 1894
              state= MY_LEX_START;
              break;  /* Do not treat contents as a comment.  */
            }
1895
#endif /* WITH_WSREP */
1896 1897 1898 1899
            /*
              Patch and skip the conditional comment to avoid it
              being propagated infinitely (eg. to a slave).
            */
1900 1901
            char *pcom= yyUnput(' ');
            comment_closed= ! consume_comment(1);
1902 1903 1904 1905
            if (! comment_closed)
            {
              *pcom= '!';
            }
1906
            /* version allowed to have one level of comment inside. */
1907 1908 1909 1910
          }
        }
        else
        {
1911
          /* Not a version comment. */
1912
          state=MY_LEX_START;
1913
          set_echo(TRUE);
1914 1915
          break;
        }
unknown's avatar
unknown committed
1916
      }
1917
      else
unknown's avatar
unknown committed
1918
      {
1919 1920 1921 1922
        in_comment= PRESERVE_COMMENT;
        yySkip();                  // Accept /
        yySkip();                  // Accept *
        comment_closed= ! consume_comment(0);
1923
        /* regular comments can have zero comments inside. */
unknown's avatar
unknown committed
1924
      }
1925 1926 1927 1928 1929
      /*
        Discard:
        - regular '/' '*' comments,
        - special comments '/' '*' '!' for a future version,
        by scanning until we find a closing '*' '/' marker.
1930 1931 1932 1933 1934 1935

        Nesting regular comments isn't allowed.  The first 
        '*' '/' returns the parser to the previous state.

        /#!VERSI oned containing /# regular #/ is allowed #/

1936 1937 1938
                Inside one versioned comment, another versioned comment
                is treated as a regular discardable comment.  It gets
                no special parsing.
1939
      */
1940

1941 1942 1943
      /* Unbalanced comments with a missing '*' '/' are a syntax error */
      if (! comment_closed)
        return (ABORT_SYM);
1944
      state = MY_LEX_START;             // Try again
1945
      restore_in_comment_state();
unknown's avatar
unknown committed
1946
      break;
1947
    case MY_LEX_END_LONG_COMMENT:
1948
      if ((in_comment != NO_COMMENT) && yyPeek() == '/')
unknown's avatar
unknown committed
1949
      {
1950
        /* Reject '*' '/' */
1951
        yyUnget();
1952
        /* Accept '*' '/', with the proper echo */
1953 1954
        set_echo(in_comment == PRESERVE_COMMENT);
        yySkipn(2);
1955
        /* And start recording the tokens again */
1956 1957
        set_echo(TRUE);
        in_comment= NO_COMMENT;
1958
        state=MY_LEX_START;
unknown's avatar
unknown committed
1959 1960
      }
      else
1961
        state= MY_LEX_CHAR;              // Return '*'
unknown's avatar
unknown committed
1962
      break;
1963
    case MY_LEX_SET_VAR:                // Check if ':='
1964
      if (yyPeek() != '=')
unknown's avatar
unknown committed
1965
      {
1966 1967 1968 1969 1970 1971 1972
        next_state= MY_LEX_START;
        if (m_thd->variables.sql_mode & MODE_ORACLE)
        {
          yylval->kwd.set_keyword(m_tok_start, 1);
          return COLON_ORACLE_SYM;
        }
        return (int) ':';
unknown's avatar
unknown committed
1973
      }
1974
      yySkip();
unknown's avatar
unknown committed
1975
      return (SET_VAR);
1976
    case MY_LEX_SEMICOLON:              // optional line terminator
1977 1978
      state= MY_LEX_CHAR;               // Return ';'
      break;
1979
    case MY_LEX_EOL:
1980
      if (eof())
unknown's avatar
unknown committed
1981
      {
1982 1983 1984 1985
        yyUnget();                 // Reject the last '\0'
        set_echo(FALSE);
        yySkip();
        set_echo(TRUE);
1986
        /* Unbalanced comments with a missing '*' '/' are a syntax error */
1987
        if (in_comment != NO_COMMENT)
1988
          return (ABORT_SYM);
1989
        next_state= MY_LEX_END;     // Mark for next loop
1990
        return(END_OF_INPUT);
unknown's avatar
unknown committed
1991 1992 1993
      }
      state=MY_LEX_CHAR;
      break;
1994
    case MY_LEX_END:
1995
      next_state= MY_LEX_END;
1996
      return(0);                        // We found end of input last time
1997

1998
      /* Actually real shouldn't start with . but allow them anyhow */
1999
    case MY_LEX_REAL_OR_POINT:
2000
      if (my_isdigit(cs, (c= yyPeek())))
2001
        state = MY_LEX_REAL;            // Real
2002 2003
      else if (c == '.')
      {
2004
        yySkip();
2005 2006
        return DOT_DOT_SYM;
      }
unknown's avatar
unknown committed
2007 2008
      else
      {
2009
        state= MY_LEX_IDENT_SEP;        // return '.'
2010
        yyUnget();                 // Put back '.'
unknown's avatar
unknown committed
2011 2012
      }
      break;
2013
    case MY_LEX_USER_END:               // end '@' of user@hostname
2014
      switch (state_map[(uchar) yyPeek()]) {
2015 2016 2017
      case MY_LEX_STRING:
      case MY_LEX_USER_VARIABLE_DELIMITER:
      case MY_LEX_STRING_OR_DELIMITER:
2018
        break;
2019
      case MY_LEX_USER_END:
2020
        next_state= MY_LEX_SYSTEM_VAR;
2021
        break;
unknown's avatar
unknown committed
2022
      default:
2023
        next_state= MY_LEX_HOSTNAME;
2024
        break;
unknown's avatar
unknown committed
2025
      }
2026 2027
      yylval->lex_str.str= (char*) get_ptr();
      yylval->lex_str.length= 1;
unknown's avatar
unknown committed
2028
      return((int) '@');
2029
    case MY_LEX_HOSTNAME:               // end '@' of user@hostname
2030
      for (c= yyGet() ;
2031
           my_isalnum(cs, c) || c == '.' || c == '_' ||  c == '$';
2032 2033
           c= yyGet()) ;
      yylval->lex_str= get_token(0, yyLength());
unknown's avatar
unknown committed
2034
      return(LEX_HOSTNAME);
2035
    case MY_LEX_SYSTEM_VAR:
2036 2037 2038 2039
      yylval->lex_str.str= (char*) get_ptr();
      yylval->lex_str.length= 1;
      yySkip();                                    // Skip '@'
      next_state= (state_map[(uchar) yyPeek()] ==
2040 2041 2042
                        MY_LEX_USER_VARIABLE_DELIMITER ?
                        MY_LEX_OPERATOR_OR_IDENT :
                        MY_LEX_IDENT_OR_KEYWORD);
unknown's avatar
unknown committed
2043
      return((int) '@');
2044
    case MY_LEX_IDENT_OR_KEYWORD:
unknown's avatar
unknown committed
2045
      /*
2046 2047 2048
        We come here when we have found two '@' in a row.
        We should now be able to handle:
        [(global | local | session) .]variable_name
unknown's avatar
unknown committed
2049
      */
2050
      return scan_ident_sysvar(thd, &yylval->ident_cli);
2051 2052 2053
    }
  }
}
2054

unknown's avatar
unknown committed
2055

2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
bool Lex_input_stream::get_7bit_or_8bit_ident(THD *thd, uchar *last_char)
{
  uchar c;
  CHARSET_INFO *const cs= thd->charset();
  const uchar *const ident_map= cs->ident_map;
  bool is_8bit= false;
  for ( ; ident_map[c= yyGet()]; )
  {
    if (c & 0x80)
      is_8bit= true; // will convert
  }
  *last_char= c;
  return is_8bit;
}
2070

unknown's avatar
unknown committed
2071

2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
int Lex_input_stream::scan_ident_sysvar(THD *thd, Lex_ident_cli_st *str)
{
  uchar last_char;
  uint length;
  int tokval;
  bool is_8bit;
  DBUG_ASSERT(m_tok_start == m_ptr);

  is_8bit= get_7bit_or_8bit_ident(thd, &last_char);

  if (last_char == '.')
    next_state= MY_LEX_IDENT_SEP;
  if (!(length= yyLength()))
    return ABORT_SYM;                  // Names must be nonempty.
2086
  if ((tokval= find_keyword(str, length, 0)))
2087 2088 2089 2090
  {
    yyUnget();                         // Put back 'c'
    return tokval;                     // Was keyword
  }
unknown's avatar
unknown committed
2091

2092
  yyUnget();                       // ptr points now after last token char
2093
  str->set_ident(m_tok_start, length, is_8bit);
unknown's avatar
unknown committed
2094

2095
  m_cpp_text_start= m_cpp_tok_start;
2096 2097 2098 2099 2100 2101
  m_cpp_text_end= m_cpp_text_start + length;
  body_utf8_append(m_cpp_text_start);
  body_utf8_append_ident(thd, str, m_cpp_text_end);

  return is_8bit ? IDENT_QUOTED : IDENT;
}
unknown's avatar
unknown committed
2102 2103


2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
/*
  We can come here if different parsing stages:
  - In an identifier chain:
       SELECT t1.cccc FROM t1;
    (when the "cccc" part starts)
    In this case both m_tok_start and m_ptr point to "cccc".
  - When a sequence of digits has changed to something else,
    therefore the token becomes an identifier rather than a number:
       SELECT 12345_6 FROM t1;
    In this case m_tok_start points to the entire "12345_678",
    while m_ptr points to "678".
*/
int Lex_input_stream::scan_ident_start(THD *thd, Lex_ident_cli_st *str)
{
  uchar c;
  bool is_8bit;
  CHARSET_INFO *const cs= thd->charset();
  const uchar *const ident_map= cs->ident_map;
  DBUG_ASSERT(m_tok_start <= m_ptr);

  if (use_mb(cs))
  {
    is_8bit= true;
    while (ident_map[c= yyGet()])
    {
      int char_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
      if (char_length <= 0)
        break;
      skip_binary(char_length - 1);
unknown's avatar
unknown committed
2133 2134
    }
  }
2135 2136 2137 2138 2139 2140 2141 2142 2143
  else
  {
    is_8bit= get_7bit_or_8bit_ident(thd, &c);
  }
  if (c == '.' && ident_map[(uchar) yyPeek()])
    next_state= MY_LEX_IDENT_SEP;// Next is '.'

  uint length= yyLength();
  yyUnget(); // ptr points now after last token char
2144 2145
  str->set_ident(m_tok_start, length, is_8bit);
  m_cpp_text_start= m_cpp_tok_start;
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
  m_cpp_text_end= m_cpp_text_start + length;
  body_utf8_append(m_cpp_text_start);
  body_utf8_append_ident(thd, str, m_cpp_text_end);
  return is_8bit ? IDENT_QUOTED : IDENT;
}


int Lex_input_stream::scan_ident_middle(THD *thd, Lex_ident_cli_st *str,
                                        CHARSET_INFO **introducer,
                                        my_lex_states *st)
{
  CHARSET_INFO *const cs= thd->charset();
  const uchar *const ident_map= cs->ident_map;
  const uchar *const state_map= cs->state_map;
  const char *start;
  uint length;
  uchar c;
  bool is_8bit;
  bool resolve_introducer= true;
  DBUG_ASSERT(m_ptr == m_tok_start + 1); // m_ptr points to the second byte

  if (use_mb(cs))
  {
    is_8bit= true;
    int char_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
    if (char_length <= 0)
    {
      *st= MY_LEX_CHAR;
      return 0;
    }
    skip_binary(char_length - 1);

    while (ident_map[c= yyGet()])
    {
      char_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
      if (char_length <= 0)
        break;
      if (char_length > 1 || (c & 0x80))
        resolve_introducer= false;
      skip_binary(char_length - 1);
    }
  }
  else
  {
2190
    is_8bit= get_7bit_or_8bit_ident(thd, &c) || (m_tok_start[0] & 0x80);
2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209
    resolve_introducer= !is_8bit;
  }
  length= yyLength();
  start= get_ptr();
  if (ignore_space)
  {
    /*
      If we find a space then this can't be an identifier. We notice this
      below by checking start != lex->ptr.
    */
    for (; state_map[(uchar) c] == MY_LEX_SKIP ; c= yyGet())
    {
      if (c == '\n')
        yylineno++;
    }
  }
  if (start == get_ptr() && c == '.' && ident_map[(uchar) yyPeek()])
    next_state= MY_LEX_IDENT_SEP;
  else
2210
  {                                    // '(' must follow directly if function
2211 2212
    int tokval;
    yyUnget();
2213
    if ((tokval= find_keyword(str, length, c == '(')))
2214
    {
2215 2216
      next_state= MY_LEX_START;        // Allow signed numbers
      return(tokval);                  // Was keyword
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
    }
    yySkip();                  // next state does a unget
  }

  /*
     Note: "SELECT _bla AS 'alias'"
     _bla should be considered as a IDENT if charset haven't been found.
     So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
     producing an error.
  */
  DBUG_ASSERT(length > 0);
2228
  if (resolve_introducer && m_tok_start[0] == '_')
2229 2230 2231
  {

    yyUnget();                       // ptr points now after last token char
2232
    str->set_ident(m_tok_start, length, false);
2233

2234
    m_cpp_text_start= m_cpp_tok_start;
2235
    m_cpp_text_end= m_cpp_text_start + length;
2236
    body_utf8_append(m_cpp_text_start, m_cpp_tok_start + length);
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
    ErrConvString csname(str->str + 1, str->length - 1, &my_charset_bin);
    CHARSET_INFO *cs= get_charset_by_csname(csname.ptr(),
                                            MY_CS_PRIMARY, MYF(0));
    if (cs)
    {
      *introducer= cs;
      return UNDERSCORE_CHARSET;
    }
    return IDENT;
  }

  yyUnget();                       // ptr points now after last token char
2249 2250
  str->set_ident(m_tok_start, length, is_8bit);
  m_cpp_text_start= m_cpp_tok_start;
2251 2252 2253 2254 2255 2256 2257 2258
  m_cpp_text_end= m_cpp_text_start + length;
  body_utf8_append(m_cpp_text_start);
  body_utf8_append_ident(thd, str, m_cpp_text_end);
  return is_8bit ? IDENT_QUOTED : IDENT;
}


int Lex_input_stream::scan_ident_delimited(THD *thd,
2259 2260
                                           Lex_ident_cli_st *str,
                                           uchar quote_char)
2261 2262 2263
{
  CHARSET_INFO *const cs= thd->charset();
  uint double_quotes= 0;
2264
  uchar c;
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
  DBUG_ASSERT(m_ptr == m_tok_start + 1);

  while ((c= yyGet()))
  {
    int var_length= my_charlen(cs, get_ptr() - 1, get_end_of_query());
    if (var_length == 1)
    {
      if (c == quote_char)
      {
        if (yyPeek() != quote_char)
          break;
        c= yyGet();
        double_quotes++;
        continue;
      }
    }
    else if (var_length > 1)
    {
      skip_binary(var_length - 1);
    }
  }

2287
  str->set_ident_quoted(m_tok_start + 1, yyLength() - 1, true, quote_char);
2288 2289
  yyUnget();                       // ptr points now after last token char

2290
  m_cpp_text_start= m_cpp_tok_start + 1;
2291 2292 2293 2294 2295 2296 2297 2298 2299
  m_cpp_text_end= m_cpp_text_start + str->length;

  if (c == quote_char)
    yySkip();                  // Skip end `
  next_state= MY_LEX_START;
  body_utf8_append(m_cpp_text_start);
  // QQQ: shouldn't it add unescaped version ????
  body_utf8_append_ident(thd, str, m_cpp_text_end);
  return IDENT_QUOTED;
unknown's avatar
unknown committed
2300
}
unknown's avatar
unknown committed
2301

2302

2303
void trim_whitespace(CHARSET_INFO *cs, LEX_CSTRING *str, size_t * prefix_length)
2304 2305 2306 2307 2308 2309
{
  /*
    TODO:
    This code assumes that there are no multi-bytes characters
    that can be considered white-space.
  */
2310

2311
  size_t plen= 0;
2312 2313
  while ((str->length > 0) && (my_isspace(cs, str->str[0])))
  {
2314
    plen++;
2315 2316 2317
    str->length --;
    str->str ++;
  }
2318 2319
  if (prefix_length)
    *prefix_length= plen;
2320 2321 2322 2323 2324 2325 2326 2327
  /*
    FIXME:
    Also, parsing backward is not safe with multi bytes characters
  */
  while ((str->length > 0) && (my_isspace(cs, str->str[str->length-1])))
  {
    str->length --;
  }
2328 2329
}

2330

unknown's avatar
unknown committed
2331 2332 2333 2334
/*
  st_select_lex structures initialisations
*/

Eugene Kosov's avatar
Eugene Kosov committed
2335
void st_select_lex_node::init_query_common()
unknown's avatar
unknown committed
2336
{
2337
  options= 0;
2338 2339
  set_linkage(UNSPECIFIED_TYPE);
  distinct= TRUE;
Michael Widenius's avatar
Michael Widenius committed
2340
  no_table_names_allowed= 0;
2341
  uncacheable= 0;
unknown's avatar
unknown committed
2342 2343 2344 2345
}

void st_select_lex_unit::init_query()
{
Eugene Kosov's avatar
Eugene Kosov committed
2346
  init_query_common();
2347
  set_linkage(GLOBAL_OPTIONS_TYPE);
2348 2349
  select_limit_cnt= HA_POS_ERROR;
  offset_limit_cnt= 0;
2350
  union_distinct= 0;
2351
  prepared= optimized= optimized_2= executed= 0;
Igor Babaev's avatar
Igor Babaev committed
2352
  optimize_started= 0;
unknown's avatar
unknown committed
2353
  item= 0;
2354 2355
  union_result= 0;
  table= 0;
unknown's avatar
unknown committed
2356
  fake_select_lex= 0;
2357
  saved_fake_select_lex= 0;
2358
  cleaned= 0;
2359
  item_list.empty();
2360
  describe= 0;
2361
  found_rows_for_union= 0;
2362
  derived= 0;
2363
  is_view= false;
2364 2365
  with_clause= 0;
  with_element= 0;
2366
  columns_are_renamed= false;
2367
  intersect_mark= NULL;
2368
  with_wrapped_tvc= false;
unknown's avatar
unknown committed
2369 2370 2371 2372
}

void st_select_lex::init_query()
{
Eugene Kosov's avatar
Eugene Kosov committed
2373
  init_query_common();
2374
  table_list.empty();
2375 2376
  top_join_list.empty();
  join_list= &top_join_list;
2377
  embedding= 0;
Igor Babaev's avatar
Igor Babaev committed
2378
  leaf_tables_prep.empty();
2379
  leaf_tables.empty();
unknown's avatar
unknown committed
2380
  item_list.empty();
Igor Babaev's avatar
Igor Babaev committed
2381
  min_max_opt_list.empty();
unknown's avatar
unknown committed
2382
  join= 0;
2383
  having= prep_having= where= prep_where= 0;
Igor Babaev's avatar
Igor Babaev committed
2384
  cond_pushed_into_where= cond_pushed_into_having= 0;
2385
  attach_to_conds.empty();
2386
  olap= UNSPECIFIED_OLAP_TYPE;
2387
  having_fix_field= 0;
2388
  having_fix_field_for_pushed_cond= 0;
2389 2390
  context.select_lex= this;
  context.init();
2391
  cond_count= between_count= with_wild= 0;
unknown's avatar
unknown committed
2392
  max_equal_elems= 0;
2393
  ref_pointer_array.reset();
unknown's avatar
unknown committed
2394
  select_n_where_fields= 0;
unknown's avatar
unknown committed
2395
  select_n_reserved= 0;
unknown's avatar
unknown committed
2396
  select_n_having_items= 0;
2397
  n_sum_items= 0;
2398
  n_child_sum_items= 0;
2399
  hidden_bit_fields= 0;
2400
  subquery_in_having= explicit_limit= 0;
2401
  is_item_list_lookup= 0;
2402
  changed_elements= 0;
2403
  first_natural_join_processing= 1;
unknown's avatar
unknown committed
2404
  first_cond_optimization= 1;
2405
  parsing_place= NO_MATTER;
2406
  save_parsing_place= NO_MATTER;
2407
  exclude_from_table_unique_test= no_wrap_view_item= FALSE;
unknown's avatar
unknown committed
2408
  nest_level= 0;
2409
  link_next= 0;
2410
  prep_leaf_list_state= UNINIT;
2411
  have_merged_subqueries= FALSE;
unknown's avatar
unknown committed
2412
  bzero((char*) expr_cache_may_be_used, sizeof(expr_cache_may_be_used));
2413
  select_list_tables= 0;
2414 2415
  m_non_agg_field_used= false;
  m_agg_func_used= false;
2416
  m_custom_agg_func_used= false;
2417 2418
  window_specs.empty();
  window_funcs.empty();
2419
  tvc= 0;
Galina Shalygina's avatar
Galina Shalygina committed
2420
  in_tvc= false;
2421
  versioned_tables= 0;
2422
  pushdown_select= 0;
unknown's avatar
unknown committed
2423 2424 2425 2426
}

void st_select_lex::init_select()
{
2427
  sj_nests.empty();
Igor Babaev's avatar
Igor Babaev committed
2428
  sj_subselects.empty();
2429
  group_list.empty();
2430 2431
  if (group_list_ptrs)
    group_list_ptrs->clear();
2432 2433
  type= 0;
  db= null_clex_str;
2434 2435 2436
  having= 0;
  table_join_options= 0;
  in_sum_expr= with_wild= 0;
unknown's avatar
unknown committed
2437
  options= 0;
unknown's avatar
unknown committed
2438
  ftfunc_list_alloc.empty();
unknown's avatar
unknown committed
2439
  inner_sum_func_list= 0;
unknown's avatar
unknown committed
2440
  ftfunc_list= &ftfunc_list_alloc;
2441
  order_list.empty();
2442 2443 2444
  /* Set limit and offset to default values */
  select_limit= 0;      /* denotes the default limit = HA_POS_ERROR */
  offset_limit= 0;      /* denotes the default offset = 0 */
2445
  is_set_query_expr_tail= false;
unknown's avatar
unknown committed
2446
  with_sum_func= 0;
2447
  with_all_modifier= 0;
2448
  is_correlated= 0;
2449
  cur_pos_in_select_list= UNDEF_POS;
2450
  cond_value= having_value= Item::COND_UNDEF;
2451
  inner_refs_list.empty();
2452
  insert_tables= 0;
Igor Babaev's avatar
Igor Babaev committed
2453
  merged_into= 0;
2454 2455
  m_non_agg_field_used= false;
  m_agg_func_used= false;
2456
  m_custom_agg_func_used= false;
2457
  name_visibility_map.clear_all();
2458
  with_dep= 0;
2459
  join= 0;
2460
  lock_type= TL_READ_DEFAULT;
2461
  tvc= 0;
2462
  in_funcs.empty();
2463
  curr_tvc_name= 0;
Galina Shalygina's avatar
Galina Shalygina committed
2464
  in_tvc= false;
2465
  versioned_tables= 0;
unknown's avatar
unknown committed
2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479
}

/*
  st_select_lex structures linking
*/

/* include on level down */
void st_select_lex_node::include_down(st_select_lex_node *upper)
{
  if ((next= upper->slave))
    next->prev= &next;
  prev= &upper->slave;
  upper->slave= this;
  master= upper;
unknown's avatar
unknown committed
2480
  slave= 0;
unknown's avatar
unknown committed
2481 2482
}

unknown's avatar
unknown committed
2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506

void st_select_lex_node::add_slave(st_select_lex_node *slave_arg)
{
  for (; slave; slave= slave->next)
    if (slave == slave_arg)
      return;

  if (slave)
  {
    st_select_lex_node *slave_arg_slave= slave_arg->slave;
    /* Insert in the front of list of slaves if any. */
    slave_arg->include_neighbour(slave);
    /* include_neighbour() sets slave_arg->slave=0, restore it. */
    slave_arg->slave= slave_arg_slave;
    /* Count on include_neighbour() setting the master. */
    DBUG_ASSERT(slave_arg->master == this);
  }
  else
  {
    slave= slave_arg;
    slave_arg->master= this;
  }
}

2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523
void st_select_lex_node::link_chain_down(st_select_lex_node *first)
{
  st_select_lex_node *last_node;
  st_select_lex_node *node= first;
  do
  {
    last_node= node;
    node->master= this;
    node= node->next;
  } while (node);
  if ((last_node->next= slave))
  {
    slave->prev= &last_node->next;
  }
  first->prev= &slave;
  slave= first;
}
unknown's avatar
unknown committed
2524

unknown's avatar
unknown committed
2525 2526
/*
  include on level down (but do not link)
unknown's avatar
unknown committed
2527

unknown's avatar
unknown committed
2528 2529 2530 2531 2532 2533
  SYNOPSYS
    st_select_lex_node::include_standalone()
    upper - reference on node underr which this node should be included
    ref - references on reference on this node
*/
void st_select_lex_node::include_standalone(st_select_lex_node *upper,
2534
                                            st_select_lex_node **ref)
unknown's avatar
unknown committed
2535 2536 2537 2538 2539 2540 2541
{
  next= 0;
  prev= ref;
  master= upper;
  slave= 0;
}

unknown's avatar
unknown committed
2542 2543 2544 2545 2546 2547 2548 2549
/* include neighbour (on same level) */
void st_select_lex_node::include_neighbour(st_select_lex_node *before)
{
  if ((next= before->next))
    next->prev= &next;
  prev= &before->next;
  before->next= this;
  master= before->master;
unknown's avatar
unknown committed
2550
  slave= 0;
unknown's avatar
unknown committed
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
}

/* including in global SELECT_LEX list */
void st_select_lex_node::include_global(st_select_lex_node **plink)
{
  if ((link_next= *plink))
    link_next->link_prev= &link_next;
  link_prev= plink;
  *plink= this;
}

//excluding from global list (internal function)
void st_select_lex_node::fast_exclude()
{
unknown's avatar
unknown committed
2565
  if (link_prev)
unknown's avatar
unknown committed
2566 2567 2568 2569
  {
    if ((*link_prev= link_next))
      link_next->link_prev= link_prev;
  }
2570 2571 2572
  // Remove slave structure
  for (; slave; slave= slave->next)
    slave->fast_exclude();
2573

unknown's avatar
unknown committed
2574 2575
}

2576

2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
/**
  @brief
    Insert a new chain of nodes into another chain before a particular link

  @param in/out
    ptr_pos_to_insert  the address of the chain pointer pointing to the link
                       before which the subchain has to be inserted
  @param   
    end_chain_node     the last link of the subchain to be inserted

  @details
    The method inserts the chain of nodes starting from this node and ending
    with the node nd_chain_node into another chain of nodes before the node
    pointed to by *ptr_pos_to_insert.
    It is assumed that ptr_pos_to_insert belongs to the chain where we insert.
    So it must be updated.

  @retval
    The method returns the pointer to the first link of the inserted chain
*/

st_select_lex_node *st_select_lex_node:: insert_chain_before(
2599
                                         st_select_lex_node **ptr_pos_to_insert,
2600 2601 2602 2603 2604 2605 2606 2607
                                         st_select_lex_node *end_chain_node)
{
  end_chain_node->link_next= *ptr_pos_to_insert;
  (*ptr_pos_to_insert)->link_prev= &end_chain_node->link_next;
  this->link_prev= ptr_pos_to_insert;
  return this;
}

Igor Babaev's avatar
Igor Babaev committed
2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623

/*
  Detach the node from its master and attach it to a new master
*/

void st_select_lex_node::move_as_slave(st_select_lex_node *new_master)
{
  exclude_from_tree();
  if (new_master->slave)
  {
    st_select_lex_node *curr= new_master->slave;
    for ( ; curr->next ; curr= curr->next) ;
    prev= &curr->next;
  }
  else
    prev= &new_master->slave;
2624
  *prev= this;
Igor Babaev's avatar
Igor Babaev committed
2625 2626 2627 2628 2629
  next= 0;
  master= new_master;
}


2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641
/*
  Exclude a node from the tree lex structure, but leave it in the global
  list of nodes.
*/

void st_select_lex_node::exclude_from_tree()
{
  if ((*prev= next))
    next->prev= prev;
}


unknown's avatar
unknown committed
2642
/*
2643
  Exclude select_lex structure (except first (first select can't be
unknown's avatar
unknown committed
2644 2645 2646 2647
  deleted, because it is most upper select))
*/
void st_select_lex_node::exclude()
{
2648
  /* exclude from global list */
unknown's avatar
unknown committed
2649
  fast_exclude();
2650 2651
  /* exclude from other structures */
  exclude_from_tree();
unknown's avatar
unknown committed
2652 2653 2654 2655 2656 2657 2658
  /* 
     We do not need following statements, because prev pointer of first 
     list element point to master->slave
     if (master->slave == this)
       master->slave= next;
  */
}
2659

2660 2661 2662 2663 2664 2665 2666 2667 2668 2669

/*
  Exclude level of current unit from tree of SELECTs

  SYNOPSYS
    st_select_lex_unit::exclude_level()

  NOTE: units which belong to current will be brought up on level of
  currernt unit 
*/
unknown's avatar
unknown committed
2670 2671 2672
void st_select_lex_unit::exclude_level()
{
  SELECT_LEX_UNIT *units= 0, **units_last= &units;
unknown's avatar
unknown committed
2673
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
unknown's avatar
unknown committed
2674
  {
unknown's avatar
unknown committed
2675
    // unlink current level from global SELECTs list
unknown's avatar
unknown committed
2676 2677
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
      sl->link_next->link_prev= sl->link_prev;
unknown's avatar
unknown committed
2678 2679

    // bring up underlay levels
unknown's avatar
unknown committed
2680 2681
    SELECT_LEX_UNIT **last= 0;
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
unknown's avatar
unknown committed
2682 2683
    {
      u->master= master;
unknown's avatar
unknown committed
2684
      last= (SELECT_LEX_UNIT**)&(u->next);
unknown's avatar
unknown committed
2685
    }
unknown's avatar
unknown committed
2686 2687 2688 2689 2690 2691 2692 2693
    if (last)
    {
      (*units_last)= sl->first_inner_unit();
      units_last= last;
    }
  }
  if (units)
  {
unknown's avatar
unknown committed
2694
    // include brought up levels in place of current
unknown's avatar
unknown committed
2695 2696
    (*prev)= units;
    (*units_last)= (SELECT_LEX_UNIT*)next;
unknown's avatar
unknown committed
2697 2698 2699
    if (next)
      next->prev= (SELECT_LEX_NODE**)units_last;
    units->prev= prev;
unknown's avatar
unknown committed
2700 2701
  }
  else
unknown's avatar
unknown committed
2702 2703
  {
    // exclude currect unit from list of nodes
unknown's avatar
unknown committed
2704
    (*prev)= next;
unknown's avatar
unknown committed
2705 2706 2707
    if (next)
      next->prev= prev;
  }
2708 2709
  // Mark it excluded
  prev= NULL;
unknown's avatar
unknown committed
2710 2711
}

2712

Oleksandr Byelkin's avatar
Oleksandr Byelkin committed
2713
#if 0
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723
/*
  Exclude subtree of current unit from tree of SELECTs

  SYNOPSYS
    st_select_lex_unit::exclude_tree()
*/
void st_select_lex_unit::exclude_tree()
{
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
  {
unknown's avatar
unknown committed
2724
    // unlink current level from global SELECTs list
2725 2726 2727
    if (sl->link_prev && (*sl->link_prev= sl->link_next))
      sl->link_next->link_prev= sl->link_prev;

unknown's avatar
unknown committed
2728
    // unlink underlay levels
2729 2730 2731 2732 2733
    for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
    {
      u->exclude_level();
    }
  }
unknown's avatar
unknown committed
2734
  // exclude currect unit from list of nodes
2735
  (*prev)= next;
unknown's avatar
unknown committed
2736 2737
  if (next)
    next->prev= prev;
2738
}
Oleksandr Byelkin's avatar
Oleksandr Byelkin committed
2739
#endif
2740 2741


unknown's avatar
unknown committed
2742 2743 2744 2745 2746
/*
  st_select_lex_node::mark_as_dependent mark all st_select_lex struct from 
  this to 'last' as dependent

  SYNOPSIS
2747
    last - pointer to last st_select_lex struct, before which all 
unknown's avatar
unknown committed
2748 2749 2750 2751 2752 2753
           st_select_lex have to be marked as dependent

  NOTE
    'last' should be reachable from this st_select_lex_node
*/

2754 2755
bool st_select_lex::mark_as_dependent(THD *thd, st_select_lex *last,
                                      Item *dependency)
unknown's avatar
unknown committed
2756
{
2757 2758 2759

  DBUG_ASSERT(this != last);

unknown's avatar
unknown committed
2760 2761 2762 2763
  /*
    Mark all selects from resolved to 1 before select where was
    found table as depended (of select where was found table)
  */
2764 2765
  SELECT_LEX *s= this;
  do
Sergey Petrunya's avatar
Sergey Petrunya committed
2766
  {
2767
    if (!(s->uncacheable & UNCACHEABLE_DEPENDENT_GENERATED))
unknown's avatar
unknown committed
2768 2769
    {
      // Select is dependent of outer select
2770
      s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
2771
                       UNCACHEABLE_DEPENDENT_GENERATED;
2772
      SELECT_LEX_UNIT *munit= s->master_unit();
2773
      munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
2774
                       UNCACHEABLE_DEPENDENT_GENERATED;
2775 2776 2777
      for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
      {
        if (sl != s &&
2778 2779
            !(sl->uncacheable & (UNCACHEABLE_DEPENDENT_GENERATED |
                                 UNCACHEABLE_UNITED)))
2780 2781
          sl->uncacheable|= UNCACHEABLE_UNITED;
      }
unknown's avatar
unknown committed
2782
    }
2783 2784 2785 2786 2787

    Item_subselect *subquery_expr= s->master_unit()->item;
    if (subquery_expr && subquery_expr->mark_as_dependent(thd, last, 
                                                          dependency))
      return TRUE;
2788
  } while ((s= s->outer_select()) != last && s != 0);
2789 2790
  is_correlated= TRUE;
  this->master_unit()->item->is_correlated= TRUE;
2791
  return FALSE;
unknown's avatar
unknown committed
2792 2793
}

unknown's avatar
unknown committed
2794 2795 2796
/*
  prohibit using LIMIT clause
*/
unknown's avatar
unknown committed
2797
bool st_select_lex::test_limit()
unknown's avatar
unknown committed
2798
{
2799
  if (select_limit != 0)
unknown's avatar
unknown committed
2800 2801
  {
    my_error(ER_NOT_SUPPORTED_YET, MYF(0),
unknown's avatar
unknown committed
2802
             "LIMIT & IN/ALL/ANY/SOME subquery");
unknown's avatar
unknown committed
2803 2804 2805 2806
    return(1);
  }
  return(0);
}
2807

2808

2809

2810 2811 2812 2813 2814
st_select_lex* st_select_lex_unit::outer_select()
{
  return (st_select_lex*) master;
}

2815

2816 2817 2818 2819 2820 2821 2822
ha_rows st_select_lex::get_offset()
{
  ulonglong val= 0;

  if (offset_limit)
  {
    // see comment for st_select_lex::get_limit()
2823 2824 2825
    bool err= offset_limit->fix_fields_if_needed(master_unit()->thd, NULL);
    DBUG_ASSERT(!err);
    val= err ? HA_POS_ERROR : offset_limit->val_uint();
2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863
  }

  return (ha_rows)val;
}


ha_rows st_select_lex::get_limit()
{
  ulonglong val= HA_POS_ERROR;

  if (select_limit)
  {
    /*
      fix_fields() has not been called for select_limit. That's due to the
      historical reasons -- this item could be only of type Item_int, and
      Item_int does not require fix_fields(). Thus, fix_fields() was never
      called for select_limit.

      Some time ago, Item_splocal was also allowed for LIMIT / OFFSET clauses.
      However, the fix_fields() behavior was not updated, which led to a crash
      in some cases.

      There is no single place where to call fix_fields() for LIMIT / OFFSET
      items during the fix-fields-phase. Thus, for the sake of readability,
      it was decided to do it here, on the evaluation phase (which is a
      violation of design, but we chose the lesser of two evils).

      We can call fix_fields() here, because select_limit can be of two
      types only: Item_int and Item_splocal. Item_int::fix_fields() is trivial,
      and Item_splocal::fix_fields() (or rather Item_sp_variable::fix_fields())
      has the following properties:
        1) it does not affect other items;
        2) it does not fail.

      Nevertheless DBUG_ASSERT was added to catch future changes in
      fix_fields() implementation. Also added runtime check against a result
      of fix_fields() in order to handle error condition in non-debug build.
    */
2864 2865 2866
    bool err= select_limit->fix_fields_if_needed(master_unit()->thd, NULL);
    DBUG_ASSERT(!err);
    val= err ? HA_POS_ERROR : select_limit->val_uint();
2867 2868 2869 2870 2871 2872
  }

  return (ha_rows)val;
}


unknown's avatar
unknown committed
2873
bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
unknown's avatar
unknown committed
2874
{
unknown's avatar
unknown committed
2875
  return add_to_list(thd, order_list, item, asc);
unknown's avatar
unknown committed
2876
}
2877

2878

2879 2880 2881 2882 2883
bool st_select_lex::add_gorder_to_list(THD *thd, Item *item, bool asc)
{
  return add_to_list(thd, gorder_list, item, asc);
}

2884

unknown's avatar
unknown committed
2885
bool st_select_lex::add_item_to_list(THD *thd, Item *item)
2886
{
2887
  DBUG_ENTER("st_select_lex::add_item_to_list");
2888
  DBUG_PRINT("info", ("Item: %p", item));
2889
  DBUG_RETURN(item_list.push_back(item, thd->mem_root));
2890 2891
}

2892

unknown's avatar
unknown committed
2893
bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
2894
{
unknown's avatar
unknown committed
2895
  return add_to_list(thd, group_list, item, asc);
2896 2897
}

2898

2899
bool st_select_lex::add_ftfunc_to_list(THD *thd, Item_func_match *func)
2900
{
2901
  return !func || ftfunc_list->push_back(func, thd->mem_root); // end of memory?
2902 2903
}

2904

2905 2906 2907 2908 2909
st_select_lex* st_select_lex::outer_select()
{
  return (st_select_lex*) master->get_master();
}

2910

2911 2912 2913 2914 2915 2916
bool st_select_lex::inc_in_sum_expr()
{
  in_sum_expr++;
  return 0;
}

2917

2918 2919 2920 2921 2922
uint st_select_lex::get_in_sum_expr()
{
  return in_sum_expr;
}

2923

2924 2925
TABLE_LIST* st_select_lex::get_table_list()
{
2926
  return table_list.first;
2927 2928 2929 2930 2931 2932 2933
}

List<Item>* st_select_lex::get_item_list()
{
  return &item_list;
}

unknown's avatar
unknown committed
2934 2935 2936 2937 2938
ulong st_select_lex::get_table_join_options()
{
  return table_join_options;
}

2939

unknown's avatar
unknown committed
2940 2941
bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
{
2942 2943 2944 2945

  if (!((options & SELECT_DISTINCT) && !group_list.elements))
    hidden_bit_fields= 0;

2946 2947 2948
  // find_order_in_list() may need some extra space, so multiply by two.
  order_group_num*= 2;

2949
  /*
2950
    We have to create array in prepared statement memory if it is a
2951 2952
    prepared statement
  */
unknown's avatar
unknown committed
2953
  Query_arena *arena= thd->stmt_arena;
2954 2955 2956
  const uint n_elems= (n_sum_items +
                       n_child_sum_items +
                       item_list.elements +
Sergei Golubchik's avatar
Sergei Golubchik committed
2957
                       select_n_reserved +
2958 2959
                       select_n_having_items +
                       select_n_where_fields +
2960 2961
                       order_group_num +
                       hidden_bit_fields) * 5;
2962
  if (!ref_pointer_array.is_null())
2963
  {
2964 2965 2966 2967 2968 2969 2970
    /*
      We need to take 'n_sum_items' into account when allocating the array,
      and this may actually increase during the optimization phase due to
      MIN/MAX rewrite in Item_in_subselect::single_value_transformer.
      In the usual case we can reuse the array from the prepare phase.
      If we need a bigger array, we must allocate a new one.
     */
2971
    if (ref_pointer_array.size() >= n_elems)
2972 2973 2974
      return false;
   }
  Item **array= static_cast<Item**>(arena->alloc(sizeof(Item*) * n_elems));
2975
  if (likely(array != NULL))
2976 2977 2978
    ref_pointer_array= Ref_ptr_array(array, n_elems);

  return array == NULL;
unknown's avatar
unknown committed
2979 2980
}

2981

2982
void st_select_lex_unit::print(String *str, enum_query_type query_type)
unknown's avatar
unknown committed
2983
{
2984
  bool union_all= !union_distinct;
2985 2986
  if (with_clause)
    with_clause->print(str, query_type);
unknown's avatar
unknown committed
2987 2988 2989 2990
  for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
  {
    if (sl != first_select())
    {
2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
      switch (sl->linkage)
      {
      default:
        DBUG_ASSERT(0);
      case UNION_TYPE:
        str->append(STRING_WITH_LEN(" union "));
        if (union_all)
          str->append(STRING_WITH_LEN("all "));
        break;
      case INTERSECT_TYPE:
        str->append(STRING_WITH_LEN(" intersect "));
        break;
      case EXCEPT_TYPE:
        str->append(STRING_WITH_LEN(" except "));
        break;
      }
3007 3008
      if (sl == union_distinct)
        union_all= TRUE;
unknown's avatar
unknown committed
3009 3010 3011
    }
    if (sl->braces)
      str->append('(');
3012
    sl->print(thd, str, query_type);
unknown's avatar
unknown committed
3013 3014 3015
    if (sl->braces)
      str->append(')');
  }
3016
  if (fake_select_lex)
unknown's avatar
unknown committed
3017 3018 3019
  {
    if (fake_select_lex->order_list.elements)
    {
3020
      str->append(STRING_WITH_LEN(" order by "));
3021 3022
      fake_select_lex->print_order(str,
        fake_select_lex->order_list.first,
3023
        query_type);
unknown's avatar
unknown committed
3024
    }
3025
    fake_select_lex->print_limit(thd, str, query_type);
unknown's avatar
unknown committed
3026
  }
3027 3028
  else if (saved_fake_select_lex)
    saved_fake_select_lex->print_limit(thd, str, query_type);
unknown's avatar
unknown committed
3029 3030 3031
}


3032 3033 3034
void st_select_lex::print_order(String *str,
                                ORDER *order,
                                enum_query_type query_type)
unknown's avatar
unknown committed
3035 3036 3037
{
  for (; order; order= order->next)
  {
3038 3039
    if (order->counter_used)
    {
3040 3041 3042 3043 3044 3045 3046
      char buffer[20];
      size_t length= my_snprintf(buffer, 20, "%d", order->counter);
      str->append(buffer, (uint) length);
    }
    else
    {
      /* replace numeric reference with equivalent for ORDER constant */
3047
      if (order->item[0]->is_order_clause_position())
3048
      {
3049 3050
        /* make it expression instead of integer constant */
        str->append(STRING_WITH_LEN("''"));
3051 3052
      }
      else
3053
        (*order->item)->print(str, query_type);
3054
    }
3055 3056
    if (order->direction == ORDER::ORDER_DESC)
       str->append(STRING_WITH_LEN(" desc"));
unknown's avatar
unknown committed
3057 3058 3059 3060 3061
    if (order->next)
      str->append(',');
  }
}
 
3062

3063 3064 3065
void st_select_lex::print_limit(THD *thd,
                                String *str,
                                enum_query_type query_type)
unknown's avatar
unknown committed
3066
{
3067 3068
  SELECT_LEX_UNIT *unit= master_unit();
  Item_subselect *item= unit->item;
3069

3070
  if (item && unit->global_parameters() == this)
unknown's avatar
VIEW  
unknown committed
3071
  {
3072 3073 3074 3075 3076 3077 3078
    Item_subselect::subs_type subs_type= item->substype();
    if (subs_type == Item_subselect::EXISTS_SUBS ||
        subs_type == Item_subselect::IN_SUBS ||
        subs_type == Item_subselect::ALL_SUBS)
    {
      return;
    }
unknown's avatar
VIEW  
unknown committed
3079
  }
3080
  if (explicit_limit)
unknown's avatar
unknown committed
3081
  {
3082
    str->append(STRING_WITH_LEN(" limit "));
unknown's avatar
unknown committed
3083 3084
    if (offset_limit)
    {
3085
      offset_limit->print(str, query_type);
unknown's avatar
unknown committed
3086 3087
      str->append(',');
    }
3088
    select_limit->print(str, query_type);
unknown's avatar
unknown committed
3089 3090 3091
  }
}

3092

3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104
/**
  @brief Restore the LEX and THD in case of a parse error.

  This is a clean up call that is invoked by the Bison generated
  parser before returning an error from MYSQLparse. If your
  semantic actions manipulate with the global thread state (which
  is a very bad practice and should not normally be employed) and
  need a clean-up in case of error, and you can not use %destructor
  rule in the grammar file itself, this function should be used
  to implement the clean up.
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3105
void LEX::cleanup_lex_after_parse_error(THD *thd)
3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
{
  /*
    Delete sphead for the side effect of restoring of the original
    LEX state, thd->lex, thd->mem_root and thd->free_list if they
    were replaced when parsing stored procedure statements.  We
    will never use sphead object after a parse error, so it's okay
    to delete it only for the sake of the side effect.
    TODO: make this functionality explicit in sp_head class.
    Sic: we must nullify the member of the main lex, not the
    current one that will be thrown away
  */
3117
  if (thd->lex->sphead)
3118
  {
3119
    sp_package *pkg;
3120
    thd->lex->sphead->restore_thd_mem_root(thd);
3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140
    if ((pkg= thd->lex->sphead->m_parent))
    {
      /*
        If a syntax error happened inside a package routine definition,
        then thd->lex points to the routine sublex. We need to restore to
        the top level LEX.
      */
      DBUG_ASSERT(pkg->m_top_level_lex);
      DBUG_ASSERT(pkg == pkg->m_top_level_lex->sphead);
      pkg->restore_thd_mem_root(thd);
      LEX *top= pkg->m_top_level_lex;
      delete pkg;
      thd->lex= top;
      thd->lex->sphead= NULL;
    }
    else
    {
      delete thd->lex->sphead;
      thd->lex->sphead= NULL;
    }
3141 3142
  }
}
unknown's avatar
VIEW  
unknown committed
3143

3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163
/*
  Initialize (or reset) Query_tables_list object.

  SYNOPSIS
    reset_query_tables_list()
      init  TRUE  - we should perform full initialization of object with
                    allocating needed memory
            FALSE - object is already initialized so we should only reset
                    its state so it can be used for parsing/processing
                    of new statement

  DESCRIPTION
    This method initializes Query_tables_list so it can be used as part
    of LEX object for parsing/processing of statement. One can also use
    this method to reset state of already initialized Query_tables_list
    so it can be used for processing of new statement.
*/

void Query_tables_list::reset_query_tables_list(bool init)
{
3164
  sql_command= SQLCOM_END;
unknown's avatar
unknown committed
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
  if (!init && query_tables)
  {
    TABLE_LIST *table= query_tables;
    for (;;)
    {
      delete table->view;
      if (query_tables_last == &table->next_global ||
          !(table= table->next_global))
        break;
    }
  }
3176 3177 3178 3179
  query_tables= 0;
  query_tables_last= &query_tables;
  query_tables_own_last= 0;
  if (init)
3180 3181 3182 3183 3184
  {
    /*
      We delay real initialization of hash (and therefore related
      memory allocation) until first insertion into this hash.
    */
Konstantin Osipov's avatar
Konstantin Osipov committed
3185
    my_hash_clear(&sroutines);
3186
  }
3187
  else if (sroutines.records)
3188 3189
  {
    /* Non-zero sroutines.records means that hash was initialized. */
3190
    my_hash_reset(&sroutines);
3191
  }
3192 3193 3194
  sroutines_list.empty();
  sroutines_list_own_last= sroutines_list.next;
  sroutines_list_own_elements= 0;
3195
  binlog_stmt_flags= 0;
3196
  stmt_accessed_table_flag= 0;
3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
}


/*
  Destroy Query_tables_list object with freeing all resources used by it.

  SYNOPSIS
    destroy_query_tables_list()
*/

void Query_tables_list::destroy_query_tables_list()
{
Konstantin Osipov's avatar
Konstantin Osipov committed
3209
  my_hash_free(&sroutines);
3210 3211 3212
}


3213 3214 3215 3216
/*
  Initialize LEX object.

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
3217
    LEX::LEX()
3218 3219 3220 3221 3222 3223 3224 3225 3226

  NOTE
    LEX object initialized with this constructor can be used as part of
    THD object for which one can safely call open_tables(), lock_tables()
    and close_thread_tables() functions. But it is not yet ready for
    statement parsing. On should use lex_start() function to prepare LEX
    for this.
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3227
LEX::LEX()
3228
  : explain(NULL), result(0), arena_for_set_stmt(0), mem_root_for_set_stmt(0),
3229
    option_type(OPT_DEFAULT), context_analysis_only(0), sphead(0),
3230
    default_used(0), is_lex_started(0), limit_rows_examined_cnt(ULONGLONG_MAX)
3231
{
unknown's avatar
unknown committed
3232

3233 3234 3235
  init_dynamic_array2(&plugins, sizeof(plugin_ref), plugins_static_buffer,
                      INITIAL_LEX_PLUGIN_LIST_SIZE,
                      INITIAL_LEX_PLUGIN_LIST_SIZE, 0);
3236
  reset_query_tables_list(TRUE);
3237
  mi.init();
3238
  init_dynamic_array2(&delete_gtid_domain, sizeof(uint32),
3239 3240 3241
                      gtid_domain_static_buffer,
                      initial_gtid_domain_buffer_size,
                      initial_gtid_domain_buffer_size, 0);
3242
  unit.slave= &builtin_select;
3243 3244 3245
}


unknown's avatar
VIEW  
unknown committed
3246
/*
3247
  Check whether the merging algorithm can be used on this VIEW
unknown's avatar
VIEW  
unknown committed
3248 3249

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
3250
    LEX::can_be_merged()
unknown's avatar
VIEW  
unknown committed
3251

3252
  DESCRIPTION
3253 3254 3255
    We can apply merge algorithm if it is single SELECT view  with
    subqueries only in WHERE clause (we do not count SELECTs of underlying
    views, and second level subqueries) and we have not grpouping, ordering,
3256 3257 3258
    HAVING clause, aggregate functions, DISTINCT clause, LIMIT clause and
    several underlying tables.

unknown's avatar
VIEW  
unknown committed
3259 3260 3261 3262 3263
  RETURN
    FALSE - only temporary table algorithm can be used
    TRUE  - merge algorithm can be used
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3264
bool LEX::can_be_merged()
unknown's avatar
VIEW  
unknown committed
3265 3266 3267 3268
{
  // TODO: do not forget implement case when select_lex.table_list.elements==0

  /* find non VIEW subqueries/unions */
3269 3270
  bool selects_allow_merge= (first_select_lex()->next_select() == 0 &&
                             !(first_select_lex()->uncacheable &
3271
                               UNCACHEABLE_RAND));
3272 3273
  if (selects_allow_merge)
  {
3274
    for (SELECT_LEX_UNIT *tmp_unit= first_select_lex()->first_inner_unit();
3275 3276
         tmp_unit;
         tmp_unit= tmp_unit->next_unit())
3277
    {
3278
      if (tmp_unit->first_select()->parent_lex == this &&
3279
          (tmp_unit->item != 0 &&
3280
           (tmp_unit->item->place() != IN_WHERE &&
3281 3282
            tmp_unit->item->place() != IN_ON &&
            tmp_unit->item->place() != SELECT_LIST)))
3283 3284 3285 3286 3287 3288 3289 3290
      {
        selects_allow_merge= 0;
        break;
      }
    }
  }

  return (selects_allow_merge &&
3291 3292 3293 3294 3295 3296
          first_select_lex()->group_list.elements == 0 &&
          first_select_lex()->having == 0 &&
          first_select_lex()->with_sum_func == 0 &&
          first_select_lex()->table_list.elements >= 1 &&
          !(first_select_lex()->options & SELECT_DISTINCT) &&
          first_select_lex()->select_limit == 0);
unknown's avatar
VIEW  
unknown committed
3297 3298
}

3299

unknown's avatar
VIEW  
unknown committed
3300
/*
3301
  check if command can use VIEW with MERGE algorithm (for top VIEWs)
unknown's avatar
VIEW  
unknown committed
3302 3303

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
3304
    LEX::can_use_merged()
unknown's avatar
VIEW  
unknown committed
3305

3306 3307 3308
  DESCRIPTION
    Only listed here commands can use merge algorithm in top level
    SELECT_LEX (for subqueries will be used merge algorithm if
Konstantin Osipov's avatar
Konstantin Osipov committed
3309
    LEX::can_not_use_merged() is not TRUE).
3310

unknown's avatar
VIEW  
unknown committed
3311 3312 3313 3314 3315
  RETURN
    FALSE - command can't use merged VIEWs
    TRUE  - VIEWs with MERGE algorithms can be used
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3316
bool LEX::can_use_merged()
unknown's avatar
VIEW  
unknown committed
3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329
{
  switch (sql_command)
  {
  case SQLCOM_SELECT:
  case SQLCOM_CREATE_TABLE:
  case SQLCOM_UPDATE:
  case SQLCOM_UPDATE_MULTI:
  case SQLCOM_DELETE:
  case SQLCOM_DELETE_MULTI:
  case SQLCOM_INSERT:
  case SQLCOM_INSERT_SELECT:
  case SQLCOM_REPLACE:
  case SQLCOM_REPLACE_SELECT:
3330
  case SQLCOM_LOAD:
unknown's avatar
VIEW  
unknown committed
3331 3332 3333 3334 3335 3336
    return TRUE;
  default:
    return FALSE;
  }
}

3337
/*
3338
  Check if command can't use merged views in any part of command
3339 3340

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
3341
    LEX::can_not_use_merged()
3342

3343 3344
  DESCRIPTION
    Temporary table algorithm will be used on all SELECT levels for queries
Konstantin Osipov's avatar
Konstantin Osipov committed
3345
    listed here (see also LEX::can_use_merged()).
3346

3347 3348 3349 3350 3351
  RETURN
    FALSE - command can't use merged VIEWs
    TRUE  - VIEWs with MERGE algorithms can be used
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3352
bool LEX::can_not_use_merged()
3353 3354 3355 3356 3357
{
  switch (sql_command)
  {
  case SQLCOM_CREATE_VIEW:
  case SQLCOM_SHOW_CREATE:
3358 3359 3360 3361 3362 3363
  /*
    SQLCOM_SHOW_FIELDS is necessary to make 
    information schema tables working correctly with views.
    see get_schema_tables_result function
  */
  case SQLCOM_SHOW_FIELDS:
3364 3365 3366 3367 3368 3369
    return TRUE;
  default:
    return FALSE;
  }
}

unknown's avatar
VIEW  
unknown committed
3370 3371 3372 3373 3374 3375 3376 3377 3378 3379
/*
  Detect that we need only table structure of derived table/view

  SYNOPSIS
    only_view_structure()

  RETURN
    TRUE yes, we need only structure
    FALSE no, we need data
*/
unknown's avatar
unknown committed
3380

Konstantin Osipov's avatar
Konstantin Osipov committed
3381
bool LEX::only_view_structure()
unknown's avatar
VIEW  
unknown committed
3382
{
3383
  switch (sql_command) {
unknown's avatar
VIEW  
unknown committed
3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397
  case SQLCOM_SHOW_CREATE:
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_SHOW_FIELDS:
  case SQLCOM_REVOKE_ALL:
  case SQLCOM_REVOKE:
  case SQLCOM_GRANT:
  case SQLCOM_CREATE_VIEW:
    return TRUE;
  default:
    return FALSE;
  }
}


unknown's avatar
unknown committed
3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409
/*
  Should Items_ident be printed correctly

  SYNOPSIS
    need_correct_ident()

  RETURN
    TRUE yes, we need only structure
    FALSE no, we need data
*/


Konstantin Osipov's avatar
Konstantin Osipov committed
3410
bool LEX::need_correct_ident()
unknown's avatar
unknown committed
3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422
{
  switch(sql_command)
  {
  case SQLCOM_SHOW_CREATE:
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_CREATE_VIEW:
    return TRUE;
  default:
    return FALSE;
  }
}

3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439
/*
  Get effective type of CHECK OPTION for given view

  SYNOPSIS
    get_effective_with_check()
    view    given view

  NOTE
    It have not sense to set CHECK OPTION for SELECT satement or subqueries,
    so we do not.

  RETURN
    VIEW_CHECK_NONE      no need CHECK OPTION
    VIEW_CHECK_LOCAL     CHECK OPTION LOCAL
    VIEW_CHECK_CASCADED  CHECK OPTION CASCADED
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3440
uint8 LEX::get_effective_with_check(TABLE_LIST *view)
3441 3442 3443 3444 3445 3446 3447
{
  if (view->select_lex->master_unit() == &unit &&
      which_check_option_applicable())
    return (uint8)view->with_check;
  return VIEW_CHECK_NONE;
}

unknown's avatar
unknown committed
3448

3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467
/**
  This method should be called only during parsing.
  It is aware of compound statements (stored routine bodies)
  and will initialize the destination with the default
  database of the stored routine, rather than the default
  database of the connection it is parsed in.
  E.g. if one has no current database selected, or current database 
  set to 'bar' and then issues:

  CREATE PROCEDURE foo.p1() BEGIN SELECT * FROM t1 END//

  t1 is meant to refer to foo.t1, not to bar.t1.

  This method is needed to support this rule.

  @return TRUE in case of error (parsing should be aborted, FALSE in
  case of success
*/

3468
bool LEX::copy_db_to(LEX_CSTRING *to)
3469
{
3470
  if (sphead && sphead->m_name.str)
3471 3472 3473 3474 3475 3476
  {
    DBUG_ASSERT(sphead->m_db.str && sphead->m_db.length);
    /*
      It is safe to assign the string by-pointer, both sphead and
      its statements reside in the same memory root.
    */
3477
    *to= sphead->m_db;
3478 3479
    return FALSE;
  }
3480
  return thd->copy_db_to(to);
3481 3482
}

3483 3484
/**
  Initialize offset and limit counters.
unknown's avatar
unknown committed
3485

3486
  @param sl SELECT_LEX to get offset and limit from.
unknown's avatar
unknown committed
3487
*/
unknown's avatar
VIEW  
unknown committed
3488

unknown's avatar
unknown committed
3489
void st_select_lex_unit::set_limit(st_select_lex *sl)
3490
{
3491
  DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
3492

3493 3494 3495 3496
  offset_limit_cnt= sl->get_offset();
  select_limit_cnt= sl->get_limit();
  if (select_limit_cnt + offset_limit_cnt >= select_limit_cnt)
    select_limit_cnt+= offset_limit_cnt;
3497
  else
3498 3499
    select_limit_cnt= HA_POS_ERROR;
}
3500 3501


3502 3503
/**
  Decide if a temporary table is needed for the UNION.
3504

3505 3506 3507
  @retval true  A temporary table is needed.
  @retval false A temporary table is not needed.
 */
3508

3509 3510
bool st_select_lex_unit::union_needs_tmp_table()
{
3511 3512
  if (with_element && with_element->is_recursive)
    return true;
3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525
  if (!with_wrapped_tvc)
  {
    for (st_select_lex *sl= first_select(); sl; sl=sl->next_select())
    {
      if (sl->tvc && sl->tvc->to_be_wrapped_as_with_tail())
      {
        with_wrapped_tvc= true;
        break;
      }
    }
  }
  if (with_wrapped_tvc)
    return true;
3526 3527 3528 3529 3530
  return union_distinct != NULL ||
    global_parameters()->order_list.elements != 0 ||
    thd->lex->sql_command == SQLCOM_INSERT_SELECT ||
    thd->lex->sql_command == SQLCOM_REPLACE_SELECT;
}  
unknown's avatar
unknown committed
3531

3532
/**
3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552
  @brief Set the initial purpose of this TABLE_LIST object in the list of used
    tables.

  We need to track this information on table-by-table basis, since when this
  table becomes an element of the pre-locked list, it's impossible to identify
  which SQL sub-statement it has been originally used in.

  E.g.:

  User request:                 SELECT * FROM t1 WHERE f1();
  FUNCTION f1():                DELETE FROM t2; RETURN 1;
  BEFORE DELETE trigger on t2:  INSERT INTO t3 VALUES (old.a);

  For this user request, the pre-locked list will contain t1, t2, t3
  table elements, each needed for different DML.

  The trigger event map is updated to reflect INSERT, UPDATE, DELETE,
  REPLACE, LOAD DATA, CREATE TABLE .. SELECT, CREATE TABLE ..
  REPLACE SELECT statements, and additionally ON DUPLICATE KEY UPDATE
  clause.
3553 3554
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3555
void LEX::set_trg_event_type_for_tables()
3556
{
3557
  uint8 new_trg_event_map= 0;
3558
  DBUG_ENTER("LEX::set_trg_event_type_for_tables");
3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587

  /*
    Some auxiliary operations
    (e.g. GRANT processing) create TABLE_LIST instances outside
    the parser. Additionally, some commands (e.g. OPTIMIZE) change
    the lock type for a table only after parsing is done. Luckily,
    these do not fire triggers and do not need to pre-load them.
    For these TABLE_LISTs set_trg_event_type is never called, and
    trg_event_map is always empty. That means that the pre-locking
    algorithm will ignore triggers defined on these tables, if
    any, and the execution will either fail with an assert in
    sql_trigger.cc or with an error that a used table was not
    pre-locked, in case of a production build.

    TODO: this usage pattern creates unnecessary module dependencies
    and should be rewritten to go through the parser.
    Table list instances created outside the parser in most cases
    refer to mysql.* system tables. It is not allowed to have
    a trigger on a system table, but keeping track of
    initialization provides extra safety in case this limitation
    is circumvented.
  */

  switch (sql_command) {
  case SQLCOM_LOCK_TABLES:
  /*
    On a LOCK TABLE, all triggers must be pre-loaded for this TABLE_LIST
    when opening an associated TABLE.
  */
3588 3589
    new_trg_event_map= trg2bit(TRG_EVENT_INSERT) | trg2bit(TRG_EVENT_UPDATE) |
                       trg2bit(TRG_EVENT_DELETE);
3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618
    break;
  /*
    Basic INSERT. If there is an additional ON DUPLIATE KEY UPDATE
    clause, it will be handled later in this method.
  */
  case SQLCOM_INSERT:                           /* fall through */
  case SQLCOM_INSERT_SELECT:
  /*
    LOAD DATA ... INFILE is expected to fire BEFORE/AFTER INSERT
    triggers.
    If the statement also has REPLACE clause, it will be
    handled later in this method.
  */
  case SQLCOM_LOAD:                             /* fall through */
  /*
    REPLACE is semantically equivalent to INSERT. In case
    of a primary or unique key conflict, it deletes the old
    record and inserts a new one. So we also may need to
    fire ON DELETE triggers. This functionality is handled
    later in this method.
  */
  case SQLCOM_REPLACE:                          /* fall through */
  case SQLCOM_REPLACE_SELECT:
  /*
    CREATE TABLE ... SELECT defaults to INSERT if the table or
    view already exists. REPLACE option of CREATE TABLE ...
    REPLACE SELECT is handled later in this method.
  */
  case SQLCOM_CREATE_TABLE:
3619
  case SQLCOM_CREATE_SEQUENCE:
3620
    new_trg_event_map|= trg2bit(TRG_EVENT_INSERT);
3621 3622 3623 3624
    break;
  /* Basic update and multi-update */
  case SQLCOM_UPDATE:                           /* fall through */
  case SQLCOM_UPDATE_MULTI:
3625
    new_trg_event_map|= trg2bit(TRG_EVENT_UPDATE);
3626 3627 3628 3629
    break;
  /* Basic delete and multi-delete */
  case SQLCOM_DELETE:                           /* fall through */
  case SQLCOM_DELETE_MULTI:
3630
    new_trg_event_map|= trg2bit(TRG_EVENT_DELETE);
3631 3632 3633 3634 3635 3636 3637
    break;
  default:
    break;
  }

  switch (duplicates) {
  case DUP_UPDATE:
3638
    new_trg_event_map|= trg2bit(TRG_EVENT_UPDATE);
3639 3640
    break;
  case DUP_REPLACE:
3641
    new_trg_event_map|= trg2bit(TRG_EVENT_DELETE);
3642 3643 3644 3645 3646 3647
    break;
  case DUP_ERROR:
  default:
    break;
  }

3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660
  if (period_conditions.is_set())
  {
    switch (sql_command)
    {
    case SQLCOM_DELETE:
    case SQLCOM_UPDATE:
    case SQLCOM_REPLACE:
      new_trg_event_map |= trg2bit(TRG_EVENT_INSERT);
    default:
      break;
    }
  }

3661

3662 3663 3664 3665
  /*
    Do not iterate over sub-selects, only the tables in the outermost
    SELECT_LEX can be modified, if any.
  */
3666
  TABLE_LIST *tables= first_select_lex()->get_table_list();
3667 3668 3669

  while (tables)
  {
3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680
    /*
      This is a fast check to filter out statements that do
      not change data, or tables  on the right side, in case of
      INSERT .. SELECT, CREATE TABLE .. SELECT and so on.
      Here we also filter out OPTIMIZE statement and non-updateable
      views, for which lock_type is TL_UNLOCK or TL_READ after
      parsing.
    */
    if (static_cast<int>(tables->lock_type) >=
        static_cast<int>(TL_WRITE_ALLOW_WRITE))
      tables->trg_event_map= new_trg_event_map;
3681 3682
    tables= tables->next_local;
  }
3683
  DBUG_VOID_RETURN;
3684 3685 3686
}


3687
/*
3688 3689
  Unlink the first table from the global table list and the first table from
  outer select (lex->select_lex) local list
3690 3691 3692

  SYNOPSIS
    unlink_first_table()
3693
    link_to_local   Set to 1 if caller should link this table to local list
unknown's avatar
unknown committed
3694

unknown's avatar
VIEW  
unknown committed
3695
  NOTES
3696 3697
    We assume that first tables in both lists is the same table or the local
    list is empty.
3698 3699

  RETURN
3700
    0      If 'query_tables' == 0
unknown's avatar
VIEW  
unknown committed
3701
    unlinked table
3702
      In this case link_to_local is set.
unknown's avatar
unknown committed
3703

3704
*/
Konstantin Osipov's avatar
Konstantin Osipov committed
3705
TABLE_LIST *LEX::unlink_first_table(bool *link_to_local)
3706
{
unknown's avatar
VIEW  
unknown committed
3707 3708 3709 3710 3711 3712 3713 3714
  TABLE_LIST *first;
  if ((first= query_tables))
  {
    /*
      Exclude from global table list
    */
    if ((query_tables= query_tables->next_global))
      query_tables->prev_global= &query_tables;
3715 3716
    else
      query_tables_last= &query_tables;
unknown's avatar
VIEW  
unknown committed
3717 3718 3719 3720 3721
    first->next_global= 0;

    /*
      and from local list if it is not empty
    */
3722
    if ((*link_to_local= MY_TEST(first_select_lex()->table_list.first)))
unknown's avatar
VIEW  
unknown committed
3723
    {
3724 3725 3726 3727 3728
      first_select_lex()->context.table_list=
         first_select_lex()->context.first_name_resolution_table=
         first->next_local;
      first_select_lex()->table_list.first= first->next_local;
      first_select_lex()->table_list.elements--;  //safety
unknown's avatar
VIEW  
unknown committed
3729 3730
      first->next_local= 0;
      /*
3731 3732
        Ensure that the global list has the same first table as the local
        list.
unknown's avatar
VIEW  
unknown committed
3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745
      */
      first_lists_tables_same();
    }
  }
  return first;
}


/*
  Bring first local table of first most outer select to first place in global
  table list

  SYNOPSYS
Konstantin Osipov's avatar
Konstantin Osipov committed
3746
     LEX::first_lists_tables_same()
unknown's avatar
VIEW  
unknown committed
3747 3748

  NOTES
3749 3750 3751 3752 3753 3754
    In many cases (for example, usual INSERT/DELETE/...) the first table of
    main SELECT_LEX have special meaning => check that it is the first table
    in global list and re-link to be first in the global list if it is
    necessary.  We need such re-linking only for queries with sub-queries in
    the select list, as only in this case tables of sub-queries will go to
    the global list first.
unknown's avatar
VIEW  
unknown committed
3755 3756
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3757
void LEX::first_lists_tables_same()
unknown's avatar
VIEW  
unknown committed
3758
{
3759
  TABLE_LIST *first_table= first_select_lex()->table_list.first;
unknown's avatar
VIEW  
unknown committed
3760 3761
  if (query_tables != first_table && first_table != 0)
  {
3762
    TABLE_LIST *next;
unknown's avatar
VIEW  
unknown committed
3763 3764
    if (query_tables_last == &first_table->next_global)
      query_tables_last= first_table->prev_global;
3765

3766 3767 3768
    if (query_tables_own_last == &first_table->next_global)
      query_tables_own_last= first_table->prev_global;

3769
    if ((next= *first_table->prev_global= first_table->next_global))
unknown's avatar
VIEW  
unknown committed
3770 3771 3772 3773
      next->prev_global= first_table->prev_global;
    /* include in new place */
    first_table->next_global= query_tables;
    /*
3774 3775 3776
       We are sure that query_tables is not 0, because first_table was not
       first table in the global list => we can use
       query_tables->prev_global without check of query_tables
unknown's avatar
VIEW  
unknown committed
3777 3778 3779 3780 3781
    */
    query_tables->prev_global= &first_table->next_global;
    first_table->prev_global= &query_tables;
    query_tables= first_table;
  }
3782 3783
}

3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800
void LEX::fix_first_select_number()
{
  SELECT_LEX *first= first_select_lex();
  if (first && first->select_number != 1)
  {
    uint num= first->select_number;
    for (SELECT_LEX *sel= all_selects_list;
         sel;
         sel= sel->next_select_in_list())
    {
      if (sel->select_number < num)
        sel->select_number++;
    }
    first->select_number= 1;
  }
}

unknown's avatar
unknown committed
3801

3802
/*
unknown's avatar
unknown committed
3803
  Link table back that was unlinked with unlink_first_table()
3804 3805 3806

  SYNOPSIS
    link_first_table_back()
3807
    link_to_local        do we need link this table to local
3808 3809 3810 3811

  RETURN
    global list
*/
unknown's avatar
VIEW  
unknown committed
3812

Konstantin Osipov's avatar
Konstantin Osipov committed
3813
void LEX::link_first_table_back(TABLE_LIST *first,
3814
                                bool link_to_local)
3815
{
unknown's avatar
VIEW  
unknown committed
3816
  if (first)
3817
  {
unknown's avatar
VIEW  
unknown committed
3818 3819
    if ((first->next_global= query_tables))
      query_tables->prev_global= &first->next_global;
3820 3821
    else
      query_tables_last= &first->next_global;
unknown's avatar
VIEW  
unknown committed
3822 3823 3824 3825
    query_tables= first;

    if (link_to_local)
    {
3826 3827 3828 3829
      first->next_local= first_select_lex()->table_list.first;
      first_select_lex()->context.table_list= first;
      first_select_lex()->table_list.first= first;
      first_select_lex()->table_list.elements++; //safety
unknown's avatar
VIEW  
unknown committed
3830 3831 3832 3833 3834
    }
  }
}


3835 3836 3837 3838 3839

/*
  cleanup lex for case when we open table by table for processing

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
3840
    LEX::cleanup_after_one_table_open()
3841 3842 3843 3844 3845

  NOTE
    This method is mostly responsible for cleaning up of selects lists and
    derived tables state. To rollback changes in Query_tables_list one has
    to call Query_tables_list::reset_query_tables_list(FALSE).
3846 3847
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3848
void LEX::cleanup_after_one_table_open()
3849 3850 3851 3852 3853 3854 3855 3856 3857
{
  /*
    thd->lex->derived_tables & additional units may be set if we open
    a view. It is necessary to clear thd->lex->derived_tables flag
    to prevent processing of derived tables during next open_and_lock_tables
    if next table is a real table and cleanup & remove underlying units
    NOTE: all units will be connected to thd->lex->select_lex, because we
    have not UNION on most upper level.
    */
3858
  if (all_selects_list != first_select_lex())
3859 3860
  {
    derived_tables= 0;
3861
    first_select_lex()->exclude_from_table_unique_test= false;
3862
    /* cleunup underlying units (units of VIEW) */
3863
    for (SELECT_LEX_UNIT *un= first_select_lex()->first_inner_unit();
3864 3865 3866 3867
         un;
         un= un->next_unit())
      un->cleanup();
    /* reduce all selects list to default state */
3868
    all_selects_list= first_select_lex();
3869
    /* remove underlying units (units of VIEW) subtree */
3870
    first_select_lex()->cut_subtree();
3871
  }
3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883
}


/*
  Save current state of Query_tables_list for this LEX, and prepare it
  for processing of new statemnt.

  SYNOPSIS
    reset_n_backup_query_tables_list()
      backup  Pointer to Query_tables_list instance to be used for backup
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3884
void LEX::reset_n_backup_query_tables_list(Query_tables_list *backup)
3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902
{
  backup->set_query_tables_list(this);
  /*
    We have to perform full initialization here since otherwise we
    will damage backed up state.
  */
  this->reset_query_tables_list(TRUE);
}


/*
  Restore state of Query_tables_list for this LEX from backup.

  SYNOPSIS
    restore_backup_query_tables_list()
      backup  Pointer to Query_tables_list instance used for backup
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3903
void LEX::restore_backup_query_tables_list(Query_tables_list *backup)
3904 3905 3906
{
  this->destroy_query_tables_list();
  this->set_query_tables_list(backup);
3907 3908 3909
}


unknown's avatar
unknown committed
3910 3911 3912 3913
/*
  Checks for usage of routines and/or tables in a parsed statement

  SYNOPSIS
Konstantin Osipov's avatar
Konstantin Osipov committed
3914
    LEX:table_or_sp_used()
unknown's avatar
unknown committed
3915 3916 3917 3918 3919 3920

  RETURN
    FALSE  No routines and tables used
    TRUE   Either or both routines and tables are used.
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3921
bool LEX::table_or_sp_used()
unknown's avatar
unknown committed
3922 3923 3924 3925 3926 3927 3928 3929 3930 3931
{
  DBUG_ENTER("table_or_sp_used");

  if (sroutines.records || query_tables)
    DBUG_RETURN(TRUE);

  DBUG_RETURN(FALSE);
}


3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950
/*
  Do end-of-prepare fixup for list of tables and their merge-VIEWed tables

  SYNOPSIS
    fix_prepare_info_in_table_list()
      thd  Thread handle
      tbl  List of tables to process

  DESCRIPTION
    Perform end-end-of prepare fixup for list of tables, if any of the tables
    is a merge-algorithm VIEW, recursively fix up its underlying tables as
    well.

*/

static void fix_prepare_info_in_table_list(THD *thd, TABLE_LIST *tbl)
{
  for (; tbl; tbl= tbl->next_local)
  {
unknown's avatar
unknown committed
3951
    if (tbl->on_expr && !tbl->prep_on_expr)
3952
    {
unknown's avatar
unknown committed
3953
      thd->check_and_register_item_tree(&tbl->prep_on_expr, &tbl->on_expr);
3954 3955
      tbl->on_expr= tbl->on_expr->copy_andor_structure(thd);
    }
3956 3957 3958 3959 3960
    if (tbl->is_view_or_derived() && tbl->is_merged_derived())
    {
      SELECT_LEX *sel= tbl->get_single_select();
      fix_prepare_info_in_table_list(thd, sel->get_table_list());
    }
3961 3962 3963 3964
  }
}


unknown's avatar
VIEW  
unknown committed
3965
/*
3966
  Save WHERE/HAVING/ON clauses and replace them with disposable copies
unknown's avatar
VIEW  
unknown committed
3967 3968 3969

  SYNOPSIS
    st_select_lex::fix_prepare_information
3970 3971 3972 3973 3974 3975 3976 3977
      thd          thread handler
      conds        in/out pointer to WHERE condition to be met at execution
      having_conds in/out pointer to HAVING condition to be met at execution
  
  DESCRIPTION
    The passed WHERE and HAVING are to be saved for the future executions.
    This function saves it, and returns a copy which can be thrashed during
    this execution of the statement. By saving/thrashing here we mean only
3978 3979
    We also save the chain of ORDER::next in group_list, in case
    the list is modified by remove_const().
3980 3981 3982
    AND/OR trees.
    The function also calls fix_prepare_info_in_table_list that saves all
    ON expressions.    
unknown's avatar
VIEW  
unknown committed
3983 3984
*/

3985 3986
void st_select_lex::fix_prepare_information(THD *thd, Item **conds, 
                                            Item **having_conds)
unknown's avatar
VIEW  
unknown committed
3987
{
3988
  DBUG_ENTER("st_select_lex::fix_prepare_information");
3989 3990
  if (!thd->stmt_arena->is_conventional() &&
      !(changed_elements & TOUCHED_SEL_COND))
unknown's avatar
VIEW  
unknown committed
3991
  {
3992
    Query_arena_stmt on_stmt_arena(thd);
3993
    changed_elements|= TOUCHED_SEL_COND;
3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006
    if (group_list.first)
    {
      if (!group_list_ptrs)
      {
        void *mem= thd->stmt_arena->alloc(sizeof(Group_list_ptrs));
        group_list_ptrs= new (mem) Group_list_ptrs(thd->stmt_arena->mem_root);
      }
      group_list_ptrs->reserve(group_list.elements);
      for (ORDER *order= group_list.first; order; order= order->next)
      {
        group_list_ptrs->push_back(order);
      }
    }
4007 4008
    if (*conds)
    {
unknown's avatar
unknown committed
4009
      thd->check_and_register_item_tree(&prep_where, conds);
4010 4011
      *conds= where= prep_where->copy_andor_structure(thd);
    }
4012 4013
    if (*having_conds)
    {
unknown's avatar
unknown committed
4014
      thd->check_and_register_item_tree(&prep_having, having_conds);
4015 4016
      *having_conds= having= prep_having->copy_andor_structure(thd);
    }
4017
    fix_prepare_info_in_table_list(thd, table_list.first);
4018
  }
4019
  DBUG_VOID_RETURN;
4020 4021
}

unknown's avatar
unknown committed
4022

unknown's avatar
unknown committed
4023
/*
unknown's avatar
VIEW  
unknown committed
4024
  There are st_select_lex::add_table_to_list &
unknown's avatar
unknown committed
4025
  st_select_lex::set_lock_for_tables are in sql_parse.cc
unknown's avatar
unknown committed
4026

unknown's avatar
VIEW  
unknown committed
4027
  st_select_lex::print is in sql_select.cc
unknown's avatar
unknown committed
4028 4029

  st_select_lex_unit::prepare, st_select_lex_unit::exec,
4030 4031
  st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
  st_select_lex_unit::change_result
unknown's avatar
unknown committed
4032
  are in sql_union.cc
unknown's avatar
unknown committed
4033
*/
4034

4035 4036 4037 4038 4039
/*
  Sets the kind of hints to be added by the calls to add_index_hint().

  SYNOPSIS
    set_index_hint_type()
4040 4041
      type_arg     The kind of hints to be added from now on.
      clause       The clause to use for hints to be added from now on.
4042 4043 4044 4045 4046 4047 4048 4049

  DESCRIPTION
    Used in filling up the tagged hints list.
    This list is filled by first setting the kind of the hint as a 
    context variable and then adding hints of the current kind.
    Then the context variable index_hint_type can be reset to the
    next hint type.
*/
4050
void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
4051 4052
                                        index_clause_map clause)
{ 
4053
  current_index_hint_type= type_arg;
4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067
  current_index_hint_clause= clause;
}


/*
  Makes an array to store index usage hints (ADD/FORCE/IGNORE INDEX).

  SYNOPSIS
    alloc_index_hints()
      thd         current thread.
*/

void st_select_lex::alloc_index_hints (THD *thd)
{ 
unknown's avatar
unknown committed
4068
  index_hints= new (thd->mem_root) List<Index_hint>(); 
4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085
}



/*
  adds an element to the array storing index usage hints 
  (ADD/FORCE/IGNORE INDEX).

  SYNOPSIS
    add_index_hint()
      thd         current thread.
      str         name of the index.
      length      number of characters in str.

  RETURN VALUE
    0 on success, non-zero otherwise
*/
4086
bool st_select_lex::add_index_hint (THD *thd, const char *str, size_t length)
4087
{
4088
  return index_hints->push_front(new (thd->mem_root) 
unknown's avatar
unknown committed
4089
                                 Index_hint(current_index_hint_type,
4090
                                            current_index_hint_clause,
4091
                                            str, length), thd->mem_root);
4092
}
4093

4094

4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111
/**
  Optimize all subqueries that have not been flattened into semi-joins.

  @details
  This functionality is a method of SELECT_LEX instead of JOIN because
  SQL statements as DELETE/UPDATE do not have a corresponding JOIN object.

  @see JOIN::optimize_unflattened_subqueries

  @param const_only  Restrict subquery optimization to constant subqueries

  @return Operation status
  @retval FALSE     success.
  @retval TRUE      error occurred.
*/

bool st_select_lex::optimize_unflattened_subqueries(bool const_only)
4112
{
4113 4114 4115 4116
  SELECT_LEX_UNIT *next_unit= NULL;
  for (SELECT_LEX_UNIT *un= first_inner_unit();
       un;
       un= next_unit ? next_unit : un->next_unit())
4117 4118
  {
    Item_subselect *subquery_predicate= un->item;
4119 4120
    next_unit= NULL;

4121 4122
    if (subquery_predicate)
    {
4123 4124
      if (!subquery_predicate->fixed)
      {
4125 4126 4127
        /*
         This subquery was excluded as part of some expression so it is
         invisible from all prepared expression.
4128
       */
4129 4130 4131 4132 4133
        next_unit= un->next_unit();
        un->exclude_level();
        if (next_unit)
          continue;
        break;
4134
      }
Sergey Petrunya's avatar
Sergey Petrunya committed
4135 4136
      if (subquery_predicate->substype() == Item_subselect::IN_SUBS)
      {
4137
        Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;
Sergey Petrunya's avatar
Sergey Petrunya committed
4138 4139 4140 4141
        if (in_subs->is_jtbm_merged)
          continue;
      }

4142 4143 4144 4145 4146 4147
      if (const_only && !subquery_predicate->const_item())
      {
        /* Skip non-constant subqueries if the caller asked so. */
        continue;
      }

unknown's avatar
unknown committed
4148
      bool empty_union_result= true;
4149
      bool is_correlated_unit= false;
4150 4151
      bool first= true;
      bool union_plan_saved= false;
unknown's avatar
unknown committed
4152 4153 4154 4155
      /*
        If the subquery is a UNION, optimize all the subqueries in the UNION. If
        there is no UNION, then the loop will execute once for the subquery.
      */
4156 4157 4158
      for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
      {
        JOIN *inner_join= sl->join;
4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169
        if (first)
          first= false;
        else
        {
          if (!union_plan_saved)
          {
            union_plan_saved= true;
            if (un->save_union_explain(un->thd->lex->explain))
              return true; /* Failure */
          }
        }
4170 4171
        if (!inner_join)
          continue;
4172
        SELECT_LEX *save_select= un->thd->lex->current_select;
4173
        ulonglong save_options;
4174
        int res;
4175
        /* We need only 1 row to determine existence */
4176
        un->set_limit(un->global_parameters());
4177
        un->thd->lex->current_select= sl;
4178
        save_options= inner_join->select_options;
4179
        if (options & SELECT_DESCRIBE)
4180 4181
        {
          /* Optimize the subquery in the context of EXPLAIN. */
4182
          sl->set_explain_type(FALSE);
unknown's avatar
unknown committed
4183 4184
          sl->options|= SELECT_DESCRIBE;
          inner_join->select_options|= SELECT_DESCRIBE;
4185
        }
4186
        res= inner_join->optimize();
4187 4188
        if (!inner_join->cleaned)
          sl->update_used_tables();
4189 4190
        sl->update_correlated_cache();
        is_correlated_unit|= sl->is_correlated;
4191
        inner_join->select_options= save_options;
4192
        un->thd->lex->current_select= save_select;
4193

4194 4195
        Explain_query *eq;
        if ((eq= inner_join->thd->lex->explain))
4196
        {
4197 4198
          Explain_select *expl_sel;
          if ((expl_sel= eq->get_select(inner_join->select_lex->select_number)))
4199 4200
          {
            sl->set_explain_type(TRUE);
4201
            expl_sel->select_type= sl->type;
4202 4203
          }
        }
4204

unknown's avatar
unknown committed
4205 4206 4207 4208 4209 4210 4211 4212
        if (empty_union_result)
        {
          /*
            If at least one subquery in a union is non-empty, the UNION result
            is non-empty. If there is no UNION, the only subquery is non-empy.
          */
          empty_union_result= inner_join->empty_result();
        }
4213 4214 4215
        if (res)
          return TRUE;
      }
unknown's avatar
unknown committed
4216 4217
      if (empty_union_result)
        subquery_predicate->no_rows_in_result();
4218 4219 4220
      if (!is_correlated_unit)
        un->uncacheable&= ~UNCACHEABLE_DEPENDENT;
      subquery_predicate->is_correlated= is_correlated_unit;
4221 4222 4223
    }
  }
  return FALSE;
4224 4225 4226
}


4227

4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241
/**
  @brief Process all derived tables/views of the SELECT.

  @param lex    LEX of this thread
  @param phase  phases to run derived tables/views through

  @details
  This function runs specified 'phases' on all tables from the
  table_list of this select.

  @return FALSE ok.
  @return TRUE an error occur.
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
4242
bool st_select_lex::handle_derived(LEX *lex, uint phases)
4243
{
4244
  return lex->handle_list_of_derived(table_list.first, phases);
4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300
}


/**
  @brief
  Returns first unoccupied table map and table number

  @param map     [out] return found map
  @param tablenr [out] return found tablenr

  @details
  Returns first unoccupied table map and table number in this select.
  Map and table are returned in *'map' and *'tablenr' accordingly.

  @retrun TRUE  no free table map/table number
  @return FALSE found free table map/table number
*/

bool st_select_lex::get_free_table_map(table_map *map, uint *tablenr)
{
  *map= 0;
  *tablenr= 0;
  TABLE_LIST *tl;
  List_iterator<TABLE_LIST> ti(leaf_tables);
  while ((tl= ti++))
  {
    if (tl->table->map > *map)
      *map= tl->table->map;
    if (tl->table->tablenr > *tablenr)
      *tablenr= tl->table->tablenr;
  }
  (*map)<<= 1;
  (*tablenr)++;
  if (*tablenr >= MAX_TABLES)
    return TRUE;
  return FALSE;
}


/**
  @brief
  Append given table to the leaf_tables list.

  @param link  Offset to which list in table structure to use
  @param table Table to append

  @details
  Append given 'table' to the leaf_tables list using the 'link' offset.
  If the 'table' is linked with other tables through next_leaf/next_local
  chains then whole list will be appended.
*/

void st_select_lex::append_table_to_list(TABLE_LIST *TABLE_LIST::*link,
                                         TABLE_LIST *table)
{
  TABLE_LIST *tl;
Igor Babaev's avatar
Igor Babaev committed
4301
  for (tl= leaf_tables.head(); tl->*link; tl= tl->*link) ;
4302 4303 4304
  tl->*link= table;
}

Igor Babaev's avatar
Igor Babaev committed
4305

4306 4307
/*
  @brief
Igor Babaev's avatar
Igor Babaev committed
4308
  Replace given table from the leaf_tables list for a list of tables 
4309

Igor Babaev's avatar
Igor Babaev committed
4310 4311
  @param table Table to replace
  @param list  List to substititute the table for
4312 4313

  @details
Igor Babaev's avatar
Igor Babaev committed
4314
  Replace 'table' from the leaf_tables list for a list of tables 'tbl_list'.
4315 4316
*/

Igor Babaev's avatar
Igor Babaev committed
4317
void st_select_lex::replace_leaf_table(TABLE_LIST *table, List<TABLE_LIST> &tbl_list)
4318 4319 4320 4321 4322 4323 4324
{
  TABLE_LIST *tl;
  List_iterator<TABLE_LIST> ti(leaf_tables);
  while ((tl= ti++))
  {
    if (tl == table)
    {
Igor Babaev's avatar
Igor Babaev committed
4325
      ti.replace(tbl_list);
4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424
      break;
    }
  }
}


/**
  @brief
  Assigns new table maps to tables in the leaf_tables list

  @param derived    Derived table to take initial table map from
  @param map        table map to begin with
  @param tablenr    table number to begin with
  @param parent_lex new parent select_lex

  @details
  Assign new table maps/table numbers to all tables in the leaf_tables list.
  'map'/'tablenr' are used for the first table and shifted to left/
  increased for each consequent table in the leaf_tables list.
  If the 'derived' table is given then it's table map/number is used for the
  first table in the list and 'map'/'tablenr' are used for the second and
  all consequent tables.
  The 'parent_lex' is set as the new parent select_lex for all tables in the
  list.
*/

void st_select_lex::remap_tables(TABLE_LIST *derived, table_map map,
                                 uint tablenr, SELECT_LEX *parent_lex)
{
  bool first_table= TRUE;
  TABLE_LIST *tl;
  table_map first_map;
  uint first_tablenr;

  if (derived && derived->table)
  {
    first_map= derived->table->map;
    first_tablenr= derived->table->tablenr;
  }
  else
  {
    first_map= map;
    map<<= 1;
    first_tablenr= tablenr++;
  }
  /*
    Assign table bit/table number.
    To the first table of the subselect the table bit/tablenr of the
    derived table is assigned. The rest of tables are getting bits
    sequentially, starting from the provided table map/tablenr.
  */
  List_iterator<TABLE_LIST> ti(leaf_tables);
  while ((tl= ti++))
  {
    if (first_table)
    {
      first_table= FALSE;
      tl->table->set_table_map(first_map, first_tablenr);
    }
    else
    {
      tl->table->set_table_map(map, tablenr);
      tablenr++;
      map<<= 1;
    }
    SELECT_LEX *old_sl= tl->select_lex;
    tl->select_lex= parent_lex;
    for(TABLE_LIST *emb= tl->embedding;
        emb && emb->select_lex == old_sl;
        emb= emb->embedding)
      emb->select_lex= parent_lex;
  }
}

/**
  @brief
  Merge a subquery into this select.

  @param derived     derived table of the subquery to be merged
  @param subq_select select_lex of the subquery
  @param map         table map for assigning to merged tables from subquery
  @param table_no    table number for assigning to merged tables from subquery

  @details
  This function merges a subquery into its parent select. In short the
  merge operation appends the subquery FROM table list to the parent's
  FROM table list. In more details:
    .) the top_join_list of the subquery is wrapped into a join_nest
       and attached to 'derived'
    .) subquery's leaf_tables list  is merged with the leaf_tables
       list of this select_lex
    .) the table maps and table numbers of the tables merged from
       the subquery are adjusted to reflect their new binding to
       this select

  @return TRUE  an error occur
  @return FALSE ok
*/

Igor Babaev's avatar
Igor Babaev committed
4425 4426
bool SELECT_LEX::merge_subquery(THD *thd, TABLE_LIST *derived,
                                SELECT_LEX *subq_select,
4427 4428 4429 4430
                                uint table_no, table_map map)
{
  derived->wrap_into_nested_join(subq_select->top_join_list);

4431
  ftfunc_list->append(subq_select->ftfunc_list);
Igor Babaev's avatar
Igor Babaev committed
4432 4433 4434
  if (join ||
      thd->lex->sql_command == SQLCOM_UPDATE_MULTI ||
      thd->lex->sql_command == SQLCOM_DELETE_MULTI)
4435
  {
Igor Babaev's avatar
Igor Babaev committed
4436 4437 4438
    List_iterator_fast<Item_in_subselect> li(subq_select->sj_subselects);
    Item_in_subselect *in_subq;
    while ((in_subq= li++))
4439
    {
4440
      sj_subselects.push_back(in_subq, thd->mem_root);
Igor Babaev's avatar
Igor Babaev committed
4441 4442
      if (in_subq->emb_on_expr_nest == NO_JOIN_NEST)
         in_subq->emb_on_expr_nest= derived;
4443
    }
4444 4445 4446 4447 4448

    uint cnt= sizeof(expr_cache_may_be_used)/sizeof(bool);
    for (uint i= 0; i < cnt; i++)
    {
      if (subq_select->expr_cache_may_be_used[i])
4449
        expr_cache_may_be_used[i]= true;
4450 4451 4452 4453 4454 4455 4456 4457 4458 4459
    }

    List_iterator_fast<Item_func_in> it(subq_select->in_funcs);
    Item_func_in *in_func;
    while ((in_func= it++))
    {
      in_funcs.push_back(in_func, thd->mem_root);
      if (in_func->emb_on_expr_nest == NO_JOIN_NEST)
        in_func->emb_on_expr_nest= derived;
    }
4460 4461 4462 4463 4464
  }

  /* Walk through child's tables and adjust table map, tablenr,
   * parent_lex */
  subq_select->remap_tables(derived, map, table_no, this);
Igor Babaev's avatar
Igor Babaev committed
4465
  subq_select->merged_into= this;
Igor Babaev's avatar
Igor Babaev committed
4466 4467 4468

  replace_leaf_table(derived, subq_select->leaf_tables);

4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505
  return FALSE;
}


/**
  @brief
  Mark tables from the leaf_tables list as belong to a derived table.

  @param derived   tables will be marked as belonging to this derived

  @details
  Run through the leaf_list and mark all tables as belonging to the 'derived'.
*/

void SELECT_LEX::mark_as_belong_to_derived(TABLE_LIST *derived)
{
  /* Mark tables as belonging to this DT */
  TABLE_LIST *tl;
  List_iterator<TABLE_LIST> ti(leaf_tables);
  while ((tl= ti++))
    tl->belong_to_derived= derived;
}


/**
  @brief
  Update used_tables cache for this select

  @details
  This function updates used_tables cache of ON expressions of all tables
  in the leaf_tables list and of the conds expression (if any).
*/

void SELECT_LEX::update_used_tables()
{
  TABLE_LIST *tl;
  List_iterator<TABLE_LIST> ti(leaf_tables);
Igor Babaev's avatar
Igor Babaev committed
4506

4507 4508
  while ((tl= ti++))
  {
Igor Babaev's avatar
Igor Babaev committed
4509
    if (tl->table && !tl->is_view_or_derived())
Igor Babaev's avatar
Igor Babaev committed
4510
    {
Igor Babaev's avatar
Igor Babaev committed
4511
      TABLE_LIST *embedding= tl->embedding;
Igor Babaev's avatar
Igor Babaev committed
4512 4513 4514
      for (embedding= tl->embedding; embedding; embedding=embedding->embedding)
      {
        if (embedding->is_view_or_derived())
4515
        {
Igor Babaev's avatar
Igor Babaev committed
4516 4517 4518 4519
          DBUG_ASSERT(embedding->is_merged_derived());
          TABLE *tab= tl->table;
          tab->covering_keys= tab->s->keys_for_keyread;
          tab->covering_keys.intersect(tab->keys_in_use_for_query);
4520
          /*
4521
            View/derived was merged. Need to recalculate read_set
4522 4523 4524 4525 4526 4527 4528
            bitmaps here. For example:
              CREATE VIEW v1 AS SELECT f1,f2,f3 FROM t1;
              SELECT f1 FROM v1;
            Initially, the view definition will put all f1,f2,f3 in the
            read_set for t1. But after the view is merged, only f1 should
            be in the read_set.
          */
Igor Babaev's avatar
Igor Babaev committed
4529
          bitmap_clear_all(tab->read_set);
Igor Babaev's avatar
Igor Babaev committed
4530 4531 4532 4533
          break;
        }
      }
    }
Igor Babaev's avatar
Igor Babaev committed
4534 4535 4536 4537 4538 4539
  }

  ti.rewind();
  while ((tl= ti++))
  {
    TABLE_LIST *embedding= tl;
Igor Babaev's avatar
Igor Babaev committed
4540
    do
Igor Babaev's avatar
Igor Babaev committed
4541
    {
Igor Babaev's avatar
Igor Babaev committed
4542
      bool maybe_null;
4543
      if ((maybe_null= MY_TEST(embedding->outer_join)))
Igor Babaev's avatar
Igor Babaev committed
4544
      {
4545
        tl->table->maybe_null= maybe_null;
Igor Babaev's avatar
Igor Babaev committed
4546 4547
        break;
      }
Igor Babaev's avatar
Igor Babaev committed
4548
    }
Igor Babaev's avatar
Igor Babaev committed
4549
    while ((embedding= embedding->embedding));
4550 4551 4552 4553 4554
    if (tl->on_expr)
    {
      tl->on_expr->update_used_tables();
      tl->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
    }
4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567
    /*
      - There is no need to check sj_on_expr, because merged semi-joins inject
        sj_on_expr into the parent's WHERE clase.
      - For non-merged semi-joins (aka JTBMs), we need to check their
        left_expr. There is no need to check the rest of the subselect, we know
        it is uncorrelated and so cannot refer to any tables in this select.
    */
    if (tl->jtbm_subselect)
    {
      Item *left_expr= tl->jtbm_subselect->left_expr;
      left_expr->walk(&Item::update_table_bitmaps_processor, FALSE, NULL);
    }

Igor Babaev's avatar
Igor Babaev committed
4568
    embedding= tl->embedding;
4569 4570 4571 4572 4573 4574 4575 4576 4577 4578
    while (embedding)
    {
      if (embedding->on_expr && 
          embedding->nested_join->join_list.head() == tl)
      {
        embedding->on_expr->update_used_tables();
        embedding->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
      }
      tl= embedding;
      embedding= tl->embedding;
4579
    }
4580
  }
Igor Babaev's avatar
Igor Babaev committed
4581

4582 4583 4584 4585 4586
  if (join->conds)
  {
    join->conds->update_used_tables();
    join->conds->walk(&Item::eval_not_null_tables, 0, NULL);
  }
Igor Babaev's avatar
Igor Babaev committed
4587 4588 4589 4590 4591 4592 4593
  if (join->having)
  {
    join->having->update_used_tables();
  }

  Item *item;
  List_iterator_fast<Item> it(join->fields_list);
4594
  select_list_tables= 0;
Igor Babaev's avatar
Igor Babaev committed
4595 4596 4597
  while ((item= it++))
  {
    item->update_used_tables();
4598
    select_list_tables|= item->used_tables();
Igor Babaev's avatar
Igor Babaev committed
4599 4600 4601 4602 4603 4604 4605 4606 4607 4608
  }
  Item_outer_ref *ref;
  List_iterator_fast<Item_outer_ref> ref_it(inner_refs_list);
  while ((ref= ref_it++))
  {
    item= ref->outer_ref;
    item->update_used_tables();
  }
  for (ORDER *order= group_list.first; order; order= order->next)
    (*order->item)->update_used_tables();
4609 4610
  if (!master_unit()->is_unit_op() ||
      master_unit()->global_parameters() != this)
Igor Babaev's avatar
Igor Babaev committed
4611 4612 4613
  {
    for (ORDER *order= order_list.first; order; order= order->next)
      (*order->item)->update_used_tables();
unknown's avatar
unknown committed
4614 4615
  }
  join->result->update_used_tables();
4616 4617
}

4618

4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634
/**
  @brief
  Update is_correlated cache for this select

  @details
*/

void st_select_lex::update_correlated_cache()
{
  TABLE_LIST *tl;
  List_iterator<TABLE_LIST> ti(leaf_tables);

  is_correlated= false;

  while ((tl= ti++))
  {
4635
    //    is_correlated|= tl->is_with_table_recursive_reference();
4636
    if (tl->on_expr)
4637
      is_correlated|= MY_TEST(tl->on_expr->used_tables() & OUTER_REF_TABLE_BIT);
4638 4639 4640 4641
    for (TABLE_LIST *embedding= tl->embedding ; embedding ;
         embedding= embedding->embedding)
    {
      if (embedding->on_expr)
4642 4643
        is_correlated|= MY_TEST(embedding->on_expr->used_tables() &
                                OUTER_REF_TABLE_BIT);
4644 4645 4646 4647
    }
  }

  if (join->conds)
4648
    is_correlated|= MY_TEST(join->conds->used_tables() & OUTER_REF_TABLE_BIT);
4649

4650 4651
  is_correlated|= join->having_is_correlated;

4652
  if (join->having)
4653
    is_correlated|= MY_TEST(join->having->used_tables() & OUTER_REF_TABLE_BIT);
4654 4655

  if (join->tmp_having)
4656 4657
    is_correlated|= MY_TEST(join->tmp_having->used_tables() &
                            OUTER_REF_TABLE_BIT);
4658 4659 4660 4661

  Item *item;
  List_iterator_fast<Item> it(join->fields_list);
  while ((item= it++))
4662
    is_correlated|= MY_TEST(item->used_tables() & OUTER_REF_TABLE_BIT);
4663 4664

  for (ORDER *order= group_list.first; order; order= order->next)
4665 4666
    is_correlated|= MY_TEST((*order->item)->used_tables() &
                            OUTER_REF_TABLE_BIT);
4667

4668
  if (!master_unit()->is_unit_op())
4669 4670
  {
    for (ORDER *order= order_list.first; order; order= order->next)
4671 4672
      is_correlated|= MY_TEST((*order->item)->used_tables() &
                              OUTER_REF_TABLE_BIT);
4673 4674 4675 4676 4677 4678 4679
  }

  if (!is_correlated)
    uncacheable&= ~UNCACHEABLE_DEPENDENT;
}


4680 4681
/**
  Set the EXPLAIN type for this subquery.
Sergey Petrunya's avatar
Sergey Petrunya committed
4682 4683 4684
  
  @param on_the_fly  TRUE<=> We're running a SHOW EXPLAIN command, so we must 
                     not change any variables
4685 4686
*/

4687
void st_select_lex::set_explain_type(bool on_the_fly)
4688
{
4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708
  bool is_primary= FALSE;
  if (next_select())
    is_primary= TRUE;

  if (!is_primary && first_inner_unit())
  {
    /*
      If there is at least one materialized derived|view then it's a PRIMARY select.
      Otherwise, all derived tables/views were merged and this select is a SIMPLE one.
    */
    for (SELECT_LEX_UNIT *un= first_inner_unit(); un; un= un->next_unit())
    {
      if ((!un->derived || un->derived->is_materialized_derived()))
      {
        is_primary= TRUE;
        break;
      }
    }
  }

4709 4710 4711
  if (on_the_fly && !is_primary && have_merged_subqueries)
    is_primary= TRUE;

4712 4713 4714
  SELECT_LEX *first= master_unit()->first_select();
  /* drop UNCACHEABLE_EXPLAIN, because it is for internal usage only */
  uint8 is_uncacheable= (uncacheable & ~UNCACHEABLE_EXPLAIN);
4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728
  
  bool using_materialization= FALSE;
  Item_subselect *parent_item;
  if ((parent_item= master_unit()->item) &&
      parent_item->substype() == Item_subselect::IN_SUBS)
  {
    Item_in_subselect *in_subs= (Item_in_subselect*)parent_item;
    /*
      Surprisingly, in_subs->is_set_strategy() can return FALSE here,
      even for the last invocation of this function for the select.
    */
    if (in_subs->test_strategy(SUBS_MATERIALIZATION))
      using_materialization= TRUE;
  }
4729

4730
  if (master_unit()->thd->lex->first_select_lex() == this)
4731
  {
4732 4733 4734 4735
    if (pushdown_select)
      type= pushed_select_text;
    else
      type= is_primary ? "PRIMARY" : "SIMPLE";
4736 4737 4738 4739 4740 4741 4742
  }
  else
  {
    if (this == first)
    {
      /* If we're a direct child of a UNION, we're the first sibling there */
      if (linkage == DERIVED_TABLE_TYPE)
4743
      {
4744 4745 4746 4747 4748
        bool is_pushed_master_unit= master_unit()->derived &&
	                            master_unit()->derived->pushdown_derived;
        if (is_pushed_master_unit)
          type= pushed_derived_text;
        else if (is_uncacheable & UNCACHEABLE_DEPENDENT)
4749 4750 4751 4752
          type= "LATERAL DERIVED";
        else
          type= "DERIVED";
      }
4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767
      else if (using_materialization)
        type= "MATERIALIZED";
      else
      {
         if (is_uncacheable & UNCACHEABLE_DEPENDENT)
           type= "DEPENDENT SUBQUERY";
         else
         {
           type= is_uncacheable? "UNCACHEABLE SUBQUERY" :
                                 "SUBQUERY";
         }
      }
    }
    else
    {
4768
      switch (linkage)
4769
      {
4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782
      case INTERSECT_TYPE:
        type= "INTERSECT";
        break;
      case EXCEPT_TYPE:
        type= "EXCEPT";
        break;
      default:
        /* This a non-first sibling in UNION */
        if (is_uncacheable & UNCACHEABLE_DEPENDENT)
          type= "DEPENDENT UNION";
        else if (using_materialization)
          type= "MATERIALIZED UNION";
        else
4783
        {
4784 4785 4786 4787 4788 4789 4790 4791 4792
          type= is_uncacheable ? "UNCACHEABLE UNION": "UNION";
          if (this == master_unit()->fake_select_lex)
            type= unit_operation_text[master_unit()->common_op()];
          /*
            join below may be =NULL when this functions is called at an early
            stage. It will be later called again and we will set the correct
            value.
          */
          if (join)
4793
          {
4794
            bool uses_cte= false;
4795 4796 4797 4798
            for (JOIN_TAB *tab= first_linear_tab(join, WITHOUT_BUSH_ROOTS,
                                                       WITH_CONST_TABLES);
                 tab;
                 tab= next_linear_tab(join, tab, WITHOUT_BUSH_ROOTS))
4799
            {
4800 4801 4802 4803
              /*
                pos_in_table_list=NULL for e.g. post-join aggregation JOIN_TABs.
              */
              if (tab->table && tab->table->pos_in_table_list &&
4804 4805
                  tab->table->pos_in_table_list->with &&
                  tab->table->pos_in_table_list->with->is_recursive)
4806 4807 4808 4809
              {
                uses_cte= true;
                break;
              }
4810
            }
4811 4812
            if (uses_cte)
              type= "RECURSIVE UNION";
4813 4814
          }
        }
4815
        break;
4816 4817 4818
      }
    }
  }
4819 4820

  if (!on_the_fly)
4821
    options|= SELECT_DESCRIBE;
4822
}
4823 4824


4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835
/**
  @brief
  Increase estimated number of records for a derived table/view

  @param records  number of records to increase estimate by

  @details
  This function increases estimated number of records by the 'records'
  for the derived table to which this select belongs to.
*/

Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
4836
void SELECT_LEX::increase_derived_records(ha_rows records)
4837 4838 4839 4840
{
  SELECT_LEX_UNIT *unit= master_unit();
  DBUG_ASSERT(unit->derived);

Igor Babaev's avatar
Igor Babaev committed
4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853
  if (unit->with_element && unit->with_element->is_recursive)
  {
    st_select_lex *first_recursive= unit->with_element->first_recursive;
    st_select_lex *sl= unit->first_select();
    for ( ; sl != first_recursive; sl= sl->next_select())
    {
      if (sl == this)
        break;
    }
    if (sl == first_recursive)
      return; 
  }
  
4854
  select_result *result= unit->result;
4855 4856 4857 4858
  switch (linkage)
  {
  case INTERSECT_TYPE:
    // result of intersect can't be more then one of components
4859
    set_if_smaller(result->est_records, records);
4860 4861 4862 4863 4864
  case EXCEPT_TYPE:
    // in worse case none of record will be removed
    break;
  default:
    // usual UNION
4865
    result->est_records+= records;
4866 4867
    break;
  }
4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886
}


/**
  @brief
  Mark select's derived table as a const one.

  @param empty Whether select has an empty result set

  @details
  Mark derived table/view of this select as a constant one (to
  materialize it at the optimization phase) unless this select belongs to a
  union. Estimated number of rows is incremented if this select has non empty
  result set.
*/

void SELECT_LEX::mark_const_derived(bool empty)
{
  TABLE_LIST *derived= master_unit()->derived;
Igor Babaev's avatar
Igor Babaev committed
4887 4888
  /* join == NULL in  DELETE ... RETURNING */
  if (!(join && join->thd->lex->describe) && derived)
4889 4890 4891
  {
    if (!empty)
      increase_derived_records(1);
Igor Babaev's avatar
Igor Babaev committed
4892 4893
    if (!master_unit()->is_unit_op() && !derived->is_merged_derived() &&
        !(join && join->with_two_phase_optimization))
4894 4895 4896 4897
      derived->fill_me= TRUE;
  }
}

Igor Babaev's avatar
Igor Babaev committed
4898

4899 4900
bool st_select_lex::save_leaf_tables(THD *thd)
{
4901 4902
  Query_arena *arena, backup;
  arena= thd->activate_stmt_arena_if_needed(&backup);
4903 4904 4905 4906 4907

  List_iterator_fast<TABLE_LIST> li(leaf_tables);
  TABLE_LIST *table;
  while ((table= li++))
  {
4908
    if (leaf_tables_exec.push_back(table, thd->mem_root))
4909
      return 1;
4910 4911
    table->tablenr_exec= table->get_tablenr();
    table->map_exec= table->get_map();
Igor Babaev's avatar
Igor Babaev committed
4912 4913 4914
    if (join && (join->select_options & SELECT_DESCRIBE))
      table->maybe_null_exec= 0;
    else
4915
      table->maybe_null_exec= table->table?  table->table->maybe_null: 0;
4916 4917 4918 4919 4920 4921 4922
  }
  if (arena)
    thd->restore_active_arena(arena, &backup);

  return 0;
}

4923

4924
bool LEX::save_prep_leaf_tables()
Igor Babaev's avatar
Igor Babaev committed
4925 4926
{
  if (!thd->save_prep_leaf_list)
4927
    return FALSE;
Igor Babaev's avatar
Igor Babaev committed
4928 4929

  Query_arena *arena= thd->stmt_arena, backup;
4930
  arena= thd->activate_stmt_arena_if_needed(&backup);
4931
  //It is used for DETETE/UPDATE so top level has only one SELECT
4932 4933
  DBUG_ASSERT(first_select_lex()->next_select() == NULL);
  bool res= first_select_lex()->save_prep_leaf_tables(thd);
4934 4935 4936 4937 4938 4939

  if (arena)
    thd->restore_active_arena(arena, &backup);

  if (res)
    return TRUE;
Igor Babaev's avatar
Igor Babaev committed
4940

4941 4942 4943
  thd->save_prep_leaf_list= FALSE;
  return FALSE;
}
Igor Babaev's avatar
Igor Babaev committed
4944

4945 4946 4947

bool st_select_lex::save_prep_leaf_tables(THD *thd)
{
Igor Babaev's avatar
Igor Babaev committed
4948 4949
  List_iterator_fast<TABLE_LIST> li(leaf_tables);
  TABLE_LIST *table;
4950 4951 4952 4953 4954 4955 4956 4957 4958 4959

  /*
    Check that the SELECT_LEX was really prepared and so tables are setup.

    It can be subquery in SET clause of UPDATE which was not prepared yet, so
    its tables are not yet setup and ready for storing.
  */
  if (prep_leaf_list_state != READY)
    return FALSE;

Igor Babaev's avatar
Igor Babaev committed
4960 4961 4962
  while ((table= li++))
  {
    if (leaf_tables_prep.push_back(table))
4963 4964
      return TRUE;
  }
4965
  prep_leaf_list_state= SAVED;
4966 4967 4968 4969 4970 4971 4972
  for (SELECT_LEX_UNIT *u= first_inner_unit(); u; u= u->next_unit())
  {
    for (SELECT_LEX *sl= u->first_select(); sl; sl= sl->next_select())
    {
      if (sl->save_prep_leaf_tables(thd))
        return TRUE;
    }
Igor Babaev's avatar
Igor Babaev committed
4973 4974
  }

4975
  return FALSE;
Igor Babaev's avatar
Igor Babaev committed
4976 4977 4978
}


4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007
/*
  Return true if this select_lex has been converted into a semi-join nest
  within 'ancestor'.

  We need a loop to check this because there could be several nested
  subselects, like

    SELECT ... FROM grand_parent 
      WHERE expr1 IN (SELECT ... FROM parent 
                        WHERE expr2 IN ( SELECT ... FROM child)

  which were converted into:
  
    SELECT ... 
    FROM grand_parent SEMI_JOIN (parent JOIN child) 
    WHERE 
      expr1 AND expr2

  In this case, both parent and child selects were merged into the parent.
*/

bool st_select_lex::is_merged_child_of(st_select_lex *ancestor)
{
  bool all_merged= TRUE;
  for (SELECT_LEX *sl= this; sl && sl!=ancestor;
       sl=sl->outer_select())
  {
    Item *subs= sl->master_unit()->item;
    if (subs && subs->type() == Item::SUBSELECT_ITEM && 
unknown's avatar
unknown committed
5008 5009
        ((Item_subselect*)subs)->substype() == Item_subselect::IN_SUBS &&
        ((Item_in_subselect*)subs)->test_strategy(SUBS_SEMI_JOIN))
5010 5011 5012
    {
      continue;
    }
5013 5014 5015 5016 5017 5018

    if (sl->master_unit()->derived &&
      sl->master_unit()->derived->is_merged_derived())
    {
      continue;
    }
5019 5020 5021 5022 5023 5024
    all_merged= FALSE;
    break;
  }
  return all_merged;
}

5025 5026 5027 5028
/* 
  This is used by SHOW EXPLAIN. It assuses query plan has been already 
  collected into QPF structures and we only need to print it out.
*/
5029

Sergey Petrunya's avatar
Sergey Petrunya committed
5030
int LEX::print_explain(select_result_sink *output, uint8 explain_flags,
Sergei Petrunia's avatar
Sergei Petrunia committed
5031
                       bool is_analyze, bool *printed_anything)
5032
{
5033
  int res;
5034
  if (explain && explain->have_query_plan())
5035
  {
Sergei Petrunia's avatar
Sergei Petrunia committed
5036
    res= explain->print_explain(output, explain_flags, is_analyze);
5037
    *printed_anything= true;
5038 5039 5040
  }
  else
  {
5041 5042
    res= 0;
    *printed_anything= false;
5043
  }
5044
  return res;
5045 5046
}

5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063

/**
  Allocates and set arena for SET STATEMENT old values.

  @param backup          where to save backup of arena.

  @retval 1 Error
  @retval 0 OK
*/

bool LEX::set_arena_for_set_stmt(Query_arena *backup)
{
  DBUG_ENTER("LEX::set_arena_for_set_stmt");
  DBUG_ASSERT(arena_for_set_stmt== 0);
  if (!mem_root_for_set_stmt)
  {
    mem_root_for_set_stmt= new MEM_ROOT();
5064
    if (unlikely(!(mem_root_for_set_stmt)))
5065
      DBUG_RETURN(1);
5066 5067
    init_sql_alloc(mem_root_for_set_stmt, "set_stmt",
                   ALLOC_ROOT_SET, ALLOC_ROOT_SET, MYF(MY_THREAD_SPECIFIC));
5068
  }
5069 5070 5071
  if (unlikely(!(arena_for_set_stmt= new(mem_root_for_set_stmt)
                 Query_arena_memroot(mem_root_for_set_stmt,
                                     Query_arena::STMT_INITIALIZED))))
5072
    DBUG_RETURN(1);
5073 5074 5075
  DBUG_PRINT("info", ("mem_root: %p  arena: %p",
                      mem_root_for_set_stmt,
                      arena_for_set_stmt));
5076 5077 5078 5079 5080 5081 5082 5083 5084 5085
  thd->set_n_backup_active_arena(arena_for_set_stmt, backup);
  DBUG_RETURN(0);
}


void LEX::reset_arena_for_set_stmt(Query_arena *backup)
{
  DBUG_ENTER("LEX::reset_arena_for_set_stmt");
  DBUG_ASSERT(arena_for_set_stmt);
  thd->restore_active_arena(arena_for_set_stmt, backup);
5086 5087 5088
  DBUG_PRINT("info", ("mem_root: %p  arena: %p",
                      arena_for_set_stmt->mem_root,
                      arena_for_set_stmt));
5089 5090 5091 5092 5093 5094 5095 5096 5097
  DBUG_VOID_RETURN;
}


void LEX::free_arena_for_set_stmt()
{
  DBUG_ENTER("LEX::free_arena_for_set_stmt");
  if (!arena_for_set_stmt)
    return;
5098 5099 5100
  DBUG_PRINT("info", ("mem_root: %p  arena: %p",
                      arena_for_set_stmt->mem_root,
                      arena_for_set_stmt));
5101 5102 5103 5104 5105 5106 5107
  arena_for_set_stmt->free_items();
  delete(arena_for_set_stmt);
  free_root(mem_root_for_set_stmt, MYF(MY_KEEP_PREALLOC));
  arena_for_set_stmt= 0;
  DBUG_VOID_RETURN;
}

5108 5109 5110 5111 5112 5113 5114 5115
void LEX::restore_set_statement_var()
{
  DBUG_ENTER("LEX::restore_set_statement_var");
  if (!old_var_list.is_empty())
  {
    DBUG_PRINT("info", ("vars: %d", old_var_list.elements));
    sql_set_variables(thd, &old_var_list, false);
    old_var_list.empty();
5116
    free_arena_for_set_stmt();
5117
  }
5118
  DBUG_ASSERT(!is_arena_for_set_stmt());
5119 5120
  DBUG_VOID_RETURN;
}
5121

5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157
unit_common_op st_select_lex_unit::common_op()
{
  SELECT_LEX *first= first_select();
  bool first_op= TRUE;
  unit_common_op operation= OP_MIX; // if no op
  for (SELECT_LEX *sl= first; sl; sl= sl->next_select())
  {
    if (sl != first)
    {
      unit_common_op op;
      switch (sl->linkage)
      {
      case INTERSECT_TYPE:
        op= OP_INTERSECT;
        break;
      case EXCEPT_TYPE:
        op= OP_EXCEPT;
        break;
      default:
        op= OP_UNION;
        break;
      }
      if (first_op)
      {
        operation= op;
        first_op= FALSE;
      }
      else
      {
        if (operation != op)
          operation= OP_MIX;
      }
    }
  }
  return operation;
}
5158
/*
5159 5160
  Save explain structures of a UNION. The only variable member is whether the 
  union has "Using filesort".
Sergey Petrunya's avatar
Sergey Petrunya committed
5161

5162
  There is also save_union_explain_part2() function, which is called before we read
Sergey Petrunya's avatar
Sergey Petrunya committed
5163
  UNION's output.
Sergey Petrunya's avatar
Sergey Petrunya committed
5164

Sergey Petrunya's avatar
Sergey Petrunya committed
5165
  The reason for it is examples like this:
Sergey Petrunya's avatar
Sergey Petrunya committed
5166

Sergey Petrunya's avatar
Sergey Petrunya committed
5167 5168 5169 5170 5171 5172
     SELECT col1 FROM t1 UNION SELECT col2 FROM t2 ORDER BY (select ... from t3 ...)

  Here, the (select ... from t3 ...) subquery must be a child of UNION's
  st_select_lex. However, it is not connected as child until a very late 
  stage in execution.
*/
Sergey Petrunya's avatar
Sergey Petrunya committed
5173

5174
int st_select_lex_unit::save_union_explain(Explain_query *output)
5175 5176
{
  SELECT_LEX *first= first_select();
5177 5178 5179 5180

  if (output->get_union(first->select_number))
    return 0; /* Already added */
    
5181 5182 5183
  Explain_union *eu= 
    new (output->mem_root) Explain_union(output->mem_root, 
                                         thd->lex->analyze_stmt);
5184 5185
  if (unlikely(!eu))
    return 0;
5186

5187 5188 5189
  if (with_element && with_element->is_recursive)
    eu->is_recursive_cte= true;
 
5190
  if (derived)
5191 5192 5193 5194 5195
    eu->connection_type= Explain_node::EXPLAIN_NODE_DERIVED;
  /* 
    Note: Non-merged semi-joins cannot be made out of UNIONs currently, so we
    dont ever set EXPLAIN_NODE_NON_MERGED_SJ.
  */
5196
  for (SELECT_LEX *sl= first; sl; sl= sl->next_select())
5197
    eu->add_select(sl->select_number);
5198

5199
  eu->fake_select_type= unit_operation_text[eu->operation= common_op()];
5200 5201
  eu->using_filesort= MY_TEST(global_parameters()->order_list.first);
  eu->using_tmp= union_needs_tmp_table();
5202

Sergey Petrunya's avatar
Sergey Petrunya committed
5203
  // Save the UNION node
5204
  output->add_node(eu);
5205

5206 5207
  if (eu->get_select_id() == 1)
    output->query_plan_ready();
5208

5209 5210 5211 5212
  return 0;
}


5213 5214 5215 5216 5217
/*
  @see  st_select_lex_unit::save_union_explain
*/

int st_select_lex_unit::save_union_explain_part2(Explain_query *output)
5218
{
5219
  Explain_union *eu= output->get_union(first_select()->select_number);
5220
  if (fake_select_lex)
5221
  {
5222 5223 5224 5225 5226
    for (SELECT_LEX_UNIT *unit= fake_select_lex->first_inner_unit(); 
         unit; unit= unit->next_unit())
    {
      if (!(unit->item && unit->item->eliminated))
      {
5227
        eu->add_child(unit->first_select()->select_number);
5228 5229
      }
    }
5230
    fake_select_lex->join->explain= &eu->fake_select_lex_explain;
5231
  }
Sergey Petrunya's avatar
Sergey Petrunya committed
5232
  return 0;
5233 5234 5235
}


5236 5237 5238 5239 5240
/**
  A routine used by the parser to decide whether we are specifying a full
  partitioning or if only partitions to add or to split.

  @note  This needs to be outside of WITH_PARTITION_STORAGE_ENGINE since it
unknown's avatar
unknown committed
5241
  is used from the sql parser that doesn't have any ifdef's
5242 5243 5244 5245 5246

  @retval  TRUE    Yes, it is part of a management partition command
  @retval  FALSE          No, not a management partition command
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
5247
bool LEX::is_partition_management() const
5248 5249
{
  return (sql_command == SQLCOM_ALTER_TABLE &&
5250 5251
          (alter_info.partition_flags ==  ALTER_PARTITION_ADD ||
           alter_info.partition_flags ==  ALTER_PARTITION_REORGANIZE));
5252 5253
}

5254 5255 5256 5257 5258 5259 5260 5261 5262 5263

/**
  Exclude last added SELECT_LEX (current) in the UNIT and return pointer in it
  (previous become currect)

  @return detached SELECT_LEX or NULL in case of error
*/

SELECT_LEX *LEX::exclude_last_select()
{
5264 5265 5266 5267 5268 5269 5270
  return exclude_not_first_select(current_select);
}

SELECT_LEX *LEX::exclude_not_first_select(SELECT_LEX *exclude)
{
  DBUG_ENTER("LEX::exclude_not_first_select");
  DBUG_PRINT("enter", ("exclude %p #%u", exclude, exclude->select_number));
5271 5272 5273 5274 5275 5276 5277 5278 5279 5280
  SELECT_LEX_UNIT *unit= exclude->master_unit();
  SELECT_LEX *sl;
  DBUG_ASSERT(unit->first_select() != exclude);
  /* we should go through the list to correctly set current_select */
  for(sl= unit->first_select();
      sl->next_select() && sl->next_select() != exclude;
      sl= sl->next_select());
  DBUG_PRINT("info", ("excl: %p  unit: %p  prev: %p", exclude, unit, sl));
  if (!sl)
    DBUG_RETURN(NULL);
5281 5282 5283 5284
  DBUG_ASSERT(&sl->next == exclude->prev);

  exclude->prev= NULL;

5285 5286 5287 5288 5289
  current_select= sl;
  DBUG_RETURN(exclude);
}


5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337
SELECT_LEX_UNIT *LEX::alloc_unit()
{
  SELECT_LEX_UNIT *unit;
  DBUG_ENTER("LEX::alloc_unit");
  if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
    DBUG_RETURN(NULL);

  unit->init_query();
  /* TODO: reentrant problem */
  unit->thd= thd;
  unit->link_next= 0;
  unit->link_prev= 0;
  /* TODO: remove return_to */
  unit->return_to= NULL;
  DBUG_RETURN(unit);
}


SELECT_LEX *LEX::alloc_select(bool select)
{
  SELECT_LEX *select_lex;
  DBUG_ENTER("LEX::alloc_select");
  if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
    DBUG_RETURN(NULL);
  DBUG_PRINT("info", ("Allocate select: %p #%u  statement lex: %p",
                      select_lex, thd->lex->stmt_lex->current_select_number,
                      thd->lex->stmt_lex));
  /*
    TODO: move following init to constructor when we get rid of builtin
    select
  */
  select_lex->select_number= ++thd->lex->stmt_lex->current_select_number;
  select_lex->parent_lex= this; /* Used in init_query. */
  select_lex->init_query();
  if (select)
    select_lex->init_select();
  select_lex->nest_level_base= &this->unit;
  select_lex->include_global((st_select_lex_node**)&all_selects_list);
  select_lex->context.resolve_in_select_list= TRUE;
  DBUG_RETURN(select_lex);
}

SELECT_LEX_UNIT *
LEX::create_unit(SELECT_LEX *first_sel)
{
  SELECT_LEX_UNIT *unit;
  DBUG_ENTER("LEX::create_unit");

5338 5339 5340
  if (first_sel->master_unit())
    DBUG_RETURN(first_sel->master_unit());

5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353
  if (!(unit= alloc_unit()))
    DBUG_RETURN(NULL);

  unit->register_select_chain(first_sel);
  if (first_sel->next_select())
  {
    unit->reset_distinct();
    DBUG_ASSERT(!unit->fake_select_lex);
    if (unit->add_fake_select_lex(thd))
      DBUG_RETURN(NULL);
  }
  DBUG_RETURN(unit);
}
5354

5355 5356 5357 5358 5359 5360
SELECT_LEX_UNIT *
SELECT_LEX::attach_selects_chain(SELECT_LEX *first_sel,
                                 Name_resolution_context *context)
{
  SELECT_LEX_UNIT *unit;
  DBUG_ENTER("SELECT_LEX::attach_select_chain");
5361

5362 5363
  if (!(unit= parent_lex->alloc_unit()))
    DBUG_RETURN(NULL);
5364

5365 5366 5367 5368 5369 5370 5371 5372 5373
  unit->register_select_chain(first_sel);
  register_unit(unit, context);
  if (first_sel->next_select())
  {
    unit->reset_distinct();
    DBUG_ASSERT(!unit->fake_select_lex);
    if (unit->add_fake_select_lex(parent_lex->thd))
      DBUG_RETURN(NULL);
  }
5374

5375 5376
  DBUG_RETURN(unit);
}
5377

5378 5379
SELECT_LEX *
LEX::wrap_unit_into_derived(SELECT_LEX_UNIT *unit)
5380
{
5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391
  SELECT_LEX *wrapping_sel;
  Table_ident *ti;
  DBUG_ENTER("LEX::wrap_unit_into_derived");

  if (!(wrapping_sel= alloc_select(TRUE)))
    DBUG_RETURN(NULL);
  Name_resolution_context *context= &wrapping_sel->context;
  context->init();
  wrapping_sel->automatic_brackets= FALSE;

  wrapping_sel->register_unit(unit, context);
5392 5393

  /* stuff dummy SELECT * FROM (...) */
5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448

  if (push_select(wrapping_sel)) // for Items & TABLE_LIST
    DBUG_RETURN(NULL);

  /* add SELECT list*/
  {
    Item *item= new (thd->mem_root)
      Item_field(thd, context, NULL, NULL, &star_clex_str);
    if (item == NULL)
      goto err;
    if (add_item_to_list(thd, item))
      goto err;
    (wrapping_sel->with_wild)++;
  }

  unit->first_select()->set_linkage(DERIVED_TABLE_TYPE);

  ti= new (thd->mem_root) Table_ident(unit);
  if (ti == NULL)
    goto err;
  {
    TABLE_LIST *table_list;
    LEX_CSTRING alias;
    if (wrapping_sel->make_unique_derived_name(thd, &alias))
      goto err;

    if (!(table_list= wrapping_sel->add_table_to_list(thd, ti, &alias,
                                                      0, TL_READ,
                                                      MDL_SHARED_READ)))
      goto err;

    context->resolve_in_table_list_only(table_list);
    wrapping_sel->add_joined_table(table_list);
  }

  pop_select();

  derived_tables|= DERIVED_SUBQUERY;

  DBUG_RETURN(wrapping_sel);

err:
  pop_select();
  DBUG_RETURN(NULL);
}

SELECT_LEX *LEX::wrap_select_chain_into_derived(SELECT_LEX *sel)
{
  SELECT_LEX *dummy_select;
  SELECT_LEX_UNIT *unit;
  Table_ident *ti;
  DBUG_ENTER("LEX::wrap_select_chain_into_derived");

  if (!(dummy_select= alloc_select(TRUE)))
     DBUG_RETURN(NULL);
5449
  Name_resolution_context *context= &dummy_select->context;
5450
  dummy_select->automatic_brackets= FALSE;
5451
  sel->distinct= TRUE; // First select has not this attribute (safety)
5452 5453 5454 5455 5456 5457 5458 5459

  if (!(unit= dummy_select->attach_selects_chain(sel, context)))
    DBUG_RETURN(NULL);

  /* stuff dummy SELECT * FROM (...) */

  if (push_select(dummy_select)) // for Items & TABLE_LIST
    DBUG_RETURN(NULL);
5460 5461

  /* add SELECT list*/
5462 5463 5464 5465 5466 5467 5468 5469 5470
  {
    Item *item= new (thd->mem_root)
      Item_field(thd, context, NULL, NULL, &star_clex_str);
    if (item == NULL)
      goto err;
    if (add_item_to_list(thd, item))
      goto err;
    (dummy_select->with_wild)++;
  }
5471

5472
  sel->set_linkage(DERIVED_TABLE_TYPE);
5473

5474 5475 5476 5477 5478 5479 5480 5481
  ti= new (thd->mem_root) Table_ident(unit);
  if (ti == NULL)
    goto err;
  {
    TABLE_LIST *table_list;
    LEX_CSTRING alias;
    if (dummy_select->make_unique_derived_name(thd, &alias))
      goto err;
5482

5483 5484 5485 5486
    if (!(table_list= dummy_select->add_table_to_list(thd, ti, &alias,
                                                      0, TL_READ,
                                                      MDL_SHARED_READ)))
      goto err;
5487

5488 5489 5490 5491 5492
    context->resolve_in_table_list_only(table_list);
    dummy_select->add_joined_table(table_list);
  }

  pop_select();
5493 5494 5495

  derived_tables|= DERIVED_SUBQUERY;

5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533
  DBUG_RETURN(dummy_select);

err:
  pop_select();
  DBUG_RETURN(NULL);
}

bool LEX::push_context(Name_resolution_context *context)
{
  DBUG_ENTER("LEX::push_context");
  DBUG_PRINT("info", ("Context: %p Select: %p (%d)",
                       context, context->select_lex,
                       (context->select_lex ?
                        context->select_lex->select_number:
                        0)));
  bool res= context_stack.push_front(context, thd->mem_root);
  DBUG_RETURN(res);
}


SELECT_LEX *LEX::create_priority_nest(SELECT_LEX *first_in_nest)
{
  DBUG_ENTER("LEX::create_priority_nest");
  DBUG_ASSERT(first_in_nest->first_nested);
  enum sub_select_type wr_unit_type= first_in_nest->get_linkage();
  bool wr_distinct= first_in_nest->distinct;
  SELECT_LEX *attach_to= first_in_nest->first_nested;
  attach_to->cut_next();
  SELECT_LEX *wrapper= wrap_select_chain_into_derived(first_in_nest);
  if (wrapper)
  {
    first_in_nest->first_nested= NULL;
    wrapper->set_linkage_and_distinct(wr_unit_type, wr_distinct);
    wrapper->first_nested= attach_to->first_nested;
    wrapper->set_master_unit(attach_to->master_unit());
    attach_to->link_neighbour(wrapper);
  }
  DBUG_RETURN(wrapper);
5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547
}


/**
  Checks if we need finish "automatic brackets" mode

  INTERSECT has higher priority then UNION and EXCEPT, so when it is need we
  automatically create lower layer for INTERSECT (automatic brackets) and
  here we check if we should return back one level up during parsing procedure.
*/

void LEX::check_automatic_up(enum sub_select_type type)
{
  if (type != INTERSECT_TYPE &&
5548
      current_select->get_linkage() == INTERSECT_TYPE &&
5549 5550 5551 5552 5553 5554 5555 5556
      current_select->outer_select() &&
      current_select->outer_select()->automatic_brackets)
  {
    nest_level--;
    current_select= current_select->outer_select();
  }
}

5557

5558
sp_variable *LEX::sp_param_init(LEX_CSTRING *name)
5559 5560 5561
{
  if (spcont->find_variable(name, true))
  {
5562
    my_error(ER_SP_DUP_PARAM, MYF(0), name->str);
5563 5564 5565
    return NULL;
  }
  sp_variable *spvar= spcont->add_variable(thd, name);
5566
  init_last_field(&spvar->field_def, name,
5567 5568 5569 5570 5571 5572 5573
                  thd->variables.collation_database);
  return spvar;
}


bool LEX::sp_param_fill_definition(sp_variable *spvar)
{
5574
  return sphead->fill_spvar_definition(thd, last_field, &spvar->name);
5575 5576 5577
}


5578 5579 5580 5581 5582 5583 5584 5585 5586
void LEX::set_stmt_init()
{
  sql_command= SQLCOM_SET_OPTION;
  mysql_init_select(this);
  option_type= OPT_SESSION;
  autocommit= 0;
};


5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622
/**
  Find a local or a package body variable by name.
  @param IN  name    - the variable name
  @param OUT ctx     - NULL, if the variable was not found,
                       or LEX::spcont (if a local variable was found)
                       or the package top level context
                       (if a package variable was found)
  @param OUT handler - NULL, if the variable was not found,
                       or a pointer to rcontext handler
  @retval            - the variable (if found), or NULL otherwise.
*/
sp_variable *
LEX::find_variable(const LEX_CSTRING *name,
                   sp_pcontext **ctx,
                   const Sp_rcontext_handler **rh) const
{
  sp_variable *spv;
  if (spcont && (spv= spcont->find_variable(name, false)))
  {
    *ctx= spcont;
    *rh= &sp_rcontext_handler_local;
    return spv;
  }
  sp_package *pkg= sphead ? sphead->m_parent : NULL;
  if (pkg && (spv= pkg->find_package_variable(name)))
  {
    *ctx= pkg->get_parse_context()->child_context(0);
    *rh= &sp_rcontext_handler_package_body;
    return spv;
  }
  *ctx= NULL;
  *rh= NULL;
  return NULL;
}


5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637
static bool is_new(const char *str)
{
  return (str[0] == 'n' || str[0] == 'N') &&
         (str[1] == 'e' || str[1] == 'E') &&
         (str[2] == 'w' || str[2] == 'W');
}

static bool is_old(const char *str)
{
  return (str[0] == 'o' || str[0] == 'O') &&
         (str[1] == 'l' || str[1] == 'L') &&
         (str[2] == 'd' || str[2] == 'D');
}


5638
bool LEX::is_trigger_new_or_old_reference(const LEX_CSTRING *name) const
5639
{
5640
  // "name" is not necessarily NULL-terminated!
5641
  return sphead && sphead->m_handler->type() == TYPE_ENUM_TRIGGER &&
5642
         name->length == 3 && (is_new(name->str) || is_old(name->str));
5643 5644 5645
}


5646 5647
void LEX::sp_variable_declarations_init(THD *thd, int nvars)
{
5648
  sp_variable *spvar= spcont->get_last_context_variable();
5649 5650 5651

  sphead->reset_lex(thd);
  spcont->declare_var_boundary(nvars);
5652
  thd->lex->init_last_field(&spvar->field_def, &spvar->name,
5653 5654 5655
                            thd->variables.collation_database);
}

5656 5657 5658 5659 5660

bool LEX::sp_variable_declarations_set_default(THD *thd, int nvars,
                                               Item *dflt_value_item)
{
  if (!dflt_value_item &&
5661
      unlikely(!(dflt_value_item= new (thd->mem_root) Item_null(thd))))
5662 5663 5664 5665 5666 5667 5668 5669 5670 5671
    return true;

  for (uint i= 0 ; i < (uint) nvars ; i++)
  {
    sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
    bool last= i + 1 == (uint) nvars;
    spvar->default_value= dflt_value_item;
    /* The last instruction is responsible for freeing LEX. */
    sp_instr_set *is= new (this->thd->mem_root)
                      sp_instr_set(sphead->instructions(),
5672 5673
                                   spcont, &sp_rcontext_handler_local,
                                   spvar->offset, dflt_value_item,
5674
                                   this, last);
5675
    if (unlikely(is == NULL || sphead->add_instr(is)))
5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691
      return true;
  }
  return false;
}


bool
LEX::sp_variable_declarations_copy_type_finalize(THD *thd, int nvars,
                                                 const Column_definition &ref,
                                                 Row_definition_list *fields,
                                                 Item *default_value)
{
  for (uint i= 0 ; i < (uint) nvars; i++)
  {
    sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
    spvar->field_def.set_type(ref);
5692 5693 5694 5695 5696
    if (fields)
    {
      DBUG_ASSERT(ref.type_handler() == &type_handler_row);
      spvar->field_def.set_row_field_definitions(fields);
    }
5697 5698
    spvar->field_def.field_name= spvar->name;
  }
5699 5700
  if (unlikely(sp_variable_declarations_set_default(thd, nvars,
                                                    default_value)))
5701 5702 5703 5704 5705 5706
    return true;
  spcont->declare_var_boundary(0);
  return sphead->restore_lex(thd);
}


5707
bool LEX::sp_variable_declarations_finalize(THD *thd, int nvars,
5708
                                            const Column_definition *cdef,
5709 5710
                                            Item *dflt_value_item)
{
5711 5712 5713
  DBUG_ASSERT(cdef);
  Column_definition tmp(*cdef);
  if (sphead->fill_spvar_definition(thd, &tmp))
5714
    return true;
5715 5716 5717 5718
  return sp_variable_declarations_copy_type_finalize(thd, nvars, tmp, NULL,
                                                     dflt_value_item);
}

5719

5720 5721 5722 5723 5724
bool LEX::sp_variable_declarations_row_finalize(THD *thd, int nvars,
                                                Row_definition_list *row,
                                                Item *dflt_value_item)
{
  DBUG_ASSERT(row);
5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736
  /*
    Prepare all row fields.
    Note, we do it only one time outside of the below loop.
    The converted list in "row" is further reused by all variable
    declarations processed by the current call.
    Example:
      DECLARE
        a, b, c ROW(x VARCHAR(10) CHARACTER SET utf8);
      BEGIN
        ...
      END;
  */
5737
  if (sphead->row_fill_field_definitions(thd, row))
5738
    return true;
5739

5740
  for (uint i= 0 ; i < (uint) nvars ; i++)
5741
  {
5742
    sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5743
    spvar->field_def.set_row_field_definitions(row);
5744
    if (sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name))
5745 5746 5747
      return true;
  }

5748 5749
  if (sp_variable_declarations_set_default(thd, nvars, dflt_value_item))
    return true;
5750 5751 5752 5753 5754
  spcont->declare_var_boundary(0);
  return sphead->restore_lex(thd);
}


5755 5756 5757 5758 5759 5760 5761 5762 5763
/**
  Finalize a %ROWTYPE declaration, e.g.:
    DECLARE a,b,c,d t1%ROWTYPE := ROW(1,2,3);

  @param thd   - the current thd
  @param nvars - the number of variables in the declaration
  @param ref   - the table or cursor name (see comments below)
  @param def   - the default value, e.g., ROW(1,2,3), or NULL (no default).
*/
5764 5765 5766 5767 5768
bool
LEX::sp_variable_declarations_rowtype_finalize(THD *thd, int nvars,
                                               Qualified_column_ident *ref,
                                               Item *def)
{
5769 5770
  uint coffp;
  const sp_pcursor *pcursor= ref->table.str && ref->db.str ? NULL :
5771 5772
                             spcont->find_cursor(&ref->m_column, &coffp,
                                                 false);
5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792
  if (pcursor)
    return sp_variable_declarations_cursor_rowtype_finalize(thd, nvars,
                                                            coffp, def);
  /*
    When parsing a qualified identifier chain, the parser does not know yet
    if it's going to be a qualified column name (for %TYPE),
    or a qualified table name (for %ROWTYPE). So it collects the chain
    into Qualified_column_ident.
    Now we know that it was actually a qualified table name (%ROWTYPE).
    Create a new Table_ident from Qualified_column_ident,
    shifting fields as follows:
    - ref->m_column becomes table_ref->table
    - ref->table    becomes table_ref->db
  */
  return sp_variable_declarations_table_rowtype_finalize(thd, nvars,
                                                         ref->table,
                                                         ref->m_column,
                                                         def);
}

5793

5794 5795 5796 5797 5798 5799 5800
bool
LEX::sp_variable_declarations_table_rowtype_finalize(THD *thd, int nvars,
                                                     const LEX_CSTRING &db,
                                                     const LEX_CSTRING &table,
                                                     Item *def)
{
  Table_ident *table_ref;
5801 5802
  if (unlikely(!(table_ref=
                 new (thd->mem_root) Table_ident(thd, &db, &table, false))))
5803 5804 5805 5806 5807 5808 5809 5810 5811
    return true;
  // Loop through all variables in the same declaration
  for (uint i= 0 ; i < (uint) nvars; i++)
  {
    sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
    spvar->field_def.set_table_rowtype_ref(table_ref);
    sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
  }
  if (sp_variable_declarations_set_default(thd, nvars, def))
5812
    return true;
5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825
  // Make sure sp_rcontext is created using the invoker security context:
  sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
  spcont->declare_var_boundary(0);
  return sphead->restore_lex(thd);
}


bool
LEX::sp_variable_declarations_cursor_rowtype_finalize(THD *thd, int nvars,
                                                      uint offset,
                                                      Item *def)
{
  const sp_pcursor *pcursor= spcont->find_cursor(offset);
5826

5827
  // Loop through all variables in the same declaration
5828
  for (uint i= 0 ; i < (uint) nvars; i++)
5829
  {
5830
    sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5831

5832
    spvar->field_def.set_cursor_rowtype_ref(offset);
5833 5834
    sp_instr_cursor_copy_struct *instr=
      new (thd->mem_root) sp_instr_cursor_copy_struct(sphead->instructions(),
5835 5836
                                                      spcont, offset,
                                                      pcursor->lex(),
5837 5838 5839 5840
                                                      spvar->offset);
    if (instr == NULL || sphead->add_instr(instr))
     return true;

5841
    sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
5842
  }
5843
  if (unlikely(sp_variable_declarations_set_default(thd, nvars, def)))
5844
    return true;
5845 5846 5847 5848 5849 5850 5851
  // Make sure sp_rcontext is created using the invoker security context:
  sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
  spcont->declare_var_boundary(0);
  return sphead->restore_lex(thd);
}


5852 5853 5854 5855 5856 5857
/*
  Add declarations for table column and SP variable anchor types:
  - DECLARE spvar1 TYPE OF db1.table1.column1;
  - DECLARE spvar1 TYPE OF table1.column1;
  - DECLARE spvar1 TYPE OF spvar0;
*/
5858 5859 5860 5861
bool
LEX::sp_variable_declarations_with_ref_finalize(THD *thd, int nvars,
                                                Qualified_column_ident *ref,
                                                Item *def)
5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872
{
  return ref->db.length == 0 && ref->table.length == 0 ?
    sp_variable_declarations_vartype_finalize(thd, nvars, ref->m_column, def) :
    sp_variable_declarations_column_type_finalize(thd, nvars, ref, def);
}


bool
LEX::sp_variable_declarations_column_type_finalize(THD *thd, int nvars,
                                                   Qualified_column_ident *ref,
                                                   Item *def)
5873
{
5874
  for (uint i= 0 ; i < (uint) nvars; i++)
5875
  {
5876
    sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
5877
    spvar->field_def.set_column_type_ref(ref);
5878
    spvar->field_def.field_name= spvar->name;
5879 5880
  }
  sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929
  if (sp_variable_declarations_set_default(thd, nvars, def))
    return true;
  spcont->declare_var_boundary(0);
  return sphead->restore_lex(thd);
}


bool
LEX::sp_variable_declarations_vartype_finalize(THD *thd, int nvars,
                                               const LEX_CSTRING &ref,
                                               Item *default_value)
{
  sp_variable *t;
  if (!spcont || !(t= spcont->find_variable(&ref, false)))
  {
    my_error(ER_SP_UNDECLARED_VAR, MYF(0), ref.str);
    return true;
  }

  if (t->field_def.is_cursor_rowtype_ref())
  {
    uint offset= t->field_def.cursor_rowtype_offset();
    return sp_variable_declarations_cursor_rowtype_finalize(thd, nvars,
                                                            offset,
                                                            default_value);
  }

  if (t->field_def.is_column_type_ref())
  {
    Qualified_column_ident *tmp= t->field_def.column_type_ref();
    return sp_variable_declarations_column_type_finalize(thd, nvars, tmp,
                                                         default_value);
  }

  if (t->field_def.is_table_rowtype_ref())
  {
    const Table_ident *tmp= t->field_def.table_rowtype_ref();
    return sp_variable_declarations_table_rowtype_finalize(thd, nvars,
                                                           tmp->db,
                                                           tmp->table,
                                                           default_value);
  }

  // A reference to a scalar or a row variable with an explicit data type
  return sp_variable_declarations_copy_type_finalize(thd, nvars,
                                                     t->field_def,
                                                     t->field_def.
                                                       row_field_definitions(),
                                                     default_value);
5930 5931 5932
}


5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956
/**********************************************************************
  The FOR LOOP statement

  This syntax:
    FOR i IN lower_bound .. upper_bound
    LOOP
      statements;
    END LOOP;

  is translated into:

    DECLARE
      i INT := lower_bound;
      j INT := upper_bound;
    BEGIN
      WHILE i <= j
      LOOP
        statements;
        i:= i + 1;
      END LOOP;
    END;
*/


5957
sp_variable *LEX::sp_add_for_loop_variable(THD *thd, const LEX_CSTRING *name,
5958 5959 5960 5961
                                           Item *value)
{
  sp_variable *spvar= spcont->add_variable(thd, name);
  spcont->declare_var_boundary(1);
5962
  spvar->field_def.field_name= spvar->name;
5963
  spvar->field_def.set_handler(&type_handler_longlong);
5964 5965
  type_handler_longlong.Column_definition_prepare_stage2(&spvar->field_def,
                                                         NULL, HA_CAN_GEOMETRY);
5966
  if (!value && unlikely(!(value= new (thd->mem_root) Item_null(thd))))
5967 5968 5969 5970 5971
    return NULL;

  spvar->default_value= value;
  sp_instr_set *is= new (this->thd->mem_root)
                    sp_instr_set(sphead->instructions(),
5972 5973
                                 spcont, &sp_rcontext_handler_local,
                                 spvar->offset, value,
5974
                                 this, true);
5975
  if (unlikely(is == NULL || sphead->add_instr(is)))
5976
    return NULL;
5977 5978 5979 5980 5981
  spcont->declare_var_boundary(0);
  return spvar;
}


5982 5983 5984 5985 5986 5987 5988 5989 5990 5991
bool LEX::sp_for_loop_implicit_cursor_statement(THD *thd,
                                                Lex_for_loop_bounds_st *bounds,
                                                sp_lex_cursor *cur)
{
  Item *item;
  DBUG_ASSERT(sphead);
  LEX_CSTRING name= {STRING_WITH_LEN("[implicit_cursor]") };
  if (sp_declare_cursor(thd, &name, cur, NULL, true))
    return true;
  DBUG_ASSERT(thd->lex == this);
5992 5993
  if (unlikely(!(bounds->m_index=
                 new (thd->mem_root) sp_assignment_lex(thd, this))))
5994 5995 5996 5997
    return true;
  bounds->m_index->sp_lex_in_use= true;
  sphead->reset_lex(thd, bounds->m_index);
  DBUG_ASSERT(thd->lex != this);
5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008
  /*
    We pass NULL as Name_resolution_context here.
    It's OK, fix_fields() will not be called for this Item_field created.
    Item_field is only needed for LEX::sp_for_loop_cursor_declarations()
    and is used to transfer the loop index variable name, "rec" in this example:
      FOR rec IN (SELECT * FROM t1)
      DO
        SELECT rec.a, rec.b;
      END FOR;
  */
  if (!(item= new (thd->mem_root) Item_field(thd, NULL, NullS, NullS, &name)))
6009 6010 6011 6012 6013 6014
    return true;
  bounds->m_index->set_item_and_free_list(item, NULL);
  if (thd->lex->sphead->restore_lex(thd))
    return true;
  DBUG_ASSERT(thd->lex == this);
  bounds->m_direction= 1;
6015
  bounds->m_target_bound= NULL;
6016 6017 6018 6019
  bounds->m_implicit_cursor= true;
  return false;
}

6020 6021
sp_variable *
LEX::sp_add_for_loop_cursor_variable(THD *thd,
6022
                                     const LEX_CSTRING *name,
6023
                                     const sp_pcursor *pcursor,
6024 6025 6026
                                     uint coffset,
                                     sp_assignment_lex *param_lex,
                                     Item_args *parameters)
6027 6028
{
  sp_variable *spvar= spcont->add_variable(thd, name);
6029 6030
  if (!spvar)
    return NULL;
6031
  spcont->declare_var_boundary(1);
6032
  sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
6033
  if (unlikely(!(spvar->default_value= new (thd->mem_root) Item_null(thd))))
6034
    return NULL;
6035

6036
  spvar->field_def.set_cursor_rowtype_ref(coffset);
6037

6038 6039 6040
  if (unlikely(sphead->add_for_loop_open_cursor(thd, spcont, spvar, pcursor,
                                                coffset,
                                                param_lex, parameters)))
6041 6042 6043
    return NULL;

  spcont->declare_var_boundary(0);
6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058
  return spvar;
}


/**
  Generate a code for a FOR loop condition:
  - Make Item_splocal for the FOR loop index variable
  - Make Item_splocal for the FOR loop upper bound variable
  - Make a comparison function item on top of these two variables
*/
bool LEX::sp_for_loop_condition(THD *thd, const Lex_for_loop_st &loop)
{
  Item_splocal *args[2];
  for (uint i= 0 ; i < 2; i++)
  {
6059
    sp_variable *src= i == 0 ? loop.m_index : loop.m_target_bound;
6060
    args[i]= new (thd->mem_root)
6061 6062
              Item_splocal(thd, &sp_rcontext_handler_local,
                           &src->name, src->offset, src->type_handler());
6063
    if (unlikely(args[i] == NULL))
6064
      return true;
6065
#ifdef DBUG_ASSERT_EXISTS
6066 6067 6068 6069 6070 6071 6072
    args[i]->m_sp= sphead;
#endif
  }

  Item *expr= loop.m_direction > 0 ?
    (Item *) new (thd->mem_root) Item_func_le(thd, args[0], args[1]) :
    (Item *) new (thd->mem_root) Item_func_ge(thd, args[0], args[1]);
6073
  return unlikely(!expr) || unlikely(sp_while_loop_expression(thd, expr));
6074 6075 6076 6077 6078 6079
}


/**
  Generate the FOR LOOP condition code in its own lex
*/
6080 6081
bool LEX::sp_for_loop_intrange_condition_test(THD *thd,
                                              const Lex_for_loop_st &loop)
6082
{
6083
  spcont->set_for_loop(loop);
6084
  sphead->reset_lex(thd);
6085
  if (unlikely(thd->lex->sp_for_loop_condition(thd, loop)))
6086 6087 6088 6089 6090
    return true;
  return thd->lex->sphead->restore_lex(thd);
}


6091 6092 6093
bool LEX::sp_for_loop_cursor_condition_test(THD *thd,
                                            const Lex_for_loop_st &loop)
{
6094
  const LEX_CSTRING *cursor_name;
6095
  Item *expr;
6096 6097
  spcont->set_for_loop(loop);
  sphead->reset_lex(thd);
6098 6099
  cursor_name= spcont->find_cursor(loop.m_cursor_offset);
  DBUG_ASSERT(cursor_name);
6100 6101 6102 6103
  if (unlikely(!(expr=
                 new (thd->mem_root)
                 Item_func_cursor_found(thd, cursor_name,
                                        loop.m_cursor_offset))))
6104
    return true;
6105 6106 6107 6108 6109 6110 6111
  if (thd->lex->sp_while_loop_expression(thd, expr))
    return true;
  return thd->lex->sphead->restore_lex(thd);
}


bool LEX::sp_for_loop_intrange_declarations(THD *thd, Lex_for_loop_st *loop,
6112
                                            const LEX_CSTRING *index,
6113 6114
                                            const Lex_for_loop_bounds_st &bounds)
{
6115 6116 6117 6118 6119 6120 6121
  Item *item;
  if ((item= bounds.m_index->get_item())->type() == Item::FIELD_ITEM)
  {
    // We're here is the lower bound is unknown identifier
    my_error(ER_SP_UNDECLARED_VAR, MYF(0), item->full_name());
    return true;
  }
Marko Mäkelä's avatar
Marko Mäkelä committed
6122
  if ((item= bounds.m_target_bound->get_item())->type() == Item::FIELD_ITEM)
6123 6124 6125 6126 6127 6128 6129 6130
  {
    // We're here is the upper bound is unknown identifier
    my_error(ER_SP_UNDECLARED_VAR, MYF(0), item->full_name());
    return true;
  }
  if (!(loop->m_index=
        bounds.m_index->sp_add_for_loop_variable(thd, index,
                                                 bounds.m_index->get_item())))
6131
    return true;
6132 6133 6134 6135 6136
  if (unlikely(!(loop->m_target_bound=
                 bounds.m_target_bound->
                 sp_add_for_loop_target_bound(thd,
                                              bounds.
                                              m_target_bound->get_item()))))
6137 6138 6139 6140 6141 6142 6143 6144 6145
     return true;
  loop->m_direction= bounds.m_direction;
  loop->m_implicit_cursor= 0;
  return false;
}


bool LEX::sp_for_loop_cursor_declarations(THD *thd,
                                          Lex_for_loop_st *loop,
6146
                                          const LEX_CSTRING *index,
6147 6148 6149 6150 6151
                                          const Lex_for_loop_bounds_st &bounds)
{
  Item *item= bounds.m_index->get_item();
  Item_splocal *item_splocal;
  Item_field *item_field;
6152
  Item_func_sp *item_func_sp= NULL;
6153
  LEX_CSTRING name;
6154
  uint coffs, param_count= 0;
6155 6156 6157 6158 6159 6160 6161
  const sp_pcursor *pcursor;

  if ((item_splocal= item->get_item_splocal()))
    name= item_splocal->m_name;
  else if ((item_field= item->type() == Item::FIELD_ITEM ?
                        static_cast<Item_field *>(item) : NULL) &&
           item_field->table_name == NULL)
6162
    name= item_field->field_name;
6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183
  else if (item->type() == Item::FUNC_ITEM &&
           static_cast<Item_func*>(item)->functype() == Item_func::FUNC_SP &&
           !static_cast<Item_func_sp*>(item)->get_sp_name()->m_explicit_name)
  {
    /*
      When a FOR LOOP for a cursor with parameters is parsed:
        FOR index IN cursor(1,2,3) LOOP
          statements;
        END LOOP;
      the parser scans "cursor(1,2,3)" using the "expr" rule,
      so it thinks that cursor(1,2,3) is a stored function call.
      It's not easy to implement this without using "expr" because
      of grammar conflicts.
      As a side effect, the Item_func_sp and its arguments in the parentheses
      belong to the same LEX. This is different from an explicit
      "OPEN cursor(1,2,3)" where every expression belongs to a separate LEX.
    */
    item_func_sp= static_cast<Item_func_sp*>(item);
    name= item_func_sp->get_sp_name()->m_name;
    param_count= item_func_sp->argument_count();
  }
6184 6185 6186 6187 6188
  else
  {
    thd->parse_error();
    return true;
  }
6189 6190 6191
  if (unlikely(!(pcursor= spcont->find_cursor_with_error(&name, &coffs,
                                                         false)) ||
               pcursor->check_param_count_with_error(param_count)))
6192 6193 6194
    return true;

  if (!(loop->m_index= sp_add_for_loop_cursor_variable(thd, index,
6195 6196 6197
                                                       pcursor, coffs,
                                                       bounds.m_index,
                                                       item_func_sp)))
6198
    return true;
6199
  loop->m_target_bound= NULL;
6200 6201 6202 6203 6204 6205 6206
  loop->m_direction= bounds.m_direction;
  loop->m_cursor_offset= coffs;
  loop->m_implicit_cursor= bounds.m_implicit_cursor;
  return false;
}


6207 6208 6209 6210 6211 6212
/**
  Generate a code for a FOR loop index increment
*/
bool LEX::sp_for_loop_increment(THD *thd, const Lex_for_loop_st &loop)
{
  Item_splocal *splocal= new (thd->mem_root)
6213 6214
    Item_splocal(thd, &sp_rcontext_handler_local,
                      &loop.m_index->name, loop.m_index->offset,
6215
                      loop.m_index->type_handler());
6216
  if (unlikely(splocal == NULL))
6217
    return true;
6218
#ifdef DBUG_ASSERT_EXISTS
6219 6220 6221
  splocal->m_sp= sphead;
#endif
  Item_int *inc= new (thd->mem_root) Item_int(thd, loop.m_direction);
6222
  if (unlikely(!inc))
6223 6224
    return true;
  Item *expr= new (thd->mem_root) Item_func_plus(thd, splocal, inc);
6225 6226 6227 6228
  if (unlikely(!expr) ||
      unlikely(sphead->set_local_variable(thd, spcont,
                                          &sp_rcontext_handler_local,
                                          loop.m_index, expr, this, true)))
6229 6230 6231 6232 6233
    return true;
  return false;
}


6234
bool LEX::sp_for_loop_intrange_finalize(THD *thd, const Lex_for_loop_st &loop)
6235 6236 6237 6238 6239
{
  sphead->reset_lex(thd);

  // Generate FOR LOOP index increment in its own lex
  DBUG_ASSERT(this != thd->lex);
6240 6241
  if (unlikely(thd->lex->sp_for_loop_increment(thd, loop) ||
               thd->lex->sphead->restore_lex(thd)))
6242 6243 6244 6245 6246 6247 6248 6249
    return true;

  // Generate a jump to the beginning of the loop
  DBUG_ASSERT(this == thd->lex);
  return sp_while_loop_finalize(thd);
}


6250 6251 6252 6253
bool LEX::sp_for_loop_cursor_finalize(THD *thd, const Lex_for_loop_st &loop)
{
  sp_instr_cfetch *instr=
    new (thd->mem_root) sp_instr_cfetch(sphead->instructions(),
6254
                                        spcont, loop.m_cursor_offset, false);
6255
  if (unlikely(instr == NULL) || unlikely(sphead->add_instr(instr)))
6256 6257 6258 6259 6260 6261
    return true;
  instr->add_to_varlist(loop.m_index);
  // Generate a jump to the beginning of the loop
  return sp_while_loop_finalize(thd);
}

6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281
bool LEX::sp_for_loop_outer_block_finalize(THD *thd,
                                           const Lex_for_loop_st &loop)
{
  Lex_spblock tmp;
  tmp.curs= MY_TEST(loop.m_implicit_cursor);
  if (unlikely(sp_block_finalize(thd, tmp))) // The outer DECLARE..BEGIN..END
    return true;
  if (!loop.is_for_loop_explicit_cursor())
    return false;
  /*
    Explicit cursor FOR loop must close the cursor automatically.
    Note, implicit cursor FOR loop does not need to close the cursor,
    it's closed by sp_instr_cpop.
  */
  sp_instr_cclose *ic= new (thd->mem_root)
                       sp_instr_cclose(sphead->instructions(), spcont,
                                       loop.m_cursor_offset);
  return ic == NULL || sphead->add_instr(ic);
}

6282 6283
/***************************************************************************/

6284
bool LEX::sp_declare_cursor(THD *thd, const LEX_CSTRING *name,
6285
                            sp_lex_cursor *cursor_stmt,
6286
                            sp_pcontext *param_ctx, bool add_cpush_instr)
6287 6288 6289 6290 6291 6292
{
  uint offp;
  sp_instr_cpush *i;

  if (spcont->find_cursor(name, &offp, true))
  {
6293
    my_error(ER_SP_DUP_CURS, MYF(0), name->str);
6294 6295
    return true;
  }
6296

6297
  if (unlikely(spcont->add_cursor(name, param_ctx, cursor_stmt)))
6298 6299 6300 6301 6302 6303 6304
    return true;

  if (add_cpush_instr)
  {
    i= new (thd->mem_root)
         sp_instr_cpush(sphead->instructions(), spcont, cursor_stmt,
                        spcont->current_cursor_count() - 1);
6305
    return unlikely(i == NULL) || unlikely(sphead->add_instr(i));
6306 6307
  }
  return false;
6308 6309 6310 6311 6312 6313 6314 6315 6316 6317
}


/**
  Generate an SP code for an "OPEN cursor_name" statement.
  @param thd
  @param name       - Name of the cursor
  @param parameters - Cursor parameters, e.g. OPEN c(1,2,3)
  @returns          - false on success, true on error
*/
6318
bool LEX::sp_open_cursor(THD *thd, const LEX_CSTRING *name,
6319 6320 6321 6322
                         List<sp_assignment_lex> *parameters)
{
  uint offset;
  const sp_pcursor *pcursor;
6323 6324 6325 6326
  uint param_count= parameters ? parameters->elements : 0;
  return !(pcursor= spcont->find_cursor_with_error(name, &offset, false)) ||
         pcursor->check_param_count_with_error(param_count) ||
         sphead->add_open_cursor(thd, spcont, offset,
6327
                                 pcursor->param_context(), parameters);
6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339
}


bool LEX::sp_handler_declaration_init(THD *thd, int type)
{
  sp_handler *h= spcont->add_handler(thd, (sp_handler::enum_type) type);

  spcont= spcont->push_context(thd, sp_pcontext::HANDLER_SCOPE);

  sp_instr_hpush_jump *i=
    new (thd->mem_root) sp_instr_hpush_jump(sphead->instructions(), spcont, h);

6340
  if (unlikely(i == NULL) || unlikely(sphead->add_instr(i)))
6341 6342 6343 6344
    return true;

  /* For continue handlers, mark end of handler scope. */
  if (type == sp_handler::CONTINUE &&
6345
      unlikely(sphead->push_backpatch(thd, i, spcont->last_label())))
6346 6347
    return true;

6348 6349 6350
  if (unlikely(sphead->push_backpatch(thd, i,
                                      spcont->push_label(thd, &empty_clex_str,
                                                         0))))
6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364
    return true;

  return false;
}


bool LEX::sp_handler_declaration_finalize(THD *thd, int type)
{
  sp_label *hlab= spcont->pop_label(); /* After this hdlr */
  sp_instr_hreturn *i;

  if (type == sp_handler::CONTINUE)
  {
    i= new (thd->mem_root) sp_instr_hreturn(sphead->instructions(), spcont);
6365 6366
    if (unlikely(i == NULL) ||
        unlikely(sphead->add_instr(i)))
6367 6368 6369 6370 6371
      return true;
  }
  else
  {  /* EXIT or UNDO handler, just jump to the end of the block */
    i= new (thd->mem_root) sp_instr_hreturn(sphead->instructions(), spcont);
6372 6373 6374
    if (unlikely(i == NULL) ||
        unlikely(sphead->add_instr(i)) ||
        unlikely(sphead->push_backpatch(thd, i, spcont->last_label()))) /* Block end */
6375 6376 6377 6378 6379 6380
      return true;
  }
  sphead->backpatch(hlab);
  spcont= spcont->pop_context();
  return false;
}
6381

6382

6383
void LEX::sp_block_init(THD *thd, const LEX_CSTRING *label)
6384
{
6385
  spcont->push_label(thd, label, sphead->instructions(), sp_label::BEGIN);
6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401
  spcont= spcont->push_context(thd, sp_pcontext::REGULAR_SCOPE);
}


bool LEX::sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
                                      class sp_label **splabel)
{
  sp_head *sp= sphead;
  sp_pcontext *ctx= spcont;
  sp_instr *i;

  sp->backpatch(ctx->last_label()); /* We always have a label */
  if (spblock.hndlrs)
  {
    i= new (thd->mem_root)
      sp_instr_hpop(sp->instructions(), ctx, spblock.hndlrs);
6402 6403
    if (unlikely(i == NULL) ||
        unlikely(sp->add_instr(i)))
6404 6405 6406 6407 6408 6409
      return true;
  }
  if (spblock.curs)
  {
    i= new (thd->mem_root)
      sp_instr_cpop(sp->instructions(), ctx, spblock.curs);
6410 6411
    if (unlikely(i == NULL) ||
        unlikely(sp->add_instr(i)))
6412 6413 6414 6415 6416 6417 6418 6419 6420
      return true;
  }
  spcont= ctx->pop_context();
  *splabel= spcont->pop_label();
  return false;
}


bool LEX::sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
6421
                            const LEX_CSTRING *end_label)
6422 6423
{
  sp_label *splabel;
6424
  if (unlikely(sp_block_finalize(thd, spblock, &splabel)))
6425
    return true;
6426 6427 6428
  if (unlikely(end_label->str &&
               lex_string_cmp(system_charset_info,
                              end_label, &splabel->name) != 0))
6429
  {
6430
    my_error(ER_SP_LABEL_MISMATCH, MYF(0), end_label->str);
6431 6432 6433 6434 6435 6436
    return true;
  }
  return false;
}


6437
sp_name *LEX::make_sp_name(THD *thd, const LEX_CSTRING *name)
6438 6439
{
  sp_name *res;
6440
  LEX_CSTRING db;
6441 6442 6443
  if (unlikely(check_routine_name(name)) ||
      unlikely(copy_db_to(&db)) ||
      unlikely((!(res= new (thd->mem_root) sp_name(&db, name, false)))))
6444 6445 6446 6447 6448
    return NULL;
  return res;
}


6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464
/**
  When a package routine name is stored in memory in Database_qualified_name,
  the dot character is used to delimit package name from the routine name,
  e.g.:
    m_db=   'test';   -- database 'test'
    m_name= 'p1.p1';  -- package 'p1', routine 'p1'
  See database_qualified_name::make_package_routine_name() for details.
  Disallow package routine names with dots,
  to avoid ambiguity when interpreting m_name='p1.p1.p1', between:
    a.  package 'p1.p1' + routine 'p1'
    b.  package 'p1'    + routine 'p1.p1'
  m_name='p1.p1.p1' will always mean (a).
*/
sp_name *LEX::make_sp_name_package_routine(THD *thd, const LEX_CSTRING *name)
{
  sp_name *res= make_sp_name(thd, name);
6465
  if (likely(res) && unlikely(strchr(res->m_name.str, '.')))
6466 6467 6468 6469 6470 6471 6472 6473
  {
    my_error(ER_SP_WRONG_NAME, MYF(0), res->m_name.str);
    res= NULL;
  }
  return res;
}


6474 6475
sp_name *LEX::make_sp_name(THD *thd, const LEX_CSTRING *name1,
                                     const LEX_CSTRING *name2)
6476 6477
{
  sp_name *res;
6478
  LEX_CSTRING norm_name1;
6479 6480 6481 6482
  if (unlikely(!name1->str) ||
      unlikely(!thd->make_lex_string(&norm_name1, name1->str,
                                     name1->length)) ||
      unlikely(check_db_name((LEX_STRING *) &norm_name1)))
6483
  {
6484
    my_error(ER_WRONG_DB_NAME, MYF(0), name1->str);
6485 6486
    return NULL;
  }
6487 6488
  if (unlikely(check_routine_name(name2)) ||
      unlikely(!(res= new (thd->mem_root) sp_name(&norm_name1, name2, true))))
6489 6490 6491 6492 6493
    return NULL;
  return res;
}


6494
sp_head *LEX::make_sp_head(THD *thd, const sp_name *name,
6495 6496
                           const Sp_handler *sph,
                           enum_sp_aggregate_type agg_type)
6497
{
6498
  sp_package *package= get_sp_package();
6499 6500 6501
  sp_head *sp;

  /* Order is important here: new - reset - init */
6502
  if (likely((sp= new sp_head(package, sph, agg_type))))
6503 6504 6505 6506
  {
    sp->reset_thd_mem_root(thd);
    sp->init(this);
    if (name)
6507 6508 6509 6510 6511 6512 6513 6514 6515 6516
    {
      if (package)
        sp->make_package_routine_name(sp->get_main_mem_root(),
                                      package->m_db,
                                      package->m_name,
                                      name->m_name);
      else
        sp->init_sp_name(name);
      sp->make_qname(sp->get_main_mem_root(), &sp->m_qname);
    }
6517 6518
    sphead= sp;
  }
6519
  sp_chistics.init();
6520 6521 6522 6523
  return sp;
}


6524
sp_head *LEX::make_sp_head_no_recursive(THD *thd, const sp_name *name,
6525 6526
                                        const Sp_handler *sph,
                                        enum_sp_aggregate_type agg_type)
6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543
{
  sp_package *package= thd->lex->get_sp_package();
  /*
    Sp_handler::sp_clone_and_link_routine() generates a standalone-alike
    statement to clone package routines for recursion, e.g.:
      CREATE PROCEDURE p1 AS BEGIN NULL; END;
    Translate a standalone routine handler to the corresponding
    package routine handler if we're cloning a package routine, e.g.:
      sp_handler_procedure -> sp_handler_package_procedure
      sp_handler_function  -> sp_handler_package_function
  */
  if (package && package->m_is_cloning_routine)
    sph= sph->package_routine_handler();
  if (!sphead ||
      (package &&
       (sph == &sp_handler_package_procedure ||
        sph == &sp_handler_package_function)))
6544
    return make_sp_head(thd, name, sph, agg_type);
6545 6546 6547 6548 6549
  my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), sph->type_str());
  return NULL;
}


6550
bool LEX::sp_body_finalize_routine(THD *thd)
6551 6552 6553 6554 6555 6556 6557 6558 6559
{
  if (sphead->check_unresolved_goto())
    return true;
  sphead->set_stmt_end(thd);
  sphead->restore_thd_mem_root(thd);
  return false;
}


6560 6561 6562 6563 6564 6565 6566
bool LEX::sp_body_finalize_procedure(THD *thd)
{
  return sphead->check_group_aggregate_instructions_forbid() ||
         sp_body_finalize_routine(thd);
}


6567 6568 6569 6570 6571 6572 6573 6574
bool LEX::sp_body_finalize_procedure_standalone(THD *thd,
                                                const sp_name *end_name)
{
  return sp_body_finalize_procedure(thd) ||
         sphead->check_standalone_routine_end_name(end_name);
}


6575 6576
bool LEX::sp_body_finalize_function(THD *thd)
{
6577 6578
  if (sphead->is_not_allowed_in_function("function") ||
      sphead->check_group_aggregate_instructions_function())
6579 6580 6581 6582 6583 6584
    return true;
  if (!(sphead->m_flags & sp_head::HAS_RETURN))
  {
    my_error(ER_SP_NORETURN, MYF(0), ErrConvDQName(sphead).ptr());
    return true;
  }
6585
  if (sp_body_finalize_routine(thd))
6586 6587 6588 6589 6590 6591
    return true;
  (void) is_native_function_with_warn(thd, &sphead->m_name);
  return false;
}


6592
bool LEX::sp_body_finalize_trigger(THD *thd)
6593
{
6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611
  return sphead->is_not_allowed_in_function("trigger") ||
         sp_body_finalize_procedure(thd);
}


bool LEX::sp_body_finalize_event(THD *thd)
{
  event_parse_data->body_changed= true;
  return sp_body_finalize_procedure(thd);
}


bool LEX::stmt_create_stored_function_finalize_standalone(const sp_name *end_name)
{
  if (sphead->check_standalone_routine_end_name(end_name))
    return true;
  stmt_create_routine_finalize();
  return false;
6612 6613 6614
}


6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631
bool LEX::sp_block_with_exceptions_finalize_declarations(THD *thd)
{
  /*
    [ DECLARE declarations ]
    BEGIN executable_section
    [ EXCEPTION exceptions ]
    END

    We are now at the "BEGIN" keyword.
    We have collected all declarations, including DECLARE HANDLER directives.
    But there will be possibly more handlers in the EXCEPTION section.

    Generate a forward jump from the end of the DECLARE section to the
    beginning of the EXCEPTION section, over the executable section.
  */
  return sphead->add_instr_jump(thd, spcont);
}
6632 6633


6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656
bool
LEX::sp_block_with_exceptions_finalize_executable_section(THD *thd,
                                         uint executable_section_ip)
{
  /*
    We're now at the end of "executable_section" of the block,
    near the "EXCEPTION" or the "END" keyword.
    Generate a jump to the END of the block over the EXCEPTION section.
  */
  if (sphead->add_instr_jump_forward_with_backpatch(thd, spcont))
    return true;
  /*
    Set the destination for the jump that we added in
    sp_block_with_exceptions_finalize_declarations().
  */
  sp_instr *instr= sphead->get_instr(executable_section_ip - 1);
  instr->backpatch(sphead->instructions(), spcont);
  return false;
}


bool
LEX::sp_block_with_exceptions_finalize_exceptions(THD *thd,
6657 6658
                                                  uint executable_section_ip,
                                                  uint exception_count)
6659
{
6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670
  if (!exception_count)
  {
    /*
      The jump from the end of DECLARE section to
      the beginning of the EXCEPTION section that we added in
      sp_block_with_exceptions_finalize_declarations() is useless
      if there were no exceptions.
      Replace it to "no operation".
    */
    return sphead->replace_instr_to_nop(thd, executable_section_ip - 1);
  }
6671 6672 6673 6674 6675 6676 6677
  /*
    Generate a jump from the end of the EXCEPTION code
    to the executable section.
  */
  return sphead->add_instr_jump(thd, spcont, executable_section_ip);
}

6678

6679 6680 6681 6682 6683 6684 6685 6686
bool LEX::sp_block_with_exceptions_add_empty(THD *thd)
{
  uint ip= sphead->instructions();
  return sp_block_with_exceptions_finalize_executable_section(thd, ip) ||
         sp_block_with_exceptions_finalize_exceptions(thd, ip, 0);
}


6687 6688 6689 6690 6691 6692 6693
bool LEX::sp_change_context(THD *thd, const sp_pcontext *ctx, bool exclusive)
{
  uint n;
  uint ip= sphead->instructions();
  if ((n= spcont->diff_handlers(ctx, exclusive)))
  {
    sp_instr_hpop *hpop= new (thd->mem_root) sp_instr_hpop(ip++, spcont, n);
6694
    if (unlikely(hpop == NULL) || unlikely(sphead->add_instr(hpop)))
6695 6696 6697 6698 6699
      return true;
  }
  if ((n= spcont->diff_cursors(ctx, exclusive)))
  {
    sp_instr_cpop *cpop= new (thd->mem_root) sp_instr_cpop(ip++, spcont, n);
6700
    if (unlikely(cpop == NULL) || unlikely(sphead->add_instr(cpop)))
6701 6702 6703 6704 6705 6706
      return true;
  }
  return false;
}


6707
bool LEX::sp_leave_statement(THD *thd, const LEX_CSTRING *label_name)
6708 6709
{
  sp_label *lab= spcont->find_label(label_name);
6710
  if (unlikely(!lab))
6711
  {
6712
    my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "LEAVE", label_name->str);
6713 6714
    return true;
  }
6715
  return sp_exit_block(thd, lab, NULL);
6716 6717
}

6718
bool LEX::sp_goto_statement(THD *thd, const LEX_CSTRING *label_name)
halfspawn's avatar
halfspawn committed
6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744
{
  sp_label *lab= spcont->find_goto_label(label_name);
  if (!lab || lab->ip == 0)
  {
    sp_label *delayedlabel;
    if (!lab)
    {
      // Label not found --> add forward jump to an unknown label
      spcont->push_goto_label(thd, label_name, 0, sp_label::GOTO);
      delayedlabel= spcont->last_goto_label();
    }
    else
    {
      delayedlabel= lab;
    }
    return sphead->push_backpatch_goto(thd, spcont, delayedlabel);
  }
  else
  {
    // Label found (backward goto)
    return sp_change_context(thd, lab->ctx, false) ||
           sphead->add_instr_jump(thd, spcont, lab->ip); /* Jump back */
  }
  return false;
}

6745
bool LEX::sp_push_goto_label(THD *thd, const LEX_CSTRING *label_name)
halfspawn's avatar
halfspawn committed
6746 6747 6748 6749
{
  sp_label *lab= spcont->find_goto_label(label_name, false);
  if (lab)
  {
6750
    if (unlikely(lab->ip != 0))
halfspawn's avatar
halfspawn committed
6751
    {
6752
      my_error(ER_SP_LABEL_REDEFINE, MYF(0), label_name->str);
halfspawn's avatar
halfspawn committed
6753 6754 6755 6756
      return true;
    }
    lab->ip= sphead->instructions();

6757
    sp_label *beginblocklabel= spcont->find_label(&empty_clex_str);
halfspawn's avatar
halfspawn committed
6758 6759 6760 6761 6762 6763 6764 6765
    sphead->backpatch_goto(thd, lab, beginblocklabel);
  }
  else
  {
    spcont->push_goto_label(thd, label_name, sphead->instructions());
  }
  return false;
}
6766

6767 6768
bool LEX::sp_exit_block(THD *thd, sp_label *lab)
{
6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782
  /*
    When jumping to a BEGIN-END block end, the target jump
    points to the block hpop/cpop cleanup instructions,
    so we should exclude the block context here.
    When jumping to something else (i.e., SP_LAB_ITER),
    there are no hpop/cpop at the jump destination,
    so we should include the block context here for cleanup.
  */
  bool exclusive= (lab->type == sp_label::BEGIN);
  return sp_change_context(thd, lab->ctx, exclusive) ||
         sphead->add_instr_jump_forward_with_backpatch(thd, spcont, lab);
}


6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793
bool LEX::sp_exit_block(THD *thd, sp_label *lab, Item *when)
{
  if (!when)
    return sp_exit_block(thd, lab);

  DBUG_ASSERT(sphead == thd->lex->sphead);
  DBUG_ASSERT(spcont == thd->lex->spcont);
  sp_instr_jump_if_not *i= new (thd->mem_root)
                           sp_instr_jump_if_not(sphead->instructions(),
                                                spcont,
                                                when, thd->lex);
6794 6795 6796
  if (unlikely(i == NULL) ||
      unlikely(sphead->add_instr(i)) ||
      unlikely(sp_exit_block(thd, lab)))
6797 6798 6799 6800 6801 6802 6803
    return true;
  i->backpatch(sphead->instructions(), spcont);
  return false;
}


bool LEX::sp_exit_statement(THD *thd, Item *item)
6804 6805
{
  sp_label *lab= spcont->find_label_current_loop_start();
6806
  if (unlikely(!lab))
6807 6808 6809 6810 6811
  {
    my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "EXIT", "");
    return true;
  }
  DBUG_ASSERT(lab->type == sp_label::ITERATION);
6812
  return sp_exit_block(thd, lab, item);
6813 6814 6815
}


6816
bool LEX::sp_exit_statement(THD *thd, const LEX_CSTRING *label_name, Item *item)
6817 6818
{
  sp_label *lab= spcont->find_label(label_name);
6819
  if (unlikely(!lab || lab->type != sp_label::ITERATION))
6820
  {
6821
    my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "EXIT", label_name->str);
6822 6823
    return true;
  }
6824
  return sp_exit_block(thd, lab, item);
6825 6826 6827
}


6828
bool LEX::sp_iterate_statement(THD *thd, const LEX_CSTRING *label_name)
6829 6830
{
  sp_label *lab= spcont->find_label(label_name);
6831
  if (unlikely(!lab || lab->type != sp_label::ITERATION))
6832
  {
6833
    my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "ITERATE", label_name->str);
6834 6835
    return true;
  }
6836 6837 6838 6839 6840 6841
  return sp_continue_loop(thd, lab);
}


bool LEX::sp_continue_loop(THD *thd, sp_label *lab)
{
6842 6843 6844 6845 6846 6847 6848 6849 6850
  if (lab->ctx->for_loop().m_index)
  {
    // We're in a FOR loop, increment the index variable before backward jump
    sphead->reset_lex(thd);
    DBUG_ASSERT(this != thd->lex);
    if (thd->lex->sp_for_loop_increment(thd, lab->ctx->for_loop()) ||
        thd->lex->sphead->restore_lex(thd))
      return true;
  }
6851 6852 6853 6854 6855
  return sp_change_context(thd, lab->ctx, false) ||
         sphead->add_instr_jump(thd, spcont, lab->ip); /* Jump back */
}


6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866
bool LEX::sp_continue_loop(THD *thd, sp_label *lab, Item *when)
{
  if (!when)
    return sp_continue_loop(thd, lab);

  DBUG_ASSERT(sphead == thd->lex->sphead);
  DBUG_ASSERT(spcont == thd->lex->spcont);
  sp_instr_jump_if_not *i= new (thd->mem_root)
                           sp_instr_jump_if_not(sphead->instructions(),
                                                spcont,
                                                when, thd->lex);
6867 6868 6869
  if (unlikely(i == NULL) ||
      unlikely(sphead->add_instr(i)) ||
      unlikely(sp_continue_loop(thd, lab)))
6870 6871 6872 6873 6874 6875 6876 6877 6878
    return true;
  i->backpatch(sphead->instructions(), spcont);
  return false;
}


bool LEX::sp_continue_statement(THD *thd, Item *when)
{
  sp_label *lab= spcont->find_label_current_loop_start();
6879
  if (unlikely(!lab))
6880 6881 6882 6883 6884 6885 6886 6887 6888
  {
    my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "CONTINUE", "");
    return true;
  }
  DBUG_ASSERT(lab->type == sp_label::ITERATION);
  return sp_continue_loop(thd, lab, when);
}


6889 6890
bool LEX::sp_continue_statement(THD *thd, const LEX_CSTRING *label_name,
                                Item *when)
6891 6892 6893 6894
{
  sp_label *lab= spcont->find_label(label_name);
  if (!lab || lab->type != sp_label::ITERATION)
  {
6895
    my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "CONTINUE", label_name->str);
6896 6897 6898 6899 6900 6901
    return true;
  }
  return sp_continue_loop(thd, lab, when);
}


6902 6903 6904 6905
bool LEX::maybe_start_compound_statement(THD *thd)
{
  if (!sphead)
  {
6906
    if (!make_sp_head(thd, NULL, &sp_handler_procedure, DEFAULT_AGGREGATE))
6907
      return true;
6908
    sphead->set_suid(SP_IS_NOT_SUID);
6909 6910 6911 6912 6913 6914
    sphead->set_body_start(thd, thd->m_parser_state->m_lip.get_cpp_ptr());
  }
  return false;
}


6915
bool LEX::sp_push_loop_label(THD *thd, const LEX_CSTRING *label_name)
6916 6917 6918 6919
{
  sp_label *lab= spcont->find_label(label_name);
  if (lab)
  {
6920
    my_error(ER_SP_LABEL_REDEFINE, MYF(0), label_name->str);
6921 6922
    return true;
  }
6923 6924
  spcont->push_label(thd, label_name, sphead->instructions(),
                     sp_label::ITERATION);
6925 6926 6927 6928 6929 6930 6931 6932 6933
  return false;
}


bool LEX::sp_push_loop_empty_label(THD *thd)
{
  if (maybe_start_compound_statement(thd))
    return true;
  /* Unlabeled controls get an empty label. */
6934
  spcont->push_label(thd, &empty_clex_str, sphead->instructions(),
6935
                     sp_label::ITERATION);
6936 6937 6938 6939
  return false;
}


6940
bool LEX::sp_pop_loop_label(THD *thd, const LEX_CSTRING *label_name)
6941 6942 6943
{
  sp_label *lab= spcont->pop_label();
  sphead->backpatch(lab);
6944
  if (label_name->str &&
6945 6946
      lex_string_cmp(system_charset_info, label_name,
                     &lab->name) != 0)
6947
  {
6948
    my_error(ER_SP_LABEL_MISMATCH, MYF(0), label_name->str);
6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962
    return true;
  }
  return false;
}


void LEX::sp_pop_loop_empty_label(THD *thd)
{
  sp_label *lab= spcont->pop_label();
  sphead->backpatch(lab);
  DBUG_ASSERT(lab->name.length == 0);
}


6963 6964 6965 6966
bool LEX::sp_while_loop_expression(THD *thd, Item *expr)
{
  sp_instr_jump_if_not *i= new (thd->mem_root)
    sp_instr_jump_if_not(sphead->instructions(), spcont, expr, this);
6967 6968 6969 6970 6971
  return (unlikely(i == NULL) ||
          /* Jumping forward */
          unlikely(sphead->push_backpatch(thd, i, spcont->last_label())) ||
          unlikely(sphead->new_cont_backpatch(i)) ||
          unlikely(sphead->add_instr(i)));
6972 6973 6974 6975 6976 6977 6978 6979
}


bool LEX::sp_while_loop_finalize(THD *thd)
{
  sp_label *lab= spcont->last_label();  /* Jumping back */
  sp_instr_jump *i= new (thd->mem_root)
    sp_instr_jump(sphead->instructions(), spcont, lab->ip);
6980 6981
  if (unlikely(i == NULL) ||
      unlikely(sphead->add_instr(i)))
6982 6983 6984 6985 6986 6987
    return true;
  sphead->do_cont_backpatch();
  return false;
}


6988 6989 6990
Item *LEX::create_and_link_Item_trigger_field(THD *thd,
                                              const LEX_CSTRING *name,
                                              bool new_row)
6991 6992 6993
{
  Item_trigger_field *trg_fld;

6994
  if (unlikely(trg_chistics.event == TRG_EVENT_INSERT && !new_row))
6995 6996 6997 6998 6999
  {
    my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "OLD", "on INSERT");
    return NULL;
  }

7000
  if (unlikely(trg_chistics.event == TRG_EVENT_DELETE && new_row))
7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021
  {
    my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "NEW", "on DELETE");
    return NULL;
  }

  DBUG_ASSERT(!new_row ||
              (trg_chistics.event == TRG_EVENT_INSERT ||
               trg_chistics.event == TRG_EVENT_UPDATE));

  const bool tmp_read_only=
    !(new_row && trg_chistics.action_time == TRG_ACTION_BEFORE);
  trg_fld= new (thd->mem_root)
             Item_trigger_field(thd, current_context(),
                                new_row ?
                                  Item_trigger_field::NEW_ROW:
                                  Item_trigger_field::OLD_ROW,
                                name, SELECT_ACL, tmp_read_only);
  /*
    Let us add this item to list of all Item_trigger_field objects
    in trigger.
  */
7022 7023
  if (likely(trg_fld))
    trg_table_fields.link_in_list(trg_fld, &trg_fld->next_trg_field);
7024 7025 7026 7027 7028

  return trg_fld;
}


7029
Item *LEX::make_item_colon_ident_ident(THD *thd,
7030 7031
                                       const Lex_ident_cli_st *ca,
                                       const Lex_ident_cli_st *cb)
7032
{
7033 7034 7035 7036
  Lex_ident_sys a(thd, ca), b(thd, cb);
  if (a.is_null() || b.is_null())
    return NULL; // OEM
  if (!is_trigger_new_or_old_reference(&a))
7037 7038 7039 7040
  {
    thd->parse_error();
    return NULL;
  }
7041 7042
  bool new_row= (a.str[0] == 'N' || a.str[0] == 'n');
  return create_and_link_Item_trigger_field(thd, &b, new_row);
7043 7044 7045
}


7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069
Item *LEX::make_item_plsql_cursor_attr(THD *thd, const LEX_CSTRING *name,
                                       plsql_cursor_attr_t attr)
{
  uint offset;
  if (unlikely(!spcont || !spcont->find_cursor(name, &offset, false)))
  {
    my_error(ER_SP_CURSOR_MISMATCH, MYF(0), name->str);
    return NULL;
  }
  switch (attr) {
  case PLSQL_CURSOR_ATTR_ISOPEN:
    return new (thd->mem_root) Item_func_cursor_isopen(thd, name, offset);
  case PLSQL_CURSOR_ATTR_FOUND:
    return new (thd->mem_root) Item_func_cursor_found(thd, name, offset);
  case PLSQL_CURSOR_ATTR_NOTFOUND:
    return new (thd->mem_root) Item_func_cursor_notfound(thd, name, offset);
  case PLSQL_CURSOR_ATTR_ROWCOUNT:
    return new (thd->mem_root) Item_func_cursor_rowcount(thd, name, offset);
  }
  DBUG_ASSERT(0);
  return NULL;
}


7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094
Item *LEX::make_item_sysvar(THD *thd,
                            enum_var_type type,
                            const LEX_CSTRING *name,
                            const LEX_CSTRING *component)

{
  Item *item;
  DBUG_ASSERT(name->str);
  /*
    "SELECT @@global.global.variable" is not allowed
    Note, "global" can come through TEXT_STRING_sys.
  */
  if (component->str && unlikely(check_reserved_words(name)))
  {
    thd->parse_error();
    return NULL;
  }
  if (unlikely(!(item= get_system_var(thd, type, name, component))))
    return NULL;
  if (!((Item_func_get_system_var*) item)->is_written_to_binlog())
    set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE);
  return item;
}


7095 7096 7097 7098 7099 7100 7101 7102
static bool param_push_or_clone(THD *thd, LEX *lex, Item_param *item)
{
  return !lex->clone_spec_offset ?
         lex->param_list.push_back(item, thd->mem_root) :
         item->add_as_clone(thd);
}


7103
Item_param *LEX::add_placeholder(THD *thd, const LEX_CSTRING *name,
7104
                                 const char *start, const char *end)
7105
{
7106
  if (unlikely(!thd->m_parser_state->m_lip.stmt_prepare_mode))
7107 7108 7109 7110
  {
    thd->parse_error(ER_SYNTAX_ERROR, start);
    return NULL;
  }
7111
  if (unlikely(!parsing_options.allows_variable))
7112 7113 7114 7115
  {
    my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
    return NULL;
  }
7116
  Query_fragment pos(thd, sphead, start, end);
7117
  Item_param *item= new (thd->mem_root) Item_param(thd, name,
7118
                                                   pos.pos(), pos.length());
7119
  if (unlikely(!item) || unlikely(param_push_or_clone(thd, this, item)))
7120 7121 7122 7123 7124 7125 7126 7127
  {
    my_error(ER_OUT_OF_RESOURCES, MYF(0));
    return NULL;
  }
  return item;
}


7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145
bool LEX::add_signal_statement(THD *thd, const sp_condition_value *v)
{
  Yacc_state *state= &thd->m_parser_state->m_yacc;
  sql_command= SQLCOM_SIGNAL;
  m_sql_cmd= new (thd->mem_root) Sql_cmd_signal(v, state->m_set_signal_info);
  return m_sql_cmd == NULL;
}


bool LEX::add_resignal_statement(THD *thd, const sp_condition_value *v)
{
  Yacc_state *state= &thd->m_parser_state->m_yacc;
  sql_command= SQLCOM_RESIGNAL;
  m_sql_cmd= new (thd->mem_root) Sql_cmd_resignal(v, state->m_set_signal_info);
  return m_sql_cmd == NULL;
}


7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177
/*
  Make an Item when an identifier is found in the FOR loop bounds:
    FOR rec IN cursor
    FOR var IN var1 .. xxx
    FOR var IN row1.field1 .. xxx
  When we parse the first expression after the "IN" keyword,
  we don't know yet if it's a cursor name, or a scalar SP variable name,
  or a field of a ROW SP variable. Here we create Item_field to remember
  the fully qualified name. Later sp_for_loop_cursor_declarations()
  detects how to treat this name properly.
*/
Item *LEX::create_item_for_loop_bound(THD *thd,
                                      const LEX_CSTRING *a,
                                      const LEX_CSTRING *b,
                                      const LEX_CSTRING *c)
{
  /*
    Pass NULL as the name resolution context.
    This is OK, fix_fields() won't be called for this Item_field.
  */
  return new (thd->mem_root) Item_field(thd, NULL, a->str, b->str, c);
}


bool LEX::check_expr_allows_fields_or_error(THD *thd, const char *name) const
{
  if (select_stack_top > 0)
    return false; // OK, fields are allowed
  my_error(ER_BAD_FIELD_ERROR, MYF(0), name, thd->where);
  return true;    // Error, fields are not allowed
}

7178
Item *LEX::create_item_ident_nospvar(THD *thd,
7179 7180
                                     const Lex_ident_sys_st *a,
                                     const Lex_ident_sys_st *b)
7181 7182 7183 7184 7185 7186 7187 7188 7189
{
  DBUG_ASSERT(this == thd->lex);
  /*
    FIXME This will work ok in simple_ident_nospvar case because
    we can't meet simple_ident_nospvar in trigger now. But it
    should be changed in future.
  */
  if (is_trigger_new_or_old_reference(a))
  {
7190
    bool new_row= (a->str[0]=='N' || a->str[0]=='n');
7191

7192
    return create_and_link_Item_trigger_field(thd, b, new_row);
7193 7194
  }

7195
  if (unlikely(current_select->no_table_names_allowed))
7196
  {
7197
    my_error(ER_TABLENAME_NOT_ALLOWED_HERE, MYF(0), a->str, thd->where);
7198 7199
    return NULL;
  }
7200 7201 7202 7203 7204

  if (current_select->parsing_place == FOR_LOOP_BOUND)
    return create_item_for_loop_bound(thd, &null_clex_str, a, b);

  return create_item_ident_field(thd, NullS, a->str, b);
7205 7206 7207
}


7208
Item_splocal *LEX::create_item_spvar_row_field(THD *thd,
7209
                                               const Sp_rcontext_handler *rh,
7210 7211
                                               const Lex_ident_sys *a,
                                               const Lex_ident_sys *b,
7212
                                               sp_variable *spv,
7213 7214
                                               const char *start,
                                               const char *end)
7215
{
7216
  if (unlikely(!parsing_options.allows_variable))
7217 7218 7219 7220 7221
  {
    my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
    return NULL;
  }

7222
  Query_fragment pos(thd, sphead, start, end);
7223
  Item_splocal *item;
7224 7225
  if (spv->field_def.is_table_rowtype_ref() ||
      spv->field_def.is_cursor_rowtype_ref())
7226
  {
7227 7228 7229 7230
    if (unlikely(!(item= new (thd->mem_root)
                   Item_splocal_row_field_by_name(thd, rh, a, b, spv->offset,
                                                  &type_handler_null,
                                                  pos.pos(), pos.length()))))
7231 7232 7233 7234 7235 7236
      return NULL;
  }
  else
  {
    uint row_field_offset;
    const Spvar_definition *def;
7237
    if (unlikely(!(def= spv->find_row_field(a, b, &row_field_offset))))
7238
      return NULL;
7239

7240 7241 7242 7243 7244
    if (unlikely(!(item= new (thd->mem_root)
                   Item_splocal_row_field(thd, rh, a, b,
                                          spv->offset, row_field_offset,
                                          def->type_handler(),
                                          pos.pos(), pos.length()))))
7245 7246
      return NULL;
  }
7247
#ifdef DBUG_ASSERT_EXISTS
7248 7249 7250 7251 7252 7253 7254
  item->m_sp= sphead;
#endif
  safe_to_cache_query=0;
  return item;
}


7255 7256 7257 7258
my_var *LEX::create_outvar(THD *thd, const LEX_CSTRING *name)
{
  const Sp_rcontext_handler *rh;
  sp_variable *spv;
7259
  if (likely((spv= find_variable(name, &rh))))
7260 7261 7262 7263 7264 7265 7266 7267 7268
    return result ? new (thd->mem_root)
                    my_var_sp(rh, name, spv->offset,
                              spv->type_handler(), sphead) :
                    NULL /* EXPLAIN */;
  my_error(ER_SP_UNDECLARED_VAR, MYF(0), name->str);
  return NULL;
}


7269
my_var *LEX::create_outvar(THD *thd,
7270 7271
                           const LEX_CSTRING *a,
                           const LEX_CSTRING *b)
7272
{
7273
  const Sp_rcontext_handler *rh;
7274
  sp_variable *t;
7275
  if (unlikely(!(t= find_variable(a, &rh))))
7276
  {
7277
    my_error(ER_SP_UNDECLARED_VAR, MYF(0), a->str);
7278 7279 7280 7281 7282 7283
    return NULL;
  }
  uint row_field_offset;
  if (!t->find_row_field(a, b, &row_field_offset))
    return NULL;
  return result ?
7284
    new (thd->mem_root) my_var_sp_row_field(rh, a, b, t->offset,
7285
                                            row_field_offset, sphead) :
7286
    NULL /* EXPLAIN */;
7287 7288 7289
}


7290 7291 7292
Item *LEX::create_item_func_nextval(THD *thd, Table_ident *table_ident)
{
  TABLE_LIST *table;
7293 7294 7295 7296
  if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
                                                          TL_OPTION_SEQUENCE,
                                                          TL_WRITE_ALLOW_WRITE,
                                                          MDL_SHARED_WRITE))))
7297
    return NULL;
7298
  thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
7299 7300 7301 7302 7303 7304 7305
  return new (thd->mem_root) Item_func_nextval(thd, table);
}


Item *LEX::create_item_func_lastval(THD *thd, Table_ident *table_ident)
{
  TABLE_LIST *table;
7306 7307 7308 7309
  if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
                                                          TL_OPTION_SEQUENCE,
                                                          TL_READ,
                                                          MDL_SHARED_READ))))
7310
    return NULL;
7311
  thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
7312 7313 7314 7315 7316
  return new (thd->mem_root) Item_func_lastval(thd, table);
}


Item *LEX::create_item_func_nextval(THD *thd,
7317 7318
                                    const LEX_CSTRING *db,
                                    const LEX_CSTRING *name)
7319 7320
{
  Table_ident *table_ident;
7321 7322
  if (unlikely(!(table_ident=
                 new (thd->mem_root) Table_ident(thd, db, name, false))))
7323 7324 7325 7326 7327 7328
    return NULL;
  return create_item_func_nextval(thd, table_ident);
}


Item *LEX::create_item_func_lastval(THD *thd,
7329 7330
                                    const LEX_CSTRING *db,
                                    const LEX_CSTRING *name)
7331 7332
{
  Table_ident *table_ident;
7333 7334
  if (unlikely(!(table_ident=
                 new (thd->mem_root) Table_ident(thd, db, name, false))))
7335 7336 7337 7338 7339
    return NULL;
  return create_item_func_lastval(thd, table_ident);
}


7340 7341 7342 7343 7344
Item *LEX::create_item_func_setval(THD *thd, Table_ident *table_ident,
                                   longlong nextval, ulonglong round,
                                   bool is_used)
{
  TABLE_LIST *table;
7345 7346 7347 7348
  if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
                                                          TL_OPTION_SEQUENCE,
                                                          TL_WRITE_ALLOW_WRITE,
                                                          MDL_SHARED_WRITE))))
7349 7350 7351 7352 7353 7354
    return NULL;
  return new (thd->mem_root) Item_func_setval(thd, table, nextval, round,
                                              is_used);
}


7355
Item *LEX::create_item_ident(THD *thd,
7356 7357
                             const Lex_ident_cli_st *ca,
                             const Lex_ident_cli_st *cb)
7358
{
7359 7360
  const char *start= ca->pos();
  const char *end= cb->end();
7361
  const Sp_rcontext_handler *rh;
7362
  sp_variable *spv;
7363 7364 7365 7366 7367 7368 7369
  DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= start);
  DBUG_ASSERT(start <= end);
  DBUG_ASSERT(end <= thd->m_parser_state->m_lip.get_end_of_query());
  Lex_ident_sys a(thd, ca), b(thd, cb);
  if (a.is_null() || b.is_null())
    return NULL; // OEM
  if ((spv= find_variable(&a, &rh)) &&
7370 7371 7372
      (spv->field_def.is_row() ||
       spv->field_def.is_table_rowtype_ref() ||
       spv->field_def.is_cursor_rowtype_ref()))
7373
    return create_item_spvar_row_field(thd, rh, &a, &b, spv, start, end);
7374

7375
  if ((thd->variables.sql_mode & MODE_ORACLE) && b.length == 7)
7376 7377
  {
    if (!my_strnncoll(system_charset_info,
7378
                      (const uchar *) b.str, 7,
7379
                      (const uchar *) "NEXTVAL", 7))
7380
      return create_item_func_nextval(thd, &null_clex_str, &a);
7381
    else if (!my_strnncoll(system_charset_info,
7382
                          (const uchar *) b.str, 7,
7383
                          (const uchar *) "CURRVAL", 7))
7384
      return create_item_func_lastval(thd, &null_clex_str, &a);
7385 7386
  }

7387
  return create_item_ident_nospvar(thd, &a, &b);
7388 7389 7390
}


7391
Item *LEX::create_item_ident(THD *thd,
7392 7393 7394
                             const Lex_ident_sys_st *a,
                             const Lex_ident_sys_st *b,
                             const Lex_ident_sys_st *c)
7395 7396
{
  const char *schema= (thd->client_capabilities & CLIENT_NO_SCHEMA ?
7397
                       NullS : a->str);
7398

7399
  if ((thd->variables.sql_mode & MODE_ORACLE) && c->length == 7)
7400 7401
  {
    if (!my_strnncoll(system_charset_info,
7402
                      (const uchar *) c->str, 7,
7403 7404 7405
                      (const uchar *) "NEXTVAL", 7))
      return create_item_func_nextval(thd, a, b);
    else if (!my_strnncoll(system_charset_info,
7406
                          (const uchar *) c->str, 7,
7407 7408 7409 7410 7411 7412
                          (const uchar *) "CURRVAL", 7))
      return create_item_func_lastval(thd, a, b);
  }

  if (current_select->no_table_names_allowed)
  {
7413
    my_error(ER_TABLENAME_NOT_ALLOWED_HERE, MYF(0), b->str, thd->where);
7414 7415
    return NULL;
  }
7416 7417 7418 7419 7420

  if (current_select->parsing_place == FOR_LOOP_BOUND)
    return create_item_for_loop_bound(thd, &null_clex_str, b, c);

  return create_item_ident_field(thd, schema, b->str, c);
7421 7422
}

7423

7424
Item *LEX::create_item_limit(THD *thd, const Lex_ident_cli_st *ca)
7425
{
7426 7427 7428 7429
  DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= ca->pos());
  DBUG_ASSERT(ca->pos() <= ca->end());
  DBUG_ASSERT(ca->end() <= thd->m_parser_state->m_lip.get_end_of_query());

7430
  const Sp_rcontext_handler *rh;
7431
  sp_variable *spv;
7432 7433 7434 7435
  Lex_ident_sys sa(thd, ca);
  if (sa.is_null())
    return NULL; // EOM
  if (!(spv= find_variable(&sa, &rh)))
7436
  {
7437
    my_error(ER_SP_UNDECLARED_VAR, MYF(0), sa.str);
7438 7439 7440
    return NULL;
  }

7441
  Query_fragment pos(thd, sphead, ca->pos(), ca->end());
7442
  Item_splocal *item;
7443 7444 7445 7446
  if (unlikely(!(item= new (thd->mem_root)
                 Item_splocal(thd, rh, &sa,
                              spv->offset, spv->type_handler(),
                              pos.pos(), pos.length()))))
7447
    return NULL;
7448
#ifdef DBUG_ASSERT_EXISTS
7449 7450 7451 7452
  item->m_sp= sphead;
#endif
  safe_to_cache_query= 0;

7453
  if (!item->is_valid_limit_clause_variable_with_error())
7454
    return NULL;
7455

7456 7457 7458 7459 7460 7461
  item->limit_clause_param= true;
  return item;
}


Item *LEX::create_item_limit(THD *thd,
7462 7463
                             const Lex_ident_cli_st *ca,
                             const Lex_ident_cli_st *cb)
7464
{
7465 7466 7467 7468
  DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= ca->pos());
  DBUG_ASSERT(ca->pos() <= cb->end());
  DBUG_ASSERT(cb->end() <= thd->m_parser_state->m_lip.get_end_of_query());

7469
  const Sp_rcontext_handler *rh;
7470
  sp_variable *spv;
7471
  Lex_ident_sys sa(thd, ca), sb(thd, cb);
7472
  if (unlikely(sa.is_null() || sb.is_null()))
7473 7474
    return NULL; // EOM
  if (!(spv= find_variable(&sa, &rh)))
7475
  {
7476
    my_error(ER_SP_UNDECLARED_VAR, MYF(0), sa.str);
7477 7478 7479 7480 7481
    return NULL;
  }
  // Qualified %TYPE variables are not possible
  DBUG_ASSERT(!spv->field_def.column_type_ref());
  Item_splocal *item;
7482 7483
  if (unlikely(!(item= create_item_spvar_row_field(thd, rh, &sa, &sb, spv,
                                                   ca->pos(), cb->end()))))
7484
    return NULL;
7485
  if (!item->is_valid_limit_clause_variable_with_error())
7486 7487 7488 7489 7490 7491
    return NULL;
  item->limit_clause_param= true;
  return item;
}


7492 7493 7494 7495
bool LEX::set_user_variable(THD *thd, const LEX_CSTRING *name, Item *val)
{
  Item_func_set_user_var *item;
  set_var_user *var;
7496 7497 7498 7499 7500
  if (unlikely(!(item= new (thd->mem_root) Item_func_set_user_var(thd, name,
                                                                  val))) ||
      unlikely(!(var= new (thd->mem_root) set_var_user(item))))
    return true;
  if (unlikely(var_list.push_back(var, thd->mem_root)))
7501 7502 7503 7504 7505
    return true;
  return false;
}


7506 7507 7508
Item *LEX::create_item_ident_field(THD *thd, const char *db,
                                   const char *table,
                                   const Lex_ident_sys_st *name)
7509
{
7510 7511 7512
  if (check_expr_allows_fields_or_error(thd, name->str))
    return NULL;

7513 7514 7515
  if (current_select->parsing_place != IN_HAVING ||
      current_select->get_in_sum_expr() > 0)
    return new (thd->mem_root) Item_field(thd, current_context(),
7516
                                          db, table, name);
7517 7518

  return new (thd->mem_root) Item_ref(thd, current_context(),
7519
                                      db, table, name);
7520 7521 7522
}


7523
Item *LEX::create_item_ident_sp(THD *thd, Lex_ident_sys_st *name,
7524 7525
                                const char *start,
                                const char *end)
7526
{
7527 7528 7529 7530
  DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= start);
  DBUG_ASSERT(start <= end);
  DBUG_ASSERT(end <= thd->m_parser_state->m_lip.get_end_of_query());

7531
  const Sp_rcontext_handler *rh;
7532 7533
  sp_variable *spv;
  DBUG_ASSERT(spcont);
7534
  DBUG_ASSERT(sphead);
7535
  if ((spv= find_variable(name, &rh)))
7536 7537 7538 7539 7540 7541 7542 7543
  {
    /* We're compiling a stored procedure and found a variable */
    if (!parsing_options.allows_variable)
    {
      my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
      return NULL;
    }

7544
    Query_fragment pos(thd, sphead, start, end);
7545
    Item_splocal *splocal= spv->field_def.is_column_type_ref() ?
7546
      new (thd->mem_root) Item_splocal_with_delayed_data_type(thd, rh, name,
7547
                                                              spv->offset,
7548 7549
                                                              pos.pos(),
                                                              pos.length()) :
7550
      new (thd->mem_root) Item_splocal(thd, rh, name,
7551
                                       spv->offset, spv->type_handler(),
7552
                                       pos.pos(), pos.length());
7553
    if (unlikely(splocal == NULL))
7554
      return NULL;
7555
#ifdef DBUG_ASSERT_EXISTS
7556 7557 7558 7559 7560 7561 7562 7563
    splocal->m_sp= sphead;
#endif
    safe_to_cache_query= 0;
    return splocal;
  }

  if (thd->variables.sql_mode & MODE_ORACLE)
  {
7564
    if (lex_string_eq(name, STRING_WITH_LEN("SQLCODE")))
7565
      return new (thd->mem_root) Item_func_sqlcode(thd);
7566
    if (lex_string_eq(name, STRING_WITH_LEN("SQLERRM")))
7567 7568
      return new (thd->mem_root) Item_func_sqlerrm(thd);
  }
7569 7570 7571 7572 7573

  if (current_select->parsing_place == FOR_LOOP_BOUND)
    return create_item_for_loop_bound(thd, &null_clex_str, &null_clex_str,
                                      name);

7574 7575 7576 7577
  return create_item_ident_nosp(thd, name);
}


7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588

bool LEX::set_variable(const LEX_CSTRING *name, Item *item)
{
  sp_pcontext *ctx;
  const Sp_rcontext_handler *rh;
  sp_variable *spv= find_variable(name, &ctx, &rh);
  return spv ? sphead->set_local_variable(thd, ctx, rh, spv, item, this, true) :
               set_system_variable(option_type, name, item);
}


7589 7590 7591 7592
/**
  Generate instructions for:
    SET x.y= expr;
*/
7593 7594
bool LEX::set_variable(const LEX_CSTRING *name1,
                       const LEX_CSTRING *name2,
7595 7596
                       Item *item)
{
7597 7598
  const Sp_rcontext_handler *rh;
  sp_pcontext *ctx;
7599
  sp_variable *spv;
7600
  if (spcont && (spv= find_variable(name1, &ctx, &rh)))
7601
  {
7602 7603
    if (spv->field_def.is_table_rowtype_ref() ||
        spv->field_def.is_cursor_rowtype_ref())
7604 7605
      return sphead->set_local_variable_row_field_by_name(thd, ctx,
                                                          rh,
7606 7607
                                                          spv, name2,
                                                          item, this);
7608 7609 7610
    // A field of a ROW variable
    uint row_field_offset;
    return !spv->find_row_field(name1, name2, &row_field_offset) ||
7611
           sphead->set_local_variable_row_field(thd, ctx, rh,
7612 7613 7614 7615
                                                spv, row_field_offset,
                                                item, this);
  }

7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630
  if (is_trigger_new_or_old_reference(name1))
    return set_trigger_field(name1, name2, item);

  return set_system_variable(thd, option_type, name1, name2, item);
}


bool LEX::set_default_system_variable(enum_var_type var_type,
                                      const LEX_CSTRING *name,
                                      Item *val)
{
  static LEX_CSTRING default_base_name= {STRING_WITH_LEN("default")};
  sys_var *var= find_sys_var(thd, name->str, name->length);
  if (!var)
    return true;
7631
  if (unlikely(!var->is_struct()))
7632
  {
7633
    my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), name->str);
7634 7635
    return true;
  }
7636 7637 7638 7639 7640 7641 7642 7643 7644 7645
  return set_system_variable(var_type, var, &default_base_name, val);
}


bool LEX::set_system_variable(enum_var_type var_type,
                              const LEX_CSTRING *name,
                              Item *val)
{
  sys_var *var= find_sys_var(thd, name->str, name->length);
  DBUG_ASSERT(thd->is_error() || var != NULL);
7646
  return likely(var) ? set_system_variable(var_type, var, &null_clex_str, val) : true;
7647 7648 7649 7650 7651 7652 7653 7654 7655
}


bool LEX::set_system_variable(THD *thd, enum_var_type var_type,
                              const LEX_CSTRING *name1,
                              const LEX_CSTRING *name2,
                              Item *val)
{
  sys_var *tmp;
7656
  if (unlikely(check_reserved_words(name1)) ||
Sergey Vojtovich's avatar
Sergey Vojtovich committed
7657
      unlikely(!(tmp= find_sys_var(thd, name2->str, name2->length, true))))
7658 7659 7660 7661 7662
  {
    my_error(ER_UNKNOWN_STRUCTURED_VARIABLE, MYF(0),
             (int) name1->length, name1->str);
    return true;
  }
7663
  if (unlikely(!tmp->is_struct()))
7664
  {
7665
    my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), name2->str);
7666 7667
    return true;
  }
7668 7669 7670 7671 7672 7673 7674 7675
  return set_system_variable(var_type, tmp, name1, val);
}


bool LEX::set_trigger_field(const LEX_CSTRING *name1, const LEX_CSTRING *name2,
                            Item *val)
{
  DBUG_ASSERT(is_trigger_new_or_old_reference(name1));
7676
  if (unlikely(name1->str[0]=='O' || name1->str[0]=='o'))
7677 7678 7679 7680
  {
    my_error(ER_TRG_CANT_CHANGE_ROW, MYF(0), "OLD", "");
    return true;
  }
7681
  if (unlikely(trg_chistics.event == TRG_EVENT_DELETE))
7682 7683 7684 7685
  {
    my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "NEW", "on DELETE");
    return true;
  }
7686
  if (unlikely(trg_chistics.action_time == TRG_ACTION_AFTER))
7687 7688 7689 7690 7691
  {
    my_error(ER_TRG_CANT_CHANGE_ROW, MYF(0), "NEW", "after ");
    return true;
  }
  return set_trigger_new_row(name2, val);
7692 7693 7694
}


7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840
#ifdef MYSQL_SERVER
uint binlog_unsafe_map[256];

#define UNSAFE(a, b, c) \
  { \
  DBUG_PRINT("unsafe_mixed_statement", ("SETTING BASE VALUES: %s, %s, %02X\n", \
    LEX::stmt_accessed_table_string(a), \
    LEX::stmt_accessed_table_string(b), \
    c)); \
  unsafe_mixed_statement(a, b, c); \
  }

/*
  Sets the combination given by "a" and "b" and automatically combinations
  given by other types of access, i.e. 2^(8 - 2), as unsafe.

  It may happen a colision when automatically defining a combination as unsafe.
  For that reason, a combination has its unsafe condition redefined only when
  the new_condition is greater then the old. For instance,
  
     . (BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY) is never overwritten by 
     . (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF).
*/
void unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,
                            LEX::enum_stmt_accessed_table b, uint condition)
{
  int type= 0;
  int index= (1U << a) | (1U << b);
  
  
  for (type= 0; type < 256; type++)
  {
    if ((type & index) == index)
    {
      binlog_unsafe_map[type] |= condition;
    }
  }
}
/*
  The BINLOG_* AND TRX_CACHE_* values can be combined by using '&' or '|',
  which means that both conditions need to be satisfied or any of them is
  enough. For example, 
    
    . BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY means that the statment is
    unsafe when the option is on and trx-cache is not empty;

    . BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF means the statement is unsafe
    in all cases.

    . TRX_CACHE_EMPTY | TRX_CACHE_NOT_EMPTY means the statement is unsafe
    in all cases. Similar as above.
*/
void binlog_unsafe_map_init()
{
  memset((void*) binlog_unsafe_map, 0, sizeof(uint) * 256);

  /*
    Classify a statement as unsafe when there is a mixed statement and an
    on-going transaction at any point of the execution if:

      1. The mixed statement is about to update a transactional table and
      a non-transactional table.

      2. The mixed statement is about to update a transactional table and
      read from a non-transactional table.

      3. The mixed statement is about to update a non-transactional table
      and temporary transactional table.

      4. The mixed statement is about to update a temporary transactional
      table and read from a non-transactional table.

      5. The mixed statement is about to update a transactional table and
      a temporary non-transactional table.
     
      6. The mixed statement is about to update a transactional table and
      read from a temporary non-transactional table.

      7. The mixed statement is about to update a temporary transactional
      table and temporary non-transactional table.

      8. The mixed statement is about to update a temporary transactional
      table and read from a temporary non-transactional table.

    After updating a transactional table if:

      9. The mixed statement is about to update a non-transactional table
      and read from a transactional table.

      10. The mixed statement is about to update a non-transactional table
      and read from a temporary transactional table.

      11. The mixed statement is about to update a temporary non-transactional
      table and read from a transactional table.
      
      12. The mixed statement is about to update a temporary non-transactional
      table and read from a temporary transactional table.

      13. The mixed statement is about to update a temporary non-transactional
      table and read from a non-transactional table.

    The reason for this is that locks acquired may not protected a concurrent
    transaction of interfering in the current execution and by consequence in
    the result.
  */
  /* Case 1. */
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
  /* Case 2. */
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
  /* Case 3. */
  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_WRITES_TEMP_TRANS_TABLE,
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
  /* Case 4. */
  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
  /* Case 5. */
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON);
  /* Case 6. */
  UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON);
  /* Case 7. */
  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON);
  /* Case 8. */
  UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
    BINLOG_DIRECT_ON);
  /* Case 9. */
  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
    (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
  /* Case 10 */
  UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
    (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
  /* Case 11. */
  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
    BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
  /* Case 12. */
  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
    BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
  /* Case 13. */
  UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
     BINLOG_DIRECT_OFF & TRX_CACHE_NOT_EMPTY);
}
#endif
7841

7842 7843 7844

/**
  @brief
Igor Babaev's avatar
Igor Babaev committed
7845
    Collect fiels that are used in the GROUP BY of this st_select_lex
7846 7847 7848 7849
    
  @param thd  The thread handle

  @details
7850 7851
    This method looks through the fields that are used in the GROUP BY of this
    st_select_lex and saves info on these fields.
7852 7853
*/

7854 7855
void st_select_lex::collect_grouping_fields_for_derived(THD *thd,
                                                        ORDER *grouping_list)
7856
{
7857
  grouping_tmp_fields.empty();
7858 7859
  List_iterator<Item> li(join->fields_list);
  Item *item= li++;
7860 7861
  for (uint i= 0; i < master_unit()->derived->table->s->fields;
       i++, (item=li++))
7862
  {
7863
    for (ORDER *ord= grouping_list; ord; ord= ord->next)
7864 7865 7866
    {
      if ((*ord->item)->eq((Item*)item, 0))
      {
7867 7868 7869
        Field_pair *grouping_tmp_field=
          new Field_pair(master_unit()->derived->table->field[i], item);
        grouping_tmp_fields.push_back(grouping_tmp_field);
7870 7871 7872 7873 7874
      }
    }
  }
}

7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903

/**
  Collect fields that are used in the GROUP BY of this SELECT
*/

bool st_select_lex::collect_grouping_fields(THD *thd)
{
  grouping_tmp_fields.empty();

  for (ORDER *ord= group_list.first; ord; ord= ord->next)
  {
    Item *item= *ord->item;
    if (item->type() != Item::FIELD_ITEM &&
        !(item->type() == Item::REF_ITEM &&
        ((((Item_ref *) item)->ref_type() == Item_ref::VIEW_REF) ||
        (((Item_ref *) item)->ref_type() == Item_ref::REF))))
      continue;

    Field_pair *grouping_tmp_field=
      new Field_pair(((Item_field *)item->real_item())->field, item);
    if (grouping_tmp_fields.push_back(grouping_tmp_field, thd->mem_root))
      return false;
  }
  if (grouping_tmp_fields.elements)
    return false;
  return true;
}


7904 7905 7906
/**
  @brief
   For a condition check possibility of exraction a formula over grouping fields 
7907 7908 7909 7910 7911

  @param thd      The thread handle
  @param cond     The condition whose subformulas are to be analyzed
  @param checker  The checker callback function to be applied to the nodes
                  of the tree of the object
7912 7913 7914 7915 7916
  
  @details
    This method traverses the AND-OR condition cond and for each subformula of
    the condition it checks whether it can be usable for the extraction of a
    condition over the grouping fields of this select. The method uses
Igor Babaev's avatar
Igor Babaev committed
7917
    the call-back parameter checker to check whether a primary formula
7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929
    depends only on grouping fields.
    The subformulas that are not usable are marked with the flag NO_EXTRACTION_FL.
    The subformulas that can be entierly extracted are marked with the flag 
    FULL_EXTRACTION_FL.
  @note
    This method is called before any call of extract_cond_for_grouping_fields.
    The flag NO_EXTRACTION_FL set in a subformula allows to avoid building clone
    for the subformula when extracting the pushable condition.
    The flag FULL_EXTRACTION_FL allows to delete later all top level conjuncts
    from cond.
*/ 

Igor Babaev's avatar
Igor Babaev committed
7930
void 
7931
st_select_lex::check_cond_extraction_for_grouping_fields(THD *thd, Item *cond)
7932
{
7933
  if (cond->get_extraction_flag() == NO_EXTRACTION_FL)
7934
    return;
7935 7936 7937
  cond->clear_extraction_flag();
  if (cond->type() == Item::COND_ITEM)
  {
7938 7939 7940 7941
    Item_cond_and *and_cond=
      (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC) ?
      ((Item_cond_and*) cond) : 0;

7942 7943 7944 7945 7946 7947 7948
    List<Item> *arg_list=  ((Item_cond*) cond)->argument_list();
    List_iterator<Item> li(*arg_list);
    uint count= 0;         // to count items not containing NO_EXTRACTION_FL
    uint count_full= 0;    // to count items with FULL_EXTRACTION_FL
    Item *item;
    while ((item=li++))
    {
7949
      check_cond_extraction_for_grouping_fields(thd, item);
7950 7951 7952 7953 7954 7955 7956 7957 7958
      if (item->get_extraction_flag() !=  NO_EXTRACTION_FL)
      {
        count++;
        if (item->get_extraction_flag() == FULL_EXTRACTION_FL)
          count_full++;
      }
      else if (!and_cond)
        break;
    }
Igor Babaev's avatar
Igor Babaev committed
7959
    if ((and_cond && count == 0) || item)
7960 7961
      cond->set_extraction_flag(NO_EXTRACTION_FL);
    if (count_full == arg_list->elements)
7962
    {
7963
      cond->set_extraction_flag(FULL_EXTRACTION_FL);
7964
    }
7965 7966 7967 7968 7969 7970 7971
    if (cond->get_extraction_flag() != 0)
    {
      li.rewind();
      while ((item=li++))
        item->clear_extraction_flag();
    }
  }
Igor Babaev's avatar
Igor Babaev committed
7972 7973
  else
  {
7974
    int fl= cond->excl_dep_on_grouping_fields(this) ?
Igor Babaev's avatar
Igor Babaev committed
7975 7976 7977
      FULL_EXTRACTION_FL : NO_EXTRACTION_FL;
    cond->set_extraction_flag(fl);
  }
7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999
}


/**
  @brief
  Build condition extractable from the given one depended on grouping fields
 
  @param thd           The thread handle
  @param cond          The condition from which the condition depended 
                       on grouping fields is to be extracted
  @param no_top_clones If it's true then no clones for the top fully 
                       extractable conjuncts are built

  @details
    For the given condition cond this method finds out what condition depended
    only on the grouping fields can be extracted from cond. If such condition C
    exists the method builds the item for it.
    This method uses the flags NO_EXTRACTION_FL and FULL_EXTRACTION_FL set by the
    preliminary call of st_select_lex::check_cond_extraction_for_grouping_fields
    to figure out whether a subformula depends only on these fields or not.
  @note
    The built condition C is always implied by the condition cond
8000
    (cond => C). The method tries to build the least restictive such
8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012
    condition (i.e. for any other condition C' such that cond => C'
    we have C => C').
  @note
    The build item is not ready for usage: substitution for the field items
    has to be done and it has to be re-fixed.
  
  @retval
    the built condition depended only on grouping fields if such a condition exists
    NULL if there is no such a condition
*/ 

Item *st_select_lex::build_cond_for_grouping_fields(THD *thd, Item *cond,
8013
                                                    bool no_top_clones)
8014 8015 8016 8017 8018 8019
{
  if (cond->get_extraction_flag() == FULL_EXTRACTION_FL)
  {
    if (no_top_clones)
      return cond;
    cond->clear_extraction_flag();
8020
    return cond->build_clone(thd);
8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032
  }
  if (cond->type() == Item::COND_ITEM)
  {
    bool cond_and= false;
    Item_cond *new_cond;
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
    {
      cond_and= true;
      new_cond=  new (thd->mem_root) Item_cond_and(thd);
    }
    else
      new_cond= new (thd->mem_root) Item_cond_or(thd);
8033
    if (unlikely(!new_cond))
8034
      return 0;
8035 8036 8037 8038 8039 8040
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
    Item *item;
    while ((item=li++))
    {
      if (item->get_extraction_flag() == NO_EXTRACTION_FL)
      {
8041 8042 8043
        DBUG_ASSERT(cond_and);
        item->clear_extraction_flag();
        continue;
8044 8045
      }
      Item *fix= build_cond_for_grouping_fields(thd, item,
8046
                                                no_top_clones & cond_and);
8047
      if (unlikely(!fix))
8048
      {
8049 8050 8051
        if (cond_and)
          continue;
        break;
8052 8053 8054 8055 8056 8057 8058
      }
      new_cond->argument_list()->push_back(fix, thd->mem_root);
    }
    
    if (!cond_and && item)
    {
      while((item= li++))
8059
        item->clear_extraction_flag();
8060 8061 8062 8063 8064
      return 0;
    }
    switch (new_cond->argument_list()->elements) 
    {
    case 0:
8065
      return 0;
8066 8067 8068 8069 8070 8071 8072 8073
    case 1:
      return new_cond->argument_list()->head();
    default:
      return new_cond;
    }
  }
  return 0;
}
8074 8075


8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209
bool st_select_lex::set_nest_level(int new_nest_level)
{
  DBUG_ENTER("st_select_lex::set_nest_level");
  DBUG_PRINT("enter", ("select #%d %p nest level: %d",
                       select_number, this, new_nest_level));
  if (new_nest_level > (int) MAX_SELECT_NESTING)
  {
    my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT, MYF(0));
    DBUG_RETURN(TRUE);
  }
  nest_level= new_nest_level;
  new_nest_level++;
  for (SELECT_LEX_UNIT *u= first_inner_unit(); u; u= u->next_unit())
  {
    if (u->set_nest_level(new_nest_level))
      DBUG_RETURN(TRUE);
  }
  DBUG_RETURN(FALSE);
}

bool st_select_lex_unit::set_nest_level(int new_nest_level)
{
  DBUG_ENTER("st_select_lex_unit::set_nest_level");
  for(SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
  {
    if (sl->set_nest_level(new_nest_level))
      DBUG_RETURN(TRUE);
  }
  if (fake_select_lex &&
      fake_select_lex->set_nest_level(new_nest_level))
    DBUG_RETURN(TRUE);
  DBUG_RETURN(FALSE);
}


bool st_select_lex::check_parameters(SELECT_LEX *main_select)
{
  DBUG_ENTER("st_select_lex::check_parameters");
  DBUG_PRINT("enter", ("select #%d %p nest level: %d",
                       select_number, this, nest_level));


  if ((options & OPTION_PROCEDURE_CLAUSE) &&
      (!parent_lex->selects_allow_procedure ||
        next_select() != NULL ||
        this != master_unit()->first_select() ||
        nest_level != 0))
  {
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "PROCEDURE");
    DBUG_RETURN(TRUE);
  }

  if ((options & SELECT_HIGH_PRIORITY) && this != main_select)
  {
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "HIGH_PRIORITY");
    DBUG_RETURN(TRUE);
  }
  if ((options & OPTION_BUFFER_RESULT) && this != main_select)
  {
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_BUFFER_RESULT");
    DBUG_RETURN(TRUE);
  }
  if ((options & OPTION_FOUND_ROWS) && this != main_select)
  {
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_CALC_FOUND_ROWS");
    DBUG_RETURN(TRUE);
  }
  if (options & OPTION_NO_QUERY_CACHE)
  {
    /*
      Allow this flag only on the first top-level SELECT statement, if
      SQL_CACHE wasn't specified.
    */
    if (this != main_select)
    {
      my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_NO_CACHE");
      DBUG_RETURN(TRUE);
    }
    if (parent_lex->sql_cache == LEX::SQL_CACHE)
    {
      my_error(ER_WRONG_USAGE, MYF(0), "SQL_CACHE", "SQL_NO_CACHE");
      DBUG_RETURN(TRUE);
    }
    parent_lex->safe_to_cache_query=0;
    parent_lex->sql_cache= LEX::SQL_NO_CACHE;
  }
  if (options & OPTION_TO_QUERY_CACHE)
  {
    /*
      Allow this flag only on the first top-level SELECT statement, if
      SQL_NO_CACHE wasn't specified.
    */
    if (this != main_select)
    {
      my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_CACHE");
      DBUG_RETURN(TRUE);
    }
    if (parent_lex->sql_cache == LEX::SQL_NO_CACHE)
    {
      my_error(ER_WRONG_USAGE, MYF(0), "SQL_NO_CACHE", "SQL_CACHE");
      DBUG_RETURN(TRUE);
    }
    parent_lex->safe_to_cache_query=1;
    parent_lex->sql_cache= LEX::SQL_CACHE;
  }

  for (SELECT_LEX_UNIT *u= first_inner_unit(); u; u= u->next_unit())
  {
    if (u->check_parameters(main_select))
      DBUG_RETURN(TRUE);
  }
  DBUG_RETURN(FALSE);
}


bool st_select_lex_unit::check_parameters(SELECT_LEX *main_select)
{
  for(SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
  {
    if (sl->check_parameters(main_select))
      return TRUE;
  }
  return fake_select_lex && fake_select_lex->check_parameters(main_select);
}


bool LEX::check_main_unit_semantics()
{
  if (unit.set_nest_level(0) ||
      unit.check_parameters(first_select_lex()))
    return TRUE;
  return FALSE;
}

8210 8211 8212 8213
int set_statement_var_if_exists(THD *thd, const char *var_name,
                                size_t var_name_length, ulonglong value)
{
  sys_var *sysvar;
8214
  if (unlikely(thd->lex->sql_command == SQLCOM_CREATE_VIEW))
8215 8216 8217 8218
  {
    my_error(ER_VIEW_SELECT_CLAUSE, MYF(0), "[NO]WAIT");
    return 1;
  }
8219
  if (unlikely(thd->lex->sphead))
8220 8221 8222 8223
  {
    my_error(ER_SP_BADSTATEMENT, MYF(0), "[NO]WAIT");
    return 1;
  }
Marko Mäkelä's avatar
Marko Mäkelä committed
8224
  if ((sysvar= find_sys_var(thd, var_name, var_name_length, true)))
8225 8226 8227
  {
    Item *item= new (thd->mem_root) Item_uint(thd, value);
    set_var *var= new (thd->mem_root) set_var(thd, OPT_SESSION, sysvar,
8228
                                              &null_clex_str, item);
8229

8230 8231
    if (unlikely(!item) || unlikely(!var) ||
        unlikely(thd->lex->stmt_var_list.push_back(var, thd->mem_root)))
8232 8233 8234 8235 8236 8237 8238
    {
      my_error(ER_OUT_OF_RESOURCES, MYF(0));
      return 1;
    }
  }
  return 0;
}
8239 8240


8241
bool LEX::sp_add_cfetch(THD *thd, const LEX_CSTRING *name)
8242 8243 8244 8245 8246 8247
{
  uint offset;
  sp_instr_cfetch *i;

  if (!spcont->find_cursor(name, &offset, false))
  {
8248
    my_error(ER_SP_CURSOR_MISMATCH, MYF(0), name->str);
8249 8250 8251
    return true;
  }
  i= new (thd->mem_root)
8252 8253
    sp_instr_cfetch(sphead->instructions(), spcont, offset,
                    !(thd->variables.sql_mode & MODE_ORACLE));
8254
  if (unlikely(i == NULL) || unlikely(sphead->add_instr(i)))
8255 8256 8257
    return true;
  return false;
}
8258 8259


8260 8261 8262 8263 8264 8265 8266 8267 8268
bool LEX::sp_add_agg_cfetch()
{
  sphead->m_flags|= sp_head::HAS_AGGREGATE_INSTR;
  sp_instr_agg_cfetch *i=
    new (thd->mem_root) sp_instr_agg_cfetch(sphead->instructions(), spcont);
  return i == NULL || sphead->add_instr(i);
}


8269 8270 8271 8272
bool LEX::create_or_alter_view_finalize(THD *thd, Table_ident *table_ident)
{
  sql_command= SQLCOM_CREATE_VIEW;
  /* first table in list is target VIEW name */
8273
  if (!first_select_lex()->add_table_to_list(thd, table_ident, NULL,
8274 8275
                                             TL_OPTION_UPDATING,
                                             TL_IGNORE,
8276
                                             MDL_EXCLUSIVE))
8277 8278 8279 8280 8281 8282 8283 8284 8285 8286
    return true;
  query_tables->open_strategy= TABLE_LIST::OPEN_STUB;
  return false;
}


bool LEX::add_alter_view(THD *thd, uint16 algorithm,
                         enum_view_suid suid,
                         Table_ident *table_ident)
{
8287
  if (unlikely(sphead))
8288 8289 8290 8291
  {
    my_error(ER_SP_BADSTATEMENT, MYF(0), "ALTER VIEW");
    return true;
  }
8292 8293
  if (unlikely(!(create_view= new (thd->mem_root)
                 Create_view_info(VIEW_ALTER, algorithm, suid))))
8294 8295 8296 8297 8298 8299 8300 8301 8302
    return true;
  return create_or_alter_view_finalize(thd, table_ident);
}


bool LEX::add_create_view(THD *thd, DDL_options_st ddl,
                          uint16 algorithm, enum_view_suid suid,
                          Table_ident *table_ident)
{
8303
  if (unlikely(set_create_options_with_check(ddl)))
8304
    return true;
8305 8306 8307 8308 8309
  if (unlikely(!(create_view= new (thd->mem_root)
                 Create_view_info(ddl.or_replace() ?
                                  VIEW_CREATE_OR_REPLACE :
                                  VIEW_CREATE_NEW,
                                  algorithm, suid))))
8310 8311 8312
    return true;
  return create_or_alter_view_finalize(thd, table_ident);
}
8313 8314 8315 8316


bool LEX::call_statement_start(THD *thd, sp_name *name)
{
8317 8318
  Database_qualified_name pkgname(&null_clex_str, &null_clex_str);
  const Sp_handler *sph= &sp_handler_procedure;
8319 8320
  sql_command= SQLCOM_CALL;
  value_list.empty();
8321 8322
  if (unlikely(sph->sp_resolve_package_routine(thd, thd->lex->sphead,
                                               name, &sph, &pkgname)))
8323
    return true;
8324
  if (unlikely(!(m_sql_cmd= new (thd->mem_root) Sql_cmd_call(name, sph))))
8325
    return true;
8326 8327 8328
  sph->add_used_routine(this, thd, name);
  if (pkgname.m_name.length)
    sp_handler_package_body.add_used_routine(this, thd, &pkgname);
8329 8330 8331 8332 8333 8334 8335
  return false;
}


bool LEX::call_statement_start(THD *thd, const LEX_CSTRING *name)
{
  sp_name *spname= make_sp_name(thd, name);
8336
  return unlikely(!spname) || call_statement_start(thd, spname);
8337 8338 8339 8340 8341 8342 8343
}


bool LEX::call_statement_start(THD *thd, const LEX_CSTRING *name1,
                                         const LEX_CSTRING *name2)
{
  sp_name *spname= make_sp_name(thd, name1, name2);
8344
  return unlikely(!spname) || call_statement_start(thd, spname);
8345 8346 8347
}


8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360
sp_package *LEX::get_sp_package() const
{
  return sphead ? sphead->get_package() : NULL;
}


sp_package *LEX::create_package_start(THD *thd,
                                      enum_sql_command command,
                                      const Sp_handler *sph,
                                      const sp_name *name_arg,
                                      DDL_options_st options)
{
  sp_package *pkg;
8361 8362

  if (unlikely(sphead))
8363 8364 8365 8366
  {
    my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), sph->type_str());
    return NULL;
  }
8367
  if (unlikely(set_command_with_check(command, options)))
8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388
    return NULL;
  if (sph->type() == TYPE_ENUM_PACKAGE_BODY)
  {
    /*
      If we start parsing a "CREATE PACKAGE BODY", we need to load
      the corresponding "CREATE PACKAGE", for the following reasons:
      1. "CREATE PACKAGE BODY" is allowed only if "CREATE PACKAGE"
         was done earlier for the same package name.
         So if "CREATE PACKAGE" does not exist, we throw an error here.
      2. When parsing "CREATE PACKAGE BODY", we need to know all package
         public and private routine names, to translate procedure and
         function calls correctly.
         For example, this statement inside a package routine:
           CALL p;
         can be translated to:
           CALL db.pkg.p; -- p is a known (public or private) package routine
           CALL db.p;     -- p is not a known package routine
    */
    sp_head *spec;
    int ret= sp_handler_package_spec.
               sp_cache_routine_reentrant(thd, name_arg, &spec);
8389
    if (unlikely(!spec))
8390 8391 8392 8393 8394 8395 8396
    {
      if (!ret)
        my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
                 "PACKAGE", ErrConvDQName(name_arg).ptr());
      return 0;
    }
  }
8397
  if (unlikely(!(pkg= new sp_package(this, name_arg, sph))))
8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423
    return NULL;
  pkg->reset_thd_mem_root(thd);
  pkg->init(this);
  pkg->make_qname(pkg->get_main_mem_root(), &pkg->m_qname);
  sphead= pkg;
  return pkg;
}


bool LEX::create_package_finalize(THD *thd,
                                  const sp_name *name,
                                  const sp_name *name2,
                                  const char *body_start,
                                  const char *body_end)
{
  if (name2 &&
      (name2->m_explicit_name != name->m_explicit_name ||
       strcmp(name2->m_db.str, name->m_db.str) ||
       !Sp_handler::eq_routine_name(name2->m_name, name->m_name)))
  {
    bool exp= name2->m_explicit_name || name->m_explicit_name;
    my_error(ER_END_IDENTIFIER_DOES_NOT_MATCH, MYF(0),
             exp ? ErrConvDQName(name2).ptr() : name2->m_name.str,
             exp ? ErrConvDQName(name).ptr() : name->m_name.str);
    return true;
  }
8424
  // TODO: reuse code in LEX::create_package_finalize and sp_head::set_stmt_end
8425
  sphead->m_body.length= body_end - body_start;
8426 8427
  if (unlikely(!(sphead->m_body.str= thd->strmake(body_start,
                                                  sphead->m_body.length))))
8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438
    return true;

  size_t not_used;
  Lex_input_stream *lip= & thd->m_parser_state->m_lip;
  sphead->m_defstr.length= lip->get_cpp_ptr() - lip->get_cpp_buf();
  sphead->m_defstr.str= thd->strmake(lip->get_cpp_buf(), sphead->m_defstr.length);
  trim_whitespace(thd->charset(), &sphead->m_defstr, &not_used);

  sphead->restore_thd_mem_root(thd);
  sp_package *pkg= sphead->get_package();
  DBUG_ASSERT(pkg);
8439 8440
  return sphead->check_group_aggregate_instructions_forbid() ||
         pkg->validate_after_parser(thd);
8441 8442 8443
}


8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455
bool LEX::add_grant_command(THD *thd, enum_sql_command sql_command_arg,
                            stored_procedure_type type_arg)
{
  if (columns.elements)
  {
    thd->parse_error();
    return true;
  }
  sql_command= sql_command_arg,
  type= type_arg;
  return false;
}
8456 8457


8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473
Item *LEX::make_item_func_substr(THD *thd, Item *a, Item *b, Item *c)
{
  return (thd->variables.sql_mode & MODE_ORACLE) ?
    new (thd->mem_root) Item_func_substr_oracle(thd, a, b, c) :
    new (thd->mem_root) Item_func_substr(thd, a, b, c);
}


Item *LEX::make_item_func_substr(THD *thd, Item *a, Item *b)
{
  return (thd->variables.sql_mode & MODE_ORACLE) ?
    new (thd->mem_root) Item_func_substr_oracle(thd, a, b) :
    new (thd->mem_root) Item_func_substr(thd, a, b);
}


8474 8475 8476 8477 8478 8479 8480 8481 8482
Item *LEX::make_item_func_replace(THD *thd,
                                  Item *org,
                                  Item *find,
                                  Item *replace)
{
  return (thd->variables.sql_mode & MODE_ORACLE) ?
    new (thd->mem_root) Item_func_replace_oracle(thd, org, find, replace) :
    new (thd->mem_root) Item_func_replace(thd, org, find, replace);
}
8483 8484


8485 8486
bool SELECT_LEX::vers_push_field(THD *thd, TABLE_LIST *table,
                                 const LEX_CSTRING field_name)
8487
{
8488
  DBUG_ASSERT(field_name.str);
8489
  Item_field *fld= new (thd->mem_root) Item_field(thd, &context,
8490 8491 8492 8493
                                                  table->db.str,
                                                  table->alias.str,
                                                  &field_name);
  if (unlikely(!fld) || unlikely(item_list.push_back(fld)))
8494 8495 8496 8497
    return true;

  if (thd->lex->view_list.elements)
  {
8498
    LEX_CSTRING *l;
8499 8500 8501
    if (unlikely(!(l= thd->make_clex_string(field_name.str,
                                            field_name.length))) ||
        unlikely(thd->lex->view_list.push_back(l)))
8502 8503 8504 8505 8506
      return true;
  }

  return false;
}
8507

8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568

Item *Lex_trim_st::make_item_func_trim_std(THD *thd) const
{
  if (m_remove)
  {
    switch (m_spec) {
    case TRIM_BOTH:
      return new (thd->mem_root) Item_func_trim(thd, m_source, m_remove);
    case TRIM_LEADING:
      return new (thd->mem_root) Item_func_ltrim(thd, m_source, m_remove);
    case TRIM_TRAILING:
     return new (thd->mem_root) Item_func_rtrim(thd, m_source, m_remove);
    }
  }

  switch (m_spec) {
  case TRIM_BOTH:
    return new (thd->mem_root) Item_func_trim(thd, m_source);
  case TRIM_LEADING:
    return new (thd->mem_root) Item_func_ltrim(thd, m_source);
  case TRIM_TRAILING:
   return new (thd->mem_root) Item_func_rtrim(thd, m_source);
  }
  DBUG_ASSERT(0);
  return NULL;
}


Item *Lex_trim_st::make_item_func_trim_oracle(THD *thd) const
{
  if (m_remove)
  {
    switch (m_spec) {
    case TRIM_BOTH:
      return new (thd->mem_root) Item_func_trim_oracle(thd, m_source, m_remove);
    case TRIM_LEADING:
      return new (thd->mem_root) Item_func_ltrim_oracle(thd, m_source, m_remove);
    case TRIM_TRAILING:
     return new (thd->mem_root) Item_func_rtrim_oracle(thd, m_source, m_remove);
    }
  }

  switch (m_spec) {
  case TRIM_BOTH:
    return new (thd->mem_root) Item_func_trim_oracle(thd, m_source);
  case TRIM_LEADING:
    return new (thd->mem_root) Item_func_ltrim_oracle(thd, m_source);
  case TRIM_TRAILING:
   return new (thd->mem_root) Item_func_rtrim_oracle(thd, m_source);
  }
  DBUG_ASSERT(0);
  return NULL;
}


Item *Lex_trim_st::make_item_func_trim(THD *thd) const
{
  return (thd->variables.sql_mode & MODE_ORACLE) ?
         make_item_func_trim_oracle(thd) :
         make_item_func_trim_std(thd);
}
8569 8570


8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604
Item *LEX::make_item_func_call_generic(THD *thd, Lex_ident_cli_st *cdb,
                                       Lex_ident_cli_st *cname, List<Item> *args)
{
  Lex_ident_sys db(thd, cdb), name(thd, cname);
  if (db.is_null() || name.is_null())
    return NULL; // EOM
  /*
    The following in practice calls:
    <code>Create_sp_func::create()</code>
    and builds a stored function.

    However, it's important to maintain the interface between the
    parser and the implementation in item_create.cc clean,
    since this will change with WL#2128 (SQL PATH):
    - INFORMATION_SCHEMA.version() is the SQL 99 syntax for the native
    function version(),
    - MySQL.version() is the SQL 2003 syntax for the native function
    version() (a vendor can specify any schema).
  */

  if (!name.str || check_db_name((LEX_STRING*) static_cast<LEX_CSTRING*>(&db)))
  {
    my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
    return NULL;
  }
  if (check_routine_name(&name))
    return NULL;

  Create_qfunc *builder= find_qualified_function_builder(thd);
  DBUG_ASSERT(builder);
  return builder->create_with_db(thd, &db, &name, true, args);
}


Sergei Golubchik's avatar
Sergei Golubchik committed
8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617
Item *LEX::create_item_qualified_asterisk(THD *thd,
                                          const Lex_ident_sys_st *name)
{
  Item *item;
  if (!(item= new (thd->mem_root) Item_field(thd, current_context(),
                                             NullS, name->str,
                                             &star_clex_str)))
    return NULL;
  current_select->with_wild++;
  return item;
}


8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674
Item *LEX::create_item_qualified_asterisk(THD *thd,
                                          const Lex_ident_sys_st *a,
                                          const Lex_ident_sys_st *b)
{
  Item *item;
  const char* schema= thd->client_capabilities & CLIENT_NO_SCHEMA ?
                      NullS : a->str;
  if (!(item= new (thd->mem_root) Item_field(thd, current_context(),
                                             schema, b->str,
                                             &star_clex_str)))
   return NULL;
  current_select->with_wild++;
  return item;
}


bool Lex_ident_sys_st::copy_ident_cli(THD *thd, const Lex_ident_cli_st *str)
{
  return thd->to_ident_sys_alloc(this, str);
}

bool Lex_ident_sys_st::copy_keyword(THD *thd, const Lex_ident_cli_st *str)
{
  return thd->make_lex_string(static_cast<LEX_CSTRING*>(this),
                              str->str, str->length) == NULL;
}

bool Lex_ident_sys_st::copy_or_convert(THD *thd,
                                       const Lex_ident_cli_st *src,
                                       CHARSET_INFO *cs)
{
  if (!src->is_8bit())
    return copy_keyword(thd, src); // 7bit string makes a wellformed identifier
  return convert(thd, src, cs);
}


bool Lex_ident_sys_st::copy_sys(THD *thd, const LEX_CSTRING *src)
{
  if (thd->check_string_for_wellformedness(src->str, src->length,
                                           system_charset_info))
    return true;
  return thd->make_lex_string(this, src->str, src->length) == NULL;
}


bool Lex_ident_sys_st::convert(THD *thd,
                               const LEX_CSTRING *src, CHARSET_INFO *cs)
{
  LEX_STRING tmp;
  if (thd->convert_with_error(system_charset_info, &tmp, cs,
                              src->str, src->length))
    return true;
  str=    tmp.str;
  length= tmp.length;
  return false;
}
8675 8676


8677
bool Lex_ident_sys_st::to_size_number(ulonglong *to) const
8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814
{
  ulonglong number;
  uint text_shift_number= 0;
  longlong prefix_number;
  const char *start_ptr= str;
  size_t str_len= length;
  const char *end_ptr= start_ptr + str_len;
  int error;
  prefix_number= my_strtoll10(start_ptr, (char**) &end_ptr, &error);
  if (likely((start_ptr + str_len - 1) == end_ptr))
  {
    switch (end_ptr[0])
    {
      case 'g':
      case 'G': text_shift_number+=30; break;
      case 'm':
      case 'M': text_shift_number+=20; break;
      case 'k':
      case 'K': text_shift_number+=10; break;
      default:
        my_error(ER_WRONG_SIZE_NUMBER, MYF(0));
        return true;
    }
    if (unlikely(prefix_number >> 31))
    {
      my_error(ER_SIZE_OVERFLOW_ERROR, MYF(0));
      return true;
    }
    number= prefix_number << text_shift_number;
  }
  else
  {
    my_error(ER_WRONG_SIZE_NUMBER, MYF(0));
    return true;
  }
  *to= number;
  return false;
}


bool LEX::part_values_current(THD *thd)
{
  partition_element *elem= part_info->curr_part_elem;
  if (!is_partition_management())
  {
    if (unlikely(part_info->part_type != VERSIONING_PARTITION))
    {
      my_error(ER_PARTITION_WRONG_TYPE, MYF(0), "SYSTEM_TIME");
      return true;
    }
  }
  else
  {
    DBUG_ASSERT(create_last_non_select_table);
    DBUG_ASSERT(create_last_non_select_table->table_name.str);
    // FIXME: other ALTER commands?
    my_error(ER_VERS_WRONG_PARTS, MYF(0),
             create_last_non_select_table->table_name.str);
    return true;
  }
  elem->type(partition_element::CURRENT);
  DBUG_ASSERT(part_info->vers_info);
  part_info->vers_info->now_part= elem;
  if (unlikely(part_info->init_column_part(thd)))
    return true;
  return false;
}


bool LEX::part_values_history(THD *thd)
{
  partition_element *elem= part_info->curr_part_elem;
  if (!is_partition_management())
  {
    if (unlikely(part_info->part_type != VERSIONING_PARTITION))
    {
      my_error(ER_PARTITION_WRONG_TYPE, MYF(0), "SYSTEM_TIME");
      return true;
    }
  }
  else
  {
    part_info->vers_init_info(thd);
    elem->id= UINT_MAX32;
  }
  DBUG_ASSERT(part_info->vers_info);
  if (unlikely(part_info->vers_info->now_part))
  {
    DBUG_ASSERT(create_last_non_select_table);
    DBUG_ASSERT(create_last_non_select_table->table_name.str);
    my_error(ER_VERS_WRONG_PARTS, MYF(0),
             create_last_non_select_table->table_name.str);
    return true;
  }
  elem->type(partition_element::HISTORY);
  if (unlikely(part_info->init_column_part(thd)))
    return true;
  return false;
}


bool LEX::last_field_generated_always_as_row_start_or_end(Lex_ident *p,
                                                          const char *type,
                                                          uint flag)
{
  if (unlikely(p->str))
  {
    my_error(ER_VERS_DUPLICATE_ROW_START_END, MYF(0), type,
             last_field->field_name.str);
    return true;
  }
  last_field->flags|= (flag | NOT_NULL_FLAG);
  DBUG_ASSERT(p);
  *p= last_field->field_name;
  return false;
}



bool LEX::last_field_generated_always_as_row_start()
{
  Vers_parse_info &info= vers_get_info();
  Lex_ident *p= &info.as_row.start;
  return last_field_generated_always_as_row_start_or_end(p, "START",
                                                         VERS_SYS_START_FLAG);
}


bool LEX::last_field_generated_always_as_row_end()
{
  Vers_parse_info &info= vers_get_info();
  Lex_ident *p= &info.as_row.end;
  return last_field_generated_always_as_row_start_or_end(p, "END",
                                                         VERS_SYS_END_FLAG);
}


8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829
void st_select_lex_unit::reset_distinct()
{
  union_distinct= NULL;
  for(SELECT_LEX *sl= first_select()->next_select();
      sl;
      sl= sl->next_select())
  {
    if (sl->distinct)
    {
      union_distinct= sl;
    }
  }
}


8830
void st_select_lex_unit::fix_distinct()
8831
{
8832 8833
  if (union_distinct && this != union_distinct->master_unit())
    reset_distinct();
8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912
}


void st_select_lex_unit::register_select_chain(SELECT_LEX *first_sel)
{
  DBUG_ASSERT(first_sel != 0);
  slave= first_sel;
  first_sel->prev= &slave;
  for(SELECT_LEX *sel=first_sel; sel; sel= sel->next_select())
  {
    sel->master= (st_select_lex_node *)this;
    uncacheable|= sel->uncacheable;
  }
}


void st_select_lex::register_unit(SELECT_LEX_UNIT *unit,
                                  Name_resolution_context *outer_context)
{
  if ((unit->next= slave))
    slave->prev= &unit->next;
  unit->prev= &slave;
  slave= unit;
  unit->master= this;
  uncacheable|= unit->uncacheable;

  for(SELECT_LEX *sel= unit->first_select();sel; sel= sel->next_select())
  {
    sel->context.outer_context= outer_context;
  }
}


void st_select_lex::add_statistics(SELECT_LEX_UNIT *unit)
{
  for (;
       unit;
       unit= unit->next_unit())
    for(SELECT_LEX *child= unit->first_select();
        child;
        child= child->next_select())
    {
      /*
        A subselect can add fields to an outer select.
        Reserve space for them.
      */
      select_n_where_fields+= child->select_n_where_fields;
      /*
        Aggregate functions in having clause may add fields
        to an outer select. Count them also.
      */
      select_n_having_items+= child->select_n_having_items;
    }
}


bool LEX::main_select_push()
{
  DBUG_ENTER("LEX::main_select_push");
  current_select_number= 1;
  builtin_select.select_number= 1;
  if (push_select(&builtin_select))
    DBUG_RETURN(TRUE);
  DBUG_RETURN(FALSE);
}

void Lex_select_lock::set_to(SELECT_LEX *sel)
{
  if (defined_lock)
  {
    if (sel->master_unit() &&
        sel == sel->master_unit()->fake_select_lex)
      sel->master_unit()->set_lock_to_the_last_select(*this);
    else
    {
      sel->parent_lex->safe_to_cache_query= 0;
      if (update_lock)
      {
        sel->lock_type= TL_WRITE;
8913
        sel->set_lock_for_tables(TL_WRITE, false);
8914 8915 8916 8917
      }
      else
      {
        sel->lock_type= TL_READ_WITH_SHARED_LOCKS;
8918
        sel->set_lock_for_tables(TL_READ_WITH_SHARED_LOCKS, false);
8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040
      }
    }
  }
}

bool Lex_order_limit_lock::set_to(SELECT_LEX *sel)
{
  /*TODO: lock */
  //if (lock.defined_lock && sel == sel->master_unit()->fake_select_lex)
  //  return TRUE;
  if (lock.defined_timeout)
  {
    THD *thd= sel->parent_lex->thd;
     if (set_statement_var_if_exists(thd,
                                     C_STRING_WITH_LEN("lock_wait_timeout"),
                                     lock.timeout) ||
         set_statement_var_if_exists(thd,
                                     C_STRING_WITH_LEN("innodb_lock_wait_timeout"),
                                     lock.timeout))
       return TRUE;
  }
  lock.set_to(sel);
  sel->explicit_limit= limit.explicit_limit;
  sel->select_limit= limit.select_limit;
  sel->offset_limit= limit.offset_limit;
  if (order_list)
  {
    if (sel->get_linkage() != GLOBAL_OPTIONS_TYPE &&
        sel->olap != UNSPECIFIED_OLAP_TYPE &&
        (sel->get_linkage() != UNION_TYPE || sel->braces))
    {
      my_error(ER_WRONG_USAGE, MYF(0),
          "CUBE/ROLLUP", "ORDER BY");
      return TRUE;
    }
    sel->order_list= *(order_list);
  }
  sel->is_set_query_expr_tail= true;
  return FALSE;
}


static void change_item_list_context(List<Item> *list,
                                     Name_resolution_context *context)
{
  List_iterator_fast<Item> it (*list);
  Item *item;
  while((item= it++))
  {
    item->walk(&Item::change_context_processor, FALSE, (void *)context);
  }
}


bool LEX::insert_select_hack(SELECT_LEX *sel)
{
  DBUG_ENTER("LEX::insert_select_hack");

  DBUG_ASSERT(first_select_lex() == &builtin_select);
  DBUG_ASSERT(sel != NULL);

  DBUG_ASSERT(builtin_select.first_inner_unit() == NULL);

  if (builtin_select.link_prev)
  {
    if ((*builtin_select.link_prev= builtin_select.link_next))
      ((st_select_lex *)builtin_select.link_next)->link_prev=
        builtin_select.link_prev;
    builtin_select.link_prev= NULL; // indicator of removal
  }

  set_main_unit(sel->master_unit());

  DBUG_ASSERT(builtin_select.table_list.elements == 1);
  TABLE_LIST *insert_table= builtin_select.table_list.first;

  if (!(insert_table->next_local= sel->table_list.first))
  {
    sel->table_list.next= &insert_table->next_local;
  }
  sel->table_list.first= insert_table;
  sel->table_list.elements++;
  insert_table->select_lex= sel;

  sel->context.first_name_resolution_table= insert_table;
  builtin_select.context= sel->context;
  change_item_list_context(&field_list, &sel->context);

  if (sel->tvc && !sel->next_select() &&
      (sql_command == SQLCOM_INSERT_SELECT ||
       sql_command == SQLCOM_REPLACE_SELECT))
  {
    DBUG_PRINT("info", ("'Usual' INSERT detected"));
    many_values= sel->tvc->lists_of_values;
    sel->options= sel->tvc->select_options;
    sel->tvc= NULL;
    if (sql_command == SQLCOM_INSERT_SELECT)
      sql_command= SQLCOM_INSERT;
    else
      sql_command= SQLCOM_REPLACE;
  }


  for (SELECT_LEX *sel= all_selects_list;
       sel;
       sel= sel->next_select_in_list())
  {
    if (sel->select_number != 1)
      sel->select_number--;
  };

  DBUG_RETURN(FALSE);
}


/*
  Create an Item_singlerow_subselect for a query expression.
*/
Item *LEX::create_item_query_expression(THD *thd,
                                        const char *tok_start,
                                        st_select_lex_unit *unit)
{
9041
  if (!expr_allows_subselect)
9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071
  {
    thd->parse_error(ER_SYNTAX_ERROR, tok_start);
    return NULL;
  }

  // Add the subtree of subquery to the current SELECT_LEX
  SELECT_LEX *curr_sel= select_stack_head();
  DBUG_ASSERT(current_select == curr_sel);
  if (!curr_sel)
    curr_sel= &builtin_select;
  curr_sel->register_unit(unit, &curr_sel->context);
  curr_sel->add_statistics(unit);

  return new (thd->mem_root)
    Item_singlerow_subselect(thd, unit->first_select());
}


/**
  Process unit parsed in brackets
*/

bool LEX::parsed_unit_in_brackets(SELECT_LEX_UNIT *unit)
{
  SELECT_LEX *first_in_nest= unit->pre_last_parse->next_select()->first_nested;
  if (first_in_nest->first_nested != first_in_nest)
  {
    /* There is a priority jump starting from first_in_nest */
    if (create_priority_nest(first_in_nest) == NULL)
      return true;
9072
    unit->fix_distinct();
9073 9074 9075 9076 9077 9078
  }
  push_select(unit->fake_select_lex);
  return false;
}


9079

9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114
/**
  Process tail of unit parsed in brackets
*/
SELECT_LEX *LEX::parsed_unit_in_brackets_tail(SELECT_LEX_UNIT *unit,
                                              Lex_order_limit_lock * l)
{
  pop_select();
  if (l)
  {
    (l)->set_to(unit->fake_select_lex);
  }
  return unit->first_select();
}


/**
  Process select parsed in brackets
*/

SELECT_LEX *LEX::parsed_select(SELECT_LEX *sel, Lex_order_limit_lock * l)
{
  pop_select();
  if (l)
  {
    if (sel->next_select())
    {
      SELECT_LEX_UNIT *unit= sel->master_unit();
      if (!unit)
        unit= create_unit(sel);
      if (!unit)
        return NULL;
      if (!unit->fake_select_lex->is_set_query_expr_tail)
        l->set_to(unit->fake_select_lex);
      else
      {
9115 9116 9117 9118 9119 9120 9121
        if (!l->order_list && !unit->fake_select_lex->explicit_limit)
        {
          sel= unit->fake_select_lex;
          l->order_list= &sel->order_list;
        }
        else
          sel= wrap_unit_into_derived(unit);
9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132
        if (!sel)
          return NULL;
        l->set_to(sel);
      }
    }
    else if (!sel->is_set_query_expr_tail)
    {
      l->set_to(sel);
    }
    else
    {
9133 9134 9135
      if (!l->order_list && !sel->explicit_limit)
        l->order_list= &sel->order_list;
      else
9136 9137 9138 9139
      {
        SELECT_LEX_UNIT *unit= create_unit(sel);
        if (!unit)
          return NULL;
9140
        sel= wrap_unit_into_derived(unit);
9141
      }
9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230
      if (!sel)
        return NULL;
      l->set_to(sel);
    }
  }
  return sel;
}


/**
  Process select parsed in brackets
*/

SELECT_LEX *LEX::parsed_select_in_brackets(SELECT_LEX *sel,
                                           Lex_order_limit_lock * l)
{
  sel->braces= TRUE;
  return parsed_select(sel, l);
}


SELECT_LEX_UNIT *LEX::parsed_select_expr_start(SELECT_LEX *s1, SELECT_LEX *s2,
                                               enum sub_select_type unit_type,
                                               bool distinct)
{
  SELECT_LEX_UNIT *res;
  SELECT_LEX *sel1;
  SELECT_LEX *sel2;
  if (!s1->next_select())
    sel1= s1;
  else
  {
    sel1= wrap_unit_into_derived(s1->master_unit());
    if (!sel1)
      return NULL;
  }
  if (!s2->next_select())
    sel2= s2;
  else
  {
    sel2= wrap_unit_into_derived(s2->master_unit());
    if (!sel2)
      return NULL;
  }
  sel1->link_neighbour(sel2);
  sel2->set_linkage_and_distinct(unit_type, distinct);
  sel2->first_nested= sel1->first_nested= sel1;
  res= create_unit(sel1);
  if (res == NULL)
    return NULL;
  res->pre_last_parse= sel1;
  return res;
}


SELECT_LEX_UNIT *LEX::parsed_select_expr_cont(SELECT_LEX_UNIT *unit,
                                              SELECT_LEX *s2,
                                              enum sub_select_type unit_type,
                                              bool distinct, bool oracle)
{
  SELECT_LEX *sel1;
  if (!s2->next_select())
    sel1= s2;
  else
  {
    sel1= wrap_unit_into_derived(s2->master_unit());
    if (!sel1)
      return NULL;
  }
  SELECT_LEX *last= unit->pre_last_parse->next_select();

  int cmp= oracle? 0 : cmp_unit_op(unit_type, last->get_linkage());
  if (cmp == 0)
  {
    sel1->first_nested= last->first_nested;
  }
  else if (cmp > 0)
  {
    last->first_nested= unit->pre_last_parse;
    sel1->first_nested= last;
  }
  else /* cmp < 0 */
  {
    SELECT_LEX *first_in_nest= last->first_nested;
    if (first_in_nest->first_nested != first_in_nest)
    {
      /* There is a priority jump starting from first_in_nest */
      if ((last= create_priority_nest(first_in_nest)) == NULL)
        return NULL;
9231
      unit->fix_distinct();
9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248
    }
    sel1->first_nested= last->first_nested;
  }
  last->link_neighbour(sel1);
  sel1->set_master_unit(unit);
  sel1->set_linkage_and_distinct(unit_type, distinct);
  unit->pre_last_parse= last;
  return unit;
}

/**
  Process parsed select in body
*/

SELECT_LEX_UNIT *LEX::parsed_body_select(SELECT_LEX *sel,
                                         Lex_order_limit_lock * l)
{
9249 9250 9251 9252 9253 9254
  if (sel->braces && l && l->lock.defined_lock)
  {
    my_error(ER_WRONG_USAGE, MYF(0), "lock options",
        "SELECT in brackets");
    return NULL;
  }
9255 9256 9257 9258
  if (!(sel= parsed_select(sel, l)))
    return NULL;

  SELECT_LEX_UNIT *res= create_unit(sel);
9259 9260 9261 9262 9263 9264 9265 9266 9267 9268
  if (res && sel->tvc && sel->order_list.elements)
  {
    if (res->add_fake_select_lex(thd))
      return NULL;
    SELECT_LEX *fake= res->fake_select_lex;
    fake->order_list= sel->order_list;
    fake->explicit_limit= sel->explicit_limit;
    fake->select_limit= sel->select_limit;
    fake->offset_limit= sel->offset_limit;
  }
9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284
  return res;
}

/**
  Process parsed unit in body
*/

bool LEX::parsed_body_unit(SELECT_LEX_UNIT *unit)
{
  SELECT_LEX *first_in_nest=
    unit->pre_last_parse->next_select()->first_nested;
  if (first_in_nest->first_nested != first_in_nest)
  {
    /* There is a priority jump starting from first_in_nest */
    if (create_priority_nest(first_in_nest) == NULL)
      return true;
9285
    unit->fix_distinct();
9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313
  }
  push_select(unit->fake_select_lex);
  return false;
}

/**
  Process parsed tail of unit in body

  TODO: make processing for double tail case
*/

SELECT_LEX_UNIT *LEX::parsed_body_unit_tail(SELECT_LEX_UNIT *unit,
                                            Lex_order_limit_lock * l)
{
  pop_select();
  if (l)
  {
    (l)->set_to(unit->fake_select_lex);
  }
  return unit;
}

/**
  Process subselect parsing
*/

SELECT_LEX *LEX::parsed_subselect(SELECT_LEX_UNIT *unit, char *place)
{
9314
  if (!expr_allows_subselect)
9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332
  {
    thd->parse_error(ER_SYNTAX_ERROR, place);
    return NULL;
  }

  // Add the subtree of subquery to the current SELECT_LEX
  SELECT_LEX *curr_sel= select_stack_head();
  DBUG_ASSERT(current_select == curr_sel);
  if (curr_sel)
  {
    curr_sel->register_unit(unit, &curr_sel->context);
    curr_sel->add_statistics(unit);
  }

  return unit->first_select();
}


9333

9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352
/**
  Process INSERT-like select
*/

bool LEX::parsed_insert_select(SELECT_LEX *first_select)
{
  if (sql_command == SQLCOM_INSERT ||
      sql_command == SQLCOM_REPLACE)
  {
    if (sql_command == SQLCOM_INSERT)
      sql_command= SQLCOM_INSERT_SELECT;
    else
      sql_command= SQLCOM_REPLACE_SELECT;
  }
  insert_select_hack(first_select);
  if (check_main_unit_semantics())
    return true;

  // fix "main" select
9353
  SELECT_LEX *blt __attribute__((unused))= pop_select();
9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478
  DBUG_ASSERT(blt == &builtin_select);
  push_select(first_select);
  return false;
}


bool LEX::parsed_TVC_start()
{
  SELECT_LEX *sel;
  many_values.empty();
  insert_list= 0;
  if (!(sel= alloc_select(TRUE)) ||
        push_select(sel))
    return true;
  sel->init_select();
  sel->braces= FALSE; // just initialisation
  return false;
}


SELECT_LEX *LEX::parsed_TVC_end()
{

  SELECT_LEX *res= pop_select(); // above TVC select
  if (!(res->tvc=
        new (thd->mem_root) table_value_constr(many_values,
          res,
          res->options)))
    return NULL;
  many_values.empty();
  return res;
}


TABLE_LIST *LEX::parsed_derived_select(SELECT_LEX *sel, int for_system_time,
                                       LEX_CSTRING *alias)
{
  TABLE_LIST *res;
  derived_tables|= DERIVED_SUBQUERY;
  sel->set_linkage(DERIVED_TABLE_TYPE);
  sel->braces= FALSE;
  // Add the subtree of subquery to the current SELECT_LEX
  SELECT_LEX *curr_sel= select_stack_head();
  DBUG_ASSERT(current_select == curr_sel);
  SELECT_LEX_UNIT *unit= sel->master_unit();
  if (!unit)
  {
    unit= create_unit(sel);
    if (!unit)
      return NULL;
  }
  curr_sel->register_unit(unit, &curr_sel->context);
  curr_sel->add_statistics(unit);

  Table_ident *ti= new (thd->mem_root) Table_ident(unit);
  if (ti == NULL)
    return NULL;
  if (!(res= curr_sel->add_table_to_list(thd, ti, alias, 0,
                                         TL_READ, MDL_SHARED_READ)))
    return NULL;
  if (for_system_time)
  {
    res->vers_conditions= vers_conditions;
  }
  return res;
}

TABLE_LIST *LEX::parsed_derived_unit(SELECT_LEX_UNIT *unit,
                                     int for_system_time,
                                     LEX_CSTRING *alias)
{
  TABLE_LIST *res;
  derived_tables|= DERIVED_SUBQUERY;
  unit->first_select()->set_linkage(DERIVED_TABLE_TYPE);

  // Add the subtree of subquery to the current SELECT_LEX
  SELECT_LEX *curr_sel= select_stack_head();
  DBUG_ASSERT(current_select == curr_sel);
  curr_sel->register_unit(unit, &curr_sel->context);
  curr_sel->add_statistics(unit);

  Table_ident *ti= new (thd->mem_root) Table_ident(unit);
  if (ti == NULL)
    return NULL;
  if (!(res= curr_sel->add_table_to_list(thd, ti, alias, 0,
                                         TL_READ, MDL_SHARED_READ)))
    return NULL;
  if (for_system_time)
  {
    res->vers_conditions= vers_conditions;
  }
  return res;
}

bool LEX::parsed_create_view(SELECT_LEX_UNIT *unit, int check)
{
  SQL_I_List<TABLE_LIST> *save= &first_select_lex()->table_list;
  set_main_unit(unit);
  if (check_main_unit_semantics())
    return true;
  first_select_lex()->table_list.push_front(save);
  current_select= first_select_lex();
  size_t len= thd->m_parser_state->m_lip.get_cpp_ptr() -
    create_view->select.str;
  void *create_view_select= thd->memdup(create_view->select.str, len);
  create_view->select.length= len;
  create_view->select.str= (char *) create_view_select;
  size_t not_used;
  trim_whitespace(thd->charset(),
      &create_view->select, &not_used);
  create_view->check= check;
  parsing_options.allows_variable= TRUE;
  return false;
}

bool LEX::select_finalize(st_select_lex_unit *expr)
{
  sql_command= SQLCOM_SELECT;
  selects_allow_into= TRUE;
  selects_allow_procedure= TRUE;
  set_main_unit(expr);
  return check_main_unit_semantics();
}


9479 9480 9481 9482 9483 9484
bool LEX::select_finalize(st_select_lex_unit *expr, Lex_select_lock l)
{
  return expr->set_lock_to_the_last_select(l) ||
         select_finalize(expr);
}

9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527
/*
  "IN" and "EXISTS" subselect can appear in two statement types:

  1. Statements that can have table columns, such as SELECT, DELETE, UPDATE
  2. Statements that cannot have table columns, e.g:
     RETURN ((1) IN (SELECT * FROM t1))
     IF ((1) IN (SELECT * FROM t1))

  Statements of the first type call master_select_push() in the beginning.
  In such case everything is properly linked.

  Statements of the second type do not call mastr_select_push().
  Here we catch the second case and relink thd->lex->builtin_select and
  select_lex to properly point to each other.

  QQ: Shouldn't subselects of other type also call relink_hack()?
  QQ: Can we do it at constructor time instead?
*/

void LEX::relink_hack(st_select_lex *select_lex)
{
  if (!select_stack_top) // Statements of the second type
  {
    if (!select_lex->get_master()->get_master())
      ((st_select_lex *) select_lex->get_master())->
        set_master(&builtin_select);
    if (!builtin_select.get_slave())
      builtin_select.set_slave(select_lex->get_master());
  }
}



bool SELECT_LEX_UNIT::set_lock_to_the_last_select(Lex_select_lock l)
{
  if (l.defined_lock)
  {
    SELECT_LEX *sel= first_select();
    while (sel->next_select())
      sel= sel->next_select();
    if (sel->braces)
    {
      my_error(ER_WRONG_USAGE, MYF(0), "lock options",
9528
               "SELECT in brackets");
9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547
      return TRUE;
    }
    l.set_to(sel);
  }
  return FALSE;
}

/**
  Generate unique name for generated derived table for this SELECT
*/

bool SELECT_LEX::make_unique_derived_name(THD *thd, LEX_CSTRING *alias)
{
  // uint32 digits + two underscores + trailing '\0'
  char buff[MAX_INT_WIDTH + 2 + 1];
  alias->length= my_snprintf(buff, sizeof(buff), "__%u", select_number);
  alias->str= thd->strmake(buff, alias->length);
  return !alias->str;
}
9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603


/*
  Make a new sp_instr_stmt and set its m_query to a concatenation
  of two strings.
*/
bool LEX::new_sp_instr_stmt(THD *thd,
                            const LEX_CSTRING &prefix,
                            const LEX_CSTRING &suffix)
{
  LEX_STRING qbuff;
  sp_instr_stmt *i;

  if (!(i= new (thd->mem_root) sp_instr_stmt(sphead->instructions(),
                                             spcont, this)))
    return true;

  qbuff.length= prefix.length + suffix.length;
  if (!(qbuff.str= (char*) alloc_root(thd->mem_root, qbuff.length + 1)))
    return true;
  memcpy(qbuff.str, prefix.str, prefix.length);
  strmake(qbuff.str + prefix.length, suffix.str, suffix.length);
  i->m_query= qbuff;
  return sphead->add_instr(i);
}


bool LEX::sp_proc_stmt_statement_finalize_buf(THD *thd, const LEX_CSTRING &qbuf)
{
  sphead->m_flags|= sp_get_flags_for_command(this);
  /* "USE db" doesn't work in a procedure */
  if (unlikely(sql_command == SQLCOM_CHANGE_DB))
  {
    my_error(ER_SP_BADSTATEMENT, MYF(0), "USE");
    return true;
  }
  /*
    Don't add an instruction for SET statements, since all
    instructions for them were already added during processing
    of "set" rule.
  */
  DBUG_ASSERT(sql_command != SQLCOM_SET_OPTION || var_list.is_empty());
  if (sql_command != SQLCOM_SET_OPTION)
    return new_sp_instr_stmt(thd, empty_clex_str, qbuf);
  return false;
}


bool LEX::sp_proc_stmt_statement_finalize(THD *thd, bool no_lookahead)
{
  // Extract the query statement from the tokenizer
  Lex_input_stream *lip= &thd->m_parser_state->m_lip;
  Lex_cstring qbuf(sphead->m_tmp_query, no_lookahead ? lip->get_ptr() :
                                                       lip->get_tok_start());
  return LEX::sp_proc_stmt_statement_finalize_buf(thd, qbuf);
}
9604 9605 9606 9607


/**
  @brief
9608
    Extract the condition that can be pushed into WHERE clause
9609 9610

  @param thd             the thread handle
9611 9612 9613
  @param cond            the condition from which to extract a pushed condition
  @param remaining_cond  IN/OUT the condition that will remain of cond after
                         the extraction
9614
  @param transformer     the transformer callback function to be
9615 9616
                         applied to the fields of the condition so it
                         can be pushed`
9617 9618 9619
  @param arg             parameter to be passed to the transformer

  @details
9620 9621 9622
    This function builds the most restrictive condition depending only on
    the fields used in the GROUP BY of this SELECT. These fields were
    collected before in grouping_tmp_fields list of this SELECT.
9623

9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636
    First this method checks if this SELECT doesn't have any aggregation
    functions and has no GROUP BY clause. If so cond can be entirely pushed
    into WHERE.

    Otherwise the method checks if there is a condition depending only on
    grouping fields that can be extracted from cond.

    The condition that can be pushed into WHERE should be transformed.
    It is done by transformer.

    The extracted condition is saved in cond_pushed_into_where of this select.
    cond can remain un empty after the extraction of the condition that can be
    pushed into WHERE. It is saved in remaining_cond.
9637 9638 9639 9640 9641 9642

  @note
    This method is called for pushdown conditions into materialized
    derived tables/views optimization.
    Item::derived_field_transformer_for_where is passed as the actual
    callback function.
9643
    Also it is called for pushdown into materialized IN subqueries.
9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658
    Item::in_subq_field_transformer_for_where is passed as the actual
    callback function.
*/

void st_select_lex::pushdown_cond_into_where_clause(THD *thd, Item *cond,
                                                    Item **remaining_cond,
                                                    Item_transformer transformer,
                                                    uchar *arg)
{
  if (!cond_pushdown_is_allowed())
    return;
  thd->lex->current_select= this;
  if (have_window_funcs())
  {
    Item *cond_over_partition_fields;
9659
    check_cond_extraction_for_grouping_fields(thd, cond);
9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690
    cond_over_partition_fields=
      build_cond_for_grouping_fields(thd, cond, true);
    if (cond_over_partition_fields)
      cond_over_partition_fields= cond_over_partition_fields->transform(thd,
                                &Item::grouping_field_transformer_for_where,
                                (uchar*) this);
    if (cond_over_partition_fields)
    {
      cond_over_partition_fields->walk(
        &Item::cleanup_excluding_const_fields_processor, 0, 0);
      cond_pushed_into_where= cond_over_partition_fields;
    }

    return;
  }

  if (!join->group_list && !with_sum_func)
  {
    cond=
      cond->transform(thd, transformer, arg);
    if (cond)
    {
      cond->walk(
        &Item::cleanup_excluding_const_fields_processor, 0, 0);
      cond_pushed_into_where= cond;
    }

    return;
  }

  /*
9691 9692
    Figure out what can be extracted from cond and pushed into
    the WHERE clause of this select.
9693 9694
  */
  Item *cond_over_grouping_fields;
9695
  check_cond_extraction_for_grouping_fields(thd, cond);
9696 9697 9698 9699
  cond_over_grouping_fields=
    build_cond_for_grouping_fields(thd, cond, true);

  /*
9700 9701
    Transform references to the columns of condition that can be pushed
    into WHERE so it can be pushed.
9702 9703 9704 9705 9706 9707 9708 9709 9710 9711
  */
  if (cond_over_grouping_fields)
    cond_over_grouping_fields= cond_over_grouping_fields->transform(thd,
                            &Item::grouping_field_transformer_for_where,
                            (uchar*) this);

  if (cond_over_grouping_fields)
  {

    /*
9712
      Remove top conjuncts in cond that has been pushed into the WHERE
9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729
      clause of this select
    */
    cond= remove_pushed_top_conjuncts(thd, cond);

    cond_over_grouping_fields->walk(
      &Item::cleanup_excluding_const_fields_processor, 0, 0);
    cond_pushed_into_where= cond_over_grouping_fields;
  }

  *remaining_cond= cond;
}


/**
  @brief
    Mark OR-conditions as non-pushable to avoid repeatable pushdown

9730
  @param cond  the processed condition
9731 9732

  @details
9733 9734 9735 9736 9737
    Consider pushdown into the materialized derived table/view.
    Consider OR condition that can be pushed into HAVING and some
    parts of this OR condition that can be pushed into WHERE.

    On example:
9738 9739 9740 9741 9742 9743 9744 9745 9746 9747

    SELECT *
    FROM t1,
    (
      SELECT a,MAX(c) AS m_c
      GROUP BY a
    ) AS dt
    WHERE ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3)) AND
          (t1.a=v1.a);

9748 9749 9750 9751 9752 9753 9754 9755 9756

    Here ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3)) or1
    can be pushed down into the HAVING of the materialized
    derived table dt.

    (dt.a>2) OR (dt.a<3) part of or1 depends only on grouping fields
    of dt and can be pushed into WHERE.

    As a result:
9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769

    SELECT *
    FROM t1,
    (
      SELECT a,MAX(c) AS m_c
      WHERE (dt.a>2) OR (dt.a<3)
      GROUP BY a
      HAVING ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3))
    ) AS dt
    WHERE ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3)) AND
          (t1.a=v1.a);


9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781
    Here (dt.a>2) OR (dt.a<3) also remains in HAVING of dt.
    When SELECT that defines df is processed HAVING pushdown optimization
    is made. In HAVING pushdown optimization it will extract
    (dt.a>2) OR (dt.a<3) condition from or1 again and push it into WHERE.
    This will cause duplicate conditions in WHERE of dt.

    To avoid repeatable pushdown such OR conditions as or1 describen
    above are marked with NO_EXTRACTION_FL.

  @note
    This method is called for pushdown into materialized
    derived tables/views/IN subqueries optimization.
9782 9783
*/

9784
void mark_or_conds_to_avoid_pushdown(Item *cond)
9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804
{
  if (cond->type() == Item::COND_ITEM &&
      ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
  {
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
    Item *item;
    while ((item=li++))
    {
      if (item->type() == Item::COND_ITEM &&
          ((Item_cond*) item)->functype() == Item_func::COND_OR_FUNC)
        item->set_extraction_flag(NO_EXTRACTION_FL);
    }
  }
  else if (cond->type() == Item::COND_ITEM &&
          ((Item_cond*) cond)->functype() == Item_func::COND_OR_FUNC)
    cond->set_extraction_flag(NO_EXTRACTION_FL);
}

/**
  @brief
9805
    Get condition that can be pushed from HAVING into WHERE
9806

9807 9808
  @param thd   the thread handle
  @param cond  the condition from which to extract the condition
9809 9810

  @details
9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843
    The method collects in attach_to_conds list conditions from cond
    that can be pushed from HAVING into WHERE.

    Conditions that can be pushed were marked with FULL_EXTRACTION_FL in
    check_cond_extraction_for_grouping_fields() method.
    Conditions that can't be pushed were marked with NO_EXTRACTION_FL.
    Conditions which parts can be pushed weren't marked.

    There are two types of conditions that can be pushed:
    1. Condition that can be simply moved from HAVING
       (if cond is marked with FULL_EXTRACTION_FL or
           cond is an AND condition and some of its parts are marked with
           FULL_EXTRACTION_FL)
       In this case condition is transformed and pushed into attach_to_conds
       list.
    2. Part of some other condition c1 that can't be entirely pushed
       (if с1 isn't marked with any flag).

       For example:

       SELECT t1.a,MAX(t1.b),t1.c
       FROM t1
       GROUP BY t1.a
       HAVING ((t1.a > 5) AND (t1.c < 3)) OR (t1.a = 3);

       Here (t1.a > 5) OR (t1.a = 3) from HAVING can be pushed into WHERE.

       In this case build_pushable_cond() is called for c1.
       This method builds a clone of the c1 part that can be pushed.

    Transformation mentioned above is made with multiple_equality_transformer
    transformer. It transforms all multiple equalities in the extracted
    condition into the set of equalities.
9844 9845

  @note
9846 9847 9848 9849
    Conditions that can be pushed are collected in attach_to_conds in this way:
    1. if cond is an AND condition its parts that can be pushed into WHERE
       are added to attach_to_conds list separately.
    2. in all other cases conditions are pushed into the list entirely.
9850 9851 9852 9853 9854 9855 9856

  @retval
    true  - if an error occurs
    false - otherwise
*/

bool
9857
st_select_lex::build_pushable_cond_for_having_pushdown(THD *thd, Item *cond)
9858
{
9859
  List<Item> equalities;
9860

9861
  /* Condition can't be pushed */
9862 9863 9864
  if (cond->get_extraction_flag() == NO_EXTRACTION_FL)
    return false;

9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909
  /**
    Condition can be pushed entirely.
    Transform its multiple equalities and add to attach_to_conds list.
  */
  if (cond->get_extraction_flag() == FULL_EXTRACTION_FL)
  {
    Item *result= cond->transform(thd,
                                  &Item::multiple_equality_transformer,
                                  (uchar *)this);
    if (!result)
      return true;
    if (result->type() == Item::COND_ITEM &&
        ((Item_cond*) result)->functype() == Item_func::COND_AND_FUNC)
    {
      List_iterator<Item> li(*((Item_cond*) result)->argument_list());
      Item *item;
      while ((item=li++))
      {
        if (attach_to_conds.push_back(item, thd->mem_root))
          return true;
      }
    }
    else
    {
      if (attach_to_conds.push_back(result, thd->mem_root))
        return true;
    }
    return false;
  }

  /**
    There is no flag set for this condition. It means that some
    part of this condition can be pushed.
  */
  if (cond->type() != Item::COND_ITEM)
    return false;
  if (((Item_cond *)cond)->functype() != Item_cond::COND_AND_FUNC)
  {
    Item *fix= cond->build_pushable_cond(thd, 0, 0);
    if (!fix)
      return false;
    if (attach_to_conds.push_back(fix, thd->mem_root))
      return true;
  }
  else
9910 9911 9912 9913 9914 9915 9916
  {
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
    Item *item;
    while ((item=li++))
    {
      if (item->get_extraction_flag() == NO_EXTRACTION_FL)
        continue;
9917
      else if (item->get_extraction_flag() == FULL_EXTRACTION_FL)
9918
      {
9919 9920 9921 9922 9923
        Item *result= item->transform(thd,
                                      &Item::multiple_equality_transformer,
                                      (uchar *)item);

        if (!result)
9924
          return true;
9925 9926
        if (result->type() == Item::COND_ITEM &&
           ((Item_cond*) result)->functype() == Item_func::COND_AND_FUNC)
9927
        {
9928 9929 9930
          List_iterator<Item> li(*((Item_cond*) result)->argument_list());
          Item *item;
          while ((item=li++))
9931
          {
9932
            if (attach_to_conds.push_back(item, thd->mem_root))
9933 9934 9935
              return true;
          }
        }
9936 9937 9938 9939 9940
        else
        {
          if (attach_to_conds.push_back(result, thd->mem_root))
            return true;
        }
9941
      }
9942
      else
9943
      {
9944 9945 9946 9947 9948
        Item *fix= item->build_pushable_cond(thd, 0, 0);
        if (!fix)
          continue;
        if (attach_to_conds.push_back(fix, thd->mem_root))
          return true;
9949 9950 9951 9952 9953 9954 9955 9956
      }
    }
  }
  return false;
}


/**
9957
  Check if item is equal to some field in Field_pair 'field_pair'
9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982
  from 'pair_list' and return found 'field_pair' if it exists.
*/

Field_pair *get_corresponding_field_pair(Item *item,
                                         List<Field_pair> pair_list)
{
  DBUG_ASSERT(item->type() == Item::FIELD_ITEM ||
              (item->type() == Item::REF_ITEM &&
               ((((Item_ref *) item)->ref_type() == Item_ref::VIEW_REF) ||
               (((Item_ref *) item)->ref_type() == Item_ref::REF))));

  List_iterator<Field_pair> it(pair_list);
  Field_pair *field_pair;
  Item_field *field_item= (Item_field *) (item->real_item());
  while ((field_pair= it++))
  {
    if (field_item->field == field_pair->field)
      return field_pair;
  }
  return NULL;
}


/**
  @brief
9983
    Collect fields from multiple equalities which are equal to grouping
9984

9985
  @param thd  the thread handle
9986 9987

  @details
9988 9989 9990
    This method checks if multiple equalities of the WHERE clause contain
    fields from GROUP BY of this SELECT. If so all fields of such multiple
    equalities are collected in grouping_tmp_fields list without repetitions.
9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016

  @retval
    true  - if an error occurs
    false - otherwise
*/

bool st_select_lex::collect_fields_equal_to_grouping(THD *thd)
{
  if (!join->cond_equal || join->cond_equal->is_empty())
    return false;

  List_iterator_fast<Item_equal> li(join->cond_equal->current_level);
  Item_equal *item_equal;

  while ((item_equal= li++))
  {
    Item_equal_fields_iterator it(*item_equal);
    Item *item;
    while ((item= it++))
    {
      if (get_corresponding_field_pair(item, grouping_tmp_fields))
        break;
    }
    if (!item)
      break;

Igor Babaev's avatar
Igor Babaev committed
10017
    it.rewind();
10018 10019
    while ((item= it++))
    {
Igor Babaev's avatar
Igor Babaev committed
10020
      if (get_corresponding_field_pair(item, grouping_tmp_fields))
10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033
        continue;
      Field_pair *grouping_tmp_field=
        new Field_pair(((Item_field *)item->real_item())->field, item);
      if (grouping_tmp_fields.push_back(grouping_tmp_field, thd->mem_root))
        return true;
    }
  }
  return false;
}


/**
  @brief
10034
    Remove marked top conjuncts of HAVING for having pushdown
10035

10036 10037
  @param thd   the thread handle
  @param cond  the condition which subformulas are to be removed
10038 10039

  @details
10040 10041
    This method removes from cond all subformulas that can be moved from HAVING
    into WHERE.
10042 10043 10044 10045 10046 10047 10048 10049

  @retval
     condition without removed subformulas
     0 if the whole 'cond' is removed
*/

Item *remove_pushed_top_conjuncts_for_having(THD *thd, Item *cond)
{
10050 10051 10052 10053 10054 10055 10056
  /* Nothing to extract */
  if (cond->get_extraction_flag() == NO_EXTRACTION_FL)
  {
    cond->clear_extraction_flag();
    return cond;
  }
  /* cond can be pushed in WHERE entirely */
10057 10058 10059 10060 10061 10062
  if (cond->get_extraction_flag() == FULL_EXTRACTION_FL)
  {
    cond->clear_extraction_flag();
    return 0;
  }

10063 10064 10065
  /* Some parts of cond can be pushed */
  if (cond->type() == Item::COND_ITEM &&
      ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
10066
  {
10067
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
10068
    Item *item;
10069
    while ((item=li++))
10070
    {
10071
      if (item->get_extraction_flag() == NO_EXTRACTION_FL)
10072
        item->clear_extraction_flag();
10073 10074
      else if (item->get_extraction_flag() == FULL_EXTRACTION_FL)
      {
10075 10076 10077 10078
        if (item->type() == Item::FUNC_ITEM &&
            ((Item_func*) item)->functype() == Item_func::MULT_EQUAL_FUNC)
          item->set_extraction_flag(DELETION_FL);
        else
10079 10080
        {
          item->clear_extraction_flag();
10081
          li.remove();
10082
        }
10083 10084
      }
    }
10085
    switch (((Item_cond*) cond)->argument_list()->elements)
10086 10087 10088 10089
    {
    case 0:
      return 0;
    case 1:
10090
      return (((Item_cond*) cond)->argument_list()->head());
10091 10092 10093 10094 10095 10096 10097 10098 10099 10100
    default:
      return cond;
    }
  }
  return cond;
}


/**
  @brief
10101
    Extract condition that can be pushed from HAVING into WHERE
10102 10103 10104 10105 10106 10107

  @param thd           the thread handle
  @param having        the HAVING clause of this select
  @param having_equal  multiple equalities of HAVING

  @details
10108 10109 10110 10111 10112 10113
    This method builds a set of conditions dependent only on
    fields used in the GROUP BY of this select (directly or indirectly
    through equalities). These conditions are extracted from the HAVING
    clause of this select.
    The method saves these conditions into attach_to_conds list and removes
    from HAVING conditions that can be entirely pushed into WHERE.
10114

10115
    Example of the HAVING pushdown transformation:
10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129

    SELECT t1.a,MAX(t1.b)
    FROM t1
    GROUP BY t1.a
    HAVING (t1.a>2) AND (MAX(c)>12);

    =>

    SELECT t1.a,MAX(t1.b)
    FROM t1
    WHERE (t1.a>2)
    GROUP BY t1.a
    HAVING (MAX(c)>12);

10130 10131 10132 10133
    In this method (t1.a>2) is not attached to the WHERE clause.
    It is pushed into the attach_to_conds list to be attached to
    the WHERE clause later.

10134 10135 10136
    In details:
    1. Collect fields used in the GROUP BY grouping_fields of this SELECT
    2. Collect fields equal to grouping_fields from the WHERE clause
Igor Babaev's avatar
Igor Babaev committed
10137 10138 10139
       of this SELECT and add them to the grouping_fields list.
    3. Extract the most restrictive condition from the HAVING clause of this
       select that depends only on the grouping fields (directly or indirectly
10140 10141 10142 10143 10144 10145 10146 10147 10148
       through equality).
       If the extracted condition is an AND condition it is transformed into a
       list of all its conjuncts saved in attach_to_conds. Otherwise,
       the condition is put into attach_to_conds as the only its element.
    4. Remove conditions from HAVING clause that can be entirely pushed
       into WHERE.
       Multiple equalities are not removed but marked with DELETION_FL flag.
       They will be deleted later in substitite_for_best_equal_field() called
       for the HAVING condition.
10149
    5. Unwrap fields wrapped in Item_ref wrappers contained in the condition
10150
       of attach_to_conds so the condition could be pushed into WHERE.
10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169

  @note
    This method is similar to st_select_lex::pushdown_cond_into_where_clause().

  @retval TRUE   if an error occurs
  @retval FALSE  otherwise
*/

Item *st_select_lex::pushdown_from_having_into_where(THD *thd, Item *having)
{
  if (!having || !group_list.first)
    return having;
  if (!cond_pushdown_is_allowed())
    return having;

  st_select_lex *save_curr_select= thd->lex->current_select;
  thd->lex->current_select= this;

  /*
Igor Babaev's avatar
Igor Babaev committed
10170
    1. Collect fields used in the GROUP BY grouping fields of this SELECT
10171
    2. Collect fields equal to grouping_fields from the WHERE clause
Igor Babaev's avatar
Igor Babaev committed
10172
       of this SELECT and add them to the grouping fields list.
10173
  */
Igor Babaev's avatar
Igor Babaev committed
10174 10175
  if (collect_grouping_fields(thd) ||
      collect_fields_equal_to_grouping(thd))
10176 10177 10178
    return having;

  /*
Igor Babaev's avatar
Igor Babaev committed
10179 10180
    3. Extract the most restrictive condition from the HAVING clause of this
       select that depends only on the grouping fields (directly or indirectly
10181 10182 10183 10184
       through equality).
       If the extracted condition is an AND condition it is transformed into a
       list of all its conjuncts saved in attach_to_conds. Otherwise,
       the condition is put into attach_to_conds as the only its element.
10185 10186 10187
  */
  List_iterator_fast<Item> it(attach_to_conds);
  Item *item;
10188
  check_cond_extraction_for_grouping_fields(thd, having);
Igor Babaev's avatar
Igor Babaev committed
10189
  if (build_pushable_cond_for_having_pushdown(thd, having))
10190 10191 10192 10193
  {
    attach_to_conds.empty();
    goto exit;
  }
10194 10195
  if (!attach_to_conds.elements)
    goto exit;
10196

10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236
  /*
    4. Remove conditions from HAVING clause that can be entirely pushed
       into WHERE.
       Multiple equalities are not removed but marked with DELETION_FL flag.
       They will be deleted later in substitite_for_best_equal_field() called
       for the HAVING condition.
  */
  having= remove_pushed_top_conjuncts_for_having(thd, having);

  /*
    Change join->cond_equal which points to the multiple equalities of
    the top level of HAVING.
    Removal of AND conditions may leave only one conjunct in HAVING.

    Example 1:
    SELECT *
    FROM t1
    GROUP BY t1.a
    (t1.a < 2) AND (t1.b = 2)

    (t1.a < 2) is pushed into WHERE.
    join->cond_equal should point on (t1.b = 2) multiple equality now.

    Example 2:
    SELECT *
    FROM t1
    GROUP BY t1.a
    (t1.a = 2) AND (t1.b < 2)

    (t1.a = 2) is pushed into WHERE.
    join->cond_equal should be NULL now.
  */
  if (having &&
      having->type() == Item::FUNC_ITEM &&
      ((Item_func*) having)->functype() == Item_func::MULT_EQUAL_FUNC)
    join->having_equal= new (thd->mem_root) COND_EQUAL((Item_equal *)having,
                                                       thd->mem_root);
  else if (!having ||
           having->type() != Item::COND_ITEM ||
           ((Item_cond *)having)->functype() != Item_cond::COND_AND_FUNC)
10237
    join->having_equal= 0;
10238 10239

  /*
10240
    5. Unwrap fields wrapped in Item_ref wrappers contained in the condition
10241 10242 10243 10244 10245 10246 10247 10248 10249
       of attach_to_conds so the condition could be pushed into WHERE.
  */
  it.rewind();
  while ((item=it++))
  {
    item= item->transform(thd,
                          &Item::field_transformer_for_having_pushdown,
                          (uchar *)this);

10250
    if (item->walk(&Item:: cleanup_processor, 0, STOP_PTR) ||
10251
        item->fix_fields(thd, NULL))
10252
    {
10253 10254
      attach_to_conds.empty();
      goto exit;
10255 10256 10257 10258 10259 10260 10261
    }
  }
exit:
  thd->lex->current_select= save_curr_select;
  return having;
}

10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308

bool LEX::stmt_install_plugin(const DDL_options_st &opt,
                              const Lex_ident_sys_st &name,
                              const LEX_CSTRING &soname)
{
  create_info.init();
  if (add_create_options_with_check(opt))
    return true;
  sql_command= SQLCOM_INSTALL_PLUGIN;
  comment= name;
  ident= soname;
  return false;
}


void LEX::stmt_install_plugin(const LEX_CSTRING &soname)
{
  sql_command= SQLCOM_INSTALL_PLUGIN;
  comment= null_clex_str;
  ident= soname;
}


bool LEX::stmt_uninstall_plugin_by_name(const DDL_options_st &opt,
                                        const Lex_ident_sys_st &name)
{
  check_opt.init();
  if (add_create_options_with_check(opt))
    return true;
  sql_command= SQLCOM_UNINSTALL_PLUGIN;
  comment= name;
  ident= null_clex_str;
  return false;
}


bool LEX::stmt_uninstall_plugin_by_soname(const DDL_options_st &opt,
                                          const LEX_CSTRING &soname)
{
  check_opt.init();
  if (add_create_options_with_check(opt))
    return true;
  sql_command= SQLCOM_UNINSTALL_PLUGIN;
  comment= null_clex_str;
  ident= soname;
  return false;
}
10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355


bool LEX::stmt_prepare_validate(const char *stmt_type)
{
  if (unlikely(table_or_sp_used()))
  {
    my_error(ER_SUBQUERIES_NOT_SUPPORTED, MYF(0), stmt_type);
    return true;
  }
  return check_main_unit_semantics();
}


bool LEX::stmt_prepare(const Lex_ident_sys_st &ident, Item *code)
{
  sql_command= SQLCOM_PREPARE;
  if (stmt_prepare_validate("PREPARE..FROM"))
    return true;
  prepared_stmt.set(ident, code, NULL);
  return false;
}


bool LEX::stmt_execute_immediate(Item *code, List<Item> *params)
{
  sql_command= SQLCOM_EXECUTE_IMMEDIATE;
  if (stmt_prepare_validate("EXECUTE IMMEDIATE"))
    return true;
  static const Lex_ident_sys immediate(STRING_WITH_LEN("IMMEDIATE"));
  prepared_stmt.set(immediate, code, params);
  return false;
}


bool LEX::stmt_execute(const Lex_ident_sys_st &ident, List<Item> *params)
{
  sql_command= SQLCOM_EXECUTE;
  prepared_stmt.set(ident, NULL, params);
  return stmt_prepare_validate("EXECUTE..USING");
}


void LEX::stmt_deallocate_prepare(const Lex_ident_sys_st &ident)
{
  sql_command= SQLCOM_DEALLOCATE_PREPARE;
  prepared_stmt.set(ident, NULL, NULL);
}
10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393


bool LEX::stmt_alter_table_exchange_partition(Table_ident *table)
{
  DBUG_ASSERT(sql_command == SQLCOM_ALTER_TABLE);
  first_select_lex()->db= table->db;
  if (first_select_lex()->db.str == NULL &&
      copy_db_to(&first_select_lex()->db))
    return true;
  name= table->table;
  alter_info.partition_flags|= ALTER_PARTITION_EXCHANGE;
  if (!first_select_lex()->add_table_to_list(thd, table, NULL,
                                             TL_OPTION_UPDATING,
                                             TL_READ_NO_INSERT,
                                             MDL_SHARED_NO_WRITE))
    return true;
  DBUG_ASSERT(!m_sql_cmd);
  m_sql_cmd= new (thd->mem_root) Sql_cmd_alter_table_exchange_partition();
  return m_sql_cmd == NULL;
}


void LEX::stmt_purge_to(const LEX_CSTRING &to)
{
  type= 0;
  sql_command= SQLCOM_PURGE;
  to_log= to.str;
}


bool LEX::stmt_purge_before(Item *item)
{
  type= 0;
  sql_command= SQLCOM_PURGE_BEFORE;
  value_list.empty();
  value_list.push_front(item, thd->mem_root);
  return check_main_unit_semantics();
}
10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430


bool LEX::stmt_create_udf_function(const DDL_options_st &options,
                                   enum_sp_aggregate_type agg_type,
                                   const Lex_ident_sys_st &name,
                                   Item_result return_type,
                                   const LEX_CSTRING &soname)
{
  if (stmt_create_function_start(options))
    return true;

   if (unlikely(is_native_function(thd, &name)))
   {
     my_error(ER_NATIVE_FCT_NAME_COLLISION, MYF(0), name.str);
     return true;
   }
   sql_command= SQLCOM_CREATE_FUNCTION;
   udf.name= name;
   udf.returns= return_type;
   udf.dl= soname.str;
   udf.type= agg_type == GROUP_AGGREGATE ? UDFTYPE_AGGREGATE :
                                           UDFTYPE_FUNCTION;
   stmt_create_routine_finalize();
   return false;
}


bool LEX::stmt_create_stored_function_start(const DDL_options_st &options,
                                            enum_sp_aggregate_type agg_type,
                                            const sp_name *spname)
{
  if (stmt_create_function_start(options) ||
      unlikely(!make_sp_head_no_recursive(thd, spname,
                                          &sp_handler_function, agg_type)))
    return true;
  return false;
}
10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446


Spvar_definition *LEX::row_field_name(THD *thd, const Lex_ident_sys_st &name)
{
  Spvar_definition *res;
  if (unlikely(check_string_char_length(&name, 0, NAME_CHAR_LEN,
                                        system_charset_info, 1)))
  {
    my_error(ER_TOO_LONG_IDENT, MYF(0), name.str);
    return NULL;
  }
  if (unlikely(!(res= new (thd->mem_root) Spvar_definition())))
    return NULL;
  init_last_field(res, &name, thd->variables.collation_database);
  return res;
}