1 #ifndef TABLE_INCLUDED
2 #define TABLE_INCLUDED
3 /* Copyright (c) 2000, 2017, Oracle and/or its affiliates.
4 Copyright (c) 2009, 2021, MariaDB
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 as published by
8 the Free Software Foundation; version 2 of the License.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */
18
19 #include "sql_plist.h"
20 #include "sql_list.h" /* Sql_alloc */
21 #include "mdl.h"
22 #include "datadict.h"
23 #include "sql_string.h" /* String */
24 #include "lex_string.h"
25
26 #ifndef MYSQL_CLIENT
27
28 #include "my_cpu.h" /* LF_BACKOFF() */
29 #include "hash.h" /* HASH */
30 #include "handler.h" /* row_type, ha_choice, handler */
31 #include "mysql_com.h" /* enum_field_types */
32 #include "thr_lock.h" /* thr_lock_type */
33 #include "filesort_utils.h"
34 #include "parse_file.h"
35
36 /* Structs that defines the TABLE */
37
38 class Item; /* Needed by ORDER */
39 typedef Item (*Item_ptr);
40 class Item_subselect;
41 class Item_field;
42 class GRANT_TABLE;
43 class st_select_lex_unit;
44 class st_select_lex;
45 class partition_info;
46 class COND_EQUAL;
47 class Security_context;
48 struct TABLE_LIST;
49 class ACL_internal_schema_access;
50 class ACL_internal_table_access;
51 class Field;
52 class Table_statistics;
53 class With_element;
54 struct TDC_element;
55 class Virtual_column_info;
56 class Table_triggers_list;
57 class TMP_TABLE_PARAM;
58 class SEQUENCE;
59 class Range_rowid_filter_cost_info;
60 class derived_handler;
61 class Pushdown_derived;
62 struct Name_resolution_context;
63
64 /*
65 Used to identify NESTED_JOIN structures within a join (applicable only to
66 structures that have not been simplified away and embed more the one
67 element)
68 */
69 typedef ulonglong nested_join_map;
70
71
72 #define tmp_file_prefix "#sql" /**< Prefix for tmp tables */
73 #define tmp_file_prefix_length 4
74 #define TMP_TABLE_KEY_EXTRA 8
75
76 /**
77 Enumerate possible types of a table from re-execution
78 standpoint.
79 TABLE_LIST class has a member of this type.
80 At prepared statement prepare, this member is assigned a value
81 as of the current state of the database. Before (re-)execution
82 of a prepared statement, we check that the value recorded at
83 prepare matches the type of the object we obtained from the
84 table definition cache.
85
86 @sa check_and_update_table_version()
87 @sa Execute_observer
88 @sa Prepared_statement::reprepare()
89 */
90
91 enum enum_table_ref_type
92 {
93 /** Initial value set by the parser */
94 TABLE_REF_NULL= 0,
95 TABLE_REF_VIEW,
96 TABLE_REF_BASE_TABLE,
97 TABLE_REF_I_S_TABLE,
98 TABLE_REF_TMP_TABLE
99 };
100
101
102 /*************************************************************************/
103
104 /**
105 Object_creation_ctx -- interface for creation context of database objects
106 (views, stored routines, events, triggers). Creation context -- is a set
107 of attributes, that should be fixed at the creation time and then be used
108 each time the object is parsed or executed.
109 */
110
111 class Object_creation_ctx
112 {
113 public:
114 Object_creation_ctx *set_n_backup(THD *thd);
115
116 void restore_env(THD *thd, Object_creation_ctx *backup_ctx);
117
118 protected:
Object_creation_ctx()119 Object_creation_ctx() {}
120 virtual Object_creation_ctx *create_backup_ctx(THD *thd) const = 0;
121
122 virtual void change_env(THD *thd) const = 0;
123
124 public:
~Object_creation_ctx()125 virtual ~Object_creation_ctx()
126 { }
127 };
128
129 /*************************************************************************/
130
131 /**
132 Default_object_creation_ctx -- default implementation of
133 Object_creation_ctx.
134 */
135
136 class Default_object_creation_ctx : public Object_creation_ctx
137 {
138 public:
get_client_cs()139 CHARSET_INFO *get_client_cs()
140 {
141 return m_client_cs;
142 }
143
get_connection_cl()144 CHARSET_INFO *get_connection_cl()
145 {
146 return m_connection_cl;
147 }
148
149 protected:
150 Default_object_creation_ctx(THD *thd);
151
152 Default_object_creation_ctx(CHARSET_INFO *client_cs,
153 CHARSET_INFO *connection_cl);
154
155 protected:
156 virtual Object_creation_ctx *create_backup_ctx(THD *thd) const;
157
158 virtual void change_env(THD *thd) const;
159
160 protected:
161 /**
162 client_cs stores the value of character_set_client session variable.
163 The only character set attribute is used.
164
165 Client character set is included into query context, because we save
166 query in the original character set, which is client character set. So,
167 in order to parse the query properly we have to switch client character
168 set on parsing.
169 */
170 CHARSET_INFO *m_client_cs;
171
172 /**
173 connection_cl stores the value of collation_connection session
174 variable. Both character set and collation attributes are used.
175
176 Connection collation is included into query context, becase it defines
177 the character set and collation of text literals in internal
178 representation of query (item-objects).
179 */
180 CHARSET_INFO *m_connection_cl;
181 };
182
183 class Query_arena;
184
185 /*************************************************************************/
186
187 /**
188 View_creation_ctx -- creation context of view objects.
189 */
190
191 class View_creation_ctx : public Default_object_creation_ctx,
192 public Sql_alloc
193 {
194 public:
195 static View_creation_ctx *create(THD *thd);
196
197 static View_creation_ctx *create(THD *thd,
198 TABLE_LIST *view);
199
200 private:
View_creation_ctx(THD * thd)201 View_creation_ctx(THD *thd)
202 : Default_object_creation_ctx(thd)
203 { }
204 };
205
206 /*************************************************************************/
207
208 /* Order clause list element */
209
210 typedef int (*fast_field_copier)(Field *to, Field *from);
211
212
213 typedef struct st_order {
214 struct st_order *next;
215 Item **item; /* Point at item in select fields */
216 Item *item_ptr; /* Storage for initial item */
217 /*
218 Reference to the function we are trying to optimize copy to
219 a temporary table
220 */
221 fast_field_copier fast_field_copier_func;
222 /* Field for which above optimizer function setup */
223 Field *fast_field_copier_setup;
224 int counter; /* position in SELECT list, correct
225 only if counter_used is true*/
226 enum enum_order {
227 ORDER_NOT_RELEVANT,
228 ORDER_ASC,
229 ORDER_DESC
230 };
231
232 enum_order direction; /* Requested direction of ordering */
233 bool in_field_list; /* true if in select field list */
234 bool counter_used; /* parameter was counter of columns */
235 Field *field; /* If tmp-table group */
236 char *buff; /* If tmp-table group */
237 table_map used; /* NOTE: the below is only set to 0 but is still used by eq_ref_table */
238 table_map depend_map;
239 } ORDER;
240
241 /**
242 State information for internal tables grants.
243 This structure is part of the TABLE_LIST, and is updated
244 during the ACL check process.
245 @sa GRANT_INFO
246 */
247 struct st_grant_internal_info
248 {
249 /** True if the internal lookup by schema name was done. */
250 bool m_schema_lookup_done;
251 /** Cached internal schema access. */
252 const ACL_internal_schema_access *m_schema_access;
253 /** True if the internal lookup by table name was done. */
254 bool m_table_lookup_done;
255 /** Cached internal table access. */
256 const ACL_internal_table_access *m_table_access;
257 };
258 typedef struct st_grant_internal_info GRANT_INTERNAL_INFO;
259
260 /**
261 @brief The current state of the privilege checking process for the current
262 user, SQL statement and SQL object.
263
264 @details The privilege checking process is divided into phases depending on
265 the level of the privilege to be checked and the type of object to be
266 accessed. Due to the mentioned scattering of privilege checking
267 functionality, it is necessary to keep track of the state of the
268 process. This information is stored in privilege, want_privilege, and
269 orig_want_privilege.
270
271 A GRANT_INFO also serves as a cache of the privilege hash tables. Relevant
272 members are grant_table and version.
273 */
274 typedef struct st_grant_info
275 {
276 /**
277 @brief A copy of the privilege information regarding the current host,
278 database, object and user.
279
280 @details The version of this copy is found in GRANT_INFO::version.
281 */
282 GRANT_TABLE *grant_table_user;
283 GRANT_TABLE *grant_table_role;
284 /**
285 @brief Used for cache invalidation when caching privilege information.
286
287 @details The privilege information is stored on disk, with dedicated
288 caches residing in memory: table-level and column-level privileges,
289 respectively, have their own dedicated caches.
290
291 The GRANT_INFO works as a level 1 cache with this member updated to the
292 current value of the global variable @c grant_version (@c static variable
293 in sql_acl.cc). It is updated Whenever the GRANT_INFO is refreshed from
294 the level 2 cache. The level 2 cache is the @c column_priv_hash structure
295 (@c static variable in sql_acl.cc)
296
297 @see grant_version
298 */
299 uint version;
300 /**
301 @brief The set of privileges that the current user has fulfilled for a
302 certain host, database, and object.
303
304 @details This field is continually updated throughout the access checking
305 process. In each step the "wanted privilege" is checked against the
306 fulfilled privileges. When/if the intersection of these sets is empty,
307 access is granted.
308
309 The set is implemented as a bitmap, with the bits defined in sql_acl.h.
310 */
311 ulong privilege;
312 /**
313 @brief the set of privileges that the current user needs to fulfil in
314 order to carry out the requested operation.
315 */
316 ulong want_privilege;
317 /**
318 Stores the requested access acl of top level tables list. Is used to
319 check access rights to the underlying tables of a view.
320 */
321 ulong orig_want_privilege;
322 /** The grant state for internal tables. */
323 GRANT_INTERNAL_INFO m_internal;
324 } GRANT_INFO;
325
326 enum tmp_table_type
327 {
328 NO_TMP_TABLE= 0, NON_TRANSACTIONAL_TMP_TABLE, TRANSACTIONAL_TMP_TABLE,
329 INTERNAL_TMP_TABLE, SYSTEM_TMP_TABLE
330 };
331 enum release_type { RELEASE_NORMAL, RELEASE_WAIT_FOR_DROP };
332
333
334 enum vcol_init_mode
335 {
336 VCOL_INIT_DEPENDENCY_FAILURE_IS_WARNING= 1,
337 VCOL_INIT_DEPENDENCY_FAILURE_IS_ERROR= 2
338 /*
339 There may be new flags here.
340 e.g. to automatically remove sql_mode dependency:
341 GENERATED ALWAYS AS (char_col) ->
342 GENERATED ALWAYS AS (RTRIM(char_col))
343 */
344 };
345
346
347 enum enum_vcol_update_mode
348 {
349 VCOL_UPDATE_FOR_READ= 0,
350 VCOL_UPDATE_FOR_WRITE,
351 VCOL_UPDATE_FOR_DELETE,
352 VCOL_UPDATE_INDEXED,
353 VCOL_UPDATE_INDEXED_FOR_UPDATE,
354 VCOL_UPDATE_FOR_REPLACE
355 };
356
357 /* Field visibility enums */
358
359 enum field_visibility_t {
360 VISIBLE= 0,
361 INVISIBLE_USER,
362 /* automatically added by the server. Can be queried explicitly
363 in SELECT, otherwise invisible from anything" */
364 INVISIBLE_SYSTEM,
365 INVISIBLE_FULL
366 };
367
368 #define INVISIBLE_MAX_BITS 3
369 #define HA_HASH_FIELD_LENGTH 8
370 #define HA_HASH_KEY_LENGTH_WITHOUT_NULL 8
371 #define HA_HASH_KEY_LENGTH_WITH_NULL 9
372
373
374 int fields_in_hash_keyinfo(KEY *keyinfo);
375
376 void setup_keyinfo_hash(KEY *key_info);
377
378 void re_setup_keyinfo_hash(KEY *key_info);
379
380 /**
381 Category of table found in the table share.
382 */
383 enum enum_table_category
384 {
385 /**
386 Unknown value.
387 */
388 TABLE_UNKNOWN_CATEGORY=0,
389
390 /**
391 Temporary table.
392 The table is visible only in the session.
393 Therefore,
394 - FLUSH TABLES WITH READ LOCK
395 - SET GLOBAL READ_ONLY = ON
396 do not apply to this table.
397 Note that LOCK TABLE t FOR READ/WRITE
398 can be used on temporary tables.
399 Temporary tables are not part of the table cache.
400 */
401 TABLE_CATEGORY_TEMPORARY=1,
402
403 /**
404 User table.
405 These tables do honor:
406 - LOCK TABLE t FOR READ/WRITE
407 - FLUSH TABLES WITH READ LOCK
408 - SET GLOBAL READ_ONLY = ON
409 User tables are cached in the table cache.
410 */
411 TABLE_CATEGORY_USER=2,
412
413 /**
414 System table, maintained by the server.
415 These tables do honor:
416 - LOCK TABLE t FOR READ/WRITE
417 - FLUSH TABLES WITH READ LOCK
418 - SET GLOBAL READ_ONLY = ON
419 Typically, writes to system tables are performed by
420 the server implementation, not explicitly be a user.
421 System tables are cached in the table cache.
422 */
423 TABLE_CATEGORY_SYSTEM=3,
424
425 /**
426 Log tables.
427 These tables are an interface provided by the system
428 to inspect the system logs.
429 These tables do *not* honor:
430 - LOCK TABLE t FOR READ/WRITE
431 - FLUSH TABLES WITH READ LOCK
432 - SET GLOBAL READ_ONLY = ON
433 as there is no point in locking explicitly
434 a LOG table.
435 An example of LOG tables are:
436 - mysql.slow_log
437 - mysql.general_log,
438 which *are* updated even when there is either
439 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
440 User queries do not write directly to these tables
441 (there are exceptions for log tables).
442 The server implementation perform writes.
443 Log tables are cached in the table cache.
444 */
445 TABLE_CATEGORY_LOG=4,
446
447 /*
448 Types below are read only tables, not affected by FLUSH TABLES or
449 MDL locks.
450 */
451 /**
452 Information schema tables.
453 These tables are an interface provided by the system
454 to inspect the system metadata.
455 These tables do *not* honor:
456 - LOCK TABLE t FOR READ/WRITE
457 - FLUSH TABLES WITH READ LOCK
458 - SET GLOBAL READ_ONLY = ON
459 as there is no point in locking explicitly
460 an INFORMATION_SCHEMA table.
461 Nothing is directly written to information schema tables.
462 Note that this value is not used currently,
463 since information schema tables are not shared,
464 but implemented as session specific temporary tables.
465 */
466 /*
467 TODO: Fixing the performance issues of I_S will lead
468 to I_S tables in the table cache, which should use
469 this table type.
470 */
471 TABLE_CATEGORY_INFORMATION=5,
472
473 /**
474 Performance schema tables.
475 These tables are an interface provided by the system
476 to inspect the system performance data.
477 These tables do *not* honor:
478 - LOCK TABLE t FOR READ/WRITE
479 - FLUSH TABLES WITH READ LOCK
480 - SET GLOBAL READ_ONLY = ON
481 as there is no point in locking explicitly
482 a PERFORMANCE_SCHEMA table.
483 An example of PERFORMANCE_SCHEMA tables are:
484 - performance_schema.*
485 which *are* updated (but not using the handler interface)
486 even when there is either
487 a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect.
488 User queries do not write directly to these tables
489 (there are exceptions for SETUP_* tables).
490 The server implementation perform writes.
491 Performance tables are cached in the table cache.
492 */
493 TABLE_CATEGORY_PERFORMANCE=6
494 };
495
496 typedef enum enum_table_category TABLE_CATEGORY;
497
498 TABLE_CATEGORY get_table_category(const LEX_CSTRING *db,
499 const LEX_CSTRING *name);
500
501
502 typedef struct st_table_field_type
503 {
504 LEX_CSTRING name;
505 LEX_CSTRING type;
506 LEX_CSTRING cset;
507 } TABLE_FIELD_TYPE;
508
509
510 typedef struct st_table_field_def
511 {
512 uint count;
513 const TABLE_FIELD_TYPE *field;
514 uint primary_key_parts;
515 const uint *primary_key_columns;
516 } TABLE_FIELD_DEF;
517
518
519 class Table_check_intact
520 {
521 protected:
522 bool has_keys;
523 virtual void report_error(uint code, const char *fmt, ...)= 0;
524
525 public:
has_keys(keys)526 Table_check_intact(bool keys= false) : has_keys(keys) {}
~Table_check_intact()527 virtual ~Table_check_intact() {}
528
529 /** Checks whether a table is intact. */
530 bool check(TABLE *table, const TABLE_FIELD_DEF *table_def);
531 };
532
533
534 /*
535 If the table isn't valid, report the error to the server log only.
536 */
537 class Table_check_intact_log_error : public Table_check_intact
538 {
539 protected:
540 void report_error(uint, const char *fmt, ...);
541 public:
Table_check_intact_log_error()542 Table_check_intact_log_error() : Table_check_intact(true) {}
543 };
544
545
546 /**
547 Class representing the fact that some thread waits for table
548 share to be flushed. Is used to represent information about
549 such waits in MDL deadlock detector.
550 */
551
552 class Wait_for_flush : public MDL_wait_for_subgraph
553 {
554 MDL_context *m_ctx;
555 TABLE_SHARE *m_share;
556 uint m_deadlock_weight;
557 public:
Wait_for_flush(MDL_context * ctx_arg,TABLE_SHARE * share_arg,uint deadlock_weight_arg)558 Wait_for_flush(MDL_context *ctx_arg, TABLE_SHARE *share_arg,
559 uint deadlock_weight_arg)
560 : m_ctx(ctx_arg), m_share(share_arg),
561 m_deadlock_weight(deadlock_weight_arg)
562 {}
563
get_ctx()564 MDL_context *get_ctx() const { return m_ctx; }
565
566 virtual bool accept_visitor(MDL_wait_for_graph_visitor *dvisitor);
567
568 virtual uint get_deadlock_weight() const;
569
570 /**
571 Pointers for participating in the list of waiters for table share.
572 */
573 Wait_for_flush *next_in_share;
574 Wait_for_flush **prev_in_share;
575 };
576
577
578 typedef I_P_List <Wait_for_flush,
579 I_P_List_adapter<Wait_for_flush,
580 &Wait_for_flush::next_in_share,
581 &Wait_for_flush::prev_in_share> >
582 Wait_for_flush_list;
583
584
585 enum open_frm_error {
586 OPEN_FRM_OK = 0,
587 OPEN_FRM_OPEN_ERROR,
588 OPEN_FRM_READ_ERROR,
589 OPEN_FRM_CORRUPTED,
590 OPEN_FRM_DISCOVER,
591 OPEN_FRM_ERROR_ALREADY_ISSUED,
592 OPEN_FRM_NOT_A_VIEW,
593 OPEN_FRM_NOT_A_TABLE,
594 OPEN_FRM_NEEDS_REBUILD
595 };
596
597 /**
598 Control block to access table statistics loaded
599 from persistent statistical tables
600 */
601
602 class TABLE_STATISTICS_CB
603 {
604 class Statistics_state
605 {
606 enum state_codes
607 {
608 EMPTY, /** data is not loaded */
609 LOADING, /** data is being loaded in some connection */
610 READY /** data is loaded and available for use */
611 };
612 int32 state;
613
614 public:
615 /** No state copy */
616 Statistics_state &operator=(const Statistics_state &) { return *this; }
617
618 /** Checks if data loading have been completed */
is_ready()619 bool is_ready() const
620 {
621 return my_atomic_load32_explicit(const_cast<int32*>(&state),
622 MY_MEMORY_ORDER_ACQUIRE) == READY;
623 }
624
625 /**
626 Sets mutual exclusion for data loading
627
628 If stats are in LOADING state, waits until state change.
629
630 @return
631 @retval true atomic EMPTY -> LOADING transfer completed, ok to load
632 @retval false stats are in READY state, no need to load
633 */
start_load()634 bool start_load()
635 {
636 for (;;)
637 {
638 int32 expected= EMPTY;
639 if (my_atomic_cas32_weak_explicit(&state, &expected, LOADING,
640 MY_MEMORY_ORDER_RELAXED,
641 MY_MEMORY_ORDER_RELAXED))
642 return true;
643 if (expected == READY)
644 return false;
645 (void) LF_BACKOFF();
646 }
647 }
648
649 /** Marks data available for subsequent use */
end_load()650 void end_load()
651 {
652 DBUG_ASSERT(my_atomic_load32_explicit(&state, MY_MEMORY_ORDER_RELAXED) ==
653 LOADING);
654 my_atomic_store32_explicit(&state, READY, MY_MEMORY_ORDER_RELEASE);
655 }
656
657 /** Restores empty state on error (e.g. OOM) */
abort_load()658 void abort_load()
659 {
660 DBUG_ASSERT(my_atomic_load32_explicit(&state, MY_MEMORY_ORDER_RELAXED) ==
661 LOADING);
662 my_atomic_store32_explicit(&state, EMPTY, MY_MEMORY_ORDER_RELAXED);
663 }
664 };
665
666 class Statistics_state stats_state;
667 class Statistics_state hist_state;
668
669 public:
670 MEM_ROOT mem_root; /* MEM_ROOT to allocate statistical data for the table */
671 Table_statistics *table_stats; /* Structure to access the statistical data */
672 ulong total_hist_size; /* Total size of all histograms */
673
histograms_are_ready()674 bool histograms_are_ready() const
675 {
676 return !total_hist_size || hist_state.is_ready();
677 }
678
start_histograms_load()679 bool start_histograms_load()
680 {
681 return total_hist_size && hist_state.start_load();
682 }
683
end_histograms_load()684 void end_histograms_load() { hist_state.end_load(); }
abort_histograms_load()685 void abort_histograms_load() { hist_state.abort_load(); }
stats_are_ready()686 bool stats_are_ready() const { return stats_state.is_ready(); }
start_stats_load()687 bool start_stats_load() { return stats_state.start_load(); }
end_stats_load()688 void end_stats_load() { stats_state.end_load(); }
abort_stats_load()689 void abort_stats_load() { stats_state.abort_load(); }
690 };
691
692 /**
693 This structure is shared between different table objects. There is one
694 instance of table share per one table in the database.
695 */
696
697 struct TABLE_SHARE
698 {
TABLE_SHARETABLE_SHARE699 TABLE_SHARE() {} /* Remove gcc warning */
700
701 /** Category of this table. */
702 TABLE_CATEGORY table_category;
703
704 /* hash of field names (contains pointers to elements of field array) */
705 HASH name_hash; /* hash of field names */
706 MEM_ROOT mem_root;
707 TYPELIB keynames; /* Pointers to keynames */
708 TYPELIB fieldnames; /* Pointer to fieldnames */
709 TYPELIB *intervals; /* pointer to interval info */
710 mysql_mutex_t LOCK_ha_data; /* To protect access to ha_data */
711 mysql_mutex_t LOCK_share; /* To protect TABLE_SHARE */
712
713 TDC_element *tdc;
714
715 LEX_CUSTRING tabledef_version;
716
717 engine_option_value *option_list; /* text options for table */
718 ha_table_option_struct *option_struct; /* structure with parsed options */
719
720 /* The following is copied to each TABLE on OPEN */
721 Field **field;
722 Field **found_next_number_field;
723 KEY *key_info; /* data of keys in database */
724 Virtual_column_info **check_constraints;
725 uint *blob_field; /* Index to blobs in Field arrray*/
726 LEX_CUSTRING vcol_defs; /* definitions of generated columns */
727
728 TABLE_STATISTICS_CB stats_cb;
729
730 uchar *default_values; /* row with default values */
731 LEX_CSTRING comment; /* Comment about table */
732 CHARSET_INFO *table_charset; /* Default charset of string fields */
733
734 MY_BITMAP *check_set; /* Fields used by check constrant */
735 MY_BITMAP all_set;
736 /*
737 Key which is used for looking-up table in table cache and in the list
738 of thread's temporary tables. Has the form of:
739 "database_name\0table_name\0" + optional part for temporary tables.
740
741 Note that all three 'table_cache_key', 'db' and 'table_name' members
742 must be set (and be non-zero) for tables in table cache. They also
743 should correspond to each other.
744 To ensure this one can use set_table_cache() methods.
745 */
746 LEX_CSTRING table_cache_key;
747 LEX_CSTRING db; /* Pointer to db */
748 LEX_CSTRING table_name; /* Table name (for open) */
749 LEX_CSTRING path; /* Path to .frm file (from datadir) */
750 LEX_CSTRING normalized_path; /* unpack_filename(path) */
751 LEX_CSTRING connect_string;
752
753 /*
754 Set of keys in use, implemented as a Bitmap.
755 Excludes keys disabled by ALTER TABLE ... DISABLE KEYS.
756 */
757 key_map keys_in_use;
758 key_map keys_for_keyread;
759 ha_rows min_rows, max_rows; /* create information */
760 ulong avg_row_length; /* create information */
761 ulong mysql_version; /* 0 if .frm is created before 5.0 */
762 ulong reclength; /* Recordlength */
763 /* Stored record length. No generated-only virtual fields are included */
764 ulong stored_rec_length;
765
766 plugin_ref db_plugin; /* storage engine plugin */
db_typeTABLE_SHARE767 inline handlerton *db_type() const /* table_type for handler */
768 {
769 return is_view ? view_pseudo_hton :
770 db_plugin ? plugin_hton(db_plugin) : NULL;
771 }
772 enum row_type row_type; /* How rows are stored */
773 enum Table_type table_type;
774 enum tmp_table_type tmp_table;
775
776 /** Transactional or not. */
777 enum ha_choice transactional;
778 /** Per-page checksums or not. */
779 enum ha_choice page_checksum;
780
781 uint key_block_size; /* create key_block_size, if used */
782 uint stats_sample_pages; /* number of pages to sample during
783 stats estimation, if used, otherwise 0. */
784 enum_stats_auto_recalc stats_auto_recalc; /* Automatic recalc of stats. */
785 uint null_bytes, last_null_bit_pos;
786 /*
787 Same as null_bytes, except that if there is only a 'delete-marker' in
788 the record then this value is 0.
789 */
790 uint null_bytes_for_compare;
791 uint fields; /* number of fields */
792 /* number of stored fields, purely virtual not included */
793 uint stored_fields;
794 uint virtual_fields; /* number of purely virtual fields */
795 /* number of purely virtual not stored blobs */
796 uint virtual_not_stored_blob_fields;
797 uint null_fields; /* number of null fields */
798 uint blob_fields; /* number of blob fields */
799 uint varchar_fields; /* number of varchar fields */
800 uint default_fields; /* number of default fields */
801 uint visible_fields; /* number of visible fields */
802
803 uint default_expressions;
804 uint table_check_constraints, field_check_constraints;
805
806 uint rec_buff_length; /* Size of table->record[] buffer */
807 uint keys, key_parts;
808 uint ext_key_parts; /* Total number of key parts in extended keys */
809 uint max_key_length, max_unique_length;
810 uint uniques; /* Number of UNIQUE index */
811 uint db_create_options; /* Create options from database */
812 uint db_options_in_use; /* Options in use */
813 uint db_record_offset; /* if HA_REC_IN_SEQ */
814 uint rowid_field_offset; /* Field_nr +1 to rowid field */
815 /* Primary key index number, used in TABLE::key_info[] */
816 uint primary_key;
817 uint next_number_index; /* autoincrement key number */
818 uint next_number_key_offset; /* autoinc keypart offset in a key */
819 uint next_number_keypart; /* autoinc keypart number in a key */
820 enum open_frm_error error; /* error from open_table_def() */
821 uint open_errno; /* error from open_table_def() */
822 uint column_bitmap_size;
823 uchar frm_version;
824
825 enum enum_v_keys { NOT_INITIALIZED=0, NO_V_KEYS, V_KEYS };
826 enum_v_keys check_set_initialized;
827
828 bool use_ext_keys; /* Extended keys can be used */
829 bool null_field_first;
830 bool system; /* Set if system table (one record) */
831 bool not_usable_by_query_cache;
832 bool online_backup; /* Set if on-line backup supported */
833 /*
834 This is used by log tables, for tables that have their own internal
835 binary logging or for tables that doesn't support statement or row logging
836 */
837 bool no_replicate;
838 bool crashed;
839 bool is_view;
840 bool can_cmp_whole_record;
841 /* This is set for temporary tables where CREATE was binary logged */
842 bool table_creation_was_logged;
843 bool non_determinstic_insert;
844 bool vcols_need_refixing;
845 bool has_update_default_function;
846 bool can_do_row_logging; /* 1 if table supports RBR */
847 bool long_unique_table;
848
849 ulong table_map_id; /* for row-based replication */
850
851 /*
852 Things that are incompatible between the stored version and the
853 current version. This is a set of HA_CREATE... bits that can be used
854 to modify create_info->used_fields for ALTER TABLE.
855 */
856 ulong incompatible_version;
857
858 /**
859 For shares representing views File_parser object with view
860 definition read from .FRM file.
861 */
862 const File_parser *view_def;
863
864 /* For sequence tables, the current sequence state */
865 SEQUENCE *sequence;
866
867 #ifdef WITH_PARTITION_STORAGE_ENGINE
868 /* filled in when reading from frm */
869 bool auto_partitioned;
870 char *partition_info_str;
871 uint partition_info_str_len;
872 uint partition_info_buffer_size;
873 plugin_ref default_part_plugin;
874 #endif
875
876 /**
877 System versioning support.
878 */
879 struct period_info_t
880 {
881 uint16 start_fieldno;
882 uint16 end_fieldno;
883 Lex_ident name;
884 Lex_ident constr_name;
start_fieldTABLE_SHARE::period_info_t885 Field *start_field(TABLE_SHARE *s) const
886 {
887 return s->field[start_fieldno];
888 }
end_fieldTABLE_SHARE::period_info_t889 Field *end_field(TABLE_SHARE *s) const
890 {
891 return s->field[end_fieldno];
892 }
893 };
894
895 vers_sys_type_t versioned;
896 period_info_t vers;
897 period_info_t period;
898
899 bool init_period_from_extra2(period_info_t *period, const uchar *data,
900 const uchar *end);
901
vers_start_fieldTABLE_SHARE902 Field *vers_start_field()
903 {
904 return field[vers.start_fieldno];
905 }
906
vers_end_fieldTABLE_SHARE907 Field *vers_end_field()
908 {
909 return field[vers.end_fieldno];
910 }
911
912 /**
913 Cache the checked structure of this table.
914
915 The pointer data is used to describe the structure that
916 a instance of the table must have. Each element of the
917 array specifies a field that must exist on the table.
918
919 The pointer is cached in order to perform the check only
920 once -- when the table is loaded from the disk.
921 */
922 const TABLE_FIELD_DEF *table_field_def_cache;
923
924 /** Main handler's share */
925 Handler_share *ha_share;
926
927 /** Instrumentation for this table share. */
928 PSI_table_share *m_psi;
929
resetTABLE_SHARE930 inline void reset() { bzero((void*)this, sizeof(*this)); }
931
932 /*
933 Set share's table cache key and update its db and table name appropriately.
934
935 SYNOPSIS
936 set_table_cache_key()
937 key_buff Buffer with already built table cache key to be
938 referenced from share.
939 key_length Key length.
940
941 NOTES
942 Since 'key_buff' buffer will be referenced from share it should has same
943 life-time as share itself.
944 This method automatically ensures that TABLE_SHARE::table_name/db have
945 appropriate values by using table cache key as their source.
946 */
947
set_table_cache_keyTABLE_SHARE948 void set_table_cache_key(char *key_buff, uint key_length)
949 {
950 table_cache_key.str= key_buff;
951 table_cache_key.length= key_length;
952 /*
953 Let us use the fact that the key is "db/0/table_name/0" + optional
954 part for temporary tables.
955 */
956 db.str= table_cache_key.str;
957 db.length= strlen(db.str);
958 table_name.str= db.str + db.length + 1;
959 table_name.length= strlen(table_name.str);
960 }
961
962
963 /*
964 Set share's table cache key and update its db and table name appropriately.
965
966 SYNOPSIS
967 set_table_cache_key()
968 key_buff Buffer to be used as storage for table cache key
969 (should be at least key_length bytes).
970 key Value for table cache key.
971 key_length Key length.
972
973 NOTE
974 Since 'key_buff' buffer will be used as storage for table cache key
975 it should has same life-time as share itself.
976 */
977
set_table_cache_keyTABLE_SHARE978 void set_table_cache_key(char *key_buff, const char *key, uint key_length)
979 {
980 memcpy(key_buff, key, key_length);
981 set_table_cache_key(key_buff, key_length);
982 }
983
require_write_privilegesTABLE_SHARE984 inline bool require_write_privileges()
985 {
986 return (table_category == TABLE_CATEGORY_LOG);
987 }
988
get_table_def_versionTABLE_SHARE989 inline ulong get_table_def_version()
990 {
991 return table_map_id;
992 }
993
994 /**
995 Convert unrelated members of TABLE_SHARE to one enum
996 representing its type.
997
998 @todo perhaps we need to have a member instead of a function.
999 */
get_table_ref_typeTABLE_SHARE1000 enum enum_table_ref_type get_table_ref_type() const
1001 {
1002 if (is_view)
1003 return TABLE_REF_VIEW;
1004 switch (tmp_table) {
1005 case NO_TMP_TABLE:
1006 return TABLE_REF_BASE_TABLE;
1007 case SYSTEM_TMP_TABLE:
1008 return TABLE_REF_I_S_TABLE;
1009 default:
1010 return TABLE_REF_TMP_TABLE;
1011 }
1012 }
1013 /**
1014 Return a table metadata version.
1015 * for base tables and views, we return table_map_id.
1016 It is assigned from a global counter incremented for each
1017 new table loaded into the table definition cache (TDC).
1018 * for temporary tables it's table_map_id again. But for
1019 temporary tables table_map_id is assigned from
1020 thd->query_id. The latter is assigned from a thread local
1021 counter incremented for every new SQL statement. Since
1022 temporary tables are thread-local, each temporary table
1023 gets a unique id.
1024 * for everything else (e.g. information schema tables),
1025 the version id is zero.
1026
1027 This choice of version id is a large compromise
1028 to have a working prepared statement validation in 5.1. In
1029 future version ids will be persistent, as described in WL#4180.
1030
1031 Let's try to explain why and how this limited solution allows
1032 to validate prepared statements.
1033
1034 Firstly, sets (in mathematical sense) of version numbers
1035 never intersect for different table types. Therefore,
1036 version id of a temporary table is never compared with
1037 a version id of a view, and vice versa.
1038
1039 Secondly, for base tables and views, we know that each DDL flushes
1040 the respective share from the TDC. This ensures that whenever
1041 a table is altered or dropped and recreated, it gets a new
1042 version id.
1043 Unfortunately, since elements of the TDC are also flushed on
1044 LRU basis, this choice of version ids leads to false positives.
1045 E.g. when the TDC size is too small, we may have a SELECT
1046 * FROM INFORMATION_SCHEMA.TABLES flush all its elements, which
1047 in turn will lead to a validation error and a subsequent
1048 reprepare of all prepared statements. This is
1049 considered acceptable, since as long as prepared statements are
1050 automatically reprepared, spurious invalidation is only
1051 a performance hit. Besides, no better simple solution exists.
1052
1053 For temporary tables, using thd->query_id ensures that if
1054 a temporary table was altered or recreated, a new version id is
1055 assigned. This suits validation needs very well and will perhaps
1056 never change.
1057
1058 Metadata of information schema tables never changes.
1059 Thus we can safely assume 0 for a good enough version id.
1060
1061 Finally, by taking into account table type, we always
1062 track that a change has taken place when a view is replaced
1063 with a base table, a base table is replaced with a temporary
1064 table and so on.
1065
1066 @sa TABLE_LIST::is_table_ref_id_equal()
1067 */
get_table_ref_versionTABLE_SHARE1068 ulong get_table_ref_version() const
1069 {
1070 return (tmp_table == SYSTEM_TMP_TABLE) ? 0 : table_map_id;
1071 }
1072
1073 bool visit_subgraph(Wait_for_flush *waiting_ticket,
1074 MDL_wait_for_graph_visitor *gvisitor);
1075
1076 bool wait_for_old_version(THD *thd, struct timespec *abstime,
1077 uint deadlock_weight);
1078 /** Release resources and free memory occupied by the table share. */
1079 void destroy();
1080
set_use_ext_keys_flagTABLE_SHARE1081 void set_use_ext_keys_flag(bool fl)
1082 {
1083 use_ext_keys= fl;
1084 }
1085
1086 uint actual_n_key_parts(THD *thd);
1087
1088 LEX_CUSTRING *frm_image; ///< only during CREATE TABLE (@sa ha_create_table)
1089
1090 /*
1091 populates TABLE_SHARE from the table description in the binary frm image.
1092 if 'write' is true, this frm image is also written into a corresponding
1093 frm file, that serves as a persistent metadata cache to avoid
1094 discovering the table over and over again
1095 */
1096 int init_from_binary_frm_image(THD *thd, bool write,
1097 const uchar *frm_image, size_t frm_length);
1098
1099 /*
1100 populates TABLE_SHARE from the table description, specified as the
1101 complete CREATE TABLE sql statement.
1102 if 'write' is true, this frm image is also written into a corresponding
1103 frm file, that serves as a persistent metadata cache to avoid
1104 discovering the table over and over again
1105 */
1106 int init_from_sql_statement_string(THD *thd, bool write,
1107 const char *sql, size_t sql_length);
1108 /*
1109 writes the frm image to an frm file, corresponding to this table
1110 */
1111 bool write_frm_image(const uchar *frm_image, size_t frm_length);
1112
write_frm_imageTABLE_SHARE1113 bool write_frm_image(void)
1114 { return frm_image ? write_frm_image(frm_image->str, frm_image->length) : 0; }
1115
1116 /*
1117 returns an frm image for this table.
1118 the memory is allocated and must be freed later
1119 */
1120 bool read_frm_image(const uchar **frm_image, size_t *frm_length);
1121
1122 /* frees the memory allocated in read_frm_image */
1123 void free_frm_image(const uchar *frm);
1124
1125 void set_overlapped_keys();
1126 };
1127
1128 /* not NULL, but cannot be dereferenced */
1129 #define UNUSABLE_TABLE_SHARE ((TABLE_SHARE*)1)
1130
1131 /**
1132 Class is used as a BLOB field value storage for
1133 intermediate GROUP_CONCAT results. Used only for
1134 GROUP_CONCAT with DISTINCT or ORDER BY options.
1135 */
1136
1137 class Blob_mem_storage: public Sql_alloc
1138 {
1139 private:
1140 MEM_ROOT storage;
1141 /**
1142 Sign that some values were cut
1143 during saving into the storage.
1144 */
1145 bool truncated_value;
1146 public:
Blob_mem_storage()1147 Blob_mem_storage() :truncated_value(false)
1148 {
1149 init_alloc_root(&storage, "Blob_mem_storage", MAX_FIELD_VARCHARLENGTH, 0,
1150 MYF(0));
1151 }
~Blob_mem_storage()1152 ~ Blob_mem_storage()
1153 {
1154 free_root(&storage, MYF(0));
1155 }
reset()1156 void reset()
1157 {
1158 free_root(&storage, MYF(MY_MARK_BLOCKS_FREE));
1159 truncated_value= false;
1160 }
1161 /**
1162 Fuction creates duplicate of 'from'
1163 string in 'storage' MEM_ROOT.
1164
1165 @param from string to copy
1166 @param length string length
1167
1168 @retval Pointer to the copied string.
1169 @retval 0 if an error occurred.
1170 */
store(const char * from,size_t length)1171 char *store(const char *from, size_t length)
1172 {
1173 return (char*) memdup_root(&storage, from, length);
1174 }
set_truncated_value(bool is_truncated_value)1175 void set_truncated_value(bool is_truncated_value)
1176 {
1177 truncated_value= is_truncated_value;
1178 }
is_truncated_value()1179 bool is_truncated_value() { return truncated_value; }
1180 };
1181
1182
1183 /* Information for one open table */
1184 enum index_hint_type
1185 {
1186 INDEX_HINT_IGNORE,
1187 INDEX_HINT_USE,
1188 INDEX_HINT_FORCE
1189 };
1190
1191 struct st_cond_statistic;
1192
1193 #define CHECK_ROW_FOR_NULLS_TO_REJECT (1 << 0)
1194 #define REJECT_ROW_DUE_TO_NULL_FIELDS (1 << 1)
1195
1196 class SplM_opt_info;
1197
1198 struct vers_select_conds_t;
1199
1200 struct TABLE
1201 {
TABLETABLE1202 TABLE() {} /* Remove gcc warning */
1203
1204 TABLE_SHARE *s;
1205 handler *file;
1206 TABLE *next, *prev;
1207
1208 private:
1209 /**
1210 Links for the list of all TABLE objects for this share.
1211 Declared as private to avoid direct manipulation with those objects.
1212 One should use methods of I_P_List template instead.
1213 */
1214 TABLE *share_all_next, **share_all_prev;
1215 TABLE *global_free_next, **global_free_prev;
1216 friend struct All_share_tables;
1217 friend struct Table_cache_instance;
1218
1219 public:
1220
1221 uint32 instance; /** Table cache instance this TABLE is belonging to */
1222 THD *in_use; /* Which thread uses this */
1223
1224 uchar *record[3]; /* Pointer to records */
1225 /* record buf to resolve hash collisions for long UNIQUE constraints */
1226 uchar *check_unique_buf;
1227 handler *update_handler; /* Handler used in case of update */
1228 uchar *write_row_record; /* Used as optimisation in
1229 THD::write_row */
1230 uchar *insert_values; /* used by INSERT ... UPDATE */
1231 /*
1232 Map of keys that can be used to retrieve all data from this table
1233 needed by the query without reading the row.
1234 */
1235 key_map covering_keys;
1236 key_map quick_keys, intersect_keys;
1237 /*
1238 A set of keys that can be used in the query that references this
1239 table.
1240
1241 All indexes disabled on the table's TABLE_SHARE (see TABLE::s) will be
1242 subtracted from this set upon instantiation. Thus for any TABLE t it holds
1243 that t.keys_in_use_for_query is a subset of t.s.keys_in_use. Generally we
1244 must not introduce any new keys here (see setup_tables).
1245
1246 The set is implemented as a bitmap.
1247 */
1248 key_map keys_in_use_for_query;
1249 /* Map of keys that can be used to calculate GROUP BY without sorting */
1250 key_map keys_in_use_for_group_by;
1251 /* Map of keys that can be used to calculate ORDER BY without sorting */
1252 key_map keys_in_use_for_order_by;
1253 /* Map of keys dependent on some constraint */
1254 key_map constraint_dependent_keys;
1255 KEY *key_info; /* data of keys in database */
1256
1257 Field **field; /* Pointer to fields */
1258 Field **vfield; /* Pointer to virtual fields*/
1259 Field **default_field; /* Fields with non-constant DEFAULT */
1260 Field *next_number_field; /* Set if next_number is activated */
1261 Field *found_next_number_field; /* Set on open */
1262 Virtual_column_info **check_constraints;
1263
1264 /* Table's triggers, 0 if there are no of them */
1265 Table_triggers_list *triggers;
1266 TABLE_LIST *pos_in_table_list;/* Element referring to this table */
1267 /* Position in thd->locked_table_list under LOCK TABLES */
1268 TABLE_LIST *pos_in_locked_tables;
1269 /* Tables used in DEFAULT and CHECK CONSTRAINT (normally sequence tables) */
1270 TABLE_LIST *internal_tables;
1271
1272 /*
1273 Not-null for temporary tables only. Non-null values means this table is
1274 used to compute GROUP BY, it has a unique of GROUP BY columns.
1275 (set by create_tmp_table)
1276 */
1277 ORDER *group;
1278 String alias; /* alias or table name */
1279 uchar *null_flags;
1280 MY_BITMAP def_read_set, def_write_set, tmp_set;
1281 MY_BITMAP def_rpl_write_set;
1282 MY_BITMAP eq_join_set; /* used to mark equi-joined fields */
1283 MY_BITMAP cond_set; /* used to mark fields from sargable conditions*/
1284 /* Active column sets */
1285 MY_BITMAP *read_set, *write_set, *rpl_write_set;
1286 /* On INSERT: fields that the user specified a value for */
1287 MY_BITMAP has_value_set;
1288
1289 /*
1290 The ID of the query that opened and is using this table. Has different
1291 meanings depending on the table type.
1292
1293 Temporary tables:
1294
1295 table->query_id is set to thd->query_id for the duration of a statement
1296 and is reset to 0 once it is closed by the same statement. A non-zero
1297 table->query_id means that a statement is using the table even if it's
1298 not the current statement (table is in use by some outer statement).
1299
1300 Non-temporary tables:
1301
1302 Under pre-locked or LOCK TABLES mode: query_id is set to thd->query_id
1303 for the duration of a statement and is reset to 0 once it is closed by
1304 the same statement. A non-zero query_id is used to control which tables
1305 in the list of pre-opened and locked tables are actually being used.
1306 */
1307 query_id_t query_id;
1308
1309 /*
1310 This structure is used for statistical data on the table that
1311 is collected by the function collect_statistics_for_table
1312 */
1313 Table_statistics *collected_stats;
1314
1315 /* The estimate of the number of records in the table used by optimizer */
1316 ha_rows used_stat_records;
1317
1318 /*
1319 For each key that has quick_keys.is_set(key) == TRUE: estimate of #records
1320 and max #key parts that range access would use.
1321 */
1322 ha_rows quick_rows[MAX_KEY];
1323 uint quick_key_parts[MAX_KEY];
1324
1325 double quick_costs[MAX_KEY];
1326 /*
1327 If there is a range access by i-th index then the cost of
1328 index only access for it is stored in quick_index_only_costs[i]
1329 */
1330 double quick_index_only_costs[MAX_KEY];
1331
1332 /*
1333 Bitmaps of key parts that =const for the duration of join execution. If
1334 we're in a subquery, then the constant may be different across subquery
1335 re-executions.
1336 */
1337 key_part_map const_key_parts[MAX_KEY];
1338
1339 uint quick_n_ranges[MAX_KEY];
1340
1341 /*
1342 Estimate of number of records that satisfy SARGable part of the table
1343 condition, or table->file->records if no SARGable condition could be
1344 constructed.
1345 This value is used by join optimizer as an estimate of number of records
1346 that will pass the table condition (condition that depends on fields of
1347 this table and constants)
1348 */
1349 ha_rows quick_condition_rows;
1350
1351 double cond_selectivity;
1352 List<st_cond_statistic> *cond_selectivity_sampling_explain;
1353
1354 table_map map; /* ID bit of table (1,2,4,8,16...) */
1355
1356 uint lock_position; /* Position in MYSQL_LOCK.table */
1357 uint lock_data_start; /* Start pos. in MYSQL_LOCK.locks */
1358 uint lock_count; /* Number of locks */
1359 uint tablenr,used_fields;
1360 uint temp_pool_slot; /* Used by intern temp tables */
1361 uint status; /* What's in record[0] */
1362 uint db_stat; /* mode of file as in handler.h */
1363 /* number of select if it is derived table */
1364 uint derived_select_number;
1365 /*
1366 Possible values:
1367 - 0 by default
1368 - JOIN_TYPE_{LEFT|RIGHT} if the table is inner w.r.t an outer join
1369 operation
1370 - 1 if the SELECT has mixed_implicit_grouping=1. example:
1371 select max(col1), col2 from t1. In this case, the query produces
1372 one row with all columns having NULL values.
1373
1374 Interpetation: If maybe_null!=0, all fields of the table are considered
1375 NULLable (and have NULL values when null_row=true)
1376 */
1377 uint maybe_null;
1378 int current_lock; /* Type of lock on table */
1379 bool copy_blobs; /* copy_blobs when storing */
1380 /*
1381 Set if next_number_field is in the UPDATE fields of INSERT ... ON DUPLICATE
1382 KEY UPDATE.
1383 */
1384 bool next_number_field_updated;
1385
1386 /*
1387 If true, the current table row is considered to have all columns set to
1388 NULL, including columns declared as "not null" (see maybe_null).
1389 */
1390 bool null_row;
1391 /*
1392 No rows that contain null values can be placed into this table.
1393 Currently this flag can be set to true only for a temporary table
1394 that used to store the result of materialization of a subquery.
1395 */
1396 bool no_rows_with_nulls;
1397 /*
1398 This field can contain two bit flags:
1399 CHECK_ROW_FOR_NULLS_TO_REJECT
1400 REJECT_ROW_DUE_TO_NULL_FIELDS
1401 The first flag is set for the dynamic contexts where it is prohibited
1402 to write any null into the table.
1403 The second flag is set only if the first flag is set on.
1404 The informs the outer scope that there was an attept to write null
1405 into a field of the table in the context where it is prohibited.
1406 This flag should be set off as soon as the first flag is set on.
1407 Currently these flags are used only the tables tno_rows_with_nulls set
1408 to true.
1409 */
1410 uint8 null_catch_flags;
1411
1412 /*
1413 TODO: Each of the following flags take up 8 bits. They can just as easily
1414 be put into one single unsigned long and instead of taking up 18
1415 bytes, it would take up 4.
1416 */
1417 bool force_index;
1418
1419 /**
1420 Flag set when the statement contains FORCE INDEX FOR ORDER BY
1421 See TABLE_LIST::process_index_hints().
1422 */
1423 bool force_index_order;
1424
1425 /**
1426 Flag set when the statement contains FORCE INDEX FOR GROUP BY
1427 See TABLE_LIST::process_index_hints().
1428 */
1429 bool force_index_group;
1430 /*
1431 TRUE<=> this table was created with create_tmp_table(... distinct=TRUE..)
1432 call
1433 */
1434 bool distinct;
1435 bool const_table,no_rows, used_for_duplicate_elimination;
1436 /**
1437 Forces DYNAMIC Aria row format for internal temporary tables.
1438 */
1439 bool keep_row_order;
1440
1441 bool no_keyread;
1442 /**
1443 If set, indicate that the table is not replicated by the server.
1444 */
1445 bool locked_by_logger;
1446 bool locked_by_name;
1447 bool fulltext_searched;
1448 bool no_cache;
1449 /* To signal that the table is associated with a HANDLER statement */
1450 bool open_by_handler;
1451 /*
1452 To indicate that a non-null value of the auto_increment field
1453 was provided by the user or retrieved from the current record.
1454 Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode.
1455 */
1456 bool auto_increment_field_not_null;
1457 bool insert_or_update; /* Can be used by the handler */
1458 bool alias_name_used; /* true if table_name is alias */
1459 bool get_fields_in_item_tree; /* Signal to fix_field */
1460 private:
1461 bool m_needs_reopen;
1462 bool created; /* For tmp tables. TRUE <=> tmp table was actually created.*/
1463 public:
1464 #ifdef HAVE_REPLICATION
1465 /* used in RBR Triggers */
1466 bool master_had_triggers;
1467 #endif
1468
1469 REGINFO reginfo; /* field connections */
1470 MEM_ROOT mem_root;
1471 /**
1472 Initialized in Item_func_group_concat::setup for appropriate
1473 temporary table if GROUP_CONCAT is used with ORDER BY | DISTINCT
1474 and BLOB field count > 0.
1475 */
1476 Blob_mem_storage *blob_storage;
1477 GRANT_INFO grant;
1478 /*
1479 The arena which the items for expressions from the table definition
1480 are associated with.
1481 Currently only the items of the expressions for virtual columns are
1482 associated with this arena.
1483 TODO: To attach the partitioning expressions to this arena.
1484 */
1485 Query_arena *expr_arena;
1486 #ifdef WITH_PARTITION_STORAGE_ENGINE
1487 partition_info *part_info; /* Partition related information */
1488 /* If true, all partitions have been pruned away */
1489 bool all_partitions_pruned_away;
1490 #endif
1491 uint max_keys; /* Size of allocated key_info array. */
1492 bool stats_is_read; /* Persistent statistics is read for the table */
1493 bool histograms_are_read;
1494 MDL_ticket *mdl_ticket;
1495
1496 /*
1497 This is used only for potentially splittable materialized tables and it
1498 points to the info used by the optimizer to apply splitting optimization
1499 */
1500 SplM_opt_info *spl_opt_info;
1501 key_map keys_usable_for_splitting;
1502
1503
resetTABLE1504 inline void reset() { bzero((void*)this, sizeof(*this)); }
1505 void init(THD *thd, TABLE_LIST *tl);
1506 bool fill_item_list(List<Item> *item_list) const;
1507 void reset_item_list(List<Item> *item_list, uint skip) const;
1508 void clear_column_bitmaps(void);
1509 void prepare_for_position(void);
1510 MY_BITMAP *prepare_for_keyread(uint index, MY_BITMAP *map);
prepare_for_keyreadTABLE1511 MY_BITMAP *prepare_for_keyread(uint index)
1512 { return prepare_for_keyread(index, &tmp_set); }
1513 void mark_index_columns(uint index, MY_BITMAP *bitmap);
1514 void mark_index_columns_no_reset(uint index, MY_BITMAP *bitmap);
1515 void mark_index_columns_for_read(uint index);
1516 void restore_column_maps_after_keyread(MY_BITMAP *backup);
1517 void mark_auto_increment_column(void);
1518 void mark_columns_needed_for_update(void);
1519 void mark_columns_needed_for_delete(void);
1520 void mark_columns_needed_for_insert(void);
1521 void mark_columns_per_binlog_row_image(void);
1522 inline bool mark_column_with_deps(Field *field);
1523 inline bool mark_virtual_column_with_deps(Field *field);
1524 inline void mark_virtual_column_deps(Field *field);
1525 bool mark_virtual_columns_for_write(bool insert_fl);
1526 bool check_virtual_columns_marked_for_read();
1527 bool check_virtual_columns_marked_for_write();
1528 void mark_default_fields_for_write(bool insert_fl);
1529 void mark_columns_used_by_virtual_fields(void);
1530 void mark_check_constraint_columns_for_read(void);
1531 int verify_constraints(bool ignore_failure);
column_bitmaps_setTABLE1532 inline void column_bitmaps_set(MY_BITMAP *read_set_arg)
1533 {
1534 read_set= read_set_arg;
1535 if (file)
1536 file->column_bitmaps_signal();
1537 }
column_bitmaps_setTABLE1538 inline void column_bitmaps_set(MY_BITMAP *read_set_arg,
1539 MY_BITMAP *write_set_arg)
1540 {
1541 read_set= read_set_arg;
1542 write_set= write_set_arg;
1543 if (file)
1544 file->column_bitmaps_signal();
1545 }
column_bitmaps_set_no_signalTABLE1546 inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg,
1547 MY_BITMAP *write_set_arg)
1548 {
1549 read_set= read_set_arg;
1550 write_set= write_set_arg;
1551 }
use_all_columnsTABLE1552 inline void use_all_columns()
1553 {
1554 column_bitmaps_set(&s->all_set, &s->all_set);
1555 }
1556 inline void use_all_stored_columns();
default_column_bitmapsTABLE1557 inline void default_column_bitmaps()
1558 {
1559 read_set= &def_read_set;
1560 write_set= &def_write_set;
1561 rpl_write_set= 0;
1562 }
1563 /** Should this instance of the table be reopened? */
needs_reopenTABLE1564 inline bool needs_reopen()
1565 { return !db_stat || m_needs_reopen; }
1566 /*
1567 Mark that all current connection instances of the table should be
1568 reopen at end of statement
1569 */
1570 void mark_table_for_reopen();
1571 /* Should only be called from Locked_tables_list::mark_table_for_reopen() */
internal_set_needs_reopenTABLE1572 void internal_set_needs_reopen(bool value)
1573 {
1574 m_needs_reopen= value;
1575 }
1576
1577 bool alloc_keys(uint key_count);
1578 bool check_tmp_key(uint key, uint key_parts,
1579 uint (*next_field_no) (uchar *), uchar *arg);
1580 bool add_tmp_key(uint key, uint key_parts,
1581 uint (*next_field_no) (uchar *), uchar *arg,
1582 bool unique);
1583 void create_key_part_by_field(KEY_PART_INFO *key_part_info,
1584 Field *field, uint fieldnr);
1585 void use_index(int key_to_save);
set_table_mapTABLE1586 void set_table_map(table_map map_arg, uint tablenr_arg)
1587 {
1588 map= map_arg;
1589 tablenr= tablenr_arg;
1590 }
1591
1592 /// Return true if table is instantiated, and false otherwise.
is_createdTABLE1593 bool is_created() const { return created; }
1594
1595 /**
1596 Set the table as "created", and enable flags in storage engine
1597 that could not be enabled without an instantiated table.
1598 */
set_createdTABLE1599 void set_created()
1600 {
1601 if (created)
1602 return;
1603 if (file->keyread_enabled())
1604 file->extra(HA_EXTRA_KEYREAD);
1605 created= true;
1606 }
1607
1608 /*
1609 Returns TRUE if the table is filled at execution phase (and so, the
1610 optimizer must not do anything that depends on the contents of the table,
1611 like range analysis or constant table detection)
1612 */
1613 bool is_filled_at_execution();
1614
1615 bool update_const_key_parts(COND *conds);
1616 void initialize_quick_structures();
1617
default_values_offsetTABLE1618 my_ptrdiff_t default_values_offset() const
1619 { return (my_ptrdiff_t) (s->default_values - record[0]); }
1620
1621 void move_fields(Field **ptr, const uchar *to, const uchar *from);
1622 void remember_blob_values(String *blob_storage);
1623 void restore_blob_values(String *blob_storage);
1624
1625 uint actual_n_key_parts(KEY *keyinfo);
1626 ulong actual_key_flags(KEY *keyinfo);
1627 int update_virtual_field(Field *vf);
1628 int update_virtual_fields(handler *h, enum_vcol_update_mode update_mode);
1629 int update_default_fields(bool ignore_errors);
1630 void evaluate_update_default_function();
1631 void reset_default_fields();
stat_recordsTABLE1632 inline ha_rows stat_records() { return used_stat_records; }
1633
1634 void prepare_triggers_for_insert_stmt_or_event();
1635 bool prepare_triggers_for_delete_stmt_or_event();
1636 bool prepare_triggers_for_update_stmt_or_event();
1637
1638 Field **field_to_fill();
1639 bool validate_default_values_of_unset_fields(THD *thd) const;
1640
1641 bool insert_all_rows_into_tmp_table(THD *thd,
1642 TABLE *tmp_table,
1643 TMP_TABLE_PARAM *tmp_table_param,
1644 bool with_cleanup);
1645 int fix_vcol_exprs(THD *thd);
1646 Field *find_field_by_name(LEX_CSTRING *str) const;
1647 bool export_structure(THD *thd, class Row_definition_list *defs);
is_splittableTABLE1648 bool is_splittable() { return spl_opt_info != NULL; }
1649 void set_spl_opt_info(SplM_opt_info *spl_info);
1650 void deny_splitting();
1651 double get_materialization_cost(); // Now used only if is_splittable()==true
1652 void add_splitting_info_for_key_field(struct KEY_FIELD *key_field);
1653
1654 key_map with_impossible_ranges;
1655
1656 /* Number of cost info elements for possible range filters */
1657 uint range_rowid_filter_cost_info_elems;
1658 /* Pointer to the array of cost info elements for range filters */
1659 Range_rowid_filter_cost_info *range_rowid_filter_cost_info;
1660 /* The array of pointers to cost info elements for range filters */
1661 Range_rowid_filter_cost_info **range_rowid_filter_cost_info_ptr;
1662
1663 void init_cost_info_for_usable_range_rowid_filters(THD *thd);
1664 void prune_range_rowid_filters();
1665 void trace_range_rowid_filters(THD *thd) const;
1666 Range_rowid_filter_cost_info *
1667 best_range_rowid_filter_for_partial_join(uint access_key_no,
1668 double records,
1669 double access_cost_factor);
1670
1671 /**
1672 System Versioning support
1673 */
1674 bool vers_write;
1675
versionedTABLE1676 bool versioned() const
1677 {
1678 DBUG_ASSERT(s);
1679 return s->versioned;
1680 }
1681
versionedTABLE1682 bool versioned(vers_sys_type_t type) const
1683 {
1684 DBUG_ASSERT(s);
1685 DBUG_ASSERT(type);
1686 return s->versioned == type;
1687 }
1688
versioned_writeTABLE1689 bool versioned_write() const
1690 {
1691 DBUG_ASSERT(versioned() || !vers_write);
1692 return versioned() ? vers_write : false;
1693 }
1694
versioned_writeTABLE1695 bool versioned_write(vers_sys_type_t type) const
1696 {
1697 DBUG_ASSERT(type);
1698 DBUG_ASSERT(versioned() || !vers_write);
1699 return versioned(type) ? vers_write : false;
1700 }
1701
vers_start_fieldTABLE1702 Field *vers_start_field() const
1703 {
1704 DBUG_ASSERT(s && s->versioned);
1705 return field[s->vers.start_fieldno];
1706 }
1707
vers_end_fieldTABLE1708 Field *vers_end_field() const
1709 {
1710 DBUG_ASSERT(s && s->versioned);
1711 return field[s->vers.end_fieldno];
1712 }
1713
1714 ulonglong vers_start_id() const;
1715 ulonglong vers_end_id() const;
1716
1717 int update_generated_fields();
1718 int period_make_insert(Item *src, Field *dst);
1719 int insert_portion_of_time(THD *thd, const vers_select_conds_t &period_conds,
1720 ha_rows *rows_inserted);
1721 bool vers_check_update(List<Item> &items);
1722
1723 int delete_row();
1724 /* Used in majority of DML (called from fill_record()) */
1725 void vers_update_fields();
1726 /* Used in DELETE, DUP REPLACE and insert history row */
1727 void vers_update_end();
1728 void find_constraint_correlated_indexes();
1729 void clone_handler_for_update();
1730 void delete_update_handler();
1731
1732 /** Number of additional fields used in versioned tables */
1733 #define VERSIONING_FIELDS 2
1734 };
1735
1736
1737 /**
1738 Helper class which specifies which members of TABLE are used for
1739 participation in the list of used/unused TABLE objects for the share.
1740 */
1741
1742 struct TABLE_share
1743 {
next_ptrTABLE_share1744 static inline TABLE **next_ptr(TABLE *l)
1745 {
1746 return &l->next;
1747 }
prev_ptrTABLE_share1748 static inline TABLE ***prev_ptr(TABLE *l)
1749 {
1750 return (TABLE ***) &l->prev;
1751 }
1752 };
1753
1754 struct All_share_tables
1755 {
next_ptrAll_share_tables1756 static inline TABLE **next_ptr(TABLE *l)
1757 {
1758 return &l->share_all_next;
1759 }
prev_ptrAll_share_tables1760 static inline TABLE ***prev_ptr(TABLE *l)
1761 {
1762 return &l->share_all_prev;
1763 }
1764 };
1765
1766 typedef I_P_List <TABLE, All_share_tables> All_share_tables_list;
1767
1768 enum enum_schema_table_state
1769 {
1770 NOT_PROCESSED= 0,
1771 PROCESSED_BY_CREATE_SORT_INDEX,
1772 PROCESSED_BY_JOIN_EXEC
1773 };
1774
1775 enum enum_fk_option { FK_OPTION_UNDEF, FK_OPTION_RESTRICT, FK_OPTION_CASCADE,
1776 FK_OPTION_SET_NULL, FK_OPTION_NO_ACTION, FK_OPTION_SET_DEFAULT};
1777
1778 typedef struct st_foreign_key_info
1779 {
1780 LEX_CSTRING *foreign_id;
1781 LEX_CSTRING *foreign_db;
1782 LEX_CSTRING *foreign_table;
1783 LEX_CSTRING *referenced_db;
1784 LEX_CSTRING *referenced_table;
1785 enum_fk_option update_method;
1786 enum_fk_option delete_method;
1787 LEX_CSTRING *referenced_key_name;
1788 List<LEX_CSTRING> foreign_fields;
1789 List<LEX_CSTRING> referenced_fields;
1790 } FOREIGN_KEY_INFO;
1791
1792 LEX_CSTRING *fk_option_name(enum_fk_option opt);
1793 bool fk_modifies_child(enum_fk_option opt);
1794
1795 #define MY_I_S_MAYBE_NULL 1U
1796 #define MY_I_S_UNSIGNED 2U
1797
1798
1799 #define SKIP_OPEN_TABLE 0U // do not open table
1800 #define OPEN_FRM_ONLY 1U // open FRM file only
1801 #define OPEN_FULL_TABLE 2U // open FRM,MYD, MYI files
1802
1803 typedef struct st_field_info
1804 {
1805 /**
1806 This is used as column name.
1807 */
1808 const char* field_name;
1809 /**
1810 For string-type columns, this is the maximum number of
1811 characters. Otherwise, it is the 'display-length' for the column.
1812 */
1813 uint field_length;
1814 /**
1815 This denotes data type for the column. For the most part, there seems to
1816 be one entry in the enum for each SQL data type, although there seem to
1817 be a number of additional entries in the enum.
1818 */
1819 enum enum_field_types field_type;
1820 int value;
1821 /**
1822 This is used to set column attributes. By default, columns are @c NOT
1823 @c NULL and @c SIGNED, and you can deviate from the default
1824 by setting the appopriate flags. You can use either one of the flags
1825 @c MY_I_S_MAYBE_NULL and @cMY_I_S_UNSIGNED or
1826 combine them using the bitwise or operator @c |. Both flags are
1827 defined in table.h.
1828 */
1829 uint field_flags; // Field atributes(maybe_null, signed, unsigned etc.)
1830 const char* old_name;
1831 /**
1832 This should be one of @c SKIP_OPEN_TABLE,
1833 @c OPEN_FRM_ONLY or @c OPEN_FULL_TABLE.
1834 */
1835 uint open_method;
1836 } ST_FIELD_INFO;
1837
1838
1839 struct TABLE_LIST;
1840 typedef class Item COND;
1841
1842 typedef struct st_schema_table
1843 {
1844 const char *table_name;
1845 ST_FIELD_INFO *fields_info;
1846 /* for FLUSH table_name */
1847 int (*reset_table) ();
1848 /* Fill table with data */
1849 int (*fill_table) (THD *thd, TABLE_LIST *tables, COND *cond);
1850 /* Handle fileds for old SHOW */
1851 int (*old_format) (THD *thd, struct st_schema_table *schema_table);
1852 int (*process_table) (THD *thd, TABLE_LIST *tables, TABLE *table,
1853 bool res, const LEX_CSTRING *db_name,
1854 const LEX_CSTRING *table_name);
1855 int idx_field1, idx_field2;
1856 bool hidden;
1857 uint i_s_requested_object; /* the object we need to open(TABLE | VIEW) */
1858 } ST_SCHEMA_TABLE;
1859
1860 class IS_table_read_plan;
1861
1862 /*
1863 Types of derived tables. The ending part is a bitmap of phases that are
1864 applicable to a derived table of the type.
1865 */
1866 #define DTYPE_ALGORITHM_UNDEFINED 0U
1867 #define DTYPE_VIEW 1U
1868 #define DTYPE_TABLE 2U
1869 #define DTYPE_MERGE 4U
1870 #define DTYPE_MATERIALIZE 8U
1871 #define DTYPE_MULTITABLE 16U
1872 #define DTYPE_MASK (DTYPE_VIEW|DTYPE_TABLE|DTYPE_MULTITABLE)
1873
1874 /*
1875 Phases of derived tables/views handling, see sql_derived.cc
1876 Values are used as parts of a bitmap attached to derived table types.
1877 */
1878 #define DT_INIT 1U
1879 #define DT_PREPARE 2U
1880 #define DT_OPTIMIZE 4U
1881 #define DT_MERGE 8U
1882 #define DT_MERGE_FOR_INSERT 16U
1883 #define DT_CREATE 32U
1884 #define DT_FILL 64U
1885 #define DT_REINIT 128U
1886 #define DT_PHASES 8U
1887 /* Phases that are applicable to all derived tables. */
1888 #define DT_COMMON (DT_INIT + DT_PREPARE + DT_REINIT + DT_OPTIMIZE)
1889 /* Phases that are applicable only to materialized derived tables. */
1890 #define DT_MATERIALIZE (DT_CREATE + DT_FILL)
1891
1892 #define DT_PHASES_MERGE (DT_COMMON | DT_MERGE | DT_MERGE_FOR_INSERT)
1893 #define DT_PHASES_MATERIALIZE (DT_COMMON | DT_MATERIALIZE)
1894
1895 #define VIEW_ALGORITHM_UNDEFINED 0
1896 /* Special value for ALTER VIEW: inherit original algorithm. */
1897 #define VIEW_ALGORITHM_INHERIT DTYPE_VIEW
1898 #define VIEW_ALGORITHM_MERGE (DTYPE_VIEW | DTYPE_MERGE)
1899 #define VIEW_ALGORITHM_TMPTABLE (DTYPE_VIEW | DTYPE_MATERIALIZE)
1900
1901 /*
1902 View algorithm values as stored in the FRM. Values differ from in-memory
1903 representation for backward compatibility.
1904 */
1905
1906 #define VIEW_ALGORITHM_UNDEFINED_FRM 0U
1907 #define VIEW_ALGORITHM_MERGE_FRM 1U
1908 #define VIEW_ALGORITHM_TMPTABLE_FRM 2U
1909
1910 #define JOIN_TYPE_LEFT 1U
1911 #define JOIN_TYPE_RIGHT 2U
1912 #define JOIN_TYPE_OUTER 4U /* Marker that this is an outer join */
1913
1914 /* view WITH CHECK OPTION parameter options */
1915 #define VIEW_CHECK_NONE 0
1916 #define VIEW_CHECK_LOCAL 1
1917 #define VIEW_CHECK_CASCADED 2
1918
1919 /* result of view WITH CHECK OPTION parameter check */
1920 #define VIEW_CHECK_OK 0
1921 #define VIEW_CHECK_ERROR 1
1922 #define VIEW_CHECK_SKIP 2
1923
1924 /** The threshold size a blob field buffer before it is freed */
1925 #define MAX_TDC_BLOB_SIZE 65536
1926
1927 /** number of bytes used by field positional indexes in frm */
1928 constexpr uint frm_fieldno_size= 2;
read_frm_fieldno(const uchar * data)1929 static inline uint16 read_frm_fieldno(const uchar *data)
1930 { return uint2korr(data); }
store_frm_fieldno(const uchar * data,uint16 fieldno)1931 static inline void store_frm_fieldno(const uchar *data, uint16 fieldno)
1932 { int2store(data, fieldno); }
1933
1934 class select_unit;
1935 class TMP_TABLE_PARAM;
1936
1937 Item *create_view_field(THD *thd, TABLE_LIST *view, Item **field_ref,
1938 LEX_CSTRING *name);
1939
1940 struct Field_translator
1941 {
1942 Item *item;
1943 LEX_CSTRING name;
1944 };
1945
1946
1947 /*
1948 Column reference of a NATURAL/USING join. Since column references in
1949 joins can be both from views and stored tables, may point to either a
1950 Field (for tables), or a Field_translator (for views).
1951 */
1952
1953 class Natural_join_column: public Sql_alloc
1954 {
1955 public:
1956 Field_translator *view_field; /* Column reference of merge view. */
1957 Item_field *table_field; /* Column reference of table or temp view. */
1958 TABLE_LIST *table_ref; /* Original base table/view reference. */
1959 /*
1960 True if a common join column of two NATURAL/USING join operands. Notice
1961 that when we have a hierarchy of nested NATURAL/USING joins, a column can
1962 be common at some level of nesting but it may not be common at higher
1963 levels of nesting. Thus this flag may change depending on at which level
1964 we are looking at some column.
1965 */
1966 bool is_common;
1967 public:
1968 Natural_join_column(Field_translator *field_param, TABLE_LIST *tab);
1969 Natural_join_column(Item_field *field_param, TABLE_LIST *tab);
1970 LEX_CSTRING *name();
1971 Item *create_item(THD *thd);
1972 Field *field();
1973 const char *safe_table_name();
1974 const char *safe_db_name();
1975 GRANT_INFO *grant();
1976 };
1977
1978
1979 /**
1980 Type of table which can be open for an element of table list.
1981 */
1982
1983 enum enum_open_type
1984 {
1985 OT_TEMPORARY_OR_BASE= 0, OT_TEMPORARY_ONLY, OT_BASE_ONLY
1986 };
1987
1988
1989 class SJ_MATERIALIZATION_INFO;
1990 class Index_hint;
1991 class Item_in_subselect;
1992
1993 /* trivial class, for %union in sql_yacc.yy */
1994 struct vers_history_point_t
1995 {
1996 vers_sys_type_t unit;
1997 Item *item;
1998 };
1999
2000 class Vers_history_point : public vers_history_point_t
2001 {
2002 void fix_item();
2003
2004 public:
Vers_history_point()2005 Vers_history_point() { empty(); }
Vers_history_point(vers_sys_type_t unit_arg,Item * item_arg)2006 Vers_history_point(vers_sys_type_t unit_arg, Item *item_arg)
2007 {
2008 unit= unit_arg;
2009 item= item_arg;
2010 fix_item();
2011 }
Vers_history_point(vers_history_point_t p)2012 Vers_history_point(vers_history_point_t p)
2013 {
2014 unit= p.unit;
2015 item= p.item;
2016 fix_item();
2017 }
empty()2018 void empty() { unit= VERS_UNDEFINED; item= NULL; }
2019 void print(String *str, enum_query_type, const char *prefix, size_t plen) const;
2020 bool resolve_unit(THD *thd);
resolve_unit_trx_id(THD * thd)2021 bool resolve_unit_trx_id(THD *thd)
2022 {
2023 if (unit == VERS_UNDEFINED)
2024 unit= VERS_TRX_ID;
2025 return false;
2026 }
resolve_unit_timestamp(THD * thd)2027 bool resolve_unit_timestamp(THD *thd)
2028 {
2029 if (unit == VERS_UNDEFINED)
2030 unit= VERS_TIMESTAMP;
2031 return false;
2032 }
2033 void bad_expression_data_type_error(const char *type) const;
2034 bool eq(const vers_history_point_t &point) const;
2035 };
2036
2037 struct vers_select_conds_t
2038 {
2039 vers_system_time_t type;
2040 vers_system_time_t orig_type;
2041 bool used:1;
2042 bool delete_history:1;
2043 Vers_history_point start;
2044 Vers_history_point end;
2045 Lex_ident name;
2046
2047 Item_field *field_start;
2048 Item_field *field_end;
2049
2050 const TABLE_SHARE::period_info_t *period;
2051
emptyvers_select_conds_t2052 void empty()
2053 {
2054 type= SYSTEM_TIME_UNSPECIFIED;
2055 orig_type= SYSTEM_TIME_UNSPECIFIED;
2056 used= false;
2057 delete_history= false;
2058 start.empty();
2059 end.empty();
2060 }
2061
2062 void init(vers_system_time_t _type,
2063 Vers_history_point _start= Vers_history_point(),
2064 Vers_history_point _end= Vers_history_point(),
2065 Lex_ident _name= "SYSTEM_TIME")
2066 {
2067 type= _type;
2068 orig_type= _type;
2069 used= false;
2070 delete_history= (type == SYSTEM_TIME_HISTORY ||
2071 type == SYSTEM_TIME_BEFORE);
2072 start= _start;
2073 end= _end;
2074 name= _name;
2075 }
2076
set_allvers_select_conds_t2077 void set_all()
2078 {
2079 type= SYSTEM_TIME_ALL;
2080 name= "SYSTEM_TIME";
2081 }
2082
2083 void print(String *str, enum_query_type query_type) const;
2084
2085 bool init_from_sysvar(THD *thd);
2086
is_setvers_select_conds_t2087 bool is_set() const
2088 {
2089 return type != SYSTEM_TIME_UNSPECIFIED;
2090 }
was_setvers_select_conds_t2091 bool was_set() const
2092 {
2093 return orig_type != SYSTEM_TIME_UNSPECIFIED;
2094 }
need_setupvers_select_conds_t2095 bool need_setup() const
2096 {
2097 return type != SYSTEM_TIME_UNSPECIFIED && type != SYSTEM_TIME_ALL;
2098 }
2099 bool resolve_units(THD *thd);
2100 bool eq(const vers_select_conds_t &conds) const;
2101 };
2102
2103 /*
2104 Table reference in the FROM clause.
2105
2106 These table references can be of several types that correspond to
2107 different SQL elements. Below we list all types of TABLE_LISTs with
2108 the necessary conditions to determine when a TABLE_LIST instance
2109 belongs to a certain type.
2110
2111 1) table (TABLE_LIST::view == NULL)
2112 - base table
2113 (TABLE_LIST::derived == NULL)
2114 - FROM-clause subquery - TABLE_LIST::table is a temp table
2115 (TABLE_LIST::derived != NULL)
2116 - information schema table
2117 (TABLE_LIST::schema_table != NULL)
2118 NOTICE: for schema tables TABLE_LIST::field_translation may be != NULL
2119 2) view (TABLE_LIST::view != NULL)
2120 - merge (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_MERGE)
2121 also (TABLE_LIST::field_translation != NULL)
2122 - tmptable (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_TMPTABLE)
2123 also (TABLE_LIST::field_translation == NULL)
2124 2.5) TODO: Add derived tables description here
2125 3) nested table reference (TABLE_LIST::nested_join != NULL)
2126 - table sequence - e.g. (t1, t2, t3)
2127 TODO: how to distinguish from a JOIN?
2128 - general JOIN
2129 TODO: how to distinguish from a table sequence?
2130 - NATURAL JOIN
2131 (TABLE_LIST::natural_join != NULL)
2132 - JOIN ... USING
2133 (TABLE_LIST::join_using_fields != NULL)
2134 - semi-join nest (sj_on_expr!= NULL && sj_subq_pred!=NULL)
2135 4) jtbm semi-join (jtbm_subselect != NULL)
2136 */
2137
2138 /** last_leaf_for_name_resolutioning support. */
2139
2140 struct LEX;
2141 class Index_hint;
2142
2143 /*
2144 @struct TABLE_CHAIN
2145 @brief Subchain of global chain of table references
2146
2147 The structure contains a pointer to the address of the next_global
2148 pointer to the first TABLE_LIST objectof the subchain and the address
2149 of the next_global pointer to the element right after the last
2150 TABLE_LIST object of the subchain. For an empty subchain both pointers
2151 have the same value.
2152 */
2153
2154 struct TABLE_CHAIN
2155 {
TABLE_CHAINTABLE_CHAIN2156 TABLE_CHAIN() {}
2157
2158 TABLE_LIST **start_pos;
2159 TABLE_LIST ** end_pos;
2160
set_start_posTABLE_CHAIN2161 void set_start_pos(TABLE_LIST **pos) { start_pos= pos; }
set_end_posTABLE_CHAIN2162 void set_end_pos(TABLE_LIST **pos) { end_pos= pos; }
2163 };
2164
2165 struct TABLE_LIST
2166 {
TABLE_LISTTABLE_LIST2167 TABLE_LIST() {} /* Remove gcc warning */
2168
2169 enum prelocking_types
2170 {
2171 PRELOCK_NONE, PRELOCK_ROUTINE, PRELOCK_FK
2172 };
2173
2174 /**
2175 Prepare TABLE_LIST that consists of one table instance to use in
2176 open_and_lock_tables
2177 */
resetTABLE_LIST2178 inline void reset() { bzero((void*)this, sizeof(*this)); }
init_one_tableTABLE_LIST2179 inline void init_one_table(const LEX_CSTRING *db_arg,
2180 const LEX_CSTRING *table_name_arg,
2181 const LEX_CSTRING *alias_arg,
2182 enum thr_lock_type lock_type_arg)
2183 {
2184 enum enum_mdl_type mdl_type;
2185 if (lock_type_arg >= TL_WRITE_ALLOW_WRITE)
2186 mdl_type= MDL_SHARED_WRITE;
2187 else if (lock_type_arg == TL_READ_NO_INSERT)
2188 mdl_type= MDL_SHARED_NO_WRITE;
2189 else
2190 mdl_type= MDL_SHARED_READ;
2191
2192 reset();
2193 DBUG_ASSERT(!db_arg->str || strlen(db_arg->str) == db_arg->length);
2194 DBUG_ASSERT(!table_name_arg->str || strlen(table_name_arg->str) == table_name_arg->length);
2195 DBUG_ASSERT(!alias_arg || strlen(alias_arg->str) == alias_arg->length);
2196 db= *db_arg;
2197 table_name= *table_name_arg;
2198 alias= (alias_arg ? *alias_arg : *table_name_arg);
2199 lock_type= lock_type_arg;
2200 updating= lock_type >= TL_WRITE_ALLOW_WRITE;
2201 mdl_request.init(MDL_key::TABLE, db.str, table_name.str, mdl_type,
2202 MDL_TRANSACTION);
2203 }
2204
TABLE_LISTTABLE_LIST2205 TABLE_LIST(TABLE *table_arg, thr_lock_type lock_type)
2206 {
2207 DBUG_ASSERT(table_arg->s);
2208 init_one_table(&table_arg->s->db, &table_arg->s->table_name,
2209 NULL, lock_type);
2210 table= table_arg;
2211 vers_conditions.name= table->s->vers.name;
2212 }
2213
init_one_table_for_prelockingTABLE_LIST2214 inline void init_one_table_for_prelocking(const LEX_CSTRING *db_arg,
2215 const LEX_CSTRING *table_name_arg,
2216 const LEX_CSTRING *alias_arg,
2217 enum thr_lock_type lock_type_arg,
2218 prelocking_types prelocking_type,
2219 TABLE_LIST *belong_to_view_arg,
2220 uint8 trg_event_map_arg,
2221 TABLE_LIST ***last_ptr,
2222 my_bool insert_data)
2223
2224 {
2225 init_one_table(db_arg, table_name_arg, alias_arg, lock_type_arg);
2226 cacheable_table= 1;
2227 prelocking_placeholder= prelocking_type;
2228 open_type= (prelocking_type == PRELOCK_ROUTINE ?
2229 OT_TEMPORARY_OR_BASE :
2230 OT_BASE_ONLY);
2231 belong_to_view= belong_to_view_arg;
2232 trg_event_map= trg_event_map_arg;
2233 /* MDL is enough for read-only FK checks, we don't need the table */
2234 if (prelocking_type == PRELOCK_FK && lock_type < TL_WRITE_ALLOW_WRITE)
2235 open_strategy= OPEN_STUB;
2236
2237 **last_ptr= this;
2238 prev_global= *last_ptr;
2239 *last_ptr= &next_global;
2240 for_insert_data= insert_data;
2241 }
2242
2243
2244 /*
2245 List of tables local to a subquery (used by SQL_I_List). Considers
2246 views as leaves (unlike 'next_leaf' below). Created at parse time
2247 in st_select_lex::add_table_to_list() -> table_list.link_in_list().
2248 */
2249 TABLE_LIST *next_local;
2250 /* link in a global list of all queries tables */
2251 TABLE_LIST *next_global, **prev_global;
2252 LEX_CSTRING db;
2253 LEX_CSTRING table_name;
2254 LEX_CSTRING schema_table_name;
2255 LEX_CSTRING alias;
2256 const char *option; /* Used by cache index */
2257 Item *on_expr; /* Used with outer join */
2258 Name_resolution_context *on_context; /* For ON expressions */
2259
2260 Item *sj_on_expr;
2261 /*
2262 (Valid only for semi-join nests) Bitmap of tables that are within the
2263 semi-join (this is different from bitmap of all nest's children because
2264 tables that were pulled out of the semi-join nest remain listed as
2265 nest's children).
2266 */
2267 table_map sj_inner_tables;
2268 /* Number of IN-compared expressions */
2269 uint sj_in_exprs;
2270
2271 /* If this is a non-jtbm semi-join nest: corresponding subselect predicate */
2272 Item_in_subselect *sj_subq_pred;
2273
2274 table_map original_subq_pred_used_tables;
2275
2276 /* If this is a jtbm semi-join object: corresponding subselect predicate */
2277 Item_in_subselect *jtbm_subselect;
2278 /* TODO: check if this can be joined with tablenr_exec */
2279 uint jtbm_table_no;
2280
2281 SJ_MATERIALIZATION_INFO *sj_mat_info;
2282
2283 /*
2284 The structure of ON expression presented in the member above
2285 can be changed during certain optimizations. This member
2286 contains a snapshot of AND-OR structure of the ON expression
2287 made after permanent transformations of the parse tree, and is
2288 used to restore ON clause before every reexecution of a prepared
2289 statement or stored procedure.
2290 */
2291 Item *prep_on_expr;
2292 COND_EQUAL *cond_equal; /* Used with outer join */
2293 /*
2294 During parsing - left operand of NATURAL/USING join where 'this' is
2295 the right operand. After parsing (this->natural_join == this) iff
2296 'this' represents a NATURAL or USING join operation. Thus after
2297 parsing 'this' is a NATURAL/USING join iff (natural_join != NULL).
2298 */
2299 TABLE_LIST *natural_join;
2300 /*
2301 True if 'this' represents a nested join that is a NATURAL JOIN.
2302 For one of the operands of 'this', the member 'natural_join' points
2303 to the other operand of 'this'.
2304 */
2305 bool is_natural_join;
2306 /* Field names in a USING clause for JOIN ... USING. */
2307 List<String> *join_using_fields;
2308 /*
2309 Explicitly store the result columns of either a NATURAL/USING join or
2310 an operand of such a join.
2311 */
2312 List<Natural_join_column> *join_columns;
2313 /* TRUE if join_columns contains all columns of this table reference. */
2314 bool is_join_columns_complete;
2315
2316 /*
2317 List of nodes in a nested join tree, that should be considered as
2318 leaves with respect to name resolution. The leaves are: views,
2319 top-most nodes representing NATURAL/USING joins, subqueries, and
2320 base tables. All of these TABLE_LIST instances contain a
2321 materialized list of columns. The list is local to a subquery.
2322 */
2323 TABLE_LIST *next_name_resolution_table;
2324 /* Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */
2325 List<Index_hint> *index_hints;
2326 TABLE *table; /* opened table */
2327 ulonglong table_id; /* table id (from binlog) for opened table */
2328 /*
2329 select_result for derived table to pass it from table creation to table
2330 filling procedure
2331 */
2332 select_unit *derived_result;
2333 /* Stub used for materialized derived tables. */
2334 table_map map; /* ID bit of table (1,2,4,8,16...) */
get_mapTABLE_LIST2335 table_map get_map()
2336 {
2337 return jtbm_subselect? table_map(1) << jtbm_table_no : table->map;
2338 }
get_tablenrTABLE_LIST2339 uint get_tablenr()
2340 {
2341 return jtbm_subselect? jtbm_table_no : table->tablenr;
2342 }
set_tablenrTABLE_LIST2343 void set_tablenr(uint new_tablenr)
2344 {
2345 if (jtbm_subselect)
2346 {
2347 jtbm_table_no= new_tablenr;
2348 }
2349 if (table)
2350 {
2351 table->tablenr= new_tablenr;
2352 table->map= table_map(1) << new_tablenr;
2353 }
2354 }
2355 /*
2356 Reference from aux_tables to local list entry of main select of
2357 multi-delete statement:
2358 delete t1 from t2,t1 where t1.a<'B' and t2.b=t1.b;
2359 here it will be reference of first occurrence of t1 to second (as you
2360 can see this lists can't be merged)
2361 */
2362 TABLE_LIST *correspondent_table;
2363 /**
2364 @brief Normally, this field is non-null for anonymous derived tables only.
2365
2366 @details This field is set to non-null for
2367
2368 - Anonymous derived tables, In this case it points to the SELECT_LEX_UNIT
2369 representing the derived table. E.g. for a query
2370
2371 @verbatim SELECT * FROM (SELECT a FROM t1) b @endverbatim
2372
2373 For the @c TABLE_LIST representing the derived table @c b, @c derived
2374 points to the SELECT_LEX_UNIT representing the result of the query within
2375 parenteses.
2376
2377 - Views. This is set for views with @verbatim ALGORITHM = TEMPTABLE
2378 @endverbatim by mysql_make_view().
2379
2380 @note Inside views, a subquery in the @c FROM clause is not allowed.
2381 @note Do not use this field to separate views/base tables/anonymous
2382 derived tables. Use TABLE_LIST::is_anonymous_derived_table().
2383 */
2384 st_select_lex_unit *derived; /* SELECT_LEX_UNIT of derived table */
2385 With_element *with; /* With element defining this table (if any) */
2386 /* Bitmap of the defining with element */
2387 table_map with_internal_reference_map;
2388 TABLE_LIST * next_with_rec_ref;
2389 bool is_derived_with_recursive_reference;
2390 bool block_handle_derived;
2391 /* The interface employed to materialize the table by a foreign engine */
2392 derived_handler *dt_handler;
2393 /* The text of the query specifying the derived table */
2394 LEX_CSTRING derived_spec;
2395 /*
2396 The object used to organize execution of the query that specifies
2397 the derived table by a foreign engine
2398 */
2399 Pushdown_derived *pushdown_derived;
2400 ST_SCHEMA_TABLE *schema_table; /* Information_schema table */
2401 st_select_lex *schema_select_lex;
2402 /*
2403 True when the view field translation table is used to convert
2404 schema table fields for backwards compatibility with SHOW command.
2405 */
2406 bool schema_table_reformed;
2407 TMP_TABLE_PARAM *schema_table_param;
2408 /* link to select_lex where this table was used */
2409 st_select_lex *select_lex;
2410 LEX *view; /* link on VIEW lex for merging */
2411 Field_translator *field_translation; /* array of VIEW fields */
2412 /* pointer to element after last one in translation table above */
2413 Field_translator *field_translation_end;
2414 bool field_translation_updated;
2415 /*
2416 List (based on next_local) of underlying tables of this view. I.e. it
2417 does not include the tables of subqueries used in the view. Is set only
2418 for merged views.
2419 */
2420 TABLE_LIST *merge_underlying_list;
2421 /*
2422 - 0 for base tables
2423 - in case of the view it is the list of all (not only underlying
2424 tables but also used in subquery ones) tables of the view.
2425 */
2426 List<TABLE_LIST> *view_tables;
2427 /* most upper view this table belongs to */
2428 TABLE_LIST *belong_to_view;
2429 /* A derived table this table belongs to */
2430 TABLE_LIST *belong_to_derived;
2431 /*
2432 The view directly referencing this table
2433 (non-zero only for merged underlying tables of a view).
2434 */
2435 TABLE_LIST *referencing_view;
2436
2437 table_map view_used_tables;
2438 table_map map_exec;
2439 /* TODO: check if this can be joined with jtbm_table_no */
2440 uint tablenr_exec;
2441 uint maybe_null_exec;
2442
2443 /* Ptr to parent MERGE table list item. See top comment in ha_myisammrg.cc */
2444 TABLE_LIST *parent_l;
2445 /*
2446 Security context (non-zero only for tables which belong
2447 to view with SQL SECURITY DEFINER)
2448 */
2449 Security_context *security_ctx;
2450 /*
2451 This view security context (non-zero only for views with
2452 SQL SECURITY DEFINER)
2453 */
2454 Security_context *view_sctx;
2455 bool allowed_show;
2456 Item *where; /* VIEW WHERE clause condition */
2457 Item *check_option; /* WITH CHECK OPTION condition */
2458 LEX_STRING select_stmt; /* text of (CREATE/SELECT) statement */
2459 LEX_CSTRING md5; /* md5 of query text */
2460 LEX_CSTRING source; /* source of CREATE VIEW */
2461 LEX_CSTRING view_db; /* saved view database */
2462 LEX_CSTRING view_name; /* saved view name */
2463 LEX_STRING timestamp; /* GMT time stamp of last operation */
2464 LEX_USER definer; /* definer of view */
2465 ulonglong file_version; /* version of file's field set */
2466 ulonglong mariadb_version; /* version of server on creation */
2467 ulonglong updatable_view; /* VIEW can be updated */
2468 /**
2469 @brief The declared algorithm, if this is a view.
2470 @details One of
2471 - VIEW_ALGORITHM_UNDEFINED
2472 - VIEW_ALGORITHM_TMPTABLE
2473 - VIEW_ALGORITHM_MERGE
2474 @to do Replace with an enum
2475 */
2476 ulonglong algorithm;
2477 ulonglong view_suid; /* view is suid (TRUE dy default) */
2478 ulonglong with_check; /* WITH CHECK OPTION */
2479 /*
2480 effective value of WITH CHECK OPTION (differ for temporary table
2481 algorithm)
2482 */
2483 uint8 effective_with_check;
2484 /**
2485 @brief The view algorithm that is actually used, if this is a view.
2486 @details One of
2487 - VIEW_ALGORITHM_UNDEFINED
2488 - VIEW_ALGORITHM_TMPTABLE
2489 - VIEW_ALGORITHM_MERGE
2490 @to do Replace with an enum
2491 */
2492 uint8 derived_type;
2493 GRANT_INFO grant;
2494 /* data need by some engines in query cache*/
2495 ulonglong engine_data;
2496 /* call back function for asking handler about caching in query cache */
2497 qc_engine_callback callback_func;
2498 thr_lock_type lock_type;
2499
2500 /*
2501 Two fields below are set during parsing this table reference in the cases
2502 when the table reference can be potentially a reference to a CTE table.
2503 In this cases the fact that the reference is a reference to a CTE or not
2504 will be ascertained at the very end of parsing of the query when referencies
2505 to CTE are resolved. For references to CTE and to derived tables no mdl
2506 requests are needed while for other table references they are. If a request
2507 is possibly postponed the info that allows to issue this request must be
2508 saved in 'mdl_type' and 'table_options'.
2509 */
2510 enum_mdl_type mdl_type;
2511 ulong table_options;
2512
2513 uint outer_join; /* Which join type */
2514 uint shared; /* Used in multi-upd */
2515 bool updatable; /* VIEW/TABLE can be updated now */
2516 bool straight; /* optimize with prev table */
2517 bool updating; /* for replicate-do/ignore table */
2518 bool force_index; /* prefer index over table scan */
2519 bool ignore_leaves; /* preload only non-leaf nodes */
2520 bool crashed; /* Table was found crashed */
2521 table_map dep_tables; /* tables the table depends on */
2522 table_map on_expr_dep_tables; /* tables on expression depends on */
2523 struct st_nested_join *nested_join; /* if the element is a nested join */
2524 TABLE_LIST *embedding; /* nested join containing the table */
2525 List<TABLE_LIST> *join_list;/* join list the table belongs to */
2526 bool lifted; /* set to true when the table is moved to
2527 the upper level at the parsing stage */
2528 bool cacheable_table; /* stop PS caching */
2529 /* used in multi-upd/views privilege check */
2530 bool table_in_first_from_clause;
2531 /**
2532 Specifies which kind of table should be open for this element
2533 of table list.
2534 */
2535 enum enum_open_type open_type;
2536 /* TRUE if this merged view contain auto_increment field */
2537 bool contain_auto_increment;
2538 bool compact_view_format; /* Use compact format for SHOW CREATE VIEW */
2539 /* view where processed */
2540 bool where_processed;
2541 /* TRUE <=> VIEW CHECK OPTION expression has been processed */
2542 bool check_option_processed;
2543 /* TABLE_TYPE_UNKNOWN if any type is acceptable */
2544 Table_type required_type;
2545 handlerton *db_type; /* table_type for handler */
2546 char timestamp_buffer[MAX_DATETIME_WIDTH + 1];
2547 /*
2548 This TABLE_LIST object is just placeholder for prelocking, it will be
2549 used for implicit LOCK TABLES only and won't be used in real statement.
2550 */
2551 prelocking_types prelocking_placeholder;
2552 /**
2553 Indicates that if TABLE_LIST object corresponds to the table/view
2554 which requires special handling.
2555 */
2556 enum enum_open_strategy
2557 {
2558 /* Normal open. */
2559 OPEN_NORMAL= 0,
2560 /* Associate a table share only if the the table exists. */
2561 OPEN_IF_EXISTS,
2562 /* Don't associate a table share. */
2563 OPEN_STUB
2564 } open_strategy;
2565 /** TRUE if an alias for this table was specified in the SQL. */
2566 bool is_alias;
2567 /** TRUE if the table is referred to in the statement using a fully
2568 qualified name (<db_name>.<table_name>).
2569 */
2570 bool is_fqtn;
2571
2572 /* TRUE <=> derived table should be filled right after optimization. */
2573 bool fill_me;
2574 /* TRUE <=> view/DT is merged. */
2575 /* TODO: replace with derived_type */
2576 bool merged;
2577 bool merged_for_insert;
2578 bool sequence; /* Part of NEXTVAL/CURVAL/LASTVAL */
2579
2580 /*
2581 Items created by create_view_field and collected to change them in case
2582 of materialization of the view/derived table
2583 */
2584 List<Item> used_items;
2585 /* Sublist (tail) of persistent used_items */
2586 List<Item> persistent_used_items;
2587
2588 /* View creation context. */
2589
2590 View_creation_ctx *view_creation_ctx;
2591
2592 /*
2593 Attributes to save/load view creation context in/from frm-file.
2594
2595 Ther are required only to be able to use existing parser to load
2596 view-definition file. As soon as the parser parsed the file, view
2597 creation context is initialized and the attributes become redundant.
2598
2599 These attributes MUST NOT be used for any purposes but the parsing.
2600 */
2601
2602 LEX_CSTRING view_client_cs_name;
2603 LEX_CSTRING view_connection_cl_name;
2604
2605 /*
2606 View definition (SELECT-statement) in the UTF-form.
2607 */
2608
2609 LEX_CSTRING view_body_utf8;
2610
2611 /* End of view definition context. */
2612
2613 /**
2614 Indicates what triggers we need to pre-load for this TABLE_LIST
2615 when opening an associated TABLE. This is filled after
2616 the parsed tree is created.
2617
2618 slave_fk_event_map is filled on the slave side with bitmaps value
2619 representing row-based event operation to help find and prelock
2620 possible FK constrain-related child tables.
2621 */
2622 uint8 trg_event_map, slave_fk_event_map;
2623 /* TRUE <=> this table is a const one and was optimized away. */
2624 bool optimized_away;
2625
2626 /**
2627 TRUE <=> already materialized. Valid only for materialized derived
2628 tables/views.
2629 */
2630 bool materialized;
2631 /* I_S: Flags to open_table (e.g. OPEN_TABLE_ONLY or OPEN_VIEW_ONLY) */
2632 uint i_s_requested_object;
2633
2634 bool prohibit_cond_pushdown;
2635
2636 /*
2637 I_S: how to read the tables (SKIP_OPEN_TABLE/OPEN_FRM_ONLY/OPEN_FULL_TABLE)
2638 */
2639 uint table_open_method;
2640 /*
2641 I_S: where the schema table was filled
2642 (this is a hack. The code should be able to figure out whether reading
2643 from I_S should be done by create_sort_index() or by JOIN::exec.)
2644 */
2645 enum enum_schema_table_state schema_table_state;
2646
2647 /* Something like a "query plan" for reading INFORMATION_SCHEMA table */
2648 IS_table_read_plan *is_table_read_plan;
2649
2650 MDL_request mdl_request;
2651
2652 #ifdef WITH_PARTITION_STORAGE_ENGINE
2653 /* List to carry partition names from PARTITION (...) clause in statement */
2654 List<String> *partition_names;
2655 #endif /* WITH_PARTITION_STORAGE_ENGINE */
2656
2657 void calc_md5(char *buffer);
2658 int view_check_option(THD *thd, bool ignore_failure);
2659 bool create_field_translation(THD *thd);
2660 bool setup_underlying(THD *thd);
2661 void cleanup_items();
placeholderTABLE_LIST2662 bool placeholder()
2663 {
2664 return derived || view || schema_table || !table;
2665 }
2666 void print(THD *thd, table_map eliminated_tables, String *str,
2667 enum_query_type query_type);
2668 bool check_single_table(TABLE_LIST **table, table_map map,
2669 TABLE_LIST *view);
2670 bool set_insert_values(MEM_ROOT *mem_root);
2671 void hide_view_error(THD *thd);
2672 TABLE_LIST *find_underlying_table(TABLE *table);
2673 TABLE_LIST *first_leaf_for_name_resolution();
2674 TABLE_LIST *last_leaf_for_name_resolution();
2675
2676 /* System Versioning */
2677 vers_select_conds_t vers_conditions;
2678 vers_select_conds_t period_conditions;
2679
has_periodTABLE_LIST2680 bool has_period() const
2681 {
2682 return period_conditions.is_set();
2683 }
2684
2685 my_bool for_insert_data;
2686
2687 /**
2688 @brief
2689 Find the bottom in the chain of embedded table VIEWs.
2690
2691 @detail
2692 This is used for single-table UPDATE/DELETE when they are modifying a
2693 single-table VIEW.
2694 */
find_table_for_updateTABLE_LIST2695 TABLE_LIST *find_table_for_update()
2696 {
2697 TABLE_LIST *tbl= this;
2698 while(!tbl->is_multitable() && tbl->single_table_updatable() &&
2699 tbl->merge_underlying_list)
2700 {
2701 tbl= tbl->merge_underlying_list;
2702 }
2703 return tbl;
2704 }
2705 TABLE *get_real_join_table();
2706 bool is_leaf_for_name_resolution();
top_tableTABLE_LIST2707 inline TABLE_LIST *top_table()
2708 { return belong_to_view ? belong_to_view : this; }
prepare_check_optionTABLE_LIST2709 inline bool prepare_check_option(THD *thd)
2710 {
2711 bool res= FALSE;
2712 if (effective_with_check)
2713 res= prep_check_option(thd, effective_with_check);
2714 return res;
2715 }
prepare_whereTABLE_LIST2716 inline bool prepare_where(THD *thd, Item **conds,
2717 bool no_where_clause)
2718 {
2719 if (!view || is_merged_derived())
2720 return prep_where(thd, conds, no_where_clause);
2721 return FALSE;
2722 }
2723
2724 void register_want_access(ulong want_access);
2725 bool prepare_security(THD *thd);
2726 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2727 Security_context *find_view_security_context(THD *thd);
2728 bool prepare_view_security_context(THD *thd);
2729 #endif
2730 /*
2731 Cleanup for re-execution in a prepared statement or a stored
2732 procedure.
2733 */
2734 void reinit_before_use(THD *thd);
2735 Item_subselect *containing_subselect();
2736
2737 /*
2738 Compiles the tagged hints list and fills up TABLE::keys_in_use_for_query,
2739 TABLE::keys_in_use_for_group_by, TABLE::keys_in_use_for_order_by,
2740 TABLE::force_index and TABLE::covering_keys.
2741 */
2742 bool process_index_hints(TABLE *table);
2743
2744 /**
2745 Compare the version of metadata from the previous execution
2746 (if any) with values obtained from the current table
2747 definition cache element.
2748
2749 @sa check_and_update_table_version()
2750 */
is_table_ref_id_equalTABLE_LIST2751 inline bool is_table_ref_id_equal(TABLE_SHARE *s) const
2752 {
2753 return (m_table_ref_type == s->get_table_ref_type() &&
2754 m_table_ref_version == s->get_table_ref_version());
2755 }
2756
2757 /**
2758 Record the value of metadata version of the corresponding
2759 table definition cache element in this parse tree node.
2760
2761 @sa check_and_update_table_version()
2762 */
set_table_ref_idTABLE_LIST2763 inline void set_table_ref_id(TABLE_SHARE *s)
2764 { set_table_ref_id(s->get_table_ref_type(), s->get_table_ref_version()); }
2765
set_table_ref_idTABLE_LIST2766 inline void set_table_ref_id(enum_table_ref_type table_ref_type_arg,
2767 ulong table_ref_version_arg)
2768 {
2769 m_table_ref_type= table_ref_type_arg;
2770 m_table_ref_version= table_ref_version_arg;
2771 }
2772
2773 /* Set of functions returning/setting state of a derived table/view. */
is_non_derivedTABLE_LIST2774 inline bool is_non_derived()
2775 {
2776 return (!derived_type);
2777 }
is_view_or_derivedTABLE_LIST2778 inline bool is_view_or_derived()
2779 {
2780 return (derived_type);
2781 }
is_viewTABLE_LIST2782 inline bool is_view()
2783 {
2784 return (derived_type & DTYPE_VIEW);
2785 }
is_derivedTABLE_LIST2786 inline bool is_derived()
2787 {
2788 return (derived_type & DTYPE_TABLE);
2789 }
2790 bool is_with_table();
2791 bool is_recursive_with_table();
2792 bool is_with_table_recursive_reference();
2793 void register_as_derived_with_rec_ref(With_element *rec_elem);
2794 bool is_nonrecursive_derived_with_rec_ref();
2795 bool fill_recursive(THD *thd);
2796
set_viewTABLE_LIST2797 inline void set_view()
2798 {
2799 derived_type= DTYPE_VIEW;
2800 }
set_derivedTABLE_LIST2801 inline void set_derived()
2802 {
2803 derived_type= DTYPE_TABLE;
2804 }
is_merged_derivedTABLE_LIST2805 inline bool is_merged_derived()
2806 {
2807 return (derived_type & DTYPE_MERGE);
2808 }
set_merged_derivedTABLE_LIST2809 inline void set_merged_derived()
2810 {
2811 DBUG_ENTER("set_merged_derived");
2812 DBUG_PRINT("enter", ("Alias: '%s' Unit: %p",
2813 (alias.str ? alias.str : "<NULL>"),
2814 get_unit()));
2815 derived_type= ((derived_type & DTYPE_MASK) |
2816 DTYPE_TABLE | DTYPE_MERGE);
2817 set_check_merged();
2818 DBUG_VOID_RETURN;
2819 }
is_materialized_derivedTABLE_LIST2820 inline bool is_materialized_derived()
2821 {
2822 return (derived_type & DTYPE_MATERIALIZE);
2823 }
set_materialized_derivedTABLE_LIST2824 void set_materialized_derived()
2825 {
2826 DBUG_ENTER("set_materialized_derived");
2827 DBUG_PRINT("enter", ("Alias: '%s' Unit: %p",
2828 (alias.str ? alias.str : "<NULL>"),
2829 get_unit()));
2830 derived= get_unit();
2831 derived_type= ((derived_type & (derived ? DTYPE_MASK : DTYPE_VIEW)) |
2832 DTYPE_TABLE | DTYPE_MATERIALIZE);
2833 set_check_materialized();
2834 DBUG_VOID_RETURN;
2835 }
is_multitableTABLE_LIST2836 inline bool is_multitable()
2837 {
2838 return (derived_type & DTYPE_MULTITABLE);
2839 }
set_multitableTABLE_LIST2840 inline void set_multitable()
2841 {
2842 derived_type|= DTYPE_MULTITABLE;
2843 }
2844 bool set_as_with_table(THD *thd, With_element *with_elem);
2845 void reset_const_table();
2846 bool handle_derived(LEX *lex, uint phases);
2847
2848 /**
2849 @brief True if this TABLE_LIST represents an anonymous derived table,
2850 i.e. the result of a subquery.
2851 */
is_anonymous_derived_tableTABLE_LIST2852 bool is_anonymous_derived_table() const { return derived && !view; }
2853
2854 /**
2855 @brief Returns the name of the database that the referenced table belongs
2856 to.
2857 */
get_db_nameTABLE_LIST2858 const char *get_db_name() const { return view != NULL ? view_db.str : db.str; }
2859
2860 /**
2861 @brief Returns the name of the table that this TABLE_LIST represents.
2862
2863 @details The unqualified table name or view name for a table or view,
2864 respectively.
2865 */
get_table_nameTABLE_LIST2866 const char *get_table_name() const { return view != NULL ? view_name.str : table_name.str; }
2867 bool is_active_sjm();
is_jtbmTABLE_LIST2868 bool is_jtbm() { return MY_TEST(jtbm_subselect != NULL); }
2869 st_select_lex_unit *get_unit();
2870 st_select_lex *get_single_select();
2871 void wrap_into_nested_join(List<TABLE_LIST> &join_list);
2872 bool init_derived(THD *thd, bool init_view);
2873 int fetch_number_of_rows();
2874 bool change_refs_to_fields();
2875
2876 bool single_table_updatable();
2877
is_inner_table_of_outer_joinTABLE_LIST2878 bool is_inner_table_of_outer_join()
2879 {
2880 for (TABLE_LIST *tbl= this; tbl; tbl= tbl->embedding)
2881 {
2882 if (tbl->outer_join)
2883 return true;
2884 }
2885 return false;
2886 }
2887 void set_lock_type(THD* thd, enum thr_lock_type lock);
2888
2889 derived_handler *find_derived_handler(THD *thd);
2890 TABLE_LIST *get_first_table();
2891
remove_join_columnsTABLE_LIST2892 void remove_join_columns()
2893 {
2894 if (join_columns)
2895 {
2896 join_columns->empty();
2897 join_columns= NULL;
2898 is_join_columns_complete= FALSE;
2899 }
2900 }
2901
2902 private:
2903 bool prep_check_option(THD *thd, uint8 check_opt_type);
2904 bool prep_where(THD *thd, Item **conds, bool no_where_clause);
2905 void set_check_materialized();
2906 #ifndef DBUG_OFF
2907 void set_check_merged();
2908 #else
set_check_mergedTABLE_LIST2909 inline void set_check_merged() {}
2910 #endif
2911 /** See comments for set_table_ref_id() */
2912 enum enum_table_ref_type m_table_ref_type;
2913 /** See comments for set_table_ref_id() */
2914 ulong m_table_ref_version;
2915 };
2916
2917 class Item;
2918
2919 /*
2920 Iterator over the fields of a generic table reference.
2921 */
2922
2923 class Field_iterator: public Sql_alloc
2924 {
2925 public:
Field_iterator()2926 Field_iterator() {} /* Remove gcc warning */
~Field_iterator()2927 virtual ~Field_iterator() {}
2928 virtual void set(TABLE_LIST *)= 0;
2929 virtual void next()= 0;
2930 virtual bool end_of_fields()= 0; /* Return 1 at end of list */
2931 virtual LEX_CSTRING *name()= 0;
2932 virtual Item *create_item(THD *)= 0;
2933 virtual Field *field()= 0;
2934 };
2935
2936
2937 /*
2938 Iterator over the fields of a base table, view with temporary
2939 table, or subquery.
2940 */
2941
2942 class Field_iterator_table: public Field_iterator
2943 {
2944 Field **ptr;
2945 public:
Field_iterator_table()2946 Field_iterator_table() :ptr(0) {}
set(TABLE_LIST * table)2947 void set(TABLE_LIST *table) { ptr= table->table->field; }
set_table(TABLE * table)2948 void set_table(TABLE *table) { ptr= table->field; }
next()2949 void next() { ptr++; }
end_of_fields()2950 bool end_of_fields() { return *ptr == 0; }
2951 LEX_CSTRING *name();
2952 Item *create_item(THD *thd);
field()2953 Field *field() { return *ptr; }
2954 };
2955
2956
2957 /* Iterator over the fields of a merge view. */
2958
2959 class Field_iterator_view: public Field_iterator
2960 {
2961 Field_translator *ptr, *array_end;
2962 TABLE_LIST *view;
2963 public:
Field_iterator_view()2964 Field_iterator_view() :ptr(0), array_end(0) {}
2965 void set(TABLE_LIST *table);
next()2966 void next() { ptr++; }
end_of_fields()2967 bool end_of_fields() { return ptr == array_end; }
2968 LEX_CSTRING *name();
2969 Item *create_item(THD *thd);
item_ptr()2970 Item **item_ptr() {return &ptr->item; }
field()2971 Field *field() { return 0; }
item()2972 inline Item *item() { return ptr->item; }
field_translator()2973 Field_translator *field_translator() { return ptr; }
2974 };
2975
2976
2977 /*
2978 Field_iterator interface to the list of materialized fields of a
2979 NATURAL/USING join.
2980 */
2981
2982 class Field_iterator_natural_join: public Field_iterator
2983 {
2984 List_iterator_fast<Natural_join_column> column_ref_it;
2985 Natural_join_column *cur_column_ref;
2986 public:
Field_iterator_natural_join()2987 Field_iterator_natural_join() :cur_column_ref(NULL) {}
~Field_iterator_natural_join()2988 ~Field_iterator_natural_join() {}
2989 void set(TABLE_LIST *table);
2990 void next();
end_of_fields()2991 bool end_of_fields() { return !cur_column_ref; }
name()2992 LEX_CSTRING *name() { return cur_column_ref->name(); }
create_item(THD * thd)2993 Item *create_item(THD *thd) { return cur_column_ref->create_item(thd); }
field()2994 Field *field() { return cur_column_ref->field(); }
column_ref()2995 Natural_join_column *column_ref() { return cur_column_ref; }
2996 };
2997
2998
2999 /*
3000 Generic iterator over the fields of an arbitrary table reference.
3001
3002 DESCRIPTION
3003 This class unifies the various ways of iterating over the columns
3004 of a table reference depending on the type of SQL entity it
3005 represents. If such an entity represents a nested table reference,
3006 this iterator encapsulates the iteration over the columns of the
3007 members of the table reference.
3008
3009 IMPLEMENTATION
3010 The implementation assumes that all underlying NATURAL/USING table
3011 references already contain their result columns and are linked into
3012 the list TABLE_LIST::next_name_resolution_table.
3013 */
3014
3015 class Field_iterator_table_ref: public Field_iterator
3016 {
3017 TABLE_LIST *table_ref, *first_leaf, *last_leaf;
3018 Field_iterator_table table_field_it;
3019 Field_iterator_view view_field_it;
3020 Field_iterator_natural_join natural_join_it;
3021 Field_iterator *field_it;
3022 void set_field_iterator();
3023 public:
Field_iterator_table_ref()3024 Field_iterator_table_ref() :field_it(NULL) {}
3025 void set(TABLE_LIST *table);
3026 void next();
end_of_fields()3027 bool end_of_fields()
3028 { return (table_ref == last_leaf && field_it->end_of_fields()); }
name()3029 LEX_CSTRING *name() { return field_it->name(); }
3030 const char *get_table_name();
3031 const char *get_db_name();
3032 GRANT_INFO *grant();
create_item(THD * thd)3033 Item *create_item(THD *thd) { return field_it->create_item(thd); }
field()3034 Field *field() { return field_it->field(); }
3035 Natural_join_column *get_or_create_column_ref(THD *thd, TABLE_LIST *parent_table_ref);
3036 Natural_join_column *get_natural_column_ref();
3037 };
3038
3039
3040 #define JOIN_OP_NEST 1
3041 #define REBALANCED_NEST 2
3042
3043 typedef struct st_nested_join
3044 {
3045 List<TABLE_LIST> join_list; /* list of elements in the nested join */
3046 /*
3047 Currently the valid values for nest type are:
3048 JOIN_OP_NEST - for nest created for JOIN operation used as an operand in
3049 a join expression, contains 2 elements;
3050 JOIN_OP_NEST | REBALANCED_NEST - nest created after tree re-balancing
3051 in st_select_lex::add_cross_joined_table(), contains 1 element;
3052 0 - for all other nests.
3053 Examples:
3054 1. SELECT * FROM t1 JOIN t2 LEFT JOIN t3 ON t2.a=t3.a;
3055 Here the nest created for LEFT JOIN at first has nest_type==JOIN_OP_NEST.
3056 After re-balancing in st_select_lex::add_cross_joined_table() this nest
3057 has nest_type==JOIN_OP_NEST | REBALANCED_NEST. The nest for JOIN created
3058 in st_select_lex::add_cross_joined_table() has nest_type== JOIN_OP_NEST.
3059 2. SELECT * FROM t1 JOIN (t2 LEFT JOIN t3 ON t2.a=t3.a)
3060 Here the nest created for LEFT JOIN has nest_type==0, because it's not
3061 an operand in a join expression. The nest created for JOIN has nest_type
3062 set to JOIN_OP_NEST.
3063 */
3064 uint nest_type;
3065 /*
3066 Bitmap of tables within this nested join (including those embedded within
3067 its children), including tables removed by table elimination.
3068 */
3069 table_map used_tables;
3070 table_map not_null_tables; /* tables that rejects nulls */
3071 /**
3072 Used for pointing out the first table in the plan being covered by this
3073 join nest. It is used exclusively within make_outerjoin_info().
3074 */
3075 struct st_join_table *first_nested;
3076 /*
3077 Used to count tables in the nested join in 2 isolated places:
3078 1. In make_outerjoin_info().
3079 2. check_interleaving_with_nj/restore_prev_nj_state (these are called
3080 by the join optimizer.
3081 Before each use the counters are zeroed by reset_nj_counters.
3082 */
3083 uint counter;
3084
3085 /*
3086 Number of elements in join_list that participate in the join plan choice:
3087 - Base tables that were not removed by table elimination
3088 - Join nests that were not removed by mark_join_nest_as_const
3089 */
3090 uint n_tables;
3091 nested_join_map nj_map; /* Bit used to identify this nested join*/
3092 /*
3093 (Valid only for semi-join nests) Bitmap of tables outside the semi-join
3094 that are used within the semi-join's ON condition.
3095 */
3096 table_map sj_depends_on;
3097 /* Outer non-trivially correlated tables */
3098 table_map sj_corr_tables;
3099 List<Item_ptr> sj_outer_expr_list;
3100 /**
3101 True if this join nest node is completely covered by the query execution
3102 plan. This means two things.
3103
3104 1. All tables on its @c join_list are covered by the plan.
3105
3106 2. All child join nest nodes are fully covered.
3107 */
is_fully_coveredst_nested_join3108 bool is_fully_covered() const { return n_tables == counter; }
3109 } NESTED_JOIN;
3110
3111
3112 typedef struct st_changed_table_list
3113 {
3114 struct st_changed_table_list *next;
3115 char *key;
3116 size_t key_length;
3117 } CHANGED_TABLE_LIST;
3118
3119
3120 typedef struct st_open_table_list{
3121 struct st_open_table_list *next;
3122 char *db,*table;
3123 uint32 in_use,locked;
3124 } OPEN_TABLE_LIST;
3125
3126
tmp_use_all_columns(TABLE * table,MY_BITMAP ** bitmap)3127 static inline MY_BITMAP *tmp_use_all_columns(TABLE *table,
3128 MY_BITMAP **bitmap)
3129 {
3130 MY_BITMAP *old= *bitmap;
3131 *bitmap= &table->s->all_set;
3132 return old;
3133 }
3134
3135
tmp_restore_column_map(MY_BITMAP ** bitmap,MY_BITMAP * old)3136 static inline void tmp_restore_column_map(MY_BITMAP **bitmap,
3137 MY_BITMAP *old)
3138 {
3139 *bitmap= old;
3140 }
3141
3142 /* The following is only needed for debugging */
3143
dbug_tmp_use_all_columns(TABLE * table,MY_BITMAP ** bitmap)3144 static inline MY_BITMAP *dbug_tmp_use_all_columns(TABLE *table,
3145 MY_BITMAP **bitmap)
3146 {
3147 #ifdef DBUG_ASSERT_EXISTS
3148 return tmp_use_all_columns(table, bitmap);
3149 #else
3150 return 0;
3151 #endif
3152 }
3153
dbug_tmp_restore_column_map(MY_BITMAP ** bitmap,MY_BITMAP * old)3154 static inline void dbug_tmp_restore_column_map(MY_BITMAP **bitmap,
3155 MY_BITMAP *old)
3156 {
3157 #ifdef DBUG_ASSERT_EXISTS
3158 tmp_restore_column_map(bitmap, old);
3159 #endif
3160 }
3161
3162
3163 /*
3164 Variant of the above : handle both read and write sets.
3165 Provide for the possiblity of the read set being the same as the write set
3166 */
dbug_tmp_use_all_columns(TABLE * table,MY_BITMAP ** save,MY_BITMAP ** read_set,MY_BITMAP ** write_set)3167 static inline void dbug_tmp_use_all_columns(TABLE *table,
3168 MY_BITMAP **save,
3169 MY_BITMAP **read_set,
3170 MY_BITMAP **write_set)
3171 {
3172 #ifdef DBUG_ASSERT_EXISTS
3173 save[0]= *read_set;
3174 save[1]= *write_set;
3175 (void) tmp_use_all_columns(table, read_set);
3176 (void) tmp_use_all_columns(table, write_set);
3177 #endif
3178 }
3179
3180
dbug_tmp_restore_column_maps(MY_BITMAP ** read_set,MY_BITMAP ** write_set,MY_BITMAP ** old)3181 static inline void dbug_tmp_restore_column_maps(MY_BITMAP **read_set,
3182 MY_BITMAP **write_set,
3183 MY_BITMAP **old)
3184 {
3185 #ifdef DBUG_ASSERT_EXISTS
3186 tmp_restore_column_map(read_set, old[0]);
3187 tmp_restore_column_map(write_set, old[1]);
3188 #endif
3189 }
3190
3191 bool ok_for_lower_case_names(const char *names);
3192
3193 enum get_table_share_flags {
3194 GTS_TABLE = 1,
3195 GTS_VIEW = 2,
3196 GTS_NOLOCK = 4,
3197 GTS_USE_DISCOVERY = 8,
3198 GTS_FORCE_DISCOVERY = 16
3199 };
3200
3201 size_t max_row_length(TABLE *table, MY_BITMAP const *cols, const uchar *data);
3202
3203 void init_mdl_requests(TABLE_LIST *table_list);
3204
3205 enum open_frm_error open_table_from_share(THD *thd, TABLE_SHARE *share,
3206 const LEX_CSTRING *alias, uint db_stat, uint prgflag,
3207 uint ha_open_flags, TABLE *outparam,
3208 bool is_create_table,
3209 List<String> *partitions_to_open= NULL);
3210 bool fix_session_vcol_expr(THD *thd, Virtual_column_info *vcol);
3211 bool fix_session_vcol_expr_for_read(THD *thd, Field *field,
3212 Virtual_column_info *vcol);
3213 bool parse_vcol_defs(THD *thd, MEM_ROOT *mem_root, TABLE *table,
3214 bool *error_reported, vcol_init_mode expr);
3215 TABLE_SHARE *alloc_table_share(const char *db, const char *table_name,
3216 const char *key, uint key_length);
3217 void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
3218 uint key_length,
3219 const char *table_name, const char *path);
3220 void free_table_share(TABLE_SHARE *share);
3221 enum open_frm_error open_table_def(THD *thd, TABLE_SHARE *share,
3222 uint flags = GTS_TABLE);
3223
3224 void open_table_error(TABLE_SHARE *share, enum open_frm_error error,
3225 int db_errno);
3226 void update_create_info_from_table(HA_CREATE_INFO *info, TABLE *form);
3227 bool check_db_name(LEX_STRING *db);
3228 bool check_column_name(const char *name);
3229 bool check_table_name(const char *name, size_t length, bool check_for_path_chars);
3230 int rename_file_ext(const char * from,const char * to,const char * ext);
3231 char *get_field(MEM_ROOT *mem, Field *field);
3232 bool get_field(MEM_ROOT *mem, Field *field, class String *res);
3233
3234 bool validate_comment_length(THD *thd, LEX_CSTRING *comment, size_t max_len,
3235 uint err_code, const char *name);
3236
3237 int closefrm(TABLE *table);
3238 void free_blobs(TABLE *table);
3239 void free_field_buffers_larger_than(TABLE *table, uint32 size);
3240 ulong get_form_pos(File file, uchar *head, TYPELIB *save_names);
3241 void append_unescaped(String *res, const char *pos, size_t length);
3242 void prepare_frm_header(THD *thd, uint reclength, uchar *fileinfo,
3243 HA_CREATE_INFO *create_info, uint keys, KEY *key_info);
3244 const char *fn_frm_ext(const char *name);
3245
3246 /* Check that the integer is in the internal */
set_zone(int nr,int min_zone,int max_zone)3247 static inline int set_zone(int nr,int min_zone,int max_zone)
3248 {
3249 if (nr <= min_zone)
3250 return min_zone;
3251 if (nr >= max_zone)
3252 return max_zone;
3253 return nr;
3254 }
3255
3256 /* performance schema */
3257 extern LEX_CSTRING PERFORMANCE_SCHEMA_DB_NAME;
3258
3259 extern LEX_CSTRING GENERAL_LOG_NAME;
3260 extern LEX_CSTRING SLOW_LOG_NAME;
3261 extern LEX_CSTRING TRANSACTION_REG_NAME;
3262
3263 /* information schema */
3264 extern LEX_CSTRING INFORMATION_SCHEMA_NAME;
3265 extern LEX_CSTRING MYSQL_SCHEMA_NAME;
3266
3267 /* table names */
3268 extern LEX_CSTRING MYSQL_PROC_NAME;
3269
is_infoschema_db(const LEX_CSTRING * name)3270 inline bool is_infoschema_db(const LEX_CSTRING *name)
3271 {
3272 return (INFORMATION_SCHEMA_NAME.length == name->length &&
3273 !my_strcasecmp(system_charset_info,
3274 INFORMATION_SCHEMA_NAME.str, name->str));
3275 }
3276
mark_as_null_row(TABLE * table)3277 inline void mark_as_null_row(TABLE *table)
3278 {
3279 table->null_row=1;
3280 table->status|=STATUS_NULL_ROW;
3281 if (table->s->null_bytes)
3282 bfill(table->null_flags,table->s->null_bytes,255);
3283 }
3284
unmark_as_null_row(TABLE * table)3285 inline void unmark_as_null_row(TABLE *table)
3286 {
3287 table->null_row=0;
3288 table->status= STATUS_NO_RECORD;
3289 }
3290
3291 bool is_simple_order(ORDER *order);
3292
3293 class Open_tables_backup;
3294
3295 /** Transaction Registry Table (TRT)
3296
3297 This table holds transaction IDs, their corresponding times and other
3298 transaction-related data which is used for transaction order resolution.
3299 When versioned table marks its records lifetime with transaction IDs,
3300 TRT is used to get their actual timestamps. */
3301
3302 class TR_table: public TABLE_LIST
3303 {
3304 THD *thd;
3305 Open_tables_backup *open_tables_backup;
3306
3307 public:
3308 enum field_id_t {
3309 FLD_TRX_ID= 0,
3310 FLD_COMMIT_ID,
3311 FLD_BEGIN_TS,
3312 FLD_COMMIT_TS,
3313 FLD_ISO_LEVEL,
3314 FIELD_COUNT
3315 };
3316
3317 enum enabled {NO, MAYBE, YES};
3318 static enum enabled use_transaction_registry;
3319
3320 /**
3321 @param[in,out] Thread handle
3322 @param[in] Current transaction is read-write.
3323 */
3324 TR_table(THD *_thd, bool rw= false);
3325 /**
3326 Opens a transaction_registry table.
3327
3328 @retval true on error, false otherwise.
3329 */
3330 bool open();
3331 ~TR_table();
3332 /**
3333 @retval current thd
3334 */
get_thd()3335 THD *get_thd() const { return thd; }
3336 /**
3337 Stores value to internal transaction_registry TABLE object.
3338
3339 @param[in] field number in a TABLE
3340 @param[in] value to store
3341 */
3342 void store(uint field_id, ulonglong val);
3343 /**
3344 Stores value to internal transaction_registry TABLE object.
3345
3346 @param[in] field number in a TABLE
3347 @param[in] value to store
3348 */
3349 void store(uint field_id, timeval ts);
3350 /**
3351 Update the transaction_registry right before commit.
3352 @param start_id transaction identifier at start
3353 @param end_id transaction identifier at commit
3354
3355 @retval false on success
3356 @retval true on error (the transaction must be rolled back)
3357 */
3358 bool update(ulonglong start_id, ulonglong end_id);
3359 // return true if found; false if not found or error
3360 bool query(ulonglong trx_id);
3361 /**
3362 Gets a row from transaction_registry with the closest commit_timestamp to
3363 first argument. We can search for a value which a lesser or greater than
3364 first argument. Also loads a row into an internal TABLE object.
3365
3366 @param[in] timestamp
3367 @param[in] true if we search for a lesser timestamp, false if greater
3368 @retval true if exists, false it not exists or an error occurred
3369 */
3370 bool query(MYSQL_TIME &commit_time, bool backwards);
3371 /**
3372 Checks whether transaction1 sees transaction0.
3373
3374 @param[out] true if transaction1 sees transaction0, undefined on error and
3375 when transaction1=transaction0 and false otherwise
3376 @param[in] transaction_id of transaction1
3377 @param[in] transaction_id of transaction0
3378 @param[in] commit time of transaction1 or 0 if we want it to be queried
3379 @param[in] isolation level (from handler.h) of transaction1
3380 @param[in] commit time of transaction0 or 0 if we want it to be queried
3381 @retval true on error, false otherwise
3382 */
3383 bool query_sees(bool &result, ulonglong trx_id1, ulonglong trx_id0,
3384 ulonglong commit_id1= 0,
3385 enum_tx_isolation iso_level1= ISO_READ_UNCOMMITTED,
3386 ulonglong commit_id0= 0);
3387
3388 /**
3389 @retval transaction isolation level of a row from internal TABLE object.
3390 */
3391 enum_tx_isolation iso_level() const;
3392 /**
3393 Stores transactioin isolation level to internal TABLE object.
3394 */
store_iso_level(enum_tx_isolation iso_level)3395 void store_iso_level(enum_tx_isolation iso_level)
3396 {
3397 DBUG_ASSERT(iso_level <= ISO_SERIALIZABLE);
3398 store(FLD_ISO_LEVEL, iso_level + 1);
3399 }
3400
3401 /**
3402 Writes a message to MariaDB log about incorrect transaction_registry schema.
3403
3404 @param[in] a message explained what's incorrect in schema
3405 */
3406 void warn_schema_incorrect(const char *reason);
3407 /**
3408 Checks whether transaction_registry table has a correct schema.
3409
3410 @retval true if schema is incorrect and false otherwise
3411 */
3412 bool check(bool error);
3413
3414 TABLE * operator-> () const
3415 {
3416 return table;
3417 }
3418 Field * operator[] (uint field_id) const
3419 {
3420 DBUG_ASSERT(field_id < FIELD_COUNT);
3421 return table->field[field_id];
3422 }
3423 operator bool () const
3424 {
3425 return table;
3426 }
3427 bool operator== (const TABLE_LIST &subj) const
3428 {
3429 return (!cmp(&db, &subj.db) && !cmp(&table_name, &subj.table_name));
3430 }
3431 bool operator!= (const TABLE_LIST &subj) const
3432 {
3433 return !(*this == subj);
3434 }
3435 };
3436
3437 #endif /* MYSQL_CLIENT */
3438
3439 #endif /* TABLE_INCLUDED */
3440