Debian Codegraph @

storage/innobase/ddl/ddl0ctx.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2020, 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 ddl/ddl0ctx.cc
29 DDL context implementation.
30 Created 2020-11-01 by Sunny Bains. */
31
32 #include "btr0load.h"
33 #include "clone0api.h"
34 #include "ddl0fts.h"
35 #include "ddl0impl-builder.h"
36 #include "ddl0impl-cursor.h"
37 #include "ddl0impl-loader.h"
38 #include "ddl0impl-merge.h"
39 #include "dict0dd.h"
40 #include "ha_prototypes.h"
41 #include "handler0alter.h"
42 #include "row0log.h"
43
44 namespace ddl {
45
46 Context::Context(trx_t *trx, dict_table_t *old_table, dict_table_t *new_table,
47 bool online, dict_index_t **indexes, const ulint *key_numbers,
48 size_t n_indexes, TABLE *table, const dtuple_t *add_cols,
49 const ulint *col_map, size_t add_autoinc,
50 ddl::Sequence &sequence, bool skip_pk_sort, Alter_stage *stage,
51 const dict_add_v_col_t *add_v, TABLE *eval_table,
52 size_t max_buffer_size, size_t max_threads) noexcept
53 : m_trx(trx),
54 m_fts(ddl::fts_parser_threads),
55 m_old_table(old_table),
56 m_new_table(new_table),
57 m_online(online),
58 m_table(table),
59 m_add_cols(add_cols),
60 m_col_map(col_map),
61 m_add_autoinc(add_autoinc),
62 m_sequence(sequence),
63 m_stage(stage),
64 m_add_v(add_v),
65 m_eval_table(eval_table),
66 m_skip_pk_sort(skip_pk_sort),
67 m_max_buffer_size(max_buffer_size),
68 m_max_threads(max_threads) {
69 ut_a(max_threads > 0);
70
71 ut_a(!m_online ||
72 trx->isolation_level == trx_t::isolation_level_t::REPEATABLE_READ);
73
74 /* Check if we need a flush observer to flush dirty pages.
75 Since we disable redo logging in bulk load, so we should flush
76 dirty pages before online log apply, because online log apply enables
77 redo logging (we can do further optimization here).
78
79 1. Online add index: flush dirty pages right before row_log_apply().
80 2. Table rebuild: flush dirty pages before row_log_table_apply().
81
82 We use bulk load to create all types of indexes except spatial index,
83 for which redo logging is enabled. If we create only spatial indexes,
84 we don't need to flush dirty pages at all. */
85 m_need_observer = m_old_table != m_new_table;
86
87 for (size_t i = 0; i < n_indexes; ++i) {
88 m_indexes.push_back(indexes[i]);
89
90 if (i == 0) {
91 ut_a(!m_skip_pk_sort || m_indexes.back()->is_clustered());
92 m_n_uniq = dict_index_get_n_unique(m_indexes.back());
93 }
94
95 if (!dict_index_is_spatial(m_indexes.back())) {
96 m_need_observer = true;
97 }
98 m_key_numbers.push_back(key_numbers[i]);
99 }
100
101 ut_a(m_trx->mysql_thd != nullptr);
102 ut_a(m_add_cols == nullptr || m_col_map != nullptr);
103 ut_a((m_old_table == m_new_table) == (m_col_map == nullptr));
104
105 trx_start_if_not_started_xa(m_trx, true, UT_LOCATION_HERE);
106
107 if (m_need_observer) {
108 const auto space_id = m_new_table->space;
109
110 auto observer = ut::new_withkey<Flush_observer>(
111 ut::make_psi_memory_key(mem_key_ddl), space_id, m_trx, m_stage);
112
113 trx_set_flush_observer(m_trx, observer);
114 }
115
116 mutex_create(LATCH_ID_DDL_AUTOINC, &m_autoinc_mutex);
117
118 m_trx->error_key_num = ULINT_UNDEFINED;
119
120 if (m_add_cols != nullptr) {
121 m_dtuple_heap = mem_heap_create(512, UT_LOCATION_HERE);
122 ut_a(m_dtuple_heap != nullptr);
123 }
124 }
125
126 Context::~Context() noexcept {
127 if (m_dtuple_heap != nullptr) {
128 ut_a(m_add_cols != nullptr);
129 mem_heap_free(m_dtuple_heap);
130 }
131 mutex_destroy(&m_autoinc_mutex);
132 }
133
134 Context::FTS::Sequence::~Sequence() noexcept {}
135
136 Flush_observer *Context::flush_observer() noexcept {
137 return m_trx->flush_observer;
138 }
139
140 THD *Context::thd() noexcept {
141 ut_a(m_trx->mysql_thd != nullptr);
142 return m_trx->mysql_thd;
143 }
144
145 const dict_index_t *Context::index() const noexcept {
146 return m_old_table->first_index();
147 }
148
149 Context::Scan_buffer_size Context::scan_buffer_size(
150 size_t n_threads) const noexcept {
151 ut_a(n_threads > 0);
152 auto n_buffers{n_threads};
153
154 /* If there is an FTS index being built, take that into account. */
155 if (m_fts.m_ptr != nullptr) {
156 n_buffers *= FTS_NUM_AUX_INDEX;
157 } else {
158 n_buffers *= m_indexes.size();
159 }
160
161 /* The maximum size of the record is considered to be srv_page_size/2,
162 because one B-tree node should be able to hold at least 2 records. But there
163 is also an i/o alignment requirement of IO_BLOCK_SIZE. This means that the
164 min io buffer size should be the sum of these two. Refer to
165 Key_sort_buffer::serialize() function and its write() lambda function to
166 understand the reasoning behind this. */
167 const auto min_io_size = (srv_page_size / 2) + IO_BLOCK_SIZE;
168
169 /* A single row *must* fit into an IO block. The IO buffer should be
170 greater than the IO physical size buffer makes it easier to handle
171 FS block aligned writes. */
172 const auto io_block_size = IO_BLOCK_SIZE + ((IO_BLOCK_SIZE * 25) / 100);
173 const auto io_size = std::max(size_t(min_io_size), io_block_size);
174
175 Scan_buffer_size size{m_max_buffer_size / n_buffers, io_size};
176
177 if (size.first <= 64 * 1024) {
178 if (size.first < srv_page_size) {
179 size.first = srv_page_size;
180 } else if (size.first >= size.second * 2) {
181 size.first -= size.second;
182 }
183 } else {
184 if (size.first >= 2 * 1024 * 1024) {
185 size.second = 1024 * 1024;
186 } else if (size.first >= 1024 * 1024) {
187 size.second = 512 * 1024;
188 } else if (size.first >= 512 * 1024) {
189 size.second = 128 * 1024;
190 } else if (size.first >= 256 * 1024) {
191 size.second = 64 * 1024;
192 } else {
193 size.second = 32 * 1024;
194 }
195 size.first -= size.second;
196 }
197
198 return size;
199 }
200
201 size_t Context::merge_io_buffer_size(size_t n_buffers) const noexcept {
202 ut_a(n_buffers > 0);
203
204 const auto io_size = load_io_buffer_size(n_buffers);
205
206 /* We aim to do IO_BLOCK_SIZE writes all the time. */
207 ut_a(!(io_size % IO_BLOCK_SIZE));
208
209 /* The buffer must be at least large enough to fit one IO block plus one row.
210 2 * IO_BLOCK_SIZE meets this criterion given limits on key length -
211 see ha_innobase::max_supported_key_length() */
212 return std::max(std::max((ulong)srv_page_size, (ulong)IO_BLOCK_SIZE * 2LU),
213 (ulong)io_size);
214 }
215
216 size_t Context::load_io_buffer_size(size_t n_buffers) const noexcept {
217 ut_a(n_buffers > 0);
218 const auto io_size = m_max_buffer_size / n_buffers;
219
220 return std::max(std::max((ulong)srv_page_size, (ulong)IO_BLOCK_SIZE),
221 (ulong)((io_size / IO_BLOCK_SIZE) * IO_BLOCK_SIZE));
222 }
223
224 bool Context::has_virtual_columns() const noexcept {
225 if (m_add_v != nullptr || dict_index_has_virtual(index())) {
226 return true;
227 }
228
229 /* Find out if there are any virtual coumns defined on the table. */
230 for (size_t i = 0; i < m_table->s->fields; ++i) {
231 if (innobase_is_v_fld(m_table->field[i])) {
232 return true;
233 }
234 }
235
236 return false;
237 }
238
239 dberr_t Context::handle_autoinc(const dtuple_t *dtuple,
240 mem_heap_t *heap) noexcept {
241 ut_ad(m_add_autoinc != ULINT_UNDEFINED);
242 ut_ad(m_add_autoinc < m_new_table->get_n_user_cols());
243
244 const auto dfield = dtuple_get_nth_field(dtuple, m_add_autoinc);
245 /* Perform a deep copy of the field because for spatial indexes,
246 the default tuple allocation is overwritten, as tuples are
247 processed at the end of the page. */
248 dfield_dup(dfield, heap);
249
250 if (dfield_is_null(dfield)) {
251 return DB_SUCCESS;
252 }
253
254 const auto dtype = dfield_get_type(dfield);
255 const auto b = static_cast<byte *>(dfield_get_data(dfield));
256
257 if (m_sequence.eof()) {
258 m_trx->error_key_num = SERVER_CLUSTER_INDEX_ID;
259 return DB_AUTOINC_READ_ERROR;
260 }
261
262 mutex_enter(&m_autoinc_mutex);
263
264 auto value = m_sequence++;
265
266 mutex_exit(&m_autoinc_mutex);
267
268 switch (dtype_get_mtype(dtype)) {
269 case DATA_INT: {
270 auto len = dfield_get_len(dfield);
271 auto usign = dtype_get_prtype(dtype) & DATA_UNSIGNED;
272 mach_write_ulonglong(b, value, len, usign);
273 break;
274 }
275
276 case DATA_FLOAT:
277 mach_float_write(b, static_cast<float>(value));
278 break;
279
280 case DATA_DOUBLE:
281 mach_double_write(b, static_cast<double>(value));
282 break;
283
284 default:
285 ut_d(ut_error);
286 }
287
288 return DB_SUCCESS;
289 }
290
291 dberr_t Context::fts_create(dict_index_t *index) noexcept {
292 /* There can only be one FTS index per table. */
293 ut_a(m_fts.m_ptr == nullptr);
294
295 m_fts.m_ptr = ut::new_withkey<ddl::FTS>(ut::make_psi_memory_key(mem_key_ddl),
296 *this, index, m_old_table);
297
298 if (m_fts.m_ptr != nullptr) {
299 return m_fts.m_ptr->init(m_fts.m_n_parser_threads);
300 } else {
301 return DB_OUT_OF_MEMORY;
302 }
303 }
304
305 dberr_t Context::cleanup(dberr_t err) noexcept {
306 ut_a(err == m_err);
307
308 if (m_err != DB_SUCCESS &&
309 m_err_key_number != std::numeric_limits<size_t>::max()) {
310 m_trx->error_key_num = m_err_key_number;
311 }
312
313 if (m_online && m_old_table == m_new_table && err != DB_SUCCESS) {
314 /* On error, flag all online secondary index creation as aborted. */
315 for (auto index : m_indexes) {
316 ut_a(!index->is_committed());
317 ut_a(!index->is_clustered());
318 ut_a(!(index->type & DICT_FTS));
319
320 /* Completed indexes should be dropped as well, and indexes whose
321 creation was aborted should be dropped from the persistent storage.
322 However, at this point we can only set some flags in the
323 not-yet-published indexes. These indexes will be dropped later in
324 drop_indexes(), called by rollback_inplace_alter_table(). */
325
326 auto latch = dict_index_get_lock(index);
327
328 switch (dict_index_get_online_status(index)) {
329 case ONLINE_INDEX_COMPLETE:
330 break;
331 case ONLINE_INDEX_CREATION:
332 rw_lock_x_lock(latch, UT_LOCATION_HERE);
333 row_log_abort_sec(index);
334 index->type |= DICT_CORRUPT;
335 rw_lock_x_unlock(latch);
336 m_new_table->drop_aborted = true;
337 [[fallthrough]];
338 case ONLINE_INDEX_ABORTED:
339 case ONLINE_INDEX_ABORTED_DROPPED:
340 break;
341 }
342 }
343 }
344
345 DBUG_EXECUTE_IF("ib_index_crash_after_bulk_load", DBUG_SUICIDE(););
346
347 auto observer = m_trx->flush_observer;
348
349 if (observer != nullptr) {
350 ut_a(m_need_observer);
351
352 DBUG_EXECUTE_IF("ib_index_build_fail_before_flush", err = DB_FAIL;);
353
354 if (err != DB_SUCCESS) {
355 observer->interrupted();
356 }
357
358 observer->flush();
359
360 ut::delete_(observer);
361
362 m_trx->flush_observer = nullptr;
363
364 auto space_id = m_new_table != nullptr ? m_new_table->space
365 : dict_sys_t::s_invalid_space_id;
366
367 /* Notify clone after flushing all pages. */
368 Clone_notify notifier(Clone_notify::Type::SPACE_ALTER_INPLACE_BULK,
369 space_id, false);
370
371 if (notifier.failed()) {
372 err = DB_ERROR;
373
374 } else if (is_interrupted()) {
375 err = DB_INTERRUPTED;
376 }
377
378 if (err == DB_SUCCESS) {
379 auto first_index = m_new_table->first_index();
380
381 for (auto index = first_index; index != nullptr; index = index->next()) {
382 if (m_old_table != m_new_table) {
383 Builder::write_redo(index);
384 }
385 }
386 }
387 }
388
389 return err;
390 }
391
392 void Context::setup_nonnull() noexcept {
393 ut_a(m_nonnull.empty());
394
395 if (m_old_table == m_new_table) {
396 return;
397 }
398
399 /* The table is being rebuilt. Identify the columns
400 that were flagged NOT nullptr in the new table, so that
401 we can quickly check that the records in the old table
402 do not violate the added NOT nullptr constraints. */
403
404 for (size_t i = 0; i < m_old_table->get_n_cols(); ++i) {
405 if (m_old_table->get_col(i)->prtype & DATA_NOT_NULL) {
406 continue;
407 }
408
409 const auto col_no = m_col_map[i];
410
411 if (col_no == ULINT_UNDEFINED) {
412 /* The column was dropped. */
413 continue;
414 }
415
416 if (m_new_table->get_col(col_no)->prtype & DATA_NOT_NULL) {
417 m_nonnull.push_back(col_no);
418 }
419 }
420 }
421
422 bool Context::check_null_constraints(const dtuple_t *row) const noexcept {
423 for (const auto i : m_nonnull) {
424 auto field = &row->fields[i];
425
426 ut_ad(dfield_get_type(field)->prtype & DATA_NOT_NULL);
427
428 if (dfield_is_null(field)) {
429 return false;
430 }
431 }
432
433 return true;
434 }
435
436 bool Context::has_fts_indexes() const noexcept {
437 if (dict_table_has_fts_index(m_old_table)) {
438 return true;
439 }
440
441 for (auto index : m_indexes) {
442 if (index->type & DICT_FTS) {
443 return true;
444 }
445 }
446 return false;
447 }
448
449 dberr_t Context::setup_fts_build() noexcept {
450 for (auto index : m_indexes) {
451 if (!(index->type & DICT_FTS)) {
452 continue;
453 }
454
455 /* There can be only one FTS index on a table. */
456 auto err = fts_create(index);
457
458 if (err != DB_SUCCESS) {
459 return err;
460 }
461 }
462
463 return DB_SUCCESS;
464 }
465
466 dberr_t Context::check_state_of_online_build_log() noexcept {
467 if (m_online && m_old_table != m_new_table) {
468 const auto err = row_log_table_get_error(index());
469
470 if (err != DB_SUCCESS) {
471 m_trx->error_key_num = SERVER_CLUSTER_INDEX_ID;
472 return err;
473 }
474 }
475
476 return DB_SUCCESS;
477 }
478
479 void Context::note_max_trx_id(dict_index_t *index) noexcept {
480 if (!m_online || m_new_table != m_old_table) {
481 return;
482 }
483
484 auto rw_latch = dict_index_get_lock(index);
485
486 rw_lock_x_lock(rw_latch, UT_LOCATION_HERE);
487
488 ut_a(dict_index_get_online_status(index) == ONLINE_INDEX_CREATION);
489
490 const auto max_trx_id = row_log_get_max_trx(index);
491
492 if (max_trx_id > index->trx_id) {
493 index->trx_id = max_trx_id;
494 }
495
496 rw_lock_x_unlock(rw_latch);
497 }
498
499 dberr_t Context::setup_pk_sort(Cursor *cursor) noexcept {
500 if (m_skip_pk_sort) {
501 return cursor->setup_pk_sort(m_n_uniq);
502 } else {
503 return DB_SUCCESS;
504 }
505 }
506
507 dberr_t Context::read_init(Cursor *cursor) noexcept {
508 ut_a(m_cursor == nullptr);
509
510 m_cursor = cursor;
511 setup_nonnull();
512
513 return setup_pk_sort(cursor);
514 }
515
516 dberr_t Context::build() noexcept {
517 Loader loader{*this};
518
519 const auto err = cleanup(loader.build_all());
520
521 /* Validate the indexes after the pages have been flushed to disk.
522 Otherwise we can deadlock between flushing and is_free page check. */
523 ut_ad(err != DB_SUCCESS || loader.validate_indexes());
524
525 return err;
526 }
527
528 bool Context::is_interrupted() noexcept { return trx_is_interrupted(m_trx); }
529
530 dtuple_t *Context::create_add_cols() noexcept {
531 ut_a(m_add_cols != nullptr);
532 ut_a(m_dtuple_heap != nullptr);
533
534 auto dtuple = dtuple_copy(m_add_cols, m_dtuple_heap);
535
536 for (size_t i = 0; i < m_add_cols->n_fields; ++i) {
537 dfield_dup(&dtuple->fields[i], m_dtuple_heap);
538 }
539
540 return dtuple;
541 }
542
543 Sequence::Sequence(THD *thd, ulonglong start_value,
544 ulonglong max_value) noexcept
545 : m_max_value(max_value), m_next_value(start_value) {
546 if (thd != nullptr && m_max_value > 0) {
547 thd_get_autoinc(thd, &m_offset, &m_increment);
548
549 if (m_increment > 1 || m_offset > 1) {
550 /* If there is an offset or increment specified
551 then we need to work out the exact next value. */
552
553 m_next_value = innobase_next_autoinc(start_value, 1, m_increment,
554 m_offset, m_max_value);
555
556 } else if (start_value == 0) {
557 /* The next value can never be 0. */
558 m_next_value = 1;
559 }
560 } else {
561 m_eof = true;
562 }
563 }
564
565 ulonglong Sequence::operator++(int) noexcept {
566 const auto current = m_next_value;
567
568 ut_ad(!m_eof);
569 ut_ad(m_max_value > 0);
570
571 m_next_value =
572 innobase_next_autoinc(current, 1, m_increment, m_offset, m_max_value);
573
574 if (m_next_value == m_max_value && current == m_next_value) {
575 m_eof = true;
576 }
577
578 return current;
579 }
580 } // namespace ddl