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