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