Debian Codegraph @

storage/innobase/handler/handler0alter.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2005, 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 handler/handler0alter.cc
29 Smart ALTER TABLE
30 *******************************************************/
31
32 /* Include necessary SQL headers */
33 #include <assert.h>
34 #include <current_thd.h>
35 #include <debug_sync.h>
36 #include <key_spec.h>
37 #include <log.h>
38 #include <my_bit.h>
39 #include <mysql/plugin.h>
40 #include <sql_class.h>
41 #include <sql_lex.h>
42 #include <sql_table.h>
43 #include <sql_thd_internal_api.h>
44 #include <sys/types.h>
45 #include "ha_prototypes.h"
46
47 #include "dd/cache/dictionary_client.h"
48 #include "dd/dd.h"
49 #include "dd/dictionary.h"
50 #include "dd/impl/properties_impl.h"
51 #include "dd/impl/types/column_impl.h"
52 #include "dd/properties.h"
53 #include "dd/types/column.h"
54 #include "dd/types/column_type_element.h"
55 #include "dd/types/index.h"
56 #include "dd/types/index_element.h"
57 #include "dd/types/partition.h"
58 #include "dd/types/partition_index.h"
59 #include "dd/types/table.h"
60 #include "dd/types/tablespace_file.h"
61 #include "dd_table_share.h"
62
63 #include "btr0sea.h"
64 #include "dict0crea.h"
65 #include "dict0dd.h"
66 #include "dict0dict.h"
67 #include "dict0inst.h" //Instant DDL
68 #include "dict0priv.h"
69 #include "dict0stats.h"
70 #include "dict0stats_bg.h"
71 #include "fsp0sysspace.h"
72 #include "fts0plugin.h"
73 #include "fts0priv.h"
74 #include "ha_innodb.h"
75 #include "ha_innopart.h"
76 #include "ha_prototypes.h"
77 #include "handler0alter.h"
78 #include "lex_string.h"
79 #include "log0buf.h"
80 #include "log0chkp.h"
81
82 #include "my_dbug.h"
83 #include "my_io.h"
84
85 #include "clone0api.h"
86 #include "ddl0ddl.h"
87 #include "dict0dd.h"
88 #include "fts0plugin.h"
89 #include "fts0priv.h"
90 #include "handler0alter.h"
91 #include "lock0lock.h"
92 #include "pars0pars.h"
93 #include "partition_info.h"
94 #include "rem0types.h"
95 #include "row0ins.h"
96 #include "row0log.h"
97 #include "row0sel.h"
98 #include "sql/create_field.h"
99 #include "srv0mon.h"
100 #include "trx0roll.h"
101 #include "trx0trx.h"
102 #include "ut0new.h"
103 #include "ut0stage.h"
104
105 /* For supporting Native InnoDB Partitioning. */
106 #include "ha_innopart.h"
107 #include "partition_info.h"
108
109 /** Function to convert the Instant_Type to a comparable int */
110 inline uint16_t instant_type_to_int(Instant_Type type) {
111 return (static_cast<typename std::underlying_type<Log_Type>::type>(type));
112 }
113
114 /** Operations for creating secondary indexes (no rebuild needed) */
115 static const Alter_inplace_info::HA_ALTER_FLAGS INNOBASE_ONLINE_CREATE =
116 Alter_inplace_info::ADD_INDEX | Alter_inplace_info::ADD_UNIQUE_INDEX |
117 Alter_inplace_info::ADD_SPATIAL_INDEX;
118
119 /** Operations for rebuilding a table in place */
120 static const Alter_inplace_info::HA_ALTER_FLAGS INNOBASE_ALTER_REBUILD =
121 Alter_inplace_info::ADD_PK_INDEX | Alter_inplace_info::DROP_PK_INDEX |
122 Alter_inplace_info::CHANGE_CREATE_OPTION
123 /* CHANGE_CREATE_OPTION needs to check innobase_need_rebuild() */
124 | Alter_inplace_info::ALTER_COLUMN_NULLABLE |
125 Alter_inplace_info::ALTER_COLUMN_NOT_NULLABLE |
126 Alter_inplace_info::ALTER_STORED_COLUMN_ORDER |
127 Alter_inplace_info::DROP_STORED_COLUMN |
128 Alter_inplace_info::ADD_STORED_BASE_COLUMN
129 /* ADD_STORED_BASE_COLUMN needs to check innobase_need_rebuild() */
130 | Alter_inplace_info::RECREATE_TABLE;
131
132 /** Operations that require changes to data */
133 static const Alter_inplace_info::HA_ALTER_FLAGS INNOBASE_ALTER_DATA =
134 INNOBASE_ONLINE_CREATE | INNOBASE_ALTER_REBUILD;
135
136 /** Operations for altering a table that InnoDB does not care about */
137 static const Alter_inplace_info::HA_ALTER_FLAGS INNOBASE_INPLACE_IGNORE =
138 Alter_inplace_info::ALTER_COLUMN_DEFAULT |
139 Alter_inplace_info::ALTER_COLUMN_COLUMN_FORMAT |
140 Alter_inplace_info::ALTER_COLUMN_STORAGE_TYPE |
141 Alter_inplace_info::ALTER_RENAME | Alter_inplace_info::CHANGE_INDEX_OPTION |
142 Alter_inplace_info::ADD_CHECK_CONSTRAINT |
143 Alter_inplace_info::DROP_CHECK_CONSTRAINT |
144 Alter_inplace_info::SUSPEND_CHECK_CONSTRAINT |
145 Alter_inplace_info::ALTER_COLUMN_VISIBILITY;
146
147 /** Operation allowed with ALGORITHM=INSTANT */
148 static const Alter_inplace_info::HA_ALTER_FLAGS INNOBASE_INSTANT_ALLOWED =
149 Alter_inplace_info::ALTER_COLUMN_NAME |
150 Alter_inplace_info::ADD_VIRTUAL_COLUMN |
151 Alter_inplace_info::DROP_VIRTUAL_COLUMN |
152 Alter_inplace_info::ALTER_VIRTUAL_COLUMN_ORDER |
153 Alter_inplace_info::ADD_STORED_BASE_COLUMN |
154 Alter_inplace_info::ALTER_STORED_COLUMN_ORDER |
155 Alter_inplace_info::DROP_STORED_COLUMN;
156
157 /** Operations on foreign key definitions (changing the schema only) */
158 static const Alter_inplace_info::HA_ALTER_FLAGS INNOBASE_FOREIGN_OPERATIONS =
159 Alter_inplace_info::DROP_FOREIGN_KEY | Alter_inplace_info::ADD_FOREIGN_KEY;
160
161 /** Operations that InnoDB cares about and can perform without rebuild */
162 static const Alter_inplace_info::HA_ALTER_FLAGS INNOBASE_ALTER_NOREBUILD =
163 INNOBASE_ONLINE_CREATE | INNOBASE_FOREIGN_OPERATIONS |
164 Alter_inplace_info::DROP_INDEX | Alter_inplace_info::DROP_UNIQUE_INDEX |
165 Alter_inplace_info::RENAME_INDEX | Alter_inplace_info::ALTER_COLUMN_NAME |
166 Alter_inplace_info::ALTER_COLUMN_EQUAL_PACK_LENGTH |
167 Alter_inplace_info::ALTER_INDEX_COMMENT |
168 Alter_inplace_info::ADD_VIRTUAL_COLUMN |
169 Alter_inplace_info::DROP_VIRTUAL_COLUMN |
170 Alter_inplace_info::ALTER_VIRTUAL_COLUMN_ORDER |
171 Alter_inplace_info::ALTER_COLUMN_INDEX_LENGTH;
172
173 struct ha_innobase_inplace_ctx : public inplace_alter_handler_ctx {
174 /** Dummy query graph */
175 que_thr_t *thr;
176 /** The prebuilt struct of the creating instance */
177 row_prebuilt_t *prebuilt;
178 /** InnoDB indexes being created */
179 dict_index_t **add_index;
180 /** MySQL key numbers for the InnoDB indexes that are being created */
181 const ulint *add_key_numbers;
182 /** number of InnoDB indexes being created */
183 ulint num_to_add_index;
184 /** InnoDB indexes being dropped */
185 dict_index_t **drop_index;
186 /** number of InnoDB indexes being dropped */
187 const ulint num_to_drop_index;
188 /** InnoDB indexes being renamed */
189 dict_index_t **rename;
190 /** number of InnoDB indexes being renamed */
191 const ulint num_to_rename;
192 /** InnoDB foreign key constraints being dropped */
193 dict_foreign_t **drop_fk;
194 /** number of InnoDB foreign key constraints being dropped */
195 const ulint num_to_drop_fk;
196 /** InnoDB foreign key constraints being added */
197 dict_foreign_t **add_fk;
198 /** number of InnoDB foreign key constraints being dropped */
199 const ulint num_to_add_fk;
200 /** whether to create the indexes online */
201 bool online;
202 /** memory heap */
203 mem_heap_t *heap;
204 /** dictionary transaction */
205 trx_t *trx;
206 /** original table (if rebuilt, differs from indexed_table) */
207 dict_table_t *old_table;
208 /** table where the indexes are being created or dropped */
209 dict_table_t *new_table;
210 /** mapping of old column numbers to new ones, or NULL */
211 const ulint *col_map;
212 /** new column names, or NULL if nothing was renamed */
213 const char **col_names;
214 /** added AUTO_INCREMENT column position, or ULINT_UNDEFINED */
215 const ulint add_autoinc;
216 /** default values of ADD COLUMN, or NULL */
217 const dtuple_t *add_cols;
218 /** autoinc sequence to use */
219 ddl::Sequence sequence;
220 /** maximum auto-increment value */
221 ulonglong max_autoinc;
222 /** temporary table name to use for old table when renaming tables */
223 const char *tmp_name;
224 /** whether the order of the clustered index is unchanged */
225 bool skip_pk_sort;
226 /** virtual columns to be added */
227 dict_v_col_t *add_vcol;
228 const char **add_vcol_name;
229 /** virtual columns to be dropped */
230 dict_v_col_t *drop_vcol;
231 const char **drop_vcol_name;
232 /** ALTER TABLE stage progress recorder */
233 Alter_stage *m_stage;
234 /** FTS AUX Tables to drop */
235 aux_name_vec_t *fts_drop_aux_vec;
236
237 ha_innobase_inplace_ctx(row_prebuilt_t *prebuilt_arg, dict_index_t **drop_arg,
238 ulint num_to_drop_arg, dict_index_t **rename_arg,
239 ulint num_to_rename_arg, dict_foreign_t **drop_fk_arg,
240 ulint num_to_drop_fk_arg, dict_foreign_t **add_fk_arg,
241 ulint num_to_add_fk_arg, bool online_arg,
242 mem_heap_t *heap_arg, dict_table_t *new_table_arg,
243 const char **col_names_arg, ulint add_autoinc_arg,
244 ulonglong autoinc_col_min_value_arg,
245 ulonglong autoinc_col_max_value_arg)
246 : inplace_alter_handler_ctx(),
247 prebuilt(prebuilt_arg),
248 add_index(nullptr),
249 add_key_numbers(nullptr),
250 num_to_add_index(0),
251 drop_index(drop_arg),
252 num_to_drop_index(num_to_drop_arg),
253 rename(rename_arg),
254 num_to_rename(num_to_rename_arg),
255 drop_fk(drop_fk_arg),
256 num_to_drop_fk(num_to_drop_fk_arg),
257 add_fk(add_fk_arg),
258 num_to_add_fk(num_to_add_fk_arg),
259 online(online_arg),
260 heap(heap_arg),
261 trx(nullptr),
262 old_table(prebuilt_arg->table),
263 new_table(new_table_arg),
264 col_map(nullptr),
265 col_names(col_names_arg),
266 add_autoinc(add_autoinc_arg),
267 add_cols(nullptr),
268 sequence(prebuilt->trx->mysql_thd, autoinc_col_min_value_arg,
269 autoinc_col_max_value_arg),
270 max_autoinc(0),
271 tmp_name(nullptr),
272 skip_pk_sort(false),
273 add_vcol(nullptr),
274 add_vcol_name(nullptr),
275 drop_vcol(nullptr),
276 drop_vcol_name(nullptr),
277 m_stage(nullptr),
278 fts_drop_aux_vec(nullptr) {
279 #ifdef UNIV_DEBUG
280 for (ulint i = 0; i < num_to_add_index; i++) {
281 ut_ad(!add_index[i]->to_be_dropped);
282 }
283 for (ulint i = 0; i < num_to_drop_index; i++) {
284 ut_ad(drop_index[i]->to_be_dropped);
285 }
286 #endif /* UNIV_DEBUG */
287
288 thr = pars_complete_graph_for_exec(nullptr, prebuilt->trx, heap, prebuilt);
289 }
290
291 ~ha_innobase_inplace_ctx() override {
292 if (fts_drop_aux_vec != nullptr) {
293 fts_free_aux_names(fts_drop_aux_vec);
294 delete fts_drop_aux_vec;
295 }
296 ut::delete_(m_stage);
297 mem_heap_free(heap);
298 }
299
300 /** Determine if the table will be rebuilt.
301 @return whether the table will be rebuilt */
302 bool need_rebuild() const { return (old_table != new_table); }
303
304 /** Set shared data between the passed in handler context
305 and current context.
306 @param[in] ctx handler context */
307 void set_shared_data(const inplace_alter_handler_ctx *ctx) override {
308 ut_ad(ctx != nullptr);
309 if (add_autoinc == ULINT_UNDEFINED) {
310 return;
311 }
312 const ha_innobase_inplace_ctx *ha_ctx =
313 static_cast<const ha_innobase_inplace_ctx *>(ctx);
314
315 /* In InnoDB table, if it's adding AUTOINC column,
316 the sequence value should be shared among contexts */
317 ut_ad(ha_ctx->add_autoinc != ULINT_UNDEFINED);
318 sequence = ha_ctx->sequence;
319 }
320
321 private:
322 // Disable copying
323 ha_innobase_inplace_ctx(const ha_innobase_inplace_ctx &);
324 ha_innobase_inplace_ctx &operator=(const ha_innobase_inplace_ctx &);
325 };
326
327 /** Structure to remember table information for updating DD */
328 struct alter_table_old_info_t {
329 /** Constructor */
330 alter_table_old_info_t() : m_discarded(), m_fts_doc_id(), m_rebuild() {}
331
332 /** If old table is discarded one */
333 bool m_discarded;
334
335 /** If old table has FTS DOC ID */
336 bool m_fts_doc_id;
337
338 /** If this ATLER TABLE requires rebuild */
339 bool m_rebuild;
340
341 /** Update the old table information
342 @param[in] old_table Old InnoDB table object
343 @param[in] rebuild True if rebuild is necessary */
344 void update(const dict_table_t *old_table, bool rebuild) {
345 m_discarded = dict_table_is_discarded(old_table);
346 m_fts_doc_id = DICT_TF2_FLAG_IS_SET(old_table, DICT_TF2_FTS_HAS_DOC_ID);
347 m_rebuild = rebuild;
348 }
349 };
350
351 /* Report an InnoDB error to the client by invoking my_error(). */
352 static UNIV_COLD void my_error_innodb(
353 dberr_t error, /*!< in: InnoDB error code */
354 const char *table, /*!< in: table name */
355 uint32_t flags) /*!< in: table flags */
356 {
357 switch (error) {
358 case DB_MISSING_HISTORY:
359 my_error(ER_TABLE_DEF_CHANGED, MYF(0));
360 break;
361 case DB_RECORD_NOT_FOUND:
362 my_error(ER_KEY_NOT_FOUND, MYF(0), table);
363 break;
364 case DB_DEADLOCK:
365 my_error(ER_LOCK_DEADLOCK, MYF(0));
366 break;
367 case DB_LOCK_WAIT_TIMEOUT:
368 my_error(ER_LOCK_WAIT_TIMEOUT, MYF(0));
369 break;
370 case DB_INTERRUPTED:
371 my_error(ER_QUERY_INTERRUPTED, MYF(0));
372 break;
373 case DB_OUT_OF_MEMORY:
374 my_error(ER_OUT_OF_RESOURCES, MYF(0));
375 break;
376 case DB_OUT_OF_FILE_SPACE:
377 my_error(ER_RECORD_FILE_FULL, MYF(0), table);
378 break;
379 case DB_OUT_OF_DISK_SPACE:
380 my_error(ER_DISK_FULL_NOWAIT, MYF(0), table);
381 break;
382 case DB_TEMP_FILE_WRITE_FAIL:
383 my_error(ER_TEMP_FILE_WRITE_FAILURE, MYF(0));
384 break;
385 case DB_TOO_BIG_INDEX_COL:
386 my_error(ER_INDEX_COLUMN_TOO_LONG, MYF(0),
387 DICT_MAX_FIELD_LEN_BY_FORMAT_FLAG(flags));
388 break;
389 case DB_TOO_MANY_CONCURRENT_TRXS:
390 my_error(ER_TOO_MANY_CONCURRENT_TRXS, MYF(0));
391 break;
392 case DB_LOCK_TABLE_FULL:
393 my_error(ER_LOCK_TABLE_FULL, MYF(0));
394 break;
395 case DB_UNDO_RECORD_TOO_BIG:
396 my_error(ER_UNDO_RECORD_TOO_BIG, MYF(0));
397 break;
398 case DB_CORRUPTION:
399 my_error(ER_NOT_KEYFILE, MYF(0), table);
400 break;
401 case DB_TOO_BIG_RECORD:
402 /* We limit max record size to 16k for 64k page size. */
403 my_error(ER_TOO_BIG_ROWSIZE, MYF(0),
404 srv_page_size == UNIV_PAGE_SIZE_MAX
405 ? REC_MAX_DATA_SIZE - 1
406 : page_get_free_space_of_empty(flags & DICT_TF_COMPACT) / 2);
407 break;
408 case DB_INVALID_NULL:
409 /* TODO: report the row, as we do for DB_DUPLICATE_KEY */
410 my_error(ER_INVALID_USE_OF_NULL, MYF(0));
411 break;
412 case DB_CANT_CREATE_GEOMETRY_OBJECT:
413 my_error(ER_CANT_CREATE_GEOMETRY_OBJECT, MYF(0));
414 break;
415 case DB_TABLESPACE_EXISTS:
416 my_error(ER_TABLESPACE_EXISTS, MYF(0), table);
417 break;
418
419 #ifdef UNIV_DEBUG
420 case DB_SUCCESS:
421 case DB_DUPLICATE_KEY:
422 case DB_ONLINE_LOG_TOO_BIG:
423 /* These codes should not be passed here. */
424 ut_error;
425 #endif /* UNIV_DEBUG */
426 default:
427 my_error(ER_GET_ERRNO, MYF(0), error, "InnoDB error");
428 break;
429 }
430 }
431
432 /** Determine if fulltext indexes exist in a given table.
433 @param table MySQL table
434 @return whether fulltext indexes exist on the table */
435 static bool innobase_fulltext_exist(const TABLE *table) {
436 for (uint i = 0; i < table->s->keys; i++) {
437 if (table->key_info[i].flags & HA_FULLTEXT) {
438 return (true);
439 }
440 }
441
442 return (false);
443 }
444
445 /** Determine if spatial indexes exist in a given table.
446 @param table MySQL table
447 @return whether spatial indexes exist on the table */
448 static bool innobase_spatial_exist(const TABLE *table) {
449 for (uint i = 0; i < table->s->keys; i++) {
450 if (table->key_info[i].flags & HA_SPATIAL) {
451 return (true);
452 }
453 }
454
455 return (false);
456 }
457
458 /** Get col in new table def of renamed column.
459 @param[in] ha_alter_info inplace alter info
460 @param[in] old_dd_column column in old table
461 @param[in] new_dd_tab new table definition
462 @return column if renamed, NULL otherwise */
463 static dd::Column *get_renamed_col(const Alter_inplace_info *ha_alter_info,
464 const dd::Column *old_dd_column,
465 const dd::Table *new_dd_tab) {
466 List_iterator_fast<Create_field> cf_it(
467 ha_alter_info->alter_info->create_list);
468 cf_it.rewind();
469 Create_field *cf;
470 while ((cf = cf_it++) != nullptr) {
471 if (cf->field && cf->field->is_flag_set(FIELD_IS_RENAMED) &&
472 innobase_strcasecmp(cf->change, old_dd_column->name().c_str()) == 0) {
473 /* This column is being renamed */
474 return (const_cast<dd::Column *>(
475 dd_find_column(&new_dd_tab->table(), cf->field_name)));
476 }
477 }
478
479 return nullptr;
480 }
481
482 /** Get the number of columns being added using ALTER TABLE.
483 @param[in] ha_alter_info inplace alter info
484 @return number of columns added using ALTER TABLE */
485 static uint32_t get_num_cols_added(const Alter_inplace_info *ha_alter_info) {
486 uint32_t n_cols_added = 0;
487
488 /* create_list is list of old columns (CREATE) and new columns (ALTER .. ADD)
489 */
490 for (const Create_field &new_field : ha_alter_info->alter_info->create_list) {
491 /* field contains column information for old columns (CREATE) */
492 /* field is nullptr for new columns (ALTER .. ADD) */
493 if (new_field.field == nullptr) {
494 n_cols_added++;
495 }
496 }
497
498 return n_cols_added;
499 }
500
501 /** Copy metadata of dd::Table and dd::Columns from old table to new table.
502 This is done during inplce alter table when table is not rebuilt.
503 @param[in] ha_alter_info inplace alter info
504 @param[in] old_dd_tab old table definition
505 @param[in,out] new_dd_tab new table definition */
506 static void dd_inplace_alter_copy_instant_metadata(
507 const Alter_inplace_info *ha_alter_info, const dd::Table *old_dd_tab,
508 dd::Table *new_dd_tab) {
509 if (!dd_table_has_row_versions(*old_dd_tab)) {
510 return;
511 }
512
513 /* Copy col phy pos from old DD table to new DD table */
514 for (auto old_dd_column : old_dd_tab->columns()) {
515 const char *s = dd_column_key_strings[DD_INSTANT_VERSION_DROPPED];
516 if (old_dd_column->se_private_data().exists(s)) {
517 uint32_t v_dropped = UINT32_UNDEFINED;
518 old_dd_column->se_private_data().get(s, &v_dropped);
519 if (v_dropped > 0) {
520 /* Dropped column will be copied after the loop. Skip for now. */
521 continue;
522 }
523 }
524
525 /* The column might have been renamed */
526 dd::Column *new_dd_column =
527 get_renamed_col(ha_alter_info, old_dd_column, new_dd_tab);
528 if (new_dd_column == nullptr) {
529 /* Get corresponding dd::column in new table if not renamed */
530 new_dd_column = const_cast<dd::Column *>(
531 dd_find_column(new_dd_tab, old_dd_column->name().c_str()));
532 }
533
534 if (new_dd_column == nullptr) {
535 /* This column must have been dropped */
536 continue;
537 }
538
539 if (new_dd_column->is_virtual()) {
540 continue;
541 }
542
543 auto fn = [&](const char *s, auto &value) {
544 if (old_dd_column->se_private_data().exists(s)) {
545 old_dd_column->se_private_data().get(s, &value);
546 new_dd_column->se_private_data().set(s, value);
547 }
548 };
549
550 /* Copy phy pos for column */
551 uint32_t phy_pos = UINT32_UNDEFINED;
552 s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
553 ut_ad(old_dd_column->se_private_data().exists(s));
554 fn(s, phy_pos);
555
556 /* copy version added */
557 uint32_t v_added = UINT32_UNDEFINED;
558 s = dd_column_key_strings[DD_INSTANT_VERSION_ADDED];
559 fn(s, v_added);
560
561 /* Copy instant default values for INSTANT ADD columns */
562 s = dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL];
563 if (old_dd_column->se_private_data().exists(s)) {
564 ut_ad(v_added > 0);
565 bool value = false;
566 fn(s, value);
567 } else {
568 s = dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT];
569 if (old_dd_column->se_private_data().exists(s)) {
570 ut_ad(v_added > 0);
571 dd::String_type value;
572 fn(s, value);
573 } else {
574 /* This columns is not INSTANT ADD */
575 ut_ad(v_added == UINT32_UNDEFINED);
576 }
577 }
578 }
579
580 if (dd_table_has_instant_drop_cols(*old_dd_tab)) {
581 /* Add INSTANT dropped column from old_dd_tab to new_dd_tab */
582 copy_dropped_columns(old_dd_tab, new_dd_tab, UINT32_UNDEFINED);
583 }
584 }
585
586 /** Check if virtual column in old and new table are in order, excluding
587 those dropped column. This is needed because when we drop a virtual column,
588 ALTER_VIRTUAL_COLUMN_ORDER is also turned on, so we can't decide if this
589 is a real ORDER change or just DROP COLUMN
590 @param[in] table old TABLE
591 @param[in] altered_table new TABLE
592 @param[in] ha_alter_info Structure describing changes to be done
593 by ALTER TABLE and holding data used during in-place alter.
594 @return true is all columns in order, false otherwise. */
595 static bool check_v_col_in_order(const TABLE *table, const TABLE *altered_table,
596 const Alter_inplace_info *ha_alter_info) {
597 ulint j = 0;
598
599 /* We don't support any adding new virtual column before
600 existed virtual column. */
601 if (ha_alter_info->handler_flags & Alter_inplace_info::ADD_VIRTUAL_COLUMN) {
602 bool has_new = false;
603
604 List_iterator_fast<Create_field> cf_it(
605 ha_alter_info->alter_info->create_list);
606
607 cf_it.rewind();
608
609 while (const Create_field *new_field = cf_it++) {
610 if (!new_field->is_virtual_gcol()) {
611 /* We do not support add virtual col
612 before autoinc column */
613 if (has_new && (new_field->flags & AUTO_INCREMENT_FLAG)) {
614 return (false);
615 }
616 continue;
617 }
618
619 /* Found a new added virtual column. */
620 if (!new_field->field) {
621 has_new = true;
622 continue;
623 }
624
625 /* If there's any old virtual column
626 after the new added virtual column,
627 order must be changed. */
628 if (has_new) {
629 return (false);
630 }
631 }
632 }
633
634 /* directly return true if ALTER_VIRTUAL_COLUMN_ORDER is not on */
635 if (!(ha_alter_info->handler_flags &
636 Alter_inplace_info::ALTER_VIRTUAL_COLUMN_ORDER)) {
637 return (true);
638 }
639
640 for (ulint i = 0; i < table->s->fields; i++) {
641 Field *field = table->s->field[i];
642 bool dropped = false;
643
644 if (field->stored_in_db) {
645 continue;
646 }
647
648 ut_ad(innobase_is_v_fld(field));
649
650 /* Check if this column is in drop list */
651 for (const Alter_drop *drop : ha_alter_info->alter_info->drop_list) {
652 if (drop->type == Alter_drop::COLUMN &&
653 my_strcasecmp(system_charset_info, field->field_name, drop->name) ==
654 0) {
655 dropped = true;
656 break;
657 }
658 }
659
660 if (dropped) {
661 continue;
662 }
663
664 /* Now check if the next virtual column in altered table
665 matches this column */
666 while (j < altered_table->s->fields) {
667 Field *new_field = altered_table->s->field[j];
668
669 if (new_field->stored_in_db) {
670 j++;
671 continue;
672 }
673
674 if (my_strcasecmp(system_charset_info, field->field_name,
675 new_field->field_name) != 0) {
676 /* different column */
677 return (false);
678 } else {
679 j++;
680 break;
681 }
682 }
683
684 if (j > altered_table->s->fields) {
685 /* there should not be less column in new table
686 without them being in drop list */
687 ut_d(ut_error);
688 ut_o(return (false));
689 }
690 }
691
692 return (true);
693 }
694
695 /** Drop the statistics for a specified table, and mark it as discard
696 after DDL
697 @param[in,out] thd THD object
698 @param[in,out] table InnoDB table object */
699 void innobase_discard_table(THD *thd, dict_table_t *table) {
700 char errstr[ERROR_STR_LENGTH];
701 if (dict_stats_drop_table(table->name.m_name, errstr, sizeof(errstr)) !=
702 DB_SUCCESS) {
703 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_ALTER_INFO,
704 "Deleting persistent statistics"
705 " for table '%s' in"
706 " InnoDB failed: %s",
707 table->name.m_name, errstr);
708 }
709
710 table->discard_after_ddl = true;
711 }
712
713 /* To check if renaming a column is ok.
714 @return true if Ok, false otherwise */
715 static bool ok_to_rename_column(const Alter_inplace_info *ha_alter_info,
716 const TABLE *old_table,
717 const TABLE *altered_table,
718 const dict_table_t *dict_table, bool instant,
719 bool report_error) {
720 List_iterator_fast<Create_field> cf_it(
721 ha_alter_info->alter_info->create_list);
722
723 for (Field **fp = old_table->field; *fp; fp++) {
724 if (!(*fp)->is_flag_set(FIELD_IS_RENAMED)) {
725 continue;
726 }
727
728 const char *name = nullptr;
729
730 cf_it.rewind();
731 while (const Create_field *cf = cf_it++) {
732 if (cf->field == *fp) {
733 name = cf->field_name;
734 goto check_if_ok_to_rename;
735 }
736 }
737
738 ut_error;
739 check_if_ok_to_rename:
740 /* Prohibit renaming a column from FTS_DOC_ID
741 if full-text indexes exist. */
742 if (!my_strcasecmp(system_charset_info, (*fp)->field_name,
743 FTS_DOC_ID_COL_NAME) &&
744 innobase_fulltext_exist(altered_table)) {
745 if (report_error) {
746 my_error(ER_INNODB_FT_WRONG_DOCID_COLUMN, MYF(0), name);
747 }
748 return false;
749 }
750
751 /* Prohibit renaming a column to an internal column. */
752 const char *s = dict_table->col_names;
753 unsigned j;
754 /* Skip user columns.
755 MySQL should have checked these already.
756 We want to allow renaming of c1 to c2, c2 to c1. */
757 for (j = 0; j < old_table->s->fields; j++) {
758 if (!innobase_is_v_fld(old_table->field[j])) {
759 s += strlen(s) + 1;
760 }
761 }
762
763 for (; j < dict_table->n_def; j++) {
764 if (!my_strcasecmp(system_charset_info, name, s)) {
765 if (report_error) {
766 my_error(ER_WRONG_COLUMN_NAME, MYF(0), s);
767 }
768 return false;
769 }
770
771 s += strlen(s) + 1;
772 }
773 }
774
775 /* If column being renamed is being referenced by any other table, don't
776 allow INSTANT in that case. */
777 if (instant) {
778 if (!dict_table->referenced_set.empty()) {
779 List_iterator_fast<Create_field> cf_it(
780 ha_alter_info->alter_info->create_list);
781
782 for (Field **fp = old_table->field; *fp; fp++) {
783 if (!(*fp)->is_flag_set(FIELD_IS_RENAMED)) {
784 continue;
785 }
786
787 const char *col_name = (*fp)->field_name;
788
789 for (dict_foreign_set::iterator it = dict_table->referenced_set.begin();
790 it != dict_table->referenced_set.end(); ++it) {
791 dict_foreign_t *foreign = *it;
792
793 for (size_t i = 0; i < foreign->n_fields; ++i) {
794 const char *r_name = foreign->referenced_col_names[i];
795 if (!my_strcasecmp(system_charset_info, r_name, col_name)) {
796 if (report_error) {
797 my_error(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON, MYF(0),
798 "ALGORITHM=INSTANT",
799 innobase_get_err_msg(
800 ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME),
801 "ALGORITHM=INPLACE");
802 }
803 return false;
804 }
805 } /* each column in reference element */
806 } /* each element in reference set */
807 } /* each column being renamed */
808 }
809 }
810
811 return true;
812 }
813
814 /** Determine if one ALTER TABLE can be done instantly on the table
815 @param[in] ha_alter_info The DDL operation
816 @param[in] table InnoDB table
817 @param[in] old_table old TABLE
818 @param[in] altered_table new TABLE
819 @return Instant_Type accordingly */
820 static inline Instant_Type innobase_support_instant(
821 const Alter_inplace_info *ha_alter_info, const dict_table_t *table,
822 const TABLE *old_table, const TABLE *altered_table) {
823 if (!(ha_alter_info->handler_flags & ~INNOBASE_INPLACE_IGNORE)) {
824 return (Instant_Type::INSTANT_NO_CHANGE);
825 }
826
827 Alter_inplace_info::HA_ALTER_FLAGS alter_inplace_flags =
828 ha_alter_info->handler_flags & ~INNOBASE_INPLACE_IGNORE;
829
830 if (alter_inplace_flags & ~INNOBASE_INSTANT_ALLOWED) {
831 return (Instant_Type::INSTANT_IMPOSSIBLE);
832 }
833
834 /* During upgrade, if columns are added in system tables, avoid instant */
835 if (current_thd->is_server_upgrade_thread()) {
836 return (Instant_Type::INSTANT_IMPOSSIBLE);
837 }
838
839 enum class INSTANT_OPERATION {
840 COLUMN_RENAME_ONLY, /*!< Only column RENAME */
841 VIRTUAL_ADD_DROP_ONLY, /*!< Only virtual column ADD AND DROP */
842 VIRTUAL_ADD_DROP_WITH_RENAME, /*!< Virtual column ADD/DROP with RENAME */
843 INSTANT_ADD, /*< INSTANT ADD possibly with virtual column ADD and
844 column RENAME */
845 INSTANT_DROP, /*|< INSTANT DROP possibly with virtual column ADD/DROP and
846 column RENAME */
847 NONE
848 };
849
850 enum INSTANT_OPERATION op = INSTANT_OPERATION::NONE;
851
852 if (!(alter_inplace_flags & ~Alter_inplace_info::ALTER_COLUMN_NAME)) {
853 op = INSTANT_OPERATION::COLUMN_RENAME_ONLY;
854 } else if (!(alter_inplace_flags &
855 ~(Alter_inplace_info::ADD_VIRTUAL_COLUMN |
856 Alter_inplace_info::DROP_VIRTUAL_COLUMN))) {
857 op = INSTANT_OPERATION::VIRTUAL_ADD_DROP_ONLY;
858 } else if (!(alter_inplace_flags &
859 ~(Alter_inplace_info::ADD_VIRTUAL_COLUMN |
860 Alter_inplace_info::DROP_VIRTUAL_COLUMN |
861 Alter_inplace_info::ALTER_COLUMN_NAME))) {
862 op = INSTANT_OPERATION::VIRTUAL_ADD_DROP_WITH_RENAME;
863 } else if (alter_inplace_flags & Alter_inplace_info::ADD_STORED_BASE_COLUMN &&
864 !(alter_inplace_flags & Alter_inplace_info::DROP_VIRTUAL_COLUMN)) {
865 op = INSTANT_OPERATION::INSTANT_ADD;
866 } else if (alter_inplace_flags & Alter_inplace_info::DROP_STORED_COLUMN) {
867 op = INSTANT_OPERATION::INSTANT_DROP;
868 }
869
870 switch (op) {
871 case INSTANT_OPERATION::COLUMN_RENAME_ONLY: {
872 bool report_error = (ha_alter_info->alter_info->requested_algorithm ==
873 Alter_info::ALTER_TABLE_ALGORITHM_INSTANT);
874 if (ok_to_rename_column(ha_alter_info, old_table, altered_table, table,
875 true, report_error)) {
876 return (Instant_Type::INSTANT_COLUMN_RENAME);
877 }
878 } break;
879 case INSTANT_OPERATION::VIRTUAL_ADD_DROP_ONLY:
880 if (check_v_col_in_order(old_table, altered_table, ha_alter_info)) {
881 return (Instant_Type::INSTANT_VIRTUAL_ONLY);
882 }
883 break;
884 case INSTANT_OPERATION::VIRTUAL_ADD_DROP_WITH_RENAME:
885 /* Not supported yet in INPLACE. So not supporting here as well. */
886 break;
887 case INSTANT_OPERATION::INSTANT_DROP:
888 if (!check_v_col_in_order(old_table, altered_table, ha_alter_info)) {
889 break;
890 }
891 [[fallthrough]];
892 case INSTANT_OPERATION::INSTANT_ADD:
893 /* If it's an ADD COLUMN without changing existing stored column orders
894 (change trailing virtual column orders is fine, especially for supporting
895 adding stored columns to a table with functional indexes), or including
896 ADD VIRTUAL COLUMN */
897 if (table->support_instant_add_drop()) {
898 return (Instant_Type::INSTANT_ADD_DROP_COLUMN);
899 }
900 break;
901 case INSTANT_OPERATION::NONE:
902 break;
903 }
904
905 return (Instant_Type::INSTANT_IMPOSSIBLE);
906 }
907
908 /** Determine if this is an instant ALTER TABLE.
909 This can be checked in *inplace_alter_table() functions, which are called
910 after check_if_supported_inplace_alter()
911 @param[in] ha_alter_info The DDL operation
912 @return whether it's an instant ALTER TABLE */
913 static inline bool is_instant(const Alter_inplace_info *ha_alter_info) {
914 return (ha_alter_info->handler_trivial_ctx !=
915 instant_type_to_int(Instant_Type::INSTANT_IMPOSSIBLE));
916 }
917
918 /** Determine if ALTER TABLE needs to rebuild the table.
919 @param[in] ha_alter_info The DDL operation
920 @return whether it is necessary to rebuild the table */
921 [[nodiscard]] static bool innobase_need_rebuild(
922 const Alter_inplace_info *ha_alter_info) {
923 if (is_instant(ha_alter_info)) {
924 return (false);
925 }
926
927 Alter_inplace_info::HA_ALTER_FLAGS alter_inplace_flags =
928 ha_alter_info->handler_flags & ~(INNOBASE_INPLACE_IGNORE);
929
930 if (alter_inplace_flags == Alter_inplace_info::CHANGE_CREATE_OPTION &&
931 !(ha_alter_info->create_info->used_fields &
932 (HA_CREATE_USED_ROW_FORMAT | HA_CREATE_USED_KEY_BLOCK_SIZE |
933 HA_CREATE_USED_TABLESPACE))) {
934 /* Any other CHANGE_CREATE_OPTION than changing
935 ROW_FORMAT, KEY_BLOCK_SIZE or TABLESPACE can be done
936 without rebuilding the table. */
937 return (false);
938 }
939
940 return (!!(ha_alter_info->handler_flags & INNOBASE_ALTER_REBUILD));
941 }
942
943 /** Check if InnoDB supports a particular alter table in-place
944 @param altered_table TABLE object for new version of table.
945 @param ha_alter_info Structure describing changes to be done
946 by ALTER TABLE and holding data used during in-place alter.
947
948 @retval HA_ALTER_INPLACE_NOT_SUPPORTED Not supported
949 @retval HA_ALTER_INPLACE_NO_LOCK Supported
950 @retval HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE Supported, but requires
951 lock during main phase and exclusive lock during prepare phase.
952 @retval HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE Supported, prepare phase
953 requires exclusive lock (any transactions that have accessed the table
954 must commit or roll back first, and no transactions can access the table
955 while prepare_inplace_alter_table() is executing)
956 */
957 enum_alter_inplace_result ha_innobase::check_if_supported_inplace_alter(
958 TABLE *altered_table, Alter_inplace_info *ha_alter_info) {
959 DBUG_TRACE;
960
961 if (srv_sys_space.created_new_raw()) {
962 return HA_ALTER_INPLACE_NOT_SUPPORTED;
963 }
964
965 if (high_level_read_only || srv_force_recovery) {
966 if (srv_force_recovery) {
967 my_error(ER_INNODB_FORCED_RECOVERY, MYF(0));
968 } else {
969 my_error(ER_READ_ONLY_MODE, MYF(0));
970 }
971 return HA_ALTER_ERROR;
972 }
973
974 if (altered_table->s->fields > REC_MAX_N_USER_FIELDS) {
975 /* Deny the inplace ALTER TABLE. MySQL will try to
976 re-create the table and ha_innobase::create() will
977 return an error too. This is how we effectively
978 deny adding too many columns to a table. */
979 ha_alter_info->unsupported_reason =
980 innobase_get_err_msg(ER_TOO_MANY_FIELDS);
981 return HA_ALTER_INPLACE_NOT_SUPPORTED;
982 }
983
984 /* We don't support change encryption attribute with inplace algorithm. */
985 char *old_encryption = this->table->s->encrypt_type.str;
986 char *new_encryption = altered_table->s->encrypt_type.str;
987
988 if (Encryption::is_none(old_encryption) !=
989 Encryption::is_none(new_encryption)) {
990 ha_alter_info->unsupported_reason =
991 innobase_get_err_msg(ER_UNSUPPORTED_ALTER_ENCRYPTION_INPLACE);
992 return HA_ALTER_INPLACE_NOT_SUPPORTED;
993 }
994
995 update_thd();
996
997 if (ha_alter_info->handler_flags &
998 ~(INNOBASE_INPLACE_IGNORE | INNOBASE_ALTER_NOREBUILD |
999 INNOBASE_ALTER_REBUILD)) {
1000 if (ha_alter_info->handler_flags &
1001 Alter_inplace_info::ALTER_STORED_COLUMN_TYPE) {
1002 if (ha_alter_info->alter_info->requested_algorithm ==
1003 Alter_info::ALTER_TABLE_ALGORITHM_INSTANT) {
1004 ha_alter_info->unsupported_reason = innobase_get_err_msg(
1005 ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE_INSTANT);
1006 } else {
1007 ha_alter_info->unsupported_reason = innobase_get_err_msg(
1008 ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE);
1009 }
1010 }
1011 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1012 }
1013
1014 /* Only support online add foreign key constraint when check_foreigns is
1015 turned off */
1016 if ((ha_alter_info->handler_flags & Alter_inplace_info::ADD_FOREIGN_KEY) &&
1017 m_prebuilt->trx->check_foreigns) {
1018 ha_alter_info->unsupported_reason =
1019 innobase_get_err_msg(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK);
1020 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1021 }
1022
1023 if (altered_table->file->ht != ht) {
1024 /* Non-native partitioning table engine. No longer supported, due to
1025 implementation of native InnoDB partitioning. */
1026 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1027 }
1028
1029 Instant_Type instant_type = innobase_support_instant(
1030 ha_alter_info, m_prebuilt->table, this->table, altered_table);
1031
1032 ha_alter_info->handler_trivial_ctx =
1033 instant_type_to_int(Instant_Type::INSTANT_IMPOSSIBLE);
1034
1035 const bool is_instant_requested =
1036 ha_alter_info->alter_info->requested_algorithm ==
1037 Alter_info::ALTER_TABLE_ALGORITHM_INSTANT;
1038
1039 if (!dict_table_is_partition(m_prebuilt->table)) {
1040 switch (instant_type) {
1041 case Instant_Type::INSTANT_IMPOSSIBLE:
1042 break;
1043 case Instant_Type::INSTANT_ADD_DROP_COLUMN:
1044 if (ha_alter_info->alter_info->requested_algorithm ==
1045 Alter_info::ALTER_TABLE_ALGORITHM_INPLACE) {
1046 /* Still fall back to INPLACE since the behaviour is different */
1047 break;
1048 } else if ((ha_alter_info->alter_info->requested_algorithm ==
1049 Alter_info::ALTER_TABLE_ALGORITHM_DEFAULT) &&
1050 !dict_table_is_discarded(m_prebuilt->table) &&
1051 btr_is_index_empty(m_prebuilt->table->first_index())) {
1052 /* No records: prefer INPLACE to prevent bumping row version */
1053 break;
1054 } else if (!((m_prebuilt->table->n_def +
1055 get_num_cols_added(ha_alter_info)) <=
1056 REC_MAX_N_USER_FIELDS + DATA_N_SYS_COLS)) {
1057 if (is_instant_requested) {
1058 my_error(ER_INNODB_INSTANT_ADD_NOT_SUPPORTED_MAX_FIELDS, MYF(0),
1059 m_prebuilt->table->name.m_name);
1060 return HA_ALTER_ERROR;
1061 }
1062 /* INSTANT can't be done any more. Fall back to INPLACE. */
1063 break;
1064 } else if (!is_valid_row_version(
1065 m_prebuilt->table->current_row_version + 1)) {
1066 ut_ad(is_valid_row_version(m_prebuilt->table->current_row_version));
1067 if (is_instant_requested) {
1068 my_error(ER_INNODB_MAX_ROW_VERSION, MYF(0),
1069 m_prebuilt->table->name.m_name);
1070 return HA_ALTER_ERROR;
1071 }
1072
1073 /* INSTANT can't be done any more. Fall back to INPLACE. */
1074 break;
1075 } else if (!Instant_ddl_impl<dd::Table>::is_instant_add_drop_possible(
1076 ha_alter_info, table, altered_table,
1077 m_prebuilt->table)) {
1078 if (is_instant_requested) {
1079 /* Return error if either max possible row size already crosses max
1080 permissible row size or may cross it after add. */
1081 my_error(ER_INNODB_INSTANT_ADD_DROP_NOT_SUPPORTED_MAX_SIZE, MYF(0));
1082 return HA_ALTER_ERROR;
1083 }
1084
1085 /* INSTANT can't be done. Fall back to INPLACE. */
1086 break;
1087 } else if (ha_alter_info->error_if_not_empty) {
1088 /* In this case, it can't be instant because the table
1089 may not be empty. Have to fall back to INPLACE */
1090 break;
1091 }
1092 [[fallthrough]];
1093 case Instant_Type::INSTANT_NO_CHANGE:
1094 case Instant_Type::INSTANT_VIRTUAL_ONLY:
1095 case Instant_Type::INSTANT_COLUMN_RENAME:
1096 ha_alter_info->handler_trivial_ctx = instant_type_to_int(instant_type);
1097 return HA_ALTER_INPLACE_INSTANT;
1098 }
1099 }
1100
1101 /* Only support NULL -> NOT NULL change if strict table sql_mode
1102 is set. Fall back to COPY for conversion if not strict tables.
1103 In-Place will fail with an error when trying to convert
1104 NULL to a NOT NULL value. */
1105 if ((ha_alter_info->handler_flags &
1106 Alter_inplace_info::ALTER_COLUMN_NOT_NULLABLE) &&
1107 !thd_is_strict_mode(m_user_thd)) {
1108 ha_alter_info->unsupported_reason =
1109 innobase_get_err_msg(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL);
1110 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1111 }
1112
1113 /* DROP PRIMARY KEY is only allowed in combination with ADD
1114 PRIMARY KEY. */
1115 if ((ha_alter_info->handler_flags & (Alter_inplace_info::ADD_PK_INDEX |
1116 Alter_inplace_info::DROP_PK_INDEX)) ==
1117 Alter_inplace_info::DROP_PK_INDEX) {
1118 ha_alter_info->unsupported_reason =
1119 innobase_get_err_msg(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK);
1120 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1121 }
1122
1123 /* If a column change from NOT NULL to NULL,
1124 and there's a implicit pk on this column. the
1125 table should be rebuild. The change should
1126 only go through the "Copy" method. */
1127 if ((ha_alter_info->handler_flags &
1128 Alter_inplace_info::ALTER_COLUMN_NULLABLE)) {
1129 const uint my_primary_key = altered_table->s->primary_key;
1130
1131 /* See if MYSQL table has no pk but we do. */
1132 if (UNIV_UNLIKELY(my_primary_key >= MAX_KEY) &&
1133 !row_table_got_default_clust_index(m_prebuilt->table)) {
1134 ha_alter_info->unsupported_reason =
1135 innobase_get_err_msg(ER_PRIMARY_CANT_HAVE_NULL);
1136 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1137 }
1138 }
1139
1140 bool add_drop_v_cols = false;
1141
1142 /* If there is add or drop virtual columns, we will support operations
1143 with these 3 options alone with inplace interface for now */
1144 if (ha_alter_info->handler_flags &
1145 (Alter_inplace_info::ADD_VIRTUAL_COLUMN |
1146 Alter_inplace_info::DROP_VIRTUAL_COLUMN |
1147 Alter_inplace_info::ALTER_VIRTUAL_COLUMN_ORDER)) {
1148 ulonglong flags = ha_alter_info->handler_flags;
1149
1150 /* TODO: uncomment the flags below, once we start to
1151 support them */
1152 flags &=
1153 ~(Alter_inplace_info::ADD_VIRTUAL_COLUMN |
1154 Alter_inplace_info::DROP_VIRTUAL_COLUMN |
1155 Alter_inplace_info::ALTER_VIRTUAL_COLUMN_ORDER
1156 /*
1157 | Alter_inplace_info::ALTER_STORED_COLUMN_ORDER
1158 | Alter_inplace_info::ADD_STORED_BASE_COLUMN
1159 | Alter_inplace_info::DROP_STORED_COLUMN
1160 | Alter_inplace_info::ALTER_STORED_COLUMN_ORDER
1161 | Alter_inplace_info::ADD_UNIQUE_INDEX
1162 */
1163 | Alter_inplace_info::ADD_INDEX | Alter_inplace_info::DROP_INDEX);
1164
1165 if (flags != 0 ||
1166 (altered_table->s->partition_info_str &&
1167 altered_table->s->partition_info_str_len) ||
1168 (!check_v_col_in_order(this->table, altered_table, ha_alter_info))) {
1169 ha_alter_info->unsupported_reason =
1170 innobase_get_err_msg(ER_UNSUPPORTED_ALTER_INPLACE_ON_VIRTUAL_COLUMN);
1171 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1172 }
1173
1174 add_drop_v_cols = true;
1175 }
1176
1177 /* We should be able to do the operation in-place.
1178 See if we can do it online (LOCK=NONE). */
1179 bool online = true;
1180
1181 List_iterator_fast<Create_field> cf_it(
1182 ha_alter_info->alter_info->create_list);
1183
1184 /* Fix the key parts. */
1185 for (KEY *new_key = ha_alter_info->key_info_buffer;
1186 new_key < ha_alter_info->key_info_buffer + ha_alter_info->key_count;
1187 new_key++) {
1188 /* Do not support adding/dropping a virtual column, while
1189 there is a table rebuild caused by adding a new FTS_DOC_ID */
1190 if ((new_key->flags & HA_FULLTEXT) && add_drop_v_cols &&
1191 !DICT_TF2_FLAG_IS_SET(m_prebuilt->table, DICT_TF2_FTS_HAS_DOC_ID)) {
1192 ha_alter_info->unsupported_reason =
1193 innobase_get_err_msg(ER_UNSUPPORTED_ALTER_INPLACE_ON_VIRTUAL_COLUMN);
1194 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1195 }
1196
1197 for (KEY_PART_INFO *key_part = new_key->key_part;
1198 key_part < new_key->key_part + new_key->user_defined_key_parts;
1199 key_part++) {
1200 const Create_field *new_field = nullptr;
1201
1202 assert(key_part->fieldnr < altered_table->s->fields);
1203
1204 cf_it.rewind();
1205 for (auto fieldnr = 0; fieldnr != key_part->fieldnr + 1; fieldnr++) {
1206 new_field = cf_it++;
1207 assert(new_field);
1208 }
1209
1210 key_part->field = altered_table->field[key_part->fieldnr];
1211 /* In some special cases InnoDB emits "false"
1212 duplicate key errors with NULL key values. Let
1213 us play safe and ensure that we can correctly
1214 print key values even in such cases. */
1215 key_part->null_offset = key_part->field->null_offset();
1216 key_part->null_bit = key_part->field->null_bit;
1217
1218 if (new_field->field) {
1219 /* This is an existing column. */
1220 continue;
1221 }
1222
1223 /* This is an added column. */
1224 assert(ha_alter_info->handler_flags & Alter_inplace_info::ADD_COLUMN);
1225
1226 /* We cannot replace a hidden FTS_DOC_ID
1227 with a user-visible FTS_DOC_ID. */
1228 if (m_prebuilt->table->fts && innobase_fulltext_exist(altered_table) &&
1229 !my_strcasecmp(system_charset_info, key_part->field->field_name,
1230 FTS_DOC_ID_COL_NAME)) {
1231 ha_alter_info->unsupported_reason = innobase_get_err_msg(
1232 ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS);
1233 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1234 }
1235
1236 assert(((key_part->field->auto_flags & Field::NEXT_NUMBER) != 0) ==
1237 key_part->field->is_flag_set(AUTO_INCREMENT_FLAG));
1238
1239 if (key_part->field->is_flag_set(AUTO_INCREMENT_FLAG)) {
1240 /* We cannot assign an AUTO_INCREMENT
1241 column values during online ALTER. */
1242 assert(key_part->field == altered_table->found_next_number_field);
1243 ha_alter_info->unsupported_reason = innobase_get_err_msg(
1244 ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC);
1245 online = false;
1246 }
1247
1248 if (key_part->field->is_virtual_gcol()) {
1249 /* Do not support adding index on newly added
1250 virtual column, while there is also a drop
1251 virtual column in the same clause */
1252 if (ha_alter_info->handler_flags &
1253 Alter_inplace_info::DROP_VIRTUAL_COLUMN) {
1254 ha_alter_info->unsupported_reason = innobase_get_err_msg(
1255 ER_UNSUPPORTED_ALTER_INPLACE_ON_VIRTUAL_COLUMN);
1256
1257 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1258 }
1259
1260 ha_alter_info->unsupported_reason =
1261 innobase_get_err_msg(ER_UNSUPPORTED_ALTER_ONLINE_ON_VIRTUAL_COLUMN);
1262 online = false;
1263 }
1264 }
1265 }
1266
1267 assert(!m_prebuilt->table->fts ||
1268 m_prebuilt->table->fts->doc_col <= table->s->fields);
1269 assert(!m_prebuilt->table->fts || m_prebuilt->table->fts->doc_col <
1270 m_prebuilt->table->get_n_user_cols());
1271
1272 if (ha_alter_info->handler_flags & Alter_inplace_info::ADD_SPATIAL_INDEX) {
1273 ha_alter_info->unsupported_reason =
1274 innobase_get_err_msg(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS);
1275 online = false;
1276 }
1277
1278 if (m_prebuilt->table->fts && innobase_fulltext_exist(altered_table)) {
1279 /* FULLTEXT indexes are supposed to remain. */
1280 /* Disallow DROP INDEX FTS_DOC_ID_INDEX */
1281
1282 for (uint i = 0; i < ha_alter_info->index_drop_count; i++) {
1283 if (!my_strcasecmp(system_charset_info,
1284 ha_alter_info->index_drop_buffer[i]->name,
1285 FTS_DOC_ID_INDEX_NAME)) {
1286 ha_alter_info->unsupported_reason = innobase_get_err_msg(
1287 ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS);
1288 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1289 }
1290 }
1291
1292 /* InnoDB can have a hidden FTS_DOC_ID_INDEX on a
1293 visible FTS_DOC_ID column as well. Prevent dropping or
1294 renaming the FTS_DOC_ID. */
1295
1296 for (Field **fp = table->field; *fp; fp++) {
1297 if (!((*fp)->is_flag_set(FIELD_IS_RENAMED) ||
1298 (*fp)->is_flag_set(FIELD_IS_DROPPED))) {
1299 continue;
1300 }
1301
1302 if (!my_strcasecmp(system_charset_info, (*fp)->field_name,
1303 FTS_DOC_ID_COL_NAME)) {
1304 ha_alter_info->unsupported_reason = innobase_get_err_msg(
1305 ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS);
1306 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1307 }
1308 }
1309 }
1310
1311 m_prebuilt->trx->will_lock++;
1312
1313 if (!online) {
1314 /* We already determined that only a non-locking
1315 operation is possible. */
1316 } else if (((ha_alter_info->handler_flags &
1317 Alter_inplace_info::ADD_PK_INDEX) ||
1318 innobase_need_rebuild(ha_alter_info)) &&
1319 (innobase_fulltext_exist(altered_table) ||
1320 innobase_spatial_exist(altered_table))) {
1321 /* Refuse to rebuild the table online, if
1322 FULLTEXT OR SPATIAL indexes are to survive the rebuild. */
1323 online = false;
1324 /* If the table already contains fulltext indexes,
1325 refuse to rebuild the table natively altogether. */
1326 if (m_prebuilt->table->fts) {
1327 ha_alter_info->unsupported_reason =
1328 innobase_get_err_msg(ER_INNODB_FT_LIMIT);
1329 return HA_ALTER_INPLACE_NOT_SUPPORTED;
1330 }
1331
1332 if (innobase_spatial_exist(altered_table)) {
1333 ha_alter_info->unsupported_reason =
1334 innobase_get_err_msg(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS);
1335 } else {
1336 ha_alter_info->unsupported_reason =
1337 innobase_get_err_msg(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS);
1338 }
1339 } else if ((ha_alter_info->handler_flags & Alter_inplace_info::ADD_INDEX)) {
1340 /* Building a full-text index requires a lock.
1341 We could do without a lock if the table already contains
1342 an FTS_DOC_ID column, but in that case we would have
1343 to apply the modification log to the full-text indexes. */
1344
1345 for (uint i = 0; i < ha_alter_info->index_add_count; i++) {
1346 const KEY *key =
1347 &ha_alter_info->key_info_buffer[ha_alter_info->index_add_buffer[i]];
1348 if (key->flags & HA_FULLTEXT) {
1349 assert(!(key->flags & HA_KEYFLAG_MASK &
1350 ~(HA_FULLTEXT | HA_PACK_KEY | HA_GENERATED_KEY |
1351 HA_BINARY_PACK_KEY)));
1352 ha_alter_info->unsupported_reason =
1353 innobase_get_err_msg(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS);
1354 online = false;
1355 break;
1356 }
1357 }
1358 }
1359
1360 return online ? HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE
1361 : HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE;
1362 }
1363
1364 /** Update the metadata in prepare phase. This only check if dd::Tablespace
1365 should be removed or(and) created, because to remove and store dd::Tablespace
1366 could fail, so it's better to do it earlier, to prevent a late rollback
1367 @param[in,out] thd MySQL connection
1368 @param[in] old_table Old InnoDB table object
1369 @param[in,out] new_table New InnoDB table object
1370 @param[in] old_dd_tab Old dd::Table or dd::Partition
1371 @return false On success
1372 @retval true On failure */
1373 template <typename Table>
1374 [[nodiscard]] static bool dd_prepare_inplace_alter_table(
1375 THD *thd, const dict_table_t *old_table, dict_table_t *new_table,
1376 const Table *old_dd_tab);
1377
1378 /** Update metadata in commit phase. Note this function should only update
1379 the metadata which would not result in failure
1380 @param[in] old_info Some table information for the old table
1381 @param[in,out] new_table New InnoDB table object
1382 @param[in] old_dd_tab Old dd::Table or dd::Partition
1383 @param[in,out] new_dd_tab New dd::Table or dd::Partition */
1384 template <typename Table>
1385 static void dd_commit_inplace_alter_table(
1386 const alter_table_old_info_t &old_info, dict_table_t *new_table,
1387 const Table *old_dd_tab, Table *new_dd_tab);
1388
1389 /** Update metadata in commit phase when the alter table does
1390 no change to the table
1391 @param[in] ha_alter_info the DDL operation
1392 @param[in] old_dd_tab Old dd::Table or dd::Partition
1393 @param[in] new_dd_tab New dd::Table or dd::Partition
1394 @param[in] ignore_fts ignore FTS update if true */
1395 template <typename Table>
1396 static void dd_commit_inplace_no_change(const Alter_inplace_info *ha_alter_info,
1397 const Table *old_dd_tab,
1398 Table *new_dd_tab, bool ignore_fts);
1399
1400 /** Update table level instant metadata in commit phase
1401 @param[in] table InnoDB table object
1402 @param[in] old_dd_tab old dd::Table
1403 @param[in] new_dd_tab new dd::Table */
1404 static void dd_commit_inplace_update_instant_meta(const dict_table_t *table,
1405 const dd::Table *old_dd_tab,
1406 dd::Table *new_dd_tab);
1407
1408 /** Update instant metadata in commit phase for partitioned table
1409 @param[in] part_share partition share object to get each
1410 partitioned table
1411 @param[in] n_parts number of partitions
1412 @param[in] old_dd_tab old dd::Table
1413 @param[in] new_dd_tab new dd::Table */
1414 static void dd_commit_inplace_update_partition_instant_meta(
1415 const Ha_innopart_share *part_share, uint16_t n_parts,
1416 const dd::Table *old_dd_tab, dd::Table *new_dd_tab);
1417
1418 /** Allows InnoDB to update internal structures with concurrent
1419 writes blocked (provided that check_if_supported_inplace_alter()
1420 did not return HA_ALTER_INPLACE_NO_LOCK).
1421 This will be invoked before inplace_alter_table().
1422 @param[in] altered_table TABLE object for new version of table.
1423 @param[in,out] ha_alter_info Structure describing changes to be done
1424 by ALTER TABLE and holding data used during in-place alter.
1425 @param[in] old_dd_tab dd::Table object describing old version
1426 of the table.
1427 @param[in,out] new_dd_tab dd::Table object for the new version of
1428 the table. Can be adjusted by this call. Changes to the table definition will
1429 be persisted in the data-dictionary at statement commit time.
1430 @retval true Failure
1431 @retval false Success
1432 */
1433 bool ha_innobase::prepare_inplace_alter_table(TABLE *altered_table,
1434 Alter_inplace_info *ha_alter_info,
1435 const dd::Table *old_dd_tab,
1436 dd::Table *new_dd_tab) {
1437 DBUG_TRACE;
1438 ut_ad(old_dd_tab != nullptr);
1439 ut_ad(new_dd_tab != nullptr);
1440
1441 if (dict_sys_t::is_dd_table_id(m_prebuilt->table->id) &&
1442 innobase_need_rebuild(ha_alter_info)) {
1443 ut_ad(!m_prebuilt->table->is_temporary());
1444 my_error(ER_NOT_ALLOWED_COMMAND, MYF(0));
1445 return true;
1446 }
1447
1448 if (altered_table->found_next_number_field != nullptr) {
1449 dd_copy_autoinc(old_dd_tab->se_private_data(),
1450 new_dd_tab->se_private_data());
1451 dd_set_autoinc(new_dd_tab->se_private_data(),
1452 ha_alter_info->create_info->auto_increment_value);
1453 }
1454
1455 return prepare_inplace_alter_table_impl<dd::Table>(
1456 altered_table, ha_alter_info, old_dd_tab, new_dd_tab);
1457 }
1458
1459 int ha_innobase::parallel_scan_init(void *&scan_ctx, size_t *num_threads,
1460 bool use_reserved_threads) {
1461 if (dict_table_is_discarded(m_prebuilt->table)) {
1462 ib_senderrf(ha_thd(), IB_LOG_LEVEL_ERROR, ER_TABLESPACE_DISCARDED,
1463 m_prebuilt->table->name.m_name);
1464
1465 return (HA_ERR_NO_SUCH_TABLE);
1466 }
1467
1468 scan_ctx = nullptr;
1469
1470 update_thd();
1471
1472 auto trx = m_prebuilt->trx;
1473
1474 innobase_register_trx(ht, ha_thd(), trx);
1475
1476 trx_start_if_not_started_xa(trx, false, UT_LOCATION_HERE);
1477
1478 trx_assign_read_view(trx);
1479
1480 size_t max_threads = thd_parallel_read_threads(m_prebuilt->trx->mysql_thd);
1481
1482 max_threads =
1483 Parallel_reader::available_threads(max_threads, use_reserved_threads);
1484
1485 if (max_threads == 0) {
1486 return (HA_ERR_GENERIC);
1487 }
1488
1489 const auto row_len = m_prebuilt->mysql_row_len;
1490
1491 auto adapter = ut::new_withkey<Parallel_reader_adapter>(
1492 UT_NEW_THIS_FILE_PSI_KEY, max_threads, row_len);
1493
1494 if (adapter == nullptr) {
1495 Parallel_reader::release_threads(max_threads);
1496 return (HA_ERR_OUT_OF_MEM);
1497 }
1498
1499 Parallel_reader::Scan_range full_scan{};
1500
1501 Parallel_reader::Config config(full_scan, m_prebuilt->table->first_index());
1502
1503 dberr_t err =
1504 adapter->add_scan(trx, config, [=](const Parallel_reader::Ctx *ctx) {
1505 return (adapter->process_rows(ctx));
1506 });
1507
1508 if (err != DB_SUCCESS) {
1509 ut::delete_(adapter);
1510 return (convert_error_code_to_mysql(err, 0, ha_thd()));
1511 }
1512
1513 scan_ctx = adapter;
1514 *num_threads = max_threads;
1515
1516 build_template(true);
1517
1518 adapter->set(m_prebuilt);
1519
1520 return (0);
1521 }
1522
1523 int ha_innobase::parallel_scan(void *scan_ctx, void **thread_ctxs,
1524 Reader::Init_fn init_fn, Reader::Load_fn load_fn,
1525 Reader::End_fn end_fn) {
1526 if (dict_table_is_discarded(m_prebuilt->table)) {
1527 ib_senderrf(ha_thd(), IB_LOG_LEVEL_ERROR, ER_TABLESPACE_DISCARDED,
1528 m_prebuilt->table->name.m_name);
1529
1530 return (HA_ERR_NO_SUCH_TABLE);
1531 }
1532
1533 ut_a(scan_ctx != nullptr);
1534
1535 update_thd();
1536
1537 build_template(true);
1538
1539 auto adapter = static_cast<Parallel_reader_adapter *>(scan_ctx);
1540
1541 auto err = adapter->run(thread_ctxs, init_fn, load_fn, end_fn);
1542
1543 return (convert_error_code_to_mysql(err, 0, ha_thd()));
1544 }
1545
1546 void ha_innobase::parallel_scan_end(void *parallel_scan_ctx) {
1547 Parallel_reader_adapter *parallel_reader =
1548 static_cast<Parallel_reader_adapter *>(parallel_scan_ctx);
1549 ut::delete_(parallel_reader);
1550 }
1551
1552 bool ha_innobase::inplace_alter_table(TABLE *altered_table,
1553 Alter_inplace_info *ha_alter_info,
1554 const dd::Table *old_dd_tab
1555 [[maybe_unused]],
1556 dd::Table *new_dd_tab [[maybe_unused]]) {
1557 DBUG_TRACE;
1558 ut_ad(old_dd_tab != nullptr);
1559 ut_ad(new_dd_tab != nullptr);
1560
1561 /* Notify clone during in place operations */
1562 Clone_notify notifier(Clone_notify::Type::SPACE_ALTER_INPLACE,
1563 dict_sys_t::s_invalid_space_id, false);
1564 ut_ad(!notifier.failed());
1565
1566 return inplace_alter_table_impl<dd::Table>(altered_table, ha_alter_info);
1567 }
1568
1569 /** Commit or rollback the changes made during
1570 prepare_inplace_alter_table() and inplace_alter_table() inside
1571 the storage engine. Note that the allowed level of concurrency
1572 during this operation will be the same as for
1573 inplace_alter_table() and thus might be higher than during
1574 prepare_inplace_alter_table(). (E.g concurrent writes were
1575 blocked during prepare, but might not be during commit).
1576 @param[in] altered_table TABLE object for new version of table.
1577 @param[in,out] ha_alter_info Structure describing changes to be done
1578 by ALTER TABLE and holding data used during in-place alter.
1579 @param[in] commit True to commit or false to rollback.
1580 @param[in] old_dd_tab dd::Table object representing old
1581 version of the table
1582 @param[in,out] new_dd_tab dd::Table object representing new
1583 version of the table. Can be adjusted by this call. Changes to the table
1584 definition will be persisted in the data-dictionary at statement
1585 commit time.
1586 @retval true Failure
1587 @retval false Success */
1588 bool ha_innobase::commit_inplace_alter_table(TABLE *altered_table,
1589 Alter_inplace_info *ha_alter_info,
1590 bool commit,
1591 const dd::Table *old_dd_tab,
1592 dd::Table *new_dd_tab) {
1593 DBUG_TRACE;
1594 ut_ad(old_dd_tab != nullptr);
1595 ut_ad(new_dd_tab != nullptr);
1596
1597 ha_innobase_inplace_ctx *ctx =
1598 static_cast<ha_innobase_inplace_ctx *>(ha_alter_info->handler_ctx);
1599
1600 alter_table_old_info_t old_info;
1601 ut_d(bool old_info_updated = false);
1602 if (commit && ctx != nullptr) {
1603 ut_ad(!!(ha_alter_info->handler_flags & ~INNOBASE_INPLACE_IGNORE));
1604 old_info.update(ctx->old_table, ctx->need_rebuild());
1605 ut_d(old_info_updated = true);
1606 }
1607
1608 bool res = commit_inplace_alter_table_impl<dd::Table>(
1609 altered_table, ha_alter_info, commit, new_dd_tab);
1610
1611 if (res || !commit) {
1612 return true;
1613 }
1614
1615 ut_ad(ctx == nullptr || !(ctx->need_rebuild() && is_instant(ha_alter_info)));
1616
1617 if (is_instant(ha_alter_info)) {
1618 ut_ad(!res);
1619
1620 Instant_ddl_impl<dd::Table> executor(
1621 ha_alter_info, m_user_thd, m_prebuilt->trx, m_prebuilt->table, table,
1622 altered_table, old_dd_tab, new_dd_tab,
1623 altered_table->found_next_number_field != nullptr
1624 ? &m_prebuilt->table->autoinc
1625 : nullptr);
1626
1627 /* Execute Instant DDL */
1628 if (executor.commit_instant_ddl()) return true;
1629 } else if (!(ha_alter_info->handler_flags & ~INNOBASE_INPLACE_IGNORE) ||
1630 ctx == nullptr) {
1631 ut_ad(!res);
1632 dd_commit_inplace_no_change(ha_alter_info, old_dd_tab, new_dd_tab, false);
1633 } else {
1634 ut_ad(old_info_updated);
1635 if (!ctx->need_rebuild() && !dict_table_has_fts_index(m_prebuilt->table)) {
1636 /* Table is not rebuilt so copy instant metadata. */
1637 dd_inplace_alter_copy_instant_metadata(ha_alter_info, old_dd_tab,
1638 new_dd_tab);
1639 }
1640
1641 dd_commit_inplace_alter_table<dd::Table>(old_info, ctx->new_table,
1642 old_dd_tab, new_dd_tab);
1643 if (!ctx->need_rebuild()) {
1644 dd_commit_inplace_update_instant_meta(ctx->new_table, old_dd_tab,
1645 new_dd_tab);
1646 }
1647 ut_ad(dd_table_match(ctx->new_table, new_dd_tab));
1648 }
1649
1650 #ifdef UNIV_DEBUG
1651 if (dd_table_has_instant_cols(*old_dd_tab) &&
1652 (ctx == nullptr || !ctx->need_rebuild())) {
1653 ut_ad(dd_table_has_instant_cols(*new_dd_tab));
1654 }
1655 #endif /* UNIV_DEBUG */
1656
1657 return res;
1658 }
1659
1660 /** Initialize the dict_foreign_t structure with supplied info
1661 @return true if added, false if duplicate foreign->id */
1662 static bool innobase_init_foreign(
1663 dict_foreign_t *foreign, /*!< in/out: structure to
1664 initialize */
1665 const char *constraint_name, /*!< in/out: constraint name if
1666 exists */
1667 dict_table_t *table, /*!< in: foreign table */
1668 dict_index_t *index, /*!< in: foreign key index */
1669 const char **column_names, /*!< in: foreign key column
1670 names */
1671 ulint num_field, /*!< in: number of columns */
1672 const char *referenced_table_name, /*!< in: referenced table
1673 name */
1674 dict_table_t *referenced_table, /*!< in: referenced table */
1675 dict_index_t *referenced_index, /*!< in: referenced index */
1676 const char **referenced_column_names, /*!< in: referenced column
1677 names */
1678 ulint referenced_num_field) /*!< in: number of referenced
1679 columns */
1680 {
1681 ut_ad(dict_sys_mutex_own());
1682
1683 if (constraint_name) {
1684 ulint db_len;
1685
1686 /* Catenate 'databasename/' to the constraint name specified
1687 by the user: we conceive the constraint as belonging to the
1688 same MySQL 'database' as the table itself. We store the name
1689 to foreign->id. */
1690
1691 db_len = dict_get_db_name_len(table->name.m_name);
1692
1693 foreign->id = static_cast<char *>(
1694 mem_heap_alloc(foreign->heap, db_len + strlen(constraint_name) + 2));
1695
1696 ut_memcpy(foreign->id, table->name.m_name, db_len);
1697 foreign->id[db_len] = '/';
1698 strcpy(foreign->id + db_len + 1, constraint_name);
1699
1700 /* Check if any existing foreign key has the same id,
1701 this is needed only if user supplies the constraint name */
1702
1703 if (table->foreign_set.find(foreign) != table->foreign_set.end()) {
1704 return (false);
1705 }
1706 }
1707
1708 foreign->foreign_table = table;
1709 foreign->foreign_table_name =
1710 mem_heap_strdup(foreign->heap, table->name.m_name);
1711 dict_mem_foreign_table_name_lookup_set(foreign, true);
1712
1713 foreign->foreign_index = index;
1714 foreign->n_fields = (unsigned int)num_field;
1715
1716 foreign->foreign_col_names = static_cast<const char **>(
1717 mem_heap_alloc(foreign->heap, num_field * sizeof(void *)));
1718
1719 for (ulint i = 0; i < foreign->n_fields; i++) {
1720 foreign->foreign_col_names[i] =
1721 mem_heap_strdup(foreign->heap, column_names[i]);
1722 }
1723
1724 foreign->referenced_index = referenced_index;
1725 foreign->referenced_table = referenced_table;
1726
1727 foreign->referenced_table_name =
1728 mem_heap_strdup(foreign->heap, referenced_table_name);
1729 dict_mem_referenced_table_name_lookup_set(foreign, true);
1730
1731 foreign->referenced_col_names = static_cast<const char **>(
1732 mem_heap_alloc(foreign->heap, referenced_num_field * sizeof(void *)));
1733
1734 for (ulint i = 0; i < foreign->n_fields; i++) {
1735 foreign->referenced_col_names[i] =
1736 mem_heap_strdup(foreign->heap, referenced_column_names[i]);
1737 }
1738
1739 return (true);
1740 }
1741
1742 /** Check whether the foreign key options is legit
1743 @return true if it is */
1744 [[nodiscard]] static bool innobase_check_fk_option(
1745 const dict_foreign_t *foreign) /*!< in: foreign key */
1746 {
1747 if (!foreign->foreign_index) {
1748 return (true);
1749 }
1750
1751 if (foreign->type &
1752 (DICT_FOREIGN_ON_UPDATE_SET_NULL | DICT_FOREIGN_ON_DELETE_SET_NULL)) {
1753 for (ulint j = 0; j < foreign->n_fields; j++) {
1754 if ((foreign->foreign_index->get_col(j)->prtype) & DATA_NOT_NULL) {
1755 /* It is not sensible to define
1756 SET NULL if the column is not
1757 allowed to be NULL! */
1758 return (false);
1759 }
1760 }
1761 }
1762
1763 return (true);
1764 }
1765
1766 /** Set foreign key options
1767 @return true if successfully set */
1768 [[nodiscard]] static bool innobase_set_foreign_key_option(
1769 dict_foreign_t *foreign, /*!< in:InnoDB Foreign key */
1770 const Foreign_key_spec *fk_key) /*!< in: Foreign key info from
1771 MySQL */
1772 {
1773 ut_ad(!foreign->type);
1774
1775 switch (fk_key->delete_opt) {
1776 case FK_OPTION_NO_ACTION:
1777 case FK_OPTION_RESTRICT:
1778 case FK_OPTION_DEFAULT:
1779 foreign->type = DICT_FOREIGN_ON_DELETE_NO_ACTION;
1780 break;
1781 case FK_OPTION_CASCADE:
1782 foreign->type = DICT_FOREIGN_ON_DELETE_CASCADE;
1783 break;
1784 case FK_OPTION_SET_NULL:
1785 foreign->type = DICT_FOREIGN_ON_DELETE_SET_NULL;
1786 break;
1787 case FK_OPTION_UNDEF:
1788 break;
1789 }
1790
1791 switch (fk_key->update_opt) {
1792 case FK_OPTION_NO_ACTION:
1793 case FK_OPTION_RESTRICT:
1794 case FK_OPTION_DEFAULT:
1795 foreign->type |= DICT_FOREIGN_ON_UPDATE_NO_ACTION;
1796 break;
1797 case FK_OPTION_CASCADE:
1798 foreign->type |= DICT_FOREIGN_ON_UPDATE_CASCADE;
1799 break;
1800 case FK_OPTION_SET_NULL:
1801 foreign->type |= DICT_FOREIGN_ON_UPDATE_SET_NULL;
1802 break;
1803 case FK_OPTION_UNDEF:
1804 break;
1805 }
1806
1807 return (innobase_check_fk_option(foreign));
1808 }
1809
1810 /** Check if a foreign key constraint can make use of an index
1811 that is being created.
1812 @return usable index, or NULL if none found */
1813 [[nodiscard]] static const KEY *innobase_find_equiv_index(
1814 const char *const *col_names,
1815 /*!< in: column names */
1816 uint n_cols, /*!< in: number of columns */
1817 const KEY *keys, /*!< in: index information */
1818 const uint *add, /*!< in: indexes being created */
1819 uint n_add) /*!< in: number of indexes to create */
1820 {
1821 for (uint i = 0; i < n_add; i++) {
1822 const KEY *key = &keys[add[i]];
1823
1824 if (key->user_defined_key_parts < n_cols || key->flags & HA_SPATIAL) {
1825 no_match:
1826 continue;
1827 }
1828
1829 for (uint j = 0; j < n_cols; j++) {
1830 const KEY_PART_INFO &key_part = key->key_part[j];
1831 uint32_t col_len = key_part.field->pack_length();
1832
1833 /* Any index on virtual columns cannot be used
1834 for reference constaint */
1835 if (innobase_is_v_fld(key_part.field)) {
1836 goto no_match;
1837 }
1838
1839 /* The MySQL pack length contains 1 or 2 bytes
1840 length field for a true VARCHAR. */
1841
1842 if (key_part.field->type() == MYSQL_TYPE_VARCHAR) {
1843 col_len -= key_part.field->get_length_bytes();
1844 }
1845
1846 if (key_part.length < col_len) {
1847 /* Column prefix indexes cannot be
1848 used for FOREIGN KEY constraints. */
1849 goto no_match;
1850 }
1851
1852 if (innobase_strcasecmp(col_names[j], key_part.field->field_name)) {
1853 /* Name mismatch */
1854 goto no_match;
1855 }
1856 }
1857
1858 return (key);
1859 }
1860
1861 return (nullptr);
1862 }
1863
1864 /** Find an index whose first fields are the columns in the array
1865 in the same order and is not marked for deletion
1866 @return matching index, NULL if not found */
1867 [[nodiscard]] static dict_index_t *innobase_find_fk_index(
1868 dict_table_t *table, /*!< in: table */
1869 const char **col_names,
1870 /*!< in: column names, or NULL
1871 to use table->col_names */
1872 dict_index_t **drop_index,
1873 /*!< in: indexes to be dropped */
1874 ulint n_drop_index,
1875 /*!< in: size of drop_index[] */
1876 const char **columns, /*!< in: array of column names */
1877 ulint n_cols) /*!< in: number of columns */
1878 {
1879 dict_index_t *index;
1880
1881 index = table->first_index();
1882
1883 while (index != nullptr) {
1884 if (!(index->type & DICT_FTS) &&
1885 dict_foreign_qualify_index(table, col_names, columns, n_cols, index,
1886 nullptr, true, 0)) {
1887 for (ulint i = 0; i < n_drop_index; i++) {
1888 if (index == drop_index[i]) {
1889 /* Skip to-be-dropped indexes. */
1890 goto next_rec;
1891 }
1892 }
1893
1894 return (index);
1895 }
1896
1897 next_rec:
1898 index = index->next();
1899 }
1900
1901 return (nullptr);
1902 }
1903
1904 /** Check whether given column is a base of stored column.
1905 @param[in] col_name column name
1906 @param[in] table table
1907 @param[in] s_cols list of stored columns
1908 @return true if the given column is a base of stored column,else false. */
1909 static bool innobase_col_check_fk(const char *col_name,
1910 const dict_table_t *table,
1911 dict_s_col_list *s_cols) {
1912 dict_s_col_list::const_iterator it;
1913
1914 for (it = s_cols->begin(); it != s_cols->end(); ++it) {
1915 dict_s_col_t s_col = *it;
1916
1917 for (ulint j = 0; j < s_col.num_base; j++) {
1918 if (strcmp(col_name, table->get_col_name(s_col.base_col[j]->ind)) == 0) {
1919 return (true);
1920 }
1921 }
1922 }
1923
1924 return (false);
1925 }
1926
1927 /** Check whether the foreign key constraint is on base of any stored columns.
1928 @param[in] foreign Foreign key constraint information
1929 @param[in] table table to which the foreign key objects
1930 to be added
1931 @param[in] s_cols list of stored column information in the table.
1932 @return true if yes, otherwise false. */
1933 static bool innobase_check_fk_stored(const dict_foreign_t *foreign,
1934 const dict_table_t *table,
1935 dict_s_col_list *s_cols) {
1936 ulint type = foreign->type;
1937
1938 type &=
1939 ~(DICT_FOREIGN_ON_DELETE_NO_ACTION | DICT_FOREIGN_ON_UPDATE_NO_ACTION);
1940
1941 if (type == 0 || s_cols == nullptr) {
1942 return (false);
1943 }
1944
1945 for (ulint i = 0; i < foreign->n_fields; i++) {
1946 if (innobase_col_check_fk(foreign->foreign_col_names[i], table, s_cols)) {
1947 return (true);
1948 }
1949 }
1950
1951 return (false);
1952 }
1953
1954 /** Create InnoDB foreign key structure from MySQL alter_info
1955 @param[in] ha_alter_info alter table info
1956 @param[in] table_share TABLE_SHARE
1957 @param[in] table table object
1958 @param[in] col_names column names, or NULL to use
1959 table->col_names
1960 @param[in] drop_index indexes to be dropped
1961 @param[in] n_drop_index size of drop_index
1962 @param[out] add_fk foreign constraint added
1963 @param[out] n_add_fk number of foreign constraints
1964 added
1965 @param[in] trx user transaction
1966 @param[in] s_cols list of stored column information
1967 @retval true if successful
1968 @retval false on error (will call my_error()) */
1969 [[nodiscard]] static bool innobase_get_foreign_key_info(
1970 Alter_inplace_info *ha_alter_info, const TABLE_SHARE *table_share,
1971 dict_table_t *table, const char **col_names, dict_index_t **drop_index,
1972 ulint n_drop_index, dict_foreign_t **add_fk, ulint *n_add_fk,
1973 const trx_t *trx, dict_s_col_list *s_cols) {
1974 const Foreign_key_spec *fk_key;
1975 dict_table_t *referenced_table = nullptr;
1976 char *referenced_table_name = nullptr;
1977 ulint num_fk = 0;
1978 Alter_info *alter_info = ha_alter_info->alter_info;
1979 MDL_ticket *mdl;
1980
1981 DBUG_TRACE;
1982
1983 *n_add_fk = 0;
1984
1985 for (const Key_spec *key : alter_info->key_list) {
1986 if (key->type != KEYTYPE_FOREIGN) {
1987 continue;
1988 }
1989
1990 const char *column_names[MAX_NUM_FK_COLUMNS];
1991 dict_index_t *index = nullptr;
1992 const char *referenced_column_names[MAX_NUM_FK_COLUMNS];
1993 dict_index_t *referenced_index = nullptr;
1994 ulint num_col = 0;
1995 ulint referenced_num_col = 0;
1996 bool correct_option;
1997 char *db_namep = nullptr;
1998 char *tbl_namep = nullptr;
1999 ulint db_name_len = 0;
2000 ulint tbl_name_len = 0;
2001 char db_name[MAX_DATABASE_NAME_LEN];
2002 char tbl_name[MAX_TABLE_NAME_LEN];
2003
2004 fk_key = down_cast<const Foreign_key_spec *>(key);
2005
2006 if (fk_key->columns.size() > 0) {
2007 size_t i = 0;
2008
2009 /* Get all the foreign key column info for the
2010 current table */
2011 while (i < fk_key->columns.size()) {
2012 column_names[i] = fk_key->columns[i]->get_field_name();
2013 ut_ad(i < MAX_NUM_FK_COLUMNS);
2014 i++;
2015 }
2016
2017 index = innobase_find_fk_index(table, col_names, drop_index, n_drop_index,
2018 column_names, i);
2019
2020 /* MySQL would add a index in the creation
2021 list if no such index for foreign table,
2022 so we have to use DBUG_EXECUTE_IF to simulate
2023 the scenario */
2024 DBUG_EXECUTE_IF("innodb_test_no_foreign_idx", index = nullptr;);
2025
2026 /* Check whether there exist such
2027 index in the the index create clause */
2028 if (!index &&
2029 !innobase_find_equiv_index(column_names, static_cast<uint>(i),
2030 ha_alter_info->key_info_buffer,
2031 ha_alter_info->index_add_buffer,
2032 ha_alter_info->index_add_count)) {
2033 my_error(ER_FK_NO_INDEX_CHILD, MYF(0),
2034 fk_key->name.str ? fk_key->name.str : "",
2035 table_share->table_name.str);
2036 goto err_exit;
2037 }
2038
2039 num_col = i;
2040 }
2041
2042 add_fk[num_fk] = dict_mem_foreign_create();
2043
2044 #ifndef _WIN32
2045 if (fk_key->ref_db.str) {
2046 tablename_to_filename(fk_key->ref_db.str, db_name, MAX_DATABASE_NAME_LEN);
2047 db_namep = db_name;
2048 db_name_len = strlen(db_name);
2049 }
2050 if (fk_key->ref_table.str) {
2051 tablename_to_filename(fk_key->ref_table.str, tbl_name,
2052 MAX_TABLE_NAME_LEN);
2053 tbl_namep = tbl_name;
2054 tbl_name_len = strlen(tbl_name);
2055 }
2056 #else
2057 ut_ad(fk_key->ref_table.str);
2058 tablename_to_filename(fk_key->ref_table.str, tbl_name, MAX_TABLE_NAME_LEN);
2059 innobase_casedn_str(tbl_name);
2060 tbl_name_len = strlen(tbl_name);
2061 tbl_namep = &tbl_name[0];
2062
2063 if (fk_key->ref_db.str != NULL) {
2064 tablename_to_filename(fk_key->ref_db.str, db_name, MAX_DATABASE_NAME_LEN);
2065 innobase_casedn_str(db_name);
2066 db_name_len = strlen(db_name);
2067 db_namep = &db_name[0];
2068 }
2069 #endif
2070 dict_sys_mutex_enter();
2071
2072 referenced_table_name = dd_get_referenced_table(
2073 table->name.m_name, db_namep, db_name_len, tbl_namep, tbl_name_len,
2074 &referenced_table, &mdl, add_fk[num_fk]->heap);
2075
2076 /* Test the case when referenced_table failed to
2077 open, if trx->check_foreigns is not set, we should
2078 still be able to add the foreign key */
2079 DBUG_EXECUTE_IF(
2080 "innodb_test_open_ref_fail", if (referenced_table) {
2081 dd_table_close(referenced_table, current_thd, &mdl, true);
2082 referenced_table = nullptr;
2083 });
2084
2085 if (!referenced_table && trx->check_foreigns) {
2086 dict_sys_mutex_exit();
2087 my_error(ER_FK_CANNOT_OPEN_PARENT, MYF(0), tbl_namep);
2088
2089 goto err_exit;
2090 }
2091
2092 if (fk_key->ref_columns.size() > 0) {
2093 size_t i = 0;
2094
2095 while (i < fk_key->ref_columns.size()) {
2096 referenced_column_names[i] = fk_key->ref_columns[i]->get_field_name();
2097 ut_ad(i < MAX_NUM_FK_COLUMNS);
2098 i++;
2099 }
2100
2101 if (referenced_table) {
2102 referenced_index = dict_foreign_find_index(referenced_table, nullptr,
2103 referenced_column_names, i,
2104 index, true, false);
2105
2106 DBUG_EXECUTE_IF("innodb_test_no_reference_idx",
2107 referenced_index = nullptr;);
2108
2109 /* Check whether there exist such
2110 index in the the index create clause */
2111 if (!referenced_index) {
2112 dd_table_close(referenced_table, current_thd, &mdl, true);
2113 dict_sys_mutex_exit();
2114 my_error(ER_FK_NO_INDEX_PARENT, MYF(0),
2115 fk_key->name.str ? fk_key->name.str : "", tbl_namep);
2116 goto err_exit;
2117 }
2118 } else {
2119 ut_a(!trx->check_foreigns);
2120 }
2121
2122 referenced_num_col = i;
2123 } else {
2124 /* Not possible to add a foreign key without a
2125 referenced column */
2126 if (referenced_table) {
2127 dd_table_close(referenced_table, current_thd, &mdl, true);
2128 }
2129 dict_sys_mutex_exit();
2130 my_error(ER_CANNOT_ADD_FOREIGN, MYF(0), tbl_namep);
2131 goto err_exit;
2132 }
2133
2134 if (!innobase_init_foreign(add_fk[num_fk], fk_key->name.str, table, index,
2135 column_names, num_col, referenced_table_name,
2136 referenced_table, referenced_index,
2137 referenced_column_names, referenced_num_col)) {
2138 if (referenced_table) {
2139 dd_table_close(referenced_table, current_thd, &mdl, true);
2140 }
2141 dict_sys_mutex_exit();
2142 my_error(ER_FK_DUP_NAME, MYF(0), add_fk[num_fk]->id);
2143 goto err_exit;
2144 }
2145
2146 if (referenced_table) {
2147 dd_table_close(referenced_table, current_thd, &mdl, true);
2148 }
2149 dict_sys_mutex_exit();
2150
2151 correct_option = innobase_set_foreign_key_option(add_fk[num_fk], fk_key);
2152
2153 DBUG_EXECUTE_IF("innodb_test_wrong_fk_option", correct_option = false;);
2154
2155 if (!correct_option) {
2156 my_error(ER_FK_INCORRECT_OPTION, MYF(0), table_share->table_name.str,
2157 add_fk[num_fk]->id);
2158 goto err_exit;
2159 }
2160
2161 if (innobase_check_fk_stored(add_fk[num_fk], table, s_cols)) {
2162 my_error(ER_CANNOT_ADD_FOREIGN_BASE_COL_STORED, MYF(0));
2163 goto err_exit;
2164 }
2165
2166 num_fk++;
2167 }
2168
2169 *n_add_fk = num_fk;
2170
2171 return true;
2172 err_exit:
2173 for (ulint i = 0; i <= num_fk; i++) {
2174 if (add_fk[i]) {
2175 dict_foreign_free(add_fk[i]);
2176 }
2177 }
2178
2179 return false;
2180 }
2181
2182 /** Copies an InnoDB column to a MySQL field. This function is
2183 adapted from row_sel_field_store_in_mysql_format(). */
2184 static void innobase_col_to_mysql(
2185 const dict_col_t *col, /*!< in: InnoDB column */
2186 const uchar *data, /*!< in: InnoDB column data */
2187 ulint len, /*!< in: length of data, in bytes */
2188 Field *field) /*!< in/out: MySQL field */
2189 {
2190 uchar *ptr;
2191 uchar *dest = field->field_ptr();
2192 ulint flen = field->pack_length();
2193
2194 switch (col->mtype) {
2195 case DATA_INT:
2196 ut_ad(len == flen);
2197
2198 /* Convert integer data from Innobase to little-endian
2199 format, sign bit restored to normal */
2200
2201 for (ptr = dest + len; ptr != dest;) {
2202 *--ptr = *data++;
2203 }
2204
2205 if (!field->is_flag_set(UNSIGNED_FLAG)) {
2206 ((byte *)dest)[len - 1] ^= 0x80;
2207 }
2208
2209 break;
2210
2211 case DATA_VARCHAR:
2212 case DATA_VARMYSQL:
2213 case DATA_BINARY:
2214 field->reset();
2215
2216 if (field->type() == MYSQL_TYPE_VARCHAR) {
2217 /* This is a >= 5.0.3 type true VARCHAR. Store the
2218 length of the data to the first byte or the first
2219 two bytes of dest. */
2220
2221 dest =
2222 row_mysql_store_true_var_len(dest, len, flen - field->key_length());
2223 }
2224
2225 /* Copy the actual data */
2226 memcpy(dest, data, len);
2227 break;
2228
2229 case DATA_VAR_POINT:
2230 case DATA_GEOMETRY:
2231 case DATA_BLOB:
2232 /* Skip MySQL BLOBs when reporting an erroneous row
2233 during index creation or table rebuild. */
2234 field->set_null();
2235 break;
2236
2237 #ifdef UNIV_DEBUG
2238 case DATA_MYSQL:
2239 ut_ad(flen >= len);
2240 ut_ad(DATA_MBMAXLEN(col->mbminmaxlen) >= DATA_MBMINLEN(col->mbminmaxlen));
2241 memcpy(dest, data, len);
2242 break;
2243
2244 default:
2245 case DATA_SYS_CHILD:
2246 case DATA_SYS:
2247 /* These column types should never be shipped to MySQL. */
2248 ut_d(ut_error);
2249 [[fallthrough]];
2250
2251 case DATA_FLOAT:
2252 case DATA_DOUBLE:
2253 case DATA_DECIMAL:
2254 case DATA_POINT:
2255 /* Above are the valid column types for MySQL data. */
2256 ut_ad(flen == len);
2257 [[fallthrough]];
2258 case DATA_FIXBINARY:
2259 case DATA_CHAR:
2260 /* We may have flen > len when there is a shorter
2261 prefix on the CHAR and BINARY column. */
2262 ut_ad(flen >= len);
2263 #else /* UNIV_DEBUG */
2264 default:
2265 #endif /* UNIV_DEBUG */
2266 memcpy(dest, data, len);
2267 }
2268 }
2269
2270 /** Copies an InnoDB record to table->record[0].
2271 @param[in,out] table Mysql table
2272 @param[in] rec Record
2273 @param[in] index Index
2274 @param[in] offsets rec_get_offsets( rec, index, ...) */
2275 void innobase_rec_to_mysql(struct TABLE *table, const rec_t *rec,
2276 const dict_index_t *index, const ulint *offsets) {
2277 uint n_fields = table->s->fields;
2278
2279 ut_ad(n_fields ==
2280 dict_table_get_n_tot_u_cols(index->table) -
2281 DICT_TF2_FLAG_IS_SET(index->table, DICT_TF2_FTS_HAS_DOC_ID));
2282
2283 for (uint i = 0; i < n_fields; i++) {
2284 Field *field = table->field[i];
2285 ulint ipos;
2286 ulint ilen;
2287 const uchar *ifield;
2288
2289 field->reset();
2290
2291 ipos = index->get_col_pos(i, true, false);
2292
2293 if (ipos == ULINT_UNDEFINED || rec_offs_nth_extern(index, offsets, ipos)) {
2294 null_field:
2295 field->set_null();
2296 continue;
2297 }
2298
2299 ifield = rec_get_nth_field_instant(rec, offsets, ipos, index, &ilen);
2300
2301 /* Assign the NULL flag */
2302 if (ilen == UNIV_SQL_NULL) {
2303 ut_ad(field->is_nullable());
2304 goto null_field;
2305 }
2306
2307 field->set_notnull();
2308
2309 innobase_col_to_mysql(index->get_field(ipos)->col, ifield, ilen, field);
2310 }
2311 }
2312
2313 /** Copies an InnoDB index entry to table->record[0].
2314 @param[in,out] table Mysql table
2315 @param[in] index Innodb index
2316 @param[in] fields Innodb index fields */
2317 void innobase_fields_to_mysql(struct TABLE *table, const dict_index_t *index,
2318 const dfield_t *fields) {
2319 uint n_fields = table->s->fields;
2320 ulint num_v = 0;
2321
2322 ut_ad(n_fields ==
2323 index->table->get_n_user_cols() +
2324 dict_table_get_n_v_cols(index->table) -
2325 DICT_TF2_FLAG_IS_SET(index->table, DICT_TF2_FTS_HAS_DOC_ID));
2326
2327 for (uint i = 0; i < n_fields; i++) {
2328 Field *field = table->field[i];
2329 ulint ipos;
2330 ulint col_n;
2331
2332 field->reset();
2333
2334 if (innobase_is_v_fld(field)) {
2335 col_n = num_v;
2336 num_v++;
2337 } else {
2338 col_n = i - num_v;
2339 }
2340
2341 ipos = index->get_col_pos(col_n, true, innobase_is_v_fld(field));
2342
2343 if (ipos == ULINT_UNDEFINED || dfield_is_ext(&fields[ipos]) ||
2344 dfield_is_null(&fields[ipos])) {
2345 field->set_null();
2346 } else {
2347 field->set_notnull();
2348
2349 const dfield_t *df = &fields[ipos];
2350
2351 innobase_col_to_mysql(index->get_field(ipos)->col,
2352 static_cast<const uchar *>(dfield_get_data(df)),
2353 dfield_get_len(df), field);
2354 }
2355 }
2356 }
2357
2358 /** Copies an InnoDB row to table->record[0].
2359 @param[in,out] table Mysql table
2360 @param[in] itab Innodb table
2361 @param[in] row Innodb row */
2362 void innobase_row_to_mysql(struct TABLE *table, const dict_table_t *itab,
2363 const dtuple_t *row) {
2364 uint n_fields = table->s->fields;
2365 ulint num_v = 0;
2366
2367 /* The InnoDB row may contain an extra FTS_DOC_ID column at the end. */
2368 ut_ad(row->n_fields == itab->get_n_cols());
2369 ut_ad(n_fields == row->n_fields - DATA_N_SYS_COLS +
2370 dict_table_get_n_v_cols(itab) -
2371 DICT_TF2_FLAG_IS_SET(itab, DICT_TF2_FTS_HAS_DOC_ID));
2372
2373 for (uint i = 0; i < n_fields; i++) {
2374 Field *field = table->field[i];
2375
2376 field->reset();
2377
2378 if (innobase_is_v_fld(field)) {
2379 /* Virtual column are not stored in InnoDB table, so
2380 skip it */
2381 num_v++;
2382 continue;
2383 }
2384
2385 const dfield_t *df = dtuple_get_nth_field(row, i - num_v);
2386
2387 if (dfield_is_ext(df) || dfield_is_null(df)) {
2388 field->set_null();
2389 } else {
2390 field->set_notnull();
2391
2392 innobase_col_to_mysql(itab->get_col(i - num_v),
2393 static_cast<const uchar *>(dfield_get_data(df)),
2394 dfield_get_len(df), field);
2395 }
2396 }
2397 }
2398
2399 /** Resets table->record[0]. */
2400 void innobase_rec_reset(TABLE *table) /*!< in/out: MySQL table */
2401 {
2402 uint n_fields = table->s->fields;
2403 uint i;
2404
2405 for (i = 0; i < n_fields; i++) {
2406 if (!table->field[i]->m_default_val_expr) {
2407 table->field[i]->set_default();
2408 } else {
2409 table->field[i]->copy_data(table->default_values_offset());
2410 }
2411 }
2412 }
2413
2414 /** This function checks that index keys are sensible.
2415 @return 0 or error number */
2416 [[nodiscard]] static int innobase_check_index_keys(
2417 const Alter_inplace_info *info,
2418 /*!< in: indexes to be created or dropped */
2419 const dict_table_t *innodb_table)
2420 /*!< in: Existing indexes */
2421 {
2422 for (uint key_num = 0; key_num < info->index_add_count; key_num++) {
2423 const KEY &key = info->key_info_buffer[info->index_add_buffer[key_num]];
2424
2425 /* Check that the same index name does not appear
2426 twice in indexes to be created. */
2427
2428 for (ulint i = 0; i < key_num; i++) {
2429 const KEY &key2 = info->key_info_buffer[info->index_add_buffer[i]];
2430
2431 if (0 == strcmp(key.name, key2.name)) {
2432 my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key.name);
2433
2434 return (ER_WRONG_NAME_FOR_INDEX);
2435 }
2436 }
2437
2438 /* Check that the same index name does not already exist. */
2439
2440 const dict_index_t *index;
2441
2442 for (index = innodb_table->first_index(); index; index = index->next()) {
2443 if (index->is_committed() && !strcmp(key.name, index->name)) {
2444 break;
2445 }
2446 }
2447
2448 /* Now we are in a situation where we have "ADD INDEX x"
2449 and an index by the same name already exists. We have 4
2450 possible cases:
2451 1. No further clauses for an index x are given. Should reject
2452 the operation.
2453 2. "DROP INDEX x" is given. Should allow the operation.
2454 3. "RENAME INDEX x TO y" is given. Should allow the operation.
2455 4. "DROP INDEX x, RENAME INDEX x TO y" is given. Should allow
2456 the operation, since no name clash occurs. In this particular
2457 case MySQL cancels the operation without calling InnoDB
2458 methods. */
2459
2460 if (index) {
2461 /* If a key by the same name is being created and
2462 dropped, the name clash is OK. */
2463 for (uint i = 0; i < info->index_drop_count; i++) {
2464 const KEY *drop_key = info->index_drop_buffer[i];
2465
2466 if (0 == strcmp(key.name, drop_key->name)) {
2467 goto name_ok;
2468 }
2469 }
2470
2471 /* If a key by the same name is being created and
2472 renamed, the name clash is OK. E.g.
2473 ALTER TABLE t ADD INDEX i (col), RENAME INDEX i TO x
2474 where the index "i" exists prior to the ALTER command.
2475 In this case we:
2476 1. rename the existing index from "i" to "x"
2477 2. add the new index "i" */
2478 for (uint i = 0; i < info->index_rename_count; i++) {
2479 const KEY_PAIR *pair = &info->index_rename_buffer[i];
2480
2481 if (0 == strcmp(key.name, pair->old_key->name)) {
2482 goto name_ok;
2483 }
2484 }
2485
2486 my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key.name);
2487
2488 return (ER_WRONG_NAME_FOR_INDEX);
2489 }
2490
2491 name_ok:
2492 for (ulint i = 0; i < key.user_defined_key_parts; i++) {
2493 const KEY_PART_INFO &key_part1 = key.key_part[i];
2494 const Field *field = key_part1.field;
2495 ulint is_unsigned;
2496
2497 switch (get_innobase_type_from_mysql_type(&is_unsigned, field)) {
2498 default:
2499 break;
2500 case DATA_INT:
2501 case DATA_FLOAT:
2502 case DATA_DOUBLE:
2503 case DATA_DECIMAL:
2504 /* Check that MySQL does not try to
2505 create a column prefix index field on
2506 an inappropriate data type. */
2507
2508 if (field->type() == MYSQL_TYPE_VARCHAR) {
2509 if (key_part1.length >=
2510 field->pack_length() - field->get_length_bytes()) {
2511 break;
2512 }
2513 } else {
2514 if (key_part1.length >= field->pack_length() ||
2515 innobase_is_multi_value_fld(field)) {
2516 break;
2517 }
2518 }
2519
2520 my_error(ER_WRONG_KEY_COLUMN, MYF(0), field->field_name);
2521 return (ER_WRONG_KEY_COLUMN);
2522 }
2523
2524 /* Check that the same column does not appear
2525 twice in the index. */
2526
2527 for (ulint j = 0; j < i; j++) {
2528 const KEY_PART_INFO &key_part2 = key.key_part[j];
2529
2530 if (key_part1.fieldnr != key_part2.fieldnr) {
2531 continue;
2532 }
2533
2534 my_error(ER_WRONG_KEY_COLUMN, MYF(0), field->field_name);
2535 return (ER_WRONG_KEY_COLUMN);
2536 }
2537 }
2538 }
2539
2540 return (0);
2541 }
2542
2543 /** Create index field definition for key part
2544 @param[in] altered_table MySQL table that is being altered,
2545 or NULL if a new clustered index
2546 is not being created
2547 @param[in] key_part MySQL key definition
2548 @param[in,out] index_field index field
2549 @param[in] new_clustered new cluster */
2550 static void innobase_create_index_field_def(const TABLE *altered_table,
2551 const KEY_PART_INFO *key_part,
2552 ddl::Index_field *index_field,
2553 bool new_clustered) {
2554 const Field *field;
2555 ulint is_unsigned;
2556 ulint col_type;
2557 ulint num_v = 0;
2558
2559 DBUG_TRACE;
2560
2561 ut_ad(key_part);
2562 ut_ad(index_field);
2563
2564 field =
2565 new_clustered ? altered_table->field[key_part->fieldnr] : key_part->field;
2566 ut_a(field);
2567
2568 for (ulint i = 0; i < key_part->fieldnr; i++) {
2569 if (innobase_is_v_fld(altered_table->field[i])) {
2570 num_v++;
2571 }
2572 }
2573
2574 col_type = get_innobase_type_from_mysql_type(&is_unsigned, field);
2575
2576 index_field->m_is_multi_value = innobase_is_multi_value_fld(field);
2577 if (!field->stored_in_db && field->gcol_info) {
2578 index_field->m_is_v_col = true;
2579 index_field->m_col_no = num_v;
2580 } else {
2581 index_field->m_is_v_col = false;
2582 index_field->m_col_no = key_part->fieldnr - num_v;
2583 }
2584 index_field->m_is_ascending = !(key_part->key_part_flag & HA_REVERSE_SORT);
2585
2586 /* No prefix index on multi-value field */
2587 if (!index_field->m_is_multi_value &&
2588 (DATA_LARGE_MTYPE(col_type) ||
2589 (key_part->length < field->pack_length() &&
2590 field->type() != MYSQL_TYPE_VARCHAR) ||
2591 (field->type() == MYSQL_TYPE_VARCHAR &&
2592 key_part->length < field->pack_length() - field->get_length_bytes()))) {
2593 index_field->m_prefix_len = key_part->length;
2594 } else {
2595 index_field->m_prefix_len = 0;
2596 }
2597 }
2598
2599 template <typename Index>
2600 const dd::Index *get_dd_index(const Index *index);
2601
2602 template <>
2603 const dd::Index *get_dd_index<dd::Index>(const dd::Index *dd_index) {
2604 return dd_index;
2605 }
2606
2607 template <>
2608 const dd::Index *get_dd_index<dd::Partition_index>(
2609 const dd::Partition_index *dd_index) {
2610 return (dd_index != nullptr) ? &dd_index->index() : nullptr;
2611 }
2612
2613 /** Create index definition for key
2614 @param[in] altered_table MySQL table that is being altered
2615 @param[in] new_dd_tab New dd table
2616 @param[in] keys Key definitions
2617 @param[in] key_number MySQL key number
2618 @param[in] new_clustered true if generating a new clustered index
2619 on the table
2620 @param[in] key_clustered true if this is the new clustered index
2621 @param[out] index_def Index definition
2622 @param[in] heap heap where memory is allocated */
2623 template <typename Table>
2624 static void innobase_create_index_def(const TABLE *altered_table,
2625 const Table *new_dd_tab, const KEY *keys,
2626 ulint key_number, bool new_clustered,
2627 bool key_clustered,
2628 ddl::Index_defn *index_def,
2629 mem_heap_t *heap) {
2630 ulint i;
2631 const KEY *key = &keys[key_number];
2632 ulint n_fields = key->user_defined_key_parts;
2633
2634 DBUG_TRACE;
2635 assert(!key_clustered || new_clustered);
2636
2637 index_def->m_fields = static_cast<ddl::Index_field *>(
2638 mem_heap_alloc(heap, n_fields * sizeof *index_def->m_fields));
2639
2640 index_def->m_parser = nullptr;
2641 index_def->m_is_ngram = false;
2642 index_def->m_key_number = key_number;
2643 index_def->m_n_fields = n_fields;
2644 index_def->m_name = mem_heap_strdup(heap, key->name);
2645 index_def->m_rebuild = new_clustered;
2646
2647 /* If this is a spatial index, we need to fetch the SRID */
2648 if (key->flags & HA_SPATIAL) {
2649 ulint dd_key_num =
2650 key_number + ((altered_table->s->primary_key == MAX_KEY) ? 1 : 0);
2651
2652 const auto *dd_index_auto =
2653 (index_def->m_key_number != ULINT_UNDEFINED)
2654 ? const_cast<const Table *>(new_dd_tab)->indexes()[dd_key_num]
2655 : nullptr;
2656
2657 const dd::Index *dd_index = get_dd_index(dd_index_auto);
2658
2659 if (dd_index != nullptr) {
2660 ut_ad(dd_index->name() == key->name);
2661 /* Spatial index indexes on only one column */
2662 size_t geom_col_idx;
2663 for (geom_col_idx = 0; geom_col_idx < dd_index->elements().size();
2664 ++geom_col_idx) {
2665 if (!dd_index->elements()[geom_col_idx]->column().is_se_hidden()) break;
2666 }
2667 const dd::Column &col = dd_index->elements()[geom_col_idx]->column();
2668 bool has_value = col.srs_id().has_value();
2669 index_def->m_srid_is_valid = has_value;
2670 index_def->m_srid = has_value ? col.srs_id().value() : 0;
2671 }
2672 }
2673
2674 if (key_clustered) {
2675 assert(!(key->flags & (HA_FULLTEXT | HA_SPATIAL)));
2676 assert(key->flags & HA_NOSAME);
2677 index_def->m_ind_type = DICT_CLUSTERED | DICT_UNIQUE;
2678 } else if (key->flags & HA_FULLTEXT) {
2679 assert(!(key->flags & (HA_SPATIAL | HA_NOSAME)));
2680 assert(!(key->flags & HA_KEYFLAG_MASK &
2681 ~(HA_FULLTEXT | HA_PACK_KEY | HA_BINARY_PACK_KEY)));
2682 index_def->m_ind_type = DICT_FTS;
2683
2684 /* Set plugin parser */
2685 /* Note: key->parser is only parser name,
2686 we need to get parser from altered_table instead */
2687 if (key->flags & HA_USES_PARSER) {
2688 for (ulint j = 0; j < altered_table->s->keys; j++) {
2689 if (ut_strcmp(altered_table->key_info[j].name, key->name) == 0) {
2690 ut_ad(altered_table->key_info[j].flags & HA_USES_PARSER);
2691
2692 plugin_ref parser = altered_table->key_info[j].parser;
2693 index_def->m_parser =
2694 static_cast<st_mysql_ftparser *>(plugin_decl(parser)->info);
2695
2696 index_def->m_is_ngram =
2697 strncmp(plugin_name(parser)->str, FTS_NGRAM_PARSER_NAME,
2698 plugin_name(parser)->length) == 0;
2699
2700 break;
2701 }
2702 }
2703
2704 DBUG_EXECUTE_IF("fts_instrument_use_default_parser",
2705 index_def->m_parser = &fts_default_parser;);
2706 ut_ad(index_def->m_parser);
2707 }
2708 } else if (key->flags & HA_SPATIAL) {
2709 assert(!(key->flags & HA_NOSAME));
2710 index_def->m_ind_type = DICT_SPATIAL;
2711 ut_ad(n_fields == 1);
2712 ulint num_v = 0;
2713
2714 /* Need to count the virtual fields before this spatial
2715 indexed field */
2716 for (ulint i = 0; i < key->key_part->fieldnr; i++) {
2717 if (innobase_is_v_fld(altered_table->field[i])) {
2718 num_v++;
2719 }
2720 }
2721 index_def->m_fields[0].m_col_no = key->key_part[0].fieldnr - num_v;
2722 index_def->m_fields[0].m_prefix_len = 0;
2723 index_def->m_fields[0].m_is_v_col = false;
2724
2725 /* Currently only ascending order is supported in spatial
2726 index. */
2727 ut_ad(!(key->key_part[0].key_part_flag & HA_REVERSE_SORT));
2728 index_def->m_fields[0].m_is_ascending = true;
2729
2730 if (!key->key_part[0].field->stored_in_db &&
2731 key->key_part[0].field->gcol_info) {
2732 index_def->m_fields[0].m_is_v_col = true;
2733 /* Currently, the spatial index cannot be created
2734 on virtual columns. It is blocked in server
2735 layer */
2736 ut_d(ut_error);
2737 } else {
2738 index_def->m_fields[0].m_is_v_col = false;
2739 }
2740 } else {
2741 index_def->m_ind_type = (key->flags & HA_NOSAME) ? DICT_UNIQUE : 0;
2742 }
2743
2744 if (!(key->flags & HA_SPATIAL)) {
2745 for (i = 0; i < n_fields; i++) {
2746 innobase_create_index_field_def(altered_table, &key->key_part[i],
2747 &index_def->m_fields[i], new_clustered);
2748
2749 if (index_def->m_fields[i].m_is_v_col) {
2750 index_def->m_ind_type |= DICT_VIRTUAL;
2751 }
2752
2753 if (index_def->m_fields[i].m_is_multi_value) {
2754 index_def->m_ind_type |= DICT_MULTI_VALUE;
2755 }
2756 }
2757 }
2758 }
2759
2760 /** Check whether the table has the FTS_DOC_ID column
2761 @return whether there exists an FTS_DOC_ID column */
2762 bool innobase_fts_check_doc_id_col(
2763 const dict_table_t *table, /*!< in: InnoDB table with
2764 fulltext index */
2765 const TABLE *altered_table,
2766 /*!< in: MySQL table with
2767 fulltext index */
2768 ulint *fts_doc_col_no,
2769 /*!< out: The column number for
2770 Doc ID, or ULINT_UNDEFINED
2771 if it is of wrong type */
2772 ulint *num_v) /*!< out: number of virtual column */
2773 {
2774 *fts_doc_col_no = ULINT_UNDEFINED;
2775
2776 const uint n_cols = altered_table->s->fields;
2777 ulint i;
2778
2779 *num_v = 0;
2780
2781 for (i = 0; i < n_cols; i++) {
2782 const Field *field = altered_table->field[i];
2783
2784 if (innobase_is_v_fld(field)) {
2785 (*num_v)++;
2786 }
2787
2788 if (my_strcasecmp(system_charset_info, field->field_name,
2789 FTS_DOC_ID_COL_NAME)) {
2790 continue;
2791 }
2792
2793 if (strcmp(field->field_name, FTS_DOC_ID_COL_NAME)) {
2794 my_error(ER_WRONG_COLUMN_NAME, MYF(0), field->field_name);
2795 } else if (field->type() != MYSQL_TYPE_LONGLONG ||
2796 field->pack_length() != 8 || field->is_nullable() ||
2797 !field->is_flag_set(UNSIGNED_FLAG) || innobase_is_v_fld(field)) {
2798 my_error(ER_INNODB_FT_WRONG_DOCID_COLUMN, MYF(0), field->field_name);
2799 } else {
2800 *fts_doc_col_no = i - *num_v;
2801 }
2802
2803 return (true);
2804 }
2805
2806 if (!table) {
2807 return (false);
2808 }
2809
2810 /* Not to count the virtual columns */
2811 i -= *num_v;
2812
2813 for (; i + DATA_N_SYS_COLS < (uint)table->n_cols; i++) {
2814 const char *name = table->get_col_name(i);
2815
2816 if (strcmp(name, FTS_DOC_ID_COL_NAME) == 0) {
2817 #ifdef UNIV_DEBUG
2818 const dict_col_t *col;
2819
2820 col = table->get_col(i);
2821
2822 /* Because the FTS_DOC_ID does not exist in
2823 the MySQL data dictionary, this must be the
2824 internally created FTS_DOC_ID column. */
2825 ut_ad(col->mtype == DATA_INT);
2826 ut_ad(col->len == 8);
2827 ut_ad(col->prtype & DATA_NOT_NULL);
2828 ut_ad(col->prtype & DATA_UNSIGNED);
2829 #endif /* UNIV_DEBUG */
2830 *fts_doc_col_no = i;
2831 return (true);
2832 }
2833 }
2834
2835 return (false);
2836 }
2837
2838 /** Check whether the table has a unique index with FTS_DOC_ID_INDEX_NAME
2839 on the Doc ID column.
2840 @return the status of the FTS_DOC_ID index */
2841 enum fts_doc_id_index_enum innobase_fts_check_doc_id_index(
2842 const dict_table_t *table, /*!< in: table definition */
2843 const TABLE *altered_table, /*!< in: MySQL table
2844 that is being altered */
2845 ulint *fts_doc_col_no) /*!< out: The column number for
2846 Doc ID, or ULINT_UNDEFINED
2847 if it is being created in
2848 ha_alter_info */
2849 {
2850 const dict_index_t *index;
2851 const dict_field_t *field;
2852
2853 if (altered_table) {
2854 /* Check if a unique index with the name of
2855 FTS_DOC_ID_INDEX_NAME is being created. */
2856
2857 for (uint i = 0; i < altered_table->s->keys; i++) {
2858 const KEY &key = altered_table->key_info[i];
2859
2860 if (innobase_strcasecmp(key.name, FTS_DOC_ID_INDEX_NAME)) {
2861 continue;
2862 }
2863
2864 if ((key.flags & HA_NOSAME) &&
2865 key.user_defined_key_parts == 1
2866 /* For now, we do not allow a descending index,
2867 because fts_doc_fetch_by_doc_id() uses the
2868 InnoDB SQL interpreter to look up FTS_DOC_ID. */
2869 && !(key.key_part[0].key_part_flag & HA_REVERSE_SORT) &&
2870 !strcmp(key.name, FTS_DOC_ID_INDEX_NAME) &&
2871 !strcmp(key.key_part[0].field->field_name, FTS_DOC_ID_COL_NAME)) {
2872 if (fts_doc_col_no) {
2873 *fts_doc_col_no = ULINT_UNDEFINED;
2874 }
2875 return (FTS_EXIST_DOC_ID_INDEX);
2876 } else {
2877 return (FTS_INCORRECT_DOC_ID_INDEX);
2878 }
2879 }
2880 }
2881
2882 if (!table) {
2883 return (FTS_NOT_EXIST_DOC_ID_INDEX);
2884 }
2885
2886 for (index = table->first_index(); index; index = index->next()) {
2887 /* Check if there exists a unique index with the name of
2888 FTS_DOC_ID_INDEX_NAME */
2889 if (innobase_strcasecmp(index->name, FTS_DOC_ID_INDEX_NAME)) {
2890 continue;
2891 }
2892
2893 if (!dict_index_is_unique(index) ||
2894 dict_index_get_n_unique(index) > 1
2895 /* For now, we do not allow a descending index,
2896 because fts_doc_fetch_by_doc_id() uses the
2897 InnoDB SQL interpreter to look up FTS_DOC_ID. */
2898 || !index->get_field(0)->is_ascending ||
2899 strcmp(index->name, FTS_DOC_ID_INDEX_NAME)) {
2900 return (FTS_INCORRECT_DOC_ID_INDEX);
2901 }
2902
2903 /* Check whether the index has FTS_DOC_ID as its
2904 first column */
2905 field = index->get_field(0);
2906
2907 /* The column would be of a BIGINT data type */
2908 if (strcmp(field->name, FTS_DOC_ID_COL_NAME) == 0 &&
2909 field->col->mtype == DATA_INT && field->col->len == 8 &&
2910 field->col->prtype & DATA_NOT_NULL && !field->col->is_virtual()) {
2911 if (fts_doc_col_no) {
2912 *fts_doc_col_no = dict_col_get_no(field->col);
2913 }
2914 return (FTS_EXIST_DOC_ID_INDEX);
2915 } else {
2916 return (FTS_INCORRECT_DOC_ID_INDEX);
2917 }
2918 }
2919
2920 /* Not found */
2921 return (FTS_NOT_EXIST_DOC_ID_INDEX);
2922 }
2923 /** Check whether the table has a unique index with FTS_DOC_ID_INDEX_NAME
2924 on the Doc ID column in MySQL create index definition.
2925 @return FTS_EXIST_DOC_ID_INDEX if there exists the FTS_DOC_ID index,
2926 FTS_INCORRECT_DOC_ID_INDEX if the FTS_DOC_ID index is of wrong format */
2927 enum fts_doc_id_index_enum innobase_fts_check_doc_id_index_in_def(
2928 ulint n_key, /*!< in: Number of keys */
2929 const KEY *key_info) /*!< in: Key definition */
2930 {
2931 /* Check whether there is a "FTS_DOC_ID_INDEX" in the to be built index
2932 list */
2933 for (ulint j = 0; j < n_key; j++) {
2934 const KEY *key = &key_info[j];
2935
2936 if (innobase_strcasecmp(key->name, FTS_DOC_ID_INDEX_NAME)) {
2937 continue;
2938 }
2939
2940 /* Do a check on FTS DOC ID_INDEX, it must be unique,
2941 named as "FTS_DOC_ID_INDEX" and on column "FTS_DOC_ID" */
2942 if (!(key->flags & HA_NOSAME) ||
2943 key->user_defined_key_parts != 1
2944 /* For now, we do not allow a descending index,
2945 because fts_doc_fetch_by_doc_id() uses the
2946 InnoDB SQL interpreter to look up FTS_DOC_ID. */
2947 || (key->key_part[0].key_part_flag & HA_REVERSE_SORT) ||
2948 strcmp(key->name, FTS_DOC_ID_INDEX_NAME) ||
2949 strcmp(key->key_part[0].field->field_name, FTS_DOC_ID_COL_NAME)) {
2950 return (FTS_INCORRECT_DOC_ID_INDEX);
2951 }
2952
2953 return (FTS_EXIST_DOC_ID_INDEX);
2954 }
2955
2956 return (FTS_NOT_EXIST_DOC_ID_INDEX);
2957 }
2958
2959 /** Create an index table where indexes are ordered as follows:
2960
2961 IF a new primary key is defined for the table THEN
2962
2963 1) New primary key
2964 2) The remaining keys in key_info
2965
2966 ELSE
2967
2968 1) All new indexes in the order they arrive from MySQL
2969
2970 ENDIF
2971
2972 @return key definitions */
2973 template <typename Table>
2974 [[nodiscard]] static MY_ATTRIBUTE((malloc)) ddl::Index_defn
2975 *innobase_create_key_defs(mem_heap_t *heap,
2976 /*!< in/out: memory heap where space for key
2977 definitions are allocated */
2978 const Alter_inplace_info *ha_alter_info,
2979 /*!< in: alter operation */
2980 const TABLE *altered_table,
2981 /*!< in: MySQL table that is being altered */
2982 const Table *new_dd_table,
2983 /*!< in: new dd table */
2984 ulint &n_add,
2985 /*!< in/out: number of indexes to be created */
2986 ulint &n_fts_add,
2987 /*!< out: number of FTS indexes to be created */
2988 bool got_default_clust,
2989 /*!< in: whether the table lacks a primary key */
2990 ulint &fts_doc_id_col,
2991 /*!< in: The column number for Doc ID */
2992 bool &add_fts_doc_id,
2993 /*!< in: whether we need to add new DOC ID
2994 column for FTS index */
2995 bool &add_fts_doc_idx)
2996 /*!< in: whether we need to add new DOC ID
2997 index for FTS index */
2998 {
2999 ddl::Index_defn *indexdef;
3000 ddl::Index_defn *index_defs;
3001 bool new_primary;
3002 const uint *const add = ha_alter_info->index_add_buffer;
3003 const KEY *const key_info = ha_alter_info->key_info_buffer;
3004
3005 DBUG_TRACE;
3006 assert(!add_fts_doc_id || add_fts_doc_idx);
3007 assert(ha_alter_info->index_add_count == n_add);
3008
3009 /* If there is a primary key, it is always the first index
3010 defined for the innodb_table. */
3011
3012 new_primary = n_add > 0 && !my_strcasecmp(system_charset_info,
3013 key_info[*add].name, "PRIMARY");
3014 n_fts_add = 0;
3015
3016 /* If there is a UNIQUE INDEX consisting entirely of NOT NULL
3017 columns and if the index does not contain column prefix(es)
3018 (only prefix/part of the column is indexed), MySQL will treat the
3019 index as a PRIMARY KEY unless the table already has one. */
3020
3021 ut_ad(altered_table->s->primary_key == 0 ||
3022 altered_table->s->primary_key == MAX_KEY);
3023
3024 if (got_default_clust && !new_primary) {
3025 new_primary = (altered_table->s->primary_key != MAX_KEY);
3026 }
3027
3028 const bool rebuild =
3029 new_primary || add_fts_doc_id || innobase_need_rebuild(ha_alter_info);
3030
3031 /* Reserve one more space if new_primary is true, and we might
3032 need to add the FTS_DOC_ID_INDEX */
3033 indexdef = index_defs = static_cast<ddl::Index_defn *>(mem_heap_alloc(
3034 heap, sizeof *indexdef *
3035 (ha_alter_info->key_count + rebuild + got_default_clust)));
3036
3037 if (rebuild) {
3038 ulint primary_key_number;
3039
3040 if (new_primary) {
3041 if (n_add == 0) {
3042 assert(got_default_clust);
3043 assert(altered_table->s->primary_key == 0);
3044 primary_key_number = 0;
3045 } else if (ha_alter_info->handler_flags &
3046 Alter_inplace_info::ALTER_COLUMN_NOT_NULLABLE) {
3047 primary_key_number = altered_table->s->primary_key;
3048 } else {
3049 primary_key_number = *add;
3050 }
3051 } else if (got_default_clust) {
3052 /* Create the GEN_CLUST_INDEX */
3053 ddl::Index_defn *index_def = indexdef++;
3054
3055 index_def->m_fields = nullptr;
3056 index_def->m_n_fields = 0;
3057 index_def->m_ind_type = DICT_CLUSTERED;
3058 index_def->m_name = innobase_index_reserve_name;
3059 index_def->m_rebuild = true;
3060 index_def->m_key_number = std::numeric_limits<size_t>::max();
3061 index_def->m_is_ngram = false;
3062 primary_key_number = ULINT_UNDEFINED;
3063 goto created_clustered;
3064 } else {
3065 primary_key_number = 0;
3066 }
3067
3068 /* Create the PRIMARY key index definition */
3069 innobase_create_index_def(altered_table, new_dd_table, key_info,
3070 primary_key_number, true, true, indexdef++, heap);
3071
3072 created_clustered:
3073 n_add = 1;
3074
3075 for (ulint i = 0; i < ha_alter_info->key_count; i++) {
3076 if (i == primary_key_number) {
3077 continue;
3078 }
3079 /* Copy the index definitions. */
3080 innobase_create_index_def(altered_table, new_dd_table, key_info, i, true,
3081 false, indexdef, heap);
3082
3083 if (indexdef->m_ind_type & DICT_FTS) {
3084 n_fts_add++;
3085 }
3086
3087 indexdef++;
3088 n_add++;
3089 }
3090
3091 if (n_fts_add > 0) {
3092 ulint num_v = 0;
3093
3094 if (!add_fts_doc_id &&
3095 !innobase_fts_check_doc_id_col(nullptr, altered_table,
3096 &fts_doc_id_col, &num_v)) {
3097 fts_doc_id_col = altered_table->s->fields - num_v;
3098 add_fts_doc_id = true;
3099 }
3100
3101 if (!add_fts_doc_idx) {
3102 fts_doc_id_index_enum ret;
3103 ulint doc_col_no;
3104
3105 ret = innobase_fts_check_doc_id_index(nullptr, altered_table,
3106 &doc_col_no);
3107
3108 /* This should have been checked before */
3109 ut_ad(ret != FTS_INCORRECT_DOC_ID_INDEX);
3110
3111 if (ret == FTS_NOT_EXIST_DOC_ID_INDEX) {
3112 add_fts_doc_idx = true;
3113 } else {
3114 ut_ad(ret == FTS_EXIST_DOC_ID_INDEX);
3115 ut_ad(doc_col_no == ULINT_UNDEFINED || doc_col_no == fts_doc_id_col);
3116 }
3117 }
3118 }
3119 } else {
3120 /* Create definitions for added secondary indexes. */
3121
3122 for (ulint i = 0; i < n_add; i++) {
3123 innobase_create_index_def(altered_table, new_dd_table, key_info, add[i],
3124 false, false, indexdef, heap);
3125
3126 if (indexdef->m_ind_type & DICT_FTS) {
3127 n_fts_add++;
3128 }
3129
3130 indexdef++;
3131 }
3132 }
3133
3134 assert(index_defs + n_add == indexdef);
3135
3136 if (add_fts_doc_idx) {
3137 ddl::Index_defn *index_def = indexdef++;
3138
3139 index_def->m_fields = static_cast<ddl::Index_field *>(
3140 mem_heap_alloc(heap, sizeof *index_def->m_fields));
3141
3142 index_def->m_n_fields = 1;
3143 index_def->m_fields->m_col_no = fts_doc_id_col;
3144 index_def->m_fields->m_prefix_len = 0;
3145 index_def->m_fields->m_is_ascending = true;
3146 index_def->m_fields->m_is_v_col = false;
3147 index_def->m_ind_type = DICT_UNIQUE;
3148 ut_ad(!rebuild || !add_fts_doc_id ||
3149 fts_doc_id_col <= altered_table->s->fields);
3150
3151 index_def->m_name = FTS_DOC_ID_INDEX_NAME;
3152 index_def->m_is_ngram = false;
3153 index_def->m_rebuild = rebuild;
3154
3155 /* TODO: assign a real MySQL key number for this */
3156 index_def->m_key_number = ULINT_UNDEFINED;
3157 n_add++;
3158 }
3159
3160 assert(indexdef > index_defs);
3161 assert((ulint)(indexdef - index_defs) <=
3162 ha_alter_info->key_count + add_fts_doc_idx + got_default_clust);
3163 assert(ha_alter_info->index_add_count <= n_add);
3164 return index_defs;
3165 }
3166
3167 /** Check each index column size, make sure they do not exceed the max limit
3168 @return true if index column size exceeds limit */
3169 [[nodiscard]] static bool innobase_check_column_length(
3170 ulint max_col_len, /*!< in: maximum column length */
3171 const KEY *key_info) /*!< in: Indexes to be created */
3172 {
3173 for (ulint key_part = 0; key_part < key_info->user_defined_key_parts;
3174 key_part++) {
3175 if (key_info->key_part[key_part].length > max_col_len) {
3176 return (true);
3177 }
3178 }
3179 return (false);
3180 }
3181
3182 /** Search for a given column in each index that is not being dropped. Return
3183 true if the column is part of any of the active indexes or it is a system
3184 column.
3185 @param[in] table table object
3186 @param[in] col_no column number of the column which is to be checked
3187 @param[in] is_v if this is a virtual column
3188 @retval true the column exists or it is a system column
3189 @retval false column does not exist */
3190 static bool check_col_exists_in_indexes(const dict_table_t *table, ulint col_no,
3191 bool is_v) {
3192 /* This function does not check system columns */
3193 if (!is_v && table->get_col(col_no)->mtype == DATA_SYS) {
3194 return (true);
3195 }
3196
3197 for (const dict_index_t *index = table->first_index(); index;
3198 index = index->next()) {
3199 for (ulint i = 0; i < index->n_user_defined_cols; i++) {
3200 const dict_col_t *idx_col = index->get_col(i);
3201
3202 if (is_v && idx_col->is_virtual()) {
3203 const dict_v_col_t *v_col =
3204 reinterpret_cast<const dict_v_col_t *>(idx_col);
3205 if (v_col->v_pos == col_no) {
3206 return (true);
3207 }
3208 }
3209
3210 if (!is_v && !idx_col->is_virtual() &&
3211 dict_col_get_no(idx_col) == col_no) {
3212 return (true);
3213 }
3214 }
3215 }
3216
3217 return (false);
3218 }
3219
3220 /** Reset dict_col_t::ord_part for those columns that fail to be indexed,
3221 Check every existing column to see if any current index references them.
3222 This should be checked after an index is dropped during ALTER TABLE.
3223 @param[in,out] table InnoDB table to check */
3224 static inline void reset_column_ord_part(dict_table_t *table) {
3225 for (ulint i = 0; i < table->get_n_cols(); i++) {
3226 if (!check_col_exists_in_indexes(table, i, false)) {
3227 table->cols[i].ord_part = 0;
3228 }
3229 }
3230
3231 for (ulint i = 0; i < dict_table_get_n_v_cols(table); i++) {
3232 if (!check_col_exists_in_indexes(table, i, true)) {
3233 table->v_cols[i].m_col.ord_part = 0;
3234 }
3235 }
3236 }
3237
3238 /** Drop in-memory metadata for index (dict_index_t) left from previous
3239 online ALTER operation.
3240 @param[in] table table to check
3241 @param[in] locked if it is dict_sys mutex locked */
3242 static void online_retry_drop_dict_indexes(dict_table_t *table, bool locked) {
3243 if (!locked) {
3244 dict_sys_mutex_enter();
3245 }
3246
3247 bool modify = false;
3248 dict_index_t *index = table->first_index();
3249
3250 for (index = index->next(); index != nullptr; index = index->next()) {
3251 if (dict_index_get_online_status(index) == ONLINE_INDEX_ABORTED_DROPPED) {
3252 dict_index_t *prev = UT_LIST_GET_PREV(indexes, index);
3253
3254 dict_index_remove_from_cache(table, index);
3255
3256 index = prev;
3257
3258 modify = true;
3259 }
3260 }
3261
3262 if (modify) {
3263 /* Since the table has been modified, table->def_trx_id should be
3264 adjusted like ddl::drop_indexes(). However, this function may
3265 be called before the DDL transaction starts, so it is impossible to
3266 get current DDL transaction ID. Thus advancing def_trx_id by 1 to
3267 simply inform other threads about this change. */
3268 ++table->def_trx_id;
3269
3270 reset_column_ord_part(table);
3271 }
3272
3273 if (!locked) {
3274 dict_sys_mutex_exit();
3275 }
3276 }
3277
3278 /** Determines if InnoDB is dropping a foreign key constraint.
3279 @param foreign the constraint
3280 @param drop_fk constraints being dropped
3281 @param n_drop_fk number of constraints that are being dropped
3282 @return whether the constraint is being dropped */
3283 [[nodiscard]] inline bool innobase_dropping_foreign(
3284 const dict_foreign_t *foreign, dict_foreign_t **drop_fk, ulint n_drop_fk) {
3285 while (n_drop_fk--) {
3286 if (*drop_fk++ == foreign) {
3287 return (true);
3288 }
3289 }
3290
3291 return (false);
3292 }
3293
3294 /** Convert a default value for ADD COLUMN.
3295
3296 @param heap Memory heap where allocated
3297 @param dfield InnoDB data field to copy to
3298 @param field MySQL value for the column
3299 @param comp nonzero if in compact format */
3300 static void innobase_build_col_map_add(mem_heap_t *heap, dfield_t *dfield,
3301 const Field *field, ulint comp) {
3302 if (field->is_real_null()) {
3303 dfield_set_null(dfield);
3304 return;
3305 }
3306
3307 ulint size = field->pack_length();
3308
3309 byte *buf = static_cast<byte *>(mem_heap_alloc(heap, size));
3310
3311 const byte *mysql_data = field->field_ptr();
3312
3313 row_mysql_store_col_in_innobase_format(dfield, buf, true, mysql_data, size,
3314 comp);
3315 }
3316
3317 /** Construct the translation table for reordering, dropping or
3318 adding columns.
3319
3320 @param ha_alter_info Data used during in-place alter
3321 @param altered_table MySQL table that is being altered
3322 @param table MySQL table as it is before the ALTER operation
3323 @param new_table InnoDB table corresponding to MySQL altered_table
3324 @param old_table InnoDB table corresponding to MYSQL table
3325 @param add_cols Default values for ADD COLUMN, or NULL if no ADD COLUMN
3326 @param heap Memory heap where allocated
3327 @return array of integers, mapping column numbers in the table
3328 to column numbers in altered_table */
3329 [[nodiscard]] static const ulint *innobase_build_col_map(
3330 Alter_inplace_info *ha_alter_info, const TABLE *altered_table,
3331 const TABLE *table, const dict_table_t *new_table,
3332 const dict_table_t *old_table, dtuple_t *add_cols, mem_heap_t *heap) {
3333 DBUG_TRACE;
3334 assert(altered_table != table);
3335 assert(new_table != old_table);
3336 assert(new_table->get_n_cols() + dict_table_get_n_v_cols(new_table) >=
3337 altered_table->s->fields + DATA_N_SYS_COLS);
3338 assert(old_table->get_n_cols() + dict_table_get_n_v_cols(old_table) >=
3339 table->s->fields + DATA_N_SYS_COLS);
3340 assert(!!add_cols ==
3341 !!(ha_alter_info->handler_flags & Alter_inplace_info::ADD_COLUMN));
3342 assert(!add_cols || dtuple_get_n_fields(add_cols) == new_table->get_n_cols());
3343
3344 ulint *col_map = static_cast<ulint *>(mem_heap_alloc(
3345 heap, (old_table->n_cols + old_table->n_v_cols) * sizeof *col_map));
3346
3347 List_iterator_fast<Create_field> cf_it(
3348 ha_alter_info->alter_info->create_list);
3349 uint i = 0;
3350 uint num_v = 0;
3351
3352 /* Any dropped columns will map to ULINT_UNDEFINED. */
3353 for (uint old_i = 0; old_i + DATA_N_SYS_COLS < old_table->n_cols; old_i++) {
3354 col_map[old_i] = ULINT_UNDEFINED;
3355 }
3356
3357 for (uint old_i = 0; old_i < old_table->n_v_cols; old_i++) {
3358 col_map[old_i + old_table->n_cols] = ULINT_UNDEFINED;
3359 }
3360
3361 while (const Create_field *new_field = cf_it++) {
3362 bool is_v = false;
3363
3364 if (innobase_is_v_fld(new_field)) {
3365 is_v = true;
3366 }
3367
3368 ulint num_old_v = 0;
3369
3370 for (uint old_i = 0; table->field[old_i]; old_i++) {
3371 const Field *field = table->field[old_i];
3372 if (innobase_is_v_fld(field)) {
3373 if (is_v && new_field->field == field) {
3374 col_map[old_table->n_cols + num_v] = num_old_v;
3375 num_old_v++;
3376 goto found_col;
3377 }
3378 num_old_v++;
3379 continue;
3380 }
3381
3382 if (new_field->field == field) {
3383 col_map[old_i - num_old_v] = i;
3384 goto found_col;
3385 }
3386 }
3387
3388 ut_ad(!is_v);
3389 innobase_build_col_map_add(heap, dtuple_get_nth_field(add_cols, i),
3390 altered_table->field[i + num_v],
3391 dict_table_is_comp(new_table));
3392 found_col:
3393 if (is_v) {
3394 num_v++;
3395 } else {
3396 i++;
3397 }
3398 }
3399
3400 assert(i == altered_table->s->fields - num_v);
3401
3402 i = table->s->fields - old_table->n_v_cols;
3403
3404 /* Add the InnoDB hidden FTS_DOC_ID column, if any. */
3405 if (i + DATA_N_SYS_COLS < old_table->n_cols) {
3406 /* There should be exactly one extra field,
3407 the FTS_DOC_ID. */
3408 assert(DICT_TF2_FLAG_IS_SET(old_table, DICT_TF2_FTS_HAS_DOC_ID));
3409 assert(i + DATA_N_SYS_COLS + 1 == old_table->n_cols);
3410 assert(!strcmp(old_table->get_col_name(i), FTS_DOC_ID_COL_NAME));
3411 if (altered_table->s->fields + DATA_N_SYS_COLS - new_table->n_v_cols <
3412 new_table->n_cols) {
3413 assert(DICT_TF2_FLAG_IS_SET(new_table, DICT_TF2_FTS_HAS_DOC_ID));
3414 assert(altered_table->s->fields + DATA_N_SYS_COLS + 1 ==
3415 static_cast<ulint>(new_table->n_cols + new_table->n_v_cols));
3416 col_map[i] = altered_table->s->fields - new_table->n_v_cols;
3417 } else {
3418 assert(!DICT_TF2_FLAG_IS_SET(new_table, DICT_TF2_FTS_HAS_DOC_ID));
3419 col_map[i] = ULINT_UNDEFINED;
3420 }
3421
3422 i++;
3423 } else {
3424 assert(!DICT_TF2_FLAG_IS_SET(old_table, DICT_TF2_FTS_HAS_DOC_ID));
3425 }
3426
3427 for (; i < old_table->n_cols; i++) {
3428 col_map[i] = i + new_table->n_cols - old_table->n_cols;
3429 }
3430
3431 return col_map;
3432 }
3433
3434 /** Drop newly create FTS index related auxiliary table during
3435 FIC create index process, before fts_add_index is called
3436 @param table table that was being rebuilt online
3437 @param trx transaction
3438 @return DB_SUCCESS if successful, otherwise last error code
3439 */
3440 static dberr_t innobase_drop_fts_index_table(dict_table_t *table, trx_t *trx) {
3441 dberr_t ret_err = DB_SUCCESS;
3442
3443 for (dict_index_t *index = table->first_index(); index != nullptr;
3444 index = index->next()) {
3445 if (index->type & DICT_FTS) {
3446 dberr_t err;
3447
3448 err = fts_drop_index_tables(trx, index, nullptr);
3449
3450 if (err != DB_SUCCESS) {
3451 ret_err = err;
3452 }
3453 }
3454 }
3455
3456 return (ret_err);
3457 }
3458
3459 /** Get the new non-virtual column names if any columns were renamed
3460 @param ha_alter_info Data used during in-place alter
3461 @param altered_table MySQL table that is being altered
3462 @param table MySQL table as it is before the ALTER operation
3463 @param user_table InnoDB table as it is before the ALTER operation
3464 @param heap Memory heap for the allocation
3465 @return array of new column names in rebuilt_table, or NULL if not renamed */
3466 [[nodiscard]] static const char **innobase_get_col_names(
3467 Alter_inplace_info *ha_alter_info, const TABLE *altered_table,
3468 const TABLE *table, const dict_table_t *user_table, mem_heap_t *heap) {
3469 const char **cols;
3470 uint i;
3471
3472 DBUG_TRACE;
3473 assert(user_table->n_t_def > table->s->fields);
3474 assert(ha_alter_info->handler_flags & Alter_inplace_info::ALTER_COLUMN_NAME);
3475
3476 cols = static_cast<const char **>(
3477 mem_heap_zalloc(heap, user_table->n_def * sizeof *cols));
3478
3479 i = 0;
3480 List_iterator_fast<Create_field> cf_it(
3481 ha_alter_info->alter_info->create_list);
3482 while (const Create_field *new_field = cf_it++) {
3483 ulint num_v = 0;
3484 assert(i < altered_table->s->fields);
3485
3486 if (innobase_is_v_fld(new_field)) {
3487 continue;
3488 }
3489
3490 for (uint old_i = 0; table->field[old_i]; old_i++) {
3491 if (innobase_is_v_fld(table->field[old_i])) {
3492 num_v++;
3493 }
3494
3495 if (new_field->field == table->field[old_i]) {
3496 cols[old_i - num_v] = new_field->field_name;
3497 break;
3498 }
3499 }
3500
3501 i++;
3502 }
3503
3504 /* Copy the internal column names. */
3505 i = table->s->fields - user_table->n_v_def;
3506 cols[i] = user_table->get_col_name(i);
3507
3508 while (++i < user_table->n_def) {
3509 cols[i] = cols[i - 1] + strlen(cols[i - 1]) + 1;
3510 }
3511
3512 return cols;
3513 }
3514
3515 /** Check whether the column prefix is increased, decreased, or unchanged.
3516 @param[in] new_prefix_len new prefix length
3517 @param[in] old_prefix_len new prefix length
3518 @retval 1 prefix is increased
3519 @retval 0 prefix is unchanged
3520 @retval -1 prefix is decreased */
3521 static inline lint innobase_pk_col_prefix_compare(ulint new_prefix_len,
3522 ulint old_prefix_len) {
3523 ut_ad(new_prefix_len < REC_MAX_DATA_SIZE);
3524 ut_ad(old_prefix_len < REC_MAX_DATA_SIZE);
3525
3526 if (new_prefix_len == old_prefix_len) {
3527 return (0);
3528 }
3529
3530 if (new_prefix_len == 0) {
3531 new_prefix_len = ULINT_MAX;
3532 }
3533
3534 if (old_prefix_len == 0) {
3535 old_prefix_len = ULINT_MAX;
3536 }
3537
3538 if (new_prefix_len > old_prefix_len) {
3539 return (1);
3540 } else {
3541 return (-1);
3542 }
3543 }
3544
3545 /** Check whether the column is existing in old table.
3546 @param[in] new_col_no new column no
3547 @param[in] col_map mapping of old column numbers to new ones
3548 @param[in] col_map_size the column map size
3549 @return true if the column is existing, otherwise false. */
3550 static inline bool innobase_pk_col_is_existing(const ulint new_col_no,
3551 const ulint *col_map,
3552 const ulint col_map_size) {
3553 for (ulint i = 0; i < col_map_size; i++) {
3554 if (col_map[i] == new_col_no) {
3555 return (true);
3556 }
3557 }
3558
3559 return (false);
3560 }
3561
3562 /** Determine whether both the indexes have same set of primary key
3563 fields arranged in the same order. If so, there is no need to do the
3564 external sorting of primary key fields.
3565
3566 Rules when we cannot skip sorting:
3567 (1) Removing existing PK columns somewhere else than at the end of the PK;
3568 (2) Adding existing columns to the PK, except at the end of the PK when no
3569 columns are removed from the PK;
3570 (3) Changing the order of existing PK columns;
3571 (4) Decreasing the prefix length just like removing existing PK columns
3572 follows rule(1), Increasing the prefix length just like adding existing
3573 PK columns follows rule(2);
3574 (5) Changing the ascending order of the existing PK columns.
3575 (6) Adding a new auto increment column with descending order in PK.
3576 @param[in] col_map mapping of old column numbers to new ones
3577 @param[in] old_clust_index index to be compared
3578 @param[in] new_clust_index index to be compared
3579 @param[in] add_autoinc added AUTO_INCREMENT column position
3580 @retval true if both indexes have same order.
3581 @retval false. */
3582 [[nodiscard]] static bool innobase_pk_order_preserved(
3583 const ulint *col_map, const dict_index_t *old_clust_index,
3584 const dict_index_t *new_clust_index, ulint add_autoinc) {
3585 ulint old_n_uniq = dict_index_get_n_ordering_defined_by_user(old_clust_index);
3586 ulint new_n_uniq = dict_index_get_n_ordering_defined_by_user(new_clust_index);
3587
3588 ut_ad(old_clust_index->is_clustered());
3589 ut_ad(new_clust_index->is_clustered());
3590 ut_ad(old_clust_index->table != new_clust_index->table);
3591 ut_ad(col_map != nullptr);
3592
3593 if (old_n_uniq == 0) {
3594 /* There was no PRIMARY KEY in the table.
3595 If there is no PRIMARY KEY after the ALTER either,
3596 no sorting is needed. */
3597 return (new_n_uniq == old_n_uniq);
3598 }
3599
3600 /* DROP PRIMARY KEY is only allowed in combination with
3601 ADD PRIMARY KEY. */
3602 ut_ad(new_n_uniq > 0);
3603
3604 /* The order of the last processed new_clust_index key field,
3605 not counting ADD COLUMN, which are constant. */
3606 lint last_field_order = -1;
3607 ulint existing_field_count = 0;
3608 ulint old_n_cols = old_clust_index->table->get_n_cols();
3609 for (ulint new_field = 0; new_field < new_n_uniq; new_field++) {
3610 ulint new_col_no = new_clust_index->fields[new_field].col->ind;
3611
3612 /* Check if there is a match in old primary key. */
3613 ulint old_field = 0;
3614 while (old_field < old_n_uniq) {
3615 ulint old_col_no = old_clust_index->fields[old_field].col->ind;
3616
3617 if (col_map[old_col_no] == new_col_no) {
3618 break;
3619 }
3620
3621 old_field++;
3622 }
3623
3624 /* The order of key field in the new primary key.
3625 1. old PK column: idx in old primary key
3626 2. existing column: old_n_uniq + sequence no
3627 3. newly added column: no order */
3628 lint new_field_order;
3629 const bool old_pk_column = old_field < old_n_uniq;
3630
3631 if (old_pk_column) {
3632 new_field_order = old_field;
3633 } else if (innobase_pk_col_is_existing(new_col_no, col_map, old_n_cols)) {
3634 new_field_order = old_n_uniq + existing_field_count++;
3635 } else {
3636 /* Skip newly added column except descending auto increment column */
3637 if (add_autoinc == new_col_no &&
3638 !new_clust_index->fields[new_field].is_ascending) {
3639 /* Descending needs sort */
3640 return (false);
3641 }
3642
3643 continue;
3644 }
3645
3646 if (last_field_order + 1 != new_field_order) {
3647 /* Old PK order is not kept, or existing column
3648 is not added at the end of old PK. */
3649 return (false);
3650 }
3651
3652 last_field_order = new_field_order;
3653
3654 if (!old_pk_column) {
3655 continue;
3656 }
3657
3658 /* Check prefix length change. */
3659 const lint prefix_change = innobase_pk_col_prefix_compare(
3660 new_clust_index->fields[new_field].prefix_len,
3661 old_clust_index->fields[old_field].prefix_len);
3662
3663 if (prefix_change < 0) {
3664 /* If a column's prefix length is decreased, it should
3665 be the last old PK column in new PK.
3666 Note: we set last_field_order to -2, so that if there
3667 are any old PK columns or existing columns after it in
3668 new PK, the comparison to new_field_order will fail in
3669 the next round.*/
3670 last_field_order = -2;
3671 } else if (prefix_change > 0) {
3672 /* If a column's prefix length is increased, it should
3673 be the last PK column in old PK. */
3674 if (old_field != old_n_uniq - 1) {
3675 return (false);
3676 }
3677 }
3678
3679 /* Check new primary key field ascending or descending changes
3680 compared to old primary key field. */
3681 bool change_asc = (new_clust_index->fields[new_field].is_ascending ==
3682 old_clust_index->fields[old_field].is_ascending);
3683
3684 if (!change_asc) {
3685 return (false);
3686 }
3687 }
3688
3689 return (true);
3690 }
3691
3692 /** Check if we are creating spatial indexes on GIS columns, which are
3693 legacy columns from earlier MySQL, such as 5.6. If so, we have to update
3694 the mtypes of the old GIS columns to DATA_GEOMETRY.
3695 In 5.6, we store GIS columns as DATA_BLOB in InnoDB layer, it will introduce
3696 confusion when we run latest server on older data. That's why we need to
3697 do the upgrade.
3698 @param[in] ha_alter_info Data used during in-place alter
3699 @param[in] table Table on which we want to add indexes
3700 @return DB_SUCCESS if update successfully or no columns need to be updated,
3701 otherwise DB_ERROR, which means we can't update the mtype for some
3702 column, and creating spatial index on it should be dangerous */
3703 static dberr_t innobase_check_gis_columns(Alter_inplace_info *ha_alter_info,
3704 dict_table_t *table) {
3705 DBUG_TRACE;
3706
3707 for (uint key_num = 0; key_num < ha_alter_info->index_add_count; key_num++) {
3708 const KEY &key =
3709 ha_alter_info
3710 ->key_info_buffer[ha_alter_info->index_add_buffer[key_num]];
3711
3712 if (!(key.flags & HA_SPATIAL)) {
3713 continue;
3714 }
3715
3716 ut_ad(key.user_defined_key_parts == 1);
3717 const KEY_PART_INFO &key_part = key.key_part[0];
3718
3719 /* Does not support spatial index on virtual columns */
3720 if (innobase_is_v_fld(key_part.field)) {
3721 return DB_UNSUPPORTED;
3722 }
3723
3724 ulint col_nr = dict_table_has_column(table, key_part.field->field_name,
3725 key_part.fieldnr);
3726 ut_ad(col_nr != table->n_def);
3727 dict_col_t *col = &table->cols[col_nr];
3728
3729 if (col->mtype != DATA_BLOB) {
3730 ut_ad(DATA_GEOMETRY_MTYPE(col->mtype));
3731 continue;
3732 }
3733
3734 const char *col_name = table->get_col_name(col_nr);
3735 col->mtype = DATA_GEOMETRY;
3736
3737 ib::info(ER_IB_MSG_598)
3738 << "Updated mtype of column" << col_name << " in table " << table->name
3739 << ", whose id is " << table->id << " to DATA_GEOMETRY";
3740 }
3741
3742 return DB_SUCCESS;
3743 }
3744
3745 /** Update the attributes for the implicit tablespaces
3746 @param[in] thd THD object
3747 @param[in] ha_alter_info Data used during in-place alter
3748 @param[in] table MySQL table that is being modified
3749 @return true Failure
3750 @return false Success */
3751 static bool prepare_inplace_change_implicit_tablespace_option(
3752 THD *thd, Alter_inplace_info *ha_alter_info, const dict_table_t *table) {
3753 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
3754 dd::cache::Dictionary_client::Auto_releaser releaser(client);
3755
3756 dd::Object_id space_id = table->dd_space_id;
3757
3758 return dd_implicit_alter_tablespace(client, space_id,
3759 ha_alter_info->create_info);
3760 }
3761
3762 /** Collect virtual column info for its addition
3763 @param[in] ha_alter_info Data used during in-place alter
3764 @param[in] altered_table MySQL table that is being altered to
3765 @param[in] table MySQL table as it is before the ALTER operation
3766 @retval true Failure
3767 @retval false Success */
3768 static bool prepare_inplace_add_virtual(Alter_inplace_info *ha_alter_info,
3769 const TABLE *altered_table,
3770 const TABLE *table) {
3771 ha_innobase_inplace_ctx *ctx;
3772 ulint i = 0;
3773 ulint j = 0;
3774 const Create_field *new_field;
3775
3776 ctx = static_cast<ha_innobase_inplace_ctx *>(ha_alter_info->handler_ctx);
3777
3778 ctx->add_vcol = static_cast<dict_v_col_t *>(mem_heap_zalloc(
3779 ctx->heap,
3780 ha_alter_info->virtual_column_add_count * sizeof *ctx->add_vcol));
3781 ctx->add_vcol_name = static_cast<const char **>(mem_heap_alloc(
3782 ctx->heap,
3783 ha_alter_info->virtual_column_add_count * sizeof *ctx->add_vcol_name));
3784
3785 List_iterator_fast<Create_field> cf_it(
3786 ha_alter_info->alter_info->create_list);
3787
3788 while ((new_field = (cf_it++)) != nullptr) {
3789 const Field *field = new_field->field;
3790 ulint old_i;
3791
3792 for (old_i = 0; table->field[old_i]; old_i++) {
3793 const Field *n_field = table->field[old_i];
3794 if (field == n_field) {
3795 break;
3796 }
3797 }
3798
3799 i++;
3800
3801 if (table->field[old_i]) {
3802 continue;
3803 }
3804
3805 ut_ad(!field);
3806
3807 ulint col_len;
3808 ulint is_unsigned;
3809 ulint field_type;
3810 ulint charset_no;
3811
3812 field = altered_table->field[i - 1];
3813
3814 ulint col_type = get_innobase_type_from_mysql_type(&is_unsigned, field);
3815 bool is_multi_value = innobase_is_multi_value_fld(field);
3816
3817 if (!field->gcol_info || field->stored_in_db) {
3818 my_error(ER_WRONG_KEY_COLUMN, MYF(0), field->field_name);
3819 return (true);
3820 }
3821
3822 if (is_multi_value) {
3823 col_len = field->key_length();
3824 } else {
3825 col_len = field->pack_length();
3826 }
3827 field_type = (ulint)field->type();
3828
3829 if (!field->is_nullable()) {
3830 field_type |= DATA_NOT_NULL;
3831 }
3832
3833 if (field->binary()) {
3834 field_type |= DATA_BINARY_TYPE;
3835 }
3836
3837 if (is_unsigned) {
3838 field_type |= DATA_UNSIGNED;
3839 }
3840
3841 if (dtype_is_string_type(col_type)) {
3842 charset_no = (ulint)field->charset()->number;
3843
3844 DBUG_EXECUTE_IF("ib_alter_add_virtual_fail",
3845 charset_no += MAX_CHAR_COLL_NUM;);
3846
3847 if (charset_no > MAX_CHAR_COLL_NUM) {
3848 my_error(ER_WRONG_KEY_COLUMN, MYF(0), field->field_name);
3849 return (true);
3850 }
3851 } else {
3852 charset_no = 0;
3853 }
3854
3855 if (field->type() == MYSQL_TYPE_VARCHAR && !is_multi_value) {
3856 uint32_t length_bytes = field->get_length_bytes();
3857
3858 col_len -= length_bytes;
3859
3860 if (length_bytes == 2) {
3861 field_type |= DATA_LONG_TRUE_VARCHAR;
3862 }
3863 }
3864
3865 ctx->add_vcol[j].m_col.prtype = dtype_form_prtype(field_type, charset_no);
3866
3867 ctx->add_vcol[j].m_col.prtype |= DATA_VIRTUAL;
3868
3869 if (is_multi_value) {
3870 ctx->add_vcol[j].m_col.prtype |= DATA_MULTI_VALUE;
3871 }
3872
3873 ctx->add_vcol[j].m_col.mtype = col_type;
3874
3875 ctx->add_vcol[j].m_col.len = col_len;
3876
3877 ctx->add_vcol[j].m_col.ind = i - 1;
3878 ctx->add_vcol[j].num_base = field->gcol_info->non_virtual_base_columns();
3879 ctx->add_vcol_name[j] = field->field_name;
3880 ctx->add_vcol[j].base_col = static_cast<dict_col_t **>(mem_heap_alloc(
3881 ctx->heap,
3882 ctx->add_vcol[j].num_base * sizeof *(ctx->add_vcol[j].base_col)));
3883 ctx->add_vcol[j].v_pos =
3884 ctx->old_table->n_v_cols - ha_alter_info->virtual_column_drop_count + j;
3885
3886 /* No need to track the list */
3887 ctx->add_vcol[j].v_indexes = nullptr;
3888 innodb_base_col_setup(ctx->old_table, field, &ctx->add_vcol[j]);
3889 j++;
3890 }
3891
3892 return (false);
3893 }
3894
3895 /** Collect virtual column info for its addition
3896 @param[in] ha_alter_info Data used during in-place alter
3897 @param[in] table MySQL table as it is before the ALTER operation
3898 @retval true Failure
3899 @retval false Success */
3900 static bool prepare_inplace_drop_virtual(Alter_inplace_info *ha_alter_info,
3901 const TABLE *table) {
3902 ha_innobase_inplace_ctx *ctx;
3903 ulint j = 0;
3904
3905 ctx = static_cast<ha_innobase_inplace_ctx *>(ha_alter_info->handler_ctx);
3906
3907 ctx->drop_vcol = static_cast<dict_v_col_t *>(mem_heap_alloc(
3908 ctx->heap,
3909 ha_alter_info->virtual_column_drop_count * sizeof *ctx->drop_vcol));
3910 ctx->drop_vcol_name = static_cast<const char **>(mem_heap_alloc(
3911 ctx->heap,
3912 ha_alter_info->virtual_column_drop_count * sizeof *ctx->drop_vcol_name));
3913
3914 for (const Alter_drop *drop : ha_alter_info->alter_info->drop_list) {
3915 const Field *field;
3916 ulint old_i;
3917
3918 if (drop->type != Alter_drop::COLUMN) continue;
3919
3920 for (old_i = 0; table->field[old_i]; old_i++) {
3921 const Field *n_field = table->field[old_i];
3922 if (!my_strcasecmp(system_charset_info, n_field->field_name,
3923 drop->name)) {
3924 break;
3925 }
3926 }
3927 /* SQL-layer already has checked that all columns to be dropped exist. */
3928 ut_ad(table->field[old_i]);
3929 field = table->field[old_i];
3930
3931 /*
3932 We don't support simultaneous removal of virtual and stored columns
3933 as in-place operation yet.
3934 */
3935 ut_ad(field->gcol_info && !field->stored_in_db);
3936
3937 ulint col_len;
3938 ulint is_unsigned;
3939 ulint field_type;
3940 ulint charset_no;
3941
3942 ulint col_type = get_innobase_type_from_mysql_type(&is_unsigned, field);
3943
3944 bool is_multi_value = innobase_is_multi_value_fld(field);
3945
3946 if (!field->gcol_info || field->stored_in_db) {
3947 my_error(ER_WRONG_KEY_COLUMN, MYF(0), field->field_name);
3948 return (true);
3949 }
3950
3951 if (is_multi_value) {
3952 col_len = field->key_length();
3953 } else {
3954 col_len = field->pack_length();
3955 }
3956
3957 field_type = (ulint)field->type();
3958
3959 if (!field->is_nullable()) {
3960 field_type |= DATA_NOT_NULL;
3961 }
3962
3963 if (field->binary()) {
3964 field_type |= DATA_BINARY_TYPE;
3965 }
3966
3967 if (is_unsigned) {
3968 field_type |= DATA_UNSIGNED;
3969 }
3970
3971 if (dtype_is_string_type(col_type)) {
3972 charset_no = (ulint)field->charset()->number;
3973
3974 DBUG_EXECUTE_IF("ib_alter_add_virtual_fail",
3975 charset_no += MAX_CHAR_COLL_NUM;);
3976
3977 if (charset_no > MAX_CHAR_COLL_NUM) {
3978 my_error(ER_WRONG_KEY_COLUMN, MYF(0), field->field_name);
3979 return (true);
3980 }
3981 } else {
3982 charset_no = 0;
3983 }
3984
3985 if (field->type() == MYSQL_TYPE_VARCHAR && !is_multi_value) {
3986 uint32_t length_bytes = field->get_length_bytes();
3987
3988 col_len -= length_bytes;
3989
3990 if (length_bytes == 2) {
3991 field_type |= DATA_LONG_TRUE_VARCHAR;
3992 }
3993 }
3994
3995 ctx->drop_vcol[j].m_col.prtype = dtype_form_prtype(field_type, charset_no);
3996
3997 ctx->drop_vcol[j].m_col.prtype |= DATA_VIRTUAL;
3998
3999 ctx->drop_vcol[j].m_col.mtype = col_type;
4000
4001 ctx->drop_vcol[j].m_col.len = col_len;
4002
4003 ctx->drop_vcol[j].m_col.ind = old_i;
4004
4005 ctx->drop_vcol_name[j] = field->field_name;
4006
4007 dict_v_col_t *v_col = dict_table_get_nth_v_col_mysql(ctx->old_table, old_i);
4008 ctx->drop_vcol[j].v_pos = v_col->v_pos;
4009 j++;
4010 }
4011
4012 return (false);
4013 }
4014
4015 /** Adjust the create index column number from "New table" to
4016 "old InnoDB table" while we are doing dropping virtual column. Since we do
4017 not create separate new table for the dropping/adding virtual columns.
4018 To correctly find the indexed column, we will need to find its col_no
4019 in the "Old Table", not the "New table".
4020 @param[in] ha_alter_info Data used during in-place alter
4021 @param[in] old_table MySQL table as it is before the ALTER operation
4022 @param[in] num_v_dropped number of virtual column dropped
4023 @param[in,out] index_def index definition */
4024 static void innodb_v_adjust_idx_col(const Alter_inplace_info *ha_alter_info,
4025 const TABLE *old_table, ulint num_v_dropped,
4026 ddl::Index_defn *index_def) {
4027 List_iterator_fast<Create_field> cf_it(
4028 ha_alter_info->alter_info->create_list);
4029 for (ulint i = 0; i < index_def->m_n_fields; i++) {
4030 #ifdef UNIV_DEBUG
4031 bool col_found = false;
4032 #endif /* UNIV_DEBUG */
4033 ulint num_v = 0;
4034
4035 auto index_field = &index_def->m_fields[i];
4036
4037 /* Only adjust virtual column col_no, since non-virtual
4038 column position (in non-vcol list) won't change unless
4039 table rebuild */
4040 if (!index_field->m_is_v_col) {
4041 continue;
4042 }
4043
4044 const Field *field = nullptr;
4045
4046 cf_it.rewind();
4047
4048 /* Found the field in the new table */
4049 while (const Create_field *new_field = cf_it++) {
4050 if (!new_field->is_virtual_gcol()) {
4051 continue;
4052 }
4053
4054 field = new_field->field;
4055
4056 if (num_v == index_field->m_col_no) {
4057 break;
4058 }
4059 num_v++;
4060 }
4061
4062 if (!field) {
4063 /* this means the field is a newly added field, this
4064 should have been blocked when we drop virtual column
4065 at the same time */
4066 ut_ad(num_v_dropped > 0);
4067 ut_error;
4068 }
4069
4070 ut_ad(field->is_virtual_gcol());
4071
4072 num_v = 0;
4073
4074 /* Look for its position in old table */
4075 for (uint old_i = 0; old_table->field[old_i]; old_i++) {
4076 if (old_table->field[old_i] == field) {
4077 /* Found it, adjust its col_no to its position
4078 in old table */
4079 index_def->m_fields[i].m_col_no = num_v;
4080 ut_d(col_found = true);
4081 break;
4082 }
4083
4084 if (old_table->field[old_i]->is_virtual_gcol()) {
4085 num_v++;
4086 }
4087 }
4088
4089 ut_ad(col_found);
4090 }
4091 }
4092
4093 /** Replace the table name in filename with the specified one
4094 @param[in] filename original file name
4095 @param[out] new_filename new file name
4096 @param[in] table_name to replace with this table name,
4097 in the format of db/name */
4098 static void replace_table_name(const char *filename, char *new_filename,
4099 const char *table_name) {
4100 const char *slash = strrchr(filename, OS_PATH_SEPARATOR);
4101 size_t len = 0;
4102
4103 if (slash == nullptr) {
4104 len = 0;
4105 } else {
4106 len = slash - filename + 1;
4107 }
4108
4109 memcpy(new_filename, filename, len);
4110
4111 slash = strchr(table_name, '/');
4112 ut_ad(slash != nullptr);
4113
4114 strcpy(new_filename + len, slash + 1);
4115
4116 len += strlen(slash + 1);
4117
4118 strcpy(new_filename + len, dot_ext[IBD]);
4119 }
4120
4121 /** Update the metadata in prepare phase. This only check if dd::Tablespace
4122 should be removed or(and) created, because to remove and store dd::Tablespace
4123 could fail, so it's better to do it earlier, to prevent a late rollback
4124 @param[in,out] thd MySQL connection
4125 @param[in] old_table Old InnoDB table object
4126 @param[in,out] new_table New InnoDB table object
4127 @param[in] old_dd_tab Old dd::Table or dd::Partition
4128 @return false On success
4129 @retval true On failure */
4130 template <typename Table>
4131 [[nodiscard]] static bool dd_prepare_inplace_alter_table(
4132 THD *thd, const dict_table_t *old_table, dict_table_t *new_table,
4133 const Table *old_dd_tab) {
4134 if (new_table->is_temporary() || old_table == new_table) {
4135 /* No need to fill in metadata for temporary tables,
4136 which would not be stored in Global DD */
4137 return false;
4138 }
4139
4140 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
4141 dd::cache::Dictionary_client::Auto_releaser releaser(client);
4142
4143 uint64_t autoextend_size{};
4144
4145 if (dict_table_is_file_per_table(old_table)) {
4146 dd::Object_id old_space_id = dd_first_index(old_dd_tab)->tablespace_id();
4147
4148 /* Copy the autoextend_size attribute value for the tablespace being
4149 dropped. This value will be copied to the new tablespace created later. */
4150 if (dd_get_tablespace_size_option(client, old_space_id, &autoextend_size)) {
4151 return true;
4152 }
4153
4154 if (dd_drop_tablespace(client, old_space_id)) {
4155 return true;
4156 }
4157 }
4158
4159 if (dict_table_is_file_per_table(new_table)) {
4160 /* Replace the table name with the final correct one */
4161 char *path = fil_space_get_first_path(new_table->space);
4162 char filename[FN_REFLEN + 1];
4163 replace_table_name(path, filename, old_table->name.m_name);
4164 ut::free(path);
4165
4166 bool discarded = false;
4167 if (dict_table_is_file_per_table(old_table)) {
4168 discarded = dd_is_discarded(*old_dd_tab);
4169 }
4170
4171 dd::Object_id dd_space_id;
4172
4173 if (dd_create_implicit_tablespace(client, new_table->space,
4174 old_table->name.m_name, filename,
4175 discarded, dd_space_id)) {
4176 my_error(ER_INTERNAL_ERROR, MYF(0),
4177 " InnoDB can't create tablespace object"
4178 " for ",
4179 new_table->name);
4180 return true;
4181 }
4182
4183 new_table->dd_space_id = dd_space_id;
4184 }
4185
4186 return false;
4187 }
4188
4189 /** Update table level instant metadata in commit phase of INPLACE ALTER
4190 @param[in] table InnoDB table object
4191 @param[in] old_dd_tab old dd::Table
4192 @param[in] new_dd_tab new dd::Table */
4193 static void dd_commit_inplace_update_instant_meta(const dict_table_t *table,
4194 const dd::Table *old_dd_tab,
4195 dd::Table *new_dd_tab) {
4196 if (!dd_table_has_instant_cols(*old_dd_tab)) {
4197 return;
4198 }
4199
4200 ut_ad(table->has_instant_cols() || table->has_row_versions());
4201
4202 const char *s = dd_table_key_strings[DD_TABLE_INSTANT_COLS];
4203 if (old_dd_tab->se_private_data().exists(s)) {
4204 ut_ad(table->is_upgraded_instant());
4205 new_dd_tab->se_private_data().set(s, table->get_instant_cols());
4206 }
4207
4208 /* Copy instant default values of columns if exists */
4209 for (uint16_t i = 0; i < table->get_n_user_cols(); ++i) {
4210 const dict_col_t *col = table->get_col(i);
4211
4212 if (col->instant_default == nullptr) {
4213 continue;
4214 }
4215
4216 dd::Column *dd_col = const_cast<dd::Column *>(
4217 dd_find_column(new_dd_tab, table->get_col_name(i)));
4218 ut_ad(dd_col != nullptr);
4219
4220 dd_write_default_value(col, dd_col);
4221 }
4222 }
4223
4224 /** Update instant metadata in commit phase for partitioned table
4225 @param[in] part_share partition share object to get each
4226 partitioned table
4227 @param[in] n_parts number of partitions
4228 @param[in] old_dd_tab old dd::Table
4229 @param[in] new_dd_tab new dd::Table */
4230 static void dd_commit_inplace_update_partition_instant_meta(
4231 const Ha_innopart_share *part_share, uint16_t n_parts,
4232 const dd::Table *old_dd_tab, dd::Table *new_dd_tab) {
4233 if (!dd_table_is_upgraded_instant(*old_dd_tab)) {
4234 return;
4235 }
4236
4237 const dict_table_t *table = part_share->get_table_part(0);
4238
4239 /* In earlier implementation of INSTANT ADD, each partition has INSTANT
4240 METADATA 'n_instant_cols' because each partiton could have different values of
4241 it. And 'n_instant_cols' of a partition has to be always >= 'n_instant_cols'
4242 of table. So while setting table level metadata take the minimum of all the
4243 partitions */
4244 for (uint16_t i = 1; i < n_parts; ++i) {
4245 if (part_share->get_table_part(i)->get_instant_cols() <
4246 table->get_instant_cols()) {
4247 table = part_share->get_table_part(i);
4248 }
4249 }
4250
4251 ut_ad(table->has_instant_cols());
4252
4253 dd_commit_inplace_update_instant_meta(table, old_dd_tab, new_dd_tab);
4254
4255 uint16_t i = 0;
4256 for (auto part : *new_dd_tab->leaf_partitions()) {
4257 if (part_share->get_table_part(i)->has_instant_cols()) {
4258 part->se_private_data().set(
4259 dd_partition_key_strings[DD_PARTITION_INSTANT_COLS],
4260 part_share->get_table_part(i)->get_instant_cols());
4261 }
4262
4263 ++i;
4264 }
4265 }
4266
4267 /** Update metadata in commit phase. Note this function should only update
4268 the metadata which would not result in failure
4269 @param[in] old_info Some table information for the old table
4270 @param[in,out] new_table New InnoDB table object
4271 @param[in] old_dd_tab Old dd::Table or dd::Partition
4272 @param[in,out] new_dd_tab New dd::Table or dd::Partition */
4273 template <typename Table>
4274 static void dd_commit_inplace_alter_table(
4275 const alter_table_old_info_t &old_info, dict_table_t *new_table,
4276 const Table *old_dd_tab, Table *new_dd_tab) {
4277 if (new_table->is_temporary()) {
4278 /* No need to fill in metadata for temporary tables,
4279 which would not be stored in Global DD */
4280 return;
4281 }
4282
4283 dd::Object_id dd_space_id;
4284
4285 if (old_info.m_rebuild) {
4286 ut_ad(!new_table->has_instant_cols());
4287 ut_ad(!new_table->has_row_versions());
4288
4289 if (dict_table_is_file_per_table(new_table)) {
4290 /* Get the one created in prepare phase */
4291 dd_space_id = new_table->dd_space_id;
4292 } else if (new_table->space == TRX_SYS_SPACE) {
4293 dd_space_id = dict_sys_t::s_dd_sys_space_id;
4294 } else {
4295 /* Currently, even if specifying a new TABLESPACE
4296 for partitioned table, existing partitions would not
4297 be moved to new tablespaces. Thus, the old
4298 tablespace id should still be used for new partition */
4299 if (dd_table_is_partitioned(new_dd_tab->table())) {
4300 dd_space_id = dd_first_index(old_dd_tab)->tablespace_id();
4301 } else {
4302 dd_space_id = dd_get_space_id(new_dd_tab->table());
4303 }
4304 ut_ad(dd_space_id != dd::INVALID_OBJECT_ID);
4305 }
4306 } else {
4307 if (old_info.m_fts_doc_id &&
4308 !dd_find_column(&new_dd_tab->table(), FTS_DOC_ID_COL_NAME)) {
4309 dd::Column *col =
4310 dd_add_hidden_column(&new_dd_tab->table(), FTS_DOC_ID_COL_NAME,
4311 FTS_DOC_ID_LEN, dd::enum_column_types::LONGLONG);
4312
4313 dd_set_hidden_unique_index(new_dd_tab->table().add_index(),
4314 FTS_DOC_ID_INDEX_NAME, col);
4315 }
4316
4317 dd_space_id = dd_first_index(old_dd_tab)->tablespace_id();
4318 }
4319
4320 dd_set_table_options(new_dd_tab, new_table);
4321
4322 new_table->dd_space_id = dd_space_id;
4323
4324 dd_write_table(dd_space_id, new_dd_tab, new_table);
4325
4326 /* If this table is discarded, we need to set this to both dd::Table
4327 and dd::Tablespace. */
4328 if (old_info.m_discarded) {
4329 dd_set_discarded(*new_dd_tab, true);
4330
4331 THD *thd = current_thd;
4332 dd::Object_id dd_space_id =
4333 (*new_dd_tab->indexes()->begin())->tablespace_id();
4334 std::string space_name(new_table->name.m_name);
4335 dict_name::convert_to_space(space_name);
4336 dd_tablespace_set_state(thd, dd_space_id, space_name,
4337 DD_SPACE_STATE_DISCARDED);
4338 }
4339 }
4340
4341 template <typename Table>
4342 static void dd_commit_inplace_no_change(const Alter_inplace_info *ha_alter_info,
4343 const Table *old_dd_tab,
4344 Table *new_dd_tab, bool ignore_fts) {
4345 if (!ignore_fts) {
4346 dd_add_fts_doc_id_index(new_dd_tab->table(), old_dd_tab->table());
4347 }
4348
4349 dd_copy_private(*new_dd_tab, *old_dd_tab);
4350
4351 if (!dd_table_is_partitioned(new_dd_tab->table()) ||
4352 dd_part_is_first(reinterpret_cast<dd::Partition *>(new_dd_tab))) {
4353 dd_copy_table(ha_alter_info, new_dd_tab->table(), old_dd_tab->table());
4354 }
4355 }
4356
4357 /** Check if the key parts of the indexes of new table will exceed the
4358 index limit based on the table row format
4359 @param[in] form MySQL table that is being altered
4360 @param[in] max_part_len max index part length allowed
4361 @return true if within limits false otherwise */
4362 static bool innobase_check_index_len(const TABLE *form, ulint max_part_len) {
4363 bool valid = true;
4364 dd_visit_keys_with_too_long_parts(form, max_part_len,
4365 [&valid](auto) { valid = false; });
4366 return valid;
4367 }
4368
4369 /** Update internal structures with concurrent writes blocked,
4370 while preparing ALTER TABLE.
4371
4372 @param ha_alter_info Data used during in-place alter
4373 @param altered_table MySQL table that is being altered
4374 @param old_table MySQL table as it is before the ALTER operation
4375 @param old_dd_tab old dd table
4376 @param new_dd_tab new dd table
4377 @param table_name Table name in MySQL
4378 @param flags Table and tablespace flags
4379 @param flags2 Additional table flags
4380 @param fts_doc_id_col The column number of FTS_DOC_ID
4381 @param add_fts_doc_id Flag: add column FTS_DOC_ID?
4382 @param add_fts_doc_id_idx Flag: add index FTS_DOC_ID_INDEX (FTS_DOC_ID)?
4383
4384 @retval true Failure
4385 @retval false Success */
4386 template <typename Table>
4387 [[nodiscard]] static bool prepare_inplace_alter_table_dict(
4388 Alter_inplace_info *ha_alter_info, const TABLE *altered_table,
4389 const TABLE *old_table, const Table *old_dd_tab, Table *new_dd_tab,
4390 const char *table_name, uint32_t flags, uint32_t flags2,
4391 ulint fts_doc_id_col, bool add_fts_doc_id, bool add_fts_doc_id_idx) {
4392 bool dict_locked = false;
4393 ulint *add_key_nums; /* MySQL key numbers */
4394 ddl::Index_defn *index_defs; /* index definitions */
4395 dict_table_t *user_table;
4396 dict_index_t *fts_index = nullptr;
4397 dberr_t error;
4398 ulint num_fts_index;
4399 dict_add_v_col_t *add_v = nullptr;
4400 dict_table_t *table;
4401 MDL_ticket *mdl = nullptr;
4402 THD *thd = current_thd;
4403 bool build_fts_common = false;
4404
4405 ha_innobase_inplace_ctx *ctx;
4406
4407 DBUG_TRACE;
4408
4409 ctx = static_cast<ha_innobase_inplace_ctx *>(ha_alter_info->handler_ctx);
4410
4411 assert((ctx->add_autoinc != ULINT_UNDEFINED) ==
4412 (ctx->sequence.m_max_value > 0));
4413 assert(!ctx->num_to_drop_index == !ctx->drop_index);
4414 assert(!ctx->num_to_drop_fk == !ctx->drop_fk);
4415 assert(!add_fts_doc_id || add_fts_doc_id_idx);
4416 assert(!add_fts_doc_id_idx || innobase_fulltext_exist(altered_table));
4417 assert(!ctx->add_cols);
4418 assert(!ctx->add_index);
4419 assert(!ctx->add_key_numbers);
4420 assert(!ctx->num_to_add_index);
4421
4422 user_table = ctx->new_table;
4423
4424 trx_start_if_not_started_xa(ctx->prebuilt->trx, true, UT_LOCATION_HERE);
4425
4426 if (ha_alter_info->handler_flags & Alter_inplace_info::DROP_VIRTUAL_COLUMN) {
4427 if (prepare_inplace_drop_virtual(ha_alter_info, old_table)) {
4428 return true;
4429 }
4430 }
4431
4432 if (ha_alter_info->handler_flags & Alter_inplace_info::ADD_VIRTUAL_COLUMN) {
4433 if (prepare_inplace_add_virtual(ha_alter_info, altered_table, old_table)) {
4434 return true;
4435 }
4436
4437 /* Need information for newly added virtual columns
4438 for create index */
4439 if (ha_alter_info->handler_flags & Alter_inplace_info::ADD_INDEX) {
4440 for (ulint i = 0; i < ha_alter_info->virtual_column_add_count; i++) {
4441 /* Set mbminmax for newly added column */
4442 ulint i_mbminlen, i_mbmaxlen;
4443 dtype_get_mblen(ctx->add_vcol[i].m_col.mtype,
4444 ctx->add_vcol[i].m_col.prtype, &i_mbminlen,
4445 &i_mbmaxlen);
4446
4447 ctx->add_vcol[i].m_col.set_mbminmaxlen(i_mbminlen, i_mbmaxlen);
4448 }
4449 add_v = static_cast<dict_add_v_col_t *>(
4450 mem_heap_alloc(ctx->heap, sizeof *add_v));
4451 add_v->n_v_col = ha_alter_info->virtual_column_add_count;
4452 add_v->v_col = ctx->add_vcol;
4453 add_v->v_col_name = ctx->add_vcol_name;
4454 }
4455 }
4456
4457 if ((ha_alter_info->handler_flags &
4458 Alter_inplace_info::CHANGE_CREATE_OPTION) &&
4459 !(ha_alter_info->create_info->used_fields & HA_CREATE_USED_TABLESPACE) &&
4460 ha_alter_info->create_info
4461 ->m_implicit_tablespace_autoextend_size_change) {
4462 /* Update the autoextend_size value in the data dictionary. Do not update
4463 if the table is being moved to a new tablespace. The autoextend_size value
4464 for the new tablespace will be updated later. */
4465 if (prepare_inplace_change_implicit_tablespace_option(
4466 ctx->prebuilt->trx->mysql_thd, ha_alter_info, ctx->old_table)) {
4467 return true;
4468 }
4469 }
4470
4471 /* There should be no order change for virtual columns coming in
4472 here */
4473 ut_ad(check_v_col_in_order(old_table, altered_table, ha_alter_info));
4474
4475 ctx->trx = ctx->prebuilt->trx;
4476
4477 /* Create table containing all indexes to be built in this
4478 ALTER TABLE ADD INDEX so that they are in the correct order
4479 in the table. */
4480
4481 ctx->num_to_add_index = ha_alter_info->index_add_count;
4482
4483 ut_ad(ctx->prebuilt->trx->mysql_thd != nullptr);
4484 const char *path = thd_innodb_tmpdir(ctx->prebuilt->trx->mysql_thd);
4485
4486 index_defs = innobase_create_key_defs(
4487 ctx->heap, ha_alter_info, altered_table, new_dd_tab,
4488 ctx->num_to_add_index, num_fts_index,
4489 row_table_got_default_clust_index(ctx->new_table), fts_doc_id_col,
4490 add_fts_doc_id, add_fts_doc_id_idx);
4491
4492 bool new_clustered = DICT_CLUSTERED & index_defs[0].m_ind_type;
4493
4494 if (num_fts_index > 1) {
4495 my_error(ER_INNODB_FT_LIMIT, MYF(0));
4496 goto error_handled;
4497 }
4498
4499 if (new_clustered) {
4500 /* If max index length is reduced due to row format change
4501 make sure the index can all be accommodated in new row format */
4502 ulint max_len = DICT_MAX_FIELD_LEN_BY_FORMAT_FLAG(flags);
4503
4504 if (max_len < DICT_MAX_FIELD_LEN_BY_FORMAT(ctx->old_table)) {
4505 if (!innobase_check_index_len(altered_table, max_len)) {
4506 my_error(ER_INDEX_COLUMN_TOO_LONG, MYF(0), max_len);
4507 goto error_handled;
4508 }
4509 }
4510 }
4511
4512 if (!ctx->online) {
4513 /* This is not an online operation (LOCK=NONE). */
4514 } else if (ctx->add_autoinc == ULINT_UNDEFINED && num_fts_index == 0 &&
4515 (!innobase_need_rebuild(ha_alter_info) ||
4516 !innobase_fulltext_exist(altered_table))) {
4517 /* InnoDB can perform an online operation (LOCK=NONE). */
4518 } else {
4519 /* This should have been blocked in
4520 check_if_supported_inplace_alter(). */
4521 my_error(ER_NOT_SUPPORTED_YET, MYF(0),
4522 thd_query_unsafe(ctx->prebuilt->trx->mysql_thd).str);
4523 ut_d(ut_error);
4524 ut_o(goto error_handled);
4525 }
4526
4527 /* The primary index would be rebuilt if a FTS Doc ID
4528 column is to be added, and the primary index definition
4529 is just copied from old table and stored in indexdefs[0] */
4530 assert(!add_fts_doc_id || new_clustered);
4531 assert(new_clustered ==
4532 (innobase_need_rebuild(ha_alter_info) || add_fts_doc_id));
4533
4534 /* Allocate memory for dictionary index definitions */
4535
4536 ctx->add_index = static_cast<dict_index_t **>(mem_heap_alloc(
4537 ctx->heap, ctx->num_to_add_index * sizeof *ctx->add_index));
4538 ctx->add_key_numbers = add_key_nums = static_cast<ulint *>(mem_heap_alloc(
4539 ctx->heap, ctx->num_to_add_index * sizeof *ctx->add_key_numbers));
4540
4541 /* Acquire a lock on the table before creating any indexes. */
4542 if (ctx->online) {
4543 error = DB_SUCCESS;
4544 } else {
4545 error = ddl::lock_table(ctx->prebuilt->trx, ctx->new_table, LOCK_S);
4546
4547 if (error != DB_SUCCESS) {
4548 goto error_handling;
4549 }
4550 }
4551
4552 /* Latch the InnoDB data dictionary exclusively so that no deadlocks
4553 or lock waits can happen in it during an index create operation. */
4554
4555 row_mysql_lock_data_dictionary(ctx->prebuilt->trx, UT_LOCATION_HERE);
4556 ut_ad(ctx->trx == ctx->prebuilt->trx);
4557 dict_locked = true;
4558
4559 /* Wait for background stats processing to stop using the table that
4560 we are going to alter. We know bg stats will not start using it again
4561 until we are holding the data dict locked and we are holding it here
4562 at least until checking ut_ad(user_table->n_ref_count == 1) below.
4563 XXX what may happen if bg stats opens the table after we
4564 have unlocked data dictionary below? */
4565 dict_stats_wait_bg_to_stop_using_table(user_table, ctx->trx);
4566
4567 online_retry_drop_dict_indexes(ctx->new_table, true);
4568
4569 ut_d(dict_table_check_for_dup_indexes(ctx->new_table, CHECK_ABORTED_OK));
4570
4571 /* If a new clustered index is defined for the table we need
4572 to rebuild the table with a temporary name. */
4573
4574 if (new_clustered) {
4575 const char *new_table_name = dict_mem_create_temporary_tablename(
4576 ctx->heap, ctx->new_table->name.m_name, ctx->new_table->id);
4577 ulint n_cols = 0;
4578 ulint n_v_cols = 0;
4579 ulint n_m_v_cols = 0;
4580 dtuple_t *add_cols;
4581 space_id_t space_id = 0;
4582
4583 /* SQL-layer already has checked that we are not dropping any
4584 columns in foreign keys to be kept or making referencing column
4585 in a foreign key with SET NULL action non-nullable. So no need to
4586 check this here. */
4587
4588 for (uint i = 0; i < altered_table->s->fields; i++) {
4589 const Field *field = altered_table->field[i];
4590
4591 if (innobase_is_v_fld(field)) {
4592 n_v_cols++;
4593 if (innobase_is_multi_value_fld(field)) {
4594 n_m_v_cols++;
4595 }
4596 } else {
4597 n_cols++;
4598 }
4599 }
4600
4601 ut_ad(n_cols + n_v_cols == altered_table->s->fields);
4602
4603 if (add_fts_doc_id) {
4604 n_cols++;
4605 assert(flags2 & DICT_TF2_FTS);
4606 assert(add_fts_doc_id_idx);
4607 flags2 |=
4608 DICT_TF2_FTS_ADD_DOC_ID | DICT_TF2_FTS_HAS_DOC_ID | DICT_TF2_FTS;
4609 }
4610
4611 assert(!add_fts_doc_id_idx || (flags2 & DICT_TF2_FTS));
4612
4613 /* Create the table. */
4614 table = dd_table_open_on_name(thd, &mdl, new_table_name, true,
4615 DICT_ERR_IGNORE_NONE);
4616
4617 if (table) {
4618 my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_table_name);
4619 dd_table_close(table, thd, &mdl, true);
4620 goto new_clustered_failed;
4621 }
4622
4623 /* Use the old tablespace unless the tablespace
4624 is changing. */
4625 if (DICT_TF_HAS_SHARED_SPACE(user_table->flags) &&
4626 (ha_alter_info->create_info->tablespace == nullptr ||
4627 (0 == strcmp(ha_alter_info->create_info->tablespace,
4628 user_table->tablespace)))) {
4629 space_id = user_table->space;
4630 } else if (tablespace_is_shared_space(ha_alter_info->create_info)) {
4631 space_id =
4632 fil_space_get_id_by_name(ha_alter_info->create_info->tablespace);
4633 ut_a(space_id != SPACE_UNKNOWN);
4634 }
4635
4636 /* The initial space id 0 may be overridden later if this
4637 table is going to be a file_per_table tablespace. */
4638 ctx->new_table =
4639 dict_mem_table_create(new_table_name, space_id, n_cols + n_v_cols,
4640 n_v_cols, n_m_v_cols, flags, flags2);
4641
4642 /* TODO: Fix this problematic assignment */
4643 ctx->new_table->dd_space_id = new_dd_tab->tablespace_id();
4644
4645 /* The rebuilt indexed_table will use the renamed
4646 column names. */
4647 ctx->col_names = nullptr;
4648
4649 if (DICT_TF_HAS_DATA_DIR(flags)) {
4650 ctx->new_table->data_dir_path =
4651 mem_heap_strdup(ctx->new_table->heap, user_table->data_dir_path);
4652 }
4653
4654 for (uint i = 0; i < altered_table->s->fields; i++) {
4655 const Field *field = altered_table->field[i];
4656 ulint is_unsigned;
4657 ulint field_type = (ulint)field->type();
4658 ulint col_type = get_innobase_type_from_mysql_type(&is_unsigned, field);
4659 ulint charset_no;
4660 ulint col_len;
4661 bool is_virtual = innobase_is_v_fld(field);
4662 bool is_multi_value = innobase_is_multi_value_fld(field);
4663
4664 /* we assume in dtype_form_prtype() that this
4665 fits in two bytes */
4666 ut_a(field_type <= MAX_CHAR_COLL_NUM);
4667
4668 if (!field->is_nullable()) {
4669 field_type |= DATA_NOT_NULL;
4670 }
4671
4672 if (field->binary()) {
4673 field_type |= DATA_BINARY_TYPE;
4674 }
4675
4676 if (is_unsigned) {
4677 field_type |= DATA_UNSIGNED;
4678 }
4679
4680 if (dtype_is_string_type(col_type)) {
4681 charset_no = (ulint)field->charset()->number;
4682
4683 if (charset_no > MAX_CHAR_COLL_NUM) {
4684 dict_mem_table_free(ctx->new_table);
4685 my_error(ER_WRONG_KEY_COLUMN, MYF(0), field->field_name);
4686 goto new_clustered_failed;
4687 }
4688 } else {
4689 charset_no = 0;
4690 }
4691
4692 if (is_multi_value) {
4693 col_len = field->key_length();
4694 } else {
4695 col_len = field->pack_length();
4696 }
4697
4698 /* The MySQL pack length contains 1 or 2 bytes
4699 length field for a true VARCHAR. Let us
4700 subtract that, so that the InnoDB column
4701 length in the InnoDB data dictionary is the
4702 real maximum byte length of the actual data. */
4703
4704 if (field->type() == MYSQL_TYPE_VARCHAR && !is_multi_value) {
4705 uint32_t length_bytes = field->get_length_bytes();
4706
4707 col_len -= length_bytes;
4708
4709 if (length_bytes == 2) {
4710 field_type |= DATA_LONG_TRUE_VARCHAR;
4711 }
4712 }
4713
4714 if (col_type == DATA_POINT) {
4715 /* DATA_POINT should be of fixed length,
4716 instead of the pack_length(blob length). */
4717 col_len = DATA_POINT_LEN;
4718 }
4719
4720 if (dict_col_name_is_reserved(field->field_name)) {
4721 dict_mem_table_free(ctx->new_table);
4722 my_error(ER_WRONG_COLUMN_NAME, MYF(0), field->field_name);
4723 goto new_clustered_failed;
4724 }
4725
4726 if (is_virtual) {
4727 field_type |= DATA_VIRTUAL;
4728 if (is_multi_value) {
4729 field_type |= DATA_MULTI_VALUE;
4730 }
4731 dict_mem_table_add_v_col(
4732 ctx->new_table, ctx->heap, field->field_name, col_type,
4733 dtype_form_prtype(field_type, charset_no), col_len, i,
4734 field->gcol_info->non_virtual_base_columns(),
4735 !field->is_hidden_by_system());
4736 } else {
4737 dict_mem_table_add_col(
4738 ctx->new_table, ctx->heap, field->field_name, col_type,
4739 dtype_form_prtype(field_type, charset_no), col_len,
4740 !field->is_hidden_by_system(), UINT32_UNDEFINED, UINT8_UNDEFINED,
4741 UINT8_UNDEFINED);
4742 }
4743 }
4744
4745 if (n_v_cols) {
4746 ulint z = 0;
4747 for (uint i = 0; i < altered_table->s->fields; i++) {
4748 dict_v_col_t *v_col;
4749 const Field *field = altered_table->field[i];
4750
4751 if (!innobase_is_v_fld(field)) {
4752 continue;
4753 }
4754 v_col = dict_table_get_nth_v_col(ctx->new_table, z);
4755 z++;
4756 innodb_base_col_setup(ctx->new_table, field, v_col);
4757 }
4758 }
4759
4760 /* Populate row version and column counts for new table */
4761 ctx->new_table->current_row_version = 0;
4762 ctx->new_table->initial_col_count = altered_table->s->fields - n_v_cols;
4763 ctx->new_table->current_col_count = ctx->new_table->initial_col_count;
4764 ctx->new_table->total_col_count = ctx->new_table->initial_col_count;
4765
4766 if (add_fts_doc_id) {
4767 fts_add_doc_id_column(ctx->new_table, ctx->heap);
4768 ctx->new_table->fts->doc_col = fts_doc_id_col;
4769 ut_ad(fts_doc_id_col == altered_table->s->fields - n_v_cols);
4770 } else if (ctx->new_table->fts) {
4771 ctx->new_table->fts->doc_col = fts_doc_id_col;
4772 }
4773
4774 const char *compression;
4775
4776 compression = ha_alter_info->create_info->compress.str;
4777
4778 if (Compression::validate(compression) != DB_SUCCESS) {
4779 compression = nullptr;
4780 }
4781
4782 if (!Encryption::is_none(ha_alter_info->create_info->encrypt_type.str)) {
4783 /* Check if keyring is ready. */
4784 if (!Encryption::check_keyring()) {
4785 dict_mem_table_free(ctx->new_table);
4786 my_error(ER_CANNOT_FIND_KEY_IN_KEYRING, MYF(0));
4787 goto new_clustered_failed;
4788 } else {
4789 /* This flag will be used to set encryption
4790 option for file-per-table tablespace. */
4791 DICT_TF2_FLAG_SET(ctx->new_table, DICT_TF2_ENCRYPTION_FILE_PER_TABLE);
4792 }
4793 }
4794
4795 dict_sys_mutex_exit();
4796
4797 error = row_create_table_for_mysql(ctx->new_table, compression,
4798 ha_alter_info->create_info, ctx->trx,
4799 nullptr);
4800
4801 dict_sys_mutex_enter();
4802
4803 switch (error) {
4804 dict_table_t *temp_table;
4805 case DB_SUCCESS:
4806 /* To bump up the table ref count and move it
4807 to LRU list if it's not temporary table */
4808 ut_ad(dict_sys_mutex_own());
4809 if (!ctx->new_table->is_temporary() &&
4810 !ctx->new_table->explicitly_non_lru) {
4811 dict_table_allow_eviction(ctx->new_table);
4812 }
4813 if ((ctx->new_table->flags2 &
4814 (DICT_TF2_FTS | DICT_TF2_FTS_ADD_DOC_ID)) ||
4815 ctx->new_table->fts != nullptr) {
4816 fts_freeze_aux_tables(ctx->new_table);
4817 }
4818 temp_table =
4819 dd_table_open_on_name_in_mem(ctx->new_table->name.m_name, true);
4820 ut_a(ctx->new_table == temp_table);
4821 /* n_ref_count must be 1, because purge cannot
4822 be executing on this very table as we are
4823 holding MDL lock. */
4824 assert(ctx->new_table->get_ref_count() == 1);
4825 break;
4826 case DB_TABLESPACE_EXISTS:
4827 my_error(ER_TABLESPACE_EXISTS, MYF(0), new_table_name);
4828 goto new_clustered_failed;
4829 case DB_DUPLICATE_KEY:
4830 my_error(HA_ERR_TABLE_EXIST, MYF(0), altered_table->s->table_name.str);
4831 goto new_clustered_failed;
4832 case DB_UNSUPPORTED:
4833 my_error(ER_UNSUPPORTED_EXTENSION, MYF(0), new_table_name);
4834 goto new_clustered_failed;
4835 case DB_IO_NO_PUNCH_HOLE_FS:
4836 my_error(ER_INNODB_COMPRESSION_FAILURE, MYF(0),
4837 "Punch hole not supported by the filesystem or the tablespace "
4838 "page size is not large enough.");
4839 goto new_clustered_failed;
4840 case DB_IO_NO_PUNCH_HOLE_TABLESPACE:
4841 my_error(ER_INNODB_COMPRESSION_FAILURE, MYF(0),
4842 "Page Compression is not supported for this tablespace");
4843 goto new_clustered_failed;
4844 default:
4845 my_error_innodb(error, table_name, flags);
4846 new_clustered_failed:
4847 ut_ad(user_table->get_ref_count() == 1);
4848
4849 goto err_exit;
4850 }
4851
4852 if (ha_alter_info->handler_flags & Alter_inplace_info::ADD_COLUMN) {
4853 add_cols =
4854 dtuple_create_with_vcol(ctx->heap, ctx->new_table->get_n_cols(),
4855 dict_table_get_n_v_cols(ctx->new_table));
4856
4857 dict_table_copy_types(add_cols, ctx->new_table);
4858 } else {
4859 add_cols = nullptr;
4860 }
4861
4862 ctx->col_map =
4863 innobase_build_col_map(ha_alter_info, altered_table, old_table,
4864 ctx->new_table, user_table, add_cols, ctx->heap);
4865 ctx->add_cols = add_cols;
4866 } else {
4867 assert(!innobase_need_rebuild(ha_alter_info));
4868 assert(old_table->s->primary_key == altered_table->s->primary_key);
4869
4870 for (dict_index_t *index = user_table->first_index(); index != nullptr;
4871 index = index->next()) {
4872 if (!index->to_be_dropped && index->is_corrupted()) {
4873 my_error(ER_CHECK_NO_SUCH_TABLE, MYF(0));
4874 goto error_handled;
4875 }
4876 }
4877
4878 if (!ctx->new_table->fts && innobase_fulltext_exist(altered_table)) {
4879 ctx->new_table->fts = fts_create(ctx->new_table);
4880 ctx->new_table->fts->doc_col = fts_doc_id_col;
4881 }
4882
4883 /* Check if we need to update mtypes of legacy GIS columns.
4884 This check is only needed when we don't have to rebuild
4885 the table, since rebuild would update all mtypes for GIS
4886 columns */
4887 error = innobase_check_gis_columns(ha_alter_info, ctx->new_table);
4888 if (error != DB_SUCCESS) {
4889 ut_ad(error == DB_ERROR);
4890 error = DB_UNSUPPORTED;
4891 goto error_handling;
4892 }
4893 }
4894
4895 ut_ad(!dict_table_is_compressed_temporary(ctx->new_table));
4896
4897 /* Assign table_id, so that no table id of
4898 fts_create_index_tables() will be written to the undo logs. */
4899 assert(ctx->new_table->id != 0);
4900
4901 /* Create the indexes and load into dictionary. */
4902
4903 for (ulint a = 0; a < ctx->num_to_add_index; a++) {
4904 if (index_defs[a].m_ind_type & DICT_VIRTUAL &&
4905 ha_alter_info->virtual_column_drop_count > 0 && !new_clustered) {
4906 innodb_v_adjust_idx_col(ha_alter_info, old_table,
4907 ha_alter_info->virtual_column_drop_count,
4908 &index_defs[a]);
4909 }
4910
4911 ctx->add_index[a] =
4912 ddl::create_index(ctx->trx, ctx->new_table, &index_defs[a], add_v);
4913
4914 add_key_nums[a] = index_defs[a].m_key_number;
4915
4916 if (!ctx->add_index[a]) {
4917 error = ctx->trx->error_state;
4918 assert(error != DB_SUCCESS);
4919 if (error == DB_TOO_BIG_RECORD) {
4920 ib::error() << "Cannot alter the table " << user_table->name
4921 << " because the record size will exceed the maximum "
4922 "allowed size for a record on the index '"
4923 << index_defs[a].m_name << "'.";
4924 }
4925 goto error_handling;
4926 }
4927
4928 assert(ctx->add_index[a]->is_committed() == new_clustered);
4929
4930 if (ctx->add_index[a]->type & DICT_FTS) {
4931 assert(num_fts_index);
4932 assert(!fts_index);
4933 assert(ctx->add_index[a]->type == DICT_FTS);
4934 fts_index = ctx->add_index[a];
4935 }
4936
4937 /* If only online ALTER TABLE operations have been
4938 requested, allocate a modification log. If the table
4939 will be locked anyway, the modification
4940 log is unnecessary. When rebuilding the table
4941 (new_clustered), we will allocate the log for the
4942 clustered index of the old table, later. */
4943 if (new_clustered || !ctx->online || user_table->ibd_file_missing ||
4944 dict_table_is_discarded(user_table)) {
4945 /* No need to allocate a modification log. */
4946 ut_ad(!ctx->add_index[a]->online_log);
4947 } else if (ctx->add_index[a]->type & DICT_FTS) {
4948 /* Fulltext indexes are not covered
4949 by a modification log. */
4950 } else {
4951 DBUG_EXECUTE_IF("innodb_OOM_prepare_inplace_alter",
4952 error = DB_OUT_OF_MEMORY;
4953 goto error_handling;);
4954 rw_lock_x_lock(&ctx->add_index[a]->lock, UT_LOCATION_HERE);
4955 bool ok = row_log_allocate(ctx->add_index[a], nullptr, true, nullptr,
4956 nullptr, path);
4957 rw_lock_x_unlock(&ctx->add_index[a]->lock);
4958
4959 if (!ok) {
4960 error = DB_OUT_OF_MEMORY;
4961 goto error_handling;
4962 }
4963 }
4964 }
4965
4966 ut_ad(new_clustered == ctx->need_rebuild());
4967
4968 DBUG_EXECUTE_IF("innodb_OOM_prepare_inplace_alter", error = DB_OUT_OF_MEMORY;
4969 goto error_handling;);
4970
4971 if (new_clustered) {
4972 dict_index_t *clust_index = user_table->first_index();
4973 dict_index_t *new_clust_index = ctx->new_table->first_index();
4974 ctx->skip_pk_sort = innobase_pk_order_preserved(
4975 ctx->col_map, clust_index, new_clust_index, ctx->add_autoinc);
4976
4977 DBUG_EXECUTE_IF("innodb_alter_table_pk_assert_no_sort",
4978 assert(ctx->skip_pk_sort););
4979
4980 if (ctx->online) {
4981 /* Allocate a log for online table rebuild. */
4982 rw_lock_x_lock(&clust_index->lock, UT_LOCATION_HERE);
4983 bool ok = row_log_allocate(
4984 clust_index, ctx->new_table,
4985 !(ha_alter_info->handler_flags & Alter_inplace_info::ADD_PK_INDEX),
4986 ctx->add_cols, ctx->col_map, path);
4987 rw_lock_x_unlock(&clust_index->lock);
4988
4989 if (!ok) {
4990 error = DB_OUT_OF_MEMORY;
4991 goto error_handling;
4992 }
4993 }
4994 }
4995
4996 if (ctx->online) {
4997 /* Assign a consistent read view for the index build scan. */
4998 trx_assign_read_view(ctx->prebuilt->trx);
4999 }
5000
5001 if (fts_index) {
5002 /* Ensure that the dictionary operation mode will
5003 not change while creating the auxiliary tables. */
5004 #ifdef UNIV_DEBUG
5005 trx_dict_op_t op = trx_get_dict_operation(ctx->trx);
5006 #endif
5007 ut_ad(ctx->trx->dict_operation_lock_mode == RW_X_LATCH);
5008 ut_ad(dict_sys_mutex_own());
5009 ut_ad(rw_lock_own(dict_operation_lock, RW_LOCK_X));
5010
5011 DICT_TF2_FLAG_SET(ctx->new_table, DICT_TF2_FTS);
5012 if (new_clustered) {
5013 /* For !new_clustered, this will be set at
5014 commit_cache_norebuild(). */
5015 ctx->new_table->fts_doc_id_index =
5016 dict_table_get_index_on_name(ctx->new_table, FTS_DOC_ID_INDEX_NAME);
5017 assert(ctx->new_table->fts_doc_id_index != nullptr);
5018 }
5019
5020 /* This function will commit the transaction and reset
5021 the trx_t::dict_operation flag on success. */
5022
5023 dict_sys_mutex_exit();
5024 error = fts_create_index_tables(ctx->trx, fts_index);
5025 dict_sys_mutex_enter();
5026
5027 DBUG_EXECUTE_IF("innodb_test_fail_after_fts_index_table",
5028 error = DB_LOCK_WAIT_TIMEOUT;
5029 goto error_handling;);
5030
5031 if (error != DB_SUCCESS) {
5032 goto error_handling;
5033 }
5034
5035 if (!ctx->new_table->fts ||
5036 ib_vector_size(ctx->new_table->fts->indexes) == 0) {
5037 bool exist_fts_common;
5038
5039 dict_sys_mutex_exit();
5040 exist_fts_common = fts_check_common_tables_exist(ctx->new_table);
5041
5042 if (!exist_fts_common) {
5043 error = fts_create_common_tables(ctx->trx, ctx->new_table,
5044 user_table->name.m_name, true);
5045
5046 DBUG_EXECUTE_IF("innodb_test_fail_after_fts_common_table",
5047 error = DB_LOCK_WAIT_TIMEOUT;);
5048
5049 if (error != DB_SUCCESS) {
5050 dict_sys_mutex_enter();
5051 goto error_handling;
5052 }
5053
5054 build_fts_common = true;
5055 }
5056
5057 error = innobase_fts_load_stopword(ctx->new_table, nullptr,
5058 ctx->prebuilt->trx->mysql_thd)
5059 ? DB_SUCCESS
5060 : DB_ERROR;
5061
5062 dict_sys_mutex_enter();
5063
5064 if (error != DB_SUCCESS) {
5065 goto error_handling;
5066 }
5067 }
5068
5069 ut_ad(trx_get_dict_operation(ctx->trx) == op);
5070 }
5071
5072 assert(error == DB_SUCCESS);
5073
5074 if (build_fts_common || fts_index) {
5075 fts_freeze_aux_tables(ctx->new_table);
5076 }
5077
5078 row_mysql_unlock_data_dictionary(ctx->prebuilt->trx);
5079 ut_ad(ctx->trx == ctx->prebuilt->trx);
5080 dict_locked = false;
5081
5082 if (dd_prepare_inplace_alter_table(ctx->prebuilt->trx->mysql_thd, user_table,
5083 ctx->new_table, old_dd_tab)) {
5084 error = DB_ERROR;
5085 }
5086
5087 if (error == DB_SUCCESS) {
5088 if (build_fts_common) {
5089 if (!fts_create_common_dd_tables(ctx->new_table)) {
5090 error = DB_ERROR;
5091 goto error_handling;
5092 }
5093 }
5094
5095 if (fts_index) {
5096 error = fts_create_index_dd_tables(ctx->new_table);
5097 if (error != DB_SUCCESS) {
5098 goto error_handling;
5099 }
5100 }
5101 }
5102
5103 error_handling:
5104
5105 if (build_fts_common || fts_index) {
5106 fts_detach_aux_tables(ctx->new_table, dict_locked);
5107 }
5108
5109 /* After an error, remove all those index definitions from the
5110 dictionary which were defined. */
5111
5112 switch (error) {
5113 case DB_SUCCESS:
5114 ut_a(!dict_locked);
5115
5116 ut_d(dict_sys_mutex_enter());
5117 ut_d(dict_table_check_for_dup_indexes(user_table, CHECK_PARTIAL_OK));
5118 ut_d(dict_sys_mutex_exit());
5119 return false;
5120 case DB_TABLESPACE_EXISTS:
5121 my_error(ER_TABLESPACE_EXISTS, MYF(0), "(unknown)");
5122 break;
5123 case DB_DUPLICATE_KEY:
5124 my_error(ER_DUP_KEY, MYF(0));
5125 break;
5126 case DB_UNSUPPORTED:
5127 my_error(ER_TABLE_CANT_HANDLE_SPKEYS, MYF(0));
5128 break;
5129 default:
5130 my_error_innodb(error, table_name, user_table->flags);
5131 }
5132
5133 error_handled:
5134
5135 ctx->prebuilt->trx->error_index = nullptr;
5136 ctx->trx->error_state = DB_SUCCESS;
5137
5138 if (!dict_locked) {
5139 row_mysql_lock_data_dictionary(ctx->prebuilt->trx, UT_LOCATION_HERE);
5140 ut_ad(ctx->trx == ctx->prebuilt->trx);
5141 }
5142
5143 if (new_clustered) {
5144 if (ctx->need_rebuild()) {
5145 if (DICT_TF2_FLAG_IS_SET(ctx->new_table, DICT_TF2_FTS)) {
5146 innobase_drop_fts_index_table(ctx->new_table, ctx->trx);
5147 }
5148
5149 dict_table_close_and_drop(ctx->trx, ctx->new_table);
5150
5151 /* Free the log for online table rebuild, if
5152 one was allocated. */
5153
5154 dict_index_t *clust_index = user_table->first_index();
5155
5156 rw_lock_x_lock(&clust_index->lock, UT_LOCATION_HERE);
5157
5158 if (clust_index->online_log) {
5159 ut_ad(ctx->online);
5160 row_log_free(clust_index->online_log);
5161 clust_index->online_status = ONLINE_INDEX_COMPLETE;
5162 }
5163
5164 rw_lock_x_unlock(&clust_index->lock);
5165 }
5166
5167 /* n_ref_count must be 1, because purge cannot
5168 be executing on this very table as we are
5169 holding MDL. */
5170 assert(user_table->get_ref_count() == 1 || ctx->online);
5171 } else {
5172 ut_ad(!ctx->need_rebuild());
5173 ddl::drop_indexes(ctx->trx, user_table, true);
5174 }
5175
5176 ut_d(dict_table_check_for_dup_indexes(user_table, CHECK_ALL_COMPLETE));
5177 ut_ad(!user_table->drop_aborted);
5178
5179 err_exit:
5180 #ifdef UNIV_DEBUG
5181 /* Clear the to_be_dropped flag in the data dictionary cache. */
5182 for (ulint i = 0; i < ctx->num_to_drop_index; i++) {
5183 assert(ctx->drop_index[i]->is_committed());
5184 assert(ctx->drop_index[i]->to_be_dropped);
5185 ctx->drop_index[i]->to_be_dropped = 0;
5186 }
5187 #endif /* UNIV_DEBUG */
5188
5189 row_mysql_unlock_data_dictionary(ctx->prebuilt->trx);
5190 ut_ad(ctx->trx == ctx->prebuilt->trx);
5191
5192 destroy(ctx);
5193 ha_alter_info->handler_ctx = nullptr;
5194
5195 return true;
5196 }
5197
5198 /* Check whether an index is needed for the foreign key constraint.
5199 If so, if it is dropped, is there an equivalent index can play its role.
5200 @return true if the index is needed and can't be dropped */
5201 [[nodiscard]] static bool innobase_check_foreign_key_index(
5202 Alter_inplace_info *ha_alter_info, /*!< in: Structure describing
5203 changes to be done by ALTER
5204 TABLE */
5205 dict_index_t *index, /*!< in: index to check */
5206 dict_table_t *indexed_table, /*!< in: table that owns the
5207 foreign keys */
5208 const char **col_names, /*!< in: column names, or NULL
5209 for indexed_table->col_names */
5210 trx_t *trx, /*!< in/out: transaction */
5211 dict_foreign_t **drop_fk, /*!< in: Foreign key constraints
5212 to drop */
5213 ulint n_drop_fk) /*!< in: Number of foreign keys
5214 to drop */
5215 {
5216 ut_ad(index != nullptr);
5217 ut_ad(indexed_table != nullptr);
5218
5219 const dict_foreign_set *fks = &indexed_table->referenced_set;
5220
5221 /* Check for all FK references from other tables to the index. */
5222 for (dict_foreign_set::const_iterator it = fks->begin(); it != fks->end();
5223 ++it) {
5224 dict_foreign_t *foreign = *it;
5225 if (foreign->referenced_index != index) {
5226 continue;
5227 }
5228 ut_ad(indexed_table == foreign->referenced_table);
5229
5230 if (nullptr == dict_foreign_find_index(indexed_table, col_names,
5231 foreign->referenced_col_names,
5232 foreign->n_fields, index,
5233 /*check_charsets=*/true,
5234 /*check_null=*/false) &&
5235 nullptr == innobase_find_equiv_index(foreign->referenced_col_names,
5236 foreign->n_fields,
5237 ha_alter_info->key_info_buffer,
5238 ha_alter_info->index_add_buffer,
5239 ha_alter_info->index_add_count)) {
5240 /* Index cannot be dropped. */
5241 trx->error_index = index;
5242 return (true);
5243 }
5244 }
5245
5246 fks = &indexed_table->foreign_set;
5247
5248 /* Check for all FK references in current table using the index. */
5249 for (dict_foreign_set::const_iterator it = fks->begin(); it != fks->end();
5250 ++it) {
5251 dict_foreign_t *foreign = *it;
5252 if (foreign->foreign_index != index) {
5253 continue;
5254 }
5255
5256 ut_ad(indexed_table == foreign->foreign_table);
5257
5258 if (!innobase_dropping_foreign(foreign, drop_fk, n_drop_fk) &&
5259 nullptr == dict_foreign_find_index(indexed_table, col_names,
5260 foreign->foreign_col_names,
5261 foreign->n_fields, index,
5262 /*check_charsets=*/true,
5263 /*check_null=*/false) &&
5264 nullptr == innobase_find_equiv_index(foreign->foreign_col_names,
5265 foreign->n_fields,
5266 ha_alter_info->key_info_buffer,
5267 ha_alter_info->index_add_buffer,
5268 ha_alter_info->index_add_count)) {
5269 /* Index cannot be dropped. */
5270 trx->error_index = index;
5271 return (true);
5272 }
5273 }
5274
5275 return (false);
5276 }
5277
5278 /** Rename a given index in the InnoDB data dictionary cache.
5279 @param[in,out] index index to rename
5280 @param new_name new index name */
5281 static void rename_index_in_cache(dict_index_t *index, const char *new_name) {
5282 DBUG_TRACE;
5283
5284 ut_ad(dict_sys_mutex_own());
5285 ut_ad(rw_lock_own(dict_operation_lock, RW_LOCK_X));
5286
5287 size_t old_name_len = strlen(index->name);
5288 size_t new_name_len = strlen(new_name);
5289
5290 if (old_name_len >= new_name_len) {
5291 /* reuse the old buffer for the name if it is large enough */
5292 memcpy(const_cast<char *>(index->name()), new_name, new_name_len + 1);
5293 } else {
5294 /* Free the old chunk of memory if it is at the topmost
5295 place in the heap, otherwise the old chunk will be freed
5296 when the index is evicted from the cache. This code will
5297 kick-in in a repeated ALTER sequences where the old name is
5298 alternately longer/shorter than the new name:
5299 1. ALTER TABLE t RENAME INDEX a TO aa;
5300 2. ALTER TABLE t RENAME INDEX aa TO a;
5301 3. go to 1. */
5302 index->name =
5303 mem_heap_strdup_replace(index->heap,
5304 /* Presumed topmost element of the heap: */
5305 index->name, old_name_len + 1, new_name);
5306 }
5307 }
5308
5309 /**
5310 Rename all indexes in data dictionary cache of a given table that are
5311 specified in ha_alter_info.
5312
5313 @param ctx alter context, used to fetch the list of indexes to rename
5314 @param ha_alter_info fetch the new names from here
5315 */
5316 static void rename_indexes_in_cache(const ha_innobase_inplace_ctx *ctx,
5317 const Alter_inplace_info *ha_alter_info) {
5318 DBUG_TRACE;
5319
5320 ut_ad(ctx->num_to_rename == ha_alter_info->index_rename_count);
5321
5322 for (ulint i = 0; i < ctx->num_to_rename; i++) {
5323 KEY_PAIR *pair = &ha_alter_info->index_rename_buffer[i];
5324 dict_index_t *index;
5325
5326 index = ctx->rename[i];
5327
5328 ut_ad(strcmp(index->name, pair->old_key->name) == 0);
5329
5330 rename_index_in_cache(index, pair->new_key->name);
5331 }
5332 }
5333
5334 /** Fill the stored column information in s_cols list.
5335 @param[in] altered_table mysql table object
5336 @param[in] table innodb table object
5337 @param[out] s_cols list of stored column
5338 @param[out] s_heap heap for storing stored
5339 column information. */
5340 static void alter_fill_stored_column(const TABLE *altered_table,
5341 dict_table_t *table,
5342 dict_s_col_list **s_cols,
5343 mem_heap_t **s_heap) {
5344 ulint n_cols = altered_table->s->fields;
5345 ulint stored_col_no = 0;
5346
5347 for (ulint i = 0; i < n_cols; i++) {
5348 Field *field = altered_table->field[i];
5349 dict_s_col_t s_col;
5350
5351 if (!innobase_is_v_fld(field)) {
5352 stored_col_no++;
5353 }
5354
5355 if (!innobase_is_s_fld(field)) {
5356 continue;
5357 }
5358
5359 ulint num_base = field->gcol_info->non_virtual_base_columns();
5360 dict_col_t *col = table->get_col(stored_col_no);
5361
5362 s_col.m_col = col;
5363 s_col.s_pos = i;
5364
5365 if (*s_cols == nullptr) {
5366 *s_cols = ut::new_withkey<dict_s_col_list>(UT_NEW_THIS_FILE_PSI_KEY);
5367 *s_heap = mem_heap_create(100, UT_LOCATION_HERE);
5368 }
5369
5370 if (num_base != 0) {
5371 s_col.base_col = static_cast<dict_col_t **>(
5372 mem_heap_zalloc(*s_heap, num_base * sizeof(dict_col_t)));
5373 } else {
5374 s_col.base_col = nullptr;
5375 }
5376
5377 s_col.num_base = num_base;
5378 innodb_base_col_setup_for_stored(table, field, &s_col);
5379
5380 (*s_cols)->push_back(s_col);
5381 }
5382 }
5383
5384 template <typename Table>
5385 void static adjust_row_format(TABLE *old_table, TABLE *altered_table,
5386 const Table *old_dd_tab, Table *new_dd_tab) {
5387 ut_ad(old_table->s->row_type == ROW_TYPE_DEFAULT ||
5388 old_table->s->row_type == ROW_TYPE_COMPRESSED);
5389 ut_ad(old_table->s->row_type == altered_table->s->row_type);
5390 ut_ad(old_table->s->real_row_type != altered_table->s->real_row_type);
5391 ut_ad(old_dd_tab->table().row_format() != new_dd_tab->table().row_format());
5392
5393 /* Revert the row_format in DD for altered table */
5394 new_dd_tab->table().set_row_format(old_dd_tab->table().row_format());
5395
5396 /* Revert the real_row_format in table share for altered table */
5397 switch (old_dd_tab->table().row_format()) {
5398 case dd::Table::RF_REDUNDANT:
5399 altered_table->s->real_row_type = ROW_TYPE_REDUNDANT;
5400 break;
5401 case dd::Table::RF_COMPACT:
5402 altered_table->s->real_row_type = ROW_TYPE_COMPACT;
5403 break;
5404 case dd::Table::RF_COMPRESSED:
5405 altered_table->s->real_row_type = ROW_TYPE_COMPRESSED;
5406 break;
5407 case dd::Table::RF_DYNAMIC:
5408 altered_table->s->real_row_type = ROW_TYPE_DYNAMIC;
5409 break;
5410 default:
5411 ut_d(ut_error);
5412 }
5413 }
5414
5415 /** Implementation of prepare_inplace_alter_table()
5416 @tparam Table dd::Table or dd::Partition
5417 @param[in] altered_table TABLE object for new version of table.
5418 @param[in,out] ha_alter_info Structure describing changes to be done
5419 by ALTER TABLE and holding data used
5420 during in-place alter.
5421 @param[in] old_dd_tab dd::Table object representing old
5422 version of the table
5423 @param[in,out] new_dd_tab dd::Table object representing new
5424 version of the table
5425 @retval true Failure
5426 @retval false Success */
5427 template <typename Table>
5428 bool ha_innobase::prepare_inplace_alter_table_impl(
5429 TABLE *altered_table, Alter_inplace_info *ha_alter_info,
5430 const Table *old_dd_tab, Table *new_dd_tab) {
5431 dict_index_t **drop_index = nullptr; /*!< Index to be dropped */
5432 ulint n_drop_index; /*!< Number of indexes to drop */
5433 dict_index_t **rename_index; /*!< Indexes to be dropped */
5434 ulint n_rename_index; /*!< Number of indexes to rename */
5435 dict_foreign_t **drop_fk; /*!< Foreign key constraints to drop */
5436 ulint n_drop_fk; /*!< Number of foreign keys to drop */
5437 dict_foreign_t **add_fk = nullptr; /*!< Foreign key constraints to drop */
5438 ulint n_add_fk; /*!< Number of foreign keys to drop */
5439 dict_table_t *indexed_table; /*!< Table where indexes are created */
5440 mem_heap_t *heap;
5441 const char **col_names;
5442 int error;
5443 ulint add_autoinc_col_no = ULINT_UNDEFINED;
5444 ulonglong autoinc_col_max_value = 0;
5445 ulint fts_doc_col_no = ULINT_UNDEFINED;
5446 bool add_fts_doc_id = false;
5447 bool add_fts_doc_id_idx = false;
5448 bool add_fts_idx = false;
5449 dict_s_col_list *s_cols = nullptr;
5450 mem_heap_t *s_heap = nullptr;
5451
5452 DBUG_TRACE;
5453 assert(!ha_alter_info->handler_ctx);
5454 assert(ha_alter_info->create_info);
5455 assert(!srv_read_only_mode);
5456
5457 MONITOR_ATOMIC_INC(MONITOR_PENDING_ALTER_TABLE);
5458
5459 #ifdef UNIV_DEBUG
5460 for (dict_index_t *index = m_prebuilt->table->first_index(); index;
5461 index = index->next()) {
5462 ut_ad(!index->to_be_dropped);
5463 }
5464 #endif /* UNIV_DEBUG */
5465
5466 ut_d(dict_sys_mutex_enter());
5467 ut_d(dict_table_check_for_dup_indexes(m_prebuilt->table, CHECK_ABORTED_OK));
5468 ut_d(dict_sys_mutex_exit());
5469
5470 indexed_table = m_prebuilt->table;
5471
5472 if (indexed_table->is_corrupted()) {
5473 /* The clustered index is corrupted. */
5474 my_error(ER_CHECK_NO_SUCH_TABLE, MYF(0));
5475 return true;
5476 }
5477
5478 if (dict_table_is_discarded(indexed_table)) {
5479 Instant_Type type = innobase_support_instant(
5480 ha_alter_info, m_prebuilt->table, this->table, altered_table);
5481 /* Even if some operations can be done instantly without rebuilding, they
5482 are still disallowed to behave like before. */
5483 if (innobase_need_rebuild(ha_alter_info) ||
5484 (type == Instant_Type::INSTANT_VIRTUAL_ONLY ||
5485 type == Instant_Type::INSTANT_ADD_DROP_COLUMN)) {
5486 my_error(ER_TABLESPACE_DISCARDED, MYF(0), indexed_table->name.m_name);
5487 return true;
5488 }
5489 }
5490
5491 if (!(ha_alter_info->handler_flags & ~INNOBASE_INPLACE_IGNORE)) {
5492 /* Nothing to do. Since there is no MDL protected, don't
5493 try to drop aborted indexes here. */
5494 assert(m_prebuilt->trx->dict_operation_lock_mode == 0);
5495 return false;
5496 }
5497
5498 if (is_instant(ha_alter_info)) {
5499 Instant_Type type = innobase_support_instant(ha_alter_info, indexed_table,
5500 this->table, altered_table);
5501
5502 if (type == Instant_Type::INSTANT_ADD_DROP_COLUMN) {
5503 ut_a(is_valid_row_version(indexed_table->current_row_version + 1));
5504 }
5505
5506 return false;
5507 }
5508
5509 /* ALTER TABLE will not implicitly move a table from a single-table
5510 tablespace to the system tablespace when innodb_file_per_table=OFF.
5511 But it will implicitly move a table from the system tablespace to a
5512 single-table tablespace if innodb_file_per_table = ON.
5513 Tables found in a general tablespace will stay there unless ALTER
5514 TABLE contains another TABLESPACE=name. If that is found it will
5515 explicitly move a table to the named tablespace.
5516 So if you specify TABLESPACE=`innodb_system` a table can be moved
5517 into the system tablespace from either a general or file-per-table
5518 tablespace. But from then on, it is labeled as using a shared space
5519 (the create options have tablespace=='innodb_system' and the
5520 SHARED_SPACE flag is set in the table flags) so it can no longer be
5521 implicitly moved to a file-per-table tablespace. */
5522 bool in_system_space = fsp_is_system_or_temp_tablespace(indexed_table->space);
5523 bool is_file_per_table =
5524 !in_system_space && !DICT_TF_HAS_SHARED_SPACE(indexed_table->flags);
5525 #ifdef UNIV_DEBUG
5526 bool in_general_space =
5527 !in_system_space && DICT_TF_HAS_SHARED_SPACE(indexed_table->flags);
5528
5529 /* The table being altered can only be in a system tablespace,
5530 or its own file-per-table tablespace, or a general tablespace. */
5531 ut_ad(1 == in_system_space + is_file_per_table + in_general_space);
5532 #endif /* UNIV_DEBUG */
5533
5534 /* If server has passed a changed row format in the new table definition and
5535 the table isn't going to be rebuilt, revert that row_format change because it
5536 is an implicit change to the previously selected default row format. We want
5537 to keep the table using the original default row_format. */
5538 if (old_dd_tab->table().row_format() != new_dd_tab->table().row_format() &&
5539 !innobase_need_rebuild(ha_alter_info)) {
5540 adjust_row_format(this->table, altered_table, old_dd_tab, new_dd_tab);
5541 }
5542
5543 /* Make a copy for existing tablespace name */
5544 char tablespace[NAME_LEN] = {'\0'};
5545 if (indexed_table->tablespace) {
5546 strcpy(tablespace, indexed_table->tablespace());
5547 }
5548
5549 create_table_info_t info(m_user_thd, altered_table,
5550 ha_alter_info->create_info, nullptr, nullptr,
5551 indexed_table->tablespace ? tablespace : nullptr,
5552 is_file_per_table, false, 0, 0, false);
5553
5554 info.set_tablespace_type(is_file_per_table);
5555
5556 if (ha_alter_info->handler_flags & Alter_inplace_info::CHANGE_CREATE_OPTION) {
5557 const char *invalid_opt = info.create_options_are_invalid();
5558 if (invalid_opt != nullptr) {
5559 my_error(ER_ILLEGAL_HA_CREATE_OPTION, MYF(0), table_type(), invalid_opt);
5560 goto err_exit_no_heap;
5561 }
5562 }
5563
5564 /* Check if any index name is reserved. */
5565 if (innobase_index_name_is_reserved(m_user_thd,
5566 ha_alter_info->key_info_buffer,
5567 ha_alter_info->key_count)) {
5568 err_exit_no_heap:
5569 assert(m_prebuilt->trx->dict_operation_lock_mode == 0);
5570 if (ha_alter_info->handler_flags & ~INNOBASE_INPLACE_IGNORE) {
5571 online_retry_drop_dict_indexes(m_prebuilt->table, false);
5572 }
5573 return true;
5574 }
5575
5576 indexed_table = m_prebuilt->table;
5577
5578 /* Check that index keys are sensible */
5579 error = innobase_check_index_keys(ha_alter_info, indexed_table);
5580
5581 if (error) {
5582 goto err_exit_no_heap;
5583 }
5584
5585 /* Prohibit renaming a column to something that the table
5586 already contains. */
5587 if (ha_alter_info->handler_flags & Alter_inplace_info::ALTER_COLUMN_NAME) {
5588 if (!ok_to_rename_column(ha_alter_info, table, altered_table,
5589 m_prebuilt->table, false, true)) {
5590 goto err_exit_no_heap;
5591 }
5592 }
5593
5594 if (!info.innobase_table_flags()) {
5595 goto err_exit_no_heap;
5596 }
5597
5598 const uint32_t max_col_len = DICT_MAX_FIELD_LEN_BY_FORMAT_FLAG(info.flags());
5599
5600 /* Check each index's column length to make sure they do not
5601 exceed limit */
5602 for (ulint i = 0; i < ha_alter_info->index_add_count; i++) {
5603 const KEY *key =
5604 &ha_alter_info->key_info_buffer[ha_alter_info->index_add_buffer[i]];
5605
5606 if (key->flags & HA_FULLTEXT) {
5607 /* The column length does not matter for
5608 fulltext search indexes. But, UNIQUE
5609 fulltext indexes are not supported. */
5610 assert(!(key->flags & HA_NOSAME));
5611 assert(!(key->flags & HA_KEYFLAG_MASK &
5612 ~(HA_FULLTEXT | HA_PACK_KEY | HA_BINARY_PACK_KEY)));
5613 add_fts_idx = true;
5614 continue;
5615 }
5616
5617 if (innobase_check_column_length(max_col_len, key)) {
5618 my_error(ER_INDEX_COLUMN_TOO_LONG, MYF(0), max_col_len);
5619 goto err_exit_no_heap;
5620 }
5621 }
5622
5623 /* Handle corrupted full-text search indexes before adding a new one */
5624 if (add_fts_idx) {
5625 for (const dict_index_t *index = indexed_table->first_index(); index;
5626 index = index->next()) {
5627 if (!(index->type & DICT_FTS)) {
5628 continue;
5629 }
5630
5631 assert(index->type == DICT_FTS || index->is_corrupted());
5632
5633 /* We need to drop any corrupted fts indexes
5634 before we add a new fts index. */
5635 if (index->is_corrupted()) {
5636 ib_errf(m_user_thd, IB_LOG_LEVEL_ERROR, ER_INNODB_INDEX_CORRUPT,
5637 "Fulltext index '%s' is corrupt. "
5638 "you should drop this index first.",
5639 index->name());
5640
5641 goto err_exit_no_heap;
5642 }
5643 }
5644 }
5645
5646 /* Check if existing index definitions of table will exceed the index
5647 limit based on the table format */
5648 if (!innobase_check_index_len(altered_table, max_col_len)) {
5649 my_error(ER_INDEX_COLUMN_TOO_LONG, MYF(0), max_col_len);
5650 goto err_exit_no_heap;
5651 }
5652
5653 n_drop_index = 0;
5654 n_drop_fk = 0;
5655
5656 if (ha_alter_info->handler_flags &
5657 (INNOBASE_ALTER_NOREBUILD | INNOBASE_ALTER_REBUILD)) {
5658 heap = mem_heap_create(1024, UT_LOCATION_HERE);
5659
5660 if (ha_alter_info->handler_flags & Alter_inplace_info::ALTER_COLUMN_NAME) {
5661 col_names = innobase_get_col_names(ha_alter_info, altered_table, table,
5662 indexed_table, heap);
5663 } else {
5664 col_names = nullptr;
5665 }
5666 } else {
5667 heap = nullptr;
5668 col_names = nullptr;
5669 }
5670
5671 if (ha_alter_info->handler_flags & Alter_inplace_info::DROP_FOREIGN_KEY) {
5672 assert(ha_alter_info->alter_info->drop_list.size() > 0);
5673
5674 drop_fk = static_cast<dict_foreign_t **>(
5675 mem_heap_alloc(heap, ha_alter_info->alter_info->drop_list.size() *
5676 sizeof(dict_foreign_t *)));
5677
5678 for (const Alter_drop *drop : ha_alter_info->alter_info->drop_list) {
5679 if (drop->type != Alter_drop::FOREIGN_KEY) {
5680 continue;
5681 }
5682
5683 for (dict_foreign_set::iterator it =
5684 m_prebuilt->table->foreign_set.begin();
5685 it != m_prebuilt->table->foreign_set.end(); ++it) {
5686 dict_foreign_t *foreign = *it;
5687 const char *fid = strchr(foreign->id, '/');
5688
5689 assert(fid);
5690 /* If no database/ prefix was present in
5691 the FOREIGN KEY constraint name, compare
5692 to the full constraint name. */
5693 fid = fid ? fid + 1 : foreign->id;
5694
5695 if (!my_strcasecmp(system_charset_info, fid, drop->name)) {
5696 drop_fk[n_drop_fk++] = foreign;
5697 goto found_fk;
5698 }
5699 }
5700
5701 /*
5702 Since we check that foreign key to be dropped exists on SQL-layer,
5703 we should not come here unless there is some bug and data-dictionary
5704 and InnoDB dictionary cache got out of sync.
5705 */
5706 assert(0);
5707 my_error(ER_CANT_DROP_FIELD_OR_KEY, MYF(0), drop->name);
5708 goto err_exit;
5709 found_fk:
5710 continue;
5711 }
5712
5713 assert(n_drop_fk > 0);
5714 } else {
5715 drop_fk = nullptr;
5716 }
5717
5718 if (ha_alter_info->index_drop_count) {
5719 dict_index_t *drop_primary = nullptr;
5720
5721 assert(ha_alter_info->handler_flags &
5722 (Alter_inplace_info::DROP_INDEX |
5723 Alter_inplace_info::DROP_UNIQUE_INDEX |
5724 Alter_inplace_info::DROP_PK_INDEX));
5725 /* Check which indexes to drop. */
5726 drop_index = static_cast<dict_index_t **>(mem_heap_alloc(
5727 heap, (ha_alter_info->index_drop_count + 1) * sizeof *drop_index));
5728
5729 for (uint i = 0; i < ha_alter_info->index_drop_count; i++) {
5730 const KEY *key = ha_alter_info->index_drop_buffer[i];
5731 dict_index_t *index =
5732 dict_table_get_index_on_name(indexed_table, key->name);
5733
5734 if (!index) {
5735 push_warning_printf(m_user_thd, Sql_condition::SL_WARNING,
5736 HA_ERR_WRONG_INDEX,
5737 "InnoDB could not find key"
5738 " with name %s",
5739 key->name);
5740 } else {
5741 ut_ad(!index->to_be_dropped);
5742 if (!index->is_clustered()) {
5743 drop_index[n_drop_index++] = index;
5744 } else {
5745 drop_primary = index;
5746 }
5747 }
5748 }
5749
5750 /* If all FULLTEXT indexes were removed, drop an
5751 internal FTS_DOC_ID_INDEX as well, unless it exists in
5752 the table. */
5753
5754 if (innobase_fulltext_exist(table) &&
5755 !innobase_fulltext_exist(altered_table) &&
5756 !DICT_TF2_FLAG_IS_SET(indexed_table, DICT_TF2_FTS_HAS_DOC_ID)) {
5757 dict_index_t *fts_doc_index = indexed_table->fts_doc_id_index;
5758 ut_ad(fts_doc_index);
5759
5760 // Add some fault tolerance for non-debug builds.
5761 if (fts_doc_index == nullptr) {
5762 goto check_if_can_drop_indexes;
5763 }
5764
5765 assert(!fts_doc_index->to_be_dropped);
5766
5767 for (uint i = 0; i < table->s->keys; i++) {
5768 if (!my_strcasecmp(system_charset_info, FTS_DOC_ID_INDEX_NAME,
5769 table->key_info[i].name)) {
5770 /* The index exists in the MySQL
5771 data dictionary. Do not drop it,
5772 even though it is no longer needed
5773 by InnoDB fulltext search. */
5774 goto check_if_can_drop_indexes;
5775 }
5776 }
5777
5778 drop_index[n_drop_index++] = fts_doc_index;
5779 }
5780
5781 check_if_can_drop_indexes:
5782 /* Check if the indexes can be dropped. */
5783
5784 /* Prevent a race condition between DROP INDEX and
5785 CREATE TABLE adding FOREIGN KEY constraints. */
5786 row_mysql_lock_data_dictionary(m_prebuilt->trx, UT_LOCATION_HERE);
5787
5788 if (!n_drop_index) {
5789 drop_index = nullptr;
5790 } else {
5791 /* Flag all indexes that are to be dropped. */
5792 for (ulint i = 0; i < n_drop_index; i++) {
5793 ut_ad(!drop_index[i]->to_be_dropped);
5794 drop_index[i]->to_be_dropped = 1;
5795 }
5796 }
5797
5798 for (uint i = 0; i < n_drop_index; i++) {
5799 dict_index_t *index = drop_index[i];
5800
5801 if (innobase_check_foreign_key_index(ha_alter_info, index, indexed_table,
5802 col_names, m_prebuilt->trx, drop_fk,
5803 n_drop_fk)) {
5804 row_mysql_unlock_data_dictionary(m_prebuilt->trx);
5805 m_prebuilt->trx->error_index = index;
5806 print_error(HA_ERR_DROP_INDEX_FK, MYF(0));
5807 goto err_exit;
5808 }
5809 }
5810
5811 /* If a primary index is dropped, need to check
5812 any depending foreign constraints get affected */
5813 if (drop_primary && innobase_check_foreign_key_index(
5814 ha_alter_info, drop_primary, indexed_table,
5815 col_names, m_prebuilt->trx, drop_fk, n_drop_fk)) {
5816 row_mysql_unlock_data_dictionary(m_prebuilt->trx);
5817 print_error(HA_ERR_DROP_INDEX_FK, MYF(0));
5818 goto err_exit;
5819 }
5820
5821 row_mysql_unlock_data_dictionary(m_prebuilt->trx);
5822 } else {
5823 drop_index = nullptr;
5824 }
5825
5826 n_rename_index = ha_alter_info->index_rename_count;
5827 rename_index = nullptr;
5828
5829 /* Create a list of dict_index_t objects that are to be renamed,
5830 also checking for requests to rename nonexistent indexes. If
5831 the table is going to be rebuilt (new_clustered == true in
5832 prepare_inplace_alter_table_dict()), then this can be skipped,
5833 but we don't for simplicity (we have not determined the value of
5834 new_clustered yet). */
5835 if (n_rename_index > 0) {
5836 rename_index = static_cast<dict_index_t **>(
5837 mem_heap_alloc(heap, n_rename_index * sizeof(*rename_index)));
5838 for (ulint i = 0; i < n_rename_index; i++) {
5839 dict_index_t *index;
5840 const char *old_name =
5841 ha_alter_info->index_rename_buffer[i].old_key->name;
5842
5843 index = dict_table_get_index_on_name(indexed_table, old_name);
5844
5845 if (index == nullptr) {
5846 my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), old_name,
5847 m_prebuilt->table->name.m_name);
5848 goto err_exit;
5849 }
5850
5851 rename_index[i] = index;
5852 }
5853 }
5854
5855 n_add_fk = 0;
5856
5857 if (ha_alter_info->handler_flags & Alter_inplace_info::ADD_FOREIGN_KEY) {
5858 ut_ad(!m_prebuilt->trx->check_foreigns);
5859
5860 alter_fill_stored_column(altered_table, m_prebuilt->table, &s_cols,
5861 &s_heap);
5862
5863 add_fk = static_cast<dict_foreign_t **>(mem_heap_zalloc(
5864 heap,
5865 ha_alter_info->alter_info->key_list.size() * sizeof(dict_foreign_t *)));
5866
5867 if (!innobase_get_foreign_key_info(ha_alter_info, table_share,
5868 m_prebuilt->table, col_names, drop_index,
5869 n_drop_index, add_fk, &n_add_fk,
5870 m_prebuilt->trx, s_cols)) {
5871 err_exit:
5872 if (n_drop_index) {
5873 row_mysql_lock_data_dictionary(m_prebuilt->trx, UT_LOCATION_HERE);
5874
5875 /* Clear the to_be_dropped flags, which might
5876 have been set at this point. */
5877 for (ulint i = 0; i < n_drop_index; i++) {
5878 ut_ad(drop_index[i]->is_committed());
5879 drop_index[i]->to_be_dropped = 0;
5880 }
5881
5882 row_mysql_unlock_data_dictionary(m_prebuilt->trx);
5883 }
5884
5885 if (heap) {
5886 mem_heap_free(heap);
5887 }
5888
5889 if (s_cols != nullptr) {
5890 ut::delete_(s_cols);
5891 mem_heap_free(s_heap);
5892 }
5893
5894 goto err_exit_no_heap;
5895 }
5896
5897 if (s_cols != nullptr) {
5898 ut::delete_(s_cols);
5899 mem_heap_free(s_heap);
5900 }
5901 }
5902
5903 if (!(ha_alter_info->handler_flags & INNOBASE_ALTER_DATA) ||
5904 ((ha_alter_info->handler_flags & ~INNOBASE_INPLACE_IGNORE) ==
5905 Alter_inplace_info::CHANGE_CREATE_OPTION &&
5906 !innobase_need_rebuild(ha_alter_info))) {
5907 if (heap) {
5908 ha_alter_info->handler_ctx = new (m_user_thd->mem_root)
5909 ha_innobase_inplace_ctx(m_prebuilt, drop_index, n_drop_index,
5910 rename_index, n_rename_index, drop_fk,
5911 n_drop_fk, add_fk, n_add_fk,
5912 ha_alter_info->online, heap, indexed_table,
5913 col_names, ULINT_UNDEFINED, 0, 0);
5914 }
5915
5916 assert(m_prebuilt->trx->dict_operation_lock_mode == 0);
5917 if (ha_alter_info->handler_flags & ~INNOBASE_INPLACE_IGNORE) {
5918 online_retry_drop_dict_indexes(m_prebuilt->table, false);
5919 }
5920
5921 if ((ha_alter_info->handler_flags &
5922 Alter_inplace_info::DROP_VIRTUAL_COLUMN) &&
5923 prepare_inplace_drop_virtual(ha_alter_info, table)) {
5924 return true;
5925 }
5926
5927 if ((ha_alter_info->handler_flags &
5928 Alter_inplace_info::ADD_VIRTUAL_COLUMN) &&
5929 prepare_inplace_add_virtual(ha_alter_info, altered_table, table)) {
5930 return true;
5931 }
5932
5933 if (ha_alter_info->handler_ctx != nullptr) {
5934 ha_innobase_inplace_ctx *ctx =
5935 static_cast<ha_innobase_inplace_ctx *>(ha_alter_info->handler_ctx);
5936 if ((ha_alter_info->handler_flags &
5937 Alter_inplace_info::CHANGE_CREATE_OPTION) &&
5938 ha_alter_info->create_info
5939 ->m_implicit_tablespace_autoextend_size_change &&
5940 prepare_inplace_change_implicit_tablespace_option(
5941 m_user_thd, ha_alter_info, ctx->old_table)) {
5942 return true;
5943 }
5944 return dd_prepare_inplace_alter_table(m_user_thd, ctx->old_table,
5945 ctx->new_table, old_dd_tab);
5946 } else {
5947 return false;
5948 }
5949 }
5950
5951 /* If we are to build a full-text search index, check whether
5952 the table already has a DOC ID column. If not, we will need to
5953 add a Doc ID hidden column and rebuild the primary index */
5954 if (innobase_fulltext_exist(altered_table)) {
5955 ulint doc_col_no;
5956 ulint num_v = 0;
5957
5958 if (!innobase_fts_check_doc_id_col(m_prebuilt->table, altered_table,
5959 &fts_doc_col_no, &num_v)) {
5960 fts_doc_col_no = altered_table->s->fields - num_v;
5961 add_fts_doc_id = true;
5962 add_fts_doc_id_idx = true;
5963
5964 push_warning_printf(m_user_thd, Sql_condition::SL_WARNING,
5965 HA_ERR_WRONG_INDEX,
5966 "InnoDB rebuilding table to add"
5967 " column " FTS_DOC_ID_COL_NAME);
5968 } else if (fts_doc_col_no == ULINT_UNDEFINED) {
5969 goto err_exit;
5970 }
5971
5972 switch (innobase_fts_check_doc_id_index(m_prebuilt->table, altered_table,
5973 &doc_col_no)) {
5974 case FTS_NOT_EXIST_DOC_ID_INDEX:
5975 add_fts_doc_id_idx = true;
5976 break;
5977 case FTS_INCORRECT_DOC_ID_INDEX:
5978 my_error(ER_INNODB_FT_WRONG_DOCID_INDEX, MYF(0), FTS_DOC_ID_INDEX_NAME);
5979 goto err_exit;
5980 case FTS_EXIST_DOC_ID_INDEX:
5981 assert(doc_col_no == fts_doc_col_no || doc_col_no == ULINT_UNDEFINED ||
5982 (ha_alter_info->handler_flags &
5983 (Alter_inplace_info::ALTER_STORED_COLUMN_ORDER |
5984 Alter_inplace_info::DROP_STORED_COLUMN |
5985 Alter_inplace_info::ADD_STORED_BASE_COLUMN)));
5986 }
5987 }
5988
5989 /* See if an AUTO_INCREMENT column was added. */
5990 uint i = 0;
5991 ulint num_v = 0;
5992 List_iterator_fast<Create_field> cf_it(
5993 ha_alter_info->alter_info->create_list);
5994 while (const Create_field *new_field = cf_it++) {
5995 const Field *field;
5996
5997 assert(i < altered_table->s->fields);
5998
5999 for (uint old_i = 0; table->field[old_i]; old_i++) {
6000 if (new_field->field == table->field[old_i]) {
6001 goto found_col;
6002 }
6003 }
6004
6005 /* This is an added column. */
6006 assert(!new_field->field);
6007 assert(ha_alter_info->handler_flags & Alter_inplace_info::ADD_COLUMN);
6008
6009 field = altered_table->field[i];
6010
6011 assert(((field->auto_flags & Field::NEXT_NUMBER) != 0) ==
6012 field->is_flag_set(AUTO_INCREMENT_FLAG));
6013
6014 if (field->is_flag_set(AUTO_INCREMENT_FLAG)) {
6015 if (add_autoinc_col_no != ULINT_UNDEFINED) {
6016 /* This should have been blocked earlier. */
6017 my_error(ER_WRONG_AUTO_KEY, MYF(0));
6018 ut_d(ut_error);
6019 ut_o(goto err_exit);
6020 }
6021
6022 /* Get the col no of the old table non-virtual column array */
6023 add_autoinc_col_no = i - num_v;
6024
6025 autoinc_col_max_value = field->get_max_int_value();
6026 }
6027 found_col:
6028 if (innobase_is_v_fld(new_field)) {
6029 ++num_v;
6030 }
6031
6032 i++;
6033 }
6034
6035 assert(heap);
6036 assert(m_user_thd == m_prebuilt->trx->mysql_thd);
6037 assert(!ha_alter_info->handler_ctx);
6038
6039 ha_alter_info->handler_ctx = new (m_user_thd->mem_root)
6040 ha_innobase_inplace_ctx(m_prebuilt, drop_index, n_drop_index,
6041 rename_index, n_rename_index, drop_fk, n_drop_fk,
6042 add_fk, n_add_fk, ha_alter_info->online, heap,
6043 m_prebuilt->table, col_names, add_autoinc_col_no,
6044 ha_alter_info->create_info->auto_increment_value,
6045 autoinc_col_max_value);
6046
6047 return prepare_inplace_alter_table_dict(
6048 ha_alter_info, altered_table, table, old_dd_tab, new_dd_tab,
6049 table_share->table_name.str, info.flags(), info.flags2(), fts_doc_col_no,
6050 add_fts_doc_id, add_fts_doc_id_idx);
6051 }
6052
6053 /** Check that the column is part of a virtual index(index contains
6054 virtual column) in the table
6055 @param[in] table Table containing column
6056 @param[in] col column to be checked
6057 @return true if this column is indexed with other virtual columns */
6058 static bool dict_col_in_v_indexes(dict_table_t *table, dict_col_t *col) {
6059 for (dict_index_t *index = table->first_index()->next(); index != nullptr;
6060 index = index->next()) {
6061 if (!dict_index_has_virtual(index)) {
6062 continue;
6063 }
6064 for (ulint k = 0; k < index->n_fields; k++) {
6065 dict_field_t *field = index->get_field(k);
6066 if (field->col->ind == col->ind) {
6067 return (true);
6068 }
6069 }
6070 }
6071
6072 return (false);
6073 }
6074
6075 /* Check whether a columnn length change alter operation requires
6076 to rebuild the template.
6077 @param[in] altered_table TABLE object for new version of table.
6078 @param[in] ha_alter_info Structure describing changes to be done
6079 by ALTER TABLE and holding data used
6080 during in-place alter.
6081 @param[in] table table being altered
6082 @return true if needs rebuild. */
6083 static bool alter_templ_needs_rebuild(TABLE *altered_table,
6084 Alter_inplace_info *ha_alter_info,
6085 dict_table_t *table) {
6086 ulint i = 0;
6087 List_iterator_fast<Create_field> cf_it(
6088 ha_alter_info->alter_info->create_list);
6089
6090 for (Field **fp = altered_table->field; *fp; fp++, i++) {
6091 cf_it.rewind();
6092 while (const Create_field *cf = cf_it++) {
6093 for (ulint j = 0; j < table->n_cols; j++) {
6094 dict_col_t *cols = table->get_col(j);
6095 if (cf->max_display_width_in_bytes() > cols->len &&
6096 dict_col_in_v_indexes(table, cols)) {
6097 return (true);
6098 }
6099 }
6100 }
6101 }
6102
6103 return (false);
6104 }
6105
6106 /** Get the name of an erroneous key.
6107 @param[in] error_key_num InnoDB number of the erroneous key
6108 @param[in] ha_alter_info changes that were being performed
6109 @param[in] table InnoDB table
6110 @return the name of the erroneous key */
6111 static const char *get_error_key_name(ulint error_key_num,
6112 const Alter_inplace_info *ha_alter_info,
6113 const dict_table_t *table) {
6114 if (error_key_num == ULINT_UNDEFINED) {
6115 return (FTS_DOC_ID_INDEX_NAME);
6116 } else if (ha_alter_info->key_count == 0) {
6117 return (table->first_index()->name);
6118 } else {
6119 return (ha_alter_info->key_info_buffer[error_key_num].name);
6120 }
6121 }
6122
6123 template <typename Table>
6124 bool ha_innobase::inplace_alter_table_impl(TABLE *altered_table,
6125 Alter_inplace_info *ha_alter_info) {
6126 dict_add_v_col_t *add_v = nullptr;
6127 dict_vcol_templ_t *s_templ = nullptr;
6128 dict_vcol_templ_t *old_templ = nullptr;
6129 struct TABLE *eval_table = altered_table;
6130 bool rebuild_templ = false;
6131 DBUG_TRACE;
6132 assert(!srv_read_only_mode);
6133
6134 ut_ad(!rw_lock_own(dict_operation_lock, RW_LOCK_X));
6135 ut_ad(!rw_lock_own(dict_operation_lock, RW_LOCK_S));
6136
6137 DEBUG_SYNC(m_user_thd, "innodb_inplace_alter_table_enter");
6138
6139 auto all_ok = [=]() -> bool {
6140 DEBUG_SYNC(m_user_thd, "innodb_after_inplace_alter_table");
6141 return false;
6142 };
6143
6144 auto success = [&]() -> bool {
6145 ut_d(dict_sys_mutex_enter());
6146 ut_d(dict_table_check_for_dup_indexes(m_prebuilt->table, CHECK_PARTIAL_OK));
6147 ut_d(dict_sys_mutex_exit());
6148 /* prebuilt->table->n_ref_count can be anything here,
6149 given that we hold at most a shared lock on the table. */
6150 return all_ok();
6151 };
6152
6153 if (!(ha_alter_info->handler_flags & INNOBASE_ALTER_DATA) ||
6154 is_instant(ha_alter_info)) {
6155 return all_ok();
6156 }
6157
6158 if (((ha_alter_info->handler_flags & ~INNOBASE_INPLACE_IGNORE) ==
6159 Alter_inplace_info::CHANGE_CREATE_OPTION &&
6160 !innobase_need_rebuild(ha_alter_info))) {
6161 return all_ok();
6162 }
6163
6164 ha_innobase_inplace_ctx *ctx =
6165 static_cast<ha_innobase_inplace_ctx *>(ha_alter_info->handler_ctx);
6166
6167 assert(ctx);
6168 assert(ctx->trx);
6169 assert(ctx->prebuilt == m_prebuilt);
6170
6171 dict_index_t *pk = m_prebuilt->table->first_index();
6172 ut_ad(pk != nullptr);
6173
6174 /* For partitioned tables this could be already allocated from a
6175 previous partition invocation. For normal tables this is NULL. */
6176 ut::delete_(ctx->m_stage);
6177
6178 ctx->m_stage = ut::new_withkey<Alter_stage>(UT_NEW_THIS_FILE_PSI_KEY, pk);
6179
6180 if (m_prebuilt->table->ibd_file_missing ||
6181 dict_table_is_discarded(m_prebuilt->table)) {
6182 return success();
6183 }
6184
6185 /* If we are doing a table rebuilding or having added virtual
6186 columns in the same clause, we will need to build a table template
6187 that carries translation information between MySQL TABLE and InnoDB
6188 table, which indicates the virtual columns and their base columns
6189 info. This is used to do the computation callback, so that the
6190 data in base columns can be extracted send to server.
6191 If the Column length changes and it is a part of virtual
6192 index then we need to rebuild the template. */
6193 rebuild_templ =
6194 ctx->need_rebuild() ||
6195 ((ha_alter_info->handler_flags &
6196 Alter_inplace_info::ALTER_COLUMN_EQUAL_PACK_LENGTH) &&
6197 alter_templ_needs_rebuild(altered_table, ha_alter_info, ctx->new_table));
6198
6199 if ((ctx->new_table->n_v_cols > 0) && rebuild_templ) {
6200 /* Save the templ if isn't NULL so as to restore the
6201 original state in case of alter operation failures. */
6202 if (ctx->new_table->vc_templ != nullptr && !ctx->need_rebuild()) {
6203 old_templ = ctx->new_table->vc_templ;
6204 }
6205 s_templ = ut::new_withkey<dict_vcol_templ_t>(UT_NEW_THIS_FILE_PSI_KEY);
6206 s_templ->vtempl = nullptr;
6207
6208 innobase_build_v_templ(altered_table, ctx->new_table, s_templ, nullptr,
6209 false, nullptr);
6210
6211 ctx->new_table->vc_templ = s_templ;
6212 } else if (ha_alter_info->virtual_column_add_count > 0 &&
6213 ha_alter_info->virtual_column_drop_count == 0) {
6214 /* if there is ongoing drop virtual column, then we disallow
6215 inplace add index on newly added virtual column, so it does
6216 not need to come in here to rebuild template with add_v.
6217 Please also see the assertion in innodb_v_adjust_idx_col() */
6218
6219 s_templ = ut::new_withkey<dict_vcol_templ_t>(UT_NEW_THIS_FILE_PSI_KEY);
6220
6221 add_v = static_cast<dict_add_v_col_t *>(
6222 mem_heap_alloc(ctx->heap, sizeof *add_v));
6223 add_v->n_v_col = ha_alter_info->virtual_column_add_count;
6224 add_v->v_col = ctx->add_vcol;
6225 add_v->v_col_name = ctx->add_vcol_name;
6226
6227 s_templ->vtempl = nullptr;
6228
6229 innobase_build_v_templ(altered_table, ctx->new_table, s_templ, add_v, false,
6230 nullptr);
6231 old_templ = ctx->new_table->vc_templ;
6232 ctx->new_table->vc_templ = s_templ;
6233 }
6234
6235 /* Drop virtual column without rebuild will keep dict table
6236 unchanged, we use old table to evaluate virtual column value
6237 in innobase_get_computed_value(). */
6238 if (!ctx->need_rebuild() && ha_alter_info->virtual_column_drop_count > 0) {
6239 eval_table = table;
6240 }
6241
6242 auto clean_up = [&](dberr_t err) -> bool {
6243 DEBUG_SYNC_C("alter_table_update_log");
6244
6245 if (err == DB_SUCCESS && ctx->online && ctx->need_rebuild()) {
6246 DEBUG_SYNC_C("row_log_table_apply1_before");
6247 err = row_log_table_apply(ctx->thr, m_prebuilt->table, altered_table,
6248 ctx->m_stage);
6249 }
6250
6251 if (s_templ) {
6252 ut_ad(ctx->need_rebuild() ||
6253 ha_alter_info->virtual_column_add_count > 0 || rebuild_templ);
6254 dict_free_vc_templ(s_templ);
6255 ut::delete_(s_templ);
6256
6257 ctx->new_table->vc_templ = old_templ;
6258 }
6259
6260 DEBUG_SYNC_C("inplace_after_index_build");
6261
6262 DBUG_EXECUTE_IF("create_index_fail", err = DB_DUPLICATE_KEY;
6263 m_prebuilt->trx->error_key_num = ULINT_UNDEFINED;);
6264
6265 /* After an error, remove all those index definitions
6266 from the dictionary which were defined. */
6267
6268 switch (err) {
6269 case DB_SUCCESS:
6270 return success();
6271 case DB_DUPLICATE_KEY: {
6272 KEY *dup_key{};
6273 if (m_prebuilt->trx->error_key_num == ULINT_UNDEFINED ||
6274 ha_alter_info->key_count == 0) {
6275 /* This should be the hidden index on
6276 FTS_DOC_ID, or there is no PRIMARY KEY in the
6277 table. Either way, we should be seeing and
6278 reporting a bogus duplicate key error. */
6279 } else if (m_prebuilt->trx->error_key_num == 0) {
6280 dup_key =
6281 &ha_alter_info->key_info_buffer[m_prebuilt->trx->error_key_num];
6282 } else {
6283 /* Check if there is generated cluster index column */
6284 if (ctx->num_to_add_index > ha_alter_info->key_count) {
6285 assert(m_prebuilt->trx->error_key_num <= ha_alter_info->key_count);
6286 dup_key =
6287 &ha_alter_info
6288 ->key_info_buffer[m_prebuilt->trx->error_key_num - 1];
6289 } else {
6290 assert(m_prebuilt->trx->error_key_num < ha_alter_info->key_count);
6291 dup_key =
6292 &ha_alter_info->key_info_buffer[m_prebuilt->trx->error_key_num];
6293 }
6294 }
6295 print_keydup_error(altered_table, dup_key, MYF(0),
6296 table_share->table_name.str);
6297 break;
6298 }
6299 case DB_ONLINE_LOG_TOO_BIG:
6300 assert(ctx->online);
6301 my_error(ER_INNODB_ONLINE_LOG_TOO_BIG, MYF(0),
6302 get_error_key_name(m_prebuilt->trx->error_key_num,
6303 ha_alter_info, m_prebuilt->table));
6304 break;
6305 case DB_INDEX_CORRUPT:
6306 my_error(ER_INDEX_CORRUPT, MYF(0),
6307 get_error_key_name(m_prebuilt->trx->error_key_num,
6308 ha_alter_info, m_prebuilt->table));
6309 break;
6310 default:
6311 my_error_innodb(err, table_share->table_name.str,
6312 m_prebuilt->table->flags);
6313 }
6314
6315 /* prebuilt->table->n_ref_count can be anything here, given
6316 that we hold at most a shared lock on the table. */
6317 m_prebuilt->trx->error_index = nullptr;
6318 ctx->trx->error_state = DB_SUCCESS;
6319
6320 return true;
6321 };
6322
6323 /* Read the clustered index of the table and build
6324 indexes based on this information using temporary
6325 files and merge sort. */
6326 DBUG_EXECUTE_IF("innodb_OOM_inplace_alter",
6327 return clean_up(DB_OUT_OF_MEMORY););
6328
6329 const auto trx = m_prebuilt->trx;
6330 const auto old_isolation_level = trx->isolation_level;
6331
6332 if (ctx->online &&
6333 trx->isolation_level != trx_t::isolation_level_t::REPEATABLE_READ) {
6334 /* We must scan the index at an isolation level >= READ COMMITTED, because
6335 a dirty read will see half written blob references.
6336
6337 ** Perform a REPEATABLE READ.
6338 When rebuilding the table online, row_log_table_apply() must not see
6339 a newer state of the table when applying the log. This is mainly to
6340 prevent false duplicate key errors, because the log will identify records
6341 by the PRIMARY KEY, and also to prevent unsafe BLOB access.
6342
6343 When creating a secondary index online, this table scan must not see
6344 records that have only been inserted to the clustered index, but have
6345 not been written to the online_log of index[]. If we performed
6346 READ UNCOMMITTED, it could happen that the ADD INDEX reaches
6347 ONLINE_INDEX_COMPLETE state between the time the DML thread has updated
6348 the clustered index but has not yet accessed secondary index. */
6349
6350 trx->isolation_level = trx_t::isolation_level_t::REPEATABLE_READ;
6351 }
6352
6353 ddl::Context ddl(trx, m_prebuilt->table, ctx->new_table, ctx->online,
6354 ctx->add_index, ctx->add_key_numbers, ctx->num_to_add_index,
6355 altered_table, ctx->add_cols, ctx->col_map, ctx->add_autoinc,
6356 ctx->sequence, ctx->skip_pk_sort, ctx->m_stage, add_v,
6357 eval_table, thd_ddl_buffer_size(m_prebuilt->trx->mysql_thd),
6358 thd_ddl_threads(m_prebuilt->trx->mysql_thd));
6359
6360 const auto err = clean_up(ddl.build());
6361
6362 trx->isolation_level = old_isolation_level;
6363
6364 return err;
6365 }
6366
6367 /** Free the modification log for online table rebuild.
6368 @param table table that was being rebuilt online */
6369 static void innobase_online_rebuild_log_free(dict_table_t *table) {
6370 dict_index_t *clust_index = table->first_index();
6371
6372 ut_ad(dict_sys_mutex_own());
6373 ut_ad(rw_lock_own(dict_operation_lock, RW_LOCK_X));
6374
6375 rw_lock_x_lock(&clust_index->lock, UT_LOCATION_HERE);
6376
6377 if (clust_index->online_log) {
6378 ut_ad(dict_index_get_online_status(clust_index) == ONLINE_INDEX_CREATION);
6379 clust_index->online_status = ONLINE_INDEX_COMPLETE;
6380 row_log_free(clust_index->online_log);
6381 DEBUG_SYNC_C("innodb_online_rebuild_log_free_aborted");
6382 }
6383
6384 assert(dict_index_get_online_status(clust_index) == ONLINE_INDEX_COMPLETE);
6385 rw_lock_x_unlock(&clust_index->lock);
6386 }
6387
6388 /** Rollback a secondary index creation, drop the indexes with
6389 temporary index prefix
6390 @param user_table InnoDB table
6391 @param table the TABLE
6392 @param locked true=table locked, false=may need to do a lazy drop
6393 @param trx the transaction
6394 */
6395 static void innobase_rollback_sec_index(dict_table_t *user_table,
6396 const TABLE *table, bool locked,
6397 trx_t *trx) {
6398 ddl::drop_indexes(trx, user_table, locked);
6399
6400 /* Free the table->fts only if there is no FTS_DOC_ID
6401 in the table */
6402 if (user_table->fts &&
6403 !DICT_TF2_FLAG_IS_SET(user_table, DICT_TF2_FTS_HAS_DOC_ID) &&
6404 !innobase_fulltext_exist(table)) {
6405 fts_free(user_table);
6406 }
6407 }
6408
6409 /** Roll back the changes made during prepare_inplace_alter_table()
6410 and inplace_alter_table() inside the storage engine. Note that the
6411 allowed level of concurrency during this operation will be the same as
6412 for inplace_alter_table() and thus might be higher than during
6413 prepare_inplace_alter_table(). (E.g concurrent writes were blocked
6414 during prepare, but might not be during commit).
6415
6416 @param[in] ha_alter_info Data used during in-place alter.
6417 @param[in] table the TABLE
6418 @param[in,out] prebuilt the prebuilt struct
6419 @retval true Failure
6420 @retval false Success
6421 */
6422 [[nodiscard]] inline bool rollback_inplace_alter_table(
6423 const Alter_inplace_info *ha_alter_info, const TABLE *table,
6424 row_prebuilt_t *prebuilt) {
6425 bool fail = false;
6426
6427 ha_innobase_inplace_ctx *ctx =
6428 static_cast<ha_innobase_inplace_ctx *>(ha_alter_info->handler_ctx);
6429
6430 DBUG_TRACE;
6431
6432 if (!ctx || !ctx->trx) {
6433 /* If we have not started a transaction yet,
6434 (almost) nothing has been or needs to be done. */
6435 goto func_exit;
6436 }
6437
6438 row_mysql_lock_data_dictionary(ctx->trx, UT_LOCATION_HERE);
6439
6440 if (ctx->need_rebuild()) {
6441 /* The table could have been closed in commit phase */
6442 if (ctx->new_table != nullptr) {
6443 dberr_t err = DB_SUCCESS;
6444 uint32_t flags = ctx->new_table->flags;
6445 /* DML threads can access ctx->new_table via the
6446 online rebuild log. Free it first. */
6447 innobase_online_rebuild_log_free(prebuilt->table);
6448
6449 dict_table_close(ctx->new_table, true, false);
6450
6451 switch (err) {
6452 case DB_SUCCESS:
6453 break;
6454 default:
6455 my_error_innodb(err, table->s->table_name.str, flags);
6456 fail = true;
6457 }
6458 }
6459 } else {
6460 assert(!(ha_alter_info->handler_flags & Alter_inplace_info::ADD_PK_INDEX));
6461 assert(ctx->new_table == prebuilt->table);
6462
6463 innobase_rollback_sec_index(prebuilt->table, table, false, ctx->trx);
6464 }
6465
6466 row_mysql_unlock_data_dictionary(ctx->trx);
6467
6468 func_exit:
6469 #ifdef UNIV_DEBUG
6470 dict_index_t *clust_index = prebuilt->table->first_index();
6471 assert(!clust_index->online_log);
6472 assert(dict_index_get_online_status(clust_index) == ONLINE_INDEX_COMPLETE);
6473 #endif /* UNIV_DEBUG */
6474
6475 if (ctx) {
6476 assert(ctx->prebuilt == prebuilt);
6477
6478 if (ctx->num_to_add_fk) {
6479 for (ulint i = 0; i < ctx->num_to_add_fk; i++) {
6480 dict_foreign_free(ctx->add_fk[i]);
6481 }
6482 }
6483
6484 if (ctx->num_to_drop_index) {
6485 row_mysql_lock_data_dictionary(prebuilt->trx, UT_LOCATION_HERE);
6486
6487 /* Clear the to_be_dropped flags
6488 in the data dictionary cache.
6489 The flags may already have been cleared,
6490 in case an error was detected in
6491 commit_inplace_alter_table(). */
6492 for (ulint i = 0; i < ctx->num_to_drop_index; i++) {
6493 dict_index_t *index = ctx->drop_index[i];
6494 assert(index->is_committed());
6495 index->to_be_dropped = 0;
6496 }
6497
6498 row_mysql_unlock_data_dictionary(prebuilt->trx);
6499 }
6500 }
6501
6502 reset_column_ord_part(prebuilt->table);
6503
6504 /* Do not commit/rollback prebuilt->trx, assume mysql will
6505 rollback it */
6506
6507 MONITOR_ATOMIC_DEC(MONITOR_PENDING_ALTER_TABLE);
6508 return fail;
6509 }
6510
6511 /** Rename or enlarge columns in the data dictionary cache
6512 as part of commit_cache_norebuild().
6513 @param ha_alter_info Data used during in-place alter.
6514 @param table the TABLE
6515 @param user_table InnoDB table that was being altered */
6516 static void innobase_rename_or_enlarge_columns_cache(
6517 Alter_inplace_info *ha_alter_info, const TABLE *table,
6518 dict_table_t *user_table) {
6519 if (!(ha_alter_info->handler_flags &
6520 (Alter_inplace_info::ALTER_COLUMN_EQUAL_PACK_LENGTH |
6521 Alter_inplace_info::ALTER_COLUMN_NAME))) {
6522 return;
6523 }
6524
6525 List_iterator_fast<Create_field> cf_it(
6526 ha_alter_info->alter_info->create_list);
6527 uint i = 0;
6528 ulint num_v = 0;
6529 ulint unsigned_flag = 0;
6530
6531 for (Field **fp = table->field; *fp; fp++, i++) {
6532 bool is_virtual = innobase_is_v_fld(*fp);
6533
6534 cf_it.rewind();
6535 while (const Create_field *cf = cf_it++) {
6536 if (cf->field != *fp) {
6537 continue;
6538 }
6539
6540 ulint col_n = is_virtual ? num_v : i - num_v;
6541
6542 if ((*fp)->is_equal(cf) == IS_EQUAL_PACK_LENGTH) {
6543 dict_col_t *col;
6544
6545 if (is_virtual) {
6546 col = &dict_table_get_nth_v_col(user_table, col_n)->m_col;
6547 } else {
6548 col = user_table->get_col(col_n);
6549 }
6550 col->len = cf->max_display_width_in_bytes();
6551
6552 ulint innodb_data_type =
6553 get_innobase_type_from_mysql_type(&unsigned_flag, cf->field);
6554 ut_ad(innodb_data_type != DATA_MISSING);
6555
6556 if (dtype_is_non_binary_string_type(innodb_data_type, col->prtype) &&
6557 (*fp)->charset()->number != cf->charset->number) {
6558 ulint old_charset = (*fp)->charset()->number;
6559 ulint new_charset = cf->charset->number;
6560 ut_ad(dtype_get_charset_coll(col->prtype) == old_charset);
6561
6562 col->prtype =
6563 dtype_form_prtype(col->prtype - (old_charset << 16), new_charset);
6564 ulint mbminlen;
6565 ulint mbmaxlen;
6566
6567 dtype_get_mblen(col->mtype, col->prtype, &mbminlen, &mbmaxlen);
6568 col->mbminmaxlen = DATA_MBMINMAXLEN(mbminlen, mbmaxlen);
6569 }
6570 }
6571
6572 if ((*fp)->is_flag_set(FIELD_IS_RENAMED)) {
6573 dict_mem_table_col_rename(user_table, col_n, cf->field->field_name,
6574 cf->field_name, is_virtual);
6575 }
6576
6577 break;
6578 }
6579
6580 if (is_virtual) {
6581 num_v++;
6582 }
6583 }
6584 }
6585 /** Get the auto-increment value of the table on commit.
6586 @param[in] ha_alter_info Data used during in-place alter
6587 @param[in,out] ctx In-place ALTER TABLE context
6588 return autoinc value in ctx->max_autoinc
6589 @param[in] altered_table MySQL table that is being altered
6590 @param[in] old_table MySQL table as it is before the ALTER operation
6591 @retval true Failure
6592 @retval false Success*/
6593 [[nodiscard]] static bool commit_get_autoinc(Alter_inplace_info *ha_alter_info,
6594 ha_innobase_inplace_ctx *ctx,
6595 const TABLE *altered_table,
6596 const TABLE *old_table) {
6597 DBUG_TRACE;
6598
6599 if (!altered_table->found_next_number_field) {
6600 /* There is no AUTO_INCREMENT column in the table
6601 after the ALTER operation. */
6602 ctx->max_autoinc = 0;
6603 } else if (ctx->add_autoinc != ULINT_UNDEFINED) {
6604 /* An AUTO_INCREMENT column was added. Get the last
6605 value from the sequence, which may be based on a
6606 supplied AUTO_INCREMENT value. */
6607 ctx->max_autoinc = ctx->sequence.last();
6608 } else if ((ha_alter_info->handler_flags &
6609 Alter_inplace_info::CHANGE_CREATE_OPTION) &&
6610 (ha_alter_info->create_info->used_fields & HA_CREATE_USED_AUTO)) {
6611 /* Check if the table is discarded */
6612 if (dict_table_is_discarded(ctx->old_table)) {
6613 return true;
6614 }
6615
6616 /* An AUTO_INCREMENT value was supplied, but the table was not
6617 rebuilt. Get the user-supplied value or the last value from the
6618 sequence. */
6619 uint64_t max_value_table;
6620
6621 Field *autoinc_field = old_table->found_next_number_field;
6622
6623 ctx->max_autoinc = ha_alter_info->create_info->auto_increment_value;
6624
6625 dict_table_autoinc_lock(ctx->old_table);
6626
6627 max_value_table = ctx->old_table->autoinc_persisted;
6628
6629 /* We still have to search the index here when we want to
6630 set the AUTO_INCREMENT value to a smaller or equal one.
6631
6632 Here is an example:
6633 Let's say we have a table t1 with one AUTOINC column, existing
6634 rows (1), (2), (100), (200), (1000), after following SQLs:
6635 DELETE FROM t1 WHERE a > 200;
6636 ALTER TABLE t1 AUTO_INCREMENT = 150;
6637 we expect the next value allocated from 201, but not 150.
6638
6639 We could only search the tree to know current max counter
6640 in the table and compare. */
6641 if (ctx->max_autoinc <= max_value_table) {
6642 dberr_t err;
6643 dict_index_t *index;
6644
6645 index = dict_table_get_index_on_first_col(ctx->old_table,
6646 autoinc_field->field_index());
6647
6648 err = row_search_max_autoinc(index, autoinc_field->field_name,
6649 &max_value_table);
6650
6651 if (err != DB_SUCCESS) {
6652 ctx->max_autoinc = 0;
6653 ut_d(ut_error);
6654 } else if (ctx->max_autoinc <= max_value_table) {
6655 ulonglong col_max_value;
6656 ulonglong offset;
6657
6658 col_max_value = autoinc_field->get_max_int_value();
6659 offset = ctx->prebuilt->autoinc_offset;
6660 ctx->max_autoinc =
6661 innobase_next_autoinc(max_value_table, 1, 1, offset, col_max_value);
6662 }
6663 }
6664
6665 dict_table_autoinc_unlock(ctx->old_table);
6666 } else {
6667 /* An AUTO_INCREMENT value was not specified.
6668 Read the old counter value from the table. */
6669 ut_ad(old_table->found_next_number_field);
6670 dict_table_autoinc_lock(ctx->old_table);
6671 ctx->max_autoinc = ctx->old_table->autoinc;
6672 dict_table_autoinc_unlock(ctx->old_table);
6673 }
6674
6675 return false;
6676 }
6677
6678 /** Add or drop foreign key constraints to the data dictionary tables,
6679 but do not touch the data dictionary cache.
6680 @param ctx In-place ALTER TABLE context
6681 @param trx Data dictionary transaction
6682 @param table_name Table name in MySQL
6683 @retval true Failure
6684 @retval false Success
6685 */
6686 [[nodiscard]] static bool innobase_update_foreign_try(
6687 ha_innobase_inplace_ctx *ctx, trx_t *trx, const char *table_name) {
6688 ulint foreign_id;
6689 ulint i;
6690
6691 DBUG_TRACE;
6692 assert(ctx);
6693
6694 foreign_id = dict_table_get_highest_foreign_id(ctx->new_table);
6695
6696 foreign_id++;
6697
6698 for (i = 0; i < ctx->num_to_add_fk; i++) {
6699 dict_foreign_t *fk = ctx->add_fk[i];
6700
6701 ut_ad(fk->foreign_table == ctx->new_table ||
6702 fk->foreign_table == ctx->old_table);
6703
6704 dberr_t error = dict_create_add_foreign_id(&foreign_id,
6705 ctx->old_table->name.m_name, fk);
6706
6707 if (error != DB_SUCCESS) {
6708 my_error(ER_TOO_LONG_IDENT, MYF(0), fk->id);
6709 return true;
6710 }
6711 if (!fk->foreign_index) {
6712 fk->foreign_index = dict_foreign_find_index(
6713 ctx->new_table, ctx->col_names, fk->foreign_col_names, fk->n_fields,
6714 fk->referenced_index, true,
6715 fk->type & (DICT_FOREIGN_ON_DELETE_SET_NULL |
6716 DICT_FOREIGN_ON_UPDATE_SET_NULL));
6717 if (!fk->foreign_index) {
6718 my_error(ER_FK_INCORRECT_OPTION, MYF(0), table_name, fk->id);
6719 return true;
6720 }
6721 }
6722
6723 /* During upgrade, inserts into SYS_* should be avoided. */
6724 if (!srv_is_upgrade_mode) {
6725 DBUG_EXECUTE_IF("innodb_test_cannot_add_fk_system", error = DB_ERROR;);
6726
6727 if (error != DB_SUCCESS) {
6728 my_error(ER_FK_FAIL_ADD_SYSTEM, MYF(0), fk->id);
6729 return true;
6730 }
6731 }
6732 }
6733 DBUG_EXECUTE_IF("ib_drop_foreign_error",
6734 my_error_innodb(DB_OUT_OF_FILE_SPACE, table_name, 0);
6735 trx->error_state = DB_SUCCESS; return true;);
6736 return false;
6737 }
6738
6739 /** Update the foreign key constraint definitions in the data dictionary cache
6740 after the changes to data dictionary tables were committed.
6741 @param[in,out] ctx In-place ALTER TABLE context
6742 @param[in] user_thd MySQL connection
6743 @param[in,out] dd_table dd table instance
6744 @return InnoDB error code (should always be DB_SUCCESS) */
6745 [[nodiscard]] static dberr_t innobase_update_foreign_cache(
6746 ha_innobase_inplace_ctx *ctx, THD *user_thd, dd::Table *dd_table) {
6747 dict_table_t *user_table;
6748 dberr_t err = DB_SUCCESS;
6749
6750 DBUG_TRACE;
6751
6752 ut_ad(dict_sys_mutex_own());
6753
6754 user_table = ctx->old_table;
6755
6756 /* Discard the added foreign keys, because we will
6757 load them from the data dictionary. */
6758 for (ulint i = 0; i < ctx->num_to_add_fk; i++) {
6759 dict_foreign_t *fk = ctx->add_fk[i];
6760 dict_foreign_free(fk);
6761 }
6762
6763 if (ctx->need_rebuild()) {
6764 /* The rebuilt table is already using the renamed
6765 column names. No need to pass col_names or to drop
6766 constraints from the data dictionary cache. */
6767 assert(!ctx->col_names);
6768 assert(user_table->foreign_set.empty());
6769 assert(user_table->referenced_set.empty());
6770 user_table = ctx->new_table;
6771 } else {
6772 /* Drop the foreign key constraints if the
6773 table was not rebuilt. If the table is rebuilt,
6774 there would not be any foreign key constraints for
6775 it yet in the data dictionary cache. */
6776 for (ulint i = 0; i < ctx->num_to_drop_fk; i++) {
6777 dict_foreign_t *fk = ctx->drop_fk[i];
6778 dict_foreign_remove_from_cache(fk);
6779 }
6780 }
6781
6782 /* Load the old or added foreign keys from the data dictionary
6783 and prevent the table from being evicted from the data
6784 dictionary cache (work around the lack of WL#6049). */
6785 dict_names_t fk_tables;
6786
6787 dd::cache::Dictionary_client *client = dd::get_dd_client(user_thd);
6788 dd::cache::Dictionary_client::Auto_releaser releaser(client);
6789 err =
6790 dd_table_load_fk(client, user_table->name.m_name, ctx->col_names,
6791 user_table, dd_table, user_thd, true, true, &fk_tables);
6792
6793 if (err == DB_CANNOT_ADD_CONSTRAINT) {
6794 fk_tables.clear();
6795
6796 /* It is possible there are existing foreign key are
6797 loaded with "foreign_key checks" off,
6798 so let's retry the loading with charset_check is off */
6799 err = dd_table_load_fk(client, user_table->name.m_name, ctx->col_names,
6800 user_table, dd_table, user_thd, true, false,
6801 &fk_tables);
6802
6803 /* The load with "charset_check" off is successful, warn
6804 the user that the foreign key has loaded with mis-matched
6805 charset */
6806 if (err == DB_SUCCESS) {
6807 push_warning_printf(user_thd, Sql_condition::SL_WARNING, ER_ALTER_INFO,
6808 "Foreign key constraints for table '%s'"
6809 " are loaded with charset check off",
6810 user_table->name.m_name);
6811 }
6812 }
6813
6814 /* For complete loading of foreign keys, all associated tables must
6815 also be loaded. */
6816
6817 while (err == DB_SUCCESS && !fk_tables.empty()) {
6818 dict_sys_mutex_exit();
6819 dd::cache::Dictionary_client *client = dd::get_dd_client(user_thd);
6820
6821 dd::cache::Dictionary_client::Auto_releaser releaser(client);
6822
6823 dd_open_fk_tables(fk_tables, false, user_thd);
6824 dict_sys_mutex_enter();
6825 }
6826
6827 return err;
6828 }
6829
6830 /** Discard the foreign key cache if anyone is affected by current
6831 column rename. This is only used for rebuild case.
6832 @param[in] ha_alter_info data used during in-place alter
6833 @param[in] mysql_table MySQL TABLE object
6834 @param[in,out] old_table InnoDB table object for old table */
6835 static void innobase_rename_col_discard_foreign(
6836 Alter_inplace_info *ha_alter_info, const TABLE *mysql_table,
6837 dict_table_t *old_table) {
6838 List_iterator_fast<Create_field> cf_it(
6839 ha_alter_info->alter_info->create_list);
6840
6841 ut_ad(ha_alter_info->handler_flags & Alter_inplace_info::ALTER_COLUMN_NAME);
6842
6843 for (Field **fp = mysql_table->field; *fp; fp++) {
6844 if (!(*fp)->is_flag_set(FIELD_IS_RENAMED)) {
6845 continue;
6846 }
6847
6848 cf_it.rewind();
6849
6850 ut_d(bool processed = false;)
6851
6852 while (Create_field *cf = cf_it++) {
6853 if (cf->field != *fp) {
6854 continue;
6855 }
6856
6857 /* Now cf->field->field_name is the old name, check the foreign key
6858 information to see any one gets affected by this rename, and discard
6859 them from cache */
6860
6861 std::list<dict_foreign_t *> fk_evict;
6862
6863 for (auto fk : old_table->foreign_set) {
6864 dict_foreign_t *foreign = fk;
6865
6866 for (unsigned i = 0; i < foreign->n_fields; i++) {
6867 if (strcmp(foreign->foreign_col_names[i], cf->field->field_name) !=
6868 0) {
6869 continue;
6870 }
6871
6872 fk_evict.push_back(foreign);
6873 break;
6874 }
6875 }
6876
6877 for (auto fk : old_table->referenced_set) {
6878 dict_foreign_t *foreign = fk;
6879
6880 for (unsigned i = 0; i < foreign->n_fields; i++) {
6881 if (strcmp(foreign->referenced_col_names[i], cf->field->field_name) !=
6882 0) {
6883 continue;
6884 }
6885
6886 fk_evict.push_back(foreign);
6887 break;
6888 }
6889 }
6890
6891 std::for_each(fk_evict.begin(), fk_evict.end(),
6892 dict_foreign_remove_from_cache);
6893
6894 ut_d(processed = true;)
6895 }
6896
6897 ut_ad(processed);
6898 }
6899 }
6900
6901 /** Commit the changes made during prepare_inplace_alter_table()
6902 and inplace_alter_table() inside the data dictionary tables,
6903 when rebuilding the table.
6904 @param ha_alter_info Data used during in-place alter
6905 @param ctx In-place ALTER TABLE context
6906 @param altered_table MySQL table that is being altered
6907 @param old_table MySQL table as it is before the ALTER operation
6908 @param trx Data dictionary transaction
6909 @param table_name Table name in MySQL
6910 @retval true Failure
6911 @retval false Success
6912 */
6913 [[nodiscard]] inline bool commit_try_rebuild(Alter_inplace_info *ha_alter_info,
6914 ha_innobase_inplace_ctx *ctx,
6915 TABLE *altered_table,
6916 const TABLE *old_table, trx_t *trx,
6917 const char *table_name) {
6918 dict_table_t *rebuilt_table = ctx->new_table;
6919 dict_table_t *user_table = ctx->old_table;
6920
6921 DBUG_TRACE;
6922 assert(ctx->need_rebuild());
6923 assert(trx->dict_operation_lock_mode == RW_X_LATCH);
6924 assert(
6925 !(ha_alter_info->handler_flags & Alter_inplace_info::DROP_FOREIGN_KEY) ||
6926 ctx->num_to_drop_fk > 0);
6927
6928 for (dict_index_t *index = rebuilt_table->first_index(); index;
6929 index = index->next()) {
6930 assert(dict_index_get_online_status(index) == ONLINE_INDEX_COMPLETE);
6931 assert(index->is_committed());
6932 if (index->is_corrupted()) {
6933 my_error(ER_INDEX_CORRUPT, MYF(0), index->name());
6934 return true;
6935 }
6936 }
6937
6938 if (innobase_update_foreign_try(ctx, trx, table_name)) {
6939 return true;
6940 }
6941
6942 dberr_t error = DB_SUCCESS;
6943
6944 /* Clear the to_be_dropped flag in the data dictionary cache
6945 of user_table. */
6946 for (ulint i = 0; i < ctx->num_to_drop_index; i++) {
6947 dict_index_t *index = ctx->drop_index[i];
6948 assert(index->table == user_table);
6949 assert(index->is_committed());
6950 assert(index->to_be_dropped);
6951 index->to_be_dropped = 0;
6952 }
6953
6954 /* We copied the table. Any indexes that were requested to be
6955 dropped were not created in the copy of the table. Apply any
6956 last bit of the rebuild log and then rename the tables. */
6957
6958 if (ctx->online) {
6959 DEBUG_SYNC_C("row_log_table_apply2_before");
6960
6961 dict_vcol_templ_t *s_templ = nullptr;
6962
6963 if (ctx->new_table->n_v_cols > 0) {
6964 s_templ = ut::new_withkey<dict_vcol_templ_t>(UT_NEW_THIS_FILE_PSI_KEY);
6965 s_templ->vtempl = nullptr;
6966
6967 innobase_build_v_templ(altered_table, ctx->new_table, s_templ, nullptr,
6968 true, nullptr);
6969 ctx->new_table->vc_templ = s_templ;
6970 }
6971
6972 error = row_log_table_apply(
6973 ctx->thr, user_table, altered_table,
6974 static_cast<ha_innobase_inplace_ctx *>(ha_alter_info->handler_ctx)
6975 ->m_stage);
6976
6977 if (s_templ) {
6978 ut_ad(ctx->need_rebuild());
6979 dict_free_vc_templ(s_templ);
6980 ut::delete_(s_templ);
6981 ctx->new_table->vc_templ = nullptr;
6982 }
6983
6984 ulint err_key = thr_get_trx(ctx->thr)->error_key_num;
6985
6986 switch (error) {
6987 KEY *dup_key;
6988 case DB_SUCCESS:
6989 break;
6990 case DB_DUPLICATE_KEY:
6991 if (err_key == ULINT_UNDEFINED) {
6992 /* This should be the hidden index on
6993 FTS_DOC_ID. */
6994 dup_key = nullptr;
6995 } else {
6996 /* Check if there is generated cluster index column */
6997 if (ctx->num_to_add_index > ha_alter_info->key_count) {
6998 assert(err_key <= ha_alter_info->key_count);
6999 dup_key = &ha_alter_info->key_info_buffer[err_key - 1];
7000 } else {
7001 assert(err_key < ha_alter_info->key_count);
7002 dup_key = &ha_alter_info->key_info_buffer[err_key];
7003 }
7004 }
7005 print_keydup_error(altered_table, dup_key, MYF(0),
7006 old_table->s->table_name.str);
7007 return true;
7008 case DB_ONLINE_LOG_TOO_BIG:
7009 my_error(ER_INNODB_ONLINE_LOG_TOO_BIG, MYF(0),
7010 get_error_key_name(err_key, ha_alter_info, rebuilt_table));
7011 return true;
7012 case DB_INDEX_CORRUPT:
7013 my_error(ER_INDEX_CORRUPT, MYF(0),
7014 get_error_key_name(err_key, ha_alter_info, rebuilt_table));
7015 return true;
7016 default:
7017 my_error_innodb(error, table_name, user_table->flags);
7018 return true;
7019 }
7020 }
7021 DBUG_EXECUTE_IF("ib_rename_column_error",
7022 my_error_innodb(DB_OUT_OF_FILE_SPACE, table_name, 0);
7023 trx->error_state = DB_SUCCESS; trx->op_info = "";
7024 return true;);
7025 DBUG_EXECUTE_IF("ib_ddl_crash_before_rename", DBUG_SUICIDE(););
7026
7027 /* The new table must inherit the flag from the
7028 "parent" table. */
7029 if (dict_table_is_discarded(user_table)) {
7030 rebuilt_table->ibd_file_missing = true;
7031 rebuilt_table->flags2 |= DICT_TF2_DISCARDED;
7032 }
7033 /* We must be still holding a table handle. */
7034 assert(user_table->get_ref_count() >= 1);
7035
7036 DBUG_EXECUTE_IF("ib_ddl_crash_after_rename", DBUG_SUICIDE(););
7037 DBUG_EXECUTE_IF("ib_rebuild_cannot_rename", error = DB_ERROR;);
7038
7039 if (user_table->get_ref_count() > 1) {
7040 /* This should only occur when an innodb_memcached
7041 connection with innodb_api_enable_mdl=off was started
7042 before commit_inplace_alter_table() locked the data
7043 dictionary. We must roll back the ALTER TABLE, because
7044 we cannot drop a table while it is being used. */
7045
7046 /* Normally, n_ref_count must be 1, because purge
7047 cannot be executing on this very table as we are
7048 holding MDL lock. */
7049 my_error(ER_TABLE_REFERENCED, MYF(0));
7050 return true;
7051 }
7052
7053 switch (error) {
7054 case DB_SUCCESS:
7055 return false;
7056 case DB_TABLESPACE_EXISTS:
7057 ut_a(rebuilt_table->get_ref_count() == 1);
7058 my_error(ER_TABLESPACE_EXISTS, MYF(0), ctx->tmp_name);
7059 return true;
7060 case DB_DUPLICATE_KEY:
7061 ut_a(rebuilt_table->get_ref_count() == 1);
7062 my_error(ER_TABLE_EXISTS_ERROR, MYF(0), ctx->tmp_name);
7063 return true;
7064 default:
7065 my_error_innodb(error, table_name, user_table->flags);
7066 return true;
7067 }
7068 }
7069
7070 /** Apply the changes made during commit_try_rebuild(),
7071 to the data dictionary cache and the file system.
7072 @param ctx In-place ALTER TABLE context */
7073 inline void commit_cache_rebuild(ha_innobase_inplace_ctx *ctx) {
7074 dberr_t error;
7075
7076 DBUG_TRACE;
7077 DEBUG_SYNC_C("commit_cache_rebuild");
7078 assert(ctx->need_rebuild());
7079 assert(dict_table_is_discarded(ctx->old_table) ==
7080 dict_table_is_discarded(ctx->new_table));
7081
7082 const char *old_name =
7083 mem_heap_strdup(ctx->heap, ctx->old_table->name.m_name);
7084
7085 /* We already committed and redo logged the renames,
7086 so this must succeed. */
7087 error = dict_table_rename_in_cache(ctx->old_table, ctx->tmp_name, false);
7088 ut_a(error == DB_SUCCESS);
7089
7090 error = dict_table_rename_in_cache(ctx->new_table, old_name, false);
7091 ut_a(error == DB_SUCCESS);
7092 }
7093
7094 /** Set of column numbers */
7095 typedef std::set<ulint, std::less<ulint>, ut::allocator<ulint>> col_set;
7096
7097 /** Store the column number of the columns in a list belonging
7098 to indexes which are not being dropped.
7099 @param[in] ctx In-place ALTER TABLE context
7100 @param[in, out] drop_col_list list which will be set, containing columns
7101 which is part of index being dropped
7102 @param[in, out] drop_v_col_list list which will be set, containing
7103 virtual columns which is part of index
7104 being dropped */
7105 static void get_col_list_to_be_dropped(const ha_innobase_inplace_ctx *ctx,
7106 col_set &drop_col_list,
7107 col_set &drop_v_col_list) {
7108 for (ulint index_count = 0; index_count < ctx->num_to_drop_index;
7109 index_count++) {
7110 const dict_index_t *index = ctx->drop_index[index_count];
7111
7112 for (ulint col = 0; col < index->n_user_defined_cols; col++) {
7113 const dict_col_t *idx_col = index->get_col(col);
7114
7115 if (idx_col->is_virtual()) {
7116 const dict_v_col_t *v_col =
7117 reinterpret_cast<const dict_v_col_t *>(idx_col);
7118 drop_v_col_list.insert(v_col->v_pos);
7119
7120 } else {
7121 ulint col_no = dict_col_get_no(idx_col);
7122 drop_col_list.insert(col_no);
7123 }
7124 }
7125 }
7126 }
7127
7128 /** Commit the changes made during prepare_inplace_alter_table() and
7129 inplace_alter_table() inside the data dictionary tables, when not rebuilding
7130 the table.
7131 @param[in] ha_alter_info Data used during in-place alter
7132 @param[in] ctx In-place ALTER TABLE context
7133 @param[in] trx Data dictionary transaction
7134 @param[in] table_name Table name in MySQL
7135 @retval true Failure
7136 @retval false Success */
7137 [[nodiscard]] inline bool commit_try_norebuild(
7138 Alter_inplace_info *ha_alter_info, ha_innobase_inplace_ctx *ctx, trx_t *trx,
7139 const char *table_name) {
7140 DBUG_TRACE;
7141 assert(!ctx->need_rebuild());
7142 assert(trx->dict_operation_lock_mode == RW_X_LATCH);
7143 assert(
7144 !(ha_alter_info->handler_flags & Alter_inplace_info::DROP_FOREIGN_KEY) ||
7145 ctx->num_to_drop_fk > 0);
7146
7147 for (ulint i = 0; i < ctx->num_to_add_index; i++) {
7148 dict_index_t *index = ctx->add_index[i];
7149 assert(dict_index_get_online_status(index) == ONLINE_INDEX_COMPLETE);
7150 assert(!index->is_committed());
7151 if (index->is_corrupted()) {
7152 /* Report a duplicate key
7153 error for the index that was
7154 flagged corrupted, most likely
7155 because a duplicate value was
7156 inserted (directly or by
7157 rollback) after
7158 ha_innobase::inplace_alter_table()
7159 completed.
7160 TODO: report this as a corruption
7161 with a detailed reason once
7162 WL#6379 has been implemented. */
7163 my_error(ER_DUP_UNKNOWN_IN_INDEX, MYF(0), index->name());
7164 return true;
7165 }
7166 }
7167
7168 if (innobase_update_foreign_try(ctx, trx, table_name)) {
7169 return true;
7170 }
7171
7172 DBUG_EXECUTE_IF("ib_rename_column_error",
7173 my_error_innodb(DB_OUT_OF_FILE_SPACE, table_name, 0);
7174 trx->error_state = DB_SUCCESS; trx->op_info = "";
7175 return true;);
7176
7177 DBUG_EXECUTE_IF("ib_resize_column_error",
7178 my_error_innodb(DB_OUT_OF_FILE_SPACE, table_name, 0);
7179 trx->error_state = DB_SUCCESS; trx->op_info = "";
7180 return true;);
7181
7182 DBUG_EXECUTE_IF(
7183 "ib_rename_index_fail1", my_error_innodb(DB_DEADLOCK, table_name, 0);
7184 trx->error_state = DB_SUCCESS; trx->op_info = ""; return true;);
7185
7186 return false;
7187 }
7188
7189 /** Commit the changes to the data dictionary cache
7190 after a successful commit_try_norebuild() call.
7191 @param ctx In-place ALTER TABLE context
7192 @param trx Data dictionary transaction object
7193 (will be started and committed)
7194 @return whether all replacements were found for dropped indexes */
7195 [[nodiscard]] inline bool commit_cache_norebuild(ha_innobase_inplace_ctx *ctx,
7196 trx_t *trx) {
7197 DBUG_TRACE;
7198
7199 bool found = true;
7200
7201 assert(!ctx->need_rebuild());
7202
7203 col_set drop_list;
7204 col_set v_drop_list;
7205 col_set::const_iterator col_it;
7206
7207 /* Check if the column, part of an index to be dropped is part of any
7208 other index which is not being dropped. If not, then set the ord_part
7209 of the column to 0. Here the columns are collected first. */
7210 get_col_list_to_be_dropped(ctx, drop_list, v_drop_list);
7211
7212 bool adding_fts_index{false};
7213
7214 for (ulint i = 0; i < ctx->num_to_add_index; i++) {
7215 dict_index_t *index = ctx->add_index[i];
7216 assert(dict_index_get_online_status(index) == ONLINE_INDEX_COMPLETE);
7217 assert(!index->is_committed());
7218 index->set_committed(true);
7219 if (index->type & DICT_FTS) {
7220 adding_fts_index = true;
7221 }
7222 }
7223
7224 if (ctx->num_to_drop_index) {
7225 /* Drop indexes in data dictionary cache and write
7226 DDL log for them */
7227 for (ulint i = 0; i < ctx->num_to_drop_index; i++) {
7228 dict_index_t *index = ctx->drop_index[i];
7229 assert(index->is_committed());
7230 assert(index->table == ctx->new_table);
7231 assert(index->to_be_dropped);
7232
7233 /* Replace the indexes in foreign key
7234 constraints if needed. */
7235 if (!dict_foreign_replace_index(index->table, ctx->col_names, index)) {
7236 found = false;
7237 }
7238 }
7239
7240 for (ulint i = 0; i < ctx->num_to_drop_index; i++) {
7241 dict_index_t *index = ctx->drop_index[i];
7242 assert(index->is_committed());
7243 assert(index->table == ctx->new_table);
7244
7245 if (index->type & DICT_FTS) {
7246 assert(index->type == DICT_FTS || index->is_corrupted());
7247 assert(index->table->fts);
7248 ctx->fts_drop_aux_vec = new aux_name_vec_t;
7249 fts_drop_index(index->table, index, trx, ctx->fts_drop_aux_vec,
7250 adding_fts_index);
7251 }
7252
7253 /* It is a single table tablespace and the .ibd file is
7254 missing if root is FIL_NULL, do nothing. */
7255 if (index->page != FIL_NULL) {
7256 dict_sys_mutex_exit();
7257 ut_d(dberr_t err =) log_ddl->write_free_tree_log(trx, index, true);
7258 ut_ad(err == DB_SUCCESS);
7259 dict_sys_mutex_enter();
7260 }
7261
7262 btr_drop_ahi_for_index(index);
7263 dict_index_remove_from_cache(index->table, index);
7264 }
7265 }
7266
7267 /* Update the ord_part after index dropped, to get accurate values */
7268 for (col_it = drop_list.begin(); col_it != drop_list.end(); ++col_it) {
7269 if (!check_col_exists_in_indexes(ctx->new_table, *col_it, false)) {
7270 ctx->new_table->cols[*col_it].ord_part = 0;
7271 }
7272 }
7273
7274 for (col_it = v_drop_list.begin(); col_it != v_drop_list.end(); ++col_it) {
7275 if (!check_col_exists_in_indexes(ctx->new_table, *col_it, true)) {
7276 ctx->new_table->v_cols[*col_it].m_col.ord_part = 0;
7277 }
7278 }
7279
7280 ctx->new_table->fts_doc_id_index =
7281 ctx->new_table->fts
7282 ? dict_table_get_index_on_name(ctx->new_table, FTS_DOC_ID_INDEX_NAME)
7283 : nullptr;
7284 assert((ctx->new_table->fts == nullptr) ==
7285 (ctx->new_table->fts_doc_id_index == nullptr));
7286
7287 return found;
7288 }
7289
7290 /** Adjust the persistent statistics after non-rebuilding ALTER TABLE.
7291 Remove statistics for dropped indexes, add statistics for created indexes
7292 and rename statistics for renamed indexes.
7293 @param ha_alter_info Data used during in-place alter
7294 @param ctx In-place ALTER TABLE context
7295 @param table_name Table name in MySQL
7296 @param thd MySQL connection
7297 */
7298 static void alter_stats_norebuild(Alter_inplace_info *ha_alter_info,
7299 ha_innobase_inplace_ctx *ctx,
7300 const char *table_name, THD *thd) {
7301 ulint i;
7302
7303 DBUG_TRACE;
7304 assert(!ctx->need_rebuild());
7305
7306 if (!dict_stats_is_persistent_enabled(ctx->new_table)) {
7307 return;
7308 }
7309
7310 /* Delete corresponding rows from the stats table. We do this
7311 in a separate transaction from trx, because lock waits are not
7312 allowed in a data dictionary transaction. (Lock waits are possible
7313 on the statistics table, because it is directly accessible by users,
7314 not covered by the dict_operation_lock.)
7315
7316 Because the data dictionary changes were already committed, orphaned
7317 rows may be left in the statistics table if the system crashes.
7318
7319 FIXME: each change to the statistics tables is being committed in a
7320 separate transaction, meaning that the operation is not atomic
7321
7322 FIXME: This will not drop the (unused) statistics for
7323 FTS_DOC_ID_INDEX if it was a hidden index, dropped together
7324 with the last renamining FULLTEXT index. */
7325 for (i = 0; i < ha_alter_info->index_drop_count; i++) {
7326 const KEY *key = ha_alter_info->index_drop_buffer[i];
7327
7328 if (key->flags & HA_FULLTEXT) {
7329 /* There are no index cardinality
7330 statistics for FULLTEXT indexes. */
7331 continue;
7332 }
7333
7334 char errstr[ERROR_STR_LENGTH];
7335
7336 if (dict_stats_drop_index(ctx->new_table->name.m_name, key->name, errstr,
7337 sizeof errstr) != DB_SUCCESS) {
7338 push_warning(thd, Sql_condition::SL_WARNING, ER_LOCK_WAIT_TIMEOUT,
7339 errstr);
7340 }
7341 }
7342
7343 for (i = 0; i < ha_alter_info->index_rename_count; i++) {
7344 KEY_PAIR *pair = &ha_alter_info->index_rename_buffer[i];
7345 dberr_t err;
7346
7347 err = dict_stats_rename_index(ctx->new_table, pair->old_key->name,
7348 pair->new_key->name);
7349
7350 if (err != DB_SUCCESS) {
7351 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_ERROR_ON_RENAME,
7352 "Error renaming an index of table '%s'"
7353 " from '%s' to '%s' in InnoDB persistent"
7354 " statistics storage: %s",
7355 table_name, pair->old_key->name, pair->new_key->name,
7356 ut_strerr(err));
7357 }
7358 }
7359
7360 for (i = 0; i < ctx->num_to_add_index; i++) {
7361 dict_index_t *index = ctx->add_index[i];
7362 assert(index->table == ctx->new_table);
7363
7364 if (!(index->type & DICT_FTS)) {
7365 dict_stats_init(ctx->new_table);
7366 dict_stats_update_for_index(index);
7367 }
7368 }
7369 }
7370
7371 /** Adjust the persistent statistics after rebuilding ALTER TABLE.
7372 Remove statistics for dropped indexes, add statistics for created indexes
7373 and rename statistics for renamed indexes.
7374 @param table InnoDB table that was rebuilt by ALTER TABLE
7375 @param table_name Table name in MySQL
7376 @param thd MySQL connection
7377 */
7378 void alter_stats_rebuild(dict_table_t *table, const char *table_name,
7379 THD *thd) {
7380 DBUG_TRACE;
7381 DBUG_EXECUTE_IF("ib_ddl_crash_before_rename", DBUG_SUICIDE(););
7382
7383 if (dict_table_is_discarded(table) ||
7384 !dict_stats_is_persistent_enabled(table)) {
7385 return;
7386 }
7387
7388 #ifdef UNIV_DEBUG
7389 bool ibd_file_missing_orig = false;
7390 #endif /* UNIV_DEBUG */
7391
7392 DBUG_EXECUTE_IF("ib_rename_index_fail2",
7393 ibd_file_missing_orig = table->ibd_file_missing;
7394 table->ibd_file_missing = true;);
7395
7396 dberr_t ret = dict_stats_update(table, DICT_STATS_RECALC_PERSISTENT);
7397
7398 DBUG_EXECUTE_IF("ib_rename_index_fail2",
7399 table->ibd_file_missing = ibd_file_missing_orig;);
7400
7401 if (ret != DB_SUCCESS) {
7402 push_warning_printf(thd, Sql_condition::SL_WARNING, ER_ALTER_INFO,
7403 "Error updating stats for table '%s'"
7404 " after table rebuild: %s",
7405 table_name, ut_strerr(ret));
7406 }
7407 }
7408
7409 /** Implementation of commit_inplace_alter_table()
7410 @tparam Table dd::Table or dd::Partition
7411 @param[in] altered_table TABLE object for new version of table.
7412 @param[in,out] ha_alter_info Structure describing changes to be done
7413 by ALTER TABLE and holding data used
7414 during in-place alter.
7415 @param[in] commit True to commit or false to rollback.
7416 @param[in,out] new_dd_tab Table object for the new version of the
7417 table. Can be adjusted by this call.
7418 Changes to the table definition
7419 will be persisted in the data-dictionary
7420 at statement version of it.
7421 @retval true Failure
7422 @retval false Success */
7423 template <typename Table>
7424 bool ha_innobase::commit_inplace_alter_table_impl(
7425 TABLE *altered_table, Alter_inplace_info *ha_alter_info, bool commit,
7426 Table *new_dd_tab) {
7427 dberr_t error;
7428 ha_innobase_inplace_ctx *ctx0;
7429 struct mtr_buf_copy_t logs;
7430
7431 ctx0 = static_cast<ha_innobase_inplace_ctx *>(ha_alter_info->handler_ctx);
7432
7433 #ifdef UNIV_DEBUG
7434 uint crash_inject_count = 1;
7435 uint crash_fail_inject_count = 1;
7436 uint failure_inject_count = 1;
7437 #endif /* UNIV_DEBUG */
7438
7439 DBUG_TRACE;
7440 assert(!srv_read_only_mode);
7441 assert(!ctx0 || ctx0->prebuilt == m_prebuilt);
7442 assert(!ctx0 || ctx0->old_table == m_prebuilt->table);
7443
7444 DEBUG_SYNC_C("innodb_commit_inplace_alter_table_enter");
7445
7446 DEBUG_SYNC_C("innodb_commit_inplace_alter_table_wait");
7447
7448 if (ctx0 != nullptr && ctx0->m_stage != nullptr) {
7449 ctx0->m_stage->begin_phase_end();
7450 }
7451
7452 if (!commit) {
7453 /* A rollback is being requested. So far we may at
7454 most have created some indexes. If any indexes were to
7455 be dropped, they would actually be dropped in this
7456 method if commit=true. */
7457 const bool ret =
7458 rollback_inplace_alter_table(ha_alter_info, table, m_prebuilt);
7459 return ret;
7460 }
7461
7462 if (!(ha_alter_info->handler_flags & ~INNOBASE_INPLACE_IGNORE) ||
7463 is_instant(ha_alter_info)) {
7464 assert(!ctx0);
7465 MONITOR_ATOMIC_DEC(MONITOR_PENDING_ALTER_TABLE);
7466 ha_alter_info->group_commit_ctx = nullptr;
7467 return false;
7468 }
7469
7470 assert(ctx0);
7471
7472 inplace_alter_handler_ctx **ctx_array;
7473 inplace_alter_handler_ctx *ctx_single[2];
7474
7475 if (ha_alter_info->group_commit_ctx) {
7476 ctx_array = ha_alter_info->group_commit_ctx;
7477 } else {
7478 ctx_single[0] = ctx0;
7479 ctx_single[1] = nullptr;
7480 ctx_array = ctx_single;
7481 }
7482
7483 assert(ctx0 == ctx_array[0]);
7484 ut_ad(m_prebuilt->table == ctx0->old_table);
7485 ha_alter_info->group_commit_ctx = nullptr;
7486
7487 trx_start_if_not_started_xa(m_prebuilt->trx, true, UT_LOCATION_HERE);
7488
7489 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx; pctx++) {
7490 ha_innobase_inplace_ctx *ctx =
7491 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7492 assert(ctx->prebuilt->trx == m_prebuilt->trx);
7493
7494 /* Exclusively lock the table, to ensure that no other
7495 transaction is holding locks on the table while we
7496 change the table definition. The MySQL meta-data lock
7497 should normally guarantee that no conflicting locks
7498 exist. However, FOREIGN KEY constraints checks and any
7499 transactions collected during crash recovery could be
7500 holding InnoDB locks only, not MySQL locks. */
7501
7502 error = ddl::lock_table(m_prebuilt->trx, ctx->old_table, LOCK_X);
7503
7504 if (error != DB_SUCCESS) {
7505 my_error_innodb(error, table_share->table_name.str, 0);
7506 return true;
7507 }
7508 }
7509
7510 DEBUG_SYNC(m_user_thd, "innodb_alter_commit_after_lock_table");
7511
7512 const bool new_clustered = ctx0->need_rebuild();
7513 trx_t *trx = ctx0->trx;
7514 bool fail = false;
7515
7516 if (new_clustered) {
7517 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx; pctx++) {
7518 ha_innobase_inplace_ctx *ctx =
7519 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7520 assert(ctx->need_rebuild());
7521
7522 if (ctx->old_table->fts) {
7523 ut_ad(!ctx->old_table->fts->add_wq);
7524 fts_optimize_remove_table(ctx->old_table);
7525 }
7526
7527 if (ctx->new_table->fts) {
7528 ut_ad(!ctx->new_table->fts->add_wq);
7529 fts_optimize_remove_table(ctx->new_table);
7530 }
7531 }
7532 }
7533
7534 if (trx == nullptr) {
7535 trx = m_prebuilt->trx;
7536 ctx0->trx = trx;
7537 assert(!new_clustered);
7538 }
7539
7540 /* Generate the temporary name for old table, and acquire mdl
7541 lock on it. */
7542 THD *thd = current_thd;
7543 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx; pctx++) {
7544 ha_innobase_inplace_ctx *ctx =
7545 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7546
7547 if (ctx->need_rebuild()) {
7548 ctx->tmp_name = dict_mem_create_temporary_tablename(
7549 ctx->heap, ctx->new_table->name.m_name, ctx->new_table->id);
7550
7551 std::string db_str;
7552 std::string tbl_str;
7553 dict_name::get_table(ctx->tmp_name, db_str, tbl_str);
7554
7555 /* Acquire mdl lock on the temporary table name. */
7556 MDL_ticket *mdl_ticket = nullptr;
7557 if (dd::acquire_exclusive_table_mdl(thd, db_str.c_str(), tbl_str.c_str(),
7558 false, &mdl_ticket)) {
7559 return true;
7560 }
7561 }
7562 }
7563
7564 /* Latch the InnoDB data dictionary exclusively so that no deadlocks
7565 or lock waits can happen in it during the data dictionary operation. */
7566 row_mysql_lock_data_dictionary(trx, UT_LOCATION_HERE);
7567
7568 /* Prevent the background statistics collection from accessing
7569 the tables. */
7570 for (;;) {
7571 bool retry = false;
7572
7573 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx; pctx++) {
7574 ha_innobase_inplace_ctx *ctx =
7575 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7576
7577 assert(new_clustered == ctx->need_rebuild());
7578
7579 if (new_clustered && !dict_stats_stop_bg(ctx->old_table)) {
7580 retry = true;
7581 }
7582
7583 if (!dict_stats_stop_bg(ctx->new_table)) {
7584 retry = true;
7585 }
7586 }
7587
7588 if (!retry) {
7589 break;
7590 }
7591
7592 DICT_STATS_BG_YIELD(trx, UT_LOCATION_HERE);
7593 }
7594
7595 /* Apply the changes to the data dictionary tables, for all partitions.*/
7596
7597 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx && !fail; pctx++) {
7598 ha_innobase_inplace_ctx *ctx =
7599 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7600
7601 assert(new_clustered == ctx->need_rebuild());
7602
7603 fail = commit_get_autoinc(ha_alter_info, ctx, altered_table, table);
7604 if (fail) {
7605 my_error(ER_TABLESPACE_DISCARDED, MYF(0), table->s->table_name.str);
7606 goto rollback_trx;
7607 }
7608
7609 if (ctx->need_rebuild()) {
7610 fail = commit_try_rebuild(ha_alter_info, ctx, altered_table, table, trx,
7611 table_share->table_name.str);
7612
7613 if (!fail) {
7614 log_ddl->write_drop_log(trx, ctx->old_table->id);
7615 }
7616 } else {
7617 fail = commit_try_norebuild(ha_alter_info, ctx, trx,
7618 table_share->table_name.str);
7619 }
7620 DBUG_INJECT_CRASH("ib_commit_inplace_crash", crash_inject_count++);
7621 #ifdef UNIV_DEBUG
7622 {
7623 /* Generate a dynamic dbug text. */
7624 char buf[32];
7625
7626 snprintf(buf, sizeof buf, "ib_commit_inplace_fail_%u",
7627 failure_inject_count++);
7628
7629 DBUG_EXECUTE_IF(buf,
7630 my_error(ER_INTERNAL_ERROR, MYF(0), "Injected error!");
7631 fail = true;);
7632 }
7633 #endif
7634 }
7635
7636 rollback_trx:
7637
7638 /* Commit or roll back the changes to the data dictionary. */
7639
7640 if (!fail && new_clustered) {
7641 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx; pctx++) {
7642 ha_innobase_inplace_ctx *ctx =
7643 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7644
7645 assert(ctx->need_rebuild());
7646
7647 /* Check for any possible problems for any
7648 file operations that will be performed in
7649 commit_cache_rebuild(). */
7650 error =
7651 fil_rename_precheck(ctx->old_table, ctx->new_table, ctx->tmp_name);
7652 if (error != DB_SUCCESS) {
7653 /* Out of memory or a problem will occur
7654 when renaming files. */
7655 fail = true;
7656 my_error_innodb(error, ctx->old_table->name.m_name,
7657 ctx->old_table->flags);
7658 }
7659 DBUG_INJECT_CRASH("ib_commit_inplace_crash", crash_inject_count++);
7660 }
7661
7662 /* Test what happens on crash here.
7663 The data dictionary transaction should be
7664 rolled back, restoring the old table. */
7665 DBUG_EXECUTE_IF("innodb_alter_commit_crash_before_commit",
7666 log_buffer_flush_to_disk();
7667 DBUG_SUICIDE(););
7668 ut_ad(!trx->fts_trx);
7669
7670 DBUG_EXECUTE_IF("innodb_alter_commit_crash_after_commit",
7671 log_make_latest_checkpoint();
7672 log_buffer_flush_to_disk(); DBUG_SUICIDE(););
7673 }
7674
7675 /* Update the in-memory structures, close some handles, release
7676 temporary files, and (unless we rolled back) update persistent
7677 statistics. */
7678 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx; pctx++) {
7679 ha_innobase_inplace_ctx *ctx =
7680 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7681
7682 assert(ctx->need_rebuild() == new_clustered);
7683
7684 if (new_clustered) {
7685 innobase_online_rebuild_log_free(ctx->old_table);
7686 }
7687
7688 if (fail) {
7689 if (new_clustered) {
7690 dict_table_close(ctx->new_table, true, false);
7691 ctx->new_table = nullptr;
7692 } else {
7693 /* We failed, but did not rebuild the table.
7694 Roll back any ADD INDEX, or get rid of garbage
7695 ADD INDEX that was left over from a previous
7696 ALTER TABLE statement. */
7697 innobase_rollback_sec_index(ctx->new_table, table, true, trx);
7698 }
7699 DBUG_INJECT_CRASH("ib_commit_inplace_crash_fail",
7700 crash_fail_inject_count++);
7701
7702 continue;
7703 }
7704
7705 innobase_copy_frm_flags_from_table_share(ctx->new_table, altered_table->s);
7706
7707 if (new_clustered) {
7708 /* We will reload and refresh the
7709 in-memory foreign key constraint
7710 metadata. This is a rename operation
7711 in preparing for dropping the old
7712 table. Set the table to_be_dropped bit
7713 here, so to make sure DML foreign key
7714 constraint check does not use the
7715 stale dict_foreign_t. This is done
7716 because WL#6049 (FK MDL) has not been
7717 implemented yet. */
7718 ctx->old_table->to_be_dropped = true;
7719
7720 DBUG_PRINT("to_be_dropped", ("table: %s", ctx->old_table->name.m_name));
7721
7722 if ((ha_alter_info->handler_flags &
7723 Alter_inplace_info::ALTER_COLUMN_NAME)) {
7724 innobase_rename_col_discard_foreign(ha_alter_info, table,
7725 ctx->old_table);
7726 }
7727
7728 /* Rename the tablespace files. */
7729 commit_cache_rebuild(ctx);
7730
7731 /* Discard the added foreign keys, because we will
7732 load them from the data dictionary. */
7733 for (ulint i = 0; i < ctx->num_to_add_fk; i++) {
7734 dict_foreign_t *fk = ctx->add_fk[i];
7735 dict_foreign_free(fk);
7736 }
7737
7738 /* There is no FK on partition table */
7739 if (m_share) {
7740 ctx->new_table->discard_after_ddl = true;
7741 }
7742 } else {
7743 error =
7744 innobase_update_foreign_cache(ctx, m_user_thd, &new_dd_tab->table());
7745
7746 if (error != DB_SUCCESS) {
7747 /* The data dictionary cache
7748 should be corrupted now. The
7749 best solution should be to
7750 kill and restart the server,
7751 but the *.frm file has not
7752 been replaced yet. */
7753 push_warning_printf(m_user_thd, Sql_condition::SL_WARNING,
7754 ER_ALTER_INFO,
7755 "InnoDB: Could not add foreign"
7756 " key constraints.");
7757 } else {
7758 if (!commit_cache_norebuild(ctx, trx)) {
7759 ut_a(!m_prebuilt->trx->check_foreigns);
7760 }
7761
7762 innobase_rename_or_enlarge_columns_cache(ha_alter_info, table,
7763 ctx->new_table);
7764
7765 rename_indexes_in_cache(ctx, ha_alter_info);
7766 }
7767 }
7768
7769 dict_mem_table_free_foreign_vcol_set(ctx->new_table);
7770 dict_mem_table_fill_foreign_vcol_set(ctx->new_table);
7771
7772 DBUG_INJECT_CRASH("ib_commit_inplace_crash", crash_inject_count++);
7773 }
7774
7775 /* Invalidate the index translation table. In partitioned
7776 tables, there is no share. */
7777 if (m_share) {
7778 m_share->idx_trans_tbl.index_count = 0;
7779 }
7780
7781 /* Tell the InnoDB server that there might be work for
7782 utility threads: */
7783
7784 srv_active_wake_master_thread();
7785
7786 if (fail) {
7787 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx; pctx++) {
7788 ha_innobase_inplace_ctx *ctx =
7789 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7790 assert(ctx->need_rebuild() == new_clustered);
7791
7792 ut_d(dict_table_check_for_dup_indexes(ctx->old_table, CHECK_ABORTED_OK));
7793 ut_a(fts_check_cached_index(ctx->old_table));
7794 DBUG_INJECT_CRASH("ib_commit_inplace_crash_fail",
7795 crash_fail_inject_count++);
7796 }
7797
7798 row_mysql_unlock_data_dictionary(trx);
7799 return true;
7800 }
7801
7802 if (ha_alter_info->virtual_column_drop_count ||
7803 ha_alter_info->virtual_column_add_count) {
7804 if (ctx0->old_table->get_ref_count() > 1) {
7805 row_mysql_unlock_data_dictionary(trx);
7806 my_error(ER_TABLE_REFERENCED, MYF(0));
7807 return true;
7808 }
7809
7810 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx; pctx++) {
7811 ha_innobase_inplace_ctx *ctx =
7812 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7813
7814 /* Drop outdated table stats. */
7815 innobase_discard_table(m_user_thd, ctx->old_table);
7816 }
7817
7818 row_mysql_unlock_data_dictionary(trx);
7819 MONITOR_ATOMIC_DEC(MONITOR_PENDING_ALTER_TABLE);
7820 return false;
7821 }
7822
7823 DBUG_EXECUTE_IF("ib_ddl_crash_after_user_trx_commit", DBUG_SUICIDE(););
7824
7825 uint64_t autoinc = 0;
7826 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx; pctx++) {
7827 ha_innobase_inplace_ctx *ctx =
7828 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7829 assert(ctx->need_rebuild() == new_clustered);
7830
7831 if (altered_table->found_next_number_field) {
7832 if (ctx->max_autoinc > autoinc) {
7833 autoinc = ctx->max_autoinc;
7834 }
7835
7836 dict_table_t *t = ctx->new_table;
7837 Field *field = altered_table->found_next_number_field;
7838
7839 dict_table_autoinc_lock(t);
7840 dict_table_autoinc_initialize(t, ctx->max_autoinc);
7841 t->autoinc_persisted = ctx->max_autoinc - 1;
7842 dict_table_autoinc_set_col_pos(t, field->field_index());
7843 dict_table_autoinc_unlock(t);
7844 }
7845
7846 bool add_fts = false;
7847
7848 /* Publish the created fulltext index, if any.
7849 Note that a fulltext index can be created without
7850 creating the clustered index, if there already exists
7851 a suitable FTS_DOC_ID column. If not, one will be
7852 created, implying new_clustered */
7853 for (ulint i = 0; i < ctx->num_to_add_index; i++) {
7854 dict_index_t *index = ctx->add_index[i];
7855
7856 if (index->type & DICT_FTS) {
7857 assert(index->type == DICT_FTS);
7858 fts_add_index(index, ctx->new_table);
7859 add_fts = true;
7860 }
7861 }
7862
7863 ut_d(dict_table_check_for_dup_indexes(ctx->new_table, CHECK_ALL_COMPLETE));
7864
7865 if (add_fts && !ctx->new_table->discard_after_ddl) {
7866 fts_optimize_add_table(ctx->new_table);
7867 }
7868
7869 ut_d(dict_table_check_for_dup_indexes(ctx->new_table, CHECK_ABORTED_OK));
7870 ut_a(fts_check_cached_index(ctx->new_table));
7871
7872 if (new_clustered) {
7873 /* Since the table has been rebuilt, we remove
7874 all persistent statistics corresponding to the
7875 old copy of the table (which was renamed to
7876 ctx->tmp_name). */
7877
7878 char errstr[ERROR_STR_LENGTH];
7879
7880 assert(0 == strcmp(ctx->old_table->name.m_name, ctx->tmp_name));
7881
7882 DBUG_EXECUTE_IF("ib_rename_index_fail3",
7883 DBUG_SET("+d,innodb_report_deadlock"););
7884
7885 if (dict_stats_drop_table(ctx->new_table->name.m_name, errstr,
7886 sizeof(errstr)) != DB_SUCCESS) {
7887 push_warning_printf(m_user_thd, Sql_condition::SL_WARNING,
7888 ER_ALTER_INFO,
7889 "Deleting persistent statistics"
7890 " for rebuilt table '%s' in"
7891 " InnoDB failed: %s",
7892 table->s->table_name.str, errstr);
7893 }
7894
7895 DBUG_EXECUTE_IF("ib_rename_index_fail3",
7896 DBUG_SET("-d,innodb_report_deadlock"););
7897
7898 DBUG_EXECUTE_IF("ib_ddl_crash_before_commit", DBUG_SUICIDE(););
7899
7900 ut_ad(m_prebuilt != ctx->prebuilt || ctx == ctx0);
7901 bool update_own_prebuilt = (m_prebuilt == ctx->prebuilt);
7902 trx_t *const user_trx = m_prebuilt->trx;
7903 if (dict_table_is_partition(ctx->new_table)) {
7904 /* Set blob_heap to NULL for partitioned tables to avoid
7905 row_prebuilt_free() from freeing them. We do this to avoid double free
7906 of blob_heap since all partitions point to the same blob_heap in
7907 prebuilt. Blob heaps of all the partitions will be freed later in the
7908 ha_innopart::clear_blob_heaps() */
7909 ctx->prebuilt->blob_heap = nullptr;
7910 }
7911
7912 row_prebuilt_free(ctx->prebuilt, true);
7913
7914 /* Drop the copy of the old table, which was
7915 renamed to ctx->tmp_name at the atomic DDL
7916 transaction commit. If the system crashes
7917 before this is completed, some orphan tables
7918 with ctx->tmp_name may be recovered. */
7919 ddl::drop_table(trx, ctx->old_table);
7920
7921 /* Rebuild the prebuilt object. */
7922 ctx->prebuilt =
7923 row_create_prebuilt(ctx->new_table, altered_table->s->reclength);
7924 if (update_own_prebuilt) {
7925 m_prebuilt = ctx->prebuilt;
7926 }
7927 user_trx->will_lock++;
7928 m_prebuilt->trx = user_trx;
7929 }
7930 DBUG_INJECT_CRASH("ib_commit_inplace_crash", crash_inject_count++);
7931 }
7932
7933 row_mysql_unlock_data_dictionary(trx);
7934
7935 if (altered_table->found_next_number_field != nullptr) {
7936 dd_set_autoinc(new_dd_tab->se_private_data(), autoinc);
7937 }
7938
7939 DBUG_EXECUTE_IF("ib_ddl_crash_before_update_stats", DBUG_SUICIDE(););
7940
7941 /* TODO: The following code could be executed
7942 while allowing concurrent access to the table
7943 (MDL downgrade). */
7944
7945 if (new_clustered) {
7946 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx; pctx++) {
7947 ha_innobase_inplace_ctx *ctx =
7948 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7949 assert(ctx->need_rebuild());
7950
7951 alter_stats_rebuild(ctx->new_table, table->s->table_name.str, m_user_thd);
7952 DBUG_INJECT_CRASH("ib_commit_inplace_crash", crash_inject_count++);
7953 }
7954 } else {
7955 for (inplace_alter_handler_ctx **pctx = ctx_array; *pctx; pctx++) {
7956 ha_innobase_inplace_ctx *ctx =
7957 static_cast<ha_innobase_inplace_ctx *>(*pctx);
7958 assert(!ctx->need_rebuild());
7959
7960 alter_stats_norebuild(ha_alter_info, ctx, table->s->table_name.str,
7961 m_user_thd);
7962 DBUG_INJECT_CRASH("ib_commit_inplace_crash", crash_inject_count++);
7963
7964 if (ctx->fts_drop_aux_vec != nullptr &&
7965 ctx->fts_drop_aux_vec->aux_name.size() > 0) {
7966 fts_drop_dd_tables(ctx->fts_drop_aux_vec,
7967 dict_table_is_file_per_table(ctx->old_table));
7968 }
7969 }
7970 }
7971
7972 /* We don't support compression for the system tablespace nor
7973 the temporary tablespace. Only because they are shared tablespaces.
7974 There is no other technical reason. */
7975
7976 innobase_parse_hint_from_comment(m_user_thd, m_prebuilt->table,
7977 altered_table->s);
7978
7979 /* TODO: Also perform DROP TABLE and DROP INDEX after
7980 the MDL downgrade. */
7981
7982 #ifdef UNIV_DEBUG
7983 dict_index_t *clust_index = ctx0->prebuilt->table->first_index();
7984 assert(!clust_index->online_log);
7985 assert(dict_index_get_online_status(clust_index) == ONLINE_INDEX_COMPLETE);
7986
7987 for (dict_index_t *index = clust_index; index; index = index->next()) {
7988 assert(!index->to_be_dropped);
7989 }
7990 #endif /* UNIV_DEBUG */
7991 MONITOR_ATOMIC_DEC(MONITOR_PENDING_ALTER_TABLE);
7992 return false;
7993 }
7994
7995 /** Helper class for in-place alter partitioned table, see handler.h */
7996 class ha_innopart_inplace_ctx : public inplace_alter_handler_ctx {
7997 /* Only used locally in this file, so have everything public for
7998 convenience. */
7999 public:
8000 /** Total number of partitions. */
8001 uint m_tot_parts;
8002 /** Array of inplace contexts for all partitions. */
8003 inplace_alter_handler_ctx **ctx_array;
8004 /** Array of prebuilt for all partitions. */
8005 row_prebuilt_t **prebuilt_array;
8006 /** Array of old table information needed for writing back to DD */
8007 alter_table_old_info_t *m_old_info;
8008
8009 ha_innopart_inplace_ctx(uint tot_parts)
8010 : inplace_alter_handler_ctx(),
8011 m_tot_parts(tot_parts),
8012 ctx_array(),
8013 prebuilt_array(),
8014 m_old_info() {}
8015
8016 ~ha_innopart_inplace_ctx() override {
8017 if (ctx_array) {
8018 for (uint i = 0; i < m_tot_parts; i++) {
8019 destroy(ctx_array[i]);
8020 }
8021 ut::free(ctx_array);
8022 }
8023
8024 if (m_old_info != nullptr) {
8025 ut::free(m_old_info);
8026 }
8027
8028 if (prebuilt_array) {
8029 /* First entry is the original prebuilt! */
8030 for (uint i = 1; i < m_tot_parts; i++) {
8031 /* Don't close the tables. */
8032 prebuilt_array[i]->table = nullptr;
8033 row_prebuilt_free(prebuilt_array[i], false);
8034 }
8035 ut::free(prebuilt_array);
8036 }
8037 }
8038 };
8039
8040 /** Helper class for encapsulating new/altered partitions during
8041 ADD(HASH/KEY)/COALESCE/REORGANIZE PARTITION. Here as many partition slots
8042 as in new table would be created, it's OK for ADD/COALESCE PARTITION,
8043 however more partition slots would probably be created for REORGANIZE PARTITION.
8044 Considering that it's easy to get table in this way, it's still OK. */
8045 class Altered_partitions {
8046 public:
8047 /** Constructor
8048 @param[in] parts total partitions */
8049 Altered_partitions(uint parts)
8050 : m_new_table_parts(),
8051 m_ins_nodes(),
8052 m_sql_stat_start(),
8053 m_trx_ids(),
8054 m_num_new_parts(parts) {}
8055
8056 /** Destructor */
8057 ~Altered_partitions();
8058
8059 /** Initialize the object.
8060 @return false on success
8061 @retval true on failure */
8062 bool initialize();
8063
8064 /** Open and set currently used partition.
8065 @param[in] new_part_id Partition id to set.
8066 @param[in,out] part Internal table object to use. */
8067 void set_part(ulint new_part_id, dict_table_t *part) {
8068 ut_ad(m_new_table_parts[new_part_id] == nullptr);
8069 m_new_table_parts[new_part_id] = part;
8070 part->skip_alter_undo = true;
8071 m_sql_stat_start.set(new_part_id);
8072 }
8073
8074 /** Get lower level internal table object for partition.
8075 @param[in] part_id Partition id.
8076 @return Lower level internal table object for the partition id. */
8077 dict_table_t *part(uint part_id) {
8078 ut_ad(part_id < m_num_new_parts);
8079 return (m_new_table_parts[part_id]);
8080 }
8081
8082 /** To write a row, set up prebuilt for using a specified partition.
8083 @param[in,out] prebuilt Prebuilt to update.
8084 @param[in] new_part_id Partition to use. */
8085 void prepare_write(row_prebuilt_t *prebuilt, uint new_part_id) const {
8086 ut_ad(m_new_table_parts[new_part_id]);
8087 prebuilt->table = m_new_table_parts[new_part_id];
8088 prebuilt->ins_node = m_ins_nodes[new_part_id];
8089 prebuilt->trx_id = m_trx_ids[new_part_id];
8090 prebuilt->sql_stat_start = m_sql_stat_start.test(new_part_id);
8091 }
8092
8093 /** After a write, update cached values for a partition from prebuilt.
8094 @param[in,out] prebuilt Prebuilt to copy from.
8095 @param[in] new_part_id Partition id to copy. */
8096 void finish_write(row_prebuilt_t *prebuilt, uint new_part_id) {
8097 ut_ad(m_new_table_parts[new_part_id] == prebuilt->table);
8098 m_ins_nodes[new_part_id] = prebuilt->ins_node;
8099 m_trx_ids[new_part_id] = prebuilt->trx_id;
8100 if (!prebuilt->sql_stat_start) {
8101 m_sql_stat_start.reset(new_part_id);
8102 }
8103 }
8104
8105 private:
8106 /** New partitions created during ADD(HASH/KEY)/COALESCE/REORGANIZE
8107 PARTITION. */
8108 dict_table_t **m_new_table_parts;
8109
8110 /** Insert nodes per partition. */
8111 ins_node_t **m_ins_nodes;
8112
8113 /** bytes for sql_stat_start bitset */
8114 byte *m_bitset;
8115
8116 /** sql_stat_start per partition */
8117 Sql_stat_start_parts m_sql_stat_start;
8118
8119 /** Trx id per partition. */
8120 trx_id_t *m_trx_ids;
8121
8122 /** Number of new partitions. */
8123 size_t m_num_new_parts;
8124 };
8125
8126 /** Destructor */
8127 Altered_partitions::~Altered_partitions() {
8128 if (m_new_table_parts != nullptr) {
8129 for (ulint i = 0; i < m_num_new_parts; i++) {
8130 if (m_new_table_parts[i] != nullptr) {
8131 m_new_table_parts[i]->skip_alter_undo = false;
8132 }
8133 }
8134
8135 ut::free(m_new_table_parts);
8136 }
8137
8138 if (m_ins_nodes != nullptr) {
8139 for (ulint i = 0; i < m_num_new_parts; i++) {
8140 if (m_ins_nodes[i] != nullptr) {
8141 ins_node_t *ins = m_ins_nodes[i];
8142 ut_ad(ins->select == nullptr);
8143 que_graph_free_recursive(ins->select);
8144 ins->select = nullptr;
8145 if (ins->entry_sys_heap != nullptr) {
8146 mem_heap_free(ins->entry_sys_heap);
8147 ins->entry_sys_heap = nullptr;
8148 }
8149 }
8150 }
8151
8152 ut::free(m_ins_nodes);
8153 }
8154
8155 ut::free(m_bitset);
8156 ut::free(m_trx_ids);
8157 }
8158
8159 /** Initialize the object.
8160 @return false on success else true. */
8161 bool Altered_partitions::initialize() {
8162 size_t alloc_size = sizeof(*m_new_table_parts) * m_num_new_parts;
8163 m_new_table_parts = static_cast<dict_table_t **>(ut::zalloc_withkey(
8164 ut::make_psi_memory_key(mem_key_partitioning), alloc_size));
8165
8166 alloc_size = sizeof(*m_ins_nodes) * m_num_new_parts;
8167 m_ins_nodes = static_cast<ins_node_t **>(ut::zalloc_withkey(
8168 ut::make_psi_memory_key(mem_key_partitioning), alloc_size));
8169
8170 alloc_size = sizeof(*m_bitset) * UT_BITS_IN_BYTES(m_num_new_parts);
8171 m_bitset = static_cast<byte *>(ut::zalloc_withkey(
8172 ut::make_psi_memory_key(mem_key_partitioning), alloc_size));
8173
8174 alloc_size = sizeof(*m_trx_ids) * m_num_new_parts;
8175 m_trx_ids = static_cast<trx_id_t *>(ut::zalloc_withkey(
8176 ut::make_psi_memory_key(mem_key_partitioning), alloc_size));
8177
8178 if (m_new_table_parts == nullptr || m_ins_nodes == nullptr ||
8179 m_bitset == nullptr || m_trx_ids == nullptr) {
8180 ut::free(m_new_table_parts);
8181 ut::free(m_ins_nodes);
8182 ut::free(m_bitset);
8183 ut::free(m_trx_ids);
8184
8185 return (true);
8186 }
8187
8188 m_sql_stat_start = {m_bitset, UT_BITS_IN_BYTES(m_num_new_parts)};
8189
8190 return (false);
8191 }
8192
8193 /** Class(interface) which manages the operations for partitions of states
8194 in different categories during ALTER PARTITION. There are four categories
8195 for now:
8196 1. normal: mapping to PART_NORMAL, which means the partition is not changed
8197 2. add: mapping to PART_TO_BE_ADDED
8198 3. drop: mapping to PART_TO_BE_DROPPED, PART_TO_BE_REORGED
8199 and PART_REORGED_DROPPED
8200 4. change: mapping to PART_CHANGED */
8201 class alter_part {
8202 public:
8203 /** Virtual destructor */
8204 virtual ~alter_part() = default;
8205
8206 /** Return the partition id */
8207 virtual uint part_id() const { return (m_part_id); }
8208
8209 /** Return the partition state */
8210 virtual partition_state state() const { return (m_state); }
8211
8212 /** Get the InnoDB table object for newly created partition
8213 if applicable
8214 @return the InnoDB table object or nullptr if not applicable */
8215 dict_table_t *new_table() { return (m_new); }
8216
8217 /** Set the freed old partition to nullptr to avoid dangling pointer
8218 @param check_in_cache whether we need to check table in cache
8219 @param part_name Partitioned table name .*/
8220 inline void free_old_part(bool check_in_cache, const char *part_name) {
8221 if (check_in_cache) {
8222 dict_sys_mutex_enter();
8223
8224 if (!dict_table_check_if_in_cache_low(part_name)) {
8225 *m_old = nullptr;
8226 }
8227
8228 dict_sys_mutex_exit();
8229
8230 } else {
8231 *m_old = nullptr;
8232 }
8233 }
8234
8235 /** Prepare
8236 @param[in,out] altered_table Table definition after the ALTER
8237 @param[in] old_part the stored old partition or nullptr
8238 if no corresponding one exists
8239 @param[in,out] new_part the stored new partition or nullptr
8240 if no corresponding one exists
8241 @return 0 or error number */
8242 virtual int prepare(TABLE *altered_table [[maybe_unused]],
8243 const dd::Partition *old_part [[maybe_unused]],
8244 dd::Partition *new_part [[maybe_unused]]) {
8245 return (0);
8246 }
8247
8248 /** Try to commit
8249 @param[in] table Table definition before the ALTER
8250 @param[in,out] altered_table Table definition after the ALTER
8251 @param[in] old_part the stored old partition or nullptr
8252 if no corresponding one exists
8253 @param[in,out] new_part the stored new partition or nullptr
8254 if no corresponding one exists
8255 @return 0 or error number */
8256 virtual int try_commit(const TABLE *table [[maybe_unused]],
8257 TABLE *altered_table [[maybe_unused]],
8258 const dd::Partition *old_part [[maybe_unused]],
8259 dd::Partition *new_part [[maybe_unused]]) {
8260 return (0);
8261 }
8262
8263 /** Rollback */
8264 virtual void rollback() { return; }
8265
8266 protected:
8267 /** Constructor
8268 @param[in,out] trx InnoDB transaction, nullptr if not used
8269 @param[in] part_id Partition id in the table. This could
8270 be partition id for either old table
8271 or new table, callers should remember
8272 which one is applicable
8273 @param[in] state Partition state of the partition on
8274 which this class will do operations.
8275 If this is for one partition in new
8276 table, the partition state is the same
8277 for both the new partition and the
8278 corresponding old partition
8279 @param[in] table_name Partitioned table name, in the
8280 form of db/table, which considers
8281 the charset
8282 @param[in,out] old InnoDB table object for old partition,
8283 default is nullptr, which means there
8284 is no corresponding object */
8285 alter_part(trx_t *trx, uint part_id, partition_state state,
8286 const char *table_name, dict_table_t **old)
8287 : m_trx(trx),
8288 m_part_id(part_id),
8289 m_state(state),
8290 m_table_name(table_name),
8291 m_old(old),
8292 m_new(nullptr) {}
8293
8294 /** Build the partition name for specified partition
8295 @param[in] dd_part dd::Partition
8296 @param[in] temp True if this is a temporary name
8297 @param[out] name Partition name buffer of length FN_REFLEN
8298 @return true if successful. */
8299 bool build_partition_name(const dd::Partition *dd_part, bool temp,
8300 char *name);
8301
8302 /** Create a new partition
8303 @param[in] part_table partition table
8304 @param[in] part_name Partition name, including db/table
8305 @param[in,out] dd_part dd::Partition
8306 @param[in] table Table format
8307 @param[in] tablespace Tablespace of this partition,
8308 if length is 0, it means no
8309 tablespace specified
8310 @param[in] file_per_table Current value of innodb_file_per_table
8311 @param[in] autoinc Next AUTOINC value to use
8312 @param[in] autoextend_size Value of AUTOEXTEND_SIZE for this tablespace
8313 @return 0 or error number */
8314 int create(const dd::Table *part_table, const char *part_name,
8315 dd::Partition *dd_part, TABLE *table, const char *tablespace,
8316 bool file_per_table, uint64_t autoinc, uint64_t autoextend_size);
8317
8318 protected:
8319 /** InnoDB transaction, nullptr if not used */
8320 trx_t *const m_trx;
8321
8322 /** Partition id in the table. This could be partition id for
8323 either old table or new table, callers should remember which one
8324 is applicable */
8325 uint m_part_id;
8326
8327 /** Partition state of the partition on which this class will
8328 do operations. If this is for one partition in new table, the
8329 partition state is the same for both the new partition and the
8330 corresponding old partition */
8331 partition_state m_state;
8332
8333 /** Partitioned table name, in form of ./db/table, which already
8334 considers the charset */
8335 const char *m_table_name;
8336
8337 /** The InnoDB table object for old partition */
8338 dict_table_t **m_old;
8339
8340 /** The InnoDB table object for newly created partition */
8341 dict_table_t *m_new;
8342 };
8343
8344 bool alter_part::build_partition_name(const dd::Partition *dd_part, bool temp,
8345 char *name) {
8346 if (!normalize_table_name(name, m_table_name)) {
8347 /* purecov: begin inspected */
8348 ut_d(ut_error);
8349 ut_o(return (false));
8350 /* purecov: end */
8351 }
8352
8353 std::string partition;
8354 /* Build the partition name. */
8355 dict_name::build_partition(dd_part, partition);
8356
8357 std::string partition_name;
8358 /* Build the partitioned table name. */
8359 dict_name::build_table("", name, partition, temp, false, partition_name);
8360 ut_ad(partition_name.length() < FN_REFLEN);
8361
8362 /* Copy partition table name. */
8363 auto name_len = partition_name.copy(name, FN_REFLEN - 1);
8364 name[name_len] = '\0';
8365
8366 return (true);
8367 }
8368
8369 int alter_part::create(const dd::Table *old_part_table, const char *part_name,
8370 dd::Partition *dd_part, TABLE *table,
8371 const char *tablespace, bool file_per_table,
8372 uint64_t autoinc, uint64_t autoextend_size) {
8373 ut_ad(m_state == PART_TO_BE_ADDED || m_state == PART_CHANGED);
8374
8375 dd::Table &dd_table = dd_part->table();
8376 dd::Properties &options = dd_table.options();
8377 uint32_t key_block_size;
8378 ut_ad(options.exists("key_block_size"));
8379 options.get("key_block_size", &key_block_size);
8380
8381 dd::Properties &part_options = dd_part->options();
8382 dd::String_type data_file_name;
8383 if (part_options.exists(data_file_name_key))
8384 (void)part_options.get(data_file_name_key, &data_file_name);
8385 /* index_file_name is not allowed for now */
8386 char full_path[FN_REFLEN];
8387 if (!data_file_name.empty()) {
8388 /* Have to append the postfix table name, to make it work */
8389 const char *name = strrchr(part_name, '/');
8390 ut_ad(name != nullptr);
8391 size_t len = data_file_name.length();
8392 strcpy(full_path, data_file_name.c_str());
8393 full_path[len] = OS_PATH_SEPARATOR;
8394 strcpy(full_path + len + 1, name + 1);
8395 }
8396
8397 HA_CREATE_INFO create_info;
8398 update_create_info_from_table(&create_info, table);
8399 create_info.auto_increment_value = autoinc;
8400 create_info.key_block_size = key_block_size;
8401 create_info.data_file_name = data_file_name.empty() ? nullptr : full_path;
8402 create_info.tablespace = tablespace[0] == '\0' ? nullptr : tablespace;
8403 create_info.m_implicit_tablespace_autoextend_size = autoextend_size;
8404
8405 /* The below check is the same as for CREATE TABLE, but since we are
8406 doing an alter here it will not trigger the check in
8407 create_option_tablespace_is_valid(). */
8408 if (tablespace_is_shared_space(&create_info) &&
8409 create_info.data_file_name != nullptr &&
8410 create_info.data_file_name[0] != '\0') {
8411 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
8412 "InnoDB: DATA DIRECTORY cannot be used"
8413 " with a TABLESPACE assignment.",
8414 MYF(0));
8415 return (HA_WRONG_CREATE_OPTION);
8416 }
8417
8418 return (innobase_basic_ddl::create_impl<dd::Partition>(
8419 current_thd, part_name, table, &create_info, dd_part, file_per_table,
8420 false, false, 0, 0, old_part_table));
8421 }
8422
8423 typedef std::vector<alter_part *, ut::allocator<alter_part *>> alter_part_array;
8424
8425 /** Construct all necessary alter_part_* objects according to the given
8426 partition states in both old and new tables */
8427 class alter_part_factory {
8428 public:
8429 /** Constructor
8430 @param[in,out] trx Transaction
8431 @param[in] ha_alter_info ALTER Information
8432 @param[in,out] part_share Innopart share
8433 @param[in] old_part_info Partition info of the table before
8434 ALTER TABLE */
8435 alter_part_factory(trx_t *trx, const Alter_inplace_info *ha_alter_info,
8436 Ha_innopart_share *part_share,
8437 partition_info *old_part_info)
8438 : m_trx(trx),
8439 m_part_share(part_share),
8440 m_ha_alter_info(ha_alter_info),
8441 m_old_part_info(old_part_info),
8442 m_file_per_table(srv_file_per_table) {}
8443
8444 /** Destructor */
8445 ~alter_part_factory() = default;
8446
8447 /** Create the alter_part_* objects according to the given
8448 partition states
8449 @param[in,out] to_drop To store the alter_part_* objects
8450 for partitions to be dropped
8451 @param[in,out] all_news To store the alter_part_* objects
8452 for partitions in table after
8453 ALTER TABLE
8454 @return false On success
8455 @retval true On failure */
8456 bool create(alter_part_array &to_drop, alter_part_array &all_news) {
8457 to_drop.clear();
8458 all_news.clear();
8459
8460 if (!(m_ha_alter_info->handler_flags &
8461 Alter_inplace_info::REORGANIZE_PARTITION)) {
8462 return (create_for_non_reorg(to_drop, all_news));
8463 } else {
8464 return (create_for_reorg(to_drop, all_news));
8465 }
8466 }
8467
8468 private:
8469 bool create_for_reorg(alter_part_array &to_drop, alter_part_array &all_news);
8470 bool create_for_non_reorg(alter_part_array &to_drop,
8471 alter_part_array &all_news);
8472 bool create_new_checking_conflict(partition_element *new_part,
8473 uint &new_part_id,
8474 alter_part_array &all_news);
8475 bool create_old_checking_conflict(partition_element *old_part,
8476 uint &old_part_id,
8477 alter_part_array &to_drop);
8478 bool is_conflict(const partition_element *new_part,
8479 const partition_element *old_part);
8480 bool create_one(alter_part_array &array, partition_element *part,
8481 uint &part_id, uint old_part_id, partition_state state,
8482 bool conflict);
8483 alter_part *create_one_low(uint &part_id, uint old_part_id,
8484 partition_state state, const char *tablespace,
8485 bool conflict);
8486
8487 private:
8488 /** InnoDB transaction */
8489 trx_t *const m_trx;
8490
8491 /** InnoDB partition specific Handler_share */
8492 Ha_innopart_share *const m_part_share;
8493
8494 /** ALTER information */
8495 const Alter_inplace_info *const m_ha_alter_info;
8496
8497 /** Partition info of the table before ALTER TABLE */
8498 partition_info *const m_old_part_info;
8499
8500 /** Current innodb_file_per_table value */
8501 bool m_file_per_table;
8502 };
8503
8504 /** Helper class for in-place alter partitions, see handler.h */
8505 class alter_parts : public inplace_alter_handler_ctx {
8506 public:
8507 /** Constructor
8508 @param[in,out] trx InnoDB transaction
8509 @param[in,out] part_share Innopart share
8510 @param[in] ha_alter_info ALTER information
8511 @param[in] old_part_info Partition info of the table before
8512 ALTER TABLE
8513 @param[in,out] new_partitions Altered partition helper */
8514 alter_parts(trx_t *trx, Ha_innopart_share *part_share,
8515 const Alter_inplace_info *ha_alter_info,
8516 partition_info *old_part_info, Altered_partitions *new_partitions)
8517 : m_trx(trx),
8518 m_part_share(part_share),
8519 m_ha_alter_info(ha_alter_info),
8520 m_new_partitions(new_partitions),
8521 m_factory(trx, ha_alter_info, part_share, old_part_info),
8522 m_news(),
8523 m_to_drop() {}
8524
8525 /** Destructor */
8526 ~alter_parts() override;
8527
8528 /** Create the to be created partitions and update internal
8529 structures with concurrent writes blocked, while preparing
8530 ALTER TABLE.
8531 @param[in] old_dd_tab dd::Table before ALTER TABLE
8532 @param[in,out] new_dd_tab dd::Table after ALTER TABLE
8533 @param[in,out] altered_table Table definition after the ALTER
8534 @return 0 or error number, my_error() should be called by callers */
8535 int prepare(const dd::Table &old_dd_tab, dd::Table &new_dd_tab,
8536 TABLE *altered_table);
8537
8538 /** Notify the storage engine that the changes made during
8539 prepare_inplace_alter_table() and inplace_alter_table()
8540 will be rolled back for all the partitions. */
8541 void rollback();
8542
8543 /** Try to commit the changes made during prepare_inplace_alter_table()
8544 inside the storage engine. This is protected by MDL_EXCLUSIVE.
8545 @param[in] old_dd_tab dd::Table before ALTER TABLE
8546 @param[in,out] new_dd_tab dd::Table after ALTER TABLE
8547 @param[in] table Table definition before the ALTER
8548 @param[in,out] altered_table Table definition after the ALTER
8549 @return 0 or error number, my_error() should be called by callers */
8550 int try_commit(const dd::Table &old_dd_tab, dd::Table &new_dd_tab,
8551 const TABLE *table, TABLE *altered_table);
8552
8553 /** Determine if this is an ALTER TABLE ... PARTITION operation
8554 @param[in] ha_alter_info thd DDL operation
8555 @return whether it is a such kind of operation */
8556 static inline bool apply_to(const Alter_inplace_info *ha_alter_info) {
8557 return ((ha_alter_info->handler_flags & OPERATIONS) != 0);
8558 }
8559
8560 /** Determine if copying data between partitions is necessary
8561 @param[in] ha_alter_info thd DDL operation
8562 @return whether it is necessary to copy data */
8563 static inline bool need_copy(const Alter_inplace_info *ha_alter_info) {
8564 ut_ad(apply_to(ha_alter_info));
8565
8566 /* Basically, only DROP PARTITION, ADD PARTITION for RANGE/LIST
8567 partitions don't require copying data between partitions */
8568 if (ha_alter_info->handler_flags & Alter_inplace_info::ADD_PARTITION) {
8569 switch (ha_alter_info->modified_part_info->part_type) {
8570 case partition_type::RANGE:
8571 case partition_type::LIST:
8572 return (false);
8573 default:
8574 break;
8575 }
8576 }
8577
8578 return (
8579 !(ha_alter_info->handler_flags & (Alter_inplace_info::DROP_PARTITION)));
8580 }
8581
8582 private:
8583 /** Initialize the m_news and m_to_drop array here
8584 @param[in] old_dd_tab dd::Table before ALTER TABLE
8585 @param[in] new_dd_tab dd::Table after ALTER TABLE
8586 @retval true if success
8587 @retval false on failure */
8588 bool prepare_alter_part(const dd::Table &old_dd_tab, dd::Table &new_dd_tab);
8589
8590 /** Prepare or commit for all the partitions in table after ALTER TABLE
8591 @param[in] old_dd_tab dd::Table before ALTER TABLE
8592 @param[in,out] new_dd_tab dd::Table after ALTER TABLE
8593 @param[in,out] altered_table Table definition after the ALTER
8594 @param[in] prepare true if it's in prepare phase,
8595 false if it's in commit phase
8596 @return 0 or error number */
8597 int prepare_or_commit_for_new(const dd::Table &old_dd_tab,
8598 dd::Table &new_dd_tab, TABLE *altered_table,
8599 bool prepare);
8600
8601 /** Prepare or commit for all the partitions in table before ALTER TABLE
8602 @param[in] old_dd_tab dd::Table before ALTER TABLE
8603 @param[in,out] altered_table Table definition after the ALTER
8604 @param[in] prepare true if it's in prepare phase,
8605 false if it's in commit phase
8606 @return 0 or error number */
8607 int prepare_or_commit_for_old(const dd::Table &old_dd_tab,
8608 TABLE *altered_table, bool prepare);
8609
8610 public:
8611 /** Operations that the native partitioning can perform inplace */
8612 static constexpr Alter_inplace_info::HA_ALTER_FLAGS OPERATIONS =
8613 Alter_inplace_info::ADD_PARTITION | Alter_inplace_info::DROP_PARTITION |
8614 Alter_inplace_info::ALTER_REBUILD_PARTITION |
8615 Alter_inplace_info::COALESCE_PARTITION |
8616 Alter_inplace_info::REORGANIZE_PARTITION;
8617
8618 private:
8619 /** InnoDB transaction */
8620 trx_t *const m_trx;
8621
8622 /** InnoDB partition specific Handler_share */
8623 Ha_innopart_share *const m_part_share;
8624
8625 /** Operation being performed */
8626 const Alter_inplace_info *const m_ha_alter_info;
8627
8628 /** New partitions helper */
8629 Altered_partitions *const m_new_partitions;
8630
8631 /** alter_part factory which creates all the necessary alter_part_* */
8632 alter_part_factory m_factory;
8633
8634 /** The alter_part array for all the newly created partitions */
8635 alter_part_array m_news;
8636
8637 /** The alter_part array for all the to be dropped partitions */
8638 alter_part_array m_to_drop;
8639 };
8640
8641 /** Class which handles the partition of state PART_NORMAL.
8642 See comments for alter_part_factory::create_for_reorg
8643 and alter_part_factory::create_for_non_reorg. */
8644 class alter_part_normal : public alter_part {
8645 public:
8646 /** Constructor
8647 @param[in] part_id Partition id in the table. This could
8648 be partition id for either old table
8649 or new table, callers should remember
8650 which one is applicable
8651 @param[in] state Partition state of the partition on
8652 which this class will do operations.
8653 If this is for one partition in new
8654 table, the partition state is the same
8655 for both the new partition and the
8656 corresponding old partition
8657 @param[in,out] old InnoDB table object for old partition,
8658 default is nullptr, which means there
8659 is no corresponding object */
8660 alter_part_normal(uint part_id, partition_state state, dict_table_t **old)
8661 : /* Table name is not used in this class, so pass a fake
8662 one */
8663 alter_part(nullptr, part_id, state, (*old)->name.m_name, old) {}
8664
8665 /** Destructor */
8666 ~alter_part_normal() override = default;
8667
8668 /** Prepare
8669 @param[in,out] altered_table Table definition after the ALTER
8670 @param[in] old_part the stored old partition or nullptr
8671 if no corresponding one exists
8672 @param[in,out] new_part the stored new partition or nullptr
8673 if no corresponding one exists
8674 @return 0 or error number */
8675 int prepare(TABLE *altered_table [[maybe_unused]],
8676 const dd::Partition *old_part, dd::Partition *new_part) override {
8677 ut_ad(old_part->name() == new_part->name());
8678
8679 dd_copy_private<dd::Partition>(*new_part, *old_part);
8680
8681 return (0);
8682 }
8683
8684 /** Try to commit
8685 @param[in] table Table definition before the ALTER
8686 @param[in,out] altered_table Table definition after the ALTER
8687 @param[in] old_part the stored old partition or nullptr
8688 if no corresponding one exists
8689 @param[in,out] new_part the stored new partition or nullptr
8690 if no corresponding one exists
8691 @return 0 or error number */
8692 int try_commit(const TABLE *table [[maybe_unused]],
8693 TABLE *altered_table [[maybe_unused]],
8694 const dd::Partition *old_part [[maybe_unused]],
8695 dd::Partition *new_part [[maybe_unused]]) override {
8696 ut_ad(m_old != nullptr);
8697
8698 btr_drop_ahi_for_table(*m_old);
8699
8700 dict_sys_mutex_enter();
8701 dd_table_close(*m_old, nullptr, nullptr, true);
8702 dict_table_remove_from_cache(*m_old);
8703 *m_old = nullptr;
8704 dict_sys_mutex_exit();
8705 return (0);
8706 }
8707 };
8708
8709 /** Class which handles the partition of the state PART_TO_BE_ADDED.
8710 See comments for alter_part_factory::create_for_reorg
8711 and alter_part_factory::create_for_non_reorg. */
8712 class alter_part_add : public alter_part {
8713 public:
8714 /** Constructor
8715 @param[in] part_id Partition id in the table. This could
8716 be partition id for either old table
8717 or new table, callers should remember
8718 which one is applicable
8719 @param[in] state Partition state of the partition on
8720 which this class will do operations.
8721 If this is for one partition in new
8722 table, the partition state is the same
8723 for both the new partition and the
8724 corresponding old partition
8725 @param[in] table_name Partitioned table name, in the form
8726 of db/table, which already considers
8727 the charset
8728 @param[in] tablespace Tablespace specified explicitly
8729 @param[in,out] trx InnoDB transaction
8730 @param[in] ha_alter_info ALTER information
8731 @param[in] file_per_table Current value of innodb_file_per_table
8732 @param[in] autoinc Next autoinc value to use
8733 @param[in] conflict True if there is already a partition
8734 table with the same name */
8735 alter_part_add(uint part_id, partition_state state, const char *table_name,
8736 const char *tablespace, trx_t *trx,
8737 const Alter_inplace_info *ha_alter_info, bool file_per_table,
8738 uint64_t autoinc, bool conflict)
8739 : alter_part(trx, part_id, state, table_name, nullptr),
8740 m_ha_alter_info(ha_alter_info),
8741 m_file_per_table(file_per_table),
8742 m_autoinc(autoinc),
8743 m_conflict(conflict) {
8744 if (tablespace == nullptr || tablespace[0] == '\0') {
8745 m_tablespace[0] = '\0';
8746 } else {
8747 strcpy(m_tablespace, tablespace);
8748 }
8749 }
8750
8751 /** Destructor */
8752 ~alter_part_add() override = default;
8753
8754 /** Prepare
8755 @param[in,out] altered_table Table definition after the ALTER
8756 @param[in] old_part the stored old partition or nullptr
8757 if no corresponding one exists
8758 @param[in,out] new_part the stored new partition or nullptr
8759 if no corresponding one exists
8760 @return 0 or error number */
8761 int prepare(TABLE *altered_table, const dd::Partition *old_part,
8762 dd::Partition *new_part) override {
8763 ut_ad(old_part != nullptr);
8764 ut_ad(new_part != nullptr);
8765 char part_name[FN_REFLEN];
8766
8767 if (is_shared_tablespace(m_tablespace)) {
8768 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION,
8769 PARTITION_IN_SHARED_TABLESPACE, MYF(0));
8770 return (HA_ERR_INTERNAL_ERROR);
8771 }
8772
8773 if (!build_partition_name(new_part, need_rename(), part_name)) {
8774 return (HA_ERR_TOO_LONG_PATH); /* purecov: inspected */
8775 }
8776
8777 /* Get the autoextend_size value from the old partition
8778 and set this value to the partition being added. */
8779 const dd::Table &part_table = old_part->table();
8780
8781 ulonglong autoextend_size{};
8782
8783 dd::get_implicit_tablespace_options(current_thd, &part_table,
8784 &autoextend_size);
8785
8786 int error =
8787 create(dd_table_has_instant_cols(part_table) ? &part_table : nullptr,
8788 part_name, new_part, altered_table, m_tablespace,
8789 m_file_per_table, m_autoinc, autoextend_size);
8790
8791 if (error == 0 && alter_parts::need_copy(m_ha_alter_info)) {
8792 /* If partition belongs to table with instant columns, copy instant
8793 metadata to new table DD */
8794 if (dd_table_has_row_versions(old_part->table())) {
8795 inherit_instant_metadata(&old_part->table(), &new_part->table());
8796 }
8797
8798 dict_sys_mutex_enter();
8799 m_new = dict_table_check_if_in_cache_low(part_name);
8800 ut_ad(m_new != nullptr);
8801 m_new->acquire();
8802 dict_table_ddl_release(m_new);
8803 dict_sys_mutex_exit();
8804
8805 return (m_new == nullptr ? DB_TABLE_NOT_FOUND : 0);
8806 }
8807
8808 return (error);
8809 }
8810
8811 /** Try to commit
8812 @param[in] table Table definition before the ALTER
8813 @param[in,out] altered_table Table definition after the ALTER
8814 @param[in] old_part the stored old partition or nullptr
8815 if no corresponding one exists
8816 @param[in,out] new_part the stored new partition or nullptr
8817 if no corresponding one exists
8818 @return 0 or error number */
8819 int try_commit(const TABLE *table [[maybe_unused]],
8820 TABLE *altered_table [[maybe_unused]],
8821 const dd::Partition *old_part [[maybe_unused]],
8822 dd::Partition *new_part) override {
8823 int error = 0;
8824
8825 if (need_rename()) {
8826 char old_name[FN_REFLEN];
8827 char new_name[FN_REFLEN];
8828
8829 if (build_partition_name(new_part, true, old_name) &&
8830 build_partition_name(new_part, false, new_name)) {
8831 error = innobase_basic_ddl::rename_impl<dd::Partition>(
8832 m_trx->mysql_thd, old_name, new_name, new_part, new_part, nullptr);
8833
8834 } else {
8835 error = HA_ERR_TOO_LONG_PATH; /* purecov: inspected */
8836 }
8837 }
8838
8839 if (m_new != nullptr) {
8840 dd_table_close(m_new, m_trx->mysql_thd, nullptr, false);
8841 m_new = nullptr;
8842 }
8843
8844 return (error);
8845 }
8846
8847 /** Rollback */
8848 void rollback() override {
8849 /* Release the new table so that in post DDL, this table can be
8850 rolled back. */
8851 if (m_new != nullptr) {
8852 dd_table_close(m_new, m_trx->mysql_thd, nullptr, false);
8853 m_new = nullptr;
8854 }
8855 }
8856
8857 private:
8858 /** Check if the new partition file needs a temporary name and
8859 should be renamed at last */
8860 bool need_rename() const { return (m_conflict); }
8861
8862 /** Inherit instant metadata of dd::Table and dd::Columns belonging to it.
8863 This is used when a new partition is added as part of REORGANIZE partition.
8864 @param[in] source Source dd table
8865 @param[in,out] dest Destination dd table */
8866 void inherit_instant_metadata(const dd::Table *source, dd::Table *dest);
8867
8868 private:
8869 /** ALTER information */
8870 const Alter_inplace_info *m_ha_alter_info;
8871
8872 /** Current value of innodb_file_per_table */
8873 const bool m_file_per_table;
8874
8875 /** Next AUTOINC value to use */
8876 const uint64_t m_autoinc;
8877
8878 /** True if there is already a partition table with the same name */
8879 const bool m_conflict;
8880
8881 /** Tablespace of this partition */
8882 char m_tablespace[FN_REFLEN + 1];
8883 };
8884
8885 void alter_part_add::inherit_instant_metadata(const dd::Table *source,
8886 dd::Table *dest) {
8887 auto add_dropped_column = [&](const dd::Column *column) {
8888 const char *col_name = column->name().c_str();
8889 /* Add this column as an SE_HIDDEN column in dest table def */
8890 dd::Column *new_column = dd_add_hidden_column(
8891 dest, col_name, column->char_length(), column->type());
8892 ut_ad(new_column != nullptr);
8893
8894 /* Copy se private data */
8895 ut_ad(!column->se_private_data().empty());
8896 new_column->se_private_data().clear();
8897 new_column->set_se_private_data(column->se_private_data());
8898
8899 new_column->set_nullable(column->is_nullable());
8900 new_column->set_char_length(column->char_length());
8901 new_column->set_numeric_scale(column->numeric_scale());
8902 new_column->set_unsigned(column->is_unsigned());
8903 new_column->set_collation_id(column->collation_id());
8904 new_column->set_type(column->type());
8905 /* Elements for enum columns */
8906 if (column->type() == dd::enum_column_types::ENUM ||
8907 column->type() == dd::enum_column_types::SET) {
8908 for (const auto *source_elem : column->elements()) {
8909 auto *elem_obj = new_column->add_element();
8910 elem_obj->set_name(source_elem->name());
8911 }
8912 }
8913 };
8914
8915 /* Copy dd::Column instant metadata */
8916 for (auto src_col : source->columns()) {
8917 dd::Column *dest_col =
8918 const_cast<dd::Column *>(dd_find_column(dest, src_col->name().c_str()));
8919
8920 if (dest_col == nullptr) {
8921 add_dropped_column(src_col);
8922 ut_ad(nullptr != dd_find_column(dest, src_col->name().c_str()));
8923 continue;
8924 }
8925
8926 if (dest_col->is_virtual()) {
8927 continue;
8928 }
8929
8930 auto fn = [&](const char *s, auto &value) {
8931 if (src_col->se_private_data().exists(s)) {
8932 src_col->se_private_data().get(s, &value);
8933 dest_col->se_private_data().set(s, value);
8934 }
8935 };
8936
8937 uint32_t v_added = UINT32_UNDEFINED;
8938 const char *s = dd_column_key_strings[DD_INSTANT_VERSION_ADDED];
8939 fn(s, v_added);
8940
8941 uint32_t v_dropped = UINT32_UNDEFINED;
8942 s = dd_column_key_strings[DD_INSTANT_VERSION_DROPPED];
8943 fn(s, v_dropped);
8944
8945 uint32_t phy_pos = UINT32_UNDEFINED;
8946 s = dd_column_key_strings[DD_INSTANT_PHYSICAL_POS];
8947 ut_ad(src_col->se_private_data().exists(s));
8948 fn(s, phy_pos);
8949
8950 s = dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT_NULL];
8951 if (src_col->se_private_data().exists(s)) {
8952 ut_ad(v_added > 0);
8953 bool value = false;
8954 fn(s, value);
8955 } else {
8956 s = dd_column_key_strings[DD_INSTANT_COLUMN_DEFAULT];
8957 if (src_col->se_private_data().exists(s)) {
8958 ut_ad(v_added > 0);
8959 dd::String_type value;
8960 fn(s, value);
8961 } else {
8962 /* This columns is not INSTANT ADD or this column is already dropped. */
8963 ut_ad(v_added == UINT32_UNDEFINED || v_dropped > 0);
8964 }
8965 }
8966 }
8967 }
8968
8969 /** Class which handles the partition of states
8970 PART_TO_BE_DROPPED, PART_TO_BE_REORGED and PART_REORGED_DROPPED.
8971 See comments for alter_part_factory::create_for_reorg
8972 and alter_part_factory::create_for_non_reorg. */
8973 class alter_part_drop : public alter_part {
8974 public:
8975 /** Constructor
8976 @param[in] part_id Partition id in the table. This could
8977 be partition id for either old table
8978 or new table, callers should remember
8979 which one is applicable
8980 @param[in] state Partition state of the partition on
8981 which this class will do operations.
8982 If this is for one partition in new
8983 table, the partition state is the same
8984 for both the new partition and the
8985 corresponding old partition
8986 @param[in] table_name Partitioned table name, in the form
8987 of db/table, which already considers
8988 the charset
8989 @param[in,out] trx InnoDB transaction
8990 @param[in,out] old InnoDB table object for old partition,
8991 default is nullptr, which means there
8992 is no corresponding object
8993 @param[in] conflict True if there is already a partition
8994 table with the same name */
8995 alter_part_drop(uint part_id, partition_state state, const char *table_name,
8996 trx_t *trx, dict_table_t **old, bool conflict)
8997 : alter_part(trx, part_id, state, table_name, old),
8998 m_conflict(conflict) {}
8999
9000 /** Destructor */
9001 ~alter_part_drop() override = default;
9002
9003 /** Try to commit
9004 @param[in] table Table definition before the ALTER
9005 @param[in,out] altered_table Table definition after the ALTER
9006 @param[in] old_part the stored old partition or nullptr
9007 if no corresponding one exists
9008 @param[in,out] new_part the stored new partition or nullptr
9009 if no corresponding one exists
9010 @return 0 or error number */
9011 int try_commit(const TABLE *table [[maybe_unused]],
9012 TABLE *altered_table [[maybe_unused]],
9013 const dd::Partition *old_part,
9014 dd::Partition *new_part) override {
9015 ut_ad(new_part == nullptr);
9016
9017 dict_sys_mutex_enter();
9018 dict_table_ddl_acquire(*m_old);
9019 dict_sys_mutex_exit();
9020 dd_table_close(*m_old, nullptr, nullptr, false);
9021
9022 int error;
9023 char part_name[FN_REFLEN];
9024 THD *thd = m_trx->mysql_thd;
9025
9026 if (!build_partition_name(old_part, false, part_name)) {
9027 return (HA_ERR_TOO_LONG_PATH); /* purecov: inspected */
9028 }
9029
9030 if (!m_conflict) {
9031 error = innobase_basic_ddl::delete_impl<dd::Partition>(thd, part_name,
9032 old_part, nullptr);
9033 DBUG_EXECUTE_IF("drop_part_fail", error = DB_ERROR;
9034 my_error(ER_LOCK_WAIT_TIMEOUT, MYF(0)););
9035 } else {
9036 /* Have to rename it to a temporary name to prevent
9037 name conflict, because later deleting table doesn't
9038 remove the data file at once. Also notice that don't
9039 use the #tmp name, because it could be already used
9040 by the corresponding new partition. */
9041 mem_heap_t *heap = mem_heap_create(FN_REFLEN, UT_LOCATION_HERE);
9042
9043 char *temp_name = dict_mem_create_temporary_tablename(
9044 heap, (*m_old)->name.m_name, (*m_old)->id);
9045
9046 std::string db_str;
9047 std::string tbl_str;
9048 dict_name::get_table(temp_name, db_str, tbl_str);
9049
9050 /* Acquire mdl lock on the temporary table name. */
9051 MDL_ticket *mdl_ticket = nullptr;
9052 if (dd::acquire_exclusive_table_mdl(thd, db_str.c_str(), tbl_str.c_str(),
9053 false, &mdl_ticket)) {
9054 mem_heap_free(heap);
9055 return (HA_ERR_GENERIC);
9056 }
9057
9058 error = innobase_basic_ddl::rename_impl<dd::Partition>(
9059 thd, part_name, temp_name, old_part, old_part, nullptr);
9060 if (error == 0) {
9061 error = innobase_basic_ddl::delete_impl<dd::Partition>(
9062 thd, temp_name, old_part, nullptr);
9063 }
9064
9065 mem_heap_free(heap);
9066 }
9067
9068 free_old_part(error != 0, part_name);
9069
9070 return (error);
9071 }
9072
9073 private:
9074 /** True if there is already a partition table with the same name */
9075 const bool m_conflict;
9076 };
9077
9078 /** Class which handles the partition of the state PART_CHANGED.
9079 See comments for alter_part_factory::create_for_reorg
9080 and alter_part_factory::create_for_non_reorg. */
9081 class alter_part_change : public alter_part {
9082 public:
9083 /** Constructor
9084 @param[in] part_id Partition id in the table. This could
9085 be partition id for either old table
9086 or new table, callers should remember
9087 which one is applicable
9088 @param[in] state Partition state of the partition on
9089 which this class will do operations.
9090 If this is for one partition in new
9091 table, the partition state is the same
9092 for both the new partition and the
9093 corresponding old partition
9094 @param[in] table_name Partitioned table name, in the form
9095 of db/table, which already considers
9096 the chraset
9097 @param[in] tablespace Tablespace specified explicitly
9098 @param[in,out] trx InnoDB transaction
9099 @param[in,out] old InnoDB table object for old partition,
9100 default is nullptr, which means there
9101 is no corresponding object
9102 @param[in] ha_alter_info ALTER information
9103 @param[in] file_per_table Current value of innodb_file_per_table
9104 @param[in] autoinc Next AUTOINC value to use */
9105 alter_part_change(uint part_id, partition_state state, const char *table_name,
9106 const char *tablespace, trx_t *trx, dict_table_t **old,
9107 const Alter_inplace_info *ha_alter_info,
9108 bool file_per_table, uint64_t autoinc)
9109 : alter_part(trx, part_id, state, table_name, old),
9110 m_ha_alter_info(ha_alter_info),
9111 m_file_per_table(file_per_table),
9112 m_autoinc(autoinc) {
9113 if (tablespace == nullptr || tablespace[0] == '\0') {
9114 m_tablespace[0] = '\0';
9115 } else {
9116 strcpy(m_tablespace, tablespace);
9117 }
9118 }
9119
9120 /** Destructor */
9121 ~alter_part_change() override = default;
9122
9123 /** Prepare
9124 @param[in,out] altered_table Table definition after the ALTER
9125 @param[in] old_part the stored old partition or nullptr
9126 if no corresponding one exists
9127 @param[in,out] new_part the stored new partition or nullptr
9128 if no corresponding one exists
9129 @return 0 or error number */
9130 int prepare(TABLE *altered_table, const dd::Partition *old_part,
9131 dd::Partition *new_part) override;
9132
9133 /** Try to commit
9134 @param[in] table Table definition before the ALTER
9135 @param[in,out] altered_table Table definition after the ALTER
9136 @param[in] old_part the stored old partition or nullptr
9137 if no corresponding one exists
9138 @param[in,out] new_part the stored new partition or nullptr
9139 if no corresponding one exists
9140 @return 0 or error number */
9141 int try_commit(const TABLE *table, TABLE *altered_table,
9142 const dd::Partition *old_part,
9143 dd::Partition *new_part) override;
9144
9145 /** Rollback */
9146 void rollback() override {
9147 /* Release the new table so that in post DDL, this table can be
9148 rolled back. */
9149 if (m_new != nullptr) {
9150 dd_table_close(m_new, m_trx->mysql_thd, nullptr, false);
9151 m_new = nullptr;
9152 }
9153 }
9154
9155 private:
9156 /** ALTER information */
9157 const Alter_inplace_info *m_ha_alter_info;
9158
9159 /** Current value of innodb_file_per_table */
9160 const bool m_file_per_table;
9161
9162 /** Next AUTOINC value to use */
9163 const uint64_t m_autoinc;
9164
9165 /** Tablespace of this partition */
9166 char m_tablespace[FN_REFLEN + 1];
9167 };
9168
9169 /** Prepare
9170 @param[in,out] altered_table Table definition after the ALTER
9171 @param[in] old_part the stored old partition or nullptr
9172 if no corresponding one exists
9173 @param[in,out] new_part the stored new partition or nullptr
9174 if no corresponding one exists
9175 @return 0 or error number */
9176 int alter_part_change::prepare(TABLE *altered_table,
9177 const dd::Partition *old_part,
9178 dd::Partition *new_part) {
9179 ut_ad(old_part != nullptr);
9180 ut_ad(new_part != nullptr);
9181
9182 /* In some scenario, it could be unnecessary to create partition
9183 with temporary name, for example, old one is in innodb_system while
9184 new one is innodb_file_per_table. However, this would result in
9185 same table name for two tables, which is confusing. So the temporary
9186 name is used always and final rename is necessary too */
9187 char part_name[FN_REFLEN];
9188
9189 if (!build_partition_name(new_part, true, part_name)) {
9190 return (HA_ERR_TOO_LONG_PATH); /* purecov: inspected */
9191 }
9192
9193 /* Copy the autoextend_size attribute for the partition being
9194 created. */
9195 const dd::Table &part_table = old_part->table();
9196
9197 ulonglong autoextend_size{};
9198
9199 dd::get_implicit_tablespace_options(current_thd, &part_table,
9200 &autoextend_size);
9201
9202 int error =
9203 create(dd_table_has_instant_cols(part_table) ? &part_table : nullptr,
9204 part_name, new_part, altered_table, m_tablespace, m_file_per_table,
9205 m_autoinc, autoextend_size);
9206
9207 if (error == 0) {
9208 dict_sys_mutex_enter();
9209 m_new = dict_table_check_if_in_cache_low(part_name);
9210 ut_ad(m_new != nullptr);
9211 m_new->acquire();
9212 dict_table_ddl_release(m_new);
9213 dict_sys_mutex_exit();
9214
9215 return (m_new == nullptr);
9216 }
9217
9218 return (error);
9219 }
9220
9221 /** Try to commit
9222 @param[in] table Table definition before the ALTER
9223 @param[in,out] altered_table Table definition after the ALTER
9224 @param[in] old_part the stored old partition or nullptr
9225 if no corresponding one exists
9226 @param[in,out] new_part the stored new partition or nullptr
9227 if no corresponding one exists
9228 @return 0 or error number */
9229 int alter_part_change::try_commit(const TABLE *table [[maybe_unused]],
9230 TABLE *altered_table [[maybe_unused]],
9231 const dd::Partition *old_part,
9232 dd::Partition *new_part) {
9233 ut_ad(old_part != nullptr);
9234 ut_ad(new_part != nullptr);
9235 ut_ad(old_part->name() == new_part->name());
9236
9237 THD *thd = m_trx->mysql_thd;
9238
9239 char *temp_old_name = dict_mem_create_temporary_tablename(
9240 (*m_old)->heap, (*m_old)->name.m_name, (*m_old)->id);
9241
9242 dict_sys_mutex_enter();
9243 dict_table_ddl_acquire(*m_old);
9244 dict_sys_mutex_exit();
9245 dd_table_close(*m_old, nullptr, nullptr, false);
9246
9247 std::string db_str;
9248 std::string tbl_str;
9249 dict_name::get_table(temp_old_name, db_str, tbl_str);
9250
9251 /* Acquire mdl lock on the temporary table name. */
9252 MDL_ticket *mdl_ticket = nullptr;
9253 if (dd::acquire_exclusive_table_mdl(thd, db_str.c_str(), tbl_str.c_str(),
9254 false, &mdl_ticket)) {
9255 return (HA_ERR_GENERIC);
9256 }
9257
9258 char old_name[FN_REFLEN];
9259 char temp_name[FN_REFLEN];
9260
9261 if (!build_partition_name(new_part, false, old_name) ||
9262 !build_partition_name(new_part, true, temp_name)) {
9263 return (HA_ERR_TOO_LONG_PATH); /* purecov: inspected */
9264 }
9265
9266 int error;
9267
9268 error = innobase_basic_ddl::rename_impl<dd::Partition>(
9269 thd, old_name, temp_old_name, old_part, old_part, nullptr);
9270 if (error == 0) {
9271 error = innobase_basic_ddl::rename_impl<dd::Partition>(
9272 thd, temp_name, old_name, new_part, new_part, nullptr);
9273 if (error == 0) {
9274 error = innobase_basic_ddl::delete_impl<dd::Partition>(thd, temp_old_name,
9275 old_part, nullptr);
9276 free_old_part(error != 0, temp_old_name);
9277 }
9278 }
9279
9280 if (m_new != nullptr) {
9281 dd_table_close(m_new, thd, nullptr, false);
9282 m_new = nullptr;
9283 }
9284
9285 return (error);
9286 }
9287
9288 /** Create alter_part_* object(s) for subpartitions of a partition,
9289 or the partition itself
9290 @param[in,out] array Where to store the new object(s)
9291 @param[in] part partition_element to handle
9292 @param[in,out] part_id Partition id for both partition and
9293 subpartition, which would be increased
9294 by number of object(s) created
9295 @param[in] old_part_id Start partition id of the table before
9296 ALTER TABLE
9297 @param[in] state Partition state
9298 @param[in] conflict Only valid when state is
9299 PART_TO_BE_ADDED. True if the new
9300 (sub)partition has the same name with
9301 an exist one and they are of
9302 innodb_file_per_table
9303 @retval false On success
9304 @retval true On failure */
9305 bool alter_part_factory::create_one(alter_part_array &array,
9306 partition_element *part, uint &part_id,
9307 uint old_part_id, partition_state state,
9308 bool conflict) {
9309 if (part->subpartitions.elements > 0) {
9310 partition_element *sub_elem;
9311 List_iterator_fast<partition_element> new_sub_it(part->subpartitions);
9312 while ((sub_elem = new_sub_it++) != nullptr) {
9313 const char *tablespace = partition_get_tablespace(
9314 m_ha_alter_info->create_info->tablespace, part, sub_elem);
9315 alter_part *alter =
9316 create_one_low(part_id, old_part_id++, state, tablespace, conflict);
9317 if (alter == nullptr) {
9318 return (true);
9319 }
9320
9321 ++part_id;
9322 array.push_back(alter);
9323 }
9324 } else {
9325 const char *tablespace = partition_get_tablespace(
9326 m_ha_alter_info->create_info->tablespace, part, nullptr);
9327 alter_part *alter =
9328 create_one_low(part_id, old_part_id++, state, tablespace, conflict);
9329 if (alter == nullptr) {
9330 return (true);
9331 }
9332
9333 ++part_id;
9334 array.push_back(alter);
9335 }
9336
9337 return (false);
9338 }
9339
9340 /** Create the specified alter_part_* object
9341 @param[in] part_id Partition id for current partition
9342
9343 @param[in] old_part_id Start partition id of the table before
9344 ALTER TABLE
9345 @param[in] state Partition state
9346 @param[in] tablespace Tablespace specified explicitly
9347 @param[in] conflict Only valid when state is
9348 PART_TO_BE_ADDED. True if the new
9349 (sub)partition has the same name with
9350 an exist one and they are of
9351 innodb_file_per_table
9352 @return alter_part_* object or nullptr */
9353 alter_part *alter_part_factory::create_one_low(uint &part_id, uint old_part_id,
9354 partition_state state,
9355 const char *tablespace,
9356 bool conflict) {
9357 alter_part *alter_part = nullptr;
9358
9359 switch (state) {
9360 case PART_NORMAL:
9361 alter_part = ut::new_withkey<alter_part_normal>(
9362 ut::make_psi_memory_key(mem_key_partitioning), part_id, state,
9363 m_part_share->get_table_part_ref(old_part_id));
9364 break;
9365 case PART_TO_BE_ADDED:
9366 alter_part = ut::new_withkey<alter_part_add>(
9367 ut::make_psi_memory_key(mem_key_partitioning), part_id, state,
9368 m_part_share->get_table_share()->normalized_path.str, tablespace,
9369 m_trx, m_ha_alter_info, m_file_per_table,
9370 m_part_share->next_auto_inc_val, conflict);
9371 break;
9372 case PART_TO_BE_DROPPED:
9373 case PART_TO_BE_REORGED:
9374 case PART_REORGED_DROPPED:
9375 alter_part = ut::new_withkey<alter_part_drop>(
9376 ut::make_psi_memory_key(mem_key_partitioning), part_id, state,
9377 m_part_share->get_table_share()->normalized_path.str, m_trx,
9378 m_part_share->get_table_part_ref(old_part_id), conflict);
9379 break;
9380 case PART_CHANGED:
9381 alter_part = ut::new_withkey<alter_part_change>(
9382 ut::make_psi_memory_key(mem_key_partitioning), part_id, state,
9383 m_part_share->get_table_share()->normalized_path.str, tablespace,
9384 m_trx, m_part_share->get_table_part_ref(old_part_id), m_ha_alter_info,
9385 m_file_per_table, m_part_share->next_auto_inc_val);
9386 break;
9387 default:
9388 ut_d(ut_error);
9389 }
9390
9391 return (alter_part);
9392 }
9393
9394 /** Create alter_part_add object(s) along with checking if the
9395 partition (and its subpartitions) conflicts with any of the original ones
9396 This is only for REORGANIZE PARTITION
9397 @param[in] new_part The new partition to check
9398 @param[in,out] new_part_id Partition id for both partition and
9399 subpartition, which would be increased
9400 by number of subpartitions per partition here
9401 @param[in,out] all_news To store the alter_part_add objects here
9402 @retval false On success
9403 @retval true On failure */
9404 bool alter_part_factory::create_new_checking_conflict(
9405 partition_element *new_part, uint &new_part_id,
9406 alter_part_array &all_news) {
9407 ut_ad((m_ha_alter_info->handler_flags &
9408 Alter_inplace_info::REORGANIZE_PARTITION) != 0);
9409
9410 partition_info *part_info = m_ha_alter_info->modified_part_info;
9411 /* To compare with this partition list which contains all the
9412 to be reorganized partitions */
9413 List_iterator_fast<partition_element> tmp_part_it(part_info->temp_partitions);
9414 partition_element *tmp_part_elem;
9415
9416 while ((tmp_part_elem = tmp_part_it++) != nullptr) {
9417 if (!is_conflict(new_part, tmp_part_elem)) {
9418 continue;
9419 }
9420
9421 if (m_ha_alter_info->modified_part_info->is_sub_partitioned()) {
9422 List_iterator_fast<partition_element> tmp_sub_it(
9423 tmp_part_elem->subpartitions);
9424 partition_element *tmp_sub_elem;
9425 List_iterator_fast<partition_element> new_sub_it(new_part->subpartitions);
9426 partition_element *new_sub_elem;
9427
9428 while ((new_sub_elem = new_sub_it++) != nullptr) {
9429 ut_ad(new_sub_elem->partition_name != nullptr);
9430 tmp_sub_elem = tmp_sub_it++;
9431 ut_ad(tmp_sub_elem != nullptr);
9432 ut_ad(tmp_sub_elem->partition_name != nullptr);
9433
9434 bool conflict = is_conflict(new_sub_elem, tmp_sub_elem);
9435 if (create_one(all_news, new_sub_elem, new_part_id, 0, PART_TO_BE_ADDED,
9436 conflict)) {
9437 return (true);
9438 }
9439 }
9440 ut_ad((tmp_sub_elem = tmp_sub_it++) == nullptr);
9441 } else {
9442 if (create_one(all_news, new_part, new_part_id, 0, PART_TO_BE_ADDED,
9443 true)) {
9444 return (true);
9445 }
9446 }
9447
9448 /* Once matched, all are done */
9449 return (false);
9450 }
9451
9452 return (
9453 create_one(all_news, new_part, new_part_id, 0, PART_TO_BE_ADDED, false));
9454 }
9455
9456 /** Create alter_part_drop object(s) along with checking if the
9457 partition (and its subpartitions) conflicts with any of the to
9458 be created ones.
9459 This is only for REORGANIZE PARTITION
9460 @param[in] old_part The old partition to check
9461 @param[in,out] old_part_id Partition id for this partition or
9462 the first subpartition, which would
9463 be increased by number of subpartitions
9464 per partition here
9465 @param[in,out] to_drop To store the alter_part_drop objects
9466 @retval false On success
9467 @retval true On failure */
9468 bool alter_part_factory::create_old_checking_conflict(
9469 partition_element *old_part, uint &old_part_id, alter_part_array &to_drop) {
9470 ut_ad((m_ha_alter_info->handler_flags &
9471 Alter_inplace_info::REORGANIZE_PARTITION) != 0);
9472
9473 partition_info *part_info = m_ha_alter_info->modified_part_info;
9474 /* To compare with this partition list which contains all the
9475 new to be added partitions */
9476 List_iterator_fast<partition_element> part_it(part_info->partitions);
9477 partition_element *part_elem;
9478
9479 while ((part_elem = part_it++) != nullptr) {
9480 if (!is_conflict(part_elem, old_part)) {
9481 continue;
9482 }
9483
9484 if (m_ha_alter_info->modified_part_info->is_sub_partitioned()) {
9485 List_iterator_fast<partition_element> sub_it(part_elem->subpartitions);
9486 partition_element *sub_elem;
9487 List_iterator_fast<partition_element> old_sub_it(old_part->subpartitions);
9488 partition_element *old_sub_elem;
9489
9490 while ((old_sub_elem = old_sub_it++) != nullptr) {
9491 ut_ad(old_sub_elem->partition_name != nullptr);
9492 sub_elem = sub_it++;
9493 ut_ad(sub_elem != nullptr);
9494 ut_ad(sub_elem->partition_name != nullptr);
9495
9496 bool conflict = is_conflict(sub_elem, old_sub_elem);
9497 if (create_one(to_drop, old_sub_elem, old_part_id, old_part_id,
9498 PART_TO_BE_REORGED, conflict)) {
9499 return (true);
9500 }
9501 }
9502 ut_ad((sub_elem = sub_it++) == nullptr);
9503 } else {
9504 if (create_one(to_drop, old_part, old_part_id, old_part_id,
9505 PART_TO_BE_REORGED, true)) {
9506 return (true);
9507 }
9508 }
9509
9510 /* Once matched, all are done */
9511 return (false);
9512 }
9513
9514 return (create_one(to_drop, old_part, old_part_id, old_part_id,
9515 PART_TO_BE_REORGED, false));
9516 }
9517
9518 /** Check if the two (sub)partitions conflict with each other,
9519 Which means they have same name.
9520 @param[in] new_part New partition to check
9521 @param[in] old_part Old partition to check
9522 @retval true Conflict
9523 @retval false Not conflict */
9524 bool alter_part_factory::is_conflict(const partition_element *new_part,
9525 const partition_element *old_part) {
9526 if (my_strcasecmp(system_charset_info, new_part->partition_name,
9527 old_part->partition_name) != 0) {
9528 return (false);
9529 }
9530
9531 /* To prevent the conflict(same) names in table cache, not to
9532 check the innodb_file_per_table */
9533 return (true);
9534 }
9535
9536 /** Suppose that there is a table with 4 range partitions: p0, p1, p2, p3,
9537 and the p2 and p3 are going to be reorganized into p21, p22, p31, p33.
9538
9539 In modified_part_info->temp_partitions list, there are only p2 and p3
9540 with the state PART_TO_BE_REORGED, while in modified_part_info->partitions
9541 list, it contains
9542 {PART_NORMAL, PART_NORMAL, PART_TO_BE_ADDED, PART_TO_BE_ADDED,
9543 PART_TO_BE_ADDED, PART_TO_BE_ADDED}.
9544
9545 So finally, the to_drop array would contain
9546 {alter_part_drop, alter_part_drop}, which are for p2, p3;
9547 the all_news array would contains
9548 {alter_part_normal, alter_part_normal, alter_part_add, alter_part_add,
9549 alter_part_add, alter_part_add}.
9550
9551 Note that the scenario that reorganized and to be reorganized
9552 partition/subpartition have the same name, would be checked here too */
9553
9554 /** Create the alter_part_* objects when it's an operation like
9555 REORGANIZE PARTITION
9556 @param[in,out] to_drop To store the alter_part_* objects
9557 for partitions to be dropped
9558 @param[in,out] all_news To store the alter_part_* objects
9559 for partitions in table after ALTER TABLE
9560 @return false On success
9561 @retval true On failure */
9562 bool alter_part_factory::create_for_reorg(alter_part_array &to_drop,
9563 alter_part_array &all_news) {
9564 ut_ad((m_ha_alter_info->handler_flags &
9565 Alter_inplace_info::REORGANIZE_PARTITION) != 0);
9566 ut_ad(m_ha_alter_info->modified_part_info->num_subparts ==
9567 m_old_part_info->num_subparts);
9568
9569 partition_info *part_info = m_ha_alter_info->modified_part_info;
9570 /* This list contains only the to be reorganized partitions,
9571 the sequence is the same as the list of m_old_part_info,
9572 and they should be consecutive ones */
9573 List_iterator_fast<partition_element> tmp_part_it(part_info->temp_partitions);
9574 /* This list contains all the new partitions */
9575 List_iterator_fast<partition_element> part_it(part_info->partitions);
9576 /* This list contains all the old partitions */
9577 List_iterator_fast<partition_element> old_part_it(
9578 m_old_part_info->partitions);
9579 partition_element *part_elem;
9580 partition_element *tmp_part_elem;
9581 partition_element *old_part_elem;
9582 uint parts_per_part =
9583 part_info->is_sub_partitioned() ? part_info->num_subparts : 1;
9584
9585 tmp_part_elem = tmp_part_it++;
9586 ut_ad(tmp_part_elem != nullptr);
9587 old_part_elem = old_part_it++;
9588 ut_ad(old_part_elem != nullptr);
9589
9590 uint old_part_id = 0;
9591 uint new_part_id = 0;
9592
9593 /* There are 3 steps here:
9594 1. Check if the old one is a to be reorganized one, if so, mark it
9595 and check next old one
9596 2. If not, check if the new one is a to be added one, if so, mark it
9597 and check next new one
9598 3. If not, the old one and the new one should point to the same
9599 partition */
9600 while ((part_elem = part_it++) != nullptr) {
9601 while (old_part_elem != nullptr && tmp_part_elem != nullptr &&
9602 strcmp(tmp_part_elem->partition_name,
9603 old_part_elem->partition_name) == 0) {
9604 ut_ad(tmp_part_elem->part_state == PART_TO_BE_REORGED);
9605
9606 if (create_old_checking_conflict(old_part_elem, old_part_id, to_drop)) {
9607 return (true);
9608 }
9609
9610 old_part_elem = old_part_it++;
9611 tmp_part_elem = tmp_part_it++;
9612 }
9613
9614 switch (part_elem->part_state) {
9615 case PART_TO_BE_ADDED:
9616
9617 if (create_new_checking_conflict(part_elem, new_part_id, all_news)) {
9618 return (true);
9619 }
9620
9621 break;
9622
9623 case PART_NORMAL:
9624
9625 ut_ad(strcmp(part_elem->partition_name,
9626 old_part_elem->partition_name) == 0);
9627
9628 if (create_one(all_news, part_elem, new_part_id, old_part_id,
9629 PART_NORMAL, false)) {
9630 return (true);
9631 }
9632
9633 old_part_elem = old_part_it++;
9634 old_part_id += parts_per_part;
9635
9636 break;
9637
9638 default:
9639 ut_d(ut_error);
9640 }
9641 }
9642
9643 ut_ad(old_part_elem == nullptr);
9644 ut_ad(tmp_part_elem == nullptr);
9645
9646 return (false);
9647 }
9648
9649 /** Suppose that there is a table with 4 range partitions: p0, p1, p2, p3.
9650
9651 1. ADD PARTITION p4
9652 modified_part_info->partitions list contains
9653 {PART_NORMAL, PART_NORMAL, PART_NORMAL, PART_NORMAL, PART_TO_BE_ADDED}.
9654
9655 So finally, the to_drop array would contain
9656 {}, which is empty;
9657 the all_news array would contains
9658 {alter_part_normal, alter_part_normal, alter_part_normal, alter_part_normal,
9659 alter_part_add}.
9660
9661 2. DROP PARTITION p2
9662 modified_part_info->partitions list contain
9663 {PART_NORMAL, PART_NORMAL, PART_TO_BE_DROPPED, PART_NORMAL}.
9664
9665 So finally, the to_drop array would contain
9666 {alter_part_drop}, which is for p2, so part_id is 2;
9667 the all_news array would contains
9668 {alter_part_normal, alter_part_normal, alter_part_normal}.
9669
9670
9671 Suppose it's the same table with 4 partitions, but it's partitioned by HASH.
9672
9673 3. ADD PARTITION 2
9674 modified_part_info->partitions list contains
9675 {PART_CHANGED, PART_CHANGED, PART_CHANGED, PART_CHANGED, PART_TO_BE_ADDED,
9676 PART_TO_BE_ADDED}.
9677
9678 So finally, the to_drop array would contain
9679 {}, which is empty;
9680 the all_news array would contains
9681 {alter_part_change, alter_part_change, alter_part_change, alter_part_change,
9682 alter_part_add, alter_part_add}.
9683
9684 4. COALESCE PARTITION 2
9685 modified_part_info->partitions contains:
9686 {PART_CHANGED, PART_CHANGED, PART_REORGED_DROPPED, PART_REORGED_DROPPED}.
9687
9688 So finally, the to_drop array would contain
9689 {alter_part_drop, alter_part_drop}, which are for p2, p3, part_id are 2 and 3;
9690 the all_news array would contains
9691 {alter_part_change, alter_part_change}.
9692
9693 5. REBUILD PARTITION p0, p2
9694 modified_part_info->partitions contains:
9695 {PART_NORMAL, PART_CHANGED, PART_NORMAL, PART_CHANGED}.
9696
9697 So finally, the to_drop array would contain
9698 {}, which is empty;
9699 the all_news array would contains
9700 {alter_part_normal, alter_part_change, alter_part_normal, alter_part_change}. */
9701
9702 /** Create the alter_part_* objects when it's NOT an operation like
9703 REORGANIZE PARTITION
9704 @param[in,out] to_drop To store the alter_part_* objects
9705 for partitions to be dropped
9706 @param[in,out] all_news To store the alter_part_* objects
9707 for partitions in table after ALTER TABLE
9708 @return false On success
9709 @retval true On Failure */
9710 bool alter_part_factory::create_for_non_reorg(alter_part_array &to_drop,
9711 alter_part_array &all_news) {
9712 ut_ad((m_ha_alter_info->handler_flags &
9713 Alter_inplace_info::REORGANIZE_PARTITION) == 0);
9714
9715 partition_info *part_info = m_ha_alter_info->modified_part_info;
9716 uint parts_per_part =
9717 part_info->is_sub_partitioned() ? part_info->num_subparts : 1;
9718 List_iterator_fast<partition_element> part_it(part_info->partitions);
9719 partition_element *part_elem;
9720 uint old_part_id = 0;
9721 uint new_part_id = 0;
9722
9723 while ((part_elem = part_it++) != nullptr) {
9724 partition_state state = part_elem->part_state;
9725 switch (state) {
9726 case PART_NORMAL:
9727 case PART_CHANGED:
9728 if (create_one(all_news, part_elem, new_part_id, old_part_id, state,
9729 false)) {
9730 return (true);
9731 }
9732
9733 old_part_id += parts_per_part;
9734 break;
9735 case PART_TO_BE_ADDED:
9736 if (create_one(all_news, part_elem, new_part_id, 0, state, false)) {
9737 return (true);
9738 }
9739
9740 break;
9741 case PART_TO_BE_DROPPED:
9742 case PART_REORGED_DROPPED:
9743 if (create_one(to_drop, part_elem, old_part_id, old_part_id, state,
9744 false)) {
9745 return (true);
9746 }
9747
9748 break;
9749 default:
9750 ut_d(ut_error);
9751 }
9752 }
9753
9754 return (false);
9755 }
9756
9757 #ifndef NDEBUG
9758 /** Check if the specified partition_state is of drop state
9759 @param[in] s The state to be checked
9760 @retval true if this is of a drop state
9761 @retval false if not */
9762 inline static bool is_drop_state(partition_state s) {
9763 return (s == PART_TO_BE_DROPPED || s == PART_REORGED_DROPPED ||
9764 s == PART_TO_BE_REORGED);
9765 }
9766 #endif
9767
9768 /** Check if the specified partition_state is of common state
9769 @param[in] s The state to be checked
9770 @retval true if this is of a common state
9771 @retval false if not */
9772 inline static bool is_common_state(partition_state s) {
9773 return (s == PART_NORMAL || s == PART_CHANGED);
9774 }
9775
9776 /** Destructor */
9777 alter_parts::~alter_parts() {
9778 for (alter_part *alter_part : m_news) {
9779 ut::delete_(alter_part);
9780 }
9781
9782 for (alter_part *alter_part : m_to_drop) {
9783 ut::delete_(alter_part);
9784 }
9785 }
9786
9787 /** Create the to be created partitions and update internal
9788 structures with concurrent writes blocked, while preparing
9789 ALTER TABLE.
9790 @param[in] old_dd_tab dd::Table before ALTER TABLE
9791 @param[in,out] new_dd_tab dd::Table after ALTER TABLE
9792 @param[in,out] altered_table Table definition after the ALTER
9793 @return 0 or error number, my_error() should be called by callers */
9794 int alter_parts::prepare(const dd::Table &old_dd_tab, dd::Table &new_dd_tab,
9795 TABLE *altered_table) {
9796 if (m_factory.create(m_to_drop, m_news)) {
9797 return (true);
9798 }
9799
9800 if (m_part_share->get_table_share()->found_next_number_field) {
9801 dd_set_autoinc(new_dd_tab.se_private_data(),
9802 m_ha_alter_info->create_info->auto_increment_value);
9803 }
9804
9805 int error;
9806 error = prepare_or_commit_for_old(old_dd_tab, altered_table, true);
9807 if (error != 0) {
9808 return (error);
9809 }
9810
9811 error =
9812 prepare_or_commit_for_new(old_dd_tab, new_dd_tab, altered_table, true);
9813
9814 /* We don't have to prepare for the partitions that will be dropped. */
9815
9816 return (error);
9817 }
9818
9819 /** Notify the storage engine that the changes made during
9820 prepare_inplace_alter_table() and inplace_alter_table()
9821 will be rolled back for all the partitions. */
9822 void alter_parts::rollback() {
9823 for (alter_part *alter_part : m_to_drop) {
9824 alter_part->rollback();
9825 }
9826
9827 for (alter_part *alter_part : m_news) {
9828 alter_part->rollback();
9829 }
9830 }
9831
9832 /** Try to commit the changes made during prepare_inplace_alter_table()
9833 inside the storage engine. This is protected by MDL_EXCLUSIVE.
9834 @param[in] old_dd_tab dd::Table before ALTER TABLE
9835 @param[in,out] new_dd_tab dd::Table after ALTER TABLE
9836 @param[in] table Table definition before the ALTER
9837 @param[in,out] altered_table Table definition after the ALTER
9838 @return 0 or error number, my_error() should be called by callers */
9839 int alter_parts::try_commit(const dd::Table &old_dd_tab, dd::Table &new_dd_tab,
9840 const TABLE *table [[maybe_unused]],
9841 TABLE *altered_table) {
9842 int error;
9843 /* Commit for the old ones first, to clear data files for new ones */
9844 error = prepare_or_commit_for_old(old_dd_tab, altered_table, false);
9845 if (error != 0) {
9846 return (error);
9847 }
9848
9849 error =
9850 prepare_or_commit_for_new(old_dd_tab, new_dd_tab, altered_table, false);
9851 if (error != 0) {
9852 return (error);
9853 }
9854
9855 return (0);
9856 }
9857
9858 /** Prepare for all the partitions in table after ALTER TABLE
9859 @param[in] old_dd_tab dd::Table before ALTER TABLE
9860 @param[in,out] new_dd_tab dd::Table after ALTER TABLE
9861 @param[in,out] altered_table Table definition after the ALTER
9862 @param[in] prepare true if it's in prepare phase,
9863 false if it's in commit phase
9864 @return 0 or error number */
9865 int alter_parts::prepare_or_commit_for_new(const dd::Table &old_dd_tab,
9866 dd::Table &new_dd_tab,
9867 TABLE *altered_table, bool prepare) {
9868 auto oldp = old_dd_tab.leaf_partitions().begin();
9869 uint new_part_id = 0;
9870 uint old_part_id = 0;
9871 uint drop_seq = 0;
9872 const dd::Partition *old_part = nullptr;
9873 int error = 0;
9874
9875 for (auto new_part : *new_dd_tab.leaf_partitions()) {
9876 ut_ad(new_part_id < m_news.size());
9877
9878 /* To add a new partition, there is no corresponding old one,
9879 otherwise, find the old one */
9880 partition_state s = m_news[new_part_id]->state();
9881 if (is_common_state(s)) {
9882 bool found = false;
9883 for (; oldp != old_dd_tab.leaf_partitions().end() && !found; ++oldp) {
9884 old_part = *oldp;
9885
9886 ++old_part_id;
9887 if (drop_seq < m_to_drop.size() &&
9888 (old_part_id - 1 == m_to_drop[drop_seq]->part_id())) {
9889 ut_ad(is_drop_state(m_to_drop[drop_seq]->state()));
9890 ++drop_seq;
9891 continue;
9892 }
9893
9894 found = true;
9895 }
9896
9897 ut_ad(found);
9898 ut_ad(drop_seq <= m_to_drop.size());
9899 ut_ad(new_part->name() == old_part->name());
9900 ut_ad((new_part->parent() == nullptr) == (old_part->parent() == nullptr));
9901 ut_ad(new_part->parent() == nullptr ||
9902 new_part->parent()->name() == old_part->parent()->name());
9903 } else {
9904 ut_ad(s == PART_TO_BE_ADDED);
9905 /* Let's still set one to get the old table name */
9906 old_part = *(old_dd_tab.leaf_partitions().begin());
9907 }
9908
9909 alter_part *alter_part = m_news[new_part_id];
9910 ut_ad(alter_part != nullptr);
9911
9912 if (prepare) {
9913 error = alter_part->prepare(altered_table, old_part, new_part);
9914 if (error != 0) {
9915 return (error);
9916 }
9917
9918 if (m_new_partitions != nullptr && alter_part->new_table() != nullptr) {
9919 m_new_partitions->set_part(new_part_id, alter_part->new_table());
9920 }
9921 } else {
9922 error =
9923 alter_part->try_commit(nullptr, altered_table, old_part, new_part);
9924 if (error != 0) {
9925 return (error);
9926 }
9927 }
9928
9929 ++new_part_id;
9930 }
9931
9932 #ifdef UNIV_DEBUG
9933 ut_ad(drop_seq <= m_to_drop.size());
9934 for (uint i = drop_seq; i < m_to_drop.size(); ++i) {
9935 ut_ad(!is_common_state(m_to_drop[i]->state()));
9936 }
9937 #endif /* UNIV_DEBUG */
9938
9939 return (error);
9940 }
9941
9942 /** Prepare or commit for all the partitions in table before ALTER TABLE
9943 @param[in] old_dd_tab dd::Table before ALTER TABLE
9944 @param[in,out] altered_table Table definition after the ALTER
9945 @param[in] prepare true if it's in prepare phase,
9946 false if it's in commit phase
9947 @return 0 or error number */
9948 int alter_parts::prepare_or_commit_for_old(const dd::Table &old_dd_tab,
9949 TABLE *altered_table, bool prepare) {
9950 uint old_part_id = 0;
9951 auto dd_part = old_dd_tab.leaf_partitions().begin();
9952 int error = 0;
9953
9954 for (alter_part *alter_part : m_to_drop) {
9955 const dd::Partition *old_part = nullptr;
9956
9957 for (; dd_part != old_dd_tab.leaf_partitions().end(); ++dd_part) {
9958 if (old_part_id++ < alter_part->part_id()) {
9959 continue;
9960 }
9961
9962 old_part = *dd_part;
9963 ++dd_part;
9964 break;
9965 }
9966 ut_ad(old_part != nullptr);
9967
9968 if (prepare) {
9969 error = alter_part->prepare(altered_table, old_part, nullptr);
9970 } else {
9971 error = alter_part->try_commit(nullptr, altered_table, old_part, nullptr);
9972 }
9973
9974 if (error != 0) {
9975 return (error);
9976 }
9977 }
9978
9979 return (error);
9980 }
9981
9982 /** Determine if one ALTER TABLE can be done instantly on the partitioned table
9983 @param[in] ha_alter_info the DDL operation
9984 @param[in] num_parts number of partitions
9985 @param[in] part_share the partitioned tables
9986 @param[in] old_table old TABLE
9987 @param[in] altered_table new TABLE
9988 @return Instant_Type accordingly */
9989 static inline Instant_Type innopart_support_instant(
9990 const Alter_inplace_info *ha_alter_info, uint16_t num_parts,
9991 const Ha_innopart_share *part_share, const TABLE *old_table,
9992 const TABLE *altered_table) {
9993 Instant_Type type = Instant_Type::INSTANT_IMPOSSIBLE;
9994
9995 for (uint32_t i = 0; i < num_parts; ++i) {
9996 type = innobase_support_instant(
9997 ha_alter_info, part_share->get_table_part(i), old_table, altered_table);
9998 if (type == Instant_Type::INSTANT_IMPOSSIBLE) {
9999 return (type);
10000 }
10001 }
10002
10003 return (type);
10004 }
10005
10006 int ha_innopart::parallel_scan_init(void *&scan_ctx, size_t *num_threads,
10007 bool use_reserved_threads) {
10008 auto max_threads = thd_parallel_read_threads(m_prebuilt->trx->mysql_thd);
10009 ut_a(max_threads <= Parallel_reader::MAX_THREADS);
10010
10011 max_threads = static_cast<ulong>(
10012 Parallel_reader::available_threads(max_threads, use_reserved_threads));
10013
10014 if (max_threads == 0) {
10015 return (HA_ERR_GENERIC);
10016 }
10017
10018 scan_ctx = nullptr;
10019
10020 const auto row_len = m_prebuilt->mysql_row_len;
10021
10022 auto adapter = ut::new_withkey<Parallel_reader_adapter>(
10023 UT_NEW_THIS_FILE_PSI_KEY, max_threads, row_len);
10024
10025 if (adapter == nullptr) {
10026 Parallel_reader::release_threads(max_threads);
10027 return (HA_ERR_OUT_OF_MEM);
10028 }
10029
10030 auto trx = m_prebuilt->trx;
10031
10032 innobase_register_trx(ht, ha_thd(), trx);
10033
10034 trx_start_if_not_started_xa(trx, false, UT_LOCATION_HERE);
10035
10036 trx_assign_read_view(trx);
10037
10038 const Parallel_reader::Scan_range FULL_SCAN{};
10039 const auto first_used_partition = m_part_info->get_first_used_partition();
10040
10041 for (auto i = first_used_partition; i < m_tot_parts;
10042 i = m_part_info->get_next_used_partition(i)) {
10043 set_partition(i);
10044
10045 if (dict_table_is_discarded(m_prebuilt->table)) {
10046 ib_senderrf(ha_thd(), IB_LOG_LEVEL_ERROR, ER_TABLESPACE_DISCARDED,
10047 m_prebuilt->table->name.m_name);
10048
10049 ut::delete_(adapter);
10050 return HA_ERR_NO_SUCH_TABLE;
10051 }
10052
10053 build_template(true);
10054
10055 Parallel_reader::Config config(FULL_SCAN, m_prebuilt->table->first_index(),
10056 0, i);
10057
10058 dberr_t err =
10059 adapter->add_scan(trx, config, [=](const Parallel_reader::Ctx *ctx) {
10060 return (adapter->process_rows(ctx));
10061 });
10062
10063 if (err != DB_SUCCESS) {
10064 ut::delete_(adapter);
10065 return (convert_error_code_to_mysql(err, 0, ha_thd()));
10066 }
10067 }
10068
10069 scan_ctx = adapter;
10070 *num_threads = max_threads;
10071
10072 adapter->set(m_prebuilt);
10073
10074 return (0);
10075 }
10076
10077 int ha_innopart::parallel_scan(void *scan_ctx, void **thread_ctxs,
10078 Parallel_reader_adapter::Init_fn init_fn,
10079 Parallel_reader_adapter::Load_fn load_fn,
10080 Parallel_reader_adapter::End_fn end_fn) {
10081 auto adapter = static_cast<Parallel_reader_adapter *>(scan_ctx);
10082
10083 auto err = adapter->run(thread_ctxs, init_fn, load_fn, end_fn);
10084
10085 return (convert_error_code_to_mysql(err, 0, ha_thd()));
10086 }
10087
10088 void ha_innopart::parallel_scan_end(void *parallel_scan_ctx) {
10089 auto adapter = static_cast<Parallel_reader_adapter *>(parallel_scan_ctx);
10090 ut::delete_(adapter);
10091 }
10092
10093 /** Check if InnoDB supports a particular alter table in-place.
10094 @param[in] altered_table TABLE object for new version of table.
10095 @param[in,out] ha_alter_info Structure describing changes to be done
10096 by ALTER TABLE and holding data used during in-place alter.
10097 @retval HA_ALTER_INPLACE_NOT_SUPPORTED Not supported
10098 @retval HA_ALTER_INPLACE_NO_LOCK Supported
10099 @retval HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE Supported, but
10100 requires lock during main phase and exclusive lock during prepare
10101 phase.
10102 @retval HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE Supported, prepare
10103 phase requires exclusive lock. */
10104 enum_alter_inplace_result ha_innopart::check_if_supported_inplace_alter(
10105 TABLE *altered_table, Alter_inplace_info *ha_alter_info) {
10106 DBUG_TRACE;
10107 assert(ha_alter_info->handler_ctx == nullptr);
10108
10109 /* Not supporting these for partitioned tables yet! */
10110
10111 /*
10112 FK not yet supported. SQL-layer blocks most of such changes.
10113 We resort to COPY algorithm for a few which are still allowed
10114 (e.g. REMOVE PARTITIONING and ADD FOREIGN KEY at the same time).
10115 */
10116 if (ha_alter_info->handler_flags & (Alter_inplace_info::ADD_FOREIGN_KEY |
10117 Alter_inplace_info::DROP_FOREIGN_KEY)) {
10118 ha_alter_info->unsupported_reason =
10119 innobase_get_err_msg(ER_FOREIGN_KEY_ON_PARTITIONED);
10120 return HA_ALTER_INPLACE_NOT_SUPPORTED;
10121 }
10122 /* FTS not yet supported either. */
10123 if ((ha_alter_info->handler_flags & Alter_inplace_info::ADD_INDEX)) {
10124 for (uint i = 0; i < ha_alter_info->index_add_count; i++) {
10125 const KEY *key =
10126 &ha_alter_info->key_info_buffer[ha_alter_info->index_add_buffer[i]];
10127 if (key->flags & HA_FULLTEXT) {
10128 assert(!(key->flags & HA_KEYFLAG_MASK &
10129 ~(HA_FULLTEXT | HA_PACK_KEY | HA_GENERATED_KEY |
10130 HA_BINARY_PACK_KEY)));
10131 ha_alter_info->unsupported_reason =
10132 innobase_get_err_msg(ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING);
10133 return HA_ALTER_INPLACE_NOT_SUPPORTED;
10134 }
10135 }
10136 }
10137 /* We cannot allow INPLACE to change order of KEY partitioning fields! */
10138 if ((ha_alter_info->handler_flags &
10139 Alter_inplace_info::ALTER_STORED_COLUMN_ORDER) &&
10140 !m_part_info->same_key_column_order(
10141 &ha_alter_info->alter_info->create_list)) {
10142 return HA_ALTER_INPLACE_NOT_SUPPORTED;
10143 }
10144
10145 /* Cannot allow INPLACE for drop and create PRIMARY KEY if partition is
10146 on Primary Key - PARTITION BY KEY() */
10147 if ((ha_alter_info->handler_flags & (Alter_inplace_info::ADD_PK_INDEX |
10148 Alter_inplace_info::DROP_PK_INDEX))) {
10149 /* Check partition by key(). */
10150 if ((m_part_info->part_type == partition_type::HASH) &&
10151 m_part_info->list_of_part_fields &&
10152 m_part_info->part_field_list.is_empty()) {
10153 return HA_ALTER_INPLACE_NOT_SUPPORTED;
10154 }
10155
10156 /* Check sub-partition by key(). */
10157 if ((m_part_info->subpart_type == partition_type::HASH) &&
10158 m_part_info->list_of_subpart_fields &&
10159 m_part_info->subpart_field_list.is_empty()) {
10160 return HA_ALTER_INPLACE_NOT_SUPPORTED;
10161 }
10162 }
10163
10164 /* Check for ALTER TABLE ... PARTITION, following operations can
10165 be done inplace */
10166 if (alter_parts::apply_to(ha_alter_info)) {
10167 /* Two meanings here:
10168 1. ALTER TABLE .. PARTITION could not be combined with
10169 other ALTER TABLE operations;
10170 2. Only one operation of ALTER TABLE .. PARTITION can be
10171 done in single statement. Only exception is that
10172 'ALTER TABLE table REORGANIZE PARTITION' for HASH/KEY
10173 partitions. This will flag both COALESCE_PARTITION
10174 and ALTER_TABLE_REORG;
10175 The ALTER_ALL_PARTITION should be screened out, which could only
10176 be set along with the REBUILD PARTITION */
10177 ut_ad(is_single_bit(ha_alter_info->handler_flags &
10178 ~Alter_inplace_info::ALTER_ALL_PARTITION) ||
10179 ha_alter_info->handler_flags ==
10180 (Alter_inplace_info::COALESCE_PARTITION |
10181 Alter_inplace_info::ALTER_TABLE_REORG));
10182 ut_ad(!(ha_alter_info->handler_flags &
10183 Alter_inplace_info::ALTER_ALL_PARTITION) ||
10184 (ha_alter_info->handler_flags &
10185 Alter_inplace_info::ALTER_REBUILD_PARTITION));
10186
10187 if (alter_parts::need_copy(ha_alter_info)) {
10188 return HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE;
10189 } else {
10190 return HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE;
10191 }
10192 }
10193
10194 Instant_Type instant_type = innopart_support_instant(
10195 ha_alter_info, m_tot_parts, m_part_share, this->table, altered_table);
10196
10197 ha_alter_info->handler_trivial_ctx =
10198 instant_type_to_int(Instant_Type::INSTANT_IMPOSSIBLE);
10199
10200 const bool is_instant_requested =
10201 ha_alter_info->alter_info->requested_algorithm ==
10202 Alter_info::ALTER_TABLE_ALGORITHM_INSTANT;
10203
10204 switch (instant_type) {
10205 case Instant_Type::INSTANT_IMPOSSIBLE:
10206 break;
10207 case Instant_Type::INSTANT_ADD_DROP_COLUMN:
10208 if (ha_alter_info->alter_info->requested_algorithm ==
10209 Alter_info::ALTER_TABLE_ALGORITHM_INPLACE) {
10210 break;
10211 } else if (!((m_prebuilt->table->n_def +
10212 get_num_cols_added(ha_alter_info)) <=
10213 REC_MAX_N_USER_FIELDS + DATA_N_SYS_COLS)) {
10214 if (is_instant_requested) {
10215 /* Following is the case when no more columns can be added to the
10216 table becuase it has reached maximum allowed user columns */
10217 if (altered_table->s->fields > REC_MAX_N_USER_FIELDS) {
10218 ha_alter_info->unsupported_reason =
10219 innobase_get_err_msg(ER_TOO_MANY_FIELDS);
10220 return HA_ALTER_INPLACE_NOT_SUPPORTED;
10221 }
10222
10223 /* In followin case, columns can't be added with INSTANT but if tried
10224 with INPLACE/COPY, it is possible to add more columns */
10225 my_error(ER_INNODB_INSTANT_ADD_NOT_SUPPORTED_MAX_FIELDS, MYF(0),
10226 m_prebuilt->table->name.m_name);
10227 return HA_ALTER_ERROR;
10228 }
10229 /* INSTANT can't be done any more. Fall back to INPLACE. */
10230 break;
10231 } else if (!is_valid_row_version(m_prebuilt->table->current_row_version +
10232 1)) {
10233 ut_ad(is_valid_row_version(m_prebuilt->table->current_row_version));
10234
10235 if (is_instant_requested) {
10236 my_error(ER_INNODB_MAX_ROW_VERSION, MYF(0),
10237 m_prebuilt->table->name.m_name);
10238 return HA_ALTER_ERROR;
10239 }
10240 /* INSTANT can't be done any more. Fall back to INPLACE. */
10241 break;
10242 } else if (!Instant_ddl_impl<dd::Table>::is_instant_add_drop_possible(
10243 ha_alter_info, table, altered_table, m_prebuilt->table)) {
10244 if (is_instant_requested) {
10245 /* Return error if either max possible row size already crosses max
10246 permissible row size or may cross it after add. */
10247 my_error(ER_INNODB_INSTANT_ADD_DROP_NOT_SUPPORTED_MAX_SIZE, MYF(0));
10248 return HA_ALTER_ERROR;
10249 }
10250
10251 /* INSTANT can't be done. Fall back to INPLACE. */
10252 break;
10253 } else if (ha_alter_info->error_if_not_empty) {
10254 /* In this case, it can't be instant because the table
10255 may not be empty. Have to fall back to INPLACE */
10256 break;
10257 }
10258 [[fallthrough]];
10259 case Instant_Type::INSTANT_NO_CHANGE:
10260 case Instant_Type::INSTANT_VIRTUAL_ONLY:
10261 case Instant_Type::INSTANT_COLUMN_RENAME:
10262 if (altered_table->s->fields > REC_MAX_N_USER_FIELDS) {
10263 /* Deny the inplace ALTER TABLE. MySQL will try to
10264 re-create the table and ha_innobase::create() will
10265 return an error too. This is how we effectively
10266 deny adding too many columns to a table. */
10267 ha_alter_info->unsupported_reason =
10268 innobase_get_err_msg(ER_TOO_MANY_FIELDS);
10269 return HA_ALTER_INPLACE_NOT_SUPPORTED;
10270 }
10271
10272 ha_alter_info->handler_trivial_ctx = instant_type_to_int(instant_type);
10273 return HA_ALTER_INPLACE_INSTANT;
10274 }
10275
10276 /* Check for PK and UNIQUE should already be done when creating the
10277 new table metadata.
10278 (fix_partition_info/check_primary_key+check_unique_key) */
10279
10280 set_partition(0);
10281 return ha_innobase::check_if_supported_inplace_alter(altered_table,
10282 ha_alter_info);
10283 }
10284
10285 /** Prepare in-place ALTER for table.
10286 Allows InnoDB to update internal structures with concurrent
10287 writes blocked (provided that check_if_supported_inplace_alter()
10288 did not return HA_ALTER_INPLACE_NO_LOCK).
10289 This will be invoked before inplace_alter_table().
10290 @param[in] altered_table TABLE object for new version of table.
10291 @param[in,out] ha_alter_info Structure describing changes to be done
10292 by ALTER TABLE and holding data used during in-place alter.
10293 @param[in] old_table_def dd::Table object describing old
10294 version of the table.
10295 @param[in,out] new_table_def dd::Table object for the new version
10296 of the table. Can be adjusted by this call. Changes to the table
10297 definition will be persisted in the data-dictionary at statement
10298 commit time.
10299 @retval true Failure.
10300 @retval false Success. */
10301 bool ha_innopart::prepare_inplace_alter_table(TABLE *altered_table,
10302 Alter_inplace_info *ha_alter_info,
10303 const dd::Table *old_table_def,
10304 dd::Table *new_table_def) {
10305 DBUG_TRACE;
10306 assert(ha_alter_info->handler_ctx == nullptr);
10307
10308 if (tablespace_is_shared_space(ha_alter_info->create_info)) {
10309 my_printf_error(ER_ILLEGAL_HA_CREATE_OPTION, PARTITION_IN_SHARED_TABLESPACE,
10310 MYF(0));
10311 return true;
10312 }
10313
10314 /* The row format in new table may differ from the old one,
10315 which is set by server earlier. So keep them the same */
10316 new_table_def->set_row_format(old_table_def->row_format());
10317
10318 if (altered_table->found_next_number_field != nullptr) {
10319 dd_copy_autoinc(old_table_def->se_private_data(),
10320 new_table_def->se_private_data());
10321 }
10322
10323 if (alter_parts::apply_to(ha_alter_info)) {
10324 return prepare_inplace_alter_partition(altered_table, ha_alter_info,
10325 old_table_def, new_table_def);
10326 }
10327
10328 ha_innopart_inplace_ctx *ctx_parts;
10329 THD *thd = ha_thd();
10330 bool res = true;
10331
10332 /* Clean up all ins/upd nodes. */
10333 clear_ins_upd_nodes();
10334 /*
10335 This object will be freed by server, so always use 'new'
10336 and there is no need to free on failure */
10337 ctx_parts = new (thd->mem_root) ha_innopart_inplace_ctx(m_tot_parts);
10338 if (ctx_parts == nullptr) {
10339 return HA_ALTER_ERROR;
10340 }
10341
10342 ctx_parts->ctx_array = ut::new_arr_withkey<inplace_alter_handler_ctx *>(
10343 UT_NEW_THIS_FILE_PSI_KEY, ut::Count{m_tot_parts + 1});
10344 if (ctx_parts->ctx_array == nullptr) {
10345 return HA_ALTER_ERROR;
10346 }
10347
10348 memset(ctx_parts->ctx_array, 0,
10349 sizeof(inplace_alter_handler_ctx *) * (m_tot_parts + 1));
10350
10351 ctx_parts->m_old_info = ut::new_arr_withkey<alter_table_old_info_t>(
10352 UT_NEW_THIS_FILE_PSI_KEY, ut::Count{m_tot_parts});
10353 if (ctx_parts->m_old_info == nullptr) {
10354 return HA_ALTER_ERROR;
10355 }
10356
10357 ctx_parts->prebuilt_array = ut::new_arr_withkey<row_prebuilt_t *>(
10358 UT_NEW_THIS_FILE_PSI_KEY, ut::Count{m_tot_parts});
10359 if (ctx_parts->prebuilt_array == nullptr) {
10360 return HA_ALTER_ERROR;
10361 }
10362 /* For the first partition use the current prebuilt. */
10363 ctx_parts->prebuilt_array[0] = m_prebuilt;
10364 /* Create new prebuilt for the rest of the partitions.
10365 It is needed for the current implementation of
10366 ha_innobase::commit_inplace_alter_table(). */
10367 for (uint i = 1; i < m_tot_parts; i++) {
10368 row_prebuilt_t *tmp_prebuilt;
10369 tmp_prebuilt = row_create_prebuilt(m_part_share->get_table_part(i),
10370 table_share->reclength);
10371 /* Use same trx as original prebuilt. */
10372 tmp_prebuilt->trx = m_prebuilt->trx;
10373 ctx_parts->prebuilt_array[i] = tmp_prebuilt;
10374 }
10375
10376 if (altered_table->found_next_number_field != nullptr) {
10377 dd_set_autoinc(new_table_def->se_private_data(),
10378 ha_alter_info->create_info->auto_increment_value);
10379 }
10380
10381 const char *save_tablespace = ha_alter_info->create_info->tablespace;
10382
10383 const char *save_data_file_name = ha_alter_info->create_info->data_file_name;
10384
10385 auto oldp = old_table_def->leaf_partitions().begin();
10386 auto newp = new_table_def->leaf_partitions()->begin();
10387
10388 for (uint i = 0; i < m_tot_parts; ++oldp, ++newp) {
10389 m_prebuilt = ctx_parts->prebuilt_array[i];
10390 set_partition(i);
10391
10392 const dd::Partition *old_part = *oldp;
10393 dd::Partition *new_part = *newp;
10394 ut_ad(old_part != nullptr);
10395 ut_ad(new_part != nullptr);
10396 ut_ad(m_prebuilt->table->id == old_part->se_private_id());
10397
10398 ha_alter_info->handler_ctx = nullptr;
10399
10400 /* Set the tablespace and data_file_name value of the
10401 alter_info to the tablespace and data_file_name value
10402 that was existing for the partition originally, so that
10403 for ALTER TABLE the tablespace clause in create option
10404 is ignored for existing partitions, and later set it
10405 back to its old value */
10406
10407 ha_alter_info->create_info->tablespace = m_prebuilt->table->tablespace;
10408 ha_alter_info->create_info->data_file_name =
10409 m_prebuilt->table->data_dir_path;
10410
10411 res = prepare_inplace_alter_table_impl<dd::Partition>(
10412 altered_table, ha_alter_info, old_part, new_part);
10413
10414 update_partition(i);
10415 ctx_parts->ctx_array[i] = ha_alter_info->handler_ctx;
10416 if (res) {
10417 break;
10418 }
10419
10420 ha_innobase_inplace_ctx *ctx =
10421 static_cast<ha_innobase_inplace_ctx *>(ctx_parts->ctx_array[i]);
10422 if (ctx != nullptr) {
10423 ctx_parts->m_old_info[i].update(ctx->old_table, ctx->need_rebuild());
10424 }
10425
10426 ++i;
10427 }
10428
10429 m_prebuilt = ctx_parts->prebuilt_array[0];
10430 ha_alter_info->handler_ctx = ctx_parts;
10431 ha_alter_info->group_commit_ctx = ctx_parts->ctx_array;
10432 ha_alter_info->create_info->tablespace = save_tablespace;
10433 ha_alter_info->create_info->data_file_name = save_data_file_name;
10434
10435 return res;
10436 }
10437
10438 bool ha_innopart::inplace_alter_table(TABLE *altered_table,
10439 Alter_inplace_info *ha_alter_info,
10440 const dd::Table *old_table_def,
10441 dd::Table *new_table_def) {
10442 if (alter_parts::apply_to(ha_alter_info)) {
10443 return (inplace_alter_partition(ha_alter_info));
10444 }
10445
10446 bool res = true;
10447 ha_innopart_inplace_ctx *ctx_parts;
10448
10449 ctx_parts =
10450 static_cast<ha_innopart_inplace_ctx *>(ha_alter_info->handler_ctx);
10451
10452 /* It could be not allocated at all */
10453 if (ctx_parts == nullptr) {
10454 return (false);
10455 }
10456
10457 auto oldp = old_table_def->leaf_partitions().begin();
10458 auto newp = new_table_def->leaf_partitions()->begin();
10459
10460 for (uint i = 0; i < m_tot_parts; ++oldp, ++newp) {
10461 m_prebuilt = ctx_parts->prebuilt_array[i];
10462 ha_alter_info->handler_ctx = ctx_parts->ctx_array[i];
10463 set_partition(i);
10464 if (i != 0 && ha_alter_info->handler_ctx != nullptr) {
10465 ha_alter_info->handler_ctx->set_shared_data(ctx_parts->ctx_array[i - 1]);
10466 }
10467
10468 res = inplace_alter_table_impl<dd::Partition>(altered_table, ha_alter_info);
10469 ut_ad(ctx_parts->ctx_array[i] == ha_alter_info->handler_ctx);
10470 ctx_parts->ctx_array[i] = ha_alter_info->handler_ctx;
10471
10472 if (res) {
10473 break;
10474 }
10475
10476 ++i;
10477 }
10478 m_prebuilt = ctx_parts->prebuilt_array[0];
10479 ha_alter_info->handler_ctx = ctx_parts;
10480 return (res);
10481 }
10482
10483 /** Commit or rollback.
10484 Commit or rollback the changes made during
10485 prepare_inplace_alter_table() and inplace_alter_table() inside
10486 the storage engine. Note that the allowed level of concurrency
10487 during this operation will be the same as for
10488 inplace_alter_table() and thus might be higher than during
10489 prepare_inplace_alter_table(). (E.g concurrent writes were
10490 blocked during prepare, but might not be during commit).
10491 @param[in] altered_table TABLE object for new version of table.
10492 @param[in,out] ha_alter_info Structure describing changes to be done
10493 by ALTER TABLE and holding data used during
10494 in-place alter.
10495 @param[in] commit true => Commit, false => Rollback.
10496 @param[in] old_table_def dd::Table object describing old
10497 version of the table.
10498 @param[in,out] new_table_def dd::Table object for the new version
10499 of the table. Can be adjusted by this call. Changes to the table
10500 definition will be persisted in the data-dictionary at statement
10501 commit time.
10502 @retval true Failure.
10503 @retval false Success. */
10504 bool ha_innopart::commit_inplace_alter_table(TABLE *altered_table,
10505 Alter_inplace_info *ha_alter_info,
10506 bool commit,
10507 const dd::Table *old_table_def,
10508 dd::Table *new_table_def) {
10509 if (alter_parts::apply_to(ha_alter_info)) {
10510 return (commit_inplace_alter_partition(altered_table, ha_alter_info, commit,
10511 old_table_def, new_table_def));
10512 }
10513
10514 ha_innopart_inplace_ctx *ctx_parts =
10515 static_cast<ha_innopart_inplace_ctx *>(ha_alter_info->handler_ctx);
10516
10517 /* It could be not allocated at all */
10518 if (ctx_parts == nullptr) {
10519 return (false);
10520 }
10521
10522 bool res = false;
10523 ut_ad(ctx_parts->ctx_array != nullptr);
10524 ut_ad(ctx_parts->prebuilt_array != nullptr);
10525 ut_ad(ctx_parts->prebuilt_array[0] == m_prebuilt);
10526
10527 if (commit) {
10528 /* Commit is done through first partition (group commit). */
10529 ut_ad(ha_alter_info->group_commit_ctx == ctx_parts->ctx_array);
10530 ha_alter_info->handler_ctx = ctx_parts->ctx_array[0];
10531 set_partition(0);
10532
10533 res = ha_innobase::commit_inplace_alter_table_impl<dd::Table>(
10534 altered_table, ha_alter_info, commit, new_table_def);
10535 ut_ad(res || !ha_alter_info->group_commit_ctx);
10536
10537 goto end;
10538 }
10539
10540 /* Rollback is done for each partition. */
10541 for (uint i = 0; i < m_tot_parts; i++) {
10542 m_prebuilt = ctx_parts->prebuilt_array[i];
10543 ha_alter_info->handler_ctx = ctx_parts->ctx_array[i];
10544 set_partition(i);
10545 if (ha_innobase::commit_inplace_alter_table_impl<dd::Table>(
10546 altered_table, ha_alter_info, commit, new_table_def)) {
10547 res = true;
10548 }
10549 ut_ad(ctx_parts->ctx_array[i] == ha_alter_info->handler_ctx);
10550 ctx_parts->ctx_array[i] = ha_alter_info->handler_ctx;
10551 }
10552 end:
10553 /* All are done successfully, now write back metadata to DD */
10554 if (commit && !res) {
10555 ut_ad(!(is_instant(ha_alter_info) && ctx_parts->m_old_info[0].m_rebuild));
10556
10557 auto oldp = old_table_def->leaf_partitions().begin();
10558 auto newp = new_table_def->leaf_partitions()->begin();
10559 bool inplace_instant = false;
10560
10561 for (uint i = 0; i < m_tot_parts; ++oldp, ++newp) {
10562 const dd::Partition *old_part = *oldp;
10563 dd::Partition *new_part = *newp;
10564 ut_ad(old_part != nullptr);
10565 ut_ad(new_part != nullptr);
10566
10567 ha_innobase_inplace_ctx *ctx =
10568 static_cast<ha_innobase_inplace_ctx *>(ctx_parts->ctx_array[i]);
10569
10570 if (is_instant(ha_alter_info)) {
10571 Instant_ddl_impl<dd::Partition> executor(
10572 ha_alter_info, m_user_thd, m_prebuilt->trx,
10573 m_part_share->get_table_part(i), table, altered_table, old_part,
10574 new_part,
10575 altered_table->found_next_number_field != nullptr
10576 ? reinterpret_cast<uint64_t *>(&m_part_share->next_auto_inc_val)
10577 : nullptr);
10578
10579 /* Execute Instant DDL */
10580 if (executor.commit_instant_ddl()) return true;
10581 } else if (!(ha_alter_info->handler_flags & ~INNOBASE_INPLACE_IGNORE) ||
10582 ctx == nullptr) {
10583 dd_commit_inplace_no_change(ha_alter_info, old_part, new_part, true);
10584 } else {
10585 inplace_instant = !ctx_parts->m_old_info[0].m_rebuild;
10586
10587 /* Table is not rebuilt so copy instant metadata.
10588 NOTE : To be done only for first partition */
10589 if (i == 0 && inplace_instant) {
10590 dd_inplace_alter_copy_instant_metadata(
10591 ha_alter_info, &old_part->table(),
10592 const_cast<dd::Table *>(&new_part->table()));
10593 }
10594
10595 dd_commit_inplace_alter_table(ctx_parts->m_old_info[i], ctx->new_table,
10596 old_part, new_part);
10597 }
10598
10599 ++i;
10600 }
10601
10602 /* In earlier implementaion, each partition has INSTANT metadata. */
10603 if (inplace_instant) {
10604 dd_commit_inplace_update_partition_instant_meta(
10605 m_part_share, m_tot_parts, old_table_def, new_table_def);
10606 }
10607
10608 #ifdef UNIV_DEBUG
10609 if (!res) {
10610 if (dd_table_has_instant_cols(*old_table_def) &&
10611 !ctx_parts->m_old_info[0].m_rebuild) {
10612 ut_ad(dd_table_has_instant_cols(*new_table_def));
10613 }
10614
10615 uint i = 0;
10616 for (auto part : *new_table_def->leaf_partitions()) {
10617 ha_innobase_inplace_ctx *ctx =
10618 static_cast<ha_innobase_inplace_ctx *>(ctx_parts->ctx_array[i++]);
10619 if (ctx != nullptr) {
10620 ut_ad(dd_table_match(ctx->new_table, part));
10621 }
10622 }
10623 }
10624 #endif /* univ_debug */
10625 }
10626
10627 /* Move the ownership of the new tables back to the m_part_share. */
10628 ha_innobase_inplace_ctx *ctx;
10629 for (uint i = 0; i < m_tot_parts; i++) {
10630 /* TODO: Fix to only use one prebuilt (i.e. make inplace
10631 alter partition aware instead of using multiple prebuilt
10632 copies... */
10633 ctx = static_cast<ha_innobase_inplace_ctx *>(ctx_parts->ctx_array[i]);
10634 if (ctx != nullptr) {
10635 m_part_share->set_table_part(i, ctx->prebuilt->table);
10636 ctx->prebuilt->table = nullptr;
10637 ctx_parts->prebuilt_array[i] = ctx->prebuilt;
10638 } else {
10639 break;
10640 }
10641 }
10642 /* The above juggling of prebuilt must be reset here. */
10643 m_prebuilt = ctx_parts->prebuilt_array[0];
10644 m_prebuilt->table = m_part_share->get_table_part(0);
10645 ha_alter_info->handler_ctx = ctx_parts;
10646 return (res);
10647 }
10648
10649 /** Create the Altered_partitoins object
10650 @param[in] ha_alter_info thd DDL operation
10651 @retval true On failure
10652 @retval false On success */
10653 bool ha_innopart::prepare_for_copy_partitions(
10654 Alter_inplace_info *ha_alter_info) {
10655 ut_ad(m_new_partitions == nullptr);
10656 ut_ad(alter_parts::need_copy(ha_alter_info));
10657
10658 uint num_parts = ha_alter_info->modified_part_info->num_parts;
10659 uint total_parts = num_parts;
10660
10661 if (ha_alter_info->modified_part_info->is_sub_partitioned()) {
10662 total_parts *= ha_alter_info->modified_part_info->num_subparts;
10663 }
10664
10665 m_new_partitions = ut::new_withkey<Altered_partitions>(
10666 ut::make_psi_memory_key(mem_key_partitioning), total_parts);
10667
10668 if (m_new_partitions == nullptr) {
10669 return (true);
10670 } else if (m_new_partitions->initialize()) {
10671 ut::delete_(m_new_partitions);
10672 m_new_partitions = nullptr;
10673 return (true);
10674 }
10675
10676 return (false);
10677 }
10678
10679 /** write row to new partition.
10680 @param[in] new_part New partition to write to.
10681 @return 0 for success else error code. */
10682 int ha_innopart::write_row_in_new_part(uint new_part) {
10683 int result;
10684 DBUG_TRACE;
10685
10686 m_last_part = new_part;
10687 if (m_new_partitions->part(new_part) == nullptr) {
10688 /* Altered partition contains misplaced row. */
10689 m_err_rec = table->record[0];
10690 return HA_ERR_ROW_IN_WRONG_PARTITION;
10691 }
10692
10693 m_new_partitions->prepare_write(m_prebuilt, new_part);
10694 result = ha_innobase::write_row(table->record[0]);
10695 m_new_partitions->finish_write(m_prebuilt, new_part);
10696 return result;
10697 }
10698
10699 /** Allows InnoDB to update internal structures with concurrent
10700 writes blocked (given that check_if_supported_inplace_alter()
10701 did not return HA_ALTER_INPLACE_NO_LOCK).
10702 This is for 'ALTER TABLE ... PARTITION' and a corresponding function
10703 to inplace_alter_table().
10704 This will be invoked before inplace_alter_partition().
10705
10706 @param[in,out] altered_table TABLE object for new version of table
10707 @param[in,out] ha_alter_info Structure describing changes to be done
10708 by ALTER TABLE and holding data used during
10709 in-place alter.
10710 @param[in] old_dd_tab Table definition before the ALTER
10711 @param[in,out] new_dd_tab Table definition after the ALTER
10712 @retval true Failure
10713 @retval false Success */
10714 bool ha_innopart::prepare_inplace_alter_partition(
10715 TABLE *altered_table, Alter_inplace_info *ha_alter_info,
10716 const dd::Table *old_dd_tab, dd::Table *new_dd_tab) {
10717 clear_ins_upd_nodes();
10718
10719 trx_start_if_not_started_xa(m_prebuilt->trx, true, UT_LOCATION_HERE);
10720
10721 if (alter_parts::need_copy(ha_alter_info) &&
10722 prepare_for_copy_partitions(ha_alter_info)) {
10723 my_error(ER_OUT_OF_RESOURCES, MYF(0));
10724 return (true);
10725 }
10726
10727 alter_parts *ctx = ut::new_withkey<alter_parts>(
10728 UT_NEW_THIS_FILE_PSI_KEY, m_prebuilt->trx, m_part_share, ha_alter_info,
10729 m_part_info, m_new_partitions);
10730
10731 if (ctx == nullptr) {
10732 my_error(ER_OUT_OF_RESOURCES, MYF(0));
10733 return (true);
10734 }
10735
10736 ha_alter_info->handler_ctx = ctx;
10737
10738 int error = ctx->prepare(*old_dd_tab, *new_dd_tab, altered_table);
10739 if (error != 0) {
10740 print_error(error, MYF(error != ER_OUTOFMEMORY ? 0 : ME_FATALERROR));
10741 }
10742 return (error);
10743 }
10744
10745 bool ha_innopart::inplace_alter_partition(Alter_inplace_info *ha_alter_info) {
10746 if (!alter_parts::need_copy(ha_alter_info)) {
10747 return (false);
10748 }
10749
10750 /* The lock type can be set as none, since in this step, the
10751 shared table lock is held, thus no other changes. This is to fix
10752 if the table was explicitly lock, then select_lock_type in the
10753 prebuilt here would not be LOCK_NONE, then row locks would be
10754 required; if we finally want to drop the original partitions,
10755 these row locks would lead to failure/crash. */
10756 ulint lock_type = m_prebuilt->select_lock_type;
10757 m_prebuilt->select_lock_type = LOCK_NONE;
10758
10759 prepare_change_partitions();
10760
10761 partition_info *old_part_info = table->part_info;
10762
10763 set_part_info(ha_alter_info->modified_part_info, true);
10764
10765 prepare_change_partitions();
10766
10767 ulonglong deleted;
10768 int res;
10769
10770 res = copy_partitions(&deleted);
10771
10772 set_part_info(old_part_info, false);
10773
10774 m_prebuilt->select_lock_type = lock_type;
10775
10776 if (res > 0) {
10777 print_error(res, MYF(res != ER_OUTOFMEMORY ? 0 : ME_FATALERROR));
10778 }
10779
10780 return (res);
10781 }
10782
10783 /** Prepare to commit or roll back ALTER TABLE...ALGORITHM=INPLACE.
10784 This is for 'ALTER TABLE ... PARTITION' and a corresponding function
10785 to commit_inplace_alter_table().
10786 @param[in,out] altered_table TABLE object for new version of table.
10787 @param[in,out] ha_alter_info ALGORITHM=INPLACE metadata
10788 @param[in] commit true=Commit, false=Rollback.
10789 @param[in] old_dd_tab old table
10790 @param[in,out] new_dd_tab new table
10791 @retval true on failure (my_error() will have been called)
10792 @retval false on success */
10793 bool ha_innopart::commit_inplace_alter_partition(
10794 TABLE *altered_table, Alter_inplace_info *ha_alter_info, bool commit,
10795 const dd::Table *old_dd_tab, dd::Table *new_dd_tab) {
10796 alter_parts *ctx = static_cast<alter_parts *>(ha_alter_info->handler_ctx);
10797 m_prebuilt->table = nullptr;
10798 if (ctx == nullptr) {
10799 ut_ad(!commit);
10800 return (false);
10801 }
10802
10803 if (commit) {
10804 int error = ctx->try_commit(*old_dd_tab, *new_dd_tab, table, altered_table);
10805 if (!error) {
10806 ut::delete_(ctx);
10807 ha_alter_info->handler_ctx = nullptr;
10808
10809 ut::delete_(m_new_partitions);
10810 m_new_partitions = nullptr;
10811
10812 if (altered_table->found_next_number_field) {
10813 dd_set_autoinc(new_dd_tab->se_private_data(),
10814 m_part_share->next_auto_inc_val);
10815 }
10816
10817 dd_copy_table(ha_alter_info, *new_dd_tab, *old_dd_tab);
10818 dd_part_adjust_table_id(new_dd_tab);
10819
10820 if (dd_table_has_instant_cols(*old_dd_tab)) {
10821 dd_inplace_alter_copy_instant_metadata(ha_alter_info, old_dd_tab,
10822 new_dd_tab);
10823 }
10824 }
10825
10826 return (error != 0);
10827 }
10828
10829 ctx->rollback();
10830 ut::delete_(ctx);
10831 ha_alter_info->handler_ctx = nullptr;
10832
10833 ut::delete_(m_new_partitions);
10834 m_new_partitions = nullptr;
10835
10836 return (false);
10837 }
10838
10839 /** Check if the DATA DIRECTORY is specified (implicitly or explicitly)
10840 @param[in] dd_part The dd::Partition to be checked
10841 @retval true the DATA DIRECTORY is specified (implicitly or explicitly)
10842 @retval false otherwise */
10843 static bool dd_part_has_datadir(const dd::Partition *dd_part) {
10844 ut_ad(dd_part_is_stored(dd_part));
10845
10846 return (dd_part->options().exists(data_file_name_key) ||
10847 (dd_part->parent() != nullptr &&
10848 dd_part->parent()->options().exists(data_file_name_key)) ||
10849 dd_part->table().se_private_data().exists(
10850 dd_table_key_strings[DD_TABLE_DATA_DIRECTORY]));
10851 }
10852
10853 /** Adjust data directory for exchange partition. Special handling of
10854 dict_table_t::data_dir_path is necessary if DATA DIRECTORY is specified. For
10855 example if DATA DIRECTORY Is '/tmp', the data directory for normal table is
10856 '/tmp/t1', while for partition is '/tmp'. So rename, the postfix table name 't1'
10857 should either be truncated or appended.
10858 @param[in] table_p partition table
10859 @param[in] table_s swap table*/
10860 void exchange_partition_adjust_datadir(dict_table_t *table_p,
10861 dict_table_t *table_s) {
10862 ut_ad(table_s->n_ref_count == 1);
10863 ut_ad(table_p->n_ref_count == 1);
10864 if (table_s->data_dir_path != nullptr) {
10865 std::string str(table_s->data_dir_path);
10866 /* new_name contains database/name but we require name */
10867 const char *name = strchr(table_s->name.m_name, '/') + 1;
10868 str.append(name);
10869
10870 ulint old_size = mem_heap_get_size(table_s->heap);
10871
10872 table_s->data_dir_path = mem_heap_strdup(table_s->heap, str.c_str());
10873
10874 ulint new_size = mem_heap_get_size(table_s->heap);
10875 dict_sys_mutex_enter();
10876 dict_sys->size += new_size - old_size;
10877 dict_sys_mutex_exit();
10878 }
10879
10880 if (table_p->data_dir_path != nullptr) {
10881 std::string str(table_p->data_dir_path);
10882 size_t found = str.find_last_of("/\\");
10883
10884 ut_ad(found != std::string::npos);
10885 found++;
10886
10887 table_p->data_dir_path[found] = '\0';
10888 }
10889 }
10890
10891 /** Exchange partition.
10892 Low-level primitive which implementation is provided here.
10893 @param[in] part_id The id of the partition to be exchanged
10894 @param[in] part_table partitioned table to be exchanged
10895 @param[in] swap_table table to be exchanged
10896 @return error number
10897 @retval 0 on success */
10898 int ha_innopart::exchange_partition_low(uint part_id, dd::Table *part_table,
10899 dd::Table *swap_table) {
10900 DBUG_TRACE;
10901
10902 ut_ad(part_table != nullptr);
10903 ut_ad(swap_table != nullptr);
10904 ut_ad(m_part_share != nullptr);
10905 ut_ad(dd_table_is_partitioned(*part_table));
10906 ut_ad(!dd_table_is_partitioned(*swap_table));
10907 ut_ad(innobase_strcasecmp(part_table->name().c_str(),
10908 table_share->table_name.str) == 0);
10909 ut_ad(part_id < m_tot_parts);
10910 std::vector<dd::Partition_index *> part_indexes;
10911 std::vector<dd::Partition_index *>::iterator p_iter;
10912 std::vector<dd::Index *> swap_indexes;
10913 std::vector<dd::Index *>::iterator s_iter;
10914 #ifdef UNIV_DEBUG
10915 std::vector<dd::Index *> part_table_indexes;
10916 std::vector<dd::Index *>::iterator pt_iter;
10917 #endif
10918
10919 if (high_level_read_only) {
10920 my_error(ER_READ_ONLY_MODE, MYF(0));
10921 return HA_ERR_TABLE_READONLY;
10922 }
10923
10924 if (dd_table_has_instant_cols(*part_table) ||
10925 dd_table_has_instant_cols(*swap_table)) {
10926 my_error(ER_PARTITION_EXCHANGE_DIFFERENT_OPTION, MYF(0),
10927 "INSTANT COLUMN(s)");
10928 return true;
10929 }
10930
10931 /* Find the specified dd::Partition object */
10932 uint id = 0;
10933 dd::Partition *dd_part = nullptr;
10934 for (auto part : *part_table->leaf_partitions()) {
10935 ut_d(dict_table_t *table = m_part_share->get_table_part(id));
10936 ut_ad(table->n_ref_count == 1);
10937 ut_ad(!table->is_temporary());
10938
10939 if (++id > part_id) {
10940 dd_part = part;
10941 break;
10942 }
10943 }
10944 ut_ad(dd_part != nullptr);
10945
10946 if (dd_part->options().exists(index_file_name_key) ||
10947 swap_table->options().exists(index_file_name_key)) {
10948 my_error(ER_PARTITION_EXCHANGE_DIFFERENT_OPTION, MYF(0), "INDEX DIRECTORY");
10949 ut_d(ut_error);
10950 ut_o(return true);
10951 }
10952
10953 /* Get the innodb table objects of part_table and swap_table */
10954 const table_id_t table_id = swap_table->se_private_id();
10955 dict_table_t *part = m_part_share->get_table_part(part_id);
10956 dict_table_t *swap;
10957 const auto hash_value = ut::hash_uint64(table_id);
10958
10959 dict_sys_mutex_enter();
10960 HASH_SEARCH(id_hash, dict_sys->table_id_hash, hash_value, dict_table_t *,
10961 swap, ut_ad(swap->cached), swap->id == table_id);
10962 dict_sys_mutex_exit();
10963 ut_ad(swap != nullptr);
10964 ut_ad(swap->n_ref_count == 1);
10965
10966 #ifdef UNIV_DEBUG
10967 /* Store and sort part_table indexes */
10968 std::copy(part_table->indexes()->begin(), part_table->indexes()->end(),
10969 std::back_inserter(part_table_indexes));
10970 std::sort(part_table_indexes.begin(), part_table_indexes.end(),
10971 [](dd::Index *a, dd::Index *b) { return (a->name() < b->name()); });
10972 #endif
10973 dd::Object_id p_se_id = dd_part->se_private_id();
10974
10975 /* Try to rename files. Tablespace checking ensures that
10976 both partition and table are of implicit tablespace. The plan is:
10977 1. Rename the swap table to the intermediate file
10978 2. Rename the partition to the swap table file
10979 3. Rename the intermediate file of swap table to the partition file */
10980 THD *thd = m_prebuilt->trx->mysql_thd;
10981 char *swap_name = strdup(swap->name.m_name);
10982 char *part_name = strdup(part->name.m_name);
10983
10984 /* Define the temporary table name, by appending TMP_POSTFIX */
10985 char temp_name[FN_REFLEN];
10986 snprintf(temp_name, sizeof temp_name, "%s%s", swap_name,
10987 dict_name::TMP_POSTFIX);
10988
10989 int error = 0;
10990 error = innobase_basic_ddl::rename_impl<dd::Table>(
10991 thd, swap_name, temp_name, swap_table, swap_table, nullptr);
10992 if (error != 0) {
10993 goto func_exit;
10994 }
10995 error = innobase_basic_ddl::rename_impl<dd::Partition>(
10996 thd, part_name, swap_name, dd_part, dd_part, nullptr);
10997 if (error != 0) {
10998 goto func_exit;
10999 }
11000 error = innobase_basic_ddl::rename_impl<dd::Table>(
11001 thd, temp_name, part_name, swap_table, swap_table, nullptr);
11002 if (error != 0) {
11003 goto func_exit;
11004 }
11005
11006 if (dd_part_has_datadir(dd_part) ||
11007 swap_table->options().exists(data_file_name_key)) {
11008 /* after above swapping swap is now partition table and part is now normal
11009 table */
11010 exchange_partition_adjust_datadir(swap, part);
11011 }
11012
11013 std::copy(dd_part->indexes()->begin(), dd_part->indexes()->end(),
11014 std::back_inserter(part_indexes));
11015 std::copy(swap_table->indexes()->begin(), swap_table->indexes()->end(),
11016 std::back_inserter(swap_indexes));
11017
11018 /* Sort the index pointers according to the index names because the index
11019 ordanility of the partition being exchanged may be different than the
11020 table being swapped */
11021 std::sort(part_indexes.begin(), part_indexes.end(),
11022 [](dd::Partition_index *a, dd::Partition_index *b) {
11023 return (a->name() < b->name());
11024 });
11025 std::sort(swap_indexes.begin(), swap_indexes.end(),
11026 [](dd::Index *a, dd::Index *b) { return (a->name() < b->name()); });
11027
11028 /* Swap the se_private_data and options between indexes.
11029 The se_private_data should be swapped between every index of
11030 dd_part and swap_table; however, options should be swapped(checked)
11031 between part_table and swap_table */
11032 ut_ad(part_indexes.size() == swap_indexes.size());
11033 for (p_iter = part_indexes.begin(), s_iter = swap_indexes.begin();
11034 p_iter < part_indexes.end() && s_iter < swap_indexes.end();
11035 p_iter++, s_iter++) {
11036 auto part_index = *p_iter;
11037 auto swap_index = *s_iter;
11038 dd::Object_id p_tablespace_id = part_index->tablespace_id();
11039 part_index->set_tablespace_id(swap_index->tablespace_id());
11040 swap_index->set_tablespace_id(p_tablespace_id);
11041
11042 ut_ad(part_index->se_private_data().empty() ==
11043 swap_index->se_private_data().empty());
11044 ut_ad(part_index->se_private_data().size() ==
11045 swap_index->se_private_data().size());
11046
11047 if (!part_index->se_private_data().empty()) {
11048 std::unique_ptr<dd::Properties> p_se_data(
11049 dd::Properties::parse_properties(""));
11050 p_se_data->insert_values(part_index->se_private_data());
11051 part_index->se_private_data().clear();
11052 part_index->set_se_private_data(swap_index->se_private_data());
11053 swap_index->se_private_data().clear();
11054 swap_index->set_se_private_data(*p_se_data);
11055 }
11056 }
11057 #ifdef UNIV_DEBUG
11058 for (s_iter = swap_indexes.begin(), pt_iter = part_table_indexes.begin();
11059 s_iter < swap_indexes.end() && pt_iter < part_table_indexes.end();
11060 pt_iter++, s_iter++) {
11061 auto part_table_index = *pt_iter;
11062 auto swap_index = *s_iter;
11063
11064 ut_ad(part_table_index->options().raw_string() ==
11065 swap_index->options().raw_string());
11066 }
11067 #endif
11068
11069 /* Swap the se_private_data and options of the two tables.
11070 Only the max autoinc should be set to both tables */
11071 if (m_part_share->get_table_share()->found_next_number_field) {
11072 uint64_t part_autoinc = part->autoinc;
11073 uint64_t swap_autoinc = swap->autoinc;
11074 uint64_t max_autoinc = std::max(part_autoinc, swap_autoinc);
11075
11076 dd_set_autoinc(swap_table->se_private_data(), max_autoinc);
11077 dd_set_autoinc(
11078 part_table->se_private_data(),
11079 std::max<uint64>(swap_autoinc, m_part_share->next_auto_inc_val));
11080
11081 dict_table_autoinc_lock(part);
11082 dict_table_autoinc_initialize(part, max_autoinc);
11083 dict_table_autoinc_unlock(part);
11084
11085 if (m_part_share->next_auto_inc_val < swap_autoinc) {
11086 lock_auto_increment();
11087 m_part_share->next_auto_inc_val = swap_autoinc;
11088 unlock_auto_increment();
11089 }
11090 }
11091
11092 /* Swap the se_private_id between partition and table */
11093
11094 dd_part->set_se_private_id(swap_table->se_private_id());
11095 swap_table->set_se_private_id(p_se_id);
11096
11097 for (auto dd_column : *swap_table->columns()) {
11098 dd_column->se_private_data().set(dd_index_key_strings[DD_TABLE_ID],
11099 p_se_id);
11100 }
11101
11102 dd_part_adjust_table_id(part_table);
11103
11104 func_exit:
11105 free(swap_name);
11106 free(part_name);
11107
11108 return error;
11109 }