MySQL 8.0.32
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;
66class Field_longlong;
67
68namespace histograms {
69class Histogram;
70}
71
74class COND_EQUAL;
75class Field_json;
76/* Structs that defines the TABLE */
77class File_parser;
78class Value_generator;
79class GRANT_TABLE;
80class Handler_share;
81class Index_hint;
82class Item;
83class Item_field;
86class Json_wrapper;
87class Opt_hints_qb;
88class Opt_hints_table;
90class Query_block;
93class SortingIterator;
94class String;
95class THD;
97class Table_ref;
100class handler;
101class partition_info;
102enum enum_stats_auto_recalc : int;
103enum Value_generator_source : short;
104enum row_type : int;
105struct AccessPath;
106struct HA_CREATE_INFO;
107struct LEX;
108struct NESTED_JOIN;
110struct TABLE;
111struct TABLE_SHARE;
112struct handlerton;
114using plan_idx = int;
115
116namespace dd {
117class Table;
118class View;
119
120enum class enum_table_type;
121} // namespace dd
123
127
131
133
135
136enum class enum_json_diff_operation;
137
139
141
143
144#define store_record(A, B) \
145 memcpy((A)->B, (A)->record[0], (size_t)(A)->s->reclength)
146#define restore_record(A, B) \
147 memcpy((A)->record[0], (A)->B, (size_t)(A)->s->reclength)
148#define cmp_record(A, B) \
149 memcmp((A)->record[0], (A)->B, (size_t)(A)->s->reclength)
150
151#define tmp_file_prefix "#sql" /**< Prefix for tmp tables */
152#define tmp_file_prefix_length 4
153#define TMP_TABLE_KEY_EXTRA 8
154#define PLACEHOLDER_TABLE_ROW_ESTIMATE 2
155
156/**
157 Enumerate possible types of a table from re-execution
158 standpoint.
159 Table_ref class has a member of this type.
160 At prepared statement prepare, this member is assigned a value
161 as of the current state of the database. Before (re-)execution
162 of a prepared statement, we check that the value recorded at
163 prepare matches the type of the object we obtained from the
164 table definition cache.
165
166 @sa check_and_update_table_version()
167 @sa Execute_observer
168 @sa Prepared_statement::reprepare()
169*/
170
172 /** Initial value set by the parser */
179
180/**
181 Enumerate possible status of a identifier name while determining
182 its validity
183*/
185
186/*************************************************************************/
187
188/**
189 Object_creation_ctx -- interface for creation context of database objects
190 (views, stored routines, events, triggers). Creation context -- is a set
191 of attributes, that should be fixed at the creation time and then be used
192 each time the object is parsed or executed.
193*/
194
196 public:
198
199 void restore_env(THD *thd, Object_creation_ctx *backup_ctx);
200
201 protected:
203 virtual Object_creation_ctx *create_backup_ctx(THD *thd) const = 0;
204 virtual void delete_backup_ctx() = 0;
205
206 virtual void change_env(THD *thd) const = 0;
207
208 public:
209 virtual ~Object_creation_ctx() = default;
210};
211
212/*************************************************************************/
213
214/**
215 Default_object_creation_ctx -- default implementation of
216 Object_creation_ctx.
217*/
218
220 public:
222
224
225 protected:
227
229 const CHARSET_INFO *connection_cl);
230
231 protected:
232 Object_creation_ctx *create_backup_ctx(THD *thd) const override;
233 void delete_backup_ctx() override;
234
235 void change_env(THD *thd) const override;
236
237 protected:
238 /**
239 client_cs stores the value of character_set_client session variable.
240 The only character set attribute is used.
241
242 Client character set is included into query context, because we save
243 query in the original character set, which is client character set. So,
244 in order to parse the query properly we have to switch client character
245 set on parsing.
246 */
248
249 /**
250 connection_cl stores the value of collation_connection session
251 variable. Both character set and collation attributes are used.
252
253 Connection collation is included into query context, because it defines
254 the character set and collation of text literals in internal
255 representation of query (item-objects).
256 */
258};
259
260/**
261 View_creation_ctx -- creation context of view objects.
262*/
263
265 public:
266 static View_creation_ctx *create(THD *thd);
267
268 static View_creation_ctx *create(THD *thd, Table_ref *view);
269
270 private:
272};
273
274/*************************************************************************/
275
276/** Order clause list element */
277
279
280struct ORDER {
281 /// @returns true if item pointer is same as original
282 bool is_item_original() const { return item[0] == item_initial; }
283
284 ORDER *next{nullptr};
285
286 /**
287 The initial ordering expression. Usually substituted during resolving
288 and must not be used during optimization and execution.
289 */
290 Item *item_initial{nullptr}; /* Storage for initial item */
291
292 public:
293 /**
294 Points at the item in the select fields. Note that this means that
295 after resolving, it points into a slice (see JOIN::ref_items),
296 even though the item is not of type Item_ref!
297 */
299
301
303 ORDER_NOT_RELEVANT}; /* Requested direction of ordering */
304 bool in_field_list{false}; /* true if in select field list */
305 /**
306 Tells whether this ORDER element was referenced with an alias or with an
307 expression, in the query:
308 SELECT a AS foo GROUP BY foo: true.
309 SELECT a AS foo GROUP BY a: false.
310 */
311 bool used_alias{false};
312 /**
313 When GROUP BY is implemented with a temporary table (i.e. the table takes
314 care to store only unique group rows, table->group != nullptr), each GROUP
315 BY expression is stored in a column of the table, which is
316 'field_in_tmp_table'.
317 Such field may point into table->record[0] (if we only use it to get its
318 value from a tmp table's row), or into 'buff' (if we use it to do index
319 lookup into the tmp table).
320 */
322 char *buff{nullptr}; /* If tmp-table group */
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_ref, 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 array */
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 overridden by SE. E.g. MyISAM does this at handler::open() and
902 handler::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_ref::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 protected: // To allow access from unit tests.
1262 /// Does this TABLE_SHARE represent a table in a secondary storage engine?
1264};
1265
1266/**
1267 Class is used as a BLOB field value storage for
1268 intermediate GROUP_CONCAT results. Used only for
1269 GROUP_CONCAT with DISTINCT or ORDER BY options.
1270 */
1271
1273 private:
1275 /**
1276 Sign that some values were cut
1277 during saving into the storage.
1278 */
1280
1281 public:
1284
1285 void reset() {
1287 truncated_value = false;
1288 }
1289 /**
1290 Function creates duplicate of 'from'
1291 string in 'storage' MEM_ROOT.
1292
1293 @param from string to copy
1294 @param length string length
1295
1296 @retval Pointer to the copied string.
1297 @retval 0 if an error occurred.
1298 */
1299 char *store(const char *from, size_t length) {
1300 return (char *)memdup_root(&storage, from, length);
1301 }
1304 }
1305 bool is_truncated_value() const { return truncated_value; }
1306};
1307
1308/**
1309 Class that represents a single change to a column value in partial
1310 update of a JSON column.
1311*/
1312class Binary_diff final {
1313 /// The offset of the start of the change.
1314 size_t m_offset;
1315
1316 /// The size of the portion that is to be replaced.
1317 size_t m_length;
1318
1319 public:
1320 /**
1321 Create a new Binary_diff object.
1322
1323 @param offset the offset of the beginning of the change
1324 @param length the length of the section that is to be replaced
1325 */
1326 Binary_diff(size_t offset, size_t length)
1328
1329 /// @return the offset of the changed data
1330 size_t offset() const { return m_offset; }
1331
1332 /// @return the length of the changed data
1333 size_t length() const { return m_length; }
1334
1335 /**
1336 Get a pointer to the start of the replacement data.
1337
1338 @param field the column that is updated
1339 @return a pointer to the start of the replacement data
1340 */
1341 const char *new_data(const Field *field) const;
1342
1343 /**
1344 Get a pointer to the start of the old data to be replaced.
1345
1346 @param field the column that is updated
1347 @return a pointer to the start of old data to be replaced.
1348 */
1349 const char *old_data(const Field *field) const;
1350};
1351
1352/**
1353 Vector of Binary_diff objects.
1354
1355 The Binary_diff objects in the vector should be ordered on offset, and none
1356 of the diffs should be overlapping or adjacent.
1357*/
1359
1360/**
1361 Flags for TABLE::m_status (maximum 8 bits).
1362 The flags define the state of the row buffer in TABLE::record[0].
1363*/
1364/**
1365 STATUS_NOT_STARTED is set when table is not accessed yet.
1366 Neither STATUS_NOT_FOUND nor STATUS_NULL_ROW can be set when this flag is set.
1367*/
1368#define STATUS_NOT_STARTED 1
1369/**
1370 Means we were searching for a row and didn't find it. This is used by
1371 storage engines (@see handler::index_read_map()) and the executor, both
1372 when doing an exact row lookup and advancing a scan (no more rows in range).
1373*/
1374#define STATUS_NOT_FOUND 2
1375/// Reserved for use by multi-table update. Means the row has been updated.
1376#define STATUS_UPDATED 16
1377/**
1378 Means that table->null_row is set. This is an artificial NULL-filled row
1379 (one example: in outer join, if no match has been found in inner table).
1380*/
1381#define STATUS_NULL_ROW 32
1382/// Reserved for use by multi-table delete. Means the row has been deleted.
1383#define STATUS_DELETED 64
1384
1385/* Information for one open table */
1387
1388/* Bitmap of table's fields */
1390
1391/*
1392 NOTE: Despite being a struct (for historical reasons), TABLE has
1393 a nontrivial destructor.
1394*/
1395struct TABLE {
1396 TABLE_SHARE *s{nullptr};
1397 handler *file{nullptr};
1398 TABLE *next{nullptr}, *prev{nullptr};
1399
1400 private:
1401 /**
1402 Links for the lists of used/unused TABLE objects for the particular
1403 table in the specific instance of Table_cache (in other words for
1404 specific Table_cache_element object).
1405 Declared as private to avoid direct manipulation with those objects.
1406 One should use methods of I_P_List template instead.
1407 */
1408 TABLE *cache_next{nullptr}, **cache_prev{nullptr};
1409
1410 /*
1411 Give Table_cache_element access to the above two members to allow
1412 using them for linking TABLE objects in a list.
1413 */
1415
1416 public:
1417 /**
1418 A bitmap marking the hidden generated columns that exists for functional
1419 indexes.
1420 */
1422 /**
1423 The current session using this table object.
1424 Should be NULL when object is not in use.
1425 For an internal temporary table, it is NULL when the table is closed.
1426 Used for two purposes:
1427 - Signal that the object is in use, and by which session.
1428 - Pass the thread handler to storage handlers.
1429 The field should NOT be used as a general THD reference, instead use
1430 a passed THD reference, or, if there is no such, current_thd.
1431 The reason for this is that we cannot guarantee the field is not NULL.
1432 */
1433 THD *in_use{nullptr};
1434 Field **field{nullptr}; /* Pointer to fields */
1435 /// Count of hidden fields, if internal temporary table; 0 otherwise.
1437
1438 uchar *record[2]{nullptr, nullptr}; /* Pointer to records */
1439 uchar *write_row_record{nullptr}; /* Used as optimisation in
1440 THD::write_row */
1441 uchar *insert_values{nullptr}; /* used by INSERT ... UPDATE */
1442
1443 /// Buffer for use in multi-row reads. Initially empty.
1445
1446 /*
1447 Map of keys that can be used to retrieve all data from this table
1448 needed by the query without reading the row.
1449 */
1452
1453 /* Merge keys are all keys that had a column referred to in the query */
1455
1456 /*
1457 possible_quick_keys is a superset of quick_keys to use with EXPLAIN of
1458 JOIN-less commands (single-table UPDATE and DELETE).
1459
1460 When explaining regular JOINs, we use JOIN_TAB::keys to output the
1461 "possible_keys" column value. However, it is not available for
1462 single-table UPDATE and DELETE commands, since they don't use JOIN
1463 optimizer at the top level. OTOH they directly use the range optimizer,
1464 that collects all keys usable for range access here.
1465 */
1467
1468 /*
1469 A set of keys that can be used in the query that references this
1470 table.
1471
1472 All indexes disabled on the table's TABLE_SHARE (see TABLE::s) will be
1473 subtracted from this set upon instantiation. Thus for any TABLE t it holds
1474 that t.keys_in_use_for_query is a subset of t.s.keys_in_use. Generally we
1475 must not introduce any new keys here (see setup_tables).
1476
1477 The set is implemented as a bitmap.
1478 */
1480 /* Map of keys that can be used to calculate GROUP BY without sorting */
1482 /* Map of keys that can be used to calculate ORDER BY without sorting */
1484 KEY *key_info{nullptr}; /* data of keys defined for the table */
1485 /**
1486 Key part array for generated keys, used for materialized derived tables.
1487 This is a contiguous array, with size given by s->max_tmp_key_parts.
1488 */
1490
1491 Field *next_number_field{nullptr}; /* Set if next_number is activated */
1492 Field *found_next_number_field{nullptr}; /* Set on open */
1493 /// Pointer to generated columns
1494 Field **vfield{nullptr};
1495 /// Pointer to fields having the default value generated
1497 /// Field used by unique constraint
1499 // ----------------------------------------------------------------------
1500 // The next few members are used if this (temporary) file is used solely for
1501 // the materialization/computation of an INTERSECT or EXCEPT set operation
1502 // (in addition to hash_field above used to detect duplicate rows). For
1503 // INTERSECT and EXCEPT, we always use the hash field and compute the shape
1504 // of the result set using m_set_counter. The latter is a hidden field
1505 // located between the hash field and the row proper, only present for
1506 // INTERSECT or EXCEPT materialized in a temporary result table. The
1507 // materialized table has no duplicate rows, relying instead of the embedded
1508 // counter to produce the correct number of duplicates with ALL semantics. If
1509 // we have distinct semantics, we squash duplicates. This all happens in the
1510 // reading step of the tmp table (TableScanIterator::Read),
1511 // cf. m_last_operation_is_distinct. For explanation if the logic of the set
1512 // counter, see MaterializeIterator<Profiler>::MaterializeQueryBlock.
1513 //
1514
1515 /// A priori unlimited. We pass this on to TableScanIterator at construction
1516 /// time, q.v., to limit the number of rows out of an EXCEPT or INTERSECT.
1517 /// For these set operations, we do not know enough to enforce the limit at
1518 /// materialize time (as for UNION): only when reading the rows with
1519 /// TableScanIterator do we check the counters.
1520 /// @todo: Ideally, this limit should be communicated to TableScanIterator in
1521 /// some other way.
1523
1524 private:
1525 /// The set counter. It points to the field in the materialized table
1526 /// holding the counter used to compute INTERSECT and EXCEPT, in record[0].
1527 /// For EXCEPT [DISTINCT | ALL] and INTERSECT DISTINCT this is a simple 64
1528 /// bits counter. For INTERSECT ALL, it is subdivided into two sub counters
1529 /// cf. class HalfCounter, cf. MaterializeQueryBlock. See set_counter().
1531
1532 /// True if we have EXCEPT, else we have INTERSECT. See is_except() and
1533 /// is_intersect().
1534 bool m_except{false};
1535
1536 /// If m_set_counter is set: true if last block has DISTINCT semantics,
1537 /// either because it is marked as such, or because we have computed this
1538 /// to give an equivalent answer. If false, we have ALL semantics.
1539 /// It will be true if any DISTINCT is given in the merged N-ary set
1540 /// operation. See is_distinct().
1542
1543 public:
1544 /// Test if this tmp table stores the result of a UNION set operation or
1545 /// a single table.
1546 /// @return true if so, else false.
1547 bool is_union_or_table() const { return m_set_counter == nullptr; }
1548 bool is_intersect() const { return m_set_counter != nullptr && !m_except; }
1549 bool is_except() const { return m_set_counter != nullptr && m_except; }
1551 /**
1552 Initialize the set counter field pointer and the type of set operation
1553 other than UNION.
1554 @param set_counter the field in the materialized table that holds the
1555 counter we use to compute intersect or except
1556 @param is_except if true, EXCEPT, else INTERSECT
1557 */
1561 }
1562
1563 void set_distinct(bool distinct) { m_last_operation_is_distinct = distinct; }
1564
1566 //
1567 // end of INTERSECT and EXCEPT specific members
1568 // ----------------------------------------------------------------------
1569
1570 Field *fts_doc_id_field{nullptr}; /* Set if FTS_DOC_ID field is present */
1571
1572 /* Table's triggers, 0 if there are no of them */
1574 Table_ref *pos_in_table_list{nullptr}; /* Element referring to this table */
1575 /* Position in thd->locked_table_list under LOCK TABLES */
1577 ORDER *group{nullptr};
1578 const char *alias{nullptr}; ///< alias or table name
1579 uchar *null_flags{nullptr}; ///< Pointer to the null flags of record[0]
1581 nullptr}; ///< Saved null_flags while null_row is true
1582
1583 /* containers */
1585 /*
1586 Bitmap of fields that one or more query condition refers to. Only
1587 used if optimizer_condition_fanout_filter is turned 'on'.
1588 Currently, only the WHERE clause and ON clause of inner joins is
1589 taken into account but not ON conditions of outer joins.
1590 Furthermore, HAVING conditions apply to groups and are therefore
1591 not useful as table condition filters.
1592 */
1594
1595 /**
1596 Bitmap of table fields (columns), which are explicitly set in the
1597 INSERT INTO statement. It is declared here to avoid memory allocation
1598 on MEM_ROOT).
1599
1600 @sa fields_set_during_insert.
1601 */
1603
1604 /**
1605 Set over all columns that the optimizer intends to read. This is used
1606 for two purposes: First, to tell the storage engine which ones it needs
1607 to populate. (In particular, NDB can save a lot of bandwidth here.)
1608 Second, functions that need to store and restore rows, such as hash join
1609 or filesort, need to know which ones to keep.
1610
1611 Set during resolving; every field that gets resolved, sets its own bit
1612 in the read set. In some cases, we switch the read set around during
1613 various phases; note that it is a pointer.
1614
1615 In addition, for binary logging purposes, the bitmaps are set according
1616 to the settings of @@binlog_row_image. Therefore, for logging purposes,
1617 some additional fields, to those specified by the optimizer, may be
1618 flagged in the read and write sets.
1619 @c TABLE::mark_columns_per_binlog_row_image for additional details.
1620 */
1622
1624
1625 /**
1626 A pointer to the bitmap of table fields (columns), which are explicitly set
1627 in the INSERT INTO statement.
1628
1629 fields_set_during_insert points to def_fields_set_during_insert
1630 for base (non-temporary) tables. In other cases, it is NULL.
1631 Triggers can not be defined for temporary tables, so this bitmap does not
1632 matter for temporary tables.
1633
1634 @sa def_fields_set_during_insert.
1635 */
1637
1638 /*
1639 The ID of the query that opened and is using this table. Has different
1640 meanings depending on the table type.
1641
1642 Temporary tables:
1643
1644 table->query_id is set to thd->query_id for the duration of a statement
1645 and is reset to 0 once it is closed by the same statement. A non-zero
1646 table->query_id means that a statement is using the table even if it's
1647 not the current statement (table is in use by some outer statement).
1648
1649 Non-temporary tables:
1650
1651 Under pre-locked or LOCK TABLES mode: query_id is set to thd->query_id
1652 for the duration of a statement and is reset to 0 once it is closed by
1653 the same statement. A non-zero query_id is used to control which tables
1654 in the list of pre-opened and locked tables are actually being used.
1655 */
1657
1658 /*
1659 For each key that has quick_keys.is_set(key) == true: estimate of #records
1660 and max #key parts that range access would use.
1661 */
1663
1664 /* Bitmaps of key parts that =const for the entire join. */
1666
1669
1670 /*
1671 Estimate of number of records that satisfy SARGable part of the table
1672 condition, or table->file->records if no SARGable condition could be
1673 constructed.
1674 This value is used by join optimizer as an estimate of number of records
1675 that will pass the table condition (condition that depends on fields of
1676 this table and constants)
1677 */
1679
1680 uint lock_position{0}; /* Position in MYSQL_LOCK.table */
1681 uint lock_data_start{0}; /* Start pos. in MYSQL_LOCK.locks */
1682 uint lock_count{0}; /* Number of locks */
1683 uint db_stat{0}; /* mode of file as in handler.h */
1684 int current_lock{0}; /* Type of lock on table */
1685
1686 // List of table check constraints.
1688
1689 private:
1690 /**
1691 If true, this table is inner w.r.t. some outer join operation, all columns
1692 are nullable (in the query), and null_row may be true.
1693 */
1694 bool nullable{false};
1695
1696 uint8 m_status{0}; /* What's in record[0] */
1697 public:
1698 /*
1699 If true, the current table row is considered to have all columns set to
1700 NULL, including columns declared as "not null" (see nullable).
1701 @todo make it private, currently join buffering changes it through a pointer
1702 */
1703 bool null_row{false};
1704
1705 bool copy_blobs{false}; /* copy_blobs when storing */
1706
1707 /*
1708 TODO: Each of the following flags take up 8 bits. They can just as easily
1709 be put into one single unsigned long and instead of taking up 18
1710 bytes, it would take up 4.
1711 */
1712 bool force_index{false};
1713
1714 /**
1715 Flag set when the statement contains FORCE INDEX FOR ORDER BY
1716 See Table_ref::process_index_hints().
1717 */
1719
1720 /**
1721 Flag set when the statement contains FORCE INDEX FOR GROUP BY
1722 See Table_ref::process_index_hints().
1723 */
1725 bool const_table{false};
1726 /// True if writes to this table should not write rows and just write keys.
1727 bool no_rows{false};
1728
1729 /**
1730 If set, the optimizer has found that row retrieval should access index
1731 tree only.
1732 */
1733 bool key_read{false};
1734 /**
1735 Certain statements which need the full row, set this to ban index-only
1736 access.
1737 */
1738 bool no_keyread{false};
1739 /**
1740 If set, indicate that the table is not replicated by the server.
1741 */
1742 bool no_replicate{false};
1743 /* To signal that the table is associated with a HANDLER statement */
1744 bool open_by_handler{false};
1745 /**
1746 To indicate that value of the auto_increment field was provided
1747 explicitly by the user or from some other source (e.g. in case of
1748 INSERT ... SELECT, ALTER TABLE or LOAD DATA) and not as default
1749 or result of conversion from NULL value.
1750
1751 @note Since auto_increment fields are always non-NULL we can't find
1752 out using methods of Field class if 0 value stored in such field
1753 was provided explicitly or is result of applying default/conversion
1754 from NULL value. In the former case no new auto_increment value
1755 needs to be generated in MODE_NO_AUTO_VALUE_ON_ZERO mode, while
1756 the latter cases require new value generation. Hence the need
1757 for this flag.
1758 @note Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode and only
1759 by handler::write_row().
1760 */
1762 bool alias_name_used{false}; /* true if table_name is alias */
1763 bool get_fields_in_item_tree{false}; /* Signal to fix_field */
1764
1765 private:
1766 /**
1767 This TABLE object is invalid and cannot be reused. TABLE object might have
1768 inconsistent info or handler might not allow some operations.
1769
1770 For example, TABLE might have inconsistent info about partitioning.
1771 We also use this flag to avoid calling handler::reset() for partitioned
1772 InnoDB tables after in-place ALTER TABLE API commit phase and to force
1773 closing table after REPAIR TABLE has failed during its prepare phase as
1774 well.
1775
1776 @note This member can be set only by thread that owns/has opened the
1777 table and while holding its THD::LOCK_thd_data lock.
1778 It can be read without locking by this owner thread, or by some other
1779 thread concurrently after acquiring owner's THD::LOCK_thd_data.
1780
1781 @note The TABLE will not be reopened under LOCK TABLES in
1782 close_thread_tables().
1783 */
1784 bool m_invalid_dict{false};
1785
1786 /**
1787 This TABLE object is invalid and cannot be reused as it has outdated
1788 rec_per_key and handler stats.
1789
1790 @note This member is protected from concurrent access to it by lock of
1791 Table Cache's partition to which this TABLE object belongs,
1792 */
1793 bool m_invalid_stats{false};
1794
1795 /**
1796 For tmp tables. true <=> tmp table has been instantiated.
1797 Also indicates that table was successfully opened since
1798 we immediately delete tmp tables which we fail to open.
1799 */
1800 bool created{false};
1801
1802 public:
1803 /// For a materializable derived or SJ table: true if has been materialized
1804 bool materialized{false};
1805 struct /* field connections */
1806 {
1807 class JOIN_TAB *join_tab{nullptr};
1808 class QEP_TAB *qep_tab{nullptr};
1809 thr_lock_type lock_type{TL_UNLOCK}; /* How table is used */
1812 /*
1813 true <=> range optimizer found that there is no rows satisfying
1814 table conditions.
1815 */
1816 bool impossible_range{false};
1818
1819 /**
1820 @todo This member should not be declared in-line. That makes it
1821 impossible for any function that does memory allocation to take a const
1822 reference to a TABLE object.
1823 */
1825 /**
1826 Initialized in Item_func_group_concat::setup for appropriate
1827 temporary table if GROUP_CONCAT is used with ORDER BY | DISTINCT
1828 and BLOB field count > 0.
1829 */
1831
1832 /**
1833 Not owned by the TABLE; used only from filesort_free_buffers().
1834 See comments on SortingIterator::CleanupAfterQuery().
1835 */
1838
1839 /**
1840 The result of applying a unique operation (by row ID) to the table, if done.
1841 In particular, this is done in some forms of index merge.
1842 */
1844 partition_info *part_info{nullptr}; /* Partition related information */
1845 /* If true, all partitions have been pruned away */
1848
1849 private:
1850 /// Cost model object for operations on this table
1852#ifndef NDEBUG
1853 /**
1854 Internal tmp table sequential number. Increased in the order of
1855 creation. Used for debugging purposes when many tmp tables are used
1856 during execution (e.g several windows with window functions)
1857 */
1859#endif
1860 public:
1861 void reset();
1862 void init(THD *thd, Table_ref *tl);
1863 bool init_tmp_table(THD *thd, TABLE_SHARE *share, MEM_ROOT *m_root,
1864 CHARSET_INFO *charset, const char *alias, Field **fld,
1865 uint *blob_fld, bool is_virtual);
1866 bool fill_item_list(mem_root_deque<Item *> *item_list) const;
1867 void clear_column_bitmaps(void);
1868 void prepare_for_position(void);
1869
1872 uint key_parts = 0) const;
1874 void mark_auto_increment_column(void);
1875 void mark_columns_needed_for_update(THD *thd, bool mark_binlog_columns);
1879 void mark_generated_columns(bool is_update);
1880 void mark_gcol_in_maps(const Field *field);
1881 void mark_check_constraint_columns(bool is_update);
1882 void column_bitmaps_set(MY_BITMAP *read_set_arg, MY_BITMAP *write_set_arg);
1883 inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg,
1884 MY_BITMAP *write_set_arg) {
1885 read_set = read_set_arg;
1886 write_set = write_set_arg;
1887 }
1888 inline void use_all_columns() {
1890 }
1894 }
1895 void invalidate_dict();
1896 void invalidate_stats();
1897 /**
1898 @note Can be called by thread owning table without additional locking, and
1899 by any other thread which has acquired owner's THD::LOCK_thd_data lock.
1900 */
1901 inline bool has_invalid_dict() const {
1902 assert(assert_invalid_dict_is_locked(this));
1903 return !db_stat || m_invalid_dict;
1904 }
1905 /// @note Can be called by thread owning Table_cache::m_lock
1906 inline bool has_invalid_stats() {
1907 assert(assert_invalid_stats_is_locked(this));
1908 return m_invalid_stats;
1909 }
1910 /// @returns first non-hidden column
1912 /// @returns count of visible fields
1914 bool alloc_tmp_keys(uint new_key_count, uint new_key_part_count,
1915 bool modify_share);
1916 bool add_tmp_key(Field_map *key_parts, bool invisible, bool modify_share);
1917 void move_tmp_key(int old_idx, bool modify_share);
1918 void drop_unused_tmp_keys(bool modify_share);
1919
1920 void set_keyread(bool flag);
1921
1922 /**
1923 Check whether the given index has a virtual generated columns.
1924
1925 @param index_no the given index to check
1926
1927 @returns true if if index is defined over at least one virtual generated
1928 column
1929 */
1930 inline bool index_contains_some_virtual_gcol(uint index_no) const {
1931 assert(index_no < s->keys);
1932 return key_info[index_no].flags & HA_VIRTUAL_GEN_KEY;
1933 }
1934 void update_const_key_parts(Item *conds);
1935
1937
1938 ptrdiff_t default_values_offset() const {
1939 return (ptrdiff_t)(s->default_values - record[0]);
1940 }
1941
1942 /// @returns true if a storage engine handler object is assigned to table
1943 bool has_storage_handler() const { return file != nullptr; }
1944
1945 /// Set storage handler for temporary table
1947 // Ensure consistent call order
1948 assert((file == nullptr && file_arg != nullptr) ||
1949 (file != nullptr && file_arg == nullptr));
1950 assert(!is_created());
1951 assert(file_arg->inited == handler::NONE);
1952 file = file_arg;
1953 }
1954 /// Return true if table is instantiated, and false otherwise.
1955 bool is_created() const { return created; }
1956
1957 /**
1958 Set the table as "created", and enable flags in storage engine
1959 that could not be enabled without an instantiated table.
1960 */
1961 void set_created();
1962 /**
1963 Set the contents of table to be "deleted", ie "not created", after having
1964 deleted the contents.
1965 */
1966 void set_deleted() { created = materialized = false; }
1967 /// Set table as nullable, ie it is inner wrt some outer join
1968 void set_nullable() { nullable = true; }
1969
1970 /// Return whether table is nullable
1971 bool is_nullable() const { return nullable; }
1972
1973 /// @return true if table contains one or more generated columns
1974 bool has_gcol() const { return vfield; }
1975
1976 /**
1977 Life cycle of the row buffer is as follows:
1978 - The initial state is "not started".
1979 - When reading a row through the storage engine handler, the status is set
1980 as "has row" or "no row", depending on whether a row was found or not.
1981 The "not started" state is cleared, as well as the "null row" state,
1982 the updated state and the deleted state.
1983 - When making a row available in record[0], make sure to update row status
1984 similarly to how the storage engine handler does it.
1985 - If a NULL-extended row is needed in join execution, the "null row" state
1986 is set. Note that this can be combined with "has row" if a row was read
1987 but condition on it was evaluated to false (happens for single-row
1988 lookup), or "no row" if no more rows could be read.
1989 Note also that for the "null row" state, the NULL bits inside the
1990 row are set to one, so the row inside the row buffer is no longer usable,
1991 unless the NULL bits are saved in a separate buffer.
1992 - The "is updated" and "is deleted" states are set when row is updated or
1993 deleted, respectively.
1994 */
1995 /// Set status for row buffer as "not started"
1998 null_row = false;
1999 }
2000
2001 /// @return true if a row operation has been done
2002 bool is_started() const { return !(m_status & STATUS_NOT_STARTED); }
2003
2004 /// Set status for row buffer: contains row
2006 m_status = 0;
2007 null_row = false;
2008 }
2009
2010 /**
2011 Set status for row buffer: contains no row. This is set when
2012 - A lookup operation finds no row
2013 - A scan operation scans past the last row of the range.
2014 - An error in generating key values before calling storage engine.
2015 */
2016 void set_no_row() {
2018 null_row = false;
2019 }
2020
2021 /**
2022 Set "row found" status from handler result
2023
2024 @param status 0 if row was found, <> 0 if row was not found
2025 */
2028 null_row = false;
2029 }
2030
2031 /**
2032 Set current row as "null row", for use in null-complemented outer join.
2033 The row buffer may or may not contain a valid row.
2034 set_null_row() and reset_null_row() are used by the join executor to
2035 signal the presence or absence of a NULL-extended row for an outer joined
2036 table. Null rows may also be used to specify rows that are all NULL in
2037 grouing operations.
2038 @note this is a destructive operation since the NULL value bit vector
2039 is overwritten. Caching operations must be aware of this.
2040 */
2042 null_row = true;
2044 if (s->null_bytes > 0) memset(null_flags, 255, s->null_bytes);
2045 }
2046
2047 /// Clear "null row" status for the current row
2049 null_row = false;
2050 m_status &= ~STATUS_NULL_ROW;
2051 }
2052
2053 /// Set "updated" property for the current row
2055 assert(is_started() && has_row());
2057 }
2058
2059 /// Set "deleted" property for the current row
2061 assert(is_started() && has_row());
2063 }
2064
2065 /// @return true if there is a row in row buffer
2066 bool has_row() const { return !(m_status & STATUS_NOT_FOUND); }
2067
2068 /// @return true if current row is null-extended
2069 bool has_null_row() const { return null_row; }
2070
2071 /// @return true if current row has been updated (multi-table update)
2072 bool has_updated_row() const { return m_status & STATUS_UPDATED; }
2073
2074 /// @return true if current row has been deleted (multi-table delete)
2075 bool has_deleted_row() const { return m_status & STATUS_DELETED; }
2076
2077 /// Save the NULL flags of the current row into the designated buffer
2079 if (s->null_bytes > 0) memcpy(null_flags_saved, null_flags, s->null_bytes);
2080 }
2081
2082 /// Restore the NULL flags of the current row from the designated buffer
2084 if (s->null_bytes > 0) memcpy(null_flags, null_flags_saved, s->null_bytes);
2085 }
2086
2087 /// Empties internal temporary table (deletes rows, closes scan)
2088 bool empty_result_table();
2089
2090 /**
2091 Initialize the optimizer cost model.
2092
2093 This function should be called each time a new query is started.
2094
2095 @param cost_model_server the main cost model object for the query
2096 */
2097 void init_cost_model(const Cost_model_server *cost_model_server) {
2098 m_cost_model.init(cost_model_server, this);
2099 }
2100
2101 /**
2102 Return the cost model object for this table.
2103 */
2104 const Cost_model_table *cost_model() const { return &m_cost_model; }
2105
2106 /**
2107 Bind all the table's value generator columns in all the forms:
2108 stored/virtual GC, default expressions and checked constraints.
2109
2110 @details When a table is opened from the dictionary, the Value Generator
2111 expressions are bound during opening (see fix_value_generator_fields()).
2112 After query execution, Item::cleanup() is called on them
2113 (see cleanup_value_generator_items()). When the table is opened from the
2114 table cache, the Value Generetor(s) need to be bound again and this
2115 function does that.
2116 */
2118
2119 /**
2120 Clean any state in items associated with generated columns to be ready for
2121 the next statement.
2122 */
2124
2125#ifndef NDEBUG
2127#endif
2128 /**
2129 Update covering keys depending on max read key length.
2130
2131 Update available covering keys for the table, based on a constrained field
2132 and the identified covering prefix keys: If the matched part of field is
2133 longer than the index prefix,
2134 the prefix index cannot be used as a covering index.
2135
2136 @param[in] field Pointer to field object
2137 @param[in] key_read_length Max read key length
2138 @param[in] covering_prefix_keys Covering prefix keys
2139 */
2140 void update_covering_prefix_keys(Field *field, uint16 key_read_length,
2141 Key_map *covering_prefix_keys);
2142
2143 private:
2144 /**
2145 Bitmap that tells which columns are eligible for partial update in an
2146 update statement.
2147
2148 The bitmap is lazily allocated in the TABLE's mem_root when
2149 #mark_column_for_partial_update() is called.
2150 */
2152
2153 /**
2154 Object which contains execution time state used for partial update
2155 of JSON columns.
2156
2157 It is allocated in the execution mem_root by #setup_partial_update() if
2158 there are columns that have been marked as eligible for partial update.
2159 */
2161
2162 /**
2163 This flag decides whether or not we should log the drop temporary table
2164 command.
2165 */
2167
2168 public:
2169 /**
2170 Does this table have any columns that can be updated using partial update
2171 in the current row?
2172
2173 @return whether any columns in the current row can be updated using partial
2174 update
2175 */
2176 bool has_binary_diff_columns() const;
2177
2178 /**
2179 Get the list of binary diffs that have been collected for a given column in
2180 the current row, or `nullptr` if partial update cannot be used for that
2181 column.
2182
2183 @param field the column to get binary diffs for
2184 @return the list of binary diffs for the column, or `nullptr` if the column
2185 cannot be updated using partial update
2186 */
2187 const Binary_diff_vector *get_binary_diffs(const Field *field) const;
2188
2189 /**
2190 Mark a given column as one that can potentially be updated using
2191 partial update during execution of an update statement.
2192
2193 Whether it is actually updated using partial update, is not
2194 determined until execution time, since that depends both on the
2195 data that is in the column and the new data that is written to the
2196 column.
2197
2198 This function should be called during preparation of an update
2199 statement.
2200
2201 @param field a column which is eligible for partial update
2202 @retval false on success
2203 @retval true on out-of-memory
2204 */
2206
2207 /**
2208 Has this column been marked for partial update?
2209
2210 Note that this only tells if the column satisfies the syntactical
2211 requirements for being partially updated. Use #is_binary_diff_enabled() or
2212 #is_logical_diff_enabled() instead to see if partial update should be used
2213 on the column.
2214
2215 @param field the column to check
2216 @return whether the column has been marked for partial update
2217 */
2218 bool is_marked_for_partial_update(const Field *field) const;
2219
2220 /**
2221 Does this table have any columns that were marked with
2222 #mark_column_for_partial_update()?
2223
2224 Note that this only tells if any of the columns satisfy the syntactical
2225 requirements for being partially updated. Use
2226 #has_binary_diff_columns(), #is_binary_diff_enabled() or
2227 #is_logical_diff_enabled() instead to see if partial update should be used
2228 on a column.
2229 */
2231
2232 /**
2233 Enable partial update of JSON columns in this table. It is only
2234 enabled for the columns that have previously been marked for
2235 partial update using #mark_column_for_partial_update().
2236
2237 @param logical_diffs should logical JSON diffs be collected in addition
2238 to the physical binary diffs?
2239
2240 This function should be called once per statement execution, when
2241 the update statement is optimized.
2242
2243 @retval false on success
2244 @retval true on out-of-memory
2245 */
2246 bool setup_partial_update(bool logical_diffs);
2247
2248 /**
2249 @see setup_partial_update(bool)
2250
2251 This is a wrapper that auto-computes the value of the parameter
2252 logical_diffs.
2253
2254 @retval false on success
2255 @retval true on out-of-memory
2256 */
2257 bool setup_partial_update();
2258
2259 /**
2260 Add a binary diff for a column that is updated using partial update.
2261
2262 @param field the column that is being updated
2263 @param offset the offset of the changed portion
2264 @param length the length of the changed portion
2265
2266 @retval false on success
2267 @retval true on out-of-memory
2268 */
2269 bool add_binary_diff(const Field *field, size_t offset, size_t length);
2270
2271 /**
2272 Clear the diffs that have been collected for partial update of
2273 JSON columns, and re-enable partial update for any columns where
2274 partial update was temporarily disabled for the current row.
2275 Should be called between each row that is updated.
2276 */
2278
2279 /**
2280 Clean up state used for partial update of JSON columns.
2281
2282 This function should be called at the end of each statement
2283 execution.
2284 */
2286
2287 /**
2288 Temporarily disable collection of binary diffs for a column in the current
2289 row.
2290
2291 This function is called during execution to disable partial update of a
2292 column that was previously marked as eligible for partial update with
2293 #mark_column_for_partial_update() during preparation.
2294
2295 Partial update of this column will be re-enabled when we go to the next
2296 row.
2297
2298 @param field the column to stop collecting binary diffs for
2299 */
2301
2302 /**
2303 Temporarily disable collection of Json_diff objects describing the
2304 logical changes of a JSON column in the current row.
2305
2306 Collection of logical JSON diffs is re-enabled when we go to the next row.
2307
2308 @param field the column to stop collecting logical JSON diffs for
2309 */
2311
2312 /**
2313 Get a buffer that can be used to hold the partially updated column value
2314 while performing partial update.
2315 */
2317
2318 /**
2319 Add a logical JSON diff describing a logical change to a JSON column in
2320 partial update.
2321
2322 @param field the column that is updated
2323 @param path the JSON path that is changed
2324 @param operation the operation to perform
2325 @param new_value the new value in the path
2326
2327 @throws std::bad_alloc if memory cannot be allocated
2328 */
2330 enum_json_diff_operation operation,
2331 const Json_wrapper *new_value);
2332
2333 /**
2334 Get the list of JSON diffs that have been collected for a given column in
2335 the current row, or `nullptr` if partial update cannot be used for that
2336 column.
2337
2338 @param field the column to get JSON diffs for
2339 @return the list of JSON diffs for the column, or `nullptr` if the column
2340 cannot be updated using partial update
2341 */
2343
2344 /**
2345 Is partial update using binary diffs enabled on this JSON column?
2346
2347 @param field the column to check
2348 @return whether the column can be updated with binary diffs
2349 */
2350 bool is_binary_diff_enabled(const Field *field) const;
2351
2352 /**
2353 Is partial update using logical diffs enabled on this JSON column?
2354
2355 @param field the column to check
2356 @return whether the column can be updated with JSON diffs
2357 */
2358 bool is_logical_diff_enabled(const Field *field) const;
2359
2360 /**
2361 Virtual fields of type BLOB have a flag m_keep_old_value. This flag is set
2362 to false for all such fields in this table.
2363 */
2365
2366 /**
2367 Set the variable should_binlog_drop_if_temp_flag, so that
2368 the logging of temporary tables can be decided.
2369
2370 @param should_binlog the value to set flag should_binlog_drop_if_temp_flag
2371 */
2372 void set_binlog_drop_if_temp(bool should_binlog);
2373
2374 /**
2375 @return whether should_binlog_drop_if_temp_flag flag is
2376 set or not
2377 */
2378 bool should_binlog_drop_if_temp(void) const;
2379};
2380
2381static inline void empty_record(TABLE *table) {
2382 restore_record(table, s->default_values);
2383 if (table->s->null_bytes > 0)
2384 memset(table->null_flags, 255, table->s->null_bytes);
2385}
2386
2387#define MY_I_S_MAYBE_NULL 1
2388#define MY_I_S_UNSIGNED 2
2389
2391 /**
2392 This is used as column name.
2393 */
2394 const char *field_name;
2395 /**
2396 For string-type columns, this is the maximum number of
2397 characters. Otherwise, it is the 'display-length' for the column.
2398 For the data type MYSQL_TYPE_DATETIME this field specifies the
2399 number of digits in the fractional part of time value.
2400 */
2402 /**
2403 This denotes data type for the column. For the most part, there seems to
2404 be one entry in the enum for each SQL data type, although there seem to
2405 be a number of additional entries in the enum.
2406 */
2409 /**
2410 This is used to set column attributes. By default, columns are @c NOT
2411 @c NULL and @c SIGNED, and you can deviate from the default
2412 by setting the appropriate flags. You can use either one of the flags
2413 @c MY_I_S_MAYBE_NULL and @c MY_I_S_UNSIGNED or
2414 combine them using the bitwise or operator @c |. Both flags are
2415 defined in table.h.
2416 */
2417 uint field_flags; // Field attributes (maybe_null, signed, unsigned etc.)
2418 const char *old_name;
2419 uint open_method; // Not used
2420};
2421
2423 const char *table_name;
2425 /* Fill table with data */
2426 int (*fill_table)(THD *thd, Table_ref *tables, Item *cond);
2427 /* Handle fields for old SHOW */
2428 int (*old_format)(THD *thd, ST_SCHEMA_TABLE *schema_table);
2429 int (*process_table)(THD *thd, Table_ref *tables, TABLE *table, bool res,
2432};
2433
2434/**
2435 Strategy for how to process a view or derived table (merge or materialization)
2436*/
2442
2443#define VIEW_SUID_INVOKER 0
2444#define VIEW_SUID_DEFINER 1
2445#define VIEW_SUID_DEFAULT 2
2446
2447/* view WITH CHECK OPTION parameter options */
2448#define VIEW_CHECK_NONE 0
2449#define VIEW_CHECK_LOCAL 1
2450#define VIEW_CHECK_CASCADED 2
2451
2452/* result of view WITH CHECK OPTION parameter check */
2453#define VIEW_CHECK_OK 0
2454#define VIEW_CHECK_ERROR 1
2455#define VIEW_CHECK_SKIP 2
2456
2457/** The threshold size a blob field buffer before it is freed */
2458#define MAX_TDC_BLOB_SIZE 65536
2459
2460/**
2461 Struct that describes an expression selected from a derived table or view.
2462*/
2464 /**
2465 Points to an item that represents the expression.
2466 If the item is determined to be unused, the pointer is set to NULL.
2467 */
2469 /// Name of selected expression
2470 const char *name;
2471};
2472
2473/*
2474 Column reference of a NATURAL/USING join. Since column references in
2475 joins can be both from views and stored tables, may point to either a
2476 Field (for tables), or a Field_translator (for views).
2477*/
2478
2480 public:
2481 Field_translator *view_field; /* Column reference of merge view. */
2482 Item_field *table_field; /* Column reference of table or temp view. */
2483 Table_ref *table_ref; /* Original base table/view reference. */
2484 /*
2485 True if a common join column of two NATURAL/USING join operands. Notice
2486 that when we have a hierarchy of nested NATURAL/USING joins, a column can
2487 be common at some level of nesting but it may not be common at higher
2488 levels of nesting. Thus this flag may change depending on at which level
2489 we are looking at some column.
2490 */
2492
2493 public:
2495 Natural_join_column(Item_field *field_param, Table_ref *tab);
2496 const char *name();
2497 Item *create_item(THD *thd);
2498 Field *field();
2499 const char *table_name();
2500 const char *db_name();
2501 GRANT_INFO *grant();
2502};
2503
2504/**
2505 This is generic enum. It may be reused in the ACL statements
2506 for clauses that can map to the values defined in this enum.
2507*/
2509 UNCHANGED, /* The clause is not specified */
2510 DEFAULT, /* Default value of clause is specified */
2511 YES, /* Value that maps to True is specified */
2512 NO /* Value that maps to False is specified */
2513};
2514
2515struct LEX_MFA {
2521 /*
2522 The following flags are indicators for the SQL syntax used while
2523 parsing CREATE/ALTER user. While other members are self-explanatory,
2524 'uses_authentication_string_clause' signifies if the password is in
2525 hash form (if the var was set to true) or not.
2526 */
2531 /* flag set during CREATE USER .. INITIAL AUTHENTICATION BY */
2533 /* flag set during ALTER USER .. ADD nth FACTOR */
2535 /* flag set during ALTER USER .. MODIFY nth FACTOR */
2537 /* flag set during ALTER USER .. DROP nth FACTOR */
2539 /*
2540 flag used during authentication and to decide if server should
2541 be in sandbox mode or not
2542 */
2544 /* flag set during ALTER USER .. nth FACTOR UNREGISTER */
2546 /* flag set during ALTER USER .. INITIATE REGISTRATION */
2548 /* flag set during ALTER USER .. FINISH REGISTRATION */
2550
2552 void reset() {
2554 auth = NULL_CSTR;
2557 nth_factor = 1;
2561 has_password_generator = false;
2562 passwordless = false;
2563 add_factor = false;
2564 drop_factor = false;
2565 modify_factor = false;
2566 requires_registration = false;
2567 unregister = false;
2568 init_registration = false;
2569 finish_registration = false;
2570 }
2571 void copy(LEX_MFA *m, MEM_ROOT *alloc);
2572};
2573
2574/*
2575 This structure holds the specifications relating to
2576 ALTER user ... PASSWORD EXPIRE ...
2577*/
2595 /* Holds the specification of 'PASSWORD REQUIRE CURRENT' clause. */
2597 void cleanup() {
2603 account_locked = false;
2615 }
2616};
2617
2618/*
2619 This structure holds the specifications related to
2620 mysql user and the associated auth details.
2621*/
2622struct LEX_USER {
2630 /* restrict MFA methods to atmost 3 authentication plugins */
2634
2635 void init() {
2636 user = NULL_CSTR;
2637 host = NULL_CSTR;
2639 uses_replace_clause = false;
2641 discard_old_password = false;
2658 mfa_list.clear();
2659 with_initial_auth = false;
2660 }
2661
2663
2664 bool add_mfa_identifications(LEX_MFA *factor2, LEX_MFA *factor3 = nullptr);
2665
2666 /*
2667 Allocates the memory in the THD mem pool and initialize the members of
2668 this struct. It is preferable to use this method to create a LEX_USER
2669 rather allocating the memory in the THD and initializing the members
2670 explicitly.
2671 */
2672 static LEX_USER *alloc(THD *thd);
2673 static LEX_USER *alloc(THD *thd, LEX_STRING *user, LEX_STRING *host);
2674 /*
2675 Initialize the members of this struct. It is preferable to use this method
2676 to initialize a LEX_USER rather initializing the members explicitly.
2677 */
2678 static LEX_USER *init(LEX_USER *to_init, THD *thd, LEX_STRING *user,
2679 LEX_STRING *host);
2680};
2681
2682/**
2683 Derive type of metadata lock to be requested for table used by a DML
2684 statement from the type of THR_LOCK lock requested for this table.
2685*/
2686
2687inline enum enum_mdl_type mdl_type_for_dml(enum thr_lock_type lock_type) {
2688 return lock_type >= TL_WRITE_ALLOW_WRITE
2692}
2693
2694/**
2695 Type of table which can be open for an element of table list.
2696*/
2697
2703
2704/**
2705 This structure is used to keep info about possible key for the result table
2706 of a derived table/view.
2707 The 'referenced_by' is the table map of tables to which this possible
2708 key corresponds.
2709 The 'used_field' is a map of fields of which this key consists of.
2710 See also the comment for the Table_ref::update_derived_keys function.
2711*/
2712
2714 public:
2718};
2719
2720class Table_function;
2721/*
2722 Table reference in the FROM clause.
2723
2724 These table references can be of several types that correspond to
2725 different SQL elements. Below we list all types of TABLE_LISTs with
2726 the necessary conditions to determine when a Table_ref instance
2727 belongs to a certain type.
2728
2729 1) table (Table_ref::view == NULL)
2730 - base table
2731 (Table_ref::derived == NULL)
2732 - subquery - Table_ref::table is a temp table
2733 (Table_ref::derived != NULL)
2734 - information schema table
2735 (Table_ref::schema_table != NULL)
2736 NOTICE: for schema tables Table_ref::field_translation may be != NULL
2737 2) view (Table_ref::view != NULL)
2738 - merge (Table_ref::effective_algorithm == VIEW_ALGORITHM_MERGE)
2739 also (Table_ref::field_translation != NULL)
2740 - temptable(Table_ref::effective_algorithm == VIEW_ALGORITHM_TEMPTABLE)
2741 also (Table_ref::field_translation == NULL)
2742 3) nested table reference (Table_ref::nested_join != NULL)
2743 - table sequence - e.g. (t1, t2, t3)
2744 TODO: how to distinguish from a JOIN?
2745 - general JOIN
2746 TODO: how to distinguish from a table sequence?
2747 - NATURAL JOIN
2748 (Table_ref::natural_join != NULL)
2749 - JOIN ... USING
2750 (Table_ref::join_using_fields != NULL)
2751 - semi-join
2752 ;
2753*/
2754
2756 public:
2757 Table_ref() = default;
2758
2759 /**
2760 Only to be used by legacy code that temporarily needs a Table_ref,
2761 more specifically: Query_result_create::binlog_show_create_table().
2762 */
2763 explicit Table_ref(TABLE *table_arg) : table(table_arg) {}
2764
2765 /// Constructor that can be used when the strings are null terminated.
2766 Table_ref(const char *db_name, const char *table_name,
2767 enum thr_lock_type lock_type)
2768 : Table_ref(db_name, strlen(db_name), table_name, strlen(table_name),
2769 table_name, lock_type) {}
2770
2771 /**
2772 Creates a Table_ref object with pre-allocated strings for database,
2773 table and alias.
2774 */
2775 Table_ref(TABLE *table_arg, const char *db_name_arg, size_t db_length_arg,
2776 const char *table_name_arg, size_t table_name_length_arg,
2777 const char *alias_arg, enum thr_lock_type lock_type_arg)
2778 : db(db_name_arg),
2779 table_name(table_name_arg),
2780 alias(alias_arg),
2781 m_map(1),
2782 table(table_arg),
2783 m_lock_descriptor{lock_type_arg},
2784 db_length(db_length_arg),
2785 table_name_length(table_name_length_arg) {
2788 }
2789
2790 /// Constructor that can be used when the strings are null terminated.
2791 Table_ref(const char *db_name, const char *table_name, const char *alias,
2792 enum thr_lock_type lock_type)
2793 : Table_ref(db_name, strlen(db_name), table_name, strlen(table_name),
2794 alias, lock_type) {}
2795
2796 /**
2797 This constructor can be used when a Table_ref is needed for an
2798 existing temporary table. These typically have very long table names, since
2799 it is a fully qualified path. For this reason, the table is set to the
2800 alias. The database name is left blank. The lock descriptor is set to
2801 TL_READ.
2802 */
2803 Table_ref(TABLE *table_arg, const char *alias_arg)
2804 : db(""),
2805 table_name(alias_arg),
2806 alias(alias_arg),
2807 m_map(1),
2808 table(table_arg),
2810 db_length(0),
2811 table_name_length(strlen(alias_arg)) {
2814 }
2815
2816 /**
2817 Sets an explicit enum_mdl_type value, without initializing
2818 m_lock_descriptor.
2819 */
2820 Table_ref(TABLE *table_arg, const char *alias_arg, enum_mdl_type mdl_type)
2821 : db(table_arg->s->db.str),
2822 table_name(table_arg->s->table_name.str),
2823 alias(alias_arg),
2824 m_map(1),
2825 table(table_arg),
2826 db_length(table_arg->s->db.length),
2827 table_name_length(table_arg->s->table_name.length) {
2830 }
2831
2832 Table_ref(const char *db_name, const char *table_name_arg,
2833 enum thr_lock_type lock_type_arg,
2834 enum enum_mdl_type mdl_request_type)
2835 : db(db_name),
2836 table_name(table_name_arg),
2837 alias(table_name_arg),
2838 m_map(1),
2839 m_lock_descriptor{lock_type_arg},
2840 db_length(strlen(db_name)),
2841 table_name_length(strlen(table_name_arg)) {
2844 mdl_request.set_type(mdl_request_type);
2845 }
2846
2847 Table_ref(const char *db_name, size_t db_length_arg,
2848 const char *table_name_arg, size_t table_name_length_arg,
2849 enum thr_lock_type lock_type_arg,
2850 enum enum_mdl_type mdl_request_type)
2851 : db(db_name),
2852 table_name(table_name_arg),
2853 alias(table_name_arg),
2854 m_map(1),
2855 m_lock_descriptor{lock_type_arg},
2856 db_length(db_length_arg),
2857 table_name_length(table_name_length_arg) {
2860 mdl_request.set_type(mdl_request_type);
2861 }
2862
2863 Table_ref(const char *db_name, size_t db_length_arg,
2864 const char *table_name_arg, size_t table_name_length_arg,
2865 enum thr_lock_type lock_type_arg)
2866 : db(db_name),
2867 table_name(table_name_arg),
2868 alias(table_name_arg),
2869 m_map(1),
2870 m_lock_descriptor{lock_type_arg},
2871 db_length(db_length_arg),
2872 table_name_length(table_name_length_arg) {}
2873
2874 /**
2875 Sets an explicit enum_mdl_type value, without initializing
2876 m_lock_descriptor.
2877 */
2878 Table_ref(const char *db_name, size_t db_length_arg,
2879 const char *table_name_arg, size_t table_name_length_arg,
2880 const char *alias_arg, enum enum_mdl_type mdl_request_type)
2881 : db(db_name),
2882 table_name(table_name_arg),
2883 alias(alias_arg),
2884 m_map(1),
2885 db_length(db_length_arg),
2886 table_name_length(table_name_length_arg) {
2889 mdl_request.set_type(mdl_request_type);
2890 }
2891
2892 Table_ref(const char *db_name, size_t db_length_arg,
2893 const char *table_name_arg, size_t table_name_length_arg,
2894 const char *alias_arg, enum thr_lock_type lock_type_arg,
2895 enum enum_mdl_type mdl_request_type)
2896 : db(db_name),
2897 table_name(table_name_arg),
2898 alias(alias_arg),
2899 m_map(1),
2900 m_lock_descriptor{lock_type_arg},
2901 db_length(db_length_arg),
2902 table_name_length(table_name_length_arg) {
2905 mdl_request.set_type(mdl_request_type);
2906 }
2907
2908 Table_ref(const char *db_name_arg, size_t db_length_arg,
2909 const char *table_name_arg, size_t table_name_length_arg,
2910 const char *alias_arg, enum thr_lock_type lock_type_arg)
2911 : db(db_name_arg),
2912 table_name(table_name_arg),
2913 alias(alias_arg),
2914 m_map(1),
2915 m_lock_descriptor{lock_type_arg},
2916 db_length(db_length_arg),
2917 table_name_length(table_name_length_arg) {
2920 }
2921
2922 /// Create a Table_ref object representing a nested join
2923 static Table_ref *new_nested_join(MEM_ROOT *allocator, const char *alias,
2925 mem_root_deque<Table_ref *> *belongs_to,
2926 Query_block *select);
2928 Item *join_cond() const { return m_join_cond; }
2929 void set_join_cond(Item *val) {
2930 // If optimization has started, it's too late to change m_join_cond.
2931 assert(m_join_cond_optim == nullptr || m_join_cond_optim == (Item *)1);
2932 m_join_cond = val;
2933 }
2936 /*
2937 Either we are setting to "empty", or there must pre-exist a
2938 permanent condition.
2939 */
2940 assert(cond == nullptr || cond == (Item *)1 || m_join_cond != nullptr);
2941 m_join_cond_optim = cond;
2942 }
2944
2945 /// @returns true if semi-join nest
2946 bool is_sj_nest() const { return m_is_sj_or_aj_nest && !m_join_cond; }
2947 /// @returns true if anti-join nest
2948 bool is_aj_nest() const { return m_is_sj_or_aj_nest && m_join_cond; }
2949 /// @returns true if anti/semi-join nest
2950 bool is_sj_or_aj_nest() const { return m_is_sj_or_aj_nest; }
2951 /// Makes the next a semi/antijoin nest
2953 assert(!m_is_sj_or_aj_nest);
2954 m_is_sj_or_aj_nest = true;
2955 }
2956
2957 /// Merge tables from a query block into a nested join structure
2959
2960 /// Reset table
2961 void reset();
2962
2963 /// Evaluate the check option of a view
2964 int view_check_option(THD *thd) const;
2965
2966 /// Cleanup field translations for a view
2967 void cleanup_items();
2968
2969 /// Produce a textual identification of this object
2970 void print(const THD *thd, String *str, enum_query_type query_type) const;
2971
2972 /// Check which single table inside a view that matches a table map
2973 bool check_single_table(Table_ref **table_ref, table_map map);
2974
2975 /// Allocate a buffer for inserted column values
2977
2979 /**
2980 Retrieve the last (right-most) leaf in a nested join tree with
2981 respect to name resolution.
2982
2983
2984 Given that 'this' is a nested table reference, recursively walk
2985 down the right-most children of 'this' until we reach a leaf
2986 table reference with respect to name resolution.
2987
2988 The right-most child of a nested table reference is the first
2989 element in the list of children because the children are inserted
2990 in reverse order.
2991
2992 @return
2993 - If 'this' is a nested table reference - the right-most child
2994 of the tree rooted in 'this',
2995 - else - 'this'
2996 */
2998 bool is_leaf_for_name_resolution() const;
2999
3000 /// Return the outermost view this table belongs to, or itself
3001 inline const Table_ref *top_table() const {
3002 return belong_to_view ? belong_to_view : this;
3003 }
3004
3006 return const_cast<Table_ref *>(
3007 const_cast<const Table_ref *>(this)->top_table());
3008 }
3009
3010 /// Prepare check option for a view
3011 bool prepare_check_option(THD *thd, bool is_cascaded = false);
3012
3013 /// Merge WHERE condition of view or derived table into outer query
3014 bool merge_where(THD *thd);
3015
3016 /// Prepare replace filter for a view (used for REPLACE command)
3017 bool prepare_replace_filter(THD *thd);
3018
3019 /// Return true if this represents a named view
3020 bool is_view() const { return view != nullptr; }
3021
3022 /// Return true if this represents a derived table (an unnamed view)
3023 bool is_derived() const { return derived != nullptr && view == nullptr; }
3024
3025 /// Return true if this represents a named view or a derived table
3026 bool is_view_or_derived() const { return derived != nullptr; }
3027
3028 /// Return true if this represents a table function
3029 bool is_table_function() const { return table_function != nullptr; }
3030 /**
3031 @returns true if this is a recursive reference inside the definition of a
3032 recursive CTE.
3033 @note that it starts its existence as a dummy derived table, until the
3034 end of resolution when it's not a derived table anymore, just a reference
3035 to the materialized temporary table. Whereas a non-recursive
3036 reference to the recursive CTE is a derived table.
3037 */
3039
3040 /// @returns true if this is a base table (permanent or temporary)
3041 bool is_base_table() const {
3042 return !(is_view_or_derived() || is_table_function() ||
3044 }
3045 /**
3046 @see is_recursive_reference().
3047 @returns true if error
3048 */
3050
3051 /**
3052 @returns true for a table that represents an optimizer internal table,
3053 is a derived table, a recursive reference, a table function.
3054 Internal tables are only visible inside a query expression, and is hence
3055 not visible in any schema, or need any kind of privilege checking.
3056 */
3057 bool is_internal() const {
3059 }
3060
3061 /**
3062 @returns true for a table that is a placeholder, ie a derived table,
3063 a view, a recursive reference, a table function or a schema table.
3064 A table is also considered to be a placeholder if it does not have a
3065 TABLE object for some other reason.
3066 */
3067 bool is_placeholder() const {
3069 is_table_function() || schema_table || table == nullptr;
3070 }
3071
3072 /// Return true if view or derived table and can be merged
3073 bool is_mergeable() const;
3074
3075 /**
3076 Checks if this is a table that contains zero rows or one row, and that can
3077 be materialized during optimization.
3078
3079 @returns true if materializable table contains one or zero rows, and
3080 materialization during optimization is permitted
3081
3082 Returning true, if the hypergraph optimizer is not active, implies that the
3083 table is materialized during optimization, so it need not be optimized
3084 during execution. The hypergraph optimizer does not care about const tables,
3085 so such tables are not executed during optimization time when it is active.
3086 */
3087 bool materializable_is_const() const;
3088
3089 /// Return true if this is a derived table or view that is merged
3091
3092 /// Set table to be merged
3093 void set_merged() {
3096 }
3097
3098 /// Return true if this is a materializable derived table/view
3101 }
3102
3103 /// Set table to be materialized
3105 // @todo We should do this only once, but currently we cannot:
3106 // assert(effective_algorithm == VIEW_ALGORITHM_UNDEFINED);
3109 }
3110
3111 /// Return true if table is updatable
3112 bool is_updatable() const { return m_updatable; }
3113
3114 /// Set table as updatable. (per default, a table is non-updatable)
3115 void set_updatable() { m_updatable = true; }
3116
3117 /// Return true if table is insertable-into
3118 bool is_insertable() const { return m_insertable; }
3119
3120 /// Set table as insertable-into. (per default, a table is not insertable)
3121 void set_insertable() { m_insertable = true; }
3122
3123 /// Return true if table is being updated
3124 bool is_updated() const { return m_updated; }
3125
3126 /// Set table and all referencing views as being updated
3128 for (Table_ref *tr = this; tr != nullptr; tr = tr->referencing_view)
3129 tr->m_updated = true;
3130 }
3131
3132 /// Return true if table is being inserted into
3133 bool is_inserted() const { return m_inserted; }
3134
3135 /// Set table and all referencing views as being inserted into
3137 for (Table_ref *tr = this; tr != nullptr; tr = tr->referencing_view)
3138 tr->m_inserted = true;
3139 }
3140
3141 /// Return true if table is being deleted from
3142 bool is_deleted() const { return m_deleted; }
3143
3144 /// Set table and all referencing views as being deleted from
3146 for (Table_ref *tr = this; tr != nullptr; tr = tr->referencing_view)
3147 tr->m_deleted = true;
3148 }
3149
3150 /// Set table as full-text search (default is not fulltext searched)
3152
3153 /// Returns true if a MATCH function references this table.
3155
3156 /**
3157 Set table as readonly, ie it is neither updatable, insertable nor
3158 deletable during this statement.
3159 */
3161 m_updatable = false;
3162 m_insertable = false;
3163 }
3164
3165 /**
3166 Return true if this is a view or derived table that is defined over
3167 more than one base table, and false otherwise.
3168 */
3169 bool is_multiple_tables() const {
3170 if (is_view_or_derived()) {
3171 assert(is_merged()); // Cannot be a materialized view
3172 return leaf_tables_count() > 1;
3173 } else {
3174 assert(nested_join == nullptr); // Must be a base table
3175 return false;
3176 }
3177 }
3178
3179 /// Return no. of base tables a merged view or derived table is defined over.
3180 uint leaf_tables_count() const;
3181
3182 /// Return first leaf table of a base table or a view/derived table
3184 Table_ref *tr = this;
3185 while (tr->merge_underlying_list) tr = tr->merge_underlying_list;
3186 return tr;
3187 }
3188
3189 /// Return any leaf table that is not an inner table of an outer join
3190 /// @todo WL#6570 with prepare-once, replace with first_leaf_table()
3191 /// when WL#6059 is merged in (it really converts RIGHT JOIN to
3192 /// LEFT JOIN so the first leaf is part of a LEFT JOIN,
3193 /// guaranteed).
3195 Table_ref *tr = this;
3196 while (tr->merge_underlying_list) {
3197 tr = tr->merge_underlying_list;
3198 /*
3199 "while" is used, however, an "if" might be sufficient since there is
3200 no more than one inner table in a join nest (with outer_join true).
3201 */
3202 while (tr->outer_join) tr = tr->next_local;
3203 }
3204 return tr;
3205 }
3206 /**
3207 Set the LEX object of a view (will also define this as a view).
3208 @note: The value 1 is used to indicate a view but without a valid
3209 query object. Use only if the LEX object is not going to
3210 be used in later processing.
3211 */
3212 void set_view_query(LEX *lex) { view = lex; }
3213
3214 /// Return the valid LEX object for a view.
3215 LEX *view_query() const {
3216 assert(view != nullptr && view != (LEX *)1);
3217 return view;
3218 }
3219
3220 /**
3221 Set the query expression of a derived table or view.
3222 (Will also define this as a derived table, unless it is a named view.)
3223 */
3225 derived = query_expr;
3226 }
3227
3228 /// Return the query expression of a derived table or view.
3230 assert(derived);
3231 return derived;
3232 }
3233
3234 /// Resolve a derived table or view reference
3235 bool resolve_derived(THD *thd, bool apply_semijoin);
3236
3237 /// Optimize the query expression representing a derived table/view
3238 bool optimize_derived(THD *thd);
3239
3240 /// Create result table for a materialized derived table/view
3241 bool create_materialized_table(THD *thd);
3242
3243 /// Materialize derived table
3244 bool materialize_derived(THD *thd);
3245
3246 /// Check if we can push outer where condition to this derived table
3248
3249 /// Return the number of hidden fields added for the temporary table
3250 /// created for this derived table.
3252
3253 /// Prepare security context for a view
3254 bool prepare_security(THD *thd);
3255
3258
3259 /**
3260 Compiles the tagged hints list and fills up TABLE::keys_in_use_for_query,
3261 TABLE::keys_in_use_for_group_by, TABLE::keys_in_use_for_order_by,
3262 TABLE::force_index and TABLE::covering_keys.
3263 */
3264 bool process_index_hints(const THD *thd, TABLE *table);
3265
3266 /**
3267 Compare the version of metadata from the previous execution
3268 (if any) with values obtained from the current table
3269 definition cache element.
3270
3271 @sa check_and_update_table_version()
3272 */
3274 return (m_table_ref_type == s->get_table_ref_type() &&
3276 }
3277
3278 /**
3279 Record the value of metadata version of the corresponding
3280 table definition cache element in this parse tree node.
3281
3282 @sa check_and_update_table_version()
3283 */
3286 }
3287
3288 void set_table_ref_id(enum_table_ref_type table_ref_type_arg,
3289 ulonglong table_ref_version_arg) {
3290 m_table_ref_type = table_ref_type_arg;
3291 m_table_ref_version = table_ref_version_arg;
3292 }
3293
3294 /**
3295 If a derived table, returns query block id of first underlying query block.
3296 Zero if not derived.
3297 */
3298 uint query_block_id() const;
3299
3300 /**
3301 This is for showing in EXPLAIN.
3302 If a derived table, returns query block id of first underlying query block
3303 of first materialized Table_ref instance. Zero if not derived.
3304 */
3306
3307 /**
3308 @brief Returns the name of the database that the referenced table belongs
3309 to.
3310 */
3311 const char *get_db_name() const { return db; }
3312
3313 /**
3314 @brief Returns the name of the table that this Table_ref represents.
3315
3316 @details The unqualified table name or view name for a table or view,
3317 respectively.
3318 */
3319 const char *get_table_name() const { return table_name; }
3321 bool update_derived_keys(THD *, Field *, Item **, uint, bool *);
3322 bool generate_keys();
3323
3324 /// Setup a derived table to use materialization
3327
3328 /// Setup a table function to use materialization
3329 bool setup_table_function(THD *thd);
3330
3331 bool create_field_translation(THD *thd);
3332
3333 /**
3334 @brief Returns the outer join nest that this Table_ref belongs to, if
3335 any.
3336
3337 @details There are two kinds of join nests, outer-join nests and semi-join
3338 nests. This function returns non-NULL in the following cases:
3339 @li 1. If this table/nest is embedded in a nest and this nest IS NOT a
3340 semi-join nest. (In other words, it is an outer-join nest.)
3341 @li 2. If this table/nest is embedded in a nest and this nest IS a
3342 semi-join nest, but this semi-join nest is embedded in another
3343 nest. (This other nest will be an outer-join nest, since all inner
3344 joined nested semi-join nests have been merged in
3345 @c simplify_joins() ).
3346 Note: This function assumes that @c simplify_joins() has been performed.
3347 Before that, join nests will be present for all types of join.
3348
3349 @return outer join nest, or NULL if none.
3350 */
3351
3353 if (!embedding) return nullptr;
3354 if (embedding->is_sj_nest()) return embedding->embedding;
3355 return embedding;
3356 }
3357 /**
3358 Return true if this table is an inner table of some outer join.
3359
3360 Examine all the embedding join nests of the table.
3361 @note This function works also before redundant join nests have been
3362 eliminated.
3363
3364 @return true if table is an inner table of some outer join, false otherwise.
3365 */
3366
3368 if (outer_join) return true;
3369 for (Table_ref *emb = embedding; emb; emb = emb->embedding) {
3370 if (emb->outer_join) return true;
3371 }
3372 return false;
3373 }
3374
3375 /**
3376 Return the base table entry of an updatable table.
3377 In DELETE and UPDATE, a view used as a target table must be mergeable,
3378 updatable and defined over a single table.
3379 */
3381 const Table_ref *tbl = this;
3382 assert(tbl->is_updatable() && !tbl->is_multiple_tables());
3383 while (tbl->is_view_or_derived()) {
3384 tbl = tbl->merge_underlying_list;
3385 assert(tbl->is_updatable() && !tbl->is_multiple_tables());
3386 }
3387 return tbl;
3388 }
3389
3391 return const_cast<Table_ref *>(
3392 static_cast<const Table_ref *>(this)->updatable_base_table());
3393 }
3394
3395 /**
3396 Mark that there is a NATURAL JOIN or JOIN ... USING between two tables.
3397
3398 This function marks that table b should be joined with a either via
3399 a NATURAL JOIN or via JOIN ... USING. Both join types are special
3400 cases of each other, so we treat them together. The function
3401 setup_conds() creates a list of equal condition between all fields
3402 of the same name for NATURAL JOIN or the fields in
3403 Table_ref::join_using_fields for JOIN ... USING.
3404 The list of equality conditions is stored
3405 either in b->join_cond(), or in JOIN::conds, depending on whether there
3406 was an outer join.
3407
3408 EXAMPLE
3409 @verbatim
3410 SELECT * FROM t1 NATURAL LEFT JOIN t2
3411 <=>
3412 SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
3413
3414 SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
3415 <=>
3416 SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)
3417
3418 SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
3419 <=>
3420 SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
3421 @endverbatim
3422
3423 @param b Right join argument.
3424 */
3426
3427 /**
3428 Set granted privileges for a table.
3429
3430 Can be used when generating temporary tables that are also used in
3431 resolver process, such as when generating a UNION table
3432
3433 @param privilege Privileges granted for this table.
3434 */
3435 void set_privileges(ulong privilege) { grant.privilege |= privilege; }
3436
3437 bool save_properties();
3438 void restore_properties();
3439
3440 /*
3441 List of tables local to a subquery or the top-level SELECT (used by
3442 SQL_I_List). Considers views as leaves (unlike 'next_leaf' below).
3443 Created at parse time in Query_block::add_table_to_list() ->
3444 table_list.link_in_list().
3445 */
3447 /* link in a global list of all queries tables */
3448 Table_ref *next_global{nullptr}, **prev_global{nullptr};
3449 const char *db{nullptr}, *table_name{nullptr}, *alias{nullptr};
3450 /*
3451 Target tablespace name: When creating or altering tables, this
3452 member points to the tablespace_name in the HA_CREATE_INFO struct.
3453 */
3455 char *option{nullptr}; /* Used by cache index */
3456
3457 /** Table level optimizer hints for this table. */
3459 /* Hints for query block of this table. */
3461
3462 void set_lock(const Lock_descriptor &descriptor) {
3463 m_lock_descriptor = descriptor;
3464 }
3465
3467
3469
3470 private:
3471 /**
3472 The members below must be kept aligned so that (1 << m_tableno) == m_map.
3473 A table that takes part in a join operation must be assigned a unique
3474 table number.
3475 */
3476 uint m_tableno{0}; ///< Table number within query block
3477 table_map m_map{0}; ///< Table map, derived from m_tableno
3478 /**
3479 If this table or join nest is the Y in "X [LEFT] JOIN Y ON C", this
3480 member points to C. May also be generated from JOIN ... USING clause.
3481 It may be modified only by permanent transformations (permanent = done
3482 once for all executions of a prepared statement).
3483 */
3486
3487 public:
3488 /*
3489 (Valid only for semi-join nests) Bitmap of tables that are within the
3490 semi-join (this is different from bitmap of all nest's children because
3491 tables that were pulled out of the semi-join nest remain listed as
3492 nest's children).
3493 */
3495
3496 /*
3497 During parsing - left operand of NATURAL/USING join where 'this' is
3498 the right operand. After parsing (this->natural_join == this) iff
3499 'this' represents a NATURAL or USING join operation. Thus after
3500 parsing 'this' is a NATURAL/USING join iff (natural_join != NULL).
3501 */
3503 /*
3504 True if 'this' represents a nested join that is a NATURAL JOIN.
3505 For one of the operands of 'this', the member 'natural_join' points
3506 to the other operand of 'this'.
3507 */
3508 bool is_natural_join{false};
3509 /* Field names in a USING clause for JOIN ... USING. */
3511 /*
3512 Explicitly store the result columns of either a NATURAL/USING join or
3513 an operand of such a join.
3514 */
3516 /* true if join_columns contains all columns of this table reference. */
3518
3519 /*
3520 List of nodes in a nested join tree, that should be considered as
3521 leaves with respect to name resolution. The leaves are: views,
3522 top-most nodes representing NATURAL/USING joins, subqueries, and
3523 base tables. All of these Table_ref instances contain a
3524 materialized list of columns. The list is local to a subquery.
3525 */
3527 /* Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */
3529 TABLE *table{nullptr}; /* opened table */
3530 Table_id table_id{}; /* table id (from binlog) for opened table */
3531 /*
3532 Query_result for derived table to pass it from table creation to table
3533 filling procedure
3534 */
3536 /*
3537 Reference from aux_tables to local list entry of main select of
3538 multi-delete statement:
3539 delete t1 from t2,t1 where t1.a<'B' and t2.b=t1.b;
3540 here it will be reference of first occurrence of t1 to second (as you
3541 can see this lists can't be merged)
3542 */
3544
3545 /*
3546 Holds the function used as the table function
3547 */
3549
3550 /**
3551 If we've previously made an access path for “derived”, it is cached here.
3552 This is useful if we need to plan the query block twice (the hypergraph
3553 optimizer can do so, with and without in2exists predicates), both saving
3554 work and avoiding issues when we try to throw away the old items_to_copy
3555 for a new (identical) one.
3556 */
3558
3559 private:
3560 /**
3561 This field is set to non-null for derived tables and views. It points
3562 to the Query_expression representing the derived table/view.
3563 E.g. for a query
3564 @verbatim SELECT * FROM (SELECT a FROM t1) b @endverbatim
3565 */
3566 Query_expression *derived{nullptr}; /* Query_expression of derived table */
3567
3568 /// If non-NULL, the CTE which this table is derived from.
3570 /**
3571 If the user has specified column names with the syntaxes "table name
3572 parenthesis column names":
3573 WITH qn(column names) AS (select...)
3574 or
3575 FROM (select...) dt(column names)
3576 or
3577 CREATE VIEW v(column_names) AS ...
3578 then this points to the list of column names. NULL otherwise.
3579 */
3581
3582 public:
3583 ST_SCHEMA_TABLE *schema_table{nullptr}; /* Information_schema table */
3585 /*
3586 True when the view field translation table is used to convert
3587 schema table fields for backwards compatibility with SHOW command.
3588 */
3590 /* link to query_block where this table was used */
3592
3593 private:
3594 LEX *view{nullptr}; /* link on VIEW lex for merging */
3595
3596 public:
3597 /// Array of selected expressions from a derived table or view.
3599
3600 /// pointer to element after last one in translation table above
3602 /*
3603 List (based on next_local) of underlying tables of this view. I.e. it
3604 does not include the tables of subqueries used in the view. Is set only
3605 for merged views.
3606 */
3608 /*
3609 - 0 for base tables
3610 - in case of the view it is the list of all (not only underlying
3611 tables but also used in subquery ones) tables of the view.
3612 */
3614 /* most upper view this table belongs to */
3616 /*
3617 The view directly referencing this table
3618 (non-zero only for merged underlying tables of a view).
3619 */
3621 /* Ptr to parent MERGE table list item. See top comment in ha_myisammrg.cc */
3623 /*
3624 Security context (non-zero only for tables which belong
3625 to view with SQL SECURITY DEFINER)
3626 */
3628 /*
3629 This view security context (non-zero only for views with
3630 SQL SECURITY DEFINER)
3631 */
3633 /*
3634 List of all base tables local to a subquery including all view
3635 tables. Unlike 'next_local', this in this list views are *not*
3636 leaves. Created in setup_tables() -> make_leaf_tables().
3637 */
3639 Item *derived_where_cond{nullptr}; ///< WHERE condition from derived table
3640 Item *check_option{nullptr}; ///< WITH CHECK OPTION condition
3641 Item *replace_filter{nullptr}; ///< Filter for REPLACE command
3642 LEX_STRING select_stmt{nullptr, 0}; ///< text of (CREATE/SELECT) statement
3643 LEX_STRING source{nullptr, 0}; ///< source of CREATE VIEW
3644 LEX_STRING timestamp{nullptr, 0}; ///< GMT time stamp of last operation
3645 LEX_USER definer; ///< definer of view
3646 /**
3647 @note: This field is currently not reliable when read from dictionary:
3648 If an underlying view is changed, updatable_view is not changed,
3649 due to lack of dependency checking in dictionary implementation.
3650 Prefer to use is_updatable() during preparation and optimization.
3651 */
3652 ulonglong updatable_view{0}; ///< VIEW can be updated
3653 /**
3654 @brief The declared algorithm, if this is a view.
3655 @details One of
3656 - VIEW_ALGORITHM_UNDEFINED
3657 - VIEW_ALGORITHM_TEMPTABLE
3658 - VIEW_ALGORITHM_MERGE
3659 @todo Replace with an enum
3660 */
3662 ulonglong view_suid{0}; ///< view is suid (true by default)
3663 ulonglong with_check{0}; ///< WITH CHECK OPTION
3664
3665 private:
3666 /// The view algorithm that is actually used, if this is a view.
3669
3670 public:
3672
3673 public:
3674 /// True if right argument of LEFT JOIN; false in other cases (i.e. if left
3675 /// argument of LEFT JOIN, if argument of INNER JOIN; RIGHT JOINs are
3676 /// converted to LEFT JOIN during contextualization).
3677 bool outer_join{false};
3678 /// True if was originally the left argument of a RIGHT JOIN, before we
3679 /// made it the right argument of a LEFT JOIN.
3681 uint shared{0}; /* Used in multi-upd */
3682 size_t db_length{0};
3684
3685 private:
3686 /// True if VIEW/TABLE is updatable, based on analysis of query (SQL rules).
3687 bool m_updatable{false};
3688 /// True if VIEW/TABLE is insertable, based on analysis of query (SQL rules).
3689 bool m_insertable{false};
3690 /// True if table is target of UPDATE statement, or updated in IODKU stmt.
3691 bool m_updated{false};
3692 /// True if table is target of INSERT statement.
3693 bool m_inserted{false};
3694 /// True if table is target of DELETE statement, or deleted in REPLACE stmt.
3695 bool m_deleted{false};
3696 bool m_fulltext_searched{false}; ///< True if fulltext searched
3697 public:
3698 bool straight{false}; /* optimize with prev table */
3699 /**
3700 True for tables and views being changed in a data change statement.
3701 Also true for tables subject to a SELECT ... FOR UPDATE.
3702 Also used by replication to filter out statements that can be ignored,
3703 especially important for multi-table UPDATE and DELETE.
3704 */
3705 bool updating{false};
3706 /// preload only non-leaf nodes (IS THIS USED???)
3707 bool ignore_leaves{false};
3708 /**
3709 The set of tables in the query block that this table depends on.
3710 Can be set due to outer join, join order hints or NOT EXISTS relationship.
3711 */
3713 /// The outer tables that an outer join's join condition depends on
3715 /**
3716 Is non-NULL if this table reference is a nested join, ie it represents
3717 the inner tables of an outer join, the tables contained in the
3718 parentheses of an inner join (eliminated during resolving), the tables
3719 referenced in a derived table or view, in a semi-join nest, the tables
3720 from the subquery.
3721 */
3723 /// The nested join containing this table reference.
3725 /// The join list immediately containing this table reference
3727 /// stop PS caching
3728 bool cacheable_table{false};
3729 /**
3730 Specifies which kind of table should be open for this element
3731 of table list.
3732 */
3734 /* true if this merged view contain auto_increment field */
3736 /// true <=> VIEW CHECK OPTION condition is processed (also for prep. stmts)
3738 /// true <=> Filter condition is processed
3740
3742 char timestamp_buffer[20]{0}; /* buffer for timestamp (19+1) */
3743 /*
3744 This Table_ref object is just placeholder for prelocking, it will be
3745 used for implicit LOCK TABLES only and won't be used in real statement.
3746 */
3748 /**
3749 Indicates that if Table_ref object corresponds to the table/view
3750 which requires special handling.
3751 */
3752 enum {
3753 /* Normal open. */
3755 /* Associate a table share only if the the table exists. */
3757 /*
3758 Associate a table share only if the the table exists.
3759 Also upgrade metadata lock to exclusive if table doesn't exist.
3760 */
3762 /* Don't associate a table share. */
3763 OPEN_STUB
3764 } open_strategy{OPEN_NORMAL};
3766 /** true if an alias for this table was specified in the SQL. */
3767 bool is_alias{false};
3768 /** true if the table is referred to in the statement using a fully
3769 qualified name (@<db_name@>.@<table_name@>).
3770 */
3771 bool is_fqtn{false};
3772 /**
3773 If true, this table is a derived (materialized) table which was created
3774 from a scalar subquery, cf.
3775 Query_block::transform_scalar_subqueries_to_join_with_derived
3776 */
3778
3779 /* View creation context. */
3780
3782
3783 /*
3784 Attributes to save/load view creation context in/from frm-file.
3785
3786 They are required only to be able to use existing parser to load
3787 view-definition file. As soon as the parser parsed the file, view
3788 creation context is initialized and the attributes become redundant.
3789
3790 These attributes MUST NOT be used for any purposes but the parsing.
3791 */
3792
3795
3796 /*
3797 View definition (SELECT-statement) in the UTF-form.
3798 */
3799
3801
3802 // True, If this is a system view
3803 bool is_system_view{false};
3804
3805 /*
3806 Set to 'true' if this is a DD table being opened in the context of a
3807 dictionary operation. Note that when 'false', this may still be a DD
3808 table when opened in a non-DD context, e.g. as part of an I_S view
3809 query.
3810 */
3811 bool is_dd_ctx_table{false};
3812
3813 /* End of view definition context. */
3814
3815 /* List of possible keys. Valid only for materialized derived tables/views. */
3817
3818 /**
3819 Indicates what triggers we need to pre-load for this Table_ref
3820 when opening an associated TABLE. This is filled after
3821 the parsed tree is created.
3822 */
3825
3827
3828 /// if true, EXPLAIN can't explain view due to insufficient rights.
3829 bool view_no_explain{false};
3830
3831 /* List to carry partition names from PARTITION (...) clause in statement */
3833
3834 /// Set table number
3836 assert(tableno < MAX_TABLES);
3838 m_map = (table_map)1 << tableno;
3839 }
3840 /// Return table number
3841 uint tableno() const { return m_tableno; }
3842
3843 /// Return table map derived from table number
3844 table_map map() const {
3845 assert(((table_map)1 << m_tableno) == m_map);
3846 return m_map;
3847 }
3848
3849 /// If non-NULL, the CTE which this table is derived from.
3852 /// @see m_derived_column_names
3855 }
3858 }
3859
3860 private:
3861 /*
3862 A group of members set and used only during JOIN::optimize().
3863 */
3864 /**
3865 Optimized copy of m_join_cond (valid for one single
3866 execution). Initialized by Query_block::get_optimizable_conditions().
3867 */
3869
3870 public:
3871 COND_EQUAL *cond_equal{nullptr}; ///< Used with outer join
3872 /// true <=> this table is a const one and was optimized away.
3873
3874 bool optimized_away{false};
3875 /**
3876 true <=> all possible keys for a derived table were collected and
3877 could be re-used while statement re-execution.
3878 */
3879
3881
3882 private:
3883 /// If a recursive reference inside the definition of a CTE.
3885 // End of group for optimization
3886
3887 /** See comments for set_metadata_id() */
3889 /** See comments for TABLE_SHARE::get_table_ref_version() */
3891
3892 /*
3893 All members whose names are suffixed with "_saved" are duplicated in
3894 class TABLE but actually belong in this class. They are saved from class
3895 TABLE when preparing a statement and restored when executing the statement.
3896 They are not required for a regular (non-prepared) statement.
3897 */
3903 bool nullable_saved{false};
3912};
3913
3914/*
3915 Iterator over the fields of a generic table reference.
3916*/
3917
3919 public:
3920 virtual ~Field_iterator() = default;
3921 virtual void set(Table_ref *) = 0;
3922 virtual void next() = 0;
3923 virtual bool end_of_fields() = 0; /* Return 1 at end of list */
3924 virtual const char *name() = 0;
3925 virtual Item *create_item(THD *) = 0;
3926 virtual Field *field() = 0;
3927};
3928
3929/*
3930 Iterator over the fields of a base table, view with temporary
3931 table, or subquery.
3932*/
3933
3936
3937 public:
3939 void set(Table_ref *table) override { ptr = table->table->field; }
3940 void set_table(TABLE *table) { ptr = table->field; }
3941 void next() override { ptr++; }
3942 bool end_of_fields() override { return *ptr == nullptr; }
3943 const char *name() override;
3944 Item *create_item(THD *thd) override;
3945 Field *field() override { return *ptr; }
3946};
3947
3948/**
3949 Iterator over the fields of a merged derived table or view.
3950*/
3951
3955
3956 public:
3958 void set(Table_ref *table) override;
3959 void next() override { ptr++; }
3960 bool end_of_fields() override { return ptr == array_end; }
3961 const char *name() override;
3962 Item *create_item(THD *thd) override;
3963 Item **item_ptr() { return &ptr->item; }
3964 Field *field() override { return nullptr; }
3965 inline Item *item() { return ptr->item; }
3967};
3968
3969/*
3970 Field_iterator interface to the list of materialized fields of a
3971 NATURAL/USING join.
3972*/
3973
3977
3978 public:
3980 ~Field_iterator_natural_join() override = default;
3981 void set(Table_ref *table) override;
3982 void next() override;
3983 bool end_of_fields() override { return !cur_column_ref; }
3984 const char *name() override { return cur_column_ref->name(); }
3985 Item *create_item(THD *thd) override {
3986 return cur_column_ref->create_item(thd);
3987 }
3988 Field *field() override { return cur_column_ref->field(); }
3990};
3991
3992/**
3993 Generic iterator over the fields of an arbitrary table reference.
3994
3995 This class unifies the various ways of iterating over the columns
3996 of a table reference depending on the type of SQL entity it
3997 represents. If such an entity represents a nested table reference,
3998 this iterator encapsulates the iteration over the columns of the
3999 members of the table reference.
4000
4001 The implementation assumes that all underlying NATURAL/USING table
4002 references already contain their result columns and are linked into
4003 the list Table_ref::next_name_resolution_table.
4004*/
4005
4012 void set_field_iterator();
4013
4014 public:
4016 void set(Table_ref *table) override;
4017 void next() override;
4018 bool end_of_fields() override {
4019 return (table_ref == last_leaf && field_it->end_of_fields());
4020 }
4021 const char *name() override { return field_it->name(); }
4022 const char *get_table_name();
4023 const char *get_db_name();
4024 GRANT_INFO *grant();
4025 Item *create_item(THD *thd) override { return field_it->create_item(thd); }
4026 Field *field() override { return field_it->field(); }
4028 Table_ref *parent_table_ref);
4030};
4031
4034 char *db, *table;
4036};
4037
4039 MY_BITMAP *bitmap) {
4040 my_bitmap_map *old = bitmap->bitmap;
4041 bitmap->bitmap = table->s->all_set.bitmap; // does not repoint last_word_ptr
4042 return old;
4043}
4044
4045static inline void tmp_restore_column_map(MY_BITMAP *bitmap,
4046 my_bitmap_map *old) {
4047 bitmap->bitmap = old;
4048}
4049
4050/* The following is only needed for debugging */
4051
4053 [[maybe_unused]],
4054 MY_BITMAP *bitmap
4055 [[maybe_unused]]) {
4056#ifndef NDEBUG
4057 return tmp_use_all_columns(table, bitmap);
4058#else
4059 return nullptr;
4060#endif
4061}
4062
4063static inline void dbug_tmp_restore_column_map(MY_BITMAP *bitmap
4064 [[maybe_unused]],
4065 my_bitmap_map *old
4066 [[maybe_unused]]) {
4067#ifndef NDEBUG
4068 tmp_restore_column_map(bitmap, old);
4069#endif
4070}
4071
4072/*
4073 Variant of the above : handle both read and write sets.
4074 Provide for the possibility of the read set being the same as the write set
4075*/
4076static inline void dbug_tmp_use_all_columns(
4077 TABLE *table [[maybe_unused]], my_bitmap_map **save [[maybe_unused]],
4078 MY_BITMAP *read_set [[maybe_unused]],
4079 MY_BITMAP *write_set [[maybe_unused]]) {
4080#ifndef NDEBUG
4081 save[0] = read_set->bitmap;
4082 save[1] = write_set->bitmap;
4083 (void)tmp_use_all_columns(table, read_set);
4084 (void)tmp_use_all_columns(table, write_set);
4085#endif
4086}
4087
4089 MY_BITMAP *read_set [[maybe_unused]], MY_BITMAP *write_set [[maybe_unused]],
4090 my_bitmap_map **old [[maybe_unused]]) {
4091#ifndef NDEBUG
4092 tmp_restore_column_map(read_set, old[0]);
4093 tmp_restore_column_map(write_set, old[1]);
4094#endif
4095}
4096
4097void init_mdl_requests(Table_ref *table_list);
4098
4099/**
4100 Unpacks the definition of a value generator in all its forms: generated
4101 column, default expression or checked constraint.
4102 The function parses the text definition of this expression, resolves its
4103 items and runs validation and calculates the base_columns_map which is used
4104 for tracking the columns the expression depends on.
4105
4106 @param[in] thd Thread handler
4107 @param[in] table Table having the value generator to be unpacked
4108 @param[in,out] val_generator Contains the expression in string format, and,
4109 if successful will be replaced by the parser
4110 with a new one having the unpacked expression.
4111 @param[in] source Source of value generator(a generated column,
4112 a regular column with generated default value or
4113 a check constraint).
4114 @param[in] source_name Name of the source (generated column, a regular
4115 column with generated default value or a check
4116 constraint).
4117 @param[in] field The column the value generator depends on. Can
4118 be null for checked constraints which do not
4119 depend on a single column.
4120 @param[in] is_create_table Indicates that table is opened as part
4121 of CREATE or ALTER and does not yet exist in SE
4122 @param[out] error_reported updated flag for the caller that no other error
4123 messages are to be generated.
4124
4125 @retval true Failure.
4126 @retval false Success.
4127*/
4128
4129bool unpack_value_generator(THD *thd, TABLE *table,
4130 Value_generator **val_generator,
4132 const char *source_name, Field *field,
4133 bool is_create_table, bool *error_reported);
4134
4135/**
4136 Unpack the partition expression. Parse the partition expression
4137 to produce an Item.
4138
4139 @param[in] thd Thread handler
4140 @param[in] outparam Table object
4141 @param[in] share TABLE_SHARE object
4142 @param[in] engine_type Engine type of the partitions.
4143 @param[in] is_create_table Indicates that table is opened as part of
4144 CREATE or ALTER and does not yet exist in SE
4145
4146 @retval true Failure.
4147 @retval false Success.
4148*/
4149
4150bool unpack_partition_info(THD *thd, TABLE *outparam, TABLE_SHARE *share,
4151 handlerton *engine_type, bool is_create_table);
4152
4153int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias,
4154 uint db_stat, uint prgflag, uint ha_open_flags,
4155 TABLE *outparam, bool is_create_table,
4156 const dd::Table *table_def_param);
4157TABLE_SHARE *alloc_table_share(const char *db, const char *table_name,
4158 const char *key, size_t key_length,
4159 bool open_secondary);
4160void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
4161 size_t key_length, const char *table_name,
4162 const char *path, MEM_ROOT *mem_root);
4163void free_table_share(TABLE_SHARE *share);
4165Ident_name_check check_db_name(const char *name, size_t length);
4167 bool preserve_lettercase);
4168bool check_column_name(const char *name);
4169Ident_name_check check_table_name(const char *name, size_t length);
4170int rename_file_ext(const char *from, const char *to, const char *ext);
4171char *get_field(MEM_ROOT *mem, Field *field);
4172bool get_field(MEM_ROOT *mem, Field *field, class String *res);
4173
4174int closefrm(TABLE *table, bool free_share);
4175void free_blobs(TABLE *table);
4176void free_blob_buffers_and_reset(TABLE *table, uint32 size);
4177int set_zone(int nr, int min_zone, int max_zone);
4178void append_unescaped(String *res, const char *pos, size_t length);
4179char *fn_rext(char *name);
4181 const LEX_CSTRING &name);
4182
4183/* performance schema */
4185
4188
4189/* information schema */
4191
4192/* mysql schema name and DD ID */
4194static const uint MYSQL_SCHEMA_DD_ID = 1;
4195
4196/* mysql tablespace name and DD ID */
4199
4200/* replication's tables */
4204
4205inline bool is_infoschema_db(const char *name, size_t len) {
4206 return (
4209}
4210
4211inline bool is_infoschema_db(const char *name) {
4213}
4214
4215inline bool is_perfschema_db(const char *name, size_t len) {
4216 return (PERFORMANCE_SCHEMA_DB_NAME.length == len &&
4218 name));
4219}
4220
4221inline bool is_perfschema_db(const char *name) {
4223 name);
4224}
4225
4226/**
4227 Check if the table belongs to the P_S, excluding setup and threads tables.
4228
4229 @note Performance Schema tables must be accessible independently of the
4230 LOCK TABLE mode. This function is needed to handle the special case
4231 of P_S tables being used under LOCK TABLE mode.
4232*/
4233inline bool belongs_to_p_s(Table_ref *tl) {
4234 return (!strcmp("performance_schema", tl->db) &&
4235 strcmp(tl->table_name, "threads") &&
4236 strstr(tl->table_name, "setup_") == nullptr);
4237}
4238
4239/**
4240 return true if the table was created explicitly.
4241*/
4242inline bool is_user_table(TABLE *table) {
4243 const char *name = table->s->table_name.str;
4245}
4246
4247bool is_simple_order(ORDER *order);
4248
4249uint add_pk_parts_to_sk(KEY *sk, uint sk_n, KEY *pk, uint pk_n,
4250 TABLE_SHARE *share, handler *handler_file,
4251 uint *usable_parts, bool use_extended_sk);
4252void setup_key_part_field(TABLE_SHARE *share, handler *handler_file,
4253 uint primary_key_n, KEY *keyinfo, uint key_n,
4254 uint key_part_n, uint *usable_parts,
4255 bool part_of_key_not_extended);
4256
4257const uchar *get_field_name(const uchar *arg, size_t *length);
4258
4259void repoint_field_to_record(TABLE *table, uchar *old_rec, uchar *new_rec);
4260bool update_generated_write_fields(const MY_BITMAP *bitmap, TABLE *table);
4262 uint active_index = MAX_KEY);
4263
4264/**
4265 Check if a Table_ref instance represents a pre-opened temporary table.
4266*/
4267
4268inline bool is_temporary_table(const Table_ref *tl) {
4269 if (tl->is_view() || tl->schema_table) return false;
4270
4271 if (!tl->table) return false;
4272
4273 /*
4274 NOTE: 'table->s' might be NULL for specially constructed TABLE
4275 instances. See SHOW TRIGGERS for example.
4276 */
4277
4278 if (!tl->table->s) return false;
4279
4280 return tl->table->s->tmp_table != NO_TMP_TABLE;
4281}
4282
4283/**
4284 After parsing, a Common Table Expression is accessed through a
4285 Table_ref. This class contains all information about the CTE which the
4286 Table_ref needs.
4287
4288 @note that before and during parsing, the CTE is described by a
4289 PT_common_table_expr.
4290*/
4292 public:
4295 TABLE *clone_tmp_table(THD *thd, Table_ref *tl);
4297 /// Remove one table reference.
4298 void remove_table(Table_ref *tr);
4299 /// Empties the materialized CTE and informs all of its clones.
4300 bool clear_all_references();
4301 /**
4302 All references to this CTE in the statement, except those inside the
4303 query expression defining this CTE.
4304 In other words, all non-recursive references.
4305 */
4307 /// True if it's a recursive CTE
4309 /**
4310 List of all TABLE_LISTSs reading/writing to the tmp table created to
4311 materialize this CTE. Due to shared materialization, only the first one
4312 has a TABLE generated by create_tmp_table(); other ones have a TABLE
4313 generated by open_table_from_share().
4314 */
4316 /// Name of the WITH block. Used only for EXPLAIN FORMAT=tree.
4318};
4319
4320/**
4321 This iterates on those references to a derived table / view / CTE which are
4322 materialized. If a recursive CTE, this includes recursive references.
4323 Upon construction it is passed a non-recursive materialized reference
4324 to the derived table (Table_ref*).
4325 For a CTE it may return more than one reference; for a derived table or a
4326 view, there is only one (as references to a same view are treated as
4327 independent objects).
4328 References are returned as TABLE*.
4329*/
4331 Table_ref *const start; ///< The reference provided in construction.
4332 size_t ref_idx{0}; ///< Current index in cte->tmp_tables
4333 bool m_is_first{true}; ///< True when at first reference in list
4334 public:
4335 explicit Derived_refs_iterator(Table_ref *start_arg) : start(start_arg) {}
4338 m_is_first = ref_idx == 0;
4339 // Derived tables and views have a single reference.
4340 if (cte == nullptr) {
4341 return ref_idx++ == 0 ? start->table : nullptr;
4342 }
4343 /*
4344 CTEs may have multiple references. Return the next one, but notice that
4345 some references may have been deleted.
4346 */
4347 while (ref_idx < cte->tmp_tables.size()) {
4348 TABLE *table = cte->tmp_tables[ref_idx++]->table;
4349 if (table != nullptr) return table;
4350 }
4351 return nullptr;
4352 }
4353 void rewind() {
4354 ref_idx = 0;
4355 m_is_first = true;
4356 }
4357 /// @returns true if the last get_next() returned the first element.
4358 bool is_first() const {
4359 // Call after get_next() has been called:
4360 assert(ref_idx > 0);
4361 return m_is_first;
4362 }
4363};
4364
4365/**
4366 RAII class to reset TABLE::autoinc_field_has_explicit_non_null_value after
4367 processing individual row in INSERT or LOAD DATA statements.
4368*/
4370 public:
4372 : m_table(table) {}
4375 }
4376
4377 private:
4379};
4380
4381// Whether we can ask the storage engine for the row ID of the last row read.
4382//
4383// Some operations needs a row ID to operate correctly (i.e. weedout). Normally,
4384// the row ID is provided by the storage engine by calling handler::position().
4385// But there are cases when position() should not be called:
4386//
4387// 1. If we have a const table (rows are fetched during optimization), we
4388// should not call position().
4389// 2. If we have a NULL-complemented row, calling position() would give a
4390// random row ID back, as there has not been any row read.
4391//
4392// Operations that needs the row ID must also check the value of
4393// QEP_TAB::rowid_status to see whether they actually need a row ID.
4394// See QEP_TAB::rowid_status for more details.
4395inline bool can_call_position(const TABLE *table) {
4396 return !table->const_table && !(table->is_nullable() && table->null_row);
4397}
4398
4399//////////////////////////////////////////////////////////////////////////
4400
4401/*
4402 NOTE:
4403 These structures are added to read .frm file in upgrade scenario.
4404
4405 They should not be used any where else in the code.
4406 They will be removed in future release.
4407 Any new code should not be added in this section.
4408*/
4409
4410/**
4411 These members were removed from TABLE_SHARE as they are not used in
4412 in the code. open_binary_frm() uses these members while reading
4413 .frm files.
4414*/
4416 public:
4419 null_field_first(false),
4420 stored_fields(0),
4422 frm_version(0),
4423 fieldnames() {}
4424
4427 uint stored_fields; /* Number of stored fields
4428 (i.e. without generated-only ones) */
4429
4430 enum utype {
4443 EMPTY_VAL, // EMPTY_VAL rather than EMPTY since EMPTY can conflict with
4444 // system headers.
4456 GENERATED_FIELD = 128
4458
4459 /**
4460 For shares representing views File_parser object with view
4461 definition read from .FRM file.
4462 */
4465 TYPELIB fieldnames; /* Pointer to fieldnames */
4466};
4467
4468/**
4469 Create TABLE_SHARE from .frm file.
4470
4471 FRM_context object is used to store the value removed from
4472 TABLE_SHARE. These values are used only for .frm file parsing.
4473
4474 @param[in] thd Thread handle.
4475 @param[in] path Path of the frm file.
4476 @param[out] share TABLE_SHARE to be populated.
4477 @param[out] frm_context FRM_context object.
4478 @param[in] db Database name.
4479 @param[in] table Table name.
4480 @param[in] is_fix_view_cols_and_deps Fix view column data, table
4481 and routine dependency.
4482
4483 @retval 0 ON SUCCESS
4484 @retval -1 ON FAILURE
4485 @retval -2 ON LESS SEVER FAILURE (see read_frm_file)
4486*/
4487int create_table_share_for_upgrade(THD *thd, const char *path,
4488 TABLE_SHARE *share, FRM_context *frm_context,
4489 const char *db, const char *table,
4490 bool is_fix_view_cols_and_deps);
4491//////////////////////////////////////////////////////////////////////////
4492
4493/**
4494 Create a copy of the key_info from TABLE_SHARE object to TABLE object.
4495
4496 Wherever prefix key is present, allocate a new Field object, having its
4497 field_length set to the prefix key length, and point the table's matching
4498 key_part->field to this new Field object.
4499
4500 This ensures that unpack_partition_info() reads the correct prefix length of
4501 partitioned fields
4502
4503 @param table Table for which key_info is to be allocated
4504 @param root MEM_ROOT in which to allocate key_info
4505
4506 @retval false Success
4507 @retval true Failed to allocate memory for table.key_info in root
4508*/
4509
4511
4512#endif /* TABLE_INCLUDED */
int64 query_id_t
Definition: binlog.h:70
Per internal schema ACL access rules.
Definition: auth_common.h:143
Per internal table ACL access rules.
Definition: auth_common.h:105
RAII class to reset TABLE::autoinc_field_has_explicit_non_null_value after processing individual row ...
Definition: table.h:4369
Autoinc_field_has_explicit_non_null_value_reset_guard(TABLE *table)
Definition: table.h:4371
~Autoinc_field_has_explicit_non_null_value_reset_guard()
Definition: table.h:4373
Class that represents a single change to a column value in partial update of a JSON column.
Definition: table.h:1312
const char * old_data(const Field *field) const
Get a pointer to the start of the old data to be replaced.
Definition: table.cc:7653
size_t length() const
Definition: table.h:1333
size_t m_length
The size of the portion that is to be replaced.
Definition: table.h:1317
const char * new_data(const Field *field) const
Get a pointer to the start of the replacement data.
Definition: table.cc:7644
Binary_diff(size_t offset, size_t length)
Create a new Binary_diff object.
Definition: table.h:1326
size_t m_offset
The offset of the start of the change.
Definition: table.h:1314
size_t offset() const
Definition: table.h:1330
Definition: sql_bitmap.h:137
Class is used as a BLOB field value storage for intermediate GROUP_CONCAT results.
Definition: table.h:1272
bool truncated_value
Sign that some values were cut during saving into the storage.
Definition: table.h:1279
Blob_mem_storage()
Definition: table.cc:4056
void reset()
Definition: table.h:1285
void set_truncated_value(bool is_truncated_value)
Definition: table.h:1302
MEM_ROOT storage
Definition: table.h:1274
~Blob_mem_storage()
Definition: table.cc:4060
bool is_truncated_value() const
Definition: table.h:1305
char * store(const char *from, size_t length)
Function creates duplicate of 'from' string in 'storage' MEM_ROOT.
Definition: table.h:1299
Definition: item_cmpfunc.h:2700
After parsing, a Common Table Expression is accessed through a Table_ref.
Definition: table.h:4291
Common_table_expr(MEM_ROOT *mem_root)
Definition: table.h:4293
LEX_STRING name
Name of the WITH block. Used only for EXPLAIN FORMAT=tree.
Definition: table.h:4317
TABLE * clone_tmp_table(THD *thd, Table_ref *tl)
Produces, from the first tmp TABLE object, a clone TABLE object for Table_ref 'tl',...
Definition: sql_derived.cc:169
bool clear_all_references()
Empties the materialized CTE and informs all of its clones.
Definition: sql_union.cc:1585
bool recursive
True if it's a recursive CTE.
Definition: table.h:4308
Mem_root_array< Table_ref * > references
All references to this CTE in the statement, except those inside the query expression defining this C...
Definition: table.h:4306
void remove_table(Table_ref *tr)
Remove one table reference.
Definition: sql_derived.cc:245
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:232
Mem_root_array< Table_ref * > tmp_tables
List of all TABLE_LISTSs reading/writing to the tmp table created to materialize this CTE.
Definition: table.h:4315
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:219
const CHARSET_INFO * get_client_cs()
Definition: table.h:221
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:223
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:257
const CHARSET_INFO * m_client_cs
client_cs stores the value of character_set_client session variable.
Definition: table.h:247
This structure is used to keep info about possible key for the result table of a derived table/view.
Definition: table.h:2713
table_map referenced_by
Definition: table.h:2715
Field_map used_fields
Definition: table.h:2716
uint key_part_count
Definition: table.h:2717
This iterates on those references to a derived table / view / CTE which are materialized.
Definition: table.h:4330
bool is_first() const
Definition: table.h:4358
TABLE * get_next()
Definition: table.h:4336
Table_ref *const start
The reference provided in construction.
Definition: table.h:4331
Derived_refs_iterator(Table_ref *start_arg)
Definition: table.h:4335
bool m_is_first
True when at first reference in list.
Definition: table.h:4333
size_t ref_idx
Current index in cte->tmp_tables.
Definition: table.h:4332
void rewind()
Definition: table.h:4353
These members were removed from TABLE_SHARE as they are not used in in the code.
Definition: table.h:4415
utype
Definition: table.h:4430
@ CASEUP
Definition: table.h:4435
@ NO
Definition: table.h:4440
@ NONE
Definition: table.h:4431
@ REL
Definition: table.h:4441
@ NEXT_NUMBER
Definition: table.h:4447
@ DATE
Definition: table.h:4432
@ PNR
Definition: table.h:4436
@ BIT_FIELD
Definition: table.h:4449
@ TIMESTAMP_OLD_FIELD
Definition: table.h:4450
@ GENERATED_FIELD
Definition: table.h:4456
@ INTERVAL_FIELD
Definition: table.h:4448
@ TIMESTAMP_UN_FIELD
Definition: table.h:4454
@ NOEMPTY
Definition: table.h:4434
@ CHECK
Definition: table.h:4442
@ YES
Definition: table.h:4439
@ TIMESTAMP_DNUN_FIELD
Definition: table.h:4455
@ BLOB_FIELD
Definition: table.h:4452
@ UNKNOWN_FIELD
Definition: table.h:4445
@ CASEDN
Definition: table.h:4446
@ TIMESTAMP_DN_FIELD
Definition: table.h:4453
@ PGNR
Definition: table.h:4438
@ EMPTY_VAL
Definition: table.h:4443
@ CAPITALIZE
Definition: table.h:4451
@ SHIELD
Definition: table.h:4433
@ BGNR
Definition: table.h:4437
bool null_field_first
Definition: table.h:4426
uchar frm_version
Definition: table.h:4464
handlerton * default_part_db_type
Definition: table.h:4425
TYPELIB fieldnames
Definition: table.h:4465