Debian Codegraph @

storage/innobase/dict/dict0dd.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2017, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License, version 2.0, as published by the
7 Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful, but WITHOUT
18 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20 for more details.
21
22 You should have received a copy of the GNU General Public License along with
23 this program; if not, write to the Free Software Foundation, Inc.,
24 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 /** @file dict/dict0dd.cc
29 Data dictionary interface */
30
31 #ifndef UNIV_HOTBACKUP
32 #include <auto_thd.h>
33 #include <current_thd.h>
34 #include <sql/thd_raii.h>
35 #include <sql_backup_lock.h>
36 #include <sql_class.h>
37 #include <sql_thd_internal_api.h>
38
39 #include "item.h"
40 #else /* !UNIV_HOTBACKUP */
41 #include <my_base.h>
42 #endif /* !UNIV_HOTBACKUP */
43
44 #include <dd/properties.h>
45
46 #include "dict0crea.h"
47 #include "dict0dd.h"
48 #include "dict0dict.h"
49 #include "dict0mem.h"
50 #include "dict0priv.h"
51 #include "sql/dd/impl/types/column_impl.h"
52 #include "sql/dd/types/column_type_element.h"
53 #ifndef UNIV_HOTBACKUP
54 #include "dict0stats.h"
55 #endif /* !UNIV_HOTBACKUP */
56 #include "data0type.h"
57 #include "dict0dict.h"
58 #include "fil0fil.h"
59 #include "mach0data.h"
60 #include "rem0rec.h"
61 #ifndef UNIV_HOTBACKUP
62 #include "fts0priv.h"
63 #include "gis/rtree_support.h" // fetch_srs
64 #endif /* !UNIV_HOTBACKUP */
65 #include "srv0start.h"
66 #include "ut0crc32.h"
67 #ifndef UNIV_HOTBACKUP
68 #include "btr0sea.h"
69 #include "derror.h"
70 #include "fts0plugin.h"
71 #include "ha_innodb.h"
72 #include "ha_innopart.h"
73 #include "ha_prototypes.h"
74 #include "mysql/plugin.h"
75 #include "query_options.h"
76 #include "sql/create_field.h"
77 #include "sql/mysqld.h" // lower_case_file_system
78 #include "sql_base.h"
79 #include "sql_table.h"
80 #include "univ.i" // Using OS_PATH_SEPARATOR
81 #endif /* !UNIV_HOTBACKUP */
82
83 const char *DD_instant_col_val_coder::encode(const byte *stream, size_t in_len,
84 size_t *out_len) {
85 cleanup();
86
87 m_result = ut::new_arr_withkey<byte>(UT_NEW_THIS_FILE_PSI_KEY,
88 ut::Count{in_len * 2});
89 char *result = reinterpret_cast<char *>(m_result);
90
91 for (size_t i = 0; i < in_len; ++i) {
92 uint8_t v1 = ((stream[i] & 0xF0) >> 4);
93 uint8_t v2 = (stream[i] & 0x0F);
94
95 result[i * 2] = (v1 < 10 ? '0' + v1 : 'a' + v1 - 10);
96 result[i * 2 + 1] = (v2 < 10 ? '0' + v2 : 'a' + v2 - 10);
97 }
98
99 *out_len = in_len * 2;
100
101 return result;
102 }
103
104 const byte *DD_instant_col_val_coder::decode(const char *stream, size_t in_len,
105 size_t *out_len) {
106 ut_ad(in_len % 2 == 0);
107
108 cleanup();
109
110 m_result = ut::new_arr_withkey<byte>(UT_NEW_THIS_FILE_PSI_KEY,
111 ut::Count{in_len / 2});
112
113 for (size_t i = 0; i < in_len / 2; ++i) {
114 char c1 = stream[i * 2];
115 char c2 = stream[i * 2 + 1];
116
117 ut_ad(isdigit(c1) || (c1 >= 'a' && c1 <= 'f'));
118 ut_ad(isdigit(c2) || (c2 >= 'a' && c2 <= 'f'));
119
120 m_result[i] = ((isdigit(c1) ? c1 - '0' : c1 - 'a' + 10) << 4) +
121 ((isdigit(c2) ? c2 - '0' : c2 - 'a' + 10));
122 }
123
124 *out_len = in_len / 2;
125
126 return m_result;
127 }
128
129 #ifndef UNIV_HOTBACKUP
130 bool dd_is_valid_row_version(uint32_t version) {
131 return (version != UINT32_UNDEFINED && version > 0 &&
132 version <= (uint32_t)MAX_ROW_VERSION);
133 }
134
135 bool dd_column_is_added(const dd::Column *dd_col) {
136 const char *s = dd_column_key_strings[DD_INSTANT_VERSION_ADDED];
137 if (!dd_col->se_private_data().exists(s)) {
138 return false;
139 }
140
141 #ifdef UNIV_DEBUG
142 uint32_t version = UINT32_UNDEFINED;
143 dd_col->se_private_data().get(s, &version);
144 ut_ad(dd_is_valid_row_version(version));
145 #endif
146
147 return true;
148 }
149
150 bool dd_column_is_dropped(const dd::Column *dd_col) {
151 const char *s = dd_column_key_strings[DD_INSTANT_VERSION_DROPPED];
152 if (!dd_col->se_private_data().exists(s)) {
153 return false;
154 }
155
156 #ifdef UNIV_DEBUG
157 uint32_t version = UINT32_UNDEFINED;
158 dd_col->se_private_data().get(s, &version);
159 ut_ad(dd_is_valid_row_version(version));
160 #endif
161
162 return true;
163 }
164
165 uint32_t dd_column_get_version_added(const dd::Column *dd_col) {
166 if (!dd_column_is_added(dd_col)) {
167 return UINT32_UNDEFINED;
168 }
169
170 uint32_t version = UINT32_UNDEFINED;
171 dd_col->se_private_data().get(dd_column_key_strings[DD_INSTANT_VERSION_ADDED],
172 &version);
173 ut_a(dd_is_valid_row_version(version));
174 return (version);
175 }
176
177 uint32_t dd_column_get_version_dropped(const dd::Column *dd_col) {
178 if (!dd_column_is_dropped(dd_col)) {
179 return UINT32_UNDEFINED;
180 }
181
182 uint32_t version = UINT32_UNDEFINED;
183 dd_col->se_private_data().get(
184 dd_column_key_strings[DD_INSTANT_VERSION_DROPPED], &version);
185 ut_a(dd_is_valid_row_version(version));
186 return (version);
187 }
188
189 /** Check if the InnoDB index is consistent with dd::Index
190 @param[in] index InnoDB index
191 @param[in] dd_index dd::Index or dd::Partition_index
192 @return true if match
193 @retval false if not match */
194 template <typename Index>
195 static bool dd_index_match(const dict_index_t *index, const Index *dd_index) {
196 bool match = true;
197
198 /* Don't check the name for primary index, since internal index
199 name could be variant */
200 if (my_strcasecmp(system_charset_info, index->name(),
201 dd_index->name().c_str()) != 0 &&
202 strcmp(dd_index->name().c_str(), "PRIMARY") != 0) {
203 ib::warn(ER_IB_MSG_162)
204 << "Index name in InnoDB is " << index->name()
205 << " while index name in global DD is " << dd_index->name();
206 match = false;
207 }
208
209 const dd::Properties &p = dd_index->se_private_data();
210 uint64_t id = 0;
211 uint32_t root = 0;
212 uint64_t trx_id = 0;
213 ut_ad(p.exists(dd_index_key_strings[DD_INDEX_ID]));
214 p.get(dd_index_key_strings[DD_INDEX_ID], &id);
215 if (id != index->id) {
216 ib::warn(ER_IB_MSG_163)
217 << "Index id in InnoDB is " << index->id << " while index id in"
218 << " global DD is " << id;
219 match = false;
220 }
221
222 ut_ad(p.exists(dd_index_key_strings[DD_INDEX_ROOT]));
223 p.get(dd_index_key_strings[DD_INDEX_ROOT], &root);
224 if (root != index->page) {
225 ib::warn(ER_IB_MSG_164)
226 << "Index root in InnoDB is " << index->page << " while index root in"
227 << " global DD is " << root;
228 match = false;
229 }
230
231 ut_ad(p.exists(dd_index_key_strings[DD_INDEX_TRX_ID]));
232 p.get(dd_index_key_strings[DD_INDEX_TRX_ID], &trx_id);
233 /* For DD tables, the trx_id=0 is got from get_se_private_id().
234 TODO: index->trx_id is not expected to be 0 once Bug#25730513 is fixed*/
235 if (trx_id != 0 && index->trx_id != 0 && trx_id != index->trx_id) {
236 ib::warn(ER_IB_MSG_165) << "Index transaction id in InnoDB is "
237 << index->trx_id << " while index transaction"
238 << " id in global DD is " << trx_id;
239 match = false;
240 }
241
242 return match;
243 }
244
245 /** Check if the InnoDB table is consistent with dd::Table
246 @tparam Table dd::Table or dd::Partition
247 @param[in] table InnoDB table
248 @param[in] dd_table dd::Table or dd::Partition
249 @return true if match
250 @retval false if not match */
251 template <typename Table>
252 bool dd_table_match(const dict_table_t *table, const Table *dd_table) {
253 /* Temporary table has no metadata written */
254 if (dd_table == nullptr || table->is_temporary()) {
255 return true;
256 }
257
258 bool match = true;
259
260 if (dd_table->se_private_id() != table->id) {
261 ib::warn(ER_IB_MSG_166)
262 << "Table id in InnoDB is " << table->id
263 << " while the id in global DD is " << dd_table->se_private_id();
264 match = false;
265 }
266
267 /* If tablespace is discarded, no need to check indexes */
268 if (dict_table_is_discarded(table)) {
269 return match;
270 }
271
272 for (const auto dd_index : dd_table->indexes()) {
273 if (dd_table->tablespace_id() == dict_sys_t::s_dd_sys_space_id &&
274 dd_index->tablespace_id() != dd_table->tablespace_id()) {
275 ib::warn(ER_IB_MSG_167)
276 << "Tablespace id in table is " << dd_table->tablespace_id()
277 << ", while tablespace id in index " << dd_index->name() << " is "
278 << dd_index->tablespace_id();
279 }
280
281 const dict_index_t *index = dd_find_index(table, dd_index);
282 ut_ad(index != nullptr);
283
284 if (!dd_index_match(index, dd_index)) {
285 match = false;
286 }
287 }
288
289 /* Tablespace and options can be checked here too */
290 return match;
291 }
292
293 template bool dd_table_match<dd::Table>(const dict_table_t *,
294 const dd::Table *);
295 template bool dd_table_match<dd::Partition>(const dict_table_t *,
296 const dd::Partition *);
297
298 /** Release a metadata lock.
299 @param[in,out] thd current thread
300 @param[in,out] mdl metadata lock */
301 void dd_mdl_release(THD *thd, MDL_ticket **mdl) {
302 if (*mdl == nullptr) {
303 return;
304 }
305
306 dd::release_mdl(thd, *mdl);
307 *mdl = nullptr;
308 }
309
310 THD *dd_thd_for_undo(const trx_t *trx) {
311 return trx->mysql_thd == nullptr ? current_thd : trx->mysql_thd;
312 }
313
314 /** Check if current undo needs a MDL or not
315 @param[in] trx transaction
316 @return true if MDL is necessary, otherwise false */
317 bool dd_mdl_for_undo(const trx_t *trx) {
318 /* Try best to find a valid THD for checking, in case in background
319 rollback thread, trx doesn't hold a mysql_thd */
320 THD *thd = dd_thd_for_undo(trx);
321
322 /* There are four cases for the undo to check here:
323 1. In recovery phase, binlog recover, there is no concurrent
324 user queries, so MDL is no necessary. In this case, thd is NULL.
325 2. In background rollback thread, there could be concurrent
326 user queries, so MDL is needed. In this case, thd is not NULL
327 3. In runtime transaction rollback, no need for MDL.
328 THD::transaction_rollback_request would be set.
329 4. In runtime asynchronous rollback, no need for MDL.
330 Check TRX_FORCE_ROLLBACK. */
331 return (thd != nullptr && !thd->transaction_rollback_request &&
332 ((trx->in_innodb & TRX_FORCE_ROLLBACK) == 0));
333 }
334
335 int acquire_uncached_table(THD *thd, dd::cache::Dictionary_client *client,
336 const dd::Table *dd_table, const char *name,
337 TABLE_SHARE *ts, TABLE *td) {
338 int error = 0;
339 dd::Schema *schema;
340 const char *table_cache_key;
341 size_t table_cache_key_len;
342
343 if (name != nullptr) {
344 schema = nullptr;
345 table_cache_key = name;
346 table_cache_key_len = dict_get_db_name_len(name);
347 } else {
348 error =
349 client->acquire_uncached<dd::Schema>(dd_table->schema_id(), &schema);
350 if (error != 0) {
351 return (error);
352 }
353 table_cache_key = schema->name().c_str();
354 table_cache_key_len = schema->name().size();
355 }
356
357 init_tmp_table_share(thd, ts, table_cache_key, table_cache_key_len,
358 dd_table->name().c_str(), "" /* file name */, nullptr);
359
360 error = open_table_def_suppress_invalid_meta_data(thd, ts, dd_table->table());
361
362 if (error == 0) {
363 error = open_table_from_share(thd, ts, (dd_table->table()).name().c_str(),
364 0, SKIP_NEW_HANDLER, 0, td, false, dd_table);
365 }
366 if (error != 0) {
367 free_table_share(ts);
368 }
369 return error;
370 }
371
372 void release_uncached_table(TABLE_SHARE *ts, TABLE *td) {
373 closefrm(td, false);
374 free_table_share(ts);
375 }
376
377 int dd_table_open_on_dd_obj(THD *thd, dd::cache::Dictionary_client *client,
378 const dd::Table &dd_table,
379 const dd::Partition *dd_part, const char *tbl_name,
380 dict_table_t *&table, const TABLE *td) {
381 #ifdef UNIV_DEBUG
382 if (dd_part != nullptr) {
383 ut_ad(&dd_part->table() == &dd_table);
384 ut_ad(dd_table.se_private_id() == dd::INVALID_OBJECT_ID);
385 ut_ad(dd_table_is_partitioned(dd_table));
386
387 ut_ad(dd_part->parent_partition_id() == dd::INVALID_OBJECT_ID ||
388 dd_part->parent() != nullptr);
389
390 ut_ad(((dd_part->table().subpartition_type() != dd::Table::ST_NONE) ==
391 (dd_part->parent() != nullptr)));
392 }
393 #endif /* UNIV_DEBUG */
394
395 int error = 0;
396 const table_id_t table_id =
397 dd_part == nullptr ? dd_table.se_private_id() : dd_part->se_private_id();
398 const auto hash_value = ut::hash_uint64(table_id);
399
400 ut_ad(table_id != dd::INVALID_OBJECT_ID);
401
402 dict_sys_mutex_enter();
403
404 HASH_SEARCH(id_hash, dict_sys->table_id_hash, hash_value, dict_table_t *,
405 table, ut_ad(table->cached), table->id == table_id);
406
407 if (table != nullptr) {
408 table->acquire();
409 }
410
411 dict_sys_mutex_exit();
412
413 if (table != nullptr) {
414 return 0;
415 }
416
417 #ifdef UNIV_DEBUG
418 /* If this is a internal temporary table, it's impossible
419 to verify the MDL against the table name, because both the
420 database name and table name may be invalid for MDL */
421 if (tbl_name && !row_is_mysql_tmp_table_name(tbl_name)) {
422 std::string db_str;
423 std::string tbl_str;
424 dict_name::get_table(tbl_name, db_str, tbl_str);
425
426 ut_ad(innobase_strcasecmp(dd_table.name().c_str(), tbl_str.c_str()) == 0);
427 }
428 #endif /* UNIV_DEBUG */
429
430 if (td != nullptr) {
431 ut_ad(tbl_name != nullptr);
432
433 if (dd_part) {
434 table = dd_open_table(client, td, tbl_name, dd_part, thd);
435 } else {
436 table = dd_open_table(client, td, tbl_name, &dd_table, thd);
437 }
438 return 0;
439 }
440
441 TABLE_SHARE ts;
442 TABLE table_def;
443
444 error =
445 acquire_uncached_table(thd, client, &dd_table, tbl_name, &ts, &table_def);
446 if (error != 0) {
447 return (error);
448 }
449
450 const char *table_name = tbl_name;
451 char tmp_name[FN_REFLEN + 1];
452 if (!tbl_name) {
453 dd::Schema *schema;
454 error = client->acquire_uncached<dd::Schema>(dd_table.schema_id(), &schema);
455 if (error != 0) {
456 return error;
457 }
458
459 bool truncated;
460 build_table_filename(tmp_name, sizeof(tmp_name) - 1, schema->name().c_str(),
461 dd_table.name().c_str(), nullptr, 0, &truncated);
462
463 if (truncated) {
464 ut_d(ut_error);
465 ut_o(return DB_TOO_LONG_PATH);
466 }
467 table_name = tmp_name;
468 }
469
470 char norm_name[FN_REFLEN];
471 if (!normalize_table_name(norm_name, table_name)) {
472 ut_d(ut_error);
473 ut_o(return DB_TOO_LONG_PATH);
474 }
475
476 if (dd_part == nullptr) {
477 table = dd_open_table(client, &table_def, norm_name, &dd_table, thd);
478 if (table == nullptr) {
479 error = HA_ERR_GENERIC;
480 }
481 } else {
482 table = dd_open_table(client, &table_def, norm_name, dd_part, thd);
483 }
484 release_uncached_table(&ts, &table_def);
485 return error;
486 }
487
488 /** Load an InnoDB table definition by InnoDB table ID.
489 @param[in,out] thd current thread
490 @param[in,out] mdl metadata lock;
491 nullptr if we are resurrecting table IX locks in recovery
492 @param[in] table_id InnoDB table or partition ID
493 @return InnoDB table
494 @retval nullptr if the table is not found, or there was an error */
495 static dict_table_t *dd_table_open_on_id_low(THD *thd, MDL_ticket **mdl,
496 table_id_t table_id) {
497 std::string part_table;
498 const char *name_to_open = nullptr;
499
500 ut_ad(thd == nullptr || thd == current_thd);
501 #ifdef UNIV_DEBUG
502 btrsea_sync_check check(false);
503 ut_ad(!sync_check_iterate(check));
504 #endif
505 ut_ad(srv_shutdown_state.load() < SRV_SHUTDOWN_DD);
506
507 if (thd == nullptr) {
508 ut_ad(mdl == nullptr);
509 thd = current_thd;
510 }
511
512 /* During server startup, while recovering XA transaction we don't have THD.
513 The table should have been already in innodb cache if present in DD while
514 resurrecting transaction. We assume the table is not in DD and return. We
515 cannot continue anyway here with NULL THD. */
516 if (thd == nullptr) {
517 return nullptr;
518 }
519
520 dict_table_t *ib_table = nullptr;
521
522 {
523 const dd::Table *dd_table;
524 const dd::Partition *dd_part = nullptr;
525 dd::cache::Dictionary_client *dc = dd::get_dd_client(thd);
526 dd::cache::Dictionary_client::Auto_releaser releaser(dc);
527
528 /* Since we start with table se_private_id, and we do not have
529 table name, so we cannot MDL lock the table(name). So we will
530 try to get the table name without MDL protection, and verify later,
531 after we got the table name and MDL lock it. Thus a loop is needed
532 in case the verification failed, and another attempt is made until
533 all things matches */
534 for (;;) {
535 dd::String_type schema;
536 dd::String_type tablename;
537 if (dc->get_table_name_by_se_private_id(handler_name, table_id, &schema,
538 &tablename)) {
539 return nullptr;
540 }
541
542 const bool not_table = schema.empty();
543
544 if (not_table) {
545 if (dc->get_table_name_by_partition_se_private_id(
546 handler_name, table_id, &schema, &tablename) ||
547 schema.empty()) {
548 return nullptr;
549 }
550 }
551
552 /* Now we have tablename, and MDL locked it if necessary. */
553 if (mdl != nullptr) {
554 if (*mdl == nullptr &&
555 dd_mdl_acquire(thd, mdl, schema.c_str(), tablename.c_str())) {
556 return nullptr;
557 }
558
559 ut_ad(*mdl != nullptr);
560 }
561
562 if (dc->acquire(schema, tablename, &dd_table) || dd_table == nullptr) {
563 if (mdl != nullptr) {
564 dd_mdl_release(thd, mdl);
565 }
566 return nullptr;
567 }
568
569 const bool is_part = dd_table_is_partitioned(*dd_table);
570
571 /* Verify facts between dd_table and facts we know
572 1) Partition table or not
573 2) Table ID matches or not
574 3) Table in InnoDB */
575 bool same_name = not_table == is_part &&
576 (not_table || dd_table->se_private_id() == table_id) &&
577 dd_table->engine() == handler_name;
578
579 /* Do more verification for partition table */
580 if (same_name && is_part) {
581 auto end = dd_table->leaf_partitions().end();
582 auto i =
583 std::search_n(dd_table->leaf_partitions().begin(), end, 1, table_id,
584 [](const dd::Partition *p, table_id_t id) {
585 return (p->se_private_id() == id);
586 });
587
588 if (i == end) {
589 same_name = false;
590 } else {
591 dd_part = *i;
592 ut_ad(dd_part_is_stored(dd_part));
593
594 std::string partition;
595 /* Build the partition name. */
596 dict_name::build_partition(dd_part, partition);
597
598 /* Build the partitioned table name. */
599 dict_name::build_table(schema.c_str(), tablename.c_str(), partition,
600 false, true, part_table);
601 name_to_open = part_table.c_str();
602 }
603 }
604
605 /* facts do not match, retry */
606 if (!same_name) {
607 if (mdl != nullptr) {
608 dd_mdl_release(thd, mdl);
609 }
610 continue;
611 }
612
613 ut_ad(same_name);
614 break;
615 }
616
617 ut_ad(dd_part != nullptr || dd_table->se_private_id() == table_id);
618 ut_ad(dd_part == nullptr || dd_table == &dd_part->table());
619 ut_ad(dd_part == nullptr || dd_part->se_private_id() == table_id);
620
621 dd_table_open_on_dd_obj(thd, dc, *dd_table, dd_part, name_to_open, ib_table,
622 nullptr);
623 }
624
625 if (mdl && ib_table == nullptr) {
626 dd_mdl_release(thd, mdl);
627 }
628
629 return ib_table;
630 }
631 #endif /* !UNIV_HOTBACKUP */
632
633 /** Check if access to a table should be refused.
634 @param[in,out] table InnoDB table or partition
635 @return error code
636 @retval 0 on success (DD_SUVCCESS) */
637 [[nodiscard]] static int dd_check_corrupted(dict_table_t *&table) {
638 if (table->is_corrupted()) {
639 if (dict_table_is_sdi(table->id)
640 #ifndef UNIV_HOTBACKUP
641 || dict_table_is_system(table->id)
642 #endif /* !UNIV_HOTBACKUP */
643 ) {
644 #ifndef UNIV_HOTBACKUP
645 my_error(ER_TABLE_CORRUPT, MYF(0), "", table->name.m_name);
646 #else /* !UNIV_HOTBACKUP */
647 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_168)
648 << "table is corrupt: " << table->name.m_name;
649 #endif /* !UNIV_HOTBACKUP */
650 } else {
651 #ifndef UNIV_HOTBACKUP
652 std::string db_str;
653 std::string tbl_str;
654 dict_name::get_table(table->name.m_name, db_str, tbl_str);
655
656 my_error(ER_TABLE_CORRUPT, MYF(0), db_str.c_str(), tbl_str.c_str());
657 #else /* !UNIV_HOTBACKUP */
658 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_169)
659 << "table is corrupt: " << table->name.m_name;
660 #endif /* !UNIV_HOTBACKUP */
661 }
662 table = nullptr;
663 return HA_ERR_TABLE_CORRUPT;
664 }
665
666 dict_index_t *index = table->first_index();
667 if (!dict_table_is_sdi(table->id) && fil_space_get(index->space) == nullptr) {
668 #ifndef UNIV_HOTBACKUP
669 if (!dict_table_is_discarded(table)) {
670 my_error(ER_TABLESPACE_MISSING, MYF(0), table->name.m_name);
671 }
672 #else /* !UNIV_HOTBACKUP */
673 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_170)
674 << "table space is missing: " << table->name.m_name;
675 #endif /* !UNIV_HOTBACKUP */
676 table = nullptr;
677 return HA_ERR_TABLESPACE_MISSING;
678 }
679
680 /* Ignore missing tablespaces for secondary indexes. */
681 for (;;) {
682 index = index->next();
683 if (!index) break;
684 if (!index->is_corrupted() && fil_space_get(index->space) == nullptr) {
685 dict_set_corrupted(index);
686 }
687 }
688
689 return 0;
690 }
691
692 /** Open a persistent InnoDB table based on InnoDB table id, and
693 hold Shared MDL lock on it.
694 @param[in] table_id table identifier
695 @param[in,out] thd current MySQL connection (for mdl)
696 @param[in,out] mdl metadata lock (*mdl set if
697 table_id was found) mdl=NULL if we are resurrecting table IX locks in recovery
698 @param[in] dict_locked dict_sys mutex is held
699 @param[in] check_corruption check if the table is corrupted or not.
700 @return table
701 @retval NULL if the table does not exist or cannot be opened */
702 dict_table_t *dd_table_open_on_id(table_id_t table_id, THD *thd,
703 MDL_ticket **mdl, bool dict_locked,
704 bool check_corruption) {
705 dict_table_t *ib_table;
706 const auto hash_value = ut::hash_uint64(table_id);
707 char full_name[MAX_FULL_NAME_LEN + 1];
708
709 if (!dict_locked) {
710 dict_sys_mutex_enter();
711 }
712
713 HASH_SEARCH(id_hash, dict_sys->table_id_hash, hash_value, dict_table_t *,
714 ib_table, ut_ad(ib_table->cached), ib_table->id == table_id);
715
716 reopen:
717 if (ib_table == nullptr) {
718 #ifndef UNIV_HOTBACKUP
719 if (dict_table_is_sdi(table_id)) {
720 /* The table is SDI table */
721 space_id_t space_id = dict_sdi_get_space_id(table_id);
722
723 /* Create in-memory table object for SDI table */
724 dict_index_t *sdi_index =
725 dict_sdi_create_idx_in_mem(space_id, false, 0, false);
726
727 if (sdi_index == nullptr) {
728 if (!dict_locked) {
729 dict_sys_mutex_exit();
730 }
731 return nullptr;
732 }
733
734 ib_table = sdi_index->table;
735
736 ut_ad(ib_table != nullptr);
737 ib_table->acquire();
738
739 if (!dict_locked) {
740 dict_sys_mutex_exit();
741 }
742 } else {
743 dict_sys_mutex_exit();
744
745 ib_table = dd_table_open_on_id_low(thd, mdl, table_id);
746
747 if (dict_locked) {
748 dict_sys_mutex_enter();
749 }
750 }
751 #else /* !UNIV_HOTBACKUP */
752 /* PRELIMINARY TEMPORARY WORKAROUND: is this ever used? */
753 bool not_hotbackup = false;
754 ut_a(not_hotbackup);
755 #endif /* !UNIV_HOTBACKUP */
756 } else if (mdl == nullptr || ib_table->is_temporary() ||
757 dict_table_is_sdi(ib_table->id)) {
758 if (dd_check_corrupted(ib_table)) {
759 ut_ad(ib_table == nullptr);
760 } else {
761 ib_table->acquire();
762 }
763
764 if (!dict_locked) {
765 dict_sys_mutex_exit();
766 }
767 } else {
768 for (;;) {
769 #ifndef UNIV_HOTBACKUP
770 std::string db_str;
771 std::string tbl_str;
772 dict_name::get_table(ib_table->name.m_name, db_str, tbl_str);
773 #endif /* !UNIV_HOTBACKUP */
774
775 memset(full_name, 0, MAX_FULL_NAME_LEN + 1);
776
777 strcpy(full_name, ib_table->name.m_name);
778
779 ut_ad(!ib_table->is_temporary());
780
781 dict_sys_mutex_exit();
782
783 #ifndef UNIV_HOTBACKUP
784 if (db_str.empty() || tbl_str.empty()) {
785 if (dict_locked) {
786 dict_sys_mutex_enter();
787 }
788 return nullptr;
789 }
790
791 if (dd_mdl_acquire(thd, mdl, db_str.c_str(), tbl_str.c_str())) {
792 if (dict_locked) {
793 dict_sys_mutex_enter();
794 }
795 return nullptr;
796 }
797 #endif /* !UNIV_HOTBACKUP */
798
799 /* Re-lookup the table after acquiring MDL. */
800 dict_sys_mutex_enter();
801
802 HASH_SEARCH(id_hash, dict_sys->table_id_hash, hash_value, dict_table_t *,
803 ib_table, ut_ad(ib_table->cached), ib_table->id == table_id);
804
805 if (ib_table != nullptr) {
806 ulint namelen = strlen(ib_table->name.m_name);
807
808 /* The table could have been renamed. After
809 we release dict mutex before the old table
810 name is MDL locked. So we need to go back
811 to MDL lock the new name. */
812 if (namelen != strlen(full_name) ||
813 memcmp(ib_table->name.m_name, full_name, namelen)) {
814 #ifndef UNIV_HOTBACKUP
815 dd_mdl_release(thd, mdl);
816 #endif /* !UNIV_HOTBACKUP */
817 continue;
818 } else if (check_corruption && dd_check_corrupted(ib_table)) {
819 ut_ad(ib_table == nullptr);
820 } else if (ib_table->discard_after_ddl) {
821 #ifndef UNIV_HOTBACKUP
822 btr_drop_ahi_for_table(ib_table);
823 dict_table_remove_from_cache(ib_table);
824 #endif /* !UNIV_HOTBACKUP */
825 ib_table = nullptr;
826 #ifndef UNIV_HOTBACKUP
827 dd_mdl_release(thd, mdl);
828 #endif /* !UNIV_HOTBACKUP */
829 goto reopen;
830 } else {
831 ib_table->acquire_with_lock();
832 }
833 }
834
835 dict_sys_mutex_exit();
836 break;
837 }
838
839 #ifndef UNIV_HOTBACKUP
840 ut_ad(*mdl != nullptr);
841
842 /* Now the table can't be found, release MDL,
843 let dd_table_open_on_id_low() do the lock, as table
844 name could be changed */
845 if (ib_table == nullptr) {
846 dd_mdl_release(thd, mdl);
847 ib_table = dd_table_open_on_id_low(thd, mdl, table_id);
848
849 if (ib_table == nullptr && *mdl != nullptr) {
850 dd_mdl_release(thd, mdl);
851 }
852 }
853 #else /* !UNIV_HOTBACKUP */
854 /* PRELIMINARY TEMPORARY WORKAROUND: is this ever used? */
855 bool not_hotbackup = false;
856 ut_a(not_hotbackup);
857 #endif /* !UNIV_HOTBACKUP */
858
859 if (dict_locked) {
860 dict_sys_mutex_enter();
861 }
862 }
863
864 ut_ad(dict_locked == dict_sys_mutex_own());
865
866 return ib_table;
867 }
868
869 #ifndef UNIV_HOTBACKUP
870 /** Set the discard flag for a non-partitioned dd table.
871 @param[in,out] thd current thread
872 @param[in] table InnoDB table
873 @param[in,out] table_def MySQL dd::Table to update
874 @param[in] discard discard flag
875 @return true if success
876 @retval false if fail. */
877 bool dd_table_discard_tablespace(THD *thd, const dict_table_t *table,
878 dd::Table *table_def, bool discard) {
879 bool ret = false;
880
881 DBUG_TRACE;
882
883 ut_ad(thd == current_thd);
884 #ifdef UNIV_DEBUG
885 btrsea_sync_check check(false);
886 ut_ad(!sync_check_iterate(check));
887 #endif /* UNIV_DEBUG */
888
889 ut_ad(srv_shutdown_state.load() < SRV_SHUTDOWN_DD);
890
891 if (table_def->se_private_id() != dd::INVALID_OBJECT_ID) {
892 ut_ad(table_def->table().leaf_partitions()->empty());
893
894 /* For discarding, we need to set new private
895 id to dd_table */
896 if (discard) {
897 /* Set the new private id to dd_table object. */
898 table_def->set_se_private_id(table->id);
899 } else {
900 ut_ad(table_def->se_private_id() == table->id);
901 }
902
903 /* Set index root page. */
904 for (auto dd_index : *table_def->indexes()) {
905 const dict_index_t *index = dd_find_index(table, dd_index);
906 ut_ad(index != nullptr);
907
908 dd::Properties &p = dd_index->se_private_data();
909 p.set(dd_index_key_strings[DD_INDEX_ROOT], index->page);
910 }
911
912 /* Set new table id for dd columns */
913 for (auto dd_column : *table_def->columns()) {
914 dd_column->se_private_data().set(dd_index_key_strings[DD_TABLE_ID],
915 table->id);
916 }
917
918 /* Set 'discard' attribute in dd::Table::se_private_data. */
919 dd_set_discarded(*table_def, discard);
920
921 /* Set the 'state' key value in dd::Tablespace::se_private_data*/
922 dd::Object_id dd_space_id =
923 (*table_def->indexes()->begin())->tablespace_id();
924 std::string space_name(table->name.m_name);
925 dict_name::convert_to_space(space_name);
926 dd_space_states dd_state =
927 (discard ? DD_SPACE_STATE_DISCARDED : DD_SPACE_STATE_NORMAL);
928 dd_tablespace_set_state(thd, dd_space_id, space_name, dd_state);
929
930 ret = true;
931 } else {
932 ret = false;
933 }
934
935 return ret;
936 }
937
938 /** Open an internal handle to a persistent InnoDB table by name.
939 @param[in,out] thd current thread
940 @param[out] mdl metadata lock
941 @param[in] name InnoDB table name
942 @param[in] dict_locked has dict_sys mutex locked
943 @param[in] ignore_err whether to ignore err
944 @param[out] error pointer to error
945 @return handle to non-partitioned table
946 @retval NULL if the table does not exist */
947 dict_table_t *dd_table_open_on_name(THD *thd, MDL_ticket **mdl,
948 const char *name, bool dict_locked,
949 ulint ignore_err, int *error) {
950 DBUG_TRACE;
951
952 #ifdef UNIV_DEBUG
953 btrsea_sync_check check(false);
954 ut_ad(!sync_check_iterate(check));
955 #endif
956 ut_ad(srv_shutdown_state.load() < SRV_SHUTDOWN_DD);
957
958 dict_table_t *table = nullptr;
959
960 /* Get pointer to a table object in InnoDB dictionary cache.
961 For intrinsic table, get it from session private data */
962 if (thd) {
963 table = thd_to_innodb_session(thd)->lookup_table_handler(name);
964 }
965
966 if (table != nullptr) {
967 table->acquire();
968 return table;
969 }
970
971 std::string db_name;
972 std::string tbl_name;
973 dict_name::get_table(name, db_name, tbl_name);
974
975 if (db_name.empty() || tbl_name.empty()) {
976 return nullptr;
977 }
978
979 bool skip_mdl = !(thd && mdl);
980
981 if (!skip_mdl) {
982 if (dict_locked) {
983 /* We cannot acquire MDL while holding dict_sys->mutex. The reason that
984 the caller has already locked this mutex is so that the dict_table_t
985 that we will find and return to it will not be dropped while the caller
986 is using it. So it is safe to exit, get the mdl and enter again before
987 finding this dict_table_t. */
988 dict_sys_mutex_exit();
989 }
990
991 bool got_mdl = dd_mdl_acquire(thd, mdl, db_name.c_str(), tbl_name.c_str());
992
993 if (dict_locked) {
994 dict_sys_mutex_enter();
995 }
996
997 if (got_mdl) {
998 return nullptr;
999 }
1000 }
1001
1002 if (!dict_locked) {
1003 dict_sys_mutex_enter();
1004 }
1005
1006 table = dict_table_check_if_in_cache_low(name);
1007
1008 if (table != nullptr) {
1009 table->acquire_with_lock();
1010 if (!dict_locked) {
1011 dict_sys_mutex_exit();
1012 }
1013 return table;
1014 }
1015
1016 dict_sys_mutex_exit();
1017
1018 const dd::Table *dd_table = nullptr;
1019 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
1020 dd::cache::Dictionary_client::Auto_releaser releaser(client);
1021
1022 if (client->acquire(db_name.c_str(), tbl_name.c_str(), &dd_table) ||
1023 dd_table == nullptr || dd_table->engine() != innobase_hton_name) {
1024 /* The checking for engine should be only useful(valid)
1025 for getting table statistics for IS. Two relevant API
1026 functions are:
1027 1. innobase_get_table_statistics
1028 2. innobase_get_index_column_cardinality */
1029 table = nullptr;
1030 } else {
1031 if (dd_table->se_private_id() == dd::INVALID_OBJECT_ID) {
1032 ut_ad(!dd_table->leaf_partitions().empty());
1033
1034 if (dict_name::is_partition(name)) {
1035 const dd::Partition *dd_part = nullptr;
1036
1037 for (auto part : dd_table->leaf_partitions()) {
1038 if (dict_name::match_partition(name, part)) {
1039 dd_part = part;
1040 break;
1041 }
1042 }
1043
1044 /* Safe check for release mode. */
1045 if (dd_part == nullptr) {
1046 table = nullptr;
1047 ut_d(ut_error);
1048 } else {
1049 dd_table_open_on_dd_obj(thd, client, *dd_table, dd_part, name, table,
1050 nullptr);
1051 }
1052
1053 } else {
1054 /* FIXME: Once FK functions will not open
1055 partitioned table in current improper way,
1056 just assert this false */
1057 table = nullptr;
1058 }
1059 } else {
1060 ut_ad(dd_table->leaf_partitions().empty());
1061 int err = dd_table_open_on_dd_obj(thd, client, *dd_table, nullptr, name,
1062 table, nullptr);
1063 if (error) {
1064 *error = err;
1065 }
1066 }
1067 }
1068
1069 if (table && table->is_corrupted() &&
1070 !(ignore_err & DICT_ERR_IGNORE_CORRUPT)) {
1071 dict_sys_mutex_enter();
1072 table->release();
1073 dict_table_remove_from_cache(table);
1074 table = nullptr;
1075 dict_sys_mutex_exit();
1076 }
1077
1078 if (table == nullptr && mdl) {
1079 dd_mdl_release(thd, mdl);
1080 *mdl = nullptr;
1081 }
1082
1083 if (dict_locked) {
1084 dict_sys_mutex_enter();
1085 }
1086
1087 return table;
1088 }
1089 #endif /* !UNIV_HOTBACKUP */
1090
1091 /** Close an internal InnoDB table handle.
1092 @param[in,out] table InnoDB table handle
1093 @param[in,out] thd current MySQL connection (for mdl)
1094 @param[in,out] mdl metadata lock (will be set NULL)
1095 @param[in] dict_locked whether we hold dict_sys mutex */
1096 void dd_table_close(dict_table_t *table, THD *thd, MDL_ticket **mdl,
1097 bool dict_locked) {
1098 dict_table_close(table, dict_locked, false);
1099
1100 #ifndef UNIV_HOTBACKUP
1101 if (mdl != nullptr && *mdl != nullptr) {
1102 ut_ad(!table->is_temporary());
1103 dd_mdl_release(thd, mdl);
1104 }
1105 #endif /* !UNIV_HOTBACKUP */
1106 }
1107
1108 #ifndef UNIV_HOTBACKUP
1109 /** Replace the tablespace name in the file name.
1110 @param[in] dd_file the tablespace file object.
1111 @param[in] new_space_name new table space name to be updated in file name.
1112 It must have already been converted to the
1113 filename_charset such that
1114 `d1/d2\d3`.`t3\t4/t5`
1115 should look like:
1116 d1@002fd2@005cd3/t3@005ct4@002ft5
1117 both on Windows and on Linux. */
1118 static void replace_space_name_in_file_name(dd::Tablespace_file *dd_file,
1119 dd::String_type new_space_name) {
1120 ut_ad(std::count(new_space_name.begin(), new_space_name.end(),
1121 Fil_path::DB_SEPARATOR) == 1);
1122
1123 /* Obtain the old tablespace file name. */
1124 dd::String_type old_file_name = dd_file->filename();
1125
1126 /* We assume that old_file_name ends with:
1127 OS_PATH_SEPARATOR + db_name + OS_PATH_SEPARATOR + table_name + dot_ext[IBD],
1128 so on Windows it can look like:
1129 .\d1@002fd2@005cd3\t1@[email protected]
1130 and on Linux it could be:
1131 ./d1@002fd2@005cd3/t1@[email protected] */
1132 ut_ad(std::count(old_file_name.begin(), old_file_name.end(),
1133 OS_PATH_SEPARATOR) >= 2);
1134 ut_ad(old_file_name.rfind(dot_ext[IBD]) ==
1135 old_file_name.length() - strlen(dot_ext[IBD]));
1136
1137 /* Strip the last two components of the path (keep the slash) */
1138 auto last_separator_pos = old_file_name.find_last_of(OS_PATH_SEPARATOR);
1139 auto previous_separator_pos =
1140 old_file_name.find_last_of(OS_PATH_SEPARATOR, last_separator_pos - 1);
1141 old_file_name.resize(previous_separator_pos + 1);
1142
1143 /* Take care of path separators */
1144 std::replace(new_space_name.begin(), new_space_name.end(),
1145 Fil_path::DB_SEPARATOR, OS_PATH_SEPARATOR);
1146
1147 old_file_name += new_space_name + dot_ext[IBD];
1148
1149 /* Update the file name path */
1150 dd_file->set_filename(old_file_name);
1151 }
1152
1153 /** Convert string to lower case.
1154 @param[in,out] name name to convert */
1155 static void to_lower(std::string &name) { innobase_casedn_str(name.data()); }
1156
1157 dberr_t dd_update_table_and_partitions_after_dir_change(dd::Object_id object_id,
1158 std::string path) {
1159 THD *thd = current_thd;
1160 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
1161 dd::cache::Dictionary_client::Auto_releaser releaser(client);
1162
1163 dd::Tablespace *dd_space;
1164 dd::Table *dd_table;
1165
1166 /* Get the dd tablespace */
1167 if (client->acquire_uncached_uncommitted<dd::Tablespace>(object_id,
1168 &dd_space) ||
1169 dd_space == nullptr) {
1170 ut_d(ut_error);
1171 ut_o(return DB_ERROR);
1172 }
1173
1174 const dd::Properties &space_properties = dd_space->se_private_data();
1175 uint32_t flags = 0;
1176 space_properties.get(dd_space_key_strings[DD_SPACE_FLAGS], &flags);
1177
1178 if (fsp_is_shared_tablespace(flags)) {
1179 /* This is a shared tablespace, dd_table is empty */
1180 return DB_SUCCESS;
1181 }
1182
1183 const auto components = dict_name::parse_tablespace_path(path);
1184 if (!components.has_value()) return DB_ERROR;
1185 const auto table_info = components.value();
1186
1187 MDL_ticket *tab_ticket = nullptr;
1188 if (dd::acquire_exclusive_table_mdl(thd, table_info.schema_name.c_str(),
1189 table_info.table_name.c_str(), false,
1190 &tab_ticket)) {
1191 ut_d(ut_error);
1192 ut_o(return DB_ERROR);
1193 }
1194
1195 /* Acquire the new dd table for modification */
1196 if (client->acquire_for_modification<dd::Table>(
1197 table_info.schema_name.c_str(), table_info.table_name.c_str(),
1198 &dd_table)) {
1199 ut_d(ut_error);
1200 ut_o(return DB_ERROR);
1201 }
1202
1203 std::string dd_table_name{dd_table->table().name()};
1204 Fil_path fpath{path};
1205
1206 bool set_true = !MySQL_datadir_path.is_ancestor(fpath);
1207 if (!dd_table_is_partitioned(*dd_table)) {
1208 /* Set the DATA DIRECTORY FLAG to true for dd table if ibd file is moved to
1209 directory other than default data dir. Remove the flag if moved from
1210 external to default data dir.*/
1211 if (set_true) {
1212 dd_table->se_private_data().set(
1213 dd_table_key_strings[DD_TABLE_DATA_DIRECTORY], set_true);
1214 } else {
1215 dd_table->se_private_data().remove(
1216 dd_table_key_strings[DD_TABLE_DATA_DIRECTORY]);
1217 }
1218 } else {
1219 dd::Partition *part_obj = dd_table->get_leaf_partition(
1220 (!table_info.subpartition.empty()) ? table_info.subpartition
1221 : table_info.partition);
1222 if (!part_obj) {
1223 ut_d(ut_error);
1224 ut_o(return DB_ERROR);
1225 }
1226 dd::Properties &part_options = part_obj->options();
1227 if (set_true) {
1228 part_obj->se_private_data().set(
1229 dd_table_key_strings[DD_TABLE_DATA_DIRECTORY], true);
1230 /* Update data_file_name for dd::partition as we do not set data
1231 directory for whole partitioned table. We acquire dd::partition later
1232 and read from it*/
1233 part_options.set(data_file_name_key, table_info.directory.c_str());
1234 } else {
1235 part_obj->se_private_data().remove(
1236 dd_table_key_strings[DD_TABLE_DATA_DIRECTORY]);
1237 part_options.remove(data_file_name_key);
1238 }
1239 }
1240
1241 bool fail = client->update(dd_table);
1242 return fail ? DB_ERROR : DB_SUCCESS;
1243 }
1244
1245 dberr_t dd_tablespace_rename(dd::Object_id dd_space_id, bool is_system_cs,
1246 const char *new_space_name, const char *new_path) {
1247 THD *thd = current_thd;
1248
1249 DBUG_TRACE;
1250 #ifdef UNIV_DEBUG
1251 btrsea_sync_check check(false);
1252 ut_ad(!sync_check_iterate(check));
1253 #endif /* UNIV_DEBUG */
1254 ut_ad(srv_shutdown_state.load() < SRV_SHUTDOWN_DD);
1255
1256 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
1257 dd::cache::Dictionary_client::Auto_releaser releaser(client);
1258
1259 dd::Tablespace *dd_space = nullptr;
1260
1261 /* Get the dd tablespace */
1262 if (client->acquire_uncached_uncommitted<dd::Tablespace>(dd_space_id,
1263 &dd_space) ||
1264 dd_space == nullptr) {
1265 ut_d(ut_error);
1266 ut_o(return DB_ERROR);
1267 }
1268
1269 MDL_ticket *src_ticket = nullptr;
1270 if (dd_tablespace_get_mdl(dd_space->name().c_str(), &src_ticket)) {
1271 ut_d(ut_error);
1272 ut_o(return DB_ERROR);
1273 }
1274
1275 std::string tablespace_name(new_space_name);
1276 /* Convert if not in system character set. */
1277 if (!is_system_cs) {
1278 dict_name::convert_to_space(tablespace_name);
1279 }
1280
1281 MDL_ticket *dst_ticket = nullptr;
1282 if (dd_tablespace_get_mdl(tablespace_name.c_str(), &dst_ticket)) {
1283 ut_d(ut_error);
1284 ut_o(return DB_ERROR);
1285 }
1286
1287 dd::Tablespace *new_space = nullptr;
1288
1289 /* Acquire the new dd tablespace for modification */
1290 if (client->acquire_for_modification<dd::Tablespace>(dd_space_id,
1291 &new_space)) {
1292 ut_d(ut_error);
1293 ut_o(return DB_ERROR);
1294 }
1295
1296 ut_ad(new_space->files().size() == 1);
1297
1298 dd::String_type old_space_name = new_space->name();
1299
1300 new_space->set_name(tablespace_name.c_str());
1301
1302 dd::Tablespace_file *dd_file =
1303 const_cast<dd::Tablespace_file *>(*(new_space->files().begin()));
1304
1305 if (new_path != nullptr) {
1306 dd_file->set_filename(new_path);
1307
1308 } else {
1309 replace_space_name_in_file_name(dd_file, new_space_name);
1310 ut_ad(dd_tablespace_get_state_enum(dd_space) == DD_SPACE_STATE_DISCARDED);
1311 }
1312
1313 bool fail = client->update(new_space);
1314 ut_ad(!fail);
1315 dd::rename_tablespace_mdl_hook(thd, src_ticket, dst_ticket);
1316
1317 return fail ? DB_ERROR : DB_SUCCESS;
1318 }
1319
1320 /** Validate the table format options.
1321 @param[in] thd THD instance
1322 @param[in] form MySQL table definition
1323 @param[in] real_type real row type if it's not ROW_TYPE_NOT_USED
1324 @param[in] zip_allowed whether ROW_FORMAT=COMPRESSED is OK
1325 @param[in] strict whether innodb_strict_mode=ON
1326 @param[out] is_redundant whether ROW_FORMAT=REDUNDANT
1327 @param[out] blob_prefix whether ROW_FORMAT=DYNAMIC
1328 or ROW_FORMAT=COMPRESSED
1329 @param[out] zip_ssize log2(compressed page size),
1330 or 0 if not ROW_FORMAT=COMPRESSED
1331 @param[out] is_implicit if tablespace is implicit
1332 @retval true if invalid (my_error will have been called)
1333 @retval false if valid */
1334 static bool format_validate(THD *thd, const TABLE *form, row_type real_type,
1335 bool zip_allowed, bool strict, bool *is_redundant,
1336 bool *blob_prefix, ulint *zip_ssize,
1337 bool is_implicit) {
1338 bool is_temporary = false;
1339 ut_ad(thd != nullptr);
1340 ut_ad(!zip_allowed || srv_page_size <= UNIV_ZIP_SIZE_MAX);
1341
1342 /* 1+log2(compressed_page_size), or 0 if not compressed */
1343 *zip_ssize = 0;
1344 const ulint zip_ssize_max =
1345 std::min((ulint)UNIV_PAGE_SSIZE_MAX, (ulint)PAGE_ZIP_SSIZE_MAX);
1346 const char *zip_refused = zip_allowed ? nullptr
1347 : srv_page_size <= UNIV_ZIP_SIZE_MAX
1348 ? "innodb_file_per_table=OFF"
1349 : "innodb_page_size>16k";
1350 bool invalid = false;
1351
1352 if (real_type == ROW_TYPE_NOT_USED) {
1353 real_type = form->s->real_row_type;
1354 }
1355
1356 if (auto key_block_size = form->s->key_block_size) {
1357 unsigned valid_zssize = 0;
1358 char kbs[MY_INT32_NUM_DECIMAL_DIGITS + sizeof "KEY_BLOCK_SIZE=" + 1];
1359 snprintf(kbs, sizeof kbs, "KEY_BLOCK_SIZE=%u", key_block_size);
1360 for (unsigned kbsize = 1, zssize = 1; zssize <= zip_ssize_max;
1361 zssize++, kbsize <<= 1) {
1362 if (kbsize == key_block_size) {
1363 valid_zssize = zssize;
1364 break;
1365 }
1366 }
1367
1368 if (valid_zssize == 0) {
1369 if (strict) {
1370 my_error(ER_WRONG_VALUE, MYF(0), "KEY_BLOCK_SIZE",
1371 kbs + sizeof "KEY_BLOCK_SIZE");
1372 invalid = true;
1373 } else {
1374 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_VALUE,
1375 ER_DEFAULT(ER_WRONG_VALUE), "KEY_BLOCK_SIZE",
1376 kbs + sizeof "KEY_BLOCK_SIZE");
1377 }
1378 } else if (!zip_allowed) {
1379 int error = is_temporary ? ER_UNSUPPORT_COMPRESSED_TEMPORARY_TABLE
1380 : ER_ILLEGAL_HA_CREATE_OPTION;
1381
1382 if (strict) {
1383 my_error(error, MYF(0), innobase_hton_name, kbs, zip_refused);
1384 invalid = true;
1385 } else {
1386 push_warning_printf(thd, Sql_condition::SL_WARNING, error,
1387 ER_DEFAULT_NONCONST(error), innobase_hton_name, kbs,
1388 zip_refused);
1389 }
1390 } else if (real_type != ROW_TYPE_COMPRESSED) {
1391 /* This could happen when
1392 1. There was an ALTER TABLE ... COPY to move
1393 the table from COMPRESSED into DYNAMIC, etc.
1394 2. For partitioned table, some partitions of which
1395 could be of different row format from the specified
1396 one */
1397 } else if (form->s->row_type == ROW_TYPE_DEFAULT ||
1398 form->s->row_type == ROW_TYPE_COMPRESSED) {
1399 ut_ad(real_type == ROW_TYPE_COMPRESSED);
1400 *zip_ssize = valid_zssize;
1401 } else {
1402 int error = is_temporary ? ER_UNSUPPORT_COMPRESSED_TEMPORARY_TABLE
1403 : ER_ILLEGAL_HA_CREATE_OPTION;
1404 const char *conflict = get_row_format_name(form->s->row_type);
1405
1406 if (strict) {
1407 my_error(error, MYF(0), innobase_hton_name, kbs, conflict);
1408 invalid = true;
1409 } else {
1410 push_warning_printf(thd, Sql_condition::SL_WARNING, error,
1411 ER_DEFAULT_NONCONST(error), innobase_hton_name, kbs,
1412 conflict);
1413 }
1414 }
1415 } else if (form->s->row_type != ROW_TYPE_COMPRESSED || !is_temporary) {
1416 /* not ROW_FORMAT=COMPRESSED (nor KEY_BLOCK_SIZE),
1417 or not TEMPORARY TABLE */
1418 } else if (strict) {
1419 my_error(ER_UNSUPPORT_COMPRESSED_TEMPORARY_TABLE, MYF(0));
1420 invalid = true;
1421 } else {
1422 push_warning(thd, Sql_condition::SL_WARNING,
1423 ER_UNSUPPORT_COMPRESSED_TEMPORARY_TABLE,
1424 ER_THD(thd, ER_UNSUPPORT_COMPRESSED_TEMPORARY_TABLE));
1425 }
1426
1427 /* Check for a valid InnoDB ROW_FORMAT specifier and
1428 other incompatibilities. */
1429 rec_format_t innodb_row_format = REC_FORMAT_DYNAMIC;
1430
1431 switch (form->s->row_type) {
1432 case ROW_TYPE_DYNAMIC:
1433 ut_ad(*zip_ssize == 0);
1434 /* If non strict_mode, row type can be converted between
1435 COMPRESSED and DYNAMIC */
1436 ut_ad(real_type == ROW_TYPE_DYNAMIC || real_type == ROW_TYPE_COMPRESSED);
1437 break;
1438 case ROW_TYPE_COMPACT:
1439 ut_ad(*zip_ssize == 0);
1440 ut_ad(real_type == ROW_TYPE_COMPACT);
1441 innodb_row_format = REC_FORMAT_COMPACT;
1442 break;
1443 case ROW_TYPE_REDUNDANT:
1444 ut_ad(*zip_ssize == 0);
1445 ut_ad(real_type == ROW_TYPE_REDUNDANT);
1446 innodb_row_format = REC_FORMAT_REDUNDANT;
1447 break;
1448 case ROW_TYPE_FIXED:
1449 case ROW_TYPE_PAGED:
1450 case ROW_TYPE_NOT_USED: {
1451 const char *name = get_row_format_name(form->s->row_type);
1452 if (strict) {
1453 my_error(ER_ILLEGAL_HA_CREATE_OPTION, MYF(0), innobase_hton_name, name);
1454 invalid = true;
1455 } else {
1456 push_warning_printf(
1457 thd, Sql_condition::SL_WARNING, ER_ILLEGAL_HA_CREATE_OPTION,
1458 ER_DEFAULT(ER_ILLEGAL_HA_CREATE_OPTION), innobase_hton_name, name);
1459 }
1460 }
1461 [[fallthrough]];
1462 case ROW_TYPE_DEFAULT:
1463 switch (real_type) {
1464 case ROW_TYPE_FIXED:
1465 case ROW_TYPE_PAGED:
1466 case ROW_TYPE_NOT_USED:
1467 case ROW_TYPE_DEFAULT:
1468 /* get_real_row_type() should not return these */
1469 ut_d(ut_error);
1470 [[fallthrough]];
1471 case ROW_TYPE_DYNAMIC:
1472 ut_ad(*zip_ssize == 0);
1473 break;
1474 case ROW_TYPE_COMPACT:
1475 ut_ad(*zip_ssize == 0);
1476 innodb_row_format = REC_FORMAT_COMPACT;
1477 break;
1478 case ROW_TYPE_REDUNDANT:
1479 ut_ad(*zip_ssize == 0);
1480 innodb_row_format = REC_FORMAT_REDUNDANT;
1481 break;
1482 case ROW_TYPE_COMPRESSED:
1483 innodb_row_format = REC_FORMAT_COMPRESSED;
1484 break;
1485 }
1486
1487 if (*zip_ssize == 0) {
1488 /* No valid KEY_BLOCK_SIZE was specified,
1489 so do not imply ROW_FORMAT=COMPRESSED. */
1490 if (innodb_row_format == REC_FORMAT_COMPRESSED) {
1491 innodb_row_format = REC_FORMAT_DYNAMIC;
1492 }
1493 break;
1494 }
1495 [[fallthrough]];
1496 case ROW_TYPE_COMPRESSED:
1497 if (is_temporary) {
1498 if (strict) {
1499 invalid = true;
1500 }
1501 /* ER_UNSUPPORT_COMPRESSED_TEMPORARY_TABLE
1502 was already reported. */
1503 ut_ad(real_type == ROW_TYPE_DYNAMIC);
1504 break;
1505 } else if (zip_allowed && real_type == ROW_TYPE_COMPRESSED) {
1506 /* ROW_FORMAT=COMPRESSED without KEY_BLOCK_SIZE
1507 implies half the maximum compressed page size. */
1508 if (*zip_ssize == 0) {
1509 *zip_ssize = zip_ssize_max - 1;
1510 }
1511 innodb_row_format = REC_FORMAT_COMPRESSED;
1512 break;
1513 }
1514
1515 if (strict) {
1516 my_error(ER_ILLEGAL_HA_CREATE_OPTION, MYF(0), innobase_hton_name,
1517 "ROW_FORMAT=COMPRESSED", zip_refused);
1518 invalid = true;
1519 }
1520 }
1521
1522 if (const char *algorithm =
1523 form->s->compress.length > 0 ? form->s->compress.str : nullptr) {
1524 Compression compression;
1525 dberr_t err = Compression::check(algorithm, &compression);
1526
1527 if (err == DB_UNSUPPORTED) {
1528 if (strict) {
1529 my_error(ER_WRONG_VALUE, MYF(0), "COMPRESSION", algorithm);
1530 invalid = true;
1531 } else {
1532 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_VALUE,
1533 ER_DEFAULT(ER_WRONG_VALUE), "COMPRESSION",
1534 algorithm);
1535 }
1536 } else if (compression.m_type != Compression::NONE) {
1537 if (*zip_ssize != 0) {
1538 if (strict) {
1539 my_error(ER_ILLEGAL_HA_CREATE_OPTION, MYF(0), innobase_hton_name,
1540 "COMPRESSION",
1541 form->s->key_block_size ? "KEY_BLOCK_SIZE"
1542 : "ROW_FORMAT=COMPRESSED");
1543 invalid = true;
1544 }
1545 }
1546
1547 if (is_temporary) {
1548 my_error(ER_ILLEGAL_HA_CREATE_OPTION, MYF(0), innobase_hton_name,
1549 "COMPRESSION", "TEMPORARY");
1550 invalid = true;
1551 } else if (!is_implicit && strict) {
1552 my_error(ER_ILLEGAL_HA_CREATE_OPTION, MYF(0), innobase_hton_name,
1553 "COMPRESSION", "TABLESPACE");
1554 invalid = true;
1555 }
1556 }
1557 }
1558
1559 /* Check if there are any FTS indexes defined on this table. */
1560 for (uint i = 0; i < form->s->keys; i++) {
1561 const KEY *key = &form->key_info[i];
1562
1563 if ((key->flags & HA_FULLTEXT) && is_temporary) {
1564 /* We don't support FTS indexes in temporary
1565 tables. */
1566 my_error(ER_INNODB_NO_FT_TEMP_TABLE, MYF(0));
1567 return true;
1568 }
1569 }
1570
1571 ut_ad((*zip_ssize == 0) == (innodb_row_format != REC_FORMAT_COMPRESSED));
1572
1573 *is_redundant = false;
1574 *blob_prefix = false;
1575
1576 switch (innodb_row_format) {
1577 case REC_FORMAT_REDUNDANT:
1578 *is_redundant = true;
1579 *blob_prefix = true;
1580 break;
1581 case REC_FORMAT_COMPACT:
1582 *blob_prefix = true;
1583 break;
1584 case REC_FORMAT_COMPRESSED:
1585 ut_ad(!is_temporary);
1586 break;
1587 case REC_FORMAT_DYNAMIC:
1588 break;
1589 }
1590
1591 return invalid;
1592 }
1593
1594 /** Set the AUTO_INCREMENT attribute.
1595 @param[in,out] se_private_data dd::Table::se_private_data
1596 @param[in] autoinc the auto-increment value */
1597 void dd_set_autoinc(dd::Properties &se_private_data, uint64_t autoinc) {
1598 /* The value of "autoinc" here is the AUTO_INCREMENT attribute
1599 specified at table creation. AUTO_INCREMENT=0 will silently
1600 be treated as AUTO_INCREMENT=1. Likewise, if no AUTO_INCREMENT
1601 attribute was specified, the value would be 0. */
1602
1603 if (autoinc > 0) {
1604 /* InnoDB persists the "previous" AUTO_INCREMENT value. */
1605 autoinc--;
1606 }
1607
1608 uint64_t version = 0;
1609
1610 if (se_private_data.exists(dd_table_key_strings[DD_TABLE_AUTOINC])) {
1611 /* Increment the dynamic metadata version, so that
1612 any previously buffered persistent dynamic metadata
1613 will be ignored after this transaction commits. */
1614
1615 if (!se_private_data.get(dd_table_key_strings[DD_TABLE_VERSION],
1616 &version)) {
1617 version++;
1618 } else {
1619 /* incomplete se_private_data */
1620 ut_d(ut_error);
1621 }
1622 }
1623
1624 se_private_data.set(dd_table_key_strings[DD_TABLE_VERSION], version);
1625 se_private_data.set(dd_table_key_strings[DD_TABLE_AUTOINC], autoinc);
1626 }
1627
1628 /** Copy the AUTO_INCREMENT and version attribute if exist.
1629 @param[in] src dd::Table::se_private_data to copy from
1630 @param[out] dest dd::Table::se_private_data to copy to */
1631 void dd_copy_autoinc(const dd::Properties &src, dd::Properties &dest) {
1632 uint64_t autoinc = 0;
1633 uint64_t version = 0;
1634
1635 if (!src.exists(dd_table_key_strings[DD_TABLE_AUTOINC])) {
1636 return;
1637 }
1638
1639 if (src.get(dd_table_key_strings[DD_TABLE_AUTOINC],
1640 reinterpret_cast<uint64_t *>(&autoinc)) ||
1641 src.get(dd_table_key_strings[DD_TABLE_VERSION],
1642 reinterpret_cast<uint64_t *>(&version))) {
1643 ut_d(ut_error);
1644 ut_o(return);
1645 }
1646
1647 dest.set(dd_table_key_strings[DD_TABLE_VERSION], version);
1648 dest.set(dd_table_key_strings[DD_TABLE_AUTOINC], autoinc);
1649 }
1650
1651 /** Copy the metadata of a table definition if there was an instant
1652 ADD COLUMN happened. This should be done when it's not an ALTER TABLE
1653 with rebuild.
1654 @param[in,out] new_table New table definition
1655 @param[in] old_table Old table definition */
1656 void dd_copy_instant_n_cols(dd::Table &new_table, const dd::Table &old_table) {
1657 ut_ad(dd_table_is_upgraded_instant(old_table));
1658
1659 if (!dd_table_is_upgraded_instant(new_table)) {
1660 uint32_t cols;
1661 old_table.se_private_data().get(dd_table_key_strings[DD_TABLE_INSTANT_COLS],
1662 &cols);
1663 new_table.se_private_data().set(dd_table_key_strings[DD_TABLE_INSTANT_COLS],
1664 cols);
1665 }
1666 #ifdef UNIV_DEBUG
1667 else {
1668 uint32_t old_cols, new_cols;
1669 old_table.se_private_data().get(dd_table_key_strings[DD_TABLE_INSTANT_COLS],
1670 &old_cols);
1671 new_table.se_private_data().get(dd_table_key_strings[DD_TABLE_INSTANT_COLS],
1672 &new_cols);
1673 ut_ad(old_cols == new_cols);
1674 }
1675 #endif /* UNIV_DEBUG */
1676 }
1677
1678 template <typename Table>
1679 void dd_copy_private(Table &new_table, const Table &old_table) {
1680 uint64_t autoinc = 0;
1681 uint64_t version = 0;
1682 bool reset = false;
1683 dd::Properties &se_private_data = new_table.se_private_data();
1684
1685 /* AUTOINC metadata could be set at the beginning for
1686 non-partitioned tables. So already set metadata should be kept */
1687 if (se_private_data.exists(dd_table_key_strings[DD_TABLE_AUTOINC])) {
1688 se_private_data.get(dd_table_key_strings[DD_TABLE_AUTOINC], &autoinc);
1689 se_private_data.get(dd_table_key_strings[DD_TABLE_VERSION], &version);
1690 reset = true;
1691 }
1692
1693 new_table.se_private_data().clear();
1694
1695 new_table.set_se_private_id(old_table.se_private_id());
1696 new_table.set_se_private_data(old_table.se_private_data());
1697
1698 if (!dd_table_is_partitioned(new_table.table()) ||
1699 dd_part_is_first(reinterpret_cast<dd::Partition *>(&new_table))) {
1700 /* copy table se-private data for first partition */
1701 new_table.table().se_private_data().clear();
1702 new_table.table().set_se_private_data(old_table.table().se_private_data());
1703 }
1704
1705 if (reset) {
1706 se_private_data.set(dd_table_key_strings[DD_TABLE_VERSION], version);
1707 se_private_data.set(dd_table_key_strings[DD_TABLE_AUTOINC], autoinc);
1708 }
1709
1710 ut_ad(new_table.indexes()->size() == old_table.indexes().size());
1711
1712 /* Note that server could provide old and new dd::Table with
1713 different index order in this case, so always do a double loop */
1714 for (const auto old_index : old_table.indexes()) {
1715 auto idx = new_table.indexes()->begin();
1716 for (; (*idx)->name() != old_index->name(); ++idx)
1717 ;
1718 ut_ad(idx != new_table.indexes()->end());
1719
1720 auto new_index = *idx;
1721 ut_ad(!old_index->se_private_data().empty());
1722 ut_ad(new_index != nullptr);
1723 ut_ad(new_index->se_private_data().empty());
1724 ut_ad(new_index->name() == old_index->name());
1725
1726 new_index->set_se_private_data(old_index->se_private_data());
1727 new_index->set_tablespace_id(old_index->tablespace_id());
1728 }
1729
1730 new_table.table().set_row_format(old_table.table().row_format());
1731 }
1732
1733 template void dd_copy_private<dd::Table>(dd::Table &, const dd::Table &);
1734 template void dd_copy_private<dd::Partition>(dd::Partition &,
1735 const dd::Partition &);
1736
1737 bool is_renamed(const Alter_inplace_info *ha_alter_info, const char *old_name,
1738 std::string &new_name) {
1739 List_iterator_fast<Create_field> cf_it(
1740 ha_alter_info->alter_info->create_list);
1741 cf_it.rewind();
1742 Create_field *cf;
1743 while ((cf = cf_it++) != nullptr) {
1744 if (cf->field && cf->field->is_flag_set(FIELD_IS_RENAMED) &&
1745 !my_strcasecmp(system_charset_info, old_name, cf->change)) {
1746 /* This column is being renamed */
1747 new_name = cf->field_name;
1748 return true;
1749 }
1750 }
1751
1752 return false;
1753 }
1754
1755 bool is_dropped(const Alter_inplace_info *ha_alter_info,
1756 const char *column_name) {
1757 for (const Alter_drop *drop : ha_alter_info->alter_info->drop_list) {
1758 if (drop->type != Alter_drop::COLUMN) continue;
1759
1760 if (!my_strcasecmp(system_charset_info, column_name, drop->name)) {
1761 return true;
1762 }
1763 }
1764
1765 return false;
1766 }
1767
1768 void dd_copy_table_columns(const Alter_inplace_info *ha_alter_info,
1769 dd::Table &new_table, const dd::Table &old_table,
1770 dict_table_t *old_dict_table) {
1771 bool first_row_version = false;
1772 if (old_dict_table && !old_dict_table->has_row_versions()) {
1773 first_row_version = true;
1774 }
1775
1776 /* Columns in new table maybe more than old tables, when this is
1777 called for adding instant columns. Also adding and dropping
1778 virtual columns instantly is another case. */
1779
1780 for (const auto old_col : old_table.columns()) {
1781 if (old_col->is_se_hidden() && !is_system_column(old_col->name().c_str()) &&
1782 (strcmp(old_col->name().c_str(), FTS_DOC_ID_COL_NAME) != 0)) {
1783 /* Must be an already dropped column. */
1784 ut_ad(dd_column_is_dropped(old_col));
1785 continue;
1786 }
1787
1788 dd::Column *new_col = nullptr;
1789 std::string new_name;
1790
1791 /* Skip the dropped column */
1792 if (is_dropped(ha_alter_info, old_col->name().c_str())) {
1793 continue;
1794 } else if (is_renamed(ha_alter_info, old_col->name().c_str(), new_name)) {
1795 new_col = const_cast<dd::Column *>(
1796 dd_find_column(&new_table, new_name.c_str()));
1797 } else {
1798 new_col = const_cast<dd::Column *>(
1799 dd_find_column(&new_table, old_col->name().c_str()));
1800 }
1801
1802 ut_a(new_col);
1803
1804 const char *s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
1805 if (!old_col->se_private_data().empty()) {
1806 if (!new_col->se_private_data().empty())
1807 new_col->se_private_data().clear();
1808 new_col->set_se_private_data(old_col->se_private_data());
1809 }
1810
1811 /* If this is first time table is getting row version, add physical pos */
1812 if (old_dict_table && !new_col->is_virtual() && first_row_version) {
1813 /* Even the renamed column would have same phy_pos as old column */
1814 dict_col_t *col =
1815 old_dict_table->get_col_by_name(old_col->name().c_str());
1816 ut_a(col != nullptr);
1817 new_col->se_private_data().set(s, col->get_phy_pos());
1818 }
1819 }
1820 }
1821
1822 void dd_part_adjust_table_id(dd::Table *new_table) {
1823 ut_ad(dd_table_is_partitioned(*new_table));
1824
1825 auto part = new_table->leaf_partitions()->begin();
1826 table_id_t table_id = (*part)->se_private_id();
1827
1828 for (auto dd_column : *new_table->table().columns()) {
1829 dd_column->se_private_data().set(dd_index_key_strings[DD_TABLE_ID],
1830 table_id);
1831 }
1832 }
1833
1834 /** Clear the instant ADD COLUMN information of a table
1835 @param[in,out] dd_table dd::Table
1836 @param[in] clear_version true if version metadata is to be cleared
1837 @return DB_SUCCESS or error code */
1838 dberr_t dd_clear_instant_table(dd::Table &dd_table, bool clear_version) {
1839 dberr_t err = DB_SUCCESS;
1840 dd_table.se_private_data().remove(
1841 dd_table_key_strings[DD_TABLE_INSTANT_COLS]);
1842
1843 std::vector<std::string> cols_to_drop;
1844
1845 for (auto col : *dd_table.columns()) {
1846 auto fn = [&](const char *s) {
1847 if (col->se_private_data().exists(s)) {
1848 col->se_private_data().remove(s);
1849 }
1850 };
1851
1852 if (!clear_version) {
1853 bool is_versioned = dd_column_is_dropped(col) || dd_column_is_added(col);
1854 if (is_versioned) {
1855 continue;
1856 }
1857
1858 /* Possibly an INSTANT ADD column */
1859 fn(dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL]);
1860 fn(dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT]);
1861 } else {
1862 /* Possibly an INSTANT ADD/DROP column with a version */
1863 if (dd_column_is_dropped(col)) {
1864 cols_to_drop.push_back(col->name().c_str());
1865 continue;
1866 }
1867 fn(dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL]);
1868 fn(dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT]);
1869 fn(dd_column_key_strings[DD_INSTANT_VERSION_ADDED]);
1870 fn(dd_column_key_strings[DD_INSTANT_VERSION_DROPPED]);
1871 fn(dd_column_key_strings[DD_INSTANT_PHYSICAL_POS]);
1872 }
1873 }
1874
1875 if (!cols_to_drop.empty()) {
1876 for (auto col_name : cols_to_drop) {
1877 if (!dd_drop_hidden_column(&dd_table, col_name.c_str())) {
1878 ib::error(ER_IB_MSG_CLEAR_INSTANT_DROP_COLUMN_METADATA)
1879 << dd_table.name().c_str();
1880 my_error(
1881 ER_INTERNAL_ERROR, MYF(0),
1882 "Failed to truncate table. You may drop and re-create this table.");
1883 ut_ad(0);
1884 err = DB_ERROR;
1885 }
1886 }
1887 }
1888 cols_to_drop.clear();
1889
1890 return err;
1891 }
1892
1893 /** Clear the instant ADD COLUMN information of a partition, to make it
1894 as a normal partition
1895 @param[in,out] dd_part dd::Partition */
1896 void dd_clear_instant_part(dd::Partition &dd_part) {
1897 ut_ad(dd_part_has_instant_cols(dd_part));
1898
1899 dd_part.se_private_data().remove(
1900 dd_partition_key_strings[DD_PARTITION_INSTANT_COLS]);
1901 }
1902
1903 #ifdef UNIV_DEBUG
1904 bool dd_instant_columns_consistent(const dd::Table &dd_table) {
1905 bool found = false;
1906 size_t n_non_instant_cols = 0;
1907 size_t n_version_add_cols [[maybe_unused]] = 0;
1908 size_t n_instant_add_cols = 0;
1909 size_t n_version_drop_cols = 0;
1910 for (auto column : dd_table.columns()) {
1911 if (column->is_virtual() || is_system_column(column->name().c_str())) {
1912 continue;
1913 }
1914
1915 if (column->se_private_data().exists(
1916 dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL]) ||
1917 column->se_private_data().exists(
1918 dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT])) {
1919 found = true;
1920 if (dd_column_is_added(column)) {
1921 n_version_add_cols++;
1922 } else {
1923 /* In upgraded table, Instant ADD column with no v_added */
1924 ut_ad(dd_table_is_upgraded_instant(dd_table));
1925 n_instant_add_cols++;
1926 }
1927
1928 continue;
1929 }
1930
1931 if (dd_column_is_dropped(column)) {
1932 n_version_drop_cols++;
1933 continue;
1934 }
1935
1936 ++n_non_instant_cols;
1937 }
1938
1939 if (!dd_table_is_upgraded_instant(dd_table)) {
1940 ut_ad(dd_table_has_row_versions(dd_table));
1941 ut_ad(n_instant_add_cols == 0);
1942 return true;
1943 }
1944
1945 /* If we reach here, table is in v1 instant format */
1946 bool exp = false;
1947 const char *s = dd_table_key_strings[DD_TABLE_INSTANT_COLS];
1948 uint32_t n_inst_cols = 0;
1949 dd_table.se_private_data().get(s, &n_inst_cols);
1950
1951 /* Note that n_inst_cols could be 0 if the table only had some virtual
1952 columns before instant ADD COLUMN. So below check should be sufficient.
1953
1954 Moreover, existing columns before first INSTANT ADD could have been dropped.
1955 So n_non_instant_cols could be less then n_inst_cols provided it is accounted
1956 in n_version_drop_cols. */
1957 exp = (n_non_instant_cols == n_inst_cols) ||
1958 (n_non_instant_cols < n_inst_cols &&
1959 (n_version_drop_cols >= (n_inst_cols - n_non_instant_cols)));
1960
1961 ut_ad(exp);
1962
1963 /* found will be false iff after upgrade INSTANT ADD column was INSTANT
1964 DROP. */
1965 bool exp2 = found || dd_table_has_row_versions(dd_table);
1966 ut_ad(exp2);
1967
1968 return (exp && exp2);
1969 }
1970 #endif /* UNIV_DEBUG */
1971
1972 void dd_visit_keys_with_too_long_parts(
1973 const TABLE *table, const size_t max_part_len,
1974 std::function<void(const KEY &)> visitor) {
1975 for (uint key_num = 0; key_num < table->s->keys; key_num++) {
1976 const KEY &key = table->key_info[key_num];
1977 if (!(key.flags & (HA_SPATIAL | HA_FULLTEXT))) {
1978 for (unsigned i = 0; i < key.user_defined_key_parts; i++) {
1979 const KEY_PART_INFO *key_part = &key.key_part[i];
1980 if (max_part_len < key_part->length) {
1981 visitor(key);
1982 continue;
1983 }
1984 }
1985 }
1986 }
1987 }
1988
1989 static void instant_update_table_cols_count(dict_table_t *dict_table,
1990 uint32_t n_added_column,
1991 uint32_t n_dropped_column) {
1992 dict_table->current_col_count += n_added_column;
1993 dict_table->current_col_count -= n_dropped_column;
1994 dict_table->total_col_count += n_added_column;
1995
1996 ut_ad(dict_table->total_col_count >= dict_table->current_col_count);
1997 }
1998
1999 bool copy_dropped_columns(const dd::Table *old_dd_table,
2000 dd::Table *new_dd_table,
2001 uint32_t current_row_version) {
2002 ut_d(bool is_instant_v1 = false);
2003
2004 for (const auto column : old_dd_table->columns()) {
2005 const char *col_name = column->name().c_str();
2006
2007 /* Copy physical pos of SYSTEM columns */
2008 if (is_system_column(col_name)) {
2009 uint32_t phy_pos = UINT32_UNDEFINED;
2010
2011 const char *s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
2012
2013 /* Following is possible if table is upgraded */
2014 if (!column->se_private_data().exists(s)) {
2015 ut_d(is_instant_v1 = true);
2016 continue;
2017 }
2018
2019 column->se_private_data().get(s, &phy_pos);
2020 ut_ad(phy_pos != UINT32_UNDEFINED);
2021
2022 dd::Column *new_table_col =
2023 const_cast<dd::Column *>(dd_find_column(new_dd_table, col_name));
2024 ut_ad(new_table_col != nullptr);
2025 new_table_col->se_private_data().set(s, phy_pos);
2026 continue;
2027 }
2028
2029 if (!column->is_se_hidden() ||
2030 innobase_strcasecmp(col_name, FTS_DOC_ID_COL_NAME) == 0) {
2031 continue;
2032 }
2033
2034 /* In V1, we can't have INSTANT DROP columns */
2035 ut_ad(!is_instant_v1);
2036
2037 const dd::Column *searchedColumn = dd_find_column(new_dd_table, col_name);
2038 if (searchedColumn != nullptr) {
2039 if (!dd_column_is_dropped(searchedColumn)) {
2040 /* User is trying to add column with name same as existing hidden
2041 * dropped column name. */
2042 ib::info(ER_IB_HIDDEN_NAME_CONFLICT, searchedColumn->name().c_str(),
2043 col_name);
2044 my_error(ER_WRONG_COLUMN_NAME, MYF(0), searchedColumn->name().c_str());
2045 return true;
2046 }
2047 /* Column is already present in new table. It is either already dropped
2048 column in previous statements or is being dropped in same statement. In
2049 both the cases, continue. */
2050 #ifdef UNIV_DEBUG
2051 ut_ad(dd_column_is_dropped(column));
2052 uint32_t v_dropped = dd_column_get_version_dropped(column);
2053 ut_ad(current_row_version >= v_dropped);
2054 #endif
2055 continue;
2056 }
2057
2058 /* Add this column as an SE_HIDDEN column in new table def */
2059 dd::Column *new_column = dd_add_hidden_column(
2060 new_dd_table, col_name, column->char_length(), column->type());
2061 ut_ad(new_column != nullptr);
2062
2063 /* Copy se private data */
2064 ut_ad(!column->se_private_data().empty());
2065 new_column->se_private_data().clear();
2066 new_column->set_se_private_data(column->se_private_data());
2067
2068 new_column->set_nullable(column->is_nullable());
2069 new_column->set_char_length(column->char_length());
2070 new_column->set_numeric_scale(column->numeric_scale());
2071 new_column->set_unsigned(column->is_unsigned());
2072 new_column->set_collation_id(column->collation_id());
2073 new_column->set_type(column->type());
2074 /* Elements for enum columns */
2075 if (column->type() == dd::enum_column_types::ENUM ||
2076 column->type() == dd::enum_column_types::SET) {
2077 for (const auto *source_elem : column->elements()) {
2078 auto *elem_obj = new_column->add_element();
2079 elem_obj->set_name(source_elem->name());
2080 }
2081 }
2082
2083 ut_ad(dd_find_column(new_dd_table, col_name) != nullptr);
2084 }
2085 return false;
2086 }
2087
2088 static void set_dropped_column_name(std::string &name, uint32_t version,
2089 uint32_t phy_pos) {
2090 std::ostringstream new_name;
2091 new_name << INSTANT_DROP_PREFIX_8_0_32 << "v" << version << "_p" << phy_pos
2092 << "_" << name;
2093 name = new_name.str();
2094 name.resize(std::min<size_t>(name.size(), NAME_CHAR_LEN));
2095 }
2096
2097 bool dd_drop_instant_columns(
2098 const dd::Table *old_dd_table, dd::Table *new_dd_table,
2099 dict_table_t *new_dict_table,
2100 const Columns &cols_to_drop IF_DEBUG(, const Columns &cols_to_add,
2101 Alter_inplace_info *ha_alter_info)) {
2102 if (dd_table_has_instant_drop_cols(*old_dd_table)) {
2103 /* Copy metadata of already dropped columns */
2104 if (copy_dropped_columns(old_dd_table, new_dd_table,
2105 new_dict_table->current_row_version))
2106 return true;
2107 }
2108
2109 #ifdef UNIV_DEBUG
2110 auto validate_column = [&](Field *column) {
2111 /* Valid cases are :
2112 1. Column is not present in the new table definition
2113 2. Column is present but it is a virtual column being added
2114 2. Column is present but it is a stored column being added
2115 3. Column is present and is not being added, it is a renamed column */
2116
2117 auto dd_col = dd_find_column(new_dd_table, column->field_name);
2118 /* Virtual columns are not part of cols_to_add so they are checked here. */
2119 if (dd_col == nullptr || dd_col->is_virtual()) {
2120 return true;
2121 }
2122
2123 for (const auto &field : cols_to_add) {
2124 if (strcmp(field->field_name, column->field_name) == 0) {
2125 return true;
2126 }
2127 }
2128
2129 for (const auto col : old_dd_table->columns()) {
2130 std::string new_name;
2131 if (is_renamed(ha_alter_info, col->name().c_str(), new_name)) {
2132 if (strcmp(new_name.c_str(), column->field_name) == 0) {
2133 return true;
2134 }
2135 }
2136 }
2137
2138 return false;
2139 };
2140 #endif
2141
2142 for (const auto &column : cols_to_drop) {
2143 ut_ad(!innobase_is_v_fld(column));
2144
2145 /* Get column to be dropped from old table def */
2146 dd::Column *col_to_drop = const_cast<dd::Column *>(
2147 dd_find_column(old_dd_table, column->field_name));
2148 ut_ad(col_to_drop != nullptr);
2149
2150 /* This column shouldn't be present in the new table and if it does,
2151 it must be being added/renamed in the same command. */
2152 ut_ad(validate_column(column));
2153
2154 dd::Properties &private_data = col_to_drop->se_private_data();
2155
2156 uint32_t phy_pos = UINT32_UNDEFINED;
2157 const char *s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
2158 if (!private_data.exists(s)) {
2159 ut_ad(!dd_table_has_row_versions(*old_dd_table));
2160 ut_ad(!new_dict_table->has_row_versions());
2161 const dict_col_t *col =
2162 new_dict_table->get_col_by_name(column->field_name);
2163 phy_pos = col->get_phy_pos();
2164 } else {
2165 private_data.get(s, &phy_pos);
2166 }
2167
2168 ut_ad(phy_pos != UINT32_UNDEFINED);
2169
2170 std::string dropped_col_name(col_to_drop->name().c_str());
2171 set_dropped_column_name(dropped_col_name,
2172 new_dict_table->current_row_version + 1, phy_pos);
2173
2174 /* Add this column as an SE_HIDDEN column in new table def. NOTE: This call
2175 will update the DD_INSTANT_VERSION_DROPPED for the column as well. */
2176 dd::Column *dropped_col =
2177 dd_add_hidden_column(new_dd_table, dropped_col_name.c_str(),
2178 col_to_drop->char_length(), col_to_drop->type());
2179 if (dropped_col == nullptr) {
2180 /* Table already has column with name same as dropped_col_name */
2181 ib::info(ER_IB_HIDDEN_NAME_CONFLICT, dropped_col_name.c_str(),
2182 dropped_col_name.c_str())
2183 << "If you have any conflicting user column please rename it.";
2184 return true;
2185 }
2186 ut_ad(dropped_col != nullptr);
2187
2188 {
2189 /* Set metadata of dropped column */
2190 dd::Properties &private_data = dropped_col->se_private_data();
2191 if (dd_column_is_added(col_to_drop)) {
2192 uint32_t v_added = dd_column_get_version_added(col_to_drop);
2193 private_data.set(dd_column_key_strings[DD_INSTANT_VERSION_ADDED],
2194 v_added);
2195 }
2196 private_data.set(dd_column_key_strings[DD_INSTANT_VERSION_DROPPED],
2197 new_dict_table->current_row_version + 1);
2198 private_data.set(dd_column_key_strings[DD_INSTANT_PHYSICAL_POS], phy_pos);
2199
2200 dropped_col->set_nullable(col_to_drop->is_nullable());
2201 dropped_col->set_char_length(col_to_drop->char_length());
2202 dropped_col->set_numeric_scale(col_to_drop->numeric_scale());
2203 dropped_col->set_unsigned(col_to_drop->is_unsigned());
2204 dropped_col->set_collation_id(col_to_drop->collation_id());
2205 dropped_col->set_type(col_to_drop->type());
2206 /* Elements for enum columns */
2207 if (col_to_drop->type() == dd::enum_column_types::ENUM ||
2208 col_to_drop->type() == dd::enum_column_types::SET) {
2209 for (const auto *source_elem : col_to_drop->elements()) {
2210 auto *elem_obj = dropped_col->add_element();
2211 elem_obj->set_name(source_elem->name());
2212 }
2213 }
2214 }
2215
2216 ut_ad(dd_find_column(new_dd_table, dropped_col_name.c_str()) != nullptr);
2217 }
2218
2219 instant_update_table_cols_count(new_dict_table, 0, cols_to_drop.size());
2220
2221 return false;
2222 }
2223
2224 bool dd_add_instant_columns(const dd::Table *old_dd_table,
2225 dd::Table *new_dd_table,
2226 dict_table_t *new_dict_table,
2227 const Columns &cols_to_add) {
2228 if (dd_table_has_instant_drop_cols(*old_dd_table)) {
2229 /* Copy metadata of already dropped columns */
2230 if (copy_dropped_columns(old_dd_table, new_dd_table,
2231 new_dict_table->current_row_version))
2232 return true;
2233 }
2234
2235 auto set_col_default = [&](Field *field, dd::Properties &se_private) {
2236 /* Get the mtype and prtype of this field. Keep this same
2237 with the code in dd_fill_dict_table(), except FTS check */
2238 ulint prtype = 0;
2239 unsigned col_len = field->pack_length();
2240 ulint nulls_allowed;
2241 ulint unsigned_type;
2242 ulint binary_type;
2243 ulint long_true_varchar;
2244 ulint charset_no;
2245 ulint mtype = get_innobase_type_from_mysql_type(&unsigned_type, field);
2246
2247 nulls_allowed = field->is_nullable() ? 0 : DATA_NOT_NULL;
2248
2249 binary_type = field->binary() ? DATA_BINARY_TYPE : 0;
2250
2251 charset_no = 0;
2252 if (dtype_is_string_type(mtype)) {
2253 charset_no = static_cast<ulint>(field->charset()->number);
2254 }
2255
2256 long_true_varchar = 0;
2257 if (field->type() == MYSQL_TYPE_VARCHAR) {
2258 col_len -= field->get_length_bytes();
2259
2260 if (field->get_length_bytes() == 2) {
2261 long_true_varchar = DATA_LONG_TRUE_VARCHAR;
2262 }
2263 }
2264
2265 prtype =
2266 dtype_form_prtype((ulint)field->type() | nulls_allowed | unsigned_type |
2267 binary_type | long_true_varchar,
2268 charset_no);
2269
2270 dict_col_t col;
2271 /* Set a fake col_pos, since this should be useless */
2272 dict_mem_fill_column_struct(&col, 0, mtype, prtype, col_len, true,
2273 UINT32_UNDEFINED,
2274 new_dict_table->current_row_version, 0);
2275 dfield_t dfield;
2276 col.copy_type(dfield_get_type(&dfield));
2277
2278 ulint size = field->pack_length();
2279 uint64_t buf;
2280 const byte *mysql_data = field->field_ptr();
2281
2282 row_mysql_store_col_in_innobase_format(
2283 &dfield, reinterpret_cast<byte *>(&buf), true, mysql_data, size,
2284 dict_table_is_comp(new_dict_table));
2285
2286 DD_instant_col_val_coder coder;
2287 size_t length = 0;
2288 const char *value = coder.encode(reinterpret_cast<byte *>(dfield.data),
2289 dfield.len, &length);
2290
2291 dd::String_type default_value;
2292 default_value.assign(dd::String_type(value, length));
2293 se_private.set(dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT],
2294 default_value);
2295 };
2296
2297 uint32_t total_cols =
2298 new_dict_table->total_col_count + new_dict_table->get_n_sys_cols();
2299 uint32_t next_phy_pos = 0;
2300 for (size_t i = 0; i < total_cols; i++) {
2301 dict_col_t *col = new_dict_table->get_col(i);
2302
2303 if (col->get_phy_pos() == UINT32_UNDEFINED) {
2304 ut_ad(col == new_dict_table->get_sys_col(DATA_ROW_ID));
2305 continue;
2306 }
2307
2308 if (col->has_prefix_phy_pos()) {
2309 /* Column prefix part of clustered index. It appears twice. */
2310 next_phy_pos += 2;
2311 continue;
2312 }
2313
2314 next_phy_pos++;
2315 }
2316
2317 uint32_t cols_added = 0;
2318 /* For each new column populate se_private_data */
2319 for (const auto new_column : cols_to_add) {
2320 Field *field = new_column;
2321
2322 ut_ad(!innobase_is_v_fld(field));
2323
2324 /* The MySQL type code has to fit in 8 bits
2325 in the metadata stored in the InnoDB change buffer. */
2326 ut_ad(field->charset() == nullptr ||
2327 field->charset()->number <= MAX_CHAR_COLL_NUM);
2328 ut_ad(field->charset() == nullptr || field->charset()->number > 0);
2329
2330 dd::Column *column = const_cast<dd::Column *>(
2331 dd_find_column(new_dd_table, field->field_name));
2332 ut_ad(column != nullptr);
2333 dd::Properties &se_private = column->se_private_data();
2334
2335 /* Set Table Id */
2336 se_private.set(dd_index_key_strings[DD_TABLE_ID], new_dict_table->id);
2337
2338 /* Set Version Added */
2339 se_private.set(dd_column_key_strings[DD_INSTANT_VERSION_ADDED],
2340 new_dict_table->current_row_version + 1);
2341
2342 /* Set physical position on row */
2343 se_private.set(dd_column_key_strings[DD_INSTANT_PHYSICAL_POS],
2344 next_phy_pos + cols_added++);
2345
2346 /* Set Default NULL */
2347 if (field->is_real_null()) {
2348 se_private.set(dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL],
2349 true);
2350 continue;
2351 }
2352
2353 /* Set Default value */
2354 set_col_default(field, se_private);
2355 }
2356
2357 instant_update_table_cols_count(new_dict_table, cols_to_add.size(), 0);
2358
2359 ut_ad(cols_added > 0);
2360 return false;
2361 }
2362
2363 /** Compare the default values between imported column and column defined
2364 in the server. Note that it's absolutely OK if there is no default value
2365 in the column defined in server, since it can be filled in later.
2366 @param[in] dd_col dd::Column
2367 @param[in] col InnoDB column object
2368 @return true The default values match
2369 @retval false Not match */
2370 bool dd_match_default_value(const dd::Column *dd_col, const dict_col_t *col) {
2371 ut_ad(col->instant_default != nullptr);
2372
2373 const dd::Properties &private_data = dd_col->se_private_data();
2374
2375 if (private_data.exists(dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT])) {
2376 dd::String_type value;
2377 const byte *default_value;
2378 size_t len;
2379 bool match;
2380 DD_instant_col_val_coder coder;
2381
2382 private_data.get(dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT], &value);
2383 default_value = coder.decode(value.c_str(), value.length(), &len);
2384
2385 match = col->instant_default->len == len &&
2386 memcmp(col->instant_default->value, default_value, len) == 0;
2387
2388 return match;
2389
2390 } else if (private_data.exists(
2391 dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL])) {
2392 return (col->instant_default->len == UNIV_SQL_NULL);
2393 }
2394
2395 return true;
2396 }
2397
2398 /** Write default value of a column to dd::Column
2399 @param[in] col default value of this column to write
2400 @param[in,out] dd_col where to store the default value */
2401 void dd_write_default_value(const dict_col_t *col, dd::Column *dd_col) {
2402 if (col->instant_default->len == UNIV_SQL_NULL) {
2403 dd_col->se_private_data().set(
2404 dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL], true);
2405 } else {
2406 dd::String_type default_value;
2407 size_t length = 0;
2408 DD_instant_col_val_coder coder;
2409 const char *value = coder.encode(col->instant_default->value,
2410 col->instant_default->len, &length);
2411
2412 default_value.assign(dd::String_type(value, length));
2413 dd_col->se_private_data().set(
2414 dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT], default_value);
2415 }
2416 }
2417
2418 /** Parse the default value from dd::Column::se_private to dict_col_t
2419 @param[in] se_private_data dd::Column::se_private
2420 @param[in,out] col InnoDB column object
2421 @param[in,out] heap Heap to store the default value */
2422 void dd_parse_default_value(const dd::Properties &se_private_data,
2423 dict_col_t *col, mem_heap_t *heap) {
2424 if (se_private_data.exists(
2425 dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL])) {
2426 col->set_default(nullptr, UNIV_SQL_NULL, heap);
2427 } else if (se_private_data.exists(
2428 dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT])) {
2429 const byte *default_value;
2430 size_t len;
2431 dd::String_type value;
2432 DD_instant_col_val_coder coder;
2433
2434 se_private_data.get(dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT],
2435 &value);
2436
2437 default_value = coder.decode(value.c_str(), value.length(), &len);
2438
2439 col->set_default(default_value, len, heap);
2440 }
2441 }
2442
2443 #ifdef UNIV_DEBUG
2444 void static inline validate_dropped_col_metadata(const dd::Table *dd_table,
2445 const dict_table_t *table) {
2446 if (!table->has_instant_drop_cols()) {
2447 return;
2448 }
2449
2450 for (size_t i = table->get_n_user_cols(); i < table->get_total_cols(); ++i) {
2451 if (is_system_column(table->get_col_name(i))) {
2452 continue;
2453 }
2454
2455 dict_col_t *col = table->get_col(i);
2456
2457 const dd::Column *dd_col = dd_find_column(dd_table, table->get_col_name(i));
2458 ut_ad(dd_col != nullptr);
2459
2460 /* Check phy_pos */
2461 uint32_t value;
2462 const char *s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
2463 dd_col->se_private_data().get(s, &value);
2464 ut_ad(value == col->get_phy_pos());
2465
2466 /* Check version_added */
2467 if (dd_column_is_added(dd_col)) {
2468 ut_ad(col->is_instant_added());
2469 ut_ad(dd_column_get_version_added(dd_col) == col->get_version_added());
2470 } else {
2471 ut_ad(!col->is_instant_added());
2472 }
2473
2474 /* Check version_dropped */
2475 ut_ad(dd_column_is_dropped(dd_col));
2476 ut_ad(col->is_instant_dropped());
2477 ut_ad(dd_column_get_version_dropped(dd_col) == col->get_version_dropped());
2478 }
2479 }
2480 #endif
2481
2482 /** Import all metadata which is related to instant ADD COLUMN of a table
2483 to dd::Table. This is used for IMPORT.
2484 @param[in] table InnoDB table object
2485 @param[in,out] dd_table dd::Table */
2486 void dd_import_instant_add_columns(const dict_table_t *table,
2487 dd::Table *dd_table) {
2488 ut_ad(table->has_instant_cols() || table->has_row_versions());
2489 ut_ad(dict_table_is_partition(table) == dd_table_is_partitioned(*dd_table));
2490
2491 if (table->has_instant_cols()) {
2492 ut_ad(table->is_upgraded_instant());
2493 if (!dd_table_is_partitioned(*dd_table)) {
2494 dd_table->se_private_data().set(
2495 dd_table_key_strings[DD_TABLE_INSTANT_COLS],
2496 table->get_instant_cols());
2497 } else { /* Partitioned table */
2498 uint32_t n_inst_cols = std::numeric_limits<uint32_t>::max();
2499
2500 if (dd_table->se_private_data().exists(
2501 dd_table_key_strings[DD_TABLE_INSTANT_COLS])) {
2502 dd_table->se_private_data().get(
2503 dd_table_key_strings[DD_TABLE_INSTANT_COLS], &n_inst_cols);
2504 }
2505
2506 if (n_inst_cols > table->get_instant_cols()) {
2507 dd_table->se_private_data().set(
2508 dd_table_key_strings[DD_TABLE_INSTANT_COLS],
2509 table->get_instant_cols());
2510 }
2511
2512 dd::Partition *partition = nullptr;
2513 for (const auto dd_part : *dd_table->leaf_partitions()) {
2514 if (dict_name::match_partition(table->name.m_name, dd_part)) {
2515 partition = dd_part;
2516 break;
2517 }
2518 }
2519
2520 ut_ad(partition != nullptr);
2521
2522 partition->se_private_data().set(
2523 dd_partition_key_strings[DD_PARTITION_INSTANT_COLS],
2524 table->get_instant_cols());
2525 }
2526 }
2527
2528 /* Copy all default values if necessary */
2529 for (uint16_t i = 0; i < table->get_n_user_cols(); ++i) {
2530 dict_col_t *col = table->get_col(i);
2531
2532 dd::Column *dd_col = const_cast<dd::Column *>(
2533 dd_find_column(dd_table, table->get_col_name(i)));
2534 ut_ad(dd_col != nullptr);
2535 dd::Properties &private_data = dd_col->se_private_data();
2536
2537 if (col->instant_default == nullptr) {
2538 ut_ad(!col->is_instant_added() && !col->is_instant_dropped());
2539 } else {
2540 /* Default values mismatch should have been done. So only write default
2541 value when it's not ever recorded */
2542 if (!private_data.exists(
2543 dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL]) &&
2544 !private_data.exists(
2545 dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT])) {
2546 dd_write_default_value(col, dd_col);
2547 }
2548 }
2549
2550 if (table->has_row_versions()) {
2551 /* Set phy_pos */
2552 uint32_t value = col->get_phy_pos();
2553 const char *s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
2554 private_data.set(s, value);
2555
2556 if (col->is_instant_added()) {
2557 /* Set version_added */
2558 value = col->get_version_added();
2559 s = dd_column_key_strings[DD_INSTANT_VERSION_ADDED];
2560 private_data.set(s, value);
2561 }
2562
2563 if (col->is_instant_dropped()) {
2564 /* Set version_dropped */
2565 value = col->get_version_dropped();
2566 s = dd_column_key_strings[DD_INSTANT_VERSION_DROPPED];
2567 private_data.set(s, value);
2568 }
2569 }
2570 }
2571
2572 /* Add phy_pos for SYSTEM COLUMNS */
2573 if (table->has_row_versions()) {
2574 auto fn = [&](uint32_t sys_col, const char *name) {
2575 dd::Column *dd_col =
2576 const_cast<dd::Column *>(dd_find_column(dd_table, name));
2577 ut_ad(dd_col != nullptr || sys_col == DATA_ROW_ID);
2578 if (!dd_col) return;
2579 dd::Properties &private_data = dd_col->se_private_data();
2580
2581 dict_col_t *dict_col = table->get_sys_col(sys_col);
2582 ut_ad(dict_col->get_phy_pos() != UINT32_UNDEFINED);
2583
2584 const char *s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
2585 private_data.set(s, dict_col->get_phy_pos());
2586 };
2587
2588 fn(DATA_ROW_ID, "DB_ROW_ID");
2589 fn(DATA_TRX_ID, "DB_TRX_ID");
2590 fn(DATA_ROLL_PTR, "DB_ROLL_PTR");
2591 }
2592
2593 ut_d(validate_dropped_col_metadata(dd_table, table));
2594 }
2595
2596 /** Write metadata of a index to dd::Index
2597 @param[in] dd_space_id Tablespace id, which server allocates
2598 @param[in,out] dd_index dd::Index
2599 @param[in] index InnoDB index object */
2600 template <typename Index>
2601 static void dd_write_index(dd::Object_id dd_space_id, Index *dd_index,
2602 const dict_index_t *index) {
2603 ut_ad(index->id != 0);
2604 ut_ad(index->page >= FSP_FIRST_INODE_PAGE_NO);
2605
2606 dd_index->set_tablespace_id(dd_space_id);
2607
2608 dd::Properties &p = dd_index->se_private_data();
2609 p.set(dd_index_key_strings[DD_INDEX_ID], index->id);
2610 p.set(dd_index_key_strings[DD_INDEX_SPACE_ID], index->space);
2611 p.set(dd_index_key_strings[DD_TABLE_ID], index->table->id);
2612 p.set(dd_index_key_strings[DD_INDEX_ROOT], index->page);
2613 p.set(dd_index_key_strings[DD_INDEX_TRX_ID], index->trx_id);
2614 }
2615
2616 template void dd_write_index<dd::Index>(dd::Object_id, dd::Index *,
2617 const dict_index_t *);
2618 template void dd_write_index<dd::Partition_index>(dd::Object_id,
2619 dd::Partition_index *,
2620 const dict_index_t *);
2621
2622 template <typename Table>
2623 void dd_write_table(dd::Object_id dd_space_id, Table *dd_table,
2624 const dict_table_t *table) {
2625 /* Only set the tablespace id for tables in innodb_system tablespace */
2626 if (dd_space_id == dict_sys_t::s_dd_sys_space_id) {
2627 dd_table->set_tablespace_id(dd_space_id);
2628 }
2629
2630 dd_table->set_se_private_id(table->id);
2631
2632 if (DICT_TF_HAS_DATA_DIR(table->flags)) {
2633 ut_ad(dict_table_is_file_per_table(table));
2634 dd_table->se_private_data().set(
2635 dd_table_key_strings[DD_TABLE_DATA_DIRECTORY], true);
2636 }
2637
2638 for (auto dd_index : *dd_table->indexes()) {
2639 /* Don't assume the index orders are the same, even on
2640 CREATE TABLE. This could be called from TRUNCATE path,
2641 which would do some adjustment on FULLTEXT index, thus
2642 the out-of-sync order */
2643 const dict_index_t *index = dd_find_index(table, dd_index);
2644 ut_ad(index != nullptr);
2645 dd_write_index(dd_space_id, dd_index, index);
2646 }
2647
2648 bool has_row_versions = table->has_row_versions();
2649 ut_ad(!has_row_versions || !table->is_fts_aux());
2650
2651 if (!dd_table_is_partitioned(dd_table->table()) ||
2652 dd_part_is_first(reinterpret_cast<dd::Partition *>(dd_table))) {
2653 std::vector<dd::Column *> cols_to_remove;
2654 const char *s = nullptr;
2655 for (auto dd_column : *dd_table->table().columns()) {
2656 dd_column->se_private_data().set(dd_index_key_strings[DD_TABLE_ID],
2657 table->id);
2658
2659 /* Write physical pos only for tables having row versions */
2660 if (!has_row_versions || dd_column->is_virtual()) {
2661 continue;
2662 }
2663
2664 /* Write physical pos for non-virtual columns */
2665 dict_col_t *col = table->get_col_by_name(dd_column->name().c_str());
2666 if (col == nullptr) {
2667 /* It's possible during TRUNCATE of table with INSTANT DROP column. */
2668 ut_a(dd_table_has_instant_cols(dd_table->table()));
2669 ut_a(table->current_row_version == 0);
2670 ut_a(dd_column_is_dropped(dd_column));
2671
2672 cols_to_remove.push_back(dd_column);
2673 continue;
2674 }
2675
2676 s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
2677 if (table->has_row_versions()) {
2678 /* In case of partitioned table, when a new partition is created,
2679 column metadata may not be set and needs to be set now. */
2680 if (dd_table_is_partitioned(dd_table->table())) {
2681 dd_column->se_private_data().set(s, col->get_phy_pos());
2682
2683 if (col->is_instant_added()) {
2684 s = dd_column_key_strings[DD_INSTANT_VERSION_ADDED];
2685 dd_column->se_private_data().set(
2686 s, (uint32_t)col->get_version_added());
2687 }
2688
2689 if (col->is_instant_dropped()) {
2690 s = dd_column_key_strings[DD_INSTANT_VERSION_DROPPED];
2691 dd_column->se_private_data().set(
2692 s, (uint32_t)col->get_version_dropped());
2693 }
2694 } else {
2695 /* Table has instant col added/dropped. Each column shall have
2696 physical pos updated. */
2697 ut_ad(dd_column->se_private_data().exists(s));
2698 }
2699 } else {
2700 /* No instant add/drop col */
2701 dd_column->se_private_data().set(s, col->get_phy_pos());
2702 }
2703 }
2704
2705 if (cols_to_remove.size() > 0) {
2706 dd::Abstract_table::Column_collection *col_collection =
2707 dd_table->table().columns();
2708 for (auto col : cols_to_remove) {
2709 ut_ad(std::find(col_collection->begin(), col_collection->end(), col) !=
2710 col_collection->end());
2711 col_collection->remove(dynamic_cast<dd::Column_impl *>(col));
2712 }
2713 }
2714 }
2715 }
2716
2717 template void dd_write_table<dd::Table>(dd::Object_id, dd::Table *,
2718 const dict_table_t *);
2719 template void dd_write_table<dd::Partition>(dd::Object_id, dd::Partition *,
2720 const dict_table_t *);
2721
2722 template <typename Table>
2723 void dd_set_table_options(Table *dd_table, const dict_table_t *table) {
2724 dd::Table *dd_table_def = &(dd_table->table());
2725 enum row_type type = ROW_TYPE_DEFAULT;
2726 dd::Table::enum_row_format format = dd::Table::RF_DYNAMIC;
2727 dd::Properties &options = dd_table_def->options();
2728
2729 switch (dict_tf_get_rec_format(table->flags)) {
2730 case REC_FORMAT_REDUNDANT:
2731 format = dd::Table::RF_REDUNDANT;
2732 type = ROW_TYPE_REDUNDANT;
2733 break;
2734 case REC_FORMAT_COMPACT:
2735 format = dd::Table::RF_COMPACT;
2736 type = ROW_TYPE_COMPACT;
2737 break;
2738 case REC_FORMAT_COMPRESSED:
2739 format = dd::Table::RF_COMPRESSED;
2740 type = ROW_TYPE_COMPRESSED;
2741 break;
2742 case REC_FORMAT_DYNAMIC:
2743 format = dd::Table::RF_DYNAMIC;
2744 type = ROW_TYPE_DYNAMIC;
2745 break;
2746 default:
2747 ut_error;
2748 }
2749
2750 if (!dd_table_is_partitioned(*dd_table_def)) {
2751 if (auto zip_ssize = DICT_TF_GET_ZIP_SSIZE(table->flags)) {
2752 uint32_t old_size;
2753 if (!options.get("key_block_size", &old_size) && old_size != 0) {
2754 options.set("key_block_size", 1 << (zip_ssize - 1));
2755 }
2756 } else {
2757 options.set("key_block_size", 0);
2758 /* It's possible that InnoDB ignores the specified
2759 key_block_size, so check the block_size for every index.
2760 Server assumes if block_size = 0, there should be no
2761 option found, so remove it when found */
2762 for (auto dd_index : *dd_table_def->indexes()) {
2763 if (dd_index->options().exists("block_size")) {
2764 dd_index->options().remove("block_size");
2765 }
2766 }
2767 }
2768
2769 dd_table_def->set_row_format(format);
2770 if (options.exists("row_type")) {
2771 options.set("row_type", type);
2772 }
2773 } else if (dd_table_def->row_format() != format) {
2774 dd_table->se_private_data().set(
2775 dd_partition_key_strings[DD_PARTITION_ROW_FORMAT], format);
2776 }
2777 }
2778
2779 template void dd_set_table_options<dd::Table>(dd::Table *,
2780 const dict_table_t *);
2781 template void dd_set_table_options<dd::Partition>(dd::Partition *,
2782 const dict_table_t *);
2783
2784 void dd_update_v_cols(dd::Table *dd_table, table_id_t id) {
2785 for (auto dd_column : *dd_table->columns()) {
2786 #ifdef UNIV_DEBUG
2787 if (dd_column->se_private_data().exists(
2788 dd_index_key_strings[DD_TABLE_ID])) {
2789 table_id_t table_id;
2790 dd_column->se_private_data().get(dd_index_key_strings[DD_TABLE_ID],
2791 reinterpret_cast<uint64_t *>(&table_id));
2792 ut_ad(table_id == id);
2793 }
2794 #endif /* UNIV_DEBUG */
2795
2796 if (!dd_column->is_virtual()) {
2797 continue;
2798 }
2799
2800 dd::Properties &p = dd_column->se_private_data();
2801
2802 if (!p.exists(dd_index_key_strings[DD_TABLE_ID])) {
2803 p.set(dd_index_key_strings[DD_TABLE_ID], id);
2804 }
2805 }
2806 }
2807
2808 /** Write metadata of a tablespace to dd::Tablespace
2809 @param[in,out] dd_space dd::Tablespace
2810 @param[in] space_id InnoDB tablespace ID
2811 @param[in] fsp_flags InnoDB tablespace flags
2812 @param[in] state InnoDB tablespace state */
2813 void dd_write_tablespace(dd::Tablespace *dd_space, space_id_t space_id,
2814 uint32_t fsp_flags, dd_space_states state) {
2815 dd::Properties &p = dd_space->se_private_data();
2816 p.set(dd_space_key_strings[DD_SPACE_ID], space_id);
2817 p.set(dd_space_key_strings[DD_SPACE_FLAGS], static_cast<uint32>(fsp_flags));
2818 p.set(dd_space_key_strings[DD_SPACE_SERVER_VERSION],
2819 DD_SPACE_CURRENT_SRV_VERSION);
2820 p.set(dd_space_key_strings[DD_SPACE_VERSION], DD_SPACE_CURRENT_SPACE_VERSION);
2821 p.set(dd_space_key_strings[DD_SPACE_STATE], dd_space_state_values[state]);
2822 }
2823
2824 /** Add fts doc id column and index to new table
2825 when old table has hidden fts doc id without fulltext index
2826 @param[in,out] new_table New dd table
2827 @param[in] old_table Old dd table */
2828 void dd_add_fts_doc_id_index(dd::Table &new_table, const dd::Table &old_table) {
2829 if (new_table.columns()->size() == old_table.columns().size()) {
2830 ut_ad(new_table.indexes()->size() == old_table.indexes().size());
2831 return;
2832 }
2833
2834 ut_ad(new_table.columns()->size() + 1 == old_table.columns().size());
2835 ut_ad(new_table.indexes()->size() + 1 == old_table.indexes().size());
2836
2837 /* Add hidden FTS_DOC_ID column */
2838 dd::Column *col = new_table.add_column();
2839 col->set_hidden(dd::Column::enum_hidden_type::HT_HIDDEN_SE);
2840 col->set_name(FTS_DOC_ID_COL_NAME);
2841 col->set_type(dd::enum_column_types::LONGLONG);
2842 col->set_nullable(false);
2843 col->set_unsigned(true);
2844 col->set_collation_id(1);
2845
2846 /* Add hidden FTS_DOC_ID index */
2847 dd_set_hidden_unique_index(new_table.add_index(), FTS_DOC_ID_INDEX_NAME, col);
2848
2849 return;
2850 }
2851
2852 /** Find the specified dd::Index or dd::Partition_index in an InnoDB table
2853 @tparam Index dd::Index or dd::Partition_index
2854 @param[in] table InnoDB table object
2855 @param[in] dd_index Index to search
2856 @return the dict_index_t object related to the index */
2857 template <typename Index>
2858 const dict_index_t *dd_find_index(const dict_table_t *table, Index *dd_index) {
2859 /* If the name is PRIMARY, return the first index directly,
2860 because the internal index name could be 'GEN_CLUST_INDEX'.
2861 It could be possible that the primary key name is not PRIMARY,
2862 because it's an implicitly upgraded unique index. We have to
2863 search all the indexes */
2864 if (dd_index->name() == "PRIMARY") {
2865 return table->first_index();
2866 }
2867
2868 /* The order could be different because all unique dd::Index(es)
2869 would be in front of other indexes. */
2870 const dict_index_t *index;
2871 for (index = table->first_index();
2872 (index != nullptr &&
2873 (dd_index->name() != index->name() || !index->is_committed()));
2874 index = index->next()) {
2875 }
2876
2877 ut_ad(index != nullptr);
2878
2879 #ifdef UNIV_DEBUG
2880 /* Never find another index with the same name */
2881 const dict_index_t *next_index = index->next();
2882 for (; (next_index != nullptr && (dd_index->name() != next_index->name() ||
2883 !next_index->is_committed()));
2884 next_index = next_index->next()) {
2885 }
2886 ut_ad(next_index == nullptr);
2887 #endif /* UNIV_DEBUG */
2888
2889 return index;
2890 }
2891
2892 /** Return the prefix length of the key.
2893 @param[in] key Key information.
2894 @param[in] key_part Key part information.
2895 @return Key prefix length or 0 if whole column is indexed.
2896 */
2897 static inline uint16_t get_index_prefix_len(const KEY &key,
2898 const KEY_PART_INFO *key_part) {
2899 if (key.flags & (HA_SPATIAL | HA_FULLTEXT)) {
2900 return 0;
2901 }
2902
2903 if (key_part->key_part_flag & HA_PART_KEY_SEG) {
2904 ut_ad(key_part->length > 0);
2905 return key_part->length;
2906 }
2907
2908 #ifdef UNIV_DEBUG
2909 auto field = key_part->field;
2910 ut_ad((!is_blob(field->real_type()) &&
2911 field->real_type() != MYSQL_TYPE_GEOMETRY) ||
2912 key_part->length >= (field->type() == MYSQL_TYPE_VARCHAR
2913 ? field->key_length()
2914 : field->pack_length()));
2915 #endif
2916
2917 return 0;
2918 }
2919
2920 template const dict_index_t *dd_find_index<dd::Index>(const dict_table_t *,
2921 dd::Index *);
2922 template const dict_index_t *dd_find_index<dd::Partition_index>(
2923 const dict_table_t *, dd::Partition_index *);
2924
2925 /** Create an index.
2926 @param[in] dd_index DD Index
2927 @param[in,out] table InnoDB table
2928 @param[in] form MySQL table structure
2929 @param[in] key_num key_info[] offset
2930 @return error code
2931 @retval 0 on success
2932 @retval HA_ERR_TOO_BIG_ROW if the record is too long */
2933 [[nodiscard]] static int dd_fill_one_dict_index(const dd::Index *dd_index,
2934 dict_table_t *table,
2935 const TABLE_SHARE *form,
2936 uint key_num) {
2937 const KEY &key = form->key_info[key_num];
2938 ulint type = 0;
2939 unsigned n_fields = key.user_defined_key_parts;
2940 unsigned n_uniq = n_fields;
2941
2942 ut_ad(!dict_sys_mutex_own());
2943 /* This name cannot be used for a non-primary index */
2944 ut_ad(key_num == form->primary_key ||
2945 my_strcasecmp(system_charset_info, key.name, primary_key_name) != 0);
2946 /* PARSER is only valid for FULLTEXT INDEX */
2947 ut_ad((key.flags & (HA_FULLTEXT | HA_USES_PARSER)) != HA_USES_PARSER);
2948 ut_ad(form->fields > 0);
2949 ut_ad(n_fields > 0);
2950
2951 if (key.flags & HA_SPATIAL) {
2952 ut_ad(!table->is_intrinsic());
2953 type = DICT_SPATIAL;
2954 ut_ad(n_fields == 1);
2955 } else if (key.flags & HA_FULLTEXT) {
2956 ut_ad(!table->is_intrinsic());
2957 type = DICT_FTS;
2958 n_uniq = 0;
2959 } else if (key_num == form->primary_key) {
2960 ut_ad(key.flags & HA_NOSAME);
2961 ut_ad(n_uniq > 0);
2962 type = DICT_CLUSTERED | DICT_UNIQUE;
2963 } else {
2964 type = (key.flags & HA_NOSAME) ? DICT_UNIQUE : 0;
2965 }
2966
2967 ut_ad(!!(type & DICT_FTS) == (n_uniq == 0));
2968
2969 dict_index_t *index =
2970 dict_mem_index_create(table->name.m_name, key.name, 0, type, n_fields);
2971
2972 index->n_uniq = n_uniq;
2973
2974 DBUG_EXECUTE_IF("ib_create_table_fail_at_create_index",
2975 const ulint max_len = DICT_MAX_FIELD_LEN_BY_FORMAT(table);
2976 dict_mem_index_free(index);
2977 my_error(ER_INDEX_COLUMN_TOO_LONG, MYF(0), max_len);
2978 return HA_ERR_TOO_BIG_ROW;);
2979
2980 for (unsigned i = 0; i < key.user_defined_key_parts; i++) {
2981 const KEY_PART_INFO *key_part = &key.key_part[i];
2982 const Field *field = key_part->field;
2983 ut_ad(field == form->field[key_part->fieldnr - 1]);
2984 ut_ad(field == form->field[field->field_index()]);
2985
2986 if (field->is_virtual_gcol()) {
2987 index->type |= DICT_VIRTUAL;
2988
2989 /* Whether it is a multi-value index */
2990 if ((field->gcol_info->expr_item &&
2991 field->gcol_info->expr_item->returns_array()) ||
2992 field->is_array()) {
2993 index->type |= DICT_MULTI_VALUE;
2994 }
2995 }
2996
2997 bool is_asc = true;
2998
2999 if (key_part->key_part_flag & HA_REVERSE_SORT) {
3000 is_asc = false;
3001 }
3002
3003 const auto prefix_len = get_index_prefix_len(key, key_part);
3004
3005 dict_col_t *col = nullptr;
3006
3007 if (innobase_is_v_fld(field)) {
3008 dict_v_col_t *v_col =
3009 dict_table_get_nth_v_col_mysql(table, field->field_index());
3010 col = reinterpret_cast<dict_col_t *>(v_col);
3011 } else {
3012 ulint t_num_v = 0;
3013 for (ulint z = 0; z < field->field_index(); z++) {
3014 if (innobase_is_v_fld(form->field[z])) {
3015 t_num_v++;
3016 }
3017 }
3018
3019 col = &table->cols[field->field_index() - t_num_v];
3020 }
3021
3022 col->is_visible = !field->is_hidden_by_system();
3023 dict_index_add_col(index, table, col, prefix_len, is_asc);
3024 }
3025
3026 ut_ad(((key.flags & HA_FULLTEXT) == HA_FULLTEXT) ==
3027 !!(index->type & DICT_FTS));
3028
3029 index->n_user_defined_cols = key.user_defined_key_parts;
3030
3031 if (dict_index_add_to_cache(table, index, 0, false) != DB_SUCCESS) {
3032 ut_d(ut_error);
3033 ut_o(return HA_ERR_GENERIC);
3034 }
3035
3036 index = UT_LIST_GET_LAST(table->indexes);
3037
3038 if (index->type & DICT_FTS) {
3039 ut_ad((key.flags & HA_FULLTEXT) == HA_FULLTEXT);
3040 ut_ad(index->n_uniq == 0);
3041 ut_ad(n_uniq == 0);
3042
3043 if (table->fts->cache == nullptr) {
3044 DICT_TF2_FLAG_SET(table, DICT_TF2_FTS);
3045 table->fts->cache = fts_cache_create(table);
3046
3047 rw_lock_x_lock(&table->fts->cache->init_lock, UT_LOCATION_HERE);
3048 /* Notify the FTS cache about this index. */
3049 fts_cache_index_cache_create(table, index);
3050 rw_lock_x_unlock(&table->fts->cache->init_lock);
3051 }
3052 }
3053
3054 if (strcmp(index->name, FTS_DOC_ID_INDEX_NAME) == 0) {
3055 ut_ad(table->fts_doc_id_index == nullptr);
3056 table->fts_doc_id_index = index;
3057 }
3058
3059 if (dict_index_is_spatial(index)) {
3060 ut_ad(dd_index->name() == key.name);
3061 size_t geom_col_idx;
3062 for (geom_col_idx = 0; geom_col_idx < dd_index->elements().size();
3063 ++geom_col_idx) {
3064 if (!dd_index->elements()[geom_col_idx]->column().is_se_hidden()) break;
3065 }
3066 const dd::Column &col = dd_index->elements()[geom_col_idx]->column();
3067 bool srid_has_value = col.srs_id().has_value();
3068 index->fill_srid_value(srid_has_value ? col.srs_id().value() : 0,
3069 srid_has_value);
3070 }
3071
3072 return 0;
3073 }
3074
3075 /** Parse MERGE_THRESHOLD value from a comment string.
3076 @param[in] thd connection
3077 @param[in] str string which might include 'MERGE_THRESHOLD='
3078 @return value parsed
3079 @retval dict_index_t::MERGE_THRESHOLD_DEFAULT for missing or invalid value. */
3080 static ulint dd_parse_merge_threshold(THD *thd, const char *str) {
3081 static constexpr char label[] = "MERGE_THRESHOLD=";
3082 const char *pos = strstr(str, label);
3083
3084 if (pos != nullptr) {
3085 pos += (sizeof label) - 1;
3086
3087 int ret = atoi(pos);
3088
3089 if (ret > 0 && unsigned(ret) <= DICT_INDEX_MERGE_THRESHOLD_DEFAULT) {
3090 return static_cast<ulint>(ret);
3091 }
3092
3093 push_warning_printf(thd, Sql_condition::SL_WARNING, WARN_OPTION_IGNORED,
3094 ER_DEFAULT(WARN_OPTION_IGNORED), "MERGE_THRESHOLD");
3095 }
3096
3097 return DICT_INDEX_MERGE_THRESHOLD_DEFAULT;
3098 }
3099
3100 /** Copy attributes from MySQL TABLE_SHARE into an InnoDB table object.
3101 @param[in,out] thd thread context
3102 @param[in,out] table InnoDB table
3103 @param[in] table_share TABLE_SHARE */
3104 inline void dd_copy_from_table_share(THD *thd, dict_table_t *table,
3105 const TABLE_SHARE *table_share) {
3106 if (table->is_temporary()) {
3107 dict_stats_set_persistent(table, false, true);
3108 } else {
3109 switch (table_share->db_create_options &
3110 (HA_OPTION_STATS_PERSISTENT | HA_OPTION_NO_STATS_PERSISTENT)) {
3111 default:
3112 /* If a CREATE or ALTER statement contains
3113 STATS_PERSISTENT=0 STATS_PERSISTENT=1,
3114 it will be interpreted as STATS_PERSISTENT=1. */
3115 case HA_OPTION_STATS_PERSISTENT:
3116 dict_stats_set_persistent(table, true, false);
3117 break;
3118 case HA_OPTION_NO_STATS_PERSISTENT:
3119 dict_stats_set_persistent(table, false, true);
3120 break;
3121 case 0:
3122 break;
3123 }
3124 }
3125
3126 dict_stats_auto_recalc_set(
3127 table, table_share->stats_auto_recalc == HA_STATS_AUTO_RECALC_ON,
3128 table_share->stats_auto_recalc == HA_STATS_AUTO_RECALC_OFF);
3129
3130 table->stats_sample_pages = table_share->stats_sample_pages;
3131
3132 const ulint merge_threshold_table =
3133 table_share->comment.str
3134 ? dd_parse_merge_threshold(thd, table_share->comment.str)
3135 : DICT_INDEX_MERGE_THRESHOLD_DEFAULT;
3136 dict_index_t *index = table->first_index();
3137
3138 index->merge_threshold = merge_threshold_table;
3139
3140 if (dict_index_is_auto_gen_clust(index)) {
3141 index = index->next();
3142 }
3143
3144 for (uint i = 0; i < table_share->keys; i++) {
3145 const KEY *key_info = &table_share->key_info[i];
3146
3147 ut_ad(index != nullptr);
3148
3149 if (key_info->flags & HA_USES_COMMENT && key_info->comment.str != nullptr) {
3150 index->merge_threshold =
3151 dd_parse_merge_threshold(thd, key_info->comment.str);
3152 } else {
3153 index->merge_threshold = merge_threshold_table;
3154 }
3155
3156 index = index->next();
3157
3158 /* Skip hidden FTS_DOC_ID index */
3159 if (index != nullptr && index->hidden) {
3160 ut_ad(strcmp(index->name, FTS_DOC_ID_INDEX_NAME) == 0);
3161 index = index->next();
3162 }
3163 }
3164
3165 #ifdef UNIV_DEBUG
3166 if (index != nullptr) {
3167 ut_ad(table_share->keys == 0);
3168 ut_ad(index->hidden);
3169 ut_ad(strcmp(index->name, FTS_DOC_ID_INDEX_NAME) == 0);
3170 }
3171 #endif
3172 }
3173
3174 /** Instantiate index related metadata
3175 @param[in,out] dd_table Global DD table metadata
3176 @param[in] m_form MySQL table definition
3177 @param[in,out] m_table InnoDB table definition
3178 @param[in] m_thd THD instance
3179 @return 0 if successful, otherwise error number */
3180 inline int dd_fill_dict_index(const dd::Table &dd_table, const TABLE *m_form,
3181 dict_table_t *m_table, THD *m_thd) {
3182 int error = 0;
3183
3184 ut_ad(!dict_sys_mutex_own());
3185
3186 /* Create the keys */
3187 if (m_form->s->keys == 0 || m_form->s->primary_key == MAX_KEY) {
3188 /* Create an index which is used as the clustered index;
3189 order the rows by the hidden InnoDB column DB_ROW_ID. */
3190 dict_index_t *index = dict_mem_index_create(
3191 m_table->name.m_name, "GEN_CLUST_INDEX", 0, DICT_CLUSTERED, 0);
3192 index->n_uniq = 0;
3193
3194 dberr_t new_err =
3195 dict_index_add_to_cache(m_table, index, index->page, false);
3196 if (new_err != DB_SUCCESS) {
3197 error = HA_ERR_GENERIC;
3198 goto dd_error;
3199 }
3200 } else {
3201 /* In InnoDB, the clustered index must always be
3202 created first. */
3203 error = dd_fill_one_dict_index(dd_table.indexes()[m_form->s->primary_key],
3204 m_table, m_form->s, m_form->s->primary_key);
3205 if (error != 0) {
3206 goto dd_error;
3207 }
3208 }
3209
3210 for (uint i = !m_form->s->primary_key; i < m_form->s->keys; i++) {
3211 ulint dd_index_num = i + ((m_form->s->primary_key == MAX_KEY) ? 1 : 0);
3212
3213 error = dd_fill_one_dict_index(dd_table.indexes()[dd_index_num], m_table,
3214 m_form->s, i);
3215 if (error != 0) {
3216 goto dd_error;
3217 }
3218 }
3219
3220 if (dict_table_has_fts_index(m_table)) {
3221 ut_ad(DICT_TF2_FLAG_IS_SET(m_table, DICT_TF2_FTS));
3222 }
3223
3224 /* Create the ancillary tables that are common to all FTS indexes on
3225 this table. */
3226 if (DICT_TF2_FLAG_IS_SET(m_table, DICT_TF2_FTS_HAS_DOC_ID) ||
3227 DICT_TF2_FLAG_IS_SET(m_table, DICT_TF2_FTS)) {
3228 fts_doc_id_index_enum ret;
3229
3230 ut_ad(!m_table->is_intrinsic());
3231 /* Check whether there already exists FTS_DOC_ID_INDEX */
3232 ret = innobase_fts_check_doc_id_index_in_def(m_form->s->keys,
3233 m_form->key_info);
3234
3235 switch (ret) {
3236 case FTS_INCORRECT_DOC_ID_INDEX:
3237 push_warning_printf(m_thd, Sql_condition::SL_WARNING,
3238 ER_WRONG_NAME_FOR_INDEX,
3239 " InnoDB: Index name %s is reserved"
3240 " for the unique index on"
3241 " FTS_DOC_ID column for FTS"
3242 " Document ID indexing"
3243 " on table %s. Please check"
3244 " the index definition to"
3245 " make sure it is of correct"
3246 " type\n",
3247 FTS_DOC_ID_INDEX_NAME, m_table->name.m_name);
3248
3249 if (m_table->fts) {
3250 fts_free(m_table);
3251 }
3252
3253 my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), FTS_DOC_ID_INDEX_NAME);
3254 return HA_ERR_GENERIC;
3255 case FTS_EXIST_DOC_ID_INDEX:
3256 break;
3257 case FTS_NOT_EXIST_DOC_ID_INDEX:
3258 dict_index_t *doc_id_index;
3259 doc_id_index = dict_mem_index_create(
3260 m_table->name.m_name, FTS_DOC_ID_INDEX_NAME, 0, DICT_UNIQUE, 1);
3261 doc_id_index->add_field(FTS_DOC_ID_COL_NAME, 0, true);
3262
3263 dberr_t new_err = dict_index_add_to_cache(m_table, doc_id_index,
3264 doc_id_index->page, false);
3265 if (new_err != DB_SUCCESS) {
3266 error = HA_ERR_GENERIC;
3267 goto dd_error;
3268 }
3269
3270 doc_id_index = UT_LIST_GET_LAST(m_table->indexes);
3271 doc_id_index->hidden = true;
3272 }
3273
3274 /* Cache all the FTS indexes on this table in the FTS
3275 specific structure. They are used for FTS indexed
3276 column update handling. */
3277 if (dict_table_has_fts_index(m_table)) {
3278 fts_t *fts = m_table->fts;
3279 ut_a(fts != nullptr);
3280
3281 dict_table_get_all_fts_indexes(m_table, m_table->fts->indexes);
3282 }
3283
3284 ulint fts_doc_id_col = ULINT_UNDEFINED;
3285
3286 ret = innobase_fts_check_doc_id_index(m_table, nullptr, &fts_doc_id_col);
3287
3288 if (ret != FTS_INCORRECT_DOC_ID_INDEX) {
3289 ut_ad(m_table->fts->doc_col == ULINT_UNDEFINED);
3290 m_table->fts->doc_col = fts_doc_id_col;
3291 ut_ad(m_table->fts->doc_col != ULINT_UNDEFINED);
3292
3293 m_table->fts_doc_id_index =
3294 dict_table_get_index_on_name(m_table, FTS_DOC_ID_INDEX_NAME);
3295 }
3296 }
3297
3298 if (error == 0) {
3299 dd_copy_from_table_share(m_thd, m_table, m_form->s);
3300 ut_ad(!m_table->is_temporary() ||
3301 !dict_table_page_size(m_table).is_compressed());
3302 if (!m_table->is_temporary()) {
3303 dict_table_stats_latch_create(m_table, true);
3304 }
3305 } else {
3306 dd_error:
3307 dict_sys_mutex_enter();
3308
3309 for (dict_index_t *f_index = UT_LIST_GET_LAST(m_table->indexes);
3310 f_index != nullptr; f_index = UT_LIST_GET_LAST(m_table->indexes)) {
3311 dict_index_remove_from_cache(m_table, f_index);
3312 }
3313
3314 dict_sys_mutex_exit();
3315
3316 dict_mem_table_free(m_table);
3317 }
3318
3319 return error;
3320 }
3321
3322 /** Determine if a table contains a fulltext index.
3323 @param[in] table dd::Table
3324 @return whether the table contains any fulltext index */
3325 inline bool dd_table_contains_fulltext(const dd::Table &table) {
3326 for (const dd::Index *index : table.indexes()) {
3327 if (index->type() == dd::Index::IT_FULLTEXT) {
3328 return true;
3329 }
3330 }
3331 return false;
3332 }
3333
3334 /** Read the metadata of default values for all columns added instantly
3335 @param[in] dd_table dd::Table
3336 @param[in,out] table InnoDB table object */
3337 static void dd_fill_instant_columns_default(const dd::Table &dd_table,
3338 dict_table_t *table) {
3339 ut_ad(table->has_instant_cols() || table->has_row_versions());
3340 ut_ad(dd_table_has_instant_cols(dd_table));
3341
3342 #ifdef UNIV_DEBUG
3343 for (uint16_t i = 0; i < table->get_n_cols(); ++i) {
3344 ut_ad(table->get_col(i)->instant_default == nullptr);
3345 }
3346 #endif /* UNIV_DEBUG */
3347
3348 uint32_t skip = 0;
3349 if (dd_table_is_partitioned(dd_table)) {
3350 if (dd_table_is_upgraded_instant(dd_table)) {
3351 /* In instant v1, when a partition is added into table, it won't have any
3352 instant columns eg :
3353 - t1 (c1, c2) with partition p0, p1.
3354 - INSTANT ADD c3
3355 - For p0 and p1, n_instant_cols = 2;
3356 - ADD NEW Partition p2.
3357 - p2 would have c1, c2 and c3 as normal column i.e. n_instant_cols = 0.
3358 - INSTANT ADD c4.
3359 - For p2, n_instant_cols = 3 now.
3360 - So for p0 and p1, we have to populate instant default for c3 and c4. But
3361 for p3, we need to set only for c4. We need to skip for c3.
3362 - So skip count = 3 - 2 = 1.
3363 - So loop has to try 2 times to set the default value for each partition
3364 but for skip 1st time (for c3) for this new partition p2. */
3365 const char *s = dd_table_key_strings[DD_TABLE_INSTANT_COLS];
3366 ut_ad(dd_table.se_private_data().exists(s));
3367
3368 uint32_t cols;
3369 dd_table.se_private_data().get(s, &cols);
3370 ut_ad(cols <= table->get_instant_cols());
3371 skip = table->get_instant_cols() - cols;
3372 }
3373 }
3374
3375 #ifdef UNIV_DEBUG
3376 auto verify_name = [&](const dd::Column *col, uint32_t pos) {
3377 const char *name = table->col_names;
3378 for (uint32_t i = 0; i < pos - 1; ++i) {
3379 name += strlen(name) + 1;
3380 }
3381 ut_ad(col->name() == name);
3382 };
3383 #endif /* UNIV_DEBUG */
3384
3385 uint32_t innodb_pos = 0;
3386 for (const auto col : dd_table.columns()) {
3387 if (col->is_virtual() || is_system_column(col->name().c_str())) {
3388 continue;
3389 }
3390
3391 const dd::Properties &private_data = col->se_private_data();
3392
3393 /* Skip the dropped columns */
3394 if (dd_column_is_dropped(col)) {
3395 continue;
3396 }
3397
3398 dict_col_t *column = table->get_col(innodb_pos++);
3399 ut_ad(!column->is_virtual());
3400
3401 ut_d(verify_name(col, innodb_pos));
3402
3403 if (!private_data.exists(
3404 dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL]) &&
3405 !private_data.exists(
3406 dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT])) {
3407 /* This is not INSTANT ADD column */
3408 ut_ad(!dd_column_is_added(col));
3409 continue;
3410 }
3411
3412 /* Skip only if it is instant added in v1. */
3413 if (skip > 0 && !dd_column_is_added(col)) {
3414 --skip;
3415 continue;
3416 }
3417
3418 /* Note that it's before dict_table_add_to_cache(),
3419 don't worry about the dict_sys->size. */
3420 dd_parse_default_value(private_data, column, table->heap);
3421 }
3422
3423 #ifdef UNIV_DEBUG
3424 if (!table->has_row_versions()) {
3425 uint16_t n_default = 0;
3426 for (uint16_t i = 0; i < table->get_n_user_cols(); ++i) {
3427 if (table->get_col(i)->instant_default != nullptr) {
3428 ++n_default;
3429 }
3430 }
3431
3432 /* Instant add columns + columns before first instant == total columns in
3433 table now. */
3434 ut_ad(n_default + table->get_instant_cols() == table->get_n_user_cols());
3435 }
3436 #endif /* UNIV_DEBUG */
3437 }
3438
3439 static void fill_dict_dropped_column(const dd::Column *column,
3440 dict_table_t *dict_table,
3441 IF_DEBUG(uint32_t &crv, )
3442 mem_heap_t *heap) {
3443 ut_ad(!column->is_virtual());
3444 ut_ad(column->is_se_hidden());
3445 ut_ad(!is_system_column(column->name().c_str()));
3446
3447 /* Get version added */
3448 uint32_t v_added = dd_column_get_version_added(column);
3449
3450 /* Get version dropped */
3451 ut_a(dd_column_is_dropped(column));
3452 uint32_t v_dropped = dd_column_get_version_dropped(column);
3453
3454 #ifdef UNIV_DEBUG
3455 crv = std::max(crv, v_dropped);
3456 #endif
3457
3458 /* Get physical position */
3459 uint32_t phy_pos = UINT32_UNDEFINED;
3460 const char *s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
3461 ut_ad(column->se_private_data().exists(s));
3462 column->se_private_data().get(s, &phy_pos);
3463 ut_ad(phy_pos != UINT32_UNDEFINED);
3464
3465 /* Get column mtype */
3466 ulint unsigned_type;
3467 ulint binary_type;
3468 ulint charset_no;
3469 const CHARSET_INFO *charset = dd_get_mysql_charset(column->collation_id());
3470 ulint mtype = get_innobase_type_from_mysql_dd_type(
3471 &unsigned_type, &binary_type, &charset_no, column->type(), charset,
3472 column->is_unsigned());
3473
3474 /* Get column length */
3475 ulint col_len = calc_pack_length(
3476 column->type(), column->char_length(), column->elements_count(),
3477 /* InnoDB always treats BIT as char. */
3478 true, column->numeric_scale(), column->is_unsigned());
3479
3480 ulint long_true_varchar = 0;
3481 if (column->type() == dd::enum_column_types::VARCHAR) {
3482 size_t length_bytes = column->char_length() > 255 ? 2 : 1;
3483 col_len -= length_bytes;
3484
3485 if (length_bytes == 2) {
3486 long_true_varchar = DATA_LONG_TRUE_VARCHAR;
3487 }
3488 }
3489
3490 /* Get column prtype */
3491 ulint nulls_allowed = column->is_nullable() ? 0 : DATA_NOT_NULL;
3492 ulint prtype = dtype_form_prtype(
3493 (ulint)dd_get_old_field_type(column->type()) | unsigned_type |
3494 binary_type | nulls_allowed | long_true_varchar,
3495 charset_no);
3496
3497 /* Add column to InnoDB dictionary cache */
3498 dict_mem_table_add_col(dict_table, heap, column->name().c_str(), mtype,
3499 prtype, col_len, false, phy_pos, v_added, v_dropped);
3500 }
3501
3502 void get_field_types(const dd::Table *dd_tab, const dict_table_t *m_table,
3503 const Field *field, unsigned &col_len, ulint &mtype,
3504 ulint &prtype) {
3505 /* The MySQL type code has to fit in 8 bits in the metadata stored in the
3506 InnoDB change buffer. */
3507 ut_ad(field->charset() == nullptr ||
3508 field->charset()->number <= MAX_CHAR_COLL_NUM);
3509 ut_ad(field->charset() == nullptr || field->charset()->number > 0);
3510
3511 ulint long_true_varchar = 0;
3512 ulint binary_type;
3513 ulint nulls_allowed;
3514 ulint unsigned_type;
3515 ulint charset_no = 0;
3516
3517 mtype = get_innobase_type_from_mysql_type(&unsigned_type, field);
3518
3519 nulls_allowed = field->is_nullable() ? 0 : DATA_NOT_NULL;
3520
3521 /* Convert non nullable fields in FTS AUX tables as nullable.
3522 This is because in 5.7, we created FTS AUX tables clustered
3523 index with nullable field, although NULLS are not inserted.
3524 When fields are nullable, the record layout is dependent on
3525 that. When registering FTS AUX Tables with new DD, we cannot
3526 register nullable fields as part of Primary Key. Hence we register
3527 them as non-nullabe in DD but treat as nullable in InnoDB.
3528 This way the compatibility with 5.7 FTS AUX tables is also
3529 maintained. */
3530 if (dd_tab && m_table->is_fts_aux()) {
3531 const dd::Table &dd_table = dd_tab->table();
3532 const dd::Column *dd_col = dd_find_column(&dd_table, field->field_name);
3533 const dd::Properties &p = dd_col->se_private_data();
3534 if (p.exists("nullable")) {
3535 bool nullable;
3536 p.get("nullable", &nullable);
3537 nulls_allowed = nullable ? 0 : DATA_NOT_NULL;
3538 }
3539 }
3540
3541 binary_type = field->binary() ? DATA_BINARY_TYPE : 0;
3542
3543 if (dtype_is_string_type(mtype)) {
3544 charset_no = static_cast<ulint>(field->charset()->number);
3545 }
3546
3547 col_len = field->pack_length();
3548 if (field->type() == MYSQL_TYPE_VARCHAR) {
3549 col_len -= field->get_length_bytes();
3550
3551 if (field->get_length_bytes() == 2) {
3552 long_true_varchar = DATA_LONG_TRUE_VARCHAR;
3553 }
3554 }
3555
3556 ulint is_virtual = (innobase_is_v_fld(field)) ? DATA_VIRTUAL : 0;
3557
3558 ulint is_multi_val =
3559 innobase_is_multi_value_fld(field) ? DATA_MULTI_VALUE : 0;
3560
3561 if (is_multi_val) {
3562 col_len = field->key_length();
3563 }
3564
3565 if (!is_virtual) {
3566 prtype =
3567 dtype_form_prtype((ulint)field->type() | nulls_allowed | unsigned_type |
3568 binary_type | long_true_varchar,
3569 charset_no);
3570 } else {
3571 prtype = dtype_form_prtype(
3572 (ulint)field->type() | nulls_allowed | unsigned_type | binary_type |
3573 long_true_varchar | is_virtual | is_multi_val,
3574 charset_no);
3575 }
3576 }
3577
3578 /** Check if the individual parts of the composite index does not exceed the
3579 limit based on the table row format. If yes, mark the index as corrupt.
3580 @param[in] m_table InnoDB table handle
3581 @param[in] table MySQL table definition */
3582 static void validate_index_len(dict_table_t *m_table, const TABLE *table) {
3583 const uint32_t max_part_len = DICT_MAX_FIELD_LEN_BY_FORMAT(m_table);
3584 dd_visit_keys_with_too_long_parts(table, max_part_len, [&](const KEY &key) {
3585 dict_index_t *index = dict_table_get_index_on_name(m_table, key.name, true);
3586 if (index != nullptr) {
3587 std::string schema_name;
3588 std::string table_name;
3589
3590 dict_set_corrupted(index);
3591 m_table->get_table_name(schema_name, table_name);
3592 ib::error(ER_IB_INDEX_PART_TOO_LONG, key.name, schema_name.c_str(),
3593 table_name.c_str(), ulong{max_part_len});
3594 }
3595 });
3596 }
3597
3598 template <typename Table>
3599 static inline void fill_dict_existing_column(
3600 const Table *dd_tab, const TABLE *m_form, dict_table_t *m_table,
3601 IF_DEBUG(uint32_t &crv, ) mem_heap_t *heap, const uint32_t pos,
3602 bool has_row_versions) {
3603 const Field *field = m_form->field[pos];
3604 unsigned col_len;
3605 ulint mtype;
3606 ulint prtype;
3607 get_field_types(&dd_tab->table(), m_table, field, col_len, mtype, prtype);
3608
3609 ulint is_virtual = (innobase_is_v_fld(field)) ? DATA_VIRTUAL : 0;
3610
3611 if (!is_virtual) {
3612 const dd::Column *column =
3613 dd_find_column(&dd_tab->table(), field->field_name);
3614 ut_ad(column != nullptr);
3615
3616 /* Get version added */
3617 uint32_t v_added = dd_column_get_version_added(column);
3618 #ifdef UNIV_DEBUG
3619 if (dd_is_valid_row_version(v_added)) {
3620 crv = std::max(crv, v_added);
3621 }
3622 #endif
3623
3624 /* This column must be present */
3625 ut_ad(!dd_column_is_dropped(column));
3626
3627 /* Get physical pos */
3628 uint32_t phy_pos = UINT32_UNDEFINED;
3629 if (has_row_versions) {
3630 ut_ad(!m_table->is_system_table && !m_table->is_fts_aux());
3631 const char *s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
3632
3633 ut_ad(column->se_private_data().exists(s));
3634 if (column->se_private_data().exists(s)) {
3635 column->se_private_data().get(s, &phy_pos);
3636 ut_ad(phy_pos != UINT32_UNDEFINED);
3637 }
3638 }
3639
3640 dict_mem_table_add_col(m_table, heap, field->field_name, mtype, prtype,
3641 col_len, !field->is_hidden_by_system(), phy_pos,
3642 (uint8_t)v_added, UINT8_UNDEFINED);
3643 } else {
3644 dict_mem_table_add_v_col(m_table, heap, field->field_name, mtype, prtype,
3645 col_len, pos,
3646 field->gcol_info->non_virtual_base_columns(),
3647 !field->is_hidden_by_system());
3648 }
3649
3650 bool is_stored = innobase_is_s_fld(field);
3651 if (is_stored) {
3652 ut_ad(!is_virtual);
3653 /* Added stored column in m_s_cols list. */
3654 dict_mem_table_add_s_col(m_table,
3655 field->gcol_info->non_virtual_base_columns());
3656 }
3657 }
3658
3659 void fill_dict_dropped_columns(const dd::Table *dd_table,
3660 dict_table_t *dict_table,
3661 IF_DEBUG(uint32_t &crv, ) mem_heap_t *heap) {
3662 ut_ad(!dict_table->is_system_table);
3663
3664 /* Fill column which has(d) been dropped instantly from the table */
3665 ut_d(uint32_t dropped_col_count = 0);
3666 for (auto column : dd_table->columns()) {
3667 if (is_system_column(column->name().c_str())) {
3668 continue;
3669 }
3670
3671 if (dd_column_is_dropped(column)) {
3672 fill_dict_dropped_column(column, dict_table, IF_DEBUG(crv, ) heap);
3673 ut_d(dropped_col_count++;);
3674 }
3675 }
3676
3677 ut_ad(dict_table->get_n_instant_drop_cols() == dropped_col_count);
3678 }
3679
3680 template <typename Table>
3681 static inline void fill_dict_columns(const Table *dd_table, const TABLE *m_form,
3682 dict_table_t *dict_table,
3683 const unsigned n_mysql_cols,
3684 mem_heap_t *heap, bool add_doc_id) {
3685 IF_DEBUG(uint32_t crv = 0;)
3686
3687 /* Add existing columns metadata information. */
3688 bool has_row_versions = dd_table_has_row_versions(dd_table->table());
3689 for (unsigned i = 0; i < n_mysql_cols; i++) {
3690 fill_dict_existing_column(dd_table, m_form, dict_table,
3691 IF_DEBUG(crv, ) heap, i, has_row_versions);
3692 }
3693
3694 if (add_doc_id) {
3695 /* Add the hidden FTS_DOC_ID column. */
3696 fts_add_doc_id_column(dict_table, heap);
3697 }
3698
3699 /* Add system columns to make adding index work */
3700 dict_table_add_system_columns(dict_table, heap);
3701
3702 if (dict_table->has_row_versions()) {
3703 /* Read physical pos for system columns. */
3704
3705 auto fn = [&](uint32_t sys_col, const char *name) {
3706 const dd::Column *dd_col = dd_find_column(&dd_table->table(), name);
3707
3708 uint32_t phy_pos = UINT32_UNDEFINED;
3709 const char *s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
3710 if (dd_col && dd_col->se_private_data().exists(s)) {
3711 dd_col->se_private_data().get(s, &phy_pos);
3712 }
3713
3714 dict_col_t *dict_col = dict_table->get_sys_col(sys_col);
3715 dict_col->set_phy_pos(phy_pos);
3716 };
3717
3718 fn(DATA_ROW_ID, "DB_ROW_ID");
3719 fn(DATA_TRX_ID, "DB_TRX_ID");
3720 fn(DATA_ROLL_PTR, "DB_ROLL_PTR");
3721 }
3722
3723 /* If table has INSTANT DROP columns, add them now. */
3724 if (dict_table->has_instant_drop_cols()) {
3725 fill_dict_dropped_columns(&dd_table->table(), dict_table,
3726 IF_DEBUG(crv, ) heap);
3727 }
3728
3729 ut_ad(dict_table->current_row_version == crv);
3730
3731 /* For each virtual column, we will need to set up its base column info */
3732 if (dict_table->n_v_cols > 0) {
3733 ulint j = 0;
3734 for (unsigned i = 0; i < n_mysql_cols; i++) {
3735 dict_v_col_t *v_col;
3736
3737 Field *field = m_form->field[i];
3738
3739 if (!innobase_is_v_fld(field)) {
3740 continue;
3741 }
3742
3743 v_col = dict_table_get_nth_v_col(dict_table, j);
3744
3745 j++;
3746
3747 innodb_base_col_setup(dict_table, field, v_col);
3748 }
3749 }
3750 }
3751
3752 /** Instantiate in-memory InnoDB table metadata (dict_table_t),
3753 without any indexes.
3754 @tparam Table dd::Table or dd::Partition
3755 @param[in] dd_tab Global Data Dictionary metadata,
3756 or NULL for internal temporary table
3757 @param[in] m_form MySQL TABLE for current table
3758 @param[in] norm_name normalized table name
3759 @param[in] create_info create info
3760 @param[in] zip_allowed whether ROW_FORMAT=COMPRESSED is OK
3761 @param[in] strict whether to use innodb_strict_mode=ON
3762 @param[in] m_thd thread THD
3763 @param[in] is_implicit if it is an implicit tablespace
3764 @return created dict_table_t on success or nullptr */
3765 template <typename Table>
3766 static inline dict_table_t *dd_fill_dict_table(const Table *dd_tab,
3767 const TABLE *m_form,
3768 const char *norm_name,
3769 HA_CREATE_INFO *create_info,
3770 bool zip_allowed, bool strict,
3771 THD *m_thd, bool is_implicit) {
3772 ut_ad(dd_tab != nullptr);
3773 ut_ad(m_thd != nullptr);
3774 ut_ad(norm_name != nullptr);
3775 ut_ad(create_info == nullptr || m_form->s->row_type == create_info->row_type);
3776 ut_ad(create_info == nullptr ||
3777 m_form->s->key_block_size == create_info->key_block_size);
3778 ut_ad(dd_tab != nullptr);
3779
3780 if (m_form->s->fields > REC_MAX_N_USER_FIELDS) {
3781 my_error(ER_TOO_MANY_FIELDS, MYF(0));
3782 return nullptr;
3783 }
3784
3785 /* Fetch se private data for table from DD object. */
3786 const dd::Properties &table_se_private = dd_tab->table().se_private_data();
3787
3788 /* Set encryption option for file-per-table tablespace. */
3789 bool is_encrypted = false;
3790 dd::String_type encrypt;
3791 if (dd_tab->table().options().exists("encrypt_type")) {
3792 dd_tab->table().options().get("encrypt_type", &encrypt);
3793 if (!Encryption::is_none(encrypt.c_str())) {
3794 ut_ad(innobase_strcasecmp(encrypt.c_str(), "y") == 0);
3795 is_encrypted = true;
3796 }
3797 }
3798
3799 /* Check discard flag. */
3800 bool is_discard = false;
3801 is_discard = dd_is_discarded(*dd_tab);
3802
3803 const unsigned n_mysql_cols = m_form->s->fields;
3804
3805 /* First check if dd::Table contains the right hidden column as FTS_DOC_ID */
3806 bool has_doc_id = false;
3807 const dd::Column *doc_col;
3808 doc_col = dd_find_column(&dd_tab->table(), FTS_DOC_ID_COL_NAME);
3809
3810 /* Check weather this is a proper typed FTS_DOC_ID */
3811 if (doc_col && doc_col->type() == dd::enum_column_types::LONGLONG &&
3812 !doc_col->is_nullable()) {
3813 has_doc_id = true;
3814 }
3815
3816 const bool fulltext =
3817 dd_tab != nullptr && dd_table_contains_fulltext(dd_tab->table());
3818
3819 #ifdef UNIV_DEBUG
3820 /* If there is a fulltext index, then it must have a FTS_DOC_ID */
3821 if (fulltext) {
3822 ut_ad(has_doc_id);
3823 }
3824 #endif
3825
3826 /* Need to add FTS_DOC_ID column if it is not defined by user,
3827 since TABLE_SHARE::fields does not contain it if it is a hidden col */
3828 bool add_doc_id = false;
3829 if (has_doc_id && doc_col->is_se_hidden()) {
3830 #ifdef UNIV_DEBUG
3831 ulint doc_id_col;
3832 ut_ad(!create_table_check_doc_id_col(m_thd, m_form, &doc_id_col));
3833 #endif
3834 add_doc_id = true;
3835 }
3836
3837 const unsigned n_cols = n_mysql_cols + (add_doc_id ? 1 : 0);
3838
3839 row_type real_type = ROW_TYPE_NOT_USED;
3840
3841 if (dd_table_is_partitioned(dd_tab->table())) {
3842 const dd::Properties &part_p = dd_tab->se_private_data();
3843 if (part_p.exists(dd_partition_key_strings[DD_PARTITION_ROW_FORMAT])) {
3844 dd::Table::enum_row_format format;
3845 part_p.get(dd_partition_key_strings[DD_PARTITION_ROW_FORMAT],
3846 reinterpret_cast<uint32_t *>(&format));
3847 switch (format) {
3848 case dd::Table::RF_REDUNDANT:
3849 real_type = ROW_TYPE_REDUNDANT;
3850 break;
3851 case dd::Table::RF_COMPACT:
3852 real_type = ROW_TYPE_COMPACT;
3853 break;
3854 case dd::Table::RF_COMPRESSED:
3855 real_type = ROW_TYPE_COMPRESSED;
3856 break;
3857 case dd::Table::RF_DYNAMIC:
3858 real_type = ROW_TYPE_DYNAMIC;
3859 break;
3860 default:
3861 ut_d(ut_error);
3862 }
3863 }
3864 }
3865
3866 bool is_redundant;
3867 bool blob_prefix;
3868 ulint zip_ssize;
3869 /* Validate the table format options */
3870 if (format_validate(m_thd, m_form, real_type, zip_allowed, strict,
3871 &is_redundant, &blob_prefix, &zip_ssize, is_implicit)) {
3872 return nullptr;
3873 }
3874
3875 ulint n_v_cols = 0;
3876 ulint n_m_v_cols = 0;
3877
3878 /* Find out the number of virtual columns */
3879 for (ulint i = 0; i < m_form->s->fields; i++) {
3880 Field *field = m_form->field[i];
3881
3882 ut_ad(!(!innobase_is_v_fld(field) && innobase_is_multi_value_fld(field)));
3883
3884 if (innobase_is_v_fld(field)) {
3885 n_v_cols++;
3886
3887 if (innobase_is_multi_value_fld(field)) {
3888 n_m_v_cols++;
3889 }
3890 }
3891 }
3892
3893 ut_ad(n_v_cols <= n_cols);
3894
3895 uint32_t i_c = 0;
3896 uint32_t c_c = 0;
3897 uint32_t t_c = 0;
3898 uint32_t c_r_v = 0;
3899
3900 dd_table_get_column_counters(dd_tab->table(), i_c, c_c, t_c, c_r_v);
3901 /* Create the dict_table_t */
3902 dict_table_t *m_table = dict_mem_table_create(norm_name, 0, n_cols, n_v_cols,
3903 n_m_v_cols, 0, 0, t_c - c_c);
3904
3905 /* Setup column counters and current row version for table */
3906 m_table->initial_col_count = i_c;
3907 m_table->current_col_count = c_c;
3908 m_table->total_col_count = t_c;
3909 m_table->current_row_version = c_r_v;
3910
3911 /* Set up the field in the newly allocated dict_table_t */
3912 m_table->id = dd_tab->se_private_id();
3913
3914 if (dd_tab->se_private_data().exists(
3915 dd_table_key_strings[DD_TABLE_DATA_DIRECTORY])) {
3916 m_table->flags |= DICT_TF_MASK_DATA_DIR;
3917 }
3918
3919 /* Note : In V2, we don't need number of columns in table when first INSTANT
3920 ADD was done. */
3921
3922 /* For upgraded table having INSTANT ADD added columns in V1, it's necessary
3923 to read the number of instant columns for normal table (from dd::Table) or
3924 for partitioned table (from dd::Partition). One partition may have no instant
3925 columns, which is fine. */
3926 if (dd_table_is_upgraded_instant(dd_tab->table())) {
3927 auto fn = [&](const dd::Properties &p, const char *s) {
3928 uint32_t n_inst_cols;
3929 ut_a(p.exists(s));
3930 p.get(s, &n_inst_cols);
3931 m_table->set_instant_cols(n_inst_cols);
3932 m_table->set_upgraded_instant();
3933 ut_ad(m_table->has_instant_cols());
3934 };
3935
3936 if (!dd_table_is_partitioned(dd_tab->table())) {
3937 fn(table_se_private, dd_table_key_strings[DD_TABLE_INSTANT_COLS]);
3938 } else if (dd_part_has_instant_cols(
3939 *reinterpret_cast<const dd::Partition *>(dd_tab))) {
3940 fn(dd_tab->se_private_data(),
3941 dd_partition_key_strings[DD_PARTITION_INSTANT_COLS]);
3942 }
3943 }
3944
3945 /* Check if this table is FTS AUX table, if so, set DICT_TF2_AUX flag */
3946 fts_aux_table_t aux_table;
3947 if (fts_is_aux_table_name(&aux_table, norm_name, strlen(norm_name))) {
3948 DICT_TF2_FLAG_SET(m_table, DICT_TF2_AUX);
3949 m_table->parent_id = aux_table.parent_id;
3950 }
3951
3952 if (is_discard) {
3953 m_table->ibd_file_missing = true;
3954 m_table->flags2 |= DICT_TF2_DISCARDED;
3955 }
3956
3957 if (!is_redundant) {
3958 m_table->flags |= DICT_TF_COMPACT;
3959 }
3960
3961 if (is_implicit) {
3962 m_table->flags2 |= DICT_TF2_USE_FILE_PER_TABLE;
3963 } else {
3964 m_table->flags |= (1 << DICT_TF_POS_SHARED_SPACE);
3965 }
3966
3967 if (!blob_prefix) {
3968 m_table->flags |= (1 << DICT_TF_POS_ATOMIC_BLOBS);
3969 }
3970
3971 if (zip_ssize != 0) {
3972 m_table->flags |= (zip_ssize << DICT_TF_POS_ZIP_SSIZE);
3973 }
3974
3975 m_table->fts = nullptr;
3976 if (has_doc_id) {
3977 if (fulltext) {
3978 DICT_TF2_FLAG_SET(m_table, DICT_TF2_FTS);
3979 }
3980
3981 if (add_doc_id) {
3982 DICT_TF2_FLAG_SET(m_table, DICT_TF2_FTS_HAS_DOC_ID);
3983 }
3984
3985 if (fulltext || add_doc_id) {
3986 m_table->fts = fts_create(m_table);
3987 m_table->fts->cache = fts_cache_create(m_table);
3988 }
3989 }
3990
3991 bool is_temp = (m_form->s->tmp_table_def != nullptr);
3992 if (is_temp) {
3993 m_table->flags2 |= DICT_TF2_TEMPORARY;
3994 }
3995
3996 if (is_encrypted) {
3997 /* We don't support encrypt intrinsic and temporary table. */
3998 ut_ad(!m_table->is_intrinsic() && !m_table->is_temporary());
3999 /* This flag will be used to set file-per-table tablespace
4000 encryption flag */
4001 DICT_TF2_FLAG_SET(m_table, DICT_TF2_ENCRYPTION_FILE_PER_TABLE);
4002 }
4003
4004 mem_heap_t *heap = mem_heap_create(1000, UT_LOCATION_HERE);
4005
4006 /* Fill out each column info */
4007 fill_dict_columns(dd_tab, m_form, m_table, n_mysql_cols, heap, add_doc_id);
4008
4009 #ifdef UNIV_DEBUG
4010 if (m_table->is_upgraded_instant()) {
4011 ut_ad(m_table->has_instant_cols());
4012 }
4013 #endif
4014
4015 if (m_table->has_instant_cols() || m_table->has_row_versions()) {
4016 dd_fill_instant_columns_default(dd_tab->table(), m_table);
4017 }
4018
4019 mem_heap_free(heap);
4020
4021 return m_table;
4022 }
4023
4024 bool dd_create_tablespace(dd::cache::Dictionary_client *dd_client,
4025 const char *dd_space_name, space_id_t space_id,
4026 uint32_t flags, const char *filename, bool discarded,
4027 dd::Object_id &dd_space_id) {
4028 /* Get the autoextend_size attribute for the tablespace */
4029 fil_space_t *space = fil_space_get(space_id);
4030 ut_ad(space != nullptr);
4031
4032 std::unique_ptr<dd::Tablespace> dd_space(dd::create_object<dd::Tablespace>());
4033
4034 if (dd_space_name != nullptr) {
4035 dd_space->set_name(dd_space_name);
4036 }
4037
4038 if (dd_tablespace_get_mdl(dd_space->name().c_str())) {
4039 return true;
4040 }
4041
4042 dd_space->set_engine(innobase_hton_name);
4043 dd::Properties &p = dd_space->se_private_data();
4044 p.set(dd_space_key_strings[DD_SPACE_ID], static_cast<uint32>(space_id));
4045 p.set(dd_space_key_strings[DD_SPACE_FLAGS], static_cast<uint32>(flags));
4046 p.set(dd_space_key_strings[DD_SPACE_SERVER_VERSION],
4047 DD_SPACE_CURRENT_SRV_VERSION);
4048 p.set(dd_space_key_strings[DD_SPACE_VERSION], DD_SPACE_CURRENT_SPACE_VERSION);
4049
4050 dd_space_states state =
4051 (fsp_is_undo_tablespace(space_id)
4052 ? DD_SPACE_STATE_ACTIVE
4053 : (discarded ? DD_SPACE_STATE_DISCARDED : DD_SPACE_STATE_NORMAL));
4054 p.set(dd_space_key_strings[DD_SPACE_STATE], dd_space_state_values[state]);
4055
4056 dd::Tablespace_file *dd_file = dd_space->add_file();
4057 dd_file->set_filename(filename);
4058 dd_file->se_private_data().set(dd_space_key_strings[DD_SPACE_ID],
4059 static_cast<uint32>(space_id));
4060
4061 dd::Properties &toptions = dd_space->options();
4062 if (!FSP_FLAGS_GET_ENCRYPTION(flags)) {
4063 /* Update DD Option value, for Unencryption */
4064 toptions.set("encryption", "N");
4065
4066 } else {
4067 /* Update DD Option value, for Encryption */
4068 toptions.set("encryption", "Y");
4069 }
4070
4071 toptions.set(autoextend_size_str, space->autoextend_size_in_bytes);
4072
4073 if (dd_client->store(dd_space.get())) {
4074 return true;
4075 }
4076
4077 dd_space_id = dd_space.get()->id();
4078
4079 return false;
4080 }
4081
4082 bool dd_create_implicit_tablespace(dd::cache::Dictionary_client *dd_client,
4083 space_id_t space_id, const char *space_name,
4084 const char *filename, bool discarded,
4085 dd::Object_id &dd_space_id) {
4086 fil_space_t *space = fil_space_get(space_id);
4087 uint32_t flags = space->flags;
4088
4089 std::string tsn(space_name);
4090 dict_name::convert_to_space(tsn);
4091
4092 bool fail = dd_create_tablespace(dd_client, tsn.c_str(), space_id, flags,
4093 filename, discarded, dd_space_id);
4094
4095 return fail;
4096 }
4097
4098 bool dd_drop_tablespace(dd::cache::Dictionary_client *dd_client,
4099 dd::Object_id dd_space_id) {
4100 std::unique_ptr<dd::Tablespace> dd_space;
4101
4102 if (dd_client->acquire_uncached_uncommitted(dd_space_id, &dd_space) ||
4103 dd_space == nullptr) {
4104 my_error(ER_INTERNAL_ERROR, MYF(0),
4105 " InnoDB can't get tablespace object"
4106 " for space ",
4107 dd_space_id);
4108
4109 return true;
4110 }
4111
4112 ut_a(dd_space != nullptr);
4113
4114 if (dd_tablespace_get_mdl(dd_space->name().c_str())) {
4115 my_error(ER_INTERNAL_ERROR, MYF(0),
4116 " InnoDB can't set exclusive MDL on"
4117 " tablespace ",
4118 dd_space->name().c_str());
4119
4120 return true;
4121 }
4122
4123 bool error = dd_client->drop(dd_space.get());
4124 DBUG_EXECUTE_IF("fail_while_dropping_dd_object", error = true;);
4125
4126 if (error) {
4127 my_error(ER_INTERNAL_ERROR, MYF(0), " InnoDB can't drop tablespace object",
4128 dd_space->name().c_str());
4129 }
4130
4131 return error;
4132 }
4133
4134 /** Determine if a tablespace is implicit.
4135 @param[in] dd_space DD space object
4136 @param[out] implicit whether the tablespace is implicit tablespace
4137 @retval false on success
4138 @retval true on failure (corrupt tablespace object). */
4139 bool dd_tablespace_is_implicit(const dd::Tablespace *dd_space, bool *implicit) {
4140 space_id_t id = 0;
4141 uint32_t flags;
4142
4143 if (dd_space->se_private_data().get(dd_space_key_strings[DD_SPACE_ID], &id)) {
4144 return true;
4145 }
4146
4147 dd_space->se_private_data().get(dd_space_key_strings[DD_SPACE_FLAGS], &flags);
4148 *implicit = fsp_is_file_per_table(id, flags);
4149
4150 return false;
4151 }
4152
4153 bool dd_get_tablespace_size_option(dd::cache::Dictionary_client *dd_client,
4154 const dd::Object_id dd_space_id,
4155 uint64_t *autoextend_size) {
4156 /* Get the tablespace object. */
4157 dd::Tablespace *dd_space = nullptr;
4158
4159 if (dd_client->acquire_uncached_uncommitted<dd::Tablespace>(dd_space_id,
4160 &dd_space)) {
4161 /* purecov: begin inspected */
4162 my_error(ER_INTERNAL_ERROR, MYF(0),
4163 " InnoDB: Can't get tablespace object for space ", dd_space_id);
4164 return true;
4165 /* purecov: end */
4166 }
4167
4168 ut_a(dd_space != nullptr);
4169
4170 const dd::Properties &p = dd_space->options();
4171
4172 if (p.exists(autoextend_size_str)) {
4173 p.get(autoextend_size_str, autoextend_size);
4174 } else {
4175 *autoextend_size = 0;
4176 }
4177
4178 return false;
4179 }
4180
4181 bool dd_implicit_alter_tablespace(dd::cache::Dictionary_client *dd_client,
4182 dd::Object_id dd_space_id,
4183 HA_CREATE_INFO *create_info) {
4184 ut_a(create_info->m_implicit_tablespace_autoextend_size_change);
4185
4186 dd::Tablespace *dd_space = nullptr;
4187 bool is_implicit{};
4188
4189 if (dd_client->acquire_uncached_uncommitted<dd::Tablespace>(dd_space_id,
4190 &dd_space) ||
4191 dd_space == nullptr ||
4192 dd_tablespace_is_implicit(dd_space, &is_implicit) || !is_implicit) {
4193 /* purecov: begin inspected */
4194 my_error(ER_INTERNAL_ERROR, MYF(0),
4195 " InnoDB: Can't get tablespace object for space ", dd_space_id);
4196 return true;
4197 /* purecov: end */
4198 }
4199
4200 ut_a(dd_space != nullptr);
4201
4202 if (dd_tablespace_get_mdl(dd_space->name().c_str())) {
4203 /* purecov: begin inspected */
4204 my_error(ER_INTERNAL_ERROR, MYF(0),
4205 " InnoDB can't set exclusive MDL on"
4206 " tablespace ",
4207 dd_space->name().c_str());
4208 return true;
4209 /* purecov: end */
4210 }
4211
4212 /* Get the space id from the tablespace properties. */
4213 const dd::Properties &pd = dd_space->se_private_data();
4214 uint32_t id;
4215 pd.get(dd_space_key_strings[DD_SPACE_ID], &id);
4216
4217 /* Get the tablespace options. */
4218 dd::Properties &p = dd_space->options();
4219
4220 /* Find out if the tablespace is discarded. */
4221 bool is_discarded = dd_tablespace_is_discarded(dd_space);
4222
4223 ut_ad(fil_space_get(id) != nullptr || is_discarded);
4224
4225 if (create_info->m_implicit_tablespace_autoextend_size_change &&
4226 create_info->m_implicit_tablespace_autoextend_size > 0 &&
4227 validate_autoextend_size_value(
4228 create_info->m_implicit_tablespace_autoextend_size) != DB_SUCCESS) {
4229 return true;
4230 }
4231
4232 /* Set the autoextend_size attribute if changed. */
4233 if (create_info->m_implicit_tablespace_autoextend_size_change) {
4234 p.set(autoextend_size_str,
4235 create_info->m_implicit_tablespace_autoextend_size);
4236 }
4237
4238 if (dd_client->update(dd_space)) {
4239 return true;
4240 }
4241
4242 /* Set the autoextend_size value in the cached space object. */
4243
4244 /* Space could be invalid in case of a discarded tablespaces. The
4245 autoextend_size attribute will be set in the fil_space_t when it
4246 is re-initialized during import. */
4247 if (!is_discarded) {
4248 if (create_info->m_implicit_tablespace_autoextend_size_change) {
4249 fil_set_autoextend_size(
4250 id, create_info->m_implicit_tablespace_autoextend_size);
4251 }
4252 }
4253
4254 return false;
4255 }
4256
4257 bool dd_set_tablespace_compression(dd::cache::Dictionary_client *client,
4258 const char *algorithm,
4259 dd::Object_id dd_space_id) {
4260 dd::Tablespace *dd_space{};
4261 auto fail = client->acquire_uncached<dd::Tablespace>(dd_space_id, &dd_space);
4262
4263 if (fail || dd_space == nullptr) {
4264 return true;
4265 }
4266
4267 space_id_t space_id = 0;
4268
4269 dd_space->se_private_data().get(dd_space_key_strings[DD_SPACE_ID], &space_id);
4270
4271 auto err = fil_set_compression(space_id, algorithm);
4272
4273 return err != DB_SUCCESS;
4274 }
4275
4276 /** Load foreign key constraint info for the dd::Table object.
4277 @param[out] m_table InnoDB table handle
4278 @param[in] dd_table Global DD table
4279 @param[in] col_names column names, or NULL
4280 @param[in] ignore_err DICT_ERR_IGNORE_FK_NOKEY or DICT_ERR_IGNORE_NONE
4281 @param[in] dict_locked True if dict_sys->mutex is already held,
4282 otherwise false
4283 @return DB_SUCCESS if successfully load FK constraint */
4284 dberr_t dd_table_load_fk_from_dd(dict_table_t *m_table,
4285 const dd::Table *dd_table,
4286 const char **col_names,
4287 dict_err_ignore_t ignore_err,
4288 bool dict_locked) {
4289 dberr_t err = DB_SUCCESS;
4290
4291 /* Now fill in the foreign key info */
4292 for (const dd::Foreign_key *key : dd_table->foreign_keys()) {
4293 char buf[MAX_FULL_NAME_LEN + 1];
4294
4295 if (*(key->name().c_str()) == '#' && *(key->name().c_str() + 1) == 'f') {
4296 continue;
4297 }
4298
4299 dd::String_type db_name = key->referenced_table_schema_name();
4300 dd::String_type tb_name = key->referenced_table_name();
4301
4302 bool truncated;
4303 build_table_filename(buf, sizeof(buf), db_name.c_str(), tb_name.c_str(),
4304 nullptr, 0, &truncated);
4305
4306 char norm_name[FN_REFLEN * 2];
4307
4308 if (truncated || !normalize_table_name(norm_name, buf)) {
4309 /* purecov: begin inspected */
4310 ut_d(ut_error);
4311 ut_o(return DB_TOO_LONG_PATH);
4312 /* purecov: end */
4313 }
4314
4315 dict_foreign_t *foreign = dict_mem_foreign_create();
4316 foreign->foreign_table_name =
4317 mem_heap_strdup(foreign->heap, m_table->name.m_name);
4318
4319 dict_mem_foreign_table_name_lookup_set(foreign, true);
4320
4321 if (innobase_get_lower_case_table_names() == 2) {
4322 innobase_casedn_str(norm_name);
4323 } else {
4324 #ifndef _WIN32
4325 if (innobase_get_lower_case_table_names() == 1) {
4326 innobase_casedn_str(norm_name);
4327 }
4328 #endif /* !_WIN32 */
4329 }
4330
4331 foreign->referenced_table_name = mem_heap_strdup(foreign->heap, norm_name);
4332 dict_mem_referenced_table_name_lookup_set(foreign, true);
4333 ulint db_len = dict_get_db_name_len(m_table->name.m_name);
4334
4335 ut_ad(db_len > 0);
4336
4337 memcpy(buf, m_table->name.m_name, db_len);
4338
4339 buf[db_len] = '\0';
4340
4341 snprintf(norm_name, sizeof norm_name, "%s/%s", buf, key->name().c_str());
4342
4343 foreign->id = mem_heap_strdup(foreign->heap, norm_name);
4344
4345 switch (key->update_rule()) {
4346 case dd::Foreign_key::RULE_NO_ACTION:
4347 /*
4348 Since SET DEFAULT clause is not supported, ignore it by converting
4349 into the value DICT_FOREIGN_ON_UPDATE_NO_ACTION
4350 */
4351 case dd::Foreign_key::RULE_SET_DEFAULT:
4352 foreign->type = DICT_FOREIGN_ON_UPDATE_NO_ACTION;
4353 break;
4354 case dd::Foreign_key::RULE_RESTRICT:
4355 foreign->type = 0;
4356 break;
4357 case dd::Foreign_key::RULE_CASCADE:
4358 foreign->type = DICT_FOREIGN_ON_UPDATE_CASCADE;
4359 break;
4360 case dd::Foreign_key::RULE_SET_NULL:
4361 foreign->type = DICT_FOREIGN_ON_UPDATE_SET_NULL;
4362 break;
4363 default:
4364 ut_d(ut_error);
4365 }
4366
4367 switch (key->delete_rule()) {
4368 case dd::Foreign_key::RULE_NO_ACTION:
4369 /*
4370 Since SET DEFAULT clause is not supported, ignore it by converting
4371 into the value DICT_FOREIGN_ON_UPDATE_NO_ACTION
4372 */
4373 case dd::Foreign_key::RULE_SET_DEFAULT:
4374 foreign->type |= DICT_FOREIGN_ON_DELETE_NO_ACTION;
4375 case dd::Foreign_key::RULE_RESTRICT:
4376 break;
4377 case dd::Foreign_key::RULE_CASCADE:
4378 foreign->type |= DICT_FOREIGN_ON_DELETE_CASCADE;
4379 break;
4380 case dd::Foreign_key::RULE_SET_NULL:
4381 foreign->type |= DICT_FOREIGN_ON_DELETE_SET_NULL;
4382 break;
4383 default:
4384 ut_d(ut_error);
4385 }
4386
4387 foreign->n_fields = key->elements().size();
4388
4389 foreign->foreign_col_names = static_cast<const char **>(
4390 mem_heap_alloc(foreign->heap, foreign->n_fields * sizeof(void *)));
4391
4392 foreign->referenced_col_names = static_cast<const char **>(
4393 mem_heap_alloc(foreign->heap, foreign->n_fields * sizeof(void *)));
4394
4395 ulint num_ref = 0;
4396
4397 for (const dd::Foreign_key_element *key_e : key->elements()) {
4398 dd::String_type ref_col_name = key_e->referenced_column_name();
4399
4400 foreign->referenced_col_names[num_ref] =
4401 mem_heap_strdup(foreign->heap, ref_col_name.c_str());
4402 ut_ad(ref_col_name.c_str());
4403
4404 const dd::Column *f_col = &key_e->column();
4405 foreign->foreign_col_names[num_ref] =
4406 mem_heap_strdup(foreign->heap, f_col->name().c_str());
4407 num_ref++;
4408 }
4409
4410 if (!dict_locked) {
4411 dict_sys_mutex_enter();
4412 }
4413 #ifdef UNIV_DEBUG
4414 dict_table_t *for_table;
4415
4416 for_table =
4417 dict_table_check_if_in_cache_low(foreign->foreign_table_name_lookup);
4418
4419 ut_ad(for_table);
4420 #endif
4421 /* Fill in foreign->foreign_table and index, then add to
4422 dict_table_t */
4423 err =
4424 dict_foreign_add_to_cache(foreign, col_names, false, true, ignore_err);
4425 if (!dict_locked) {
4426 dict_sys_mutex_exit();
4427 }
4428
4429 if (err != DB_SUCCESS) {
4430 break;
4431 }
4432
4433 /* Set up the FK virtual column info */
4434 dict_mem_table_free_foreign_vcol_set(m_table);
4435 dict_mem_table_fill_foreign_vcol_set(m_table);
4436 }
4437 return err;
4438 }
4439
4440 /** Load foreign key constraint for the table. Note, it could also open
4441 the foreign table, if this table is referenced by the foreign table
4442 @param[in,out] client data dictionary client
4443 @param[in] tbl_name Table Name
4444 @param[in] col_names column names, or NULL
4445 @param[out] m_table InnoDB table handle
4446 @param[in] dd_table Global DD table
4447 @param[in] thd thread THD
4448 @param[in] dict_locked True if dict_sys->mutex is already held,
4449 otherwise false
4450 @param[in] check_charsets whether to check charset compatibility
4451 @param[in,out] fk_tables name list for tables that refer to this table
4452 @return DB_SUCCESS if successfully load FK constraint */
4453 dberr_t dd_table_load_fk(dd::cache::Dictionary_client *client,
4454 const char *tbl_name, const char **col_names,
4455 dict_table_t *m_table, const dd::Table *dd_table,
4456 THD *thd, bool dict_locked, bool check_charsets,
4457 dict_names_t *fk_tables) {
4458 dberr_t err = DB_SUCCESS;
4459 dict_err_ignore_t ignore_err = DICT_ERR_IGNORE_NONE;
4460
4461 /* Check whether FOREIGN_KEY_CHECKS is set to 0. If so, the table
4462 can be opened even if some FK indexes are missing. If not, the table
4463 can't be opened in the same situation */
4464 if (thd_test_options(thd, OPTION_NO_FOREIGN_KEY_CHECKS)) {
4465 ignore_err = DICT_ERR_IGNORE_FK_NOKEY;
4466 }
4467
4468 err = dd_table_load_fk_from_dd(m_table, dd_table, col_names, ignore_err,
4469 dict_locked);
4470
4471 if (err != DB_SUCCESS) {
4472 return err;
4473 }
4474
4475 if (dict_locked) {
4476 dict_sys_mutex_exit();
4477 }
4478
4479 DBUG_EXECUTE_IF("enable_stack_overrun_post_alter_commit",
4480 { DBUG_SET("+d,simulate_stack_overrun"); });
4481 err = dd_table_check_for_child(client, tbl_name, col_names, m_table,
4482 check_charsets, ignore_err, fk_tables);
4483 DBUG_EXECUTE_IF("enable_stack_overrun_post_alter_commit",
4484 { DBUG_SET("-d,simulate_stack_overrun"); });
4485
4486 if (dict_locked) {
4487 dict_sys_mutex_enter();
4488 }
4489
4490 return err;
4491 }
4492
4493 dberr_t dd_table_check_for_child(dd::cache::Dictionary_client *client,
4494 const char *tbl_name, const char **col_names,
4495 dict_table_t *m_table, bool check_charsets,
4496 dict_err_ignore_t ignore_err,
4497 dict_names_t *fk_tables) {
4498 dberr_t err = DB_SUCCESS;
4499
4500 /* TODO: NewDD: Temporary ignore DD system table until
4501 WL#6049 inplace */
4502 if (!dict_sys_t::is_dd_table_id(m_table->id) && fk_tables != nullptr) {
4503 std::vector<dd::String_type> child_schema;
4504 std::vector<dd::String_type> child_name;
4505 std::string db_str;
4506 std::string tbl_str;
4507
4508 dict_name::get_table(m_table->name.m_name, db_str, tbl_str);
4509
4510 if (client->fetch_fk_children_uncached(db_str.c_str(), tbl_str.c_str(),
4511 "InnoDB", false, &child_schema,
4512 &child_name)) {
4513 return DB_ERROR;
4514 }
4515
4516 std::vector<dd::String_type>::iterator it = child_name.begin();
4517 for (auto &db_name : child_schema) {
4518 dd::String_type tb_name = *it;
4519
4520 char buf[2 * NAME_CHAR_LEN * 5 + 2 + 1];
4521 bool truncated;
4522 build_table_filename(buf, sizeof(buf), db_name.c_str(), tb_name.c_str(),
4523 nullptr, 0, &truncated);
4524
4525 char full_name[FN_REFLEN];
4526
4527 if (truncated || !normalize_table_name(full_name, buf)) {
4528 /* purecov: begin inspected */
4529 ut_d(ut_error);
4530 ut_o(return DB_TOO_LONG_PATH);
4531 /* purecov: end */
4532 }
4533
4534 if (innobase_get_lower_case_table_names() == 2) {
4535 innobase_casedn_str(full_name);
4536 } else {
4537 #ifndef _WIN32
4538 if (innobase_get_lower_case_table_names() == 1) {
4539 innobase_casedn_str(full_name);
4540 }
4541 #endif /* !_WIN32 */
4542 }
4543
4544 dict_sys_mutex_enter();
4545
4546 /* Load the foreign table first */
4547 dict_table_t *foreign_table =
4548 dd_table_open_on_name_in_mem(full_name, true);
4549
4550 if (foreign_table) {
4551 for (auto &fk : foreign_table->foreign_set) {
4552 if (strcmp(fk->referenced_table_name, tbl_name) != 0) {
4553 continue;
4554 }
4555
4556 if (fk->referenced_table) {
4557 ut_ad(fk->referenced_table == m_table);
4558 } else {
4559 err = dict_foreign_add_to_cache(fk, col_names, check_charsets,
4560 false, ignore_err);
4561 if (err != DB_SUCCESS) {
4562 foreign_table->release();
4563 dict_sys_mutex_exit();
4564 return err;
4565 }
4566 }
4567 }
4568 foreign_table->release();
4569 } else {
4570 /* To avoid recursively loading the tables
4571 related through the foreign key constraints,
4572 the child table name is saved here. The child
4573 table will be loaded later, along with its
4574 foreign key constraint. */
4575 lint old_size = mem_heap_get_size(m_table->heap);
4576
4577 fk_tables->push_back(
4578 mem_heap_strdupl(m_table->heap, full_name, strlen(full_name)));
4579
4580 lint new_size = mem_heap_get_size(m_table->heap);
4581 dict_sys->size += new_size - old_size;
4582 }
4583
4584 dict_sys_mutex_exit();
4585
4586 ut_ad(it != child_name.end());
4587 ++it;
4588 }
4589 }
4590
4591 return err;
4592 }
4593
4594 /** Get tablespace name of dd::Table
4595 @tparam Table dd::Table or dd::Partition
4596 @param[in] dd_table dd table object
4597 @return the tablespace name or nullptr if failed */
4598 template <typename Table>
4599 const char *dd_table_get_space_name(const Table *dd_table) {
4600 dd::Tablespace *dd_space = nullptr;
4601 THD *thd = current_thd;
4602 const char *space_name;
4603
4604 DBUG_TRACE;
4605 ut_ad(srv_shutdown_state.load() < SRV_SHUTDOWN_DD);
4606
4607 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
4608 dd::cache::Dictionary_client::Auto_releaser releaser(client);
4609
4610 dd::Object_id dd_space_id = (*dd_table->indexes().begin())->tablespace_id();
4611
4612 if (client->acquire_uncached_uncommitted<dd::Tablespace>(dd_space_id,
4613 &dd_space) ||
4614 dd_space == nullptr) {
4615 ut_d(ut_error);
4616 ut_o(return nullptr);
4617 }
4618
4619 space_name = dd_space->name().c_str();
4620
4621 return space_name;
4622 }
4623
4624 /** Get the first filepath from mysql.tablespace_datafiles
4625 for a given space_id.
4626 @tparam Table dd::Table or dd::Partition
4627 @param[in,out] heap heap for store file name.
4628 @param[in] table dict table
4629 @param[in] dd_table dd table obj
4630 @return First filepath (caller must invoke ut::free() on it)
4631 @retval nullptr if no mysql.tablespace_datafiles entry was found. */
4632 template <typename Table>
4633 char *dd_get_first_path(mem_heap_t *heap, dict_table_t *table,
4634 Table *dd_table) {
4635 char *filepath = nullptr;
4636 dd::Tablespace *dd_space = nullptr;
4637 THD *thd = current_thd;
4638 MDL_ticket *mdl = nullptr;
4639 dd::Object_id dd_space_id;
4640
4641 ut_ad(srv_shutdown_state.load() < SRV_SHUTDOWN_DD);
4642 ut_ad(!dict_sys_mutex_own());
4643
4644 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
4645 dd::cache::Dictionary_client::Auto_releaser releaser(client);
4646
4647 if (dd_table == nullptr) {
4648 std::string db_str;
4649 std::string tbl_str;
4650 dict_name::get_table(table->name.m_name, db_str, tbl_str);
4651
4652 if (db_str.empty() || tbl_str.empty() ||
4653 dd_mdl_acquire(thd, &mdl, db_str.c_str(), tbl_str.c_str())) {
4654 return nullptr;
4655 }
4656
4657 const dd::Table *table_def = nullptr;
4658 if (client->acquire(db_str.c_str(), tbl_str.c_str(), &table_def) ||
4659 table_def == nullptr) {
4660 dd_mdl_release(thd, &mdl);
4661 return nullptr;
4662 }
4663
4664 dd_space_id = dd_first_index(table_def)->tablespace_id();
4665
4666 dd_mdl_release(thd, &mdl);
4667 } else {
4668 dd_space_id = dd_first_index(dd_table)->tablespace_id();
4669 }
4670
4671 if (client->acquire_uncached_uncommitted<dd::Tablespace>(dd_space_id,
4672 &dd_space)) {
4673 ut_d(ut_error);
4674 ut_o(return nullptr);
4675 }
4676
4677 if (dd_space != nullptr) {
4678 dd::Tablespace_file *dd_file =
4679 const_cast<dd::Tablespace_file *>(*(dd_space->files().begin()));
4680
4681 filepath = mem_heap_strdup(heap, dd_file->filename().c_str());
4682
4683 return filepath;
4684 }
4685
4686 return nullptr;
4687 }
4688
4689 template <typename Table>
4690 void dd_get_and_save_data_dir_path(dict_table_t *table, const Table *dd_table,
4691 bool dict_mutex_own) {
4692 mem_heap_t *heap = nullptr;
4693
4694 if (!DICT_TF_HAS_DATA_DIR(table->flags) || table->data_dir_path != nullptr) {
4695 return;
4696 }
4697
4698 char *path = fil_space_get_first_path(table->space);
4699
4700 if (path == nullptr) {
4701 heap = mem_heap_create(100, UT_LOCATION_HERE);
4702 if (dict_mutex_own) {
4703 dict_mutex_exit_for_mysql();
4704 }
4705 path = dd_get_first_path(heap, table, dd_table);
4706 if (dict_mutex_own) {
4707 dict_mutex_enter_for_mysql();
4708 }
4709 }
4710
4711 if (!dict_mutex_own) {
4712 dict_mutex_enter_for_mysql();
4713 }
4714
4715 if (path != nullptr) {
4716 dict_save_data_dir_path(table, path);
4717 }
4718
4719 if (!dict_mutex_own) {
4720 dict_mutex_exit_for_mysql();
4721 }
4722
4723 if (heap != nullptr) {
4724 mem_heap_free(heap);
4725 } else {
4726 ut::free(path);
4727 }
4728 }
4729
4730 template void dd_get_and_save_data_dir_path<dd::Table>(dict_table_t *,
4731 const dd::Table *, bool);
4732
4733 template void dd_get_and_save_data_dir_path<dd::Partition>(
4734 dict_table_t *, const dd::Partition *, bool);
4735
4736 /** Get the meta-data filename from the table name for a
4737 single-table tablespace.
4738 @param[in,out] table table object
4739 @param[in] dd_table DD table object
4740 @param[out] filename filename
4741 @param[in] max_len filename max length */
4742 void dd_get_meta_data_filename(dict_table_t *table, dd::Table *dd_table,
4743 char *filename, ulint max_len) {
4744 /* Make sure the data_dir_path is set. */
4745 dd_get_and_save_data_dir_path(table, dd_table, false);
4746
4747 std::string path = dict_table_get_datadir(table);
4748
4749 auto filepath = Fil_path::make(path, table->name.m_name, CFG, true);
4750
4751 ut_a(max_len >= strlen(filepath) + 1);
4752
4753 strcpy(filename, filepath);
4754
4755 ut::free(filepath);
4756 }
4757
4758 /** Opens a tablespace for dd_load_table_one()
4759 @tparam Table dd::Table or dd::Partition
4760 @param[in,out] dd_table dd table
4761 @param[in,out] table A table that refers to the tablespace to
4762 open
4763 @param[in,out] heap A memory heap
4764 @param[in] expected_fsp_flags expected flags of tablespace to be
4765 loaded
4766 @param[in] ignore_err Whether to ignore an error. */
4767 template <typename Table>
4768 void dd_load_tablespace(const Table *dd_table, dict_table_t *table,
4769 mem_heap_t *heap, dict_err_ignore_t ignore_err,
4770 uint32_t expected_fsp_flags) {
4771 ut_ad(!table->is_temporary());
4772 ut_ad(dict_sys_mutex_own());
4773
4774 /* The system and temporary tablespaces are preloaded and
4775 always available. */
4776 if (fsp_is_system_or_temp_tablespace(table->space)) {
4777 return;
4778 }
4779
4780 if (dict_table_is_discarded(table)) {
4781 /* If doing an IMPORT, don't report this warning. This is expected */
4782 if (thd_tablespace_op(current_thd) != Alter_info::ALTER_IMPORT_TABLESPACE) {
4783 ib::warn(ER_IB_MSG_171)
4784 << "Tablespace for table " << table->name << " is set as discarded.";
4785 }
4786
4787 table->ibd_file_missing = true;
4788 return;
4789 }
4790
4791 /* A general tablespace name is not the same as the table name.
4792 Use the general tablespace name if it can be read from the
4793 dictionary, if not use 'innodb_general_##. */
4794 char *shared_space_name = nullptr;
4795 const char *space_name;
4796 std::string tablespace_name;
4797 const char *tbl_name;
4798
4799 if (DICT_TF_HAS_SHARED_SPACE(table->flags)) {
4800 if (table->space == dict_sys_t::s_dict_space_id) {
4801 shared_space_name = mem_strdup(dict_sys_t::s_dd_space_name);
4802 } else if (srv_sys_tablespaces_open) {
4803 /* For avoiding deadlock, we need to exit
4804 dict_sys->mutex. */
4805 dict_sys_mutex_exit();
4806 shared_space_name = mem_strdup(dd_table_get_space_name(dd_table));
4807 dict_sys_mutex_enter();
4808 } else {
4809 /* Make the temporary tablespace name. */
4810 shared_space_name = static_cast<char *>(ut::malloc_withkey(
4811 UT_NEW_THIS_FILE_PSI_KEY, strlen(general_space_name) + 20));
4812
4813 sprintf(shared_space_name, "%s_" ULINTPF, general_space_name,
4814 static_cast<ulint>(table->space));
4815 }
4816
4817 space_name = shared_space_name;
4818 tbl_name = space_name;
4819 } else {
4820 tbl_name = table->name.m_name;
4821
4822 tablespace_name.assign(tbl_name);
4823 dict_name::convert_to_space(tablespace_name);
4824 space_name = tablespace_name.c_str();
4825 }
4826
4827 auto is_already_opened = [&]() {
4828 if (fil_space_exists_in_mem(table->space, space_name, false, true)) {
4829 dd_get_and_save_data_dir_path(table, dd_table, true);
4830 ut::free(shared_space_name);
4831 return true;
4832 }
4833 return false;
4834 };
4835
4836 /* The tablespace may already be open. */
4837 if (is_already_opened()) return;
4838
4839 if (!(ignore_err & DICT_ERR_IGNORE_RECOVER_LOCK)) {
4840 ib::error(ER_IB_MSG_172)
4841 << "Failed to find tablespace for table " << table->name
4842 << " in the cache. Attempting"
4843 " to load the tablespace with space id "
4844 << table->space;
4845 }
4846
4847 /* Try to get the filepath if this space_id is already open.
4848 If the filepath is not found, fil_ibd_open() will make a default
4849 filepath from the tablespace name */
4850 char *filepath = fil_space_get_first_path(table->space);
4851
4852 if (filepath != nullptr) {
4853 /* If space id is already open with a different space name, then skip
4854 loading the space. It can happen because DDL log recovery might not
4855 have happened yet. */
4856 table->ibd_file_missing = true;
4857
4858 ut::free(shared_space_name);
4859 ut::free(filepath);
4860 return;
4861 }
4862
4863 ut_ad(filepath == nullptr);
4864
4865 /* If the space is not open yet, then try to open by dd path. If the file
4866 path is changed then boot_tablespaces() would always open the tablespace. */
4867 dict_sys_mutex_exit();
4868 filepath = dd_get_first_path(heap, table, dd_table);
4869 DEBUG_SYNC_C("innodb_dd_load_tablespace_no_dict_mutex");
4870 dict_sys_mutex_enter();
4871
4872 if (filepath == nullptr) {
4873 ib::warn(ER_IB_MSG_173) << "Could not find the filepath"
4874 << " for table " << table->name << ", space ID "
4875 << table->space << " in the data dictionary.";
4876 }
4877
4878 /* The tablespace may have been opened while we released the dict_sys mutex.
4879 We need to check again if it was not opened in meantime, as fil_ibd_open
4880 will try to close it forcefully, even if some IO is underway, leading to
4881 crash. */
4882 if (is_already_opened()) return;
4883
4884 /* Try to open the tablespace. We set the 2nd param (fix_dict) to
4885 false because we do not have an x-lock on dict_operation_lock */
4886 dberr_t err =
4887 fil_ibd_open(true, FIL_TYPE_TABLESPACE, table->space, expected_fsp_flags,
4888 space_name, filepath, true, false);
4889
4890 if (err == DB_SUCCESS) {
4891 /* This will set the DATA DIRECTORY for SHOW CREATE TABLE. */
4892 dd_get_and_save_data_dir_path(table, dd_table, true);
4893 } else {
4894 /* We failed to find a sensible tablespace file */
4895 table->ibd_file_missing = true;
4896 }
4897
4898 ut::free(shared_space_name);
4899 }
4900
4901 /** Get the space name from mysql.tablespaces for a given space_id.
4902 @tparam Table dd::Table or dd::Partition
4903 @param[in,out] heap heap for store file name.
4904 @param[in] table dict table
4905 @param[in] dd_table dd table obj
4906 @return First filepath (caller must invoke ut::free() on it)
4907 @retval nullptr if no mysql.tablespace_datafiles entry was found. */
4908 template <typename Table>
4909 char *dd_space_get_name(mem_heap_t *heap, dict_table_t *table,
4910 Table *dd_table) {
4911 dd::Object_id dd_space_id;
4912 THD *thd = current_thd;
4913 dd::Tablespace *dd_space = nullptr;
4914
4915 ut_ad(srv_shutdown_state.load() < SRV_SHUTDOWN_DD);
4916 ut_ad(!dict_sys_mutex_own());
4917
4918 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
4919 dd::cache::Dictionary_client::Auto_releaser releaser(client);
4920
4921 if (dd_table == nullptr) {
4922 std::string db_str;
4923 std::string tbl_str;
4924 dict_name::get_table(table->name.m_name, db_str, tbl_str);
4925
4926 MDL_ticket *mdl = nullptr;
4927 if (db_str.empty() || tbl_str.empty() ||
4928 dd_mdl_acquire(thd, &mdl, db_str.c_str(), tbl_str.c_str())) {
4929 return nullptr;
4930 }
4931
4932 const dd::Table *table_def = nullptr;
4933 if (client->acquire(db_str.c_str(), tbl_str.c_str(), &table_def) ||
4934 table_def == nullptr) {
4935 dd_mdl_release(thd, &mdl);
4936 return nullptr;
4937 }
4938
4939 dd_space_id = dd_first_index(table_def)->tablespace_id();
4940
4941 dd_mdl_release(thd, &mdl);
4942 } else {
4943 dd_space_id = dd_first_index(dd_table)->tablespace_id();
4944 }
4945
4946 if (client->acquire_uncached_uncommitted<dd::Tablespace>(dd_space_id,
4947 &dd_space) ||
4948 dd_space == nullptr) {
4949 ut_d(ut_error);
4950 ut_o(return nullptr);
4951 }
4952
4953 return mem_heap_strdup(heap, dd_space->name().c_str());
4954 }
4955
4956 /** Make sure the tablespace name is saved in dict_table_t if the table
4957 uses a general tablespace.
4958 Try to read it from the fil_system_t first, then from DD.
4959 @param[in] table Table object
4960 @param[in] dd_table Global DD table or partition object
4961 @param[in] dict_mutex_own true if dict_sys->mutex is owned already */
4962 template <typename Table>
4963 void dd_get_and_save_space_name(dict_table_t *table, const Table *dd_table,
4964 bool dict_mutex_own) {
4965 /* Do this only for general tablespaces. */
4966 if (!DICT_TF_HAS_SHARED_SPACE(table->flags)) {
4967 return;
4968 }
4969
4970 bool use_cache = true;
4971 if (table->tablespace != nullptr) {
4972 if (srv_sys_tablespaces_open &&
4973 dict_table_has_temp_general_tablespace_name(table->tablespace)) {
4974 /* We previous saved the temporary name,
4975 get the real one now. */
4976 use_cache = false;
4977 } else {
4978 /* Keep and use this name */
4979 return;
4980 }
4981 }
4982
4983 if (use_cache) {
4984 fil_space_t *space = fil_space_acquire_silent(table->space);
4985
4986 if (space != nullptr) {
4987 /* Use this name unless it is a temporary general
4988 tablespace name and we can now replace it. */
4989 if (!srv_sys_tablespaces_open ||
4990 !dict_table_has_temp_general_tablespace_name(space->name)) {
4991 /* Use this tablespace name */
4992 table->tablespace = mem_heap_strdup(table->heap, space->name);
4993
4994 fil_space_release(space);
4995 return;
4996 }
4997 fil_space_release(space);
4998 }
4999 }
5000
5001 /* Read it from the dictionary. */
5002 if (srv_sys_tablespaces_open) {
5003 if (dict_mutex_own) {
5004 dict_mutex_exit_for_mysql();
5005 }
5006
5007 table->tablespace = dd_space_get_name(table->heap, table, dd_table);
5008
5009 if (dict_mutex_own) {
5010 dict_mutex_enter_for_mysql();
5011 }
5012 }
5013 }
5014
5015 template void dd_get_and_save_space_name<dd::Table>(dict_table_t *,
5016 const dd::Table *, bool);
5017
5018 template void dd_get_and_save_space_name<dd::Partition>(dict_table_t *,
5019 const dd::Partition *,
5020 bool);
5021
5022 /** Open or load a table definition based on a Global DD object.
5023 @tparam Table dd::Table or dd::Partition
5024 @param[in,out] client data dictionary client
5025 @param[in] table MySQL table definition
5026 @param[in] norm_name Table Name
5027 @param[in] dd_table Global DD table or partition object
5028 @param[in] thd thread THD
5029 @param[in,out] fk_list stack of table names which need to load
5030 @return ptr to dict_table_t filled, otherwise, nullptr */
5031 template <typename Table>
5032 dict_table_t *dd_open_table_one(dd::cache::Dictionary_client *client,
5033 const TABLE *table, const char *norm_name,
5034 const Table *dd_table, THD *thd,
5035 dict_names_t &fk_list) {
5036 ut_ad(dd_table != nullptr);
5037
5038 bool implicit;
5039 std::unique_ptr<dd::Tablespace> dd_space;
5040
5041 if (dd_table->tablespace_id() == dict_sys_t::s_dd_dict_space_id) {
5042 /* DD tables are in shared DD tablespace */
5043 implicit = false;
5044 } else {
5045 if (client->acquire_uncached_uncommitted<dd::Tablespace>(
5046 dd_first_index(dd_table)->tablespace_id(), &dd_space) ||
5047 dd_space == nullptr) {
5048 /* Tablespace no longer exist, it could be already dropped */
5049 return nullptr;
5050 }
5051
5052 if (dd_tablespace_is_implicit(dd_space.get(), &implicit)) {
5053 /* Corrupt tablespace info. */
5054 return nullptr;
5055 }
5056 }
5057
5058 const bool zip_allowed = srv_page_size <= UNIV_ZIP_SIZE_MAX;
5059 const bool strict = false;
5060 bool first_index = true;
5061
5062 /* Create dict_table_t for the table */
5063 dict_table_t *m_table = dd_fill_dict_table(
5064 dd_table, table, norm_name, nullptr, zip_allowed, strict, thd, implicit);
5065
5066 if (m_table == nullptr) {
5067 return nullptr;
5068 }
5069
5070 /* Create dict_index_t for the table */
5071 int ret;
5072 ret = dd_fill_dict_index(dd_table->table(), table, m_table, thd);
5073
5074 if (ret != 0) {
5075 return nullptr;
5076 }
5077
5078 if (dd_space && !implicit) {
5079 const char *name = dd_space->name().c_str();
5080 if (name) {
5081 m_table->tablespace = mem_heap_strdupl(m_table->heap, name, strlen(name));
5082 }
5083 }
5084
5085 if (Field **autoinc_col = table->s->found_next_number_field) {
5086 const dd::Properties &p = dd_table->table().se_private_data();
5087 dict_table_autoinc_set_col_pos(m_table, (*autoinc_col)->field_index());
5088 uint64_t version, autoinc = 0;
5089 if (p.get(dd_table_key_strings[DD_TABLE_VERSION], &version) ||
5090 p.get(dd_table_key_strings[DD_TABLE_AUTOINC], &autoinc)) {
5091 ut_ad(!"problem setting AUTO_INCREMENT");
5092 return nullptr;
5093 }
5094
5095 m_table->version = version;
5096 dict_table_autoinc_lock(m_table);
5097 dict_table_autoinc_initialize(m_table, autoinc + 1);
5098 dict_table_autoinc_unlock(m_table);
5099 m_table->autoinc_persisted = autoinc;
5100 }
5101
5102 mem_heap_t *heap = mem_heap_create(100, UT_LOCATION_HERE);
5103 bool fail = false;
5104
5105 /* Now fill the space ID and Root page number for each index */
5106 dict_index_t *index = m_table->first_index();
5107 for (const auto dd_index : dd_table->indexes()) {
5108 ut_ad(index != nullptr);
5109
5110 const dd::Properties &se_private_data = dd_index->se_private_data();
5111 uint64_t id = 0;
5112 uint32_t root = 0;
5113 uint32_t sid = 0;
5114 uint64_t trx_id = 0;
5115 dd::Object_id index_space_id = dd_index->tablespace_id();
5116
5117 if (dd_table->tablespace_id() == dict_sys_t::s_dd_dict_space_id) {
5118 sid = dict_sys_t::s_dict_space_id;
5119 } else if (dd_table->tablespace_id() == dict_sys_t::s_dd_temp_space_id) {
5120 sid = dict_sys_t::s_temp_space_id;
5121 } else {
5122 std::unique_ptr<dd::Tablespace> index_space;
5123 if (client->acquire_uncached_uncommitted<dd::Tablespace>(index_space_id,
5124 &index_space) ||
5125 index_space == nullptr) {
5126 my_error(ER_TABLESPACE_MISSING, MYF(0), m_table->name.m_name);
5127 fail = true;
5128 break;
5129 }
5130
5131 if (index_space->se_private_data().get(dd_space_key_strings[DD_SPACE_ID],
5132 &sid)) {
5133 fail = true;
5134 break;
5135 }
5136 }
5137
5138 if (first_index) {
5139 ut_ad(m_table->space == 0);
5140 m_table->space = sid;
5141 ut_ad(dd_table->tablespace_id() == dd::INVALID_OBJECT_ID ||
5142 dd_table->tablespace_id() == index_space_id);
5143 m_table->dd_space_id = index_space_id;
5144
5145 uint32_t dd_fsp_flags;
5146 if (dd_table->tablespace_id() == dict_sys_t::s_dd_dict_space_id) {
5147 dd_fsp_flags = dict_tf_to_fsp_flags(m_table->flags);
5148 } else {
5149 ut_ad(dd_space != nullptr);
5150 dd_space->se_private_data().get(dd_space_key_strings[DD_SPACE_FLAGS],
5151 &dd_fsp_flags);
5152 }
5153
5154 /* Make sure the data_dir_path is set in the dict_table_t. */
5155 dd_get_and_save_data_dir_path(m_table, dd_table, false);
5156
5157 dict_sys_mutex_enter();
5158 dd_load_tablespace(dd_table, m_table, heap, DICT_ERR_IGNORE_RECOVER_LOCK,
5159 dd_fsp_flags);
5160
5161 DEBUG_SYNC_C("innodb_dd_load_tablespace_done");
5162
5163 if (dd_space && m_table->space != TRX_SYS_SPACE &&
5164 fil_space_get(m_table->space) != nullptr) {
5165 /* Get the autoextend_size property from the tablespace
5166 and set the fil_space_t::autoextend_size attribute. */
5167 const dd::Properties &o = dd_space->options();
5168 uint64_t autoextend_size{};
5169
5170 if (o.exists(autoextend_size_str)) {
5171 o.get(autoextend_size_str, &autoextend_size);
5172 }
5173
5174 ut_d(dberr_t ret =)
5175 fil_set_autoextend_size(m_table->space, autoextend_size);
5176 ut_ad(ret == DB_SUCCESS);
5177 }
5178
5179 dict_sys_mutex_exit();
5180 first_index = false;
5181 }
5182
5183 if (se_private_data.get(dd_index_key_strings[DD_INDEX_ID], &id) ||
5184 se_private_data.get(dd_index_key_strings[DD_INDEX_ROOT], &root) ||
5185 se_private_data.get(dd_index_key_strings[DD_INDEX_TRX_ID], &trx_id)) {
5186 fail = true;
5187 break;
5188 }
5189
5190 ut_ad(root > 1);
5191 ut_ad(index->type & DICT_FTS || root != FIL_NULL ||
5192 dict_table_is_discarded(m_table));
5193 ut_ad(id != 0);
5194 index->page = root;
5195 index->space = sid;
5196 index->id = id;
5197 index->trx_id = trx_id;
5198
5199 /** Look up the spatial reference system in the
5200 dictionary. Since this may cause a table open to read the
5201 dictionary tables, it must be done while not holding
5202 &dict_sys->mutex. */
5203 if (dict_index_is_spatial(index))
5204 index->rtr_srs.reset(fetch_srs(index->srid));
5205
5206 index = index->next();
5207 }
5208
5209 if (!implicit) {
5210 dd_get_and_save_space_name(m_table, dd_table, false);
5211 }
5212
5213 dict_sys_mutex_enter();
5214
5215 if (fail) {
5216 for (dict_index_t *index = UT_LIST_GET_LAST(m_table->indexes);
5217 index != nullptr; index = UT_LIST_GET_LAST(m_table->indexes)) {
5218 dict_index_remove_from_cache(m_table, index);
5219 }
5220 dict_mem_table_free(m_table);
5221 dict_sys_mutex_exit();
5222 mem_heap_free(heap);
5223
5224 return nullptr;
5225 }
5226
5227 /* Re-check if the table has been opened/added by a concurrent
5228 thread */
5229 dict_table_t *exist = dict_table_check_if_in_cache_low(norm_name);
5230 if (exist != nullptr) {
5231 for (dict_index_t *index = UT_LIST_GET_LAST(m_table->indexes);
5232 index != nullptr; index = UT_LIST_GET_LAST(m_table->indexes)) {
5233 dict_index_remove_from_cache(m_table, index);
5234 }
5235 dict_mem_table_free(m_table);
5236
5237 m_table = exist;
5238 } else {
5239 dict_table_add_to_cache(m_table, true);
5240
5241 validate_index_len(m_table, table);
5242
5243 if (m_table->fts && dict_table_has_fts_index(m_table)) {
5244 fts_optimize_add_table(m_table);
5245 }
5246
5247 if (dict_sys->dynamic_metadata != nullptr) {
5248 dict_table_load_dynamic_metadata(m_table);
5249 }
5250 }
5251
5252 m_table->acquire();
5253
5254 dict_sys_mutex_exit();
5255
5256 /* Check if this is a DD system table */
5257 if (m_table != nullptr) {
5258 std::string db_str;
5259 std::string tbl_str;
5260 dict_name::get_table(m_table->name.m_name, db_str, tbl_str);
5261
5262 m_table->is_dd_table =
5263 dd::get_dictionary()->is_dd_table_name(db_str.c_str(), tbl_str.c_str());
5264 }
5265
5266 /* Load foreign key info. It could also register child table(s) that
5267 refers to current table */
5268 if (exist == nullptr) {
5269 dberr_t error =
5270 dd_table_load_fk(client, norm_name, nullptr, m_table,
5271 &dd_table->table(), thd, false, true, &fk_list);
5272 if (error != DB_SUCCESS) {
5273 dict_table_close(m_table, false, false);
5274 m_table = nullptr;
5275 }
5276 }
5277 mem_heap_free(heap);
5278
5279 return m_table;
5280 }
5281
5282 /** Open single table with name
5283 @param[in] name table name
5284 @param[in] dict_locked dict_sys mutex is held or not
5285 @param[in,out] fk_list foreign key name list
5286 @param[in] thd thread THD */
5287 static void dd_open_table_one_on_name(const char *name, bool dict_locked,
5288 dict_names_t &fk_list, THD *thd) {
5289 dict_table_t *table = nullptr;
5290 const dd::Table *dd_table = nullptr;
5291 MDL_ticket *mdl = nullptr;
5292
5293 if (!dict_locked) {
5294 dict_sys_mutex_enter();
5295 }
5296
5297 table = dict_table_check_if_in_cache_low(name);
5298
5299 if (table != nullptr) {
5300 /* If the table is in cached already, do nothing. */
5301 if (!dict_locked) {
5302 dict_sys_mutex_exit();
5303 }
5304
5305 return;
5306 } else {
5307 /* Otherwise, open it by dd obj. */
5308
5309 /* Exit sys mutex to access server info */
5310 dict_sys_mutex_exit();
5311
5312 std::string db_str;
5313 std::string tbl_str;
5314 dict_name::get_table(name, db_str, tbl_str);
5315
5316 if (db_str.empty() || tbl_str.empty() ||
5317 dd_mdl_acquire(thd, &mdl, db_str.c_str(), tbl_str.c_str())) {
5318 goto func_exit;
5319 }
5320
5321 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
5322 dd::cache::Dictionary_client::Auto_releaser releaser(client);
5323
5324 if (client->acquire(db_str.c_str(), tbl_str.c_str(), &dd_table) ||
5325 dd_table == nullptr) {
5326 goto func_exit;
5327 }
5328
5329 ut_ad(dd_table->se_private_id() != dd::INVALID_OBJECT_ID);
5330
5331 TABLE_SHARE ts;
5332
5333 init_tmp_table_share(thd, &ts, db_str.c_str(), db_str.length(),
5334 dd_table->name().c_str(), "" /* file name */, nullptr);
5335
5336 ulint error =
5337 open_table_def_suppress_invalid_meta_data(thd, &ts, *dd_table);
5338
5339 if (error != 0) {
5340 goto func_exit;
5341 }
5342
5343 TABLE td;
5344
5345 error = open_table_from_share(thd, &ts, dd_table->name().c_str(), 0,
5346 SKIP_NEW_HANDLER, 0, &td, false, dd_table);
5347
5348 if (error != 0) {
5349 free_table_share(&ts);
5350 goto func_exit;
5351 }
5352
5353 table = dd_open_table_one(client, &td, name, dd_table, thd, fk_list);
5354
5355 closefrm(&td, false);
5356 free_table_share(&ts);
5357 }
5358
5359 func_exit:
5360 if (table != nullptr) {
5361 dd_table_close(table, thd, &mdl, false);
5362 } else {
5363 dd_mdl_release(thd, &mdl);
5364 }
5365
5366 if (dict_locked) {
5367 dict_sys_mutex_enter();
5368 }
5369 }
5370
5371 /** Open foreign tables reference a table.
5372 @param[in] fk_list foreign key name list
5373 @param[in] dict_locked dict_sys mutex is locked or not
5374 @param[in] thd thread THD */
5375 void dd_open_fk_tables(dict_names_t &fk_list, bool dict_locked, THD *thd) {
5376 while (!fk_list.empty()) {
5377 char *name = const_cast<char *>(fk_list.front());
5378
5379 if (innobase_get_lower_case_table_names() == 2) {
5380 innobase_casedn_str(name);
5381 } else {
5382 #ifndef _WIN32
5383 if (innobase_get_lower_case_table_names() == 1) {
5384 innobase_casedn_str(name);
5385 }
5386 #endif /* !_WIN32 */
5387 }
5388
5389 dd_open_table_one_on_name(name, dict_locked, fk_list, thd);
5390
5391 fk_list.pop_front();
5392 }
5393 }
5394
5395 /** Open or load a table definition based on a Global DD object.
5396 @tparam Table dd::Table or dd::Partition
5397 @param[in,out] client data dictionary client
5398 @param[in] table MySQL table definition
5399 @param[in] norm_name Table Name
5400 @param[in] dd_table Global DD table or partition object
5401 @param[in] thd thread THD
5402 @return ptr to dict_table_t filled, otherwise, nullptr */
5403 template <typename Table>
5404 dict_table_t *dd_open_table(dd::cache::Dictionary_client *client,
5405 const TABLE *table, const char *norm_name,
5406 const Table *dd_table, THD *thd) {
5407 dict_table_t *m_table = nullptr;
5408 dict_names_t fk_list;
5409
5410 m_table = dd_open_table_one(client, table, norm_name, dd_table, thd, fk_list);
5411
5412 /* If there is foreign table references to this table, we will
5413 try to open them */
5414 if (m_table != nullptr && !fk_list.empty()) {
5415 dd_open_fk_tables(fk_list, false, thd);
5416 }
5417
5418 return m_table;
5419 }
5420
5421 template dict_table_t *dd_open_table<dd::Table>(dd::cache::Dictionary_client *,
5422 const TABLE *, const char *,
5423 const dd::Table *, THD *);
5424
5425 template dict_table_t *dd_open_table<dd::Partition>(
5426 dd::cache::Dictionary_client *, const TABLE *, const char *,
5427 const dd::Partition *, THD *);
5428
5429 /** Get next record from a new dd system table, like mysql.tables...
5430 @param[in,out] pcur Persistent cursor
5431 @param[in] mtr Mini-transaction
5432 @return the next rec of the dd system table */
5433 static const rec_t *dd_getnext_system_low(btr_pcur_t *pcur, mtr_t *mtr) {
5434 rec_t *rec = nullptr;
5435 bool is_comp = dict_table_is_comp(pcur->index()->table);
5436
5437 while (!rec || rec_get_deleted_flag(rec, is_comp)) {
5438 pcur->move_to_next_user_rec(mtr);
5439
5440 rec = pcur->get_rec();
5441
5442 if (!pcur->is_on_user_rec()) {
5443 /* end of index */
5444 pcur->close();
5445
5446 return nullptr;
5447 }
5448 }
5449
5450 /* Get a record, let's save the position */
5451 pcur->store_position(mtr);
5452
5453 return rec;
5454 }
5455
5456 /** Get next record of new DD system tables
5457 @param[in,out] pcur Persistent cursor
5458 @param[in] mtr Mini-transaction
5459 @retval next record */
5460 const rec_t *dd_getnext_system_rec(btr_pcur_t *pcur, mtr_t *mtr) {
5461 /* Restore the position */
5462 pcur->restore_position(BTR_SEARCH_LEAF, mtr, UT_LOCATION_HERE);
5463
5464 return dd_getnext_system_low(pcur, mtr);
5465 }
5466
5467 /** Scan a new dd system table, like mysql.tables...
5468 @param[in] thd THD
5469 @param[in,out] mdl MDL lock
5470 @param[in,out] pcur Persistent cursor
5471 @param[in,out] mtr Mini-transaction
5472 @param[in] system_table_name Which dd system table to open
5473 @param[in,out] table dict_table_t obj of dd system table
5474 @retval the first rec of the dd system table */
5475 const rec_t *dd_startscan_system(THD *thd, MDL_ticket **mdl, btr_pcur_t *pcur,
5476 mtr_t *mtr, const char *system_table_name,
5477 dict_table_t **table) {
5478 dict_index_t *clust_index;
5479 const rec_t *rec = nullptr;
5480
5481 *table = dd_table_open_on_name(thd, mdl, system_table_name, true, false);
5482 mtr_commit(mtr);
5483
5484 clust_index = UT_LIST_GET_FIRST((*table)->indexes);
5485
5486 mtr_start(mtr);
5487 pcur->open_at_side(true, clust_index, BTR_SEARCH_LEAF, true, 0, mtr);
5488
5489 rec = dd_getnext_system_low(pcur, mtr);
5490
5491 return rec;
5492 }
5493
5494 /**
5495 All DD tables would contain DB_TRX_ID and DB_ROLL_PTR fields
5496 before other fields. This offset indicates the position at
5497 which the first DD column is located.
5498 */
5499 static const int DD_FIELD_OFFSET = 2;
5500
5501 /** Process one mysql.tables record and get the dict_table_t
5502 @param[in] heap Temp memory heap
5503 @param[in,out] rec mysql.tables record
5504 @param[in,out] table dict_table_t to fill
5505 @param[in] dd_tables dict_table_t obj of dd system table
5506 @param[in] mdl MDL on the table
5507 @param[in] mtr Mini-transaction
5508 @retval error message, or NULL on success */
5509 const char *dd_process_dd_tables_rec_and_mtr_commit(
5510 mem_heap_t *heap, const rec_t *rec, dict_table_t **table,
5511 dict_table_t *dd_tables, MDL_ticket **mdl, mtr_t *mtr) {
5512 ulint len;
5513 const byte *field;
5514 const char *err_msg = nullptr;
5515 ulint table_id;
5516
5517 ut_ad(!rec_get_deleted_flag(rec, dict_table_is_comp(dd_tables)));
5518 ut_ad(mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_S_FIX));
5519
5520 ulint *offsets = rec_get_offsets(rec, dd_tables->first_index(), nullptr,
5521 ULINT_UNDEFINED, UT_LOCATION_HERE, &heap);
5522
5523 const dd::Object_table &dd_object_table = dd::get_dd_table<dd::Table>();
5524
5525 field = rec_get_nth_field(
5526 nullptr, rec, offsets,
5527 dd_object_table.field_number("FIELD_ENGINE") + DD_FIELD_OFFSET, &len);
5528
5529 /* If "engine" field is not "innodb", return. */
5530 if (strncmp((const char *)field, "InnoDB", 6) != 0) {
5531 *table = nullptr;
5532 mtr_commit(mtr);
5533 return err_msg;
5534 }
5535
5536 /* Get the se_private_id field. */
5537 field = rec_get_nth_field(
5538 nullptr, rec, offsets,
5539 dd_object_table.field_number("FIELD_SE_PRIVATE_ID") + DD_FIELD_OFFSET,
5540 &len);
5541
5542 if (len != 8) {
5543 *table = nullptr;
5544 mtr_commit(mtr);
5545 return err_msg;
5546 }
5547
5548 /* Get the table id */
5549 table_id = mach_read_from_8(field);
5550
5551 /* Skip mysql.* tables. */
5552 if (dict_sys_t::is_dd_table_id(table_id)) {
5553 *table = nullptr;
5554 mtr_commit(mtr);
5555 return err_msg;
5556 }
5557
5558 /* Commit before load the table again */
5559 mtr_commit(mtr);
5560 THD *thd = current_thd;
5561
5562 *table = dd_table_open_on_id(table_id, thd, mdl, true, false);
5563
5564 if (!(*table)) {
5565 err_msg = "Table not found";
5566 }
5567
5568 return err_msg;
5569 }
5570
5571 /** Process one mysql.table_partitions record and get the dict_table_t
5572 @param[in] heap Temp memory heap
5573 @param[in,out] rec mysql.table_partitions record
5574 @param[in,out] table dict_table_t to fill
5575 @param[in] dd_tables dict_table_t obj of dd partition table
5576 @param[in] mdl MDL on the table
5577 @param[in] mtr Mini-transaction
5578 @retval error message, or NULL on success */
5579 const char *dd_process_dd_partitions_rec_and_mtr_commit(
5580 mem_heap_t *heap, const rec_t *rec, dict_table_t **table,
5581 dict_table_t *dd_tables, MDL_ticket **mdl, mtr_t *mtr) {
5582 ulint len;
5583 const byte *field;
5584 const char *err_msg = nullptr;
5585 ulint table_id;
5586
5587 ut_ad(mtr_memo_contains_page(mtr, rec, MTR_MEMO_PAGE_S_FIX));
5588
5589 ut_ad(!rec_get_deleted_flag(rec, dict_table_is_comp(dd_tables)));
5590
5591 ulint *offsets = rec_get_offsets(rec, dd_tables->first_index(), nullptr,
5592 ULINT_UNDEFINED, UT_LOCATION_HERE, &heap);
5593
5594 const dd::Object_table &dd_object_table = dd::get_dd_table<dd::Partition>();
5595
5596 /* Get the engine field. */
5597 field = rec_get_nth_field(
5598 nullptr, rec, offsets,
5599 dd_object_table.field_number("FIELD_ENGINE") + DD_FIELD_OFFSET, &len);
5600
5601 /* If "engine" field is not "innodb", return. */
5602 if (strncmp((const char *)field, "InnoDB", 6) != 0) {
5603 *table = nullptr;
5604 mtr_commit(mtr);
5605 return err_msg;
5606 }
5607
5608 /* Get the se_private_id field. */
5609 field = rec_get_nth_field(
5610 nullptr, rec, offsets,
5611 dd_object_table.field_number("FIELD_SE_PRIVATE_ID") + DD_FIELD_OFFSET,
5612 &len);
5613
5614 /* When table is partitioned table, the se_private_id is null. */
5615 if (len != 8) {
5616 *table = nullptr;
5617 mtr_commit(mtr);
5618 return err_msg;
5619 }
5620
5621 /* Get the table id */
5622 table_id = mach_read_from_8(field);
5623
5624 /* Skip mysql.* tables. */
5625 if (dict_sys_t::is_dd_table_id(table_id)) {
5626 *table = nullptr;
5627 mtr_commit(mtr);
5628 return err_msg;
5629 }
5630
5631 /* Commit before load the table again */
5632 mtr_commit(mtr);
5633 THD *thd = current_thd;
5634
5635 *table = dd_table_open_on_id(table_id, thd, mdl, true, false);
5636
5637 if (!(*table)) {
5638 err_msg = "Table not found";
5639 }
5640
5641 return err_msg;
5642 }
5643
5644 /** Process one mysql.columns record and get info to dict_col_t
5645 @param[in,out] heap Temp memory heap
5646 @param[in] rec mysql.columns record
5647 @param[in,out] col dict_col_t to fill
5648 @param[in,out] table_id Table id
5649 @param[in,out] col_name Column name
5650 @param[in,out] nth_v_col Nth v column
5651 @param[in] dd_columns dict_table_t obj of mysql.columns
5652 @param[in,out] mtr Mini-transaction
5653 @retval true if column is filled */
5654 bool dd_process_dd_columns_rec(mem_heap_t *heap, const rec_t *rec,
5655 dict_col_t *col, table_id_t *table_id,
5656 char **col_name, ulint *nth_v_col,
5657 const dict_table_t *dd_columns, mtr_t *mtr) {
5658 ulint len;
5659 const byte *field;
5660 dict_col_t *t_col;
5661 ulint pos;
5662 ulint v_pos = 0;
5663 dd::Column::enum_hidden_type hidden;
5664 bool is_virtual;
5665 dict_v_col_t *vcol = nullptr;
5666
5667 ut_ad(!rec_get_deleted_flag(rec, dict_table_is_comp(dd_columns)));
5668
5669 ulint *offsets = rec_get_offsets(rec, dd_columns->first_index(), nullptr,
5670 ULINT_UNDEFINED, UT_LOCATION_HERE, &heap);
5671
5672 const dd::Object_table &dd_object_table = dd::get_dd_table<dd::Column>();
5673
5674 /* Get the hidden attribute, and skip if it's a hidden column. */
5675 field = rec_get_nth_field(
5676 nullptr, rec, offsets,
5677 dd_object_table.field_number("FIELD_HIDDEN") + DD_FIELD_OFFSET, &len);
5678 hidden = static_cast<dd::Column::enum_hidden_type>(mach_read_from_1(field));
5679 if (hidden == dd::Column::enum_hidden_type::HT_HIDDEN_SE ||
5680 hidden == dd::Column::enum_hidden_type::HT_HIDDEN_SQL) {
5681 mtr_commit(mtr);
5682 return false;
5683 }
5684
5685 /* Get the column name. */
5686 field = rec_get_nth_field(
5687 nullptr, rec, offsets,
5688 dd_object_table.field_number("FIELD_NAME") + DD_FIELD_OFFSET, &len);
5689 *col_name = mem_heap_strdupl(heap, (const char *)field, len);
5690
5691 /* Get the position. */
5692 field = rec_get_nth_field(
5693 nullptr, rec, offsets,
5694 dd_object_table.field_number("FIELD_ORDINAL_POSITION") + DD_FIELD_OFFSET,
5695 &len);
5696 pos = mach_read_from_4(field) - 1;
5697
5698 /* Get the is_virtual attribute. */
5699 field = rec_get_nth_field(nullptr, rec, offsets, 21, &len);
5700 is_virtual = mach_read_from_1(field) & 0x01;
5701
5702 /* Get the se_private_data field. */
5703 field = rec_get_nth_field(
5704 nullptr, rec, offsets,
5705 dd_object_table.field_number("FIELD_SE_PRIVATE_DATA") + DD_FIELD_OFFSET,
5706 &len);
5707
5708 if (len == 0 || len == UNIV_SQL_NULL) {
5709 mtr_commit(mtr);
5710 return false;
5711 }
5712
5713 char *p_ptr = (char *)mem_heap_strdupl(heap, (const char *)field, len);
5714 dd::String_type prop((char *)p_ptr);
5715 dd::Properties *p = dd::Properties::parse_properties(prop);
5716
5717 /* Load the table and get the col. */
5718 if (!p || !p->exists(dd_index_key_strings[DD_TABLE_ID])) {
5719 if (p) {
5720 delete p;
5721 }
5722 mtr_commit(mtr);
5723 return false;
5724 }
5725
5726 if (!p->get(dd_index_key_strings[DD_TABLE_ID], (uint64_t *)table_id)) {
5727 THD *thd = current_thd;
5728 dict_table_t *table;
5729 MDL_ticket *mdl = nullptr;
5730
5731 /* Commit before we try to load the table. */
5732 mtr_commit(mtr);
5733 table = dd_table_open_on_id(*table_id, thd, &mdl, true, true);
5734
5735 if (!table) {
5736 delete p;
5737 return false;
5738 }
5739
5740 if (is_virtual) {
5741 vcol = dict_table_get_nth_v_col_mysql(table, pos);
5742
5743 if (vcol == nullptr) {
5744 dd_table_close(table, thd, &mdl, true);
5745 delete p;
5746 return false;
5747 }
5748
5749 /* Copy info. */
5750 col->ind = vcol->m_col.ind;
5751 col->mtype = vcol->m_col.mtype;
5752 col->prtype = vcol->m_col.prtype;
5753 col->len = vcol->m_col.len;
5754
5755 v_pos = dict_create_v_col_pos(vcol->v_pos, vcol->m_col.ind);
5756 } else {
5757 if (table->n_v_cols == 0) {
5758 t_col = table->get_col(pos);
5759 } else {
5760 ulint col_nr;
5761
5762 col_nr = dict_table_has_column(table, *col_name, pos);
5763 t_col = table->get_col(col_nr);
5764 ut_ad(t_col);
5765 }
5766
5767 /* Copy info. */
5768 col->ind = t_col->ind;
5769 col->mtype = t_col->mtype;
5770 col->prtype = t_col->prtype;
5771 col->len = t_col->len;
5772 }
5773
5774 if (p->exists(dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL]) ||
5775 p->exists(dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT])) {
5776 dd_parse_default_value(*p, col, heap);
5777 }
5778
5779 dd_table_close(table, thd, &mdl, true);
5780 delete p;
5781 } else {
5782 delete p;
5783 mtr_commit(mtr);
5784 return false;
5785 }
5786
5787 /* Report the virtual column number */
5788 if (col->prtype & DATA_VIRTUAL) {
5789 ut_ad(vcol != nullptr);
5790 ut_ad(v_pos != 0);
5791 ut_ad(is_virtual);
5792
5793 *nth_v_col = dict_get_v_col_pos(v_pos);
5794 } else {
5795 *nth_v_col = ULINT_UNDEFINED;
5796 }
5797
5798 return true;
5799 }
5800
5801 /** Process one mysql.columns record for virtual columns
5802 @param[in] heap temp memory heap
5803 @param[in,out] rec mysql.columns record
5804 @param[in,out] table_id Table id
5805 @param[in,out] pos Position
5806 @param[in,out] base_pos Base column position
5807 @param[in,out] n_row Number of rows
5808 @param[in] dd_columns dict_table_t obj of mysql.columns
5809 @param[in] mtr Mini-transaction
5810 @retval true if virtual info is filled */
5811 bool dd_process_dd_virtual_columns_rec(mem_heap_t *heap, const rec_t *rec,
5812 table_id_t *table_id, ulint **pos,
5813 ulint **base_pos, ulint *n_row,
5814 dict_table_t *dd_columns, mtr_t *mtr) {
5815 ulint len;
5816 const byte *field;
5817 ulint origin_pos;
5818 dd::Column::enum_hidden_type hidden;
5819 bool is_virtual;
5820
5821 ut_ad(!rec_get_deleted_flag(rec, dict_table_is_comp(dd_columns)));
5822
5823 ulint *offsets = rec_get_offsets(rec, dd_columns->first_index(), nullptr,
5824 ULINT_UNDEFINED, UT_LOCATION_HERE, &heap);
5825
5826 const dd::Object_table &dd_object_table = dd::get_dd_table<dd::Column>();
5827
5828 /* Get the is_virtual attribute, and skip if it's not a virtual column. */
5829 field = rec_get_nth_field(
5830 nullptr, rec, offsets,
5831 dd_object_table.field_number("FIELD_IS_VIRTUAL") + DD_FIELD_OFFSET, &len);
5832 is_virtual = mach_read_from_1(field) & 0x01;
5833 if (!is_virtual) {
5834 mtr_commit(mtr);
5835 return false;
5836 }
5837
5838 /* Get the hidden attribute, and skip if it's a hidden column. */
5839 field = rec_get_nth_field(
5840 nullptr, rec, offsets,
5841 dd_object_table.field_number("FIELD_HIDDEN") + DD_FIELD_OFFSET, &len);
5842 hidden = static_cast<dd::Column::enum_hidden_type>(mach_read_from_1(field));
5843 if (hidden == dd::Column::enum_hidden_type::HT_HIDDEN_SE) {
5844 mtr_commit(mtr);
5845 return false;
5846 }
5847
5848 /* Get the position. */
5849 field = rec_get_nth_field(
5850 nullptr, rec, offsets,
5851 dd_object_table.field_number("FIELD_ORDINAL_POSITION") + DD_FIELD_OFFSET,
5852 &len);
5853 origin_pos = mach_read_from_4(field) - 1;
5854
5855 /* Get the se_private_data field. */
5856 field = rec_get_nth_field(
5857 nullptr, rec, offsets,
5858 dd_object_table.field_number("FIELD_SE_PRIVATE_DATA") + DD_FIELD_OFFSET,
5859 &len);
5860
5861 if (len == 0 || len == UNIV_SQL_NULL) {
5862 mtr_commit(mtr);
5863 return false;
5864 }
5865
5866 char *p_ptr = (char *)mem_heap_strdupl(heap, (const char *)field, len);
5867 dd::String_type prop((char *)p_ptr);
5868 dd::Properties *p = dd::Properties::parse_properties(prop);
5869
5870 /* Load the table and get the col. */
5871 if (!p || !p->exists(dd_index_key_strings[DD_TABLE_ID])) {
5872 if (p) {
5873 delete p;
5874 }
5875 mtr_commit(mtr);
5876 return false;
5877 }
5878
5879 if (!p->get(dd_index_key_strings[DD_TABLE_ID], (uint64_t *)table_id)) {
5880 THD *thd = current_thd;
5881 dict_table_t *table;
5882 MDL_ticket *mdl = nullptr;
5883 dict_v_col_t *vcol = nullptr;
5884
5885 /* Commit before we try to load the table. */
5886 mtr_commit(mtr);
5887 table = dd_table_open_on_id(*table_id, thd, &mdl, true, true);
5888
5889 if (!table) {
5890 delete p;
5891 return false;
5892 }
5893
5894 vcol = dict_table_get_nth_v_col_mysql(table, origin_pos);
5895
5896 if (vcol == nullptr || vcol->num_base == 0) {
5897 dd_table_close(table, thd, &mdl, true);
5898 delete p;
5899 return false;
5900 }
5901
5902 *pos = static_cast<ulint *>(
5903 mem_heap_alloc(heap, vcol->num_base * sizeof(ulint)));
5904 *base_pos = static_cast<ulint *>(
5905 mem_heap_alloc(heap, vcol->num_base * sizeof(ulint)));
5906 *n_row = vcol->num_base;
5907 for (ulint i = 0; i < *n_row; i++) {
5908 (*pos)[i] = dict_create_v_col_pos(vcol->v_pos, vcol->m_col.ind);
5909 (*base_pos)[i] = vcol->base_col[i]->ind;
5910 }
5911
5912 dd_table_close(table, thd, &mdl, true);
5913 delete p;
5914 } else {
5915 delete p;
5916 mtr_commit(mtr);
5917 return false;
5918 }
5919
5920 return true;
5921 }
5922
5923 /** Process one mysql.indexes record and get the dict_index_t
5924 @param[in] heap Temp memory heap
5925 @param[in,out] rec mysql.indexes record
5926 @param[in,out] index dict_index_t to fill
5927 @param[in] mdl MDL on index->table
5928 @param[in,out] parent Parent table if it's fts aux table.
5929 @param[in,out] parent_mdl MDL on parent if it's fts aux table.
5930 @param[in] dd_indexes dict_table_t obj of mysql.indexes
5931 @param[in] mtr Mini-transaction
5932 @retval true if index is filled */
5933 bool dd_process_dd_indexes_rec(mem_heap_t *heap, const rec_t *rec,
5934 const dict_index_t **index, MDL_ticket **mdl,
5935 dict_table_t **parent, MDL_ticket **parent_mdl,
5936 dict_table_t *dd_indexes, mtr_t *mtr) {
5937 ulint len;
5938 const byte *field;
5939 uint32_t index_id;
5940 uint32_t space_id;
5941 uint64_t table_id;
5942
5943 *index = nullptr;
5944
5945 ut_ad(!rec_get_deleted_flag(rec, dict_table_is_comp(dd_indexes)));
5946
5947 ulint *offsets = rec_get_offsets(rec, dd_indexes->first_index(), nullptr,
5948 ULINT_UNDEFINED, UT_LOCATION_HERE, &heap);
5949
5950 const dd::Object_table &dd_object_table = dd::get_dd_table<dd::Index>();
5951
5952 field = rec_get_nth_field(
5953 nullptr, rec, offsets,
5954 dd_object_table.field_number("FIELD_ENGINE") + DD_FIELD_OFFSET, &len);
5955
5956 /* If "engine" field is not "innodb", return. */
5957 if (strncmp((const char *)field, "InnoDB", 6) != 0) {
5958 mtr_commit(mtr);
5959 return false;
5960 }
5961
5962 /* Get the se_private_data field. */
5963 field = rec_get_nth_field(
5964 nullptr, rec, offsets,
5965 dd_object_table.field_number("FIELD_SE_PRIVATE_DATA") + DD_FIELD_OFFSET,
5966 &len);
5967
5968 if (len == 0 || len == UNIV_SQL_NULL) {
5969 mtr_commit(mtr);
5970 return false;
5971 }
5972
5973 /* Get index id. */
5974 dd::String_type prop((char *)field);
5975 dd::Properties *p = dd::Properties::parse_properties(prop);
5976
5977 if (!p || !p->exists(dd_index_key_strings[DD_INDEX_ID]) ||
5978 !p->exists(dd_index_key_strings[DD_INDEX_SPACE_ID])) {
5979 if (p) {
5980 delete p;
5981 }
5982 mtr_commit(mtr);
5983 return false;
5984 }
5985
5986 if (p->get(dd_index_key_strings[DD_INDEX_ID], &index_id)) {
5987 delete p;
5988 mtr_commit(mtr);
5989 return false;
5990 }
5991
5992 /* Get the tablespace id. */
5993 if (p->get(dd_index_key_strings[DD_INDEX_SPACE_ID], &space_id)) {
5994 delete p;
5995 mtr_commit(mtr);
5996 return false;
5997 }
5998
5999 /* Skip mysql.* indexes. */
6000 if (space_id == dict_sys->s_dict_space_id) {
6001 delete p;
6002 mtr_commit(mtr);
6003 return false;
6004 }
6005
6006 /* Load the table and get the index. */
6007 if (!p->exists(dd_index_key_strings[DD_TABLE_ID])) {
6008 delete p;
6009 mtr_commit(mtr);
6010 return false;
6011 }
6012
6013 if (!p->get(dd_index_key_strings[DD_TABLE_ID], &table_id)) {
6014 THD *thd = current_thd;
6015 dict_table_t *table;
6016
6017 /* Commit before load the table */
6018 mtr_commit(mtr);
6019 table = dd_table_open_on_id(table_id, thd, mdl, true, true);
6020
6021 if (!table) {
6022 delete p;
6023 return false;
6024 }
6025
6026 /* For fts aux table, we need to acquire mdl lock on parent. */
6027 if (table->is_fts_aux()) {
6028 fts_aux_table_t fts_table;
6029
6030 /* Find the parent ID. */
6031 ut_d(bool is_fts =) fts_is_aux_table_name(&fts_table, table->name.m_name,
6032 strlen(table->name.m_name));
6033 ut_ad(is_fts);
6034
6035 table_id_t parent_id = fts_table.parent_id;
6036
6037 dd_table_close(table, thd, mdl, true);
6038
6039 *parent = dd_table_open_on_id(parent_id, thd, parent_mdl, true, true);
6040
6041 if (*parent == nullptr) {
6042 delete p;
6043 return false;
6044 }
6045
6046 table = dd_table_open_on_id(table_id, thd, mdl, true, true);
6047
6048 if (!table) {
6049 dd_table_close(*parent, thd, parent_mdl, true);
6050 delete p;
6051 return false;
6052 }
6053 }
6054
6055 for (const dict_index_t *t_index = table->first_index(); t_index != nullptr;
6056 t_index = t_index->next()) {
6057 if (t_index->space == space_id && t_index->id == index_id) {
6058 *index = t_index;
6059 }
6060 }
6061
6062 if (*index == nullptr) {
6063 dd_table_close(table, thd, mdl, true);
6064 if (table->is_fts_aux() && *parent) {
6065 dd_table_close(*parent, thd, parent_mdl, true);
6066 }
6067 delete p;
6068 return false;
6069 }
6070
6071 delete p;
6072 } else {
6073 delete p;
6074 mtr_commit(mtr);
6075 return false;
6076 }
6077
6078 return true;
6079 }
6080
6081 /** Process one mysql.indexes record and get brief info to dict_index_t
6082 @param[in] heap temp memory heap
6083 @param[in,out] rec mysql.indexes record
6084 @param[in,out] index_id index id
6085 @param[in,out] space_id space id
6086 @param[in] dd_indexes dict_table_t obj of mysql.indexes
6087 @retval true if index is filled */
6088 bool dd_process_dd_indexes_rec_simple(mem_heap_t *heap, const rec_t *rec,
6089 space_index_t *index_id,
6090 space_id_t *space_id,
6091 dict_table_t *dd_indexes) {
6092 ulint len;
6093 const byte *field;
6094 uint32_t idx_id;
6095
6096 ut_ad(!rec_get_deleted_flag(rec, dict_table_is_comp(dd_indexes)));
6097
6098 ulint *offsets = rec_get_offsets(rec, dd_indexes->first_index(), nullptr,
6099 ULINT_UNDEFINED, UT_LOCATION_HERE, &heap);
6100
6101 const dd::Object_table &dd_object_table = dd::get_dd_table<dd::Index>();
6102
6103 field = rec_get_nth_field(
6104 nullptr, rec, offsets,
6105 dd_object_table.field_number("FIELD_ENGINE") + DD_FIELD_OFFSET, &len);
6106
6107 /* If "engine" field is not "innodb", return. */
6108 if (strncmp((const char *)field, "InnoDB", 6) != 0) {
6109 return false;
6110 }
6111
6112 /* Get the se_private_data field. */
6113 field = rec_get_nth_field(
6114 nullptr, rec, offsets,
6115 dd_object_table.field_number("FIELD_SE_PRIVATE_DATA") + DD_FIELD_OFFSET,
6116 &len);
6117
6118 if (len == 0 || len == UNIV_SQL_NULL) {
6119 return false;
6120 }
6121
6122 /* Get index id. */
6123 dd::String_type prop((char *)field);
6124 dd::Properties *p = dd::Properties::parse_properties(prop);
6125
6126 if (!p || !p->exists(dd_index_key_strings[DD_INDEX_ID]) ||
6127 !p->exists(dd_index_key_strings[DD_INDEX_SPACE_ID])) {
6128 if (p) {
6129 delete p;
6130 }
6131 return false;
6132 }
6133
6134 if (p->get(dd_index_key_strings[DD_INDEX_ID], &idx_id)) {
6135 delete p;
6136 return false;
6137 }
6138 *index_id = idx_id;
6139
6140 /* Get the tablespace_id. */
6141 if (p->get(dd_index_key_strings[DD_INDEX_SPACE_ID], space_id)) {
6142 delete p;
6143 return false;
6144 }
6145
6146 delete p;
6147
6148 return true;
6149 }
6150
6151 bool dd_process_dd_tablespaces_rec(mem_heap_t *heap, const rec_t *rec,
6152 space_id_t *space_id, char **name,
6153 uint32_t *flags, uint32_t *server_version,
6154 uint32_t *space_version, bool *is_encrypted,
6155 uint64_t *autoextend_size,
6156 dd::String_type *state,
6157 dict_table_t *dd_spaces) {
6158 ulint len;
6159 const byte *field;
6160 char *prop_str;
6161 char *opt_str;
6162
6163 ut_ad(!rec_get_deleted_flag(rec, dict_table_is_comp(dd_spaces)));
6164
6165 ulint *offsets = rec_get_offsets(rec, dd_spaces->first_index(), nullptr,
6166 ULINT_UNDEFINED, UT_LOCATION_HERE, &heap);
6167
6168 const dd::Object_table &dd_object_table = dd::get_dd_table<dd::Tablespace>();
6169
6170 field = rec_get_nth_field(
6171 nullptr, rec, offsets,
6172 dd_object_table.field_number("FIELD_ENGINE") + DD_FIELD_OFFSET, &len);
6173
6174 /* If "engine" field is not "innodb", return. */
6175 if (strncmp((const char *)field, "InnoDB", 6) != 0) {
6176 return false;
6177 }
6178
6179 /* Get name field. */
6180 field = rec_get_nth_field(
6181 nullptr, rec, offsets,
6182 dd_object_table.field_number("FIELD_NAME") + DD_FIELD_OFFSET, &len);
6183 *name = reinterpret_cast<char *>(mem_heap_zalloc(heap, len + 1));
6184 memcpy(*name, field, len);
6185
6186 /* Get the options string. */
6187 field = rec_get_nth_field(
6188 nullptr, rec, offsets,
6189 dd_object_table.field_number("FIELD_OPTIONS") + DD_FIELD_OFFSET, &len);
6190
6191 if (len == 0 || len == UNIV_SQL_NULL) {
6192 return false; /* purecov: inspected */
6193 }
6194
6195 opt_str = static_cast<char *>(mem_heap_zalloc(heap, len + 1));
6196 memcpy(opt_str, field, len);
6197 dd::String_type opt(opt_str);
6198 const dd::Properties *o = dd::Properties::parse_properties(opt);
6199
6200 if (!o) {
6201 return false; /* purecov: inspected */
6202 }
6203
6204 /* Get encrypted. */
6205 *is_encrypted = false;
6206 dd::String_type encrypt;
6207 if (o->exists("encryption") && o->get("encryption", &encrypt)) {
6208 /* purecov: begin inspected */
6209 delete o;
6210 return false;
6211 /* purecov: end */
6212 }
6213
6214 if (!Encryption::is_none(encrypt.c_str())) {
6215 *is_encrypted = true;
6216 }
6217
6218 /* Get autoextend_size. */
6219 *autoextend_size = 0;
6220 if (o->exists(autoextend_size_str) &&
6221 o->get(autoextend_size_str, autoextend_size)) {
6222 /* purecov: begin inspected */
6223 delete o;
6224 return false;
6225 /* purecov: end */
6226 }
6227
6228 delete o;
6229
6230 /* Get the se_private_data field. */
6231 field = rec_get_nth_field(
6232 nullptr, rec, offsets,
6233 dd_object_table.field_number("FIELD_SE_PRIVATE_DATA") + DD_FIELD_OFFSET,
6234 &len);
6235
6236 if (len == 0 || len == UNIV_SQL_NULL) {
6237 return false;
6238 }
6239
6240 prop_str = static_cast<char *>(mem_heap_zalloc(heap, len + 1));
6241 memcpy(prop_str, field, len);
6242 dd::String_type prop(prop_str);
6243 const dd::Properties *p = dd::Properties::parse_properties(prop);
6244
6245 if (!p || !p->exists(dd_space_key_strings[DD_SPACE_ID]) ||
6246 !p->exists(dd_index_key_strings[DD_SPACE_FLAGS])) {
6247 if (p) {
6248 delete p;
6249 }
6250 return false;
6251 }
6252
6253 /* Get space id. */
6254 if (p->get(dd_space_key_strings[DD_SPACE_ID], space_id)) {
6255 delete p;
6256 return false;
6257 }
6258
6259 /* Get space flags. */
6260 if (p->get(dd_space_key_strings[DD_SPACE_FLAGS], flags)) {
6261 delete p;
6262 return false;
6263 }
6264
6265 /* Get server version. */
6266 if (p->get(dd_space_key_strings[DD_SPACE_SERVER_VERSION], server_version)) {
6267 delete p;
6268 return false;
6269 }
6270
6271 /* Get space version. */
6272 if (p->get(dd_space_key_strings[DD_SPACE_VERSION], space_version)) {
6273 delete p;
6274 return false;
6275 }
6276
6277 /* Get tablespace state. */
6278 dd_tablespace_get_state(p, state, *space_id);
6279
6280 /* For UNDO tablespaces, encryption is governed by srv_undo_log_encrypt
6281 variable and DD flags are not updated for encryption changes. Following
6282 is a workaround until UNDO tablespace encryption change is done by a DDL. */
6283 if (fsp_is_undo_tablespace(*space_id)) {
6284 *is_encrypted = srv_undo_log_encrypt;
6285 } else if (FSP_FLAGS_GET_ENCRYPTION(*flags)) {
6286 /* Get Encryption. */
6287 *is_encrypted = true;
6288 }
6289
6290 delete p;
6291
6292 return true;
6293 }
6294
6295 /** Get dd tablespace id for fts table
6296 @param[in] parent_table parent table of fts table
6297 @param[in] table fts table
6298 @param[in,out] dd_space_id dd table space id
6299 @return true on success, false on failure. */
6300 static bool dd_get_or_assign_fts_tablespace_id(const dict_table_t *parent_table,
6301 const dict_table_t *table,
6302 dd::Object_id &dd_space_id) {
6303 THD *thd = current_thd;
6304 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
6305 dd::cache::Dictionary_client::Auto_releaser releaser(client);
6306
6307 dd::Object_id space_id = parent_table->dd_space_id;
6308 ut_ad(space_id != dd::INVALID_OBJECT_ID);
6309
6310 dd_space_id = dd::INVALID_OBJECT_ID;
6311
6312 if (dict_table_is_file_per_table(table)) {
6313 /* This means user table and file_per_table */
6314 bool ret;
6315 char *filename = fil_space_get_first_path(table->space);
6316
6317 ret = dd_create_implicit_tablespace(
6318 client, table->space, table->name.m_name, filename, false, dd_space_id);
6319
6320 ut::free(filename);
6321 if (ret) {
6322 return false;
6323 }
6324
6325 } else if (table->space != TRX_SYS_SPACE &&
6326 table->space != srv_tmp_space.space_id()) {
6327 /* This is a user table that resides in shared tablespace */
6328 ut_ad(!dict_table_is_file_per_table(parent_table));
6329 ut_ad(!dict_table_is_file_per_table(table));
6330 ut_ad(DICT_TF_HAS_SHARED_SPACE(table->flags));
6331
6332 /* Currently the tablespace id is hard coded as 0 */
6333 dd_space_id = space_id;
6334
6335 const dd::Tablespace *index_space = nullptr;
6336 if (client->acquire<dd::Tablespace>(space_id, &index_space)) {
6337 return false;
6338 }
6339
6340 uint32_t id;
6341 if (index_space == nullptr) {
6342 return false;
6343 } else if (index_space->se_private_data().get(
6344 dd_space_key_strings[DD_SPACE_ID], &id) ||
6345 id != table->space) {
6346 ut_ad(!"missing or incorrect tablespace id");
6347 return false;
6348 }
6349 } else if (table->space == TRX_SYS_SPACE) {
6350 /* This is a user table that resides in innodb_system
6351 tablespace */
6352 ut_ad(!dict_table_is_file_per_table(table));
6353 dd_space_id = dict_sys_t::s_dd_sys_space_id;
6354 }
6355
6356 return true;
6357 }
6358
6359 /** Set table options for fts dd tables according to dict table
6360 @param[in,out] dd_table dd table instance
6361 @param[in] table dict table instance */
6362 void dd_set_fts_table_options(dd::Table *dd_table, const dict_table_t *table) {
6363 dd_table->set_engine(innobase_hton_name);
6364 dd_table->set_hidden(dd::Abstract_table::HT_HIDDEN_SE);
6365 dd_table->set_collation_id(my_charset_bin.number);
6366
6367 dd::Table::enum_row_format row_format = dd::Table::RF_DYNAMIC;
6368 switch (dict_tf_get_rec_format(table->flags)) {
6369 case REC_FORMAT_REDUNDANT:
6370 row_format = dd::Table::RF_REDUNDANT;
6371 break;
6372 case REC_FORMAT_COMPACT:
6373 row_format = dd::Table::RF_COMPACT;
6374 break;
6375 case REC_FORMAT_COMPRESSED:
6376 row_format = dd::Table::RF_COMPRESSED;
6377 break;
6378 case REC_FORMAT_DYNAMIC:
6379 row_format = dd::Table::RF_DYNAMIC;
6380 break;
6381 default:
6382 ut_error;
6383 }
6384
6385 dd_table->set_row_format(row_format);
6386
6387 /* FTS AUX tables are always not encrypted/compressed
6388 as it is designed now. So both "compress" and "encrypt_type"
6389 option are not set */
6390
6391 dd::Properties *table_options = &dd_table->options();
6392 table_options->set("pack_record", true);
6393 table_options->set("checksum", false);
6394 table_options->set("delay_key_write", false);
6395 table_options->set("avg_row_length", 0);
6396 table_options->set("stats_sample_pages", 0);
6397 table_options->set("stats_auto_recalc", HA_STATS_AUTO_RECALC_DEFAULT);
6398
6399 if (auto zip_ssize = DICT_TF_GET_ZIP_SSIZE(table->flags)) {
6400 table_options->set("key_block_size", 1 << (zip_ssize - 1));
6401 } else {
6402 table_options->set("key_block_size", 0);
6403 }
6404 }
6405
6406 /** Add nullability info to column se_private_data
6407 @param[in,out] dd_col DD table column
6408 @param[in] col InnoDB table column */
6409 static void dd_set_fts_nullability(dd::Column *dd_col, const dict_col_t *col) {
6410 bool is_nullable = !(col->prtype & DATA_NOT_NULL);
6411 dd::Properties &p = dd_col->se_private_data();
6412 p.set("nullable", is_nullable);
6413 }
6414
6415 /** Create dd table for fts aux index table
6416 @param[in] parent_table parent table of fts table
6417 @param[in,out] table fts table
6418 @param[in] charset fts index charset
6419 @return true on success, false on failure */
6420 bool dd_create_fts_index_table(const dict_table_t *parent_table,
6421 dict_table_t *table,
6422 const CHARSET_INFO *charset) {
6423 ut_ad(charset != nullptr);
6424
6425 std::string db_name;
6426 std::string table_name;
6427 dict_name::get_table(table->name.m_name, db_name, table_name);
6428
6429 /* Create dd::Table object */
6430 THD *thd = current_thd;
6431 dd::Schema_MDL_locker mdl_locker(thd);
6432 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
6433 dd::cache::Dictionary_client::Auto_releaser releaser(client);
6434
6435 const dd::Schema *schema = nullptr;
6436 if (mdl_locker.ensure_locked(db_name.c_str()) ||
6437 client->acquire<dd::Schema>(db_name.c_str(), &schema)) {
6438 return false;
6439 }
6440
6441 /* Check if schema is nullptr? */
6442 if (schema == nullptr) {
6443 my_error(ER_BAD_DB_ERROR, MYF(0), db_name.c_str());
6444 return false;
6445 }
6446
6447 std::unique_ptr<dd::Table> dd_table_obj(schema->create_table(thd));
6448 dd::Table *dd_table = dd_table_obj.get();
6449
6450 dd_table->set_name(table_name.c_str());
6451 dd_table->set_schema_id(schema->id());
6452
6453 dd_set_fts_table_options(dd_table, table);
6454
6455 /* FTS AUX tables are always not encrypted/compressed
6456 as it is designed now. So both "compress" and "encrypt_type"
6457 option are not set */
6458
6459 /* Fill columns */
6460 /* 1st column: word */
6461 const char *col_name = nullptr;
6462 dd::Column *col = dd_table->add_column();
6463 col_name = "word";
6464 col->set_name(col_name);
6465 col->set_type(dd::enum_column_types::VARCHAR);
6466 col->set_char_length(FTS_INDEX_WORD_LEN);
6467 col->set_nullable(false);
6468 col->set_collation_id(charset->number);
6469 ut_ad(strcmp(col_name, table->get_col_name(0)) == 0);
6470 dd_set_fts_nullability(col, table->get_col(0));
6471
6472 dd::Column *key_col1 = col;
6473
6474 /* 2nd column: first_doc_id */
6475 col = dd_table->add_column();
6476 col->set_name("first_doc_id");
6477 col->set_type(dd::enum_column_types::LONGLONG);
6478 col->set_char_length(20);
6479 col->set_numeric_scale(0);
6480 col->set_nullable(false);
6481 col->set_unsigned(true);
6482 col->set_collation_id(charset->number);
6483
6484 dd::Column *key_col2 = col;
6485
6486 /* 3rd column: last_doc_id */
6487 col = dd_table->add_column();
6488 col->set_name("last_doc_id");
6489 col->set_type(dd::enum_column_types::LONGLONG);
6490 col->set_char_length(20);
6491 col->set_numeric_scale(0);
6492 col->set_nullable(false);
6493 col->set_unsigned(true);
6494 col->set_collation_id(charset->number);
6495
6496 /* 4th column: doc_count */
6497 col = dd_table->add_column();
6498 col->set_name("doc_count");
6499 col->set_type(dd::enum_column_types::LONG);
6500 col->set_char_length(4);
6501 col->set_numeric_scale(0);
6502 col->set_nullable(false);
6503 col->set_unsigned(true);
6504 col->set_collation_id(charset->number);
6505
6506 /* 5th column: ilist */
6507 col = dd_table->add_column();
6508 col->set_name("ilist");
6509 col->set_type(dd::enum_column_types::BLOB);
6510 col->set_char_length(8);
6511 col->set_nullable(false);
6512 col->set_collation_id(my_charset_bin.number);
6513
6514 /* Fill index */
6515 dd::Index *index = dd_table->add_index();
6516 index->set_name("FTS_INDEX_TABLE_IND");
6517 index->set_algorithm(dd::Index::IA_BTREE);
6518 index->set_algorithm_explicit(false);
6519 index->set_visible(true);
6520 index->set_type(dd::Index::IT_PRIMARY);
6521 index->set_ordinal_position(1);
6522 index->set_generated(false);
6523 index->set_engine(dd_table->engine());
6524
6525 index->options().set("flags", 32);
6526
6527 dd::Index_element *index_elem;
6528 index_elem = index->add_element(key_col1);
6529 index_elem->set_length(FTS_INDEX_WORD_LEN);
6530
6531 index_elem = index->add_element(key_col2);
6532 index_elem->set_length(FTS_INDEX_FIRST_DOC_ID_LEN);
6533
6534 /* Fill table space info, etc */
6535 dd::Object_id dd_space_id;
6536 if (!dd_get_or_assign_fts_tablespace_id(parent_table, table, dd_space_id)) {
6537 return false;
6538 }
6539
6540 table->dd_space_id = dd_space_id;
6541
6542 dd_write_table(dd_space_id, dd_table, table);
6543
6544 MDL_ticket *mdl_ticket = nullptr;
6545 if (dd::acquire_exclusive_table_mdl(thd, db_name.c_str(), table_name.c_str(),
6546 false, &mdl_ticket)) {
6547 ut_d(ut_error);
6548 ut_o(return false);
6549 }
6550
6551 /* Store table to dd */
6552 bool fail = client->store(dd_table);
6553 if (fail) {
6554 ut_d(ut_error);
6555 ut_o(return false);
6556 }
6557
6558 return true;
6559 }
6560
6561 /** Create dd table for fts aux common table
6562 @param[in] parent_table parent table of fts table
6563 @param[in,out] table fts table
6564 @param[in] is_config flag whether it's fts aux configure table
6565 @return true on success, false on failure */
6566 bool dd_create_fts_common_table(const dict_table_t *parent_table,
6567 dict_table_t *table, bool is_config) {
6568 std::string db_name;
6569 std::string table_name;
6570
6571 dict_name::get_table(table->name.m_name, db_name, table_name);
6572
6573 /* Create dd::Table object */
6574 THD *thd = current_thd;
6575 dd::Schema_MDL_locker mdl_locker(thd);
6576 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
6577 dd::cache::Dictionary_client::Auto_releaser releaser(client);
6578
6579 const dd::Schema *schema = nullptr;
6580 if (mdl_locker.ensure_locked(db_name.c_str()) ||
6581 client->acquire<dd::Schema>(db_name.c_str(), &schema)) {
6582 return false;
6583 }
6584
6585 /* Check if schema is nullptr */
6586 if (schema == nullptr) {
6587 my_error(ER_BAD_DB_ERROR, MYF(0), db_name.c_str());
6588 return false;
6589 }
6590
6591 std::unique_ptr<dd::Table> dd_table_obj(schema->create_table(thd));
6592 dd::Table *dd_table = dd_table_obj.get();
6593
6594 dd_table->set_name(table_name.c_str());
6595 dd_table->set_schema_id(schema->id());
6596
6597 dd_set_fts_table_options(dd_table, table);
6598 const char *col_name = nullptr;
6599
6600 /* Fill columns */
6601 if (!is_config) {
6602 /* 1st column: doc_id */
6603 dd::Column *col = dd_table->add_column();
6604 col_name = "doc_id";
6605 col->set_name(col_name);
6606 col->set_type(dd::enum_column_types::LONGLONG);
6607 col->set_char_length(20);
6608 col->set_numeric_scale(0);
6609 col->set_nullable(false);
6610 col->set_unsigned(true);
6611 col->set_collation_id(my_charset_bin.number);
6612 ut_ad(strcmp(col_name, table->get_col_name(0)) == 0);
6613 dd_set_fts_nullability(col, table->get_col(0));
6614
6615 dd::Column *key_col1 = col;
6616
6617 /* Fill index */
6618 dd::Index *index = dd_table->add_index();
6619 index->set_name("FTS_COMMON_TABLE_IND");
6620 index->set_algorithm(dd::Index::IA_BTREE);
6621 index->set_algorithm_explicit(false);
6622 index->set_visible(true);
6623 index->set_type(dd::Index::IT_PRIMARY);
6624 index->set_ordinal_position(1);
6625 index->set_generated(false);
6626 index->set_engine(dd_table->engine());
6627
6628 index->options().set("flags", 32);
6629
6630 dd::Index_element *index_elem;
6631 index_elem = index->add_element(key_col1);
6632 index_elem->set_length(FTS_INDEX_FIRST_DOC_ID_LEN);
6633 } else {
6634 /* Fill columns */
6635 /* 1st column: key */
6636 dd::Column *col = dd_table->add_column();
6637 col_name = "key";
6638 col->set_name(col_name);
6639 col->set_type(dd::enum_column_types::VARCHAR);
6640 col->set_char_length(FTS_CONFIG_TABLE_KEY_COL_LEN);
6641 col->set_nullable(false);
6642 col->set_collation_id(my_charset_latin1.number);
6643 ut_ad(strcmp(col_name, table->get_col_name(0)) == 0);
6644 dd_set_fts_nullability(col, table->get_col(0));
6645
6646 dd::Column *key_col1 = col;
6647
6648 /* 2nd column: value */
6649 col = dd_table->add_column();
6650 col->set_name("value");
6651 col->set_type(dd::enum_column_types::VARCHAR);
6652 col->set_char_length(FTS_CONFIG_TABLE_VALUE_COL_LEN);
6653 col->set_nullable(false);
6654 col->set_collation_id(my_charset_latin1.number);
6655
6656 /* Fill index */
6657 dd::Index *index = dd_table->add_index();
6658 index->set_name("FTS_COMMON_TABLE_IND");
6659 index->set_algorithm(dd::Index::IA_BTREE);
6660 index->set_algorithm_explicit(false);
6661 index->set_visible(true);
6662 index->set_type(dd::Index::IT_PRIMARY);
6663 index->set_ordinal_position(1);
6664 index->set_generated(false);
6665 index->set_engine(dd_table->engine());
6666
6667 index->options().set("flags", 32);
6668
6669 dd::Index_element *index_elem;
6670 index_elem = index->add_element(key_col1);
6671 index_elem->set_length(FTS_CONFIG_TABLE_KEY_COL_LEN);
6672 }
6673
6674 /* Fill table space info, etc */
6675 dd::Object_id dd_space_id;
6676 if (!dd_get_or_assign_fts_tablespace_id(parent_table, table, dd_space_id)) {
6677 ut_d(ut_error);
6678 ut_o(return false);
6679 }
6680
6681 table->dd_space_id = dd_space_id;
6682
6683 dd_write_table(dd_space_id, dd_table, table);
6684
6685 MDL_ticket *mdl_ticket = nullptr;
6686 if (dd::acquire_exclusive_table_mdl(thd, db_name.c_str(), table_name.c_str(),
6687 false, &mdl_ticket)) {
6688 return false;
6689 }
6690
6691 /* Store table to dd */
6692 bool fail = client->store(dd_table);
6693 if (fail) {
6694 ut_d(ut_error);
6695 ut_o(return false);
6696 }
6697
6698 return true;
6699 }
6700
6701 /** Drop dd table & tablespace for fts aux table
6702 @param[in] name table name
6703 @param[in] file_per_table flag whether use file per table
6704 @return true on success, false on failure. */
6705 bool dd_drop_fts_table(const char *name, bool file_per_table) {
6706 std::string db_name;
6707 std::string table_name;
6708
6709 dict_name::get_table(name, db_name, table_name);
6710
6711 /* Create dd::Table object */
6712 THD *thd = current_thd;
6713 dd::Schema_MDL_locker mdl_locker(thd);
6714 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
6715 dd::cache::Dictionary_client::Auto_releaser releaser(client);
6716
6717 MDL_ticket *mdl_ticket = nullptr;
6718 if (dd::acquire_exclusive_table_mdl(thd, db_name.c_str(), table_name.c_str(),
6719 false, &mdl_ticket)) {
6720 return false;
6721 }
6722
6723 const dd::Table *dd_table = nullptr;
6724 if (client->acquire<dd::Table>(db_name.c_str(), table_name.c_str(),
6725 &dd_table)) {
6726 return false;
6727 }
6728
6729 if (dd_table == nullptr) {
6730 return false;
6731 }
6732
6733 if (file_per_table) {
6734 dd::Object_id dd_space_id = (*dd_table->indexes().begin())->tablespace_id();
6735 /*
6736 * In databases upgraded from MySQL versions 5.6.5 to 5.6.19,
6737 * FTS tables may be located in system tablespace even if parent
6738 * table is file-per-table. In this case we obviously don't want to
6739 * drop the tablespace.
6740 */
6741 if (dd_space_id != dict_sys_t::s_dd_sys_space_id) {
6742 bool error = dd_drop_tablespace(client, dd_space_id);
6743 ut_a(!error);
6744 }
6745 }
6746
6747 if (client->drop(dd_table)) {
6748 return false;
6749 }
6750
6751 return true;
6752 }
6753
6754 /** Rename dd table & tablespace files for fts aux table
6755 @param[in] table dict table
6756 @param[in] old_name old innodb table name
6757 @return true on success, false on failure. */
6758 bool dd_rename_fts_table(const dict_table_t *table, const char *old_name) {
6759 std::string new_db;
6760 std::string new_table;
6761 dict_name::get_table(table->name.m_name, new_db, new_table);
6762
6763 std::string old_db;
6764 std::string old_table;
6765 dict_name::get_table(old_name, old_db, old_table);
6766
6767 ut_ad(new_db.compare(old_db) != 0);
6768 ut_ad(new_table.compare(old_table) == 0);
6769
6770 /* Create dd::Table object */
6771 THD *thd = current_thd;
6772 dd::Schema_MDL_locker mdl_locker(thd);
6773 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
6774 dd::cache::Dictionary_client::Auto_releaser releaser(client);
6775
6776 const dd::Schema *to_sch = nullptr;
6777 if (client->acquire<dd::Schema>(new_db.c_str(), &to_sch)) {
6778 return false;
6779 }
6780
6781 MDL_ticket *mdl_ticket = nullptr;
6782 if (dd::acquire_exclusive_table_mdl(thd, old_db.c_str(), old_table.c_str(),
6783 false, &mdl_ticket)) {
6784 return false;
6785 }
6786
6787 MDL_ticket *mdl_ticket2 = nullptr;
6788 if (dd::acquire_exclusive_table_mdl(thd, new_db.c_str(), new_table.c_str(),
6789 false, &mdl_ticket2)) {
6790 return false;
6791 }
6792
6793 dd::Table *dd_table = nullptr;
6794 if (client->acquire_for_modification<dd::Table>(
6795 old_db.c_str(), old_table.c_str(), &dd_table)) {
6796 return false;
6797 }
6798
6799 // Set schema id
6800 dd_table->set_schema_id(to_sch->id());
6801
6802 /* Rename dd tablespace file */
6803 if (dict_table_is_file_per_table(table)) {
6804 char *new_path = fil_space_get_first_path(table->space);
6805
6806 if (dd_tablespace_rename(table->dd_space_id, false, table->name.m_name,
6807 new_path) != DB_SUCCESS) {
6808 ut_error;
6809 }
6810
6811 ut::free(new_path);
6812 }
6813
6814 if (client->update(dd_table)) {
6815 ut_d(ut_error);
6816 ut_o(return false);
6817 }
6818
6819 return true;
6820 }
6821
6822 /** Set the space_id attribute in se_private_data of tablespace
6823 @param[in,out] dd_space dd::Tablespace object
6824 @param[in] space_id tablespace ID */
6825 void dd_tablespace_set_space_id(dd::Tablespace *dd_space, space_id_t space_id) {
6826 dd::Properties &p = dd_space->se_private_data();
6827
6828 p.set(dd_space_key_strings[DD_SPACE_ID], space_id);
6829 }
6830
6831 void dd_tablespace_set_state(THD *thd, dd::Object_id dd_space_id,
6832 std::string space_name, dd_space_states dd_state) {
6833 using Client = dd::cache::Dictionary_client;
6834 using Releaser = dd::cache::Dictionary_client::Auto_releaser;
6835
6836 /* Get Tablespace object */
6837 dd::Tablespace *dd_space = nullptr;
6838 Client *client = dd::get_dd_client(thd);
6839 Releaser releaser{client};
6840
6841 if (dd_tablespace_get_mdl(space_name.c_str())) {
6842 ut_error;
6843 }
6844
6845 if (client->acquire_for_modification(dd_space_id, &dd_space) ||
6846 dd_space == nullptr) {
6847 ut_error;
6848 }
6849
6850 ut_a(dd_space != nullptr);
6851
6852 dd_tablespace_set_state(dd_space, dd_state);
6853
6854 if (client->update(dd_space)) {
6855 ut_d(ut_error);
6856 }
6857 }
6858
6859 void dd_tablespace_set_state(dd::Tablespace *dd_space, dd_space_states state) {
6860 dd::Properties &p = dd_space->se_private_data();
6861
6862 p.set(dd_space_key_strings[DD_SPACE_STATE], dd_space_state_values[state]);
6863 }
6864
6865 bool dd_tablespace_set_id_and_state(const char *space_name, space_id_t space_id,
6866 dd_space_states state) {
6867 THD *thd = current_thd;
6868 dd::Tablespace *dd_space;
6869
6870 dd::cache::Dictionary_client *dc = dd::get_dd_client(thd);
6871 dd::cache::Dictionary_client::Auto_releaser releaser{dc};
6872 dd::String_type tsn{space_name};
6873
6874 bool dd_result = dc->acquire_for_modification(tsn, &dd_space);
6875 if (dd_space == nullptr) {
6876 return DD_FAILURE;
6877 }
6878
6879 dd_tablespace_set_space_id(dd_space, space_id);
6880
6881 dd_tablespace_set_state(dd_space, state);
6882
6883 return dd::commit_or_rollback_tablespace_change(thd, dd_space, dd_result);
6884 }
6885
6886 void dd_set_discarded(dd::Table &table, bool discard) {
6887 ut_ad(!dd_table_is_partitioned(table));
6888
6889 dd::Properties &p = table.se_private_data();
6890 p.set(dd_table_key_strings[DD_TABLE_DISCARD], discard);
6891 }
6892
6893 void dd_set_discarded(dd::Partition &partition, bool discard) {
6894 #ifdef UNIV_DEBUG
6895 bool is_leaf = false;
6896 for (const dd::Partition *part : *partition.table().leaf_partitions()) {
6897 if (part == &partition) {
6898 is_leaf = true;
6899 break;
6900 }
6901 }
6902 ut_ad(is_leaf);
6903 #endif
6904
6905 dd::Properties &p = partition.se_private_data();
6906 p.set(dd_partition_key_strings[DD_PARTITION_DISCARD], discard);
6907 }
6908
6909 void dd_tablespace_get_state(const dd::Tablespace *dd_space,
6910 dd::String_type *state, space_id_t space_id) {
6911 const dd::Properties &p = dd_space->se_private_data();
6912
6913 dd_tablespace_get_state(&p, state, space_id);
6914 }
6915
6916 void dd_tablespace_get_state(const dd::Properties *p, dd::String_type *state,
6917 space_id_t space_id) {
6918 if (p->exists(dd_space_key_strings[DD_SPACE_STATE])) {
6919 p->get(dd_space_key_strings[DD_SPACE_STATE], state);
6920 } else {
6921 /* If this k/v pair is missing then the database may have been created
6922 by an earlier version. So calculate the state. */
6923 dd_space_states state_enum =
6924 dd_tablespace_get_state_enum_legacy(p, space_id);
6925 *state = dd_space_state_values[state_enum];
6926 }
6927 }
6928
6929 dd_space_states dd_tablespace_get_state_enum(const dd::Tablespace *dd_space,
6930 space_id_t space_id) {
6931 const dd::Properties &p = dd_space->se_private_data();
6932
6933 return dd_tablespace_get_state_enum(&p, space_id);
6934 }
6935
6936 dd_space_states dd_tablespace_get_state_enum(const dd::Properties *p,
6937 space_id_t space_id) {
6938 dd_space_states state_enum = DD_SPACE_STATE__LAST;
6939
6940 /* Look for the 'state' key and read its value from the DD. */
6941 if (p->exists(dd_space_key_strings[DD_SPACE_STATE])) {
6942 dd::String_type state;
6943 p->get(dd_space_key_strings[DD_SPACE_STATE], &state);
6944
6945 /* Convert this string to a number. */
6946 for (int s = DD_SPACE_STATE_NORMAL; s < DD_SPACE_STATE__LAST; s++) {
6947 if (state == dd_space_state_values[s]) {
6948 state_enum = (dd_space_states)s;
6949 return state_enum;
6950 }
6951 }
6952 }
6953
6954 return dd_tablespace_get_state_enum_legacy(p, space_id);
6955 }
6956
6957 dd_space_states dd_tablespace_get_state_enum_legacy(const dd::Properties *p,
6958 space_id_t space_id) {
6959 dd_space_states state_enum = DD_SPACE_STATE__LAST;
6960
6961 /* This is called when the 'state' key is missing from the
6962 dd::Tablespace::se_private_data field. The database may have been
6963 created by an earlier version. So calculate the state another way.
6964 First, make sure we have the space_id. */
6965 if (space_id == SPACE_UNKNOWN) {
6966 if (p->exists(dd_space_key_strings[DD_SPACE_ID])) {
6967 p->get(dd_space_key_strings[DD_SPACE_ID], &space_id);
6968 } else {
6969 return DD_SPACE_STATE__LAST;
6970 }
6971 }
6972 ut_ad(space_id != SPACE_UNKNOWN);
6973
6974 /* Undo tablespaces have the state recorded in undo::spaces. */
6975 if (fsp_is_undo_tablespace(space_id)) {
6976 undo::spaces->s_lock();
6977 undo::Tablespace *undo_space = undo::spaces->find(undo::id2num(space_id));
6978
6979 if (undo_space->is_active()) {
6980 state_enum = DD_SPACE_STATE_ACTIVE;
6981 } else if (undo_space->is_empty()) {
6982 state_enum = DD_SPACE_STATE_EMPTY;
6983 } else {
6984 state_enum = DD_SPACE_STATE_INACTIVE;
6985 }
6986 undo::spaces->s_unlock();
6987
6988 return state_enum;
6989 }
6990
6991 /* This is an IBD tablespace without the 'state' key value. It might have
6992 been created with a MySQL version before the 'state' field was introduced.
6993 Look for the 'discarded' key value. */
6994 bool is_discarded = false;
6995 if (p->exists(dd_space_key_strings[DD_SPACE_DISCARD])) {
6996 p->get(dd_space_key_strings[DD_SPACE_DISCARD], &is_discarded);
6997 }
6998
6999 state_enum = is_discarded ? DD_SPACE_STATE_DISCARDED : DD_SPACE_STATE_NORMAL;
7000
7001 return state_enum;
7002 }
7003
7004 /** Get the discarded state from se_private_data of tablespace
7005 @param[in] dd_space dd::Tablespace object */
7006 bool dd_tablespace_is_discarded(const dd::Tablespace *dd_space) {
7007 dd::String_type dd_state;
7008
7009 dd_tablespace_get_state(dd_space, &dd_state);
7010
7011 if (dd_state == dd_space_state_values[DD_SPACE_STATE_DISCARDED]) {
7012 return true;
7013 }
7014
7015 return false;
7016 }
7017
7018 bool dd_tablespace_get_mdl(const char *space_name, MDL_ticket **mdl_ticket,
7019 bool foreground) {
7020 THD *thd = current_thd;
7021 /* Safeguard in release mode if background thread doesn't have THD. */
7022 if (thd == nullptr) {
7023 ut_d(ut_error);
7024 ut_o(return true);
7025 }
7026 /* Explicit duration for background threads. */
7027 bool trx_duration = foreground;
7028
7029 /* Background thread should not block on MDL lock. */
7030 ulong timeout = foreground ? thd->variables.lock_wait_timeout : 0;
7031 bool result = acquire_shared_backup_lock(thd, timeout, trx_duration);
7032
7033 if (!result) {
7034 result = dd::acquire_exclusive_tablespace_mdl(thd, space_name, false,
7035 mdl_ticket, trx_duration);
7036 if (result) {
7037 release_backup_lock(thd);
7038 }
7039 }
7040
7041 /* For background thread, clear timeout error. */
7042 if (result && !foreground && thd->is_error()) {
7043 thd->clear_error();
7044 }
7045 return result;
7046 }
7047
7048 /** Release the MDL held by the given ticket.
7049 @param[in] mdl_ticket tablespace MDL ticket */
7050 void dd_release_mdl(MDL_ticket *mdl_ticket) {
7051 dd::release_mdl(current_thd, mdl_ticket);
7052 release_backup_lock(current_thd);
7053 }
7054
7055 #ifdef UNIV_DEBUG
7056 /** @return total number of indexes of all DD tables */
7057 uint32_t dd_get_total_indexes_num() {
7058 uint32_t indexes_count = 0;
7059 for (uint32_t idx = 0; idx < innodb_dd_table_size; idx++) {
7060 indexes_count += innodb_dd_table[idx].n_indexes;
7061 }
7062 return indexes_count;
7063 }
7064 #endif /* UNIV_DEBUG */
7065
7066 /** Open a table from its database and table name, this is currently used by
7067 foreign constraint parser to get the referenced table.
7068 @param[in] name foreign key table name
7069 @param[in] database_name table db name
7070 @param[in] database_name_len db name length
7071 @param[in] table_name table db name
7072 @param[in] table_name_len table name length
7073 @param[in,out] table table object or NULL
7074 @param[in,out] mdl mdl on table
7075 @param[in,out] heap heap memory
7076 @return complete table name with database and table name, allocated from
7077 heap memory passed in */
7078 char *dd_get_referenced_table(const char *name, const char *database_name,
7079 ulint database_name_len, const char *table_name,
7080 ulint table_name_len, dict_table_t **table,
7081 MDL_ticket **mdl, mem_heap_t *heap) {
7082 char *ref;
7083 const char *db_name;
7084
7085 bool is_part = dict_name::is_partition(name);
7086
7087 *table = nullptr;
7088
7089 if (!database_name) {
7090 /* Use the database name of the foreign key table */
7091
7092 db_name = name;
7093 database_name_len = dict_get_db_name_len(name);
7094 } else {
7095 db_name = database_name;
7096 }
7097
7098 /* Copy database_name, '/', table_name, '\0' */
7099 ref = static_cast<char *>(
7100 mem_heap_alloc(heap, database_name_len + table_name_len + 2));
7101
7102 memcpy(ref, db_name, database_name_len);
7103 ref[database_name_len] = '/';
7104 memcpy(ref + database_name_len + 1, table_name, table_name_len + 1);
7105
7106 /* Values; 0 = Store and compare as given; case sensitive
7107 1 = Store and compare in lower; case insensitive
7108 2 = Store as given, compare in lower; case semi-sensitive */
7109 if (innobase_get_lower_case_table_names() == 2) {
7110 innobase_casedn_str(ref);
7111 if (!is_part) {
7112 *table = dd_table_open_on_name(current_thd, mdl, ref, true,
7113 DICT_ERR_IGNORE_NONE);
7114 }
7115 memcpy(ref, db_name, database_name_len);
7116 ref[database_name_len] = '/';
7117 memcpy(ref + database_name_len + 1, table_name, table_name_len + 1);
7118
7119 } else {
7120 #ifndef _WIN32
7121 if (innobase_get_lower_case_table_names() == 1) {
7122 innobase_casedn_str(ref);
7123 }
7124 #else
7125 innobase_casedn_str(ref);
7126 #endif /* !_WIN32 */
7127 if (!is_part) {
7128 *table = dd_table_open_on_name(current_thd, mdl, ref, true,
7129 DICT_ERR_IGNORE_NONE);
7130 }
7131 }
7132
7133 return ref;
7134 }
7135
7136 /** Update all InnoDB tablespace cache objects. This step is done post
7137 dictionary trx rollback, binlog recovery and DDL_LOG apply. So DD is
7138 consistent. Update the cached tablespace objects, if they differ from
7139 the dictionary.
7140 @param[in,out] thd thread handle
7141 @retval true on error
7142 @retval false on success */
7143 bool dd_tablespace_update_cache(THD *thd) {
7144 /* If there are no prepared trxs, then DD reads would have been
7145 already consistent. No need to update cache */
7146 if (!trx_sys->found_prepared_trx) {
7147 return false;
7148 }
7149
7150 dd::cache::Dictionary_client *dc = dd::get_dd_client(thd);
7151 dd::cache::Dictionary_client::Auto_releaser releaser(dc);
7152 std::vector<const dd::Tablespace *> tablespaces;
7153
7154 space_id_t max_id = 0;
7155
7156 if (dc->fetch_global_components(&tablespaces)) {
7157 return true;
7158 }
7159
7160 bool fail = false;
7161
7162 for (const dd::Tablespace *t : tablespaces) {
7163 ut_ad(!fail);
7164
7165 if (t->engine() != innobase_hton_name) {
7166 continue;
7167 }
7168
7169 const dd::Properties &p = t->se_private_data();
7170 uint32_t id;
7171 uint32_t flags = 0;
7172
7173 /* There should be exactly one file name associated
7174 with each InnoDB tablespace, except innodb_system */
7175 fail = p.get(dd_space_key_strings[DD_SPACE_ID], &id) ||
7176 p.get(dd_space_key_strings[DD_SPACE_FLAGS], &flags) ||
7177 (t->files().size() != 1 &&
7178 strcmp(t->name().c_str(), dict_sys_t::s_sys_space_name) != 0);
7179
7180 if (fail) {
7181 break;
7182 }
7183
7184 /* Undo tablespaces may be deleted and re-created at
7185 startup and not registered in DD. So exempt undo tablespaces
7186 from verification */
7187 if (fsp_is_undo_tablespace(id)) {
7188 continue;
7189 }
7190
7191 if (!dict_sys_t::is_reserved(id) && id > max_id) {
7192 /* Currently try to find the max one only, it should
7193 be able to reuse the deleted smaller ones later */
7194 max_id = id;
7195 }
7196
7197 const dd::Tablespace_file *f = *t->files().begin();
7198 fail = f == nullptr;
7199 if (fail) {
7200 break;
7201 }
7202
7203 const char *space_name = t->name().c_str();
7204 fil_space_t *space = fil_space_get(id);
7205
7206 if (space != nullptr) {
7207 /* If the tablespace is already in cache, verify that
7208 the tablespace name matches the name in dictionary.
7209 If it doesn't match, use the name from dictionary. */
7210
7211 /* Exclude Encryption flag as (un)encryption operation might be
7212 rolling forward in background thread. */
7213 ut_ad(!((space->flags ^ flags) & ~(FSP_FLAGS_MASK_ENCRYPTION)));
7214
7215 fil_space_update_name(space, space_name);
7216
7217 } else {
7218 fil_type_t purpose = fsp_is_system_temporary(id) ? FIL_TYPE_TEMPORARY
7219 : FIL_TYPE_TABLESPACE;
7220
7221 const char *filename = f->filename().c_str();
7222
7223 /* If the user tablespace is not in cache, load the
7224 tablespace now, with the name from dictionary */
7225
7226 /* It's safe to pass space_name in tablename charset
7227 because filename is already in filename charset. */
7228 dberr_t err = fil_ibd_open(false, purpose, id, flags, space_name,
7229 filename, false, false);
7230 switch (err) {
7231 case DB_SUCCESS:
7232 break;
7233 case DB_CANNOT_OPEN_FILE:
7234 break;
7235 default:
7236 ib::info(ER_IB_MSG_174)
7237 << "Unable to open tablespace " << id << " (flags=" << flags
7238 << ", filename=" << filename << ")."
7239 << " Have you deleted/moved the .IBD";
7240 ut_strerr(err);
7241 }
7242 }
7243 if (id != TRX_SYS_SPACE && fil_space_get(id) != nullptr) {
7244 /* Get the autoextend_size property from the tablespace
7245 and set the fil_space_t::autoextend_size attribute. */
7246 const dd::Properties &o = t->options();
7247 uint64_t autoextend_size{};
7248
7249 if (o.exists(autoextend_size_str)) {
7250 o.get(autoextend_size_str, &autoextend_size);
7251 }
7252
7253 ut_d(dberr_t ret =) fil_set_autoextend_size(id, autoextend_size);
7254 ut_ad(ret == DB_SUCCESS);
7255 }
7256 }
7257
7258 fil_set_max_space_id_if_bigger(max_id);
7259 return fail;
7260 }
7261
7262 /* Check if the table belongs to an encrypted tablespace.
7263 @param[in] table table for which check is to be done
7264 @return true if it does. */
7265 bool dd_is_table_in_encrypted_tablespace(const dict_table_t *table) {
7266 fil_space_t *space = fil_space_get(table->space);
7267 if (space != nullptr) {
7268 return FSP_FLAGS_GET_ENCRYPTION(space->flags);
7269 } else {
7270 /* Its possible that tablespace flag is missing (for ex: after
7271 discard tablespace). In that case get tablespace flags from Data
7272 Dictionary/ */
7273 THD *thd = current_thd;
7274 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
7275 dd::cache::Dictionary_client::Auto_releaser releaser(client);
7276 dd::Tablespace *dd_space = nullptr;
7277
7278 if (!client->acquire_uncached_uncommitted<dd::Tablespace>(
7279 table->dd_space_id, &dd_space) &&
7280 dd_space != nullptr) {
7281 uint32_t flags;
7282 dd_space->se_private_data().get(dd_space_key_strings[DD_SPACE_FLAGS],
7283 &flags);
7284
7285 return FSP_FLAGS_GET_ENCRYPTION(flags);
7286 }
7287 /* We should not reach here */
7288 ut_d(ut_error);
7289 ut_o(return false);
7290 }
7291 }
7292
7293 void dict_table_t::get_table_name(std::string &schema,
7294 std::string &table) const {
7295 std::string dict_table_name(name.m_name);
7296 dict_name::get_table(dict_table_name, schema, table);
7297 }
7298 #endif /* !UNIV_HOTBACKUP */
7299
7300 #ifndef UNIV_HOTBACKUP
7301 namespace dict_name {
7302 void file_to_table(std::string &name, bool quiet) {
7303 ut_ad(name.length() < FN_REFLEN);
7304 char conv_name[FN_REFLEN + 1];
7305
7306 /* Convert to system character set from file name character set. */
7307 filename_to_tablename(name.c_str(), conv_name, FN_REFLEN, quiet);
7308 name.assign(conv_name);
7309 }
7310
7311 void table_to_file(std::string &name) {
7312 ut_ad(name.length() < FN_REFLEN);
7313 char conv_name[FN_REFLEN + 1];
7314
7315 /* Convert to system character set from file name character set. */
7316 static_cast<void>(tablename_to_filename(name.c_str(), conv_name, FN_REFLEN));
7317 name.assign(conv_name);
7318 }
7319
7320 /** Get partition and sub-partition separator strings.
7321 @param[in] is_57 true, if 5.7 style separator is needed
7322 @param[out] part_sep partition separator
7323 @param[out] sub_part_sep sub-partition separator */
7324 static void get_partition_separators(bool is_57, std::string &part_sep,
7325 std::string &sub_part_sep) {
7326 if (!is_57) {
7327 part_sep.assign(PART_SEPARATOR);
7328 sub_part_sep.assign(SUB_PART_SEPARATOR);
7329 return;
7330 }
7331 /* 5.7 style partition separators. */
7332 #ifdef _WIN32
7333 part_sep.assign(PART_SEPARATOR);
7334 sub_part_sep.assign(SUB_PART_SEPARATOR);
7335 #else
7336 part_sep.assign(ALT_PART_SEPARATOR);
7337 sub_part_sep.assign(ALT_SUB_PART_SEPARATOR);
7338 #endif /* _WIN32 */
7339 }
7340
7341 /** Check for partition and sub partition.
7342 @param[in] dict_name name from innodb dictionary
7343 @param[in] sub_part true, if checking sub partition
7344 @param[out] position position of partition in string
7345 @return true, iff partition/sub-partition exists. */
7346 static bool check_partition(const std::string &dict_name, bool sub_part,
7347 size_t &position) {
7348 std::string part_sep = sub_part ? SUB_PART_SEPARATOR : PART_SEPARATOR;
7349
7350 /* Check for partition separator string. */
7351 position = dict_name.find(part_sep);
7352
7353 if (position != std::string::npos) {
7354 return true;
7355 }
7356
7357 std::string alt_sep = sub_part ? ALT_SUB_PART_SEPARATOR : ALT_PART_SEPARATOR;
7358
7359 /* Check for alternative partition separator. It is safe check for
7360 release build server and for upgrade. */
7361 position = dict_name.find(alt_sep);
7362
7363 if (position != std::string::npos) {
7364 return true;
7365 }
7366
7367 return false;
7368 }
7369
7370 /** Check for TMP extension name.
7371 @param[in] dict_name name from innodb dictionary
7372 @param[out] position position of TMP extension in string
7373 @return true, iff TMP extension exists. */
7374 static bool check_tmp(const std::string &dict_name, size_t &position) {
7375 std::string check_name(dict_name);
7376 position = std::string::npos;
7377
7378 /* For partitioned or sub partitioned table we need to search the
7379 temp postfix within the partition, sub-partition string. The temp
7380 extension looks as follows in different cases.
7381
7382 1. Non partitioned table : table_name#TMP
7383 2. Table Partition : table_name#p#part_name#TMP
7384 3. Table Sub Partition : table_name#p#part_name#sp#sub_part_name#TMP
7385
7386 The issue with checking only #TMP at the end of string is that the partition
7387 or sub partition could be named as 'TMP' and in following cases we could
7388 wrongly classify it as name with temporary extension.
7389
7390 1. Table Partition : table_name#p#TMP
7391 3. Table Sub Partition : table_name#p#part_name#sp#TMP */
7392
7393 size_t part_begin = std::string::npos;
7394
7395 if (check_partition(dict_name, false, part_begin)) {
7396 part_begin += PART_SEPARATOR_LEN;
7397 auto part_string = check_name.substr(part_begin);
7398 /* Modify the name to start from the beginning of partition string
7399 excluding the partition separator '#p#'. */
7400 check_name.assign(part_string);
7401
7402 size_t sub_part_begin = std::string::npos;
7403
7404 if (check_partition(part_string, true, sub_part_begin)) {
7405 sub_part_begin += SUB_PART_SEPARATOR_LEN;
7406 auto sub_part_string = check_name.substr(sub_part_begin);
7407 /* Modify the name to start from the beginning of sub-partition string
7408 excluding the sub-partition separator '#sp#'. */
7409 check_name.assign(sub_part_string);
7410 }
7411 }
7412
7413 auto length = check_name.size();
7414
7415 if (length < TMP_POSTFIX_LEN) {
7416 return false;
7417 }
7418
7419 auto postfix_pos = length - TMP_POSTFIX_LEN;
7420 auto ret = check_name.compare(postfix_pos, TMP_POSTFIX_LEN, TMP_POSTFIX);
7421
7422 if (ret == 0) {
7423 auto length = dict_name.size();
7424 ut_a(length >= TMP_POSTFIX_LEN);
7425
7426 position = length - TMP_POSTFIX_LEN;
7427 ut_ad(0 == dict_name.compare(position, TMP_POSTFIX_LEN, TMP_POSTFIX));
7428 return true;
7429 }
7430 return false;
7431 }
7432
7433 bool is_partition(const std::string &dict_name) {
7434 size_t position;
7435 return check_partition(dict_name, false, position);
7436 }
7437
7438 void get_table(const std::string &dict_name, std::string &schema,
7439 std::string &table) {
7440 bool is_tmp;
7441 std::string partition;
7442 get_table(dict_name, true, schema, table, partition, is_tmp);
7443 }
7444
7445 void get_table(const std::string &dict_name, bool convert, std::string &schema,
7446 std::string &table, std::string &partition, bool &is_tmp) {
7447 size_t table_begin = dict_name.find(SCHEMA_SEPARATOR);
7448
7449 /* Check if schema is specified. */
7450 if (table_begin == std::string::npos) {
7451 table_begin = 0;
7452 schema.clear();
7453 } else {
7454 schema.assign(dict_name.substr(0, table_begin));
7455 if (convert) {
7456 /* Perform conversion if requested. Allow invalid conversion
7457 in schema name. For temp table server passes directory name
7458 instead of schema name which might contain "." resulting in
7459 conversion to "?". For temp table this schema name is never used. */
7460 file_to_table(schema, true);
7461 }
7462 ++table_begin;
7463 }
7464
7465 table.assign(dict_name.substr(table_begin));
7466 partition.clear();
7467
7468 /* Check if partitioned table. */
7469 size_t part_begin = std::string::npos;
7470 bool is_part = check_partition(table, false, part_begin);
7471
7472 /* Check if temp extension. */
7473 size_t tmp_begin = std::string::npos;
7474 is_tmp = check_tmp(table, tmp_begin);
7475
7476 if (is_part) {
7477 ut_ad(part_begin > 0);
7478 size_t part_len = std::string::npos;
7479
7480 if (is_tmp && tmp_begin > part_begin) {
7481 part_len = tmp_begin - part_begin;
7482 } else if (is_tmp) {
7483 /* TMP extension must follow partition. */
7484 ut_d(ut_error);
7485 }
7486 partition.assign(table.substr(part_begin, part_len));
7487 table.assign(table.substr(0, part_begin));
7488
7489 } else if (is_tmp) {
7490 ut_ad(tmp_begin > 0);
7491 table.assign(table.substr(0, tmp_begin));
7492 }
7493
7494 /* Perform conversion if requested. */
7495 if (convert) {
7496 file_to_table(table, false);
7497 }
7498 }
7499
7500 std::optional<table_name_components> parse_tablespace_path(std::string path) {
7501 // Initialize variables
7502 table_name_components table_info;
7503
7504 // Find the last '/'
7505 const size_t last_slash = path.find_last_of(OS_PATH_SEPARATOR);
7506 if (!last_slash || last_slash == std::string::npos ||
7507 last_slash == path.size() - 1) {
7508 return {};
7509 }
7510 const size_t second_last_slash =
7511 path.find_last_of(OS_PATH_SEPARATOR, last_slash - 1);
7512 if (!second_last_slash || second_last_slash == std::string::npos) return {};
7513
7514 // Extract directory
7515 table_info.directory = path.substr(0, second_last_slash);
7516
7517 // Extract schema name
7518 table_info.schema_name =
7519 path.substr(second_last_slash + 1, last_slash - second_last_slash - 1);
7520 file_to_table(table_info.schema_name, false);
7521
7522 // Extract table name
7523 std::string temp_table = path.substr(last_slash + 1);
7524 size_t hash_pos = temp_table.find_first_of("#.");
7525 table_info.table_name = temp_table.substr(0, hash_pos);
7526 file_to_table(table_info.table_name, false);
7527
7528 std::string part_seperator(PART_SEPARATOR);
7529 std::string sub_part_seperator(SUB_PART_SEPARATOR);
7530
7531 // Check for partitions and subpartitions
7532 bool has_partitions = temp_table.find(PART_SEPARATOR) != std::string::npos;
7533 if (!has_partitions) {
7534 has_partitions = temp_table.find(ALT_PART_SEPARATOR) != std::string::npos;
7535 if (has_partitions) {
7536 part_seperator = ALT_PART_SEPARATOR;
7537 sub_part_seperator = ALT_SUB_PART_SEPARATOR;
7538 }
7539 }
7540
7541 bool has_subpartitions =
7542 temp_table.find(sub_part_seperator) != std::string::npos;
7543
7544 if (has_partitions) {
7545 // Extract partition name
7546 size_t part_start =
7547 temp_table.find(part_seperator) + std::string(part_seperator).length();
7548 size_t part_end = has_subpartitions ? temp_table.find(sub_part_seperator)
7549 : temp_table.find('.');
7550
7551 ut_ad(part_end != std::string::npos);
7552 std::string temp_partition =
7553 temp_table.substr(part_start, part_end - part_start);
7554 file_to_table(temp_partition, false);
7555 table_info.partition = temp_partition;
7556 }
7557
7558 if (has_subpartitions) {
7559 // Extract subpartition name
7560 size_t sub_part_start = temp_table.find(sub_part_seperator) +
7561 std::string(sub_part_seperator).length();
7562 size_t sub_part_end = temp_table.find('.');
7563 ut_ad(sub_part_end != std::string::npos);
7564 std::string temp_subpartition =
7565 temp_table.substr(sub_part_start, sub_part_end - sub_part_start);
7566 file_to_table(temp_subpartition, false);
7567 table_info.subpartition = temp_subpartition;
7568 }
7569
7570 return table_info;
7571 }
7572
7573 void get_partition(const std::string &partition, bool convert,
7574 std::string &part, std::string &sub_part) {
7575 ut_ad(is_partition(partition));
7576
7577 /* Check if sub-partition exists. */
7578 size_t sub_pos = std::string::npos;
7579 bool is_sub = check_partition(partition, true, sub_pos);
7580
7581 /* Assign partition name. */
7582 size_t part_begin = PART_SEPARATOR_LEN;
7583 size_t part_len = std::string::npos;
7584
7585 if (is_sub) {
7586 ut_ad(sub_pos > part_begin);
7587 part_len = sub_pos - part_begin;
7588 }
7589
7590 part.assign(partition.substr(part_begin, part_len));
7591 if (convert) {
7592 file_to_table(part, false);
7593 }
7594
7595 /* Assign sub-partition name. */
7596 sub_part.clear();
7597 if (!is_sub) {
7598 return;
7599 }
7600
7601 auto sub_begin = sub_pos + SUB_PART_SEPARATOR_LEN;
7602 auto sub_len = std::string::npos;
7603
7604 sub_part.assign(partition.substr(sub_begin, sub_len));
7605
7606 if (convert) {
7607 file_to_table(sub_part, false);
7608 }
7609 }
7610
7611 void build_table(const std::string &schema, const std::string &table,
7612 const std::string &partition, bool is_tmp, bool convert,
7613 std::string &dict_name) {
7614 dict_name.clear();
7615 std::string conv_str;
7616
7617 /* Check and append schema name. */
7618 if (!schema.empty()) {
7619 conv_str.assign(schema);
7620 /* Convert schema name. */
7621 if (convert) {
7622 table_to_file(conv_str);
7623 }
7624 dict_name.append(conv_str);
7625 dict_name.append(SCHEMA_SEPARATOR);
7626 }
7627
7628 conv_str.assign(table);
7629 /* Convert table name. */
7630 if (convert) {
7631 table_to_file(conv_str);
7632 }
7633 dict_name.append(conv_str);
7634
7635 /* Check and assign partition string. Any conversion for partition
7636 and sub-partition is already done while building partition string. */
7637 if (!partition.empty()) {
7638 dict_name.append(partition);
7639 }
7640
7641 /* Check and append temporary extension. */
7642 if (is_tmp) {
7643 dict_name.append(TMP_POSTFIX);
7644 }
7645 }
7646
7647 /** Build partition string from partition and sub-partition name
7648 @param[in] part partition name
7649 @param[in] sub_part sub-partition name
7650 @param[in] conv callback to convert partition/sub-partition name
7651 @param[in] is_57 if 5.7 style partition name is needed
7652 @param[out] partition partition string for dictionary table name */
7653 static void build_partition_low(const std::string part,
7654 const std::string sub_part, Convert_Func conv,
7655 bool is_57, std::string &partition) {
7656 partition.clear();
7657 std::string conv_str;
7658
7659 if (part.empty()) {
7660 ut_d(ut_error);
7661 ut_o(return);
7662 }
7663
7664 /* Get partition separator strings */
7665 std::string part_sep;
7666 std::string sub_part_sep;
7667
7668 get_partition_separators(is_57, part_sep, sub_part_sep);
7669
7670 /* Append separator and partition. */
7671 partition.append(part_sep);
7672
7673 conv_str.assign(part);
7674 if (conv) {
7675 conv(conv_str);
7676 }
7677 partition.append(conv_str);
7678
7679 if (sub_part.empty()) {
7680 return;
7681 }
7682
7683 /* Append separator and sub-partition. */
7684 partition.append(sub_part_sep);
7685
7686 conv_str.assign(sub_part);
7687 if (conv) {
7688 conv(conv_str);
7689 }
7690 partition.append(conv_str);
7691 }
7692
7693 /** Get partition and sub-partition name from DD. We convert the names to
7694 lower case.
7695 @param[in] dd_part partition object from DD
7696 @param[in] lower_case convert to lower case name
7697 @param[out] part_name partition name
7698 @param[out] sub_name sub-partition name */
7699 static void get_part_from_dd(const dd::Partition *dd_part, bool lower_case,
7700 std::string &part_name, std::string &sub_name) {
7701 /* Assume sub-partition and get the parent partition. */
7702 auto sub_part = dd_part;
7703 auto part = sub_part->parent();
7704
7705 /* If parent is null then there is no sub-partition. */
7706 if (part == nullptr) {
7707 part = dd_part;
7708 sub_part = nullptr;
7709 }
7710
7711 ut_ad(part->name().length() < FN_REFLEN);
7712
7713 part_name.assign(part->name().c_str());
7714 /* Convert partition name to lower case. */
7715 if (lower_case) {
7716 to_lower(part_name);
7717 }
7718
7719 sub_name.clear();
7720 if (sub_part != nullptr) {
7721 ut_ad(sub_part->name().length() < FN_REFLEN);
7722
7723 sub_name.assign(sub_part->name().c_str());
7724 /* Convert sub-partition name to lower case. */
7725 if (lower_case) {
7726 to_lower(sub_name);
7727 }
7728 }
7729 }
7730
7731 void build_partition(const dd::Partition *dd_part, std::string &partition) {
7732 std::string part_name;
7733 std::string sub_name;
7734
7735 /* Extract partition and sub-partition name from DD. */
7736 get_part_from_dd(dd_part, true, part_name, sub_name);
7737
7738 /* Build partition string after converting names. */
7739 build_partition_low(part_name, sub_name, table_to_file, false, partition);
7740 }
7741
7742 void build_57_partition(const dd::Partition *dd_part, std::string &partition) {
7743 std::string part_name;
7744 std::string sub_name;
7745
7746 /* Extract partition and sub-partition name from DD. In 5.7, partition and
7747 sub-partition names are kept in same letter case as given by user. */
7748 bool lower_case = false;
7749
7750 /* On windows, 5.7 partition sub-partition names are in lower case always. */
7751 #ifdef _WIN32
7752 lower_case = true;
7753 #endif /* _WIN32 */
7754
7755 get_part_from_dd(dd_part, lower_case, part_name, sub_name);
7756
7757 /* Build partition string after converting names. */
7758 build_partition_low(part_name, sub_name, table_to_file, true, partition);
7759 }
7760
7761 bool match_partition(const std::string &dict_name,
7762 const dd::Partition *dd_part) {
7763 std::string dd_partition;
7764
7765 /* Extract partition and sub-partition name from DD. */
7766 build_partition(dd_part, dd_partition);
7767
7768 std::string schema;
7769 std::string table;
7770 bool is_tmp;
7771 std::string partition;
7772
7773 /* Extract schema, table and partition string without conversion. */
7774 get_table(dict_name, false, schema, table, partition, is_tmp);
7775
7776 #ifdef UNIV_DEBUG
7777 /* Innodb dictionary name should already be in lower case. */
7778 ut_ad(partition.length() < FN_REFLEN);
7779
7780 char partition_string[FN_REFLEN];
7781 auto part_len = partition.copy(&partition_string[0], FN_REFLEN - 1);
7782 partition_string[part_len] = '\0';
7783
7784 innobase_casedn_path(&partition_string[0]);
7785 std::string lower_case_str(&partition_string[0]);
7786
7787 ut_ad(partition.compare(lower_case_str) == 0);
7788 #endif /* UNIV_DEBUG */
7789
7790 /* Match the string from DD and innodb dictionary. */
7791 return (dd_partition.compare(partition) == 0);
7792 }
7793
7794 /** Get table and partition string in system cs from dictionary name.
7795 @param[in] dict_name table name in dictionary
7796 @param[out] schema schema name
7797 @param[out] table table name
7798 @param[out] partition partition string
7799 @param[out] is_tmp true, if temporary table created by DDL */
7800 static void get_table_parts(const std::string &dict_name, std::string &schema,
7801 std::string &table, std::string &partition,
7802 bool &is_tmp) {
7803 /* Extract schema, table and partition string converting to system cs. */
7804 get_table(dict_name, true, schema, table, partition, is_tmp);
7805
7806 if (!partition.empty()) {
7807 std::string part;
7808 std::string sub_part;
7809
7810 /* Extract partition details converting to system cs. */
7811 get_partition(partition, true, part, sub_part);
7812
7813 /* During upgrade from 5.7 it is possible to have upper case
7814 names from SYS tables. */
7815 if (srv_is_upgrade_mode) {
7816 to_lower(part);
7817 to_lower(sub_part);
7818 }
7819
7820 #ifdef UNIV_DEBUG
7821 /* Validate that the names are in lower case. */
7822 std::string save_part(part);
7823 to_lower(part);
7824 ut_ad(save_part.compare(part) == 0);
7825
7826 std::string save_sub_part(sub_part);
7827 to_lower(sub_part);
7828 ut_ad(save_sub_part.compare(sub_part) == 0);
7829 #endif // UNIV_DEBUG
7830
7831 /* Build partition string. No conversion required. */
7832 partition.clear();
7833 build_partition_low(part, sub_part, nullptr, false, partition);
7834 }
7835 }
7836
7837 void convert_to_space(std::string &dict_name) {
7838 std::string schema;
7839 std::string table;
7840 std::string partition;
7841 bool is_tmp = false;
7842
7843 /* Get all table parts converted to system cs. */
7844 get_table_parts(dict_name, schema, table, partition, is_tmp);
7845
7846 /* For lower case file systems, schema and table name are converted
7847 to lower case before generating tablespace name. Skip for general
7848 table space i.e. schema is empty. */
7849 if (lower_case_file_system && !schema.empty()) {
7850 ut_ad(lower_case_table_names != 0);
7851 to_lower(schema);
7852 to_lower(table);
7853 }
7854
7855 /* Build the space name. No conversion required. */
7856 dict_name.clear();
7857 build_table(schema, table, partition, is_tmp, false, dict_name);
7858
7859 ut_ad(dict_name.length() < dict_name::MAX_SPACE_NAME_LEN);
7860 }
7861
7862 void rebuild_space(const std::string &dict_name, std::string &space_name) {
7863 std::string schema;
7864 std::string table;
7865 std::string partition;
7866 bool is_tmp = false;
7867
7868 /* Get all table parts converted to system cs. */
7869 get_table_parts(dict_name, schema, table, partition, is_tmp);
7870
7871 if (is_tmp) {
7872 partition.append(TMP_POSTFIX);
7873 }
7874
7875 auto part_len = partition.length();
7876 auto space_len = space_name.length();
7877
7878 ut_ad(space_len > part_len);
7879
7880 if (space_len > part_len) {
7881 auto part_pos = space_len - part_len;
7882
7883 std::string space_part = space_name.substr(part_pos);
7884 if (space_part.compare(partition) == 0) {
7885 return;
7886 }
7887 space_name.replace(part_pos, std::string::npos, partition);
7888 }
7889 }
7890
7891 void rebuild(std::string &dict_name) {
7892 std::string schema;
7893 std::string table;
7894 std::string partition;
7895 bool is_tmp = false;
7896
7897 /* Conversion is needed only for partitioned table. */
7898 if (!is_partition(dict_name)) {
7899 return;
7900 }
7901
7902 /* Extract schema, table and partition string without conversion. */
7903 get_table(dict_name, false, schema, table, partition, is_tmp);
7904
7905 if (!partition.empty()) {
7906 std::string part;
7907 std::string sub_part;
7908
7909 /* Extract partition details converting to system cs. */
7910 get_partition(partition, true, part, sub_part);
7911
7912 /* Convert partition names to lower case. */
7913 to_lower(part);
7914 to_lower(sub_part);
7915
7916 /* Build partition string converting to file cs. */
7917 partition.clear();
7918 build_partition_low(part, sub_part, table_to_file, false, partition);
7919 }
7920
7921 /* Re-build the table name. No cs conversion required. */
7922 dict_name.clear();
7923 build_table(schema, table, partition, is_tmp, false, dict_name);
7924 }
7925
7926 } // namespace dict_name
7927 #endif /* !UNIV_HOTBACKUP */