MySQL 8.0.40
Source Code Documentation
sp_head.h
Go to the documentation of this file.
1/* Copyright (c) 2002, 2024, Oracle and/or its affiliates.
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 designed to work 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 either included with
13 the program or referenced in the documentation.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License, version 2.0, for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
23
24#ifndef _SP_HEAD_H_
25#define _SP_HEAD_H_
26
27#include <stddef.h>
28#include <sys/types.h>
29#include <string>
30#include <vector>
31
32#include "lex_string.h"
33#include "map_helpers.h"
34#include "my_alloc.h"
35#include "my_dbug.h"
36#include "my_inttypes.h"
37#include "my_psi_config.h"
38#include "my_sqlcommand.h"
39#include "my_sys.h"
41#include "mysqld_error.h"
43#include "sql/create_field.h"
44#include "sql/mem_root_array.h" // Mem_root_array
45#include "sql/sql_lex.h"
46#include "sql/sql_list.h"
48#include "sql/table.h"
49
50class Field;
51class Item;
55class THD;
56class sp_head;
57struct CHARSET_INFO;
58struct MY_BITMAP;
59
60/**
61 @defgroup Stored_Routines Stored Routines
62 @ingroup Runtime_Environment
63 @{
64*/
65
66class sp_branch_instr;
67class sp_instr;
68class sp_label;
70class sp_pcontext;
71
72/**
73 Number of PSI_statement_info instruments
74 for internal stored programs statements.
75*/
76#define SP_PSI_STATEMENT_INFO_COUNT 16
77
78#ifdef HAVE_PSI_INTERFACE
79void init_sp_psi_keys(void);
80#endif
81
82///////////////////////////////////////////////////////////////////////////
83
84/**
85 Stored_program_creation_ctx -- base class for creation context of stored
86 programs (stored routines, triggers, events).
87*/
88
90 public:
91 const CHARSET_INFO *get_db_cl() { return m_db_cl; }
92
93 public:
95
96 protected:
97 explicit Stored_program_creation_ctx(THD *thd);
98
100 const CHARSET_INFO *connection_cl,
101 const CHARSET_INFO *db_cl)
102 : Default_object_creation_ctx(client_cs, connection_cl), m_db_cl(db_cl) {}
103
104 protected:
105 void change_env(THD *thd) const override;
106
107 protected:
108 /**
109 db_cl stores the value of the database collation. Both character set
110 and collation attributes are used.
111
112 Database collation is included into the context because it defines the
113 default collation for stored-program variables.
114 */
116};
117
118///////////////////////////////////////////////////////////////////////////
119
120class sp_name {
121 public:
125 bool m_explicit_name; /**< Prepend the db name? */
126
127 sp_name(const LEX_CSTRING &db, const LEX_STRING &name, bool use_explicit_name)
128 : m_db(db), m_name(name), m_explicit_name(use_explicit_name) {
129 m_qname.str = nullptr;
130 m_qname.length = 0;
131 }
132
133 /** Create temporary sp_name object for Sroutine_hash_entry. */
134 sp_name(const Sroutine_hash_entry *rt, char *qname_buff);
135
136 // Init. the qualified name from the db and name.
137 void init_qname(THD *thd); // thd for memroot allocation
138};
139
140///////////////////////////////////////////////////////////////////////////
141
142/**
143 sp_parser_data provides a scope for attributes used at the SP-parsing
144 stage only.
145*/
147 private:
151 };
152
153 public:
160 m_cont_level(0),
163
164 ///////////////////////////////////////////////////////////////////////
165
166 /**
167 Start parsing a stored program body statement.
168
169 This method switches THD::mem_root and THD::m_item_list in order to parse
170 SP-body. The current values are kept to be restored after the body
171 statement is parsed.
172
173 @param thd Thread context.
174 @param sp Stored Program being parsed.
175 */
176 void start_parsing_sp_body(THD *thd, sp_head *sp);
177
178 /**
179 Finish parsing of a stored program body statement.
180
181 This method switches THD::mem_root and THD::m_item_list back when SP-body
182 parsing is completed.
183
184 @param thd Thread context.
185 */
186 void finish_parsing_sp_body(THD *thd);
187
188 /**
189 @retval true if SP-body statement is being parsed.
190 @retval false otherwise.
191 */
192 bool is_parsing_sp_body() const { return m_saved_memroot != nullptr; }
193
194 ///////////////////////////////////////////////////////////////////////
195
196 void process_new_sp_instr(THD *thd, sp_instr *i);
197
198 ///////////////////////////////////////////////////////////////////////
199
200 const char *get_current_stmt_start_ptr() const {
202 }
203
204 void set_current_stmt_start_ptr(const char *stmt_start_ptr) {
205 m_current_stmt_start_ptr = stmt_start_ptr;
206 }
207
208 ///////////////////////////////////////////////////////////////////////
209
210 const char *get_option_start_ptr() const { return m_option_start_ptr; }
211
212 void set_option_start_ptr(const char *option_start_ptr) {
213 m_option_start_ptr = option_start_ptr;
214 }
215
216 ///////////////////////////////////////////////////////////////////////
217
218 const char *get_parameter_start_ptr() const { return m_param_start_ptr; }
219
220 void set_parameter_start_ptr(const char *ptr) { m_param_start_ptr = ptr; }
221
222 const char *get_parameter_end_ptr() const { return m_param_end_ptr; }
223
224 void set_parameter_end_ptr(const char *ptr) { m_param_end_ptr = ptr; }
225
226 ///////////////////////////////////////////////////////////////////////
227
228 const char *get_body_start_ptr() const { return m_body_start_ptr; }
229
230 void set_body_start_ptr(const char *ptr) { m_body_start_ptr = ptr; }
231
232 ///////////////////////////////////////////////////////////////////////
233
234 void push_lex(LEX *lex) { m_lex_stack.push_front(lex); }
235
236 LEX *pop_lex() { return m_lex_stack.pop(); }
237
238 ///////////////////////////////////////////////////////////////////////
239 // Backpatch-list operations.
240 ///////////////////////////////////////////////////////////////////////
241
242 /**
243 Put the instruction on the backpatch list, associated with the label.
244
245 @param i The SP-instruction.
246 @param label The label.
247
248 @return Error flag.
249 */
251
252 /**
253 Update all instruction with the given label in the backpatch list
254 to the given instruction pointer.
255
256 @param label The label.
257 @param dest The instruction pointer.
258 */
259 void do_backpatch(sp_label *label, uint dest);
260
261 ///////////////////////////////////////////////////////////////////////
262 // Backpatch operations for supporting CONTINUE handlers.
263 ///////////////////////////////////////////////////////////////////////
264
265 /**
266 Start a new backpatch level for the SP-instruction requiring continue
267 destination. If the SP-instruction is NULL, the level is just increased.
268
269 @note Only subclasses of sp_lex_branch_instr need backpatching of
270 continue destinations (and no other classes do):
271 - sp_instr_jump_if_not
272 - sp_instr_set_case_expr
273 - sp_instr_jump_case_when
274
275 That's why the methods below accept sp_lex_branch_instr to make this
276 relationship clear. And these two functions are the only places where
277 set_cont_dest() is used, so set_cont_dest() is also a member of
278 sp_lex_branch_instr.
279
280 @todo These functions should probably be declared in a separate
281 interface class, but currently we try to minimize the sp_instr
282 hierarchy.
283
284 @return false always.
285 */
287 ++m_cont_level;
288 return false;
289 }
290
291 /**
292 Add a SP-instruction to the current level.
293
294 @param i The SP-instruction.
295
296 @return Error flag.
297 */
299
300 /**
301 Backpatch (and pop) the current level to the given instruction pointer.
302
303 @param dest The instruction pointer.
304 */
305 void do_cont_backpatch(uint dest);
306
307 private:
308 /// Start of the current statement's query string.
310
311 /// Start of the SET-expression query string.
313
314 /**
315 Stack of LEX-objects. It's needed to handle processing of
316 sub-statements.
317 */
319
320 /**
321 Position in the CREATE PROCEDURE- or CREATE FUNCTION-statement's query
322 string corresponding to the start of parameter declarations (stored
323 procedure or stored function parameters).
324 */
325 const char *m_param_start_ptr;
326
327 /**
328 Position in the CREATE PROCEDURE- or CREATE FUNCTION-statement's query
329 string corresponding to the end of parameter declarations (stored
330 procedure or stored function parameters).
331 */
332 const char *m_param_end_ptr;
333
334 /**
335 Position in the CREATE-/ALTER-stored-program statement's query string
336 corresponding to the start of the first SQL-statement.
337 */
338 const char *m_body_start_ptr;
339
340 /// Instructions needing backpatching
342
343 /**
344 We need a special list for backpatching of instructions with a continue
345 destination (in the case of a continue handler catching an error in
346 the test), since it would otherwise interfere with the normal backpatch
347 mechanism - e.g. jump_if_not instructions have two different destinations
348 which are to be patched differently.
349 Since these occur in a more restricted way (always the same "level" in
350 the code), we don't need the label.
351 */
353
354 /// The current continue backpatch level
356
357 /**********************************************************************
358 The following attributes are used to store THD values during parsing
359 of stored program body.
360
361 @sa start_parsing_sp_body()
362 @sa finish_parsing_sp_body()
363 **********************************************************************/
364
365 /// THD's memroot.
367
368 /// THD's item list.
370};
371
372///////////////////////////////////////////////////////////////////////////
373
374struct SP_TABLE;
375
376/**
377 sp_head represents one instance of a stored program. It might be of any type
378 (stored procedure, function, trigger, event).
379*/
380class sp_head {
381 public:
382 /** Possible values of m_flags */
383 enum {
384 HAS_RETURN = 1, // For FUNCTIONs only: is set if has RETURN
385 MULTI_RESULTS = 8, // Is set if a procedure with SELECT(s)
386 CONTAINS_DYNAMIC_SQL = 16, // Is set if a procedure with PREPARE/EXECUTE
387 IS_INVOKED = 32, // Is set if this sp_head is being used
389 64, // Is set if a procedure with 'set autocommit'
390 /* Is set if a procedure with COMMIT (implicit or explicit) | ROLLBACK */
392 LOG_SLOW_STATEMENTS = 256, // Used by events
393 LOG_GENERAL_LOG = 512, // Used by events
396
397 /**
398 Marks routines that directly (i.e. not by calling other routines)
399 change tables. Note that this flag is set automatically based on
400 type of statements used in the stored routine and is different
401 from routine characteristic provided by user in a form of CONTAINS
402 SQL, READS SQL DATA, MODIFIES SQL DATA clauses. The latter are
403 accepted by parser but pretty much ignored after that.
404 We don't rely on them:
405 a) for compatibility reasons.
406 b) because in CONTAINS SQL case they don't provide enough
407 information anyway.
408 */
410 /**
411 Set when a stored program contains sub-statement(s) that creates or drops
412 temporary table(s). When set, used to mark invoking statement as unsafe to
413 be binlogged in STATEMENT format, when in MIXED mode.
414 */
415 HAS_TEMP_TABLE_DDL = 8192
416 };
417
418 public:
419 /************************************************************************
420 Public attributes.
421 ************************************************************************/
422
423 /// Stored program type.
425
426 /// Stored program flags.
428
429 /**
430 Instrumentation interface for SP.
431 */
433
434 /**
435 Definition of the RETURN-field (from the RETURNS-clause).
436 It's used (and valid) for stored functions only.
437 */
439
440 /// Attributes used during the parsing stage only.
442
443 /// Stored program characteristics.
445
446 /**
447 The value of sql_mode system variable at the CREATE-time.
448
449 It should be stored along with the character sets in the
450 Stored_program_creation_ctx.
451 */
453
454 /// Fully qualified name (@<db name@>.@<sp name@>).
456
457 bool m_explicit_name; ///< Prepend the db name? */
458
467
470
471 /// Recursion level of the current SP instance. The levels are numbered from
472 /// 0.
474
475 /**
476 A list of different recursion level instances for the same procedure.
477 For every recursion level we have an sp_head instance. This instances
478 connected in the list. The list ordered by increasing recursion level
479 (m_recursion_level).
480 */
482
483 /// Pointer to the first element of the above list
485
486 /**
487 Pointer to the first free (non-INVOKED) routine in the list of
488 cached instances for this SP. This pointer is set only for the first
489 SP in the list of instances (see above m_first_cached_sp pointer).
490 The pointer equal to 0 if we have no free instances.
491 For non-first instance value of this pointer meaningless (point to itself);
492 */
494
495 /**
496 Pointer to the last element in the list of instances of the SP.
497 For non-first instance value of this pointer meaningless (point to itself);
498 */
500
501 /**
502 Set containing names of stored routines used by this routine.
503 Note that unlike elements of similar set for statement elements of this
504 set are not linked in one list. Because of this we are able save memory
505 by using for this set same objects that are used in 'sroutines' sets
506 for statements of which this stored routine consists.
507
508 See Sroutine_hash_entry for explanation why this hash uses binary
509 key comparison.
510 */
512
513 /*
514 Security context for stored routine which should be run under
515 definer privileges.
516 */
518
519 /////////////////////////////////////////////////////////////////////////
520 // Trigger-specific public attributes.
521 /////////////////////////////////////////////////////////////////////////
522
523 /**
524 List of item (Item_trigger_field objects)'s lists representing fields
525 in old/new version of row in trigger. We use this list for checking
526 whether all such fields are valid or not at trigger creation time and for
527 binding these fields to TABLE object at table open (although for latter
528 pointer to table being opened is probably enough).
529 */
531 /**
532 List of all the Item_trigger_field items created while parsing
533 sp instruction. After parsing, in add_instr method this list
534 is moved to per instruction Item_trigger_field list
535 "sp_lex_instr::m_trig_field_list".
536 */
538
539 /// Trigger characteristics.
541
542 /// The Table_trigger_dispatcher instance, where this trigger belongs to.
544
545 public:
546 static void destroy(sp_head *sp);
547
548 /// Is this routine being executed?
549 bool is_invoked() const { return m_flags & IS_INVOKED; }
550
551 /**
552 Get the value of the SP cache version, as remembered
553 when the routine was inserted into the cache.
554 */
556
557 /// Set the value of the SP cache version.
560 }
561
563
565 m_creation_ctx = creation_ctx->clone(&main_mem_root);
566 }
567
568 /// Set the body-definition start position.
569 void set_body_start(THD *thd, const char *begin_ptr);
570
571 /// Set the statement-definition (body-definition) end position.
572 void set_body_end(THD *thd);
573
575 GRANT_INFO *subject_table_grant,
576 bool need_fix_fields);
577
578 void mark_used_trigger_fields(TABLE *subject_table);
579
580 bool has_updated_trigger_fields(const MY_BITMAP *used_fields) const;
581
582 /**
583 Execute trigger stored program.
584
585 - changes security context for triggers
586 - switch to new memroot
587 - call sp_head::execute
588 - restore old memroot
589 - restores security context
590
591 @param thd Thread context
592 @param db_name database name
593 @param table_name table name
594 @param grant_info GRANT_INFO structure to be filled with
595 information about definer's privileges
596 on subject table
597
598 @todo
599 We should create sp_rcontext once per command and reuse it
600 on subsequent executions of a trigger.
601
602 @return Error status.
603 */
604 bool execute_trigger(THD *thd, const LEX_CSTRING &db_name,
605 const LEX_CSTRING &table_name, GRANT_INFO *grant_info);
606
607 /**
608 Execute a function.
609
610 - evaluate parameters
611 - changes security context for SUID routines
612 - switch to new memroot
613 - call sp_head::execute
614 - restore old memroot
615 - evaluate the return value
616 - restores security context
617
618 @param thd Thread context.
619 @param args Passed arguments (these are items from containing
620 statement?)
621 @param argcount Number of passed arguments. We need to check if
622 this is correct.
623 @param return_fld Save result here.
624
625 @todo
626 We should create sp_rcontext once per command and reuse
627 it on subsequent executions of a function/trigger.
628
629 @todo
630 In future we should associate call arena/mem_root with
631 sp_rcontext and allocate all these objects (and sp_rcontext
632 itself) on it directly rather than juggle with arenas.
633
634 @return Error status.
635 */
636 bool execute_function(THD *thd, Item **args, uint argcount,
637 Field *return_fld);
638
639 /**
640 Execute a procedure.
641
642 The function does the following steps:
643 - Set all parameters
644 - changes security context for SUID routines
645 - call sp_head::execute
646 - copy back values of INOUT and OUT parameters
647 - restores security context
648
649 @param thd Thread context.
650 @param args List of values passed as arguments.
651
652 @return Error status.
653 */
654
656
657 /**
658 Add instruction to SP.
659
660 @param thd Thread context.
661 @param instr Instruction.
662
663 @return Error status.
664 */
665 bool add_instr(THD *thd, sp_instr *instr);
666
667 /**
668 Returns true if any substatement in the routine directly
669 (not through another routine) modifies data/changes table.
670
671 @sa Comment for MODIFIES_DATA flag.
672 */
673 bool modifies_data() const { return m_flags & MODIFIES_DATA; }
674
675 /**
676 @returns true if stored program has sub-statement(s) to CREATE/DROP
677 temporary table(s).
678 @retval true if HAS_TEMP_TABLE_DDL is set in m_flags.
679 @retval false Otherwise.
680 */
682
683 uint instructions() { return static_cast<uint>(m_instructions.size()); }
684
686
687 /**
688 Reset LEX-object during parsing, before we parse a sub statement.
689
690 @param thd Thread context.
691
692 @return Error status.
693 */
694 bool reset_lex(THD *thd);
695
696 /**
697 Restore LEX-object during parsing, after we have parsed a sub statement.
698
699 @param thd Thread context.
700
701 @return Error status.
702 */
703 bool restore_lex(THD *thd);
704
705 char *name(uint *lenp = nullptr) const {
706 if (lenp) *lenp = (uint)m_name.length;
707 return m_name.str;
708 }
709
710 /**
711 Create Field-object corresponding to the RETURN field of a stored function.
712 This operation makes sense for stored functions only.
713
714 @param thd thread context.
715 @param field_max_length the max length (in the sense of Item classes).
716 @param field_name the field name (item name).
717 @param table the field's table.
718
719 @return newly created and initialized Field-instance,
720 or NULL in case of error.
721 */
722 Field *create_result_field(THD *thd, size_t field_max_length,
723 const char *field_name, TABLE *table) const;
724
725 void returns_type(THD *thd, String *result) const;
726
727 void set_info(longlong created, longlong modified, st_sp_chistics *chistics,
729
730 void set_definer(const char *definer, size_t definerlen);
731 void set_definer(const LEX_CSTRING &user_name, const LEX_CSTRING &host_name);
732
733 /**
734 Do some minimal optimization of the code:
735 -# Mark used instructions
736 -# While doing this, shortcut jumps to jump instructions
737 -# Compact the code, removing unused instructions.
738
739 This is the main mark and move loop; it relies on the following methods
740 in sp_instr and its subclasses:
741
742 - opt_mark() : Mark instruction as reachable
743 - opt_shortcut_jump(): Shortcut jumps to the final destination;
744 used by opt_mark().
745 - opt_move() : Update moved instruction
746 - set_destination() : Set the new destination (jump instructions only)
747 */
748 void optimize();
749
750 /**
751 Helper used during flow analysis during code optimization.
752 See the implementation of <code>opt_mark()</code>.
753 @param ip the instruction to add to the leads list
754 @param leads the list of remaining paths to explore in the graph that
755 represents the code, during flow analysis.
756 */
757 void add_mark_lead(uint ip, List<sp_instr> *leads);
758
759 /**
760 Get SP-instruction at given index.
761
762 NOTE: it is important to have *unsigned* int here, sometimes we get (-1)
763 passed here, so it gets converted to MAX_INT, and the result of the
764 function call is NULL.
765 */
767 return (i < (uint)m_instructions.size()) ? m_instructions.at(i) : NULL;
768 }
769
770 /**
771 Add tables used by routine to the table list.
772
773 Converts multi-set of tables used by this routine to table list and adds
774 this list to the end of table list specified by 'query_tables_last_ptr'.
775
776 Elements of list will be allocated in PS memroot, so this list will be
777 persistent between PS executions.
778
779 @param[in] thd Thread context
780 @param[in,out] query_tables_last_ptr Pointer to the next_global member of
781 last element of the list where tables
782 will be added (or to its root).
783 @param[in] sql_command SQL-command for which we are adding
784 elements to the table list.
785 @param[in] belong_to_view Uppermost view which uses this
786 routine, NULL if none.
787 */
789 Table_ref ***query_tables_last_ptr,
790 enum_sql_command sql_command,
791 Table_ref *belong_to_view);
792
793 /**
794 Check if this stored routine contains statements disallowed
795 in a stored function or trigger, and set an appropriate error message
796 if this is the case.
797 */
800 my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "Dynamic SQL");
801 else if (m_flags & MULTI_RESULTS)
802 my_error(ER_SP_NO_RETSET, MYF(0), where);
804 my_error(ER_SP_CANT_SET_AUTOCOMMIT, MYF(0));
806 my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
807 else if (m_flags & HAS_SQLCOM_RESET)
808 my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "RESET");
809 else if (m_flags & HAS_SQLCOM_FLUSH)
810 my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "FLUSH");
811
812 return (m_flags &
815 }
816
817#ifndef NDEBUG
818 /**
819 Return the routine instructions as a result set.
820 @return Error status.
821 */
822 bool show_routine_code(THD *thd);
823#endif
824
825 /*
826 This method is intended for attributes of a routine which need
827 to propagate upwards to the Query_tables_list of the caller (when
828 a property of a sp_head needs to "taint" the calling statement).
829 */
831 /*
832 If this routine needs row-based binary logging, the entire top statement
833 too (we cannot switch from statement-based to row-based only for this
834 routine, as in statement-based the top-statement may be binlogged and
835 the sub-statements not).
836 */
837 DBUG_PRINT("info", ("lex->get_stmt_unsafe_flags(): 0x%x",
838 prelocking_ctx->get_stmt_unsafe_flags()));
839 DBUG_PRINT("info", ("sp_head(0x%p=%s)->unsafe_flags: 0x%x", this, name(),
840 unsafe_flags));
841 prelocking_ctx->set_stmt_unsafe_flags(unsafe_flags);
842
843 /*
844 If temporary table is created or dropped in the stored program then
845 statement is unsafe to be logged in STATEMENT format, when in MIXED mode.
846 */
848 }
849
850 /**
851 @return root parsing context for this stored program.
852 */
854 return const_cast<sp_pcontext *>(m_root_parsing_ctx);
855 }
856
857 /**
858 @return SP-persistent mem-root. Instructions and expressions are stored in
859 its memory between executions.
860 */
862 return const_cast<MEM_ROOT *>(&main_mem_root);
863 }
864
865 /**
866 Check if a user has access right to a SP.
867
868 @param thd Thread context.
869 @param[out] full_access Set to 1 if the user is the owner
870 of the stored program.
871
872 @return Error status.
873 */
874 bool check_show_access(THD *thd, bool *full_access);
875
876 /**
877 Change routine security context, and check if there is an EXECUTE privilege
878 in new context. If there is no EXECUTE privilege, change the context back
879 and return an error.
880
881 @param thd Thread context.
882 @param[out] save_ctx Where to save the old security context.
883
884 @todo Cache if the definer has the rights to use the object on the first
885 usage and reset the cache only if someone does a GRANT statement that 'may'
886 affect this.
887
888 @return Error status.
889 */
890 bool set_security_ctx(THD *thd, Security_context **save_ctx);
891
892 private:
893 /// Use sp_start_parsing() to create instances of sp_head.
895
896 /// Use destroy() to destoy instances of sp_head.
897 ~sp_head();
898
899 /// SP-persistent memory root (for instructions and expressions).
901
902 /// Root parsing context (topmost BEGIN..END block) of this SP.
904
905 /// The SP-instructions.
907
908 /**
909 Multi-set representing optimized list of tables to be locked by this
910 routine. Does not include tables which are used by invoked routines.
911
912 @note
913 For prelocking-free SPs this multiset is constructed too.
914 We do so because the same instance of sp_head may be called both
915 in prelocked mode and in non-prelocked mode.
916 */
918
919 /*
920 The same information as in m_sptabs, but sorted (by an arbitrary key).
921 This is useful to get consistent locking order, which makes MTR tests
922 more deterministic across platforms. It does not have a bearing on the
923 actual behavior of the server.
924 */
925 std::vector<SP_TABLE *> m_sptabs_sorted;
926
927 /**
928 Version of the stored routine cache at the moment when the
929 routine was added to it. Is used only for functions and
930 procedures, not used for triggers or events. When sp_head is
931 created, its version is 0. When it's added to the cache, the
932 version is assigned the global value 'Cversion'.
933 If later on Cversion is incremented, we know that the routine
934 is obsolete and should not be used --
935 sp_cache_flush_obsolete() will purge it.
936 */
938
939 /// Snapshot of several system variables at CREATE-time.
941
942 /// Flags of LEX::enum_binlog_stmt_unsafe.
944
945 private:
946 /// Copy sp name from parser.
947 void init_sp_name(THD *thd, sp_name *spname);
948
949 /**
950 Execute the routine. The main instruction jump loop is there.
951 Assume the parameters already set.
952
953 @param thd Thread context.
954 @param merge_da_on_success Flag specifying if Warning Info should be
955 propagated to the caller on Completion
956 Condition or not.
957
958 @todo
959 - Will write this SP statement into binlog separately
960 (TODO: consider changing the condition to "not inside event union")
961
962 @return Error status.
963 */
964 bool execute(THD *thd, bool merge_da_on_success);
965
966 /**
967 Perform a forward flow analysis in the generated code.
968 Mark reachable instructions, for the optimizer.
969 */
970 void opt_mark();
971
972 /**
973 Merge the list of tables used by some query into the multi-set of
974 tables used by routine.
975
976 @param thd Thread context.
977 @param table Table list.
978 @param lex_for_tmp_check LEX of the query for which we are merging
979 table list.
980
981 @note
982 This method will use LEX provided to check whenever we are creating
983 temporary table and mark it as such in target multi-set.
984
985 @return Error status.
986 */
987 bool merge_table_list(THD *thd, Table_ref *table, LEX *lex_for_tmp_check);
988
989 friend sp_head *sp_start_parsing(THD *thd, enum_sp_type sp_type,
991
992 // Prevent use of copy constructor and assignment operator.
993 sp_head(const sp_head &);
995};
996
997///////////////////////////////////////////////////////////////////////////
998
999/**
1000 @} (end of group Stored_Routines)
1001*/
1002
1003#endif /* _SP_HEAD_H_ */
Create_field is a description a field/column that may or may not exists in a table.
Definition: create_field.h:51
Default_object_creation_ctx – default implementation of Object_creation_ctx.
Definition: table.h:221
Definition: field.h:575
Represents NEW/OLD version of field of row which is changed/read in trigger.
Definition: item.h:6572
Base class that is used to represent any kind of expression in a relational query.
Definition: item.h:853
Definition: sql_list.h:434
A typesafe replacement for DYNAMIC_ARRAY.
Definition: mem_root_array.h:426
Definition: sql_lex.h:2507
void set_stmt_unsafe_flags(uint32 flags)
Set the bits of binlog_stmt_flags determining the type of unsafeness of the current statement.
Definition: sql_lex.h:2840
uint32 get_stmt_unsafe_flags() const
Return a binary combination of all unsafe warnings for the statement.
Definition: sql_lex.h:2853
void set_stmt_unsafe_with_mixed_mode()
Definition: sql_lex.h:3078
Simple intrusive linked list.
Definition: sql_list.h:46
A set of THD members describing the current authenticated user.
Definition: sql_security_ctx.h:55
Structure that represents element in the set of stored routines used by statement or routine.
Definition: sp.h:224
Stored_program_creation_ctx – base class for creation context of stored programs (stored routines,...
Definition: sp_head.h:89
const CHARSET_INFO * m_db_cl
db_cl stores the value of the database collation.
Definition: sp_head.h:115
virtual Stored_program_creation_ctx * clone(MEM_ROOT *mem_root)=0
void change_env(THD *thd) const override
Definition: sp_head.cc:3510
Stored_program_creation_ctx(THD *thd)
Definition: sp_head.cc:3506
Stored_program_creation_ctx(const CHARSET_INFO *client_cs, const CHARSET_INFO *connection_cl, const CHARSET_INFO *db_cl)
Definition: sp_head.h:99
const CHARSET_INFO * get_db_cl()
Definition: sp_head.h:91
Using this class is fraught with peril, and you need to be very careful when doing so.
Definition: sql_string.h:168
For each client connection we create a separate thread with THD serving as a thread/connection descri...
Definition: sql_lexer_thd.h:34
Definition: table.h:2791
This class holds all information about triggers of a table.
Definition: table_trigger_dispatcher.h:63
This is an interface to be used from Item_trigger_field to access information about table trigger fie...
Definition: table_trigger_field_support.h:44
std::unordered_map, but with my_malloc and collation-aware comparison.
Definition: map_helpers.h:210
std::unordered_map, but with my_malloc, so that you can track the memory used using PSI memory keys.
Definition: map_helpers.h:148
A (partial) implementation of std::deque allocating its blocks on a MEM_ROOT.
Definition: mem_root_deque.h:110
An interface for all SP-instructions with destinations that need to be updated by the SP-optimizer.
Definition: sp_instr.h:78
sp_head represents one instance of a stored program.
Definition: sp_head.h:380
void set_creation_ctx(Stored_program_creation_ctx *creation_ctx)
Definition: sp_head.h:564
bool add_instr(THD *thd, sp_instr *instr)
Add instruction to SP.
Definition: sp_head.cc:3056
LEX_STRING m_name
Definition: sp_head.h:460
bool execute_function(THD *thd, Item **args, uint argcount, Field *return_fld)
Execute a function.
Definition: sp_head.cc:2508
st_sp_chistics * m_chistics
Stored program characteristics.
Definition: sp_head.h:444
sp_head(MEM_ROOT &&mem_root, enum_sp_type type)
Use sp_start_parsing() to create instances of sp_head.
Definition: sp_head.cc:1699
int64 sp_cache_version() const
Get the value of the SP cache version, as remembered when the routine was inserted into the cache.
Definition: sp_head.h:555
void set_definer(const char *definer, size_t definerlen)
Definition: sp_head.cc:3032
void operator=(sp_head &)
LEX_CSTRING m_body
Definition: sp_head.h:462
bool setup_trigger_fields(THD *thd, Table_trigger_field_support *tfs, GRANT_INFO *subject_table_grant, bool need_fix_fields)
Definition: sp_head.cc:1826
bool has_updated_trigger_fields(const MY_BITMAP *used_fields) const
Check whether any table's fields are used in trigger.
Definition: sp_head.cc:1878
void init_sp_name(THD *thd, sp_name *spname)
Copy sp name from parser.
Definition: sp_head.cc:1749
bool execute_procedure(THD *thd, mem_root_deque< Item * > *args)
Execute a procedure.
Definition: sp_head.cc:2721
void set_body_end(THD *thd)
Set the statement-definition (body-definition) end position.
Definition: sp_head.cc:1778
void set_info(longlong created, longlong modified, st_sp_chistics *chistics, sql_mode_t sql_mode)
Definition: sp_head.cc:3018
ulong m_recursion_level
Recursion level of the current SP instance.
Definition: sp_head.h:473
longlong m_created
Definition: sp_head.h:468
sp_head * m_first_instance
Pointer to the first element of the above list.
Definition: sp_head.h:484
uint instructions()
Definition: sp_head.h:683
collation_unordered_map< std::string, SP_TABLE * > m_sptabs
Multi-set representing optimized list of tables to be locked by this routine.
Definition: sp_head.h:917
bool execute(THD *thd, bool merge_da_on_success)
Execute the routine.
Definition: sp_head.cc:1983
Security_context m_security_ctx
Definition: sp_head.h:517
Create_field m_return_field_def
Definition of the RETURN-field (from the RETURNS-clause).
Definition: sp_head.h:438
LEX_STRING m_defstr
Definition: sp_head.h:464
uint m_flags
Stored program flags.
Definition: sp_head.h:427
SQL_I_List< SQL_I_List< Item_trigger_field > > m_list_of_trig_fields_item_lists
List of item (Item_trigger_field objects)'s lists representing fields in old/new version of row in tr...
Definition: sp_head.h:530
void add_used_tables_to_table_list(THD *thd, Table_ref ***query_tables_last_ptr, enum_sql_command sql_command, Table_ref *belong_to_view)
Add tables used by routine to the table list.
Definition: sp_head.cc:3301
friend sp_head * sp_start_parsing(THD *thd, enum_sp_type sp_type, sp_name *sp_name)
Start parsing of a stored program.
Definition: sp.cc:2154
int64 m_sp_cache_version
Version of the stored routine cache at the moment when the routine was added to it.
Definition: sp_head.h:937
sp_pcontext * m_root_parsing_ctx
Root parsing context (topmost BEGIN..END block) of this SP.
Definition: sp_head.h:903
LEX_STRING m_params
Definition: sp_head.h:461
bool show_routine_code(THD *thd)
Return the routine instructions as a result set.
Definition: sp_head.cc:3161
class Table_trigger_dispatcher * m_trg_list
The Table_trigger_dispatcher instance, where this trigger belongs to.
Definition: sp_head.h:543
malloc_unordered_map< std::string, Sroutine_hash_entry * > m_sroutines
Set containing names of stored routines used by this routine.
Definition: sp_head.h:511
std::vector< SP_TABLE * > m_sptabs_sorted
Definition: sp_head.h:925
LEX_STRING m_db
Definition: sp_head.h:459
Field * create_result_field(THD *thd, size_t field_max_length, const char *field_name, TABLE *table) const
Create Field-object corresponding to the RETURN field of a stored function.
Definition: sp_head.cc:1925
bool check_show_access(THD *thd, bool *full_access)
Check if a user has access right to a SP.
Definition: sp_head.cc:3374
void set_sp_cache_version(int64 sp_cache_version)
Set the value of the SP cache version.
Definition: sp_head.h:558
bool m_explicit_name
Prepend the db name? *‍/.
Definition: sp_head.h:457
bool is_not_allowed_in_function(const char *where)
Check if this stored routine contains statements disallowed in a stored function or trigger,...
Definition: sp_head.h:798
void mark_used_trigger_fields(TABLE *subject_table)
Definition: sp_head.cc:1848
void returns_type(THD *thd, String *result) const
Definition: sp_head.cc:1956
LEX_CSTRING m_body_utf8
Definition: sp_head.h:463
Mem_root_array< sp_instr * > m_instructions
The SP-instructions.
Definition: sp_head.h:906
uint32 unsafe_flags
Flags of LEX::enum_binlog_stmt_unsafe.
Definition: sp_head.h:943
Stored_program_creation_ctx * m_creation_ctx
Snapshot of several system variables at CREATE-time.
Definition: sp_head.h:940
bool is_invoked() const
Is this routine being executed?
Definition: sp_head.h:549
LEX_STRING m_qname
Fully qualified name (<db name>.<sp name>).
Definition: sp_head.h:455
LEX_STRING m_definer_host
Definition: sp_head.h:466
sql_mode_t m_sql_mode
The value of sql_mode system variable at the CREATE-time.
Definition: sp_head.h:452
MEM_ROOT * get_persistent_mem_root() const
Definition: sp_head.h:861
bool merge_table_list(THD *thd, Table_ref *table, LEX *lex_for_tmp_check)
Merge the list of tables used by some query into the multi-set of tables used by routine.
Definition: sp_head.cc:3211
longlong m_modified
Definition: sp_head.h:469
bool restore_lex(THD *thd)
Restore LEX-object during parsing, after we have parsed a sub statement.
Definition: sp_head.cc:2968
static void destroy(sp_head *sp)
Definition: sp_head.cc:1688
~sp_head()
Use destroy() to destoy instances of sp_head.
Definition: sp_head.cc:1897
sp_instr * last_instruction()
Definition: sp_head.h:685
LEX_STRING m_definer_user
Definition: sp_head.h:465
char * name(uint *lenp=nullptr) const
Definition: sp_head.h:705
void set_body_start(THD *thd, const char *begin_ptr)
Set the body-definition start position.
Definition: sp_head.cc:1772
void add_mark_lead(uint ip, List< sp_instr > *leads)
Helper used during flow analysis during code optimization.
Definition: sp_head.cc:3120
@ MULTI_RESULTS
Definition: sp_head.h:385
@ HAS_TEMP_TABLE_DDL
Set when a stored program contains sub-statement(s) that creates or drops temporary table(s).
Definition: sp_head.h:415
@ HAS_SQLCOM_RESET
Definition: sp_head.h:394
@ MODIFIES_DATA
Marks routines that directly (i.e.
Definition: sp_head.h:409
@ LOG_GENERAL_LOG
Definition: sp_head.h:393
@ HAS_COMMIT_OR_ROLLBACK
Definition: sp_head.h:391
@ IS_INVOKED
Definition: sp_head.h:387
@ CONTAINS_DYNAMIC_SQL
Definition: sp_head.h:386
@ HAS_SQLCOM_FLUSH
Definition: sp_head.h:395
@ LOG_SLOW_STATEMENTS
Definition: sp_head.h:392
@ HAS_RETURN
Definition: sp_head.h:384
@ HAS_SET_AUTOCOMMIT_STMT
Definition: sp_head.h:388
bool has_temp_table_ddl() const
Definition: sp_head.h:681
bool execute_trigger(THD *thd, const LEX_CSTRING &db_name, const LEX_CSTRING &table_name, GRANT_INFO *grant_info)
Execute trigger stored program.
Definition: sp_head.cc:2402
PSI_sp_share * m_sp_share
Instrumentation interface for SP.
Definition: sp_head.h:432
sp_parser_data m_parser_data
Attributes used during the parsing stage only.
Definition: sp_head.h:441
Stored_program_creation_ctx * get_creation_ctx()
Definition: sp_head.h:562
sp_head * m_next_cached_sp
A list of different recursion level instances for the same procedure.
Definition: sp_head.h:481
bool reset_lex(THD *thd)
Reset LEX-object during parsing, before we parse a sub statement.
Definition: sp_head.cc:2944
MEM_ROOT main_mem_root
SP-persistent memory root (for instructions and expressions).
Definition: sp_head.h:900
st_trg_chistics m_trg_chistics
Trigger characteristics.
Definition: sp_head.h:540
sp_head * m_first_free_instance
Pointer to the first free (non-INVOKED) routine in the list of cached instances for this SP.
Definition: sp_head.h:493
void optimize()
Do some minimal optimization of the code:
Definition: sp_head.cc:3087
enum_sp_type m_type
Stored program type.
Definition: sp_head.h:424
bool modifies_data() const
Returns true if any substatement in the routine directly (not through another routine) modifies data/...
Definition: sp_head.h:673
void propagate_attributes(Query_tables_list *prelocking_ctx)
Definition: sp_head.h:830
sp_head * m_last_cached_sp
Pointer to the last element in the list of instances of the SP.
Definition: sp_head.h:499
void opt_mark()
Perform a forward flow analysis in the generated code.
Definition: sp_head.cc:3126
sp_pcontext * get_root_parsing_context() const
Definition: sp_head.h:853
sp_head(const sp_head &)
sp_instr * get_instr(uint i)
Get SP-instruction at given index.
Definition: sp_head.h:766
bool set_security_ctx(THD *thd, Security_context **save_ctx)
Change routine security context, and check if there is an EXECUTE privilege in new context.
Definition: sp_head.cc:3388
SQL_I_List< Item_trigger_field > m_cur_instr_trig_field_items
List of all the Item_trigger_field items created while parsing sp instruction.
Definition: sp_head.h:537
Base class for every SP-instruction.
Definition: sp_instr.h:105
This class represents an SQL/PSM label.
Definition: sp_pcontext.h:94
sp_lex_branch_instr is a base class for SP-instructions, which might perform conditional jump dependi...
Definition: sp_instr.h:796
Definition: sp_head.h:120
LEX_STRING m_qname
Definition: sp_head.h:124
bool m_explicit_name
Prepend the db name?
Definition: sp_head.h:125
void init_qname(THD *thd)
Init the qualified name from the db and name.
Definition: sp_head.cc:1674
LEX_STRING m_name
Definition: sp_head.h:123
sp_name(const LEX_CSTRING &db, const LEX_STRING &name, bool use_explicit_name)
Definition: sp_head.h:127
LEX_CSTRING m_db
Definition: sp_head.h:122
sp_parser_data provides a scope for attributes used at the SP-parsing stage only.
Definition: sp_head.h:146
const char * m_current_stmt_start_ptr
Start of the current statement's query string.
Definition: sp_head.h:309
void push_lex(LEX *lex)
Definition: sp_head.h:234
uint m_cont_level
The current continue backpatch level.
Definition: sp_head.h:355
bool add_backpatch_entry(sp_branch_instr *i, sp_label *label)
Put the instruction on the backpatch list, associated with the label.
Definition: sp_head.cc:3453
void start_parsing_sp_body(THD *thd, sp_head *sp)
Start parsing a stored program body statement.
Definition: sp_head.cc:3420
Item * m_saved_item_list
THD's item list.
Definition: sp_head.h:369
const char * get_option_start_ptr() const
Definition: sp_head.h:210
const char * m_param_end_ptr
Position in the CREATE PROCEDURE- or CREATE FUNCTION-statement's query string corresponding to the en...
Definition: sp_head.h:332
void do_cont_backpatch(uint dest)
Backpatch (and pop) the current level to the given instruction pointer.
Definition: sp_head.cc:3478
bool is_parsing_sp_body() const
Definition: sp_head.h:192
MEM_ROOT * m_saved_memroot
THD's memroot.
Definition: sp_head.h:366
sp_parser_data()
Definition: sp_head.h:154
const char * m_param_start_ptr
Position in the CREATE PROCEDURE- or CREATE FUNCTION-statement's query string corresponding to the st...
Definition: sp_head.h:325
void process_new_sp_instr(THD *thd, sp_instr *i)
Definition: sp_head.cc:3489
const char * get_parameter_end_ptr() const
Definition: sp_head.h:222
void set_body_start_ptr(const char *ptr)
Definition: sp_head.h:230
void set_parameter_start_ptr(const char *ptr)
Definition: sp_head.h:220
void set_current_stmt_start_ptr(const char *stmt_start_ptr)
Definition: sp_head.h:204
const char * m_body_start_ptr
Position in the CREATE-/ALTER-stored-program statement's query string corresponding to the start of t...
Definition: sp_head.h:338
void set_parameter_end_ptr(const char *ptr)
Definition: sp_head.h:224
List< Backpatch_info > m_backpatch
Instructions needing backpatching.
Definition: sp_head.h:341
LEX * pop_lex()
Definition: sp_head.h:236
bool add_cont_backpatch_entry(sp_lex_branch_instr *i)
Add a SP-instruction to the current level.
Definition: sp_head.cc:3473
List< LEX > m_lex_stack
Stack of LEX-objects.
Definition: sp_head.h:318
const char * m_option_start_ptr
Start of the SET-expression query string.
Definition: sp_head.h:312
List< sp_lex_branch_instr > m_cont_backpatch
We need a special list for backpatching of instructions with a continue destination (in the case of a...
Definition: sp_head.h:352
void set_option_start_ptr(const char *option_start_ptr)
Definition: sp_head.h:212
const char * get_body_start_ptr() const
Definition: sp_head.h:228
bool new_cont_backpatch()
Start a new backpatch level for the SP-instruction requiring continue destination.
Definition: sp_head.h:286
void finish_parsing_sp_body(THD *thd)
Finish parsing of a stored program body statement.
Definition: sp_head.cc:3431
const char * get_parameter_start_ptr() const
Definition: sp_head.h:218
const char * get_current_stmt_start_ptr() const
Definition: sp_head.h:200
void do_backpatch(sp_label *label, uint dest)
Update all instruction with the given label in the backpatch list to the given instruction pointer.
Definition: sp_head.cc:3464
The class represents parse-time context, which keeps track of declared variables/parameters,...
Definition: sp_pcontext.h:252
static MEM_ROOT mem_root
Definition: client_plugin.cc:110
ulonglong sql_mode_t
Definition: dd_event.h:37
Fido Client Authentication nullptr
Definition: fido_client_plugin.cc:222
enum_sp_type
enum_sp_type defines type codes of stored programs.
Definition: sql_lex.h:222
void my_error(int nr, myf MyFlags,...)
Fill in and print a previously registered error message.
Definition: my_error.cc:216
void init_sp_psi_keys(void)
Definition: sp_head.cc:1542
struct PSI_sp_share PSI_sp_share
Definition: psi_statement_bits.h:119
This file follows Google coding style, except for the name MEM_ROOT (which is kept for historical rea...
#define DBUG_PRINT(keyword, arglist)
Definition: my_dbug.h:181
Some integer typedefs for easier portability.
int64_t int64
Definition: my_inttypes.h:68
long long int longlong
Definition: my_inttypes.h:55
#define MYF(v)
Definition: my_inttypes.h:97
uint32_t uint32
Definition: my_inttypes.h:67
Defines various enable/disable and HAVE_ macros related to the performance schema instrumentation sys...
enum_sql_command
Definition: my_sqlcommand.h:46
Common header for many mysys elements.
static char * where
Definition: mysqldump.cc:140
static const char * sql_mode
Definition: mysqlslap.cc:197
const char * table_name
Definition: rules_table_service.cc:56
const char * db_name
Definition: rules_table_service.cc:55
Performance schema instrumentation interface.
required string type
Definition: replication_group_member_actions.proto:34
case opt name
Definition: sslopt-case.h:33
Definition: m_ctype.h:385
The current state of the privilege checking process for the current user, SQL statement and SQL objec...
Definition: table.h:358
The LEX object currently serves three different purposes:
Definition: sql_lex.h:3710
The MEM_ROOT is a simple arena, where allocations are carved out of larger blocks.
Definition: my_alloc.h:83
Definition: mysql_lex_string.h:40
Definition: mysql_lex_string.h:35
char * str
Definition: mysql_lex_string.h:36
size_t length
Definition: mysql_lex_string.h:37
Definition: my_bitmap.h:43
SP_TABLE represents all instances of one table in an optimized multi-set of tables used by a stored p...
Definition: sp_head.cc:1568
Definition: table.h:1399
Definition: result.h:30
Definition: sp_head.h:148
sp_label * label
Definition: sp_head.h:149
sp_branch_instr * instr
Definition: sp_head.h:150
Definition: sql_lex.h:2466
Definition: sql_lex.h:2475
#define NULL
Definition: types.h:55
unsigned int uint
Definition: uca9-dump.cc:75