1 /* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
2
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License, version 2.0,
5 as published by the Free Software Foundation.
6
7 This program is also distributed with certain software (including
8 but not limited to OpenSSL) that is licensed under separate terms,
9 as designated in a particular file or component or in included license
10 documentation. The authors of MySQL hereby grant you an additional
11 permission to link the program and your derivative works with the
12 separately licensed software that they have included with MySQL.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License, version 2.0, for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
22
23 #ifndef SQL_CLASS_INCLUDED
24 #define SQL_CLASS_INCLUDED
25
26 /*
27 This file contains the declaration of the THD class and classes which THD
28 depends on. It should contain as little else as possible to increase
29 cohesion and reduce coupling. Since THD is used in many places, many files
30 are dependent on this header and thus require recompilation if it changes.
31 Historically this file contained "Classes in mysql".
32 */
33
34 #include "my_config.h"
35
36 #include <limits.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <string.h>
40 #ifdef HAVE_SYS_TIME_H
41 #include <sys/time.h>
42 #endif
43 #include <sys/types.h>
44 #include <atomic>
45 #include <bitset>
46 #include <memory>
47 #include <new>
48 #include <string>
49
50 #include "dur_prop.h" // durability_properties
51 #include "lex_string.h"
52 #include "m_ctype.h"
53 #include "map_helpers.h"
54 #include "my_alloc.h"
55 #include "my_base.h"
56 #include "my_command.h"
57 #include "my_compiler.h"
58 #include "my_dbug.h"
59 #include "my_inttypes.h"
60 #include "my_io.h"
61 #include "my_psi_config.h"
62 #include "my_sqlcommand.h"
63 #include "my_sys.h"
64 #include "my_table_map.h"
65 #include "my_thread_local.h"
66 #include "mysql/components/services/my_thread_bits.h"
67 #include "mysql/components/services/mysql_cond_bits.h"
68 #include "mysql/components/services/mysql_mutex_bits.h"
69 #include "mysql/components/services/psi_idle_bits.h"
70 #include "mysql/components/services/psi_stage_bits.h"
71 #include "mysql/components/services/psi_statement_bits.h"
72 #include "mysql/components/services/psi_thread_bits.h"
73 #include "mysql/components/services/psi_transaction_bits.h"
74 #include "mysql/psi/mysql_mutex.h"
75 #include "mysql/psi/mysql_statement.h"
76 #include "mysql/psi/mysql_thread.h"
77 #include "mysql/psi/psi_base.h"
78 #include "mysql/thread_type.h"
79 #include "mysql_com.h"
80 #include "mysql_com_server.h" // NET_SERVER
81 #include "mysqld_error.h"
82 #include "pfs_thread_provider.h"
83 #include "prealloced_array.h"
84 #include "sql/auth/sql_security_ctx.h" // Security_context
85 #include "sql/current_thd.h"
86 #include "sql/dd/string_type.h" // dd::string_type
87 #include "sql/discrete_interval.h" // Discrete_interval
88 #include "sql/locked_tables_list.h" // enum_locked_tables_mode
89 #include "sql/mdl.h"
90 #include "sql/opt_costmodel.h"
91 #include "sql/opt_trace_context.h" // Opt_trace_context
92 #include "sql/psi_memory_key.h"
93 #include "sql/query_options.h"
94 #include "sql/resourcegroups/resource_group_basic_types.h"
95 #include "sql/rpl_context.h" // Rpl_thd_context
96 #include "sql/rpl_gtid.h"
97 #include "sql/session_tracker.h" // Session_tracker
98 #include "sql/sql_connect.h"
99 #include "sql/sql_const.h"
100 #include "sql/sql_digest_stream.h" // sql_digest_state
101 #include "sql/sql_error.h"
102 #include "sql/sql_list.h"
103 #include "sql/sql_plugin_ref.h"
104 #include "sql/sys_vars_resource_mgr.h" // Session_sysvar_resource_manager
105 #include "sql/system_variables.h" // system_variables
106 #include "sql/transaction_info.h" // Ha_trx_info
107 #include "sql/xa.h"
108 #include "sql_string.h"
109 #include "template_utils.h"
110 #include "thr_lock.h"
111 #include "violite.h"
112
113 enum enum_check_fields : int;
114 enum enum_tx_isolation : int;
115 enum ha_notification_type : int;
116 class Item;
117 class Parser_state;
118 class PROFILING;
119 class Query_tables_list;
120 class Relay_log_info;
121 class THD;
122 class partition_info;
123 class Protocol;
124 class Protocol_binary;
125 class Protocol_classic;
126 class Protocol_text;
127 class sp_rcontext;
128 class user_var_entry;
129 struct LEX;
130 struct LEX_USER;
131 struct TABLE;
132 struct TABLE_LIST;
133 struct timeval;
134 struct User_level_lock;
135 struct YYLTYPE;
136
137 namespace dd {
138 namespace cache {
139 class Dictionary_client;
140 }
141
142 class DD_kill_immunizer;
143 } // namespace dd
144
145 class Internal_error_handler;
146 class Modification_plan;
147 class Query_result;
148 class Reprepare_observer;
149 class Rows_log_event;
150 class Time_zone;
151 class sp_cache;
152 struct Binlog_user_var_event;
153 struct LOG_INFO;
154
155 typedef struct user_conn USER_CONN;
156 struct MYSQL_LOCK;
157
158 extern "C" void thd_enter_cond(void *opaque_thd, mysql_cond_t *cond,
159 mysql_mutex_t *mutex,
160 const PSI_stage_info *stage,
161 PSI_stage_info *old_stage,
162 const char *src_function, const char *src_file,
163 int src_line);
164 extern "C" void thd_exit_cond(void *opaque_thd, const PSI_stage_info *stage,
165 const char *src_function, const char *src_file,
166 int src_line);
167
168 extern "C" void thd_enter_stage(void *opaque_thd,
169 const PSI_stage_info *new_stage,
170 PSI_stage_info *old_stage,
171 const char *src_function, const char *src_file,
172 int src_line);
173
174 extern "C" void thd_set_waiting_for_disk_space(void *opaque_thd,
175 const bool waiting);
176
177 #define THD_STAGE_INFO(thd, stage) \
178 (thd)->enter_stage(&stage, NULL, __func__, __FILE__, __LINE__)
179
180 extern char empty_c_string[1];
181
182 /*
183 We preallocate data for several storage engine plugins.
184 so: innodb + bdb + ndb + binlog + myisam + myisammrg + archive +
185 example + csv + heap + blackhole + federated + 0
186 (yes, the sum is deliberately inaccurate)
187 */
188 constexpr size_t PREALLOC_NUM_HA = 15;
189
190 /**
191 To be used for pool-of-threads (implemented differently on various OSs)
192 */
193 class thd_scheduler {
194 public:
195 void *data; /* scheduler-specific data structure */
196
thd_scheduler()197 thd_scheduler() : data(nullptr) {}
198
~thd_scheduler()199 ~thd_scheduler() {}
200 };
201
202 PSI_thread *thd_get_psi(THD *thd);
203 void thd_set_psi(THD *thd, PSI_thread *psi);
204
205 /**
206 the struct aggregates two paramenters that identify an event
207 uniquely in scope of communication of a particular master and slave couple.
208 I.e there can not be 2 events from the same staying connected master which
209 have the same coordinates.
210 @note
211 Such identifier is not yet unique generally as the event originating master
212 is resetable. Also the crashed master can be replaced with some other.
213 */
214 typedef struct rpl_event_coordinates {
215 char *file_name; // binlog file name (directories stripped)
216 my_off_t pos; // event's position in the binlog file
217 } LOG_POS_COORD;
218
219 #define THD_SENTRY_MAGIC 0xfeedd1ff
220 #define THD_SENTRY_GONE 0xdeadbeef
221
222 #define THD_CHECK_SENTRY(thd) DBUG_ASSERT(thd->dbug_sentry == THD_SENTRY_MAGIC)
223
224 class Query_arena {
225 private:
226 /*
227 List of items created for this query. Every item adds itself to the list
228 on creation (see Item::Item() for details)
229 */
230 Item *m_item_list;
231
232 public:
233 MEM_ROOT *mem_root; // Pointer to current memroot
234 /*
235 The states reflects three different life cycles for three
236 different types of statements:
237 Prepared statement: STMT_INITIALIZED -> STMT_PREPARED -> STMT_EXECUTED.
238 Stored procedure: STMT_INITIALIZED_FOR_SP -> STMT_EXECUTED.
239 Other statements: STMT_REGULAR_EXECUTION never changes.
240 */
241 enum enum_state {
242 STMT_INITIALIZED = 0,
243 STMT_INITIALIZED_FOR_SP = 1,
244 STMT_PREPARED = 2,
245 STMT_REGULAR_EXECUTION = 3,
246 STMT_EXECUTED = 4,
247 STMT_ERROR = -1
248 };
249
250 /*
251 State and state changes in SP:
252 1) When state is STMT_INITIALIZED_FOR_SP, objects in the item tree are
253 created on the statement memroot. This is enforced through
254 ps_arena_holder checking the state.
255 2) After the first execute (call p1()), this state should change to
256 STMT_EXECUTED. Objects will be created on the execution memroot and will
257 be destroyed at the end of each execution.
258 3) In case an ER_NEED_REPREPARE error occurs, state should be changed to
259 STMT_INITIALIZED_FOR_SP and objects will again be created on the
260 statement memroot. At the end of this execution, state should change to
261 STMT_EXECUTED.
262 */
263 private:
264 enum_state state;
265
266 public:
Query_arena(MEM_ROOT * mem_root_arg,enum enum_state state_arg)267 Query_arena(MEM_ROOT *mem_root_arg, enum enum_state state_arg)
268 : m_item_list(nullptr), mem_root(mem_root_arg), state(state_arg) {}
269
270 /*
271 This constructor is used only when Query_arena is created as
272 backup storage for another instance of Query_arena.
273 */
Query_arena()274 Query_arena()
275 : m_item_list(nullptr), mem_root(nullptr), state(STMT_INITIALIZED) {}
276
277 virtual ~Query_arena() = default;
278
item_list()279 Item *item_list() const { return m_item_list; }
reset_item_list()280 void reset_item_list() { m_item_list = nullptr; }
set_item_list(Item * item)281 void set_item_list(Item *item) { m_item_list = item; }
282 void add_item(Item *item);
283 void free_items();
set_state(enum_state state_arg)284 void set_state(enum_state state_arg) { state = state_arg; }
get_state()285 enum_state get_state() const { return state; }
is_stmt_prepare()286 bool is_stmt_prepare() const { return state == STMT_INITIALIZED; }
is_stmt_prepare_or_first_sp_execute()287 bool is_stmt_prepare_or_first_sp_execute() const {
288 return (int)state < (int)STMT_PREPARED;
289 }
is_stmt_prepare_or_first_stmt_execute()290 bool is_stmt_prepare_or_first_stmt_execute() const {
291 return (int)state <= (int)STMT_PREPARED;
292 }
293 /// @returns true if a regular statement, ie not prepared and not stored proc
is_regular()294 bool is_regular() const { return state == STMT_REGULAR_EXECUTION; }
295
alloc(size_t size)296 void *alloc(size_t size) { return mem_root->Alloc(size); }
mem_calloc(size_t size)297 void *mem_calloc(size_t size) {
298 void *ptr;
299 if ((ptr = mem_root->Alloc(size))) memset(ptr, 0, size);
300 return ptr;
301 }
302 template <typename T>
alloc_typed()303 T *alloc_typed() {
304 void *m = alloc(sizeof(T));
305 return m == nullptr ? nullptr : new (m) T;
306 }
307 template <typename T>
memdup_typed(const T * mem)308 T *memdup_typed(const T *mem) {
309 return static_cast<T *>(memdup_root(mem_root, mem, sizeof(T)));
310 }
mem_strdup(const char * str)311 char *mem_strdup(const char *str) { return strdup_root(mem_root, str); }
strmake(const char * str,size_t size)312 char *strmake(const char *str, size_t size) const {
313 return strmake_root(mem_root, str, size);
314 }
memdup(const void * str,size_t size)315 void *memdup(const void *str, size_t size) {
316 return memdup_root(mem_root, str, size);
317 }
318
319 /**
320 Copies memory-managing members from `set`. No references are kept to it.
321
322 @param set A Query_arena from which members are copied.
323 */
324 void set_query_arena(const Query_arena &set);
325
326 /**
327 Copy the current arena to `backup` and set the current
328 arena to match `source`
329
330 @param source A Query_arena from which members are copied.
331 @param backup A Query_arena to which members are first saved.
332 */
333 void swap_query_arena(const Query_arena &source, Query_arena *backup);
334 };
335
336 class Prepared_statement;
337
338 /**
339 Container for all prepared statements created/used in a connection.
340
341 Prepared statements in Prepared_statement_map have unique id
342 (guaranteed by id assignment in Prepared_statement::Prepared_statement).
343
344 Non-empty statement names are unique too: attempt to insert a new statement
345 with duplicate name causes older statement to be deleted.
346
347 Prepared statements are auto-deleted when they are removed from the map
348 and when the map is deleted.
349 */
350
351 class Prepared_statement_map {
352 public:
353 Prepared_statement_map();
354
355 /**
356 Insert a new statement to the thread-local prepared statement map.
357
358 If there was an old statement with the same name, replace it with the
359 new one. Otherwise, check if max_prepared_stmt_count is not reached yet,
360 increase prepared_stmt_count, and insert the new statement. It's okay
361 to delete an old statement and fail to insert the new one.
362
363 All named prepared statements are also present in names_hash.
364 Prepared statement names in names_hash are unique.
365 The statement is added only if prepared_stmt_count < max_prepard_stmt_count
366 m_last_found_statement always points to a valid statement or is 0
367
368 @retval 0 success
369 @retval 1 error: out of resources or max_prepared_stmt_count limit has been
370 reached. An error is sent to the client, the statement
371 is deleted.
372 */
373 int insert(Prepared_statement *statement);
374
375 /** Find prepared statement by name. */
376 Prepared_statement *find_by_name(const LEX_CSTRING &name);
377
378 /** Find prepared statement by ID. */
379 Prepared_statement *find(ulong id);
380
381 /** Erase all prepared statements (calls Prepared_statement destructor). */
382 void erase(Prepared_statement *statement);
383
384 void claim_memory_ownership();
385
386 void reset();
387
388 ~Prepared_statement_map();
389
390 private:
391 malloc_unordered_map<ulong, std::unique_ptr<Prepared_statement>> st_hash;
392 collation_unordered_map<std::string, Prepared_statement *> names_hash;
393 Prepared_statement *m_last_found_statement;
394 };
395
396 /**
397 A registry for item tree transformations performed during
398 query optimization. We register only those changes which require
399 a rollback to re-execute a prepared statement or stored procedure
400 yet another time.
401 */
402
403 class Item_change_record : public ilink<Item_change_record> {
404 private:
405 // not used
Item_change_record()406 Item_change_record() {}
407
408 public:
Item_change_record(Item ** place,Item * new_value)409 Item_change_record(Item **place, Item *new_value)
410 : place(place), old_value(*place), new_value(new_value) {}
411 Item **place;
412 Item *old_value;
413 Item *new_value;
414 bool m_cancel{false};
415 };
416
417 typedef I_List<Item_change_record> Item_change_list;
418
419 /**
420 Class that holds information about tables which were opened and locked
421 by the thread. It is also used to save/restore this information in
422 push_open_tables_state()/pop_open_tables_state().
423 */
424
425 class Open_tables_state {
426 private:
427 /**
428 A stack of Reprepare_observer-instances. The top most instance is the
429 currently active one. This stack is used during execution of prepared
430 statements and stored programs in order to detect metadata changes.
431 The locking subsystem reports a metadata change if the top-most item is not
432 NULL.
433
434 When Open_tables_state part of THD is reset to open a system or
435 INFORMATION_SCHEMA table, NULL is temporarily pushed to avoid spurious
436 ER_NEED_REPREPARE errors -- system and INFORMATION_SCHEMA tables are not
437 subject to metadata version tracking.
438
439 A stack is used here for the convenience -- in some cases we need to
440 temporarily override/disable current Reprepare_observer-instance.
441
442 NOTE: This is not a list of observers, only the top-most element will be
443 notified in case of a metadata change.
444
445 @sa check_and_update_table_version()
446 */
447 Prealloced_array<Reprepare_observer *, 4> m_reprepare_observers;
448
449 public:
get_reprepare_observer()450 Reprepare_observer *get_reprepare_observer() const {
451 return m_reprepare_observers.size() > 0 ? m_reprepare_observers.back()
452 : NULL;
453 }
454
push_reprepare_observer(Reprepare_observer * o)455 void push_reprepare_observer(Reprepare_observer *o) {
456 m_reprepare_observers.push_back(o);
457 }
458
pop_reprepare_observer()459 Reprepare_observer *pop_reprepare_observer() {
460 Reprepare_observer *retval = m_reprepare_observers.back();
461 m_reprepare_observers.pop_back();
462 return retval;
463 }
464
reset_reprepare_observers()465 void reset_reprepare_observers() { m_reprepare_observers.clear(); }
466
467 public:
468 /**
469 List of regular tables in use by this thread. Contains persistent base
470 tables that were opened with @see open_tables().
471 */
472 TABLE *open_tables;
473 /**
474 List of temporary tables used by this thread. Contains user-level
475 temporary tables, created with CREATE TEMPORARY TABLE, and
476 intermediate tables used in ALTER TABLE implementation.
477 */
478 TABLE *temporary_tables;
479 /*
480 During a MySQL session, one can lock tables in two modes: automatic
481 or manual. In automatic mode all necessary tables are locked just before
482 statement execution, and all acquired locks are stored in 'lock'
483 member. Unlocking takes place automatically as well, when the
484 statement ends.
485 Manual mode comes into play when a user issues a 'LOCK TABLES'
486 statement. In this mode the user can only use the locked tables.
487 Trying to use any other tables will give an error.
488 The locked tables are also stored in this member, however,
489 thd->locked_tables_mode is turned on. Manual locking is described in
490 the 'LOCK_TABLES' chapter of the MySQL manual.
491 See also lock_tables() for details.
492 */
493 MYSQL_LOCK *lock;
494
495 /*
496 CREATE-SELECT keeps an extra lock for the table being
497 created. This field is used to keep the extra lock available for
498 lower level routines, which would otherwise miss that lock.
499 */
500 MYSQL_LOCK *extra_lock;
501
502 /*
503 Enum enum_locked_tables_mode and locked_tables_mode member are
504 used to indicate whether the so-called "locked tables mode" is on,
505 and what kind of mode is active.
506
507 Locked tables mode is used when it's necessary to open and
508 lock many tables at once, for usage across multiple
509 (sub-)statements.
510 This may be necessary either for queries that use stored functions
511 and triggers, in which case the statements inside functions and
512 triggers may be executed many times, or for implementation of
513 LOCK TABLES, in which case the opened tables are reused by all
514 subsequent statements until a call to UNLOCK TABLES.
515
516 The kind of locked tables mode employed for stored functions and
517 triggers is also called "prelocked mode".
518 In this mode, first open_tables() call to open the tables used
519 in a statement analyses all functions used by the statement
520 and adds all indirectly used tables to the list of tables to
521 open and lock.
522 It also marks the parse tree of the statement as requiring
523 prelocking. After that, lock_tables() locks the entire list
524 of tables and changes THD::locked_tables_modeto LTM_PRELOCKED.
525 All statements executed inside functions or triggers
526 use the prelocked tables, instead of opening their own ones.
527 Prelocked mode is turned off automatically once close_thread_tables()
528 of the main statement is called.
529 */
530 enum enum_locked_tables_mode locked_tables_mode;
531
532 enum enum_flags {
533 BACKUPS_AVAIL = (1U << 0), /* There are backups available. */
534 SYSTEM_TABLES = (1U << 1) /* We are opening system tables. */
535 };
536
537 /*
538 Flags with information about the open tables state.
539 */
540 uint state_flags;
541 /**
542 This constructor initializes Open_tables_state instance which can only
543 be used as backup storage. To prepare Open_tables_state instance for
544 operations which open/lock/close tables (e.g. open_table()) one has to
545 call init_open_tables_state().
546 */
Open_tables_state()547 Open_tables_state()
548 : m_reprepare_observers(PSI_INSTRUMENT_ME), state_flags(0U) {}
549
550 void set_open_tables_state(Open_tables_state *state);
551
552 void reset_open_tables_state();
553 };
554
555 /**
556 Storage for backup of Open_tables_state. Must
557 be used only to open system tables (TABLE_CATEGORY_SYSTEM
558 and TABLE_CATEGORY_LOG).
559 */
560
561 class Open_tables_backup : public Open_tables_state {
562 public:
563 /**
564 When we backup the open tables state to open a system
565 table or tables, we want to save state of metadata
566 locks which were acquired before the backup. It is used
567 to release metadata locks on system tables after they are
568 no longer used.
569 */
570 MDL_savepoint mdl_system_tables_svp;
571 };
572
573 /**
574 Enum that represents which phase of secondary engine optimization
575 the current statement is in.
576 */
577 enum class Secondary_engine_optimization {
578 /**
579 The current statement should only use tables from primary storage
580 engines. Use of secondary storage engines is disabled.
581 */
582 PRIMARY_ONLY,
583
584 /**
585 The current statement should only use tables from the primary
586 storage engine. However, use of secondary storage engines is not
587 disabled, so the optimizer may choose to trigger a repreparation
588 against the secondary storage engine if it believes that use of a
589 secondary storage engine is beneficial.
590 */
591 PRIMARY_TENTATIVELY,
592
593 /**
594 The current statement should use tables from a secondary storage
595 engine if possible. Otherwise, fall back to using tables from
596 primary storage engine only.
597 */
598 SECONDARY,
599 };
600
601 /**
602 @class Sub_statement_state
603 @brief Used to save context when executing a function or trigger
604 */
605
606 /* Defines used for Sub_statement_state::in_sub_stmt */
607
608 #define SUB_STMT_TRIGGER 1
609 #define SUB_STMT_FUNCTION 2
610
611 class Sub_statement_state {
612 public:
613 ulonglong option_bits;
614 ulonglong first_successful_insert_id_in_prev_stmt;
615 ulonglong first_successful_insert_id_in_cur_stmt;
616 Discrete_intervals_list auto_inc_intervals_forced;
617 ulonglong current_found_rows;
618 ulonglong previous_found_rows;
619 ha_rows num_truncated_fields, sent_row_count, examined_row_count;
620 ulong client_capabilities;
621 uint in_sub_stmt;
622 bool enable_slow_log;
623 SAVEPOINT *savepoints;
624 enum enum_check_fields check_for_truncated_fields;
625 };
626
show_system_thread(enum_thread_type thread)627 inline char const *show_system_thread(enum_thread_type thread) {
628 #define RETURN_NAME_AS_STRING(NAME) \
629 case (NAME): \
630 return #NAME
631 switch (thread) {
632 static char buf[64];
633 RETURN_NAME_AS_STRING(NON_SYSTEM_THREAD);
634 RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_IO);
635 RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_SQL);
636 RETURN_NAME_AS_STRING(SYSTEM_THREAD_NDBCLUSTER_BINLOG);
637 RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_SCHEDULER);
638 RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_WORKER);
639 RETURN_NAME_AS_STRING(SYSTEM_THREAD_INFO_REPOSITORY);
640 RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_WORKER);
641 RETURN_NAME_AS_STRING(SYSTEM_THREAD_COMPRESS_GTID_TABLE);
642 RETURN_NAME_AS_STRING(SYSTEM_THREAD_BACKGROUND);
643 RETURN_NAME_AS_STRING(SYSTEM_THREAD_DD_INITIALIZE);
644 RETURN_NAME_AS_STRING(SYSTEM_THREAD_DD_RESTART);
645 RETURN_NAME_AS_STRING(SYSTEM_THREAD_SERVER_INITIALIZE);
646 RETURN_NAME_AS_STRING(SYSTEM_THREAD_INIT_FILE);
647 default:
648 sprintf(buf, "<UNKNOWN SYSTEM THREAD: %d>", thread);
649 return buf;
650 }
651 #undef RETURN_NAME_AS_STRING
652 }
653
654 /**
655 Storage engine specific thread local data.
656 */
657
658 struct Ha_data {
659 /**
660 Storage engine specific thread local data.
661 Lifetime: one user connection.
662 */
663 void *ha_ptr;
664 /**
665 A memorizer to engine specific "native" transaction object to provide
666 storage engine detach-re-attach facility.
667 The server level transaction object can dissociate from storage engine
668 transactions. The released "native" transaction reference
669 can be hold in the member until it is reconciled later.
670 Lifetime: Depends on caller of @c hton::replace_native_transaction_in_thd.
671 For instance in the case of slave server applier handling XA transaction
672 it is from XA START to XA PREPARE.
673 */
674 void *ha_ptr_backup;
675 /**
676 0: Life time: one statement within a transaction. If @@autocommit is
677 on, also represents the entire transaction.
678 @sa trans_register_ha()
679
680 1: Life time: one transaction within a connection.
681 If the storage engine does not participate in a transaction,
682 this should not be used.
683 @sa trans_register_ha()
684 */
685 Ha_trx_info ha_info[2];
686
687 /**
688 NULL: engine is not bound to this thread
689 non-NULL: engine is bound to this thread, engine shutdown forbidden
690 */
691 plugin_ref lock;
692
Ha_dataHa_data693 Ha_data() : ha_ptr(nullptr), ha_ptr_backup(nullptr), lock(nullptr) {}
694 };
695
696 /**
697 An instance of the global read lock in a connection.
698 Implemented in lock.cc.
699 */
700
701 class Global_read_lock {
702 public:
703 enum enum_grl_state {
704 GRL_NONE,
705 GRL_ACQUIRED,
706 GRL_ACQUIRED_AND_BLOCKS_COMMIT
707 };
708
Global_read_lock()709 Global_read_lock()
710 : m_state(GRL_NONE),
711 m_mdl_global_shared_lock(nullptr),
712 m_mdl_blocks_commits_lock(nullptr) {}
713
714 bool lock_global_read_lock(THD *thd);
715 void unlock_global_read_lock(THD *thd);
716
717 /**
718 Used by innodb memcached server to check if any connections
719 have global read lock
720 */
global_read_lock_active()721 static bool global_read_lock_active() { return m_atomic_active_requests > 0; }
722
723 /**
724 Check if this connection can acquire protection against GRL and
725 emit error if otherwise.
726 */
can_acquire_protection()727 bool can_acquire_protection() const {
728 if (m_state) {
729 my_error(ER_CANT_UPDATE_WITH_READLOCK, MYF(0));
730 return true;
731 }
732 return false;
733 }
734 bool make_global_read_lock_block_commit(THD *thd);
is_acquired()735 bool is_acquired() const { return m_state != GRL_NONE; }
736 void set_explicit_lock_duration(THD *thd);
737
738 private:
739 static std::atomic<int32> m_atomic_active_requests;
740 enum_grl_state m_state;
741 /**
742 In order to acquire the global read lock, the connection must
743 acquire shared metadata lock in GLOBAL namespace, to prohibit
744 all DDL.
745 */
746 MDL_ticket *m_mdl_global_shared_lock;
747 /**
748 Also in order to acquire the global read lock, the connection
749 must acquire a shared metadata lock in COMMIT namespace, to
750 prohibit commits.
751 */
752 MDL_ticket *m_mdl_blocks_commits_lock;
753 };
754
755 extern "C" void my_message_sql(uint error, const char *str, myf MyFlags);
756
757 /**
758 This class keeps the context of transactional DDL statements. Currently only
759 CREATE TABLE with START TRANSACTION uses this context.
760 */
761 class Transactional_ddl_context {
762 public:
Transactional_ddl_context(THD * thd)763 explicit Transactional_ddl_context(THD *thd) : m_thd(thd) {
764 DBUG_ASSERT(m_thd != nullptr);
765 }
766
~Transactional_ddl_context()767 ~Transactional_ddl_context() {
768 DBUG_ASSERT(!m_hton);
769 post_ddl();
770 }
771
772 void init(dd::String_type db, dd::String_type tablename,
773 const handlerton *hton);
774
inited()775 bool inited() { return m_hton != nullptr; }
776
777 void rollback();
778
779 void post_ddl();
780
781 private:
782 // The current thread.
783 THD *m_thd{nullptr};
784
785 // Handlerton pointer to table's engine begin created.
786 const handlerton *m_hton{nullptr};
787
788 // Schema and table name being created.
789 dd::String_type m_db{};
790 dd::String_type m_tablename{};
791 };
792
793 /**
794 @class THD
795 For each client connection we create a separate thread with THD serving as
796 a thread/connection descriptor
797 */
798
799 class THD : public MDL_context_owner,
800 public Query_arena,
801 public Open_tables_state {
802 private:
is_stmt_prepare()803 inline bool is_stmt_prepare() const {
804 DBUG_ASSERT(0);
805 return Query_arena::is_stmt_prepare();
806 }
807
is_stmt_prepare_or_first_sp_execute()808 inline bool is_stmt_prepare_or_first_sp_execute() const {
809 DBUG_ASSERT(0);
810 return Query_arena::is_stmt_prepare_or_first_sp_execute();
811 }
812
is_stmt_prepare_or_first_stmt_execute()813 inline bool is_stmt_prepare_or_first_stmt_execute() const {
814 DBUG_ASSERT(0);
815 return Query_arena::is_stmt_prepare_or_first_stmt_execute();
816 }
817
is_regular()818 inline bool is_regular() const {
819 DBUG_ASSERT(0);
820 return Query_arena::is_regular();
821 }
822
823 public:
824 MDL_context mdl_context;
825
826 /*
827 MARK_COLUMNS_NONE: Means mark_used_colums is not set and no indicator to
828 handler of fields used is set
829 MARK_COLUMNS_READ: Means a bit in read set is set to inform handler
830 that the field is to be read. Update covering_keys
831 and merge_keys too.
832 MARK_COLUMNS_WRITE: Means a bit is set in write set to inform handler
833 that it needs to update this field in write_row
834 and update_row.
835 MARK_COLUMNS_TEMP: Mark bit in read set, but ignore key sets.
836 Used by filesort().
837 */
838 enum enum_mark_columns mark_used_columns;
839 /**
840 Used by Item::check_column_privileges() to tell which privileges
841 to check for.
842 Set to ~0ULL before starting to resolve a statement.
843 Set to desired privilege mask before calling a resolver function that will
844 call Item::check_column_privileges().
845 After use, restore previous value as current value.
846 */
847 ulong want_privilege;
848
849 private:
850 /**
851 The lex to hold the parsed tree of conventional (non-prepared) queries.
852 Whereas for prepared and stored procedure statements we use an own lex
853 instance for each new query, for conventional statements we reuse
854 the same lex. (@see mysql_parse for details).
855 */
856 std::unique_ptr<LEX> main_lex;
857
858 public:
859 LEX *lex; // parse tree descriptor
dd_client()860 dd::cache::Dictionary_client *dd_client() const // Get the dictionary client.
861 {
862 return m_dd_client.get();
863 }
864
865 private:
866 std::unique_ptr<dd::cache::Dictionary_client> m_dd_client;
867
868 /**
869 The query associated with this statement.
870 */
871 LEX_CSTRING m_query_string;
872 String m_normalized_query;
873
874 /**
875 Currently selected catalog.
876 */
877
878 LEX_CSTRING m_catalog;
879 /**
880 Name of the current (default) database.
881
882 If there is the current (default) database, "db" contains its name. If
883 there is no current (default) database, "db" is NULL and "db_length" is
884 0. In other words, "db", "db_length" must either be NULL, or contain a
885 valid database name.
886
887 @note this attribute is set and alloced by the slave SQL thread (for
888 the THD of that thread); that thread is (and must remain, for now) the
889 only responsible for freeing this member.
890 */
891 LEX_CSTRING m_db;
892
893 /**
894 Resource group context indicating the current resource group
895 and the name of the resource group to switch to during execution
896 of a query.
897 */
898 resourcegroups::Resource_group_ctx m_resource_group_ctx;
899
900 /**
901 In some cases, we may want to modify the query (i.e. replace
902 passwords with their hashes before logging the statement etc.).
903
904 In case the query was rewritten, the original query will live in
905 m_query_string, while the rewritten query lives in rewritten_query.
906 If rewritten_query is empty, m_query_string should be logged.
907 If rewritten_query is non-empty, the rewritten query it contains
908 should be used in logs (general log, slow query log, binary log).
909
910 Currently, password obfuscation is the only rewriting we do; more
911 may follow at a later date, both pre- and post parsing of the query.
912 Rewriting of binloggable statements must preserve all pertinent
913 information.
914
915 Similar restrictions as for m_query_string (see there) hold for locking:
916 - Value may only be (re)set from owning thread (current_thd)
917 - Value must be modified using (reset|swap)_rewritten_query().
918 Doing so will protect the update with LOCK_thd_query.
919 - The owner (current_thd) may read the value without holding the lock.
920 - Other threads may read the value, but must hold LOCK_thd_query to do so.
921 */
922 String m_rewritten_query;
923
924 public:
925 /* Used to execute base64 coded binlog events in MySQL server */
926 Relay_log_info *rli_fake;
927 /* Slave applier execution context */
928 Relay_log_info *rli_slave;
929
930 /* Is transaction commit still pending */
931 bool tx_commit_pending;
932
933 /**
934 The function checks whether the thread is processing queries from binlog,
935 as automatically generated by mysqlbinlog.
936
937 @return true when the thread is a binlog applier
938 */
is_binlog_applier()939 bool is_binlog_applier() const {
940 return rli_fake && variables.pseudo_slave_mode;
941 }
942
943 /**
944 When the thread is a binlog or slave applier it detaches the engine
945 ha_data associated with it and memorizes the fact of that.
946 */
947 void rpl_detach_engine_ha_data();
948
949 /**
950 When the thread is a binlog or slave applier it reattaches the engine
951 ha_data associated with it and memorizes the fact of that.
952 */
953 void rpl_reattach_engine_ha_data();
954
955 /**
956 @return true when the current binlog (rli_fake) or slave (rli_slave)
957 applier thread has detached the engine ha_data,
958 see @c rpl_detach_engine_ha_data.
959 @note The detached transaction applier resets a memo
960 mark at once with this check.
961 */
962 bool rpl_unflag_detached_engine_ha_data() const;
963
964 void reset_for_next_command();
965 /*
966 Constant for THD::where initialization in the beginning of every query.
967
968 It's needed because we do not save/restore THD::where normally during
969 primary (non subselect) query execution.
970 */
971 static const char *const DEFAULT_WHERE;
972
973 /** Aditional network instrumentation for the server only. */
974 NET_SERVER m_net_server_extension;
975 /**
976 Hash for user variables.
977 User variables are per session,
978 but can also be monitored outside of the session,
979 so a lock is needed to prevent race conditions.
980 Protected by @c LOCK_thd_data.
981 */
982 collation_unordered_map<std::string, unique_ptr_with_deleter<user_var_entry>>
983 user_vars{system_charset_info, key_memory_user_var_entry};
984 struct rand_struct rand; // used for authentication
985 struct System_variables variables; // Changeable local variables
986 struct System_status_var status_var; // Per thread statistic vars
987 struct System_status_var *initial_status_var; /* used by show status */
988 // has status_var already been added to global_status_var?
989 bool status_var_aggregated;
990
991 /**
992 Session's connection attributes for the connected client
993 */
994 std::vector<char> m_connection_attributes;
995
996 /**
997 Current query cost.
998 @sa system_status_var::last_query_cost
999 */
1000 double m_current_query_cost;
1001 /**
1002 Current query partial plans.
1003 @sa system_status_var::last_query_partial_plans
1004 */
1005 ulonglong m_current_query_partial_plans;
1006
1007 /**
1008 Clear the query costs attributes for the current query.
1009 */
clear_current_query_costs()1010 void clear_current_query_costs() {
1011 m_current_query_cost = 0.0;
1012 m_current_query_partial_plans = 0;
1013 }
1014
1015 /**
1016 Save the current query costs attributes in
1017 the thread session status.
1018 Use this method only after the query execution is completed,
1019 so that
1020 @code SHOW SESSION STATUS like 'last_query_%' @endcode
1021 @code SELECT * from performance_schema.session_status
1022 WHERE VARIABLE_NAME like 'last_query_%' @endcode
1023 actually reports the previous query, not itself.
1024 */
save_current_query_costs()1025 void save_current_query_costs() {
1026 DBUG_ASSERT(!status_var_aggregated);
1027 status_var.last_query_cost = m_current_query_cost;
1028 status_var.last_query_partial_plans = m_current_query_partial_plans;
1029 }
1030
1031 THR_LOCK_INFO lock_info; // Locking info of this thread
1032 /**
1033 Protects THD data accessed from other threads.
1034 The attributes protected are:
1035 - thd->is_killable (used by KILL statement and shutdown).
1036 - thd->user_vars (user variables, inspected by monitoring)
1037 Is locked when THD is deleted.
1038 */
1039 mysql_mutex_t LOCK_thd_data;
1040
1041 /**
1042 Protects THD::m_query_string. No other mutexes should be locked
1043 while having this mutex locked.
1044 */
1045 mysql_mutex_t LOCK_thd_query;
1046
1047 /**
1048 Protects THD::variables while being updated. This should be taken inside
1049 of LOCK_thd_data and outside of LOCK_global_system_variables.
1050 */
1051 mysql_mutex_t LOCK_thd_sysvar;
1052
1053 /**
1054 Protects THD::m_protocol when it gets removed in x plugin.
1055 */
1056 mysql_mutex_t LOCK_thd_protocol;
1057
1058 /**
1059 Protects query plan (SELECT/UPDATE/DELETE's) from being freed/changed
1060 while another thread explains it. Following structures are protected by
1061 this mutex:
1062 THD::Query_plan
1063 Modification_plan
1064 SELECT_LEX::join
1065 JOIN::plan_state
1066 Tree of SELECT_LEX_UNIT after THD::Query_plan was set till
1067 THD::Query_plan cleanup
1068 JOIN_TAB::select->quick
1069 Code that changes objects above should take this mutex.
1070 Explain code takes this mutex to block changes to named structures to
1071 avoid crashes in following functions:
1072 explain_single_table_modification
1073 explain_query
1074 Sql_cmd_explain_other_thread::execute
1075 When doing EXPLAIN CONNECTION:
1076 all explain code assumes that this mutex is already taken.
1077 When doing ordinary EXPLAIN:
1078 the mutex does need to be taken (no need to protect reading my own data,
1079 moreover EXPLAIN CONNECTION can't run on an ordinary EXPLAIN).
1080 */
1081 private:
1082 mysql_mutex_t LOCK_query_plan;
1083
1084 public:
1085 /// Locks the query plan of this THD
lock_query_plan()1086 void lock_query_plan() { mysql_mutex_lock(&LOCK_query_plan); }
unlock_query_plan()1087 void unlock_query_plan() { mysql_mutex_unlock(&LOCK_query_plan); }
1088
1089 /** All prepared statements of this connection. */
1090 Prepared_statement_map stmt_map;
1091 /*
1092 A pointer to the stack frame of handle_one_connection(),
1093 which is called first in the thread for handling a client
1094 */
1095 const char *thread_stack;
1096
1097 /**
1098 @note
1099 Some members of THD (currently 'Statement::db',
1100 'catalog' and 'query') are set and alloced by the slave SQL thread
1101 (for the THD of that thread); that thread is (and must remain, for now)
1102 the only responsible for freeing these 3 members. If you add members
1103 here, and you add code to set them in replication, don't forget to
1104 free_them_and_set_them_to_0 in replication properly. For details see
1105 the 'err:' label of the handle_slave_sql() in sql/slave.cc.
1106
1107 @see handle_slave_sql
1108 */
1109
1110 Security_context m_main_security_ctx;
1111 Security_context *m_security_ctx;
1112
security_context()1113 Security_context *security_context() const { return m_security_ctx; }
set_security_context(Security_context * sctx)1114 void set_security_context(Security_context *sctx) { m_security_ctx = sctx; }
1115 List<Security_context> m_view_ctx_list;
1116
1117 /**
1118 @note
1119 The optional password validation plugin doesn't have any API for
1120 temporally disable its functionality for a particular session.
1121 To get around this issue we introduce a boolean variable in the THD
1122 which we check before each call to the password validation plugin.
1123 Password validation is invoked from within the authentication plugin
1124 in the generate_authentication_string() method.
1125
1126 @see generate_authentication_string
1127 */
1128 bool m_disable_password_validation;
1129
1130 /*
1131 Points to info-string that we show in SHOW PROCESSLIST
1132 You are supposed to update thd->proc_info only if you have coded
1133 a time-consuming piece that MySQL can get stuck in for a long time.
1134
1135 Set it using the thd_proc_info(THD *thread, const char *message)
1136 macro/function.
1137
1138 This member is accessed and assigned without any synchronization.
1139 Therefore, it may point only to constant (statically
1140 allocated) strings, which memory won't go away over time.
1141 */
1142 const char *proc_info;
1143
1144 std::unique_ptr<Protocol_text> protocol_text; // Normal protocol
1145 std::unique_ptr<Protocol_binary> protocol_binary; // Binary protocol
1146
get_protocol()1147 const Protocol *get_protocol() const { return m_protocol; }
1148
get_protocol()1149 Protocol *get_protocol() { return m_protocol; }
1150
get_ssl()1151 SSL_handle get_ssl() const {
1152 #ifndef DBUG_OFF
1153 if (current_thd != this) {
1154 /*
1155 When inspecting this thread from monitoring,
1156 the monitoring thread MUST lock LOCK_thd_data,
1157 to be allowed to safely inspect SSL status variables.
1158 */
1159 mysql_mutex_assert_owner(&LOCK_thd_data);
1160 }
1161 #endif
1162 return m_SSL;
1163 }
1164
1165 /**
1166 Asserts that the protocol is of type text or binary and then
1167 returns the m_protocol casted to Protocol_classic. This method
1168 is needed to prevent misuse of pluggable protocols by legacy code
1169 */
get_protocol_classic()1170 const Protocol_classic *get_protocol_classic() const {
1171 DBUG_ASSERT(is_classic_protocol());
1172 return pointer_cast<const Protocol_classic *>(m_protocol);
1173 }
1174
get_protocol_classic()1175 Protocol_classic *get_protocol_classic() {
1176 DBUG_ASSERT(is_classic_protocol());
1177 return pointer_cast<Protocol_classic *>(m_protocol);
1178 }
1179
1180 private:
1181 Protocol *m_protocol; // Current protocol
1182 /**
1183 SSL data attached to this connection.
1184 This is an opaque pointer,
1185 When building with SSL, this pointer is non NULL
1186 only if the connection is using SSL.
1187 When building without SSL, this pointer is always NULL.
1188 The SSL data can be inspected to read per thread
1189 status variables,
1190 and this can be inspected while the thread is running.
1191 */
1192 SSL_handle m_SSL = {nullptr};
1193
1194 public:
1195 /**
1196 Query plan for EXPLAINable commands, should be locked with
1197 LOCK_query_plan before using.
1198 */
1199 class Query_plan {
1200 private:
1201 THD *const thd;
1202 /// Original sql_command;
1203 enum_sql_command sql_command;
1204 /// LEX of topmost statement
1205 LEX *lex;
1206 /// Query plan for UPDATE/DELETE/INSERT/REPLACE
1207 const Modification_plan *modification_plan;
1208 /// True if query is run in prepared statement
1209 bool is_ps;
1210
1211 explicit Query_plan(const Query_plan &); ///< not defined
1212 Query_plan &operator=(const Query_plan &); ///< not defined
1213
1214 public:
1215 /// Asserts that current_thd has locked this plan, if it does not own it.
assert_plan_is_locked_if_other()1216 void assert_plan_is_locked_if_other() const
1217 #ifdef DBUG_OFF
1218 {
1219 }
1220 #else
1221 ;
1222 #endif
1223
Query_plan(THD * thd_arg)1224 explicit Query_plan(THD *thd_arg)
1225 : thd(thd_arg),
1226 sql_command(SQLCOM_END),
1227 lex(nullptr),
1228 modification_plan(nullptr),
1229 is_ps(false) {}
1230
1231 /**
1232 Set query plan.
1233
1234 @note This function takes THD::LOCK_query_plan mutex.
1235 */
1236 void set_query_plan(enum_sql_command sql_cmd, LEX *lex_arg, bool ps);
1237
1238 /*
1239 The 4 getters below expect THD::LOCK_query_plan to be already taken
1240 if called from another thread.
1241 */
get_command()1242 enum_sql_command get_command() const {
1243 assert_plan_is_locked_if_other();
1244 return sql_command;
1245 }
get_lex()1246 LEX *get_lex() const {
1247 assert_plan_is_locked_if_other();
1248 return lex;
1249 }
get_modification_plan()1250 Modification_plan const *get_modification_plan() const {
1251 assert_plan_is_locked_if_other();
1252 return modification_plan;
1253 }
is_ps_query()1254 bool is_ps_query() const {
1255 assert_plan_is_locked_if_other();
1256 return is_ps;
1257 }
1258 bool is_single_table_plan() const;
1259 void set_modification_plan(Modification_plan *plan_arg);
1260
1261 } query_plan;
1262
catalog()1263 const LEX_CSTRING &catalog() const { return m_catalog; }
1264
set_catalog(const LEX_CSTRING & catalog)1265 void set_catalog(const LEX_CSTRING &catalog) { m_catalog = catalog; }
1266
1267 private:
1268 unsigned int m_current_stage_key;
1269
1270 public:
1271 // See comment in THD::enter_cond about why SUPPRESS_TSAN is needed.
1272 void enter_stage(const PSI_stage_info *stage, PSI_stage_info *old_stage,
1273 const char *calling_func, const char *calling_file,
1274 const unsigned int calling_line) SUPPRESS_TSAN;
get_proc_info()1275 const char *get_proc_info() const { return proc_info; }
1276
1277 /*
1278 Used in error messages to tell user in what part of MySQL we found an
1279 error. E. g. when where= "having clause", if fix_fields() fails, user
1280 will know that the error was in having clause.
1281 */
1282 const char *where;
1283
1284 ulong max_client_packet_length;
1285
1286 collation_unordered_map<std::string, unique_ptr_my_free<TABLE_LIST>>
1287 handler_tables_hash{&my_charset_latin1,
1288 key_memory_THD_handler_tables_hash};
1289 /*
1290 A thread can hold named user-level locks. This variable
1291 contains granted tickets if a lock is present. See item_func.cc and
1292 chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK.
1293 */
1294 malloc_unordered_map<std::string, User_level_lock *> ull_hash{
1295 key_memory_User_level_lock};
1296 #ifndef DBUG_OFF
1297 uint dbug_sentry; // watch out for memory corruption
1298 #endif
1299 bool is_killable;
1300 /**
1301 Mutex protecting access to current_mutex and current_cond.
1302 */
1303 mysql_mutex_t LOCK_current_cond;
1304 /**
1305 The mutex used with current_cond.
1306 @see current_cond
1307 */
1308 std::atomic<mysql_mutex_t *> current_mutex;
1309 /**
1310 Pointer to the condition variable the thread owning this THD
1311 is currently waiting for. If the thread is not waiting, the
1312 value is NULL. Set by THD::enter_cond().
1313
1314 If this thread is killed (shutdown or KILL stmt), another
1315 thread will broadcast on this condition variable so that the
1316 thread can be unstuck.
1317 */
1318 std::atomic<mysql_cond_t *> current_cond;
1319 /**
1320 Condition variable used for waiting by the THR_LOCK.c subsystem.
1321 */
1322 mysql_cond_t COND_thr_lock;
1323
1324 private:
1325 /**
1326 Type of current query: COM_STMT_PREPARE, COM_QUERY, etc.
1327 Set from first byte of the packet in do_command()
1328 */
1329 enum enum_server_command m_command;
1330
1331 private:
1332 bool m_is_admin_conn;
1333
1334 public:
set_admin_connection(bool admin)1335 void set_admin_connection(bool admin) { m_is_admin_conn = admin; }
is_admin_connection()1336 bool is_admin_connection() const { return m_is_admin_conn; }
1337
1338 uint32 unmasked_server_id;
1339 uint32 server_id;
1340 uint32 file_id; // for LOAD DATA INFILE
1341 /* remote (peer) port */
1342 uint16 peer_port;
1343 struct timeval start_time;
1344 struct timeval user_time;
1345 ulonglong start_utime, utime_after_lock;
1346
1347 /**
1348 Type of lock to be used for all DML statements, except INSERT, in cases
1349 when lock is not specified explicitly. Set to TL_WRITE or
1350 TL_WRITE_LOW_PRIORITY depending on whether low_priority_updates option is
1351 off or on.
1352 */
1353 thr_lock_type update_lock_default;
1354 /**
1355 Type of lock to be used for INSERT statement if lock is not specified
1356 explicitly. Set to TL_WRITE_CONCURRENT_INSERT or TL_WRITE_LOW_PRIORITY
1357 depending on whether low_priority_updates option is off or on.
1358 */
1359 thr_lock_type insert_lock_default;
1360
1361 /* <> 0 if we are inside of trigger or stored function. */
1362 uint in_sub_stmt;
1363
1364 /**
1365 Used by fill_status() to avoid acquiring LOCK_status mutex twice
1366 when this function is called recursively (e.g. queries
1367 that contains SELECT on I_S.GLOBAL_STATUS with subquery on the
1368 same I_S table).
1369 Incremented each time fill_status() function is entered and
1370 decremented each time before it returns from the function.
1371 */
1372 uint fill_status_recursion_level;
1373 uint fill_variables_recursion_level;
1374
1375 private:
1376 /* container for handler's private per-connection data */
1377 Prealloced_array<Ha_data, PREALLOC_NUM_HA> ha_data;
1378
1379 public:
1380 /**
1381 Retrieve Ha_data for a given slot. Each handler has a fixed slot nr.
1382 */
get_ha_data(int slot)1383 Ha_data *get_ha_data(int slot) { return &ha_data[slot]; }
1384
1385 /**
1386 Copy ha_data into the provided argument. Used by Attachble_transaction.
1387 */
backup_ha_data(Prealloced_array<Ha_data,PREALLOC_NUM_HA> * backup)1388 void backup_ha_data(Prealloced_array<Ha_data, PREALLOC_NUM_HA> *backup) {
1389 /*
1390 Protect with LOCK_thd_data avoid accessing ha_data while it
1391 is being modified.
1392 */
1393 mysql_mutex_lock(&this->LOCK_thd_data);
1394 *backup = ha_data;
1395 mysql_mutex_unlock(&this->LOCK_thd_data);
1396 }
1397
1398 /**
1399 Restore ha_data from the provided backup copy.
1400 Used by Attachable_Transaction.
1401 */
restore_ha_data(const Prealloced_array<Ha_data,PREALLOC_NUM_HA> & backup)1402 void restore_ha_data(
1403 const Prealloced_array<Ha_data, PREALLOC_NUM_HA> &backup) {
1404 /*
1405 Protect with LOCK_thd_data to avoid e.g. KILL CONNECTION
1406 reading ha_data while it is being modified.
1407 */
1408 mysql_mutex_lock(&this->LOCK_thd_data);
1409 ha_data = backup;
1410 mysql_mutex_unlock(&this->LOCK_thd_data);
1411 }
1412
1413 /*
1414 Position of first event in Binlog
1415 *after* last event written by this
1416 thread.
1417 */
1418 rpl_event_coordinates binlog_next_event_pos;
1419 void set_next_event_pos(const char *_filename, ulonglong _pos);
1420 void clear_next_event_pos();
1421
1422 /*
1423 Ptr to row event extra data to be written to Binlog /
1424 received from Binlog.
1425
1426 */
1427 uchar *binlog_row_event_extra_data;
1428
1429 int binlog_setup_trx_data();
1430
1431 /*
1432 Public interface to write RBR events to the binlog
1433 */
1434 int binlog_write_table_map(TABLE *table, bool is_transactional,
1435 bool binlog_rows_query);
1436 int binlog_write_row(TABLE *table, bool is_transactional,
1437 const uchar *new_data,
1438 const unsigned char *extra_row_info);
1439 int binlog_delete_row(TABLE *table, bool is_transactional,
1440 const uchar *old_data,
1441 const unsigned char *extra_row_info);
1442 int binlog_update_row(TABLE *table, bool is_transactional,
1443 const uchar *old_data, const uchar *new_data,
1444 const uchar *extra_row_info);
set_server_id(uint32 sid)1445 void set_server_id(uint32 sid) { server_id = sid; }
1446
1447 /*
1448 Member functions to handle pending event for row-level logging.
1449 */
1450 template <class RowsEventT>
1451 Rows_log_event *binlog_prepare_pending_rows_event(
1452 TABLE *table, uint32 serv_id, size_t needed, bool is_transactional,
1453 const unsigned char *extra_row_info, uint32 source_part_id = INT_MAX);
1454 Rows_log_event *binlog_get_pending_rows_event(bool is_transactional) const;
binlog_flush_pending_rows_event(bool stmt_end)1455 inline int binlog_flush_pending_rows_event(bool stmt_end) {
1456 return (binlog_flush_pending_rows_event(stmt_end, false) ||
1457 binlog_flush_pending_rows_event(stmt_end, true));
1458 }
1459 int binlog_flush_pending_rows_event(bool stmt_end, bool is_transactional);
1460
1461 /**
1462 Determine the binlog format of the current statement.
1463
1464 @retval 0 if the current statement will be logged in statement
1465 format.
1466 @retval nonzero if the current statement will be logged in row
1467 format.
1468 */
is_current_stmt_binlog_format_row()1469 int is_current_stmt_binlog_format_row() const {
1470 DBUG_ASSERT(current_stmt_binlog_format == BINLOG_FORMAT_STMT ||
1471 current_stmt_binlog_format == BINLOG_FORMAT_ROW);
1472 return current_stmt_binlog_format == BINLOG_FORMAT_ROW;
1473 }
1474
1475 /**
1476 Determine if binlogging is currently disabled for this session.
1477
1478 There are two ways that binlogging can be disabled:
1479
1480 1. The binary log file is closed (globally). This can happen for
1481 two reasons: either --skip-log-bin was used on the command line,
1482 or a binlog write error happened when binlog_error_action=IGNORE_ERROR.
1483
1484 2. The binary log is disabled on session level. This can happen for
1485 two reasons: either the user has set @@session.sql_log_bin = 0,
1486 or the server code has internally disabled the binary log (by
1487 either setting thd->variables.option_bits &= ~OPTION_BIN_LOG or
1488 creating a Disable_binlog_guard object).
1489
1490 Even if this function returns true and the binary log is disabled,
1491 it is possible that the statement will be written to the binary log,
1492 in the cases where the server has merely temporarily disabled binary
1493 logging.
1494
1495 And even if this function returns false and the binary log is
1496 enabled, it is possible that the statement will not be written to
1497 the binary log, e.g. in case it is a no-op, it fails, it gets rolled
1498 back, or some other session closes the binary log due to a write
1499 error when using binlog_error_action=IGNORE_ERROR.
1500
1501 @retval true The binary log is currently disabled for the statement.
1502
1503 @retval false The binary log is currently enabled for the statement.
1504 */
1505 bool is_current_stmt_binlog_disabled() const;
1506
1507 /**
1508 Determine if binlogging is currently disabled for this session.
1509 If the binary log is disabled for this thread (either by log_bin=0 or
1510 sql_log_bin=0 or by log_slave_updates=0 for a slave thread), then the
1511 statement will not be written to the binary log.
1512
1513 @retval true The binary log is currently disabled for the statement.
1514
1515 @retval false The binary log is currently enabled for the statement.
1516 */
1517 bool is_current_stmt_binlog_log_slave_updates_disabled() const;
1518
1519 /**
1520 Determine if binloging is enabled in row format and write set extraction is
1521 enabled for this session
1522 @retval true if is enable
1523 @retval false otherwise
1524 */
1525 bool is_current_stmt_binlog_row_enabled_with_write_set_extraction() const;
1526
1527 /** Tells whether the given optimizer_switch flag is on */
optimizer_switch_flag(ulonglong flag)1528 inline bool optimizer_switch_flag(ulonglong flag) const {
1529 return (variables.optimizer_switch & flag);
1530 }
1531
1532 enum binlog_filter_state {
1533 BINLOG_FILTER_UNKNOWN,
1534 BINLOG_FILTER_CLEAR,
1535 BINLOG_FILTER_SET
1536 };
1537
reset_binlog_local_stmt_filter()1538 inline void reset_binlog_local_stmt_filter() {
1539 m_binlog_filter_state = BINLOG_FILTER_UNKNOWN;
1540 }
1541
clear_binlog_local_stmt_filter()1542 inline void clear_binlog_local_stmt_filter() {
1543 DBUG_ASSERT(m_binlog_filter_state == BINLOG_FILTER_UNKNOWN);
1544 m_binlog_filter_state = BINLOG_FILTER_CLEAR;
1545 }
1546
set_binlog_local_stmt_filter()1547 inline void set_binlog_local_stmt_filter() {
1548 DBUG_ASSERT(m_binlog_filter_state == BINLOG_FILTER_UNKNOWN);
1549 m_binlog_filter_state = BINLOG_FILTER_SET;
1550 }
1551
get_binlog_local_stmt_filter()1552 binlog_filter_state get_binlog_local_stmt_filter() const {
1553 return m_binlog_filter_state;
1554 }
1555
1556 /** Holds active timer object */
1557 struct THD_timer_info *timer;
1558 /**
1559 After resetting(cancelling) timer, current timer object is cached
1560 with timer_cache timer to reuse.
1561 */
1562 struct THD_timer_info *timer_cache;
1563
1564 private:
1565 /*
1566 Indicates that the command which is under execution should ignore the
1567 'read_only' and 'super_read_only' options.
1568 */
1569 bool skip_readonly_check;
1570 /**
1571 Indicate if the current statement should be discarded
1572 instead of written to the binlog.
1573 This is used to discard special statements, such as
1574 DML or DDL that affects only 'local' (non replicated)
1575 tables, such as performance_schema.*
1576 */
1577 binlog_filter_state m_binlog_filter_state;
1578
1579 /**
1580 Indicates the format in which the current statement will be
1581 logged. This can only be set from @c decide_logging_format().
1582 */
1583 enum_binlog_format current_stmt_binlog_format;
1584
1585 /**
1586 Bit field for the state of binlog warnings.
1587
1588 The first Lex::BINLOG_STMT_UNSAFE_COUNT bits list all types of
1589 unsafeness that the current statement has.
1590
1591 This must be a member of THD and not of LEX, because warnings are
1592 detected and issued in different places (@c
1593 decide_logging_format() and @c binlog_query(), respectively).
1594 Between these calls, the THD->lex object may change; e.g., if a
1595 stored routine is invoked. Only THD persists between the calls.
1596 */
1597 uint32 binlog_unsafe_warning_flags;
1598
1599 /*
1600 Number of outstanding table maps, i.e., table maps in the
1601 transaction cache.
1602 */
1603 uint binlog_table_maps;
1604 /*
1605 MTS: db names listing to be updated by the query databases
1606 */
1607 List<char> *binlog_accessed_db_names;
1608
1609 /**
1610 The binary log position of the transaction.
1611
1612 The file and position are zero if the current transaction has not
1613 been written to the binary log.
1614
1615 @see set_trans_pos
1616 @see get_trans_pos
1617
1618 @todo Similar information is kept in the patch for BUG#11762277
1619 and by the master/slave heartbeat implementation. We should merge
1620 these positions instead of maintaining three different ones.
1621 */
1622 /**@{*/
1623 const char *m_trans_log_file;
1624 char *m_trans_fixed_log_file;
1625 my_off_t m_trans_end_pos;
1626 /**@}*/
1627 // NOTE: Ideally those two should be in Protocol,
1628 // but currently its design doesn't allow that.
1629 NET net; // client connection descriptor
1630 String packet; // dynamic buffer for network I/O
1631 public:
set_skip_readonly_check()1632 void set_skip_readonly_check() { skip_readonly_check = true; }
1633
is_cmd_skip_readonly()1634 bool is_cmd_skip_readonly() const { return skip_readonly_check; }
1635
reset_skip_readonly_check()1636 void reset_skip_readonly_check() {
1637 if (skip_readonly_check) skip_readonly_check = false;
1638 }
1639
1640 void issue_unsafe_warnings();
1641
get_binlog_table_maps()1642 uint get_binlog_table_maps() const { return binlog_table_maps; }
clear_binlog_table_maps()1643 void clear_binlog_table_maps() { binlog_table_maps = 0; }
1644
1645 /*
1646 MTS: accessor to binlog_accessed_db_names list
1647 */
get_binlog_accessed_db_names()1648 List<char> *get_binlog_accessed_db_names() const {
1649 return binlog_accessed_db_names;
1650 }
1651
1652 /* MTS: method inserts a new unique name into binlog_updated_dbs */
1653 void add_to_binlog_accessed_dbs(const char *db);
1654
1655 private:
1656 std::unique_ptr<Transaction_ctx> m_transaction;
1657
1658 /** An utility struct for @c Attachable_trx */
1659 struct Transaction_state {
1660 Transaction_state();
1661 ~Transaction_state();
1662 void backup(THD *thd);
1663 void restore(THD *thd);
1664
1665 /// SQL-command.
1666 enum_sql_command m_sql_command;
1667
1668 Query_tables_list *m_query_tables_list;
1669
1670 /// Open-tables state.
1671 Open_tables_backup m_open_tables_state;
1672
1673 /// SQL_MODE.
1674 sql_mode_t m_sql_mode;
1675
1676 /// Transaction isolation level.
1677 enum_tx_isolation m_tx_isolation;
1678
1679 /// Ha_data array.
1680 Prealloced_array<Ha_data, PREALLOC_NUM_HA> m_ha_data;
1681
1682 /// Transaction_ctx instance.
1683 Transaction_ctx *m_trx;
1684
1685 /// Transaction read-only state.
1686 bool m_tx_read_only;
1687
1688 /// THD options.
1689 ulonglong m_thd_option_bits;
1690
1691 /// Current transaction instrumentation.
1692 PSI_transaction_locker *m_transaction_psi;
1693
1694 /// Server status flags.
1695 uint m_server_status;
1696
1697 /// THD::in_lock_tables value.
1698 bool m_in_lock_tables;
1699
1700 /**
1701 Current time zone (i.e. @@session.time_zone) usage indicator.
1702
1703 Saving it allows data-dictionary code to read timestamp values
1704 as datetimes from system tables without disturbing user's statement.
1705
1706 TODO: We need to change DD code not to use @@session.time_zone at all and
1707 stick to UTC for internal storage of timestamps in DD objects.
1708 */
1709 bool m_time_zone_used;
1710
1711 /**
1712 Transaction rollback request flag.
1713
1714 InnoDB can try to access table definition while rolling back regular
1715 transaction. So we need to be able to start attachable transaction
1716 without being affected by, and affecting, the rollback state of regular
1717 transaction.
1718 */
1719 bool m_transaction_rollback_request;
1720 };
1721
1722 public:
1723 enum enum_reset_lex { RESET_LEX, DO_NOT_RESET_LEX };
1724
1725 private:
1726 /**
1727 Class representing read-only attachable transaction, encapsulates
1728 knowledge how to backup state of current transaction, start
1729 read-only attachable transaction in SE, finalize it and then restore
1730 state of original transaction back. Also serves as a base class for
1731 read-write attachable transaction implementation.
1732 */
1733 class Attachable_trx {
1734 public:
1735 Attachable_trx(THD *thd, Attachable_trx *prev_trx);
1736 virtual ~Attachable_trx();
get_prev_attachable_trx()1737 Attachable_trx *get_prev_attachable_trx() const {
1738 return m_prev_attachable_trx;
1739 }
is_read_only()1740 virtual bool is_read_only() const { return true; }
1741
1742 protected:
1743 /// THD instance.
1744 THD *m_thd;
1745
1746 enum_reset_lex m_reset_lex;
1747
1748 /**
1749 Attachable_trx which was active for the THD before when this
1750 transaction was started (NULL in most cases).
1751 */
1752 Attachable_trx *m_prev_attachable_trx;
1753
1754 /// Transaction state data.
1755 Transaction_state m_trx_state;
1756
1757 private:
1758 Attachable_trx(const Attachable_trx &);
1759 Attachable_trx &operator=(const Attachable_trx &);
1760 };
1761
1762 /**
1763 A derived from THD::Attachable_trx class allows updates in
1764 the attachable transaction. Callers of the class methods must
1765 make sure the attachable_rw won't cause deadlock with the main transaction.
1766 The destructor does not invoke ha_commit_{stmt,trans} nor ha_rollback_trans
1767 on purpose.
1768 Burden to terminate the read-write instance also lies on the caller!
1769 In order to use this interface it *MUST* prove that no side effect to
1770 the global transaction state can be inflicted by a chosen method.
1771
1772 This class is being used only by class Gtid_table_access_context by
1773 replication and by dd::info_schema::Table_statistics.
1774 */
1775
1776 class Attachable_trx_rw : public Attachable_trx {
1777 public:
is_read_only()1778 bool is_read_only() const { return false; }
1779 explicit Attachable_trx_rw(THD *thd);
1780
1781 private:
1782 Attachable_trx_rw(const Attachable_trx_rw &);
1783 Attachable_trx_rw &operator=(const Attachable_trx_rw &);
1784 };
1785
1786 Attachable_trx *m_attachable_trx;
1787
1788 public:
get_transaction()1789 Transaction_ctx *get_transaction() { return m_transaction.get(); }
1790
get_transaction()1791 const Transaction_ctx *get_transaction() const { return m_transaction.get(); }
1792
1793 /**
1794 Changes the Transaction_ctx instance within THD-object. The previous
1795 Transaction_ctx instance is destroyed.
1796
1797 @note this is a THD-internal operation which MUST NOT be used outside.
1798
1799 @param transaction_ctx new Transaction_ctx instance to be associated with
1800 the THD-object.
1801 */
1802 void set_transaction(Transaction_ctx *transaction_ctx);
1803
1804 Global_read_lock global_read_lock;
1805
1806 Vio *active_vio = {nullptr};
1807
1808 /* Active network vio for clone remote connection. */
1809 Vio *clone_vio = {nullptr};
1810
1811 /*
1812 This is to track items changed during execution of a prepared
1813 statement/stored procedure. It's created by
1814 register_item_tree_change() in memory root of THD, and freed in
1815 rollback_item_tree_changes(). For conventional execution it's always
1816 empty.
1817 */
1818 Item_change_list change_list;
1819
1820 /*
1821 A permanent memory area of the statement. For conventional
1822 execution, the parsed tree and execution runtime reside in the same
1823 memory root. In this case stmt_arena points to THD. In case of
1824 a prepared statement or a stored procedure statement, thd->mem_root
1825 conventionally points to runtime memory, and thd->stmt_arena
1826 points to the memory of the PS/SP, where the parsed tree of the
1827 statement resides. Whenever you need to perform a permanent
1828 transformation of a parsed tree, you should allocate new memory in
1829 stmt_arena, to allow correct re-execution of PS/SP.
1830 Note: in the parser, stmt_arena == thd, even for PS/SP.
1831 */
1832 Query_arena *stmt_arena;
1833
1834 /*
1835 map for tables that will be updated for a multi-table update query
1836 statement, for other query statements, this will be zero.
1837 */
1838 table_map table_map_for_update;
1839
1840 /* Tells if LAST_INSERT_ID(#) was called for the current statement */
1841 bool arg_of_last_insert_id_function;
1842 /*
1843 ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for
1844 insertion into an auto_increment column".
1845 */
1846 /*
1847 This is the first autogenerated insert id which was *successfully*
1848 inserted by the previous statement (exactly, if the previous statement
1849 didn't successfully insert an autogenerated insert id, then it's the one
1850 of the statement before, etc).
1851 It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#).
1852 It is returned by LAST_INSERT_ID().
1853 */
1854 ulonglong first_successful_insert_id_in_prev_stmt;
1855 /*
1856 Variant of the above, used for storing in statement-based binlog. The
1857 difference is that the one above can change as the execution of a stored
1858 function progresses, while the one below is set once and then does not
1859 change (which is the value which statement-based binlog needs).
1860 */
1861 ulonglong first_successful_insert_id_in_prev_stmt_for_binlog;
1862 /*
1863 This is the first autogenerated insert id which was *successfully*
1864 inserted by the current statement. It is maintained only to set
1865 first_successful_insert_id_in_prev_stmt when statement ends.
1866 */
1867 ulonglong first_successful_insert_id_in_cur_stmt;
1868 /*
1869 We follow this logic:
1870 - when stmt starts, first_successful_insert_id_in_prev_stmt contains the
1871 first insert id successfully inserted by the previous stmt.
1872 - as stmt makes progress, handler::insert_id_for_cur_row changes;
1873 every time get_auto_increment() is called,
1874 auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the
1875 reserved interval (if statement-based binlogging).
1876 - at first successful insertion of an autogenerated value,
1877 first_successful_insert_id_in_cur_stmt is set to
1878 handler::insert_id_for_cur_row.
1879 - when stmt goes to binlog,
1880 auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if
1881 non-empty.
1882 - when stmt ends, first_successful_insert_id_in_prev_stmt is set to
1883 first_successful_insert_id_in_cur_stmt.
1884 */
1885 /*
1886 stmt_depends_on_first_successful_insert_id_in_prev_stmt is set when
1887 LAST_INSERT_ID() is used by a statement.
1888 If it is set, first_successful_insert_id_in_prev_stmt_for_binlog will be
1889 stored in the statement-based binlog.
1890 This variable is CUMULATIVE along the execution of a stored function or
1891 trigger: if one substatement sets it to 1 it will stay 1 until the
1892 function/trigger ends, thus making sure that
1893 first_successful_insert_id_in_prev_stmt_for_binlog does not change anymore
1894 and is propagated to the caller for binlogging.
1895 */
1896 bool stmt_depends_on_first_successful_insert_id_in_prev_stmt;
1897 /*
1898 List of auto_increment intervals reserved by the thread so far, for
1899 storage in the statement-based binlog.
1900 Note that its minimum is not first_successful_insert_id_in_cur_stmt:
1901 assuming a table with an autoinc column, and this happens:
1902 INSERT INTO ... VALUES(3);
1903 SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL);
1904 then the latter INSERT will insert no rows
1905 (first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3"
1906 in the binlog is still needed; the list's minimum will contain 3.
1907 This variable is cumulative: if several statements are written to binlog
1908 as one (stored functions or triggers are used) this list is the
1909 concatenation of all intervals reserved by all statements.
1910 */
1911 Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog;
1912 /* Used by replication and SET INSERT_ID */
1913 Discrete_intervals_list auto_inc_intervals_forced;
1914 /*
1915 There is BUG#19630 where statement-based replication of stored
1916 functions/triggers with two auto_increment columns breaks.
1917 We however ensure that it works when there is 0 or 1 auto_increment
1918 column; our rules are
1919 a) on master, while executing a top statement involving substatements,
1920 first top- or sub- statement to generate auto_increment values wins the
1921 exclusive right to see its values be written to binlog (the write
1922 will be done by the statement or its caller), and the losers won't see
1923 their values be written to binlog.
1924 b) on slave, while replicating a top statement involving substatements,
1925 first top- or sub- statement to need to read auto_increment values from
1926 the master's binlog wins the exclusive right to read them (so the losers
1927 won't read their values from binlog but instead generate on their own).
1928 a) implies that we mustn't backup/restore
1929 auto_inc_intervals_in_cur_stmt_for_binlog.
1930 b) implies that we mustn't backup/restore auto_inc_intervals_forced.
1931
1932 If there are more than 1 auto_increment columns, then intervals for
1933 different columns may mix into the
1934 auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong,
1935 but there is no point in preventing this mixing by preventing intervals
1936 from the secondly inserted column to come into the list, as such
1937 prevention would be wrong too.
1938 What will happen in the case of
1939 INSERT INTO t1 (auto_inc) VALUES(NULL);
1940 where t1 has a trigger which inserts into an auto_inc column of t2, is
1941 that in binlog we'll store the interval of t1 and the interval of t2 (when
1942 we store intervals, soon), then in slave, t1 will use both intervals, t2
1943 will use none; if t1 inserts the same number of rows as on master,
1944 normally the 2nd interval will not be used by t1, which is fine. t2's
1945 values will be wrong if t2's internal auto_increment counter is different
1946 from what it was on master (which is likely). In 5.1, in mixed binlogging
1947 mode, row-based binlogging is used for such cases where two
1948 auto_increment columns are inserted.
1949 */
record_first_successful_insert_id_in_cur_stmt(ulonglong id_arg)1950 inline void record_first_successful_insert_id_in_cur_stmt(ulonglong id_arg) {
1951 if (first_successful_insert_id_in_cur_stmt == 0)
1952 first_successful_insert_id_in_cur_stmt = id_arg;
1953 }
read_first_successful_insert_id_in_prev_stmt(void)1954 inline ulonglong read_first_successful_insert_id_in_prev_stmt(void) {
1955 if (!stmt_depends_on_first_successful_insert_id_in_prev_stmt) {
1956 /* It's the first time we read it */
1957 first_successful_insert_id_in_prev_stmt_for_binlog =
1958 first_successful_insert_id_in_prev_stmt;
1959 stmt_depends_on_first_successful_insert_id_in_prev_stmt = true;
1960 }
1961 return first_successful_insert_id_in_prev_stmt;
1962 }
reset_first_successful_insert_id()1963 inline void reset_first_successful_insert_id() {
1964 arg_of_last_insert_id_function = false;
1965 first_successful_insert_id_in_prev_stmt = 0;
1966 first_successful_insert_id_in_cur_stmt = 0;
1967 first_successful_insert_id_in_prev_stmt_for_binlog = 0;
1968 stmt_depends_on_first_successful_insert_id_in_prev_stmt = false;
1969 }
1970
1971 /*
1972 Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#"
1973 (mysqlbinlog). We'll soon add a variant which can take many intervals in
1974 argument.
1975 */
force_one_auto_inc_interval(ulonglong next_id)1976 inline void force_one_auto_inc_interval(ulonglong next_id) {
1977 auto_inc_intervals_forced.empty(); // in case of multiple SET INSERT_ID
1978 auto_inc_intervals_forced.append(next_id, ULLONG_MAX, 0);
1979 }
1980
1981 /**
1982 Stores the result of the FOUND_ROWS() function. Set at query end, stable
1983 throughout the query.
1984 */
1985 ulonglong previous_found_rows;
1986 /**
1987 Dynamic, collected and set also in subqueries. Not stable throughout query.
1988 previous_found_rows is a snapshot of this take at query end making it
1989 stable throughout the next query, see update_previous_found_rows.
1990 */
1991 ulonglong current_found_rows;
1992
1993 /*
1994 Indicate if the gtid_executed table is being operated implicitly
1995 within current transaction. This happens because we are inserting
1996 a GTID specified through SET GTID_NEXT by user client or
1997 slave SQL thread/workers.
1998 */
1999 bool is_operating_gtid_table_implicitly;
2000 /*
2001 Indicate that a sub-statement is being operated implicitly
2002 within current transaction.
2003 As we don't want that this implicit sub-statement to consume the
2004 GTID of the actual transaction, we set it true at the beginning of
2005 the sub-statement and set it false again after "committing" the
2006 sub-statement.
2007 When it is true, the applier will not save the transaction owned
2008 gtid into mysql.gtid_executed table before transaction prepare, as
2009 it does when binlog is disabled, or binlog is enabled and
2010 log_slave_updates is disabled.
2011 Also the flag is made to defer updates to the slave info table from
2012 intermediate commits by non-atomic DDL.
2013 Rpl_info_table::do_flush_info(), rpl_rli.h::is_atomic_ddl_commit_on_slave()
2014 uses this flag.
2015 */
2016 bool is_operating_substatement_implicitly;
2017
2018 private:
2019 /**
2020 Stores the result of ROW_COUNT() function.
2021
2022 ROW_COUNT() function is a MySQL extention, but we try to keep it
2023 similar to ROW_COUNT member of the GET DIAGNOSTICS stack of the SQL
2024 standard (see SQL99, part 2, search for ROW_COUNT). It's value is
2025 implementation defined for anything except INSERT, DELETE, UPDATE.
2026
2027 ROW_COUNT is assigned according to the following rules:
2028
2029 - In my_ok():
2030 - for DML statements: to the number of affected rows;
2031 - for DDL statements: to 0.
2032
2033 - In my_eof(): to -1 to indicate that there was a result set.
2034
2035 We derive this semantics from the JDBC specification, where int
2036 java.sql.Statement.getUpdateCount() is defined to (sic) "return the
2037 current result as an update count; if the result is a ResultSet
2038 object or there are no more results, -1 is returned".
2039
2040 - In my_error(): to -1 to be compatible with the MySQL C API and
2041 MySQL ODBC driver.
2042
2043 - For SIGNAL statements: to 0 per WL#2110 specification (see also
2044 sql_signal.cc comment). Zero is used since that's the "default"
2045 value of ROW_COUNT in the Diagnostics Area.
2046 */
2047
2048 longlong m_row_count_func; /* For the ROW_COUNT() function */
2049
2050 public:
get_row_count_func()2051 inline longlong get_row_count_func() const { return m_row_count_func; }
2052
set_row_count_func(longlong row_count_func)2053 inline void set_row_count_func(longlong row_count_func) {
2054 m_row_count_func = row_count_func;
2055 }
2056
2057 ha_rows num_truncated_fields;
2058
2059 private:
2060 /**
2061 Number of rows we actually sent to the client, including "synthetic"
2062 rows in ROLLUP etc.
2063 */
2064 ha_rows m_sent_row_count;
2065
2066 /**
2067 Number of rows read and/or evaluated for a statement. Used for
2068 slow log reporting.
2069
2070 An examined row is defined as a row that is read and/or evaluated
2071 according to a statement condition, including in
2072 create_sort_index(). Rows may be counted more than once, e.g., a
2073 statement including ORDER BY could possibly evaluate the row in
2074 filesort() before reading it for e.g. update.
2075 */
2076 ha_rows m_examined_row_count;
2077
2078 private:
2079 USER_CONN *m_user_connect;
2080
2081 public:
2082 void set_user_connect(USER_CONN *uc);
get_user_connect()2083 const USER_CONN *get_user_connect() const { return m_user_connect; }
2084
2085 void increment_user_connections_counter();
2086 void decrement_user_connections_counter();
2087
2088 void increment_con_per_hour_counter();
2089
2090 void increment_updates_counter();
2091
2092 void increment_questions_counter();
2093
2094 void time_out_user_resource_limits();
2095
2096 public:
get_sent_row_count()2097 ha_rows get_sent_row_count() const { return m_sent_row_count; }
2098
get_examined_row_count()2099 ha_rows get_examined_row_count() const { return m_examined_row_count; }
2100
2101 void set_sent_row_count(ha_rows count);
2102
2103 void inc_sent_row_count(ha_rows count);
2104 void inc_examined_row_count(ha_rows count);
2105
2106 void inc_status_created_tmp_disk_tables();
2107 void inc_status_created_tmp_tables();
2108 void inc_status_select_full_join();
2109 void inc_status_select_full_range_join();
2110 void inc_status_select_range();
2111 void inc_status_select_range_check();
2112 void inc_status_select_scan();
2113 void inc_status_sort_merge_passes();
2114 void inc_status_sort_range();
2115 void inc_status_sort_rows(ha_rows count);
2116 void inc_status_sort_scan();
2117 void set_status_no_index_used();
2118 void set_status_no_good_index_used();
2119
2120 const CHARSET_INFO *db_charset;
2121 #if defined(ENABLED_PROFILING)
2122 std::unique_ptr<PROFILING> profiling;
2123 #endif
2124
2125 /** Current stage progress instrumentation. */
2126 PSI_stage_progress *m_stage_progress_psi;
2127 /** Current statement digest. */
2128 sql_digest_state *m_digest;
2129 /** Current statement digest token array. */
2130 unsigned char *m_token_array;
2131 /** Top level statement digest. */
2132 sql_digest_state m_digest_state;
2133
2134 /** Current statement instrumentation. */
2135 PSI_statement_locker *m_statement_psi;
2136 #ifdef HAVE_PSI_STATEMENT_INTERFACE
2137 /** Current statement instrumentation state. */
2138 PSI_statement_locker_state m_statement_state;
2139 #endif /* HAVE_PSI_STATEMENT_INTERFACE */
2140
2141 /** Current transaction instrumentation. */
2142 PSI_transaction_locker *m_transaction_psi;
2143 #ifdef HAVE_PSI_TRANSACTION_INTERFACE
2144 /** Current transaction instrumentation state. */
2145 PSI_transaction_locker_state m_transaction_state;
2146 #endif /* HAVE_PSI_TRANSACTION_INTERFACE */
2147
2148 /** Idle instrumentation. */
2149 PSI_idle_locker *m_idle_psi;
2150 #ifdef HAVE_PSI_IDLE_INTERFACE
2151 /** Idle instrumentation state. */
2152 PSI_idle_locker_state m_idle_state;
2153 #endif /* HAVE_PSI_IDLE_INTERFACE */
2154 /** True if the server code is IDLE for this connection. */
2155 bool m_server_idle;
2156
2157 /*
2158 Id of current query. Statement can be reused to execute several queries
2159 query_id is global in context of the whole MySQL server.
2160 ID is automatically generated from mutex-protected counter.
2161 It's used in handler code for various purposes: to check which columns
2162 from table are necessary for this select, to check if it's necessary to
2163 update auto-updatable fields (like auto_increment and timestamp).
2164 */
2165 query_id_t query_id;
2166 ulong col_access;
2167
2168 /* Statement id is thread-wide. This counter is used to generate ids */
2169 ulong statement_id_counter;
2170 ulong rand_saved_seed1, rand_saved_seed2;
2171 my_thread_t real_id; /* For debugging */
2172 /**
2173 This counter is 32 bit because of the client protocol.
2174
2175 @note It is not meant to be used for my_thread_self(), see @c real_id for
2176 this.
2177
2178 @note Set to reserved_thread_id on initialization. This is a magic
2179 value that is only to be used for temporary THDs not present in
2180 the global THD list.
2181 */
2182 private:
2183 my_thread_id m_thread_id;
2184
2185 public:
2186 /**
2187 Assign a value to m_thread_id by calling
2188 Global_THD_manager::get_new_thread_id().
2189 */
2190 void set_new_thread_id();
thread_id()2191 my_thread_id thread_id() const { return m_thread_id; }
2192 uint tmp_table;
2193 uint server_status, open_options;
2194 enum enum_thread_type system_thread;
2195
2196 // Check if this THD belongs to a system thread.
is_system_thread()2197 bool is_system_thread() const { return system_thread != NON_SYSTEM_THREAD; }
2198
2199 // Check if this THD belongs to a dd bootstrap system thread.
is_dd_system_thread()2200 bool is_dd_system_thread() const {
2201 return system_thread == SYSTEM_THREAD_DD_INITIALIZE ||
2202 system_thread == SYSTEM_THREAD_DD_RESTART;
2203 }
2204
2205 // Check if this THD belongs to the initialize system thread. The
2206 // initialize thread executes statements that are compiled into the
2207 // server.
is_initialize_system_thread()2208 bool is_initialize_system_thread() const {
2209 return system_thread == SYSTEM_THREAD_SERVER_INITIALIZE;
2210 }
2211
2212 // Check if this THD is executing statements passed through a init file.
is_init_file_system_thread()2213 bool is_init_file_system_thread() const {
2214 return system_thread == SYSTEM_THREAD_INIT_FILE;
2215 }
2216
2217 // Check if this THD belongs to a bootstrap system thread. Note that
2218 // this thread type may execute statements submitted by the user.
is_bootstrap_system_thread()2219 bool is_bootstrap_system_thread() const {
2220 return is_dd_system_thread() || is_initialize_system_thread() ||
2221 is_init_file_system_thread();
2222 }
2223
2224 // Check if this THD belongs to a server upgrade thread. Server upgrade
2225 // threads execute statements that are compiled into the server.
is_server_upgrade_thread()2226 bool is_server_upgrade_thread() const {
2227 return system_thread == SYSTEM_THREAD_SERVER_UPGRADE;
2228 }
2229
2230 /*
2231 Current or next transaction isolation level.
2232 When a connection is established, the value is taken from
2233 @@session.tx_isolation (default transaction isolation for
2234 the session), which is in turn taken from @@global.tx_isolation
2235 (the global value).
2236 If there is no transaction started, this variable
2237 holds the value of the next transaction's isolation level.
2238 When a transaction starts, the value stored in this variable
2239 becomes "actual".
2240 At transaction commit or rollback, we assign this variable
2241 again from @@session.tx_isolation.
2242 The only statement that can otherwise change the value
2243 of this variable is SET TRANSACTION ISOLATION LEVEL.
2244 Its purpose is to effect the isolation level of the next
2245 transaction in this session. When this statement is executed,
2246 the value in this variable is changed. However, since
2247 this statement is only allowed when there is no active
2248 transaction, this assignment (naturally) only affects the
2249 upcoming transaction.
2250 At the end of the current active transaction the value is
2251 be reset again from @@session.tx_isolation, as described
2252 above.
2253 */
2254 enum_tx_isolation tx_isolation;
2255 /*
2256 Current or next transaction access mode.
2257 See comment above regarding tx_isolation.
2258 */
2259 bool tx_read_only;
2260 /*
2261 Transaction cannot be rolled back must be given priority.
2262 When two transactions conflict inside InnoDB, the one with
2263 greater priority wins.
2264 */
2265 int tx_priority;
2266 /*
2267 All transactions executed by this thread will have high
2268 priority mode, independent of tx_priority value.
2269 */
2270 int thd_tx_priority;
2271
2272 enum_check_fields check_for_truncated_fields;
2273
2274 // For user variables replication
2275 Prealloced_array<Binlog_user_var_event *, 2> user_var_events;
2276 MEM_ROOT *user_var_events_alloc; /* Allocate above array elements here */
2277
2278 /**
2279 Used by MYSQL_BIN_LOG to maintain the commit queue for binary log
2280 group commit.
2281 */
2282 THD *next_to_commit;
2283
2284 /**
2285 The member is served for marking a query that CREATEs or ALTERs
2286 a table declared with a TIMESTAMP column as dependent on
2287 @@session.explicit_defaults_for_timestamp.
2288 Is set to true by parser, unset at the end of the query.
2289 Possible marking in checked by binary logger.
2290 */
2291 bool binlog_need_explicit_defaults_ts;
2292
2293 /**
2294 Functions to set and get transaction position.
2295
2296 These functions are used to set the transaction position for the
2297 transaction written when committing this transaction.
2298 */
2299 /**@{*/
set_trans_pos(const char * file,my_off_t pos)2300 void set_trans_pos(const char *file, my_off_t pos) {
2301 DBUG_TRACE;
2302 DBUG_ASSERT(((file == nullptr) && (pos == 0)) ||
2303 ((file != nullptr) && (pos != 0)));
2304 if (file) {
2305 DBUG_PRINT("enter", ("file: %s, pos: %llu", file, pos));
2306 // Only the file name should be used, not the full path
2307 m_trans_log_file = file + dirname_length(file);
2308 if (!m_trans_fixed_log_file)
2309 m_trans_fixed_log_file = (char *)main_mem_root.Alloc(FN_REFLEN + 1);
2310 DBUG_ASSERT(strlen(m_trans_log_file) <= FN_REFLEN);
2311 strcpy(m_trans_fixed_log_file, m_trans_log_file);
2312 } else {
2313 m_trans_log_file = nullptr;
2314 m_trans_fixed_log_file = nullptr;
2315 }
2316
2317 m_trans_end_pos = pos;
2318 DBUG_PRINT("return",
2319 ("m_trans_log_file: %s, m_trans_fixed_log_file: %s, "
2320 "m_trans_end_pos: %llu",
2321 m_trans_log_file, m_trans_fixed_log_file, m_trans_end_pos));
2322 return;
2323 }
2324
get_trans_pos(const char ** file_var,my_off_t * pos_var)2325 void get_trans_pos(const char **file_var, my_off_t *pos_var) const {
2326 DBUG_TRACE;
2327 if (file_var) *file_var = m_trans_log_file;
2328 if (pos_var) *pos_var = m_trans_end_pos;
2329 DBUG_PRINT("return",
2330 ("file: %s, pos: %llu", file_var ? *file_var : "<none>",
2331 pos_var ? *pos_var : 0));
2332 return;
2333 }
2334
get_trans_fixed_pos(const char ** file_var,my_off_t * pos_var)2335 void get_trans_fixed_pos(const char **file_var, my_off_t *pos_var) const {
2336 DBUG_TRACE;
2337 if (file_var) *file_var = m_trans_fixed_log_file;
2338 if (pos_var) *pos_var = m_trans_end_pos;
2339 DBUG_PRINT("return",
2340 ("file: %s, pos: %llu", file_var ? *file_var : "<none>",
2341 pos_var ? *pos_var : 0));
2342 return;
2343 }
2344
2345 /**@}*/
2346
2347 /*
2348 Error code from committing or rolling back the transaction.
2349 */
2350 enum Commit_error {
2351 CE_NONE = 0,
2352 CE_FLUSH_ERROR,
2353 CE_SYNC_ERROR,
2354 CE_COMMIT_ERROR,
2355 CE_ERROR_COUNT
2356 } commit_error;
2357
2358 /*
2359 Define durability properties that engines may check to
2360 improve performance.
2361 */
2362 enum durability_properties durability_property;
2363
2364 /*
2365 If checking this in conjunction with a wait condition, please
2366 include a check after enter_cond() if you want to avoid a race
2367 condition. For details see the implementation of awake(),
2368 especially the "broadcast" part.
2369 */
2370 enum killed_state {
2371 NOT_KILLED = 0,
2372 KILL_CONNECTION = ER_SERVER_SHUTDOWN,
2373 KILL_QUERY = ER_QUERY_INTERRUPTED,
2374 KILL_TIMEOUT = ER_QUERY_TIMEOUT,
2375 KILLED_NO_VALUE /* means neither of the states */
2376 };
2377 std::atomic<killed_state> killed;
2378
2379 /**
2380 Whether we are currently in the execution phase of an EXPLAIN ANALYZE query.
2381 If so, send_kill_message() won't actually set an error; we will add a
2382 warning near the end of the execution instead.
2383 */
2384 bool running_explain_analyze = false;
2385
2386 /**
2387 When operation on DD tables is in progress then THD is set to kill immune
2388 mode.
2389 This member holds DD_kill_immunizer object created to make DD operations
2390 immune from the kill operations. Member also indicated whether THD is in
2391 kill immune mode or not.
2392 */
2393 dd::DD_kill_immunizer *kill_immunizer;
2394
2395 /* scramble - random string sent to client on handshake */
2396 char scramble[SCRAMBLE_LENGTH + 1];
2397
2398 /// @todo: slave_thread is completely redundant, we should use 'system_thread'
2399 /// instead /sven
2400 bool slave_thread;
2401
2402 uchar password;
2403
2404 private:
2405 /**
2406 Set to true if execution of the current compound statement
2407 can not continue. In particular, disables activation of
2408 CONTINUE or EXIT handlers of stored routines.
2409 Reset in the end of processing of the current user request, in
2410 @see mysql_reset_thd_for_next_command().
2411 */
2412 bool m_is_fatal_error;
2413
2414 public:
2415 /**
2416 Set by a storage engine to request the entire
2417 transaction (that possibly spans multiple engines) to
2418 rollback. Reset in ha_rollback.
2419 */
2420 bool transaction_rollback_request;
2421 /**
2422 true if we are in a sub-statement and the current error can
2423 not be safely recovered until we left the sub-statement mode.
2424 In particular, disables activation of CONTINUE and EXIT
2425 handlers inside sub-statements. E.g. if it is a deadlock
2426 error and requires a transaction-wide rollback, this flag is
2427 raised (traditionally, MySQL first has to close all the reads
2428 via @see handler::ha_index_or_rnd_end() and only then perform
2429 the rollback).
2430 Reset to false when we leave the sub-statement mode.
2431 */
2432 bool is_fatal_sub_stmt_error;
2433 bool query_start_usec_used;
2434 bool rand_used, time_zone_used;
2435 bool in_lock_tables;
2436 /**
2437 True if a slave error. Causes the slave to stop. Not the same
2438 as the statement execution error (is_error()), since
2439 a statement may be expected to return an error, e.g. because
2440 it returned an error on master, and this is OK on the slave.
2441 */
2442 bool is_slave_error;
2443
2444 /** is set if some thread specific value(s) used in a statement. */
2445 bool thread_specific_used;
2446 /**
2447 is set if a statement accesses a temporary table created through
2448 CREATE TEMPORARY TABLE.
2449 */
2450 bool charset_is_system_charset, charset_is_collation_connection;
2451 bool charset_is_character_set_filesystem;
2452 bool enable_slow_log; /* enable slow log for current statement */
2453 /* set during loop of derived table processing */
2454 bool derived_tables_processing;
2455 // Set while parsing INFORMATION_SCHEMA system views.
2456 bool parsing_system_view;
2457
2458 /** Current SP-runtime context. */
2459 sp_rcontext *sp_runtime_ctx;
2460 sp_cache *sp_proc_cache;
2461 sp_cache *sp_func_cache;
2462
2463 /** number of name_const() substitutions, see sp_head.cc:subst_spvars() */
2464 uint query_name_consts;
2465
2466 /*
2467 If we do a purge of binary logs, log index info of the threads
2468 that are currently reading it needs to be adjusted. To do that
2469 each thread that is using LOG_INFO needs to adjust the pointer to it
2470 */
2471 LOG_INFO *current_linfo;
2472 /* Used by the sys_var class to store temporary values */
2473 union {
2474 bool bool_value;
2475 long long_value;
2476 ulong ulong_value;
2477 ulonglong ulonglong_value;
2478 double double_value;
2479 } sys_var_tmp;
2480
2481 struct {
2482 /*
2483 If true, mysql_bin_log::write(Log_event) call will not write events to
2484 binlog, and maintain 2 below variables instead (use
2485 mysql_bin_log.start_union_events to turn this on)
2486 */
2487 bool do_union;
2488 /*
2489 If true, at least one mysql_bin_log::write(Log_event) call has been
2490 made after last mysql_bin_log.start_union_events() call.
2491 */
2492 bool unioned_events;
2493 /*
2494 If true, at least one mysql_bin_log::write(Log_event e), where
2495 e.cache_stmt == true call has been made after last
2496 mysql_bin_log.start_union_events() call.
2497 */
2498 bool unioned_events_trans;
2499
2500 /*
2501 'queries' (actually SP statements) that run under inside this binlog
2502 union have thd->query_id >= first_query_id.
2503 */
2504 query_id_t first_query_id;
2505 } binlog_evt_union;
2506
2507 /**
2508 Internal parser state.
2509 Note that since the parser is not re-entrant, we keep only one parser
2510 state here. This member is valid only when executing code during parsing.
2511 */
2512 Parser_state *m_parser_state;
2513
2514 Locked_tables_list locked_tables_list;
2515
2516 partition_info *work_part_info;
2517
2518 /**
2519 Array of active audit plugins which have been used by this THD.
2520 This list is later iterated to invoke release_thd() on those
2521 plugins.
2522 */
2523 Plugin_array audit_class_plugins;
2524 /**
2525 Array of bits indicating which audit classes have already been
2526 added to the list of audit plugins which are currently in use.
2527 */
2528 Prealloced_array<unsigned long, 11> audit_class_mask;
2529
2530 #if defined(ENABLED_DEBUG_SYNC)
2531 /* Debug Sync facility. See debug_sync.cc. */
2532 struct st_debug_sync_control *debug_sync_control;
2533 #endif /* defined(ENABLED_DEBUG_SYNC) */
2534
2535 // We don't want to load/unload plugins for unit tests.
2536 bool m_enable_plugins;
2537
2538 /**
2539 Used by some transformations that need Item:transform to make a permanent
2540 transform. Will be voided by WL#6570.
2541 */
2542 bool m_permanent_transform{false};
2543
2544 /**
2545 RAII class to push m_permanent_transform in a scope
2546 */
2547 class Permanent_transform {
2548 private:
2549 bool m_old_value;
2550 THD *m_thd;
2551
2552 public:
Permanent_transform(THD * thd)2553 Permanent_transform(THD *thd) {
2554 m_thd = thd;
2555 m_old_value = thd->m_permanent_transform;
2556 thd->m_permanent_transform = true;
2557 }
~Permanent_transform()2558 ~Permanent_transform() { m_thd->m_permanent_transform = m_old_value; }
2559 };
2560
2561 /*
2562 Audit API events are generated, when this flag is true. The flag
2563 is initially true, but it can be set false in some cases, e.g.
2564 Session Service's THDs are created with auditing disabled. Auditing
2565 is enabled on MYSQL_AUDIT_CONNECTION_CONNECT event.
2566 */
2567 bool m_audited;
2568
2569 THD(bool enable_plugins = true);
2570
2571 /*
2572 The THD dtor is effectively split in two:
2573 THD::release_resources() and ~THD().
2574
2575 We want to minimize the time we hold LOCK_thd_list,
2576 so when destroying a global thread, do:
2577
2578 thd->release_resources()
2579 Global_THD_manager::get_instance()->remove_thd();
2580 delete thd;
2581 */
2582 ~THD();
2583
2584 void release_resources();
release_resources_done()2585 bool release_resources_done() const { return m_release_resources_done; }
2586
2587 private:
2588 bool m_release_resources_done;
2589 bool cleanup_done;
2590 void cleanup(void);
2591
2592 void init(void);
2593
2594 public:
2595 /**
2596 Initialize memory roots necessary for query processing and (!)
2597 pre-allocate memory for it. We can't do that in THD constructor because
2598 there are use cases (acl_init, watcher threads,
2599 killing mysqld) where it's vital to not allocate excessive and not used
2600 memory. Note, that we still don't return error from init_query_mem_roots()
2601 if preallocation fails, we should notice that at the first call to
2602 alloc_root.
2603 */
2604 void init_query_mem_roots();
2605 void cleanup_connection(void);
2606 void cleanup_after_query();
2607 void store_globals();
2608 void restore_globals();
2609
set_active_vio(Vio * vio)2610 inline void set_active_vio(Vio *vio) {
2611 mysql_mutex_lock(&LOCK_thd_data);
2612 active_vio = vio;
2613 mysql_mutex_unlock(&LOCK_thd_data);
2614 }
2615
set_ssl(Vio * vio)2616 inline void set_ssl(Vio *vio) {
2617 mysql_mutex_lock(&LOCK_thd_data);
2618 m_SSL = (SSL *)vio->ssl_arg;
2619 mysql_mutex_unlock(&LOCK_thd_data);
2620 }
2621
clear_active_vio()2622 inline void clear_active_vio() {
2623 mysql_mutex_lock(&LOCK_thd_data);
2624 active_vio = nullptr;
2625 m_SSL = nullptr;
2626 mysql_mutex_unlock(&LOCK_thd_data);
2627 }
2628
2629 /** Set active clone network Vio for remote clone.
2630 @param[in] vio network vio */
set_clone_vio(Vio * vio)2631 inline void set_clone_vio(Vio *vio) {
2632 mysql_mutex_lock(&LOCK_thd_data);
2633 clone_vio = vio;
2634 mysql_mutex_unlock(&LOCK_thd_data);
2635 }
2636
2637 /** Clear clone network Vio for remote clone. */
clear_clone_vio()2638 inline void clear_clone_vio() {
2639 mysql_mutex_lock(&LOCK_thd_data);
2640 clone_vio = nullptr;
2641 mysql_mutex_unlock(&LOCK_thd_data);
2642 }
2643
2644 /** Check if clone network Vio is active. */
check_clone_vio()2645 inline bool check_clone_vio() {
2646 mysql_mutex_lock(&LOCK_thd_data);
2647 bool is_active = (clone_vio != nullptr);
2648 mysql_mutex_unlock(&LOCK_thd_data);
2649 return (is_active);
2650 }
2651
2652 /** Shutdown clone vio, if active. */
2653 void shutdown_clone_vio();
2654
2655 enum_vio_type get_vio_type() const;
2656
2657 void shutdown_active_vio();
2658 void awake(THD::killed_state state_to_set);
2659
2660 /** Disconnect the associated communication endpoint. */
2661 void disconnect(bool server_shutdown = false);
2662
2663 enum enum_binlog_query_type {
2664 /* The query can be logged in row format or in statement format. */
2665 ROW_QUERY_TYPE,
2666
2667 /* The query has to be logged in statement format. */
2668 STMT_QUERY_TYPE,
2669
2670 QUERY_TYPE_COUNT
2671 };
2672
2673 int binlog_query(enum_binlog_query_type qtype, const char *query,
2674 size_t query_len, bool is_trans, bool direct,
2675 bool suppress_use, int errcode);
2676
2677 // Begin implementation of MDL_context_owner interface.
2678
enter_cond(mysql_cond_t * cond,mysql_mutex_t * mutex,const PSI_stage_info * stage,PSI_stage_info * old_stage,const char * src_function,const char * src_file,int src_line)2679 void enter_cond(mysql_cond_t *cond, mysql_mutex_t *mutex,
2680 const PSI_stage_info *stage, PSI_stage_info *old_stage,
2681 const char *src_function, const char *src_file,
2682 int src_line) {
2683 DBUG_TRACE;
2684 mysql_mutex_assert_owner(mutex);
2685 /*
2686 Sic: We don't lock LOCK_current_cond here.
2687 If we did, we could end up in deadlock with THD::awake()
2688 which locks current_mutex while LOCK_current_cond is locked.
2689 */
2690 current_mutex = mutex;
2691 current_cond = cond;
2692 enter_stage(stage, old_stage, src_function, src_file, src_line);
2693 return;
2694 }
2695
exit_cond(const PSI_stage_info * stage,const char * src_function,const char * src_file,int src_line)2696 void exit_cond(const PSI_stage_info *stage, const char *src_function,
2697 const char *src_file, int src_line) {
2698 DBUG_TRACE;
2699 /*
2700 current_mutex must be unlocked _before_ LOCK_current_cond is
2701 locked (if that would not be the case, you'll get a deadlock if someone
2702 does a THD::awake() on you).
2703 */
2704 mysql_mutex_assert_not_owner(current_mutex.load());
2705 mysql_mutex_lock(&LOCK_current_cond);
2706 current_mutex = nullptr;
2707 current_cond = nullptr;
2708 mysql_mutex_unlock(&LOCK_current_cond);
2709 enter_stage(stage, nullptr, src_function, src_file, src_line);
2710 return;
2711 }
2712
is_killed()2713 virtual int is_killed() const final { return killed; }
get_thd()2714 virtual THD *get_thd() { return this; }
2715
2716 /**
2717 A callback to the server internals that is used to address
2718 special cases of the locking protocol.
2719 Invoked when acquiring an exclusive lock, for each thread that
2720 has a conflicting shared metadata lock.
2721
2722 This function aborts waiting of the thread on a data lock, to make
2723 it notice the pending exclusive lock and back off.
2724
2725 @note This function does not wait for the thread to give away its
2726 locks. Waiting is done outside for all threads at once.
2727
2728 @param ctx_in_use The MDL context owner (thread) to wake up.
2729 @param needs_thr_lock_abort Indicates that to wake up thread
2730 this call needs to abort its waiting
2731 on table-level lock.
2732 */
2733 virtual void notify_shared_lock(MDL_context_owner *ctx_in_use,
2734 bool needs_thr_lock_abort);
2735
2736 virtual bool notify_hton_pre_acquire_exclusive(const MDL_key *mdl_key,
2737 bool *victimized);
2738
2739 virtual void notify_hton_post_release_exclusive(const MDL_key *mdl_key);
2740
2741 /**
2742 Provide thread specific random seed for MDL_context's PRNG.
2743
2744 Note that even if two connections will request seed during handling of
2745 statements which were started at exactly the same time, and thus will
2746 get the same values in PRNG at the start, they will naturally diverge
2747 soon, since calls to PRNG in MDL subsystem are affected by many factors
2748 making process quite random. OTOH the fact that we use time as a seed
2749 gives more randomness and thus better coverage in tests as opposed to
2750 using thread_id for the same purpose.
2751 */
get_rand_seed()2752 virtual uint get_rand_seed() const { return (uint)start_utime; }
2753
2754 // End implementation of MDL_context_owner interface.
2755
is_strict_mode()2756 inline bool is_strict_mode() const {
2757 return (variables.sql_mode &
2758 (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES));
2759 }
collation()2760 inline const CHARSET_INFO *collation() {
2761 return variables.collation_server ? variables.collation_server
2762 : default_charset_info;
2763 }
time_zone()2764 inline Time_zone *time_zone() {
2765 time_zone_used = true;
2766 return variables.time_zone;
2767 }
query_start_in_secs()2768 time_t query_start_in_secs() const { return start_time.tv_sec; }
2769 timeval query_start_timeval_trunc(uint decimals);
2770 void set_time();
set_time(const struct timeval * t)2771 void set_time(const struct timeval *t) {
2772 user_time = *t;
2773 set_time();
2774 }
2775 void set_time_after_lock();
is_fsp_truncate_mode()2776 inline bool is_fsp_truncate_mode() const {
2777 return (variables.sql_mode & MODE_TIME_TRUNCATE_FRACTIONAL);
2778 }
2779
2780 /**
2781 Evaluate the current time, and if it exceeds the long-query-time
2782 setting, mark the query as slow.
2783 */
2784 void update_slow_query_status();
2785
found_rows()2786 ulonglong found_rows() const { return previous_found_rows; }
2787
2788 /*
2789 Call when it is clear that the query is ended and we have collected the
2790 right value for current_found_rows. Calling this method makes a snapshot of
2791 that value and makes it ready and stable for subsequent FOUND_ROWS() call
2792 in the next statement.
2793 */
update_previous_found_rows()2794 inline void update_previous_found_rows() {
2795 previous_found_rows = current_found_rows;
2796 }
2797
2798 /**
2799 Returns true if session is in a multi-statement transaction mode.
2800
2801 OPTION_NOT_AUTOCOMMIT: When autocommit is off, a multi-statement
2802 transaction is implicitly started on the first statement after a
2803 previous transaction has been ended.
2804
2805 OPTION_BEGIN: Regardless of the autocommit status, a multi-statement
2806 transaction can be explicitly started with the statements "START
2807 TRANSACTION", "BEGIN [WORK]", "[COMMIT | ROLLBACK] AND CHAIN", etc.
2808
2809 Note: this doesn't tell you whether a transaction is active.
2810 A session can be in multi-statement transaction mode, and yet
2811 have no active transaction, e.g., in case of:
2812 set \@\@autocommit=0;
2813 set \@a= 3; <-- these statements don't
2814 set transaction isolation level serializable; <-- start an active
2815 flush tables; <-- transaction
2816
2817 I.e. for the above scenario this function returns true, even
2818 though no active transaction has begun.
2819 @sa in_active_multi_stmt_transaction()
2820 */
in_multi_stmt_transaction_mode()2821 inline bool in_multi_stmt_transaction_mode() const {
2822 return variables.option_bits & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN);
2823 }
2824 /**
2825 true if the session is in a multi-statement transaction mode
2826 (@sa in_multi_stmt_transaction_mode()) *and* there is an
2827 active transaction, i.e. there is an explicit start of a
2828 transaction with BEGIN statement, or implicit with a
2829 statement that uses a transactional engine.
2830
2831 For example, these scenarios don't start an active transaction
2832 (even though the server is in multi-statement transaction mode):
2833
2834 @verbatim
2835 set @@autocommit=0;
2836 select * from nontrans_table;
2837 set @var = true;
2838 flush tables;
2839 @endverbatim
2840
2841 Note, that even for a statement that starts a multi-statement
2842 transaction (i.e. select * from trans_table), this
2843 flag won't be set until we open the statement's tables
2844 and the engines register themselves for the transaction
2845 (see trans_register_ha()),
2846 hence this method is reliable to use only after
2847 open_tables() has completed.
2848
2849 Why do we need a flag?
2850 ----------------------
2851 We need to maintain a (at first glance redundant)
2852 session flag, rather than looking at thd->transaction.all.ha_list
2853 because of explicit start of a transaction with BEGIN.
2854
2855 I.e. in case of
2856 BEGIN;
2857 select * from nontrans_t1; <-- in_active_multi_stmt_transaction() is true
2858 */
in_active_multi_stmt_transaction()2859 inline bool in_active_multi_stmt_transaction() const {
2860 return server_status & SERVER_STATUS_IN_TRANS;
2861 }
fill_information_schema_tables()2862 bool fill_information_schema_tables() const {
2863 return !stmt_arena->is_stmt_prepare();
2864 }
2865
2866 bool convert_string(LEX_STRING *to, const CHARSET_INFO *to_cs,
2867 const char *from, size_t from_length,
2868 const CHARSET_INFO *from_cs, bool report_error = false);
2869
2870 int send_explain_fields(Query_result *result);
2871
2872 /**
2873 Clear the current error, if any.
2874 We do not clear is_fatal_error or is_fatal_sub_stmt_error since we
2875 assume this is never called if the fatal error is set.
2876 @todo: To silence an error, one should use Internal_error_handler
2877 mechanism. In future this function will be removed.
2878 */
clear_error()2879 inline void clear_error() {
2880 DBUG_TRACE;
2881 if (get_stmt_da()->is_error()) get_stmt_da()->reset_diagnostics_area();
2882 is_slave_error = false;
2883 return;
2884 }
2885
2886 bool is_classic_protocol() const;
2887
2888 /** Return false if connection to client is broken. */
2889 bool is_connected() final;
2890
2891 /**
2892 Mark the current error as fatal. Warning: this does not
2893 set any error, it sets a property of the error, so must be
2894 followed or prefixed with my_error().
2895 */
fatal_error()2896 void fatal_error() { m_is_fatal_error = true; }
is_fatal_error()2897 bool is_fatal_error() const { return m_is_fatal_error; }
2898 /**
2899 true if there is an error in the error stack.
2900
2901 Please use this method instead of direct access to
2902 net.report_error.
2903
2904 If true, the current (sub)-statement should be aborted.
2905 The main difference between this member and is_fatal_error
2906 is that a fatal error can not be handled by a stored
2907 procedure continue handler, whereas a normal error can.
2908
2909 To raise this flag, use my_error().
2910 */
is_error()2911 inline bool is_error() const { return get_stmt_da()->is_error(); }
2912
2913 /// Returns first Diagnostics Area for the current statement.
get_stmt_da()2914 Diagnostics_area *get_stmt_da() { return m_stmt_da; }
2915
2916 /// Returns first Diagnostics Area for the current statement.
get_stmt_da()2917 const Diagnostics_area *get_stmt_da() const { return m_stmt_da; }
2918
2919 /// Returns the second Diagnostics Area for the current statement.
get_stacked_da()2920 const Diagnostics_area *get_stacked_da() const {
2921 return get_stmt_da()->stacked_da();
2922 }
2923
2924 /**
2925 Returns thread-local Diagnostics Area for parsing.
2926 We need to have a clean DA in case errors or warnings are thrown
2927 during parsing, but we can't just reset the main DA in case we
2928 have a diagnostic statement on our hand that needs the old DA
2929 to answer questions about the previous execution.
2930 Keeping a static per-thread DA for parsing is less costly than
2931 allocating a temporary one for each statement we parse.
2932 */
get_parser_da()2933 Diagnostics_area *get_parser_da() { return &m_parser_da; }
2934
2935 /**
2936 Returns thread-local Diagnostics Area to be used by query rewrite plugins.
2937 Query rewrite plugins use their own diagnostics area. The reason is that
2938 they are invoked right before and right after parsing, and we don't want
2939 conditions raised by plugins in either statement nor parser DA until we
2940 know which type of statement we have parsed.
2941
2942 @note The diagnostics area is instantiated the first time it is asked for.
2943 */
get_query_rewrite_plugin_da()2944 Diagnostics_area *get_query_rewrite_plugin_da() {
2945 return m_query_rewrite_plugin_da_ptr;
2946 }
2947
2948 /**
2949 Push the given Diagnostics Area on top of the stack, making
2950 it the new first Diagnostics Area. Conditions in the new second
2951 Diagnostics Area will be copied to the new first Diagnostics Area.
2952
2953 @param da Diagnostics Area to be come the top of
2954 the Diagnostics Area stack.
2955 @param copy_conditions
2956 Copy the conditions from the new second Diagnostics Area
2957 to the new first Diagnostics Area, as per SQL standard.
2958 */
2959 void push_diagnostics_area(Diagnostics_area *da,
2960 bool copy_conditions = true) {
2961 get_stmt_da()->push_diagnostics_area(this, da, copy_conditions);
2962 m_stmt_da = da;
2963 }
2964
2965 /// Pop the top DA off the Diagnostics Area stack.
pop_diagnostics_area()2966 void pop_diagnostics_area() {
2967 m_stmt_da = get_stmt_da()->pop_diagnostics_area();
2968 }
2969
2970 /**
2971 Inserts the new protocol at the top of the protocol stack, and make it
2972 the current protocol for this thd.
2973
2974 @param protocol Protocol to be inserted.
2975 */
2976 void push_protocol(Protocol *protocol);
2977
2978 template <typename ProtocolClass>
push_protocol(const std::unique_ptr<ProtocolClass> & protocol)2979 void push_protocol(const std::unique_ptr<ProtocolClass> &protocol) {
2980 push_protocol(protocol.get());
2981 }
2982
2983 /**
2984 Pops the top protocol of the Protocol stack and sets the previous one
2985 as the current protocol.
2986 */
2987 void pop_protocol();
2988
2989 public:
charset()2990 const CHARSET_INFO *charset() const { return variables.character_set_client; }
2991 void update_charset();
2992
2993 /**
2994 Update the place with new_value.
2995 If THD::m_permanent_transform is false:
2996 - Use a plain assignment (iff THD::stmt_area->is_regular())
2997 or assign and register place for rollback.
2998 If THD::m_permanent_transform is true:
2999 - we a) remove any rollback requests for this location and b) do the
3000 assignment without registering any rollback request.
3001
3002 @param place The location at which we want set a new value
3003 @param new_value The new value
3004 */
3005 void change_item_tree(Item **place, Item *new_value);
3006
3007 /**
3008 Remember that place was updated with new_value so it can be restored
3009 by rollback_item_tree_changes().
3010
3011 @param[in] place the location that will change, and whose old value
3012 we need to remember for restoration
3013 @param[in] new_value new value about to be inserted into *place, remember
3014 for associative lookup, see replace_rollback_place()
3015 */
3016 void nocheck_register_item_tree_change(Item **place, Item *new_value);
3017
3018 /**
3019 Find and update change record of an underlying item based on the new
3020 value for a place.
3021
3022 If we have already saved a position to rollback for new_value,
3023 forget that rollback position and register the new place instead,
3024 typically because a transformation has made the old place irrelevant.
3025 If not, a no-op.
3026
3027 @param new_place The new location in which we have presumably saved
3028 the new value, but which need to be rolled back to
3029 the old value.
3030 This location must also contain the new value.
3031 @returns old_value if one was found, else nullptr
3032 */
3033 Item *replace_rollback_place(Item **new_place);
3034
3035 /**
3036 Place has an alias of a new value which should possibly be rolled back.
3037 If so, this location should be rolled back as well.
3038 The value will already be registered with a rollback value in another
3039 place. Find that rollback value, and register a rollback record for this
3040 place as well, using the same rollback value.
3041
3042 @param place the location of the alias
3043 */
3044 void alias_rollback(Item **place);
3045
3046 void update_ident_context(SELECT_LEX *orig_block, SELECT_LEX *new_block);
3047 void cancel_rollback(Item *new_item);
3048 void cancel_rollback_at(Item **place);
3049 /**
3050 Restore locations set by calls to nocheck_register_item_tree_change(). The
3051 value to be restored depends on whether replace_rollback_place()
3052 has been called. If not, we restore the original value. If it has been
3053 called, we restore the one supplied by the latest call to
3054 replace_rollback_place()
3055 */
3056 void rollback_item_tree_changes();
3057
3058 /*
3059 Cleanup statement parse state (parse tree, lex) and execution
3060 state after execution of a non-prepared SQL statement.
3061 */
3062 void end_statement();
3063 void send_kill_message() const;
3064
3065 void reset_n_backup_open_tables_state(Open_tables_backup *backup,
3066 uint add_state_flags);
3067 void restore_backup_open_tables_state(Open_tables_backup *backup);
3068 void reset_sub_statement_state(Sub_statement_state *backup, uint new_state);
3069 void restore_sub_statement_state(Sub_statement_state *backup);
3070
3071 public:
3072 /**
3073 Start a read-only attachable transaction.
3074 There must be no active attachable transactions (in other words, there can
3075 be only one active attachable transaction at a time).
3076 */
3077 void begin_attachable_ro_transaction();
3078
3079 /**
3080 Start a read-write attachable transaction.
3081 All the read-only class' requirements apply.
3082 Additional requirements are documented along the class
3083 declaration.
3084 */
3085 void begin_attachable_rw_transaction();
3086
3087 /**
3088 End an active attachable transaction. Applies to both the read-only
3089 and the read-write versions.
3090 Note, that the read-write attachable transaction won't be terminated
3091 inside this method.
3092 To invoke the function there must be active attachable transaction.
3093 */
3094 void end_attachable_transaction();
3095
3096 /**
3097 @return true if there is an active attachable transaction.
3098 */
is_attachable_ro_transaction_active()3099 bool is_attachable_ro_transaction_active() const {
3100 return m_attachable_trx != nullptr && m_attachable_trx->is_read_only();
3101 }
3102
3103 /**
3104 @return true if there is an active attachable transaction.
3105 */
is_attachable_transaction_active()3106 bool is_attachable_transaction_active() const {
3107 return m_attachable_trx != nullptr;
3108 }
3109
3110 /**
3111 @return true if there is an active rw attachable transaction.
3112 */
is_attachable_rw_transaction_active()3113 bool is_attachable_rw_transaction_active() const {
3114 return m_attachable_trx != nullptr && !m_attachable_trx->is_read_only();
3115 }
3116
3117 public:
3118 /*
3119 @todo Make these methods private or remove them completely. Only
3120 decide_logging_format should call them. /Sven
3121 */
set_current_stmt_binlog_format_row_if_mixed()3122 inline void set_current_stmt_binlog_format_row_if_mixed() {
3123 DBUG_TRACE;
3124 /*
3125 This should only be called from decide_logging_format.
3126
3127 @todo Once we have ensured this, uncomment the following
3128 statement, remove the big comment below that, and remove the
3129 in_sub_stmt==0 condition from the following 'if'.
3130 */
3131 /* DBUG_ASSERT(in_sub_stmt == 0); */
3132 /*
3133 If in a stored/function trigger, the caller should already have done the
3134 change. We test in_sub_stmt to prevent introducing bugs where people
3135 wouldn't ensure that, and would switch to row-based mode in the middle
3136 of executing a stored function/trigger (which is too late, see also
3137 reset_current_stmt_binlog_format_row()); this condition will make their
3138 tests fail and so force them to propagate the
3139 lex->binlog_row_based_if_mixed upwards to the caller.
3140 */
3141 if ((variables.binlog_format == BINLOG_FORMAT_MIXED) && (in_sub_stmt == 0))
3142 set_current_stmt_binlog_format_row();
3143
3144 return;
3145 }
set_current_stmt_binlog_format_row()3146 inline void set_current_stmt_binlog_format_row() {
3147 DBUG_TRACE;
3148 current_stmt_binlog_format = BINLOG_FORMAT_ROW;
3149 return;
3150 }
clear_current_stmt_binlog_format_row()3151 inline void clear_current_stmt_binlog_format_row() {
3152 DBUG_TRACE;
3153 current_stmt_binlog_format = BINLOG_FORMAT_STMT;
3154 return;
3155 }
reset_current_stmt_binlog_format_row()3156 inline void reset_current_stmt_binlog_format_row() {
3157 DBUG_TRACE;
3158 DBUG_PRINT("debug", ("in_sub_stmt: %d, system_thread: %s", in_sub_stmt != 0,
3159 show_system_thread(system_thread)));
3160 if (in_sub_stmt == 0) {
3161 if (variables.binlog_format == BINLOG_FORMAT_ROW)
3162 set_current_stmt_binlog_format_row();
3163 else
3164 clear_current_stmt_binlog_format_row();
3165 }
3166 return;
3167 }
3168
3169 /**
3170 Copies variables.original_commit_timestamp to
3171 ((Slave_worker *)rli_slave)->original_commit_timestamp,
3172 if this is a slave thread.
3173 */
3174 void set_original_commit_timestamp_for_slave_thread();
3175
3176 /// Return the value of @@gtid_next_list: either a Gtid_set or NULL.
get_gtid_next_list()3177 Gtid_set *get_gtid_next_list() {
3178 return variables.gtid_next_list.is_non_null
3179 ? variables.gtid_next_list.gtid_set
3180 : nullptr;
3181 }
3182
3183 /// Return the value of @@gtid_next_list: either a Gtid_set or NULL.
get_gtid_next_list_const()3184 const Gtid_set *get_gtid_next_list_const() const {
3185 return const_cast<THD *>(this)->get_gtid_next_list();
3186 }
3187
3188 /**
3189 Return true if the statement/transaction cache is currently empty,
3190 false otherwise.
3191
3192 @param is_transactional if true, check the transaction cache.
3193 If false, check the statement cache.
3194 */
3195 bool is_binlog_cache_empty(bool is_transactional) const;
3196
3197 /**
3198 The GTID of the currently owned transaction.
3199
3200 ==== Modes of ownership ====
3201
3202 The following modes of ownership are possible:
3203
3204 - owned_gtid.sidno==0: the thread does not own any transaction.
3205
3206 - owned_gtid.sidno==THD::OWNED_SIDNO_ANONYMOUS(==-2): the thread
3207 owns an anonymous transaction
3208
3209 - owned_gtid.sidno>0 and owned_gtid.gno>0: the thread owns a GTID
3210 transaction.
3211
3212 - (owned_gtid.sidno==THD::OWNED_SIDNO_GTID_SET(==-1): this is
3213 currently not used. It was reserved for the case where multiple
3214 GTIDs are owned (using gtid_next_list). This was one idea to
3215 make GTIDs work with NDB: due to the epoch concept, multiple
3216 transactions can be combined into one in NDB, and therefore a
3217 single transaction on a slave can have multiple GTIDs.)
3218
3219 ==== Life cycle of ownership ====
3220
3221 Generally, transaction ownership starts when the transaction is
3222 assigned its GTID and ends when the transaction commits or rolls
3223 back. On a master (GTID_NEXT=AUTOMATIC), the GTID is assigned
3224 just before binlog flush; on a slave (GTID_NEXT=UUID:NUMBER or
3225 GTID_NEXT=ANONYMOUS) it is assigned before starting the
3226 transaction.
3227
3228 A new client always starts with owned_gtid.sidno=0.
3229
3230 Ownership can be acquired in the following ways:
3231
3232 A1. If GTID_NEXT = 'AUTOMATIC' and GTID_MODE = OFF/OFF_PERMISSIVE:
3233 The thread acquires anonymous ownership in
3234 gtid_state->generate_automatic_gtid called from
3235 MYSQL_BIN_LOG::write_transaction.
3236
3237 A2. If GTID_NEXT = 'AUTOMATIC' and GTID_MODE = ON/ON_PERMISSIVE:
3238 The thread generates the GTID and acquires ownership in
3239 gtid_state->generate_automatic_gtid called from
3240 MYSQL_BIN_LOG::write_transaction.
3241
3242 A3. If GTID_NEXT = 'UUID:NUMBER': The thread acquires ownership in
3243 the following ways:
3244
3245 - In a client, the SET GTID_NEXT statement acquires ownership.
3246
3247 - The slave's analogy to a clients SET GTID_NEXT statement is
3248 Gtid_log_event::do_apply_event. So the slave acquires
3249 ownership in this function.
3250
3251 Note: if the GTID UUID:NUMBER is already included in
3252 GTID_EXECUTED, then the transaction must be skipped (the GTID
3253 auto-skip feature). Thus, ownership is *not* acquired in this
3254 case and owned_gtid.sidno==0.
3255
3256 A4. If GTID_NEXT = 'ANONYMOUS':
3257
3258 - In a client, the SET GTID_NEXT statement acquires ownership.
3259
3260 - In a slave thread, Gtid_log_event::do_apply_event acquires
3261 ownership.
3262
3263 - Contrary to the case of GTID_NEXT='UUID:NUMBER', it is
3264 allowed to execute two transactions in sequence without
3265 changing GTID_NEXT (cf. R1 and R2 below). Both transactions
3266 should be executed as anonymous transactions. But ownership
3267 is released when the first transaction commits. Therefore,
3268 when GTID_NEXT='ANONYMOUS', we also acquire anonymous
3269 ownership when starting to execute a statement, in
3270 gtid_reacquire_ownership_if_anonymous called from
3271 gtid_pre_statement_checks (usually called from
3272 mysql_execute_command).
3273
3274 A5. Slave applier threads start in a special mode, having
3275 GTID_NEXT='NOT_YET_DETERMINED'. This mode cannot be set in a
3276 regular client. When GTID_NEXT=NOT_YET_DETERMINED, the slave
3277 thread is postponing the decision of the value of GTID_NEXT
3278 until it has more information. There are three cases:
3279
3280 - If the first transaction of the relay log has a
3281 Gtid_log_event, then it will set GTID_NEXT=GTID:NUMBER and
3282 acquire GTID ownership in Gtid_log_event::do_apply_event.
3283
3284 - If the first transaction of the relay log has a
3285 Anonymous_gtid_log_event, then it will set
3286 GTID_NEXT=ANONYMOUS and acquire anonymous ownership in
3287 Gtid_log_event::do_apply_event.
3288
3289 - If the relay log was received from a pre-5.7.6 master with
3290 GTID_MODE=OFF (or a pre-5.6 master), then there are neither
3291 Gtid_log_events nor Anonymous_log_events in the relay log.
3292 In this case, the slave sets GTID_NEXT=ANONYMOUS and
3293 acquires anonymous ownership when executing a
3294 Query_log_event (Query_log_event::do_apply_event calls
3295 mysql_parse which calls gtid_pre_statement_checks which
3296 calls gtid_reacquire_ownership_if_anonymous).
3297
3298 Ownership is released in the following ways:
3299
3300 R1. A thread that holds GTID ownership releases ownership at
3301 transaction commit or rollback. If GTID_NEXT=AUTOMATIC, all
3302 is fine. If GTID_NEXT=UUID:NUMBER, the UUID:NUMBER cannot be
3303 used for another transaction, since only one transaction can
3304 have any given GTID. To avoid the user mistake of forgetting
3305 to set back GTID_NEXT, on commit we set
3306 thd->variables.gtid_next.type=UNDEFINED_GTID. Then, any
3307 statement that user tries to execute other than SET GTID_NEXT
3308 will generate an error.
3309
3310 R2. A thread that holds anonymous ownership releases ownership at
3311 transaction commit or rollback. In this case there is no harm
3312 in leaving GTID_NEXT='ANONYMOUS', so
3313 thd->variables.gtid_next.type will remain ANONYMOUS_GTID and
3314 not UNDEFINED_GTID.
3315
3316 There are statements that generate multiple transactions in the
3317 binary log. This includes the following:
3318
3319 M1. DROP TABLE that is used with multiple tables, and the tables
3320 belong to more than one of the following groups: non-temporary
3321 table, temporary transactional table, temporary
3322 non-transactional table. DROP TABLE is split into one
3323 transaction for each of these groups of tables.
3324
3325 M2. DROP DATABASE that fails e.g. because rmdir fails. Then a
3326 single DROP TABLE is generated, which lists all tables that
3327 were dropped before the failure happened. But if the list of
3328 tables is big, and grows over a limit, the statement will be
3329 split into multiple statements.
3330
3331 M3. CREATE TABLE ... SELECT that is logged in row format. Then
3332 the server generates a single CREATE statement, followed by a
3333 BEGIN ... row events ... COMMIT transaction.
3334
3335 M4. A statement that updates both transactional and
3336 non-transactional tables in the same statement, and is logged
3337 in row format. Then it generates one transaction for the
3338 non-transactional row updates, followed by one transaction for
3339 the transactional row updates.
3340
3341 M5. CALL is executed as multiple transactions and logged as
3342 multiple transactions.
3343
3344 The general rules for multi-transaction statements are:
3345
3346 - If GTID_NEXT=AUTOMATIC and GTID_MODE=ON or ON_PERMISSIVE, one
3347 GTID should be generated for each transaction within the
3348 statement. Therefore, ownership must be released after each
3349 commit so that a new GTID can be generated by the next
3350 transaction. Typically mysql_bin_log.commit() is called to
3351 achieve this. (Note that some of these statements are currently
3352 disallowed when GTID_MODE=ON.)
3353
3354 - If GTID_NEXT=AUTOMATIC and GTID_MODE=OFF or OFF_PERMISSIVE, one
3355 Anonymous_gtid_log_event should be generated for each
3356 transaction within the statement. Similar to the case above, we
3357 call mysql_bin_log.commit() and release ownership between
3358 transactions within the statement.
3359
3360 This works for all the special cases M1-M5 except M4. When a
3361 statement writes both non-transactional and transactional
3362 updates to the binary log, both the transaction cache and the
3363 statement cache are flushed within the same call to
3364 flush_thread_caches(THD) from within the binary log group commit
3365 code. At that point we cannot use mysql_bin_log.commit().
3366 Instead we release ownership using direct calls to
3367 gtid_state->release_anonymous_ownership() and
3368 thd->clear_owned_gtids() from binlog_cache_mngr::flush.
3369
3370 - If GTID_NEXT=ANONYMOUS, anonymous ownership must be *preserved*
3371 between transactions within the statement, to prevent that a
3372 concurrent SET GTID_MODE=ON makes it impossible to log the
3373 statement. To avoid that ownership is released if
3374 mysql_bin_log.commit() is called, we set
3375 thd->is_commit_in_middle_of_statement before calling
3376 mysql_bin_log.commit. Note that we must set this flag only if
3377 GTID_NEXT=ANONYMOUS, not if the transaction is anonymous when
3378 GTID_NEXT=AUTOMATIC and GTID_MODE=OFF.
3379
3380 This works for all the special cases M1-M5 except M4. When a
3381 statement writes non-transactional updates in the middle of a
3382 transaction, but keeps some transactional updates in the
3383 transaction cache, then it is not easy to know at the time of
3384 calling mysql_bin_log.commit() whether anonymous ownership needs
3385 to be preserved or not. Instead, we directly check if the
3386 transaction cache is nonempty before releasing anonymous
3387 ownership inside Gtid_state::update_gtids_impl.
3388
3389 - If GTID_NEXT='UUID:NUMBER', it is impossible to log a
3390 multi-transaction statement, since each GTID can only be used by
3391 one transaction. Therefore, an error must be generated in this
3392 case. Errors are generated in different ways for the different
3393 statement types:
3394
3395 - DROP TABLE: we can detect the situation before it happens,
3396 since the table type is known once the tables are opened. So
3397 we generate an error before even executing the statement.
3398
3399 - DROP DATABASE: we can't detect the situation until it is too
3400 late; the tables have already been dropped and we cannot log
3401 anything meaningful. So we don't log at all.
3402
3403 - CREATE TABLE ... SELECT: this is not allowed when
3404 enforce_gtid_consistency is ON; the statement will be
3405 forbidden in is_ddl_gtid_compatible.
3406
3407 - Statements that update both transactional and
3408 non-transactional tables are disallowed when GTID_MODE=ON, so
3409 this normally does not happen. However, it can happen if the
3410 slave uses a different engine type than the master, so that a
3411 statement that updates InnoDB+InnoDB on master updates
3412 InnoDB+MyISAM on slave. In this case the statement will be
3413 forbidden in is_dml_gtid_compatible and will not be allowed to
3414 execute.
3415
3416 - CALL: the second statement will generate an error because
3417 GTID_NEXT is 'undefined'. Note that this situation can only
3418 happen if user does it on purpose: A CALL on master is logged
3419 as multiple statements, so a slave never executes CALL with
3420 GTID_NEXT='UUID:NUMBER'.
3421
3422 Finally, ownership release is suppressed in one more corner case:
3423
3424 C1. Administration statements including OPTIMIZE TABLE, REPAIR
3425 TABLE, or ANALYZE TABLE are written to the binary log even if
3426 they fail. This means that the thread first calls
3427 trans_rollack, and then writes the statement to the binlog.
3428 Rollback normally releases ownership. But ownership must be
3429 kept until writing the binlog. The solution is that these
3430 statements set thd->skip_gtid_rollback=true before calling
3431 trans_rollback, and Gtid_state::update_on_rollback does not
3432 release ownership if the flag is set.
3433
3434 @todo It would probably be better to encapsulate this more, maybe
3435 use Gtid_specification instead of Gtid.
3436 */
3437 Gtid owned_gtid;
3438 static const int OWNED_SIDNO_GTID_SET = -1;
3439 static const int OWNED_SIDNO_ANONYMOUS = -2;
3440
3441 /**
3442 For convenience, this contains the SID component of the GTID
3443 stored in owned_gtid.
3444 */
3445 rpl_sid owned_sid;
3446
3447 /** SE GTID persistence flag types. */
3448 enum Se_GTID_flag : size_t {
3449 /** Pin owned GTID */
3450 SE_GTID_PIN = 0,
3451 /** Cleanup GTID during unpin. */
3452 SE_GTID_CLEANUP,
3453 /** SE would persist GTID for current transaction. */
3454 SE_GTID_PERSIST,
3455 /** If RESET log in progress. */
3456 SE_GTID_RESET_LOG,
3457 /** Max element holding the biset size. */
3458 SE_GTID_MAX
3459 };
3460
3461 using Se_GTID_flagset = std::bitset<SE_GTID_MAX>;
3462
3463 /** Flags for SE GTID persistence. */
3464 Se_GTID_flagset m_se_gtid_flags;
3465
3466 /** Defer freeing owned GTID and SID till unpinned. */
pin_gtid()3467 void pin_gtid() { m_se_gtid_flags.set(SE_GTID_PIN); }
3468
3469 /** Unpin and free GTID and SID. */
unpin_gtid()3470 void unpin_gtid() {
3471 m_se_gtid_flags.reset(SE_GTID_PIN);
3472 /* Do any deferred cleanup */
3473 if (m_se_gtid_flags[SE_GTID_CLEANUP]) {
3474 clear_owned_gtids();
3475 m_se_gtid_flags.reset(SE_GTID_CLEANUP);
3476 }
3477 }
3478
3479 /** @return true, if single phase XA commit operation. */
3480 bool is_one_phase_commit();
3481
3482 /** Set when binlog reset operation is started. */
set_log_reset()3483 void set_log_reset() { m_se_gtid_flags.set(SE_GTID_RESET_LOG); }
3484
3485 /** Cleared after flushing SE logs during binlog reset. */
clear_log_reset()3486 void clear_log_reset() { m_se_gtid_flags.reset(SE_GTID_RESET_LOG); }
3487
3488 /** @return true, if binlog reset operation. */
is_log_reset()3489 bool is_log_reset() const { return (m_se_gtid_flags[SE_GTID_RESET_LOG]); }
3490
3491 /** Set by SE when it guarantees GTID persistence. */
set_gtid_persisted_by_se()3492 void set_gtid_persisted_by_se() { m_se_gtid_flags.set(SE_GTID_PERSIST); }
3493
3494 /** Reset by SE at transaction end after persisting GTID. */
reset_gtid_persisted_by_se()3495 void reset_gtid_persisted_by_se() { m_se_gtid_flags.reset(SE_GTID_PERSIST); }
3496
3497 /** @return true, if SE persists GTID for current transaction. */
se_persists_gtid()3498 bool se_persists_gtid() const {
3499 DBUG_EXECUTE_IF("disable_se_persists_gtid", return (false););
3500 auto trx = get_transaction();
3501 auto xid_state = trx->xid_state();
3502 /* XA transactions are always persisted by Innodb. */
3503 return (!xid_state->has_state(XID_STATE::XA_NOTR) ||
3504 m_se_gtid_flags[SE_GTID_PERSIST]);
3505 }
3506
3507 #ifdef HAVE_GTID_NEXT_LIST
3508 /**
3509 If this thread owns a set of GTIDs (i.e., GTID_NEXT_LIST != NULL),
3510 then this member variable contains the subset of those GTIDs that
3511 are owned by this thread.
3512 */
3513 Gtid_set owned_gtid_set;
3514 #endif
3515
3516 /*
3517 Replication related context.
3518
3519 @todo: move more parts of replication related fields in THD to inside this
3520 class.
3521 */
3522 Rpl_thd_context rpl_thd_ctx;
3523
clear_owned_gtids()3524 void clear_owned_gtids() {
3525 /* Defer GTID cleanup if pinned. Used for XA transactions where
3526 SE(Innodb) needs to read GTID. */
3527 if (m_se_gtid_flags[SE_GTID_PIN]) {
3528 m_se_gtid_flags.set(SE_GTID_CLEANUP);
3529 return;
3530 }
3531 if (owned_gtid.sidno == OWNED_SIDNO_GTID_SET) {
3532 #ifdef HAVE_GTID_NEXT_LIST
3533 owned_gtid_set.clear();
3534 #else
3535 DBUG_ASSERT(0);
3536 #endif
3537 }
3538 owned_gtid.clear();
3539 owned_sid.clear();
3540 owned_gtid.dbug_print(nullptr, "set owned_gtid in clear_owned_gtids");
3541 }
3542
3543 /** @return true, if owned GTID is empty or waiting for deferred cleanup. */
owned_gtid_is_empty()3544 bool owned_gtid_is_empty() {
3545 if (m_se_gtid_flags[SE_GTID_CLEANUP]) {
3546 return (true);
3547 }
3548 return (owned_gtid.is_empty());
3549 }
3550
3551 /*
3552 There are some statements (like OPTIMIZE TABLE, ANALYZE TABLE and
3553 REPAIR TABLE) that might call trans_rollback_stmt() and also will be
3554 sucessfully executed and will have to go to the binary log.
3555 For these statements, the skip_gtid_rollback flag must be set to avoid
3556 problems when the statement is executed with a GTID_NEXT set to
3557 ASSIGNED_GTID (like the SQL thread do when applying events from other
3558 server). When this flag is set, a call to gtid_rollback() will do nothing.
3559 */
3560 bool skip_gtid_rollback;
3561 /*
3562 There are some statements (like DROP DATABASE that fails on rmdir
3563 and gets rewritten to multiple DROP TABLE statements) that may
3564 call trans_commit_stmt() before it has written all statements to
3565 the binlog. When using GTID_NEXT = ANONYMOUS, such statements
3566 should not release ownership of the anonymous transaction until
3567 all statements have been written to the binlog. To prevent that
3568 update_gtid_impl releases ownership, such statements must set this
3569 flag.
3570 */
3571 bool is_commit_in_middle_of_statement;
3572
3573 /*
3574 True while the transaction is executing, if one of
3575 is_ddl_gtid_consistent or is_dml_gtid_consistent returned false.
3576 */
3577 bool has_gtid_consistency_violation;
3578
db()3579 const LEX_CSTRING &db() const { return m_db; }
3580
3581 /**
3582 Set the current database; use deep copy of C-string.
3583
3584 @param new_db the new database name.
3585
3586 Initialize the current database from a NULL-terminated string with
3587 length. If we run out of memory, we free the current database and
3588 return true. This way the user will notice the error as there will be
3589 no current database selected (in addition to the error message set by
3590 malloc).
3591
3592 @note This operation just sets {db, db_length}. Switching the current
3593 database usually involves other actions, like switching other database
3594 attributes including security context. In the future, this operation
3595 will be made private and more convenient interface will be provided.
3596
3597 @return Operation status
3598 @retval false Success
3599 @retval true Out-of-memory error
3600 */
3601 bool set_db(const LEX_CSTRING &new_db);
3602
3603 /**
3604 Set the current database; use shallow copy of C-string.
3605
3606 @param new_db the new database name.
3607
3608 @note This operation just sets {db, db_length}. Switching the current
3609 database usually involves other actions, like switching other database
3610 attributes including security context. In the future, this operation
3611 will be made private and more convenient interface will be provided.
3612 */
reset_db(const LEX_CSTRING & new_db)3613 void reset_db(const LEX_CSTRING &new_db) {
3614 m_db.str = new_db.str;
3615 m_db.length = new_db.length;
3616 #ifdef HAVE_PSI_THREAD_INTERFACE
3617 PSI_THREAD_CALL(set_thread_db)(new_db.str, static_cast<int>(new_db.length));
3618 #endif
3619 }
3620 /*
3621 Copy the current database to the argument. Use the current arena to
3622 allocate memory for a deep copy: current database may be freed after
3623 a statement is parsed but before it's executed.
3624 */
copy_db_to(char const ** p_db,size_t * p_db_length)3625 bool copy_db_to(char const **p_db, size_t *p_db_length) const {
3626 if (m_db.str == nullptr) {
3627 my_error(ER_NO_DB_ERROR, MYF(0));
3628 return true;
3629 }
3630 *p_db = strmake(m_db.str, m_db.length);
3631 *p_db_length = m_db.length;
3632 return false;
3633 }
3634
copy_db_to(char ** p_db,size_t * p_db_length)3635 bool copy_db_to(char **p_db, size_t *p_db_length) const {
3636 return copy_db_to(const_cast<char const **>(p_db), p_db_length);
3637 }
3638
3639 thd_scheduler scheduler;
3640
3641 /**
3642 Get resource group context.
3643
3644 @returns pointer to resource group context.
3645 */
3646
resource_group_ctx()3647 resourcegroups::Resource_group_ctx *resource_group_ctx() {
3648 return &m_resource_group_ctx;
3649 }
3650
3651 public:
3652 /**
3653 Save the performance schema thread instrumentation
3654 associated with this user session.
3655 @param psi Performance schema thread instrumentation
3656 */
set_psi(PSI_thread * psi)3657 void set_psi(PSI_thread *psi) { m_psi = psi; }
3658
3659 /**
3660 Read the performance schema thread instrumentation
3661 associated with this user session.
3662 This method is safe to use from a different thread.
3663 */
get_psi()3664 PSI_thread *get_psi() const { return m_psi; }
3665
3666 private:
3667 /**
3668 Performance schema thread instrumentation for this session.
3669 This member is maintained using atomic operations,
3670 do not access it directly.
3671 @sa set_psi
3672 @sa get_psi
3673 */
3674 std::atomic<PSI_thread *> m_psi;
3675
3676 public:
get_internal_handler()3677 const Internal_error_handler *get_internal_handler() const {
3678 return m_internal_handler;
3679 }
3680
3681 /**
3682 Add an internal error handler to the thread execution context.
3683 @param handler the exception handler to add
3684 */
3685 void push_internal_handler(Internal_error_handler *handler);
3686
3687 private:
3688 /**
3689 Handle a sql condition.
3690 @param sql_errno the condition error number
3691 @param sqlstate the condition sqlstate
3692 @param level the condition level
3693 @param msg the condition message text
3694 @return true if the condition is handled
3695 */
3696 bool handle_condition(uint sql_errno, const char *sqlstate,
3697 Sql_condition::enum_severity_level *level,
3698 const char *msg);
3699
3700 public:
3701 /**
3702 Remove the error handler last pushed.
3703 */
3704 Internal_error_handler *pop_internal_handler();
3705
3706 Opt_trace_context opt_trace; ///< optimizer trace of current statement
3707 /**
3708 Raise an exception condition.
3709 @param code the MYSQL_ERRNO error code of the error
3710 */
3711 void raise_error(uint code);
3712
3713 /**
3714 Raise an exception condition, with a formatted message.
3715 @param code the MYSQL_ERRNO error code of the error
3716 */
3717 void raise_error_printf(uint code, ...);
3718
3719 /**
3720 Raise a completion condition (warning).
3721 @param code the MYSQL_ERRNO error code of the warning
3722 */
3723 void raise_warning(uint code);
3724
3725 /**
3726 Raise a completion condition (warning), with a formatted message.
3727 @param code the MYSQL_ERRNO error code of the warning
3728 */
3729 void raise_warning_printf(uint code, ...);
3730
3731 /**
3732 Raise a completion condition (note), with a fixed message.
3733 @param code the MYSQL_ERRNO error code of the note
3734 */
3735 void raise_note(uint code);
3736
3737 /**
3738 Raise an completion condition (note), with a formatted message.
3739 @param code the MYSQL_ERRNO error code of the note
3740 */
3741 void raise_note_printf(uint code, ...);
3742
3743 private:
3744 /*
3745 Only the implementation of the SIGNAL and RESIGNAL statements
3746 is permitted to raise SQL conditions in a generic way,
3747 or to raise them by bypassing handlers (RESIGNAL).
3748 To raise a SQL condition, the code should use the public
3749 raise_error() or raise_warning() methods provided by class THD.
3750 */
3751 friend class Sql_cmd_common_signal;
3752 friend class Sql_cmd_signal;
3753 friend class Sql_cmd_resignal;
3754 friend void push_warning(THD *thd,
3755 Sql_condition::enum_severity_level severity,
3756 uint code, const char *message_text);
3757 friend void my_message_sql(uint, const char *, myf);
3758
3759 /**
3760 Raise a generic SQL condition. Also calls mysql_audit_notify() unless
3761 the condition is handled by a SQL condition handler.
3762
3763 @param sql_errno the condition error number
3764 @param sqlstate the condition SQLSTATE
3765 @param level the condition level
3766 @param msg the condition message text
3767 @param fatal_error should the fatal_error flag be set?
3768 @return The condition raised, or NULL
3769 */
3770 Sql_condition *raise_condition(uint sql_errno, const char *sqlstate,
3771 Sql_condition::enum_severity_level level,
3772 const char *msg, bool fatal_error = false);
3773
3774 public:
3775 void set_command(enum enum_server_command command);
3776
get_command()3777 inline enum enum_server_command get_command() const { return m_command; }
3778
3779 /**
3780 For safe and protected access to the query string, the following
3781 rules should be followed:
3782 1: Only the owner (current_thd) can set the query string.
3783 This will be protected by LOCK_thd_query.
3784 2: The owner (current_thd) can read the query string without
3785 locking LOCK_thd_query.
3786 3: Other threads must lock LOCK_thd_query before reading
3787 the query string.
3788
3789 This means that write-write conflicts are avoided by LOCK_thd_query.
3790 Read(by owner or other thread)-write(other thread) are disallowed.
3791 Read(other thread)-write(by owner) conflicts are avoided by LOCK_thd_query.
3792 Read(by owner)-write(by owner) won't happen as THD=thread.
3793
3794 We want to keep current_thd out of header files, so the debug assert,
3795 is moved to the .cc file. In optimized mode, we want this getter to
3796 be fast, so we inline it.
3797 */
3798 void debug_assert_query_locked() const;
query()3799 const LEX_CSTRING &query() const {
3800 #ifndef DBUG_OFF
3801 debug_assert_query_locked();
3802 #endif
3803 return m_query_string;
3804 }
3805
3806 /**
3807 The current query in normalized form. The format is intended to be
3808 identical to the digest text of performance_schema, but not limited in
3809 size. In this case the parse tree is traversed as opposed to a (limited)
3810 token buffer. The string is allocated by this Statement and will be
3811 available until the next call to this function or this object is deleted.
3812
3813 @note We have no protection against out-of-memory errors as this function
3814 relies on the Item::print() interface which does not propagate errors.
3815
3816 @return The current query in normalized form.
3817 */
3818 const String normalized_query();
3819
3820 /**
3821 Set query to be displayed in performance schema (threads table etc.).
3822 */
set_query_for_display(const char * query_arg MY_ATTRIBUTE ((unused)),size_t query_length_arg MY_ATTRIBUTE ((unused)))3823 void set_query_for_display(const char *query_arg MY_ATTRIBUTE((unused)),
3824 size_t query_length_arg MY_ATTRIBUTE((unused))) {
3825 // Set in pfs events statements table
3826 MYSQL_SET_STATEMENT_TEXT(m_statement_psi, query_arg,
3827 static_cast<uint>(query_length_arg));
3828 #ifdef HAVE_PSI_THREAD_INTERFACE
3829 // Set in pfs threads table
3830 PSI_THREAD_CALL(set_thread_info)
3831 (query_arg, static_cast<uint>(query_length_arg));
3832 #endif
3833 }
reset_query_for_display(void)3834 void reset_query_for_display(void) { set_query_for_display(nullptr, 0); }
3835
3836 /**
3837 Assign a new value to thd->m_query_string.
3838 Protected with the LOCK_thd_query mutex.
3839 */
set_query(const char * query_arg,size_t query_length_arg)3840 void set_query(const char *query_arg, size_t query_length_arg) {
3841 LEX_CSTRING tmp = {query_arg, query_length_arg};
3842 set_query(tmp);
3843 }
3844 void set_query(LEX_CSTRING query_arg);
reset_query()3845 void reset_query() { set_query(LEX_CSTRING()); }
3846
3847 /**
3848 Set the rewritten query (with passwords obfuscated etc.) on the THD.
3849 Wraps this in the LOCK_thd_query mutex to protect against race conditions
3850 with SHOW PROCESSLIST inspecting that string.
3851
3852 This uses swap() and therefore "steals" the argument from the caller;
3853 the caller MUST take care not to try to use its own string after calling
3854 this function! This is an optimization for mysql_rewrite_query() so we
3855 don't copy its temporary string (which may get very long, up to
3856 @@max_allowed_packet).
3857
3858 Using this outside of mysql_rewrite_query() is almost certainly wrong;
3859 please check with the runtime team!
3860
3861 @param query_arg The rewritten query to use for slow/bin/general logging.
3862 The value will be released in the caller and MUST NOT
3863 be used there after calling this function.
3864 */
3865 void swap_rewritten_query(String &query_arg);
3866
3867 /**
3868 Get the rewritten query (with passwords obfuscated etc.) from the THD.
3869 If done from a different thread (from the one that the rewritten_query
3870 is set on), the caller must hold LOCK_thd_query while calling this!
3871 */
rewritten_query()3872 const String &rewritten_query() const {
3873 #ifndef DBUG_OFF
3874 if (current_thd != this) mysql_mutex_assert_owner(&LOCK_thd_query);
3875 #endif
3876 return m_rewritten_query;
3877 }
3878
3879 /**
3880 Reset thd->m_rewritten_query. Protected with the LOCK_thd_query mutex.
3881 */
reset_rewritten_query()3882 void reset_rewritten_query() {
3883 if (rewritten_query().length()) {
3884 String empty;
3885 swap_rewritten_query(empty);
3886 }
3887 }
3888
3889 /**
3890 Assign a new value to thd->query_id.
3891 Protected with the LOCK_thd_data mutex.
3892 */
set_query_id(query_id_t new_query_id)3893 void set_query_id(query_id_t new_query_id) {
3894 mysql_mutex_lock(&LOCK_thd_data);
3895 query_id = new_query_id;
3896 mysql_mutex_unlock(&LOCK_thd_data);
3897 MYSQL_SET_STATEMENT_QUERY_ID(m_statement_psi, new_query_id);
3898 }
3899
3900 /**
3901 Assign a new value to open_tables.
3902 Protected with the LOCK_thd_data mutex.
3903 */
set_open_tables(TABLE * open_tables_arg)3904 void set_open_tables(TABLE *open_tables_arg) {
3905 mysql_mutex_lock(&LOCK_thd_data);
3906 open_tables = open_tables_arg;
3907 mysql_mutex_unlock(&LOCK_thd_data);
3908 }
3909
3910 /**
3911 Assign a new value to is_killable
3912 Protected with the LOCK_thd_data mutex.
3913 */
set_is_killable(bool is_killable_arg)3914 void set_is_killable(bool is_killable_arg) {
3915 mysql_mutex_lock(&LOCK_thd_data);
3916 is_killable = is_killable_arg;
3917 mysql_mutex_unlock(&LOCK_thd_data);
3918 }
3919
enter_locked_tables_mode(enum_locked_tables_mode mode_arg)3920 void enter_locked_tables_mode(enum_locked_tables_mode mode_arg) {
3921 DBUG_ASSERT(locked_tables_mode == LTM_NONE);
3922
3923 if (mode_arg == LTM_LOCK_TABLES) {
3924 /*
3925 When entering LOCK TABLES mode we should set explicit duration
3926 for all metadata locks acquired so far in order to avoid releasing
3927 them till UNLOCK TABLES statement.
3928 We don't do this when entering prelocked mode since sub-statements
3929 don't release metadata locks and restoring status-quo after leaving
3930 prelocking mode gets complicated.
3931 */
3932 mdl_context.set_explicit_duration_for_all_locks();
3933 }
3934
3935 locked_tables_mode = mode_arg;
3936 }
3937 void leave_locked_tables_mode();
3938 int decide_logging_format(TABLE_LIST *tables);
3939 /**
3940 is_dml_gtid_compatible() and is_ddl_gtid_compatible() check if the
3941 statement that is about to be processed will safely get a
3942 GTID. Currently, the following cases may lead to errors
3943 (e.g. duplicated GTIDs) and as such are forbidden:
3944
3945 1. DML statements that mix non-transactional updates with
3946 transactional updates.
3947
3948 2. Transactions that use non-transactional tables after
3949 having used transactional tables.
3950
3951 3. CREATE...SELECT statement;
3952
3953 4. CREATE TEMPORARY TABLE or DROP TEMPORARY TABLE within a
3954 transaction
3955
3956 The first two conditions have to be checked in
3957 decide_logging_format, because that's where we know if the table
3958 is transactional or not. These are implemented in
3959 is_dml_gtid_compatible().
3960
3961 The third and fourth conditions have to be checked in
3962 mysql_execute_command because (1) that prevents implicit commit
3963 from being executed if the statement fails; (2) DROP TEMPORARY
3964 TABLE does not invoke decide_logging_format. These are
3965 implemented in is_ddl_gtid_compatible().
3966
3967 In the cases where GTID violations generate errors,
3968 is_ddl_gtid_compatible() needs to be called before the implicit
3969 pre-commit, so that there is no implicit commit if the statement
3970 fails.
3971
3972 In the cases where GTID violations do not generate errors,
3973 is_ddl_gtid_compatible() needs to be called after the implicit
3974 pre-commit, because in these cases the function will increase the
3975 global counter automatic_gtid_violating_transaction_count or
3976 anonymous_gtid_violating_transaction_count. If there is an
3977 ongoing transaction, the implicit commit will commit the
3978 transaction, which will call update_gtids_impl, which should
3979 decrease the counters depending on whether the *old* was violating
3980 GTID-consistency or not. Thus, we should increase the counters
3981 only after the old transaction is committed.
3982
3983 @param some_transactional_table true if the statement updates some
3984 transactional table; false otherwise.
3985
3986 @param some_non_transactional_table true if the statement updates
3987 some non-transactional table; false otherwise.
3988
3989 @param non_transactional_tables_are_tmp true if all updated
3990 non-transactional tables are temporary.
3991
3992 @retval true if the statement is compatible;
3993 @retval false if the statement is not compatible.
3994 */
3995 bool is_dml_gtid_compatible(bool some_transactional_table,
3996 bool some_non_transactional_table,
3997 bool non_transactional_tables_are_tmp);
3998 bool is_ddl_gtid_compatible();
binlog_invoker()3999 void binlog_invoker() { m_binlog_invoker = true; }
need_binlog_invoker()4000 bool need_binlog_invoker() const { return m_binlog_invoker; }
4001 void get_definer(LEX_USER *definer);
set_invoker(const LEX_STRING * user,const LEX_STRING * host)4002 void set_invoker(const LEX_STRING *user, const LEX_STRING *host) {
4003 m_invoker_user.str = user->str;
4004 m_invoker_user.length = user->length;
4005 m_invoker_host.str = host->str;
4006 m_invoker_host.length = host->length;
4007 }
get_invoker_user()4008 LEX_CSTRING get_invoker_user() const { return m_invoker_user; }
get_invoker_host()4009 LEX_CSTRING get_invoker_host() const { return m_invoker_host; }
has_invoker()4010 bool has_invoker() const { return m_invoker_user.str != nullptr; }
4011
4012 void mark_transaction_to_rollback(bool all);
4013
4014 private:
4015 /** The current internal error handler for this thread, or NULL. */
4016 Internal_error_handler *m_internal_handler;
4017
4018 /**
4019 This memory root is used for two purposes:
4020 - for conventional queries, to allocate structures stored in main_lex
4021 during parsing, and allocate runtime data (execution plan, etc.)
4022 during execution.
4023 - for prepared queries, only to allocate runtime data. The parsed
4024 tree itself is reused between executions and thus is stored elsewhere.
4025 */
4026 MEM_ROOT main_mem_root;
4027 Diagnostics_area main_da;
4028 Diagnostics_area m_parser_da; /**< cf. get_parser_da() */
4029 Diagnostics_area m_query_rewrite_plugin_da;
4030 Diagnostics_area *m_query_rewrite_plugin_da_ptr;
4031
4032 Diagnostics_area *m_stmt_da;
4033
4034 /**
4035 It will be set TURE if CURRENT_USER() is called in account management
4036 statements or default definer is set in CREATE/ALTER SP, SF, Event,
4037 TRIGGER or VIEW statements.
4038
4039 Current user will be binlogged into Query_log_event if current_user_used
4040 is true; It will be stored into m_invoker_host and m_invoker_user by SQL
4041 thread.
4042 */
4043 bool m_binlog_invoker;
4044
4045 /**
4046 It points to the invoker in the Query_log_event.
4047 SQL thread use it as the default definer in CREATE/ALTER SP, SF, Event,
4048 TRIGGER or VIEW statements or current user in account management
4049 statements if it is not NULL.
4050 */
4051 LEX_CSTRING m_invoker_user;
4052 LEX_CSTRING m_invoker_host;
4053
4054 friend class Protocol_classic;
4055
4056 private:
4057 /**
4058 Optimizer cost model for server operations.
4059 */
4060 Cost_model_server m_cost_model;
4061
4062 public:
4063 /**
4064 Initialize the optimizer cost model.
4065
4066 This function should be called each time a new query is started.
4067 */
init_cost_model()4068 void init_cost_model() { m_cost_model.init(); }
4069
4070 /**
4071 Retrieve the optimizer cost model for this connection.
4072 */
cost_model()4073 const Cost_model_server *cost_model() const { return &m_cost_model; }
4074
4075 Session_tracker session_tracker;
4076 Session_sysvar_resource_manager session_sysvar_res_mgr;
4077
syntax_error()4078 void syntax_error() { syntax_error(ER_SYNTAX_ERROR); }
4079 void syntax_error(const char *format, ...)
4080 MY_ATTRIBUTE((format(printf, 2, 3)));
4081 void syntax_error(int mysql_errno, ...);
4082
syntax_error_at(const YYLTYPE & location)4083 void syntax_error_at(const YYLTYPE &location) {
4084 syntax_error_at(location, ER_SYNTAX_ERROR);
4085 }
4086 void syntax_error_at(const YYLTYPE &location, const char *format, ...)
4087 MY_ATTRIBUTE((format(printf, 3, 4)));
4088 void syntax_error_at(const YYLTYPE &location, int mysql_errno, ...);
4089
4090 void vsyntax_error_at(const YYLTYPE &location, const char *format,
4091 va_list args) MY_ATTRIBUTE((format(printf, 3, 0)));
4092 void vsyntax_error_at(const char *pos_in_lexer_raw_buffer, const char *format,
4093 va_list args) MY_ATTRIBUTE((format(printf, 3, 0)));
4094
4095 /**
4096 Send name and type of result to client.
4097
4098 Sum fields has table name empty and field_name.
4099
4100 @param list List of items to send to client
4101 @param flags Bit mask with the following functions:
4102 - 1 send number of rows
4103 - 2 send default values
4104 - 4 don't write eof packet
4105
4106 @retval
4107 false ok
4108 @retval
4109 true Error (Note that in this case the error is not sent to the client)
4110 */
4111
4112 bool send_result_metadata(List<Item> *list, uint flags);
4113
4114 /**
4115 Send one result set row.
4116
4117 @param row_items a collection of column values for that row
4118
4119 @return Error status.
4120 @retval true Error.
4121 @retval false Success.
4122 */
4123
4124 bool send_result_set_row(List<Item> *row_items);
4125
4126 /*
4127 Send the status of the current statement execution over network.
4128
4129 In MySQL, there are two types of SQL statements: those that return
4130 a result set and those that return status information only.
4131
4132 If a statement returns a result set, it consists of 3 parts:
4133 - result set meta-data
4134 - variable number of result set rows (can be 0)
4135 - followed and terminated by EOF or ERROR packet
4136
4137 Once the client has seen the meta-data information, it always
4138 expects an EOF or ERROR to terminate the result set. If ERROR is
4139 received, the result set rows are normally discarded (this is up
4140 to the client implementation, libmysql at least does discard them).
4141 EOF, on the contrary, means "successfully evaluated the entire
4142 result set". Since we don't know how many rows belong to a result
4143 set until it's evaluated, EOF/ERROR is the indicator of the end
4144 of the row stream. Note, that we can not buffer result set rows
4145 on the server -- there may be an arbitrary number of rows. But
4146 we do buffer the last packet (EOF/ERROR) in the Diagnostics_area and
4147 delay sending it till the very end of execution (here), to be able to
4148 change EOF to an ERROR if commit failed or some other error occurred
4149 during the last cleanup steps taken after execution.
4150
4151 A statement that does not return a result set doesn't send result
4152 set meta-data either. Instead it returns one of:
4153 - OK packet
4154 - ERROR packet.
4155 Similarly to the EOF/ERROR of the previous statement type, OK/ERROR
4156 packet is "buffered" in the Diagnostics Area and sent to the client
4157 in the end of statement.
4158
4159 @note This method defines a template, but delegates actual
4160 sending of data to virtual Protocol::send_{ok,eof,error}. This
4161 allows for implementation of protocols that "intercept" ok/eof/error
4162 messages, and store them in memory, etc, instead of sending to
4163 the client.
4164
4165 @pre The Diagnostics Area is assigned or disabled. It can not be empty
4166 -- we assume that every SQL statement or COM_* command
4167 generates OK, ERROR, or EOF status.
4168
4169 @post The status information is encoded to protocol format and sent to the
4170 client.
4171
4172 @return We conventionally return void, since the only type of error
4173 that can happen here is a NET (transport) error, and that one
4174 will become visible when we attempt to read from the NET the
4175 next command.
4176 Diagnostics_area::is_sent is set for debugging purposes only.
4177 */
4178
4179 void send_statement_status();
4180
4181 /**
4182 This is only used by master dump threads.
4183 When the master receives a new connection from a slave with a
4184 UUID (for slave versions >= 5.6)/server_id(for slave versions < 5.6)
4185 that is already connected, it will set this flag true
4186 before killing the old slave connection.
4187 */
4188 bool duplicate_slave_id;
4189
4190 /**
4191 Claim all the memory used by the THD object.
4192 This method is to keep memory instrumentation statistics
4193 updated, when an object is transfered across threads.
4194 */
4195 void claim_memory_ownership();
4196
is_a_srv_session()4197 bool is_a_srv_session() const { return is_a_srv_session_thd; }
mark_as_srv_session()4198 void mark_as_srv_session() { is_a_srv_session_thd = true; }
4199
4200 /**
4201 Returns the plugin, the thd belongs to.
4202 @return pointer to the plugin id
4203 */
get_plugin()4204 const st_plugin_int *get_plugin() const { return m_plugin; }
4205 /**
4206 Sets the plugin id to the value provided as parameter
4207 @param plugin the id of the plugin the thd belongs to
4208 */
set_plugin(const st_plugin_int * plugin)4209 void set_plugin(const st_plugin_int *plugin) { m_plugin = plugin; }
4210 #ifndef DBUG_OFF
get_tmp_table_seq_id()4211 uint get_tmp_table_seq_id() { return tmp_table_seq_id++; }
set_tmp_table_seq_id(uint arg)4212 void set_tmp_table_seq_id(uint arg) { tmp_table_seq_id = arg; }
4213 #endif
4214
is_plugin_fake_ddl()4215 bool is_plugin_fake_ddl() const { return m_is_plugin_fake_ddl; }
mark_plugin_fake_ddl(bool flag)4216 void mark_plugin_fake_ddl(bool flag) { m_is_plugin_fake_ddl = flag; }
4217
4218 private:
4219 /**
4220 Variable to mark if the object is part of a Srv_session object, which
4221 aggregates THD.
4222 */
4223 bool is_a_srv_session_thd;
4224
4225 /// Stores the plugin id it is attached to (if any).
4226 const st_plugin_int *m_plugin{nullptr};
4227
4228 /**
4229 Creating or dropping plugin native table through a plugin service.
4230 This variable enables the DDL command execution from
4231 dd::create_native_table() to be executed without committing the
4232 transaction.
4233 */
4234 bool m_is_plugin_fake_ddl;
4235
4236 #ifndef DBUG_OFF
4237 /**
4238 Sequential number of internal tmp table created in the statement. Useful for
4239 tracking tmp tables when number of them is involved in a query.
4240 */
4241 uint tmp_table_seq_id;
4242
4243 public:
4244 /*
4245 The member serves to guard against duplicate use of the same xid
4246 at binary logging.
4247 */
4248 XID debug_binlog_xid_last;
4249 #endif
4250 private:
4251 /*
4252 Flag set by my_write before waiting for disk space.
4253
4254 This is used by replication to decide if the I/O thread should be
4255 killed or not when stopping the replication threads.
4256
4257 In ordinary STOP SLAVE case, the I/O thread will wait for disk space
4258 or to be killed regardless of this flag value.
4259
4260 In server shutdown case, if this flag is true, the I/O thread will be
4261 signaled with KILL_CONNECTION to abort the waiting, letting the server
4262 to shutdown promptly.
4263 */
4264 bool waiting_for_disk_space = false;
4265
4266 public:
4267 /**
4268 Set the waiting_for_disk_space flag.
4269
4270 @param waiting The value to set in the flag.
4271 */
set_waiting_for_disk_space(bool waiting)4272 void set_waiting_for_disk_space(bool waiting) {
4273 waiting_for_disk_space = waiting;
4274 }
4275 /**
4276 Returns the current waiting_for_disk_space flag value.
4277 */
is_waiting_for_disk_space()4278 bool is_waiting_for_disk_space() const { return waiting_for_disk_space; }
4279
4280 bool sql_parser();
4281
4282 /// Enables or disables use of secondary storage engines in this session.
set_secondary_engine_optimization(Secondary_engine_optimization state)4283 void set_secondary_engine_optimization(Secondary_engine_optimization state) {
4284 m_secondary_engine_optimization = state;
4285 }
4286
4287 /**
4288 Can secondary storage engines be used for query execution in
4289 this session?
4290 */
secondary_engine_optimization()4291 Secondary_engine_optimization secondary_engine_optimization() const {
4292 return m_secondary_engine_optimization;
4293 }
4294
4295 /**
4296 Checks if queries in this session can use a secondary storage engine for
4297 execution. A secondary engine cannot be used if any of the following
4298 conditions is true:
4299
4300 - Secondary engines are disabled in the session
4301 - The user has disabled secondary engines
4302 - LOCK TABLES mode is active
4303 - Multi-statement transaction mode is active
4304 - It is a sub-statement of a stored procedure
4305
4306 @return true if secondary storage engines can be used in this
4307 session, or false otherwise
4308 */
4309 bool secondary_storage_engine_eligible() const;
4310
4311 private:
4312 /**
4313 This flag tells if a secondary storage engine can be used to
4314 execute a query in this session.
4315 */
4316 Secondary_engine_optimization m_secondary_engine_optimization =
4317 Secondary_engine_optimization::PRIMARY_ONLY;
4318
4319 void cleanup_after_parse_error();
4320 /**
4321 Flag that indicates if the user of current session has SYSTEM_USER privilege
4322 */
4323 std::atomic<bool> m_is_system_user;
4324
4325 public:
4326 bool is_system_user();
4327 void set_system_user(bool system_user_flag);
4328
4329 public:
4330 Transactional_ddl_context m_transactional_ddl{this};
4331 };
4332
4333 /**
4334 Return lock_tables_mode for secondary engine.
4335 @param cthd thread context
4336 @retval true if lock_tables_mode is on
4337 @retval false, otherwise
4338 */
secondary_engine_lock_tables_mode(const THD & cthd)4339 inline bool secondary_engine_lock_tables_mode(const THD &cthd) {
4340 return (cthd.locked_tables_mode == LTM_LOCK_TABLES ||
4341 cthd.locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES);
4342 }
4343
4344 /** A short cut for thd->get_stmt_da()->set_ok_status(). */
4345 void my_ok(THD *thd, ulonglong affected_rows = 0, ulonglong id = 0,
4346 const char *message = nullptr);
4347
4348 /** A short cut for thd->get_stmt_da()->set_eof_status(). */
4349 void my_eof(THD *thd);
4350
4351 bool add_item_to_list(THD *thd, Item *item);
4352
4353 /*************************************************************************/
4354
4355 /**
4356 The function re-attaches the engine ha_data (which was previously detached by
4357 detach_ha_data_from_thd) to THD.
4358 This is typically done to replication applier executing
4359 one of XA-PREPARE, XA-COMMIT ONE PHASE or rollback.
4360
4361 @param thd thread context
4362 @param hton pointer to handlerton
4363 */
4364
4365 void reattach_engine_ha_data_to_thd(THD *thd, const struct handlerton *hton);
4366
4367 /**
4368 Check if engine substitution is allowed in the current thread context.
4369
4370 @param thd thread context
4371 @retval true if engine substitution is allowed
4372 @retval false otherwise
4373 */
4374
is_engine_substitution_allowed(const THD * thd)4375 inline bool is_engine_substitution_allowed(const THD *thd) {
4376 return !(thd->variables.sql_mode & MODE_NO_ENGINE_SUBSTITUTION);
4377 }
4378
4379 /**
4380 Returns if the user of the session has the SYSTEM_USER privilege or not.
4381
4382 @retval true User has SYSTEM_USER privilege
4383 @retval false Otherwise
4384 */
is_system_user()4385 inline bool THD::is_system_user() {
4386 return m_is_system_user.load(std::memory_order_seq_cst);
4387 }
4388
4389 /**
4390 Sets the system_user flag atomically for the current session.
4391
4392 @param [in] system_user_flag boolean flag that indicates value to set.
4393 */
set_system_user(bool system_user_flag)4394 inline void THD::set_system_user(bool system_user_flag) {
4395 m_is_system_user.store(system_user_flag, std::memory_order_seq_cst);
4396 }
4397
4398 #endif /* SQL_CLASS_INCLUDED */
4399