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