1 #ifndef TABLE_INCLUDED
2 #define TABLE_INCLUDED
3
4 /* Copyright (c) 2000, 2020, 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 DBUG_OFF
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 const CHARSET_INFO *table_charset; /* Default charset of string fields */
605
606 MY_BITMAP all_set;
607 /*
608 Key which is used for looking-up table in table cache and in the list
609 of thread's temporary tables. Has the form of:
610 "database_name\0table_name\0" + optional part for temporary tables.
611
612 Note that all three 'table_cache_key', 'db' and 'table_name' members
613 must be set (and be non-zero) for tables in table cache. They also
614 should correspond to each other.
615 To ensure this one can use set_table_cache() methods.
616 */
617 LEX_STRING table_cache_key;
618 LEX_STRING db; /* Pointer to db */
619 LEX_STRING table_name; /* Table name (for open) */
620 LEX_STRING path; /* Path to .frm file (from datadir) */
621 LEX_STRING normalized_path; /* unpack_filename(path) */
622 LEX_STRING connect_string;
623
624 /*
625 Set of keys in use, implemented as a Bitmap.
626 Excludes keys disabled by ALTER TABLE ... DISABLE KEYS.
627 */
628 key_map keys_in_use;
629 key_map keys_for_keyread;
630 ha_rows min_rows, max_rows; /* create information */
631 ulong avg_row_length; /* create information */
632 /**
633 TABLE_SHARE version, if changed the TABLE_SHARE must be reopened.
634 NOTE: The TABLE_SHARE will not be reopened during LOCK TABLES in
635 close_thread_tables!!!
636 */
637 ulong version;
638 ulong mysql_version; /* 0 if .frm is created before 5.0 */
639 ulong reclength; /* Recordlength */
640 ulong stored_rec_length; /* Stored record length
641 (no generated-only generated fields) */
642
643 plugin_ref db_plugin; /* storage engine plugin */
db_typeTABLE_SHARE644 inline handlerton *db_type() const /* table_type for handler */
645 {
646 // DBUG_ASSERT(db_plugin);
647 return db_plugin ? plugin_data<handlerton*>(db_plugin) : NULL;
648 }
649 enum row_type row_type; /* How rows are stored */
650 enum tmp_table_type tmp_table;
651
652 uint ref_count; /* How many TABLE objects uses this */
653 uint key_block_size; /* create key_block_size, if used */
654 uint stats_sample_pages; /* number of pages to sample during
655 stats estimation, if used, otherwise 0. */
656 enum_stats_auto_recalc stats_auto_recalc; /* Automatic recalc of stats. */
657 uint null_bytes, last_null_bit_pos;
658 uint fields; /* Number of fields */
659 uint stored_fields; /* Number of stored fields
660 (i.e. without generated-only ones) */
661 uint rec_buff_length; /* Size of table->record[] buffer */
662 uint keys; /* Number of keys defined for the table*/
663 uint key_parts; /* Number of key parts of all keys
664 defined for the table
665 */
666 uint max_key_length; /* Length of the longest key */
667 uint max_unique_length; /* Length of the longest unique key */
668 uint total_key_length;
669 uint uniques; /* Number of UNIQUE index */
670 uint null_fields; /* number of null fields */
671 uint blob_fields; /* number of blob fields */
672 uint varchar_fields; /* number of varchar fields */
673 uint db_create_options; /* Create options from database */
674 uint db_options_in_use; /* Options in use */
675 uint db_record_offset; /* if HA_REC_IN_SEQ */
676 uint rowid_field_offset; /* Field_nr +1 to rowid field */
677 /* Primary key index number, used in TABLE::key_info[] */
678 uint primary_key;
679 uint next_number_index; /* autoincrement key number */
680 uint next_number_key_offset; /* autoinc keypart offset in a key */
681 uint next_number_keypart; /* autoinc keypart number in a key */
682 uint error, open_errno, errarg; /* error from open_table_def() */
683 uint column_bitmap_size;
684 uchar frm_version;
685 uint vfields; /* Number of generated fields */
686 bool null_field_first;
687 bool system; /* Set if system table (one record) */
688 bool crypted; /* If .frm file is crypted */
689 bool db_low_byte_first; /* Portable row format */
690 bool crashed;
691 bool is_view;
692 bool m_open_in_progress; /* True: alloc'ed, false: def opened */
693 Table_id table_map_id; /* for row-based replication */
694
695 /*
696 Cache for row-based replication table share checks that does not
697 need to be repeated. Possible values are: -1 when cache value is
698 not calculated yet, 0 when table *shall not* be replicated, 1 when
699 table *may* be replicated.
700 */
701 int cached_row_logging_check;
702
703 /*
704 Storage media to use for this table (unless another storage
705 media has been specified on an individual column - in versions
706 where that is supported)
707 */
708 enum ha_storage_media default_storage_media;
709
710 /* Name of the tablespace used for this table */
711 char *tablespace;
712
713 /* filled in when reading from frm */
714 bool auto_partitioned;
715 char *partition_info_str;
716 uint partition_info_str_len;
717 uint partition_info_buffer_size;
718 handlerton *default_part_db_type;
719
720 /**
721 Cache the checked structure of this table.
722
723 The pointer data is used to describe the structure that
724 a instance of the table must have. Each element of the
725 array specifies a field that must exist on the table.
726
727 The pointer is cached in order to perform the check only
728 once -- when the table is loaded from the disk.
729 */
730 const TABLE_FIELD_DEF *table_field_def_cache;
731
732 /** Main handler's share */
733 Handler_share *ha_share;
734
735 /** Instrumentation for this table share. */
736 PSI_table_share *m_psi;
737
738 /**
739 List of tickets representing threads waiting for the share to be flushed.
740 */
741 Wait_for_flush_list m_flush_tickets;
742
743 /**
744 For shares representing views File_parser object with view
745 definition read from .FRM file.
746 */
747 const File_parser *view_def;
748
749
750 /*
751 Set share's table cache key and update its db and table name appropriately.
752
753 SYNOPSIS
754 set_table_cache_key()
755 key_buff Buffer with already built table cache key to be
756 referenced from share.
757 key_length Key length.
758
759 NOTES
760 Since 'key_buff' buffer will be referenced from share it should has same
761 life-time as share itself.
762 This method automatically ensures that TABLE_SHARE::table_name/db have
763 appropriate values by using table cache key as their source.
764 */
765
set_table_cache_keyTABLE_SHARE766 void set_table_cache_key(char *key_buff, size_t key_length)
767 {
768 table_cache_key.str= key_buff;
769 table_cache_key.length= key_length;
770 /*
771 Let us use the fact that the key is "db/0/table_name/0" + optional
772 part for temporary tables.
773 */
774 db.str= table_cache_key.str;
775 db.length= strlen(db.str);
776 table_name.str= db.str + db.length + 1;
777 table_name.length= strlen(table_name.str);
778 }
779
780
781 /*
782 Set share's table cache key and update its db and table name appropriately.
783
784 SYNOPSIS
785 set_table_cache_key()
786 key_buff Buffer to be used as storage for table cache key
787 (should be at least key_length bytes).
788 key Value for table cache key.
789 key_length Key length.
790
791 NOTE
792 Since 'key_buff' buffer will be used as storage for table cache key
793 it should has same life-time as share itself.
794 */
795
set_table_cache_keyTABLE_SHARE796 void set_table_cache_key(char *key_buff, const char *key, size_t key_length)
797 {
798 memcpy(key_buff, key, key_length);
799 set_table_cache_key(key_buff, key_length);
800 }
801
honor_global_locksTABLE_SHARE802 inline bool honor_global_locks()
803 {
804 return ((table_category == TABLE_CATEGORY_USER)
805 || (table_category == TABLE_CATEGORY_SYSTEM));
806 }
807
get_table_def_versionTABLE_SHARE808 inline ulonglong get_table_def_version()
809 {
810 return table_map_id;
811 }
812
813
814 /** Is this table share being expelled from the table definition cache? */
has_old_versionTABLE_SHARE815 inline bool has_old_version() const
816 {
817 return version != refresh_version;
818 }
819 /**
820 Convert unrelated members of TABLE_SHARE to one enum
821 representing its type.
822
823 @todo perhaps we need to have a member instead of a function.
824 */
get_table_ref_typeTABLE_SHARE825 enum enum_table_ref_type get_table_ref_type() const
826 {
827 if (is_view)
828 return TABLE_REF_VIEW;
829 switch (tmp_table) {
830 case NO_TMP_TABLE:
831 return TABLE_REF_BASE_TABLE;
832 case SYSTEM_TMP_TABLE:
833 return TABLE_REF_I_S_TABLE;
834 default:
835 return TABLE_REF_TMP_TABLE;
836 }
837 }
838 /**
839 Return a table metadata version.
840 * for base tables and views, we return table_map_id.
841 It is assigned from a global counter incremented for each
842 new table loaded into the table definition cache (TDC).
843 * for temporary tables it's table_map_id again. But for
844 temporary tables table_map_id is assigned from
845 thd->query_id. The latter is assigned from a thread local
846 counter incremented for every new SQL statement. Since
847 temporary tables are thread-local, each temporary table
848 gets a unique id.
849 * for everything else (e.g. information schema tables),
850 the version id is zero.
851
852 This choice of version id is a large compromise
853 to have a working prepared statement validation in 5.1. In
854 future version ids will be persistent, as described in WL#4180.
855
856 Let's try to explain why and how this limited solution allows
857 to validate prepared statements.
858
859 Firstly, sets (in mathematical sense) of version numbers
860 never intersect for different table types. Therefore,
861 version id of a temporary table is never compared with
862 a version id of a view, and vice versa.
863
864 Secondly, for base tables and views, we know that each DDL flushes
865 the respective share from the TDC. This ensures that whenever
866 a table is altered or dropped and recreated, it gets a new
867 version id.
868 Unfortunately, since elements of the TDC are also flushed on
869 LRU basis, this choice of version ids leads to false positives.
870 E.g. when the TDC size is too small, we may have a SELECT
871 * FROM INFORMATION_SCHEMA.TABLES flush all its elements, which
872 in turn will lead to a validation error and a subsequent
873 reprepare of all prepared statements. This is
874 considered acceptable, since as long as prepared statements are
875 automatically reprepared, spurious invalidation is only
876 a performance hit. Besides, no better simple solution exists.
877
878 For temporary tables, using thd->query_id ensures that if
879 a temporary table was altered or recreated, a new version id is
880 assigned. This suits validation needs very well and will perhaps
881 never change.
882
883 Metadata of information schema tables never changes.
884 Thus we can safely assume 0 for a good enough version id.
885
886 Finally, by taking into account table type, we always
887 track that a change has taken place when a view is replaced
888 with a base table, a base table is replaced with a temporary
889 table and so on.
890
891 @sa TABLE_LIST::is_table_ref_id_equal()
892 */
get_table_ref_versionTABLE_SHARE893 ulonglong get_table_ref_version() const
894 {
895 return (tmp_table == SYSTEM_TMP_TABLE) ? 0 : table_map_id.id();
896 }
897
898 bool visit_subgraph(Wait_for_flush *waiting_ticket,
899 MDL_wait_for_graph_visitor *gvisitor);
900
901 bool wait_for_old_version(THD *thd, struct timespec *abstime,
902 uint deadlock_weight);
903 /** Release resources and free memory occupied by the table share. */
904 void destroy();
905 };
906
907
908 /**
909 Class is used as a BLOB field value storage for
910 intermediate GROUP_CONCAT results. Used only for
911 GROUP_CONCAT with DISTINCT or ORDER BY options.
912 */
913
914 class Blob_mem_storage: public Sql_alloc
915 {
916 private:
917 MEM_ROOT storage;
918 /**
919 Sign that some values were cut
920 during saving into the storage.
921 */
922 bool truncated_value;
923 public:
Blob_mem_storage()924 Blob_mem_storage() :truncated_value(false)
925 {
926 init_alloc_root(key_memory_blob_mem_storage,
927 &storage, MAX_FIELD_VARCHARLENGTH, 0);
928 }
~Blob_mem_storage()929 ~ Blob_mem_storage()
930 {
931 free_root(&storage, MYF(0));
932 }
reset()933 void reset()
934 {
935 free_root(&storage, MYF(MY_MARK_BLOCKS_FREE));
936 truncated_value= false;
937 }
938 /**
939 Fuction creates duplicate of 'from'
940 string in 'storage' MEM_ROOT.
941
942 @param from string to copy
943 @param length string length
944
945 @retval Pointer to the copied string.
946 @retval 0 if an error occured.
947 */
store(const char * from,size_t length)948 char *store(const char *from, size_t length)
949 {
950 return (char*) memdup_root(&storage, from, length);
951 }
set_truncated_value(bool is_truncated_value)952 void set_truncated_value(bool is_truncated_value)
953 {
954 truncated_value= is_truncated_value;
955 }
is_truncated_value()956 bool is_truncated_value() { return truncated_value; }
957 };
958
959
960 /**
961 Flags for TABLE::status (maximum 8 bits). Do NOT add new ones.
962 @todo: GARBAGE and NOT_FOUND could be unified. UPDATED and DELETED could be
963 changed to "bool current_row_has_already_been_modified" in the
964 multi_update/delete objects (one such bool per to-be-modified table).
965 @todo aim at removing the status. There should be more local ways.
966 */
967 #define STATUS_GARBAGE 1
968 /**
969 Means we were searching for a row and didn't find it. This is used by
970 storage engines (@see handler::index_read_map()) and the Server layer.
971 */
972 #define STATUS_NOT_FOUND 2
973 /// Reserved for use by multi-table update. Means the row has been updated.
974 #define STATUS_UPDATED 16
975 /**
976 Means that table->null_row is set. This is an artificial NULL-filled row
977 (one example: in outer join, if no match has been found in inner table).
978 */
979 #define STATUS_NULL_ROW 32
980 /// Reserved for use by multi-table delete. Means the row has been deleted.
981 #define STATUS_DELETED 64
982
983
984 /* Information for one open table */
985 enum index_hint_type
986 {
987 INDEX_HINT_IGNORE,
988 INDEX_HINT_USE,
989 INDEX_HINT_FORCE
990 };
991
992 /* Bitmap of table's fields */
993 typedef Bitmap<MAX_FIELDS> Field_map;
994
995 struct TABLE
996 {
TABLETABLE997 TABLE() { memset(this, 0, sizeof(*this)); }
998 /*
999 Since TABLE instances are often cleared using memset(), do not
1000 add virtual members and do not inherit from TABLE.
1001 Otherwise memset() will start overwriting the vtable pointer.
1002 */
1003
1004 TABLE_SHARE *s;
1005 handler *file;
1006 TABLE *next, *prev;
1007
1008 private:
1009 /**
1010 Links for the lists of used/unused TABLE objects for the particular
1011 table in the specific instance of Table_cache (in other words for
1012 specific Table_cache_element object).
1013 Declared as private to avoid direct manipulation with those objects.
1014 One should use methods of I_P_List template instead.
1015 */
1016 TABLE *cache_next, **cache_prev;
1017
1018 /*
1019 Give Table_cache_element access to the above two members to allow
1020 using them for linking TABLE objects in a list.
1021 */
1022 friend class Table_cache_element;
1023
1024 public:
1025
1026 THD *in_use; /* Which thread uses this */
1027 Field **field; /* Pointer to fields */
1028 /// Count of hidden fields, if internal temporary table; 0 otherwise.
1029 uint hidden_field_count;
1030
1031 uchar *record[2]; /* Pointer to records */
1032 uchar *write_row_record; /* Used as optimisation in
1033 THD::write_row */
1034 uchar *insert_values; /* used by INSERT ... UPDATE */
1035 /*
1036 Map of keys that can be used to retrieve all data from this table
1037 needed by the query without reading the row.
1038 */
1039 key_map covering_keys;
1040 key_map quick_keys, merge_keys;
1041
1042 /*
1043 possible_quick_keys is a superset of quick_keys to use with EXPLAIN of
1044 JOIN-less commands (single-table UPDATE and DELETE).
1045
1046 When explaining regular JOINs, we use JOIN_TAB::keys to output the
1047 "possible_keys" column value. However, it is not available for
1048 single-table UPDATE and DELETE commands, since they don't use JOIN
1049 optimizer at the top level. OTOH they directly use the range optimizer,
1050 that collects all keys usable for range access here.
1051 */
1052 key_map possible_quick_keys;
1053
1054 /*
1055 A set of keys that can be used in the query that references this
1056 table.
1057
1058 All indexes disabled on the table's TABLE_SHARE (see TABLE::s) will be
1059 subtracted from this set upon instantiation. Thus for any TABLE t it holds
1060 that t.keys_in_use_for_query is a subset of t.s.keys_in_use. Generally we
1061 must not introduce any new keys here (see setup_tables).
1062
1063 The set is implemented as a bitmap.
1064 */
1065 key_map keys_in_use_for_query;
1066 /* Map of keys that can be used to calculate GROUP BY without sorting */
1067 key_map keys_in_use_for_group_by;
1068 /* Map of keys that can be used to calculate ORDER BY without sorting */
1069 key_map keys_in_use_for_order_by;
1070 KEY *key_info; /* data of keys defined for the table */
1071
1072 Field *next_number_field; /* Set if next_number is activated */
1073 Field *found_next_number_field; /* Set on open */
1074 Field **vfield; /* Pointer to generated fields*/
1075 Field *hash_field; /* Field used by unique constraint */
1076 Field *fts_doc_id_field; /* Set if FTS_DOC_ID field is present */
1077
1078 /* Table's triggers, 0 if there are no of them */
1079 Table_trigger_dispatcher *triggers;
1080 TABLE_LIST *pos_in_table_list;/* Element referring to this table */
1081 /* Position in thd->locked_table_list under LOCK TABLES */
1082 TABLE_LIST *pos_in_locked_tables;
1083 ORDER *group;
1084 const char *alias; /* alias or table name */
1085 uchar *null_flags;
1086 my_bitmap_map *bitmap_init_value;
1087 MY_BITMAP def_read_set, def_write_set, tmp_set; /* containers */
1088 /*
1089 Bitmap of fields that one or more query condition refers to. Only
1090 used if optimizer_condition_fanout_filter is turned 'on'.
1091 Currently, only the WHERE clause and ON clause of inner joins is
1092 taken into account but not ON conditions of outer joins.
1093 Furthermore, HAVING conditions apply to groups and are therefore
1094 not useful as table condition filters.
1095 */
1096 MY_BITMAP cond_set;
1097
1098 /**
1099 Bitmap of table fields (columns), which are explicitly set in the
1100 INSERT INTO statement. It is declared here to avoid memory allocation
1101 on MEM_ROOT).
1102
1103 @sa fields_set_during_insert.
1104 */
1105 MY_BITMAP def_fields_set_during_insert;
1106
1107 MY_BITMAP *read_set, *write_set; /* Active column sets */
1108
1109 /**
1110 A pointer to the bitmap of table fields (columns), which are explicitly set
1111 in the INSERT INTO statement.
1112
1113 fields_set_during_insert points to def_fields_set_during_insert
1114 for base (non-temporary) tables. In other cases, it is NULL.
1115 Triggers can not be defined for temporary tables, so this bitmap does not
1116 matter for temporary tables.
1117
1118 @sa def_fields_set_during_insert.
1119 */
1120 MY_BITMAP *fields_set_during_insert;
1121
1122 /*
1123 The ID of the query that opened and is using this table. Has different
1124 meanings depending on the table type.
1125
1126 Temporary tables:
1127
1128 table->query_id is set to thd->query_id for the duration of a statement
1129 and is reset to 0 once it is closed by the same statement. A non-zero
1130 table->query_id means that a statement is using the table even if it's
1131 not the current statement (table is in use by some outer statement).
1132
1133 Non-temporary tables:
1134
1135 Under pre-locked or LOCK TABLES mode: query_id is set to thd->query_id
1136 for the duration of a statement and is reset to 0 once it is closed by
1137 the same statement. A non-zero query_id is used to control which tables
1138 in the list of pre-opened and locked tables are actually being used.
1139 */
1140 query_id_t query_id;
1141
1142 /*
1143 For each key that has quick_keys.is_set(key) == TRUE: estimate of #records
1144 and max #key parts that range access would use.
1145 */
1146 ha_rows quick_rows[MAX_KEY];
1147
1148 /* Bitmaps of key parts that =const for the entire join. */
1149 key_part_map const_key_parts[MAX_KEY];
1150
1151 uint quick_key_parts[MAX_KEY];
1152 uint quick_n_ranges[MAX_KEY];
1153
1154 /*
1155 Estimate of number of records that satisfy SARGable part of the table
1156 condition, or table->file->records if no SARGable condition could be
1157 constructed.
1158 This value is used by join optimizer as an estimate of number of records
1159 that will pass the table condition (condition that depends on fields of
1160 this table and constants)
1161 */
1162 ha_rows quick_condition_rows;
1163
1164 uint lock_position; /* Position in MYSQL_LOCK.table */
1165 uint lock_data_start; /* Start pos. in MYSQL_LOCK.locks */
1166 uint lock_count; /* Number of locks */
1167 uint temp_pool_slot; /* Used by intern temp tables */
1168 uint db_stat; /* mode of file as in handler.h */
1169 int current_lock; /* Type of lock on table */
1170
1171 private:
1172 /**
1173 If true, this table is inner w.r.t. some outer join operation, all columns
1174 are nullable (in the query), and null_row may be true.
1175 */
1176 my_bool nullable;
1177
1178 public:
1179 /*
1180 If true, the current table row is considered to have all columns set to
1181 NULL, including columns declared as "not null" (see nullable).
1182 @todo make it private, currently join buffering changes it through a pointer
1183 */
1184 my_bool null_row;
1185
1186 uint8 status; /* What's in record[0] */
1187 my_bool copy_blobs; /* copy_blobs when storing */
1188
1189 /*
1190 TODO: Each of the following flags take up 8 bits. They can just as easily
1191 be put into one single unsigned long and instead of taking up 18
1192 bytes, it would take up 4.
1193 */
1194 my_bool force_index;
1195
1196 /**
1197 Flag set when the statement contains FORCE INDEX FOR ORDER BY
1198 See TABLE_LIST::process_index_hints().
1199 */
1200 my_bool force_index_order;
1201
1202 /**
1203 Flag set when the statement contains FORCE INDEX FOR GROUP BY
1204 See TABLE_LIST::process_index_hints().
1205 */
1206 my_bool force_index_group;
1207 my_bool distinct;
1208 my_bool const_table;
1209 my_bool no_rows;
1210
1211 /**
1212 If set, the optimizer has found that row retrieval should access index
1213 tree only.
1214 */
1215 my_bool key_read;
1216 /**
1217 Certain statements which need the full row, set this to ban index-only
1218 access.
1219 */
1220 my_bool no_keyread;
1221 my_bool locked_by_logger;
1222 /**
1223 If set, indicate that the table is not replicated by the server.
1224 */
1225 my_bool no_replicate;
1226 my_bool locked_by_name;
1227 my_bool fulltext_searched;
1228 my_bool no_cache;
1229 /* To signal that the table is associated with a HANDLER statement */
1230 my_bool open_by_handler;
1231 /*
1232 To indicate that a non-null value of the auto_increment field
1233 was provided by the user or retrieved from the current record.
1234 Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode.
1235 */
1236 my_bool auto_increment_field_not_null;
1237 my_bool insert_or_update; /* Can be used by the handler */
1238 my_bool alias_name_used; /* true if table_name is alias */
1239 my_bool get_fields_in_item_tree; /* Signal to fix_field */
1240 /**
1241 This table must be reopened and is not to be reused.
1242 NOTE: The TABLE will not be reopened during LOCK TABLES in
1243 close_thread_tables!!!
1244 */
1245 my_bool m_needs_reopen;
1246 private:
1247 bool created; /* For tmp tables. TRUE <=> tmp table has been instantiated.*/
1248 public:
1249 uint max_keys; /* Size of allocated key_info array. */
1250
1251 struct /* field connections */
1252 {
1253 class JOIN_TAB *join_tab;
1254 class QEP_TAB *qep_tab;
1255 enum thr_lock_type lock_type; /* How table is used */
1256 bool not_exists_optimize;
1257 /*
1258 TRUE <=> range optimizer found that there is no rows satisfying
1259 table conditions.
1260 */
1261 bool impossible_range;
1262 } reginfo;
1263
1264 /**
1265 @todo This member should not be declared in-line. That makes it
1266 impossible for any function that does memory allocation to take a const
1267 reference to a TABLE object.
1268 */
1269 MEM_ROOT mem_root;
1270 /**
1271 Initialized in Item_func_group_concat::setup for appropriate
1272 temporary table if GROUP_CONCAT is used with ORDER BY | DISTINCT
1273 and BLOB field count > 0.
1274 */
1275 Blob_mem_storage *blob_storage;
1276 GRANT_INFO grant;
1277 Filesort_info sort;
1278 partition_info *part_info; /* Partition related information */
1279 /* If true, all partitions have been pruned away */
1280 bool all_partitions_pruned_away;
1281 MDL_ticket *mdl_ticket;
1282
1283 private:
1284 /// Cost model object for operations on this table
1285 Cost_model_table m_cost_model;
1286 public:
1287
1288 void init(THD *thd, TABLE_LIST *tl);
1289 bool fill_item_list(List<Item> *item_list) const;
1290 void reset_item_list(List<Item> *item_list) const;
1291 void clear_column_bitmaps(void);
1292 void prepare_for_position(void);
1293
1294 void mark_column_used(THD *thd, Field *field, enum enum_mark_columns mark);
1295 void mark_columns_used_by_index_no_reset(uint index, MY_BITMAP *map,
1296 uint key_parts= 0);
1297 void mark_columns_used_by_index(uint index);
1298 void mark_auto_increment_column(void);
1299 void mark_columns_needed_for_update(bool mark_binlog_columns);
1300 void mark_columns_needed_for_delete(void);
1301 void mark_columns_needed_for_insert(void);
1302 void mark_columns_per_binlog_row_image(void);
1303 void mark_generated_columns(bool is_update);
1304 bool is_field_used_by_generated_columns(uint field_index);
1305 void mark_gcol_in_maps(Field *field);
column_bitmaps_setTABLE1306 inline void column_bitmaps_set(MY_BITMAP *read_set_arg,
1307 MY_BITMAP *write_set_arg)
1308 {
1309 read_set= read_set_arg;
1310 write_set= write_set_arg;
1311 if (file && created)
1312 file->column_bitmaps_signal();
1313 }
column_bitmaps_set_no_signalTABLE1314 inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg,
1315 MY_BITMAP *write_set_arg)
1316 {
1317 read_set= read_set_arg;
1318 write_set= write_set_arg;
1319 }
use_all_columnsTABLE1320 inline void use_all_columns()
1321 {
1322 column_bitmaps_set(&s->all_set, &s->all_set);
1323 }
default_column_bitmapsTABLE1324 inline void default_column_bitmaps()
1325 {
1326 read_set= &def_read_set;
1327 write_set= &def_write_set;
1328 }
1329 /** Should this instance of the table be reopened? */
needs_reopenTABLE1330 inline bool needs_reopen()
1331 { return !db_stat || m_needs_reopen; }
1332 /// @returns first non-hidden column
visible_field_ptrTABLE1333 Field **visible_field_ptr() const
1334 { return field + hidden_field_count; }
1335 /// @returns count of visible fields
visible_field_countTABLE1336 uint visible_field_count() const
1337 { return s->fields - hidden_field_count; }
1338 bool alloc_keys(uint key_count);
1339 bool add_tmp_key(Field_map *key_parts, char *key_name);
1340 void use_index(int key_to_save);
1341
set_keyreadTABLE1342 void set_keyread(bool flag)
1343 {
1344 DBUG_ASSERT(file);
1345 if (flag && !key_read)
1346 {
1347 key_read= 1;
1348 if (is_created())
1349 file->extra(HA_EXTRA_KEYREAD);
1350 }
1351 else if (!flag && key_read)
1352 {
1353 key_read= 0;
1354 if (is_created())
1355 file->extra(HA_EXTRA_NO_KEYREAD);
1356 }
1357 }
1358
1359 /**
1360 Check whether the given index has a virtual generated columns.
1361
1362 @param index_no the given index to check
1363
1364 @returns true if if index is defined over at least one virtual generated
1365 column
1366 */
index_contains_some_virtual_gcolTABLE1367 inline bool index_contains_some_virtual_gcol(uint index_no)
1368 {
1369 DBUG_ASSERT(index_no < s->keys);
1370 return key_info[index_no].flags & HA_VIRTUAL_GEN_KEY;
1371 }
1372 bool update_const_key_parts(Item *conds);
1373
1374 bool check_read_removal(uint index);
1375
default_values_offsetTABLE1376 my_ptrdiff_t default_values_offset() const
1377 { return (my_ptrdiff_t) (s->default_values - record[0]); }
1378
1379 /// Return true if table is instantiated, and false otherwise.
is_createdTABLE1380 bool is_created() const { return created; }
1381
1382 /**
1383 Set the table as "created", and enable flags in storage engine
1384 that could not be enabled without an instantiated table.
1385 */
set_createdTABLE1386 void set_created()
1387 {
1388 if (created)
1389 return;
1390 if (key_read)
1391 file->extra(HA_EXTRA_KEYREAD);
1392 created= true;
1393 }
1394 /**
1395 Set the contents of table to be "deleted", ie "not created", after having
1396 deleted the contents.
1397 */
set_deletedTABLE1398 void set_deleted()
1399 {
1400 created= false;
1401 }
1402 /// Set table as nullable, ie it is inner wrt some outer join
set_nullableTABLE1403 void set_nullable() { nullable= TRUE; }
1404
1405 /// Return whether table is nullable
is_nullableTABLE1406 bool is_nullable() const { return nullable; }
1407
1408 /// @return true if table contains one or more generated columns
has_gcolTABLE1409 bool has_gcol() const { return vfield; }
1410
1411 /// @return true if table contains one or more virtual generated columns
1412 bool has_virtual_gcol() const;
1413
1414 /// Set current row as "null row", for use in null-complemented outer join
set_null_rowTABLE1415 void set_null_row()
1416 {
1417 null_row= TRUE;
1418 status|= STATUS_NULL_ROW;
1419 memset(null_flags, 255, s->null_bytes);
1420 }
1421
1422 /// Clear "null row" status for the current row
reset_null_rowTABLE1423 void reset_null_row()
1424 {
1425 null_row= FALSE;
1426 status&= ~STATUS_NULL_ROW;
1427 }
1428
1429 /// @return true if current row is null-extended
has_null_rowTABLE1430 bool has_null_row() const { return null_row; }
1431
1432 /**
1433 Initialize the optimizer cost model.
1434
1435 This function should be called each time a new query is started.
1436
1437 @param cost_model_server the main cost model object for the query
1438 */
init_cost_modelTABLE1439 void init_cost_model(const Cost_model_server* cost_model_server)
1440 {
1441 m_cost_model.init(cost_model_server, this);
1442 }
1443
1444 /**
1445 Return the cost model object for this table.
1446 */
cost_modelTABLE1447 const Cost_model_table* cost_model() const { return &m_cost_model; }
1448
1449 /**
1450 Fix table's generated columns' (GC) expressions
1451
1452 @details When a table is opened from the dictionary, the GCs' expressions
1453 are fixed during opening (see fix_fields_gcol_func()). After query
1454 execution, Item::cleanup() is called on them (see cleanup_gc_items()). When
1455 the table is opened from the table cache, the GCs need to be fixed again
1456 and this function does that.
1457
1458 @param[in] thd the current thread
1459 @return true if error, else false
1460 */
1461 bool refix_gc_items(THD *thd);
1462
1463 /**
1464 Clean any state in items associated with generated columns to be ready for
1465 the next statement.
1466 */
1467 void cleanup_gc_items();
1468
1469 /**
1470 Check if table contains any records.
1471
1472 @param thd The thread object
1473 @param[out] retval Pointer to boolean value (true if table is not empty).
1474
1475 @returns false for success, true for error
1476 */
1477 bool contains_records(THD *thd, bool *retval);
1478 private:
1479
1480 /**
1481 This flag decides whether or not we should log the drop temporary table
1482 command.
1483 */
1484 bool should_binlog_drop_if_temp_flag;
1485
1486 public:
1487 /**
1488 Virtual fields of type BLOB have a flag m_keep_old_value. This flag is set
1489 to false for all such fields in this table.
1490 */
1491 void blobs_need_not_keep_old_value();
1492
1493 /**
1494 Set the variable should_binlog_drop_if_temp_flag, so that
1495 the logging of temporary tables can be decided.
1496
1497 @param should_binlog the value to set flag should_binlog_drop_if_temp_flag
1498 */
1499 void set_binlog_drop_if_temp(bool should_binlog);
1500
1501 /**
1502 @return whether should_binlog_drop_if_temp_flag flag is
1503 set or not
1504 */
1505 bool should_binlog_drop_if_temp(void) const;
1506 };
1507
1508
1509 enum enum_schema_table_state
1510 {
1511 NOT_PROCESSED= 0,
1512 PROCESSED_BY_CREATE_SORT_INDEX,
1513 PROCESSED_BY_JOIN_EXEC
1514 };
1515
1516 typedef struct st_foreign_key_info
1517 {
1518 LEX_STRING *foreign_id;
1519 LEX_STRING *foreign_db;
1520 LEX_STRING *foreign_table;
1521 LEX_STRING *referenced_db;
1522 LEX_STRING *referenced_table;
1523 LEX_STRING *update_method;
1524 LEX_STRING *delete_method;
1525 LEX_STRING *referenced_key_name;
1526 List<LEX_STRING> foreign_fields;
1527 List<LEX_STRING> referenced_fields;
1528 } FOREIGN_KEY_INFO;
1529
1530 #define MY_I_S_MAYBE_NULL 1
1531 #define MY_I_S_UNSIGNED 2
1532
1533
1534 #define SKIP_OPEN_TABLE 0 // do not open table
1535 #define OPEN_FRM_ONLY 1 // open FRM file only
1536 #define OPEN_FULL_TABLE 2 // open FRM,MYD, MYI files
1537
1538 typedef struct st_field_info
1539 {
1540 /**
1541 This is used as column name.
1542 */
1543 const char* field_name;
1544 /**
1545 For string-type columns, this is the maximum number of
1546 characters. Otherwise, it is the 'display-length' for the column.
1547 For the data type MYSQL_TYPE_DATETIME this field specifies the
1548 number of digits in the fractional part of time value.
1549 */
1550 uint field_length;
1551 /**
1552 This denotes data type for the column. For the most part, there seems to
1553 be one entry in the enum for each SQL data type, although there seem to
1554 be a number of additional entries in the enum.
1555 */
1556 enum enum_field_types field_type;
1557 int value;
1558 /**
1559 This is used to set column attributes. By default, columns are @c NOT
1560 @c NULL and @c SIGNED, and you can deviate from the default
1561 by setting the appopriate flags. You can use either one of the flags
1562 @c MY_I_S_MAYBE_NULL and @cMY_I_S_UNSIGNED or
1563 combine them using the bitwise or operator @c |. Both flags are
1564 defined in table.h.
1565 */
1566 uint field_flags; // Field atributes(maybe_null, signed, unsigned etc.)
1567 const char* old_name;
1568 /**
1569 This should be one of @c SKIP_OPEN_TABLE,
1570 @c OPEN_FRM_ONLY or @c OPEN_FULL_TABLE.
1571 */
1572 uint open_method;
1573 } ST_FIELD_INFO;
1574
1575
1576 struct TABLE_LIST;
1577
1578 typedef struct st_schema_table
1579 {
1580 const char* table_name;
1581 ST_FIELD_INFO *fields_info;
1582 /* Create information_schema table */
1583 TABLE *(*create_table) (THD *thd, TABLE_LIST *table_list);
1584 /* Fill table with data */
1585 int (*fill_table) (THD *thd, TABLE_LIST *tables, Item *cond);
1586 /* Handle fileds for old SHOW */
1587 int (*old_format) (THD *thd, struct st_schema_table *schema_table);
1588 int (*process_table) (THD *thd, TABLE_LIST *tables, TABLE *table,
1589 bool res, LEX_STRING *db_name, LEX_STRING *table_name);
1590 int idx_field1, idx_field2;
1591 bool hidden;
1592 uint i_s_requested_object; /* the object we need to open(TABLE | VIEW) */
1593 } ST_SCHEMA_TABLE;
1594
1595
1596 #define JOIN_TYPE_LEFT 1
1597 #define JOIN_TYPE_RIGHT 2
1598
1599 /**
1600 Strategy for how to process a view or derived table (merge or materialization)
1601 */
1602 enum enum_view_algorithm {
1603 VIEW_ALGORITHM_UNDEFINED = 0,
1604 VIEW_ALGORITHM_TEMPTABLE = 1,
1605 VIEW_ALGORITHM_MERGE = 2
1606 };
1607
1608 #define VIEW_SUID_INVOKER 0
1609 #define VIEW_SUID_DEFINER 1
1610 #define VIEW_SUID_DEFAULT 2
1611
1612 /* view WITH CHECK OPTION parameter options */
1613 #define VIEW_CHECK_NONE 0
1614 #define VIEW_CHECK_LOCAL 1
1615 #define VIEW_CHECK_CASCADED 2
1616
1617 /* result of view WITH CHECK OPTION parameter check */
1618 #define VIEW_CHECK_OK 0
1619 #define VIEW_CHECK_ERROR 1
1620 #define VIEW_CHECK_SKIP 2
1621
1622 /** The threshold size a blob field buffer before it is freed */
1623 #define MAX_TDC_BLOB_SIZE 65536
1624
1625 /**
1626 Struct that describes an expression selected from a derived table or view.
1627 */
1628 struct Field_translator
1629 {
1630 /**
1631 Points to an item that represents the expression.
1632 If the item is determined to be unused, the pointer is set to NULL.
1633 */
1634 Item *item;
1635 /// Name of selected expression
1636 const char *name;
1637 };
1638
1639
1640 /*
1641 Column reference of a NATURAL/USING join. Since column references in
1642 joins can be both from views and stored tables, may point to either a
1643 Field (for tables), or a Field_translator (for views).
1644 */
1645
1646 class Natural_join_column: public Sql_alloc
1647 {
1648 public:
1649 Field_translator *view_field; /* Column reference of merge view. */
1650 Item_field *table_field; /* Column reference of table or temp view. */
1651 TABLE_LIST *table_ref; /* Original base table/view reference. */
1652 /*
1653 True if a common join column of two NATURAL/USING join operands. Notice
1654 that when we have a hierarchy of nested NATURAL/USING joins, a column can
1655 be common at some level of nesting but it may not be common at higher
1656 levels of nesting. Thus this flag may change depending on at which level
1657 we are looking at some column.
1658 */
1659 bool is_common;
1660 public:
1661 Natural_join_column(Field_translator *field_param, TABLE_LIST *tab);
1662 Natural_join_column(Item_field *field_param, TABLE_LIST *tab);
1663 const char *name();
1664 Item *create_item(THD *thd);
1665 Field *field();
1666 const char *table_name();
1667 const char *db_name();
1668 GRANT_INFO *grant();
1669 };
1670
1671
1672 /*
1673 This structure holds the specifications relating to
1674 ALTER user ... PASSWORD EXPIRE ...
1675 */
1676 typedef struct st_lex_alter {
1677 bool update_password_expired_fields;
1678 bool update_password_expired_column;
1679 bool use_default_password_lifetime;
1680 uint16 expire_after_days;
1681 bool update_account_locked_column;
1682 bool account_locked;
1683 } LEX_ALTER;
1684
1685 /*
1686 This structure holds the specifications related to
1687 mysql user and the associated auth details.
1688 */
1689 typedef struct st_lex_user {
1690 LEX_CSTRING user;
1691 LEX_CSTRING host;
1692 LEX_CSTRING plugin;
1693 LEX_CSTRING auth;
1694 /*
1695 The following flags are indicators for the SQL syntax used while
1696 parsing CREATE/ALTER user. While other members are self-explanatory,
1697 'uses_authentication_string_clause' signifies if the password is in
1698 hash form (if the var was set to true) or not.
1699 */
1700 bool uses_identified_by_clause;
1701 bool uses_identified_with_clause;
1702 bool uses_authentication_string_clause;
1703 bool uses_identified_by_password_clause;
1704 LEX_ALTER alter_status;
1705 } LEX_USER;
1706
1707
1708 /**
1709 Derive type of metadata lock to be requested for table used by a DML
1710 statement from the type of THR_LOCK lock requested for this table.
1711 */
1712
mdl_type_for_dml(enum thr_lock_type lock_type)1713 inline enum enum_mdl_type mdl_type_for_dml(enum thr_lock_type lock_type)
1714 {
1715 return lock_type >= TL_WRITE_ALLOW_WRITE ?
1716 (lock_type == TL_WRITE_LOW_PRIORITY ?
1717 MDL_SHARED_WRITE_LOW_PRIO : MDL_SHARED_WRITE) :
1718 MDL_SHARED_READ;
1719 }
1720
1721 /**
1722 Type of table which can be open for an element of table list.
1723 */
1724
1725 enum enum_open_type
1726 {
1727 OT_TEMPORARY_OR_BASE= 0, OT_TEMPORARY_ONLY, OT_BASE_ONLY
1728 };
1729
1730 /**
1731 This structure is used to keep info about possible key for the result table
1732 of a derived table/view.
1733 The 'referenced_by' is the table map of tables to which this possible
1734 key corresponds.
1735 The 'used_field' is a map of fields of which this key consists of.
1736 See also the comment for the TABLE_LIST::update_derived_keys function.
1737 */
1738
1739 class Derived_key: public Sql_alloc {
1740 public:
1741 table_map referenced_by;
1742 Field_map used_fields;
1743 };
1744
1745
1746 /*
1747 Table reference in the FROM clause.
1748
1749 These table references can be of several types that correspond to
1750 different SQL elements. Below we list all types of TABLE_LISTs with
1751 the necessary conditions to determine when a TABLE_LIST instance
1752 belongs to a certain type.
1753
1754 1) table (TABLE_LIST::view == NULL)
1755 - base table
1756 (TABLE_LIST::derived == NULL)
1757 - subquery - TABLE_LIST::table is a temp table
1758 (TABLE_LIST::derived != NULL)
1759 - information schema table
1760 (TABLE_LIST::schema_table != NULL)
1761 NOTICE: for schema tables TABLE_LIST::field_translation may be != NULL
1762 2) view (TABLE_LIST::view != NULL)
1763 - merge (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_MERGE)
1764 also (TABLE_LIST::field_translation != NULL)
1765 - temptable(TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_TEMPTABLE)
1766 also (TABLE_LIST::field_translation == NULL)
1767 3) nested table reference (TABLE_LIST::nested_join != NULL)
1768 - table sequence - e.g. (t1, t2, t3)
1769 TODO: how to distinguish from a JOIN?
1770 - general JOIN
1771 TODO: how to distinguish from a table sequence?
1772 - NATURAL JOIN
1773 (TABLE_LIST::natural_join != NULL)
1774 - JOIN ... USING
1775 (TABLE_LIST::join_using_fields != NULL)
1776 - semi-join
1777 ;
1778 */
1779
1780 struct TABLE_LIST
1781 {
TABLE_LISTTABLE_LIST1782 TABLE_LIST() { memset(this, 0, sizeof(*this)); }
1783
1784 /**
1785 Prepare TABLE_LIST that consists of one table instance to use in
1786 simple_open_and_lock_tables
1787 */
init_one_tableTABLE_LIST1788 inline void init_one_table(const char *db_name_arg,
1789 size_t db_length_arg,
1790 const char *table_name_arg,
1791 size_t table_name_length_arg,
1792 const char *alias_arg,
1793 enum thr_lock_type lock_type_arg,
1794 enum enum_mdl_type mdl_type_arg)
1795 {
1796 new (this) TABLE_LIST;
1797 m_map= 1;
1798 db= (char*) db_name_arg;
1799 db_length= db_length_arg;
1800 table_name= (char*) table_name_arg;
1801 table_name_length= table_name_length_arg;
1802 alias= (char*) alias_arg;
1803 lock_type= lock_type_arg;
1804 MDL_REQUEST_INIT(&mdl_request,
1805 MDL_key::TABLE, db, table_name,
1806 mdl_type_arg,
1807 MDL_TRANSACTION);
1808 callback_func= 0;
1809 opt_hints_table= NULL;
1810 opt_hints_qb= NULL;
1811 }
1812
init_one_tableTABLE_LIST1813 inline void init_one_table(const char *db_name_arg,
1814 size_t db_length_arg,
1815 const char *table_name_arg,
1816 size_t table_name_length_arg,
1817 const char *alias_arg,
1818 enum thr_lock_type lock_type_arg)
1819 {
1820 init_one_table(db_name_arg, db_length_arg,
1821 table_name_arg, table_name_length_arg,
1822 alias_arg, lock_type_arg,
1823 mdl_type_for_dml(lock_type_arg));
1824 }
1825
1826 /// Create a TABLE_LIST object representing a nested join
1827 static TABLE_LIST *new_nested_join(MEM_ROOT *allocator,
1828 const char *alias,
1829 TABLE_LIST *embedding,
1830 List<TABLE_LIST> *belongs_to,
1831 class st_select_lex *select);
1832
join_cond_refTABLE_LIST1833 Item **join_cond_ref() { return &m_join_cond; }
join_condTABLE_LIST1834 Item *join_cond() const { return m_join_cond; }
set_join_condTABLE_LIST1835 void set_join_cond(Item *val)
1836 {
1837 // If optimization has started, it's too late to change m_join_cond.
1838 DBUG_ASSERT(m_join_cond_optim == NULL ||
1839 m_join_cond_optim == (Item*)1);
1840 m_join_cond= val;
1841 }
join_cond_optimTABLE_LIST1842 Item *join_cond_optim() const { return m_join_cond_optim; }
set_join_cond_optimTABLE_LIST1843 void set_join_cond_optim(Item *cond)
1844 {
1845 /*
1846 Either we are setting to "empty", or there must pre-exist a
1847 permanent condition.
1848 */
1849 DBUG_ASSERT(cond == NULL || cond == (Item*)1 ||
1850 m_join_cond != NULL);
1851 m_join_cond_optim= cond;
1852 }
join_cond_optim_refTABLE_LIST1853 Item **join_cond_optim_ref() { return &m_join_cond_optim; }
1854
1855 /// Get the semi-join condition for a semi-join nest, NULL otherwise
sj_condTABLE_LIST1856 Item *sj_cond() const { return m_sj_cond; }
1857
1858 /// Set the semi-join condition for a semi-join nest
set_sj_condTABLE_LIST1859 void set_sj_cond(Item *cond)
1860 {
1861 DBUG_ASSERT(m_sj_cond == NULL);
1862 m_sj_cond= cond;
1863 }
1864
1865 /// Merge tables from a query block into a nested join structure
1866 bool merge_underlying_tables(class st_select_lex *select);
1867
1868 /// Reset table
1869 void reset();
1870
1871 void calc_md5(char *buffer);
1872
1873 /// Evaluate the check option of a view
1874 int view_check_option(THD *thd) const;
1875
1876 /// Cleanup field translations for a view
1877 void cleanup_items();
1878
1879 /**
1880 Check whether the table is a placeholder, ie a derived table, a view or
1881 a schema table.
1882 A table is also considered to be a placeholder if it does not have a
1883 TABLE object for some other reason.
1884 */
is_placeholderTABLE_LIST1885 bool is_placeholder() const
1886 {
1887 return is_view_or_derived() || schema_table || !table;
1888 }
1889
1890 /// Produce a textual identification of this object
1891 void print(THD *thd, String *str, enum_query_type query_type) const;
1892
1893 /// Check which single table inside a view that matches a table map
1894 bool check_single_table(TABLE_LIST **table_ref, table_map map);
1895
1896 /// Allocate a buffer for inserted column values
1897 bool set_insert_values(MEM_ROOT *mem_root);
1898
1899 TABLE_LIST *first_leaf_for_name_resolution();
1900 TABLE_LIST *last_leaf_for_name_resolution();
1901 bool is_leaf_for_name_resolution() const;
1902
1903 /// Return the outermost view this table belongs to, or itself
top_tableTABLE_LIST1904 inline const TABLE_LIST *top_table() const
1905 { return belong_to_view ? belong_to_view : this; }
1906
top_tableTABLE_LIST1907 inline TABLE_LIST *top_table()
1908 {
1909 return
1910 const_cast<TABLE_LIST*>(const_cast<const TABLE_LIST*>(this)->top_table());
1911 }
1912
1913 /// Prepare check option for a view
1914 bool prepare_check_option(THD *thd, bool is_cascaded= false);
1915
1916 /// Merge WHERE condition of view or derived table into outer query
1917 bool merge_where(THD *thd);
1918
1919 /// Prepare replace filter for a view (used for REPLACE command)
1920 bool prepare_replace_filter(THD *thd);
1921
1922 /// Return true if this represents a named view
is_viewTABLE_LIST1923 bool is_view() const
1924 {
1925 return view != NULL;
1926 }
1927
1928 /// Return true if this represents a derived table (an unnamed view)
is_derivedTABLE_LIST1929 bool is_derived() const
1930 {
1931 return derived != NULL && view == NULL;
1932 }
1933
1934 /// Return true if this represents a named view or a derived table
is_view_or_derivedTABLE_LIST1935 bool is_view_or_derived() const
1936 {
1937 return derived != NULL;
1938 }
1939
1940 /// Return true if view or derived table and can be merged
1941 bool is_mergeable() const;
1942
1943 /**
1944 @returns true if materializable table contains one or zero rows.
1945
1946 Returning true implies that the table is materialized during optimization,
1947 so it need not be optimized during execution.
1948 */
1949 bool materializable_is_const() const;
1950
1951 /// Return true if this is a derived table or view that is merged
is_mergedTABLE_LIST1952 bool is_merged() const
1953 {
1954 return effective_algorithm == VIEW_ALGORITHM_MERGE;
1955 }
1956
1957 /// Set table to be merged
set_mergedTABLE_LIST1958 void set_merged()
1959 {
1960 DBUG_ASSERT(effective_algorithm == VIEW_ALGORITHM_UNDEFINED);
1961 effective_algorithm= VIEW_ALGORITHM_MERGE;
1962 }
1963
1964 /// Return true if this is a materializable derived table/view
uses_materializationTABLE_LIST1965 bool uses_materialization() const
1966 {
1967 return effective_algorithm == VIEW_ALGORITHM_TEMPTABLE;
1968 }
1969
1970 /// Set table to be materialized
set_uses_materializationTABLE_LIST1971 void set_uses_materialization()
1972 {
1973 // @todo We should do this only once, but currently we cannot:
1974 //DBUG_ASSERT(effective_algorithm == VIEW_ALGORITHM_UNDEFINED);
1975 DBUG_ASSERT(effective_algorithm != VIEW_ALGORITHM_MERGE);
1976 effective_algorithm= VIEW_ALGORITHM_TEMPTABLE;
1977 }
1978
1979 /// Return true if table is updatable
is_updatableTABLE_LIST1980 bool is_updatable() const { return m_updatable; }
1981
1982 /// Set table as updatable. (per default, a table is non-updatable)
set_updatableTABLE_LIST1983 void set_updatable() { m_updatable= true; }
1984
1985 /// Return true if table is insertable-into
is_insertableTABLE_LIST1986 bool is_insertable() const { return m_insertable; }
1987
1988 /// Set table as insertable-into. (per default, a table is not insertable)
set_insertableTABLE_LIST1989 void set_insertable() { m_insertable= true; }
1990
1991 /**
1992 Return true if this is a view or derived table that is defined over
1993 more than one base table, and false otherwise.
1994 */
is_multiple_tablesTABLE_LIST1995 bool is_multiple_tables() const
1996 {
1997 if (is_view_or_derived())
1998 {
1999 DBUG_ASSERT(is_merged()); // Cannot be a materialized view
2000 return leaf_tables_count() > 1;
2001 }
2002 else
2003 {
2004 DBUG_ASSERT(nested_join == NULL); // Must be a base table
2005 return false;
2006 }
2007 }
2008
2009 /// Return no. of base tables a merged view or derived table is defined over.
2010 uint leaf_tables_count() const;
2011
2012 /// Return first leaf table of a base table or a view/derived table
first_leaf_tableTABLE_LIST2013 TABLE_LIST *first_leaf_table()
2014 {
2015 TABLE_LIST *tr= this;
2016 while (tr->merge_underlying_list)
2017 tr= tr->merge_underlying_list;
2018 return tr;
2019 }
2020
2021 /// Return any leaf table that is not an inner table of an outer join
2022 /// @todo when WL#6570 is implemented, replace with first_leaf_table()
any_outer_leaf_tableTABLE_LIST2023 TABLE_LIST *any_outer_leaf_table()
2024 {
2025 TABLE_LIST *tr= this;
2026 while (tr->merge_underlying_list)
2027 {
2028 tr= tr->merge_underlying_list;
2029 /*
2030 "while" is used, however, an "if" might be sufficient since there is
2031 no more than one inner table in a join nest (with outer_join true).
2032 */
2033 while (tr->outer_join)
2034 tr= tr->next_local;
2035 }
2036 return tr;
2037 }
2038 /**
2039 Set the LEX object of a view (will also define this as a view).
2040 @note: The value 1 is used to indicate a view but without a valid
2041 query object. Use only if the LEX object is not going to
2042 be used in later processing.
2043 */
set_view_queryTABLE_LIST2044 void set_view_query(LEX *lex)
2045 {
2046 view= lex;
2047 }
2048
2049 /// Return the valid LEX object for a view.
view_queryTABLE_LIST2050 LEX *view_query() const
2051 {
2052 DBUG_ASSERT(view != NULL && view != (LEX *)1);
2053 return view;
2054 }
2055
2056 /**
2057 Set the query expression of a derived table or view.
2058 (Will also define this as a derived table, unless it is a named view.)
2059 */
set_derived_unitTABLE_LIST2060 void set_derived_unit(st_select_lex_unit *query_expr)
2061 {
2062 derived= query_expr;
2063 }
2064
2065 /// Return the query expression of a derived table or view.
derived_unitTABLE_LIST2066 st_select_lex_unit *derived_unit() const
2067 {
2068 DBUG_ASSERT(derived);
2069 return derived;
2070 }
2071
2072 /// Set temporary name from underlying temporary table:
set_name_temporaryTABLE_LIST2073 void set_name_temporary()
2074 {
2075 DBUG_ASSERT(is_view_or_derived() && uses_materialization());
2076 table_name= table->s->table_name.str;
2077 table_name_length= table->s->table_name.length;
2078 db= (char *)"";
2079 db_length= 0;
2080 }
2081
2082 /// Reset original name for temporary table.
reset_name_temporaryTABLE_LIST2083 void reset_name_temporary()
2084 {
2085 DBUG_ASSERT(is_view_or_derived() && uses_materialization());
2086 DBUG_ASSERT(db != view_db.str && table_name != view_name.str);
2087 if (is_view())
2088 {
2089 db= view_db.str;
2090 db_length= view_db.length;
2091 }
2092 table_name= view_name.str;
2093 table_name_length= view_name.length;
2094 }
2095
2096 /// Resolve a derived table or view reference
2097 bool resolve_derived(THD *thd, bool apply_semijoin);
2098
2099 /// Optimize the query expression representing a derived table/view
2100 bool optimize_derived(THD *thd);
2101
2102 /// Create result table for a materialized derived table/view
2103 bool create_derived(THD *thd);
2104
2105 /// Materialize derived table
2106 bool materialize_derived(THD *thd);
2107
2108 /// Clean up the query expression for a materialized derived table
2109 bool cleanup_derived();
2110
2111 /// Set wanted privilege for subsequent column privilege checking
2112 void set_want_privilege(ulong want_privilege);
2113
2114 /// Prepare security context for a view
2115 bool prepare_security(THD *thd);
2116
2117 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2118 Security_context *find_view_security_context(THD *thd);
2119 bool prepare_view_securety_context(THD *thd);
2120 #endif
2121
2122 /// Cleanup for re-execution in a prepared statement or a stored procedure.
2123 void reinit_before_use(THD *thd);
2124
2125 /**
2126 Compiles the tagged hints list and fills up TABLE::keys_in_use_for_query,
2127 TABLE::keys_in_use_for_group_by, TABLE::keys_in_use_for_order_by,
2128 TABLE::force_index and TABLE::covering_keys.
2129 */
2130 bool process_index_hints(TABLE *table);
2131
2132 /**
2133 Compare the version of metadata from the previous execution
2134 (if any) with values obtained from the current table
2135 definition cache element.
2136
2137 @sa check_and_update_table_version()
2138 */
is_table_ref_id_equalTABLE_LIST2139 bool is_table_ref_id_equal(TABLE_SHARE *s) const
2140 {
2141 return (m_table_ref_type == s->get_table_ref_type() &&
2142 m_table_ref_version == s->get_table_ref_version());
2143 }
2144
2145 /**
2146 Record the value of metadata version of the corresponding
2147 table definition cache element in this parse tree node.
2148
2149 @sa check_and_update_table_version()
2150 */
set_table_ref_idTABLE_LIST2151 void set_table_ref_id(TABLE_SHARE *s)
2152 { set_table_ref_id(s->get_table_ref_type(), s->get_table_ref_version()); }
2153
set_table_ref_idTABLE_LIST2154 void set_table_ref_id(enum_table_ref_type table_ref_type_arg,
2155 ulonglong table_ref_version_arg)
2156 {
2157 m_table_ref_type= table_ref_type_arg;
2158 m_table_ref_version= table_ref_version_arg;
2159 }
2160
2161 /// returns query block id for derived table, and zero if not derived.
2162 uint query_block_id() const;
2163
2164 /**
2165 @brief Returns the name of the database that the referenced table belongs
2166 to.
2167 */
get_db_nameTABLE_LIST2168 const char *get_db_name() const { return view != NULL ? view_db.str : db; }
2169
2170 /**
2171 @brief Returns the name of the table that this TABLE_LIST represents.
2172
2173 @details The unqualified table name or view name for a table or view,
2174 respectively.
2175 */
get_table_nameTABLE_LIST2176 const char *get_table_name() const
2177 {
2178 return view != NULL ? view_name.str : table_name;
2179 }
2180 int fetch_number_of_rows();
2181 bool update_derived_keys(Field*, Item**, uint);
2182 bool generate_keys();
2183
2184 /// Setup a derived table to use materialization
2185 bool setup_materialized_derived(THD *thd);
2186
2187 bool create_field_translation(THD *thd);
2188
2189 /**
2190 @brief Returns the outer join nest that this TABLE_LIST belongs to, if any.
2191
2192 @details There are two kinds of join nests, outer-join nests and semi-join
2193 nests. This function returns non-NULL in the following cases:
2194 @li 1. If this table/nest is embedded in a nest and this nest IS NOT a
2195 semi-join nest. (In other words, it is an outer-join nest.)
2196 @li 2. If this table/nest is embedded in a nest and this nest IS a
2197 semi-join nest, but this semi-join nest is embedded in another
2198 nest. (This other nest will be an outer-join nest, since all inner
2199 joined nested semi-join nests have been merged in
2200 @c simplify_joins() ).
2201 Note: This function assumes that @c simplify_joins() has been performed.
2202 Before that, join nests will be present for all types of join.
2203
2204 @return outer join nest, or NULL if none.
2205 */
2206
outer_join_nestTABLE_LIST2207 TABLE_LIST *outer_join_nest() const
2208 {
2209 if (!embedding)
2210 return NULL;
2211 if (embedding->sj_cond())
2212 return embedding->embedding;
2213 return embedding;
2214 }
2215 /**
2216 Return true if this table is an inner table of some outer join.
2217
2218 Examine all the embedding join nests of the table.
2219 @note This function works also before redundant join nests have been
2220 eliminated.
2221
2222 @return true if table is an inner table of some outer join, false otherwise.
2223 */
2224
is_inner_table_of_outer_joinTABLE_LIST2225 bool is_inner_table_of_outer_join() const
2226 {
2227 if (outer_join)
2228 return true;
2229 for (TABLE_LIST *emb= embedding; emb; emb= emb->embedding)
2230 {
2231 if (emb->outer_join)
2232 return true;
2233 }
2234 return false;
2235 }
2236
2237 /**
2238 Return the base table entry of an updatable table.
2239 In DELETE and UPDATE, a view used as a target table must be mergeable,
2240 updatable and defined over a single table.
2241 */
updatable_base_tableTABLE_LIST2242 TABLE_LIST *updatable_base_table()
2243 {
2244 TABLE_LIST *tbl= this;
2245 DBUG_ASSERT(tbl->is_updatable() && !tbl->is_multiple_tables());
2246 while (tbl->is_view_or_derived())
2247 {
2248 tbl= tbl->merge_underlying_list;
2249 DBUG_ASSERT(tbl->is_updatable() && !tbl->is_multiple_tables());
2250 }
2251 return tbl;
2252 }
2253
2254
2255 /**
2256 Set granted privileges for a table.
2257
2258 Can be used when generating temporary tables that are also used in
2259 resolver process, such as when generating a UNION table
2260
2261 @param privilege Privileges granted for this table.
2262 */
set_privilegesTABLE_LIST2263 void set_privileges(ulong privilege)
2264 {
2265 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2266 grant.privilege|= privilege;
2267 if (table)
2268 table->grant.privilege|= privilege;
2269 #endif
2270 }
2271 /*
2272 List of tables local to a subquery or the top-level SELECT (used by
2273 SQL_I_List). Considers views as leaves (unlike 'next_leaf' below).
2274 Created at parse time in st_select_lex::add_table_to_list() ->
2275 table_list.link_in_list().
2276 */
2277 TABLE_LIST *next_local;
2278 /* link in a global list of all queries tables */
2279 TABLE_LIST *next_global, **prev_global;
2280 const char *db, *table_name, *alias;
2281 /*
2282 Target tablespace name: When creating or altering tables, this
2283 member points to the tablespace_name in the HA_CREATE_INFO struct.
2284 */
2285 LEX_CSTRING target_tablespace_name;
2286 char *schema_table_name;
2287 char *option; /* Used by cache index */
2288
2289 /** Table level optimizer hints for this table. */
2290 Opt_hints_table *opt_hints_table;
2291 /* Hints for query block of this table. */
2292 Opt_hints_qb *opt_hints_qb;
2293
2294 private:
2295 /**
2296 The members below must be kept aligned so that (1 << m_tableno) == m_map.
2297 A table that takes part in a join operation must be assigned a unique
2298 table number.
2299 */
2300 uint m_tableno; ///< Table number within query block
2301 table_map m_map; ///< Table map, derived from m_tableno
2302 /**
2303 If this table or join nest is the Y in "X [LEFT] JOIN Y ON C", this
2304 member points to C. May also be generated from JOIN ... USING clause.
2305 It may be modified only by permanent transformations (permanent = done
2306 once for all executions of a prepared statement).
2307 */
2308 Item *m_join_cond;
2309 Item *m_sj_cond; ///< Synthesized semijoin condition
2310 public:
2311 /*
2312 (Valid only for semi-join nests) Bitmap of tables that are within the
2313 semi-join (this is different from bitmap of all nest's children because
2314 tables that were pulled out of the semi-join nest remain listed as
2315 nest's children).
2316 */
2317 table_map sj_inner_tables;
2318
2319 /*
2320 During parsing - left operand of NATURAL/USING join where 'this' is
2321 the right operand. After parsing (this->natural_join == this) iff
2322 'this' represents a NATURAL or USING join operation. Thus after
2323 parsing 'this' is a NATURAL/USING join iff (natural_join != NULL).
2324 */
2325 TABLE_LIST *natural_join;
2326 /*
2327 True if 'this' represents a nested join that is a NATURAL JOIN.
2328 For one of the operands of 'this', the member 'natural_join' points
2329 to the other operand of 'this'.
2330 */
2331 bool is_natural_join;
2332 /* Field names in a USING clause for JOIN ... USING. */
2333 List<String> *join_using_fields;
2334 /*
2335 Explicitly store the result columns of either a NATURAL/USING join or
2336 an operand of such a join.
2337 */
2338 List<Natural_join_column> *join_columns;
2339 /* TRUE if join_columns contains all columns of this table reference. */
2340 bool is_join_columns_complete;
2341
2342 /*
2343 List of nodes in a nested join tree, that should be considered as
2344 leaves with respect to name resolution. The leaves are: views,
2345 top-most nodes representing NATURAL/USING joins, subqueries, and
2346 base tables. All of these TABLE_LIST instances contain a
2347 materialized list of columns. The list is local to a subquery.
2348 */
2349 TABLE_LIST *next_name_resolution_table;
2350 /* Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */
2351 List<Index_hint> *index_hints;
2352 TABLE *table; /* opened table */
2353 Table_id table_id; /* table id (from binlog) for opened table */
2354 /*
2355 Query_result for derived table to pass it from table creation to table
2356 filling procedure
2357 */
2358 Query_result_union *derived_result;
2359 /*
2360 Reference from aux_tables to local list entry of main select of
2361 multi-delete statement:
2362 delete t1 from t2,t1 where t1.a<'B' and t2.b=t1.b;
2363 here it will be reference of first occurrence of t1 to second (as you
2364 can see this lists can't be merged)
2365 */
2366 TABLE_LIST *correspondent_table;
2367 private:
2368 /**
2369 This field is set to non-null for derived tables and views. It points
2370 to the SELECT_LEX_UNIT representing the derived table/view.
2371 E.g. for a query
2372
2373 @verbatim SELECT * FROM (SELECT a FROM t1) b @endverbatim
2374
2375 @note Inside views, a subquery in the @c FROM clause is not allowed.
2376 */
2377 st_select_lex_unit *derived; /* SELECT_LEX_UNIT of derived table */
2378
2379 public:
2380 ST_SCHEMA_TABLE *schema_table; /* Information_schema table */
2381 st_select_lex *schema_select_lex;
2382 /*
2383 True when the view field translation table is used to convert
2384 schema table fields for backwards compatibility with SHOW command.
2385 */
2386 bool schema_table_reformed;
2387 Temp_table_param *schema_table_param;
2388 /* link to select_lex where this table was used */
2389 st_select_lex *select_lex;
2390
2391 private:
2392 LEX *view; /* link on VIEW lex for merging */
2393
2394 public:
2395 /// Array of selected expressions from a derived table or view.
2396 Field_translator *field_translation;
2397
2398 /// pointer to element after last one in translation table above
2399 Field_translator *field_translation_end;
2400 /*
2401 List (based on next_local) of underlying tables of this view. I.e. it
2402 does not include the tables of subqueries used in the view. Is set only
2403 for merged views.
2404 */
2405 TABLE_LIST *merge_underlying_list;
2406 /*
2407 - 0 for base tables
2408 - in case of the view it is the list of all (not only underlying
2409 tables but also used in subquery ones) tables of the view.
2410 */
2411 List<TABLE_LIST> *view_tables;
2412 /* most upper view this table belongs to */
2413 TABLE_LIST *belong_to_view;
2414 /*
2415 The view directly referencing this table
2416 (non-zero only for merged underlying tables of a view).
2417 */
2418 TABLE_LIST *referencing_view;
2419 /* Ptr to parent MERGE table list item. See top comment in ha_myisammrg.cc */
2420 TABLE_LIST *parent_l;
2421 /*
2422 Security context (non-zero only for tables which belong
2423 to view with SQL SECURITY DEFINER)
2424 */
2425 Security_context *security_ctx;
2426 /*
2427 This view security context (non-zero only for views with
2428 SQL SECURITY DEFINER)
2429 */
2430 Security_context *view_sctx;
2431 /*
2432 List of all base tables local to a subquery including all view
2433 tables. Unlike 'next_local', this in this list views are *not*
2434 leaves. Created in setup_tables() -> make_leaf_tables().
2435 */
2436 bool allowed_show;
2437 TABLE_LIST *next_leaf;
2438 Item *derived_where_cond; ///< WHERE condition from derived table
2439 Item *check_option; ///< WITH CHECK OPTION condition
2440 Item *replace_filter; ///< Filter for REPLACE command
2441 LEX_STRING select_stmt; ///< text of (CREATE/SELECT) statement
2442 LEX_STRING md5; ///< md5 of query text
2443 LEX_STRING source; ///< source of CREATE VIEW
2444 LEX_CSTRING view_db; ///< saved view database
2445 LEX_CSTRING view_name; ///< saved view name
2446 LEX_STRING timestamp; ///< GMT time stamp of last operation
2447 st_lex_user definer; ///< definer of view
2448 ulonglong file_version; ///< version of file's field set
2449 /**
2450 @note: This field is currently not reliable when read from dictionary:
2451 If an underlying view is changed, updatable_view is not changed,
2452 due to lack of dependency checking in dictionary implementation.
2453 Prefer to use is_updatable() during preparation and optimization.
2454 */
2455 ulonglong updatable_view; ///< VIEW can be updated
2456 /**
2457 @brief The declared algorithm, if this is a view.
2458 @details One of
2459 - VIEW_ALGORITHM_UNDEFINED
2460 - VIEW_ALGORITHM_TEMPTABLE
2461 - VIEW_ALGORITHM_MERGE
2462 @to do Replace with an enum
2463 */
2464 ulonglong algorithm;
2465 ulonglong view_suid; ///< view is suid (TRUE by default)
2466 ulonglong with_check; ///< WITH CHECK OPTION
2467
2468 private:
2469 /// The view algorithm that is actually used, if this is a view.
2470 enum_view_algorithm effective_algorithm;
2471 public:
2472 GRANT_INFO grant;
2473 /* data need by some engines in query cache*/
2474 ulonglong engine_data;
2475 /* call back function for asking handler about caching in query cache */
2476 qc_engine_callback callback_func;
2477 thr_lock_type lock_type;
2478 uint outer_join; /* Which join type */
2479 uint shared; /* Used in multi-upd */
2480 size_t db_length;
2481 size_t table_name_length;
2482 private:
2483 bool m_updatable; /* VIEW/TABLE can be updated */
2484 bool m_insertable; /* VIEW/TABLE can be inserted into */
2485 public:
2486 bool straight; /* optimize with prev table */
2487 bool updating; /* for replicate-do/ignore table */
2488 bool force_index; /* prefer index over table scan */
2489 bool ignore_leaves; /* preload only non-leaf nodes */
2490 table_map dep_tables; /* tables the table depends on */
2491 table_map on_expr_dep_tables; /* tables on expression depends on */
2492 struct st_nested_join *nested_join; /* if the element is a nested join */
2493 TABLE_LIST *embedding; /* nested join containing the table */
2494 List<TABLE_LIST> *join_list;/* join list the table belongs to */
2495 bool cacheable_table; /* stop PS caching */
2496 /* used in multi-upd/views privilege check */
2497 bool table_in_first_from_clause;
2498 /**
2499 Specifies which kind of table should be open for this element
2500 of table list.
2501 */
2502 enum enum_open_type open_type;
2503 /* TRUE if this merged view contain auto_increment field */
2504 bool contain_auto_increment;
2505 /// TRUE <=> VIEW CHECK OPTION condition is processed (also for prep. stmts)
2506 bool check_option_processed;
2507 /// TRUE <=> Filter condition is processed
2508 bool replace_filter_processed;
2509 /* FRMTYPE_ERROR if any type is acceptable */
2510 enum frm_type_enum required_type;
2511 char timestamp_buffer[20]; /* buffer for timestamp (19+1) */
2512 /*
2513 This TABLE_LIST object is just placeholder for prelocking, it will be
2514 used for implicit LOCK TABLES only and won't be used in real statement.
2515 */
2516 bool prelocking_placeholder;
2517 /**
2518 Indicates that if TABLE_LIST object corresponds to the table/view
2519 which requires special handling.
2520 */
2521 enum
2522 {
2523 /* Normal open. */
2524 OPEN_NORMAL= 0,
2525 /* Associate a table share only if the the table exists. */
2526 OPEN_IF_EXISTS,
2527 /*
2528 Associate a table share only if the the table exists.
2529 Also upgrade metadata lock to exclusive if table doesn't exist.
2530 */
2531 OPEN_FOR_CREATE,
2532 /* Don't associate a table share. */
2533 OPEN_STUB
2534 } open_strategy;
2535 bool internal_tmp_table;
2536 /** TRUE if an alias for this table was specified in the SQL. */
2537 bool is_alias;
2538 /** TRUE if the table is referred to in the statement using a fully
2539 qualified name (<db_name>.<table_name>).
2540 */
2541 bool is_fqtn;
2542
2543
2544 /* View creation context. */
2545
2546 View_creation_ctx *view_creation_ctx;
2547
2548 /*
2549 Attributes to save/load view creation context in/from frm-file.
2550
2551 Ther are required only to be able to use existing parser to load
2552 view-definition file. As soon as the parser parsed the file, view
2553 creation context is initialized and the attributes become redundant.
2554
2555 These attributes MUST NOT be used for any purposes but the parsing.
2556 */
2557
2558 LEX_STRING view_client_cs_name;
2559 LEX_STRING view_connection_cl_name;
2560
2561 /*
2562 View definition (SELECT-statement) in the UTF-form.
2563 */
2564
2565 LEX_STRING view_body_utf8;
2566
2567 /* End of view definition context. */
2568 /* List of possible keys. Valid only for materialized derived tables/views. */
2569 List<Derived_key> derived_key_list;
2570
2571 /**
2572 Indicates what triggers we need to pre-load for this TABLE_LIST
2573 when opening an associated TABLE. This is filled after
2574 the parsed tree is created.
2575 */
2576 uint8 trg_event_map;
2577 uint i_s_requested_object;
2578 bool has_db_lookup_value;
2579 bool has_table_lookup_value;
2580 uint table_open_method;
2581 enum enum_schema_table_state schema_table_state;
2582
2583 MDL_request mdl_request;
2584
2585 /// if true, EXPLAIN can't explain view due to insufficient rights.
2586 bool view_no_explain;
2587
2588 /* List to carry partition names from PARTITION (...) clause in statement */
2589 List<String> *partition_names;
2590
2591 /// Set table number
set_tablenoTABLE_LIST2592 void set_tableno(uint tableno)
2593 {
2594 DBUG_ASSERT(tableno < MAX_TABLES);
2595 m_tableno= tableno;
2596 m_map= (table_map)1 << tableno;
2597 }
2598 /// Return table number
tablenoTABLE_LIST2599 uint tableno() const { return m_tableno; }
2600
2601 /// Return table map derived from table number
mapTABLE_LIST2602 table_map map() const
2603 {
2604 DBUG_ASSERT(((table_map)1 << m_tableno) == m_map);
2605 return m_map;
2606 }
2607
2608 private:
2609 /*
2610 A group of members set and used only during JOIN::optimize().
2611 */
2612 /**
2613 Optimized copy of m_join_cond (valid for one single
2614 execution). Initialized by SELECT_LEX::get_optimizable_conditions().
2615 @todo it would be good to reset it in reinit_before_use(), if
2616 reinit_stmt_before_use() had a loop including join nests.
2617 */
2618 Item *m_join_cond_optim;
2619 public:
2620
2621 COND_EQUAL *cond_equal; ///< Used with outer join
2622 /// true <=> this table is a const one and was optimized away.
2623 bool optimized_away;
2624 /**
2625 true <=> all possible keys for a derived table were collected and
2626 could be re-used while statement re-execution.
2627 */
2628 bool derived_keys_ready;
2629 // End of group for optimization
2630
2631 private:
2632 /** See comments for set_metadata_id() */
2633 enum enum_table_ref_type m_table_ref_type;
2634 /** See comments for TABLE_SHARE::get_table_ref_version() */
2635 ulonglong m_table_ref_version;
2636 };
2637
2638
2639 /*
2640 Iterator over the fields of a generic table reference.
2641 */
2642
2643 class Field_iterator: public Sql_alloc
2644 {
2645 public:
Field_iterator()2646 Field_iterator() {} /* Remove gcc warning */
~Field_iterator()2647 virtual ~Field_iterator() {}
2648 virtual void set(TABLE_LIST *)= 0;
2649 virtual void next()= 0;
2650 virtual bool end_of_fields()= 0; /* Return 1 at end of list */
2651 virtual const char *name()= 0;
2652 virtual Item *create_item(THD *)= 0;
2653 virtual Field *field()= 0;
2654 };
2655
2656
2657 /*
2658 Iterator over the fields of a base table, view with temporary
2659 table, or subquery.
2660 */
2661
2662 class Field_iterator_table: public Field_iterator
2663 {
2664 Field **ptr;
2665 public:
Field_iterator_table()2666 Field_iterator_table() :ptr(0) {}
set(TABLE_LIST * table)2667 void set(TABLE_LIST *table) { ptr= table->table->field; }
set_table(TABLE * table)2668 void set_table(TABLE *table) { ptr= table->field; }
next()2669 void next() { ptr++; }
end_of_fields()2670 bool end_of_fields() { return *ptr == 0; }
2671 const char *name();
2672 Item *create_item(THD *thd);
field()2673 Field *field() { return *ptr; }
2674 };
2675
2676
2677 /**
2678 Iterator over the fields of a merged derived table or view.
2679 */
2680
2681 class Field_iterator_view: public Field_iterator
2682 {
2683 Field_translator *ptr, *array_end;
2684 TABLE_LIST *view;
2685 public:
Field_iterator_view()2686 Field_iterator_view() :ptr(0), array_end(0) {}
2687 void set(TABLE_LIST *table);
next()2688 void next() { ptr++; }
end_of_fields()2689 bool end_of_fields() { return ptr == array_end; }
2690 const char *name();
2691 Item *create_item(THD *thd);
item_ptr()2692 Item **item_ptr() {return &ptr->item; }
field()2693 Field *field() { return 0; }
item()2694 inline Item *item() { return ptr->item; }
field_translator()2695 Field_translator *field_translator() { return ptr; }
2696 };
2697
2698
2699 /*
2700 Field_iterator interface to the list of materialized fields of a
2701 NATURAL/USING join.
2702 */
2703
2704 class Field_iterator_natural_join: public Field_iterator
2705 {
2706 List_iterator_fast<Natural_join_column> column_ref_it;
2707 Natural_join_column *cur_column_ref;
2708 public:
Field_iterator_natural_join()2709 Field_iterator_natural_join() :cur_column_ref(NULL) {}
~Field_iterator_natural_join()2710 ~Field_iterator_natural_join() {}
2711 void set(TABLE_LIST *table);
2712 void next();
end_of_fields()2713 bool end_of_fields() { return !cur_column_ref; }
name()2714 const char *name() { return cur_column_ref->name(); }
create_item(THD * thd)2715 Item *create_item(THD *thd) { return cur_column_ref->create_item(thd); }
field()2716 Field *field() { return cur_column_ref->field(); }
column_ref()2717 Natural_join_column *column_ref() { return cur_column_ref; }
2718 };
2719
2720
2721 /*
2722 Generic iterator over the fields of an arbitrary table reference.
2723
2724 DESCRIPTION
2725 This class unifies the various ways of iterating over the columns
2726 of a table reference depending on the type of SQL entity it
2727 represents. If such an entity represents a nested table reference,
2728 this iterator encapsulates the iteration over the columns of the
2729 members of the table reference.
2730
2731 IMPLEMENTATION
2732 The implementation assumes that all underlying NATURAL/USING table
2733 references already contain their result columns and are linked into
2734 the list TABLE_LIST::next_name_resolution_table.
2735 */
2736
2737 class Field_iterator_table_ref: public Field_iterator
2738 {
2739 TABLE_LIST *table_ref, *first_leaf, *last_leaf;
2740 Field_iterator_table table_field_it;
2741 Field_iterator_view view_field_it;
2742 Field_iterator_natural_join natural_join_it;
2743 Field_iterator *field_it;
2744 void set_field_iterator();
2745 public:
Field_iterator_table_ref()2746 Field_iterator_table_ref() :field_it(NULL) {}
2747 void set(TABLE_LIST *table);
2748 void next();
end_of_fields()2749 bool end_of_fields()
2750 { return (table_ref == last_leaf && field_it->end_of_fields()); }
name()2751 const char *name() { return field_it->name(); }
2752 const char *get_table_name();
2753 const char *get_db_name();
2754 GRANT_INFO *grant();
create_item(THD * thd)2755 Item *create_item(THD *thd) { return field_it->create_item(thd); }
field()2756 Field *field() { return field_it->field(); }
2757 Natural_join_column *get_or_create_column_ref(THD *thd, TABLE_LIST *parent_table_ref);
2758 Natural_join_column *get_natural_column_ref();
2759 };
2760
2761 /**
2762 Semijoin_mat_optimize collects data used when calculating the cost of
2763 executing a semijoin operation using a materialization strategy.
2764 It is used during optimization phase only.
2765 */
2766
2767 struct Semijoin_mat_optimize
2768 {
2769 /// Optimal join order calculated for inner tables of this semijoin op.
2770 struct st_position *positions;
2771 /// True if data types allow the MaterializeLookup semijoin strategy
2772 bool lookup_allowed;
2773 /// True if data types allow the MaterializeScan semijoin strategy
2774 bool scan_allowed;
2775 /// Expected #rows in the materialized table
2776 double expected_rowcount;
2777 /// Materialization cost - execute sub-join and write rows to temp.table
2778 Cost_estimate materialization_cost;
2779 /// Cost to make one lookup in the temptable
2780 Cost_estimate lookup_cost;
2781 /// Cost of scanning the materialized table
2782 Cost_estimate scan_cost;
2783 /// Array of pointers to fields in the materialized table.
2784 Item_field **mat_fields;
2785 };
2786
2787
2788 /**
2789 Struct st_nested_join is used to represent how tables are connected through
2790 outer join operations and semi-join operations to form a query block.
2791 Out of the parser, inner joins are also represented by st_nested_join
2792 structs, but these are later flattened out by simplify_joins().
2793 Some outer join nests are also flattened, when it can be determined that
2794 they can be processed as inner joins instead of outer joins.
2795 */
2796 typedef struct st_nested_join
2797 {
st_nested_joinst_nested_join2798 st_nested_join() { memset(this, 0, sizeof(*this)); }
2799
2800 List<TABLE_LIST> join_list; /* list of elements in the nested join */
2801 table_map used_tables; /* bitmap of tables in the nested join */
2802 table_map not_null_tables; /* tables that rejects nulls */
2803 /**
2804 Used for pointing out the first table in the plan being covered by this
2805 join nest. It is used exclusively within make_outerjoin_info().
2806 */
2807 plan_idx first_nested;
2808 /**
2809 Set to true when natural join or using information has been processed.
2810 */
2811 bool natural_join_processed;
2812 /**
2813 Number of tables and outer join nests administered by this nested join
2814 object for the sake of cost analysis. Includes direct member tables as
2815 well as tables included through semi-join nests, but notice that semi-join
2816 nests themselves are not counted.
2817 */
2818 uint nj_total;
2819 /**
2820 Used to count tables in the nested join in 2 isolated places:
2821 1. In make_outerjoin_info().
2822 2. check_interleaving_with_nj/backout_nj_state (these are called
2823 by the join optimizer.
2824 Before each use the counters are zeroed by SELECT_LEX::reset_nj_counters.
2825 */
2826 uint nj_counter;
2827 /**
2828 Bit identifying this nested join. Only nested joins representing the
2829 outer join structure need this, other nests have bit set to zero.
2830 */
2831 nested_join_map nj_map;
2832 /**
2833 Tables outside the semi-join that are used within the semi-join's
2834 ON condition (ie. the subquery WHERE clause and optional IN equalities).
2835 */
2836 table_map sj_depends_on;
2837 /**
2838 Outer non-trivially correlated tables, a true subset of sj_depends_on
2839 */
2840 table_map sj_corr_tables;
2841 /**
2842 Query block id if this struct is generated from a subquery transform.
2843 */
2844 uint query_block_id;
2845
2846 /// Bitmap of which strategies are enabled for this semi-join nest
2847 uint sj_enabled_strategies;
2848
2849 /*
2850 Lists of trivially-correlated expressions from the outer and inner tables
2851 of the semi-join, respectively.
2852 */
2853 List<Item> sj_outer_exprs, sj_inner_exprs;
2854 Semijoin_mat_optimize sjm;
2855 } NESTED_JOIN;
2856
2857
2858 typedef struct st_open_table_list{
2859 struct st_open_table_list *next;
2860 char *db,*table;
2861 uint32 in_use,locked;
2862 } OPEN_TABLE_LIST;
2863
2864
tmp_use_all_columns(TABLE * table,MY_BITMAP * bitmap)2865 static inline my_bitmap_map *tmp_use_all_columns(TABLE *table,
2866 MY_BITMAP *bitmap)
2867 {
2868 my_bitmap_map *old= bitmap->bitmap;
2869 bitmap->bitmap= table->s->all_set.bitmap;// does not repoint last_word_ptr
2870 return old;
2871 }
2872
2873
tmp_restore_column_map(MY_BITMAP * bitmap,my_bitmap_map * old)2874 static inline void tmp_restore_column_map(MY_BITMAP *bitmap,
2875 my_bitmap_map *old)
2876 {
2877 bitmap->bitmap= old;
2878 }
2879
2880 /* The following is only needed for debugging */
2881
dbug_tmp_use_all_columns(TABLE * table,MY_BITMAP * bitmap)2882 static inline my_bitmap_map *dbug_tmp_use_all_columns(TABLE *table,
2883 MY_BITMAP *bitmap)
2884 {
2885 #ifndef DBUG_OFF
2886 return tmp_use_all_columns(table, bitmap);
2887 #else
2888 return 0;
2889 #endif
2890 }
2891
dbug_tmp_restore_column_map(MY_BITMAP * bitmap,my_bitmap_map * old)2892 static inline void dbug_tmp_restore_column_map(MY_BITMAP *bitmap,
2893 my_bitmap_map *old)
2894 {
2895 #ifndef DBUG_OFF
2896 tmp_restore_column_map(bitmap, old);
2897 #endif
2898 }
2899
2900
2901 /*
2902 Variant of the above : handle both read and write sets.
2903 Provide for the possiblity of the read set being the same as the write set
2904 */
dbug_tmp_use_all_columns(TABLE * table,my_bitmap_map ** save,MY_BITMAP * read_set,MY_BITMAP * write_set)2905 static inline void dbug_tmp_use_all_columns(TABLE *table,
2906 my_bitmap_map **save,
2907 MY_BITMAP *read_set,
2908 MY_BITMAP *write_set)
2909 {
2910 #ifndef DBUG_OFF
2911 save[0]= read_set->bitmap;
2912 save[1]= write_set->bitmap;
2913 (void) tmp_use_all_columns(table, read_set);
2914 (void) tmp_use_all_columns(table, write_set);
2915 #endif
2916 }
2917
2918
dbug_tmp_restore_column_maps(MY_BITMAP * read_set,MY_BITMAP * write_set,my_bitmap_map ** old)2919 static inline void dbug_tmp_restore_column_maps(MY_BITMAP *read_set,
2920 MY_BITMAP *write_set,
2921 my_bitmap_map **old)
2922 {
2923 #ifndef DBUG_OFF
2924 tmp_restore_column_map(read_set, old[0]);
2925 tmp_restore_column_map(write_set, old[1]);
2926 #endif
2927 }
2928
2929
2930 size_t max_row_length(TABLE *table, const uchar *data);
2931
2932
2933 void init_mdl_requests(TABLE_LIST *table_list);
2934
2935 int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias,
2936 uint db_stat, uint prgflag, uint ha_open_flags,
2937 TABLE *outparam, bool is_create_table);
2938 TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, const char *key,
2939 size_t key_length);
2940 void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
2941 size_t key_length,
2942 const char *table_name, const char *path);
2943 void free_table_share(TABLE_SHARE *share);
2944
2945
2946 /**
2947 Get the tablespace name for a table.
2948
2949 This function will open the .FRM file for the given TABLE_LIST element
2950 and fill Tablespace_hash_set with the tablespace name used by table and
2951 table partitions, if present. For NDB tables with version before 50120,
2952 the function will ask the SE for the tablespace name, because for these
2953 tables, the tablespace name is not stored in the.FRM file, but only
2954 within the SE itself.
2955
2956 @note The function does *not* consider errors. If the file is not present,
2957 this does not raise an error. The reason is that this function will
2958 be used for tables that may not exist, e.g. in the context of
2959 'DROP TABLE IF EXISTS', which does not care whether the table
2960 exists or not. The function returns success in this case.
2961
2962 @note Strings inserted into hash are allocated in the memory
2963 root of the thd, and will be freed implicitly.
2964
2965 @param thd - Thread context.
2966 @param table - Table from which we read the tablespace names.
2967 @param tablespace_set (OUT)- Hash set to be filled with tablespace names.
2968
2969 @retval true - On failure, especially due to memory allocation errors
2970 and partition string parse errors.
2971 @retval false - On success. Even if tablespaces are not used by table.
2972 */
2973
2974 bool get_table_and_parts_tablespace_names(
2975 THD *thd,
2976 TABLE_LIST *table,
2977 Tablespace_hash_set *tablespace_set);
2978
2979 int open_table_def(THD *thd, TABLE_SHARE *share, uint db_flags);
2980 void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg);
2981 void update_create_info_from_table(HA_CREATE_INFO *info, TABLE *form);
2982 enum_ident_name_check check_and_convert_db_name(LEX_STRING *db,
2983 bool preserve_lettercase);
2984 bool check_column_name(const char *name);
2985 enum_ident_name_check check_table_name(const char *name, size_t length,
2986 bool check_for_path_chars);
2987 int rename_file_ext(const char * from,const char * to,const char * ext);
2988 char *get_field(MEM_ROOT *mem, Field *field);
2989 bool get_field(MEM_ROOT *mem, Field *field, class String *res);
2990
2991 int closefrm(TABLE *table, bool free_share);
2992 int read_string(File file, uchar* *to, size_t length);
2993 void free_blobs(TABLE *table);
2994 void free_blob_buffers_and_reset(TABLE *table, uint32 size);
2995 int set_zone(int nr,int min_zone,int max_zone);
2996 ulong make_new_entry(File file,uchar *fileinfo,TYPELIB *formnames,
2997 const char *newname);
2998 ulong next_io_size(ulong pos);
2999 void append_unescaped(String *res, const char *pos, size_t length);
3000 File create_frm(THD *thd, const char *name, const char *db,
3001 const char *table, uint reclength, uchar *fileinfo,
3002 HA_CREATE_INFO *create_info, uint keys, KEY *key_info);
3003 char *fn_rext(char *name);
3004
3005 /* performance schema */
3006 extern LEX_STRING PERFORMANCE_SCHEMA_DB_NAME;
3007
3008 extern LEX_STRING GENERAL_LOG_NAME;
3009 extern LEX_STRING SLOW_LOG_NAME;
3010
3011 /* information schema */
3012 extern LEX_STRING INFORMATION_SCHEMA_NAME;
3013 extern LEX_STRING MYSQL_SCHEMA_NAME;
3014
3015 /* replication's tables */
3016 extern LEX_STRING RLI_INFO_NAME;
3017 extern LEX_STRING MI_INFO_NAME;
3018 extern LEX_STRING WORKER_INFO_NAME;
3019
is_infoschema_db(const char * name,size_t len)3020 inline bool is_infoschema_db(const char *name, size_t len)
3021 {
3022 return (INFORMATION_SCHEMA_NAME.length == len &&
3023 !my_strcasecmp(system_charset_info,
3024 INFORMATION_SCHEMA_NAME.str, name));
3025 }
3026
is_infoschema_db(const char * name)3027 inline bool is_infoschema_db(const char *name)
3028 {
3029 return !my_strcasecmp(system_charset_info,
3030 INFORMATION_SCHEMA_NAME.str, name);
3031 }
3032
is_perfschema_db(const char * name,size_t len)3033 inline bool is_perfschema_db(const char *name, size_t len)
3034 {
3035 return (PERFORMANCE_SCHEMA_DB_NAME.length == len &&
3036 !my_strcasecmp(system_charset_info,
3037 PERFORMANCE_SCHEMA_DB_NAME.str, name));
3038 }
3039
is_perfschema_db(const char * name)3040 inline bool is_perfschema_db(const char *name)
3041 {
3042 return !my_strcasecmp(system_charset_info,
3043 PERFORMANCE_SCHEMA_DB_NAME.str, name);
3044 }
3045
3046 /**
3047 Check if the table belongs to the P_S, excluding setup and threads tables.
3048
3049 @note Performance Schema tables must be accessible independently of the
3050 LOCK TABLE mode. This function is needed to handle the special case
3051 of P_S tables being used under LOCK TABLE mode.
3052 */
belongs_to_p_s(TABLE_LIST * tl)3053 inline bool belongs_to_p_s(TABLE_LIST *tl)
3054 {
3055 return (!strcmp("performance_schema", tl->db) &&
3056 strcmp(tl->table_name, "threads") &&
3057 strstr(tl->table_name, "setup_") == NULL);
3058 }
3059
3060 TYPELIB *typelib(MEM_ROOT *mem_root, List<String> &strings);
3061
3062 /**
3063 return true if the table was created explicitly.
3064 */
is_user_table(TABLE * table)3065 inline bool is_user_table(TABLE * table)
3066 {
3067 const char *name= table->s->table_name.str;
3068 return strncmp(name, tmp_file_prefix, tmp_file_prefix_length);
3069 }
3070
3071 bool is_simple_order(ORDER *order);
3072
3073 void repoint_field_to_record(TABLE *table, uchar *old_rec, uchar *new_rec);
3074 bool update_generated_write_fields(const MY_BITMAP *bitmap, TABLE *table);
3075 bool update_generated_read_fields(uchar *buf, TABLE *table,
3076 uint active_index= MAX_KEY);
3077
3078 #endif /* MYSQL_CLIENT */
3079
3080 #endif /* TABLE_INCLUDED */
3081