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