1 #ifndef TABLE_INCLUDED
2 #define TABLE_INCLUDED
3 /* Copyright (c) 2000, 2017, Oracle and/or its affiliates.
4    Copyright (c) 2009, 2021, MariaDB
5 
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; version 2 of the License.
9 
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14 
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335  USA */
18 
19 #include "sql_plist.h"
20 #include "sql_list.h"                           /* Sql_alloc */
21 #include "mdl.h"
22 #include "datadict.h"
23 #include "sql_string.h"                         /* String */
24 #include "lex_string.h"
25 
26 #ifndef MYSQL_CLIENT
27 
28 #include "hash.h"                               /* HASH */
29 #include "handler.h"                /* row_type, ha_choice, handler */
30 #include "mysql_com.h"              /* enum_field_types */
31 #include "thr_lock.h"                  /* thr_lock_type */
32 #include "filesort_utils.h"
33 #include "parse_file.h"
34 
35 /* Structs that defines the TABLE */
36 
37 class Item;				/* Needed by ORDER */
38 typedef Item (*Item_ptr);
39 class Item_subselect;
40 class Item_field;
41 class GRANT_TABLE;
42 class st_select_lex_unit;
43 class st_select_lex;
44 class partition_info;
45 class COND_EQUAL;
46 class Security_context;
47 struct TABLE_LIST;
48 class ACL_internal_schema_access;
49 class ACL_internal_table_access;
50 class Field;
51 class Table_statistics;
52 class With_element;
53 struct TDC_element;
54 class Virtual_column_info;
55 class Table_triggers_list;
56 class TMP_TABLE_PARAM;
57 class SEQUENCE;
58 struct Name_resolution_context;
59 
60 /*
61   Used to identify NESTED_JOIN structures within a join (applicable only to
62   structures that have not been simplified away and embed more the one
63   element)
64 */
65 typedef ulonglong nested_join_map;
66 
67 
68 #define tmp_file_prefix "#sql"			/**< Prefix for tmp tables */
69 #define tmp_file_prefix_length 4
70 #define TMP_TABLE_KEY_EXTRA 8
71 
72 /**
73   Enumerate possible types of a table from re-execution
74   standpoint.
75   TABLE_LIST class has a member of this type.
76   At prepared statement prepare, this member is assigned a value
77   as of the current state of the database. Before (re-)execution
78   of a prepared statement, we check that the value recorded at
79   prepare matches the type of the object we obtained from the
80   table definition cache.
81 
82   @sa check_and_update_table_version()
83   @sa Execute_observer
84   @sa Prepared_statement::reprepare()
85 */
86 
87 enum enum_table_ref_type
88 {
89   /** Initial value set by the parser */
90   TABLE_REF_NULL= 0,
91   TABLE_REF_VIEW,
92   TABLE_REF_BASE_TABLE,
93   TABLE_REF_I_S_TABLE,
94   TABLE_REF_TMP_TABLE
95 };
96 
97 
98 /*************************************************************************/
99 
100 /**
101  Object_creation_ctx -- interface for creation context of database objects
102  (views, stored routines, events, triggers). Creation context -- is a set
103  of attributes, that should be fixed at the creation time and then be used
104  each time the object is parsed or executed.
105 */
106 
107 class Object_creation_ctx
108 {
109 public:
110   Object_creation_ctx *set_n_backup(THD *thd);
111 
112   void restore_env(THD *thd, Object_creation_ctx *backup_ctx);
113 
114 protected:
Object_creation_ctx()115   Object_creation_ctx() {}
116   virtual Object_creation_ctx *create_backup_ctx(THD *thd) const = 0;
117 
118   virtual void change_env(THD *thd) const = 0;
119 
120 public:
~Object_creation_ctx()121   virtual ~Object_creation_ctx()
122   { }
123 };
124 
125 /*************************************************************************/
126 
127 /**
128  Default_object_creation_ctx -- default implementation of
129  Object_creation_ctx.
130 */
131 
132 class Default_object_creation_ctx : public Object_creation_ctx
133 {
134 public:
get_client_cs()135   CHARSET_INFO *get_client_cs()
136   {
137     return m_client_cs;
138   }
139 
get_connection_cl()140   CHARSET_INFO *get_connection_cl()
141   {
142     return m_connection_cl;
143   }
144 
145 protected:
146   Default_object_creation_ctx(THD *thd);
147 
148   Default_object_creation_ctx(CHARSET_INFO *client_cs,
149                               CHARSET_INFO *connection_cl);
150 
151 protected:
152   virtual Object_creation_ctx *create_backup_ctx(THD *thd) const;
153 
154   virtual void change_env(THD *thd) const;
155 
156 protected:
157   /**
158     client_cs stores the value of character_set_client session variable.
159     The only character set attribute is used.
160 
161     Client character set is included into query context, because we save
162     query in the original character set, which is client character set. So,
163     in order to parse the query properly we have to switch client character
164     set on parsing.
165   */
166   CHARSET_INFO *m_client_cs;
167 
168   /**
169     connection_cl stores the value of collation_connection session
170     variable. Both character set and collation attributes are used.
171 
172     Connection collation is included into query context, becase it defines
173     the character set and collation of text literals in internal
174     representation of query (item-objects).
175   */
176   CHARSET_INFO *m_connection_cl;
177 };
178 
179 class Query_arena;
180 
181 /*************************************************************************/
182 
183 /**
184  View_creation_ctx -- creation context of view objects.
185 */
186 
187 class View_creation_ctx : public Default_object_creation_ctx,
188                           public Sql_alloc
189 {
190 public:
191   static View_creation_ctx *create(THD *thd);
192 
193   static View_creation_ctx *create(THD *thd,
194                                    TABLE_LIST *view);
195 
196 private:
View_creation_ctx(THD * thd)197   View_creation_ctx(THD *thd)
198     : Default_object_creation_ctx(thd)
199   { }
200 };
201 
202 /*************************************************************************/
203 
204 /* Order clause list element */
205 
206 typedef int (*fast_field_copier)(Field *to, Field *from);
207 
208 
209 typedef struct st_order {
210   struct st_order *next;
211   Item	 **item;			/* Point at item in select fields */
212   Item	 *item_ptr;			/* Storage for initial item */
213   /*
214     Reference to the function we are trying to optimize copy to
215     a temporary table
216   */
217   fast_field_copier fast_field_copier_func;
218   /* Field for which above optimizer function setup */
219   Field  *fast_field_copier_setup;
220   int    counter;                       /* position in SELECT list, correct
221                                            only if counter_used is true*/
222   enum enum_order {
223     ORDER_NOT_RELEVANT,
224     ORDER_ASC,
225     ORDER_DESC
226   };
227 
228   enum_order direction;                 /* Requested direction of ordering */
229   bool	 in_field_list;			/* true if in select field list */
230   bool   counter_used;                  /* parameter was counter of columns */
231   Field  *field;			/* If tmp-table group */
232   char	 *buff;				/* If tmp-table group */
233   table_map used; /* NOTE: the below is only set to 0 but is still used by eq_ref_table */
234   table_map depend_map;
235 } ORDER;
236 
237 /**
238   State information for internal tables grants.
239   This structure is part of the TABLE_LIST, and is updated
240   during the ACL check process.
241   @sa GRANT_INFO
242 */
243 struct st_grant_internal_info
244 {
245   /** True if the internal lookup by schema name was done. */
246   bool m_schema_lookup_done;
247   /** Cached internal schema access. */
248   const ACL_internal_schema_access *m_schema_access;
249   /** True if the internal lookup by table name was done. */
250   bool m_table_lookup_done;
251   /** Cached internal table access. */
252   const ACL_internal_table_access *m_table_access;
253 };
254 typedef struct st_grant_internal_info GRANT_INTERNAL_INFO;
255 
256 /**
257    @brief The current state of the privilege checking process for the current
258    user, SQL statement and SQL object.
259 
260    @details The privilege checking process is divided into phases depending on
261    the level of the privilege to be checked and the type of object to be
262    accessed. Due to the mentioned scattering of privilege checking
263    functionality, it is necessary to keep track of the state of the
264    process. This information is stored in privilege, want_privilege, and
265    orig_want_privilege.
266 
267    A GRANT_INFO also serves as a cache of the privilege hash tables. Relevant
268    members are grant_table and version.
269  */
270 typedef struct st_grant_info
271 {
272   /**
273      @brief A copy of the privilege information regarding the current host,
274      database, object and user.
275 
276      @details The version of this copy is found in GRANT_INFO::version.
277    */
278   GRANT_TABLE *grant_table_user;
279   GRANT_TABLE *grant_table_role;
280   /**
281      @brief Used for cache invalidation when caching privilege information.
282 
283      @details The privilege information is stored on disk, with dedicated
284      caches residing in memory: table-level and column-level privileges,
285      respectively, have their own dedicated caches.
286 
287      The GRANT_INFO works as a level 1 cache with this member updated to the
288      current value of the global variable @c grant_version (@c static variable
289      in sql_acl.cc). It is updated Whenever the GRANT_INFO is refreshed from
290      the level 2 cache. The level 2 cache is the @c column_priv_hash structure
291      (@c static variable in sql_acl.cc)
292 
293      @see grant_version
294    */
295   uint version;
296   /**
297      @brief The set of privileges that the current user has fulfilled for a
298      certain host, database, and object.
299 
300      @details This field is continually updated throughout the access checking
301      process. In each step the "wanted privilege" is checked against the
302      fulfilled privileges. When/if the intersection of these sets is empty,
303      access is granted.
304 
305      The set is implemented as a bitmap, with the bits defined in sql_acl.h.
306    */
307   ulong privilege;
308   /**
309      @brief the set of privileges that the current user needs to fulfil in
310      order to carry out the requested operation.
311    */
312   ulong want_privilege;
313   /**
314     Stores the requested access acl of top level tables list. Is used to
315     check access rights to the underlying tables of a view.
316   */
317   ulong orig_want_privilege;
318   /** The grant state for internal tables. */
319   GRANT_INTERNAL_INFO m_internal;
320 } GRANT_INFO;
321 
322 enum tmp_table_type
323 {
324   NO_TMP_TABLE= 0, NON_TRANSACTIONAL_TMP_TABLE, TRANSACTIONAL_TMP_TABLE,
325   INTERNAL_TMP_TABLE, SYSTEM_TMP_TABLE
326 };
327 enum release_type { RELEASE_NORMAL, RELEASE_WAIT_FOR_DROP };
328 
329 
330 enum vcol_init_mode
331 {
332   VCOL_INIT_DEPENDENCY_FAILURE_IS_WARNING= 1,
333   VCOL_INIT_DEPENDENCY_FAILURE_IS_ERROR= 2
334   /*
335     There may be new flags here.
336     e.g. to automatically remove sql_mode dependency:
337       GENERATED ALWAYS AS (char_col) ->
338       GENERATED ALWAYS AS (RTRIM(char_col))
339   */
340 };
341 
342 
343 enum enum_vcol_update_mode
344 {
345   VCOL_UPDATE_FOR_READ= 0,
346   VCOL_UPDATE_FOR_WRITE,
347   VCOL_UPDATE_FOR_DELETE,
348   VCOL_UPDATE_INDEXED,
349   VCOL_UPDATE_INDEXED_FOR_UPDATE,
350   VCOL_UPDATE_FOR_REPLACE
351 };
352 
353 /* Field visibility enums */
354 
355 enum field_visibility_t {
356   VISIBLE= 0,
357   INVISIBLE_USER,
358   /* automatically added by the server. Can be queried explicitly
359   in SELECT, otherwise invisible from anything" */
360   INVISIBLE_SYSTEM,
361   INVISIBLE_FULL
362 };
363 
364 #define INVISIBLE_MAX_BITS 3
365 
366 
367 /**
368   Category of table found in the table share.
369 */
370 enum enum_table_category
371 {
372   /**
373     Unknown value.
374   */
375   TABLE_UNKNOWN_CATEGORY=0,
376 
377   /**
378     Temporary table.
379     The table is visible only in the session.
380     Therefore,
381     - FLUSH TABLES WITH READ LOCK
382     - SET GLOBAL READ_ONLY = ON
383     do not apply to this table.
384     Note that LOCK TABLE t FOR READ/WRITE
385     can be used on temporary tables.
386     Temporary tables are not part of the table cache.
387   */
388   TABLE_CATEGORY_TEMPORARY=1,
389 
390   /**
391     User table.
392     These tables do honor:
393     - LOCK TABLE t FOR READ/WRITE
394     - FLUSH TABLES WITH READ LOCK
395     - SET GLOBAL READ_ONLY = ON
396     User tables are cached in the table cache.
397   */
398   TABLE_CATEGORY_USER=2,
399 
400   /**
401     System table, maintained by the server.
402     These tables do honor:
403     - LOCK TABLE t FOR READ/WRITE
404     - FLUSH TABLES WITH READ LOCK
405     - SET GLOBAL READ_ONLY = ON
406     Typically, writes to system tables are performed by
407     the server implementation, not explicitly be a user.
408     System tables are cached in the table cache.
409   */
410   TABLE_CATEGORY_SYSTEM=3,
411 
412   /**
413     Information schema tables.
414     These tables are an interface provided by the system
415     to inspect the system metadata.
416     These tables do *not* honor:
417     - LOCK TABLE t FOR READ/WRITE
418     - FLUSH TABLES WITH READ LOCK
419     - SET GLOBAL READ_ONLY = ON
420     as there is no point in locking explicitly
421     an INFORMATION_SCHEMA table.
422     Nothing is directly written to information schema tables.
423     Note that this value is not used currently,
424     since information schema tables are not shared,
425     but implemented as session specific temporary tables.
426   */
427   /*
428     TODO: Fixing the performance issues of I_S will lead
429     to I_S tables in the table cache, which should use
430     this table type.
431   */
432   TABLE_CATEGORY_INFORMATION=4,
433 
434   /**
435     Log tables.
436     These tables are an interface provided by the system
437     to inspect the system logs.
438     These tables do *not* honor:
439     - LOCK TABLE t FOR READ/WRITE
440     - FLUSH TABLES WITH READ LOCK
441     - SET GLOBAL READ_ONLY = ON
442     as there is no point in locking explicitly
443     a LOG table.
444     An example of LOG tables are:
445     - mysql.slow_log
446     - mysql.general_log,
447     which *are* updated even when there is either
448     a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
449     User queries do not write directly to these tables
450     (there are exceptions for log tables).
451     The server implementation perform writes.
452     Log tables are cached in the table cache.
453   */
454   TABLE_CATEGORY_LOG=5,
455 
456   /**
457     Performance schema tables.
458     These tables are an interface provided by the system
459     to inspect the system performance data.
460     These tables do *not* honor:
461     - LOCK TABLE t FOR READ/WRITE
462     - FLUSH TABLES WITH READ LOCK
463     - SET GLOBAL READ_ONLY = ON
464     as there is no point in locking explicitly
465     a PERFORMANCE_SCHEMA table.
466     An example of PERFORMANCE_SCHEMA tables are:
467     - performance_schema.*
468     which *are* updated (but not using the handler interface)
469     even when there is either
470     a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
471     User queries do not write directly to these tables
472     (there are exceptions for SETUP_* tables).
473     The server implementation perform writes.
474     Performance tables are cached in the table cache.
475   */
476   TABLE_CATEGORY_PERFORMANCE=6
477 };
478 typedef enum enum_table_category TABLE_CATEGORY;
479 
480 TABLE_CATEGORY get_table_category(const LEX_CSTRING *db,
481                                   const LEX_CSTRING *name);
482 
483 
484 typedef struct st_table_field_type
485 {
486   LEX_CSTRING name;
487   LEX_CSTRING type;
488   LEX_CSTRING cset;
489 } TABLE_FIELD_TYPE;
490 
491 
492 typedef struct st_table_field_def
493 {
494   uint count;
495   const TABLE_FIELD_TYPE *field;
496   uint primary_key_parts;
497   const uint *primary_key_columns;
498 } TABLE_FIELD_DEF;
499 
500 
501 class Table_check_intact
502 {
503 protected:
504   bool has_keys;
505   virtual void report_error(uint code, const char *fmt, ...)= 0;
506 
507 public:
has_keys(keys)508   Table_check_intact(bool keys= false) : has_keys(keys) {}
~Table_check_intact()509   virtual ~Table_check_intact() {}
510 
511   /** Checks whether a table is intact. */
512   bool check(TABLE *table, const TABLE_FIELD_DEF *table_def);
513 };
514 
515 
516 /*
517   If the table isn't valid, report the error to the server log only.
518 */
519 class Table_check_intact_log_error : public Table_check_intact
520 {
521 protected:
522   void report_error(uint, const char *fmt, ...);
523 public:
Table_check_intact_log_error()524   Table_check_intact_log_error() : Table_check_intact(true) {}
525 };
526 
527 
528 /**
529   Class representing the fact that some thread waits for table
530   share to be flushed. Is used to represent information about
531   such waits in MDL deadlock detector.
532 */
533 
534 class Wait_for_flush : public MDL_wait_for_subgraph
535 {
536   MDL_context *m_ctx;
537   TABLE_SHARE *m_share;
538   uint m_deadlock_weight;
539 public:
Wait_for_flush(MDL_context * ctx_arg,TABLE_SHARE * share_arg,uint deadlock_weight_arg)540   Wait_for_flush(MDL_context *ctx_arg, TABLE_SHARE *share_arg,
541                uint deadlock_weight_arg)
542     : m_ctx(ctx_arg), m_share(share_arg),
543       m_deadlock_weight(deadlock_weight_arg)
544   {}
545 
get_ctx()546   MDL_context *get_ctx() const { return m_ctx; }
547 
548   virtual bool accept_visitor(MDL_wait_for_graph_visitor *dvisitor);
549 
550   virtual uint get_deadlock_weight() const;
551 
552   /**
553     Pointers for participating in the list of waiters for table share.
554   */
555   Wait_for_flush *next_in_share;
556   Wait_for_flush **prev_in_share;
557 };
558 
559 
560 typedef I_P_List <Wait_for_flush,
561                   I_P_List_adapter<Wait_for_flush,
562                                    &Wait_for_flush::next_in_share,
563                                    &Wait_for_flush::prev_in_share> >
564                  Wait_for_flush_list;
565 
566 
567 enum open_frm_error {
568   OPEN_FRM_OK = 0,
569   OPEN_FRM_OPEN_ERROR,
570   OPEN_FRM_READ_ERROR,
571   OPEN_FRM_CORRUPTED,
572   OPEN_FRM_DISCOVER,
573   OPEN_FRM_ERROR_ALREADY_ISSUED,
574   OPEN_FRM_NOT_A_VIEW,
575   OPEN_FRM_NOT_A_TABLE,
576   OPEN_FRM_NEEDS_REBUILD
577 };
578 
579 /**
580   Control block to access table statistics loaded
581   from persistent statistical tables
582 */
583 
584 class TABLE_STATISTICS_CB
585 {
586   class Statistics_state
587   {
588     enum state_codes
589     {
590       EMPTY,   /** data is not loaded */
591       LOADING, /** data is being loaded in some connection */
592       READY    /** data is loaded and available for use */
593     };
594     int32 state;
595 
596   public:
597     /** No state copy */
598     Statistics_state &operator=(const Statistics_state &) { return *this; }
599 
600     /** Checks if data loading have been completed */
is_ready()601     bool is_ready() const
602     {
603       return my_atomic_load32_explicit(const_cast<int32*>(&state),
604                                        MY_MEMORY_ORDER_ACQUIRE) == READY;
605     }
606 
607     /**
608       Sets mutual exclusion for data loading
609 
610       If stats are in LOADING state, waits until state change.
611 
612       @return
613         @retval true atomic EMPTY -> LOADING transfer completed, ok to load
614         @retval false stats are in READY state, no need to load
615     */
start_load()616     bool start_load()
617     {
618       for (;;)
619       {
620         int32 expected= EMPTY;
621         if (my_atomic_cas32_weak_explicit(&state, &expected, LOADING,
622                                           MY_MEMORY_ORDER_RELAXED,
623                                           MY_MEMORY_ORDER_RELAXED))
624           return true;
625         if (expected == READY)
626           return false;
627         (void) LF_BACKOFF();
628       }
629     }
630 
631     /** Marks data available for subsequent use */
end_load()632     void end_load()
633     {
634       DBUG_ASSERT(my_atomic_load32_explicit(&state, MY_MEMORY_ORDER_RELAXED) ==
635                   LOADING);
636       my_atomic_store32_explicit(&state, READY, MY_MEMORY_ORDER_RELEASE);
637     }
638 
639     /** Restores empty state on error (e.g. OOM) */
abort_load()640     void abort_load()
641     {
642       DBUG_ASSERT(my_atomic_load32_explicit(&state, MY_MEMORY_ORDER_RELAXED) ==
643                   LOADING);
644       my_atomic_store32_explicit(&state, EMPTY, MY_MEMORY_ORDER_RELAXED);
645     }
646   };
647 
648   class Statistics_state stats_state;
649   class Statistics_state hist_state;
650 
651 public:
652   MEM_ROOT  mem_root; /* MEM_ROOT to allocate statistical data for the table */
653   Table_statistics *table_stats; /* Structure to access the statistical data */
654   ulong total_hist_size;         /* Total size of all histograms */
655 
histograms_are_ready()656   bool histograms_are_ready() const
657   {
658     return !total_hist_size || hist_state.is_ready();
659   }
660 
start_histograms_load()661   bool start_histograms_load()
662   {
663     return total_hist_size && hist_state.start_load();
664   }
665 
end_histograms_load()666   void end_histograms_load() { hist_state.end_load(); }
abort_histograms_load()667   void abort_histograms_load() { hist_state.abort_load(); }
stats_are_ready()668   bool stats_are_ready() const { return stats_state.is_ready(); }
start_stats_load()669   bool start_stats_load() { return stats_state.start_load(); }
end_stats_load()670   void end_stats_load() { stats_state.end_load(); }
abort_stats_load()671   void abort_stats_load() { stats_state.abort_load(); }
672 };
673 
674 /**
675   This structure is shared between different table objects. There is one
676   instance of table share per one table in the database.
677 */
678 
679 struct TABLE_SHARE
680 {
TABLE_SHARETABLE_SHARE681   TABLE_SHARE() {}                    /* Remove gcc warning */
682 
683   /** Category of this table. */
684   TABLE_CATEGORY table_category;
685 
686   /* hash of field names (contains pointers to elements of field array) */
687   HASH	name_hash;			/* hash of field names */
688   MEM_ROOT mem_root;
689   TYPELIB keynames;			/* Pointers to keynames */
690   TYPELIB fieldnames;			/* Pointer to fieldnames */
691   TYPELIB *intervals;			/* pointer to interval info */
692   mysql_mutex_t LOCK_ha_data;           /* To protect access to ha_data */
693   mysql_mutex_t LOCK_share;             /* To protect TABLE_SHARE */
694 
695   TDC_element *tdc;
696 
697   LEX_CUSTRING tabledef_version;
698 
699   engine_option_value *option_list;     /* text options for table */
700   ha_table_option_struct *option_struct; /* structure with parsed options */
701 
702   /* The following is copied to each TABLE on OPEN */
703   Field **field;
704   Field **found_next_number_field;
705   KEY  *key_info;			/* data of keys in database */
706   Virtual_column_info **check_constraints;
707   uint	*blob_field;			/* Index to blobs in Field arrray*/
708   LEX_CUSTRING vcol_defs;              /* definitions of generated columns */
709 
710   TABLE_STATISTICS_CB stats_cb;
711 
712   uchar	*default_values;		/* row with default values */
713   LEX_CSTRING comment;			/* Comment about table */
714   CHARSET_INFO *table_charset;		/* Default charset of string fields */
715 
716   MY_BITMAP *check_set;                 /* Fields used by check constrant */
717   MY_BITMAP all_set;
718   /*
719     Key which is used for looking-up table in table cache and in the list
720     of thread's temporary tables. Has the form of:
721       "database_name\0table_name\0" + optional part for temporary tables.
722 
723     Note that all three 'table_cache_key', 'db' and 'table_name' members
724     must be set (and be non-zero) for tables in table cache. They also
725     should correspond to each other.
726     To ensure this one can use set_table_cache() methods.
727   */
728   LEX_CSTRING table_cache_key;
729   LEX_CSTRING db;                        /* Pointer to db */
730   LEX_CSTRING table_name;                /* Table name (for open) */
731   LEX_CSTRING path;                	/* Path to .frm file (from datadir) */
732   LEX_CSTRING normalized_path;		/* unpack_filename(path) */
733   LEX_CSTRING connect_string;
734 
735   /*
736      Set of keys in use, implemented as a Bitmap.
737      Excludes keys disabled by ALTER TABLE ... DISABLE KEYS.
738   */
739   key_map keys_in_use;
740   key_map keys_for_keyread;
741   ha_rows min_rows, max_rows;		/* create information */
742   ulong   avg_row_length;		/* create information */
743   ulong   mysql_version;		/* 0 if .frm is created before 5.0 */
744   ulong   reclength;			/* Recordlength */
745   /* Stored record length. No generated-only virtual fields are included */
746   ulong   stored_rec_length;
747 
748   plugin_ref db_plugin;			/* storage engine plugin */
db_typeTABLE_SHARE749   inline handlerton *db_type() const	/* table_type for handler */
750   {
751     return is_view   ? view_pseudo_hton :
752            db_plugin ? plugin_hton(db_plugin) : NULL;
753   }
754   enum row_type row_type;		/* How rows are stored */
755   enum Table_type table_type;
756   enum tmp_table_type tmp_table;
757 
758   /** Transactional or not. */
759   enum ha_choice transactional;
760   /** Per-page checksums or not. */
761   enum ha_choice page_checksum;
762 
763   uint key_block_size;			/* create key_block_size, if used */
764   uint stats_sample_pages;		/* number of pages to sample during
765 					stats estimation, if used, otherwise 0. */
766   enum_stats_auto_recalc stats_auto_recalc; /* Automatic recalc of stats. */
767   uint null_bytes, last_null_bit_pos;
768   /*
769     Same as null_bytes, except that if there is only a 'delete-marker' in
770     the record then this value is 0.
771   */
772   uint null_bytes_for_compare;
773   uint fields;                          /* number of fields */
774   /* number of stored fields, purely virtual not included */
775   uint stored_fields;
776   uint virtual_fields;                  /* number of purely virtual fields */
777   /* number of purely virtual not stored blobs */
778   uint virtual_not_stored_blob_fields;
779   uint null_fields;                     /* number of null fields */
780   uint blob_fields;                     /* number of blob fields */
781   uint varchar_fields;                  /* number of varchar fields */
782   uint default_fields;                  /* number of default fields */
783   uint visible_fields;                  /* number of visible fields */
784 
785   uint default_expressions;
786   uint table_check_constraints, field_check_constraints;
787 
788   uint rec_buff_length;                 /* Size of table->record[] buffer */
789   uint keys, key_parts;
790   uint ext_key_parts;       /* Total number of key parts in extended keys */
791   uint max_key_length, max_unique_length;
792   uint uniques;                         /* Number of UNIQUE index */
793   uint db_create_options;		/* Create options from database */
794   uint db_options_in_use;		/* Options in use */
795   uint db_record_offset;		/* if HA_REC_IN_SEQ */
796   uint rowid_field_offset;		/* Field_nr +1 to rowid field */
797   /* Primary key index number, used in TABLE::key_info[] */
798   uint primary_key;
799   uint next_number_index;               /* autoincrement key number */
800   uint next_number_key_offset;          /* autoinc keypart offset in a key */
801   uint next_number_keypart;             /* autoinc keypart number in a key */
802   enum open_frm_error error;            /* error from open_table_def() */
803   uint open_errno;                      /* error from open_table_def() */
804   uint column_bitmap_size;
805   uchar frm_version;
806 
807   enum enum_v_keys { NOT_INITIALIZED=0, NO_V_KEYS, V_KEYS };
808   enum_v_keys check_set_initialized;
809 
810   bool use_ext_keys;                    /* Extended keys can be used */
811   bool null_field_first;
812   bool system;                          /* Set if system table (one record) */
813   bool not_usable_by_query_cache;
814   /*
815     This is used by log tables, for tables that have their own internal
816     binary logging or for tables that doesn't support statement or row logging
817    */
818   bool no_replicate;
819   bool crashed;
820   bool is_view;
821   bool can_cmp_whole_record;
822   /* This is set for temporary tables where CREATE was binary logged */
823   bool table_creation_was_logged;
824   bool non_determinstic_insert;
825   bool vcols_need_refixing;
826   bool has_update_default_function;
827   bool can_do_row_logging;              /* 1 if table supports RBR */
828   ulong table_map_id;                   /* for row-based replication */
829 
830   /*
831     Things that are incompatible between the stored version and the
832     current version. This is a set of HA_CREATE... bits that can be used
833     to modify create_info->used_fields for ALTER TABLE.
834   */
835   ulong incompatible_version;
836 
837   /**
838     For shares representing views File_parser object with view
839     definition read from .FRM file.
840   */
841   const File_parser *view_def;
842 
843   /* For sequence tables, the current sequence state */
844   SEQUENCE *sequence;
845 
846 #ifdef WITH_PARTITION_STORAGE_ENGINE
847   /* filled in when reading from frm */
848   bool auto_partitioned;
849   char *partition_info_str;
850   uint  partition_info_str_len;
851   uint  partition_info_buffer_size;
852   plugin_ref default_part_plugin;
853 #endif
854 
855   /**
856     System versioning support.
857    */
858 
859   vers_sys_type_t versioned;
860   uint16 row_start_field;
861   uint16 row_end_field;
862 
vers_start_fieldTABLE_SHARE863   Field *vers_start_field()
864   {
865     return field[row_start_field];
866   }
867 
vers_end_fieldTABLE_SHARE868   Field *vers_end_field()
869   {
870     return field[row_end_field];
871   }
872 
873   /**
874     Cache the checked structure of this table.
875 
876     The pointer data is used to describe the structure that
877     a instance of the table must have. Each element of the
878     array specifies a field that must exist on the table.
879 
880     The pointer is cached in order to perform the check only
881     once -- when the table is loaded from the disk.
882   */
883   const TABLE_FIELD_DEF *table_field_def_cache;
884 
885   /** Main handler's share */
886   Handler_share *ha_share;
887 
888   /** Instrumentation for this table share. */
889   PSI_table_share *m_psi;
890 
resetTABLE_SHARE891   inline void reset() { bzero((void*)this, sizeof(*this)); }
892 
893   /*
894     Set share's table cache key and update its db and table name appropriately.
895 
896     SYNOPSIS
897       set_table_cache_key()
898         key_buff    Buffer with already built table cache key to be
899                     referenced from share.
900         key_length  Key length.
901 
902     NOTES
903       Since 'key_buff' buffer will be referenced from share it should has same
904       life-time as share itself.
905       This method automatically ensures that TABLE_SHARE::table_name/db have
906       appropriate values by using table cache key as their source.
907   */
908 
set_table_cache_keyTABLE_SHARE909   void set_table_cache_key(char *key_buff, uint key_length)
910   {
911     table_cache_key.str= key_buff;
912     table_cache_key.length= key_length;
913     /*
914       Let us use the fact that the key is "db/0/table_name/0" + optional
915       part for temporary tables.
916     */
917     db.str=            table_cache_key.str;
918     db.length=         strlen(db.str);
919     table_name.str=    db.str + db.length + 1;
920     table_name.length= strlen(table_name.str);
921   }
922 
923 
924   /*
925     Set share's table cache key and update its db and table name appropriately.
926 
927     SYNOPSIS
928       set_table_cache_key()
929         key_buff    Buffer to be used as storage for table cache key
930                     (should be at least key_length bytes).
931         key         Value for table cache key.
932         key_length  Key length.
933 
934     NOTE
935       Since 'key_buff' buffer will be used as storage for table cache key
936       it should has same life-time as share itself.
937   */
938 
set_table_cache_keyTABLE_SHARE939   void set_table_cache_key(char *key_buff, const char *key, uint key_length)
940   {
941     memcpy(key_buff, key, key_length);
942     set_table_cache_key(key_buff, key_length);
943   }
944 
require_write_privilegesTABLE_SHARE945   inline bool require_write_privileges()
946   {
947     return (table_category == TABLE_CATEGORY_LOG);
948   }
949 
get_table_def_versionTABLE_SHARE950   inline ulong get_table_def_version()
951   {
952     return table_map_id;
953   }
954 
955   /**
956     Convert unrelated members of TABLE_SHARE to one enum
957     representing its type.
958 
959     @todo perhaps we need to have a member instead of a function.
960   */
get_table_ref_typeTABLE_SHARE961   enum enum_table_ref_type get_table_ref_type() const
962   {
963     if (is_view)
964       return TABLE_REF_VIEW;
965     switch (tmp_table) {
966     case NO_TMP_TABLE:
967       return TABLE_REF_BASE_TABLE;
968     case SYSTEM_TMP_TABLE:
969       return TABLE_REF_I_S_TABLE;
970     default:
971       return TABLE_REF_TMP_TABLE;
972     }
973   }
974   /**
975     Return a table metadata version.
976      * for base tables and views, we return table_map_id.
977        It is assigned from a global counter incremented for each
978        new table loaded into the table definition cache (TDC).
979      * for temporary tables it's table_map_id again. But for
980        temporary tables table_map_id is assigned from
981        thd->query_id. The latter is assigned from a thread local
982        counter incremented for every new SQL statement. Since
983        temporary tables are thread-local, each temporary table
984        gets a unique id.
985      * for everything else (e.g. information schema tables),
986        the version id is zero.
987 
988    This choice of version id is a large compromise
989    to have a working prepared statement validation in 5.1. In
990    future version ids will be persistent, as described in WL#4180.
991 
992    Let's try to explain why and how this limited solution allows
993    to validate prepared statements.
994 
995    Firstly, sets (in mathematical sense) of version numbers
996    never intersect for different table types. Therefore,
997    version id of a temporary table is never compared with
998    a version id of a view, and vice versa.
999 
1000    Secondly, for base tables and views, we know that each DDL flushes
1001    the respective share from the TDC. This ensures that whenever
1002    a table is altered or dropped and recreated, it gets a new
1003    version id.
1004    Unfortunately, since elements of the TDC are also flushed on
1005    LRU basis, this choice of version ids leads to false positives.
1006    E.g. when the TDC size is too small, we may have a SELECT
1007    * FROM INFORMATION_SCHEMA.TABLES flush all its elements, which
1008    in turn will lead to a validation error and a subsequent
1009    reprepare of all prepared statements.  This is
1010    considered acceptable, since as long as prepared statements are
1011    automatically reprepared, spurious invalidation is only
1012    a performance hit. Besides, no better simple solution exists.
1013 
1014    For temporary tables, using thd->query_id ensures that if
1015    a temporary table was altered or recreated, a new version id is
1016    assigned. This suits validation needs very well and will perhaps
1017    never change.
1018 
1019    Metadata of information schema tables never changes.
1020    Thus we can safely assume 0 for a good enough version id.
1021 
1022    Finally, by taking into account table type, we always
1023    track that a change has taken place when a view is replaced
1024    with a base table, a base table is replaced with a temporary
1025    table and so on.
1026 
1027    @sa TABLE_LIST::is_table_ref_id_equal()
1028   */
get_table_ref_versionTABLE_SHARE1029   ulong get_table_ref_version() const
1030   {
1031     return (tmp_table == SYSTEM_TMP_TABLE) ? 0 : table_map_id;
1032   }
1033 
1034   bool visit_subgraph(Wait_for_flush *waiting_ticket,
1035                       MDL_wait_for_graph_visitor *gvisitor);
1036 
1037   bool wait_for_old_version(THD *thd, struct timespec *abstime,
1038                             uint deadlock_weight);
1039   /** Release resources and free memory occupied by the table share. */
1040   void destroy();
1041 
set_use_ext_keys_flagTABLE_SHARE1042   void set_use_ext_keys_flag(bool fl)
1043   {
1044     use_ext_keys= fl;
1045   }
1046 
1047   uint actual_n_key_parts(THD *thd);
1048 
1049   LEX_CUSTRING *frm_image; ///< only during CREATE TABLE (@sa ha_create_table)
1050 
1051   /*
1052     populates TABLE_SHARE from the table description in the binary frm image.
1053     if 'write' is true, this frm image is also written into a corresponding
1054     frm file, that serves as a persistent metadata cache to avoid
1055     discovering the table over and over again
1056   */
1057   int init_from_binary_frm_image(THD *thd, bool write,
1058                                  const uchar *frm_image, size_t frm_length);
1059 
1060   /*
1061     populates TABLE_SHARE from the table description, specified as the
1062     complete CREATE TABLE sql statement.
1063     if 'write' is true, this frm image is also written into a corresponding
1064     frm file, that serves as a persistent metadata cache to avoid
1065     discovering the table over and over again
1066   */
1067   int init_from_sql_statement_string(THD *thd, bool write,
1068                                      const char *sql, size_t sql_length);
1069   /*
1070     writes the frm image to an frm file, corresponding to this table
1071   */
1072   bool write_frm_image(const uchar *frm_image, size_t frm_length);
1073 
write_frm_imageTABLE_SHARE1074   bool write_frm_image(void)
1075   { return frm_image ? write_frm_image(frm_image->str, frm_image->length) : 0; }
1076 
1077   /*
1078     returns an frm image for this table.
1079     the memory is allocated and must be freed later
1080   */
1081   bool read_frm_image(const uchar **frm_image, size_t *frm_length);
1082 
1083   /* frees the memory allocated in read_frm_image */
1084   void free_frm_image(const uchar *frm);
1085 };
1086 
1087 
1088 /**
1089    Class is used as a BLOB field value storage for
1090    intermediate GROUP_CONCAT results. Used only for
1091    GROUP_CONCAT with  DISTINCT or ORDER BY options.
1092  */
1093 
1094 class Blob_mem_storage: public Sql_alloc
1095 {
1096 private:
1097   MEM_ROOT storage;
1098   /**
1099     Sign that some values were cut
1100     during saving into the storage.
1101   */
1102   bool truncated_value;
1103 public:
Blob_mem_storage()1104   Blob_mem_storage() :truncated_value(false)
1105   {
1106     init_alloc_root(&storage, "Blob_mem_storage", MAX_FIELD_VARCHARLENGTH, 0,
1107                     MYF(0));
1108   }
~Blob_mem_storage()1109   ~ Blob_mem_storage()
1110   {
1111     free_root(&storage, MYF(0));
1112   }
reset()1113   void reset()
1114   {
1115     free_root(&storage, MYF(MY_MARK_BLOCKS_FREE));
1116     truncated_value= false;
1117   }
1118   /**
1119      Fuction creates duplicate of 'from'
1120      string in 'storage' MEM_ROOT.
1121 
1122      @param from           string to copy
1123      @param length         string length
1124 
1125      @retval Pointer to the copied string.
1126      @retval 0 if an error occurred.
1127   */
store(const char * from,size_t length)1128   char *store(const char *from, size_t length)
1129   {
1130     return (char*) memdup_root(&storage, from, length);
1131   }
set_truncated_value(bool is_truncated_value)1132   void set_truncated_value(bool is_truncated_value)
1133   {
1134     truncated_value= is_truncated_value;
1135   }
is_truncated_value()1136   bool is_truncated_value() { return truncated_value; }
1137 };
1138 
1139 
1140 /* Information for one open table */
1141 enum index_hint_type
1142 {
1143   INDEX_HINT_IGNORE,
1144   INDEX_HINT_USE,
1145   INDEX_HINT_FORCE
1146 };
1147 
1148 struct st_cond_statistic;
1149 
1150 #define      CHECK_ROW_FOR_NULLS_TO_REJECT   (1 << 0)
1151 #define      REJECT_ROW_DUE_TO_NULL_FIELDS   (1 << 1)
1152 
1153 /* Bitmap of table's fields */
1154 typedef Bitmap<MAX_FIELDS> Field_map;
1155 
1156 class SplM_opt_info;
1157 
1158 struct TABLE
1159 {
TABLETABLE1160   TABLE() {}                               /* Remove gcc warning */
1161 
1162   TABLE_SHARE	*s;
1163   handler	*file;
1164   TABLE *next, *prev;
1165 
1166 private:
1167   /**
1168      Links for the list of all TABLE objects for this share.
1169      Declared as private to avoid direct manipulation with those objects.
1170      One should use methods of I_P_List template instead.
1171   */
1172   TABLE *share_all_next, **share_all_prev;
1173   TABLE *global_free_next, **global_free_prev;
1174   friend struct All_share_tables;
1175   friend struct Table_cache_instance;
1176 
1177 public:
1178 
1179   uint32 instance; /** Table cache instance this TABLE is belonging to */
1180   THD	*in_use;                        /* Which thread uses this */
1181 
1182   uchar *record[3];			/* Pointer to records */
1183   uchar *write_row_record;		/* Used as optimisation in
1184 					   THD::write_row */
1185   uchar *insert_values;                  /* used by INSERT ... UPDATE */
1186   /*
1187     Map of keys that can be used to retrieve all data from this table
1188     needed by the query without reading the row.
1189   */
1190   key_map covering_keys;
1191   key_map quick_keys, intersect_keys;
1192   /*
1193     A set of keys that can be used in the query that references this
1194     table.
1195 
1196     All indexes disabled on the table's TABLE_SHARE (see TABLE::s) will be
1197     subtracted from this set upon instantiation. Thus for any TABLE t it holds
1198     that t.keys_in_use_for_query is a subset of t.s.keys_in_use. Generally we
1199     must not introduce any new keys here (see setup_tables).
1200 
1201     The set is implemented as a bitmap.
1202   */
1203   key_map keys_in_use_for_query;
1204   /* Map of keys that can be used to calculate GROUP BY without sorting */
1205   key_map keys_in_use_for_group_by;
1206   /* Map of keys that can be used to calculate ORDER BY without sorting */
1207   key_map keys_in_use_for_order_by;
1208   KEY  *key_info;			/* data of keys in database */
1209 
1210   Field **field;                        /* Pointer to fields */
1211   Field **vfield;                       /* Pointer to virtual fields*/
1212   Field **default_field;                /* Fields with non-constant DEFAULT */
1213   Field *next_number_field;		/* Set if next_number is activated */
1214   Field *found_next_number_field;	/* Set on open */
1215   Virtual_column_info **check_constraints;
1216 
1217   /* Table's triggers, 0 if there are no of them */
1218   Table_triggers_list *triggers;
1219   TABLE_LIST *pos_in_table_list;/* Element referring to this table */
1220   /* Position in thd->locked_table_list under LOCK TABLES */
1221   TABLE_LIST *pos_in_locked_tables;
1222   /* Tables used in DEFAULT and CHECK CONSTRAINT (normally sequence tables) */
1223   TABLE_LIST *internal_tables;
1224 
1225   /*
1226     Not-null for temporary tables only. Non-null values means this table is
1227     used to compute GROUP BY, it has a unique of GROUP BY columns.
1228     (set by create_tmp_table)
1229   */
1230   ORDER		*group;
1231   String	alias;            	  /* alias or table name */
1232   uchar		*null_flags;
1233   MY_BITMAP     def_read_set, def_write_set, tmp_set;
1234   MY_BITMAP     def_rpl_write_set;
1235   MY_BITMAP     eq_join_set;         /* used to mark equi-joined fields */
1236   MY_BITMAP     cond_set;   /* used to mark fields from sargable conditions*/
1237   /* Active column sets */
1238   MY_BITMAP     *read_set, *write_set, *rpl_write_set;
1239   /* Set if using virtual fields */
1240   MY_BITMAP     *vcol_set, *def_vcol_set;
1241   /* On INSERT: fields that the user specified a value for */
1242   MY_BITMAP	has_value_set;
1243 
1244   /*
1245    The ID of the query that opened and is using this table. Has different
1246    meanings depending on the table type.
1247 
1248    Temporary tables:
1249 
1250    table->query_id is set to thd->query_id for the duration of a statement
1251    and is reset to 0 once it is closed by the same statement. A non-zero
1252    table->query_id means that a statement is using the table even if it's
1253    not the current statement (table is in use by some outer statement).
1254 
1255    Non-temporary tables:
1256 
1257    Under pre-locked or LOCK TABLES mode: query_id is set to thd->query_id
1258    for the duration of a statement and is reset to 0 once it is closed by
1259    the same statement. A non-zero query_id is used to control which tables
1260    in the list of pre-opened and locked tables are actually being used.
1261   */
1262   query_id_t	query_id;
1263 
1264   /*
1265     This structure is used for statistical data on the table that
1266     is collected by the function collect_statistics_for_table
1267   */
1268   Table_statistics *collected_stats;
1269 
1270   /* The estimate of the number of records in the table used by optimizer */
1271   ha_rows used_stat_records;
1272 
1273   /*
1274     For each key that has quick_keys.is_set(key) == TRUE: estimate of #records
1275     and max #key parts that range access would use.
1276   */
1277   ha_rows	quick_rows[MAX_KEY];
1278   double 	quick_costs[MAX_KEY];
1279 
1280   /*
1281     Bitmaps of key parts that =const for the duration of join execution. If
1282     we're in a subquery, then the constant may be different across subquery
1283     re-executions.
1284   */
1285   key_part_map  const_key_parts[MAX_KEY];
1286 
1287   uint		quick_key_parts[MAX_KEY];
1288   uint		quick_n_ranges[MAX_KEY];
1289 
1290   /*
1291     Estimate of number of records that satisfy SARGable part of the table
1292     condition, or table->file->records if no SARGable condition could be
1293     constructed.
1294     This value is used by join optimizer as an estimate of number of records
1295     that will pass the table condition (condition that depends on fields of
1296     this table and constants)
1297   */
1298   ha_rows       quick_condition_rows;
1299 
1300   double cond_selectivity;
1301   List<st_cond_statistic> *cond_selectivity_sampling_explain;
1302 
1303   table_map	map;                    /* ID bit of table (1,2,4,8,16...) */
1304 
1305   uint          lock_position;          /* Position in MYSQL_LOCK.table */
1306   uint          lock_data_start;        /* Start pos. in MYSQL_LOCK.locks */
1307   uint          lock_count;             /* Number of locks */
1308   uint		tablenr,used_fields;
1309   uint          temp_pool_slot;		/* Used by intern temp tables */
1310   uint		status;                 /* What's in record[0] */
1311   uint		db_stat;		/* mode of file as in handler.h */
1312   /* number of select if it is derived table */
1313   uint          derived_select_number;
1314   /*
1315     Possible values:
1316      - 0 by default
1317      - JOIN_TYPE_{LEFT|RIGHT} if the table is inner w.r.t an outer join
1318        operation
1319      - 1 if the SELECT has mixed_implicit_grouping=1. example:
1320        select max(col1), col2 from t1. In this case, the query produces
1321        one row with all columns having NULL values.
1322 
1323     Interpetation: If maybe_null!=0, all fields of the table are considered
1324     NULLable (and have NULL values when null_row=true)
1325   */
1326   uint maybe_null;
1327   int		current_lock;           /* Type of lock on table */
1328   bool copy_blobs;			/* copy_blobs when storing */
1329   /*
1330     Set if next_number_field is in the UPDATE fields of INSERT ... ON DUPLICATE
1331     KEY UPDATE.
1332   */
1333   bool next_number_field_updated;
1334 
1335   /*
1336     If true, the current table row is considered to have all columns set to
1337     NULL, including columns declared as "not null" (see maybe_null).
1338   */
1339   bool null_row;
1340   /*
1341     No rows that contain null values can be placed into this table.
1342     Currently this flag can be set to true only for a temporary table
1343     that used to store the result of materialization of a subquery.
1344   */
1345   bool no_rows_with_nulls;
1346   /*
1347     This field can contain two bit flags:
1348       CHECK_ROW_FOR_NULLS_TO_REJECT
1349       REJECT_ROW_DUE_TO_NULL_FIELDS
1350     The first flag is set for the dynamic contexts where it is prohibited
1351     to write any null into the table.
1352     The second flag is set only if the first flag is set on.
1353     The informs the outer scope that there was an attept to write null
1354     into a field of the table in the context where it is prohibited.
1355     This flag should be set off as soon as the first flag is set on.
1356     Currently these flags are used only the tables tno_rows_with_nulls set
1357     to true.
1358   */
1359   uint8 null_catch_flags;
1360 
1361   /*
1362     TODO: Each of the following flags take up 8 bits. They can just as easily
1363     be put into one single unsigned long and instead of taking up 18
1364     bytes, it would take up 4.
1365   */
1366   bool force_index;
1367 
1368   /**
1369     Flag set when the statement contains FORCE INDEX FOR ORDER BY
1370     See TABLE_LIST::process_index_hints().
1371   */
1372   bool force_index_order;
1373 
1374   /**
1375     Flag set when the statement contains FORCE INDEX FOR GROUP BY
1376     See TABLE_LIST::process_index_hints().
1377   */
1378   bool force_index_group;
1379   /*
1380     TRUE<=> this table was created with create_tmp_table(... distinct=TRUE..)
1381     call
1382   */
1383   bool distinct;
1384   bool const_table,no_rows, used_for_duplicate_elimination;
1385   /**
1386     Forces DYNAMIC Aria row format for internal temporary tables.
1387   */
1388   bool keep_row_order;
1389 
1390   bool no_keyread;
1391   /**
1392     If set, indicate that the table is not replicated by the server.
1393   */
1394   bool locked_by_logger;
1395   bool locked_by_name;
1396   bool fulltext_searched;
1397   bool no_cache;
1398   /* To signal that the table is associated with a HANDLER statement */
1399   bool open_by_handler;
1400   /*
1401     To indicate that a non-null value of the auto_increment field
1402     was provided by the user or retrieved from the current record.
1403     Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode.
1404   */
1405   bool auto_increment_field_not_null;
1406   bool insert_or_update;             /* Can be used by the handler */
1407   bool alias_name_used;              /* true if table_name is alias */
1408   bool get_fields_in_item_tree;      /* Signal to fix_field */
1409 private:
1410   bool m_needs_reopen;
1411   bool created;    /* For tmp tables. TRUE <=> tmp table was actually created.*/
1412 public:
1413 #ifdef HAVE_REPLICATION
1414   /* used in RBR Triggers */
1415   bool master_had_triggers;
1416 #endif
1417 
1418   REGINFO reginfo;			/* field connections */
1419   MEM_ROOT mem_root;
1420   /**
1421      Initialized in Item_func_group_concat::setup for appropriate
1422      temporary table if GROUP_CONCAT is used with ORDER BY | DISTINCT
1423      and BLOB field count > 0.
1424    */
1425   Blob_mem_storage *blob_storage;
1426   GRANT_INFO grant;
1427   /*
1428     The arena which the items for expressions from the table definition
1429     are associated with.
1430     Currently only the items of the expressions for virtual columns are
1431     associated with this arena.
1432     TODO: To attach the partitioning expressions to this arena.
1433   */
1434   Query_arena *expr_arena;
1435 #ifdef WITH_PARTITION_STORAGE_ENGINE
1436   partition_info *part_info;            /* Partition related information */
1437   /* If true, all partitions have been pruned away */
1438   bool all_partitions_pruned_away;
1439 #endif
1440   uint max_keys; /* Size of allocated key_info array. */
1441   bool stats_is_read;     /* Persistent statistics is read for the table */
1442   bool histograms_are_read;
1443   MDL_ticket *mdl_ticket;
1444 
1445   /*
1446     This is used only for potentially splittable materialized tables and it
1447     points to the info used by the optimizer to apply splitting optimization
1448   */
1449   SplM_opt_info *spl_opt_info;
1450   key_map keys_usable_for_splitting;
1451 
1452 
resetTABLE1453   inline void reset() { bzero((void*)this, sizeof(*this)); }
1454   void init(THD *thd, TABLE_LIST *tl);
1455   bool fill_item_list(List<Item> *item_list) const;
1456   void reset_item_list(List<Item> *item_list, uint skip) const;
1457   void clear_column_bitmaps(void);
1458   void prepare_for_position(void);
1459   MY_BITMAP *prepare_for_keyread(uint index, MY_BITMAP *map);
prepare_for_keyreadTABLE1460   MY_BITMAP *prepare_for_keyread(uint index)
1461   { return prepare_for_keyread(index, &tmp_set); }
1462   void mark_index_columns(uint index, MY_BITMAP *bitmap);
1463   void mark_index_columns_no_reset(uint index, MY_BITMAP *bitmap);
1464   void mark_index_columns_for_read(uint index);
1465   void restore_column_maps_after_keyread(MY_BITMAP *backup);
1466   void mark_auto_increment_column(void);
1467   void mark_columns_needed_for_update(void);
1468   void mark_columns_needed_for_delete(void);
1469   void mark_columns_needed_for_insert(void);
1470   void mark_columns_per_binlog_row_image(void);
1471   bool mark_virtual_col(Field *field);
1472   bool mark_virtual_columns_for_write(bool insert_fl);
1473   bool check_virtual_columns_marked_for_read();
1474   bool check_virtual_columns_marked_for_write();
1475   void mark_default_fields_for_write(bool insert_fl);
1476   void mark_columns_used_by_virtual_fields(void);
1477   void mark_check_constraint_columns_for_read(void);
1478   int verify_constraints(bool ignore_failure);
column_bitmaps_setTABLE1479   inline void column_bitmaps_set(MY_BITMAP *read_set_arg)
1480   {
1481     read_set= read_set_arg;
1482     if (file)
1483       file->column_bitmaps_signal();
1484   }
column_bitmaps_setTABLE1485   inline void column_bitmaps_set(MY_BITMAP *read_set_arg,
1486                                  MY_BITMAP *write_set_arg)
1487   {
1488     read_set= read_set_arg;
1489     write_set= write_set_arg;
1490     if (file)
1491       file->column_bitmaps_signal();
1492   }
column_bitmaps_setTABLE1493   inline void column_bitmaps_set(MY_BITMAP *read_set_arg,
1494                                  MY_BITMAP *write_set_arg,
1495                                  MY_BITMAP *vcol_set_arg)
1496   {
1497     read_set= read_set_arg;
1498     write_set= write_set_arg;
1499     vcol_set= vcol_set_arg;
1500     if (file)
1501       file->column_bitmaps_signal();
1502   }
column_bitmaps_set_no_signalTABLE1503   inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg,
1504                                            MY_BITMAP *write_set_arg)
1505   {
1506     read_set= read_set_arg;
1507     write_set= write_set_arg;
1508   }
column_bitmaps_set_no_signalTABLE1509   inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg,
1510                                            MY_BITMAP *write_set_arg,
1511                                            MY_BITMAP *vcol_set_arg)
1512   {
1513     read_set= read_set_arg;
1514     write_set= write_set_arg;
1515     vcol_set= vcol_set_arg;
1516   }
use_all_columnsTABLE1517   inline void use_all_columns()
1518   {
1519     column_bitmaps_set(&s->all_set, &s->all_set);
1520   }
default_column_bitmapsTABLE1521   inline void default_column_bitmaps()
1522   {
1523     read_set= &def_read_set;
1524     write_set= &def_write_set;
1525     vcol_set= def_vcol_set;                     /* Note that this may be 0 */
1526     rpl_write_set= 0;
1527   }
1528   /** Should this instance of the table be reopened? */
needs_reopenTABLE1529   inline bool needs_reopen()
1530   { return !db_stat || m_needs_reopen; }
1531   /*
1532     Mark that all current connection instances of the table should be
1533     reopen at end of statement
1534   */
1535   void mark_table_for_reopen();
1536   /* Should only be called from Locked_tables_list::mark_table_for_reopen() */
internal_set_needs_reopenTABLE1537   void internal_set_needs_reopen(bool value)
1538   {
1539     m_needs_reopen= value;
1540   }
1541 
1542   bool alloc_keys(uint key_count);
1543   bool check_tmp_key(uint key, uint key_parts,
1544                      uint (*next_field_no) (uchar *), uchar *arg);
1545   bool add_tmp_key(uint key, uint key_parts,
1546                    uint (*next_field_no) (uchar *), uchar *arg,
1547                    bool unique);
1548   void create_key_part_by_field(KEY_PART_INFO *key_part_info,
1549                                 Field *field, uint fieldnr);
1550   void use_index(int key_to_save);
set_table_mapTABLE1551   void set_table_map(table_map map_arg, uint tablenr_arg)
1552   {
1553     map= map_arg;
1554     tablenr= tablenr_arg;
1555   }
1556 
1557   /// Return true if table is instantiated, and false otherwise.
is_createdTABLE1558   bool is_created() const { return created; }
1559 
1560   /**
1561     Set the table as "created", and enable flags in storage engine
1562     that could not be enabled without an instantiated table.
1563   */
set_createdTABLE1564   void set_created()
1565   {
1566     if (created)
1567       return;
1568     if (file->keyread_enabled())
1569       file->extra(HA_EXTRA_KEYREAD);
1570     created= true;
1571   }
1572 
1573   /*
1574     Returns TRUE if the table is filled at execution phase (and so, the
1575     optimizer must not do anything that depends on the contents of the table,
1576     like range analysis or constant table detection)
1577   */
1578   bool is_filled_at_execution();
1579 
1580   bool update_const_key_parts(COND *conds);
1581   void initialize_quick_structures();
1582 
default_values_offsetTABLE1583   my_ptrdiff_t default_values_offset() const
1584   { return (my_ptrdiff_t) (s->default_values - record[0]); }
1585 
1586   void move_fields(Field **ptr, const uchar *to, const uchar *from);
1587   void remember_blob_values(String *blob_storage);
1588   void restore_blob_values(String *blob_storage);
1589 
1590   uint actual_n_key_parts(KEY *keyinfo);
1591   ulong actual_key_flags(KEY *keyinfo);
1592   int update_virtual_field(Field *vf);
1593   int update_virtual_fields(handler *h, enum_vcol_update_mode update_mode);
1594   int update_default_fields(bool ignore_errors);
1595   void evaluate_update_default_function();
1596   void reset_default_fields();
stat_recordsTABLE1597   inline ha_rows stat_records() { return used_stat_records; }
1598 
1599   void prepare_triggers_for_insert_stmt_or_event();
1600   bool prepare_triggers_for_delete_stmt_or_event();
1601   bool prepare_triggers_for_update_stmt_or_event();
1602 
1603   Field **field_to_fill();
1604   bool validate_default_values_of_unset_fields(THD *thd) const;
1605 
1606   bool insert_all_rows_into_tmp_table(THD *thd,
1607                                       TABLE *tmp_table,
1608                                       TMP_TABLE_PARAM *tmp_table_param,
1609                                       bool with_cleanup);
1610   int fix_vcol_exprs(THD *thd);
1611   Field *find_field_by_name(LEX_CSTRING *str) const;
1612   bool export_structure(THD *thd, class Row_definition_list *defs);
is_splittableTABLE1613   bool is_splittable() { return spl_opt_info != NULL; }
1614   void set_spl_opt_info(SplM_opt_info *spl_info);
1615   void deny_splitting();
1616   double get_materialization_cost(); // Now used only if is_splittable()==true
1617   void add_splitting_info_for_key_field(struct KEY_FIELD *key_field);
1618 
1619   /**
1620     System Versioning support
1621    */
1622   bool vers_write;
1623 
versionedTABLE1624   bool versioned() const
1625   {
1626     DBUG_ASSERT(s);
1627     return s->versioned;
1628   }
1629 
versionedTABLE1630   bool versioned(vers_sys_type_t type) const
1631   {
1632     DBUG_ASSERT(s);
1633     DBUG_ASSERT(type);
1634     return s->versioned == type;
1635   }
1636 
versioned_writeTABLE1637   bool versioned_write() const
1638   {
1639     DBUG_ASSERT(versioned() || !vers_write);
1640     return versioned() ? vers_write : false;
1641   }
1642 
versioned_writeTABLE1643   bool versioned_write(vers_sys_type_t type) const
1644   {
1645     DBUG_ASSERT(type);
1646     DBUG_ASSERT(versioned() || !vers_write);
1647     return versioned(type) ? vers_write : false;
1648   }
1649 
vers_start_fieldTABLE1650   Field *vers_start_field() const
1651   {
1652     DBUG_ASSERT(s && s->versioned);
1653     return field[s->row_start_field];
1654   }
1655 
vers_end_fieldTABLE1656   Field *vers_end_field() const
1657   {
1658     DBUG_ASSERT(s && s->versioned);
1659     return field[s->row_end_field];
1660   }
1661 
1662   ulonglong vers_start_id() const;
1663   ulonglong vers_end_id() const;
1664 
1665   bool vers_check_update(List<Item> &items);
1666 
1667   int delete_row();
1668   /* Used in majority of DML (called from fill_record()) */
1669   void vers_update_fields();
1670   /* Used in DELETE, DUP REPLACE and insert history row */
1671   void vers_update_end();
1672 
1673 /** Number of additional fields used in versioned tables */
1674 #define VERSIONING_FIELDS 2
1675 };
1676 
1677 
1678 /**
1679    Helper class which specifies which members of TABLE are used for
1680    participation in the list of used/unused TABLE objects for the share.
1681 */
1682 
1683 struct TABLE_share
1684 {
next_ptrTABLE_share1685   static inline TABLE **next_ptr(TABLE *l)
1686   {
1687     return &l->next;
1688   }
prev_ptrTABLE_share1689   static inline TABLE ***prev_ptr(TABLE *l)
1690   {
1691     return (TABLE ***) &l->prev;
1692   }
1693 };
1694 
1695 struct All_share_tables
1696 {
next_ptrAll_share_tables1697   static inline TABLE **next_ptr(TABLE *l)
1698   {
1699     return &l->share_all_next;
1700   }
prev_ptrAll_share_tables1701   static inline TABLE ***prev_ptr(TABLE *l)
1702   {
1703     return &l->share_all_prev;
1704   }
1705 };
1706 
1707 typedef I_P_List <TABLE, All_share_tables> All_share_tables_list;
1708 
1709 enum enum_schema_table_state
1710 {
1711   NOT_PROCESSED= 0,
1712   PROCESSED_BY_CREATE_SORT_INDEX,
1713   PROCESSED_BY_JOIN_EXEC
1714 };
1715 
1716 enum enum_fk_option { FK_OPTION_UNDEF, FK_OPTION_RESTRICT, FK_OPTION_CASCADE,
1717                FK_OPTION_SET_NULL, FK_OPTION_NO_ACTION, FK_OPTION_SET_DEFAULT};
1718 
1719 typedef struct st_foreign_key_info
1720 {
1721   LEX_CSTRING *foreign_id;
1722   LEX_CSTRING *foreign_db;
1723   LEX_CSTRING *foreign_table;
1724   LEX_CSTRING *referenced_db;
1725   LEX_CSTRING *referenced_table;
1726   enum_fk_option update_method;
1727   enum_fk_option delete_method;
1728   LEX_CSTRING *referenced_key_name;
1729   List<LEX_CSTRING> foreign_fields;
1730   List<LEX_CSTRING> referenced_fields;
1731 } FOREIGN_KEY_INFO;
1732 
1733 LEX_CSTRING *fk_option_name(enum_fk_option opt);
1734 bool fk_modifies_child(enum_fk_option opt);
1735 
1736 #define MY_I_S_MAYBE_NULL 1U
1737 #define MY_I_S_UNSIGNED   2U
1738 
1739 
1740 #define SKIP_OPEN_TABLE 0U               // do not open table
1741 #define OPEN_FRM_ONLY   1U               // open FRM file only
1742 #define OPEN_FULL_TABLE 2U               // open FRM,MYD, MYI files
1743 
1744 typedef struct st_field_info
1745 {
1746   /**
1747       This is used as column name.
1748   */
1749   const char* field_name;
1750   /**
1751      For string-type columns, this is the maximum number of
1752      characters. Otherwise, it is the 'display-length' for the column.
1753   */
1754   uint field_length;
1755   /**
1756      This denotes data type for the column. For the most part, there seems to
1757      be one entry in the enum for each SQL data type, although there seem to
1758      be a number of additional entries in the enum.
1759   */
1760   enum enum_field_types field_type;
1761   int value;
1762   /**
1763      This is used to set column attributes. By default, columns are @c NOT
1764      @c NULL and @c SIGNED, and you can deviate from the default
1765      by setting the appopriate flags. You can use either one of the flags
1766      @c MY_I_S_MAYBE_NULL and @cMY_I_S_UNSIGNED or
1767      combine them using the bitwise or operator @c |. Both flags are
1768      defined in table.h.
1769    */
1770   uint field_flags;        // Field atributes(maybe_null, signed, unsigned etc.)
1771   const char* old_name;
1772   /**
1773      This should be one of @c SKIP_OPEN_TABLE,
1774      @c OPEN_FRM_ONLY or @c OPEN_FULL_TABLE.
1775   */
1776   uint open_method;
1777 } ST_FIELD_INFO;
1778 
1779 
1780 struct TABLE_LIST;
1781 typedef class Item COND;
1782 
1783 typedef struct st_schema_table
1784 {
1785   const char *table_name;
1786   ST_FIELD_INFO *fields_info;
1787   /* for FLUSH table_name */
1788   int (*reset_table) ();
1789   /* Fill table with data */
1790   int (*fill_table) (THD *thd, TABLE_LIST *tables, COND *cond);
1791   /* Handle fileds for old SHOW */
1792   int (*old_format) (THD *thd, struct st_schema_table *schema_table);
1793   int (*process_table) (THD *thd, TABLE_LIST *tables, TABLE *table,
1794                         bool res, const LEX_CSTRING *db_name,
1795                         const LEX_CSTRING *table_name);
1796   int idx_field1, idx_field2;
1797   bool hidden;
1798   uint i_s_requested_object;  /* the object we need to open(TABLE | VIEW) */
1799 } ST_SCHEMA_TABLE;
1800 
1801 class IS_table_read_plan;
1802 
1803 /*
1804   Types of derived tables. The ending part is a bitmap of phases that are
1805   applicable to a derived table of the type.
1806 */
1807 #define DTYPE_ALGORITHM_UNDEFINED    0U
1808 #define DTYPE_VIEW                   1U
1809 #define DTYPE_TABLE                  2U
1810 #define DTYPE_MERGE                  4U
1811 #define DTYPE_MATERIALIZE            8U
1812 #define DTYPE_MULTITABLE             16U
1813 #define DTYPE_MASK                   (DTYPE_VIEW|DTYPE_TABLE|DTYPE_MULTITABLE)
1814 
1815 /*
1816   Phases of derived tables/views handling, see sql_derived.cc
1817   Values are used as parts of a bitmap attached to derived table types.
1818 */
1819 #define DT_INIT             1U
1820 #define DT_PREPARE          2U
1821 #define DT_OPTIMIZE         4U
1822 #define DT_MERGE            8U
1823 #define DT_MERGE_FOR_INSERT 16U
1824 #define DT_CREATE           32U
1825 #define DT_FILL             64U
1826 #define DT_REINIT           128U
1827 #define DT_PHASES           8U
1828 /* Phases that are applicable to all derived tables. */
1829 #define DT_COMMON       (DT_INIT + DT_PREPARE + DT_REINIT + DT_OPTIMIZE)
1830 /* Phases that are applicable only to materialized derived tables. */
1831 #define DT_MATERIALIZE  (DT_CREATE + DT_FILL)
1832 
1833 #define DT_PHASES_MERGE (DT_COMMON | DT_MERGE | DT_MERGE_FOR_INSERT)
1834 #define DT_PHASES_MATERIALIZE (DT_COMMON | DT_MATERIALIZE)
1835 
1836 #define VIEW_ALGORITHM_UNDEFINED 0
1837 /* Special value for ALTER VIEW: inherit original algorithm. */
1838 #define VIEW_ALGORITHM_INHERIT   DTYPE_VIEW
1839 #define VIEW_ALGORITHM_MERGE    (DTYPE_VIEW | DTYPE_MERGE)
1840 #define VIEW_ALGORITHM_TMPTABLE (DTYPE_VIEW | DTYPE_MATERIALIZE)
1841 
1842 /*
1843   View algorithm values as stored in the FRM. Values differ from in-memory
1844   representation for backward compatibility.
1845 */
1846 
1847 #define VIEW_ALGORITHM_UNDEFINED_FRM  0U
1848 #define VIEW_ALGORITHM_MERGE_FRM      1U
1849 #define VIEW_ALGORITHM_TMPTABLE_FRM   2U
1850 
1851 #define JOIN_TYPE_LEFT	1U
1852 #define JOIN_TYPE_RIGHT	2U
1853 #define JOIN_TYPE_OUTER 4U	/* Marker that this is an outer join */
1854 
1855 /* view WITH CHECK OPTION parameter options */
1856 #define VIEW_CHECK_NONE       0
1857 #define VIEW_CHECK_LOCAL      1
1858 #define VIEW_CHECK_CASCADED   2
1859 
1860 /* result of view WITH CHECK OPTION parameter check */
1861 #define VIEW_CHECK_OK         0
1862 #define VIEW_CHECK_ERROR      1
1863 #define VIEW_CHECK_SKIP       2
1864 
1865 /** The threshold size a blob field buffer before it is freed */
1866 #define MAX_TDC_BLOB_SIZE 65536
1867 
1868 class select_unit;
1869 class TMP_TABLE_PARAM;
1870 
1871 Item *create_view_field(THD *thd, TABLE_LIST *view, Item **field_ref,
1872                         LEX_CSTRING *name);
1873 
1874 struct Field_translator
1875 {
1876   Item *item;
1877   LEX_CSTRING name;
1878 };
1879 
1880 
1881 /*
1882   Column reference of a NATURAL/USING join. Since column references in
1883   joins can be both from views and stored tables, may point to either a
1884   Field (for tables), or a Field_translator (for views).
1885 */
1886 
1887 class Natural_join_column: public Sql_alloc
1888 {
1889 public:
1890   Field_translator *view_field;  /* Column reference of merge view. */
1891   Item_field       *table_field; /* Column reference of table or temp view. */
1892   TABLE_LIST *table_ref; /* Original base table/view reference. */
1893   /*
1894     True if a common join column of two NATURAL/USING join operands. Notice
1895     that when we have a hierarchy of nested NATURAL/USING joins, a column can
1896     be common at some level of nesting but it may not be common at higher
1897     levels of nesting. Thus this flag may change depending on at which level
1898     we are looking at some column.
1899   */
1900   bool is_common;
1901 public:
1902   Natural_join_column(Field_translator *field_param, TABLE_LIST *tab);
1903   Natural_join_column(Item_field *field_param, TABLE_LIST *tab);
1904   LEX_CSTRING *name();
1905   Item *create_item(THD *thd);
1906   Field *field();
1907   const char *safe_table_name();
1908   const char *safe_db_name();
1909   GRANT_INFO *grant();
1910 };
1911 
1912 
1913 /**
1914    Type of table which can be open for an element of table list.
1915 */
1916 
1917 enum enum_open_type
1918 {
1919   OT_TEMPORARY_OR_BASE= 0, OT_TEMPORARY_ONLY, OT_BASE_ONLY
1920 };
1921 
1922 
1923 class SJ_MATERIALIZATION_INFO;
1924 class Index_hint;
1925 class Item_in_subselect;
1926 
1927 /* trivial class, for %union in sql_yacc.yy */
1928 struct vers_history_point_t
1929 {
1930   vers_sys_type_t unit;
1931   Item *item;
1932 };
1933 
1934 class Vers_history_point : public vers_history_point_t
1935 {
1936   void fix_item();
1937 
1938 public:
Vers_history_point()1939   Vers_history_point() { empty(); }
Vers_history_point(vers_sys_type_t unit_arg,Item * item_arg)1940   Vers_history_point(vers_sys_type_t unit_arg, Item *item_arg)
1941   {
1942     unit= unit_arg;
1943     item= item_arg;
1944     fix_item();
1945   }
Vers_history_point(vers_history_point_t p)1946   Vers_history_point(vers_history_point_t p)
1947   {
1948     unit= p.unit;
1949     item= p.item;
1950     fix_item();
1951   }
empty()1952   void empty() { unit= VERS_UNDEFINED; item= NULL; }
1953   void print(String *str, enum_query_type, const char *prefix, size_t plen) const;
1954   bool resolve_unit(THD *thd);
resolve_unit_trx_id(THD * thd)1955   bool resolve_unit_trx_id(THD *thd)
1956   {
1957     if (unit == VERS_UNDEFINED)
1958       unit= VERS_TRX_ID;
1959     return false;
1960   }
resolve_unit_timestamp(THD * thd)1961   bool resolve_unit_timestamp(THD *thd)
1962   {
1963     if (unit == VERS_UNDEFINED)
1964       unit= VERS_TIMESTAMP;
1965     return false;
1966   }
1967   void bad_expression_data_type_error(const char *type) const;
1968   bool eq(const vers_history_point_t &point) const;
1969 };
1970 
1971 struct vers_select_conds_t
1972 {
1973   vers_system_time_t type;
1974   vers_system_time_t orig_type;
1975   bool used:1;
1976   bool delete_history:1;
1977   Vers_history_point start;
1978   Vers_history_point end;
1979 
emptyvers_select_conds_t1980   void empty()
1981   {
1982     type= SYSTEM_TIME_UNSPECIFIED;
1983     orig_type= SYSTEM_TIME_UNSPECIFIED;
1984     used= false;
1985     delete_history= false;
1986     start.empty();
1987     end.empty();
1988   }
1989 
1990   void init(vers_system_time_t _type,
1991             Vers_history_point _start= Vers_history_point(),
1992             Vers_history_point _end= Vers_history_point())
1993   {
1994     type= _type;
1995     orig_type= _type;
1996     used= false;
1997     delete_history= (type == SYSTEM_TIME_HISTORY ||
1998       type == SYSTEM_TIME_BEFORE);
1999     start= _start;
2000     end= _end;
2001   }
2002 
2003   void print(String *str, enum_query_type query_type) const;
2004 
2005   bool init_from_sysvar(THD *thd);
2006 
is_setvers_select_conds_t2007   bool is_set() const
2008   {
2009     return type != SYSTEM_TIME_UNSPECIFIED;
2010   }
was_setvers_select_conds_t2011   bool was_set() const
2012   {
2013     return orig_type != SYSTEM_TIME_UNSPECIFIED;
2014   }
need_setupvers_select_conds_t2015   bool need_setup() const
2016   {
2017     return type != SYSTEM_TIME_UNSPECIFIED && type != SYSTEM_TIME_ALL;
2018   }
2019   bool resolve_units(THD *thd);
2020   bool eq(const vers_select_conds_t &conds) const;
2021 };
2022 
2023 /*
2024   Table reference in the FROM clause.
2025 
2026   These table references can be of several types that correspond to
2027   different SQL elements. Below we list all types of TABLE_LISTs with
2028   the necessary conditions to determine when a TABLE_LIST instance
2029   belongs to a certain type.
2030 
2031   1) table (TABLE_LIST::view == NULL)
2032      - base table
2033        (TABLE_LIST::derived == NULL)
2034      - FROM-clause subquery - TABLE_LIST::table is a temp table
2035        (TABLE_LIST::derived != NULL)
2036      - information schema table
2037        (TABLE_LIST::schema_table != NULL)
2038        NOTICE: for schema tables TABLE_LIST::field_translation may be != NULL
2039   2) view (TABLE_LIST::view != NULL)
2040      - merge    (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_MERGE)
2041            also (TABLE_LIST::field_translation != NULL)
2042      - tmptable (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_TMPTABLE)
2043            also (TABLE_LIST::field_translation == NULL)
2044   2.5) TODO: Add derived tables description here
2045   3) nested table reference (TABLE_LIST::nested_join != NULL)
2046      - table sequence - e.g. (t1, t2, t3)
2047        TODO: how to distinguish from a JOIN?
2048      - general JOIN
2049        TODO: how to distinguish from a table sequence?
2050      - NATURAL JOIN
2051        (TABLE_LIST::natural_join != NULL)
2052        - JOIN ... USING
2053          (TABLE_LIST::join_using_fields != NULL)
2054      - semi-join nest (sj_on_expr!= NULL && sj_subq_pred!=NULL)
2055   4) jtbm semi-join (jtbm_subselect != NULL)
2056 */
2057 
2058 /** last_leaf_for_name_resolutioning support. */
2059 
2060 struct LEX;
2061 class Index_hint;
2062 
2063 /*
2064   @struct TABLE_CHAIN
2065   @brief Subchain of global chain of table references
2066 
2067   The structure contains a pointer to the address of the next_global
2068   pointer to the first TABLE_LIST objectof the subchain and the address
2069   of the next_global pointer to the element right after the last
2070   TABLE_LIST object of the subchain.  For an empty subchain both pointers
2071   have the same value.
2072 */
2073 
2074 struct TABLE_CHAIN
2075 {
TABLE_CHAINTABLE_CHAIN2076   TABLE_CHAIN() {}
2077 
2078   TABLE_LIST **start_pos;
2079   TABLE_LIST ** end_pos;
2080 
set_start_posTABLE_CHAIN2081   void set_start_pos(TABLE_LIST **pos) { start_pos= pos; }
set_end_posTABLE_CHAIN2082   void set_end_pos(TABLE_LIST **pos) { end_pos= pos; }
2083 };
2084 
2085 struct TABLE_LIST
2086 {
TABLE_LISTTABLE_LIST2087   TABLE_LIST() {}                          /* Remove gcc warning */
2088 
2089   enum prelocking_types
2090   {
2091     PRELOCK_NONE, PRELOCK_ROUTINE, PRELOCK_FK
2092   };
2093 
2094   /**
2095     Prepare TABLE_LIST that consists of one table instance to use in
2096     open_and_lock_tables
2097   */
resetTABLE_LIST2098   inline void reset() { bzero((void*)this, sizeof(*this)); }
init_one_tableTABLE_LIST2099   inline void init_one_table(const LEX_CSTRING *db_arg,
2100                              const LEX_CSTRING *table_name_arg,
2101                              const LEX_CSTRING *alias_arg,
2102                              enum thr_lock_type lock_type_arg)
2103   {
2104     enum enum_mdl_type mdl_type;
2105     if (lock_type_arg >= TL_WRITE_ALLOW_WRITE)
2106       mdl_type= MDL_SHARED_WRITE;
2107     else if (lock_type_arg == TL_READ_NO_INSERT)
2108       mdl_type= MDL_SHARED_NO_WRITE;
2109     else
2110       mdl_type= MDL_SHARED_READ;
2111 
2112     reset();
2113     DBUG_ASSERT(!db_arg->str || strlen(db_arg->str) == db_arg->length);
2114     DBUG_ASSERT(!table_name_arg->str || strlen(table_name_arg->str) == table_name_arg->length);
2115     DBUG_ASSERT(!alias_arg || strlen(alias_arg->str) == alias_arg->length);
2116     db= *db_arg;
2117     table_name= *table_name_arg;
2118     alias= (alias_arg ? *alias_arg : *table_name_arg);
2119     lock_type= lock_type_arg;
2120     updating= lock_type >= TL_WRITE_ALLOW_WRITE;
2121     mdl_request.init(MDL_key::TABLE, db.str, table_name.str, mdl_type,
2122                      MDL_TRANSACTION);
2123   }
2124 
TABLE_LISTTABLE_LIST2125   TABLE_LIST(TABLE *table_arg, thr_lock_type lock_type)
2126   {
2127     DBUG_ASSERT(table_arg->s);
2128     init_one_table(&table_arg->s->db, &table_arg->s->table_name,
2129                    NULL, lock_type);
2130     table= table_arg;
2131   }
2132 
init_one_table_for_prelockingTABLE_LIST2133   inline void init_one_table_for_prelocking(const LEX_CSTRING *db_arg,
2134                                             const LEX_CSTRING *table_name_arg,
2135                                             const LEX_CSTRING *alias_arg,
2136                                             enum thr_lock_type lock_type_arg,
2137                                             prelocking_types prelocking_type,
2138                                             TABLE_LIST *belong_to_view_arg,
2139                                             uint8 trg_event_map_arg,
2140                                             TABLE_LIST ***last_ptr,
2141                                             my_bool insert_data)
2142 
2143   {
2144     init_one_table(db_arg, table_name_arg, alias_arg, lock_type_arg);
2145     cacheable_table= 1;
2146     prelocking_placeholder= prelocking_type;
2147     open_type= (prelocking_type == PRELOCK_ROUTINE ?
2148                 OT_TEMPORARY_OR_BASE :
2149                 OT_BASE_ONLY);
2150     belong_to_view= belong_to_view_arg;
2151     trg_event_map= trg_event_map_arg;
2152     /* MDL is enough for read-only FK checks, we don't need the table */
2153     if (prelocking_type == PRELOCK_FK && lock_type < TL_WRITE_ALLOW_WRITE)
2154       open_strategy= OPEN_STUB;
2155 
2156     **last_ptr= this;
2157     prev_global= *last_ptr;
2158     *last_ptr= &next_global;
2159     for_insert_data= insert_data;
2160   }
2161 
2162 
2163   /*
2164     List of tables local to a subquery (used by SQL_I_List). Considers
2165     views as leaves (unlike 'next_leaf' below). Created at parse time
2166     in st_select_lex::add_table_to_list() -> table_list.link_in_list().
2167   */
2168   TABLE_LIST *next_local;
2169   /* link in a global list of all queries tables */
2170   TABLE_LIST *next_global, **prev_global;
2171   LEX_CSTRING   db;
2172   LEX_CSTRING   table_name;
2173   LEX_CSTRING   schema_table_name;
2174   LEX_CSTRING   alias;
2175   const char    *option;                /* Used by cache index  */
2176   Item		*on_expr;		/* Used with outer join */
2177   Name_resolution_context *on_context;  /* For ON expressions */
2178 
2179   Item          *sj_on_expr;
2180   /*
2181     (Valid only for semi-join nests) Bitmap of tables that are within the
2182     semi-join (this is different from bitmap of all nest's children because
2183     tables that were pulled out of the semi-join nest remain listed as
2184     nest's children).
2185   */
2186   table_map     sj_inner_tables;
2187   /* Number of IN-compared expressions */
2188   uint          sj_in_exprs;
2189 
2190   /* If this is a non-jtbm semi-join nest: corresponding subselect predicate */
2191   Item_in_subselect  *sj_subq_pred;
2192 
2193   table_map     original_subq_pred_used_tables;
2194 
2195   /* If this is a jtbm semi-join object: corresponding subselect predicate */
2196   Item_in_subselect  *jtbm_subselect;
2197   /* TODO: check if this can be joined with tablenr_exec */
2198   uint jtbm_table_no;
2199 
2200   SJ_MATERIALIZATION_INFO *sj_mat_info;
2201 
2202   /*
2203     The structure of ON expression presented in the member above
2204     can be changed during certain optimizations. This member
2205     contains a snapshot of AND-OR structure of the ON expression
2206     made after permanent transformations of the parse tree, and is
2207     used to restore ON clause before every reexecution of a prepared
2208     statement or stored procedure.
2209   */
2210   Item          *prep_on_expr;
2211   COND_EQUAL    *cond_equal;            /* Used with outer join */
2212   /*
2213     During parsing - left operand of NATURAL/USING join where 'this' is
2214     the right operand. After parsing (this->natural_join == this) iff
2215     'this' represents a NATURAL or USING join operation. Thus after
2216     parsing 'this' is a NATURAL/USING join iff (natural_join != NULL).
2217   */
2218   TABLE_LIST *natural_join;
2219   /*
2220     True if 'this' represents a nested join that is a NATURAL JOIN.
2221     For one of the operands of 'this', the member 'natural_join' points
2222     to the other operand of 'this'.
2223   */
2224   bool is_natural_join;
2225   /* Field names in a USING clause for JOIN ... USING. */
2226   List<String> *join_using_fields;
2227   /*
2228     Explicitly store the result columns of either a NATURAL/USING join or
2229     an operand of such a join.
2230   */
2231   List<Natural_join_column> *join_columns;
2232   /* TRUE if join_columns contains all columns of this table reference. */
2233   bool is_join_columns_complete;
2234 
2235   /*
2236     List of nodes in a nested join tree, that should be considered as
2237     leaves with respect to name resolution. The leaves are: views,
2238     top-most nodes representing NATURAL/USING joins, subqueries, and
2239     base tables. All of these TABLE_LIST instances contain a
2240     materialized list of columns. The list is local to a subquery.
2241   */
2242   TABLE_LIST *next_name_resolution_table;
2243   /* Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */
2244   List<Index_hint> *index_hints;
2245   TABLE        *table;                          /* opened table */
2246   ulonglong         table_id; /* table id (from binlog) for opened table */
2247   /*
2248     select_result for derived table to pass it from table creation to table
2249     filling procedure
2250   */
2251   select_unit  *derived_result;
2252   /* Stub used for materialized derived tables. */
2253   table_map	map;                    /* ID bit of table (1,2,4,8,16...) */
get_mapTABLE_LIST2254   table_map get_map()
2255   {
2256     return jtbm_subselect? table_map(1) << jtbm_table_no : table->map;
2257   }
get_tablenrTABLE_LIST2258   uint get_tablenr()
2259   {
2260     return jtbm_subselect? jtbm_table_no : table->tablenr;
2261   }
set_tablenrTABLE_LIST2262   void set_tablenr(uint new_tablenr)
2263   {
2264     if (jtbm_subselect)
2265     {
2266       jtbm_table_no= new_tablenr;
2267     }
2268     if (table)
2269     {
2270       table->tablenr= new_tablenr;
2271       table->map= table_map(1) << new_tablenr;
2272     }
2273   }
2274   /*
2275     Reference from aux_tables to local list entry of main select of
2276     multi-delete statement:
2277     delete t1 from t2,t1 where t1.a<'B' and t2.b=t1.b;
2278     here it will be reference of first occurrence of t1 to second (as you
2279     can see this lists can't be merged)
2280   */
2281   TABLE_LIST	*correspondent_table;
2282   /**
2283      @brief Normally, this field is non-null for anonymous derived tables only.
2284 
2285      @details This field is set to non-null for
2286 
2287      - Anonymous derived tables, In this case it points to the SELECT_LEX_UNIT
2288      representing the derived table. E.g. for a query
2289 
2290      @verbatim SELECT * FROM (SELECT a FROM t1) b @endverbatim
2291 
2292      For the @c TABLE_LIST representing the derived table @c b, @c derived
2293      points to the SELECT_LEX_UNIT representing the result of the query within
2294      parenteses.
2295 
2296      - Views. This is set for views with @verbatim ALGORITHM = TEMPTABLE
2297      @endverbatim by mysql_make_view().
2298 
2299      @note Inside views, a subquery in the @c FROM clause is not allowed.
2300      @note Do not use this field to separate views/base tables/anonymous
2301      derived tables. Use TABLE_LIST::is_anonymous_derived_table().
2302   */
2303   st_select_lex_unit *derived;		/* SELECT_LEX_UNIT of derived table */
2304   With_element *with;          /* With element defining this table (if any) */
2305   /* Bitmap of the defining with element */
2306   table_map with_internal_reference_map;
2307   TABLE_LIST * next_with_rec_ref;
2308   bool is_derived_with_recursive_reference;
2309   bool block_handle_derived;
2310   ST_SCHEMA_TABLE *schema_table;        /* Information_schema table */
2311   st_select_lex	*schema_select_lex;
2312   /*
2313     True when the view field translation table is used to convert
2314     schema table fields for backwards compatibility with SHOW command.
2315   */
2316   bool schema_table_reformed;
2317   TMP_TABLE_PARAM *schema_table_param;
2318   /* link to select_lex where this table was used */
2319   st_select_lex	*select_lex;
2320   LEX *view;                    /* link on VIEW lex for merging */
2321   Field_translator *field_translation;	/* array of VIEW fields */
2322   /* pointer to element after last one in translation table above */
2323   Field_translator *field_translation_end;
2324   bool field_translation_updated;
2325   /*
2326     List (based on next_local) of underlying tables of this view. I.e. it
2327     does not include the tables of subqueries used in the view. Is set only
2328     for merged views.
2329   */
2330   TABLE_LIST	*merge_underlying_list;
2331   /*
2332     - 0 for base tables
2333     - in case of the view it is the list of all (not only underlying
2334     tables but also used in subquery ones) tables of the view.
2335   */
2336   List<TABLE_LIST> *view_tables;
2337   /* most upper view this table belongs to */
2338   TABLE_LIST	*belong_to_view;
2339   /* A derived table this table belongs to */
2340   TABLE_LIST    *belong_to_derived;
2341   /*
2342     The view directly referencing this table
2343     (non-zero only for merged underlying tables of a view).
2344   */
2345   TABLE_LIST	*referencing_view;
2346 
2347   table_map view_used_tables;
2348   table_map     map_exec;
2349   /* TODO: check if this can be joined with jtbm_table_no */
2350   uint          tablenr_exec;
2351   uint          maybe_null_exec;
2352 
2353   /* Ptr to parent MERGE table list item. See top comment in ha_myisammrg.cc */
2354   TABLE_LIST    *parent_l;
2355   /*
2356     Security  context (non-zero only for tables which belong
2357     to view with SQL SECURITY DEFINER)
2358   */
2359   Security_context *security_ctx;
2360   /*
2361     This view security context (non-zero only for views with
2362     SQL SECURITY DEFINER)
2363   */
2364   Security_context *view_sctx;
2365   bool allowed_show;
2366   Item          *where;                 /* VIEW WHERE clause condition */
2367   Item          *check_option;          /* WITH CHECK OPTION condition */
2368   LEX_STRING	select_stmt;		/* text of (CREATE/SELECT) statement */
2369   LEX_CSTRING	md5;			/* md5 of query text */
2370   LEX_CSTRING	source;			/* source of CREATE VIEW */
2371   LEX_CSTRING	view_db;		/* saved view database */
2372   LEX_CSTRING	view_name;		/* saved view name */
2373   LEX_STRING	timestamp;		/* GMT time stamp of last operation */
2374   LEX_USER      definer;                /* definer of view */
2375   ulonglong	file_version;		/* version of file's field set */
2376   ulonglong	mariadb_version;	/* version of server on creation */
2377   ulonglong     updatable_view;         /* VIEW can be updated */
2378   /**
2379       @brief The declared algorithm, if this is a view.
2380       @details One of
2381       - VIEW_ALGORITHM_UNDEFINED
2382       - VIEW_ALGORITHM_TMPTABLE
2383       - VIEW_ALGORITHM_MERGE
2384       @to do Replace with an enum
2385   */
2386   ulonglong	algorithm;
2387   ulonglong     view_suid;              /* view is suid (TRUE dy default) */
2388   ulonglong     with_check;             /* WITH CHECK OPTION */
2389   /*
2390     effective value of WITH CHECK OPTION (differ for temporary table
2391     algorithm)
2392   */
2393   uint8         effective_with_check;
2394   /**
2395       @brief The view algorithm that is actually used, if this is a view.
2396       @details One of
2397       - VIEW_ALGORITHM_UNDEFINED
2398       - VIEW_ALGORITHM_TMPTABLE
2399       - VIEW_ALGORITHM_MERGE
2400       @to do Replace with an enum
2401   */
2402   uint8         derived_type;
2403   GRANT_INFO	grant;
2404   /* data need by some engines in query cache*/
2405   ulonglong     engine_data;
2406   /* call back function for asking handler about caching in query cache */
2407   qc_engine_callback callback_func;
2408   thr_lock_type lock_type;
2409 
2410   /*
2411     Two fields below are set during parsing this table reference in the cases
2412     when the table reference can be potentially a reference to a CTE table.
2413     In this cases the fact that the reference is a reference to a CTE or not
2414     will be ascertained at the very end of parsing of the query when referencies
2415     to CTE are resolved. For references to CTE and to derived tables no mdl
2416     requests are needed while for other table references they are. If a request
2417     is possibly postponed the info that allows to issue this request must be
2418     saved in 'mdl_type' and 'table_options'.
2419   */
2420   enum_mdl_type mdl_type;
2421   ulong         table_options;
2422 
2423   uint		outer_join;		/* Which join type */
2424   uint		shared;			/* Used in multi-upd */
2425   bool          updatable;		/* VIEW/TABLE can be updated now */
2426   bool		straight;		/* optimize with prev table */
2427   bool          updating;               /* for replicate-do/ignore table */
2428   bool		force_index;		/* prefer index over table scan */
2429   bool          ignore_leaves;          /* preload only non-leaf nodes */
2430   bool          crashed;                 /* Table was found crashed */
2431   table_map     dep_tables;             /* tables the table depends on      */
2432   table_map     on_expr_dep_tables;     /* tables on expression depends on  */
2433   struct st_nested_join *nested_join;   /* if the element is a nested join  */
2434   TABLE_LIST *embedding;             /* nested join containing the table */
2435   List<TABLE_LIST> *join_list;/* join list the table belongs to   */
2436   bool          lifted;               /* set to true when the table is moved to
2437                                          the upper level at the parsing stage */
2438   bool		cacheable_table;	/* stop PS caching */
2439   /* used in multi-upd/views privilege check */
2440   bool		table_in_first_from_clause;
2441   /**
2442      Specifies which kind of table should be open for this element
2443      of table list.
2444   */
2445   enum enum_open_type open_type;
2446   /* TRUE if this merged view contain auto_increment field */
2447   bool          contain_auto_increment;
2448   bool          compact_view_format;    /* Use compact format for SHOW CREATE VIEW */
2449   /* view where processed */
2450   bool          where_processed;
2451   /* TRUE <=> VIEW CHECK OPTION expression has been processed */
2452   bool          check_option_processed;
2453   /* TABLE_TYPE_UNKNOWN if any type is acceptable */
2454   Table_type    required_type;
2455   handlerton	*db_type;		/* table_type for handler */
2456   char		timestamp_buffer[MAX_DATETIME_WIDTH + 1];
2457   /*
2458     This TABLE_LIST object is just placeholder for prelocking, it will be
2459     used for implicit LOCK TABLES only and won't be used in real statement.
2460   */
2461   prelocking_types prelocking_placeholder;
2462   /**
2463      Indicates that if TABLE_LIST object corresponds to the table/view
2464      which requires special handling.
2465   */
2466   enum enum_open_strategy
2467   {
2468     /* Normal open. */
2469     OPEN_NORMAL= 0,
2470     /* Associate a table share only if the the table exists. */
2471     OPEN_IF_EXISTS,
2472     /* Don't associate a table share. */
2473     OPEN_STUB
2474   } open_strategy;
2475   /** TRUE if an alias for this table was specified in the SQL. */
2476   bool          is_alias;
2477   /** TRUE if the table is referred to in the statement using a fully
2478       qualified name (<db_name>.<table_name>).
2479   */
2480   bool          is_fqtn;
2481 
2482   /* TRUE <=> derived table should be filled right after optimization. */
2483   bool          fill_me;
2484   /* TRUE <=> view/DT is merged. */
2485   /* TODO: replace with derived_type */
2486   bool          merged;
2487   bool          merged_for_insert;
2488   bool          sequence;  /* Part of NEXTVAL/CURVAL/LASTVAL */
2489 
2490   /*
2491     Items created by create_view_field and collected to change them in case
2492     of materialization of the view/derived table
2493   */
2494   List<Item>    used_items;
2495   /* Sublist (tail) of persistent used_items */
2496   List<Item>    persistent_used_items;
2497 
2498   /* View creation context. */
2499 
2500   View_creation_ctx *view_creation_ctx;
2501 
2502   /*
2503     Attributes to save/load view creation context in/from frm-file.
2504 
2505     Ther are required only to be able to use existing parser to load
2506     view-definition file. As soon as the parser parsed the file, view
2507     creation context is initialized and the attributes become redundant.
2508 
2509     These attributes MUST NOT be used for any purposes but the parsing.
2510   */
2511 
2512   LEX_CSTRING view_client_cs_name;
2513   LEX_CSTRING view_connection_cl_name;
2514 
2515   /*
2516     View definition (SELECT-statement) in the UTF-form.
2517   */
2518 
2519   LEX_CSTRING view_body_utf8;
2520 
2521    /* End of view definition context. */
2522 
2523   /**
2524     Indicates what triggers we need to pre-load for this TABLE_LIST
2525     when opening an associated TABLE. This is filled after
2526     the parsed tree is created.
2527 
2528     slave_fk_event_map is filled on the slave side with bitmaps value
2529     representing row-based event operation to help find and prelock
2530     possible FK constrain-related child tables.
2531   */
2532   uint8 trg_event_map, slave_fk_event_map;
2533   /* TRUE <=> this table is a const one and was optimized away. */
2534   bool optimized_away;
2535 
2536   /**
2537     TRUE <=> already materialized. Valid only for materialized derived
2538     tables/views.
2539   */
2540   bool materialized;
2541   /* I_S: Flags to open_table (e.g. OPEN_TABLE_ONLY or OPEN_VIEW_ONLY) */
2542   uint i_s_requested_object;
2543 
2544   bool prohibit_cond_pushdown;
2545 
2546   /*
2547     I_S: how to read the tables (SKIP_OPEN_TABLE/OPEN_FRM_ONLY/OPEN_FULL_TABLE)
2548   */
2549   uint table_open_method;
2550   /*
2551     I_S: where the schema table was filled
2552     (this is a hack. The code should be able to figure out whether reading
2553     from I_S should be done by create_sort_index() or by JOIN::exec.)
2554   */
2555   enum enum_schema_table_state schema_table_state;
2556 
2557   /* Something like a "query plan" for reading INFORMATION_SCHEMA table */
2558   IS_table_read_plan *is_table_read_plan;
2559 
2560   MDL_request mdl_request;
2561 
2562 #ifdef WITH_PARTITION_STORAGE_ENGINE
2563   /* List to carry partition names from PARTITION (...) clause in statement */
2564   List<String> *partition_names;
2565 #endif /* WITH_PARTITION_STORAGE_ENGINE */
2566 
2567   void calc_md5(char *buffer);
2568   int view_check_option(THD *thd, bool ignore_failure);
2569   bool create_field_translation(THD *thd);
2570   bool setup_underlying(THD *thd);
2571   void cleanup_items();
placeholderTABLE_LIST2572   bool placeholder()
2573   {
2574     return derived || view || schema_table || !table;
2575   }
2576   void print(THD *thd, table_map eliminated_tables, String *str,
2577              enum_query_type query_type);
2578   bool check_single_table(TABLE_LIST **table, table_map map,
2579                           TABLE_LIST *view);
2580   bool set_insert_values(MEM_ROOT *mem_root);
2581   void hide_view_error(THD *thd);
2582   TABLE_LIST *find_underlying_table(TABLE *table);
2583   TABLE_LIST *first_leaf_for_name_resolution();
2584   TABLE_LIST *last_leaf_for_name_resolution();
2585 
2586   /* System Versioning */
2587   vers_select_conds_t vers_conditions;
2588 
2589   my_bool for_insert_data;
2590 
2591   /**
2592      @brief
2593        Find the bottom in the chain of embedded table VIEWs.
2594 
2595      @detail
2596        This is used for single-table UPDATE/DELETE when they are modifying a
2597        single-table VIEW.
2598   */
find_table_for_updateTABLE_LIST2599   TABLE_LIST *find_table_for_update()
2600   {
2601     TABLE_LIST *tbl= this;
2602     while(!tbl->is_multitable() && tbl->single_table_updatable() &&
2603         tbl->merge_underlying_list)
2604     {
2605       tbl= tbl->merge_underlying_list;
2606     }
2607     return tbl;
2608   }
2609   TABLE *get_real_join_table();
2610   bool is_leaf_for_name_resolution();
top_tableTABLE_LIST2611   inline TABLE_LIST *top_table()
2612     { return belong_to_view ? belong_to_view : this; }
prepare_check_optionTABLE_LIST2613   inline bool prepare_check_option(THD *thd)
2614   {
2615     bool res= FALSE;
2616     if (effective_with_check)
2617       res= prep_check_option(thd, effective_with_check);
2618     return res;
2619   }
prepare_whereTABLE_LIST2620   inline bool prepare_where(THD *thd, Item **conds,
2621                             bool no_where_clause)
2622   {
2623     if (!view || is_merged_derived())
2624       return prep_where(thd, conds, no_where_clause);
2625     return FALSE;
2626   }
2627 
2628   void register_want_access(ulong want_access);
2629   bool prepare_security(THD *thd);
2630 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2631   Security_context *find_view_security_context(THD *thd);
2632   bool prepare_view_security_context(THD *thd);
2633 #endif
2634   /*
2635     Cleanup for re-execution in a prepared statement or a stored
2636     procedure.
2637   */
2638   void reinit_before_use(THD *thd);
2639   Item_subselect *containing_subselect();
2640 
2641   /*
2642     Compiles the tagged hints list and fills up TABLE::keys_in_use_for_query,
2643     TABLE::keys_in_use_for_group_by, TABLE::keys_in_use_for_order_by,
2644     TABLE::force_index and TABLE::covering_keys.
2645   */
2646   bool process_index_hints(TABLE *table);
2647 
2648   /**
2649     Compare the version of metadata from the previous execution
2650     (if any) with values obtained from the current table
2651     definition cache element.
2652 
2653     @sa check_and_update_table_version()
2654   */
is_table_ref_id_equalTABLE_LIST2655   inline bool is_table_ref_id_equal(TABLE_SHARE *s) const
2656   {
2657     return (m_table_ref_type == s->get_table_ref_type() &&
2658             m_table_ref_version == s->get_table_ref_version());
2659   }
2660 
2661   /**
2662     Record the value of metadata version of the corresponding
2663     table definition cache element in this parse tree node.
2664 
2665     @sa check_and_update_table_version()
2666   */
set_table_ref_idTABLE_LIST2667   inline void set_table_ref_id(TABLE_SHARE *s)
2668   { set_table_ref_id(s->get_table_ref_type(), s->get_table_ref_version()); }
2669 
set_table_ref_idTABLE_LIST2670   inline void set_table_ref_id(enum_table_ref_type table_ref_type_arg,
2671                         ulong table_ref_version_arg)
2672   {
2673     m_table_ref_type= table_ref_type_arg;
2674     m_table_ref_version= table_ref_version_arg;
2675   }
2676 
2677   /* Set of functions returning/setting state of a derived table/view. */
is_non_derivedTABLE_LIST2678   inline bool is_non_derived()
2679   {
2680     return (!derived_type);
2681   }
is_view_or_derivedTABLE_LIST2682   inline bool is_view_or_derived()
2683   {
2684     return (derived_type);
2685   }
is_viewTABLE_LIST2686   inline bool is_view()
2687   {
2688     return (derived_type & DTYPE_VIEW);
2689   }
is_derivedTABLE_LIST2690   inline bool is_derived()
2691   {
2692     return (derived_type & DTYPE_TABLE);
2693   }
2694   bool is_with_table();
2695   bool is_recursive_with_table();
2696   bool is_with_table_recursive_reference();
2697   void register_as_derived_with_rec_ref(With_element *rec_elem);
2698   bool is_nonrecursive_derived_with_rec_ref();
2699   bool fill_recursive(THD *thd);
2700 
set_viewTABLE_LIST2701   inline void set_view()
2702   {
2703     derived_type= DTYPE_VIEW;
2704   }
set_derivedTABLE_LIST2705   inline void set_derived()
2706   {
2707     derived_type= DTYPE_TABLE;
2708   }
is_merged_derivedTABLE_LIST2709   inline bool is_merged_derived()
2710   {
2711     return (derived_type & DTYPE_MERGE);
2712   }
set_merged_derivedTABLE_LIST2713   inline void set_merged_derived()
2714   {
2715     DBUG_ENTER("set_merged_derived");
2716     DBUG_PRINT("enter", ("Alias: '%s'  Unit: %p",
2717                         (alias.str ? alias.str : "<NULL>"),
2718                          get_unit()));
2719     derived_type= ((derived_type & DTYPE_MASK) |
2720                    DTYPE_TABLE | DTYPE_MERGE);
2721     set_check_merged();
2722     DBUG_VOID_RETURN;
2723   }
is_materialized_derivedTABLE_LIST2724   inline bool is_materialized_derived()
2725   {
2726     return (derived_type & DTYPE_MATERIALIZE);
2727   }
set_materialized_derivedTABLE_LIST2728   void set_materialized_derived()
2729   {
2730     DBUG_ENTER("set_materialized_derived");
2731     DBUG_PRINT("enter", ("Alias: '%s'  Unit: %p",
2732                         (alias.str ? alias.str : "<NULL>"),
2733                          get_unit()));
2734     derived= get_unit();
2735     derived_type= ((derived_type & (derived ? DTYPE_MASK : DTYPE_VIEW)) |
2736                    DTYPE_TABLE | DTYPE_MATERIALIZE);
2737     set_check_materialized();
2738     DBUG_VOID_RETURN;
2739   }
is_multitableTABLE_LIST2740   inline bool is_multitable()
2741   {
2742     return (derived_type & DTYPE_MULTITABLE);
2743   }
set_multitableTABLE_LIST2744   inline void set_multitable()
2745   {
2746     derived_type|= DTYPE_MULTITABLE;
2747   }
2748   bool set_as_with_table(THD *thd, With_element *with_elem);
2749   void reset_const_table();
2750   bool handle_derived(LEX *lex, uint phases);
2751 
2752   /**
2753      @brief True if this TABLE_LIST represents an anonymous derived table,
2754      i.e.  the result of a subquery.
2755   */
is_anonymous_derived_tableTABLE_LIST2756   bool is_anonymous_derived_table() const { return derived && !view; }
2757 
2758   /**
2759      @brief Returns the name of the database that the referenced table belongs
2760      to.
2761   */
get_db_nameTABLE_LIST2762   const char *get_db_name() const { return view != NULL ? view_db.str : db.str; }
2763 
2764   /**
2765      @brief Returns the name of the table that this TABLE_LIST represents.
2766 
2767      @details The unqualified table name or view name for a table or view,
2768      respectively.
2769    */
get_table_nameTABLE_LIST2770   const char *get_table_name() const { return view != NULL ? view_name.str : table_name.str; }
2771   bool is_active_sjm();
is_jtbmTABLE_LIST2772   bool is_jtbm() { return MY_TEST(jtbm_subselect != NULL); }
2773   st_select_lex_unit *get_unit();
2774   st_select_lex *get_single_select();
2775   void wrap_into_nested_join(List<TABLE_LIST> &join_list);
2776   bool init_derived(THD *thd, bool init_view);
2777   int fetch_number_of_rows();
2778   bool change_refs_to_fields();
2779 
2780   bool single_table_updatable();
2781 
is_inner_table_of_outer_joinTABLE_LIST2782   bool is_inner_table_of_outer_join()
2783   {
2784     for (TABLE_LIST *tbl= this; tbl; tbl= tbl->embedding)
2785     {
2786       if (tbl->outer_join)
2787         return true;
2788     }
2789     return false;
2790   }
2791   void set_lock_type(THD* thd, enum thr_lock_type lock);
2792   void check_pushable_cond_for_table(Item *cond);
2793   Item *build_pushable_cond_for_table(THD *thd, Item *cond);
2794 
remove_join_columnsTABLE_LIST2795   void remove_join_columns()
2796   {
2797     if (join_columns)
2798     {
2799       join_columns->empty();
2800       join_columns= NULL;
2801       is_join_columns_complete= FALSE;
2802     }
2803   }
2804 
2805 private:
2806   bool prep_check_option(THD *thd, uint8 check_opt_type);
2807   bool prep_where(THD *thd, Item **conds, bool no_where_clause);
2808   void set_check_materialized();
2809 #ifndef DBUG_OFF
2810   void set_check_merged();
2811 #else
set_check_mergedTABLE_LIST2812   inline void set_check_merged() {}
2813 #endif
2814   /** See comments for set_table_ref_id() */
2815   enum enum_table_ref_type m_table_ref_type;
2816   /** See comments for set_table_ref_id() */
2817   ulong m_table_ref_version;
2818 };
2819 
2820 class Item;
2821 
2822 /*
2823   Iterator over the fields of a generic table reference.
2824 */
2825 
2826 class Field_iterator: public Sql_alloc
2827 {
2828 public:
Field_iterator()2829   Field_iterator() {}                         /* Remove gcc warning */
~Field_iterator()2830   virtual ~Field_iterator() {}
2831   virtual void set(TABLE_LIST *)= 0;
2832   virtual void next()= 0;
2833   virtual bool end_of_fields()= 0;              /* Return 1 at end of list */
2834   virtual LEX_CSTRING *name()= 0;
2835   virtual Item *create_item(THD *)= 0;
2836   virtual Field *field()= 0;
2837 };
2838 
2839 
2840 /*
2841   Iterator over the fields of a base table, view with temporary
2842   table, or subquery.
2843 */
2844 
2845 class Field_iterator_table: public Field_iterator
2846 {
2847   Field **ptr;
2848 public:
Field_iterator_table()2849   Field_iterator_table() :ptr(0) {}
set(TABLE_LIST * table)2850   void set(TABLE_LIST *table) { ptr= table->table->field; }
set_table(TABLE * table)2851   void set_table(TABLE *table) { ptr= table->field; }
next()2852   void next() { ptr++; }
end_of_fields()2853   bool end_of_fields() { return *ptr == 0; }
2854   LEX_CSTRING *name();
2855   Item *create_item(THD *thd);
field()2856   Field *field() { return *ptr; }
2857 };
2858 
2859 
2860 /* Iterator over the fields of a merge view. */
2861 
2862 class Field_iterator_view: public Field_iterator
2863 {
2864   Field_translator *ptr, *array_end;
2865   TABLE_LIST *view;
2866 public:
Field_iterator_view()2867   Field_iterator_view() :ptr(0), array_end(0) {}
2868   void set(TABLE_LIST *table);
next()2869   void next() { ptr++; }
end_of_fields()2870   bool end_of_fields() { return ptr == array_end; }
2871   LEX_CSTRING *name();
2872   Item *create_item(THD *thd);
item_ptr()2873   Item **item_ptr() {return &ptr->item; }
field()2874   Field *field() { return 0; }
item()2875   inline Item *item() { return ptr->item; }
field_translator()2876   Field_translator *field_translator() { return ptr; }
2877 };
2878 
2879 
2880 /*
2881   Field_iterator interface to the list of materialized fields of a
2882   NATURAL/USING join.
2883 */
2884 
2885 class Field_iterator_natural_join: public Field_iterator
2886 {
2887   List_iterator_fast<Natural_join_column> column_ref_it;
2888   Natural_join_column *cur_column_ref;
2889 public:
Field_iterator_natural_join()2890   Field_iterator_natural_join() :cur_column_ref(NULL) {}
~Field_iterator_natural_join()2891   ~Field_iterator_natural_join() {}
2892   void set(TABLE_LIST *table);
2893   void next();
end_of_fields()2894   bool end_of_fields() { return !cur_column_ref; }
name()2895   LEX_CSTRING *name() { return cur_column_ref->name(); }
create_item(THD * thd)2896   Item *create_item(THD *thd) { return cur_column_ref->create_item(thd); }
field()2897   Field *field() { return cur_column_ref->field(); }
column_ref()2898   Natural_join_column *column_ref() { return cur_column_ref; }
2899 };
2900 
2901 
2902 /*
2903   Generic iterator over the fields of an arbitrary table reference.
2904 
2905   DESCRIPTION
2906     This class unifies the various ways of iterating over the columns
2907     of a table reference depending on the type of SQL entity it
2908     represents. If such an entity represents a nested table reference,
2909     this iterator encapsulates the iteration over the columns of the
2910     members of the table reference.
2911 
2912   IMPLEMENTATION
2913     The implementation assumes that all underlying NATURAL/USING table
2914     references already contain their result columns and are linked into
2915     the list TABLE_LIST::next_name_resolution_table.
2916 */
2917 
2918 class Field_iterator_table_ref: public Field_iterator
2919 {
2920   TABLE_LIST *table_ref, *first_leaf, *last_leaf;
2921   Field_iterator_table        table_field_it;
2922   Field_iterator_view         view_field_it;
2923   Field_iterator_natural_join natural_join_it;
2924   Field_iterator *field_it;
2925   void set_field_iterator();
2926 public:
Field_iterator_table_ref()2927   Field_iterator_table_ref() :field_it(NULL) {}
2928   void set(TABLE_LIST *table);
2929   void next();
end_of_fields()2930   bool end_of_fields()
2931   { return (table_ref == last_leaf && field_it->end_of_fields()); }
name()2932   LEX_CSTRING *name() { return field_it->name(); }
2933   const char *get_table_name();
2934   const char *get_db_name();
2935   GRANT_INFO *grant();
create_item(THD * thd)2936   Item *create_item(THD *thd) { return field_it->create_item(thd); }
field()2937   Field *field() { return field_it->field(); }
2938   Natural_join_column *get_or_create_column_ref(THD *thd, TABLE_LIST *parent_table_ref);
2939   Natural_join_column *get_natural_column_ref();
2940 };
2941 
2942 
2943 #define JOIN_OP_NEST       1
2944 #define REBALANCED_NEST    2
2945 
2946 typedef struct st_nested_join
2947 {
2948   List<TABLE_LIST>  join_list;       /* list of elements in the nested join */
2949   /*
2950     Currently the valid values for nest type are:
2951     JOIN_OP_NEST - for nest created for JOIN operation used as an operand in
2952     a join expression, contains 2 elements;
2953     JOIN_OP_NEST | REBALANCED_NEST -  nest created after tree re-balancing
2954     in st_select_lex::add_cross_joined_table(), contains 1 element;
2955     0 - for all other nests.
2956     Examples:
2957     1.  SELECT * FROM t1 JOIN t2 LEFT JOIN t3 ON t2.a=t3.a;
2958     Here the nest created for LEFT JOIN at first has nest_type==JOIN_OP_NEST.
2959     After re-balancing in st_select_lex::add_cross_joined_table() this nest
2960     has nest_type==JOIN_OP_NEST | REBALANCED_NEST. The nest for JOIN created
2961     in st_select_lex::add_cross_joined_table() has nest_type== JOIN_OP_NEST.
2962     2.  SELECT * FROM t1 JOIN (t2 LEFT JOIN t3 ON t2.a=t3.a)
2963     Here the nest created for LEFT JOIN has nest_type==0, because it's not
2964     an operand in a join expression. The nest created for JOIN has nest_type
2965     set to JOIN_OP_NEST.
2966   */
2967   uint nest_type;
2968   /*
2969     Bitmap of tables within this nested join (including those embedded within
2970     its children), including tables removed by table elimination.
2971   */
2972   table_map         used_tables;
2973   table_map         not_null_tables; /* tables that rejects nulls           */
2974   /**
2975     Used for pointing out the first table in the plan being covered by this
2976     join nest. It is used exclusively within make_outerjoin_info().
2977    */
2978   struct st_join_table *first_nested;
2979   /*
2980     Used to count tables in the nested join in 2 isolated places:
2981     1. In make_outerjoin_info().
2982     2. check_interleaving_with_nj/restore_prev_nj_state (these are called
2983        by the join optimizer.
2984     Before each use the counters are zeroed by reset_nj_counters.
2985   */
2986   uint              counter;
2987 
2988   /*
2989     Number of elements in join_list that participate in the join plan choice:
2990     - Base tables that were not removed by table elimination
2991     - Join nests that were not removed by mark_join_nest_as_const
2992   */
2993   uint              n_tables;
2994   nested_join_map   nj_map;          /* Bit used to identify this nested join*/
2995   /*
2996     (Valid only for semi-join nests) Bitmap of tables outside the semi-join
2997     that are used within the semi-join's ON condition.
2998   */
2999   table_map         sj_depends_on;
3000   /* Outer non-trivially correlated tables */
3001   table_map         sj_corr_tables;
3002   List<Item_ptr>    sj_outer_expr_list;
3003   /**
3004      True if this join nest node is completely covered by the query execution
3005      plan. This means two things.
3006 
3007      1. All tables on its @c join_list are covered by the plan.
3008 
3009      2. All child join nest nodes are fully covered.
3010    */
is_fully_coveredst_nested_join3011   bool is_fully_covered() const { return n_tables == counter; }
3012 } NESTED_JOIN;
3013 
3014 
3015 typedef struct st_changed_table_list
3016 {
3017   struct	st_changed_table_list *next;
3018   char		*key;
3019   size_t  key_length;
3020 } CHANGED_TABLE_LIST;
3021 
3022 
3023 typedef struct st_open_table_list{
3024   struct st_open_table_list *next;
3025   char	*db,*table;
3026   uint32 in_use,locked;
3027 } OPEN_TABLE_LIST;
3028 
3029 
tmp_use_all_columns(TABLE * table,MY_BITMAP ** bitmap)3030 static inline MY_BITMAP *tmp_use_all_columns(TABLE *table,
3031                                              MY_BITMAP **bitmap)
3032 {
3033   MY_BITMAP *old= *bitmap;
3034   *bitmap= &table->s->all_set;
3035   return old;
3036 }
3037 
3038 
tmp_restore_column_map(MY_BITMAP ** bitmap,MY_BITMAP * old)3039 static inline void tmp_restore_column_map(MY_BITMAP **bitmap,
3040                                           MY_BITMAP *old)
3041 {
3042   *bitmap= old;
3043 }
3044 
3045 /* The following is only needed for debugging */
3046 
dbug_tmp_use_all_columns(TABLE * table,MY_BITMAP ** bitmap)3047 static inline MY_BITMAP *dbug_tmp_use_all_columns(TABLE *table,
3048                                                       MY_BITMAP **bitmap)
3049 {
3050 #ifdef DBUG_ASSERT_EXISTS
3051   return tmp_use_all_columns(table, bitmap);
3052 #else
3053   return 0;
3054 #endif
3055 }
3056 
dbug_tmp_restore_column_map(MY_BITMAP ** bitmap,MY_BITMAP * old)3057 static inline void dbug_tmp_restore_column_map(MY_BITMAP **bitmap,
3058                                                MY_BITMAP *old)
3059 {
3060 #ifdef DBUG_ASSERT_EXISTS
3061   tmp_restore_column_map(bitmap, old);
3062 #endif
3063 }
3064 
3065 
3066 /*
3067   Variant of the above : handle both read and write sets.
3068   Provide for the possiblity of the read set being the same as the write set
3069 */
dbug_tmp_use_all_columns(TABLE * table,MY_BITMAP ** save,MY_BITMAP ** read_set,MY_BITMAP ** write_set)3070 static inline void dbug_tmp_use_all_columns(TABLE *table,
3071                                             MY_BITMAP **save,
3072                                             MY_BITMAP **read_set,
3073                                             MY_BITMAP **write_set)
3074 {
3075 #ifdef DBUG_ASSERT_EXISTS
3076   save[0]= *read_set;
3077   save[1]= *write_set;
3078   (void) tmp_use_all_columns(table, read_set);
3079   (void) tmp_use_all_columns(table, write_set);
3080 #endif
3081 }
3082 
3083 
dbug_tmp_restore_column_maps(MY_BITMAP ** read_set,MY_BITMAP ** write_set,MY_BITMAP ** old)3084 static inline void dbug_tmp_restore_column_maps(MY_BITMAP **read_set,
3085                                                 MY_BITMAP **write_set,
3086                                                 MY_BITMAP **old)
3087 {
3088 #ifdef DBUG_ASSERT_EXISTS
3089   tmp_restore_column_map(read_set, old[0]);
3090   tmp_restore_column_map(write_set, old[1]);
3091 #endif
3092 }
3093 
3094 bool ok_for_lower_case_names(const char *names);
3095 
3096 enum get_table_share_flags {
3097   GTS_TABLE                = 1,
3098   GTS_VIEW                 = 2,
3099   GTS_NOLOCK               = 4,
3100   GTS_USE_DISCOVERY        = 8,
3101   GTS_FORCE_DISCOVERY      = 16
3102 };
3103 
3104 size_t max_row_length(TABLE *table, MY_BITMAP const *cols, const uchar *data);
3105 
3106 void init_mdl_requests(TABLE_LIST *table_list);
3107 
3108 enum open_frm_error open_table_from_share(THD *thd, TABLE_SHARE *share,
3109                        const LEX_CSTRING *alias, uint db_stat, uint prgflag,
3110                        uint ha_open_flags, TABLE *outparam,
3111                        bool is_create_table,
3112                        List<String> *partitions_to_open= NULL);
3113 bool fix_session_vcol_expr(THD *thd, Virtual_column_info *vcol);
3114 bool fix_session_vcol_expr_for_read(THD *thd, Field *field,
3115                                     Virtual_column_info *vcol);
3116 bool parse_vcol_defs(THD *thd, MEM_ROOT *mem_root, TABLE *table,
3117                      bool *error_reported, vcol_init_mode expr);
3118 TABLE_SHARE *alloc_table_share(const char *db, const char *table_name,
3119                                const char *key, uint key_length);
3120 void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
3121                           uint key_length,
3122                           const char *table_name, const char *path);
3123 void free_table_share(TABLE_SHARE *share);
3124 enum open_frm_error open_table_def(THD *thd, TABLE_SHARE *share,
3125                                    uint flags = GTS_TABLE);
3126 
3127 void open_table_error(TABLE_SHARE *share, enum open_frm_error error,
3128                       int db_errno);
3129 void update_create_info_from_table(HA_CREATE_INFO *info, TABLE *form);
3130 bool check_db_name(LEX_STRING *db);
3131 bool check_column_name(const char *name);
3132 bool check_table_name(const char *name, size_t length, bool check_for_path_chars);
3133 int rename_file_ext(const char * from,const char * to,const char * ext);
3134 char *get_field(MEM_ROOT *mem, Field *field);
3135 bool get_field(MEM_ROOT *mem, Field *field, class String *res);
3136 
3137 bool validate_comment_length(THD *thd, LEX_CSTRING *comment, size_t max_len,
3138                              uint err_code, const char *name);
3139 
3140 int closefrm(TABLE *table);
3141 void free_blobs(TABLE *table);
3142 void free_field_buffers_larger_than(TABLE *table, uint32 size);
3143 ulong get_form_pos(File file, uchar *head, TYPELIB *save_names);
3144 void append_unescaped(String *res, const char *pos, size_t length);
3145 void prepare_frm_header(THD *thd, uint reclength, uchar *fileinfo,
3146                         HA_CREATE_INFO *create_info, uint keys, KEY *key_info);
3147 const char *fn_frm_ext(const char *name);
3148 
3149 /* Check that the integer is in the internal */
set_zone(int nr,int min_zone,int max_zone)3150 static inline int set_zone(int nr,int min_zone,int max_zone)
3151 {
3152   if (nr <= min_zone)
3153     return min_zone;
3154   if (nr >= max_zone)
3155     return max_zone;
3156   return nr;
3157 }
3158 
3159 /* performance schema */
3160 extern LEX_CSTRING PERFORMANCE_SCHEMA_DB_NAME;
3161 
3162 extern LEX_CSTRING GENERAL_LOG_NAME;
3163 extern LEX_CSTRING SLOW_LOG_NAME;
3164 extern LEX_CSTRING TRANSACTION_REG_NAME;
3165 
3166 /* information schema */
3167 extern LEX_CSTRING INFORMATION_SCHEMA_NAME;
3168 extern LEX_CSTRING MYSQL_SCHEMA_NAME;
3169 
3170 /* table names */
3171 extern LEX_CSTRING MYSQL_USER_NAME, MYSQL_DB_NAME, MYSQL_PROC_NAME;
3172 
is_infoschema_db(const LEX_CSTRING * name)3173 inline bool is_infoschema_db(const LEX_CSTRING *name)
3174 {
3175   return (INFORMATION_SCHEMA_NAME.length == name->length &&
3176           !my_strcasecmp(system_charset_info,
3177                          INFORMATION_SCHEMA_NAME.str, name->str));
3178 }
3179 
mark_as_null_row(TABLE * table)3180 inline void mark_as_null_row(TABLE *table)
3181 {
3182   table->null_row=1;
3183   table->status|=STATUS_NULL_ROW;
3184   if (table->s->null_bytes)
3185     bfill(table->null_flags,table->s->null_bytes,255);
3186 }
3187 
unmark_as_null_row(TABLE * table)3188 inline void unmark_as_null_row(TABLE *table)
3189 {
3190   table->null_row=0;
3191   table->status= STATUS_NO_RECORD;
3192 }
3193 
3194 bool is_simple_order(ORDER *order);
3195 
3196 class Open_tables_backup;
3197 
3198 /** Transaction Registry Table (TRT)
3199 
3200     This table holds transaction IDs, their corresponding times and other
3201     transaction-related data which is used for transaction order resolution.
3202     When versioned table marks its records lifetime with transaction IDs,
3203     TRT is used to get their actual timestamps. */
3204 
3205 class TR_table: public TABLE_LIST
3206 {
3207   THD *thd;
3208   Open_tables_backup *open_tables_backup;
3209 
3210 public:
3211   enum field_id_t {
3212     FLD_TRX_ID= 0,
3213     FLD_COMMIT_ID,
3214     FLD_BEGIN_TS,
3215     FLD_COMMIT_TS,
3216     FLD_ISO_LEVEL,
3217     FIELD_COUNT
3218   };
3219 
3220   enum enabled {NO, MAYBE, YES};
3221   static enum enabled use_transaction_registry;
3222 
3223   /**
3224      @param[in,out] Thread handle
3225      @param[in] Current transaction is read-write.
3226    */
3227   TR_table(THD *_thd, bool rw= false);
3228   /**
3229      Opens a transaction_registry table.
3230 
3231      @retval true on error, false otherwise.
3232    */
3233   bool open();
3234   ~TR_table();
3235   /**
3236      @retval current thd
3237   */
get_thd()3238   THD *get_thd() const { return thd; }
3239   /**
3240      Stores value to internal transaction_registry TABLE object.
3241 
3242      @param[in] field number in a TABLE
3243      @param[in] value to store
3244    */
3245   void store(uint field_id, ulonglong val);
3246   /**
3247      Stores value to internal transaction_registry TABLE object.
3248 
3249      @param[in] field number in a TABLE
3250      @param[in] value to store
3251    */
3252   void store(uint field_id, timeval ts);
3253   /**
3254     Update the transaction_registry right before commit.
3255     @param start_id    transaction identifier at start
3256     @param end_id      transaction identifier at commit
3257 
3258     @retval false      on success
3259     @retval true       on error (the transaction must be rolled back)
3260   */
3261   bool update(ulonglong start_id, ulonglong end_id);
3262   // return true if found; false if not found or error
3263   bool query(ulonglong trx_id);
3264   /**
3265      Gets a row from transaction_registry with the closest commit_timestamp to
3266      first argument. We can search for a value which a lesser or greater than
3267      first argument. Also loads a row into an internal TABLE object.
3268 
3269      @param[in] timestamp
3270      @param[in] true if we search for a lesser timestamp, false if greater
3271      @retval true if exists, false it not exists or an error occurred
3272    */
3273   bool query(MYSQL_TIME &commit_time, bool backwards);
3274   /**
3275      Checks whether transaction1 sees transaction0.
3276 
3277      @param[out] true if transaction1 sees transaction0, undefined on error and
3278        when transaction1=transaction0 and false otherwise
3279      @param[in] transaction_id of transaction1
3280      @param[in] transaction_id of transaction0
3281      @param[in] commit time of transaction1 or 0 if we want it to be queried
3282      @param[in] isolation level (from handler.h) of transaction1
3283      @param[in] commit time of transaction0 or 0 if we want it to be queried
3284      @retval true on error, false otherwise
3285    */
3286   bool query_sees(bool &result, ulonglong trx_id1, ulonglong trx_id0,
3287                   ulonglong commit_id1= 0,
3288                   enum_tx_isolation iso_level1= ISO_READ_UNCOMMITTED,
3289                   ulonglong commit_id0= 0);
3290 
3291   /**
3292      @retval transaction isolation level of a row from internal TABLE object.
3293    */
3294   enum_tx_isolation iso_level() const;
3295   /**
3296      Stores transactioin isolation level to internal TABLE object.
3297    */
store_iso_level(enum_tx_isolation iso_level)3298   void store_iso_level(enum_tx_isolation iso_level)
3299   {
3300     DBUG_ASSERT(iso_level <= ISO_SERIALIZABLE);
3301     store(FLD_ISO_LEVEL, iso_level + 1);
3302   }
3303 
3304   /**
3305      Writes a message to MariaDB log about incorrect transaction_registry schema.
3306 
3307      @param[in] a message explained what's incorrect in schema
3308    */
3309   void warn_schema_incorrect(const char *reason);
3310   /**
3311      Checks whether transaction_registry table has a correct schema.
3312 
3313      @retval true if schema is incorrect and false otherwise
3314    */
3315   bool check(bool error);
3316 
3317   TABLE * operator-> () const
3318   {
3319     return table;
3320   }
3321   Field * operator[] (uint field_id) const
3322   {
3323     DBUG_ASSERT(field_id < FIELD_COUNT);
3324     return table->field[field_id];
3325   }
3326   operator bool () const
3327   {
3328     return table;
3329   }
3330   bool operator== (const TABLE_LIST &subj) const
3331   {
3332     return (!cmp(&db, &subj.db) && !cmp(&table_name, &subj.table_name));
3333   }
3334   bool operator!= (const TABLE_LIST &subj) const
3335   {
3336     return !(*this == subj);
3337   }
3338 };
3339 
3340 #endif /* MYSQL_CLIENT */
3341 
3342 #endif /* TABLE_INCLUDED */
3343