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