1 /* Copyright (c) 2000, 2019, Oracle and/or its affiliates.
2    Copyright (c) 2009, 2021, MariaDB Corporation.
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; version 2 of the License.
7 
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12 
13    You should have received a copy of the GNU General Public License
14    along with this program; if not, write to the Free Software
15    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335  USA */
16 
17 
18 /* A lexical scanner on a temporary buffer with a yacc interface */
19 
20 #define MYSQL_LEX 1
21 #include "mariadb.h"
22 #include "sql_priv.h"
23 #include "sql_class.h"                          // sql_lex.h: SQLCOM_END
24 #include "sql_lex.h"
25 #include "sql_parse.h"                          // add_to_list
26 #include "item_create.h"
27 #include <m_ctype.h>
28 #include <hash.h>
29 #include "sp_head.h"
30 #include "sp.h"
31 #include "sql_select.h"
32 #include "sql_cte.h"
33 #include "sql_signal.h"
34 #include "sql_derived.h"
35 #include "sql_truncate.h"                      // Sql_cmd_truncate_table
36 #include "sql_admin.h"                         // Sql_cmd_analyze/Check..._table
37 #include "sql_partition.h"
38 #include "sql_partition_admin.h"               // Sql_cmd_alter_table_*_part
39 #include "event_parse_data.h"
40 
parse_error(uint err_number)41 void LEX::parse_error(uint err_number)
42 {
43   thd->parse_error(err_number);
44 }
45 
46 
47 /**
48   LEX_STRING constant for null-string to be used in parser and other places.
49 */
50 const LEX_STRING empty_lex_str=   {(char *) "", 0};
51 const LEX_CSTRING null_clex_str=  {NULL, 0};
52 const LEX_CSTRING empty_clex_str= {"", 0};
53 const LEX_CSTRING star_clex_str=  {"*", 1};
54 const LEX_CSTRING param_clex_str= {"?", 1};
55 
56 
57 /**
58   Helper action for a case expression statement (the expr in 'CASE expr').
59   This helper is used for 'searched' cases only.
60   @param lex the parser lex context
61   @param expr the parsed expression
62   @return 0 on success
63 */
64 
case_stmt_action_expr()65 int sp_expr_lex::case_stmt_action_expr()
66 {
67   int case_expr_id= spcont->register_case_expr();
68   sp_instr_set_case_expr *i;
69 
70   if (spcont->push_case_expr_id(case_expr_id))
71     return 1;
72 
73   i= new (thd->mem_root)
74     sp_instr_set_case_expr(sphead->instructions(), spcont, case_expr_id,
75                            get_item(), this);
76 
77   sphead->add_cont_backpatch(i);
78   return sphead->add_instr(i);
79 }
80 
81 /**
82   Helper action for a case when condition.
83   This helper is used for both 'simple' and 'searched' cases.
84   @param lex the parser lex context
85   @param when the parsed expression for the WHEN clause
86   @param simple true for simple cases, false for searched cases
87 */
88 
case_stmt_action_when(bool simple)89 int sp_expr_lex::case_stmt_action_when(bool simple)
90 {
91   uint ip= sphead->instructions();
92   sp_instr_jump_if_not *i;
93   Item_case_expr *var;
94   Item *expr;
95 
96   if (simple)
97   {
98     var= new (thd->mem_root)
99          Item_case_expr(thd, spcont->get_current_case_expr_id());
100 
101 #ifdef DBUG_ASSERT_EXISTS
102     if (var)
103     {
104       var->m_sp= sphead;
105     }
106 #endif
107 
108     expr= new (thd->mem_root) Item_func_eq(thd, var, get_item());
109     i= new (thd->mem_root) sp_instr_jump_if_not(ip, spcont, expr, this);
110   }
111   else
112     i= new (thd->mem_root) sp_instr_jump_if_not(ip, spcont, get_item(), this);
113 
114   /*
115     BACKPATCH: Registering forward jump from
116     "case_stmt_action_when" to "case_stmt_action_then"
117     (jump_if_not from instruction 2 to 5, 5 to 8 ... in the example)
118   */
119 
120   return
121     !MY_TEST(i) ||
122     sphead->push_backpatch(thd, i, spcont->push_label(thd, &empty_clex_str, 0)) ||
123     sphead->add_cont_backpatch(i) ||
124     sphead->add_instr(i);
125 }
126 
127 /**
128   Helper action for a case then statements.
129   This helper is used for both 'simple' and 'searched' cases.
130   @param lex the parser lex context
131 */
132 
case_stmt_action_then()133 int LEX::case_stmt_action_then()
134 {
135   uint ip= sphead->instructions();
136   sp_instr_jump *i= new (thd->mem_root) sp_instr_jump(ip, spcont);
137   if (!MY_TEST(i) || sphead->add_instr(i))
138     return 1;
139 
140   /*
141     BACKPATCH: Resolving forward jump from
142     "case_stmt_action_when" to "case_stmt_action_then"
143     (jump_if_not from instruction 2 to 5, 5 to 8 ... in the example)
144   */
145 
146   sphead->backpatch(spcont->pop_label());
147 
148   /*
149     BACKPATCH: Registering forward jump from
150     "case_stmt_action_then" to after END CASE
151     (jump from instruction 4 to 12, 7 to 12 ... in the example)
152   */
153 
154   return sphead->push_backpatch(thd, i, spcont->last_label());
155 }
156 
157 
158 /**
159   Helper action for a SET statement.
160   Used to push a system variable into the assignment list.
161 
162   @param tmp      the system variable with base name
163   @param var_type the scope of the variable
164   @param val      the value being assigned to the variable
165 
166   @return TRUE if error, FALSE otherwise.
167 */
168 
169 bool
set_system_variable(enum enum_var_type var_type,sys_var * sysvar,const Lex_ident_sys_st * base_name,Item * val)170 LEX::set_system_variable(enum enum_var_type var_type,
171                          sys_var *sysvar, const Lex_ident_sys_st *base_name,
172                          Item *val)
173 {
174   set_var *setvar;
175 
176   /* No AUTOCOMMIT from a stored function or trigger. */
177   if (spcont && sysvar == Sys_autocommit_ptr)
178     sphead->m_flags|= sp_head::HAS_SET_AUTOCOMMIT_STMT;
179 
180   if (val && val->type() == Item::FIELD_ITEM &&
181       ((Item_field*)val)->table_name.str)
182   {
183     my_error(ER_WRONG_TYPE_FOR_VAR, MYF(0), sysvar->name.str);
184     return TRUE;
185   }
186 
187   if (!(setvar= new (thd->mem_root) set_var(thd, var_type, sysvar,
188                                             base_name, val)))
189     return TRUE;
190 
191   return var_list.push_back(setvar, thd->mem_root);
192 }
193 
194 
195 /**
196   Helper action for a SET statement.
197   Used to SET a field of NEW row.
198 
199   @param name     the field name
200   @param val      the value being assigned to the row
201 
202   @return TRUE if error, FALSE otherwise.
203 */
204 
set_trigger_new_row(const LEX_CSTRING * name,Item * val)205 bool LEX::set_trigger_new_row(const LEX_CSTRING *name, Item *val)
206 {
207   Item_trigger_field *trg_fld;
208   sp_instr_set_trigger_field *sp_fld;
209 
210   /* QQ: Shouldn't this be field's default value ? */
211   if (! val)
212     val= new (thd->mem_root) Item_null(thd);
213 
214   DBUG_ASSERT(trg_chistics.action_time == TRG_ACTION_BEFORE &&
215               (trg_chistics.event == TRG_EVENT_INSERT ||
216                trg_chistics.event == TRG_EVENT_UPDATE));
217 
218   trg_fld= new (thd->mem_root)
219             Item_trigger_field(thd, current_context(),
220                                Item_trigger_field::NEW_ROW,
221                                *name, UPDATE_ACL, FALSE);
222 
223   if (unlikely(trg_fld == NULL))
224     return TRUE;
225 
226   sp_fld= new (thd->mem_root)
227         sp_instr_set_trigger_field(sphead->instructions(),
228                                    spcont, trg_fld, val, this);
229 
230   if (unlikely(sp_fld == NULL))
231     return TRUE;
232 
233   /*
234     Let us add this item to list of all Item_trigger_field
235     objects in trigger.
236   */
237   trg_table_fields.link_in_list(trg_fld, &trg_fld->next_trg_field);
238 
239   return sphead->add_instr(sp_fld);
240 }
241 
242 
243 /**
244   Create an object to represent a SP variable in the Item-hierarchy.
245 
246   @param  name        The SP variable name.
247   @param  spvar       The SP variable (optional).
248   @param  start_in_q  Start position of the SP variable name in the query.
249   @param  end_in_q    End position of the SP variable name in the query.
250 
251   @remark If spvar is not specified, the name is used to search for the
252           variable in the parse-time context. If the variable does not
253           exist, a error is set and NULL is returned to the caller.
254 
255   @return An Item_splocal object representing the SP variable, or NULL on error.
256 */
257 Item_splocal*
create_item_for_sp_var(const Lex_ident_cli_st * cname,sp_variable * spvar)258 LEX::create_item_for_sp_var(const Lex_ident_cli_st *cname, sp_variable *spvar)
259 {
260   const Sp_rcontext_handler *rh;
261   Item_splocal *item;
262   const char *start_in_q= cname->pos();
263   const char *end_in_q= cname->end();
264   uint pos_in_q, len_in_q;
265   Lex_ident_sys name(thd, cname);
266 
267   if (name.is_null())
268     return NULL;  // EOM
269 
270   /* If necessary, look for the variable. */
271   if (spcont && !spvar)
272     spvar= find_variable(&name, &rh);
273 
274   if (!spvar)
275   {
276     my_error(ER_SP_UNDECLARED_VAR, MYF(0), name.str);
277     return NULL;
278   }
279 
280   DBUG_ASSERT(spcont && spvar);
281 
282   /* Position and length of the SP variable name in the query. */
283   pos_in_q= (uint)(start_in_q - sphead->m_tmp_query);
284   len_in_q= (uint)(end_in_q - start_in_q);
285 
286   item= new (thd->mem_root)
287     Item_splocal(thd, rh, &name, spvar->offset, spvar->type_handler(),
288                  pos_in_q, len_in_q);
289 
290 #ifdef DBUG_ASSERT_EXISTS
291   if (item)
292     item->m_sp= sphead;
293 #endif
294 
295   return item;
296 }
297 
298 
299 /**
300   Helper to resolve the SQL:2003 Syntax exception 1) in <in predicate>.
301   See SQL:2003, Part 2, section 8.4 <in predicate>, Note 184, page 383.
302   This function returns the proper item for the SQL expression
303   <code>left [NOT] IN ( expr )</code>
304   @param thd the current thread
305   @param left the in predicand
306   @param equal true for IN predicates, false for NOT IN predicates
307   @param expr first and only expression of the in value list
308   @return an expression representing the IN predicate.
309 */
handle_sql2003_note184_exception(THD * thd,Item * left,bool equal,Item * expr)310 Item* handle_sql2003_note184_exception(THD *thd, Item* left, bool equal,
311                                        Item *expr)
312 {
313   /*
314     Relevant references for this issue:
315     - SQL:2003, Part 2, section 8.4 <in predicate>, page 383,
316     - SQL:2003, Part 2, section 7.2 <row value expression>, page 296,
317     - SQL:2003, Part 2, section 6.3 <value expression primary>, page 174,
318     - SQL:2003, Part 2, section 7.15 <subquery>, page 370,
319     - SQL:2003 Feature F561, "Full value expressions".
320 
321     The exception in SQL:2003 Note 184 means:
322     Item_singlerow_subselect, which corresponds to a <scalar subquery>,
323     should be re-interpreted as an Item_in_subselect, which corresponds
324     to a <table subquery> when used inside an <in predicate>.
325 
326     Our reading of Note 184 is reccursive, so that all:
327     - IN (( <subquery> ))
328     - IN ((( <subquery> )))
329     - IN '('^N <subquery> ')'^N
330     - etc
331     should be interpreted as a <table subquery>, no matter how deep in the
332     expression the <subquery> is.
333   */
334 
335   Item *result;
336 
337   DBUG_ENTER("handle_sql2003_note184_exception");
338 
339   if (expr->type() == Item::SUBSELECT_ITEM)
340   {
341     Item_subselect *expr2 = (Item_subselect*) expr;
342 
343     if (expr2->substype() == Item_subselect::SINGLEROW_SUBS)
344     {
345       Item_singlerow_subselect *expr3 = (Item_singlerow_subselect*) expr2;
346       st_select_lex *subselect;
347 
348       /*
349         Implement the mandated change, by altering the semantic tree:
350           left IN Item_singlerow_subselect(subselect)
351         is modified to
352           left IN (subselect)
353         which is represented as
354           Item_in_subselect(left, subselect)
355       */
356       subselect= expr3->invalidate_and_restore_select_lex();
357       result= new (thd->mem_root) Item_in_subselect(thd, left, subselect);
358 
359       if (! equal)
360         result = negate_expression(thd, result);
361 
362       DBUG_RETURN(result);
363     }
364   }
365 
366   if (equal)
367     result= new (thd->mem_root) Item_func_eq(thd, left, expr);
368   else
369     result= new (thd->mem_root) Item_func_ne(thd, left, expr);
370 
371   DBUG_RETURN(result);
372 }
373 
374 /**
375   Create a separate LEX for each assignment if in SP.
376 
377   If we are in SP we want have own LEX for each assignment.
378   This is mostly because it is hard for several sp_instr_set
379   and sp_instr_set_trigger instructions share one LEX.
380   (Well, it is theoretically possible but adds some extra
381   overhead on preparation for execution stage and IMO less
382   robust).
383 
384   QQ: May be we should simply prohibit group assignments in SP?
385 
386   @see sp_create_assignment_instr
387 
388   @param thd           Thread context
389   @param pos           The position in the raw SQL buffer
390 */
391 
392 
sp_create_assignment_lex(THD * thd,const char * pos)393 bool sp_create_assignment_lex(THD *thd, const char *pos)
394 {
395   if (thd->lex->sphead)
396   {
397     sp_lex_local *new_lex;
398     if (!(new_lex= new (thd->mem_root) sp_lex_set_var(thd, thd->lex)) ||
399         new_lex->main_select_push())
400       return true;
401     new_lex->sphead->m_tmp_query= pos;
402     return thd->lex->sphead->reset_lex(thd, new_lex);
403   }
404   else
405     if (thd->lex->main_select_push(false))
406       return true;
407   return false;
408 }
409 
410 
411 /**
412   Create a SP instruction for a SET assignment.
413 
414   @see sp_create_assignment_lex
415 
416   @param thd              - Thread context
417   @param no_lookahead     - True if the parser has no lookahead
418   @param need_set_keyword - if a SET statement "SET a=10",
419                             or a direct assignment overwise "a:=10"
420   @return false if success, true otherwise.
421 */
422 
sp_create_assignment_instr(THD * thd,bool no_lookahead,bool need_set_keyword)423 bool sp_create_assignment_instr(THD *thd, bool no_lookahead,
424                                 bool need_set_keyword)
425 {
426   LEX *lex= thd->lex;
427 
428   if (lex->sphead)
429   {
430     if (!lex->var_list.is_empty())
431     {
432       /*
433         - Every variable assignment from the same SET command, e.g.:
434             SET @var1=expr1, @var2=expr2;
435           produce each own sp_create_assignment_instr() call
436           lex->var_list.elements is 1 in this case.
437         - This query:
438             SET TRANSACTION READ ONLY, ISOLATION LEVEL SERIALIZABLE;
439           in translated to:
440             SET tx_read_only=1, tx_isolation=ISO_SERIALIZABLE;
441           but produces a single sp_create_assignment_instr() call
442           which includes the query fragment covering both options.
443       */
444       DBUG_ASSERT(lex->var_list.elements >= 1 && lex->var_list.elements <= 2);
445       /*
446         sql_mode=ORACLE's direct assignment of a global variable
447         is not possible by the grammar.
448       */
449       DBUG_ASSERT(lex->option_type != OPT_GLOBAL || need_set_keyword);
450       /*
451         We have assignment to user or system variable or
452         option setting, so we should construct sp_instr_stmt
453         for it.
454       */
455       Lex_input_stream *lip= &thd->m_parser_state->m_lip;
456 
457       /*
458         Extract the query statement from the tokenizer.  The
459         end is either lip->ptr, if there was no lookahead,
460         lip->tok_end otherwise.
461       */
462       static const LEX_CSTRING setlc= { STRING_WITH_LEN("SET ") };
463       static const LEX_CSTRING setgl= { STRING_WITH_LEN("SET GLOBAL ") };
464       const char *qend= no_lookahead ? lip->get_ptr() : lip->get_tok_end();
465       Lex_cstring qbuf(lex->sphead->m_tmp_query, qend);
466       if (lex->new_sp_instr_stmt(thd,
467                                  lex->option_type == OPT_GLOBAL ? setgl :
468                                  need_set_keyword ?               setlc :
469                                                                   null_clex_str,
470                                  qbuf))
471         return true;
472     }
473     lex->pop_select();
474     if (lex->check_main_unit_semantics())
475     {
476       /*
477         "lex" can be referrenced by:
478         - sp_instr_set                          SET a= expr;
479         - sp_instr_set_row_field                SET r.a= expr;
480         - sp_instr_stmt (just generated above)  SET @a= expr;
481         In this case, "lex" is fully owned by sp_instr_xxx and it will
482         be deleted by the destructor ~sp_instr_xxx().
483         So we should remove "lex" from the stack sp_head::m_lex,
484         to avoid double free.
485         Note, in case "lex" is not owned by any sp_instr_xxx,
486         it's also safe to remove it from the stack right now.
487         So we can remove it unconditionally, without testing lex->sp_lex_in_use.
488       */
489       lex->sphead->restore_lex(thd);
490       return true;
491     }
492     enum_var_type inner_option_type= lex->option_type;
493     if (lex->sphead->restore_lex(thd))
494       return true;
495     /* Copy option_type to outer lex in case it has changed. */
496     thd->lex->option_type= inner_option_type;
497   }
498   else
499     lex->pop_select();
500   return false;
501 }
502 
503 
add_key_to_list(LEX_CSTRING * field_name,enum Key::Keytype type,bool check_exists)504 void LEX::add_key_to_list(LEX_CSTRING *field_name,
505                           enum Key::Keytype type, bool check_exists)
506 {
507   Key *key;
508   MEM_ROOT *mem_root= thd->mem_root;
509   key= new (mem_root)
510         Key(type, &null_clex_str, HA_KEY_ALG_UNDEF, false,
511              DDL_options(check_exists ?
512                          DDL_options::OPT_IF_NOT_EXISTS :
513                          DDL_options::OPT_NONE));
514   key->columns.push_back(new (mem_root) Key_part_spec(field_name, 0),
515                          mem_root);
516   alter_info.key_list.push_back(key, mem_root);
517 }
518 
519 
add_alter_list(LEX_CSTRING name,Virtual_column_info * expr,bool exists)520 bool LEX::add_alter_list(LEX_CSTRING name, Virtual_column_info *expr,
521                          bool exists)
522 {
523   MEM_ROOT *mem_root= thd->mem_root;
524   Alter_column *ac= new (mem_root) Alter_column(name, expr, exists);
525   if (unlikely(ac == NULL))
526     return true;
527   alter_info.alter_list.push_back(ac, mem_root);
528   alter_info.flags|= ALTER_CHANGE_COLUMN_DEFAULT;
529   return false;
530 }
531 
532 
add_alter_list(LEX_CSTRING name,LEX_CSTRING new_name,bool exists)533 bool LEX::add_alter_list(LEX_CSTRING name, LEX_CSTRING new_name, bool exists)
534 {
535   Alter_column *ac= new (thd->mem_root) Alter_column(name, new_name, exists);
536   if (unlikely(ac == NULL))
537     return true;
538   alter_info.alter_list.push_back(ac, thd->mem_root);
539   alter_info.flags|= ALTER_RENAME_COLUMN;
540   return false;
541 }
542 
543 
init_last_field(Column_definition * field,const LEX_CSTRING * field_name,const CHARSET_INFO * cs)544 void LEX::init_last_field(Column_definition *field,
545                           const LEX_CSTRING *field_name,
546                           const CHARSET_INFO *cs)
547 {
548   last_field= field;
549 
550   field->field_name= *field_name;
551 
552   /* reset LEX fields that are used in Create_field::set_and_check() */
553   charset= cs;
554 }
555 
556 
set_bincmp(CHARSET_INFO * cs,bool bin)557 bool LEX::set_bincmp(CHARSET_INFO *cs, bool bin)
558 {
559   /*
560      if charset is NULL - we're parsing a field declaration.
561      we cannot call find_bin_collation for a field here, because actual
562      field charset is determined in get_sql_field_charset() much later.
563      so we only set a flag.
564   */
565   if (!charset)
566   {
567     charset= cs;
568     last_field->flags|= bin ? BINCMP_FLAG : 0;
569     return false;
570   }
571 
572   charset= bin ? find_bin_collation(cs ? cs : charset)
573                :                    cs ? cs : charset;
574   return charset == NULL;
575 }
576 
577 
add_virtual_expression(THD * thd,Item * expr)578 Virtual_column_info *add_virtual_expression(THD *thd, Item *expr)
579 {
580   Virtual_column_info *v= new (thd->mem_root) Virtual_column_info();
581   if (unlikely(!v))
582      return 0;
583    v->expr= expr;
584    v->utf8= 0;  /* connection charset */
585    return v;
586 }
587 
588 
589 
590 /**
591   @note The order of the elements of this array must correspond to
592   the order of elements in enum_binlog_stmt_unsafe.
593 */
594 const int
595 Query_tables_list::binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT] =
596 {
597   ER_BINLOG_UNSAFE_LIMIT,
598   ER_BINLOG_UNSAFE_INSERT_DELAYED,
599   ER_BINLOG_UNSAFE_SYSTEM_TABLE,
600   ER_BINLOG_UNSAFE_AUTOINC_COLUMNS,
601   ER_BINLOG_UNSAFE_UDF,
602   ER_BINLOG_UNSAFE_SYSTEM_VARIABLE,
603   ER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
604   ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS,
605   ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
606   ER_BINLOG_UNSAFE_MIXED_STATEMENT,
607   ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT,
608   ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE,
609   ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT,
610   ER_BINLOG_UNSAFE_REPLACE_SELECT,
611   ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT,
612   ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT,
613   ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC,
614   ER_BINLOG_UNSAFE_UPDATE_IGNORE,
615   ER_BINLOG_UNSAFE_INSERT_TWO_KEYS,
616   ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST
617 };
618 
619 
620 /* Longest standard keyword name */
621 
622 #define TOCK_NAME_LENGTH 24
623 
624 /*
625   The following data is based on the latin1 character set, and is only
626   used when comparing keywords
627 */
628 
629 static uchar to_upper_lex[]=
630 {
631     0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
632    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
633    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
634    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
635    64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
636    80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
637    96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
638    80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127,
639   128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
640   144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
641   160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
642   176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
643   192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
644   208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
645   192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
646   208,209,210,211,212,213,214,247,216,217,218,219,220,221,222,255
647 };
648 
649 /*
650   Names of the index hints (for error messages). Keep in sync with
651   index_hint_type
652 */
653 
654 const char * index_hint_type_name[] =
655 {
656   "IGNORE INDEX",
657   "USE INDEX",
658   "FORCE INDEX"
659 };
660 
lex_casecmp(const char * s,const char * t,uint len)661 inline int lex_casecmp(const char *s, const char *t, uint len)
662 {
663   while (len-- != 0 &&
664          to_upper_lex[(uchar) *s++] == to_upper_lex[(uchar) *t++]) ;
665   return (int) len+1;
666 }
667 
668 #include <lex_hash.h>
669 
670 
lex_init(void)671 void lex_init(void)
672 {
673   uint i;
674   DBUG_ENTER("lex_init");
675   for (i=0 ; i < array_elements(symbols) ; i++)
676     symbols[i].length=(uchar) strlen(symbols[i].name);
677   for (i=0 ; i < array_elements(sql_functions) ; i++)
678     sql_functions[i].length=(uchar) strlen(sql_functions[i].name);
679 
680   DBUG_VOID_RETURN;
681 }
682 
683 
lex_free(void)684 void lex_free(void)
685 {                                        // Call this when daemon ends
686   DBUG_ENTER("lex_free");
687   DBUG_VOID_RETURN;
688 }
689 
690 /**
691   Initialize lex object for use in fix_fields and parsing.
692 
693   SYNOPSIS
694     init_lex_with_single_table()
695     @param thd                 The thread object
696     @param table               The table object
697   @return Operation status
698     @retval TRUE                An error occurred, memory allocation error
699     @retval FALSE               Ok
700 
701   DESCRIPTION
702     This function is used to initialize a lex object on the
703     stack for use by fix_fields and for parsing. In order to
704     work properly it also needs to initialize the
705     Name_resolution_context object of the lexer.
706     Finally it needs to set a couple of variables to ensure
707     proper functioning of fix_fields.
708 */
709 
710 int
init_lex_with_single_table(THD * thd,TABLE * table,LEX * lex)711 init_lex_with_single_table(THD *thd, TABLE *table, LEX *lex)
712 {
713   TABLE_LIST *table_list;
714   Table_ident *table_ident;
715   SELECT_LEX *select_lex= lex->first_select_lex();
716   Name_resolution_context *context= &select_lex->context;
717   /*
718     We will call the parser to create a part_info struct based on the
719     partition string stored in the frm file.
720     We will use a local lex object for this purpose. However we also
721     need to set the Name_resolution_object for this lex object. We
722     do this by using add_table_to_list where we add the table that
723     we're working with to the Name_resolution_context.
724   */
725   thd->lex= lex;
726   lex_start(thd);
727   context->init();
728   if (unlikely((!(table_ident= new Table_ident(thd,
729                                                &table->s->db,
730                                                &table->s->table_name,
731                                                TRUE)))) ||
732       (unlikely(!(table_list= select_lex->add_table_to_list(thd,
733                                                             table_ident,
734                                                             NULL,
735                                                             0)))))
736     return TRUE;
737   context->resolve_in_table_list_only(table_list);
738   lex->use_only_table_context= TRUE;
739   lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VCOL_EXPR;
740   select_lex->cur_pos_in_select_list= UNDEF_POS;
741   table->map= 1; //To ensure correct calculation of const item
742   table_list->table= table;
743   table_list->cacheable_table= false;
744   lex->create_last_non_select_table= table_list;
745   return FALSE;
746 }
747 
748 /**
749   End use of local lex with single table
750 
751   SYNOPSIS
752     end_lex_with_single_table()
753     @param thd               The thread object
754     @param table             The table object
755     @param old_lex           The real lex object connected to THD
756 
757   DESCRIPTION
758     This function restores the real lex object after calling
759     init_lex_with_single_table and also restores some table
760     variables temporarily set.
761 */
762 
763 void
end_lex_with_single_table(THD * thd,TABLE * table,LEX * old_lex)764 end_lex_with_single_table(THD *thd, TABLE *table, LEX *old_lex)
765 {
766   LEX *lex= thd->lex;
767   table->map= 0;
768   table->get_fields_in_item_tree= FALSE;
769   lex_end(lex);
770   thd->lex= old_lex;
771 }
772 
773 
774 void
reset()775 st_parsing_options::reset()
776 {
777   allows_variable= TRUE;
778   lookup_keywords_after_qualifier= false;
779 }
780 
781 
782 /**
783   Perform initialization of Lex_input_stream instance.
784 
785   Basically, a buffer for pre-processed query. This buffer should be large
786   enough to keep multi-statement query. The allocation is done once in
787   Lex_input_stream::init() in order to prevent memory pollution when
788   the server is processing large multi-statement queries.
789 */
790 
init(THD * thd,char * buff,size_t length)791 bool Lex_input_stream::init(THD *thd,
792                             char* buff,
793                             size_t length)
794 {
795   DBUG_EXECUTE_IF("bug42064_simulate_oom",
796                   DBUG_SET("+d,simulate_out_of_memory"););
797 
798   m_cpp_buf= (char*) thd->alloc(length + 1);
799 
800   DBUG_EXECUTE_IF("bug42064_simulate_oom",
801                   DBUG_SET("-d,bug42064_simulate_oom"););
802 
803   if (m_cpp_buf == NULL)
804     return true;
805 
806   m_thd= thd;
807   reset(buff, length);
808 
809   return false;
810 }
811 
812 
813 /**
814   Prepare Lex_input_stream instance state for use for handling next SQL statement.
815 
816   It should be called between two statements in a multi-statement query.
817   The operation resets the input stream to the beginning-of-parse state,
818   but does not reallocate m_cpp_buf.
819 */
820 
821 void
reset(char * buffer,size_t length)822 Lex_input_stream::reset(char *buffer, size_t length)
823 {
824   yylineno= 1;
825   lookahead_token= -1;
826   lookahead_yylval= NULL;
827   m_ptr= buffer;
828   m_tok_start= NULL;
829   m_tok_end= NULL;
830   m_end_of_query= buffer + length;
831   m_tok_start_prev= NULL;
832   m_buf= buffer;
833   m_buf_length= length;
834   m_echo= TRUE;
835   m_cpp_tok_start= NULL;
836   m_cpp_tok_start_prev= NULL;
837   m_cpp_tok_end= NULL;
838   m_body_utf8= NULL;
839   m_cpp_utf8_processed_ptr= NULL;
840   next_state= MY_LEX_START;
841   found_semicolon= NULL;
842   ignore_space= MY_TEST(m_thd->variables.sql_mode & MODE_IGNORE_SPACE);
843   stmt_prepare_mode= FALSE;
844   multi_statements= TRUE;
845   in_comment=NO_COMMENT;
846   m_underscore_cs= NULL;
847   m_cpp_ptr= m_cpp_buf;
848 }
849 
850 
851 /**
852   The operation is called from the parser in order to
853   1) designate the intention to have utf8 body;
854   1) Indicate to the lexer that we will need a utf8 representation of this
855      statement;
856   2) Determine the beginning of the body.
857 
858   @param thd        Thread context.
859   @param begin_ptr  Pointer to the start of the body in the pre-processed
860                     buffer.
861 */
862 
body_utf8_start(THD * thd,const char * begin_ptr)863 void Lex_input_stream::body_utf8_start(THD *thd, const char *begin_ptr)
864 {
865   DBUG_ASSERT(begin_ptr);
866   DBUG_ASSERT(m_cpp_buf <= begin_ptr && begin_ptr <= m_cpp_buf + m_buf_length);
867 
868   size_t body_utf8_length= get_body_utf8_maximum_length(thd);
869 
870   m_body_utf8= (char *) thd->alloc(body_utf8_length + 1);
871   m_body_utf8_ptr= m_body_utf8;
872   *m_body_utf8_ptr= 0;
873 
874   m_cpp_utf8_processed_ptr= begin_ptr;
875 }
876 
877 
get_body_utf8_maximum_length(THD * thd)878 size_t Lex_input_stream::get_body_utf8_maximum_length(THD *thd)
879 {
880   /*
881     String literals can grow during escaping:
882     1a. Character string '<TAB>' can grow to '\t', 3 bytes to 4 bytes growth.
883     1b. Character string '1000 times <TAB>' grows from
884         1002 to 2002 bytes (including quotes), which gives a little bit
885         less than 2 times growth.
886     "2" should be a reasonable multiplier that safely covers escaping needs.
887   */
888   return (m_buf_length / thd->variables.character_set_client->mbminlen) *
889           my_charset_utf8mb3_bin.mbmaxlen * 2/*for escaping*/;
890 }
891 
892 
893 /**
894   @brief The operation appends unprocessed part of pre-processed buffer till
895   the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to end_ptr.
896 
897   The idea is that some tokens in the pre-processed buffer (like character
898   set introducers) should be skipped.
899 
900   Example:
901     CPP buffer: SELECT 'str1', _latin1 'str2';
902     m_cpp_utf8_processed_ptr -- points at the "SELECT ...";
903     In order to skip "_latin1", the following call should be made:
904       body_utf8_append(<pointer to "_latin1 ...">, <pointer to " 'str2'...">)
905 
906   @param ptr      Pointer in the pre-processed buffer, which specifies the
907                   end of the chunk, which should be appended to the utf8
908                   body.
909   @param end_ptr  Pointer in the pre-processed buffer, to which
910                   m_cpp_utf8_processed_ptr will be set in the end of the
911                   operation.
912 */
913 
body_utf8_append(const char * ptr,const char * end_ptr)914 void Lex_input_stream::body_utf8_append(const char *ptr,
915                                         const char *end_ptr)
916 {
917   DBUG_ASSERT(m_cpp_buf <= ptr && ptr <= m_cpp_buf + m_buf_length);
918   DBUG_ASSERT(m_cpp_buf <= end_ptr && end_ptr <= m_cpp_buf + m_buf_length);
919 
920   if (!m_body_utf8)
921     return;
922 
923   if (m_cpp_utf8_processed_ptr >= ptr)
924     return;
925 
926   size_t bytes_to_copy= ptr - m_cpp_utf8_processed_ptr;
927 
928   memcpy(m_body_utf8_ptr, m_cpp_utf8_processed_ptr, bytes_to_copy);
929   m_body_utf8_ptr += bytes_to_copy;
930   *m_body_utf8_ptr= 0;
931 
932   m_cpp_utf8_processed_ptr= end_ptr;
933 }
934 
935 /**
936   The operation appends unprocessed part of the pre-processed buffer till
937   the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to ptr.
938 
939   @param ptr  Pointer in the pre-processed buffer, which specifies the end
940               of the chunk, which should be appended to the utf8 body.
941 */
942 
body_utf8_append(const char * ptr)943 void Lex_input_stream::body_utf8_append(const char *ptr)
944 {
945   body_utf8_append(ptr, ptr);
946 }
947 
948 /**
949   The operation converts the specified text literal to the utf8 and appends
950   the result to the utf8-body.
951 
952   @param thd      Thread context.
953   @param txt      Text literal.
954   @param txt_cs   Character set of the text literal.
955   @param end_ptr  Pointer in the pre-processed buffer, to which
956                   m_cpp_utf8_processed_ptr will be set in the end of the
957                   operation.
958 */
959 
960 void
body_utf8_append_ident(THD * thd,const Lex_string_with_metadata_st * txt,const char * end_ptr)961 Lex_input_stream::body_utf8_append_ident(THD *thd,
962                                          const Lex_string_with_metadata_st *txt,
963                                          const char *end_ptr)
964 {
965   if (!m_cpp_utf8_processed_ptr)
966     return;
967 
968   LEX_CSTRING utf_txt;
969   thd->make_text_string_sys(&utf_txt, txt); // QQ: check return value?
970 
971   /* NOTE: utf_txt.length is in bytes, not in symbols. */
972   memcpy(m_body_utf8_ptr, utf_txt.str, utf_txt.length);
973   m_body_utf8_ptr += utf_txt.length;
974   *m_body_utf8_ptr= 0;
975 
976   m_cpp_utf8_processed_ptr= end_ptr;
977 }
978 
979 
980 
981 
982 extern "C" {
983 
984 /**
985   Escape a character. Consequently puts "escape" and "wc" characters into
986   the destination utf8 string.
987   @param cs     - the character set (utf8)
988   @param escape - the escape character (backslash, single quote, double quote)
989   @param wc     - the character to be escaped
990   @param str    - the destination string
991   @param end    - the end of the destination string
992   @returns      - a code according to the wc_mb() convension.
993 */
my_wc_mb_utf8mb3_with_escape(CHARSET_INFO * cs,my_wc_t escape,my_wc_t wc,uchar * str,uchar * end)994 int my_wc_mb_utf8mb3_with_escape(CHARSET_INFO *cs, my_wc_t escape, my_wc_t wc,
995                                  uchar *str, uchar *end)
996 {
997   DBUG_ASSERT(escape > 0);
998   if (str + 1 >= end)
999     return MY_CS_TOOSMALL2;  // Not enough space, need at least two bytes.
1000   *str= (uchar)escape;
1001   int cnvres= my_charset_utf8mb3_handler.wc_mb(cs, wc, str + 1, end);
1002   if (cnvres > 0)
1003     return cnvres + 1;       // The character was normally put
1004   if (cnvres == MY_CS_ILUNI)
1005     return MY_CS_ILUNI;      // Could not encode "wc" (e.g. non-BMP character)
1006   DBUG_ASSERT(cnvres <= MY_CS_TOOSMALL);
1007   return cnvres - 1;         // Not enough space
1008 }
1009 
1010 
1011 /**
1012   Optionally escape a character.
1013   If "escape" is non-zero, then both "escape" and "wc" are put to
1014   the destination string. Otherwise, only "wc" is put.
1015   @param cs     - the character set (utf8)
1016   @param wc     - the character to be optionally escaped
1017   @param escape - the escape character, or 0
1018   @param ewc    - the escaped replacement of "wc" (e.g. 't' for '\t')
1019   @param str    - the destination string
1020   @param end    - the end of the destination string
1021   @returns      - a code according to the wc_mb() conversion.
1022 */
my_wc_mb_utf8mb3_opt_escape(CHARSET_INFO * cs,my_wc_t wc,my_wc_t escape,my_wc_t ewc,uchar * str,uchar * end)1023 int my_wc_mb_utf8mb3_opt_escape(CHARSET_INFO *cs,
1024                                 my_wc_t wc, my_wc_t escape, my_wc_t ewc,
1025                                 uchar *str, uchar *end)
1026 {
1027   return escape ? my_wc_mb_utf8mb3_with_escape(cs, escape, ewc, str, end) :
1028                   my_charset_utf8mb3_handler.wc_mb(cs, wc, str, end);
1029 }
1030 
1031 /**
1032   Encode a character with optional backlash escaping and quote escaping.
1033   Quote marks are escaped using another quote mark.
1034   Additionally, if "escape" is non-zero, then special characters are
1035   also escaped using "escape".
1036   Otherwise (if "escape" is zero, e.g. in case of MODE_NO_BACKSLASH_ESCAPES),
1037   then special characters are not escaped and handled as normal characters.
1038 
1039   @param cs        - the character set (utf8)
1040   @param wc        - the character to be encoded
1041   @param str       - the destination string
1042   @param end       - the end of the destination string
1043   @param sep       - the string delimiter (e.g. ' or ")
1044   @param escape    - the escape character (backslash, or 0)
1045   @returns         - a code according to the wc_mb() convension.
1046 */
my_wc_mb_utf8mb3_escape(CHARSET_INFO * cs,my_wc_t wc,uchar * str,uchar * end,my_wc_t sep,my_wc_t escape)1047 int my_wc_mb_utf8mb3_escape(CHARSET_INFO *cs, my_wc_t wc,
1048                             uchar *str, uchar *end,
1049                             my_wc_t sep, my_wc_t escape)
1050 {
1051   DBUG_ASSERT(escape == 0 || escape == '\\');
1052   DBUG_ASSERT(sep == '"' || sep == '\'');
1053   switch (wc) {
1054   case 0:      return my_wc_mb_utf8mb3_opt_escape(cs, wc, escape, '0', str, end);
1055   case '\t':   return my_wc_mb_utf8mb3_opt_escape(cs, wc, escape, 't', str, end);
1056   case '\r':   return my_wc_mb_utf8mb3_opt_escape(cs, wc, escape, 'r', str, end);
1057   case '\n':   return my_wc_mb_utf8mb3_opt_escape(cs, wc, escape, 'n', str, end);
1058   case '\032': return my_wc_mb_utf8mb3_opt_escape(cs, wc, escape, 'Z', str, end);
1059   case '\'':
1060   case '\"':
1061     if (wc == sep)
1062       return my_wc_mb_utf8mb3_with_escape(cs, wc, wc, str, end);
1063   }
1064   return my_charset_utf8mb3_handler.wc_mb(cs, wc, str, end); // No escaping needed
1065 }
1066 
1067 
1068 /** wc_mb() compatible routines for all sql_mode and delimiter combinations */
my_wc_mb_utf8mb3_escape_single_quote_and_backslash(CHARSET_INFO * cs,my_wc_t wc,uchar * str,uchar * end)1069 int my_wc_mb_utf8mb3_escape_single_quote_and_backslash(CHARSET_INFO *cs,
1070                                                     my_wc_t wc,
1071                                                     uchar *str, uchar *end)
1072 {
1073   return my_wc_mb_utf8mb3_escape(cs, wc, str, end, '\'', '\\');
1074 }
1075 
1076 
my_wc_mb_utf8mb3_escape_double_quote_and_backslash(CHARSET_INFO * cs,my_wc_t wc,uchar * str,uchar * end)1077 int my_wc_mb_utf8mb3_escape_double_quote_and_backslash(CHARSET_INFO *cs,
1078                                                     my_wc_t wc,
1079                                                     uchar *str, uchar *end)
1080 {
1081   return my_wc_mb_utf8mb3_escape(cs, wc, str, end, '"', '\\');
1082 }
1083 
1084 
my_wc_mb_utf8mb3_escape_single_quote(CHARSET_INFO * cs,my_wc_t wc,uchar * str,uchar * end)1085 int my_wc_mb_utf8mb3_escape_single_quote(CHARSET_INFO *cs, my_wc_t wc,
1086                                       uchar *str, uchar *end)
1087 {
1088   return my_wc_mb_utf8mb3_escape(cs, wc, str, end, '\'', 0);
1089 }
1090 
1091 
my_wc_mb_utf8mb3_escape_double_quote(CHARSET_INFO * cs,my_wc_t wc,uchar * str,uchar * end)1092 int my_wc_mb_utf8mb3_escape_double_quote(CHARSET_INFO *cs, my_wc_t wc,
1093                                       uchar *str, uchar *end)
1094 {
1095   return my_wc_mb_utf8mb3_escape(cs, wc, str, end, '"', 0);
1096 }
1097 
1098 }; // End of extern "C"
1099 
1100 
1101 /**
1102   Get an escaping function, depending on the current sql_mode and the
1103   string separator.
1104 */
1105 my_charset_conv_wc_mb
get_escape_func(THD * thd,my_wc_t sep) const1106 Lex_input_stream::get_escape_func(THD *thd, my_wc_t sep) const
1107 {
1108   return thd->backslash_escapes() ?
1109          (sep == '"' ? my_wc_mb_utf8mb3_escape_double_quote_and_backslash:
1110                        my_wc_mb_utf8mb3_escape_single_quote_and_backslash) :
1111          (sep == '"' ? my_wc_mb_utf8mb3_escape_double_quote:
1112                        my_wc_mb_utf8mb3_escape_single_quote);
1113 }
1114 
1115 
1116 /**
1117   Append a text literal to the end of m_body_utf8.
1118   The string is escaped according to the current sql_mode and the
1119   string delimiter (e.g. ' or ").
1120 
1121   @param thd       - current THD
1122   @param txt       - the string to be appended to m_body_utf8.
1123                      Note, the string must be already unescaped.
1124   @param cs        - the character set of the string
1125   @param end_ptr   - m_cpp_utf8_processed_ptr will be set to this value
1126                      (see body_utf8_append_ident for details)
1127   @param sep       - the string delimiter (single or double quote)
1128 */
body_utf8_append_escape(THD * thd,const LEX_CSTRING * txt,CHARSET_INFO * cs,const char * end_ptr,my_wc_t sep)1129 void Lex_input_stream::body_utf8_append_escape(THD *thd,
1130                                                const LEX_CSTRING *txt,
1131                                                CHARSET_INFO *cs,
1132                                                const char *end_ptr,
1133                                                my_wc_t sep)
1134 {
1135   DBUG_ASSERT(sep == '\'' || sep == '"');
1136   if (!m_cpp_utf8_processed_ptr)
1137     return;
1138   uint errors;
1139   /**
1140     We previously alloced m_body_utf8 to be able to store the query with all
1141     strings properly escaped. See get_body_utf8_maximum_length().
1142     So here we have guaranteedly enough space to append any string literal
1143     with escaping. Passing txt->length*2 as "available space" is always safe.
1144     For better safety purposes we could calculate get_body_utf8_maximum_length()
1145     every time we append a string, but this would affect performance negatively,
1146     so let's check that we don't get beyond the allocated buffer in
1147     debug build only.
1148   */
1149   DBUG_ASSERT(m_body_utf8 + get_body_utf8_maximum_length(thd) >=
1150               m_body_utf8_ptr + txt->length * 2);
1151   uint32 cnv_length= my_convert_using_func(m_body_utf8_ptr, txt->length * 2,
1152                                            &my_charset_utf8mb3_general_ci,
1153                                            get_escape_func(thd, sep),
1154                                            txt->str, txt->length,
1155                                            cs, cs->cset->mb_wc,
1156                                            &errors);
1157   m_body_utf8_ptr+= cnv_length;
1158   *m_body_utf8_ptr= 0;
1159   m_cpp_utf8_processed_ptr= end_ptr;
1160 }
1161 
1162 
add_digest_token(uint token,LEX_YYSTYPE yylval)1163 void Lex_input_stream::add_digest_token(uint token, LEX_YYSTYPE yylval)
1164 {
1165   if (m_digest != NULL)
1166   {
1167     m_digest= digest_add_token(m_digest, token, yylval);
1168   }
1169 }
1170 
reduce_digest_token(uint token_left,uint token_right)1171 void Lex_input_stream::reduce_digest_token(uint token_left, uint token_right)
1172 {
1173   if (m_digest != NULL)
1174   {
1175     m_digest= digest_reduce_token(m_digest, token_left, token_right);
1176   }
1177 }
1178 
1179 /**
1180   lex starting operations for builtin select collected together
1181 */
1182 
lex_start(LEX * plex)1183 void SELECT_LEX::lex_start(LEX *plex)
1184 {
1185   SELECT_LEX_UNIT *unit= &plex->unit;
1186   /* 'parent_lex' is used in init_query() so it must be before it. */
1187   parent_lex= plex;
1188   init_query();
1189   master= unit;
1190   prev= &unit->slave;
1191   link_next= slave= next= 0;
1192   link_prev= (st_select_lex_node**)&(plex->all_selects_list);
1193   DBUG_ASSERT(!group_list_ptrs);
1194   select_number= 1;
1195   in_sum_expr=0;
1196   ftfunc_list_alloc.empty();
1197   ftfunc_list= &ftfunc_list_alloc;
1198   group_list.empty();
1199   order_list.empty();
1200   gorder_list.empty();
1201 }
1202 
lex_start(THD * thd)1203 void lex_start(THD *thd)
1204 {
1205   DBUG_ENTER("lex_start");
1206   thd->lex->start(thd);
1207   DBUG_VOID_RETURN;
1208 }
1209 
1210 
1211 /*
1212   This is called before every query that is to be parsed.
1213   Because of this, it's critical to not do too much things here.
1214   (We already do too much here)
1215 */
1216 
start(THD * thd_arg)1217 void LEX::start(THD *thd_arg)
1218 {
1219   DBUG_ENTER("LEX::start");
1220   DBUG_PRINT("info", ("This: %p thd_arg->lex: %p", this, thd_arg->lex));
1221 
1222   thd= unit.thd= thd_arg;
1223   stmt_lex= this; // default, should be rewritten for VIEWs And CTEs
1224 
1225   DBUG_ASSERT(!explain);
1226 
1227   builtin_select.lex_start(this);
1228   lex_options= 0;
1229   context_stack.empty();
1230   //empty select_stack
1231   select_stack_top= 0;
1232   unit.init_query();
1233   current_select_number= 0;
1234   curr_with_clause= 0;
1235   with_clauses_list= 0;
1236   with_clauses_list_last_next= &with_clauses_list;
1237   clone_spec_offset= 0;
1238   create_view= NULL;
1239   field_list.empty();
1240   value_list.empty();
1241   update_list.empty();
1242   set_var_list.empty();
1243   param_list.empty();
1244   view_list.empty();
1245   with_persistent_for_clause= FALSE;
1246   column_list= NULL;
1247   index_list= NULL;
1248   prepared_stmt.lex_start();
1249   auxiliary_table_list.empty();
1250   unit.next= unit.master= unit.link_next= unit.return_to= 0;
1251   unit.prev= unit.link_prev= 0;
1252   unit.slave= current_select= all_selects_list= &builtin_select;
1253   sql_cache= LEX::SQL_CACHE_UNSPECIFIED;
1254   describe= 0;
1255   analyze_stmt= 0;
1256   explain_json= false;
1257   context_analysis_only= 0;
1258   derived_tables= 0;
1259   with_cte_resolution= false;
1260   only_cte_resolution= false;
1261   safe_to_cache_query= 1;
1262   parsing_options.reset();
1263   empty_field_list_on_rset= 0;
1264   part_info= 0;
1265   m_sql_cmd= NULL;
1266   duplicates= DUP_ERROR;
1267   ignore= 0;
1268   spname= NULL;
1269   spcont= NULL;
1270   proc_list.first= 0;
1271   escape_used= FALSE;
1272   default_used= FALSE;
1273   query_tables= 0;
1274   reset_query_tables_list(FALSE);
1275   clause_that_disallows_subselect= NULL;
1276   selects_allow_into= FALSE;
1277   selects_allow_procedure= FALSE;
1278   use_only_table_context= FALSE;
1279   parse_vcol_expr= FALSE;
1280   check_exists= FALSE;
1281   create_info.lex_start();
1282   verbose= 0;
1283 
1284   name= null_clex_str;
1285   event_parse_data= NULL;
1286   profile_options= PROFILE_NONE;
1287   nest_level= 0;
1288   builtin_select.nest_level_base= &unit;
1289   allow_sum_func.clear_all();
1290   in_sum_func= NULL;
1291 
1292   used_tables= 0;
1293   table_type= TABLE_TYPE_UNKNOWN;
1294   reset_slave_info.all= false;
1295   limit_rows_examined= 0;
1296   limit_rows_examined_cnt= ULONGLONG_MAX;
1297   var_list.empty();
1298   stmt_var_list.empty();
1299   proc_list.elements=0;
1300 
1301   save_group_list.empty();
1302   save_order_list.empty();
1303   win_ref= NULL;
1304   win_frame= NULL;
1305   frame_top_bound= NULL;
1306   frame_bottom_bound= NULL;
1307   win_spec= NULL;
1308 
1309   vers_conditions.empty();
1310   period_conditions.empty();
1311 
1312   is_lex_started= TRUE;
1313 
1314   next_is_main= FALSE;
1315   next_is_down= FALSE;
1316 
1317   wild= 0;
1318   exchange= 0;
1319 
1320   DBUG_VOID_RETURN;
1321 }
1322 
lex_end(LEX * lex)1323 void lex_end(LEX *lex)
1324 {
1325   DBUG_ENTER("lex_end");
1326   DBUG_PRINT("enter", ("lex: %p", lex));
1327 
1328   lex_unlock_plugins(lex);
1329   lex_end_nops(lex);
1330 
1331   DBUG_VOID_RETURN;
1332 }
1333 
lex_unlock_plugins(LEX * lex)1334 void lex_unlock_plugins(LEX *lex)
1335 {
1336   DBUG_ENTER("lex_unlock_plugins");
1337 
1338   /* release used plugins */
1339   if (lex->plugins.elements) /* No function call and no mutex if no plugins. */
1340   {
1341     plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer,
1342                        lex->plugins.elements);
1343   }
1344   reset_dynamic(&lex->plugins);
1345   DBUG_VOID_RETURN;
1346 }
1347 
1348 /*
1349   Don't delete lex->sphead, it'll be needed for EXECUTE.
1350   Note that of all statements that populate lex->sphead
1351   only SQLCOM_COMPOUND can be PREPAREd
1352 
1353   MASTER INFO parameters (or state) is normally cleared towards the end
1354   of a statement. But in case of PS, the state needs to be preserved during
1355   its lifetime and should only be cleared on PS close or deallocation.
1356 */
lex_end_nops(LEX * lex)1357 void lex_end_nops(LEX *lex)
1358 {
1359   DBUG_ENTER("lex_end_nops");
1360   sp_head::destroy(lex->sphead);
1361   lex->sphead= NULL;
1362 
1363   /* Reset LEX_MASTER_INFO */
1364   lex->mi.reset(lex->sql_command == SQLCOM_CHANGE_MASTER);
1365   delete_dynamic(&lex->delete_gtid_domain);
1366 
1367   DBUG_VOID_RETURN;
1368 }
1369 
~Yacc_state()1370 Yacc_state::~Yacc_state()
1371 {
1372   if (yacc_yyss)
1373   {
1374     my_free(yacc_yyss);
1375     my_free(yacc_yyvs);
1376   }
1377 }
1378 
find_keyword(Lex_ident_cli_st * kwd,uint len,bool function)1379 int Lex_input_stream::find_keyword(Lex_ident_cli_st *kwd,
1380                                    uint len, bool function)
1381 {
1382   const char *tok= m_tok_start;
1383 
1384   SYMBOL *symbol= get_hash_symbol(tok, len, function);
1385   if (symbol)
1386   {
1387     kwd->set_keyword(tok, len);
1388     DBUG_ASSERT(tok >= get_buf());
1389     DBUG_ASSERT(tok < get_end_of_query());
1390 
1391     if (m_thd->variables.sql_mode & MODE_ORACLE)
1392     {
1393       switch (symbol->tok) {
1394       case BEGIN_MARIADB_SYM:          return BEGIN_ORACLE_SYM;
1395       case BLOB_MARIADB_SYM:           return BLOB_ORACLE_SYM;
1396       case BODY_MARIADB_SYM:           return BODY_ORACLE_SYM;
1397       case CLOB_MARIADB_SYM:           return CLOB_ORACLE_SYM;
1398       case CONTINUE_MARIADB_SYM:       return CONTINUE_ORACLE_SYM;
1399       case DECLARE_MARIADB_SYM:        return DECLARE_ORACLE_SYM;
1400       case DECODE_MARIADB_SYM:         return DECODE_ORACLE_SYM;
1401       case ELSEIF_MARIADB_SYM:         return ELSEIF_ORACLE_SYM;
1402       case ELSIF_MARIADB_SYM:          return ELSIF_ORACLE_SYM;
1403       case EXCEPTION_MARIADB_SYM:      return EXCEPTION_ORACLE_SYM;
1404       case EXIT_MARIADB_SYM:           return EXIT_ORACLE_SYM;
1405       case GOTO_MARIADB_SYM:           return GOTO_ORACLE_SYM;
1406       case NUMBER_MARIADB_SYM:         return NUMBER_ORACLE_SYM;
1407       case OTHERS_MARIADB_SYM:         return OTHERS_ORACLE_SYM;
1408       case PACKAGE_MARIADB_SYM:        return PACKAGE_ORACLE_SYM;
1409       case RAISE_MARIADB_SYM:          return RAISE_ORACLE_SYM;
1410       case RAW_MARIADB_SYM:            return RAW_ORACLE_SYM;
1411       case RETURN_MARIADB_SYM:         return RETURN_ORACLE_SYM;
1412       case ROWTYPE_MARIADB_SYM:        return ROWTYPE_ORACLE_SYM;
1413       case VARCHAR2_MARIADB_SYM:       return VARCHAR2_ORACLE_SYM;
1414       }
1415     }
1416 
1417     if ((symbol->tok == NOT_SYM) &&
1418         (m_thd->variables.sql_mode & MODE_HIGH_NOT_PRECEDENCE))
1419       return NOT2_SYM;
1420     if ((symbol->tok == OR2_SYM) &&
1421         (m_thd->variables.sql_mode & MODE_PIPES_AS_CONCAT))
1422     {
1423       return (m_thd->variables.sql_mode & MODE_ORACLE) ?
1424              ORACLE_CONCAT_SYM : MYSQL_CONCAT_SYM;
1425     }
1426 
1427     return symbol->tok;
1428   }
1429   return 0;
1430 }
1431 
1432 /*
1433   Check if name is a keyword
1434 
1435   SYNOPSIS
1436     is_keyword()
1437     name      checked name (must not be empty)
1438     len       length of checked name
1439 
1440   RETURN VALUES
1441     0         name is a keyword
1442     1         name isn't a keyword
1443 */
1444 
is_keyword(const char * name,uint len)1445 bool is_keyword(const char *name, uint len)
1446 {
1447   DBUG_ASSERT(len != 0);
1448   return get_hash_symbol(name,len,0)!=0;
1449 }
1450 
1451 /**
1452   Check if name is a sql function
1453 
1454     @param name      checked name
1455 
1456     @return is this a native function or not
1457     @retval 0         name is a function
1458     @retval 1         name isn't a function
1459 */
1460 
is_lex_native_function(const LEX_CSTRING * name)1461 bool is_lex_native_function(const LEX_CSTRING *name)
1462 {
1463   DBUG_ASSERT(name != NULL);
1464   return (get_hash_symbol(name->str, (uint) name->length, 1) != 0);
1465 }
1466 
1467 
is_native_function(THD * thd,const LEX_CSTRING * name)1468 bool is_native_function(THD *thd, const LEX_CSTRING *name)
1469 {
1470   if (find_native_function_builder(thd, name))
1471     return true;
1472 
1473   if (is_lex_native_function(name))
1474     return true;
1475 
1476   if (Type_handler::handler_by_name(thd, *name))
1477     return true;
1478 
1479   return false;
1480 }
1481 
1482 
is_native_function_with_warn(THD * thd,const LEX_CSTRING * name)1483 bool is_native_function_with_warn(THD *thd, const LEX_CSTRING *name)
1484 {
1485   if (!is_native_function(thd, name))
1486     return false;
1487   /*
1488     This warning will be printed when
1489     [1] A client query is parsed,
1490     [2] A stored function is loaded by db_load_routine.
1491     Printing the warning for [2] is intentional, to cover the
1492     following scenario:
1493     - A user define a SF 'foo' using MySQL 5.N
1494     - An application uses select foo(), and works.
1495     - MySQL 5.{N+1} defines a new native function 'foo', as
1496     part of a new feature.
1497     - MySQL 5.{N+1} documentation is updated, and should mention
1498     that there is a potential incompatible change in case of
1499     existing stored function named 'foo'.
1500     - The user deploys 5.{N+1}. At this point, 'select foo()'
1501     means something different, and the user code is most likely
1502     broken (it's only safe if the code is 'select db.foo()').
1503     With a warning printed when the SF is loaded (which has to
1504     occur before the call), the warning will provide a hint
1505     explaining the root cause of a later failure of 'select foo()'.
1506     With no warning printed, the user code will fail with no
1507     apparent reason.
1508     Printing a warning each time db_load_routine is executed for
1509     an ambiguous function is annoying, since that can happen a lot,
1510     but in practice should not happen unless there *are* name
1511     collisions.
1512     If a collision exists, it should not be silenced but fixed.
1513   */
1514   push_warning_printf(thd,
1515                       Sql_condition::WARN_LEVEL_NOTE,
1516                       ER_NATIVE_FCT_NAME_COLLISION,
1517                       ER_THD(thd, ER_NATIVE_FCT_NAME_COLLISION),
1518                       name->str);
1519   return true;
1520 }
1521 
1522 
1523 /* make a copy of token before ptr and set yytoklen */
1524 
get_token(uint skip,uint length)1525 LEX_CSTRING Lex_input_stream::get_token(uint skip, uint length)
1526 {
1527   LEX_CSTRING tmp;
1528   yyUnget();                       // ptr points now after last token char
1529   tmp.length= length;
1530   tmp.str= m_thd->strmake(m_tok_start + skip, tmp.length);
1531 
1532   m_cpp_text_start= m_cpp_tok_start + skip;
1533   m_cpp_text_end= m_cpp_text_start + tmp.length;
1534 
1535   return tmp;
1536 }
1537 
1538 
1539 static size_t
my_unescape(CHARSET_INFO * cs,char * to,const char * str,const char * end,int sep,bool backslash_escapes)1540 my_unescape(CHARSET_INFO *cs, char *to, const char *str, const char *end,
1541             int sep, bool backslash_escapes)
1542 {
1543   char *start= to;
1544   for ( ; str != end ; str++)
1545   {
1546 #ifdef USE_MB
1547     int l;
1548     if (cs->use_mb() && (l= my_ismbchar(cs, str, end)))
1549     {
1550       while (l--)
1551         *to++ = *str++;
1552       str--;
1553       continue;
1554     }
1555 #endif
1556     if (backslash_escapes && *str == '\\' && str + 1 != end)
1557     {
1558       switch(*++str) {
1559       case 'n':
1560         *to++='\n';
1561         break;
1562       case 't':
1563         *to++= '\t';
1564         break;
1565       case 'r':
1566         *to++ = '\r';
1567         break;
1568       case 'b':
1569         *to++ = '\b';
1570         break;
1571       case '0':
1572         *to++= 0;                      // Ascii null
1573         break;
1574       case 'Z':                        // ^Z must be escaped on Win32
1575         *to++='\032';
1576         break;
1577       case '_':
1578       case '%':
1579         *to++= '\\';                   // remember prefix for wildcard
1580         /* Fall through */
1581       default:
1582         *to++= *str;
1583         break;
1584       }
1585     }
1586     else if (*str == sep)
1587       *to++= *str++;                // Two ' or "
1588     else
1589       *to++ = *str;
1590   }
1591   *to= 0;
1592   return to - start;
1593 }
1594 
1595 
1596 size_t
unescape(CHARSET_INFO * cs,char * to,const char * str,const char * end,int sep)1597 Lex_input_stream::unescape(CHARSET_INFO *cs, char *to,
1598                            const char *str, const char *end,
1599                            int sep)
1600 {
1601   return my_unescape(cs, to, str, end, sep, m_thd->backslash_escapes());
1602 }
1603 
1604 
1605 /*
1606   Return an unescaped text literal without quotes
1607   Fix sometimes to do only one scan of the string
1608 */
1609 
get_text(Lex_string_with_metadata_st * dst,uint sep,int pre_skip,int post_skip)1610 bool Lex_input_stream::get_text(Lex_string_with_metadata_st *dst, uint sep,
1611                                 int pre_skip, int post_skip)
1612 {
1613   uchar c;
1614   uint found_escape=0;
1615   CHARSET_INFO *cs= m_thd->charset();
1616   bool is_8bit= false;
1617 
1618   while (! eof())
1619   {
1620     c= yyGet();
1621     if (c & 0x80)
1622       is_8bit= true;
1623 #ifdef USE_MB
1624     {
1625       int l;
1626       if (cs->use_mb() &&
1627           (l = my_ismbchar(cs,
1628                            get_ptr() -1,
1629                            get_end_of_query()))) {
1630         skip_binary(l-1);
1631         continue;
1632       }
1633     }
1634 #endif
1635     if (c == '\\' &&
1636         !(m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))
1637     {                                        // Escaped character
1638       found_escape=1;
1639       if (eof())
1640         return true;
1641       yySkip();
1642     }
1643     else if (c == sep)
1644     {
1645       if (c == yyGet())                 // Check if two separators in a row
1646       {
1647         found_escape=1;                 // duplicate. Remember for delete
1648         continue;
1649       }
1650       else
1651         yyUnget();
1652 
1653       /* Found end. Unescape and return string */
1654       const char *str, *end;
1655       char *to;
1656 
1657       str= m_tok_start;
1658       end= get_ptr();
1659       /* Extract the text from the token */
1660       str += pre_skip;
1661       end -= post_skip;
1662       DBUG_ASSERT(end >= str);
1663 
1664       if (!(to= (char*) m_thd->alloc((uint) (end - str) + 1)))
1665       {
1666         dst->set(&empty_clex_str, 0, '\0');
1667         return true;                   // Sql_alloc has set error flag
1668       }
1669 
1670       m_cpp_text_start= m_cpp_tok_start + pre_skip;
1671       m_cpp_text_end= get_cpp_ptr() - post_skip;
1672 
1673       if (!found_escape)
1674       {
1675         size_t len= (end - str);
1676         memcpy(to, str, len);
1677         to[len]= '\0';
1678         dst->set(to, len, is_8bit, '\0');
1679       }
1680       else
1681       {
1682         size_t len= unescape(cs, to, str, end, sep);
1683         dst->set(to, len, is_8bit, '\0');
1684       }
1685       return false;
1686     }
1687   }
1688   return true;                         // unexpected end of query
1689 }
1690 
1691 
1692 /*
1693 ** Calc type of integer; long integer, longlong integer or real.
1694 ** Returns smallest type that match the string.
1695 ** When using unsigned long long values the result is converted to a real
1696 ** because else they will be unexpected sign changes because all calculation
1697 ** is done with longlong or double.
1698 */
1699 
1700 static const char *long_str="2147483647";
1701 static const uint long_len=10;
1702 static const char *signed_long_str="-2147483648";
1703 static const char *longlong_str="9223372036854775807";
1704 static const uint longlong_len=19;
1705 static const char *signed_longlong_str="-9223372036854775808";
1706 static const uint signed_longlong_len=19;
1707 static const char *unsigned_longlong_str="18446744073709551615";
1708 static const uint unsigned_longlong_len=20;
1709 
int_token(const char * str,uint length)1710 static inline uint int_token(const char *str,uint length)
1711 {
1712   if (length < long_len)                        // quick normal case
1713     return NUM;
1714   bool neg=0;
1715 
1716   if (*str == '+')                              // Remove sign and pre-zeros
1717   {
1718     str++; length--;
1719   }
1720   else if (*str == '-')
1721   {
1722     str++; length--;
1723     neg=1;
1724   }
1725   while (*str == '0' && length)
1726   {
1727     str++; length --;
1728   }
1729   if (length < long_len)
1730     return NUM;
1731 
1732   uint smaller,bigger;
1733   const char *cmp;
1734   if (neg)
1735   {
1736     if (length == long_len)
1737     {
1738       cmp= signed_long_str + 1;
1739       smaller= NUM;                                   // If <= signed_long_str
1740       bigger= LONG_NUM;                               // If >= signed_long_str
1741     }
1742     else if (length < signed_longlong_len)
1743       return LONG_NUM;
1744     else if (length > signed_longlong_len)
1745       return DECIMAL_NUM;
1746     else
1747     {
1748       cmp= signed_longlong_str + 1;
1749       smaller= LONG_NUM;                              // If <= signed_longlong_str
1750       bigger=DECIMAL_NUM;
1751     }
1752   }
1753   else
1754   {
1755     if (length == long_len)
1756     {
1757       cmp= long_str;
1758       smaller=NUM;
1759       bigger=LONG_NUM;
1760     }
1761     else if (length < longlong_len)
1762       return LONG_NUM;
1763     else if (length > longlong_len)
1764     {
1765       if (length > unsigned_longlong_len)
1766         return DECIMAL_NUM;
1767       cmp=unsigned_longlong_str;
1768       smaller=ULONGLONG_NUM;
1769       bigger=DECIMAL_NUM;
1770     }
1771     else
1772     {
1773       cmp=longlong_str;
1774       smaller=LONG_NUM;
1775       bigger= ULONGLONG_NUM;
1776     }
1777   }
1778   while (*cmp && *cmp++ == *str++) ;
1779   return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
1780 }
1781 
1782 
1783 /**
1784   Given a stream that is advanced to the first contained character in
1785   an open comment, consume the comment.  Optionally, if we are allowed,
1786   recurse so that we understand comments within this current comment.
1787 
1788   At this level, we do not support version-condition comments.  We might
1789   have been called with having just passed one in the stream, though.  In
1790   that case, we probably want to tolerate mundane comments inside.  Thus,
1791   the case for recursion.
1792 
1793   @retval  Whether EOF reached before comment is closed.
1794 */
consume_comment(int remaining_recursions_permitted)1795 bool Lex_input_stream::consume_comment(int remaining_recursions_permitted)
1796 {
1797   // only one level of nested comments are allowed
1798   DBUG_ASSERT(remaining_recursions_permitted == 0 ||
1799               remaining_recursions_permitted == 1);
1800   uchar c;
1801   while (!eof())
1802   {
1803     c= yyGet();
1804 
1805     if (remaining_recursions_permitted == 1)
1806     {
1807       if ((c == '/') && (yyPeek() == '*'))
1808       {
1809         yyUnput('(');  // Replace nested "/*..." with "(*..."
1810         yySkip();      // and skip "("
1811 
1812         yySkip(); /* Eat asterisk */
1813         if (consume_comment(0))
1814           return true;
1815 
1816         yyUnput(')');  // Replace "...*/" with "...*)"
1817         yySkip();      // and skip ")"
1818         continue;
1819       }
1820     }
1821 
1822     if (c == '*')
1823     {
1824       if (yyPeek() == '/')
1825       {
1826         yySkip(); // Eat slash
1827         return FALSE;
1828       }
1829     }
1830 
1831     if (c == '\n')
1832       yylineno++;
1833   }
1834 
1835   return TRUE;
1836 }
1837 
1838 
1839 /*
1840   MYSQLlex remember the following states from the following MYSQLlex()
1841 
1842   @param yylval         [out]  semantic value of the token being parsed (yylval)
1843   @param thd            THD
1844 
1845   - MY_LEX_EOQ                  Found end of query
1846   - MY_LEX_OPERATOR_OR_IDENT    Last state was an ident, text or number
1847                                 (which can't be followed by a signed number)
1848 */
1849 
MYSQLlex(YYSTYPE * yylval,THD * thd)1850 int MYSQLlex(YYSTYPE *yylval, THD *thd)
1851 {
1852   return thd->m_parser_state->m_lip.lex_token(yylval, thd);
1853 }
1854 
1855 
ORAlex(YYSTYPE * yylval,THD * thd)1856 int ORAlex(YYSTYPE *yylval, THD *thd)
1857 {
1858   return thd->m_parser_state->m_lip.lex_token(yylval, thd);
1859 }
1860 
1861 
lex_token(YYSTYPE * yylval,THD * thd)1862 int Lex_input_stream::lex_token(YYSTYPE *yylval, THD *thd)
1863 {
1864   int token;
1865   const int left_paren= (int) '(';
1866 
1867   if (lookahead_token >= 0)
1868   {
1869     /*
1870       The next token was already parsed in advance,
1871       return it.
1872     */
1873     token= lookahead_token;
1874     lookahead_token= -1;
1875     *yylval= *(lookahead_yylval);
1876     lookahead_yylval= NULL;
1877     return token;
1878   }
1879 
1880   token= lex_one_token(yylval, thd);
1881   add_digest_token(token, yylval);
1882 
1883   SELECT_LEX *curr_sel= thd->lex->current_select;
1884 
1885   switch(token) {
1886   case WITH:
1887     /*
1888       Parsing 'WITH' 'ROLLUP' or 'WITH' 'CUBE' requires 2 look ups,
1889       which makes the grammar LALR(2).
1890       Replace by a single 'WITH_ROLLUP' or 'WITH_CUBE' token,
1891       to transform the grammar into a LALR(1) grammar,
1892       which sql_yacc.yy can process.
1893     */
1894     token= lex_one_token(yylval, thd);
1895     add_digest_token(token, yylval);
1896     switch(token) {
1897     case CUBE_SYM:
1898       return WITH_CUBE_SYM;
1899     case ROLLUP_SYM:
1900       return WITH_ROLLUP_SYM;
1901     case SYSTEM:
1902       return WITH_SYSTEM_SYM;
1903     default:
1904       /*
1905         Save the token following 'WITH'
1906       */
1907       lookahead_yylval= yylval;
1908       lookahead_token= token;
1909       return WITH;
1910     }
1911     break;
1912   case FOR_SYM:
1913     /*
1914      * Additional look-ahead to resolve doubtful cases like:
1915      * SELECT ... FOR UPDATE
1916      * SELECT ... FOR SYSTEM_TIME ... .
1917      */
1918     token= lex_one_token(yylval, thd);
1919     add_digest_token(token, yylval);
1920     switch(token) {
1921     case SYSTEM_TIME_SYM:
1922       return FOR_SYSTEM_TIME_SYM;
1923     default:
1924       /*
1925         Save the token following 'FOR_SYM'
1926       */
1927       lookahead_yylval= yylval;
1928       lookahead_token= token;
1929       return FOR_SYM;
1930     }
1931     break;
1932   case VALUES:
1933     if (curr_sel &&
1934         (curr_sel->parsing_place == BEFORE_OPT_LIST ||
1935          curr_sel->parsing_place == AFTER_LIST))
1936     {
1937       curr_sel->parsing_place= NO_MATTER;
1938       break;
1939     }
1940     if (curr_sel &&
1941         (curr_sel->parsing_place == IN_UPDATE_ON_DUP_KEY ||
1942          curr_sel->parsing_place == IN_PART_FUNC))
1943       return VALUE_SYM;
1944     token= lex_one_token(yylval, thd);
1945     add_digest_token(token, yylval);
1946     switch(token) {
1947     case LESS_SYM:
1948       return VALUES_LESS_SYM;
1949     case IN_SYM:
1950       return VALUES_IN_SYM;
1951     default:
1952       lookahead_yylval= yylval;
1953       lookahead_token= token;
1954       return VALUES;
1955     }
1956   case VALUE_SYM:
1957     if (curr_sel &&
1958         (curr_sel->parsing_place == BEFORE_OPT_LIST ||
1959          curr_sel->parsing_place == AFTER_LIST))
1960     {
1961       curr_sel->parsing_place= NO_MATTER;
1962       return VALUES;
1963     }
1964     break;
1965   case PARTITION_SYM:
1966   case SELECT_SYM:
1967   case UNION_SYM:
1968     if (curr_sel &&
1969         (curr_sel->parsing_place == BEFORE_OPT_LIST ||
1970          curr_sel->parsing_place == AFTER_LIST))
1971     {
1972       curr_sel->parsing_place= NO_MATTER;
1973     }
1974     break;
1975   case left_paren:
1976     if (!curr_sel ||
1977         curr_sel->parsing_place != BEFORE_OPT_LIST)
1978       return token;
1979     token= lex_one_token(yylval, thd);
1980     add_digest_token(token, yylval);
1981     lookahead_yylval= yylval;
1982     yylval= NULL;
1983     lookahead_token= token;
1984     curr_sel->parsing_place= NO_MATTER;
1985     if (token == LIKE)
1986       return LEFT_PAREN_LIKE;
1987     if (token == WITH)
1988       return LEFT_PAREN_WITH;
1989     if (token != left_paren && token != SELECT_SYM && token != VALUES)
1990       return LEFT_PAREN_ALT;
1991     else
1992       return left_paren;
1993     break;
1994   default:
1995     break;
1996   }
1997   return token;
1998 }
1999 
2000 
lex_one_token(YYSTYPE * yylval,THD * thd)2001 int Lex_input_stream::lex_one_token(YYSTYPE *yylval, THD *thd)
2002 {
2003   uchar UNINIT_VAR(c);
2004   bool comment_closed;
2005   int tokval;
2006   uint length;
2007   enum my_lex_states state;
2008   LEX *lex= thd->lex;
2009   CHARSET_INFO *const cs= thd->charset();
2010   const uchar *const state_map= cs->state_map;
2011   const uchar *const ident_map= cs->ident_map;
2012 
2013   start_token();
2014   state= next_state;
2015   next_state= MY_LEX_OPERATOR_OR_IDENT;
2016   for (;;)
2017   {
2018     switch (state) {
2019     case MY_LEX_OPERATOR_OR_IDENT:        // Next is operator or keyword
2020     case MY_LEX_START:                    // Start of token
2021       // Skip starting whitespace
2022       while(state_map[c= yyPeek()] == MY_LEX_SKIP)
2023       {
2024         if (c == '\n')
2025           yylineno++;
2026 
2027         yySkip();
2028       }
2029 
2030       /* Start of real token */
2031       restart_token();
2032       c= yyGet();
2033       state= (enum my_lex_states) state_map[c];
2034       break;
2035     case MY_LEX_ESCAPE:
2036       if (!eof() && yyGet() == 'N')
2037       {                                        // Allow \N as shortcut for NULL
2038         yylval->lex_str.str= (char*) "\\N";
2039         yylval->lex_str.length= 2;
2040         return NULL_SYM;
2041       }
2042       /* Fall through */
2043     case MY_LEX_CHAR:                          // Unknown or single char token
2044       if (c == '%' && (m_thd->variables.sql_mode & MODE_ORACLE))
2045       {
2046         next_state= MY_LEX_START;
2047         return PERCENT_ORACLE_SYM;
2048       }
2049       if (c == '[' && (m_thd->variables.sql_mode & MODE_MSSQL))
2050         return scan_ident_delimited(thd, &yylval->ident_cli, ']');
2051       /* Fall through */
2052     case MY_LEX_SKIP:                          // This should not happen
2053       if (c != ')')
2054         next_state= MY_LEX_START;         // Allow signed numbers
2055       yylval->kwd.set_keyword(m_tok_start, 1);
2056       return((int) c);
2057 
2058     case MY_LEX_MINUS_OR_COMMENT:
2059       if (yyPeek() == '-' &&
2060           (my_isspace(cs,yyPeekn(1)) ||
2061            my_iscntrl(cs,yyPeekn(1))))
2062       {
2063         state=MY_LEX_COMMENT;
2064         break;
2065       }
2066       next_state= MY_LEX_START;        // Allow signed numbers
2067       return((int) c);
2068 
2069     case MY_LEX_PLACEHOLDER:
2070       /*
2071         Check for a placeholder: it should not precede a possible identifier
2072         because of binlogging: when a placeholder is replaced with
2073         its value in a query for the binlog, the query must stay
2074         grammatically correct.
2075       */
2076       next_state= MY_LEX_START;        // Allow signed numbers
2077       if (stmt_prepare_mode && !ident_map[(uchar) yyPeek()])
2078         return(PARAM_MARKER);
2079       return((int) c);
2080 
2081     case MY_LEX_COMMA:
2082       next_state= MY_LEX_START;        // Allow signed numbers
2083       /*
2084         Warning:
2085         This is a work around, to make the "remember_name" rule in
2086         sql/sql_yacc.yy work properly.
2087         The problem is that, when parsing "select expr1, expr2",
2088         the code generated by bison executes the *pre* action
2089         remember_name (see select_item) *before* actually parsing the
2090         first token of expr2.
2091       */
2092       restart_token();
2093       return((int) c);
2094 
2095     case MY_LEX_IDENT_OR_NCHAR:
2096     {
2097       uint sep;
2098       if (yyPeek() != '\'')
2099       {
2100         state= MY_LEX_IDENT;
2101         break;
2102       }
2103       /* Found N'string' */
2104       yySkip();                         // Skip '
2105       if (get_text(&yylval->lex_string_with_metadata, (sep= yyGetLast()), 2, 1))
2106       {
2107         state= MY_LEX_CHAR;                    // Read char by char
2108         break;
2109       }
2110 
2111       body_utf8_append(m_cpp_text_start);
2112       body_utf8_append_escape(thd, &yylval->lex_string_with_metadata,
2113                                    national_charset_info,
2114                                    m_cpp_text_end, sep);
2115       return(NCHAR_STRING);
2116     }
2117     case MY_LEX_IDENT_OR_HEX:
2118       if (yyPeek() == '\'')
2119       {                                      // Found x'hex-number'
2120         state= MY_LEX_HEX_NUMBER;
2121         break;
2122       }
2123       /* fall through */
2124     case MY_LEX_IDENT_OR_BIN:
2125       if (yyPeek() == '\'')
2126       {                                 // Found b'bin-number'
2127         state= MY_LEX_BIN_NUMBER;
2128         break;
2129       }
2130       /* fall through */
2131     case MY_LEX_IDENT:
2132     {
2133       tokval= scan_ident_middle(thd, &yylval->ident_cli,
2134                                 &yylval->charset, &state);
2135       if (!tokval)
2136         continue;
2137       if (tokval == UNDERSCORE_CHARSET)
2138         m_underscore_cs= yylval->charset;
2139       return tokval;
2140     }
2141 
2142     case MY_LEX_IDENT_SEP:                  // Found ident and now '.'
2143       yylval->lex_str.str= (char*) get_ptr();
2144       yylval->lex_str.length= 1;
2145       c= yyGet();                          // should be '.'
2146       if (lex->parsing_options.lookup_keywords_after_qualifier)
2147         next_state= MY_LEX_IDENT_OR_KEYWORD;
2148       else
2149         next_state= MY_LEX_IDENT_START;    // Next is ident (not keyword)
2150       if (!ident_map[(uchar) yyPeek()])    // Probably ` or "
2151         next_state= MY_LEX_START;
2152       return((int) c);
2153 
2154     case MY_LEX_NUMBER_IDENT:                   // number or ident which num-start
2155       if (yyGetLast() == '0')
2156       {
2157         c= yyGet();
2158         if (c == 'x')
2159         {
2160           while (my_isxdigit(cs, (c = yyGet()))) ;
2161           if ((yyLength() >= 3) && !ident_map[c])
2162           {
2163             /* skip '0x' */
2164             yylval->lex_str= get_token(2, yyLength() - 2);
2165             return (HEX_NUM);
2166           }
2167           yyUnget();
2168           state= MY_LEX_IDENT_START;
2169           break;
2170         }
2171         else if (c == 'b')
2172         {
2173           while ((c= yyGet()) == '0' || c == '1')
2174             ;
2175           if ((yyLength() >= 3) && !ident_map[c])
2176           {
2177             /* Skip '0b' */
2178             yylval->lex_str= get_token(2, yyLength() - 2);
2179             return (BIN_NUM);
2180           }
2181           yyUnget();
2182           state= MY_LEX_IDENT_START;
2183           break;
2184         }
2185         yyUnget();
2186       }
2187 
2188       while (my_isdigit(cs, (c= yyGet()))) ;
2189       if (!ident_map[c])
2190       {                                        // Can't be identifier
2191         state=MY_LEX_INT_OR_REAL;
2192         break;
2193       }
2194       if (c == 'e' || c == 'E')
2195       {
2196         // The following test is written this way to allow numbers of type 1e1
2197         if (my_isdigit(cs, yyPeek()) ||
2198             (c=(yyGet())) == '+' || c == '-')
2199         {                                       // Allow 1E+10
2200           if (my_isdigit(cs, yyPeek()))         // Number must have digit after sign
2201           {
2202             yySkip();
2203             while (my_isdigit(cs, yyGet())) ;
2204             yylval->lex_str= get_token(0, yyLength());
2205             return(FLOAT_NUM);
2206           }
2207         }
2208         /*
2209           We've found:
2210           - A sequence of digits
2211           - Followed by 'e' or 'E'
2212           - Followed by some byte XX which is not a known mantissa start,
2213             and it's known to be a valid identifier part.
2214             XX can be either a 8bit identifier character, or a multi-byte head.
2215         */
2216         yyUnget();
2217         return scan_ident_start(thd, &yylval->ident_cli);
2218       }
2219       /*
2220         We've found:
2221         - A sequence of digits
2222         - Followed by some character XX, which is neither 'e' nor 'E',
2223           and it's known to be a valid identifier part.
2224           XX can be a 8bit identifier character, or a multi-byte head.
2225       */
2226       yyUnget();
2227       return scan_ident_start(thd, &yylval->ident_cli);
2228 
2229     case MY_LEX_IDENT_START:                    // We come here after '.'
2230       return scan_ident_start(thd, &yylval->ident_cli);
2231 
2232     case MY_LEX_USER_VARIABLE_DELIMITER:        // Found quote char
2233       return scan_ident_delimited(thd, &yylval->ident_cli, m_tok_start[0]);
2234 
2235     case MY_LEX_INT_OR_REAL:                    // Complete int or incomplete real
2236       if (c != '.' || yyPeek() == '.')
2237       {
2238         /*
2239           Found a complete integer number:
2240           - the number is either not followed by a dot at all, or
2241           - the number is followed by a double dot as in: FOR i IN 1..10
2242         */
2243         yylval->lex_str= get_token(0, yyLength());
2244         return int_token(yylval->lex_str.str, (uint) yylval->lex_str.length);
2245       }
2246       // fall through
2247     case MY_LEX_REAL:                           // Incomplete real number
2248       while (my_isdigit(cs, c= yyGet())) ;
2249 
2250       if (c == 'e' || c == 'E')
2251       {
2252         c= yyGet();
2253         if (c == '-' || c == '+')
2254           c= yyGet();                           // Skip sign
2255         if (!my_isdigit(cs, c))
2256 	  return ABORT_SYM; // No digit after sign
2257         while (my_isdigit(cs, yyGet())) ;
2258         yylval->lex_str= get_token(0, yyLength());
2259         return(FLOAT_NUM);
2260       }
2261       yylval->lex_str= get_token(0, yyLength());
2262       return(DECIMAL_NUM);
2263 
2264     case MY_LEX_HEX_NUMBER:             // Found x'hexstring'
2265       yySkip();                    // Accept opening '
2266       while (my_isxdigit(cs, (c= yyGet()))) ;
2267       if (c != '\'')
2268         return(ABORT_SYM);              // Illegal hex constant
2269       yySkip();                    // Accept closing '
2270       length= yyLength();          // Length of hexnum+3
2271       if ((length % 2) == 0)
2272         return(ABORT_SYM);              // odd number of hex digits
2273       yylval->lex_str= get_token(2,            // skip x'
2274                                  length - 3);  // don't count x' and last '
2275       return HEX_STRING;
2276 
2277     case MY_LEX_BIN_NUMBER:           // Found b'bin-string'
2278       yySkip();                  // Accept opening '
2279       while ((c= yyGet()) == '0' || c == '1')
2280         ;
2281       if (c != '\'')
2282         return(ABORT_SYM);            // Illegal hex constant
2283       yySkip();                  // Accept closing '
2284       length= yyLength();        // Length of bin-num + 3
2285       yylval->lex_str= get_token(2,           // skip b'
2286                                  length - 3); // don't count b' and last '
2287       return (BIN_NUM);
2288 
2289     case MY_LEX_CMP_OP:                     // Incomplete comparison operator
2290       next_state= MY_LEX_START;        // Allow signed numbers
2291       if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP ||
2292           state_map[(uchar) yyPeek()] == MY_LEX_LONG_CMP_OP)
2293       {
2294         yySkip();
2295         if ((tokval= find_keyword(&yylval->kwd, 2, 0)))
2296           return(tokval);
2297         yyUnget();
2298       }
2299       return(c);
2300 
2301     case MY_LEX_LONG_CMP_OP:                // Incomplete comparison operator
2302       next_state= MY_LEX_START;
2303       if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP ||
2304           state_map[(uchar) yyPeek()] == MY_LEX_LONG_CMP_OP)
2305       {
2306         yySkip();
2307         if (state_map[(uchar) yyPeek()] == MY_LEX_CMP_OP)
2308         {
2309           yySkip();
2310           if ((tokval= find_keyword(&yylval->kwd, 3, 0)))
2311             return(tokval);
2312           yyUnget();
2313         }
2314         if ((tokval= find_keyword(&yylval->kwd, 2, 0)))
2315           return(tokval);
2316         yyUnget();
2317       }
2318       return(c);
2319 
2320     case MY_LEX_BOOL:
2321       if (c != yyPeek())
2322       {
2323         state= MY_LEX_CHAR;
2324         break;
2325       }
2326       yySkip();
2327       tokval= find_keyword(&yylval->kwd, 2, 0);  // Is a bool operator
2328       next_state= MY_LEX_START;                  // Allow signed numbers
2329       return(tokval);
2330 
2331     case MY_LEX_STRING_OR_DELIMITER:
2332       if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
2333       {
2334         state= MY_LEX_USER_VARIABLE_DELIMITER;
2335         break;
2336       }
2337       /* " used for strings */
2338       /* fall through */
2339     case MY_LEX_STRING:                        // Incomplete text string
2340     {
2341       uint sep;
2342       if (get_text(&yylval->lex_string_with_metadata, (sep= yyGetLast()), 1, 1))
2343       {
2344         state= MY_LEX_CHAR;                     // Read char by char
2345         break;
2346       }
2347       CHARSET_INFO *strcs= m_underscore_cs ? m_underscore_cs : cs;
2348       body_utf8_append(m_cpp_text_start);
2349 
2350       body_utf8_append_escape(thd, &yylval->lex_string_with_metadata,
2351                                    strcs, m_cpp_text_end, sep);
2352       m_underscore_cs= NULL;
2353       return(TEXT_STRING);
2354     }
2355     case MY_LEX_COMMENT:                       //  Comment
2356       lex->lex_options|= OPTION_LEX_FOUND_COMMENT;
2357       while ((c= yyGet()) != '\n' && c) ;
2358       yyUnget();                          // Safety against eof
2359       state= MY_LEX_START;                     // Try again
2360       break;
2361     case MY_LEX_LONG_COMMENT:                  // Long C comment?
2362       if (yyPeek() != '*')
2363       {
2364         state= MY_LEX_CHAR;                     // Probable division
2365         break;
2366       }
2367       lex->lex_options|= OPTION_LEX_FOUND_COMMENT;
2368       /* Reject '/' '*', since we might need to turn off the echo */
2369       yyUnget();
2370 
2371       save_in_comment_state();
2372 
2373       if (yyPeekn(2) == '!' ||
2374           (yyPeekn(2) == 'M' && yyPeekn(3) == '!'))
2375       {
2376         bool maria_comment_syntax= yyPeekn(2) == 'M';
2377         in_comment= DISCARD_COMMENT;
2378         /* Accept '/' '*' '!', but do not keep this marker. */
2379         set_echo(FALSE);
2380         yySkipn(maria_comment_syntax ? 4 : 3);
2381 
2382         /*
2383           The special comment format is very strict:
2384           '/' '*' '!', followed by an optional 'M' and exactly
2385           1-2 digits (major), 2 digits (minor), then 2 digits (dot).
2386           32302  -> 3.23.02
2387           50032  -> 5.0.32
2388           50114  -> 5.1.14
2389           100000 -> 10.0.0
2390         */
2391         if (  my_isdigit(cs, yyPeekn(0))
2392            && my_isdigit(cs, yyPeekn(1))
2393            && my_isdigit(cs, yyPeekn(2))
2394            && my_isdigit(cs, yyPeekn(3))
2395            && my_isdigit(cs, yyPeekn(4))
2396            )
2397         {
2398           ulong version;
2399           uint length= 5;
2400           char *end_ptr= (char*) get_ptr() + length;
2401           int error;
2402           if (my_isdigit(cs, yyPeekn(5)))
2403           {
2404             end_ptr++;                          // 6 digit number
2405             length++;
2406           }
2407 
2408           version= (ulong) my_strtoll10(get_ptr(), &end_ptr, &error);
2409 
2410           /*
2411             MySQL-5.7 has new features and might have new SQL syntax that
2412             MariaDB-10.0 does not understand. Ignore all versioned comments
2413             with MySQL versions in the range 50700-999999, but
2414             do not ignore MariaDB specific comments for the same versions.
2415           */
2416           if (version <= MYSQL_VERSION_ID &&
2417               (version < 50700 || version > 99999 || maria_comment_syntax))
2418           {
2419             /* Accept 'M' 'm' 'm' 'd' 'd' */
2420             yySkipn(length);
2421             /* Expand the content of the special comment as real code */
2422             set_echo(TRUE);
2423             state=MY_LEX_START;
2424             break;  /* Do not treat contents as a comment.  */
2425           }
2426           else
2427           {
2428 #ifdef WITH_WSREP
2429             if (WSREP(thd) && version == 99997 && wsrep_thd_is_local(thd))
2430             {
2431               WSREP_DEBUG("consistency check: %s", thd->query());
2432               thd->wsrep_consistency_check= CONSISTENCY_CHECK_DECLARED;
2433               yySkipn(5);
2434               set_echo(TRUE);
2435               state= MY_LEX_START;
2436               break;  /* Do not treat contents as a comment.  */
2437             }
2438 #endif /* WITH_WSREP */
2439             /*
2440               Patch and skip the conditional comment to avoid it
2441               being propagated infinitely (eg. to a slave).
2442             */
2443             char *pcom= yyUnput(' ');
2444             comment_closed= ! consume_comment(1);
2445             if (! comment_closed)
2446             {
2447               *pcom= '!';
2448             }
2449             /* version allowed to have one level of comment inside. */
2450           }
2451         }
2452         else
2453         {
2454           /* Not a version comment. */
2455           state=MY_LEX_START;
2456           set_echo(TRUE);
2457           break;
2458         }
2459       }
2460       else
2461       {
2462         in_comment= PRESERVE_COMMENT;
2463         yySkip();                  // Accept /
2464         yySkip();                  // Accept *
2465         comment_closed= ! consume_comment(0);
2466         /* regular comments can have zero comments inside. */
2467       }
2468       /*
2469         Discard:
2470         - regular '/' '*' comments,
2471         - special comments '/' '*' '!' for a future version,
2472         by scanning until we find a closing '*' '/' marker.
2473 
2474         Nesting regular comments isn't allowed.  The first
2475         '*' '/' returns the parser to the previous state.
2476 
2477         /#!VERSI oned containing /# regular #/ is allowed #/
2478 
2479                 Inside one versioned comment, another versioned comment
2480                 is treated as a regular discardable comment.  It gets
2481                 no special parsing.
2482       */
2483 
2484       /* Unbalanced comments with a missing '*' '/' are a syntax error */
2485       if (! comment_closed)
2486         return (ABORT_SYM);
2487       state = MY_LEX_START;             // Try again
2488       restore_in_comment_state();
2489       break;
2490     case MY_LEX_END_LONG_COMMENT:
2491       if ((in_comment != NO_COMMENT) && yyPeek() == '/')
2492       {
2493         /* Reject '*' '/' */
2494         yyUnget();
2495         /* Accept '*' '/', with the proper echo */
2496         set_echo(in_comment == PRESERVE_COMMENT);
2497         yySkipn(2);
2498         /* And start recording the tokens again */
2499         set_echo(TRUE);
2500         in_comment= NO_COMMENT;
2501         state=MY_LEX_START;
2502       }
2503       else
2504         state= MY_LEX_CHAR;              // Return '*'
2505       break;
2506     case MY_LEX_SET_VAR:                // Check if ':='
2507       if (yyPeek() != '=')
2508       {
2509         next_state= MY_LEX_START;
2510         if (m_thd->variables.sql_mode & MODE_ORACLE)
2511         {
2512           yylval->kwd.set_keyword(m_tok_start, 1);
2513           return COLON_ORACLE_SYM;
2514         }
2515         return (int) ':';
2516       }
2517       yySkip();
2518       return (SET_VAR);
2519     case MY_LEX_SEMICOLON:              // optional line terminator
2520       state= MY_LEX_CHAR;               // Return ';'
2521       break;
2522     case MY_LEX_EOL:
2523       if (eof())
2524       {
2525         yyUnget();                 // Reject the last '\0'
2526         set_echo(FALSE);
2527         yySkip();
2528         set_echo(TRUE);
2529         /* Unbalanced comments with a missing '*' '/' are a syntax error */
2530         if (in_comment != NO_COMMENT)
2531           return (ABORT_SYM);
2532         next_state= MY_LEX_END;     // Mark for next loop
2533         return(END_OF_INPUT);
2534       }
2535       state=MY_LEX_CHAR;
2536       break;
2537     case MY_LEX_END:
2538       next_state= MY_LEX_END;
2539       return(0);                        // We found end of input last time
2540 
2541       /* Actually real shouldn't start with . but allow them anyhow */
2542     case MY_LEX_REAL_OR_POINT:
2543       if (my_isdigit(cs, (c= yyPeek())))
2544         state = MY_LEX_REAL;            // Real
2545       else if (c == '.')
2546       {
2547         yySkip();
2548         return DOT_DOT_SYM;
2549       }
2550       else
2551       {
2552         state= MY_LEX_IDENT_SEP;        // return '.'
2553         yyUnget();                 // Put back '.'
2554       }
2555       break;
2556     case MY_LEX_USER_END:               // end '@' of user@hostname
2557       switch (state_map[(uchar) yyPeek()]) {
2558       case MY_LEX_STRING:
2559       case MY_LEX_USER_VARIABLE_DELIMITER:
2560       case MY_LEX_STRING_OR_DELIMITER:
2561         break;
2562       case MY_LEX_USER_END:
2563         next_state= MY_LEX_SYSTEM_VAR;
2564         break;
2565       default:
2566         next_state= MY_LEX_HOSTNAME;
2567         break;
2568       }
2569       yylval->lex_str.str= (char*) get_ptr() - 1;
2570       yylval->lex_str.length= 1;
2571       return((int) '@');
2572     case MY_LEX_HOSTNAME:               // end '@' of user@hostname
2573       for (c= yyGet() ;
2574            my_isalnum(cs, c) || c == '.' || c == '_' ||  c == '$';
2575            c= yyGet()) ;
2576       yylval->lex_str= get_token(0, yyLength());
2577       return(LEX_HOSTNAME);
2578     case MY_LEX_SYSTEM_VAR:
2579       yylval->lex_str.str= (char*) get_ptr();
2580       yylval->lex_str.length= 1;
2581       yySkip();                                    // Skip '@'
2582       next_state= (state_map[(uchar) yyPeek()] ==
2583                         MY_LEX_USER_VARIABLE_DELIMITER ?
2584                         MY_LEX_OPERATOR_OR_IDENT :
2585                         MY_LEX_IDENT_OR_KEYWORD);
2586       return((int) '@');
2587     case MY_LEX_IDENT_OR_KEYWORD:
2588       /*
2589         We come here when we have found two '@' in a row.
2590         We should now be able to handle:
2591         [(global | local | session) .]variable_name
2592       */
2593       return scan_ident_sysvar(thd, &yylval->ident_cli);
2594     }
2595   }
2596 }
2597 
2598 
get_7bit_or_8bit_ident(THD * thd,uchar * last_char)2599 bool Lex_input_stream::get_7bit_or_8bit_ident(THD *thd, uchar *last_char)
2600 {
2601   uchar c;
2602   CHARSET_INFO *const cs= thd->charset();
2603   const uchar *const ident_map= cs->ident_map;
2604   bool is_8bit= false;
2605   for ( ; ident_map[c= yyGet()]; )
2606   {
2607     if (c & 0x80)
2608       is_8bit= true; // will convert
2609   }
2610   *last_char= c;
2611   return is_8bit;
2612 }
2613 
2614 
scan_ident_sysvar(THD * thd,Lex_ident_cli_st * str)2615 int Lex_input_stream::scan_ident_sysvar(THD *thd, Lex_ident_cli_st *str)
2616 {
2617   uchar last_char;
2618   uint length;
2619   int tokval;
2620   bool is_8bit;
2621   DBUG_ASSERT(m_tok_start == m_ptr);
2622 
2623   is_8bit= get_7bit_or_8bit_ident(thd, &last_char);
2624 
2625   if (last_char == '.')
2626     next_state= MY_LEX_IDENT_SEP;
2627   if (!(length= yyLength()))
2628     return ABORT_SYM;                  // Names must be nonempty.
2629   if ((tokval= find_keyword(str, length, 0)))
2630   {
2631     yyUnget();                         // Put back 'c'
2632     return tokval;                     // Was keyword
2633   }
2634 
2635   yyUnget();                       // ptr points now after last token char
2636   str->set_ident(m_tok_start, length, is_8bit);
2637 
2638   m_cpp_text_start= m_cpp_tok_start;
2639   m_cpp_text_end= m_cpp_text_start + length;
2640   body_utf8_append(m_cpp_text_start);
2641   body_utf8_append_ident(thd, str, m_cpp_text_end);
2642 
2643   return is_8bit ? IDENT_QUOTED : IDENT;
2644 }
2645 
2646 
2647 /*
2648   We can come here if different parsing stages:
2649   - In an identifier chain:
2650        SELECT t1.cccc FROM t1;
2651     (when the "cccc" part starts)
2652     In this case both m_tok_start and m_ptr point to "cccc".
2653   - When a sequence of digits has changed to something else,
2654     therefore the token becomes an identifier rather than a number:
2655        SELECT 12345_6 FROM t1;
2656     In this case m_tok_start points to the entire "12345_678",
2657     while m_ptr points to "678".
2658 */
scan_ident_start(THD * thd,Lex_ident_cli_st * str)2659 int Lex_input_stream::scan_ident_start(THD *thd, Lex_ident_cli_st *str)
2660 {
2661   uchar c;
2662   bool is_8bit;
2663   CHARSET_INFO *const cs= thd->charset();
2664   const uchar *const ident_map= cs->ident_map;
2665   DBUG_ASSERT(m_tok_start <= m_ptr);
2666 
2667   if (cs->use_mb())
2668   {
2669     is_8bit= true;
2670     while (ident_map[c= yyGet()])
2671     {
2672       int char_length= cs->charlen(get_ptr() - 1, get_end_of_query());
2673       if (char_length <= 0)
2674         break;
2675       skip_binary(char_length - 1);
2676     }
2677   }
2678   else
2679   {
2680     is_8bit= get_7bit_or_8bit_ident(thd, &c);
2681   }
2682   if (c == '.' && ident_map[(uchar) yyPeek()])
2683     next_state= MY_LEX_IDENT_SEP;// Next is '.'
2684 
2685   uint length= yyLength();
2686   yyUnget(); // ptr points now after last token char
2687   str->set_ident(m_tok_start, length, is_8bit);
2688   m_cpp_text_start= m_cpp_tok_start;
2689   m_cpp_text_end= m_cpp_text_start + length;
2690   body_utf8_append(m_cpp_text_start);
2691   body_utf8_append_ident(thd, str, m_cpp_text_end);
2692   return is_8bit ? IDENT_QUOTED : IDENT;
2693 }
2694 
2695 
scan_ident_middle(THD * thd,Lex_ident_cli_st * str,CHARSET_INFO ** introducer,my_lex_states * st)2696 int Lex_input_stream::scan_ident_middle(THD *thd, Lex_ident_cli_st *str,
2697                                         CHARSET_INFO **introducer,
2698                                         my_lex_states *st)
2699 {
2700   CHARSET_INFO *const cs= thd->charset();
2701   const uchar *const ident_map= cs->ident_map;
2702   const uchar *const state_map= cs->state_map;
2703   const char *start;
2704   uint length;
2705   uchar c;
2706   bool is_8bit;
2707   bool resolve_introducer= true;
2708   DBUG_ASSERT(m_ptr == m_tok_start + 1); // m_ptr points to the second byte
2709 
2710   if (cs->use_mb())
2711   {
2712     is_8bit= true;
2713     int char_length= cs->charlen(get_ptr() - 1, get_end_of_query());
2714     if (char_length <= 0)
2715     {
2716       *st= MY_LEX_CHAR;
2717       return 0;
2718     }
2719     skip_binary(char_length - 1);
2720 
2721     while (ident_map[c= yyGet()])
2722     {
2723       char_length= cs->charlen(get_ptr() - 1, get_end_of_query());
2724       if (char_length <= 0)
2725         break;
2726       if (char_length > 1 || (c & 0x80))
2727         resolve_introducer= false;
2728       skip_binary(char_length - 1);
2729     }
2730   }
2731   else
2732   {
2733     is_8bit= get_7bit_or_8bit_ident(thd, &c) || (m_tok_start[0] & 0x80);
2734     resolve_introducer= !is_8bit;
2735   }
2736   length= yyLength();
2737   start= get_ptr();
2738   if (ignore_space)
2739   {
2740     /*
2741       If we find a space then this can't be an identifier. We notice this
2742       below by checking start != lex->ptr.
2743     */
2744     for (; state_map[(uchar) c] == MY_LEX_SKIP ; c= yyGet())
2745     {
2746       if (c == '\n')
2747         yylineno++;
2748     }
2749   }
2750   if (start == get_ptr() && c == '.' && ident_map[(uchar) yyPeek()])
2751     next_state= MY_LEX_IDENT_SEP;
2752   else
2753   {                                    // '(' must follow directly if function
2754     int tokval;
2755     yyUnget();
2756     if ((tokval= find_keyword(str, length, c == '(')))
2757     {
2758       next_state= MY_LEX_START;        // Allow signed numbers
2759       return(tokval);                  // Was keyword
2760     }
2761     yySkip();                  // next state does a unget
2762   }
2763 
2764   yyUnget();                       // ptr points now after last token char
2765   str->set_ident(m_tok_start, length, is_8bit);
2766   m_cpp_text_start= m_cpp_tok_start;
2767   m_cpp_text_end= m_cpp_text_start + length;
2768 
2769   /*
2770      Note: "SELECT _bla AS 'alias'"
2771      _bla should be considered as a IDENT if charset haven't been found.
2772      So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
2773      producing an error.
2774   */
2775   DBUG_ASSERT(length > 0);
2776   if (resolve_introducer && m_tok_start[0] == '_')
2777   {
2778     ErrConvString csname(str->str + 1, str->length - 1, &my_charset_bin);
2779     CHARSET_INFO *cs= get_charset_by_csname(csname.ptr(),
2780                                             MY_CS_PRIMARY, MYF(0));
2781     if (cs)
2782     {
2783       body_utf8_append(m_cpp_text_start, m_cpp_tok_start + length);
2784       *introducer= cs;
2785       return UNDERSCORE_CHARSET;
2786     }
2787   }
2788 
2789   body_utf8_append(m_cpp_text_start);
2790   body_utf8_append_ident(thd, str, m_cpp_text_end);
2791   return is_8bit ? IDENT_QUOTED : IDENT;
2792 }
2793 
2794 
scan_ident_delimited(THD * thd,Lex_ident_cli_st * str,uchar quote_char)2795 int Lex_input_stream::scan_ident_delimited(THD *thd,
2796                                            Lex_ident_cli_st *str,
2797                                            uchar quote_char)
2798 {
2799   CHARSET_INFO *const cs= thd->charset();
2800   uint double_quotes= 0;
2801   uchar c;
2802   DBUG_ASSERT(m_ptr == m_tok_start + 1);
2803 
2804   for ( ; ; )
2805   {
2806     if (!(c= yyGet()))
2807     {
2808       /*
2809         End-of-query or straight 0x00 inside a delimited identifier.
2810         Return the quote character, to have the parser fail on syntax error.
2811       */
2812       m_ptr= (char *) m_tok_start + 1;
2813       if (m_echo)
2814         m_cpp_ptr= (char *) m_cpp_tok_start + 1;
2815       return quote_char;
2816     }
2817     int var_length= cs->charlen(get_ptr() - 1, get_end_of_query());
2818     if (var_length == 1)
2819     {
2820       if (c == quote_char)
2821       {
2822         if (yyPeek() != quote_char)
2823           break;
2824         c= yyGet();
2825         double_quotes++;
2826         continue;
2827       }
2828     }
2829     else if (var_length > 1)
2830     {
2831       skip_binary(var_length - 1);
2832     }
2833   }
2834 
2835   str->set_ident_quoted(m_tok_start + 1, yyLength() - 1, true, quote_char);
2836   yyUnget();                       // ptr points now after last token char
2837 
2838   m_cpp_text_start= m_cpp_tok_start + 1;
2839   m_cpp_text_end= m_cpp_text_start + str->length;
2840 
2841   if (c == quote_char)
2842     yySkip();                  // Skip end `
2843   next_state= MY_LEX_START;
2844   body_utf8_append(m_cpp_text_start);
2845   // QQQ: shouldn't it add unescaped version ????
2846   body_utf8_append_ident(thd, str, m_cpp_text_end);
2847   return IDENT_QUOTED;
2848 }
2849 
2850 
trim_whitespace(CHARSET_INFO * cs,LEX_CSTRING * str,size_t * prefix_length)2851 void trim_whitespace(CHARSET_INFO *cs, LEX_CSTRING *str, size_t * prefix_length)
2852 {
2853   /*
2854     TODO:
2855     This code assumes that there are no multi-bytes characters
2856     that can be considered white-space.
2857   */
2858 
2859   size_t plen= 0;
2860   while ((str->length > 0) && (my_isspace(cs, str->str[0])))
2861   {
2862     plen++;
2863     str->length --;
2864     str->str ++;
2865   }
2866   if (prefix_length)
2867     *prefix_length= plen;
2868   /*
2869     FIXME:
2870     Also, parsing backward is not safe with multi bytes characters
2871   */
2872   while ((str->length > 0) && (my_isspace(cs, str->str[str->length-1])))
2873   {
2874     str->length --;
2875   }
2876 }
2877 
2878 
2879 /*
2880   st_select_lex structures initialisations
2881 */
2882 
init_query_common()2883 void st_select_lex_node::init_query_common()
2884 {
2885   options= 0;
2886   set_linkage(UNSPECIFIED_TYPE);
2887   distinct= TRUE;
2888   no_table_names_allowed= 0;
2889   uncacheable= 0;
2890 }
2891 
init_query()2892 void st_select_lex_unit::init_query()
2893 {
2894   init_query_common();
2895   set_linkage(GLOBAL_OPTIONS_TYPE);
2896   lim.set_unlimited();
2897   union_distinct= 0;
2898   prepared= optimized= optimized_2= executed= 0;
2899   bag_set_op_optimized= 0;
2900   optimize_started= 0;
2901   item= 0;
2902   union_result= 0;
2903   table= 0;
2904   fake_select_lex= 0;
2905   saved_fake_select_lex= 0;
2906   cleaned= 0;
2907   item_list.empty();
2908   describe= 0;
2909   found_rows_for_union= 0;
2910   derived= 0;
2911   is_view= false;
2912   with_clause= 0;
2913   with_element= 0;
2914   cloned_from= 0;
2915   columns_are_renamed= false;
2916   with_wrapped_tvc= false;
2917   have_except_all_or_intersect_all= false;
2918 }
2919 
init_query()2920 void st_select_lex::init_query()
2921 {
2922   init_query_common();
2923   table_list.empty();
2924   top_join_list.empty();
2925   join_list= &top_join_list;
2926   embedding= 0;
2927   leaf_tables_prep.empty();
2928   leaf_tables.empty();
2929   item_list.empty();
2930   min_max_opt_list.empty();
2931   join= 0;
2932   having= prep_having= where= prep_where= 0;
2933   cond_pushed_into_where= cond_pushed_into_having= 0;
2934   attach_to_conds.empty();
2935   olap= UNSPECIFIED_OLAP_TYPE;
2936   having_fix_field= 0;
2937   having_fix_field_for_pushed_cond= 0;
2938   context.select_lex= this;
2939   context.init();
2940   cond_count= between_count= with_wild= 0;
2941   max_equal_elems= 0;
2942   ref_pointer_array.reset();
2943   select_n_where_fields= 0;
2944   select_n_reserved= 0;
2945   select_n_having_items= 0;
2946   n_sum_items= 0;
2947   n_child_sum_items= 0;
2948   hidden_bit_fields= 0;
2949   fields_in_window_functions= 0;
2950   subquery_in_having= explicit_limit= 0;
2951   is_item_list_lookup= 0;
2952   changed_elements= 0;
2953   first_natural_join_processing= 1;
2954   first_cond_optimization= 1;
2955   is_service_select= 0;
2956   parsing_place= NO_MATTER;
2957   save_parsing_place= NO_MATTER;
2958   context_analysis_place= NO_MATTER;
2959   exclude_from_table_unique_test= no_wrap_view_item= FALSE;
2960   nest_level= 0;
2961   link_next= 0;
2962   prep_leaf_list_state= UNINIT;
2963   have_merged_subqueries= FALSE;
2964   bzero((char*) expr_cache_may_be_used, sizeof(expr_cache_may_be_used));
2965   select_list_tables= 0;
2966   m_non_agg_field_used= false;
2967   m_agg_func_used= false;
2968   m_custom_agg_func_used= false;
2969   window_specs.empty();
2970   window_funcs.empty();
2971   tvc= 0;
2972   in_tvc= false;
2973   versioned_tables= 0;
2974   pushdown_select= 0;
2975 }
2976 
init_select()2977 void st_select_lex::init_select()
2978 {
2979   sj_nests.empty();
2980   sj_subselects.empty();
2981   group_list.empty();
2982   if (group_list_ptrs)
2983     group_list_ptrs->clear();
2984   type= 0;
2985   db= null_clex_str;
2986   having= 0;
2987   table_join_options= 0;
2988   in_sum_expr= with_wild= 0;
2989   options= 0;
2990   ftfunc_list_alloc.empty();
2991   inner_sum_func_list= 0;
2992   ftfunc_list= &ftfunc_list_alloc;
2993   order_list.empty();
2994   /* Set limit and offset to default values */
2995   select_limit= 0;      /* denotes the default limit = HA_POS_ERROR */
2996   offset_limit= 0;      /* denotes the default offset = 0 */
2997   is_set_query_expr_tail= false;
2998   with_sum_func= 0;
2999   with_all_modifier= 0;
3000   is_correlated= 0;
3001   cur_pos_in_select_list= UNDEF_POS;
3002   cond_value= having_value= Item::COND_UNDEF;
3003   inner_refs_list.empty();
3004   insert_tables= 0;
3005   merged_into= 0;
3006   m_non_agg_field_used= false;
3007   m_agg_func_used= false;
3008   m_custom_agg_func_used= false;
3009   name_visibility_map.clear_all();
3010   with_dep= 0;
3011   join= 0;
3012   lock_type= TL_READ_DEFAULT;
3013   save_many_values.empty();
3014   save_insert_list= 0;
3015   tvc= 0;
3016   in_funcs.empty();
3017   curr_tvc_name= 0;
3018   in_tvc= false;
3019   versioned_tables= 0;
3020   nest_flags= 0;
3021 }
3022 
3023 /*
3024   st_select_lex structures linking
3025 */
3026 
3027 /* include on level down */
include_down(st_select_lex_node * upper)3028 void st_select_lex_node::include_down(st_select_lex_node *upper)
3029 {
3030   if ((next= upper->slave))
3031     next->prev= &next;
3032   prev= &upper->slave;
3033   upper->slave= this;
3034   master= upper;
3035   slave= 0;
3036 }
3037 
3038 
add_slave(st_select_lex_node * slave_arg)3039 void st_select_lex_node::add_slave(st_select_lex_node *slave_arg)
3040 {
3041   for (; slave; slave= slave->next)
3042     if (slave == slave_arg)
3043       return;
3044 
3045   if (slave)
3046   {
3047     st_select_lex_node *slave_arg_slave= slave_arg->slave;
3048     /* Insert in the front of list of slaves if any. */
3049     slave_arg->include_neighbour(slave);
3050     /* include_neighbour() sets slave_arg->slave=0, restore it. */
3051     slave_arg->slave= slave_arg_slave;
3052     /* Count on include_neighbour() setting the master. */
3053     DBUG_ASSERT(slave_arg->master == this);
3054   }
3055   else
3056   {
3057     slave= slave_arg;
3058     slave_arg->master= this;
3059     slave->prev= &master->slave;
3060     slave->next= 0;
3061   }
3062 }
3063 
link_chain_down(st_select_lex_node * first)3064 void st_select_lex_node::link_chain_down(st_select_lex_node *first)
3065 {
3066   st_select_lex_node *last_node;
3067   st_select_lex_node *node= first;
3068   do
3069   {
3070     last_node= node;
3071     node->master= this;
3072     node= node->next;
3073   } while (node);
3074   if ((last_node->next= slave))
3075   {
3076     slave->prev= &last_node->next;
3077   }
3078   first->prev= &slave;
3079   slave= first;
3080 }
3081 
3082 /*
3083   @brief
3084     Substitute this node in select tree for a newly creates node
3085 
3086   @param  subst the node to substitute for
3087 
3088   @details
3089     The function substitute this node in the select tree for a newly
3090     created node subst. This node is just removed from the tree but all
3091     its link fields and the attached sub-tree remain untouched.
3092 */
3093 
substitute_in_tree(st_select_lex_node * subst)3094 void st_select_lex_node::substitute_in_tree(st_select_lex_node *subst)
3095 {
3096   if ((subst->next= next))
3097     next->prev= &subst->next;
3098   subst->prev= prev;
3099   (*prev)= subst;
3100   subst->master= master;
3101 }
3102 
3103 /*
3104   include on level down (but do not link)
3105 
3106   SYNOPSYS
3107     st_select_lex_node::include_standalone()
3108     upper - reference on node underr which this node should be included
3109     ref - references on reference on this node
3110 */
include_standalone(st_select_lex_node * upper,st_select_lex_node ** ref)3111 void st_select_lex_node::include_standalone(st_select_lex_node *upper,
3112                                             st_select_lex_node **ref)
3113 {
3114   next= 0;
3115   prev= ref;
3116   master= upper;
3117   slave= 0;
3118 }
3119 
3120 /* include neighbour (on same level) */
include_neighbour(st_select_lex_node * before)3121 void st_select_lex_node::include_neighbour(st_select_lex_node *before)
3122 {
3123   if ((next= before->next))
3124     next->prev= &next;
3125   prev= &before->next;
3126   before->next= this;
3127   master= before->master;
3128   slave= 0;
3129 }
3130 
3131 /* including in global SELECT_LEX list */
include_global(st_select_lex_node ** plink)3132 void st_select_lex_node::include_global(st_select_lex_node **plink)
3133 {
3134   if ((link_next= *plink))
3135     link_next->link_prev= &link_next;
3136   link_prev= plink;
3137   *plink= this;
3138 }
3139 
3140 //excluding from global list (internal function)
fast_exclude()3141 void st_select_lex_node::fast_exclude()
3142 {
3143   if (link_prev)
3144   {
3145     if ((*link_prev= link_next))
3146       link_next->link_prev= link_prev;
3147   }
3148   // Remove slave structure
3149   for (; slave; slave= slave->next)
3150     slave->fast_exclude();
3151 
3152 }
3153 
3154 
3155 /**
3156   @brief
3157     Insert a new chain of nodes into another chain before a particular link
3158 
3159   @param in/out
3160     ptr_pos_to_insert  the address of the chain pointer pointing to the link
3161                        before which the subchain has to be inserted
3162   @param
3163     end_chain_node     the last link of the subchain to be inserted
3164 
3165   @details
3166     The method inserts the chain of nodes starting from this node and ending
3167     with the node nd_chain_node into another chain of nodes before the node
3168     pointed to by *ptr_pos_to_insert.
3169     It is assumed that ptr_pos_to_insert belongs to the chain where we insert.
3170     So it must be updated.
3171 
3172   @retval
3173     The method returns the pointer to the first link of the inserted chain
3174 */
3175 
insert_chain_before(st_select_lex_node ** ptr_pos_to_insert,st_select_lex_node * end_chain_node)3176 st_select_lex_node *st_select_lex_node:: insert_chain_before(
3177                                          st_select_lex_node **ptr_pos_to_insert,
3178                                          st_select_lex_node *end_chain_node)
3179 {
3180   end_chain_node->link_next= *ptr_pos_to_insert;
3181   (*ptr_pos_to_insert)->link_prev= &end_chain_node->link_next;
3182   link_prev= ptr_pos_to_insert;
3183   return this;
3184 }
3185 
3186 
3187 /*
3188   Detach the node from its master and attach it to a new master
3189 */
3190 
move_as_slave(st_select_lex_node * new_master)3191 void st_select_lex_node::move_as_slave(st_select_lex_node *new_master)
3192 {
3193   exclude_from_tree();
3194   if (new_master->slave)
3195   {
3196     st_select_lex_node *curr= new_master->slave;
3197     for ( ; curr->next ; curr= curr->next) ;
3198     prev= &curr->next;
3199   }
3200   else
3201     prev= &new_master->slave;
3202   *prev= this;
3203   next= 0;
3204   master= new_master;
3205 }
3206 
3207 
3208 /*
3209   Exclude a node from the tree lex structure, but leave it in the global
3210   list of nodes.
3211 */
3212 
exclude_from_tree()3213 void st_select_lex_node::exclude_from_tree()
3214 {
3215   if ((*prev= next))
3216     next->prev= prev;
3217 }
3218 
3219 
3220 /*
3221   Exclude select_lex structure (except first (first select can't be
3222   deleted, because it is most upper select))
3223 */
exclude()3224 void st_select_lex_node::exclude()
3225 {
3226   /* exclude from global list */
3227   fast_exclude();
3228   /* exclude from other structures */
3229   exclude_from_tree();
3230   /*
3231      We do not need following statements, because prev pointer of first
3232      list element point to master->slave
3233      if (master->slave == this)
3234        master->slave= next;
3235   */
3236 }
3237 
3238 
3239 /*
3240   Exclude level of current unit from tree of SELECTs
3241 
3242   SYNOPSYS
3243     st_select_lex_unit::exclude_level()
3244 
3245   NOTE: units which belong to current will be brought up on level of
3246   currernt unit
3247 */
exclude_level()3248 void st_select_lex_unit::exclude_level()
3249 {
3250   SELECT_LEX_UNIT *units= 0, **units_last= &units;
3251   for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
3252   {
3253     // unlink current level from global SELECTs list
3254     if (sl->link_prev && (*sl->link_prev= sl->link_next))
3255       sl->link_next->link_prev= sl->link_prev;
3256 
3257     // bring up underlay levels
3258     SELECT_LEX_UNIT **last= 0;
3259     for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
3260     {
3261       u->master= master;
3262       last= (SELECT_LEX_UNIT**)&(u->next);
3263     }
3264     if (last)
3265     {
3266       (*units_last)= sl->first_inner_unit();
3267       units_last= last;
3268     }
3269   }
3270   if (units)
3271   {
3272     // include brought up levels in place of current
3273     (*prev)= units;
3274     (*units_last)= (SELECT_LEX_UNIT*)next;
3275     if (next)
3276       next->prev= (SELECT_LEX_NODE**)units_last;
3277     units->prev= prev;
3278   }
3279   else
3280   {
3281     // exclude currect unit from list of nodes
3282     (*prev)= next;
3283     if (next)
3284       next->prev= prev;
3285   }
3286   // Mark it excluded
3287   prev= NULL;
3288 }
3289 
3290 
3291 #if 0
3292 /*
3293   Exclude subtree of current unit from tree of SELECTs
3294 
3295   SYNOPSYS
3296     st_select_lex_unit::exclude_tree()
3297 */
3298 void st_select_lex_unit::exclude_tree()
3299 {
3300   for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
3301   {
3302     // unlink current level from global SELECTs list
3303     if (sl->link_prev && (*sl->link_prev= sl->link_next))
3304       sl->link_next->link_prev= sl->link_prev;
3305 
3306     // unlink underlay levels
3307     for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
3308     {
3309       u->exclude_level();
3310     }
3311   }
3312   // exclude currect unit from list of nodes
3313   (*prev)= next;
3314   if (next)
3315     next->prev= prev;
3316 }
3317 #endif
3318 
3319 
3320 /*
3321   st_select_lex_node::mark_as_dependent mark all st_select_lex struct from
3322   this to 'last' as dependent
3323 
3324   SYNOPSIS
3325     last - pointer to last st_select_lex struct, before which all
3326            st_select_lex have to be marked as dependent
3327 
3328   NOTE
3329     'last' should be reachable from this st_select_lex_node
3330 */
3331 
mark_as_dependent(THD * thd,st_select_lex * last,Item_ident * dependency)3332 bool st_select_lex::mark_as_dependent(THD *thd, st_select_lex *last,
3333                                       Item_ident *dependency)
3334 {
3335 
3336   DBUG_ASSERT(this != last);
3337 
3338   /*
3339     Mark all selects from resolved to 1 before select where was
3340     found table as depended (of select where was found table)
3341 
3342     We move by name resolution context, bacause during merge can some select
3343     be excleded from SELECT tree
3344   */
3345   Name_resolution_context *c= &this->context;
3346   do
3347   {
3348     SELECT_LEX *s= c->select_lex;
3349     if (!(s->uncacheable & UNCACHEABLE_DEPENDENT_GENERATED))
3350     {
3351       // Select is dependent of outer select
3352       s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
3353                        UNCACHEABLE_DEPENDENT_GENERATED;
3354       SELECT_LEX_UNIT *munit= s->master_unit();
3355       munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
3356                        UNCACHEABLE_DEPENDENT_GENERATED;
3357       for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
3358       {
3359         if (sl != s &&
3360             !(sl->uncacheable & (UNCACHEABLE_DEPENDENT_GENERATED |
3361                                  UNCACHEABLE_UNITED)))
3362           sl->uncacheable|= UNCACHEABLE_UNITED;
3363       }
3364     }
3365 
3366     Item_subselect *subquery_expr= s->master_unit()->item;
3367     if (subquery_expr && subquery_expr->mark_as_dependent(thd, last,
3368                                                           dependency))
3369       return TRUE;
3370   } while ((c= c->outer_context) != NULL && (c->select_lex != last));
3371   is_correlated= TRUE;
3372   master_unit()->item->is_correlated= TRUE;
3373   return FALSE;
3374 }
3375 
3376 /*
3377   prohibit using LIMIT clause
3378 */
test_limit()3379 bool st_select_lex::test_limit()
3380 {
3381   if (select_limit != 0)
3382   {
3383     my_error(ER_NOT_SUPPORTED_YET, MYF(0),
3384              "LIMIT & IN/ALL/ANY/SOME subquery");
3385     return(1);
3386   }
3387   return(0);
3388 }
3389 
3390 
3391 
outer_select()3392 st_select_lex* st_select_lex_unit::outer_select()
3393 {
3394   return (st_select_lex*) master;
3395 }
3396 
3397 
get_offset()3398 ha_rows st_select_lex::get_offset()
3399 {
3400   ulonglong val= 0;
3401 
3402   if (offset_limit)
3403   {
3404     // see comment for st_select_lex::get_limit()
3405     bool err= offset_limit->fix_fields_if_needed(master_unit()->thd, NULL);
3406     DBUG_ASSERT(!err);
3407     val= err ? HA_POS_ERROR : offset_limit->val_uint();
3408   }
3409 
3410   return (ha_rows)val;
3411 }
3412 
3413 
get_limit()3414 ha_rows st_select_lex::get_limit()
3415 {
3416   ulonglong val= HA_POS_ERROR;
3417 
3418   if (select_limit)
3419   {
3420     /*
3421       fix_fields() has not been called for select_limit. That's due to the
3422       historical reasons -- this item could be only of type Item_int, and
3423       Item_int does not require fix_fields(). Thus, fix_fields() was never
3424       called for select_limit.
3425 
3426       Some time ago, Item_splocal was also allowed for LIMIT / OFFSET clauses.
3427       However, the fix_fields() behavior was not updated, which led to a crash
3428       in some cases.
3429 
3430       There is no single place where to call fix_fields() for LIMIT / OFFSET
3431       items during the fix-fields-phase. Thus, for the sake of readability,
3432       it was decided to do it here, on the evaluation phase (which is a
3433       violation of design, but we chose the lesser of two evils).
3434 
3435       We can call fix_fields() here, because select_limit can be of two
3436       types only: Item_int and Item_splocal. Item_int::fix_fields() is trivial,
3437       and Item_splocal::fix_fields() (or rather Item_sp_variable::fix_fields())
3438       has the following properties:
3439         1) it does not affect other items;
3440         2) it does not fail.
3441 
3442       Nevertheless DBUG_ASSERT was added to catch future changes in
3443       fix_fields() implementation. Also added runtime check against a result
3444       of fix_fields() in order to handle error condition in non-debug build.
3445     */
3446     bool err= select_limit->fix_fields_if_needed(master_unit()->thd, NULL);
3447     DBUG_ASSERT(!err);
3448     val= err ? HA_POS_ERROR : select_limit->val_uint();
3449   }
3450 
3451   return (ha_rows)val;
3452 }
3453 
3454 
add_order_to_list(THD * thd,Item * item,bool asc)3455 bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
3456 {
3457   return add_to_list(thd, order_list, item, asc);
3458 }
3459 
3460 
add_gorder_to_list(THD * thd,Item * item,bool asc)3461 bool st_select_lex::add_gorder_to_list(THD *thd, Item *item, bool asc)
3462 {
3463   return add_to_list(thd, gorder_list, item, asc);
3464 }
3465 
3466 
add_item_to_list(THD * thd,Item * item)3467 bool st_select_lex::add_item_to_list(THD *thd, Item *item)
3468 {
3469   DBUG_ENTER("st_select_lex::add_item_to_list");
3470   DBUG_PRINT("info", ("Item: %p", item));
3471   DBUG_RETURN(item_list.push_back(item, thd->mem_root));
3472 }
3473 
3474 
add_group_to_list(THD * thd,Item * item,bool asc)3475 bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
3476 {
3477   return add_to_list(thd, group_list, item, asc);
3478 }
3479 
3480 
add_ftfunc_to_list(THD * thd,Item_func_match * func)3481 bool st_select_lex::add_ftfunc_to_list(THD *thd, Item_func_match *func)
3482 {
3483   return !func || ftfunc_list->push_back(func, thd->mem_root); // end of memory?
3484 }
3485 
3486 
outer_select()3487 st_select_lex* st_select_lex::outer_select()
3488 {
3489   return (st_select_lex*) master->get_master();
3490 }
3491 
3492 
inc_in_sum_expr()3493 bool st_select_lex::inc_in_sum_expr()
3494 {
3495   in_sum_expr++;
3496   return 0;
3497 }
3498 
3499 
get_in_sum_expr()3500 uint st_select_lex::get_in_sum_expr()
3501 {
3502   return in_sum_expr;
3503 }
3504 
3505 
get_table_list()3506 TABLE_LIST* st_select_lex::get_table_list()
3507 {
3508   return table_list.first;
3509 }
3510 
get_item_list()3511 List<Item>* st_select_lex::get_item_list()
3512 {
3513   return &item_list;
3514 }
3515 
get_table_join_options()3516 ulong st_select_lex::get_table_join_options()
3517 {
3518   return table_join_options;
3519 }
3520 
3521 
setup_ref_array(THD * thd,uint order_group_num)3522 bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
3523 {
3524 
3525   if (!((options & SELECT_DISTINCT) && !group_list.elements))
3526     hidden_bit_fields= 0;
3527 
3528   // find_order_in_list() may need some extra space, so multiply by two.
3529   order_group_num*= 2;
3530 
3531   /*
3532     We have to create array in prepared statement memory if it is a
3533     prepared statement
3534   */
3535   Query_arena *arena= thd->stmt_arena;
3536   const size_t n_elems= (n_sum_items +
3537                        n_child_sum_items +
3538                        item_list.elements +
3539                        select_n_reserved +
3540                        select_n_having_items +
3541                        select_n_where_fields +
3542                        order_group_num +
3543                        hidden_bit_fields +
3544                        fields_in_window_functions) * (size_t) 5;
3545   DBUG_ASSERT(n_elems % 5 == 0);
3546   if (!ref_pointer_array.is_null())
3547   {
3548     /*
3549       We need to take 'n_sum_items' into account when allocating the array,
3550       and this may actually increase during the optimization phase due to
3551       MIN/MAX rewrite in Item_in_subselect::single_value_transformer.
3552       In the usual case we can reuse the array from the prepare phase.
3553       If we need a bigger array, we must allocate a new one.
3554      */
3555     if (ref_pointer_array.size() >= n_elems)
3556       return false;
3557    }
3558   Item **array= static_cast<Item**>(arena->alloc(sizeof(Item*) * n_elems));
3559   if (likely(array != NULL))
3560     ref_pointer_array= Ref_ptr_array(array, n_elems);
3561 
3562   return array == NULL;
3563 }
3564 
3565 
3566 /*
3567   @brief
3568     Print the whole statement
3569 
3570     @param str         Print into this string
3571     @param query_type  Flags describing how to print
3572 
3573   @detail
3574     The intent is to allow to eventually print back any query.
3575 
3576     This is useful e.g. for storage engines that take over diferrent kinds of
3577     queries
3578 */
3579 
print(String * str,enum_query_type query_type)3580 void LEX::print(String *str, enum_query_type query_type)
3581 {
3582   if (sql_command == SQLCOM_UPDATE)
3583   {
3584     SELECT_LEX *sel= first_select_lex();
3585     str->append(STRING_WITH_LEN("UPDATE "));
3586     if (ignore)
3587       str->append(STRING_WITH_LEN("IGNORE "));
3588     // table name. If the query was using a view, we need
3589     // the underlying table name, not the view name
3590     TABLE_LIST *base_tbl= query_tables->table->pos_in_table_list;
3591     base_tbl->print(thd, table_map(0), str, query_type);
3592     str->append(STRING_WITH_LEN(" SET "));
3593     // print item assignments
3594     List_iterator<Item> it(sel->item_list);
3595     List_iterator<Item> it2(value_list);
3596     Item *col_ref, *value;
3597     bool first= true;
3598     while ((col_ref= it++) && (value= it2++))
3599     {
3600       if (first)
3601         first= false;
3602       else
3603         str->append(STRING_WITH_LEN(", "));
3604       col_ref->print(str, query_type);
3605       str->append(STRING_WITH_LEN("="));
3606       value->print(str, query_type);
3607     }
3608 
3609     if (sel->where)
3610     {
3611       str->append(STRING_WITH_LEN(" WHERE "));
3612       sel->where->print(str, query_type);
3613     }
3614 
3615     if (sel->order_list.elements)
3616     {
3617       str->append(STRING_WITH_LEN(" ORDER BY "));
3618       for (ORDER *ord= sel->order_list.first; ord; ord= ord->next)
3619       {
3620         if (ord != sel->order_list.first)
3621           str->append(STRING_WITH_LEN(", "));
3622         (*ord->item)->print(str, query_type);
3623       }
3624     }
3625     if (sel->select_limit)
3626     {
3627       str->append(STRING_WITH_LEN(" LIMIT "));
3628       sel->select_limit->print(str, query_type);
3629     }
3630   }
3631   else if (sql_command == SQLCOM_DELETE)
3632   {
3633     SELECT_LEX *sel= first_select_lex();
3634     str->append(STRING_WITH_LEN("DELETE "));
3635     if (ignore)
3636       str->append(STRING_WITH_LEN("IGNORE "));
3637 
3638     str->append(STRING_WITH_LEN("FROM "));
3639     // table name. If the query was using a view, we need
3640     // the underlying table name, not the view name
3641     TABLE_LIST *base_tbl= query_tables->table->pos_in_table_list;
3642     base_tbl->print(thd, table_map(0), str, query_type);
3643 
3644     if (sel->where)
3645     {
3646       str->append(STRING_WITH_LEN(" WHERE "));
3647       sel->where->print(str, query_type);
3648     }
3649 
3650     if (sel->order_list.elements)
3651     {
3652       str->append(STRING_WITH_LEN(" ORDER BY "));
3653       for (ORDER *ord= sel->order_list.first; ord; ord= ord->next)
3654       {
3655         if (ord != sel->order_list.first)
3656           str->append(STRING_WITH_LEN(", "));
3657         (*ord->item)->print(str, query_type);
3658       }
3659     }
3660     if (sel->select_limit)
3661     {
3662       str->append(STRING_WITH_LEN(" LIMIT "));
3663       sel->select_limit->print(str, query_type);
3664     }
3665   }
3666   else
3667     DBUG_ASSERT(0); // Not implemented yet
3668 }
3669 
print(String * str,enum_query_type query_type)3670 void st_select_lex_unit::print(String *str, enum_query_type query_type)
3671 {
3672   if (with_clause)
3673     with_clause->print(thd, str, query_type);
3674   for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
3675   {
3676     if (sl != first_select())
3677     {
3678       switch (sl->linkage)
3679       {
3680       default:
3681         DBUG_ASSERT(0);
3682         /* fall through */
3683       case UNION_TYPE:
3684         str->append(STRING_WITH_LEN(" union "));
3685         break;
3686       case INTERSECT_TYPE:
3687         str->append(STRING_WITH_LEN(" intersect "));
3688         break;
3689       case EXCEPT_TYPE:
3690         str->append(STRING_WITH_LEN(" except "));
3691         break;
3692       }
3693       if (!sl->distinct)
3694         str->append(STRING_WITH_LEN("all "));
3695     }
3696     if (sl->braces)
3697       str->append('(');
3698     sl->print(thd, str, query_type);
3699     if (sl->braces)
3700       str->append(')');
3701   }
3702   if (fake_select_lex)
3703   {
3704     if (fake_select_lex->order_list.elements)
3705     {
3706       str->append(STRING_WITH_LEN(" order by "));
3707       fake_select_lex->print_order(str,
3708         fake_select_lex->order_list.first,
3709         query_type);
3710     }
3711     fake_select_lex->print_limit(thd, str, query_type);
3712   }
3713   else if (saved_fake_select_lex)
3714     saved_fake_select_lex->print_limit(thd, str, query_type);
3715 }
3716 
3717 
print_order(String * str,ORDER * order,enum_query_type query_type)3718 void st_select_lex::print_order(String *str,
3719                                 ORDER *order,
3720                                 enum_query_type query_type)
3721 {
3722   for (; order; order= order->next)
3723   {
3724     if (order->counter_used)
3725     {
3726       char buffer[20];
3727       size_t length= my_snprintf(buffer, 20, "%d", order->counter);
3728       str->append(buffer, (uint) length);
3729     }
3730     else
3731     {
3732       /* replace numeric reference with equivalent for ORDER constant */
3733       if (order->item[0]->is_order_clause_position())
3734       {
3735         /* make it expression instead of integer constant */
3736         str->append(STRING_WITH_LEN("''"));
3737       }
3738       else
3739         (*order->item)->print(str, query_type);
3740     }
3741     if (order->direction == ORDER::ORDER_DESC)
3742        str->append(STRING_WITH_LEN(" desc"));
3743     if (order->next)
3744       str->append(',');
3745   }
3746 }
3747 
3748 
print_limit(THD * thd,String * str,enum_query_type query_type)3749 void st_select_lex::print_limit(THD *thd,
3750                                 String *str,
3751                                 enum_query_type query_type)
3752 {
3753   SELECT_LEX_UNIT *unit= master_unit();
3754   Item_subselect *item= unit->item;
3755 
3756   if (item && unit->global_parameters() == this)
3757   {
3758     Item_subselect::subs_type subs_type= item->substype();
3759     if (subs_type == Item_subselect::IN_SUBS ||
3760         subs_type == Item_subselect::ALL_SUBS)
3761     {
3762       return;
3763     }
3764   }
3765   if (explicit_limit && select_limit)
3766   {
3767     str->append(STRING_WITH_LEN(" limit "));
3768     if (offset_limit)
3769     {
3770       offset_limit->print(str, query_type);
3771       str->append(',');
3772     }
3773     select_limit->print(str, query_type);
3774   }
3775 }
3776 
3777 
3778 /**
3779   @brief Restore the LEX and THD in case of a parse error.
3780 
3781   This is a clean up call that is invoked by the Bison generated
3782   parser before returning an error from MYSQLparse. If your
3783   semantic actions manipulate with the global thread state (which
3784   is a very bad practice and should not normally be employed) and
3785   need a clean-up in case of error, and you can not use %destructor
3786   rule in the grammar file itself, this function should be used
3787   to implement the clean up.
3788 */
3789 
cleanup_lex_after_parse_error(THD * thd)3790 void LEX::cleanup_lex_after_parse_error(THD *thd)
3791 {
3792   /*
3793     Delete sphead for the side effect of restoring of the original
3794     LEX state, thd->lex, thd->mem_root and thd->free_list if they
3795     were replaced when parsing stored procedure statements.  We
3796     will never use sphead object after a parse error, so it's okay
3797     to delete it only for the sake of the side effect.
3798     TODO: make this functionality explicit in sp_head class.
3799     Sic: we must nullify the member of the main lex, not the
3800     current one that will be thrown away
3801   */
3802   if (thd->lex->sphead)
3803   {
3804     sp_package *pkg;
3805     thd->lex->sphead->restore_thd_mem_root(thd);
3806     if ((pkg= thd->lex->sphead->m_parent))
3807     {
3808       /*
3809         If a syntax error happened inside a package routine definition,
3810         then thd->lex points to the routine sublex. We need to restore to
3811         the top level LEX.
3812       */
3813       DBUG_ASSERT(pkg->m_top_level_lex);
3814       DBUG_ASSERT(pkg == pkg->m_top_level_lex->sphead);
3815       pkg->restore_thd_mem_root(thd);
3816       LEX *top= pkg->m_top_level_lex;
3817       sp_package::destroy(pkg);
3818       thd->lex= top;
3819       thd->lex->sphead= NULL;
3820     }
3821     else
3822     {
3823       sp_head::destroy(thd->lex->sphead);
3824       thd->lex->sphead= NULL;
3825     }
3826   }
3827 }
3828 
3829 /*
3830   Initialize (or reset) Query_tables_list object.
3831 
3832   SYNOPSIS
3833     reset_query_tables_list()
3834       init  TRUE  - we should perform full initialization of object with
3835                     allocating needed memory
3836             FALSE - object is already initialized so we should only reset
3837                     its state so it can be used for parsing/processing
3838                     of new statement
3839 
3840   DESCRIPTION
3841     This method initializes Query_tables_list so it can be used as part
3842     of LEX object for parsing/processing of statement. One can also use
3843     this method to reset state of already initialized Query_tables_list
3844     so it can be used for processing of new statement.
3845 */
3846 
reset_query_tables_list(bool init)3847 void Query_tables_list::reset_query_tables_list(bool init)
3848 {
3849   sql_command= SQLCOM_END;
3850   if (!init && query_tables)
3851   {
3852     TABLE_LIST *table= query_tables;
3853     for (;;)
3854     {
3855       delete table->view;
3856       if (query_tables_last == &table->next_global ||
3857           !(table= table->next_global))
3858         break;
3859     }
3860   }
3861   query_tables= 0;
3862   query_tables_last= &query_tables;
3863   query_tables_own_last= 0;
3864   if (init)
3865   {
3866     /*
3867       We delay real initialization of hash (and therefore related
3868       memory allocation) until first insertion into this hash.
3869     */
3870     my_hash_clear(&sroutines);
3871   }
3872   else if (sroutines.records)
3873   {
3874     /* Non-zero sroutines.records means that hash was initialized. */
3875     my_hash_reset(&sroutines);
3876   }
3877   sroutines_list.empty();
3878   sroutines_list_own_last= sroutines_list.next;
3879   sroutines_list_own_elements= 0;
3880   binlog_stmt_flags= 0;
3881   stmt_accessed_table_flag= 0;
3882 }
3883 
3884 
3885 /*
3886   Destroy Query_tables_list object with freeing all resources used by it.
3887 
3888   SYNOPSIS
3889     destroy_query_tables_list()
3890 */
3891 
destroy_query_tables_list()3892 void Query_tables_list::destroy_query_tables_list()
3893 {
3894   my_hash_free(&sroutines);
3895 }
3896 
3897 
3898 /*
3899   Initialize LEX object.
3900 
3901   SYNOPSIS
3902     LEX::LEX()
3903 
3904   NOTE
3905     LEX object initialized with this constructor can be used as part of
3906     THD object for which one can safely call open_tables(), lock_tables()
3907     and close_thread_tables() functions. But it is not yet ready for
3908     statement parsing. On should use lex_start() function to prepare LEX
3909     for this.
3910 */
3911 
LEX()3912 LEX::LEX()
3913   : explain(NULL), result(0), part_info(NULL), arena_for_set_stmt(0), mem_root_for_set_stmt(0),
3914     option_type(OPT_DEFAULT), context_analysis_only(0), sphead(0),
3915     default_used(0), is_lex_started(0), limit_rows_examined_cnt(ULONGLONG_MAX)
3916 {
3917 
3918   init_dynamic_array2(PSI_INSTRUMENT_ME, &plugins, sizeof(plugin_ref),
3919                       plugins_static_buffer, INITIAL_LEX_PLUGIN_LIST_SIZE,
3920                       INITIAL_LEX_PLUGIN_LIST_SIZE, 0);
3921   reset_query_tables_list(TRUE);
3922   mi.init();
3923   init_dynamic_array2(PSI_INSTRUMENT_ME, &delete_gtid_domain, sizeof(uint32),
3924                       gtid_domain_static_buffer,
3925                       initial_gtid_domain_buffer_size,
3926                       initial_gtid_domain_buffer_size, 0);
3927   unit.slave= &builtin_select;
3928 }
3929 
3930 
3931 /*
3932   Check whether the merging algorithm can be used on this VIEW
3933 
3934   SYNOPSIS
3935     LEX::can_be_merged()
3936 
3937   DESCRIPTION
3938     We can apply merge algorithm if it is single SELECT view  with
3939     subqueries only in WHERE clause (we do not count SELECTs of underlying
3940     views, and second level subqueries) and we have not grpouping, ordering,
3941     HAVING clause, aggregate functions, DISTINCT clause, LIMIT clause and
3942     several underlying tables.
3943 
3944   RETURN
3945     FALSE - only temporary table algorithm can be used
3946     TRUE  - merge algorithm can be used
3947 */
3948 
can_be_merged()3949 bool LEX::can_be_merged()
3950 {
3951   // TODO: do not forget implement case when select_lex.table_list.elements==0
3952 
3953   /* find non VIEW subqueries/unions */
3954   bool selects_allow_merge= (first_select_lex()->next_select() == 0 &&
3955                              !(first_select_lex()->uncacheable &
3956                                UNCACHEABLE_RAND));
3957   if (selects_allow_merge)
3958   {
3959     for (SELECT_LEX_UNIT *tmp_unit= first_select_lex()->first_inner_unit();
3960          tmp_unit;
3961          tmp_unit= tmp_unit->next_unit())
3962     {
3963       if (tmp_unit->first_select()->parent_lex == this &&
3964           (tmp_unit->item != 0 &&
3965            (tmp_unit->item->place() != IN_WHERE &&
3966             tmp_unit->item->place() != IN_ON &&
3967             tmp_unit->item->place() != SELECT_LIST)))
3968       {
3969         selects_allow_merge= 0;
3970         break;
3971       }
3972     }
3973   }
3974 
3975   return (selects_allow_merge &&
3976           first_select_lex()->group_list.elements == 0 &&
3977           first_select_lex()->having == 0 &&
3978           first_select_lex()->with_sum_func == 0 &&
3979           first_select_lex()->table_list.elements >= 1 &&
3980           !(first_select_lex()->options & SELECT_DISTINCT) &&
3981           first_select_lex()->select_limit == 0);
3982 }
3983 
3984 
3985 /*
3986   check if command can use VIEW with MERGE algorithm (for top VIEWs)
3987 
3988   SYNOPSIS
3989     LEX::can_use_merged()
3990 
3991   DESCRIPTION
3992     Only listed here commands can use merge algorithm in top level
3993     SELECT_LEX (for subqueries will be used merge algorithm if
3994     LEX::can_not_use_merged() is not TRUE).
3995 
3996   RETURN
3997     FALSE - command can't use merged VIEWs
3998     TRUE  - VIEWs with MERGE algorithms can be used
3999 */
4000 
can_use_merged()4001 bool LEX::can_use_merged()
4002 {
4003   switch (sql_command)
4004   {
4005   case SQLCOM_SELECT:
4006   case SQLCOM_CREATE_TABLE:
4007   case SQLCOM_UPDATE:
4008   case SQLCOM_UPDATE_MULTI:
4009   case SQLCOM_DELETE:
4010   case SQLCOM_DELETE_MULTI:
4011   case SQLCOM_INSERT:
4012   case SQLCOM_INSERT_SELECT:
4013   case SQLCOM_REPLACE:
4014   case SQLCOM_REPLACE_SELECT:
4015   case SQLCOM_LOAD:
4016     return TRUE;
4017   default:
4018     return FALSE;
4019   }
4020 }
4021 
4022 /*
4023   Check if command can't use merged views in any part of command
4024 
4025   SYNOPSIS
4026     LEX::can_not_use_merged()
4027 
4028   DESCRIPTION
4029     Temporary table algorithm will be used on all SELECT levels for queries
4030     listed here (see also LEX::can_use_merged()).
4031 
4032   RETURN
4033     FALSE - command can't use merged VIEWs
4034     TRUE  - VIEWs with MERGE algorithms can be used
4035 */
4036 
can_not_use_merged()4037 bool LEX::can_not_use_merged()
4038 {
4039   switch (sql_command)
4040   {
4041   case SQLCOM_CREATE_VIEW:
4042   case SQLCOM_SHOW_CREATE:
4043   /*
4044     SQLCOM_SHOW_FIELDS is necessary to make
4045     information schema tables working correctly with views.
4046     see get_schema_tables_result function
4047   */
4048   case SQLCOM_SHOW_FIELDS:
4049     return TRUE;
4050   default:
4051     return FALSE;
4052   }
4053 }
4054 
4055 /**
4056   Detect that we need only table structure of derived table/view.
4057 
4058   Also used by I_S tables (@see create_schema_table) to detect that
4059   they need a full table structure and cannot optimize unused columns away
4060 
4061   @retval TRUE yes, we need only structure
4062   @retval FALSE no, we need data
4063 */
4064 
only_view_structure()4065 bool LEX::only_view_structure()
4066 {
4067   switch (sql_command) {
4068   case SQLCOM_SHOW_CREATE:
4069   case SQLCOM_CHECKSUM:
4070   case SQLCOM_SHOW_TABLES:
4071   case SQLCOM_SHOW_FIELDS:
4072   case SQLCOM_REVOKE_ALL:
4073   case SQLCOM_REVOKE:
4074   case SQLCOM_GRANT:
4075   case SQLCOM_CREATE_VIEW:
4076     return TRUE;
4077   case SQLCOM_CREATE_TABLE:
4078     return create_info.like();
4079   default:
4080     return FALSE;
4081   }
4082 }
4083 
4084 
4085 /*
4086   Should Items_ident be printed correctly
4087 
4088   SYNOPSIS
4089     need_correct_ident()
4090 
4091   RETURN
4092     TRUE yes, we need only structure
4093     FALSE no, we need data
4094 */
4095 
4096 
need_correct_ident()4097 bool LEX::need_correct_ident()
4098 {
4099   switch(sql_command)
4100   {
4101   case SQLCOM_SHOW_CREATE:
4102   case SQLCOM_SHOW_TABLES:
4103   case SQLCOM_CREATE_VIEW:
4104     return TRUE;
4105   default:
4106     return FALSE;
4107   }
4108 }
4109 
4110 /*
4111   Get effective type of CHECK OPTION for given view
4112 
4113   SYNOPSIS
4114     get_effective_with_check()
4115     view    given view
4116 
4117   NOTE
4118     It have not sense to set CHECK OPTION for SELECT satement or subqueries,
4119     so we do not.
4120 
4121   RETURN
4122     VIEW_CHECK_NONE      no need CHECK OPTION
4123     VIEW_CHECK_LOCAL     CHECK OPTION LOCAL
4124     VIEW_CHECK_CASCADED  CHECK OPTION CASCADED
4125 */
4126 
get_effective_with_check(TABLE_LIST * view)4127 uint8 LEX::get_effective_with_check(TABLE_LIST *view)
4128 {
4129   if (view->select_lex->master_unit() == &unit &&
4130       which_check_option_applicable())
4131     return (uint8)view->with_check;
4132   return VIEW_CHECK_NONE;
4133 }
4134 
4135 
4136 /**
4137   This method should be called only during parsing.
4138   It is aware of compound statements (stored routine bodies)
4139   and will initialize the destination with the default
4140   database of the stored routine, rather than the default
4141   database of the connection it is parsed in.
4142   E.g. if one has no current database selected, or current database
4143   set to 'bar' and then issues:
4144 
4145   CREATE PROCEDURE foo.p1() BEGIN SELECT * FROM t1 END//
4146 
4147   t1 is meant to refer to foo.t1, not to bar.t1.
4148 
4149   This method is needed to support this rule.
4150 
4151   @return TRUE in case of error (parsing should be aborted, FALSE in
4152   case of success
4153 */
4154 
copy_db_to(LEX_CSTRING * to)4155 bool LEX::copy_db_to(LEX_CSTRING *to)
4156 {
4157   if (sphead && sphead->m_name.str)
4158   {
4159     DBUG_ASSERT(sphead->m_db.str && sphead->m_db.length);
4160     /*
4161       It is safe to assign the string by-pointer, both sphead and
4162       its statements reside in the same memory root.
4163     */
4164     *to= sphead->m_db;
4165     return FALSE;
4166   }
4167   return thd->copy_db_to(to);
4168 }
4169 
4170 /**
4171   Initialize offset and limit counters.
4172 
4173   @param sl SELECT_LEX to get offset and limit from.
4174 */
4175 
set_limit(st_select_lex * sl)4176 void st_select_lex_unit::set_limit(st_select_lex *sl)
4177 {
4178   DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
4179 
4180   lim.set_limit(sl->get_limit(), sl->get_offset());
4181 }
4182 
4183 
4184 /**
4185   Decide if a temporary table is needed for the UNION.
4186 
4187   @retval true  A temporary table is needed.
4188   @retval false A temporary table is not needed.
4189  */
4190 
union_needs_tmp_table()4191 bool st_select_lex_unit::union_needs_tmp_table()
4192 {
4193   if (with_element && with_element->is_recursive)
4194     return true;
4195   if (!with_wrapped_tvc)
4196   {
4197     for (st_select_lex *sl= first_select(); sl; sl=sl->next_select())
4198     {
4199       if (sl->tvc && sl->tvc->to_be_wrapped_as_with_tail())
4200       {
4201         with_wrapped_tvc= true;
4202         break;
4203       }
4204       if (sl != first_select() && sl->linkage != UNION_TYPE)
4205         return true;
4206     }
4207   }
4208   if (with_wrapped_tvc)
4209     return true;
4210   return union_distinct != NULL ||
4211     global_parameters()->order_list.elements != 0 ||
4212     thd->lex->sql_command == SQLCOM_INSERT_SELECT ||
4213     thd->lex->sql_command == SQLCOM_REPLACE_SELECT;
4214 }
4215 
4216 /**
4217   @brief Set the initial purpose of this TABLE_LIST object in the list of used
4218     tables.
4219 
4220   We need to track this information on table-by-table basis, since when this
4221   table becomes an element of the pre-locked list, it's impossible to identify
4222   which SQL sub-statement it has been originally used in.
4223 
4224   E.g.:
4225 
4226   User request:                 SELECT * FROM t1 WHERE f1();
4227   FUNCTION f1():                DELETE FROM t2; RETURN 1;
4228   BEFORE DELETE trigger on t2:  INSERT INTO t3 VALUES (old.a);
4229 
4230   For this user request, the pre-locked list will contain t1, t2, t3
4231   table elements, each needed for different DML.
4232 
4233   The trigger event map is updated to reflect INSERT, UPDATE, DELETE,
4234   REPLACE, LOAD DATA, CREATE TABLE .. SELECT, CREATE TABLE ..
4235   REPLACE SELECT statements, and additionally ON DUPLICATE KEY UPDATE
4236   clause.
4237 */
4238 
set_trg_event_type_for_tables()4239 void LEX::set_trg_event_type_for_tables()
4240 {
4241   uint8 new_trg_event_map= 0;
4242   DBUG_ENTER("LEX::set_trg_event_type_for_tables");
4243 
4244   /*
4245     Some auxiliary operations
4246     (e.g. GRANT processing) create TABLE_LIST instances outside
4247     the parser. Additionally, some commands (e.g. OPTIMIZE) change
4248     the lock type for a table only after parsing is done. Luckily,
4249     these do not fire triggers and do not need to pre-load them.
4250     For these TABLE_LISTs set_trg_event_type is never called, and
4251     trg_event_map is always empty. That means that the pre-locking
4252     algorithm will ignore triggers defined on these tables, if
4253     any, and the execution will either fail with an assert in
4254     sql_trigger.cc or with an error that a used table was not
4255     pre-locked, in case of a production build.
4256 
4257     TODO: this usage pattern creates unnecessary module dependencies
4258     and should be rewritten to go through the parser.
4259     Table list instances created outside the parser in most cases
4260     refer to mysql.* system tables. It is not allowed to have
4261     a trigger on a system table, but keeping track of
4262     initialization provides extra safety in case this limitation
4263     is circumvented.
4264   */
4265 
4266   switch (sql_command) {
4267   case SQLCOM_LOCK_TABLES:
4268   /*
4269     On a LOCK TABLE, all triggers must be pre-loaded for this TABLE_LIST
4270     when opening an associated TABLE.
4271   */
4272     new_trg_event_map= trg2bit(TRG_EVENT_INSERT) | trg2bit(TRG_EVENT_UPDATE) |
4273                        trg2bit(TRG_EVENT_DELETE);
4274     break;
4275   /*
4276     Basic INSERT. If there is an additional ON DUPLIATE KEY UPDATE
4277     clause, it will be handled later in this method.
4278   */
4279   case SQLCOM_INSERT:                           /* fall through */
4280   case SQLCOM_INSERT_SELECT:
4281   /*
4282     LOAD DATA ... INFILE is expected to fire BEFORE/AFTER INSERT
4283     triggers.
4284     If the statement also has REPLACE clause, it will be
4285     handled later in this method.
4286   */
4287   case SQLCOM_LOAD:                             /* fall through */
4288   /*
4289     REPLACE is semantically equivalent to INSERT. In case
4290     of a primary or unique key conflict, it deletes the old
4291     record and inserts a new one. So we also may need to
4292     fire ON DELETE triggers. This functionality is handled
4293     later in this method.
4294   */
4295   case SQLCOM_REPLACE:                          /* fall through */
4296   case SQLCOM_REPLACE_SELECT:
4297   /*
4298     CREATE TABLE ... SELECT defaults to INSERT if the table or
4299     view already exists. REPLACE option of CREATE TABLE ...
4300     REPLACE SELECT is handled later in this method.
4301   */
4302   case SQLCOM_CREATE_TABLE:
4303   case SQLCOM_CREATE_SEQUENCE:
4304     new_trg_event_map|= trg2bit(TRG_EVENT_INSERT);
4305     break;
4306   /* Basic update and multi-update */
4307   case SQLCOM_UPDATE:                           /* fall through */
4308   case SQLCOM_UPDATE_MULTI:
4309     new_trg_event_map|= trg2bit(TRG_EVENT_UPDATE);
4310     break;
4311   /* Basic delete and multi-delete */
4312   case SQLCOM_DELETE:                           /* fall through */
4313   case SQLCOM_DELETE_MULTI:
4314     new_trg_event_map|= trg2bit(TRG_EVENT_DELETE);
4315     break;
4316   default:
4317     break;
4318   }
4319 
4320   switch (duplicates) {
4321   case DUP_UPDATE:
4322     new_trg_event_map|= trg2bit(TRG_EVENT_UPDATE);
4323     break;
4324   case DUP_REPLACE:
4325     new_trg_event_map|= trg2bit(TRG_EVENT_DELETE);
4326     break;
4327   case DUP_ERROR:
4328   default:
4329     break;
4330   }
4331 
4332   if (period_conditions.is_set())
4333   {
4334     switch (sql_command)
4335     {
4336     case SQLCOM_DELETE:
4337     case SQLCOM_UPDATE:
4338     case SQLCOM_REPLACE:
4339       new_trg_event_map |= trg2bit(TRG_EVENT_INSERT);
4340     default:
4341       break;
4342     }
4343   }
4344 
4345 
4346   /*
4347     Do not iterate over sub-selects, only the tables in the outermost
4348     SELECT_LEX can be modified, if any.
4349   */
4350   TABLE_LIST *tables= first_select_lex()->get_table_list();
4351 
4352   while (tables)
4353   {
4354     /*
4355       This is a fast check to filter out statements that do
4356       not change data, or tables  on the right side, in case of
4357       INSERT .. SELECT, CREATE TABLE .. SELECT and so on.
4358       Here we also filter out OPTIMIZE statement and non-updateable
4359       views, for which lock_type is TL_UNLOCK or TL_READ after
4360       parsing.
4361     */
4362     if (static_cast<int>(tables->lock_type) >=
4363         static_cast<int>(TL_WRITE_ALLOW_WRITE))
4364       tables->trg_event_map= new_trg_event_map;
4365     tables= tables->next_local;
4366   }
4367   DBUG_VOID_RETURN;
4368 }
4369 
4370 
4371 /*
4372   Unlink the first table from the global table list and the first table from
4373   outer select (lex->select_lex) local list
4374 
4375   SYNOPSIS
4376     unlink_first_table()
4377     link_to_local   Set to 1 if caller should link this table to local list
4378 
4379   NOTES
4380     We assume that first tables in both lists is the same table or the local
4381     list is empty.
4382 
4383   RETURN
4384     0      If 'query_tables' == 0
4385     unlinked table
4386       In this case link_to_local is set.
4387 
4388 */
unlink_first_table(bool * link_to_local)4389 TABLE_LIST *LEX::unlink_first_table(bool *link_to_local)
4390 {
4391   TABLE_LIST *first;
4392   if ((first= query_tables))
4393   {
4394     /*
4395       Exclude from global table list
4396     */
4397     if ((query_tables= query_tables->next_global))
4398       query_tables->prev_global= &query_tables;
4399     else
4400       query_tables_last= &query_tables;
4401     first->next_global= 0;
4402 
4403     /*
4404       and from local list if it is not empty
4405     */
4406     if ((*link_to_local= MY_TEST(first_select_lex()->table_list.first)))
4407     {
4408       first_select_lex()->context.table_list=
4409          first_select_lex()->context.first_name_resolution_table=
4410          first->next_local;
4411       first_select_lex()->table_list.first= first->next_local;
4412       first_select_lex()->table_list.elements--;  //safety
4413       first->next_local= 0;
4414       /*
4415         Ensure that the global list has the same first table as the local
4416         list.
4417       */
4418       first_lists_tables_same();
4419     }
4420   }
4421   return first;
4422 }
4423 
4424 
4425 /*
4426   Bring first local table of first most outer select to first place in global
4427   table list
4428 
4429   SYNOPSYS
4430      LEX::first_lists_tables_same()
4431 
4432   NOTES
4433     In many cases (for example, usual INSERT/DELETE/...) the first table of
4434     main SELECT_LEX have special meaning => check that it is the first table
4435     in global list and re-link to be first in the global list if it is
4436     necessary.  We need such re-linking only for queries with sub-queries in
4437     the select list, as only in this case tables of sub-queries will go to
4438     the global list first.
4439 */
4440 
first_lists_tables_same()4441 void LEX::first_lists_tables_same()
4442 {
4443   TABLE_LIST *first_table= first_select_lex()->table_list.first;
4444   if (query_tables != first_table && first_table != 0)
4445   {
4446     TABLE_LIST *next;
4447     if (query_tables_last == &first_table->next_global)
4448       query_tables_last= first_table->prev_global;
4449 
4450     if (query_tables_own_last == &first_table->next_global)
4451       query_tables_own_last= first_table->prev_global;
4452 
4453     if ((next= *first_table->prev_global= first_table->next_global))
4454       next->prev_global= first_table->prev_global;
4455     /* include in new place */
4456     first_table->next_global= query_tables;
4457     /*
4458        We are sure that query_tables is not 0, because first_table was not
4459        first table in the global list => we can use
4460        query_tables->prev_global without check of query_tables
4461     */
4462     query_tables->prev_global= &first_table->next_global;
4463     first_table->prev_global= &query_tables;
4464     query_tables= first_table;
4465   }
4466 }
4467 
fix_first_select_number()4468 void LEX::fix_first_select_number()
4469 {
4470   SELECT_LEX *first= first_select_lex();
4471   if (first && first->select_number != 1)
4472   {
4473     uint num= first->select_number;
4474     for (SELECT_LEX *sel= all_selects_list;
4475          sel;
4476          sel= sel->next_select_in_list())
4477     {
4478       if (sel->select_number < num)
4479         sel->select_number++;
4480     }
4481     first->select_number= 1;
4482   }
4483 }
4484 
4485 
4486 /*
4487   Link table back that was unlinked with unlink_first_table()
4488 
4489   SYNOPSIS
4490     link_first_table_back()
4491     link_to_local        do we need link this table to local
4492 
4493   RETURN
4494     global list
4495 */
4496 
link_first_table_back(TABLE_LIST * first,bool link_to_local)4497 void LEX::link_first_table_back(TABLE_LIST *first,
4498                                 bool link_to_local)
4499 {
4500   if (first)
4501   {
4502     if ((first->next_global= query_tables))
4503       query_tables->prev_global= &first->next_global;
4504     else
4505       query_tables_last= &first->next_global;
4506     query_tables= first;
4507 
4508     if (link_to_local)
4509     {
4510       first->next_local= first_select_lex()->table_list.first;
4511       first_select_lex()->context.table_list= first;
4512       first_select_lex()->table_list.first= first;
4513       first_select_lex()->table_list.elements++; //safety
4514     }
4515   }
4516 }
4517 
4518 
4519 
4520 /*
4521   cleanup lex for case when we open table by table for processing
4522 
4523   SYNOPSIS
4524     LEX::cleanup_after_one_table_open()
4525 
4526   NOTE
4527     This method is mostly responsible for cleaning up of selects lists and
4528     derived tables state. To rollback changes in Query_tables_list one has
4529     to call Query_tables_list::reset_query_tables_list(FALSE).
4530 */
4531 
cleanup_after_one_table_open()4532 void LEX::cleanup_after_one_table_open()
4533 {
4534   /*
4535     thd->lex->derived_tables & additional units may be set if we open
4536     a view. It is necessary to clear thd->lex->derived_tables flag
4537     to prevent processing of derived tables during next open_and_lock_tables
4538     if next table is a real table and cleanup & remove underlying units
4539     NOTE: all units will be connected to thd->lex->select_lex, because we
4540     have not UNION on most upper level.
4541     */
4542   if (all_selects_list != first_select_lex())
4543   {
4544     derived_tables= 0;
4545     first_select_lex()->exclude_from_table_unique_test= false;
4546     /* cleunup underlying units (units of VIEW) */
4547     for (SELECT_LEX_UNIT *un= first_select_lex()->first_inner_unit();
4548          un;
4549          un= un->next_unit())
4550       un->cleanup();
4551     /* reduce all selects list to default state */
4552     all_selects_list= first_select_lex();
4553     /* remove underlying units (units of VIEW) subtree */
4554     first_select_lex()->cut_subtree();
4555   }
4556 }
4557 
4558 
4559 /*
4560   Save current state of Query_tables_list for this LEX, and prepare it
4561   for processing of new statemnt.
4562 
4563   SYNOPSIS
4564     reset_n_backup_query_tables_list()
4565       backup  Pointer to Query_tables_list instance to be used for backup
4566 */
4567 
reset_n_backup_query_tables_list(Query_tables_list * backup)4568 void LEX::reset_n_backup_query_tables_list(Query_tables_list *backup)
4569 {
4570   backup->set_query_tables_list(this);
4571   /*
4572     We have to perform full initialization here since otherwise we
4573     will damage backed up state.
4574   */
4575   reset_query_tables_list(TRUE);
4576 }
4577 
4578 
4579 /*
4580   Restore state of Query_tables_list for this LEX from backup.
4581 
4582   SYNOPSIS
4583     restore_backup_query_tables_list()
4584       backup  Pointer to Query_tables_list instance used for backup
4585 */
4586 
restore_backup_query_tables_list(Query_tables_list * backup)4587 void LEX::restore_backup_query_tables_list(Query_tables_list *backup)
4588 {
4589   destroy_query_tables_list();
4590   set_query_tables_list(backup);
4591 }
4592 
4593 
4594 /*
4595   Checks for usage of routines and/or tables in a parsed statement
4596 
4597   SYNOPSIS
4598     LEX:table_or_sp_used()
4599 
4600   RETURN
4601     FALSE  No routines and tables used
4602     TRUE   Either or both routines and tables are used.
4603 */
4604 
table_or_sp_used()4605 bool LEX::table_or_sp_used()
4606 {
4607   DBUG_ENTER("table_or_sp_used");
4608 
4609   if (sroutines.records || query_tables)
4610     DBUG_RETURN(TRUE);
4611 
4612   DBUG_RETURN(FALSE);
4613 }
4614 
4615 
4616 /*
4617   Do end-of-prepare fixup for list of tables and their merge-VIEWed tables
4618 
4619   SYNOPSIS
4620     fix_prepare_info_in_table_list()
4621       thd  Thread handle
4622       tbl  List of tables to process
4623 
4624   DESCRIPTION
4625     Perform end-end-of prepare fixup for list of tables, if any of the tables
4626     is a merge-algorithm VIEW, recursively fix up its underlying tables as
4627     well.
4628 
4629 */
4630 
fix_prepare_info_in_table_list(THD * thd,TABLE_LIST * tbl)4631 static void fix_prepare_info_in_table_list(THD *thd, TABLE_LIST *tbl)
4632 {
4633   for (; tbl; tbl= tbl->next_local)
4634   {
4635     if (tbl->on_expr && !tbl->prep_on_expr)
4636     {
4637       thd->check_and_register_item_tree(&tbl->prep_on_expr, &tbl->on_expr);
4638       tbl->on_expr= tbl->on_expr->copy_andor_structure(thd);
4639     }
4640     if (tbl->is_view_or_derived() && tbl->is_merged_derived())
4641     {
4642       SELECT_LEX *sel= tbl->get_single_select();
4643       fix_prepare_info_in_table_list(thd, sel->get_table_list());
4644     }
4645   }
4646 }
4647 
4648 
4649 /*
4650   Save WHERE/HAVING/ON clauses and replace them with disposable copies
4651 
4652   SYNOPSIS
4653     st_select_lex::fix_prepare_information
4654       thd          thread handler
4655       conds        in/out pointer to WHERE condition to be met at execution
4656       having_conds in/out pointer to HAVING condition to be met at execution
4657 
4658   DESCRIPTION
4659     The passed WHERE and HAVING are to be saved for the future executions.
4660     This function saves it, and returns a copy which can be thrashed during
4661     this execution of the statement. By saving/thrashing here we mean only
4662     We also save the chain of ORDER::next in group_list, in case
4663     the list is modified by remove_const().
4664     AND/OR trees.
4665     The function also calls fix_prepare_info_in_table_list that saves all
4666     ON expressions.
4667 */
4668 
fix_prepare_information(THD * thd,Item ** conds,Item ** having_conds)4669 void st_select_lex::fix_prepare_information(THD *thd, Item **conds,
4670                                             Item **having_conds)
4671 {
4672   DBUG_ENTER("st_select_lex::fix_prepare_information");
4673   if (!thd->stmt_arena->is_conventional() &&
4674       !(changed_elements & TOUCHED_SEL_COND))
4675   {
4676     Query_arena_stmt on_stmt_arena(thd);
4677     changed_elements|= TOUCHED_SEL_COND;
4678     if (group_list.first)
4679     {
4680       if (!group_list_ptrs)
4681       {
4682         void *mem= thd->stmt_arena->alloc(sizeof(Group_list_ptrs));
4683         group_list_ptrs= new (mem) Group_list_ptrs(thd->stmt_arena->mem_root);
4684       }
4685       group_list_ptrs->reserve(group_list.elements);
4686       for (ORDER *order= group_list.first; order; order= order->next)
4687       {
4688         group_list_ptrs->push_back(order);
4689       }
4690     }
4691     if (*conds)
4692     {
4693       thd->check_and_register_item_tree(&prep_where, conds);
4694       *conds= where= prep_where->copy_andor_structure(thd);
4695     }
4696     if (*having_conds)
4697     {
4698       thd->check_and_register_item_tree(&prep_having, having_conds);
4699       *having_conds= having= prep_having->copy_andor_structure(thd);
4700     }
4701     fix_prepare_info_in_table_list(thd, table_list.first);
4702   }
4703   DBUG_VOID_RETURN;
4704 }
4705 
4706 
4707 /*
4708   There are st_select_lex::add_table_to_list &
4709   st_select_lex::set_lock_for_tables are in sql_parse.cc
4710 
4711   st_select_lex::print is in sql_select.cc
4712 
4713   st_select_lex_unit::prepare, st_select_lex_unit::exec,
4714   st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
4715   st_select_lex_unit::change_result
4716   are in sql_union.cc
4717 */
4718 
4719 /*
4720   Sets the kind of hints to be added by the calls to add_index_hint().
4721 
4722   SYNOPSIS
4723     set_index_hint_type()
4724       type_arg     The kind of hints to be added from now on.
4725       clause       The clause to use for hints to be added from now on.
4726 
4727   DESCRIPTION
4728     Used in filling up the tagged hints list.
4729     This list is filled by first setting the kind of the hint as a
4730     context variable and then adding hints of the current kind.
4731     Then the context variable index_hint_type can be reset to the
4732     next hint type.
4733 */
set_index_hint_type(enum index_hint_type type_arg,index_clause_map clause)4734 void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
4735                                         index_clause_map clause)
4736 {
4737   current_index_hint_type= type_arg;
4738   current_index_hint_clause= clause;
4739 }
4740 
4741 
4742 /*
4743   Makes an array to store index usage hints (ADD/FORCE/IGNORE INDEX).
4744 
4745   SYNOPSIS
4746     alloc_index_hints()
4747       thd         current thread.
4748 */
4749 
alloc_index_hints(THD * thd)4750 void st_select_lex::alloc_index_hints (THD *thd)
4751 {
4752   index_hints= new (thd->mem_root) List<Index_hint>();
4753 }
4754 
4755 
4756 
4757 /*
4758   adds an element to the array storing index usage hints
4759   (ADD/FORCE/IGNORE INDEX).
4760 
4761   SYNOPSIS
4762     add_index_hint()
4763       thd         current thread.
4764       str         name of the index.
4765       length      number of characters in str.
4766 
4767   RETURN VALUE
4768     0 on success, non-zero otherwise
4769 */
add_index_hint(THD * thd,const char * str,size_t length)4770 bool st_select_lex::add_index_hint (THD *thd, const char *str, size_t length)
4771 {
4772   return index_hints->push_front(new (thd->mem_root)
4773                                  Index_hint(current_index_hint_type,
4774                                             current_index_hint_clause,
4775                                             str, length), thd->mem_root);
4776 }
4777 
4778 
4779 /**
4780   Optimize all subqueries that have not been flattened into semi-joins.
4781 
4782   @details
4783   This functionality is a method of SELECT_LEX instead of JOIN because
4784   SQL statements as DELETE/UPDATE do not have a corresponding JOIN object.
4785 
4786   @see JOIN::optimize_unflattened_subqueries
4787 
4788   @param const_only  Restrict subquery optimization to constant subqueries
4789 
4790   @return Operation status
4791   @retval FALSE     success.
4792   @retval TRUE      error occurred.
4793 */
4794 
optimize_unflattened_subqueries(bool const_only)4795 bool st_select_lex::optimize_unflattened_subqueries(bool const_only)
4796 {
4797   SELECT_LEX_UNIT *next_unit= NULL;
4798   for (SELECT_LEX_UNIT *un= first_inner_unit();
4799        un;
4800        un= next_unit ? next_unit : un->next_unit())
4801   {
4802     Item_subselect *subquery_predicate= un->item;
4803     next_unit= NULL;
4804 
4805     if (subquery_predicate)
4806     {
4807       if (!subquery_predicate->fixed)
4808       {
4809         /*
4810          This subquery was excluded as part of some expression so it is
4811          invisible from all prepared expression.
4812        */
4813         next_unit= un->next_unit();
4814         un->exclude_level();
4815         if (next_unit)
4816           continue;
4817         break;
4818       }
4819       if (subquery_predicate->substype() == Item_subselect::IN_SUBS)
4820       {
4821         Item_in_subselect *in_subs= subquery_predicate->get_IN_subquery();
4822         if (in_subs->is_jtbm_merged)
4823           continue;
4824       }
4825 
4826       if (const_only && !subquery_predicate->const_item())
4827       {
4828         /* Skip non-constant subqueries if the caller asked so. */
4829         continue;
4830       }
4831 
4832       bool empty_union_result= true;
4833       bool is_correlated_unit= false;
4834       bool first= true;
4835       bool union_plan_saved= false;
4836       /*
4837         If the subquery is a UNION, optimize all the subqueries in the UNION. If
4838         there is no UNION, then the loop will execute once for the subquery.
4839       */
4840       for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
4841       {
4842         JOIN *inner_join= sl->join;
4843         if (first)
4844           first= false;
4845         else
4846         {
4847           if (!union_plan_saved)
4848           {
4849             union_plan_saved= true;
4850             if (un->save_union_explain(un->thd->lex->explain))
4851               return true; /* Failure */
4852           }
4853         }
4854         if (!inner_join)
4855           continue;
4856         SELECT_LEX *save_select= un->thd->lex->current_select;
4857         ulonglong save_options;
4858         int res;
4859         /* We need only 1 row to determine existence */
4860         un->set_limit(un->global_parameters());
4861         un->thd->lex->current_select= sl;
4862         save_options= inner_join->select_options;
4863         if (options & SELECT_DESCRIBE)
4864         {
4865           /* Optimize the subquery in the context of EXPLAIN. */
4866           sl->set_explain_type(FALSE);
4867           sl->options|= SELECT_DESCRIBE;
4868           inner_join->select_options|= SELECT_DESCRIBE;
4869         }
4870         if ((res= inner_join->optimize()))
4871           return TRUE;
4872         if (!inner_join->cleaned)
4873           sl->update_used_tables();
4874         sl->update_correlated_cache();
4875         is_correlated_unit|= sl->is_correlated;
4876         inner_join->select_options= save_options;
4877         un->thd->lex->current_select= save_select;
4878 
4879         Explain_query *eq;
4880         if ((eq= inner_join->thd->lex->explain))
4881         {
4882           Explain_select *expl_sel;
4883           if ((expl_sel= eq->get_select(inner_join->select_lex->select_number)))
4884           {
4885             sl->set_explain_type(TRUE);
4886             expl_sel->select_type= sl->type;
4887           }
4888         }
4889 
4890         if (empty_union_result)
4891         {
4892           /*
4893             If at least one subquery in a union is non-empty, the UNION result
4894             is non-empty. If there is no UNION, the only subquery is non-empy.
4895           */
4896           empty_union_result= inner_join->empty_result();
4897         }
4898         if (res)
4899           return TRUE;
4900       }
4901       if (empty_union_result)
4902         subquery_predicate->no_rows_in_result();
4903 
4904       if (is_correlated_unit)
4905       {
4906         /*
4907           Some parts of UNION are not correlated. This means we will need to
4908           re-execute the whole UNION every time. Mark all parts of the UNION
4909           as correlated so that they are prepared to be executed multiple
4910           times (if we don't do that, some part of the UNION may free its
4911           execution data at the end of first execution and crash on the second
4912           execution)
4913         */
4914         for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
4915           sl->uncacheable |= UNCACHEABLE_DEPENDENT;
4916       }
4917       else
4918         un->uncacheable&= ~UNCACHEABLE_DEPENDENT;
4919       subquery_predicate->is_correlated= is_correlated_unit;
4920     }
4921   }
4922   return FALSE;
4923 }
4924 
4925 
4926 
4927 /**
4928   @brief Process all derived tables/views of the SELECT.
4929 
4930   @param lex    LEX of this thread
4931   @param phase  phases to run derived tables/views through
4932 
4933   @details
4934   This function runs specified 'phases' on all tables from the
4935   table_list of this select.
4936 
4937   @return FALSE ok.
4938   @return TRUE an error occur.
4939 */
4940 
handle_derived(LEX * lex,uint phases)4941 bool st_select_lex::handle_derived(LEX *lex, uint phases)
4942 {
4943   return lex->handle_list_of_derived(table_list.first, phases);
4944 }
4945 
4946 
4947 /**
4948   @brief
4949   Returns first unoccupied table map and table number
4950 
4951   @param map     [out] return found map
4952   @param tablenr [out] return found tablenr
4953 
4954   @details
4955   Returns first unoccupied table map and table number in this select.
4956   Map and table are returned in *'map' and *'tablenr' accordingly.
4957 
4958   @retrun TRUE  no free table map/table number
4959   @return FALSE found free table map/table number
4960 */
4961 
get_free_table_map(table_map * map,uint * tablenr)4962 bool st_select_lex::get_free_table_map(table_map *map, uint *tablenr)
4963 {
4964   *map= 0;
4965   *tablenr= 0;
4966   TABLE_LIST *tl;
4967   List_iterator<TABLE_LIST> ti(leaf_tables);
4968   while ((tl= ti++))
4969   {
4970     if (tl->table->map > *map)
4971       *map= tl->table->map;
4972     if (tl->table->tablenr > *tablenr)
4973       *tablenr= tl->table->tablenr;
4974   }
4975   (*map)<<= 1;
4976   (*tablenr)++;
4977   if (*tablenr >= MAX_TABLES)
4978     return TRUE;
4979   return FALSE;
4980 }
4981 
4982 
4983 /**
4984   @brief
4985   Append given table to the leaf_tables list.
4986 
4987   @param link  Offset to which list in table structure to use
4988   @param table Table to append
4989 
4990   @details
4991   Append given 'table' to the leaf_tables list using the 'link' offset.
4992   If the 'table' is linked with other tables through next_leaf/next_local
4993   chains then whole list will be appended.
4994 */
4995 
append_table_to_list(TABLE_LIST * TABLE_LIST::* link,TABLE_LIST * table)4996 void st_select_lex::append_table_to_list(TABLE_LIST *TABLE_LIST::*link,
4997                                          TABLE_LIST *table)
4998 {
4999   TABLE_LIST *tl;
5000   for (tl= leaf_tables.head(); tl->*link; tl= tl->*link) ;
5001   tl->*link= table;
5002 }
5003 
5004 
5005 /*
5006   @brief
5007   Replace given table from the leaf_tables list for a list of tables
5008 
5009   @param table Table to replace
5010   @param list  List to substititute the table for
5011 
5012   @details
5013   Replace 'table' from the leaf_tables list for a list of tables 'tbl_list'.
5014 */
5015 
replace_leaf_table(TABLE_LIST * table,List<TABLE_LIST> & tbl_list)5016 void st_select_lex::replace_leaf_table(TABLE_LIST *table, List<TABLE_LIST> &tbl_list)
5017 {
5018   TABLE_LIST *tl;
5019   List_iterator<TABLE_LIST> ti(leaf_tables);
5020   while ((tl= ti++))
5021   {
5022     if (tl == table)
5023     {
5024       ti.replace(tbl_list);
5025       break;
5026     }
5027   }
5028 }
5029 
5030 
5031 /**
5032   @brief
5033   Assigns new table maps to tables in the leaf_tables list
5034 
5035   @param derived    Derived table to take initial table map from
5036   @param map        table map to begin with
5037   @param tablenr    table number to begin with
5038   @param parent_lex new parent select_lex
5039 
5040   @details
5041   Assign new table maps/table numbers to all tables in the leaf_tables list.
5042   'map'/'tablenr' are used for the first table and shifted to left/
5043   increased for each consequent table in the leaf_tables list.
5044   If the 'derived' table is given then it's table map/number is used for the
5045   first table in the list and 'map'/'tablenr' are used for the second and
5046   all consequent tables.
5047   The 'parent_lex' is set as the new parent select_lex for all tables in the
5048   list.
5049 */
5050 
remap_tables(TABLE_LIST * derived,table_map map,uint tablenr,SELECT_LEX * parent_lex)5051 void st_select_lex::remap_tables(TABLE_LIST *derived, table_map map,
5052                                  uint tablenr, SELECT_LEX *parent_lex)
5053 {
5054   bool first_table= TRUE;
5055   TABLE_LIST *tl;
5056   table_map first_map;
5057   uint first_tablenr;
5058 
5059   if (derived && derived->table)
5060   {
5061     first_map= derived->table->map;
5062     first_tablenr= derived->table->tablenr;
5063   }
5064   else
5065   {
5066     first_map= map;
5067     map<<= 1;
5068     first_tablenr= tablenr++;
5069   }
5070   /*
5071     Assign table bit/table number.
5072     To the first table of the subselect the table bit/tablenr of the
5073     derived table is assigned. The rest of tables are getting bits
5074     sequentially, starting from the provided table map/tablenr.
5075   */
5076   List_iterator<TABLE_LIST> ti(leaf_tables);
5077   while ((tl= ti++))
5078   {
5079     if (first_table)
5080     {
5081       first_table= FALSE;
5082       tl->table->set_table_map(first_map, first_tablenr);
5083     }
5084     else
5085     {
5086       tl->table->set_table_map(map, tablenr);
5087       tablenr++;
5088       map<<= 1;
5089     }
5090     SELECT_LEX *old_sl= tl->select_lex;
5091     tl->select_lex= parent_lex;
5092     for(TABLE_LIST *emb= tl->embedding;
5093         emb && emb->select_lex == old_sl;
5094         emb= emb->embedding)
5095       emb->select_lex= parent_lex;
5096   }
5097 }
5098 
5099 /**
5100   @brief
5101   Merge a subquery into this select.
5102 
5103   @param derived     derived table of the subquery to be merged
5104   @param subq_select select_lex of the subquery
5105   @param map         table map for assigning to merged tables from subquery
5106   @param table_no    table number for assigning to merged tables from subquery
5107 
5108   @details
5109   This function merges a subquery into its parent select. In short the
5110   merge operation appends the subquery FROM table list to the parent's
5111   FROM table list. In more details:
5112     .) the top_join_list of the subquery is wrapped into a join_nest
5113        and attached to 'derived'
5114     .) subquery's leaf_tables list  is merged with the leaf_tables
5115        list of this select_lex
5116     .) the table maps and table numbers of the tables merged from
5117        the subquery are adjusted to reflect their new binding to
5118        this select
5119 
5120   @return TRUE  an error occur
5121   @return FALSE ok
5122 */
5123 
merge_subquery(THD * thd,TABLE_LIST * derived,SELECT_LEX * subq_select,uint table_no,table_map map)5124 bool SELECT_LEX::merge_subquery(THD *thd, TABLE_LIST *derived,
5125                                 SELECT_LEX *subq_select,
5126                                 uint table_no, table_map map)
5127 {
5128   derived->wrap_into_nested_join(subq_select->top_join_list);
5129 
5130   ftfunc_list->append(subq_select->ftfunc_list);
5131   if (join ||
5132       thd->lex->sql_command == SQLCOM_UPDATE_MULTI ||
5133       thd->lex->sql_command == SQLCOM_DELETE_MULTI)
5134   {
5135     List_iterator_fast<Item_in_subselect> li(subq_select->sj_subselects);
5136     Item_in_subselect *in_subq;
5137     while ((in_subq= li++))
5138     {
5139       sj_subselects.push_back(in_subq, thd->mem_root);
5140       if (in_subq->emb_on_expr_nest == NO_JOIN_NEST)
5141          in_subq->emb_on_expr_nest= derived;
5142     }
5143 
5144     uint cnt= sizeof(expr_cache_may_be_used)/sizeof(bool);
5145     for (uint i= 0; i < cnt; i++)
5146     {
5147       if (subq_select->expr_cache_may_be_used[i])
5148         expr_cache_may_be_used[i]= true;
5149     }
5150 
5151     List_iterator_fast<Item_func_in> it(subq_select->in_funcs);
5152     Item_func_in *in_func;
5153     while ((in_func= it++))
5154     {
5155       in_funcs.push_back(in_func, thd->mem_root);
5156       if (in_func->emb_on_expr_nest == NO_JOIN_NEST)
5157         in_func->emb_on_expr_nest= derived;
5158     }
5159   }
5160 
5161   /* Walk through child's tables and adjust table map, tablenr,
5162    * parent_lex */
5163   subq_select->remap_tables(derived, map, table_no, this);
5164   subq_select->merged_into= this;
5165 
5166   replace_leaf_table(derived, subq_select->leaf_tables);
5167 
5168   return FALSE;
5169 }
5170 
5171 
5172 /**
5173   @brief
5174   Mark tables from the leaf_tables list as belong to a derived table.
5175 
5176   @param derived   tables will be marked as belonging to this derived
5177 
5178   @details
5179   Run through the leaf_list and mark all tables as belonging to the 'derived'.
5180 */
5181 
mark_as_belong_to_derived(TABLE_LIST * derived)5182 void SELECT_LEX::mark_as_belong_to_derived(TABLE_LIST *derived)
5183 {
5184   /* Mark tables as belonging to this DT */
5185   TABLE_LIST *tl;
5186   List_iterator<TABLE_LIST> ti(leaf_tables);
5187   while ((tl= ti++))
5188     tl->belong_to_derived= derived;
5189 }
5190 
5191 
5192 /**
5193   @brief
5194   Update used_tables cache for this select
5195 
5196   @details
5197   This function updates used_tables cache of ON expressions of all tables
5198   in the leaf_tables list and of the conds expression (if any).
5199 */
5200 
update_used_tables()5201 void SELECT_LEX::update_used_tables()
5202 {
5203   TABLE_LIST *tl;
5204   List_iterator<TABLE_LIST> ti(leaf_tables);
5205 
5206   while ((tl= ti++))
5207   {
5208     if (tl->table && !tl->is_view_or_derived())
5209     {
5210       TABLE_LIST *embedding= tl->embedding;
5211       for (embedding= tl->embedding; embedding; embedding=embedding->embedding)
5212       {
5213         if (embedding->is_view_or_derived())
5214         {
5215           DBUG_ASSERT(embedding->is_merged_derived());
5216           TABLE *tab= tl->table;
5217           tab->covering_keys= tab->s->keys_for_keyread;
5218           tab->covering_keys.intersect(tab->keys_in_use_for_query);
5219           /*
5220             View/derived was merged. Need to recalculate read_set
5221             bitmaps here. For example:
5222               CREATE VIEW v1 AS SELECT f1,f2,f3 FROM t1;
5223               SELECT f1 FROM v1;
5224             Initially, the view definition will put all f1,f2,f3 in the
5225             read_set for t1. But after the view is merged, only f1 should
5226             be in the read_set.
5227           */
5228           bitmap_clear_all(tab->read_set);
5229           break;
5230         }
5231       }
5232     }
5233   }
5234 
5235   ti.rewind();
5236   while ((tl= ti++))
5237   {
5238     TABLE_LIST *embedding= tl;
5239     do
5240     {
5241       bool maybe_null;
5242       if ((maybe_null= MY_TEST(embedding->outer_join)))
5243       {
5244         tl->table->maybe_null= maybe_null;
5245         break;
5246       }
5247     }
5248     while ((embedding= embedding->embedding));
5249     if (tl->on_expr)
5250     {
5251       tl->on_expr->update_used_tables();
5252       tl->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
5253     }
5254     /*
5255       - There is no need to check sj_on_expr, because merged semi-joins inject
5256         sj_on_expr into the parent's WHERE clase.
5257       - For non-merged semi-joins (aka JTBMs), we need to check their
5258         left_expr. There is no need to check the rest of the subselect, we know
5259         it is uncorrelated and so cannot refer to any tables in this select.
5260     */
5261     if (tl->jtbm_subselect)
5262     {
5263       Item *left_expr= tl->jtbm_subselect->left_exp();
5264       left_expr->walk(&Item::update_table_bitmaps_processor, FALSE, NULL);
5265     }
5266 
5267     embedding= tl->embedding;
5268     while (embedding)
5269     {
5270       if (embedding->on_expr &&
5271           embedding->nested_join->join_list.head() == tl)
5272       {
5273         embedding->on_expr->update_used_tables();
5274         embedding->on_expr->walk(&Item::eval_not_null_tables, 0, NULL);
5275       }
5276       tl= embedding;
5277       embedding= tl->embedding;
5278     }
5279   }
5280 
5281   if (join->conds)
5282   {
5283     join->conds->update_used_tables();
5284     join->conds->walk(&Item::eval_not_null_tables, 0, NULL);
5285   }
5286   if (join->having)
5287   {
5288     join->having->update_used_tables();
5289   }
5290 
5291   Item *item;
5292   List_iterator_fast<Item> it(join->all_fields);
5293   select_list_tables= 0;
5294   while ((item= it++))
5295   {
5296     item->update_used_tables();
5297     select_list_tables|= item->used_tables();
5298   }
5299   Item_outer_ref *ref;
5300   List_iterator_fast<Item_outer_ref> ref_it(inner_refs_list);
5301   while ((ref= ref_it++))
5302   {
5303     item= ref->outer_ref;
5304     item->update_used_tables();
5305   }
5306   for (ORDER *order= group_list.first; order; order= order->next)
5307     (*order->item)->update_used_tables();
5308   if (!master_unit()->is_unit_op() ||
5309       master_unit()->global_parameters() != this)
5310   {
5311     for (ORDER *order= order_list.first; order; order= order->next)
5312       (*order->item)->update_used_tables();
5313   }
5314   join->result->update_used_tables();
5315 }
5316 
5317 
5318 /**
5319   @brief
5320   Update is_correlated cache for this select
5321 
5322   @details
5323 */
5324 
update_correlated_cache()5325 void st_select_lex::update_correlated_cache()
5326 {
5327   TABLE_LIST *tl;
5328   List_iterator<TABLE_LIST> ti(leaf_tables);
5329 
5330   is_correlated= false;
5331 
5332   while ((tl= ti++))
5333   {
5334     //    is_correlated|= tl->is_with_table_recursive_reference();
5335     if (tl->on_expr)
5336       is_correlated|= MY_TEST(tl->on_expr->used_tables() & OUTER_REF_TABLE_BIT);
5337     for (TABLE_LIST *embedding= tl->embedding ; embedding ;
5338          embedding= embedding->embedding)
5339     {
5340       if (embedding->on_expr)
5341         is_correlated|= MY_TEST(embedding->on_expr->used_tables() &
5342                                 OUTER_REF_TABLE_BIT);
5343     }
5344   }
5345 
5346   if (join->conds)
5347     is_correlated|= MY_TEST(join->conds->used_tables() & OUTER_REF_TABLE_BIT);
5348 
5349   is_correlated|= join->having_is_correlated;
5350 
5351   if (join->having)
5352     is_correlated|= MY_TEST(join->having->used_tables() & OUTER_REF_TABLE_BIT);
5353 
5354   if (join->tmp_having)
5355     is_correlated|= MY_TEST(join->tmp_having->used_tables() &
5356                             OUTER_REF_TABLE_BIT);
5357 
5358   Item *item;
5359   List_iterator_fast<Item> it(join->fields_list);
5360   while ((item= it++))
5361     is_correlated|= MY_TEST(item->used_tables() & OUTER_REF_TABLE_BIT);
5362 
5363   for (ORDER *order= group_list.first; order; order= order->next)
5364     is_correlated|= MY_TEST((*order->item)->used_tables() &
5365                             OUTER_REF_TABLE_BIT);
5366 
5367   if (!master_unit()->is_unit_op())
5368   {
5369     for (ORDER *order= order_list.first; order; order= order->next)
5370       is_correlated|= MY_TEST((*order->item)->used_tables() &
5371                               OUTER_REF_TABLE_BIT);
5372   }
5373 
5374   if (!is_correlated)
5375     uncacheable&= ~UNCACHEABLE_DEPENDENT;
5376 }
5377 
5378 
5379 /**
5380   Set the EXPLAIN type for this subquery.
5381 
5382   @param on_the_fly  TRUE<=> We're running a SHOW EXPLAIN command, so we must
5383                      not change any variables
5384 */
5385 
set_explain_type(bool on_the_fly)5386 void st_select_lex::set_explain_type(bool on_the_fly)
5387 {
5388   bool is_primary= FALSE;
5389   if (next_select())
5390     is_primary= TRUE;
5391 
5392   if (!is_primary && first_inner_unit())
5393   {
5394     /*
5395       If there is at least one materialized derived|view then it's a PRIMARY select.
5396       Otherwise, all derived tables/views were merged and this select is a SIMPLE one.
5397     */
5398     for (SELECT_LEX_UNIT *un= first_inner_unit(); un; un= un->next_unit())
5399     {
5400       if ((!un->derived || un->derived->is_materialized_derived()))
5401       {
5402         is_primary= TRUE;
5403         break;
5404       }
5405     }
5406   }
5407 
5408   if (on_the_fly && !is_primary && have_merged_subqueries)
5409     is_primary= TRUE;
5410 
5411   SELECT_LEX *first= master_unit()->first_select();
5412   /* drop UNCACHEABLE_EXPLAIN, because it is for internal usage only */
5413   uint8 is_uncacheable= (uncacheable & ~UNCACHEABLE_EXPLAIN);
5414 
5415   bool using_materialization= FALSE;
5416   Item_subselect *parent_item;
5417   if ((parent_item= master_unit()->item) &&
5418       parent_item->substype() == Item_subselect::IN_SUBS)
5419   {
5420     Item_in_subselect *in_subs= parent_item->get_IN_subquery();
5421     /*
5422       Surprisingly, in_subs->is_set_strategy() can return FALSE here,
5423       even for the last invocation of this function for the select.
5424     */
5425     if (in_subs->test_strategy(SUBS_MATERIALIZATION))
5426       using_materialization= TRUE;
5427   }
5428 
5429   if (master_unit()->thd->lex->first_select_lex() == this)
5430   {
5431     if (pushdown_select)
5432       type= pushed_select_text;
5433     else
5434       type= is_primary ? "PRIMARY" : "SIMPLE";
5435   }
5436   else
5437   {
5438     if (this == first)
5439     {
5440       /* If we're a direct child of a UNION, we're the first sibling there */
5441       if (linkage == DERIVED_TABLE_TYPE)
5442       {
5443         bool is_pushed_master_unit= master_unit()->derived &&
5444 	                            master_unit()->derived->pushdown_derived;
5445         if (is_pushed_master_unit)
5446           type= pushed_derived_text;
5447         else if (is_uncacheable & UNCACHEABLE_DEPENDENT)
5448           type= "LATERAL DERIVED";
5449         else
5450           type= "DERIVED";
5451       }
5452       else if (using_materialization)
5453         type= "MATERIALIZED";
5454       else
5455       {
5456          if (is_uncacheable & UNCACHEABLE_DEPENDENT)
5457            type= "DEPENDENT SUBQUERY";
5458          else
5459          {
5460            type= is_uncacheable? "UNCACHEABLE SUBQUERY" :
5461                                  "SUBQUERY";
5462          }
5463       }
5464     }
5465     else
5466     {
5467       switch (linkage)
5468       {
5469       case INTERSECT_TYPE:
5470         type= "INTERSECT";
5471         break;
5472       case EXCEPT_TYPE:
5473         type= "EXCEPT";
5474         break;
5475       default:
5476         /* This a non-first sibling in UNION */
5477         if (is_uncacheable & UNCACHEABLE_DEPENDENT)
5478           type= "DEPENDENT UNION";
5479         else if (using_materialization)
5480           type= "MATERIALIZED UNION";
5481         else
5482         {
5483           type= is_uncacheable ? "UNCACHEABLE UNION": "UNION";
5484           if (this == master_unit()->fake_select_lex)
5485             type= unit_operation_text[master_unit()->common_op()];
5486           /*
5487             join below may be =NULL when this functions is called at an early
5488             stage. It will be later called again and we will set the correct
5489             value.
5490           */
5491           if (join)
5492           {
5493             bool uses_cte= false;
5494             for (JOIN_TAB *tab= first_linear_tab(join, WITHOUT_BUSH_ROOTS,
5495                                                        WITH_CONST_TABLES);
5496                  tab;
5497                  tab= next_linear_tab(join, tab, WITHOUT_BUSH_ROOTS))
5498             {
5499               /*
5500                 pos_in_table_list=NULL for e.g. post-join aggregation JOIN_TABs.
5501               */
5502               if (!(tab->table && tab->table->pos_in_table_list))
5503 	        continue;
5504               TABLE_LIST *tbl= tab->table->pos_in_table_list;
5505               if (tbl->with && tbl->with->is_recursive &&
5506                   tbl->is_with_table_recursive_reference())
5507               {
5508                 uses_cte= true;
5509                 break;
5510               }
5511             }
5512             if (uses_cte)
5513               type= "RECURSIVE UNION";
5514           }
5515         }
5516         break;
5517       }
5518     }
5519   }
5520 
5521   if (!on_the_fly)
5522     options|= SELECT_DESCRIBE;
5523 }
5524 
5525 
5526 /**
5527   @brief
5528   Increase estimated number of records for a derived table/view
5529 
5530   @param records  number of records to increase estimate by
5531 
5532   @details
5533   This function increases estimated number of records by the 'records'
5534   for the derived table to which this select belongs to.
5535 */
5536 
increase_derived_records(ha_rows records)5537 void SELECT_LEX::increase_derived_records(ha_rows records)
5538 {
5539   SELECT_LEX_UNIT *unit= master_unit();
5540   DBUG_ASSERT(unit->derived);
5541 
5542   if (unit->with_element && unit->with_element->is_recursive)
5543   {
5544     st_select_lex *first_recursive= unit->with_element->first_recursive;
5545     st_select_lex *sl= unit->first_select();
5546     for ( ; sl != first_recursive; sl= sl->next_select())
5547     {
5548       if (sl == this)
5549         break;
5550     }
5551     if (sl == first_recursive)
5552       return;
5553   }
5554 
5555   select_result *result= unit->result;
5556   switch (linkage)
5557   {
5558   case INTERSECT_TYPE:
5559     // result of intersect can't be more then one of components
5560     set_if_smaller(result->est_records, records);
5561   case EXCEPT_TYPE:
5562     // in worse case none of record will be removed
5563     break;
5564   default:
5565     // usual UNION
5566     if (HA_ROWS_MAX - records > result->est_records)
5567       result->est_records+= records;
5568     else
5569       result->est_records= HA_ROWS_MAX;
5570     break;
5571   }
5572 }
5573 
5574 
5575 /**
5576   @brief
5577   Mark select's derived table as a const one.
5578 
5579   @param empty Whether select has an empty result set
5580 
5581   @details
5582   Mark derived table/view of this select as a constant one (to
5583   materialize it at the optimization phase) unless this select belongs to a
5584   union. Estimated number of rows is incremented if this select has non empty
5585   result set.
5586 */
5587 
mark_const_derived(bool empty)5588 void SELECT_LEX::mark_const_derived(bool empty)
5589 {
5590   TABLE_LIST *derived= master_unit()->derived;
5591   /* join == NULL in  DELETE ... RETURNING */
5592   if (!(join && join->thd->lex->describe) && derived)
5593   {
5594     if (!empty)
5595       increase_derived_records(1);
5596     if (!master_unit()->is_unit_op() && !derived->is_merged_derived() &&
5597         !(join && join->with_two_phase_optimization))
5598       derived->fill_me= TRUE;
5599   }
5600 }
5601 
5602 
save_leaf_tables(THD * thd)5603 bool st_select_lex::save_leaf_tables(THD *thd)
5604 {
5605   Query_arena *arena, backup;
5606   arena= thd->activate_stmt_arena_if_needed(&backup);
5607 
5608   List_iterator_fast<TABLE_LIST> li(leaf_tables);
5609   TABLE_LIST *table;
5610   while ((table= li++))
5611   {
5612     if (leaf_tables_exec.push_back(table, thd->mem_root))
5613       return 1;
5614     table->tablenr_exec= table->get_tablenr();
5615     table->map_exec= table->get_map();
5616     if (join && (join->select_options & SELECT_DESCRIBE))
5617       table->maybe_null_exec= 0;
5618     else
5619       table->maybe_null_exec= table->table?  table->table->maybe_null: 0;
5620   }
5621   if (arena)
5622     thd->restore_active_arena(arena, &backup);
5623 
5624   return 0;
5625 }
5626 
5627 
save_prep_leaf_tables()5628 bool LEX::save_prep_leaf_tables()
5629 {
5630   if (!thd->save_prep_leaf_list)
5631     return FALSE;
5632 
5633   Query_arena *arena= thd->stmt_arena, backup;
5634   arena= thd->activate_stmt_arena_if_needed(&backup);
5635   //It is used for DETETE/UPDATE so top level has only one SELECT
5636   DBUG_ASSERT(first_select_lex()->next_select() == NULL);
5637   bool res= first_select_lex()->save_prep_leaf_tables(thd);
5638 
5639   if (arena)
5640     thd->restore_active_arena(arena, &backup);
5641 
5642   if (res)
5643     return TRUE;
5644 
5645   thd->save_prep_leaf_list= FALSE;
5646   return FALSE;
5647 }
5648 
5649 
save_prep_leaf_tables(THD * thd)5650 bool st_select_lex::save_prep_leaf_tables(THD *thd)
5651 {
5652   if (prep_leaf_list_state == SAVED)
5653     return FALSE;
5654 
5655   List_iterator_fast<TABLE_LIST> li(leaf_tables);
5656   TABLE_LIST *table;
5657 
5658   /*
5659     Check that the SELECT_LEX was really prepared and so tables are setup.
5660 
5661     It can be subquery in SET clause of UPDATE which was not prepared yet, so
5662     its tables are not yet setup and ready for storing.
5663   */
5664   if (prep_leaf_list_state != READY)
5665     return FALSE;
5666 
5667   while ((table= li++))
5668   {
5669     if (leaf_tables_prep.push_back(table))
5670       return TRUE;
5671   }
5672   prep_leaf_list_state= SAVED;
5673   for (SELECT_LEX_UNIT *u= first_inner_unit(); u; u= u->next_unit())
5674   {
5675     for (SELECT_LEX *sl= u->first_select(); sl; sl= sl->next_select())
5676     {
5677       if (sl->save_prep_leaf_tables(thd))
5678         return TRUE;
5679     }
5680   }
5681 
5682   return FALSE;
5683 }
5684 
5685 
5686 /**
5687   Set exclude_from_table_unique_test for selects of this select and all selects
5688   belonging to the underlying units of derived tables or views
5689 */
5690 
set_unique_exclude()5691 void st_select_lex::set_unique_exclude()
5692 {
5693   exclude_from_table_unique_test= TRUE;
5694   for (SELECT_LEX_UNIT *unit= first_inner_unit();
5695        unit;
5696        unit= unit->next_unit())
5697   {
5698     if (unit->derived && unit->derived->is_view_or_derived())
5699     {
5700       for (SELECT_LEX *sl= unit->first_select(); sl; sl= sl->next_select())
5701         sl->set_unique_exclude();
5702     }
5703   }
5704 }
5705 
5706 
5707 /*
5708   Return true if this select_lex has been converted into a semi-join nest
5709   within 'ancestor'.
5710 
5711   We need a loop to check this because there could be several nested
5712   subselects, like
5713 
5714     SELECT ... FROM grand_parent
5715       WHERE expr1 IN (SELECT ... FROM parent
5716                         WHERE expr2 IN ( SELECT ... FROM child)
5717 
5718   which were converted into:
5719 
5720     SELECT ...
5721     FROM grand_parent SEMI_JOIN (parent JOIN child)
5722     WHERE
5723       expr1 AND expr2
5724 
5725   In this case, both parent and child selects were merged into the parent.
5726 */
5727 
is_merged_child_of(st_select_lex * ancestor)5728 bool st_select_lex::is_merged_child_of(st_select_lex *ancestor)
5729 {
5730   bool all_merged= TRUE;
5731   for (SELECT_LEX *sl= this; sl && sl!=ancestor;
5732        sl=sl->outer_select())
5733   {
5734     Item *subs= sl->master_unit()->item;
5735     Item_in_subselect *in_subs= (subs ? subs->get_IN_subquery() : NULL);
5736     if (in_subs &&
5737         ((Item_subselect*)subs)->substype() == Item_subselect::IN_SUBS &&
5738         in_subs->test_strategy(SUBS_SEMI_JOIN))
5739     {
5740       continue;
5741     }
5742 
5743     if (sl->master_unit()->derived &&
5744       sl->master_unit()->derived->is_merged_derived())
5745     {
5746       continue;
5747     }
5748     all_merged= FALSE;
5749     break;
5750   }
5751   return all_merged;
5752 }
5753 
5754 /*
5755   This is used by SHOW EXPLAIN. It assuses query plan has been already
5756   collected into QPF structures and we only need to print it out.
5757 */
5758 
print_explain(select_result_sink * output,uint8 explain_flags,bool is_analyze,bool * printed_anything)5759 int LEX::print_explain(select_result_sink *output, uint8 explain_flags,
5760                        bool is_analyze, bool *printed_anything)
5761 {
5762   int res;
5763   if (explain && explain->have_query_plan())
5764   {
5765     res= explain->print_explain(output, explain_flags, is_analyze);
5766     *printed_anything= true;
5767   }
5768   else
5769   {
5770     res= 0;
5771     *printed_anything= false;
5772   }
5773   return res;
5774 }
5775 
5776 
5777 /**
5778   Allocates and set arena for SET STATEMENT old values.
5779 
5780   @param backup          where to save backup of arena.
5781 
5782   @retval 1 Error
5783   @retval 0 OK
5784 */
5785 
set_arena_for_set_stmt(Query_arena * backup)5786 bool LEX::set_arena_for_set_stmt(Query_arena *backup)
5787 {
5788   DBUG_ENTER("LEX::set_arena_for_set_stmt");
5789   DBUG_ASSERT(arena_for_set_stmt== 0);
5790   if (!mem_root_for_set_stmt)
5791   {
5792     mem_root_for_set_stmt= new MEM_ROOT();
5793     if (unlikely(!(mem_root_for_set_stmt)))
5794       DBUG_RETURN(1);
5795     init_sql_alloc(PSI_INSTRUMENT_ME, mem_root_for_set_stmt, ALLOC_ROOT_SET,
5796                    ALLOC_ROOT_SET, MYF(MY_THREAD_SPECIFIC));
5797   }
5798   if (unlikely(!(arena_for_set_stmt= new(mem_root_for_set_stmt)
5799                  Query_arena_memroot(mem_root_for_set_stmt,
5800                                      Query_arena::STMT_INITIALIZED))))
5801     DBUG_RETURN(1);
5802   DBUG_PRINT("info", ("mem_root: %p  arena: %p",
5803                       mem_root_for_set_stmt,
5804                       arena_for_set_stmt));
5805   thd->set_n_backup_active_arena(arena_for_set_stmt, backup);
5806   DBUG_RETURN(0);
5807 }
5808 
5809 
reset_arena_for_set_stmt(Query_arena * backup)5810 void LEX::reset_arena_for_set_stmt(Query_arena *backup)
5811 {
5812   DBUG_ENTER("LEX::reset_arena_for_set_stmt");
5813   DBUG_ASSERT(arena_for_set_stmt);
5814   thd->restore_active_arena(arena_for_set_stmt, backup);
5815   DBUG_PRINT("info", ("mem_root: %p  arena: %p",
5816                       arena_for_set_stmt->mem_root,
5817                       arena_for_set_stmt));
5818   DBUG_VOID_RETURN;
5819 }
5820 
5821 
free_arena_for_set_stmt()5822 void LEX::free_arena_for_set_stmt()
5823 {
5824   DBUG_ENTER("LEX::free_arena_for_set_stmt");
5825   if (!arena_for_set_stmt)
5826     return;
5827   DBUG_PRINT("info", ("mem_root: %p  arena: %p",
5828                       arena_for_set_stmt->mem_root,
5829                       arena_for_set_stmt));
5830   arena_for_set_stmt->free_items();
5831   delete(arena_for_set_stmt);
5832   free_root(mem_root_for_set_stmt, MYF(MY_KEEP_PREALLOC));
5833   arena_for_set_stmt= 0;
5834   DBUG_VOID_RETURN;
5835 }
5836 
restore_set_statement_var()5837 bool LEX::restore_set_statement_var()
5838 {
5839   bool err= false;
5840   DBUG_ENTER("LEX::restore_set_statement_var");
5841   if (!old_var_list.is_empty())
5842   {
5843     DBUG_PRINT("info", ("vars: %d", old_var_list.elements));
5844     err= sql_set_variables(thd, &old_var_list, false);
5845     old_var_list.empty();
5846     free_arena_for_set_stmt();
5847   }
5848   DBUG_ASSERT(!is_arena_for_set_stmt());
5849   DBUG_RETURN(err);
5850 }
5851 
common_op()5852 unit_common_op st_select_lex_unit::common_op()
5853 {
5854   SELECT_LEX *first= first_select();
5855   bool first_op= TRUE;
5856   unit_common_op operation= OP_MIX; // if no op
5857   for (SELECT_LEX *sl= first; sl; sl= sl->next_select())
5858   {
5859     if (sl != first)
5860     {
5861       unit_common_op op;
5862       switch (sl->linkage)
5863       {
5864       case INTERSECT_TYPE:
5865         op= OP_INTERSECT;
5866         break;
5867       case EXCEPT_TYPE:
5868         op= OP_EXCEPT;
5869         break;
5870       default:
5871         op= OP_UNION;
5872         break;
5873       }
5874       if (first_op)
5875       {
5876         operation= op;
5877         first_op= FALSE;
5878       }
5879       else
5880       {
5881         if (operation != op)
5882           operation= OP_MIX;
5883       }
5884     }
5885   }
5886   return operation;
5887 }
5888 /*
5889   Save explain structures of a UNION. The only variable member is whether the
5890   union has "Using filesort".
5891 
5892   There is also save_union_explain_part2() function, which is called before we read
5893   UNION's output.
5894 
5895   The reason for it is examples like this:
5896 
5897      SELECT col1 FROM t1 UNION SELECT col2 FROM t2 ORDER BY (select ... from t3 ...)
5898 
5899   Here, the (select ... from t3 ...) subquery must be a child of UNION's
5900   st_select_lex. However, it is not connected as child until a very late
5901   stage in execution.
5902 */
5903 
save_union_explain(Explain_query * output)5904 int st_select_lex_unit::save_union_explain(Explain_query *output)
5905 {
5906   SELECT_LEX *first= first_select();
5907 
5908   if (output->get_union(first->select_number))
5909     return 0; /* Already added */
5910 
5911   Explain_union *eu=
5912     new (output->mem_root) Explain_union(output->mem_root,
5913                                          thd->lex->analyze_stmt);
5914   if (unlikely(!eu))
5915     return 0;
5916 
5917   if (with_element && with_element->is_recursive)
5918     eu->is_recursive_cte= true;
5919 
5920   if (derived)
5921     eu->connection_type= Explain_node::EXPLAIN_NODE_DERIVED;
5922   /*
5923     Note: Non-merged semi-joins cannot be made out of UNIONs currently, so we
5924     don't ever set EXPLAIN_NODE_NON_MERGED_SJ.
5925   */
5926   for (SELECT_LEX *sl= first; sl; sl= sl->next_select())
5927     eu->add_select(sl->select_number);
5928 
5929   eu->fake_select_type= unit_operation_text[eu->operation= common_op()];
5930   eu->using_filesort= MY_TEST(global_parameters()->order_list.first);
5931   eu->using_tmp= union_needs_tmp_table();
5932 
5933   // Save the UNION node
5934   output->add_node(eu);
5935 
5936   if (eu->get_select_id() == 1)
5937     output->query_plan_ready();
5938 
5939   return 0;
5940 }
5941 
5942 
5943 /*
5944   @see  st_select_lex_unit::save_union_explain
5945 */
5946 
save_union_explain_part2(Explain_query * output)5947 int st_select_lex_unit::save_union_explain_part2(Explain_query *output)
5948 {
5949   Explain_union *eu= output->get_union(first_select()->select_number);
5950   if (fake_select_lex)
5951   {
5952     for (SELECT_LEX_UNIT *unit= fake_select_lex->first_inner_unit();
5953          unit; unit= unit->next_unit())
5954     {
5955       if (unit->explainable())
5956         eu->add_child(unit->first_select()->select_number);
5957     }
5958     fake_select_lex->join->explain= &eu->fake_select_lex_explain;
5959   }
5960   return 0;
5961 }
5962 
5963 
5964 /**
5965   A routine used by the parser to decide whether we are specifying a full
5966   partitioning or if only partitions to add or to split.
5967 
5968   @note  This needs to be outside of WITH_PARTITION_STORAGE_ENGINE since it
5969   is used from the sql parser that doesn't have any ifdef's
5970 
5971   @retval  TRUE    Yes, it is part of a management partition command
5972   @retval  FALSE          No, not a management partition command
5973 */
5974 
is_partition_management() const5975 bool LEX::is_partition_management() const
5976 {
5977   return (sql_command == SQLCOM_ALTER_TABLE &&
5978           (alter_info.partition_flags ==  ALTER_PARTITION_ADD ||
5979            alter_info.partition_flags ==  ALTER_PARTITION_REORGANIZE));
5980 }
5981 
5982 
5983 /**
5984   Exclude last added SELECT_LEX (current) in the UNIT and return pointer in it
5985   (previous become currect)
5986 
5987   @return detached SELECT_LEX or NULL in case of error
5988 */
5989 
exclude_last_select()5990 SELECT_LEX *LEX::exclude_last_select()
5991 {
5992   return exclude_not_first_select(current_select);
5993 }
5994 
exclude_not_first_select(SELECT_LEX * exclude)5995 SELECT_LEX *LEX::exclude_not_first_select(SELECT_LEX *exclude)
5996 {
5997   DBUG_ENTER("LEX::exclude_not_first_select");
5998   DBUG_PRINT("enter", ("exclude %p #%u", exclude, exclude->select_number));
5999   SELECT_LEX_UNIT *unit= exclude->master_unit();
6000   SELECT_LEX *sl;
6001   DBUG_ASSERT(unit->first_select() != exclude);
6002   /* we should go through the list to correctly set current_select */
6003   for(sl= unit->first_select();
6004       sl->next_select() && sl->next_select() != exclude;
6005       sl= sl->next_select());
6006   DBUG_PRINT("info", ("excl: %p  unit: %p  prev: %p", exclude, unit, sl));
6007   if (!sl)
6008     DBUG_RETURN(NULL);
6009   DBUG_ASSERT(&sl->next == exclude->prev);
6010 
6011   exclude->prev= NULL;
6012 
6013   current_select= sl;
6014   DBUG_RETURN(exclude);
6015 }
6016 
6017 
alloc_unit()6018 SELECT_LEX_UNIT *LEX::alloc_unit()
6019 {
6020   SELECT_LEX_UNIT *unit;
6021   DBUG_ENTER("LEX::alloc_unit");
6022   if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
6023     DBUG_RETURN(NULL);
6024 
6025   unit->init_query();
6026   /* TODO: reentrant problem */
6027   unit->thd= thd;
6028   unit->link_next= 0;
6029   unit->link_prev= 0;
6030   /* TODO: remove return_to */
6031   unit->return_to= NULL;
6032   DBUG_RETURN(unit);
6033 }
6034 
6035 
alloc_select(bool select)6036 SELECT_LEX *LEX::alloc_select(bool select)
6037 {
6038   SELECT_LEX *select_lex;
6039   DBUG_ENTER("LEX::alloc_select");
6040   if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
6041     DBUG_RETURN(NULL);
6042   DBUG_PRINT("info", ("Allocate select: %p #%u  statement lex: %p",
6043                       select_lex, thd->lex->stmt_lex->current_select_number,
6044                       thd->lex->stmt_lex));
6045   /*
6046     TODO: move following init to constructor when we get rid of builtin
6047     select
6048   */
6049   select_lex->select_number= ++thd->lex->stmt_lex->current_select_number;
6050   select_lex->parent_lex= this; /* Used in init_query. */
6051   select_lex->init_query();
6052   if (select)
6053     select_lex->init_select();
6054   select_lex->nest_level_base= &this->unit;
6055   select_lex->include_global((st_select_lex_node**)&all_selects_list);
6056   select_lex->context.resolve_in_select_list= TRUE;
6057   DBUG_RETURN(select_lex);
6058 }
6059 
6060 SELECT_LEX_UNIT *
create_unit(SELECT_LEX * first_sel)6061 LEX::create_unit(SELECT_LEX *first_sel)
6062 {
6063   SELECT_LEX_UNIT *unit;
6064   DBUG_ENTER("LEX::create_unit");
6065 
6066   unit = first_sel->master_unit();
6067 
6068   if (!unit && !(unit= alloc_unit()))
6069     DBUG_RETURN(NULL);
6070 
6071   unit->register_select_chain(first_sel);
6072   if (first_sel->next_select())
6073   {
6074     unit->reset_distinct();
6075     DBUG_ASSERT(!unit->fake_select_lex);
6076     if (unit->add_fake_select_lex(thd))
6077       DBUG_RETURN(NULL);
6078   }
6079   DBUG_RETURN(unit);
6080 }
6081 
6082 SELECT_LEX_UNIT *
attach_selects_chain(SELECT_LEX * first_sel,Name_resolution_context * context)6083 SELECT_LEX::attach_selects_chain(SELECT_LEX *first_sel,
6084                                  Name_resolution_context *context)
6085 {
6086   SELECT_LEX_UNIT *unit;
6087   DBUG_ENTER("SELECT_LEX::attach_select_chain");
6088 
6089   if (!(unit= parent_lex->alloc_unit()))
6090     DBUG_RETURN(NULL);
6091 
6092   unit->register_select_chain(first_sel);
6093   register_unit(unit, context);
6094   if (first_sel->next_select())
6095   {
6096     unit->reset_distinct();
6097     DBUG_ASSERT(!unit->fake_select_lex);
6098     if (unit->add_fake_select_lex(parent_lex->thd))
6099       DBUG_RETURN(NULL);
6100   }
6101 
6102   DBUG_RETURN(unit);
6103 }
6104 
6105 SELECT_LEX *
wrap_unit_into_derived(SELECT_LEX_UNIT * unit)6106 LEX::wrap_unit_into_derived(SELECT_LEX_UNIT *unit)
6107 {
6108   SELECT_LEX *wrapping_sel;
6109   Table_ident *ti;
6110   DBUG_ENTER("LEX::wrap_unit_into_derived");
6111 
6112   if (!(wrapping_sel= alloc_select(TRUE)))
6113     DBUG_RETURN(NULL);
6114   Name_resolution_context *context= &wrapping_sel->context;
6115   context->init();
6116   wrapping_sel->automatic_brackets= FALSE;
6117   wrapping_sel->mark_as_unit_nest();
6118   wrapping_sel->register_unit(unit, context);
6119 
6120   /* stuff dummy SELECT * FROM (...) */
6121 
6122   if (push_select(wrapping_sel)) // for Items & TABLE_LIST
6123     DBUG_RETURN(NULL);
6124 
6125   /* add SELECT list*/
6126   {
6127     Item *item= new (thd->mem_root) Item_field(thd, context, star_clex_str);
6128     if (item == NULL)
6129       goto err;
6130     if (add_item_to_list(thd, item))
6131       goto err;
6132     (wrapping_sel->with_wild)++;
6133   }
6134 
6135   unit->first_select()->set_linkage(DERIVED_TABLE_TYPE);
6136 
6137   ti= new (thd->mem_root) Table_ident(unit);
6138   if (ti == NULL)
6139     goto err;
6140   {
6141     TABLE_LIST *table_list;
6142     LEX_CSTRING alias;
6143     if (wrapping_sel->make_unique_derived_name(thd, &alias))
6144       goto err;
6145 
6146     if (!(table_list= wrapping_sel->add_table_to_list(thd, ti, &alias,
6147                                                       0, TL_READ,
6148                                                       MDL_SHARED_READ)))
6149       goto err;
6150 
6151     context->resolve_in_table_list_only(table_list);
6152     wrapping_sel->add_joined_table(table_list);
6153   }
6154 
6155   pop_select();
6156 
6157   derived_tables|= DERIVED_SUBQUERY;
6158 
6159   DBUG_RETURN(wrapping_sel);
6160 
6161 err:
6162   pop_select();
6163   DBUG_RETURN(NULL);
6164 }
6165 
wrap_select_chain_into_derived(SELECT_LEX * sel)6166 SELECT_LEX *LEX::wrap_select_chain_into_derived(SELECT_LEX *sel)
6167 {
6168   SELECT_LEX *dummy_select;
6169   SELECT_LEX_UNIT *unit;
6170   Table_ident *ti;
6171   DBUG_ENTER("LEX::wrap_select_chain_into_derived");
6172 
6173   if (!(dummy_select= alloc_select(TRUE)))
6174      DBUG_RETURN(NULL);
6175   Name_resolution_context *context= &dummy_select->context;
6176   dummy_select->automatic_brackets= FALSE;
6177   sel->distinct= TRUE; // First select has not this attribute (safety)
6178 
6179   if (!(unit= dummy_select->attach_selects_chain(sel, context)))
6180     DBUG_RETURN(NULL);
6181 
6182   /* stuff dummy SELECT * FROM (...) */
6183 
6184   if (push_select(dummy_select)) // for Items & TABLE_LIST
6185     DBUG_RETURN(NULL);
6186 
6187   /* add SELECT list*/
6188   {
6189     Item *item= new (thd->mem_root) Item_field(thd, context, star_clex_str);
6190     if (item == NULL)
6191       goto err;
6192     if (add_item_to_list(thd, item))
6193       goto err;
6194     (dummy_select->with_wild)++;
6195   }
6196 
6197   sel->set_linkage(DERIVED_TABLE_TYPE);
6198 
6199   ti= new (thd->mem_root) Table_ident(unit);
6200   if (ti == NULL)
6201     goto err;
6202   {
6203     TABLE_LIST *table_list;
6204     LEX_CSTRING alias;
6205     if (dummy_select->make_unique_derived_name(thd, &alias))
6206       goto err;
6207 
6208     if (!(table_list= dummy_select->add_table_to_list(thd, ti, &alias,
6209                                                       0, TL_READ,
6210                                                       MDL_SHARED_READ)))
6211       goto err;
6212 
6213     context->resolve_in_table_list_only(table_list);
6214     dummy_select->add_joined_table(table_list);
6215   }
6216 
6217   pop_select();
6218 
6219   derived_tables|= DERIVED_SUBQUERY;
6220 
6221   DBUG_RETURN(dummy_select);
6222 
6223 err:
6224   pop_select();
6225   DBUG_RETURN(NULL);
6226 }
6227 
push_context(Name_resolution_context * context)6228 bool LEX::push_context(Name_resolution_context *context)
6229 {
6230   DBUG_ENTER("LEX::push_context");
6231   DBUG_PRINT("info", ("Context: %p Select: %p (%d)",
6232                        context, context->select_lex,
6233                        (context->select_lex ?
6234                         context->select_lex->select_number:
6235                         0)));
6236   bool res= context_stack.push_front(context, thd->mem_root);
6237   DBUG_RETURN(res);
6238 }
6239 
6240 
pop_context()6241 Name_resolution_context *LEX::pop_context()
6242 {
6243   DBUG_ENTER("LEX::pop_context");
6244   Name_resolution_context *context= context_stack.pop();
6245   DBUG_PRINT("info", ("Context: %p Select: %p (%d)",
6246                        context, context->select_lex,
6247                        (context->select_lex ?
6248                         context->select_lex->select_number:
6249                         0)));
6250   DBUG_RETURN(context);
6251 }
6252 
6253 
create_priority_nest(SELECT_LEX * first_in_nest)6254 SELECT_LEX *LEX::create_priority_nest(SELECT_LEX *first_in_nest)
6255 {
6256   DBUG_ENTER("LEX::create_priority_nest");
6257   DBUG_ASSERT(first_in_nest->first_nested);
6258   enum sub_select_type wr_unit_type= first_in_nest->get_linkage();
6259   bool wr_distinct= first_in_nest->distinct;
6260   SELECT_LEX *attach_to= first_in_nest->first_nested;
6261   attach_to->cut_next();
6262   SELECT_LEX *wrapper= wrap_select_chain_into_derived(first_in_nest);
6263   if (wrapper)
6264   {
6265     first_in_nest->first_nested= NULL;
6266     wrapper->set_linkage_and_distinct(wr_unit_type, wr_distinct);
6267     wrapper->first_nested= attach_to->first_nested;
6268     wrapper->set_master_unit(attach_to->master_unit());
6269     attach_to->link_neighbour(wrapper);
6270   }
6271   DBUG_RETURN(wrapper);
6272 }
6273 
6274 
6275 /**
6276   Checks if we need finish "automatic brackets" mode
6277 
6278   INTERSECT has higher priority then UNION and EXCEPT, so when it is need we
6279   automatically create lower layer for INTERSECT (automatic brackets) and
6280   here we check if we should return back one level up during parsing procedure.
6281 */
6282 
check_automatic_up(enum sub_select_type type)6283 void LEX::check_automatic_up(enum sub_select_type type)
6284 {
6285   if (type != INTERSECT_TYPE &&
6286       current_select->get_linkage() == INTERSECT_TYPE &&
6287       current_select->outer_select() &&
6288       current_select->outer_select()->automatic_brackets)
6289   {
6290     nest_level--;
6291     current_select= current_select->outer_select();
6292   }
6293 }
6294 
6295 
sp_param_init(LEX_CSTRING * name)6296 sp_variable *LEX::sp_param_init(LEX_CSTRING *name)
6297 {
6298   if (spcont->find_variable(name, true))
6299   {
6300     my_error(ER_SP_DUP_PARAM, MYF(0), name->str);
6301     return NULL;
6302   }
6303   sp_variable *spvar= spcont->add_variable(thd, name);
6304   init_last_field(&spvar->field_def, name,
6305                   thd->variables.collation_database);
6306   return spvar;
6307 }
6308 
6309 
sp_param_fill_definition(sp_variable * spvar,const Lex_field_type_st & def)6310 bool LEX::sp_param_fill_definition(sp_variable *spvar,
6311                                    const Lex_field_type_st &def)
6312 {
6313   return
6314     last_field->set_attributes(thd, def, charset,
6315                                COLUMN_DEFINITION_ROUTINE_PARAM) ||
6316     sphead->fill_spvar_definition(thd, last_field, &spvar->name);
6317 }
6318 
6319 
sf_return_fill_definition(const Lex_field_type_st & def)6320 bool LEX::sf_return_fill_definition(const Lex_field_type_st &def)
6321 {
6322   return
6323     last_field->set_attributes(thd, def, charset,
6324                                COLUMN_DEFINITION_FUNCTION_RETURN) ||
6325     sphead->fill_field_definition(thd, last_field);
6326 }
6327 
6328 
set_stmt_init()6329 void LEX::set_stmt_init()
6330 {
6331   sql_command= SQLCOM_SET_OPTION;
6332   mysql_init_select(this);
6333   option_type= OPT_SESSION;
6334   autocommit= 0;
6335   var_list.empty();
6336 };
6337 
6338 
6339 /**
6340   Find a local or a package body variable by name.
6341   @param IN  name    - the variable name
6342   @param OUT ctx     - NULL, if the variable was not found,
6343                        or LEX::spcont (if a local variable was found)
6344                        or the package top level context
6345                        (if a package variable was found)
6346   @param OUT handler - NULL, if the variable was not found,
6347                        or a pointer to rcontext handler
6348   @retval            - the variable (if found), or NULL otherwise.
6349 */
6350 sp_variable *
find_variable(const LEX_CSTRING * name,sp_pcontext ** ctx,const Sp_rcontext_handler ** rh) const6351 LEX::find_variable(const LEX_CSTRING *name,
6352                    sp_pcontext **ctx,
6353                    const Sp_rcontext_handler **rh) const
6354 {
6355   sp_variable *spv;
6356   if (spcont && (spv= spcont->find_variable(name, false)))
6357   {
6358     *ctx= spcont;
6359     *rh= &sp_rcontext_handler_local;
6360     return spv;
6361   }
6362   sp_package *pkg= sphead ? sphead->m_parent : NULL;
6363   if (pkg && (spv= pkg->find_package_variable(name)))
6364   {
6365     *ctx= pkg->get_parse_context()->child_context(0);
6366     *rh= &sp_rcontext_handler_package_body;
6367     return spv;
6368   }
6369   *ctx= NULL;
6370   *rh= NULL;
6371   return NULL;
6372 }
6373 
6374 
is_new(const char * str)6375 static bool is_new(const char *str)
6376 {
6377   return (str[0] == 'n' || str[0] == 'N') &&
6378          (str[1] == 'e' || str[1] == 'E') &&
6379          (str[2] == 'w' || str[2] == 'W');
6380 }
6381 
is_old(const char * str)6382 static bool is_old(const char *str)
6383 {
6384   return (str[0] == 'o' || str[0] == 'O') &&
6385          (str[1] == 'l' || str[1] == 'L') &&
6386          (str[2] == 'd' || str[2] == 'D');
6387 }
6388 
6389 
is_trigger_new_or_old_reference(const LEX_CSTRING * name) const6390 bool LEX::is_trigger_new_or_old_reference(const LEX_CSTRING *name) const
6391 {
6392   // "name" is not necessarily NULL-terminated!
6393   return sphead && sphead->m_handler->type() == SP_TYPE_TRIGGER &&
6394          name->length == 3 && (is_new(name->str) || is_old(name->str));
6395 }
6396 
6397 
sp_variable_declarations_init(THD * thd,int nvars)6398 void LEX::sp_variable_declarations_init(THD *thd, int nvars)
6399 {
6400   sp_variable *spvar= spcont->get_last_context_variable();
6401 
6402   sphead->reset_lex(thd);
6403   spcont->declare_var_boundary(nvars);
6404   thd->lex->init_last_field(&spvar->field_def, &spvar->name,
6405                             thd->variables.collation_database);
6406 }
6407 
6408 
sp_variable_declarations_set_default(THD * thd,int nvars,Item * dflt_value_item)6409 bool LEX::sp_variable_declarations_set_default(THD *thd, int nvars,
6410                                                Item *dflt_value_item)
6411 {
6412   bool has_default_clause= dflt_value_item != NULL;
6413   if (!has_default_clause &&
6414       unlikely(!(dflt_value_item= new (thd->mem_root) Item_null(thd))))
6415     return true;
6416 
6417   sp_variable *first_spvar = NULL;
6418 
6419   for (uint i= 0 ; i < (uint) nvars ; i++)
6420   {
6421     sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
6422 
6423     if (i == 0) {
6424       first_spvar = spvar;
6425     } else if (has_default_clause) {
6426       Item_splocal *item =
6427               new (thd->mem_root)
6428                       Item_splocal(thd, &sp_rcontext_handler_local,
6429                                    &first_spvar->name, first_spvar->offset,
6430                                    first_spvar->type_handler(), 0, 0);
6431       if (item == NULL)
6432         return true; // OOM
6433 #ifndef DBUG_OFF
6434       item->m_sp = sphead;
6435 #endif
6436       dflt_value_item = item;
6437     }
6438 
6439     bool last= i + 1 == (uint) nvars;
6440     spvar->default_value= dflt_value_item;
6441     /* The last instruction is responsible for freeing LEX. */
6442     sp_instr_set *is= new (thd->mem_root)
6443                       sp_instr_set(sphead->instructions(),
6444                                    spcont, &sp_rcontext_handler_local,
6445                                    spvar->offset, dflt_value_item,
6446                                    this, last);
6447     if (unlikely(is == NULL || sphead->add_instr(is)))
6448       return true;
6449   }
6450   return false;
6451 }
6452 
6453 
6454 bool
sp_variable_declarations_copy_type_finalize(THD * thd,int nvars,const Column_definition & ref,Row_definition_list * fields,Item * default_value)6455 LEX::sp_variable_declarations_copy_type_finalize(THD *thd, int nvars,
6456                                                  const Column_definition &ref,
6457                                                  Row_definition_list *fields,
6458                                                  Item *default_value)
6459 {
6460   for (uint i= 0 ; i < (uint) nvars; i++)
6461   {
6462     sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
6463     spvar->field_def.set_type(ref);
6464     if (fields)
6465     {
6466       DBUG_ASSERT(ref.type_handler() == &type_handler_row);
6467       spvar->field_def.set_row_field_definitions(fields);
6468     }
6469     spvar->field_def.field_name= spvar->name;
6470   }
6471   if (unlikely(sp_variable_declarations_set_default(thd, nvars,
6472                                                     default_value)))
6473     return true;
6474   spcont->declare_var_boundary(0);
6475   return sphead->restore_lex(thd);
6476 }
6477 
6478 
sp_variable_declarations_finalize(THD * thd,int nvars,const Column_definition * cdef,Item * dflt_value_item)6479 bool LEX::sp_variable_declarations_finalize(THD *thd, int nvars,
6480                                             const Column_definition *cdef,
6481                                             Item *dflt_value_item)
6482 {
6483   DBUG_ASSERT(cdef);
6484   Column_definition tmp(*cdef);
6485   if (sphead->fill_spvar_definition(thd, &tmp))
6486     return true;
6487   return sp_variable_declarations_copy_type_finalize(thd, nvars, tmp, NULL,
6488                                                      dflt_value_item);
6489 }
6490 
6491 
sp_variable_declarations_row_finalize(THD * thd,int nvars,Row_definition_list * row,Item * dflt_value_item)6492 bool LEX::sp_variable_declarations_row_finalize(THD *thd, int nvars,
6493                                                 Row_definition_list *row,
6494                                                 Item *dflt_value_item)
6495 {
6496   DBUG_ASSERT(row);
6497   /*
6498     Prepare all row fields.
6499     Note, we do it only one time outside of the below loop.
6500     The converted list in "row" is further reused by all variable
6501     declarations processed by the current call.
6502     Example:
6503       DECLARE
6504         a, b, c ROW(x VARCHAR(10) CHARACTER SET utf8);
6505       BEGIN
6506         ...
6507       END;
6508   */
6509   if (sphead->row_fill_field_definitions(thd, row))
6510     return true;
6511 
6512   for (uint i= 0 ; i < (uint) nvars ; i++)
6513   {
6514     sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
6515     spvar->field_def.set_row_field_definitions(row);
6516     if (sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name))
6517       return true;
6518   }
6519 
6520   if (sp_variable_declarations_set_default(thd, nvars, dflt_value_item))
6521     return true;
6522   spcont->declare_var_boundary(0);
6523   return sphead->restore_lex(thd);
6524 }
6525 
6526 
6527 /**
6528   Finalize a %ROWTYPE declaration, e.g.:
6529     DECLARE a,b,c,d t1%ROWTYPE := ROW(1,2,3);
6530 
6531   @param thd   - the current thd
6532   @param nvars - the number of variables in the declaration
6533   @param ref   - the table or cursor name (see comments below)
6534   @param def   - the default value, e.g., ROW(1,2,3), or NULL (no default).
6535 */
6536 bool
sp_variable_declarations_rowtype_finalize(THD * thd,int nvars,Qualified_column_ident * ref,Item * def)6537 LEX::sp_variable_declarations_rowtype_finalize(THD *thd, int nvars,
6538                                                Qualified_column_ident *ref,
6539                                                Item *def)
6540 {
6541   uint coffp;
6542   const sp_pcursor *pcursor= ref->table.str && ref->db.str ? NULL :
6543                              spcont->find_cursor(&ref->m_column, &coffp,
6544                                                  false);
6545   if (pcursor)
6546     return sp_variable_declarations_cursor_rowtype_finalize(thd, nvars,
6547                                                             coffp, def);
6548   /*
6549     When parsing a qualified identifier chain, the parser does not know yet
6550     if it's going to be a qualified column name (for %TYPE),
6551     or a qualified table name (for %ROWTYPE). So it collects the chain
6552     into Qualified_column_ident.
6553     Now we know that it was actually a qualified table name (%ROWTYPE).
6554     Create a new Table_ident from Qualified_column_ident,
6555     shifting fields as follows:
6556     - ref->m_column becomes table_ref->table
6557     - ref->table    becomes table_ref->db
6558   */
6559   return sp_variable_declarations_table_rowtype_finalize(thd, nvars,
6560                                                          ref->table,
6561                                                          ref->m_column,
6562                                                          def);
6563 }
6564 
6565 
6566 bool
sp_variable_declarations_table_rowtype_finalize(THD * thd,int nvars,const LEX_CSTRING & db,const LEX_CSTRING & table,Item * def)6567 LEX::sp_variable_declarations_table_rowtype_finalize(THD *thd, int nvars,
6568                                                      const LEX_CSTRING &db,
6569                                                      const LEX_CSTRING &table,
6570                                                      Item *def)
6571 {
6572   Table_ident *table_ref;
6573   if (unlikely(!(table_ref=
6574                  new (thd->mem_root) Table_ident(thd, &db, &table, false))))
6575     return true;
6576   // Loop through all variables in the same declaration
6577   for (uint i= 0 ; i < (uint) nvars; i++)
6578   {
6579     sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
6580     spvar->field_def.set_table_rowtype_ref(table_ref);
6581     sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
6582   }
6583   if (sp_variable_declarations_set_default(thd, nvars, def))
6584     return true;
6585   // Make sure sp_rcontext is created using the invoker security context:
6586   sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
6587   spcont->declare_var_boundary(0);
6588   return sphead->restore_lex(thd);
6589 }
6590 
6591 
6592 bool
sp_variable_declarations_cursor_rowtype_finalize(THD * thd,int nvars,uint offset,Item * def)6593 LEX::sp_variable_declarations_cursor_rowtype_finalize(THD *thd, int nvars,
6594                                                       uint offset,
6595                                                       Item *def)
6596 {
6597   const sp_pcursor *pcursor= spcont->find_cursor(offset);
6598 
6599   // Loop through all variables in the same declaration
6600   for (uint i= 0 ; i < (uint) nvars; i++)
6601   {
6602     sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
6603 
6604     spvar->field_def.set_cursor_rowtype_ref(offset);
6605     sp_instr_cursor_copy_struct *instr=
6606       new (thd->mem_root) sp_instr_cursor_copy_struct(sphead->instructions(),
6607                                                       spcont, offset,
6608                                                       pcursor->lex(),
6609                                                       spvar->offset);
6610     if (instr == NULL || sphead->add_instr(instr))
6611      return true;
6612 
6613     sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
6614   }
6615   if (unlikely(sp_variable_declarations_set_default(thd, nvars, def)))
6616     return true;
6617   // Make sure sp_rcontext is created using the invoker security context:
6618   sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
6619   spcont->declare_var_boundary(0);
6620   return sphead->restore_lex(thd);
6621 }
6622 
6623 
6624 /*
6625   Add declarations for table column and SP variable anchor types:
6626   - DECLARE spvar1 TYPE OF db1.table1.column1;
6627   - DECLARE spvar1 TYPE OF table1.column1;
6628   - DECLARE spvar1 TYPE OF spvar0;
6629 */
6630 bool
sp_variable_declarations_with_ref_finalize(THD * thd,int nvars,Qualified_column_ident * ref,Item * def)6631 LEX::sp_variable_declarations_with_ref_finalize(THD *thd, int nvars,
6632                                                 Qualified_column_ident *ref,
6633                                                 Item *def)
6634 {
6635   return ref->db.length == 0 && ref->table.length == 0 ?
6636     sp_variable_declarations_vartype_finalize(thd, nvars, ref->m_column, def) :
6637     sp_variable_declarations_column_type_finalize(thd, nvars, ref, def);
6638 }
6639 
6640 
6641 bool
sp_variable_declarations_column_type_finalize(THD * thd,int nvars,Qualified_column_ident * ref,Item * def)6642 LEX::sp_variable_declarations_column_type_finalize(THD *thd, int nvars,
6643                                                    Qualified_column_ident *ref,
6644                                                    Item *def)
6645 {
6646   for (uint i= 0 ; i < (uint) nvars; i++)
6647   {
6648     sp_variable *spvar= spcont->get_last_context_variable((uint) nvars - 1 - i);
6649     spvar->field_def.set_column_type_ref(ref);
6650     spvar->field_def.field_name= spvar->name;
6651   }
6652   sphead->m_flags|= sp_head::HAS_COLUMN_TYPE_REFS;
6653   if (sp_variable_declarations_set_default(thd, nvars, def))
6654     return true;
6655   spcont->declare_var_boundary(0);
6656   return sphead->restore_lex(thd);
6657 }
6658 
6659 
6660 bool
sp_variable_declarations_vartype_finalize(THD * thd,int nvars,const LEX_CSTRING & ref,Item * default_value)6661 LEX::sp_variable_declarations_vartype_finalize(THD *thd, int nvars,
6662                                                const LEX_CSTRING &ref,
6663                                                Item *default_value)
6664 {
6665   sp_variable *t;
6666   if (!spcont || !(t= spcont->find_variable(&ref, false)))
6667   {
6668     my_error(ER_SP_UNDECLARED_VAR, MYF(0), ref.str);
6669     return true;
6670   }
6671 
6672   if (t->field_def.is_cursor_rowtype_ref())
6673   {
6674     uint offset= t->field_def.cursor_rowtype_offset();
6675     return sp_variable_declarations_cursor_rowtype_finalize(thd, nvars,
6676                                                             offset,
6677                                                             default_value);
6678   }
6679 
6680   if (t->field_def.is_column_type_ref())
6681   {
6682     Qualified_column_ident *tmp= t->field_def.column_type_ref();
6683     return sp_variable_declarations_column_type_finalize(thd, nvars, tmp,
6684                                                          default_value);
6685   }
6686 
6687   if (t->field_def.is_table_rowtype_ref())
6688   {
6689     const Table_ident *tmp= t->field_def.table_rowtype_ref();
6690     return sp_variable_declarations_table_rowtype_finalize(thd, nvars,
6691                                                            tmp->db,
6692                                                            tmp->table,
6693                                                            default_value);
6694   }
6695 
6696   // A reference to a scalar or a row variable with an explicit data type
6697   return sp_variable_declarations_copy_type_finalize(thd, nvars,
6698                                                      t->field_def,
6699                                                      t->field_def.
6700                                                        row_field_definitions(),
6701                                                      default_value);
6702 }
6703 
6704 
6705 /**********************************************************************
6706   The FOR LOOP statement
6707 
6708   This syntax:
6709     FOR i IN lower_bound .. upper_bound
6710     LOOP
6711       statements;
6712     END LOOP;
6713 
6714   is translated into:
6715 
6716     DECLARE
6717       i INT := lower_bound;
6718       j INT := upper_bound;
6719     BEGIN
6720       WHILE i <= j
6721       LOOP
6722         statements;
6723         i:= i + 1;
6724       END LOOP;
6725     END;
6726 */
6727 
6728 
sp_add_for_loop_variable(THD * thd,const LEX_CSTRING * name,Item * value)6729 sp_variable *LEX::sp_add_for_loop_variable(THD *thd, const LEX_CSTRING *name,
6730                                            Item *value)
6731 {
6732   sp_variable *spvar= spcont->add_variable(thd, name);
6733   spcont->declare_var_boundary(1);
6734   spvar->field_def.field_name= spvar->name;
6735   spvar->field_def.set_handler(&type_handler_slonglong);
6736   type_handler_slonglong.Column_definition_prepare_stage2(&spvar->field_def,
6737                                                           NULL, HA_CAN_GEOMETRY);
6738   if (!value && unlikely(!(value= new (thd->mem_root) Item_null(thd))))
6739     return NULL;
6740 
6741   spvar->default_value= value;
6742   sp_instr_set *is= new (thd->mem_root)
6743                     sp_instr_set(sphead->instructions(),
6744                                  spcont, &sp_rcontext_handler_local,
6745                                  spvar->offset, value,
6746                                  this, true);
6747   if (unlikely(is == NULL || sphead->add_instr(is)))
6748     return NULL;
6749   spcont->declare_var_boundary(0);
6750   return spvar;
6751 }
6752 
6753 
sp_for_loop_implicit_cursor_statement(THD * thd,Lex_for_loop_bounds_st * bounds,sp_lex_cursor * cur)6754 bool LEX::sp_for_loop_implicit_cursor_statement(THD *thd,
6755                                                 Lex_for_loop_bounds_st *bounds,
6756                                                 sp_lex_cursor *cur)
6757 {
6758   Item *item;
6759   DBUG_ASSERT(sphead);
6760   LEX_CSTRING name= {STRING_WITH_LEN("[implicit_cursor]") };
6761   if (sp_declare_cursor(thd, &name, cur, NULL, true))
6762     return true;
6763   DBUG_ASSERT(thd->lex == this);
6764   if (unlikely(!(bounds->m_index=
6765                  new (thd->mem_root) sp_assignment_lex(thd, this))))
6766     return true;
6767   bounds->m_index->sp_lex_in_use= true;
6768   sphead->reset_lex(thd, bounds->m_index);
6769   DBUG_ASSERT(thd->lex != this);
6770   /*
6771     We pass NULL as Name_resolution_context here.
6772     It's OK, fix_fields() will not be called for this Item_field created.
6773     Item_field is only needed for LEX::sp_for_loop_cursor_declarations()
6774     and is used to transfer the loop index variable name, "rec" in this example:
6775       FOR rec IN (SELECT * FROM t1)
6776       DO
6777         SELECT rec.a, rec.b;
6778       END FOR;
6779   */
6780   if (!(item= new (thd->mem_root) Item_field(thd, NULL, name)))
6781     return true;
6782   bounds->m_index->set_item_and_free_list(item, NULL);
6783   if (thd->lex->sphead->restore_lex(thd))
6784     return true;
6785   DBUG_ASSERT(thd->lex == this);
6786   bounds->m_direction= 1;
6787   bounds->m_target_bound= NULL;
6788   bounds->m_implicit_cursor= true;
6789   return false;
6790 }
6791 
6792 sp_variable *
sp_add_for_loop_cursor_variable(THD * thd,const LEX_CSTRING * name,const sp_pcursor * pcursor,uint coffset,sp_assignment_lex * param_lex,Item_args * parameters)6793 LEX::sp_add_for_loop_cursor_variable(THD *thd,
6794                                      const LEX_CSTRING *name,
6795                                      const sp_pcursor *pcursor,
6796                                      uint coffset,
6797                                      sp_assignment_lex *param_lex,
6798                                      Item_args *parameters)
6799 {
6800   sp_variable *spvar= spcont->add_variable(thd, name);
6801   if (!spvar)
6802     return NULL;
6803   spcont->declare_var_boundary(1);
6804   sphead->fill_spvar_definition(thd, &spvar->field_def, &spvar->name);
6805   if (unlikely(!(spvar->default_value= new (thd->mem_root) Item_null(thd))))
6806     return NULL;
6807 
6808   spvar->field_def.set_cursor_rowtype_ref(coffset);
6809 
6810   if (unlikely(sphead->add_for_loop_open_cursor(thd, spcont, spvar, pcursor,
6811                                                 coffset,
6812                                                 param_lex, parameters)))
6813     return NULL;
6814 
6815   spcont->declare_var_boundary(0);
6816   return spvar;
6817 }
6818 
6819 
6820 /**
6821   Generate a code for a FOR loop condition:
6822   - Make Item_splocal for the FOR loop index variable
6823   - Make Item_splocal for the FOR loop upper bound variable
6824   - Make a comparison function item on top of these two variables
6825 */
sp_for_loop_condition(THD * thd,const Lex_for_loop_st & loop)6826 bool LEX::sp_for_loop_condition(THD *thd, const Lex_for_loop_st &loop)
6827 {
6828   Item_splocal *args[2];
6829   for (uint i= 0 ; i < 2; i++)
6830   {
6831     sp_variable *src= i == 0 ? loop.m_index : loop.m_target_bound;
6832     args[i]= new (thd->mem_root)
6833               Item_splocal(thd, &sp_rcontext_handler_local,
6834                            &src->name, src->offset, src->type_handler());
6835     if (unlikely(args[i] == NULL))
6836       return true;
6837 #ifdef DBUG_ASSERT_EXISTS
6838     args[i]->m_sp= sphead;
6839 #endif
6840   }
6841 
6842   Item *expr= loop.m_direction > 0 ?
6843     (Item *) new (thd->mem_root) Item_func_le(thd, args[0], args[1]) :
6844     (Item *) new (thd->mem_root) Item_func_ge(thd, args[0], args[1]);
6845   return unlikely(!expr) || unlikely(sp_while_loop_expression(thd, expr));
6846 }
6847 
6848 
6849 /**
6850   Generate the FOR LOOP condition code in its own lex
6851 */
sp_for_loop_intrange_condition_test(THD * thd,const Lex_for_loop_st & loop)6852 bool LEX::sp_for_loop_intrange_condition_test(THD *thd,
6853                                               const Lex_for_loop_st &loop)
6854 {
6855   spcont->set_for_loop(loop);
6856   sphead->reset_lex(thd);
6857   if (unlikely(thd->lex->sp_for_loop_condition(thd, loop)))
6858     return true;
6859   return thd->lex->sphead->restore_lex(thd);
6860 }
6861 
6862 
sp_for_loop_cursor_condition_test(THD * thd,const Lex_for_loop_st & loop)6863 bool LEX::sp_for_loop_cursor_condition_test(THD *thd,
6864                                             const Lex_for_loop_st &loop)
6865 {
6866   const LEX_CSTRING *cursor_name;
6867   Item *expr;
6868   spcont->set_for_loop(loop);
6869   sphead->reset_lex(thd);
6870   cursor_name= spcont->find_cursor(loop.m_cursor_offset);
6871   DBUG_ASSERT(cursor_name);
6872   if (unlikely(!(expr=
6873                  new (thd->mem_root)
6874                  Item_func_cursor_found(thd, cursor_name,
6875                                         loop.m_cursor_offset))))
6876     return true;
6877   if (thd->lex->sp_while_loop_expression(thd, expr))
6878     return true;
6879   return thd->lex->sphead->restore_lex(thd);
6880 }
6881 
6882 
sp_for_loop_intrange_declarations(THD * thd,Lex_for_loop_st * loop,const LEX_CSTRING * index,const Lex_for_loop_bounds_st & bounds)6883 bool LEX::sp_for_loop_intrange_declarations(THD *thd, Lex_for_loop_st *loop,
6884                                             const LEX_CSTRING *index,
6885                                             const Lex_for_loop_bounds_st &bounds)
6886 {
6887   Item *item;
6888   if ((item= bounds.m_index->get_item())->type() == Item::FIELD_ITEM)
6889   {
6890     // We're here is the lower bound is unknown identifier
6891     my_error(ER_SP_UNDECLARED_VAR, MYF(0), item->full_name());
6892     return true;
6893   }
6894   if ((item= bounds.m_target_bound->get_item())->type() == Item::FIELD_ITEM)
6895   {
6896     // We're here is the upper bound is unknown identifier
6897     my_error(ER_SP_UNDECLARED_VAR, MYF(0), item->full_name());
6898     return true;
6899   }
6900   if (!(loop->m_index=
6901         bounds.m_index->sp_add_for_loop_variable(thd, index,
6902                                                  bounds.m_index->get_item())))
6903     return true;
6904   if (unlikely(!(loop->m_target_bound=
6905                  bounds.m_target_bound->
6906                  sp_add_for_loop_target_bound(thd,
6907                                               bounds.
6908                                               m_target_bound->get_item()))))
6909      return true;
6910   loop->m_direction= bounds.m_direction;
6911   loop->m_implicit_cursor= 0;
6912   return false;
6913 }
6914 
6915 
sp_for_loop_cursor_declarations(THD * thd,Lex_for_loop_st * loop,const LEX_CSTRING * index,const Lex_for_loop_bounds_st & bounds)6916 bool LEX::sp_for_loop_cursor_declarations(THD *thd,
6917                                           Lex_for_loop_st *loop,
6918                                           const LEX_CSTRING *index,
6919                                           const Lex_for_loop_bounds_st &bounds)
6920 {
6921   Item *item= bounds.m_index->get_item();
6922   Item_splocal *item_splocal;
6923   Item_field *item_field;
6924   Item_func_sp *item_func_sp= NULL;
6925   LEX_CSTRING name;
6926   uint coffs, param_count= 0;
6927   const sp_pcursor *pcursor;
6928   DBUG_ENTER("LEX::sp_for_loop_cursor_declarations");
6929 
6930   if ((item_splocal= item->get_item_splocal()))
6931     name= item_splocal->m_name;
6932   else if ((item_field= item->type() == Item::FIELD_ITEM ?
6933                         static_cast<Item_field *>(item) : NULL) &&
6934            item_field->table_name.str == NULL)
6935     name= item_field->field_name;
6936   else if (item->type() == Item::FUNC_ITEM &&
6937            static_cast<Item_func*>(item)->functype() == Item_func::FUNC_SP &&
6938            !static_cast<Item_func_sp*>(item)->get_sp_name()->m_explicit_name)
6939   {
6940     /*
6941       When a FOR LOOP for a cursor with parameters is parsed:
6942         FOR index IN cursor(1,2,3) LOOP
6943           statements;
6944         END LOOP;
6945       the parser scans "cursor(1,2,3)" using the "expr" rule,
6946       so it thinks that cursor(1,2,3) is a stored function call.
6947       It's not easy to implement this without using "expr" because
6948       of grammar conflicts.
6949       As a side effect, the Item_func_sp and its arguments in the parentheses
6950       belong to the same LEX. This is different from an explicit
6951       "OPEN cursor(1,2,3)" where every expression belongs to a separate LEX.
6952     */
6953     item_func_sp= static_cast<Item_func_sp*>(item);
6954     name= item_func_sp->get_sp_name()->m_name;
6955     param_count= item_func_sp->argument_count();
6956   }
6957   else
6958   {
6959     thd->parse_error();
6960     DBUG_RETURN(true);
6961   }
6962   if (unlikely(!(pcursor= spcont->find_cursor_with_error(&name, &coffs,
6963                                                          false)) ||
6964                pcursor->check_param_count_with_error(param_count)))
6965     DBUG_RETURN(true);
6966 
6967   if (!(loop->m_index= sp_add_for_loop_cursor_variable(thd, index,
6968                                                        pcursor, coffs,
6969                                                        bounds.m_index,
6970                                                        item_func_sp)))
6971     DBUG_RETURN(true);
6972   loop->m_target_bound= NULL;
6973   loop->m_direction= bounds.m_direction;
6974   loop->m_cursor_offset= coffs;
6975   loop->m_implicit_cursor= bounds.m_implicit_cursor;
6976   DBUG_RETURN(false);
6977 }
6978 
6979 
6980 /**
6981   Generate a code for a FOR loop index increment
6982 */
sp_for_loop_increment(THD * thd,const Lex_for_loop_st & loop)6983 bool LEX::sp_for_loop_increment(THD *thd, const Lex_for_loop_st &loop)
6984 {
6985   Item_splocal *splocal= new (thd->mem_root)
6986     Item_splocal(thd, &sp_rcontext_handler_local,
6987                       &loop.m_index->name, loop.m_index->offset,
6988                       loop.m_index->type_handler());
6989   if (unlikely(splocal == NULL))
6990     return true;
6991 #ifdef DBUG_ASSERT_EXISTS
6992   splocal->m_sp= sphead;
6993 #endif
6994   Item_int *inc= new (thd->mem_root) Item_int(thd, loop.m_direction);
6995   if (unlikely(!inc))
6996     return true;
6997   Item *expr= new (thd->mem_root) Item_func_plus(thd, splocal, inc);
6998   if (unlikely(!expr) ||
6999       unlikely(sphead->set_local_variable(thd, spcont,
7000                                           &sp_rcontext_handler_local,
7001                                           loop.m_index, expr, this, true)))
7002     return true;
7003   return false;
7004 }
7005 
7006 
sp_for_loop_intrange_finalize(THD * thd,const Lex_for_loop_st & loop)7007 bool LEX::sp_for_loop_intrange_finalize(THD *thd, const Lex_for_loop_st &loop)
7008 {
7009   sphead->reset_lex(thd);
7010 
7011   // Generate FOR LOOP index increment in its own lex
7012   DBUG_ASSERT(this != thd->lex);
7013   if (unlikely(thd->lex->sp_for_loop_increment(thd, loop) ||
7014                thd->lex->sphead->restore_lex(thd)))
7015     return true;
7016 
7017   // Generate a jump to the beginning of the loop
7018   DBUG_ASSERT(this == thd->lex);
7019   return sp_while_loop_finalize(thd);
7020 }
7021 
7022 
sp_for_loop_cursor_finalize(THD * thd,const Lex_for_loop_st & loop)7023 bool LEX::sp_for_loop_cursor_finalize(THD *thd, const Lex_for_loop_st &loop)
7024 {
7025   sp_instr_cfetch *instr=
7026     new (thd->mem_root) sp_instr_cfetch(sphead->instructions(),
7027                                         spcont, loop.m_cursor_offset, false);
7028   if (unlikely(instr == NULL) || unlikely(sphead->add_instr(instr)))
7029     return true;
7030   instr->add_to_varlist(loop.m_index);
7031   // Generate a jump to the beginning of the loop
7032   return sp_while_loop_finalize(thd);
7033 }
7034 
sp_for_loop_outer_block_finalize(THD * thd,const Lex_for_loop_st & loop)7035 bool LEX::sp_for_loop_outer_block_finalize(THD *thd,
7036                                            const Lex_for_loop_st &loop)
7037 {
7038   Lex_spblock tmp;
7039   tmp.curs= MY_TEST(loop.m_implicit_cursor);
7040   if (unlikely(sp_block_finalize(thd, tmp))) // The outer DECLARE..BEGIN..END
7041     return true;
7042   if (!loop.is_for_loop_explicit_cursor())
7043     return false;
7044   /*
7045     Explicit cursor FOR loop must close the cursor automatically.
7046     Note, implicit cursor FOR loop does not need to close the cursor,
7047     it's closed by sp_instr_cpop.
7048   */
7049   sp_instr_cclose *ic= new (thd->mem_root)
7050                        sp_instr_cclose(sphead->instructions(), spcont,
7051                                        loop.m_cursor_offset);
7052   return ic == NULL || sphead->add_instr(ic);
7053 }
7054 
7055 /***************************************************************************/
7056 
sp_declare_cursor(THD * thd,const LEX_CSTRING * name,sp_lex_cursor * cursor_stmt,sp_pcontext * param_ctx,bool add_cpush_instr)7057 bool LEX::sp_declare_cursor(THD *thd, const LEX_CSTRING *name,
7058                             sp_lex_cursor *cursor_stmt,
7059                             sp_pcontext *param_ctx, bool add_cpush_instr)
7060 {
7061   uint offp;
7062   sp_instr_cpush *i;
7063 
7064   if (spcont->find_cursor(name, &offp, true))
7065   {
7066     my_error(ER_SP_DUP_CURS, MYF(0), name->str);
7067     return true;
7068   }
7069 
7070   if (unlikely(spcont->add_cursor(name, param_ctx, cursor_stmt)))
7071     return true;
7072 
7073   if (add_cpush_instr)
7074   {
7075     i= new (thd->mem_root)
7076          sp_instr_cpush(sphead->instructions(), spcont, cursor_stmt,
7077                         spcont->current_cursor_count() - 1);
7078     return unlikely(i == NULL) || unlikely(sphead->add_instr(i));
7079   }
7080   return false;
7081 }
7082 
7083 
7084 /**
7085   Generate an SP code for an "OPEN cursor_name" statement.
7086   @param thd
7087   @param name       - Name of the cursor
7088   @param parameters - Cursor parameters, e.g. OPEN c(1,2,3)
7089   @returns          - false on success, true on error
7090 */
sp_open_cursor(THD * thd,const LEX_CSTRING * name,List<sp_assignment_lex> * parameters)7091 bool LEX::sp_open_cursor(THD *thd, const LEX_CSTRING *name,
7092                          List<sp_assignment_lex> *parameters)
7093 {
7094   uint offset;
7095   const sp_pcursor *pcursor;
7096   uint param_count= parameters ? parameters->elements : 0;
7097   return !(pcursor= spcont->find_cursor_with_error(name, &offset, false)) ||
7098          pcursor->check_param_count_with_error(param_count) ||
7099          sphead->add_open_cursor(thd, spcont, offset,
7100                                  pcursor->param_context(), parameters);
7101 }
7102 
7103 
sp_handler_declaration_init(THD * thd,int type)7104 bool LEX::sp_handler_declaration_init(THD *thd, int type)
7105 {
7106   sp_handler *h= spcont->add_handler(thd, (sp_handler::enum_type) type);
7107 
7108   spcont= spcont->push_context(thd, sp_pcontext::HANDLER_SCOPE);
7109 
7110   sp_instr_hpush_jump *i=
7111     new (thd->mem_root) sp_instr_hpush_jump(sphead->instructions(), spcont, h);
7112 
7113   if (unlikely(i == NULL) || unlikely(sphead->add_instr(i)))
7114     return true;
7115 
7116   /* For continue handlers, mark end of handler scope. */
7117   if (type == sp_handler::CONTINUE &&
7118       unlikely(sphead->push_backpatch(thd, i, spcont->last_label())))
7119     return true;
7120 
7121   if (unlikely(sphead->push_backpatch(thd, i,
7122                                       spcont->push_label(thd, &empty_clex_str,
7123                                                          0))))
7124     return true;
7125 
7126   return false;
7127 }
7128 
7129 
sp_handler_declaration_finalize(THD * thd,int type)7130 bool LEX::sp_handler_declaration_finalize(THD *thd, int type)
7131 {
7132   sp_label *hlab= spcont->pop_label(); /* After this hdlr */
7133   sp_instr_hreturn *i;
7134 
7135   if (type == sp_handler::CONTINUE)
7136   {
7137     i= new (thd->mem_root) sp_instr_hreturn(sphead->instructions(), spcont);
7138     if (unlikely(i == NULL) ||
7139         unlikely(sphead->add_instr(i)))
7140       return true;
7141   }
7142   else
7143   {  /* EXIT or UNDO handler, just jump to the end of the block */
7144     i= new (thd->mem_root) sp_instr_hreturn(sphead->instructions(), spcont);
7145     if (unlikely(i == NULL) ||
7146         unlikely(sphead->add_instr(i)) ||
7147         unlikely(sphead->push_backpatch(thd, i, spcont->last_label()))) /* Block end */
7148       return true;
7149   }
7150   sphead->backpatch(hlab);
7151   spcont= spcont->pop_context();
7152   return false;
7153 }
7154 
7155 
sp_block_init(THD * thd,const LEX_CSTRING * label)7156 void LEX::sp_block_init(THD *thd, const LEX_CSTRING *label)
7157 {
7158   spcont->push_label(thd, label, sphead->instructions(), sp_label::BEGIN);
7159   spcont= spcont->push_context(thd, sp_pcontext::REGULAR_SCOPE);
7160 }
7161 
7162 
sp_block_finalize(THD * thd,const Lex_spblock_st spblock,class sp_label ** splabel)7163 bool LEX::sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
7164                                       class sp_label **splabel)
7165 {
7166   sp_head *sp= sphead;
7167   sp_pcontext *ctx= spcont;
7168   sp_instr *i;
7169 
7170   sp->backpatch(ctx->last_label()); /* We always have a label */
7171   if (spblock.hndlrs)
7172   {
7173     i= new (thd->mem_root)
7174       sp_instr_hpop(sp->instructions(), ctx, spblock.hndlrs);
7175     if (unlikely(i == NULL) ||
7176         unlikely(sp->add_instr(i)))
7177       return true;
7178   }
7179   if (spblock.curs)
7180   {
7181     i= new (thd->mem_root)
7182       sp_instr_cpop(sp->instructions(), ctx, spblock.curs);
7183     if (unlikely(i == NULL) ||
7184         unlikely(sp->add_instr(i)))
7185       return true;
7186   }
7187   spcont= ctx->pop_context();
7188   *splabel= spcont->pop_label();
7189   return false;
7190 }
7191 
7192 
sp_block_finalize(THD * thd,const Lex_spblock_st spblock,const LEX_CSTRING * end_label)7193 bool LEX::sp_block_finalize(THD *thd, const Lex_spblock_st spblock,
7194                             const LEX_CSTRING *end_label)
7195 {
7196   sp_label *splabel;
7197   if (unlikely(sp_block_finalize(thd, spblock, &splabel)))
7198     return true;
7199   if (unlikely(end_label->str &&
7200                lex_string_cmp(system_charset_info,
7201                               end_label, &splabel->name) != 0))
7202   {
7203     my_error(ER_SP_LABEL_MISMATCH, MYF(0), end_label->str);
7204     return true;
7205   }
7206   return false;
7207 }
7208 
7209 
make_sp_name(THD * thd,const LEX_CSTRING * name)7210 sp_name *LEX::make_sp_name(THD *thd, const LEX_CSTRING *name)
7211 {
7212   sp_name *res;
7213   LEX_CSTRING db;
7214   if (unlikely(check_routine_name(name)) ||
7215       unlikely(copy_db_to(&db)) ||
7216       unlikely((!(res= new (thd->mem_root) sp_name(&db, name, false)))))
7217     return NULL;
7218   return res;
7219 }
7220 
7221 
7222 /**
7223   When a package routine name is stored in memory in Database_qualified_name,
7224   the dot character is used to delimit package name from the routine name,
7225   e.g.:
7226     m_db=   'test';   -- database 'test'
7227     m_name= 'p1.p1';  -- package 'p1', routine 'p1'
7228   See database_qualified_name::make_package_routine_name() for details.
7229   Disallow package routine names with dots,
7230   to avoid ambiguity when interpreting m_name='p1.p1.p1', between:
7231     a.  package 'p1.p1' + routine 'p1'
7232     b.  package 'p1'    + routine 'p1.p1'
7233   m_name='p1.p1.p1' will always mean (a).
7234 */
make_sp_name_package_routine(THD * thd,const LEX_CSTRING * name)7235 sp_name *LEX::make_sp_name_package_routine(THD *thd, const LEX_CSTRING *name)
7236 {
7237   sp_name *res= make_sp_name(thd, name);
7238   if (likely(res) && unlikely(strchr(res->m_name.str, '.')))
7239   {
7240     my_error(ER_SP_WRONG_NAME, MYF(0), res->m_name.str);
7241     res= NULL;
7242   }
7243   return res;
7244 }
7245 
7246 
make_sp_name(THD * thd,const LEX_CSTRING * name1,const LEX_CSTRING * name2)7247 sp_name *LEX::make_sp_name(THD *thd, const LEX_CSTRING *name1,
7248                                      const LEX_CSTRING *name2)
7249 {
7250   sp_name *res;
7251   LEX_CSTRING norm_name1;
7252   if (unlikely(!name1->str) ||
7253       unlikely(!thd->make_lex_string(&norm_name1, name1->str,
7254                                      name1->length)) ||
7255       unlikely(check_db_name((LEX_STRING *) &norm_name1)))
7256   {
7257     my_error(ER_WRONG_DB_NAME, MYF(0), name1->str);
7258     return NULL;
7259   }
7260   if (unlikely(check_routine_name(name2)) ||
7261       unlikely(!(res= new (thd->mem_root) sp_name(&norm_name1, name2, true))))
7262     return NULL;
7263   return res;
7264 }
7265 
7266 
make_sp_head(THD * thd,const sp_name * name,const Sp_handler * sph,enum_sp_aggregate_type agg_type)7267 sp_head *LEX::make_sp_head(THD *thd, const sp_name *name,
7268                            const Sp_handler *sph,
7269                            enum_sp_aggregate_type agg_type)
7270 {
7271   sp_package *package= get_sp_package();
7272   sp_head *sp;
7273 
7274   /* Order is important here: new - reset - init */
7275   if (likely((sp= sp_head::create(package, sph, agg_type))))
7276   {
7277     sp->reset_thd_mem_root(thd);
7278     sp->init(this);
7279     if (name)
7280     {
7281       if (package)
7282         sp->make_package_routine_name(sp->get_main_mem_root(),
7283                                       package->m_db,
7284                                       package->m_name,
7285                                       name->m_name);
7286       else
7287         sp->init_sp_name(name);
7288       sp->make_qname(sp->get_main_mem_root(), &sp->m_qname);
7289     }
7290     sphead= sp;
7291   }
7292   sp_chistics.init();
7293   return sp;
7294 }
7295 
7296 
make_sp_head_no_recursive(THD * thd,const sp_name * name,const Sp_handler * sph,enum_sp_aggregate_type agg_type)7297 sp_head *LEX::make_sp_head_no_recursive(THD *thd, const sp_name *name,
7298                                         const Sp_handler *sph,
7299                                         enum_sp_aggregate_type agg_type)
7300 {
7301   sp_package *package= thd->lex->get_sp_package();
7302   /*
7303     Sp_handler::sp_clone_and_link_routine() generates a standalone-alike
7304     statement to clone package routines for recursion, e.g.:
7305       CREATE PROCEDURE p1 AS BEGIN NULL; END;
7306     Translate a standalone routine handler to the corresponding
7307     package routine handler if we're cloning a package routine, e.g.:
7308       sp_handler_procedure -> sp_handler_package_procedure
7309       sp_handler_function  -> sp_handler_package_function
7310   */
7311   if (package && package->m_is_cloning_routine)
7312     sph= sph->package_routine_handler();
7313   if (!sphead ||
7314       (package &&
7315        (sph == &sp_handler_package_procedure ||
7316         sph == &sp_handler_package_function)))
7317     return make_sp_head(thd, name, sph, agg_type);
7318   my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), sph->type_str());
7319   return NULL;
7320 }
7321 
7322 
sp_body_finalize_routine(THD * thd)7323 bool LEX::sp_body_finalize_routine(THD *thd)
7324 {
7325   if (sphead->check_unresolved_goto())
7326     return true;
7327   sphead->set_stmt_end(thd);
7328   sphead->restore_thd_mem_root(thd);
7329   return false;
7330 }
7331 
7332 
sp_body_finalize_procedure(THD * thd)7333 bool LEX::sp_body_finalize_procedure(THD *thd)
7334 {
7335   return sphead->check_group_aggregate_instructions_forbid() ||
7336          sp_body_finalize_routine(thd);
7337 }
7338 
7339 
sp_body_finalize_procedure_standalone(THD * thd,const sp_name * end_name)7340 bool LEX::sp_body_finalize_procedure_standalone(THD *thd,
7341                                                 const sp_name *end_name)
7342 {
7343   return sp_body_finalize_procedure(thd) ||
7344          sphead->check_standalone_routine_end_name(end_name);
7345 }
7346 
7347 
sp_body_finalize_function(THD * thd)7348 bool LEX::sp_body_finalize_function(THD *thd)
7349 {
7350   if (sphead->is_not_allowed_in_function("function") ||
7351       sphead->check_group_aggregate_instructions_function())
7352     return true;
7353   if (!(sphead->m_flags & sp_head::HAS_RETURN))
7354   {
7355     my_error(ER_SP_NORETURN, MYF(0), ErrConvDQName(sphead).ptr());
7356     return true;
7357   }
7358   if (sp_body_finalize_routine(thd))
7359     return true;
7360   (void) is_native_function_with_warn(thd, &sphead->m_name);
7361   return false;
7362 }
7363 
7364 
sp_body_finalize_trigger(THD * thd)7365 bool LEX::sp_body_finalize_trigger(THD *thd)
7366 {
7367   return sphead->is_not_allowed_in_function("trigger") ||
7368          sp_body_finalize_procedure(thd);
7369 }
7370 
7371 
sp_body_finalize_event(THD * thd)7372 bool LEX::sp_body_finalize_event(THD *thd)
7373 {
7374   event_parse_data->body_changed= true;
7375   return sp_body_finalize_procedure(thd);
7376 }
7377 
7378 
stmt_create_stored_function_finalize_standalone(const sp_name * end_name)7379 bool LEX::stmt_create_stored_function_finalize_standalone(const sp_name *end_name)
7380 {
7381   if (sphead->check_standalone_routine_end_name(end_name))
7382     return true;
7383   stmt_create_routine_finalize();
7384   return false;
7385 }
7386 
7387 
sp_block_with_exceptions_finalize_declarations(THD * thd)7388 bool LEX::sp_block_with_exceptions_finalize_declarations(THD *thd)
7389 {
7390   /*
7391     [ DECLARE declarations ]
7392     BEGIN executable_section
7393     [ EXCEPTION exceptions ]
7394     END
7395 
7396     We are now at the "BEGIN" keyword.
7397     We have collected all declarations, including DECLARE HANDLER directives.
7398     But there will be possibly more handlers in the EXCEPTION section.
7399 
7400     Generate a forward jump from the end of the DECLARE section to the
7401     beginning of the EXCEPTION section, over the executable section.
7402   */
7403   return sphead->add_instr_jump(thd, spcont);
7404 }
7405 
7406 
7407 bool
sp_block_with_exceptions_finalize_executable_section(THD * thd,uint executable_section_ip)7408 LEX::sp_block_with_exceptions_finalize_executable_section(THD *thd,
7409                                          uint executable_section_ip)
7410 {
7411   /*
7412     We're now at the end of "executable_section" of the block,
7413     near the "EXCEPTION" or the "END" keyword.
7414     Generate a jump to the END of the block over the EXCEPTION section.
7415   */
7416   if (sphead->add_instr_jump_forward_with_backpatch(thd, spcont))
7417     return true;
7418   /*
7419     Set the destination for the jump that we added in
7420     sp_block_with_exceptions_finalize_declarations().
7421   */
7422   sp_instr *instr= sphead->get_instr(executable_section_ip - 1);
7423   instr->backpatch(sphead->instructions(), spcont);
7424   return false;
7425 }
7426 
7427 
7428 bool
sp_block_with_exceptions_finalize_exceptions(THD * thd,uint executable_section_ip,uint exception_count)7429 LEX::sp_block_with_exceptions_finalize_exceptions(THD *thd,
7430                                                   uint executable_section_ip,
7431                                                   uint exception_count)
7432 {
7433   if (!exception_count)
7434   {
7435     /*
7436       The jump from the end of DECLARE section to
7437       the beginning of the EXCEPTION section that we added in
7438       sp_block_with_exceptions_finalize_declarations() is useless
7439       if there were no exceptions.
7440       Replace it to "no operation".
7441     */
7442     return sphead->replace_instr_to_nop(thd, executable_section_ip - 1);
7443   }
7444   /*
7445     Generate a jump from the end of the EXCEPTION code
7446     to the executable section.
7447   */
7448   return sphead->add_instr_jump(thd, spcont, executable_section_ip);
7449 }
7450 
7451 
sp_block_with_exceptions_add_empty(THD * thd)7452 bool LEX::sp_block_with_exceptions_add_empty(THD *thd)
7453 {
7454   uint ip= sphead->instructions();
7455   return sp_block_with_exceptions_finalize_executable_section(thd, ip) ||
7456          sp_block_with_exceptions_finalize_exceptions(thd, ip, 0);
7457 }
7458 
7459 
sp_change_context(THD * thd,const sp_pcontext * ctx,bool exclusive)7460 bool LEX::sp_change_context(THD *thd, const sp_pcontext *ctx, bool exclusive)
7461 {
7462   uint n;
7463   uint ip= sphead->instructions();
7464   if ((n= spcont->diff_handlers(ctx, exclusive)))
7465   {
7466     sp_instr_hpop *hpop= new (thd->mem_root) sp_instr_hpop(ip++, spcont, n);
7467     if (unlikely(hpop == NULL) || unlikely(sphead->add_instr(hpop)))
7468       return true;
7469   }
7470   if ((n= spcont->diff_cursors(ctx, exclusive)))
7471   {
7472     sp_instr_cpop *cpop= new (thd->mem_root) sp_instr_cpop(ip++, spcont, n);
7473     if (unlikely(cpop == NULL) || unlikely(sphead->add_instr(cpop)))
7474       return true;
7475   }
7476   return false;
7477 }
7478 
7479 
sp_leave_statement(THD * thd,const LEX_CSTRING * label_name)7480 bool LEX::sp_leave_statement(THD *thd, const LEX_CSTRING *label_name)
7481 {
7482   sp_label *lab= spcont->find_label(label_name);
7483   if (unlikely(!lab))
7484   {
7485     my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "LEAVE", label_name->str);
7486     return true;
7487   }
7488   return sp_exit_block(thd, lab, NULL);
7489 }
7490 
sp_goto_statement(THD * thd,const LEX_CSTRING * label_name)7491 bool LEX::sp_goto_statement(THD *thd, const LEX_CSTRING *label_name)
7492 {
7493   sp_label *lab= spcont->find_goto_label(label_name);
7494   if (!lab || lab->ip == 0)
7495   {
7496     sp_label *delayedlabel;
7497     if (!lab)
7498     {
7499       // Label not found --> add forward jump to an unknown label
7500       spcont->push_goto_label(thd, label_name, 0, sp_label::GOTO);
7501       delayedlabel= spcont->last_goto_label();
7502     }
7503     else
7504     {
7505       delayedlabel= lab;
7506     }
7507     return sphead->push_backpatch_goto(thd, spcont, delayedlabel);
7508   }
7509   else
7510   {
7511     // Label found (backward goto)
7512     return sp_change_context(thd, lab->ctx, false) ||
7513            sphead->add_instr_jump(thd, spcont, lab->ip); /* Jump back */
7514   }
7515   return false;
7516 }
7517 
sp_push_goto_label(THD * thd,const LEX_CSTRING * label_name)7518 bool LEX::sp_push_goto_label(THD *thd, const LEX_CSTRING *label_name)
7519 {
7520   sp_label *lab= spcont->find_goto_label(label_name, false);
7521   if (lab)
7522   {
7523     if (unlikely(lab->ip != 0))
7524     {
7525       my_error(ER_SP_LABEL_REDEFINE, MYF(0), label_name->str);
7526       return true;
7527     }
7528     lab->ip= sphead->instructions();
7529 
7530     sp_label *beginblocklabel= spcont->find_label(&empty_clex_str);
7531     sphead->backpatch_goto(thd, lab, beginblocklabel);
7532   }
7533   else
7534   {
7535     spcont->push_goto_label(thd, label_name, sphead->instructions());
7536   }
7537   return false;
7538 }
7539 
sp_exit_block(THD * thd,sp_label * lab)7540 bool LEX::sp_exit_block(THD *thd, sp_label *lab)
7541 {
7542   /*
7543     When jumping to a BEGIN-END block end, the target jump
7544     points to the block hpop/cpop cleanup instructions,
7545     so we should exclude the block context here.
7546     When jumping to something else (i.e., SP_LAB_ITER),
7547     there are no hpop/cpop at the jump destination,
7548     so we should include the block context here for cleanup.
7549   */
7550   bool exclusive= (lab->type == sp_label::BEGIN);
7551   return sp_change_context(thd, lab->ctx, exclusive) ||
7552          sphead->add_instr_jump_forward_with_backpatch(thd, spcont, lab);
7553 }
7554 
7555 
sp_exit_block(THD * thd,sp_label * lab,Item * when)7556 bool LEX::sp_exit_block(THD *thd, sp_label *lab, Item *when)
7557 {
7558   if (!when)
7559     return sp_exit_block(thd, lab);
7560 
7561   DBUG_ASSERT(sphead == thd->lex->sphead);
7562   DBUG_ASSERT(spcont == thd->lex->spcont);
7563   sp_instr_jump_if_not *i= new (thd->mem_root)
7564                            sp_instr_jump_if_not(sphead->instructions(),
7565                                                 spcont,
7566                                                 when, this);
7567   if (unlikely(i == NULL) ||
7568       unlikely(sphead->add_instr(i)) ||
7569       unlikely(sp_exit_block(thd, lab)))
7570     return true;
7571   i->backpatch(sphead->instructions(), spcont);
7572   return false;
7573 }
7574 
7575 
sp_exit_statement(THD * thd,Item * item)7576 bool LEX::sp_exit_statement(THD *thd, Item *item)
7577 {
7578   sp_label *lab= spcont->find_label_current_loop_start();
7579   if (unlikely(!lab))
7580   {
7581     my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "EXIT", "");
7582     return true;
7583   }
7584   DBUG_ASSERT(lab->type == sp_label::ITERATION);
7585   return sp_exit_block(thd, lab, item);
7586 }
7587 
7588 
sp_exit_statement(THD * thd,const LEX_CSTRING * label_name,Item * item)7589 bool LEX::sp_exit_statement(THD *thd, const LEX_CSTRING *label_name, Item *item)
7590 {
7591   sp_label *lab= spcont->find_label(label_name);
7592   if (unlikely(!lab || lab->type != sp_label::ITERATION))
7593   {
7594     my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "EXIT", label_name->str);
7595     return true;
7596   }
7597   return sp_exit_block(thd, lab, item);
7598 }
7599 
7600 
sp_iterate_statement(THD * thd,const LEX_CSTRING * label_name)7601 bool LEX::sp_iterate_statement(THD *thd, const LEX_CSTRING *label_name)
7602 {
7603   sp_label *lab= spcont->find_label(label_name);
7604   if (unlikely(!lab || lab->type != sp_label::ITERATION))
7605   {
7606     my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "ITERATE", label_name->str);
7607     return true;
7608   }
7609   return sp_continue_loop(thd, lab);
7610 }
7611 
7612 
sp_continue_loop(THD * thd,sp_label * lab)7613 bool LEX::sp_continue_loop(THD *thd, sp_label *lab)
7614 {
7615   if (lab->ctx->for_loop().m_index)
7616   {
7617     // We're in a FOR loop, increment the index variable before backward jump
7618     sphead->reset_lex(thd);
7619     DBUG_ASSERT(this != thd->lex);
7620     if (thd->lex->sp_for_loop_increment(thd, lab->ctx->for_loop()) ||
7621         thd->lex->sphead->restore_lex(thd))
7622       return true;
7623   }
7624   return sp_change_context(thd, lab->ctx, false) ||
7625          sphead->add_instr_jump(thd, spcont, lab->ip); /* Jump back */
7626 }
7627 
7628 
sp_continue_statement(THD * thd)7629 bool LEX::sp_continue_statement(THD *thd)
7630 {
7631   sp_label *lab= spcont->find_label_current_loop_start();
7632   if (unlikely(!lab))
7633   {
7634     my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "CONTINUE", "");
7635     return true;
7636   }
7637   DBUG_ASSERT(lab->type == sp_label::ITERATION);
7638   return sp_continue_loop(thd, lab);
7639 }
7640 
7641 
sp_continue_statement(THD * thd,const LEX_CSTRING * label_name)7642 bool LEX::sp_continue_statement(THD *thd, const LEX_CSTRING *label_name)
7643 {
7644   sp_label *lab= spcont->find_label(label_name);
7645   if (!lab || lab->type != sp_label::ITERATION)
7646   {
7647     my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "CONTINUE", label_name->str);
7648     return true;
7649   }
7650   return sp_continue_loop(thd, lab);
7651 }
7652 
7653 
sp_continue_loop(THD * thd,sp_label * lab,Item * when)7654 bool LEX::sp_continue_loop(THD *thd, sp_label *lab, Item *when)
7655 {
7656   DBUG_ASSERT(when);
7657   DBUG_ASSERT(sphead == thd->lex->sphead);
7658   DBUG_ASSERT(spcont == thd->lex->spcont);
7659   sp_instr_jump_if_not *i= new (thd->mem_root)
7660                            sp_instr_jump_if_not(sphead->instructions(),
7661                                                 spcont,
7662                                                 when, this);
7663   if (unlikely(i == NULL) ||
7664       unlikely(sphead->add_instr(i)) ||
7665       unlikely(sp_continue_loop(thd, lab)))
7666     return true;
7667   i->backpatch(sphead->instructions(), spcont);
7668   return false;
7669 }
7670 
7671 
sp_continue_when_statement(THD * thd)7672 bool sp_expr_lex::sp_continue_when_statement(THD *thd)
7673 {
7674   sp_label *lab= spcont->find_label_current_loop_start();
7675   if (unlikely(!lab))
7676   {
7677     my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "CONTINUE", "");
7678     return true;
7679   }
7680   DBUG_ASSERT(lab->type == sp_label::ITERATION);
7681   return sp_continue_loop(thd, lab, get_item());
7682 }
7683 
7684 
sp_continue_when_statement(THD * thd,const LEX_CSTRING * label_name)7685 bool sp_expr_lex::sp_continue_when_statement(THD *thd,
7686                                              const LEX_CSTRING *label_name)
7687 {
7688   sp_label *lab= spcont->find_label(label_name);
7689   if (!lab || lab->type != sp_label::ITERATION)
7690   {
7691     my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "CONTINUE", label_name->str);
7692     return true;
7693   }
7694   return sp_continue_loop(thd, lab, get_item());
7695 }
7696 
7697 
maybe_start_compound_statement(THD * thd)7698 bool LEX::maybe_start_compound_statement(THD *thd)
7699 {
7700   if (!sphead)
7701   {
7702     if (!make_sp_head(thd, NULL, &sp_handler_procedure, DEFAULT_AGGREGATE))
7703       return true;
7704     sphead->set_suid(SP_IS_NOT_SUID);
7705     sphead->set_body_start(thd, thd->m_parser_state->m_lip.get_cpp_ptr());
7706   }
7707   return false;
7708 }
7709 
7710 
sp_push_loop_label(THD * thd,const LEX_CSTRING * label_name)7711 bool LEX::sp_push_loop_label(THD *thd, const LEX_CSTRING *label_name)
7712 {
7713   sp_label *lab= spcont->find_label(label_name);
7714   if (lab)
7715   {
7716     my_error(ER_SP_LABEL_REDEFINE, MYF(0), label_name->str);
7717     return true;
7718   }
7719   spcont->push_label(thd, label_name, sphead->instructions(),
7720                      sp_label::ITERATION);
7721   return false;
7722 }
7723 
7724 
sp_push_loop_empty_label(THD * thd)7725 bool LEX::sp_push_loop_empty_label(THD *thd)
7726 {
7727   if (maybe_start_compound_statement(thd))
7728     return true;
7729   /* Unlabeled controls get an empty label. */
7730   spcont->push_label(thd, &empty_clex_str, sphead->instructions(),
7731                      sp_label::ITERATION);
7732   return false;
7733 }
7734 
7735 
sp_pop_loop_label(THD * thd,const LEX_CSTRING * label_name)7736 bool LEX::sp_pop_loop_label(THD *thd, const LEX_CSTRING *label_name)
7737 {
7738   sp_label *lab= spcont->pop_label();
7739   sphead->backpatch(lab);
7740   if (label_name->str &&
7741       lex_string_cmp(system_charset_info, label_name,
7742                      &lab->name) != 0)
7743   {
7744     my_error(ER_SP_LABEL_MISMATCH, MYF(0), label_name->str);
7745     return true;
7746   }
7747   return false;
7748 }
7749 
7750 
sp_pop_loop_empty_label(THD * thd)7751 void LEX::sp_pop_loop_empty_label(THD *thd)
7752 {
7753   sp_label *lab= spcont->pop_label();
7754   sphead->backpatch(lab);
7755   DBUG_ASSERT(lab->name.length == 0);
7756 }
7757 
7758 
sp_while_loop_expression(THD * thd,Item * item)7759 bool LEX::sp_while_loop_expression(THD *thd, Item *item)
7760 {
7761   sp_instr_jump_if_not *i= new (thd->mem_root)
7762     sp_instr_jump_if_not(sphead->instructions(), spcont, item, this);
7763   return (unlikely(i == NULL) ||
7764           /* Jumping forward */
7765           unlikely(sphead->push_backpatch(thd, i, spcont->last_label())) ||
7766           unlikely(sphead->new_cont_backpatch(i)) ||
7767           unlikely(sphead->add_instr(i)));
7768 }
7769 
7770 
sp_while_loop_finalize(THD * thd)7771 bool LEX::sp_while_loop_finalize(THD *thd)
7772 {
7773   sp_label *lab= spcont->last_label();  /* Jumping back */
7774   sp_instr_jump *i= new (thd->mem_root)
7775     sp_instr_jump(sphead->instructions(), spcont, lab->ip);
7776   if (unlikely(i == NULL) ||
7777       unlikely(sphead->add_instr(i)))
7778     return true;
7779   sphead->do_cont_backpatch();
7780   return false;
7781 }
7782 
7783 
create_and_link_Item_trigger_field(THD * thd,const LEX_CSTRING * name,bool new_row)7784 Item *LEX::create_and_link_Item_trigger_field(THD *thd,
7785                                               const LEX_CSTRING *name,
7786                                               bool new_row)
7787 {
7788   Item_trigger_field *trg_fld;
7789 
7790   if (unlikely(trg_chistics.event == TRG_EVENT_INSERT && !new_row))
7791   {
7792     my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "OLD", "on INSERT");
7793     return NULL;
7794   }
7795 
7796   if (unlikely(trg_chistics.event == TRG_EVENT_DELETE && new_row))
7797   {
7798     my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "NEW", "on DELETE");
7799     return NULL;
7800   }
7801 
7802   DBUG_ASSERT(!new_row ||
7803               (trg_chistics.event == TRG_EVENT_INSERT ||
7804                trg_chistics.event == TRG_EVENT_UPDATE));
7805 
7806   const bool tmp_read_only=
7807     !(new_row && trg_chistics.action_time == TRG_ACTION_BEFORE);
7808   trg_fld= new (thd->mem_root)
7809              Item_trigger_field(thd, current_context(),
7810                                 new_row ?
7811                                   Item_trigger_field::NEW_ROW:
7812                                   Item_trigger_field::OLD_ROW,
7813                                 *name, SELECT_ACL, tmp_read_only);
7814   /*
7815     Let us add this item to list of all Item_trigger_field objects
7816     in trigger.
7817   */
7818   if (likely(trg_fld))
7819     trg_table_fields.link_in_list(trg_fld, &trg_fld->next_trg_field);
7820 
7821   return trg_fld;
7822 }
7823 
7824 
make_item_colon_ident_ident(THD * thd,const Lex_ident_cli_st * ca,const Lex_ident_cli_st * cb)7825 Item *LEX::make_item_colon_ident_ident(THD *thd,
7826                                        const Lex_ident_cli_st *ca,
7827                                        const Lex_ident_cli_st *cb)
7828 {
7829   Lex_ident_sys a(thd, ca), b(thd, cb);
7830   if (a.is_null() || b.is_null())
7831     return NULL; // OEM
7832   if (!is_trigger_new_or_old_reference(&a))
7833   {
7834     thd->parse_error();
7835     return NULL;
7836   }
7837   bool new_row= (a.str[0] == 'N' || a.str[0] == 'n');
7838   return create_and_link_Item_trigger_field(thd, &b, new_row);
7839 }
7840 
7841 
make_item_plsql_cursor_attr(THD * thd,const LEX_CSTRING * name,plsql_cursor_attr_t attr)7842 Item *LEX::make_item_plsql_cursor_attr(THD *thd, const LEX_CSTRING *name,
7843                                        plsql_cursor_attr_t attr)
7844 {
7845   uint offset;
7846   if (unlikely(!spcont || !spcont->find_cursor(name, &offset, false)))
7847   {
7848     my_error(ER_SP_CURSOR_MISMATCH, MYF(0), name->str);
7849     return NULL;
7850   }
7851   switch (attr) {
7852   case PLSQL_CURSOR_ATTR_ISOPEN:
7853     return new (thd->mem_root) Item_func_cursor_isopen(thd, name, offset);
7854   case PLSQL_CURSOR_ATTR_FOUND:
7855     return new (thd->mem_root) Item_func_cursor_found(thd, name, offset);
7856   case PLSQL_CURSOR_ATTR_NOTFOUND:
7857     return new (thd->mem_root) Item_func_cursor_notfound(thd, name, offset);
7858   case PLSQL_CURSOR_ATTR_ROWCOUNT:
7859     return new (thd->mem_root) Item_func_cursor_rowcount(thd, name, offset);
7860   }
7861   DBUG_ASSERT(0);
7862   return NULL;
7863 }
7864 
7865 
make_item_sysvar(THD * thd,enum_var_type type,const LEX_CSTRING * name,const LEX_CSTRING * component)7866 Item *LEX::make_item_sysvar(THD *thd,
7867                             enum_var_type type,
7868                             const LEX_CSTRING *name,
7869                             const LEX_CSTRING *component)
7870 
7871 {
7872   Item *item;
7873   DBUG_ASSERT(name->str);
7874   /*
7875     "SELECT @@global.global.variable" is not allowed
7876     Note, "global" can come through TEXT_STRING_sys.
7877   */
7878   if (component->str && unlikely(check_reserved_words(name)))
7879   {
7880     thd->parse_error();
7881     return NULL;
7882   }
7883   if (unlikely(!(item= get_system_var(thd, type, name, component))))
7884     return NULL;
7885   if (!((Item_func_get_system_var*) item)->is_written_to_binlog())
7886     set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE);
7887   return item;
7888 }
7889 
7890 
param_push_or_clone(THD * thd,LEX * lex,Item_param * item)7891 static bool param_push_or_clone(THD *thd, LEX *lex, Item_param *item)
7892 {
7893   return !lex->clone_spec_offset ?
7894          lex->param_list.push_back(item, thd->mem_root) :
7895          item->add_as_clone(thd);
7896 }
7897 
7898 
add_placeholder(THD * thd,const LEX_CSTRING * name,const char * start,const char * end)7899 Item_param *LEX::add_placeholder(THD *thd, const LEX_CSTRING *name,
7900                                  const char *start, const char *end)
7901 {
7902   if (unlikely(!thd->m_parser_state->m_lip.stmt_prepare_mode))
7903   {
7904     thd->parse_error(ER_SYNTAX_ERROR, start);
7905     return NULL;
7906   }
7907   if (unlikely(!parsing_options.allows_variable))
7908   {
7909     my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
7910     return NULL;
7911   }
7912   Query_fragment pos(thd, sphead, start, end);
7913   Item_param *item= new (thd->mem_root) Item_param(thd, name,
7914                                                    pos.pos(), pos.length());
7915   if (unlikely(!item) || unlikely(param_push_or_clone(thd, this, item)))
7916   {
7917     my_error(ER_OUT_OF_RESOURCES, MYF(0));
7918     return NULL;
7919   }
7920   return item;
7921 }
7922 
7923 
add_signal_statement(THD * thd,const sp_condition_value * v)7924 bool LEX::add_signal_statement(THD *thd, const sp_condition_value *v)
7925 {
7926   Yacc_state *state= &thd->m_parser_state->m_yacc;
7927   sql_command= SQLCOM_SIGNAL;
7928   m_sql_cmd= new (thd->mem_root) Sql_cmd_signal(v, state->m_set_signal_info);
7929   return m_sql_cmd == NULL;
7930 }
7931 
7932 
add_resignal_statement(THD * thd,const sp_condition_value * v)7933 bool LEX::add_resignal_statement(THD *thd, const sp_condition_value *v)
7934 {
7935   Yacc_state *state= &thd->m_parser_state->m_yacc;
7936   sql_command= SQLCOM_RESIGNAL;
7937   m_sql_cmd= new (thd->mem_root) Sql_cmd_resignal(v, state->m_set_signal_info);
7938   return m_sql_cmd == NULL;
7939 }
7940 
7941 
7942 /*
7943   Make an Item when an identifier is found in the FOR loop bounds:
7944     FOR rec IN cursor
7945     FOR var IN var1 .. xxx
7946     FOR var IN row1.field1 .. xxx
7947   When we parse the first expression after the "IN" keyword,
7948   we don't know yet if it's a cursor name, or a scalar SP variable name,
7949   or a field of a ROW SP variable. Here we create Item_field to remember
7950   the fully qualified name. Later sp_for_loop_cursor_declarations()
7951   detects how to treat this name properly.
7952 */
create_item_for_loop_bound(THD * thd,const LEX_CSTRING * a,const LEX_CSTRING * b,const LEX_CSTRING * c)7953 Item *LEX::create_item_for_loop_bound(THD *thd,
7954                                       const LEX_CSTRING *a,
7955                                       const LEX_CSTRING *b,
7956                                       const LEX_CSTRING *c)
7957 {
7958   /*
7959     Pass NULL as the name resolution context.
7960     This is OK, fix_fields() won't be called for this Item_field.
7961   */
7962   return new (thd->mem_root) Item_field(thd, NULL, *a, *b, *c);
7963 }
7964 
7965 
check_expr_allows_fields_or_error(THD * thd,const char * name) const7966 bool LEX::check_expr_allows_fields_or_error(THD *thd, const char *name) const
7967 {
7968   if (select_stack_top > 0)
7969     return false; // OK, fields are allowed
7970   my_error(ER_BAD_FIELD_ERROR, MYF(0), name, thd->where);
7971   return true;    // Error, fields are not allowed
7972 }
7973 
create_item_ident_nospvar(THD * thd,const Lex_ident_sys_st * a,const Lex_ident_sys_st * b)7974 Item *LEX::create_item_ident_nospvar(THD *thd,
7975                                      const Lex_ident_sys_st *a,
7976                                      const Lex_ident_sys_st *b)
7977 {
7978   DBUG_ASSERT(this == thd->lex);
7979   /*
7980     FIXME This will work ok in simple_ident_nospvar case because
7981     we can't meet simple_ident_nospvar in trigger now. But it
7982     should be changed in future.
7983   */
7984   if (is_trigger_new_or_old_reference(a))
7985   {
7986     bool new_row= (a->str[0]=='N' || a->str[0]=='n');
7987 
7988     return create_and_link_Item_trigger_field(thd, b, new_row);
7989   }
7990 
7991   if (unlikely(current_select->no_table_names_allowed))
7992   {
7993     my_error(ER_TABLENAME_NOT_ALLOWED_HERE, MYF(0), a->str, thd->where);
7994     return NULL;
7995   }
7996 
7997   if (current_select->parsing_place == FOR_LOOP_BOUND)
7998     return create_item_for_loop_bound(thd, &null_clex_str, a, b);
7999 
8000   return create_item_ident_field(thd, Lex_ident_sys(), *a, *b);
8001 }
8002 
8003 
create_item_spvar_row_field(THD * thd,const Sp_rcontext_handler * rh,const Lex_ident_sys * a,const Lex_ident_sys * b,sp_variable * spv,const char * start,const char * end)8004 Item_splocal *LEX::create_item_spvar_row_field(THD *thd,
8005                                                const Sp_rcontext_handler *rh,
8006                                                const Lex_ident_sys *a,
8007                                                const Lex_ident_sys *b,
8008                                                sp_variable *spv,
8009                                                const char *start,
8010                                                const char *end)
8011 {
8012   if (unlikely(!parsing_options.allows_variable))
8013   {
8014     my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
8015     return NULL;
8016   }
8017 
8018   Query_fragment pos(thd, sphead, start, end);
8019   Item_splocal *item;
8020   if (spv->field_def.is_table_rowtype_ref() ||
8021       spv->field_def.is_cursor_rowtype_ref())
8022   {
8023     if (unlikely(!(item= new (thd->mem_root)
8024                    Item_splocal_row_field_by_name(thd, rh, a, b, spv->offset,
8025                                                   &type_handler_null,
8026                                                   pos.pos(), pos.length()))))
8027       return NULL;
8028   }
8029   else
8030   {
8031     uint row_field_offset;
8032     const Spvar_definition *def;
8033     if (unlikely(!(def= spv->find_row_field(a, b, &row_field_offset))))
8034       return NULL;
8035 
8036     if (unlikely(!(item= new (thd->mem_root)
8037                    Item_splocal_row_field(thd, rh, a, b,
8038                                           spv->offset, row_field_offset,
8039                                           def->type_handler(),
8040                                           pos.pos(), pos.length()))))
8041       return NULL;
8042   }
8043 #ifdef DBUG_ASSERT_EXISTS
8044   item->m_sp= sphead;
8045 #endif
8046   safe_to_cache_query=0;
8047   return item;
8048 }
8049 
8050 
create_outvar(THD * thd,const LEX_CSTRING * name)8051 my_var *LEX::create_outvar(THD *thd, const LEX_CSTRING *name)
8052 {
8053   const Sp_rcontext_handler *rh;
8054   sp_variable *spv;
8055   if (likely((spv= find_variable(name, &rh))))
8056     return result ? new (thd->mem_root)
8057                     my_var_sp(rh, name, spv->offset,
8058                               spv->type_handler(), sphead) :
8059                     NULL /* EXPLAIN */;
8060   my_error(ER_SP_UNDECLARED_VAR, MYF(0), name->str);
8061   return NULL;
8062 }
8063 
8064 
create_outvar(THD * thd,const LEX_CSTRING * a,const LEX_CSTRING * b)8065 my_var *LEX::create_outvar(THD *thd,
8066                            const LEX_CSTRING *a,
8067                            const LEX_CSTRING *b)
8068 {
8069   const Sp_rcontext_handler *rh;
8070   sp_variable *t;
8071   if (unlikely(!(t= find_variable(a, &rh))))
8072   {
8073     my_error(ER_SP_UNDECLARED_VAR, MYF(0), a->str);
8074     return NULL;
8075   }
8076   uint row_field_offset;
8077   if (!t->find_row_field(a, b, &row_field_offset))
8078     return NULL;
8079   return result ?
8080     new (thd->mem_root) my_var_sp_row_field(rh, a, b, t->offset,
8081                                             row_field_offset, sphead) :
8082     NULL /* EXPLAIN */;
8083 }
8084 
8085 
create_item_func_nextval(THD * thd,Table_ident * table_ident)8086 Item *LEX::create_item_func_nextval(THD *thd, Table_ident *table_ident)
8087 {
8088   TABLE_LIST *table;
8089   if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
8090                                                           TL_OPTION_SEQUENCE,
8091                                                           TL_WRITE_ALLOW_WRITE,
8092                                                           MDL_SHARED_WRITE))))
8093     return NULL;
8094   thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8095   return new (thd->mem_root) Item_func_nextval(thd, table);
8096 }
8097 
8098 
create_item_func_lastval(THD * thd,Table_ident * table_ident)8099 Item *LEX::create_item_func_lastval(THD *thd, Table_ident *table_ident)
8100 {
8101   TABLE_LIST *table;
8102   if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
8103                                                           TL_OPTION_SEQUENCE,
8104                                                           TL_READ,
8105                                                           MDL_SHARED_READ))))
8106     return NULL;
8107   thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8108   return new (thd->mem_root) Item_func_lastval(thd, table);
8109 }
8110 
8111 
create_item_func_nextval(THD * thd,const LEX_CSTRING * db,const LEX_CSTRING * name)8112 Item *LEX::create_item_func_nextval(THD *thd,
8113                                     const LEX_CSTRING *db,
8114                                     const LEX_CSTRING *name)
8115 {
8116   Table_ident *table_ident;
8117   if (unlikely(!(table_ident=
8118                  new (thd->mem_root) Table_ident(thd, db, name, false))))
8119     return NULL;
8120   return create_item_func_nextval(thd, table_ident);
8121 }
8122 
8123 
create_item_func_lastval(THD * thd,const LEX_CSTRING * db,const LEX_CSTRING * name)8124 Item *LEX::create_item_func_lastval(THD *thd,
8125                                     const LEX_CSTRING *db,
8126                                     const LEX_CSTRING *name)
8127 {
8128   Table_ident *table_ident;
8129   if (unlikely(!(table_ident=
8130                  new (thd->mem_root) Table_ident(thd, db, name, false))))
8131     return NULL;
8132   return create_item_func_lastval(thd, table_ident);
8133 }
8134 
8135 
create_item_func_setval(THD * thd,Table_ident * table_ident,longlong nextval,ulonglong round,bool is_used)8136 Item *LEX::create_item_func_setval(THD *thd, Table_ident *table_ident,
8137                                    longlong nextval, ulonglong round,
8138                                    bool is_used)
8139 {
8140   TABLE_LIST *table;
8141   if (unlikely(!(table= current_select->add_table_to_list(thd, table_ident, 0,
8142                                                           TL_OPTION_SEQUENCE,
8143                                                           TL_WRITE_ALLOW_WRITE,
8144                                                           MDL_SHARED_WRITE))))
8145     return NULL;
8146   return new (thd->mem_root) Item_func_setval(thd, table, nextval, round,
8147                                               is_used);
8148 }
8149 
8150 
create_item_ident(THD * thd,const Lex_ident_cli_st * ca,const Lex_ident_cli_st * cb)8151 Item *LEX::create_item_ident(THD *thd,
8152                              const Lex_ident_cli_st *ca,
8153                              const Lex_ident_cli_st *cb)
8154 {
8155   const char *start= ca->pos();
8156   const char *end= cb->end();
8157   const Sp_rcontext_handler *rh;
8158   sp_variable *spv;
8159   DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= start);
8160   DBUG_ASSERT(start <= end);
8161   DBUG_ASSERT(end <= thd->m_parser_state->m_lip.get_end_of_query());
8162   Lex_ident_sys a(thd, ca), b(thd, cb);
8163   if (a.is_null() || b.is_null())
8164     return NULL; // OEM
8165   if ((spv= find_variable(&a, &rh)) &&
8166       (spv->field_def.is_row() ||
8167        spv->field_def.is_table_rowtype_ref() ||
8168        spv->field_def.is_cursor_rowtype_ref()))
8169     return create_item_spvar_row_field(thd, rh, &a, &b, spv, start, end);
8170 
8171   if ((thd->variables.sql_mode & MODE_ORACLE) && b.length == 7)
8172   {
8173     if (!system_charset_info->strnncoll(
8174                       (const uchar *) b.str, 7,
8175                       (const uchar *) "NEXTVAL", 7))
8176       return create_item_func_nextval(thd, &null_clex_str, &a);
8177     else if (!system_charset_info->strnncoll(
8178                           (const uchar *) b.str, 7,
8179                           (const uchar *) "CURRVAL", 7))
8180       return create_item_func_lastval(thd, &null_clex_str, &a);
8181   }
8182 
8183   return create_item_ident_nospvar(thd, &a, &b);
8184 }
8185 
8186 
create_item_ident(THD * thd,const Lex_ident_sys_st * a,const Lex_ident_sys_st * b,const Lex_ident_sys_st * c)8187 Item *LEX::create_item_ident(THD *thd,
8188                              const Lex_ident_sys_st *a,
8189                              const Lex_ident_sys_st *b,
8190                              const Lex_ident_sys_st *c)
8191 {
8192   Lex_ident_sys_st schema= thd->client_capabilities & CLIENT_NO_SCHEMA ?
8193                            Lex_ident_sys() : *a;
8194   if ((thd->variables.sql_mode & MODE_ORACLE) && c->length == 7)
8195   {
8196     if (!system_charset_info->strnncoll(
8197                       (const uchar *) c->str, 7,
8198                       (const uchar *) "NEXTVAL", 7))
8199       return create_item_func_nextval(thd, a, b);
8200     else if (!system_charset_info->strnncoll(
8201                           (const uchar *) c->str, 7,
8202                           (const uchar *) "CURRVAL", 7))
8203       return create_item_func_lastval(thd, a, b);
8204   }
8205 
8206   if (current_select->no_table_names_allowed)
8207   {
8208     my_error(ER_TABLENAME_NOT_ALLOWED_HERE, MYF(0), b->str, thd->where);
8209     return NULL;
8210   }
8211 
8212   if (current_select->parsing_place == FOR_LOOP_BOUND)
8213     return create_item_for_loop_bound(thd, &null_clex_str, b, c);
8214 
8215   return create_item_ident_field(thd, schema, *b, *c);
8216 }
8217 
8218 
create_item_limit(THD * thd,const Lex_ident_cli_st * ca)8219 Item *LEX::create_item_limit(THD *thd, const Lex_ident_cli_st *ca)
8220 {
8221   DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= ca->pos());
8222   DBUG_ASSERT(ca->pos() <= ca->end());
8223   DBUG_ASSERT(ca->end() <= thd->m_parser_state->m_lip.get_end_of_query());
8224 
8225   const Sp_rcontext_handler *rh;
8226   sp_variable *spv;
8227   Lex_ident_sys sa(thd, ca);
8228   if (sa.is_null())
8229     return NULL; // EOM
8230   if (!(spv= find_variable(&sa, &rh)))
8231   {
8232     my_error(ER_SP_UNDECLARED_VAR, MYF(0), sa.str);
8233     return NULL;
8234   }
8235 
8236   Query_fragment pos(thd, sphead, ca->pos(), ca->end());
8237   Item_splocal *item;
8238   if (unlikely(!(item= new (thd->mem_root)
8239                  Item_splocal(thd, rh, &sa,
8240                               spv->offset, spv->type_handler(),
8241                               clone_spec_offset ? 0 : pos.pos(),
8242                               clone_spec_offset ? 0 : pos.length()))))
8243     return NULL;
8244 #ifdef DBUG_ASSERT_EXISTS
8245   item->m_sp= sphead;
8246 #endif
8247   safe_to_cache_query= 0;
8248 
8249   if (!item->is_valid_limit_clause_variable_with_error())
8250     return NULL;
8251 
8252   item->limit_clause_param= true;
8253   return item;
8254 }
8255 
8256 
create_item_limit(THD * thd,const Lex_ident_cli_st * ca,const Lex_ident_cli_st * cb)8257 Item *LEX::create_item_limit(THD *thd,
8258                              const Lex_ident_cli_st *ca,
8259                              const Lex_ident_cli_st *cb)
8260 {
8261   DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= ca->pos());
8262   DBUG_ASSERT(ca->pos() <= cb->end());
8263   DBUG_ASSERT(cb->end() <= thd->m_parser_state->m_lip.get_end_of_query());
8264 
8265   const Sp_rcontext_handler *rh;
8266   sp_variable *spv;
8267   Lex_ident_sys sa(thd, ca), sb(thd, cb);
8268   if (unlikely(sa.is_null() || sb.is_null()))
8269     return NULL; // EOM
8270   if (!(spv= find_variable(&sa, &rh)))
8271   {
8272     my_error(ER_SP_UNDECLARED_VAR, MYF(0), sa.str);
8273     return NULL;
8274   }
8275   // Qualified %TYPE variables are not possible
8276   DBUG_ASSERT(!spv->field_def.column_type_ref());
8277   Item_splocal *item;
8278   if (unlikely(!(item= create_item_spvar_row_field(thd, rh, &sa, &sb, spv,
8279                                                    ca->pos(), cb->end()))))
8280     return NULL;
8281   if (!item->is_valid_limit_clause_variable_with_error())
8282     return NULL;
8283   item->limit_clause_param= true;
8284   return item;
8285 }
8286 
8287 
set_user_variable(THD * thd,const LEX_CSTRING * name,Item * val)8288 bool LEX::set_user_variable(THD *thd, const LEX_CSTRING *name, Item *val)
8289 {
8290   Item_func_set_user_var *item;
8291   set_var_user *var;
8292   if (unlikely(!(item= new (thd->mem_root) Item_func_set_user_var(thd, name,
8293                                                                   val))) ||
8294       unlikely(!(var= new (thd->mem_root) set_var_user(item))))
8295     return true;
8296   if (unlikely(var_list.push_back(var, thd->mem_root)))
8297     return true;
8298   return false;
8299 }
8300 
8301 
create_item_ident_field(THD * thd,const Lex_ident_sys_st & db,const Lex_ident_sys_st & table,const Lex_ident_sys_st & name)8302 Item *LEX::create_item_ident_field(THD *thd,
8303                                    const Lex_ident_sys_st &db,
8304                                    const Lex_ident_sys_st &table,
8305                                    const Lex_ident_sys_st &name)
8306 {
8307   if (check_expr_allows_fields_or_error(thd, name.str))
8308     return NULL;
8309 
8310   if (current_select->parsing_place != IN_HAVING ||
8311       current_select->get_in_sum_expr() > 0)
8312     return new (thd->mem_root) Item_field(thd, current_context(),
8313                                           db, table, name);
8314 
8315   return new (thd->mem_root) Item_ref(thd, current_context(),
8316                                       db, table, name);
8317 }
8318 
8319 
create_item_ident_sp(THD * thd,Lex_ident_sys_st * name,const char * start,const char * end)8320 Item *LEX::create_item_ident_sp(THD *thd, Lex_ident_sys_st *name,
8321                                 const char *start,
8322                                 const char *end)
8323 {
8324   DBUG_ASSERT(thd->m_parser_state->m_lip.get_buf() <= start);
8325   DBUG_ASSERT(start <= end);
8326   DBUG_ASSERT(end <= thd->m_parser_state->m_lip.get_end_of_query());
8327 
8328   const Sp_rcontext_handler *rh;
8329   sp_variable *spv;
8330   uint unused_off;
8331   DBUG_ASSERT(spcont);
8332   DBUG_ASSERT(sphead);
8333   if ((spv= find_variable(name, &rh)))
8334   {
8335     /* We're compiling a stored procedure and found a variable */
8336     if (!parsing_options.allows_variable)
8337     {
8338       my_error(ER_VIEW_SELECT_VARIABLE, MYF(0));
8339       return NULL;
8340     }
8341 
8342     Query_fragment pos(thd, sphead, start, end);
8343     uint f_pos= clone_spec_offset ? 0 : pos.pos();
8344     uint f_length= clone_spec_offset ? 0 : pos.length();
8345     Item_splocal *splocal= spv->field_def.is_column_type_ref() ?
8346       new (thd->mem_root) Item_splocal_with_delayed_data_type(thd, rh, name,
8347                                                               spv->offset,
8348                                                               f_pos, f_length) :
8349       new (thd->mem_root) Item_splocal(thd, rh, name,
8350                                        spv->offset, spv->type_handler(),
8351                                        f_pos, f_length);
8352     if (unlikely(splocal == NULL))
8353       return NULL;
8354 #ifdef DBUG_ASSERT_EXISTS
8355     splocal->m_sp= sphead;
8356 #endif
8357     safe_to_cache_query= 0;
8358     return splocal;
8359   }
8360 
8361   if (thd->variables.sql_mode & MODE_ORACLE)
8362   {
8363     if (lex_string_eq(name, STRING_WITH_LEN("SQLCODE")))
8364       return new (thd->mem_root) Item_func_sqlcode(thd);
8365     if (lex_string_eq(name, STRING_WITH_LEN("SQLERRM")))
8366       return new (thd->mem_root) Item_func_sqlerrm(thd);
8367   }
8368 
8369   if (fields_are_impossible() &&
8370       (current_select->parsing_place != FOR_LOOP_BOUND ||
8371        spcont->find_cursor(name, &unused_off, false) == NULL))
8372   {
8373     // we are out of SELECT or FOR so it is syntax error
8374     my_error(ER_SP_UNDECLARED_VAR, MYF(0), name->str);
8375     return NULL;
8376   }
8377 
8378   if (current_select->parsing_place == FOR_LOOP_BOUND)
8379     return create_item_for_loop_bound(thd, &null_clex_str, &null_clex_str,
8380                                       name);
8381 
8382   return create_item_ident_nosp(thd, name);
8383 }
8384 
8385 
8386 
set_variable(const Lex_ident_sys_st * name,Item * item)8387 bool LEX::set_variable(const Lex_ident_sys_st *name, Item *item)
8388 {
8389   sp_pcontext *ctx;
8390   const Sp_rcontext_handler *rh;
8391   sp_variable *spv= find_variable(name, &ctx, &rh);
8392   return spv ? sphead->set_local_variable(thd, ctx, rh, spv, item, this, true) :
8393                set_system_variable(option_type, name, item);
8394 }
8395 
8396 
8397 /**
8398   Generate instructions for:
8399     SET x.y= expr;
8400 */
set_variable(const Lex_ident_sys_st * name1,const Lex_ident_sys_st * name2,Item * item)8401 bool LEX::set_variable(const Lex_ident_sys_st *name1,
8402                        const Lex_ident_sys_st *name2,
8403                        Item *item)
8404 {
8405   const Sp_rcontext_handler *rh;
8406   sp_pcontext *ctx;
8407   sp_variable *spv;
8408   if (spcont && (spv= find_variable(name1, &ctx, &rh)))
8409   {
8410     if (spv->field_def.is_table_rowtype_ref() ||
8411         spv->field_def.is_cursor_rowtype_ref())
8412       return sphead->set_local_variable_row_field_by_name(thd, ctx,
8413                                                           rh,
8414                                                           spv, name2,
8415                                                           item, this);
8416     // A field of a ROW variable
8417     uint row_field_offset;
8418     return !spv->find_row_field(name1, name2, &row_field_offset) ||
8419            sphead->set_local_variable_row_field(thd, ctx, rh,
8420                                                 spv, row_field_offset,
8421                                                 item, this);
8422   }
8423 
8424   if (is_trigger_new_or_old_reference(name1))
8425     return set_trigger_field(name1, name2, item);
8426 
8427   return set_system_variable(thd, option_type, name1, name2, item);
8428 }
8429 
8430 
set_default_system_variable(enum_var_type var_type,const Lex_ident_sys_st * name,Item * val)8431 bool LEX::set_default_system_variable(enum_var_type var_type,
8432                                       const Lex_ident_sys_st *name,
8433                                       Item *val)
8434 {
8435   static Lex_ident_sys default_base_name= {STRING_WITH_LEN("default")};
8436   sys_var *var= find_sys_var(thd, name->str, name->length);
8437   if (!var)
8438     return true;
8439   if (unlikely(!var->is_struct()))
8440   {
8441     my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), name->str);
8442     return true;
8443   }
8444   return set_system_variable(var_type, var, &default_base_name, val);
8445 }
8446 
8447 
set_system_variable(enum_var_type var_type,const Lex_ident_sys_st * name,Item * val)8448 bool LEX::set_system_variable(enum_var_type var_type,
8449                               const Lex_ident_sys_st *name,
8450                               Item *val)
8451 {
8452   sys_var *var= find_sys_var(thd, name->str, name->length);
8453   DBUG_ASSERT(thd->is_error() || var != NULL);
8454   static Lex_ident_sys null_str;
8455   return likely(var) ? set_system_variable(var_type, var, &null_str, val) : true;
8456 }
8457 
8458 
set_system_variable(THD * thd,enum_var_type var_type,const Lex_ident_sys_st * name1,const Lex_ident_sys_st * name2,Item * val)8459 bool LEX::set_system_variable(THD *thd, enum_var_type var_type,
8460                               const Lex_ident_sys_st *name1,
8461                               const Lex_ident_sys_st *name2,
8462                               Item *val)
8463 {
8464   sys_var *tmp;
8465   if (unlikely(check_reserved_words(name1)) ||
8466       unlikely(!(tmp= find_sys_var(thd, name2->str, name2->length, true))))
8467   {
8468     my_error(ER_UNKNOWN_STRUCTURED_VARIABLE, MYF(0),
8469              (int) name1->length, name1->str);
8470     return true;
8471   }
8472   if (unlikely(!tmp->is_struct()))
8473   {
8474     my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), name2->str);
8475     return true;
8476   }
8477   return set_system_variable(var_type, tmp, name1, val);
8478 }
8479 
8480 
set_trigger_field(const LEX_CSTRING * name1,const LEX_CSTRING * name2,Item * val)8481 bool LEX::set_trigger_field(const LEX_CSTRING *name1, const LEX_CSTRING *name2,
8482                             Item *val)
8483 {
8484   DBUG_ASSERT(is_trigger_new_or_old_reference(name1));
8485   if (unlikely(name1->str[0]=='O' || name1->str[0]=='o'))
8486   {
8487     my_error(ER_TRG_CANT_CHANGE_ROW, MYF(0), "OLD", "");
8488     return true;
8489   }
8490   if (unlikely(trg_chistics.event == TRG_EVENT_DELETE))
8491   {
8492     my_error(ER_TRG_NO_SUCH_ROW_IN_TRG, MYF(0), "NEW", "on DELETE");
8493     return true;
8494   }
8495   if (unlikely(trg_chistics.action_time == TRG_ACTION_AFTER))
8496   {
8497     my_error(ER_TRG_CANT_CHANGE_ROW, MYF(0), "NEW", "after ");
8498     return true;
8499   }
8500   return set_trigger_new_row(name2, val);
8501 }
8502 
8503 
8504 #ifdef MYSQL_SERVER
8505 uint binlog_unsafe_map[256];
8506 
8507 #define UNSAFE(a, b, c) \
8508   { \
8509   DBUG_PRINT("unsafe_mixed_statement", ("SETTING BASE VALUES: %s, %s, %02X", \
8510     LEX::stmt_accessed_table_string(a), \
8511     LEX::stmt_accessed_table_string(b), \
8512     c)); \
8513   unsafe_mixed_statement(a, b, c); \
8514   }
8515 
8516 /*
8517   Sets the combination given by "a" and "b" and automatically combinations
8518   given by other types of access, i.e. 2^(8 - 2), as unsafe.
8519 
8520   It may happen a colision when automatically defining a combination as unsafe.
8521   For that reason, a combination has its unsafe condition redefined only when
8522   the new_condition is greater then the old. For instance,
8523 
8524      . (BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY) is never overwritten by
8525      . (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF).
8526 */
unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,LEX::enum_stmt_accessed_table b,uint condition)8527 void unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,
8528                             LEX::enum_stmt_accessed_table b, uint condition)
8529 {
8530   int type= 0;
8531   int index= (1U << a) | (1U << b);
8532 
8533 
8534   for (type= 0; type < 256; type++)
8535   {
8536     if ((type & index) == index)
8537     {
8538       binlog_unsafe_map[type] |= condition;
8539     }
8540   }
8541 }
8542 /*
8543   The BINLOG_* AND TRX_CACHE_* values can be combined by using '&' or '|',
8544   which means that both conditions need to be satisfied or any of them is
8545   enough. For example,
8546 
8547     . BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY means that the statment is
8548     unsafe when the option is on and trx-cache is not empty;
8549 
8550     . BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF means the statement is unsafe
8551     in all cases.
8552 
8553     . TRX_CACHE_EMPTY | TRX_CACHE_NOT_EMPTY means the statement is unsafe
8554     in all cases. Similar as above.
8555 */
binlog_unsafe_map_init()8556 void binlog_unsafe_map_init()
8557 {
8558   memset((void*) binlog_unsafe_map, 0, sizeof(uint) * 256);
8559 
8560   /*
8561     Classify a statement as unsafe when there is a mixed statement and an
8562     on-going transaction at any point of the execution if:
8563 
8564       1. The mixed statement is about to update a transactional table and
8565       a non-transactional table.
8566 
8567       2. The mixed statement is about to update a transactional table and
8568       read from a non-transactional table.
8569 
8570       3. The mixed statement is about to update a non-transactional table
8571       and temporary transactional table.
8572 
8573       4. The mixed statement is about to update a temporary transactional
8574       table and read from a non-transactional table.
8575 
8576       5. The mixed statement is about to update a transactional table and
8577       a temporary non-transactional table.
8578 
8579       6. The mixed statement is about to update a transactional table and
8580       read from a temporary non-transactional table.
8581 
8582       7. The mixed statement is about to update a temporary transactional
8583       table and temporary non-transactional table.
8584 
8585       8. The mixed statement is about to update a temporary transactional
8586       table and read from a temporary non-transactional table.
8587 
8588     After updating a transactional table if:
8589 
8590       9. The mixed statement is about to update a non-transactional table
8591       and read from a transactional table.
8592 
8593       10. The mixed statement is about to update a non-transactional table
8594       and read from a temporary transactional table.
8595 
8596       11. The mixed statement is about to update a temporary non-transactional
8597       table and read from a transactional table.
8598 
8599       12. The mixed statement is about to update a temporary non-transactional
8600       table and read from a temporary transactional table.
8601 
8602       13. The mixed statement is about to update a temporary non-transactional
8603       table and read from a non-transactional table.
8604 
8605     The reason for this is that locks acquired may not protected a concurrent
8606     transaction of interfering in the current execution and by consequence in
8607     the result.
8608   */
8609   /* Case 1. */
8610   UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_NON_TRANS_TABLE,
8611     BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
8612   /* Case 2. */
8613   UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
8614     BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
8615   /* Case 3. */
8616   UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_WRITES_TEMP_TRANS_TABLE,
8617     BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
8618   /* Case 4. */
8619   UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
8620     BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
8621   /* Case 5. */
8622   UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
8623     BINLOG_DIRECT_ON);
8624   /* Case 6. */
8625   UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
8626     BINLOG_DIRECT_ON);
8627   /* Case 7. */
8628   UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
8629     BINLOG_DIRECT_ON);
8630   /* Case 8. */
8631   UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
8632     BINLOG_DIRECT_ON);
8633   /* Case 9. */
8634   UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
8635     (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
8636   /* Case 10 */
8637   UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
8638     (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
8639   /* Case 11. */
8640   UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
8641     BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
8642   /* Case 12. */
8643   UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
8644     BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
8645   /* Case 13. */
8646   UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
8647      BINLOG_DIRECT_OFF & TRX_CACHE_NOT_EMPTY);
8648 }
8649 #endif
8650 
8651 
8652 /**
8653   @brief
8654     Collect fiels that are used in the GROUP BY of this st_select_lex
8655 
8656   @param thd  The thread handle
8657 
8658   @details
8659     This method looks through the fields that are used in the GROUP BY of this
8660     st_select_lex and saves info on these fields.
8661 */
8662 
collect_grouping_fields_for_derived(THD * thd,ORDER * grouping_list)8663 void st_select_lex::collect_grouping_fields_for_derived(THD *thd,
8664                                                         ORDER *grouping_list)
8665 {
8666   grouping_tmp_fields.empty();
8667   List_iterator<Item> li(join->fields_list);
8668   Item *item= li++;
8669   for (uint i= 0; i < master_unit()->derived->table->s->fields;
8670        i++, (item=li++))
8671   {
8672     for (ORDER *ord= grouping_list; ord; ord= ord->next)
8673     {
8674       if ((*ord->item)->eq((Item*)item, 0))
8675       {
8676         Field_pair *grouping_tmp_field=
8677           new Field_pair(master_unit()->derived->table->field[i], item);
8678         grouping_tmp_fields.push_back(grouping_tmp_field);
8679       }
8680     }
8681   }
8682 }
8683 
8684 
8685 /**
8686   Collect fields that are used in the GROUP BY of this SELECT
8687 */
8688 
collect_grouping_fields(THD * thd)8689 bool st_select_lex::collect_grouping_fields(THD *thd)
8690 {
8691   grouping_tmp_fields.empty();
8692 
8693   for (ORDER *ord= group_list.first; ord; ord= ord->next)
8694   {
8695     Item *item= *ord->item;
8696     if (item->type() != Item::FIELD_ITEM &&
8697         !(item->type() == Item::REF_ITEM &&
8698           item->real_type() == Item::FIELD_ITEM &&
8699           ((((Item_ref *) item)->ref_type() == Item_ref::VIEW_REF) ||
8700            (((Item_ref *) item)->ref_type() == Item_ref::REF))))
8701       continue;
8702 
8703     Field_pair *grouping_tmp_field=
8704       new Field_pair(((Item_field *)item->real_item())->field, item);
8705     if (grouping_tmp_fields.push_back(grouping_tmp_field, thd->mem_root))
8706       return false;
8707   }
8708   if (grouping_tmp_fields.elements)
8709     return false;
8710   return true;
8711 }
8712 
8713 
8714 /**
8715   @brief
8716    For a condition check possibility of exraction a formula over grouping fields
8717 
8718   @param thd      The thread handle
8719   @param cond     The condition whose subformulas are to be analyzed
8720   @param checker  The checker callback function to be applied to the nodes
8721                   of the tree of the object
8722 
8723   @details
8724     This method traverses the AND-OR condition cond and for each subformula of
8725     the condition it checks whether it can be usable for the extraction of a
8726     condition over the grouping fields of this select. The method uses
8727     the call-back parameter checker to check whether a primary formula
8728     depends only on grouping fields.
8729     The subformulas that are not usable are marked with the flag NO_EXTRACTION_FL.
8730     The subformulas that can be entierly extracted are marked with the flag
8731     FULL_EXTRACTION_FL.
8732   @note
8733     This method is called before any call of extract_cond_for_grouping_fields.
8734     The flag NO_EXTRACTION_FL set in a subformula allows to avoid building clone
8735     for the subformula when extracting the pushable condition.
8736     The flag FULL_EXTRACTION_FL allows to delete later all top level conjuncts
8737     from cond.
8738 */
8739 
8740 void
check_cond_extraction_for_grouping_fields(THD * thd,Item * cond)8741 st_select_lex::check_cond_extraction_for_grouping_fields(THD *thd, Item *cond)
8742 {
8743   if (cond->get_extraction_flag() == NO_EXTRACTION_FL)
8744     return;
8745   cond->clear_extraction_flag();
8746   if (cond->type() == Item::COND_ITEM)
8747   {
8748     Item_cond_and *and_cond=
8749       (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC) ?
8750       ((Item_cond_and*) cond) : 0;
8751 
8752     List<Item> *arg_list=  ((Item_cond*) cond)->argument_list();
8753     List_iterator<Item> li(*arg_list);
8754     uint count= 0;         // to count items not containing NO_EXTRACTION_FL
8755     uint count_full= 0;    // to count items with FULL_EXTRACTION_FL
8756     Item *item;
8757     while ((item=li++))
8758     {
8759       check_cond_extraction_for_grouping_fields(thd, item);
8760       if (item->get_extraction_flag() !=  NO_EXTRACTION_FL)
8761       {
8762         count++;
8763         if (item->get_extraction_flag() == FULL_EXTRACTION_FL)
8764           count_full++;
8765       }
8766       else if (!and_cond)
8767         break;
8768     }
8769     if ((and_cond && count == 0) || item)
8770       cond->set_extraction_flag(NO_EXTRACTION_FL);
8771     if (count_full == arg_list->elements)
8772     {
8773       cond->set_extraction_flag(FULL_EXTRACTION_FL);
8774     }
8775     if (cond->get_extraction_flag() != 0)
8776     {
8777       li.rewind();
8778       while ((item=li++))
8779         item->clear_extraction_flag();
8780     }
8781   }
8782   else
8783   {
8784     int fl= cond->excl_dep_on_grouping_fields(this) && !cond->is_expensive() ?
8785       FULL_EXTRACTION_FL : NO_EXTRACTION_FL;
8786     cond->set_extraction_flag(fl);
8787   }
8788 }
8789 
8790 
8791 /**
8792   @brief
8793   Build condition extractable from the given one depended on grouping fields
8794 
8795   @param thd           The thread handle
8796   @param cond          The condition from which the condition depended
8797                        on grouping fields is to be extracted
8798   @param no_top_clones If it's true then no clones for the top fully
8799                        extractable conjuncts are built
8800 
8801   @details
8802     For the given condition cond this method finds out what condition depended
8803     only on the grouping fields can be extracted from cond. If such condition C
8804     exists the method builds the item for it.
8805     This method uses the flags NO_EXTRACTION_FL and FULL_EXTRACTION_FL set by the
8806     preliminary call of st_select_lex::check_cond_extraction_for_grouping_fields
8807     to figure out whether a subformula depends only on these fields or not.
8808   @note
8809     The built condition C is always implied by the condition cond
8810     (cond => C). The method tries to build the least restictive such
8811     condition (i.e. for any other condition C' such that cond => C'
8812     we have C => C').
8813   @note
8814     The build item is not ready for usage: substitution for the field items
8815     has to be done and it has to be re-fixed.
8816 
8817   @retval
8818     the built condition depended only on grouping fields if such a condition exists
8819     NULL if there is no such a condition
8820 */
8821 
build_cond_for_grouping_fields(THD * thd,Item * cond,bool no_top_clones)8822 Item *st_select_lex::build_cond_for_grouping_fields(THD *thd, Item *cond,
8823                                                     bool no_top_clones)
8824 {
8825   if (cond->get_extraction_flag() == FULL_EXTRACTION_FL)
8826   {
8827     if (no_top_clones)
8828       return cond;
8829     cond->clear_extraction_flag();
8830     return cond->build_clone(thd);
8831   }
8832   if (cond->type() == Item::COND_ITEM)
8833   {
8834     bool cond_and= false;
8835     Item_cond *new_cond;
8836     if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
8837     {
8838       cond_and= true;
8839       new_cond=  new (thd->mem_root) Item_cond_and(thd);
8840     }
8841     else
8842       new_cond= new (thd->mem_root) Item_cond_or(thd);
8843     if (unlikely(!new_cond))
8844       return 0;
8845     List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
8846     Item *item;
8847     while ((item=li++))
8848     {
8849       if (item->get_extraction_flag() == NO_EXTRACTION_FL)
8850       {
8851         DBUG_ASSERT(cond_and);
8852         item->clear_extraction_flag();
8853         continue;
8854       }
8855       Item *fix= build_cond_for_grouping_fields(thd, item,
8856                                                 no_top_clones & cond_and);
8857       if (unlikely(!fix))
8858       {
8859         if (cond_and)
8860           continue;
8861         break;
8862       }
8863       new_cond->argument_list()->push_back(fix, thd->mem_root);
8864     }
8865 
8866     if (!cond_and && item)
8867     {
8868       while((item= li++))
8869         item->clear_extraction_flag();
8870       return 0;
8871     }
8872     switch (new_cond->argument_list()->elements)
8873     {
8874     case 0:
8875       return 0;
8876     case 1:
8877       return new_cond->argument_list()->head();
8878     default:
8879       return new_cond;
8880     }
8881   }
8882   return 0;
8883 }
8884 
8885 
set_nest_level(int new_nest_level)8886 bool st_select_lex::set_nest_level(int new_nest_level)
8887 {
8888   DBUG_ENTER("st_select_lex::set_nest_level");
8889   DBUG_PRINT("enter", ("select #%d %p nest level: %d",
8890                        select_number, this, new_nest_level));
8891   if (new_nest_level > (int) MAX_SELECT_NESTING)
8892   {
8893     my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT, MYF(0));
8894     DBUG_RETURN(TRUE);
8895   }
8896   nest_level= new_nest_level;
8897   new_nest_level++;
8898   for (SELECT_LEX_UNIT *u= first_inner_unit(); u; u= u->next_unit())
8899   {
8900     if (u->set_nest_level(new_nest_level))
8901       DBUG_RETURN(TRUE);
8902   }
8903   DBUG_RETURN(FALSE);
8904 }
8905 
set_nest_level(int new_nest_level)8906 bool st_select_lex_unit::set_nest_level(int new_nest_level)
8907 {
8908   DBUG_ENTER("st_select_lex_unit::set_nest_level");
8909   for(SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
8910   {
8911     if (sl->set_nest_level(new_nest_level))
8912       DBUG_RETURN(TRUE);
8913   }
8914   if (fake_select_lex &&
8915       fake_select_lex->set_nest_level(new_nest_level))
8916     DBUG_RETURN(TRUE);
8917   DBUG_RETURN(FALSE);
8918 }
8919 
8920 
check_parameters(SELECT_LEX * main_select)8921 bool st_select_lex::check_parameters(SELECT_LEX *main_select)
8922 {
8923   DBUG_ENTER("st_select_lex::check_parameters");
8924   DBUG_PRINT("enter", ("select #%d %p nest level: %d",
8925                        select_number, this, nest_level));
8926 
8927 
8928   if ((options & OPTION_PROCEDURE_CLAUSE) &&
8929       (!parent_lex->selects_allow_procedure ||
8930         next_select() != NULL ||
8931         this != master_unit()->first_select() ||
8932         nest_level != 0))
8933   {
8934     my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "PROCEDURE");
8935     DBUG_RETURN(TRUE);
8936   }
8937 
8938   if ((options & SELECT_HIGH_PRIORITY) && this != main_select)
8939   {
8940     my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "HIGH_PRIORITY");
8941     DBUG_RETURN(TRUE);
8942   }
8943   if ((options & OPTION_BUFFER_RESULT) && this != main_select)
8944   {
8945     my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_BUFFER_RESULT");
8946     DBUG_RETURN(TRUE);
8947   }
8948   if ((options & OPTION_FOUND_ROWS) && this != main_select)
8949   {
8950     my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_CALC_FOUND_ROWS");
8951     DBUG_RETURN(TRUE);
8952   }
8953   if (options & OPTION_NO_QUERY_CACHE)
8954   {
8955     /*
8956       Allow this flag only on the first top-level SELECT statement, if
8957       SQL_CACHE wasn't specified.
8958     */
8959     if (this != main_select)
8960     {
8961       my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_NO_CACHE");
8962       DBUG_RETURN(TRUE);
8963     }
8964     if (parent_lex->sql_cache == LEX::SQL_CACHE)
8965     {
8966       my_error(ER_WRONG_USAGE, MYF(0), "SQL_CACHE", "SQL_NO_CACHE");
8967       DBUG_RETURN(TRUE);
8968     }
8969     parent_lex->safe_to_cache_query=0;
8970     parent_lex->sql_cache= LEX::SQL_NO_CACHE;
8971   }
8972   if (options & OPTION_TO_QUERY_CACHE)
8973   {
8974     /*
8975       Allow this flag only on the first top-level SELECT statement, if
8976       SQL_NO_CACHE wasn't specified.
8977     */
8978     if (this != main_select)
8979     {
8980       my_error(ER_CANT_USE_OPTION_HERE, MYF(0), "SQL_CACHE");
8981       DBUG_RETURN(TRUE);
8982     }
8983     if (parent_lex->sql_cache == LEX::SQL_NO_CACHE)
8984     {
8985       my_error(ER_WRONG_USAGE, MYF(0), "SQL_NO_CACHE", "SQL_CACHE");
8986       DBUG_RETURN(TRUE);
8987     }
8988     parent_lex->safe_to_cache_query=1;
8989     parent_lex->sql_cache= LEX::SQL_CACHE;
8990   }
8991 
8992   for (SELECT_LEX_UNIT *u= first_inner_unit(); u; u= u->next_unit())
8993   {
8994     if (u->check_parameters(main_select))
8995       DBUG_RETURN(TRUE);
8996   }
8997   DBUG_RETURN(FALSE);
8998 }
8999 
9000 
check_parameters(SELECT_LEX * main_select)9001 bool st_select_lex_unit::check_parameters(SELECT_LEX *main_select)
9002 {
9003   for(SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
9004   {
9005     if (sl->check_parameters(main_select))
9006       return TRUE;
9007   }
9008   return fake_select_lex && fake_select_lex->check_parameters(main_select);
9009 }
9010 
9011 
check_main_unit_semantics()9012 bool LEX::check_main_unit_semantics()
9013 {
9014   if (unit.set_nest_level(0) ||
9015       unit.check_parameters(first_select_lex()))
9016     return TRUE;
9017   if (check_cte_dependencies_and_resolve_references())
9018     return TRUE;
9019   return FALSE;
9020 }
9021 
set_statement_var_if_exists(THD * thd,const char * var_name,size_t var_name_length,ulonglong value)9022 int set_statement_var_if_exists(THD *thd, const char *var_name,
9023                                 size_t var_name_length, ulonglong value)
9024 {
9025   sys_var *sysvar;
9026   if (unlikely(thd->lex->sql_command == SQLCOM_CREATE_VIEW))
9027   {
9028     my_error(ER_VIEW_SELECT_CLAUSE, MYF(0), "[NO]WAIT");
9029     return 1;
9030   }
9031   if (unlikely(thd->lex->sphead))
9032   {
9033     my_error(ER_SP_BADSTATEMENT, MYF(0), "[NO]WAIT");
9034     return 1;
9035   }
9036   if ((sysvar= find_sys_var(thd, var_name, var_name_length, true)))
9037   {
9038     Item *item= new (thd->mem_root) Item_uint(thd, value);
9039     set_var *var= new (thd->mem_root) set_var(thd, OPT_SESSION, sysvar,
9040                                               &null_clex_str, item);
9041 
9042     if (unlikely(!item) || unlikely(!var) ||
9043         unlikely(thd->lex->stmt_var_list.push_back(var, thd->mem_root)))
9044     {
9045       my_error(ER_OUT_OF_RESOURCES, MYF(0));
9046       return 1;
9047     }
9048   }
9049   return 0;
9050 }
9051 
9052 
sp_add_cfetch(THD * thd,const LEX_CSTRING * name)9053 bool LEX::sp_add_cfetch(THD *thd, const LEX_CSTRING *name)
9054 {
9055   uint offset;
9056   sp_instr_cfetch *i;
9057 
9058   if (!spcont->find_cursor(name, &offset, false))
9059   {
9060     my_error(ER_SP_CURSOR_MISMATCH, MYF(0), name->str);
9061     return true;
9062   }
9063   i= new (thd->mem_root)
9064     sp_instr_cfetch(sphead->instructions(), spcont, offset,
9065                     !(thd->variables.sql_mode & MODE_ORACLE));
9066   if (unlikely(i == NULL) || unlikely(sphead->add_instr(i)))
9067     return true;
9068   return false;
9069 }
9070 
9071 
sp_add_agg_cfetch()9072 bool LEX::sp_add_agg_cfetch()
9073 {
9074   sphead->m_flags|= sp_head::HAS_AGGREGATE_INSTR;
9075   sp_instr_agg_cfetch *i=
9076     new (thd->mem_root) sp_instr_agg_cfetch(sphead->instructions(), spcont);
9077   return i == NULL || sphead->add_instr(i);
9078 }
9079 
9080 
create_or_alter_view_finalize(THD * thd,Table_ident * table_ident)9081 bool LEX::create_or_alter_view_finalize(THD *thd, Table_ident *table_ident)
9082 {
9083   sql_command= SQLCOM_CREATE_VIEW;
9084   /* first table in list is target VIEW name */
9085   if (!first_select_lex()->add_table_to_list(thd, table_ident, NULL,
9086                                              TL_OPTION_UPDATING,
9087                                              TL_IGNORE,
9088                                              MDL_EXCLUSIVE))
9089     return true;
9090   query_tables->open_strategy= TABLE_LIST::OPEN_STUB;
9091   return false;
9092 }
9093 
9094 
add_alter_view(THD * thd,uint16 algorithm,enum_view_suid suid,Table_ident * table_ident)9095 bool LEX::add_alter_view(THD *thd, uint16 algorithm,
9096                          enum_view_suid suid,
9097                          Table_ident *table_ident)
9098 {
9099   if (unlikely(sphead))
9100   {
9101     my_error(ER_SP_BADSTATEMENT, MYF(0), "ALTER VIEW");
9102     return true;
9103   }
9104   if (unlikely(!(create_view= new (thd->mem_root)
9105                  Create_view_info(VIEW_ALTER, algorithm, suid))))
9106     return true;
9107   return create_or_alter_view_finalize(thd, table_ident);
9108 }
9109 
9110 
add_create_view(THD * thd,DDL_options_st ddl,uint16 algorithm,enum_view_suid suid,Table_ident * table_ident)9111 bool LEX::add_create_view(THD *thd, DDL_options_st ddl,
9112                           uint16 algorithm, enum_view_suid suid,
9113                           Table_ident *table_ident)
9114 {
9115   if (unlikely(set_create_options_with_check(ddl)))
9116     return true;
9117   if (unlikely(!(create_view= new (thd->mem_root)
9118                  Create_view_info(ddl.or_replace() ?
9119                                   VIEW_CREATE_OR_REPLACE :
9120                                   VIEW_CREATE_NEW,
9121                                   algorithm, suid))))
9122     return true;
9123   return create_or_alter_view_finalize(thd, table_ident);
9124 }
9125 
9126 
call_statement_start(THD * thd,sp_name * name)9127 bool LEX::call_statement_start(THD *thd, sp_name *name)
9128 {
9129   Database_qualified_name pkgname(&null_clex_str, &null_clex_str);
9130   const Sp_handler *sph= &sp_handler_procedure;
9131   sql_command= SQLCOM_CALL;
9132   value_list.empty();
9133   if (unlikely(sph->sp_resolve_package_routine(thd, thd->lex->sphead,
9134                                                name, &sph, &pkgname)))
9135     return true;
9136   if (unlikely(!(m_sql_cmd= new (thd->mem_root) Sql_cmd_call(name, sph))))
9137     return true;
9138   sph->add_used_routine(this, thd, name);
9139   if (pkgname.m_name.length)
9140     sp_handler_package_body.add_used_routine(this, thd, &pkgname);
9141   return false;
9142 }
9143 
9144 
call_statement_start(THD * thd,const Lex_ident_sys_st * name)9145 bool LEX::call_statement_start(THD *thd, const Lex_ident_sys_st *name)
9146 {
9147   sp_name *spname= make_sp_name(thd, name);
9148   return unlikely(!spname) || call_statement_start(thd, spname);
9149 }
9150 
9151 
call_statement_start(THD * thd,const Lex_ident_sys_st * name1,const Lex_ident_sys_st * name2)9152 bool LEX::call_statement_start(THD *thd, const Lex_ident_sys_st *name1,
9153                                          const Lex_ident_sys_st *name2)
9154 {
9155   sp_name *spname= make_sp_name(thd, name1, name2);
9156   return unlikely(!spname) || call_statement_start(thd, spname);
9157 }
9158 
9159 
get_sp_package() const9160 sp_package *LEX::get_sp_package() const
9161 {
9162   return sphead ? sphead->get_package() : NULL;
9163 }
9164 
9165 
create_package_start(THD * thd,enum_sql_command command,const Sp_handler * sph,const sp_name * name_arg,DDL_options_st options)9166 sp_package *LEX::create_package_start(THD *thd,
9167                                       enum_sql_command command,
9168                                       const Sp_handler *sph,
9169                                       const sp_name *name_arg,
9170                                       DDL_options_st options)
9171 {
9172   sp_package *pkg;
9173 
9174   if (unlikely(sphead))
9175   {
9176     my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), sph->type_str());
9177     return NULL;
9178   }
9179   if (unlikely(set_command_with_check(command, options)))
9180     return NULL;
9181   if (sph->type() == SP_TYPE_PACKAGE_BODY)
9182   {
9183     /*
9184       If we start parsing a "CREATE PACKAGE BODY", we need to load
9185       the corresponding "CREATE PACKAGE", for the following reasons:
9186       1. "CREATE PACKAGE BODY" is allowed only if "CREATE PACKAGE"
9187          was done earlier for the same package name.
9188          So if "CREATE PACKAGE" does not exist, we throw an error here.
9189       2. When parsing "CREATE PACKAGE BODY", we need to know all package
9190          public and private routine names, to translate procedure and
9191          function calls correctly.
9192          For example, this statement inside a package routine:
9193            CALL p;
9194          can be translated to:
9195            CALL db.pkg.p; -- p is a known (public or private) package routine
9196            CALL db.p;     -- p is not a known package routine
9197     */
9198     sp_head *spec;
9199     int ret= sp_handler_package_spec.
9200                sp_cache_routine_reentrant(thd, name_arg, &spec);
9201     if (unlikely(!spec))
9202     {
9203       if (!ret)
9204         my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
9205                  "PACKAGE", ErrConvDQName(name_arg).ptr());
9206       return 0;
9207     }
9208   }
9209   if (unlikely(!(pkg= sp_package::create(this, name_arg, sph))))
9210     return NULL;
9211   pkg->reset_thd_mem_root(thd);
9212   pkg->init(this);
9213   pkg->make_qname(pkg->get_main_mem_root(), &pkg->m_qname);
9214   sphead= pkg;
9215   return pkg;
9216 }
9217 
9218 
create_package_finalize(THD * thd,const sp_name * name,const sp_name * name2,const char * body_start,const char * body_end)9219 bool LEX::create_package_finalize(THD *thd,
9220                                   const sp_name *name,
9221                                   const sp_name *name2,
9222                                   const char *body_start,
9223                                   const char *body_end)
9224 {
9225   if (name2 &&
9226       (name2->m_explicit_name != name->m_explicit_name ||
9227        strcmp(name2->m_db.str, name->m_db.str) ||
9228        !Sp_handler::eq_routine_name(name2->m_name, name->m_name)))
9229   {
9230     bool exp= name2->m_explicit_name || name->m_explicit_name;
9231     my_error(ER_END_IDENTIFIER_DOES_NOT_MATCH, MYF(0),
9232              exp ? ErrConvDQName(name2).ptr() : name2->m_name.str,
9233              exp ? ErrConvDQName(name).ptr() : name->m_name.str);
9234     return true;
9235   }
9236   // TODO: reuse code in LEX::create_package_finalize and sp_head::set_stmt_end
9237   sphead->m_body.length= body_end - body_start;
9238   if (unlikely(!(sphead->m_body.str= thd->strmake(body_start,
9239                                                   sphead->m_body.length))))
9240     return true;
9241 
9242   size_t not_used;
9243   Lex_input_stream *lip= & thd->m_parser_state->m_lip;
9244   sphead->m_defstr.length= lip->get_cpp_ptr() - lip->get_cpp_buf();
9245   sphead->m_defstr.str= thd->strmake(lip->get_cpp_buf(), sphead->m_defstr.length);
9246   trim_whitespace(thd->charset(), &sphead->m_defstr, &not_used);
9247 
9248   sphead->restore_thd_mem_root(thd);
9249   sp_package *pkg= sphead->get_package();
9250   DBUG_ASSERT(pkg);
9251   return sphead->check_group_aggregate_instructions_forbid() ||
9252          pkg->validate_after_parser(thd);
9253 }
9254 
9255 
add_grant_command(THD * thd,const List<LEX_COLUMN> & columns)9256 bool LEX::add_grant_command(THD *thd, const List<LEX_COLUMN> &columns)
9257 {
9258   if (columns.elements)
9259   {
9260     thd->parse_error();
9261     return true;
9262   }
9263   return false;
9264 }
9265 
9266 
make_item_func_substr(THD * thd,Item * a,Item * b,Item * c)9267 Item *LEX::make_item_func_substr(THD *thd, Item *a, Item *b, Item *c)
9268 {
9269   return (thd->variables.sql_mode & MODE_ORACLE) ?
9270     new (thd->mem_root) Item_func_substr_oracle(thd, a, b, c) :
9271     new (thd->mem_root) Item_func_substr(thd, a, b, c);
9272 }
9273 
9274 
make_item_func_substr(THD * thd,Item * a,Item * b)9275 Item *LEX::make_item_func_substr(THD *thd, Item *a, Item *b)
9276 {
9277   return (thd->variables.sql_mode & MODE_ORACLE) ?
9278     new (thd->mem_root) Item_func_substr_oracle(thd, a, b) :
9279     new (thd->mem_root) Item_func_substr(thd, a, b);
9280 }
9281 
9282 
make_item_func_replace(THD * thd,Item * org,Item * find,Item * replace)9283 Item *LEX::make_item_func_replace(THD *thd,
9284                                   Item *org,
9285                                   Item *find,
9286                                   Item *replace)
9287 {
9288   return (thd->variables.sql_mode & MODE_ORACLE) ?
9289     new (thd->mem_root) Item_func_replace_oracle(thd, org, find, replace) :
9290     new (thd->mem_root) Item_func_replace(thd, org, find, replace);
9291 }
9292 
9293 
vers_push_field(THD * thd,TABLE_LIST * table,const LEX_CSTRING field_name)9294 bool SELECT_LEX::vers_push_field(THD *thd, TABLE_LIST *table,
9295                                  const LEX_CSTRING field_name)
9296 {
9297   DBUG_ASSERT(field_name.str);
9298   Item_field *fld= new (thd->mem_root) Item_field(thd, &context,
9299                                                   table->db,
9300                                                   table->alias,
9301                                                   field_name);
9302   if (unlikely(!fld) || unlikely(item_list.push_back(fld)))
9303     return true;
9304 
9305   if (thd->lex->view_list.elements)
9306   {
9307     LEX_CSTRING *l;
9308     if (unlikely(!(l= thd->make_clex_string(field_name.str,
9309                                             field_name.length))) ||
9310         unlikely(thd->lex->view_list.push_back(l)))
9311       return true;
9312   }
9313 
9314   return false;
9315 }
9316 
9317 
make_item_func_trim_std(THD * thd) const9318 Item *Lex_trim_st::make_item_func_trim_std(THD *thd) const
9319 {
9320   if (m_remove)
9321   {
9322     switch (m_spec) {
9323     case TRIM_BOTH:
9324       return new (thd->mem_root) Item_func_trim(thd, m_source, m_remove);
9325     case TRIM_LEADING:
9326       return new (thd->mem_root) Item_func_ltrim(thd, m_source, m_remove);
9327     case TRIM_TRAILING:
9328      return new (thd->mem_root) Item_func_rtrim(thd, m_source, m_remove);
9329     }
9330   }
9331 
9332   switch (m_spec) {
9333   case TRIM_BOTH:
9334     return new (thd->mem_root) Item_func_trim(thd, m_source);
9335   case TRIM_LEADING:
9336     return new (thd->mem_root) Item_func_ltrim(thd, m_source);
9337   case TRIM_TRAILING:
9338    return new (thd->mem_root) Item_func_rtrim(thd, m_source);
9339   }
9340   DBUG_ASSERT(0);
9341   return NULL;
9342 }
9343 
9344 
make_item_func_trim_oracle(THD * thd) const9345 Item *Lex_trim_st::make_item_func_trim_oracle(THD *thd) const
9346 {
9347   if (m_remove)
9348   {
9349     switch (m_spec) {
9350     case TRIM_BOTH:
9351       return new (thd->mem_root) Item_func_trim_oracle(thd, m_source, m_remove);
9352     case TRIM_LEADING:
9353       return new (thd->mem_root) Item_func_ltrim_oracle(thd, m_source, m_remove);
9354     case TRIM_TRAILING:
9355      return new (thd->mem_root) Item_func_rtrim_oracle(thd, m_source, m_remove);
9356     }
9357   }
9358 
9359   switch (m_spec) {
9360   case TRIM_BOTH:
9361     return new (thd->mem_root) Item_func_trim_oracle(thd, m_source);
9362   case TRIM_LEADING:
9363     return new (thd->mem_root) Item_func_ltrim_oracle(thd, m_source);
9364   case TRIM_TRAILING:
9365    return new (thd->mem_root) Item_func_rtrim_oracle(thd, m_source);
9366   }
9367   DBUG_ASSERT(0);
9368   return NULL;
9369 }
9370 
9371 
make_item_func_trim(THD * thd) const9372 Item *Lex_trim_st::make_item_func_trim(THD *thd) const
9373 {
9374   return (thd->variables.sql_mode & MODE_ORACLE) ?
9375          make_item_func_trim_oracle(thd) :
9376          make_item_func_trim_std(thd);
9377 }
9378 
9379 
make_item_func_call_generic(THD * thd,Lex_ident_cli_st * cdb,Lex_ident_cli_st * cname,List<Item> * args)9380 Item *LEX::make_item_func_call_generic(THD *thd, Lex_ident_cli_st *cdb,
9381                                        Lex_ident_cli_st *cname, List<Item> *args)
9382 {
9383   Lex_ident_sys db(thd, cdb), name(thd, cname);
9384   if (db.is_null() || name.is_null())
9385     return NULL; // EOM
9386   /*
9387     The following in practice calls:
9388     <code>Create_sp_func::create()</code>
9389     and builds a stored function.
9390 
9391     However, it's important to maintain the interface between the
9392     parser and the implementation in item_create.cc clean,
9393     since this will change with WL#2128 (SQL PATH):
9394     - INFORMATION_SCHEMA.version() is the SQL 99 syntax for the native
9395     function version(),
9396     - MySQL.version() is the SQL 2003 syntax for the native function
9397     version() (a vendor can specify any schema).
9398   */
9399 
9400   if (!name.str || check_db_name((LEX_STRING*) static_cast<LEX_CSTRING*>(&db)))
9401   {
9402     my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
9403     return NULL;
9404   }
9405   if (check_routine_name(&name))
9406     return NULL;
9407 
9408   Create_qfunc *builder= find_qualified_function_builder(thd);
9409   DBUG_ASSERT(builder);
9410   return builder->create_with_db(thd, &db, &name, true, args);
9411 }
9412 
9413 
make_item_func_call_native_or_parse_error(THD * thd,Lex_ident_cli_st & name,List<Item> * args)9414 Item *LEX::make_item_func_call_native_or_parse_error(THD *thd,
9415                                                      Lex_ident_cli_st &name,
9416                                                      List<Item> *args)
9417 {
9418   Create_func *builder= find_native_function_builder(thd, &name);
9419   DBUG_EXECUTE_IF("make_item_func_call_native_simulate_not_found",
9420                   builder= NULL;);
9421   if (builder)
9422     return builder->create_func(thd, &name, args);
9423   thd->parse_error(ER_SYNTAX_ERROR, name.end());
9424   return NULL;
9425 }
9426 
9427 
create_item_qualified_asterisk(THD * thd,const Lex_ident_sys_st * name)9428 Item *LEX::create_item_qualified_asterisk(THD *thd,
9429                                           const Lex_ident_sys_st *name)
9430 {
9431   Item *item;
9432   if (!(item= new (thd->mem_root) Item_field(thd, current_context(),
9433                                              null_clex_str, *name,
9434                                              star_clex_str)))
9435     return NULL;
9436   current_select->with_wild++;
9437   return item;
9438 }
9439 
9440 
create_item_qualified_asterisk(THD * thd,const Lex_ident_sys_st * a,const Lex_ident_sys_st * b)9441 Item *LEX::create_item_qualified_asterisk(THD *thd,
9442                                           const Lex_ident_sys_st *a,
9443                                           const Lex_ident_sys_st *b)
9444 {
9445   Item *item;
9446   Lex_ident_sys_st schema= thd->client_capabilities & CLIENT_NO_SCHEMA ?
9447                            Lex_ident_sys() : *a;
9448   if (!(item= new (thd->mem_root) Item_field(thd, current_context(),
9449                                              schema, *b, star_clex_str)))
9450    return NULL;
9451   current_select->with_wild++;
9452   return item;
9453 }
9454 
9455 
copy_ident_cli(THD * thd,const Lex_ident_cli_st * str)9456 bool Lex_ident_sys_st::copy_ident_cli(THD *thd, const Lex_ident_cli_st *str)
9457 {
9458   return thd->to_ident_sys_alloc(this, str);
9459 }
9460 
copy_keyword(THD * thd,const Lex_ident_cli_st * str)9461 bool Lex_ident_sys_st::copy_keyword(THD *thd, const Lex_ident_cli_st *str)
9462 {
9463   return thd->make_lex_string(static_cast<LEX_CSTRING*>(this),
9464                               str->str, str->length) == NULL;
9465 }
9466 
copy_or_convert(THD * thd,const Lex_ident_cli_st * src,CHARSET_INFO * cs)9467 bool Lex_ident_sys_st::copy_or_convert(THD *thd,
9468                                        const Lex_ident_cli_st *src,
9469                                        CHARSET_INFO *cs)
9470 {
9471   if (!src->is_8bit())
9472     return copy_keyword(thd, src); // 7bit string makes a wellformed identifier
9473   return convert(thd, src, cs);
9474 }
9475 
9476 
copy_sys(THD * thd,const LEX_CSTRING * src)9477 bool Lex_ident_sys_st::copy_sys(THD *thd, const LEX_CSTRING *src)
9478 {
9479   if (thd->check_string_for_wellformedness(src->str, src->length,
9480                                            system_charset_info))
9481     return true;
9482   return thd->make_lex_string(this, src->str, src->length) == NULL;
9483 }
9484 
9485 
convert(THD * thd,const LEX_CSTRING * src,CHARSET_INFO * cs)9486 bool Lex_ident_sys_st::convert(THD *thd,
9487                                const LEX_CSTRING *src, CHARSET_INFO *cs)
9488 {
9489   LEX_STRING tmp;
9490   if (thd->convert_with_error(system_charset_info, &tmp, cs,
9491                               src->str, src->length))
9492     return true;
9493   str=    tmp.str;
9494   length= tmp.length;
9495   return false;
9496 }
9497 
9498 
to_size_number(ulonglong * to) const9499 bool Lex_ident_sys_st::to_size_number(ulonglong *to) const
9500 {
9501   ulonglong number;
9502   uint text_shift_number= 0;
9503   longlong prefix_number;
9504   const char *start_ptr= str;
9505   size_t str_len= length;
9506   const char *end_ptr= start_ptr + str_len;
9507   int error;
9508   prefix_number= my_strtoll10(start_ptr, (char**) &end_ptr, &error);
9509   if (likely((start_ptr + str_len - 1) == end_ptr))
9510   {
9511     switch (end_ptr[0])
9512     {
9513       case 'g':
9514       case 'G': text_shift_number+=30; break;
9515       case 'm':
9516       case 'M': text_shift_number+=20; break;
9517       case 'k':
9518       case 'K': text_shift_number+=10; break;
9519       default:
9520         my_error(ER_WRONG_SIZE_NUMBER, MYF(0));
9521         return true;
9522     }
9523     if (unlikely(prefix_number >> 31))
9524     {
9525       my_error(ER_SIZE_OVERFLOW_ERROR, MYF(0));
9526       return true;
9527     }
9528     number= prefix_number << text_shift_number;
9529   }
9530   else
9531   {
9532     my_error(ER_WRONG_SIZE_NUMBER, MYF(0));
9533     return true;
9534   }
9535   *to= number;
9536   return false;
9537 }
9538 
9539 
part_values_current(THD * thd)9540 bool LEX::part_values_current(THD *thd)
9541 {
9542   partition_element *elem= part_info->curr_part_elem;
9543   if (!is_partition_management())
9544   {
9545     if (unlikely(part_info->part_type != VERSIONING_PARTITION))
9546     {
9547       my_error(ER_PARTITION_WRONG_TYPE, MYF(0), "SYSTEM_TIME");
9548       return true;
9549     }
9550   }
9551   else
9552   {
9553     DBUG_ASSERT(create_last_non_select_table);
9554     DBUG_ASSERT(create_last_non_select_table->table_name.str);
9555     // FIXME: other ALTER commands?
9556     my_error(ER_VERS_WRONG_PARTS, MYF(0),
9557              create_last_non_select_table->table_name.str);
9558     return true;
9559   }
9560   elem->type= partition_element::CURRENT;
9561   DBUG_ASSERT(part_info->vers_info);
9562   part_info->vers_info->now_part= elem;
9563   return false;
9564 }
9565 
9566 
part_values_history(THD * thd)9567 bool LEX::part_values_history(THD *thd)
9568 {
9569   partition_element *elem= part_info->curr_part_elem;
9570   if (!is_partition_management())
9571   {
9572     if (unlikely(part_info->part_type != VERSIONING_PARTITION))
9573     {
9574       my_error(ER_PARTITION_WRONG_TYPE, MYF(0), "SYSTEM_TIME");
9575       return true;
9576     }
9577   }
9578   else
9579   {
9580     part_info->vers_init_info(thd);
9581     elem->id= UINT_MAX32;
9582   }
9583   DBUG_ASSERT(part_info->vers_info);
9584   if (unlikely(part_info->vers_info->now_part))
9585   {
9586     DBUG_ASSERT(create_last_non_select_table);
9587     DBUG_ASSERT(create_last_non_select_table->table_name.str);
9588     my_error(ER_VERS_WRONG_PARTS, MYF(0),
9589              create_last_non_select_table->table_name.str);
9590     return true;
9591   }
9592   elem->type= partition_element::HISTORY;
9593   return false;
9594 }
9595 
9596 
last_field_generated_always_as_row_start_or_end(Lex_ident * p,const char * type,uint flag)9597 bool LEX::last_field_generated_always_as_row_start_or_end(Lex_ident *p,
9598                                                           const char *type,
9599                                                           uint flag)
9600 {
9601   if (unlikely(p->str))
9602   {
9603     my_error(ER_VERS_DUPLICATE_ROW_START_END, MYF(0), type,
9604              last_field->field_name.str);
9605     return true;
9606   }
9607   last_field->flags|= (flag | NOT_NULL_FLAG);
9608   DBUG_ASSERT(p);
9609   *p= last_field->field_name;
9610   return false;
9611 }
9612 
9613 
9614 
last_field_generated_always_as_row_start()9615 bool LEX::last_field_generated_always_as_row_start()
9616 {
9617   Vers_parse_info &info= vers_get_info();
9618   Lex_ident *p= &info.as_row.start;
9619   return last_field_generated_always_as_row_start_or_end(p, "START",
9620                                                          VERS_ROW_START);
9621 }
9622 
9623 
last_field_generated_always_as_row_end()9624 bool LEX::last_field_generated_always_as_row_end()
9625 {
9626   Vers_parse_info &info= vers_get_info();
9627   Lex_ident *p= &info.as_row.end;
9628   return last_field_generated_always_as_row_start_or_end(p, "END",
9629                                                          VERS_ROW_END);
9630 }
9631 
reset_distinct()9632 void st_select_lex_unit::reset_distinct()
9633 {
9634   union_distinct= NULL;
9635   for(SELECT_LEX *sl= first_select()->next_select();
9636       sl;
9637       sl= sl->next_select())
9638   {
9639     if (sl->distinct)
9640     {
9641       union_distinct= sl;
9642     }
9643   }
9644 }
9645 
9646 
save_values_list_state()9647 void LEX::save_values_list_state()
9648 {
9649   current_select->save_many_values= many_values;
9650   current_select->save_insert_list= insert_list;
9651 }
9652 
9653 
restore_values_list_state()9654 void LEX::restore_values_list_state()
9655 {
9656   many_values= current_select->save_many_values;
9657   insert_list= current_select->save_insert_list;
9658 }
9659 
9660 
fix_distinct()9661 void st_select_lex_unit::fix_distinct()
9662 {
9663   if (union_distinct && this != union_distinct->master_unit())
9664     reset_distinct();
9665 }
9666 
9667 
register_select_chain(SELECT_LEX * first_sel)9668 void st_select_lex_unit::register_select_chain(SELECT_LEX *first_sel)
9669 {
9670   DBUG_ASSERT(first_sel != 0);
9671   slave= first_sel;
9672   first_sel->prev= &slave;
9673   for(SELECT_LEX *sel=first_sel; sel; sel= sel->next_select())
9674   {
9675     sel->master= (st_select_lex_node *)this;
9676     uncacheable|= sel->uncacheable;
9677   }
9678 }
9679 
9680 
register_unit(SELECT_LEX_UNIT * unit,Name_resolution_context * outer_context)9681 void st_select_lex::register_unit(SELECT_LEX_UNIT *unit,
9682                                   Name_resolution_context *outer_context)
9683 {
9684   if ((unit->next= slave))
9685     slave->prev= &unit->next;
9686   unit->prev= &slave;
9687   slave= unit;
9688   unit->master= this;
9689   uncacheable|= unit->uncacheable;
9690 
9691   for(SELECT_LEX *sel= unit->first_select();sel; sel= sel->next_select())
9692   {
9693     sel->context.outer_context= outer_context;
9694   }
9695 }
9696 
9697 
add_statistics(SELECT_LEX_UNIT * unit)9698 void st_select_lex::add_statistics(SELECT_LEX_UNIT *unit)
9699 {
9700   for (;
9701        unit;
9702        unit= unit->next_unit())
9703     for(SELECT_LEX *child= unit->first_select();
9704         child;
9705         child= child->next_select())
9706     {
9707       /*
9708         A subselect can add fields to an outer select.
9709         Reserve space for them.
9710       */
9711       select_n_where_fields+= child->select_n_where_fields;
9712       /*
9713         Aggregate functions in having clause may add fields
9714         to an outer select. Count them also.
9715       */
9716       select_n_having_items+= child->select_n_having_items;
9717     }
9718 }
9719 
9720 
main_select_push(bool service)9721 bool LEX::main_select_push(bool service)
9722 {
9723   DBUG_ENTER("LEX::main_select_push");
9724   DBUG_PRINT("info", ("service: %u", service));
9725   current_select_number= ++thd->lex->stmt_lex->current_select_number;
9726   builtin_select.select_number= current_select_number;
9727   builtin_select.is_service_select= service;
9728   if (push_select(&builtin_select))
9729     DBUG_RETURN(TRUE);
9730   DBUG_RETURN(FALSE);
9731 }
9732 
set_to(SELECT_LEX * sel)9733 void Lex_select_lock::set_to(SELECT_LEX *sel)
9734 {
9735   if (defined_lock)
9736   {
9737     if (sel->master_unit() &&
9738         sel == sel->master_unit()->fake_select_lex)
9739       sel->master_unit()->set_lock_to_the_last_select(*this);
9740     else
9741     {
9742       sel->parent_lex->safe_to_cache_query= 0;
9743       if (update_lock)
9744       {
9745         sel->lock_type= TL_WRITE;
9746         sel->set_lock_for_tables(TL_WRITE, false);
9747       }
9748       else
9749       {
9750         sel->lock_type= TL_READ_WITH_SHARED_LOCKS;
9751         sel->set_lock_for_tables(TL_READ_WITH_SHARED_LOCKS, false);
9752       }
9753     }
9754   }
9755 }
9756 
set_to(SELECT_LEX * sel)9757 bool Lex_order_limit_lock::set_to(SELECT_LEX *sel)
9758 {
9759   /*TODO: lock */
9760   //if (lock.defined_lock && sel == sel->master_unit()->fake_select_lex)
9761   //  return TRUE;
9762   if (lock.defined_timeout)
9763   {
9764     THD *thd= sel->parent_lex->thd;
9765      if (set_statement_var_if_exists(thd,
9766                                      C_STRING_WITH_LEN("lock_wait_timeout"),
9767                                      lock.timeout) ||
9768          set_statement_var_if_exists(thd,
9769                                      C_STRING_WITH_LEN("innodb_lock_wait_timeout"),
9770                                      lock.timeout))
9771        return TRUE;
9772   }
9773   lock.set_to(sel);
9774   sel->explicit_limit= limit.explicit_limit;
9775   sel->select_limit= limit.select_limit;
9776   sel->offset_limit= limit.offset_limit;
9777   if (order_list)
9778   {
9779     if (sel->get_linkage() != GLOBAL_OPTIONS_TYPE &&
9780         sel->olap != UNSPECIFIED_OLAP_TYPE &&
9781         (sel->get_linkage() != UNION_TYPE || sel->braces))
9782     {
9783       my_error(ER_WRONG_USAGE, MYF(0),
9784           "CUBE/ROLLUP", "ORDER BY");
9785       return TRUE;
9786     }
9787     sel->order_list= *(order_list);
9788   }
9789   sel->is_set_query_expr_tail= true;
9790   return FALSE;
9791 }
9792 
9793 
change_item_list_context(List<Item> * list,Name_resolution_context * context)9794 static void change_item_list_context(List<Item> *list,
9795                                      Name_resolution_context *context)
9796 {
9797   List_iterator_fast<Item> it (*list);
9798   Item *item;
9799   while((item= it++))
9800   {
9801     item->walk(&Item::change_context_processor, FALSE, (void *)context);
9802   }
9803 }
9804 
9805 
insert_select_hack(SELECT_LEX * sel)9806 bool LEX::insert_select_hack(SELECT_LEX *sel)
9807 {
9808   DBUG_ENTER("LEX::insert_select_hack");
9809 
9810   DBUG_ASSERT(first_select_lex() == &builtin_select);
9811   DBUG_ASSERT(sel != NULL);
9812 
9813   DBUG_ASSERT(builtin_select.first_inner_unit() == NULL);
9814 
9815   if (builtin_select.link_prev)
9816   {
9817     if ((*builtin_select.link_prev= builtin_select.link_next))
9818       ((st_select_lex *)builtin_select.link_next)->link_prev=
9819         builtin_select.link_prev;
9820     builtin_select.link_prev= NULL; // indicator of removal
9821   }
9822 
9823   if (set_main_unit(sel->master_unit()))
9824     return true;
9825 
9826   DBUG_ASSERT(builtin_select.table_list.elements == 1);
9827   TABLE_LIST *insert_table= builtin_select.table_list.first;
9828 
9829   if (!(insert_table->next_local= sel->table_list.first))
9830   {
9831     sel->table_list.next= &insert_table->next_local;
9832   }
9833   sel->table_list.first= insert_table;
9834   sel->table_list.elements++;
9835   insert_table->select_lex= sel;
9836 
9837   sel->context.first_name_resolution_table= insert_table;
9838   builtin_select.context= sel->context;
9839   change_item_list_context(&field_list, &sel->context);
9840 
9841   if (sel->tvc && !sel->next_select() &&
9842       (sql_command == SQLCOM_INSERT_SELECT ||
9843        sql_command == SQLCOM_REPLACE_SELECT))
9844   {
9845     DBUG_PRINT("info", ("'Usual' INSERT detected"));
9846     many_values= sel->tvc->lists_of_values;
9847     sel->options= sel->tvc->select_options;
9848     sel->tvc= NULL;
9849     if (sql_command == SQLCOM_INSERT_SELECT)
9850       sql_command= SQLCOM_INSERT;
9851     else
9852       sql_command= SQLCOM_REPLACE;
9853   }
9854 
9855 
9856   for (SELECT_LEX *sel= all_selects_list;
9857        sel;
9858        sel= sel->next_select_in_list())
9859   {
9860     if (sel->select_number != 1)
9861       sel->select_number--;
9862   };
9863 
9864   DBUG_RETURN(FALSE);
9865 }
9866 
9867 
9868 /**
9869   Create an Item_singlerow_subselect for a query expression.
9870 */
9871 
create_item_query_expression(THD * thd,st_select_lex_unit * unit)9872 Item *LEX::create_item_query_expression(THD *thd,
9873                                         st_select_lex_unit *unit)
9874 {
9875   if (clause_that_disallows_subselect)
9876   {
9877     my_error(ER_SUBQUERIES_NOT_SUPPORTED, MYF(0),
9878              clause_that_disallows_subselect);
9879     return NULL;
9880   }
9881 
9882   // Add the subtree of subquery to the current SELECT_LEX
9883   SELECT_LEX *curr_sel= select_stack_head();
9884   DBUG_ASSERT(current_select == curr_sel ||
9885               (curr_sel == NULL && current_select == &builtin_select));
9886   if (!curr_sel)
9887   {
9888     curr_sel= &builtin_select;
9889     curr_sel->register_unit(unit, &curr_sel->context);
9890     curr_sel->add_statistics(unit);
9891   }
9892 
9893   return new (thd->mem_root)
9894     Item_singlerow_subselect(thd, unit->first_select());
9895 }
9896 
9897 
parsed_select_expr_start(SELECT_LEX * s1,SELECT_LEX * s2,enum sub_select_type unit_type,bool distinct)9898 SELECT_LEX_UNIT *LEX::parsed_select_expr_start(SELECT_LEX *s1, SELECT_LEX *s2,
9899                                                enum sub_select_type unit_type,
9900                                                bool distinct)
9901 {
9902   SELECT_LEX_UNIT *res;
9903   SELECT_LEX *sel1;
9904   SELECT_LEX *sel2;
9905   if (!s1->next_select())
9906     sel1= s1;
9907   else
9908   {
9909     sel1= wrap_unit_into_derived(s1->master_unit());
9910     if (!sel1)
9911       return NULL;
9912   }
9913   if (!s2->next_select())
9914     sel2= s2;
9915   else
9916   {
9917     sel2= wrap_unit_into_derived(s2->master_unit());
9918     if (!sel2)
9919       return NULL;
9920   }
9921   sel1->link_neighbour(sel2);
9922   sel2->set_linkage_and_distinct(unit_type, distinct);
9923   sel2->first_nested= sel1->first_nested= sel1;
9924   res= create_unit(sel1);
9925   if (res == NULL)
9926     return NULL;
9927   res->pre_last_parse= sel1;
9928   push_select(res->fake_select_lex);
9929   return res;
9930 }
9931 
9932 
parsed_select_expr_cont(SELECT_LEX_UNIT * unit,SELECT_LEX * s2,enum sub_select_type unit_type,bool distinct,bool oracle)9933 SELECT_LEX_UNIT *LEX::parsed_select_expr_cont(SELECT_LEX_UNIT *unit,
9934                                               SELECT_LEX *s2,
9935                                               enum sub_select_type unit_type,
9936                                               bool distinct, bool oracle)
9937 {
9938   DBUG_ASSERT(!s2->next_select());
9939   SELECT_LEX *sel1= s2;
9940   SELECT_LEX *last= unit->pre_last_parse->next_select();
9941 
9942   int cmp= oracle? 0 : cmp_unit_op(unit_type, last->get_linkage());
9943   if (cmp == 0)
9944   {
9945     sel1->first_nested= last->first_nested;
9946   }
9947   else if (cmp > 0)
9948   {
9949     last->first_nested= unit->pre_last_parse;
9950     sel1->first_nested= last;
9951   }
9952   else /* cmp < 0 */
9953   {
9954     SELECT_LEX *first_in_nest= last->first_nested;
9955     if (first_in_nest->first_nested != first_in_nest)
9956     {
9957       /* There is a priority jump starting from first_in_nest */
9958       if ((last= create_priority_nest(first_in_nest)) == NULL)
9959         return NULL;
9960       unit->fix_distinct();
9961     }
9962     sel1->first_nested= last->first_nested;
9963   }
9964   last->link_neighbour(sel1);
9965   sel1->set_master_unit(unit);
9966   sel1->set_linkage_and_distinct(unit_type, distinct);
9967   unit->pre_last_parse= last;
9968   return unit;
9969 }
9970 
9971 
9972 /**
9973   Add primary expression as the next term in a given query expression body
9974   pruducing a new query expression body
9975 */
9976 
9977 SELECT_LEX_UNIT *
add_primary_to_query_expression_body(SELECT_LEX_UNIT * unit,SELECT_LEX * sel,enum sub_select_type unit_type,bool distinct,bool oracle)9978 LEX::add_primary_to_query_expression_body(SELECT_LEX_UNIT *unit,
9979                                           SELECT_LEX *sel,
9980                                           enum sub_select_type unit_type,
9981                                           bool distinct,
9982                                           bool oracle)
9983 {
9984   SELECT_LEX *sel2= sel;
9985   if (sel->master_unit() && sel->master_unit()->first_select()->next_select())
9986   {
9987     sel2= wrap_unit_into_derived(sel->master_unit());
9988     if (!sel2)
9989       return NULL;
9990   }
9991   SELECT_LEX *sel1= unit->first_select();
9992   if (!sel1->next_select())
9993     unit= parsed_select_expr_start(sel1, sel2, unit_type, distinct);
9994   else
9995     unit= parsed_select_expr_cont(unit, sel2, unit_type, distinct, oracle);
9996   return unit;
9997 }
9998 
9999 
10000 SELECT_LEX_UNIT *
add_primary_to_query_expression_body(SELECT_LEX_UNIT * unit,SELECT_LEX * sel,enum sub_select_type unit_type,bool distinct)10001 LEX::add_primary_to_query_expression_body(SELECT_LEX_UNIT *unit,
10002                                           SELECT_LEX *sel,
10003                                           enum sub_select_type unit_type,
10004                                           bool distinct)
10005 {
10006   return
10007     add_primary_to_query_expression_body(unit, sel, unit_type, distinct,
10008                                          thd->variables.sql_mode & MODE_ORACLE);
10009 }
10010 
10011 /**
10012   Add query primary to a parenthesized query primary
10013   pruducing a new query expression body
10014 */
10015 
10016 SELECT_LEX_UNIT *
add_primary_to_query_expression_body_ext_parens(SELECT_LEX_UNIT * unit,SELECT_LEX * sel,enum sub_select_type unit_type,bool distinct)10017 LEX::add_primary_to_query_expression_body_ext_parens(
10018                                                  SELECT_LEX_UNIT *unit,
10019                                                  SELECT_LEX *sel,
10020                                                  enum sub_select_type unit_type,
10021                                                  bool distinct)
10022 {
10023   SELECT_LEX *sel1= unit->first_select();
10024   if (unit->first_select()->next_select())
10025   {
10026     sel1= wrap_unit_into_derived(unit);
10027     if (!sel1)
10028       return NULL;
10029     if (!create_unit(sel1))
10030       return NULL;
10031   }
10032   SELECT_LEX *sel2= sel;
10033   if (sel->master_unit() && sel->master_unit()->first_select()->next_select())
10034   {
10035     sel2= wrap_unit_into_derived(sel->master_unit());
10036     if (!sel2)
10037       return NULL;
10038   }
10039   unit= parsed_select_expr_start(sel1, sel2, unit_type, distinct);
10040   return unit;
10041 }
10042 
10043 
10044 /**
10045   Process multi-operand query expression body
10046 */
10047 
parsed_multi_operand_query_expression_body(SELECT_LEX_UNIT * unit)10048 bool LEX::parsed_multi_operand_query_expression_body(SELECT_LEX_UNIT *unit)
10049 {
10050   SELECT_LEX *first_in_nest=
10051     unit->pre_last_parse->next_select()->first_nested;
10052   if (first_in_nest->first_nested != first_in_nest)
10053   {
10054     /* There is a priority jump starting from first_in_nest */
10055     if (create_priority_nest(first_in_nest) == NULL)
10056       return true;
10057     unit->fix_distinct();
10058   }
10059   return false;
10060 }
10061 
10062 
10063 /**
10064   Add non-empty tail to a query expression body
10065 */
10066 
add_tail_to_query_expression_body(SELECT_LEX_UNIT * unit,Lex_order_limit_lock * l)10067 SELECT_LEX_UNIT *LEX::add_tail_to_query_expression_body(SELECT_LEX_UNIT *unit,
10068                                                         Lex_order_limit_lock *l)
10069 {
10070   DBUG_ASSERT(l != NULL);
10071   pop_select();
10072   SELECT_LEX *sel= unit->first_select()->next_select() ? unit->fake_select_lex :
10073                                                          unit->first_select();
10074   l->set_to(sel);
10075   return unit;
10076 }
10077 
10078 
10079 /**
10080   Add non-empty tail to a parenthesized query primary
10081 */
10082 
10083 SELECT_LEX_UNIT *
add_tail_to_query_expression_body_ext_parens(SELECT_LEX_UNIT * unit,Lex_order_limit_lock * l)10084 LEX::add_tail_to_query_expression_body_ext_parens(SELECT_LEX_UNIT *unit,
10085                                                   Lex_order_limit_lock *l)
10086 {
10087   SELECT_LEX *sel= unit->first_select()->next_select() ? unit->fake_select_lex :
10088                                                          unit->first_select();
10089 
10090   DBUG_ASSERT(l != NULL);
10091 
10092   pop_select();
10093   if (sel->is_set_query_expr_tail)
10094   {
10095     if (!l->order_list && !sel->explicit_limit)
10096       l->order_list= &sel->order_list;
10097     else
10098     {
10099       if (!unit)
10100         return NULL;
10101       sel= wrap_unit_into_derived(unit);
10102       if (!sel)
10103         return NULL;
10104      if (!create_unit(sel))
10105       return NULL;
10106    }
10107   }
10108   l->set_to(sel);
10109   return sel->master_unit();
10110 }
10111 
10112 
10113 /**
10114   Process subselect parsing
10115 */
10116 
parsed_subselect(SELECT_LEX_UNIT * unit)10117 SELECT_LEX *LEX::parsed_subselect(SELECT_LEX_UNIT *unit)
10118 {
10119   if (clause_that_disallows_subselect)
10120   {
10121     my_error(ER_SUBQUERIES_NOT_SUPPORTED, MYF(0),
10122              clause_that_disallows_subselect);
10123     return NULL;
10124   }
10125 
10126   // Add the subtree of subquery to the current SELECT_LEX
10127   SELECT_LEX *curr_sel= select_stack_head();
10128   DBUG_ASSERT(current_select == curr_sel ||
10129               (curr_sel == NULL && current_select == &builtin_select));
10130   if (curr_sel)
10131   {
10132     curr_sel->register_unit(unit, context_stack.head());
10133     curr_sel->add_statistics(unit);
10134   }
10135 
10136   return unit->first_select();
10137 }
10138 
10139 
10140 /**
10141   Process INSERT-like select
10142 */
10143 
parsed_insert_select(SELECT_LEX * first_select)10144 bool LEX::parsed_insert_select(SELECT_LEX *first_select)
10145 {
10146   if (sql_command == SQLCOM_INSERT ||
10147       sql_command == SQLCOM_REPLACE)
10148   {
10149     if (sql_command == SQLCOM_INSERT)
10150       sql_command= SQLCOM_INSERT_SELECT;
10151     else
10152       sql_command= SQLCOM_REPLACE_SELECT;
10153   }
10154   insert_select_hack(first_select);
10155   if (check_main_unit_semantics())
10156     return true;
10157 
10158   // fix "main" select
10159   SELECT_LEX *blt __attribute__((unused))= pop_select();
10160   DBUG_ASSERT(blt == &builtin_select);
10161   push_select(first_select);
10162   return false;
10163 }
10164 
10165 
parsed_TVC_start()10166 bool LEX::parsed_TVC_start()
10167 {
10168   SELECT_LEX *sel;
10169   save_values_list_state();
10170   many_values.empty();
10171   insert_list= 0;
10172   if (!(sel= alloc_select(TRUE)) ||
10173         push_select(sel))
10174     return true;
10175   sel->init_select();
10176   sel->braces= FALSE; // just initialisation
10177   return false;
10178 }
10179 
10180 
parsed_TVC_end()10181 SELECT_LEX *LEX::parsed_TVC_end()
10182 {
10183   SELECT_LEX *res= pop_select(); // above TVC select
10184   if (!(res->tvc=
10185         new (thd->mem_root) table_value_constr(many_values,
10186           res,
10187           res->options)))
10188     return NULL;
10189   restore_values_list_state();
10190   return res;
10191 }
10192 
10193 
10194 
parsed_derived_table(SELECT_LEX_UNIT * unit,int for_system_time,LEX_CSTRING * alias)10195 TABLE_LIST *LEX::parsed_derived_table(SELECT_LEX_UNIT *unit,
10196                                      int for_system_time,
10197                                      LEX_CSTRING *alias)
10198 {
10199   TABLE_LIST *res;
10200   derived_tables|= DERIVED_SUBQUERY;
10201   unit->first_select()->set_linkage(DERIVED_TABLE_TYPE);
10202 
10203   // Add the subtree of subquery to the current SELECT_LEX
10204   SELECT_LEX *curr_sel= select_stack_head();
10205   DBUG_ASSERT(current_select == curr_sel ||
10206               (curr_sel == NULL && current_select == &builtin_select));
10207 
10208   Table_ident *ti= new (thd->mem_root) Table_ident(unit);
10209   if (ti == NULL)
10210     return NULL;
10211   if (!(res= curr_sel->add_table_to_list(thd, ti, alias, 0,
10212                                          TL_READ, MDL_SHARED_READ)))
10213     return NULL;
10214   if (for_system_time)
10215   {
10216     res->vers_conditions= vers_conditions;
10217   }
10218   return res;
10219 }
10220 
parsed_create_view(SELECT_LEX_UNIT * unit,int check)10221 bool LEX::parsed_create_view(SELECT_LEX_UNIT *unit, int check)
10222 {
10223   SQL_I_List<TABLE_LIST> *save= &first_select_lex()->table_list;
10224   if (set_main_unit(unit))
10225     return true;
10226   if (check_main_unit_semantics())
10227     return true;
10228   first_select_lex()->table_list.push_front(save);
10229   current_select= first_select_lex();
10230   size_t len= thd->m_parser_state->m_lip.get_cpp_ptr() -
10231     create_view->select.str;
10232   void *create_view_select= thd->memdup(create_view->select.str, len);
10233   create_view->select.length= len;
10234   create_view->select.str= (char *) create_view_select;
10235   size_t not_used;
10236   trim_whitespace(thd->charset(),
10237       &create_view->select, &not_used);
10238   create_view->check= check;
10239   parsing_options.allows_variable= TRUE;
10240   return false;
10241 }
10242 
select_finalize(st_select_lex_unit * expr)10243 bool LEX::select_finalize(st_select_lex_unit *expr)
10244 {
10245   sql_command= SQLCOM_SELECT;
10246   selects_allow_into= TRUE;
10247   selects_allow_procedure= TRUE;
10248   if (set_main_unit(expr))
10249     return true;
10250   return check_main_unit_semantics();
10251 }
10252 
10253 
select_finalize(st_select_lex_unit * expr,Lex_select_lock l)10254 bool LEX::select_finalize(st_select_lex_unit *expr, Lex_select_lock l)
10255 {
10256   return expr->set_lock_to_the_last_select(l) ||
10257          select_finalize(expr);
10258 }
10259 
10260 
10261 /*
10262   "IN" and "EXISTS" subselect can appear in two statement types:
10263 
10264   1. Statements that can have table columns, such as SELECT, DELETE, UPDATE
10265   2. Statements that cannot have table columns, e.g:
10266      RETURN ((1) IN (SELECT * FROM t1))
10267      IF ((1) IN (SELECT * FROM t1))
10268 
10269   Statements of the first type call master_select_push() in the beginning.
10270   In such case everything is properly linked.
10271 
10272   Statements of the second type do not call mastr_select_push().
10273   Here we catch the second case and relink thd->lex->builtin_select and
10274   select_lex to properly point to each other.
10275 
10276   QQ: Shouldn't subselects of other type also call relink_hack()?
10277   QQ: Can we do it at constructor time instead?
10278 */
10279 
relink_hack(st_select_lex * select_lex)10280 void LEX::relink_hack(st_select_lex *select_lex)
10281 {
10282   if (!select_stack_top) // Statements of the second type
10283   {
10284     if (!select_lex->get_master()->get_master())
10285       ((st_select_lex *) select_lex->get_master())->
10286         set_master(&builtin_select);
10287     if (!builtin_select.get_slave())
10288       builtin_select.set_slave(select_lex->get_master());
10289   }
10290 }
10291 
10292 
set_lock_to_the_last_select(Lex_select_lock l)10293 bool SELECT_LEX_UNIT::set_lock_to_the_last_select(Lex_select_lock l)
10294 {
10295   if (l.defined_lock)
10296   {
10297     SELECT_LEX *sel= first_select();
10298     while (sel->next_select())
10299       sel= sel->next_select();
10300     if (sel->braces)
10301     {
10302       my_error(ER_WRONG_USAGE, MYF(0), "lock options",
10303                "SELECT in brackets");
10304       return TRUE;
10305     }
10306     l.set_to(sel);
10307   }
10308   return FALSE;
10309 }
10310 
10311 /**
10312   Generate unique name for generated derived table for this SELECT
10313 */
10314 
make_unique_derived_name(THD * thd,LEX_CSTRING * alias)10315 bool SELECT_LEX::make_unique_derived_name(THD *thd, LEX_CSTRING *alias)
10316 {
10317   // uint32 digits + two underscores + trailing '\0'
10318   char buff[MAX_INT_WIDTH + 2 + 1];
10319   alias->length= my_snprintf(buff, sizeof(buff), "__%u", select_number);
10320   alias->str= thd->strmake(buff, alias->length);
10321   return !alias->str;
10322 }
10323 
10324 
10325 /*
10326   Make a new sp_instr_stmt and set its m_query to a concatenation
10327   of two strings.
10328 */
new_sp_instr_stmt(THD * thd,const LEX_CSTRING & prefix,const LEX_CSTRING & suffix)10329 bool LEX::new_sp_instr_stmt(THD *thd,
10330                             const LEX_CSTRING &prefix,
10331                             const LEX_CSTRING &suffix)
10332 {
10333   LEX_STRING qbuff;
10334   sp_instr_stmt *i;
10335 
10336   if (!(i= new (thd->mem_root) sp_instr_stmt(sphead->instructions(),
10337                                              spcont, this)))
10338     return true;
10339 
10340   qbuff.length= prefix.length + suffix.length;
10341   if (!(qbuff.str= (char*) alloc_root(thd->mem_root, qbuff.length + 1)))
10342     return true;
10343   if (prefix.length)
10344     memcpy(qbuff.str, prefix.str, prefix.length);
10345   strmake(qbuff.str + prefix.length, suffix.str, suffix.length);
10346   i->m_query= qbuff;
10347   return sphead->add_instr(i);
10348 }
10349 
10350 
sp_proc_stmt_statement_finalize_buf(THD * thd,const LEX_CSTRING & qbuf)10351 bool LEX::sp_proc_stmt_statement_finalize_buf(THD *thd, const LEX_CSTRING &qbuf)
10352 {
10353   sphead->m_flags|= sp_get_flags_for_command(this);
10354   /* "USE db" doesn't work in a procedure */
10355   if (unlikely(sql_command == SQLCOM_CHANGE_DB))
10356   {
10357     my_error(ER_SP_BADSTATEMENT, MYF(0), "USE");
10358     return true;
10359   }
10360   /*
10361     Don't add an instruction for SET statements, since all
10362     instructions for them were already added during processing
10363     of "set" rule.
10364   */
10365   DBUG_ASSERT(sql_command != SQLCOM_SET_OPTION || var_list.is_empty());
10366   if (sql_command != SQLCOM_SET_OPTION)
10367     return new_sp_instr_stmt(thd, empty_clex_str, qbuf);
10368   return false;
10369 }
10370 
10371 
sp_proc_stmt_statement_finalize(THD * thd,bool no_lookahead)10372 bool LEX::sp_proc_stmt_statement_finalize(THD *thd, bool no_lookahead)
10373 {
10374   // Extract the query statement from the tokenizer
10375   Lex_input_stream *lip= &thd->m_parser_state->m_lip;
10376   Lex_cstring qbuf(sphead->m_tmp_query, no_lookahead ? lip->get_ptr() :
10377                                                        lip->get_tok_start());
10378   return LEX::sp_proc_stmt_statement_finalize_buf(thd, qbuf);
10379 }
10380 
10381 
10382 /**
10383   @brief
10384     Extract the condition that can be pushed into WHERE clause
10385 
10386   @param thd             the thread handle
10387   @param cond            the condition from which to extract a pushed condition
10388   @param remaining_cond  IN/OUT the condition that will remain of cond after
10389                          the extraction
10390   @param transformer     the transformer callback function to be
10391                          applied to the fields of the condition so it
10392                          can be pushed`
10393   @param arg             parameter to be passed to the transformer
10394 
10395   @details
10396     This function builds the most restrictive condition depending only on
10397     the fields used in the GROUP BY of this SELECT. These fields were
10398     collected before in grouping_tmp_fields list of this SELECT.
10399 
10400     First this method checks if this SELECT doesn't have any aggregation
10401     functions and has no GROUP BY clause. If so cond can be entirely pushed
10402     into WHERE.
10403 
10404     Otherwise the method checks if there is a condition depending only on
10405     grouping fields that can be extracted from cond.
10406 
10407     The condition that can be pushed into WHERE should be transformed.
10408     It is done by transformer.
10409 
10410     The extracted condition is saved in cond_pushed_into_where of this select.
10411     COND can remain not empty after the extraction of the conditions that can be
10412     pushed into WHERE. It is saved in remaining_cond.
10413 
10414   @note
10415     This method is called for pushdown conditions into materialized
10416     derived tables/views optimization.
10417     Item::derived_field_transformer_for_where is passed as the actual
10418     callback function.
10419     Also it is called for pushdown into materialized IN subqueries.
10420     Item::in_subq_field_transformer_for_where is passed as the actual
10421     callback function.
10422 */
10423 
pushdown_cond_into_where_clause(THD * thd,Item * cond,Item ** remaining_cond,Item_transformer transformer,uchar * arg)10424 void st_select_lex::pushdown_cond_into_where_clause(THD *thd, Item *cond,
10425                                                     Item **remaining_cond,
10426                                                     Item_transformer transformer,
10427                                                     uchar *arg)
10428 {
10429   if (!cond_pushdown_is_allowed())
10430     return;
10431   thd->lex->current_select= this;
10432   if (have_window_funcs())
10433   {
10434     Item *cond_over_partition_fields;
10435     check_cond_extraction_for_grouping_fields(thd, cond);
10436     cond_over_partition_fields=
10437       build_cond_for_grouping_fields(thd, cond, true);
10438     if (cond_over_partition_fields)
10439       cond_over_partition_fields= cond_over_partition_fields->transform(thd,
10440                                 &Item::grouping_field_transformer_for_where,
10441                                 (uchar*) this);
10442     if (cond_over_partition_fields)
10443     {
10444       cond_over_partition_fields->walk(
10445         &Item::cleanup_excluding_const_fields_processor, 0, 0);
10446       cond_pushed_into_where= cond_over_partition_fields;
10447     }
10448 
10449     return;
10450   }
10451 
10452   if (!join->group_list && !with_sum_func)
10453   {
10454     cond= transform_condition_or_part(thd, cond, transformer, arg);
10455     if (cond)
10456     {
10457       cond->walk(
10458         &Item::cleanup_excluding_const_fields_processor, 0, 0);
10459       cond_pushed_into_where= cond;
10460     }
10461 
10462     return;
10463   }
10464 
10465   /*
10466     Figure out what can be extracted from cond and pushed into
10467     the WHERE clause of this select.
10468   */
10469   Item *cond_over_grouping_fields;
10470   check_cond_extraction_for_grouping_fields(thd, cond);
10471   cond_over_grouping_fields=
10472     build_cond_for_grouping_fields(thd, cond, true);
10473 
10474   /*
10475     Transform references to the columns of condition that can be pushed
10476     into WHERE so it can be pushed.
10477   */
10478   if (cond_over_grouping_fields)
10479   {
10480     cond_over_grouping_fields=
10481        transform_condition_or_part(thd, cond_over_grouping_fields,
10482                                    &Item::grouping_field_transformer_for_where,
10483                                    (uchar*) this);
10484   }
10485 
10486   if (cond_over_grouping_fields)
10487   {
10488 
10489     /*
10490       Remove top conjuncts in cond that has been pushed into the WHERE
10491       clause of this select
10492     */
10493     cond= remove_pushed_top_conjuncts(thd, cond);
10494 
10495     cond_over_grouping_fields->walk(
10496       &Item::cleanup_excluding_const_fields_processor, 0, 0);
10497     cond_pushed_into_where= cond_over_grouping_fields;
10498   }
10499 
10500   *remaining_cond= cond;
10501 }
10502 
10503 
10504 /**
10505   @brief
10506     Mark OR-conditions as non-pushable to avoid repeatable pushdown
10507 
10508   @param cond  the processed condition
10509 
10510   @details
10511     Consider pushdown into the materialized derived table/view.
10512     Consider OR condition that can be pushed into HAVING and some
10513     parts of this OR condition that can be pushed into WHERE.
10514 
10515     On example:
10516 
10517     SELECT *
10518     FROM t1,
10519     (
10520       SELECT a,MAX(c) AS m_c
10521       GROUP BY a
10522     ) AS dt
10523     WHERE ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3)) AND
10524           (t1.a=v1.a);
10525 
10526 
10527     Here ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3)) or1
10528     can be pushed down into the HAVING of the materialized
10529     derived table dt.
10530 
10531     (dt.a>2) OR (dt.a<3) part of or1 depends only on grouping fields
10532     of dt and can be pushed into WHERE.
10533 
10534     As a result:
10535 
10536     SELECT *
10537     FROM t1,
10538     (
10539       SELECT a,MAX(c) AS m_c
10540       WHERE (dt.a>2) OR (dt.a<3)
10541       GROUP BY a
10542       HAVING ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3))
10543     ) AS dt
10544     WHERE ((dt.m_c>10) AND (dt.a>2)) OR ((dt.m_c<7) and (dt.a<3)) AND
10545           (t1.a=v1.a);
10546 
10547 
10548     Here (dt.a>2) OR (dt.a<3) also remains in HAVING of dt.
10549     When SELECT that defines df is processed HAVING pushdown optimization
10550     is made. In HAVING pushdown optimization it will extract
10551     (dt.a>2) OR (dt.a<3) condition from or1 again and push it into WHERE.
10552     This will cause duplicate conditions in WHERE of dt.
10553 
10554     To avoid repeatable pushdown such OR conditions as or1 describen
10555     above are marked with NO_EXTRACTION_FL.
10556 
10557   @note
10558     This method is called for pushdown into materialized
10559     derived tables/views/IN subqueries optimization.
10560 */
10561 
mark_or_conds_to_avoid_pushdown(Item * cond)10562 void mark_or_conds_to_avoid_pushdown(Item *cond)
10563 {
10564   if (cond->type() == Item::COND_ITEM &&
10565       ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
10566   {
10567     List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
10568     Item *item;
10569     while ((item=li++))
10570     {
10571       if (item->type() == Item::COND_ITEM &&
10572           ((Item_cond*) item)->functype() == Item_func::COND_OR_FUNC)
10573         item->set_extraction_flag(NO_EXTRACTION_FL);
10574     }
10575   }
10576   else if (cond->type() == Item::COND_ITEM &&
10577           ((Item_cond*) cond)->functype() == Item_func::COND_OR_FUNC)
10578     cond->set_extraction_flag(NO_EXTRACTION_FL);
10579 }
10580 
10581 /**
10582   @brief
10583     Get condition that can be pushed from HAVING into WHERE
10584 
10585   @param thd   the thread handle
10586   @param cond  the condition from which to extract the condition
10587 
10588   @details
10589     The method collects in attach_to_conds list conditions from cond
10590     that can be pushed from HAVING into WHERE.
10591 
10592     Conditions that can be pushed were marked with FULL_EXTRACTION_FL in
10593     check_cond_extraction_for_grouping_fields() method.
10594     Conditions that can't be pushed were marked with NO_EXTRACTION_FL.
10595     Conditions which parts can be pushed weren't marked.
10596 
10597     There are two types of conditions that can be pushed:
10598     1. Condition that can be simply moved from HAVING
10599        (if cond is marked with FULL_EXTRACTION_FL or
10600            cond is an AND condition and some of its parts are marked with
10601            FULL_EXTRACTION_FL)
10602        In this case condition is transformed and pushed into attach_to_conds
10603        list.
10604     2. Part of some other condition c1 that can't be entirely pushed
10605        (if с1 isn't marked with any flag).
10606 
10607        For example:
10608 
10609        SELECT t1.a,MAX(t1.b),t1.c
10610        FROM t1
10611        GROUP BY t1.a
10612        HAVING ((t1.a > 5) AND (t1.c < 3)) OR (t1.a = 3);
10613 
10614        Here (t1.a > 5) OR (t1.a = 3) from HAVING can be pushed into WHERE.
10615 
10616        In this case build_pushable_cond() is called for c1.
10617        This method builds a clone of the c1 part that can be pushed.
10618 
10619     Transformation mentioned above is made with multiple_equality_transformer
10620     transformer. It transforms all multiple equalities in the extracted
10621     condition into the set of equalities.
10622 
10623   @note
10624     Conditions that can be pushed are collected in attach_to_conds in this way:
10625     1. if cond is an AND condition its parts that can be pushed into WHERE
10626        are added to attach_to_conds list separately.
10627     2. in all other cases conditions are pushed into the list entirely.
10628 
10629   @retval
10630     true  - if an error occurs
10631     false - otherwise
10632 */
10633 
10634 bool
build_pushable_cond_for_having_pushdown(THD * thd,Item * cond)10635 st_select_lex::build_pushable_cond_for_having_pushdown(THD *thd, Item *cond)
10636 {
10637   List<Item> equalities;
10638 
10639   /* Condition can't be pushed */
10640   if (cond->get_extraction_flag() == NO_EXTRACTION_FL)
10641     return false;
10642 
10643   /**
10644     Condition can be pushed entirely.
10645     Transform its multiple equalities and add to attach_to_conds list.
10646   */
10647   if (cond->get_extraction_flag() == FULL_EXTRACTION_FL)
10648   {
10649     Item *result= cond->transform(thd,
10650                                   &Item::multiple_equality_transformer,
10651                                   (uchar *)this);
10652     if (!result)
10653       return true;
10654     if (result->type() == Item::COND_ITEM &&
10655         ((Item_cond*) result)->functype() == Item_func::COND_AND_FUNC)
10656     {
10657       List_iterator<Item> li(*((Item_cond*) result)->argument_list());
10658       Item *item;
10659       while ((item= li++))
10660       {
10661         if (attach_to_conds.push_back(item, thd->mem_root))
10662           return true;
10663       }
10664     }
10665     else
10666     {
10667       if (attach_to_conds.push_back(result, thd->mem_root))
10668         return true;
10669     }
10670     return false;
10671   }
10672 
10673   /**
10674     There is no flag set for this condition. It means that some
10675     part of this condition can be pushed.
10676   */
10677   if (cond->type() != Item::COND_ITEM)
10678     return false;
10679 
10680   if (((Item_cond *)cond)->functype() != Item_cond::COND_AND_FUNC)
10681   {
10682     /*
10683       cond is not a conjunctive formula and it cannot be pushed into WHERE.
10684       Try to extract a formula that can be pushed.
10685     */
10686     Item *fix= cond->build_pushable_cond(thd, 0, 0);
10687     if (!fix)
10688       return false;
10689     if (attach_to_conds.push_back(fix, thd->mem_root))
10690       return true;
10691   }
10692   else
10693   {
10694     List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
10695     Item *item;
10696     while ((item=li++))
10697     {
10698       if (item->get_extraction_flag() == NO_EXTRACTION_FL)
10699         continue;
10700       else if (item->get_extraction_flag() == FULL_EXTRACTION_FL)
10701       {
10702         Item *result= item->transform(thd,
10703                                       &Item::multiple_equality_transformer,
10704                                       (uchar *)item);
10705         if (!result)
10706           return true;
10707         if (result->type() == Item::COND_ITEM &&
10708            ((Item_cond*) result)->functype() == Item_func::COND_AND_FUNC)
10709         {
10710           List_iterator<Item> li(*((Item_cond*) result)->argument_list());
10711           Item *item;
10712           while ((item=li++))
10713           {
10714             if (attach_to_conds.push_back(item, thd->mem_root))
10715               return true;
10716           }
10717         }
10718         else
10719         {
10720           if (attach_to_conds.push_back(result, thd->mem_root))
10721             return true;
10722         }
10723       }
10724       else
10725       {
10726         Item *fix= item->build_pushable_cond(thd, 0, 0);
10727         if (!fix)
10728           continue;
10729         if (attach_to_conds.push_back(fix, thd->mem_root))
10730           return true;
10731       }
10732     }
10733   }
10734   return false;
10735 }
10736 
10737 
10738 /**
10739   Check if item is equal to some field in Field_pair 'field_pair'
10740   from 'pair_list' and return found 'field_pair' if it exists.
10741 */
10742 
get_corresponding_field_pair(Item * item,List<Field_pair> pair_list)10743 Field_pair *get_corresponding_field_pair(Item *item,
10744                                          List<Field_pair> pair_list)
10745 {
10746   DBUG_ASSERT(item->type() == Item::FIELD_ITEM ||
10747               (item->type() == Item::REF_ITEM &&
10748                ((((Item_ref *) item)->ref_type() == Item_ref::VIEW_REF) ||
10749                (((Item_ref *) item)->ref_type() == Item_ref::REF))));
10750 
10751   List_iterator<Field_pair> it(pair_list);
10752   Field_pair *field_pair;
10753   Item_field *field_item= (Item_field *) (item->real_item());
10754   while ((field_pair= it++))
10755   {
10756     if (field_item->field == field_pair->field)
10757       return field_pair;
10758   }
10759   return NULL;
10760 }
10761 
10762 
10763 /**
10764   @brief
10765     Collect fields from multiple equalities which are equal to grouping
10766 
10767   @param thd  the thread handle
10768 
10769   @details
10770     This method checks if multiple equalities of the WHERE clause contain
10771     fields from GROUP BY of this SELECT. If so all fields of such multiple
10772     equalities are collected in grouping_tmp_fields list without repetitions.
10773 
10774   @retval
10775     true  - if an error occurs
10776     false - otherwise
10777 */
10778 
collect_fields_equal_to_grouping(THD * thd)10779 bool st_select_lex::collect_fields_equal_to_grouping(THD *thd)
10780 {
10781   if (!join->cond_equal || join->cond_equal->is_empty())
10782     return false;
10783 
10784   List_iterator_fast<Item_equal> li(join->cond_equal->current_level);
10785   Item_equal *item_equal;
10786 
10787   while ((item_equal= li++))
10788   {
10789     Item_equal_fields_iterator it(*item_equal);
10790     Item *item;
10791     while ((item= it++))
10792     {
10793       if (get_corresponding_field_pair(item, grouping_tmp_fields))
10794         break;
10795     }
10796     if (!item)
10797       break;
10798 
10799     it.rewind();
10800     while ((item= it++))
10801     {
10802       if (get_corresponding_field_pair(item, grouping_tmp_fields))
10803         continue;
10804       Field_pair *grouping_tmp_field=
10805         new Field_pair(((Item_field *)item->real_item())->field, item);
10806       if (grouping_tmp_fields.push_back(grouping_tmp_field, thd->mem_root))
10807         return true;
10808     }
10809   }
10810   return false;
10811 }
10812 
10813 
10814 /**
10815   @brief
10816     Remove marked top conjuncts of HAVING for having pushdown
10817 
10818   @param thd   the thread handle
10819   @param cond  the condition which subformulas are to be removed
10820 
10821   @details
10822     This method removes from cond all subformulas that can be moved from HAVING
10823     into WHERE.
10824 
10825   @retval
10826      condition without removed subformulas
10827      0 if the whole 'cond' is removed
10828 */
10829 
remove_pushed_top_conjuncts_for_having(THD * thd,Item * cond)10830 Item *remove_pushed_top_conjuncts_for_having(THD *thd, Item *cond)
10831 {
10832   /* Nothing to extract */
10833   if (cond->get_extraction_flag() == NO_EXTRACTION_FL)
10834   {
10835     cond->clear_extraction_flag();
10836     return cond;
10837   }
10838   /* cond can be pushed in WHERE entirely */
10839   if (cond->get_extraction_flag() == FULL_EXTRACTION_FL)
10840   {
10841     cond->clear_extraction_flag();
10842     return 0;
10843   }
10844 
10845   /* Some parts of cond can be pushed */
10846   if (cond->type() == Item::COND_ITEM &&
10847       ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
10848   {
10849     List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
10850     Item *item;
10851     while ((item=li++))
10852     {
10853       if (item->get_extraction_flag() == NO_EXTRACTION_FL)
10854         item->clear_extraction_flag();
10855       else if (item->get_extraction_flag() == FULL_EXTRACTION_FL)
10856       {
10857         if (item->type() == Item::FUNC_ITEM &&
10858             ((Item_func*) item)->functype() == Item_func::MULT_EQUAL_FUNC)
10859           item->set_extraction_flag(DELETION_FL);
10860         else
10861         {
10862           item->clear_extraction_flag();
10863           li.remove();
10864         }
10865       }
10866     }
10867     switch (((Item_cond*) cond)->argument_list()->elements)
10868     {
10869     case 0:
10870       return 0;
10871     case 1:
10872       return (((Item_cond*) cond)->argument_list()->head());
10873     default:
10874       return cond;
10875     }
10876   }
10877   return cond;
10878 }
10879 
10880 
10881 /**
10882   @brief
10883     Extract condition that can be pushed from HAVING into WHERE
10884 
10885   @param thd           the thread handle
10886   @param having        the HAVING clause of this select
10887   @param having_equal  multiple equalities of HAVING
10888 
10889   @details
10890     This method builds a set of conditions dependent only on
10891     fields used in the GROUP BY of this select (directly or indirectly
10892     through equalities). These conditions are extracted from the HAVING
10893     clause of this select.
10894     The method saves these conditions into attach_to_conds list and removes
10895     from HAVING conditions that can be entirely pushed into WHERE.
10896 
10897     Example of the HAVING pushdown transformation:
10898 
10899     SELECT t1.a,MAX(t1.b)
10900     FROM t1
10901     GROUP BY t1.a
10902     HAVING (t1.a>2) AND (MAX(c)>12);
10903 
10904     =>
10905 
10906     SELECT t1.a,MAX(t1.b)
10907     FROM t1
10908     WHERE (t1.a>2)
10909     GROUP BY t1.a
10910     HAVING (MAX(c)>12);
10911 
10912     In this method (t1.a>2) is not attached to the WHERE clause.
10913     It is pushed into the attach_to_conds list to be attached to
10914     the WHERE clause later.
10915 
10916     In details:
10917     1. Collect fields used in the GROUP BY grouping_fields of this SELECT
10918     2. Collect fields equal to grouping_fields from the WHERE clause
10919        of this SELECT and add them to the grouping_fields list.
10920     3. Extract the most restrictive condition from the HAVING clause of this
10921        select that depends only on the grouping fields (directly or indirectly
10922        through equality).
10923        If the extracted condition is an AND condition it is transformed into a
10924        list of all its conjuncts saved in attach_to_conds. Otherwise,
10925        the condition is put into attach_to_conds as the only its element.
10926     4. Remove conditions from HAVING clause that can be entirely pushed
10927        into WHERE.
10928        Multiple equalities are not removed but marked with DELETION_FL flag.
10929        They will be deleted later in substitite_for_best_equal_field() called
10930        for the HAVING condition.
10931     5. Unwrap fields wrapped in Item_ref wrappers contained in the condition
10932        of attach_to_conds so the condition could be pushed into WHERE.
10933 
10934   @note
10935     This method is similar to st_select_lex::pushdown_cond_into_where_clause().
10936 
10937   @retval TRUE   if an error occurs
10938   @retval FALSE  otherwise
10939 */
10940 
pushdown_from_having_into_where(THD * thd,Item * having)10941 Item *st_select_lex::pushdown_from_having_into_where(THD *thd, Item *having)
10942 {
10943   if (!having || !group_list.first)
10944     return having;
10945   if (!cond_pushdown_is_allowed())
10946     return having;
10947 
10948   st_select_lex *save_curr_select= thd->lex->current_select;
10949   thd->lex->current_select= this;
10950 
10951   /*
10952     1. Collect fields used in the GROUP BY grouping fields of this SELECT
10953     2. Collect fields equal to grouping_fields from the WHERE clause
10954        of this SELECT and add them to the grouping fields list.
10955   */
10956   if (collect_grouping_fields(thd) ||
10957       collect_fields_equal_to_grouping(thd))
10958     return having;
10959 
10960   /*
10961     3. Extract the most restrictive condition from the HAVING clause of this
10962        select that depends only on the grouping fields (directly or indirectly
10963        through equality).
10964        If the extracted condition is an AND condition it is transformed into a
10965        list of all its conjuncts saved in attach_to_conds. Otherwise,
10966        the condition is put into attach_to_conds as the only its element.
10967   */
10968   List_iterator_fast<Item> it(attach_to_conds);
10969   Item *item;
10970   check_cond_extraction_for_grouping_fields(thd, having);
10971   if (build_pushable_cond_for_having_pushdown(thd, having))
10972   {
10973     attach_to_conds.empty();
10974     goto exit;
10975   }
10976   if (!attach_to_conds.elements)
10977     goto exit;
10978 
10979   /*
10980     4. Remove conditions from HAVING clause that can be entirely pushed
10981        into WHERE.
10982        Multiple equalities are not removed but marked with DELETION_FL flag.
10983        They will be deleted later in substitite_for_best_equal_field() called
10984        for the HAVING condition.
10985   */
10986   having= remove_pushed_top_conjuncts_for_having(thd, having);
10987 
10988   /*
10989     Change join->cond_equal which points to the multiple equalities of
10990     the top level of HAVING.
10991     Removal of AND conditions may leave only one conjunct in HAVING.
10992 
10993     Example 1:
10994     SELECT *
10995     FROM t1
10996     GROUP BY t1.a
10997     (t1.a < 2) AND (t1.b = 2)
10998 
10999     (t1.a < 2) is pushed into WHERE.
11000     join->cond_equal should point on (t1.b = 2) multiple equality now.
11001 
11002     Example 2:
11003     SELECT *
11004     FROM t1
11005     GROUP BY t1.a
11006     (t1.a = 2) AND (t1.b < 2)
11007 
11008     (t1.a = 2) is pushed into WHERE.
11009     join->cond_equal should be NULL now.
11010   */
11011   if (having &&
11012       having->type() == Item::FUNC_ITEM &&
11013       ((Item_func*) having)->functype() == Item_func::MULT_EQUAL_FUNC)
11014     join->having_equal= new (thd->mem_root) COND_EQUAL((Item_equal *)having,
11015                                                        thd->mem_root);
11016   else if (!having ||
11017            having->type() != Item::COND_ITEM ||
11018            ((Item_cond *)having)->functype() != Item_cond::COND_AND_FUNC)
11019     join->having_equal= 0;
11020 
11021   /*
11022     5. Unwrap fields wrapped in Item_ref wrappers contained in the condition
11023        of attach_to_conds so the condition could be pushed into WHERE.
11024   */
11025   it.rewind();
11026   while ((item=it++))
11027   {
11028     item= item->transform(thd,
11029                           &Item::field_transformer_for_having_pushdown,
11030                           (uchar *)this);
11031 
11032     if (item->walk(&Item::cleanup_excluding_immutables_processor, 0, STOP_PTR)
11033         || item->fix_fields(thd, NULL))
11034     {
11035       attach_to_conds.empty();
11036       goto exit;
11037     }
11038   }
11039 exit:
11040   thd->lex->current_select= save_curr_select;
11041   return having;
11042 }
11043 
11044 
stmt_install_plugin(const DDL_options_st & opt,const Lex_ident_sys_st & name,const LEX_CSTRING & soname)11045 bool LEX::stmt_install_plugin(const DDL_options_st &opt,
11046                               const Lex_ident_sys_st &name,
11047                               const LEX_CSTRING &soname)
11048 {
11049   create_info.init();
11050   if (add_create_options_with_check(opt))
11051     return true;
11052   sql_command= SQLCOM_INSTALL_PLUGIN;
11053   comment= name;
11054   ident= soname;
11055   return false;
11056 }
11057 
11058 
stmt_install_plugin(const LEX_CSTRING & soname)11059 void LEX::stmt_install_plugin(const LEX_CSTRING &soname)
11060 {
11061   sql_command= SQLCOM_INSTALL_PLUGIN;
11062   comment= null_clex_str;
11063   ident= soname;
11064 }
11065 
11066 
stmt_uninstall_plugin_by_name(const DDL_options_st & opt,const Lex_ident_sys_st & name)11067 bool LEX::stmt_uninstall_plugin_by_name(const DDL_options_st &opt,
11068                                         const Lex_ident_sys_st &name)
11069 {
11070   check_opt.init();
11071   if (add_create_options_with_check(opt))
11072     return true;
11073   sql_command= SQLCOM_UNINSTALL_PLUGIN;
11074   comment= name;
11075   ident= null_clex_str;
11076   return false;
11077 }
11078 
11079 
stmt_uninstall_plugin_by_soname(const DDL_options_st & opt,const LEX_CSTRING & soname)11080 bool LEX::stmt_uninstall_plugin_by_soname(const DDL_options_st &opt,
11081                                           const LEX_CSTRING &soname)
11082 {
11083   check_opt.init();
11084   if (add_create_options_with_check(opt))
11085     return true;
11086   sql_command= SQLCOM_UNINSTALL_PLUGIN;
11087   comment= null_clex_str;
11088   ident= soname;
11089   return false;
11090 }
11091 
11092 
stmt_prepare_validate(const char * stmt_type)11093 bool LEX::stmt_prepare_validate(const char *stmt_type)
11094 {
11095   if (unlikely(table_or_sp_used()))
11096   {
11097     my_error(ER_SUBQUERIES_NOT_SUPPORTED, MYF(0), stmt_type);
11098     return true;
11099   }
11100   return check_main_unit_semantics();
11101 }
11102 
11103 
stmt_prepare(const Lex_ident_sys_st & ident,Item * code)11104 bool LEX::stmt_prepare(const Lex_ident_sys_st &ident, Item *code)
11105 {
11106   sql_command= SQLCOM_PREPARE;
11107   if (stmt_prepare_validate("PREPARE..FROM"))
11108     return true;
11109   prepared_stmt.set(ident, code, NULL);
11110   return false;
11111 }
11112 
11113 
stmt_execute_immediate(Item * code,List<Item> * params)11114 bool LEX::stmt_execute_immediate(Item *code, List<Item> *params)
11115 {
11116   sql_command= SQLCOM_EXECUTE_IMMEDIATE;
11117   if (stmt_prepare_validate("EXECUTE IMMEDIATE"))
11118     return true;
11119   static const Lex_ident_sys immediate(STRING_WITH_LEN("IMMEDIATE"));
11120   prepared_stmt.set(immediate, code, params);
11121   return false;
11122 }
11123 
11124 
stmt_execute(const Lex_ident_sys_st & ident,List<Item> * params)11125 bool LEX::stmt_execute(const Lex_ident_sys_st &ident, List<Item> *params)
11126 {
11127   sql_command= SQLCOM_EXECUTE;
11128   prepared_stmt.set(ident, NULL, params);
11129   return stmt_prepare_validate("EXECUTE..USING");
11130 }
11131 
11132 
stmt_deallocate_prepare(const Lex_ident_sys_st & ident)11133 void LEX::stmt_deallocate_prepare(const Lex_ident_sys_st &ident)
11134 {
11135   sql_command= SQLCOM_DEALLOCATE_PREPARE;
11136   prepared_stmt.set(ident, NULL, NULL);
11137 }
11138 
11139 
stmt_alter_table_exchange_partition(Table_ident * table)11140 bool LEX::stmt_alter_table_exchange_partition(Table_ident *table)
11141 {
11142   DBUG_ASSERT(sql_command == SQLCOM_ALTER_TABLE);
11143   first_select_lex()->db= table->db;
11144   if (first_select_lex()->db.str == NULL &&
11145       copy_db_to(&first_select_lex()->db))
11146     return true;
11147   name= table->table;
11148   alter_info.partition_flags|= ALTER_PARTITION_EXCHANGE;
11149   if (!first_select_lex()->add_table_to_list(thd, table, NULL,
11150                                              TL_OPTION_UPDATING,
11151                                              TL_READ_NO_INSERT,
11152                                              MDL_SHARED_NO_WRITE))
11153     return true;
11154   DBUG_ASSERT(!m_sql_cmd);
11155   m_sql_cmd= new (thd->mem_root) Sql_cmd_alter_table_exchange_partition();
11156   return m_sql_cmd == NULL;
11157 }
11158 
11159 
stmt_purge_to(const LEX_CSTRING & to)11160 void LEX::stmt_purge_to(const LEX_CSTRING &to)
11161 {
11162   type= 0;
11163   sql_command= SQLCOM_PURGE;
11164   to_log= to.str;
11165 }
11166 
11167 
stmt_purge_before(Item * item)11168 bool LEX::stmt_purge_before(Item *item)
11169 {
11170   type= 0;
11171   sql_command= SQLCOM_PURGE_BEFORE;
11172   value_list.empty();
11173   value_list.push_front(item, thd->mem_root);
11174   return check_main_unit_semantics();
11175 }
11176 
11177 
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)11178 bool LEX::stmt_create_udf_function(const DDL_options_st &options,
11179                                    enum_sp_aggregate_type agg_type,
11180                                    const Lex_ident_sys_st &name,
11181                                    Item_result return_type,
11182                                    const LEX_CSTRING &soname)
11183 {
11184   if (stmt_create_function_start(options))
11185     return true;
11186 
11187    if (unlikely(is_native_function(thd, &name)))
11188    {
11189      my_error(ER_NATIVE_FCT_NAME_COLLISION, MYF(0), name.str);
11190      return true;
11191    }
11192    sql_command= SQLCOM_CREATE_FUNCTION;
11193    udf.name= name;
11194    udf.returns= return_type;
11195    udf.dl= soname.str;
11196    udf.type= agg_type == GROUP_AGGREGATE ? UDFTYPE_AGGREGATE :
11197                                            UDFTYPE_FUNCTION;
11198    stmt_create_routine_finalize();
11199    return false;
11200 }
11201 
11202 
stmt_create_stored_function_start(const DDL_options_st & options,enum_sp_aggregate_type agg_type,const sp_name * spname)11203 bool LEX::stmt_create_stored_function_start(const DDL_options_st &options,
11204                                             enum_sp_aggregate_type agg_type,
11205                                             const sp_name *spname)
11206 {
11207   if (stmt_create_function_start(options) ||
11208       unlikely(!make_sp_head_no_recursive(thd, spname,
11209                                           &sp_handler_function, agg_type)))
11210     return true;
11211   return false;
11212 }
11213 
11214 
stmt_drop_function(const DDL_options_st & options,const Lex_ident_sys_st & db,const Lex_ident_sys_st & name)11215 bool LEX::stmt_drop_function(const DDL_options_st &options,
11216                              const Lex_ident_sys_st &db,
11217                              const Lex_ident_sys_st &name)
11218 {
11219   if (unlikely(db.str && check_db_name((LEX_STRING*) &db)))
11220   {
11221     my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
11222     return true;
11223   }
11224   if (unlikely(sphead))
11225   {
11226     my_error(ER_SP_NO_DROP_SP, MYF(0), "FUNCTION");
11227     return true;
11228   }
11229   set_command(SQLCOM_DROP_FUNCTION, options);
11230   spname= new (thd->mem_root) sp_name(&db, &name, true);
11231   return spname == NULL;
11232 }
11233 
11234 
stmt_drop_function(const DDL_options_st & options,const Lex_ident_sys_st & name)11235 bool LEX::stmt_drop_function(const DDL_options_st &options,
11236                              const Lex_ident_sys_st &name)
11237 {
11238   LEX_CSTRING db= {0, 0};
11239   if (unlikely(sphead))
11240   {
11241     my_error(ER_SP_NO_DROP_SP, MYF(0), "FUNCTION");
11242     return true;
11243   }
11244   if (thd->db.str && unlikely(copy_db_to(&db)))
11245     return true;
11246   set_command(SQLCOM_DROP_FUNCTION, options);
11247   spname= new (thd->mem_root) sp_name(&db, &name, false);
11248   return spname == NULL;
11249 }
11250 
11251 
stmt_drop_procedure(const DDL_options_st & options,sp_name * name)11252 bool LEX::stmt_drop_procedure(const DDL_options_st &options,
11253                               sp_name *name)
11254 {
11255   if (unlikely(sphead))
11256   {
11257     my_error(ER_SP_NO_DROP_SP, MYF(0), "PROCEDURE");
11258     return true;
11259   }
11260   set_command(SQLCOM_DROP_PROCEDURE, options);
11261   spname= name;
11262   return false;
11263 }
11264 
11265 
stmt_alter_function_start(sp_name * name)11266 bool LEX::stmt_alter_function_start(sp_name *name)
11267 {
11268   if (unlikely(sphead))
11269   {
11270     my_error(ER_SP_NO_DROP_SP, MYF(0), "FUNCTION");
11271     return true;
11272   }
11273   if (main_select_push())
11274     return true;
11275   sp_chistics.init();
11276   sql_command= SQLCOM_ALTER_FUNCTION;
11277   spname= name;
11278   return false;
11279 }
11280 
11281 
stmt_alter_procedure_start(sp_name * name)11282 bool LEX::stmt_alter_procedure_start(sp_name *name)
11283 {
11284   if (unlikely(sphead))
11285   {
11286     my_error(ER_SP_NO_DROP_SP, MYF(0), "PROCEDURE");
11287     return true;
11288   }
11289   if (main_select_push())
11290     return true;
11291   sp_chistics.init();
11292   sql_command= SQLCOM_ALTER_PROCEDURE;
11293   spname= name;
11294   return false;
11295 }
11296 
11297 
row_field_name(THD * thd,const Lex_ident_sys_st & name)11298 Spvar_definition *LEX::row_field_name(THD *thd, const Lex_ident_sys_st &name)
11299 {
11300   Spvar_definition *res;
11301   if (unlikely(check_string_char_length(&name, 0, NAME_CHAR_LEN,
11302                                         system_charset_info, 1)))
11303   {
11304     my_error(ER_TOO_LONG_IDENT, MYF(0), name.str);
11305     return NULL;
11306   }
11307   if (unlikely(!(res= new (thd->mem_root) Spvar_definition())))
11308     return NULL;
11309   init_last_field(res, &name, thd->variables.collation_database);
11310   return res;
11311 }
11312 
11313 
11314 Item *
create_typecast_item_or_error(THD * thd,Item * item,CHARSET_INFO * cs) const11315 Lex_cast_type_st::create_typecast_item_or_error(THD *thd, Item *item,
11316                                                 CHARSET_INFO *cs) const
11317 {
11318   Item *tmp= create_typecast_item(thd, item, cs);
11319   if (!tmp)
11320   {
11321     Name name= m_type_handler->name();
11322     char buf[128];
11323     size_t length= my_snprintf(buf, sizeof(buf), "CAST(expr AS %.*s)",
11324                                (int) name.length(), name.ptr());
11325     my_error(ER_UNKNOWN_OPERATOR, MYF(0),
11326              ErrConvString(buf, length, system_charset_info).ptr());
11327   }
11328   return tmp;
11329 }
11330 
11331 
set_handler_length_flags(const Type_handler * handler,const char * length,uint32 flags)11332 void Lex_field_type_st::set_handler_length_flags(const Type_handler *handler,
11333                                                  const char *length,
11334                                                  uint32 flags)
11335 {
11336   DBUG_ASSERT(!handler->is_unsigned());
11337   if (flags & UNSIGNED_FLAG)
11338     handler= handler->type_handler_unsigned();
11339   set(handler, length, NULL);
11340 }
11341 
11342 
set_field_type_udt(Lex_field_type_st * type,const LEX_CSTRING & name,const Lex_length_and_dec_st & attr)11343 bool LEX::set_field_type_udt(Lex_field_type_st *type,
11344                              const LEX_CSTRING &name,
11345                              const Lex_length_and_dec_st &attr)
11346 {
11347   const Type_handler *h;
11348   if (!(h= Type_handler::handler_by_name_or_error(thd, name)))
11349     return true;
11350   type->set(h, attr);
11351   charset= &my_charset_bin;
11352   return false;
11353 }
11354 
11355 
set_cast_type_udt(Lex_cast_type_st * type,const LEX_CSTRING & name)11356 bool LEX::set_cast_type_udt(Lex_cast_type_st *type,
11357                              const LEX_CSTRING &name)
11358 {
11359   const Type_handler *h;
11360   if (!(h= Type_handler::handler_by_name_or_error(thd, name)))
11361     return true;
11362   type->set(h);
11363   charset= NULL;
11364   return false;
11365 }
11366 
11367 
sp_repeat_loop_finalize(THD * thd)11368 bool sp_expr_lex::sp_repeat_loop_finalize(THD *thd)
11369 {
11370   uint ip= sphead->instructions();
11371   sp_label *lab= spcont->last_label();  /* Jumping back */
11372   sp_instr_jump_if_not *i= new (thd->mem_root)
11373     sp_instr_jump_if_not(ip, spcont, get_item(), lab->ip, this);
11374   if (unlikely(i == NULL) ||
11375       unlikely(sphead->add_instr(i)))
11376     return true;
11377   /* We can shortcut the cont_backpatch here */
11378   i->m_cont_dest= ip+1;
11379   return false;
11380 }
11381 
11382 
sp_if_expr(THD * thd)11383 bool sp_expr_lex::sp_if_expr(THD *thd)
11384 {
11385   uint ip= sphead->instructions();
11386   sp_instr_jump_if_not *i= new (thd->mem_root)
11387                            sp_instr_jump_if_not(ip, spcont, get_item(), this);
11388   return
11389     (unlikely(i == NULL) ||
11390     unlikely(sphead->push_backpatch(thd, i,
11391                                     spcont->push_label(thd, &empty_clex_str,
11392                                                        0))) ||
11393     unlikely(sphead->add_cont_backpatch(i)) ||
11394     unlikely(sphead->add_instr(i)));
11395 }
11396 
11397 
sp_if_after_statements(THD * thd)11398 bool LEX::sp_if_after_statements(THD *thd)
11399 {
11400   uint ip= sphead->instructions();
11401   sp_instr_jump *i= new (thd->mem_root) sp_instr_jump(ip, spcont);
11402   if (unlikely(i == NULL) ||
11403       unlikely(sphead->add_instr(i)))
11404     return true;
11405   sphead->backpatch(spcont->pop_label());
11406   sphead->push_backpatch(thd, i, spcont->push_label(thd, &empty_clex_str, 0));
11407   return false;
11408 }
11409 
11410 
stmt_signal_value(const Lex_ident_sys_st & ident)11411 sp_condition_value *LEX::stmt_signal_value(const Lex_ident_sys_st &ident)
11412 {
11413   sp_condition_value *cond;
11414   /* SIGNAL foo cannot be used outside of stored programs */
11415   if (unlikely(spcont == NULL))
11416   {
11417     my_error(ER_SP_COND_MISMATCH, MYF(0), ident.str);
11418     return NULL;
11419   }
11420   cond= spcont->find_declared_or_predefined_condition(thd, &ident);
11421   if (unlikely(cond == NULL))
11422   {
11423     my_error(ER_SP_COND_MISMATCH, MYF(0), ident.str);
11424     return NULL;
11425   }
11426   bool bad= thd->variables.sql_mode & MODE_ORACLE ?
11427             !cond->has_sql_state() :
11428             cond->type != sp_condition_value::SQLSTATE;
11429   if (unlikely(bad))
11430   {
11431     my_error(ER_SIGNAL_BAD_CONDITION_TYPE, MYF(0));
11432     return NULL;
11433   }
11434   return cond;
11435 }
11436 
11437 
add_table_foreign_key(const LEX_CSTRING * name,const LEX_CSTRING * constraint_name,Table_ident * ref_table_name,DDL_options ddl_options)11438 bool LEX::add_table_foreign_key(const LEX_CSTRING *name,
11439                                 const LEX_CSTRING *constraint_name,
11440                                 Table_ident *ref_table_name,
11441                                 DDL_options ddl_options)
11442 {
11443   Key *key= new (thd->mem_root) Foreign_key(name,
11444                                             &last_key->columns,
11445                                             constraint_name,
11446                                             &ref_table_name->db,
11447                                             &ref_table_name->table,
11448                                             &ref_list,
11449                                             fk_delete_opt,
11450                                             fk_update_opt,
11451                                             fk_match_option,
11452                                             ddl_options);
11453   if (unlikely(key == NULL))
11454     return true;
11455 
11456   /*
11457     handle_if_exists_options() expects the two keys in this order:
11458     the Foreign_key, followed by its auto-generated Key.
11459   */
11460   alter_info.key_list.push_back(key, thd->mem_root);
11461   alter_info.key_list.push_back(last_key, thd->mem_root);
11462 
11463   option_list= NULL;
11464 
11465   /* Only used for ALTER TABLE. Ignored otherwise. */
11466   alter_info.flags|= ALTER_ADD_FOREIGN_KEY;
11467 
11468   return false;
11469 }
11470 
11471 
add_column_foreign_key(const LEX_CSTRING * name,const LEX_CSTRING * constraint_name,Table_ident * ref_table_name,DDL_options ddl_options)11472 bool LEX::add_column_foreign_key(const LEX_CSTRING *name,
11473                                  const LEX_CSTRING *constraint_name,
11474                                  Table_ident *ref_table_name,
11475                                  DDL_options ddl_options)
11476 {
11477   if (last_field->vcol_info || last_field->vers_sys_field())
11478   {
11479     thd->parse_error();
11480     return true;
11481   }
11482   if (unlikely(!(last_key= (new (thd->mem_root)
11483                             Key(Key::MULTIPLE, constraint_name,
11484                             HA_KEY_ALG_UNDEF, true, ddl_options)))))
11485     return true;
11486   Key_part_spec *key= new (thd->mem_root) Key_part_spec(name, 0);
11487   if (unlikely(key == NULL))
11488     return true;
11489   last_key->columns.push_back(key, thd->mem_root);
11490   if (ref_list.is_empty())
11491   {
11492     ref_list.push_back(key, thd->mem_root);
11493   }
11494   if (unlikely(add_table_foreign_key(constraint_name, constraint_name,
11495                                      ref_table_name, ddl_options)))
11496       return true;
11497   option_list= NULL;
11498 
11499   /* Only used for ALTER TABLE. Ignored otherwise. */
11500   alter_info.flags|= ALTER_ADD_FOREIGN_KEY;
11501 
11502   return false;
11503 }
11504 
11505 
stmt_grant_table(THD * thd,Grant_privilege * grant,const Lex_grant_object_name & ident,privilege_t grant_option)11506 bool LEX::stmt_grant_table(THD *thd,
11507                            Grant_privilege *grant,
11508                            const Lex_grant_object_name &ident,
11509                            privilege_t grant_option)
11510 {
11511   sql_command= SQLCOM_GRANT;
11512   return
11513     grant->set_object_name(thd, ident, current_select, grant_option) ||
11514     !(m_sql_cmd= new (thd->mem_root) Sql_cmd_grant_table(sql_command, *grant));
11515 }
11516 
11517 
stmt_revoke_table(THD * thd,Grant_privilege * grant,const Lex_grant_object_name & ident)11518 bool LEX::stmt_revoke_table(THD *thd,
11519                             Grant_privilege *grant,
11520                             const Lex_grant_object_name &ident)
11521 {
11522   sql_command= SQLCOM_REVOKE;
11523   return
11524     grant->set_object_name(thd, ident, current_select, NO_ACL) ||
11525     !(m_sql_cmd= new (thd->mem_root) Sql_cmd_grant_table(sql_command, *grant));
11526 }
11527 
11528 
stmt_grant_sp(THD * thd,Grant_privilege * grant,const Lex_grant_object_name & ident,const Sp_handler & sph,privilege_t grant_option)11529 bool LEX::stmt_grant_sp(THD *thd,
11530                         Grant_privilege *grant,
11531                         const Lex_grant_object_name &ident,
11532                         const Sp_handler &sph,
11533                         privilege_t grant_option)
11534 {
11535   sql_command= SQLCOM_GRANT;
11536   return
11537     grant->set_object_name(thd, ident, current_select, grant_option) ||
11538     add_grant_command(thd, grant->columns()) ||
11539     !(m_sql_cmd= new (thd->mem_root) Sql_cmd_grant_sp(sql_command,
11540                                                       *grant, sph));
11541 }
11542 
11543 
stmt_revoke_sp(THD * thd,Grant_privilege * grant,const Lex_grant_object_name & ident,const Sp_handler & sph)11544 bool LEX::stmt_revoke_sp(THD *thd,
11545                          Grant_privilege *grant,
11546                          const Lex_grant_object_name &ident,
11547                          const Sp_handler &sph)
11548 {
11549   sql_command= SQLCOM_REVOKE;
11550   return
11551     grant->set_object_name(thd, ident, current_select, NO_ACL) ||
11552     add_grant_command(thd, grant->columns()) ||
11553     !(m_sql_cmd= new (thd->mem_root) Sql_cmd_grant_sp(sql_command,
11554                                                       *grant, sph));
11555 }
11556 
11557 
stmt_grant_proxy(THD * thd,LEX_USER * user,privilege_t grant_option)11558 bool LEX::stmt_grant_proxy(THD *thd, LEX_USER *user, privilege_t grant_option)
11559 {
11560   users_list.push_front(user);
11561   sql_command= SQLCOM_GRANT;
11562   return !(m_sql_cmd= new (thd->mem_root) Sql_cmd_grant_proxy(sql_command,
11563                                                               grant_option));
11564 }
11565 
11566 
stmt_revoke_proxy(THD * thd,LEX_USER * user)11567 bool LEX::stmt_revoke_proxy(THD *thd, LEX_USER *user)
11568 {
11569   users_list.push_front(user);
11570   sql_command= SQLCOM_REVOKE;
11571   return !(m_sql_cmd= new (thd->mem_root) Sql_cmd_grant_proxy(sql_command,
11572                                                               NO_ACL));
11573 }
11574 
11575 
current_user_for_set_password(THD * thd)11576 LEX_USER *LEX::current_user_for_set_password(THD *thd)
11577 {
11578   LEX_CSTRING pw= { STRING_WITH_LEN("password") };
11579   if (unlikely(spcont && spcont->find_variable(&pw, false)))
11580   {
11581     my_error(ER_SP_BAD_VAR_SHADOW, MYF(0), pw.str);
11582     return NULL;
11583   }
11584   LEX_USER *res;
11585   if (unlikely(!(res= (LEX_USER*) thd->calloc(sizeof(LEX_USER)))))
11586     return NULL;
11587   res->user= current_user;
11588   return res;
11589 }
11590 
11591 
sp_create_set_password_instr(THD * thd,LEX_USER * user,USER_AUTH * auth,bool no_lookahead)11592 bool LEX::sp_create_set_password_instr(THD *thd,
11593                                        LEX_USER *user,
11594                                        USER_AUTH *auth,
11595                                        bool no_lookahead)
11596 {
11597   user->auth= auth;
11598   set_var_password *var= new (thd->mem_root) set_var_password(user);
11599   if (unlikely(var == NULL) ||
11600       unlikely(var_list.push_back(var, thd->mem_root)))
11601     return true;
11602   autocommit= true;
11603   if (sphead)
11604     sphead->m_flags|= sp_head::HAS_SET_AUTOCOMMIT_STMT;
11605   return sp_create_assignment_instr(thd, no_lookahead);
11606 }
11607 
11608 
map_data_type(const Lex_ident_sys_st & schema_name,Lex_field_type_st * type) const11609 bool LEX::map_data_type(const Lex_ident_sys_st &schema_name,
11610                         Lex_field_type_st *type) const
11611 {
11612   const Schema *schema= schema_name.str ?
11613                         Schema::find_by_name(schema_name) :
11614                         Schema::find_implied(thd);
11615   if (!schema)
11616   {
11617     char buf[128];
11618     const Name type_name= type->type_handler()->name();
11619     my_snprintf(buf, sizeof(buf), "%.*s.%.*s",
11620                 (int) schema_name.length, schema_name.str,
11621                 (int) type_name.length(), type_name.ptr());
11622     my_error(ER_UNKNOWN_DATA_TYPE, MYF(0), buf);
11623     return true;
11624   }
11625   const Type_handler *mapped= schema->map_data_type(thd, type->type_handler());
11626   type->set_handler(mapped);
11627   return false;
11628 }
11629 
11630 
explainable() const11631 bool SELECT_LEX_UNIT::explainable() const
11632 {
11633   /*
11634     EXPLAIN/ANALYZE unit, when:
11635     (1) if it's a subquery - it's not part of eliminated WHERE/ON clause.
11636     (2) if it's a CTE - it's not hanging (needed for execution)
11637     (3) if it's a derived - it's not merged
11638     if it's not 1/2/3 - it's some weird internal thing, ignore it
11639   */
11640   return item ?
11641            !item->eliminated :                        // (1)
11642            with_element ?
11643              derived && derived->derived_result &&
11644                !with_element->is_hanging_recursive(): // (2)
11645              derived ?
11646                derived->is_materialized_derived() :   // (3)
11647                false;
11648 }
11649