MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
sql_class.h
1 /* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15 
16 #ifndef SQL_CLASS_INCLUDED
17 #define SQL_CLASS_INCLUDED
18 
19 /* Classes in mysql */
20 
21 #include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */
22 #ifdef MYSQL_SERVER
23 #include "unireg.h" // REQUIRED: for other includes
24 #endif
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 "sql_locale.h" /* my_locale_st */
31 #include "sql_profile.h" /* PROFILING */
32 #include "scheduler.h" /* thd_scheduler */
33 #include "protocol.h" /* Protocol_text, Protocol_binary */
34 #include "violite.h" /* vio_is_connected */
35 #include "thr_lock.h" /* thr_lock_type, THR_LOCK_DATA,
36  THR_LOCK_INFO */
37 #include "opt_trace_context.h" /* Opt_trace_context */
38 #include "rpl_gtid.h"
39 
40 #include <mysql/psi/mysql_stage.h>
42 #include <mysql/psi/mysql_idle.h>
43 #include <mysql_com_server.h>
44 #include "sql_data_change.h"
45 
46 #define FLAGSTR(V,F) ((V)&(F)?#F" ":"")
47 
52 extern "C"
53 const char *set_thd_proc_info(void *thd_arg, const char *info,
54  const char *calling_func,
55  const char *calling_file,
56  const unsigned int calling_line);
57 
58 #define thd_proc_info(thd, msg) \
59  set_thd_proc_info(thd, msg, __func__, __FILE__, __LINE__)
60 
61 extern "C"
62 void set_thd_stage_info(void *thd,
63  const PSI_stage_info *new_stage,
64  PSI_stage_info *old_stage,
65  const char *calling_func,
66  const char *calling_file,
67  const unsigned int calling_line);
68 
69 #define THD_STAGE_INFO(thd, stage) \
70  (thd)->enter_stage(& stage, NULL, __func__, __FILE__, __LINE__)
71 
72 class Reprepare_observer;
73 class Relay_log_info;
74 
75 class Query_log_event;
76 class Load_log_event;
77 class sp_rcontext;
78 class sp_cache;
79 class Parser_state;
80 class Rows_log_event;
82 class User_level_lock;
83 class user_var_entry;
84 
85 enum enum_ha_read_modes { RFIRST, RNEXT, RPREV, RLAST, RKEY, RNEXT_SAME };
86 
87 enum enum_delay_key_write { DELAY_KEY_WRITE_NONE, DELAY_KEY_WRITE_ON,
88  DELAY_KEY_WRITE_ALL };
89 enum enum_slave_exec_mode { SLAVE_EXEC_MODE_STRICT,
90  SLAVE_EXEC_MODE_IDEMPOTENT,
91  SLAVE_EXEC_MODE_LAST_BIT };
92 enum enum_slave_type_conversions { SLAVE_TYPE_CONVERSIONS_ALL_LOSSY,
93  SLAVE_TYPE_CONVERSIONS_ALL_NON_LOSSY,
94  SLAVE_TYPE_CONVERSIONS_ALL_UNSIGNED,
95  SLAVE_TYPE_CONVERSIONS_ALL_SIGNED};
96 enum enum_slave_rows_search_algorithms { SLAVE_ROWS_TABLE_SCAN = (1U << 0),
97  SLAVE_ROWS_INDEX_SCAN = (1U << 1),
98  SLAVE_ROWS_HASH_SCAN = (1U << 2)};
99 
100 enum enum_mark_columns
101 { MARK_COLUMNS_NONE, MARK_COLUMNS_READ, MARK_COLUMNS_WRITE};
102 enum enum_filetype { FILETYPE_CSV, FILETYPE_XML };
103 
104 /* Bits for different SQL modes modes (including ANSI mode) */
105 #define MODE_REAL_AS_FLOAT 1
106 #define MODE_PIPES_AS_CONCAT 2
107 #define MODE_ANSI_QUOTES 4
108 #define MODE_IGNORE_SPACE 8
109 #define MODE_NOT_USED 16
110 #define MODE_ONLY_FULL_GROUP_BY 32
111 #define MODE_NO_UNSIGNED_SUBTRACTION 64
112 #define MODE_NO_DIR_IN_CREATE 128
113 #define MODE_POSTGRESQL 256
114 #define MODE_ORACLE 512
115 #define MODE_MSSQL 1024
116 #define MODE_DB2 2048
117 #define MODE_MAXDB 4096
118 #define MODE_NO_KEY_OPTIONS 8192
119 #define MODE_NO_TABLE_OPTIONS 16384
120 #define MODE_NO_FIELD_OPTIONS 32768
121 #define MODE_MYSQL323 65536L
122 #define MODE_MYSQL40 (MODE_MYSQL323*2)
123 #define MODE_ANSI (MODE_MYSQL40*2)
124 #define MODE_NO_AUTO_VALUE_ON_ZERO (MODE_ANSI*2)
125 #define MODE_NO_BACKSLASH_ESCAPES (MODE_NO_AUTO_VALUE_ON_ZERO*2)
126 #define MODE_STRICT_TRANS_TABLES (MODE_NO_BACKSLASH_ESCAPES*2)
127 #define MODE_STRICT_ALL_TABLES (MODE_STRICT_TRANS_TABLES*2)
128 #define MODE_NO_ZERO_IN_DATE (MODE_STRICT_ALL_TABLES*2)
129 #define MODE_NO_ZERO_DATE (MODE_NO_ZERO_IN_DATE*2)
130 #define MODE_INVALID_DATES (MODE_NO_ZERO_DATE*2)
131 #define MODE_ERROR_FOR_DIVISION_BY_ZERO (MODE_INVALID_DATES*2)
132 #define MODE_TRADITIONAL (MODE_ERROR_FOR_DIVISION_BY_ZERO*2)
133 #define MODE_NO_AUTO_CREATE_USER (MODE_TRADITIONAL*2)
134 #define MODE_HIGH_NOT_PRECEDENCE (MODE_NO_AUTO_CREATE_USER*2)
135 #define MODE_NO_ENGINE_SUBSTITUTION (MODE_HIGH_NOT_PRECEDENCE*2)
136 #define MODE_PAD_CHAR_TO_FULL_LENGTH (ULL(1) << 31)
137 
138 extern char internal_table_name[2];
139 extern char empty_c_string[1];
140 extern LEX_STRING EMPTY_STR;
141 extern LEX_STRING NULL_STR;
142 extern MYSQL_PLUGIN_IMPORT const char **errmesg;
143 
144 extern bool volatile shutdown_in_progress;
145 
146 extern "C" LEX_STRING * thd_query_string (MYSQL_THD thd);
147 extern "C" char **thd_query(MYSQL_THD thd);
148 
154 {
155 private:
156  LEX_STRING string;
157  const CHARSET_INFO *cs;
158 public:
159  CSET_STRING() : cs(&my_charset_bin)
160  {
161  string.str= NULL;
162  string.length= 0;
163  }
164  CSET_STRING(char *str_arg, size_t length_arg, const CHARSET_INFO *cs_arg) :
165  cs(cs_arg)
166  {
167  DBUG_ASSERT(cs_arg != NULL);
168  string.str= str_arg;
169  string.length= length_arg;
170  }
171 
172  inline char *str() const { return string.str; }
173  inline size_t length() const { return string.length; }
174  const CHARSET_INFO *charset() const { return cs; }
175 
176  friend LEX_STRING * thd_query_string (MYSQL_THD thd);
177  friend char **thd_query(MYSQL_THD thd);
178 };
179 
180 
181 #define TC_LOG_PAGE_SIZE 8192
182 #define TC_LOG_MIN_SIZE (3*TC_LOG_PAGE_SIZE)
183 
184 #define TC_HEURISTIC_RECOVER_COMMIT 1
185 #define TC_HEURISTIC_RECOVER_ROLLBACK 2
186 extern ulong tc_heuristic_recover;
187 
188 typedef struct st_user_var_events
189 {
190  user_var_entry *user_var_event;
191  char *value;
192  ulong length;
193  Item_result type;
194  uint charset_number;
195  bool unsigned_flag;
197 
198 
199 class Key_part_spec :public Sql_alloc {
200 public:
201  LEX_STRING field_name;
202  uint length;
203  Key_part_spec(const LEX_STRING &name, uint len)
204  : field_name(name), length(len)
205  {}
206  Key_part_spec(const char *name, const size_t name_len, uint len)
207  : length(len)
208  { field_name.str= (char *)name; field_name.length= name_len; }
209  bool operator==(const Key_part_spec& other) const;
219  Key_part_spec *clone(MEM_ROOT *mem_root) const
220  { return new (mem_root) Key_part_spec(*this); }
221 };
222 
223 
224 class Alter_drop :public Sql_alloc {
225 public:
226  enum drop_type {KEY, COLUMN, FOREIGN_KEY };
227  const char *name;
228  enum drop_type type;
229  Alter_drop(enum drop_type par_type,const char *par_name)
230  :name(par_name), type(par_type)
231  {
232  DBUG_ASSERT(par_name != NULL);
233  }
238  Alter_drop *clone(MEM_ROOT *mem_root) const
239  { return new (mem_root) Alter_drop(*this); }
240 };
241 
242 
243 class Alter_column :public Sql_alloc {
244 public:
245  const char *name;
246  Item *def;
247  Alter_column(const char *par_name,Item *literal)
248  :name(par_name), def(literal) {}
253  Alter_column *clone(MEM_ROOT *mem_root) const
254  { return new (mem_root) Alter_column(*this); }
255 };
256 
257 
258 class Key :public Sql_alloc {
259 public:
260  enum Keytype { PRIMARY, UNIQUE, MULTIPLE, FULLTEXT, SPATIAL, FOREIGN_KEY};
261  enum Keytype type;
262  KEY_CREATE_INFO key_create_info;
263  List<Key_part_spec> columns;
264  LEX_STRING name;
265  bool generated;
266 
267  Key(enum Keytype type_par, const LEX_STRING &name_arg,
268  KEY_CREATE_INFO *key_info_arg,
269  bool generated_arg, List<Key_part_spec> &cols)
270  :type(type_par), key_create_info(*key_info_arg), columns(cols),
271  name(name_arg), generated(generated_arg)
272  {}
273  Key(enum Keytype type_par, const char *name_arg, size_t name_len_arg,
274  KEY_CREATE_INFO *key_info_arg, bool generated_arg,
275  List<Key_part_spec> &cols)
276  :type(type_par), key_create_info(*key_info_arg), columns(cols),
277  generated(generated_arg)
278  {
279  name.str= (char *)name_arg;
280  name.length= name_len_arg;
281  }
282  Key(const Key &rhs, MEM_ROOT *mem_root);
283  virtual ~Key() {}
284  /* Equality comparison of keys (ignoring name) */
285  friend bool foreign_key_prefix(Key *a, Key *b);
290  virtual Key *clone(MEM_ROOT *mem_root) const
291  { return new (mem_root) Key(*this, mem_root); }
292 };
293 
294 class Table_ident;
295 
296 class Foreign_key: public Key {
297 public:
298  enum fk_match_opt { FK_MATCH_UNDEF, FK_MATCH_FULL,
299  FK_MATCH_PARTIAL, FK_MATCH_SIMPLE};
300  enum fk_option { FK_OPTION_UNDEF, FK_OPTION_RESTRICT, FK_OPTION_CASCADE,
301  FK_OPTION_SET_NULL, FK_OPTION_NO_ACTION, FK_OPTION_DEFAULT};
302 
303  LEX_STRING ref_db;
304  LEX_STRING ref_table;
305  List<Key_part_spec> ref_columns;
306  uint delete_opt, update_opt, match_opt;
307  Foreign_key(const LEX_STRING &name_arg, List<Key_part_spec> &cols,
308  const LEX_STRING &ref_db_arg, const LEX_STRING &ref_table_arg,
309  List<Key_part_spec> &ref_cols,
310  uint delete_opt_arg, uint update_opt_arg, uint match_opt_arg)
311  :Key(FOREIGN_KEY, name_arg, &default_key_create_info, 0, cols),
312  ref_db(ref_db_arg), ref_table(ref_table_arg), ref_columns(ref_cols),
313  delete_opt(delete_opt_arg), update_opt(update_opt_arg),
314  match_opt(match_opt_arg)
315  {
316  // We don't check for duplicate FKs.
317  key_create_info.check_for_duplicate_indexes= false;
318  }
319  Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root);
324  virtual Key *clone(MEM_ROOT *mem_root) const
325  { return new (mem_root) Foreign_key(*this, mem_root); }
326 };
327 
328 typedef struct st_mysql_lock
329 {
330  TABLE **table;
331  uint table_count,lock_count;
332  THR_LOCK_DATA **locks;
333 } MYSQL_LOCK;
334 
335 
336 class LEX_COLUMN : public Sql_alloc
337 {
338 public:
339  String column;
340  uint rights;
341  LEX_COLUMN (const String& x,const uint& y ): column (x),rights (y) {}
342 };
343 
344 class MY_LOCALE;
345 
350 struct Query_cache_block;
351 
353 {
354  /*
355  'first_query_block' should be accessed only via query cache
356  functions and methods to maintain proper locking.
357  */
358  Query_cache_block *first_query_block;
359  void set_first_query_block(Query_cache_block *first_query_block_arg)
360  {
361  first_query_block= first_query_block_arg;
362  }
363 
364  Query_cache_tls() :first_query_block(NULL) {}
365 };
366 
367 /* SIGNAL / RESIGNAL / GET DIAGNOSTICS */
368 
373 typedef enum enum_diag_condition_item_name
374 {
375  /*
376  Conditions that can be set by the user (SIGNAL/RESIGNAL),
377  and by the server implementation.
378  */
379 
380  DIAG_CLASS_ORIGIN= 0,
381  FIRST_DIAG_SET_PROPERTY= DIAG_CLASS_ORIGIN,
382  DIAG_SUBCLASS_ORIGIN= 1,
383  DIAG_CONSTRAINT_CATALOG= 2,
384  DIAG_CONSTRAINT_SCHEMA= 3,
385  DIAG_CONSTRAINT_NAME= 4,
386  DIAG_CATALOG_NAME= 5,
387  DIAG_SCHEMA_NAME= 6,
388  DIAG_TABLE_NAME= 7,
389  DIAG_COLUMN_NAME= 8,
390  DIAG_CURSOR_NAME= 9,
391  DIAG_MESSAGE_TEXT= 10,
392  DIAG_MYSQL_ERRNO= 11,
393  LAST_DIAG_SET_PROPERTY= DIAG_MYSQL_ERRNO
394 } Diag_condition_item_name;
395 
400 extern const LEX_STRING Diag_condition_item_names[];
401 
402 #include "sql_lex.h" /* Must be here */
403 
404 extern LEX_CSTRING sql_statement_names[(uint) SQLCOM_END + 1];
405 class Delayed_insert;
406 class select_result;
407 class Time_zone;
408 
409 #define THD_SENTRY_MAGIC 0xfeedd1ff
410 #define THD_SENTRY_GONE 0xdeadbeef
411 
412 #define THD_CHECK_SENTRY(thd) DBUG_ASSERT(thd->dbug_sentry == THD_SENTRY_MAGIC)
413 
414 typedef ulonglong sql_mode_t;
415 
416 typedef struct system_variables
417 {
418  /*
419  How dynamically allocated system variables are handled:
420 
421  The global_system_variables and max_system_variables are "authoritative"
422  They both should have the same 'version' and 'size'.
423  When attempting to access a dynamic variable, if the session version
424  is out of date, then the session version is updated and realloced if
425  neccessary and bytes copied from global to make up for missing data.
426  */
427  ulong dynamic_variables_version;
428  char* dynamic_variables_ptr;
429  uint dynamic_variables_head; /* largest valid variable offset */
430  uint dynamic_variables_size; /* how many bytes are in use */
431  LIST *dynamic_variables_allocs; /* memory hunks for PLUGIN_VAR_MEMALLOC */
432 
433  ulonglong max_heap_table_size;
434  ulonglong tmp_table_size;
435  ulonglong long_query_time;
436  my_bool end_markers_in_json;
437  /* A bitmap for switching optimizations on/off */
438  ulonglong optimizer_switch;
439  ulonglong optimizer_trace;
441  long optimizer_trace_offset;
442  long optimizer_trace_limit;
443  ulong optimizer_trace_max_mem_size;
444  sql_mode_t sql_mode;
445  ulonglong option_bits;
446  ha_rows select_limit;
447  ha_rows max_join_size;
448  ulong auto_increment_increment, auto_increment_offset;
449  ulong bulk_insert_buff_size;
450  uint eq_range_index_dive_limit;
451  ulong join_buff_size;
452  ulong lock_wait_timeout;
453  ulong max_allowed_packet;
454  ulong max_error_count;
455  ulong max_length_for_sort_data;
456  ulong max_sort_length;
457  ulong max_tmp_tables;
458  ulong max_insert_delayed_threads;
459  ulong min_examined_row_limit;
460  ulong multi_range_count;
461  ulong myisam_repair_threads;
462  ulong myisam_sort_buff_size;
463  ulong myisam_stats_method;
464  ulong net_buffer_length;
465  ulong net_interactive_timeout;
466  ulong net_read_timeout;
467  ulong net_retry_count;
468  ulong net_wait_timeout;
469  ulong net_write_timeout;
470  ulong optimizer_prune_level;
471  ulong optimizer_search_depth;
472  ulong preload_buff_size;
473  ulong profiling_history_size;
474  ulong read_buff_size;
475  ulong read_rnd_buff_size;
476  ulong div_precincrement;
477  ulong sortbuff_size;
478  ulong max_sp_recursion_depth;
479  ulong default_week_format;
480  ulong max_seeks_for_key;
481  ulong range_alloc_block_size;
482  ulong query_alloc_block_size;
483  ulong query_prealloc_size;
484  ulong trans_alloc_block_size;
485  ulong trans_prealloc_size;
486  ulong group_concat_max_len;
487 
489  my_bool binlog_direct_non_trans_update;
490  ulong binlog_row_image;
491  my_bool sql_log_bin;
492  ulong completion_type;
493  ulong query_cache_type;
494  ulong tx_isolation;
495  ulong updatable_views_with_limit;
496  uint max_user_connections;
501  my_thread_id pseudo_thread_id;
505  my_bool tx_read_only;
506  my_bool low_priority_updates;
507  my_bool new_mode;
508  my_bool query_cache_wlock_invalidate;
509  my_bool engine_condition_pushdown;
510  my_bool keep_files_on_create;
511 
512  my_bool old_alter_table;
513  uint old_passwords;
514  my_bool big_tables;
515 
516  plugin_ref table_plugin;
517  plugin_ref temp_table_plugin;
518 
519  /* Only charset part of these variables is sensible */
520  const CHARSET_INFO *character_set_filesystem;
521  const CHARSET_INFO *character_set_client;
522  const CHARSET_INFO *character_set_results;
523 
524  /* Both charset and collation parts of these variables are important */
525  const CHARSET_INFO *collation_server;
526  const CHARSET_INFO *collation_database;
527  const CHARSET_INFO *collation_connection;
528 
529  /* Error messages */
530  MY_LOCALE *lc_messages;
531  /* Locale Support */
532  MY_LOCALE *lc_time_names;
533 
534  Time_zone *time_zone;
535  /*
536  TIMESTAMP fields are by default created with DEFAULT clauses
537  implicitly without users request. This flag when set, disables
538  implicit default values and expect users to provide explicit
539  default clause. i.e., when set columns are defined as NULL,
540  instead of NOT NULL by default.
541  */
542  my_bool explicit_defaults_for_timestamp;
543 
544  my_bool sysdate_is_now;
545  my_bool binlog_rows_query_log_events;
546 
547  double long_query_time_double;
548 
549  my_bool pseudo_slave_mode;
550 
551  Gtid_specification gtid_next;
552  Gtid_set_or_null gtid_next_list;
553 
554 } SV;
555 
556 
563 typedef struct system_status_var
564 {
565  ulonglong created_tmp_disk_tables;
566  ulonglong created_tmp_tables;
567  ulonglong ha_commit_count;
568  ulonglong ha_delete_count;
569  ulonglong ha_read_first_count;
570  ulonglong ha_read_last_count;
571  ulonglong ha_read_key_count;
572  ulonglong ha_read_next_count;
573  ulonglong ha_read_prev_count;
574  ulonglong ha_read_rnd_count;
575  ulonglong ha_read_rnd_next_count;
576  /*
577  This number doesn't include calls to the default implementation and
578  calls made by range access. The intent is to count only calls made by
579  BatchedKeyAccess.
580  */
581  ulonglong ha_multi_range_read_init_count;
582  ulonglong ha_rollback_count;
583  ulonglong ha_update_count;
584  ulonglong ha_write_count;
585  ulonglong ha_prepare_count;
586  ulonglong ha_discover_count;
587  ulonglong ha_savepoint_count;
588  ulonglong ha_savepoint_rollback_count;
589  ulonglong ha_external_lock_count;
590  ulonglong opened_tables;
591  ulonglong opened_shares;
592  ulonglong table_open_cache_hits;
593  ulonglong table_open_cache_misses;
594  ulonglong table_open_cache_overflows;
595  ulonglong select_full_join_count;
596  ulonglong select_full_range_join_count;
597  ulonglong select_range_count;
598  ulonglong select_range_check_count;
599  ulonglong select_scan_count;
600  ulonglong long_query_count;
601  ulonglong filesort_merge_passes;
602  ulonglong filesort_range_count;
603  ulonglong filesort_rows;
604  ulonglong filesort_scan_count;
605  /* Prepared statements and binary protocol */
606  ulonglong com_stmt_prepare;
607  ulonglong com_stmt_reprepare;
608  ulonglong com_stmt_execute;
609  ulonglong com_stmt_send_long_data;
610  ulonglong com_stmt_fetch;
611  ulonglong com_stmt_reset;
612  ulonglong com_stmt_close;
613 
614  ulonglong bytes_received;
615  ulonglong bytes_sent;
616  /*
617  Number of statements sent from the client
618  */
619  ulonglong questions;
620 
621  ulong com_other;
622  ulong com_stat[(uint) SQLCOM_END];
623 
624  /*
625  IMPORTANT!
626  SEE last_system_status_var DEFINITION BELOW.
627  Below 'last_system_status_var' are all variables that cannot be handled
628  automatically by add_to_status()/add_diff_to_status().
629  */
630  double last_query_cost;
631  ulonglong last_query_partial_plans;
632 } STATUS_VAR;
633 
634 /*
635  This is used for 'SHOW STATUS'. It must be updated to the last ulong
636  variable in system_status_var which is makes sens to add to the global
637  counter
638 */
639 
640 #define last_system_status_var questions
641 
642 void mark_transaction_to_rollback(THD *thd, bool all);
643 
644 
653 inline CHARSET_INFO *
654 mysqld_collation_get_by_name(const char *name,
655  CHARSET_INFO *name_cs= system_charset_info)
656 {
657  CHARSET_INFO *cs;
658  MY_CHARSET_LOADER loader;
659  my_charset_loader_init_mysys(&loader);
660  if (!(cs= my_collation_get_by_name(&loader, name, MYF(0))))
661  {
662  ErrConvString err(name, name_cs);
663  my_error(ER_UNKNOWN_COLLATION, MYF(0), err.ptr());
664  if (loader.error[0])
665  push_warning_printf(current_thd,
666  Sql_condition::WARN_LEVEL_WARN,
667  ER_UNKNOWN_COLLATION, "%s", loader.error);
668  }
669  return cs;
670 }
671 
672 
673 #ifdef MYSQL_SERVER
674 
675 void free_tmp_table(THD *thd, TABLE *entry);
676 
677 
678 /* The following macro is to make init of Query_arena simpler */
679 #ifndef DBUG_OFF
680 #define INIT_ARENA_DBUG_INFO is_backup_arena= 0; is_reprepared= FALSE;
681 #else
682 #define INIT_ARENA_DBUG_INFO
683 #endif
684 
685 class Query_arena
686 {
687 public:
688  /*
689  List of items created in the parser for this query. Every item puts
690  itself to the list on creation (see Item::Item() for details))
691  */
692  Item *free_list;
693  MEM_ROOT *mem_root; // Pointer to current memroot
694 #ifndef DBUG_OFF
695  bool is_backup_arena; /* True if this arena is used for backup. */
696  bool is_reprepared;
697 #endif
698  /*
699  The states relfects three diffrent life cycles for three
700  different types of statements:
701  Prepared statement: STMT_INITIALIZED -> STMT_PREPARED -> STMT_EXECUTED.
702  Stored procedure: STMT_INITIALIZED_FOR_SP -> STMT_EXECUTED.
703  Other statements: STMT_CONVENTIONAL_EXECUTION never changes.
704  */
705  enum enum_state
706  {
707  STMT_INITIALIZED= 0, STMT_INITIALIZED_FOR_SP= 1, STMT_PREPARED= 2,
708  STMT_CONVENTIONAL_EXECUTION= 3, STMT_EXECUTED= 4, STMT_ERROR= -1
709  };
710 
711  enum_state state;
712 
713  /* We build without RTTI, so dynamic_cast can't be used. */
714  enum Type
715  {
716  STATEMENT, PREPARED_STATEMENT, STORED_PROCEDURE
717  };
718 
719  Query_arena(MEM_ROOT *mem_root_arg, enum enum_state state_arg) :
720  free_list(0), mem_root(mem_root_arg), state(state_arg)
721  { INIT_ARENA_DBUG_INFO; }
722  /*
723  This constructor is used only when Query_arena is created as
724  backup storage for another instance of Query_arena.
725  */
726  Query_arena() { INIT_ARENA_DBUG_INFO; }
727 
728  virtual Type type() const;
729  virtual ~Query_arena() {};
730 
731  inline bool is_stmt_prepare() const { return state == STMT_INITIALIZED; }
732  inline bool is_stmt_prepare_or_first_sp_execute() const
733  { return (int)state < (int)STMT_PREPARED; }
734  inline bool is_stmt_prepare_or_first_stmt_execute() const
735  { return (int)state <= (int)STMT_PREPARED; }
736  inline bool is_conventional() const
737  { return state == STMT_CONVENTIONAL_EXECUTION; }
738 
739  inline void* alloc(size_t size) { return alloc_root(mem_root,size); }
740  inline void* calloc(size_t size)
741  {
742  void *ptr;
743  if ((ptr=alloc_root(mem_root,size)))
744  memset(ptr, 0, size);
745  return ptr;
746  }
747  inline char *strdup(const char *str)
748  { return strdup_root(mem_root,str); }
749  inline char *strmake(const char *str, size_t size)
750  { return strmake_root(mem_root,str,size); }
751  inline void *memdup(const void *str, size_t size)
752  { return memdup_root(mem_root,str,size); }
753  inline void *memdup_w_gap(const void *str, size_t size, uint gap)
754  {
755  void *ptr;
756  if ((ptr= alloc_root(mem_root,size+gap)))
757  memcpy(ptr,str,size);
758  return ptr;
759  }
760 
761  void set_query_arena(Query_arena *set);
762 
763  void free_items();
764  /* Close the active state associated with execution of this statement */
765  virtual void cleanup_stmt();
766 };
767 
768 
769 class Server_side_cursor;
770 
787 class Statement: public Query_arena
788 {
789  Statement(const Statement &rhs); /* not implemented: */
790  Statement &operator=(const Statement &rhs); /* non-copyable */
791 public:
792  /*
793  Uniquely identifies each statement object in thread scope; change during
794  statement lifetime. FIXME: must be const
795  */
796  ulong id;
797 
798  /*
799  MARK_COLUMNS_NONE: Means mark_used_colums is not set and no indicator to
800  handler of fields used is set
801  MARK_COLUMNS_READ: Means a bit in read set is set to inform handler
802  that the field is to be read. If field list contains
803  duplicates, then thd->dup_field is set to point
804  to the last found duplicate.
805  MARK_COLUMNS_WRITE: Means a bit is set in write set to inform handler
806  that it needs to update this field in write_row
807  and update_row.
808  */
809  enum enum_mark_columns mark_used_columns;
810 
811  LEX_STRING name; /* name for named prepared statements */
812  LEX *lex; // parse tree descriptor
813  /*
814  Points to the query associated with this statement. It's const, but
815  we need to declare it char * because all table handlers are written
816  in C and need to point to it.
817 
818  Note that if we set query = NULL, we must at the same time set
819  query_length = 0, and protect the whole operation with
820  LOCK_thd_data mutex. To avoid crashes in races, if we do not
821  know that thd->query cannot change at the moment, we should print
822  thd->query like this:
823  (1) reserve the LOCK_thd_data mutex;
824  (2) print or copy the value of query and query_length
825  (3) release LOCK_thd_data mutex.
826  This printing is needed at least in SHOW PROCESSLIST and SHOW
827  ENGINE INNODB STATUS.
828  */
829  CSET_STRING query_string;
830 
831  /*
832  In some cases, we may want to modify the query (i.e. replace
833  passwords with their hashes before logging the statement etc.).
834 
835  In case the query was rewritten, the original query will live in
836  query_string, while the rewritten query lives in rewritten_query.
837  If rewritten_query is empty, query_string should be logged.
838  If rewritten_query is non-empty, the rewritten query it contains
839  should be used in logs (general log, slow query log, binary log).
840 
841  Currently, password obfuscation is the only rewriting we do; more
842  may follow at a later date, both pre- and post parsing of the query.
843  Rewriting of binloggable statements must preserve all pertinent
844  information.
845  */
846  String rewritten_query;
847 
848  inline char *query() const { return query_string.str(); }
849  inline uint32 query_length() const { return query_string.length(); }
850  const CHARSET_INFO *query_charset() const { return query_string.charset(); }
851  void set_query_inner(const CSET_STRING &string_arg)
852  {
853  query_string= string_arg;
854  }
855  void set_query_inner(char *query_arg, uint32 query_length_arg,
856  const CHARSET_INFO *cs_arg)
857  {
858  set_query_inner(CSET_STRING(query_arg, query_length_arg, cs_arg));
859  }
860  void reset_query_inner()
861  {
862  set_query_inner(CSET_STRING());
863  }
877  char *db;
878  size_t db_length;
879 
880 public:
881 
882  /* This constructor is called for backup statements */
883  Statement() {}
884 
885  Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg,
886  enum enum_state state_arg, ulong id_arg);
887  virtual ~Statement();
888 
889  /* Assign execution context (note: not all members) of given stmt to self */
890  virtual void set_statement(Statement *stmt);
891  void set_n_backup_statement(Statement *stmt, Statement *backup);
892  void restore_backup_statement(Statement *stmt, Statement *backup);
893  /* return class type */
894  virtual Type type() const;
895 };
896 
897 
909 class Statement_map
910 {
911 public:
912  Statement_map();
913 
914  int insert(THD *thd, Statement *statement);
915 
916  Statement *find_by_name(LEX_STRING *name)
917  {
918  Statement *stmt;
919  stmt= (Statement*)my_hash_search(&names_hash, (uchar*)name->str,
920  name->length);
921  return stmt;
922  }
923 
924  Statement *find(ulong id)
925  {
926  if (last_found_statement == 0 || id != last_found_statement->id)
927  {
928  Statement *stmt;
929  stmt= (Statement *) my_hash_search(&st_hash, (uchar *) &id, sizeof(id));
930  if (stmt && stmt->name.str)
931  return NULL;
932  last_found_statement= stmt;
933  }
934  return last_found_statement;
935  }
936  /*
937  Close all cursors of this connection that use tables of a storage
938  engine that has transaction-specific state and therefore can not
939  survive COMMIT or ROLLBACK. Currently all but MyISAM cursors are closed.
940  CURRENTLY NOT IMPLEMENTED!
941  */
942  void close_transient_cursors();
943  void erase(Statement *statement);
944  /* Erase all statements (calls Statement destructor) */
945  void reset();
946  ~Statement_map();
947 private:
948  HASH st_hash;
949  HASH names_hash;
950  Statement *last_found_statement;
951 };
952 
953 class Ha_trx_info;
954 
955 struct THD_TRANS
956 {
957  /* true is not all entries in the ht[] support 2pc */
958  bool no_2pc;
959  int rw_ha_count;
960  /* storage engines that registered in this transaction */
961  Ha_trx_info *ha_list;
962 
963 private:
964  /*
965  The purpose of this member variable (i.e. flag) is to keep track of
966  statements which cannot be rolled back safely(completely).
967  For example,
968 
969  * statements that modified non-transactional tables. The value
970  MODIFIED_NON_TRANS_TABLE is set within mysql_insert, mysql_update,
971  mysql_delete, etc if a non-transactional table is modified.
972 
973  * 'DROP TEMPORARY TABLE' and 'CREATE TEMPORARY TABLE' statements.
974  The former sets the value CREATED_TEMP_TABLE is set and the latter
975  the value DROPPED_TEMP_TABLE.
976 
977  The tracked statements are modified in scope of:
978 
979  * transaction, when the variable is a member of THD::transaction.all
980 
981  * top-level statement or sub-statement, when the variable is a
982  member of THD::transaction.stmt
983 
984  This member has the following life cycle:
985 
986  * stmt.m_unsafe_rollback_flags is used to keep track of top-level statements
987  which cannot be rolled back safely. At the end of the statement, the value
988  of stmt.m_unsafe_rollback_flags is merged with all.m_unsafe_rollback_flags
989  and gets reset.
990 
991  * all.cannot_safely_rollback is reset at the end of transaction
992 
993  * Since we do not have a dedicated context for execution of a sub-statement,
994  to keep track of non-transactional changes in a sub-statement, we re-use
995  stmt.m_unsafe_rollback_flags. At entrance into a sub-statement, a copy of
996  the value of stmt.m_unsafe_rollback_flags (containing the changes of the
997  outer statement) is saved on stack. Then stmt.m_unsafe_rollback_flags is
998  reset to 0 and the substatement is executed. Then the new value is merged
999  with the saved value.
1000  */
1001 
1002  unsigned int m_unsafe_rollback_flags;
1003  /*
1004  Define the type of statemens which cannot be rolled back safely.
1005  Each type occupies one bit in m_unsafe_rollback_flags.
1006  */
1007  static unsigned int const MODIFIED_NON_TRANS_TABLE= 0x01;
1008  static unsigned int const CREATED_TEMP_TABLE= 0x02;
1009  static unsigned int const DROPPED_TEMP_TABLE= 0x04;
1010 
1011 public:
1012 #ifndef DBUG_OFF
1013  void dbug_unsafe_rollback_flags(const char* msg) const
1014  {
1015  DBUG_PRINT("debug", ("%s.unsafe_rollback_flags: %s%s%s",
1016  msg,
1017  FLAGSTR(m_unsafe_rollback_flags, MODIFIED_NON_TRANS_TABLE),
1018  FLAGSTR(m_unsafe_rollback_flags, CREATED_TEMP_TABLE),
1019  FLAGSTR(m_unsafe_rollback_flags, DROPPED_TEMP_TABLE)));
1020  }
1021 #endif
1022 
1023  bool cannot_safely_rollback() const
1024  {
1025  return m_unsafe_rollback_flags > 0;
1026  }
1027  unsigned int get_unsafe_rollback_flags() const
1028  {
1029  return m_unsafe_rollback_flags;
1030  }
1031  void set_unsafe_rollback_flags(unsigned int flags)
1032  {
1033  DBUG_PRINT("debug", ("set_unsafe_rollback_flags: %d", flags));
1034  m_unsafe_rollback_flags= flags;
1035  }
1036  void add_unsafe_rollback_flags(unsigned int flags)
1037  {
1038  DBUG_PRINT("debug", ("add_unsafe_rollback_flags: %d", flags));
1039  m_unsafe_rollback_flags|= flags;
1040  }
1041  void reset_unsafe_rollback_flags()
1042  {
1043  DBUG_PRINT("debug", ("reset_unsafe_rollback_flags"));
1044  m_unsafe_rollback_flags= 0;
1045  }
1046  void mark_modified_non_trans_table()
1047  {
1048  DBUG_PRINT("debug", ("mark_modified_non_trans_table"));
1049  m_unsafe_rollback_flags|= MODIFIED_NON_TRANS_TABLE;
1050  }
1051  bool has_modified_non_trans_table() const
1052  {
1053  return m_unsafe_rollback_flags & MODIFIED_NON_TRANS_TABLE;
1054  }
1055  void mark_created_temp_table()
1056  {
1057  DBUG_PRINT("debug", ("mark_created_temp_table"));
1058  m_unsafe_rollback_flags|= CREATED_TEMP_TABLE;
1059  }
1060  bool has_created_temp_table() const
1061  {
1062  return m_unsafe_rollback_flags & CREATED_TEMP_TABLE;
1063  }
1064  void mark_dropped_temp_table()
1065  {
1066  DBUG_PRINT("debug", ("mark_dropped_temp_table"));
1067  m_unsafe_rollback_flags|= DROPPED_TEMP_TABLE;
1068  }
1069  bool has_dropped_temp_table() const
1070  {
1071  return m_unsafe_rollback_flags & DROPPED_TEMP_TABLE;
1072  }
1073 
1074  void reset()
1075  {
1076  no_2pc= FALSE;
1077  rw_ha_count= 0;
1078  reset_unsafe_rollback_flags();
1079  }
1080  bool is_empty() const { return ha_list == NULL; }
1081 };
1082 
1100 class Ha_trx_info
1101 {
1102 #ifndef DBUG_OFF
1103  friend const char *
1104  ha_list_names(Ha_trx_info *ha_list, char *const buf_arg)
1105  {
1106  char *buf = buf_arg;
1107  while (ha_list)
1108  {
1109  buf += sprintf(buf, "%s", ha_legacy_type_name(ha_list->m_ht->db_type));
1110  ha_list = ha_list->m_next;
1111  if (ha_list)
1112  buf += sprintf(buf, ", ");
1113  }
1114  if (buf == buf_arg)
1115  sprintf(buf, "<NONE>");
1116  return buf_arg;
1117  }
1118 #endif
1119 
1120 public:
1122  void register_ha(THD_TRANS *trans, handlerton *ht_arg)
1123  {
1124  DBUG_ENTER("Ha_trx_info::register_ha");
1125  DBUG_PRINT("enter", ("trans: 0x%llx, ht: 0x%llx (%s)",
1126  (ulonglong) trans, (ulonglong) ht_arg,
1127  ha_legacy_type_name(ht_arg->db_type)));
1128  DBUG_ASSERT(m_flags == 0);
1129  DBUG_ASSERT(m_ht == NULL);
1130  DBUG_ASSERT(m_next == NULL);
1131 
1132  m_ht= ht_arg;
1133  m_flags= (int) TRX_READ_ONLY; /* Assume read-only at start. */
1134 
1135  m_next= trans->ha_list;
1136  trans->ha_list= this;
1137  DBUG_VOID_RETURN;
1138  }
1139 
1141  void reset()
1142  {
1143  DBUG_ENTER("Ha_trx_info::reset");
1144  m_next= NULL;
1145  m_ht= NULL;
1146  m_flags= 0;
1147  DBUG_VOID_RETURN;
1148  }
1149 
1150  Ha_trx_info() { reset(); }
1151 
1152  void set_trx_read_write()
1153  {
1154  DBUG_ASSERT(is_started());
1155  m_flags|= (int) TRX_READ_WRITE;
1156  }
1157  bool is_trx_read_write() const
1158  {
1159  DBUG_ASSERT(is_started());
1160  return m_flags & (int) TRX_READ_WRITE;
1161  }
1162  bool is_started() const { return m_ht != NULL; }
1164  void coalesce_trx_with(const Ha_trx_info *stmt_trx)
1165  {
1166  /*
1167  Must be called only after the transaction has been started.
1168  Can be called many times, e.g. when we have many
1169  read-write statements in a transaction.
1170  */
1171  DBUG_ASSERT(is_started());
1172  if (stmt_trx->is_trx_read_write())
1173  set_trx_read_write();
1174  }
1175  Ha_trx_info *next() const
1176  {
1177  DBUG_ASSERT(is_started());
1178  return m_next;
1179  }
1180  handlerton *ht() const
1181  {
1182  DBUG_ASSERT(is_started());
1183  return m_ht;
1184  }
1185 private:
1186  enum { TRX_READ_ONLY= 0, TRX_READ_WRITE= 1 };
1188  Ha_trx_info *m_next;
1194  handlerton *m_ht;
1200  uchar m_flags;
1201 };
1202 
1203 struct st_savepoint {
1204  struct st_savepoint *prev;
1205  char *name;
1206  uint length;
1207  Ha_trx_info *ha_list;
1209  MDL_savepoint mdl_savepoint;
1210 };
1211 
1212 enum xa_states {XA_NOTR=0, XA_ACTIVE, XA_IDLE, XA_PREPARED, XA_ROLLBACK_ONLY};
1213 extern const char *xa_state_names[];
1214 
1215 typedef struct st_xid_state {
1216  /* For now, this is only used to catch duplicated external xids */
1217  XID xid; // transaction identifier
1218  enum xa_states xa_state; // used by external XA only
1219  bool in_thd;
1220  /* Error reported by the Resource Manager (RM) to the Transaction Manager. */
1221  uint rm_error;
1222 } XID_STATE;
1223 
1224 extern mysql_mutex_t LOCK_xid_cache;
1225 extern HASH xid_cache;
1226 bool xid_cache_init(void);
1227 void xid_cache_free(void);
1228 XID_STATE *xid_cache_search(XID *xid);
1229 bool xid_cache_insert(XID *xid, enum xa_states xa_state);
1230 bool xid_cache_insert(XID_STATE *xid_state);
1231 void xid_cache_delete(XID_STATE *xid_state);
1232 
1238 class Security_context {
1239 private:
1240 
1241 String host;
1242 String ip;
1243 String external_user;
1244 public:
1245  Security_context() {} /* Remove gcc warning */
1246  /*
1247  host - host of the client
1248  user - user of the client, set to NULL until the user has been read from
1249  the connection
1250  priv_user - The user privilege we are using. May be "" for anonymous user.
1251  ip - client IP
1252  */
1253  char *user;
1254  char priv_user[USERNAME_LENGTH];
1255  char proxy_user[USERNAME_LENGTH + MAX_HOSTNAME + 5];
1256  /* The host privilege we are using */
1257  char priv_host[MAX_HOSTNAME];
1258  /* points to host if host is available, otherwise points to ip */
1259  const char *host_or_ip;
1260  ulong master_access; /* Global privileges from mysql.user */
1261  ulong db_access; /* Privileges for current db */
1262  bool password_expired; /* password expiration flag */
1263 
1264  void init();
1265  void destroy();
1266  void skip_grants();
1267  inline char *priv_host_name()
1268  {
1269  return (*priv_host ? priv_host : (char *)"%");
1270  }
1271 
1272  bool set_user(char *user_arg);
1273  String *get_host();
1274  String *get_ip();
1275  String *get_external_user();
1276  void set_host(const char *p);
1277  void set_ip(const char *p);
1278  void set_external_user(const char *p);
1279  void set_host(const char *str, size_t len);
1280 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1281  bool
1282  change_security_context(THD *thd,
1283  LEX_STRING *definer_user,
1284  LEX_STRING *definer_host,
1285  LEX_STRING *db,
1286  Security_context **backup);
1287 
1288  void
1289  restore_security_context(THD *thd, Security_context *backup);
1290 #endif
1291  bool user_matches(Security_context *);
1292 };
1293 
1294 
1300 class Log_throttle
1301 {
1305  ulonglong window_end;
1306 
1311  const ulong window_size;
1312 
1319  ulong count;
1320 
1321 protected:
1326  const char *summary_template;
1327 
1331  void new_window(ulonglong now);
1332 
1341  bool inc_log_count(ulong rate) { return (++count > rate); }
1342 
1348  bool in_window(ulonglong now) const { return (now < window_end); };
1349 
1360  ulong prepare_summary(ulong rate);
1361 
1366  Log_throttle(ulong window_usecs, const char *msg)
1367  : window_end(0), window_size(window_usecs),
1368  count(0), summary_template(msg)
1369  {}
1370 
1371 public:
1376  static const ulong LOG_THROTTLE_WINDOW_SIZE= 60000000;
1377 };
1378 
1379 
1385 class Slow_log_throttle : public Log_throttle
1386 {
1387 private:
1394  Security_context aggregate_sctx;
1395 
1400  ulonglong total_exec_time;
1401 
1406  ulonglong total_lock_time;
1407 
1412  ulong *rate;
1413 
1418  bool (*log_summary)(THD *, const char *, uint);
1419 
1423  mysql_mutex_t *LOCK_log_throttle;
1424 
1428  void new_window(ulonglong now);
1429 
1433  void print_summary(THD *thd, ulong suppressed,
1434  ulonglong print_lock_time,
1435  ulonglong print_exec_time);
1436 
1437 public:
1438 
1445  Slow_log_throttle(ulong *threshold, mysql_mutex_t *lock, ulong window_usecs,
1446  bool (*logger)(THD *, const char *, uint),
1447  const char *msg);
1448 
1462  bool flush(THD *thd);
1463 
1471  bool log(THD *thd, bool eligible);
1472 };
1473 
1474 
1480 class Error_log_throttle : public Log_throttle
1481 {
1482 private:
1486  void (*log_summary)(const char *, ...);
1487 
1491  void print_summary(ulong suppressed)
1492  {
1493  (*log_summary)(summary_template, suppressed);
1494  }
1495 
1496 public:
1502  Error_log_throttle(ulong window_usecs,
1503  void (*logger)(const char*, ...),
1504  const char *msg)
1505  : Log_throttle(window_usecs, msg), log_summary(logger)
1506  {}
1507 
1518  bool flush(THD *thd);
1519 
1526  bool log(THD *thd);
1527 };
1528 
1529 
1530 extern Slow_log_throttle log_throttle_qni;
1531 
1532 
1540 struct Item_change_record: public ilink<Item_change_record>
1541 {
1542  Item **place;
1543  Item *old_value;
1544 };
1545 
1546 typedef I_List<Item_change_record> Item_change_list;
1547 
1548 
1554 enum enum_locked_tables_mode
1555 {
1556  LTM_NONE= 0,
1557  LTM_LOCK_TABLES,
1558  LTM_PRELOCKED,
1559  LTM_PRELOCKED_UNDER_LOCK_TABLES
1560 };
1561 
1562 
1569 class Open_tables_state
1570 {
1571 private:
1592  Dynamic_array<Reprepare_observer *> m_reprepare_observers;
1593 
1594 public:
1595  Reprepare_observer *get_reprepare_observer() const
1596  {
1597  return
1598  m_reprepare_observers.elements() > 0 ?
1599  *m_reprepare_observers.back() :
1600  NULL;
1601  }
1602 
1603  void push_reprepare_observer(Reprepare_observer *o)
1604  { m_reprepare_observers.append(o); }
1605 
1606  Reprepare_observer *pop_reprepare_observer()
1607  { return m_reprepare_observers.pop(); }
1608 
1609  void reset_reprepare_observers()
1610  { m_reprepare_observers.clear(); }
1611 
1612 public:
1617  TABLE *open_tables;
1625  TABLE *temporary_tables;
1626  TABLE *derived_tables;
1627  /*
1628  During a MySQL session, one can lock tables in two modes: automatic
1629  or manual. In automatic mode all necessary tables are locked just before
1630  statement execution, and all acquired locks are stored in 'lock'
1631  member. Unlocking takes place automatically as well, when the
1632  statement ends.
1633  Manual mode comes into play when a user issues a 'LOCK TABLES'
1634  statement. In this mode the user can only use the locked tables.
1635  Trying to use any other tables will give an error.
1636  The locked tables are also stored in this member, however,
1637  thd->locked_tables_mode is turned on. Manual locking is described in
1638  the 'LOCK_TABLES' chapter of the MySQL manual.
1639  See also lock_tables() for details.
1640  */
1641  MYSQL_LOCK *lock;
1642 
1643  /*
1644  CREATE-SELECT keeps an extra lock for the table being
1645  created. This field is used to keep the extra lock available for
1646  lower level routines, which would otherwise miss that lock.
1647  */
1648  MYSQL_LOCK *extra_lock;
1649 
1650  /*
1651  Enum enum_locked_tables_mode and locked_tables_mode member are
1652  used to indicate whether the so-called "locked tables mode" is on,
1653  and what kind of mode is active.
1654 
1655  Locked tables mode is used when it's necessary to open and
1656  lock many tables at once, for usage across multiple
1657  (sub-)statements.
1658  This may be necessary either for queries that use stored functions
1659  and triggers, in which case the statements inside functions and
1660  triggers may be executed many times, or for implementation of
1661  LOCK TABLES, in which case the opened tables are reused by all
1662  subsequent statements until a call to UNLOCK TABLES.
1663 
1664  The kind of locked tables mode employed for stored functions and
1665  triggers is also called "prelocked mode".
1666  In this mode, first open_tables() call to open the tables used
1667  in a statement analyses all functions used by the statement
1668  and adds all indirectly used tables to the list of tables to
1669  open and lock.
1670  It also marks the parse tree of the statement as requiring
1671  prelocking. After that, lock_tables() locks the entire list
1672  of tables and changes THD::locked_tables_modeto LTM_PRELOCKED.
1673  All statements executed inside functions or triggers
1674  use the prelocked tables, instead of opening their own ones.
1675  Prelocked mode is turned off automatically once close_thread_tables()
1676  of the main statement is called.
1677  */
1678  enum enum_locked_tables_mode locked_tables_mode;
1679  uint current_tablenr;
1680 
1681  enum enum_flags {
1682  BACKUPS_AVAIL = (1U << 0) /* There are backups available */
1683  };
1684 
1685  /*
1686  Flags with information about the open tables state.
1687  */
1688  uint state_flags;
1695  Open_tables_state() : state_flags(0U) { }
1696 
1697  void set_open_tables_state(Open_tables_state *state);
1698 
1699  void reset_open_tables_state();
1700 };
1701 
1702 
1709 class Open_tables_backup: public Open_tables_state
1710 {
1711 public:
1719  MDL_savepoint mdl_system_tables_svp;
1720 };
1721 
1727 /* Defines used for Sub_statement_state::in_sub_stmt */
1728 
1729 #define SUB_STMT_TRIGGER 1
1730 #define SUB_STMT_FUNCTION 2
1731 
1732 
1733 class Sub_statement_state
1734 {
1735 public:
1736  ulonglong option_bits;
1737  ulonglong first_successful_insert_id_in_prev_stmt;
1738  ulonglong first_successful_insert_id_in_cur_stmt, insert_id_for_cur_row;
1739  Discrete_interval auto_inc_interval_for_cur_row;
1740  Discrete_intervals_list auto_inc_intervals_forced;
1741  ulonglong limit_found_rows;
1742  ha_rows cuted_fields, sent_row_count, examined_row_count;
1743  ulong client_capabilities;
1744  uint in_sub_stmt;
1745  bool enable_slow_log;
1746  bool last_insert_id_used;
1747  SAVEPOINT *savepoints;
1748  enum enum_check_fields count_cuted_fields;
1749 };
1750 
1751 
1752 /* Flags for the THD::system_thread variable */
1753 enum enum_thread_type
1754 {
1755  NON_SYSTEM_THREAD= 0,
1756  SYSTEM_THREAD_DELAYED_INSERT= 1,
1757  SYSTEM_THREAD_SLAVE_IO= 2,
1758  SYSTEM_THREAD_SLAVE_SQL= 4,
1759  SYSTEM_THREAD_NDBCLUSTER_BINLOG= 8,
1760  SYSTEM_THREAD_EVENT_SCHEDULER= 16,
1761  SYSTEM_THREAD_EVENT_WORKER= 32,
1762  SYSTEM_THREAD_INFO_REPOSITORY= 64,
1763  SYSTEM_THREAD_SLAVE_WORKER= 128
1764 };
1765 
1766 inline char const *
1767 show_system_thread(enum_thread_type thread)
1768 {
1769 #define RETURN_NAME_AS_STRING(NAME) case (NAME): return #NAME
1770  switch (thread) {
1771  static char buf[64];
1772  RETURN_NAME_AS_STRING(NON_SYSTEM_THREAD);
1773  RETURN_NAME_AS_STRING(SYSTEM_THREAD_DELAYED_INSERT);
1774  RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_IO);
1775  RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_SQL);
1776  RETURN_NAME_AS_STRING(SYSTEM_THREAD_NDBCLUSTER_BINLOG);
1777  RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_SCHEDULER);
1778  RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_WORKER);
1779  RETURN_NAME_AS_STRING(SYSTEM_THREAD_INFO_REPOSITORY);
1780  RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_WORKER);
1781  default:
1782  sprintf(buf, "<UNKNOWN SYSTEM THREAD: %d>", thread);
1783  return buf;
1784  }
1785 #undef RETURN_NAME_AS_STRING
1786 }
1787 
1793 class Internal_error_handler
1794 {
1795 protected:
1796  Internal_error_handler() :
1797  m_prev_internal_handler(NULL)
1798  {}
1799 
1800  virtual ~Internal_error_handler() {}
1801 
1802 public:
1827  virtual bool handle_condition(THD *thd,
1828  uint sql_errno,
1829  const char* sqlstate,
1830  Sql_condition::enum_warning_level level,
1831  const char* msg,
1832  Sql_condition ** cond_hdl) = 0;
1833 
1834 private:
1835  Internal_error_handler *m_prev_internal_handler;
1836  friend class THD;
1837 };
1838 
1839 
1845 class Dummy_error_handler : public Internal_error_handler
1846 {
1847 public:
1848  bool handle_condition(THD *thd,
1849  uint sql_errno,
1850  const char* sqlstate,
1851  Sql_condition::enum_warning_level level,
1852  const char* msg,
1853  Sql_condition ** cond_hdl)
1854  {
1855  /* Ignore error */
1856  return TRUE;
1857  }
1858 };
1859 
1860 
1868 class Drop_table_error_handler : public Internal_error_handler
1869 {
1870 public:
1871  Drop_table_error_handler() {}
1872 
1873 public:
1874  bool handle_condition(THD *thd,
1875  uint sql_errno,
1876  const char* sqlstate,
1877  Sql_condition::enum_warning_level level,
1878  const char* msg,
1879  Sql_condition ** cond_hdl);
1880 
1881 private:
1882 };
1883 
1884 
1910 class Locked_tables_list
1911 {
1912 private:
1913  MEM_ROOT m_locked_tables_root;
1914  TABLE_LIST *m_locked_tables;
1915  TABLE_LIST **m_locked_tables_last;
1917  TABLE **m_reopen_array;
1924  size_t m_locked_tables_count;
1925 public:
1926  Locked_tables_list()
1927  :m_locked_tables(NULL),
1928  m_locked_tables_last(&m_locked_tables),
1929  m_reopen_array(NULL),
1930  m_locked_tables_count(0)
1931  {
1932  init_sql_alloc(&m_locked_tables_root, MEM_ROOT_BLOCK_SIZE, 0);
1933  }
1934  void unlock_locked_tables(THD *thd);
1935  ~Locked_tables_list()
1936  {
1937  unlock_locked_tables(0);
1938  }
1939  bool init_locked_tables(THD *thd);
1940  TABLE_LIST *locked_tables() { return m_locked_tables; }
1941  void unlink_from_list(THD *thd, TABLE_LIST *table_list,
1942  bool remove_from_locked_tables);
1943  void unlink_all_closed_tables(THD *thd,
1944  MYSQL_LOCK *lock,
1945  size_t reopen_count);
1946  bool reopen_tables(THD *thd);
1947 };
1948 
1949 
1954 struct Ha_data
1955 {
1960  void *ha_ptr;
1971  Ha_trx_info ha_info[2];
1976  plugin_ref lock;
1977  Ha_data() :ha_ptr(NULL) {}
1978 };
1979 
1985 class Global_read_lock
1986 {
1987 public:
1988  enum enum_grl_state
1989  {
1990  GRL_NONE,
1991  GRL_ACQUIRED,
1992  GRL_ACQUIRED_AND_BLOCKS_COMMIT
1993  };
1994 
1995  Global_read_lock()
1996  : m_state(GRL_NONE),
1997  m_mdl_global_shared_lock(NULL),
1998  m_mdl_blocks_commits_lock(NULL)
1999  {}
2000 
2001  bool lock_global_read_lock(THD *thd);
2002  void unlock_global_read_lock(THD *thd);
2007  bool can_acquire_protection() const
2008  {
2009  if (m_state)
2010  {
2011  my_error(ER_CANT_UPDATE_WITH_READLOCK, MYF(0));
2012  return TRUE;
2013  }
2014  return FALSE;
2015  }
2016  bool make_global_read_lock_block_commit(THD *thd);
2017  bool is_acquired() const { return m_state != GRL_NONE; }
2018  void set_explicit_lock_duration(THD *thd);
2019 private:
2020  enum_grl_state m_state;
2026  MDL_ticket *m_mdl_global_shared_lock;
2032  MDL_ticket *m_mdl_blocks_commits_lock;
2033 };
2034 
2035 extern "C" void my_message_sql(uint error, const char *str, myf MyFlags);
2036 
2037 
2038 /*
2039  Convert microseconds since epoch to timeval.
2040  @param micro_time Microseconds.
2041  @param OUT tm A timeval variable to write to.
2042 */
2043 static inline void
2044 my_micro_time_to_timeval(ulonglong micro_time, struct timeval *tm)
2045 {
2046  tm->tv_sec= (long) (micro_time / 1000000);
2047  tm->tv_usec= (long) (micro_time % 1000000);
2048 }
2049 
2056 class THD :public MDL_context_owner,
2057  public Statement,
2058  public Open_tables_state
2059 {
2060 private:
2061  inline bool is_stmt_prepare() const
2062  { DBUG_ASSERT(0); return Statement::is_stmt_prepare(); }
2063 
2064  inline bool is_stmt_prepare_or_first_sp_execute() const
2065  { DBUG_ASSERT(0); return Statement::is_stmt_prepare_or_first_sp_execute(); }
2066 
2067  inline bool is_stmt_prepare_or_first_stmt_execute() const
2068  { DBUG_ASSERT(0); return Statement::is_stmt_prepare_or_first_stmt_execute(); }
2069 
2070  inline bool is_conventional() const
2071  { DBUG_ASSERT(0); return Statement::is_conventional(); }
2072 
2073 public:
2074  MDL_context mdl_context;
2075 
2076  /* Used to execute base64 coded binlog events in MySQL server */
2077  Relay_log_info* rli_fake;
2078  /* Slave applier execution context */
2079  Relay_log_info* rli_slave;
2080 
2081  void reset_for_next_command();
2082  /*
2083  Constant for THD::where initialization in the beginning of every query.
2084 
2085  It's needed because we do not save/restore THD::where normally during
2086  primary (non subselect) query execution.
2087  */
2088  static const char * const DEFAULT_WHERE;
2089 
2090 #ifdef EMBEDDED_LIBRARY
2091  struct st_mysql *mysql;
2092  unsigned long client_stmt_id;
2093  unsigned long client_param_count;
2094  struct st_mysql_bind *client_params;
2095  char *extra_data;
2096  ulong extra_length;
2097  struct st_mysql_data *cur_data;
2098  struct st_mysql_data *first_data;
2099  struct st_mysql_data **data_tail;
2100  void clear_data_list();
2101  struct st_mysql_data *alloc_new_dataset();
2102  /*
2103  In embedded server it points to the statement that is processed
2104  in the current query. We store some results directly in statement
2105  fields then.
2106  */
2107  struct st_mysql_stmt *current_stmt;
2108 #endif
2109 #ifdef HAVE_QUERY_CACHE
2110  Query_cache_tls query_cache_tls;
2111 #endif
2112  NET net; // client connection descriptor
2114  NET_SERVER m_net_server_extension;
2115  Protocol *protocol; // Current protocol
2116  Protocol_text protocol_text; // Normal protocol
2117  Protocol_binary protocol_binary; // Binary protocol
2118  HASH user_vars; // hash for user variables
2119  String packet; // dynamic buffer for network I/O
2120  String convert_buffer; // buffer for charset conversions
2121  struct rand_struct rand; // used for authentication
2122  struct system_variables variables; // Changeable local variables
2123  struct system_status_var status_var; // Per thread statistic vars
2124  struct system_status_var *initial_status_var; /* used by show status */
2125  THR_LOCK_INFO lock_info; // Locking info of this thread
2133  mysql_mutex_t LOCK_thd_data;
2134 
2135  /* all prepared statements and cursors of this connection */
2136  Statement_map stmt_map;
2137  /*
2138  A pointer to the stack frame of handle_one_connection(),
2139  which is called first in the thread for handling a client
2140  */
2141  char *thread_stack;
2142 
2146  char *catalog;
2147 
2161  Security_context main_security_ctx;
2162  Security_context *security_ctx;
2163 
2164  /*
2165  Points to info-string that we show in SHOW PROCESSLIST
2166  You are supposed to update thd->proc_info only if you have coded
2167  a time-consuming piece that MySQL can get stuck in for a long time.
2168 
2169  Set it using the thd_proc_info(THD *thread, const char *message)
2170  macro/function.
2171 
2172  This member is accessed and assigned without any synchronization.
2173  Therefore, it may point only to constant (statically
2174  allocated) strings, which memory won't go away over time.
2175  */
2176  const char *proc_info;
2177 
2178 private:
2179  unsigned int m_current_stage_key;
2180 
2181 public:
2182  void enter_stage(const PSI_stage_info *stage,
2183  PSI_stage_info *old_stage,
2184  const char *calling_func,
2185  const char *calling_file,
2186  const unsigned int calling_line);
2187 
2188  const char *get_proc_info() const
2189  { return proc_info; }
2190 
2191  /*
2192  Used in error messages to tell user in what part of MySQL we found an
2193  error. E. g. when where= "having clause", if fix_fields() fails, user
2194  will know that the error was in having clause.
2195  */
2196  const char *where;
2197 
2198  ulong client_capabilities; /* What the client supports */
2199  ulong max_client_packet_length;
2200 
2201  HASH handler_tables_hash;
2202  /*
2203  One thread can hold up to one named user-level lock. This variable
2204  points to a lock object if the lock is present. See item_func.cc and
2205  chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK.
2206  */
2207  User_level_lock *ull;
2208 #ifndef DBUG_OFF
2209  uint dbug_sentry; // watch out for memory corruption
2210 #endif
2211  struct st_my_thread_var *mysys_var;
2212 
2213 private:
2218  enum enum_server_command m_command;
2219 
2220 public:
2221  uint32 unmasked_server_id;
2222  uint32 server_id;
2223  uint32 file_id; // for LOAD DATA INFILE
2224  /* remote (peer) port */
2225  uint16 peer_port;
2226  struct timeval start_time;
2227  struct timeval user_time;
2228  // track down slow pthread_create
2229  ulonglong prior_thr_create_utime, thr_create_utime;
2230  ulonglong start_utime, utime_after_lock;
2231 
2232  thr_lock_type update_lock_default;
2233  Delayed_insert *di;
2234 
2235  /* <> 0 if we are inside of trigger or stored function. */
2236  uint in_sub_stmt;
2237 
2246  uint fill_status_recursion_level;
2247 
2248  /* container for handler's private per-connection data */
2249  Ha_data ha_data[MAX_HA];
2250 
2251  /*
2252  Position of first event in Binlog
2253  *after* last event written by this
2254  thread.
2255  */
2256  event_coordinates binlog_next_event_pos;
2257  void set_next_event_pos(const char* _filename, ulonglong _pos);
2258  void clear_next_event_pos();
2259 
2260  /*
2261  Ptr to row event extra data to be written to Binlog /
2262  received from Binlog.
2263 
2264  */
2265  uchar* binlog_row_event_extra_data;
2266  static bool binlog_row_event_extra_data_eq(const uchar* a,
2267  const uchar* b);
2268 
2269 #ifndef MYSQL_CLIENT
2270  int binlog_setup_trx_data();
2271 
2272  /*
2273  Public interface to write RBR events to the binlog
2274  */
2275  int binlog_write_table_map(TABLE *table, bool is_transactional,
2276  bool binlog_rows_query);
2277  int binlog_write_row(TABLE* table, bool is_transactional,
2278  const uchar *new_data,
2279  const uchar* extra_row_info);
2280  int binlog_delete_row(TABLE* table, bool is_transactional,
2281  const uchar *old_data,
2282  const uchar* extra_row_info);
2283  int binlog_update_row(TABLE* table, bool is_transactional,
2284  const uchar *old_data, const uchar *new_data,
2285  const uchar* extra_row_info);
2286  void binlog_prepare_row_images(TABLE* table);
2287 
2288  void set_server_id(uint32 sid) { server_id = sid; }
2289 
2290  /*
2291  Member functions to handle pending event for row-level logging.
2292  */
2293  template <class RowsEventT> Rows_log_event*
2294  binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id,
2295  size_t needed,
2296  bool is_transactional,
2297  RowsEventT* hint,
2298  const uchar* extra_row_info);
2299  Rows_log_event* binlog_get_pending_rows_event(bool is_transactional) const;
2300  inline int binlog_flush_pending_rows_event(bool stmt_end)
2301  {
2302  return (binlog_flush_pending_rows_event(stmt_end, FALSE) ||
2303  binlog_flush_pending_rows_event(stmt_end, TRUE));
2304  }
2305  int binlog_flush_pending_rows_event(bool stmt_end, bool is_transactional);
2306 
2315  int is_current_stmt_binlog_format_row() const {
2316  DBUG_ASSERT(current_stmt_binlog_format == BINLOG_FORMAT_STMT ||
2317  current_stmt_binlog_format == BINLOG_FORMAT_ROW);
2318  return current_stmt_binlog_format == BINLOG_FORMAT_ROW;
2319  }
2321  inline bool optimizer_switch_flag(ulonglong flag) const
2322  {
2323  return (variables.optimizer_switch & flag);
2324  }
2325 
2326  enum binlog_filter_state
2327  {
2328  BINLOG_FILTER_UNKNOWN,
2329  BINLOG_FILTER_CLEAR,
2330  BINLOG_FILTER_SET
2331  };
2332 
2333  inline void reset_binlog_local_stmt_filter()
2334  {
2335  m_binlog_filter_state= BINLOG_FILTER_UNKNOWN;
2336  }
2337 
2338  inline void clear_binlog_local_stmt_filter()
2339  {
2340  DBUG_ASSERT(m_binlog_filter_state == BINLOG_FILTER_UNKNOWN);
2341  m_binlog_filter_state= BINLOG_FILTER_CLEAR;
2342  }
2343 
2344  inline void set_binlog_local_stmt_filter()
2345  {
2346  DBUG_ASSERT(m_binlog_filter_state == BINLOG_FILTER_UNKNOWN);
2347  m_binlog_filter_state= BINLOG_FILTER_SET;
2348  }
2349 
2350  inline binlog_filter_state get_binlog_local_stmt_filter()
2351  {
2352  return m_binlog_filter_state;
2353  }
2354 
2355 private:
2363  binlog_filter_state m_binlog_filter_state;
2364 
2369  enum_binlog_format current_stmt_binlog_format;
2370 
2383  uint32 binlog_unsafe_warning_flags;
2384 
2385  /*
2386  Number of outstanding table maps, i.e., table maps in the
2387  transaction cache.
2388  */
2389  uint binlog_table_maps;
2390  /*
2391  MTS: db names listing to be updated by the query databases
2392  */
2393  List<char> *binlog_accessed_db_names;
2394 
2409  const char *m_trans_log_file;
2410  const char *m_trans_fixed_log_file;
2411  my_off_t m_trans_end_pos;
2414 public:
2415  void issue_unsafe_warnings();
2416 
2417  uint get_binlog_table_maps() const {
2418  return binlog_table_maps;
2419  }
2420  void clear_binlog_table_maps() {
2421  binlog_table_maps= 0;
2422  }
2423 
2424  /*
2425  MTS: accessor to binlog_accessed_db_names list
2426  */
2427  List<char> * get_binlog_accessed_db_names()
2428  {
2429  return binlog_accessed_db_names;
2430  }
2431 
2432  /*
2433  MTS: resetter of binlog_accessed_db_names list normally
2434  at the end of the query execution
2435  */
2436  void clear_binlog_accessed_db_names() { binlog_accessed_db_names= NULL; }
2437 
2438  /* MTS: method inserts a new unique name into binlog_updated_dbs */
2439  void add_to_binlog_accessed_dbs(const char *db);
2440 
2441 #endif /* MYSQL_CLIENT */
2442 
2443 public:
2444 
2445  struct st_transactions {
2446  SAVEPOINT *savepoints;
2447  THD_TRANS all; // Trans since BEGIN WORK
2448  THD_TRANS stmt; // Trans for current statement
2449  XID_STATE xid_state;
2450  Rows_log_event *m_pending_rows_event;
2451 
2452  /*
2453  Tables changed in transaction (that must be invalidated in query cache).
2454  List contain only transactional tables, that not invalidated in query
2455  cache (instead of full list of changed in transaction tables).
2456  */
2457  CHANGED_TABLE_LIST* changed_tables;
2458  MEM_ROOT mem_root; // Transaction-life memory allocation pool
2459 
2460  /*
2461  (Mostly) binlog-specific fields use while flushing the caches
2462  and committing transactions.
2463  We don't use bitfield any more in the struct. Modification will
2464  be lost when concurrently updating multiple bit fields. It will
2465  cause a race condition in a multi-threaded application. And we
2466  already caught a race condition case between xid_written and
2467  ready_preempt in MYSQL_BIN_LOG::ordered_commit.
2468  */
2469  struct {
2470  bool enabled; // see ha_enable_transaction()
2471  bool pending; // Is the transaction commit pending?
2472  bool xid_written; // The session wrote an XID
2473  bool real_commit; // Is this a "real" commit?
2474  bool commit_low; // see MYSQL_BIN_LOG::ordered_commit
2475  bool run_hooks; // Call the after_commit hook
2476 #ifndef DBUG_OFF
2477  bool ready_preempt; // internal in MYSQL_BIN_LOG::ordered_commit
2478 #endif
2479  } flags;
2480 
2481  void cleanup()
2482  {
2483  DBUG_ENTER("THD::st_transaction::cleanup");
2484  changed_tables= 0;
2485  savepoints= 0;
2486 
2487  /*
2488  If rm_error is raised, it means that this piece of a distributed
2489  transaction has failed and must be rolled back. But the user must
2490  rollback it explicitly, so don't start a new distributed XA until
2491  then.
2492  */
2493  if (!xid_state.rm_error)
2494  xid_state.xid.null();
2495  free_root(&mem_root,MYF(MY_KEEP_PREALLOC));
2496  DBUG_VOID_RETURN;
2497  }
2498  my_bool is_active()
2499  {
2500  return (all.ha_list != NULL);
2501  }
2502  st_transactions()
2503  {
2504  memset(this, 0, sizeof(*this));
2505  xid_state.xid.null();
2506  init_sql_alloc(&mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0);
2507  }
2508  void push_unsafe_rollback_warnings(THD *thd)
2509  {
2510  if (all.has_modified_non_trans_table())
2511  push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
2512  ER_WARNING_NOT_COMPLETE_ROLLBACK,
2513  ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
2514 
2515  if (all.has_created_temp_table())
2516  push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
2517  ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE,
2518  ER(ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE));
2519 
2520  if (all.has_dropped_temp_table())
2521  push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
2522  ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE,
2523  ER(ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE));
2524  }
2525  void merge_unsafe_rollback_flags()
2526  {
2527  /*
2528  Merge stmt.unsafe_rollback_flags to all.unsafe_rollback_flags. If
2529  the statement cannot be rolled back safely, the transaction including
2530  this statement definitely cannot rolled back safely.
2531  */
2532  all.add_unsafe_rollback_flags(stmt.get_unsafe_rollback_flags());
2533  }
2534  } transaction;
2535  Global_read_lock global_read_lock;
2536  Field *dup_field;
2537 #ifndef __WIN__
2538  sigset_t signals;
2539 #endif
2540 #ifdef SIGNAL_WITH_VIO_SHUTDOWN
2541  Vio* active_vio;
2542 #endif
2543  /*
2544  This is to track items changed during execution of a prepared
2545  statement/stored procedure. It's created by
2546  register_item_tree_change() in memory root of THD, and freed in
2547  rollback_item_tree_changes(). For conventional execution it's always
2548  empty.
2549  */
2550  Item_change_list change_list;
2551 
2552  /*
2553  A permanent memory area of the statement. For conventional
2554  execution, the parsed tree and execution runtime reside in the same
2555  memory root. In this case stmt_arena points to THD. In case of
2556  a prepared statement or a stored procedure statement, thd->mem_root
2557  conventionally points to runtime memory, and thd->stmt_arena
2558  points to the memory of the PS/SP, where the parsed tree of the
2559  statement resides. Whenever you need to perform a permanent
2560  transformation of a parsed tree, you should allocate new memory in
2561  stmt_arena, to allow correct re-execution of PS/SP.
2562  Note: in the parser, stmt_arena == thd, even for PS/SP.
2563  */
2564  Query_arena *stmt_arena;
2565 
2566  /*
2567  map for tables that will be updated for a multi-table update query
2568  statement, for other query statements, this will be zero.
2569  */
2570  table_map table_map_for_update;
2571 
2572  /* Tells if LAST_INSERT_ID(#) was called for the current statement */
2573  bool arg_of_last_insert_id_function;
2574  /*
2575  ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for
2576  insertion into an auto_increment column".
2577  */
2578  /*
2579  This is the first autogenerated insert id which was *successfully*
2580  inserted by the previous statement (exactly, if the previous statement
2581  didn't successfully insert an autogenerated insert id, then it's the one
2582  of the statement before, etc).
2583  It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#).
2584  It is returned by LAST_INSERT_ID().
2585  */
2586  ulonglong first_successful_insert_id_in_prev_stmt;
2587  /*
2588  Variant of the above, used for storing in statement-based binlog. The
2589  difference is that the one above can change as the execution of a stored
2590  function progresses, while the one below is set once and then does not
2591  change (which is the value which statement-based binlog needs).
2592  */
2593  ulonglong first_successful_insert_id_in_prev_stmt_for_binlog;
2594  /*
2595  This is the first autogenerated insert id which was *successfully*
2596  inserted by the current statement. It is maintained only to set
2597  first_successful_insert_id_in_prev_stmt when statement ends.
2598  */
2599  ulonglong first_successful_insert_id_in_cur_stmt;
2600  /*
2601  We follow this logic:
2602  - when stmt starts, first_successful_insert_id_in_prev_stmt contains the
2603  first insert id successfully inserted by the previous stmt.
2604  - as stmt makes progress, handler::insert_id_for_cur_row changes;
2605  every time get_auto_increment() is called,
2606  auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the
2607  reserved interval (if statement-based binlogging).
2608  - at first successful insertion of an autogenerated value,
2609  first_successful_insert_id_in_cur_stmt is set to
2610  handler::insert_id_for_cur_row.
2611  - when stmt goes to binlog,
2612  auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if
2613  non-empty.
2614  - when stmt ends, first_successful_insert_id_in_prev_stmt is set to
2615  first_successful_insert_id_in_cur_stmt.
2616  */
2617  /*
2618  stmt_depends_on_first_successful_insert_id_in_prev_stmt is set when
2619  LAST_INSERT_ID() is used by a statement.
2620  If it is set, first_successful_insert_id_in_prev_stmt_for_binlog will be
2621  stored in the statement-based binlog.
2622  This variable is CUMULATIVE along the execution of a stored function or
2623  trigger: if one substatement sets it to 1 it will stay 1 until the
2624  function/trigger ends, thus making sure that
2625  first_successful_insert_id_in_prev_stmt_for_binlog does not change anymore
2626  and is propagated to the caller for binlogging.
2627  */
2628  bool stmt_depends_on_first_successful_insert_id_in_prev_stmt;
2629  /*
2630  List of auto_increment intervals reserved by the thread so far, for
2631  storage in the statement-based binlog.
2632  Note that its minimum is not first_successful_insert_id_in_cur_stmt:
2633  assuming a table with an autoinc column, and this happens:
2634  INSERT INTO ... VALUES(3);
2635  SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL);
2636  then the latter INSERT will insert no rows
2637  (first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3"
2638  in the binlog is still needed; the list's minimum will contain 3.
2639  This variable is cumulative: if several statements are written to binlog
2640  as one (stored functions or triggers are used) this list is the
2641  concatenation of all intervals reserved by all statements.
2642  */
2643  Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog;
2644  /* Used by replication and SET INSERT_ID */
2645  Discrete_intervals_list auto_inc_intervals_forced;
2646  /*
2647  There is BUG#19630 where statement-based replication of stored
2648  functions/triggers with two auto_increment columns breaks.
2649  We however ensure that it works when there is 0 or 1 auto_increment
2650  column; our rules are
2651  a) on master, while executing a top statement involving substatements,
2652  first top- or sub- statement to generate auto_increment values wins the
2653  exclusive right to see its values be written to binlog (the write
2654  will be done by the statement or its caller), and the losers won't see
2655  their values be written to binlog.
2656  b) on slave, while replicating a top statement involving substatements,
2657  first top- or sub- statement to need to read auto_increment values from
2658  the master's binlog wins the exclusive right to read them (so the losers
2659  won't read their values from binlog but instead generate on their own).
2660  a) implies that we mustn't backup/restore
2661  auto_inc_intervals_in_cur_stmt_for_binlog.
2662  b) implies that we mustn't backup/restore auto_inc_intervals_forced.
2663 
2664  If there are more than 1 auto_increment columns, then intervals for
2665  different columns may mix into the
2666  auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong,
2667  but there is no point in preventing this mixing by preventing intervals
2668  from the secondly inserted column to come into the list, as such
2669  prevention would be wrong too.
2670  What will happen in the case of
2671  INSERT INTO t1 (auto_inc) VALUES(NULL);
2672  where t1 has a trigger which inserts into an auto_inc column of t2, is
2673  that in binlog we'll store the interval of t1 and the interval of t2 (when
2674  we store intervals, soon), then in slave, t1 will use both intervals, t2
2675  will use none; if t1 inserts the same number of rows as on master,
2676  normally the 2nd interval will not be used by t1, which is fine. t2's
2677  values will be wrong if t2's internal auto_increment counter is different
2678  from what it was on master (which is likely). In 5.1, in mixed binlogging
2679  mode, row-based binlogging is used for such cases where two
2680  auto_increment columns are inserted.
2681  */
2682  inline void record_first_successful_insert_id_in_cur_stmt(ulonglong id_arg)
2683  {
2684  if (first_successful_insert_id_in_cur_stmt == 0)
2685  first_successful_insert_id_in_cur_stmt= id_arg;
2686  }
2687  inline ulonglong read_first_successful_insert_id_in_prev_stmt(void)
2688  {
2689  if (!stmt_depends_on_first_successful_insert_id_in_prev_stmt)
2690  {
2691  /* It's the first time we read it */
2692  first_successful_insert_id_in_prev_stmt_for_binlog=
2693  first_successful_insert_id_in_prev_stmt;
2694  stmt_depends_on_first_successful_insert_id_in_prev_stmt= 1;
2695  }
2696  return first_successful_insert_id_in_prev_stmt;
2697  }
2698  /*
2699  Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#"
2700  (mysqlbinlog). We'll soon add a variant which can take many intervals in
2701  argument.
2702  */
2703  inline void force_one_auto_inc_interval(ulonglong next_id)
2704  {
2705  auto_inc_intervals_forced.empty(); // in case of multiple SET INSERT_ID
2706  auto_inc_intervals_forced.append(next_id, ULONGLONG_MAX, 0);
2707  }
2708 
2709  ulonglong limit_found_rows;
2710 
2711 private:
2741  longlong m_row_count_func; /* For the ROW_COUNT() function */
2742 
2743 public:
2744  inline longlong get_row_count_func() const
2745  {
2746  return m_row_count_func;
2747  }
2748 
2749  inline void set_row_count_func(longlong row_count_func)
2750  {
2751  m_row_count_func= row_count_func;
2752  }
2753 
2754  ha_rows cuted_fields;
2755 
2756 private:
2761  ha_rows m_sent_row_count;
2762 
2773  ha_rows m_examined_row_count;
2774 
2775 private:
2776  USER_CONN *m_user_connect;
2777 
2778 public:
2779  void set_user_connect(USER_CONN *uc);
2780  const USER_CONN* get_user_connect()
2781  { return m_user_connect; }
2782 
2783  void increment_user_connections_counter();
2784  void decrement_user_connections_counter();
2785 
2786  void increment_con_per_hour_counter();
2787 
2788  void increment_updates_counter();
2789 
2790  void increment_questions_counter();
2791 
2792  void time_out_user_resource_limits();
2793 
2794 public:
2795  ha_rows get_sent_row_count() const
2796  { return m_sent_row_count; }
2797 
2798  ha_rows get_examined_row_count() const
2799  { return m_examined_row_count; }
2800 
2801  void set_sent_row_count(ha_rows count);
2802  void set_examined_row_count(ha_rows count);
2803 
2804  void inc_sent_row_count(ha_rows count);
2805  void inc_examined_row_count(ha_rows count);
2806 
2807  void inc_status_created_tmp_disk_tables();
2808  void inc_status_created_tmp_files();
2809  void inc_status_created_tmp_tables();
2810  void inc_status_select_full_join();
2811  void inc_status_select_full_range_join();
2812  void inc_status_select_range();
2813  void inc_status_select_range_check();
2814  void inc_status_select_scan();
2815  void inc_status_sort_merge_passes();
2816  void inc_status_sort_range();
2817  void inc_status_sort_rows(ha_rows count);
2818  void inc_status_sort_scan();
2819  void set_status_no_index_used();
2820  void set_status_no_good_index_used();
2821 
2822  const CHARSET_INFO *db_charset;
2823 #if defined(ENABLED_PROFILING)
2824  PROFILING profiling;
2825 #endif
2826 
2828  PSI_statement_locker *m_statement_psi;
2829 #ifdef HAVE_PSI_STATEMENT_INTERFACE
2830 
2831  PSI_statement_locker_state m_statement_state;
2832 #endif /* HAVE_PSI_STATEMENT_INTERFACE */
2833 
2834  PSI_idle_locker *m_idle_psi;
2835 #ifdef HAVE_PSI_IDLE_INTERFACE
2836 
2837  PSI_idle_locker_state m_idle_state;
2838 #endif /* HAVE_PSI_IDLE_INTERFACE */
2839 
2840  bool m_server_idle;
2841 
2842  /*
2843  Id of current query. Statement can be reused to execute several queries
2844  query_id is global in context of the whole MySQL server.
2845  ID is automatically generated from mutex-protected counter.
2846  It's used in handler code for various purposes: to check which columns
2847  from table are necessary for this select, to check if it's necessary to
2848  update auto-updatable fields (like auto_increment and timestamp).
2849  */
2850  query_id_t query_id;
2851  ulong col_access;
2852 
2853  /* Statement id is thread-wide. This counter is used to generate ids */
2854  ulong statement_id_counter;
2855  ulong rand_saved_seed1, rand_saved_seed2;
2856  pthread_t real_id; /* For debugging */
2857  my_thread_id thread_id;
2858  uint tmp_table;
2859  uint server_status,open_options;
2860  enum enum_thread_type system_thread;
2861  uint select_number; //number of select (used for EXPLAIN)
2862  /*
2863  Current or next transaction isolation level.
2864  When a connection is established, the value is taken from
2865  @@session.tx_isolation (default transaction isolation for
2866  the session), which is in turn taken from @@global.tx_isolation
2867  (the global value).
2868  If there is no transaction started, this variable
2869  holds the value of the next transaction's isolation level.
2870  When a transaction starts, the value stored in this variable
2871  becomes "actual".
2872  At transaction commit or rollback, we assign this variable
2873  again from @@session.tx_isolation.
2874  The only statement that can otherwise change the value
2875  of this variable is SET TRANSACTION ISOLATION LEVEL.
2876  Its purpose is to effect the isolation level of the next
2877  transaction in this session. When this statement is executed,
2878  the value in this variable is changed. However, since
2879  this statement is only allowed when there is no active
2880  transaction, this assignment (naturally) only affects the
2881  upcoming transaction.
2882  At the end of the current active transaction the value is
2883  be reset again from @@session.tx_isolation, as described
2884  above.
2885  */
2886  enum_tx_isolation tx_isolation;
2887  /*
2888  Current or next transaction access mode.
2889  See comment above regarding tx_isolation.
2890  */
2891  bool tx_read_only;
2892  enum_check_fields count_cuted_fields;
2893 
2894  DYNAMIC_ARRAY user_var_events; /* For user variables replication */
2895  MEM_ROOT *user_var_events_alloc; /* Allocate above array elements here */
2896 
2901  THD *next_to_commit;
2902 
2910  void set_trans_pos(const char *file, my_off_t pos)
2911  {
2912  DBUG_ENTER("THD::set_trans_pos");
2913  DBUG_ASSERT(((file == 0) && (pos == 0)) || ((file != 0) && (pos != 0)));
2914  if (file)
2915  {
2916  DBUG_PRINT("enter", ("file: %s, pos: %llu", file, pos));
2917  // Only the file name should be used, not the full path
2918  m_trans_log_file= file + dirname_length(file);
2919  MEM_ROOT *log_file_mem_root= &main_mem_root;
2920  if (!m_trans_fixed_log_file)
2921  m_trans_fixed_log_file= new (log_file_mem_root) char[FN_REFLEN + 1];
2922  m_trans_fixed_log_file= strdup_root(log_file_mem_root,
2923  file + dirname_length(file));
2924  }
2925  else
2926  {
2927  m_trans_log_file= NULL;
2928  m_trans_fixed_log_file= NULL;
2929  }
2930 
2931  m_trans_end_pos= pos;
2932  DBUG_PRINT("return", ("m_trans_log_file: %s, m_trans_fixed_log_file: %s, "
2933  "m_trans_end_pos: %llu", m_trans_log_file,
2934  m_trans_fixed_log_file, m_trans_end_pos));
2935  DBUG_VOID_RETURN;
2936  }
2937 
2938  void get_trans_pos(const char **file_var, my_off_t *pos_var) const
2939  {
2940  DBUG_ENTER("THD::get_trans_pos");
2941  if (file_var)
2942  *file_var = m_trans_log_file;
2943  if (pos_var)
2944  *pos_var= m_trans_end_pos;
2945  DBUG_PRINT("return", ("file: %s, pos: %llu",
2946  file_var ? *file_var : "<none>",
2947  pos_var ? *pos_var : 0));
2948  DBUG_VOID_RETURN;
2949  }
2950 
2951  void get_trans_fixed_pos(const char **file_var, my_off_t *pos_var) const
2952  {
2953  DBUG_ENTER("THD::get_trans_fixed_pos");
2954  if (file_var)
2955  *file_var = m_trans_fixed_log_file;
2956  if (pos_var)
2957  *pos_var= m_trans_end_pos;
2958  DBUG_PRINT("return", ("file: %s, pos: %llu",
2959  file_var ? *file_var : "<none>",
2960  pos_var ? *pos_var : 0));
2961  DBUG_VOID_RETURN;
2962  }
2966  /*
2967  Error code from committing or rolling back the transaction.
2968  */
2969  enum Commit_error
2970  {
2971  CE_NONE= 0,
2972  CE_FLUSH_ERROR,
2973  CE_COMMIT_ERROR,
2974  CE_ERROR_COUNT
2975  } commit_error;
2976 
2977  /*
2978  Define durability properties that engines may check to
2979  improve performance.
2980  */
2981  enum durability_properties durability_property;
2982 
2983  /*
2984  If checking this in conjunction with a wait condition, please
2985  include a check after enter_cond() if you want to avoid a race
2986  condition. For details see the implementation of awake(),
2987  especially the "broadcast" part.
2988  */
2989  enum killed_state
2990  {
2991  NOT_KILLED=0,
2992  KILL_BAD_DATA=1,
2993  KILL_CONNECTION=ER_SERVER_SHUTDOWN,
2994  KILL_QUERY=ER_QUERY_INTERRUPTED,
2995  KILLED_NO_VALUE /* means neither of the states */
2996  };
2997  killed_state volatile killed;
2998 
2999  /* scramble - random string sent to client on handshake */
3000  char scramble[SCRAMBLE_LENGTH+1];
3001 
3003  bool slave_thread, one_shot_set;
3004  bool no_errors;
3005  uchar password;
3013  bool is_fatal_error;
3019  bool transaction_rollback_request;
3031  bool is_fatal_sub_stmt_error;
3032  bool query_start_used, query_start_usec_used;
3033  bool rand_used, time_zone_used;
3034  /* for IS NULL => = last_insert_id() fix in remove_eq_conds() */
3035  bool substitute_null_with_insert_id;
3036  bool in_lock_tables;
3043  bool is_slave_error;
3044  bool bootstrap;
3045 
3047  bool thread_specific_used;
3052  bool charset_is_system_charset, charset_is_collation_connection;
3053  bool charset_is_character_set_filesystem;
3054  bool enable_slow_log; /* enable slow log for current statement */
3055  bool abort_on_warning;
3056  bool got_warning; /* Set on call to push_warning() */
3057  /* set during loop of derived table processing */
3058  bool derived_tables_processing;
3059  my_bool tablespace_op; /* This is TRUE in DISCARD/IMPORT TABLESPACE */
3060 
3062  sp_rcontext *sp_runtime_ctx;
3063  sp_cache *sp_proc_cache;
3064  sp_cache *sp_func_cache;
3065 
3067  uint query_name_consts;
3068 
3069  /*
3070  If we do a purge of binary logs, log index info of the threads
3071  that are currently reading it needs to be adjusted. To do that
3072  each thread that is using LOG_INFO needs to adjust the pointer to it
3073  */
3074  LOG_INFO* current_linfo;
3075  NET* slave_net; // network connection from slave -> m.
3076  /* Used by the sys_var class to store temporary values */
3077  union
3078  {
3079  my_bool my_bool_value;
3080  long long_value;
3081  ulong ulong_value;
3082  ulonglong ulonglong_value;
3083  double double_value;
3084  } sys_var_tmp;
3085 
3086  struct {
3087  /*
3088  If true, mysql_bin_log::write(Log_event) call will not write events to
3089  binlog, and maintain 2 below variables instead (use
3090  mysql_bin_log.start_union_events to turn this on)
3091  */
3092  bool do_union;
3093  /*
3094  If TRUE, at least one mysql_bin_log::write(Log_event) call has been
3095  made after last mysql_bin_log.start_union_events() call.
3096  */
3097  bool unioned_events;
3098  /*
3099  If TRUE, at least one mysql_bin_log::write(Log_event e), where
3100  e.cache_stmt == TRUE call has been made after last
3101  mysql_bin_log.start_union_events() call.
3102  */
3103  bool unioned_events_trans;
3104 
3105  /*
3106  'queries' (actually SP statements) that run under inside this binlog
3107  union have thd->query_id >= first_query_id.
3108  */
3109  query_id_t first_query_id;
3110  } binlog_evt_union;
3111 
3117  Parser_state *m_parser_state;
3118 
3119  Locked_tables_list locked_tables_list;
3120 
3121 #ifdef WITH_PARTITION_STORAGE_ENGINE
3122  partition_info *work_part_info;
3123 #endif
3124 
3125 #ifndef EMBEDDED_LIBRARY
3126 
3131  DYNAMIC_ARRAY audit_class_plugins;
3136  unsigned long audit_class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE];
3137 #endif
3138 
3139 #if defined(ENABLED_DEBUG_SYNC)
3140  /* Debug Sync facility. See debug_sync.cc. */
3141  struct st_debug_sync_control *debug_sync_control;
3142 #endif /* defined(ENABLED_DEBUG_SYNC) */
3143 
3144  // We don't want to load/unload plugins for unit tests.
3145  bool m_enable_plugins;
3146 
3147  THD(bool enable_plugins= true);
3148 
3149  /*
3150  The THD dtor is effectively split in two:
3151  THD::release_resources() and ~THD().
3152 
3153  We want to minimize the time we hold LOCK_thread_count,
3154  so when destroying a global thread, do:
3155 
3156  thd->release_resources()
3157  mysql_mutex_lock(&LOCK_thread_count);
3158  remove_global_thread(thd);
3159  mysql_mutex_unlock(&LOCK_thread_count);
3160  delete thd;
3161  */
3162  ~THD();
3163 
3164  void release_resources();
3165  bool release_resources_done() const { return m_release_resources_done; }
3166 
3167 private:
3168  bool m_release_resources_done;
3169  bool cleanup_done;
3170  void cleanup(void);
3171 
3172 public:
3173  void init(void);
3174  /*
3175  Initialize memory roots necessary for query processing and (!)
3176  pre-allocate memory for it. We can't do that in THD constructor because
3177  there are use cases (acl_init, delayed inserts, watcher threads,
3178  killing mysqld) where it's vital to not allocate excessive and not used
3179  memory. Note, that we still don't return error from init_for_queries():
3180  if preallocation fails, we should notice that at the first call to
3181  alloc_root.
3182  */
3183  void init_for_queries(Relay_log_info *rli= NULL);
3184  void change_user(void);
3185  void cleanup_after_query();
3186  bool store_globals();
3187  bool restore_globals();
3188 #ifdef SIGNAL_WITH_VIO_SHUTDOWN
3189  inline void set_active_vio(Vio* vio)
3190  {
3191  mysql_mutex_lock(&LOCK_thd_data);
3192  active_vio = vio;
3193  mysql_mutex_unlock(&LOCK_thd_data);
3194  }
3195  inline void clear_active_vio()
3196  {
3197  mysql_mutex_lock(&LOCK_thd_data);
3198  active_vio = 0;
3199  mysql_mutex_unlock(&LOCK_thd_data);
3200  }
3201  void shutdown_active_vio();
3202 #endif
3203  void awake(THD::killed_state state_to_set);
3204 
3206  void disconnect();
3207 
3208 #ifndef MYSQL_CLIENT
3209  enum enum_binlog_query_type {
3210  /* The query can be logged in row format or in statement format. */
3211  ROW_QUERY_TYPE,
3212 
3213  /* The query has to be logged in statement format. */
3214  STMT_QUERY_TYPE,
3215 
3216  QUERY_TYPE_COUNT
3217  };
3218 
3219  int binlog_query(enum_binlog_query_type qtype,
3220  char const *query, ulong query_len, bool is_trans,
3221  bool direct, bool suppress_use,
3222  int errcode);
3223 #endif
3224 
3225  // Begin implementation of MDL_context_owner interface.
3226 
3227  inline void
3228  enter_cond(mysql_cond_t *cond, mysql_mutex_t* mutex,
3229  const PSI_stage_info *stage, PSI_stage_info *old_stage,
3230  const char *src_function, const char *src_file,
3231  int src_line)
3232  {
3233  DBUG_ENTER("THD::enter_cond");
3234  mysql_mutex_assert_owner(mutex);
3235  DBUG_PRINT("debug", ("thd: 0x%llx, mysys_var: 0x%llx, current_mutex: 0x%llx -> 0x%llx",
3236  (ulonglong) this,
3237  (ulonglong) mysys_var,
3238  (ulonglong) mysys_var->current_mutex,
3239  (ulonglong) mutex));
3240  mysys_var->current_mutex = mutex;
3241  mysys_var->current_cond = cond;
3242  enter_stage(stage, old_stage, src_function, src_file, src_line);
3243  DBUG_VOID_RETURN;
3244  }
3245  inline void exit_cond(const PSI_stage_info *stage,
3246  const char *src_function, const char *src_file,
3247  int src_line)
3248  {
3249  DBUG_ENTER("THD::exit_cond");
3250  /*
3251  Putting the mutex unlock in thd->exit_cond() ensures that
3252  mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is
3253  locked (if that would not be the case, you'll get a deadlock if someone
3254  does a THD::awake() on you).
3255  */
3256  DBUG_PRINT("debug", ("thd: 0x%llx, mysys_var: 0x%llx, current_mutex: 0x%llx -> 0x%llx",
3257  (ulonglong) this,
3258  (ulonglong) mysys_var,
3259  (ulonglong) mysys_var->current_mutex,
3260  0ULL));
3261  mysql_mutex_unlock(mysys_var->current_mutex);
3262  mysql_mutex_lock(&mysys_var->mutex);
3263  mysys_var->current_mutex = 0;
3264  mysys_var->current_cond = 0;
3265  enter_stage(stage, NULL, src_function, src_file, src_line);
3266  mysql_mutex_unlock(&mysys_var->mutex);
3267  DBUG_VOID_RETURN;
3268  }
3269 
3270  virtual int is_killed() { return killed; }
3271  virtual THD* get_thd() { return this; }
3272 
3296  virtual bool notify_shared_lock(MDL_context_owner *ctx_in_use,
3297  bool needs_thr_lock_abort);
3298 
3299  // End implementation of MDL_context_owner interface.
3300 
3301  inline sql_mode_t datetime_flags() const
3302  {
3303  return variables.sql_mode &
3304  (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE | MODE_INVALID_DATES);
3305  }
3306  inline bool is_strict_mode() const
3307  {
3308  return test(variables.sql_mode & (MODE_STRICT_TRANS_TABLES |
3309  MODE_STRICT_ALL_TABLES));
3310  }
3311  inline Time_zone *time_zone()
3312  {
3313  time_zone_used= 1;
3314  return variables.time_zone;
3315  }
3316  inline time_t query_start()
3317  {
3318  query_start_used= 1;
3319  return start_time.tv_sec;
3320  }
3321  inline long query_start_usec()
3322  {
3323  query_start_usec_used= 1;
3324  return start_time.tv_usec;
3325  }
3326  inline timeval query_start_timeval()
3327  {
3328  query_start_used= query_start_usec_used= true;
3329  return start_time;
3330  }
3331  timeval query_start_timeval_trunc(uint decimals);
3332  inline void set_time()
3333  {
3334  start_utime= utime_after_lock= my_micro_time();
3335  if (user_time.tv_sec || user_time.tv_usec)
3336  {
3337  start_time= user_time;
3338  }
3339  else
3340  my_micro_time_to_timeval(start_utime, &start_time);
3341 
3342 #ifdef HAVE_PSI_THREAD_INTERFACE
3343  PSI_THREAD_CALL(set_thread_start_time)(start_time.tv_sec);
3344 #endif
3345  }
3346  inline void set_current_time()
3347  {
3348  my_micro_time_to_timeval(my_micro_time(), &start_time);
3349 #ifdef HAVE_PSI_THREAD_INTERFACE
3350  PSI_THREAD_CALL(set_thread_start_time)(start_time.tv_sec);
3351 #endif
3352  }
3353  inline void set_time(const struct timeval *t)
3354  {
3355  start_time= user_time= *t;
3356  start_utime= utime_after_lock= my_micro_time();
3357 #ifdef HAVE_PSI_THREAD_INTERFACE
3358  PSI_THREAD_CALL(set_thread_start_time)(start_time.tv_sec);
3359 #endif
3360  }
3361  /*TODO: this will be obsolete when we have support for 64 bit my_time_t */
3362  inline bool is_valid_time()
3363  {
3364  return (IS_TIME_T_VALID_FOR_TIMESTAMP(start_time.tv_sec));
3365  }
3366  void set_time_after_lock()
3367  {
3368  utime_after_lock= my_micro_time();
3369  MYSQL_SET_STATEMENT_LOCK_TIME(m_statement_psi, (utime_after_lock - start_utime));
3370  }
3371  ulonglong current_utime() { return my_micro_time(); }
3380  void update_server_status()
3381  {
3382  ulonglong end_utime_of_query= current_utime();
3383  if (end_utime_of_query > utime_after_lock + variables.long_query_time)
3384  server_status|= SERVER_QUERY_WAS_SLOW;
3385  }
3386  inline ulonglong found_rows(void)
3387  {
3388  return limit_found_rows;
3389  }
3413  inline bool in_multi_stmt_transaction_mode() const
3414  {
3415  return variables.option_bits & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN);
3416  }
3450  inline bool in_active_multi_stmt_transaction() const
3451  {
3452  return server_status & SERVER_STATUS_IN_TRANS;
3453  }
3454  inline bool fill_derived_tables()
3455  {
3456  return !stmt_arena->is_stmt_prepare() && !lex->only_view_structure();
3457  }
3458  inline bool fill_information_schema_tables()
3459  {
3460  return !stmt_arena->is_stmt_prepare();
3461  }
3462  inline void* trans_alloc(unsigned int size)
3463  {
3464  return alloc_root(&transaction.mem_root,size);
3465  }
3466 
3467  LEX_STRING *make_lex_string(LEX_STRING *lex_str,
3468  const char* str, uint length,
3469  bool allocate_lex_string);
3470 
3471  bool convert_string(LEX_STRING *to, const CHARSET_INFO *to_cs,
3472  const char *from, uint from_length,
3473  const CHARSET_INFO *from_cs);
3474 
3475  bool convert_string(String *s, const CHARSET_INFO *from_cs,
3476  const CHARSET_INFO *to_cs);
3477 
3478  void add_changed_table(TABLE *table);
3479  void add_changed_table(const char *key, long key_length);
3480  CHANGED_TABLE_LIST * changed_table_dup(const char *key, long key_length);
3481  int send_explain_fields(select_result *result);
3482 
3490  inline void clear_error()
3491  {
3492  DBUG_ENTER("clear_error");
3493  if (get_stmt_da()->is_error())
3494  get_stmt_da()->reset_diagnostics_area();
3495  is_slave_error= 0;
3496  DBUG_VOID_RETURN;
3497  }
3498 #ifndef EMBEDDED_LIBRARY
3499  inline bool vio_ok() const { return net.vio != 0; }
3501  bool is_connected()
3502  {
3503  /*
3504  All system threads (e.g., the slave IO thread) are connected but
3505  not using vio. So this function always returns true for all
3506  system threads.
3507  */
3508  return system_thread || (vio_ok() ? vio_is_connected(net.vio) : FALSE);
3509  }
3510 #else
3511  inline bool vio_ok() const { return TRUE; }
3512  inline bool is_connected() { return TRUE; }
3513 #endif
3514 
3519  inline void fatal_error()
3520  {
3521  DBUG_ASSERT(get_stmt_da()->is_error() || killed);
3522  is_fatal_error= 1;
3523  DBUG_PRINT("error",("Fatal error set"));
3524  }
3538  inline bool is_error() const { return get_stmt_da()->is_error(); }
3539 
3541  Diagnostics_area *get_stmt_da()
3542  { return m_stmt_da; }
3543 
3545  const Diagnostics_area *get_stmt_da() const
3546  { return m_stmt_da; }
3547 
3549  void set_stmt_da(Diagnostics_area *da)
3550  { m_stmt_da= da; }
3551 
3552 public:
3553  inline const CHARSET_INFO *charset()
3554  { return variables.character_set_client; }
3555  void update_charset();
3556 
3557  void change_item_tree(Item **place, Item *new_value)
3558  {
3559  /* TODO: check for OOM condition here */
3560  if (!stmt_arena->is_conventional())
3561  {
3562  DBUG_PRINT("info",
3563  ("change_item_tree place %p old_value %p new_value %p",
3564  place, *place, new_value));
3565  nocheck_register_item_tree_change(place, *place, mem_root);
3566  }
3567  *place= new_value;
3568  }
3569 
3570 /*
3571  Find and update change record of an underlying item.
3572 
3573  @param old_ref The old place of moved expression.
3574  @param new_ref The new place of moved expression.
3575  @details
3576  During permanent transformations, e.g. join flattening in simplify_joins,
3577  a condition could be moved from one place to another, e.g. from on_expr
3578  to WHERE condition. If the moved condition has replaced some other with
3579  change_item_tree() function, the change record will restore old value
3580  to the wrong place during rollback_item_tree_changes. This function goes
3581  through the list of change records, and replaces Item_change_record::place.
3582 */
3583  void change_item_tree_place(Item **old_ref, Item **new_ref);
3584  void nocheck_register_item_tree_change(Item **place, Item *old_value,
3585  MEM_ROOT *runtime_memroot);
3586  void rollback_item_tree_changes();
3587 
3588  /*
3589  Cleanup statement parse state (parse tree, lex) and execution
3590  state after execution of a non-prepared SQL statement.
3591  */
3592  void end_statement();
3593  inline int killed_errno() const
3594  {
3595  killed_state killed_val; /* to cache the volatile 'killed' */
3596  return (killed_val= killed) != KILL_BAD_DATA ? killed_val : 0;
3597  }
3598  inline void send_kill_message() const
3599  {
3600  int err= killed_errno();
3601  if (err && !get_stmt_da()->is_set())
3602  {
3603  if ((err == KILL_CONNECTION) && !shutdown_in_progress)
3604  err = KILL_QUERY;
3605  /*
3606  KILL is fatal because:
3607  - if a condition handler was allowed to trap and ignore a KILL, one
3608  could create routines which the DBA could not kill
3609  - INSERT/UPDATE IGNORE should fail: if KILL arrives during
3610  JOIN::optimize(), statement cannot possibly run as its caller expected
3611  => "OK" would be misleading the caller.
3612  */
3613  my_message(err, ER(err), MYF(ME_FATALERROR));
3614  }
3615  }
3616  /* return TRUE if we will abort query if we make a warning now */
3617  inline bool really_abort_on_warning()
3618  {
3619  return (abort_on_warning &&
3620  (!transaction.stmt.cannot_safely_rollback() ||
3621  (variables.sql_mode & MODE_STRICT_ALL_TABLES)));
3622  }
3623  void set_status_var_init();
3624  void reset_n_backup_open_tables_state(Open_tables_backup *backup);
3625  void restore_backup_open_tables_state(Open_tables_backup *backup);
3626  void reset_sub_statement_state(Sub_statement_state *backup, uint new_state);
3627  void restore_sub_statement_state(Sub_statement_state *backup);
3628  void set_n_backup_active_arena(Query_arena *set, Query_arena *backup);
3629  void restore_active_arena(Query_arena *set, Query_arena *backup);
3630 
3631  /*
3632  @todo Make these methods private or remove them completely. Only
3633  decide_logging_format should call them. /Sven
3634  */
3635  inline void set_current_stmt_binlog_format_row_if_mixed()
3636  {
3637  DBUG_ENTER("set_current_stmt_binlog_format_row_if_mixed");
3638  /*
3639  This should only be called from decide_logging_format.
3640 
3641  @todo Once we have ensured this, uncomment the following
3642  statement, remove the big comment below that, and remove the
3643  in_sub_stmt==0 condition from the following 'if'.
3644  */
3645  /* DBUG_ASSERT(in_sub_stmt == 0); */
3646  /*
3647  If in a stored/function trigger, the caller should already have done the
3648  change. We test in_sub_stmt to prevent introducing bugs where people
3649  wouldn't ensure that, and would switch to row-based mode in the middle
3650  of executing a stored function/trigger (which is too late, see also
3651  reset_current_stmt_binlog_format_row()); this condition will make their
3652  tests fail and so force them to propagate the
3653  lex->binlog_row_based_if_mixed upwards to the caller.
3654  */
3655  if ((variables.binlog_format == BINLOG_FORMAT_MIXED) &&
3656  (in_sub_stmt == 0))
3657  set_current_stmt_binlog_format_row();
3658 
3659  DBUG_VOID_RETURN;
3660  }
3661  inline void set_current_stmt_binlog_format_row()
3662  {
3663  DBUG_ENTER("set_current_stmt_binlog_format_row");
3664  current_stmt_binlog_format= BINLOG_FORMAT_ROW;
3665  DBUG_VOID_RETURN;
3666  }
3667  inline void clear_current_stmt_binlog_format_row()
3668  {
3669  DBUG_ENTER("clear_current_stmt_binlog_format_row");
3670  current_stmt_binlog_format= BINLOG_FORMAT_STMT;
3671  DBUG_VOID_RETURN;
3672  }
3673  inline void reset_current_stmt_binlog_format_row()
3674  {
3675  DBUG_ENTER("reset_current_stmt_binlog_format_row");
3676  /*
3677  If there are temporary tables, don't reset back to
3678  statement-based. Indeed it could be that:
3679  CREATE TEMPORARY TABLE t SELECT UUID(); # row-based
3680  # and row-based does not store updates to temp tables
3681  # in the binlog.
3682  INSERT INTO u SELECT * FROM t; # stmt-based
3683  and then the INSERT will fail as data inserted into t was not logged.
3684  So we continue with row-based until the temp table is dropped.
3685  If we are in a stored function or trigger, we mustn't reset in the
3686  middle of its execution (as the binary logging way of a stored function
3687  or trigger is decided when it starts executing, depending for example on
3688  the caller (for a stored function: if caller is SELECT or
3689  INSERT/UPDATE/DELETE...).
3690  */
3691  DBUG_PRINT("debug",
3692  ("temporary_tables: %s, in_sub_stmt: %s, system_thread: %s",
3693  YESNO(temporary_tables), YESNO(in_sub_stmt),
3694  show_system_thread(system_thread)));
3695  if (in_sub_stmt == 0)
3696  {
3697  if (variables.binlog_format == BINLOG_FORMAT_ROW)
3698  set_current_stmt_binlog_format_row();
3699  else if (temporary_tables == NULL)
3700  clear_current_stmt_binlog_format_row();
3701  }
3702  DBUG_VOID_RETURN;
3703  }
3704 
3706  Gtid_set *get_gtid_next_list()
3707  {
3708  return variables.gtid_next_list.is_non_null ?
3709  variables.gtid_next_list.gtid_set : NULL;
3710  }
3711 
3713  const Gtid_set *get_gtid_next_list_const() const
3714  {
3715  return const_cast<THD *>(this)->get_gtid_next_list();
3716  }
3717 
3723  Group_cache *get_group_cache(bool is_transactional);
3724 
3731  Gtid owned_gtid;
3737  Gtid_set owned_gtid_set;
3738 
3739  void clear_owned_gtids()
3740  {
3741  if (owned_gtid.sidno == -1)
3742  {
3743 #ifdef HAVE_GTID_NEXT_LIST
3744  owned_gtid_set.clear();
3745 #else
3746  DBUG_ASSERT(0);
3747 #endif
3748  }
3749  owned_gtid.sidno= 0;
3750  }
3751 
3773  bool set_db(const char *new_db, size_t new_db_len)
3774  {
3775  bool result;
3776  /*
3777  Acquiring mutex LOCK_thd_data as we either free the memory allocated
3778  for the database and reallocating the memory for the new db or memcpy
3779  the new_db to the db.
3780  */
3781  mysql_mutex_lock(&LOCK_thd_data);
3782  /* Do not reallocate memory if current chunk is big enough. */
3783  if (db && new_db && db_length >= new_db_len)
3784  memcpy(db, new_db, new_db_len+1);
3785  else
3786  {
3787  my_free(db);
3788  if (new_db)
3789  db= my_strndup(new_db, new_db_len, MYF(MY_WME | ME_FATALERROR));
3790  else
3791  db= NULL;
3792  }
3793  db_length= db ? new_db_len : 0;
3794  mysql_mutex_unlock(&LOCK_thd_data);
3795  result= new_db && !db;
3796 #ifdef HAVE_PSI_THREAD_INTERFACE
3797  if (result)
3798  PSI_THREAD_CALL(set_thread_db)(new_db, static_cast<int>(new_db_len));
3799 #endif
3800  return result;
3801  }
3802 
3814  void reset_db(char *new_db, size_t new_db_len)
3815  {
3816  db= new_db;
3817  db_length= new_db_len;
3818 #ifdef HAVE_PSI_THREAD_INTERFACE
3819  PSI_THREAD_CALL(set_thread_db)(new_db, static_cast<int>(new_db_len));
3820 #endif
3821  }
3822  /*
3823  Copy the current database to the argument. Use the current arena to
3824  allocate memory for a deep copy: current database may be freed after
3825  a statement is parsed but before it's executed.
3826  */
3827  bool copy_db_to(char **p_db, size_t *p_db_length)
3828  {
3829  if (db == NULL)
3830  {
3831  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
3832  return TRUE;
3833  }
3834  *p_db= strmake(db, db_length);
3835  *p_db_length= db_length;
3836  return FALSE;
3837  }
3838  thd_scheduler scheduler;
3839 
3840 public:
3841  inline Internal_error_handler *get_internal_handler()
3842  { return m_internal_handler; }
3843 
3848  void push_internal_handler(Internal_error_handler *handler);
3849 
3850 private:
3860  bool handle_condition(uint sql_errno,
3861  const char* sqlstate,
3862  Sql_condition::enum_warning_level level,
3863  const char* msg,
3864  Sql_condition ** cond_hdl);
3865 
3866 public:
3870  Internal_error_handler *pop_internal_handler();
3871 
3872  Opt_trace_context opt_trace;
3873 
3877  void raise_error(uint code);
3878 
3883  void raise_error_printf(uint code, ...);
3884 
3889  void raise_warning(uint code);
3890 
3895  void raise_warning_printf(uint code, ...);
3896 
3901  void raise_note(uint code);
3902 
3907  void raise_note_printf(uint code, ...);
3908 
3909 private:
3910  /*
3911  Only the implementation of the SIGNAL and RESIGNAL statements
3912  is permitted to raise SQL conditions in a generic way,
3913  or to raise them by bypassing handlers (RESIGNAL).
3914  To raise a SQL condition, the code should use the public
3915  raise_error() or raise_warning() methods provided by class THD.
3916  */
3917  friend class Sql_cmd_common_signal;
3918  friend class Sql_cmd_signal;
3919  friend class Sql_cmd_resignal;
3920  friend void push_warning(THD*, Sql_condition::enum_warning_level, uint, const char*);
3921  friend void my_message_sql(uint, const char *, myf);
3922 
3931  Sql_condition*
3932  raise_condition(uint sql_errno,
3933  const char* sqlstate,
3934  Sql_condition::enum_warning_level level,
3935  const char* msg);
3936 
3937 public:
3939  virtual void set_statement(Statement *stmt);
3940 
3941  void set_command(enum enum_server_command command);
3942 
3943  inline enum enum_server_command get_command() const
3944  { return m_command; }
3945 
3950  void set_query(char *query_arg, uint32 query_length_arg,
3951  const CHARSET_INFO *cs_arg)
3952  {
3953  set_query(CSET_STRING(query_arg, query_length_arg, cs_arg));
3954  }
3955  void set_query(char *query_arg, uint32 query_length_arg) /*Mutex protected*/
3956  {
3957  set_query(CSET_STRING(query_arg, query_length_arg, charset()));
3958  }
3959  void set_query(const CSET_STRING &str); /* Mutex protected */
3960  void reset_query() /* Mutex protected */
3961  { set_query(CSET_STRING()); }
3962  void set_query_and_id(char *query_arg, uint32 query_length_arg,
3963  const CHARSET_INFO *cs, query_id_t new_query_id);
3964  void set_query_id(query_id_t new_query_id);
3965  void set_open_tables(TABLE *open_tables_arg)
3966  {
3967  mysql_mutex_lock(&LOCK_thd_data);
3968  open_tables= open_tables_arg;
3969  mysql_mutex_unlock(&LOCK_thd_data);
3970  }
3971  void set_mysys_var(struct st_my_thread_var *new_mysys_var);
3972  void enter_locked_tables_mode(enum_locked_tables_mode mode_arg)
3973  {
3974  DBUG_ASSERT(locked_tables_mode == LTM_NONE);
3975 
3976  if (mode_arg == LTM_LOCK_TABLES)
3977  {
3978  /*
3979  When entering LOCK TABLES mode we should set explicit duration
3980  for all metadata locks acquired so far in order to avoid releasing
3981  them till UNLOCK TABLES statement.
3982  We don't do this when entering prelocked mode since sub-statements
3983  don't release metadata locks and restoring status-quo after leaving
3984  prelocking mode gets complicated.
3985  */
3986  mdl_context.set_explicit_duration_for_all_locks();
3987  }
3988 
3989  locked_tables_mode= mode_arg;
3990  }
3991  void leave_locked_tables_mode();
3992  int decide_logging_format(TABLE_LIST *tables);
4033  bool
4034  is_dml_gtid_compatible(bool transactional_table,
4035  bool non_transactional_table,
4036  bool non_transactional_tmp_tables) const;
4037  bool is_ddl_gtid_compatible() const;
4038  void binlog_invoker() { m_binlog_invoker= TRUE; }
4039  bool need_binlog_invoker() { return m_binlog_invoker; }
4040  void get_definer(LEX_USER *definer);
4041  void set_invoker(const LEX_STRING *user, const LEX_STRING *host)
4042  {
4043  invoker_user= *user;
4044  invoker_host= *host;
4045  }
4046  LEX_STRING get_invoker_user() { return invoker_user; }
4047  LEX_STRING get_invoker_host() { return invoker_host; }
4048  bool has_invoker() { return invoker_user.length > 0; }
4049 
4050 #ifndef DBUG_OFF
4051 private:
4052  int gis_debug; // Storage for "SELECT ST_GIS_DEBUG(param);"
4053 public:
4054  int get_gis_debug() { return gis_debug; }
4055  void set_gis_debug(int arg) { gis_debug= arg; }
4056 #endif
4057 
4058 private:
4059 
4061  Internal_error_handler *m_internal_handler;
4062 
4069  LEX main_lex;
4078  MEM_ROOT main_mem_root;
4079  Diagnostics_area main_da;
4080  Diagnostics_area *m_stmt_da;
4081 
4090  bool m_binlog_invoker;
4091 
4098  LEX_STRING invoker_user;
4099  LEX_STRING invoker_host;
4100 };
4101 
4102 
4107 class Prepared_stmt_arena_holder
4108 {
4109 public:
4118  Prepared_stmt_arena_holder(THD *thd, bool activate_now_if_needed= true)
4119  :m_thd(thd),
4120  m_arena(NULL)
4121  {
4122  if (activate_now_if_needed &&
4123  !m_thd->stmt_arena->is_conventional() &&
4124  m_thd->mem_root != m_thd->stmt_arena->mem_root)
4125  {
4126  m_thd->set_n_backup_active_arena(m_thd->stmt_arena, &m_backup);
4127  m_arena= m_thd->stmt_arena;
4128  }
4129  }
4130 
4135  ~Prepared_stmt_arena_holder()
4136  {
4137  if (is_activated())
4138  m_thd->restore_active_arena(m_arena, &m_backup);
4139  }
4140 
4141  bool is_activated() const
4142  { return m_arena != NULL; }
4143 
4144 private:
4146  THD *const m_thd;
4147 
4149  Query_arena *m_arena;
4150 
4152  Query_arena m_backup;
4153 };
4154 
4155 
4158 inline void
4159 my_ok(THD *thd, ulonglong affected_rows= 0, ulonglong id= 0,
4160  const char *message= NULL)
4161 {
4162  thd->set_row_count_func(affected_rows);
4163  thd->get_stmt_da()->set_ok_status(affected_rows, id, message);
4164 }
4165 
4166 
4169 inline void
4170 my_eof(THD *thd)
4171 {
4172  thd->set_row_count_func(-1);
4173  thd->get_stmt_da()->set_eof_status(thd);
4174 }
4175 
4176 #define tmp_disable_binlog(A) \
4177  {ulonglong tmp_disable_binlog__save_options= (A)->variables.option_bits; \
4178  (A)->variables.option_bits&= ~OPTION_BIN_LOG
4179 
4180 #define reenable_binlog(A) (A)->variables.option_bits= tmp_disable_binlog__save_options;}
4181 
4182 
4183 LEX_STRING *
4184 make_lex_string_root(MEM_ROOT *mem_root,
4185  LEX_STRING *lex_str, const char* str, uint length,
4186  bool allocate_lex_string);
4187 
4188 /*
4189  Used to hold information about file and file structure in exchange
4190  via non-DB file (...INTO OUTFILE..., ...LOAD DATA...)
4191  XXX: We never call destructor for objects of this class.
4192 */
4193 
4194 class sql_exchange :public Sql_alloc
4195 {
4196 public:
4197  enum enum_filetype filetype; /* load XML, Added by Arnold & Erik */
4198  char *file_name;
4199  const String *field_term, *enclosed, *line_term, *line_start, *escaped;
4200  bool opt_enclosed;
4201  bool dumpfile;
4202  ulong skip_lines;
4203  const CHARSET_INFO *cs;
4204  sql_exchange(char *name, bool dumpfile_flag,
4205  enum_filetype filetype_arg= FILETYPE_CSV);
4206  bool escaped_given(void);
4207 };
4208 
4209 /*
4210  This is used to get result from a select
4211 */
4212 
4213 class JOIN;
4214 
4215 class select_result :public Sql_alloc {
4216 protected:
4217  THD *thd;
4218  SELECT_LEX_UNIT *unit;
4219 public:
4224  ha_rows estimated_rowcount;
4225  select_result();
4226  virtual ~select_result() {};
4227  virtual int prepare(List<Item> &list, SELECT_LEX_UNIT *u)
4228  {
4229  unit= u;
4230  return 0;
4231  }
4232  virtual int prepare2(void) { return 0; }
4233  /*
4234  Because of peculiarities of prepared statements protocol
4235  we need to know number of columns in the result set (if
4236  there is a result set) apart from sending columns metadata.
4237  */
4238  virtual uint field_count(List<Item> &fields) const
4239  { return fields.elements; }
4240  virtual bool send_result_set_metadata(List<Item> &list, uint flags)=0;
4241  virtual bool send_data(List<Item> &items)=0;
4242  virtual bool initialize_tables (JOIN *join=0) { return 0; }
4243  virtual void send_error(uint errcode,const char *err);
4244  virtual bool send_eof()=0;
4252  virtual bool check_simple_select() const;
4253  virtual void abort_result_set() {}
4254  /*
4255  Cleanup instance of this class for next execution of a prepared
4256  statement/stored procedure.
4257  */
4258  virtual void cleanup();
4259  void set_thd(THD *thd_arg) { thd= thd_arg; }
4260 
4266  void reset_offset_limit_cnt() { unit->offset_limit_cnt= 0; }
4267 
4268 #ifdef EMBEDDED_LIBRARY
4269  virtual void begin_dataset() {}
4270 #else
4271  void begin_dataset() {}
4272 #endif
4273 };
4274 
4275 
4276 /*
4277  Base class for select_result descendands which intercept and
4278  transform result set rows. As the rows are not sent to the client,
4279  sending of result set metadata should be suppressed as well.
4280 */
4281 
4282 class select_result_interceptor: public select_result
4283 {
4284 public:
4285  select_result_interceptor() {} /* Remove gcc warning */
4286  uint field_count(List<Item> &fields) const { return 0; }
4287  bool send_result_set_metadata(List<Item> &fields, uint flag) { return FALSE; }
4288 };
4289 
4290 
4291 class select_send :public select_result {
4297  bool is_result_set_started;
4298 public:
4299  select_send() :is_result_set_started(FALSE) {}
4300  bool send_result_set_metadata(List<Item> &list, uint flags);
4301  bool send_data(List<Item> &items);
4302  bool send_eof();
4303  virtual bool check_simple_select() const { return FALSE; }
4304  void abort_result_set();
4305  virtual void cleanup();
4306 };
4307 
4308 
4309 class select_to_file :public select_result_interceptor {
4310 protected:
4311  sql_exchange *exchange;
4312  File file;
4313  IO_CACHE cache;
4314  ha_rows row_count;
4315  char path[FN_REFLEN];
4316 
4317 public:
4318  select_to_file(sql_exchange *ex) :exchange(ex), file(-1),row_count(0L)
4319  { path[0]=0; }
4320  ~select_to_file();
4321  void send_error(uint errcode,const char *err);
4322  bool send_eof();
4323  void cleanup();
4324 };
4325 
4326 
4327 #define ESCAPE_CHARS "ntrb0ZN" // keep synchronous with READ_INFO::unescape
4328 
4329 
4330 /*
4331  List of all possible characters of a numeric value text representation.
4332 */
4333 #define NUMERIC_CHARS ".0123456789e+-"
4334 
4335 
4336 class select_export :public select_to_file {
4337  uint field_term_length;
4338  int field_sep_char,escape_char,line_sep_char;
4339  int field_term_char; // first char of FIELDS TERMINATED BY or MAX_INT
4340  /*
4341  The is_ambiguous_field_sep field is true if a value of the field_sep_char
4342  field is one of the 'n', 't', 'r' etc characters
4343  (see the READ_INFO::unescape method and the ESCAPE_CHARS constant value).
4344  */
4345  bool is_ambiguous_field_sep;
4346  /*
4347  The is_ambiguous_field_term is true if field_sep_char contains the first
4348  char of the FIELDS TERMINATED BY (ENCLOSED BY is empty), and items can
4349  contain this character.
4350  */
4351  bool is_ambiguous_field_term;
4352  /*
4353  The is_unsafe_field_sep field is true if a value of the field_sep_char
4354  field is one of the '0'..'9', '+', '-', '.' and 'e' characters
4355  (see the NUMERIC_CHARS constant value).
4356  */
4357  bool is_unsafe_field_sep;
4358  bool fixed_row_size;
4359  const CHARSET_INFO *write_cs; // output charset
4360 public:
4361  select_export(sql_exchange *ex) :select_to_file(ex) {}
4362  ~select_export();
4363  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
4364  bool send_data(List<Item> &items);
4365 };
4366 
4367 
4368 class select_dump :public select_to_file {
4369 public:
4370  select_dump(sql_exchange *ex) :select_to_file(ex) {}
4371  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
4372  bool send_data(List<Item> &items);
4373 };
4374 
4380 class select_insert :public select_result_interceptor {
4381 public:
4382  TABLE_LIST *table_list;
4383  TABLE *table;
4384 private:
4390  List<Item> *fields;
4391 protected:
4393  bool bulk_insert_started;
4394 public:
4395  ulonglong autoinc_value_of_last_inserted_row; // autogenerated or not
4396  COPY_INFO info;
4397  COPY_INFO update;
4398  bool insert_into_view;
4399 
4448  select_insert(TABLE_LIST *table_list_par,
4449  TABLE *table_par,
4450  List<Item> *target_columns,
4451  List<Item> *target_or_source_columns,
4452  List<Item> *update_fields,
4453  List<Item> *update_values,
4454  enum_duplicates duplic,
4455  bool ignore)
4456  :table_list(table_list_par),
4457  table(table_par),
4458  fields(target_or_source_columns),
4459  bulk_insert_started(false),
4460  autoinc_value_of_last_inserted_row(0),
4461  info(COPY_INFO::INSERT_OPERATION,
4462  target_columns,
4463  // manage_defaults
4464  (target_columns == NULL || target_columns->elements != 0),
4465  duplic,
4466  ignore),
4467  update(COPY_INFO::UPDATE_OPERATION,
4468  update_fields,
4469  update_values),
4470  insert_into_view(table_list_par && table_list_par->view != 0)
4471  {
4472  DBUG_ASSERT(target_or_source_columns != NULL);
4473  DBUG_ASSERT(target_columns == target_or_source_columns ||
4474  target_columns == NULL);
4475  }
4476 
4477 
4478 public:
4479  ~select_insert();
4480  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
4481  virtual int prepare2(void);
4482  bool send_data(List<Item> &items);
4483  virtual void store_values(List<Item> &values);
4484  void send_error(uint errcode,const char *err);
4485  bool send_eof();
4486  virtual void abort_result_set();
4487  /* not implemented: select_insert is never re-used in prepared statements */
4488  void cleanup();
4489 };
4490 
4491 
4498 class select_create: public select_insert {
4499  ORDER *group;
4501  HA_CREATE_INFO *create_info;
4502  TABLE_LIST *select_tables;
4503  Alter_info *alter_info;
4504  Field **field;
4505  /* lock data for tmp table */
4506  MYSQL_LOCK *m_lock;
4507  /* m_lock or thd->extra_lock */
4508  MYSQL_LOCK **m_plock;
4509 public:
4510  select_create (TABLE_LIST *table_arg,
4511  HA_CREATE_INFO *create_info_par,
4512  Alter_info *alter_info_arg,
4513  List<Item> &select_fields,enum_duplicates duplic, bool ignore,
4514  TABLE_LIST *select_tables_arg)
4515  :select_insert (NULL, // table_list_par
4516  NULL, // table_par
4517  NULL, // target_columns
4518  &select_fields,
4519  NULL, // update_fields
4520  NULL, // update_values
4521  duplic,
4522  ignore),
4523  create_table(table_arg),
4524  create_info(create_info_par),
4525  select_tables(select_tables_arg),
4526  alter_info(alter_info_arg),
4527  m_plock(NULL)
4528  {}
4529  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
4530 
4531  int binlog_show_create_table(TABLE **tables, uint count);
4532  void store_values(List<Item> &values);
4533  void send_error(uint errcode,const char *err);
4534  bool send_eof();
4535  virtual void abort_result_set();
4536 
4537  // Needed for access from local class MY_HOOKS in prepare(), since thd is proteted.
4538  const THD *get_thd(void) { return thd; }
4539  const HA_CREATE_INFO *get_create_info() { return create_info; };
4540  int prepare2(void);
4541 };
4542 
4543 #include <myisam.h>
4544 
4545 /*
4546  Param to create temporary tables when doing SELECT:s
4547  NOTE
4548  This structure is copied using memcpy as a part of JOIN.
4549 */
4550 
4551 class TMP_TABLE_PARAM :public Sql_alloc
4552 {
4553 public:
4555  Copy_field *copy_field, *copy_field_end;
4556  uchar *group_buff;
4557  Item **items_to_copy; /* Fields in tmp table */
4558  MI_COLUMNDEF *recinfo,*start_recinfo;
4559  KEY *keyinfo;
4560  ha_rows end_write_records;
4568  uint field_count;
4577  uint func_count;
4586  uint sum_func_count;
4587  uint hidden_field_count;
4588  uint group_parts,group_length,group_null_parts;
4589  uint quick_group;
4596  uint outer_sum_func_count;
4603  bool using_outer_summary_function;
4604  CHARSET_INFO *table_charset;
4605  bool schema_table;
4606  /*
4607  True if GROUP BY and its aggregate functions are already computed
4608  by a table access method (e.g. by loose index scan). In this case
4609  query execution should not perform aggregation and should treat
4610  aggregate functions as normal functions.
4611  */
4612  bool precomputed_group_by;
4613  bool force_copy_fields;
4620  bool skip_create_table;
4621  /*
4622  If TRUE, create_tmp_field called from create_tmp_table will convert
4623  all BIT fields to 64-bit longs. This is a workaround the limitation
4624  that MEMORY tables cannot index BIT columns.
4625  */
4626  bool bit_fields_as_long;
4627 
4628  TMP_TABLE_PARAM()
4629  :copy_field(0), copy_field_end(0), group_parts(0),
4630  group_length(0), group_null_parts(0), outer_sum_func_count(0),
4631  using_outer_summary_function(0),
4632  schema_table(0), precomputed_group_by(0), force_copy_fields(0),
4633  skip_create_table(FALSE), bit_fields_as_long(0)
4634  {}
4635  ~TMP_TABLE_PARAM()
4636  {
4637  cleanup();
4638  }
4639  void init(void);
4640  inline void cleanup(void)
4641  {
4642  if (copy_field) /* Fix for Intel compiler */
4643  {
4644  delete [] copy_field;
4645  copy_field= NULL;
4646  copy_field_end= NULL;
4647  }
4648  }
4649 };
4650 
4651 class select_union :public select_result_interceptor
4652 {
4653  TMP_TABLE_PARAM tmp_table_param;
4654 public:
4655  TABLE *table;
4656 
4657  select_union() :table(0) {}
4658  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
4659  bool send_data(List<Item> &items);
4660  bool send_eof();
4661  bool flush();
4662  void cleanup();
4663  bool create_result_table(THD *thd, List<Item> *column_types,
4664  bool is_distinct, ulonglong options,
4665  const char *alias, bool bit_fields_as_long,
4666  bool create_table);
4667  friend bool mysql_derived_create(THD *thd, LEX *lex, TABLE_LIST *derived);
4668 };
4669 
4670 /* Base subselect interface class */
4671 class select_subselect :public select_result_interceptor
4672 {
4673 protected:
4674  Item_subselect *item;
4675 public:
4676  select_subselect(Item_subselect *item);
4677  bool send_data(List<Item> &items)=0;
4678  bool send_eof() { return 0; };
4679 };
4680 
4681 /* Single value subselect interface class */
4682 class select_singlerow_subselect :public select_subselect
4683 {
4684 public:
4685  select_singlerow_subselect(Item_subselect *item_arg)
4686  :select_subselect(item_arg)
4687  {}
4688  bool send_data(List<Item> &items);
4689 };
4690 
4691 /* used in independent ALL/ANY optimisation */
4692 class select_max_min_finder_subselect :public select_subselect
4693 {
4694  Item_cache *cache;
4695  bool (select_max_min_finder_subselect::*op)();
4696  bool fmax;
4702  bool ignore_nulls;
4703 public:
4704  select_max_min_finder_subselect(Item_subselect *item_arg, bool mx,
4705  bool ignore_nulls)
4706  :select_subselect(item_arg), cache(0), fmax(mx), ignore_nulls(ignore_nulls)
4707  {}
4708  void cleanup();
4709  bool send_data(List<Item> &items);
4710 private:
4711  bool cmp_real();
4712  bool cmp_int();
4713  bool cmp_decimal();
4714  bool cmp_str();
4715 };
4716 
4717 /* EXISTS subselect interface class */
4718 class select_exists_subselect :public select_subselect
4719 {
4720 public:
4721  select_exists_subselect(Item_subselect *item_arg)
4722  :select_subselect(item_arg){}
4723  bool send_data(List<Item> &items);
4724 };
4725 
4726 
4727 /* Structs used when sorting */
4728 
4729 typedef struct st_sort_field {
4730  Field *field; /* Field to sort */
4731  Item *item; /* Item if not sorting fields */
4732  uint length; /* Length of sort field */
4733  uint suffix_length; /* Length suffix (0-4) */
4734  Item_result result_type; /* Type of item */
4735  bool reverse; /* if descending sort */
4736  bool need_strxnfrm; /* If we have to use strxnfrm() */
4737 } SORT_FIELD;
4738 
4739 
4740 typedef struct st_sort_buffer {
4741  uint index; /* 0 or 1 */
4742  uint sort_orders;
4743  uint change_pos; /* If sort-fields changed */
4744  char **buff;
4745  SORT_FIELD *sortorder;
4746 } SORT_BUFFER;
4747 
4748 /* Structure for db & table in sql_yacc */
4749 
4750 class Table_ident :public Sql_alloc
4751 {
4752 public:
4753  LEX_STRING db;
4754  LEX_STRING table;
4755  SELECT_LEX_UNIT *sel;
4756  inline Table_ident(THD *thd, LEX_STRING db_arg, LEX_STRING table_arg,
4757  bool force)
4758  :table(table_arg), sel((SELECT_LEX_UNIT *)0)
4759  {
4760  if (!force && (thd->client_capabilities & CLIENT_NO_SCHEMA))
4761  db.str=0;
4762  else
4763  db= db_arg;
4764  }
4765  inline Table_ident(LEX_STRING table_arg)
4766  :table(table_arg), sel((SELECT_LEX_UNIT *)0)
4767  {
4768  db.str=0;
4769  }
4770  /*
4771  This constructor is used only for the case when we create a derived
4772  table. A derived table has no name and doesn't belong to any database.
4773  Later, if there was an alias specified for the table, it will be set
4774  by add_table_to_list.
4775  */
4776  inline Table_ident(SELECT_LEX_UNIT *s) : sel(s)
4777  {
4778  /* We must have a table name here as this is used with add_table_to_list */
4779  db.str= empty_c_string; /* a subject to casedn_str */
4780  db.length= 0;
4781  table.str= internal_table_name;
4782  table.length=1;
4783  }
4784  bool is_derived_table() const { return test(sel); }
4785  inline void change_db(char *db_name)
4786  {
4787  db.str= db_name; db.length= (uint) strlen(db_name);
4788  }
4789 };
4790 
4791 // this is needed for user_vars hash
4792 class user_var_entry
4793 {
4794  static const size_t extra_size= sizeof(double);
4795  char *m_ptr; // Value
4796  ulong m_length; // Value length
4797  Item_result m_type; // Value type
4798 
4799  void reset_value()
4800  { m_ptr= NULL; m_length= 0; }
4801  void set_value(char *value, ulong length)
4802  { m_ptr= value; m_length= length; }
4803 
4811  char *internal_buffer_ptr() const
4812  { return (char *) this + ALIGN_SIZE(sizeof(user_var_entry)); }
4813 
4818  char *name_ptr() const
4819  { return internal_buffer_ptr() + extra_size; }
4820 
4826  bool realloc(uint length);
4827 
4833  bool alloced()
4834  { return m_ptr && m_ptr != internal_buffer_ptr(); }
4835 
4839  void free_value()
4840  {
4841  if (alloced())
4842  my_free(m_ptr);
4843  }
4844 
4849  void copy_name(const Simple_cstring &name)
4850  {
4851  name.strcpy(name_ptr());
4852  entry_name= Name_string(name_ptr(), name.length());
4853  }
4854 
4859  void init(const Simple_cstring &name)
4860  {
4861  copy_name(name);
4862  reset_value();
4863  update_query_id= 0;
4864  collation.set(NULL, DERIVATION_IMPLICIT, 0);
4865  unsigned_flag= 0;
4866  /*
4867  If we are here, we were called from a SET or a query which sets a
4868  variable. Imagine it is this:
4869  INSERT INTO t SELECT @a:=10, @a:=@a+1.
4870  Then when we have a Item_func_get_user_var (because of the @a+1) so we
4871  think we have to write the value of @a to the binlog. But before that,
4872  we have a Item_func_set_user_var to create @a (@a:=10), in this we mark
4873  the variable as "already logged" (line below) so that it won't be logged
4874  by Item_func_get_user_var (because that's not necessary).
4875  */
4876  used_query_id= current_thd->query_id;
4877  set_type(STRING_RESULT);
4878  }
4879 
4889  bool store(void *from, uint length, Item_result type);
4890 
4891 public:
4892  user_var_entry() {} /* Remove gcc warning */
4893 
4894  Simple_cstring entry_name; // Variable name
4895  DTCollation collation; // Collation with attributes
4896  query_id_t update_query_id, used_query_id;
4897  bool unsigned_flag; // true if unsigned, false if signed
4898 
4912  bool store(void *from, uint length, Item_result type,
4913  const CHARSET_INFO *cs, Derivation dv, bool unsigned_arg);
4918  void set_type(Item_result type) { m_type= type; }
4924  void set_null_value(Item_result type)
4925  {
4926  free_value();
4927  reset_value();
4928  set_type(type);
4929  }
4930 
4938  static user_var_entry *create(const Name_string &name)
4939  {
4940  user_var_entry *entry;
4941  uint size= ALIGN_SIZE(sizeof(user_var_entry)) +
4942  (name.length() + 1) + extra_size;
4943  if (!(entry= (user_var_entry*) my_malloc(size, MYF(MY_WME |
4944  ME_FATALERROR))))
4945  return NULL;
4946  entry->init(name);
4947  return entry;
4948  }
4949 
4954  void destroy()
4955  {
4956  free_value(); // Free the external value buffer
4957  my_free(this); // Free the instance itself
4958  }
4959 
4960  /* Routines to access the value and its type */
4961  const char *ptr() const { return m_ptr; }
4962  ulong length() const { return m_length; }
4963  Item_result type() const { return m_type; }
4964  /* Item-alike routines to access the value */
4965  double val_real(my_bool *null_value);
4966  longlong val_int(my_bool *null_value) const;
4967  String *val_str(my_bool *null_value, String *str, uint decimals);
4968  my_decimal *val_decimal(my_bool *null_value, my_decimal *result);
4969 };
4970 
4971 /*
4972  Unique -- class for unique (removing of duplicates).
4973  Puts all values to the TREE. If the tree becomes too big,
4974  it's dumped to the file. User can request sorted values, or
4975  just iterate through them. In the last case tree merging is performed in
4976  memory simultaneously with iteration, so it should be ~2-3x faster.
4977  */
4978 
4979 class Unique :public Sql_alloc
4980 {
4981  DYNAMIC_ARRAY file_ptrs;
4982  ulong max_elements;
4983  ulonglong max_in_memory_size;
4984  IO_CACHE file;
4985  TREE tree;
4986  uchar *record_pointers;
4987  bool flush();
4988  uint size;
4989 
4990 public:
4991  ulong elements;
4992  Unique(qsort_cmp2 comp_func, void *comp_func_fixed_arg,
4993  uint size_arg, ulonglong max_in_memory_size_arg);
4994  ~Unique();
4995  ulong elements_in_tree() { return tree.elements_in_tree; }
4996  inline bool unique_add(void *ptr)
4997  {
4998  DBUG_ENTER("unique_add");
4999  DBUG_PRINT("info", ("tree %u - %lu", tree.elements_in_tree, max_elements));
5000  if (tree.elements_in_tree > max_elements && flush())
5001  DBUG_RETURN(1);
5002  DBUG_RETURN(!tree_insert(&tree, ptr, 0, tree.custom_arg));
5003  }
5004 
5005  bool get(TABLE *table);
5006  static double get_use_cost(uint *buffer, uint nkeys, uint key_size,
5007  ulonglong max_in_memory_size);
5008  inline static int get_cost_calc_buff_size(ulong nkeys, uint key_size,
5009  ulonglong max_in_memory_size)
5010  {
5011  register ulonglong max_elems_in_tree=
5012  (1 + max_in_memory_size / ALIGN_SIZE(sizeof(TREE_ELEMENT)+key_size));
5013  return (int) (sizeof(uint)*(1 + nkeys/max_elems_in_tree));
5014  }
5015 
5016  void reset();
5017  bool walk(tree_walk_action action, void *walk_action_arg);
5018 
5019  uint get_size() const { return size; }
5020  ulonglong get_max_in_memory_size() const { return max_in_memory_size; }
5021 
5022  friend int unique_write_to_file(uchar* key, element_count count, Unique *unique);
5023  friend int unique_write_to_ptrs(uchar* key, element_count count, Unique *unique);
5024 };
5025 
5026 
5027 class multi_delete :public select_result_interceptor
5028 {
5029  TABLE_LIST *delete_tables, *table_being_deleted;
5030  Unique **tempfiles;
5031  ha_rows deleted, found;
5032  uint num_of_tables;
5033  int error;
5034  bool do_delete;
5035  /* True if at least one table we delete from is transactional */
5036  bool transactional_tables;
5037  /* True if at least one table we delete from is not transactional */
5038  bool normal_tables;
5039  bool delete_while_scanning;
5040  /*
5041  error handling (rollback and binlogging) can happen in send_eof()
5042  so that afterward send_error() needs to find out that.
5043  */
5044  bool error_handled;
5045 
5046 public:
5047  multi_delete(TABLE_LIST *dt, uint num_of_tables);
5048  ~multi_delete();
5049  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
5050  bool send_data(List<Item> &items);
5051  bool initialize_tables (JOIN *join);
5052  void send_error(uint errcode,const char *err);
5053  int do_deletes();
5054  int do_table_deletes(TABLE *table, bool ignore);
5055  bool send_eof();
5056  inline ha_rows num_deleted()
5057  {
5058  return deleted;
5059  }
5060  virtual void abort_result_set();
5061 };
5062 
5063 
5068 class multi_update :public select_result_interceptor
5069 {
5070  TABLE_LIST *all_tables; /* query/update command tables */
5071  TABLE_LIST *leaves; /* list of leves of join table tree */
5072  TABLE_LIST *update_tables, *table_being_updated;
5073  TABLE **tmp_tables, *main_table, *table_to_update;
5074  TMP_TABLE_PARAM *tmp_table_param;
5075  ha_rows updated, found;
5076  List <Item> *fields, *values;
5077  List <Item> **fields_for_table, **values_for_table;
5078  uint table_count;
5079  /*
5080  List of tables referenced in the CHECK OPTION condition of
5081  the updated view excluding the updated table.
5082  */
5083  List <TABLE> unupdated_check_opt_tables;
5084  Copy_field *copy_field;
5085  enum enum_duplicates handle_duplicates;
5086  bool do_update, trans_safe;
5087  /* True if the update operation has made a change in a transactional table */
5088  bool transactional_tables;
5089  bool ignore;
5090  /*
5091  error handling (rollback and binlogging) can happen in send_eof()
5092  so that afterward send_error() needs to find out that.
5093  */
5094  bool error_handled;
5095 
5110  COPY_INFO **update_operations;
5111 
5112 public:
5113  multi_update(TABLE_LIST *ut, TABLE_LIST *leaves_list,
5114  List<Item> *fields, List<Item> *values,
5115  enum_duplicates handle_duplicates, bool ignore);
5116  ~multi_update();
5117  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
5118  bool send_data(List<Item> &items);
5119  bool initialize_tables (JOIN *join);
5120  void send_error(uint errcode,const char *err);
5121  int do_updates();
5122  bool send_eof();
5123  inline ha_rows num_found()
5124  {
5125  return found;
5126  }
5127  inline ha_rows num_updated()
5128  {
5129  return updated;
5130  }
5131  virtual void abort_result_set();
5132 };
5133 
5134 class my_var : public Sql_alloc {
5135 public:
5136  LEX_STRING s;
5137 #ifndef DBUG_OFF
5138  /*
5139  Routine to which this Item_splocal belongs. Used for checking if correct
5140  runtime context is used for variable handling.
5141  */
5142  sp_head *sp;
5143 #endif
5144  bool local;
5145  uint offset;
5146  enum_field_types type;
5147  my_var (LEX_STRING& j, bool i, uint o, enum_field_types t)
5148  :s(j), local(i), offset(o), type(t)
5149  {}
5150  ~my_var() {}
5151 };
5152 
5153 class select_dumpvar :public select_result_interceptor {
5154  ha_rows row_count;
5155 public:
5156  List<my_var> var_list;
5157  select_dumpvar() { var_list.empty(); row_count= 0;}
5158  ~select_dumpvar() {}
5159  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
5160  bool send_data(List<Item> &items);
5161  bool send_eof();
5162  virtual bool check_simple_select() const;
5163  void cleanup();
5164 };
5165 
5166 /* Bits in sql_command_flags */
5167 
5168 #define CF_CHANGES_DATA (1U << 0)
5169 /* The 2nd bit is unused -- it used to be CF_HAS_ROW_COUNT. */
5170 #define CF_STATUS_COMMAND (1U << 2)
5171 #define CF_SHOW_TABLE_COMMAND (1U << 3)
5172 #define CF_WRITE_LOGS_COMMAND (1U << 4)
5173 
5186 #define CF_REEXECUTION_FRAGILE (1U << 5)
5187 
5198 #define CF_IMPLICIT_COMMIT_BEGIN (1U << 6)
5199 
5209 #define CF_IMPLICIT_COMMIT_END (1U << 7)
5210 
5216 #define CF_AUTO_COMMIT_TRANS (CF_IMPLICIT_COMMIT_BEGIN | CF_IMPLICIT_COMMIT_END)
5217 
5226 #define CF_DIAGNOSTIC_STMT (1U << 8)
5227 
5232 #define CF_CAN_GENERATE_ROW_EVENTS (1U << 9)
5233 
5238 #define CF_PREOPEN_TMP_TABLES (1U << 10)
5239 
5244 #define CF_HA_CLOSE (1U << 11)
5245 
5249 #define CF_CAN_BE_EXPLAINED (1U << 12)
5250 
5252 #define CF_OPTIMIZER_TRACE (1U << 14)
5253 
5258 #define CF_DISALLOW_IN_RO_TRANS (1U << 15)
5259 
5260 /* Bits in server_command_flags */
5261 
5269 #define CF_SKIP_QUERY_ID (1U << 0)
5270 
5277 #define CF_SKIP_QUESTIONS (1U << 1)
5278 
5279 void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var);
5280 
5281 void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var,
5282  STATUS_VAR *dec_var);
5283 void mark_transaction_to_rollback(THD *thd, bool all);
5284 
5285 /* Inline functions */
5286 
5287 inline bool add_item_to_list(THD *thd, Item *item)
5288 {
5289  return thd->lex->current_select->add_item_to_list(thd, item);
5290 }
5291 
5292 inline bool add_value_to_list(THD *thd, Item *value)
5293 {
5294  return thd->lex->value_list.push_back(value);
5295 }
5296 
5297 inline bool add_order_to_list(THD *thd, Item *item, bool asc)
5298 {
5299  return thd->lex->current_select->add_order_to_list(thd, item, asc);
5300 }
5301 
5302 inline bool add_gorder_to_list(THD *thd, Item *item, bool asc)
5303 {
5304  return thd->lex->current_select->add_gorder_to_list(thd, item, asc);
5305 }
5306 
5307 inline bool add_group_to_list(THD *thd, Item *item, bool asc)
5308 {
5309  return thd->lex->current_select->add_group_to_list(thd, item, asc);
5310 }
5311 
5312 #endif /* MYSQL_SERVER */
5313 
5314 #endif /* SQL_CLASS_INCLUDED */