1 /* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
2 
3    This program is free software; you can redistribute it and/or modify
4    it under the terms of the GNU General Public License, version 2.0,
5    as published by the Free Software Foundation.
6 
7    This program is also distributed with certain software (including
8    but not limited to OpenSSL) that is licensed under separate terms,
9    as designated in a particular file or component or in included license
10    documentation.  The authors of MySQL hereby grant you an additional
11    permission to link the program and your derivative works with the
12    separately licensed software that they have included with MySQL.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License, version 2.0, for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
22 
23 #include "my_global.h"    // NO_EMBEDDED_ACCESS_CHECKS
24 #include "sp_instr.h"
25 #include "item.h"         // Item_splocal
26 #include "log.h"          // query_logger
27 #include "opt_trace.h"    // opt_trace_disable_etc
28 #include "probes_mysql.h" // MYSQL_QUERY_EXEC_START
29 #include "sp_head.h"      // sp_head
30 #include "sp.h"           // sp_get_item_value
31 #include "sp_rcontext.h"  // sp_rcontext
32 #include "auth_common.h"  // SELECT_ACL
33 #include "sql_base.h"     // open_temporary_tables
34 #include "sql_parse.h"    // check_table_access
35 #include "sql_prepare.h"  // reinit_stmt_before_use
36 #include "transaction.h"  // trans_commit_stmt
37 #include "prealloced_array.h"
38 #include "binlog.h"
39 #include "item_cmpfunc.h" // Item_func_eq
40 #include "debug_sync.h"   // DEBUG_SYNC
41 
42 #include <algorithm>
43 #include <functional>
44 
45 #include "trigger.h"                  // Trigger
46 #include "table_trigger_dispatcher.h" // Table_trigger_dispatcher
47 
48 
49 class Cmp_splocal_locations :
50   public std::binary_function<const Item_splocal*, const Item_splocal*, bool>
51 {
52 public:
operator ()(const Item_splocal * a,const Item_splocal * b)53   bool operator()(const Item_splocal *a, const Item_splocal *b)
54   {
55     DBUG_ASSERT(a == b || a->pos_in_query != b->pos_in_query);
56     return a->pos_in_query < b->pos_in_query;
57   }
58 };
59 
60 /*
61   StoredRoutinesBinlogging
62   This paragraph applies only to statement-based binlogging. Row-based
63   binlogging does not need anything special like this except for a special
64   case that is mentioned below in section 2.1
65 
66   Top-down overview:
67 
68   1. Statements
69 
70   Statements that have is_update_query(stmt) == TRUE are written into the
71   binary log verbatim.
72   Examples:
73     UPDATE tbl SET tbl.x = spfunc_w_side_effects()
74     UPDATE tbl SET tbl.x=1 WHERE spfunc_w_side_effect_that_returns_false(tbl.y)
75 
76   Statements that have is_update_query(stmt) == FALSE (e.g. SELECTs) are not
77   written into binary log. Instead we catch function calls the statement
78   makes and write it into binary log separately (see #3).
79 
80   2. PROCEDURE calls
81 
82   CALL statements are not written into binary log. Instead
83   * Any FUNCTION invocation (in SET, IF, WHILE, OPEN CURSOR and other SP
84     instructions) is written into binlog separately.
85 
86   * Each statement executed in SP is binlogged separately, according to rules
87     in #1, with the exception that we modify query string: we replace uses
88     of SP local variables with NAME_CONST('spvar_name', <spvar-value>) calls.
89     This substitution is done in subst_spvars().
90 
91   2.1 Miscellaneous case: DDLs (Eg: ALTER EVENT) in StoredProcedure(SP) uses
92       its local variables
93 
94   * Irrespective of binlog format, DDLs are always binlogged in statement mode.
95     Hence if there are any DDLs, in stored procedure, that uses SP local
96     variables,  those should be replaced with NAME_CONST('spvar_name', <spvar-value>)
97     even if binlog format is 'row'.
98 
99   3. FUNCTION calls
100 
101   In sp_head::execute_function(), we check
102    * If this function invocation is done from a statement that is written
103      into the binary log.
104    * If there were any attempts to write events to the binary log during
105      function execution (grep for start_union_events and stop_union_events)
106 
107    If the answers are No and Yes, we write the function call into the binary
108    log as "SELECT spfunc(<param1value>, <param2value>, ...)"
109 
110 
111   4. Miscellaneous issues.
112 
113   4.1 User variables.
114 
115   When we call mysql_bin_log.write() for an SP statement, thd->user_var_events
116   must hold set<{var_name, value}> pairs for all user variables used during
117   the statement execution.
118   This set is produced by tracking user variable reads during statement
119   execution.
120 
121   For SPs, this has the following implications:
122   1) thd->user_var_events may contain events from several SP statements and
123      needs to be valid after execution of these statements was finished. In
124      order to achieve that, we
125      * Allocate user_var_events array elements on appropriate mem_root (grep
126        for user_var_events_alloc).
127      * Use is_query_in_union() to determine if user_var_event is created.
128 
129   2) We need to empty thd->user_var_events after we have wrote a function
130      call. This is currently done by making
131      reset_dynamic(&thd->user_var_events);
132      calls in several different places. (TODO consider moving this into
133      mysql_bin_log.write() function)
134 
135   4.2 Auto_increment storage in binlog
136 
137   As we may write two statements to binlog from one single logical statement
138   (case of "SELECT func1(),func2()": it is binlogged as "SELECT func1()" and
139   then "SELECT func2()"), we need to reset auto_increment binlog variables
140   after each binlogged SELECT. Otherwise, the auto_increment value of the
141   first SELECT would be used for the second too.
142 */
143 
144 /**
145   Replace thd->query{_length} with a string that one can write to
146   the binlog.
147 
148   The binlog-suitable string is produced by replacing references to SP local
149   variables with NAME_CONST('sp_var_name', value) calls.
150 
151   @param thd        Current thread.
152   @param instr      Instruction (we look for Item_splocal instances in
153                     instr->free_list)
154   @param query_str  Original query string
155 
156   @retval false on success.
157   thd->query{_length} either has been appropriately replaced or there
158   is no need for replacements.
159 
160   @retval true in case of out of memory error.
161 */
subst_spvars(THD * thd,sp_instr * instr,LEX_STRING * query_str)162 static bool subst_spvars(THD *thd, sp_instr *instr, LEX_STRING *query_str)
163 {
164   // Stack-local array, does not need instrumentation.
165   Prealloced_array<Item_splocal*, 16> sp_vars_uses(PSI_NOT_INSTRUMENTED);
166 
167   /* Find all instances of Item_splocal used in this statement */
168   for (Item *item= instr->free_list; item; item= item->next)
169   {
170     if (item->is_splocal())
171     {
172       Item_splocal *item_spl= (Item_splocal*)item;
173       if (item_spl->pos_in_query)
174         sp_vars_uses.push_back(item_spl);
175     }
176   }
177 
178   if (sp_vars_uses.empty())
179     return false;
180 
181   /* Sort SP var refs by their occurrences in the query */
182   std::sort(sp_vars_uses.begin(), sp_vars_uses.end(), Cmp_splocal_locations());
183 
184   /*
185     Construct a statement string where SP local var refs are replaced
186     with "NAME_CONST(name, value)"
187   */
188   char buffer[512];
189   String qbuf(buffer, sizeof(buffer), &my_charset_bin);
190   qbuf.length(0);
191   char *cur= query_str->str;
192   int prev_pos= 0;
193   int res= 0;
194   thd->query_name_consts= 0;
195 
196   for (Item_splocal **splocal= sp_vars_uses.begin();
197        splocal != sp_vars_uses.end(); splocal++)
198   {
199     Item *val;
200 
201     char str_buffer[STRING_BUFFER_USUAL_SIZE];
202     String str_value_holder(str_buffer, sizeof(str_buffer),
203                             &my_charset_latin1);
204     String *str_value;
205 
206     /* append the text between sp ref occurrences */
207     res|= qbuf.append(cur + prev_pos, (*splocal)->pos_in_query - prev_pos);
208     prev_pos= (*splocal)->pos_in_query + (*splocal)->len_in_query;
209 
210     res|= (*splocal)->fix_fields(thd, (Item **) splocal);
211     if (res)
212       break;
213 
214     if ((*splocal)->limit_clause_param)
215     {
216       res|= qbuf.append_ulonglong((*splocal)->val_uint());
217       if (res)
218         break;
219       continue;
220     }
221 
222     /* append the spvar substitute */
223     res|= qbuf.append(STRING_WITH_LEN(" NAME_CONST('"));
224     res|= qbuf.append((*splocal)->m_name);
225     res|= qbuf.append(STRING_WITH_LEN("',"));
226 
227     if (res)
228       break;
229 
230     val= (*splocal)->this_item();
231     str_value= sp_get_item_value(thd, val, &str_value_holder);
232     if (str_value)
233       res|= qbuf.append(*str_value);
234     else
235       res|= qbuf.append(STRING_WITH_LEN("NULL"));
236     res|= qbuf.append(')');
237     if (res)
238       break;
239 
240     thd->query_name_consts++;
241   }
242   if (res ||
243       qbuf.append(cur + prev_pos, query_str->length - prev_pos))
244     return true;
245 
246   char *pbuf;
247   if ((pbuf= static_cast<char*>(thd->alloc(qbuf.length() + 1))))
248   {
249     memcpy(pbuf, qbuf.ptr(), qbuf.length());
250     pbuf[qbuf.length()]= 0;
251   }
252   else
253     return true;
254 
255   thd->set_query(pbuf, qbuf.length());
256 
257   return false;
258 }
259 
260 ///////////////////////////////////////////////////////////////////////////
261 // Sufficient max length of printed destinations and frame offsets (all uints).
262 ///////////////////////////////////////////////////////////////////////////
263 
264 #define SP_INSTR_UINT_MAXLEN  8
265 #define SP_STMT_PRINT_MAXLEN 40
266 
267 ///////////////////////////////////////////////////////////////////////////
268 // sp_lex_instr implementation.
269 ///////////////////////////////////////////////////////////////////////////
270 
271 
272 class SP_instr_error_handler : public Internal_error_handler
273 {
274 public:
SP_instr_error_handler()275   SP_instr_error_handler()
276     : cts_table_exists_error(false)
277   {}
278 
handle_condition(THD * thd,uint sql_errno,const char *,Sql_condition::enum_severity_level *,const char *)279   virtual bool handle_condition(THD *thd,
280                                 uint sql_errno,
281                                 const char*,
282                                 Sql_condition::enum_severity_level*,
283                                 const char*)
284   {
285     /*
286       Check if the "table exists" error or warning reported for the
287       CREATE TABLE ... SELECT statement.
288     */
289     if (thd->lex && thd->lex->sql_command == SQLCOM_CREATE_TABLE &&
290         thd->lex->select_lex && thd->lex->select_lex->item_list.elements > 0 &&
291         sql_errno == ER_TABLE_EXISTS_ERROR)
292       cts_table_exists_error= true;
293 
294     return false;
295   }
296 
297   bool cts_table_exists_error;
298 };
299 
300 
reset_lex_and_exec_core(THD * thd,uint * nextp,bool open_tables)301 bool sp_lex_instr::reset_lex_and_exec_core(THD *thd,
302                                            uint *nextp,
303                                            bool open_tables)
304 {
305   /*
306     The flag is saved at the entry to the following substatement.
307     It's reset further in the common code part.
308     It's merged with the saved parent's value at the exit of this func.
309   */
310 
311   unsigned int parent_unsafe_rollback_flags=
312     thd->get_transaction()->get_unsafe_rollback_flags(Transaction_ctx::STMT);
313   thd->get_transaction()->reset_unsafe_rollback_flags(Transaction_ctx::STMT);
314 
315   /* Check pre-conditions. */
316 
317   DBUG_ASSERT(!thd->derived_tables);
318   DBUG_ASSERT(thd->change_list.is_empty());
319 
320   /*
321     Use our own lex.
322 
323     Although it is saved/restored in sp_head::execute() when we are
324     entering/leaving routine, it's still should be saved/restored here,
325     in order to properly behave in case of ER_NEED_REPREPARE error
326     (when ER_NEED_REPREPARE happened, and we failed to re-parse the query).
327   */
328 
329   LEX *lex_saved= thd->lex;
330   thd->lex= m_lex;
331 
332   /* Set new query id. */
333 
334   thd->set_query_id(next_query_id());
335 
336   if (thd->locked_tables_mode <= LTM_LOCK_TABLES)
337   {
338     /*
339       This statement will enter/leave prelocked mode on its own.
340       Entering prelocked mode changes table list and related members
341       of LEX, so we'll need to restore them.
342     */
343     if (m_lex_query_tables_own_last)
344     {
345       /*
346         We've already entered/left prelocked mode with this statement.
347         Attach the list of tables that need to be prelocked and mark m_lex
348         as having such list attached.
349       */
350       *m_lex_query_tables_own_last= m_prelocking_tables;
351       m_lex->mark_as_requiring_prelocking(m_lex_query_tables_own_last);
352     }
353   }
354 
355   bool error= reinit_stmt_before_use(thd, m_lex);
356 
357   /*
358     In case a session state exists do not cache the SELECT stmt. If we
359     cache SELECT statment when session state information exists, then
360     the result sets of this SELECT are cached which contains changed
361     session information. Next time when same query is executed when there
362     is no change in session state, then result sets are picked from cache
363     which is wrong as the result sets picked from cache have changed
364     state information.
365     In case of embedded server since session state information is not
366     sent there is no need to turn off cache.
367   */
368 
369 #ifndef EMBEDDED_LIBRARY
370   if (thd->get_protocol()->has_client_capability(CLIENT_SESSION_TRACK) &&
371       thd->session_tracker.enabled_any() &&
372       thd->session_tracker.changed_any())
373     thd->lex->safe_to_cache_query= 0;
374 #endif
375 
376   SP_instr_error_handler sp_instr_error_handler;
377   thd->push_internal_handler(&sp_instr_error_handler);
378 
379   /* Open tables if needed. */
380 
381   if (!error)
382   {
383     if (open_tables)
384     {
385       // todo: break this block out into a separate function.
386       /*
387         IF, CASE, DECLARE, SET, RETURN, have 'open_tables' true; they may
388         have a subquery in parameter and are worth tracing. They don't
389         correspond to a SQL command so we pretend that they are SQLCOM_SELECT.
390       */
391       Opt_trace_start ots(thd, m_lex->query_tables, SQLCOM_SELECT,
392                           &m_lex->var_list, NULL, 0, this,
393                           thd->variables.character_set_client);
394       Opt_trace_object trace_command(&thd->opt_trace);
395       Opt_trace_array trace_command_steps(&thd->opt_trace, "steps");
396 
397       /*
398         Check whenever we have access to tables for this statement
399         and open and lock them before executing instructions core function.
400         If we are not opening any tables, we don't need to check permissions
401         either.
402       */
403       if (m_lex->query_tables)
404         error= (open_temporary_tables(thd, m_lex->query_tables) ||
405                 check_table_access(thd, SELECT_ACL, m_lex->query_tables, false,
406                                    UINT_MAX, false));
407 
408       if (!error)
409         error= open_and_lock_tables(thd, m_lex->query_tables, 0);
410 
411       if (!error)
412       {
413         error= exec_core(thd, nextp);
414         DBUG_PRINT("info",("exec_core returned: %d", error));
415       }
416 
417       /*
418         Call after unit->cleanup() to close open table
419         key read.
420       */
421 
422       m_lex->unit->cleanup(true);
423 
424       /* Here we also commit or rollback the current statement. */
425 
426       if (! thd->in_sub_stmt)
427       {
428         thd->get_stmt_da()->set_overwrite_status(true);
429         thd->is_error() ? trans_rollback_stmt(thd) : trans_commit_stmt(thd);
430         thd->get_stmt_da()->set_overwrite_status(false);
431       }
432       thd_proc_info(thd, "closing tables");
433       close_thread_tables(thd);
434       thd_proc_info(thd, 0);
435 
436       if (! thd->in_sub_stmt)
437       {
438         if (thd->transaction_rollback_request)
439         {
440           trans_rollback_implicit(thd);
441           thd->mdl_context.release_transactional_locks();
442         }
443         else if (! thd->in_multi_stmt_transaction_mode())
444           thd->mdl_context.release_transactional_locks();
445         else
446           thd->mdl_context.release_statement_locks();
447       }
448     }
449     else
450     {
451       DEBUG_SYNC(thd, "sp_lex_instr_before_exec_core");
452       error= exec_core(thd, nextp);
453       DBUG_PRINT("info",("exec_core returned: %d", error));
454     }
455   }
456 
457   // Pop SP_instr_error_handler error handler.
458   thd->pop_internal_handler();
459 
460   if (m_lex->query_tables_own_last)
461   {
462     /*
463       We've entered and left prelocking mode when executing statement
464       stored in m_lex.
465       m_lex->query_tables(->next_global)* list now has a 'tail' - a list
466       of tables that are added for prelocking. (If this is the first
467       execution, the 'tail' was added by open_tables(), otherwise we've
468       attached it above in this function).
469       Now we'll save the 'tail', and detach it.
470     */
471     m_lex_query_tables_own_last= m_lex->query_tables_own_last;
472     m_prelocking_tables= *m_lex_query_tables_own_last;
473     *m_lex_query_tables_own_last= NULL;
474     m_lex->mark_as_requiring_prelocking(NULL);
475   }
476 
477   /* Rollback changes to the item tree during execution. */
478 
479   thd->rollback_item_tree_changes();
480 
481   /*
482     Change state of current arena according to outcome of execution.
483 
484     When entering this function, state is STMT_INITIALIZED_FOR_SP if this is
485     the first execution, otherwise it is STMT_EXECUTED.
486 
487     When an error occurs during opening tables, no execution takes place and
488     no state change will take place.
489 
490     When a re-prepare error is raised, the next execution will re-prepare the
491     statement. To make sure that items are created in the statement mem_root,
492     change state to STMT_INITIALIZED_FOR_SP.
493 
494     In other cases, the state should become (or remain) STMT_EXECUTED.
495     See Query_arena->state definition for explanation.
496 
497     Some special handling of CREATE TABLE .... SELECT in an SP is required. The
498     state is set to STMT_INITIALIZED_FOR_SP even in case of "table exists"
499     error situation.
500 
501     Why is this necessary? A useful pointer would be to note how
502     PREPARE/EXECUTE uses functions like select_like_stmt_test to implement
503     CREATE TABLE .... SELECT. The SELECT part of the DDL is resolved first.
504     Then there is an attempt to create the table. So in the execution phase,
505     if "table exists" error occurs or flush table preceeds the execute, the
506     item tree of the select is re-created and followed by an attempt to create
507     the table.
508 
509     But SP uses mysql_execute_command (which is used by the conventional
510     execute) after doing a parse. This creates a problem for SP since it
511     tries to preserve the item tree from the previous execution.
512   */
513 
514   bool reprepare_error=
515     error && thd->is_error() &&
516     thd->get_stmt_da()->mysql_errno() == ER_NEED_REPREPARE;
517 
518   if (reprepare_error || sp_instr_error_handler.cts_table_exists_error)
519     thd->stmt_arena->state= Query_arena::STMT_INITIALIZED_FOR_SP;
520   else if (!error || !thd->is_error() ||
521            (thd->get_stmt_da()->mysql_errno() != ER_CANT_REOPEN_TABLE &&
522             thd->get_stmt_da()->mysql_errno() != ER_NO_SUCH_TABLE &&
523             thd->get_stmt_da()->mysql_errno() != ER_UPDATE_TABLE_USED))
524     thd->stmt_arena->state= Query_arena::STMT_EXECUTED;
525 
526   /*
527     Merge here with the saved parent's values
528     what is needed from the substatement gained
529   */
530 
531   thd->get_transaction()->add_unsafe_rollback_flags(
532     Transaction_ctx::STMT,
533     parent_unsafe_rollback_flags);
534 
535   if (thd->variables.session_track_transaction_info > TX_TRACK_NONE)
536   {
537     ((Transaction_state_tracker *)
538      thd->session_tracker.get_tracker(TRANSACTION_INFO_TRACKER))
539       ->add_trx_state_from_thd(thd);
540   }
541 
542   /* Restore original lex. */
543 
544   thd->lex= lex_saved;
545 
546   /*
547     Unlike for PS we should not call Item's destructors for newly created
548     items after execution of each instruction in stored routine. This is
549     because SP often create Item (like Item_int, Item_string etc...) when
550     they want to store some value in local variable, pass return value and
551     etc... So their life time should be longer than one instruction.
552 
553     cleanup_items() is called in sp_head::execute()
554   */
555 
556   return error || thd->is_error();
557 }
558 
559 
parse_expr(THD * thd,sp_head * sp)560 LEX *sp_lex_instr::parse_expr(THD *thd, sp_head *sp)
561 {
562   String sql_query;
563   sql_digest_state *parent_digest= thd->m_digest;
564   PSI_statement_locker *parent_locker= thd->m_statement_psi;
565   SQL_I_List<Item_trigger_field> *next_trig_list_bkp= NULL;
566   sql_query.set_charset(system_charset_info);
567 
568   get_query(&sql_query);
569 
570   if (sql_query.length() == 0)
571   {
572     // The instruction has returned zero-length query string. That means, the
573     // re-preparation of the instruction is not possible. We should not come
574     // here in the normal life.
575     DBUG_ASSERT(false);
576     my_error(ER_UNKNOWN_ERROR, MYF(0));
577     return NULL;
578   }
579 
580   if (m_trig_field_list.elements)
581     next_trig_list_bkp= m_trig_field_list.first->next_trig_field_list;
582   // Cleanup current THD from previously held objects before new parsing.
583   cleanup_before_parsing(thd);
584 
585   // Cleanup and re-init the lex mem_root for re-parse.
586   free_root(&m_lex_mem_root, MYF(0));
587   init_sql_alloc(PSI_NOT_INSTRUMENTED, &m_lex_mem_root,
588                  MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC);
589 
590   /*
591     Switch mem-roots. We store the new LEX and its Items in the
592     m_lex_mem_root since it is freed before reparse triggered due to
593     invalidation. This avoids the memory leak in case re-parse is
594     initiated. Also set the statement query arena to the lex mem_root.
595   */
596   MEM_ROOT *execution_mem_root= thd->mem_root;
597   Query_arena parse_arena(&m_lex_mem_root, thd->stmt_arena->state);
598 
599   thd->mem_root= &m_lex_mem_root;
600   thd->stmt_arena->set_query_arena(&parse_arena);
601 
602   // Prepare parser state. It can be done just before parse_sql(), do it here
603   // only to simplify exit in case of failure (out-of-memory error).
604 
605   Parser_state parser_state;
606 
607   if (parser_state.init(thd, sql_query.c_ptr(), sql_query.length()))
608     return NULL;
609 
610   // Switch THD::free_list. It's used to remember the newly created set of Items
611   // during parsing. We should clean those items after each execution.
612 
613   Item *execution_free_list= thd->free_list;
614   thd->free_list= NULL;
615 
616   // Create a new LEX and intialize it.
617 
618   LEX *lex_saved= thd->lex;
619 
620   thd->lex= new (thd->mem_root) st_lex_local;
621   lex_start(thd);
622 
623   thd->lex->sphead= sp;
624   thd->lex->set_sp_current_parsing_ctx(get_parsing_ctx());
625   sp->m_parser_data.set_current_stmt_start_ptr(sql_query.c_ptr());
626 
627   // Parse the just constructed SELECT-statement.
628 
629   thd->m_digest= NULL;
630   thd->m_statement_psi= NULL;
631   bool parsing_failed= parse_sql(thd, &parser_state, NULL);
632   thd->m_digest= parent_digest;
633   thd->m_statement_psi= parent_locker;
634 
635   if (!parsing_failed)
636   {
637     thd->lex->set_trg_event_type_for_tables();
638 
639     // Call after-parsing callback.
640     parsing_failed= on_after_expr_parsing(thd);
641 
642     if (sp->m_type == SP_TYPE_TRIGGER)
643     {
644       /*
645         Also let us bind these objects to Field objects in table being opened.
646 
647         We ignore errors of setup_field() here, because if even something is
648         wrong we still will be willing to open table to perform some operations
649         (e.g.  SELECT)... Anyway some things can be checked only during trigger
650         execution.
651       */
652 
653       Trigger *t= sp->m_trg_list->find_trigger(thd->lex->sphead->m_name);
654 
655       DBUG_ASSERT(t);
656 
657       if (!t)
658         return NULL; // Don't take chances in production.
659 
660       for (Item_trigger_field *trg_fld= sp->m_cur_instr_trig_field_items.first;
661            trg_fld;
662            trg_fld= trg_fld->next_trg_field)
663       {
664         trg_fld->setup_field(thd, sp->m_trg_list->get_trigger_field_support(),
665                              t->get_subject_table_grant());
666       }
667 
668       /**
669         Move Item_trigger_field's list to instruction's Item_trigger_field
670         list.
671       */
672       if (sp->m_cur_instr_trig_field_items.elements)
673       {
674         sp->m_cur_instr_trig_field_items.save_and_clear(&m_trig_field_list);
675         m_trig_field_list.first->next_trig_field_list= next_trig_list_bkp;
676       }
677     }
678 
679     // Append newly created Items to the list of Items, owned by this
680     // instruction.
681     free_list= thd->free_list;
682   }
683 
684   // Restore THD::lex.
685 
686   thd->lex->sphead= NULL;
687   thd->lex->set_sp_current_parsing_ctx(NULL);
688 
689   LEX *expr_lex= thd->lex;
690   thd->lex= lex_saved;
691 
692   // Restore execution mem-root and THD::free_list.
693 
694   thd->mem_root= execution_mem_root;
695   thd->free_list= execution_free_list;
696 
697   // That's it.
698 
699   return parsing_failed ? NULL : expr_lex;
700 }
701 
702 
validate_lex_and_execute_core(THD * thd,uint * nextp,bool open_tables)703 bool sp_lex_instr::validate_lex_and_execute_core(THD *thd,
704                                                  uint *nextp,
705                                                  bool open_tables)
706 {
707   Reprepare_observer reprepare_observer;
708   int reprepare_attempt= 0;
709 
710   while (true)
711   {
712     DBUG_EXECUTE_IF("simulate_bug18831513", { invalidate(); });
713     if (is_invalid())
714     {
715       LEX *lex= parse_expr(thd, thd->sp_runtime_ctx->sp);
716 
717       if (!lex)
718         return true;
719 
720       set_lex(lex, true);
721 
722       m_first_execution= true;
723     }
724 
725     /*
726       Install the metadata observer. If some metadata version is
727       different from prepare time and an observer is installed,
728       the observer method will be invoked to push an error into
729       the error stack.
730     */
731     Reprepare_observer *stmt_reprepare_observer= NULL;
732 
733     /*
734       Meta-data versions are stored in the LEX-object on the first execution.
735       Thus, the reprepare observer should not be installed for the first
736       execution, because it will always be triggered.
737 
738       Then, the reprepare observer should be installed for the statements, which
739       are marked by CF_REEXECUTION_FRAGILE (@sa CF_REEXECUTION_FRAGILE) or if
740       the SQL-command is SQLCOM_END, which means that the LEX-object is
741       representing an expression, so the exact SQL-command does not matter.
742     */
743 
744     if (!m_first_execution &&
745         (sql_command_flags[m_lex->sql_command] & CF_REEXECUTION_FRAGILE ||
746          m_lex->sql_command == SQLCOM_END))
747     {
748       reprepare_observer.reset_reprepare_observer();
749       stmt_reprepare_observer= &reprepare_observer;
750     }
751 
752     thd->push_reprepare_observer(stmt_reprepare_observer);
753 
754     bool rc= reset_lex_and_exec_core(thd, nextp, open_tables);
755 
756     thd->pop_reprepare_observer();
757 
758     m_first_execution= false;
759 
760     if (!rc)
761       return false;
762 
763     /*
764       Here is why we need all the checks below:
765         - if the reprepare observer is not set, we've got an error, which should
766           be raised to the user;
767         - if we've got fatal error, it should be raised to the user;
768         - if our thread got killed during execution, the error should be raised
769           to the user;
770         - if we've got an error, different from ER_NEED_REPREPARE, we need to
771           raise it to the user;
772         - we take only 3 attempts to reprepare the query, otherwise we might end
773           up in the endless loop.
774     */
775     if (stmt_reprepare_observer &&
776         !thd->is_fatal_error &&
777         !thd->killed &&
778         thd->get_stmt_da()->mysql_errno() == ER_NEED_REPREPARE &&
779         reprepare_attempt++ < 3)
780     {
781       DBUG_ASSERT(stmt_reprepare_observer->is_invalidated());
782 
783       thd->clear_error();
784       free_lex();
785       invalidate();
786     }
787     else
788       return true;
789   }
790 }
791 
792 
set_lex(LEX * lex,bool is_lex_owner)793 void sp_lex_instr::set_lex(LEX *lex, bool is_lex_owner)
794 {
795   free_lex();
796 
797   m_lex= lex;
798   m_is_lex_owner= is_lex_owner;
799   m_lex_query_tables_own_last= NULL;
800 
801   if (m_lex)
802     m_lex->sp_lex_in_use= true;
803 }
804 
805 
free_lex()806 void sp_lex_instr::free_lex()
807 {
808   if (!m_is_lex_owner || !m_lex)
809     return;
810 
811   /* Prevent endless recursion. */
812   m_lex->sphead= NULL;
813   lex_end(m_lex);
814   delete (st_lex_local *) m_lex;
815 
816   m_lex= NULL;
817   m_is_lex_owner= false;
818   m_lex_query_tables_own_last= NULL;
819 }
820 
821 
cleanup_before_parsing(THD * thd)822 void sp_lex_instr::cleanup_before_parsing(THD *thd)
823 {
824   /*
825     Destroy items in the instruction's free list before re-parsing the
826     statement query string (and thus, creating new items).
827   */
828   free_items();
829 
830   // Remove previously stored trigger-field items.
831   sp_head *sp= thd->sp_runtime_ctx->sp;
832 
833   if (sp->m_type == SP_TYPE_TRIGGER)
834     m_trig_field_list.empty();
835 }
836 
837 
get_query(String * sql_query) const838 void sp_lex_instr::get_query(String *sql_query) const
839 {
840   LEX_STRING expr_query= this->get_expr_query();
841 
842   if (!expr_query.str)
843   {
844     sql_query->length(0);
845     return;
846   }
847 
848   sql_query->append("SELECT ");
849   sql_query->append(expr_query.str, expr_query.length);
850 }
851 
852 
853 ///////////////////////////////////////////////////////////////////////////
854 // sp_instr_stmt implementation.
855 ///////////////////////////////////////////////////////////////////////////
856 
857 #ifdef HAVE_PSI_INTERFACE
858 PSI_statement_info sp_instr_stmt::psi_info=
859 { 0, "stmt", 0};
860 #endif
861 
execute(THD * thd,uint * nextp)862 bool sp_instr_stmt::execute(THD *thd, uint *nextp)
863 {
864   bool need_subst= false;
865   bool rc= false;
866 
867   DBUG_PRINT("info", ("query: '%.*s'", (int) m_query.length, m_query.str));
868 
869   thd->set_query_for_display(m_query.str, m_query.length);
870 
871   const LEX_CSTRING query_backup= thd->query();
872 
873 #if defined(ENABLED_PROFILING)
874   /* This SP-instr is profilable and will be captured. */
875   thd->profiling.set_query_source(m_query.str, m_query.length);
876 #endif
877 
878   /*
879     If we can't set thd->query_string at all, we give up on this statement.
880   */
881   if (alloc_query(thd, m_query.str, m_query.length))
882     return true;
883 
884   /*
885     Check whether we actually need a substitution of SP variables with
886     NAME_CONST(...) (using subst_spvars()).
887     If both of the following apply, we won't need to substitute:
888 
889     - general log is off
890 
891     - binary logging is off
892 
893     - if the query generates row events in binlog row format mode
894     (DDLs are always written in statement format irrespective of binlog_format
895     and they can have SP variables in it. For example, 'ALTER EVENT' is allowed
896     inside a procedure and can contain SP variables in it. Those too need to be
897     substituted with NAME_CONST(...))
898 
899     We don't have to substitute on behalf of the query cache as
900     queries with SP vars are not cached, anyway.
901 
902     query_name_consts is used elsewhere in a special case concerning
903     CREATE TABLE, but we do not need to do anything about that here.
904 
905     The slow query log is another special case: we won't know whether a
906     query qualifies for the slow query log until after it's been
907     executed. We assume that most queries are not slow, so we do not
908     pre-emptively substitute just for the slow query log. If a query
909     ends up being slow after all and we haven't done the substitution
910     already for any of the above (general log etc.), we'll do the
911     substitution immediately before writing to the log.
912   */
913 
914   need_subst= !((thd->variables.option_bits & OPTION_LOG_OFF) &&
915                (!(thd->variables.option_bits & OPTION_BIN_LOG) ||
916                 !mysql_bin_log.is_open() ||
917                 (thd->is_current_stmt_binlog_format_row() &&
918                  sqlcom_can_generate_row_events(m_lex->sql_command))));
919 
920   /*
921     If we need to do a substitution but can't (OOM), give up.
922   */
923 
924   if (need_subst && subst_spvars(thd, this, &m_query))
925     return true;
926 
927   /*
928     (the order of query cache and subst_spvars calls is irrelevant because
929     queries with SP vars can't be cached)
930   */
931   if (unlikely((thd->variables.option_bits & OPTION_LOG_OFF)==0))
932     query_logger.general_log_write(thd, COM_QUERY, thd->query().str,
933                                    thd->query().length);
934 
935   if (query_cache.send_result_to_client(thd, thd->query()) <= 0)
936   {
937     rc= validate_lex_and_execute_core(thd, nextp, false);
938 
939     if (thd->get_stmt_da()->is_eof())
940     {
941       /* Finalize server status flags after executing a statement. */
942       thd->update_server_status();
943 
944       thd->send_statement_status();
945     }
946 
947     query_cache.end_of_result(thd);
948 
949     if (!rc && unlikely(log_slow_applicable(thd)))
950     {
951       /*
952         We actually need to write the slow log. Check whether we already
953         called subst_spvars() above, otherwise, do it now.  In the highly
954         unlikely event of subst_spvars() failing (OOM), we'll try to log
955         the unmodified statement instead.
956       */
957       if (!need_subst)
958         rc= subst_spvars(thd, this, &m_query);
959       log_slow_do(thd);
960     }
961 
962     /*
963       With the current setup, a subst_spvars() and a mysql_rewrite_query()
964       (rewriting passwords etc.) will not both happen to a query.
965       If this ever changes, we give the engineer pause here so they will
966       double-check whether the potential conflict they created is a
967       problem.
968     */
969     DBUG_ASSERT((thd->query_name_consts == 0) ||
970                 (thd->rewritten_query().length() == 0));
971   }
972   else
973     *nextp= get_ip() + 1;
974 
975   thd->set_query(query_backup);
976   thd->query_name_consts= 0;
977 
978   return rc || thd->is_error();
979 }
980 
981 
print(String * str)982 void sp_instr_stmt::print(String *str)
983 {
984   /* stmt CMD "..." */
985   if (str->reserve(SP_STMT_PRINT_MAXLEN + SP_INSTR_UINT_MAXLEN + 8))
986     return;
987   str->qs_append(STRING_WITH_LEN("stmt"));
988   str->qs_append(STRING_WITH_LEN(" \""));
989 
990   /*
991     Print the query string (but not too much of it), just to indicate which
992     statement it is.
993   */
994   size_t len= m_query.length;
995   if (len > SP_STMT_PRINT_MAXLEN)
996     len= SP_STMT_PRINT_MAXLEN-3;
997 
998   /* Copy the query string and replace '\n' with ' ' in the process */
999   for (size_t i= 0 ; i < len ; i++)
1000   {
1001     char c= m_query.str[i];
1002     if (c == '\n')
1003       c= ' ';
1004     str->qs_append(c);
1005   }
1006   if (m_query.length > SP_STMT_PRINT_MAXLEN)
1007     str->qs_append(STRING_WITH_LEN("...")); /* Indicate truncated string */
1008   str->qs_append(STRING_WITH_LEN("\""));
1009 }
1010 
1011 
exec_core(THD * thd,uint * nextp)1012 bool sp_instr_stmt::exec_core(THD *thd, uint *nextp)
1013 {
1014   MYSQL_QUERY_EXEC_START(const_cast<char*>(thd->query().str),
1015                          thd->thread_id(),
1016                          (char *) (thd->db().str ? thd->db().str : ""),
1017                          (char *) thd->security_context()->priv_user().str,
1018                          (char *) thd->security_context()->host_or_ip().str,
1019                          3);
1020 
1021   thd->lex->set_sp_current_parsing_ctx(get_parsing_ctx());
1022   thd->lex->sphead= thd->sp_runtime_ctx->sp;
1023 
1024   PSI_statement_locker *statement_psi_saved= thd->m_statement_psi;
1025 
1026   bool rc= mysql_execute_command(thd);
1027 
1028   thd->lex->set_sp_current_parsing_ctx(NULL);
1029   thd->lex->sphead= NULL;
1030   thd->m_statement_psi= statement_psi_saved;
1031 
1032   MYSQL_QUERY_EXEC_DONE(rc);
1033 
1034   *nextp= get_ip() + 1;
1035 
1036   return rc;
1037 }
1038 
1039 
1040 ///////////////////////////////////////////////////////////////////////////
1041 // sp_instr_set implementation.
1042 ///////////////////////////////////////////////////////////////////////////
1043 
1044 #ifdef HAVE_PSI_INTERFACE
1045 PSI_statement_info sp_instr_set::psi_info=
1046 { 0, "set", 0};
1047 #endif
1048 
exec_core(THD * thd,uint * nextp)1049 bool sp_instr_set::exec_core(THD *thd, uint *nextp)
1050 {
1051   *nextp= get_ip() + 1;
1052 
1053   if (!thd->sp_runtime_ctx->set_variable(thd, m_offset, &m_value_item))
1054     return false;
1055 
1056   /* Failed to evaluate the value. Reset the variable to NULL. */
1057 
1058   if (thd->sp_runtime_ctx->set_variable(thd, m_offset, 0))
1059   {
1060     /* If this also failed, let's abort. */
1061     my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
1062   }
1063 
1064   return true;
1065 }
1066 
1067 
print(String * str)1068 void sp_instr_set::print(String *str)
1069 {
1070   /* set name@offset ... */
1071   size_t rsrv = SP_INSTR_UINT_MAXLEN+6;
1072   sp_variable *var = m_parsing_ctx->find_variable(m_offset);
1073 
1074   /* 'var' should always be non-null, but just in case... */
1075   if (var)
1076     rsrv+= var->name.length;
1077   if (str->reserve(rsrv))
1078     return;
1079   str->qs_append(STRING_WITH_LEN("set "));
1080   if (var)
1081   {
1082     str->qs_append(var->name.str, var->name.length);
1083     str->qs_append('@');
1084   }
1085   str->qs_append(m_offset);
1086   str->qs_append(' ');
1087   m_value_item->print(str, QT_TO_ARGUMENT_CHARSET);
1088 }
1089 
1090 
1091 ///////////////////////////////////////////////////////////////////////////
1092 // sp_instr_set_trigger_field implementation.
1093 ///////////////////////////////////////////////////////////////////////////
1094 
1095 #ifdef HAVE_PSI_INTERFACE
1096 PSI_statement_info sp_instr_set_trigger_field::psi_info=
1097 { 0, "set_trigger_field", 0};
1098 #endif
1099 
exec_core(THD * thd,uint * nextp)1100 bool sp_instr_set_trigger_field::exec_core(THD *thd, uint *nextp)
1101 {
1102   *nextp= get_ip() + 1;
1103   thd->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL;
1104   Strict_error_handler strict_handler(Strict_error_handler::
1105                                       ENABLE_SET_SELECT_STRICT_ERROR_HANDLER);
1106   /*
1107     Before Triggers are executed after the 'data' is assigned
1108     to the Field objects. If triggers wants to SET invalid value
1109     to the Field objects (NEW.<variable_name>= <Invalid value>),
1110     it should not be allowed.
1111   */
1112   if (thd->is_strict_mode() && !thd->lex->is_ignore())
1113     thd->push_internal_handler(&strict_handler);
1114   bool error= m_trigger_field->set_value(thd, &m_value_item);
1115   if (thd->is_strict_mode() && !thd->lex->is_ignore())
1116     thd->pop_internal_handler();
1117   return error;
1118 }
1119 
1120 
print(String * str)1121 void sp_instr_set_trigger_field::print(String *str)
1122 {
1123   str->append(STRING_WITH_LEN("set_trigger_field "));
1124   m_trigger_field->print(str, QT_ORDINARY);
1125   str->append(STRING_WITH_LEN(":="));
1126   m_value_item->print(str, QT_TO_ARGUMENT_CHARSET);
1127 }
1128 
1129 
on_after_expr_parsing(THD * thd)1130 bool sp_instr_set_trigger_field::on_after_expr_parsing(THD *thd)
1131 {
1132   DBUG_ASSERT(thd->lex->select_lex->item_list.elements == 1);
1133 
1134   m_value_item= thd->lex->select_lex->item_list.head();
1135 
1136   DBUG_ASSERT(!m_trigger_field);
1137 
1138   m_trigger_field=
1139     new (thd->mem_root) Item_trigger_field(thd->lex->current_context(),
1140                                            TRG_NEW_ROW,
1141                                            m_trigger_field_name.str,
1142                                            UPDATE_ACL,
1143                                            false);
1144 
1145   if (m_trigger_field)
1146   {
1147     /* Adding m_trigger_field to the list of all Item_trigger_field objects */
1148     sp_head *sp= thd->sp_runtime_ctx->sp;
1149     sp->m_cur_instr_trig_field_items.
1150       link_in_list(m_trigger_field, &m_trigger_field->next_trg_field);
1151   }
1152 
1153   return m_value_item == NULL || m_trigger_field == NULL;
1154 }
1155 
1156 
cleanup_before_parsing(THD * thd)1157 void sp_instr_set_trigger_field::cleanup_before_parsing(THD *thd)
1158 {
1159   sp_lex_instr::cleanup_before_parsing(thd);
1160 
1161   m_trigger_field= NULL;
1162 }
1163 
1164 
1165 ///////////////////////////////////////////////////////////////////////////
1166 // sp_instr_jump implementation.
1167 ///////////////////////////////////////////////////////////////////////////
1168 
1169 #ifdef HAVE_PSI_INTERFACE
1170 PSI_statement_info sp_instr_jump::psi_info=
1171 { 0, "jump", 0};
1172 #endif
1173 
print(String * str)1174 void sp_instr_jump::print(String *str)
1175 {
1176   /* jump dest */
1177   if (str->reserve(SP_INSTR_UINT_MAXLEN+5))
1178     return;
1179   str->qs_append(STRING_WITH_LEN("jump "));
1180   str->qs_append(m_dest);
1181 }
1182 
1183 
opt_mark(sp_head * sp,List<sp_instr> * leads)1184 uint sp_instr_jump::opt_mark(sp_head *sp, List<sp_instr> *leads)
1185 {
1186   m_dest= opt_shortcut_jump(sp, this);
1187   if (m_dest != get_ip() + 1)   /* Jumping to following instruction? */
1188     m_marked= true;
1189   m_optdest= sp->get_instr(m_dest);
1190   return m_dest;
1191 }
1192 
1193 
opt_shortcut_jump(sp_head * sp,sp_instr * start)1194 uint sp_instr_jump::opt_shortcut_jump(sp_head *sp, sp_instr *start)
1195 {
1196   uint dest= m_dest;
1197   sp_instr *i;
1198 
1199   while ((i= sp->get_instr(dest)))
1200   {
1201     uint ndest;
1202 
1203     if (start == i || this == i)
1204       break;
1205     ndest= i->opt_shortcut_jump(sp, start);
1206     if (ndest == dest)
1207       break;
1208     dest= ndest;
1209   }
1210   return dest;
1211 }
1212 
1213 
opt_move(uint dst,List<sp_branch_instr> * bp)1214 void sp_instr_jump::opt_move(uint dst, List<sp_branch_instr> *bp)
1215 {
1216   if (m_dest > get_ip())
1217     bp->push_back(this);      // Forward
1218   else if (m_optdest)
1219     m_dest= m_optdest->get_ip();  // Backward
1220   m_ip= dst;
1221 }
1222 
1223 
1224 ///////////////////////////////////////////////////////////////////////////
1225 // sp_instr_jump_if_not class implementation
1226 ///////////////////////////////////////////////////////////////////////////
1227 
1228 #ifdef HAVE_PSI_INTERFACE
1229 PSI_statement_info sp_instr_jump_if_not::psi_info=
1230 { 0, "jump_if_not", 0};
1231 #endif
1232 
exec_core(THD * thd,uint * nextp)1233 bool sp_instr_jump_if_not::exec_core(THD *thd, uint *nextp)
1234 {
1235   DBUG_ASSERT(m_expr_item);
1236 
1237   Item *item= sp_prepare_func_item(thd, &m_expr_item);
1238 
1239   if (!item)
1240     return true;
1241 
1242   *nextp= item->val_bool() ? get_ip() + 1 : m_dest;
1243 
1244   return false;
1245 }
1246 
1247 
print(String * str)1248 void sp_instr_jump_if_not::print(String *str)
1249 {
1250   /* jump_if_not dest(cont) ... */
1251   if (str->reserve(2*SP_INSTR_UINT_MAXLEN+14+32)) // Add some for the expr. too
1252     return;
1253   str->qs_append(STRING_WITH_LEN("jump_if_not "));
1254   str->qs_append(m_dest);
1255   str->qs_append('(');
1256   str->qs_append(m_cont_dest);
1257   str->qs_append(STRING_WITH_LEN(") "));
1258   m_expr_item->print(str, QT_ORDINARY);
1259 }
1260 
1261 
1262 ///////////////////////////////////////////////////////////////////////////
1263 // sp_lex_branch_instr implementation.
1264 ///////////////////////////////////////////////////////////////////////////
1265 
1266 
opt_mark(sp_head * sp,List<sp_instr> * leads)1267 uint sp_lex_branch_instr::opt_mark(sp_head *sp, List<sp_instr> *leads)
1268 {
1269   m_marked= true;
1270 
1271   sp_instr *i= sp->get_instr(m_dest);
1272 
1273   if (i)
1274   {
1275     m_dest= i->opt_shortcut_jump(sp, this);
1276     m_optdest= sp->get_instr(m_dest);
1277   }
1278 
1279   sp->add_mark_lead(m_dest, leads);
1280 
1281   i= sp->get_instr(m_cont_dest);
1282 
1283   if (i)
1284   {
1285     m_cont_dest= i->opt_shortcut_jump(sp, this);
1286     m_cont_optdest= sp->get_instr(m_cont_dest);
1287   }
1288 
1289   sp->add_mark_lead(m_cont_dest, leads);
1290 
1291   return get_ip() + 1;
1292 }
1293 
1294 
opt_move(uint dst,List<sp_branch_instr> * bp)1295 void sp_lex_branch_instr::opt_move(uint dst, List<sp_branch_instr> *bp)
1296 {
1297   /*
1298     cont. destinations may point backwards after shortcutting jumps
1299     during the mark phase. If it's still pointing forwards, only
1300     push this for backpatching if sp_instr_jump::opt_move() will not
1301     do it (i.e. if the m_dest points backwards).
1302    */
1303   if (m_cont_dest > get_ip())
1304   {                             // Forward
1305     if (m_dest < get_ip())
1306       bp->push_back(this);
1307   }
1308   else if (m_cont_optdest)
1309     m_cont_dest= m_cont_optdest->get_ip(); // Backward
1310 
1311   /* This will take care of m_dest and m_ip */
1312   if (m_dest > get_ip())
1313     bp->push_back(this);      // Forward
1314   else if (m_optdest)
1315     m_dest= m_optdest->get_ip();  // Backward
1316   m_ip= dst;
1317 }
1318 
1319 
1320 ///////////////////////////////////////////////////////////////////////////
1321 // sp_instr_jump_case_when implementation.
1322 ///////////////////////////////////////////////////////////////////////////
1323 
1324 #ifdef HAVE_PSI_INTERFACE
1325 PSI_statement_info sp_instr_jump_case_when::psi_info=
1326 { 0, "jump_case_when", 0};
1327 #endif
1328 
exec_core(THD * thd,uint * nextp)1329 bool sp_instr_jump_case_when::exec_core(THD *thd, uint *nextp)
1330 {
1331   DBUG_ASSERT(m_eq_item);
1332 
1333   Item *item= sp_prepare_func_item(thd, &m_eq_item);
1334 
1335   if (!item)
1336     return true;
1337 
1338   *nextp= item->val_bool() ? get_ip() + 1 : m_dest;
1339 
1340   return false;
1341 }
1342 
1343 
print(String * str)1344 void sp_instr_jump_case_when::print(String *str)
1345 {
1346   /* jump_if_not dest(cont) ... */
1347   if (str->reserve(2*SP_INSTR_UINT_MAXLEN+14+32)) // Add some for the expr. too
1348     return;
1349   str->qs_append(STRING_WITH_LEN("jump_if_not_case_when "));
1350   str->qs_append(m_dest);
1351   str->qs_append('(');
1352   str->qs_append(m_cont_dest);
1353   str->qs_append(STRING_WITH_LEN(") "));
1354   m_eq_item->print(str, QT_ORDINARY);
1355 }
1356 
1357 
build_expr_items(THD * thd)1358 bool sp_instr_jump_case_when::build_expr_items(THD *thd)
1359 {
1360   // Setup CASE-expression item (m_case_expr_item).
1361 
1362   m_case_expr_item= new Item_case_expr(m_case_expr_id);
1363 
1364   if (!m_case_expr_item)
1365     return true;
1366 
1367 #ifndef DBUG_OFF
1368   m_case_expr_item->m_sp= thd->lex->sphead;
1369 #endif
1370 
1371   // Setup WHEN-expression item (m_expr_item) if it is not already set.
1372   //
1373   // This function can be called in two cases:
1374   //
1375   //   - during initial (regular) parsing of SP. In this case we don't have
1376   //     lex->select_lex (because it's not a SELECT statement), but
1377   //     m_expr_item is already set in constructor.
1378   //
1379   //   - during re-parsing after meta-data change. In this case we've just
1380   //     parsed aux-SELECT statement, so we need to take 1st (and the only one)
1381   //     item from its list.
1382 
1383   if (!m_expr_item)
1384   {
1385     DBUG_ASSERT(thd->lex->select_lex->item_list.elements == 1);
1386 
1387     m_expr_item= thd->lex->select_lex->item_list.head();
1388   }
1389 
1390   // Setup main expression item (m_expr_item).
1391 
1392   m_eq_item= new Item_func_eq(m_case_expr_item, m_expr_item);
1393 
1394   if (!m_eq_item)
1395     return true;
1396 
1397   return false;
1398 }
1399 
1400 
1401 ///////////////////////////////////////////////////////////////////////////
1402 // sp_instr_freturn implementation.
1403 ///////////////////////////////////////////////////////////////////////////
1404 
1405 #ifdef HAVE_PSI_INTERFACE
1406 PSI_statement_info sp_instr_freturn::psi_info=
1407 { 0, "freturn", 0};
1408 #endif
1409 
exec_core(THD * thd,uint * nextp)1410 bool sp_instr_freturn::exec_core(THD *thd, uint *nextp)
1411 {
1412   /*
1413     Change <next instruction pointer>, so that this will be the last
1414     instruction in the stored function.
1415   */
1416 
1417   *nextp= UINT_MAX;
1418 
1419   /*
1420     Evaluate the value of return expression and store it in current runtime
1421     context.
1422 
1423     NOTE: It's necessary to evaluate result item right here, because we must
1424     do it in scope of execution the current context/block.
1425   */
1426 
1427   return thd->sp_runtime_ctx->set_return_value(thd, &m_expr_item);
1428 }
1429 
1430 
print(String * str)1431 void sp_instr_freturn::print(String *str)
1432 {
1433   /* freturn type expr... */
1434   if (str->reserve(1024+8+32)) // Add some for the expr. too
1435     return;
1436   str->qs_append(STRING_WITH_LEN("freturn "));
1437   str->qs_append((uint) m_return_field_type);
1438   str->qs_append(' ');
1439   m_expr_item->print(str, QT_ORDINARY);
1440 }
1441 
1442 
1443 ///////////////////////////////////////////////////////////////////////////
1444 // sp_instr_hpush_jump implementation.
1445 ///////////////////////////////////////////////////////////////////////////
1446 
1447 #ifdef HAVE_PSI_INTERFACE
1448 PSI_statement_info sp_instr_hpush_jump::psi_info=
1449 { 0, "hpush_jump", 0};
1450 #endif
1451 
execute(THD * thd,uint * nextp)1452 bool sp_instr_hpush_jump::execute(THD *thd, uint *nextp)
1453 {
1454   *nextp= m_dest;
1455 
1456   return thd->sp_runtime_ctx->push_handler(m_handler, get_ip() + 1);
1457 }
1458 
1459 
print(String * str)1460 void sp_instr_hpush_jump::print(String *str)
1461 {
1462   /* hpush_jump dest fsize type */
1463   if (str->reserve(SP_INSTR_UINT_MAXLEN*2 + 21))
1464     return;
1465 
1466   str->qs_append(STRING_WITH_LEN("hpush_jump "));
1467   str->qs_append(m_dest);
1468   str->qs_append(' ');
1469   str->qs_append(m_frame);
1470 
1471   m_handler->print(str);
1472 }
1473 
1474 
opt_mark(sp_head * sp,List<sp_instr> * leads)1475 uint sp_instr_hpush_jump::opt_mark(sp_head *sp, List<sp_instr> *leads)
1476 {
1477   m_marked= true;
1478 
1479   sp_instr *i= sp->get_instr(m_dest);
1480 
1481   if (i)
1482   {
1483     m_dest= i->opt_shortcut_jump(sp, this);
1484     m_optdest= sp->get_instr(m_dest);
1485   }
1486 
1487   sp->add_mark_lead(m_dest, leads);
1488 
1489   /*
1490     For continue handlers, all instructions in the scope of the handler
1491     are possible leads. For example, the instruction after freturn might
1492     be executed if the freturn triggers the condition handled by the
1493     continue handler.
1494 
1495     m_dest marks the start of the handler scope. It's added as a lead
1496     above, so we start on m_dest+1 here.
1497     m_opt_hpop is the hpop marking the end of the handler scope.
1498   */
1499   if (m_handler->type == sp_handler::CONTINUE)
1500   {
1501     for (uint scope_ip= m_dest+1; scope_ip <= m_opt_hpop; scope_ip++)
1502       sp->add_mark_lead(scope_ip, leads);
1503   }
1504 
1505   return get_ip() + 1;
1506 }
1507 
1508 
1509 ///////////////////////////////////////////////////////////////////////////
1510 // sp_instr_hpop implementation.
1511 ///////////////////////////////////////////////////////////////////////////
1512 
1513 #ifdef HAVE_PSI_INTERFACE
1514 PSI_statement_info sp_instr_hpop::psi_info=
1515 { 0, "hpop", 0};
1516 #endif
1517 
execute(THD * thd,uint * nextp)1518 bool sp_instr_hpop::execute(THD *thd, uint *nextp)
1519 {
1520   thd->sp_runtime_ctx->pop_handlers(m_parsing_ctx);
1521   *nextp= get_ip() + 1;
1522   return false;
1523 }
1524 
1525 
1526 ///////////////////////////////////////////////////////////////////////////
1527 // sp_instr_hreturn implementation.
1528 ///////////////////////////////////////////////////////////////////////////
1529 
1530 #ifdef HAVE_PSI_INTERFACE
1531 PSI_statement_info sp_instr_hreturn::psi_info=
1532 { 0, "hreturn", 0};
1533 #endif
1534 
execute(THD * thd,uint * nextp)1535 bool sp_instr_hreturn::execute(THD *thd, uint *nextp)
1536 {
1537   /*
1538     Obtain next instruction pointer (m_dest is set for EXIT handlers, retrieve
1539     the instruction pointer from runtime context for CONTINUE handlers).
1540   */
1541 
1542   sp_rcontext *rctx= thd->sp_runtime_ctx;
1543 
1544   *nextp= m_dest ? m_dest : rctx->get_last_handler_continue_ip();
1545 
1546   /*
1547     Remove call frames for handlers, which are "below" the BEGIN..END block of
1548     the next instruction.
1549   */
1550 
1551   sp_instr *next_instr= rctx->sp->get_instr(*nextp);
1552   rctx->exit_handler(thd, next_instr->get_parsing_ctx());
1553 
1554   return false;
1555 }
1556 
1557 
print(String * str)1558 void sp_instr_hreturn::print(String *str)
1559 {
1560   /* hreturn framesize dest */
1561   if (str->reserve(SP_INSTR_UINT_MAXLEN*2 + 9))
1562     return;
1563   str->qs_append(STRING_WITH_LEN("hreturn "));
1564   if (m_dest)
1565   {
1566     // NOTE: this is legacy: hreturn instruction for EXIT handler
1567     // should print out 0 as frame index.
1568     str->qs_append(STRING_WITH_LEN("0 "));
1569     str->qs_append(m_dest);
1570   }
1571   else
1572   {
1573     str->qs_append(m_frame);
1574   }
1575 }
1576 
1577 
opt_mark(sp_head * sp,List<sp_instr> * leads)1578 uint sp_instr_hreturn::opt_mark(sp_head *sp, List<sp_instr> *leads)
1579 {
1580   m_marked= true;
1581 
1582   if (m_dest)
1583   {
1584     /*
1585       This is an EXIT handler; next instruction step is in m_dest.
1586      */
1587     return m_dest;
1588   }
1589 
1590   /*
1591     This is a CONTINUE handler; next instruction step will come from
1592     the handler stack and not from opt_mark.
1593    */
1594   return UINT_MAX;
1595 }
1596 
1597 
1598 ///////////////////////////////////////////////////////////////////////////
1599 // sp_instr_cpush implementation.
1600 ///////////////////////////////////////////////////////////////////////////
1601 
1602 #ifdef HAVE_PSI_INTERFACE
1603 PSI_statement_info sp_instr_cpush::psi_info=
1604 { 0, "cpush", 0};
1605 #endif
1606 
execute(THD * thd,uint * nextp)1607 bool sp_instr_cpush::execute(THD *thd, uint *nextp)
1608 {
1609   *nextp= get_ip() + 1;
1610 
1611   // sp_instr_cpush::execute() just registers the cursor in the runtime context.
1612 
1613   return thd->sp_runtime_ctx->push_cursor(this);
1614 }
1615 
1616 
exec_core(THD * thd,uint * nextp)1617 bool sp_instr_cpush::exec_core(THD *thd, uint *nextp)
1618 {
1619   sp_cursor *c= thd->sp_runtime_ctx->get_cursor(m_cursor_idx);
1620 
1621   // sp_instr_cpush::exec_core() opens the cursor (it's called from
1622   // sp_instr_copen::execute().
1623 
1624   return c ? c->open(thd) : true;
1625 }
1626 
1627 
print(String * str)1628 void sp_instr_cpush::print(String *str)
1629 {
1630   const LEX_STRING *cursor_name= m_parsing_ctx->find_cursor(m_cursor_idx);
1631 
1632   size_t rsrv= SP_INSTR_UINT_MAXLEN + 7 + m_cursor_query.length + 1;
1633 
1634   if (cursor_name)
1635     rsrv+= cursor_name->length;
1636   if (str->reserve(rsrv))
1637     return;
1638   str->qs_append(STRING_WITH_LEN("cpush "));
1639   if (cursor_name)
1640   {
1641     str->qs_append(cursor_name->str, cursor_name->length);
1642     str->qs_append('@');
1643   }
1644   str->qs_append(m_cursor_idx);
1645 
1646   str->qs_append(':');
1647   str->qs_append(m_cursor_query.str, m_cursor_query.length);
1648 }
1649 
1650 
1651 ///////////////////////////////////////////////////////////////////////////
1652 // sp_instr_cpop implementation.
1653 ///////////////////////////////////////////////////////////////////////////
1654 
1655 #ifdef HAVE_PSI_INTERFACE
1656 PSI_statement_info sp_instr_cpop::psi_info=
1657 { 0, "cpop", 0};
1658 #endif
1659 
execute(THD * thd,uint * nextp)1660 bool sp_instr_cpop::execute(THD *thd, uint *nextp)
1661 {
1662   thd->sp_runtime_ctx->pop_cursors(m_count);
1663   *nextp= get_ip() + 1;
1664 
1665   return false;
1666 }
1667 
1668 
print(String * str)1669 void sp_instr_cpop::print(String *str)
1670 {
1671   /* cpop count */
1672   if (str->reserve(SP_INSTR_UINT_MAXLEN+5))
1673     return;
1674   str->qs_append(STRING_WITH_LEN("cpop "));
1675   str->qs_append(m_count);
1676 }
1677 
1678 
1679 ///////////////////////////////////////////////////////////////////////////
1680 // sp_instr_copen implementation.
1681 ///////////////////////////////////////////////////////////////////////////
1682 
1683 #ifdef HAVE_PSI_INTERFACE
1684 PSI_statement_info sp_instr_copen::psi_info=
1685 { 0, "copen", 0};
1686 #endif
1687 
execute(THD * thd,uint * nextp)1688 bool sp_instr_copen::execute(THD *thd, uint *nextp)
1689 {
1690   // Manipulating a CURSOR with an expression should clear DA.
1691   clear_da(thd);
1692 
1693   *nextp= get_ip() + 1;
1694 
1695   // Get the cursor pointer.
1696 
1697   sp_cursor *c= thd->sp_runtime_ctx->get_cursor(m_cursor_idx);
1698 
1699   if (!c)
1700     return true;
1701 
1702   // Retrieve sp_instr_cpush instance.
1703 
1704   sp_instr_cpush *push_instr= c->get_push_instr();
1705 
1706   // Switch Statement Arena to the sp_instr_cpush object. It contains the
1707   // free_list of the query, so new items (if any) are stored in the right
1708   // free_list, and we can cleanup after each open.
1709 
1710   Query_arena *stmt_arena_saved= thd->stmt_arena;
1711   thd->stmt_arena= push_instr;
1712 
1713   // Switch to the cursor's lex and execute sp_instr_cpush::exec_core().
1714   // sp_instr_cpush::exec_core() is *not* executed during
1715   // sp_instr_cpush::execute(). sp_instr_cpush::exec_core() is intended to be
1716   // executed on cursor opening.
1717 
1718   bool rc= push_instr->validate_lex_and_execute_core(thd, nextp, false);
1719 
1720   // Cleanup the query's items.
1721 
1722   if (push_instr->free_list)
1723     cleanup_items(push_instr->free_list);
1724 
1725   // Restore Statement Arena.
1726 
1727   thd->stmt_arena= stmt_arena_saved;
1728 
1729   return rc;
1730 }
1731 
1732 
print(String * str)1733 void sp_instr_copen::print(String *str)
1734 {
1735   const LEX_STRING *cursor_name= m_parsing_ctx->find_cursor(m_cursor_idx);
1736 
1737   /* copen name@offset */
1738   size_t rsrv= SP_INSTR_UINT_MAXLEN+7;
1739 
1740   if (cursor_name)
1741     rsrv+= cursor_name->length;
1742   if (str->reserve(rsrv))
1743     return;
1744   str->qs_append(STRING_WITH_LEN("copen "));
1745   if (cursor_name)
1746   {
1747     str->qs_append(cursor_name->str, cursor_name->length);
1748     str->qs_append('@');
1749   }
1750   str->qs_append(m_cursor_idx);
1751 }
1752 
1753 
1754 ///////////////////////////////////////////////////////////////////////////
1755 // sp_instr_cclose implementation.
1756 ///////////////////////////////////////////////////////////////////////////
1757 
1758 #ifdef HAVE_PSI_INTERFACE
1759 PSI_statement_info sp_instr_cclose::psi_info=
1760 { 0, "cclose", 0};
1761 #endif
1762 
execute(THD * thd,uint * nextp)1763 bool sp_instr_cclose::execute(THD *thd, uint *nextp)
1764 {
1765   // Manipulating a CURSOR with an expression should clear DA.
1766   clear_da(thd);
1767 
1768   *nextp= get_ip() + 1;
1769 
1770   sp_cursor *c= thd->sp_runtime_ctx->get_cursor(m_cursor_idx);
1771 
1772   return c ? c->close(thd) : true;
1773 }
1774 
1775 
print(String * str)1776 void sp_instr_cclose::print(String *str)
1777 {
1778   const LEX_STRING *cursor_name= m_parsing_ctx->find_cursor(m_cursor_idx);
1779 
1780   /* cclose name@offset */
1781   size_t rsrv= SP_INSTR_UINT_MAXLEN+8;
1782 
1783   if (cursor_name)
1784     rsrv+= cursor_name->length;
1785   if (str->reserve(rsrv))
1786     return;
1787   str->qs_append(STRING_WITH_LEN("cclose "));
1788   if (cursor_name)
1789   {
1790     str->qs_append(cursor_name->str, cursor_name->length);
1791     str->qs_append('@');
1792   }
1793   str->qs_append(m_cursor_idx);
1794 }
1795 
1796 
1797 ///////////////////////////////////////////////////////////////////////////
1798 // sp_instr_cfetch implementation.
1799 ///////////////////////////////////////////////////////////////////////////
1800 
1801 #ifdef HAVE_PSI_INTERFACE
1802 PSI_statement_info sp_instr_cfetch::psi_info=
1803 { 0, "cfetch", 0};
1804 #endif
1805 
execute(THD * thd,uint * nextp)1806 bool sp_instr_cfetch::execute(THD *thd, uint *nextp)
1807 {
1808   // Manipulating a CURSOR with an expression should clear DA.
1809   clear_da(thd);
1810 
1811   *nextp= get_ip() + 1;
1812 
1813   sp_cursor *c= thd->sp_runtime_ctx->get_cursor(m_cursor_idx);
1814 
1815   return c ? c->fetch(thd, &m_varlist) : true;
1816 }
1817 
1818 
print(String * str)1819 void sp_instr_cfetch::print(String *str)
1820 {
1821   List_iterator_fast<sp_variable> li(m_varlist);
1822   sp_variable *pv;
1823   const LEX_STRING *cursor_name= m_parsing_ctx->find_cursor(m_cursor_idx);
1824 
1825   /* cfetch name@offset vars... */
1826   size_t rsrv= SP_INSTR_UINT_MAXLEN+8;
1827 
1828   if (cursor_name)
1829     rsrv+= cursor_name->length;
1830   if (str->reserve(rsrv))
1831     return;
1832   str->qs_append(STRING_WITH_LEN("cfetch "));
1833   if (cursor_name)
1834   {
1835     str->qs_append(cursor_name->str, cursor_name->length);
1836     str->qs_append('@');
1837   }
1838   str->qs_append(m_cursor_idx);
1839   while ((pv= li++))
1840   {
1841     if (str->reserve(pv->name.length+SP_INSTR_UINT_MAXLEN+2))
1842       return;
1843     str->qs_append(' ');
1844     str->qs_append(pv->name.str, pv->name.length);
1845     str->qs_append('@');
1846     str->qs_append(pv->offset);
1847   }
1848 }
1849 
1850 
1851 ///////////////////////////////////////////////////////////////////////////
1852 // sp_instr_error implementation.
1853 ///////////////////////////////////////////////////////////////////////////
1854 
1855 #ifdef HAVE_PSI_INTERFACE
1856 PSI_statement_info sp_instr_error::psi_info=
1857 { 0, "error", 0};
1858 #endif
1859 
print(String * str)1860 void sp_instr_error::print(String *str)
1861 {
1862   /* error code */
1863   if (str->reserve(SP_INSTR_UINT_MAXLEN+6))
1864     return;
1865   str->qs_append(STRING_WITH_LEN("error "));
1866   str->qs_append(m_errcode);
1867 }
1868 
1869 
1870 ///////////////////////////////////////////////////////////////////////////
1871 // sp_instr_set_case_expr implementation.
1872 ///////////////////////////////////////////////////////////////////////////
1873 
1874 #ifdef HAVE_PSI_INTERFACE
1875 PSI_statement_info sp_instr_set_case_expr::psi_info=
1876 { 0, "set_case_expr", 0};
1877 #endif
1878 
exec_core(THD * thd,uint * nextp)1879 bool sp_instr_set_case_expr::exec_core(THD *thd, uint *nextp)
1880 {
1881   *nextp= get_ip() + 1;
1882 
1883   sp_rcontext *rctx= thd->sp_runtime_ctx;
1884 
1885   if (rctx->set_case_expr(thd, m_case_expr_id, &m_expr_item) &&
1886       !rctx->get_case_expr(m_case_expr_id))
1887   {
1888     // Failed to evaluate the value, the case expression is still not
1889     // initialized. Set to NULL so we can continue.
1890 
1891     Item *null_item= new Item_null();
1892 
1893     if (!null_item || rctx->set_case_expr(thd, m_case_expr_id, &null_item))
1894     {
1895       // If this also failed, we have to abort.
1896       my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
1897     }
1898 
1899     return true;
1900   }
1901 
1902   return false;
1903 }
1904 
1905 
print(String * str)1906 void sp_instr_set_case_expr::print(String *str)
1907 {
1908   /* set_case_expr (cont) id ... */
1909   str->reserve(2*SP_INSTR_UINT_MAXLEN+18+32); // Add some extra for expr too
1910   str->qs_append(STRING_WITH_LEN("set_case_expr ("));
1911   str->qs_append(m_cont_dest);
1912   str->qs_append(STRING_WITH_LEN(") "));
1913   str->qs_append(m_case_expr_id);
1914   str->qs_append(' ');
1915   m_expr_item->print(str, QT_ORDINARY);
1916 }
1917 
1918 
opt_mark(sp_head * sp,List<sp_instr> * leads)1919 uint sp_instr_set_case_expr::opt_mark(sp_head *sp, List<sp_instr> *leads)
1920 {
1921   m_marked= true;
1922 
1923   sp_instr *i= sp->get_instr(m_cont_dest);
1924 
1925   if (i)
1926   {
1927     m_cont_dest= i->opt_shortcut_jump(sp, this);
1928     m_cont_optdest= sp->get_instr(m_cont_dest);
1929   }
1930 
1931   sp->add_mark_lead(m_cont_dest, leads);
1932   return get_ip() + 1;
1933 }
1934 
1935 
opt_move(uint dst,List<sp_branch_instr> * bp)1936 void sp_instr_set_case_expr::opt_move(uint dst, List<sp_branch_instr> *bp)
1937 {
1938   if (m_cont_dest > get_ip())
1939     bp->push_back(this);        // Forward
1940   else if (m_cont_optdest)
1941     m_cont_dest= m_cont_optdest->get_ip(); // Backward
1942   m_ip= dst;
1943 }
1944