1 #ifndef TABLE_INCLUDED
2 #define TABLE_INCLUDED
3
4 /* Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License, version 2.0,
8 as published by the Free Software Foundation.
9
10 This program is also distributed with certain software (including
11 but not limited to OpenSSL) that is licensed under separate terms,
12 as designated in a particular file or component or in included license
13 documentation. The authors of MySQL hereby grant you an additional
14 permission to link the program and your derivative works with the
15 separately licensed software that they have included with MySQL.
16
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License, version 2.0, for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
25
26 #include <string.h>
27 #include <sys/types.h>
28 #include <string>
29
30 #include "field_types.h"
31 #include "lex_string.h"
32 #include "libbinlogevents/include/table_id.h" // Table_id
33 #include "m_ctype.h"
34 #include "map_helpers.h"
35 #include "mem_root_deque.h"
36 #include "my_alloc.h"
37 #include "my_base.h"
38 #include "my_bitmap.h"
39 #include "my_compiler.h"
40 #include "my_dbug.h"
41 #include "my_inttypes.h"
42 #include "my_sys.h"
43 #include "my_table_map.h"
44 #include "mysql/components/services/mysql_mutex_bits.h"
45 #include "mysql/components/services/psi_table_bits.h"
46 #include "sql/dd/types/foreign_key.h" // dd::Foreign_key::enum_rule
47 #include "sql/enum_query_type.h" // enum_query_type
48 #include "sql/key.h"
49 #include "sql/key_spec.h"
50 #include "sql/mdl.h" // MDL_wait_for_subgraph
51 #include "sql/mem_root_array.h"
52 #include "sql/opt_costmodel.h" // Cost_model_table
53 #include "sql/record_buffer.h" // Record_buffer
54 #include "sql/sql_bitmap.h" // Bitmap
55 #include "sql/sql_const.h"
56 #include "sql/sql_list.h"
57 #include "sql/sql_plist.h"
58 #include "sql/sql_plugin_ref.h"
59 #include "sql/sql_sort.h" // Sort_result
60 #include "thr_lock.h"
61 #include "typelib.h"
62
63 #include "sql/mem_root_array.h"
64
65 class Field;
66
67 namespace histograms {
68 class Histogram;
69 }
70
71 class ACL_internal_schema_access;
72 class ACL_internal_table_access;
73 class COND_EQUAL;
74 class Field_json;
75 /* Structs that defines the TABLE */
76 class File_parser;
77 class Value_generator;
78 class GRANT_TABLE;
79 class Handler_share;
80 class Index_hint;
81 class Item;
82 class Item_field;
83 class Json_diff_vector;
84 class Json_seekable_path;
85 class Json_wrapper;
86 class Opt_hints_qb;
87 class Opt_hints_table;
88 class Query_result_union;
89 class SELECT_LEX;
90 class SELECT_LEX_UNIT;
91 class Security_context;
92 class SortingIterator;
93 class String;
94 class THD;
95 class Table_cache_element;
96 class Table_trigger_dispatcher;
97 class Temp_table_param;
98 class handler;
99 class partition_info;
100 enum enum_stats_auto_recalc : int;
101 enum Value_generator_source : short;
102 enum row_type : int;
103 struct HA_CREATE_INFO;
104 struct LEX;
105 struct NESTED_JOIN;
106 struct Partial_update_info;
107 struct TABLE;
108 struct TABLE_LIST;
109 struct TABLE_SHARE;
110 struct handlerton;
111 typedef int8 plan_idx;
112
113 namespace dd {
114 class Table;
115 class View;
116
117 enum class enum_table_type;
118 } // namespace dd
119 class Common_table_expr;
120
121 class Sql_table_check_constraint;
122 using Sql_table_check_constraint_list =
123 Mem_root_array<Sql_table_check_constraint>;
124
125 class Sql_check_constraint_share;
126 using Sql_check_constraint_share_list =
127 Mem_root_array<Sql_check_constraint_share>;
128
129 typedef Mem_root_array_YY<LEX_CSTRING> Create_col_name_list;
130
131 typedef int64 query_id_t;
132
133 enum class enum_json_diff_operation;
134
135 bool assert_ref_count_is_locked(const TABLE_SHARE *);
136
137 #define store_record(A, B) \
138 memcpy((A)->B, (A)->record[0], (size_t)(A)->s->reclength)
139 #define restore_record(A, B) \
140 memcpy((A)->record[0], (A)->B, (size_t)(A)->s->reclength)
141 #define cmp_record(A, B) \
142 memcmp((A)->record[0], (A)->B, (size_t)(A)->s->reclength)
143
144 #define tmp_file_prefix "#sql" /**< Prefix for tmp tables */
145 #define tmp_file_prefix_length 4
146 #define TMP_TABLE_KEY_EXTRA 8
147 #define PLACEHOLDER_TABLE_ROW_ESTIMATE 2
148
149 /**
150 Enumerate possible types of a table from re-execution
151 standpoint.
152 TABLE_LIST class has a member of this type.
153 At prepared statement prepare, this member is assigned a value
154 as of the current state of the database. Before (re-)execution
155 of a prepared statement, we check that the value recorded at
156 prepare matches the type of the object we obtained from the
157 table definition cache.
158
159 @sa check_and_update_table_version()
160 @sa Execute_observer
161 @sa Prepared_statement::reprepare()
162 */
163
164 enum enum_table_ref_type {
165 /** Initial value set by the parser */
166 TABLE_REF_NULL = 0,
167 TABLE_REF_VIEW,
168 TABLE_REF_BASE_TABLE,
169 TABLE_REF_I_S_TABLE,
170 TABLE_REF_TMP_TABLE
171 };
172
173 /**
174 Enumerate possible status of a identifier name while determining
175 its validity
176 */
177 enum class Ident_name_check { OK, WRONG, TOO_LONG };
178
179 enum rowid_statuses {
180 NO_ROWID_NEEDED,
181 ROWID_PROVIDED_BY_ITERATOR_READ_CALL,
182 NEED_TO_CALL_POSITION_FOR_ROWID
183 };
184
185 /*************************************************************************/
186
187 /**
188 Object_creation_ctx -- interface for creation context of database objects
189 (views, stored routines, events, triggers). Creation context -- is a set
190 of attributes, that should be fixed at the creation time and then be used
191 each time the object is parsed or executed.
192 */
193
194 class Object_creation_ctx {
195 public:
196 Object_creation_ctx *set_n_backup(THD *thd);
197
198 void restore_env(THD *thd, Object_creation_ctx *backup_ctx);
199
200 protected:
Object_creation_ctx()201 Object_creation_ctx() {}
202 virtual Object_creation_ctx *create_backup_ctx(THD *thd) const = 0;
203 virtual void delete_backup_ctx() = 0;
204
205 virtual void change_env(THD *thd) const = 0;
206
207 public:
~Object_creation_ctx()208 virtual ~Object_creation_ctx() {}
209 };
210
211 /*************************************************************************/
212
213 /**
214 Default_object_creation_ctx -- default implementation of
215 Object_creation_ctx.
216 */
217
218 class Default_object_creation_ctx : public Object_creation_ctx {
219 public:
get_client_cs()220 const CHARSET_INFO *get_client_cs() { return m_client_cs; }
221
get_connection_cl()222 const CHARSET_INFO *get_connection_cl() { return m_connection_cl; }
223
224 protected:
225 Default_object_creation_ctx(THD *thd);
226
227 Default_object_creation_ctx(const CHARSET_INFO *client_cs,
228 const CHARSET_INFO *connection_cl);
229
230 protected:
231 virtual Object_creation_ctx *create_backup_ctx(THD *thd) const;
232 virtual void delete_backup_ctx();
233
234 virtual void change_env(THD *thd) const;
235
236 protected:
237 /**
238 client_cs stores the value of character_set_client session variable.
239 The only character set attribute is used.
240
241 Client character set is included into query context, because we save
242 query in the original character set, which is client character set. So,
243 in order to parse the query properly we have to switch client character
244 set on parsing.
245 */
246 const CHARSET_INFO *m_client_cs;
247
248 /**
249 connection_cl stores the value of collation_connection session
250 variable. Both character set and collation attributes are used.
251
252 Connection collation is included into query context, becase it defines
253 the character set and collation of text literals in internal
254 representation of query (item-objects).
255 */
256 const CHARSET_INFO *m_connection_cl;
257 };
258
259 /**
260 View_creation_ctx -- creation context of view objects.
261 */
262
263 class View_creation_ctx : public Default_object_creation_ctx {
264 public:
265 static View_creation_ctx *create(THD *thd);
266
267 static View_creation_ctx *create(THD *thd, TABLE_LIST *view);
268
269 private:
View_creation_ctx(THD * thd)270 View_creation_ctx(THD *thd) : Default_object_creation_ctx(thd) {}
271 };
272
273 /*************************************************************************/
274
275 /** Order clause list element */
276
277 class Item_rollup_group_item;
278
279 struct ORDER {
280 ORDER *next{nullptr};
281 /**
282 Points at the item in the select fields. Note that this means that
283 after resolving, it points into a slice (see JOIN::ref_items),
284 even though the item is not of type Item_ref!
285 */
286 Item **item{nullptr};
287 Item *item_ptr{nullptr}; /* Storage for initial item */
288 Item_rollup_group_item *rollup_item{nullptr};
289
290 enum_order direction{
291 ORDER_NOT_RELEVANT}; /* Requested direction of ordering */
292 bool in_field_list{false}; /* true if in select field list */
293 /**
294 Tells whether this ORDER element was referenced with an alias or with an
295 expression, in the query:
296 SELECT a AS foo GROUP BY foo: true.
297 SELECT a AS foo GROUP BY a: false.
298 */
299 bool used_alias{false};
300 /**
301 When GROUP BY is implemented with a temporary table (i.e. the table takes
302 care to store only unique group rows, table->group != nullptr), each GROUP
303 BY expression is stored in a column of the table, which is
304 'field_in_tmp_table'.
305 Such field may point into table->record[0] (if we only use it to get its
306 value from a tmp table's row), or into 'buff' (if we use it to do index
307 lookup into the tmp table).
308 */
309 Field *field_in_tmp_table{nullptr};
310 char *buff{nullptr}; /* If tmp-table group */
311 table_map used{0}, depend_map{0};
312 bool is_position{false}; /* An item expresses a position in a ORDER clause */
313 bool is_explicit{false}; /* Whether ASC/DESC is explicitly specified */
314 };
315
316 /**
317 State information for internal tables grants.
318 This structure is part of the TABLE_LIST, and is updated
319 during the ACL check process.
320 @sa GRANT_INFO
321 */
322 struct GRANT_INTERNAL_INFO {
323 /** True if the internal lookup by schema name was done. */
324 bool m_schema_lookup_done{false};
325 /** Cached internal schema access. */
326 const ACL_internal_schema_access *m_schema_access{nullptr};
327 /** True if the internal lookup by table name was done. */
328 bool m_table_lookup_done{false};
329 /** Cached internal table access. */
330 const ACL_internal_table_access *m_table_access{nullptr};
331 };
332
333 /**
334 @brief The current state of the privilege checking process for the current
335 user, SQL statement and SQL object.
336
337 @details The privilege checking process is divided into phases depending on
338 the level of the privilege to be checked and the type of object to be
339 accessed. Due to the mentioned scattering of privilege checking
340 functionality, it is necessary to keep track of the state of the process.
341
342 A GRANT_INFO also serves as a cache of the privilege hash tables. Relevant
343 members are grant_table and version.
344 */
345 struct GRANT_INFO {
346 GRANT_INFO();
347 /**
348 @brief A copy of the privilege information regarding the current host,
349 database, object and user.
350
351 @details The version of this copy is found in GRANT_INFO::version.
352 */
353 GRANT_TABLE *grant_table{nullptr};
354 /**
355 @brief Used for cache invalidation when caching privilege information.
356
357 @details The privilege information is stored on disk, with dedicated
358 caches residing in memory: table-level and column-level privileges,
359 respectively, have their own dedicated caches.
360
361 The GRANT_INFO works as a level 1 cache with this member updated to the
362 current value of the global variable @c grant_version (@c static variable
363 in sql_acl.cc). It is updated Whenever the GRANT_INFO is refreshed from
364 the level 2 cache. The level 2 cache is the @c column_priv_hash structure
365 (@c static variable in sql_acl.cc)
366
367 @see grant_version
368 */
369 uint version{0};
370 /**
371 @brief The set of privileges that the current user has fulfilled for a
372 certain host, database, and object.
373
374 @details This field is continually updated throughout the access checking
375 process. In each step the "wanted privilege" is checked against the
376 fulfilled privileges. When/if the intersection of these sets is empty,
377 access is granted.
378
379 The set is implemented as a bitmap, with the bits defined in sql_acl.h.
380 */
381 ulong privilege{0};
382 /** The grant state for internal tables. */
383 GRANT_INTERNAL_INFO m_internal;
384 };
385
386 enum tmp_table_type {
387 NO_TMP_TABLE,
388 NON_TRANSACTIONAL_TMP_TABLE,
389 TRANSACTIONAL_TMP_TABLE,
390 INTERNAL_TMP_TABLE,
391 SYSTEM_TMP_TABLE
392 };
393
394 /**
395 Category of table found in the table share.
396 */
397 enum enum_table_category {
398 /**
399 Unknown value.
400 */
401 TABLE_UNKNOWN_CATEGORY = 0,
402
403 /**
404 Temporary table.
405 The table is visible only in the session.
406 Therefore,
407 - FLUSH TABLES WITH READ LOCK
408 - SET GLOBAL READ_ONLY = ON
409 do not apply to this table.
410 Note that LOCK TABLE t FOR READ/WRITE
411 can be used on temporary tables.
412 Temporary tables are not part of the table cache.
413
414 2016-06-14 Contrary to what's written in these comments, the truth is:
415 - tables created by CREATE TEMPORARY TABLE have TABLE_CATEGORY_USER
416 - tables created by create_tmp_table() (internal ones) have
417 TABLE_CATEGORY_TEMPORARY.
418 ha_innodb.cc relies on this observation (so: grep it). If you clean this
419 up, you may also want to look at 'no_tmp_table'; its enum values' meanings
420 have degraded over time: INTERNAL_TMP_TABLE is not used for some internal
421 tmp tables (derived tables). Unification of both enums would be
422 great. Whatever the result, we need to be able to distinguish the two
423 types of temporary tables above, as usage patterns are more restricted for
424 the second type, and allow more optimizations.
425 */
426 TABLE_CATEGORY_TEMPORARY = 1,
427
428 /**
429 User table.
430 These tables do honor:
431 - LOCK TABLE t FOR READ/WRITE
432 - FLUSH TABLES WITH READ LOCK
433 - SET GLOBAL READ_ONLY = ON
434 User tables are cached in the table cache.
435 */
436 TABLE_CATEGORY_USER = 2,
437
438 /**
439 System table, maintained by the server.
440 These tables do honor:
441 - LOCK TABLE t FOR READ/WRITE
442 - FLUSH TABLES WITH READ LOCK
443 - SET GLOBAL READ_ONLY = ON
444 Typically, writes to system tables are performed by
445 the server implementation, not explicitly be a user.
446 System tables are cached in the table cache.
447 */
448 TABLE_CATEGORY_SYSTEM = 3,
449
450 /**
451 Information schema tables.
452 These tables are an interface provided by the system
453 to inspect the system metadata.
454 These tables do *not* honor:
455 - LOCK TABLE t FOR READ/WRITE
456 - FLUSH TABLES WITH READ LOCK
457 - SET GLOBAL READ_ONLY = ON
458 as there is no point in locking explicitly
459 an INFORMATION_SCHEMA table.
460 Nothing is directly written to information schema tables.
461 Note that this value is not used currently,
462 since information schema tables are not shared,
463 but implemented as session specific temporary tables.
464 */
465 /*
466 TODO: Fixing the performance issues of I_S will lead
467 to I_S tables in the table cache, which should use
468 this table type.
469 */
470 TABLE_CATEGORY_INFORMATION = 4,
471
472 /**
473 Log tables.
474 These tables are an interface provided by the system
475 to inspect the system logs.
476 These tables do *not* honor:
477 - LOCK TABLE t FOR READ/WRITE
478 - FLUSH TABLES WITH READ LOCK
479 - SET GLOBAL READ_ONLY = ON
480 as there is no point in locking explicitly
481 a LOG table.
482 An example of LOG tables are:
483 - mysql.slow_log
484 - mysql.general_log,
485 which *are* updated even when there is either
486 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
487 User queries do not write directly to these tables
488 (there are exceptions for log tables).
489 The server implementation perform writes.
490 Log tables are cached in the table cache.
491 */
492 TABLE_CATEGORY_LOG = 5,
493
494 /**
495 Performance schema tables.
496 These tables are an interface provided by the system
497 to inspect the system performance data.
498 These tables do *not* honor:
499 - LOCK TABLE t FOR READ/WRITE
500 - FLUSH TABLES WITH READ LOCK
501 - SET GLOBAL READ_ONLY = ON
502 as there is no point in locking explicitly
503 a PERFORMANCE_SCHEMA table.
504 An example of PERFORMANCE_SCHEMA tables are:
505 - performance_schema.*
506 which *are* updated (but not using the handler interface)
507 even when there is either
508 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
509 User queries do not write directly to these tables
510 (there are exceptions for SETUP_* tables).
511 The server implementation perform writes.
512 Performance tables are cached in the table cache.
513 */
514 TABLE_CATEGORY_PERFORMANCE = 6,
515
516 /**
517 Replication Information Tables.
518 These tables are used to store replication information.
519 These tables do *not* honor:
520 - LOCK TABLE t FOR READ/WRITE
521 - FLUSH TABLES WITH READ LOCK
522 - SET GLOBAL READ_ONLY = ON
523 as there is no point in locking explicitly
524 a Replication Information table.
525 An example of replication tables are:
526 - mysql.slave_master_info
527 - mysql.slave_relay_log_info,
528 which *are* updated even when there is either
529 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
530 User queries do not write directly to these tables.
531 Replication tables are cached in the table cache.
532 */
533 TABLE_CATEGORY_RPL_INFO = 7,
534
535 /**
536 Gtid Table.
537 The table is used to store gtids.
538 The table does *not* honor:
539 - LOCK TABLE t FOR READ/WRITE
540 - FLUSH TABLES WITH READ LOCK
541 - SET GLOBAL READ_ONLY = ON
542 as there is no point in locking explicitly
543 a Gtid table.
544 An example of gtid_executed table is:
545 - mysql.gtid_executed,
546 which is updated even when there is either
547 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
548 Gtid table is cached in the table cache.
549 */
550 TABLE_CATEGORY_GTID = 8,
551
552 /**
553 A data dictionary table.
554 Table's with this category will skip checking the
555 TABLE_SHARE versions because these table structures
556 are fixed upon server bootstrap.
557 */
558 TABLE_CATEGORY_DICTIONARY = 9
559 };
560 typedef enum enum_table_category TABLE_CATEGORY;
561
562 extern ulong refresh_version;
563
564 struct TABLE_FIELD_TYPE {
565 LEX_CSTRING name;
566 LEX_CSTRING type;
567 LEX_CSTRING cset;
568 };
569
570 struct TABLE_FIELD_DEF {
571 uint count;
572 const TABLE_FIELD_TYPE *field;
573 };
574
575 class Table_check_intact {
576 protected:
577 bool has_keys;
578 virtual void report_error(uint code, const char *fmt, ...) = 0;
579
580 public:
Table_check_intact()581 Table_check_intact() : has_keys(false) {}
~Table_check_intact()582 virtual ~Table_check_intact() {}
583
584 /**
585 Checks whether a table is intact.
586
587 @param thd Session.
588 @param table Table to check.
589 @param table_def Table definition struct.
590 */
591 bool check(THD *thd, TABLE *table, const TABLE_FIELD_DEF *table_def);
592 };
593
594 /**
595 Class representing the fact that some thread waits for table
596 share to be flushed. Is used to represent information about
597 such waits in MDL deadlock detector.
598 */
599
600 class Wait_for_flush : public MDL_wait_for_subgraph {
601 MDL_context *m_ctx;
602 TABLE_SHARE *m_share;
603 uint m_deadlock_weight;
604
605 public:
Wait_for_flush(MDL_context * ctx_arg,TABLE_SHARE * share_arg,uint deadlock_weight_arg)606 Wait_for_flush(MDL_context *ctx_arg, TABLE_SHARE *share_arg,
607 uint deadlock_weight_arg)
608 : m_ctx(ctx_arg),
609 m_share(share_arg),
610 m_deadlock_weight(deadlock_weight_arg) {}
611
get_ctx()612 MDL_context *get_ctx() const { return m_ctx; }
613
614 virtual bool accept_visitor(MDL_wait_for_graph_visitor *dvisitor);
615
616 virtual uint get_deadlock_weight() const;
617
618 /**
619 Pointers for participating in the list of waiters for table share.
620 */
621 Wait_for_flush *next_in_share;
622 Wait_for_flush **prev_in_share;
623 };
624
625 typedef I_P_List<
626 Wait_for_flush,
627 I_P_List_adapter<Wait_for_flush, &Wait_for_flush::next_in_share,
628 &Wait_for_flush::prev_in_share>>
629 Wait_for_flush_list;
630
631 typedef struct Table_share_foreign_key_info {
632 LEX_CSTRING referenced_table_db;
633 LEX_CSTRING referenced_table_name;
634 /**
635 Name of unique key matching FK in parent table, "" if there is no
636 unique key.
637 */
638 LEX_CSTRING unique_constraint_name;
639 dd::Foreign_key::enum_rule update_rule, delete_rule;
640 uint columns;
641 /**
642 Arrays with names of referencing columns of the FK.
643 */
644 LEX_CSTRING *column_name;
645 } TABLE_SHARE_FOREIGN_KEY_INFO;
646
647 typedef struct Table_share_foreign_key_parent_info {
648 LEX_CSTRING referencing_table_db;
649 LEX_CSTRING referencing_table_name;
650 dd::Foreign_key::enum_rule update_rule, delete_rule;
651 } TABLE_SHARE_FOREIGN_KEY_PARENT_INFO;
652
653 /**
654 This structure is shared between different table objects. There is one
655 instance of table share per one table in the database.
656 */
657
658 struct TABLE_SHARE {
659 TABLE_SHARE() = default;
660
661 /**
662 Create a new TABLE_SHARE with the given version number.
663 @param version the version of the TABLE_SHARE
664 @param secondary set to true if the TABLE_SHARE represents a table
665 in a secondary storage engine
666 */
TABLE_SHARETABLE_SHARE667 TABLE_SHARE(unsigned long version, bool secondary)
668 : m_version(version), m_secondary_engine(secondary) {}
669
670 /*
671 A map of [uint, Histogram] values, where the key is the field index. The
672 map is populated with any histogram statistics when it is loaded/created.
673 */
674 malloc_unordered_map<uint, const histograms::Histogram *> *m_histograms{
675 nullptr};
676
677 /**
678 Find the histogram for the given field index.
679
680 @param field_index the index of the field we want to find a histogram for
681
682 @retval nullptr if no histogram is found
683 @retval a pointer to a histogram if one is found
684 */
685 const histograms::Histogram *find_histogram(uint field_index) const;
686
687 /** Category of this table. */
688 TABLE_CATEGORY table_category{TABLE_UNKNOWN_CATEGORY};
689
690 /* hash of field names (contains pointers to elements of field array) */
691 collation_unordered_map<std::string, Field **> *name_hash{nullptr};
692 MEM_ROOT mem_root;
693 TYPELIB keynames; /* Pointers to keynames */
694 TYPELIB *intervals{nullptr}; /* pointer to interval info */
695 mysql_mutex_t LOCK_ha_data; /* To protect access to ha_data */
696 TABLE_SHARE *next{nullptr}, **prev{nullptr}; /* Link to unused shares */
697 /**
698 Array of table_cache_instances pointers to elements of table caches
699 respresenting this table in each of Table_cache instances.
700 Allocated along with the share itself in alloc_table_share().
701 Each element of the array is protected by Table_cache::m_lock in the
702 corresponding Table_cache. False sharing should not be a problem in
703 this case as elements of this array are supposed to be updated rarely.
704 */
705 Table_cache_element **cache_element{nullptr};
706
707 /* The following is copied to each TABLE on OPEN */
708 Field **field{nullptr};
709 Field **found_next_number_field{nullptr};
710 KEY *key_info{nullptr}; /* data of keys defined for the table */
711 uint *blob_field{nullptr}; /* Index to blobs in Field arrray*/
712
713 uchar *default_values{nullptr}; /* row with default values */
714 LEX_STRING comment{nullptr, 0}; /* Comment about table */
715 LEX_STRING compress{nullptr, 0}; /* Compression algorithm */
716 LEX_STRING encrypt_type{nullptr, 0}; /* encryption algorithm */
717
718 /** Secondary storage engine. */
719 LEX_CSTRING secondary_engine{nullptr, 0};
720
721 const CHARSET_INFO *table_charset{
722 nullptr}; /* Default charset of string fields */
723
724 MY_BITMAP all_set;
725 /*
726 Key which is used for looking-up table in table cache and in the list
727 of thread's temporary tables. Has the form of:
728 "database_name\0table_name\0" + optional part for temporary tables.
729
730 Note that all three 'table_cache_key', 'db' and 'table_name' members
731 must be set (and be non-zero) for tables in table cache. They also
732 should correspond to each other.
733 To ensure this one can use set_table_cache() methods.
734 */
735 LEX_CSTRING table_cache_key{nullptr, 0};
736 LEX_CSTRING db{nullptr, 0}; /* Pointer to db */
737 LEX_CSTRING table_name{nullptr, 0}; /* Table name (for open) */
738 LEX_STRING path{nullptr, 0}; /* Path to .frm file (from datadir) */
739 LEX_CSTRING normalized_path{nullptr, 0}; /* unpack_filename(path) */
740 LEX_STRING connect_string{nullptr, 0};
741
742 LEX_CSTRING engine_attribute = EMPTY_CSTR;
743 LEX_CSTRING secondary_engine_attribute = EMPTY_CSTR;
744
745 /**
746 The set of indexes that are not disabled for this table. I.e. it excludes
747 indexes disabled by `ALTER TABLE ... DISABLE KEYS`, however it does
748 include invisible indexes. The data dictionary populates this bitmap.
749 */
750 Key_map keys_in_use;
751
752 /// The set of visible and enabled indexes for this table.
753 Key_map visible_indexes;
754 Key_map keys_for_keyread;
755 ha_rows min_rows{0}, max_rows{0}; /* create information */
756 ulong avg_row_length{0}; /* create information */
757 ulong mysql_version{0}; /* 0 if .frm is created before 5.0 */
758 ulong reclength{0}; /* Recordlength */
759 ulong stored_rec_length{0}; /* Stored record length
760 (no generated-only generated fields) */
761
762 plugin_ref db_plugin{nullptr}; /* storage engine plugin */
db_typeTABLE_SHARE763 inline handlerton *db_type() const /* table_type for handler */
764 {
765 // DBUG_ASSERT(db_plugin);
766 return db_plugin ? plugin_data<handlerton *>(db_plugin) : NULL;
767 }
768 /**
769 Value of ROW_FORMAT option for the table as provided by user.
770 Can be different from the real row format used by the storage
771 engine. ROW_TYPE_DEFAULT value indicates that no explicit
772 ROW_FORMAT was specified for the table. @sa real_row_type.
773 */
774 enum row_type row_type = {}; // Zero-initialized to ROW_TYPE_DEFAULT
775 /** Real row format used for the table by the storage engine. */
776 enum row_type real_row_type = {}; // Zero-initialized to ROW_TYPE_DEFAULT
777 tmp_table_type tmp_table{NO_TMP_TABLE};
778
779 /**
780 Only for internal temporary tables.
781 Count of TABLEs (having this TABLE_SHARE) which have a "handler"
782 (table->file!=nullptr).
783 */
784 uint tmp_handler_count{0};
785
786 uint key_block_size{0}; /* create key_block_size, if used */
787 uint stats_sample_pages{0}; /* number of pages to sample during
788 stats estimation, if used, otherwise 0. */
789 enum_stats_auto_recalc
790 stats_auto_recalc{}; /* Automatic recalc of stats.
791 Zero-initialized to HA_STATS_AUTO_RECALC_DEFAULT
792 */
793 uint null_bytes{0}, last_null_bit_pos{0};
794 uint fields{0}; /* Number of fields */
795 uint rec_buff_length{0}; /* Size of table->record[] buffer */
796 uint keys{0}; /* Number of keys defined for the table*/
797 uint key_parts{0}; /* Number of key parts of all keys
798 defined for the table
799 */
800 uint max_key_length{0}; /* Length of the longest key */
801 uint max_unique_length{0}; /* Length of the longest unique key */
802 uint total_key_length{0};
803 uint null_fields{0}; /* number of null fields */
804 uint blob_fields{0}; /* number of blob fields */
805 uint varchar_fields{0}; /* number of varchar fields */
806 /**
807 For materialized derived tables; @see add_derived_key().
808 'first' means: having the lowest position in key_info.
809 */
810 uint first_unused_tmp_key{0};
811 /**
812 For materialized derived tables: maximum size of key_info array. Used for
813 debugging purpose only.
814 */
815 uint max_tmp_keys{0};
816
817 /**
818 Bitmap with flags representing some of table options/attributes.
819
820 @sa HA_OPTION_PACK_RECORD, HA_OPTION_PACK_KEYS, ...
821
822 @note This is basically copy of HA_CREATE_INFO::table_options bitmap
823 at the time of table opening/usage.
824 */
825 uint db_create_options{0};
826 /**
827 Bitmap with flags representing some of table options/attributes which
828 are in use by storage engine.
829
830 @note db_options_in_use is normally copy of db_create_options but can
831 be overriden by SE. E.g. MyISAM does this at handler::open() and
832 hander::info() time.
833 */
834 uint db_options_in_use{0};
835 uint rowid_field_offset{0}; /* Field_nr +1 to rowid field */
836 /* Primary key index number, used in TABLE::key_info[] */
837 uint primary_key{0};
838 uint next_number_index{0}; /* autoincrement key number */
839 uint next_number_key_offset{0}; /* autoinc keypart offset in a key */
840 uint next_number_keypart{0}; /* autoinc keypart number in a key */
841 bool error{false}; /* error during open_table_def() */
842 uint column_bitmap_size{0};
843 /// Number of generated fields
844 uint vfields{0};
845 /// Number of fields having the default value generated
846 uint gen_def_field_count{0};
847 bool system{false}; /* Set if system table (one record) */
848 bool db_low_byte_first{false}; /* Portable row format */
849 bool crashed{false};
850 bool is_view{false};
851 bool m_open_in_progress{false}; /* True: alloc'ed, false: def opened */
852 Table_id table_map_id; /* for row-based replication */
853
854 /*
855 Cache for row-based replication table share checks that does not
856 need to be repeated. Possible values are: -1 when cache value is
857 not calculated yet, 0 when table *shall not* be replicated, 1 when
858 table *may* be replicated.
859 */
860 int cached_row_logging_check{0};
861
862 /*
863 Storage media to use for this table (unless another storage
864 media has been specified on an individual column - in versions
865 where that is supported)
866 */
867 ha_storage_media default_storage_media{HA_SM_DEFAULT};
868
869 /* Name of the tablespace used for this table */
870 const char *tablespace{nullptr};
871
872 /**
873 Partition meta data. Allocated from TABLE_SHARE::mem_root,
874 created when reading from the dd tables,
875 used as template for each TABLE instance.
876 The reason for having it on the TABLE_SHARE is to be able to reuse the
877 partition_elements containing partition names, values etc. instead of
878 allocating them for each TABLE instance.
879 TODO: Currently it is filled in and then only used for generating
880 the partition_info_str. The plan is to clone/copy/reference each
881 TABLE::part_info instance from it.
882 What is missing before it can be completed:
883 1) The partition expression, currently created only during parsing which
884 also needs the current TABLE instance as context for name resolution etc.
885 2) The partition values, currently the DD stores them as text so it needs
886 to be converted to field images (which is now done by first parsing the
887 value text into an Item, then saving the Item result/value into a field
888 and then finally copy the field image).
889 */
890 partition_info *m_part_info{nullptr};
891 // TODO: Remove these four variables:
892 /**
893 Filled in when reading from frm.
894 This can simply be removed when removing the .frm support,
895 since it is already stored in the new DD.
896 */
897 bool auto_partitioned{false};
898 /**
899 Storing the full partitioning clause (PARTITION BY ...) which is used
900 when creating new partition_info object for each new TABLE object by
901 parsing this string.
902 These two will be needed until the missing parts above is fixed.
903 */
904 char *partition_info_str{nullptr};
905 uint partition_info_str_len{0};
906
907 /**
908 Cache the checked structure of this table.
909
910 The pointer data is used to describe the structure that
911 a instance of the table must have. Each element of the
912 array specifies a field that must exist on the table.
913
914 The pointer is cached in order to perform the check only
915 once -- when the table is loaded from the disk.
916 */
917 const TABLE_FIELD_DEF *table_field_def_cache{nullptr};
918
919 /** Main handler's share */
920 Handler_share *ha_share{nullptr};
921
922 /** Instrumentation for this table share. */
923 PSI_table_share *m_psi{nullptr};
924
925 /**
926 List of tickets representing threads waiting for the share to be flushed.
927 */
928 Wait_for_flush_list m_flush_tickets;
929
930 /**
931 View object holding view definition read from DD. This object is not
932 cached, and is owned by the table share. We are not able to read it
933 on demand since we may then get a cache miss while holding LOCK_OPEN.
934 */
935 const dd::View *view_object{nullptr};
936
937 /**
938 Data-dictionary object describing explicit temporary table represented
939 by this share. NULL for other table types (non-temporary tables, internal
940 temporary tables). This object is owned by TABLE_SHARE and should be
941 deleted along with it.
942 */
943 dd::Table *tmp_table_def{nullptr};
944
945 /// For materialized derived tables; @see add_derived_key().
946 SELECT_LEX *owner_of_possible_tmp_keys{nullptr};
947
948 /**
949 Arrays with descriptions of foreign keys in which this table participates
950 as child or parent. We only cache in them information from dd::Table object
951 which is sufficient for use by prelocking algorithm/to check if table is
952 referenced by a foreign key.
953 */
954 uint foreign_keys{0};
955 TABLE_SHARE_FOREIGN_KEY_INFO *foreign_key{nullptr};
956 uint foreign_key_parents{0};
957 TABLE_SHARE_FOREIGN_KEY_PARENT_INFO *foreign_key_parent{nullptr};
958
959 // List of check constraint share instances.
960 Sql_check_constraint_share_list *check_constraint_share_list{nullptr};
961
962 /**
963 Set share's table cache key and update its db and table name appropriately.
964
965 @param key_buff Buffer with already built table cache key to be
966 referenced from share.
967 @param key_length Key length.
968
969 @note
970 Since 'key_buff' buffer will be referenced from share it should has same
971 life-time as share itself.
972 This method automatically ensures that TABLE_SHARE::table_name/db have
973 appropriate values by using table cache key as their source.
974 */
975
set_table_cache_keyTABLE_SHARE976 void set_table_cache_key(char *key_buff, size_t key_length) {
977 table_cache_key.str = key_buff;
978 table_cache_key.length = key_length;
979 /*
980 Let us use the fact that the key is "db/0/table_name/0" + optional
981 part for temporary tables.
982 */
983 db.str = table_cache_key.str;
984 db.length = strlen(db.str);
985 table_name.str = db.str + db.length + 1;
986 table_name.length = strlen(table_name.str);
987 }
988
989 /**
990 Set share's table cache key and update its db and table name appropriately.
991
992 @param key_buff Buffer to be used as storage for table cache key
993 (should be at least key_length bytes).
994 @param key Value for table cache key.
995 @param key_length Key length.
996
997 NOTE
998 Since 'key_buff' buffer will be used as storage for table cache key
999 it should has same life-time as share itself.
1000 */
1001
set_table_cache_keyTABLE_SHARE1002 void set_table_cache_key(char *key_buff, const char *key, size_t key_length) {
1003 memcpy(key_buff, key, key_length);
1004 set_table_cache_key(key_buff, key_length);
1005 }
1006
get_table_def_versionTABLE_SHARE1007 ulonglong get_table_def_version() const { return table_map_id; }
1008
1009 /** Returns the version of this TABLE_SHARE. */
versionTABLE_SHARE1010 unsigned long version() const { return m_version; }
1011
1012 /**
1013 Set the version of this TABLE_SHARE to zero. This marks the
1014 TABLE_SHARE for automatic removal from the table definition cache
1015 once it is no longer referenced.
1016 */
1017 void clear_version();
1018
1019 /** Is this table share being expelled from the table definition cache? */
has_old_versionTABLE_SHARE1020 bool has_old_version() const { return version() != refresh_version; }
1021
1022 /**
1023 Convert unrelated members of TABLE_SHARE to one enum
1024 representing its type.
1025
1026 @todo perhaps we need to have a member instead of a function.
1027 */
get_table_ref_typeTABLE_SHARE1028 enum enum_table_ref_type get_table_ref_type() const {
1029 if (is_view) return TABLE_REF_VIEW;
1030 switch (tmp_table) {
1031 case NO_TMP_TABLE:
1032 return TABLE_REF_BASE_TABLE;
1033 case SYSTEM_TMP_TABLE:
1034 return TABLE_REF_I_S_TABLE;
1035 default:
1036 return TABLE_REF_TMP_TABLE;
1037 }
1038 }
1039 /**
1040 Return a table metadata version.
1041 * for base tables and views, we return table_map_id.
1042 It is assigned from a global counter incremented for each
1043 new table loaded into the table definition cache (TDC).
1044 * for temporary tables it's table_map_id again. But for
1045 temporary tables table_map_id is assigned from
1046 thd->query_id. The latter is assigned from a thread local
1047 counter incremented for every new SQL statement. Since
1048 temporary tables are thread-local, each temporary table
1049 gets a unique id.
1050 * for everything else (e.g. information schema tables),
1051 the version id is zero.
1052
1053 This choice of version id is a large compromise
1054 to have a working prepared statement validation in 5.1. In
1055 future version ids will be persistent, as described in WL#4180.
1056
1057 Let's try to explain why and how this limited solution allows
1058 to validate prepared statements.
1059
1060 Firstly, sets (in mathematical sense) of version numbers
1061 never intersect for different table types. Therefore,
1062 version id of a temporary table is never compared with
1063 a version id of a view, and vice versa.
1064
1065 Secondly, for base tables and views, we know that each DDL flushes
1066 the respective share from the TDC. This ensures that whenever
1067 a table is altered or dropped and recreated, it gets a new
1068 version id.
1069 Unfortunately, since elements of the TDC are also flushed on
1070 LRU basis, this choice of version ids leads to false positives.
1071 E.g. when the TDC size is too small, we may have a SELECT
1072 * FROM INFORMATION_SCHEMA.TABLES flush all its elements, which
1073 in turn will lead to a validation error and a subsequent
1074 reprepare of all prepared statements. This is
1075 considered acceptable, since as long as prepared statements are
1076 automatically reprepared, spurious invalidation is only
1077 a performance hit. Besides, no better simple solution exists.
1078
1079 For temporary tables, using thd->query_id ensures that if
1080 a temporary table was altered or recreated, a new version id is
1081 assigned. This suits validation needs very well and will perhaps
1082 never change.
1083
1084 Metadata of information schema tables never changes.
1085 Thus we can safely assume 0 for a good enough version id.
1086
1087 Finally, by taking into account table type, we always
1088 track that a change has taken place when a view is replaced
1089 with a base table, a base table is replaced with a temporary
1090 table and so on.
1091
1092 @retval 0 For schema tables, DD tables and system views.
1093 non-0 For bases tables, views and temporary tables.
1094
1095 @sa TABLE_LIST::is_table_ref_id_equal()
1096 */
1097 ulonglong get_table_ref_version() const;
1098
1099 /** Determine if the table is missing a PRIMARY KEY. */
is_missing_primary_keyTABLE_SHARE1100 bool is_missing_primary_key() const {
1101 DBUG_ASSERT(primary_key <= MAX_KEY);
1102 return primary_key == MAX_KEY;
1103 }
1104
1105 uint find_first_unused_tmp_key(const Key_map &k);
1106
1107 bool visit_subgraph(Wait_for_flush *waiting_ticket,
1108 MDL_wait_for_graph_visitor *gvisitor);
1109
1110 bool wait_for_old_version(THD *thd, struct timespec *abstime,
1111 uint deadlock_weight);
1112
1113 /**
1114 The set of indexes that the optimizer may use when creating an execution
1115 plan.
1116 */
1117 Key_map usable_indexes(const THD *thd) const;
1118
1119 /** Release resources and free memory occupied by the table share. */
1120 void destroy();
1121
1122 /**
1123 How many TABLE objects use this TABLE_SHARE.
1124 @return the reference count
1125 */
ref_countTABLE_SHARE1126 unsigned int ref_count() const {
1127 DBUG_ASSERT(assert_ref_count_is_locked(this));
1128 return m_ref_count;
1129 }
1130
1131 /**
1132 Increment the reference count by one.
1133 @return the new reference count
1134 */
increment_ref_countTABLE_SHARE1135 unsigned int increment_ref_count() {
1136 DBUG_ASSERT(assert_ref_count_is_locked(this));
1137 DBUG_ASSERT(!m_open_in_progress);
1138 return ++m_ref_count;
1139 }
1140
1141 /**
1142 Decrement the reference count by one.
1143 @return the new reference count
1144 */
decrement_ref_countTABLE_SHARE1145 unsigned int decrement_ref_count() {
1146 DBUG_ASSERT(assert_ref_count_is_locked(this));
1147 DBUG_ASSERT(!m_open_in_progress);
1148 DBUG_ASSERT(m_ref_count > 0);
1149 return --m_ref_count;
1150 }
1151
1152 /// Does this TABLE_SHARE represent a table in a primary storage engine?
is_primary_engineTABLE_SHARE1153 bool is_primary_engine() const { return !m_secondary_engine; }
1154
1155 /// Does this TABLE_SHARE represent a table in a secondary storage engine?
is_secondary_engineTABLE_SHARE1156 bool is_secondary_engine() const { return m_secondary_engine; }
1157
1158 /**
1159 Does this TABLE_SHARE represent a primary table that has a shadow
1160 copy in a secondary storage engine?
1161 */
has_secondary_engineTABLE_SHARE1162 bool has_secondary_engine() const {
1163 return is_primary_engine() && secondary_engine.str != nullptr;
1164 }
1165
1166 /** Returns whether this table is referenced by a foreign key. */
is_referenced_by_foreign_keyTABLE_SHARE1167 bool is_referenced_by_foreign_key() const { return foreign_key_parents != 0; }
1168
1169 private:
1170 /// How many TABLE objects use this TABLE_SHARE.
1171 unsigned int m_ref_count{0};
1172
1173 /**
1174 TABLE_SHARE version, if changed the TABLE_SHARE must be reopened.
1175 NOTE: The TABLE_SHARE will not be reopened during LOCK TABLES in
1176 close_thread_tables!!!
1177 */
1178 unsigned long m_version{0};
1179
1180 /// Does this TABLE_SHARE represent a table in a secondary storage engine?
1181 bool m_secondary_engine{false};
1182 };
1183
1184 /**
1185 Class is used as a BLOB field value storage for
1186 intermediate GROUP_CONCAT results. Used only for
1187 GROUP_CONCAT with DISTINCT or ORDER BY options.
1188 */
1189
1190 class Blob_mem_storage {
1191 private:
1192 MEM_ROOT storage;
1193 /**
1194 Sign that some values were cut
1195 during saving into the storage.
1196 */
1197 bool truncated_value;
1198
1199 public:
1200 Blob_mem_storage();
1201 ~Blob_mem_storage();
1202
reset()1203 void reset() {
1204 free_root(&storage, MYF(MY_MARK_BLOCKS_FREE));
1205 truncated_value = false;
1206 }
1207 /**
1208 Fuction creates duplicate of 'from'
1209 string in 'storage' MEM_ROOT.
1210
1211 @param from string to copy
1212 @param length string length
1213
1214 @retval Pointer to the copied string.
1215 @retval 0 if an error occurred.
1216 */
store(const char * from,size_t length)1217 char *store(const char *from, size_t length) {
1218 return (char *)memdup_root(&storage, from, length);
1219 }
set_truncated_value(bool is_truncated_value)1220 void set_truncated_value(bool is_truncated_value) {
1221 truncated_value = is_truncated_value;
1222 }
is_truncated_value()1223 bool is_truncated_value() const { return truncated_value; }
1224 };
1225
1226 /**
1227 Class that represents a single change to a column value in partial
1228 update of a JSON column.
1229 */
1230 class Binary_diff final {
1231 /// The offset of the start of the change.
1232 size_t m_offset;
1233
1234 /// The size of the portion that is to be replaced.
1235 size_t m_length;
1236
1237 public:
1238 /**
1239 Create a new Binary_diff object.
1240
1241 @param offset the offset of the beginning of the change
1242 @param length the length of the section that is to be replaced
1243 */
Binary_diff(size_t offset,size_t length)1244 Binary_diff(size_t offset, size_t length)
1245 : m_offset(offset), m_length(length) {}
1246
1247 /// @return the offset of the changed data
offset()1248 size_t offset() const { return m_offset; }
1249
1250 /// @return the length of the changed data
length()1251 size_t length() const { return m_length; }
1252
1253 /**
1254 Get a pointer to the start of the replacement data.
1255
1256 @param field the column that is updated
1257 @return a pointer to the start of the replacement data
1258 */
1259 const char *new_data(const Field *field) const;
1260
1261 /**
1262 Get a pointer to the start of the old data to be replaced.
1263
1264 @param field the column that is updated
1265 @return a pointer to the start of old data to be replaced.
1266 */
1267 const char *old_data(const Field *field) const;
1268 };
1269
1270 /**
1271 Vector of Binary_diff objects.
1272
1273 The Binary_diff objects in the vector should be ordered on offset, and none
1274 of the diffs should be overlapping or adjacent.
1275 */
1276 using Binary_diff_vector = Mem_root_array<Binary_diff>;
1277
1278 /**
1279 Flags for TABLE::m_status (maximum 8 bits).
1280 The flags define the state of the row buffer in TABLE::record[0].
1281 */
1282 /**
1283 STATUS_NOT_STARTED is set when table is not accessed yet.
1284 Neither STATUS_NOT_FOUND nor STATUS_NULL_ROW can be set when this flag is set.
1285 */
1286 #define STATUS_NOT_STARTED 1
1287 /**
1288 Means we were searching for a row and didn't find it. This is used by
1289 storage engines (@see handler::index_read_map()) and the executor, both
1290 when doing an exact row lookup and advancing a scan (no more rows in range).
1291 */
1292 #define STATUS_NOT_FOUND 2
1293 /// Reserved for use by multi-table update. Means the row has been updated.
1294 #define STATUS_UPDATED 16
1295 /**
1296 Means that table->null_row is set. This is an artificial NULL-filled row
1297 (one example: in outer join, if no match has been found in inner table).
1298 */
1299 #define STATUS_NULL_ROW 32
1300 /// Reserved for use by multi-table delete. Means the row has been deleted.
1301 #define STATUS_DELETED 64
1302
1303 /* Information for one open table */
1304 enum index_hint_type { INDEX_HINT_IGNORE, INDEX_HINT_USE, INDEX_HINT_FORCE };
1305
1306 /* Bitmap of table's fields */
1307 typedef Bitmap<MAX_FIELDS> Field_map;
1308
1309 /*
1310 NOTE: Despite being a struct (for historical reasons), TABLE has
1311 a nontrivial destructor.
1312 */
1313 struct TABLE {
1314 TABLE_SHARE *s{nullptr};
1315 handler *file{nullptr};
1316 TABLE *next{nullptr}, *prev{nullptr};
1317
1318 private:
1319 /**
1320 Links for the lists of used/unused TABLE objects for the particular
1321 table in the specific instance of Table_cache (in other words for
1322 specific Table_cache_element object).
1323 Declared as private to avoid direct manipulation with those objects.
1324 One should use methods of I_P_List template instead.
1325 */
1326 TABLE *cache_next{nullptr}, **cache_prev{nullptr};
1327
1328 /*
1329 Give Table_cache_element access to the above two members to allow
1330 using them for linking TABLE objects in a list.
1331 */
1332 friend class Table_cache_element;
1333
1334 public:
1335 /**
1336 A bitmap marking the hidden generated columns that exists for functional
1337 indexes.
1338 */
1339 MY_BITMAP fields_for_functional_indexes;
1340
1341 THD *in_use{nullptr}; /* Which thread uses this */
1342 Field **field{nullptr}; /* Pointer to fields */
1343 /// Count of hidden fields, if internal temporary table; 0 otherwise.
1344 uint hidden_field_count{0};
1345
1346 uchar *record[2]{nullptr, nullptr}; /* Pointer to records */
1347 uchar *write_row_record{nullptr}; /* Used as optimisation in
1348 THD::write_row */
1349 uchar *insert_values{nullptr}; /* used by INSERT ... UPDATE */
1350
1351 /// Buffer for use in multi-row reads. Initially empty.
1352 Record_buffer m_record_buffer{0, 0, nullptr};
1353
1354 /*
1355 Map of keys that can be used to retrieve all data from this table
1356 needed by the query without reading the row.
1357 */
1358 Key_map covering_keys;
1359 Key_map quick_keys;
1360
1361 /* Merge keys are all keys that had a column reffered to in the query */
1362 Key_map merge_keys;
1363
1364 /*
1365 possible_quick_keys is a superset of quick_keys to use with EXPLAIN of
1366 JOIN-less commands (single-table UPDATE and DELETE).
1367
1368 When explaining regular JOINs, we use JOIN_TAB::keys to output the
1369 "possible_keys" column value. However, it is not available for
1370 single-table UPDATE and DELETE commands, since they don't use JOIN
1371 optimizer at the top level. OTOH they directly use the range optimizer,
1372 that collects all keys usable for range access here.
1373 */
1374 Key_map possible_quick_keys;
1375
1376 /*
1377 A set of keys that can be used in the query that references this
1378 table.
1379
1380 All indexes disabled on the table's TABLE_SHARE (see TABLE::s) will be
1381 subtracted from this set upon instantiation. Thus for any TABLE t it holds
1382 that t.keys_in_use_for_query is a subset of t.s.keys_in_use. Generally we
1383 must not introduce any new keys here (see setup_tables).
1384
1385 The set is implemented as a bitmap.
1386 */
1387 Key_map keys_in_use_for_query;
1388 /* Map of keys that can be used to calculate GROUP BY without sorting */
1389 Key_map keys_in_use_for_group_by;
1390 /* Map of keys that can be used to calculate ORDER BY without sorting */
1391 Key_map keys_in_use_for_order_by;
1392 KEY *key_info{nullptr}; /* data of keys defined for the table */
1393
1394 Field *next_number_field{nullptr}; /* Set if next_number is activated */
1395 Field *found_next_number_field{nullptr}; /* Set on open */
1396 /// Pointer to generated columns
1397 Field **vfield{nullptr};
1398 /// Pointer to fields having the default value generated
1399 Field **gen_def_fields_ptr{nullptr};
1400 /// Field used by unique constraint
1401 Field *hash_field{nullptr};
1402 Field *fts_doc_id_field{nullptr}; /* Set if FTS_DOC_ID field is present */
1403
1404 /* Table's triggers, 0 if there are no of them */
1405 Table_trigger_dispatcher *triggers{nullptr};
1406 TABLE_LIST *pos_in_table_list{nullptr}; /* Element referring to this table */
1407 /* Position in thd->locked_table_list under LOCK TABLES */
1408 TABLE_LIST *pos_in_locked_tables{nullptr};
1409 ORDER *group{nullptr};
1410 const char *alias{nullptr}; ///< alias or table name
1411 uchar *null_flags{nullptr}; ///< Pointer to the null flags of record[0]
1412 uchar *null_flags_saved{
1413 nullptr}; ///< Saved null_flags while null_row is true
1414
1415 /* containers */
1416 MY_BITMAP def_read_set, def_write_set, tmp_set, pack_row_tmp_set;
1417 /*
1418 Bitmap of fields that one or more query condition refers to. Only
1419 used if optimizer_condition_fanout_filter is turned 'on'.
1420 Currently, only the WHERE clause and ON clause of inner joins is
1421 taken into account but not ON conditions of outer joins.
1422 Furthermore, HAVING conditions apply to groups and are therefore
1423 not useful as table condition filters.
1424 */
1425 MY_BITMAP cond_set;
1426
1427 /**
1428 Bitmap of table fields (columns), which are explicitly set in the
1429 INSERT INTO statement. It is declared here to avoid memory allocation
1430 on MEM_ROOT).
1431
1432 @sa fields_set_during_insert.
1433 */
1434 MY_BITMAP def_fields_set_during_insert;
1435
1436 /**
1437 Set over all columns that the optimizer intends to read. This is used
1438 for two purposes: First, to tell the storage engine which ones it needs
1439 to populate. (In particular, NDB can save a lot of bandwidth here.)
1440 Second, functions that need to store and restore rows, such as hash join
1441 or filesort, need to know which ones to keep.
1442
1443 Set during resolving; every field that gets resolved, sets its own bit
1444 in the read set. In some cases, we switch the read set around during
1445 various phases; note that it is a pointer.
1446
1447 In addition, for binary logging purposes, the bitmaps are set according
1448 to the settings of @@binlog_row_image. Therefore, for logging purposes,
1449 some additional fields, to those specified by the optimizer, may be
1450 flagged in the read and write sets.
1451 @c TABLE::mark_columns_per_binlog_row_image for additional details.
1452 */
1453 MY_BITMAP *read_set{nullptr};
1454
1455 MY_BITMAP *write_set{nullptr};
1456
1457 /**
1458 A pointer to the bitmap of table fields (columns), which are explicitly set
1459 in the INSERT INTO statement.
1460
1461 fields_set_during_insert points to def_fields_set_during_insert
1462 for base (non-temporary) tables. In other cases, it is NULL.
1463 Triggers can not be defined for temporary tables, so this bitmap does not
1464 matter for temporary tables.
1465
1466 @sa def_fields_set_during_insert.
1467 */
1468 MY_BITMAP *fields_set_during_insert{nullptr};
1469
1470 /*
1471 The ID of the query that opened and is using this table. Has different
1472 meanings depending on the table type.
1473
1474 Temporary tables:
1475
1476 table->query_id is set to thd->query_id for the duration of a statement
1477 and is reset to 0 once it is closed by the same statement. A non-zero
1478 table->query_id means that a statement is using the table even if it's
1479 not the current statement (table is in use by some outer statement).
1480
1481 Non-temporary tables:
1482
1483 Under pre-locked or LOCK TABLES mode: query_id is set to thd->query_id
1484 for the duration of a statement and is reset to 0 once it is closed by
1485 the same statement. A non-zero query_id is used to control which tables
1486 in the list of pre-opened and locked tables are actually being used.
1487 */
1488 query_id_t query_id{0};
1489
1490 /*
1491 For each key that has quick_keys.is_set(key) == true: estimate of #records
1492 and max #key parts that range access would use.
1493 */
1494 ha_rows quick_rows[MAX_KEY]{0};
1495
1496 /* Bitmaps of key parts that =const for the entire join. */
1497 key_part_map const_key_parts[MAX_KEY]{0};
1498
1499 uint quick_key_parts[MAX_KEY]{0};
1500 uint quick_n_ranges[MAX_KEY]{0};
1501
1502 /*
1503 Estimate of number of records that satisfy SARGable part of the table
1504 condition, or table->file->records if no SARGable condition could be
1505 constructed.
1506 This value is used by join optimizer as an estimate of number of records
1507 that will pass the table condition (condition that depends on fields of
1508 this table and constants)
1509 */
1510 ha_rows quick_condition_rows{0};
1511
1512 uint lock_position{0}; /* Position in MYSQL_LOCK.table */
1513 uint lock_data_start{0}; /* Start pos. in MYSQL_LOCK.locks */
1514 uint lock_count{0}; /* Number of locks */
1515 uint db_stat{0}; /* mode of file as in handler.h */
1516 int current_lock{0}; /* Type of lock on table */
1517
1518 // List of table check constraints.
1519 Sql_table_check_constraint_list *table_check_constraint_list{nullptr};
1520
1521 private:
1522 /**
1523 If true, this table is inner w.r.t. some outer join operation, all columns
1524 are nullable (in the query), and null_row may be true.
1525 */
1526 bool nullable{false};
1527
1528 uint8 m_status{0}; /* What's in record[0] */
1529 public:
1530 /*
1531 If true, the current table row is considered to have all columns set to
1532 NULL, including columns declared as "not null" (see nullable).
1533 @todo make it private, currently join buffering changes it through a pointer
1534 */
1535 bool null_row{false};
1536
1537 bool copy_blobs{false}; /* copy_blobs when storing */
1538
1539 /*
1540 TODO: Each of the following flags take up 8 bits. They can just as easily
1541 be put into one single unsigned long and instead of taking up 18
1542 bytes, it would take up 4.
1543 */
1544 bool force_index{false};
1545
1546 /**
1547 Flag set when the statement contains FORCE INDEX FOR ORDER BY
1548 See TABLE_LIST::process_index_hints().
1549 */
1550 bool force_index_order{false};
1551
1552 /**
1553 Flag set when the statement contains FORCE INDEX FOR GROUP BY
1554 See TABLE_LIST::process_index_hints().
1555 */
1556 bool force_index_group{false};
1557 /**
1558 Whether this is a temporary table that already has a UNIQUE index (removing
1559 duplicate rows on insert), so that the optimizer does not need to run
1560 DISTINCT itself.
1561 */
1562 bool is_distinct{false};
1563 bool const_table{false};
1564 /// True if writes to this table should not write rows and just write keys.
1565 bool no_rows{false};
1566
1567 /**
1568 If set, the optimizer has found that row retrieval should access index
1569 tree only.
1570 */
1571 bool key_read{false};
1572 /**
1573 Certain statements which need the full row, set this to ban index-only
1574 access.
1575 */
1576 bool no_keyread{false};
1577 /**
1578 If set, indicate that the table is not replicated by the server.
1579 */
1580 bool no_replicate{false};
1581 bool fulltext_searched{false};
1582 bool no_cache{false};
1583 /* To signal that the table is associated with a HANDLER statement */
1584 bool open_by_handler{false};
1585 /**
1586 To indicate that value of the auto_increment field was provided
1587 explicitly by the user or from some other source (e.g. in case of
1588 INSERT ... SELECT, ALTER TABLE or LOAD DATA) and not as default
1589 or result of conversion from NULL value.
1590
1591 @note Since auto_increment fields are always non-NULL we can't find
1592 out using methods of Field class if 0 value stored in such field
1593 was provided explicitly or is result of applying default/conversion
1594 from NULL value. In the former case no new auto_increment value
1595 needs to be generated in MODE_NO_AUTO_VALUE_ON_ZERO mode, while
1596 the latter cases require new value generation. Hence the need
1597 for this flag.
1598 @note Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode and only
1599 by handler::write_row().
1600 */
1601 bool autoinc_field_has_explicit_non_null_value{false};
1602 bool alias_name_used{false}; /* true if table_name is alias */
1603 bool get_fields_in_item_tree{false}; /* Signal to fix_field */
1604 /**
1605 This table must be reopened and is not to be reused.
1606 NOTE: The TABLE will not be reopened during LOCK TABLES in
1607 close_thread_tables!!!
1608 */
1609 bool m_needs_reopen{false};
1610
1611 private:
1612 /**
1613 For tmp tables. true <=> tmp table has been instantiated.
1614 Also indicates that table was successfully opened since
1615 we immediately delete tmp tables which we fail to open.
1616 */
1617 bool created{false};
1618
1619 public:
1620 /// For a materializable derived or SJ table: true if has been materialized
1621 bool materialized{false};
1622 struct /* field connections */
1623 {
1624 class JOIN_TAB *join_tab{nullptr};
1625 class QEP_TAB *qep_tab{nullptr};
1626 thr_lock_type lock_type{TL_UNLOCK}; /* How table is used */
1627 thr_locked_row_action locked_row_action{THR_DEFAULT};
1628 bool not_exists_optimize{false};
1629 /*
1630 true <=> range optimizer found that there is no rows satisfying
1631 table conditions.
1632 */
1633 bool impossible_range{false};
1634 } reginfo;
1635
1636 /**
1637 @todo This member should not be declared in-line. That makes it
1638 impossible for any function that does memory allocation to take a const
1639 reference to a TABLE object.
1640 */
1641 MEM_ROOT mem_root;
1642 /**
1643 Initialized in Item_func_group_concat::setup for appropriate
1644 temporary table if GROUP_CONCAT is used with ORDER BY | DISTINCT
1645 and BLOB field count > 0.
1646 */
1647 Blob_mem_storage *blob_storage{nullptr};
1648
1649 /**
1650 Not owned by the TABLE; used only from filesort_free_buffers().
1651 See comments on SortingIterator::CleanupAfterQuery().
1652 */
1653 SortingIterator *sorting_iterator{nullptr};
1654 SortingIterator *duplicate_removal_iterator{nullptr};
1655
1656 /**
1657 The result of applying a unique opertion (by row ID) to the table, if done.
1658 In particular, this is done in some forms of index merge.
1659 */
1660 Sort_result unique_result;
1661 partition_info *part_info{nullptr}; /* Partition related information */
1662 /* If true, all partitions have been pruned away */
1663 bool all_partitions_pruned_away{false};
1664 MDL_ticket *mdl_ticket{nullptr};
1665
1666 private:
1667 /// Cost model object for operations on this table
1668 Cost_model_table m_cost_model;
1669 #ifndef DBUG_OFF
1670 /**
1671 Internal tmp table sequential number. Increased in the order of
1672 creation. Used for debugging purposes when many tmp tables are used
1673 during execution (e.g several windows with window functions)
1674 */
1675 uint tmp_table_seq_id{0};
1676 #endif
1677 public:
1678 void reset();
1679 void init(THD *thd, TABLE_LIST *tl);
1680 bool init_tmp_table(THD *thd, TABLE_SHARE *share, MEM_ROOT *m_root,
1681 CHARSET_INFO *charset, const char *alias, Field **fld,
1682 uint *blob_fld, bool is_virtual);
1683 bool fill_item_list(List<Item> *item_list) const;
1684 void reset_item_list(List<Item> *item_list) const;
1685 void clear_column_bitmaps(void);
1686 void prepare_for_position(void);
1687
1688 void mark_column_used(Field *field, enum enum_mark_columns mark);
1689 void mark_columns_used_by_index_no_reset(uint index, MY_BITMAP *map,
1690 uint key_parts = 0) const;
1691 void mark_columns_used_by_index(uint index);
1692 void mark_auto_increment_column(void);
1693 void mark_columns_needed_for_update(THD *thd, bool mark_binlog_columns);
1694 void mark_columns_needed_for_delete(THD *thd);
1695 void mark_columns_needed_for_insert(THD *thd);
1696 void mark_columns_per_binlog_row_image(THD *thd);
1697 void mark_generated_columns(bool is_update);
1698 void mark_gcol_in_maps(const Field *field);
1699 void mark_check_constraint_columns(bool is_update);
1700 void column_bitmaps_set(MY_BITMAP *read_set_arg, MY_BITMAP *write_set_arg);
column_bitmaps_set_no_signalTABLE1701 inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg,
1702 MY_BITMAP *write_set_arg) {
1703 read_set = read_set_arg;
1704 write_set = write_set_arg;
1705 }
use_all_columnsTABLE1706 inline void use_all_columns() {
1707 column_bitmaps_set(&s->all_set, &s->all_set);
1708 }
default_column_bitmapsTABLE1709 inline void default_column_bitmaps() {
1710 read_set = &def_read_set;
1711 write_set = &def_write_set;
1712 }
1713 /** Should this instance of the table be reopened? */
needs_reopenTABLE1714 inline bool needs_reopen() { return !db_stat || m_needs_reopen; }
1715 /// @returns first non-hidden column
visible_field_ptrTABLE1716 Field **visible_field_ptr() const { return field + hidden_field_count; }
1717 /// @returns count of visible fields
visible_field_countTABLE1718 uint visible_field_count() const { return s->fields - hidden_field_count; }
1719 bool alloc_tmp_keys(uint key_count, bool modify_share);
1720 bool add_tmp_key(Field_map *key_parts, char *key_name, bool invisible,
1721 bool modify_share);
1722 void copy_tmp_key(int old_idx, bool modify_share);
1723 void drop_unused_tmp_keys(bool modify_share);
1724
1725 void set_keyread(bool flag);
1726
1727 /**
1728 Check whether the given index has a virtual generated columns.
1729
1730 @param index_no the given index to check
1731
1732 @returns true if if index is defined over at least one virtual generated
1733 column
1734 */
index_contains_some_virtual_gcolTABLE1735 inline bool index_contains_some_virtual_gcol(uint index_no) const {
1736 DBUG_ASSERT(index_no < s->keys);
1737 return key_info[index_no].flags & HA_VIRTUAL_GEN_KEY;
1738 }
1739 bool update_const_key_parts(Item *conds);
1740
1741 bool check_read_removal(uint index);
1742
default_values_offsetTABLE1743 ptrdiff_t default_values_offset() const {
1744 return (ptrdiff_t)(s->default_values - record[0]);
1745 }
1746
1747 /// Return true if table is instantiated, and false otherwise.
is_createdTABLE1748 bool is_created() const { return created; }
1749
1750 /**
1751 Set the table as "created", and enable flags in storage engine
1752 that could not be enabled without an instantiated table.
1753 */
1754 void set_created();
1755 /**
1756 Set the contents of table to be "deleted", ie "not created", after having
1757 deleted the contents.
1758 */
set_deletedTABLE1759 void set_deleted() { created = materialized = false; }
1760 /// Set table as nullable, ie it is inner wrt some outer join
set_nullableTABLE1761 void set_nullable() { nullable = true; }
1762
1763 /// Return whether table is nullable
is_nullableTABLE1764 bool is_nullable() const { return nullable; }
1765
1766 /// @return true if table contains one or more generated columns
has_gcolTABLE1767 bool has_gcol() const { return vfield; }
1768
1769 /**
1770 Life cycle of the row buffer is as follows:
1771 - The initial state is "not started".
1772 - When reading a row through the storage engine handler, the status is set
1773 as "has row" or "no row", depending on whether a row was found or not.
1774 The "not started" state is cleared, as well as the "null row" state,
1775 the updated state and the deleted state.
1776 - When making a row available in record[0], make sure to update row status
1777 similarly to how the storage engine handler does it.
1778 - If a NULL-extended row is needed in join execution, the "null row" state
1779 is set. Note that this can be combined with "has row" if a row was read
1780 but condition on it was evaluated to false (happens for single-row
1781 lookup), or "no row" if no more rows could be read.
1782 Note also that for the "null row" state, the NULL bits inside the
1783 row are set to one, so the row inside the row buffer is no longer usable,
1784 unless the NULL bits are saved in a separate buffer.
1785 - The "is updated" and "is deleted" states are set when row is updated or
1786 deleted, respectively.
1787 */
1788 /// Set status for row buffer as "not started"
set_not_startedTABLE1789 void set_not_started() {
1790 m_status = STATUS_NOT_STARTED | STATUS_NOT_FOUND;
1791 null_row = false;
1792 }
1793
1794 /// @return true if a row operation has been done
is_startedTABLE1795 bool is_started() const { return !(m_status & STATUS_NOT_STARTED); }
1796
1797 /// Set status for row buffer: contains row
set_found_rowTABLE1798 void set_found_row() {
1799 m_status = 0;
1800 null_row = false;
1801 }
1802
1803 /**
1804 Set status for row buffer: contains no row. This is set when
1805 - A lookup operation finds no row
1806 - A scan operation scans past the last row of the range.
1807 - An error in generating key values before calling storage engine.
1808 */
set_no_rowTABLE1809 void set_no_row() {
1810 m_status = STATUS_NOT_FOUND;
1811 null_row = false;
1812 }
1813
1814 /**
1815 Set "row found" status from handler result
1816
1817 @param status 0 if row was found, <> 0 if row was not found
1818 */
set_row_status_from_handlerTABLE1819 void set_row_status_from_handler(int status) {
1820 m_status = status ? STATUS_NOT_FOUND : 0;
1821 null_row = false;
1822 }
1823
1824 /**
1825 Set current row as "null row", for use in null-complemented outer join.
1826 The row buffer may or may not contain a valid row.
1827 set_null_row() and reset_null_row() are used by the join executor to
1828 signal the presence or absence of a NULL-extended row for an outer joined
1829 table. Null rows may also be used to specify rows that are all NULL in
1830 grouing operations.
1831 @note this is a destructive operation since the NULL value bit vector
1832 is overwritten. Caching operations must be aware of this.
1833 */
set_null_rowTABLE1834 void set_null_row() {
1835 null_row = true;
1836 m_status |= STATUS_NULL_ROW;
1837 if (s->null_bytes > 0) memset(null_flags, 255, s->null_bytes);
1838 }
1839
1840 /// Clear "null row" status for the current row
reset_null_rowTABLE1841 void reset_null_row() {
1842 null_row = false;
1843 m_status &= ~STATUS_NULL_ROW;
1844 }
1845
1846 /// Set "updated" property for the current row
set_updated_rowTABLE1847 void set_updated_row() {
1848 DBUG_ASSERT(is_started() && has_row());
1849 m_status |= STATUS_UPDATED;
1850 }
1851
1852 /// Set "deleted" property for the current row
set_deleted_rowTABLE1853 void set_deleted_row() {
1854 DBUG_ASSERT(is_started() && has_row());
1855 m_status |= STATUS_DELETED;
1856 }
1857
1858 /// @return true if there is a row in row buffer
has_rowTABLE1859 bool has_row() const { return !(m_status & STATUS_NOT_FOUND); }
1860
1861 /// @return true if current row is null-extended
has_null_rowTABLE1862 bool has_null_row() const { return null_row; }
1863
1864 /// @return true if current row has been updated (multi-table update)
has_updated_rowTABLE1865 bool has_updated_row() const { return m_status & STATUS_UPDATED; }
1866
1867 /// @return true if current row has been deleted (multi-table delete)
has_deleted_rowTABLE1868 bool has_deleted_row() const { return m_status & STATUS_DELETED; }
1869
1870 /// Save the NULL flags of the current row into the designated buffer
save_null_flagsTABLE1871 void save_null_flags() {
1872 if (s->null_bytes > 0) memcpy(null_flags_saved, null_flags, s->null_bytes);
1873 }
1874
1875 /// Restore the NULL flags of the current row from the designated buffer
restore_null_flagsTABLE1876 void restore_null_flags() {
1877 if (s->null_bytes > 0) memcpy(null_flags, null_flags_saved, s->null_bytes);
1878 }
1879
1880 /// Empties internal temporary table (deletes rows, closes scan)
1881 bool empty_result_table();
1882
1883 /**
1884 Initialize the optimizer cost model.
1885
1886 This function should be called each time a new query is started.
1887
1888 @param cost_model_server the main cost model object for the query
1889 */
init_cost_modelTABLE1890 void init_cost_model(const Cost_model_server *cost_model_server) {
1891 m_cost_model.init(cost_model_server, this);
1892 }
1893
1894 /**
1895 Return the cost model object for this table.
1896 */
cost_modelTABLE1897 const Cost_model_table *cost_model() const { return &m_cost_model; }
1898
1899 /**
1900 Fix table's generated columns' (GC) and/or default expressions
1901
1902 @details When a table is opened from the dictionary, the Value Generator
1903 expressions are fixed during opening (see fix_value_generators_fields()).
1904 After query execution, Item::cleanup() is called on them
1905 (see cleanup_value_generator_items()). When the table is opened from the
1906 table cache, the Value Generetor(s) need to be fixed again and this
1907 function does that.
1908
1909 @param[in] thd the current thread
1910 @return true if error, else false
1911 */
1912 bool refix_value_generator_items(THD *thd);
1913
1914 /**
1915 Helper function for refix_value_generator_items() that fixes one column's
1916 expression (be it GC or default expression) and check constraint expression.
1917
1918 @param[in] thd current thread
1919 @param[in,out] g_expr the expression who's items needs to be fixed
1920 @param[in] table the table it blongs to
1921 @param[in] field the column it blongs to (for GC and Default
1922 expression).
1923 @param[in] source Source of value generator(a generated column, a
1924 regular column with generated default value or
1925 a check constraint).
1926 @param[in] source_name Name of the source (generated column, a reguler
1927 column with generated default value or a check
1928 constraint).
1929
1930 @return true if error, else false
1931 */
1932 bool refix_inner_value_generator_items(THD *thd, Value_generator *g_expr,
1933 Field *field, TABLE *table,
1934 Value_generator_source source,
1935 const char *source_name);
1936
1937 /**
1938 Clean any state in items associated with generated columns to be ready for
1939 the next statement.
1940 */
1941 void cleanup_value_generator_items();
1942
1943 #ifndef DBUG_OFF
set_tmp_table_seq_idTABLE1944 void set_tmp_table_seq_id(uint arg) { tmp_table_seq_id = arg; }
1945 #endif
1946 /**
1947 Update covering keys depending on max read key length.
1948
1949 Update available covering keys for the table, based on a constrained field
1950 and the identified covering prefix keys: If the matched part of field is
1951 longer than the index prefix,
1952 the prefix index cannot be used as a covering index.
1953
1954 @param[in] field Pointer to field object
1955 @param[in] key_read_length Max read key length
1956 @param[in] covering_prefix_keys Covering prefix keys
1957 */
1958 void update_covering_prefix_keys(Field *field, uint16 key_read_length,
1959 Key_map *covering_prefix_keys);
1960
1961 private:
1962 /**
1963 Bitmap that tells which columns are eligible for partial update in an
1964 update statement.
1965
1966 The bitmap is lazily allocated in the TABLE's mem_root when
1967 #mark_column_for_partial_update() is called.
1968 */
1969 MY_BITMAP *m_partial_update_columns{nullptr};
1970
1971 /**
1972 Object which contains execution time state used for partial update
1973 of JSON columns.
1974
1975 It is allocated in the execution mem_root by #setup_partial_update() if
1976 there are columns that have been marked as eligible for partial update.
1977 */
1978 Partial_update_info *m_partial_update_info{nullptr};
1979
1980 /**
1981 This flag decides whether or not we should log the drop temporary table
1982 command.
1983 */
1984 bool should_binlog_drop_if_temp_flag{false};
1985
1986 public:
1987 /**
1988 Does this table have any columns that can be updated using partial update
1989 in the current row?
1990
1991 @return whether any columns in the current row can be updated using partial
1992 update
1993 */
1994 bool has_binary_diff_columns() const;
1995
1996 /**
1997 Get the list of binary diffs that have been collected for a given column in
1998 the current row, or `nullptr` if partial update cannot be used for that
1999 column.
2000
2001 @param field the column to get binary diffs for
2002 @return the list of binary diffs for the column, or `nullptr` if the column
2003 cannot be updated using partial update
2004 */
2005 const Binary_diff_vector *get_binary_diffs(const Field *field) const;
2006
2007 /**
2008 Mark a given column as one that can potentially be updated using
2009 partial update during execution of an update statement.
2010
2011 Whether it is actually updated using partial update, is not
2012 determined until execution time, since that depends both on the
2013 data that is in the column and the new data that is written to the
2014 column.
2015
2016 This function should be called during preparation of an update
2017 statement.
2018
2019 @param field a column which is eligible for partial update
2020 @retval false on success
2021 @retval true on out-of-memory
2022 */
2023 bool mark_column_for_partial_update(const Field *field);
2024
2025 /**
2026 Has this column been marked for partial update?
2027
2028 Note that this only tells if the column satisfies the syntactical
2029 requirements for being partially updated. Use #is_binary_diff_enabled() or
2030 #is_logical_diff_enabled() instead to see if partial update should be used
2031 on the column.
2032
2033 @param field the column to check
2034 @return whether the column has been marked for partial update
2035 */
2036 bool is_marked_for_partial_update(const Field *field) const;
2037
2038 /**
2039 Does this table have any columns that were marked with
2040 #mark_column_for_partial_update()?
2041
2042 Note that this only tells if any of the columns satisfy the syntactical
2043 requirements for being partially updated. Use
2044 #has_binary_diff_columns(), #is_binary_diff_enabled() or
2045 #is_logical_diff_enabled() instead to see if partial update should be used
2046 on a column.
2047 */
2048 bool has_columns_marked_for_partial_update() const;
2049
2050 /**
2051 Enable partial update of JSON columns in this table. It is only
2052 enabled for the columns that have previously been marked for
2053 partial update using #mark_column_for_partial_update().
2054
2055 @param logical_diffs should logical JSON diffs be collected in addition
2056 to the physical binary diffs?
2057
2058 This function should be called once per statement execution, when
2059 the update statement is optimized.
2060
2061 @retval false on success
2062 @retval true on out-of-memory
2063 */
2064 bool setup_partial_update(bool logical_diffs);
2065
2066 /**
2067 @see setup_partial_update(bool)
2068
2069 This is a wrapper that auto-computes the value of the parameter
2070 logical_diffs.
2071
2072 @retval false on success
2073 @retval true on out-of-memory
2074 */
2075 bool setup_partial_update();
2076
2077 /**
2078 Add a binary diff for a column that is updated using partial update.
2079
2080 @param field the column that is being updated
2081 @param offset the offset of the changed portion
2082 @param length the length of the changed portion
2083
2084 @retval false on success
2085 @retval true on out-of-memory
2086 */
2087 bool add_binary_diff(const Field *field, size_t offset, size_t length);
2088
2089 /**
2090 Clear the diffs that have been collected for partial update of
2091 JSON columns, and re-enable partial update for any columns where
2092 partial update was temporarily disabled for the current row.
2093 Should be called between each row that is updated.
2094 */
2095 void clear_partial_update_diffs();
2096
2097 /**
2098 Clean up state used for partial update of JSON columns.
2099
2100 This function should be called at the end of each statement
2101 execution.
2102 */
2103 void cleanup_partial_update();
2104
2105 /**
2106 Temporarily disable collection of binary diffs for a column in the current
2107 row.
2108
2109 This function is called during execution to disable partial update of a
2110 column that was previously marked as eligible for partial update with
2111 #mark_column_for_partial_update() during preparation.
2112
2113 Partial update of this column will be re-enabled when we go to the next
2114 row.
2115
2116 @param field the column to stop collecting binary diffs for
2117 */
2118 void disable_binary_diffs_for_current_row(const Field *field);
2119
2120 /**
2121 Temporarily disable collection of Json_diff objects describing the
2122 logical changes of a JSON column in the current row.
2123
2124 Collection of logical JSON diffs is re-enabled when we go to the next row.
2125
2126 @param field the column to stop collecting logical JSON diffs for
2127 */
2128 void disable_logical_diffs_for_current_row(const Field *field) const;
2129
2130 /**
2131 Get a buffer that can be used to hold the partially updated column value
2132 while performing partial update.
2133 */
2134 String *get_partial_update_buffer();
2135
2136 /**
2137 Add a logical JSON diff describing a logical change to a JSON column in
2138 partial update.
2139
2140 @param field the column that is updated
2141 @param path the JSON path that is changed
2142 @param operation the operation to perform
2143 @param new_value the new value in the path
2144
2145 @throws std::bad_alloc if memory cannot be allocated
2146 */
2147 void add_logical_diff(const Field_json *field, const Json_seekable_path &path,
2148 enum_json_diff_operation operation,
2149 const Json_wrapper *new_value);
2150
2151 /**
2152 Get the list of JSON diffs that have been collected for a given column in
2153 the current row, or `nullptr` if partial update cannot be used for that
2154 column.
2155
2156 @param field the column to get JSON diffs for
2157 @return the list of JSON diffs for the column, or `nullptr` if the column
2158 cannot be updated using partial update
2159 */
2160 const Json_diff_vector *get_logical_diffs(const Field_json *field) const;
2161
2162 /**
2163 Is partial update using binary diffs enabled on this JSON column?
2164
2165 @param field the column to check
2166 @return whether the column can be updated with binary diffs
2167 */
2168 bool is_binary_diff_enabled(const Field *field) const;
2169
2170 /**
2171 Is partial update using logical diffs enabled on this JSON column?
2172
2173 @param field the column to check
2174 @return whether the column can be updated with JSON diffs
2175 */
2176 bool is_logical_diff_enabled(const Field *field) const;
2177
2178 /**
2179 Virtual fields of type BLOB have a flag m_keep_old_value. This flag is set
2180 to false for all such fields in this table.
2181 */
2182 void blobs_need_not_keep_old_value();
2183
2184 /**
2185 Set the variable should_binlog_drop_if_temp_flag, so that
2186 the logging of temporary tables can be decided.
2187
2188 @param should_binlog the value to set flag should_binlog_drop_if_temp_flag
2189 */
2190 void set_binlog_drop_if_temp(bool should_binlog);
2191
2192 /**
2193 @return whether should_binlog_drop_if_temp_flag flag is
2194 set or not
2195 */
2196 bool should_binlog_drop_if_temp(void) const;
2197 };
2198
empty_record(TABLE * table)2199 static inline void empty_record(TABLE *table) {
2200 restore_record(table, s->default_values);
2201 if (table->s->null_bytes > 0)
2202 memset(table->null_flags, 255, table->s->null_bytes);
2203 }
2204
2205 enum enum_schema_table_state : int {
2206 NOT_PROCESSED = 0,
2207 PROCESSED_BY_CREATE_SORT_INDEX,
2208 PROCESSED_BY_JOIN_EXEC
2209 };
2210
2211 #define MY_I_S_MAYBE_NULL 1
2212 #define MY_I_S_UNSIGNED 2
2213
2214 struct ST_FIELD_INFO {
2215 /**
2216 This is used as column name.
2217 */
2218 const char *field_name;
2219 /**
2220 For string-type columns, this is the maximum number of
2221 characters. Otherwise, it is the 'display-length' for the column.
2222 For the data type MYSQL_TYPE_DATETIME this field specifies the
2223 number of digits in the fractional part of time value.
2224 */
2225 uint field_length;
2226 /**
2227 This denotes data type for the column. For the most part, there seems to
2228 be one entry in the enum for each SQL data type, although there seem to
2229 be a number of additional entries in the enum.
2230 */
2231 enum_field_types field_type;
2232 int value;
2233 /**
2234 This is used to set column attributes. By default, columns are @c NOT
2235 @c NULL and @c SIGNED, and you can deviate from the default
2236 by setting the appropriate flags. You can use either one of the flags
2237 @c MY_I_S_MAYBE_NULL and @c MY_I_S_UNSIGNED or
2238 combine them using the bitwise or operator @c |. Both flags are
2239 defined in table.h.
2240 */
2241 uint field_flags; // Field atributes(maybe_null, signed, unsigned etc.)
2242 const char *old_name;
2243 uint open_method; // Not used
2244 };
2245
2246 struct ST_SCHEMA_TABLE {
2247 const char *table_name;
2248 ST_FIELD_INFO *fields_info;
2249 /* Fill table with data */
2250 int (*fill_table)(THD *thd, TABLE_LIST *tables, Item *cond);
2251 /* Handle fileds for old SHOW */
2252 int (*old_format)(THD *thd, ST_SCHEMA_TABLE *schema_table);
2253 int (*process_table)(THD *thd, TABLE_LIST *tables, TABLE *table, bool res,
2254 LEX_CSTRING db_name, LEX_CSTRING table_name);
2255 bool hidden;
2256 };
2257
2258 enum Outer_join_type {
2259 JOIN_TYPE_INNER = 0,
2260 JOIN_TYPE_LEFT = 1,
2261 JOIN_TYPE_RIGHT = 2
2262 };
2263
2264 /**
2265 Strategy for how to process a view or derived table (merge or materialization)
2266 */
2267 enum enum_view_algorithm {
2268 VIEW_ALGORITHM_UNDEFINED = 0,
2269 VIEW_ALGORITHM_TEMPTABLE = 1,
2270 VIEW_ALGORITHM_MERGE = 2
2271 };
2272
2273 #define VIEW_SUID_INVOKER 0
2274 #define VIEW_SUID_DEFINER 1
2275 #define VIEW_SUID_DEFAULT 2
2276
2277 /* view WITH CHECK OPTION parameter options */
2278 #define VIEW_CHECK_NONE 0
2279 #define VIEW_CHECK_LOCAL 1
2280 #define VIEW_CHECK_CASCADED 2
2281
2282 /* result of view WITH CHECK OPTION parameter check */
2283 #define VIEW_CHECK_OK 0
2284 #define VIEW_CHECK_ERROR 1
2285 #define VIEW_CHECK_SKIP 2
2286
2287 /** The threshold size a blob field buffer before it is freed */
2288 #define MAX_TDC_BLOB_SIZE 65536
2289
2290 /**
2291 Struct that describes an expression selected from a derived table or view.
2292 */
2293 struct Field_translator {
2294 /**
2295 Points to an item that represents the expression.
2296 If the item is determined to be unused, the pointer is set to NULL.
2297 */
2298 Item *item;
2299 /// Name of selected expression
2300 const char *name;
2301 };
2302
2303 /*
2304 Column reference of a NATURAL/USING join. Since column references in
2305 joins can be both from views and stored tables, may point to either a
2306 Field (for tables), or a Field_translator (for views).
2307 */
2308
2309 class Natural_join_column {
2310 public:
2311 Field_translator *view_field; /* Column reference of merge view. */
2312 Item_field *table_field; /* Column reference of table or temp view. */
2313 TABLE_LIST *table_ref; /* Original base table/view reference. */
2314 /*
2315 True if a common join column of two NATURAL/USING join operands. Notice
2316 that when we have a hierarchy of nested NATURAL/USING joins, a column can
2317 be common at some level of nesting but it may not be common at higher
2318 levels of nesting. Thus this flag may change depending on at which level
2319 we are looking at some column.
2320 */
2321 bool is_common;
2322
2323 public:
2324 Natural_join_column(Field_translator *field_param, TABLE_LIST *tab);
2325 Natural_join_column(Item_field *field_param, TABLE_LIST *tab);
2326 const char *name();
2327 Item *create_item(THD *thd);
2328 Field *field();
2329 const char *table_name();
2330 const char *db_name();
2331 GRANT_INFO *grant();
2332 };
2333
2334 /**
2335 This is generic enum. It may be reused in the ACL statements
2336 for clauses that can map to the values defined in this enum.
2337 */
2338 enum class Lex_acl_attrib_udyn {
2339 UNCHANGED, /* The clause is not specified */
2340 DEFAULT, /* Default value of clause is specified */
2341 YES, /* Value that maps to True is specified */
2342 NO /* Value that maps to False is specified */
2343 };
2344
2345 /*
2346 This structure holds the specifications relating to
2347 ALTER user ... PASSWORD EXPIRE ...
2348 */
2349 struct LEX_ALTER {
2350 bool update_password_expired_fields;
2351 bool update_password_expired_column;
2352 bool use_default_password_lifetime;
2353 uint16 expire_after_days;
2354 bool update_account_locked_column;
2355 bool account_locked;
2356 uint32 password_history_length;
2357 bool use_default_password_history;
2358 bool update_password_history;
2359 uint32 password_reuse_interval;
2360 bool use_default_password_reuse_interval;
2361 bool update_password_reuse_interval;
2362 uint failed_login_attempts;
2363 bool update_failed_login_attempts;
2364 int password_lock_time;
2365 bool update_password_lock_time;
2366 /* Holds the specification of 'PASSWORD REQUIRE CURRENT' clause. */
2367 Lex_acl_attrib_udyn update_password_require_current;
cleanupLEX_ALTER2368 void cleanup() {
2369 update_password_expired_fields = false;
2370 update_password_expired_column = false;
2371 use_default_password_lifetime = true;
2372 expire_after_days = 0;
2373 update_account_locked_column = false;
2374 account_locked = false;
2375 use_default_password_history = true;
2376 update_password_history = false;
2377 use_default_password_reuse_interval = true;
2378 update_password_reuse_interval = false;
2379 update_password_require_current = Lex_acl_attrib_udyn::UNCHANGED;
2380 password_history_length = 0;
2381 password_reuse_interval = 0;
2382 update_password_lock_time = false;
2383 update_failed_login_attempts = false;
2384 failed_login_attempts = 0;
2385 password_lock_time = 0;
2386 }
2387 };
2388
2389 /*
2390 This structure holds the specifications related to
2391 mysql user and the associated auth details.
2392 */
2393 struct LEX_USER {
2394 LEX_CSTRING user;
2395 LEX_CSTRING host;
2396 LEX_CSTRING plugin;
2397 LEX_CSTRING auth;
2398 LEX_CSTRING current_auth;
2399 /*
2400 The following flags are indicators for the SQL syntax used while
2401 parsing CREATE/ALTER user. While other members are self-explanatory,
2402 'uses_authentication_string_clause' signifies if the password is in
2403 hash form (if the var was set to true) or not.
2404 */
2405 bool uses_identified_by_clause;
2406 bool uses_identified_with_clause;
2407 bool uses_authentication_string_clause;
2408 bool uses_replace_clause;
2409 bool retain_current_password;
2410 bool discard_old_password;
2411 bool has_password_generator;
2412 LEX_ALTER alter_status;
2413 /*
2414 Allocates the memory in the THD mem pool and initialize the members of
2415 this struct. It is preferable to use this method to create a LEX_USER
2416 rather allocating the memory in the THD and initializing the members
2417 explicitly.
2418 */
2419 static LEX_USER *alloc(THD *thd, LEX_STRING *user, LEX_STRING *host);
2420 };
2421
2422 /**
2423 Derive type of metadata lock to be requested for table used by a DML
2424 statement from the type of THR_LOCK lock requested for this table.
2425 */
2426
mdl_type_for_dml(enum thr_lock_type lock_type)2427 inline enum enum_mdl_type mdl_type_for_dml(enum thr_lock_type lock_type) {
2428 return lock_type >= TL_WRITE_ALLOW_WRITE
2429 ? (lock_type == TL_WRITE_LOW_PRIORITY ? MDL_SHARED_WRITE_LOW_PRIO
2430 : MDL_SHARED_WRITE)
2431 : MDL_SHARED_READ;
2432 }
2433
2434 /**
2435 Type of table which can be open for an element of table list.
2436 */
2437
2438 enum enum_open_type {
2439 OT_TEMPORARY_OR_BASE = 0,
2440 OT_TEMPORARY_ONLY,
2441 OT_BASE_ONLY
2442 };
2443
2444 /**
2445 This structure is used to keep info about possible key for the result table
2446 of a derived table/view.
2447 The 'referenced_by' is the table map of tables to which this possible
2448 key corresponds.
2449 The 'used_field' is a map of fields of which this key consists of.
2450 See also the comment for the TABLE_LIST::update_derived_keys function.
2451 */
2452
2453 class Derived_key {
2454 public:
2455 table_map referenced_by;
2456 Field_map used_fields;
2457 };
2458
2459 class Table_function;
2460 /*
2461 Table reference in the FROM clause.
2462
2463 These table references can be of several types that correspond to
2464 different SQL elements. Below we list all types of TABLE_LISTs with
2465 the necessary conditions to determine when a TABLE_LIST instance
2466 belongs to a certain type.
2467
2468 1) table (TABLE_LIST::view == NULL)
2469 - base table
2470 (TABLE_LIST::derived == NULL)
2471 - subquery - TABLE_LIST::table is a temp table
2472 (TABLE_LIST::derived != NULL)
2473 - information schema table
2474 (TABLE_LIST::schema_table != NULL)
2475 NOTICE: for schema tables TABLE_LIST::field_translation may be != NULL
2476 2) view (TABLE_LIST::view != NULL)
2477 - merge (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_MERGE)
2478 also (TABLE_LIST::field_translation != NULL)
2479 - temptable(TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_TEMPTABLE)
2480 also (TABLE_LIST::field_translation == NULL)
2481 3) nested table reference (TABLE_LIST::nested_join != NULL)
2482 - table sequence - e.g. (t1, t2, t3)
2483 TODO: how to distinguish from a JOIN?
2484 - general JOIN
2485 TODO: how to distinguish from a table sequence?
2486 - NATURAL JOIN
2487 (TABLE_LIST::natural_join != NULL)
2488 - JOIN ... USING
2489 (TABLE_LIST::join_using_fields != NULL)
2490 - semi-join
2491 ;
2492 */
2493
2494 struct TABLE_LIST {
2495 TABLE_LIST() = default;
2496
2497 /**
2498 Only to be used by legacy code that temporarily needs a TABLE_LIST, more
2499 specifically: Query_result_create::binlog_show_create_table().
2500 */
TABLE_LISTTABLE_LIST2501 explicit TABLE_LIST(TABLE *table_arg) : table(table_arg) {}
2502
2503 /// Constructor that can be used when the strings are null terminated.
TABLE_LISTTABLE_LIST2504 TABLE_LIST(const char *db_name, const char *table_name,
2505 enum thr_lock_type lock_type)
2506 : TABLE_LIST(db_name, strlen(db_name), table_name, strlen(table_name),
2507 table_name, lock_type) {}
2508
2509 /**
2510 Creates a TABLE_LIST object with pre-allocated strings for database, table
2511 and alias.
2512 */
TABLE_LISTTABLE_LIST2513 TABLE_LIST(TABLE *table_arg, const char *db_name_arg, size_t db_length_arg,
2514 const char *table_name_arg, size_t table_name_length_arg,
2515 const char *alias_arg, enum thr_lock_type lock_type_arg)
2516 : db(db_name_arg),
2517 table_name(table_name_arg),
2518 alias(alias_arg),
2519 m_map(1),
2520 table(table_arg),
2521 m_lock_descriptor{lock_type_arg},
2522 db_length(db_length_arg),
2523 table_name_length(table_name_length_arg) {
2524 MDL_REQUEST_INIT(&mdl_request, MDL_key::TABLE, db, table_name,
2525 mdl_type_for_dml(m_lock_descriptor.type), MDL_TRANSACTION);
2526 }
2527
2528 /// Constructor that can be used when the strings are null terminated.
TABLE_LISTTABLE_LIST2529 TABLE_LIST(const char *db_name, const char *table_name, const char *alias,
2530 enum thr_lock_type lock_type)
2531 : TABLE_LIST(db_name, strlen(db_name), table_name, strlen(table_name),
2532 alias, lock_type) {}
2533
2534 /**
2535 This constructor can be used when a TABLE_LIST is needed for an existing
2536 temporary table. These typically have very long table names, since it is
2537 a fully qualified path. For this reason, the table is set to the alias.
2538 The database name is left blank. The lock descriptor is set to TL_READ.
2539 */
TABLE_LISTTABLE_LIST2540 TABLE_LIST(TABLE *table_arg, const char *alias_arg)
2541 : db(""),
2542 table_name(alias_arg),
2543 alias(alias_arg),
2544 m_map(1),
2545 table(table_arg),
2546 m_lock_descriptor{TL_READ},
2547 db_length(0),
2548 table_name_length(strlen(alias_arg)) {
2549 MDL_REQUEST_INIT(&mdl_request, MDL_key::TABLE, db, table_name,
2550 mdl_type_for_dml(m_lock_descriptor.type), MDL_TRANSACTION);
2551 }
2552
2553 /**
2554 Sets an explicit enum_mdl_type value, without initializing
2555 m_lock_descriptor.
2556 */
TABLE_LISTTABLE_LIST2557 TABLE_LIST(TABLE *table_arg, const char *alias_arg, enum_mdl_type mdl_type)
2558 : db(table_arg->s->db.str),
2559 table_name(table_arg->s->table_name.str),
2560 alias(alias_arg),
2561 m_map(1),
2562 table(table_arg),
2563 db_length(table_arg->s->db.length),
2564 table_name_length(table_arg->s->table_name.length) {
2565 MDL_REQUEST_INIT(&mdl_request, MDL_key::TABLE, db, table_name, mdl_type,
2566 MDL_TRANSACTION);
2567 }
2568
TABLE_LISTTABLE_LIST2569 TABLE_LIST(const char *db_name, const char *table_name_arg,
2570 enum thr_lock_type lock_type_arg,
2571 enum enum_mdl_type mdl_request_type)
2572 : db(db_name),
2573 table_name(table_name_arg),
2574 alias(table_name_arg),
2575 m_map(1),
2576 m_lock_descriptor{lock_type_arg},
2577 db_length(strlen(db_name)),
2578 table_name_length(strlen(table_name_arg)) {
2579 MDL_REQUEST_INIT(&mdl_request, MDL_key::TABLE, db, table_name,
2580 mdl_type_for_dml(m_lock_descriptor.type), MDL_TRANSACTION);
2581 mdl_request.set_type(mdl_request_type);
2582 }
2583
TABLE_LISTTABLE_LIST2584 TABLE_LIST(const char *db_name, size_t db_length_arg,
2585 const char *table_name_arg, size_t table_name_length_arg,
2586 enum thr_lock_type lock_type_arg,
2587 enum enum_mdl_type mdl_request_type)
2588 : db(db_name),
2589 table_name(table_name_arg),
2590 alias(table_name_arg),
2591 m_map(1),
2592 m_lock_descriptor{lock_type_arg},
2593 db_length(db_length_arg),
2594 table_name_length(table_name_length_arg) {
2595 MDL_REQUEST_INIT(&mdl_request, MDL_key::TABLE, db, table_name,
2596 mdl_type_for_dml(m_lock_descriptor.type), MDL_TRANSACTION);
2597 mdl_request.set_type(mdl_request_type);
2598 }
2599
TABLE_LISTTABLE_LIST2600 TABLE_LIST(const char *db_name, size_t db_length_arg,
2601 const char *table_name_arg, size_t table_name_length_arg,
2602 enum thr_lock_type lock_type_arg)
2603 : db(db_name),
2604 table_name(table_name_arg),
2605 alias(table_name_arg),
2606 m_map(1),
2607 m_lock_descriptor{lock_type_arg},
2608 db_length(db_length_arg),
2609 table_name_length(table_name_length_arg) {}
2610
2611 /**
2612 Sets an explicit enum_mdl_type value, without initializing
2613 m_lock_descriptor.
2614 */
TABLE_LISTTABLE_LIST2615 TABLE_LIST(const char *db_name, size_t db_length_arg,
2616 const char *table_name_arg, size_t table_name_length_arg,
2617 const char *alias_arg, enum enum_mdl_type mdl_request_type)
2618 : db(db_name),
2619 table_name(table_name_arg),
2620 alias(alias_arg),
2621 m_map(1),
2622 db_length(db_length_arg),
2623 table_name_length(table_name_length_arg) {
2624 MDL_REQUEST_INIT(&mdl_request, MDL_key::TABLE, db, table_name,
2625 mdl_type_for_dml(m_lock_descriptor.type), MDL_TRANSACTION);
2626 mdl_request.set_type(mdl_request_type);
2627 }
2628
TABLE_LISTTABLE_LIST2629 TABLE_LIST(const char *db_name, size_t db_length_arg,
2630 const char *table_name_arg, size_t table_name_length_arg,
2631 const char *alias_arg, enum thr_lock_type lock_type_arg,
2632 enum enum_mdl_type mdl_request_type)
2633 : db(db_name),
2634 table_name(table_name_arg),
2635 alias(alias_arg),
2636 m_map(1),
2637 m_lock_descriptor{lock_type_arg},
2638 db_length(db_length_arg),
2639 table_name_length(table_name_length_arg) {
2640 MDL_REQUEST_INIT(&mdl_request, MDL_key::TABLE, db, table_name,
2641 mdl_type_for_dml(m_lock_descriptor.type), MDL_TRANSACTION);
2642 mdl_request.set_type(mdl_request_type);
2643 }
2644
TABLE_LISTTABLE_LIST2645 TABLE_LIST(const char *db_name_arg, size_t db_length_arg,
2646 const char *table_name_arg, size_t table_name_length_arg,
2647 const char *alias_arg, enum thr_lock_type lock_type_arg)
2648 : db(db_name_arg),
2649 table_name(table_name_arg),
2650 alias(alias_arg),
2651 m_map(1),
2652 m_lock_descriptor{lock_type_arg},
2653 db_length(db_length_arg),
2654 table_name_length(table_name_length_arg) {
2655 MDL_REQUEST_INIT(&mdl_request, MDL_key::TABLE, db, table_name,
2656 mdl_type_for_dml(m_lock_descriptor.type), MDL_TRANSACTION);
2657 }
2658
2659 /// Create a TABLE_LIST object representing a nested join
2660 static TABLE_LIST *new_nested_join(MEM_ROOT *allocator, const char *alias,
2661 TABLE_LIST *embedding,
2662 mem_root_deque<TABLE_LIST *> *belongs_to,
2663 SELECT_LEX *select);
2664
join_cond_refTABLE_LIST2665 Item **join_cond_ref() { return &m_join_cond; }
join_condTABLE_LIST2666 Item *join_cond() const { return m_join_cond; }
set_join_condTABLE_LIST2667 void set_join_cond(Item *val) {
2668 // If optimization has started, it's too late to change m_join_cond.
2669 DBUG_ASSERT(m_join_cond_optim == nullptr || m_join_cond_optim == (Item *)1);
2670 m_join_cond = val;
2671 }
join_cond_optimTABLE_LIST2672 Item *join_cond_optim() const { return m_join_cond_optim; }
set_join_cond_optimTABLE_LIST2673 void set_join_cond_optim(Item *cond) {
2674 /*
2675 Either we are setting to "empty", or there must pre-exist a
2676 permanent condition.
2677 */
2678 DBUG_ASSERT(cond == nullptr || cond == (Item *)1 || m_join_cond != nullptr);
2679 m_join_cond_optim = cond;
2680 }
join_cond_optim_refTABLE_LIST2681 Item **join_cond_optim_ref() { return &m_join_cond_optim; }
2682
2683 /// @returns true if semi-join nest
is_sj_nestTABLE_LIST2684 bool is_sj_nest() const { return m_is_sj_or_aj_nest && !m_join_cond; }
2685 /// @returns true if anti-join nest
is_aj_nestTABLE_LIST2686 bool is_aj_nest() const { return m_is_sj_or_aj_nest && m_join_cond; }
2687 /// @returns true if anti/semi-join nest
is_sj_or_aj_nestTABLE_LIST2688 bool is_sj_or_aj_nest() const { return m_is_sj_or_aj_nest; }
2689 /// Makes the next a semi/antijoin nest
set_sj_or_aj_nestTABLE_LIST2690 void set_sj_or_aj_nest() {
2691 DBUG_ASSERT(!m_is_sj_or_aj_nest);
2692 m_is_sj_or_aj_nest = true;
2693 }
2694
2695 /// Merge tables from a query block into a nested join structure
2696 bool merge_underlying_tables(SELECT_LEX *select);
2697
2698 /// Evaluate the check option of a view
2699 int view_check_option(THD *thd) const;
2700
2701 /// Cleanup field translations for a view
2702 void cleanup_items();
2703
2704 /// Produce a textual identification of this object
2705 void print(const THD *thd, String *str, enum_query_type query_type) const;
2706
2707 /// Check which single table inside a view that matches a table map
2708 bool check_single_table(TABLE_LIST **table_ref, table_map map);
2709
2710 /// Allocate a buffer for inserted column values
2711 bool set_insert_values(MEM_ROOT *mem_root);
2712
2713 TABLE_LIST *first_leaf_for_name_resolution();
2714 TABLE_LIST *last_leaf_for_name_resolution();
2715 bool is_leaf_for_name_resolution() const;
2716
2717 /// Return the outermost view this table belongs to, or itself
top_tableTABLE_LIST2718 inline const TABLE_LIST *top_table() const {
2719 return belong_to_view ? belong_to_view : this;
2720 }
2721
top_tableTABLE_LIST2722 inline TABLE_LIST *top_table() {
2723 return const_cast<TABLE_LIST *>(
2724 const_cast<const TABLE_LIST *>(this)->top_table());
2725 }
2726
2727 /// Prepare check option for a view
2728 bool prepare_check_option(THD *thd, bool is_cascaded = false);
2729
2730 /// Merge WHERE condition of view or derived table into outer query
2731 bool merge_where(THD *thd);
2732
2733 /// Prepare replace filter for a view (used for REPLACE command)
2734 bool prepare_replace_filter(THD *thd);
2735
2736 /// Return true if this represents a named view
is_viewTABLE_LIST2737 bool is_view() const { return view != nullptr; }
2738
2739 /// Return true if this represents a derived table (an unnamed view)
is_derivedTABLE_LIST2740 bool is_derived() const { return derived != nullptr && view == nullptr; }
2741
2742 /// Return true if this represents a named view or a derived table
is_view_or_derivedTABLE_LIST2743 bool is_view_or_derived() const { return derived != nullptr; }
2744
2745 /// Return true if this represents a table function
is_table_functionTABLE_LIST2746 bool is_table_function() const { return table_function != nullptr; }
2747 /**
2748 @returns true if this is a recursive reference inside the definition of a
2749 recursive CTE.
2750 @note that it starts its existence as a dummy derived table, until the
2751 end of resolution when it's not a derived table anymore, just a reference
2752 to the materialized temporary table. Whereas a non-recursive
2753 reference to the recursive CTE is a derived table.
2754 */
is_recursive_referenceTABLE_LIST2755 bool is_recursive_reference() const { return m_is_recursive_reference; }
2756
2757 /**
2758 @see is_recursive_reference().
2759 @returns true if error
2760 */
2761 bool set_recursive_reference();
2762
2763 /**
2764 @returns true for a table that represents an optimizer internal table,
2765 is a derived table, a recursive reference, a table function.
2766 Internal tables are only visible inside a query expression, and is hence
2767 not visible in any schema, or need any kind of privilege checking.
2768 */
is_internalTABLE_LIST2769 bool is_internal() const {
2770 return is_derived() || is_recursive_reference() || is_table_function();
2771 }
2772
2773 /**
2774 @returns true for a table that is a placeholder, ie a derived table,
2775 a view, a recursive reference, a table function or a schema table.
2776 A table is also considered to be a placeholder if it does not have a
2777 TABLE object for some other reason.
2778 */
is_placeholderTABLE_LIST2779 bool is_placeholder() const {
2780 return is_view_or_derived() || is_recursive_reference() ||
2781 is_table_function() || schema_table || table == nullptr;
2782 }
2783
2784 /// Return true if view or derived table and can be merged
2785 bool is_mergeable() const;
2786
2787 /**
2788 Checks if this is a table that contains zero rows or one row, and that can
2789 be materialized during optimization.
2790
2791 @returns true if materializable table contains one or zero rows, and
2792 materialization during optimization is permitted
2793
2794 Returning true implies that the table is materialized during optimization,
2795 so it need not be optimized during execution.
2796 */
2797 bool materializable_is_const() const;
2798
2799 /// Return true if this is a derived table or view that is merged
is_mergedTABLE_LIST2800 bool is_merged() const { return effective_algorithm == VIEW_ALGORITHM_MERGE; }
2801
2802 /// Set table to be merged
set_mergedTABLE_LIST2803 void set_merged() {
2804 DBUG_ASSERT(effective_algorithm == VIEW_ALGORITHM_UNDEFINED);
2805 effective_algorithm = VIEW_ALGORITHM_MERGE;
2806 }
2807
2808 /// Return true if this is a materializable derived table/view
uses_materializationTABLE_LIST2809 bool uses_materialization() const {
2810 return effective_algorithm == VIEW_ALGORITHM_TEMPTABLE;
2811 }
2812
2813 /// Set table to be materialized
set_uses_materializationTABLE_LIST2814 void set_uses_materialization() {
2815 // @todo We should do this only once, but currently we cannot:
2816 // DBUG_ASSERT(effective_algorithm == VIEW_ALGORITHM_UNDEFINED);
2817 DBUG_ASSERT(effective_algorithm != VIEW_ALGORITHM_MERGE);
2818 effective_algorithm = VIEW_ALGORITHM_TEMPTABLE;
2819 }
2820
2821 /// Return true if table is updatable
is_updatableTABLE_LIST2822 bool is_updatable() const { return m_updatable; }
2823
2824 /// Set table as updatable. (per default, a table is non-updatable)
set_updatableTABLE_LIST2825 void set_updatable() { m_updatable = true; }
2826
2827 /// Return true if table is insertable-into
is_insertableTABLE_LIST2828 bool is_insertable() const { return m_insertable; }
2829
2830 /// Set table as insertable-into. (per default, a table is not insertable)
set_insertableTABLE_LIST2831 void set_insertable() { m_insertable = true; }
2832
2833 /**
2834 Set table as readonly, ie it is neither updatable, insertable nor
2835 deletable during this statement.
2836 */
set_readonlyTABLE_LIST2837 void set_readonly() {
2838 m_updatable = false;
2839 m_insertable = false;
2840 }
2841
2842 /**
2843 Return true if this is a view or derived table that is defined over
2844 more than one base table, and false otherwise.
2845 */
is_multiple_tablesTABLE_LIST2846 bool is_multiple_tables() const {
2847 if (is_view_or_derived()) {
2848 DBUG_ASSERT(is_merged()); // Cannot be a materialized view
2849 return leaf_tables_count() > 1;
2850 } else {
2851 DBUG_ASSERT(nested_join == nullptr); // Must be a base table
2852 return false;
2853 }
2854 }
2855
2856 /// Return no. of base tables a merged view or derived table is defined over.
2857 uint leaf_tables_count() const;
2858
2859 /// Return first leaf table of a base table or a view/derived table
first_leaf_tableTABLE_LIST2860 TABLE_LIST *first_leaf_table() {
2861 TABLE_LIST *tr = this;
2862 while (tr->merge_underlying_list) tr = tr->merge_underlying_list;
2863 return tr;
2864 }
2865
2866 /// Return any leaf table that is not an inner table of an outer join
2867 /// @todo when WL#6570 is implemented, replace with first_leaf_table()
any_outer_leaf_tableTABLE_LIST2868 TABLE_LIST *any_outer_leaf_table() {
2869 TABLE_LIST *tr = this;
2870 while (tr->merge_underlying_list) {
2871 tr = tr->merge_underlying_list;
2872 /*
2873 "while" is used, however, an "if" might be sufficient since there is
2874 no more than one inner table in a join nest (with outer_join true).
2875 */
2876 while (tr->outer_join) tr = tr->next_local;
2877 }
2878 return tr;
2879 }
2880 /**
2881 Set the LEX object of a view (will also define this as a view).
2882 @note: The value 1 is used to indicate a view but without a valid
2883 query object. Use only if the LEX object is not going to
2884 be used in later processing.
2885 */
set_view_queryTABLE_LIST2886 void set_view_query(LEX *lex) { view = lex; }
2887
2888 /// Return the valid LEX object for a view.
view_queryTABLE_LIST2889 LEX *view_query() const {
2890 DBUG_ASSERT(view != nullptr && view != (LEX *)1);
2891 return view;
2892 }
2893
2894 /**
2895 Set the query expression of a derived table or view.
2896 (Will also define this as a derived table, unless it is a named view.)
2897 */
set_derived_unitTABLE_LIST2898 void set_derived_unit(SELECT_LEX_UNIT *query_expr) { derived = query_expr; }
2899
2900 /// Return the query expression of a derived table or view.
derived_unitTABLE_LIST2901 SELECT_LEX_UNIT *derived_unit() const {
2902 DBUG_ASSERT(derived);
2903 return derived;
2904 }
2905
2906 /// Save names of materialized table @see reset_name_temporary
save_name_temporaryTABLE_LIST2907 void save_name_temporary() {
2908 view_db.str = db;
2909 view_db.length = db_length;
2910 view_name.str = table_name;
2911 view_name.length = table_name_length;
2912 }
2913
2914 /// Set temporary name from underlying temporary table:
set_name_temporaryTABLE_LIST2915 void set_name_temporary() {
2916 DBUG_ASSERT((is_view_or_derived()) && uses_materialization());
2917 table_name = table->s->table_name.str;
2918 table_name_length = table->s->table_name.length;
2919 db = "";
2920 db_length = 0;
2921 }
2922
2923 /// Reset original name for temporary table.
reset_name_temporaryTABLE_LIST2924 void reset_name_temporary() {
2925 DBUG_ASSERT((is_table_function() || is_view_or_derived()) &&
2926 uses_materialization());
2927 /*
2928 When printing a query using a view or CTE, we need the table's name and
2929 the alias; the name has been destroyed if the table was materialized,
2930 so we restore it:
2931 */
2932 DBUG_ASSERT(table_name != view_name.str);
2933 table_name = view_name.str;
2934 table_name_length = view_name.length;
2935 if (is_view()) // restore database's name too
2936 {
2937 DBUG_ASSERT(db != view_db.str);
2938 db = view_db.str;
2939 db_length = view_db.length;
2940 }
2941 }
2942
2943 /// Resolve a derived table or view reference
2944 bool resolve_derived(THD *thd, bool apply_semijoin);
2945
2946 /// Optimize the query expression representing a derived table/view
2947 bool optimize_derived(THD *thd);
2948
2949 /// Create result table for a materialized derived table/view
2950 bool create_materialized_table(THD *thd);
2951
2952 /// Materialize derived table
2953 bool materialize_derived(THD *thd);
2954
2955 /// Clean up the query expression for a materialized derived table
2956 bool cleanup_derived(THD *thd);
2957
2958 /// Prepare security context for a view
2959 bool prepare_security(THD *thd);
2960
2961 Security_context *find_view_security_context(THD *thd);
2962 bool prepare_view_security_context(THD *thd);
2963
2964 /// Cleanup for re-execution in a prepared statement or a stored procedure.
2965 void reinit_before_use(THD *thd);
2966
2967 /**
2968 Compiles the tagged hints list and fills up TABLE::keys_in_use_for_query,
2969 TABLE::keys_in_use_for_group_by, TABLE::keys_in_use_for_order_by,
2970 TABLE::force_index and TABLE::covering_keys.
2971 */
2972 bool process_index_hints(const THD *thd, TABLE *table);
2973
2974 /**
2975 Compare the version of metadata from the previous execution
2976 (if any) with values obtained from the current table
2977 definition cache element.
2978
2979 @sa check_and_update_table_version()
2980 */
is_table_ref_id_equalTABLE_LIST2981 bool is_table_ref_id_equal(TABLE_SHARE *s) const {
2982 return (m_table_ref_type == s->get_table_ref_type() &&
2983 m_table_ref_version == s->get_table_ref_version());
2984 }
2985
2986 /**
2987 Record the value of metadata version of the corresponding
2988 table definition cache element in this parse tree node.
2989
2990 @sa check_and_update_table_version()
2991 */
set_table_ref_idTABLE_LIST2992 void set_table_ref_id(TABLE_SHARE *s) {
2993 set_table_ref_id(s->get_table_ref_type(), s->get_table_ref_version());
2994 }
2995
set_table_ref_idTABLE_LIST2996 void set_table_ref_id(enum_table_ref_type table_ref_type_arg,
2997 ulonglong table_ref_version_arg) {
2998 m_table_ref_type = table_ref_type_arg;
2999 m_table_ref_version = table_ref_version_arg;
3000 }
3001
3002 /**
3003 If a derived table, returns query block id of first underlying query block.
3004 Zero if not derived.
3005 */
3006 uint query_block_id() const;
3007
3008 /**
3009 This is for showing in EXPLAIN.
3010 If a derived table, returns query block id of first underlying query block
3011 of first materialized TABLE_LIST instance. Zero if not derived.
3012 */
3013 uint query_block_id_for_explain() const;
3014
3015 /**
3016 @brief Returns the name of the database that the referenced table belongs
3017 to.
3018 */
get_db_nameTABLE_LIST3019 const char *get_db_name() const { return view != nullptr ? view_db.str : db; }
3020
3021 /**
3022 @brief Returns the name of the table that this TABLE_LIST represents.
3023
3024 @details The unqualified table name or view name for a table or view,
3025 respectively.
3026 */
get_table_nameTABLE_LIST3027 const char *get_table_name() const {
3028 return view != nullptr ? view_name.str : table_name;
3029 }
3030 int fetch_number_of_rows();
3031 bool update_derived_keys(THD *, Field *, Item **, uint, bool *);
3032 bool generate_keys();
3033
3034 /// Setup a derived table to use materialization
3035 bool setup_materialized_derived(THD *thd);
3036 bool setup_materialized_derived_tmp_table(THD *thd);
3037
3038 /// Setup a table function to use materialization
3039 bool setup_table_function(THD *thd);
3040
3041 bool create_field_translation(THD *thd);
3042
3043 /**
3044 @brief Returns the outer join nest that this TABLE_LIST belongs to, if any.
3045
3046 @details There are two kinds of join nests, outer-join nests and semi-join
3047 nests. This function returns non-NULL in the following cases:
3048 @li 1. If this table/nest is embedded in a nest and this nest IS NOT a
3049 semi-join nest. (In other words, it is an outer-join nest.)
3050 @li 2. If this table/nest is embedded in a nest and this nest IS a
3051 semi-join nest, but this semi-join nest is embedded in another
3052 nest. (This other nest will be an outer-join nest, since all inner
3053 joined nested semi-join nests have been merged in
3054 @c simplify_joins() ).
3055 Note: This function assumes that @c simplify_joins() has been performed.
3056 Before that, join nests will be present for all types of join.
3057
3058 @return outer join nest, or NULL if none.
3059 */
3060
outer_join_nestTABLE_LIST3061 TABLE_LIST *outer_join_nest() const {
3062 if (!embedding) return nullptr;
3063 if (embedding->is_sj_nest()) return embedding->embedding;
3064 return embedding;
3065 }
3066 /**
3067 Return true if this table is an inner table of some outer join.
3068
3069 Examine all the embedding join nests of the table.
3070 @note This function works also before redundant join nests have been
3071 eliminated.
3072
3073 @return true if table is an inner table of some outer join, false otherwise.
3074 */
3075
is_inner_table_of_outer_joinTABLE_LIST3076 bool is_inner_table_of_outer_join() const {
3077 if (outer_join) return true;
3078 for (TABLE_LIST *emb = embedding; emb; emb = emb->embedding) {
3079 if (emb->outer_join) return true;
3080 }
3081 return false;
3082 }
3083
3084 /**
3085 Return the base table entry of an updatable table.
3086 In DELETE and UPDATE, a view used as a target table must be mergeable,
3087 updatable and defined over a single table.
3088 */
updatable_base_tableTABLE_LIST3089 const TABLE_LIST *updatable_base_table() const {
3090 const TABLE_LIST *tbl = this;
3091 DBUG_ASSERT(tbl->is_updatable() && !tbl->is_multiple_tables());
3092 while (tbl->is_view_or_derived()) {
3093 tbl = tbl->merge_underlying_list;
3094 DBUG_ASSERT(tbl->is_updatable() && !tbl->is_multiple_tables());
3095 }
3096 return tbl;
3097 }
3098
updatable_base_tableTABLE_LIST3099 TABLE_LIST *updatable_base_table() {
3100 return const_cast<TABLE_LIST *>(
3101 static_cast<const TABLE_LIST *>(this)->updatable_base_table());
3102 }
3103
3104 /**
3105 Mark that there is a NATURAL JOIN or JOIN ... USING between two tables.
3106
3107 This function marks that table b should be joined with a either via
3108 a NATURAL JOIN or via JOIN ... USING. Both join types are special
3109 cases of each other, so we treat them together. The function
3110 setup_conds() creates a list of equal condition between all fields
3111 of the same name for NATURAL JOIN or the fields in
3112 TABLE_LIST::join_using_fields for JOIN ... USING.
3113 The list of equality conditions is stored
3114 either in b->join_cond(), or in JOIN::conds, depending on whether there
3115 was an outer join.
3116
3117 EXAMPLE
3118 @verbatim
3119 SELECT * FROM t1 NATURAL LEFT JOIN t2
3120 <=>
3121 SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
3122
3123 SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
3124 <=>
3125 SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)
3126
3127 SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
3128 <=>
3129 SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
3130 @endverbatim
3131
3132 @param b Right join argument.
3133 */
add_join_naturalTABLE_LIST3134 void add_join_natural(TABLE_LIST *b) { b->natural_join = this; }
3135
3136 /**
3137 Set granted privileges for a table.
3138
3139 Can be used when generating temporary tables that are also used in
3140 resolver process, such as when generating a UNION table
3141
3142 @param privilege Privileges granted for this table.
3143 */
set_privilegesTABLE_LIST3144 void set_privileges(ulong privilege) { grant.privilege |= privilege; }
3145 /*
3146 List of tables local to a subquery or the top-level SELECT (used by
3147 SQL_I_List). Considers views as leaves (unlike 'next_leaf' below).
3148 Created at parse time in SELECT_LEX::add_table_to_list() ->
3149 table_list.link_in_list().
3150 */
3151 TABLE_LIST *next_local{nullptr};
3152 /* link in a global list of all queries tables */
3153 TABLE_LIST *next_global{nullptr}, **prev_global{nullptr};
3154 const char *db{nullptr}, *table_name{nullptr}, *alias{nullptr};
3155 /*
3156 Target tablespace name: When creating or altering tables, this
3157 member points to the tablespace_name in the HA_CREATE_INFO struct.
3158 */
3159 LEX_CSTRING target_tablespace_name{nullptr, 0};
3160 const char *schema_table_name{nullptr};
3161 char *option{nullptr}; /* Used by cache index */
3162
3163 /** Table level optimizer hints for this table. */
3164 Opt_hints_table *opt_hints_table{nullptr};
3165 /* Hints for query block of this table. */
3166 Opt_hints_qb *opt_hints_qb{nullptr};
3167
set_lockTABLE_LIST3168 void set_lock(const Lock_descriptor &descriptor) {
3169 m_lock_descriptor = descriptor;
3170 }
3171
lock_descriptorTABLE_LIST3172 const Lock_descriptor &lock_descriptor() const { return m_lock_descriptor; }
3173
3174 private:
3175 /**
3176 The members below must be kept aligned so that (1 << m_tableno) == m_map.
3177 A table that takes part in a join operation must be assigned a unique
3178 table number.
3179 */
3180 uint m_tableno{0}; ///< Table number within query block
3181 table_map m_map{0}; ///< Table map, derived from m_tableno
3182 /**
3183 If this table or join nest is the Y in "X [LEFT] JOIN Y ON C", this
3184 member points to C. May also be generated from JOIN ... USING clause.
3185 It may be modified only by permanent transformations (permanent = done
3186 once for all executions of a prepared statement).
3187 */
3188 Item *m_join_cond{nullptr};
3189 bool m_is_sj_or_aj_nest{false};
3190
3191 public:
3192 /*
3193 (Valid only for semi-join nests) Bitmap of tables that are within the
3194 semi-join (this is different from bitmap of all nest's children because
3195 tables that were pulled out of the semi-join nest remain listed as
3196 nest's children).
3197 */
3198 table_map sj_inner_tables{0};
3199
3200 /*
3201 During parsing - left operand of NATURAL/USING join where 'this' is
3202 the right operand. After parsing (this->natural_join == this) iff
3203 'this' represents a NATURAL or USING join operation. Thus after
3204 parsing 'this' is a NATURAL/USING join iff (natural_join != NULL).
3205 */
3206 TABLE_LIST *natural_join{nullptr};
3207 /*
3208 True if 'this' represents a nested join that is a NATURAL JOIN.
3209 For one of the operands of 'this', the member 'natural_join' points
3210 to the other operand of 'this'.
3211 */
3212 bool is_natural_join{false};
3213 /* Field names in a USING clause for JOIN ... USING. */
3214 List<String> *join_using_fields{nullptr};
3215 /*
3216 Explicitly store the result columns of either a NATURAL/USING join or
3217 an operand of such a join.
3218 */
3219 List<Natural_join_column> *join_columns{nullptr};
3220 /* true if join_columns contains all columns of this table reference. */
3221 bool is_join_columns_complete{false};
3222
3223 /*
3224 List of nodes in a nested join tree, that should be considered as
3225 leaves with respect to name resolution. The leaves are: views,
3226 top-most nodes representing NATURAL/USING joins, subqueries, and
3227 base tables. All of these TABLE_LIST instances contain a
3228 materialized list of columns. The list is local to a subquery.
3229 */
3230 TABLE_LIST *next_name_resolution_table{nullptr};
3231 /* Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */
3232 List<Index_hint> *index_hints{nullptr};
3233 TABLE *table{nullptr}; /* opened table */
3234 Table_id table_id{}; /* table id (from binlog) for opened table */
3235 /*
3236 Query_result for derived table to pass it from table creation to table
3237 filling procedure
3238 */
3239 Query_result_union *derived_result{nullptr};
3240 /*
3241 Reference from aux_tables to local list entry of main select of
3242 multi-delete statement:
3243 delete t1 from t2,t1 where t1.a<'B' and t2.b=t1.b;
3244 here it will be reference of first occurrence of t1 to second (as you
3245 can see this lists can't be merged)
3246 */
3247 TABLE_LIST *correspondent_table{nullptr};
3248
3249 /*
3250 Holds the function used as the table function
3251 */
3252 Table_function *table_function{nullptr};
3253
3254 private:
3255 /**
3256 This field is set to non-null for derived tables and views. It points
3257 to the SELECT_LEX_UNIT representing the derived table/view.
3258 E.g. for a query
3259 @verbatim SELECT * FROM (SELECT a FROM t1) b @endverbatim
3260 */
3261 SELECT_LEX_UNIT *derived{nullptr}; /* SELECT_LEX_UNIT of derived table */
3262
3263 /// If non-NULL, the CTE which this table is derived from.
3264 Common_table_expr *m_common_table_expr{nullptr};
3265 /**
3266 If the user has specified column names with the syntaxes "table name
3267 parenthesis column names":
3268 WITH qn(column names) AS (select...)
3269 or
3270 FROM (select...) dt(column names)
3271 or
3272 CREATE VIEW v(column_names) AS ...
3273 then this points to the list of column names. NULL otherwise.
3274 */
3275 const Create_col_name_list *m_derived_column_names{nullptr};
3276
3277 public:
3278 ST_SCHEMA_TABLE *schema_table{nullptr}; /* Information_schema table */
3279 SELECT_LEX *schema_select_lex{nullptr};
3280 /*
3281 True when the view field translation table is used to convert
3282 schema table fields for backwards compatibility with SHOW command.
3283 */
3284 bool schema_table_reformed{false};
3285 Temp_table_param *schema_table_param{nullptr};
3286 /* link to select_lex where this table was used */
3287 SELECT_LEX *select_lex{nullptr};
3288
3289 private:
3290 LEX *view{nullptr}; /* link on VIEW lex for merging */
3291
3292 public:
3293 /// Array of selected expressions from a derived table or view.
3294 Field_translator *field_translation{nullptr};
3295
3296 /// pointer to element after last one in translation table above
3297 Field_translator *field_translation_end{nullptr};
3298 /*
3299 List (based on next_local) of underlying tables of this view. I.e. it
3300 does not include the tables of subqueries used in the view. Is set only
3301 for merged views.
3302 */
3303 TABLE_LIST *merge_underlying_list{nullptr};
3304 /*
3305 - 0 for base tables
3306 - in case of the view it is the list of all (not only underlying
3307 tables but also used in subquery ones) tables of the view.
3308 */
3309 mem_root_deque<TABLE_LIST *> *view_tables{nullptr};
3310 /* most upper view this table belongs to */
3311 TABLE_LIST *belong_to_view{nullptr};
3312 /*
3313 The view directly referencing this table
3314 (non-zero only for merged underlying tables of a view).
3315 */
3316 TABLE_LIST *referencing_view{nullptr};
3317 /* Ptr to parent MERGE table list item. See top comment in ha_myisammrg.cc */
3318 TABLE_LIST *parent_l{nullptr};
3319 /*
3320 Security context (non-zero only for tables which belong
3321 to view with SQL SECURITY DEFINER)
3322 */
3323 Security_context *security_ctx{nullptr};
3324 /*
3325 This view security context (non-zero only for views with
3326 SQL SECURITY DEFINER)
3327 */
3328 Security_context *view_sctx{nullptr};
3329 /*
3330 List of all base tables local to a subquery including all view
3331 tables. Unlike 'next_local', this in this list views are *not*
3332 leaves. Created in setup_tables() -> make_leaf_tables().
3333 */
3334 TABLE_LIST *next_leaf{nullptr};
3335 Item *derived_where_cond{nullptr}; ///< WHERE condition from derived table
3336 Item *check_option{nullptr}; ///< WITH CHECK OPTION condition
3337 Item *replace_filter{nullptr}; ///< Filter for REPLACE command
3338 LEX_STRING select_stmt{nullptr, 0}; ///< text of (CREATE/SELECT) statement
3339 LEX_STRING source{nullptr, 0}; ///< source of CREATE VIEW
3340 LEX_CSTRING view_db{nullptr, 0}; ///< saved view database
3341 LEX_CSTRING view_name{nullptr, 0}; ///< saved view name
3342 LEX_STRING timestamp{nullptr, 0}; ///< GMT time stamp of last operation
3343 LEX_USER definer; ///< definer of view
3344 /**
3345 @note: This field is currently not reliable when read from dictionary:
3346 If an underlying view is changed, updatable_view is not changed,
3347 due to lack of dependency checking in dictionary implementation.
3348 Prefer to use is_updatable() during preparation and optimization.
3349 */
3350 ulonglong updatable_view{0}; ///< VIEW can be updated
3351 /**
3352 @brief The declared algorithm, if this is a view.
3353 @details One of
3354 - VIEW_ALGORITHM_UNDEFINED
3355 - VIEW_ALGORITHM_TEMPTABLE
3356 - VIEW_ALGORITHM_MERGE
3357 @todo Replace with an enum
3358 */
3359 ulonglong algorithm{0};
3360 ulonglong view_suid{0}; ///< view is suid (true by default)
3361 ulonglong with_check{0}; ///< WITH CHECK OPTION
3362
3363 private:
3364 /// The view algorithm that is actually used, if this is a view.
3365 enum_view_algorithm effective_algorithm{VIEW_ALGORITHM_UNDEFINED};
3366 Lock_descriptor m_lock_descriptor;
3367
3368 public:
3369 GRANT_INFO grant;
3370
3371 public:
3372 Outer_join_type outer_join{JOIN_TYPE_INNER}; /* Which join type */
3373 uint shared{0}; /* Used in multi-upd */
3374 size_t db_length{0};
3375 size_t table_name_length{0};
3376
3377 private:
3378 bool m_updatable{false}; /* VIEW/TABLE can be updated */
3379 bool m_insertable{false}; /* VIEW/TABLE can be inserted into */
3380 public:
3381 bool straight{false}; /* optimize with prev table */
3382 /**
3383 True for tables and views being changed in a data change statement.
3384 Also true for tables subject to a SELECT ... FOR UPDATE.
3385 Also used by replication to filter out statements that can be ignored,
3386 especially important for multi-table UPDATE and DELETE.
3387 */
3388 bool updating{false};
3389 /// True if using an index is preferred over a table scan.
3390 bool force_index{false};
3391 /// preload only non-leaf nodes (IS THIS USED???)
3392 bool ignore_leaves{false};
3393 /**
3394 The set of tables in the query block that this table depends on.
3395 Can be set due to outer join, join order hints or NOT EXISTS relationship.
3396 */
3397 table_map dep_tables{0};
3398 /// The outer tables that an outer join's join condition depends on
3399 table_map join_cond_dep_tables{0};
3400 /**
3401 Is non-NULL if this table reference is a nested join, ie it represents
3402 the inner tables of an outer join, the tables contained in the
3403 parentheses of an inner join (eliminated during resolving), the tables
3404 referenced in a derived table or view, in a semi-join nest, the tables
3405 from the subquery.
3406 */
3407 NESTED_JOIN *nested_join{nullptr};
3408 /// The nested join containing this table reference.
3409 TABLE_LIST *embedding{nullptr};
3410 /// The join list immediately containing this table reference
3411 mem_root_deque<TABLE_LIST *> *join_list{nullptr};
3412 /// stop PS caching
3413 bool cacheable_table{false};
3414 /**
3415 Specifies which kind of table should be open for this element
3416 of table list.
3417 */
3418 enum_open_type open_type{OT_TEMPORARY_OR_BASE};
3419 /* true if this merged view contain auto_increment field */
3420 bool contain_auto_increment{false};
3421 /// true <=> VIEW CHECK OPTION condition is processed (also for prep. stmts)
3422 bool check_option_processed{false};
3423 /// true <=> Filter condition is processed
3424 bool replace_filter_processed{false};
3425
3426 dd::enum_table_type required_type{};
3427 char timestamp_buffer[20]{0}; /* buffer for timestamp (19+1) */
3428 /*
3429 This TABLE_LIST object is just placeholder for prelocking, it will be
3430 used for implicit LOCK TABLES only and won't be used in real statement.
3431 */
3432 bool prelocking_placeholder{false};
3433 /**
3434 Indicates that if TABLE_LIST object corresponds to the table/view
3435 which requires special handling.
3436 */
3437 enum {
3438 /* Normal open. */
3439 OPEN_NORMAL = 0,
3440 /* Associate a table share only if the the table exists. */
3441 OPEN_IF_EXISTS,
3442 /*
3443 Associate a table share only if the the table exists.
3444 Also upgrade metadata lock to exclusive if table doesn't exist.
3445 */
3446 OPEN_FOR_CREATE,
3447 /* Don't associate a table share. */
3448 OPEN_STUB
3449 } open_strategy{OPEN_NORMAL};
3450 bool internal_tmp_table{false};
3451 /** true if an alias for this table was specified in the SQL. */
3452 bool is_alias{false};
3453 /** true if the table is referred to in the statement using a fully
3454 qualified name (@<db_name@>.@<table_name@>).
3455 */
3456 bool is_fqtn{false};
3457 /**
3458 If true, this table is a derived (materialized) table which was created
3459 from a scalar subquery, cf.
3460 SELECT_LEX::transform_scalar_subqueries_to_derived
3461 */
3462 bool m_was_scalar_subquery{false};
3463 /**
3464 If true, this is a derived table for grouping which was made for a query
3465 block which also has one or more derived tables created from a scalar
3466 subquery, cf. m_was_scalar_subquery. m_is_grouped2derived implies
3467 m_was_scalar_subquery holds for at least one other local table but not the
3468 other way around. See SELECT_LEX::transform_grouped_to_derived.
3469 */
3470 bool m_was_grouped2derived{false};
3471
3472 /// If this is a derived table created by transforming a quantified subquery.
3473 /// @todo remove after WL#6570.
3474 bool m_was_table_subquery{false};
3475 /// Usable only if was_table_subquery==true; contains the index of the
3476 /// first SJ-inner expression of the subquery predicate.
3477 int m_first_sj_inner_expr_of_subquery{0};
3478
3479 /* View creation context. */
3480
3481 View_creation_ctx *view_creation_ctx{nullptr};
3482
3483 /*
3484 Attributes to save/load view creation context in/from frm-file.
3485
3486 They are required only to be able to use existing parser to load
3487 view-definition file. As soon as the parser parsed the file, view
3488 creation context is initialized and the attributes become redundant.
3489
3490 These attributes MUST NOT be used for any purposes but the parsing.
3491 */
3492
3493 LEX_CSTRING view_client_cs_name{nullptr, 0};
3494 LEX_CSTRING view_connection_cl_name{nullptr, 0};
3495
3496 /*
3497 View definition (SELECT-statement) in the UTF-form.
3498 */
3499
3500 LEX_STRING view_body_utf8{nullptr, 0};
3501
3502 // True, If this is a system view
3503 bool is_system_view{false};
3504
3505 /*
3506 Set to 'true' if this is a DD table being opened in the context of a
3507 dictionary operation. Note that when 'false', this may still be a DD
3508 table when opened in a non-DD context, e.g. as part of an I_S view
3509 query.
3510 */
3511 bool is_dd_ctx_table{false};
3512
3513 /* End of view definition context. */
3514
3515 /* List of possible keys. Valid only for materialized derived tables/views. */
3516 List<Derived_key> derived_key_list;
3517
3518 /**
3519 Indicates what triggers we need to pre-load for this TABLE_LIST
3520 when opening an associated TABLE. This is filled after
3521 the parsed tree is created.
3522 */
3523 uint8 trg_event_map{0};
3524 uint i_s_requested_object{0};
3525 bool has_db_lookup_value{false};
3526 bool has_table_lookup_value{false};
3527 uint table_open_method{0};
3528 enum_schema_table_state schema_table_state{NOT_PROCESSED};
3529
3530 MDL_request mdl_request;
3531
3532 /// if true, EXPLAIN can't explain view due to insufficient rights.
3533 bool view_no_explain{false};
3534
3535 /* List to carry partition names from PARTITION (...) clause in statement */
3536 List<String> *partition_names{nullptr};
3537
3538 /// Set table number
set_tablenoTABLE_LIST3539 void set_tableno(uint tableno) {
3540 DBUG_ASSERT(tableno < MAX_TABLES);
3541 m_tableno = tableno;
3542 m_map = (table_map)1 << tableno;
3543 }
3544 /// Return table number
tablenoTABLE_LIST3545 uint tableno() const { return m_tableno; }
3546
3547 /// Return table map derived from table number
mapTABLE_LIST3548 table_map map() const {
3549 DBUG_ASSERT(((table_map)1 << m_tableno) == m_map);
3550 return m_map;
3551 }
3552
3553 /// If non-NULL, the CTE which this table is derived from.
common_table_exprTABLE_LIST3554 Common_table_expr *common_table_expr() const { return m_common_table_expr; }
set_common_table_exprTABLE_LIST3555 void set_common_table_expr(Common_table_expr *c) { m_common_table_expr = c; }
3556 /// @see m_derived_column_names
derived_column_namesTABLE_LIST3557 const Create_col_name_list *derived_column_names() const {
3558 return m_derived_column_names;
3559 }
set_derived_column_namesTABLE_LIST3560 void set_derived_column_names(const Create_col_name_list *d) {
3561 m_derived_column_names = d;
3562 }
3563 void propagate_table_maps(table_map map_arg);
3564
3565 private:
3566 /*
3567 A group of members set and used only during JOIN::optimize().
3568 */
3569 /**
3570 Optimized copy of m_join_cond (valid for one single
3571 execution). Initialized by SELECT_LEX::get_optimizable_conditions().
3572 @todo it would be goo dto reset it in reinit_before_use(), if
3573 reinit_stmt_before_use() had a loop including join nests.
3574 */
3575 Item *m_join_cond_optim{nullptr};
3576
3577 public:
3578 COND_EQUAL *cond_equal{nullptr}; ///< Used with outer join
3579 /// true <=> this table is a const one and was optimized away.
3580 bool optimized_away{false};
3581 /**
3582 true <=> all possible keys for a derived table were collected and
3583 could be re-used while statement re-execution.
3584 */
3585 bool derived_keys_ready{false};
3586
3587 private:
3588 /// If a recursive reference inside the definition of a CTE.
3589 bool m_is_recursive_reference{false};
3590 // End of group for optimization
3591
3592 private:
3593 /** See comments for set_metadata_id() */
3594 enum_table_ref_type m_table_ref_type{TABLE_REF_NULL};
3595 /** See comments for TABLE_SHARE::get_table_ref_version() */
3596 ulonglong m_table_ref_version{0};
3597 };
3598
3599 /*
3600 Iterator over the fields of a generic table reference.
3601 */
3602
3603 class Field_iterator {
3604 public:
3605 virtual ~Field_iterator() = default;
3606 virtual void set(TABLE_LIST *) = 0;
3607 virtual void next() = 0;
3608 virtual bool end_of_fields() = 0; /* Return 1 at end of list */
3609 virtual const char *name() = 0;
3610 virtual Item *create_item(THD *) = 0;
3611 virtual Field *field() = 0;
3612 };
3613
3614 /*
3615 Iterator over the fields of a base table, view with temporary
3616 table, or subquery.
3617 */
3618
3619 class Field_iterator_table : public Field_iterator {
3620 Field **ptr;
3621
3622 public:
Field_iterator_table()3623 Field_iterator_table() : ptr(nullptr) {}
set(TABLE_LIST * table)3624 void set(TABLE_LIST *table) { ptr = table->table->field; }
set_table(TABLE * table)3625 void set_table(TABLE *table) { ptr = table->field; }
next()3626 void next() { ptr++; }
end_of_fields()3627 bool end_of_fields() { return *ptr == nullptr; }
3628 const char *name();
3629 Item *create_item(THD *thd);
field()3630 Field *field() { return *ptr; }
3631 };
3632
3633 /**
3634 Iterator over the fields of a merged derived table or view.
3635 */
3636
3637 class Field_iterator_view : public Field_iterator {
3638 Field_translator *ptr, *array_end;
3639 TABLE_LIST *view;
3640
3641 public:
Field_iterator_view()3642 Field_iterator_view() : ptr(nullptr), array_end(nullptr) {}
3643 void set(TABLE_LIST *table);
next()3644 void next() { ptr++; }
end_of_fields()3645 bool end_of_fields() { return ptr == array_end; }
3646 const char *name();
3647 Item *create_item(THD *thd);
item_ptr()3648 Item **item_ptr() { return &ptr->item; }
field()3649 Field *field() { return nullptr; }
item()3650 inline Item *item() { return ptr->item; }
field_translator()3651 Field_translator *field_translator() { return ptr; }
3652 };
3653
3654 /*
3655 Field_iterator interface to the list of materialized fields of a
3656 NATURAL/USING join.
3657 */
3658
3659 class Field_iterator_natural_join : public Field_iterator {
3660 List_iterator_fast<Natural_join_column> column_ref_it;
3661 Natural_join_column *cur_column_ref;
3662
3663 public:
Field_iterator_natural_join()3664 Field_iterator_natural_join() : cur_column_ref(nullptr) {}
~Field_iterator_natural_join()3665 ~Field_iterator_natural_join() {}
3666 void set(TABLE_LIST *table);
3667 void next();
end_of_fields()3668 bool end_of_fields() { return !cur_column_ref; }
name()3669 const char *name() { return cur_column_ref->name(); }
create_item(THD * thd)3670 Item *create_item(THD *thd) { return cur_column_ref->create_item(thd); }
field()3671 Field *field() { return cur_column_ref->field(); }
column_ref()3672 Natural_join_column *column_ref() { return cur_column_ref; }
3673 };
3674
3675 /**
3676 Generic iterator over the fields of an arbitrary table reference.
3677
3678 This class unifies the various ways of iterating over the columns
3679 of a table reference depending on the type of SQL entity it
3680 represents. If such an entity represents a nested table reference,
3681 this iterator encapsulates the iteration over the columns of the
3682 members of the table reference.
3683
3684 The implementation assumes that all underlying NATURAL/USING table
3685 references already contain their result columns and are linked into
3686 the list TABLE_LIST::next_name_resolution_table.
3687 */
3688
3689 class Field_iterator_table_ref : public Field_iterator {
3690 TABLE_LIST *table_ref, *first_leaf, *last_leaf;
3691 Field_iterator_table table_field_it;
3692 Field_iterator_view view_field_it;
3693 Field_iterator_natural_join natural_join_it;
3694 Field_iterator *field_it;
3695 void set_field_iterator();
3696
3697 public:
Field_iterator_table_ref()3698 Field_iterator_table_ref() : field_it(nullptr) {}
3699 void set(TABLE_LIST *table);
3700 void next();
end_of_fields()3701 bool end_of_fields() {
3702 return (table_ref == last_leaf && field_it->end_of_fields());
3703 }
name()3704 const char *name() { return field_it->name(); }
3705 const char *get_table_name();
3706 const char *get_db_name();
3707 GRANT_INFO *grant();
create_item(THD * thd)3708 Item *create_item(THD *thd) { return field_it->create_item(thd); }
field()3709 Field *field() { return field_it->field(); }
3710 Natural_join_column *get_or_create_column_ref(THD *thd,
3711 TABLE_LIST *parent_table_ref);
3712 Natural_join_column *get_natural_column_ref();
3713 };
3714
3715 struct OPEN_TABLE_LIST {
3716 OPEN_TABLE_LIST *next;
3717 char *db, *table;
3718 uint32 in_use, locked;
3719 };
3720
tmp_use_all_columns(TABLE * table,MY_BITMAP * bitmap)3721 static inline my_bitmap_map *tmp_use_all_columns(TABLE *table,
3722 MY_BITMAP *bitmap) {
3723 my_bitmap_map *old = bitmap->bitmap;
3724 bitmap->bitmap = table->s->all_set.bitmap; // does not repoint last_word_ptr
3725 return old;
3726 }
3727
tmp_restore_column_map(MY_BITMAP * bitmap,my_bitmap_map * old)3728 static inline void tmp_restore_column_map(MY_BITMAP *bitmap,
3729 my_bitmap_map *old) {
3730 bitmap->bitmap = old;
3731 }
3732
3733 /* The following is only needed for debugging */
3734
dbug_tmp_use_all_columns(TABLE * table MY_ATTRIBUTE ((unused)),MY_BITMAP * bitmap MY_ATTRIBUTE ((unused)))3735 static inline my_bitmap_map *dbug_tmp_use_all_columns(
3736 TABLE *table MY_ATTRIBUTE((unused)),
3737 MY_BITMAP *bitmap MY_ATTRIBUTE((unused))) {
3738 #ifndef DBUG_OFF
3739 return tmp_use_all_columns(table, bitmap);
3740 #else
3741 return nullptr;
3742 #endif
3743 }
3744
dbug_tmp_restore_column_map(MY_BITMAP * bitmap MY_ATTRIBUTE ((unused)),my_bitmap_map * old MY_ATTRIBUTE ((unused)))3745 static inline void dbug_tmp_restore_column_map(
3746 MY_BITMAP *bitmap MY_ATTRIBUTE((unused)),
3747 my_bitmap_map *old MY_ATTRIBUTE((unused))) {
3748 #ifndef DBUG_OFF
3749 tmp_restore_column_map(bitmap, old);
3750 #endif
3751 }
3752
3753 /*
3754 Variant of the above : handle both read and write sets.
3755 Provide for the possiblity of the read set being the same as the write set
3756 */
dbug_tmp_use_all_columns(TABLE * table MY_ATTRIBUTE ((unused)),my_bitmap_map ** save MY_ATTRIBUTE ((unused)),MY_BITMAP * read_set MY_ATTRIBUTE ((unused)),MY_BITMAP * write_set MY_ATTRIBUTE ((unused)))3757 static inline void dbug_tmp_use_all_columns(
3758 TABLE *table MY_ATTRIBUTE((unused)),
3759 my_bitmap_map **save MY_ATTRIBUTE((unused)),
3760 MY_BITMAP *read_set MY_ATTRIBUTE((unused)),
3761 MY_BITMAP *write_set MY_ATTRIBUTE((unused))) {
3762 #ifndef DBUG_OFF
3763 save[0] = read_set->bitmap;
3764 save[1] = write_set->bitmap;
3765 (void)tmp_use_all_columns(table, read_set);
3766 (void)tmp_use_all_columns(table, write_set);
3767 #endif
3768 }
3769
dbug_tmp_restore_column_maps(MY_BITMAP * read_set MY_ATTRIBUTE ((unused)),MY_BITMAP * write_set MY_ATTRIBUTE ((unused)),my_bitmap_map ** old MY_ATTRIBUTE ((unused)))3770 static inline void dbug_tmp_restore_column_maps(
3771 MY_BITMAP *read_set MY_ATTRIBUTE((unused)),
3772 MY_BITMAP *write_set MY_ATTRIBUTE((unused)),
3773 my_bitmap_map **old MY_ATTRIBUTE((unused))) {
3774 #ifndef DBUG_OFF
3775 tmp_restore_column_map(read_set, old[0]);
3776 tmp_restore_column_map(write_set, old[1]);
3777 #endif
3778 }
3779
3780 void init_mdl_requests(TABLE_LIST *table_list);
3781
3782 /**
3783 Unpacks the definition of a generated column, default expression or check
3784 constraint expression passed as argument. Parses the text obtained from
3785 TABLE_SHARE and produces an Item.
3786
3787 @param thd Thread handler
3788 @param table Table with the checked field
3789 @param val_generator The expression to unpack.
3790 @param source Source of value generator(a generated column,
3791 a regular column with generated default value or
3792 a check constraint).
3793 @param source_name Name of the source (generated column, a reguler
3794 column with generated default value or a check
3795 constraint).
3796 @param field Pointer to Field object
3797 @param is_create_table Indicates that table is opened as part
3798 of CREATE or ALTER and does not yet exist in SE
3799 @param error_reported updated flag for the caller that no other error
3800 messages are to be generated.
3801
3802 @retval true Failure.
3803 @retval false Success.
3804 */
3805
3806 bool unpack_value_generator(THD *thd, TABLE *table,
3807 Value_generator **val_generator,
3808 Value_generator_source source,
3809 const char *source_name, Field *field,
3810 bool is_create_table, bool *error_reported);
3811
3812 /**
3813 Unpack the partition expression. Parse the partition expression
3814 to produce an Item.
3815
3816 @param[in] thd Thread handler
3817 @param[in] outparam Table object
3818 @param[in] share TABLE_SHARE object
3819 @param[in] engine_type Engine type of the partitions.
3820 @param[in] is_create_table Indicates that table is opened as part of
3821 CREATE or ALTER and does not yet exist in SE
3822
3823 @retval true Failure.
3824 @retval false Success.
3825 */
3826
3827 bool unpack_partition_info(THD *thd, TABLE *outparam, TABLE_SHARE *share,
3828 handlerton *engine_type, bool is_create_table);
3829
3830 int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias,
3831 uint db_stat, uint prgflag, uint ha_open_flags,
3832 TABLE *outparam, bool is_create_table,
3833 const dd::Table *table_def_param);
3834 TABLE_SHARE *alloc_table_share(const char *db, const char *table_name,
3835 const char *key, size_t key_length,
3836 bool open_secondary);
3837 void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
3838 size_t key_length, const char *table_name,
3839 const char *path, MEM_ROOT *mem_root);
3840 void free_table_share(TABLE_SHARE *share);
3841 void update_create_info_from_table(HA_CREATE_INFO *info, TABLE *form);
3842 Ident_name_check check_db_name(const char *name, size_t length);
3843 Ident_name_check check_and_convert_db_name(LEX_STRING *db,
3844 bool preserve_lettercase);
3845 bool check_column_name(const char *name);
3846 Ident_name_check check_table_name(const char *name, size_t length);
3847 int rename_file_ext(const char *from, const char *to, const char *ext);
3848 char *get_field(MEM_ROOT *mem, Field *field);
3849 bool get_field(MEM_ROOT *mem, Field *field, class String *res);
3850
3851 int closefrm(TABLE *table, bool free_share);
3852 void free_blobs(TABLE *table);
3853 void free_blob_buffers_and_reset(TABLE *table, uint32 size);
3854 int set_zone(int nr, int min_zone, int max_zone);
3855 void append_unescaped(String *res, const char *pos, size_t length);
3856 char *fn_rext(char *name);
3857 TABLE_CATEGORY get_table_category(const LEX_CSTRING &db,
3858 const LEX_CSTRING &name);
3859
3860 /* performance schema */
3861 extern LEX_CSTRING PERFORMANCE_SCHEMA_DB_NAME;
3862
3863 extern LEX_CSTRING GENERAL_LOG_NAME;
3864 extern LEX_CSTRING SLOW_LOG_NAME;
3865
3866 /* information schema */
3867 extern LEX_CSTRING INFORMATION_SCHEMA_NAME;
3868
3869 /* mysql schema name and DD ID */
3870 extern LEX_CSTRING MYSQL_SCHEMA_NAME;
3871 static const uint MYSQL_SCHEMA_DD_ID = 1;
3872
3873 /* mysql tablespace name and DD ID */
3874 extern LEX_CSTRING MYSQL_TABLESPACE_NAME;
3875 static const uint MYSQL_TABLESPACE_DD_ID = 1;
3876
3877 /* replication's tables */
3878 extern LEX_CSTRING RLI_INFO_NAME;
3879 extern LEX_CSTRING MI_INFO_NAME;
3880 extern LEX_CSTRING WORKER_INFO_NAME;
3881
is_infoschema_db(const char * name,size_t len)3882 inline bool is_infoschema_db(const char *name, size_t len) {
3883 return (
3884 INFORMATION_SCHEMA_NAME.length == len &&
3885 !my_strcasecmp(system_charset_info, INFORMATION_SCHEMA_NAME.str, name));
3886 }
3887
is_infoschema_db(const char * name)3888 inline bool is_infoschema_db(const char *name) {
3889 return !my_strcasecmp(system_charset_info, INFORMATION_SCHEMA_NAME.str, name);
3890 }
3891
is_perfschema_db(const char * name,size_t len)3892 inline bool is_perfschema_db(const char *name, size_t len) {
3893 return (PERFORMANCE_SCHEMA_DB_NAME.length == len &&
3894 !my_strcasecmp(system_charset_info, PERFORMANCE_SCHEMA_DB_NAME.str,
3895 name));
3896 }
3897
is_perfschema_db(const char * name)3898 inline bool is_perfschema_db(const char *name) {
3899 return !my_strcasecmp(system_charset_info, PERFORMANCE_SCHEMA_DB_NAME.str,
3900 name);
3901 }
3902
3903 /**
3904 return true if the table was created explicitly.
3905 */
is_user_table(TABLE * table)3906 inline bool is_user_table(TABLE *table) {
3907 const char *name = table->s->table_name.str;
3908 return strncmp(name, tmp_file_prefix, tmp_file_prefix_length);
3909 }
3910
3911 bool is_simple_order(ORDER *order);
3912
3913 uint add_pk_parts_to_sk(KEY *sk, uint sk_n, KEY *pk, uint pk_n,
3914 TABLE_SHARE *share, handler *handler_file,
3915 uint *usable_parts);
3916 void setup_key_part_field(TABLE_SHARE *share, handler *handler_file,
3917 uint primary_key_n, KEY *keyinfo, uint key_n,
3918 uint key_part_n, uint *usable_parts,
3919 bool part_of_key_not_extended);
3920
3921 const uchar *get_field_name(const uchar *arg, size_t *length);
3922
3923 void repoint_field_to_record(TABLE *table, uchar *old_rec, uchar *new_rec);
3924 bool update_generated_write_fields(const MY_BITMAP *bitmap, TABLE *table);
3925 bool update_generated_read_fields(uchar *buf, TABLE *table,
3926 uint active_index = MAX_KEY);
3927
3928 /**
3929 Check if a TABLE_LIST instance represents a pre-opened temporary table.
3930 */
3931
is_temporary_table(const TABLE_LIST * tl)3932 inline bool is_temporary_table(const TABLE_LIST *tl) {
3933 if (tl->is_view() || tl->schema_table) return false;
3934
3935 if (!tl->table) return false;
3936
3937 /*
3938 NOTE: 'table->s' might be NULL for specially constructed TABLE
3939 instances. See SHOW TRIGGERS for example.
3940 */
3941
3942 if (!tl->table->s) return false;
3943
3944 return tl->table->s->tmp_table != NO_TMP_TABLE;
3945 }
3946
3947 /**
3948 After parsing, a Common Table Expression is accessed through a
3949 TABLE_LIST. This class contains all information about the CTE which the
3950 TABLE_LIST needs.
3951
3952 @note that before and during parsing, the CTE is described by a
3953 PT_common_table_expr.
3954 */
3955 class Common_table_expr {
3956 public:
Common_table_expr(MEM_ROOT * mem_root)3957 Common_table_expr(MEM_ROOT *mem_root)
3958 : references(mem_root), recursive(false), tmp_tables(mem_root) {}
3959 TABLE *clone_tmp_table(THD *thd, TABLE_LIST *tl);
3960 bool substitute_recursive_reference(THD *thd, SELECT_LEX *sl);
3961 /// Empties the materialized CTE and informs all of its clones.
3962 bool clear_all_references();
3963 /**
3964 All references to this CTE in the statement, except those inside the
3965 query expression defining this CTE.
3966 In other words, all non-recursive references.
3967 */
3968 Mem_root_array<TABLE_LIST *> references;
3969 /// True if it's a recursive CTE
3970 bool recursive;
3971 /**
3972 List of all TABLE_LISTSs reading/writing to the tmp table created to
3973 materialize this CTE. Due to shared materialization, only the first one
3974 has a TABLE generated by create_tmp_table(); other ones have a TABLE
3975 generated by open_table_from_share().
3976 */
3977 Mem_root_array<TABLE_LIST *> tmp_tables;
3978 /// Name of the WITH block. Used only for EXPLAIN FORMAT=tree.
3979 LEX_STRING name;
3980 };
3981
3982 /**
3983 This iterates on those references to a derived table / view / CTE which are
3984 materialized. If a recursive CTE, this includes recursive references.
3985 Upon construction it is passed a non-recursive materialized reference
3986 to the derived table (TABLE_LIST*).
3987 For a CTE it may return more than one reference; for a derived table or a
3988 view, there is only one (as references to a same view are treated as
3989 independent objects).
3990 References are returned as TABLE*.
3991 */
3992 class Derived_refs_iterator {
3993 TABLE_LIST *const start; ///< The reference provided in construction.
3994 int ref_idx; ///< Current index in cte->tmp_tables
3995 public:
Derived_refs_iterator(TABLE_LIST * start_arg)3996 explicit Derived_refs_iterator(TABLE_LIST *start_arg)
3997 : start(start_arg), ref_idx(-1) {}
get_next()3998 TABLE *get_next() {
3999 ref_idx++;
4000 const Common_table_expr *cte = start->common_table_expr();
4001 if (!cte) return (ref_idx < 1) ? start->table : nullptr;
4002 return ((uint)ref_idx < cte->tmp_tables.size())
4003 ? cte->tmp_tables[ref_idx]->table
4004 : nullptr;
4005 }
rewind()4006 void rewind() { ref_idx = -1; }
4007 /// @returns true if the last get_next() returned the first element.
is_first()4008 bool is_first() const { return ref_idx == 0; }
4009 };
4010
4011 /**
4012 RAII class to reset TABLE::autoinc_field_has_explicit_non_null_value after
4013 processing individual row in INSERT or LOAD DATA statements.
4014 */
4015 class Autoinc_field_has_explicit_non_null_value_reset_guard {
4016 public:
Autoinc_field_has_explicit_non_null_value_reset_guard(TABLE * table)4017 Autoinc_field_has_explicit_non_null_value_reset_guard(TABLE *table)
4018 : m_table(table) {}
~Autoinc_field_has_explicit_non_null_value_reset_guard()4019 ~Autoinc_field_has_explicit_non_null_value_reset_guard() {
4020 m_table->autoinc_field_has_explicit_non_null_value = false;
4021 }
4022
4023 private:
4024 TABLE *m_table;
4025 };
4026
4027 // Whether we can ask the storage engine for the row ID of the last row read.
4028 //
4029 // Some operations needs a row ID to operate correctly (i.e. weedout). Normally,
4030 // the row ID is provided by the storage engine by calling handler::position().
4031 // But there are cases when position() should not be called:
4032 //
4033 // 1. If we have a const table (rows are fetched during optimization), we
4034 // should not call position().
4035 // 2. If we have a NULL-complemented row, calling position() would give a
4036 // random row ID back, as there has not been any row read.
4037 //
4038 // Operations that needs the row ID must also check the value of
4039 // QEP_TAB::rowid_status to see whether they actually need a row ID.
4040 // See QEP_TAB::rowid_status for more details.
can_call_position(const TABLE * table)4041 inline bool can_call_position(const TABLE *table) {
4042 return !table->const_table && !(table->is_nullable() && table->null_row);
4043 }
4044
4045 //////////////////////////////////////////////////////////////////////////
4046
4047 /*
4048 NOTE:
4049 These structures are added to read .frm file in upgrade scenario.
4050
4051 They should not be used any where else in the code.
4052 They will be removed in future release.
4053 Any new code should not be added in this section.
4054 */
4055
4056 /**
4057 These members were removed from TABLE_SHARE as they are not used in
4058 in the code. open_binary_frm() uses these members while reading
4059 .frm files.
4060 */
4061 class FRM_context {
4062 public:
FRM_context()4063 FRM_context()
4064 : default_part_db_type(nullptr),
4065 null_field_first(false),
4066 stored_fields(0),
4067 view_def(nullptr),
4068 frm_version(0),
4069 fieldnames() {}
4070
4071 handlerton *default_part_db_type;
4072 bool null_field_first;
4073 uint stored_fields; /* Number of stored fields
4074 (i.e. without generated-only ones) */
4075
4076 enum utype {
4077 NONE,
4078 DATE,
4079 SHIELD,
4080 NOEMPTY,
4081 CASEUP,
4082 PNR,
4083 BGNR,
4084 PGNR,
4085 YES,
4086 NO,
4087 REL,
4088 CHECK,
4089 EMPTY_VAL, // EMPTY_VAL rather than EMPTY since EMPTY can conflict with
4090 // system headers.
4091 UNKNOWN_FIELD,
4092 CASEDN,
4093 NEXT_NUMBER,
4094 INTERVAL_FIELD,
4095 BIT_FIELD,
4096 TIMESTAMP_OLD_FIELD,
4097 CAPITALIZE,
4098 BLOB_FIELD,
4099 TIMESTAMP_DN_FIELD,
4100 TIMESTAMP_UN_FIELD,
4101 TIMESTAMP_DNUN_FIELD,
4102 GENERATED_FIELD = 128
4103 };
4104
4105 /**
4106 For shares representing views File_parser object with view
4107 definition read from .FRM file.
4108 */
4109 const File_parser *view_def;
4110 uchar frm_version;
4111 TYPELIB fieldnames; /* Pointer to fieldnames */
4112 };
4113
4114 /**
4115 Create TABLE_SHARE from .frm file.
4116
4117 FRM_context object is used to store the value removed from
4118 TABLE_SHARE. These values are used only for .frm file parsing.
4119
4120 @param[in] thd Thread handle.
4121 @param[in] path Path of the frm file.
4122 @param[out] share TABLE_SHARE to be populated.
4123 @param[out] frm_context FRM_context object.
4124 @param[in] db Database name.
4125 @param[in] table Table name.
4126 @param[in] is_fix_view_cols_and_deps Fix view column data, table
4127 and routine dependency.
4128
4129 @retval TABLE_SHARE ON SUCCESS
4130 @retval NULL ON FAILURE
4131 */
4132 bool create_table_share_for_upgrade(THD *thd, const char *path,
4133 TABLE_SHARE *share,
4134 FRM_context *frm_context, const char *db,
4135 const char *table,
4136 bool is_fix_view_cols_and_deps);
4137 //////////////////////////////////////////////////////////////////////////
4138
4139 /**
4140 Create a copy of the key_info from TABLE_SHARE object to TABLE object.
4141
4142 Wherever prefix key is present, allocate a new Field object, having its
4143 field_length set to the prefix key length, and point the table's matching
4144 key_part->field to this new Field object.
4145
4146 This ensures that unpack_partition_info() reads the correct prefix length of
4147 partitioned fields
4148
4149 @param table Table for which key_info is to be allocated
4150 @param root MEM_ROOT in which to allocate key_info
4151
4152 @retval false Success
4153 @retval true Failed to allocate memory for table.key_info in root
4154 */
4155
4156 bool create_key_part_field_with_prefix_length(TABLE *table, MEM_ROOT *root);
4157
4158 #endif /* TABLE_INCLUDED */
4159