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