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