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