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