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