MySQL 8.0.29
Source Code Documentation
table.h
Go to the documentation of this file.
1#ifndef TABLE_INCLUDED
2#define TABLE_INCLUDED
3
4/* Copyright (c) 2000, 2022, Oracle and/or its affiliates.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License, version 2.0,
8 as published by the Free Software Foundation.
9
10 This program is also distributed with certain software (including
11 but not limited to OpenSSL) that is licensed under separate terms,
12 as designated in a particular file or component or in included license
13 documentation. The authors of MySQL hereby grant you an additional
14 permission to link the program and your derivative works with the
15 separately licensed software that they have included with MySQL.
16
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License, version 2.0, for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
25
26#include <assert.h>
27#include <string.h>
28#include <sys/types.h>
29#include <string>
30
31#include "field_types.h"
32#include "lex_string.h"
33#include "libbinlogevents/include/table_id.h" // Table_id
34#include "m_ctype.h"
35#include "map_helpers.h"
36#include "mem_root_deque.h"
37#include "my_alloc.h"
38#include "my_base.h"
39#include "my_bitmap.h"
40#include "my_compiler.h"
41
42#include "my_inttypes.h"
43#include "my_sys.h"
44#include "my_table_map.h"
47#include "sql/dd/types/foreign_key.h" // dd::Foreign_key::enum_rule
48#include "sql/enum_query_type.h" // enum_query_type
49#include "sql/key.h"
50#include "sql/key_spec.h"
51#include "sql/mdl.h" // MDL_wait_for_subgraph
52#include "sql/mem_root_array.h"
53#include "sql/opt_costmodel.h" // Cost_model_table
54#include "sql/partition_info.h"
55#include "sql/record_buffer.h" // Record_buffer
56#include "sql/sql_bitmap.h" // Bitmap
57#include "sql/sql_const.h"
58#include "sql/sql_list.h"
59#include "sql/sql_plist.h"
60#include "sql/sql_plugin_ref.h"
61#include "sql/sql_sort.h" // Sort_result
62#include "thr_lock.h"
63#include "typelib.h"
64
65class Field;
66
67namespace histograms {
68class Histogram;
69}
70
73class COND_EQUAL;
74class Field_json;
75/* Structs that defines the TABLE */
76class File_parser;
77class Value_generator;
78class GRANT_TABLE;
79class Handler_share;
80class Index_hint;
81class Item;
82class Item_field;
85class Json_wrapper;
86class Opt_hints_qb;
87class Opt_hints_table;
89class Query_block;
92class SortingIterator;
93class String;
94class THD;
98class handler;
99class partition_info;
100enum enum_stats_auto_recalc : int;
101enum Value_generator_source : short;
102enum row_type : int;
103struct AccessPath;
104struct HA_CREATE_INFO;
105struct LEX;
106struct NESTED_JOIN;
108struct TABLE;
109struct TABLE_LIST;
110struct TABLE_SHARE;
111struct handlerton;
113using plan_idx = int;
114
115namespace dd {
116class Table;
117class View;
118
119enum class enum_table_type;
120} // namespace dd
122
126
130
132
134
135enum class enum_json_diff_operation;
136
138
140
142
143#define store_record(A, B) \
144 memcpy((A)->B, (A)->record[0], (size_t)(A)->s->reclength)
145#define restore_record(A, B) \
146 memcpy((A)->record[0], (A)->B, (size_t)(A)->s->reclength)
147#define cmp_record(A, B) \
148 memcmp((A)->record[0], (A)->B, (size_t)(A)->s->reclength)
149
150#define tmp_file_prefix "#sql" /**< Prefix for tmp tables */
151#define tmp_file_prefix_length 4
152#define TMP_TABLE_KEY_EXTRA 8
153#define PLACEHOLDER_TABLE_ROW_ESTIMATE 2
154
155/**
156 Enumerate possible types of a table from re-execution
157 standpoint.
158 TABLE_LIST class has a member of this type.
159 At prepared statement prepare, this member is assigned a value
160 as of the current state of the database. Before (re-)execution
161 of a prepared statement, we check that the value recorded at
162 prepare matches the type of the object we obtained from the
163 table definition cache.
164
165 @sa check_and_update_table_version()
166 @sa Execute_observer
167 @sa Prepared_statement::reprepare()
168*/
169
171 /** Initial value set by the parser */
178
179/**
180 Enumerate possible status of a identifier name while determining
181 its validity
182*/
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
195 public:
197
198 void restore_env(THD *thd, Object_creation_ctx *backup_ctx);
199
200 protected:
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:
208 virtual ~Object_creation_ctx() = default;
209};
210
211/*************************************************************************/
212
213/**
214 Default_object_creation_ctx -- default implementation of
215 Object_creation_ctx.
216*/
217
219 public:
221
223
224 protected:
226
228 const CHARSET_INFO *connection_cl);
229
230 protected:
231 Object_creation_ctx *create_backup_ctx(THD *thd) const override;
232 void delete_backup_ctx() override;
233
234 void change_env(THD *thd) const override;
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 */
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 */
257};
258
259/**
260 View_creation_ctx -- creation context of view objects.
261*/
262
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:
271};
272
273/*************************************************************************/
274
275/** Order clause list element */
276
278
279struct ORDER {
280 /// @returns true if item pointer is same as original
281 bool is_item_original() const { return item[0] == item_initial; }
282
283 ORDER *next{nullptr};
284
285 /**
286 The initial ordering expression. Usually substituted during resolving
287 and must not be used during optimization and execution.
288 */
289 Item *item_initial{nullptr}; /* Storage for initial item */
290
291 public:
292 /**
293 Points at the item in the select fields. Note that this means that
294 after resolving, it points into a slice (see JOIN::ref_items),
295 even though the item is not of type Item_ref!
296 */
298
300
302 ORDER_NOT_RELEVANT}; /* Requested direction of ordering */
303 bool in_field_list{false}; /* true if in select field list */
304 /**
305 Tells whether this ORDER element was referenced with an alias or with an
306 expression, in the query:
307 SELECT a AS foo GROUP BY foo: true.
308 SELECT a AS foo GROUP BY a: false.
309 */
310 bool used_alias{false};
311 /**
312 When GROUP BY is implemented with a temporary table (i.e. the table takes
313 care to store only unique group rows, table->group != nullptr), each GROUP
314 BY expression is stored in a column of the table, which is
315 'field_in_tmp_table'.
316 Such field may point into table->record[0] (if we only use it to get its
317 value from a tmp table's row), or into 'buff' (if we use it to do index
318 lookup into the tmp table).
319 */
321 char *buff{nullptr}; /* If tmp-table group */
323 bool is_position{false}; /* An item expresses a position in a ORDER clause */
324 bool is_explicit{false}; /* Whether ASC/DESC is explicitly specified */
325};
326
327/**
328 State information for internal tables grants.
329 This structure is part of the TABLE_LIST, and is updated
330 during the ACL check process.
331 @sa GRANT_INFO
332*/
334 /** True if the internal lookup by schema name was done. */
336 /** Cached internal schema access. */
338 /** True if the internal lookup by table name was done. */
340 /** Cached internal table access. */
342};
343
344/**
345 @brief The current state of the privilege checking process for the current
346 user, SQL statement and SQL object.
347
348 @details The privilege checking process is divided into phases depending on
349 the level of the privilege to be checked and the type of object to be
350 accessed. Due to the mentioned scattering of privilege checking
351 functionality, it is necessary to keep track of the state of the process.
352
353 A GRANT_INFO also serves as a cache of the privilege hash tables. Relevant
354 members are grant_table and version.
355 */
357 GRANT_INFO();
358 /**
359 @brief A copy of the privilege information regarding the current host,
360 database, object and user.
361
362 @details The version of this copy is found in GRANT_INFO::version.
363 */
365 /**
366 @brief Used for cache invalidation when caching privilege information.
367
368 @details The privilege information is stored on disk, with dedicated
369 caches residing in memory: table-level and column-level privileges,
370 respectively, have their own dedicated caches.
371
372 The GRANT_INFO works as a level 1 cache with this member updated to the
373 current value of the global variable @c grant_version (@c static variable
374 in sql_acl.cc). It is updated Whenever the GRANT_INFO is refreshed from
375 the level 2 cache. The level 2 cache is the @c column_priv_hash structure
376 (@c static variable in sql_acl.cc)
377
378 @see grant_version
379 */
381 /**
382 @brief The set of privileges that the current user has fulfilled for a
383 certain host, database, and object.
384
385 @details This field is continually updated throughout the access checking
386 process. In each step the "wanted privilege" is checked against the
387 fulfilled privileges. When/if the intersection of these sets is empty,
388 access is granted.
389
390 The set is implemented as a bitmap, with the bits defined in sql_acl.h.
391 */
392 ulong privilege{0};
393 /** The grant state for internal tables. */
395};
396
404
405/**
406 Category of table found in the table share.
407*/
409 /**
410 Unknown value.
411 */
413
414 /**
415 Temporary table.
416 The table is visible only in the session.
417 Therefore,
418 - FLUSH TABLES WITH READ LOCK
419 - SET GLOBAL READ_ONLY = ON
420 do not apply to this table.
421 Note that LOCK TABLE t FOR READ/WRITE
422 can be used on temporary tables.
423 Temporary tables are not part of the table cache.
424
425 2016-06-14 Contrary to what's written in these comments, the truth is:
426 - tables created by CREATE TEMPORARY TABLE have TABLE_CATEGORY_USER
427 - tables created by create_tmp_table() (internal ones) have
428 TABLE_CATEGORY_TEMPORARY.
429 ha_innodb.cc relies on this observation (so: grep it). If you clean this
430 up, you may also want to look at 'no_tmp_table'; its enum values' meanings
431 have degraded over time: INTERNAL_TMP_TABLE is not used for some internal
432 tmp tables (derived tables). Unification of both enums would be
433 great. Whatever the result, we need to be able to distinguish the two
434 types of temporary tables above, as usage patterns are more restricted for
435 the second type, and allow more optimizations.
436 */
438
439 /**
440 User table.
441 These tables do honor:
442 - LOCK TABLE t FOR READ/WRITE
443 - FLUSH TABLES WITH READ LOCK
444 - SET GLOBAL READ_ONLY = ON
445 User tables are cached in the table cache.
446 */
448
449 /**
450 System table, maintained by the server.
451 These tables do honor:
452 - LOCK TABLE t FOR READ/WRITE
453 - FLUSH TABLES WITH READ LOCK
454 - SET GLOBAL READ_ONLY = ON
455 Typically, writes to system tables are performed by
456 the server implementation, not explicitly be a user.
457 System tables are cached in the table cache.
458 */
460
461 /**
462 Information schema tables.
463 These tables are an interface provided by the system
464 to inspect the system metadata.
465 These tables do *not* honor:
466 - LOCK TABLE t FOR READ/WRITE
467 - FLUSH TABLES WITH READ LOCK
468 - SET GLOBAL READ_ONLY = ON
469 as there is no point in locking explicitly
470 an INFORMATION_SCHEMA table.
471 Nothing is directly written to information schema tables.
472 Note that this value is not used currently,
473 since information schema tables are not shared,
474 but implemented as session specific temporary tables.
475 */
476 /*
477 TODO: Fixing the performance issues of I_S will lead
478 to I_S tables in the table cache, which should use
479 this table type.
480 */
482
483 /**
484 Log tables.
485 These tables are an interface provided by the system
486 to inspect the system logs.
487 These tables do *not* honor:
488 - LOCK TABLE t FOR READ/WRITE
489 - FLUSH TABLES WITH READ LOCK
490 - SET GLOBAL READ_ONLY = ON
491 as there is no point in locking explicitly
492 a LOG table.
493 An example of LOG tables are:
494 - mysql.slow_log
495 - mysql.general_log,
496 which *are* updated even when there is either
497 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
498 User queries do not write directly to these tables
499 (there are exceptions for log tables).
500 The server implementation perform writes.
501 Log tables are cached in the table cache.
502 */
504
505 /**
506 Performance schema tables.
507 These tables are an interface provided by the system
508 to inspect the system performance data.
509 These tables do *not* honor:
510 - LOCK TABLE t FOR READ/WRITE
511 - FLUSH TABLES WITH READ LOCK
512 - SET GLOBAL READ_ONLY = ON
513 as there is no point in locking explicitly
514 a PERFORMANCE_SCHEMA table.
515 An example of PERFORMANCE_SCHEMA tables are:
516 - performance_schema.*
517 which *are* updated (but not using the handler interface)
518 even when there is either
519 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
520 User queries do not write directly to these tables
521 (there are exceptions for SETUP_* tables).
522 The server implementation perform writes.
523 Performance tables are cached in the table cache.
524 */
526
527 /**
528 Replication Information Tables.
529 These tables are used to store replication information.
530 These tables do *not* honor:
531 - LOCK TABLE t FOR READ/WRITE
532 - FLUSH TABLES WITH READ LOCK
533 - SET GLOBAL READ_ONLY = ON
534 as there is no point in locking explicitly
535 a Replication Information table.
536 An example of replication tables are:
537 - mysql.slave_master_info
538 - mysql.slave_relay_log_info,
539 which *are* updated even when there is either
540 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
541 User queries do not write directly to these tables.
542 Replication tables are cached in the table cache.
543 */
545
546 /**
547 Gtid Table.
548 The table is used to store gtids.
549 The table does *not* honor:
550 - LOCK TABLE t FOR READ/WRITE
551 - FLUSH TABLES WITH READ LOCK
552 - SET GLOBAL READ_ONLY = ON
553 as there is no point in locking explicitly
554 a Gtid table.
555 An example of gtid_executed table is:
556 - mysql.gtid_executed,
557 which is updated even when there is either
558 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
559 Gtid table is cached in the table cache.
560 */
562
563 /**
564 A data dictionary table.
565 Table's with this category will skip checking the
566 TABLE_SHARE versions because these table structures
567 are fixed upon server bootstrap.
568 */
570
571 /**
572 A ACL metadata table.
573 For table in this category we will skip row locks when SQL statement
574 reads them.
575 */
579
580extern ulong refresh_version;
581
586};
587
591};
592
594 protected:
596 virtual void report_error(uint code, const char *fmt, ...) = 0;
597
598 public:
600 virtual ~Table_check_intact() = default;
601
602 /**
603 Checks whether a table is intact. Should be done *just* after the table has
604 been opened.
605
606 @param[in] thd Thread handle
607 @param[in] table The table to check
608 @param[in] table_def Expected structure of the table (column name
609 and type)
610
611 @retval false OK
612 @retval true There was an error.
613 */
614 bool check(THD *thd, TABLE *table, const TABLE_FIELD_DEF *table_def);
615};
616
617/**
618 Class representing the fact that some thread waits for table
619 share to be flushed. Is used to represent information about
620 such waits in MDL deadlock detector.
621*/
622
627
628 public:
630 uint deadlock_weight_arg)
631 : m_ctx(ctx_arg),
632 m_share(share_arg),
633 m_deadlock_weight(deadlock_weight_arg) {}
634
635 MDL_context *get_ctx() const { return m_ctx; }
636
637 bool accept_visitor(MDL_wait_for_graph_visitor *dvisitor) override;
638
639 uint get_deadlock_weight() const override;
640
641 /**
642 Pointers for participating in the list of waiters for table share.
643 */
646};
647
648typedef I_P_List<
653
657 /**
658 Name of unique key matching FK in parent table, "" if there is no
659 unique key.
660 */
664 /**
665 Arrays with names of referencing columns of the FK.
666 */
669
675
676/**
677 Definition of name for generated keys, owned by TABLE_SHARE
678*/
679struct Key_name {
681};
682
683/**
684 This structure is shared between different table objects. There is one
685 instance of table share per one table in the database.
686*/
687
689 TABLE_SHARE() = default;
690
691 /**
692 Create a new TABLE_SHARE with the given version number.
693 @param version the version of the TABLE_SHARE
694 @param secondary set to true if the TABLE_SHARE represents a table
695 in a secondary storage engine
696 */
697 TABLE_SHARE(unsigned long version, bool secondary)
698 : m_version(version), m_secondary_engine(secondary) {}
699
700 /*
701 A map of [uint, Histogram] values, where the key is the field index. The
702 map is populated with any histogram statistics when it is loaded/created.
703 */
705 nullptr};
706
707 /**
708 Find the histogram for the given field index.
709
710 @param field_index the index of the field we want to find a histogram for
711
712 @retval nullptr if no histogram is found
713 @retval a pointer to a histogram if one is found
714 */
715 const histograms::Histogram *find_histogram(uint field_index) const;
716
717 /** Category of this table. */
719
721 /**
722 Used to allocate new handler for internal temporary table when the
723 size limitation of the primary storage engine is exceeded.
724 */
726
727 TYPELIB keynames; /* Pointers to keynames */
728 TYPELIB *intervals{nullptr}; /* pointer to interval info */
729 mysql_mutex_t LOCK_ha_data; /* To protect access to ha_data */
730 TABLE_SHARE *next{nullptr}, **prev{nullptr}; /* Link to unused shares */
731 /**
732 Array of table_cache_instances pointers to elements of table caches
733 respresenting this table in each of Table_cache instances.
734 Allocated along with the share itself in alloc_table_share().
735 Each element of the array is protected by Table_cache::m_lock in the
736 corresponding Table_cache. False sharing should not be a problem in
737 this case as elements of this array are supposed to be updated rarely.
738 */
740
741 /* The following is copied to each TABLE on OPEN */
742 Field **field{nullptr};
744 KEY *key_info{nullptr}; /* data of keys defined for the table */
745 uint *blob_field{nullptr}; /* Index to blobs in Field arrray*/
746
747 uchar *default_values{nullptr}; /* row with default values */
748 LEX_STRING comment{nullptr, 0}; /* Comment about table */
749 LEX_STRING compress{nullptr, 0}; /* Compression algorithm */
750 LEX_STRING encrypt_type{nullptr, 0}; /* encryption algorithm */
751
752 /** Secondary storage engine. */
754
756 nullptr}; /* Default charset of string fields */
757
759 /*
760 Key which is used for looking-up table in table cache and in the list
761 of thread's temporary tables. Has the form of:
762 "database_name\0table_name\0" + optional part for temporary tables.
763
764 Note that all three 'table_cache_key', 'db' and 'table_name' members
765 must be set (and be non-zero) for tables in table cache. They also
766 should correspond to each other.
767 To ensure this one can use set_table_cache() methods.
768 */
770 LEX_CSTRING db{nullptr, 0}; /* Pointer to db */
771 LEX_CSTRING table_name{nullptr, 0}; /* Table name (for open) */
772 LEX_STRING path{nullptr, 0}; /* Path to .frm file (from datadir) */
773 LEX_CSTRING normalized_path{nullptr, 0}; /* unpack_filename(path) */
775
778
779 /**
780 The set of indexes that are not disabled for this table. I.e. it excludes
781 indexes disabled by `ALTER TABLE ... DISABLE KEYS`, however it does
782 include invisible indexes. The data dictionary populates this bitmap.
783 */
785
786 /// The set of visible and enabled indexes for this table.
789 ha_rows min_rows{0}, max_rows{0}; /* create information */
790 ulong avg_row_length{0}; /* create information */
791 ulong mysql_version{0}; /* 0 if .frm is created before 5.0 */
792 ulong reclength{0}; /* Recordlength */
793 ulong stored_rec_length{0}; /* Stored record length
794 (no generated-only generated fields) */
796
797 plugin_ref db_plugin{nullptr}; /* storage engine plugin */
798 inline handlerton *db_type() const /* table_type for handler */
799 {
800 // assert(db_plugin);
801 return db_plugin ? plugin_data<handlerton *>(db_plugin) : NULL;
802 }
803 /**
804 Value of ROW_FORMAT option for the table as provided by user.
805 Can be different from the real row format used by the storage
806 engine. ROW_TYPE_DEFAULT value indicates that no explicit
807 ROW_FORMAT was specified for the table. @sa real_row_type.
808 */
809 enum row_type row_type = {}; // Zero-initialized to ROW_TYPE_DEFAULT
810 /** Real row format used for the table by the storage engine. */
811 enum row_type real_row_type = {}; // Zero-initialized to ROW_TYPE_DEFAULT
813
814 /**
815 Only for internal temporary tables.
816 Count of TABLEs (having this TABLE_SHARE) which have a "handler"
817 (table->file!=nullptr) which is open (ha_open() has been called).
818 */
820
821 /**
822 Only for internal temporary tables.
823 Count of TABLEs (having this TABLE_SHARE) which have opened this table.
824 */
826
827 // Can only be 1,2,4,8 or 16, but use uint32_t since that how it is
828 // represented in InnoDB
829 std::uint32_t key_block_size{0}; /* create key_block_size, if used */
830 uint stats_sample_pages{0}; /* number of pages to sample during
831 stats estimation, if used, otherwise 0. */
833 stats_auto_recalc{}; /* Automatic recalc of stats.
834 Zero-initialized to HA_STATS_AUTO_RECALC_DEFAULT
835 */
837 uint fields{0}; /* Number of fields */
838 uint rec_buff_length{0}; /* Size of table->record[] buffer */
839 uint keys{0}; /* Number of keys defined for the table*/
840 uint key_parts{0}; /* Number of key parts of all keys
841 defined for the table
842 */
843 uint max_key_length{0}; /* Length of the longest key */
844 uint max_unique_length{0}; /* Length of the longest unique key */
846 /**
847 Whether this is a temporary table that already has a UNIQUE index (removing
848 duplicate rows on insert), so that the optimizer does not need to run
849 DISTINCT itself.
850 */
851 bool is_distinct{false};
852
853 uint null_fields{0}; /* number of null fields */
854 uint blob_fields{0}; /* number of blob fields */
855 uint varchar_fields{0}; /* number of varchar fields */
856 /**
857 For materialized derived tables; @see add_derived_key().
858 'first' means: having the lowest position in key_info.
859 */
861 /**
862 For materialized derived tables: allocated size of key_info array.
863 */
865 /**
866 For materialized derived tables: allocated size of base_key_parts array of
867 all TABLE objects. Used for generated keys.
868 */
870 /**
871 Array of names for generated keys, used for materialized derived tables.
872 Shared among all TABLE objects referring to this table share.
873 */
875 /**
876 Records per key array, used for materialized derived tables.
877 This is a contiguous array, with size given by max_tmp_key_parts.
878 The array is shared with all TABLE objects referring to this table share.
879 */
880 ulong *base_rec_per_key{nullptr};
881 /**
882 Records per key array, float rep., used for materialized derived tables.
883 This is a contiguous array, with size given by max_tmp_key_parts.
884 The array is shared with all TABLE objects referring to this table share.
885 */
887 /**
888 Bitmap with flags representing some of table options/attributes.
889
890 @sa HA_OPTION_PACK_RECORD, HA_OPTION_PACK_KEYS, ...
891
892 @note This is basically copy of HA_CREATE_INFO::table_options bitmap
893 at the time of table opening/usage.
894 */
896 /**
897 Bitmap with flags representing some of table options/attributes which
898 are in use by storage engine.
899
900 @note db_options_in_use is normally copy of db_create_options but can
901 be overriden by SE. E.g. MyISAM does this at handler::open() and
902 hander::info() time.
903 */
905 uint rowid_field_offset{0}; /* Field_nr +1 to rowid field */
906 /* Primary key index number, used in TABLE::key_info[] */
908 uint next_number_index{0}; /* autoincrement key number */
909 uint next_number_key_offset{0}; /* autoinc keypart offset in a key */
910 uint next_number_keypart{0}; /* autoinc keypart number in a key */
911 bool error{false}; /* error during open_table_def() */
913 /// Number of generated fields
915 /// Number of fields having the default value generated
917 bool system{false}; /* Set if system table (one record) */
918 bool db_low_byte_first{false}; /* Portable row format */
919 bool crashed{false};
920 bool is_view{false};
921 bool m_open_in_progress{false}; /* True: alloc'ed, false: def opened */
922 Table_id table_map_id; /* for row-based replication */
923
924 /*
925 Cache for row-based replication table share checks that does not
926 need to be repeated. Possible values are: -1 when cache value is
927 not calculated yet, 0 when table *shall not* be replicated, 1 when
928 table *may* be replicated.
929 */
931
932 /*
933 Storage media to use for this table (unless another storage
934 media has been specified on an individual column - in versions
935 where that is supported)
936 */
938
939 /* Name of the tablespace used for this table */
940 const char *tablespace{nullptr};
941
942 /**
943 Partition meta data. Allocated from TABLE_SHARE::mem_root,
944 created when reading from the dd tables,
945 used as template for each TABLE instance.
946 The reason for having it on the TABLE_SHARE is to be able to reuse the
947 partition_elements containing partition names, values etc. instead of
948 allocating them for each TABLE instance.
949 TODO: Currently it is filled in and then only used for generating
950 the partition_info_str. The plan is to clone/copy/reference each
951 TABLE::part_info instance from it.
952 What is missing before it can be completed:
953 1) The partition expression, currently created only during parsing which
954 also needs the current TABLE instance as context for name resolution etc.
955 2) The partition values, currently the DD stores them as text so it needs
956 to be converted to field images (which is now done by first parsing the
957 value text into an Item, then saving the Item result/value into a field
958 and then finally copy the field image).
959 */
961 // TODO: Remove these four variables:
962 /**
963 Filled in when reading from frm.
964 This can simply be removed when removing the .frm support,
965 since it is already stored in the new DD.
966 */
967 bool auto_partitioned{false};
968 /**
969 Storing the full partitioning clause (PARTITION BY ...) which is used
970 when creating new partition_info object for each new TABLE object by
971 parsing this string.
972 These two will be needed until the missing parts above is fixed.
973 */
974 char *partition_info_str{nullptr};
976
977 /**
978 Cache the checked structure of this table.
979
980 The pointer data is used to describe the structure that
981 a instance of the table must have. Each element of the
982 array specifies a field that must exist on the table.
983
984 The pointer is cached in order to perform the check only
985 once -- when the table is loaded from the disk.
986 */
988
989 /** Main handler's share */
991
992 /** Instrumentation for this table share. */
994
995 /**
996 List of tickets representing threads waiting for the share to be flushed.
997 */
999
1000 /**
1001 View object holding view definition read from DD. This object is not
1002 cached, and is owned by the table share. We are not able to read it
1003 on demand since we may then get a cache miss while holding LOCK_OPEN.
1004 */
1005 const dd::View *view_object{nullptr};
1006
1007 /**
1008 Data-dictionary object describing explicit temporary table represented
1009 by this share. NULL for other table types (non-temporary tables, internal
1010 temporary tables). This object is owned by TABLE_SHARE and should be
1011 deleted along with it.
1012 */
1014
1015 /// For materialized derived tables; @see add_derived_key().
1017
1018 /**
1019 Arrays with descriptions of foreign keys in which this table participates
1020 as child or parent. We only cache in them information from dd::Table object
1021 which is sufficient for use by prelocking algorithm/to check if table is
1022 referenced by a foreign key.
1023 */
1028
1029 // List of check constraint share instances.
1031
1032 /**
1033 Schema's read only mode - ON (true) or OFF (false). This is filled in
1034 when the share is initialized with meta data from DD. If the schema is
1035 altered, the tables and share are removed. This can be done since
1036 ALTER SCHEMA acquires exclusive meta data locks on the tables in the
1037 schema. We set this only for non-temporary tables. Otherwise, the value
1038 of the member below is 'NOT_SET'.
1039 */
1042
1043 /**
1044 Set share's table cache key and update its db and table name appropriately.
1045
1046 @param key_buff Buffer with already built table cache key to be
1047 referenced from share.
1048 @param key_length Key length.
1049
1050 @note
1051 Since 'key_buff' buffer will be referenced from share it should has same
1052 life-time as share itself.
1053 This method automatically ensures that TABLE_SHARE::table_name/db have
1054 appropriate values by using table cache key as their source.
1055 */
1056
1057 void set_table_cache_key(char *key_buff, size_t key_length) {
1058 table_cache_key.str = key_buff;
1060 /*
1061 Let us use the fact that the key is "db/0/table_name/0" + optional
1062 part for temporary tables.
1063 */
1065 db.length = strlen(db.str);
1066 table_name.str = db.str + db.length + 1;
1067 table_name.length = strlen(table_name.str);
1068 }
1069
1070 /**
1071 Set share's table cache key and update its db and table name appropriately.
1072
1073 @param key_buff Buffer to be used as storage for table cache key
1074 (should be at least key_length bytes).
1075 @param key Value for table cache key.
1076 @param key_length Key length.
1077
1078 NOTE
1079 Since 'key_buff' buffer will be used as storage for table cache key
1080 it should has same life-time as share itself.
1081 */
1082
1083 void set_table_cache_key(char *key_buff, const char *key, size_t key_length) {
1084 memcpy(key_buff, key, key_length);
1086 }
1087
1089
1090 /** Returns the version of this TABLE_SHARE. */
1091 unsigned long version() const { return m_version; }
1092
1093 /**
1094 Set the version of this TABLE_SHARE to zero. This marks the
1095 TABLE_SHARE for automatic removal from the table definition cache
1096 once it is no longer referenced.
1097 */
1098 void clear_version();
1099
1100 /** Is this table share being expelled from the table definition cache? */
1101 bool has_old_version() const { return version() != refresh_version; }
1102
1103 /**
1104 Convert unrelated members of TABLE_SHARE to one enum
1105 representing its type.
1106
1107 @todo perhaps we need to have a member instead of a function.
1108 */
1110 if (is_view) return TABLE_REF_VIEW;
1111 switch (tmp_table) {
1112 case NO_TMP_TABLE:
1113 return TABLE_REF_BASE_TABLE;
1114 case SYSTEM_TMP_TABLE:
1115 return TABLE_REF_I_S_TABLE;
1116 default:
1117 return TABLE_REF_TMP_TABLE;
1118 }
1119 }
1120 /**
1121 Return a table metadata version.
1122 * for base tables and views, we return table_map_id.
1123 It is assigned from a global counter incremented for each
1124 new table loaded into the table definition cache (TDC).
1125 * for temporary tables it's table_map_id again. But for
1126 temporary tables table_map_id is assigned from
1127 thd->query_id. The latter is assigned from a thread local
1128 counter incremented for every new SQL statement. Since
1129 temporary tables are thread-local, each temporary table
1130 gets a unique id.
1131 * for everything else (e.g. information schema tables),
1132 the version id is zero.
1133
1134 This choice of version id is a large compromise
1135 to have a working prepared statement validation in 5.1. In
1136 future version ids will be persistent, as described in WL#4180.
1137
1138 Let's try to explain why and how this limited solution allows
1139 to validate prepared statements.
1140
1141 Firstly, sets (in mathematical sense) of version numbers
1142 never intersect for different table types. Therefore,
1143 version id of a temporary table is never compared with
1144 a version id of a view, and vice versa.
1145
1146 Secondly, for base tables and views, we know that each DDL flushes
1147 the respective share from the TDC. This ensures that whenever
1148 a table is altered or dropped and recreated, it gets a new
1149 version id.
1150 Unfortunately, since elements of the TDC are also flushed on
1151 LRU basis, this choice of version ids leads to false positives.
1152 E.g. when the TDC size is too small, we may have a SELECT
1153 * FROM INFORMATION_SCHEMA.TABLES flush all its elements, which
1154 in turn will lead to a validation error and a subsequent
1155 reprepare of all prepared statements. This is
1156 considered acceptable, since as long as prepared statements are
1157 automatically reprepared, spurious invalidation is only
1158 a performance hit. Besides, no better simple solution exists.
1159
1160 For temporary tables, using thd->query_id ensures that if
1161 a temporary table was altered or recreated, a new version id is
1162 assigned. This suits validation needs very well and will perhaps
1163 never change.
1164
1165 Metadata of information schema tables never changes.
1166 Thus we can safely assume 0 for a good enough version id.
1167
1168 Finally, by taking into account table type, we always
1169 track that a change has taken place when a view is replaced
1170 with a base table, a base table is replaced with a temporary
1171 table and so on.
1172
1173 @retval 0 For schema tables, DD tables and system views.
1174 non-0 For bases tables, views and temporary tables.
1175
1176 @sa TABLE_LIST::is_table_ref_id_equal()
1177 */
1179
1180 /** Determine if the table is missing a PRIMARY KEY. */
1182 assert(primary_key <= MAX_KEY);
1183 return primary_key == MAX_KEY;
1184 }
1185
1187
1188 bool visit_subgraph(Wait_for_flush *waiting_ticket,
1189 MDL_wait_for_graph_visitor *gvisitor);
1190
1191 bool wait_for_old_version(THD *thd, struct timespec *abstime,
1192 uint deadlock_weight);
1193
1194 /**
1195 The set of indexes that the optimizer may use when creating an execution
1196 plan.
1197 */
1198 Key_map usable_indexes(const THD *thd) const;
1199
1200 /** Release resources and free memory occupied by the table share. */
1201 void destroy();
1202
1203 /**
1204 How many TABLE objects use this TABLE_SHARE.
1205 @return the reference count
1206 */
1207 unsigned int ref_count() const {
1208 assert(assert_ref_count_is_locked(this));
1209 return m_ref_count;
1210 }
1211
1212 /**
1213 Increment the reference count by one.
1214 @return the new reference count
1215 */
1216 unsigned int increment_ref_count() {
1217 assert(assert_ref_count_is_locked(this));
1218 assert(!m_open_in_progress);
1219 return ++m_ref_count;
1220 }
1221
1222 /**
1223 Decrement the reference count by one.
1224 @return the new reference count
1225 */
1226 unsigned int decrement_ref_count() {
1227 assert(assert_ref_count_is_locked(this));
1228 assert(!m_open_in_progress);
1229 assert(m_ref_count > 0);
1230 return --m_ref_count;
1231 }
1232
1233 /// Does this TABLE_SHARE represent a table in a primary storage engine?
1234 bool is_primary_engine() const { return !m_secondary_engine; }
1235
1236 /// Does this TABLE_SHARE represent a table in a secondary storage engine?
1238
1239 /**
1240 Does this TABLE_SHARE represent a primary table that has a shadow
1241 copy in a secondary storage engine?
1242 */
1244 return is_primary_engine() && secondary_engine.str != nullptr;
1245 }
1246
1247 /** Returns whether this table is referenced by a foreign key. */
1249
1250 private:
1251 /// How many TABLE objects use this TABLE_SHARE.
1252 unsigned int m_ref_count{0};
1253
1254 /**
1255 TABLE_SHARE version, if changed the TABLE_SHARE must be reopened.
1256 NOTE: The TABLE_SHARE will not be reopened during LOCK TABLES in
1257 close_thread_tables!!!
1258 */
1259 unsigned long m_version{0};
1260
1261 /// Does this TABLE_SHARE represent a table in a secondary storage engine?
1263};
1264
1265/**
1266 Class is used as a BLOB field value storage for
1267 intermediate GROUP_CONCAT results. Used only for
1268 GROUP_CONCAT with DISTINCT or ORDER BY options.
1269 */
1270
1272 private:
1274 /**
1275 Sign that some values were cut
1276 during saving into the storage.
1277 */
1279
1280 public:
1283
1284 void reset() {
1286 truncated_value = false;
1287 }
1288 /**
1289 Fuction creates duplicate of 'from'
1290 string in 'storage' MEM_ROOT.
1291
1292 @param from string to copy
1293 @param length string length
1294
1295 @retval Pointer to the copied string.
1296 @retval 0 if an error occurred.
1297 */
1298 char *store(const char *from, size_t length) {
1299 return (char *)memdup_root(&storage, from, length);
1300 }
1303 }
1304 bool is_truncated_value() const { return truncated_value; }
1305};
1306
1307/**
1308 Class that represents a single change to a column value in partial
1309 update of a JSON column.
1310*/
1311class Binary_diff final {
1312 /// The offset of the start of the change.
1313 size_t m_offset;
1314
1315 /// The size of the portion that is to be replaced.
1316 size_t m_length;
1317
1318 public:
1319 /**
1320 Create a new Binary_diff object.
1321
1322 @param offset the offset of the beginning of the change
1323 @param length the length of the section that is to be replaced
1324 */
1325 Binary_diff(size_t offset, size_t length)
1327
1328 /// @return the offset of the changed data
1329 size_t offset() const { return m_offset; }
1330
1331 /// @return the length of the changed data
1332 size_t length() const { return m_length; }
1333
1334 /**
1335 Get a pointer to the start of the replacement data.
1336
1337 @param field the column that is updated
1338 @return a pointer to the start of the replacement data
1339 */
1340 const char *new_data(const Field *field) const;
1341
1342 /**
1343 Get a pointer to the start of the old data to be replaced.
1344
1345 @param field the column that is updated
1346 @return a pointer to the start of old data to be replaced.
1347 */
1348 const char *old_data(const Field *field) const;
1349};
1350
1351/**
1352 Vector of Binary_diff objects.
1353
1354 The Binary_diff objects in the vector should be ordered on offset, and none
1355 of the diffs should be overlapping or adjacent.
1356*/
1358
1359/**
1360 Flags for TABLE::m_status (maximum 8 bits).
1361 The flags define the state of the row buffer in TABLE::record[0].
1362*/
1363/**
1364 STATUS_NOT_STARTED is set when table is not accessed yet.
1365 Neither STATUS_NOT_FOUND nor STATUS_NULL_ROW can be set when this flag is set.
1366*/
1367#define STATUS_NOT_STARTED 1
1368/**
1369 Means we were searching for a row and didn't find it. This is used by
1370 storage engines (@see handler::index_read_map()) and the executor, both
1371 when doing an exact row lookup and advancing a scan (no more rows in range).
1372*/
1373#define STATUS_NOT_FOUND 2
1374/// Reserved for use by multi-table update. Means the row has been updated.
1375#define STATUS_UPDATED 16
1376/**
1377 Means that table->null_row is set. This is an artificial NULL-filled row
1378 (one example: in outer join, if no match has been found in inner table).
1379*/
1380#define STATUS_NULL_ROW 32
1381/// Reserved for use by multi-table delete. Means the row has been deleted.
1382#define STATUS_DELETED 64
1383
1384/* Information for one open table */
1386
1387/* Bitmap of table's fields */
1389
1390/*
1391 NOTE: Despite being a struct (for historical reasons), TABLE has
1392 a nontrivial destructor.
1393*/
1394struct TABLE {
1395 TABLE_SHARE *s{nullptr};
1396 handler *file{nullptr};
1397 TABLE *next{nullptr}, *prev{nullptr};
1398
1399 private:
1400 /**
1401 Links for the lists of used/unused TABLE objects for the particular
1402 table in the specific instance of Table_cache (in other words for
1403 specific Table_cache_element object).
1404 Declared as private to avoid direct manipulation with those objects.
1405 One should use methods of I_P_List template instead.
1406 */
1407 TABLE *cache_next{nullptr}, **cache_prev{nullptr};
1408
1409 /*
1410 Give Table_cache_element access to the above two members to allow
1411 using them for linking TABLE objects in a list.
1412 */
1414
1415 public:
1416 /**
1417 A bitmap marking the hidden generated columns that exists for functional
1418 indexes.
1419 */
1421 /**
1422 The current session using this table object.
1423 Should be NULL when object is not in use.
1424 For an internal temporary table, it is NULL when the table is closed.
1425 Used for two purposes:
1426 - Signal that the object is in use, and by which session.
1427 - Pass the thread handler to storage handlers.
1428 The field should NOT be used as a general THD reference, instead use
1429 a passed THD reference, or, if there is no such, current_thd.
1430 The reason for this is that we cannot guarantee the field is not NULL.
1431 */
1432 THD *in_use{nullptr};
1433 Field **field{nullptr}; /* Pointer to fields */
1434 /// Count of hidden fields, if internal temporary table; 0 otherwise.
1436
1437 uchar *record[2]{nullptr, nullptr}; /* Pointer to records */
1438 uchar *write_row_record{nullptr}; /* Used as optimisation in
1439 THD::write_row */
1440 uchar *insert_values{nullptr}; /* used by INSERT ... UPDATE */
1441
1442 /// Buffer for use in multi-row reads. Initially empty.
1444
1445 /*
1446 Map of keys that can be used to retrieve all data from this table
1447 needed by the query without reading the row.
1448 */
1451
1452 /* Merge keys are all keys that had a column reffered to in the query */
1454
1455 /*
1456 possible_quick_keys is a superset of quick_keys to use with EXPLAIN of
1457 JOIN-less commands (single-table UPDATE and DELETE).
1458
1459 When explaining regular JOINs, we use JOIN_TAB::keys to output the
1460 "possible_keys" column value. However, it is not available for
1461 single-table UPDATE and DELETE commands, since they don't use JOIN
1462 optimizer at the top level. OTOH they directly use the range optimizer,
1463 that collects all keys usable for range access here.
1464 */
1466
1467 /*
1468 A set of keys that can be used in the query that references this
1469 table.
1470
1471 All indexes disabled on the table's TABLE_SHARE (see TABLE::s) will be
1472 subtracted from this set upon instantiation. Thus for any TABLE t it holds
1473 that t.keys_in_use_for_query is a subset of t.s.keys_in_use. Generally we
1474 must not introduce any new keys here (see setup_tables).
1475
1476 The set is implemented as a bitmap.
1477 */
1479 /* Map of keys that can be used to calculate GROUP BY without sorting */
1481 /* Map of keys that can be used to calculate ORDER BY without sorting */
1483 KEY *key_info{nullptr}; /* data of keys defined for the table */
1484 /**
1485 Key part array for generated keys, used for materialized derived tables.
1486 This is a contiguous array, with size given by s->max_tmp_key_parts.
1487 */
1489
1490 Field *next_number_field{nullptr}; /* Set if next_number is activated */
1491 Field *found_next_number_field{nullptr}; /* Set on open */
1492 /// Pointer to generated columns
1493 Field **vfield{nullptr};
1494 /// Pointer to fields having the default value generated
1496 /// Field used by unique constraint
1498 Field *fts_doc_id_field{nullptr}; /* Set if FTS_DOC_ID field is present */
1499
1500 /* Table's triggers, 0 if there are no of them */
1502 TABLE_LIST *pos_in_table_list{nullptr}; /* Element referring to this table */
1503 /* Position in thd->locked_table_list under LOCK TABLES */
1505 ORDER *group{nullptr};
1506 const char *alias{nullptr}; ///< alias or table name
1507 uchar *null_flags{nullptr}; ///< Pointer to the null flags of record[0]
1509 nullptr}; ///< Saved null_flags while null_row is true
1510
1511 /* containers */
1513 /*
1514 Bitmap of fields that one or more query condition refers to. Only
1515 used if optimizer_condition_fanout_filter is turned 'on'.
1516 Currently, only the WHERE clause and ON clause of inner joins is
1517 taken into account but not ON conditions of outer joins.
1518 Furthermore, HAVING conditions apply to groups and are therefore
1519 not useful as table condition filters.
1520 */
1522
1523 /**
1524 Bitmap of table fields (columns), which are explicitly set in the
1525 INSERT INTO statement. It is declared here to avoid memory allocation
1526 on MEM_ROOT).
1527
1528 @sa fields_set_during_insert.
1529 */
1531
1532 /**
1533 Set over all columns that the optimizer intends to read. This is used
1534 for two purposes: First, to tell the storage engine which ones it needs
1535 to populate. (In particular, NDB can save a lot of bandwidth here.)
1536 Second, functions that need to store and restore rows, such as hash join
1537 or filesort, need to know which ones to keep.
1538
1539 Set during resolving; every field that gets resolved, sets its own bit
1540 in the read set. In some cases, we switch the read set around during
1541 various phases; note that it is a pointer.
1542
1543 In addition, for binary logging purposes, the bitmaps are set according
1544 to the settings of @@binlog_row_image. Therefore, for logging purposes,
1545 some additional fields, to those specified by the optimizer, may be
1546 flagged in the read and write sets.
1547 @c TABLE::mark_columns_per_binlog_row_image for additional details.
1548 */
1550
1552
1553 /**
1554 A pointer to the bitmap of table fields (columns), which are explicitly set
1555 in the INSERT INTO statement.
1556
1557 fields_set_during_insert points to def_fields_set_during_insert
1558 for base (non-temporary) tables. In other cases, it is NULL.
1559 Triggers can not be defined for temporary tables, so this bitmap does not
1560 matter for temporary tables.
1561
1562 @sa def_fields_set_during_insert.
1563 */
1565
1566 /*
1567 The ID of the query that opened and is using this table. Has different
1568 meanings depending on the table type.
1569
1570 Temporary tables:
1571
1572 table->query_id is set to thd->query_id for the duration of a statement
1573 and is reset to 0 once it is closed by the same statement. A non-zero
1574 table->query_id means that a statement is using the table even if it's
1575 not the current statement (table is in use by some outer statement).
1576
1577 Non-temporary tables:
1578
1579 Under pre-locked or LOCK TABLES mode: query_id is set to thd->query_id
1580 for the duration of a statement and is reset to 0 once it is closed by
1581 the same statement. A non-zero query_id is used to control which tables
1582 in the list of pre-opened and locked tables are actually being used.
1583 */
1585
1586 /*
1587 For each key that has quick_keys.is_set(key) == true: estimate of #records
1588 and max #key parts that range access would use.
1589 */
1591
1592 /* Bitmaps of key parts that =const for the entire join. */
1594
1597
1598 /*
1599 Estimate of number of records that satisfy SARGable part of the table
1600 condition, or table->file->records if no SARGable condition could be
1601 constructed.
1602 This value is used by join optimizer as an estimate of number of records
1603 that will pass the table condition (condition that depends on fields of
1604 this table and constants)
1605 */
1607
1608 uint lock_position{0}; /* Position in MYSQL_LOCK.table */
1609 uint lock_data_start{0}; /* Start pos. in MYSQL_LOCK.locks */
1610 uint lock_count{0}; /* Number of locks */
1611 uint db_stat{0}; /* mode of file as in handler.h */
1612 int current_lock{0}; /* Type of lock on table */
1613
1614 // List of table check constraints.
1616
1617 private:
1618 /**
1619 If true, this table is inner w.r.t. some outer join operation, all columns
1620 are nullable (in the query), and null_row may be true.
1621 */
1622 bool nullable{false};
1623
1624 uint8 m_status{0}; /* What's in record[0] */
1625 public:
1626 /*
1627 If true, the current table row is considered to have all columns set to
1628 NULL, including columns declared as "not null" (see nullable).
1629 @todo make it private, currently join buffering changes it through a pointer
1630 */
1631 bool null_row{false};
1632
1633 bool copy_blobs{false}; /* copy_blobs when storing */
1634
1635 /*
1636 TODO: Each of the following flags take up 8 bits. They can just as easily
1637 be put into one single unsigned long and instead of taking up 18
1638 bytes, it would take up 4.
1639 */
1640 bool force_index{false};
1641
1642 /**
1643 Flag set when the statement contains FORCE INDEX FOR ORDER BY
1644 See TABLE_LIST::process_index_hints().
1645 */
1647
1648 /**
1649 Flag set when the statement contains FORCE INDEX FOR GROUP BY
1650 See TABLE_LIST::process_index_hints().
1651 */
1653 bool const_table{false};
1654 /// True if writes to this table should not write rows and just write keys.
1655 bool no_rows{false};
1656
1657 /**
1658 If set, the optimizer has found that row retrieval should access index
1659 tree only.
1660 */
1661 bool key_read{false};
1662 /**
1663 Certain statements which need the full row, set this to ban index-only
1664 access.
1665 */
1666 bool no_keyread{false};
1667 /**
1668 If set, indicate that the table is not replicated by the server.
1669 */
1670 bool no_replicate{false};
1671 /* To signal that the table is associated with a HANDLER statement */
1672 bool open_by_handler{false};
1673 /**
1674 To indicate that value of the auto_increment field was provided
1675 explicitly by the user or from some other source (e.g. in case of
1676 INSERT ... SELECT, ALTER TABLE or LOAD DATA) and not as default
1677 or result of conversion from NULL value.
1678
1679 @note Since auto_increment fields are always non-NULL we can't find
1680 out using methods of Field class if 0 value stored in such field
1681 was provided explicitly or is result of applying default/conversion
1682 from NULL value. In the former case no new auto_increment value
1683 needs to be generated in MODE_NO_AUTO_VALUE_ON_ZERO mode, while
1684 the latter cases require new value generation. Hence the need
1685 for this flag.
1686 @note Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode and only
1687 by handler::write_row().
1688 */
1690 bool alias_name_used{false}; /* true if table_name is alias */
1691 bool get_fields_in_item_tree{false}; /* Signal to fix_field */
1692
1693 private:
1694 /**
1695 This TABLE object is invalid and cannot be reused. TABLE object might have
1696 inconsistent info or handler might not allow some operations.
1697
1698 For example, TABLE might have inconsistent info about partitioning.
1699 We also use this flag to avoid calling handler::reset() for partitioned
1700 InnoDB tables after in-place ALTER TABLE API commit phase and to force
1701 closing table after REPAIR TABLE has failed during its prepare phase as
1702 well.
1703
1704 @note This member can be set only by thread that owns/has opened the
1705 table and while holding its THD::LOCK_thd_data lock.
1706 It can be read without locking by this owner thread, or by some other
1707 thread concurrently after acquring owner's THD::LOCK_thd_data.
1708
1709 @note The TABLE will not be reopened under LOCK TABLES in
1710 close_thread_tables().
1711 */
1712 bool m_invalid_dict{false};
1713
1714 /**
1715 This TABLE object is invalid and cannot be reused as it has outdated
1716 rec_per_key and handler stats.
1717
1718 @note This member is protected from concurrent access to it by lock of
1719 Table Cache's partition to which this TABLE object belongs,
1720 */
1721 bool m_invalid_stats{false};
1722
1723 /**
1724 For tmp tables. true <=> tmp table has been instantiated.
1725 Also indicates that table was successfully opened since
1726 we immediately delete tmp tables which we fail to open.
1727 */
1728 bool created{false};
1729
1730 public:
1731 /// For a materializable derived or SJ table: true if has been materialized
1732 bool materialized{false};
1733 struct /* field connections */
1734 {
1735 class JOIN_TAB *join_tab{nullptr};
1736 class QEP_TAB *qep_tab{nullptr};
1737 thr_lock_type lock_type{TL_UNLOCK}; /* How table is used */
1740 /*
1741 true <=> range optimizer found that there is no rows satisfying
1742 table conditions.
1743 */
1744 bool impossible_range{false};
1746
1747 /**
1748 @todo This member should not be declared in-line. That makes it
1749 impossible for any function that does memory allocation to take a const
1750 reference to a TABLE object.
1751 */
1753 /**
1754 Initialized in Item_func_group_concat::setup for appropriate
1755 temporary table if GROUP_CONCAT is used with ORDER BY | DISTINCT
1756 and BLOB field count > 0.
1757 */
1759
1760 /**
1761 Not owned by the TABLE; used only from filesort_free_buffers().
1762 See comments on SortingIterator::CleanupAfterQuery().
1763 */
1766
1767 /**
1768 The result of applying a unique opertion (by row ID) to the table, if done.
1769 In particular, this is done in some forms of index merge.
1770 */
1772 partition_info *part_info{nullptr}; /* Partition related information */
1773 /* If true, all partitions have been pruned away */
1776
1777 private:
1778 /// Cost model object for operations on this table
1780#ifndef NDEBUG
1781 /**
1782 Internal tmp table sequential number. Increased in the order of
1783 creation. Used for debugging purposes when many tmp tables are used
1784 during execution (e.g several windows with window functions)
1785 */
1787#endif
1788 public:
1789 void reset();
1790 void init(THD *thd, TABLE_LIST *tl);
1791 bool init_tmp_table(THD *thd, TABLE_SHARE *share, MEM_ROOT *m_root,
1792 CHARSET_INFO *charset, const char *alias, Field **fld,
1793 uint *blob_fld, bool is_virtual);
1794 bool fill_item_list(mem_root_deque<Item *> *item_list) const;
1795 void reset_item_list(const mem_root_deque<Item *> &item_list) const;
1796 void clear_column_bitmaps(void);
1797 void prepare_for_position(void);
1798
1801 uint key_parts = 0) const;
1803 void mark_auto_increment_column(void);
1804 void mark_columns_needed_for_update(THD *thd, bool mark_binlog_columns);
1808 void mark_generated_columns(bool is_update);
1809 void mark_gcol_in_maps(const Field *field);
1810 void mark_check_constraint_columns(bool is_update);
1811 void column_bitmaps_set(MY_BITMAP *read_set_arg, MY_BITMAP *write_set_arg);
1812 inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg,
1813 MY_BITMAP *write_set_arg) {
1814 read_set = read_set_arg;
1815 write_set = write_set_arg;
1816 }
1817 inline void use_all_columns() {
1819 }
1823 }
1824 void invalidate_dict();
1825 void invalidate_stats();
1826 /**
1827 @note Can be called by thread owning table without additional locking, and
1828 by any other thread which has acquired owner's THD::LOCK_thd_data lock.
1829 */
1830 inline bool has_invalid_dict() const {
1831 assert(assert_invalid_dict_is_locked(this));
1832 return !db_stat || m_invalid_dict;
1833 }
1834 /// @note Can be called by thread owning Table_cache::m_lock
1835 inline bool has_invalid_stats() {
1836 assert(assert_invalid_stats_is_locked(this));
1837 return m_invalid_stats;
1838 }
1839 /// @returns first non-hidden column
1841 /// @returns count of visible fields
1843 bool alloc_tmp_keys(uint new_key_count, uint new_key_part_count,
1844 bool modify_share);
1845 bool add_tmp_key(Field_map *key_parts, bool invisible, bool modify_share);
1846 void move_tmp_key(int old_idx, bool modify_share);
1847 void drop_unused_tmp_keys(bool modify_share);
1848
1849 void set_keyread(bool flag);
1850
1851 /**
1852 Check whether the given index has a virtual generated columns.
1853
1854 @param index_no the given index to check
1855
1856 @returns true if if index is defined over at least one virtual generated
1857 column
1858 */
1859 inline bool index_contains_some_virtual_gcol(uint index_no) const {
1860 assert(index_no < s->keys);
1861 return key_info[index_no].flags & HA_VIRTUAL_GEN_KEY;
1862 }
1863 void update_const_key_parts(Item *conds);
1864
1866
1867 ptrdiff_t default_values_offset() const {
1868 return (ptrdiff_t)(s->default_values - record[0]);
1869 }
1870
1871 /// @returns true if a storage engine handler object is assigned to table
1872 bool has_storage_handler() const { return file != nullptr; }
1873
1874 /// Set storage handler for temporary table
1876 // Ensure consistent call order
1877 assert((file == nullptr && file_arg != nullptr) ||
1878 (file != nullptr && file_arg == nullptr));
1879 assert(!is_created());
1880 assert(file_arg->inited == handler::NONE);
1881 file = file_arg;
1882 }
1883 /// Return true if table is instantiated, and false otherwise.
1884 bool is_created() const { return created; }
1885
1886 /**
1887 Set the table as "created", and enable flags in storage engine
1888 that could not be enabled without an instantiated table.
1889 */
1890 void set_created();
1891 /**
1892 Set the contents of table to be "deleted", ie "not created", after having
1893 deleted the contents.
1894 */
1895 void set_deleted() { created = materialized = false; }
1896 /// Set table as nullable, ie it is inner wrt some outer join
1897 void set_nullable() { nullable = true; }
1898
1899 /// Return whether table is nullable
1900 bool is_nullable() const { return nullable; }
1901
1902 /// @return true if table contains one or more generated columns
1903 bool has_gcol() const { return vfield; }
1904
1905 /**
1906 Life cycle of the row buffer is as follows:
1907 - The initial state is "not started".
1908 - When reading a row through the storage engine handler, the status is set
1909 as "has row" or "no row", depending on whether a row was found or not.
1910 The "not started" state is cleared, as well as the "null row" state,
1911 the updated state and the deleted state.
1912 - When making a row available in record[0], make sure to update row status
1913 similarly to how the storage engine handler does it.
1914 - If a NULL-extended row is needed in join execution, the "null row" state
1915 is set. Note that this can be combined with "has row" if a row was read
1916 but condition on it was evaluated to false (happens for single-row
1917 lookup), or "no row" if no more rows could be read.
1918 Note also that for the "null row" state, the NULL bits inside the
1919 row are set to one, so the row inside the row buffer is no longer usable,
1920 unless the NULL bits are saved in a separate buffer.
1921 - The "is updated" and "is deleted" states are set when row is updated or
1922 deleted, respectively.
1923 */
1924 /// Set status for row buffer as "not started"
1927 null_row = false;
1928 }
1929
1930 /// @return true if a row operation has been done
1931 bool is_started() const { return !(m_status & STATUS_NOT_STARTED); }
1932
1933 /// Set status for row buffer: contains row
1935 m_status = 0;
1936 null_row = false;
1937 }
1938
1939 /**
1940 Set status for row buffer: contains no row. This is set when
1941 - A lookup operation finds no row
1942 - A scan operation scans past the last row of the range.
1943 - An error in generating key values before calling storage engine.
1944 */
1945 void set_no_row() {
1947 null_row = false;
1948 }
1949
1950 /**
1951 Set "row found" status from handler result
1952
1953 @param status 0 if row was found, <> 0 if row was not found
1954 */
1957 null_row = false;
1958 }
1959
1960 /**
1961 Set current row as "null row", for use in null-complemented outer join.
1962 The row buffer may or may not contain a valid row.
1963 set_null_row() and reset_null_row() are used by the join executor to
1964 signal the presence or absence of a NULL-extended row for an outer joined
1965 table. Null rows may also be used to specify rows that are all NULL in
1966 grouing operations.
1967 @note this is a destructive operation since the NULL value bit vector
1968 is overwritten. Caching operations must be aware of this.
1969 */
1971 null_row = true;
1973 if (s->null_bytes > 0) memset(null_flags, 255, s->null_bytes);
1974 }
1975
1976 /// Clear "null row" status for the current row
1978 null_row = false;
1979 m_status &= ~STATUS_NULL_ROW;
1980 }
1981
1982 /// Set "updated" property for the current row
1984 assert(is_started() && has_row());
1986 }
1987
1988 /// Set "deleted" property for the current row
1990 assert(is_started() && has_row());
1992 }
1993
1994 /// @return true if there is a row in row buffer
1995 bool has_row() const { return !(m_status & STATUS_NOT_FOUND); }
1996
1997 /// @return true if current row is null-extended
1998 bool has_null_row() const { return null_row; }
1999
2000 /// @return true if current row has been updated (multi-table update)
2001 bool has_updated_row() const { return m_status & STATUS_UPDATED; }
2002
2003 /// @return true if current row has been deleted (multi-table delete)
2004 bool has_deleted_row() const { return m_status & STATUS_DELETED; }
2005
2006 /// Save the NULL flags of the current row into the designated buffer
2008 if (s->null_bytes > 0) memcpy(null_flags_saved, null_flags, s->null_bytes);
2009 }
2010
2011 /// Restore the NULL flags of the current row from the designated buffer
2013 if (s->null_bytes > 0) memcpy(null_flags, null_flags_saved, s->null_bytes);
2014 }
2015
2016 /// Empties internal temporary table (deletes rows, closes scan)
2017 bool empty_result_table();
2018
2019 /**
2020 Initialize the optimizer cost model.
2021
2022 This function should be called each time a new query is started.
2023
2024 @param cost_model_server the main cost model object for the query
2025 */
2026 void init_cost_model(const Cost_model_server *cost_model_server) {
2027 m_cost_model.init(cost_model_server, this);
2028 }
2029
2030 /**
2031 Return the cost model object for this table.
2032 */
2033 const Cost_model_table *cost_model() const { return &m_cost_model; }
2034
2035 /**
2036 Bind all the table's value generator columns in all the forms:
2037 stored/virtual GC, default expressions and checked constraints.
2038
2039 @details When a table is opened from the dictionary, the Value Generator
2040 expressions are bound during opening (see fix_value_generator_fields()).
2041 After query execution, Item::cleanup() is called on them
2042 (see cleanup_value_generator_items()). When the table is opened from the
2043 table cache, the Value Generetor(s) need to be bound again and this
2044 function does that.
2045 */
2047
2048 /**
2049 Clean any state in items associated with generated columns to be ready for
2050 the next statement.
2051 */
2053
2054#ifndef NDEBUG
2056#endif
2057 /**
2058 Update covering keys depending on max read key length.
2059
2060 Update available covering keys for the table, based on a constrained field
2061 and the identified covering prefix keys: If the matched part of field is
2062 longer than the index prefix,
2063 the prefix index cannot be used as a covering index.
2064
2065 @param[in] field Pointer to field object
2066 @param[in] key_read_length Max read key length
2067 @param[in] covering_prefix_keys Covering prefix keys
2068 */
2069 void update_covering_prefix_keys(Field *field, uint16 key_read_length,
2070 Key_map *covering_prefix_keys);
2071
2072 private:
2073 /**
2074 Bitmap that tells which columns are eligible for partial update in an
2075 update statement.
2076
2077 The bitmap is lazily allocated in the TABLE's mem_root when
2078 #mark_column_for_partial_update() is called.
2079 */
2081
2082 /**
2083 Object which contains execution time state used for partial update
2084 of JSON columns.
2085
2086 It is allocated in the execution mem_root by #setup_partial_update() if
2087 there are columns that have been marked as eligible for partial update.
2088 */
2090
2091 /**
2092 This flag decides whether or not we should log the drop temporary table
2093 command.
2094 */
2096
2097 public:
2098 /**
2099 Does this table have any columns that can be updated using partial update
2100 in the current row?
2101
2102 @return whether any columns in the current row can be updated using partial
2103 update
2104 */
2105 bool has_binary_diff_columns() const;
2106
2107 /**
2108 Get the list of binary diffs that have been collected for a given column in
2109 the current row, or `nullptr` if partial update cannot be used for that
2110 column.
2111
2112 @param field the column to get binary diffs for
2113 @return the list of binary diffs for the column, or `nullptr` if the column
2114 cannot be updated using partial update
2115 */
2116 const Binary_diff_vector *get_binary_diffs(const Field *field) const;
2117
2118 /**
2119 Mark a given column as one that can potentially be updated using
2120 partial update during execution of an update statement.
2121
2122 Whether it is actually updated using partial update, is not
2123 determined until execution time, since that depends both on the
2124 data that is in the column and the new data that is written to the
2125 column.
2126
2127 This function should be called during preparation of an update
2128 statement.
2129
2130 @param field a column which is eligible for partial update
2131 @retval false on success
2132 @retval true on out-of-memory
2133 */
2135
2136 /**
2137 Has this column been marked for partial update?
2138
2139 Note that this only tells if the column satisfies the syntactical
2140 requirements for being partially updated. Use #is_binary_diff_enabled() or
2141 #is_logical_diff_enabled() instead to see if partial update should be used
2142 on the column.
2143
2144 @param field the column to check
2145 @return whether the column has been marked for partial update
2146 */
2147 bool is_marked_for_partial_update(const Field *field) const;
2148
2149 /**
2150 Does this table have any columns that were marked with
2151 #mark_column_for_partial_update()?
2152
2153 Note that this only tells if any of the columns satisfy the syntactical
2154 requirements for being partially updated. Use
2155 #has_binary_diff_columns(), #is_binary_diff_enabled() or
2156 #is_logical_diff_enabled() instead to see if partial update should be used
2157 on a column.
2158 */
2160
2161 /**
2162 Enable partial update of JSON columns in this table. It is only
2163 enabled for the columns that have previously been marked for
2164 partial update using #mark_column_for_partial_update().
2165
2166 @param logical_diffs should logical JSON diffs be collected in addition
2167 to the physical binary diffs?
2168
2169 This function should be called once per statement execution, when
2170 the update statement is optimized.
2171
2172 @retval false on success
2173 @retval true on out-of-memory
2174 */
2175 bool setup_partial_update(bool logical_diffs);
2176
2177 /**
2178 @see setup_partial_update(bool)
2179
2180 This is a wrapper that auto-computes the value of the parameter
2181 logical_diffs.
2182
2183 @retval false on success
2184 @retval true on out-of-memory
2185 */
2186 bool setup_partial_update();
2187
2188 /**
2189 Add a binary diff for a column that is updated using partial update.
2190
2191 @param field the column that is being updated
2192 @param offset the offset of the changed portion
2193 @param length the length of the changed portion
2194
2195 @retval false on success
2196 @retval true on out-of-memory
2197 */
2198 bool add_binary_diff(const Field *field, size_t offset, size_t length);
2199
2200 /**
2201 Clear the diffs that have been collected for partial update of
2202 JSON columns, and re-enable partial update for any columns where
2203 partial update was temporarily disabled for the current row.
2204 Should be called between each row that is updated.
2205 */
2207
2208 /**
2209 Clean up state used for partial update of JSON columns.
2210
2211 This function should be called at the end of each statement
2212 execution.
2213 */
2215
2216 /**
2217 Temporarily disable collection of binary diffs for a column in the current
2218 row.
2219
2220 This function is called during execution to disable partial update of a
2221 column that was previously marked as eligible for partial update with
2222 #mark_column_for_partial_update() during preparation.
2223
2224 Partial update of this column will be re-enabled when we go to the next
2225 row.
2226
2227 @param field the column to stop collecting binary diffs for
2228 */
2230
2231 /**
2232 Temporarily disable collection of Json_diff objects describing the
2233 logical changes of a JSON column in the current row.
2234
2235 Collection of logical JSON diffs is re-enabled when we go to the next row.
2236
2237 @param field the column to stop collecting logical JSON diffs for
2238 */
2240
2241 /**
2242 Get a buffer that can be used to hold the partially updated column value
2243 while performing partial update.
2244 */
2246
2247 /**
2248 Add a logical JSON diff describing a logical change to a JSON column in
2249 partial update.
2250
2251 @param field the column that is updated
2252 @param path the JSON path that is changed
2253 @param operation the operation to perform
2254 @param new_value the new value in the path
2255
2256 @throws std::bad_alloc if memory cannot be allocated
2257 */
2259 enum_json_diff_operation operation,
2260 const Json_wrapper *new_value);
2261
2262 /**
2263 Get the list of JSON diffs that have been collected for a given column in
2264 the current row, or `nullptr` if partial update cannot be used for that
2265 column.
2266
2267 @param field the column to get JSON diffs for
2268 @return the list of JSON diffs for the column, or `nullptr` if the column
2269 cannot be updated using partial update
2270 */
2272
2273 /**
2274 Is partial update using binary diffs enabled on this JSON column?
2275
2276 @param field the column to check
2277 @return whether the column can be updated with binary diffs
2278 */
2279 bool is_binary_diff_enabled(const Field *field) const;
2280
2281 /**
2282 Is partial update using logical diffs enabled on this JSON column?
2283
2284 @param field the column to check
2285 @return whether the column can be updated with JSON diffs
2286 */
2287 bool is_logical_diff_enabled(const Field *field) const;
2288
2289 /**
2290 Virtual fields of type BLOB have a flag m_keep_old_value. This flag is set
2291 to false for all such fields in this table.
2292 */
2294
2295 /**
2296 Set the variable should_binlog_drop_if_temp_flag, so that
2297 the logging of temporary tables can be decided.
2298
2299 @param should_binlog the value to set flag should_binlog_drop_if_temp_flag
2300 */
2301 void set_binlog_drop_if_temp(bool should_binlog);
2302
2303 /**
2304 @return whether should_binlog_drop_if_temp_flag flag is
2305 set or not
2306 */
2307 bool should_binlog_drop_if_temp(void) const;
2308};
2309
2310static inline void empty_record(TABLE *table) {
2311 restore_record(table, s->default_values);
2312 if (table->s->null_bytes > 0)
2313 memset(table->null_flags, 255, table->s->null_bytes);
2314}
2315
2316#define MY_I_S_MAYBE_NULL 1
2317#define MY_I_S_UNSIGNED 2
2318
2320 /**
2321 This is used as column name.
2322 */
2323 const char *field_name;
2324 /**
2325 For string-type columns, this is the maximum number of
2326 characters. Otherwise, it is the 'display-length' for the column.
2327 For the data type MYSQL_TYPE_DATETIME this field specifies the
2328 number of digits in the fractional part of time value.
2329 */
2331 /**
2332 This denotes data type for the column. For the most part, there seems to
2333 be one entry in the enum for each SQL data type, although there seem to
2334 be a number of additional entries in the enum.
2335 */
2338 /**
2339 This is used to set column attributes. By default, columns are @c NOT
2340 @c NULL and @c SIGNED, and you can deviate from the default
2341 by setting the appropriate flags. You can use either one of the flags
2342 @c MY_I_S_MAYBE_NULL and @c MY_I_S_UNSIGNED or
2343 combine them using the bitwise or operator @c |. Both flags are
2344 defined in table.h.
2345 */
2346 uint field_flags; // Field atributes(maybe_null, signed, unsigned etc.)
2347 const char *old_name;
2348 uint open_method; // Not used
2349};
2350
2352 const char *table_name;
2354 /* Fill table with data */
2355 int (*fill_table)(THD *thd, TABLE_LIST *tables, Item *cond);
2356 /* Handle fileds for old SHOW */
2357 int (*old_format)(THD *thd, ST_SCHEMA_TABLE *schema_table);
2358 int (*process_table)(THD *thd, TABLE_LIST *tables, TABLE *table, bool res,
2361};
2362
2363/**
2364 Strategy for how to process a view or derived table (merge or materialization)
2365*/
2371
2372#define VIEW_SUID_INVOKER 0
2373#define VIEW_SUID_DEFINER 1
2374#define VIEW_SUID_DEFAULT 2
2375
2376/* view WITH CHECK OPTION parameter options */
2377#define VIEW_CHECK_NONE 0
2378#define VIEW_CHECK_LOCAL 1
2379#define VIEW_CHECK_CASCADED 2
2380
2381/* result of view WITH CHECK OPTION parameter check */
2382#define VIEW_CHECK_OK 0
2383#define VIEW_CHECK_ERROR 1
2384#define VIEW_CHECK_SKIP 2
2385
2386/** The threshold size a blob field buffer before it is freed */
2387#define MAX_TDC_BLOB_SIZE 65536
2388
2389/**
2390 Struct that describes an expression selected from a derived table or view.
2391*/
2393 /**
2394 Points to an item that represents the expression.
2395 If the item is determined to be unused, the pointer is set to NULL.
2396 */
2398 /// Name of selected expression
2399 const char *name;
2400};
2401
2402/*
2403 Column reference of a NATURAL/USING join. Since column references in
2404 joins can be both from views and stored tables, may point to either a
2405 Field (for tables), or a Field_translator (for views).
2406*/
2407
2409 public:
2410 Field_translator *view_field; /* Column reference of merge view. */
2411 Item_field *table_field; /* Column reference of table or temp view. */
2412 TABLE_LIST *table_ref; /* Original base table/view reference. */
2413 /*
2414 True if a common join column of two NATURAL/USING join operands. Notice
2415 that when we have a hierarchy of nested NATURAL/USING joins, a column can
2416 be common at some level of nesting but it may not be common at higher
2417 levels of nesting. Thus this flag may change depending on at which level
2418 we are looking at some column.
2419 */
2421
2422 public:
2424 Natural_join_column(Item_field *field_param, TABLE_LIST *tab);
2425 const char *name();
2426 Item *create_item(THD *thd);
2427 Field *field();
2428 const char *table_name();
2429 const char *db_name();
2430 GRANT_INFO *grant();
2431};
2432
2433/**
2434 This is generic enum. It may be reused in the ACL statements
2435 for clauses that can map to the values defined in this enum.
2436*/
2438 UNCHANGED, /* The clause is not specified */
2439 DEFAULT, /* Default value of clause is specified */
2440 YES, /* Value that maps to True is specified */
2441 NO /* Value that maps to False is specified */
2442};
2443
2444struct LEX_MFA {
2450 /*
2451 The following flags are indicators for the SQL syntax used while
2452 parsing CREATE/ALTER user. While other members are self-explanatory,
2453 'uses_authentication_string_clause' signifies if the password is in
2454 hash form (if the var was set to true) or not.
2455 */
2460 /* flag set during CREATE USER .. INITIAL AUTHENTICATION BY */
2462 /* flag set during ALTER USER .. ADD nth FACTOR */
2464 /* flag set during ALTER USER .. MODIFY nth FACTOR */
2466 /* flag set during ALTER USER .. DROP nth FACTOR */
2468 /*
2469 flag used during authentication and to decide if server should
2470 be in sandbox mode or not
2471 */
2473 /* flag set during ALTER USER .. nth FACTOR UNREGISTER */
2475 /* flag set during ALTER USER .. INITIATE REGISTRATION */
2477 /* flag set during ALTER USER .. FINISH REGISTRATION */
2479
2481 void reset() {
2483 auth = NULL_CSTR;
2486 nth_factor = 1;
2490 has_password_generator = false;
2491 passwordless = false;
2492 add_factor = false;
2493 drop_factor = false;
2494 modify_factor = false;
2495 requires_registration = false;
2496 unregister = false;
2497 init_registration = false;
2498 finish_registration = false;
2499 }
2500 void copy(LEX_MFA *m, MEM_ROOT *alloc);
2501};
2502
2503/*
2504 This structure holds the specifications relating to
2505 ALTER user ... PASSWORD EXPIRE ...
2506*/
2524 /* Holds the specification of 'PASSWORD REQUIRE CURRENT' clause. */
2526 void cleanup() {
2532 account_locked = false;
2544 }
2545};
2546
2547/*
2548 This structure holds the specifications related to
2549 mysql user and the associated auth details.
2550*/
2551struct LEX_USER {
2559 /* restrict MFA methods to atmost 3 authentication plugins */
2563
2564 void init() {
2565 user = NULL_CSTR;
2566 host = NULL_CSTR;
2568 uses_replace_clause = false;
2570 discard_old_password = false;
2587 mfa_list.clear();
2588 with_initial_auth = false;
2589 }
2590
2592
2593 bool add_mfa_identifications(LEX_MFA *factor2, LEX_MFA *factor3 = nullptr);
2594
2595 /*
2596 Allocates the memory in the THD mem pool and initialize the members of
2597 this struct. It is preferable to use this method to create a LEX_USER
2598 rather allocating the memory in the THD and initializing the members
2599 explicitly.
2600 */
2601 static LEX_USER *alloc(THD *thd);
2602 static LEX_USER *alloc(THD *thd, LEX_STRING *user, LEX_STRING *host);
2603 /*
2604 Initialize the members of this struct. It is preferable to use this method
2605 to initialize a LEX_USER rather initializing the members explicitly.
2606 */
2607 static LEX_USER *init(LEX_USER *to_init, THD *thd, LEX_STRING *user,
2608 LEX_STRING *host);
2609};
2610
2611/**
2612 Derive type of metadata lock to be requested for table used by a DML
2613 statement from the type of THR_LOCK lock requested for this table.
2614*/
2615
2616inline enum enum_mdl_type mdl_type_for_dml(enum thr_lock_type lock_type) {
2617 return lock_type >= TL_WRITE_ALLOW_WRITE
2621}
2622
2623/**
2624 Type of table which can be open for an element of table list.
2625*/
2626
2632
2633/**
2634 This structure is used to keep info about possible key for the result table
2635 of a derived table/view.
2636 The 'referenced_by' is the table map of tables to which this possible
2637 key corresponds.
2638 The 'used_field' is a map of fields of which this key consists of.
2639 See also the comment for the TABLE_LIST::update_derived_keys function.
2640*/
2641
2643 public:
2647};
2648
2649class Table_function;
2650/*
2651 Table reference in the FROM clause.
2652
2653 These table references can be of several types that correspond to
2654 different SQL elements. Below we list all types of TABLE_LISTs with
2655 the necessary conditions to determine when a TABLE_LIST instance
2656 belongs to a certain type.
2657
2658 1) table (TABLE_LIST::view == NULL)
2659 - base table
2660 (TABLE_LIST::derived == NULL)
2661 - subquery - TABLE_LIST::table is a temp table
2662 (TABLE_LIST::derived != NULL)
2663 - information schema table
2664 (TABLE_LIST::schema_table != NULL)
2665 NOTICE: for schema tables TABLE_LIST::field_translation may be != NULL
2666 2) view (TABLE_LIST::view != NULL)
2667 - merge (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_MERGE)
2668 also (TABLE_LIST::field_translation != NULL)
2669 - temptable(TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_TEMPTABLE)
2670 also (TABLE_LIST::field_translation == NULL)
2671 3) nested table reference (TABLE_LIST::nested_join != NULL)
2672 - table sequence - e.g. (t1, t2, t3)
2673 TODO: how to distinguish from a JOIN?
2674 - general JOIN
2675 TODO: how to distinguish from a table sequence?
2676 - NATURAL JOIN
2677 (TABLE_LIST::natural_join != NULL)
2678 - JOIN ... USING
2679 (TABLE_LIST::join_using_fields != NULL)
2680 - semi-join
2681 ;
2682*/
2683
2685 TABLE_LIST() = default;
2686
2687 /**
2688 Only to be used by legacy code that temporarily needs a TABLE_LIST, more
2689 specifically: Query_result_create::binlog_show_create_table().
2690 */
2691 explicit TABLE_LIST(TABLE *table_arg) : table(table_arg) {}
2692
2693 /// Constructor that can be used when the strings are null terminated.
2694 TABLE_LIST(const char *db_name, const char *table_name,
2695 enum thr_lock_type lock_type)
2696 : TABLE_LIST(db_name, strlen(db_name), table_name, strlen(table_name),
2697 table_name, lock_type) {}
2698
2699 /**
2700 Creates a TABLE_LIST object with pre-allocated strings for database, table
2701 and alias.
2702 */
2703 TABLE_LIST(TABLE *table_arg, const char *db_name_arg, size_t db_length_arg,
2704 const char *table_name_arg, size_t table_name_length_arg,
2705 const char *alias_arg, enum thr_lock_type lock_type_arg)
2706 : db(db_name_arg),
2707 table_name(table_name_arg),
2708 alias(alias_arg),
2709 m_map(1),
2710 table(table_arg),
2711 m_lock_descriptor{lock_type_arg},
2712 db_length(db_length_arg),
2713 table_name_length(table_name_length_arg) {
2716 }
2717
2718 /// Constructor that can be used when the strings are null terminated.
2719 TABLE_LIST(const char *db_name, const char *table_name, const char *alias,
2720 enum thr_lock_type lock_type)
2721 : TABLE_LIST(db_name, strlen(db_name), table_name, strlen(table_name),
2722 alias, lock_type) {}
2723
2724 /**
2725 This constructor can be used when a TABLE_LIST is needed for an existing
2726 temporary table. These typically have very long table names, since it is
2727 a fully qualified path. For this reason, the table is set to the alias.
2728 The database name is left blank. The lock descriptor is set to TL_READ.
2729 */
2730 TABLE_LIST(TABLE *table_arg, const char *alias_arg)
2731 : db(""),
2732 table_name(alias_arg),
2733 alias(alias_arg),
2734 m_map(1),
2735 table(table_arg),
2737 db_length(0),
2738 table_name_length(strlen(alias_arg)) {
2741 }
2742
2743 /**
2744 Sets an explicit enum_mdl_type value, without initializing
2745 m_lock_descriptor.
2746 */
2747 TABLE_LIST(TABLE *table_arg, const char *alias_arg, enum_mdl_type mdl_type)
2748 : db(table_arg->s->db.str),
2749 table_name(table_arg->s->table_name.str),
2750 alias(alias_arg),
2751 m_map(1),
2752 table(table_arg),
2753 db_length(table_arg->s->db.length),
2754 table_name_length(table_arg->s->table_name.length) {
2757 }
2758
2759 TABLE_LIST(const char *db_name, const char *table_name_arg,
2760 enum thr_lock_type lock_type_arg,
2761 enum enum_mdl_type mdl_request_type)
2762 : db(db_name),
2763 table_name(table_name_arg),
2764 alias(table_name_arg),
2765 m_map(1),
2766 m_lock_descriptor{lock_type_arg},
2767 db_length(strlen(db_name)),
2768 table_name_length(strlen(table_name_arg)) {
2771 mdl_request.set_type(mdl_request_type);
2772 }
2773
2774 TABLE_LIST(const char *db_name, size_t db_length_arg,
2775 const char *table_name_arg, size_t table_name_length_arg,
2776 enum thr_lock_type lock_type_arg,
2777 enum enum_mdl_type mdl_request_type)
2778 : db(db_name),
2779 table_name(table_name_arg),
2780 alias(table_name_arg),
2781 m_map(1),
2782 m_lock_descriptor{lock_type_arg},
2783 db_length(db_length_arg),
2784 table_name_length(table_name_length_arg) {
2787 mdl_request.set_type(mdl_request_type);
2788 }
2789
2790 TABLE_LIST(const char *db_name, size_t db_length_arg,
2791 const char *table_name_arg, size_t table_name_length_arg,
2792 enum thr_lock_type lock_type_arg)
2793 : db(db_name),
2794 table_name(table_name_arg),
2795 alias(table_name_arg),
2796 m_map(1),
2797 m_lock_descriptor{lock_type_arg},
2798 db_length(db_length_arg),
2799 table_name_length(table_name_length_arg) {}
2800
2801 /**
2802 Sets an explicit enum_mdl_type value, without initializing
2803 m_lock_descriptor.
2804 */
2805 TABLE_LIST(const char *db_name, size_t db_length_arg,
2806 const char *table_name_arg, size_t table_name_length_arg,
2807 const char *alias_arg, enum enum_mdl_type mdl_request_type)
2808 : db(db_name),
2809 table_name(table_name_arg),
2810 alias(alias_arg),
2811 m_map(1),
2812 db_length(db_length_arg),
2813 table_name_length(table_name_length_arg) {
2816 mdl_request.set_type(mdl_request_type);
2817 }
2818
2819 TABLE_LIST(const char *db_name, size_t db_length_arg,
2820 const char *table_name_arg, size_t table_name_length_arg,
2821 const char *alias_arg, enum thr_lock_type lock_type_arg,
2822 enum enum_mdl_type mdl_request_type)
2823 : db(db_name),
2824 table_name(table_name_arg),
2825 alias(alias_arg),
2826 m_map(1),
2827 m_lock_descriptor{lock_type_arg},
2828 db_length(db_length_arg),
2829 table_name_length(table_name_length_arg) {
2832 mdl_request.set_type(mdl_request_type);
2833 }
2834
2835 TABLE_LIST(const char *db_name_arg, size_t db_length_arg,
2836 const char *table_name_arg, size_t table_name_length_arg,
2837 const char *alias_arg, enum thr_lock_type lock_type_arg)
2838 : db(db_name_arg),
2839 table_name(table_name_arg),
2840 alias(alias_arg),
2841 m_map(1),
2842 m_lock_descriptor{lock_type_arg},
2843 db_length(db_length_arg),
2844 table_name_length(table_name_length_arg) {
2847 }
2848
2849 /// Create a TABLE_LIST object representing a nested join
2850 static TABLE_LIST *new_nested_join(MEM_ROOT *allocator, const char *alias,
2852 mem_root_deque<TABLE_LIST *> *belongs_to,
2853 Query_block *select);
2855 Item *join_cond() const { return m_join_cond; }
2856 void set_join_cond(Item *val) {
2857 // If optimization has started, it's too late to change m_join_cond.
2858 assert(m_join_cond_optim == nullptr || m_join_cond_optim == (Item *)1);
2859 m_join_cond = val;
2860 }
2863 /*
2864 Either we are setting to "empty", or there must pre-exist a
2865 permanent condition.
2866 */
2867 assert(cond == nullptr || cond == (Item *)1 || m_join_cond != nullptr);
2868 m_join_cond_optim = cond;
2869 }
2871
2872 /// @returns true if semi-join nest
2873 bool is_sj_nest() const { return m_is_sj_or_aj_nest && !m_join_cond; }
2874 /// @returns true if anti-join nest
2875 bool is_aj_nest() const { return m_is_sj_or_aj_nest && m_join_cond; }
2876 /// @returns true if anti/semi-join nest
2877 bool is_sj_or_aj_nest() const { return m_is_sj_or_aj_nest; }
2878 /// Makes the next a semi/antijoin nest
2880 assert(!m_is_sj_or_aj_nest);
2881 m_is_sj_or_aj_nest = true;
2882 }
2883
2884 /// Merge tables from a query block into a nested join structure
2886
2887 /// Reset table
2888 void reset();
2889
2890 /// Evaluate the check option of a view
2891 int view_check_option(THD *thd) const;
2892
2893 /// Cleanup field translations for a view
2894 void cleanup_items();
2895
2896 /// Produce a textual identification of this object
2897 void print(const THD *thd, String *str, enum_query_type query_type) const;
2898
2899 /// Check which single table inside a view that matches a table map
2900 bool check_single_table(TABLE_LIST **table_ref, table_map map);
2901
2902 /// Allocate a buffer for inserted column values
2904
2906 /**
2907 Retrieve the last (right-most) leaf in a nested join tree with
2908 respect to name resolution.
2909
2910
2911 Given that 'this' is a nested table reference, recursively walk
2912 down the right-most children of 'this' until we reach a leaf
2913 table reference with respect to name resolution.
2914
2915 The right-most child of a nested table reference is the first
2916 element in the list of children because the children are inserted
2917 in reverse order.
2918
2919 @return
2920 - If 'this' is a nested table reference - the right-most child
2921 of the tree rooted in 'this',
2922 - else - 'this'
2923 */
2925 bool is_leaf_for_name_resolution() const;
2926
2927 /// Return the outermost view this table belongs to, or itself
2928 inline const TABLE_LIST *top_table() const {
2929 return belong_to_view ? belong_to_view : this;
2930 }
2931
2933 return const_cast<TABLE_LIST *>(
2934 const_cast<const TABLE_LIST *>(this)->top_table());
2935 }
2936
2937 /// Prepare check option for a view
2938 bool prepare_check_option(THD *thd, bool is_cascaded = false);
2939
2940 /// Merge WHERE condition of view or derived table into outer query
2941 bool merge_where(THD *thd);
2942
2943 /// Prepare replace filter for a view (used for REPLACE command)
2944 bool prepare_replace_filter(THD *thd);
2945
2946 /// Return true if this represents a named view
2947 bool is_view() const { return view != nullptr; }
2948
2949 /// Return true if this represents a derived table (an unnamed view)
2950 bool is_derived() const { return derived != nullptr && view == nullptr; }
2951
2952 /// Return true if this represents a named view or a derived table
2953 bool is_view_or_derived() const { return derived != nullptr; }
2954
2955 /// Return true if this represents a table function
2956 bool is_table_function() const { return table_function != nullptr; }
2957 /**
2958 @returns true if this is a recursive reference inside the definition of a
2959 recursive CTE.
2960 @note that it starts its existence as a dummy derived table, until the
2961 end of resolution when it's not a derived table anymore, just a reference
2962 to the materialized temporary table. Whereas a non-recursive
2963 reference to the recursive CTE is a derived table.
2964 */
2966
2967 /// @returns true if this is a base table (permanent or temporary)
2968 bool is_base_table() const {
2969 return !(is_view_or_derived() || is_table_function() ||
2971 }
2972 /**
2973 @see is_recursive_reference().
2974 @returns true if error
2975 */
2977
2978 /**
2979 @returns true for a table that represents an optimizer internal table,
2980 is a derived table, a recursive reference, a table function.
2981 Internal tables are only visible inside a query expression, and is hence
2982 not visible in any schema, or need any kind of privilege checking.
2983 */
2984 bool is_internal() const {
2986 }
2987
2988 /**
2989 @returns true for a table that is a placeholder, ie a derived table,
2990 a view, a recursive reference, a table function or a schema table.
2991 A table is also considered to be a placeholder if it does not have a
2992 TABLE object for some other reason.
2993 */
2994 bool is_placeholder() const {
2996 is_table_function() || schema_table || table == nullptr;
2997 }
2998
2999 /// Return true if view or derived table and can be merged
3000 bool is_mergeable() const;
3001
3002 /**
3003 Checks if this is a table that contains zero rows or one row, and that can
3004 be materialized during optimization.
3005
3006 @returns true if materializable table contains one or zero rows, and
3007 materialization during optimization is permitted
3008
3009 Returning true, if the hypergraph optimizer is not active, implies that the
3010 table is materialized during optimization, so it need not be optimized
3011 during execution. The hypergraph optimizer does not care about const tables,
3012 so such tables are not executed during optimization time when it is active.
3013 */
3014 bool materializable_is_const() const;
3015
3016 /// Return true if this is a derived table or view that is merged
3018
3019 /// Set table to be merged
3020 void set_merged() {
3023 }
3024
3025 /// Return true if this is a materializable derived table/view
3028 }
3029
3030 /// Set table to be materialized
3032 // @todo We should do this only once, but currently we cannot:
3033 // assert(effective_algorithm == VIEW_ALGORITHM_UNDEFINED);
3036 }
3037
3038 /// Return true if table is updatable
3039 bool is_updatable() const { return m_updatable; }
3040
3041 /// Set table as updatable. (per default, a table is non-updatable)
3042 void set_updatable() { m_updatable = true; }
3043
3044 /// Return true if table is insertable-into
3045 bool is_insertable() const { return m_insertable; }
3046
3047 /// Set table as insertable-into. (per default, a table is not insertable)
3048 void set_insertable() { m_insertable = true; }
3049
3050 /// Return true if table is being updated
3051 bool is_updated() const { return m_updated; }
3052
3053 /// Set table and all referencing views as being updated
3055 for (TABLE_LIST *tr = this; tr != nullptr; tr = tr->referencing_view)
3056 tr->m_updated = true;
3057 }
3058
3059 /// Return true if table is being inserted into
3060 bool is_inserted() const { return m_inserted; }
3061
3062 /// Set table and all referencing views as being inserted into
3064 for (TABLE_LIST *tr = this; tr != nullptr; tr = tr->referencing_view)
3065 tr->m_inserted = true;
3066 }
3067
3068 /// Return true if table is being deleted from
3069 bool is_deleted() const { return m_deleted; }
3070
3071 /// Set table and all referencing views as being deleted from
3073 for (TABLE_LIST *tr = this; tr != nullptr; tr = tr->referencing_view)
3074 tr->m_deleted = true;
3075 }
3076
3077 /// Set table as full-text search (default is not fulltext searched)
3079
3080 /// Returns true if a MATCH function references this table.
3082
3083 /**
3084 Set table as readonly, ie it is neither updatable, insertable nor
3085 deletable during this statement.
3086 */
3088 m_updatable = false;
3089 m_insertable = false;
3090 }
3091
3092 /**
3093 Return true if this is a view or derived table that is defined over
3094 more than one base table, and false otherwise.
3095 */
3096 bool is_multiple_tables() const {
3097 if (is_view_or_derived()) {
3098 assert(is_merged()); // Cannot be a materialized view
3099 return leaf_tables_count() > 1;
3100 } else {
3101 assert(nested_join == nullptr); // Must be a base table
3102 return false;
3103 }
3104 }
3105
3106 /// Return no. of base tables a merged view or derived table is defined over.
3107 uint leaf_tables_count() const;
3108
3109 /// Return first leaf table of a base table or a view/derived table
3111 TABLE_LIST *tr = this;
3112 while (tr->merge_underlying_list) tr = tr->merge_underlying_list;
3113 return tr;
3114 }
3115
3116 /// Return any leaf table that is not an inner table of an outer join
3117 /// @todo WL#6570 with prepare-once, replace with first_leaf_table()
3118 /// when WL#6059 is merged in (it really converts RIGHT JOIN to
3119 /// LEFT JOIN so the first leaf is part of a LEFT JOIN,
3120 /// guaranteed).
3122 TABLE_LIST *tr = this;
3123 while (tr->merge_underlying_list) {
3124 tr = tr->merge_underlying_list;
3125 /*
3126 "while" is used, however, an "if" might be sufficient since there is
3127 no more than one inner table in a join nest (with outer_join true).
3128 */
3129 while (tr->outer_join) tr = tr->next_local;
3130 }
3131 return tr;
3132 }
3133 /**
3134 Set the LEX object of a view (will also define this as a view).
3135 @note: The value 1 is used to indicate a view but without a valid
3136 query object. Use only if the LEX object is not going to
3137 be used in later processing.
3138 */
3139 void set_view_query(LEX *lex) { view = lex; }
3140
3141 /// Return the valid LEX object for a view.
3142 LEX *view_query() const {
3143 assert(view != nullptr && view != (LEX *)1);
3144 return view;
3145 }
3146
3147 /**
3148 Set the query expression of a derived table or view.
3149 (Will also define this as a derived table, unless it is a named view.)
3150 */
3152 derived = query_expr;
3153 }
3154
3155 /// Return the query expression of a derived table or view.
3157 assert(derived);
3158 return derived;
3159 }
3160
3161 /// Resolve a derived table or view reference
3162 bool resolve_derived(THD *thd, bool apply_semijoin);
3163
3164 /// Optimize the query expression representing a derived table/view
3165 bool optimize_derived(THD *thd);
3166
3167 /// Create result table for a materialized derived table/view
3168 bool create_materialized_table(THD *thd);
3169
3170 /// Materialize derived table
3171 bool materialize_derived(THD *thd);
3172
3173 /// Check if we can push outer where condition to this derived table
3175
3176 /// Return the number of hidden fields added for the temporary table
3177 /// created for this derived table.
3179
3180 /// Clean up the query expression for a materialized derived table
3181 void cleanup_derived(THD *thd);
3182
3183 /// Prepare security context for a view
3184 bool prepare_security(THD *thd);
3185
3188
3189 /**
3190 Compiles the tagged hints list and fills up TABLE::keys_in_use_for_query,
3191 TABLE::keys_in_use_for_group_by, TABLE::keys_in_use_for_order_by,
3192 TABLE::force_index and TABLE::covering_keys.
3193 */
3194 bool process_index_hints(const THD *thd, TABLE *table);
3195
3196 /**
3197 Compare the version of metadata from the previous execution
3198 (if any) with values obtained from the current table
3199 definition cache element.
3200
3201 @sa check_and_update_table_version()
3202 */
3204 return (m_table_ref_type == s->get_table_ref_type() &&
3206 }
3207
3208 /**
3209 Record the value of metadata version of the corresponding
3210 table definition cache element in this parse tree node.
3211
3212 @sa check_and_update_table_version()
3213 */
3216 }
3217
3218 void set_table_ref_id(enum_table_ref_type table_ref_type_arg,
3219 ulonglong table_ref_version_arg) {
3220 m_table_ref_type = table_ref_type_arg;
3221 m_table_ref_version = table_ref_version_arg;
3222 }
3223
3224 /**
3225 If a derived table, returns query block id of first underlying query block.
3226 Zero if not derived.
3227 */
3228 uint query_block_id() const;
3229
3230 /**
3231 This is for showing in EXPLAIN.
3232 If a derived table, returns query block id of first underlying query block
3233 of first materialized TABLE_LIST instance. Zero if not derived.
3234 */
3236
3237 /**
3238 @brief Returns the name of the database that the referenced table belongs
3239 to.
3240 */
3241 const char *get_db_name() const { return db; }
3242
3243 /**
3244 @brief Returns the name of the table that this TABLE_LIST represents.
3245
3246 @details The unqualified table name or view name for a table or view,
3247 respectively.
3248 */
3249 const char *get_table_name() const { return table_name; }
3251 bool update_derived_keys(THD *, Field *, Item **, uint, bool *);
3252 bool generate_keys();
3253
3254 /// Setup a derived table to use materialization
3257
3258 /// Setup a table function to use materialization
3259 bool setup_table_function(THD *thd);
3260
3261 bool create_field_translation(THD *thd);
3262
3263 /**
3264 @brief Returns the outer join nest that this TABLE_LIST belongs to, if any.
3265
3266 @details There are two kinds of join nests, outer-join nests and semi-join
3267 nests. This function returns non-NULL in the following cases:
3268 @li 1. If this table/nest is embedded in a nest and this nest IS NOT a
3269 semi-join nest. (In other words, it is an outer-join nest.)
3270 @li 2. If this table/nest is embedded in a nest and this nest IS a
3271 semi-join nest, but this semi-join nest is embedded in another
3272 nest. (This other nest will be an outer-join nest, since all inner
3273 joined nested semi-join nests have been merged in
3274 @c simplify_joins() ).
3275 Note: This function assumes that @c simplify_joins() has been performed.
3276 Before that, join nests will be present for all types of join.
3277
3278 @return outer join nest, or NULL if none.
3279 */
3280
3282 if (!embedding) return nullptr;
3283 if (embedding->is_sj_nest()) return embedding->embedding;
3284 return embedding;
3285 }
3286 /**
3287 Return true if this table is an inner table of some outer join.
3288
3289 Examine all the embedding join nests of the table.
3290 @note This function works also before redundant join nests have been
3291 eliminated.
3292
3293 @return true if table is an inner table of some outer join, false otherwise.
3294 */
3295
3297 if (outer_join) return true;
3298 for (TABLE_LIST *emb = embedding; emb; emb = emb->embedding) {
3299 if (emb->outer_join) return true;
3300 }
3301 return false;
3302 }
3303
3304 /**
3305 Return the base table entry of an updatable table.
3306 In DELETE and UPDATE, a view used as a target table must be mergeable,
3307 updatable and defined over a single table.
3308 */
3310 const TABLE_LIST *tbl = this;
3311 assert(tbl->is_updatable() && !tbl->is_multiple_tables());
3312 while (tbl->is_view_or_derived()) {
3313 tbl = tbl->merge_underlying_list;
3314 assert(tbl->is_updatable() && !tbl->is_multiple_tables());
3315 }
3316 return tbl;
3317 }
3318
3320 return const_cast<TABLE_LIST *>(
3321 static_cast<const TABLE_LIST *>(this)->updatable_base_table());
3322 }
3323
3324 /**
3325 Mark that there is a NATURAL JOIN or JOIN ... USING between two tables.
3326
3327 This function marks that table b should be joined with a either via
3328 a NATURAL JOIN or via JOIN ... USING. Both join types are special
3329 cases of each other, so we treat them together. The function
3330 setup_conds() creates a list of equal condition between all fields
3331 of the same name for NATURAL JOIN or the fields in
3332 TABLE_LIST::join_using_fields for JOIN ... USING.
3333 The list of equality conditions is stored
3334 either in b->join_cond(), or in JOIN::conds, depending on whether there
3335 was an outer join.
3336
3337 EXAMPLE
3338 @verbatim
3339 SELECT * FROM t1 NATURAL LEFT JOIN t2
3340 <=>
3341 SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
3342
3343 SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
3344 <=>
3345 SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)
3346
3347 SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
3348 <=>
3349 SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
3350 @endverbatim
3351
3352 @param b Right join argument.
3353 */
3355
3356 /**
3357 Set granted privileges for a table.
3358
3359 Can be used when generating temporary tables that are also used in
3360 resolver process, such as when generating a UNION table
3361
3362 @param privilege Privileges granted for this table.
3363 */
3364 void set_privileges(ulong privilege) { grant.privilege |= privilege; }
3365
3366 bool save_properties();
3367 void restore_properties();
3368
3369 /*
3370 List of tables local to a subquery or the top-level SELECT (used by
3371 SQL_I_List). Considers views as leaves (unlike 'next_leaf' below).
3372 Created at parse time in Query_block::add_table_to_list() ->
3373 table_list.link_in_list().
3374 */
3376 /* link in a global list of all queries tables */
3377 TABLE_LIST *next_global{nullptr}, **prev_global{nullptr};
3378 const char *db{nullptr}, *table_name{nullptr}, *alias{nullptr};
3379 /*
3380 Target tablespace name: When creating or altering tables, this
3381 member points to the tablespace_name in the HA_CREATE_INFO struct.
3382 */
3384 char *option{nullptr}; /* Used by cache index */
3385
3386 /** Table level optimizer hints for this table. */
3388 /* Hints for query block of this table. */
3390
3391 void set_lock(const Lock_descriptor &descriptor) {
3392 m_lock_descriptor = descriptor;
3393 }
3394
3396
3398
3399 private:
3400 /**
3401 The members below must be kept aligned so that (1 << m_tableno) == m_map.
3402 A table that takes part in a join operation must be assigned a unique
3403 table number.
3404 */
3405 uint m_tableno{0}; ///< Table number within query block
3406 table_map m_map{0}; ///< Table map, derived from m_tableno
3407 /**
3408 If this table or join nest is the Y in "X [LEFT] JOIN Y ON C", this
3409 member points to C. May also be generated from JOIN ... USING clause.
3410 It may be modified only by permanent transformations (permanent = done
3411 once for all executions of a prepared statement).
3412 */
3415
3416 public:
3417 /*
3418 (Valid only for semi-join nests) Bitmap of tables that are within the
3419 semi-join (this is different from bitmap of all nest's children because
3420 tables that were pulled out of the semi-join nest remain listed as
3421 nest's children).
3422 */
3424
3425 /*
3426 During parsing - left operand of NATURAL/USING join where 'this' is
3427 the right operand. After parsing (this->natural_join == this) iff
3428 'this' represents a NATURAL or USING join operation. Thus after
3429 parsing 'this' is a NATURAL/USING join iff (natural_join != NULL).
3430 */
3432 /*
3433 True if 'this' represents a nested join that is a NATURAL JOIN.
3434 For one of the operands of 'this', the member 'natural_join' points
3435 to the other operand of 'this'.
3436 */
3437 bool is_natural_join{false};
3438 /* Field names in a USING clause for JOIN ... USING. */
3440 /*
3441 Explicitly store the result columns of either a NATURAL/USING join or
3442 an operand of such a join.
3443 */
3445 /* true if join_columns contains all columns of this table reference. */
3447
3448 /*
3449 List of nodes in a nested join tree, that should be considered as
3450 leaves with respect to name resolution. The leaves are: views,
3451 top-most nodes representing NATURAL/USING joins, subqueries, and
3452 base tables. All of these TABLE_LIST instances contain a
3453 materialized list of columns. The list is local to a subquery.
3454 */
3456 /* Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */
3458 TABLE *table{nullptr}; /* opened table */
3459 Table_id table_id{}; /* table id (from binlog) for opened table */
3460 /*
3461 Query_result for derived table to pass it from table creation to table
3462 filling procedure
3463 */
3465 /*
3466 Reference from aux_tables to local list entry of main select of
3467 multi-delete statement:
3468 delete t1 from t2,t1 where t1.a<'B' and t2.b=t1.b;
3469 here it will be reference of first occurrence of t1 to second (as you
3470 can see this lists can't be merged)
3471 */
3473
3474 /*
3475 Holds the function used as the table function
3476 */
3478
3479 /**
3480 If we've previously made an access path for “derived”, it is cached here.
3481 This is useful if we need to plan the query block twice (the hypergraph
3482 optimizer can do so, with and without in2exists predicates), both saving
3483 work and avoiding issues when we try to throw away the old items_to_copy
3484 for a new (identical) one.
3485 */
3487
3488 private:
3489 /**
3490 This field is set to non-null for derived tables and views. It points
3491 to the Query_expression representing the derived table/view.
3492 E.g. for a query
3493 @verbatim SELECT * FROM (SELECT a FROM t1) b @endverbatim
3494 */
3495 Query_expression *derived{nullptr}; /* Query_expression of derived table */
3496
3497 /// If non-NULL, the CTE which this table is derived from.
3499 /**
3500 If the user has specified column names with the syntaxes "table name
3501 parenthesis column names":
3502 WITH qn(column names) AS (select...)
3503 or
3504 FROM (select...) dt(column names)
3505 or
3506 CREATE VIEW v(column_names) AS ...
3507 then this points to the list of column names. NULL otherwise.
3508 */
3510
3511 public:
3512 ST_SCHEMA_TABLE *schema_table{nullptr}; /* Information_schema table */
3514 /*
3515 True when the view field translation table is used to convert
3516 schema table fields for backwards compatibility with SHOW command.
3517 */
3520 /* link to query_block where this table was used */
3522
3523 private:
3524 LEX *view{nullptr}; /* link on VIEW lex for merging */
3525
3526 public:
3527 /// Array of selected expressions from a derived table or view.
3529
3530 /// pointer to element after last one in translation table above
3532 /*
3533 List (based on next_local) of underlying tables of this view. I.e. it
3534 does not include the tables of subqueries used in the view. Is set only
3535 for merged views.
3536 */
3538 /*
3539 - 0 for base tables
3540 - in case of the view it is the list of all (not only underlying
3541 tables but also used in subquery ones) tables of the view.
3542 */
3544 /* most upper view this table belongs to */
3546 /*
3547 The view directly referencing this table
3548 (non-zero only for merged underlying tables of a view).
3549 */
3551 /* Ptr to parent MERGE table list item. See top comment in ha_myisammrg.cc */
3553 /*
3554 Security context (non-zero only for tables which belong
3555 to view with SQL SECURITY DEFINER)
3556 */
3558 /*
3559 This view security context (non-zero only for views with
3560 SQL SECURITY DEFINER)
3561 */
3563 /*
3564 List of all base tables local to a subquery including all view
3565 tables. Unlike 'next_local', this in this list views are *not*
3566 leaves. Created in setup_tables() -> make_leaf_tables().
3567 */
3569 Item *derived_where_cond{nullptr}; ///< WHERE condition from derived table
3570 Item *check_option{nullptr}; ///< WITH CHECK OPTION condition
3571 Item *replace_filter{nullptr}; ///< Filter for REPLACE command
3572 LEX_STRING select_stmt{nullptr, 0}; ///< text of (CREATE/SELECT) statement
3573 LEX_STRING source{nullptr, 0}; ///< source of CREATE VIEW
3574 LEX_STRING timestamp{nullptr, 0}; ///< GMT time stamp of last operation
3575 LEX_USER definer; ///< definer of view
3576 /**
3577 @note: This field is currently not reliable when read from dictionary:
3578 If an underlying view is changed, updatable_view is not changed,
3579 due to lack of dependency checking in dictionary implementation.
3580 Prefer to use is_updatable() during preparation and optimization.
3581 */
3582 ulonglong updatable_view{0}; ///< VIEW can be updated
3583 /**
3584 @brief The declared algorithm, if this is a view.
3585 @details One of
3586 - VIEW_ALGORITHM_UNDEFINED
3587 - VIEW_ALGORITHM_TEMPTABLE
3588 - VIEW_ALGORITHM_MERGE
3589 @todo Replace with an enum
3590 */
3592 ulonglong view_suid{0}; ///< view is suid (true by default)
3593 ulonglong with_check{0}; ///< WITH CHECK OPTION
3594
3595 private:
3596 /// The view algorithm that is actually used, if this is a view.
3599
3600 public:
3602
3603 public:
3604 /// True if right argument of LEFT JOIN; false in other cases (i.e. if left
3605 /// argument of LEFT JOIN, if argument of INNER JOIN; RIGHT JOINs are
3606 /// converted to LEFT JOIN during contextualization).
3607 bool outer_join{false};
3608 /// True if was originally the left argument of a RIGHT JOIN, before we
3609 /// made it the right argument of a LEFT JOIN.
3611 uint shared{0}; /* Used in multi-upd */
3612 size_t db_length{0};
3614
3615 private:
3616 /// True if VIEW/TABLE is updatable, based on analysis of query (SQL rules).
3617 bool m_updatable{false};
3618 /// True if VIEW/TABLE is insertable, based on analysis of query (SQL rules).
3619 bool m_insertable{false};
3620 /// True if table is target of UPDATE statement, or updated in IODKU stmt.
3621 bool m_updated{false};
3622 /// True if table is target of INSERT statement.
3623 bool m_inserted{false};
3624 /// True if table is target of DELETE statement, or deleted in REPLACE stmt.
3625 bool m_deleted{false};
3626 bool m_fulltext_searched{false}; ///< True if fulltext searched
3627 public:
3628 bool straight{false}; /* optimize with prev table */
3629 /**
3630 True for tables and views being changed in a data change statement.
3631 Also true for tables subject to a SELECT ... FOR UPDATE.
3632 Also used by replication to filter out statements that can be ignored,
3633 especially important for multi-table UPDATE and DELETE.
3634 */
3635 bool updating{false};
3636 /// preload only non-leaf nodes (IS THIS USED???)
3637 bool ignore_leaves{false};
3638 /**
3639 The set of tables in the query block that this table depends on.
3640 Can be set due to outer join, join order hints or NOT EXISTS relationship.
3641 */
3643 /// The outer tables that an outer join's join condition depends on
3645 /**
3646 Is non-NULL if this table reference is a nested join, ie it represents
3647 the inner tables of an outer join, the tables contained in the
3648 parentheses of an inner join (eliminated during resolving), the tables
3649 referenced in a derived table or view, in a semi-join nest, the tables
3650 from the subquery.
3651 */
3653 /// The nested join containing this table reference.
3655 /// The join list immediately containing this table reference
3657 /// stop PS caching
3658 bool cacheable_table{false};
3659 /**
3660 Specifies which kind of table should be open for this element
3661 of table list.
3662 */
3664 /* true if this merged view contain auto_increment field */
3666 /// true <=> VIEW CHECK OPTION condition is processed (also for prep. stmts)
3668 /// true <=> Filter condition is processed
3670
3672 char timestamp_buffer[20]{0}; /* buffer for timestamp (19+1) */
3673 /*
3674 This TABLE_LIST object is just placeholder for prelocking, it will be
3675 used for implicit LOCK TABLES only and won't be used in real statement.
3676 */
3678 /**
3679 Indicates that if TABLE_LIST object corresponds to the table/view
3680 which requires special handling.
3681 */
3682 enum {
3683 /* Normal open. */
3685 /* Associate a table share only if the the table exists. */
3687 /*
3688 Associate a table share only if the the table exists.
3689 Also upgrade metadata lock to exclusive if table doesn't exist.
3690 */
3692 /* Don't associate a table share. */
3693 OPEN_STUB
3694 } open_strategy{OPEN_NORMAL};
3696 /** true if an alias for this table was specified in the SQL. */
3697 bool is_alias{false};
3698 /** true if the table is referred to in the statement using a fully
3699 qualified name (@<db_name@>.@<table_name@>).
3700 */
3701 bool is_fqtn{false};
3702 /**
3703 If true, this table is a derived (materialized) table which was created
3704 from a scalar subquery, cf.
3705 Query_block::transform_scalar_subqueries_to_join_with_derived
3706 */
3708
3709 /* View creation context. */
3710
3712
3713 /*
3714 Attributes to save/load view creation context in/from frm-file.
3715
3716 They are required only to be able to use existing parser to load
3717 view-definition file. As soon as the parser parsed the file, view
3718 creation context is initialized and the attributes become redundant.
3719
3720 These attributes MUST NOT be used for any purposes but the parsing.
3721 */
3722
3725
3726 /*
3727 View definition (SELECT-statement) in the UTF-form.
3728 */
3729
3731
3732 // True, If this is a system view
3733 bool is_system_view{false};
3734
3735 /*
3736 Set to 'true' if this is a DD table being opened in the context of a
3737 dictionary operation. Note that when 'false', this may still be a DD
3738 table when opened in a non-DD context, e.g. as part of an I_S view
3739 query.
3740 */
3741 bool is_dd_ctx_table{false};
3742
3743 /* End of view definition context. */
3744
3745 /* List of possible keys. Valid only for materialized derived tables/views. */
3747
3748 /**
3749 Indicates what triggers we need to pre-load for this TABLE_LIST
3750 when opening an associated TABLE. This is filled after
3751 the parsed tree is created.
3752 */
3759
3761
3762 /// if true, EXPLAIN can't explain view due to insufficient rights.
3763 bool view_no_explain{false};
3764
3765 /* List to carry partition names from PARTITION (...) clause in statement */
3767
3768 /// Set table number
3770 assert(tableno < MAX_TABLES);
3772 m_map = (table_map)1 << tableno;
3773 }
3774 /// Return table number
3775 uint tableno() const { return m_tableno; }
3776
3777 /// Return table map derived from table number
3778 table_map map() const {
3779 assert(((table_map)1 << m_tableno) == m_map);
3780 return m_map;
3781 }
3782
3783 /// If non-NULL, the CTE which this table is derived from.
3786 /// @see m_derived_column_names
3789 }
3792 }
3793
3794 private:
3795 /*
3796 A group of members set and used only during JOIN::optimize().
3797 */
3798 /**
3799 Optimized copy of m_join_cond (valid for one single
3800 execution). Initialized by Query_block::get_optimizable_conditions().
3801 */
3803
3804 public:
3805 COND_EQUAL *cond_equal{nullptr}; ///< Used with outer join
3806 /// true <=> this table is a const one and was optimized away.
3807
3808 bool optimized_away{false};
3809 /**
3810 true <=> all possible keys for a derived table were collected and
3811 could be re-used while statement re-execution.
3812 */
3813
3815
3816 private:
3817 /// If a recursive reference inside the definition of a CTE.
3819 // End of group for optimization
3820
3821 /** See comments for set_metadata_id() */
3823 /** See comments for TABLE_SHARE::get_table_ref_version() */
3825
3826 /*
3827 All members whose names are suffixed with "_saved" are duplicated in
3828 class TABLE but actually belong in this class. They are saved from class
3829 TABLE when preparing a statement and restored when executing the statement.
3830 They are not required for a regular (non-prepared) statement.
3831 */
3837 bool nullable_saved{false};
3846};
3847
3848/*
3849 Iterator over the fields of a generic table reference.
3850*/
3851
3853 public:
3854 virtual ~Field_iterator() = default;
3855 virtual void set(TABLE_LIST *) = 0;
3856 virtual void next() = 0;
3857 virtual bool end_of_fields() = 0; /* Return 1 at end of list */
3858 virtual const char *name() = 0;
3859 virtual Item *create_item(THD *) = 0;
3860 virtual Field *field() = 0;
3861};
3862
3863/*
3864 Iterator over the fields of a base table, view with temporary
3865 table, or subquery.
3866*/
3867
3870
3871 public:
3873 void set(TABLE_LIST *table) override { ptr = table->table->field; }
3874 void set_table(TABLE *table) { ptr = table->field; }
3875 void next() override { ptr++; }
3876 bool end_of_fields() override { return *ptr == nullptr; }
3877 const char *name() override;
3878 Item *create_item(THD *thd) override;
3879 Field *field() override { return *ptr; }
3880};
3881
3882/**
3883 Iterator over the fields of a merged derived table or view.
3884*/
3885
3889
3890 public:
3892 void set(TABLE_LIST *table) override;
3893 void next() override { ptr++; }
3894 bool end_of_fields() override { return ptr == array_end; }
3895 const char *name() override;
3896 Item *create_item(THD *thd) override;
3897 Item **item_ptr() { return &ptr->item; }
3898 Field *field() override { return nullptr; }
3899 inline Item *item() { return ptr->item; }
3901};
3902
3903/*
3904 Field_iterator interface to the list of materialized fields of a
3905 NATURAL/USING join.
3906*/
3907
3911
3912 public:
3914 ~Field_iterator_natural_join() override = default;
3915 void set(TABLE_LIST *table) override;
3916 void next() override;
3917 bool end_of_fields() override { return !cur_column_ref; }
3918 const char *name() override { return cur_column_ref->name(); }
3919 Item *create_item(THD *thd) override {
3920 return cur_column_ref->create_item(thd);
3921 }
3922 Field *field() override { return cur_column_ref->field(); }
3924};
3925
3926/**
3927 Generic iterator over the fields of an arbitrary table reference.
3928
3929 This class unifies the various ways of iterating over the columns
3930 of a table reference depending on the type of SQL entity it
3931 represents. If such an entity represents a nested table reference,
3932 this iterator encapsulates the iteration over the columns of the
3933 members of the table reference.
3934
3935 The implementation assumes that all underlying NATURAL/USING table
3936 references already contain their result columns and are linked into
3937 the list TABLE_LIST::next_name_resolution_table.
3938*/
3939
3946 void set_field_iterator();
3947
3948 public:
3950 void set(TABLE_LIST *table) override;
3951 void next() override;
3952 bool end_of_fields() override {
3953 return (table_ref == last_leaf && field_it->end_of_fields());
3954 }
3955 const char *name() override { return field_it->name(); }
3956 const char *get_table_name();
3957 const char *get_db_name();
3958 GRANT_INFO *grant();
3959 Item *create_item(THD *thd) override { return field_it->create_item(thd); }
3960 Field *field() override { return field_it->field(); }
3962 TABLE_LIST *parent_table_ref);
3964};
3965
3968 char *db, *table;
3970};
3971
3973 MY_BITMAP *bitmap) {
3974 my_bitmap_map *old = bitmap->bitmap;
3975 bitmap->bitmap = table->s->all_set.bitmap; // does not repoint last_word_ptr
3976 return old;
3977}
3978
3979static inline void tmp_restore_column_map(MY_BITMAP *bitmap,
3980 my_bitmap_map *old) {
3981 bitmap->bitmap = old;
3982}
3983
3984/* The following is only needed for debugging */
3985
3987 [[maybe_unused]],
3988 MY_BITMAP *bitmap
3989 [[maybe_unused]]) {
3990#ifndef NDEBUG
3991 return tmp_use_all_columns(table, bitmap);
3992#else
3993 return nullptr;
3994#endif
3995}
3996
3997static inline void dbug_tmp_restore_column_map(MY_BITMAP *bitmap
3998 [[maybe_unused]],
3999 my_bitmap_map *old
4000 [[maybe_unused]]) {
4001#ifndef NDEBUG
4002 tmp_restore_column_map(bitmap, old);
4003#endif
4004}
4005
4006/*
4007 Variant of the above : handle both read and write sets.
4008 Provide for the possiblity of the read set being the same as the write set
4009*/
4010static inline void dbug_tmp_use_all_columns(
4011 TABLE *table [[maybe_unused]], my_bitmap_map **save [[maybe_unused]],
4012 MY_BITMAP *read_set [[maybe_unused]],
4013 MY_BITMAP *write_set [[maybe_unused]]) {
4014#ifndef NDEBUG
4015 save[0] = read_set->bitmap;
4016 save[1] = write_set->bitmap;
4017 (void)tmp_use_all_columns(table, read_set);
4018 (void)tmp_use_all_columns(table, write_set);
4019#endif
4020}
4021
4023 MY_BITMAP *read_set [[maybe_unused]], MY_BITMAP *write_set [[maybe_unused]],
4024 my_bitmap_map **old [[maybe_unused]]) {
4025#ifndef NDEBUG
4026 tmp_restore_column_map(read_set, old[0]);
4027 tmp_restore_column_map(write_set, old[1]);
4028#endif
4029}
4030
4031void init_mdl_requests(TABLE_LIST *table_list);
4032
4033/**
4034 Unpacks the definition of a value generator in all its forms: generated
4035 column, default expression or checked constraint.
4036 The function parses the text defintion of this expression, resolves its
4037 items and runs validation and calculates the base_columns_map which is used
4038 for tracking the columns the expression depends on.
4039
4040 @param[in] thd Thread handler
4041 @param[in] table Table having the value generator to be unpacked
4042 @param[in,out] val_generator Contains the expression in string format, and,
4043 if successful will be replaced by the parser
4044 with a new one having the unpacked expression.
4045 @param[in] source Source of value generator(a generated column,
4046 a regular column with generated default value or
4047 a check constraint).
4048 @param[in] source_name Name of the source (generated column, a regular
4049 column with generated default value or a check
4050 constraint).
4051 @param[in] field The column the value generator depends on. Can
4052 be null for checked constraints which do not
4053 depend on a single column.
4054 @param[in] is_create_table Indicates that table is opened as part
4055 of CREATE or ALTER and does not yet exist in SE
4056 @param[out] error_reported updated flag for the caller that no other error
4057 messages are to be generated.
4058
4059 @retval true Failure.
4060 @retval false Success.
4061*/
4062
4063bool unpack_value_generator(THD *thd, TABLE *table,
4064 Value_generator **val_generator,
4066 const char *source_name, Field *field,
4067 bool is_create_table, bool *error_reported);
4068
4069/**
4070 Unpack the partition expression. Parse the partition expression
4071 to produce an Item.
4072
4073 @param[in] thd Thread handler
4074 @param[in] outparam Table object
4075 @param[in] share TABLE_SHARE object
4076 @param[in] engine_type Engine type of the partitions.
4077 @param[in] is_create_table Indicates that table is opened as part of
4078 CREATE or ALTER and does not yet exist in SE
4079
4080 @retval true Failure.
4081 @retval false Success.
4082*/
4083
4084bool unpack_partition_info(THD *thd, TABLE *outparam, TABLE_SHARE *share,
4085 handlerton *engine_type, bool is_create_table);
4086
4087int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias,
4088 uint db_stat, uint prgflag, uint ha_open_flags,
4089 TABLE *outparam, bool is_create_table,
4090 const dd::Table *table_def_param);
4091TABLE_SHARE *alloc_table_share(const char *db, const char *table_name,
4092 const char *key, size_t key_length,
4093 bool open_secondary);
4094void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
4095 size_t key_length, const char *table_name,
4096 const char *path, MEM_ROOT *mem_root);
4097void free_table_share(TABLE_SHARE *share);
4099Ident_name_check check_db_name(const char *name, size_t length);
4101 bool preserve_lettercase);
4102bool check_column_name(const char *name);
4103Ident_name_check check_table_name(const char *name, size_t length);
4104int rename_file_ext(const char *from, const char *to, const char *ext);
4105char *get_field(MEM_ROOT *mem, Field *field);
4106bool get_field(MEM_ROOT *mem, Field *field, class String *res);
4107
4108int closefrm(TABLE *table, bool free_share);
4109void free_blobs(TABLE *table);
4110void free_blob_buffers_and_reset(TABLE *table, uint32 size);
4111int set_zone(int nr, int min_zone, int max_zone);
4112void append_unescaped(String *res, const char *pos, size_t length);
4113char *fn_rext(char *name);
4115 const LEX_CSTRING &name);
4116
4117/* performance schema */
4119
4122
4123/* information schema */
4125
4126/* mysql schema name and DD ID */
4128static const uint MYSQL_SCHEMA_DD_ID = 1;
4129
4130/* mysql tablespace name and DD ID */
4133
4134/* replication's tables */
4138
4139inline bool is_infoschema_db(const char *name, size_t len) {
4140 return (
4143}
4144
4145inline bool is_infoschema_db(const char *name) {
4147}
4148
4149inline bool is_perfschema_db(const char *name, size_t len) {
4150 return (PERFORMANCE_SCHEMA_DB_NAME.length == len &&
4152 name));
4153}
4154
4155inline bool is_perfschema_db(const char *name) {
4157 name);
4158}
4159
4160/**
4161 Check if the table belongs to the P_S, excluding setup and threads tables.
4162
4163 @note Performance Schema tables must be accessible independently of the
4164 LOCK TABLE mode. This function is needed to handle the special case
4165 of P_S tables being used under LOCK TABLE mode.
4166*/
4167inline bool belongs_to_p_s(TABLE_LIST *tl) {
4168 return (!strcmp("performance_schema", tl->db) &&
4169 strcmp(tl->table_name, "threads") &&
4170 strstr(tl->table_name, "setup_") == nullptr);
4171}
4172
4173/**
4174 return true if the table was created explicitly.
4175*/
4176inline bool is_user_table(TABLE *table) {
4177 const char *name = table->s->table_name.str;
4179}
4180
4181bool is_simple_order(ORDER *order);
4182
4183uint add_pk_parts_to_sk(KEY *sk, uint sk_n, KEY *pk, uint pk_n,
4184 TABLE_SHARE *share, handler *handler_file,
4185 uint *usable_parts, bool use_extended_sk);
4186void setup_key_part_field(TABLE_SHARE *share, handler *handler_file,
4187 uint primary_key_n, KEY *keyinfo, uint key_n,
4188 uint key_part_n, uint *usable_parts,
4189 bool part_of_key_not_extended);
4190
4191const uchar *get_field_name(const uchar *arg, size_t *length);
4192
4193void repoint_field_to_record(TABLE *table, uchar *old_rec, uchar *new_rec);
4194bool update_generated_write_fields(const MY_BITMAP *bitmap, TABLE *table);
4196 uint active_index = MAX_KEY);
4197
4198/**
4199 Check if a TABLE_LIST instance represents a pre-opened temporary table.
4200*/
4201
4202inline bool is_temporary_table(const TABLE_LIST *tl) {
4203 if (tl->is_view() || tl->schema_table) return false;
4204
4205 if (!tl->table) return false;
4206
4207 /*
4208 NOTE: 'table->s' might be NULL for specially constructed TABLE
4209 instances. See SHOW TRIGGERS for example.
4210 */
4211
4212 if (!tl->table->s) return false;
4213
4214 return tl->table->s->tmp_table != NO_TMP_TABLE;
4215}
4216
4217/**
4218 After parsing, a Common Table Expression is accessed through a
4219 TABLE_LIST. This class contains all information about the CTE which the
4220 TABLE_LIST needs.
4221
4222 @note that before and during parsing, the CTE is described by a
4223 PT_common_table_expr.
4224*/
4226 public:
4229 TABLE *clone_tmp_table(THD *thd, TABLE_LIST *tl);
4231 /// Remove one table reference.
4232 void remove_table(TABLE_LIST *tr);
4233 /// Empties the materialized CTE and informs all of its clones.
4234 bool clear_all_references();
4235 /**
4236 All references to this CTE in the statement, except those inside the
4237 query expression defining this CTE.
4238 In other words, all non-recursive references.
4239 */
4241 /// True if it's a recursive CTE
4243 /**
4244 List of all TABLE_LISTSs reading/writing to the tmp table created to
4245 materialize this CTE. Due to shared materialization, only the first one
4246 has a TABLE generated by create_tmp_table(); other ones have a TABLE
4247 generated by open_table_from_share().
4248 */
4250 /// Name of the WITH block. Used only for EXPLAIN FORMAT=tree.
4252};
4253
4254/**
4255 This iterates on those references to a derived table / view / CTE which are
4256 materialized. If a recursive CTE, this includes recursive references.
4257 Upon construction it is passed a non-recursive materialized reference
4258 to the derived table (TABLE_LIST*).
4259 For a CTE it may return more than one reference; for a derived table or a
4260 view, there is only one (as references to a same view are treated as
4261 independent objects).
4262 References are returned as TABLE*.
4263*/
4265 TABLE_LIST *const start; ///< The reference provided in construction.
4266 size_t ref_idx{0}; ///< Current index in cte->tmp_tables
4267 bool m_is_first{true}; ///< True when at first reference in list
4268 public:
4269 explicit Derived_refs_iterator(TABLE_LIST *start_arg) : start(start_arg) {}
4272 m_is_first = ref_idx == 0;
4273 // Derived tables and views have a single reference.
4274 if (cte == nullptr) {
4275 return ref_idx++ == 0 ? start->table : nullptr;
4276 }
4277 /*
4278 CTEs may have multiple references. Return the next one, but notice that
4279 some references may have been deleted.
4280 */
4281 while (ref_idx < cte->tmp_tables.size()) {
4282 TABLE *table = cte->tmp_tables[ref_idx++]->table;
4283 if (table != nullptr) return table;
4284 }
4285 return nullptr;
4286 }
4287 void rewind() {
4288 ref_idx = 0;
4289 m_is_first = true;
4290 }
4291 /// @returns true if the last get_next() returned the first element.
4292 bool is_first() const {
4293 // Call after get_next() has been called:
4294 assert(ref_idx > 0);
4295 return m_is_first;
4296 }
4297};
4298
4299/**
4300 RAII class to reset TABLE::autoinc_field_has_explicit_non_null_value after
4301 processing individual row in INSERT or LOAD DATA statements.
4302*/
4304 public:
4306 : m_table(table) {}
4309 }
4310
4311 private:
4313};
4314
4315// Whether we can ask the storage engine for the row ID of the last row read.
4316//
4317// Some operations needs a row ID to operate correctly (i.e. weedout). Normally,
4318// the row ID is provided by the storage engine by calling handler::position().
4319// But there are cases when position() should not be called:
4320//
4321// 1. If we have a const table (rows are fetched during optimization), we
4322// should not call position().
4323// 2. If we have a NULL-complemented row, calling position() would give a
4324// random row ID back, as there has not been any row read.
4325//
4326// Operations that needs the row ID must also check the value of
4327// QEP_TAB::rowid_status to see whether they actually need a row ID.
4328// See QEP_TAB::rowid_status for more details.
4329inline bool can_call_position(const TABLE *table) {
4330 return !table->const_table && !(table->is_nullable() && table->null_row);
4331}
4332
4333//////////////////////////////////////////////////////////////////////////
4334
4335/*
4336 NOTE:
4337 These structures are added to read .frm file in upgrade scenario.
4338
4339 They should not be used any where else in the code.
4340 They will be removed in future release.
4341 Any new code should not be added in this section.
4342*/
4343
4344/**
4345 These members were removed from TABLE_SHARE as they are not used in
4346 in the code. open_binary_frm() uses these members while reading
4347 .frm files.
4348*/
4350 public:
4353 null_field_first(false),
4354 stored_fields(0),
4356 frm_version(0),
4357 fieldnames() {}
4358
4361 uint stored_fields; /* Number of stored fields
4362 (i.e. without generated-only ones) */
4363
4364 enum utype {
4377 EMPTY_VAL, // EMPTY_VAL rather than EMPTY since EMPTY can conflict with
4378 // system headers.
4390 GENERATED_FIELD = 128
4392
4393 /**
4394 For shares representing views File_parser object with view
4395 definition read from .FRM file.
4396 */
4399 TYPELIB fieldnames; /* Pointer to fieldnames */
4400};
4401
4402/**
4403 Create TABLE_SHARE from .frm file.
4404
4405 FRM_context object is used to store the value removed from
4406 TABLE_SHARE. These values are used only for .frm file parsing.
4407
4408 @param[in] thd Thread handle.
4409 @param[in] path Path of the frm file.
4410 @param[out] share TABLE_SHARE to be populated.
4411 @param[out] frm_context FRM_context object.
4412 @param[in] db Database name.
4413 @param[in] table Table name.
4414 @param[in] is_fix_view_cols_and_deps Fix view column data, table
4415 and routine dependency.
4416
4417 @retval TABLE_SHARE ON SUCCESS
4418 @retval NULL ON FAILURE
4419*/
4420bool create_table_share_for_upgrade(THD *thd, const char *path,
4421 TABLE_SHARE *share,
4422 FRM_context *frm_context, const char *db,
4423 const char *table,
4424 bool is_fix_view_cols_and_deps);
4425//////////////////////////////////////////////////////////////////////////
4426
4427/**
4428 Create a copy of the key_info from TABLE_SHARE object to TABLE object.
4429
4430 Wherever prefix key is present, allocate a new Field object, having its
4431 field_length set to the prefix key length, and point the table's matching
4432 key_part->field to this new Field object.
4433
4434 This ensures that unpack_partition_info() reads the correct prefix length of
4435 partitioned fields
4436
4437 @param table Table for which key_info is to be allocated
4438 @param root MEM_ROOT in which to allocate key_info
4439
4440 @retval false Success
4441 @retval true Failed to allocate memory for table.key_info in root
4442*/
4443
4445
4446#endif /* TABLE_INCLUDED */
int64 query_id_t
Definition: binlog.h:70
Per internal schema ACL access rules.
Definition: auth_common.h:137
Per internal table ACL access rules.
Definition: auth_common.h:102
RAII class to reset TABLE::autoinc_field_has_explicit_non_null_value after processing individual row ...
Definition: table.h:4303
Autoinc_field_has_explicit_non_null_value_reset_guard(TABLE *table)
Definition: table.h:4305
~Autoinc_field_has_explicit_non_null_value_reset_guard()
Definition: table.h:4307
Class that represents a single change to a column value in partial update of a JSON column.
Definition: table.h:1311
const char * old_data(const Field *field) const
Get a pointer to the start of the old data to be replaced.
Definition: table.cc:7639
size_t length() const
Definition: table.h:1332
size_t m_length
The size of the portion that is to be replaced.
Definition: table.h:1316
const char * new_data(const Field *field) const
Get a pointer to the start of the replacement data.
Definition: table.cc:7630
Binary_diff(size_t offset, size_t length)
Create a new Binary_diff object.
Definition: table.h:1325
size_t m_offset
The offset of the start of the change.
Definition: table.h:1313
size_t offset() const
Definition: table.h:1329
Definition: sql_bitmap.h:137
Class is used as a BLOB field value storage for intermediate GROUP_CONCAT results.
Definition: table.h:1271
bool truncated_value
Sign that some values were cut during saving into the storage.
Definition: table.h:1278
Blob_mem_storage()
Definition: table.cc:4021
void reset()
Definition: table.h:1284
void set_truncated_value(bool is_truncated_value)
Definition: table.h:1301
MEM_ROOT storage
Definition: table.h:1273
~Blob_mem_storage()
Definition: table.cc:4025
bool is_truncated_value() const
Definition: table.h:1304
char * store(const char *from, size_t length)
Fuction creates duplicate of 'from' string in 'storage' MEM_ROOT.
Definition: table.h:1298
Definition: item_cmpfunc.h:2633
After parsing, a Common Table Expression is accessed through a TABLE_LIST.
Definition: table.h:4225
void remove_table(TABLE_LIST *tr)
Remove one table reference.
Definition: sql_derived.cc:242
Common_table_expr(MEM_ROOT *mem_root)
Definition: table.h:4227
LEX_STRING name
Name of the WITH block. Used only for EXPLAIN FORMAT=tree.
Definition: table.h:4251
TABLE * clone_tmp_table(THD *thd, TABLE_LIST *tl)
Produces, from the first tmp TABLE object, a clone TABLE object for TABLE_LIST 'tl',...
Definition: sql_derived.cc:169
bool clear_all_references()
Empties the materialized CTE and informs all of its clones.
Definition: sql_union.cc:1112
Mem_root_array< TABLE_LIST * > tmp_tables
List of all TABLE_LISTSs reading/writing to the tmp table created to materialize this CTE.
Definition: table.h:4249
bool recursive
True if it's a recursive CTE.
Definition: table.h:4242
Mem_root_array< TABLE_LIST * > references
All references to this CTE in the statement, except those inside the query expression defining this C...
Definition: table.h:4240
bool substitute_recursive_reference(THD *thd, Query_block *sl)
Replaces the recursive reference in query block 'sl' with a clone of the first tmp table.
Definition: sql_derived.cc:229
API for getting cost estimates for server operations that are not directly related to a table object.
Definition: opt_costmodel.h:51
API for getting cost estimates for operations on table data.
Definition: opt_costmodel.h:239
void init(const Cost_model_server *cost_model_server, const TABLE *table)
Initializes the cost model object.
Definition: opt_costmodel.cc:60
Default_object_creation_ctx – default implementation of Object_creation_ctx.
Definition: table.h:218
const CHARSET_INFO * get_client_cs()
Definition: table.h:220
void change_env(THD *thd) const override
Definition: table.cc:211
void delete_backup_ctx() override
Definition: table.cc:209
Default_object_creation_ctx(THD *thd)
Definition: table.cc:196
const CHARSET_INFO * get_connection_cl()
Definition: table.h:222
Object_creation_ctx * create_backup_ctx(THD *thd) const override
Definition: table.cc:204
const CHARSET_INFO * m_connection_cl
connection_cl stores the value of collation_connection session variable.
Definition: table.h:256
const CHARSET_INFO * m_client_cs
client_cs stores the value of character_set_client session variable.
Definition: table.h:246
This structure is used to keep info about possible key for the result table of a derived table/view.
Definition: table.h:2642
table_map referenced_by
Definition: table.h:2644
Field_map used_fields
Definition: table.h:2645
uint key_part_count
Definition: table.h:2646
This iterates on those references to a derived table / view / CTE which are materialized.
Definition: table.h:4264
bool is_first() const
Definition: table.h:4292
TABLE * get_next()
Definition: table.h:4270
Derived_refs_iterator(TABLE_LIST *start_arg)
Definition: table.h:4269
TABLE_LIST *const start
The reference provided in construction.
Definition: table.h:4265
bool m_is_first
True when at first reference in list.
Definition: table.h:4267
size_t ref_idx
Current index in cte->tmp_tables.
Definition: table.h:4266
void rewind()
Definition: table.h:4287
These members were removed from TABLE_SHARE as they are not used in in the code.
Definition: table.h:4349
utype
Definition: table.h:4364
@ CASEUP
Definition: table.h:4369
@ NO
Definition: table.h:4374
@ NONE
Definition: table.h:4365
@ REL
Definition: table.h:4375
@ NEXT_NUMBER
Definition: table.h:4381
@ DATE
Definition: table.h:4366
@ PNR
Definition: table.h:4370
@ BIT_FIELD
Definition: table.h:4383
@ TIMESTAMP_OLD_FIELD
Definition: table.h:4384
@ GENERATED_FIELD
Definition: table.h:4390
@ INTERVAL_FIELD
Definition: table.h:4382
@ TIMESTAMP_UN_FIELD
Definition: table.h:4388
@ NOEMPTY
Definition: table.h:4368
@ CHECK
Definition: table.h:4376
@ YES
Definition: table.h:4373
@ TIMESTAMP_DNUN_FIELD
Definition: table.h:4389
@ BLOB_FIELD
Definition: table.h:4386
@ UNKNOWN_FIELD
Definition: table.h:4379
@ CASEDN
Definition: table.h:4380
@ TIMESTAMP_DN_FIELD
Definition: table.h:4387
@ PGNR
Definition: table.h:4372
@ EMPTY_VAL
Definition: table.h:4377
@ CAPITALIZE
Definition: table.h:4385
@ SHIELD
Definition: table.h:4367
@ BGNR
Definition: table.h:4371
bool null_field_first
Definition: table.h:4360
uchar frm_version
Definition: table.h:4398
handlerton * default_part_db_type
Definition: table.h:4359
TYPELIB fieldnames
Definition: table.h:4399
const File_parser * view_def
For shares representing views File_parser object with view definition read from .FRM file.
Definition: table.h:4397
uint stored_fields
Definition: table.h:4361
FRM_context()
Definition: table.h:4351
Definition: table.h:3908
~Field_iterator_natural_join() override=default
void set(TABLE_LIST *table) override
Definition: table.cc:5108
Natural_join_column * column_ref()
Definition: table.h:3923
void next() override
Definition: table.cc:5114
Natural_join_column * cur_column_ref
Definition: table.h:3910
Field_iterator_natural_join()
Definition: table.h:3913
const char * name() override
Definition: table.h:3918
List_iterator_fast< Natural_join_column > column_ref_it
Definition: table.h:3909
bool end_of_fields() override
Definition: table.h:3917
Item * create_item(THD *thd) override
Definition: table.h:3919
Field * field() override
Definition: table.h:3922
Generic iterator over the fields of an arbitrary table reference.
Definition: table.h:3940
Natural_join_column * get_or_create_column_ref(THD *thd, TABLE_LIST *parent_table_ref)
Create new or return existing column reference to a column of a natural/using join.
Definition: table.cc:5255
Field_iterator * field_it
Definition: table.h:3945
Field_iterator_view view_field_it
Definition: table.h:3943
const char * get_table_name()
Definition: table.cc:5187
Field * field() override
Definition: table.h:3960
const char * get_db_name()
Definition: table.cc:5194
Field_iterator_table_ref()
Definition: table.h:3949
TABLE_LIST * first_leaf
Definition: table.h:3941
GRANT_INFO * grant()
Definition: table.cc:5214
void next() override
Definition: table.cc:5173
void set(TABLE_LIST *table) override
Definition: table.cc:5164
Field_iterator_table table_field_it
Definition: table.h:3942
const char * name() override
Definition: table.h:3955
TABLE_LIST * last_leaf
Definition: table.h:3941
Natural_join_column * get_natural_column_ref()
Return an existing reference to a column of a natural/using join.
Definition: table.cc:5335
void set_field_iterator()
Definition: table.cc:5121
TABLE_LIST * table_ref
Definition: table.h:3941
Item * create_item(THD *thd) override
Definition: table.h:3959
bool end_of_fields() override
Definition: table.h:3952
Field_iterator_natural_join natural_join_it
Definition: table.h:3944
Definition: table.h:3868
const char * name() override
Definition: table.cc:5031
Field ** ptr
Definition: table.h:3869
void set(TABLE_LIST *table) override
Definition: table.h:3873
Item * create_item(THD *thd) override
Definition: table.cc:5033
void set_table(TABLE *table)
Definition: table.h:3874
void next() override
Definition: table.h:3875
Field_iterator_table()
Definition: table.h:3872
bool end_of_fields() override
Definition: table.h:3876