1 #ifndef TABLE_INCLUDED
2 #define TABLE_INCLUDED
3
4 /* Copyright (c) 2000, 2021, Oracle and/or its affiliates.
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
28 #ifndef MYSQL_CLIENT
29
30 #include "hash.h" // HASH
31 #include "datadict.h" // frm_type_enum
32 #include "handler.h" // row_type
33 #include "mdl.h" // MDL_wait_for_subgraph
34 #include "opt_costmodel.h" // Cost_model_table
35 #include "sql_bitmap.h" // Bitmap
36 #include "sql_sort.h" // Filesort_info
37 #include "table_id.h" // Table_id
38 #include "lock.h" // Tablespace_hash_set
39
40 /* Structs that defines the TABLE */
41 class File_parser;
42 class Item_subselect;
43 class Item_field;
44 class GRANT_TABLE;
45 class st_select_lex_unit;
46 class COND_EQUAL;
47 class Security_context;
48 class ACL_internal_schema_access;
49 class ACL_internal_table_access;
50 class Table_cache_element;
51 class Table_trigger_dispatcher;
52 class Query_result_union;
53 class Temp_table_param;
54 class Index_hint;
55 struct Name_resolution_context;
56 struct LEX;
57 typedef int8 plan_idx;
58 class Opt_hints_qb;
59 class Opt_hints_table;
60
61 #define store_record(A,B) memcpy((A)->B,(A)->record[0],(size_t) (A)->s->reclength)
62 #define restore_record(A,B) memcpy((A)->record[0],(A)->B,(size_t) (A)->s->reclength)
63 #define cmp_record(A,B) memcmp((A)->record[0],(A)->B,(size_t) (A)->s->reclength)
64 #define empty_record(A) { \
65 restore_record((A),s->default_values); \
66 memset((A)->null_flags, 255, (A)->s->null_bytes);\
67 }
68
69 /*
70 Used to identify NESTED_JOIN structures within a join (applicable to
71 structures representing outer joins that have not been simplified away).
72 */
73 typedef ulonglong nested_join_map;
74
75
76 #define tmp_file_prefix "#sql" /**< Prefix for tmp tables */
77 #define tmp_file_prefix_length 4
78 #define TMP_TABLE_KEY_EXTRA 8
79
80 /**
81 Enumerate possible types of a table from re-execution
82 standpoint.
83 TABLE_LIST class has a member of this type.
84 At prepared statement prepare, this member is assigned a value
85 as of the current state of the database. Before (re-)execution
86 of a prepared statement, we check that the value recorded at
87 prepare matches the type of the object we obtained from the
88 table definition cache.
89
90 @sa check_and_update_table_version()
91 @sa Execute_observer
92 @sa Prepared_statement::reprepare()
93 */
94
95 enum enum_table_ref_type
96 {
97 /** Initial value set by the parser */
98 TABLE_REF_NULL= 0,
99 TABLE_REF_VIEW,
100 TABLE_REF_BASE_TABLE,
101 TABLE_REF_I_S_TABLE,
102 TABLE_REF_TMP_TABLE
103 };
104
105 /**
106 Enumerate possible status of a identifier name while determining
107 its validity
108 */
109 enum enum_ident_name_check
110 {
111 IDENT_NAME_OK,
112 IDENT_NAME_WRONG,
113 IDENT_NAME_TOO_LONG
114 };
115
116 /*************************************************************************/
117
118 /**
119 Object_creation_ctx -- interface for creation context of database objects
120 (views, stored routines, events, triggers). Creation context -- is a set
121 of attributes, that should be fixed at the creation time and then be used
122 each time the object is parsed or executed.
123 */
124
125 class Object_creation_ctx
126 {
127 public:
128 Object_creation_ctx *set_n_backup(THD *thd);
129
130 void restore_env(THD *thd, Object_creation_ctx *backup_ctx);
131
132 protected:
Object_creation_ctx()133 Object_creation_ctx() {}
134 virtual Object_creation_ctx *create_backup_ctx(THD *thd) const = 0;
135
136 virtual void change_env(THD *thd) const = 0;
137
138 public:
~Object_creation_ctx()139 virtual ~Object_creation_ctx()
140 { }
141 };
142
143 /*************************************************************************/
144
145 /**
146 Default_object_creation_ctx -- default implementation of
147 Object_creation_ctx.
148 */
149
150 class Default_object_creation_ctx : public Object_creation_ctx
151 {
152 public:
get_client_cs()153 const CHARSET_INFO *get_client_cs()
154 {
155 return m_client_cs;
156 }
157
get_connection_cl()158 const CHARSET_INFO *get_connection_cl()
159 {
160 return m_connection_cl;
161 }
162
163 protected:
164 Default_object_creation_ctx(THD *thd);
165
166 Default_object_creation_ctx(const CHARSET_INFO *client_cs,
167 const CHARSET_INFO *connection_cl);
168
169 protected:
170 virtual Object_creation_ctx *create_backup_ctx(THD *thd) const;
171
172 virtual void change_env(THD *thd) const;
173
174 protected:
175 /**
176 client_cs stores the value of character_set_client session variable.
177 The only character set attribute is used.
178
179 Client character set is included into query context, because we save
180 query in the original character set, which is client character set. So,
181 in order to parse the query properly we have to switch client character
182 set on parsing.
183 */
184 const CHARSET_INFO *m_client_cs;
185
186 /**
187 connection_cl stores the value of collation_connection session
188 variable. Both character set and collation attributes are used.
189
190 Connection collation is included into query context, becase it defines
191 the character set and collation of text literals in internal
192 representation of query (item-objects).
193 */
194 const CHARSET_INFO *m_connection_cl;
195 };
196
197
198 /**
199 View_creation_ctx -- creation context of view objects.
200 */
201
202 class View_creation_ctx : public Default_object_creation_ctx,
203 public Sql_alloc
204 {
205 public:
206 static View_creation_ctx *create(THD *thd);
207
208 static View_creation_ctx *create(THD *thd,
209 TABLE_LIST *view);
210
211 private:
View_creation_ctx(THD * thd)212 View_creation_ctx(THD *thd)
213 : Default_object_creation_ctx(thd)
214 { }
215 };
216
217 /*************************************************************************/
218
219 /** Order clause list element */
220
221 typedef struct st_order {
222 struct st_order *next;
223 Item **item; /* Point at item in select fields */
224 Item *item_ptr; /* Storage for initial item */
225
226 enum enum_order {
227 ORDER_NOT_RELEVANT,
228 ORDER_ASC,
229 ORDER_DESC
230 };
231
232 enum_order direction; /* Requested direction of ordering */
233 bool in_field_list; /* true if in select field list */
234 /**
235 Tells whether this ORDER element was referenced with an alias or with an
236 expression, in the query:
237 SELECT a AS foo GROUP BY foo: true.
238 SELECT a AS foo GROUP BY a: false.
239 */
240 bool used_alias;
241 Field *field; /* If tmp-table group */
242 char *buff; /* If tmp-table group */
243 table_map used, depend_map;
244 bool is_position; /* An item expresses a position in a ORDER clause */
245 } ORDER;
246
247 /**
248 State information for internal tables grants.
249 This structure is part of the TABLE_LIST, and is updated
250 during the ACL check process.
251 @sa GRANT_INFO
252 */
253 struct st_grant_internal_info
254 {
st_grant_internal_infost_grant_internal_info255 st_grant_internal_info()
256 : m_schema_lookup_done(false),
257 m_schema_access(NULL),
258 m_table_lookup_done(false),
259 m_table_access(NULL)
260 {}
261
262 /** True if the internal lookup by schema name was done. */
263 bool m_schema_lookup_done;
264 /** Cached internal schema access. */
265 const ACL_internal_schema_access *m_schema_access;
266 /** True if the internal lookup by table name was done. */
267 bool m_table_lookup_done;
268 /** Cached internal table access. */
269 const ACL_internal_table_access *m_table_access;
270 };
271 typedef struct st_grant_internal_info GRANT_INTERNAL_INFO;
272
273 /**
274 @brief The current state of the privilege checking process for the current
275 user, SQL statement and SQL object.
276
277 @details The privilege checking process is divided into phases depending on
278 the level of the privilege to be checked and the type of object to be
279 accessed. Due to the mentioned scattering of privilege checking
280 functionality, it is necessary to keep track of the state of the
281 process. This information is stored in privilege and want_privilege.
282
283 A GRANT_INFO also serves as a cache of the privilege hash tables. Relevant
284 members are grant_table and version.
285 */
286 struct GRANT_INFO
287 {
288 GRANT_INFO();
289 /**
290 @brief A copy of the privilege information regarding the current host,
291 database, object and user.
292
293 @details The version of this copy is found in GRANT_INFO::version.
294 */
295 GRANT_TABLE *grant_table;
296 /**
297 @brief Used for cache invalidation when caching privilege information.
298
299 @details The privilege information is stored on disk, with dedicated
300 caches residing in memory: table-level and column-level privileges,
301 respectively, have their own dedicated caches.
302
303 The GRANT_INFO works as a level 1 cache with this member updated to the
304 current value of the global variable @c grant_version (@c static variable
305 in sql_acl.cc). It is updated Whenever the GRANT_INFO is refreshed from
306 the level 2 cache. The level 2 cache is the @c column_priv_hash structure
307 (@c static variable in sql_acl.cc)
308
309 @see grant_version
310 */
311 uint version;
312 /**
313 @brief The set of privileges that the current user has fulfilled for a
314 certain host, database, and object.
315
316 @details This field is continually updated throughout the access checking
317 process. In each step the "wanted privilege" is checked against the
318 fulfilled privileges. When/if the intersection of these sets is empty,
319 access is granted.
320
321 The set is implemented as a bitmap, with the bits defined in sql_acl.h.
322 */
323 ulong privilege;
324 #ifndef NDEBUG
325 /**
326 @brief the set of privileges that the current user needs to fulfil in
327 order to carry out the requested operation. Used in debug build to
328 ensure individual column privileges are assigned consistently.
329 @todo remove this member in 5.8.
330 */
331 ulong want_privilege;
332 #endif
333 /** The grant state for internal tables. */
334 GRANT_INTERNAL_INFO m_internal;
335 };
336
337 enum tmp_table_type
338 {
339 NO_TMP_TABLE, NON_TRANSACTIONAL_TMP_TABLE, TRANSACTIONAL_TMP_TABLE,
340 INTERNAL_TMP_TABLE, SYSTEM_TMP_TABLE
341 };
342
343
344 /**
345 Category of table found in the table share.
346 */
347 enum enum_table_category
348 {
349 /**
350 Unknown value.
351 */
352 TABLE_UNKNOWN_CATEGORY=0,
353
354 /**
355 Temporary table.
356 The table is visible only in the session.
357 Therefore,
358 - FLUSH TABLES WITH READ LOCK
359 - SET GLOBAL READ_ONLY = ON
360 do not apply to this table.
361 Note that LOCK TABLE t FOR READ/WRITE
362 can be used on temporary tables.
363 Temporary tables are not part of the table cache.
364 */
365 TABLE_CATEGORY_TEMPORARY=1,
366
367 /**
368 User table.
369 These tables do honor:
370 - LOCK TABLE t FOR READ/WRITE
371 - FLUSH TABLES WITH READ LOCK
372 - SET GLOBAL READ_ONLY = ON
373 User tables are cached in the table cache.
374 */
375 TABLE_CATEGORY_USER=2,
376
377 /**
378 System table, maintained by the server.
379 These tables do honor:
380 - LOCK TABLE t FOR READ/WRITE
381 - FLUSH TABLES WITH READ LOCK
382 - SET GLOBAL READ_ONLY = ON
383 Typically, writes to system tables are performed by
384 the server implementation, not explicitly be a user.
385 System tables are cached in the table cache.
386 */
387 TABLE_CATEGORY_SYSTEM=3,
388
389 /**
390 Information schema tables.
391 These tables are an interface provided by the system
392 to inspect the system metadata.
393 These tables do *not* honor:
394 - LOCK TABLE t FOR READ/WRITE
395 - FLUSH TABLES WITH READ LOCK
396 - SET GLOBAL READ_ONLY = ON
397 as there is no point in locking explicitly
398 an INFORMATION_SCHEMA table.
399 Nothing is directly written to information schema tables.
400 Note that this value is not used currently,
401 since information schema tables are not shared,
402 but implemented as session specific temporary tables.
403 */
404 /*
405 TODO: Fixing the performance issues of I_S will lead
406 to I_S tables in the table cache, which should use
407 this table type.
408 */
409 TABLE_CATEGORY_INFORMATION=4,
410
411 /**
412 Log tables.
413 These tables are an interface provided by the system
414 to inspect the system logs.
415 These tables do *not* honor:
416 - LOCK TABLE t FOR READ/WRITE
417 - FLUSH TABLES WITH READ LOCK
418 - SET GLOBAL READ_ONLY = ON
419 as there is no point in locking explicitly
420 a LOG table.
421 An example of LOG tables are:
422 - mysql.slow_log
423 - mysql.general_log,
424 which *are* updated even when there is either
425 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
426 User queries do not write directly to these tables
427 (there are exceptions for log tables).
428 The server implementation perform writes.
429 Log tables are cached in the table cache.
430 */
431 TABLE_CATEGORY_LOG=5,
432
433 /**
434 Performance schema tables.
435 These tables are an interface provided by the system
436 to inspect the system performance data.
437 These tables do *not* honor:
438 - LOCK TABLE t FOR READ/WRITE
439 - FLUSH TABLES WITH READ LOCK
440 - SET GLOBAL READ_ONLY = ON
441 as there is no point in locking explicitly
442 a PERFORMANCE_SCHEMA table.
443 An example of PERFORMANCE_SCHEMA tables are:
444 - performance_schema.*
445 which *are* updated (but not using the handler interface)
446 even when there is either
447 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
448 User queries do not write directly to these tables
449 (there are exceptions for SETUP_* tables).
450 The server implementation perform writes.
451 Performance tables are cached in the table cache.
452 */
453 TABLE_CATEGORY_PERFORMANCE=6,
454
455 /**
456 Replication Information Tables.
457 These tables are used to store replication information.
458 These tables do *not* honor:
459 - LOCK TABLE t FOR READ/WRITE
460 - FLUSH TABLES WITH READ LOCK
461 - SET GLOBAL READ_ONLY = ON
462 as there is no point in locking explicitly
463 a Replication Information table.
464 An example of replication tables are:
465 - mysql.slave_master_info
466 - mysql.slave_relay_log_info,
467 which *are* updated even when there is either
468 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
469 User queries do not write directly to these tables.
470 Replication tables are cached in the table cache.
471 */
472 TABLE_CATEGORY_RPL_INFO=7,
473
474 /**
475 Gtid Table.
476 The table is used to store gtids.
477 The table does *not* honor:
478 - LOCK TABLE t FOR READ/WRITE
479 - FLUSH TABLES WITH READ LOCK
480 - SET GLOBAL READ_ONLY = ON
481 as there is no point in locking explicitly
482 a Gtid table.
483 An example of gtid_executed table is:
484 - mysql.gtid_executed,
485 which is updated even when there is either
486 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
487 Gtid table is cached in the table cache.
488 */
489 TABLE_CATEGORY_GTID=8
490 };
491 typedef enum enum_table_category TABLE_CATEGORY;
492
493 extern ulong refresh_version;
494
495 typedef struct st_table_field_type
496 {
497 LEX_STRING name;
498 LEX_STRING type;
499 LEX_STRING cset;
500 } TABLE_FIELD_TYPE;
501
502
503 typedef struct st_table_field_def
504 {
505 uint count;
506 const TABLE_FIELD_TYPE *field;
507 } TABLE_FIELD_DEF;
508
509
510 class Table_check_intact
511 {
512 protected:
513 bool has_keys;
514 virtual void report_error(uint code, const char *fmt, ...)= 0;
515
516 public:
Table_check_intact()517 Table_check_intact() : has_keys(FALSE) {}
~Table_check_intact()518 virtual ~Table_check_intact() {}
519
520 /** Checks whether a table is intact. */
521 bool check(TABLE *table, const TABLE_FIELD_DEF *table_def);
522 };
523
524
525 /**
526 Class representing the fact that some thread waits for table
527 share to be flushed. Is used to represent information about
528 such waits in MDL deadlock detector.
529 */
530
531 class Wait_for_flush : public MDL_wait_for_subgraph
532 {
533 MDL_context *m_ctx;
534 TABLE_SHARE *m_share;
535 uint m_deadlock_weight;
536 public:
Wait_for_flush(MDL_context * ctx_arg,TABLE_SHARE * share_arg,uint deadlock_weight_arg)537 Wait_for_flush(MDL_context *ctx_arg, TABLE_SHARE *share_arg,
538 uint deadlock_weight_arg)
539 : m_ctx(ctx_arg), m_share(share_arg),
540 m_deadlock_weight(deadlock_weight_arg)
541 {}
542
get_ctx()543 MDL_context *get_ctx() const { return m_ctx; }
544
545 virtual bool accept_visitor(MDL_wait_for_graph_visitor *dvisitor);
546
547 virtual uint get_deadlock_weight() const;
548
549 /**
550 Pointers for participating in the list of waiters for table share.
551 */
552 Wait_for_flush *next_in_share;
553 Wait_for_flush **prev_in_share;
554 };
555
556
557 typedef I_P_List <Wait_for_flush,
558 I_P_List_adapter<Wait_for_flush,
559 &Wait_for_flush::next_in_share,
560 &Wait_for_flush::prev_in_share> >
561 Wait_for_flush_list;
562
563
564 /**
565 This structure is shared between different table objects. There is one
566 instance of table share per one table in the database.
567 */
568
569 struct TABLE_SHARE
570 {
TABLE_SHARETABLE_SHARE571 TABLE_SHARE() { memset(this, 0, sizeof(*this)); }
572
573 /** Category of this table. */
574 TABLE_CATEGORY table_category;
575
576 /* hash of field names (contains pointers to elements of field array) */
577 HASH name_hash; /* hash of field names */
578 MEM_ROOT mem_root;
579 TYPELIB keynames; /* Pointers to keynames */
580 TYPELIB fieldnames; /* Pointer to fieldnames */
581 TYPELIB *intervals; /* pointer to interval info */
582 mysql_mutex_t LOCK_ha_data; /* To protect access to ha_data */
583 TABLE_SHARE *next, **prev; /* Link to unused shares */
584 /**
585 Array of table_cache_instances pointers to elements of table caches
586 respresenting this table in each of Table_cache instances.
587 Allocated along with the share itself in alloc_table_share().
588 Each element of the array is protected by Table_cache::m_lock in the
589 corresponding Table_cache. False sharing should not be a problem in
590 this case as elements of this array are supposed to be updated rarely.
591 */
592 Table_cache_element **cache_element;
593
594 /* The following is copied to each TABLE on OPEN */
595 Field **field;
596 Field **found_next_number_field;
597 KEY *key_info; /* data of keys defined for the table */
598 uint *blob_field; /* Index to blobs in Field arrray*/
599
600 uchar *default_values; /* row with default values */
601 LEX_STRING comment; /* Comment about table */
602 LEX_STRING compress; /* Compression algorithm */
603 LEX_STRING encrypt_type; /* encryption algorithm */
604 uint32_t encryption_key_id;
605 bool was_encryption_key_id_set;
606 const CHARSET_INFO *table_charset; /* Default charset of string fields */
607
608 MY_BITMAP all_set;
609 /*
610 Key which is used for looking-up table in table cache and in the list
611 of thread's temporary tables. Has the form of:
612 "database_name\0table_name\0" + optional part for temporary tables.
613
614 Note that all three 'table_cache_key', 'db' and 'table_name' members
615 must be set (and be non-zero) for tables in table cache. They also
616 should correspond to each other.
617 To ensure this one can use set_table_cache() methods.
618 */
619 LEX_STRING table_cache_key;
620 LEX_STRING db; /* Pointer to db */
621 LEX_STRING table_name; /* Table name (for open) */
622 LEX_STRING path; /* Path to .frm file (from datadir) */
623 LEX_STRING normalized_path; /* unpack_filename(path) */
624 LEX_STRING connect_string;
625
626 /*
627 Set of keys in use, implemented as a Bitmap.
628 Excludes keys disabled by ALTER TABLE ... DISABLE KEYS.
629 */
630 key_map keys_in_use;
631 key_map keys_for_keyread;
632 ha_rows min_rows, max_rows; /* create information */
633 ulong avg_row_length; /* create information */
634 /**
635 TABLE_SHARE version, if changed the TABLE_SHARE must be reopened.
636 NOTE: The TABLE_SHARE will not be reopened during LOCK TABLES in
637 close_thread_tables!!!
638 */
639 ulong version;
640 ulong mysql_version; /* 0 if .frm is created before 5.0 */
641 ulong reclength; /* Recordlength */
642 ulong stored_rec_length; /* Stored record length
643 (no generated-only generated fields) */
644
645 plugin_ref db_plugin; /* storage engine plugin */
db_typeTABLE_SHARE646 inline handlerton *db_type() const /* table_type for handler */
647 {
648 // assert(db_plugin);
649 return db_plugin ? plugin_data<handlerton*>(db_plugin) : NULL;
650 }
651 enum row_type row_type; /* How rows are stored */
652 enum tmp_table_type tmp_table;
653
654 uint ref_count; /* How many TABLE objects uses this */
655 uint key_block_size; /* create key_block_size, if used */
656 uint stats_sample_pages; /* number of pages to sample during
657 stats estimation, if used, otherwise 0. */
658 enum_stats_auto_recalc stats_auto_recalc; /* Automatic recalc of stats. */
659 uint null_bytes, last_null_bit_pos;
660 uint fields; /* Number of fields */
661 uint stored_fields; /* Number of stored fields
662 (i.e. without generated-only ones) */
663 uint rec_buff_length; /* Size of table->record[] buffer */
664 uint keys; /* Number of keys defined for the table*/
665 uint key_parts; /* Number of key parts of all keys
666 defined for the table
667 */
668 uint max_key_length; /* Length of the longest key */
669 uint max_unique_length; /* Length of the longest unique key */
670 uint total_key_length;
671 uint uniques; /* Number of UNIQUE index */
672 uint null_fields; /* number of null fields */
673 uint blob_fields; /* number of blob fields */
674 uint varchar_fields; /* number of varchar fields */
675 uint db_create_options; /* Create options from database */
676 uint db_options_in_use; /* Options in use */
677 uint db_record_offset; /* if HA_REC_IN_SEQ */
678 uint rowid_field_offset; /* Field_nr +1 to rowid field */
679 /* Primary key index number, used in TABLE::key_info[] */
680 uint primary_key;
681 uint next_number_index; /* autoincrement key number */
682 uint next_number_key_offset; /* autoinc keypart offset in a key */
683 uint next_number_keypart; /* autoinc keypart number in a key */
684 uint error, open_errno, errarg; /* error from open_table_def() */
685 uint column_bitmap_size;
686 uchar frm_version;
687 uint vfields; /* Number of generated fields */
688 bool null_field_first;
689 bool system; /* Set if system table (one record) */
690 bool crypted; /* If .frm file is crypted */
691 bool db_low_byte_first; /* Portable row format */
692 bool crashed;
693 bool is_view;
694 bool m_open_in_progress; /* True: alloc'ed, false: def opened */
695 Table_id table_map_id; /* for row-based replication */
696
697 /*
698 Cache for row-based replication table share checks that does not
699 need to be repeated. Possible values are: -1 when cache value is
700 not calculated yet, 0 when table *shall not* be replicated, 1 when
701 table *may* be replicated.
702 */
703 int cached_row_logging_check;
704
705 /*
706 Storage media to use for this table (unless another storage
707 media has been specified on an individual column - in versions
708 where that is supported)
709 */
710 enum ha_storage_media default_storage_media;
711
712 /* Name of the tablespace used for this table */
713 char *tablespace;
714
715 /* filled in when reading from frm */
716 bool auto_partitioned;
717 char *partition_info_str;
718 uint partition_info_str_len;
719 uint partition_info_buffer_size;
720 handlerton *default_part_db_type;
721
722 /**
723 Cache the checked structure of this table.
724
725 The pointer data is used to describe the structure that
726 a instance of the table must have. Each element of the
727 array specifies a field that must exist on the table.
728
729 The pointer is cached in order to perform the check only
730 once -- when the table is loaded from the disk.
731 */
732 const TABLE_FIELD_DEF *table_field_def_cache;
733
734 /** Main handler's share */
735 Handler_share *ha_share;
736
737 /** Instrumentation for this table share. */
738 PSI_table_share *m_psi;
739
740 /**
741 List of tickets representing threads waiting for the share to be flushed.
742 */
743 Wait_for_flush_list m_flush_tickets;
744
745 /**
746 For shares representing views File_parser object with view
747 definition read from .FRM file.
748 */
749 const File_parser *view_def;
750
751 /**
752 True in the case if tokudb read-free-replication is used for the table
753 without explicit pk and corresponding warning was issued to disable
754 repeated warning.
755 */
756 bool rfr_lookup_warning;
757
758 /*
759 Set share's table cache key and update its db and table name appropriately.
760
761 SYNOPSIS
762 set_table_cache_key()
763 key_buff Buffer with already built table cache key to be
764 referenced from share.
765 key_length Key length.
766
767 NOTES
768 Since 'key_buff' buffer will be referenced from share it should has same
769 life-time as share itself.
770 This method automatically ensures that TABLE_SHARE::table_name/db have
771 appropriate values by using table cache key as their source.
772 */
773
set_table_cache_keyTABLE_SHARE774 void set_table_cache_key(char *key_buff, size_t key_length)
775 {
776 table_cache_key.str= key_buff;
777 table_cache_key.length= key_length;
778 /*
779 Let us use the fact that the key is "db/0/table_name/0" + optional
780 part for temporary tables.
781 */
782 db.str= table_cache_key.str;
783 db.length= strlen(db.str);
784 table_name.str= db.str + db.length + 1;
785 table_name.length= strlen(table_name.str);
786 }
787
788
789 /*
790 Set share's table cache key and update its db and table name appropriately.
791
792 SYNOPSIS
793 set_table_cache_key()
794 key_buff Buffer to be used as storage for table cache key
795 (should be at least key_length bytes).
796 key Value for table cache key.
797 key_length Key length.
798
799 NOTE
800 Since 'key_buff' buffer will be used as storage for table cache key
801 it should has same life-time as share itself.
802 */
803
set_table_cache_keyTABLE_SHARE804 void set_table_cache_key(char *key_buff, const char *key, size_t key_length)
805 {
806 memcpy(key_buff, key, key_length);
807 set_table_cache_key(key_buff, key_length);
808 }
809
honor_global_locksTABLE_SHARE810 inline bool honor_global_locks()
811 {
812 return ((table_category == TABLE_CATEGORY_USER)
813 || (table_category == TABLE_CATEGORY_SYSTEM));
814 }
815
get_table_def_versionTABLE_SHARE816 inline ulonglong get_table_def_version()
817 {
818 return table_map_id;
819 }
820
821
822 /** Is this table share being expelled from the table definition cache? */
has_old_versionTABLE_SHARE823 inline bool has_old_version() const
824 {
825 return version != refresh_version;
826 }
827 /**
828 Convert unrelated members of TABLE_SHARE to one enum
829 representing its type.
830
831 @todo perhaps we need to have a member instead of a function.
832 */
get_table_ref_typeTABLE_SHARE833 enum enum_table_ref_type get_table_ref_type() const
834 {
835 if (is_view)
836 return TABLE_REF_VIEW;
837 switch (tmp_table) {
838 case NO_TMP_TABLE:
839 return TABLE_REF_BASE_TABLE;
840 case SYSTEM_TMP_TABLE:
841 return TABLE_REF_I_S_TABLE;
842 default:
843 return TABLE_REF_TMP_TABLE;
844 }
845 }
846 /**
847 Return a table metadata version.
848 * for base tables and views, we return table_map_id.
849 It is assigned from a global counter incremented for each
850 new table loaded into the table definition cache (TDC).
851 * for temporary tables it's table_map_id again. But for
852 temporary tables table_map_id is assigned from
853 thd->query_id. The latter is assigned from a thread local
854 counter incremented for every new SQL statement. Since
855 temporary tables are thread-local, each temporary table
856 gets a unique id.
857 * for everything else (e.g. information schema tables),
858 the version id is zero.
859
860 This choice of version id is a large compromise
861 to have a working prepared statement validation in 5.1. In
862 future version ids will be persistent, as described in WL#4180.
863
864 Let's try to explain why and how this limited solution allows
865 to validate prepared statements.
866
867 Firstly, sets (in mathematical sense) of version numbers
868 never intersect for different table types. Therefore,
869 version id of a temporary table is never compared with
870 a version id of a view, and vice versa.
871
872 Secondly, for base tables and views, we know that each DDL flushes
873 the respective share from the TDC. This ensures that whenever
874 a table is altered or dropped and recreated, it gets a new
875 version id.
876 Unfortunately, since elements of the TDC are also flushed on
877 LRU basis, this choice of version ids leads to false positives.
878 E.g. when the TDC size is too small, we may have a SELECT
879 * FROM INFORMATION_SCHEMA.TABLES flush all its elements, which
880 in turn will lead to a validation error and a subsequent
881 reprepare of all prepared statements. This is
882 considered acceptable, since as long as prepared statements are
883 automatically reprepared, spurious invalidation is only
884 a performance hit. Besides, no better simple solution exists.
885
886 For temporary tables, using thd->query_id ensures that if
887 a temporary table was altered or recreated, a new version id is
888 assigned. This suits validation needs very well and will perhaps
889 never change.
890
891 Metadata of information schema tables never changes.
892 Thus we can safely assume 0 for a good enough version id.
893
894 Finally, by taking into account table type, we always
895 track that a change has taken place when a view is replaced
896 with a base table, a base table is replaced with a temporary
897 table and so on.
898
899 @sa TABLE_LIST::is_table_ref_id_equal()
900 */
get_table_ref_versionTABLE_SHARE901 ulonglong get_table_ref_version() const
902 {
903 return (tmp_table == SYSTEM_TMP_TABLE) ? 0 : table_map_id.id();
904 }
905
906 bool visit_subgraph(Wait_for_flush *waiting_ticket,
907 MDL_wait_for_graph_visitor *gvisitor);
908
909 bool wait_for_old_version(THD *thd, struct timespec *abstime,
910 uint deadlock_weight);
911 /** Release resources and free memory occupied by the table share. */
912 void destroy();
913
914 /**
915 Checks if TABLE_SHARE has at least one field with
916 COLUMN_FORMAT_TYPE_COMPRESSED flag.
917 */
918 bool has_compressed_columns() const;
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(key_memory_blob_mem_storage,
941 &storage, MAX_FIELD_VARCHARLENGTH, 0);
942 }
~Blob_mem_storage()943 ~ Blob_mem_storage()
944 {
945 free_root(&storage, MYF(0));
946 }
reset()947 void reset()
948 {
949 free_root(&storage, MYF(MY_MARK_BLOCKS_FREE));
950 truncated_value= false;
951 }
952 /**
953 Fuction creates duplicate of 'from'
954 string in 'storage' MEM_ROOT.
955
956 @param from string to copy
957 @param length string length
958
959 @retval Pointer to the copied string.
960 @retval 0 if an error occured.
961 */
store(const char * from,size_t length)962 char *store(const char *from, size_t length)
963 {
964 return (char*) memdup_root(&storage, from, length);
965 }
set_truncated_value(bool is_truncated_value)966 void set_truncated_value(bool is_truncated_value)
967 {
968 truncated_value= is_truncated_value;
969 }
is_truncated_value()970 bool is_truncated_value() { return truncated_value; }
971 };
972
973
974 /**
975 Flags for TABLE::status (maximum 8 bits). Do NOT add new ones.
976 @todo: GARBAGE and NOT_FOUND could be unified. UPDATED and DELETED could be
977 changed to "bool current_row_has_already_been_modified" in the
978 multi_update/delete objects (one such bool per to-be-modified table).
979 @todo aim at removing the status. There should be more local ways.
980 */
981 #define STATUS_GARBAGE 1
982 /**
983 Means we were searching for a row and didn't find it. This is used by
984 storage engines (@see handler::index_read_map()) and the Server layer.
985 */
986 #define STATUS_NOT_FOUND 2
987 /// Reserved for use by multi-table update. Means the row has been updated.
988 #define STATUS_UPDATED 16
989 /**
990 Means that table->null_row is set. This is an artificial NULL-filled row
991 (one example: in outer join, if no match has been found in inner table).
992 */
993 #define STATUS_NULL_ROW 32
994 /// Reserved for use by multi-table delete. Means the row has been deleted.
995 #define STATUS_DELETED 64
996
997
998 /* Information for one open table */
999 enum index_hint_type
1000 {
1001 INDEX_HINT_IGNORE,
1002 INDEX_HINT_USE,
1003 INDEX_HINT_FORCE
1004 };
1005
1006 /* Bitmap of table's fields */
1007 typedef Bitmap<MAX_FIELDS> Field_map;
1008
1009 struct TABLE
1010 {
TABLETABLE1011 TABLE() { memset(this, 0, sizeof(*this)); }
1012 /*
1013 Since TABLE instances are often cleared using memset(), do not
1014 add virtual members and do not inherit from TABLE.
1015 Otherwise memset() will start overwriting the vtable pointer.
1016 */
1017
1018 TABLE_SHARE *s;
1019 handler *file;
1020 TABLE *next, *prev;
1021
1022 private:
1023 /**
1024 Links for the lists of used/unused TABLE objects for the particular
1025 table in the specific instance of Table_cache (in other words for
1026 specific Table_cache_element object).
1027 Declared as private to avoid direct manipulation with those objects.
1028 One should use methods of I_P_List template instead.
1029 */
1030 TABLE *cache_next, **cache_prev;
1031
1032 /*
1033 Give Table_cache_element access to the above two members to allow
1034 using them for linking TABLE objects in a list.
1035 */
1036 friend class Table_cache_element;
1037
1038 public:
1039
1040 THD *in_use; /* Which thread uses this */
1041 Field **field; /* Pointer to fields */
1042 /// Count of hidden fields, if internal temporary table; 0 otherwise.
1043 uint hidden_field_count;
1044
1045 uchar *record[2]; /* Pointer to records */
1046 uchar *write_row_record; /* Used as optimisation in
1047 THD::write_row */
1048 uchar *insert_values; /* used by INSERT ... UPDATE */
1049 /*
1050 Map of keys that can be used to retrieve all data from this table
1051 needed by the query without reading the row.
1052 */
1053 key_map covering_keys;
1054 key_map quick_keys, merge_keys;
1055
1056 /*
1057 possible_quick_keys is a superset of quick_keys to use with EXPLAIN of
1058 JOIN-less commands (single-table UPDATE and DELETE).
1059
1060 When explaining regular JOINs, we use JOIN_TAB::keys to output the
1061 "possible_keys" column value. However, it is not available for
1062 single-table UPDATE and DELETE commands, since they don't use JOIN
1063 optimizer at the top level. OTOH they directly use the range optimizer,
1064 that collects all keys usable for range access here.
1065 */
1066 key_map possible_quick_keys;
1067
1068 /*
1069 A set of keys that can be used in the query that references this
1070 table.
1071
1072 All indexes disabled on the table's TABLE_SHARE (see TABLE::s) will be
1073 subtracted from this set upon instantiation. Thus for any TABLE t it holds
1074 that t.keys_in_use_for_query is a subset of t.s.keys_in_use. Generally we
1075 must not introduce any new keys here (see setup_tables).
1076
1077 The set is implemented as a bitmap.
1078 */
1079 key_map keys_in_use_for_query;
1080 /* Map of keys that can be used to calculate GROUP BY without sorting */
1081 key_map keys_in_use_for_group_by;
1082 /* Map of keys that can be used to calculate ORDER BY without sorting */
1083 key_map keys_in_use_for_order_by;
1084 KEY *key_info; /* data of keys defined for the table */
1085
1086 Field *next_number_field; /* Set if next_number is activated */
1087 Field *found_next_number_field; /* Set on open */
1088 Field **vfield; /* Pointer to generated fields*/
1089 Field *hash_field; /* Field used by unique constraint */
1090 Field *fts_doc_id_field; /* Set if FTS_DOC_ID field is present */
1091
1092 /* Table's triggers, 0 if there are no of them */
1093 Table_trigger_dispatcher *triggers;
1094 TABLE_LIST *pos_in_table_list;/* Element referring to this table */
1095 /* Position in thd->locked_table_list under LOCK TABLES */
1096 TABLE_LIST *pos_in_locked_tables;
1097 ORDER *group;
1098 const char *alias; /* alias or table name */
1099 uchar *null_flags;
1100 my_bitmap_map *bitmap_init_value;
1101 MY_BITMAP def_read_set, def_write_set, tmp_set; /* containers */
1102 /*
1103 Bitmap of fields that one or more query condition refers to. Only
1104 used if optimizer_condition_fanout_filter is turned 'on'.
1105 Currently, only the WHERE clause and ON clause of inner joins is
1106 taken into account but not ON conditions of outer joins.
1107 Furthermore, HAVING conditions apply to groups and are therefore
1108 not useful as table condition filters.
1109 */
1110 MY_BITMAP cond_set;
1111
1112 /**
1113 Bitmap of table fields (columns), which are explicitly set in the
1114 INSERT INTO statement. It is declared here to avoid memory allocation
1115 on MEM_ROOT).
1116
1117 @sa fields_set_during_insert.
1118 */
1119 MY_BITMAP def_fields_set_during_insert;
1120
1121 MY_BITMAP *read_set, *write_set; /* Active column sets */
1122
1123 /**
1124 A pointer to the bitmap of table fields (columns), which are explicitly set
1125 in the INSERT INTO statement.
1126
1127 fields_set_during_insert points to def_fields_set_during_insert
1128 for base (non-temporary) tables. In other cases, it is NULL.
1129 Triggers can not be defined for temporary tables, so this bitmap does not
1130 matter for temporary tables.
1131
1132 @sa def_fields_set_during_insert.
1133 */
1134 MY_BITMAP *fields_set_during_insert;
1135
1136 /*
1137 The ID of the query that opened and is using this table. Has different
1138 meanings depending on the table type.
1139
1140 Temporary tables:
1141
1142 table->query_id is set to thd->query_id for the duration of a statement
1143 and is reset to 0 once it is closed by the same statement. A non-zero
1144 table->query_id means that a statement is using the table even if it's
1145 not the current statement (table is in use by some outer statement).
1146
1147 Non-temporary tables:
1148
1149 Under pre-locked or LOCK TABLES mode: query_id is set to thd->query_id
1150 for the duration of a statement and is reset to 0 once it is closed by
1151 the same statement. A non-zero query_id is used to control which tables
1152 in the list of pre-opened and locked tables are actually being used.
1153 */
1154 query_id_t query_id;
1155
1156 /*
1157 For each key that has quick_keys.is_set(key) == TRUE: estimate of #records
1158 and max #key parts that range access would use.
1159 */
1160 ha_rows quick_rows[MAX_KEY];
1161
1162 /* Bitmaps of key parts that =const for the entire join. */
1163 key_part_map const_key_parts[MAX_KEY];
1164
1165 uint quick_key_parts[MAX_KEY];
1166 uint quick_n_ranges[MAX_KEY];
1167
1168 /*
1169 Estimate of number of records that satisfy SARGable part of the table
1170 condition, or table->file->records if no SARGable condition could be
1171 constructed.
1172 This value is used by join optimizer as an estimate of number of records
1173 that will pass the table condition (condition that depends on fields of
1174 this table and constants)
1175 */
1176 ha_rows quick_condition_rows;
1177
1178 uint lock_position; /* Position in MYSQL_LOCK.table */
1179 uint lock_data_start; /* Start pos. in MYSQL_LOCK.locks */
1180 uint lock_count; /* Number of locks */
1181 uint temp_pool_slot; /* Used by intern temp tables */
1182 uint db_stat; /* mode of file as in handler.h */
1183 int current_lock; /* Type of lock on table */
1184
1185 private:
1186 /**
1187 If true, this table is inner w.r.t. some outer join operation, all columns
1188 are nullable (in the query), and null_row may be true.
1189 */
1190 my_bool nullable;
1191
1192 public:
1193 /*
1194 If true, the current table row is considered to have all columns set to
1195 NULL, including columns declared as "not null" (see nullable).
1196 @todo make it private, currently join buffering changes it through a pointer
1197 */
1198 my_bool null_row;
1199
1200 uint8 status; /* What's in record[0] */
1201 my_bool copy_blobs; /* copy_blobs when storing */
1202
1203 /*
1204 TODO: Each of the following flags take up 8 bits. They can just as easily
1205 be put into one single unsigned long and instead of taking up 18
1206 bytes, it would take up 4.
1207 */
1208 my_bool force_index;
1209
1210 /**
1211 Flag set when the statement contains FORCE INDEX FOR ORDER BY
1212 See TABLE_LIST::process_index_hints().
1213 */
1214 my_bool force_index_order;
1215
1216 /**
1217 Flag set when the statement contains FORCE INDEX FOR GROUP BY
1218 See TABLE_LIST::process_index_hints().
1219 */
1220 my_bool force_index_group;
1221 my_bool distinct;
1222 my_bool const_table;
1223 my_bool no_rows;
1224
1225 /**
1226 If set, the optimizer has found that row retrieval should access index
1227 tree only.
1228 */
1229 my_bool key_read;
1230 /**
1231 Certain statements which need the full row, set this to ban index-only
1232 access.
1233 */
1234 my_bool no_keyread;
1235 my_bool locked_by_logger;
1236 /**
1237 If set, indicate that the table is not replicated by the server.
1238 */
1239 my_bool no_replicate;
1240 my_bool locked_by_name;
1241 my_bool fulltext_searched;
1242 my_bool no_cache;
1243 /* To signal that the table is associated with a HANDLER statement */
1244 my_bool open_by_handler;
1245 /*
1246 To indicate that a non-null value of the auto_increment field
1247 was provided by the user or retrieved from the current record.
1248 Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode.
1249 */
1250 my_bool auto_increment_field_not_null;
1251 my_bool insert_or_update; /* Can be used by the handler */
1252 my_bool alias_name_used; /* true if table_name is alias */
1253 my_bool get_fields_in_item_tree; /* Signal to fix_field */
1254 /**
1255 This table must be reopened and is not to be reused.
1256 NOTE: The TABLE will not be reopened during LOCK TABLES in
1257 close_thread_tables!!!
1258 */
1259 my_bool m_needs_reopen;
1260 private:
1261 bool created; /* For tmp tables. TRUE <=> tmp table has been instantiated.*/
1262 public:
1263 uint max_keys; /* Size of allocated key_info array. */
1264
1265 struct /* field connections */
1266 {
1267 class JOIN_TAB *join_tab;
1268 class QEP_TAB *qep_tab;
1269 enum thr_lock_type lock_type; /* How table is used */
1270 bool not_exists_optimize;
1271 /*
1272 TRUE <=> range optimizer found that there is no rows satisfying
1273 table conditions.
1274 */
1275 bool impossible_range;
1276 } reginfo;
1277
1278 /**
1279 @todo This member should not be declared in-line. That makes it
1280 impossible for any function that does memory allocation to take a const
1281 reference to a TABLE object.
1282 */
1283 MEM_ROOT mem_root;
1284 /**
1285 Initialized in Item_func_group_concat::setup for appropriate
1286 temporary table if GROUP_CONCAT is used with ORDER BY | DISTINCT
1287 and BLOB field count > 0.
1288 */
1289 Blob_mem_storage *blob_storage;
1290 GRANT_INFO grant;
1291 Filesort_info sort;
1292 partition_info *part_info; /* Partition related information */
1293 /* If true, all partitions have been pruned away */
1294 bool all_partitions_pruned_away;
1295 MDL_ticket *mdl_ticket;
1296
1297 private:
1298 /// Cost model object for operations on this table
1299 Cost_model_table m_cost_model;
1300 public:
1301
1302 void init(THD *thd, TABLE_LIST *tl);
1303 bool fill_item_list(List<Item> *item_list) const;
1304 void reset_item_list(List<Item> *item_list) const;
1305 void clear_column_bitmaps(void);
1306 void prepare_for_position(void);
1307
1308 void mark_column_used(THD *thd, Field *field, enum enum_mark_columns mark);
1309 void mark_columns_used_by_index_no_reset(uint index, MY_BITMAP *map,
1310 uint key_parts= 0);
1311 void mark_columns_used_by_index(uint index);
1312 void mark_auto_increment_column(void);
1313 void mark_columns_needed_for_update(bool mark_binlog_columns);
1314 void mark_columns_needed_for_delete(void);
1315 void mark_columns_needed_for_insert(void);
1316 void mark_columns_per_binlog_row_image(void);
1317 void mark_generated_columns(bool is_update);
1318 bool is_field_used_by_generated_columns(uint field_index);
1319 void mark_gcol_in_maps(Field *field);
column_bitmaps_setTABLE1320 inline void column_bitmaps_set(MY_BITMAP *read_set_arg,
1321 MY_BITMAP *write_set_arg)
1322 {
1323 read_set= read_set_arg;
1324 write_set= write_set_arg;
1325 if (file && created)
1326 file->column_bitmaps_signal();
1327 }
column_bitmaps_set_no_signalTABLE1328 inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg,
1329 MY_BITMAP *write_set_arg)
1330 {
1331 read_set= read_set_arg;
1332 write_set= write_set_arg;
1333 }
use_all_columnsTABLE1334 inline void use_all_columns()
1335 {
1336 column_bitmaps_set(&s->all_set, &s->all_set);
1337 }
default_column_bitmapsTABLE1338 inline void default_column_bitmaps()
1339 {
1340 read_set= &def_read_set;
1341 write_set= &def_write_set;
1342 }
1343 /** Should this instance of the table be reopened? */
needs_reopenTABLE1344 inline bool needs_reopen()
1345 { return !db_stat || m_needs_reopen; }
1346 /// @returns first non-hidden column
visible_field_ptrTABLE1347 Field **visible_field_ptr() const
1348 { return field + hidden_field_count; }
1349 /// @returns count of visible fields
visible_field_countTABLE1350 uint visible_field_count() const
1351 { return s->fields - hidden_field_count; }
1352 bool alloc_keys(uint key_count);
1353 bool add_tmp_key(Field_map *key_parts, char *key_name);
1354 void use_index(int key_to_save);
1355
set_keyreadTABLE1356 void set_keyread(bool flag)
1357 {
1358 assert(file);
1359 if (flag && !key_read)
1360 {
1361 key_read= 1;
1362 if (is_created())
1363 file->extra(HA_EXTRA_KEYREAD);
1364 }
1365 else if (!flag && key_read)
1366 {
1367 key_read= 0;
1368 if (is_created())
1369 file->extra(HA_EXTRA_NO_KEYREAD);
1370 }
1371 }
1372
1373 /**
1374 Check whether the given index has a virtual generated columns.
1375
1376 @param index_no the given index to check
1377
1378 @returns true if if index is defined over at least one virtual generated
1379 column
1380 */
index_contains_some_virtual_gcolTABLE1381 inline bool index_contains_some_virtual_gcol(uint index_no)
1382 {
1383 assert(index_no < s->keys);
1384 return key_info[index_no].flags & HA_VIRTUAL_GEN_KEY;
1385 }
1386 bool update_const_key_parts(Item *conds);
1387
1388 bool check_read_removal(uint index);
1389
default_values_offsetTABLE1390 my_ptrdiff_t default_values_offset() const
1391 { return (my_ptrdiff_t) (s->default_values - record[0]); }
1392
1393 /// Return true if table is instantiated, and false otherwise.
is_createdTABLE1394 bool is_created() const { return created; }
1395
1396 /**
1397 Set the table as "created", and enable flags in storage engine
1398 that could not be enabled without an instantiated table.
1399 */
set_createdTABLE1400 void set_created()
1401 {
1402 if (created)
1403 return;
1404 if (key_read)
1405 file->extra(HA_EXTRA_KEYREAD);
1406 created= true;
1407 }
1408 /**
1409 Set the contents of table to be "deleted", ie "not created", after having
1410 deleted the contents.
1411 */
set_deletedTABLE1412 void set_deleted()
1413 {
1414 created= false;
1415 }
1416 /// Set table as nullable, ie it is inner wrt some outer join
set_nullableTABLE1417 void set_nullable() { nullable= TRUE; }
1418
1419 /// Return whether table is nullable
is_nullableTABLE1420 bool is_nullable() const { return nullable; }
1421
1422 /// @return true if table contains one or more generated columns
has_gcolTABLE1423 bool has_gcol() const { return vfield; }
1424
1425 /// @return true if table contains one or more virtual generated columns
1426 bool has_virtual_gcol() const;
1427
1428 /// Set current row as "null row", for use in null-complemented outer join
set_null_rowTABLE1429 void set_null_row()
1430 {
1431 null_row= TRUE;
1432 status|= STATUS_NULL_ROW;
1433 memset(null_flags, 255, s->null_bytes);
1434 }
1435
1436 /// Clear "null row" status for the current row
reset_null_rowTABLE1437 void reset_null_row()
1438 {
1439 null_row= FALSE;
1440 status&= ~STATUS_NULL_ROW;
1441 }
1442
1443 /// @return true if current row is null-extended
has_null_rowTABLE1444 bool has_null_row() const { return null_row; }
1445
1446 /**
1447 Initialize the optimizer cost model.
1448
1449 This function should be called each time a new query is started.
1450
1451 @param cost_model_server the main cost model object for the query
1452 */
init_cost_modelTABLE1453 void init_cost_model(const Cost_model_server* cost_model_server)
1454 {
1455 m_cost_model.init(cost_model_server, this);
1456 }
1457
1458 /**
1459 Return the cost model object for this table.
1460 */
cost_modelTABLE1461 const Cost_model_table* cost_model() const { return &m_cost_model; }
1462
1463 /**
1464 Fix table's generated columns' (GC) expressions
1465
1466 @details When a table is opened from the dictionary, the GCs' expressions
1467 are fixed during opening (see fix_fields_gcol_func()). After query
1468 execution, Item::cleanup() is called on them (see cleanup_gc_items()). When
1469 the table is opened from the table cache, the GCs need to be fixed again
1470 and this function does that.
1471
1472 @param[in] thd the current thread
1473 @return true if error, else false
1474 */
1475 bool refix_gc_items(THD *thd);
1476
1477 /**
1478 Clean any state in items associated with generated columns to be ready for
1479 the next statement.
1480 */
1481 void cleanup_gc_items();
1482
1483 /**
1484 Checks if TABLE has at least one field with
1485 COLUMN_FORMAT_TYPE_COMPRESSED flag.
1486 */
1487 bool has_compressed_columns() const;
1488
1489 /**
1490 Checks if TABLE has at least one field with
1491 COLUMN_FORMAT_TYPE_COMPRESSED flag and non-empty
1492 zip_dict.
1493 */
1494 bool has_compressed_columns_with_dictionaries() const;
1495
1496 /**
1497 Updates zip_dict_name in the TABLE's field definitions based on the
1498 values from the supplied list of Create_field objects.
1499 */
1500 void update_compressed_columns_info(const List<Create_field>& fields);
1501
1502 /**
1503 Check if table contains any records.
1504
1505 @param thd The thread object
1506 @param[out] retval Pointer to boolean value (true if table is not empty).
1507
1508 @returns false for success, true for error
1509 */
1510 bool contains_records(THD *thd, bool *retval);
1511 private:
1512
1513 /**
1514 This flag decides whether or not we should log the drop temporary table
1515 command.
1516 */
1517 bool should_binlog_drop_if_temp_flag;
1518
1519 public:
1520 /**
1521 Virtual fields of type BLOB have a flag m_keep_old_value. This flag is set
1522 to false for all such fields in this table.
1523 */
1524 void blobs_need_not_keep_old_value();
1525
1526 /**
1527 Set the variable should_binlog_drop_if_temp_flag, so that
1528 the logging of temporary tables can be decided.
1529
1530 @param should_binlog the value to set flag should_binlog_drop_if_temp_flag
1531 */
1532 void set_binlog_drop_if_temp(bool should_binlog);
1533
1534 /**
1535 @return whether should_binlog_drop_if_temp_flag flag is
1536 set or not
1537 */
1538 bool should_binlog_drop_if_temp(void) const;
1539 };
1540
1541
1542 enum enum_schema_table_state
1543 {
1544 NOT_PROCESSED= 0,
1545 PROCESSED_BY_CREATE_SORT_INDEX,
1546 PROCESSED_BY_JOIN_EXEC
1547 };
1548
1549 typedef struct st_foreign_key_info
1550 {
1551 LEX_STRING *foreign_id;
1552 LEX_STRING *foreign_db;
1553 LEX_STRING *foreign_table;
1554 LEX_STRING *referenced_db;
1555 LEX_STRING *referenced_table;
1556 LEX_STRING *update_method;
1557 LEX_STRING *delete_method;
1558 LEX_STRING *referenced_key_name;
1559 List<LEX_STRING> foreign_fields;
1560 List<LEX_STRING> referenced_fields;
1561 } FOREIGN_KEY_INFO;
1562
1563 #define MY_I_S_MAYBE_NULL 1
1564 #define MY_I_S_UNSIGNED 2
1565
1566
1567 #define SKIP_OPEN_TABLE 0 // do not open table
1568 #define OPEN_FRM_ONLY 1 // open FRM file only
1569 #define OPEN_FULL_TABLE 2 // open FRM,MYD, MYI files
1570
1571 typedef struct st_field_info
1572 {
1573 /**
1574 This is used as column name.
1575 */
1576 const char* field_name;
1577 /**
1578 For string-type columns, this is the maximum number of
1579 characters. Otherwise, it is the 'display-length' for the column.
1580 For the data type MYSQL_TYPE_DATETIME this field specifies the
1581 number of digits in the fractional part of time value.
1582 */
1583 uint field_length;
1584 /**
1585 This denotes data type for the column. For the most part, there seems to
1586 be one entry in the enum for each SQL data type, although there seem to
1587 be a number of additional entries in the enum.
1588 */
1589 enum enum_field_types field_type;
1590 int value;
1591 /**
1592 This is used to set column attributes. By default, columns are @c NOT
1593 @c NULL and @c SIGNED, and you can deviate from the default
1594 by setting the appopriate flags. You can use either one of the flags
1595 @c MY_I_S_MAYBE_NULL and @cMY_I_S_UNSIGNED or
1596 combine them using the bitwise or operator @c |. Both flags are
1597 defined in table.h.
1598 */
1599 uint field_flags; // Field atributes(maybe_null, signed, unsigned etc.)
1600 const char* old_name;
1601 /**
1602 This should be one of @c SKIP_OPEN_TABLE,
1603 @c OPEN_FRM_ONLY or @c OPEN_FULL_TABLE.
1604 */
1605 uint open_method;
1606 } ST_FIELD_INFO;
1607
1608
1609 struct TABLE_LIST;
1610
1611 typedef struct st_schema_table
1612 {
1613 const char* table_name;
1614 ST_FIELD_INFO *fields_info;
1615 /* Create information_schema table */
1616 TABLE *(*create_table) (THD *thd, TABLE_LIST *table_list);
1617 /* Fill table with data */
1618 int (*fill_table) (THD *thd, TABLE_LIST *tables, Item *cond);
1619 /* Handle fileds for old SHOW */
1620 int (*old_format) (THD *thd, struct st_schema_table *schema_table);
1621 int (*process_table) (THD *thd, TABLE_LIST *tables, TABLE *table,
1622 bool res, LEX_STRING *db_name, LEX_STRING *table_name);
1623 int idx_field1, idx_field2;
1624 bool hidden;
1625 uint i_s_requested_object; /* the object we need to open(TABLE | VIEW) */
1626 } ST_SCHEMA_TABLE;
1627
1628
1629 #define JOIN_TYPE_LEFT 1
1630 #define JOIN_TYPE_RIGHT 2
1631
1632 /**
1633 Strategy for how to process a view or derived table (merge or materialization)
1634 */
1635 enum enum_view_algorithm {
1636 VIEW_ALGORITHM_UNDEFINED = 0,
1637 VIEW_ALGORITHM_TEMPTABLE = 1,
1638 VIEW_ALGORITHM_MERGE = 2
1639 };
1640
1641 #define VIEW_SUID_INVOKER 0
1642 #define VIEW_SUID_DEFINER 1
1643 #define VIEW_SUID_DEFAULT 2
1644
1645 /* view WITH CHECK OPTION parameter options */
1646 #define VIEW_CHECK_NONE 0
1647 #define VIEW_CHECK_LOCAL 1
1648 #define VIEW_CHECK_CASCADED 2
1649
1650 /* result of view WITH CHECK OPTION parameter check */
1651 #define VIEW_CHECK_OK 0
1652 #define VIEW_CHECK_ERROR 1
1653 #define VIEW_CHECK_SKIP 2
1654
1655 /** The threshold size a blob field buffer before it is freed */
1656 #define MAX_TDC_BLOB_SIZE 65536
1657
1658 /**
1659 Struct that describes an expression selected from a derived table or view.
1660 */
1661 struct Field_translator
1662 {
1663 /**
1664 Points to an item that represents the expression.
1665 If the item is determined to be unused, the pointer is set to NULL.
1666 */
1667 Item *item;
1668 /// Name of selected expression
1669 const char *name;
1670 };
1671
1672
1673 /*
1674 Column reference of a NATURAL/USING join. Since column references in
1675 joins can be both from views and stored tables, may point to either a
1676 Field (for tables), or a Field_translator (for views).
1677 */
1678
1679 class Natural_join_column: public Sql_alloc
1680 {
1681 public:
1682 Field_translator *view_field; /* Column reference of merge view. */
1683 Item_field *table_field; /* Column reference of table or temp view. */
1684 TABLE_LIST *table_ref; /* Original base table/view reference. */
1685 /*
1686 True if a common join column of two NATURAL/USING join operands. Notice
1687 that when we have a hierarchy of nested NATURAL/USING joins, a column can
1688 be common at some level of nesting but it may not be common at higher
1689 levels of nesting. Thus this flag may change depending on at which level
1690 we are looking at some column.
1691 */
1692 bool is_common;
1693 public:
1694 Natural_join_column(Field_translator *field_param, TABLE_LIST *tab);
1695 Natural_join_column(Item_field *field_param, TABLE_LIST *tab);
1696 const char *name();
1697 Item *create_item(THD *thd);
1698 Field *field();
1699 const char *table_name();
1700 const char *db_name();
1701 GRANT_INFO *grant();
1702 };
1703
1704
1705 /*
1706 This structure holds the specifications relating to
1707 ALTER user ... PASSWORD EXPIRE ...
1708 */
1709 typedef struct st_lex_alter {
1710 bool update_password_expired_fields;
1711 bool update_password_expired_column;
1712 bool use_default_password_lifetime;
1713 uint16 expire_after_days;
1714 bool update_account_locked_column;
1715 bool account_locked;
1716 } LEX_ALTER;
1717
1718 /*
1719 This structure holds the specifications related to
1720 mysql user and the associated auth details.
1721 */
1722 typedef struct st_lex_user {
1723 LEX_CSTRING user;
1724 LEX_CSTRING host;
1725 LEX_CSTRING plugin;
1726 LEX_CSTRING auth;
1727 /*
1728 The following flags are indicators for the SQL syntax used while
1729 parsing CREATE/ALTER user. While other members are self-explanatory,
1730 'uses_authentication_string_clause' signifies if the password is in
1731 hash form (if the var was set to true) or not.
1732 */
1733 bool uses_identified_by_clause;
1734 bool uses_identified_with_clause;
1735 bool uses_authentication_string_clause;
1736 bool uses_identified_by_password_clause;
1737 LEX_ALTER alter_status;
1738 } LEX_USER;
1739
1740
1741 /**
1742 Derive type of metadata lock to be requested for table used by a DML
1743 statement from the type of THR_LOCK lock requested for this table.
1744 */
1745
mdl_type_for_dml(enum thr_lock_type lock_type)1746 inline enum enum_mdl_type mdl_type_for_dml(enum thr_lock_type lock_type)
1747 {
1748 return lock_type >= TL_WRITE_ALLOW_WRITE ?
1749 (lock_type == TL_WRITE_LOW_PRIORITY ?
1750 MDL_SHARED_WRITE_LOW_PRIO : MDL_SHARED_WRITE) :
1751 MDL_SHARED_READ;
1752 }
1753
1754 /**
1755 Type of table which can be open for an element of table list.
1756 */
1757
1758 enum enum_open_type
1759 {
1760 OT_TEMPORARY_OR_BASE= 0, OT_TEMPORARY_ONLY, OT_BASE_ONLY
1761 };
1762
1763 /**
1764 This structure is used to keep info about possible key for the result table
1765 of a derived table/view.
1766 The 'referenced_by' is the table map of tables to which this possible
1767 key corresponds.
1768 The 'used_field' is a map of fields of which this key consists of.
1769 See also the comment for the TABLE_LIST::update_derived_keys function.
1770 */
1771
1772 class Derived_key: public Sql_alloc {
1773 public:
1774 table_map referenced_by;
1775 Field_map used_fields;
1776 };
1777
1778
1779 /*
1780 Table reference in the FROM clause.
1781
1782 These table references can be of several types that correspond to
1783 different SQL elements. Below we list all types of TABLE_LISTs with
1784 the necessary conditions to determine when a TABLE_LIST instance
1785 belongs to a certain type.
1786
1787 1) table (TABLE_LIST::view == NULL)
1788 - base table
1789 (TABLE_LIST::derived == NULL)
1790 - subquery - TABLE_LIST::table is a temp table
1791 (TABLE_LIST::derived != NULL)
1792 - information schema table
1793 (TABLE_LIST::schema_table != NULL)
1794 NOTICE: for schema tables TABLE_LIST::field_translation may be != NULL
1795 2) view (TABLE_LIST::view != NULL)
1796 - merge (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_MERGE)
1797 also (TABLE_LIST::field_translation != NULL)
1798 - temptable(TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_TEMPTABLE)
1799 also (TABLE_LIST::field_translation == NULL)
1800 3) nested table reference (TABLE_LIST::nested_join != NULL)
1801 - table sequence - e.g. (t1, t2, t3)
1802 TODO: how to distinguish from a JOIN?
1803 - general JOIN
1804 TODO: how to distinguish from a table sequence?
1805 - NATURAL JOIN
1806 (TABLE_LIST::natural_join != NULL)
1807 - JOIN ... USING
1808 (TABLE_LIST::join_using_fields != NULL)
1809 - semi-join
1810 ;
1811 */
1812
1813 struct TABLE_LIST
1814 {
TABLE_LISTTABLE_LIST1815 TABLE_LIST() { memset(this, 0, sizeof(*this)); }
1816
1817 /**
1818 Prepare TABLE_LIST that consists of one table instance to use in
1819 simple_open_and_lock_tables
1820 */
init_one_tableTABLE_LIST1821 inline void init_one_table(const char *db_name_arg,
1822 size_t db_length_arg,
1823 const char *table_name_arg,
1824 size_t table_name_length_arg,
1825 const char *alias_arg,
1826 enum thr_lock_type lock_type_arg,
1827 enum enum_mdl_type mdl_type_arg)
1828 {
1829 new (this) TABLE_LIST;
1830 m_map= 1;
1831 db= (char*) db_name_arg;
1832 db_length= db_length_arg;
1833 table_name= (char*) table_name_arg;
1834 table_name_length= table_name_length_arg;
1835 alias= (char*) alias_arg;
1836 lock_type= lock_type_arg;
1837 MDL_REQUEST_INIT(&mdl_request,
1838 MDL_key::TABLE, db, table_name,
1839 mdl_type_arg,
1840 MDL_TRANSACTION);
1841 callback_func= 0;
1842 opt_hints_table= NULL;
1843 opt_hints_qb= NULL;
1844 }
1845
init_one_tableTABLE_LIST1846 inline void init_one_table(const char *db_name_arg,
1847 size_t db_length_arg,
1848 const char *table_name_arg,
1849 size_t table_name_length_arg,
1850 const char *alias_arg,
1851 enum thr_lock_type lock_type_arg)
1852 {
1853 init_one_table(db_name_arg, db_length_arg,
1854 table_name_arg, table_name_length_arg,
1855 alias_arg, lock_type_arg,
1856 mdl_type_for_dml(lock_type_arg));
1857 }
1858
1859 /// Create a TABLE_LIST object representing a nested join
1860 static TABLE_LIST *new_nested_join(MEM_ROOT *allocator,
1861 const char *alias,
1862 TABLE_LIST *embedding,
1863 List<TABLE_LIST> *belongs_to,
1864 class st_select_lex *select);
1865
join_cond_refTABLE_LIST1866 Item **join_cond_ref() { return &m_join_cond; }
join_condTABLE_LIST1867 Item *join_cond() const { return m_join_cond; }
set_join_condTABLE_LIST1868 void set_join_cond(Item *val)
1869 {
1870 // If optimization has started, it's too late to change m_join_cond.
1871 assert(m_join_cond_optim == NULL ||
1872 m_join_cond_optim == (Item*)1);
1873 m_join_cond= val;
1874 }
join_cond_optimTABLE_LIST1875 Item *join_cond_optim() const { return m_join_cond_optim; }
set_join_cond_optimTABLE_LIST1876 void set_join_cond_optim(Item *cond)
1877 {
1878 /*
1879 Either we are setting to "empty", or there must pre-exist a
1880 permanent condition.
1881 */
1882 assert(cond == NULL || cond == (Item*)1 ||
1883 m_join_cond != NULL);
1884 m_join_cond_optim= cond;
1885 }
join_cond_optim_refTABLE_LIST1886 Item **join_cond_optim_ref() { return &m_join_cond_optim; }
1887
1888 /// Get the semi-join condition for a semi-join nest, NULL otherwise
sj_condTABLE_LIST1889 Item *sj_cond() const { return m_sj_cond; }
1890
1891 /// Set the semi-join condition for a semi-join nest
set_sj_condTABLE_LIST1892 void set_sj_cond(Item *cond)
1893 {
1894 assert(m_sj_cond == NULL);
1895 m_sj_cond= cond;
1896 }
1897
1898 /// Merge tables from a query block into a nested join structure
1899 bool merge_underlying_tables(class st_select_lex *select);
1900
1901 /// Reset table
1902 void reset();
1903
1904 void calc_md5(char *buffer);
1905
1906 /// Evaluate the check option of a view
1907 int view_check_option(THD *thd) const;
1908
1909 /// Cleanup field translations for a view
1910 void cleanup_items();
1911
1912 /**
1913 Check whether the table is a placeholder, ie a derived table, a view or
1914 a schema table.
1915 A table is also considered to be a placeholder if it does not have a
1916 TABLE object for some other reason.
1917 */
is_placeholderTABLE_LIST1918 bool is_placeholder() const
1919 {
1920 return is_view_or_derived() || schema_table || !table;
1921 }
1922
1923 /// Produce a textual identification of this object
1924 void print(THD *thd, String *str, enum_query_type query_type) const;
1925
1926 /// Check which single table inside a view that matches a table map
1927 bool check_single_table(TABLE_LIST **table_ref, table_map map);
1928
1929 /// Allocate a buffer for inserted column values
1930 bool set_insert_values(MEM_ROOT *mem_root);
1931
1932 TABLE_LIST *first_leaf_for_name_resolution();
1933 TABLE_LIST *last_leaf_for_name_resolution();
1934 bool is_leaf_for_name_resolution() const;
1935
1936 /// Return the outermost view this table belongs to, or itself
top_tableTABLE_LIST1937 inline const TABLE_LIST *top_table() const
1938 { return belong_to_view ? belong_to_view : this; }
1939
top_tableTABLE_LIST1940 inline TABLE_LIST *top_table()
1941 {
1942 return
1943 const_cast<TABLE_LIST*>(const_cast<const TABLE_LIST*>(this)->top_table());
1944 }
1945
1946 /// Prepare check option for a view
1947 bool prepare_check_option(THD *thd, bool is_cascaded= false);
1948
1949 /// Merge WHERE condition of view or derived table into outer query
1950 bool merge_where(THD *thd);
1951
1952 /// Prepare replace filter for a view (used for REPLACE command)
1953 bool prepare_replace_filter(THD *thd);
1954
1955 /// Return true if this represents a named view
is_viewTABLE_LIST1956 bool is_view() const
1957 {
1958 return view != NULL;
1959 }
1960
1961 /// Return true if this represents a derived table (an unnamed view)
is_derivedTABLE_LIST1962 bool is_derived() const
1963 {
1964 return derived != NULL && view == NULL;
1965 }
1966
1967 /// Return true if this represents a named view or a derived table
is_view_or_derivedTABLE_LIST1968 bool is_view_or_derived() const
1969 {
1970 return derived != NULL;
1971 }
1972
1973 /// Return true if view or derived table and can be merged
1974 bool is_mergeable() const;
1975
1976 /**
1977 @returns true if materializable table contains one or zero rows.
1978
1979 Returning true implies that the table is materialized during optimization,
1980 so it need not be optimized during execution.
1981 */
1982 bool materializable_is_const() const;
1983
1984 /// Return true if this is a derived table or view that is merged
is_mergedTABLE_LIST1985 bool is_merged() const
1986 {
1987 return effective_algorithm == VIEW_ALGORITHM_MERGE;
1988 }
1989
1990 /// Set table to be merged
set_mergedTABLE_LIST1991 void set_merged()
1992 {
1993 assert(effective_algorithm == VIEW_ALGORITHM_UNDEFINED);
1994 effective_algorithm= VIEW_ALGORITHM_MERGE;
1995 }
1996
1997 /// Return true if this is a materializable derived table/view
uses_materializationTABLE_LIST1998 bool uses_materialization() const
1999 {
2000 return effective_algorithm == VIEW_ALGORITHM_TEMPTABLE;
2001 }
2002
2003 /// Set table to be materialized
set_uses_materializationTABLE_LIST2004 void set_uses_materialization()
2005 {
2006 // @todo We should do this only once, but currently we cannot:
2007 //assert(effective_algorithm == VIEW_ALGORITHM_UNDEFINED);
2008 assert(effective_algorithm != VIEW_ALGORITHM_MERGE);
2009 effective_algorithm= VIEW_ALGORITHM_TEMPTABLE;
2010 }
2011
2012 /// Return true if table is updatable
is_updatableTABLE_LIST2013 bool is_updatable() const { return m_updatable; }
2014
2015 /// Set table as updatable. (per default, a table is non-updatable)
set_updatableTABLE_LIST2016 void set_updatable() { m_updatable= true; }
2017
2018 /// Return true if table is insertable-into
is_insertableTABLE_LIST2019 bool is_insertable() const { return m_insertable; }
2020
2021 /// Set table as insertable-into. (per default, a table is not insertable)
set_insertableTABLE_LIST2022 void set_insertable() { m_insertable= true; }
2023
2024 /**
2025 Return true if this is a view or derived table that is defined over
2026 more than one base table, and false otherwise.
2027 */
is_multiple_tablesTABLE_LIST2028 bool is_multiple_tables() const
2029 {
2030 if (is_view_or_derived())
2031 {
2032 assert(is_merged()); // Cannot be a materialized view
2033 return leaf_tables_count() > 1;
2034 }
2035 else
2036 {
2037 assert(nested_join == NULL); // Must be a base table
2038 return false;
2039 }
2040 }
2041
2042 /// Return no. of base tables a merged view or derived table is defined over.
2043 uint leaf_tables_count() const;
2044
2045 /// Return first leaf table of a base table or a view/derived table
first_leaf_tableTABLE_LIST2046 TABLE_LIST *first_leaf_table()
2047 {
2048 TABLE_LIST *tr= this;
2049 while (tr->merge_underlying_list)
2050 tr= tr->merge_underlying_list;
2051 return tr;
2052 }
2053
2054 /// Return any leaf table that is not an inner table of an outer join
2055 /// @todo when WL#6570 is implemented, replace with first_leaf_table()
any_outer_leaf_tableTABLE_LIST2056 TABLE_LIST *any_outer_leaf_table()
2057 {
2058 TABLE_LIST *tr= this;
2059 while (tr->merge_underlying_list)
2060 {
2061 tr= tr->merge_underlying_list;
2062 /*
2063 "while" is used, however, an "if" might be sufficient since there is
2064 no more than one inner table in a join nest (with outer_join true).
2065 */
2066 while (tr->outer_join)
2067 tr= tr->next_local;
2068 }
2069 return tr;
2070 }
2071 /**
2072 Set the LEX object of a view (will also define this as a view).
2073 @note: The value 1 is used to indicate a view but without a valid
2074 query object. Use only if the LEX object is not going to
2075 be used in later processing.
2076 */
set_view_queryTABLE_LIST2077 void set_view_query(LEX *lex)
2078 {
2079 view= lex;
2080 }
2081
2082 /// Return the valid LEX object for a view.
view_queryTABLE_LIST2083 LEX *view_query() const
2084 {
2085 assert(view != NULL && view != (LEX *)1);
2086 return view;
2087 }
2088
2089 /**
2090 Set the query expression of a derived table or view.
2091 (Will also define this as a derived table, unless it is a named view.)
2092 */
set_derived_unitTABLE_LIST2093 void set_derived_unit(st_select_lex_unit *query_expr)
2094 {
2095 derived= query_expr;
2096 }
2097
2098 /// Return the query expression of a derived table or view.
derived_unitTABLE_LIST2099 st_select_lex_unit *derived_unit() const
2100 {
2101 assert(derived);
2102 return derived;
2103 }
2104
2105 /// Set temporary name from underlying temporary table:
set_name_temporaryTABLE_LIST2106 void set_name_temporary()
2107 {
2108 assert(is_view_or_derived() && uses_materialization());
2109 table_name= table->s->table_name.str;
2110 table_name_length= table->s->table_name.length;
2111 db= (char *)"";
2112 db_length= 0;
2113 }
2114
2115 /// Reset original name for temporary table.
reset_name_temporaryTABLE_LIST2116 void reset_name_temporary()
2117 {
2118 assert(is_view_or_derived() && uses_materialization());
2119 assert(db != view_db.str && table_name != view_name.str);
2120 if (is_view())
2121 {
2122 db= view_db.str;
2123 db_length= view_db.length;
2124 }
2125 table_name= view_name.str;
2126 table_name_length= view_name.length;
2127 }
2128
2129 /// Resolve a derived table or view reference
2130 bool resolve_derived(THD *thd, bool apply_semijoin);
2131
2132 /// Optimize the query expression representing a derived table/view
2133 bool optimize_derived(THD *thd);
2134
2135 /// Create result table for a materialized derived table/view
2136 bool create_derived(THD *thd);
2137
2138 /// Materialize derived table
2139 bool materialize_derived(THD *thd);
2140
2141 /// Clean up the query expression for a materialized derived table
2142 bool cleanup_derived();
2143
2144 /// Set wanted privilege for subsequent column privilege checking
2145 void set_want_privilege(ulong want_privilege);
2146
2147 /// Prepare security context for a view
2148 bool prepare_security(THD *thd);
2149
2150 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2151 Security_context *find_view_security_context(THD *thd);
2152 bool prepare_view_securety_context(THD *thd);
2153 #endif
2154
2155 /// Cleanup for re-execution in a prepared statement or a stored procedure.
2156 void reinit_before_use(THD *thd);
2157
2158 /**
2159 Compiles the tagged hints list and fills up TABLE::keys_in_use_for_query,
2160 TABLE::keys_in_use_for_group_by, TABLE::keys_in_use_for_order_by,
2161 TABLE::force_index and TABLE::covering_keys.
2162 */
2163 bool process_index_hints(TABLE *table);
2164
2165 /**
2166 Compare the version of metadata from the previous execution
2167 (if any) with values obtained from the current table
2168 definition cache element.
2169
2170 @sa check_and_update_table_version()
2171 */
is_table_ref_id_equalTABLE_LIST2172 bool is_table_ref_id_equal(TABLE_SHARE *s) const
2173 {
2174 return (m_table_ref_type == s->get_table_ref_type() &&
2175 m_table_ref_version == s->get_table_ref_version());
2176 }
2177
2178 /**
2179 Record the value of metadata version of the corresponding
2180 table definition cache element in this parse tree node.
2181
2182 @sa check_and_update_table_version()
2183 */
set_table_ref_idTABLE_LIST2184 void set_table_ref_id(TABLE_SHARE *s)
2185 { set_table_ref_id(s->get_table_ref_type(), s->get_table_ref_version()); }
2186
set_table_ref_idTABLE_LIST2187 void set_table_ref_id(enum_table_ref_type table_ref_type_arg,
2188 ulonglong table_ref_version_arg)
2189 {
2190 m_table_ref_type= table_ref_type_arg;
2191 m_table_ref_version= table_ref_version_arg;
2192 }
2193
2194 /// returns query block id for derived table, and zero if not derived.
2195 uint query_block_id() const;
2196
2197 /**
2198 @brief Returns the name of the database that the referenced table belongs
2199 to.
2200 */
get_db_nameTABLE_LIST2201 const char *get_db_name() const { return view != NULL ? view_db.str : db; }
2202
2203 /**
2204 @brief Returns the name of the table that this TABLE_LIST represents.
2205
2206 @details The unqualified table name or view name for a table or view,
2207 respectively.
2208 */
get_table_nameTABLE_LIST2209 const char *get_table_name() const
2210 {
2211 return view != NULL ? view_name.str : table_name;
2212 }
2213 int fetch_number_of_rows();
2214 bool update_derived_keys(Field*, Item**, uint);
2215 bool generate_keys();
2216
2217 /// Setup a derived table to use materialization
2218 bool setup_materialized_derived(THD *thd);
2219
2220 bool create_field_translation(THD *thd);
2221
2222 /**
2223 @brief Returns the outer join nest that this TABLE_LIST belongs to, if any.
2224
2225 @details There are two kinds of join nests, outer-join nests and semi-join
2226 nests. This function returns non-NULL in the following cases:
2227 @li 1. If this table/nest is embedded in a nest and this nest IS NOT a
2228 semi-join nest. (In other words, it is an outer-join nest.)
2229 @li 2. If this table/nest is embedded in a nest and this nest IS a
2230 semi-join nest, but this semi-join nest is embedded in another
2231 nest. (This other nest will be an outer-join nest, since all inner
2232 joined nested semi-join nests have been merged in
2233 @c simplify_joins() ).
2234 Note: This function assumes that @c simplify_joins() has been performed.
2235 Before that, join nests will be present for all types of join.
2236
2237 @return outer join nest, or NULL if none.
2238 */
2239
outer_join_nestTABLE_LIST2240 TABLE_LIST *outer_join_nest() const
2241 {
2242 if (!embedding)
2243 return NULL;
2244 if (embedding->sj_cond())
2245 return embedding->embedding;
2246 return embedding;
2247 }
2248 /**
2249 Return true if this table is an inner table of some outer join.
2250
2251 Examine all the embedding join nests of the table.
2252 @note This function works also before redundant join nests have been
2253 eliminated.
2254
2255 @return true if table is an inner table of some outer join, false otherwise.
2256 */
2257
is_inner_table_of_outer_joinTABLE_LIST2258 bool is_inner_table_of_outer_join() const
2259 {
2260 if (outer_join)
2261 return true;
2262 for (TABLE_LIST *emb= embedding; emb; emb= emb->embedding)
2263 {
2264 if (emb->outer_join)
2265 return true;
2266 }
2267 return false;
2268 }
2269
2270 /**
2271 Return the base table entry of an updatable table.
2272 In DELETE and UPDATE, a view used as a target table must be mergeable,
2273 updatable and defined over a single table.
2274 */
updatable_base_tableTABLE_LIST2275 TABLE_LIST *updatable_base_table()
2276 {
2277 TABLE_LIST *tbl= this;
2278 assert(tbl->is_updatable() && !tbl->is_multiple_tables());
2279 while (tbl->is_view_or_derived())
2280 {
2281 tbl= tbl->merge_underlying_list;
2282 assert(tbl->is_updatable() && !tbl->is_multiple_tables());
2283 }
2284 return tbl;
2285 }
2286
2287
2288 /**
2289 Set granted privileges for a table.
2290
2291 Can be used when generating temporary tables that are also used in
2292 resolver process, such as when generating a UNION table
2293
2294 @param privilege Privileges granted for this table.
2295 */
set_privilegesTABLE_LIST2296 void set_privileges(ulong privilege)
2297 {
2298 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2299 grant.privilege|= privilege;
2300 if (table)
2301 table->grant.privilege|= privilege;
2302 #endif
2303 }
2304 /*
2305 List of tables local to a subquery or the top-level SELECT (used by
2306 SQL_I_List). Considers views as leaves (unlike 'next_leaf' below).
2307 Created at parse time in st_select_lex::add_table_to_list() ->
2308 table_list.link_in_list().
2309 */
2310 TABLE_LIST *next_local;
2311 /* link in a global list of all queries tables */
2312 TABLE_LIST *next_global, **prev_global;
2313 const char *db, *table_name, *alias;
2314 /*
2315 Target tablespace name: When creating or altering tables, this
2316 member points to the tablespace_name in the HA_CREATE_INFO struct.
2317 */
2318 LEX_CSTRING target_tablespace_name;
2319 char *schema_table_name;
2320 char *option; /* Used by cache index */
2321
2322 /** Table level optimizer hints for this table. */
2323 Opt_hints_table *opt_hints_table;
2324 /* Hints for query block of this table. */
2325 Opt_hints_qb *opt_hints_qb;
2326
2327 private:
2328 /**
2329 The members below must be kept aligned so that (1 << m_tableno) == m_map.
2330 A table that takes part in a join operation must be assigned a unique
2331 table number.
2332 */
2333 uint m_tableno; ///< Table number within query block
2334 table_map m_map; ///< Table map, derived from m_tableno
2335 /**
2336 If this table or join nest is the Y in "X [LEFT] JOIN Y ON C", this
2337 member points to C. May also be generated from JOIN ... USING clause.
2338 It may be modified only by permanent transformations (permanent = done
2339 once for all executions of a prepared statement).
2340 */
2341 Item *m_join_cond;
2342 Item *m_sj_cond; ///< Synthesized semijoin condition
2343 public:
2344 /*
2345 (Valid only for semi-join nests) Bitmap of tables that are within the
2346 semi-join (this is different from bitmap of all nest's children because
2347 tables that were pulled out of the semi-join nest remain listed as
2348 nest's children).
2349 */
2350 table_map sj_inner_tables;
2351
2352 /*
2353 During parsing - left operand of NATURAL/USING join where 'this' is
2354 the right operand. After parsing (this->natural_join == this) iff
2355 'this' represents a NATURAL or USING join operation. Thus after
2356 parsing 'this' is a NATURAL/USING join iff (natural_join != NULL).
2357 */
2358 TABLE_LIST *natural_join;
2359 /*
2360 True if 'this' represents a nested join that is a NATURAL JOIN.
2361 For one of the operands of 'this', the member 'natural_join' points
2362 to the other operand of 'this'.
2363 */
2364 bool is_natural_join;
2365 /* Field names in a USING clause for JOIN ... USING. */
2366 List<String> *join_using_fields;
2367 /*
2368 Explicitly store the result columns of either a NATURAL/USING join or
2369 an operand of such a join.
2370 */
2371 List<Natural_join_column> *join_columns;
2372 /* TRUE if join_columns contains all columns of this table reference. */
2373 bool is_join_columns_complete;
2374
2375 /*
2376 List of nodes in a nested join tree, that should be considered as
2377 leaves with respect to name resolution. The leaves are: views,
2378 top-most nodes representing NATURAL/USING joins, subqueries, and
2379 base tables. All of these TABLE_LIST instances contain a
2380 materialized list of columns. The list is local to a subquery.
2381 */
2382 TABLE_LIST *next_name_resolution_table;
2383 /* Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */
2384 List<Index_hint> *index_hints;
2385 TABLE *table; /* opened table */
2386 Table_id table_id; /* table id (from binlog) for opened table */
2387 /*
2388 Query_result for derived table to pass it from table creation to table
2389 filling procedure
2390 */
2391 Query_result_union *derived_result;
2392 /*
2393 Reference from aux_tables to local list entry of main select of
2394 multi-delete statement:
2395 delete t1 from t2,t1 where t1.a<'B' and t2.b=t1.b;
2396 here it will be reference of first occurrence of t1 to second (as you
2397 can see this lists can't be merged)
2398 */
2399 TABLE_LIST *correspondent_table;
2400 private:
2401 /**
2402 This field is set to non-null for derived tables and views. It points
2403 to the SELECT_LEX_UNIT representing the derived table/view.
2404 E.g. for a query
2405
2406 @verbatim SELECT * FROM (SELECT a FROM t1) b @endverbatim
2407
2408 @note Inside views, a subquery in the @c FROM clause is not allowed.
2409 */
2410 st_select_lex_unit *derived; /* SELECT_LEX_UNIT of derived table */
2411
2412 public:
2413 ST_SCHEMA_TABLE *schema_table; /* Information_schema table */
2414 st_select_lex *schema_select_lex;
2415 /*
2416 True when the view field translation table is used to convert
2417 schema table fields for backwards compatibility with SHOW command.
2418 */
2419 bool schema_table_reformed;
2420 Temp_table_param *schema_table_param;
2421 /* link to select_lex where this table was used */
2422 st_select_lex *select_lex;
2423
2424 private:
2425 LEX *view; /* link on VIEW lex for merging */
2426
2427 public:
2428 /// Array of selected expressions from a derived table or view.
2429 Field_translator *field_translation;
2430
2431 /// pointer to element after last one in translation table above
2432 Field_translator *field_translation_end;
2433 /*
2434 List (based on next_local) of underlying tables of this view. I.e. it
2435 does not include the tables of subqueries used in the view. Is set only
2436 for merged views.
2437 */
2438 TABLE_LIST *merge_underlying_list;
2439 /*
2440 - 0 for base tables
2441 - in case of the view it is the list of all (not only underlying
2442 tables but also used in subquery ones) tables of the view.
2443 */
2444 List<TABLE_LIST> *view_tables;
2445 /* most upper view this table belongs to */
2446 TABLE_LIST *belong_to_view;
2447 /*
2448 The view directly referencing this table
2449 (non-zero only for merged underlying tables of a view).
2450 */
2451 TABLE_LIST *referencing_view;
2452 /* Ptr to parent MERGE table list item. See top comment in ha_myisammrg.cc */
2453 TABLE_LIST *parent_l;
2454 /*
2455 Security context (non-zero only for tables which belong
2456 to view with SQL SECURITY DEFINER)
2457 */
2458 Security_context *security_ctx;
2459 /*
2460 This view security context (non-zero only for views with
2461 SQL SECURITY DEFINER)
2462 */
2463 Security_context *view_sctx;
2464 /*
2465 List of all base tables local to a subquery including all view
2466 tables. Unlike 'next_local', this in this list views are *not*
2467 leaves. Created in setup_tables() -> make_leaf_tables().
2468 */
2469 bool allowed_show;
2470 TABLE_LIST *next_leaf;
2471 Item *derived_where_cond; ///< WHERE condition from derived table
2472 Item *check_option; ///< WITH CHECK OPTION condition
2473 Item *replace_filter; ///< Filter for REPLACE command
2474 LEX_STRING select_stmt; ///< text of (CREATE/SELECT) statement
2475 LEX_STRING md5; ///< md5 of query text
2476 LEX_STRING source; ///< source of CREATE VIEW
2477 LEX_CSTRING view_db; ///< saved view database
2478 LEX_CSTRING view_name; ///< saved view name
2479 LEX_STRING timestamp; ///< GMT time stamp of last operation
2480 st_lex_user definer; ///< definer of view
2481 ulonglong file_version; ///< version of file's field set
2482 /**
2483 @note: This field is currently not reliable when read from dictionary:
2484 If an underlying view is changed, updatable_view is not changed,
2485 due to lack of dependency checking in dictionary implementation.
2486 Prefer to use is_updatable() during preparation and optimization.
2487 */
2488 ulonglong updatable_view; ///< VIEW can be updated
2489 /**
2490 @brief The declared algorithm, if this is a view.
2491 @details One of
2492 - VIEW_ALGORITHM_UNDEFINED
2493 - VIEW_ALGORITHM_TEMPTABLE
2494 - VIEW_ALGORITHM_MERGE
2495 @to do Replace with an enum
2496 */
2497 ulonglong algorithm;
2498 ulonglong view_suid; ///< view is suid (TRUE by default)
2499 ulonglong with_check; ///< WITH CHECK OPTION
2500
2501 private:
2502 /// The view algorithm that is actually used, if this is a view.
2503 enum_view_algorithm effective_algorithm;
2504 public:
2505 GRANT_INFO grant;
2506 /* data need by some engines in query cache*/
2507 ulonglong engine_data;
2508 /* call back function for asking handler about caching in query cache */
2509 qc_engine_callback callback_func;
2510 thr_lock_type lock_type;
2511 uint outer_join; /* Which join type */
2512 uint shared; /* Used in multi-upd */
2513 size_t db_length;
2514 size_t table_name_length;
2515 private:
2516 bool m_updatable; /* VIEW/TABLE can be updated */
2517 bool m_insertable; /* VIEW/TABLE can be inserted into */
2518 public:
2519 bool straight; /* optimize with prev table */
2520 bool updating; /* for replicate-do/ignore table */
2521 bool force_index; /* prefer index over table scan */
2522 bool ignore_leaves; /* preload only non-leaf nodes */
2523 table_map dep_tables; /* tables the table depends on */
2524 table_map on_expr_dep_tables; /* tables on expression depends on */
2525 struct st_nested_join *nested_join; /* if the element is a nested join */
2526 TABLE_LIST *embedding; /* nested join containing the table */
2527 List<TABLE_LIST> *join_list;/* join list the table belongs to */
2528 bool cacheable_table; /* stop PS caching */
2529 /* used in multi-upd/views privilege check */
2530 bool table_in_first_from_clause;
2531 /**
2532 Specifies which kind of table should be open for this element
2533 of table list.
2534 */
2535 enum enum_open_type open_type;
2536 /* TRUE if this merged view contain auto_increment field */
2537 bool contain_auto_increment;
2538 /// TRUE <=> VIEW CHECK OPTION condition is processed (also for prep. stmts)
2539 bool check_option_processed;
2540 /// TRUE <=> Filter condition is processed
2541 bool replace_filter_processed;
2542 /* FRMTYPE_ERROR if any type is acceptable */
2543 enum frm_type_enum required_type;
2544 char timestamp_buffer[20]; /* buffer for timestamp (19+1) */
2545 /*
2546 This TABLE_LIST object is just placeholder for prelocking, it will be
2547 used for implicit LOCK TABLES only and won't be used in real statement.
2548 */
2549 bool prelocking_placeholder;
2550 /**
2551 Indicates that if TABLE_LIST object corresponds to the table/view
2552 which requires special handling.
2553 */
2554 enum
2555 {
2556 /* Normal open. */
2557 OPEN_NORMAL= 0,
2558 /* Associate a table share only if the the table exists. */
2559 OPEN_IF_EXISTS,
2560 /*
2561 Associate a table share only if the the table exists.
2562 Also upgrade metadata lock to exclusive if table doesn't exist.
2563 */
2564 OPEN_FOR_CREATE,
2565 /* Don't associate a table share. */
2566 OPEN_STUB
2567 } open_strategy;
2568 bool internal_tmp_table;
2569 /** TRUE if an alias for this table was specified in the SQL. */
2570 bool is_alias;
2571 /** TRUE if the table is referred to in the statement using a fully
2572 qualified name (<db_name>.<table_name>).
2573 */
2574 bool is_fqtn;
2575
2576
2577 /* View creation context. */
2578
2579 View_creation_ctx *view_creation_ctx;
2580
2581 /*
2582 Attributes to save/load view creation context in/from frm-file.
2583
2584 Ther are required only to be able to use existing parser to load
2585 view-definition file. As soon as the parser parsed the file, view
2586 creation context is initialized and the attributes become redundant.
2587
2588 These attributes MUST NOT be used for any purposes but the parsing.
2589 */
2590
2591 LEX_STRING view_client_cs_name;
2592 LEX_STRING view_connection_cl_name;
2593
2594 /*
2595 View definition (SELECT-statement) in the UTF-form.
2596 */
2597
2598 LEX_STRING view_body_utf8;
2599
2600 /* End of view definition context. */
2601 /* List of possible keys. Valid only for materialized derived tables/views. */
2602 List<Derived_key> derived_key_list;
2603
2604 /**
2605 Indicates what triggers we need to pre-load for this TABLE_LIST
2606 when opening an associated TABLE. This is filled after
2607 the parsed tree is created.
2608 */
2609 uint8 trg_event_map;
2610 uint i_s_requested_object;
2611 bool has_db_lookup_value;
2612 bool has_table_lookup_value;
2613 uint table_open_method;
2614 enum enum_schema_table_state schema_table_state;
2615
2616 MDL_request mdl_request;
2617
2618 /// if true, EXPLAIN can't explain view due to insufficient rights.
2619 bool view_no_explain;
2620
2621 /* List to carry partition names from PARTITION (...) clause in statement */
2622 List<String> *partition_names;
2623
2624 /// Set table number
set_tablenoTABLE_LIST2625 void set_tableno(uint tableno)
2626 {
2627 assert(tableno < MAX_TABLES);
2628 m_tableno= tableno;
2629 m_map= (table_map)1 << tableno;
2630 }
2631 /// Return table number
tablenoTABLE_LIST2632 uint tableno() const { return m_tableno; }
2633
2634 /// Return table map derived from table number
mapTABLE_LIST2635 table_map map() const
2636 {
2637 assert(((table_map)1 << m_tableno) == m_map);
2638 return m_map;
2639 }
2640
2641 private:
2642 /*
2643 A group of members set and used only during JOIN::optimize().
2644 */
2645 /**
2646 Optimized copy of m_join_cond (valid for one single
2647 execution). Initialized by SELECT_LEX::get_optimizable_conditions().
2648 @todo it would be good to reset it in reinit_before_use(), if
2649 reinit_stmt_before_use() had a loop including join nests.
2650 */
2651 Item *m_join_cond_optim;
2652 public:
2653
2654 COND_EQUAL *cond_equal; ///< Used with outer join
2655 /// true <=> this table is a const one and was optimized away.
2656 bool optimized_away;
2657 /**
2658 true <=> all possible keys for a derived table were collected and
2659 could be re-used while statement re-execution.
2660 */
2661 bool derived_keys_ready;
2662 // End of group for optimization
2663
2664 private:
2665 /** See comments for set_metadata_id() */
2666 enum enum_table_ref_type m_table_ref_type;
2667 /** See comments for TABLE_SHARE::get_table_ref_version() */
2668 ulonglong m_table_ref_version;
2669 };
2670
2671
2672 /*
2673 Iterator over the fields of a generic table reference.
2674 */
2675
2676 class Field_iterator: public Sql_alloc
2677 {
2678 public:
Field_iterator()2679 Field_iterator() {} /* Remove gcc warning */
~Field_iterator()2680 virtual ~Field_iterator() {}
2681 virtual void set(TABLE_LIST *)= 0;
2682 virtual void next()= 0;
2683 virtual bool end_of_fields()= 0; /* Return 1 at end of list */
2684 virtual const char *name()= 0;
2685 virtual Item *create_item(THD *)= 0;
2686 virtual Field *field()= 0;
2687 };
2688
2689
2690 /*
2691 Iterator over the fields of a base table, view with temporary
2692 table, or subquery.
2693 */
2694
2695 class Field_iterator_table: public Field_iterator
2696 {
2697 Field **ptr;
2698 public:
Field_iterator_table()2699 Field_iterator_table() :ptr(0) {}
set(TABLE_LIST * table)2700 void set(TABLE_LIST *table) { ptr= table->table->field; }
set_table(TABLE * table)2701 void set_table(TABLE *table) { ptr= table->field; }
next()2702 void next() { ptr++; }
end_of_fields()2703 bool end_of_fields() { return *ptr == 0; }
2704 const char *name();
2705 Item *create_item(THD *thd);
field()2706 Field *field() { return *ptr; }
2707 };
2708
2709
2710 /**
2711 Iterator over the fields of a merged derived table or view.
2712 */
2713
2714 class Field_iterator_view: public Field_iterator
2715 {
2716 Field_translator *ptr, *array_end;
2717 TABLE_LIST *view;
2718 public:
Field_iterator_view()2719 Field_iterator_view() :ptr(0), array_end(0) {}
2720 void set(TABLE_LIST *table);
next()2721 void next() { ptr++; }
end_of_fields()2722 bool end_of_fields() { return ptr == array_end; }
2723 const char *name();
2724 Item *create_item(THD *thd);
item_ptr()2725 Item **item_ptr() {return &ptr->item; }
field()2726 Field *field() { return 0; }
item()2727 inline Item *item() { return ptr->item; }
field_translator()2728 Field_translator *field_translator() { return ptr; }
2729 };
2730
2731
2732 /*
2733 Field_iterator interface to the list of materialized fields of a
2734 NATURAL/USING join.
2735 */
2736
2737 class Field_iterator_natural_join: public Field_iterator
2738 {
2739 List_iterator_fast<Natural_join_column> column_ref_it;
2740 Natural_join_column *cur_column_ref;
2741 public:
Field_iterator_natural_join()2742 Field_iterator_natural_join() :cur_column_ref(NULL) {}
~Field_iterator_natural_join()2743 ~Field_iterator_natural_join() {}
2744 void set(TABLE_LIST *table);
2745 void next();
end_of_fields()2746 bool end_of_fields() { return !cur_column_ref; }
name()2747 const char *name() { return cur_column_ref->name(); }
create_item(THD * thd)2748 Item *create_item(THD *thd) { return cur_column_ref->create_item(thd); }
field()2749 Field *field() { return cur_column_ref->field(); }
column_ref()2750 Natural_join_column *column_ref() { return cur_column_ref; }
2751 };
2752
2753
2754 /*
2755 Generic iterator over the fields of an arbitrary table reference.
2756
2757 DESCRIPTION
2758 This class unifies the various ways of iterating over the columns
2759 of a table reference depending on the type of SQL entity it
2760 represents. If such an entity represents a nested table reference,
2761 this iterator encapsulates the iteration over the columns of the
2762 members of the table reference.
2763
2764 IMPLEMENTATION
2765 The implementation assumes that all underlying NATURAL/USING table
2766 references already contain their result columns and are linked into
2767 the list TABLE_LIST::next_name_resolution_table.
2768 */
2769
2770 class Field_iterator_table_ref: public Field_iterator
2771 {
2772 TABLE_LIST *table_ref, *first_leaf, *last_leaf;
2773 Field_iterator_table table_field_it;
2774 Field_iterator_view view_field_it;
2775 Field_iterator_natural_join natural_join_it;
2776 Field_iterator *field_it;
2777 void set_field_iterator();
2778 public:
Field_iterator_table_ref()2779 Field_iterator_table_ref() :field_it(NULL) {}
2780 void set(TABLE_LIST *table);
2781 void next();
end_of_fields()2782 bool end_of_fields()
2783 { return (table_ref == last_leaf && field_it->end_of_fields()); }
name()2784 const char *name() { return field_it->name(); }
2785 const char *get_table_name();
2786 const char *get_db_name();
2787 GRANT_INFO *grant();
create_item(THD * thd)2788 Item *create_item(THD *thd) { return field_it->create_item(thd); }
field()2789 Field *field() { return field_it->field(); }
2790 Natural_join_column *get_or_create_column_ref(THD *thd, TABLE_LIST *parent_table_ref);
2791 Natural_join_column *get_natural_column_ref();
2792 };
2793
2794 /**
2795 Semijoin_mat_optimize collects data used when calculating the cost of
2796 executing a semijoin operation using a materialization strategy.
2797 It is used during optimization phase only.
2798 */
2799
2800 struct Semijoin_mat_optimize
2801 {
2802 /// Optimal join order calculated for inner tables of this semijoin op.
2803 struct st_position *positions;
2804 /// True if data types allow the MaterializeLookup semijoin strategy
2805 bool lookup_allowed;
2806 /// True if data types allow the MaterializeScan semijoin strategy
2807 bool scan_allowed;
2808 /// Expected #rows in the materialized table
2809 double expected_rowcount;
2810 /// Materialization cost - execute sub-join and write rows to temp.table
2811 Cost_estimate materialization_cost;
2812 /// Cost to make one lookup in the temptable
2813 Cost_estimate lookup_cost;
2814 /// Cost of scanning the materialized table
2815 Cost_estimate scan_cost;
2816 /// Array of pointers to fields in the materialized table.
2817 Item_field **mat_fields;
2818 };
2819
2820
2821 /**
2822 Struct st_nested_join is used to represent how tables are connected through
2823 outer join operations and semi-join operations to form a query block.
2824 Out of the parser, inner joins are also represented by st_nested_join
2825 structs, but these are later flattened out by simplify_joins().
2826 Some outer join nests are also flattened, when it can be determined that
2827 they can be processed as inner joins instead of outer joins.
2828 */
2829 typedef struct st_nested_join
2830 {
st_nested_joinst_nested_join2831 st_nested_join() { memset(this, 0, sizeof(*this)); }
2832
2833 List<TABLE_LIST> join_list; /* list of elements in the nested join */
2834 table_map used_tables; /* bitmap of tables in the nested join */
2835 table_map not_null_tables; /* tables that rejects nulls */
2836 /**
2837 Used for pointing out the first table in the plan being covered by this
2838 join nest. It is used exclusively within make_outerjoin_info().
2839 */
2840 plan_idx first_nested;
2841 /**
2842 Set to true when natural join or using information has been processed.
2843 */
2844 bool natural_join_processed;
2845 /**
2846 Number of tables and outer join nests administered by this nested join
2847 object for the sake of cost analysis. Includes direct member tables as
2848 well as tables included through semi-join nests, but notice that semi-join
2849 nests themselves are not counted.
2850 */
2851 uint nj_total;
2852 /**
2853 Used to count tables in the nested join in 2 isolated places:
2854 1. In make_outerjoin_info().
2855 2. check_interleaving_with_nj/backout_nj_state (these are called
2856 by the join optimizer.
2857 Before each use the counters are zeroed by SELECT_LEX::reset_nj_counters.
2858 */
2859 uint nj_counter;
2860 /**
2861 Bit identifying this nested join. Only nested joins representing the
2862 outer join structure need this, other nests have bit set to zero.
2863 */
2864 nested_join_map nj_map;
2865 /**
2866 Tables outside the semi-join that are used within the semi-join's
2867 ON condition (ie. the subquery WHERE clause and optional IN equalities).
2868 */
2869 table_map sj_depends_on;
2870 /**
2871 Outer non-trivially correlated tables, a true subset of sj_depends_on
2872 */
2873 table_map sj_corr_tables;
2874 /**
2875 Query block id if this struct is generated from a subquery transform.
2876 */
2877 uint query_block_id;
2878
2879 /// Bitmap of which strategies are enabled for this semi-join nest
2880 uint sj_enabled_strategies;
2881
2882 /*
2883 Lists of trivially-correlated expressions from the outer and inner tables
2884 of the semi-join, respectively.
2885 */
2886 List<Item> sj_outer_exprs, sj_inner_exprs;
2887 Semijoin_mat_optimize sjm;
2888 } NESTED_JOIN;
2889
2890
2891 typedef struct st_open_table_list{
2892 struct st_open_table_list *next;
2893 char *db,*table;
2894 uint32 in_use,locked;
2895 } OPEN_TABLE_LIST;
2896
2897
tmp_use_all_columns(TABLE * table,MY_BITMAP * bitmap)2898 static inline my_bitmap_map *tmp_use_all_columns(TABLE *table,
2899 MY_BITMAP *bitmap)
2900 {
2901 my_bitmap_map *old= bitmap->bitmap;
2902 bitmap->bitmap= table->s->all_set.bitmap;// does not repoint last_word_ptr
2903 return old;
2904 }
2905
2906
tmp_restore_column_map(MY_BITMAP * bitmap,my_bitmap_map * old)2907 static inline void tmp_restore_column_map(MY_BITMAP *bitmap,
2908 my_bitmap_map *old)
2909 {
2910 bitmap->bitmap= old;
2911 }
2912
2913 /* The following is only needed for debugging */
2914
dbug_tmp_use_all_columns(TABLE * table,MY_BITMAP * bitmap)2915 static inline my_bitmap_map *dbug_tmp_use_all_columns(TABLE *table,
2916 MY_BITMAP *bitmap)
2917 {
2918 #ifndef NDEBUG
2919 return tmp_use_all_columns(table, bitmap);
2920 #else
2921 return 0;
2922 #endif
2923 }
2924
dbug_tmp_restore_column_map(MY_BITMAP * bitmap,my_bitmap_map * old)2925 static inline void dbug_tmp_restore_column_map(MY_BITMAP *bitmap,
2926 my_bitmap_map *old)
2927 {
2928 #ifndef NDEBUG
2929 tmp_restore_column_map(bitmap, old);
2930 #endif
2931 }
2932
2933
2934 /*
2935 Variant of the above : handle both read and write sets.
2936 Provide for the possiblity of the read set being the same as the write set
2937 */
dbug_tmp_use_all_columns(TABLE * table,my_bitmap_map ** save,MY_BITMAP * read_set,MY_BITMAP * write_set)2938 static inline void dbug_tmp_use_all_columns(TABLE *table,
2939 my_bitmap_map **save,
2940 MY_BITMAP *read_set,
2941 MY_BITMAP *write_set)
2942 {
2943 #ifndef NDEBUG
2944 save[0]= read_set->bitmap;
2945 save[1]= write_set->bitmap;
2946 (void) tmp_use_all_columns(table, read_set);
2947 (void) tmp_use_all_columns(table, write_set);
2948 #endif
2949 }
2950
2951
dbug_tmp_restore_column_maps(MY_BITMAP * read_set,MY_BITMAP * write_set,my_bitmap_map ** old)2952 static inline void dbug_tmp_restore_column_maps(MY_BITMAP *read_set,
2953 MY_BITMAP *write_set,
2954 my_bitmap_map **old)
2955 {
2956 #ifndef NDEBUG
2957 tmp_restore_column_map(read_set, old[0]);
2958 tmp_restore_column_map(write_set, old[1]);
2959 #endif
2960 }
2961
2962
2963 size_t max_row_length(TABLE *table, const uchar *data);
2964
2965
2966 void init_mdl_requests(TABLE_LIST *table_list);
2967
2968 int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias,
2969 uint db_stat, uint prgflag, uint ha_open_flags,
2970 TABLE *outparam, bool is_create_table);
2971 TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, const char *key,
2972 size_t key_length);
2973 void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
2974 size_t key_length,
2975 const char *table_name, const char *path);
2976 void free_table_share(TABLE_SHARE *share);
2977
2978
2979 /**
2980 Get the tablespace name for a table.
2981
2982 This function will open the .FRM file for the given TABLE_LIST element
2983 and fill Tablespace_hash_set with the tablespace name used by table and
2984 table partitions, if present. For NDB tables with version before 50120,
2985 the function will ask the SE for the tablespace name, because for these
2986 tables, the tablespace name is not stored in the.FRM file, but only
2987 within the SE itself.
2988
2989 @note The function does *not* consider errors. If the file is not present,
2990 this does not raise an error. The reason is that this function will
2991 be used for tables that may not exist, e.g. in the context of
2992 'DROP TABLE IF EXISTS', which does not care whether the table
2993 exists or not. The function returns success in this case.
2994
2995 @note Strings inserted into hash are allocated in the memory
2996 root of the thd, and will be freed implicitly.
2997
2998 @param thd - Thread context.
2999 @param table - Table from which we read the tablespace names.
3000 @param tablespace_set (OUT)- Hash set to be filled with tablespace names.
3001
3002 @retval true - On failure, especially due to memory allocation errors
3003 and partition string parse errors.
3004 @retval false - On success. Even if tablespaces are not used by table.
3005 */
3006
3007 bool get_table_and_parts_tablespace_names(
3008 THD *thd,
3009 TABLE_LIST *table,
3010 Tablespace_hash_set *tablespace_set);
3011
3012 int open_table_def(THD *thd, TABLE_SHARE *share, uint db_flags);
3013 void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg);
3014 void update_create_info_from_table(HA_CREATE_INFO *info, TABLE *form);
3015 enum_ident_name_check check_and_convert_db_name(LEX_STRING *db,
3016 bool preserve_lettercase);
3017 bool check_column_name(const char *name);
3018 enum_ident_name_check check_table_name(const char *name, size_t length,
3019 bool check_for_path_chars);
3020 int rename_file_ext(const char * from,const char * to,const char * ext);
3021 char *get_field(MEM_ROOT *mem, Field *field);
3022 bool get_field(MEM_ROOT *mem, Field *field, class String *res);
3023
3024 int closefrm(TABLE *table, bool free_share);
3025 int read_string(File file, uchar* *to, size_t length);
3026 void free_blobs(TABLE *table);
3027 void free_blob_buffers_and_reset(TABLE *table, uint32 size);
3028 int set_zone(int nr,int min_zone,int max_zone);
3029 ulong make_new_entry(File file,uchar *fileinfo,TYPELIB *formnames,
3030 const char *newname);
3031 ulong next_io_size(ulong pos);
3032 void append_unescaped(String *res, const char *pos, size_t length);
3033 File create_frm(THD *thd, const char *name, const char *db,
3034 const char *table, uint reclength, uchar *fileinfo,
3035 HA_CREATE_INFO *create_info, uint keys, KEY *key_info);
3036 char *fn_rext(char *name);
3037
3038 /* performance schema */
3039 extern LEX_STRING PERFORMANCE_SCHEMA_DB_NAME;
3040
3041 extern LEX_STRING GENERAL_LOG_NAME;
3042 extern LEX_STRING SLOW_LOG_NAME;
3043
3044 /* information schema */
3045 extern LEX_STRING INFORMATION_SCHEMA_NAME;
3046 extern LEX_STRING MYSQL_SCHEMA_NAME;
3047
3048 /* replication's tables */
3049 extern LEX_STRING RLI_INFO_NAME;
3050 extern LEX_STRING MI_INFO_NAME;
3051 extern LEX_STRING WORKER_INFO_NAME;
3052
is_infoschema_db(const char * name,size_t len)3053 inline bool is_infoschema_db(const char *name, size_t len)
3054 {
3055 return (INFORMATION_SCHEMA_NAME.length == len &&
3056 !my_strcasecmp(system_charset_info,
3057 INFORMATION_SCHEMA_NAME.str, name));
3058 }
3059
is_infoschema_db(const char * name)3060 inline bool is_infoschema_db(const char *name)
3061 {
3062 return !my_strcasecmp(system_charset_info,
3063 INFORMATION_SCHEMA_NAME.str, name);
3064 }
3065
is_perfschema_db(const char * name,size_t len)3066 inline bool is_perfschema_db(const char *name, size_t len)
3067 {
3068 return (PERFORMANCE_SCHEMA_DB_NAME.length == len &&
3069 !my_strcasecmp(system_charset_info,
3070 PERFORMANCE_SCHEMA_DB_NAME.str, name));
3071 }
3072
is_perfschema_db(const char * name)3073 inline bool is_perfschema_db(const char *name)
3074 {
3075 return !my_strcasecmp(system_charset_info,
3076 PERFORMANCE_SCHEMA_DB_NAME.str, name);
3077 }
3078
3079 /**
3080 Check if the table belongs to the P_S, excluding setup and threads tables.
3081
3082 @note Performance Schema tables must be accessible independently of the
3083 LOCK TABLE mode. This function is needed to handle the special case
3084 of P_S tables being used under LOCK TABLE mode.
3085 */
belongs_to_p_s(TABLE_LIST * tl)3086 inline bool belongs_to_p_s(TABLE_LIST *tl)
3087 {
3088 return (!strcmp("performance_schema", tl->db) &&
3089 strcmp(tl->table_name, "threads") &&
3090 strstr(tl->table_name, "setup_") == NULL);
3091 }
3092
3093 TYPELIB *typelib(MEM_ROOT *mem_root, List<String> &strings);
3094
3095 /**
3096 return true if the table was created explicitly.
3097 */
is_user_table(TABLE * table)3098 inline bool is_user_table(TABLE * table)
3099 {
3100 const char *name= table->s->table_name.str;
3101 return strncmp(name, tmp_file_prefix, tmp_file_prefix_length);
3102 }
3103
3104 bool is_simple_order(ORDER *order);
3105
3106 void repoint_field_to_record(TABLE *table, uchar *old_rec, uchar *new_rec);
3107 bool update_generated_write_fields(const MY_BITMAP *bitmap, TABLE *table);
3108 bool update_generated_read_fields(uchar *buf, TABLE *table,
3109 uint active_index= MAX_KEY);
3110
3111 ulong get_form_pos(File file, uchar *head);
3112 #endif /* MYSQL_CLIENT */
3113
3114 #endif /* TABLE_INCLUDED */
3115