1 /*
2    Copyright (c) 2000, 2016, Oracle and/or its affiliates.
3    Copyright (c) 2009, 2021, MariaDB Corporation.
4 
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; version 2 of the License.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1335  USA */
17 
18 #ifndef SQL_CLASS_INCLUDED
19 #define SQL_CLASS_INCLUDED
20 
21 /* Classes in mysql */
22 
23 #include "dur_prop.h"
24 #include <waiting_threads.h>
25 #include "sql_const.h"
26 #include <mysql/plugin_audit.h>
27 #include "log.h"
28 #include "rpl_tblmap.h"
29 #include "mdl.h"
30 #include "field.h"                              // Create_field
31 #include "probes_mysql.h"
32 #include "sql_locale.h"     /* my_locale_st */
33 #include "sql_profile.h"    /* PROFILING */
34 #include "scheduler.h"      /* thd_scheduler */
35 #include "protocol.h"       /* Protocol_text, Protocol_binary */
36 #include "violite.h"        /* vio_is_connected */
37 #include "thr_lock.h"       /* thr_lock_type, THR_LOCK_DATA, THR_LOCK_INFO */
38 #include "thr_timer.h"
39 #include "thr_malloc.h"
40 #include "log_slow.h"      /* LOG_SLOW_DISABLE_... */
41 #include <my_tree.h>
42 
43 #include "sql_digest_stream.h"            // sql_digest_state
44 
45 #include <mysql/psi/mysql_stage.h>
46 #include <mysql/psi/mysql_statement.h>
47 #include <mysql/psi/mysql_idle.h>
48 #include <mysql/psi/mysql_table.h>
49 #include <mysql_com_server.h>
50 #include "session_tracker.h"
51 
52 extern "C"
53 void set_thd_stage_info(void *thd,
54                         const PSI_stage_info *new_stage,
55                         PSI_stage_info *old_stage,
56                         const char *calling_func,
57                         const char *calling_file,
58                         const unsigned int calling_line);
59 
60 #define THD_STAGE_INFO(thd, stage) \
61   (thd)->enter_stage(&stage, __func__, __FILE__, __LINE__)
62 
63 #include "my_apc.h"
64 #include "rpl_gtid.h"
65 #include "wsrep_mysqld.h"
66 
67 class Reprepare_observer;
68 class Relay_log_info;
69 struct rpl_group_info;
70 class Rpl_filter;
71 class Query_log_event;
72 class Load_log_event;
73 class sp_rcontext;
74 class sp_cache;
75 class Lex_input_stream;
76 class Parser_state;
77 class Rows_log_event;
78 class Sroutine_hash_entry;
79 class user_var_entry;
80 struct Trans_binlog_info;
81 class rpl_io_thread_info;
82 class rpl_sql_thread_info;
83 
84 enum enum_ha_read_modes { RFIRST, RNEXT, RPREV, RLAST, RKEY, RNEXT_SAME };
85 enum enum_duplicates { DUP_ERROR, DUP_REPLACE, DUP_UPDATE };
86 enum enum_delay_key_write { DELAY_KEY_WRITE_NONE, DELAY_KEY_WRITE_ON,
87 			    DELAY_KEY_WRITE_ALL };
88 enum enum_slave_exec_mode { SLAVE_EXEC_MODE_STRICT,
89                             SLAVE_EXEC_MODE_IDEMPOTENT,
90                             SLAVE_EXEC_MODE_LAST_BIT };
91 enum enum_slave_run_triggers_for_rbr { SLAVE_RUN_TRIGGERS_FOR_RBR_NO,
92                                        SLAVE_RUN_TRIGGERS_FOR_RBR_YES,
93                                        SLAVE_RUN_TRIGGERS_FOR_RBR_LOGGING};
94 enum enum_slave_type_conversions { SLAVE_TYPE_CONVERSIONS_ALL_LOSSY,
95                                    SLAVE_TYPE_CONVERSIONS_ALL_NON_LOSSY};
96 
97 /*
98   MARK_COLUMNS_READ:  A column is goind to be read.
99   MARK_COLUMNS_WRITE: A column is going to be written to.
100   MARK_COLUMNS_READ:  A column is goind to be read.
101                       A bit in read set is set to inform handler that the field
102                       is to be read. If field list contains duplicates, then
103                       thd->dup_field is set to point to the last found
104                       duplicate.
105   MARK_COLUMNS_WRITE: A column is going to be written to.
106                       A bit is set in write set to inform handler that it needs
107                       to update this field in write_row and update_row.
108 */
109 enum enum_column_usage
110 { COLUMNS_READ, COLUMNS_WRITE, MARK_COLUMNS_READ, MARK_COLUMNS_WRITE};
111 
should_mark_column(enum_column_usage column_usage)112 static inline bool should_mark_column(enum_column_usage column_usage)
113 { return column_usage >= MARK_COLUMNS_READ; }
114 
115 enum enum_filetype { FILETYPE_CSV, FILETYPE_XML };
116 
117 enum enum_binlog_row_image {
118   /** PKE in the before image and changed columns in the after image */
119   BINLOG_ROW_IMAGE_MINIMAL= 0,
120   /** Whenever possible, before and after image contain all columns except blobs. */
121   BINLOG_ROW_IMAGE_NOBLOB= 1,
122   /** All columns in both before and after image. */
123   BINLOG_ROW_IMAGE_FULL= 2
124 };
125 
126 
127 /* Bits for different SQL modes modes (including ANSI mode) */
128 #define MODE_REAL_AS_FLOAT              (1ULL << 0)
129 #define MODE_PIPES_AS_CONCAT            (1ULL << 1)
130 #define MODE_ANSI_QUOTES                (1ULL << 2)
131 #define MODE_IGNORE_SPACE               (1ULL << 3)
132 #define MODE_IGNORE_BAD_TABLE_OPTIONS   (1ULL << 4)
133 #define MODE_ONLY_FULL_GROUP_BY         (1ULL << 5)
134 #define MODE_NO_UNSIGNED_SUBTRACTION    (1ULL << 6)
135 #define MODE_NO_DIR_IN_CREATE           (1ULL << 7)
136 #define MODE_POSTGRESQL                 (1ULL << 8)
137 #define MODE_ORACLE                     (1ULL << 9)
138 #define MODE_MSSQL                      (1ULL << 10)
139 #define MODE_DB2                        (1ULL << 11)
140 #define MODE_MAXDB                      (1ULL << 12)
141 #define MODE_NO_KEY_OPTIONS             (1ULL << 13)
142 #define MODE_NO_TABLE_OPTIONS           (1ULL << 14)
143 #define MODE_NO_FIELD_OPTIONS           (1ULL << 15)
144 #define MODE_MYSQL323                   (1ULL << 16)
145 #define MODE_MYSQL40                    (1ULL << 17)
146 #define MODE_ANSI                       (1ULL << 18)
147 #define MODE_NO_AUTO_VALUE_ON_ZERO      (1ULL << 19)
148 #define MODE_NO_BACKSLASH_ESCAPES       (1ULL << 20)
149 #define MODE_STRICT_TRANS_TABLES        (1ULL << 21)
150 #define MODE_STRICT_ALL_TABLES          (1ULL << 22)
151 #define MODE_NO_ZERO_IN_DATE            (1ULL << 23)
152 #define MODE_NO_ZERO_DATE               (1ULL << 24)
153 #define MODE_INVALID_DATES              (1ULL << 25)
154 #define MODE_ERROR_FOR_DIVISION_BY_ZERO (1ULL << 26)
155 #define MODE_TRADITIONAL                (1ULL << 27)
156 #define MODE_NO_AUTO_CREATE_USER        (1ULL << 28)
157 #define MODE_HIGH_NOT_PRECEDENCE        (1ULL << 29)
158 #define MODE_NO_ENGINE_SUBSTITUTION     (1ULL << 30)
159 #define MODE_PAD_CHAR_TO_FULL_LENGTH    (1ULL << 31)
160 #define MODE_EMPTY_STRING_IS_NULL       (1ULL << 32)
161 #define MODE_SIMULTANEOUS_ASSIGNMENT    (1ULL << 33)
162 
163 /* Bits for different old style modes */
164 #define OLD_MODE_NO_DUP_KEY_WARNINGS_WITH_IGNORE	(1 << 0)
165 #define OLD_MODE_NO_PROGRESS_INFO			(1 << 1)
166 #define OLD_MODE_ZERO_DATE_TIME_CAST                    (1 << 2)
167 
168 extern char internal_table_name[2];
169 extern char empty_c_string[1];
170 extern MYSQL_PLUGIN_IMPORT const char **errmesg;
171 
172 extern bool volatile shutdown_in_progress;
173 
174 extern "C" LEX_STRING * thd_query_string (MYSQL_THD thd);
175 extern "C" size_t thd_query_safe(MYSQL_THD thd, char *buf, size_t buflen);
176 
177 /**
178   @class CSET_STRING
179   @brief Character set armed LEX_STRING
180 */
181 class CSET_STRING
182 {
183 private:
184   LEX_STRING string;
185   CHARSET_INFO *cs;
186 public:
CSET_STRING()187   CSET_STRING() : cs(&my_charset_bin)
188   {
189     string.str= NULL;
190     string.length= 0;
191   }
CSET_STRING(char * str_arg,size_t length_arg,CHARSET_INFO * cs_arg)192   CSET_STRING(char *str_arg, size_t length_arg, CHARSET_INFO *cs_arg) :
193   cs(cs_arg)
194   {
195     DBUG_ASSERT(cs_arg != NULL);
196     string.str= str_arg;
197     string.length= length_arg;
198   }
199 
str()200   inline char *str() const { return string.str; }
length()201   inline size_t length() const { return string.length; }
charset()202   CHARSET_INFO *charset() const { return cs; }
203 
204   friend LEX_STRING * thd_query_string (MYSQL_THD thd);
205 };
206 
207 
208 #define TC_HEURISTIC_RECOVER_COMMIT   1
209 #define TC_HEURISTIC_RECOVER_ROLLBACK 2
210 extern ulong tc_heuristic_recover;
211 
212 typedef struct st_user_var_events
213 {
214   user_var_entry *user_var_event;
215   char *value;
216   size_t length;
217   Item_result type;
218   uint charset_number;
219   bool unsigned_flag;
220 } BINLOG_USER_VAR_EVENT;
221 
222 /*
223   The COPY_INFO structure is used by INSERT/REPLACE code.
224   The schema of the row counting by the INSERT/INSERT ... ON DUPLICATE KEY
225   UPDATE code:
226     If a row is inserted then the copied variable is incremented.
227     If a row is updated by the INSERT ... ON DUPLICATE KEY UPDATE and the
228       new data differs from the old one then the copied and the updated
229       variables are incremented.
230     The touched variable is incremented if a row was touched by the update part
231       of the INSERT ... ON DUPLICATE KEY UPDATE no matter whether the row
232       was actually changed or not.
233 */
234 typedef struct st_copy_info {
235   ha_rows records; /**< Number of processed records */
236   ha_rows deleted; /**< Number of deleted records */
237   ha_rows updated; /**< Number of updated records */
238   ha_rows copied;  /**< Number of copied records */
239   ha_rows error_count;
240   ha_rows touched; /* Number of touched records */
241   enum enum_duplicates handle_duplicates;
242   int escape_char, last_errno;
243   bool ignore;
244   /* for INSERT ... UPDATE */
245   List<Item> *update_fields;
246   List<Item> *update_values;
247   /* for VIEW ... WITH CHECK OPTION */
248   TABLE_LIST *view;
249   TABLE_LIST *table_list;                       /* Normal table */
250 } COPY_INFO;
251 
252 
253 class Key_part_spec :public Sql_alloc {
254 public:
255   LEX_CSTRING field_name;
256   uint length;
257   bool generated;
258   Key_part_spec(const LEX_CSTRING *name, uint len, bool gen= false)
259     : field_name(*name), length(len), generated(gen)
260   {}
261   bool operator==(const Key_part_spec& other) const;
262   /**
263     Construct a copy of this Key_part_spec. field_name is copied
264     by-pointer as it is known to never change. At the same time
265     'length' may be reset in mysql_prepare_create_table, and this
266     is why we supply it with a copy.
267 
268     @return If out of memory, 0 is returned and an error is set in
269     THD.
270   */
clone(MEM_ROOT * mem_root)271   Key_part_spec *clone(MEM_ROOT *mem_root) const
272   { return new (mem_root) Key_part_spec(*this); }
273 };
274 
275 
276 class Alter_drop :public Sql_alloc {
277 public:
278   enum drop_type {KEY, COLUMN, FOREIGN_KEY, CHECK_CONSTRAINT };
279   const char *name;
280   enum drop_type type;
281   bool drop_if_exists;
Alter_drop(enum drop_type par_type,const char * par_name,bool par_exists)282   Alter_drop(enum drop_type par_type,const char *par_name, bool par_exists)
283     :name(par_name), type(par_type), drop_if_exists(par_exists)
284   {
285     DBUG_ASSERT(par_name != NULL);
286   }
287   /**
288     Used to make a clone of this object for ALTER/CREATE TABLE
289     @sa comment for Key_part_spec::clone
290   */
clone(MEM_ROOT * mem_root)291   Alter_drop *clone(MEM_ROOT *mem_root) const
292     { return new (mem_root) Alter_drop(*this); }
type_name()293   const char *type_name()
294   {
295     return type == COLUMN ? "COLUMN" :
296            type == CHECK_CONSTRAINT ? "CONSTRAINT" :
297            type == KEY ? "INDEX" : "FOREIGN KEY";
298   }
299 };
300 
301 
302 class Alter_column :public Sql_alloc {
303 public:
304   const char *name;
305   Virtual_column_info *default_value;
306   bool alter_if_exists;
Alter_column(const char * par_name,Virtual_column_info * expr,bool par_exists)307   Alter_column(const char *par_name, Virtual_column_info *expr, bool par_exists)
308     :name(par_name), default_value(expr), alter_if_exists(par_exists) {}
309   /**
310     Used to make a clone of this object for ALTER/CREATE TABLE
311     @sa comment for Key_part_spec::clone
312   */
clone(MEM_ROOT * mem_root)313   Alter_column *clone(MEM_ROOT *mem_root) const
314     { return new (mem_root) Alter_column(*this); }
315 };
316 
317 
318 class Key :public Sql_alloc, public DDL_options {
319 public:
320   enum Keytype { PRIMARY, UNIQUE, MULTIPLE, FULLTEXT, SPATIAL, FOREIGN_KEY};
321   enum Keytype type;
322   KEY_CREATE_INFO key_create_info;
323   List<Key_part_spec> columns;
324   LEX_CSTRING name;
325   engine_option_value *option_list;
326   bool generated;
327   bool invisible;
328 
Key(enum Keytype type_par,const LEX_CSTRING * name_arg,ha_key_alg algorithm_arg,bool generated_arg,DDL_options_st ddl_options)329   Key(enum Keytype type_par, const LEX_CSTRING *name_arg,
330       ha_key_alg algorithm_arg, bool generated_arg, DDL_options_st ddl_options)
331     :DDL_options(ddl_options),
332      type(type_par), key_create_info(default_key_create_info),
333     name(*name_arg), option_list(NULL), generated(generated_arg),
334     invisible(false)
335   {
336     key_create_info.algorithm= algorithm_arg;
337   }
Key(enum Keytype type_par,const LEX_CSTRING * name_arg,KEY_CREATE_INFO * key_info_arg,bool generated_arg,List<Key_part_spec> * cols,engine_option_value * create_opt,DDL_options_st ddl_options)338   Key(enum Keytype type_par, const LEX_CSTRING *name_arg,
339       KEY_CREATE_INFO *key_info_arg,
340       bool generated_arg, List<Key_part_spec> *cols,
341       engine_option_value *create_opt, DDL_options_st ddl_options)
342     :DDL_options(ddl_options),
343      type(type_par), key_create_info(*key_info_arg), columns(*cols),
344     name(*name_arg), option_list(create_opt), generated(generated_arg),
345     invisible(false)
346   {}
347   Key(const Key &rhs, MEM_ROOT *mem_root);
~Key()348   virtual ~Key() {}
349   /* Equality comparison of keys (ignoring name) */
350   friend bool foreign_key_prefix(Key *a, Key *b);
351   /**
352     Used to make a clone of this object for ALTER/CREATE TABLE
353     @sa comment for Key_part_spec::clone
354   */
clone(MEM_ROOT * mem_root)355   virtual Key *clone(MEM_ROOT *mem_root) const
356     { return new (mem_root) Key(*this, mem_root); }
357 };
358 
359 
360 class Foreign_key: public Key {
361 public:
362   enum fk_match_opt { FK_MATCH_UNDEF, FK_MATCH_FULL,
363 		      FK_MATCH_PARTIAL, FK_MATCH_SIMPLE};
364   LEX_CSTRING ref_db;
365   LEX_CSTRING ref_table;
366   List<Key_part_spec> ref_columns;
367   enum enum_fk_option delete_opt, update_opt;
368   enum fk_match_opt match_opt;
Foreign_key(const LEX_CSTRING * name_arg,List<Key_part_spec> * cols,const LEX_CSTRING * ref_db_arg,const LEX_CSTRING * ref_table_arg,List<Key_part_spec> * ref_cols,enum_fk_option delete_opt_arg,enum_fk_option update_opt_arg,fk_match_opt match_opt_arg,DDL_options ddl_options)369   Foreign_key(const LEX_CSTRING *name_arg, List<Key_part_spec> *cols,
370 	      const LEX_CSTRING *ref_db_arg, const LEX_CSTRING *ref_table_arg,
371               List<Key_part_spec> *ref_cols,
372               enum_fk_option delete_opt_arg, enum_fk_option update_opt_arg,
373               fk_match_opt match_opt_arg,
374 	      DDL_options ddl_options)
375     :Key(FOREIGN_KEY, name_arg, &default_key_create_info, 0, cols, NULL,
376          ddl_options),
377     ref_db(*ref_db_arg), ref_table(*ref_table_arg), ref_columns(*ref_cols),
378     delete_opt(delete_opt_arg), update_opt(update_opt_arg),
379     match_opt(match_opt_arg)
380    {
381     // We don't check for duplicate FKs.
382     key_create_info.check_for_duplicate_indexes= false;
383   }
384  Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root);
385   /**
386     Used to make a clone of this object for ALTER/CREATE TABLE
387     @sa comment for Key_part_spec::clone
388   */
clone(MEM_ROOT * mem_root)389   virtual Key *clone(MEM_ROOT *mem_root) const
390   { return new (mem_root) Foreign_key(*this, mem_root); }
391   /* Used to validate foreign key options */
392   bool validate(List<Create_field> &table_fields);
393 };
394 
395 typedef struct st_mysql_lock
396 {
397   TABLE **table;
398   THR_LOCK_DATA **locks;
399   uint table_count,lock_count;
400   uint flags;
401 } MYSQL_LOCK;
402 
403 
404 class LEX_COLUMN : public Sql_alloc
405 {
406 public:
407   String column;
408   uint rights;
LEX_COLUMN(const String & x,const uint & y)409   LEX_COLUMN (const String& x,const  uint& y ): column (x),rights (y) {}
410 };
411 
412 class MY_LOCALE;
413 
414 /**
415   Query_cache_tls -- query cache thread local data.
416 */
417 
418 struct Query_cache_block;
419 
420 struct Query_cache_tls
421 {
422   /*
423     'first_query_block' should be accessed only via query cache
424     functions and methods to maintain proper locking.
425   */
426   Query_cache_block *first_query_block;
set_first_query_blockQuery_cache_tls427   void set_first_query_block(Query_cache_block *first_query_block_arg)
428   {
429     first_query_block= first_query_block_arg;
430   }
431 
Query_cache_tlsQuery_cache_tls432   Query_cache_tls() :first_query_block(NULL) {}
433 };
434 
435 /* SIGNAL / RESIGNAL / GET DIAGNOSTICS */
436 
437 /**
438   This enumeration list all the condition item names of a condition in the
439   SQL condition area.
440 */
441 typedef enum enum_diag_condition_item_name
442 {
443   /*
444     Conditions that can be set by the user (SIGNAL/RESIGNAL),
445     and by the server implementation.
446   */
447 
448   DIAG_CLASS_ORIGIN= 0,
449   FIRST_DIAG_SET_PROPERTY= DIAG_CLASS_ORIGIN,
450   DIAG_SUBCLASS_ORIGIN= 1,
451   DIAG_CONSTRAINT_CATALOG= 2,
452   DIAG_CONSTRAINT_SCHEMA= 3,
453   DIAG_CONSTRAINT_NAME= 4,
454   DIAG_CATALOG_NAME= 5,
455   DIAG_SCHEMA_NAME= 6,
456   DIAG_TABLE_NAME= 7,
457   DIAG_COLUMN_NAME= 8,
458   DIAG_CURSOR_NAME= 9,
459   DIAG_MESSAGE_TEXT= 10,
460   DIAG_MYSQL_ERRNO= 11,
461   LAST_DIAG_SET_PROPERTY= DIAG_MYSQL_ERRNO
462 } Diag_condition_item_name;
463 
464 /**
465   Name of each diagnostic condition item.
466   This array is indexed by Diag_condition_item_name.
467 */
468 extern const LEX_CSTRING Diag_condition_item_names[];
469 
470 /**
471   These states are bit coded with HARD. For each state there must be a pair
472   <state_even_num>, and <state_odd_num>_HARD.
473 */
474 enum killed_state
475 {
476   NOT_KILLED= 0,
477   KILL_HARD_BIT= 1,                             /* Bit for HARD KILL */
478   KILL_BAD_DATA= 2,
479   KILL_BAD_DATA_HARD= 3,
480   KILL_QUERY= 4,
481   KILL_QUERY_HARD= 5,
482   /*
483     ABORT_QUERY signals to the query processor to stop execution ASAP without
484     issuing an error. Instead a warning is issued, and when possible a partial
485     query result is returned to the client.
486   */
487   ABORT_QUERY= 6,
488   ABORT_QUERY_HARD= 7,
489   KILL_TIMEOUT= 8,
490   KILL_TIMEOUT_HARD= 9,
491   /*
492     When binlog reading thread connects to the server it kills
493     all the binlog threads with the same ID.
494   */
495   KILL_SLAVE_SAME_ID= 10,
496   /*
497     All of the following killed states will kill the connection
498     KILL_CONNECTION must be the first of these and it must start with
499     an even number (becasue of HARD bit)!
500   */
501   KILL_CONNECTION= 12,
502   KILL_CONNECTION_HARD= 13,
503   KILL_SYSTEM_THREAD= 14,
504   KILL_SYSTEM_THREAD_HARD= 15,
505   KILL_SERVER= 16,
506   KILL_SERVER_HARD= 17,
507   /*
508     Used in threadpool to signal wait timeout.
509   */
510   KILL_WAIT_TIMEOUT= 18,
511   KILL_WAIT_TIMEOUT_HARD= 19
512 
513 };
514 
515 #define killed_mask_hard(killed) ((killed_state) ((killed) & ~KILL_HARD_BIT))
516 
517 enum killed_type
518 {
519   KILL_TYPE_ID,
520   KILL_TYPE_USER,
521   KILL_TYPE_QUERY
522 };
523 
524 #include "sql_lex.h"				/* Must be here */
525 
526 class Delayed_insert;
527 class select_result;
528 class Time_zone;
529 
530 #define THD_SENTRY_MAGIC 0xfeedd1ff
531 #define THD_SENTRY_GONE  0xdeadbeef
532 
533 #define THD_CHECK_SENTRY(thd) DBUG_ASSERT(thd->dbug_sentry == THD_SENTRY_MAGIC)
534 
535 typedef struct system_variables
536 {
537   /*
538     How dynamically allocated system variables are handled:
539 
540     The global_system_variables and max_system_variables are "authoritative"
541     They both should have the same 'version' and 'size'.
542     When attempting to access a dynamic variable, if the session version
543     is out of date, then the session version is updated and realloced if
544     neccessary and bytes copied from global to make up for missing data.
545 
546     Note that one should use my_bool instead of bool here, as the variables
547     are used with my_getopt.c
548   */
549   ulong dynamic_variables_version;
550   char* dynamic_variables_ptr;
551   uint dynamic_variables_head;    /* largest valid variable offset */
552   uint dynamic_variables_size;    /* how many bytes are in use */
553 
554   ulonglong max_heap_table_size;
555   ulonglong tmp_memory_table_size;
556   ulonglong tmp_disk_table_size;
557   ulonglong long_query_time;
558   ulonglong max_statement_time;
559   ulonglong optimizer_switch;
560   sql_mode_t sql_mode; ///< which non-standard SQL behaviour should be enabled
561   sql_mode_t old_behavior; ///< which old SQL behaviour should be enabled
562   ulonglong option_bits; ///< OPTION_xxx constants, e.g. OPTION_PROFILING
563   ulonglong join_buff_space_limit;
564   ulonglong log_slow_filter;
565   ulonglong log_slow_verbosity;
566   ulonglong log_slow_disabled_statements;
567   ulonglong log_disabled_statements;
568   ulonglong bulk_insert_buff_size;
569   ulonglong join_buff_size;
570   ulonglong sortbuff_size;
571   ulonglong default_regex_flags;
572   ulonglong max_mem_used;
573 
574   /**
575      Place holders to store Multi-source variables in sys_var.cc during
576      update and show of variables.
577   */
578   ulonglong slave_skip_counter;
579   ulonglong max_relay_log_size;
580 
581   ha_rows select_limit;
582   ha_rows max_join_size;
583   ha_rows expensive_subquery_limit;
584   ulong auto_increment_increment, auto_increment_offset;
585 #ifdef WITH_WSREP
586   /*
587     Stored values of the auto_increment_increment and auto_increment_offset
588     that are will be restored when wsrep_auto_increment_control will be set
589     to 'OFF', because the setting it to 'ON' leads to overwriting of the
590     original values (which are set by the user) by calculated ones (which
591     are based on the cluster size):
592   */
593   ulong saved_auto_increment_increment, saved_auto_increment_offset;
594 #endif /* WITH_WSREP */
595   uint eq_range_index_dive_limit;
596   ulong column_compression_zlib_strategy;
597   ulong lock_wait_timeout;
598   ulong join_cache_level;
599   ulong max_allowed_packet;
600   ulong max_error_count;
601   ulong max_length_for_sort_data;
602   ulong max_recursive_iterations;
603   ulong max_sort_length;
604   ulong max_tmp_tables;
605   ulong max_insert_delayed_threads;
606   ulong min_examined_row_limit;
607   ulong multi_range_count;
608   ulong net_buffer_length;
609   ulong net_interactive_timeout;
610   ulong net_read_timeout;
611   ulong net_retry_count;
612   ulong net_wait_timeout;
613   ulong net_write_timeout;
614   ulong optimizer_prune_level;
615   ulong optimizer_search_depth;
616   ulong optimizer_selectivity_sampling_limit;
617   ulong optimizer_use_condition_selectivity;
618   ulong use_stat_tables;
619   ulong histogram_size;
620   ulong histogram_type;
621   ulong preload_buff_size;
622   ulong profiling_history_size;
623   ulong read_buff_size;
624   ulong read_rnd_buff_size;
625   ulong mrr_buff_size;
626   ulong div_precincrement;
627   /* Total size of all buffers used by the subselect_rowid_merge_engine. */
628   ulong rowid_merge_buff_size;
629   ulong max_sp_recursion_depth;
630   ulong default_week_format;
631   ulong max_seeks_for_key;
632   ulong range_alloc_block_size;
633   ulong query_alloc_block_size;
634   ulong query_prealloc_size;
635   ulong trans_alloc_block_size;
636   ulong trans_prealloc_size;
637   ulong log_warnings;
638   /* Flags for slow log filtering */
639   ulong log_slow_rate_limit;
640   ulong binlog_format; ///< binlog format for this thd (see enum_binlog_format)
641   ulong binlog_row_image;
642   ulong progress_report_time;
643   ulong completion_type;
644   ulong query_cache_type;
645   ulong tx_isolation;
646   ulong updatable_views_with_limit;
647   ulong alter_algorithm;
648   int max_user_connections;
649   ulong server_id;
650   /**
651     In slave thread we need to know in behalf of which
652     thread the query is being run to replicate temp tables properly
653   */
654   my_thread_id pseudo_thread_id;
655   /**
656      When replicating an event group with GTID, keep these values around so
657      slave binlog can receive the same GTID as the original.
658   */
659   uint32     gtid_domain_id;
660   uint64     gtid_seq_no;
661 
662   uint group_concat_max_len;
663 
664   /**
665     Default transaction access mode. READ ONLY (true) or READ WRITE (false).
666   */
667   my_bool tx_read_only;
668   my_bool low_priority_updates;
669   my_bool query_cache_wlock_invalidate;
670   my_bool keep_files_on_create;
671 
672   my_bool old_mode;
673   my_bool old_passwords;
674   my_bool big_tables;
675   my_bool only_standard_compliant_cte;
676   my_bool query_cache_strip_comments;
677   my_bool sql_log_slow;
678   my_bool sql_log_bin;
679   /*
680     A flag to help detect whether binary logging was temporarily disabled
681     (see tmp_disable_binlog(A) macro).
682   */
683   my_bool sql_log_bin_off;
684   my_bool binlog_annotate_row_events;
685   my_bool binlog_direct_non_trans_update;
686   my_bool column_compression_zlib_wrap;
687 
688   plugin_ref table_plugin;
689   plugin_ref tmp_table_plugin;
690   plugin_ref enforced_table_plugin;
691 
692   /* Only charset part of these variables is sensible */
693   CHARSET_INFO  *character_set_filesystem;
694   CHARSET_INFO  *character_set_client;
695   CHARSET_INFO  *character_set_results;
696 
697   /* Both charset and collation parts of these variables are important */
698   CHARSET_INFO	*collation_server;
699   CHARSET_INFO	*collation_database;
700   CHARSET_INFO  *collation_connection;
701 
702   /* Names. These will be allocated in buffers in thd */
703   LEX_CSTRING default_master_connection;
704 
705   /* Error messages */
706   MY_LOCALE *lc_messages;
707   const char ***errmsgs;             /* lc_messages->errmsg->errmsgs */
708 
709   /* Locale Support */
710   MY_LOCALE *lc_time_names;
711 
712   Time_zone *time_zone;
713 
714   my_bool sysdate_is_now;
715 
716   /* deadlock detection */
717   ulong wt_timeout_short, wt_deadlock_search_depth_short;
718   ulong wt_timeout_long, wt_deadlock_search_depth_long;
719 
720   my_bool wsrep_on;
721   my_bool wsrep_causal_reads;
722   my_bool wsrep_dirty_reads;
723   uint wsrep_sync_wait;
724   ulong wsrep_retry_autocommit;
725   ulong wsrep_OSU_method;
726   double long_query_time_double, max_statement_time_double;
727 
728   my_bool pseudo_slave_mode;
729 
730   char *session_track_system_variables;
731   ulong session_track_transaction_info;
732   my_bool session_track_schema;
733   my_bool session_track_state_change;
734 
735   ulong threadpool_priority;
736 
737   uint idle_transaction_timeout;
738   uint idle_readonly_transaction_timeout;
739   uint idle_write_transaction_timeout;
740   uint column_compression_threshold;
741   uint column_compression_zlib_level;
742   uint in_subquery_conversion_threshold;
743 
744   vers_asof_timestamp_t vers_asof_timestamp;
745   ulong vers_alter_history;
746 } SV;
747 
748 /**
749   Per thread status variables.
750   Must be long/ulong up to last_system_status_var so that
751   add_to_status/add_diff_to_status can work.
752 */
753 
754 typedef struct system_status_var
755 {
756   ulong column_compressions;
757   ulong column_decompressions;
758   ulong com_stat[(uint) SQLCOM_END];
759   ulong com_create_tmp_table;
760   ulong com_drop_tmp_table;
761   ulong com_other;
762   ulong com_multi;
763 
764   ulong com_stmt_prepare;
765   ulong com_stmt_reprepare;
766   ulong com_stmt_execute;
767   ulong com_stmt_send_long_data;
768   ulong com_stmt_fetch;
769   ulong com_stmt_reset;
770   ulong com_stmt_close;
771 
772   ulong com_register_slave;
773   ulong created_tmp_disk_tables_;
774   ulong created_tmp_tables_;
775   ulong ha_commit_count;
776   ulong ha_delete_count;
777   ulong ha_read_first_count;
778   ulong ha_read_last_count;
779   ulong ha_read_key_count;
780   ulong ha_read_next_count;
781   ulong ha_read_prev_count;
782   ulong ha_read_retry_count;
783   ulong ha_read_rnd_count;
784   ulong ha_read_rnd_next_count;
785   ulong ha_read_rnd_deleted_count;
786 
787   /*
788     This number doesn't include calls to the default implementation and
789     calls made by range access. The intent is to count only calls made by
790     BatchedKeyAccess.
791   */
792   ulong ha_mrr_init_count;
793   ulong ha_mrr_key_refills_count;
794   ulong ha_mrr_rowid_refills_count;
795 
796   ulong ha_rollback_count;
797   ulong ha_update_count;
798   ulong ha_write_count;
799   /* The following are for internal temporary tables */
800   ulong ha_tmp_update_count;
801   ulong ha_tmp_write_count;
802   ulong ha_tmp_delete_count;
803   ulong ha_prepare_count;
804   ulong ha_icp_attempts;
805   ulong ha_icp_match;
806   ulong ha_discover_count;
807   ulong ha_savepoint_count;
808   ulong ha_savepoint_rollback_count;
809   ulong ha_external_lock_count;
810 
811   ulong opened_tables;
812   ulong opened_shares;
813   ulong opened_views;               /* +1 opening a view */
814 
815   ulong select_full_join_count_;
816   ulong select_full_range_join_count_;
817   ulong select_range_count_;
818   ulong select_range_check_count_;
819   ulong select_scan_count_;
820   ulong update_scan_count;
821   ulong delete_scan_count;
822   ulong executed_triggers;
823   ulong long_query_count;
824   ulong filesort_merge_passes_;
825   ulong filesort_range_count_;
826   ulong filesort_rows_;
827   ulong filesort_scan_count_;
828   ulong filesort_pq_sorts_;
829 
830   /* Features used */
831   ulong feature_custom_aggregate_functions; /* +1 when custom aggregate
832                                             functions are used */
833   ulong feature_dynamic_columns;    /* +1 when creating a dynamic column */
834   ulong feature_fulltext;	    /* +1 when MATCH is used */
835   ulong feature_gis;                /* +1 opening a table with GIS features */
836   ulong feature_invisible_columns;     /* +1 opening a table with invisible column */
837   ulong feature_json;		    /* +1 when JSON function appears in the statement */
838   ulong feature_locale;		    /* +1 when LOCALE is set */
839   ulong feature_subquery;	    /* +1 when subqueries are used */
840   ulong feature_system_versioning;  /* +1 opening a table WITH SYSTEM VERSIONING */
841   ulong feature_timezone;	    /* +1 when XPATH is used */
842   ulong feature_trigger;	    /* +1 opening a table with triggers */
843   ulong feature_xml;		    /* +1 when XPATH is used */
844   ulong feature_window_functions;   /* +1 when window functions are used */
845 
846   /* From MASTER_GTID_WAIT usage */
847   ulong master_gtid_wait_timeouts;          /* Number of timeouts */
848   ulong master_gtid_wait_time;              /* Time in microseconds */
849   ulong master_gtid_wait_count;
850 
851   ulong empty_queries;
852   ulong access_denied_errors;
853   ulong lost_connections;
854   ulong max_statement_time_exceeded;
855   /*
856     Number of statements sent from the client
857   */
858   ulong questions;
859   /*
860     IMPORTANT!
861     SEE last_system_status_var DEFINITION BELOW.
862     Below 'last_system_status_var' are all variables that cannot be handled
863     automatically by add_to_status()/add_diff_to_status().
864   */
865   ulonglong bytes_received;
866   ulonglong bytes_sent;
867   ulonglong rows_read;
868   ulonglong rows_sent;
869   ulonglong rows_tmp_read;
870   ulonglong binlog_bytes_written;
871   ulonglong table_open_cache_hits;
872   ulonglong table_open_cache_misses;
873   ulonglong table_open_cache_overflows;
874   double last_query_cost;
875   double cpu_time, busy_time;
876   uint32 threads_running;
877   /* Don't initialize */
878   /* Memory used for thread local storage */
879   int64 max_local_memory_used;
880   volatile int64 local_memory_used;
881   /* Memory allocated for global usage */
882   volatile int64 global_memory_used;
883 } STATUS_VAR;
884 
885 /*
886   This is used for 'SHOW STATUS'. It must be updated to the last ulong
887   variable in system_status_var which is makes sense to add to the global
888   counter
889 */
890 
891 #define last_system_status_var questions
892 #define last_cleared_system_status_var local_memory_used
893 
894 /*
895   Global status variables
896 */
897 
898 extern ulong feature_files_opened_with_delayed_keys, feature_check_constraint;
899 
900 void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var);
901 
902 void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var,
903                         STATUS_VAR *dec_var);
904 
905 uint calc_sum_of_all_status(STATUS_VAR *to);
calc_sum_of_all_status_if_needed(STATUS_VAR * to)906 static inline void calc_sum_of_all_status_if_needed(STATUS_VAR *to)
907 {
908   if (to->local_memory_used == 0)
909   {
910     mysql_mutex_lock(&LOCK_status);
911     *to= global_status_var;
912     mysql_mutex_unlock(&LOCK_status);
913     calc_sum_of_all_status(to);
914     DBUG_ASSERT(to->local_memory_used);
915   }
916 }
917 
918 /*
919   Update global_memory_used. We have to do this with atomic_add as the
920   global value can change outside of LOCK_status.
921 */
update_global_memory_status(int64 size)922 static inline void update_global_memory_status(int64 size)
923 {
924   DBUG_PRINT("info", ("global memory_used: %lld  size: %lld",
925                       (longlong) global_status_var.global_memory_used,
926                       size));
927   // workaround for gcc 4.2.4-1ubuntu4 -fPIE (from DEB_BUILD_HARDENING=1)
928   int64 volatile * volatile ptr= &global_status_var.global_memory_used;
929   my_atomic_add64_explicit(ptr, size, MY_MEMORY_ORDER_RELAXED);
930 }
931 
932 /**
933   Get collation by name, send error to client on failure.
934   @param name     Collation name
935   @param name_cs  Character set of the name string
936   @return
937   @retval         NULL on error
938   @retval         Pointter to CHARSET_INFO with the given name on success
939 */
940 static inline CHARSET_INFO *
941 mysqld_collation_get_by_name(const char *name,
942                              CHARSET_INFO *name_cs= system_charset_info)
943 {
944   CHARSET_INFO *cs;
945   MY_CHARSET_LOADER loader;
946   my_charset_loader_init_mysys(&loader);
947   if (!(cs= my_collation_get_by_name(&loader, name, MYF(0))))
948   {
949     ErrConvString err(name, name_cs);
950     my_error(ER_UNKNOWN_COLLATION, MYF(0), err.ptr());
951     if (loader.error[0])
952       push_warning_printf(current_thd,
953                           Sql_condition::WARN_LEVEL_WARN,
954                           ER_UNKNOWN_COLLATION, "%s", loader.error);
955   }
956   return cs;
957 }
958 
is_supported_parser_charset(CHARSET_INFO * cs)959 static inline bool is_supported_parser_charset(CHARSET_INFO *cs)
960 {
961   return MY_TEST(cs->mbminlen == 1 && cs->number != 17 /* filename */);
962 }
963 
964 #ifdef MYSQL_SERVER
965 
966 void free_tmp_table(THD *thd, TABLE *entry);
967 
968 
969 /* The following macro is to make init of Query_arena simpler */
970 #ifdef DBUG_ASSERT_EXISTS
971 #define INIT_ARENA_DBUG_INFO is_backup_arena= 0; is_reprepared= FALSE;
972 #else
973 #define INIT_ARENA_DBUG_INFO
974 #endif
975 
976 class Query_arena
977 {
978 public:
979   /*
980     List of items created in the parser for this query. Every item puts
981     itself to the list on creation (see Item::Item() for details))
982   */
983   Item *free_list;
984   MEM_ROOT *mem_root;                   // Pointer to current memroot
985 #ifdef DBUG_ASSERT_EXISTS
986   bool is_backup_arena; /* True if this arena is used for backup. */
987   bool is_reprepared;
988 #endif
989   /*
990     The states relfects three diffrent life cycles for three
991     different types of statements:
992     Prepared statement: STMT_INITIALIZED -> STMT_PREPARED -> STMT_EXECUTED.
993     Stored procedure:   STMT_INITIALIZED_FOR_SP -> STMT_EXECUTED.
994     Other statements:   STMT_CONVENTIONAL_EXECUTION never changes.
995   */
996   enum enum_state
997   {
998     STMT_INITIALIZED= 0, STMT_INITIALIZED_FOR_SP= 1, STMT_PREPARED= 2,
999     STMT_CONVENTIONAL_EXECUTION= 3, STMT_EXECUTED= 4, STMT_ERROR= -1
1000   };
1001 
1002   enum_state state;
1003 
1004 public:
1005   /* We build without RTTI, so dynamic_cast can't be used. */
1006   enum Type
1007   {
1008     STATEMENT, PREPARED_STATEMENT, STORED_PROCEDURE, TABLE_ARENA
1009   };
1010 
Query_arena(MEM_ROOT * mem_root_arg,enum enum_state state_arg)1011   Query_arena(MEM_ROOT *mem_root_arg, enum enum_state state_arg) :
1012     free_list(0), mem_root(mem_root_arg), state(state_arg)
1013   { INIT_ARENA_DBUG_INFO; }
1014   /*
1015     This constructor is used only when Query_arena is created as
1016     backup storage for another instance of Query_arena.
1017   */
Query_arena()1018   Query_arena() { INIT_ARENA_DBUG_INFO; }
1019 
1020   virtual Type type() const;
~Query_arena()1021   virtual ~Query_arena() {};
1022 
is_stmt_prepare()1023   inline bool is_stmt_prepare() const { return state == STMT_INITIALIZED; }
is_stmt_prepare_or_first_sp_execute()1024   inline bool is_stmt_prepare_or_first_sp_execute() const
1025   { return (int)state < (int)STMT_PREPARED; }
is_stmt_prepare_or_first_stmt_execute()1026   inline bool is_stmt_prepare_or_first_stmt_execute() const
1027   { return (int)state <= (int)STMT_PREPARED; }
is_stmt_execute()1028   inline bool is_stmt_execute() const
1029   { return state == STMT_PREPARED || state == STMT_EXECUTED; }
is_conventional()1030   inline bool is_conventional() const
1031   { return state == STMT_CONVENTIONAL_EXECUTION; }
1032 
alloc(size_t size)1033   inline void* alloc(size_t size) { return alloc_root(mem_root,size); }
calloc(size_t size)1034   inline void* calloc(size_t size)
1035   {
1036     void *ptr;
1037     if (likely((ptr=alloc_root(mem_root,size))))
1038       bzero(ptr, size);
1039     return ptr;
1040   }
strdup(const char * str)1041   inline char *strdup(const char *str)
1042   { return strdup_root(mem_root,str); }
strmake(const char * str,size_t size)1043   inline char *strmake(const char *str, size_t size)
1044   { return strmake_root(mem_root,str,size); }
memdup(const void * str,size_t size)1045   inline void *memdup(const void *str, size_t size)
1046   { return memdup_root(mem_root,str,size); }
memdup_w_gap(const void * str,size_t size,size_t gap)1047   inline void *memdup_w_gap(const void *str, size_t size, size_t gap)
1048   {
1049     void *ptr;
1050     if (likely((ptr= alloc_root(mem_root,size+gap))))
1051       memcpy(ptr,str,size);
1052     return ptr;
1053   }
1054 
1055   void set_query_arena(Query_arena *set);
1056 
1057   void free_items();
1058   /* Close the active state associated with execution of this statement */
1059   virtual void cleanup_stmt();
1060 };
1061 
1062 
1063 class Query_arena_memroot: public Query_arena, public Sql_alloc
1064 {
1065 public:
Query_arena_memroot(MEM_ROOT * mem_root_arg,enum enum_state state_arg)1066   Query_arena_memroot(MEM_ROOT *mem_root_arg, enum enum_state state_arg) :
1067     Query_arena(mem_root_arg, state_arg)
1068   {}
Query_arena_memroot()1069   Query_arena_memroot() : Query_arena()
1070   {}
1071 
~Query_arena_memroot()1072   virtual ~Query_arena_memroot() {}
1073 };
1074 
1075 
1076 class Query_arena_stmt
1077 {
1078   THD *thd;
1079   Query_arena backup;
1080   Query_arena *arena;
1081 
1082 public:
1083   Query_arena_stmt(THD *_thd);
1084   ~Query_arena_stmt();
arena_replaced()1085   bool arena_replaced()
1086   {
1087     return arena != NULL;
1088   }
1089 };
1090 
1091 
1092 class Server_side_cursor;
1093 
1094 /**
1095   @class Statement
1096   @brief State of a single command executed against this connection.
1097 
1098   One connection can contain a lot of simultaneously running statements,
1099   some of which could be:
1100    - prepared, that is, contain placeholders,
1101    - opened as cursors. We maintain 1 to 1 relationship between
1102      statement and cursor - if user wants to create another cursor for his
1103      query, we create another statement for it.
1104   To perform some action with statement we reset THD part to the state  of
1105   that statement, do the action, and then save back modified state from THD
1106   to the statement. It will be changed in near future, and Statement will
1107   be used explicitly.
1108 */
1109 
1110 class Statement: public ilink, public Query_arena
1111 {
1112   Statement(const Statement &rhs);              /* not implemented: */
1113   Statement &operator=(const Statement &rhs);   /* non-copyable */
1114 public:
1115   /*
1116     Uniquely identifies each statement object in thread scope; change during
1117     statement lifetime. FIXME: must be const
1118   */
1119    ulong id;
1120 
1121   enum enum_column_usage column_usage;
1122 
1123   LEX_CSTRING name; /* name for named prepared statements */
1124   LEX *lex;                                     // parse tree descriptor
1125   /*
1126     Points to the query associated with this statement. It's const, but
1127     we need to declare it char * because all table handlers are written
1128     in C and need to point to it.
1129 
1130     Note that if we set query = NULL, we must at the same time set
1131     query_length = 0, and protect the whole operation with
1132     LOCK_thd_data mutex. To avoid crashes in races, if we do not
1133     know that thd->query cannot change at the moment, we should print
1134     thd->query like this:
1135       (1) reserve the LOCK_thd_data mutex;
1136       (2) print or copy the value of query and query_length
1137       (3) release LOCK_thd_data mutex.
1138     This printing is needed at least in SHOW PROCESSLIST and SHOW
1139     ENGINE INNODB STATUS.
1140   */
1141   CSET_STRING query_string;
1142   /*
1143     If opt_query_cache_strip_comments is set, this contains query without
1144     comments. If not set, it contains pointer to query_string.
1145   */
1146   String base_query;
1147 
1148 
query()1149   inline char *query() const { return query_string.str(); }
query_length()1150   inline uint32 query_length() const
1151   {
1152     return static_cast<uint32>(query_string.length());
1153   }
query_end()1154   inline char *query_end() const
1155   {
1156     return query_string.str() + query_string.length();
1157   }
query_charset()1158   CHARSET_INFO *query_charset() const { return query_string.charset(); }
set_query_inner(const CSET_STRING & string_arg)1159   void set_query_inner(const CSET_STRING &string_arg)
1160   {
1161     query_string= string_arg;
1162   }
set_query_inner(char * query_arg,uint32 query_length_arg,CHARSET_INFO * cs_arg)1163   void set_query_inner(char *query_arg, uint32 query_length_arg,
1164                        CHARSET_INFO *cs_arg)
1165   {
1166     set_query_inner(CSET_STRING(query_arg, query_length_arg, cs_arg));
1167   }
reset_query_inner()1168   void reset_query_inner()
1169   {
1170     set_query_inner(CSET_STRING());
1171   }
1172   /**
1173     Name of the current (default) database.
1174 
1175     If there is the current (default) database, "db.str" contains its name. If
1176     there is no current (default) database, "db.str" is NULL and "db.length" is
1177     0. In other words, db must either be NULL, or contain a
1178     valid database name.
1179   */
1180 
1181   LEX_CSTRING db;
1182 
1183   /* This is set to 1 of last call to send_result_to_client() was ok */
1184   my_bool query_cache_is_applicable;
1185 
1186   /* This constructor is called for backup statements */
Statement()1187   Statement() {}
1188 
1189   Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg,
1190             enum enum_state state_arg, ulong id_arg);
1191   virtual ~Statement();
1192 
1193   /* Assign execution context (note: not all members) of given stmt to self */
1194   virtual void set_statement(Statement *stmt);
1195   void set_n_backup_statement(Statement *stmt, Statement *backup);
1196   void restore_backup_statement(Statement *stmt, Statement *backup);
1197   /* return class type */
1198   virtual Type type() const;
1199 };
1200 
1201 
1202 /**
1203   Container for all statements created/used in a connection.
1204   Statements in Statement_map have unique Statement::id (guaranteed by id
1205   assignment in Statement::Statement)
1206   Non-empty statement names are unique too: attempt to insert a new statement
1207   with duplicate name causes older statement to be deleted
1208 
1209   Statements are auto-deleted when they are removed from the map and when the
1210   map is deleted.
1211 */
1212 
1213 class Statement_map
1214 {
1215 public:
1216   Statement_map();
1217 
1218   int insert(THD *thd, Statement *statement);
1219 
find_by_name(LEX_CSTRING * name)1220   Statement *find_by_name(LEX_CSTRING *name)
1221   {
1222     Statement *stmt;
1223     stmt= (Statement*)my_hash_search(&names_hash, (uchar*)name->str,
1224                                      name->length);
1225     return stmt;
1226   }
1227 
find(ulong id)1228   Statement *find(ulong id)
1229   {
1230     if (last_found_statement == 0 || id != last_found_statement->id)
1231     {
1232       Statement *stmt;
1233       stmt= (Statement *) my_hash_search(&st_hash, (uchar *) &id, sizeof(id));
1234       if (stmt && stmt->name.str)
1235         return NULL;
1236       last_found_statement= stmt;
1237     }
1238     return last_found_statement;
1239   }
1240   /*
1241     Close all cursors of this connection that use tables of a storage
1242     engine that has transaction-specific state and therefore can not
1243     survive COMMIT or ROLLBACK. Currently all but MyISAM cursors are closed.
1244   */
1245   void close_transient_cursors();
1246   void erase(Statement *statement);
1247   /* Erase all statements (calls Statement destructor) */
1248   void reset();
1249   ~Statement_map();
1250 private:
1251   HASH st_hash;
1252   HASH names_hash;
1253   I_List<Statement> transient_cursor_list;
1254   Statement *last_found_statement;
1255 };
1256 
1257 struct st_savepoint {
1258   struct st_savepoint *prev;
1259   char                *name;
1260   uint                 length;
1261   Ha_trx_info         *ha_list;
1262   /** State of metadata locks before this savepoint was set. */
1263   MDL_savepoint        mdl_savepoint;
1264 };
1265 
1266 enum xa_states {XA_NOTR=0, XA_ACTIVE, XA_IDLE, XA_PREPARED, XA_ROLLBACK_ONLY};
1267 extern const char *xa_state_names[];
1268 class XID_cache_element;
1269 
1270 typedef struct st_xid_state {
1271   /* For now, this is only used to catch duplicated external xids */
1272   XID  xid;                           // transaction identifier
1273   enum xa_states xa_state;            // used by external XA only
1274   /* Error reported by the Resource Manager (RM) to the Transaction Manager. */
1275   uint rm_error;
1276   XID_cache_element *xid_cache_element;
1277 
1278   /**
1279     Check that XA transaction has an uncommitted work. Report an error
1280     to the user in case when there is an uncommitted work for XA transaction.
1281 
1282     @return  result of check
1283       @retval  false  XA transaction is NOT in state IDLE, PREPARED
1284                       or ROLLBACK_ONLY.
1285       @retval  true   XA transaction is in state IDLE or PREPARED
1286                       or ROLLBACK_ONLY.
1287   */
1288 
check_has_uncommitted_xast_xid_state1289   bool check_has_uncommitted_xa() const
1290   {
1291     if (xa_state == XA_IDLE ||
1292         xa_state == XA_PREPARED ||
1293         xa_state == XA_ROLLBACK_ONLY)
1294     {
1295       my_error(ER_XAER_RMFAIL, MYF(0), xa_state_names[xa_state]);
1296       return true;
1297     }
1298     return false;
1299   }
1300 } XID_STATE;
1301 
1302 void xid_cache_init(void);
1303 void xid_cache_free(void);
1304 XID_STATE *xid_cache_search(THD *thd, XID *xid);
1305 bool xid_cache_insert(XID *xid, enum xa_states xa_state);
1306 bool xid_cache_insert(THD *thd, XID_STATE *xid_state);
1307 void xid_cache_delete(THD *thd, XID_STATE *xid_state);
1308 int xid_cache_iterate(THD *thd, my_hash_walk_action action, void *argument);
1309 
1310 /**
1311   @class Security_context
1312   @brief A set of THD members describing the current authenticated user.
1313 */
1314 
1315 class Security_context {
1316 public:
Security_context()1317   Security_context() {}                       /* Remove gcc warning */
1318   /*
1319     host - host of the client
1320     user - user of the client, set to NULL until the user has been read from
1321     the connection
1322     priv_user - The user privilege we are using. May be "" for anonymous user.
1323     ip - client IP
1324   */
1325   const char *host;
1326   const char *user, *ip;
1327   char   priv_user[USERNAME_LENGTH];
1328   char   proxy_user[USERNAME_LENGTH + MAX_HOSTNAME + 5];
1329   /* The host privilege we are using */
1330   char   priv_host[MAX_HOSTNAME];
1331   /* The role privilege we are using */
1332   char   priv_role[USERNAME_LENGTH];
1333   /* The external user (if available) */
1334   char   *external_user;
1335   /* points to host if host is available, otherwise points to ip */
1336   const char *host_or_ip;
1337   ulong master_access;                 /* Global privileges from mysql.user */
1338   ulong db_access;                     /* Privileges for current db */
1339 
1340   void init();
1341   void destroy();
1342   void skip_grants();
priv_host_name()1343   inline char *priv_host_name()
1344   {
1345     return (*priv_host ? priv_host : (char *)"%");
1346   }
1347 
1348   bool set_user(char *user_arg);
1349 
1350 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1351   bool
1352   change_security_context(THD *thd,
1353                           LEX_CSTRING *definer_user,
1354                           LEX_CSTRING *definer_host,
1355                           LEX_CSTRING *db,
1356                           Security_context **backup);
1357 
1358   void
1359   restore_security_context(THD *thd, Security_context *backup);
1360 #endif
1361   bool user_matches(Security_context *);
1362 };
1363 
1364 
1365 /**
1366   A registry for item tree transformations performed during
1367   query optimization. We register only those changes which require
1368   a rollback to re-execute a prepared statement or stored procedure
1369   yet another time.
1370 */
1371 
1372 struct Item_change_record;
1373 class Item_change_list
1374 {
1375   I_List<Item_change_record> change_list;
1376 public:
1377   void nocheck_register_item_tree_change(Item **place, Item *old_value,
1378                                          MEM_ROOT *runtime_memroot);
1379   void check_and_register_item_tree_change(Item **place, Item **new_value,
1380                                            MEM_ROOT *runtime_memroot);
1381   void rollback_item_tree_changes();
move_elements_to(Item_change_list * to)1382   void move_elements_to(Item_change_list *to)
1383   {
1384     change_list.move_elements_to(&to->change_list);
1385   }
is_empty()1386   bool is_empty() { return change_list.is_empty(); }
1387 };
1388 
1389 
1390 class Item_change_list_savepoint: public Item_change_list
1391 {
1392 public:
Item_change_list_savepoint(Item_change_list * list)1393   Item_change_list_savepoint(Item_change_list *list)
1394   {
1395     list->move_elements_to(this);
1396   }
rollback(Item_change_list * list)1397   void rollback(Item_change_list *list)
1398   {
1399     list->rollback_item_tree_changes();
1400     move_elements_to(list);
1401   }
~Item_change_list_savepoint()1402   ~Item_change_list_savepoint()
1403   {
1404     DBUG_ASSERT(is_empty());
1405   }
1406 };
1407 
1408 
1409 /**
1410   Type of locked tables mode.
1411   See comment for THD::locked_tables_mode for complete description.
1412 */
1413 
1414 enum enum_locked_tables_mode
1415 {
1416   LTM_NONE= 0,
1417   LTM_LOCK_TABLES,
1418   LTM_PRELOCKED,
1419   LTM_PRELOCKED_UNDER_LOCK_TABLES,
1420   LTM_always_last
1421 };
1422 
1423 /**
1424   The following structure is an extension to TABLE_SHARE and is
1425   exclusively for temporary tables.
1426 
1427   @note:
1428   Although, TDC_element has data members (like next, prev &
1429   all_tables) to store the list of TABLE_SHARE & TABLE objects
1430   related to a particular TABLE_SHARE, they cannot be moved to
1431   TABLE_SHARE in order to be reused for temporary tables. This
1432   is because, as concurrent threads iterating through hash of
1433   TDC_element's may need access to all_tables, but if all_tables
1434   is made part of TABLE_SHARE, then TDC_element->share->all_tables
1435   is not always guaranteed to be valid, as TDC_element can live
1436   longer than TABLE_SHARE.
1437 */
1438 struct TMP_TABLE_SHARE : public TABLE_SHARE
1439 {
1440 private:
1441   /*
1442    Link to all temporary table shares. Declared as private to
1443    avoid direct manipulation with those objects. One should
1444    use methods of I_P_List template instead.
1445   */
1446   TMP_TABLE_SHARE *tmp_next;
1447   TMP_TABLE_SHARE **tmp_prev;
1448 
1449   friend struct All_tmp_table_shares;
1450 
1451 public:
1452   /*
1453     Doubly-linked (back-linked) lists of used and unused TABLE objects
1454     for this share.
1455   */
1456   All_share_tables_list all_tmp_tables;
1457 };
1458 
1459 /**
1460   Helper class which specifies which members of TMP_TABLE_SHARE are
1461   used for participation in the list of temporary tables.
1462 */
1463 
1464 struct All_tmp_table_shares
1465 {
next_ptrAll_tmp_table_shares1466   static inline TMP_TABLE_SHARE **next_ptr(TMP_TABLE_SHARE *l)
1467   {
1468     return &l->tmp_next;
1469   }
prev_ptrAll_tmp_table_shares1470   static inline TMP_TABLE_SHARE ***prev_ptr(TMP_TABLE_SHARE *l)
1471   {
1472     return &l->tmp_prev;
1473   }
1474 };
1475 
1476 /* Also used in rpl_rli.h. */
1477 typedef I_P_List <TMP_TABLE_SHARE, All_tmp_table_shares> All_tmp_tables_list;
1478 
1479 /**
1480   Class that holds information about tables which were opened and locked
1481   by the thread. It is also used to save/restore this information in
1482   push_open_tables_state()/pop_open_tables_state().
1483 */
1484 
1485 class Open_tables_state
1486 {
1487 public:
1488   /**
1489     As part of class THD, this member is set during execution
1490     of a prepared statement. When it is set, it is used
1491     by the locking subsystem to report a change in table metadata.
1492 
1493     When Open_tables_state part of THD is reset to open
1494     a system or INFORMATION_SCHEMA table, the member is cleared
1495     to avoid spurious ER_NEED_REPREPARE errors -- system and
1496     INFORMATION_SCHEMA tables are not subject to metadata version
1497     tracking.
1498     @sa check_and_update_table_version()
1499   */
1500   Reprepare_observer *m_reprepare_observer;
1501 
1502   /**
1503     List of regular tables in use by this thread. Contains temporary and
1504     base tables that were opened with @see open_tables().
1505   */
1506   TABLE *open_tables;
1507 
1508   /**
1509     A list of temporary tables used by this thread. This includes
1510     user-level temporary tables, created with CREATE TEMPORARY TABLE,
1511     and internal temporary tables, created, e.g., to resolve a SELECT,
1512     or for an intermediate table used in ALTER.
1513   */
1514   All_tmp_tables_list *temporary_tables;
1515 
1516   /*
1517     Derived tables.
1518   */
1519   TABLE *derived_tables;
1520 
1521   /*
1522     Temporary tables created for recursive table references.
1523   */
1524   TABLE *rec_tables;
1525 
1526   /*
1527     During a MySQL session, one can lock tables in two modes: automatic
1528     or manual. In automatic mode all necessary tables are locked just before
1529     statement execution, and all acquired locks are stored in 'lock'
1530     member. Unlocking takes place automatically as well, when the
1531     statement ends.
1532     Manual mode comes into play when a user issues a 'LOCK TABLES'
1533     statement. In this mode the user can only use the locked tables.
1534     Trying to use any other tables will give an error.
1535     The locked tables are also stored in this member, however,
1536     thd->locked_tables_mode is turned on.  Manual locking is described in
1537     the 'LOCK_TABLES' chapter of the MySQL manual.
1538     See also lock_tables() for details.
1539   */
1540   MYSQL_LOCK *lock;
1541 
1542   /*
1543     CREATE-SELECT keeps an extra lock for the table being
1544     created. This field is used to keep the extra lock available for
1545     lower level routines, which would otherwise miss that lock.
1546    */
1547   MYSQL_LOCK *extra_lock;
1548 
1549   /*
1550     Enum enum_locked_tables_mode and locked_tables_mode member are
1551     used to indicate whether the so-called "locked tables mode" is on,
1552     and what kind of mode is active.
1553 
1554     Locked tables mode is used when it's necessary to open and
1555     lock many tables at once, for usage across multiple
1556     (sub-)statements.
1557     This may be necessary either for queries that use stored functions
1558     and triggers, in which case the statements inside functions and
1559     triggers may be executed many times, or for implementation of
1560     LOCK TABLES, in which case the opened tables are reused by all
1561     subsequent statements until a call to UNLOCK TABLES.
1562 
1563     The kind of locked tables mode employed for stored functions and
1564     triggers is also called "prelocked mode".
1565     In this mode, first open_tables() call to open the tables used
1566     in a statement analyses all functions used by the statement
1567     and adds all indirectly used tables to the list of tables to
1568     open and lock.
1569     It also marks the parse tree of the statement as requiring
1570     prelocking. After that, lock_tables() locks the entire list
1571     of tables and changes THD::locked_tables_modeto LTM_PRELOCKED.
1572     All statements executed inside functions or triggers
1573     use the prelocked tables, instead of opening their own ones.
1574     Prelocked mode is turned off automatically once close_thread_tables()
1575     of the main statement is called.
1576   */
1577   enum enum_locked_tables_mode locked_tables_mode;
1578   uint current_tablenr;
1579 
1580   enum enum_flags {
1581     BACKUPS_AVAIL = (1U << 0)     /* There are backups available */
1582   };
1583 
1584   /*
1585     Flags with information about the open tables state.
1586   */
1587   uint state_flags;
1588   /**
1589      This constructor initializes Open_tables_state instance which can only
1590      be used as backup storage. To prepare Open_tables_state instance for
1591      operations which open/lock/close tables (e.g. open_table()) one has to
1592      call init_open_tables_state().
1593   */
Open_tables_state()1594   Open_tables_state() : state_flags(0U) { }
1595 
set_open_tables_state(Open_tables_state * state)1596   void set_open_tables_state(Open_tables_state *state)
1597   {
1598     *this= *state;
1599   }
1600 
reset_open_tables_state(THD * thd)1601   void reset_open_tables_state(THD *thd)
1602   {
1603     open_tables= 0;
1604     temporary_tables= 0;
1605     derived_tables= 0;
1606     rec_tables= 0;
1607     extra_lock= 0;
1608     lock= 0;
1609     locked_tables_mode= LTM_NONE;
1610     state_flags= 0U;
1611     m_reprepare_observer= NULL;
1612   }
1613 };
1614 
1615 
1616 /**
1617   Storage for backup of Open_tables_state. Must
1618   be used only to open system tables (TABLE_CATEGORY_SYSTEM
1619   and TABLE_CATEGORY_LOG).
1620 */
1621 
1622 class Open_tables_backup: public Open_tables_state
1623 {
1624 public:
1625   /**
1626     When we backup the open tables state to open a system
1627     table or tables, we want to save state of metadata
1628     locks which were acquired before the backup. It is used
1629     to release metadata locks on system tables after they are
1630     no longer used.
1631   */
1632   MDL_savepoint mdl_system_tables_svp;
1633 };
1634 
1635 /**
1636   @class Sub_statement_state
1637   @brief Used to save context when executing a function or trigger
1638 
1639   operations on stat tables aren't technically a sub-statement, but they are
1640   similar in a sense that they cannot change the transaction status.
1641 */
1642 
1643 /* Defines used for Sub_statement_state::in_sub_stmt */
1644 
1645 #define SUB_STMT_TRIGGER 1
1646 #define SUB_STMT_FUNCTION 2
1647 #define SUB_STMT_STAT_TABLES 4
1648 
1649 
1650 class Sub_statement_state
1651 {
1652 public:
1653   Discrete_interval auto_inc_interval_for_cur_row;
1654   Discrete_intervals_list auto_inc_intervals_forced;
1655   SAVEPOINT *savepoints;
1656   ulonglong option_bits;
1657   ulonglong first_successful_insert_id_in_prev_stmt;
1658   ulonglong first_successful_insert_id_in_cur_stmt, insert_id_for_cur_row;
1659   ulonglong limit_found_rows;
1660   ulonglong tmp_tables_size;
1661   ulonglong client_capabilities;
1662   ulonglong cuted_fields, sent_row_count, examined_row_count;
1663   ulonglong affected_rows;
1664   ulonglong bytes_sent_old;
1665   ulong     tmp_tables_used;
1666   ulong     tmp_tables_disk_used;
1667   ulong     query_plan_fsort_passes;
1668   ulong query_plan_flags;
1669   uint in_sub_stmt;    /* 0,  SUB_STMT_TRIGGER or SUB_STMT_FUNCTION */
1670   bool enable_slow_log;
1671   bool last_insert_id_used;
1672   enum enum_check_fields count_cuted_fields;
1673 };
1674 
1675 
1676 /* Flags for the THD::system_thread variable */
1677 enum enum_thread_type
1678 {
1679   NON_SYSTEM_THREAD= 0,
1680   SYSTEM_THREAD_DELAYED_INSERT= 1,
1681   SYSTEM_THREAD_SLAVE_IO= 2,
1682   SYSTEM_THREAD_SLAVE_SQL= 4,
1683   SYSTEM_THREAD_EVENT_SCHEDULER= 8,
1684   SYSTEM_THREAD_EVENT_WORKER= 16,
1685   SYSTEM_THREAD_BINLOG_BACKGROUND= 32,
1686   SYSTEM_THREAD_SLAVE_BACKGROUND= 64,
1687   SYSTEM_THREAD_GENERIC= 128,
1688   SYSTEM_THREAD_SEMISYNC_MASTER_BACKGROUND= 256
1689 };
1690 
1691 inline char const *
show_system_thread(enum_thread_type thread)1692 show_system_thread(enum_thread_type thread)
1693 {
1694 #define RETURN_NAME_AS_STRING(NAME) case (NAME): return #NAME
1695   switch (thread) {
1696     static char buf[64];
1697     RETURN_NAME_AS_STRING(NON_SYSTEM_THREAD);
1698     RETURN_NAME_AS_STRING(SYSTEM_THREAD_DELAYED_INSERT);
1699     RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_IO);
1700     RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_SQL);
1701     RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_SCHEDULER);
1702     RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_WORKER);
1703     RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_BACKGROUND);
1704     RETURN_NAME_AS_STRING(SYSTEM_THREAD_SEMISYNC_MASTER_BACKGROUND);
1705   default:
1706     sprintf(buf, "<UNKNOWN SYSTEM THREAD: %d>", thread);
1707     return buf;
1708   }
1709 #undef RETURN_NAME_AS_STRING
1710 }
1711 
1712 /**
1713   This class represents the interface for internal error handlers.
1714   Internal error handlers are exception handlers used by the server
1715   implementation.
1716 */
1717 
1718 class Internal_error_handler
1719 {
1720 protected:
Internal_error_handler()1721   Internal_error_handler() :
1722     m_prev_internal_handler(NULL)
1723   {}
1724 
~Internal_error_handler()1725   virtual ~Internal_error_handler() {}
1726 
1727 public:
1728   /**
1729     Handle a sql condition.
1730     This method can be implemented by a subclass to achieve any of the
1731     following:
1732     - mask a warning/error internally, prevent exposing it to the user,
1733     - mask a warning/error and throw another one instead.
1734     When this method returns true, the sql condition is considered
1735     'handled', and will not be propagated to upper layers.
1736     It is the responsability of the code installing an internal handler
1737     to then check for trapped conditions, and implement logic to recover
1738     from the anticipated conditions trapped during runtime.
1739 
1740     This mechanism is similar to C++ try/throw/catch:
1741     - 'try' correspond to <code>THD::push_internal_handler()</code>,
1742     - 'throw' correspond to <code>my_error()</code>,
1743     which invokes <code>my_message_sql()</code>,
1744     - 'catch' correspond to checking how/if an internal handler was invoked,
1745     before removing it from the exception stack with
1746     <code>THD::pop_internal_handler()</code>.
1747 
1748     @param thd the calling thread
1749     @param cond the condition raised.
1750     @return true if the condition is handled
1751   */
1752   virtual bool handle_condition(THD *thd,
1753                                 uint sql_errno,
1754                                 const char* sqlstate,
1755                                 Sql_condition::enum_warning_level *level,
1756                                 const char* msg,
1757                                 Sql_condition ** cond_hdl) = 0;
1758 
1759 private:
1760   Internal_error_handler *m_prev_internal_handler;
1761   friend class THD;
1762 };
1763 
1764 
1765 /**
1766   Implements the trivial error handler which cancels all error states
1767   and prevents an SQLSTATE to be set.
1768 */
1769 
1770 class Dummy_error_handler : public Internal_error_handler
1771 {
1772 public:
handle_condition(THD * thd,uint sql_errno,const char * sqlstate,Sql_condition::enum_warning_level * level,const char * msg,Sql_condition ** cond_hdl)1773   bool handle_condition(THD *thd,
1774                         uint sql_errno,
1775                         const char* sqlstate,
1776                         Sql_condition::enum_warning_level *level,
1777                         const char* msg,
1778                         Sql_condition ** cond_hdl)
1779   {
1780     /* Ignore error */
1781     return TRUE;
1782   }
Dummy_error_handler()1783   Dummy_error_handler() {}                    /* Remove gcc warning */
1784 };
1785 
1786 
1787 /**
1788   Implements the trivial error handler which counts errors as they happen.
1789 */
1790 
1791 class Counting_error_handler : public Internal_error_handler
1792 {
1793 public:
1794   int errors;
handle_condition(THD * thd,uint sql_errno,const char * sqlstate,Sql_condition::enum_warning_level * level,const char * msg,Sql_condition ** cond_hdl)1795   bool handle_condition(THD *thd,
1796                         uint sql_errno,
1797                         const char* sqlstate,
1798                         Sql_condition::enum_warning_level *level,
1799                         const char* msg,
1800                         Sql_condition ** cond_hdl)
1801   {
1802     if (*level == Sql_condition::WARN_LEVEL_ERROR)
1803       errors++;
1804     return false;
1805   }
Counting_error_handler()1806   Counting_error_handler() : errors(0) {}
1807 };
1808 
1809 
1810 /**
1811   This class is an internal error handler implementation for
1812   DROP TABLE statements. The thing is that there may be warnings during
1813   execution of these statements, which should not be exposed to the user.
1814   This class is intended to silence such warnings.
1815 */
1816 
1817 class Drop_table_error_handler : public Internal_error_handler
1818 {
1819 public:
Drop_table_error_handler()1820   Drop_table_error_handler() {}
1821 
1822 public:
1823   bool handle_condition(THD *thd,
1824                         uint sql_errno,
1825                         const char* sqlstate,
1826                         Sql_condition::enum_warning_level *level,
1827                         const char* msg,
1828                         Sql_condition ** cond_hdl);
1829 
1830 private:
1831 };
1832 
1833 
1834 /**
1835   Internal error handler to process an error from MDL_context::upgrade_lock()
1836   and mysql_lock_tables(). Used by implementations of HANDLER READ and
1837   LOCK TABLES LOCAL.
1838 */
1839 
1840 class MDL_deadlock_and_lock_abort_error_handler: public Internal_error_handler
1841 {
1842 public:
1843   virtual
1844   bool handle_condition(THD *thd,
1845                         uint sql_errno,
1846                         const char *sqlstate,
1847                         Sql_condition::enum_warning_level *level,
1848                         const char* msg,
1849                         Sql_condition **cond_hdl);
1850 
need_reopen()1851   bool need_reopen() const { return m_need_reopen; };
init()1852   void init() { m_need_reopen= FALSE; };
1853 private:
1854   bool m_need_reopen;
1855 };
1856 
1857 
1858 /**
1859   Tables that were locked with LOCK TABLES statement.
1860 
1861   Encapsulates a list of TABLE_LIST instances for tables
1862   locked by LOCK TABLES statement, memory root for metadata locks,
1863   and, generally, the context of LOCK TABLES statement.
1864 
1865   In LOCK TABLES mode, the locked tables are kept open between
1866   statements.
1867   Therefore, we can't allocate metadata locks on execution memory
1868   root -- as well as tables, the locks need to stay around till
1869   UNLOCK TABLES is called.
1870   The locks are allocated in the memory root encapsulated in this
1871   class.
1872 
1873   Some SQL commands, like FLUSH TABLE or ALTER TABLE, demand that
1874   the tables they operate on are closed, at least temporarily.
1875   This class encapsulates a list of TABLE_LIST instances, one
1876   for each base table from LOCK TABLES list,
1877   which helps conveniently close the TABLEs when it's necessary
1878   and later reopen them.
1879 
1880   Implemented in sql_base.cc
1881 */
1882 
1883 class Locked_tables_list
1884 {
1885 public:
1886   MEM_ROOT m_locked_tables_root;
1887 private:
1888   TABLE_LIST *m_locked_tables;
1889   TABLE_LIST **m_locked_tables_last;
1890   /** An auxiliary array used only in reopen_tables(). */
1891   TABLE_LIST **m_reopen_array;
1892   /**
1893     Count the number of tables in m_locked_tables list. We can't
1894     rely on thd->lock->table_count because it excludes
1895     non-transactional temporary tables. We need to know
1896     an exact number of TABLE objects.
1897   */
1898   uint m_locked_tables_count;
1899 public:
1900   bool some_table_marked_for_reopen;
1901 
Locked_tables_list()1902   Locked_tables_list()
1903     :m_locked_tables(NULL),
1904     m_locked_tables_last(&m_locked_tables),
1905     m_reopen_array(NULL),
1906     m_locked_tables_count(0),
1907     some_table_marked_for_reopen(0)
1908   {
1909     init_sql_alloc(&m_locked_tables_root, "Locked_tables_list",
1910                    MEM_ROOT_BLOCK_SIZE, 0,
1911                    MYF(MY_THREAD_SPECIFIC));
1912   }
1913   void unlock_locked_tables(THD *thd);
1914   void unlock_locked_table(THD *thd, MDL_ticket *mdl_ticket);
~Locked_tables_list()1915   ~Locked_tables_list()
1916   {
1917     reset();
1918   }
1919   void reset();
1920   bool init_locked_tables(THD *thd);
locked_tables()1921   TABLE_LIST *locked_tables() { return m_locked_tables; }
1922   void unlink_from_list(THD *thd, TABLE_LIST *table_list,
1923                         bool remove_from_locked_tables);
1924   void unlink_all_closed_tables(THD *thd,
1925                                 MYSQL_LOCK *lock,
1926                                 size_t reopen_count);
1927   bool reopen_tables(THD *thd, bool need_reopen);
1928   bool restore_lock(THD *thd, TABLE_LIST *dst_table_list, TABLE *table,
1929                     MYSQL_LOCK *lock);
1930   void add_back_last_deleted_lock(TABLE_LIST *dst_table_list);
1931   void mark_table_for_reopen(THD *thd, TABLE *table);
1932 };
1933 
1934 
1935 /**
1936   Storage engine specific thread local data.
1937 */
1938 
1939 struct Ha_data
1940 {
1941   /**
1942     Storage engine specific thread local data.
1943     Lifetime: one user connection.
1944   */
1945   void *ha_ptr;
1946   /**
1947     0: Life time: one statement within a transaction. If @@autocommit is
1948     on, also represents the entire transaction.
1949     @sa trans_register_ha()
1950 
1951     1: Life time: one transaction within a connection.
1952     If the storage engine does not participate in a transaction,
1953     this should not be used.
1954     @sa trans_register_ha()
1955   */
1956   Ha_trx_info ha_info[2];
1957   /**
1958     NULL: engine is not bound to this thread
1959     non-NULL: engine is bound to this thread, engine shutdown forbidden
1960   */
1961   plugin_ref lock;
Ha_dataHa_data1962   Ha_data() :ha_ptr(NULL) {}
1963 };
1964 
1965 /**
1966   An instance of the global read lock in a connection.
1967   Implemented in lock.cc.
1968 */
1969 
1970 class Global_read_lock
1971 {
1972 public:
1973   enum enum_grl_state
1974   {
1975     GRL_NONE,
1976     GRL_ACQUIRED,
1977     GRL_ACQUIRED_AND_BLOCKS_COMMIT
1978   };
1979 
Global_read_lock()1980   Global_read_lock()
1981     : m_state(GRL_NONE),
1982       m_mdl_global_shared_lock(NULL),
1983       m_mdl_blocks_commits_lock(NULL)
1984   {}
1985 
1986   bool lock_global_read_lock(THD *thd);
1987   void unlock_global_read_lock(THD *thd);
1988   /**
1989     Check if this connection can acquire protection against GRL and
1990     emit error if otherwise.
1991   */
can_acquire_protection()1992   bool can_acquire_protection() const
1993   {
1994     if (m_state)
1995     {
1996       my_error(ER_CANT_UPDATE_WITH_READLOCK, MYF(0));
1997       return TRUE;
1998     }
1999     return FALSE;
2000   }
2001   bool make_global_read_lock_block_commit(THD *thd);
is_acquired()2002   bool is_acquired() const { return m_state != GRL_NONE; }
2003   void set_explicit_lock_duration(THD *thd);
2004 private:
2005   enum_grl_state m_state;
2006   /**
2007     In order to acquire the global read lock, the connection must
2008     acquire shared metadata lock in GLOBAL namespace, to prohibit
2009     all DDL.
2010   */
2011   MDL_ticket *m_mdl_global_shared_lock;
2012   /**
2013     Also in order to acquire the global read lock, the connection
2014     must acquire a shared metadata lock in COMMIT namespace, to
2015     prohibit commits.
2016   */
2017   MDL_ticket *m_mdl_blocks_commits_lock;
2018 };
2019 
2020 
2021 /*
2022   Class to facilitate the commit of one transactions waiting for the commit of
2023   another transaction to complete first.
2024 
2025   This is used during (parallel) replication, to allow different transactions
2026   to be applied in parallel, but still commit in order.
2027 
2028   The transaction that wants to wait for a prior commit must first register
2029   to wait with register_wait_for_prior_commit(waitee). Such registration
2030   must be done holding the waitee->LOCK_wait_commit, to prevent the other
2031   THD from disappearing during the registration.
2032 
2033   Then during commit, if a THD is registered to wait, it will call
2034   wait_for_prior_commit() as part of ha_commit_trans(). If no wait is
2035   registered, or if the waitee for has already completed commit, then
2036   wait_for_prior_commit() returns immediately.
2037 
2038   And when a THD that may be waited for has completed commit (more precisely
2039   commit_ordered()), then it must call wakeup_subsequent_commits() to wake
2040   up any waiters. Note that this must be done at a point that is guaranteed
2041   to be later than any waiters registering themselves. It is safe to call
2042   wakeup_subsequent_commits() multiple times, as waiters are removed from
2043   registration as part of the wakeup.
2044 
2045   The reason for separate register and wait calls is that this allows to
2046   register the wait early, at a point where the waited-for THD is known to
2047   exist. And then the actual wait can be done much later, where the
2048   waited-for THD may have been long gone. By registering early, the waitee
2049   can signal before disappearing.
2050 */
2051 struct wait_for_commit
2052 {
2053   /*
2054     The LOCK_wait_commit protects the fields subsequent_commits_list and
2055     wakeup_subsequent_commits_running (for a waitee), and the pointer
2056     waiterr and associated COND_wait_commit (for a waiter).
2057   */
2058   mysql_mutex_t LOCK_wait_commit;
2059   mysql_cond_t COND_wait_commit;
2060   /* List of threads that did register_wait_for_prior_commit() on us. */
2061   wait_for_commit *subsequent_commits_list;
2062   /* Link field for entries in subsequent_commits_list. */
2063   wait_for_commit *next_subsequent_commit;
2064   /*
2065     Our waitee, if we did register_wait_for_prior_commit(), and were not
2066     yet woken up. Else NULL.
2067 
2068     When this is cleared for wakeup, the COND_wait_commit condition is
2069     signalled.
2070   */
2071   wait_for_commit *waitee;
2072   /*
2073     Generic pointer for use by the transaction coordinator to optimise the
2074     waiting for improved group commit.
2075 
2076     Currently used by binlog TC to signal that a waiter is ready to commit, so
2077     that the waitee can grab it and group commit it directly. It is free to be
2078     used by another transaction coordinator for similar purposes.
2079   */
2080   void *opaque_pointer;
2081   /* The wakeup error code from the waitee. 0 means no error. */
2082   int wakeup_error;
2083   /*
2084     Flag set when wakeup_subsequent_commits_running() is active, see comments
2085     on that function for details.
2086   */
2087   bool wakeup_subsequent_commits_running;
2088   /*
2089     This flag can be set when a commit starts, but has not completed yet.
2090     It is used by binlog group commit to allow a waiting transaction T2 to
2091     join the group commit of an earlier transaction T1. When T1 has queued
2092     itself for group commit, it will set the commit_started flag. Then when
2093     T2 becomes ready to commit and needs to wait for T1 to commit first, T2
2094     can queue itself before waiting, and thereby participate in the same
2095     group commit as T1.
2096   */
2097   bool commit_started;
2098 
2099   void register_wait_for_prior_commit(wait_for_commit *waitee);
wait_for_prior_commitwait_for_commit2100   int wait_for_prior_commit(THD *thd)
2101   {
2102     /*
2103       Quick inline check, to avoid function call and locking in the common case
2104       where no wakeup is registered, or a registered wait was already signalled.
2105     */
2106     if (waitee)
2107       return wait_for_prior_commit2(thd);
2108     else
2109     {
2110       if (wakeup_error)
2111         my_error(ER_PRIOR_COMMIT_FAILED, MYF(0));
2112       return wakeup_error;
2113     }
2114   }
wakeup_subsequent_commitswait_for_commit2115   void wakeup_subsequent_commits(int wakeup_error_arg)
2116   {
2117     /*
2118       Do the check inline, so only the wakeup case takes the cost of a function
2119       call for every commmit.
2120 
2121       Note that the check is done without locking. It is the responsibility of
2122       the user of the wakeup facility to ensure that no waiters can register
2123       themselves after the last call to wakeup_subsequent_commits().
2124 
2125       This avoids having to take another lock for every commit, which would be
2126       pointless anyway - even if we check under lock, there is nothing to
2127       prevent a waiter from arriving just after releasing the lock.
2128     */
2129     if (subsequent_commits_list)
2130       wakeup_subsequent_commits2(wakeup_error_arg);
2131   }
unregister_wait_for_prior_commitwait_for_commit2132   void unregister_wait_for_prior_commit()
2133   {
2134     if (waitee)
2135       unregister_wait_for_prior_commit2();
2136     else
2137       wakeup_error= 0;
2138   }
2139   /*
2140     Remove a waiter from the list in the waitee. Used to unregister a wait.
2141     The caller must be holding the locks of both waiter and waitee.
2142   */
remove_from_listwait_for_commit2143   void remove_from_list(wait_for_commit **next_ptr_ptr)
2144   {
2145     wait_for_commit *cur;
2146 
2147     while ((cur= *next_ptr_ptr) != NULL)
2148     {
2149       if (cur == this)
2150       {
2151         *next_ptr_ptr= this->next_subsequent_commit;
2152         break;
2153       }
2154       next_ptr_ptr= &cur->next_subsequent_commit;
2155     }
2156     waitee= NULL;
2157   }
2158 
2159   void wakeup(int wakeup_error);
2160 
2161   int wait_for_prior_commit2(THD *thd);
2162   void wakeup_subsequent_commits2(int wakeup_error);
2163   void unregister_wait_for_prior_commit2();
2164 
2165   wait_for_commit();
2166   ~wait_for_commit();
2167   void reinit();
2168 };
2169 
2170 extern "C" void my_message_sql(uint error, const char *str, myf MyFlags);
2171 
2172 /**
2173   @class THD
2174   For each client connection we create a separate thread with THD serving as
2175   a thread/connection descriptor
2176 */
2177 
2178 class THD :public Statement,
2179            /*
2180              This is to track items changed during execution of a prepared
2181              statement/stored procedure. It's created by
2182              nocheck_register_item_tree_change() in memory root of THD,
2183              and freed in rollback_item_tree_changes().
2184              For conventional execution it's always empty.
2185            */
2186            public Item_change_list,
2187            public MDL_context_owner,
2188            public Open_tables_state
2189 {
2190 private:
is_stmt_prepare()2191   inline bool is_stmt_prepare() const
2192   { DBUG_ASSERT(0); return Statement::is_stmt_prepare(); }
2193 
is_stmt_prepare_or_first_sp_execute()2194   inline bool is_stmt_prepare_or_first_sp_execute() const
2195   { DBUG_ASSERT(0); return Statement::is_stmt_prepare_or_first_sp_execute(); }
2196 
is_stmt_prepare_or_first_stmt_execute()2197   inline bool is_stmt_prepare_or_first_stmt_execute() const
2198   { DBUG_ASSERT(0); return Statement::is_stmt_prepare_or_first_stmt_execute(); }
2199 
is_conventional()2200   inline bool is_conventional() const
2201   { DBUG_ASSERT(0); return Statement::is_conventional(); }
2202 
dec_thread_count(void)2203   void dec_thread_count(void)
2204   {
2205     DBUG_ASSERT(thread_count > 0);
2206     thread_safe_decrement32(&thread_count);
2207     signal_thd_deleted();
2208   }
2209 
2210 
inc_thread_count(void)2211   void inc_thread_count(void)
2212   {
2213     thread_safe_increment32(&thread_count);
2214   }
2215 
2216 public:
2217   MDL_context mdl_context;
2218 
2219   /* Used to execute base64 coded binlog events in MySQL server */
2220   Relay_log_info* rli_fake;
2221   rpl_group_info* rgi_fake;
2222   /* Slave applier execution context */
2223   rpl_group_info* rgi_slave;
2224 
2225   union {
2226     rpl_io_thread_info *rpl_io_info;
2227     rpl_sql_thread_info *rpl_sql_info;
2228   } system_thread_info;
2229 
2230   void reset_for_next_command(bool do_clear_errors= 1);
2231   /*
2232     Constant for THD::where initialization in the beginning of every query.
2233 
2234     It's needed because we do not save/restore THD::where normally during
2235     primary (non subselect) query execution.
2236   */
2237   static const char * const DEFAULT_WHERE;
2238 
2239 #ifdef EMBEDDED_LIBRARY
2240   struct st_mysql  *mysql;
2241   unsigned long	 client_stmt_id;
2242   unsigned long  client_param_count;
2243   struct st_mysql_bind *client_params;
2244   char *extra_data;
2245   ulong extra_length;
2246   struct st_mysql_data *cur_data;
2247   struct st_mysql_data *first_data;
2248   struct st_mysql_data **data_tail;
2249   void clear_data_list();
2250   struct st_mysql_data *alloc_new_dataset();
2251   /*
2252     In embedded server it points to the statement that is processed
2253     in the current query. We store some results directly in statement
2254     fields then.
2255   */
2256   struct st_mysql_stmt *current_stmt;
2257 #endif
2258 #ifdef HAVE_QUERY_CACHE
2259   Query_cache_tls query_cache_tls;
2260 #endif
2261   NET	  net;				// client connection descriptor
2262   /** Aditional network instrumentation for the server only. */
2263   NET_SERVER m_net_server_extension;
2264   scheduler_functions *scheduler;       // Scheduler for this connection
2265   Protocol *protocol;			// Current protocol
2266   Protocol_text   protocol_text;	// Normal protocol
2267   Protocol_binary protocol_binary;	// Binary protocol
2268   HASH    user_vars;			// hash for user variables
2269   String  packet;			// dynamic buffer for network I/O
2270   String  convert_buffer;               // buffer for charset conversions
2271   struct  my_rnd_struct rand;		// used for authentication
2272   struct  system_variables variables;	// Changeable local variables
2273   struct  system_status_var status_var; // Per thread statistic vars
2274   struct  system_status_var org_status_var; // For user statistics
2275   struct  system_status_var *initial_status_var; /* used by show status */
2276   THR_LOCK_INFO lock_info;              // Locking info of this thread
2277   /**
2278     Protects THD data accessed from other threads:
2279     - thd->query and thd->query_length (used by SHOW ENGINE
2280       INNODB STATUS and SHOW PROCESSLIST
2281     - thd->db (used in SHOW PROCESSLIST)
2282     Is locked when THD is deleted.
2283   */
2284   mysql_mutex_t LOCK_thd_data;
2285   /*
2286     Protects:
2287     - kill information
2288     - mysys_var (used by KILL statement and shutdown).
2289     - Also ensures that THD is not deleted while mutex is hold
2290   */
2291   mysql_mutex_t LOCK_thd_kill;
2292 
2293   /* all prepared statements and cursors of this connection */
2294   Statement_map stmt_map;
2295 
2296   /* Last created prepared statement */
2297   Statement *last_stmt;
set_last_stmt(Statement * stmt)2298   inline void set_last_stmt(Statement *stmt)
2299   { last_stmt= (is_error() ? NULL : stmt); }
clear_last_stmt()2300   inline void clear_last_stmt() { last_stmt= NULL; }
2301 
2302   /*
2303     A pointer to the stack frame of handle_one_connection(),
2304     which is called first in the thread for handling a client
2305   */
2306   char	  *thread_stack;
2307 
2308   /**
2309     Currently selected catalog.
2310   */
2311   char *catalog;
2312 
2313   /**
2314     @note
2315     Some members of THD (currently 'Statement::db',
2316     'catalog' and 'query')  are set and alloced by the slave SQL thread
2317     (for the THD of that thread); that thread is (and must remain, for now)
2318     the only responsible for freeing these 3 members. If you add members
2319     here, and you add code to set them in replication, don't forget to
2320     free_them_and_set_them_to_0 in replication properly. For details see
2321     the 'err:' label of the handle_slave_sql() in sql/slave.cc.
2322 
2323     @see handle_slave_sql
2324   */
2325 
2326   Security_context main_security_ctx;
2327   Security_context *security_ctx;
2328 
2329   /*
2330     Points to info-string that we show in SHOW PROCESSLIST
2331     You are supposed to update thd->proc_info only if you have coded
2332     a time-consuming piece that MySQL can get stuck in for a long time.
2333 
2334     Set it using the  thd_proc_info(THD *thread, const char *message)
2335     macro/function.
2336 
2337     This member is accessed and assigned without any synchronization.
2338     Therefore, it may point only to constant (statically
2339     allocated) strings, which memory won't go away over time.
2340   */
2341   const char *proc_info;
2342 
2343 private:
2344   unsigned int m_current_stage_key;
2345 
2346 public:
enter_stage(const PSI_stage_info * stage,const char * calling_func,const char * calling_file,const unsigned int calling_line)2347   void enter_stage(const PSI_stage_info *stage,
2348                    const char *calling_func,
2349                    const char *calling_file,
2350                    const unsigned int calling_line)
2351   {
2352     DBUG_PRINT("THD::enter_stage", ("%s at %s:%d", stage->m_name,
2353                                     calling_file, calling_line));
2354     DBUG_ASSERT(stage);
2355     m_current_stage_key= stage->m_key;
2356     proc_info= stage->m_name;
2357 #if defined(ENABLED_PROFILING)
2358     profiling.status_change(proc_info, calling_func, calling_file,
2359                             calling_line);
2360 #endif
2361 #ifdef HAVE_PSI_THREAD_INTERFACE
2362     MYSQL_SET_STAGE(m_current_stage_key, calling_file, calling_line);
2363 #endif
2364   }
2365 
backup_stage(PSI_stage_info * stage)2366   void backup_stage(PSI_stage_info *stage)
2367   {
2368     stage->m_key= m_current_stage_key;
2369     stage->m_name= proc_info;
2370   }
2371 
get_proc_info()2372   const char *get_proc_info() const
2373   { return proc_info; }
2374 
2375   /*
2376     Used in error messages to tell user in what part of MySQL we found an
2377     error. E. g. when where= "having clause", if fix_fields() fails, user
2378     will know that the error was in having clause.
2379   */
2380   const char *where;
2381 
2382   /* Needed by MariaDB semi sync replication */
2383   Trans_binlog_info *semisync_info;
2384   /* If this is a semisync slave connection. */
2385   bool semi_sync_slave;
2386   ulonglong client_capabilities;  /* What the client supports */
2387   ulong max_client_packet_length;
2388 
2389   HASH		handler_tables_hash;
2390   /*
2391     A thread can hold named user-level locks. This variable
2392     contains granted tickets if a lock is present. See item_func.cc and
2393     chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK.
2394   */
2395   HASH ull_hash;
2396   /* Hash of used seqeunces (for PREVIOUS value) */
2397   HASH sequences;
2398 #ifdef DBUG_ASSERT_EXISTS
2399   uint dbug_sentry; // watch out for memory corruption
2400 #endif
2401   struct st_my_thread_var *mysys_var;
2402 
2403   /* Original charset number from the first client packet, or COM_CHANGE_USER*/
2404   CHARSET_INFO *org_charset;
2405 private:
2406   /*
2407     Type of current query: COM_STMT_PREPARE, COM_QUERY, etc. Set from
2408     first byte of the packet in do_command()
2409   */
2410   enum enum_server_command m_command;
2411 
2412 public:
2413   uint32     file_id;			// for LOAD DATA INFILE
2414   /* remote (peer) port */
2415   uint16     peer_port;
2416   my_time_t  start_time;             // start_time and its sec_part
2417   ulong      start_time_sec_part;    // are almost always used separately
2418   my_hrtime_t user_time;
2419   // track down slow pthread_create
2420   ulonglong  prior_thr_create_utime, thr_create_utime;
2421   ulonglong  start_utime, utime_after_lock, utime_after_query;
2422 
2423   // Process indicator
2424   struct {
2425     /*
2426       true, if the currently running command can send progress report
2427       packets to a client. Set by mysql_execute_command() for safe commands
2428       See CF_REPORT_PROGRESS
2429     */
2430     bool       report_to_client;
2431     /*
2432       true, if we will send progress report packets to a client
2433       (client has requested them, see MARIADB_CLIENT_PROGRESS; report_to_client
2434       is true; not in sub-statement)
2435     */
2436     bool       report;
2437     uint       stage, max_stage;
2438     ulonglong  counter, max_counter;
2439     ulonglong  next_report_time;
2440     Query_arena *arena;
2441   } progress;
2442 
2443   thr_lock_type update_lock_default;
2444   Delayed_insert *di;
2445 
2446   /* <> 0 if we are inside of trigger or stored function. */
2447   uint in_sub_stmt;
2448   /* True when opt_userstat_running is set at start of query */
2449   bool userstat_running;
2450   /*
2451     True if we have to log all errors. Are set by some engines to temporary
2452     force errors to the error log.
2453   */
2454   bool log_all_errors;
2455 
2456   /* Do not set socket timeouts for wait_timeout (used with threadpool) */
2457   bool skip_wait_timeout;
2458 
2459   bool prepare_derived_at_open;
2460 
2461   /* Set to 1 if status of this THD is already in global status */
2462   bool status_in_global;
2463 
2464   /*
2465     To signal that the tmp table to be created is created for materialized
2466     derived table or a view.
2467   */
2468   bool create_tmp_table_for_derived;
2469 
2470   bool save_prep_leaf_list;
2471 
2472   /* container for handler's private per-connection data */
2473   Ha_data ha_data[MAX_HA];
2474 
2475   /**
2476     Bit field for the state of binlog warnings.
2477 
2478     The first Lex::BINLOG_STMT_UNSAFE_COUNT bits list all types of
2479     unsafeness that the current statement has.
2480 
2481     This must be a member of THD and not of LEX, because warnings are
2482     detected and issued in different places (@c
2483     decide_logging_format() and @c binlog_query(), respectively).
2484     Between these calls, the THD->lex object may change; e.g., if a
2485     stored routine is invoked.  Only THD persists between the calls.
2486   */
2487   uint32 binlog_unsafe_warning_flags;
2488 
2489 #ifndef MYSQL_CLIENT
2490   binlog_cache_mngr *  binlog_setup_trx_data();
2491 
2492   /*
2493     Public interface to write RBR events to the binlog
2494   */
2495   void binlog_start_trans_and_stmt();
2496   void binlog_set_stmt_begin();
2497   int binlog_write_table_map(TABLE *table, bool is_transactional,
2498                              my_bool *with_annotate= 0);
2499   int binlog_write_row(TABLE* table, bool is_transactional,
2500                        const uchar *buf);
2501   int binlog_delete_row(TABLE* table, bool is_transactional,
2502                         const uchar *buf);
2503   int binlog_update_row(TABLE* table, bool is_transactional,
2504                         const uchar *old_data, const uchar *new_data);
2505   static void binlog_prepare_row_images(TABLE* table);
2506 
set_server_id(uint32 sid)2507   void set_server_id(uint32 sid) { variables.server_id = sid; }
2508 
2509   /*
2510     Member functions to handle pending event for row-level logging.
2511   */
2512   template <class RowsEventT> Rows_log_event*
2513     binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id,
2514                                       size_t needed,
2515                                       bool is_transactional,
2516                                       RowsEventT* hint);
2517   Rows_log_event* binlog_get_pending_rows_event(bool is_transactional) const;
2518   void binlog_set_pending_rows_event(Rows_log_event* ev, bool is_transactional);
binlog_flush_pending_rows_event(bool stmt_end)2519   inline int binlog_flush_pending_rows_event(bool stmt_end)
2520   {
2521     return (binlog_flush_pending_rows_event(stmt_end, FALSE) ||
2522             binlog_flush_pending_rows_event(stmt_end, TRUE));
2523   }
2524   int binlog_flush_pending_rows_event(bool stmt_end, bool is_transactional);
2525   int binlog_remove_pending_rows_event(bool clear_maps, bool is_transactional);
2526 
2527   /**
2528     Determine the binlog format of the current statement.
2529 
2530     @retval 0 if the current statement will be logged in statement
2531     format.
2532     @retval nonzero if the current statement will be logged in row
2533     format.
2534    */
is_current_stmt_binlog_format_row()2535   int is_current_stmt_binlog_format_row() const {
2536     DBUG_ASSERT(current_stmt_binlog_format == BINLOG_FORMAT_STMT ||
2537                 current_stmt_binlog_format == BINLOG_FORMAT_ROW);
2538     return current_stmt_binlog_format == BINLOG_FORMAT_ROW;
2539   }
2540   /**
2541     Determine if binlogging is disabled for this session
2542     @retval 0 if the current statement binlogging is disabled
2543               (could be because of binlog closed/binlog option
2544                is set to false).
2545     @retval 1 if the current statement will be binlogged
2546   */
is_current_stmt_binlog_disabled()2547   inline bool is_current_stmt_binlog_disabled() const
2548   {
2549     return (!(variables.option_bits & OPTION_BIN_LOG) ||
2550             !mysql_bin_log.is_open());
2551   }
2552 
2553   enum binlog_filter_state
2554   {
2555     BINLOG_FILTER_UNKNOWN,
2556     BINLOG_FILTER_CLEAR,
2557     BINLOG_FILTER_SET
2558   };
2559 
reset_binlog_local_stmt_filter()2560   inline void reset_binlog_local_stmt_filter()
2561   {
2562     m_binlog_filter_state= BINLOG_FILTER_UNKNOWN;
2563   }
2564 
clear_binlog_local_stmt_filter()2565   inline void clear_binlog_local_stmt_filter()
2566   {
2567     DBUG_ASSERT(m_binlog_filter_state == BINLOG_FILTER_UNKNOWN);
2568     m_binlog_filter_state= BINLOG_FILTER_CLEAR;
2569   }
2570 
set_binlog_local_stmt_filter()2571   inline void set_binlog_local_stmt_filter()
2572   {
2573     DBUG_ASSERT(m_binlog_filter_state == BINLOG_FILTER_UNKNOWN);
2574     m_binlog_filter_state= BINLOG_FILTER_SET;
2575   }
2576 
get_binlog_local_stmt_filter()2577   inline binlog_filter_state get_binlog_local_stmt_filter()
2578   {
2579     return m_binlog_filter_state;
2580   }
2581 
2582 private:
2583   /**
2584     Indicate if the current statement should be discarded
2585     instead of written to the binlog.
2586     This is used to discard special statements, such as
2587     DML or DDL that affects only 'local' (non replicated)
2588     tables, such as performance_schema.*
2589   */
2590   binlog_filter_state m_binlog_filter_state;
2591 
2592   /**
2593     Indicates the format in which the current statement will be
2594     logged.  This can only be set from @c decide_logging_format().
2595   */
2596   enum_binlog_format current_stmt_binlog_format;
2597 
2598   /*
2599     Number of outstanding table maps, i.e., table maps in the
2600     transaction cache.
2601   */
2602   uint binlog_table_maps;
2603 public:
2604   void issue_unsafe_warnings();
reset_unsafe_warnings()2605   void reset_unsafe_warnings()
2606   { binlog_unsafe_warning_flags= 0; }
2607 
get_binlog_table_maps()2608   uint get_binlog_table_maps() const {
2609     return binlog_table_maps;
2610   }
clear_binlog_table_maps()2611   void clear_binlog_table_maps() {
2612     binlog_table_maps= 0;
2613   }
2614 #endif /* MYSQL_CLIENT */
2615 
2616 public:
2617 
2618   struct st_transactions {
2619     SAVEPOINT *savepoints;
2620     THD_TRANS all;			// Trans since BEGIN WORK
2621     THD_TRANS stmt;			// Trans for current statement
2622     bool on;                            // see ha_enable_transaction()
2623     XID_STATE xid_state;
2624     WT_THD wt;                          ///< for deadlock detection
2625     Rows_log_event *m_pending_rows_event;
2626 
2627     struct st_trans_time : public timeval
2628     {
resetst_transactions::st_trans_time2629       void reset(THD *thd)
2630       {
2631         tv_sec= thd->query_start();
2632         tv_usec= (long) thd->query_start_sec_part();
2633       }
2634     } start_time;
2635 
2636     /*
2637        Tables changed in transaction (that must be invalidated in query cache).
2638        List contain only transactional tables, that not invalidated in query
2639        cache (instead of full list of changed in transaction tables).
2640     */
2641     CHANGED_TABLE_LIST* changed_tables;
2642     MEM_ROOT mem_root; // Transaction-life memory allocation pool
cleanupst_transactions2643     void cleanup()
2644     {
2645       DBUG_ENTER("thd::cleanup");
2646       changed_tables= 0;
2647       savepoints= 0;
2648       /*
2649         If rm_error is raised, it means that this piece of a distributed
2650         transaction has failed and must be rolled back. But the user must
2651         rollback it explicitly, so don't start a new distributed XA until
2652         then.
2653       */
2654       if (!xid_state.rm_error)
2655         xid_state.xid.null();
2656       free_root(&mem_root,MYF(MY_KEEP_PREALLOC));
2657       DBUG_VOID_RETURN;
2658     }
is_activest_transactions2659     my_bool is_active()
2660     {
2661       return (all.ha_list != NULL);
2662     }
st_transactionsst_transactions2663     st_transactions()
2664     {
2665       bzero((char*)this, sizeof(*this));
2666       xid_state.xid.null();
2667       init_sql_alloc(&mem_root, "THD::transactions",
2668                      ALLOC_ROOT_MIN_BLOCK_SIZE, 0,
2669                      MYF(MY_THREAD_SPECIFIC));
2670     }
2671   } transaction;
2672   Global_read_lock global_read_lock;
2673   Field      *dup_field;
2674 #ifndef __WIN__
2675   sigset_t signals;
2676 #endif
2677 #ifdef SIGNAL_WITH_VIO_CLOSE
2678   Vio* active_vio;
2679 #endif
2680 
2681   /*
2682     A permanent memory area of the statement. For conventional
2683     execution, the parsed tree and execution runtime reside in the same
2684     memory root. In this case stmt_arena points to THD. In case of
2685     a prepared statement or a stored procedure statement, thd->mem_root
2686     conventionally points to runtime memory, and thd->stmt_arena
2687     points to the memory of the PS/SP, where the parsed tree of the
2688     statement resides. Whenever you need to perform a permanent
2689     transformation of a parsed tree, you should allocate new memory in
2690     stmt_arena, to allow correct re-execution of PS/SP.
2691     Note: in the parser, stmt_arena == thd, even for PS/SP.
2692   */
2693   Query_arena *stmt_arena;
2694 
2695   void *bulk_param;
2696 
2697   /*
2698     map for tables that will be updated for a multi-table update query
2699     statement, for other query statements, this will be zero.
2700   */
2701   table_map table_map_for_update;
2702 
2703   /* Tells if LAST_INSERT_ID(#) was called for the current statement */
2704   bool arg_of_last_insert_id_function;
2705   /*
2706     ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for
2707     insertion into an auto_increment column".
2708   */
2709   /*
2710     This is the first autogenerated insert id which was *successfully*
2711     inserted by the previous statement (exactly, if the previous statement
2712     didn't successfully insert an autogenerated insert id, then it's the one
2713     of the statement before, etc).
2714     It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#).
2715     It is returned by LAST_INSERT_ID().
2716   */
2717   ulonglong  first_successful_insert_id_in_prev_stmt;
2718   /*
2719     Variant of the above, used for storing in statement-based binlog. The
2720     difference is that the one above can change as the execution of a stored
2721     function progresses, while the one below is set once and then does not
2722     change (which is the value which statement-based binlog needs).
2723   */
2724   ulonglong  first_successful_insert_id_in_prev_stmt_for_binlog;
2725   /*
2726     This is the first autogenerated insert id which was *successfully*
2727     inserted by the current statement. It is maintained only to set
2728     first_successful_insert_id_in_prev_stmt when statement ends.
2729   */
2730   ulonglong  first_successful_insert_id_in_cur_stmt;
2731   /*
2732     We follow this logic:
2733     - when stmt starts, first_successful_insert_id_in_prev_stmt contains the
2734     first insert id successfully inserted by the previous stmt.
2735     - as stmt makes progress, handler::insert_id_for_cur_row changes;
2736     every time get_auto_increment() is called,
2737     auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the
2738     reserved interval (if statement-based binlogging).
2739     - at first successful insertion of an autogenerated value,
2740     first_successful_insert_id_in_cur_stmt is set to
2741     handler::insert_id_for_cur_row.
2742     - when stmt goes to binlog,
2743     auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if
2744     non-empty.
2745     - when stmt ends, first_successful_insert_id_in_prev_stmt is set to
2746     first_successful_insert_id_in_cur_stmt.
2747   */
2748   /*
2749     stmt_depends_on_first_successful_insert_id_in_prev_stmt is set when
2750     LAST_INSERT_ID() is used by a statement.
2751     If it is set, first_successful_insert_id_in_prev_stmt_for_binlog will be
2752     stored in the statement-based binlog.
2753     This variable is CUMULATIVE along the execution of a stored function or
2754     trigger: if one substatement sets it to 1 it will stay 1 until the
2755     function/trigger ends, thus making sure that
2756     first_successful_insert_id_in_prev_stmt_for_binlog does not change anymore
2757     and is propagated to the caller for binlogging.
2758   */
2759   bool       stmt_depends_on_first_successful_insert_id_in_prev_stmt;
2760   /*
2761     List of auto_increment intervals reserved by the thread so far, for
2762     storage in the statement-based binlog.
2763     Note that its minimum is not first_successful_insert_id_in_cur_stmt:
2764     assuming a table with an autoinc column, and this happens:
2765     INSERT INTO ... VALUES(3);
2766     SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL);
2767     then the latter INSERT will insert no rows
2768     (first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3"
2769     in the binlog is still needed; the list's minimum will contain 3.
2770     This variable is cumulative: if several statements are written to binlog
2771     as one (stored functions or triggers are used) this list is the
2772     concatenation of all intervals reserved by all statements.
2773   */
2774   Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog;
2775   /* Used by replication and SET INSERT_ID */
2776   Discrete_intervals_list auto_inc_intervals_forced;
2777   /*
2778     There is BUG#19630 where statement-based replication of stored
2779     functions/triggers with two auto_increment columns breaks.
2780     We however ensure that it works when there is 0 or 1 auto_increment
2781     column; our rules are
2782     a) on master, while executing a top statement involving substatements,
2783     first top- or sub- statement to generate auto_increment values wins the
2784     exclusive right to see its values be written to binlog (the write
2785     will be done by the statement or its caller), and the losers won't see
2786     their values be written to binlog.
2787     b) on slave, while replicating a top statement involving substatements,
2788     first top- or sub- statement to need to read auto_increment values from
2789     the master's binlog wins the exclusive right to read them (so the losers
2790     won't read their values from binlog but instead generate on their own).
2791     a) implies that we mustn't backup/restore
2792     auto_inc_intervals_in_cur_stmt_for_binlog.
2793     b) implies that we mustn't backup/restore auto_inc_intervals_forced.
2794 
2795     If there are more than 1 auto_increment columns, then intervals for
2796     different columns may mix into the
2797     auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong,
2798     but there is no point in preventing this mixing by preventing intervals
2799     from the secondly inserted column to come into the list, as such
2800     prevention would be wrong too.
2801     What will happen in the case of
2802     INSERT INTO t1 (auto_inc) VALUES(NULL);
2803     where t1 has a trigger which inserts into an auto_inc column of t2, is
2804     that in binlog we'll store the interval of t1 and the interval of t2 (when
2805     we store intervals, soon), then in slave, t1 will use both intervals, t2
2806     will use none; if t1 inserts the same number of rows as on master,
2807     normally the 2nd interval will not be used by t1, which is fine. t2's
2808     values will be wrong if t2's internal auto_increment counter is different
2809     from what it was on master (which is likely). In 5.1, in mixed binlogging
2810     mode, row-based binlogging is used for such cases where two
2811     auto_increment columns are inserted.
2812   */
record_first_successful_insert_id_in_cur_stmt(ulonglong id_arg)2813   inline void record_first_successful_insert_id_in_cur_stmt(ulonglong id_arg)
2814   {
2815     if (first_successful_insert_id_in_cur_stmt == 0)
2816       first_successful_insert_id_in_cur_stmt= id_arg;
2817   }
read_first_successful_insert_id_in_prev_stmt(void)2818   inline ulonglong read_first_successful_insert_id_in_prev_stmt(void)
2819   {
2820     if (!stmt_depends_on_first_successful_insert_id_in_prev_stmt)
2821     {
2822       /* It's the first time we read it */
2823       first_successful_insert_id_in_prev_stmt_for_binlog=
2824         first_successful_insert_id_in_prev_stmt;
2825       stmt_depends_on_first_successful_insert_id_in_prev_stmt= 1;
2826     }
2827     return first_successful_insert_id_in_prev_stmt;
2828   }
2829   /*
2830     Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#"
2831     (mysqlbinlog). We'll soon add a variant which can take many intervals in
2832     argument.
2833   */
force_one_auto_inc_interval(ulonglong next_id)2834   inline void force_one_auto_inc_interval(ulonglong next_id)
2835   {
2836     auto_inc_intervals_forced.empty(); // in case of multiple SET INSERT_ID
2837     auto_inc_intervals_forced.append(next_id, ULONGLONG_MAX, 0);
2838   }
2839 
2840   ulonglong  limit_found_rows;
2841 
2842 private:
2843   /**
2844     Stores the result of ROW_COUNT() function.
2845 
2846     ROW_COUNT() function is a MySQL extention, but we try to keep it
2847     similar to ROW_COUNT member of the GET DIAGNOSTICS stack of the SQL
2848     standard (see SQL99, part 2, search for ROW_COUNT). It's value is
2849     implementation defined for anything except INSERT, DELETE, UPDATE.
2850 
2851     ROW_COUNT is assigned according to the following rules:
2852 
2853       - In my_ok():
2854         - for DML statements: to the number of affected rows;
2855         - for DDL statements: to 0.
2856 
2857       - In my_eof(): to -1 to indicate that there was a result set.
2858 
2859         We derive this semantics from the JDBC specification, where int
2860         java.sql.Statement.getUpdateCount() is defined to (sic) "return the
2861         current result as an update count; if the result is a ResultSet
2862         object or there are no more results, -1 is returned".
2863 
2864       - In my_error(): to -1 to be compatible with the MySQL C API and
2865         MySQL ODBC driver.
2866 
2867       - For SIGNAL statements: to 0 per WL#2110 specification (see also
2868         sql_signal.cc comment). Zero is used since that's the "default"
2869         value of ROW_COUNT in the diagnostics area.
2870   */
2871 
2872   longlong m_row_count_func;    /* For the ROW_COUNT() function */
2873 
2874 public:
get_row_count_func()2875   inline longlong get_row_count_func() const
2876   {
2877     return m_row_count_func;
2878   }
2879 
set_row_count_func(longlong row_count_func)2880   inline void set_row_count_func(longlong row_count_func)
2881   {
2882     m_row_count_func= row_count_func;
2883   }
set_affected_rows(longlong row_count_func)2884   inline void set_affected_rows(longlong row_count_func)
2885   {
2886     /*
2887       We have to add to affected_rows (used by slow log), as otherwise
2888       information for 'call' will be wrong
2889     */
2890     affected_rows+= (row_count_func >= 0 ? row_count_func : 0);
2891   }
2892 
2893   ha_rows    cuted_fields;
2894 
2895 private:
2896   /*
2897     number of rows we actually sent to the client, including "synthetic"
2898     rows in ROLLUP etc.
2899   */
2900   ha_rows    m_sent_row_count;
2901 
2902   /**
2903     Number of rows read and/or evaluated for a statement. Used for
2904     slow log reporting.
2905 
2906     An examined row is defined as a row that is read and/or evaluated
2907     according to a statement condition, including in
2908     create_sort_index(). Rows may be counted more than once, e.g., a
2909     statement including ORDER BY could possibly evaluate the row in
2910     filesort() before reading it for e.g. update.
2911   */
2912   ha_rows    m_examined_row_count;
2913 
2914 public:
get_sent_row_count()2915   ha_rows get_sent_row_count() const
2916   { return m_sent_row_count; }
2917 
get_examined_row_count()2918   ha_rows get_examined_row_count() const
2919   { return m_examined_row_count; }
2920 
get_affected_rows()2921   ulonglong get_affected_rows() const
2922   { return affected_rows; }
2923 
2924   void set_sent_row_count(ha_rows count);
2925   void set_examined_row_count(ha_rows count);
2926 
2927   void inc_sent_row_count(ha_rows count);
2928   void inc_examined_row_count(ha_rows count);
2929 
2930   void inc_status_created_tmp_disk_tables();
2931   void inc_status_created_tmp_files();
2932   void inc_status_created_tmp_tables();
2933   void inc_status_select_full_join();
2934   void inc_status_select_full_range_join();
2935   void inc_status_select_range();
2936   void inc_status_select_range_check();
2937   void inc_status_select_scan();
2938   void inc_status_sort_merge_passes();
2939   void inc_status_sort_range();
2940   void inc_status_sort_rows(ha_rows count);
2941   void inc_status_sort_scan();
2942   void set_status_no_index_used();
2943   void set_status_no_good_index_used();
2944 
2945   /**
2946     The number of rows and/or keys examined by the query, both read,
2947     changed or written.
2948   */
2949   ulonglong accessed_rows_and_keys;
2950 
2951   /**
2952     Check if the number of rows accessed by a statement exceeded
2953     LIMIT ROWS EXAMINED. If so, signal the query engine to stop execution.
2954   */
check_limit_rows_examined()2955   void check_limit_rows_examined()
2956   {
2957     if (++accessed_rows_and_keys > lex->limit_rows_examined_cnt)
2958       set_killed(ABORT_QUERY);
2959   }
2960 
2961   USER_CONN *user_connect;
2962   CHARSET_INFO *db_charset;
2963 #if defined(ENABLED_PROFILING)
2964   PROFILING  profiling;
2965 #endif
2966 
2967   /** Current statement digest. */
2968   sql_digest_state *m_digest;
2969   /** Current statement digest token array. */
2970   unsigned char *m_token_array;
2971   /** Top level statement digest. */
2972   sql_digest_state m_digest_state;
2973 
2974   /** Current statement instrumentation. */
2975   PSI_statement_locker *m_statement_psi;
2976 #ifdef HAVE_PSI_STATEMENT_INTERFACE
2977   /** Current statement instrumentation state. */
2978   PSI_statement_locker_state m_statement_state;
2979 #endif /* HAVE_PSI_STATEMENT_INTERFACE */
2980   /** Idle instrumentation. */
2981   PSI_idle_locker *m_idle_psi;
2982 #ifdef HAVE_PSI_IDLE_INTERFACE
2983   /** Idle instrumentation state. */
2984   PSI_idle_locker_state m_idle_state;
2985 #endif /* HAVE_PSI_IDLE_INTERFACE */
2986 
2987   /*
2988     Id of current query. Statement can be reused to execute several queries
2989     query_id is global in context of the whole MySQL server.
2990     ID is automatically generated from mutex-protected counter.
2991     It's used in handler code for various purposes: to check which columns
2992     from table are necessary for this select, to check if it's necessary to
2993     update auto-updatable fields (like auto_increment and timestamp).
2994   */
2995   query_id_t query_id;
2996   ulong      col_access;
2997 
2998   /* Statement id is thread-wide. This counter is used to generate ids */
2999   ulong      statement_id_counter;
3000   ulong	     rand_saved_seed1, rand_saved_seed2;
3001 
3002   /* The following variables are used when printing to slow log */
3003   ulong      query_plan_flags;
3004   ulong      query_plan_fsort_passes;
3005   ulong      tmp_tables_used;
3006   ulong      tmp_tables_disk_used;
3007   ulonglong  tmp_tables_size;
3008   ulonglong  bytes_sent_old;
3009   ulonglong  affected_rows;                     /* Number of changed rows */
3010 
3011   pthread_t  real_id;                           /* For debugging */
3012   my_thread_id  thread_id, thread_dbug_id;
3013   uint32      os_thread_id;
3014   uint	     tmp_table, global_disable_checkpoint;
3015   uint	     server_status,open_options;
3016   enum enum_thread_type system_thread;
3017   /*
3018     Current or next transaction isolation level.
3019     When a connection is established, the value is taken from
3020     @@session.tx_isolation (default transaction isolation for
3021     the session), which is in turn taken from @@global.tx_isolation
3022     (the global value).
3023     If there is no transaction started, this variable
3024     holds the value of the next transaction's isolation level.
3025     When a transaction starts, the value stored in this variable
3026     becomes "actual".
3027     At transaction commit or rollback, we assign this variable
3028     again from @@session.tx_isolation.
3029     The only statement that can otherwise change the value
3030     of this variable is SET TRANSACTION ISOLATION LEVEL.
3031     Its purpose is to effect the isolation level of the next
3032     transaction in this session. When this statement is executed,
3033     the value in this variable is changed. However, since
3034     this statement is only allowed when there is no active
3035     transaction, this assignment (naturally) only affects the
3036     upcoming transaction.
3037     At the end of the current active transaction the value is
3038     be reset again from @@session.tx_isolation, as described
3039     above.
3040   */
3041   enum_tx_isolation tx_isolation;
3042   /*
3043     Current or next transaction access mode.
3044     See comment above regarding tx_isolation.
3045   */
3046   bool              tx_read_only;
3047   enum_check_fields count_cuted_fields;
3048 
3049   DYNAMIC_ARRAY user_var_events;        /* For user variables replication */
3050   MEM_ROOT      *user_var_events_alloc; /* Allocate above array elements here */
3051 
3052   /*
3053     Define durability properties that engines may check to
3054     improve performance. Not yet used in MariaDB
3055   */
3056   enum durability_properties durability_property;
3057 
3058   /*
3059     If checking this in conjunction with a wait condition, please
3060     include a check after enter_cond() if you want to avoid a race
3061     condition. For details see the implementation of awake(),
3062     especially the "broadcast" part.
3063   */
3064   killed_state volatile killed;
3065 
3066   /*
3067     The following is used if one wants to have a specific error number and
3068     text for the kill
3069   */
3070   struct err_info
3071   {
3072     int no;
3073     const char msg[256];
3074   } *killed_err;
3075 
3076   /* See also thd_killed() */
3077   inline bool check_killed(bool dont_send_error_message= 0)
3078   {
3079     if (unlikely(killed))
3080     {
3081       if (!dont_send_error_message)
3082         send_kill_message();
3083       return TRUE;
3084     }
3085     if (apc_target.have_apc_requests())
3086       apc_target.process_apc_requests();
3087     return FALSE;
3088   }
3089 
3090   /* scramble - random string sent to client on handshake */
3091   char	     scramble[SCRAMBLE_LENGTH+1];
3092 
3093   /*
3094     If this is a slave, the name of the connection stored here.
3095     This is used for taging error messages in the log files.
3096   */
3097   LEX_CSTRING connection_name;
3098   char       default_master_connection_buff[MAX_CONNECTION_NAME+1];
3099   uint8      password; /* 0, 1 or 2 */
3100   uint8      failed_com_change_user;
3101   bool       slave_thread;
3102   bool       extra_port;                        /* If extra connection */
3103   bool	     no_errors;
3104 
3105   /**
3106     Set to TRUE if execution of the current compound statement
3107     can not continue. In particular, disables activation of
3108     CONTINUE or EXIT handlers of stored routines.
3109     Reset in the end of processing of the current user request, in
3110     @see THD::reset_for_next_command().
3111   */
3112   bool is_fatal_error;
3113   /**
3114     Set by a storage engine to request the entire
3115     transaction (that possibly spans multiple engines) to
3116     rollback. Reset in ha_rollback.
3117   */
3118   bool       transaction_rollback_request;
3119   /**
3120     TRUE if we are in a sub-statement and the current error can
3121     not be safely recovered until we left the sub-statement mode.
3122     In particular, disables activation of CONTINUE and EXIT
3123     handlers inside sub-statements. E.g. if it is a deadlock
3124     error and requires a transaction-wide rollback, this flag is
3125     raised (traditionally, MySQL first has to close all the reads
3126     via @see handler::ha_index_or_rnd_end() and only then perform
3127     the rollback).
3128     Reset to FALSE when we leave the sub-statement mode.
3129   */
3130   bool       is_fatal_sub_stmt_error;
3131   bool	     rand_used, time_zone_used;
3132   bool       query_start_sec_part_used;
3133   /* for IS NULL => = last_insert_id() fix in remove_eq_conds() */
3134   bool       substitute_null_with_insert_id;
3135   bool	     in_lock_tables;
3136   bool       bootstrap, cleanup_done, free_connection_done;
3137 
3138   /**  is set if some thread specific value(s) used in a statement. */
3139   bool       thread_specific_used;
3140   /**
3141     is set if a statement accesses a temporary table created through
3142     CREATE TEMPORARY TABLE.
3143   */
3144 private:
3145   bool       charset_is_system_charset, charset_is_collation_connection;
3146   bool       charset_is_character_set_filesystem;
3147 public:
3148   bool       enable_slow_log;    /* Enable slow log for current statement */
3149   bool	     abort_on_warning;
3150   bool 	     got_warning;       /* Set on call to push_warning() */
3151   /* set during loop of derived table processing */
3152   bool       derived_tables_processing;
3153   bool       tablespace_op;	/* This is TRUE in DISCARD/IMPORT TABLESPACE */
3154   /* True if we have to log the current statement */
3155   bool	     log_current_statement;
3156   /**
3157     True if a slave error. Causes the slave to stop. Not the same
3158     as the statement execution error (is_error()), since
3159     a statement may be expected to return an error, e.g. because
3160     it returned an error on master, and this is OK on the slave.
3161   */
3162   bool       is_slave_error;
3163   /*
3164     True when a transaction is queued up for binlog group commit.
3165     Used so that if another transaction needs to wait for a row lock held by
3166     this transaction, it can signal to trigger the group commit immediately,
3167     skipping the normal --binlog-commit-wait-count wait.
3168   */
3169   bool waiting_on_group_commit;
3170   /*
3171     Set true when another transaction goes to wait on a row lock held by this
3172     transaction. Used together with waiting_on_group_commit.
3173   */
3174   bool has_waiter;
3175   /*
3176     In case of a slave, set to the error code the master got when executing
3177     the query. 0 if no error on the master.
3178   */
3179   int	     slave_expected_error;
3180   enum_sql_command last_sql_command;  // Last sql_command exceuted in mysql_execute_command()
3181 
3182   sp_rcontext *spcont;		// SP runtime context
3183   sp_cache   *sp_proc_cache;
3184   sp_cache   *sp_func_cache;
3185   sp_cache   *sp_package_spec_cache;
3186   sp_cache   *sp_package_body_cache;
3187 
3188   /** number of name_const() substitutions, see sp_head.cc:subst_spvars() */
3189   uint       query_name_consts;
3190 
3191   /*
3192     If we do a purge of binary logs, log index info of the threads
3193     that are currently reading it needs to be adjusted. To do that
3194     each thread that is using LOG_INFO needs to adjust the pointer to it
3195   */
3196   LOG_INFO*  current_linfo;
3197   NET*       slave_net;			// network connection from slave -> m.
3198 
3199   /*
3200     Used to update global user stats.  The global user stats are updated
3201     occasionally with the 'diff' variables.  After the update, the 'diff'
3202     variables are reset to 0.
3203   */
3204   /* Time when the current thread connected to MySQL. */
3205   time_t current_connect_time;
3206   /* Last time when THD stats were updated in global_user_stats. */
3207   time_t last_global_update_time;
3208   /* Number of commands not reflected in global_user_stats yet. */
3209   uint select_commands, update_commands, other_commands;
3210   ulonglong start_cpu_time;
3211   ulonglong start_bytes_received;
3212 
3213   /* Used by the sys_var class to store temporary values */
3214   union
3215   {
3216     my_bool   my_bool_value;
3217     int       int_value;
3218     uint      uint_value;
3219     long      long_value;
3220     ulong     ulong_value;
3221     ulonglong ulonglong_value;
3222     double    double_value;
3223     void      *ptr_value;
3224   } sys_var_tmp;
3225 
3226   struct {
3227     /*
3228       If true, mysql_bin_log::write(Log_event) call will not write events to
3229       binlog, and maintain 2 below variables instead (use
3230       mysql_bin_log.start_union_events to turn this on)
3231     */
3232     bool do_union;
3233     /*
3234       If TRUE, at least one mysql_bin_log::write(Log_event) call has been
3235       made after last mysql_bin_log.start_union_events() call.
3236     */
3237     bool unioned_events;
3238     /*
3239       If TRUE, at least one mysql_bin_log::write(Log_event e), where
3240       e.cache_stmt == TRUE call has been made after last
3241       mysql_bin_log.start_union_events() call.
3242     */
3243     bool unioned_events_trans;
3244 
3245     /*
3246       'queries' (actually SP statements) that run under inside this binlog
3247       union have thd->query_id >= first_query_id.
3248     */
3249     query_id_t first_query_id;
3250   } binlog_evt_union;
3251 
3252   mysql_cond_t              COND_wsrep_thd;
3253   /**
3254     Internal parser state.
3255     Note that since the parser is not re-entrant, we keep only one parser
3256     state here. This member is valid only when executing code during parsing.
3257   */
3258   Parser_state *m_parser_state;
3259 
3260   Locked_tables_list locked_tables_list;
3261 
3262 #ifdef WITH_PARTITION_STORAGE_ENGINE
3263   partition_info *work_part_info;
3264 #endif
3265 
3266 #ifndef EMBEDDED_LIBRARY
3267   /**
3268     Array of active audit plugins which have been used by this THD.
3269     This list is later iterated to invoke release_thd() on those
3270     plugins.
3271   */
3272   DYNAMIC_ARRAY audit_class_plugins;
3273   /**
3274     Array of bits indicating which audit classes have already been
3275     added to the list of audit plugins which are currently in use.
3276   */
3277   unsigned long audit_class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE];
3278   int audit_plugin_version;
3279 #endif
3280 
3281 #if defined(ENABLED_DEBUG_SYNC)
3282   /* Debug Sync facility. See debug_sync.cc. */
3283   struct st_debug_sync_control *debug_sync_control;
3284 #endif /* defined(ENABLED_DEBUG_SYNC) */
3285   /**
3286     @param id                thread identifier
3287     @param is_wsrep_applier  thread type
3288   */
3289   THD(my_thread_id id, bool is_wsrep_applier= false);
3290 
3291   ~THD();
3292 
3293   void init();
3294   /*
3295     Initialize memory roots necessary for query processing and (!)
3296     pre-allocate memory for it. We can't do that in THD constructor because
3297     there are use cases (acl_init, delayed inserts, watcher threads,
3298     killing mysqld) where it's vital to not allocate excessive and not used
3299     memory. Note, that we still don't return error from init_for_queries():
3300     if preallocation fails, we should notice that at the first call to
3301     alloc_root.
3302   */
3303   void init_for_queries();
3304   void update_all_stats();
3305   void update_stats(void);
3306   void change_user(void);
3307   void cleanup(void);
3308   void cleanup_after_query();
3309   void free_connection();
3310   void reset_for_reuse();
3311   bool store_globals();
3312   void reset_globals();
3313 #ifdef SIGNAL_WITH_VIO_CLOSE
set_active_vio(Vio * vio)3314   inline void set_active_vio(Vio* vio)
3315   {
3316     mysql_mutex_lock(&LOCK_thd_data);
3317     active_vio = vio;
3318     mysql_mutex_unlock(&LOCK_thd_data);
3319   }
clear_active_vio()3320   inline void clear_active_vio()
3321   {
3322     mysql_mutex_lock(&LOCK_thd_data);
3323     active_vio = 0;
3324     mysql_mutex_unlock(&LOCK_thd_data);
3325   }
3326   void close_active_vio();
3327 #endif
3328   void awake_no_mutex(killed_state state_to_set);
awake(killed_state state_to_set)3329   void awake(killed_state state_to_set)
3330   {
3331     mysql_mutex_lock(&LOCK_thd_kill);
3332     awake_no_mutex(state_to_set);
3333     mysql_mutex_unlock(&LOCK_thd_kill);
3334   }
3335 
3336   /** Disconnect the associated communication endpoint. */
3337   void disconnect();
3338 
3339 
3340   /*
3341     Allows this thread to serve as a target for others to schedule Async
3342     Procedure Calls on.
3343 
3344     It's possible to schedule any code to be executed this way, by
3345     inheriting from the Apc_call object. Currently, only
3346     Show_explain_request uses this.
3347   */
3348   Apc_target apc_target;
3349 
3350 #ifndef MYSQL_CLIENT
3351   enum enum_binlog_query_type {
3352     /* The query can be logged in row format or in statement format. */
3353     ROW_QUERY_TYPE,
3354 
3355     /* The query has to be logged in statement format. */
3356     STMT_QUERY_TYPE,
3357 
3358     QUERY_TYPE_COUNT
3359   };
3360 
3361   int binlog_query(enum_binlog_query_type qtype,
3362                    char const *query, ulong query_len, bool is_trans,
3363                    bool direct, bool suppress_use,
3364                    int errcode);
3365 #endif
3366 
3367   inline void
enter_cond(mysql_cond_t * cond,mysql_mutex_t * mutex,const PSI_stage_info * stage,PSI_stage_info * old_stage,const char * src_function,const char * src_file,int src_line)3368   enter_cond(mysql_cond_t *cond, mysql_mutex_t* mutex,
3369              const PSI_stage_info *stage, PSI_stage_info *old_stage,
3370              const char *src_function, const char *src_file,
3371              int src_line)
3372   {
3373     mysql_mutex_assert_owner(mutex);
3374     mysys_var->current_mutex = mutex;
3375     mysys_var->current_cond = cond;
3376     if (old_stage)
3377       backup_stage(old_stage);
3378     if (stage)
3379       enter_stage(stage, src_function, src_file, src_line);
3380   }
exit_cond(const PSI_stage_info * stage,const char * src_function,const char * src_file,int src_line)3381   inline void exit_cond(const PSI_stage_info *stage,
3382                         const char *src_function, const char *src_file,
3383                         int src_line)
3384   {
3385     /*
3386       Putting the mutex unlock in thd->exit_cond() ensures that
3387       mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is
3388       locked (if that would not be the case, you'll get a deadlock if someone
3389       does a THD::awake() on you).
3390     */
3391     mysql_mutex_unlock(mysys_var->current_mutex);
3392     mysql_mutex_lock(&mysys_var->mutex);
3393     mysys_var->current_mutex = 0;
3394     mysys_var->current_cond = 0;
3395     if (stage)
3396       enter_stage(stage, src_function, src_file, src_line);
3397     mysql_mutex_unlock(&mysys_var->mutex);
3398     return;
3399   }
is_killed()3400   virtual int is_killed() { return killed; }
get_thd()3401   virtual THD* get_thd() { return this; }
3402 
3403   /**
3404     A callback to the server internals that is used to address
3405     special cases of the locking protocol.
3406     Invoked when acquiring an exclusive lock, for each thread that
3407     has a conflicting shared metadata lock.
3408 
3409     This function:
3410     - aborts waiting of the thread on a data lock, to make it notice
3411       the pending exclusive lock and back off.
3412     - if the thread is an INSERT DELAYED thread, sends it a KILL
3413       signal to terminate it.
3414 
3415     @note This function does not wait for the thread to give away its
3416           locks. Waiting is done outside for all threads at once.
3417 
3418     @param ctx_in_use           The MDL context owner (thread) to wake up.
3419     @param needs_thr_lock_abort Indicates that to wake up thread
3420                                 this call needs to abort its waiting
3421                                 on table-level lock.
3422 
3423     @retval  TRUE  if the thread was woken up
3424     @retval  FALSE otherwise.
3425    */
3426   virtual bool notify_shared_lock(MDL_context_owner *ctx_in_use,
3427                                   bool needs_thr_lock_abort);
3428 
3429   // End implementation of MDL_context_owner interface.
3430 
is_strict_mode()3431   inline bool is_strict_mode() const
3432   {
3433     return (bool) (variables.sql_mode & (MODE_STRICT_TRANS_TABLES |
3434                                          MODE_STRICT_ALL_TABLES));
3435   }
backslash_escapes()3436   inline bool backslash_escapes() const
3437   {
3438     return !MY_TEST(variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES);
3439   }
3440   const Type_handler *type_handler_for_datetime() const;
3441   bool timestamp_to_TIME(MYSQL_TIME *ltime, my_time_t ts,
3442                          ulong sec_part, ulonglong fuzzydate);
query_start()3443   inline my_time_t query_start() { return start_time; }
query_start_sec_part()3444   inline ulong query_start_sec_part()
3445   { query_start_sec_part_used=1; return start_time_sec_part; }
3446   MYSQL_TIME query_start_TIME();
3447 
3448 private:
3449   struct {
3450     my_hrtime_t start;
3451     my_time_t sec;
3452     ulong sec_part;
3453   } system_time;
3454 
set_system_time()3455   void set_system_time()
3456   {
3457     my_hrtime_t hrtime= my_hrtime();
3458     my_time_t sec= hrtime_to_my_time(hrtime);
3459     ulong sec_part= hrtime_sec_part(hrtime);
3460     if (sec > system_time.sec ||
3461         (sec == system_time.sec && sec_part > system_time.sec_part) ||
3462         hrtime.val < system_time.start.val)
3463     {
3464       system_time.sec= sec;
3465       system_time.sec_part= sec_part;
3466       system_time.start= hrtime;
3467     }
3468     else
3469     {
3470       if (system_time.sec_part < TIME_MAX_SECOND_PART)
3471         system_time.sec_part++;
3472       else
3473       {
3474         system_time.sec++;
3475         system_time.sec_part= 0;
3476       }
3477     }
3478   }
3479 
3480 public:
transaction_time()3481   timeval transaction_time()
3482   {
3483     if (!in_multi_stmt_transaction_mode())
3484       transaction.start_time.reset(this);
3485     return transaction.start_time;
3486   }
3487 
set_start_time()3488   inline void set_start_time()
3489   {
3490     if (user_time.val)
3491     {
3492       start_time= hrtime_to_my_time(user_time);
3493       start_time_sec_part= hrtime_sec_part(user_time);
3494     }
3495     else
3496     {
3497       set_system_time();
3498       start_time= system_time.sec;
3499       start_time_sec_part= system_time.sec_part;
3500     }
3501     PSI_CALL_set_thread_start_time(start_time);
3502   }
set_time()3503   inline void set_time()
3504   {
3505     set_start_time();
3506     start_utime= utime_after_lock= microsecond_interval_timer();
3507   }
3508   /* only used in SET @@timestamp=... */
set_time(my_hrtime_t t)3509   inline void set_time(my_hrtime_t t)
3510   {
3511     user_time= t;
3512     set_time();
3513   }
3514   /*
3515     this is only used by replication and BINLOG command.
3516     usecs > TIME_MAX_SECOND_PART means "was not in binlog"
3517   */
set_time(my_time_t t,ulong sec_part)3518   inline void set_time(my_time_t t, ulong sec_part)
3519   {
3520     if (opt_secure_timestamp > (slave_thread ? SECTIME_REPL : SECTIME_SUPER))
3521       set_time();                 // note that BINLOG itself requires SUPER
3522     else
3523     {
3524       if (sec_part <= TIME_MAX_SECOND_PART)
3525       {
3526         start_time= system_time.sec= t;
3527         start_time_sec_part= system_time.sec_part= sec_part;
3528       }
3529       else if (t != system_time.sec)
3530       {
3531         start_time= system_time.sec= t;
3532         start_time_sec_part= system_time.sec_part= 0;
3533       }
3534       else
3535       {
3536         start_time= t;
3537         start_time_sec_part= ++system_time.sec_part;
3538       }
3539       user_time.val= hrtime_from_time(start_time) + start_time_sec_part;
3540       PSI_CALL_set_thread_start_time(start_time);
3541       start_utime= utime_after_lock= microsecond_interval_timer();
3542     }
3543   }
set_time_after_lock()3544   void set_time_after_lock()
3545   {
3546     utime_after_lock= microsecond_interval_timer();
3547     MYSQL_SET_STATEMENT_LOCK_TIME(m_statement_psi,
3548                                   (utime_after_lock - start_utime));
3549   }
current_utime()3550   ulonglong current_utime()  { return microsecond_interval_timer(); }
3551 
3552   /* Tell SHOW PROCESSLIST to show time from this point */
set_time_for_next_stage()3553   inline void set_time_for_next_stage()
3554   {
3555     utime_after_query= current_utime();
3556   }
3557 
3558   /**
3559    Update server status after execution of a top level statement.
3560    Currently only checks if a query was slow, and assigns
3561    the status accordingly.
3562    Evaluate the current time, and if it exceeds the long-query-time
3563    setting, mark the query as slow.
3564   */
update_server_status()3565   void update_server_status()
3566   {
3567     set_time_for_next_stage();
3568     if (utime_after_query >= utime_after_lock + variables.long_query_time)
3569       server_status|= SERVER_QUERY_WAS_SLOW;
3570   }
found_rows(void)3571   inline ulonglong found_rows(void)
3572   {
3573     return limit_found_rows;
3574   }
3575   /**
3576     Returns TRUE if session is in a multi-statement transaction mode.
3577 
3578     OPTION_NOT_AUTOCOMMIT: When autocommit is off, a multi-statement
3579     transaction is implicitly started on the first statement after a
3580     previous transaction has been ended.
3581 
3582     OPTION_BEGIN: Regardless of the autocommit status, a multi-statement
3583     transaction can be explicitly started with the statements "START
3584     TRANSACTION", "BEGIN [WORK]", "[COMMIT | ROLLBACK] AND CHAIN", etc.
3585 
3586     Note: this doesn't tell you whether a transaction is active.
3587     A session can be in multi-statement transaction mode, and yet
3588     have no active transaction, e.g., in case of:
3589     set @@autocommit=0;
3590     set @a= 3;                                     <-- these statements don't
3591     set transaction isolation level serializable;  <-- start an active
3592     flush tables;                                  <-- transaction
3593 
3594     I.e. for the above scenario this function returns TRUE, even
3595     though no active transaction has begun.
3596     @sa in_active_multi_stmt_transaction()
3597   */
in_multi_stmt_transaction_mode()3598   inline bool in_multi_stmt_transaction_mode()
3599   {
3600     return variables.option_bits & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN);
3601   }
3602   /**
3603     TRUE if the session is in a multi-statement transaction mode
3604     (@sa in_multi_stmt_transaction_mode()) *and* there is an
3605     active transaction, i.e. there is an explicit start of a
3606     transaction with BEGIN statement, or implicit with a
3607     statement that uses a transactional engine.
3608 
3609     For example, these scenarios don't start an active transaction
3610     (even though the server is in multi-statement transaction mode):
3611 
3612     set @@autocommit=0;
3613     select * from nontrans_table;
3614     set @var=TRUE;
3615     flush tables;
3616 
3617     Note, that even for a statement that starts a multi-statement
3618     transaction (i.e. select * from trans_table), this
3619     flag won't be set until we open the statement's tables
3620     and the engines register themselves for the transaction
3621     (see trans_register_ha()),
3622     hence this method is reliable to use only after
3623     open_tables() has completed.
3624 
3625     Why do we need a flag?
3626     ----------------------
3627     We need to maintain a (at first glance redundant)
3628     session flag, rather than looking at thd->transaction.all.ha_list
3629     because of explicit start of a transaction with BEGIN.
3630 
3631     I.e. in case of
3632     BEGIN;
3633     select * from nontrans_t1; <-- in_active_multi_stmt_transaction() is true
3634   */
in_active_multi_stmt_transaction()3635   inline bool in_active_multi_stmt_transaction()
3636   {
3637     return server_status & SERVER_STATUS_IN_TRANS;
3638   }
fill_information_schema_tables()3639   inline bool fill_information_schema_tables()
3640   {
3641     return !stmt_arena->is_stmt_prepare();
3642   }
trans_alloc(size_t size)3643   inline void* trans_alloc(size_t size)
3644   {
3645     return alloc_root(&transaction.mem_root,size);
3646   }
3647 
make_lex_string(LEX_STRING * lex_str,const char * str,size_t length)3648   LEX_STRING *make_lex_string(LEX_STRING *lex_str, const char* str, size_t length)
3649   {
3650     if (!(lex_str->str= strmake_root(mem_root, str, length)))
3651     {
3652       lex_str->length= 0;
3653       return 0;
3654     }
3655     lex_str->length= length;
3656     return lex_str;
3657   }
make_lex_string(LEX_CSTRING * lex_str,const char * str,size_t length)3658   LEX_CSTRING *make_lex_string(LEX_CSTRING *lex_str, const char* str, size_t length)
3659   {
3660     if (!(lex_str->str= strmake_root(mem_root, str, length)))
3661     {
3662       lex_str->length= 0;
3663       return 0;
3664     }
3665     lex_str->length= length;
3666     return lex_str;
3667   }
3668   // Remove double quotes:  aaa""bbb -> aaa"bbb
quote_unescape(LEX_CSTRING * dst,const LEX_CSTRING * src,char quote)3669   bool quote_unescape(LEX_CSTRING *dst, const LEX_CSTRING *src, char quote)
3670   {
3671     const char *tmp= src->str;
3672     const char *tmpend= src->str + src->length;
3673     char *to;
3674     if (!(dst->str= to= (char *) alloc(src->length + 1)))
3675     {
3676       dst->length= 0; // Safety
3677       return true;
3678     }
3679     for ( ; tmp < tmpend; )
3680     {
3681       if ((*to++= *tmp++) == quote)
3682         tmp++;                                  // Skip double quotes
3683     }
3684     *to= 0;                                     // End null for safety
3685     dst->length= to - dst->str;
3686     return false;
3687   }
3688 
make_clex_string(const char * str,size_t length)3689   LEX_CSTRING *make_clex_string(const char* str, size_t length)
3690   {
3691     LEX_CSTRING *lex_str;
3692     char *tmp;
3693     if (unlikely(!(lex_str= (LEX_CSTRING *)alloc_root(mem_root,
3694                                                       sizeof(LEX_CSTRING) +
3695                                                       length+1))))
3696       return 0;
3697     tmp= (char*) (lex_str+1);
3698     lex_str->str= tmp;
3699     memcpy(tmp, str, length);
3700     tmp[length]= 0;
3701     lex_str->length= length;
3702     return lex_str;
3703   }
make_clex_string(const LEX_CSTRING from)3704   LEX_CSTRING *make_clex_string(const LEX_CSTRING from)
3705   {
3706     return make_clex_string(from.str, from.length);
3707   }
3708 
3709   // Allocate LEX_STRING for character set conversion
alloc_lex_string(LEX_STRING * dst,size_t length)3710   bool alloc_lex_string(LEX_STRING *dst, size_t length)
3711   {
3712     if (likely((dst->str= (char*) alloc(length))))
3713       return false;
3714     dst->length= 0;  // Safety
3715     return true;     // EOM
3716   }
3717   bool convert_string(LEX_STRING *to, CHARSET_INFO *to_cs,
3718 		      const char *from, size_t from_length,
3719 		      CHARSET_INFO *from_cs);
convert_string(LEX_CSTRING * to,CHARSET_INFO * to_cs,const char * from,size_t from_length,CHARSET_INFO * from_cs)3720   bool convert_string(LEX_CSTRING *to, CHARSET_INFO *to_cs,
3721                       const char *from, size_t from_length,
3722                       CHARSET_INFO *from_cs)
3723   {
3724     LEX_STRING tmp;
3725     bool rc= convert_string(&tmp, to_cs, from, from_length, from_cs);
3726     to->str= tmp.str;
3727     to->length= tmp.length;
3728     return rc;
3729   }
convert_string(LEX_CSTRING * to,CHARSET_INFO * tocs,const LEX_CSTRING * from,CHARSET_INFO * fromcs,bool simple_copy_is_possible)3730   bool convert_string(LEX_CSTRING *to, CHARSET_INFO *tocs,
3731                       const LEX_CSTRING *from, CHARSET_INFO *fromcs,
3732                       bool simple_copy_is_possible)
3733   {
3734     if (!simple_copy_is_possible)
3735       return unlikely(convert_string(to, tocs, from->str, from->length, fromcs));
3736     *to= *from;
3737     return false;
3738   }
3739   /*
3740     Convert a strings between character sets.
3741     Uses my_convert_fix(), which uses an mb_wc .. mc_mb loop internally.
3742     dstcs and srccs cannot be &my_charset_bin.
3743   */
3744   bool convert_fix(CHARSET_INFO *dstcs, LEX_STRING *dst,
3745                    CHARSET_INFO *srccs, const char *src, size_t src_length,
3746                    String_copier *status);
3747 
3748   /*
3749     Same as above, but additionally sends ER_INVALID_CHARACTER_STRING
3750     in case of bad byte sequences or Unicode conversion problems.
3751   */
3752   bool convert_with_error(CHARSET_INFO *dstcs, LEX_STRING *dst,
3753                           CHARSET_INFO *srccs,
3754                           const char *src, size_t src_length);
3755   /*
3756     If either "dstcs" or "srccs" is &my_charset_bin,
3757     then performs native copying using cs->cset->copy_fix().
3758     Otherwise, performs Unicode conversion using convert_fix().
3759   */
3760   bool copy_fix(CHARSET_INFO *dstcs, LEX_STRING *dst,
3761                 CHARSET_INFO *srccs, const char *src, size_t src_length,
3762                 String_copier *status);
3763 
3764   /*
3765     Same as above, but additionally sends ER_INVALID_CHARACTER_STRING
3766     in case of bad byte sequences or Unicode conversion problems.
3767   */
3768   bool copy_with_error(CHARSET_INFO *dstcs, LEX_STRING *dst,
3769                        CHARSET_INFO *srccs, const char *src, size_t src_length);
3770 
3771   bool convert_string(String *s, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs);
3772 
3773   /*
3774     Check if the string is wellformed, raise an error if not wellformed.
3775     @param str    - The string to check.
3776     @param length - the string length.
3777   */
3778   bool check_string_for_wellformedness(const char *str,
3779                                        size_t length,
3780                                        CHARSET_INFO *cs) const;
3781 
3782   bool to_ident_sys_alloc(Lex_ident_sys_st *to, const Lex_ident_cli_st *from);
3783 
3784   /*
3785     Create a string literal with optional client->connection conversion.
3786     @param str        - the string in the client character set
3787     @param length     - length of the string
3788     @param repertoire - the repertoire of the string
3789   */
3790   Item_basic_constant *make_string_literal(const char *str, size_t length,
3791                                            uint repertoire);
make_string_literal(const Lex_string_with_metadata_st & str)3792   Item_basic_constant *make_string_literal(const Lex_string_with_metadata_st &str)
3793   {
3794     uint repertoire= str.repertoire(variables.character_set_client);
3795     return make_string_literal(str.str, str.length, repertoire);
3796   }
3797   Item_basic_constant *make_string_literal_nchar(const Lex_string_with_metadata_st &str);
3798   Item_basic_constant *make_string_literal_charset(const Lex_string_with_metadata_st &str,
3799                                                    CHARSET_INFO *cs);
make_text_string_sys(LEX_CSTRING * to,const Lex_string_with_metadata_st * from)3800   bool make_text_string_sys(LEX_CSTRING *to,
3801                             const Lex_string_with_metadata_st *from)
3802   {
3803     return convert_string(to, system_charset_info,
3804                           from, charset(), charset_is_system_charset);
3805   }
make_text_string_connection(LEX_CSTRING * to,const Lex_string_with_metadata_st * from)3806   bool make_text_string_connection(LEX_CSTRING *to,
3807                                    const Lex_string_with_metadata_st *from)
3808   {
3809     return convert_string(to, variables.collation_connection,
3810                           from, charset(), charset_is_collation_connection);
3811   }
make_text_string_filesystem(LEX_CSTRING * to,const Lex_string_with_metadata_st * from)3812   bool make_text_string_filesystem(LEX_CSTRING *to,
3813                                    const Lex_string_with_metadata_st *from)
3814   {
3815     return convert_string(to, variables.character_set_filesystem,
3816                           from, charset(), charset_is_character_set_filesystem);
3817   }
3818   void add_changed_table(TABLE *table);
3819   void add_changed_table(const char *key, size_t key_length);
3820   CHANGED_TABLE_LIST * changed_table_dup(const char *key, size_t key_length);
3821   int prepare_explain_fields(select_result *result, List<Item> *field_list,
3822                              uint8 explain_flags, bool is_analyze);
3823   int send_explain_fields(select_result *result, uint8 explain_flags,
3824                           bool is_analyze);
3825   void make_explain_field_list(List<Item> &field_list, uint8 explain_flags,
3826                                bool is_analyze);
3827   void make_explain_json_field_list(List<Item> &field_list, bool is_analyze);
3828 
3829   /**
3830     Clear the current error, if any.
3831     We do not clear is_fatal_error or is_fatal_sub_stmt_error since we
3832     assume this is never called if the fatal error is set.
3833 
3834     @todo: To silence an error, one should use Internal_error_handler
3835     mechanism. Issuing an error that can be possibly later "cleared" is not
3836     compatible with other installed error handlers and audit plugins.
3837   */
3838   inline void clear_error(bool clear_diagnostics= 0)
3839   {
3840     DBUG_ENTER("clear_error");
3841     if (get_stmt_da()->is_error() || clear_diagnostics)
3842       get_stmt_da()->reset_diagnostics_area();
3843     is_slave_error= 0;
3844     if (killed == KILL_BAD_DATA)
3845       reset_killed();
3846     DBUG_VOID_RETURN;
3847   }
3848 
3849 #ifndef EMBEDDED_LIBRARY
vio_ok()3850   inline bool vio_ok() const { return net.vio != 0; }
3851   /** Return FALSE if connection to client is broken. */
is_connected()3852   bool is_connected()
3853   {
3854     /*
3855       All system threads (e.g., the slave IO thread) are connected but
3856       not using vio. So this function always returns true for all
3857       system threads.
3858     */
3859     return system_thread || (vio_ok() ? vio_is_connected(net.vio) : FALSE);
3860   }
3861 #else
vio_ok()3862   inline bool vio_ok() const { return TRUE; }
is_connected()3863   inline bool is_connected() { return TRUE; }
3864 #endif
3865   /**
3866     Mark the current error as fatal. Warning: this does not
3867     set any error, it sets a property of the error, so must be
3868     followed or prefixed with my_error().
3869   */
fatal_error()3870   inline void fatal_error()
3871   {
3872     DBUG_ASSERT(get_stmt_da()->is_error() || killed);
3873     is_fatal_error= 1;
3874     DBUG_PRINT("error",("Fatal error set"));
3875   }
3876   /**
3877     TRUE if there is an error in the error stack.
3878 
3879     Please use this method instead of direct access to
3880     net.report_error.
3881 
3882     If TRUE, the current (sub)-statement should be aborted.
3883     The main difference between this member and is_fatal_error
3884     is that a fatal error can not be handled by a stored
3885     procedure continue handler, whereas a normal error can.
3886 
3887     To raise this flag, use my_error().
3888   */
is_error()3889   inline bool is_error() const { return m_stmt_da->is_error(); }
set_bulk_execution(void * bulk)3890   void set_bulk_execution(void *bulk)
3891   {
3892     bulk_param= bulk;
3893     m_stmt_da->set_bulk_execution(MY_TEST(bulk));
3894   }
is_bulk_op()3895   bool is_bulk_op() const { return MY_TEST(bulk_param); }
3896 
3897   /// Returns Diagnostics-area for the current statement.
get_stmt_da()3898   Diagnostics_area *get_stmt_da()
3899   { return m_stmt_da; }
3900 
3901   /// Returns Diagnostics-area for the current statement.
get_stmt_da()3902   const Diagnostics_area *get_stmt_da() const
3903   { return m_stmt_da; }
3904 
3905   /// Sets Diagnostics-area for the current statement.
set_stmt_da(Diagnostics_area * da)3906   void set_stmt_da(Diagnostics_area *da)
3907   { m_stmt_da= da; }
3908 
charset()3909   inline CHARSET_INFO *charset() const { return variables.character_set_client; }
3910   void update_charset();
update_charset(CHARSET_INFO * character_set_client,CHARSET_INFO * collation_connection)3911   void update_charset(CHARSET_INFO *character_set_client,
3912                       CHARSET_INFO *collation_connection)
3913   {
3914     variables.character_set_client= character_set_client;
3915     variables.collation_connection= collation_connection;
3916     update_charset();
3917   }
update_charset(CHARSET_INFO * character_set_client,CHARSET_INFO * collation_connection,CHARSET_INFO * character_set_results)3918   void update_charset(CHARSET_INFO *character_set_client,
3919                       CHARSET_INFO *collation_connection,
3920                       CHARSET_INFO *character_set_results)
3921   {
3922     variables.character_set_client= character_set_client;
3923     variables.collation_connection= collation_connection;
3924     variables.character_set_results= character_set_results;
3925     update_charset();
3926   }
3927 
activate_stmt_arena_if_needed(Query_arena * backup)3928   inline Query_arena *activate_stmt_arena_if_needed(Query_arena *backup)
3929   {
3930     /*
3931       Use the persistent arena if we are in a prepared statement or a stored
3932       procedure statement and we have not already changed to use this arena.
3933     */
3934     if (!stmt_arena->is_conventional() && mem_root != stmt_arena->mem_root)
3935     {
3936       set_n_backup_active_arena(stmt_arena, backup);
3937       return stmt_arena;
3938     }
3939     return 0;
3940   }
3941 
3942 
is_item_tree_change_register_required()3943   bool is_item_tree_change_register_required()
3944   {
3945     return !stmt_arena->is_conventional()
3946            || stmt_arena->type() == Query_arena::TABLE_ARENA;
3947   }
3948 
change_item_tree(Item ** place,Item * new_value)3949   void change_item_tree(Item **place, Item *new_value)
3950   {
3951     DBUG_ENTER("THD::change_item_tree");
3952     DBUG_PRINT("enter", ("Register: %p (%p) <- %p",
3953                        *place, place, new_value));
3954     /* TODO: check for OOM condition here */
3955     if (is_item_tree_change_register_required())
3956       nocheck_register_item_tree_change(place, *place, mem_root);
3957     *place= new_value;
3958     DBUG_VOID_RETURN;
3959   }
3960   /**
3961     Make change in item tree after checking whether it needs registering
3962 
3963 
3964     @param place         place where we should assign new value
3965     @param new_value     place of the new value
3966 
3967     @details
3968     see check_and_register_item_tree_change details
3969   */
check_and_register_item_tree(Item ** place,Item ** new_value)3970   void check_and_register_item_tree(Item **place, Item **new_value)
3971   {
3972     if (!stmt_arena->is_conventional())
3973       check_and_register_item_tree_change(place, new_value, mem_root);
3974     /*
3975       We have to use memcpy instead of  *place= *new_value merge to
3976       avoid problems with strict aliasing.
3977     */
3978     memcpy((char*) place, new_value, sizeof(*new_value));
3979   }
3980 
3981   /*
3982     Cleanup statement parse state (parse tree, lex) and execution
3983     state after execution of a non-prepared SQL statement.
3984   */
3985   void end_statement();
3986 
3987   /*
3988     Mark thread to be killed, with optional error number and string.
3989     string is not released, so it has to be allocted on thd mem_root
3990     or be a global string
3991 
3992     Ensure that we don't replace a kill with a lesser one. For example
3993     if user has done 'kill_connection' we shouldn't replace it with
3994     KILL_QUERY.
3995   */
3996   inline void set_killed(killed_state killed_arg,
3997                          int killed_errno_arg= 0,
3998                          const char *killed_err_msg_arg= 0)
3999   {
4000     mysql_mutex_lock(&LOCK_thd_kill);
4001     set_killed_no_mutex(killed_arg, killed_errno_arg, killed_err_msg_arg);
4002     mysql_mutex_unlock(&LOCK_thd_kill);
4003   }
4004   /*
4005     This is only used by THD::awake where we need to keep the lock mutex
4006     locked over some time.
4007     It's ok to have this inline, as in most cases killed_errno_arg will
4008     be a constant 0 and most of the function will disappear.
4009   */
4010   inline void set_killed_no_mutex(killed_state killed_arg,
4011                                   int killed_errno_arg= 0,
4012                                   const char *killed_err_msg_arg= 0)
4013   {
4014     if (killed <= killed_arg)
4015     {
4016       killed= killed_arg;
4017       if (killed_errno_arg)
4018       {
4019         /*
4020           If alloc fails, we only remember the killed flag.
4021           The worst things that can happen is that we get
4022           a suboptimal error message.
4023         */
4024         killed_err= (err_info*) alloc_root(&main_mem_root, sizeof(*killed_err));
4025         if (likely(killed_err))
4026         {
4027           killed_err->no= killed_errno_arg;
4028           ::strmake((char*) killed_err->msg, killed_err_msg_arg,
4029                     sizeof(killed_err->msg)-1);
4030         }
4031       }
4032     }
4033   }
4034   int killed_errno();
4035   void reset_killed();
reset_kill_query()4036   inline void reset_kill_query()
4037   {
4038     if (killed < KILL_CONNECTION)
4039     {
4040       reset_killed();
4041       mysys_var->abort= 0;
4042     }
4043   }
send_kill_message()4044   inline void send_kill_message()
4045   {
4046     mysql_mutex_lock(&LOCK_thd_kill);
4047     int err= killed_errno();
4048     if (err)
4049       my_message(err, killed_err ? killed_err->msg : ER_THD(this, err),
4050                  MYF(0));
4051     mysql_mutex_unlock(&LOCK_thd_kill);
4052   }
4053   /* return TRUE if we will abort query if we make a warning now */
really_abort_on_warning()4054   inline bool really_abort_on_warning()
4055   {
4056     return (abort_on_warning &&
4057             (!transaction.stmt.modified_non_trans_table ||
4058              (variables.sql_mode & MODE_STRICT_ALL_TABLES)));
4059   }
4060   void set_status_var_init();
4061   void reset_n_backup_open_tables_state(Open_tables_backup *backup);
4062   void restore_backup_open_tables_state(Open_tables_backup *backup);
4063   void reset_sub_statement_state(Sub_statement_state *backup, uint new_state);
4064   void restore_sub_statement_state(Sub_statement_state *backup);
4065   void store_slow_query_state(Sub_statement_state *backup);
4066   void reset_slow_query_state();
4067   void add_slow_query_state(Sub_statement_state *backup);
4068   void set_n_backup_active_arena(Query_arena *set, Query_arena *backup);
4069   void restore_active_arena(Query_arena *set, Query_arena *backup);
4070 
get_binlog_format(enum_binlog_format * format,enum_binlog_format * current_format)4071   inline void get_binlog_format(enum_binlog_format *format,
4072                                 enum_binlog_format *current_format)
4073   {
4074     *format= (enum_binlog_format) variables.binlog_format;
4075     *current_format= current_stmt_binlog_format;
4076   }
get_current_stmt_binlog_format()4077   inline enum_binlog_format get_current_stmt_binlog_format()
4078   {
4079     return current_stmt_binlog_format;
4080   }
set_binlog_format(enum_binlog_format format,enum_binlog_format current_format)4081   inline void set_binlog_format(enum_binlog_format format,
4082                                 enum_binlog_format current_format)
4083   {
4084     DBUG_ENTER("set_binlog_format");
4085     variables.binlog_format= format;
4086     current_stmt_binlog_format= current_format;
4087     DBUG_VOID_RETURN;
4088   }
set_binlog_format_stmt()4089   inline void set_binlog_format_stmt()
4090   {
4091     DBUG_ENTER("set_binlog_format_stmt");
4092     variables.binlog_format=    BINLOG_FORMAT_STMT;
4093     current_stmt_binlog_format= BINLOG_FORMAT_STMT;
4094     DBUG_VOID_RETURN;
4095   }
4096   /*
4097     @todo Make these methods private or remove them completely.  Only
4098     decide_logging_format should call them. /Sven
4099   */
set_current_stmt_binlog_format_row_if_mixed()4100   inline void set_current_stmt_binlog_format_row_if_mixed()
4101   {
4102     DBUG_ENTER("set_current_stmt_binlog_format_row_if_mixed");
4103     /*
4104       This should only be called from decide_logging_format.
4105 
4106       @todo Once we have ensured this, uncomment the following
4107       statement, remove the big comment below that, and remove the
4108       in_sub_stmt==0 condition from the following 'if'.
4109     */
4110     /* DBUG_ASSERT(in_sub_stmt == 0); */
4111     /*
4112       If in a stored/function trigger, the caller should already have done the
4113       change. We test in_sub_stmt to prevent introducing bugs where people
4114       wouldn't ensure that, and would switch to row-based mode in the middle
4115       of executing a stored function/trigger (which is too late, see also
4116       reset_current_stmt_binlog_format_row()); this condition will make their
4117       tests fail and so force them to propagate the
4118       lex->binlog_row_based_if_mixed upwards to the caller.
4119     */
4120     if ((wsrep_binlog_format() == BINLOG_FORMAT_MIXED) && (in_sub_stmt == 0))
4121       set_current_stmt_binlog_format_row();
4122 
4123     DBUG_VOID_RETURN;
4124   }
4125 
set_current_stmt_binlog_format(enum_binlog_format format)4126   inline void set_current_stmt_binlog_format(enum_binlog_format format)
4127   {
4128     current_stmt_binlog_format= format;
4129   }
4130 
set_current_stmt_binlog_format_row()4131   inline void set_current_stmt_binlog_format_row()
4132   {
4133     DBUG_ENTER("set_current_stmt_binlog_format_row");
4134     current_stmt_binlog_format= BINLOG_FORMAT_ROW;
4135     DBUG_VOID_RETURN;
4136   }
4137   /* Set binlog format temporarily to statement. Returns old format */
set_current_stmt_binlog_format_stmt()4138   inline enum_binlog_format set_current_stmt_binlog_format_stmt()
4139   {
4140     enum_binlog_format orig_format= current_stmt_binlog_format;
4141     DBUG_ENTER("set_current_stmt_binlog_format_stmt");
4142     current_stmt_binlog_format= BINLOG_FORMAT_STMT;
4143     DBUG_RETURN(orig_format);
4144   }
restore_stmt_binlog_format(enum_binlog_format format)4145   inline void restore_stmt_binlog_format(enum_binlog_format format)
4146   {
4147     DBUG_ENTER("restore_stmt_binlog_format");
4148     DBUG_ASSERT(!is_current_stmt_binlog_format_row());
4149     current_stmt_binlog_format= format;
4150     DBUG_VOID_RETURN;
4151   }
reset_current_stmt_binlog_format_row()4152   inline void reset_current_stmt_binlog_format_row()
4153   {
4154     DBUG_ENTER("reset_current_stmt_binlog_format_row");
4155     /*
4156       If there are temporary tables, don't reset back to
4157       statement-based. Indeed it could be that:
4158       CREATE TEMPORARY TABLE t SELECT UUID(); # row-based
4159       # and row-based does not store updates to temp tables
4160       # in the binlog.
4161       INSERT INTO u SELECT * FROM t; # stmt-based
4162       and then the INSERT will fail as data inserted into t was not logged.
4163       So we continue with row-based until the temp table is dropped.
4164       If we are in a stored function or trigger, we mustn't reset in the
4165       middle of its execution (as the binary logging way of a stored function
4166       or trigger is decided when it starts executing, depending for example on
4167       the caller (for a stored function: if caller is SELECT or
4168       INSERT/UPDATE/DELETE...).
4169     */
4170     DBUG_PRINT("debug",
4171                ("temporary_tables: %s, in_sub_stmt: %s, system_thread: %s",
4172                 YESNO(has_thd_temporary_tables()), YESNO(in_sub_stmt),
4173                 show_system_thread(system_thread)));
4174     if (in_sub_stmt == 0)
4175     {
4176       if (wsrep_binlog_format() == BINLOG_FORMAT_ROW)
4177         set_current_stmt_binlog_format_row();
4178       else if (!has_thd_temporary_tables())
4179         set_current_stmt_binlog_format_stmt();
4180     }
4181     DBUG_VOID_RETURN;
4182   }
4183 
4184   /**
4185     Set the current database; use deep copy of C-string.
4186 
4187     @param new_db     a pointer to the new database name.
4188     @param new_db_len length of the new database name.
4189 
4190     Initialize the current database from a NULL-terminated string with
4191     length. If we run out of memory, we free the current database and
4192     return TRUE.  This way the user will notice the error as there will be
4193     no current database selected (in addition to the error message set by
4194     malloc).
4195 
4196     @note This operation just sets {db, db_length}. Switching the current
4197     database usually involves other actions, like switching other database
4198     attributes including security context. In the future, this operation
4199     will be made private and more convenient interface will be provided.
4200 
4201     @return Operation status
4202       @retval FALSE Success
4203       @retval TRUE  Out-of-memory error
4204   */
4205   bool set_db(const LEX_CSTRING *new_db);
4206 
4207   /** Set the current database, without copying */
4208   void reset_db(const LEX_CSTRING *new_db);
4209 
4210   /*
4211     Copy the current database to the argument. Use the current arena to
4212     allocate memory for a deep copy: current database may be freed after
4213     a statement is parsed but before it's executed.
4214 
4215     Can only be called by owner of thd (no mutex protection)
4216   */
copy_db_to(LEX_CSTRING * to)4217   bool copy_db_to(LEX_CSTRING *to)
4218   {
4219     if (db.str == NULL)
4220     {
4221       /*
4222         No default database is set. In this case if it's guaranteed that
4223         no CTE can be used in the statement then we can throw an error right
4224         now at the parser stage. Otherwise the decision about throwing such
4225         a message must be postponed until a post-parser stage when we are able
4226         to resolve all CTE names as we don't need this message to be thrown
4227         for any CTE references.
4228       */
4229       if (!lex->with_cte_resolution)
4230         my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
4231       return TRUE;
4232     }
4233 
4234     to->str= strmake(db.str, db.length);
4235     to->length= db.length;
4236     return to->str == NULL;                     /* True on error */
4237   }
4238   /* Get db name or "". Use for printing current db */
get_db()4239   const char *get_db()
4240   { return safe_str(db.str); }
4241 
4242   thd_scheduler event_scheduler;
4243 
4244 public:
get_internal_handler()4245   inline Internal_error_handler *get_internal_handler()
4246   { return m_internal_handler; }
4247 
4248   /**
4249     Add an internal error handler to the thread execution context.
4250     @param handler the exception handler to add
4251   */
4252   void push_internal_handler(Internal_error_handler *handler);
4253 
4254 private:
4255   /**
4256     Handle a sql condition.
4257     @param sql_errno the condition error number
4258     @param sqlstate the condition sqlstate
4259     @param level the condition level
4260     @param msg the condition message text
4261     @param[out] cond_hdl the sql condition raised, if any
4262     @return true if the condition is handled
4263   */
4264   bool handle_condition(uint sql_errno,
4265                         const char* sqlstate,
4266                         Sql_condition::enum_warning_level *level,
4267                         const char* msg,
4268                         Sql_condition ** cond_hdl);
4269 
4270 public:
4271   /**
4272     Remove the error handler last pushed.
4273   */
4274   Internal_error_handler *pop_internal_handler();
4275 
4276   /**
4277     Raise an exception condition.
4278     @param code the MYSQL_ERRNO error code of the error
4279   */
4280   void raise_error(uint code);
4281 
4282   /**
4283     Raise an exception condition, with a formatted message.
4284     @param code the MYSQL_ERRNO error code of the error
4285   */
4286   void raise_error_printf(uint code, ...);
4287 
4288   /**
4289     Raise a completion condition (warning).
4290     @param code the MYSQL_ERRNO error code of the warning
4291   */
4292   void raise_warning(uint code);
4293 
4294   /**
4295     Raise a completion condition (warning), with a formatted message.
4296     @param code the MYSQL_ERRNO error code of the warning
4297   */
4298   void raise_warning_printf(uint code, ...);
4299 
4300   /**
4301     Raise a completion condition (note), with a fixed message.
4302     @param code the MYSQL_ERRNO error code of the note
4303   */
4304   void raise_note(uint code);
4305 
4306   /**
4307     Raise an completion condition (note), with a formatted message.
4308     @param code the MYSQL_ERRNO error code of the note
4309   */
4310   void raise_note_printf(uint code, ...);
4311 
4312   /**
4313     @brief Push an error message into MySQL error stack with line
4314     and position information.
4315 
4316     This function provides semantic action implementers with a way
4317     to push the famous "You have a syntax error near..." error
4318     message into the error stack, which is normally produced only if
4319     a parse error is discovered internally by the Bison generated
4320     parser.
4321   */
parse_error(const char * err_text,const char * yytext)4322   void parse_error(const char *err_text, const char *yytext)
4323   {
4324     Lex_input_stream *lip= &m_parser_state->m_lip;
4325     if (!yytext && !(yytext= lip->get_tok_start()))
4326         yytext= "";
4327     /* Push an error into the error stack */
4328     ErrConvString err(yytext, strlen(yytext), variables.character_set_client);
4329     my_printf_error(ER_PARSE_ERROR,  ER_THD(this, ER_PARSE_ERROR), MYF(0),
4330                     err_text, err.ptr(), lip->yylineno);
4331   }
4332   void parse_error(uint err_number, const char *yytext= 0)
4333   {
4334     parse_error(ER_THD(this, err_number), yytext);
4335   }
parse_error()4336   void parse_error()
4337   {
4338     parse_error(ER_SYNTAX_ERROR);
4339   }
4340 #ifdef mysqld_error_find_printf_error_used
parse_error(const char * t)4341   void parse_error(const char *t)
4342   {
4343   }
4344 #endif
4345 private:
4346   /*
4347     Only the implementation of the SIGNAL and RESIGNAL statements
4348     is permitted to raise SQL conditions in a generic way,
4349     or to raise them by bypassing handlers (RESIGNAL).
4350     To raise a SQL condition, the code should use the public
4351     raise_error() or raise_warning() methods provided by class THD.
4352   */
4353   friend class Sql_cmd_common_signal;
4354   friend class Sql_cmd_signal;
4355   friend class Sql_cmd_resignal;
4356   friend void push_warning(THD*, Sql_condition::enum_warning_level, uint, const char*);
4357   friend void my_message_sql(uint, const char *, myf);
4358 
4359   /**
4360     Raise a generic SQL condition.
4361     @param sql_errno the condition error number
4362     @param sqlstate the condition SQLSTATE
4363     @param level the condition level
4364     @param msg the condition message text
4365     @return The condition raised, or NULL
4366   */
4367   Sql_condition*
raise_condition(uint sql_errno,const char * sqlstate,Sql_condition::enum_warning_level level,const char * msg)4368   raise_condition(uint sql_errno,
4369                   const char* sqlstate,
4370                   Sql_condition::enum_warning_level level,
4371                   const char* msg)
4372   {
4373     return raise_condition(sql_errno, sqlstate, level,
4374                            Sql_user_condition_identity(), msg);
4375   }
4376 
4377   /**
4378     Raise a generic or a user defined SQL condition.
4379     @param ucid      - the user condition identity
4380                        (or an empty identity if not a user condition)
4381     @param sql_errno - the condition error number
4382     @param sqlstate  - the condition SQLSTATE
4383     @param level     - the condition level
4384     @param msg       - the condition message text
4385     @return The condition raised, or NULL
4386   */
4387   Sql_condition*
4388   raise_condition(uint sql_errno,
4389                   const char* sqlstate,
4390                   Sql_condition::enum_warning_level level,
4391                   const Sql_user_condition_identity &ucid,
4392                   const char* msg);
4393 
4394   Sql_condition*
raise_condition(const Sql_condition * cond)4395   raise_condition(const Sql_condition *cond)
4396   {
4397     Sql_condition *raised= raise_condition(cond->get_sql_errno(),
4398                                            cond->get_sqlstate(),
4399                                            cond->get_level(),
4400                                            *cond/*Sql_user_condition_identity*/,
4401                                            cond->get_message_text());
4402     if (raised)
4403       raised->copy_opt_attributes(cond);
4404     return raised;
4405   }
4406 
4407 public:
4408   /** Overloaded to guard query/query_length fields */
4409   virtual void set_statement(Statement *stmt);
set_command(enum enum_server_command command)4410   void set_command(enum enum_server_command command)
4411   {
4412     m_command= command;
4413 #ifdef HAVE_PSI_THREAD_INTERFACE
4414     PSI_STATEMENT_CALL(set_thread_command)(m_command);
4415 #endif
4416   }
get_command()4417   inline enum enum_server_command get_command() const
4418   { return m_command; }
4419 
4420   /**
4421     Assign a new value to thd->query and thd->query_id and mysys_var.
4422     Protected with LOCK_thd_data mutex.
4423   */
set_query(char * query_arg,size_t query_length_arg,CHARSET_INFO * cs_arg)4424   void set_query(char *query_arg, size_t query_length_arg,
4425                  CHARSET_INFO *cs_arg)
4426   {
4427     set_query(CSET_STRING(query_arg, query_length_arg, cs_arg));
4428   }
set_query(char * query_arg,size_t query_length_arg)4429   void set_query(char *query_arg, size_t query_length_arg) /*Mutex protected*/
4430   {
4431     set_query(CSET_STRING(query_arg, query_length_arg, charset()));
4432   }
set_query(const CSET_STRING & string_arg)4433   void set_query(const CSET_STRING &string_arg)
4434   {
4435     mysql_mutex_lock(&LOCK_thd_data);
4436     set_query_inner(string_arg);
4437     mysql_mutex_unlock(&LOCK_thd_data);
4438 
4439     PSI_CALL_set_thread_info(query(), query_length());
4440   }
reset_query()4441   void reset_query()               /* Mutex protected */
4442   { set_query(CSET_STRING()); }
4443   void set_query_and_id(char *query_arg, uint32 query_length_arg,
4444                         CHARSET_INFO *cs, query_id_t new_query_id);
set_query_id(query_id_t new_query_id)4445   void set_query_id(query_id_t new_query_id)
4446   {
4447     query_id= new_query_id;
4448   }
set_open_tables(TABLE * open_tables_arg)4449   void set_open_tables(TABLE *open_tables_arg)
4450   {
4451     mysql_mutex_lock(&LOCK_thd_data);
4452     open_tables= open_tables_arg;
4453     mysql_mutex_unlock(&LOCK_thd_data);
4454   }
4455   void set_mysys_var(struct st_my_thread_var *new_mysys_var);
enter_locked_tables_mode(enum_locked_tables_mode mode_arg)4456   void enter_locked_tables_mode(enum_locked_tables_mode mode_arg)
4457   {
4458     DBUG_ASSERT(locked_tables_mode == LTM_NONE);
4459 
4460     if (mode_arg == LTM_LOCK_TABLES)
4461     {
4462       /*
4463         When entering LOCK TABLES mode we should set explicit duration
4464         for all metadata locks acquired so far in order to avoid releasing
4465         them till UNLOCK TABLES statement.
4466         We don't do this when entering prelocked mode since sub-statements
4467         don't release metadata locks and restoring status-quo after leaving
4468         prelocking mode gets complicated.
4469       */
4470       mdl_context.set_explicit_duration_for_all_locks();
4471     }
4472 
4473     locked_tables_mode= mode_arg;
4474   }
4475   void leave_locked_tables_mode();
4476   /* Relesae transactional locks if there are no active transactions */
release_transactional_locks()4477   void release_transactional_locks()
4478   {
4479     if (!(server_status &
4480           (SERVER_STATUS_IN_TRANS | SERVER_STATUS_IN_TRANS_READONLY)))
4481       mdl_context.release_transactional_locks();
4482   }
4483   int decide_logging_format(TABLE_LIST *tables);
4484   /*
4485    In Some cases when decide_logging_format is called it does not have all
4486    information to decide the logging format. So that cases we call decide_logging_format_2
4487    at later stages in execution.
4488    One example would be binlog format for IODKU but column with unique key is not inserted.
4489    We dont have inserted columns info when we call decide_logging_format so on later stage we call
4490    decide_logging_format_low
4491 
4492    @returns 0 if no format is changed
4493             1 if there is change in binlog format
4494   */
4495   int decide_logging_format_low(TABLE *table);
4496 
4497   enum need_invoker { INVOKER_NONE=0, INVOKER_USER, INVOKER_ROLE};
binlog_invoker(bool role)4498   void binlog_invoker(bool role) { m_binlog_invoker= role ? INVOKER_ROLE : INVOKER_USER; }
need_binlog_invoker()4499   enum need_invoker need_binlog_invoker() { return m_binlog_invoker; }
4500   void get_definer(LEX_USER *definer, bool role);
set_invoker(const LEX_CSTRING * user,const LEX_CSTRING * host)4501   void set_invoker(const LEX_CSTRING *user, const LEX_CSTRING *host)
4502   {
4503     invoker.user= *user;
4504     invoker.host= *host;
4505   }
get_invoker_user()4506   LEX_CSTRING get_invoker_user() { return invoker.user; }
get_invoker_host()4507   LEX_CSTRING get_invoker_host() { return invoker.host; }
has_invoker()4508   bool has_invoker() { return invoker.user.length > 0; }
4509 
print_aborted_warning(uint threshold,const char * reason)4510   void print_aborted_warning(uint threshold, const char *reason)
4511   {
4512     if (global_system_variables.log_warnings > threshold)
4513     {
4514       Security_context *sctx= &main_security_ctx;
4515       sql_print_warning(ER_THD(this, ER_NEW_ABORTING_CONNECTION),
4516                         thread_id, (db.str ? db.str : "unconnected"),
4517                         sctx->user ? sctx->user : "unauthenticated",
4518                         sctx->host_or_ip, reason);
4519     }
4520   }
4521 
4522 public:
clear_wakeup_ready()4523   void clear_wakeup_ready() { wakeup_ready= false; }
4524   /*
4525     Sleep waiting for others to wake us up with signal_wakeup_ready().
4526     Must call clear_wakeup_ready() before waiting.
4527   */
4528   void wait_for_wakeup_ready();
4529   /* Wake this thread up from wait_for_wakeup_ready(). */
4530   void signal_wakeup_ready();
4531 
add_status_to_global()4532   void add_status_to_global()
4533   {
4534     DBUG_ASSERT(status_in_global == 0);
4535     mysql_mutex_lock(&LOCK_status);
4536     add_to_status(&global_status_var, &status_var);
4537     /* Mark that this THD status has already been added in global status */
4538     status_var.global_memory_used= 0;
4539     status_in_global= 1;
4540     mysql_mutex_unlock(&LOCK_status);
4541   }
4542 
4543   wait_for_commit *wait_for_commit_ptr;
wait_for_prior_commit()4544   int wait_for_prior_commit()
4545   {
4546     if (wait_for_commit_ptr)
4547       return wait_for_commit_ptr->wait_for_prior_commit(this);
4548     return 0;
4549   }
wakeup_subsequent_commits(int wakeup_error)4550   void wakeup_subsequent_commits(int wakeup_error)
4551   {
4552     if (wait_for_commit_ptr)
4553       wait_for_commit_ptr->wakeup_subsequent_commits(wakeup_error);
4554   }
suspend_subsequent_commits()4555   wait_for_commit *suspend_subsequent_commits() {
4556     wait_for_commit *suspended= wait_for_commit_ptr;
4557     wait_for_commit_ptr= NULL;
4558     return suspended;
4559   }
resume_subsequent_commits(wait_for_commit * suspended)4560   void resume_subsequent_commits(wait_for_commit *suspended) {
4561     DBUG_ASSERT(!wait_for_commit_ptr);
4562     wait_for_commit_ptr= suspended;
4563   }
4564 
4565   void mark_transaction_to_rollback(bool all);
4566 private:
4567 
4568   /** The current internal error handler for this thread, or NULL. */
4569   Internal_error_handler *m_internal_handler;
4570 
4571   /**
4572     The lex to hold the parsed tree of conventional (non-prepared) queries.
4573     Whereas for prepared and stored procedure statements we use an own lex
4574     instance for each new query, for conventional statements we reuse
4575     the same lex. (@see mysql_parse for details).
4576   */
4577   LEX main_lex;
4578   /**
4579     This memory root is used for two purposes:
4580     - for conventional queries, to allocate structures stored in main_lex
4581     during parsing, and allocate runtime data (execution plan, etc.)
4582     during execution.
4583     - for prepared queries, only to allocate runtime data. The parsed
4584     tree itself is reused between executions and thus is stored elsewhere.
4585   */
4586   MEM_ROOT main_mem_root;
4587   Diagnostics_area main_da;
4588   Diagnostics_area *m_stmt_da;
4589 
4590   /**
4591     It will be set if CURRENT_USER() or CURRENT_ROLE() is called in account
4592     management statements or default definer is set in CREATE/ALTER SP, SF,
4593     Event, TRIGGER or VIEW statements.
4594 
4595     Current user or role will be binlogged into Query_log_event if
4596     m_binlog_invoker is not NONE; It will be stored into invoker_host and
4597     invoker_user by SQL thread.
4598    */
4599   enum need_invoker m_binlog_invoker;
4600 
4601   /**
4602     It points to the invoker in the Query_log_event.
4603     SQL thread use it as the default definer in CREATE/ALTER SP, SF, Event,
4604     TRIGGER or VIEW statements or current user in account management
4605     statements if it is not NULL.
4606    */
4607   AUTHID invoker;
4608 
4609 public:
4610 #ifndef EMBEDDED_LIBRARY
4611   Session_tracker session_tracker;
4612 #endif //EMBEDDED_LIBRARY
4613   /*
4614     Flag, mutex and condition for a thread to wait for a signal from another
4615     thread.
4616 
4617     Currently used to wait for group commit to complete, can also be used for
4618     other purposes.
4619   */
4620   bool wakeup_ready;
4621   mysql_mutex_t LOCK_wakeup_ready;
4622   mysql_cond_t COND_wakeup_ready;
4623   /*
4624     The GTID assigned to the last commit. If no GTID was assigned to any commit
4625     so far, this is indicated by last_commit_gtid.seq_no == 0.
4626   */
4627 private:
4628   rpl_gtid m_last_commit_gtid;
4629 
4630 public:
get_last_commit_gtid()4631   rpl_gtid get_last_commit_gtid() { return m_last_commit_gtid; }
4632   void set_last_commit_gtid(rpl_gtid &gtid);
4633 
4634 
4635   LF_PINS *tdc_hash_pins;
4636   LF_PINS *xid_hash_pins;
4637   bool fix_xid_hash_pins();
4638 
4639 /* Members related to temporary tables. */
4640 public:
4641   /* Opened table states. */
4642   enum Temporary_table_state {
4643     TMP_TABLE_IN_USE,
4644     TMP_TABLE_NOT_IN_USE,
4645     TMP_TABLE_ANY
4646   };
4647   bool has_thd_temporary_tables();
4648 
4649   TABLE *create_and_open_tmp_table(handlerton *hton,
4650                                    LEX_CUSTRING *frm,
4651                                    const char *path,
4652                                    const char *db,
4653                                    const char *table_name,
4654                                    bool open_in_engine,
4655                                    bool open_internal_tables);
4656 
4657   TABLE *find_temporary_table(const char *db, const char *table_name,
4658                               Temporary_table_state state= TMP_TABLE_IN_USE);
4659   TABLE *find_temporary_table(const TABLE_LIST *tl,
4660                               Temporary_table_state state= TMP_TABLE_IN_USE);
4661 
4662   TMP_TABLE_SHARE *find_tmp_table_share_w_base_key(const char *key,
4663                                                    uint key_length);
4664   TMP_TABLE_SHARE *find_tmp_table_share(const char *db,
4665                                         const char *table_name);
4666   TMP_TABLE_SHARE *find_tmp_table_share(const TABLE_LIST *tl);
4667   TMP_TABLE_SHARE *find_tmp_table_share(const char *key, size_t key_length);
4668 
4669   bool open_temporary_table(TABLE_LIST *tl);
4670   bool open_temporary_tables(TABLE_LIST *tl);
4671 
4672   bool close_temporary_tables();
4673   bool rename_temporary_table(TABLE *table, const LEX_CSTRING *db,
4674                               const LEX_CSTRING *table_name);
4675   bool drop_temporary_table(TABLE *table, bool *is_trans, bool delete_table);
4676   bool rm_temporary_table(handlerton *hton, const char *path);
4677   void mark_tmp_tables_as_free_for_reuse();
4678   void mark_tmp_table_as_free_for_reuse(TABLE *table);
4679 
4680   TMP_TABLE_SHARE* save_tmp_table_share(TABLE *table);
4681   void restore_tmp_table_share(TMP_TABLE_SHARE *share);
4682   void close_unused_temporary_table_instances(const TABLE_LIST *tl);
4683 
4684 private:
4685   /* Whether a lock has been acquired? */
4686   bool m_tmp_tables_locked;
4687 
4688   bool has_temporary_tables();
4689   uint create_tmp_table_def_key(char *key, const char *db,
4690                                 const char *table_name);
4691   TMP_TABLE_SHARE *create_temporary_table(handlerton *hton, LEX_CUSTRING *frm,
4692                                           const char *path, const char *db,
4693                                           const char *table_name);
4694   TABLE *find_temporary_table(const char *key, uint key_length,
4695                               Temporary_table_state state);
4696   TABLE *open_temporary_table(TMP_TABLE_SHARE *share, const char *alias,
4697                               bool open_in_engine);
4698   bool find_and_use_tmp_table(const TABLE_LIST *tl, TABLE **out_table);
4699   bool use_temporary_table(TABLE *table, TABLE **out_table);
4700   void close_temporary_table(TABLE *table);
4701   bool log_events_and_free_tmp_shares();
4702   void free_tmp_table_share(TMP_TABLE_SHARE *share, bool delete_table);
4703   void free_temporary_table(TABLE *table);
4704   bool lock_temporary_tables();
4705   void unlock_temporary_tables();
4706 
tmpkeyval(TMP_TABLE_SHARE * share)4707   inline uint tmpkeyval(TMP_TABLE_SHARE *share)
4708   {
4709     return uint4korr(share->table_cache_key.str +
4710                      share->table_cache_key.length - 4);
4711   }
4712 
tmp_table_share(TABLE * table)4713   inline TMP_TABLE_SHARE *tmp_table_share(TABLE *table)
4714   {
4715     DBUG_ASSERT(table->s->tmp_table);
4716     return static_cast<TMP_TABLE_SHARE *>(table->s);
4717   }
4718 
4719 public:
wsrep_binlog_format()4720   inline ulong wsrep_binlog_format() const
4721   {
4722     return WSREP_FORMAT(variables.binlog_format);
4723   }
4724 
4725 #ifdef WITH_WSREP
4726   const bool                wsrep_applier; /* dedicated slave applier thread */
4727   bool                      wsrep_applier_closing; /* applier marked to close */
4728   bool                      wsrep_client_thread; /* to identify client threads*/
4729   bool                      wsrep_PA_safe;
4730   bool                      wsrep_converted_lock_session;
4731   bool                      wsrep_apply_toi; /* applier processing in TOI */
4732   enum wsrep_exec_mode      wsrep_exec_mode;
4733   query_id_t                wsrep_last_query_id;
4734   enum wsrep_query_state    wsrep_query_state;
4735   enum wsrep_conflict_state wsrep_conflict_state;
4736   wsrep_trx_meta_t          wsrep_trx_meta;
4737   uint32                    wsrep_rand;
4738   Relay_log_info            *wsrep_rli;
4739   rpl_group_info            *wsrep_rgi;
4740   wsrep_ws_handle_t         wsrep_ws_handle;
4741   ulong                     wsrep_retry_counter; // of autocommit
4742   char                      *wsrep_retry_query;
4743   size_t                    wsrep_retry_query_len;
4744   enum enum_server_command  wsrep_retry_command;
4745   enum wsrep_consistency_check_mode
4746                             wsrep_consistency_check;
4747   int                       wsrep_mysql_replicated;
4748   const char                *wsrep_TOI_pre_query; /* a query to apply before
4749                                                      the actual TOI query */
4750   size_t                    wsrep_TOI_pre_query_len;
4751   wsrep_po_handle_t         wsrep_po_handle;
4752   size_t                    wsrep_po_cnt;
4753 #ifdef GTID_SUPPORT
4754   rpl_sid                   wsrep_po_sid;
4755 #endif /*  GTID_SUPPORT */
4756   void                      *wsrep_apply_format;
4757   char                      wsrep_info[128]; /* string for dynamic proc info */
4758   /*
4759     When enabled, do not replicate/binlog updates from the current table that's
4760     being processed. At the moment, it is used to keep mysql.gtid_slave_pos
4761     table updates from being replicated to other nodes via galera replication.
4762   */
4763   bool                      wsrep_ignore_table;
4764   wsrep_gtid_t              wsrep_sync_wait_gtid;
4765   ulong                     wsrep_affected_rows;
4766   bool                      wsrep_replicate_GTID;
4767   bool                      wsrep_skip_wsrep_GTID;
4768   /* This flag is set when innodb do an intermediate commit to
4769   processing the LOAD DATA INFILE statement by splitting it into 10K
4770   rows chunks. If flag is set, then binlog rotation is not performed
4771   while intermediate transaction try to commit, because in this case
4772   rotation causes unregistration of innodb handler. Later innodb handler
4773   registered again, but replication of last chunk of rows is skipped
4774   by the innodb engine: */
4775   bool                      wsrep_split_flag;
4776 #endif /* WITH_WSREP */
4777 
4778   /* Handling of timeouts for commands */
4779   thr_timer_t query_timer;
4780 
4781 public:
set_query_timer()4782   void set_query_timer()
4783   {
4784 #ifndef EMBEDDED_LIBRARY
4785     /*
4786       Don't start a query timer if
4787       - If timeouts are not set
4788       - if we are in a stored procedure or sub statement
4789       - If this is a slave thread
4790       - If we already have set a timeout (happens when running prepared
4791         statements that calls mysql_execute_command())
4792     */
4793     if (!variables.max_statement_time || spcont  || in_sub_stmt ||
4794         slave_thread || query_timer.expired == 0)
4795       return;
4796     thr_timer_settime(&query_timer, variables.max_statement_time);
4797 #endif
4798   }
reset_query_timer()4799   void reset_query_timer()
4800   {
4801 #ifndef EMBEDDED_LIBRARY
4802     if (spcont || in_sub_stmt || slave_thread)
4803       return;
4804     if (!query_timer.expired)
4805       thr_timer_end(&query_timer);
4806 #endif
4807   }
restore_set_statement_var()4808   void restore_set_statement_var()
4809   {
4810     main_lex.restore_set_statement_var();
4811   }
4812   /* Copy relevant `stmt` transaction flags to `all` transaction. */
merge_unsafe_rollback_flags()4813   void merge_unsafe_rollback_flags()
4814   {
4815     if (transaction.stmt.modified_non_trans_table)
4816       transaction.all.modified_non_trans_table= TRUE;
4817     transaction.all.m_unsafe_rollback_flags|=
4818       (transaction.stmt.m_unsafe_rollback_flags &
4819        (THD_TRANS::MODIFIED_NON_TRANS_TABLE |
4820         THD_TRANS::DID_WAIT | THD_TRANS::CREATED_TEMP_TABLE |
4821         THD_TRANS::DROPPED_TEMP_TABLE | THD_TRANS::DID_DDL |
4822         THD_TRANS::EXECUTED_TABLE_ADMIN_CMD));
4823   }
4824   /*
4825     Reset current_linfo
4826     Setting current_linfo to 0 needs to be done with LOCK_thread_count to
4827     ensure that adjust_linfo_offsets doesn't use a structure that may
4828     be deleted.
4829   */
reset_current_linfo()4830   inline void reset_current_linfo()
4831   {
4832     mysql_mutex_lock(&LOCK_thread_count);
4833     current_linfo= 0;
4834     mysql_mutex_unlock(&LOCK_thread_count);
4835   }
4836 
4837   bool sql_parser(LEX *old_lex, LEX *lex,
4838                   char *str, uint str_len, bool stmt_prepare_mode);
4839 
4840 
get_net_wait_timeout()4841   uint get_net_wait_timeout()
4842   {
4843     if (in_active_multi_stmt_transaction())
4844     {
4845       if (transaction.all.is_trx_read_write())
4846       {
4847         if (variables.idle_write_transaction_timeout > 0)
4848           return variables.idle_write_transaction_timeout;
4849       }
4850       else
4851       {
4852         if (variables.idle_readonly_transaction_timeout > 0)
4853           return variables.idle_readonly_transaction_timeout;
4854       }
4855 
4856       if (variables.idle_transaction_timeout > 0)
4857         return variables.idle_transaction_timeout;
4858     }
4859 
4860     return variables.net_wait_timeout;
4861   }
4862 
4863   /**
4864     Switch to a sublex, to parse a substatement or an expression.
4865   */
set_local_lex(sp_lex_local * sublex)4866   void set_local_lex(sp_lex_local *sublex)
4867   {
4868     DBUG_ASSERT(lex->sphead);
4869     lex= sublex;
4870     /* Reset part of parser state which needs this. */
4871     m_parser_state->m_yacc.reset_before_substatement();
4872   }
4873 
4874   /**
4875     Switch back from a sublex (currently pointed by this->lex) to the old lex.
4876     Sublex is merged to "oldlex" and this->lex is set to "oldlex".
4877 
4878     This method is called after parsing a substatement or an expression.
4879     set_local_lex() must be previously called.
4880     @param oldlex - The old lex which was active before set_local_lex().
4881     @returns      - false on success, true on error (failed to merge LEX's).
4882 
4883     See also sp_head::merge_lex().
4884   */
4885   bool restore_from_local_lex_to_old_lex(LEX *oldlex);
4886 
4887   Item *sp_fix_func_item(Item **it_addr);
4888   Item *sp_prepare_func_item(Item **it_addr, uint cols= 1);
4889   bool sp_eval_expr(Field *result_field, Item **expr_item_ptr);
4890 };
4891 
add_to_active_threads(THD * thd)4892 inline void add_to_active_threads(THD *thd)
4893 {
4894   mysql_mutex_lock(&LOCK_thread_count);
4895   threads.append(thd);
4896   mysql_mutex_unlock(&LOCK_thread_count);
4897 }
4898 
4899 /*
4900   This should be called when you want to delete a thd that was not
4901   running any queries.
4902 */
4903 
unlink_not_visible_thd(THD * thd)4904 inline void unlink_not_visible_thd(THD *thd)
4905 {
4906   mysql_mutex_lock(&LOCK_thread_count);
4907   thd->unlink();
4908   mysql_mutex_unlock(&LOCK_thread_count);
4909 }
4910 
4911 /** A short cut for thd->get_stmt_da()->set_ok_status(). */
4912 
4913 inline void
4914 my_ok(THD *thd, ulonglong affected_rows_arg= 0, ulonglong id= 0,
4915         const char *message= NULL)
4916 {
4917   thd->set_row_count_func(affected_rows_arg);
4918   thd->set_affected_rows(affected_rows_arg);
4919   thd->get_stmt_da()->set_ok_status(affected_rows_arg, id, message);
4920 }
4921 
4922 
4923 /** A short cut for thd->get_stmt_da()->set_eof_status(). */
4924 
4925 inline void
my_eof(THD * thd)4926 my_eof(THD *thd)
4927 {
4928   thd->set_row_count_func(-1);
4929   thd->get_stmt_da()->set_eof_status(thd);
4930 
4931   TRANSACT_TRACKER(add_trx_state(thd, TX_RESULT_SET));
4932 }
4933 
4934 #define tmp_disable_binlog(A)                                              \
4935   {ulonglong tmp_disable_binlog__save_options= (A)->variables.option_bits; \
4936   (A)->variables.option_bits&= ~OPTION_BIN_LOG;                            \
4937   (A)->variables.sql_log_bin_off= 1;
4938 
4939 #define reenable_binlog(A)                                                  \
4940   (A)->variables.option_bits= tmp_disable_binlog__save_options;             \
4941   (A)->variables.sql_log_bin_off= 0;}
4942 
4943 
sql_mode_for_dates(THD * thd)4944 inline sql_mode_t sql_mode_for_dates(THD *thd)
4945 {
4946   return thd->variables.sql_mode &
4947           (MODE_NO_ZERO_DATE | MODE_NO_ZERO_IN_DATE | MODE_INVALID_DATES);
4948 }
4949 
4950 /*
4951   Used to hold information about file and file structure in exchange
4952   via non-DB file (...INTO OUTFILE..., ...LOAD DATA...)
4953   XXX: We never call destructor for objects of this class.
4954 */
4955 
4956 class sql_exchange :public Sql_alloc
4957 {
4958 public:
4959   enum enum_filetype filetype; /* load XML, Added by Arnold & Erik */
4960   const char *file_name;
4961   String *field_term,*enclosed,*line_term,*line_start,*escaped;
4962   bool opt_enclosed;
4963   bool dumpfile;
4964   ulong skip_lines;
4965   CHARSET_INFO *cs;
4966   sql_exchange(const char *name, bool dumpfile_flag,
4967                enum_filetype filetype_arg= FILETYPE_CSV);
4968   bool escaped_given(void) const;
4969 };
4970 
4971 /*
4972   This is used to get result from a select
4973 */
4974 
4975 class JOIN;
4976 
4977 /* Pure interface for sending tabular data */
4978 class select_result_sink: public Sql_alloc
4979 {
4980 public:
4981   THD *thd;
select_result_sink(THD * thd_arg)4982   select_result_sink(THD *thd_arg): thd(thd_arg) {}
4983   /*
4984     send_data returns 0 on ok, 1 on error and -1 if data was ignored, for
4985     example for a duplicate row entry written to a temp table.
4986   */
4987   virtual int send_data(List<Item> &items)=0;
~select_result_sink()4988   virtual ~select_result_sink() {};
reset(THD * thd_arg)4989   void reset(THD *thd_arg) { thd= thd_arg; }
4990 };
4991 
4992 class select_result_interceptor;
4993 
4994 /*
4995   Interface for sending tabular data, together with some other stuff:
4996 
4997   - Primary purpose seems to be seding typed tabular data:
4998      = the DDL is sent with send_fields()
4999      = the rows are sent with send_data()
5000   Besides that,
5001   - there seems to be an assumption that the sent data is a result of
5002     SELECT_LEX_UNIT *unit,
5003   - nest_level is used by SQL parser
5004 */
5005 
5006 class select_result :public select_result_sink
5007 {
5008 protected:
5009   /*
5010     All descendant classes have their send_data() skip the first
5011     unit->offset_limit_cnt rows sent.  Select_materialize
5012     also uses unit->get_column_types().
5013   */
5014   SELECT_LEX_UNIT *unit;
5015   /* Something used only by the parser: */
5016 public:
5017   ha_rows est_records;  /* estimated number of records in the result */
select_result(THD * thd_arg)5018  select_result(THD *thd_arg): select_result_sink(thd_arg), est_records(0) {}
set_unit(SELECT_LEX_UNIT * unit_arg)5019   void set_unit(SELECT_LEX_UNIT *unit_arg) { unit= unit_arg; }
~select_result()5020   virtual ~select_result() {};
5021   /**
5022     Change wrapped select_result.
5023 
5024     Replace the wrapped result object with new_result and call
5025     prepare() and prepare2() on new_result.
5026 
5027     This base class implementation doesn't wrap other select_results.
5028 
5029     @param new_result The new result object to wrap around
5030 
5031     @retval false Success
5032     @retval true  Error
5033   */
change_result(select_result * new_result)5034   virtual bool change_result(select_result *new_result)
5035   {
5036     return false;
5037   }
prepare(List<Item> & list,SELECT_LEX_UNIT * u)5038   virtual int prepare(List<Item> &list, SELECT_LEX_UNIT *u)
5039   {
5040     unit= u;
5041     return 0;
5042   }
prepare2(JOIN * join)5043   virtual int prepare2(JOIN *join) { return 0; }
5044   /*
5045     Because of peculiarities of prepared statements protocol
5046     we need to know number of columns in the result set (if
5047     there is a result set) apart from sending columns metadata.
5048   */
field_count(List<Item> & fields)5049   virtual uint field_count(List<Item> &fields) const
5050   { return fields.elements; }
5051   virtual bool send_result_set_metadata(List<Item> &list, uint flags)=0;
initialize_tables(JOIN * join)5052   virtual bool initialize_tables (JOIN *join) { return 0; }
5053   virtual bool send_eof()=0;
5054   /**
5055     Check if this query returns a result set and therefore is allowed in
5056     cursors and set an error message if it is not the case.
5057 
5058     @retval FALSE     success
5059     @retval TRUE      error, an error message is set
5060   */
5061   virtual bool check_simple_select() const;
abort_result_set()5062   virtual void abort_result_set() {}
5063   /*
5064     Cleanup instance of this class for next execution of a prepared
5065     statement/stored procedure.
5066   */
5067   virtual void cleanup();
set_thd(THD * thd_arg)5068   void set_thd(THD *thd_arg) { thd= thd_arg; }
reset(THD * thd_arg)5069   void reset(THD *thd_arg)
5070   {
5071     select_result_sink::reset(thd_arg);
5072     unit= NULL;
5073   }
5074 #ifdef EMBEDDED_LIBRARY
begin_dataset()5075   virtual void begin_dataset() {}
5076 #else
begin_dataset()5077   void begin_dataset() {}
5078 #endif
update_used_tables()5079   virtual void update_used_tables() {}
5080 
5081   /* this method is called just before the first row of the table can be read */
prepare_to_read_rows()5082   virtual void prepare_to_read_rows() {}
5083 
reset_offset_limit()5084   void reset_offset_limit()
5085   {
5086     unit->offset_limit_cnt= 0;
5087   }
5088 
5089   /*
5090     This returns
5091     - NULL if the class sends output row to the client
5092     - this if the output is set elsewhere (a file, @variable, or table).
5093   */
5094   virtual select_result_interceptor *result_interceptor()=0;
5095 
5096   /*
5097     This method is used to distinguish an normal SELECT from the cursor
5098     structure discovery for cursor%ROWTYPE routine variables.
5099     If this method returns "true", then a SELECT execution performs only
5100     all preparation stages, but does not fetch any rows.
5101   */
view_structure_only()5102   virtual bool view_structure_only() const { return false; }
5103 };
5104 
5105 
5106 /*
5107   This is a select_result_sink which simply writes all data into a (temporary)
5108   table. Creation/deletion of the table is outside of the scope of the class
5109 
5110   It is aimed at capturing SHOW EXPLAIN output, so:
5111   - Unlike select_result class, we don't assume that the sent data is an
5112     output of a SELECT_LEX_UNIT (and so we dont apply "LIMIT x,y" from the
5113     unit)
5114   - We don't try to convert the target table to MyISAM
5115 */
5116 
5117 class select_result_explain_buffer : public select_result_sink
5118 {
5119 public:
select_result_explain_buffer(THD * thd_arg,TABLE * table_arg)5120   select_result_explain_buffer(THD *thd_arg, TABLE *table_arg) :
5121     select_result_sink(thd_arg), dst_table(table_arg) {};
5122 
5123   TABLE *dst_table; /* table to write into */
5124 
5125   /* The following is called in the child thread: */
5126   int send_data(List<Item> &items);
5127 };
5128 
5129 
5130 /*
5131   This is a select_result_sink which stores the data in text form.
5132 
5133   It is only used to save EXPLAIN output.
5134 */
5135 
5136 class select_result_text_buffer : public select_result_sink
5137 {
5138 public:
select_result_text_buffer(THD * thd_arg)5139   select_result_text_buffer(THD *thd_arg): select_result_sink(thd_arg) {}
5140   int send_data(List<Item> &items);
5141   bool send_result_set_metadata(List<Item> &fields, uint flag);
5142 
5143   void save_to(String *res);
5144 private:
5145   int append_row(List<Item> &items, bool send_names);
5146 
5147   List<char*> rows;
5148   int n_columns;
5149 };
5150 
5151 
5152 /*
5153   Base class for select_result descendands which intercept and
5154   transform result set rows. As the rows are not sent to the client,
5155   sending of result set metadata should be suppressed as well.
5156 */
5157 
5158 class select_result_interceptor: public select_result
5159 {
5160 public:
select_result_interceptor(THD * thd_arg)5161   select_result_interceptor(THD *thd_arg):
5162     select_result(thd_arg), suppress_my_ok(false)
5163   {
5164     DBUG_ENTER("select_result_interceptor::select_result_interceptor");
5165     DBUG_PRINT("enter", ("this %p", this));
5166     DBUG_VOID_RETURN;
5167   }              /* Remove gcc warning */
field_count(List<Item> & fields)5168   uint field_count(List<Item> &fields) const { return 0; }
send_result_set_metadata(List<Item> & fields,uint flag)5169   bool send_result_set_metadata(List<Item> &fields, uint flag) { return FALSE; }
result_interceptor()5170   select_result_interceptor *result_interceptor() { return this; }
5171 
5172   /*
5173     Instruct the object to not call my_ok(). Client output will be handled
5174     elsewhere. (this is used by ANALYZE $stmt feature).
5175   */
disable_my_ok_calls()5176   void disable_my_ok_calls() { suppress_my_ok= true; }
reset(THD * thd_arg)5177   void reset(THD *thd_arg)
5178   {
5179     select_result::reset(thd_arg);
5180     suppress_my_ok= false;
5181   }
5182 protected:
5183   bool suppress_my_ok;
5184 };
5185 
5186 
5187 class sp_cursor_statistics
5188 {
5189 protected:
5190   ulonglong m_fetch_count; // Number of FETCH commands since last OPEN
5191   ulonglong m_row_count;   // Number of successful FETCH since last OPEN
5192   bool m_found;            // If last FETCH fetched a row
5193 public:
sp_cursor_statistics()5194   sp_cursor_statistics()
5195    :m_fetch_count(0),
5196     m_row_count(0),
5197     m_found(false)
5198   { }
found()5199   bool found() const
5200   { return m_found; }
5201 
row_count()5202   ulonglong row_count() const
5203   { return m_row_count; }
5204 
fetch_count()5205   ulonglong fetch_count() const
5206   { return m_fetch_count; }
reset()5207   void reset() { *this= sp_cursor_statistics(); }
5208 };
5209 
5210 
5211 /* A mediator between stored procedures and server side cursors */
5212 class sp_lex_keeper;
5213 class sp_cursor: public sp_cursor_statistics
5214 {
5215 private:
5216   /// An interceptor of cursor result set used to implement
5217   /// FETCH <cname> INTO <varlist>.
5218   class Select_fetch_into_spvars: public select_result_interceptor
5219   {
5220     List<sp_variable> *spvar_list;
5221     uint field_count;
5222     bool m_view_structure_only;
5223     bool send_data_to_variable_list(List<sp_variable> &vars, List<Item> &items);
5224   public:
Select_fetch_into_spvars(THD * thd_arg,bool view_structure_only)5225     Select_fetch_into_spvars(THD *thd_arg, bool view_structure_only)
5226      :select_result_interceptor(thd_arg),
5227       m_view_structure_only(view_structure_only)
5228     {}
reset(THD * thd_arg)5229     void reset(THD *thd_arg)
5230     {
5231       select_result_interceptor::reset(thd_arg);
5232       spvar_list= NULL;
5233       field_count= 0;
5234     }
get_field_count()5235     uint get_field_count() { return field_count; }
set_spvar_list(List<sp_variable> * vars)5236     void set_spvar_list(List<sp_variable> *vars) { spvar_list= vars; }
5237 
send_eof()5238     virtual bool send_eof() { return FALSE; }
5239     virtual int send_data(List<Item> &items);
5240     virtual int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
view_structure_only()5241     virtual bool view_structure_only() const { return m_view_structure_only; }
5242 };
5243 
5244 public:
sp_cursor()5245   sp_cursor()
5246    :result(NULL, false),
5247     m_lex_keeper(NULL),
5248     server_side_cursor(NULL)
5249   { }
sp_cursor(THD * thd_arg,sp_lex_keeper * lex_keeper,bool view_structure_only)5250   sp_cursor(THD *thd_arg, sp_lex_keeper *lex_keeper, bool view_structure_only)
5251    :result(thd_arg, view_structure_only),
5252     m_lex_keeper(lex_keeper),
5253     server_side_cursor(NULL)
5254   {}
5255 
~sp_cursor()5256   virtual ~sp_cursor()
5257   { destroy(); }
5258 
get_lex_keeper()5259   sp_lex_keeper *get_lex_keeper() { return m_lex_keeper; }
5260 
5261   int open(THD *thd);
5262 
5263   int close(THD *thd);
5264 
is_open()5265   my_bool is_open()
5266   { return MY_TEST(server_side_cursor); }
5267 
5268   int fetch(THD *, List<sp_variable> *vars, bool error_on_no_data);
5269 
5270   bool export_structure(THD *thd, Row_definition_list *list);
5271 
reset(THD * thd_arg,sp_lex_keeper * lex_keeper)5272   void reset(THD *thd_arg, sp_lex_keeper *lex_keeper)
5273   {
5274     sp_cursor_statistics::reset();
5275     result.reset(thd_arg);
5276     m_lex_keeper= lex_keeper;
5277     server_side_cursor= NULL;
5278   }
5279 
5280 private:
5281   Select_fetch_into_spvars result;
5282   sp_lex_keeper *m_lex_keeper;
5283   Server_side_cursor *server_side_cursor;
5284   void destroy();
5285 };
5286 
5287 
5288 class select_send :public select_result {
5289   /**
5290     True if we have sent result set metadata to the client.
5291     In this case the client always expects us to end the result
5292     set with an eof or error packet
5293   */
5294   bool is_result_set_started;
5295 public:
select_send(THD * thd_arg)5296   select_send(THD *thd_arg):
5297     select_result(thd_arg), is_result_set_started(FALSE) {}
5298   bool send_result_set_metadata(List<Item> &list, uint flags);
5299   int send_data(List<Item> &items);
5300   bool send_eof();
check_simple_select()5301   virtual bool check_simple_select() const { return FALSE; }
5302   void abort_result_set();
5303   virtual void cleanup();
result_interceptor()5304   select_result_interceptor *result_interceptor() { return NULL; }
5305 };
5306 
5307 
5308 /*
5309   We need this class, because select_send::send_eof() will call ::my_eof.
5310 
5311   See also class Protocol_discard.
5312 */
5313 
5314 class select_send_analyze : public select_send
5315 {
send_result_set_metadata(List<Item> & list,uint flags)5316   bool send_result_set_metadata(List<Item> &list, uint flags) { return 0; }
send_eof()5317   bool send_eof() { return 0; }
abort_result_set()5318   void abort_result_set() {}
5319 public:
select_send_analyze(THD * thd_arg)5320   select_send_analyze(THD *thd_arg): select_send(thd_arg) {}
5321 };
5322 
5323 
5324 class select_to_file :public select_result_interceptor {
5325 protected:
5326   sql_exchange *exchange;
5327   File file;
5328   IO_CACHE cache;
5329   ha_rows row_count;
5330   char path[FN_REFLEN];
5331 
5332 public:
select_to_file(THD * thd_arg,sql_exchange * ex)5333   select_to_file(THD *thd_arg, sql_exchange *ex):
5334     select_result_interceptor(thd_arg), exchange(ex), file(-1),row_count(0L)
5335   { path[0]=0; }
5336   ~select_to_file();
5337   bool send_eof();
5338   void cleanup();
5339 };
5340 
5341 
5342 #define ESCAPE_CHARS "ntrb0ZN" // keep synchronous with READ_INFO::unescape
5343 
5344 
5345 /*
5346  List of all possible characters of a numeric value text representation.
5347 */
5348 #define NUMERIC_CHARS ".0123456789e+-"
5349 
5350 
5351 class select_export :public select_to_file {
5352   uint field_term_length;
5353   int field_sep_char,escape_char,line_sep_char;
5354   int field_term_char; // first char of FIELDS TERMINATED BY or MAX_INT
5355   /*
5356     The is_ambiguous_field_sep field is true if a value of the field_sep_char
5357     field is one of the 'n', 't', 'r' etc characters
5358     (see the READ_INFO::unescape method and the ESCAPE_CHARS constant value).
5359   */
5360   bool is_ambiguous_field_sep;
5361   /*
5362      The is_ambiguous_field_term is true if field_sep_char contains the first
5363      char of the FIELDS TERMINATED BY (ENCLOSED BY is empty), and items can
5364      contain this character.
5365   */
5366   bool is_ambiguous_field_term;
5367   /*
5368     The is_unsafe_field_sep field is true if a value of the field_sep_char
5369     field is one of the '0'..'9', '+', '-', '.' and 'e' characters
5370     (see the NUMERIC_CHARS constant value).
5371   */
5372   bool is_unsafe_field_sep;
5373   bool fixed_row_size;
5374   CHARSET_INFO *write_cs; // output charset
5375 public:
select_export(THD * thd_arg,sql_exchange * ex)5376   select_export(THD *thd_arg, sql_exchange *ex): select_to_file(thd_arg, ex) {}
5377   ~select_export();
5378   int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
5379   int send_data(List<Item> &items);
5380 };
5381 
5382 
5383 class select_dump :public select_to_file {
5384 public:
select_dump(THD * thd_arg,sql_exchange * ex)5385   select_dump(THD *thd_arg, sql_exchange *ex): select_to_file(thd_arg, ex) {}
5386   int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
5387   int send_data(List<Item> &items);
5388 };
5389 
5390 
5391 class select_insert :public select_result_interceptor {
5392  public:
5393   TABLE_LIST *table_list;
5394   TABLE *table;
5395   List<Item> *fields;
5396   ulonglong autoinc_value_of_last_inserted_row; // autogenerated or not
5397   COPY_INFO info;
5398   bool insert_into_view;
5399   select_insert(THD *thd_arg, TABLE_LIST *table_list_par,
5400 		TABLE *table_par, List<Item> *fields_par,
5401 		List<Item> *update_fields, List<Item> *update_values,
5402 		enum_duplicates duplic, bool ignore);
5403   ~select_insert();
5404   int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
5405   virtual int prepare2(JOIN *join);
5406   virtual int send_data(List<Item> &items);
5407   virtual void store_values(List<Item> &values);
can_rollback_data()5408   virtual bool can_rollback_data() { return 0; }
5409   bool prepare_eof();
5410   bool send_ok_packet();
5411   bool send_eof();
5412   virtual void abort_result_set();
5413   /* not implemented: select_insert is never re-used in prepared statements */
5414   void cleanup();
5415 };
5416 
5417 
5418 class select_create: public select_insert {
5419   TABLE_LIST *create_table;
5420   Table_specification_st *create_info;
5421   TABLE_LIST *select_tables;
5422   Alter_info *alter_info;
5423   Field **field;
5424   /* lock data for tmp table */
5425   MYSQL_LOCK *m_lock;
5426   /* m_lock or thd->extra_lock */
5427   MYSQL_LOCK **m_plock;
5428   bool       exit_done;
5429   TMP_TABLE_SHARE *saved_tmp_table_share;
5430 
5431 public:
select_create(THD * thd_arg,TABLE_LIST * table_arg,Table_specification_st * create_info_par,Alter_info * alter_info_arg,List<Item> & select_fields,enum_duplicates duplic,bool ignore,TABLE_LIST * select_tables_arg)5432   select_create(THD *thd_arg, TABLE_LIST *table_arg,
5433                 Table_specification_st *create_info_par,
5434                 Alter_info *alter_info_arg,
5435                 List<Item> &select_fields,enum_duplicates duplic, bool ignore,
5436                 TABLE_LIST *select_tables_arg):
5437     select_insert(thd_arg, table_arg, NULL, &select_fields, 0, 0, duplic,
5438                   ignore),
5439     create_table(table_arg),
5440     create_info(create_info_par),
5441     select_tables(select_tables_arg),
5442     alter_info(alter_info_arg),
5443     m_plock(NULL), exit_done(0),
5444     saved_tmp_table_share(0)
5445     {}
5446   int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
5447 
5448   int binlog_show_create_table(TABLE **tables, uint count);
5449   void store_values(List<Item> &values);
5450   bool send_eof();
5451   virtual void abort_result_set();
can_rollback_data()5452   virtual bool can_rollback_data() { return 1; }
5453 
5454   // Needed for access from local class MY_HOOKS in prepare(), since thd is proteted.
get_thd(void)5455   const THD *get_thd(void) { return thd; }
get_create_info()5456   const HA_CREATE_INFO *get_create_info() { return create_info; };
prepare2(JOIN * join)5457   int prepare2(JOIN *join) { return 0; }
5458 
5459 private:
5460   TABLE *create_table_from_items(THD *thd,
5461                                   List<Item> *items,
5462                                   MYSQL_LOCK **lock,
5463                                   TABLEOP_HOOKS *hooks);
5464 };
5465 
5466 #include <myisam.h>
5467 
5468 #ifdef WITH_ARIA_STORAGE_ENGINE
5469 #include <maria.h>
5470 #else
5471 #undef USE_ARIA_FOR_TMP_TABLES
5472 #endif
5473 
5474 #ifdef USE_ARIA_FOR_TMP_TABLES
5475 #define TMP_ENGINE_COLUMNDEF MARIA_COLUMNDEF
5476 #define TMP_ENGINE_HTON maria_hton
5477 #define TMP_ENGINE_NAME "Aria"
tmp_table_max_key_length()5478 inline uint tmp_table_max_key_length() { return maria_max_key_length(); }
tmp_table_max_key_parts()5479 inline uint tmp_table_max_key_parts() { return maria_max_key_segments(); }
5480 #else
5481 #define TMP_ENGINE_COLUMNDEF MI_COLUMNDEF
5482 #define TMP_ENGINE_HTON myisam_hton
5483 #define TMP_ENGINE_NAME "MyISAM"
tmp_table_max_key_length()5484 inline uint tmp_table_max_key_length() { return MI_MAX_KEY_LENGTH; }
tmp_table_max_key_parts()5485 inline uint tmp_table_max_key_parts() { return MI_MAX_KEY_SEG; }
5486 #endif
5487 
5488 /*
5489   Param to create temporary tables when doing SELECT:s
5490   NOTE
5491     This structure is copied using memcpy as a part of JOIN.
5492 */
5493 
5494 class TMP_TABLE_PARAM :public Sql_alloc
5495 {
5496 public:
5497   List<Item> copy_funcs;
5498   Copy_field *copy_field, *copy_field_end;
5499   uchar	    *group_buff;
5500   Item	    **items_to_copy;			/* Fields in tmp table */
5501   TMP_ENGINE_COLUMNDEF *recinfo, *start_recinfo;
5502   KEY *keyinfo;
5503   ha_rows end_write_records;
5504   /**
5505     Number of normal fields in the query, including those referred to
5506     from aggregate functions. Hence, "SELECT `field1`,
5507     SUM(`field2`) from t1" sets this counter to 2.
5508 
5509     @see count_field_types
5510   */
5511   uint	field_count;
5512   /**
5513     Number of fields in the query that have functions. Includes both
5514     aggregate functions (e.g., SUM) and non-aggregates (e.g., RAND).
5515     Also counts functions referred to from aggregate functions, i.e.,
5516     "SELECT SUM(RAND())" sets this counter to 2.
5517 
5518     @see count_field_types
5519   */
5520   uint  func_count;
5521   /**
5522     Number of fields in the query that have aggregate functions. Note
5523     that the optimizer may choose to optimize away these fields by
5524     replacing them with constants, in which case sum_func_count will
5525     need to be updated.
5526 
5527     @see opt_sum_query, count_field_types
5528   */
5529   uint  sum_func_count;
5530   uint  hidden_field_count;
5531   uint	group_parts,group_length,group_null_parts;
5532   uint	quick_group;
5533   /**
5534     Enabled when we have atleast one outer_sum_func. Needed when used
5535     along with distinct.
5536 
5537     @see create_tmp_table
5538   */
5539   bool  using_outer_summary_function;
5540   CHARSET_INFO *table_charset;
5541   bool schema_table;
5542   /* TRUE if the temp table is created for subquery materialization. */
5543   bool materialized_subquery;
5544   /* TRUE if all columns of the table are guaranteed to be non-nullable */
5545   bool force_not_null_cols;
5546   /*
5547     True if GROUP BY and its aggregate functions are already computed
5548     by a table access method (e.g. by loose index scan). In this case
5549     query execution should not perform aggregation and should treat
5550     aggregate functions as normal functions.
5551   */
5552   bool precomputed_group_by;
5553   bool force_copy_fields;
5554   /*
5555     If TRUE, create_tmp_field called from create_tmp_table will convert
5556     all BIT fields to 64-bit longs. This is a workaround the limitation
5557     that MEMORY tables cannot index BIT columns.
5558   */
5559   bool bit_fields_as_long;
5560   /*
5561     Whether to create or postpone actual creation of this temporary table.
5562     TRUE <=> create_tmp_table will create only the TABLE structure.
5563   */
5564   bool skip_create_table;
5565 
TMP_TABLE_PARAM()5566   TMP_TABLE_PARAM()
5567     :copy_field(0), group_parts(0),
5568      group_length(0), group_null_parts(0),
5569      using_outer_summary_function(0),
5570      schema_table(0), materialized_subquery(0), force_not_null_cols(0),
5571      precomputed_group_by(0),
5572      force_copy_fields(0), bit_fields_as_long(0), skip_create_table(0)
5573   {}
~TMP_TABLE_PARAM()5574   ~TMP_TABLE_PARAM()
5575   {
5576     cleanup();
5577   }
5578   void init(void);
cleanup(void)5579   inline void cleanup(void)
5580   {
5581     if (copy_field)				/* Fix for Intel compiler */
5582     {
5583       delete [] copy_field;
5584       copy_field= NULL;
5585       copy_field_end= NULL;
5586     }
5587   }
5588 };
5589 
5590 
5591 class select_unit :public select_result_interceptor
5592 {
5593   uint curr_step, prev_step, curr_sel;
5594   enum sub_select_type step;
5595 public:
5596   Item_int *intersect_mark;
5597   TMP_TABLE_PARAM tmp_table_param;
5598   int write_err; /* Error code from the last send_data->ha_write_row call. */
5599   TABLE *table;
5600 
select_unit(THD * thd_arg)5601   select_unit(THD *thd_arg):
5602     select_result_interceptor(thd_arg),
5603     intersect_mark(0), table(0)
5604   {
5605     init();
5606     tmp_table_param.init();
5607   }
5608   int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
5609   /**
5610     Do prepare() and prepare2() if they have been postponed until
5611     column type information is computed (used by select_union_direct).
5612 
5613     @param types Column types
5614 
5615     @return false on success, true on failure
5616   */
postponed_prepare(List<Item> & types)5617   virtual bool postponed_prepare(List<Item> &types)
5618   { return false; }
5619   int send_data(List<Item> &items);
5620   bool send_eof();
5621   virtual bool flush();
5622   void cleanup();
5623   virtual bool create_result_table(THD *thd, List<Item> *column_types,
5624                                    bool is_distinct, ulonglong options,
5625                                    const LEX_CSTRING *alias,
5626                                    bool bit_fields_as_long,
5627                                    bool create_table,
5628                                    bool keep_row_order,
5629                                    uint hidden);
get_tmp_table_param()5630   TMP_TABLE_PARAM *get_tmp_table_param() { return &tmp_table_param; }
init()5631   void init()
5632   {
5633     curr_step= prev_step= 0;
5634     curr_sel= UINT_MAX;
5635     step= UNION_TYPE;
5636     write_err= 0;
5637   }
5638   void change_select();
5639 };
5640 
5641 class select_union_recursive :public select_unit
5642 {
5643  public:
5644   /* The temporary table with the new records generated by one iterative step */
5645   TABLE *incr_table;
5646   /* The TMP_TABLE_PARAM structure used to create incr_table */
5647   TMP_TABLE_PARAM incr_table_param;
5648   /* One of tables from the list rec_tables (determined dynamically) */
5649   TABLE *first_rec_table_to_update;
5650   /*
5651     The list of all recursive table references to the CTE for whose
5652     specification this select_union_recursive was created
5653  */
5654   List<TABLE_LIST> rec_table_refs;
5655   /*
5656     The count of how many times cleanup() was called with cleaned==false
5657     for the unit specifying the recursive CTE for which this object was created
5658     or for the unit specifying a CTE that mutually recursive with this CTE.
5659   */
5660   uint cleanup_count;
5661 
select_union_recursive(THD * thd_arg)5662   select_union_recursive(THD *thd_arg):
5663     select_unit(thd_arg),
5664     incr_table(0), first_rec_table_to_update(0), cleanup_count(0)
5665   { incr_table_param.init(); };
5666 
5667   int send_data(List<Item> &items);
5668   bool create_result_table(THD *thd, List<Item> *column_types,
5669                            bool is_distinct, ulonglong options,
5670                            const LEX_CSTRING *alias,
5671                            bool bit_fields_as_long,
5672                            bool create_table,
5673                            bool keep_row_order,
5674                            uint hidden);
5675   void cleanup();
5676 };
5677 
5678 /**
5679   UNION result that is passed directly to the receiving select_result
5680   without filling a temporary table.
5681 
5682   Function calls are forwarded to the wrapped select_result, but some
5683   functions are expected to be called only once for each query, so
5684   they are only executed for the first SELECT in the union (execept
5685   for send_eof(), which is executed only for the last SELECT).
5686 
5687   This select_result is used when a UNION is not DISTINCT and doesn't
5688   have a global ORDER BY clause. @see st_select_lex_unit::prepare().
5689 */
5690 
5691 class select_union_direct :public select_unit
5692 {
5693 private:
5694   /* Result object that receives all rows */
5695   select_result *result;
5696   /* The last SELECT_LEX of the union */
5697   SELECT_LEX *last_select_lex;
5698 
5699   /* Wrapped result has received metadata */
5700   bool done_send_result_set_metadata;
5701   /* Wrapped result has initialized tables */
5702   bool done_initialize_tables;
5703 
5704   /* Accumulated limit_found_rows */
5705   ulonglong limit_found_rows;
5706 
5707   /* Number of rows offset */
5708   ha_rows offset;
5709   /* Number of rows limit + offset, @see select_union_direct::send_data() */
5710   ha_rows limit;
5711 
5712 public:
5713   /* Number of rows in the union */
5714   ha_rows send_records;
select_union_direct(THD * thd_arg,select_result * result_arg,SELECT_LEX * last_select_lex_arg)5715   select_union_direct(THD *thd_arg, select_result *result_arg,
5716                       SELECT_LEX *last_select_lex_arg):
5717   select_unit(thd_arg), result(result_arg),
5718     last_select_lex(last_select_lex_arg),
5719     done_send_result_set_metadata(false), done_initialize_tables(false),
5720     limit_found_rows(0)
5721     { send_records= 0; }
5722   bool change_result(select_result *new_result);
field_count(List<Item> & fields)5723   uint field_count(List<Item> &fields) const
5724   {
5725     // Only called for top-level select_results, usually select_send
5726     DBUG_ASSERT(false); /* purecov: inspected */
5727     return 0; /* purecov: inspected */
5728   }
5729   bool postponed_prepare(List<Item> &types);
5730   bool send_result_set_metadata(List<Item> &list, uint flags);
5731   int send_data(List<Item> &items);
5732   bool initialize_tables (JOIN *join);
5733   bool send_eof();
flush()5734   bool flush() { return false; }
check_simple_select()5735   bool check_simple_select() const
5736   {
5737     /* Only called for top-level select_results, usually select_send */
5738     DBUG_ASSERT(false); /* purecov: inspected */
5739     return false; /* purecov: inspected */
5740   }
abort_result_set()5741   void abort_result_set()
5742   {
5743     result->abort_result_set(); /* purecov: inspected */
5744   }
cleanup()5745   void cleanup()
5746   {
5747     send_records= 0;
5748   }
set_thd(THD * thd_arg)5749   void set_thd(THD *thd_arg)
5750   {
5751     /*
5752       Only called for top-level select_results, usually select_send,
5753       and for the results of subquery engines
5754       (select_<something>_subselect).
5755     */
5756     DBUG_ASSERT(false); /* purecov: inspected */
5757   }
reset_offset_limit_cnt()5758   void reset_offset_limit_cnt()
5759   {
5760     // EXPLAIN should never output to a select_union_direct
5761     DBUG_ASSERT(false); /* purecov: inspected */
5762   }
begin_dataset()5763   void begin_dataset()
5764   {
5765     // Only called for sp_cursor::Select_fetch_into_spvars
5766     DBUG_ASSERT(false); /* purecov: inspected */
5767   }
5768 };
5769 
5770 
5771 /* Base subselect interface class */
5772 class select_subselect :public select_result_interceptor
5773 {
5774 protected:
5775   Item_subselect *item;
5776 public:
select_subselect(THD * thd_arg,Item_subselect * item_arg)5777   select_subselect(THD *thd_arg, Item_subselect *item_arg):
5778     select_result_interceptor(thd_arg), item(item_arg) {}
5779   int send_data(List<Item> &items)=0;
send_eof()5780   bool send_eof() { return 0; };
5781 };
5782 
5783 /* Single value subselect interface class */
5784 class select_singlerow_subselect :public select_subselect
5785 {
5786 public:
select_singlerow_subselect(THD * thd_arg,Item_subselect * item_arg)5787   select_singlerow_subselect(THD *thd_arg, Item_subselect *item_arg):
5788     select_subselect(thd_arg, item_arg)
5789   {}
5790   int send_data(List<Item> &items);
5791 };
5792 
5793 
5794 /*
5795   This class specializes select_union to collect statistics about the
5796   data stored in the temp table. Currently the class collects statistcs
5797   about NULLs.
5798 */
5799 
5800 class select_materialize_with_stats : public select_unit
5801 {
5802 protected:
5803   class Column_statistics
5804   {
5805   public:
5806     /* Count of NULLs per column. */
5807     ha_rows null_count;
5808     /* The row number that contains the first NULL in a column. */
5809     ha_rows min_null_row;
5810     /* The row number that contains the last NULL in a column. */
5811     ha_rows max_null_row;
5812   };
5813 
5814   /* Array of statistics data per column. */
5815   Column_statistics* col_stat;
5816 
5817   /*
5818     The number of columns in the biggest sub-row that consists of only
5819     NULL values.
5820   */
5821   uint max_nulls_in_row;
5822   /*
5823     Count of rows writtent to the temp table. This is redundant as it is
5824     already stored in handler::stats.records, however that one is relatively
5825     expensive to compute (given we need that for evry row).
5826   */
5827   ha_rows count_rows;
5828 
5829 protected:
5830   void reset();
5831 
5832 public:
select_materialize_with_stats(THD * thd_arg)5833   select_materialize_with_stats(THD *thd_arg): select_unit(thd_arg)
5834   { tmp_table_param.init(); }
5835   bool create_result_table(THD *thd, List<Item> *column_types,
5836                            bool is_distinct, ulonglong options,
5837                            const LEX_CSTRING *alias,
5838                            bool bit_fields_as_long,
5839                            bool create_table,
5840                            bool keep_row_order,
5841                            uint hidden);
5842   bool init_result_table(ulonglong select_options);
5843   int send_data(List<Item> &items);
5844   void cleanup();
get_null_count_of_col(uint idx)5845   ha_rows get_null_count_of_col(uint idx)
5846   {
5847     DBUG_ASSERT(idx < table->s->fields);
5848     return col_stat[idx].null_count;
5849   }
get_max_null_of_col(uint idx)5850   ha_rows get_max_null_of_col(uint idx)
5851   {
5852     DBUG_ASSERT(idx < table->s->fields);
5853     return col_stat[idx].max_null_row;
5854   }
get_min_null_of_col(uint idx)5855   ha_rows get_min_null_of_col(uint idx)
5856   {
5857     DBUG_ASSERT(idx < table->s->fields);
5858     return col_stat[idx].min_null_row;
5859   }
get_max_nulls_in_row()5860   uint get_max_nulls_in_row() { return max_nulls_in_row; }
5861 };
5862 
5863 
5864 /* used in independent ALL/ANY optimisation */
5865 class select_max_min_finder_subselect :public select_subselect
5866 {
5867   Item_cache *cache;
5868   bool (select_max_min_finder_subselect::*op)();
5869   bool fmax;
5870   bool is_all;
5871 public:
select_max_min_finder_subselect(THD * thd_arg,Item_subselect * item_arg,bool mx,bool all)5872   select_max_min_finder_subselect(THD *thd_arg, Item_subselect *item_arg,
5873                                   bool mx, bool all):
5874     select_subselect(thd_arg, item_arg), cache(0), fmax(mx), is_all(all)
5875   {}
5876   void cleanup();
5877   int send_data(List<Item> &items);
5878   bool cmp_real();
5879   bool cmp_int();
5880   bool cmp_decimal();
5881   bool cmp_str();
5882   bool cmp_time();
5883 };
5884 
5885 /* EXISTS subselect interface class */
5886 class select_exists_subselect :public select_subselect
5887 {
5888 public:
select_exists_subselect(THD * thd_arg,Item_subselect * item_arg)5889   select_exists_subselect(THD *thd_arg, Item_subselect *item_arg):
5890     select_subselect(thd_arg, item_arg) {}
5891   int send_data(List<Item> &items);
5892 };
5893 
5894 
5895 /*
5896   Optimizer and executor structure for the materialized semi-join info. This
5897   structure contains
5898    - The sj-materialization temporary table
5899    - Members needed to make index lookup or a full scan of the temptable.
5900 */
5901 class SJ_MATERIALIZATION_INFO : public Sql_alloc
5902 {
5903 public:
5904   /* Optimal join sub-order */
5905   struct st_position *positions;
5906 
5907   uint tables; /* Number of tables in the sj-nest */
5908 
5909   /* Number of rows in the materialized table, before the de-duplication */
5910   double rows_with_duplicates;
5911 
5912   /* Expected #rows in the materialized table, after de-duplication */
5913   double rows;
5914 
5915   /*
5916     Cost to materialize - execute the sub-join and write rows into temp.table
5917   */
5918   Cost_estimate materialization_cost;
5919 
5920   /* Cost to make one lookup in the temptable */
5921   Cost_estimate lookup_cost;
5922 
5923   /* Cost of scanning the materialized table */
5924   Cost_estimate scan_cost;
5925 
5926   /* --- Execution structures ---------- */
5927 
5928   /*
5929     TRUE <=> This structure is used for execution. We don't necessarily pick
5930     sj-materialization, so some of SJ_MATERIALIZATION_INFO structures are not
5931     used by materialization
5932   */
5933   bool is_used;
5934 
5935   bool materialized; /* TRUE <=> materialization already performed */
5936   /*
5937     TRUE  - the temptable is read with full scan
5938     FALSE - we use the temptable for index lookups
5939   */
5940   bool is_sj_scan;
5941 
5942   /* The temptable and its related info */
5943   TMP_TABLE_PARAM sjm_table_param;
5944   List<Item> sjm_table_cols;
5945   TABLE *table;
5946 
5947   /* Structure used to make index lookups */
5948   struct st_table_ref *tab_ref;
5949   Item *in_equality; /* See create_subq_in_equalities() */
5950 
5951   Item *join_cond; /* See comments in make_join_select() */
5952   Copy_field *copy_field; /* Needed for SJ_Materialization scan */
5953 };
5954 
5955 
5956 /* Structs used when sorting */
5957 struct SORT_FIELD_ATTR
5958 {
5959   uint length;          /* Length of sort field */
5960   uint suffix_length;   /* Length suffix (0-4) */
5961 };
5962 
5963 
5964 struct SORT_FIELD: public SORT_FIELD_ATTR
5965 {
5966   Field *field;				/* Field to sort */
5967   Item	*item;				/* Item if not sorting fields */
5968   bool reverse;				/* if descending sort */
5969 };
5970 
5971 
5972 typedef struct st_sort_buffer {
5973   uint index;					/* 0 or 1 */
5974   uint sort_orders;
5975   uint change_pos;				/* If sort-fields changed */
5976   char **buff;
5977   SORT_FIELD *sortorder;
5978 } SORT_BUFFER;
5979 
5980 /* Structure for db & table in sql_yacc */
5981 
5982 class Table_ident :public Sql_alloc
5983 {
5984 public:
5985   LEX_CSTRING db;
5986   LEX_CSTRING table;
5987   SELECT_LEX_UNIT *sel;
Table_ident(THD * thd,const LEX_CSTRING * db_arg,const LEX_CSTRING * table_arg,bool force)5988   inline Table_ident(THD *thd, const LEX_CSTRING *db_arg,
5989                      const LEX_CSTRING *table_arg,
5990 		     bool force)
5991     :table(*table_arg), sel((SELECT_LEX_UNIT *)0)
5992   {
5993     if (!force && (thd->client_capabilities & CLIENT_NO_SCHEMA))
5994       db= null_clex_str;
5995     else
5996       db= *db_arg;
5997   }
Table_ident(const LEX_CSTRING * table_arg)5998   inline Table_ident(const LEX_CSTRING *table_arg)
5999     :table(*table_arg), sel((SELECT_LEX_UNIT *)0)
6000   {
6001     db= null_clex_str;
6002   }
6003   /*
6004     This constructor is used only for the case when we create a derived
6005     table. A derived table has no name and doesn't belong to any database.
6006     Later, if there was an alias specified for the table, it will be set
6007     by add_table_to_list.
6008   */
Table_ident(SELECT_LEX_UNIT * s)6009   inline Table_ident(SELECT_LEX_UNIT *s) : sel(s)
6010   {
6011     /* We must have a table name here as this is used with add_table_to_list */
6012     db.str= empty_c_string;                    /* a subject to casedn_str */
6013     db.length= 0;
6014     table.str= internal_table_name;
6015     table.length=1;
6016   }
is_derived_table()6017   bool is_derived_table() const { return MY_TEST(sel); }
change_db(LEX_CSTRING * db_name)6018   inline void change_db(LEX_CSTRING *db_name)
6019   {
6020     db= *db_name;
6021   }
6022   bool resolve_table_rowtype_ref(THD *thd, Row_definition_list &defs);
6023   bool append_to(THD *thd, String *to) const;
6024 };
6025 
6026 
6027 class Qualified_column_ident: public Table_ident
6028 {
6029 public:
6030   LEX_CSTRING m_column;
6031 public:
Qualified_column_ident(const LEX_CSTRING * column)6032   Qualified_column_ident(const LEX_CSTRING *column)
6033     :Table_ident(&null_clex_str),
6034     m_column(*column)
6035   { }
Qualified_column_ident(const LEX_CSTRING * table,const LEX_CSTRING * column)6036   Qualified_column_ident(const LEX_CSTRING *table, const LEX_CSTRING *column)
6037    :Table_ident(table),
6038     m_column(*column)
6039   { }
Qualified_column_ident(THD * thd,const LEX_CSTRING * db,const LEX_CSTRING * table,const LEX_CSTRING * column)6040   Qualified_column_ident(THD *thd,
6041                          const LEX_CSTRING *db,
6042                          const LEX_CSTRING *table,
6043                          const LEX_CSTRING *column)
6044    :Table_ident(thd, db, table, false),
6045     m_column(*column)
6046   { }
6047   bool resolve_type_ref(THD *thd, Column_definition *def);
6048   bool append_to(THD *thd, String *to) const;
6049 };
6050 
6051 
6052 // this is needed for user_vars hash
6053 class user_var_entry
6054 {
6055   CHARSET_INFO *m_charset;
6056  public:
user_var_entry()6057   user_var_entry() {}                         /* Remove gcc warning */
6058   LEX_CSTRING name;
6059   char *value;
6060   size_t length;
6061   query_id_t update_query_id, used_query_id;
6062   Item_result type;
6063   bool unsigned_flag;
6064 
6065   double val_real(bool *null_value);
6066   longlong val_int(bool *null_value) const;
6067   String *val_str(bool *null_value, String *str, uint decimals);
6068   my_decimal *val_decimal(bool *null_value, my_decimal *result);
charset()6069   CHARSET_INFO *charset() const { return m_charset; }
set_charset(CHARSET_INFO * cs)6070   void set_charset(CHARSET_INFO *cs) { m_charset= cs; }
6071 };
6072 
6073 user_var_entry *get_variable(HASH *hash, LEX_CSTRING *name,
6074 				    bool create_if_not_exists);
6075 
6076 class SORT_INFO;
6077 class multi_delete :public select_result_interceptor
6078 {
6079   TABLE_LIST *delete_tables, *table_being_deleted;
6080   Unique **tempfiles;
6081   ha_rows deleted, found;
6082   uint num_of_tables;
6083   int error;
6084   bool do_delete;
6085   /* True if at least one table we delete from is transactional */
6086   bool transactional_tables;
6087   /* True if at least one table we delete from is not transactional */
6088   bool normal_tables;
6089   bool delete_while_scanning;
6090   /*
6091      error handling (rollback and binlogging) can happen in send_eof()
6092      so that afterward abort_result_set() needs to find out that.
6093   */
6094   bool error_handled;
6095 
6096 public:
6097   multi_delete(THD *thd_arg, TABLE_LIST *dt, uint num_of_tables);
6098   ~multi_delete();
6099   int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
6100   int send_data(List<Item> &items);
6101   bool initialize_tables (JOIN *join);
6102   int do_deletes();
6103   int do_table_deletes(TABLE *table, SORT_INFO *sort_info, bool ignore);
6104   bool send_eof();
num_deleted()6105   inline ha_rows num_deleted() const { return deleted; }
6106   virtual void abort_result_set();
6107   void prepare_to_read_rows();
6108 };
6109 
6110 
6111 class multi_update :public select_result_interceptor
6112 {
6113   TABLE_LIST *all_tables; /* query/update command tables */
6114   List<TABLE_LIST> *leaves;     /* list of leaves of join table tree */
6115   List<TABLE_LIST> updated_leaves;  /* list of of updated leaves */
6116   TABLE_LIST *update_tables;
6117   TABLE **tmp_tables, *main_table, *table_to_update;
6118   TMP_TABLE_PARAM *tmp_table_param;
6119   ha_rows updated, found;
6120   List <Item> *fields, *values;
6121   List <Item> **fields_for_table, **values_for_table;
6122   uint table_count;
6123   /*
6124    List of tables referenced in the CHECK OPTION condition of
6125    the updated view excluding the updated table.
6126   */
6127   List <TABLE> unupdated_check_opt_tables;
6128   Copy_field *copy_field;
6129   enum enum_duplicates handle_duplicates;
6130   bool do_update, trans_safe;
6131   /* True if the update operation has made a change in a transactional table */
6132   bool transactional_tables;
6133   bool ignore;
6134   /*
6135      error handling (rollback and binlogging) can happen in send_eof()
6136      so that afterward  abort_result_set() needs to find out that.
6137   */
6138   bool error_handled;
6139 
6140   /* Need this to protect against multiple prepare() calls */
6141   bool prepared;
6142 
6143   // For System Versioning (may need to insert new fields to a table).
6144   ha_rows updated_sys_ver;
6145 
6146   bool has_vers_fields;
6147 
6148 public:
6149   multi_update(THD *thd_arg, TABLE_LIST *ut, List<TABLE_LIST> *leaves_list,
6150 	       List<Item> *fields, List<Item> *values,
6151 	       enum_duplicates handle_duplicates, bool ignore);
6152   ~multi_update();
6153   bool init(THD *thd);
6154   int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
6155   int send_data(List<Item> &items);
6156   bool initialize_tables (JOIN *join);
6157   int prepare2(JOIN *join);
6158   int  do_updates();
6159   bool send_eof();
num_found()6160   inline ha_rows num_found() const { return found; }
num_updated()6161   inline ha_rows num_updated() const { return updated; }
6162   virtual void abort_result_set();
6163   void update_used_tables();
6164   void prepare_to_read_rows();
6165 };
6166 
6167 class my_var_sp;
6168 class my_var : public Sql_alloc  {
6169 public:
6170   const LEX_CSTRING name;
6171   enum type { SESSION_VAR, LOCAL_VAR, PARAM_VAR };
6172   type scope;
my_var(const LEX_CSTRING * j,enum type s)6173   my_var(const LEX_CSTRING *j, enum type s) : name(*j), scope(s) { }
~my_var()6174   virtual ~my_var() {}
6175   virtual bool set(THD *thd, Item *val) = 0;
get_my_var_sp()6176   virtual my_var_sp *get_my_var_sp() { return NULL; }
6177 };
6178 
6179 class my_var_sp: public my_var {
6180   const Sp_rcontext_handler *m_rcontext_handler;
6181   const Type_handler *m_type_handler;
6182 public:
6183   uint offset;
6184   /*
6185     Routine to which this Item_splocal belongs. Used for checking if correct
6186     runtime context is used for variable handling.
6187   */
6188   sp_head *sp;
my_var_sp(const Sp_rcontext_handler * rcontext_handler,const LEX_CSTRING * j,uint o,const Type_handler * type_handler,sp_head * s)6189   my_var_sp(const Sp_rcontext_handler *rcontext_handler,
6190             const LEX_CSTRING *j, uint o, const Type_handler *type_handler,
6191             sp_head *s)
6192     : my_var(j, LOCAL_VAR),
6193       m_rcontext_handler(rcontext_handler),
6194       m_type_handler(type_handler), offset(o), sp(s) { }
~my_var_sp()6195   ~my_var_sp() { }
6196   bool set(THD *thd, Item *val);
get_my_var_sp()6197   my_var_sp *get_my_var_sp() { return this; }
type_handler()6198   const Type_handler *type_handler() const { return m_type_handler; }
6199   sp_rcontext *get_rcontext(sp_rcontext *local_ctx) const;
6200 };
6201 
6202 /*
6203   This class handles fields of a ROW SP variable when it's used as a OUT
6204   parameter in a stored procedure.
6205 */
6206 class my_var_sp_row_field: public my_var_sp
6207 {
6208   uint m_field_offset;
6209 public:
my_var_sp_row_field(const Sp_rcontext_handler * rcontext_handler,const LEX_CSTRING * varname,const LEX_CSTRING * fieldname,uint var_idx,uint field_idx,sp_head * s)6210   my_var_sp_row_field(const Sp_rcontext_handler *rcontext_handler,
6211                       const LEX_CSTRING *varname, const LEX_CSTRING *fieldname,
6212                       uint var_idx, uint field_idx, sp_head *s)
6213    :my_var_sp(rcontext_handler, varname, var_idx,
6214               &type_handler_double/*Not really used*/, s),
6215     m_field_offset(field_idx)
6216   { }
6217   bool set(THD *thd, Item *val);
6218 };
6219 
6220 class my_var_user: public my_var {
6221 public:
my_var_user(const LEX_CSTRING * j)6222   my_var_user(const LEX_CSTRING *j)
6223     : my_var(j, SESSION_VAR) { }
~my_var_user()6224   ~my_var_user() { }
6225   bool set(THD *thd, Item *val);
6226 };
6227 
6228 class select_dumpvar :public select_result_interceptor {
6229   ha_rows row_count;
6230   my_var_sp *m_var_sp_row; // Not NULL if SELECT INTO row_type_sp_variable
6231   bool send_data_to_var_list(List<Item> &items);
6232 public:
6233   List<my_var> var_list;
select_dumpvar(THD * thd_arg)6234   select_dumpvar(THD *thd_arg)
6235    :select_result_interceptor(thd_arg), row_count(0), m_var_sp_row(NULL)
6236   { var_list.empty(); }
~select_dumpvar()6237   ~select_dumpvar() {}
6238   int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
6239   int send_data(List<Item> &items);
6240   bool send_eof();
6241   virtual bool check_simple_select() const;
6242   void cleanup();
6243 };
6244 
6245 /* Bits in sql_command_flags */
6246 
6247 #define CF_CHANGES_DATA           (1U << 0)
6248 #define CF_REPORT_PROGRESS        (1U << 1)
6249 #define CF_STATUS_COMMAND         (1U << 2)
6250 #define CF_SHOW_TABLE_COMMAND     (1U << 3)
6251 #define CF_WRITE_LOGS_COMMAND     (1U << 4)
6252 
6253 /**
6254   Must be set for SQL statements that may contain
6255   Item expressions and/or use joins and tables.
6256   Indicates that the parse tree of such statement may
6257   contain rule-based optimizations that depend on metadata
6258   (i.e. number of columns in a table), and consequently
6259   that the statement must be re-prepared whenever
6260   referenced metadata changes. Must not be set for
6261   statements that themselves change metadata, e.g. RENAME,
6262   ALTER and other DDL, since otherwise will trigger constant
6263   reprepare. Consequently, complex item expressions and
6264   joins are currently prohibited in these statements.
6265 */
6266 #define CF_REEXECUTION_FRAGILE    (1U << 5)
6267 /**
6268   Implicitly commit before the SQL statement is executed.
6269 
6270   Statements marked with this flag will cause any active
6271   transaction to end (commit) before proceeding with the
6272   command execution.
6273 
6274   This flag should be set for statements that probably can't
6275   be rolled back or that do not expect any previously metadata
6276   locked tables.
6277 */
6278 #define CF_IMPLICT_COMMIT_BEGIN   (1U << 6)
6279 /**
6280   Implicitly commit after the SQL statement.
6281 
6282   Statements marked with this flag are automatically committed
6283   at the end of the statement.
6284 
6285   This flag should be set for statements that will implicitly
6286   open and take metadata locks on system tables that should not
6287   be carried for the whole duration of a active transaction.
6288 */
6289 #define CF_IMPLICIT_COMMIT_END    (1U << 7)
6290 /**
6291   CF_IMPLICT_COMMIT_BEGIN and CF_IMPLICIT_COMMIT_END are used
6292   to ensure that the active transaction is implicitly committed
6293   before and after every DDL statement and any statement that
6294   modifies our currently non-transactional system tables.
6295 */
6296 #define CF_AUTO_COMMIT_TRANS  (CF_IMPLICT_COMMIT_BEGIN | CF_IMPLICIT_COMMIT_END)
6297 
6298 /**
6299   Diagnostic statement.
6300   Diagnostic statements:
6301   - SHOW WARNING
6302   - SHOW ERROR
6303   - GET DIAGNOSTICS (WL#2111)
6304   do not modify the diagnostics area during execution.
6305 */
6306 #define CF_DIAGNOSTIC_STMT        (1U << 8)
6307 
6308 /**
6309   Identifies statements that may generate row events
6310   and that may end up in the binary log.
6311 */
6312 #define CF_CAN_GENERATE_ROW_EVENTS (1U << 9)
6313 
6314 /**
6315   Identifies statements which may deal with temporary tables and for which
6316   temporary tables should be pre-opened to simplify privilege checks.
6317 */
6318 #define CF_PREOPEN_TMP_TABLES   (1U << 10)
6319 
6320 /**
6321   Identifies statements for which open handlers should be closed in the
6322   beginning of the statement.
6323 */
6324 #define CF_HA_CLOSE             (1U << 11)
6325 
6326 /**
6327   Identifies statements that can be explained with EXPLAIN.
6328 */
6329 #define CF_CAN_BE_EXPLAINED       (1U << 12)
6330 
6331 /** Identifies statements which may generate an optimizer trace */
6332 #define CF_OPTIMIZER_TRACE        (1U << 14)
6333 
6334 /**
6335    Identifies statements that should always be disallowed in
6336    read only transactions.
6337 */
6338 #define CF_DISALLOW_IN_RO_TRANS   (1U << 15)
6339 
6340 /**
6341   Statement that need the binlog format to be unchanged.
6342 */
6343 #define CF_FORCE_ORIGINAL_BINLOG_FORMAT (1U << 16)
6344 
6345 /**
6346   Statement that inserts new rows (INSERT, REPLACE, LOAD, ALTER TABLE)
6347 */
6348 #define CF_INSERTS_DATA (1U << 17)
6349 
6350 /**
6351   Statement that updates existing rows (UPDATE, multi-update)
6352 */
6353 #define CF_UPDATES_DATA (1U << 18)
6354 
6355 /**
6356   Not logged into slow log as "admin commands"
6357 */
6358 #define CF_ADMIN_COMMAND (1U << 19)
6359 
6360 /**
6361   SP Bulk execution safe
6362 */
6363 #define CF_PS_ARRAY_BINDING_SAFE (1U << 20)
6364 /**
6365   SP Bulk execution optimized
6366 */
6367 #define CF_PS_ARRAY_BINDING_OPTIMIZED (1U << 21)
6368 /**
6369   If command creates or drops a table
6370 */
6371 #define CF_SCHEMA_CHANGE (1U << 22)
6372 /**
6373   If command creates or drops a database
6374 */
6375 #define CF_DB_CHANGE (1U << 23)
6376 
6377 /* Bits in server_command_flags */
6378 
6379 /**
6380   Statement that deletes existing rows (DELETE, DELETE_MULTI)
6381 */
6382 #define CF_DELETES_DATA (1U << 24)
6383 
6384 /**
6385   Skip the increase of the global query id counter. Commonly set for
6386   commands that are stateless (won't cause any change on the server
6387   internal states).
6388 */
6389 #define CF_SKIP_QUERY_ID        (1U << 0)
6390 
6391 /**
6392   Skip the increase of the number of statements that clients have
6393   sent to the server. Commonly used for commands that will cause
6394   a statement to be executed but the statement might have not been
6395   sent by the user (ie: stored procedure).
6396 */
6397 #define CF_SKIP_QUESTIONS       (1U << 1)
6398 #ifdef WITH_WSREP
6399 /**
6400   Do not check that wsrep snapshot is ready before allowing this command
6401 */
6402 #define CF_SKIP_WSREP_CHECK     (1U << 2)
6403 #else
6404 #define CF_SKIP_WSREP_CHECK     0
6405 #endif /* WITH_WSREP */
6406 
6407 /**
6408   Do not allow it for COM_MULTI batch
6409 */
6410 #define CF_NO_COM_MULTI         (1U << 3)
6411 
6412 /* Inline functions */
6413 
add_item_to_list(THD * thd,Item * item)6414 inline bool add_item_to_list(THD *thd, Item *item)
6415 {
6416   return thd->lex->current_select->add_item_to_list(thd, item);
6417 }
6418 
add_value_to_list(THD * thd,Item * value)6419 inline bool add_value_to_list(THD *thd, Item *value)
6420 {
6421   return thd->lex->value_list.push_back(value, thd->mem_root);
6422 }
6423 
add_order_to_list(THD * thd,Item * item,bool asc)6424 inline bool add_order_to_list(THD *thd, Item *item, bool asc)
6425 {
6426   return thd->lex->current_select->add_order_to_list(thd, item, asc);
6427 }
6428 
add_gorder_to_list(THD * thd,Item * item,bool asc)6429 inline bool add_gorder_to_list(THD *thd, Item *item, bool asc)
6430 {
6431   return thd->lex->current_select->add_gorder_to_list(thd, item, asc);
6432 }
6433 
add_group_to_list(THD * thd,Item * item,bool asc)6434 inline bool add_group_to_list(THD *thd, Item *item, bool asc)
6435 {
6436   return thd->lex->current_select->add_group_to_list(thd, item, asc);
6437 }
6438 
and_conds(THD * thd,Item * a,Item * b)6439 inline Item *and_conds(THD *thd, Item *a, Item *b)
6440 {
6441   if (!b) return a;
6442   if (!a) return b;
6443   return new (thd->mem_root) Item_cond_and(thd, a, b);
6444 }
6445 
6446 /* inline handler methods that need to know TABLE and THD structures */
increment_statistics(ulong SSV::* offset)6447 inline void handler::increment_statistics(ulong SSV::*offset) const
6448 {
6449   status_var_increment(table->in_use->status_var.*offset);
6450   table->in_use->check_limit_rows_examined();
6451 }
6452 
decrement_statistics(ulong SSV::* offset)6453 inline void handler::decrement_statistics(ulong SSV::*offset) const
6454 {
6455   status_var_decrement(table->in_use->status_var.*offset);
6456 }
6457 
6458 
ha_ft_read(uchar * buf)6459 inline int handler::ha_ft_read(uchar *buf)
6460 {
6461   int error= ft_read(buf);
6462   if (!error)
6463     update_rows_read();
6464 
6465   table->status=error ? STATUS_NOT_FOUND: 0;
6466   return error;
6467 }
6468 
ha_rnd_pos_by_record(uchar * buf)6469 inline int handler::ha_rnd_pos_by_record(uchar *buf)
6470 {
6471   int error= rnd_pos_by_record(buf);
6472   table->status=error ? STATUS_NOT_FOUND: 0;
6473   return error;
6474 }
6475 
ha_read_first_row(uchar * buf,uint primary_key)6476 inline int handler::ha_read_first_row(uchar *buf, uint primary_key)
6477 {
6478   int error= read_first_row(buf, primary_key);
6479   if (!error)
6480     update_rows_read();
6481   table->status=error ? STATUS_NOT_FOUND: 0;
6482   return error;
6483 }
6484 
ha_write_tmp_row(uchar * buf)6485 inline int handler::ha_write_tmp_row(uchar *buf)
6486 {
6487   int error;
6488   MYSQL_INSERT_ROW_START(table_share->db.str, table_share->table_name.str);
6489   increment_statistics(&SSV::ha_tmp_write_count);
6490   TABLE_IO_WAIT(tracker, m_psi, PSI_TABLE_WRITE_ROW, MAX_KEY, 0,
6491                 { error= write_row(buf); })
6492   MYSQL_INSERT_ROW_DONE(error);
6493   return error;
6494 }
6495 
ha_delete_tmp_row(uchar * buf)6496 inline int handler::ha_delete_tmp_row(uchar *buf)
6497 {
6498   int error;
6499   MYSQL_DELETE_ROW_START(table_share->db.str, table_share->table_name.str);
6500   increment_statistics(&SSV::ha_tmp_delete_count);
6501   TABLE_IO_WAIT(tracker, m_psi, PSI_TABLE_DELETE_ROW, MAX_KEY, 0,
6502                 { error= delete_row(buf); })
6503   MYSQL_DELETE_ROW_DONE(error);
6504   return error;
6505 }
6506 
ha_update_tmp_row(const uchar * old_data,uchar * new_data)6507 inline int handler::ha_update_tmp_row(const uchar *old_data, uchar *new_data)
6508 {
6509   int error;
6510   MYSQL_UPDATE_ROW_START(table_share->db.str, table_share->table_name.str);
6511   increment_statistics(&SSV::ha_tmp_update_count);
6512   TABLE_IO_WAIT(tracker, m_psi, PSI_TABLE_UPDATE_ROW, active_index, 0,
6513                 { error= update_row(old_data, new_data);})
6514   MYSQL_UPDATE_ROW_DONE(error);
6515   return error;
6516 }
6517 
6518 
6519 extern pthread_attr_t *get_connection_attrib(void);
6520 
6521 /**
6522    Set thread entering a condition
6523 
6524    This function should be called before putting a thread to wait for
6525    a condition. @a mutex should be held before calling this
6526    function. After being waken up, @f thd_exit_cond should be called.
6527 
6528    @param thd      The thread entering the condition, NULL means current thread
6529    @param cond     The condition the thread is going to wait for
6530    @param mutex    The mutex associated with the condition, this must be
6531                    held before call this function
6532    @param stage    The new process message for the thread
6533    @param old_stage The old process message for the thread
6534    @param src_function The caller source function name
6535    @param src_file The caller source file name
6536    @param src_line The caller source line number
6537 */
6538 void thd_enter_cond(MYSQL_THD thd, mysql_cond_t *cond, mysql_mutex_t *mutex,
6539                     const PSI_stage_info *stage, PSI_stage_info *old_stage,
6540                     const char *src_function, const char *src_file,
6541                     int src_line);
6542 
6543 #define THD_ENTER_COND(P1, P2, P3, P4, P5) \
6544   thd_enter_cond(P1, P2, P3, P4, P5, __func__, __FILE__, __LINE__)
6545 
6546 /**
6547    Set thread leaving a condition
6548 
6549    This function should be called after a thread being waken up for a
6550    condition.
6551 
6552    @param thd      The thread entering the condition, NULL means current thread
6553    @param stage    The process message, ususally this should be the old process
6554                    message before calling @f thd_enter_cond
6555    @param src_function The caller source function name
6556    @param src_file The caller source file name
6557    @param src_line The caller source line number
6558 */
6559 void thd_exit_cond(MYSQL_THD thd, const PSI_stage_info *stage,
6560                    const char *src_function, const char *src_file,
6561                    int src_line);
6562 
6563 #define THD_EXIT_COND(P1, P2) \
6564   thd_exit_cond(P1, P2, __func__, __FILE__, __LINE__)
6565 
binlog_should_compress(size_t len)6566 inline bool binlog_should_compress(size_t len)
6567 {
6568   return opt_bin_log_compress &&
6569     len >= opt_bin_log_compress_min_len;
6570 }
6571 
6572 
6573 /**
6574    Save thd sql_mode on instantiation.
6575    On destruction it resets the mode to the previously stored value.
6576 */
6577 class Sql_mode_save
6578 {
6579  public:
Sql_mode_save(THD * thd)6580   Sql_mode_save(THD *thd) : thd(thd), old_mode(thd->variables.sql_mode) {}
~Sql_mode_save()6581   ~Sql_mode_save() { thd->variables.sql_mode = old_mode; }
6582 
6583  private:
6584   THD *thd;
6585   sql_mode_t old_mode; // SQL mode saved at construction time.
6586 };
6587 
6588 class Abort_on_warning_instant_set
6589 {
6590   THD *m_thd;
6591   bool m_save_abort_on_warning;
6592 public:
Abort_on_warning_instant_set(THD * thd,bool temporary_value)6593   Abort_on_warning_instant_set(THD *thd, bool temporary_value)
6594    :m_thd(thd), m_save_abort_on_warning(thd->abort_on_warning)
6595   {
6596     thd->abort_on_warning= temporary_value;
6597   }
~Abort_on_warning_instant_set()6598   ~Abort_on_warning_instant_set()
6599   {
6600     m_thd->abort_on_warning= m_save_abort_on_warning;
6601   }
6602 };
6603 
6604 class Switch_to_definer_security_ctx
6605 {
6606  public:
Switch_to_definer_security_ctx(THD * thd,TABLE_LIST * table)6607   Switch_to_definer_security_ctx(THD *thd, TABLE_LIST *table) :
6608     m_thd(thd), m_sctx(thd->security_ctx)
6609   {
6610     if (table->security_ctx)
6611       thd->security_ctx= table->security_ctx;
6612   }
~Switch_to_definer_security_ctx()6613   ~Switch_to_definer_security_ctx() { m_thd->security_ctx = m_sctx; }
6614 
6615  private:
6616   THD *m_thd;
6617   Security_context *m_sctx;
6618 };
6619 
6620 
6621 class Check_level_instant_set
6622 {
6623   THD *m_thd;
6624   enum_check_fields m_check_level;
6625 public:
Check_level_instant_set(THD * thd,enum_check_fields temporary_value)6626   Check_level_instant_set(THD *thd, enum_check_fields temporary_value)
6627    :m_thd(thd), m_check_level(thd->count_cuted_fields)
6628   {
6629     thd->count_cuted_fields= temporary_value;
6630   }
~Check_level_instant_set()6631   ~Check_level_instant_set()
6632   {
6633     m_thd->count_cuted_fields= m_check_level;
6634   }
6635 };
6636 
6637 
6638 /**
6639   This class resembles the SQL Standard schema qualified object name:
6640   <schema qualified name> ::= [ <schema name> <period> ] <qualified identifier>
6641 */
6642 class Database_qualified_name
6643 {
6644 public:
6645   LEX_CSTRING m_db;
6646   LEX_CSTRING m_name;
Database_qualified_name(const LEX_CSTRING * db,const LEX_CSTRING * name)6647   Database_qualified_name(const LEX_CSTRING *db, const LEX_CSTRING *name)
6648    :m_db(*db), m_name(*name)
6649   { }
Database_qualified_name(const LEX_CSTRING & db,const LEX_CSTRING & name)6650   Database_qualified_name(const LEX_CSTRING &db, const LEX_CSTRING &name)
6651    :m_db(db), m_name(name)
6652   { }
Database_qualified_name(const char * db,size_t db_length,const char * name,size_t name_length)6653   Database_qualified_name(const char *db, size_t db_length,
6654                           const char *name, size_t name_length)
6655   {
6656     m_db.str= db;
6657     m_db.length= db_length;
6658     m_name.str= name;
6659     m_name.length= name_length;
6660   }
6661 
eq(const Database_qualified_name * other)6662   bool eq(const Database_qualified_name *other) const
6663   {
6664     CHARSET_INFO *cs= lower_case_table_names ?
6665                       &my_charset_utf8_general_ci :
6666                       &my_charset_utf8_bin;
6667     return
6668       m_db.length == other->m_db.length &&
6669       m_name.length == other->m_name.length &&
6670       !my_strnncoll(cs,
6671                     (const uchar *) m_db.str, m_db.length,
6672                     (const uchar *) other->m_db.str, other->m_db.length) &&
6673       !my_strnncoll(cs,
6674                     (const uchar *) m_name.str, m_name.length,
6675                     (const uchar *) other->m_name.str, other->m_name.length);
6676   }
6677   void copy(MEM_ROOT *mem_root, const LEX_CSTRING &db,
6678                                 const LEX_CSTRING &name);
6679   // Export db and name as a qualified name string: 'db.name'
make_qname(char * dst,size_t dstlen)6680   size_t make_qname(char *dst, size_t dstlen) const
6681   {
6682     return my_snprintf(dst, dstlen, "%.*s.%.*s",
6683                        (int) m_db.length, m_db.str,
6684                        (int) m_name.length, m_name.str);
6685   }
6686   // Export db and name as a qualified name string, allocate on mem_root.
make_qname(MEM_ROOT * mem_root,LEX_CSTRING * dst)6687   bool make_qname(MEM_ROOT *mem_root, LEX_CSTRING *dst) const
6688   {
6689     const uint dot= !!m_db.length;
6690     char *tmp;
6691     /* format: [database + dot] + name + '\0' */
6692     dst->length= m_db.length + dot + m_name.length;
6693     if (unlikely(!(dst->str= tmp= (char*) alloc_root(mem_root,
6694                                                      dst->length + 1))))
6695       return true;
6696     sprintf(tmp, "%.*s%.*s%.*s",
6697             (int) m_db.length, (m_db.length ? m_db.str : ""),
6698             dot, ".",
6699             (int) m_name.length, m_name.str);
6700     DBUG_SLOW_ASSERT(ok_for_lower_case_names(m_db.str));
6701     return false;
6702   }
6703 
make_package_routine_name(MEM_ROOT * mem_root,const LEX_CSTRING & package,const LEX_CSTRING & routine)6704   bool make_package_routine_name(MEM_ROOT *mem_root,
6705                                  const LEX_CSTRING &package,
6706                                  const LEX_CSTRING &routine)
6707   {
6708     char *tmp;
6709     size_t length= package.length + 1 + routine.length + 1;
6710     if (unlikely(!(tmp= (char *) alloc_root(mem_root, length))))
6711       return true;
6712     m_name.length= my_snprintf(tmp, length, "%.*s.%.*s",
6713                                (int) package.length, package.str,
6714                                (int) routine.length, routine.str);
6715     m_name.str= tmp;
6716     return false;
6717   }
6718 
make_package_routine_name(MEM_ROOT * mem_root,const LEX_CSTRING & db,const LEX_CSTRING & package,const LEX_CSTRING & routine)6719   bool make_package_routine_name(MEM_ROOT *mem_root,
6720                                  const LEX_CSTRING &db,
6721                                  const LEX_CSTRING &package,
6722                                  const LEX_CSTRING &routine)
6723   {
6724     if (unlikely(make_package_routine_name(mem_root, package, routine)))
6725       return true;
6726     if (unlikely(!(m_db.str= strmake_root(mem_root, db.str, db.length))))
6727       return true;
6728     m_db.length= db.length;
6729     return false;
6730   }
6731 };
6732 
6733 
6734 class ErrConvDQName: public ErrConv
6735 {
6736   const Database_qualified_name *m_name;
6737 public:
ErrConvDQName(const Database_qualified_name * name)6738   ErrConvDQName(const Database_qualified_name *name)
6739    :m_name(name)
6740   { }
ptr()6741   const char *ptr() const
6742   {
6743     m_name->make_qname(err_buffer, sizeof(err_buffer));
6744     return err_buffer;
6745   }
6746 };
6747 
6748 class Type_holder: public Sql_alloc,
6749                    public Item_args,
6750                    public Type_handler_hybrid_field_type,
6751                    public Type_all_attributes,
6752                    public Type_geometry_attributes
6753 {
6754   TYPELIB *m_typelib;
6755   bool m_maybe_null;
6756 public:
Type_holder()6757   Type_holder()
6758    :m_typelib(NULL),
6759     m_maybe_null(false)
6760   { }
6761 
set_maybe_null(bool maybe_null_arg)6762   void set_maybe_null(bool maybe_null_arg) { m_maybe_null= maybe_null_arg; }
get_maybe_null()6763   bool get_maybe_null() const { return m_maybe_null; }
6764 
decimal_precision()6765   uint decimal_precision() const
6766   {
6767     /*
6768       Type_holder is not used directly to create fields, so
6769       its virtual decimal_precision() is never called.
6770       We should eventually extend create_result_table() to accept
6771       an array of Type_holders directly, without having to allocate
6772       Item_type_holder's and put them into List<Item>.
6773     */
6774     DBUG_ASSERT(0);
6775     return 0;
6776   }
set_geometry_type(uint type)6777   void set_geometry_type(uint type)
6778   {
6779     Type_geometry_attributes::set_geometry_type(type);
6780   }
uint_geometry_type()6781   uint uint_geometry_type() const
6782   {
6783     return Type_geometry_attributes::get_geometry_type();
6784   }
set_typelib(TYPELIB * typelib)6785   void set_typelib(TYPELIB *typelib)
6786   {
6787     m_typelib= typelib;
6788   }
get_typelib()6789   TYPELIB *get_typelib() const
6790   {
6791     return m_typelib;
6792   }
6793 
aggregate_attributes(THD * thd)6794   bool aggregate_attributes(THD *thd)
6795   {
6796     for (uint i= 0; i < arg_count; i++)
6797       m_maybe_null|= args[i]->maybe_null;
6798     return
6799        type_handler()->Item_hybrid_func_fix_attributes(thd,
6800                                                        "UNION", this, this,
6801                                                        args, arg_count);
6802   }
6803 };
6804 
6805 
6806 /*
6807   A helper class to set THD flags to emit warnings/errors in case of
6808   overflow/type errors during assigning values into the SP variable fields.
6809   Saves original flags values in constructor.
6810   Restores original flags in destructor.
6811 */
6812 class Sp_eval_expr_state
6813 {
6814   THD *m_thd;
6815   enum_check_fields m_count_cuted_fields;
6816   bool m_abort_on_warning;
6817   bool m_stmt_modified_non_trans_table;
start()6818   void start()
6819   {
6820     m_thd->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL;
6821     m_thd->abort_on_warning= m_thd->is_strict_mode();
6822     m_thd->transaction.stmt.modified_non_trans_table= false;
6823   }
stop()6824   void stop()
6825   {
6826     m_thd->count_cuted_fields= m_count_cuted_fields;
6827     m_thd->abort_on_warning= m_abort_on_warning;
6828     m_thd->transaction.stmt.modified_non_trans_table=
6829       m_stmt_modified_non_trans_table;
6830   }
6831 public:
Sp_eval_expr_state(THD * thd)6832   Sp_eval_expr_state(THD *thd)
6833    :m_thd(thd),
6834     m_count_cuted_fields(thd->count_cuted_fields),
6835     m_abort_on_warning(thd->abort_on_warning),
6836     m_stmt_modified_non_trans_table(thd->transaction.stmt.
6837                                     modified_non_trans_table)
6838   {
6839     start();
6840   }
~Sp_eval_expr_state()6841   ~Sp_eval_expr_state()
6842   {
6843     stop();
6844   }
6845 };
6846 
6847 
6848 #ifndef DBUG_OFF
6849 void dbug_serve_apcs(THD *thd, int n_calls);
6850 #endif
6851 
6852 class ScopedStatementReplication
6853 {
6854 public:
ScopedStatementReplication(THD * thd)6855   ScopedStatementReplication(THD *thd) :
6856     saved_binlog_format(thd
6857                         ? thd->set_current_stmt_binlog_format_stmt()
6858                         : BINLOG_FORMAT_MIXED),
6859     thd(thd)
6860   {}
~ScopedStatementReplication()6861   ~ScopedStatementReplication()
6862   {
6863     if (thd)
6864       thd->restore_stmt_binlog_format(saved_binlog_format);
6865   }
6866 
6867 private:
6868   const enum_binlog_format saved_binlog_format;
6869   THD *const thd;
6870 };
6871 
6872 #endif /* MYSQL_SERVER */
6873 #endif /* SQL_CLASS_INCLUDED */
6874