1 #ifndef TABLE_INCLUDED
2 #define TABLE_INCLUDED
3 
4 /* Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
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, version 2.0,
8    as published by the Free Software Foundation.
9 
10    This program is also distributed with certain software (including
11    but not limited to OpenSSL) that is licensed under separate terms,
12    as designated in a particular file or component or in included license
13    documentation.  The authors of MySQL hereby grant you an additional
14    permission to link the program and your derivative works with the
15    separately licensed software that they have included with MySQL.
16 
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License, version 2.0, for more details.
21 
22    You should have received a copy of the GNU General Public License
23    along with this program; if not, write to the Free Software
24    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
25 
26 #include "my_global.h"                          /* NO_EMBEDDED_ACCESS_CHECKS */
27 #include "sql_plist.h"
28 #include "sql_alloc.h"
29 #include "mdl.h"
30 #include "datadict.h"
31 
32 #ifndef MYSQL_CLIENT
33 
34 #include "hash.h"                               /* HASH */
35 #include "handler.h"                /* row_type, ha_choice, handler */
36 #include "mysql_com.h"              /* enum_field_types */
37 #include "thr_lock.h"                  /* thr_lock_type */
38 #include "filesort_utils.h"
39 #include "parse_file.h"
40 #include "table_id.h"
41 
42 /* Structs that defines the TABLE */
43 
44 class Item;				/* Needed by ORDER */
45 class Item_subselect;
46 class Item_field;
47 class GRANT_TABLE;
48 class st_select_lex_unit;
49 class st_select_lex;
50 class partition_info;
51 class COND_EQUAL;
52 class Security_context;
53 struct TABLE_LIST;
54 class ACL_internal_schema_access;
55 class ACL_internal_table_access;
56 class Field;
57 class Field_temporal_with_date_and_time;
58 class Table_cache_element;
59 
60 /*
61   Used to identify NESTED_JOIN structures within a join (applicable to
62   structures representing outer joins that have not been simplified away).
63 */
64 typedef ulonglong nested_join_map;
65 
66 
67 #define tmp_file_prefix "#sql"			/**< Prefix for tmp tables */
68 #define tmp_file_prefix_length 4
69 #define TMP_TABLE_KEY_EXTRA 8
70 
71 /**
72   Enumerate possible types of a table from re-execution
73   standpoint.
74   TABLE_LIST class has a member of this type.
75   At prepared statement prepare, this member is assigned a value
76   as of the current state of the database. Before (re-)execution
77   of a prepared statement, we check that the value recorded at
78   prepare matches the type of the object we obtained from the
79   table definition cache.
80 
81   @sa check_and_update_table_version()
82   @sa Execute_observer
83   @sa Prepared_statement::reprepare()
84 */
85 
86 enum enum_table_ref_type
87 {
88   /** Initial value set by the parser */
89   TABLE_REF_NULL= 0,
90   TABLE_REF_VIEW,
91   TABLE_REF_BASE_TABLE,
92   TABLE_REF_I_S_TABLE,
93   TABLE_REF_TMP_TABLE
94 };
95 
96 /**
97  Enumerate possible status of a identifier name while determining
98  its validity
99 */
100 enum enum_ident_name_check
101 {
102   IDENT_NAME_OK,
103   IDENT_NAME_WRONG,
104   IDENT_NAME_TOO_LONG
105 };
106 
107 /*************************************************************************/
108 
109 /**
110  Object_creation_ctx -- interface for creation context of database objects
111  (views, stored routines, events, triggers). Creation context -- is a set
112  of attributes, that should be fixed at the creation time and then be used
113  each time the object is parsed or executed.
114 */
115 
116 class Object_creation_ctx
117 {
118 public:
119   Object_creation_ctx *set_n_backup(THD *thd);
120 
121   void restore_env(THD *thd, Object_creation_ctx *backup_ctx);
122 
123 protected:
Object_creation_ctx()124   Object_creation_ctx() {}
125   virtual Object_creation_ctx *create_backup_ctx(THD *thd) const = 0;
126 
127   virtual void change_env(THD *thd) const = 0;
128 
129 public:
~Object_creation_ctx()130   virtual ~Object_creation_ctx()
131   { }
132 };
133 
134 /*************************************************************************/
135 
136 /**
137  Default_object_creation_ctx -- default implementation of
138  Object_creation_ctx.
139 */
140 
141 class Default_object_creation_ctx : public Object_creation_ctx
142 {
143 public:
get_client_cs()144   const CHARSET_INFO *get_client_cs()
145   {
146     return m_client_cs;
147   }
148 
get_connection_cl()149   const CHARSET_INFO *get_connection_cl()
150   {
151     return m_connection_cl;
152   }
153 
154 protected:
155   Default_object_creation_ctx(THD *thd);
156 
157   Default_object_creation_ctx(const CHARSET_INFO *client_cs,
158                               const CHARSET_INFO *connection_cl);
159 
160 protected:
161   virtual Object_creation_ctx *create_backup_ctx(THD *thd) const;
162 
163   virtual void change_env(THD *thd) const;
164 
165 protected:
166   /**
167     client_cs stores the value of character_set_client session variable.
168     The only character set attribute is used.
169 
170     Client character set is included into query context, because we save
171     query in the original character set, which is client character set. So,
172     in order to parse the query properly we have to switch client character
173     set on parsing.
174   */
175   const CHARSET_INFO *m_client_cs;
176 
177   /**
178     connection_cl stores the value of collation_connection session
179     variable. Both character set and collation attributes are used.
180 
181     Connection collation is included into query context, becase it defines
182     the character set and collation of text literals in internal
183     representation of query (item-objects).
184   */
185   const CHARSET_INFO *m_connection_cl;
186 };
187 
188 
189 /**
190  View_creation_ctx -- creation context of view objects.
191 */
192 
193 class View_creation_ctx : public Default_object_creation_ctx,
194                           public Sql_alloc
195 {
196 public:
197   static View_creation_ctx *create(THD *thd);
198 
199   static View_creation_ctx *create(THD *thd,
200                                    TABLE_LIST *view);
201 
202 private:
View_creation_ctx(THD * thd)203   View_creation_ctx(THD *thd)
204     : Default_object_creation_ctx(thd)
205   { }
206 };
207 
208 /*************************************************************************/
209 
210 /** Order clause list element */
211 
212 typedef struct st_order {
213   struct st_order *next;
214   Item   **item;                        /* Point at item in select fields */
215   Item   *item_ptr;                     /* Storage for initial item */
216   int    counter;                       /* position in SELECT list, correct
217                                            only if counter_used is true */
218   enum enum_order {
219     ORDER_NOT_RELEVANT,
220     ORDER_ASC,
221     ORDER_DESC
222   };
223 
224   enum_order direction;                 /* Requested direction of ordering */
225   bool   in_field_list;                 /* true if in select field list */
226   bool   counter_used;                  /* parameter was counter of columns */
227   /**
228      Tells whether this ORDER element was referenced with an alias or with an
229      expression, in the query:
230      SELECT a AS foo GROUP BY foo: true.
231      SELECT a AS foo GROUP BY a: false.
232   */
233   bool   used_alias;
234   Field  *field;                        /* If tmp-table group */
235   char   *buff;                         /* If tmp-table group */
236   table_map used, depend_map;
237 } ORDER;
238 
239 /**
240   State information for internal tables grants.
241   This structure is part of the TABLE_LIST, and is updated
242   during the ACL check process.
243   @sa GRANT_INFO
244 */
245 struct st_grant_internal_info
246 {
247   /** True if the internal lookup by schema name was done. */
248   bool m_schema_lookup_done;
249   /** Cached internal schema access. */
250   const ACL_internal_schema_access *m_schema_access;
251   /** True if the internal lookup by table name was done. */
252   bool m_table_lookup_done;
253   /** Cached internal table access. */
254   const ACL_internal_table_access *m_table_access;
255 };
256 typedef struct st_grant_internal_info GRANT_INTERNAL_INFO;
257 
258 /**
259    @brief The current state of the privilege checking process for the current
260    user, SQL statement and SQL object.
261 
262    @details The privilege checking process is divided into phases depending on
263    the level of the privilege to be checked and the type of object to be
264    accessed. Due to the mentioned scattering of privilege checking
265    functionality, it is necessary to keep track of the state of the
266    process. This information is stored in privilege, want_privilege, and
267    orig_want_privilege.
268 
269    A GRANT_INFO also serves as a cache of the privilege hash tables. Relevant
270    members are grant_table and version.
271  */
272 typedef struct st_grant_info
273 {
274   /**
275      @brief A copy of the privilege information regarding the current host,
276      database, object and user.
277 
278      @details The version of this copy is found in GRANT_INFO::version.
279    */
280   GRANT_TABLE *grant_table;
281   /**
282      @brief Used for cache invalidation when caching privilege information.
283 
284      @details The privilege information is stored on disk, with dedicated
285      caches residing in memory: table-level and column-level privileges,
286      respectively, have their own dedicated caches.
287 
288      The GRANT_INFO works as a level 1 cache with this member updated to the
289      current value of the global variable @c grant_version (@c static variable
290      in sql_acl.cc). It is updated Whenever the GRANT_INFO is refreshed from
291      the level 2 cache. The level 2 cache is the @c column_priv_hash structure
292      (@c static variable in sql_acl.cc)
293 
294      @see grant_version
295    */
296   uint version;
297   /**
298      @brief The set of privileges that the current user has fulfilled for a
299      certain host, database, and object.
300 
301      @details This field is continually updated throughout the access checking
302      process. In each step the "wanted privilege" is checked against the
303      fulfilled privileges. When/if the intersection of these sets is empty,
304      access is granted.
305 
306      The set is implemented as a bitmap, with the bits defined in sql_acl.h.
307    */
308   ulong privilege;
309   /**
310      @brief the set of privileges that the current user needs to fulfil in
311      order to carry out the requested operation.
312    */
313   ulong want_privilege;
314   /**
315     Stores the requested access acl of top level tables list. Is used to
316     check access rights to the underlying tables of a view.
317   */
318   ulong orig_want_privilege;
319   /** The grant state for internal tables. */
320   GRANT_INTERNAL_INFO m_internal;
321 } GRANT_INFO;
322 
323 enum tmp_table_type
324 {
325   NO_TMP_TABLE, NON_TRANSACTIONAL_TMP_TABLE, TRANSACTIONAL_TMP_TABLE,
326   INTERNAL_TMP_TABLE, SYSTEM_TMP_TABLE
327 };
328 enum release_type { RELEASE_NORMAL, RELEASE_WAIT_FOR_DROP };
329 
330 
331 class Filesort_info
332 {
333   /// Buffer for sorting keys.
334   Filesort_buffer filesort_buffer;
335 
336 public:
337   IO_CACHE *io_cache;           /* If sorted through filesort */
338   uchar     *buffpek;           /* Buffer for buffpek structures */
339   uint      buffpek_len;        /* Max number of buffpeks in the buffer */
340   uchar     *addon_buf;         /* Pointer to a buffer if sorted with fields */
341   size_t    addon_length;       /* Length of the buffer */
342   struct st_sort_addon_field *addon_field;     /* Pointer to the fields info */
343   void    (*unpack)(struct st_sort_addon_field *, uchar *); /* To unpack back */
344   uchar     *record_pointers;    /* If sorted in memory */
345   ha_rows   found_records;      /* How many records in sort */
346 
Filesort_info()347   Filesort_info(): record_pointers(0) {};
348   /** Sort filesort_buffer */
sort_buffer(Sort_param * param,uint count)349   void sort_buffer(Sort_param *param, uint count)
350   { filesort_buffer.sort_buffer(param, count); }
351 
352   /**
353      Accessors for Filesort_buffer (which @c).
354   */
get_record_buffer(uint idx)355   uchar *get_record_buffer(uint idx)
356   { return filesort_buffer.get_record_buffer(idx); }
357 
get_sort_keys()358   uchar **get_sort_keys()
359   { return filesort_buffer.get_sort_keys(); }
360 
alloc_sort_buffer(uint num_records,uint record_length)361   uchar **alloc_sort_buffer(uint num_records, uint record_length)
362   { return filesort_buffer.alloc_sort_buffer(num_records, record_length); }
363 
free_sort_buffer()364   void free_sort_buffer()
365   { filesort_buffer.free_sort_buffer(); }
366 
init_record_pointers()367   void init_record_pointers()
368   { filesort_buffer.init_record_pointers(); }
369 
sort_buffer_size()370   size_t sort_buffer_size() const
371   { return filesort_buffer.sort_buffer_size(); }
372 };
373 
374 class Field_blob;
375 class Table_triggers_list;
376 
377 /**
378   Category of table found in the table share.
379 */
380 enum enum_table_category
381 {
382   /**
383     Unknown value.
384   */
385   TABLE_UNKNOWN_CATEGORY=0,
386 
387   /**
388     Temporary table.
389     The table is visible only in the session.
390     Therefore,
391     - FLUSH TABLES WITH READ LOCK
392     - SET GLOBAL READ_ONLY = ON
393     do not apply to this table.
394     Note that LOCK TABLE t FOR READ/WRITE
395     can be used on temporary tables.
396     Temporary tables are not part of the table cache.
397   */
398   TABLE_CATEGORY_TEMPORARY=1,
399 
400   /**
401     User table.
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     User tables are cached in the table cache.
407   */
408   TABLE_CATEGORY_USER=2,
409 
410   /**
411     System table, maintained by the server.
412     These tables do honor:
413     - LOCK TABLE t FOR READ/WRITE
414     - FLUSH TABLES WITH READ LOCK
415     - SET GLOBAL READ_ONLY = ON
416     Typically, writes to system tables are performed by
417     the server implementation, not explicitly be a user.
418     System tables are cached in the table cache.
419   */
420   TABLE_CATEGORY_SYSTEM=3,
421 
422   /**
423     Information schema tables.
424     These tables are an interface provided by the system
425     to inspect the system metadata.
426     These tables do *not* honor:
427     - LOCK TABLE t FOR READ/WRITE
428     - FLUSH TABLES WITH READ LOCK
429     - SET GLOBAL READ_ONLY = ON
430     as there is no point in locking explicitly
431     an INFORMATION_SCHEMA table.
432     Nothing is directly written to information schema tables.
433     Note that this value is not used currently,
434     since information schema tables are not shared,
435     but implemented as session specific temporary tables.
436   */
437   /*
438     TODO: Fixing the performance issues of I_S will lead
439     to I_S tables in the table cache, which should use
440     this table type.
441   */
442   TABLE_CATEGORY_INFORMATION=4,
443 
444   /**
445     Log tables.
446     These tables are an interface provided by the system
447     to inspect the system logs.
448     These tables do *not* honor:
449     - LOCK TABLE t FOR READ/WRITE
450     - FLUSH TABLES WITH READ LOCK
451     - SET GLOBAL READ_ONLY = ON
452     as there is no point in locking explicitly
453     a LOG table.
454     An example of LOG tables are:
455     - mysql.slow_log
456     - mysql.general_log,
457     which *are* updated even when there is either
458     a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
459     User queries do not write directly to these tables
460     (there are exceptions for log tables).
461     The server implementation perform writes.
462     Log tables are cached in the table cache.
463   */
464   TABLE_CATEGORY_LOG=5,
465 
466   /**
467     Performance schema tables.
468     These tables are an interface provided by the system
469     to inspect the system performance data.
470     These tables do *not* honor:
471     - LOCK TABLE t FOR READ/WRITE
472     - FLUSH TABLES WITH READ LOCK
473     - SET GLOBAL READ_ONLY = ON
474     as there is no point in locking explicitly
475     a PERFORMANCE_SCHEMA table.
476     An example of PERFORMANCE_SCHEMA tables are:
477     - performance_schema.*
478     which *are* updated (but not using the handler interface)
479     even when there is either
480     a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
481     User queries do not write directly to these tables
482     (there are exceptions for SETUP_* tables).
483     The server implementation perform writes.
484     Performance tables are cached in the table cache.
485   */
486   TABLE_CATEGORY_PERFORMANCE=6,
487 
488   /**
489     Replication Information Tables.
490     These tables are used to store replication information.
491     These tables do *not* honor:
492     - LOCK TABLE t FOR READ/WRITE
493     - FLUSH TABLES WITH READ LOCK
494     - SET GLOBAL READ_ONLY = ON
495     as there is no point in locking explicitly
496     a Replication Information table.
497     An example of replication tables are:
498     - mysql.slave_master_info
499     - mysql.slave_relay_log_info,
500     which *are* updated even when there is either
501     a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
502     User queries do not write directly to these tables.
503     Replication tables are cached in the table cache.
504   */
505   TABLE_CATEGORY_RPL_INFO=7
506 };
507 typedef enum enum_table_category TABLE_CATEGORY;
508 
509 TABLE_CATEGORY get_table_category(const LEX_STRING *db,
510                                   const LEX_STRING *name);
511 
512 
513 extern ulong refresh_version;
514 
515 typedef struct st_table_field_type
516 {
517   LEX_STRING name;
518   LEX_STRING type;
519   LEX_STRING cset;
520 } TABLE_FIELD_TYPE;
521 
522 
523 typedef struct st_table_field_def
524 {
525   uint count;
526   const TABLE_FIELD_TYPE *field;
527 } TABLE_FIELD_DEF;
528 
529 
530 class Table_check_intact
531 {
532 protected:
533   bool has_keys;
534   virtual void report_error(uint code, const char *fmt, ...)= 0;
535 
536 public:
Table_check_intact()537   Table_check_intact() : has_keys(FALSE) {}
~Table_check_intact()538   virtual ~Table_check_intact() {}
539 
540   /** Checks whether a table is intact. */
541   bool check(TABLE *table, const TABLE_FIELD_DEF *table_def);
542 };
543 
544 
545 /**
546   Class representing the fact that some thread waits for table
547   share to be flushed. Is used to represent information about
548   such waits in MDL deadlock detector.
549 */
550 
551 class Wait_for_flush : public MDL_wait_for_subgraph
552 {
553   MDL_context *m_ctx;
554   TABLE_SHARE *m_share;
555   uint m_deadlock_weight;
556 public:
Wait_for_flush(MDL_context * ctx_arg,TABLE_SHARE * share_arg,uint deadlock_weight_arg)557   Wait_for_flush(MDL_context *ctx_arg, TABLE_SHARE *share_arg,
558                uint deadlock_weight_arg)
559     : m_ctx(ctx_arg), m_share(share_arg),
560       m_deadlock_weight(deadlock_weight_arg)
561   {}
562 
get_ctx()563   MDL_context *get_ctx() const { return m_ctx; }
564 
565   virtual bool accept_visitor(MDL_wait_for_graph_visitor *dvisitor);
566 
567   virtual uint get_deadlock_weight() const;
568 
569   /**
570     Pointers for participating in the list of waiters for table share.
571   */
572   Wait_for_flush *next_in_share;
573   Wait_for_flush **prev_in_share;
574 };
575 
576 
577 typedef I_P_List <Wait_for_flush,
578                   I_P_List_adapter<Wait_for_flush,
579                                    &Wait_for_flush::next_in_share,
580                                    &Wait_for_flush::prev_in_share> >
581                  Wait_for_flush_list;
582 
583 
584 /**
585   This structure is shared between different table objects. There is one
586   instance of table share per one table in the database.
587 */
588 
589 struct TABLE_SHARE
590 {
TABLE_SHARETABLE_SHARE591   TABLE_SHARE() {}                    /* Remove gcc warning */
592 
593   /** Category of this table. */
594   TABLE_CATEGORY table_category;
595 
596   /* hash of field names (contains pointers to elements of field array) */
597   HASH	name_hash;			/* hash of field names */
598   MEM_ROOT mem_root;
599   TYPELIB keynames;			/* Pointers to keynames */
600   TYPELIB fieldnames;			/* Pointer to fieldnames */
601   TYPELIB *intervals;			/* pointer to interval info */
602   mysql_mutex_t LOCK_ha_data;           /* To protect access to ha_data */
603   TABLE_SHARE *next, **prev;            /* Link to unused shares */
604   /**
605     Array of table_cache_instances pointers to elements of table caches
606     respresenting this table in each of Table_cache instances.
607     Allocated along with the share itself in alloc_table_share().
608     Each element of the array is protected by Table_cache::m_lock in the
609     corresponding Table_cache. False sharing should not be a problem in
610     this case as elements of this array are supposed to be updated rarely.
611   */
612   Table_cache_element **cache_element;
613 
614   /* The following is copied to each TABLE on OPEN */
615   Field **field;
616   Field **found_next_number_field;
617   KEY  *key_info;			/* data of keys defined for the table */
618   uint	*blob_field;			/* Index to blobs in Field arrray*/
619 
620   uchar	*default_values;		/* row with default values */
621   LEX_STRING comment;			/* Comment about table */
622   const CHARSET_INFO *table_charset;	/* Default charset of string fields */
623 
624   MY_BITMAP all_set;
625   /*
626     Key which is used for looking-up table in table cache and in the list
627     of thread's temporary tables. Has the form of:
628       "database_name\0table_name\0" + optional part for temporary tables.
629 
630     Note that all three 'table_cache_key', 'db' and 'table_name' members
631     must be set (and be non-zero) for tables in table cache. They also
632     should correspond to each other.
633     To ensure this one can use set_table_cache() methods.
634   */
635   LEX_STRING table_cache_key;
636   LEX_STRING db;                        /* Pointer to db */
637   LEX_STRING table_name;                /* Table name (for open) */
638   LEX_STRING path;                	/* Path to .frm file (from datadir) */
639   LEX_STRING normalized_path;		/* unpack_filename(path) */
640   LEX_STRING connect_string;
641 
642   /*
643      Set of keys in use, implemented as a Bitmap.
644      Excludes keys disabled by ALTER TABLE ... DISABLE KEYS.
645   */
646   key_map keys_in_use;
647   key_map keys_for_keyread;
648   ha_rows min_rows, max_rows;		/* create information */
649   ulong   avg_row_length;		/* create information */
650   /**
651     TABLE_SHARE version, if changed the TABLE_SHARE must be reopened.
652     NOTE: The TABLE_SHARE will not be reopened during LOCK TABLES in
653     close_thread_tables!!!
654   */
655   ulong   version;
656   ulong   mysql_version;		/* 0 if .frm is created before 5.0 */
657   ulong   reclength;			/* Recordlength */
658 
659   plugin_ref db_plugin;			/* storage engine plugin */
db_typeTABLE_SHARE660   inline handlerton *db_type() const	/* table_type for handler */
661   {
662     // DBUG_ASSERT(db_plugin);
663     return db_plugin ? plugin_data(db_plugin, handlerton*) : NULL;
664   }
665   enum row_type row_type;		/* How rows are stored */
666   enum tmp_table_type tmp_table;
667 
668   uint ref_count;                       /* How many TABLE objects uses this */
669   uint key_block_size;			/* create key_block_size, if used */
670   uint stats_sample_pages;		/* number of pages to sample during
671 					stats estimation, if used, otherwise 0. */
672   enum_stats_auto_recalc stats_auto_recalc; /* Automatic recalc of stats. */
673   uint null_bytes, last_null_bit_pos;
674   uint fields;				/* Number of fields */
675   uint rec_buff_length;                 /* Size of table->record[] buffer */
676   uint keys;                            /* Number of keys defined for the table*/
677   uint key_parts;                       /* Number of key parts of all keys
678                                            defined for the table
679                                         */
680   uint max_key_length;                  /* Length of the longest key */
681   uint max_unique_length;               /* Length of the longest unique key */
682   uint total_key_length;
683   uint uniques;                         /* Number of UNIQUE index */
684   uint null_fields;			/* number of null fields */
685   uint blob_fields;			/* number of blob fields */
686   uint varchar_fields;                  /* number of varchar fields */
687   uint db_create_options;		/* Create options from database */
688   uint db_options_in_use;		/* Options in use */
689   uint db_record_offset;		/* if HA_REC_IN_SEQ */
690   uint rowid_field_offset;		/* Field_nr +1 to rowid field */
691   /* Primary key index number, used in TABLE::key_info[] */
692   uint primary_key;
693   uint next_number_index;               /* autoincrement key number */
694   uint next_number_key_offset;          /* autoinc keypart offset in a key */
695   uint next_number_keypart;             /* autoinc keypart number in a key */
696   uint error, open_errno, errarg;       /* error from open_table_def() */
697   uint column_bitmap_size;
698   uchar frm_version;
699   bool null_field_first;
700   bool system;                          /* Set if system table (one record) */
701   bool crypted;                         /* If .frm file is crypted */
702   bool db_low_byte_first;		/* Portable row format */
703   bool crashed;
704   bool is_view;
705   Table_id table_map_id;                   /* for row-based replication */
706 
707   /*
708     Cache for row-based replication table share checks that does not
709     need to be repeated. Possible values are: -1 when cache value is
710     not calculated yet, 0 when table *shall not* be replicated, 1 when
711     table *may* be replicated.
712   */
713   int cached_row_logging_check;
714 
715   /*
716     Storage media to use for this table (unless another storage
717     media has been specified on an individual column - in versions
718     where that is supported)
719   */
720   enum ha_storage_media default_storage_media;
721 
722   /* Name of the tablespace used for this table */
723   char *tablespace;
724 
725 #ifdef WITH_PARTITION_STORAGE_ENGINE
726   /* filled in when reading from frm */
727   bool auto_partitioned;
728   char *partition_info_str;
729   uint  partition_info_str_len;
730   uint  partition_info_buffer_size;
731   handlerton *default_part_db_type;
732 #endif
733 
734   /**
735     Cache the checked structure of this table.
736 
737     The pointer data is used to describe the structure that
738     a instance of the table must have. Each element of the
739     array specifies a field that must exist on the table.
740 
741     The pointer is cached in order to perform the check only
742     once -- when the table is loaded from the disk.
743   */
744   const TABLE_FIELD_DEF *table_field_def_cache;
745 
746   /** Main handler's share */
747   Handler_share *ha_share;
748 
749   /** Instrumentation for this table share. */
750   PSI_table_share *m_psi;
751 
752   /**
753     List of tickets representing threads waiting for the share to be flushed.
754   */
755   Wait_for_flush_list m_flush_tickets;
756 
757   /**
758     For shares representing views File_parser object with view
759     definition read from .FRM file.
760   */
761   const File_parser *view_def;
762 
763 
764   /*
765     Set share's table cache key and update its db and table name appropriately.
766 
767     SYNOPSIS
768       set_table_cache_key()
769         key_buff    Buffer with already built table cache key to be
770                     referenced from share.
771         key_length  Key length.
772 
773     NOTES
774       Since 'key_buff' buffer will be referenced from share it should has same
775       life-time as share itself.
776       This method automatically ensures that TABLE_SHARE::table_name/db have
777       appropriate values by using table cache key as their source.
778   */
779 
set_table_cache_keyTABLE_SHARE780   void set_table_cache_key(char *key_buff, uint key_length)
781   {
782     table_cache_key.str= key_buff;
783     table_cache_key.length= key_length;
784     /*
785       Let us use the fact that the key is "db/0/table_name/0" + optional
786       part for temporary tables.
787     */
788     db.str=            table_cache_key.str;
789     db.length=         strlen(db.str);
790     table_name.str=    db.str + db.length + 1;
791     table_name.length= strlen(table_name.str);
792   }
793 
794 
795   /*
796     Set share's table cache key and update its db and table name appropriately.
797 
798     SYNOPSIS
799       set_table_cache_key()
800         key_buff    Buffer to be used as storage for table cache key
801                     (should be at least key_length bytes).
802         key         Value for table cache key.
803         key_length  Key length.
804 
805     NOTE
806       Since 'key_buff' buffer will be used as storage for table cache key
807       it should has same life-time as share itself.
808   */
809 
set_table_cache_keyTABLE_SHARE810   void set_table_cache_key(char *key_buff, const char *key, uint key_length)
811   {
812     memcpy(key_buff, key, key_length);
813     set_table_cache_key(key_buff, key_length);
814   }
815 
honor_global_locksTABLE_SHARE816   inline bool honor_global_locks()
817   {
818     return ((table_category == TABLE_CATEGORY_USER)
819             || (table_category == TABLE_CATEGORY_SYSTEM));
820   }
821 
get_table_def_versionTABLE_SHARE822   inline ulonglong get_table_def_version()
823   {
824     return table_map_id;
825   }
826 
827 
828   /** Is this table share being expelled from the table definition cache?  */
has_old_versionTABLE_SHARE829   inline bool has_old_version() const
830   {
831     return version != refresh_version;
832   }
833   /**
834     Convert unrelated members of TABLE_SHARE to one enum
835     representing its type.
836 
837     @todo perhaps we need to have a member instead of a function.
838   */
get_table_ref_typeTABLE_SHARE839   enum enum_table_ref_type get_table_ref_type() const
840   {
841     if (is_view)
842       return TABLE_REF_VIEW;
843     switch (tmp_table) {
844     case NO_TMP_TABLE:
845       return TABLE_REF_BASE_TABLE;
846     case SYSTEM_TMP_TABLE:
847       return TABLE_REF_I_S_TABLE;
848     default:
849       return TABLE_REF_TMP_TABLE;
850     }
851   }
852   /**
853     Return a table metadata version.
854      * for base tables and views, we return table_map_id.
855        It is assigned from a global counter incremented for each
856        new table loaded into the table definition cache (TDC).
857      * for temporary tables it's table_map_id again. But for
858        temporary tables table_map_id is assigned from
859        thd->query_id. The latter is assigned from a thread local
860        counter incremented for every new SQL statement. Since
861        temporary tables are thread-local, each temporary table
862        gets a unique id.
863      * for everything else (e.g. information schema tables),
864        the version id is zero.
865 
866    This choice of version id is a large compromise
867    to have a working prepared statement validation in 5.1. In
868    future version ids will be persistent, as described in WL#4180.
869 
870    Let's try to explain why and how this limited solution allows
871    to validate prepared statements.
872 
873    Firstly, sets (in mathematical sense) of version numbers
874    never intersect for different table types. Therefore,
875    version id of a temporary table is never compared with
876    a version id of a view, and vice versa.
877 
878    Secondly, for base tables and views, we know that each DDL flushes
879    the respective share from the TDC. This ensures that whenever
880    a table is altered or dropped and recreated, it gets a new
881    version id.
882    Unfortunately, since elements of the TDC are also flushed on
883    LRU basis, this choice of version ids leads to false positives.
884    E.g. when the TDC size is too small, we may have a SELECT
885    * FROM INFORMATION_SCHEMA.TABLES flush all its elements, which
886    in turn will lead to a validation error and a subsequent
887    reprepare of all prepared statements.  This is
888    considered acceptable, since as long as prepared statements are
889    automatically reprepared, spurious invalidation is only
890    a performance hit. Besides, no better simple solution exists.
891 
892    For temporary tables, using thd->query_id ensures that if
893    a temporary table was altered or recreated, a new version id is
894    assigned. This suits validation needs very well and will perhaps
895    never change.
896 
897    Metadata of information schema tables never changes.
898    Thus we can safely assume 0 for a good enough version id.
899 
900    Finally, by taking into account table type, we always
901    track that a change has taken place when a view is replaced
902    with a base table, a base table is replaced with a temporary
903    table and so on.
904 
905    @sa TABLE_LIST::is_table_ref_id_equal()
906   */
get_table_ref_versionTABLE_SHARE907   ulonglong get_table_ref_version() const
908   {
909     return (tmp_table == SYSTEM_TMP_TABLE) ? 0 : table_map_id.id();
910   }
911 
912   bool visit_subgraph(Wait_for_flush *waiting_ticket,
913                       MDL_wait_for_graph_visitor *gvisitor);
914 
915   bool wait_for_old_version(THD *thd, struct timespec *abstime,
916                             uint deadlock_weight);
917   /** Release resources and free memory occupied by the table share. */
918   void destroy();
919 };
920 
921 
922 /**
923    Class is used as a BLOB field value storage for
924    intermediate GROUP_CONCAT results. Used only for
925    GROUP_CONCAT with  DISTINCT or ORDER BY options.
926  */
927 
928 class Blob_mem_storage: public Sql_alloc
929 {
930 private:
931   MEM_ROOT storage;
932   /**
933     Sign that some values were cut
934     during saving into the storage.
935   */
936   bool truncated_value;
937 public:
Blob_mem_storage()938   Blob_mem_storage() :truncated_value(false)
939   {
940     init_alloc_root(&storage, MAX_FIELD_VARCHARLENGTH, 0);
941   }
~Blob_mem_storage()942   ~ Blob_mem_storage()
943   {
944     free_root(&storage, MYF(0));
945   }
reset()946   void reset()
947   {
948     free_root(&storage, MYF(MY_MARK_BLOCKS_FREE));
949     truncated_value= false;
950   }
951   /**
952      Fuction creates duplicate of 'from'
953      string in 'storage' MEM_ROOT.
954 
955      @param from           string to copy
956      @param length         string length
957 
958      @retval Pointer to the copied string.
959      @retval 0 if an error occured.
960   */
store(const char * from,uint length)961   char *store(const char *from, uint length)
962   {
963     return (char*) memdup_root(&storage, from, length);
964   }
set_truncated_value(bool is_truncated_value)965   void set_truncated_value(bool is_truncated_value)
966   {
967     truncated_value= is_truncated_value;
968   }
is_truncated_value()969   bool is_truncated_value() { return truncated_value; }
970 };
971 
972 
973 /* Information for one open table */
974 enum index_hint_type
975 {
976   INDEX_HINT_IGNORE,
977   INDEX_HINT_USE,
978   INDEX_HINT_FORCE
979 };
980 
981 /* Bitmap of table's fields */
982 typedef Bitmap<MAX_FIELDS> Field_map;
983 
984 struct TABLE
985 {
TABLETABLE986   TABLE() {}                               /* Remove gcc warning */
987   /*
988     Since TABLE instances are often cleared using memset(), do not
989     add virtual members and do not inherit from TABLE.
990     Otherwise memset() will start overwriting the vtable pointer.
991   */
992 
993   TABLE_SHARE	*s;
994   handler	*file;
995   TABLE *next, *prev;
996 
997 private:
998   /**
999      Links for the lists of used/unused TABLE objects for the particular
1000      table in the specific instance of Table_cache (in other words for
1001      specific Table_cache_element object).
1002      Declared as private to avoid direct manipulation with those objects.
1003      One should use methods of I_P_List template instead.
1004   */
1005   TABLE *cache_next, **cache_prev;
1006 
1007   /*
1008     Give Table_cache_element access to the above two members to allow
1009     using them for linking TABLE objects in a list.
1010   */
1011   friend class Table_cache_element;
1012 
1013 public:
1014 
1015   THD	*in_use;                        /* Which thread uses this */
1016   Field **field;			/* Pointer to fields */
1017 
1018   uchar *record[2];			/* Pointer to records */
1019   uchar *write_row_record;		/* Used as optimisation in
1020 					   THD::write_row */
1021   uchar *insert_values;                  /* used by INSERT ... UPDATE */
1022   /*
1023     Map of keys that can be used to retrieve all data from this table
1024     needed by the query without reading the row.
1025   */
1026   key_map covering_keys;
1027   key_map quick_keys, merge_keys;
1028   key_map used_keys;  /* Indexes that cover all fields used by the query */
1029 
1030   /*
1031     possible_quick_keys is a superset of quick_keys to use with EXPLAIN of
1032     JOIN-less commands (single-table UPDATE and DELETE).
1033 
1034     When explaining regular JOINs, we use JOIN_TAB::keys to output the
1035     "possible_keys" column value. However, it is not available for
1036     single-table UPDATE and DELETE commands, since they don't use JOIN
1037     optimizer at the top level. OTOH they directly use the range optimizer,
1038     that collects all keys usable for range access here.
1039   */
1040   key_map possible_quick_keys;
1041 
1042   /*
1043     A set of keys that can be used in the query that references this
1044     table.
1045 
1046     All indexes disabled on the table's TABLE_SHARE (see TABLE::s) will be
1047     subtracted from this set upon instantiation. Thus for any TABLE t it holds
1048     that t.keys_in_use_for_query is a subset of t.s.keys_in_use. Generally we
1049     must not introduce any new keys here (see setup_tables).
1050 
1051     The set is implemented as a bitmap.
1052   */
1053   key_map keys_in_use_for_query;
1054   /* Map of keys that can be used to calculate GROUP BY without sorting */
1055   key_map keys_in_use_for_group_by;
1056   /* Map of keys that can be used to calculate ORDER BY without sorting */
1057   key_map keys_in_use_for_order_by;
1058   KEY  *key_info;			/* data of keys defined for the table */
1059 
1060   Field *next_number_field;		/* Set if next_number is activated */
1061   Field *found_next_number_field;	/* Set on open */
1062   Field *fts_doc_id_field;              /* Set if FTS_DOC_ID field is present */
1063 
1064   /* Table's triggers, 0 if there are no of them */
1065   Table_triggers_list *triggers;
1066   TABLE_LIST *pos_in_table_list;/* Element referring to this table */
1067   /* Position in thd->locked_table_list under LOCK TABLES */
1068   TABLE_LIST *pos_in_locked_tables;
1069   ORDER		*group;
1070   const char	*alias;            	  /* alias or table name */
1071   uchar		*null_flags;
1072   my_bitmap_map	*bitmap_init_value;
1073   MY_BITMAP     def_read_set, def_write_set, tmp_set; /* containers */
1074   MY_BITMAP     *read_set, *write_set;          /* Active column sets */
1075   /*
1076    The ID of the query that opened and is using this table. Has different
1077    meanings depending on the table type.
1078 
1079    Temporary tables:
1080 
1081    table->query_id is set to thd->query_id for the duration of a statement
1082    and is reset to 0 once it is closed by the same statement. A non-zero
1083    table->query_id means that a statement is using the table even if it's
1084    not the current statement (table is in use by some outer statement).
1085 
1086    Non-temporary tables:
1087 
1088    Under pre-locked or LOCK TABLES mode: query_id is set to thd->query_id
1089    for the duration of a statement and is reset to 0 once it is closed by
1090    the same statement. A non-zero query_id is used to control which tables
1091    in the list of pre-opened and locked tables are actually being used.
1092   */
1093   query_id_t	query_id;
1094 
1095   /*
1096     For each key that has quick_keys.is_set(key) == TRUE: estimate of #records
1097     and max #key parts that range access would use.
1098   */
1099   ha_rows	quick_rows[MAX_KEY];
1100 
1101   /* Bitmaps of key parts that =const for the entire join. */
1102   key_part_map  const_key_parts[MAX_KEY];
1103 
1104   uint		quick_key_parts[MAX_KEY];
1105   uint		quick_n_ranges[MAX_KEY];
1106 
1107   /*
1108     Estimate of number of records that satisfy SARGable part of the table
1109     condition, or table->file->records if no SARGable condition could be
1110     constructed.
1111     This value is used by join optimizer as an estimate of number of records
1112     that will pass the table condition (condition that depends on fields of
1113     this table and constants)
1114   */
1115   ha_rows       quick_condition_rows;
1116   table_map	map;                    /* ID bit of table (1,2,4,8,16...) */
1117 
1118   uint          lock_position;          /* Position in MYSQL_LOCK.table */
1119   uint          lock_data_start;        /* Start pos. in MYSQL_LOCK.locks */
1120   uint          lock_count;             /* Number of locks */
1121   uint		tablenr,used_fields;
1122   uint          temp_pool_slot;		/* Used by intern temp tables */
1123   uint		db_stat;		/* mode of file as in handler.h */
1124   int		current_lock;           /* Type of lock on table */
1125 
1126   /*
1127     0 or JOIN_TYPE_{LEFT|RIGHT}. Currently this is only compared to 0.
1128     If maybe_null !=0, this table is inner w.r.t. some outer join operation,
1129     and null_row may be true.
1130   */
1131   uint maybe_null;
1132   /*
1133     If true, the current table row is considered to have all columns set to
1134     NULL, including columns declared as "not null" (see maybe_null).
1135   */
1136   my_bool null_row;
1137 
1138   uint8   status;                       /* What's in record[0] */
1139   my_bool copy_blobs;                   /* copy_blobs when storing */
1140 
1141   /*
1142     TODO: Each of the following flags take up 8 bits. They can just as easily
1143     be put into one single unsigned long and instead of taking up 18
1144     bytes, it would take up 4.
1145   */
1146   my_bool force_index;
1147 
1148   /**
1149     Flag set when the statement contains FORCE INDEX FOR ORDER BY
1150     See TABLE_LIST::process_index_hints().
1151   */
1152   my_bool force_index_order;
1153 
1154   /**
1155     Flag set when the statement contains FORCE INDEX FOR GROUP BY
1156     See TABLE_LIST::process_index_hints().
1157   */
1158   my_bool force_index_group;
1159   my_bool distinct,const_table,no_rows;
1160 
1161   /**
1162      If set, the optimizer has found that row retrieval should access index
1163      tree only.
1164    */
1165   my_bool key_read;
1166   my_bool no_keyread;
1167   my_bool locked_by_logger;
1168   /**
1169     If set, indicate that the table is not replicated by the server.
1170   */
1171   my_bool no_replicate;
1172   my_bool locked_by_name;
1173   my_bool fulltext_searched;
1174   my_bool no_cache;
1175   /* To signal that the table is associated with a HANDLER statement */
1176   my_bool open_by_handler;
1177   /*
1178     To indicate that a non-null value of the auto_increment field
1179     was provided by the user or retrieved from the current record.
1180     Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode.
1181   */
1182   my_bool auto_increment_field_not_null;
1183   my_bool insert_or_update;             /* Can be used by the handler */
1184   my_bool alias_name_used;		/* true if table_name is alias */
1185   my_bool get_fields_in_item_tree;      /* Signal to fix_field */
1186   /**
1187     This table must be reopened and is not to be reused.
1188     NOTE: The TABLE will not be reopened during LOCK TABLES in
1189     close_thread_tables!!!
1190   */
1191   my_bool m_needs_reopen;
1192 private:
1193   bool created; /* For tmp tables. TRUE <=> tmp table has been instantiated.*/
1194 public:
1195   uint max_keys; /* Size of allocated key_info array. */
1196 
1197   REGINFO reginfo;			/* field connections */
1198   /**
1199      @todo This member should not be declared in-line. That makes it
1200      impossible for any function that does memory allocation to take a const
1201      reference to a TABLE object.
1202    */
1203   MEM_ROOT mem_root;
1204   /**
1205      Initialized in Item_func_group_concat::setup for appropriate
1206      temporary table if GROUP_CONCAT is used with ORDER BY | DISTINCT
1207      and BLOB field count > 0.
1208    */
1209   Blob_mem_storage *blob_storage;
1210   GRANT_INFO grant;
1211   Filesort_info sort;
1212 #ifdef WITH_PARTITION_STORAGE_ENGINE
1213   partition_info *part_info;            /* Partition related information */
1214   /* If true, all partitions have been pruned away */
1215   bool all_partitions_pruned_away;
1216 #endif
1217   MDL_ticket *mdl_ticket;
1218 
1219   void init(THD *thd, TABLE_LIST *tl);
1220   bool fill_item_list(List<Item> *item_list) const;
1221   void reset_item_list(List<Item> *item_list) const;
1222   void clear_column_bitmaps(void);
1223   void prepare_for_position(void);
1224   void mark_columns_used_by_index_no_reset(uint index, MY_BITMAP *map);
1225   void mark_columns_used_by_index(uint index);
1226   void mark_auto_increment_column(void);
1227   void mark_columns_needed_for_update(bool mark_binlog_columns);
1228   void mark_columns_needed_for_delete(void);
1229   void mark_columns_needed_for_insert(void);
1230   void mark_columns_per_binlog_row_image(void);
column_bitmaps_setTABLE1231   inline void column_bitmaps_set(MY_BITMAP *read_set_arg,
1232                                  MY_BITMAP *write_set_arg)
1233   {
1234     read_set= read_set_arg;
1235     write_set= write_set_arg;
1236     if (file && created)
1237       file->column_bitmaps_signal();
1238   }
column_bitmaps_set_no_signalTABLE1239   inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg,
1240                                            MY_BITMAP *write_set_arg)
1241   {
1242     read_set= read_set_arg;
1243     write_set= write_set_arg;
1244   }
use_all_columnsTABLE1245   inline void use_all_columns()
1246   {
1247     column_bitmaps_set(&s->all_set, &s->all_set);
1248   }
default_column_bitmapsTABLE1249   inline void default_column_bitmaps()
1250   {
1251     read_set= &def_read_set;
1252     write_set= &def_write_set;
1253   }
1254   /** Should this instance of the table be reopened? */
needs_reopenTABLE1255   inline bool needs_reopen()
1256   { return !db_stat || m_needs_reopen; }
1257   bool alloc_keys(uint key_count);
1258   bool add_tmp_key(Field_map *key_parts, char *key_name);
1259   void use_index(int key_to_save);
1260 
set_keyreadTABLE1261   void set_keyread(bool flag)
1262   {
1263     DBUG_ASSERT(file);
1264     if (flag && !key_read)
1265     {
1266       key_read= 1;
1267       if (is_created())
1268         file->extra(HA_EXTRA_KEYREAD);
1269     }
1270     else if (!flag && key_read)
1271     {
1272       key_read= 0;
1273       if (is_created())
1274         file->extra(HA_EXTRA_NO_KEYREAD);
1275     }
1276   }
1277 
1278   bool update_const_key_parts(Item *conds);
1279 
1280   bool check_read_removal(uint index);
1281 
1282   /// Return true if table is instantiated, and false otherwise.
is_createdTABLE1283   bool is_created() const { return created; }
1284 
1285   /**
1286     Set the table as "created", and enable flags in storage engine
1287     that could not be enabled without an instantiated table.
1288   */
set_createdTABLE1289   void set_created()
1290   {
1291     if (created)
1292       return;
1293     if (key_read)
1294       file->extra(HA_EXTRA_KEYREAD);
1295     created= true;
1296   }
1297   /**
1298     Set the contents of table to be "deleted", ie "not created", after having
1299     deleted the contents.
1300   */
set_deletedTABLE1301   void set_deleted()
1302   {
1303     created= false;
1304   }
1305 };
1306 
1307 
1308 enum enum_schema_table_state
1309 {
1310   NOT_PROCESSED= 0,
1311   PROCESSED_BY_CREATE_SORT_INDEX,
1312   PROCESSED_BY_JOIN_EXEC
1313 };
1314 
1315 typedef struct st_foreign_key_info
1316 {
1317   LEX_STRING *foreign_id;
1318   LEX_STRING *foreign_db;
1319   LEX_STRING *foreign_table;
1320   LEX_STRING *referenced_db;
1321   LEX_STRING *referenced_table;
1322   LEX_STRING *update_method;
1323   LEX_STRING *delete_method;
1324   LEX_STRING *referenced_key_name;
1325   List<LEX_STRING> foreign_fields;
1326   List<LEX_STRING> referenced_fields;
1327 } FOREIGN_KEY_INFO;
1328 
1329 #define MY_I_S_MAYBE_NULL 1
1330 #define MY_I_S_UNSIGNED   2
1331 
1332 
1333 #define SKIP_OPEN_TABLE 0                // do not open table
1334 #define OPEN_FRM_ONLY   1                // open FRM file only
1335 #define OPEN_FULL_TABLE 2                // open FRM,MYD, MYI files
1336 
1337 typedef struct st_field_info
1338 {
1339   /**
1340       This is used as column name.
1341   */
1342   const char* field_name;
1343   /**
1344      For string-type columns, this is the maximum number of
1345      characters. Otherwise, it is the 'display-length' for the column.
1346   */
1347   uint field_length;
1348   /**
1349      This denotes data type for the column. For the most part, there seems to
1350      be one entry in the enum for each SQL data type, although there seem to
1351      be a number of additional entries in the enum.
1352   */
1353   enum enum_field_types field_type;
1354   int value;
1355   /**
1356      This is used to set column attributes. By default, columns are @c NOT
1357      @c NULL and @c SIGNED, and you can deviate from the default
1358      by setting the appopriate flags. You can use either one of the flags
1359      @c MY_I_S_MAYBE_NULL and @cMY_I_S_UNSIGNED or
1360      combine them using the bitwise or operator @c |. Both flags are
1361      defined in table.h.
1362    */
1363   uint field_flags;        // Field atributes(maybe_null, signed, unsigned etc.)
1364   const char* old_name;
1365   /**
1366      This should be one of @c SKIP_OPEN_TABLE,
1367      @c OPEN_FRM_ONLY or @c OPEN_FULL_TABLE.
1368   */
1369   uint open_method;
1370 } ST_FIELD_INFO;
1371 
1372 
1373 struct TABLE_LIST;
1374 
1375 typedef struct st_schema_table
1376 {
1377   const char* table_name;
1378   ST_FIELD_INFO *fields_info;
1379   /* Create information_schema table */
1380   TABLE *(*create_table)  (THD *thd, TABLE_LIST *table_list);
1381   /* Fill table with data */
1382   int (*fill_table) (THD *thd, TABLE_LIST *tables, Item *cond);
1383   /* Handle fileds for old SHOW */
1384   int (*old_format) (THD *thd, struct st_schema_table *schema_table);
1385   int (*process_table) (THD *thd, TABLE_LIST *tables, TABLE *table,
1386                         bool res, LEX_STRING *db_name, LEX_STRING *table_name);
1387   int idx_field1, idx_field2;
1388   bool hidden;
1389   uint i_s_requested_object;  /* the object we need to open(TABLE | VIEW) */
1390 } ST_SCHEMA_TABLE;
1391 
1392 
1393 #define JOIN_TYPE_LEFT	1
1394 #define JOIN_TYPE_RIGHT	2
1395 
1396 enum enum_derived_type {
1397   VIEW_ALGORITHM_UNDEFINED = 0,
1398   VIEW_ALGORITHM_TMPTABLE,
1399   VIEW_ALGORITHM_MERGE,
1400   DERIVED_ALGORITHM_TMPTABLE
1401 };
1402 
1403 #define VIEW_SUID_INVOKER               0
1404 #define VIEW_SUID_DEFINER               1
1405 #define VIEW_SUID_DEFAULT               2
1406 
1407 /* view WITH CHECK OPTION parameter options */
1408 #define VIEW_CHECK_NONE       0
1409 #define VIEW_CHECK_LOCAL      1
1410 #define VIEW_CHECK_CASCADED   2
1411 
1412 /* result of view WITH CHECK OPTION parameter check */
1413 #define VIEW_CHECK_OK         0
1414 #define VIEW_CHECK_ERROR      1
1415 #define VIEW_CHECK_SKIP       2
1416 
1417 /** The threshold size a blob field buffer before it is freed */
1418 #define MAX_TDC_BLOB_SIZE 65536
1419 
1420 class select_union;
1421 class TMP_TABLE_PARAM;
1422 
1423 struct Field_translator
1424 {
1425   Item *item;
1426   const char *name;
1427 };
1428 
1429 
1430 /*
1431   Column reference of a NATURAL/USING join. Since column references in
1432   joins can be both from views and stored tables, may point to either a
1433   Field (for tables), or a Field_translator (for views).
1434 */
1435 
1436 class Natural_join_column: public Sql_alloc
1437 {
1438 public:
1439   Field_translator *view_field;  /* Column reference of merge view. */
1440   Item_field       *table_field; /* Column reference of table or temp view. */
1441   TABLE_LIST *table_ref; /* Original base table/view reference. */
1442   /*
1443     True if a common join column of two NATURAL/USING join operands. Notice
1444     that when we have a hierarchy of nested NATURAL/USING joins, a column can
1445     be common at some level of nesting but it may not be common at higher
1446     levels of nesting. Thus this flag may change depending on at which level
1447     we are looking at some column.
1448   */
1449   bool is_common;
1450 public:
1451   Natural_join_column(Field_translator *field_param, TABLE_LIST *tab);
1452   Natural_join_column(Item_field *field_param, TABLE_LIST *tab);
1453   const char *name();
1454   Item *create_item(THD *thd);
1455   Field *field();
1456   const char *table_name();
1457   const char *db_name();
1458   GRANT_INFO *grant();
1459 };
1460 
1461 
1462 /**
1463    Type of table which can be open for an element of table list.
1464 */
1465 
1466 enum enum_open_type
1467 {
1468   OT_TEMPORARY_OR_BASE= 0, OT_TEMPORARY_ONLY, OT_BASE_ONLY
1469 };
1470 
1471 /**
1472   This structure is used to keep info about possible key for the result table
1473   of a derived table/view.
1474   The 'referenced_by' is the table map of tables to which this possible
1475     key corresponds.
1476   The 'used_field' is a map of fields of which this key consists of.
1477   See also the comment for the TABLE_LIST::update_derived_keys function.
1478 */
1479 
1480 class Derived_key: public Sql_alloc {
1481 public:
1482   table_map referenced_by;
1483   Field_map used_fields;
1484 };
1485 
1486 class Index_hint;
1487 class Item_exists_subselect;
1488 
1489 
1490 /*
1491   Table reference in the FROM clause.
1492 
1493   These table references can be of several types that correspond to
1494   different SQL elements. Below we list all types of TABLE_LISTs with
1495   the necessary conditions to determine when a TABLE_LIST instance
1496   belongs to a certain type.
1497 
1498   1) table (TABLE_LIST::view == NULL)
1499      - base table
1500        (TABLE_LIST::derived == NULL)
1501      - subquery - TABLE_LIST::table is a temp table
1502        (TABLE_LIST::derived != NULL)
1503      - information schema table
1504        (TABLE_LIST::schema_table != NULL)
1505        NOTICE: for schema tables TABLE_LIST::field_translation may be != NULL
1506   2) view (TABLE_LIST::view != NULL)
1507      - merge    (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_MERGE)
1508            also (TABLE_LIST::field_translation != NULL)
1509      - tmptable (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_TMPTABLE)
1510            also (TABLE_LIST::field_translation == NULL)
1511   3) nested table reference (TABLE_LIST::nested_join != NULL)
1512      - table sequence - e.g. (t1, t2, t3)
1513        TODO: how to distinguish from a JOIN?
1514      - general JOIN
1515        TODO: how to distinguish from a table sequence?
1516      - NATURAL JOIN
1517        (TABLE_LIST::natural_join != NULL)
1518        - JOIN ... USING
1519          (TABLE_LIST::join_using_fields != NULL)
1520      - semi-join
1521        ;
1522 */
1523 
1524 struct Name_resolution_context;
1525 struct LEX;
1526 struct TABLE_LIST
1527 {
TABLE_LISTTABLE_LIST1528   TABLE_LIST() {}                          /* Remove gcc warning */
1529 
1530   /**
1531     Prepare TABLE_LIST that consists of one table instance to use in
1532     simple_open_and_lock_tables
1533   */
init_one_tableTABLE_LIST1534   inline void init_one_table(const char *db_name_arg,
1535                              size_t db_length_arg,
1536                              const char *table_name_arg,
1537                              size_t table_name_length_arg,
1538                              const char *alias_arg,
1539                              enum thr_lock_type lock_type_arg)
1540   {
1541     memset(this, 0, sizeof(*this));
1542     db= (char*) db_name_arg;
1543     db_length= db_length_arg;
1544     table_name= (char*) table_name_arg;
1545     table_name_length= table_name_length_arg;
1546     alias= (char*) alias_arg;
1547     lock_type= lock_type_arg;
1548     mdl_request.init(MDL_key::TABLE, db, table_name,
1549                      (lock_type >= TL_WRITE_ALLOW_WRITE) ?
1550                      MDL_SHARED_WRITE : MDL_SHARED_READ,
1551                      MDL_TRANSACTION);
1552     callback_func= 0;
1553   }
1554 
1555   /// Create a TABLE_LIST object representing a nested join
1556   static TABLE_LIST *new_nested_join(MEM_ROOT *allocator,
1557                                      const char *alias,
1558                                      TABLE_LIST *embedding,
1559                                      List<TABLE_LIST> *belongs_to,
1560                                      class st_select_lex *select);
1561 
1562   /*
1563     List of tables local to a subquery or the top-level SELECT (used by
1564     SQL_I_List). Considers views as leaves (unlike 'next_leaf' below).
1565     Created at parse time in st_select_lex::add_table_to_list() ->
1566     table_list.link_in_list().
1567   */
1568   TABLE_LIST *next_local;
1569   /* link in a global list of all queries tables */
1570   TABLE_LIST *next_global, **prev_global;
1571   char		*db, *alias, *table_name, *schema_table_name;
1572   char          *option;                /* Used by cache index  */
1573   /**
1574      Context which should be used to resolve identifiers contained in the ON
1575      condition of the embedding join nest.
1576      @todo When name resolution contexts are created after parsing, we should
1577      be able to store this in the embedding join nest instead.
1578   */
1579   Name_resolution_context *context_of_embedding;
1580 
1581 private:
1582   Item		*m_join_cond;           /* Used with outer join */
1583 public:
join_cond_refTABLE_LIST1584   Item         **join_cond_ref() { return &m_join_cond; }
join_condTABLE_LIST1585   Item          *join_cond() const { return m_join_cond; }
set_join_condTABLE_LIST1586   Item          *set_join_cond(Item *val)
1587                  { return m_join_cond= val; }
1588   /*
1589     The structure of the join condition presented in the member above
1590     can be changed during certain optimizations. This member
1591     contains a snapshot of AND-OR structure of the join condition
1592     made after permanent transformations of the parse tree, and is
1593     used to restore the join condition before every reexecution of a prepared
1594     statement or stored procedure.
1595   */
1596   Item          *prep_join_cond;
1597 
1598   Item          *sj_on_expr;            /* Synthesized semijoin condition */
1599   /*
1600     (Valid only for semi-join nests) Bitmap of tables that are within the
1601     semi-join (this is different from bitmap of all nest's children because
1602     tables that were pulled out of the semi-join nest remain listed as
1603     nest's children).
1604   */
1605   table_map     sj_inner_tables;
1606 
1607   COND_EQUAL    *cond_equal;            /* Used with outer join */
1608   /*
1609     During parsing - left operand of NATURAL/USING join where 'this' is
1610     the right operand. After parsing (this->natural_join == this) iff
1611     'this' represents a NATURAL or USING join operation. Thus after
1612     parsing 'this' is a NATURAL/USING join iff (natural_join != NULL).
1613   */
1614   TABLE_LIST *natural_join;
1615   /*
1616     True if 'this' represents a nested join that is a NATURAL JOIN.
1617     For one of the operands of 'this', the member 'natural_join' points
1618     to the other operand of 'this'.
1619   */
1620   bool is_natural_join;
1621   /* Field names in a USING clause for JOIN ... USING. */
1622   List<String> *join_using_fields;
1623   /*
1624     Explicitly store the result columns of either a NATURAL/USING join or
1625     an operand of such a join.
1626   */
1627   List<Natural_join_column> *join_columns;
1628   /* TRUE if join_columns contains all columns of this table reference. */
1629   bool is_join_columns_complete;
1630 
1631   /*
1632     List of nodes in a nested join tree, that should be considered as
1633     leaves with respect to name resolution. The leaves are: views,
1634     top-most nodes representing NATURAL/USING joins, subqueries, and
1635     base tables. All of these TABLE_LIST instances contain a
1636     materialized list of columns. The list is local to a subquery.
1637   */
1638   TABLE_LIST *next_name_resolution_table;
1639   /* Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */
1640   List<Index_hint> *index_hints;
1641   TABLE        *table;                          /* opened table */
1642   Table_id table_id; /* table id (from binlog) for opened table */
1643   /*
1644     select_result for derived table to pass it from table creation to table
1645     filling procedure
1646   */
1647   select_union  *derived_result;
1648   /*
1649     Reference from aux_tables to local list entry of main select of
1650     multi-delete statement:
1651     delete t1 from t2,t1 where t1.a<'B' and t2.b=t1.b;
1652     here it will be reference of first occurrence of t1 to second (as you
1653     can see this lists can't be merged)
1654   */
1655   TABLE_LIST	*correspondent_table;
1656   /**
1657      @brief Normally, this field is non-null for anonymous derived tables only.
1658 
1659      @details This field is set to non-null for
1660 
1661      - Anonymous derived tables, In this case it points to the SELECT_LEX_UNIT
1662      representing the derived table. E.g. for a query
1663 
1664      @verbatim SELECT * FROM (SELECT a FROM t1) b @endverbatim
1665 
1666      For the @c TABLE_LIST representing the derived table @c b, @c derived
1667      points to the SELECT_LEX_UNIT representing the result of the query within
1668      parenteses.
1669 
1670      - Views. This is set for views with @verbatim ALGORITHM = TEMPTABLE
1671      @endverbatim by mysql_make_view().
1672 
1673      @note Inside views, a subquery in the @c FROM clause is not allowed.
1674      @note Do not use this field to separate views/base tables/anonymous
1675      derived tables. Use TABLE_LIST::is_anonymous_derived_table().
1676   */
1677   st_select_lex_unit *derived;		/* SELECT_LEX_UNIT of derived table */
1678   /*
1679     TRUE <=> all possible keys for a derived table were collected and
1680     could be re-used while statement re-execution.
1681   */
1682   bool derived_keys_ready;
1683   ST_SCHEMA_TABLE *schema_table;        /* Information_schema table */
1684   st_select_lex	*schema_select_lex;
1685   /*
1686     True when the view field translation table is used to convert
1687     schema table fields for backwards compatibility with SHOW command.
1688   */
1689   bool schema_table_reformed;
1690   TMP_TABLE_PARAM *schema_table_param;
1691   /* link to select_lex where this table was used */
1692   st_select_lex	*select_lex;
1693   LEX *view;                    /* link on VIEW lex for merging */
1694   Field_translator *field_translation;	/* array of VIEW fields */
1695   /* pointer to element after last one in translation table above */
1696   Field_translator *field_translation_end;
1697   /*
1698     List (based on next_local) of underlying tables of this view. I.e. it
1699     does not include the tables of subqueries used in the view. Is set only
1700     for merged views.
1701   */
1702   TABLE_LIST	*merge_underlying_list;
1703   /*
1704     - 0 for base tables
1705     - in case of the view it is the list of all (not only underlying
1706     tables but also used in subquery ones) tables of the view.
1707   */
1708   List<TABLE_LIST> *view_tables;
1709   /* most upper view this table belongs to */
1710   TABLE_LIST	*belong_to_view;
1711   /*
1712     The view directly referencing this table
1713     (non-zero only for merged underlying tables of a view).
1714   */
1715   TABLE_LIST	*referencing_view;
1716   /* Ptr to parent MERGE table list item. See top comment in ha_myisammrg.cc */
1717   TABLE_LIST    *parent_l;
1718   /*
1719     Security  context (non-zero only for tables which belong
1720     to view with SQL SECURITY DEFINER)
1721   */
1722   Security_context *security_ctx;
1723   /*
1724     This view security context (non-zero only for views with
1725     SQL SECURITY DEFINER)
1726   */
1727   Security_context *view_sctx;
1728   /*
1729     List of all base tables local to a subquery including all view
1730     tables. Unlike 'next_local', this in this list views are *not*
1731     leaves. Created in setup_tables() -> make_leaves_list().
1732   */
1733   bool allowed_show;
1734   TABLE_LIST	*next_leaf;
1735   Item          *where;                 /* VIEW WHERE clause condition */
1736   Item          *check_option;          /* WITH CHECK OPTION condition */
1737   LEX_STRING	select_stmt;		/* text of (CREATE/SELECT) statement */
1738   LEX_STRING	md5;			/* md5 of query text */
1739   LEX_STRING	source;			/* source of CREATE VIEW */
1740   LEX_STRING	view_db;		/* saved view database */
1741   LEX_STRING	view_name;		/* saved view name */
1742   LEX_STRING	timestamp;		/* GMT time stamp of last operation */
1743   st_lex_user   definer;                /* definer of view */
1744   ulonglong	file_version;		/* version of file's field set */
1745   ulonglong     updatable_view;         /* VIEW can be updated */
1746   /**
1747       @brief The declared algorithm, if this is a view.
1748       @details One of
1749       - VIEW_ALGORITHM_UNDEFINED
1750       - VIEW_ALGORITHM_TMPTABLE
1751       - VIEW_ALGORITHM_MERGE
1752       @to do Replace with an enum
1753   */
1754   ulonglong	algorithm;
1755   ulonglong     view_suid;              /* view is suid (TRUE dy default) */
1756   ulonglong     with_check;             /* WITH CHECK OPTION */
1757   /*
1758     effective value of WITH CHECK OPTION (differ for temporary table
1759     algorithm)
1760   */
1761   uint8         effective_with_check;
1762   /**
1763       @brief The view algorithm that is actually used, if this is a view.
1764       @details One of
1765       - VIEW_ALGORITHM_UNDEFINED
1766       - VIEW_ALGORITHM_TMPTABLE
1767       - VIEW_ALGORITHM_MERGE
1768       @to do Replace with an enum
1769   */
1770   enum_derived_type effective_algorithm;
1771   GRANT_INFO	grant;
1772   /* data need by some engines in query cache*/
1773   ulonglong     engine_data;
1774   /* call back function for asking handler about caching in query cache */
1775   qc_engine_callback callback_func;
1776   thr_lock_type lock_type;
1777   uint		outer_join;		/* Which join type */
1778   uint		shared;			/* Used in multi-upd */
1779   size_t        db_length;
1780   size_t        table_name_length;
1781   bool          updatable;		/* VIEW/TABLE can be updated now */
1782   bool		straight;		/* optimize with prev table */
1783   bool          updating;               /* for replicate-do/ignore table */
1784   bool		force_index;		/* prefer index over table scan */
1785   bool          ignore_leaves;          /* preload only non-leaf nodes */
1786   table_map     dep_tables;             /* tables the table depends on      */
1787   table_map     on_expr_dep_tables;     /* tables on expression depends on  */
1788   struct st_nested_join *nested_join;   /* if the element is a nested join  */
1789   TABLE_LIST *embedding;             /* nested join containing the table */
1790   List<TABLE_LIST> *join_list;/* join list the table belongs to   */
1791   bool		cacheable_table;	/* stop PS caching */
1792   /* used in multi-upd/views privilege check */
1793   bool		table_in_first_from_clause;
1794   /**
1795      Specifies which kind of table should be open for this element
1796      of table list.
1797   */
1798   enum enum_open_type open_type;
1799   /* TRUE if this merged view contain auto_increment field */
1800   bool          contain_auto_increment;
1801   bool          multitable_view;        /* TRUE iff this is multitable view */
1802   bool          compact_view_format;    /* Use compact format for SHOW CREATE VIEW */
1803   /* view where processed */
1804   bool          where_processed;
1805   /* TRUE <=> VIEW CHECK OPTION expression has been processed */
1806   bool          check_option_processed;
1807   /* FRMTYPE_ERROR if any type is acceptable */
1808   enum frm_type_enum required_type;
1809   char		timestamp_buffer[20];	/* buffer for timestamp (19+1) */
1810   /*
1811     This TABLE_LIST object is just placeholder for prelocking, it will be
1812     used for implicit LOCK TABLES only and won't be used in real statement.
1813   */
1814   bool          prelocking_placeholder;
1815   /**
1816      Indicates that if TABLE_LIST object corresponds to the table/view
1817      which requires special handling.
1818   */
1819   enum
1820   {
1821     /* Normal open. */
1822     OPEN_NORMAL= 0,
1823     /* Associate a table share only if the the table exists. */
1824     OPEN_IF_EXISTS,
1825     /*
1826       Associate a table share only if the the table exists.
1827       Also upgrade metadata lock to exclusive if table doesn't exist.
1828     */
1829     OPEN_FOR_CREATE,
1830     /* Don't associate a table share. */
1831     OPEN_STUB
1832   } open_strategy;
1833   bool          internal_tmp_table;
1834   /** TRUE if an alias for this table was specified in the SQL. */
1835   bool          is_alias;
1836   /** TRUE if the table is referred to in the statement using a fully
1837       qualified name (<db_name>.<table_name>).
1838   */
1839   bool          is_fqtn;
1840 
1841 
1842   /* View creation context. */
1843 
1844   View_creation_ctx *view_creation_ctx;
1845 
1846   /*
1847     Attributes to save/load view creation context in/from frm-file.
1848 
1849     Ther are required only to be able to use existing parser to load
1850     view-definition file. As soon as the parser parsed the file, view
1851     creation context is initialized and the attributes become redundant.
1852 
1853     These attributes MUST NOT be used for any purposes but the parsing.
1854   */
1855 
1856   LEX_STRING view_client_cs_name;
1857   LEX_STRING view_connection_cl_name;
1858 
1859   /*
1860     View definition (SELECT-statement) in the UTF-form.
1861   */
1862 
1863   LEX_STRING view_body_utf8;
1864 
1865    /* End of view definition context. */
1866   /* List of possible keys. Valid only for materialized derived tables/views. */
1867   List<Derived_key> derived_key_list;
1868 
1869   /**
1870     Indicates what triggers we need to pre-load for this TABLE_LIST
1871     when opening an associated TABLE. This is filled after
1872     the parsed tree is created.
1873   */
1874   uint8 trg_event_map;
1875   /* TRUE <=> this table is a const one and was optimized away. */
1876   bool optimized_away;
1877   uint i_s_requested_object;
1878   bool has_db_lookup_value;
1879   bool has_table_lookup_value;
1880   uint table_open_method;
1881   enum enum_schema_table_state schema_table_state;
1882 
1883   MDL_request mdl_request;
1884 
1885 #ifdef WITH_PARTITION_STORAGE_ENGINE
1886   /* List to carry partition names from PARTITION (...) clause in statement */
1887   List<String> *partition_names;
1888 #endif /* WITH_PARTITION_STORAGE_ENGINE */
1889 
1890   void calc_md5(char *buffer);
1891   void set_underlying_merge();
1892   int view_check_option(THD *thd, bool ignore_failure) const;
1893   bool setup_underlying(THD *thd);
1894   void cleanup_items();
placeholderTABLE_LIST1895   bool placeholder()
1896   {
1897     return derived || view || schema_table || !table;
1898   }
1899   void print(THD *thd, String *str, enum_query_type query_type);
1900   bool check_single_table(TABLE_LIST **table, table_map map,
1901                           TABLE_LIST *view);
1902   bool set_insert_values(MEM_ROOT *mem_root);
1903   void hide_view_error(THD *thd);
1904   TABLE_LIST *find_underlying_table(TABLE *table);
1905   TABLE_LIST *first_leaf_for_name_resolution();
1906   TABLE_LIST *last_leaf_for_name_resolution();
1907   bool is_leaf_for_name_resolution();
top_tableTABLE_LIST1908   inline const TABLE_LIST *top_table() const
1909     { return belong_to_view ? belong_to_view : this; }
1910 
top_tableTABLE_LIST1911   inline TABLE_LIST *top_table()
1912   {
1913     return
1914       const_cast<TABLE_LIST*>(const_cast<const TABLE_LIST*>(this)->top_table());
1915   }
1916 
prepare_check_optionTABLE_LIST1917   inline bool prepare_check_option(THD *thd)
1918   {
1919     bool res= FALSE;
1920     if (effective_with_check)
1921       res= prep_check_option(thd, effective_with_check);
1922     return res;
1923   }
prepare_whereTABLE_LIST1924   inline bool prepare_where(THD *thd, Item **conds,
1925                             bool no_where_clause)
1926   {
1927     if (effective_algorithm == VIEW_ALGORITHM_MERGE)
1928       return prep_where(thd, conds, no_where_clause);
1929     return FALSE;
1930   }
1931   /**
1932     @returns
1933       TRUE  this is a materializable derived table/view.
1934       FALSE otherwise.
1935   */
uses_materializationTABLE_LIST1936   inline bool uses_materialization() const
1937   {
1938     return (effective_algorithm == VIEW_ALGORITHM_TMPTABLE ||
1939             effective_algorithm == DERIVED_ALGORITHM_TMPTABLE);
1940   }
is_view_or_derivedTABLE_LIST1941   inline bool is_view_or_derived() const
1942   {
1943     return (effective_algorithm != VIEW_ALGORITHM_UNDEFINED);
1944   }
1945   /**
1946     @returns true if materializable table contains one or zero rows.
1947 
1948     Returning true implies that the table is materialized during optimization,
1949     so it need not be optimized during execution.
1950   */
1951   bool materializable_is_const() const;
1952 
1953   void register_want_access(ulong want_access);
1954   bool prepare_security(THD *thd);
1955 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1956   Security_context *find_view_security_context(THD *thd);
1957   bool prepare_view_securety_context(THD *thd);
1958 #endif
1959   /*
1960     Cleanup for re-execution in a prepared statement or a stored
1961     procedure.
1962   */
1963   void reinit_before_use(THD *thd);
1964   Item_subselect *containing_subselect();
1965 
1966   /*
1967     Compiles the tagged hints list and fills up TABLE::keys_in_use_for_query,
1968     TABLE::keys_in_use_for_group_by, TABLE::keys_in_use_for_order_by,
1969     TABLE::force_index and TABLE::covering_keys.
1970   */
1971   bool process_index_hints(TABLE *table);
1972 
1973   /**
1974     Compare the version of metadata from the previous execution
1975     (if any) with values obtained from the current table
1976     definition cache element.
1977 
1978     @sa check_and_update_table_version()
1979   */
1980   inline
is_table_ref_id_equalTABLE_LIST1981   bool is_table_ref_id_equal(TABLE_SHARE *s) const
1982   {
1983     return (m_table_ref_type == s->get_table_ref_type() &&
1984             m_table_ref_version == s->get_table_ref_version());
1985   }
1986 
1987   /**
1988     Record the value of metadata version of the corresponding
1989     table definition cache element in this parse tree node.
1990 
1991     @sa check_and_update_table_version()
1992   */
1993   inline
set_table_ref_idTABLE_LIST1994   void set_table_ref_id(TABLE_SHARE *s)
1995   { set_table_ref_id(s->get_table_ref_type(), s->get_table_ref_version()); }
1996 
1997   inline
set_table_ref_idTABLE_LIST1998   void set_table_ref_id(enum_table_ref_type table_ref_type_arg,
1999                         ulonglong table_ref_version_arg)
2000   {
2001     m_table_ref_type= table_ref_type_arg;
2002     m_table_ref_version= table_ref_version_arg;
2003   }
2004 
2005   /**
2006      @brief True if this TABLE_LIST represents an anonymous derived table,
2007      i.e.  the result of a subquery.
2008   */
is_anonymous_derived_tableTABLE_LIST2009   bool is_anonymous_derived_table() const { return derived && !view; }
2010 
2011   /// returns query block id for derived table, and zero if not derived.
2012   uint query_block_id() const;
2013 
2014   /**
2015      @brief Returns the name of the database that the referenced table belongs
2016      to.
2017   */
get_db_nameTABLE_LIST2018   char *get_db_name() const { return view != NULL ? view_db.str : db; }
2019 
2020   /**
2021      @brief Returns the name of the table that this TABLE_LIST represents.
2022 
2023      @details The unqualified table name or view name for a table or view,
2024      respectively.
2025    */
get_table_nameTABLE_LIST2026   char *get_table_name() const { return view != NULL ? view_name.str : table_name; }
2027   int fetch_number_of_rows();
2028   bool update_derived_keys(Field*, Item**, uint);
2029   bool generate_keys();
2030   bool handle_derived(LEX *lex, bool (*processor)(THD*, LEX*, TABLE_LIST*));
2031   st_select_lex_unit *get_unit() const;
2032 
2033   /**
2034     @brief Returns the outer join nest that this TABLE_LIST belongs to, if any.
2035 
2036     @details There are two kinds of join nests, outer-join nests and semi-join
2037     nests.  This function returns non-NULL in the following cases:
2038       @li 1. If this table/nest is embedded in a nest and this nest IS NOT a
2039              semi-join nest.  (In other words, it is an outer-join nest.)
2040       @li 2. If this table/nest is embedded in a nest and this nest IS a
2041              semi-join nest, but this semi-join nest is embedded in another
2042              nest. (This other nest will be an outer-join nest, since all inner
2043              joined nested semi-join nests have been merged in
2044              @c simplify_joins() ).
2045     Note: This function assumes that @c simplify_joins() has been performed.
2046     Before that, join nests will be present for all types of join.
2047 
2048     @return outer join nest, or NULL if none.
2049    */
outer_join_nestTABLE_LIST2050   TABLE_LIST *outer_join_nest() const
2051   {
2052     if (!embedding)
2053       return NULL;
2054     if (embedding->sj_on_expr)
2055       return embedding->embedding;
2056     return embedding;
2057   }
2058 
2059 private:
2060   bool prep_check_option(THD *thd, uint8 check_opt_type);
2061   bool prep_where(THD *thd, Item **conds, bool no_where_clause);
2062   /** See comments for set_metadata_id() */
2063   enum enum_table_ref_type m_table_ref_type;
2064   /** See comments for TABLE_SHARE::get_table_ref_version() */
2065   ulonglong m_table_ref_version;
2066 };
2067 
2068 
2069 struct st_position;
2070 
2071 class Item;
2072 
2073 /*
2074   Iterator over the fields of a generic table reference.
2075 */
2076 
2077 class Field_iterator: public Sql_alloc
2078 {
2079 public:
Field_iterator()2080   Field_iterator() {}                         /* Remove gcc warning */
~Field_iterator()2081   virtual ~Field_iterator() {}
2082   virtual void set(TABLE_LIST *)= 0;
2083   virtual void next()= 0;
2084   virtual bool end_of_fields()= 0;              /* Return 1 at end of list */
2085   virtual const char *name()= 0;
2086   virtual Item *create_item(THD *)= 0;
2087   virtual Field *field()= 0;
2088 };
2089 
2090 
2091 /*
2092   Iterator over the fields of a base table, view with temporary
2093   table, or subquery.
2094 */
2095 
2096 class Field_iterator_table: public Field_iterator
2097 {
2098   Field **ptr;
2099 public:
Field_iterator_table()2100   Field_iterator_table() :ptr(0) {}
set(TABLE_LIST * table)2101   void set(TABLE_LIST *table) { ptr= table->table->field; }
set_table(TABLE * table)2102   void set_table(TABLE *table) { ptr= table->field; }
next()2103   void next() { ptr++; }
end_of_fields()2104   bool end_of_fields() { return *ptr == 0; }
2105   const char *name();
2106   Item *create_item(THD *thd);
field()2107   Field *field() { return *ptr; }
2108 };
2109 
2110 
2111 /* Iterator over the fields of a merge view. */
2112 
2113 class Field_iterator_view: public Field_iterator
2114 {
2115   Field_translator *ptr, *array_end;
2116   TABLE_LIST *view;
2117 public:
Field_iterator_view()2118   Field_iterator_view() :ptr(0), array_end(0) {}
2119   void set(TABLE_LIST *table);
next()2120   void next() { ptr++; }
end_of_fields()2121   bool end_of_fields() { return ptr == array_end; }
2122   const char *name();
2123   Item *create_item(THD *thd);
item_ptr()2124   Item **item_ptr() {return &ptr->item; }
field()2125   Field *field() { return 0; }
item()2126   inline Item *item() { return ptr->item; }
field_translator()2127   Field_translator *field_translator() { return ptr; }
2128 };
2129 
2130 
2131 /*
2132   Field_iterator interface to the list of materialized fields of a
2133   NATURAL/USING join.
2134 */
2135 
2136 class Field_iterator_natural_join: public Field_iterator
2137 {
2138   List_iterator_fast<Natural_join_column> column_ref_it;
2139   Natural_join_column *cur_column_ref;
2140 public:
Field_iterator_natural_join()2141   Field_iterator_natural_join() :cur_column_ref(NULL) {}
~Field_iterator_natural_join()2142   ~Field_iterator_natural_join() {}
2143   void set(TABLE_LIST *table);
2144   void next();
end_of_fields()2145   bool end_of_fields() { return !cur_column_ref; }
name()2146   const char *name() { return cur_column_ref->name(); }
create_item(THD * thd)2147   Item *create_item(THD *thd) { return cur_column_ref->create_item(thd); }
field()2148   Field *field() { return cur_column_ref->field(); }
column_ref()2149   Natural_join_column *column_ref() { return cur_column_ref; }
2150 };
2151 
2152 
2153 /*
2154   Generic iterator over the fields of an arbitrary table reference.
2155 
2156   DESCRIPTION
2157     This class unifies the various ways of iterating over the columns
2158     of a table reference depending on the type of SQL entity it
2159     represents. If such an entity represents a nested table reference,
2160     this iterator encapsulates the iteration over the columns of the
2161     members of the table reference.
2162 
2163   IMPLEMENTATION
2164     The implementation assumes that all underlying NATURAL/USING table
2165     references already contain their result columns and are linked into
2166     the list TABLE_LIST::next_name_resolution_table.
2167 */
2168 
2169 class Field_iterator_table_ref: public Field_iterator
2170 {
2171   TABLE_LIST *table_ref, *first_leaf, *last_leaf;
2172   Field_iterator_table        table_field_it;
2173   Field_iterator_view         view_field_it;
2174   Field_iterator_natural_join natural_join_it;
2175   Field_iterator *field_it;
2176   void set_field_iterator();
2177 public:
Field_iterator_table_ref()2178   Field_iterator_table_ref() :field_it(NULL) {}
2179   void set(TABLE_LIST *table);
2180   void next();
end_of_fields()2181   bool end_of_fields()
2182   { return (table_ref == last_leaf && field_it->end_of_fields()); }
name()2183   const char *name() { return field_it->name(); }
2184   const char *get_table_name();
2185   const char *get_db_name();
2186   GRANT_INFO *grant();
create_item(THD * thd)2187   Item *create_item(THD *thd) { return field_it->create_item(thd); }
field()2188   Field *field() { return field_it->field(); }
2189   Natural_join_column *get_or_create_column_ref(THD *thd, TABLE_LIST *parent_table_ref);
2190   Natural_join_column *get_natural_column_ref();
2191 };
2192 
2193 /**
2194   Semijoin_mat_optimize collects data used when calculating the cost of
2195   executing a semijoin operation using a materialization strategy.
2196   It is used during optimization phase only.
2197 */
2198 
2199 struct Semijoin_mat_optimize
2200 {
2201   /// Optimal join order calculated for inner tables of this semijoin op.
2202   struct st_position *positions;
2203   /// True if data types allow the MaterializeLookup semijoin strategy
2204   bool lookup_allowed;
2205   /// True if data types allow the MaterializeScan semijoin strategy
2206   bool scan_allowed;
2207   /// Expected #rows in the materialized table
2208   double expected_rowcount;
2209   /// Materialization cost - execute sub-join and write rows to temp.table
2210   Cost_estimate materialization_cost;
2211   /// Cost to make one lookup in the temptable
2212   Cost_estimate lookup_cost;
2213   /// Cost of scanning the materialized table
2214   Cost_estimate scan_cost;
2215   /// Array of pointers to fields in the materialized table.
2216   Item_field **mat_fields;
2217 };
2218 
2219 /**
2220   Struct st_nested_join is used to represent how tables are connected through
2221   outer join operations and semi-join operations to form a query block.
2222   Out of the parser, inner joins are also represented by st_nested_join
2223   structs, but these are later flattened out by simplify_joins().
2224   Some outer join nests are also flattened, when it can be determined that
2225   they can be processed as inner joins instead of outer joins.
2226 */
2227 typedef struct st_nested_join
2228 {
2229   List<TABLE_LIST>  join_list;       /* list of elements in the nested join */
2230   table_map         used_tables;     /* bitmap of tables in the nested join */
2231   table_map         not_null_tables; /* tables that rejects nulls           */
2232   /**
2233     Used for pointing out the first table in the plan being covered by this
2234     join nest. It is used exclusively within make_outerjoin_info().
2235    */
2236   struct st_join_table *first_nested;
2237   /**
2238     Number of tables and outer join nests administered by this nested join
2239     object for the sake of cost analysis. Includes direct member tables as
2240     well as tables included through semi-join nests, but notice that semi-join
2241     nests themselves are not counted.
2242   */
2243   uint              nj_total;
2244   /**
2245     Used to count tables in the nested join in 2 isolated places:
2246     1. In make_outerjoin_info().
2247     2. check_interleaving_with_nj/backout_nj_state (these are called
2248        by the join optimizer.
2249     Before each use the counters are zeroed by reset_nj_counters.
2250   */
2251   uint              nj_counter;
2252   /**
2253     Bit identifying this nested join. Only nested joins representing the
2254     outer join structure need this, other nests have bit set to zero.
2255   */
2256   nested_join_map   nj_map;
2257   /**
2258     Tables outside the semi-join that are used within the semi-join's
2259     ON condition (ie. the subquery WHERE clause and optional IN equalities).
2260   */
2261   table_map         sj_depends_on;
2262   /**
2263     Outer non-trivially correlated tables, a true subset of sj_depends_on
2264   */
2265   table_map         sj_corr_tables;
2266   /**
2267     Query block id if this struct is generated from a subquery transform.
2268   */
2269   uint query_block_id;
2270   /*
2271     Lists of trivially-correlated expressions from the outer and inner tables
2272     of the semi-join, respectively.
2273   */
2274   List<Item>        sj_outer_exprs, sj_inner_exprs;
2275   Semijoin_mat_optimize sjm;
2276 } NESTED_JOIN;
2277 
2278 
2279 typedef struct st_changed_table_list
2280 {
2281   struct	st_changed_table_list *next;
2282   char		*key;
2283   uint32        key_length;
2284 } CHANGED_TABLE_LIST;
2285 
2286 
2287 typedef struct st_open_table_list{
2288   struct st_open_table_list *next;
2289   char	*db,*table;
2290   uint32 in_use,locked;
2291 } OPEN_TABLE_LIST;
2292 
2293 
tmp_use_all_columns(TABLE * table,MY_BITMAP * bitmap)2294 static inline my_bitmap_map *tmp_use_all_columns(TABLE *table,
2295                                                  MY_BITMAP *bitmap)
2296 {
2297   my_bitmap_map *old= bitmap->bitmap;
2298   bitmap->bitmap= table->s->all_set.bitmap;// does not repoint last_word_ptr
2299   return old;
2300 }
2301 
2302 
tmp_restore_column_map(MY_BITMAP * bitmap,my_bitmap_map * old)2303 static inline void tmp_restore_column_map(MY_BITMAP *bitmap,
2304                                           my_bitmap_map *old)
2305 {
2306   bitmap->bitmap= old;
2307 }
2308 
2309 /* The following is only needed for debugging */
2310 
dbug_tmp_use_all_columns(TABLE * table,MY_BITMAP * bitmap)2311 static inline my_bitmap_map *dbug_tmp_use_all_columns(TABLE *table,
2312                                                       MY_BITMAP *bitmap)
2313 {
2314 #ifndef DBUG_OFF
2315   return tmp_use_all_columns(table, bitmap);
2316 #else
2317   return 0;
2318 #endif
2319 }
2320 
dbug_tmp_restore_column_map(MY_BITMAP * bitmap,my_bitmap_map * old)2321 static inline void dbug_tmp_restore_column_map(MY_BITMAP *bitmap,
2322                                                my_bitmap_map *old)
2323 {
2324 #ifndef DBUG_OFF
2325   tmp_restore_column_map(bitmap, old);
2326 #endif
2327 }
2328 
2329 
2330 /*
2331   Variant of the above : handle both read and write sets.
2332   Provide for the possiblity of the read set being the same as the write set
2333 */
dbug_tmp_use_all_columns(TABLE * table,my_bitmap_map ** save,MY_BITMAP * read_set,MY_BITMAP * write_set)2334 static inline void dbug_tmp_use_all_columns(TABLE *table,
2335                                             my_bitmap_map **save,
2336                                             MY_BITMAP *read_set,
2337                                             MY_BITMAP *write_set)
2338 {
2339 #ifndef DBUG_OFF
2340   save[0]= read_set->bitmap;
2341   save[1]= write_set->bitmap;
2342   (void) tmp_use_all_columns(table, read_set);
2343   (void) tmp_use_all_columns(table, write_set);
2344 #endif
2345 }
2346 
2347 
dbug_tmp_restore_column_maps(MY_BITMAP * read_set,MY_BITMAP * write_set,my_bitmap_map ** old)2348 static inline void dbug_tmp_restore_column_maps(MY_BITMAP *read_set,
2349                                                 MY_BITMAP *write_set,
2350                                                 my_bitmap_map **old)
2351 {
2352 #ifndef DBUG_OFF
2353   tmp_restore_column_map(read_set, old[0]);
2354   tmp_restore_column_map(write_set, old[1]);
2355 #endif
2356 }
2357 
2358 
2359 size_t max_row_length(TABLE *table, const uchar *data);
2360 
2361 
2362 void init_mdl_requests(TABLE_LIST *table_list);
2363 
2364 int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias,
2365                           uint db_stat, uint prgflag, uint ha_open_flags,
2366                           TABLE *outparam, bool is_create_table);
2367 TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, const char *key,
2368                                uint key_length);
2369 void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
2370                           uint key_length,
2371                           const char *table_name, const char *path);
2372 void free_table_share(TABLE_SHARE *share);
2373 int open_table_def(THD *thd, TABLE_SHARE *share, uint db_flags);
2374 void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg);
2375 void update_create_info_from_table(HA_CREATE_INFO *info, TABLE *form);
2376 enum_ident_name_check check_and_convert_db_name(LEX_STRING *db,
2377                                                 bool preserve_lettercase);
2378 bool check_column_name(const char *name);
2379 enum_ident_name_check check_table_name(const char *name, size_t length,
2380                                        bool check_for_path_chars);
2381 int rename_file_ext(const char * from,const char * to,const char * ext);
2382 char *get_field(MEM_ROOT *mem, Field *field);
2383 bool get_field(MEM_ROOT *mem, Field *field, class String *res);
2384 
2385 int closefrm(TABLE *table, bool free_share);
2386 int read_string(File file, uchar* *to, size_t length);
2387 void free_blobs(TABLE *table);
2388 void free_field_buffers_larger_than(TABLE *table, uint32 size);
2389 int set_zone(int nr,int min_zone,int max_zone);
2390 ulong get_form_pos(File file, uchar *head, TYPELIB *save_names);
2391 ulong make_new_entry(File file,uchar *fileinfo,TYPELIB *formnames,
2392 		     const char *newname);
2393 ulong next_io_size(ulong pos);
2394 void append_unescaped(String *res, const char *pos, uint length);
2395 File create_frm(THD *thd, const char *name, const char *db,
2396                 const char *table, uint reclength, uchar *fileinfo,
2397   		HA_CREATE_INFO *create_info, uint keys, KEY *key_info);
2398 char *fn_rext(char *name);
2399 
2400 /* performance schema */
2401 extern LEX_STRING PERFORMANCE_SCHEMA_DB_NAME;
2402 
2403 extern LEX_STRING GENERAL_LOG_NAME;
2404 extern LEX_STRING SLOW_LOG_NAME;
2405 
2406 /* information schema */
2407 extern LEX_STRING INFORMATION_SCHEMA_NAME;
2408 extern LEX_STRING MYSQL_SCHEMA_NAME;
2409 
2410 /* replication's tables */
2411 extern LEX_STRING RLI_INFO_NAME;
2412 extern LEX_STRING MI_INFO_NAME;
2413 extern LEX_STRING WORKER_INFO_NAME;
2414 
is_infoschema_db(const char * name,size_t len)2415 inline bool is_infoschema_db(const char *name, size_t len)
2416 {
2417   return (INFORMATION_SCHEMA_NAME.length == len &&
2418           !my_strcasecmp(system_charset_info,
2419                          INFORMATION_SCHEMA_NAME.str, name));
2420 }
2421 
is_infoschema_db(const char * name)2422 inline bool is_infoschema_db(const char *name)
2423 {
2424   return !my_strcasecmp(system_charset_info,
2425                         INFORMATION_SCHEMA_NAME.str, name);
2426 }
2427 
2428 TYPELIB *typelib(MEM_ROOT *mem_root, List<String> &strings);
2429 
2430 /**
2431   return true if the table was created explicitly.
2432 */
is_user_table(TABLE * table)2433 inline bool is_user_table(TABLE * table)
2434 {
2435   const char *name= table->s->table_name.str;
2436   return strncmp(name, tmp_file_prefix, tmp_file_prefix_length);
2437 }
2438 
mark_as_null_row(TABLE * table)2439 inline void mark_as_null_row(TABLE *table)
2440 {
2441   table->null_row=1;
2442   table->status|=STATUS_NULL_ROW;
2443   memset(table->null_flags, 255, table->s->null_bytes);
2444 }
2445 
2446 bool is_simple_order(ORDER *order);
2447 
2448 #endif /* MYSQL_CLIENT */
2449 
2450 #endif /* TABLE_INCLUDED */
2451