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