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