MySQL 8.2.0
Source Code Documentation
sql_class.h
Go to the documentation of this file.
1/* Copyright (c) 2000, 2023, 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 <stack>
49#include <string>
50#include <unordered_map>
51
52#include "dur_prop.h" // durability_properties
53#include "lex_string.h"
54#include "map_helpers.h"
55#include "my_alloc.h"
56#include "my_base.h"
57#include "my_command.h"
58#include "my_compiler.h"
59#include "my_dbug.h"
60#include "my_inttypes.h"
61#include "my_io.h"
62#include "my_psi_config.h"
63#include "my_sqlcommand.h"
64#include "my_sys.h"
65#include "my_table_map.h"
66#include "my_thread_local.h"
67#include "my_time_t.h"
77#include "mysql/plugin_audit.h"
82#include "mysql/thread_type.h"
83#include "mysql_com_server.h" // NET_SERVER
84#include "mysqld_error.h"
85#include "pfs_thread_provider.h"
86#include "prealloced_array.h"
87#include "sql/auth/sql_security_ctx.h" // Security_context
88#include "sql/current_thd.h"
89#include "sql/dd/string_type.h" // dd::string_type
90#include "sql/discrete_interval.h" // Discrete_interval
91#include "sql/locked_tables_list.h" // enum_locked_tables_mode
92#include "sql/mdl.h"
93#include "sql/opt_costmodel.h"
94#include "sql/opt_trace_context.h" // Opt_trace_context
95#include "sql/parse_location.h"
96#include "sql/psi_memory_key.h"
97#include "sql/query_options.h"
100#include "sql/rpl_context.h" // Rpl_thd_context
101#include "sql/rpl_gtid.h"
102#include "sql/session_tracker.h" // Session_tracker
103#include "sql/sql_audit.h"
104#include "sql/sql_connect.h"
105#include "sql/sql_const.h"
106#include "sql/sql_digest_stream.h" // sql_digest_state
107#include "sql/sql_error.h"
108#include "sql/sql_list.h"
109#include "sql/sql_plugin_ref.h"
110#include "sql/sys_vars_resource_mgr.h" // Session_sysvar_resource_manager
111#include "sql/system_variables.h" // system_variables
112#include "sql/transaction_info.h" // Ha_trx_info
113#include "sql/xa.h"
115#include "sql_string.h"
116#include "template_utils.h"
117#include "thr_lock.h"
118#include "violite.h"
119
120enum enum_check_fields : int;
121enum enum_tx_isolation : int;
122enum ha_notification_type : int;
123class Item;
124class Parser_state;
125class PROFILING;
127class Relay_log_info;
128class THD;
129class partition_info;
130class Protocol;
131class Protocol_binary;
132class Protocol_classic;
133class Protocol_text;
134template <class T>
135class mem_root_deque;
136class sp_rcontext;
137class user_var_entry;
138struct LEX;
139struct LEX_USER;
140struct TABLE;
141class Table_ref;
142struct timeval;
143struct User_level_lock;
144
145namespace dd {
146namespace cache {
147class Dictionary_client;
148}
149
150class DD_kill_immunizer;
151} // namespace dd
152
155class Query_result;
157class Rows_log_event;
158class Time_zone;
159class sp_cache;
161struct LOG_INFO;
162
163typedef struct user_conn USER_CONN;
164struct MYSQL_LOCK;
165
166extern "C" void thd_enter_cond(void *opaque_thd, mysql_cond_t *cond,
167 mysql_mutex_t *mutex,
168 const PSI_stage_info *stage,
169 PSI_stage_info *old_stage,
170 const char *src_function, const char *src_file,
171 int src_line);
172extern "C" void thd_exit_cond(void *opaque_thd, const PSI_stage_info *stage,
173 const char *src_function, const char *src_file,
174 int src_line);
175
176extern "C" void thd_enter_stage(void *opaque_thd,
177 const PSI_stage_info *new_stage,
178 PSI_stage_info *old_stage,
179 const char *src_function, const char *src_file,
180 int src_line);
181
182extern "C" void thd_set_waiting_for_disk_space(void *opaque_thd,
183 const bool waiting);
184
185#define THD_STAGE_INFO(thd, stage) \
186 (thd)->enter_stage(&stage, NULL, __func__, __FILE__, __LINE__)
187
188extern char empty_c_string[1];
189
190/*
191 We preallocate data for several storage engine plugins.
192 so: innodb + bdb + ndb + binlog + myisam + myisammrg + archive +
193 example + csv + heap + blackhole + federated + 0
194 (yes, the sum is deliberately inaccurate)
195*/
196constexpr size_t PREALLOC_NUM_HA = 15;
197
198#ifndef NDEBUG
199// Used to sample certain debug flags when a query is read but before the reply
200// is sent.
201enum class TDM { ANY, ON, ZERO, NOT_AVAILABLE };
203#endif /* not defined NDEBUG */
204
205/**
206 To be used for pool-of-threads (implemented differently on various OSs)
207*/
209 public:
210 void *data; /* scheduler-specific data structure */
211
213
214 ~thd_scheduler() = default;
215};
216
218void thd_set_psi(THD *thd, PSI_thread *psi);
219
220/**
221 Return @@session.terminology_use_previous for the current THD.
222
223 @return the integer value of one of the enumeration values in
224 terminology_use_previous::enum_compatibility_version.
225*/
226extern "C" unsigned int thd_get_current_thd_terminology_use_previous();
227
229 /**
230 Memory counter object doesn't update global memory counter and doesn't throw
231 OOM error.
232 */
234 /**
235 if MEM_CNT_UPDATE_GLOBAL_COUNTER is set, memory counter object updates
236 global memory counter.
237 */
239 /**
240 if MEM_CNT_GENERATE_ERROR is set, memory counter object generates OOM error if
241 any.
242*/
244 /**
245 if MEM_CNT_GENERATE_LOG_ERROR is set, memory counter object generates OOM
246 error to error log if any.
247*/
250
252 private:
253 bool m_enabled{false};
254 THD *m_thd{nullptr}; // Pointer to THD object.
255 Diagnostics_area m_da{false}; // Diagnostics area.
256 ulonglong mem_counter{0}; // Amount of memory consumed by thread.
257 ulonglong max_conn_mem{0}; // Max amount memory consumed by thread.
258 ulonglong glob_mem_counter{0}; // Amount of memory added to global
259 // memory counter.
260 uint curr_mode{MEM_CNT_DEFAULT}; // Current memory counter mode.
261 uint orig_mode{MEM_CNT_DEFAULT}; // Original memory counter mode
262 // (sets at init_mode() stage).
263 bool is_connection_stage{true}; // True on connection stage,
264 // resets to false after successful
265 // connection.
266 public:
269 assert(!m_enabled);
270 assert(glob_mem_counter == 0);
271 }
272 void set_thd(THD *thd) { m_thd = thd; }
273 void enable() { m_enabled = true; }
274 void disable();
275
276 void alloc_cnt(size_t size);
277 void free_cnt(size_t size);
278 int reset();
279 void flush();
280 /**
281 Restore original memory counter mode.
282 */
284 /**
285 Set NO ERROR memory counter mode.
286 */
289 }
290 /**
291 Function sets current memory counter mode.
292
293 @param mode_arg current memory counter mode.
294 */
295 void set_curr_mode(uint mode_arg) { curr_mode = mode_arg; }
296 /**
297 Function sets original memory counter mode.
298
299 @param mode_arg original memory counter mode.
300 */
301 void set_orig_mode(uint mode_arg) { orig_mode = mode_arg; }
302 /**
303 Check if memory counter error is issued.
304
305 @retval true if memory counter error is issued, false otherwise.
306 */
307 bool is_error() const { return m_da.is_error(); }
308 void set_thd_error_status() const;
309
310 private:
311 int generate_error(int err_no, ulonglong mem_limit, ulonglong mem_size);
312 /**
313 Check if memory counter is in error mode.
314
315 @retval true if memory counter is in error mode, false otherwise.
316 */
317 bool is_error_mode() const { return (curr_mode & MEM_CNT_GENERATE_ERROR); }
318 /**
319 Check if memory counter is in error log mode.
320
321 @retval true if memory counter is in error log mode, false otherwise.
322 */
323 bool is_error_log_mode() const {
325 }
326};
327
328/**
329 the struct aggregates two parameters that identify an event
330 uniquely in scope of communication of a particular master and slave couple.
331 I.e there can not be 2 events from the same staying connected master which
332 have the same coordinates.
333 @note
334 Such identifier is not yet unique generally as the event originating master
335 is resettable. Also the crashed master can be replaced with some other.
336*/
337typedef struct rpl_event_coordinates {
338 char *file_name; // binlog file name (directories stripped)
339 my_off_t pos; // event's position in the binlog file
341
342#define THD_SENTRY_MAGIC 0xfeedd1ff
343#define THD_SENTRY_GONE 0xdeadbeef
344
345#define THD_CHECK_SENTRY(thd) assert(thd->dbug_sentry == THD_SENTRY_MAGIC)
346
348 private:
349 /*
350 List of items created for this query. Every item adds itself to the list
351 on creation (see Item::Item() for details)
352 */
354
355 public:
356 MEM_ROOT *mem_root; // Pointer to current memroot
357 /// To check whether a reprepare operation is active
358 bool is_repreparing{false};
359 /*
360 The states reflects three different life cycles for three
361 different types of statements:
362 Prepared statement: STMT_INITIALIZED -> STMT_PREPARED -> STMT_EXECUTED.
363 Stored procedure: STMT_INITIALIZED_FOR_SP -> STMT_EXECUTED.
364 Other statements: STMT_REGULAR_EXECUTION never changes.
365 */
372 STMT_ERROR = -1
373 };
374
375 /*
376 State and state changes in SP:
377 1) When state is STMT_INITIALIZED_FOR_SP, objects in the item tree are
378 created on the statement memroot. This is enforced through
379 ps_arena_holder checking the state.
380 2) After the first execute (call p1()), this state should change to
381 STMT_EXECUTED. Objects will be created on the execution memroot and will
382 be destroyed at the end of each execution.
383 3) In case an ER_NEED_REPREPARE error occurs, state should be changed to
384 STMT_INITIALIZED_FOR_SP and objects will again be created on the
385 statement memroot. At the end of this execution, state should change to
386 STMT_EXECUTED.
387 */
388 private:
390
391 public:
392 Query_arena(MEM_ROOT *mem_root_arg, enum enum_state state_arg)
393 : m_item_list(nullptr), mem_root(mem_root_arg), state(state_arg) {}
394
395 /*
396 This constructor is used only when Query_arena is created as
397 backup storage for another instance of Query_arena.
398 */
401
402 virtual ~Query_arena() = default;
403
404 Item *item_list() const { return m_item_list; }
405 void reset_item_list() { m_item_list = nullptr; }
406 void set_item_list(Item *item) { m_item_list = item; }
407 void add_item(Item *item);
408 void free_items();
409 void set_state(enum_state state_arg) { state = state_arg; }
410 enum_state get_state() const { return state; }
411 bool is_stmt_prepare() const { return state == STMT_INITIALIZED; }
413 return (int)state < (int)STMT_PREPARED;
414 }
416 return (int)state <= (int)STMT_PREPARED;
417 }
418 /// @returns true if a regular statement, ie not prepared and not stored proc
419 bool is_regular() const { return state == STMT_REGULAR_EXECUTION; }
420
421 void *alloc(size_t size) { return mem_root->Alloc(size); }
422 void *mem_calloc(size_t size) {
423 void *ptr;
424 if ((ptr = mem_root->Alloc(size))) memset(ptr, 0, size);
425 return ptr;
426 }
427 template <typename T>
429 void *m = alloc(sizeof(T));
430 return m == nullptr ? nullptr : new (m) T;
431 }
432 template <typename T>
433 T *memdup_typed(const T *mem) {
434 return static_cast<T *>(memdup_root(mem_root, mem, sizeof(T)));
435 }
436 char *mem_strdup(const char *str) { return strdup_root(mem_root, str); }
437 char *strmake(const char *str, size_t size) const {
438 return strmake_root(mem_root, str, size);
439 }
441 LEX_CSTRING ret;
442 ret.str = strmake(str.str, str.length);
443 ret.length = ret.str ? str.length : 0;
444 return ret;
445 }
446 void *memdup(const void *str, size_t size) {
447 return memdup_root(mem_root, str, size);
448 }
449
450 /**
451 Copies memory-managing members from `set`. No references are kept to it.
452
453 @param set A Query_arena from which members are copied.
454 */
455 void set_query_arena(const Query_arena &set);
456
457 /**
458 Copy the current arena to `backup` and set the current
459 arena to match `source`
460
461 @param source A Query_arena from which members are copied.
462 @param backup A Query_arena to which members are first saved.
463 */
465};
466
468
469/**
470 Container for all prepared statements created/used in a connection.
471
472 Prepared statements in Prepared_statement_map have unique id
473 (guaranteed by id assignment in Prepared_statement::Prepared_statement).
474
475 Non-empty statement names are unique too: attempt to insert a new statement
476 with duplicate name causes older statement to be deleted.
477
478 Prepared statements are auto-deleted when they are removed from the map
479 and when the map is deleted.
480*/
481
483 public:
485
486 /**
487 Insert a new statement to the thread-local prepared statement map.
488
489 If there was an old statement with the same name, replace it with the
490 new one. Otherwise, check if max_prepared_stmt_count is not reached yet,
491 increase prepared_stmt_count, and insert the new statement. It's okay
492 to delete an old statement and fail to insert the new one.
493
494 All named prepared statements are also present in names_hash.
495 Prepared statement names in names_hash are unique.
496 The statement is added only if prepared_stmt_count < max_prepard_stmt_count
497 m_last_found_statement always points to a valid statement or is 0
498
499 @retval 0 success
500 @retval 1 error: out of resources or max_prepared_stmt_count limit has been
501 reached. An error is sent to the client, the statement
502 is deleted.
503 */
505
506 /** Find prepared statement by name. */
508
509 /** Find prepared statement by ID. */
510 Prepared_statement *find(ulong id);
511
512 /** Erase all prepared statements (calls Prepared_statement destructor). */
514
515 void claim_memory_ownership(bool claim);
516
517 void reset();
518
520
521 private:
525};
526
527/**
528 A registry for item tree transformations performed during
529 query optimization. We register only those changes which require
530 a rollback to re-execute a prepared statement or stored procedure
531 yet another time.
532*/
533
534class Item_change_record : public ilink<Item_change_record> {
535 private:
536 // not used
538
539 public:
545 bool m_cancel{false};
546};
547
549
550/**
551 Class that holds information about tables which were opened and locked
552 by the thread. It is also used to save/restore this information in
553 push_open_tables_state()/pop_open_tables_state().
554*/
555
557 private:
558 /**
559 A stack of Reprepare_observer-instances. The top most instance is the
560 currently active one. This stack is used during execution of prepared
561 statements and stored programs in order to detect metadata changes.
562 The locking subsystem reports a metadata change if the top-most item is not
563 NULL.
564
565 When Open_tables_state part of THD is reset to open a system or
566 INFORMATION_SCHEMA table, NULL is temporarily pushed to avoid spurious
567 ER_NEED_REPREPARE errors -- system and INFORMATION_SCHEMA tables are not
568 subject to metadata version tracking.
569
570 A stack is used here for the convenience -- in some cases we need to
571 temporarily override/disable current Reprepare_observer-instance.
572
573 NOTE: This is not a list of observers, only the top-most element will be
574 notified in case of a metadata change.
575
576 @sa check_and_update_table_version()
577 */
579
580 public:
582 return m_reprepare_observers.size() > 0 ? m_reprepare_observers.back()
583 : nullptr;
584 }
585
587 m_reprepare_observers.push_back(o);
588 }
589
592 m_reprepare_observers.pop_back();
593 return retval;
594 }
595
597
598 public:
599 /**
600 List of regular tables in use by this thread. Contains persistent base
601 tables that were opened with @see open_tables().
602 */
604 /**
605 List of temporary tables used by this thread. Contains user-level
606 temporary tables, created with CREATE TEMPORARY TABLE, and
607 intermediate tables used in ALTER TABLE implementation.
608 */
610 /*
611 During a MySQL session, one can lock tables in two modes: automatic
612 or manual. In automatic mode all necessary tables are locked just before
613 statement execution, and all acquired locks are stored in 'lock'
614 member. Unlocking takes place automatically as well, when the
615 statement ends.
616 Manual mode comes into play when a user issues a 'LOCK TABLES'
617 statement. In this mode the user can only use the locked tables.
618 Trying to use any other tables will give an error.
619 The locked tables are also stored in this member, however,
620 thd->locked_tables_mode is turned on. Manual locking is described in
621 the 'LOCK_TABLES' chapter of the MySQL manual.
622 See also lock_tables() for details.
623 */
625
626 /*
627 CREATE-SELECT keeps an extra lock for the table being
628 created. This field is used to keep the extra lock available for
629 lower level routines, which would otherwise miss that lock.
630 */
632
633 /*
634 Enum enum_locked_tables_mode and locked_tables_mode member are
635 used to indicate whether the so-called "locked tables mode" is on,
636 and what kind of mode is active.
637
638 Locked tables mode is used when it's necessary to open and
639 lock many tables at once, for usage across multiple
640 (sub-)statements.
641 This may be necessary either for queries that use stored functions
642 and triggers, in which case the statements inside functions and
643 triggers may be executed many times, or for implementation of
644 LOCK TABLES, in which case the opened tables are reused by all
645 subsequent statements until a call to UNLOCK TABLES.
646
647 The kind of locked tables mode employed for stored functions and
648 triggers is also called "prelocked mode".
649 In this mode, first open_tables() call to open the tables used
650 in a statement analyses all functions used by the statement
651 and adds all indirectly used tables to the list of tables to
652 open and lock.
653 It also marks the parse tree of the statement as requiring
654 prelocking. After that, lock_tables() locks the entire list
655 of tables and changes THD::locked_tables_modeto LTM_PRELOCKED.
656 All statements executed inside functions or triggers
657 use the prelocked tables, instead of opening their own ones.
658 Prelocked mode is turned off automatically once close_thread_tables()
659 of the main statement is called.
660 */
662
664 BACKUPS_AVAIL = (1U << 0), /* There are backups available. */
665 SYSTEM_TABLES = (1U << 1) /* We are opening system tables. */
666 };
667
668 /*
669 Flags with information about the open tables state.
670 */
672 /**
673 This constructor initializes Open_tables_state instance which can only
674 be used as backup storage. To prepare Open_tables_state instance for
675 operations which open/lock/close tables (e.g. open_table()) one has to
676 call init_open_tables_state().
677 */
680
682
684};
685
686/**
687 Storage for backup of Open_tables_state. Must
688 be used only to open system tables (TABLE_CATEGORY_SYSTEM
689 and TABLE_CATEGORY_LOG).
690*/
691
693 public:
694 /**
695 When we backup the open tables state to open a system
696 table or tables, we want to save state of metadata
697 locks which were acquired before the backup. It is used
698 to release metadata locks on system tables after they are
699 no longer used.
700 */
702};
703
704/**
705 Enum that represents which phase of secondary engine optimization
706 the current statement is in.
707*/
709 /**
710 The current statement should only use tables from primary storage
711 engines. Use of secondary storage engines is disabled.
712 */
714
715 /**
716 The current statement should only use tables from the primary
717 storage engine. However, use of secondary storage engines is not
718 disabled, so the optimizer may choose to trigger a repreparation
719 against the secondary storage engine if it believes that use of a
720 secondary storage engine is beneficial.
721 */
723
724 /**
725 The current statement should use tables from a secondary storage
726 engine if possible. Otherwise, fall back to using tables from
727 primary storage engine only.
728 */
729 SECONDARY,
730};
731
732/**
733 @class Sub_statement_state
734 @brief Used to save context when executing a function or trigger
735*/
736
737/* Defines used for Sub_statement_state::in_sub_stmt */
738
739#define SUB_STMT_TRIGGER 1
740#define SUB_STMT_FUNCTION 2
741
743 public:
756};
757
758inline char const *show_system_thread(enum_thread_type thread) {
759#define RETURN_NAME_AS_STRING(NAME) \
760 case (NAME): \
761 return #NAME
762 switch (thread) {
763 static char buf[64];
778 default:
779 sprintf(buf, "<UNKNOWN SYSTEM THREAD: %d>", thread);
780 return buf;
781 }
782#undef RETURN_NAME_AS_STRING
783}
784
785/**
786 Storage engine specific thread local data.
787*/
788
789struct Ha_data {
790 /**
791 Storage engine specific thread local data.
792 Lifetime: one user connection.
793 */
794 void *ha_ptr;
795 /**
796 A memorizer to engine specific "native" transaction object to provide
797 storage engine detach-re-attach facility.
798 The server level transaction object can dissociate from storage engine
799 transactions. The released "native" transaction reference
800 can be hold in the member until it is reconciled later.
801 Lifetime: Depends on caller of @c hton::replace_native_transaction_in_thd.
802 For instance in the case of slave server applier handling XA transaction
803 it is from XA START to XA PREPARE.
804 */
806 /**
807 0: Life time: one statement within a transaction. If @@autocommit is
808 on, also represents the entire transaction.
809 @sa trans_register_ha()
810
811 1: Life time: one transaction within a connection.
812 If the storage engine does not participate in a transaction,
813 this should not be used.
814 @sa trans_register_ha()
815 */
817
818 /**
819 NULL: engine is not bound to this thread
820 non-NULL: engine is bound to this thread, engine shutdown forbidden
821 */
823
825};
826
827/**
828 An instance of the global read lock in a connection.
829 Implemented in lock.cc.
830*/
831
833 public:
838 };
839
841 : m_state(GRL_NONE),
844
845 bool lock_global_read_lock(THD *thd);
846 void unlock_global_read_lock(THD *thd);
847
848 /**
849 Used by innodb memcached server to check if any connections
850 have global read lock
851 */
853
854 /**
855 Check if this connection can acquire protection against GRL and
856 emit error if otherwise.
857 */
859 if (m_state) {
860 my_error(ER_CANT_UPDATE_WITH_READLOCK, MYF(0));
861 return true;
862 }
863 return false;
864 }
866 bool is_acquired() const { return m_state != GRL_NONE; }
868
869 private:
870 static std::atomic<int32> m_atomic_active_requests;
872 /**
873 In order to acquire the global read lock, the connection must
874 acquire shared metadata lock in GLOBAL namespace, to prohibit
875 all DDL.
876 */
878 /**
879 Also in order to acquire the global read lock, the connection
880 must acquire a shared metadata lock in COMMIT namespace, to
881 prohibit commits.
882 */
884};
885
886extern "C" void my_message_sql(uint error, const char *str, myf MyFlags);
887
888/**
889 This class keeps the context of transactional DDL statements. Currently only
890 CREATE TABLE with START TRANSACTION uses this context.
891*/
893 public:
894 explicit Transactional_ddl_context(THD *thd) : m_thd(thd) {
895 assert(m_thd != nullptr);
896 }
897
899 assert(!m_hton);
900 post_ddl();
901 }
902
903 void init(dd::String_type db, dd::String_type tablename,
904 const handlerton *hton);
905
906 bool inited() { return m_hton != nullptr; }
907
908 void rollback();
909
910 void post_ddl();
911
912 private:
913 // The current thread.
914 THD *m_thd{nullptr};
915
916 // Handlerton pointer to table's engine begin created.
917 const handlerton *m_hton{nullptr};
918
919 // Schema and table name being created.
922};
923
924struct PS_PARAM;
925
927 std::pair<Event_tracking_class, Event_tracking_information *>;
928using Event_tracking_data_stack = std::stack<Event_tracking_data>;
929
930/**
931 @class THD
932 For each client connection we create a separate thread with THD serving as
933 a thread/connection descriptor
934*/
935
936class THD : public MDL_context_owner,
937 public Query_arena,
938 public Open_tables_state {
939 public:
940 /**
941 Controlled memory stats for this session.
942 This member is the first in THD,
943 to initialize Thd_mem_cnt() before allocating more memory.
944 */
946
947 private:
948 bool is_stmt_prepare() const = delete;
951 inline bool is_regular() const = delete;
952
953 public:
955
956 /**
957 MARK_COLUMNS_NONE: Means mark_used_columns is not set and no indicator to
958 handler of fields used is set
959 MARK_COLUMNS_READ: Means a bit in read set is set to inform handler
960 that the field is to be read. Update covering_keys
961 and merge_keys too.
962 MARK_COLUMNS_WRITE: Means a bit is set in write set to inform handler
963 that it needs to update this field in write_row
964 and update_row.
965 MARK_COLUMNS_TEMP: Mark bit in read set, but ignore key sets.
966 Used by filesort().
967 */
969 /**
970 Used by Item::check_column_privileges() to tell which privileges
971 to check for.
972 Set to ~0ULL before starting to resolve a statement.
973 Set to desired privilege mask before calling a resolver function that will
974 call Item::check_column_privileges().
975 After use, restore previous value as current value.
976 */
978
979 private:
980 /**
981 The lex to hold the parsed tree of conventional (non-prepared) queries.
982 Whereas for prepared and stored procedure statements we use an own lex
983 instance for each new query, for conventional statements we reuse
984 the same lex. (@see dispatch_sql_command for details).
985 */
986 std::unique_ptr<LEX> main_lex;
987
988 public:
989 LEX *lex; // parse tree descriptor
990 dd::cache::Dictionary_client *dd_client() const // Get the dictionary client.
991 {
992 return m_dd_client.get();
993 }
994
995 private:
996 std::unique_ptr<dd::cache::Dictionary_client> m_dd_client;
997
998 /**
999 The query associated with this statement.
1000 */
1003 std::atomic<bool> m_safe_to_display;
1004
1005 /**
1006 Currently selected catalog.
1007 */
1008
1010 /**
1011 Name of the current (default) database.
1012
1013 If there is the current (default) database, "db" contains its name. If
1014 there is no current (default) database, "db" is NULL and "db_length" is
1015 0. In other words, "db", "db_length" must either be NULL, or contain a
1016 valid database name.
1017
1018 @note this attribute is set and allocated by the slave SQL thread (for
1019 the THD of that thread); that thread is (and must remain, for now) the
1020 only responsible for freeing this member.
1021 */
1023
1024 /**
1025 Resource group context indicating the current resource group
1026 and the name of the resource group to switch to during execution
1027 of a query.
1028 */
1030
1031 /**
1032 In some cases, we may want to modify the query (i.e. replace
1033 passwords with their hashes before logging the statement etc.).
1034
1035 In case the query was rewritten, the original query will live in
1036 m_query_string, while the rewritten query lives in rewritten_query.
1037 If rewritten_query is empty, m_query_string should be logged.
1038 If rewritten_query is non-empty, the rewritten query it contains
1039 should be used in logs (general log, slow query log, binary log).
1040
1041 Currently, password obfuscation is the only rewriting we do; more
1042 may follow at a later date, both pre- and post parsing of the query.
1043 Rewriting of binloggable statements must preserve all pertinent
1044 information.
1045
1046 Similar restrictions as for m_query_string (see there) hold for locking:
1047 - Value may only be (re)set from owning thread (current_thd)
1048 - Value must be modified using (reset|swap)_rewritten_query().
1049 Doing so will protect the update with LOCK_thd_query.
1050 - The owner (current_thd) may read the value without holding the lock.
1051 - Other threads may read the value, but must hold LOCK_thd_query to do so.
1052 */
1054
1055 public:
1056 /* Used to execute base64 coded binlog events in MySQL server */
1058 /* Slave applier execution context */
1060
1061 /* Is transaction commit still pending */
1063
1064 /**
1065 The function checks whether the thread is processing queries from binlog,
1066 as automatically generated by mysqlbinlog.
1067
1068 @return true when the thread is a binlog applier
1069 */
1070 bool is_binlog_applier() const {
1071 return rli_fake && variables.pseudo_replica_mode;
1072 }
1073
1074 /**
1075 When the thread is a binlog or slave applier it detaches the engine
1076 ha_data associated with it and memorizes the fact of that.
1077 */
1079
1080 /**
1081 When the thread is a binlog or slave applier it reattaches the engine
1082 ha_data associated with it and memorizes the fact of that.
1083 */
1085
1086 /**
1087 @return true when the current binlog (rli_fake) or slave (rli_slave)
1088 applier thread has detached the engine ha_data,
1089 see @c rpl_detach_engine_ha_data.
1090 @note The detached transaction applier resets a memo
1091 mark at once with this check.
1092 */
1093 bool is_engine_ha_data_detached() const;
1094
1096 /*
1097 Constant for THD::where initialization in the beginning of every query.
1098
1099 It's needed because we do not save/restore THD::where normally during
1100 primary (non subselect) query execution.
1101 */
1102 static const char *const DEFAULT_WHERE;
1103
1104 /** Additional network instrumentation for the server only. */
1106 /**
1107 Hash for user variables.
1108 User variables are per session,
1109 but can also be monitored outside of the session,
1110 so a lock is needed to prevent race conditions.
1111 Protected by @c LOCK_thd_data.
1112 */
1115 struct rand_struct rand; // used for authentication
1116 struct System_variables variables; // Changeable local variables
1117 struct System_status_var status_var; // Per thread statistic vars
1118 struct System_status_var
1119 *copy_status_var_ptr; // A copy of the statistic vars asof the start of
1120 // the query
1121 struct System_status_var *initial_status_var; /* used by show status */
1122 // has status_var already been added to global_status_var?
1124
1125 /**
1126 Session's connection attributes for the connected client
1127 */
1128 std::vector<char> m_connection_attributes;
1129
1130 /**
1131 Current query cost.
1132 @sa system_status_var::last_query_cost
1133 */
1135 /**
1136 Current query partial plans.
1137 @sa system_status_var::last_query_partial_plans
1138 */
1140
1141 /**
1142 Clear the query costs attributes for the current query.
1143 */
1147 }
1148
1149 /**
1150 Save the current query costs attributes in
1151 the thread session status.
1152 Use this method only after the query execution is completed,
1153 so that
1154 @code SHOW SESSION STATUS like 'last_query_%' @endcode
1155 @code SELECT * from performance_schema.session_status
1156 WHERE VARIABLE_NAME like 'last_query_%' @endcode
1157 actually reports the previous query, not itself.
1158 */
1160 assert(!status_var_aggregated);
1163 }
1164
1165 /**
1166 Clear copy of the status variables.
1167 */
1169
1170 /**
1171 Copy status variables into a structure pointed by the specified pointer and
1172 keep track of the pointer internally.
1173
1174 @param dst_var status variable structure pointer, where internal status
1175 variables are copied into.
1176 */
1178 *dst_var = status_var;
1179 copy_status_var_ptr = dst_var;
1180 }
1181
1182 /**
1183 Copy status variables into a structure pointed by the specified pointer
1184 passed into copy_status_var method call.
1185 */
1187 if (copy_status_var_ptr) {
1188 /* Reset for values at start of next statement */
1190 }
1191 }
1192
1193 THR_LOCK_INFO lock_info; // Locking info of this thread
1194 /**
1195 Protects THD data accessed from other threads.
1196 The attributes protected are:
1197 - thd->is_killable (used by KILL statement and shutdown).
1198 - thd->user_vars (user variables, inspected by monitoring)
1199 Is locked when THD is deleted.
1200 */
1202
1203 /**
1204 Protects THD::m_query_string. No other mutexes should be locked
1205 while having this mutex locked.
1206 */
1208
1209 /**
1210 Protects THD::variables while being updated. This should be taken inside
1211 of LOCK_thd_data and outside of LOCK_global_system_variables.
1212 */
1214
1215#ifndef NDEBUG
1217#endif
1218
1219 /**
1220 Protects THD::m_protocol when it gets removed in x plugin.
1221 */
1223
1224 /**
1225 Protects THD::m_security_ctx from inspection (e.g. by old-style
1226 SHOW PROCESSLIST) while COM_CHANGE_USER changes the context.
1227 */
1229
1230 /**
1231 Protects query plan (SELECT/UPDATE/DELETE's) from being freed/changed
1232 while another thread explains it. Following structures are protected by
1233 this mutex:
1234 THD::Query_plan
1235 Modification_plan
1236 Query_block::join
1237 JOIN::plan_state
1238 Tree of Query_expression after THD::Query_plan was set till
1239 THD::Query_plan cleanup
1240 JOIN_TAB::select->quick
1241 Code that changes objects above should take this mutex.
1242 Explain code takes this mutex to block changes to named structures to
1243 avoid crashes in following functions:
1244 explain_single_table_modification
1245 explain_query
1246 Sql_cmd_explain_other_thread::execute
1247 When doing EXPLAIN CONNECTION:
1248 all explain code assumes that this mutex is already taken.
1249 When doing ordinary EXPLAIN:
1250 the mutex does need to be taken (no need to protect reading my own data,
1251 moreover EXPLAIN CONNECTION can't run on an ordinary EXPLAIN).
1252 */
1253 private:
1255
1256 public:
1257 /// Locks the query plan of this THD
1260
1261 /** All prepared statements of this connection. */
1263 /*
1264 A pointer to the stack frame of handle_one_connection(),
1265 which is called first in the thread for handling a client
1266 */
1267 const char *thread_stack;
1268
1269 /**
1270 @note
1271 Some members of THD (currently 'Statement::db',
1272 'catalog' and 'query') are set and allocated by the slave SQL thread
1273 (for the THD of that thread); that thread is (and must remain, for now)
1274 the only responsible for freeing these 3 members. If you add members
1275 here, and you add code to set them in replication, don't forget to
1276 free_them_and_set_them_to_0 in replication properly. For details see
1277 the 'err:' label of the handle_slave_sql() in sql/slave.cc.
1278
1279 @see handle_slave_sql
1280 */
1281
1284
1288
1289 /**
1290 @note
1291 The optional password validation plugin doesn't have any API for
1292 temporally disable its functionality for a particular session.
1293 To get around this issue we introduce a boolean variable in the THD
1294 which we check before each call to the password validation plugin.
1295 Password validation is invoked from within the authentication plugin
1296 in the generate_authentication_string() method.
1297
1298 @see generate_authentication_string
1299 */
1301
1302 std::unique_ptr<Protocol_text> protocol_text; // Normal protocol
1303 std::unique_ptr<Protocol_binary> protocol_binary; // Binary protocol
1304
1305 const Protocol *get_protocol() const { return m_protocol; }
1306
1308
1310#ifndef NDEBUG
1311 if (current_thd != this) {
1312 /*
1313 When inspecting this thread from monitoring,
1314 the monitoring thread MUST lock LOCK_thd_data,
1315 to be allowed to safely inspect SSL status variables.
1316 */
1318 }
1319#endif
1320 return m_SSL;
1321 }
1322
1323 /**
1324 Asserts that the protocol is of type text or binary and then
1325 returns the m_protocol casted to Protocol_classic. This method
1326 is needed to prevent misuse of pluggable protocols by legacy code
1327 */
1329 assert(is_classic_protocol());
1330 return pointer_cast<const Protocol_classic *>(m_protocol);
1331 }
1332
1334 assert(is_classic_protocol());
1335 return pointer_cast<Protocol_classic *>(m_protocol);
1336 }
1337
1338 private:
1339 Protocol *m_protocol; // Current protocol
1340 /**
1341 SSL data attached to this connection.
1342 This is an opaque pointer,
1343 When building with SSL, this pointer is non NULL
1344 only if the connection is using SSL.
1345 When building without SSL, this pointer is always NULL.
1346 The SSL data can be inspected to read per thread
1347 status variables,
1348 and this can be inspected while the thread is running.
1349 */
1350 SSL_handle m_SSL = {nullptr};
1351
1352 public:
1353 /**
1354 Query plan for EXPLAINable commands, should be locked with
1355 LOCK_query_plan before using.
1356 */
1358 private:
1359 THD *const thd;
1360 /// Original sql_command;
1362 /// LEX of topmost statement
1364 /// Query plan for UPDATE/DELETE/INSERT/REPLACE
1366 /// True if query is run in prepared statement
1367 bool is_ps;
1368
1369 explicit Query_plan(const Query_plan &); ///< not defined
1370 Query_plan &operator=(const Query_plan &); ///< not defined
1371
1372 public:
1373 /// Asserts that current_thd has locked this plan, if it does not own it.
1375#ifdef NDEBUG
1376 {
1377 }
1378#else
1379 ;
1380#endif
1381
1382 explicit Query_plan(THD *thd_arg)
1383 : thd(thd_arg),
1385 lex(nullptr),
1387 is_ps(false) {}
1388
1389 /**
1390 Set query plan.
1391
1392 @note This function takes THD::LOCK_query_plan mutex.
1393 */
1394 void set_query_plan(enum_sql_command sql_cmd, LEX *lex_arg, bool ps);
1395
1396 /*
1397 The 4 getters below expect THD::LOCK_query_plan to be already taken
1398 if called from another thread.
1399 */
1402 return sql_command;
1403 }
1404 LEX *get_lex() const {
1406 return lex;
1407 }
1410 return modification_plan;
1411 }
1412 bool is_ps_query() const {
1414 return is_ps;
1415 }
1416 bool is_single_table_plan() const;
1418
1420
1421 const LEX_CSTRING &catalog() const { return m_catalog; }
1422
1424
1425 private:
1427
1428 /*
1429 Points to info-string that we show in SHOW PROCESSLIST
1430 You are supposed to update thd->proc_info only if you have coded
1431 a time-consuming piece that MySQL can get stuck in for a long time.
1432
1433 Set it using the thd_proc_info(THD *thread, const char *message)
1434 macro/function.
1435
1436 This member is accessed and assigned without any synchronization.
1437 Therefore, it may point only to constant (statically
1438 allocated) strings, which memory won't go away over time.
1439 */
1440 const char *m_proc_info;
1441 /**
1442 Return the m_proc_info, possibly using the string of an older
1443 server release, according to @@terminology_use_previous.
1444
1445 @param sysvars Use the value of
1446 @@terminology_use_previous stored in this
1447 System_variables object.
1448
1449 @return The "proc_info", also known as "stage", of this thread.
1450 */
1451 const char *proc_info(const System_variables &sysvars) const;
1452
1453 public:
1454 // See comment in THD::enter_cond about why SUPPRESS_TSAN is needed.
1455 void enter_stage(const PSI_stage_info *stage, PSI_stage_info *old_stage,
1456 const char *calling_func, const char *calling_file,
1457 const unsigned int calling_line) SUPPRESS_TSAN;
1458 const char *proc_info() const { return m_proc_info; }
1459 /**
1460 Return the m_proc_info, possibly using the string of an older
1461 server release, according to
1462 @@session.terminology_use_previous.
1463
1464 @param invoking_thd Use
1465 @@session.terminology_use_previous of this session.
1466
1467 @return The "proc_info", also known as "stage", of this thread.
1468 */
1469 const char *proc_info_session(THD *invoking_thd) const {
1470 return proc_info(invoking_thd->variables);
1471 }
1474
1475 /*
1476 Used in error messages to tell user in what part of MySQL we found an
1477 error. E. g. when where= "having clause", if fix_fields() fails, user
1478 will know that the error was in having clause.
1479 */
1480 const char *where;
1481
1483
1487 /*
1488 A thread can hold named user-level locks. This variable
1489 contains granted tickets if a lock is present. See item_func.cc and
1490 chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK.
1491 */
1494#ifndef NDEBUG
1495 uint dbug_sentry; // watch out for memory corruption
1496#endif
1498 /**
1499 Mutex protecting access to current_mutex and current_cond.
1500 */
1502 /**
1503 The mutex used with current_cond.
1504 @see current_cond
1505 */
1506 std::atomic<mysql_mutex_t *> current_mutex;
1507 /**
1508 Pointer to the condition variable the thread owning this THD
1509 is currently waiting for. If the thread is not waiting, the
1510 value is NULL. Set by THD::enter_cond().
1511
1512 If this thread is killed (shutdown or KILL stmt), another
1513 thread will broadcast on this condition variable so that the
1514 thread can be unstuck.
1515 */
1516 std::atomic<mysql_cond_t *> current_cond;
1517 /**
1518 Condition variable used for waiting by the THR_LOCK.c subsystem.
1519 */
1521
1522 /// @brief Enables ordering in ha_commit_low. Used in binlog::commit
1523 /// @note Additional requirements need to be met
1524 /// in order to invoke commit ordering in ha_commit_low
1525 /// @see is_ha_commit_low_invoking_commit_order
1527
1528 /// @brief Enables ordering in ha_commit_low. Used in binlog::commit
1529 /// @note Additional requirements need to be met
1530 /// in order to invoke commit ordering in ha_commit_low
1531 /// @see is_ha_commit_low_invoking_commit_order
1533
1534 /// @brief Obtains flag indicating whether additional ordering in the
1535 /// ha_commit_low function is enabled. If not, ordering will take place in
1536 /// binlog::commit
1537 /// @details Accessor for the m_is_low_level_commit_ordering_enabled
1538 /// @return When true, ha_commit_low may order this transaction
1540
1541 private:
1542 /// @brief Flag indicating whether additional ordering in the ha_commit_low
1543 /// function is enabled. If disabled, ordering will take place in
1544 /// binlog::commit. It is set up in binlog::commit
1546
1547 /**
1548 Type of current query: COM_STMT_PREPARE, COM_QUERY, etc.
1549 Set from first byte of the packet in do_command()
1550 */
1552
1553 private:
1555
1556 public:
1557 void set_admin_connection(bool admin) { m_is_admin_conn = admin; }
1558 bool is_admin_connection() const { return m_is_admin_conn; }
1559
1562 uint32 file_id; // for LOAD DATA INFILE
1563 /* remote (peer) port */
1565 struct timeval start_time;
1566 struct timeval user_time;
1567 /**
1568 Query start time, expressed in microseconds.
1569 */
1571
1572 private:
1573 /**
1574 Time spent waiting for TABLE locks and DATA locks.
1575 Expressed in microseconds.
1576 */
1578
1579 public:
1581 void inc_lock_usec(ulonglong usec);
1583 top = m_lock_usec;
1584 m_lock_usec = 0;
1585 }
1587
1588 /**
1589 Type of lock to be used for all DML statements, except INSERT, in cases
1590 when lock is not specified explicitly. Set to TL_WRITE or
1591 TL_WRITE_LOW_PRIORITY depending on whether low_priority_updates option is
1592 off or on.
1593 */
1595 /**
1596 Type of lock to be used for INSERT statement if lock is not specified
1597 explicitly. Set to TL_WRITE_CONCURRENT_INSERT or TL_WRITE_LOW_PRIORITY
1598 depending on whether low_priority_updates option is off or on.
1599 */
1601
1602 /* <> 0 if we are inside of trigger or stored function. */
1604
1605 /**
1606 Used by fill_status() to avoid acquiring LOCK_status mutex twice
1607 when this function is called recursively (e.g. queries
1608 that contains SELECT on I_S.GLOBAL_STATUS with subquery on the
1609 same I_S table).
1610 Incremented each time fill_status() function is entered and
1611 decremented each time before it returns from the function.
1612 */
1615
1616 private:
1617 /* container for handler's private per-connection data */
1619
1620 public:
1621 /**
1622 Retrieve Ha_data for a given slot. Each handler has a fixed slot nr.
1623 */
1624 Ha_data *get_ha_data(int slot) { return &ha_data[slot]; }
1625
1626 /**
1627 Copy ha_data into the provided argument. Used by Attachble_transaction.
1628 */
1630 /*
1631 Protect with LOCK_thd_data avoid accessing ha_data while it
1632 is being modified.
1633 */
1634 mysql_mutex_lock(&this->LOCK_thd_data);
1635 *backup = ha_data;
1636 mysql_mutex_unlock(&this->LOCK_thd_data);
1637 }
1638
1639 /**
1640 Restore ha_data from the provided backup copy.
1641 Used by Attachable_Transaction.
1642 */
1645 /*
1646 Protect with LOCK_thd_data to avoid e.g. KILL CONNECTION
1647 reading ha_data while it is being modified.
1648 */
1649 mysql_mutex_lock(&this->LOCK_thd_data);
1650 ha_data = backup;
1651 mysql_mutex_unlock(&this->LOCK_thd_data);
1652 }
1653
1654 /*
1655 Position of first event in Binlog
1656 *after* last event written by this
1657 thread.
1658 */
1660 void set_next_event_pos(const char *_filename, ulonglong _pos);
1661 void clear_next_event_pos();
1662
1663 /*
1664 Ptr to row event extra data to be written to Binlog /
1665 received from Binlog.
1666
1667 */
1669
1671
1672 /*
1673 Public interface to write RBR events to the binlog
1674 */
1675 int binlog_write_table_map(TABLE *table, bool is_transactional,
1676 bool binlog_rows_query);
1677 int binlog_write_row(TABLE *table, bool is_transactional,
1678 const uchar *new_data,
1679 const unsigned char *extra_row_info);
1680 int binlog_delete_row(TABLE *table, bool is_transactional,
1681 const uchar *old_data,
1682 const unsigned char *extra_row_info);
1683 int binlog_update_row(TABLE *table, bool is_transactional,
1684 const uchar *old_data, const uchar *new_data,
1685 const uchar *extra_row_info);
1686 void set_server_id(uint32 sid) { server_id = sid; }
1687
1688 /*
1689 Member functions to handle pending event for row-level logging.
1690 */
1691 template <class RowsEventT>
1693 TABLE *table, uint32 serv_id, size_t needed, bool is_transactional,
1694 const unsigned char *extra_row_info, uint32 source_part_id = INT_MAX);
1695 Rows_log_event *binlog_get_pending_rows_event(bool is_transactional) const;
1696 inline int binlog_flush_pending_rows_event(bool stmt_end) {
1697 return (binlog_flush_pending_rows_event(stmt_end, false) ||
1698 binlog_flush_pending_rows_event(stmt_end, true));
1699 }
1700 int binlog_flush_pending_rows_event(bool stmt_end, bool is_transactional);
1701
1702 /**
1703 Determine the binlog format of the current statement.
1704
1705 @retval 0 if the current statement will be logged in statement
1706 format.
1707 @retval nonzero if the current statement will be logged in row
1708 format.
1709 */
1714 }
1715
1716 /**
1717 Determine if binlogging is currently disabled for this session.
1718
1719 There are two ways that binlogging can be disabled:
1720
1721 1. The binary log file is closed (globally). This can happen for
1722 two reasons: either --skip-log-bin was used on the command line,
1723 or a binlog write error happened when binlog_error_action=IGNORE_ERROR.
1724
1725 2. The binary log is disabled on session level. This can happen for
1726 two reasons: either the user has set @@session.sql_log_bin = 0,
1727 or the server code has internally disabled the binary log (by
1728 either setting thd->variables.option_bits &= ~OPTION_BIN_LOG or
1729 creating a Disable_binlog_guard object).
1730
1731 Even if this function returns true and the binary log is disabled,
1732 it is possible that the statement will be written to the binary log,
1733 in the cases where the server has merely temporarily disabled binary
1734 logging.
1735
1736 And even if this function returns false and the binary log is
1737 enabled, it is possible that the statement will not be written to
1738 the binary log, e.g. in case it is a no-op, it fails, it gets rolled
1739 back, or some other session closes the binary log due to a write
1740 error when using binlog_error_action=IGNORE_ERROR.
1741
1742 @retval true The binary log is currently disabled for the statement.
1743
1744 @retval false The binary log is currently enabled for the statement.
1745 */
1747
1748 /**
1749 Determine if binlogging is currently disabled for this session.
1750 If the binary log is disabled for this thread (either by log_bin=0 or
1751 sql_log_bin=0 or by log_replica_updates=0 for a slave thread), then the
1752 statement will not be written to the binary log.
1753
1754 @retval true The binary log is currently disabled for the statement.
1755
1756 @retval false The binary log is currently enabled for the statement.
1757 */
1759
1760 /**
1761 Checks whether binlog caches are disabled (binlog does not cache data) or
1762 empty in case binloggging is enabled in the current call to this function.
1763 This function may be safely called in case binlogging is disabled.
1764 @retval true binlog local caches are empty or disabled and binlogging is
1765 enabled
1766 @retval false binlog local caches are enabled and contain data or binlogging
1767 is disabled
1768 */
1770
1771 /**
1772 Determine if binloging is enabled in row format and write set extraction is
1773 enabled for this session
1774 @retval true if is enable
1775 @retval false otherwise
1776 */
1778
1779 /** Tells whether the given optimizer_switch flag is on */
1781 return (variables.optimizer_switch & flag);
1782 }
1783
1789
1792 }
1793
1797 }
1798
1802 }
1803
1805 return m_binlog_filter_state;
1806 }
1807
1808 /** Holds active timer object */
1810 /**
1811 After resetting(cancelling) timer, current timer object is cached
1812 with timer_cache timer to reuse.
1813 */
1815
1816 private:
1817 /*
1818 Indicates that the command which is under execution should ignore the
1819 'read_only' and 'super_read_only' options.
1820 */
1822
1823 /*
1824 Indicates that the command which is under execution should ignore the
1825 read only transaction mode.
1826 */
1828 /**
1829 Indicate if the current statement should be discarded
1830 instead of written to the binlog.
1831 This is used to discard special statements, such as
1832 DML or DDL that affects only 'local' (non replicated)
1833 tables, such as performance_schema.*
1834 */
1836
1837 /**
1838 Indicates the format in which the current statement will be
1839 logged. This can only be set from @c decide_logging_format().
1840 */
1842
1843 /**
1844 Bit field for the state of binlog warnings.
1845
1846 The first Lex::BINLOG_STMT_UNSAFE_COUNT bits list all types of
1847 unsafeness that the current statement has.
1848
1849 This must be a member of THD and not of LEX, because warnings are
1850 detected and issued in different places (@c
1851 decide_logging_format() and @c binlog_query(), respectively).
1852 Between these calls, the THD->lex object may change; e.g., if a
1853 stored routine is invoked. Only THD persists between the calls.
1854 */
1856
1857 /*
1858 Number of outstanding table maps, i.e., table maps in the
1859 transaction cache.
1860 */
1862 /*
1863 MTS: db names listing to be updated by the query databases
1864 */
1866
1867 /**
1868 The binary log position of the transaction.
1869
1870 The file and position are zero if the current transaction has not
1871 been written to the binary log.
1872
1873 @see set_trans_pos
1874 @see get_trans_pos
1875
1876 @todo Similar information is kept in the patch for BUG#11762277
1877 and by the master/slave heartbeat implementation. We should merge
1878 these positions instead of maintaining three different ones.
1879 */
1880 /**@{*/
1881 const char *m_trans_log_file;
1884 /**@}*/
1885 // NOTE: Ideally those two should be in Protocol,
1886 // but currently its design doesn't allow that.
1887 NET net; // client connection descriptor
1888 String packet; // dynamic buffer for network I/O
1889 public:
1890 const NET *get_net() const { return &net; }
1891
1893 skip_readonly_check = true;
1894 // Make a transaction skip the read only check set via the command
1895 // SET SESSION TRANSACTION READ ONLY
1897 }
1900 }
1902
1905 }
1909 }
1910
1914 }
1915
1916 void issue_unsafe_warnings();
1917
1920
1921 /*
1922 MTS: accessor to binlog_accessed_db_names list
1923 */
1926 }
1927
1928 /* MTS: method inserts a new unique name into binlog_updated_dbs */
1929 void add_to_binlog_accessed_dbs(const char *db);
1930
1931 bool is_applier_thread() const {
1934 }
1935
1936 private:
1937 std::unique_ptr<Transaction_ctx> m_transaction;
1938
1939 /** An utility struct for @c Attachable_trx */
1943 void backup(THD *thd);
1944 void restore(THD *thd);
1945
1946 /// SQL-command.
1948
1950
1951 /// Open-tables state.
1953
1954 /// SQL_MODE.
1956
1957 /// Transaction isolation level.
1959
1960 /// Ha_data array.
1962
1963 /// Transaction_ctx instance.
1965
1966 /// Transaction read-only state.
1968
1969 /// THD options.
1971
1972 /// Current transaction instrumentation.
1974
1975 /// Server status flags.
1977
1978 /// THD::in_lock_tables value.
1980
1981 /**
1982 Current time zone (i.e. @@session.time_zone) usage indicator.
1983
1984 Saving it allows data-dictionary code to read timestamp values
1985 as datetimes from system tables without disturbing user's statement.
1986
1987 TODO: We need to change DD code not to use @@session.time_zone at all and
1988 stick to UTC for internal storage of timestamps in DD objects.
1989 */
1991
1992 /**
1993 Transaction rollback request flag.
1994
1995 InnoDB can try to access table definition while rolling back regular
1996 transaction. So we need to be able to start attachable transaction
1997 without being affected by, and affecting, the rollback state of regular
1998 transaction.
1999 */
2001 };
2002
2003 public:
2005
2006 private:
2007 /**
2008 Class representing read-only attachable transaction, encapsulates
2009 knowledge how to backup state of current transaction, start
2010 read-only attachable transaction in SE, finalize it and then restore
2011 state of original transaction back. Also serves as a base class for
2012 read-write attachable transaction implementation.
2013 */
2015 public:
2016 Attachable_trx(THD *thd, Attachable_trx *prev_trx);
2017 virtual ~Attachable_trx();
2019 return m_prev_attachable_trx;
2020 }
2021 virtual bool is_read_only() const { return true; }
2022
2023 protected:
2024 /// THD instance.
2026
2028
2029 /**
2030 Attachable_trx which was active for the THD before when this
2031 transaction was started (NULL in most cases).
2032 */
2034
2035 /// Transaction state data.
2037
2038 private:
2041 };
2042
2043 /**
2044 A derived from THD::Attachable_trx class allows updates in
2045 the attachable transaction. Callers of the class methods must
2046 make sure the attachable_rw won't cause deadlock with the main transaction.
2047 The destructor does not invoke ha_commit_{stmt,trans} nor ha_rollback_trans
2048 on purpose.
2049 Burden to terminate the read-write instance also lies on the caller!
2050 In order to use this interface it *MUST* prove that no side effect to
2051 the global transaction state can be inflicted by a chosen method.
2052
2053 This class is being used only by class Gtid_table_access_context by
2054 replication and by dd::info_schema::Table_statistics.
2055 */
2056
2058 public:
2059 bool is_read_only() const override { return false; }
2060 explicit Attachable_trx_rw(THD *thd);
2061
2062 private:
2065 };
2066
2068
2069 public:
2071
2072 const Transaction_ctx *get_transaction() const { return m_transaction.get(); }
2073
2074 /**
2075 Changes the Transaction_ctx instance within THD-object. The previous
2076 Transaction_ctx instance is destroyed.
2077
2078 @note this is a THD-internal operation which MUST NOT be used outside.
2079
2080 @param transaction_ctx new Transaction_ctx instance to be associated with
2081 the THD-object.
2082 */
2083 void set_transaction(Transaction_ctx *transaction_ctx);
2084
2086
2087 Vio *active_vio = {nullptr};
2088
2089 /* Active network vio for clone remote connection. */
2090 Vio *clone_vio = {nullptr};
2091
2092 /**
2093 This is used to track transient changes to items during optimization of a
2094 prepared statement/stored procedure. Change objects are created by
2095 change_item_tree() in memory root of THD, and freed by
2096 rollback_item_tree_changes(). Changes recorded here are rolled back at
2097 the end of execution.
2098
2099 Transient changes require the following conditions:
2100 - The statement is not regular (ie. it is prepared or part of SP).
2101 - The change is performed outside preparation code (ie. it is
2102 performed during the optimization phase).
2103 - The change is applied to non-transient items (ie. items that have
2104 been created before or during preparation, not items that have been
2105 created in the optimization phase. Notice that the tree of AND/OR
2106 conditions is always as transient objects during optimization.
2107 Doing this should be quite harmless, though.)
2108 change_item_tree() only records changes to non-regular statements.
2109 It is also ensured that no changes are applied in preparation phase by
2110 asserting that the list of items is empty (see Sql_cmd_dml::prepare()).
2111 Other constraints are not enforced, in particular care must be taken
2112 so that all changes made during optimization to non-transient Items in
2113 non-regular statements must be recorded.
2114 */
2116
2117 /*
2118 A permanent memory area of the statement. For conventional
2119 execution, the parsed tree and execution runtime reside in the same
2120 memory root. In this case stmt_arena points to THD. In case of
2121 a prepared statement or a stored procedure statement, thd->mem_root
2122 conventionally points to runtime memory, and thd->stmt_arena
2123 points to the memory of the PS/SP, where the parsed tree of the
2124 statement resides. Whenever you need to perform a permanent
2125 transformation of a parsed tree, you should allocate new memory in
2126 stmt_arena, to allow correct re-execution of PS/SP.
2127 Note: in the parser, stmt_arena == thd, even for PS/SP.
2128 */
2130
2131 /*
2132 map for tables that will be updated for a multi-table update query
2133 statement, for other query statements, this will be zero.
2134 */
2136
2137 /* Tells if LAST_INSERT_ID(#) was called for the current statement */
2139 /*
2140 ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for
2141 insertion into an auto_increment column".
2142 */
2143 /*
2144 This is the first autogenerated insert id which was *successfully*
2145 inserted by the previous statement (exactly, if the previous statement
2146 didn't successfully insert an autogenerated insert id, then it's the one
2147 of the statement before, etc).
2148 It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#).
2149 It is returned by LAST_INSERT_ID().
2150 */
2152 /*
2153 Variant of the above, used for storing in statement-based binlog. The
2154 difference is that the one above can change as the execution of a stored
2155 function progresses, while the one below is set once and then does not
2156 change (which is the value which statement-based binlog needs).
2157 */
2159 /*
2160 This is the first autogenerated insert id which was *successfully*
2161 inserted by the current statement. It is maintained only to set
2162 first_successful_insert_id_in_prev_stmt when statement ends.
2163 */
2165 /*
2166 We follow this logic:
2167 - when stmt starts, first_successful_insert_id_in_prev_stmt contains the
2168 first insert id successfully inserted by the previous stmt.
2169 - as stmt makes progress, handler::insert_id_for_cur_row changes;
2170 every time get_auto_increment() is called,
2171 auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the
2172 reserved interval (if statement-based binlogging).
2173 - at first successful insertion of an autogenerated value,
2174 first_successful_insert_id_in_cur_stmt is set to
2175 handler::insert_id_for_cur_row.
2176 - when stmt goes to binlog,
2177 auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if
2178 non-empty.
2179 - when stmt ends, first_successful_insert_id_in_prev_stmt is set to
2180 first_successful_insert_id_in_cur_stmt.
2181 */
2182 /*
2183 stmt_depends_on_first_successful_insert_id_in_prev_stmt is set when
2184 LAST_INSERT_ID() is used by a statement.
2185 If it is set, first_successful_insert_id_in_prev_stmt_for_binlog will be
2186 stored in the statement-based binlog.
2187 This variable is CUMULATIVE along the execution of a stored function or
2188 trigger: if one substatement sets it to 1 it will stay 1 until the
2189 function/trigger ends, thus making sure that
2190 first_successful_insert_id_in_prev_stmt_for_binlog does not change anymore
2191 and is propagated to the caller for binlogging.
2192 */
2194 /*
2195 List of auto_increment intervals reserved by the thread so far, for
2196 storage in the statement-based binlog.
2197 Note that its minimum is not first_successful_insert_id_in_cur_stmt:
2198 assuming a table with an autoinc column, and this happens:
2199 INSERT INTO ... VALUES(3);
2200 SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL);
2201 then the latter INSERT will insert no rows
2202 (first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3"
2203 in the binlog is still needed; the list's minimum will contain 3.
2204 This variable is cumulative: if several statements are written to binlog
2205 as one (stored functions or triggers are used) this list is the
2206 concatenation of all intervals reserved by all statements.
2207 */
2209 /* Used by replication and SET INSERT_ID */
2211 /*
2212 There is BUG#19630 where statement-based replication of stored
2213 functions/triggers with two auto_increment columns breaks.
2214 We however ensure that it works when there is 0 or 1 auto_increment
2215 column; our rules are
2216 a) on master, while executing a top statement involving substatements,
2217 first top- or sub- statement to generate auto_increment values wins the
2218 exclusive right to see its values be written to binlog (the write
2219 will be done by the statement or its caller), and the losers won't see
2220 their values be written to binlog.
2221 b) on slave, while replicating a top statement involving substatements,
2222 first top- or sub- statement to need to read auto_increment values from
2223 the master's binlog wins the exclusive right to read them (so the losers
2224 won't read their values from binlog but instead generate on their own).
2225 a) implies that we mustn't backup/restore
2226 auto_inc_intervals_in_cur_stmt_for_binlog.
2227 b) implies that we mustn't backup/restore auto_inc_intervals_forced.
2228
2229 If there are more than 1 auto_increment columns, then intervals for
2230 different columns may mix into the
2231 auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong,
2232 but there is no point in preventing this mixing by preventing intervals
2233 from the secondly inserted column to come into the list, as such
2234 prevention would be wrong too.
2235 What will happen in the case of
2236 INSERT INTO t1 (auto_inc) VALUES(NULL);
2237 where t1 has a trigger which inserts into an auto_inc column of t2, is
2238 that in binlog we'll store the interval of t1 and the interval of t2 (when
2239 we store intervals, soon), then in slave, t1 will use both intervals, t2
2240 will use none; if t1 inserts the same number of rows as on master,
2241 normally the 2nd interval will not be used by t1, which is fine. t2's
2242 values will be wrong if t2's internal auto_increment counter is different
2243 from what it was on master (which is likely). In 5.1, in mixed binlogging
2244 mode, row-based binlogging is used for such cases where two
2245 auto_increment columns are inserted.
2246 */
2250 }
2253 /* It's the first time we read it */
2257 }
2259 }
2266 }
2267
2268 /*
2269 Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#"
2270 (mysqlbinlog). We'll soon add a variant which can take many intervals in
2271 argument.
2272 */
2274 auto_inc_intervals_forced.clear(); // in case of multiple SET INSERT_ID
2275 auto_inc_intervals_forced.append(next_id, ULLONG_MAX, 0);
2276 }
2277
2278 /**
2279 Stores the result of the FOUND_ROWS() function. Set at query end, stable
2280 throughout the query.
2281 */
2283 /**
2284 Dynamic, collected and set also in subqueries. Not stable throughout query.
2285 previous_found_rows is a snapshot of this take at query end making it
2286 stable throughout the next query, see update_previous_found_rows.
2287 */
2289
2290 /*
2291 Indicate if the gtid_executed table is being operated implicitly
2292 within current transaction. This happens because we are inserting
2293 a GTID specified through SET GTID_NEXT by user client or
2294 slave SQL thread/workers.
2295 */
2297 /*
2298 Indicate that a sub-statement is being operated implicitly
2299 within current transaction.
2300 As we don't want that this implicit sub-statement to consume the
2301 GTID of the actual transaction, we set it true at the beginning of
2302 the sub-statement and set it false again after "committing" the
2303 sub-statement.
2304 When it is true, the applier will not save the transaction owned
2305 gtid into mysql.gtid_executed table before transaction prepare, as
2306 it does when binlog is disabled, or binlog is enabled and
2307 log_replica_updates is disabled.
2308 Also the flag is made to defer updates to the slave info table from
2309 intermediate commits by non-atomic DDL.
2310 Rpl_info_table::do_flush_info(), rpl_rli.h::is_atomic_ddl_commit_on_slave()
2311 uses this flag.
2312 */
2314
2315 private:
2316 /**
2317 Stores the result of ROW_COUNT() function.
2318
2319 ROW_COUNT() function is a MySQL extension, but we try to keep it
2320 similar to ROW_COUNT member of the GET DIAGNOSTICS stack of the SQL
2321 standard (see SQL99, part 2, search for ROW_COUNT). Its value is
2322 implementation defined for anything except INSERT, DELETE, UPDATE.
2323
2324 ROW_COUNT is assigned according to the following rules:
2325
2326 - In my_ok():
2327 - for DML statements: to the number of affected rows;
2328 - for DDL statements: to 0.
2329
2330 - In my_eof(): to -1 to indicate that there was a result set.
2331
2332 We derive this semantics from the JDBC specification, where int
2333 java.sql.Statement.getUpdateCount() is defined to (sic) "return the
2334 current result as an update count; if the result is a ResultSet
2335 object or there are no more results, -1 is returned".
2336
2337 - In my_error(): to -1 to be compatible with the MySQL C API and
2338 MySQL ODBC driver.
2339
2340 - For SIGNAL statements: to 0 per WL#2110 specification (see also
2341 sql_signal.cc comment). Zero is used since that's the "default"
2342 value of ROW_COUNT in the Diagnostics Area.
2343 */
2344
2345 longlong m_row_count_func; /* For the ROW_COUNT() function */
2346
2347 public:
2349
2350 inline void set_row_count_func(longlong row_count_func) {
2351 m_row_count_func = row_count_func;
2352 }
2353
2355
2356 private:
2357 /**
2358 Number of rows we actually sent to the client, including "synthetic"
2359 rows in ROLLUP etc.
2360 */
2362
2363 /**
2364 Number of rows read and/or evaluated for a statement. Used for
2365 slow log reporting.
2366
2367 An examined row is defined as a row that is read and/or evaluated
2368 according to a statement condition, including in
2369 create_sort_index(). Rows may be counted more than once, e.g., a
2370 statement including ORDER BY could possibly evaluate the row in
2371 filesort() before reading it for e.g. update.
2372 */
2374
2375 private:
2377
2378 public:
2379 void set_user_connect(USER_CONN *uc);
2380 const USER_CONN *get_user_connect() const { return m_user_connect; }
2381
2384
2386
2388
2390
2392
2393 public:
2395
2397
2399
2402
2411 void inc_status_sort_range();
2413 void inc_status_sort_scan();
2416
2418#if defined(ENABLED_PROFILING)
2419 std::unique_ptr<PROFILING> profiling;
2420#endif
2421
2422 /** Current stage progress instrumentation. */
2424 /** Current statement digest. */
2426 /** Current statement digest token array. */
2427 unsigned char *m_token_array;
2428 /** Top level statement digest. */
2430
2431 /** Current statement instrumentation. */
2433#ifdef HAVE_PSI_STATEMENT_INTERFACE
2434 /** Current statement instrumentation state. */
2436#endif /* HAVE_PSI_STATEMENT_INTERFACE */
2437
2438 /** Current transaction instrumentation. */
2440#ifdef HAVE_PSI_TRANSACTION_INTERFACE
2441 /** Current transaction instrumentation state. */
2443#endif /* HAVE_PSI_TRANSACTION_INTERFACE */
2444
2445 /** Idle instrumentation. */
2447#ifdef HAVE_PSI_IDLE_INTERFACE
2448 /** Idle instrumentation state. */
2450#endif /* HAVE_PSI_IDLE_INTERFACE */
2451 /** True if the server code is IDLE for this connection. */
2453
2454 /*
2455 Id of current query. Statement can be reused to execute several queries
2456 query_id is global in context of the whole MySQL server.
2457 ID is automatically generated from mutex-protected counter.
2458 It's used in handler code for various purposes: to check which columns
2459 from table are necessary for this select, to check if it's necessary to
2460 update auto-updatable fields (like auto_increment and timestamp).
2461 */
2463
2464 /* Statement id is thread-wide. This counter is used to generate ids */
2468 /**
2469 This counter is 32 bit because of the client protocol.
2470
2471 @note It is not meant to be used for my_thread_self(), see @c real_id for
2472 this.
2473
2474 @note Set to reserved_thread_id on initialization. This is a magic
2475 value that is only to be used for temporary THDs not present in
2476 the global THD list.
2477 */
2478 private:
2480
2481 public:
2482 /**
2483 Assign a value to m_thread_id by calling
2484 Global_THD_manager::get_new_thread_id().
2485 */
2486 void set_new_thread_id();
2491
2492 // Check if this THD belongs to a system thread.
2494
2495 // Check if this THD belongs to a dd bootstrap system thread.
2496 bool is_dd_system_thread() const {
2499 }
2500
2501 // Check if this THD belongs to the initialize system thread. The
2502 // initialize thread executes statements that are compiled into the
2503 // server.
2506 }
2507
2508 // Check if this THD is executing statements passed through a init file.
2511 }
2512
2513 // Check if this THD belongs to a bootstrap system thread. Note that
2514 // this thread type may execute statements submitted by the user.
2518 }
2519
2520 // Check if this THD belongs to a server upgrade thread. Server upgrade
2521 // threads execute statements that are compiled into the server.
2524 }
2525
2526 /*
2527 Current or next transaction isolation level.
2528 When a connection is established, the value is taken from
2529 @@session.tx_isolation (default transaction isolation for
2530 the session), which is in turn taken from @@global.tx_isolation
2531 (the global value).
2532 If there is no transaction started, this variable
2533 holds the value of the next transaction's isolation level.
2534 When a transaction starts, the value stored in this variable
2535 becomes "actual".
2536 At transaction commit or rollback, we assign this variable
2537 again from @@session.tx_isolation.
2538 The only statement that can otherwise change the value
2539 of this variable is SET TRANSACTION ISOLATION LEVEL.
2540 Its purpose is to effect the isolation level of the next
2541 transaction in this session. When this statement is executed,
2542 the value in this variable is changed. However, since
2543 this statement is only allowed when there is no active
2544 transaction, this assignment (naturally) only affects the
2545 upcoming transaction.
2546 At the end of the current active transaction the value is
2547 be reset again from @@session.tx_isolation, as described
2548 above.
2549 */
2551 /*
2552 Current or next transaction access mode.
2553 See comment above regarding tx_isolation.
2554 */
2556 /*
2557 Transaction cannot be rolled back must be given priority.
2558 When two transactions conflict inside InnoDB, the one with
2559 greater priority wins.
2560 */
2562 /*
2563 All transactions executed by this thread will have high
2564 priority mode, independent of tx_priority value.
2565 */
2567
2569
2570 // For user variables replication
2572 MEM_ROOT *user_var_events_alloc; /* Allocate above array elements here */
2573
2574 /**
2575 Used by MYSQL_BIN_LOG to maintain the commit queue for binary log
2576 group commit.
2577 */
2579
2580 /**
2581 The member is served for marking a query that CREATEs or ALTERs
2582 a table declared with a TIMESTAMP column as dependent on
2583 @@session.explicit_defaults_for_timestamp.
2584 Is set to true by parser, unset at the end of the query.
2585 Possible marking in checked by binary logger.
2586 */
2588
2589 /**
2590 Functions to set and get transaction position.
2591
2592 These functions are used to set the transaction position for the
2593 transaction written when committing this transaction.
2594 */
2595 /**@{*/
2596 void set_trans_pos(const char *file, my_off_t pos) {
2597 DBUG_TRACE;
2598 assert(((file == nullptr) && (pos == 0)) ||
2599 ((file != nullptr) && (pos != 0)));
2600 if (file) {
2601 DBUG_PRINT("enter", ("file: %s, pos: %llu", file, pos));
2602 // Only the file name should be used, not the full path
2606 assert(strlen(m_trans_log_file) <= FN_REFLEN);
2608 } else {
2609 m_trans_log_file = nullptr;
2610 m_trans_fixed_log_file = nullptr;
2611 }
2612
2613 m_trans_end_pos = pos;
2614 DBUG_PRINT("return",
2615 ("m_trans_log_file: %s, m_trans_fixed_log_file: %s, "
2616 "m_trans_end_pos: %llu",
2618 return;
2619 }
2620
2621 void get_trans_pos(const char **file_var, my_off_t *pos_var) const {
2622 DBUG_TRACE;
2623 if (file_var) *file_var = m_trans_log_file;
2624 if (pos_var) *pos_var = m_trans_end_pos;
2625 DBUG_PRINT("return",
2626 ("file: %s, pos: %llu", file_var ? *file_var : "<none>",
2627 pos_var ? *pos_var : 0));
2628 return;
2629 }
2630
2631 void get_trans_fixed_pos(const char **file_var, my_off_t *pos_var) const {
2632 DBUG_TRACE;
2633 if (file_var) *file_var = m_trans_fixed_log_file;
2634 if (pos_var) *pos_var = m_trans_end_pos;
2635 DBUG_PRINT("return",
2636 ("file: %s, pos: %llu", file_var ? *file_var : "<none>",
2637 pos_var ? *pos_var : 0));
2638 return;
2639 }
2640
2641 /**@}*/
2642
2643 /*
2644 Error code from committing or rolling back the transaction.
2645 */
2654
2655 /*
2656 Define durability properties that engines may check to
2657 improve performance.
2658 */
2660
2661 /*
2662 If checking this in conjunction with a wait condition, please
2663 include a check after enter_cond() if you want to avoid a race
2664 condition. For details see the implementation of awake(),
2665 especially the "broadcast" part.
2666 */
2669 KILL_CONNECTION = ER_SERVER_SHUTDOWN,
2670 KILL_QUERY = ER_QUERY_INTERRUPTED,
2671 KILL_TIMEOUT = ER_QUERY_TIMEOUT,
2672 KILLED_NO_VALUE /* means neither of the states */
2674 std::atomic<killed_state> killed;
2675
2676 /**
2677 Whether we are currently in the execution phase of an EXPLAIN ANALYZE query.
2678 If so, send_kill_message() won't actually set an error; we will add a
2679 warning near the end of the execution instead.
2680 */
2682
2683 /**
2684 When operation on DD tables is in progress then THD is set to kill immune
2685 mode.
2686 This member holds DD_kill_immunizer object created to make DD operations
2687 immune from the kill operations. Member also indicated whether THD is in
2688 kill immune mode or not.
2689 */
2691
2692 /* scramble - random string sent to client on handshake */
2694
2695 /// @todo: slave_thread is completely redundant, we should use 'system_thread'
2696 /// instead /sven
2698
2700
2701 private:
2702 /**
2703 Set to true if execution of the current compound statement
2704 can not continue. In particular, disables activation of
2705 CONTINUE or EXIT handlers of stored routines.
2706 Reset in the end of processing of the current user request, in
2707 @see mysql_reset_thd_for_next_command().
2708 */
2710
2711 public:
2712 /**
2713 Set by a storage engine to request the entire
2714 transaction (that possibly spans multiple engines) to
2715 rollback. Reset in ha_rollback.
2716 */
2718 /**
2719 true if we are in a sub-statement and the current error can
2720 not be safely recovered until we left the sub-statement mode.
2721 In particular, disables activation of CONTINUE and EXIT
2722 handlers inside sub-statements. E.g. if it is a deadlock
2723 error and requires a transaction-wide rollback, this flag is
2724 raised (traditionally, MySQL first has to close all the reads
2725 via @see handler::ha_index_or_rnd_end() and only then perform
2726 the rollback).
2727 Reset to false when we leave the sub-statement mode.
2728 */
2733 /**
2734 True if a slave error. Causes the slave to stop. Not the same
2735 as the statement execution error (is_error()), since
2736 a statement may be expected to return an error, e.g. because
2737 it returned an error on master, and this is OK on the slave.
2738 */
2740
2741 /** is set if some thread specific value(s) used in a statement. */
2743 /**
2744 is set if a statement accesses a temporary table created through
2745 CREATE TEMPORARY TABLE.
2746 */
2749 bool enable_slow_log; /* enable slow log for current statement */
2750 /* set during loop of derived table processing */
2752 // Set while parsing INFORMATION_SCHEMA system views.
2754
2755 /** Current SP-runtime context. */
2759
2760 /** number of name_const() substitutions, see sp_head.cc:subst_spvars() */
2762
2763 /* Used by the sys_var class to store temporary values */
2764 union {
2771
2772 struct {
2773 /*
2774 If true, mysql_bin_log::write(Log_event) call will not write events to
2775 binlog, and maintain 2 below variables instead (use
2776 mysql_bin_log.start_union_events to turn this on)
2777 */
2779 /*
2780 If true, at least one mysql_bin_log::write(Log_event) call has been
2781 made after last mysql_bin_log.start_union_events() call.
2782 */
2784 /*
2785 If true, at least one mysql_bin_log::write(Log_event e), where
2786 e.cache_stmt == true call has been made after last
2787 mysql_bin_log.start_union_events() call.
2788 */
2790
2791 /*
2792 'queries' (actually SP statements) that run under inside this binlog
2793 union have thd->query_id >= first_query_id.
2794 */
2797
2798 /**
2799 Internal parser state.
2800 Note that since the parser is not re-entrant, we keep only one parser
2801 state here. This member is valid only when executing code during parsing.
2802 */
2804
2806
2808
2809 /**
2810 Array of active audit plugins which have been used by this THD.
2811 This list is later iterated to invoke release_thd() on those
2812 plugins.
2813 */
2815 /**
2816 Array of bits indicating which audit classes have already been
2817 added to the list of audit plugins which are currently in use.
2818 */
2820
2821#if defined(ENABLED_DEBUG_SYNC)
2822 /* Debug Sync facility. See debug_sync.cc. */
2823 struct st_debug_sync_control *debug_sync_control;
2824#endif /* defined(ENABLED_DEBUG_SYNC) */
2825
2826 // We don't want to load/unload plugins for unit tests.
2828
2829 /*
2830 Audit API events are generated, when this flag is true. The flag
2831 is initially true, but it can be set false in some cases, e.g.
2832 Session Service's THDs are created with auditing disabled. Auditing
2833 is enabled on EVENT_TRACKING_CONNECTION_CONNECT event.
2834 */
2836
2837 explicit THD(bool enable_plugins = true);
2838
2839 /*
2840 The THD dtor is effectively split in two:
2841 THD::release_resources() and ~THD().
2842
2843 We want to minimize the time we hold LOCK_thd_list,
2844 so when destroying a global thread, do:
2845
2846 thd->release_resources()
2847 Global_THD_manager::get_instance()->remove_thd();
2848 delete thd;
2849 */
2850 ~THD() override;
2851
2852 void release_resources();
2853 /**
2854 @returns true if THD resources are released.
2855 */
2856 bool release_resources_done() const;
2857 /**
2858 Check if THD is being disposed (i.e. m_thd_life_cycle_stage >=
2859 SCHEDULED_FOR_DISPOSAL)
2860
2861 Non-owner thread should acquire LOCK_thd_data to check THD state without
2862 getting into races.
2863
2864 @returns true of THD is being disposed.
2865 */
2866 bool is_being_disposed() const;
2867
2868 private:
2869 /**
2870 Represents life cycle stages of THD instance.
2871 Stage transition in THD clean up:
2872 1. ACTIVE -> ACTIVE_AND_CLEAN
2873
2874 Stage transition in THD disposal:
2875 1. ACTIVE -> SCHEDULED_FOR_DISPOSAL -> CLEANED_UP -> RESOURCES_RELEASED
2876 -> DISPOSED.
2877 2. ACTIVE_AND_CLEAN -> CLEANED_UP -> RESOURCES_RELEASED -> DISPOSED.
2878 */
2885 DISPOSED
2888 enum_thd_life_cycle_stages::ACTIVE};
2889
2890 /**
2891 Set THD in ACTIVE life stage to disposal stage.
2892
2893 To avoid race conditions with non-owner thread checking THD disposal state,
2894 LOCK_thd_data should be acquired before changing THD stage to disposal
2895 stage.
2896 */
2897 void start_disposal();
2898
2899 /**
2900 @returns true if THD is cleaned up.
2901 */
2902 bool is_cleanup_done();
2903 void cleanup(void);
2904
2905 void init(void);
2906
2907 public:
2908 /**
2909 Initialize memory roots necessary for query processing and (!)
2910 pre-allocate memory for it. We can't do that in THD constructor because
2911 there are use cases (acl_init, watcher threads,
2912 killing mysqld) where it's vital to not allocate excessive and not used
2913 memory. Note, that we still don't return error from init_query_mem_roots()
2914 if preallocation fails, we should notice that at the first call to
2915 alloc_root.
2916 */
2917 void init_query_mem_roots();
2918 void cleanup_connection(void);
2919 void cleanup_after_query();
2920 void store_globals();
2921 void restore_globals();
2922
2923 inline void set_active_vio(Vio *vio) {
2925 active_vio = vio;
2927 }
2928
2929 inline void set_ssl(Vio *vio) {
2931 m_SSL = (SSL *)vio->ssl_arg;
2933 }
2934
2935 inline void clear_active_vio() {
2937 active_vio = nullptr;
2938 m_SSL = nullptr;
2940 }
2941
2942 /** Set active clone network Vio for remote clone.
2943 @param[in] vio network vio */
2944 inline void set_clone_vio(Vio *vio) {
2946 clone_vio = vio;
2948 }
2949
2950 /** Clear clone network Vio for remote clone. */
2951 inline void clear_clone_vio() {
2953 clone_vio = nullptr;
2955 }
2956
2957 /** Check if clone network Vio is active. */
2958 inline bool check_clone_vio() {
2960 const bool is_active = (clone_vio != nullptr);
2962 return (is_active);
2963 }
2964
2965 /** Shutdown clone vio, if active. */
2966 void shutdown_clone_vio();
2967
2969
2970 void shutdown_active_vio();
2971 void awake(THD::killed_state state_to_set);
2972
2973 /** Disconnect the associated communication endpoint. */
2974 void disconnect(bool server_shutdown = false);
2975
2977 /* The query can be logged in row format or in statement format. */
2979
2980 /* The query has to be logged in statement format. */
2982
2985
2986 int binlog_query(enum_binlog_query_type qtype, const char *query,
2987 size_t query_len, bool is_trans, bool direct,
2988 bool suppress_use, int errcode);
2989
2990 // Begin implementation of MDL_context_owner interface.
2991
2993 const PSI_stage_info *stage, PSI_stage_info *old_stage,
2994 const char *src_function, const char *src_file,
2995 int src_line) override {
2996 DBUG_TRACE;
2998 /*
2999 Sic: We don't lock LOCK_current_cond here.
3000 If we did, we could end up in deadlock with THD::awake()
3001 which locks current_mutex while LOCK_current_cond is locked.
3002 */
3003 current_mutex = mutex;
3004 current_cond = cond;
3005 enter_stage(stage, old_stage, src_function, src_file, src_line);
3006 return;
3007 }
3008
3009 void exit_cond(const PSI_stage_info *stage, const char *src_function,
3010 const char *src_file, int src_line) override {
3011 DBUG_TRACE;
3012 /*
3013 current_mutex must be unlocked _before_ LOCK_current_cond is
3014 locked (if that would not be the case, you'll get a deadlock if someone
3015 does a THD::awake() on you).
3016 */
3019 current_mutex = nullptr;
3020 current_cond = nullptr;
3022 enter_stage(stage, nullptr, src_function, src_file, src_line);
3023 return;
3024 }
3025
3026 int is_killed() const final { return killed; }
3028 /*
3029 We need to return if this thread can have any commit order waiters
3030 which are still accounted by MDL deadlock detector (even in absence
3031 of any MDL locks). We approximate this check by testing whether
3032 this thread is replication applier. Doing more precise check is going
3033 to be more expensive and possibly racy.
3034 */
3035 return slave_thread;
3036 }
3037
3038 THD *get_thd() override { return this; }
3039
3040 /**
3041 A callback to the server internals that is used to address
3042 special cases of the locking protocol.
3043 Invoked when acquiring an exclusive lock, for each thread that
3044 has a conflicting shared metadata lock.
3045
3046 This function aborts waiting of the thread on a data lock, to make
3047 it notice the pending exclusive lock and back off.
3048
3049 @note This function does not wait for the thread to give away its
3050 locks. Waiting is done outside for all threads at once.
3051
3052 @param ctx_in_use The MDL context owner (thread) to wake up.
3053 @param needs_thr_lock_abort Indicates that to wake up thread
3054 this call needs to abort its waiting
3055 on table-level lock.
3056 */
3057 void notify_shared_lock(MDL_context_owner *ctx_in_use,
3058 bool needs_thr_lock_abort) override;
3059
3060 bool notify_hton_pre_acquire_exclusive(const MDL_key *mdl_key,
3061 bool *victimized) override;
3062
3063 void notify_hton_post_release_exclusive(const MDL_key *mdl_key) override;
3064
3065 /**
3066 Provide thread specific random seed for MDL_context's PRNG.
3067
3068 Note that even if two connections will request seed during handling of
3069 statements which were started at exactly the same time, and thus will
3070 get the same values in PRNG at the start, they will naturally diverge
3071 soon, since calls to PRNG in MDL subsystem are affected by many factors
3072 making process quite random. OTOH the fact that we use time as a seed
3073 gives more randomness and thus better coverage in tests as opposed to
3074 using thread_id for the same purpose.
3075 */
3076 uint get_rand_seed() const override { return (uint)start_utime; }
3077
3078 // End implementation of MDL_context_owner interface.
3079
3080 inline bool is_strict_mode() const {
3081 return (variables.sql_mode &
3083 }
3084 inline const CHARSET_INFO *collation() {
3085 return variables.collation_server ? variables.collation_server
3087 }
3089 time_zone_used = true;
3090 return variables.time_zone;
3091 }
3092 time_t query_start_in_secs() const { return start_time.tv_sec; }
3094 void set_time();
3095 void set_time(const struct timeval *t) {
3096 user_time = *t;
3097 set_time();
3098 }
3099 inline bool is_fsp_truncate_mode() const {
3101 }
3102
3103 /**
3104 Evaluate the current time, and if it exceeds the long-query-time
3105 setting, mark the query as slow.
3106 */
3108
3110
3111 /*
3112 Call when it is clear that the query is ended and we have collected the
3113 right value for current_found_rows. Calling this method makes a snapshot of
3114 that value and makes it ready and stable for subsequent FOUND_ROWS() call
3115 in the next statement.
3116 */
3119 }
3120
3121 /**
3122 Returns true if session is in a multi-statement transaction mode.
3123
3124 OPTION_NOT_AUTOCOMMIT: When autocommit is off, a multi-statement
3125 transaction is implicitly started on the first statement after a
3126 previous transaction has been ended.
3127
3128 OPTION_BEGIN: Regardless of the autocommit status, a multi-statement
3129 transaction can be explicitly started with the statements "START
3130 TRANSACTION", "BEGIN [WORK]", "[COMMIT | ROLLBACK] AND CHAIN", etc.
3131
3132 Note: this doesn't tell you whether a transaction is active.
3133 A session can be in multi-statement transaction mode, and yet
3134 have no active transaction, e.g., in case of:
3135 set \@\@autocommit=0;
3136 set \@a= 3; <-- these statements don't
3137 set transaction isolation level serializable; <-- start an active
3138 flush tables; <-- transaction
3139
3140 I.e. for the above scenario this function returns true, even
3141 though no active transaction has begun.
3142 @sa in_active_multi_stmt_transaction()
3143 */
3145 return variables.option_bits & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN);
3146 }
3147 /**
3148 true if the session is in a multi-statement transaction mode
3149 (@sa in_multi_stmt_transaction_mode()) *and* there is an
3150 active transaction, i.e. there is an explicit start of a
3151 transaction with BEGIN statement, or implicit with a
3152 statement that uses a transactional engine.
3153
3154 For example, these scenarios don't start an active transaction
3155 (even though the server is in multi-statement transaction mode):
3156
3157 @verbatim
3158 set @@autocommit=0;
3159 select * from nontrans_table;
3160 set @var = true;
3161 flush tables;
3162 @endverbatim
3163
3164 Note, that even for a statement that starts a multi-statement
3165 transaction (i.e. select * from trans_table), this
3166 flag won't be set until we open the statement's tables
3167 and the engines register themselves for the transaction
3168 (see trans_register_ha()),
3169 hence this method is reliable to use only after
3170 open_tables() has completed.
3171
3172 Why do we need a flag?
3173 ----------------------
3174 We need to maintain a (at first glance redundant)
3175 session flag, rather than looking at thd->transaction.all.ha_list
3176 because of explicit start of a transaction with BEGIN.
3177
3178 I.e. in case of
3179 BEGIN;
3180 select * from nontrans_t1; <-- in_active_multi_stmt_transaction() is true
3181 */
3184 }
3186 return !stmt_arena->is_stmt_prepare();
3187 }
3188
3190 const char *from, size_t from_length,
3191 const CHARSET_INFO *from_cs, bool report_error = false);
3192
3194
3195 /**
3196 Clear the current error, if any.
3197 We do not clear is_fatal_error or is_fatal_sub_stmt_error since we
3198 assume this is never called if the fatal error is set.
3199 @todo: To silence an error, one should use Internal_error_handler
3200 mechanism. In future this function will be removed.
3201 */
3202 inline void clear_error() {
3203 DBUG_TRACE;
3205 is_slave_error = false;
3206 return;
3207 }
3208
3209 bool is_classic_protocol() const;
3210
3211 /** Return false if connection to client is broken. */
3212 bool is_connected() final;
3213
3214 /**
3215 Mark the current error as fatal. Warning: this does not
3216 set any error, it sets a property of the error, so must be
3217 followed or prefixed with my_error().
3218 */
3220 bool is_fatal_error() const { return m_is_fatal_error; }
3221 /**
3222 true if there is an error in the error stack.
3223
3224 Please use this method instead of direct access to
3225 net.report_error.
3226
3227 If true, the current (sub)-statement should be aborted.
3228 The main difference between this member and is_fatal_error
3229 is that a fatal error can not be handled by a stored
3230 procedure continue handler, whereas a normal error can.
3231
3232 To raise this flag, use my_error().
3233 */
3234 inline bool is_error() const { return get_stmt_da()->is_error(); }
3235
3236 /// Returns first Diagnostics Area for the current statement.
3238
3239 /// Returns first Diagnostics Area for the current statement.
3240 const Diagnostics_area *get_stmt_da() const { return m_stmt_da; }
3241
3242 /// Returns the second Diagnostics Area for the current statement.
3244 return get_stmt_da()->stacked_da();
3245 }
3246
3247 /**
3248 Returns thread-local Diagnostics Area for parsing.
3249 We need to have a clean DA in case errors or warnings are thrown
3250 during parsing, but we can't just reset the main DA in case we
3251 have a diagnostic statement on our hand that needs the old DA
3252 to answer questions about the previous execution.
3253 Keeping a static per-thread DA for parsing is less costly than
3254 allocating a temporary one for each statement we parse.
3255 */
3257
3258 /**
3259 Returns thread-local Diagnostics Area to be used by query rewrite plugins.
3260 Query rewrite plugins use their own diagnostics area. The reason is that
3261 they are invoked right before and right after parsing, and we don't want
3262 conditions raised by plugins in either statement nor parser DA until we
3263 know which type of statement we have parsed.
3264
3265 @note The diagnostics area is instantiated the first time it is asked for.
3266 */
3269 }
3270
3271 /**
3272 Push the given Diagnostics Area on top of the stack, making
3273 it the new first Diagnostics Area. Conditions in the new second
3274 Diagnostics Area will be copied to the new first Diagnostics Area.
3275
3276 @param da Diagnostics Area to be come the top of
3277 the Diagnostics Area stack.
3278 @param copy_conditions
3279 Copy the conditions from the new second Diagnostics Area
3280 to the new first Diagnostics Area, as per SQL standard.
3281 */
3283 bool copy_conditions = true) {
3284 get_stmt_da()->push_diagnostics_area(this, da, copy_conditions);
3285 m_stmt_da = da;
3286 }
3287
3288 /// Pop the top DA off the Diagnostics Area stack.
3291 }
3292
3293 /**
3294 Inserts the new protocol at the top of the protocol stack, and make it
3295 the current protocol for this thd.
3296
3297 @param protocol Protocol to be inserted.
3298 */
3299 void push_protocol(Protocol *protocol);
3300
3301 template <typename ProtocolClass>
3302 void push_protocol(const std::unique_ptr<ProtocolClass> &protocol) {
3303 push_protocol(protocol.get());
3304 }
3305
3306 /**
3307 Pops the top protocol of the Protocol stack and sets the previous one
3308 as the current protocol.
3309 */
3310 void pop_protocol();
3311
3312 public:
3314 void update_charset();
3315
3316 /**
3317 Record a transient change to a pointer to an Item within another Item.
3318 */
3319 void change_item_tree(Item **place, Item *new_value) {
3320 /* TODO: check for OOM condition here */
3321 if (!stmt_arena->is_regular()) {
3322 DBUG_PRINT("info", ("change_item_tree place %p old_value %p new_value %p",
3323 place, *place, new_value));
3324 nocheck_register_item_tree_change(place, new_value);
3325 }
3326 *place = new_value;
3327 }
3328
3329 /**
3330 Remember that place was updated with new_value so it can be restored
3331 by rollback_item_tree_changes().
3332
3333 @param[in] place the location that will change, and whose old value
3334 we need to remember for restoration
3335 @param[in] new_value new value about to be inserted into *place
3336 */
3337 void nocheck_register_item_tree_change(Item **place, Item *new_value);
3338
3339 /**
3340 Restore locations set by calls to nocheck_register_item_tree_change().
3341 */
3343
3344 /*
3345 Cleanup statement parse state (parse tree, lex) and execution
3346 state after execution of a non-prepared SQL statement.
3347 */
3348 void end_statement();
3349 void send_kill_message() const;
3350
3352 uint add_state_flags);
3356
3357 public:
3358 /**
3359 Start a read-only attachable transaction.
3360 There must be no active attachable transactions (in other words, there can
3361 be only one active attachable transaction at a time).
3362 */
3364
3365 /**
3366 Start a read-write attachable transaction.
3367 All the read-only class' requirements apply.
3368 Additional requirements are documented along the class
3369 declaration.
3370 */
3372
3373 /**
3374 End an active attachable transaction. Applies to both the read-only
3375 and the read-write versions.
3376 Note, that the read-write attachable transaction won't be terminated
3377 inside this method.
3378 To invoke the function there must be active attachable transaction.
3379 */
3381
3382 /**
3383 @return true if there is an active attachable transaction.
3384 */
3386 return m_attachable_trx != nullptr && m_attachable_trx->is_read_only();
3387 }
3388
3389 /**
3390 @return true if there is an active attachable transaction.
3391 */
3393 return m_attachable_trx != nullptr;
3394 }
3395
3396 /**
3397 @return true if there is an active rw attachable transaction.
3398 */
3400 return m_attachable_trx != nullptr && !m_attachable_trx->is_read_only();
3401 }
3402
3403 public:
3404 /*
3405 @todo Make these methods private or remove them completely. Only
3406 decide_logging_format should call them. /Sven
3407 */
3409 DBUG_TRACE;
3410 /*
3411 This should only be called from decide_logging_format.
3412
3413 @todo Once we have ensured this, uncomment the following
3414 statement, remove the big comment below that, and remove the
3415 in_sub_stmt==0 condition from the following 'if'.
3416 */
3417 /* assert(in_sub_stmt == 0); */
3418 /*
3419 If in a stored/function trigger, the caller should already have done the
3420 change. We test in_sub_stmt to prevent introducing bugs where people
3421 wouldn't ensure that, and would switch to row-based mode in the middle
3422 of executing a stored function/trigger (which is too late, see also
3423 reset_current_stmt_binlog_format_row()); this condition will make their
3424 tests fail and so force them to propagate the
3425 lex->binlog_row_based_if_mixed upwards to the caller.
3426 */
3427 if ((variables.binlog_format == BINLOG_FORMAT_MIXED) && (in_sub_stmt == 0))
3429
3430 return;
3431 }
3433 DBUG_TRACE;
3435 return;
3436 }
3438 DBUG_TRACE;
3440 return;
3441 }
3443 DBUG_TRACE;
3444 DBUG_PRINT("debug", ("in_sub_stmt: %d, system_thread: %s", in_sub_stmt != 0,
3446 if (in_sub_stmt == 0) {
3447 if (variables.binlog_format == BINLOG_FORMAT_ROW)
3449 else
3451 }
3452 return;
3453 }
3454
3455 /**
3456 Copies variables.original_commit_timestamp to
3457 ((Slave_worker *)rli_slave)->original_commit_timestamp,
3458 if this is a slave thread.
3459 */
3461
3462 /// Return the value of @@gtid_next_list: either a Gtid_set or NULL.
3464 return variables.gtid_next_list.is_non_null
3465 ? variables.gtid_next_list.gtid_set
3466 : nullptr;
3467 }
3468
3469 /// Return the value of @@gtid_next_list: either a Gtid_set or NULL.
3471 return const_cast<THD *>(this)->get_gtid_next_list();
3472 }
3473
3474 /**
3475 Return true if the statement/transaction cache is currently empty,
3476 false otherwise.
3477
3478 @param is_transactional if true, check the transaction cache.
3479 If false, check the statement cache.
3480 */
3481 bool is_binlog_cache_empty(bool is_transactional) const;
3482
3483 /**
3484 The GTID of the currently owned transaction.
3485
3486 ==== Modes of ownership ====
3487
3488 The following modes of ownership are possible:
3489
3490 - owned_gtid.sidno==0: the thread does not own any transaction.
3491
3492 - owned_gtid.sidno==THD::OWNED_SIDNO_ANONYMOUS(==-2): the thread
3493 owns an anonymous transaction
3494
3495 - owned_gtid.sidno>0 and owned_gtid.gno>0: the thread owns a GTID
3496 transaction.
3497
3498 - (owned_gtid.sidno==THD::OWNED_SIDNO_GTID_SET(==-1): this is
3499 currently not used. It was reserved for the case where multiple
3500 GTIDs are owned (using gtid_next_list). This was one idea to
3501 make GTIDs work with NDB: due to the epoch concept, multiple
3502 transactions can be combined into one in NDB, and therefore a
3503 single transaction on a slave can have multiple GTIDs.)
3504
3505 ==== Life cycle of ownership ====
3506
3507 Generally, transaction ownership starts when the transaction is
3508 assigned its GTID and ends when the transaction commits or rolls
3509 back. On a master (GTID_NEXT=AUTOMATIC), the GTID is assigned
3510 just before binlog flush; on a slave (GTID_NEXT=UUID:NUMBER or
3511 GTID_NEXT=ANONYMOUS) it is assigned before starting the
3512 transaction.
3513
3514 A new client always starts with owned_gtid.sidno=0.
3515
3516 Ownership can be acquired in the following ways:
3517
3518 A1. If GTID_NEXT = 'AUTOMATIC' and GTID_MODE = OFF/OFF_PERMISSIVE:
3519 The thread acquires anonymous ownership in
3520 gtid_state->generate_automatic_gtid called from
3521 MYSQL_BIN_LOG::write_transaction.
3522
3523 A2. If GTID_NEXT = 'AUTOMATIC' and GTID_MODE = ON/ON_PERMISSIVE:
3524 The thread generates the GTID and acquires ownership in
3525 gtid_state->generate_automatic_gtid called from
3526 MYSQL_BIN_LOG::write_transaction.
3527
3528 A3. If GTID_NEXT = 'UUID:NUMBER': The thread acquires ownership in
3529 the following ways:
3530
3531 - In a client, the SET GTID_NEXT statement acquires ownership.
3532
3533 - The slave's analogy to a clients SET GTID_NEXT statement is
3534 Gtid_log_event::do_apply_event. So the slave acquires
3535 ownership in this function.
3536
3537 Note: if the GTID UUID:NUMBER is already included in
3538 GTID_EXECUTED, then the transaction must be skipped (the GTID
3539 auto-skip feature). Thus, ownership is *not* acquired in this
3540 case and owned_gtid.sidno==0.
3541
3542 A4. If GTID_NEXT = 'ANONYMOUS':
3543
3544 - In a client, the SET GTID_NEXT statement acquires ownership.
3545
3546 - In a slave thread, Gtid_log_event::do_apply_event acquires
3547 ownership.
3548
3549 - Contrary to the case of GTID_NEXT='UUID:NUMBER', it is
3550 allowed to execute two transactions in sequence without
3551 changing GTID_NEXT (cf. R1 and R2 below). Both transactions
3552 should be executed as anonymous transactions. But ownership
3553 is released when the first transaction commits. Therefore,
3554 when GTID_NEXT='ANONYMOUS', we also acquire anonymous
3555 ownership when starting to execute a statement, in
3556 gtid_reacquire_ownership_if_anonymous called from
3557 gtid_pre_statement_checks (usually called from
3558 mysql_execute_command).
3559
3560 A5. Slave applier threads start in a special mode, having
3561 GTID_NEXT='NOT_YET_DETERMINED'. This mode cannot be set in a
3562 regular client. When GTID_NEXT=NOT_YET_DETERMINED, the slave
3563 thread is postponing the decision of the value of GTID_NEXT
3564 until it has more information. There are three cases:
3565
3566 - If the first transaction of the relay log has a
3567 Gtid_log_event, then it will set GTID_NEXT=GTID:NUMBER and
3568 acquire GTID ownership in Gtid_log_event::do_apply_event.
3569
3570 - If the first transaction of the relay log has a
3571 Anonymous_gtid_log_event, then it will set
3572 GTID_NEXT=ANONYMOUS and acquire anonymous ownership in
3573 Gtid_log_event::do_apply_event.
3574
3575 - If the relay log was received from a pre-5.7.6 master with
3576 GTID_MODE=OFF (or a pre-5.6 master), then there are neither
3577 Gtid_log_events nor Anonymous_log_events in the relay log.
3578 In this case, the slave sets GTID_NEXT=ANONYMOUS and
3579 acquires anonymous ownership when executing a
3580 Query_log_event (Query_log_event::do_apply_event calls
3581 dispatch_sql_command which calls gtid_pre_statement_checks which
3582 calls gtid_reacquire_ownership_if_anonymous).
3583
3584 Ownership is released in the following ways:
3585
3586 R1. A thread that holds GTID ownership releases ownership at
3587 transaction commit or rollback. If GTID_NEXT=AUTOMATIC, all
3588 is fine. If GTID_NEXT=UUID:NUMBER, the UUID:NUMBER cannot be
3589 used for another transaction, since only one transaction can
3590 have any given GTID. To avoid the user mistake of forgetting
3591 to set back GTID_NEXT, on commit we set
3592 thd->variables.gtid_next.type=UNDEFINED_GTID. Then, any
3593 statement that user tries to execute other than SET GTID_NEXT
3594 will generate an error.
3595
3596 R2. A thread that holds anonymous ownership releases ownership at
3597 transaction commit or rollback. In this case there is no harm
3598 in leaving GTID_NEXT='ANONYMOUS', so
3599 thd->variables.gtid_next.type will remain ANONYMOUS_GTID and
3600 not UNDEFINED_GTID.
3601
3602 There are statements that generate multiple transactions in the
3603 binary log. This includes the following:
3604
3605 M1. DROP TABLE that is used with multiple tables, and the tables
3606 belong to more than one of the following groups: non-temporary
3607 table, temporary transactional table, temporary
3608 non-transactional table. DROP TABLE is split into one
3609 transaction for each of these groups of tables.
3610
3611 M2. DROP DATABASE that fails e.g. because rmdir fails. Then a
3612 single DROP TABLE is generated, which lists all tables that
3613 were dropped before the failure happened. But if the list of
3614 tables is big, and grows over a limit, the statement will be
3615 split into multiple statements.
3616
3617 M3. CREATE TABLE ... SELECT that is logged in row format. Then
3618 the server generates a single CREATE statement, followed by a
3619 BEGIN ... row events ... COMMIT transaction.
3620
3621 M4. A statement that updates both transactional and
3622 non-transactional tables in the same statement, and is logged
3623 in row format. Then it generates one transaction for the
3624 non-transactional row updates, followed by one transaction for
3625 the transactional row updates.
3626
3627 M5. CALL is executed as multiple transactions and logged as
3628 multiple transactions.
3629
3630 The general rules for multi-transaction statements are:
3631
3632 - If GTID_NEXT=AUTOMATIC and GTID_MODE=ON or ON_PERMISSIVE, one
3633 GTID should be generated for each transaction within the
3634 statement. Therefore, ownership must be released after each
3635 commit so that a new GTID can be generated by the next
3636 transaction. Typically mysql_bin_log.commit() is called to
3637 achieve this. (Note that some of these statements are currently
3638 disallowed when GTID_MODE=ON.)
3639
3640 - If GTID_NEXT=AUTOMATIC and GTID_MODE=OFF or OFF_PERMISSIVE, one
3641 Anonymous_gtid_log_event should be generated for each
3642 transaction within the statement. Similar to the case above, we
3643 call mysql_bin_log.commit() and release ownership between
3644 transactions within the statement.
3645
3646 This works for all the special cases M1-M5 except M4. When a
3647 statement writes both non-transactional and transactional
3648 updates to the binary log, both the transaction cache and the
3649 statement cache are flushed within the same call to
3650 flush_thread_caches(THD) from within the binary log group commit
3651 code. At that point we cannot use mysql_bin_log.commit().
3652 Instead we release ownership using direct calls to
3653 gtid_state->release_anonymous_ownership() and
3654 thd->clear_owned_gtids() from binlog_cache_mngr::flush.
3655
3656 - If GTID_NEXT=ANONYMOUS, anonymous ownership must be *preserved*
3657 between transactions within the statement, to prevent that a
3658 concurrent SET GTID_MODE=ON makes it impossible to log the
3659 statement. To avoid that ownership is released if
3660 mysql_bin_log.commit() is called, we set
3661 thd->is_commit_in_middle_of_statement before calling
3662 mysql_bin_log.commit. Note that we must set this flag only if
3663 GTID_NEXT=ANONYMOUS, not if the transaction is anonymous when
3664 GTID_NEXT=AUTOMATIC and GTID_MODE=OFF.
3665
3666 This works for all the special cases M1-M5 except M4. When a
3667 statement writes non-transactional updates in the middle of a
3668 transaction, but keeps some transactional updates in the
3669 transaction cache, then it is not easy to know at the time of
3670 calling mysql_bin_log.commit() whether anonymous ownership needs
3671 to be preserved or not. Instead, we directly check if the
3672 transaction cache is nonempty before releasing anonymous
3673 ownership inside Gtid_state::update_gtids_impl.
3674
3675 - If GTID_NEXT='UUID:NUMBER', it is impossible to log a
3676 multi-transaction statement, since each GTID can only be used by
3677 one transaction. Therefore, an error must be generated in this
3678 case. Errors are generated in different ways for the different
3679 statement types:
3680
3681 - DROP TABLE: we can detect the situation before it happens,
3682 since the table type is known once the tables are opened. So
3683 we generate an error before even executing the statement.
3684
3685 - DROP DATABASE: we can't detect the situation until it is too
3686 late; the tables have already been dropped and we cannot log
3687 anything meaningful. So we don't log at all.
3688
3689 - CREATE TABLE ... SELECT: this is not allowed when
3690 enforce_gtid_consistency is ON; the statement will be
3691 forbidden in is_ddl_gtid_compatible.
3692
3693 - Statements that update both transactional and
3694 non-transactional tables are disallowed when GTID_MODE=ON, so
3695 this normally does not happen. However, it can happen if the
3696 slave uses a different engine type than the master, so that a
3697 statement that updates InnoDB+InnoDB on master updates
3698 InnoDB+MyISAM on slave. In this case the statement will be
3699 forbidden in is_dml_gtid_compatible and will not be allowed to
3700 execute.
3701
3702 - CALL: the second statement will generate an error because
3703 GTID_NEXT is 'undefined'. Note that this situation can only
3704 happen if user does it on purpose: A CALL on master is logged
3705 as multiple statements, so a slave never executes CALL with
3706 GTID_NEXT='UUID:NUMBER'.
3707
3708 Finally, ownership release is suppressed in one more corner case:
3709
3710 C1. Administration statements including OPTIMIZE TABLE, REPAIR
3711 TABLE, or ANALYZE TABLE are written to the binary log even if
3712 they fail. This means that the thread first calls
3713 trans_rollack, and then writes the statement to the binlog.
3714 Rollback normally releases ownership. But ownership must be
3715 kept until writing the binlog. The solution is that these
3716 statements set thd->skip_gtid_rollback=true before calling
3717 trans_rollback, and Gtid_state::update_on_rollback does not
3718 release ownership if the flag is set.
3719
3720 @todo It would probably be better to encapsulate this more, maybe
3721 use Gtid_specification instead of Gtid.
3722 */
3724 static const int OWNED_SIDNO_GTID_SET = -1;
3725 static const int OWNED_SIDNO_ANONYMOUS = -2;
3726
3727 /**
3728 For convenience, this contains the SID component of the GTID
3729 stored in owned_gtid.
3730 */
3732
3733 /** SE GTID persistence flag types. */
3734 enum Se_GTID_flag : size_t {
3735 /** Pin owned GTID */
3737 /** Cleanup GTID during unpin. */
3739 /** SE would persist GTID for current transaction. */
3741 /** If RESET log in progress. */
3743 /** Explicit request for SE to persist GTID for current transaction. */
3745 /** Max element holding the biset size. */
3748
3749 using Se_GTID_flagset = std::bitset<SE_GTID_MAX>;
3750
3751 /** Flags for SE GTID persistence. */
3753
3754 /** Defer freeing owned GTID and SID till unpinned. */
3756
3757 /** Unpin and free GTID and SID. */
3758 void unpin_gtid() {
3760 /* Do any deferred cleanup */
3764 }
3765 }
3766
3767 /** @return true, if single phase XA commit operation. */
3768 bool is_one_phase_commit();
3769
3770 /** Set when binlog reset operation is started. */
3772
3773 /** Cleared after flushing SE logs during binlog reset. */
3775
3776 /** @return true, if binlog reset operation. */
3778
3779 /** Set by SE when it guarantees GTID persistence. */
3781
3782 /** Request SE to persist GTID explicitly. */
3786 }
3787
3788 /** Reset by SE at transaction end after persisting GTID. */
3792 }
3793
3794 /** @return true, if SE persists GTID for current transaction. */
3795 bool se_persists_gtid() const {
3796 DBUG_EXECUTE_IF("disable_se_persists_gtid", return (false););
3797 auto trx = get_transaction();
3798 auto xid_state = trx->xid_state();
3799 /* XA transactions are always persisted by Innodb. */
3800 return (!xid_state->has_state(XID_STATE::XA_NOTR) ||
3802 }
3803
3804 /** @return true, if SE is explicitly set to persists GTID. */
3806 DBUG_EXECUTE_IF("disable_se_persists_gtid", return (false););
3808 }
3809
3810 /** @return true, if external XA transaction is in progress. */
3811 bool is_extrenal_xa() const {
3812 auto trx = get_transaction();
3813 auto xid_state = trx->xid_state();
3814 return !xid_state->has_state(XID_STATE::XA_NOTR);
3815 }
3816
3817#ifdef HAVE_GTID_NEXT_LIST
3818 /**
3819 If this thread owns a set of GTIDs (i.e., GTID_NEXT_LIST != NULL),
3820 then this member variable contains the subset of those GTIDs that
3821 are owned by this thread.
3822 */
3823 Gtid_set owned_gtid_set;
3824#endif
3825
3826 /*
3827 Replication related context.
3828
3829 @todo: move more parts of replication related fields in THD to inside this
3830 class.
3831 */
3833
3835 /* Defer GTID cleanup if pinned. Used for XA transactions where
3836 SE(Innodb) needs to read GTID. */
3839 return;
3840 }
3842#ifdef HAVE_GTID_NEXT_LIST
3843 owned_gtid_set.clear();
3844#else
3845 assert(0);
3846#endif
3847 }
3848 owned_gtid.clear();
3849 owned_sid.clear();
3850 owned_gtid.dbug_print(nullptr, "set owned_gtid in clear_owned_gtids");
3851 }
3852
3853 /** @return true, if owned GTID is empty or waiting for deferred cleanup. */
3856 return (true);
3857 }
3858 return (owned_gtid.is_empty());
3859 }
3860
3861 /*
3862 There are some statements (like OPTIMIZE TABLE, ANALYZE TABLE and
3863 REPAIR TABLE) that might call trans_rollback_stmt() and also will be
3864 successfully executed and will have to go to the binary log.
3865 For these statements, the skip_gtid_rollback flag must be set to avoid
3866 problems when the statement is executed with a GTID_NEXT set to
3867 ASSIGNED_GTID (like the SQL thread do when applying events from other
3868 server). When this flag is set, a call to gtid_rollback() will do nothing.
3869 */
3871 /*
3872 There are some statements (like DROP DATABASE that fails on rmdir
3873 and gets rewritten to multiple DROP TABLE statements) that may
3874 call trans_commit_stmt() before it has written all statements to
3875 the binlog. When using GTID_NEXT = ANONYMOUS, such statements
3876 should not release ownership of the anonymous transaction until
3877 all statements have been written to the binlog. To prevent that
3878 update_gtid_impl releases ownership, such statements must set this
3879 flag.
3880 */
3882
3883 /*
3884 True while the transaction is executing, if one of
3885 is_ddl_gtid_consistent or is_dml_gtid_consistent returned false.
3886 */
3888
3889 const LEX_CSTRING &db() const { return m_db; }
3890
3891 /**
3892 Set the current database; use deep copy of C-string.
3893
3894 @param new_db the new database name.
3895
3896 Initialize the current database from a NULL-terminated string with
3897 length. If we run out of memory, we free the current database and
3898 return true. This way the user will notice the error as there will be
3899 no current database selected (in addition to the error message set by
3900 malloc).
3901
3902 @note This operation just sets {db, db_length}. Switching the current
3903 database usually involves other actions, like switching other database
3904 attributes including security context. In the future, this operation
3905 will be made private and more convenient interface will be provided.
3906
3907 @return Operation status
3908 @retval false Success
3909 @retval true Out-of-memory error
3910 */
3911 bool set_db(const LEX_CSTRING &new_db);
3912
3913 /**
3914 Set the current database; use shallow copy of C-string.
3915
3916 @param new_db the new database name.
3917
3918 @note This operation just sets {db, db_length}. Switching the current
3919 database usually involves other actions, like switching other database
3920 attributes including security context. In the future, this operation
3921 will be made private and more convenient interface will be provided.
3922 */
3923 void reset_db(const LEX_CSTRING &new_db) {
3924 m_db.str = new_db.str;
3925 m_db.length = new_db.length;
3926#ifdef HAVE_PSI_THREAD_INTERFACE
3927 PSI_THREAD_CALL(set_thread_db)(new_db.str, static_cast<int>(new_db.length));
3928#endif
3929 }
3930 /*
3931 Copy the current database to the argument. Use the current arena to
3932 allocate memory for a deep copy: current database may be freed after
3933 a statement is parsed but before it's executed.
3934 */
3935 bool copy_db_to(char const **p_db, size_t *p_db_length) const {
3936 if (m_db.str == nullptr) {
3937 my_error(ER_NO_DB_ERROR, MYF(0));
3938 return true;
3939 }
3940 *p_db = strmake(m_db.str, m_db.length);
3941 *p_db_length = m_db.length;
3942 return false;
3943 }
3944
3945 bool copy_db_to(char **p_db, size_t *p_db_length) const {
3946 return copy_db_to(const_cast<char const **>(p_db), p_db_length);
3947 }
3948
3950
3951 /**
3952 Get resource group context.
3953
3954 @returns pointer to resource group context.
3955 */
3956
3958 return &m_resource_group_ctx;
3959 }
3960
3961 public:
3962 /**
3963 Save the performance schema thread instrumentation
3964 associated with this user session.
3965 @param psi Performance schema thread instrumentation
3966 */
3967 void set_psi(PSI_thread *psi) { m_psi = psi; }
3968
3969 /**
3970 Read the performance schema thread instrumentation
3971 associated with this user session.
3972 This method is safe to use from a different thread.
3973 */
3974 PSI_thread *get_psi() const { return m_psi; }
3975
3976 private:
3977 /**
3978 Performance schema thread instrumentation for this session.
3979 This member is maintained using atomic operations,
3980 do not access it directly.
3981 @sa set_psi
3982 @sa get_psi
3983 */
3984 std::atomic<PSI_thread *> m_psi;
3985
3986 public:
3988 return m_internal_handler;
3989 }
3990
3991 /**
3992 Add an internal error handler to the thread execution context.
3993 @param handler the exception handler to add
3994 */
3996
3997 private:
3998 /**
3999 Handle a sql condition.
4000 @param sql_errno the condition error number
4001 @param sqlstate the condition sqlstate
4002 @param level the condition level
4003 @param msg the condition message text
4004 @return true if the condition is handled
4005 */
4006 bool handle_condition(uint sql_errno, const char *sqlstate,
4008 const char *msg);
4009
4010 public:
4011 /**
4012 Remove the error handler last pushed.
4013 */
4015
4016 Opt_trace_context opt_trace; ///< optimizer trace of current statement
4017 /**
4018 Raise an exception condition.
4019 @param code the MYSQL_ERRNO error code of the error
4020 */
4021 void raise_error(uint code);
4022
4023 /**
4024 Raise an exception condition, with a formatted message.
4025 @param code the MYSQL_ERRNO error code of the error
4026 */
4027 void raise_error_printf(uint code, ...);
4028
4029 /**
4030 Raise a completion condition (warning).
4031 @param code the MYSQL_ERRNO error code of the warning
4032 */
4033 void raise_warning(uint code);
4034
4035 /**
4036 Raise a completion condition (warning), with a formatted message.
4037 @param code the MYSQL_ERRNO error code of the warning
4038 */
4039 void raise_warning_printf(uint code, ...);
4040
4041 /**
4042 Raise a completion condition (note), with a fixed message.
4043 @param code the MYSQL_ERRNO error code of the note
4044 */
4045 void raise_note(uint code);
4046
4047 /**
4048 Raise an completion condition (note), with a formatted message.
4049 @param code the MYSQL_ERRNO error code of the note
4050 */
4051 void raise_note_printf(uint code, ...);
4052
4053 private:
4054 /*
4055 Only the implementation of the SIGNAL and RESIGNAL statements
4056 is permitted to raise SQL conditions in a generic way,
4057 or to raise them by bypassing handlers (RESIGNAL).
4058 To raise a SQL condition, the code should use the public
4059 raise_error() or raise_warning() methods provided by class THD.
4060 */
4062 friend class Sql_cmd_signal;
4063 friend class Sql_cmd_resignal;
4064 friend void push_warning(THD *thd,
4066 uint code, const char *message_text);
4067 friend void my_message_sql(uint, const char *, myf);
4068
4069 /**
4070 Raise a generic SQL condition. Also calls
4071 mysql_event_tracking_general_notify() unless the condition is handled by a
4072 SQL condition handler.
4073
4074 @param sql_errno the condition error number
4075 @param sqlstate the condition SQLSTATE
4076 @param level the condition level
4077 @param msg the condition message text
4078 @param fatal_error should the fatal_error flag be set?
4079 @return The condition raised, or NULL
4080 */
4081 Sql_condition *raise_condition(uint sql_errno, const char *sqlstate,
4083 const char *msg, bool fatal_error = false);
4084
4085 public:
4087
4088 inline enum enum_server_command get_command() const { return m_command; }
4089
4090 /**
4091 For safe and protected access to the query string, the following
4092 rules should be followed:
4093 1: Only the owner (current_thd) can set the query string.
4094 This will be protected by LOCK_thd_query.
4095 2: The owner (current_thd) can read the query string without
4096 locking LOCK_thd_query.
4097 3: Other threads must lock LOCK_thd_query before reading
4098 the query string.
4099
4100 This means that write-write conflicts are avoided by LOCK_thd_query.
4101 Read(by owner or other thread)-write(other thread) are disallowed.
4102 Read(other thread)-write(by owner) conflicts are avoided by LOCK_thd_query.
4103 Read(by owner)-write(by owner) won't happen as THD=thread.
4104
4105 We want to keep current_thd out of header files, so the debug assert,
4106 is moved to the .cc file. In optimized mode, we want this getter to
4107 be fast, so we inline it.
4108 */
4109 void debug_assert_query_locked() const;
4110 const LEX_CSTRING &query() const {
4111#ifndef NDEBUG
4113#endif
4114 return m_query_string;
4115 }
4116
4117 /**
4118 The current query in normalized form. The format is intended to be
4119 identical to the digest text of performance_schema, but not limited in
4120 size. In this case the parse tree is traversed as opposed to a (limited)
4121 token buffer. The string is allocated by this Statement and will be
4122 available until the next call to this function or this object is deleted.
4123
4124 @note We have no protection against out-of-memory errors as this function
4125 relies on the Item::print() interface which does not propagate errors.
4126
4127 @return The current query in normalized form.
4128 */
4129 const String normalized_query();
4130
4131 /**
4132 Set query to be displayed in performance schema (threads table etc.). Also
4133 mark the query safe to display for information_schema.process_list.
4134 */
4135 void set_query_for_display(const char *query_arg [[maybe_unused]],
4136 size_t query_length_arg [[maybe_unused]]) {
4137 // Set in pfs events statements table
4139 static_cast<uint>(query_length_arg));
4140#ifdef HAVE_PSI_THREAD_INTERFACE
4141 // Set in pfs threads table
4142 PSI_THREAD_CALL(set_thread_info)
4143 (query_arg, static_cast<uint>(query_length_arg));
4144#endif
4145 set_safe_display(true);
4146 }
4147
4148 /**
4149 Reset query string to be displayed in PFS. Also reset the safety flag
4150 for information_schema.process_list for next query.
4151 */
4153 set_query_for_display(nullptr, 0);
4154 m_safe_to_display.store(false);
4155 }
4156
4157 /** @return true, if safe to display the query string. */
4158 bool safe_to_display() const { return m_safe_to_display.load(); }
4159
4160 /** Set if the query string to be safe to display.
4161 @param[in] safe if it is safe to display query string */
4162 void set_safe_display(bool safe) { m_safe_to_display.store(safe); }
4163
4164 /**
4165 Assign a new value to thd->m_query_string.
4166 Protected with the LOCK_thd_query mutex.
4167 */
4168 void set_query(const char *query_arg, size_t query_length_arg) {
4169 const LEX_CSTRING tmp = {query_arg, query_length_arg};
4170 set_query(tmp);
4171 }
4172 void set_query(LEX_CSTRING query_arg);
4174
4175 /**
4176 Set the rewritten query (with passwords obfuscated etc.) on the THD.
4177 Wraps this in the LOCK_thd_query mutex to protect against race conditions
4178 with SHOW PROCESSLIST inspecting that string.
4179
4180 This uses swap() and therefore "steals" the argument from the caller;
4181 the caller MUST take care not to try to use its own string after calling
4182 this function! This is an optimization for mysql_rewrite_query() so we
4183 don't copy its temporary string (which may get very long, up to
4184 @@max_allowed_packet).
4185
4186 Using this outside of mysql_rewrite_query() is almost certainly wrong;
4187 please check with the runtime team!
4188
4189 @param query_arg The rewritten query to use for slow/bin/general logging.
4190 The value will be released in the caller and MUST NOT
4191 be used there after calling this function.
4192 */
4193 void swap_rewritten_query(String &query_arg);
4194
4195 /**
4196 Get the rewritten query (with passwords obfuscated etc.) from the THD.
4197 If done from a different thread (from the one that the rewritten_query
4198 is set on), the caller must hold LOCK_thd_query while calling this!
4199 */
4200 const String &rewritten_query() const {
4201#ifndef NDEBUG
4203#endif
4204 return m_rewritten_query;
4205 }
4206
4207 /**
4208 Reset thd->m_rewritten_query. Protected with the LOCK_thd_query mutex.
4209 */
4211 if (rewritten_query().length()) {
4212 String empty;
4214 }
4215 }
4216
4217 /**
4218 Assign a new value to thd->query_id.
4219 Protected with the LOCK_thd_data mutex.
4220 */
4221 void set_query_id(query_id_t new_query_id) {
4223 query_id = new_query_id;
4226 }
4227
4228 /**
4229 Assign a new value to open_tables.
4230 Protected with the LOCK_thd_data mutex.
4231 */
4232 void set_open_tables(TABLE *open_tables_arg) {
4234 open_tables = open_tables_arg;
4236 }
4237
4238 /**
4239 Assign a new value to is_killable
4240 Protected with the LOCK_thd_data mutex.
4241 */
4242 void set_is_killable(bool is_killable_arg) {
4244 is_killable = is_killable_arg;
4246 }
4247
4249 assert(locked_tables_mode == LTM_NONE);
4250
4251 if (mode_arg == LTM_LOCK_TABLES) {
4252 /*
4253 When entering LOCK TABLES mode we should set explicit duration
4254 for all metadata locks acquired so far in order to avoid releasing
4255 them till UNLOCK TABLES statement.
4256 We don't do this when entering prelocked mode since sub-statements
4257 don't release metadata locks and restoring status-quo after leaving
4258 prelocking mode gets complicated.
4259 */
4261 }
4262
4263 locked_tables_mode = mode_arg;
4264 }
4266 int decide_logging_format(Table_ref *tables);
4267 /**
4268 is_dml_gtid_compatible() and is_ddl_gtid_compatible() check if the
4269 statement that is about to be processed will safely get a
4270 GTID. Currently, the following cases may lead to errors
4271 (e.g. duplicated GTIDs) and as such are forbidden:
4272
4273 1. DML statements that mix non-transactional updates with
4274 transactional updates.
4275
4276 2. Transactions that use non-transactional tables after
4277 having used transactional tables.
4278
4279 3. CREATE...SELECT statement;
4280
4281 4. CREATE TEMPORARY TABLE or DROP TEMPORARY TABLE within a
4282 transaction
4283
4284 The first two conditions have to be checked in
4285 decide_logging_format, because that's where we know if the table
4286 is transactional or not. These are implemented in
4287 is_dml_gtid_compatible().
4288
4289 The third and fourth conditions have to be checked in
4290 mysql_execute_command because (1) that prevents implicit commit
4291 from being executed if the statement fails; (2) DROP TEMPORARY
4292 TABLE does not invoke decide_logging_format. These are
4293 implemented in is_ddl_gtid_compatible().
4294
4295 In the cases where GTID violations generate errors,
4296 is_ddl_gtid_compatible() needs to be called before the implicit
4297 pre-commit, so that there is no implicit commit if the statement
4298 fails.
4299
4300 In the cases where GTID violations do not generate errors,
4301 is_ddl_gtid_compatible() needs to be called after the implicit
4302 pre-commit, because in these cases the function will increase the
4303 global counter automatic_gtid_violating_transaction_count or
4304 anonymous_gtid_violating_transaction_count. If there is an
4305 ongoing transaction, the implicit commit will commit the
4306 transaction, which will call update_gtids_impl, which should
4307 decrease the counters depending on whether the *old* was violating
4308 GTID-consistency or not. Thus, we should increase the counters
4309 only after the old transaction is committed.
4310
4311 @param some_transactional_table true if the statement updates some
4312 transactional table; false otherwise.
4313
4314 @param some_non_transactional_table true if the statement updates
4315 some non-transactional table; false otherwise.
4316
4317 @param non_transactional_tables_are_tmp true if all updated
4318 non-transactional tables are temporary.
4319
4320 @retval true if the statement is compatible;
4321 @retval false if the statement is not compatible.
4322 */
4323 bool is_dml_gtid_compatible(bool some_transactional_table,
4324 bool some_non_transactional_table,
4325 bool non_transactional_tables_are_tmp);
4328 bool need_binlog_invoker() const { return m_binlog_invoker; }
4329 void get_definer(LEX_USER *definer);
4331 m_invoker_user.str = user->str;
4332 m_invoker_user.length = user->length;
4333 m_invoker_host.str = host->str;
4334 m_invoker_host.length = host->length;
4335 }
4338 bool has_invoker() const { return m_invoker_user.str != nullptr; }
4339
4341
4342 private:
4343 /** The current internal error handler for this thread, or NULL. */
4345
4346 /**
4347 This memory root is used for two purposes:
4348 - for conventional queries, to allocate structures stored in main_lex
4349 during parsing, and allocate runtime data (execution plan, etc.)
4350 during execution.
4351 - for prepared queries, only to allocate runtime data. The parsed
4352 tree itself is reused between executions and thus is stored elsewhere.
4353 */
4356 Diagnostics_area m_parser_da; /**< cf. get_parser_da() */
4359
4361
4362 /**
4363 It will be set TRUE if CURRENT_USER() is called in account management
4364 statements or default definer is set in CREATE/ALTER SP, SF, Event,
4365 TRIGGER or VIEW statements.
4366
4367 Current user will be binlogged into Query_log_event if current_user_used
4368 is true; It will be stored into m_invoker_host and m_invoker_user by SQL
4369 thread.
4370 */
4372
4373 /**
4374 It points to the invoker in the Query_log_event.
4375 SQL thread use it as the default definer in CREATE/ALTER SP, SF, Event,
4376 TRIGGER or VIEW statements or current user in account management
4377 statements if it is not NULL.
4378 */
4381
4382 friend class Protocol_classic;
4383
4384 private:
4385 /**
4386 Optimizer cost model for server operations.
4387 */
4390
4391 public:
4392 /**
4393 Initialize the optimizer cost model.
4394
4395 This function should be called each time a new query is started.
4396 */
4397 void init_cost_model();
4398
4399 /**
4400 Retrieve the optimizer cost model for this connection.
4401 */
4402 const Cost_model_server *cost_model() const;
4403
4406
4407 void syntax_error() { syntax_error(ER_SYNTAX_ERROR); }
4408 void syntax_error(const char *format, ...)
4409 MY_ATTRIBUTE((format(printf, 2, 3)));
4410 void syntax_error(int mysql_errno, ...);
4411
4412 void syntax_error_at(const POS &location) {
4413 syntax_error_at(location, ER_SYNTAX_ERROR);
4414 }
4415 void syntax_error_at(const POS &location, const char *format, ...)
4416 MY_ATTRIBUTE((format(printf, 3, 4)));
4417 void syntax_error_at(const POS &location, int mysql_errno, ...);
4418
4419 void vsyntax_error_at(const POS &location, const char *format, va_list args)
4420 MY_ATTRIBUTE((format(printf, 3, 0)));
4421 void vsyntax_error_at(const char *pos_in_lexer_raw_buffer, const char *format,
4422 va_list args) MY_ATTRIBUTE((format(printf, 3, 0)));
4423
4424 /**
4425 Send name and type of result to client.
4426
4427 Sum fields has table name empty and field_name.
4428
4429 @param list List of items to send to client
4430 @param flags Bit mask with the following functions:
4431 - 1 send number of rows
4432 - 2 send default values
4433 - 4 don't write eof packet
4434
4435 @retval
4436 false ok
4437 @retval
4438 true Error (Note that in this case the error is not sent to the client)
4439 */
4440
4441 bool send_result_metadata(const mem_root_deque<Item *> &list, uint flags);
4442
4443 /**
4444 Send one result set row.
4445
4446 @param row_items a collection of column values for that row
4447
4448 @return Error status.
4449 @retval true Error.
4450 @retval false Success.
4451 */
4452
4453 bool send_result_set_row(const mem_root_deque<Item *> &row_items);
4454
4455 /*
4456 Send the status of the current statement execution over network.
4457
4458 In MySQL, there are two types of SQL statements: those that return
4459 a result set and those that return status information only.
4460
4461 If a statement returns a result set, it consists of 3 parts:
4462 - result set meta-data
4463 - variable number of result set rows (can be 0)
4464 - followed and terminated by EOF or ERROR packet
4465
4466 Once the client has seen the meta-data information, it always
4467 expects an EOF or ERROR to terminate the result set. If ERROR is
4468 received, the result set rows are normally discarded (this is up
4469 to the client implementation, libmysql at least does discard them).
4470 EOF, on the contrary, means "successfully evaluated the entire
4471 result set". Since we don't know how many rows belong to a result
4472 set until it's evaluated, EOF/ERROR is the indicator of the end
4473 of the row stream. Note, that we can not buffer result set rows
4474 on the server -- there may be an arbitrary number of rows. But
4475 we do buffer the last packet (EOF/ERROR) in the Diagnostics_area and
4476 delay sending it till the very end of execution (here), to be able to
4477 change EOF to an ERROR if commit failed or some other error occurred
4478 during the last cleanup steps taken after execution.
4479
4480 A statement that does not return a result set doesn't send result
4481 set meta-data either. Instead it returns one of:
4482 - OK packet
4483 - ERROR packet.
4484 Similarly to the EOF/ERROR of the previous statement type, OK/ERROR
4485 packet is "buffered" in the Diagnostics Area and sent to the client
4486 in the end of statement.
4487
4488 @note This method defines a template, but delegates actual
4489 sending of data to virtual Protocol::send_{ok,eof,error}. This
4490 allows for implementation of protocols that "intercept" ok/eof/error
4491 messages, and store them in memory, etc, instead of sending to
4492 the client.
4493
4494 @pre The Diagnostics Area is assigned or disabled. It can not be empty
4495 -- we assume that every SQL statement or COM_* command
4496 generates OK, ERROR, or EOF status.
4497
4498 @post The status information is encoded to protocol format and sent to the
4499 client.
4500
4501 @return We conventionally return void, since the only type of error
4502 that can happen here is a NET (transport) error, and that one
4503 will become visible when we attempt to read from the NET the
4504 next command.
4505 Diagnostics_area::is_sent is set for debugging purposes only.
4506 */
4507
4508 void send_statement_status();
4509
4510 /**
4511 This is only used by master dump threads.
4512 When the master receives a new connection from a slave with a
4513 UUID (for slave versions >= 5.6)/server_id(for slave versions < 5.6)
4514 that is already connected, it will set this flag true
4515 before killing the old slave connection.
4516 */
4518
4519 /**
4520 Claim all the memory used by the THD object.
4521 This method is to keep memory instrumentation statistics
4522 updated, when an object is transferred across threads.
4523 */
4524 void claim_memory_ownership(bool claim);
4525
4528
4529 /**
4530 Returns the plugin, the thd belongs to.
4531 @return pointer to the plugin id
4532 */
4533 const st_plugin_int *get_plugin() const { return m_plugin; }
4534 /**
4535 Sets the plugin id to the value provided as parameter
4536 @param plugin the id of the plugin the thd belongs to
4537 */
4538 void set_plugin(const st_plugin_int *plugin) { m_plugin = plugin; }
4539#ifndef NDEBUG
4541 void set_tmp_table_seq_id(uint arg) { tmp_table_seq_id = arg; }
4542#endif
4543
4546
4547 private:
4548 /**
4549 Variable to mark if the object is part of a Srv_session object, which
4550 aggregates THD.
4551 */
4553
4554 /// Stores the plugin id it is attached to (if any).
4555 const st_plugin_int *m_plugin{nullptr};
4556
4557 /**
4558 Creating or dropping plugin native table through a plugin service.
4559 This variable enables the DDL command execution from
4560 dd::create_native_table() to be executed without committing the
4561 transaction.
4562 */
4564
4565#ifndef NDEBUG
4566 /**
4567 Sequential number of internal tmp table created in the statement. Useful for
4568 tracking tmp tables when number of them is involved in a query.
4569 */
4571
4572 public:
4573 /*
4574 The member serves to guard against duplicate use of the same xid
4575 at binary logging.
4576 */
4578#endif
4579 private:
4580 /*
4581 Flag set by my_write before waiting for disk space.
4582
4583 This is used by replication to decide if the I/O thread should be
4584 killed or not when stopping the replication threads.
4585
4586 In ordinary STOP SLAVE case, the I/O thread will wait for disk space
4587 or to be killed regardless of this flag value.
4588
4589 In server shutdown case, if this flag is true, the I/O thread will be
4590 signaled with KILL_CONNECTION to abort the waiting, letting the server
4591 to shutdown promptly.
4592 */
4594
4595 public:
4596 /**
4597 Set the waiting_for_disk_space flag.
4598
4599 @param waiting The value to set in the flag.
4600 */
4601 void set_waiting_for_disk_space(bool waiting) {
4602 waiting_for_disk_space = waiting;
4603 }
4604 /**
4605 Returns the current waiting_for_disk_space flag value.
4606 */
4608
4609 bool sql_parser();
4610
4611 /// Enables or disables use of secondary storage engines in this session.
4614 }
4615
4616 /**
4617 Can secondary storage engines be used for query execution in
4618 this session?
4619 */
4622 }
4623
4624 /**
4625 Checks if queries in this session can use a secondary storage engine for
4626 execution.
4627
4628 @return true if secondary storage engines can be used in this
4629 session, or false otherwise
4630 */
4632
4633 /// Indicate whether secondary storage engine is forced for this execution
4636 }
4637
4639
4640 private:
4641 /**
4642 This flag tells if a secondary storage engine can be used to
4643 execute a query in this session.
4644 */
4647
4648 /**
4649 Flag that tells whether secondary storage engine is forced for execution.
4650 Notice that use_secondary_engine is not reliable because it may be restored
4651 early.
4652 */
4654
4656 /**
4657 Flag that indicates if the user of current session has SYSTEM_USER privilege
4658 */
4659 std::atomic<bool> m_is_system_user;
4660 /**
4661 Flag that indicates if the user of current session has CONNECTION_ADMIN
4662 privilege
4663 */
4664 std::atomic<bool> m_is_connection_admin;
4665
4666 public:
4667 bool is_system_user();
4668 void set_system_user(bool system_user_flag);
4669
4670 bool is_connection_admin();
4671 void set_connection_admin(bool connection_admin_flag);
4672
4673 public:
4675
4676 /**
4677 Flag to indicate this thread is executing
4678 @ref sys_var::update for a @ref OPT_GLOBAL variable.
4679
4680 This flag imply the thread already holds @ref LOCK_global_system_variables.
4681 Knowing this is required to resolve reentrancy issues
4682 in the system variable code, when callers
4683 read system variable Y while inside an update function
4684 for system variable X.
4685 Executing table io while inside a system variable update function
4686 will indirectly cause this.
4687 @todo Clean up callers and remove m_inside_system_variable_global_update.
4688 */
4690
4691 public:
4692 /** The parameter value bindings for the current query. Allocated on the THD
4693 * memroot. Can be empty */
4695 /** the number of elements in parameters */
4697
4698 public:
4699 /**
4700 Copy session properties that affect table access
4701 from the parent session to the current session.
4702
4703 The following properties:
4704 - the OPTION_BIN_LOG flag,
4705 - the skip_readonly_check flag,
4706 - the transaction isolation (tx_isolation)
4707 are copied from the parent to the current THD.
4708
4709 This is useful to execute an isolated, internal THD session
4710 to access tables, while leaving tables in the parent session
4711 unchanged.
4712
4713 @param thd parent session
4714 */
4718
4721
4722#ifndef NDEBUG
4723 const char *current_key_name;
4727 return (is_error() &&
4728 (get_stmt_da()->mysql_errno() == ER_DA_GLOBAL_CONN_LIMIT ||
4729 get_stmt_da()->mysql_errno() == ER_DA_CONN_LIMIT));
4730 }
4731#endif
4732
4733 public:
4734 bool add_external(unsigned int slot, void *data);
4735 void *fetch_external(unsigned int slot);
4737
4738 private:
4739 std::unordered_map<unsigned int, void *> external_store_;
4740
4741 public:
4743 if (!event_tracking_data_.empty()) return event_tracking_data_.top();
4744 return std::make_pair(Event_tracking_class::LAST, nullptr);
4745 }
4746
4748 unsigned long subevent, bool check_audited);
4749 bool event_notify(struct st_mysql_event_generic *event_data);
4752 }
4753
4754 private:
4758
4760
4764}; // End of class THD
4765
4766/**
4767 Return lock_tables_mode for secondary engine.
4768 @param cthd thread context
4769 @retval true if lock_tables_mode is on
4770 @retval false, otherwise
4771 */
4772inline bool secondary_engine_lock_tables_mode(const THD &cthd) {
4773 return (cthd.locked_tables_mode == LTM_LOCK_TABLES ||
4775}
4776
4777/** A short cut for thd->get_stmt_da()->set_ok_status(). */
4778void my_ok(THD *thd, ulonglong affected_rows = 0, ulonglong id = 0,
4779 const char *message = nullptr);
4780
4781/** A short cut for thd->get_stmt_da()->set_eof_status(). */
4782void my_eof(THD *thd);
4783
4784bool add_item_to_list(THD *thd, Item *item);
4785
4786/*************************************************************************/
4787
4788/**
4789 Check if engine substitution is allowed in the current thread context.
4790
4791 @param thd thread context
4792 @retval true if engine substitution is allowed
4793 @retval false otherwise
4794*/
4795
4796inline bool is_engine_substitution_allowed(const THD *thd) {
4798}
4799
4800/**
4801 Returns if the user of the session has the SYSTEM_USER privilege or not.
4802
4803 @retval true User has SYSTEM_USER privilege
4804 @retval false Otherwise
4805*/
4806inline bool THD::is_system_user() {
4807 return m_is_system_user.load(std::memory_order_seq_cst);
4808}
4809
4810/**
4811 Sets the system_user flag atomically for the current session.
4812
4813 @param [in] system_user_flag boolean flag that indicates value to set.
4814*/
4815inline void THD::set_system_user(bool system_user_flag) {
4816 m_is_system_user.store(system_user_flag, std::memory_order_seq_cst);
4817}
4818
4819/**
4820 Returns if the user of the session has the CONNECTION_ADMIN privilege or not.
4821
4822 @retval true User has CONNECTION_ADMIN privilege
4823 @retval false Otherwise
4824*/
4826 return m_is_connection_admin.load(std::memory_order_seq_cst);
4827}
4828
4829/**
4830 Sets the connection_admin flag atomically for the current session.
4831
4832 @param [in] connection_admin_flag boolean flag that indicates value to set.
4833*/
4834inline void THD::set_connection_admin(bool connection_admin_flag) {
4835 m_is_connection_admin.store(connection_admin_flag, std::memory_order_seq_cst);
4836}
4837
4838/**
4839 Returns true if xa transactions are detached as part of executing XA PREPARE.
4840*/
4841inline bool is_xa_tran_detached_on_prepare(const THD *thd) {
4842 return thd->variables.xa_detach_on_prepare;
4843}
4844
4845#endif /* SQL_CLASS_INCLUDED */
app_data_ptr new_data(u_int n, char *val, cons_type consensus)
Kerberos Client Authentication nullptr
Definition: auth_kerberos_client_plugin.cc:250
int64 query_id_t
Definition: binlog.h:71
API for getting cost estimates for server operations that are not directly related to a table object.
Definition: opt_costmodel.h:53
Stores status of the currently executed statement.
Definition: sql_error.h:268
bool is_error() const
Definition: sql_error.h:365
void reset_diagnostics_area()
Clear this Diagnostics Area.
Definition: sql_error.cc:359
Diagnostics_area * pop_diagnostics_area()
Pop "this" off the Diagnostics Area stack.
Definition: sql_error.cc:636
const Diagnostics_area * stacked_da() const
Returns the Diagnostics Area below the current diagnostics area on the stack.
Definition: sql_error.h:586
void push_diagnostics_area(THD *thd, Diagnostics_area *da, bool copy_conditions)
Push the given Diagnostics Area on top of the stack.
Definition: sql_error.cc:625
List of Discrete_interval objects.
Definition: discrete_interval.h:86
bool append(Discrete_interval *new_interval)
Definition: discrete_interval.h:116
void clear()
Definition: discrete_interval.h:143
Definition: reference_caching_setup.h:108
void refresh_all()
Definition: reference_caching_setup.cc:246
Definition: sql_audit.h:374
An instance of the global read lock in a connection.
Definition: sql_class.h:832
bool can_acquire_protection() const
Check if this connection can acquire protection against GRL and emit error if otherwise.
Definition: sql_class.h:858
MDL_ticket * m_mdl_blocks_commits_lock
Also in order to acquire the global read lock, the connection must acquire a shared metadata lock in ...
Definition: sql_class.h:883
MDL_ticket * m_mdl_global_shared_lock
In order to acquire the global read lock, the connection must acquire shared metadata lock in GLOBAL ...
Definition: sql_class.h:877
enum_grl_state m_state
Definition: sql_class.h:871
bool is_acquired() const
Definition: sql_class.h:866
Global_read_lock()
Definition: sql_class.h:840
static bool global_read_lock_active()
Used by innodb memcached server to check if any connections have global read lock.
Definition: sql_class.h:852
enum_grl_state
Definition: sql_class.h:834
@ GRL_ACQUIRED_AND_BLOCKS_COMMIT
Definition: sql_class.h:837
@ GRL_ACQUIRED
Definition: sql_class.h:836
@ GRL_NONE
Definition: sql_class.h:835
Represents a set of GTIDs.
Definition: rpl_gtid.h:1466
void clear()
Removes all gtids from this Gtid_set.
Definition: rpl_gtid_set.cc:263
Either statement transaction or normal transaction - related thread-specific storage engine data.
Definition: transaction_info.h:402
This class represents the interface for internal error handlers.
Definition: error_handler.h:46
A registry for item tree transformations performed during query optimization.
Definition: sql_class.h:534
bool m_cancel
Definition: sql_class.h:545
Item * old_value
Definition: sql_class.h:543
Item_change_record(Item **place, Item *new_value)
Definition: sql_class.h:540
Item ** place
Definition: sql_class.h:542
Item * new_value
Definition: sql_class.h:544
Item_change_record()=default
Base class that is used to represent any kind of expression in a relational query.
Definition: item.h:932
Definition: sql_list.h:433
Tables that were locked with LOCK TABLES statement.
Definition: locked_tables_list.h:88
An interface to separate the MDL module from the THD, and the rest of the server code.
Definition: mdl.h:84
Context of the owner of metadata locks.
Definition: mdl.h:1411
void set_explicit_duration_for_all_locks()
Set explicit duration for all locks in the context.
Definition: mdl.cc:4631
Savepoint for MDL context.
Definition: mdl.h:1316
A granted metadata lock.
Definition: mdl.h:984
Table modification plan for JOIN-less statements (update/delete)
Definition: opt_explain.h:81
Storage for backup of Open_tables_state.
Definition: sql_class.h:692
MDL_savepoint mdl_system_tables_svp
When we backup the open tables state to open a system table or tables, we want to save state of metad...
Definition: sql_class.h:701
Class that holds information about tables which were opened and locked by the thread.
Definition: sql_class.h:556
MYSQL_LOCK * lock
Definition: sql_class.h:624
TABLE * open_tables
List of regular tables in use by this thread.
Definition: sql_class.h:603
MYSQL_LOCK * extra_lock
Definition: sql_class.h:631
Open_tables_state()
This constructor initializes Open_tables_state instance which can only be used as backup storage.
Definition: sql_class.h:678
uint state_flags
Definition: sql_class.h:671
void reset_open_tables_state()
Definition: sql_class.cc:618
Reprepare_observer * pop_reprepare_observer()
Definition: sql_class.h:590
void push_reprepare_observer(Reprepare_observer *o)
Definition: sql_class.h:586
enum_flags
Definition: sql_class.h:663
@ BACKUPS_AVAIL
Definition: sql_class.h:664
@ SYSTEM_TABLES
Definition: sql_class.h:665
enum enum_locked_tables_mode locked_tables_mode
Definition: sql_class.h:661
Reprepare_observer * get_reprepare_observer() const
Definition: sql_class.h:581
TABLE * temporary_tables
List of temporary tables used by this thread.
Definition: sql_class.h:609
void reset_reprepare_observers()
Definition: sql_class.h:596
void set_open_tables_state(Open_tables_state *state)
Definition: sql_class.cc:603
Prealloced_array< Reprepare_observer *, 4 > m_reprepare_observers
A stack of Reprepare_observer-instances.
Definition: sql_class.h:578
A per-session context which is always available at any point of execution, because in practice it's a...
Definition: opt_trace_context.h:91
Profiling state for a single THD; contains multiple QUERY_PROFILE objects.
Definition: sql_profile.h:225
Internal state of the parser.
Definition: sql_lexer_parser_state.h:43
Plugin array helper class.
Definition: sql_plugin_ref.h:109
A typesafe replacement for DYNAMIC_ARRAY.
Definition: prealloced_array.h:70
Container for all prepared statements created/used in a connection.
Definition: sql_class.h:482
Prepared_statement_map()
Definition: sql_class.cc:2063
void claim_memory_ownership(bool claim)
Definition: sql_class.cc:2125
Prepared_statement * find_by_name(const LEX_CSTRING &name)
Find prepared statement by name.
Definition: sql_class.cc:2100
int insert(Prepared_statement *statement)
Insert a new statement to the thread-local prepared statement map.
Definition: sql_class.cc:2069
Prepared_statement * m_last_found_statement
Definition: sql_class.h:524
~Prepared_statement_map()
Definition: sql_class.cc:2149
void reset()
Definition: sql_class.cc:2131
void erase(Prepared_statement *statement)
Erase all prepared statements (calls Prepared_statement destructor).
Definition: sql_class.cc:2114
collation_unordered_map< std::string, Prepared_statement * > names_hash
Definition: sql_class.h:523
malloc_unordered_map< ulong, std::unique_ptr< Prepared_statement > > st_hash
Definition: sql_class.h:522
Prepared_statement * find(ulong id)
Find prepared statement by ID.
Definition: sql_class.cc:2105
Prepared_statement: a statement that can contain placeholders.
Definition: sql_prepare.h:345
Definition: protocol_classic.h:241
Definition: protocol_classic.h:53
Class used for the old (MySQL 4.0 protocol).
Definition: protocol_classic.h:219
Definition: protocol.h:32
Definition: sql_class.h:347
enum_state get_state() const
Definition: sql_class.h:410
bool is_stmt_prepare_or_first_stmt_execute() const
Definition: sql_class.h:415
T * memdup_typed(const T *mem)
Definition: sql_class.h:433
enum_state
Definition: sql_class.h:366
@ STMT_INITIALIZED
Definition: sql_class.h:367
@ STMT_ERROR
Definition: sql_class.h:372
@ STMT_REGULAR_EXECUTION
Definition: sql_class.h:370
@ STMT_PREPARED
Definition: sql_class.h:369
@ STMT_INITIALIZED_FOR_SP
Definition: sql_class.h:368
@ STMT_EXECUTED
Definition: sql_class.h:371
bool is_repreparing
To check whether a reprepare operation is active.
Definition: sql_class.h:358
bool is_stmt_prepare() const
Definition: sql_class.h:411
LEX_CSTRING strmake(LEX_CSTRING str)
Definition: sql_class.h:440
void reset_item_list()
Definition: sql_class.h:405
char * mem_strdup(const char *str)
Definition: sql_class.h:436
void free_items()
Definition: sql_class.cc:2027
Item * m_item_list
Definition: sql_class.h:353
void * alloc(size_t size)
Definition: sql_class.h:421
Query_arena(MEM_ROOT *mem_root_arg, enum enum_state state_arg)
Definition: sql_class.h:392
bool is_regular() const
Definition: sql_class.h:419
void set_query_arena(const Query_arena &set)
Copies memory-managing members from set.
Definition: sql_class.cc:2038
char * strmake(const char *str, size_t size) const
Definition: sql_class.h:437
enum_state state
Definition: sql_class.h:389
void set_item_list(Item *item)
Definition: sql_class.h:406
void add_item(Item *item)
Definition: sql_class.cc:2022
void * mem_calloc(size_t size)
Definition: sql_class.h:422
void swap_query_arena(const Query_arena &source, Query_arena *backup)
Copy the current arena to backup and set the current arena to match source
Definition: sql_class.cc:2044
void set_state(enum_state state_arg)
Definition: sql_class.h:409
T * alloc_typed()
Definition: sql_class.h:428
Query_arena()
Definition: sql_class.h:399
Item * item_list() const
Definition: sql_class.h:404
bool is_stmt_prepare_or_first_sp_execute() const
Definition: sql_class.h:412
void * memdup(const void *str, size_t size)
Definition: sql_class.h:446
MEM_ROOT * mem_root
Definition: sql_class.h:356
virtual ~Query_arena()=default
Definition: query_result.h:57
Definition: sql_lex.h:2515
Definition: rpl_rli.h:202
An interface that is used to take an action when the locking module notices that a table version has ...
Definition: sql_prepare.h:80
Common base class for all row-containing log events.
Definition: log_event.h:2716
Definition: rpl_context.h:402
A set of THD members describing the current authenticated user.
Definition: sql_security_ctx.h:52
Definition: sys_vars_resource_mgr.h:69
Definition: session_tracker.h:128
Sql_cmd_common_signal represents the common properties of the SIGNAL and RESIGNAL statements.
Definition: sql_signal.h:87
Sql_cmd_resignal represents a RESIGNAL statement.
Definition: sql_signal.h:167
Sql_cmd_signal represents a SIGNAL statement.
Definition: sql_signal.h:147
Representation of a SQL condition.
Definition: sql_error.h:57
enum_severity_level
Enumeration value describing the severity of the condition.
Definition: sql_error.h:62
Using this class is fraught with peril, and you need to be very careful when doing so.
Definition: sql_string.h:166
Used to save context when executing a function or trigger.
Definition: sql_class.h:742
ulonglong option_bits
Definition: sql_class.h:744
bool enable_slow_log
Definition: sql_class.h:753
ulong client_capabilities
Definition: sql_class.h:751
ulonglong first_successful_insert_id_in_cur_stmt
Definition: sql_class.h:746
ha_rows examined_row_count
Definition: sql_class.h:750
SAVEPOINT * savepoints
Definition: sql_class.h:754
ulonglong current_found_rows
Definition: sql_class.h:748
ha_rows sent_row_count
Definition: sql_class.h:750
ulonglong previous_found_rows
Definition: sql_class.h:749
enum enum_check_fields check_for_truncated_fields
Definition: sql_class.h:755
Discrete_intervals_list auto_inc_intervals_forced
Definition: sql_class.h:747
ha_rows num_truncated_fields
Definition: sql_class.h:750
uint in_sub_stmt
Definition: sql_class.h:752
ulonglong first_successful_insert_id_in_prev_stmt
Definition: sql_class.h:745
A derived from THD::Attachable_trx class allows updates in the attachable transaction.
Definition: sql_class.h:2057
bool is_read_only() const override
Definition: sql_class.h:2059
Attachable_trx_rw(const Attachable_trx_rw &)
Attachable_trx_rw & operator=(const Attachable_trx_rw &)
Attachable_trx_rw(THD *thd)
Definition: sql_class.cc:534
Class representing read-only attachable transaction, encapsulates knowledge how to backup state of cu...
Definition: sql_class.h:2014
THD * m_thd
THD instance.
Definition: sql_class.h:2025
Transaction_state m_trx_state
Transaction state data.
Definition: sql_class.h:2036