Debian Codegraph @

storage/innobase/row/row0log.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2011, 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 row/row0log.cc
29 Modification log for online index creation and online table rebuild
30
31 Created 2011-05-26 Marko Makela
32 *******************************************************/
33
34 #include "row0log.h"
35
36 #include "my_config.h"
37
38 #include <fcntl.h>
39 #include <algorithm>
40 #include <map>
41
42 #include "data0data.h"
43 #include "ddl0ddl.h"
44 #include "handler0alter.h"
45 #include "lob0lob.h"
46 #include "log0chkp.h"
47 #include "que0que.h"
48 #include "row0ext.h"
49 #include "row0ins.h"
50 #include "row0mysql.h"
51 #include "row0row.h"
52 #include "row0upd.h"
53 #include "scope_guard.h"
54 #include "srv0mon.h"
55 #include "trx0rec.h"
56 #include "ut0new.h"
57 #include "ut0stage.h"
58
59 #include "my_dbug.h"
60
61 /** Table row modification operations during online table rebuild.
62 Delete-marked records are not copied to the rebuilt table. */
63 enum row_tab_op {
64 /** Insert a record */
65 ROW_T_INSERT = 0x41,
66 /** Update a record in place */
67 ROW_T_UPDATE,
68 /** Delete (purge) a record */
69 ROW_T_DELETE
70 };
71
72 /** Index record modification operations during online index creation */
73 enum row_op {
74 /** Insert a record */
75 ROW_OP_INSERT = 0x61,
76 /** Delete a record */
77 ROW_OP_DELETE
78 };
79
80 /** Size of the modification log entry header, in bytes */
81 /**op, extra_size*/
82 constexpr uint32_t ROW_LOG_HEADER_SIZE = 2;
83
84 /** Log block for modifications during online ALTER TABLE */
85 struct row_log_buf_t {
86 /** File block buffer */
87 byte *block;
88
89 /** Buffer for accessing a record that spans two blocks */
90 ddl::mrec_buf_t buf;
91
92 /** Current position in blocks */
93 ulint blocks;
94
95 /** Current position within block */
96 ulint bytes;
97
98 /** logical position, in bytes from the start of the row_log_table log; 0 for
99 row_log_online_op() and row_log_apply(). */
100 ulonglong total;
101 };
102
103 /** Tracks BLOB allocation during online ALTER TABLE */
104 class row_log_table_blob_t {
105 public:
106 /** Constructor (declaring a BLOB freed)
107 @param offset_arg row_log_t::tail::total */
108 #ifdef UNIV_DEBUG
109 row_log_table_blob_t(ulonglong offset_arg)
110 : old_offset(0), free_offset(offset_arg), offset(BLOB_FREED) {}
111 #else /* UNIV_DEBUG */
112 row_log_table_blob_t() : offset(BLOB_FREED) {}
113 #endif /* UNIV_DEBUG */
114
115 /** Declare a BLOB freed again.
116 @param offset_arg row_log_t::tail::total */
117 #ifdef UNIV_DEBUG
118 void blob_free(ulonglong offset_arg)
119 #else /* UNIV_DEBUG */
120 void blob_free()
121 #endif /* UNIV_DEBUG */
122 {
123 ut_ad(offset < offset_arg);
124 ut_ad(offset != BLOB_FREED);
125 ut_d(old_offset = offset);
126 ut_d(free_offset = offset_arg);
127 offset = BLOB_FREED;
128 }
129 /** Declare a freed BLOB reused.
130 @param offset_arg row_log_t::tail::total */
131 void blob_alloc(ulonglong offset_arg) {
132 ut_ad(free_offset <= offset_arg);
133 ut_d(old_offset = offset);
134 offset = offset_arg;
135 }
136 /** Determine if a BLOB was freed at a given log position
137 @param offset_arg row_log_t::head::total after the log record
138 @return true if freed */
139 bool is_freed(ulonglong offset_arg) const {
140 /* This is supposed to be the offset at the end of the
141 current log record. */
142 ut_ad(offset_arg > 0);
143 /* We should never get anywhere close the magic value. */
144 ut_ad(offset_arg < BLOB_FREED);
145 return (offset_arg < offset);
146 }
147
148 private:
149 /** Magic value for a freed BLOB */
150 static const ulonglong BLOB_FREED = ~0ULL;
151 #ifdef UNIV_DEBUG
152 /** Old offset, in case a page was freed, reused, freed, ... */
153 ulonglong old_offset;
154 /** Offset of last blob_free() */
155 ulonglong free_offset;
156 #endif /* UNIV_DEBUG */
157 /** Byte offset to the log file */
158 ulonglong offset;
159 };
160
161 /** @brief Map of off-page column page numbers to 0 or log byte offsets.
162
163 If there is no mapping for a page number, it is safe to access.
164 If a page number maps to 0, it is an off-page column that has been freed.
165 If a page number maps to a nonzero number, the number is a byte offset
166 into the index->online_log, indicating that the page is safe to access
167 when applying log records starting from that offset. */
168 typedef std::map<
169 page_no_t, row_log_table_blob_t, std::less<page_no_t>,
170 ut::allocator<std::pair<const page_no_t, row_log_table_blob_t>>>
171 page_no_map;
172
173 /** @brief Buffer for logging modifications during online index creation
174
175 All modifications to an index that is being created will be logged by
176 row_log_online_op() to this buffer.
177
178 All modifications to a table that is being rebuilt will be logged by
179 row_log_table_delete(), row_log_table_update(), row_log_table_insert()
180 to this buffer.
181
182 When head.blocks == tail.blocks, the reader will access tail.block
183 directly. When also head.bytes == tail.bytes, both counts will be
184 reset to 0 and the file will be truncated. */
185 struct row_log_t {
186 /** File descriptor */
187 ddl::Unique_os_file_descriptor file;
188
189 /** Mutex protecting error, max_trx and tail */
190 ib_mutex_t mutex;
191
192 /** Map of page numbers of off-page columns that have been freed during
193 table-rebuilding ALTER TABLE (row_log_table_*); protected by index->lock
194 X-latch only */
195 page_no_map *blobs;
196
197 /** Table that is being rebuilt, or NULL when this is a secondary index that
198 is being created online */
199 dict_table_t *table;
200
201 /** Whether the definition of the PRIMARY KEY has remained the same */
202 bool same_pk;
203
204 /** Default values of added columns, or NULL */
205 const dtuple_t *add_cols;
206
207 /** Mapping of old column numbers to new ones, or NULL if !table */
208 const ulint *col_map;
209
210 /** Error that occurred during online table rebuild */
211 dberr_t error;
212
213 /** Biggest observed trx_id in row_log_online_op(); protected by mutex and
214 index->lock S-latch, or by index->lock X-latch only */
215 trx_id_t max_trx;
216
217 /** writer context; protected by mutex and index->lock S-latch, or by
218 index->lock X-latch only */
219 row_log_buf_t tail;
220
221 /** Reader context; protected by MDL only; modifiable by
222 row_log_apply_ops() */
223 row_log_buf_t head;
224
225 /** number of non-virtual column in old table */
226 size_t n_old_col;
227
228 /** number of virtual column in old table */
229 size_t n_old_vcol;
230
231 /** Where to create temporary file during log operation */
232 const char *path;
233 };
234
235 /** Create the file or online log if it does not exist.
236 @param[in,out] log online rebuild log
237 @return true if success, false if not */
238 [[nodiscard]] static bool row_log_tmpfile(row_log_t *log) {
239 DBUG_TRACE;
240 if (!log->file.is_open()) {
241 log->file = ddl::file_create_low(log->path);
242 DBUG_EXECUTE_IF("row_log_tmpfile_fail", log->file.close(););
243 if (log->file.is_open()) {
244 MONITOR_ATOMIC_INC(MONITOR_ALTER_TABLE_LOG_FILES);
245 }
246 }
247
248 return log->file.is_open();
249 }
250
251 /** Allocate the memory for the log buffer.
252 @param[in,out] log_buf Buffer used for log operation
253 @return true if success, false if not */
254 [[nodiscard]] static bool row_log_block_allocate(row_log_buf_t &log_buf) {
255 DBUG_TRACE;
256 if (log_buf.block == nullptr) {
257 DBUG_EXECUTE_IF("simulate_row_log_allocation_failure", return false;);
258
259 log_buf.block = static_cast<uint8_t *>(ut::malloc_large_page_withkey(
260 ut::make_psi_memory_key(mem_key_row_log_buf), srv_sort_buf_size,
261 ut::fallback_to_normal_page_t{}));
262
263 if (log_buf.block == nullptr) {
264 return false;
265 }
266 }
267 return true;
268 }
269
270 /** Free the log buffer.
271 @param[in,out] log_buf Buffer used for log operation */
272 static void row_log_block_free(row_log_buf_t &log_buf) {
273 DBUG_TRACE;
274 ut::free_large_page(log_buf.block, ut::fallback_to_normal_page_t{});
275 log_buf.block = nullptr;
276 }
277
278 /** Logs an operation to a secondary index that is (or was) being created. */
279 void row_log_online_op(
280 dict_index_t *index, /*!< in/out: index, S or X latched */
281 const dtuple_t *tuple, /*!< in: index tuple */
282 trx_id_t trx_id) /*!< in: transaction ID for insert,
283 or 0 for delete */
284 {
285 byte *b;
286 ulint extra_size;
287 ulint size;
288 ulint mrec_size;
289 ulint avail_size;
290 row_log_t *log;
291
292 ut_ad(dtuple_validate(tuple));
293 ut_ad(dtuple_get_n_fields(tuple) == dict_index_get_n_fields(index));
294 ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_S) ||
295 rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
296 ut_ad(!index->is_clustered());
297
298 if (index->is_corrupted()) {
299 return;
300 }
301
302 ut_ad(dict_index_is_online_ddl(index));
303
304 /* Compute the size of the record. This differs from ddl::buf_encode(),
305 because here we do not encode extra_size+1 (and reserve 0 as the
306 end-of-chunk marker). */
307
308 /* Secondary index, version doesn't matter */
309 size = rec_get_serialize_size(index, tuple->fields, tuple->n_fields, nullptr,
310 &extra_size, MAX_ROW_VERSION);
311 ut_ad(size >= extra_size);
312 ut_ad(size <= sizeof log->tail.buf);
313
314 mrec_size = ROW_LOG_HEADER_SIZE + (extra_size >= 0x80) + size +
315 (trx_id ? DATA_TRX_ID_LEN : 0);
316
317 log = index->online_log;
318 mutex_enter(&log->mutex);
319
320 if (trx_id > log->max_trx) {
321 log->max_trx = trx_id;
322 }
323
324 if (!row_log_block_allocate(log->tail)) {
325 log->error = DB_OUT_OF_MEMORY;
326 goto err_exit;
327 }
328
329 UNIV_MEM_INVALID(log->tail.buf, sizeof log->tail.buf);
330
331 ut_ad(log->tail.bytes < srv_sort_buf_size);
332 avail_size = srv_sort_buf_size - log->tail.bytes;
333
334 if (mrec_size > avail_size) {
335 b = log->tail.buf;
336 } else {
337 b = log->tail.block + log->tail.bytes;
338 }
339
340 if (trx_id != 0) {
341 *b++ = ROW_OP_INSERT;
342 trx_write_trx_id(b, trx_id);
343 b += DATA_TRX_ID_LEN;
344 } else {
345 *b++ = ROW_OP_DELETE;
346 }
347
348 if (extra_size < 0x80) {
349 *b++ = (byte)extra_size;
350 } else {
351 ut_ad(extra_size < 0x8000);
352 *b++ = (byte)(0x80 | (extra_size >> 8));
353 *b++ = (byte)extra_size;
354 }
355
356 rec_serialize_dtuple(b + extra_size, index, tuple->fields, tuple->n_fields,
357 nullptr, MAX_ROW_VERSION);
358 b += size;
359
360 if (mrec_size >= avail_size) {
361 dberr_t err;
362 IORequest request(IORequest::ROW_LOG | IORequest::WRITE);
363 const os_offset_t byte_offset =
364 (os_offset_t)log->tail.blocks * srv_sort_buf_size;
365
366 if (byte_offset + srv_sort_buf_size >= srv_online_max_size) {
367 goto write_failed;
368 }
369
370 if (mrec_size == avail_size) {
371 ut_ad(b == &log->tail.block[srv_sort_buf_size]);
372 } else {
373 ut_ad(b == log->tail.buf + mrec_size);
374 memcpy(log->tail.block + log->tail.bytes, log->tail.buf, avail_size);
375 }
376
377 UNIV_MEM_ASSERT_RW(log->tail.block, srv_sort_buf_size);
378
379 if (!row_log_tmpfile(log)) {
380 log->error = DB_OUT_OF_MEMORY;
381 goto err_exit;
382 }
383
384 err = os_file_write_int_fd(request, "(modification log)", log->file.get(),
385 log->tail.block, byte_offset, srv_sort_buf_size);
386
387 log->tail.blocks++;
388 if (err != DB_SUCCESS) {
389 write_failed:
390 /* We set the flag directly instead of
391 invoking dict_set_corrupted() here,
392 because the index is not "public" yet. */
393 index->type |= DICT_CORRUPT;
394 }
395 UNIV_MEM_INVALID(log->tail.block, srv_sort_buf_size);
396 memcpy(log->tail.block, log->tail.buf + avail_size, mrec_size - avail_size);
397 log->tail.bytes = mrec_size - avail_size;
398 } else {
399 log->tail.bytes += mrec_size;
400 ut_ad(b == log->tail.block + log->tail.bytes);
401 }
402
403 UNIV_MEM_INVALID(log->tail.buf, sizeof log->tail.buf);
404 err_exit:
405 mutex_exit(&log->mutex);
406 }
407
408 /** Gets the error status of the online index rebuild log.
409 @return DB_SUCCESS or error code */
410 dberr_t row_log_table_get_error(
411 const dict_index_t *index) /*!< in: clustered index of a table
412 that is being rebuilt online */
413 {
414 ut_ad(index->is_clustered());
415 ut_ad(dict_index_is_online_ddl(index));
416 return (index->online_log->error);
417 }
418
419 /** Starts logging an operation to a table that is being rebuilt.
420 @return pointer to log, or NULL if no logging is necessary */
421 [[nodiscard]] static byte *row_log_table_open(
422 row_log_t *log, /*!< in/out: online rebuild log */
423 ulint size, /*!< in: size of log record */
424 ulint *avail) /*!< out: available size for log record */
425 {
426 mutex_enter(&log->mutex);
427
428 UNIV_MEM_INVALID(log->tail.buf, sizeof log->tail.buf);
429
430 if (log->error != DB_SUCCESS) {
431 err_exit:
432 mutex_exit(&log->mutex);
433 return (nullptr);
434 }
435
436 if (!row_log_block_allocate(log->tail)) {
437 log->error = DB_OUT_OF_MEMORY;
438 goto err_exit;
439 }
440
441 ut_ad(log->tail.bytes < srv_sort_buf_size);
442 *avail = srv_sort_buf_size - log->tail.bytes;
443
444 if (size > *avail) {
445 /* Make sure log->tail.buf is large enough */
446 ut_ad(size <= sizeof log->tail.buf);
447 return (log->tail.buf);
448 } else {
449 return (log->tail.block + log->tail.bytes);
450 }
451 }
452
453 /** Stops logging an operation to a table that is being rebuilt.
454 @param[in,out] log online rebuild log
455 @param[in] b end of log record
456 @param[in] size size od log record
457 @param[in] avail available size for log record */
458 static void row_log_table_close_func(row_log_t *log,
459 IF_DEBUG(const byte *b, ) ulint size,
460 ulint avail) {
461 ut_ad(mutex_own(&log->mutex));
462
463 if (size >= avail) {
464 dberr_t err;
465 IORequest request(IORequest::ROW_LOG | IORequest::WRITE);
466 const os_offset_t byte_offset =
467 (os_offset_t)log->tail.blocks * srv_sort_buf_size;
468
469 if (byte_offset + srv_sort_buf_size >= srv_online_max_size) {
470 goto write_failed;
471 }
472
473 if (size == avail) {
474 ut_ad(b == &log->tail.block[srv_sort_buf_size]);
475 } else {
476 ut_ad(b == log->tail.buf + size);
477 memcpy(log->tail.block + log->tail.bytes, log->tail.buf, avail);
478 }
479
480 UNIV_MEM_ASSERT_RW(log->tail.block, srv_sort_buf_size);
481
482 if (!row_log_tmpfile(log)) {
483 log->error = DB_OUT_OF_MEMORY;
484 goto err_exit;
485 }
486
487 err = os_file_write_int_fd(request, "(modification log)", log->file.get(),
488 log->tail.block, byte_offset, srv_sort_buf_size);
489
490 log->tail.blocks++;
491 if (err != DB_SUCCESS) {
492 write_failed:
493 log->error = DB_ONLINE_LOG_TOO_BIG;
494 }
495 UNIV_MEM_INVALID(log->tail.block, srv_sort_buf_size);
496 memcpy(log->tail.block, log->tail.buf + avail, size - avail);
497 log->tail.bytes = size - avail;
498 } else {
499 log->tail.bytes += size;
500 ut_ad(b == log->tail.block + log->tail.bytes);
501 }
502
503 log->tail.total += size;
504 UNIV_MEM_INVALID(log->tail.buf, sizeof log->tail.buf);
505 err_exit:
506 mutex_exit(&log->mutex);
507 }
508
509 static inline void row_log_table_close(row_log_t *log,
510 const byte *b [[maybe_unused]],
511 ulint size, ulint avail) {
512 row_log_table_close_func(log, IF_DEBUG(b, ) size, avail);
513 }
514
515 /** Check whether a virtual column is indexed in the new table being
516 created during alter table
517 @param[in] index cluster index
518 @param[in] v_no virtual column number
519 @return true if it is indexed, else false */
520 bool row_log_col_is_indexed(const dict_index_t *index, ulint v_no) {
521 return (
522 dict_table_get_nth_v_col(index->online_log->table, v_no)->m_col.ord_part);
523 }
524
525 /** Logs a delete operation to a table that is being rebuilt.
526 This will be merged in row_log_table_apply_delete(). */
527 void row_log_table_delete(
528 const rec_t *rec, /*!< in: clustered index leaf page record,
529 page X-latched */
530 const dtuple_t *ventry, /*!< in: dtuple holding virtual column info */
531 dict_index_t *index, /*!< in/out: clustered index, S-latched
532 or X-latched */
533 const ulint *offsets, /*!< in: rec_get_offsets(rec,index) */
534 const byte *sys) /*!< in: DB_TRX_ID,DB_ROLL_PTR that should
535 be logged, or NULL to use those in rec */
536 {
537 ulint old_pk_extra_size;
538 ulint old_pk_size;
539 ulint mrec_size;
540 ulint avail_size;
541 mem_heap_t *heap = nullptr;
542 const dtuple_t *old_pk;
543
544 if (index->is_corrupted() || !dict_index_is_online_ddl(index) ||
545 index->online_log->error != DB_SUCCESS) {
546 return;
547 }
548
549 ut_ad(index->is_clustered());
550 ut_ad(rec_offs_validate(rec, index, offsets));
551 ut_ad(rec_offs_n_fields(offsets) == dict_index_get_n_fields(index));
552 ut_ad(rec_offs_size(offsets) <= sizeof index->online_log->tail.buf);
553 ut_ad(rw_lock_own_flagged(&index->lock,
554 RW_LOCK_FLAG_S | RW_LOCK_FLAG_X | RW_LOCK_FLAG_SX));
555
556 dict_table_t *new_table = index->online_log->table;
557 dict_index_t *new_index = new_table->first_index();
558
559 ut_ad(new_index->is_clustered());
560 ut_ad(!dict_index_is_online_ddl(new_index));
561
562 /* Create the tuple PRIMARY KEY,DB_TRX_ID,DB_ROLL_PTR in new_table. */
563 if (index->online_log->same_pk) {
564 dtuple_t *tuple;
565 ut_ad(new_index->n_uniq == index->n_uniq);
566
567 /* The PRIMARY KEY and DB_TRX_ID,DB_ROLL_PTR are in the first
568 fields of the record. */
569 heap = mem_heap_create(
570 DATA_TRX_ID_LEN + DTUPLE_EST_ALLOC(new_index->n_uniq + 2),
571 UT_LOCATION_HERE);
572 old_pk = tuple = dtuple_create(heap, new_index->n_uniq + 2);
573 dict_index_copy_types(tuple, new_index, tuple->n_fields);
574 dtuple_set_n_fields_cmp(tuple, new_index->n_uniq);
575
576 for (ulint i = 0; i < dtuple_get_n_fields(tuple); i++) {
577 ulint len;
578 const void *field = rec_get_nth_field(nullptr, rec, offsets, i, &len);
579 dfield_t *dfield = dtuple_get_nth_field(tuple, i);
580 ut_ad(len != UNIV_SQL_NULL);
581 ut_ad(!rec_offs_nth_extern(index, offsets, i));
582 dfield_set_data(dfield, field, len);
583 }
584
585 if (sys) {
586 dfield_set_data(dtuple_get_nth_field(tuple, new_index->n_uniq), sys,
587 DATA_TRX_ID_LEN);
588 dfield_set_data(dtuple_get_nth_field(tuple, new_index->n_uniq + 1),
589 sys + DATA_TRX_ID_LEN, DATA_ROLL_PTR_LEN);
590 }
591 } else {
592 /* The PRIMARY KEY has changed. Translate the tuple. */
593 old_pk = row_log_table_get_pk(rec, index, offsets, nullptr, &heap);
594
595 if (!old_pk) {
596 ut_ad(index->online_log->error != DB_SUCCESS);
597 if (heap) {
598 goto func_exit;
599 }
600 return;
601 }
602 }
603
604 ut_ad(DATA_TRX_ID_LEN ==
605 dtuple_get_nth_field(old_pk, old_pk->n_fields - 2)->len);
606 ut_ad(DATA_ROLL_PTR_LEN ==
607 dtuple_get_nth_field(old_pk, old_pk->n_fields - 1)->len);
608 old_pk_size = /* because it's PK, (changed or not), version doesn't matter */
609 rec_get_serialize_size(new_index, old_pk->fields, old_pk->n_fields,
610 nullptr, &old_pk_extra_size, MAX_ROW_VERSION);
611 ut_ad(old_pk_extra_size < 0x100);
612
613 /* 2 = 1 (extra_size) + at least 1 byte payload */
614 mrec_size = 2 + old_pk_size;
615
616 /* Check if we need to log virtual column data */
617 if (ventry->n_v_fields > 0) {
618 ulint v_extra;
619 mrec_size += rec_get_serialize_size(new_index, nullptr, 0, ventry, &v_extra,
620 MAX_ROW_VERSION);
621 }
622
623 if (byte *b = row_log_table_open(index->online_log, mrec_size, &avail_size)) {
624 *b++ = ROW_T_DELETE;
625 *b++ = static_cast<byte>(old_pk_extra_size);
626
627 rec_serialize_dtuple(b + old_pk_extra_size, new_index, old_pk->fields,
628 old_pk->n_fields, nullptr, MAX_ROW_VERSION);
629
630 b += old_pk_size;
631
632 /* log virtual columns */
633 if (ventry->n_v_fields > 0) {
634 rec_serialize_dtuple(b, new_index, nullptr, 0, ventry, MAX_ROW_VERSION);
635 b += mach_read_from_2(b);
636 } else if (index->table->n_v_cols) {
637 mach_write_to_2(b, 2);
638 b += 2;
639 }
640
641 row_log_table_close(index->online_log, b, mrec_size, avail_size);
642 }
643
644 func_exit:
645 mem_heap_free(heap);
646 }
647
648 /** Logs an insert or update to a table that is being rebuilt.
649 @param[in] rec clustered index leaf page record in
650 ROW_FORMAT=REDUNDANT, page X-latched
651 @param[in] ventry dtuple holding virtual column info or NULL
652 @param[in] o_ventry old dtuple holding virtual column info or NULL
653 @param[in,out] index clustered index, S-latched or X-latched
654 @param[in] insert true if insert, false if update
655 @param[in] old_pk old PRIMARY KEY value (if !insert and a PRIMARY
656 KEY is being created)
657 @param[in] new_index clustered index of the new table, not latched */
658 static void row_log_table_low_redundant(const rec_t *rec,
659 const dtuple_t *ventry,
660 const dtuple_t *o_ventry,
661 dict_index_t *index, bool insert,
662 const dtuple_t *old_pk,
663 const dict_index_t *new_index) {
664 ulint num_v = ventry ? dtuple_get_n_v_fields(ventry) : 0;
665
666 ut_ad(!page_is_comp(page_align(rec)));
667 ut_ad(dict_index_get_n_fields(index) == rec_get_n_fields_old(rec, index));
668 ut_ad(dict_tf2_is_valid(index->table->flags, index->table->flags2));
669 ut_ad(!dict_table_is_comp(index->table)); /* redundant row format */
670 ut_ad(new_index->is_clustered());
671
672 uint8_t rec_version = UINT8_UNDEFINED;
673 bool rec_has_version = false;
674 if (rec_old_is_versioned(rec)) {
675 rec_version = rec_get_instant_row_version_old(rec);
676 ut_ad(is_valid_row_version(rec_version));
677 ut_ad(index->has_row_versions() || rec_version == 0);
678 rec_has_version = true;
679 }
680
681 const auto n_total_fields = index->get_n_total_fields();
682
683 mem_heap_t *heap =
684 mem_heap_create(DTUPLE_EST_ALLOC(n_total_fields), UT_LOCATION_HERE);
685 /* Create tuple with total fields because for inplace update on record in a
686 table with INSTANT DROP columns, we keep the records on current version i.e.
687 dropped column value may still exists. */
688 dtuple_t *tuple = dtuple_create_with_vcol(heap, n_total_fields, num_v);
689 dict_index_copy_types(tuple, index, n_total_fields);
690
691 if (num_v) {
692 dict_table_copy_v_types(tuple, index->table);
693 }
694
695 dtuple_set_n_fields_cmp(tuple, dict_index_get_n_unique(index));
696
697 if (rec_get_1byte_offs_flag(rec)) {
698 for (uint16_t i = 0; i < n_total_fields; i++) {
699 dfield_t *dfield;
700 ulint len;
701 const void *field;
702
703 dfield = dtuple_get_nth_field(tuple, i);
704 field = rec_get_nth_field_old_instant(rec, i, index, &len);
705
706 dfield_set_data(dfield, field, len);
707 }
708 } else {
709 for (uint16_t i = 0; i < n_total_fields; i++) {
710 dfield_t *dfield;
711 ulint len;
712 const void *field;
713
714 dfield = dtuple_get_nth_field(tuple, i);
715 field = rec_get_nth_field_old_instant(rec, i, index, &len);
716
717 dfield_set_data(dfield, field, len);
718
719 /* Fields stored as default value is not stored externally. */
720 size_t phy_pos = index->get_field(i)->col->get_col_phy_pos();
721 if (phy_pos < rec_get_n_fields_old_raw(rec) &&
722 rec_2_is_field_extern(index, rec, i)) {
723 dfield_set_ext(dfield);
724 }
725 }
726 }
727
728 ulint extra_size;
729 ulint size = rec_get_serialize_size(index, tuple->fields, tuple->n_fields,
730 ventry, &extra_size, rec_version);
731
732 const size_t additional_size_for_instant = get_extra_bytes_for_temp_redundant(
733 index, is_valid_row_version(rec_version));
734
735 extra_size += additional_size_for_instant;
736
737 ulint mrec_size = ROW_LOG_HEADER_SIZE + size + (extra_size >= 0x80) +
738 additional_size_for_instant;
739
740 if (num_v) {
741 if (o_ventry) {
742 ulint v_extra = 0;
743 mrec_size += rec_get_serialize_size(new_index, nullptr, 0, o_ventry,
744 &v_extra, MAX_ROW_VERSION);
745 }
746 } else if (index->table->n_v_cols) {
747 mrec_size += 2;
748 }
749
750 ulint old_pk_size;
751 ulint old_pk_extra_size;
752 if (insert || index->online_log->same_pk) {
753 ut_ad(!old_pk);
754 old_pk_extra_size = old_pk_size = 0;
755 } else {
756 ut_ad(old_pk);
757 ut_ad(old_pk->n_fields == 2 + old_pk->n_fields_cmp);
758 ut_ad(DATA_TRX_ID_LEN ==
759 dtuple_get_nth_field(old_pk, old_pk->n_fields - 2)->len);
760 ut_ad(DATA_ROLL_PTR_LEN ==
761 dtuple_get_nth_field(old_pk, old_pk->n_fields - 1)->len);
762
763 /* PK fileds, version doesn't matter. */
764 old_pk_size =
765 rec_get_serialize_size(new_index, old_pk->fields, old_pk->n_fields,
766 nullptr, &old_pk_extra_size, MAX_ROW_VERSION);
767 ut_ad(old_pk_extra_size < 0x100);
768 mrec_size += 1 /*old_pk_extra_size*/ + old_pk_size;
769 }
770
771 ulint avail_size;
772 if (byte *b = row_log_table_open(index->online_log, mrec_size, &avail_size)) {
773 /* Write TYPE in 1 byte */
774 *b++ = insert ? ROW_T_INSERT : ROW_T_UPDATE;
775
776 if (old_pk_size) {
777 *b++ = static_cast<byte>(old_pk_extra_size);
778 /* It's PK fields for new table, version doesn't matter. */
779 rec_serialize_dtuple(b + old_pk_extra_size, new_index, old_pk->fields,
780 old_pk->n_fields, ventry, UINT8_UNDEFINED);
781 b += old_pk_size;
782 }
783
784 /* Write extra size in 1 or 2 bytes */
785 if (extra_size < 0x80) {
786 *b++ = static_cast<byte>(extra_size);
787 } else {
788 ut_ad(extra_size < 0x8000);
789 *b++ = static_cast<byte>(0x80 | (extra_size >> 8));
790 *b++ = static_cast<byte>(extra_size);
791 }
792
793 /* Convert and write record in TEMP format */
794 rec_serialize_dtuple(b + extra_size, index, tuple->fields, tuple->n_fields,
795 ventry, rec_version);
796
797 /* Write instant metadata in 1 or 2 bytes */
798 if (index->has_instant_cols_or_row_versions()) {
799 /* Write infobit in 1 byte */
800 byte *temp_rec = b + extra_size;
801 rec_set_info_bits_new_temp(temp_rec, rec_get_info_bits(rec, false));
802 if (rec_has_version) {
803 rec_new_temp_set_versioned(temp_rec, true);
804 /* Write the record version in 1 byte */
805 byte *temp_version = temp_rec - 2;
806 memcpy(temp_version, &rec_version, sizeof(uint8_t));
807 } else {
808 rec_new_temp_set_versioned(temp_rec, false);
809 }
810 }
811
812 /* Move 'b' to past INSTANT metadata */
813 b += additional_size_for_instant;
814
815 /* Move 'b' to past record data */
816 b += size;
817
818 if (num_v) {
819 if (o_ventry) {
820 rec_serialize_dtuple(b, new_index, nullptr, 0, o_ventry,
821 MAX_ROW_VERSION);
822 b += mach_read_from_2(b);
823 }
824 } else if (index->table->n_v_cols) {
825 /* The table contains virtual columns, but nothing
826 has changed for them, so just mark a 2 bytes length
827 field */
828 mach_write_to_2(b, 2);
829 b += 2;
830 }
831
832 row_log_table_close(index->online_log, b, mrec_size, avail_size);
833 }
834
835 mem_heap_free(heap);
836 }
837
838 /** Logs an insert or update to a table that is being rebuilt.
839 @param[in] rec clustered index leaf page record, page X-latched
840 @param[in] ventry dtuple holding virtual column info
841 @param[in] o_ventry dtuple holding old virtual column info
842 @param[in,out] index clustered index, S-latched or X-latched
843 @param[in] offsets rec_get_offsets(rec,index)
844 @param[in] insert true if insert, false if update
845 @param[in] old_pk old PRIMARY KEY value (if !insert and a PRIMARY
846 KEY is being created) */
847 static void row_log_table_low(const rec_t *rec, const dtuple_t *ventry,
848 const dtuple_t *o_ventry, dict_index_t *index,
849 const ulint *offsets, bool insert,
850 const dtuple_t *old_pk) {
851 if (index->is_corrupted() || !dict_index_is_online_ddl(index) ||
852 index->online_log->error != DB_SUCCESS) {
853 return;
854 }
855
856 const dict_index_t *new_index = index->online_log->table->first_index();
857
858 ut_ad(index->is_clustered());
859 ut_ad(new_index->is_clustered());
860 ut_ad(!dict_index_is_online_ddl(new_index));
861 ut_ad(rec_offs_validate(rec, index, offsets));
862 ut_ad(rec_offs_n_fields(offsets) == dict_index_get_n_fields(index));
863 ut_ad(rec_offs_size(offsets) <= sizeof index->online_log->tail.buf);
864 ut_ad(rw_lock_own_flagged(&index->lock,
865 RW_LOCK_FLAG_S | RW_LOCK_FLAG_X | RW_LOCK_FLAG_SX));
866 ut_ad(fil_page_get_type(page_align(rec)) == FIL_PAGE_INDEX);
867 ut_ad(page_is_leaf(page_align(rec)));
868 ut_ad(page_is_comp(page_align(rec)) == rec_offs_comp(offsets));
869 /* old_pk=row_log_table_get_pk() [not needed in INSERT] is a prefix
870 of the clustered index record (PRIMARY KEY,DB_TRX_ID,DB_ROLL_PTR),
871 with no information on virtual columns */
872 ut_ad(!old_pk || !insert);
873 ut_ad(!old_pk || old_pk->n_v_fields == 0);
874 ut_ad(!o_ventry || !insert);
875 ut_ad(!o_ventry || ventry);
876
877 if (!rec_offs_comp(offsets)) {
878 row_log_table_low_redundant(rec, ventry, o_ventry, index, insert, old_pk,
879 new_index);
880 return;
881 }
882
883 ut_ad(page_is_comp(page_align(rec)));
884 ut_ad(rec_get_status(rec) == REC_STATUS_ORDINARY);
885
886 /* Check the instant to decide copying info bit or not */
887 ulint omit_size =
888 REC_N_NEW_EXTRA_BYTES -
889 (index->has_instant_cols_or_row_versions() ? REC_N_TMP_EXTRA_BYTES : 0);
890
891 ulint extra_size = rec_offs_extra_size(offsets) - omit_size;
892
893 ulint mrec_size = ROW_LOG_HEADER_SIZE + (extra_size >= 0x80) +
894 rec_offs_size(offsets) - omit_size;
895
896 if (ventry && ventry->n_v_fields > 0) {
897 ulint v_extra = 0;
898 uint64_t rec_size = rec_get_serialize_size(new_index, nullptr, 0, ventry,
899 &v_extra, MAX_ROW_VERSION);
900
901 mrec_size += rec_size;
902
903 /* If there is actually nothing to be logged for new entry, then
904 there must be also nothing to do with old entry. In this case,
905 make it same with the case below, by only keep 2 bytes length marker */
906 if (rec_size > 2 && o_ventry != nullptr) {
907 mrec_size += rec_get_serialize_size(new_index, nullptr, 0, o_ventry,
908 &v_extra, MAX_ROW_VERSION);
909 }
910 } else if (index->table->n_v_cols) {
911 /* Always leave 2 bytes length marker for virtual column
912 data logging even if there is none of them is indexed if table
913 has virtual columns */
914 mrec_size += 2;
915 }
916
917 ulint old_pk_size;
918 ulint old_pk_extra_size;
919 if (insert || index->online_log->same_pk) {
920 ut_ad(!old_pk);
921 old_pk_extra_size = old_pk_size = 0;
922 } else {
923 ut_ad(old_pk);
924 ut_ad(old_pk->n_fields == 2 + old_pk->n_fields_cmp);
925 ut_ad(DATA_TRX_ID_LEN ==
926 dtuple_get_nth_field(old_pk, old_pk->n_fields - 2)->len);
927 ut_ad(DATA_ROLL_PTR_LEN ==
928 dtuple_get_nth_field(old_pk, old_pk->n_fields - 1)->len);
929 /* PK fields. version doesn't matter. */
930 old_pk_size =
931 rec_get_serialize_size(new_index, old_pk->fields, old_pk->n_fields,
932 nullptr, &old_pk_extra_size, MAX_ROW_VERSION);
933 ut_ad(old_pk_extra_size < 0x100);
934 mrec_size += 1 /*old_pk_extra_size*/ + old_pk_size;
935 }
936
937 ulint avail_size;
938 if (byte *b = row_log_table_open(index->online_log, mrec_size, &avail_size)) {
939 *b++ = insert ? ROW_T_INSERT : ROW_T_UPDATE;
940
941 if (old_pk_size) {
942 ut_ad(!insert);
943
944 *b++ = static_cast<byte>(old_pk_extra_size);
945 /* PK fields. version doesn't matter. */
946 rec_serialize_dtuple(b + old_pk_extra_size, new_index, old_pk->fields,
947 old_pk->n_fields, nullptr, MAX_ROW_VERSION);
948 b += old_pk_size;
949 }
950
951 if (extra_size < 0x80) {
952 *b++ = static_cast<byte>(extra_size);
953 } else {
954 ut_ad(extra_size < 0x8000);
955 *b++ = static_cast<byte>(0x80 | (extra_size >> 8));
956 *b++ = static_cast<byte>(extra_size);
957 }
958
959 memcpy(b, rec - rec_offs_extra_size(offsets), extra_size);
960 b += extra_size;
961 memcpy(b, rec, rec_offs_data_size(offsets));
962 b += rec_offs_data_size(offsets);
963
964 if (ventry && ventry->n_v_fields > 0) {
965 uint64_t new_v_size;
966
967 rec_serialize_dtuple(b, new_index, nullptr, 0, ventry, MAX_ROW_VERSION);
968 new_v_size = mach_read_from_2(b);
969 b += new_v_size;
970
971 /* Nothing for new entry to be logged, skip the old one too. */
972 if (new_v_size != 2 && o_ventry != nullptr) {
973 rec_serialize_dtuple(b, new_index, nullptr, 0, o_ventry,
974 MAX_ROW_VERSION);
975 b += mach_read_from_2(b);
976 }
977 } else if (index->table->n_v_cols) {
978 /* The table contains virtual columns, but nothing
979 has changed for them, so just mark a 2 bytes length
980 field */
981 mach_write_to_2(b, 2);
982 b += 2;
983 }
984
985 row_log_table_close(index->online_log, b, mrec_size, avail_size);
986 }
987 }
988
989 /** Logs an update to a table that is being rebuilt.
990 This will be merged in row_log_table_apply_update(). */
991 void row_log_table_update(
992 const rec_t *rec, /*!< in: clustered index leaf page record,
993 page X-latched */
994 dict_index_t *index, /*!< in/out: clustered index, S-latched
995 or X-latched */
996 const ulint *offsets, /*!< in: rec_get_offsets(rec,index) */
997 const dtuple_t *old_pk, /*!< in: row_log_table_get_pk()
998 before the update */
999 const dtuple_t *new_v_row, /*!< in: dtuple contains the new virtual
1000 columns */
1001 const dtuple_t *old_v_row) /*!< in: dtuple contains the old virtual
1002 columns */
1003 {
1004 row_log_table_low(rec, new_v_row, old_v_row, index, offsets, false, old_pk);
1005 }
1006
1007 /** Gets the old table column of a PRIMARY KEY column.
1008 @param table old table (before ALTER TABLE)
1009 @param col_map mapping of old column numbers to new ones
1010 @param col_no column position in the new table
1011 @return old table column, or NULL if this is an added column */
1012 static const dict_col_t *row_log_table_get_pk_old_col(const dict_table_t *table,
1013 const ulint *col_map,
1014 ulint col_no) {
1015 for (ulint i = 0; i < table->n_cols; i++) {
1016 if (col_no == col_map[i]) {
1017 return (table->get_col(i));
1018 }
1019 }
1020
1021 return (nullptr);
1022 }
1023
1024 /** Maps an old table column of a PRIMARY KEY column.
1025 @param[in] index index being operated on
1026 @param[in] ifield clustered index field in the new table (after
1027 ALTER TABLE)
1028 @param[in,out] dfield clustered index tuple field in the new table
1029 @param[in,out] heap memory heap for allocating dfield contents
1030 @param[in] rec clustered index leaf page record in the old
1031 table
1032 @param[in] offsets rec_get_offsets(rec)
1033 @param[in] i rec field corresponding to col
1034 @param[in] page_size page size of the old table
1035 @param[in] max_len maximum length of dfield
1036 @retval DB_INVALID_NULL if a NULL value is encountered
1037 @retval DB_TOO_BIG_INDEX_COL if the maximum prefix length is exceeded */
1038 static dberr_t row_log_table_get_pk_col(dict_index_t *index,
1039 const dict_field_t *ifield,
1040 dfield_t *dfield, mem_heap_t *heap,
1041 const rec_t *rec, const ulint *offsets,
1042 ulint i, const page_size_t &page_size,
1043 ulint max_len) {
1044 const byte *field;
1045 ulint len;
1046
1047 field = rec_get_nth_field_instant(rec, offsets, i, index, &len);
1048
1049 DBUG_EXECUTE_IF("incorrect_instant_add_drop_field_fetched", field = nullptr;);
1050
1051 ut_ad(len != UNIV_SQL_ADD_COL_DEFAULT);
1052 if (field == nullptr) {
1053 ib::error(ER_IB_PRIMARY_KEY_IS_INSTANT, index->get_field(i)->name(),
1054 ulong(i), index->table_name, index->name());
1055 return (DB_INDEX_CORRUPT);
1056 }
1057
1058 if (len == UNIV_SQL_NULL) {
1059 return (DB_INVALID_NULL);
1060 }
1061
1062 if (rec_offs_nth_extern(index, offsets, i)) {
1063 ulint field_len = ifield->prefix_len;
1064 byte *blob_field;
1065
1066 if (!field_len) {
1067 field_len = ifield->fixed_len;
1068 if (!field_len) {
1069 field_len = max_len + 1;
1070 }
1071 }
1072
1073 blob_field = static_cast<byte *>(mem_heap_alloc(heap, field_len));
1074
1075 len = lob::btr_copy_externally_stored_field_prefix(
1076 nullptr, index, blob_field, field_len, page_size, field, false, len);
1077
1078 if (len >= max_len + 1) {
1079 return (DB_TOO_BIG_INDEX_COL);
1080 }
1081
1082 dfield_set_data(dfield, blob_field, len);
1083 } else {
1084 dfield_set_data(dfield, mem_heap_dup(heap, field, len), len);
1085 }
1086
1087 return (DB_SUCCESS);
1088 }
1089
1090 /** Constructs the old PRIMARY KEY and DB_TRX_ID,DB_ROLL_PTR
1091 of a table that is being rebuilt.
1092 @return tuple of PRIMARY KEY,DB_TRX_ID,DB_ROLL_PTR in the rebuilt table,
1093 or NULL if the PRIMARY KEY definition does not change */
1094 const dtuple_t *row_log_table_get_pk(
1095 const rec_t *rec, /*!< in: clustered index leaf page record,
1096 page X-latched */
1097 dict_index_t *index, /*!< in/out: clustered index, S-latched
1098 or X-latched */
1099 const ulint *offsets, /*!< in: rec_get_offsets(rec,index) */
1100 byte *sys, /*!< out: DB_TRX_ID,DB_ROLL_PTR for
1101 row_log_table_delete(), or NULL */
1102 mem_heap_t **heap) /*!< in/out: memory heap where allocated */
1103 {
1104 dtuple_t *tuple = nullptr;
1105 row_log_t *log = index->online_log;
1106
1107 ut_ad(index->is_clustered());
1108 ut_ad(dict_index_is_online_ddl(index));
1109 ut_ad(!dict_index_is_sdi(index));
1110 ut_ad(!offsets || rec_offs_validate(rec, index, offsets));
1111 ut_ad(rw_lock_own_flagged(&index->lock,
1112 RW_LOCK_FLAG_S | RW_LOCK_FLAG_X | RW_LOCK_FLAG_SX));
1113
1114 ut_ad(log);
1115 ut_ad(log->table);
1116
1117 if (log->same_pk) {
1118 /* The PRIMARY KEY columns are unchanged. */
1119 if (sys) {
1120 /* Store the DB_TRX_ID,DB_ROLL_PTR. */
1121 ulint trx_id_offs = index->trx_id_offset;
1122
1123 if (!trx_id_offs) {
1124 ulint pos = index->get_sys_col_pos(DATA_TRX_ID);
1125 ulint len;
1126 ut_ad(pos > 0);
1127
1128 if (!offsets) {
1129 offsets = rec_get_offsets(rec, index, nullptr, pos + 1,
1130 UT_LOCATION_HERE, heap);
1131 }
1132
1133 trx_id_offs = rec_get_nth_field_offs(index, offsets, pos, &len);
1134 ut_ad(len == DATA_TRX_ID_LEN);
1135 }
1136
1137 memcpy(sys, rec + trx_id_offs, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
1138 }
1139
1140 return (nullptr);
1141 }
1142
1143 mutex_enter(&log->mutex);
1144
1145 /* log->error is protected by log->mutex. */
1146 if (log->error == DB_SUCCESS) {
1147 dict_table_t *new_table = log->table;
1148 dict_index_t *new_index = new_table->first_index();
1149 const ulint new_n_uniq = dict_index_get_n_unique(new_index);
1150
1151 if (!*heap) {
1152 ulint size = 0;
1153
1154 if (!offsets) {
1155 size += (1 + REC_OFFS_HEADER_SIZE + index->n_fields) * sizeof *offsets;
1156 }
1157
1158 for (ulint i = 0; i < new_n_uniq; i++) {
1159 size += new_index->get_col(i)->get_min_size();
1160 }
1161
1162 *heap = mem_heap_create(DTUPLE_EST_ALLOC(new_n_uniq + 2) + size,
1163 UT_LOCATION_HERE);
1164 }
1165
1166 if (!offsets) {
1167 offsets = rec_get_offsets(rec, index, nullptr, ULINT_UNDEFINED,
1168 UT_LOCATION_HERE, heap);
1169 }
1170
1171 tuple = dtuple_create(*heap, new_n_uniq + 2);
1172 dict_index_copy_types(tuple, new_index, tuple->n_fields);
1173 dtuple_set_n_fields_cmp(tuple, new_n_uniq);
1174
1175 const ulint max_len = DICT_MAX_FIELD_LEN_BY_FORMAT(new_table);
1176
1177 const page_size_t &page_size = dict_table_page_size(index->table);
1178
1179 for (ulint new_i = 0; new_i < new_n_uniq; new_i++) {
1180 dict_field_t *ifield;
1181 dfield_t *dfield;
1182 ulint prtype;
1183 ulint mbminmaxlen;
1184
1185 ifield = new_index->get_field(new_i);
1186 dfield = dtuple_get_nth_field(tuple, new_i);
1187
1188 const ulint col_no = ifield->col->ind;
1189
1190 if (const dict_col_t *col = row_log_table_get_pk_old_col(
1191 index->table, log->col_map, col_no)) {
1192 ulint i = dict_col_get_clust_pos(col, index);
1193
1194 if (i == ULINT_UNDEFINED) {
1195 log->error = DB_CORRUPTION;
1196 ut_d(ut_error);
1197 ut_o(goto err_exit);
1198 }
1199
1200 log->error = row_log_table_get_pk_col(index, ifield, dfield, *heap, rec,
1201 offsets, i, page_size, max_len);
1202
1203 if (log->error != DB_SUCCESS) {
1204 ut_o(err_exit:) tuple = nullptr;
1205 goto func_exit;
1206 }
1207
1208 mbminmaxlen = col->mbminmaxlen;
1209 prtype = col->prtype;
1210 } else {
1211 /* No matching column was found in the old
1212 table, so this must be an added column.
1213 Copy the default value. */
1214 ut_ad(log->add_cols);
1215
1216 dfield_copy(dfield, dtuple_get_nth_field(log->add_cols, col_no));
1217 mbminmaxlen = dfield->type.mbminmaxlen;
1218 prtype = dfield->type.prtype;
1219 }
1220
1221 ut_ad(!dfield_is_ext(dfield));
1222 ut_ad(!dfield_is_null(dfield));
1223
1224 if (ifield->prefix_len) {
1225 ulint len = dtype_get_at_most_n_mbchars(
1226 prtype, mbminmaxlen, ifield->prefix_len, dfield_get_len(dfield),
1227 static_cast<const char *>(dfield_get_data(dfield)));
1228
1229 ut_ad(len <= dfield_get_len(dfield));
1230 dfield_set_len(dfield, len);
1231 }
1232 }
1233
1234 const byte *trx_roll = rec + row_get_trx_id_offset(index, offsets);
1235
1236 /* Copy the fields, because the fields will be updated
1237 or the record may be moved somewhere else in the B-tree
1238 as part of the upcoming operation. */
1239 if (sys) {
1240 memcpy(sys, trx_roll, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
1241 trx_roll = sys;
1242 } else {
1243 trx_roll = static_cast<const byte *>(
1244 mem_heap_dup(*heap, trx_roll, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN));
1245 }
1246
1247 dfield_set_data(dtuple_get_nth_field(tuple, new_n_uniq), trx_roll,
1248 DATA_TRX_ID_LEN);
1249 dfield_set_data(dtuple_get_nth_field(tuple, new_n_uniq + 1),
1250 trx_roll + DATA_TRX_ID_LEN, DATA_ROLL_PTR_LEN);
1251 }
1252
1253 func_exit:
1254 mutex_exit(&log->mutex);
1255 return (tuple);
1256 }
1257
1258 /** Logs an insert to a table that is being rebuilt.
1259 This will be merged in row_log_table_apply_insert(). */
1260 void row_log_table_insert(
1261 const rec_t *rec, /*!< in: clustered index leaf page record,
1262 page X-latched */
1263 const dtuple_t *ventry, /*!< in: dtuple holding virtual column info */
1264 dict_index_t *index, /*!< in/out: clustered index, S-latched
1265 or X-latched */
1266 const ulint *offsets) /*!< in: rec_get_offsets(rec,index) */
1267 {
1268 row_log_table_low(rec, ventry, nullptr, index, offsets, true, nullptr);
1269 }
1270
1271 /** Notes that a BLOB is being freed during online ALTER TABLE. */
1272 void row_log_table_blob_free(
1273 dict_index_t *index, /*!< in/out: clustered index, X-latched */
1274 page_no_t page_no) /*!< in: starting page number of the BLOB */
1275 {
1276 DBUG_TRACE;
1277
1278 ut_ad(index->is_clustered());
1279 ut_ad(dict_index_is_online_ddl(index));
1280 ut_ad(rw_lock_own_flagged(&index->lock, RW_LOCK_FLAG_X | RW_LOCK_FLAG_SX));
1281 ut_ad(page_no != FIL_NULL);
1282
1283 if (index->online_log->error != DB_SUCCESS) {
1284 return;
1285 }
1286
1287 page_no_map *blobs = index->online_log->blobs;
1288
1289 if (blobs == nullptr) {
1290 index->online_log->blobs = blobs =
1291 ut::new_withkey<page_no_map>(UT_NEW_THIS_FILE_PSI_KEY);
1292 }
1293
1294 #ifdef UNIV_DEBUG
1295 const ulonglong log_pos = index->online_log->tail.total;
1296 #else
1297 #define log_pos /* empty */
1298 #endif /* UNIV_DEBUG */
1299
1300 const page_no_map::value_type v(page_no, row_log_table_blob_t(log_pos));
1301
1302 std::pair<page_no_map::iterator, bool> p = blobs->insert(v);
1303
1304 if (!p.second) {
1305 /* Update the existing mapping. */
1306 ut_ad(p.first->first == page_no);
1307 p.first->second.blob_free(log_pos);
1308 }
1309 #undef log_pos
1310 }
1311
1312 /** Notes that a BLOB is being allocated during online ALTER TABLE. */
1313 void row_log_table_blob_alloc(
1314 dict_index_t *index, /*!< in/out: clustered index, X-latched */
1315 page_no_t page_no) /*!< in: starting page number of the BLOB */
1316 {
1317 DBUG_TRACE;
1318
1319 ut_ad(index->is_clustered());
1320 ut_ad(dict_index_is_online_ddl(index));
1321
1322 ut_ad(rw_lock_own_flagged(&index->lock, RW_LOCK_FLAG_X | RW_LOCK_FLAG_SX));
1323
1324 ut_ad(page_no != FIL_NULL);
1325
1326 if (index->online_log->error != DB_SUCCESS) {
1327 return;
1328 }
1329
1330 /* Only track allocations if the same page has been freed
1331 earlier. Double allocation without a free is not allowed. */
1332 if (page_no_map *blobs = index->online_log->blobs) {
1333 page_no_map::iterator p = blobs->find(page_no);
1334
1335 if (p != blobs->end()) {
1336 ut_ad(p->first == page_no);
1337 p->second.blob_alloc(index->online_log->tail.total);
1338 }
1339 }
1340 }
1341
1342 /** Converts a log record to a table row.
1343 @return converted row, or NULL if the conversion fails */
1344 [[nodiscard]] static const dtuple_t *row_log_table_apply_convert_mrec(
1345 const ddl::mrec_t *mrec, /*!< in: merge record */
1346 dict_index_t *index, /*!< in: index of mrec */
1347 const ulint *offsets, /*!< in: offsets of mrec */
1348 const row_log_t *log, /*!< in: rebuild context */
1349 mem_heap_t *heap, /*!< in/out: memory heap */
1350 dberr_t *error) /*!< out: DB_SUCCESS or
1351 DB_MISSING_HISTORY or
1352 reason of failure */
1353 {
1354 dtuple_t *row;
1355 ulint num_v = dict_table_get_n_v_cols(log->table);
1356
1357 *error = DB_SUCCESS;
1358
1359 /* This is based on row_build(). */
1360 if (log->add_cols) {
1361 row = dtuple_copy(log->add_cols, heap);
1362 /* dict_table_copy_types() would set the fields to NULL */
1363 for (ulint i = 0; i < log->table->get_n_cols(); i++) {
1364 log->table->get_col(i)->copy_type(
1365 dfield_get_type(dtuple_get_nth_field(row, i)));
1366 }
1367 } else {
1368 row = dtuple_create_with_vcol(heap, log->table->get_n_cols(), num_v);
1369 dict_table_copy_types(row, log->table);
1370 }
1371
1372 for (ulint i = 0; i < rec_offs_n_fields(offsets); i++) {
1373 const dict_field_t *ind_field = index->get_field(i);
1374
1375 if (ind_field->prefix_len) {
1376 /* Column prefixes can only occur in key
1377 fields, which cannot be stored externally. For
1378 a column prefix, there should also be the full
1379 field in the clustered index tuple. The row
1380 tuple comprises full fields, not prefixes. */
1381 ut_ad(!rec_offs_nth_extern(index, offsets, i));
1382 continue;
1383 }
1384
1385 const dict_col_t *col = ind_field->col;
1386 if (col->is_instant_dropped()) {
1387 /* Skip instanly dropped column */
1388 continue;
1389 }
1390
1391 ulint col_no = log->col_map[dict_col_get_no(col)];
1392
1393 if (col_no == ULINT_UNDEFINED) {
1394 /* dropped column */
1395 continue;
1396 }
1397
1398 dfield_t *dfield = dtuple_get_nth_field(row, col_no);
1399
1400 ulint len;
1401 const byte *data;
1402
1403 if (rec_offs_nth_extern(index, offsets, i)) {
1404 ut_ad(rec_offs_any_extern(offsets));
1405 rw_lock_x_lock(dict_index_get_lock(index), UT_LOCATION_HERE);
1406
1407 if (const page_no_map *blobs = log->blobs) {
1408 data = rec_get_nth_field(index, mrec, offsets, i, &len);
1409 ut_ad(len >= BTR_EXTERN_FIELD_REF_SIZE);
1410
1411 page_no_t page_no = mach_read_from_4(
1412 data + len - (BTR_EXTERN_FIELD_REF_SIZE - lob::BTR_EXTERN_PAGE_NO));
1413 page_no_map::const_iterator p = blobs->find(page_no);
1414 if (p != blobs->end() && p->second.is_freed(log->head.total)) {
1415 /* This BLOB has been freed.
1416 We must not access the row. */
1417 *error = DB_MISSING_HISTORY;
1418 dfield_set_data(dfield, data, len);
1419 dfield_set_ext(dfield);
1420 goto blob_done;
1421 }
1422 }
1423
1424 /* Reading a LOB of another transaction. The ALTER
1425 TABLE trx is not the owner of this LOB. So instead
1426 of passing current trx, a nullptr is passed for trx.*/
1427 data = lob::btr_rec_copy_externally_stored_field(
1428 nullptr, index, mrec, offsets, dict_table_page_size(index->table), i,
1429 &len, nullptr, false, heap);
1430
1431 ut_a(data);
1432 dfield_set_data(dfield, data, len);
1433 blob_done:
1434 rw_lock_x_unlock(dict_index_get_lock(index));
1435 } else {
1436 data = rec_get_nth_field_instant(mrec, offsets, i, index, &len);
1437 dfield_set_data(dfield, data, len);
1438 }
1439
1440 if (len != UNIV_SQL_NULL && col->mtype == DATA_MYSQL && col->len != len &&
1441 !dict_table_is_comp(log->table)) {
1442 ut_ad(col->len >= len);
1443 if (dict_table_is_comp(index->table)) {
1444 byte *buf = (byte *)mem_heap_alloc(heap, col->len);
1445 memcpy(buf, dfield->data, len);
1446 memset(buf + len, 0x20, col->len - len);
1447
1448 dfield_set_data(dfield, buf, col->len);
1449 } else {
1450 /* field length mismatch should not happen
1451 when rebuilding the redundant row format
1452 table. */
1453 *error = DB_CORRUPTION;
1454 ut_d(ut_error);
1455 ut_o(return (nullptr));
1456 }
1457 }
1458
1459 /* See if any columns were changed to NULL or NOT NULL. */
1460 const dict_col_t *new_col = log->table->get_col(col_no);
1461 ut_ad(new_col->mtype == col->mtype);
1462
1463 /* Assert that prtype matches except for nullability. */
1464 ut_ad(!((new_col->prtype ^ col->prtype) & ~DATA_NOT_NULL));
1465 ut_ad(!((new_col->prtype ^ dfield_get_type(dfield)->prtype) &
1466 ~DATA_NOT_NULL));
1467
1468 if (new_col->prtype == col->prtype) {
1469 continue;
1470 }
1471
1472 if ((new_col->prtype & DATA_NOT_NULL) && dfield_is_null(dfield)) {
1473 /* We got a NULL value for a NOT NULL column. */
1474 *error = DB_INVALID_NULL;
1475 return (nullptr);
1476 }
1477
1478 /* Adjust the DATA_NOT_NULL flag in the parsed row. */
1479 dfield_get_type(dfield)->prtype = new_col->prtype;
1480
1481 ut_ad(new_col->assert_equal(dfield_get_type(dfield)));
1482 }
1483
1484 /* read the virtual column data if any */
1485 if (num_v) {
1486 byte *b = const_cast<byte *>(mrec) + rec_offs_data_size(offsets);
1487 trx_undo_read_v_cols(log->table, b, row, false, true,
1488 &(log->col_map[log->n_old_col]), heap);
1489 }
1490
1491 return (row);
1492 }
1493
1494 /** Tries to insert an entry into a secondary index, which is created for
1495 multi-value field. For each value to be inserted, if a record with exactly
1496 the same fields is found, the other record is necessarily marked deleted.
1497 It is then unmarked. Otherwise, the entry is just inserted to the index.
1498 @param[in] flags undo logging and locking flags
1499 @param[in] index secondary index
1500 @param[in,out] offsets_heap memory heap that can be emptied
1501 @param[in,out] heap memory heap
1502 @param[in,out] entry index entry to insert
1503 @param[in] trx_id PAGE_MAX_TRX_ID during row_log_table_apply(),
1504 or trx_id when undo log is disabled during
1505 alter copy operation or 0
1506 @param[in] thr query thread
1507 @retval DB_SUCCESS on success
1508 @retval DB_LOCK_WAIT on lock wait when !(flags & BTR_NO_LOCKING_FLAG)
1509 @retval DB_FAIL if retry with BTR_MODIFY_TREE is needed
1510 @return error code */
1511 [[nodiscard]] static dberr_t apply_insert_multi_value(
1512 uint32_t flags, dict_index_t *index, mem_heap_t *offsets_heap,
1513 mem_heap_t *heap, dtuple_t *entry, trx_id_t trx_id, que_thr_t *thr) {
1514 dberr_t err = DB_SUCCESS;
1515 Multi_value_entry_builder_insert mv_entry_builder(index, entry);
1516
1517 for (dtuple_t *mv_entry = mv_entry_builder.begin(); mv_entry != nullptr;
1518 mv_entry = mv_entry_builder.next()) {
1519 err =
1520 row_ins_sec_index_entry_low(flags, BTR_MODIFY_TREE, index, offsets_heap,
1521 heap, mv_entry, trx_id, thr, false);
1522 if (err != DB_SUCCESS) {
1523 break;
1524 }
1525 }
1526
1527 return (err);
1528 }
1529
1530 /** Replays an insert operation on a table that was rebuilt.
1531 @return DB_SUCCESS or error code */
1532 [[nodiscard]] static dberr_t row_log_table_apply_insert_low(
1533 que_thr_t *thr, /*!< in: query graph */
1534 const dtuple_t *row, /*!< in: table row
1535 in the old table definition */
1536 trx_id_t trx_id, /*!< in: trx_id of the row */
1537 mem_heap_t *offsets_heap, /*!< in/out: memory heap
1538 that can be emptied */
1539 mem_heap_t *heap, /*!< in/out: memory heap */
1540 ddl::Dup *dup) /*!< in/out: for reporting
1541 duplicate key errors */
1542 {
1543 dberr_t error;
1544 dtuple_t *entry;
1545 const row_log_t *log = dup->m_index->online_log;
1546 dict_index_t *index = log->table->first_index();
1547 ulint n_index = 0;
1548
1549 ut_ad(dtuple_validate(row));
1550 ut_ad(trx_id);
1551
1552 DBUG_PRINT("ib_alter_table",
1553 ("insert table " IB_ID_FMT "(index " IB_ID_FMT "): %s",
1554 index->table->id, index->id, rec_printer(row).str().c_str()));
1555
1556 static const uint32_t flags = (BTR_CREATE_FLAG | BTR_NO_LOCKING_FLAG |
1557 BTR_NO_UNDO_LOG_FLAG | BTR_KEEP_SYS_FLAG);
1558
1559 entry = row_build_index_entry(row, nullptr, index, heap);
1560
1561 error = row_ins_clust_index_entry_low(flags, BTR_MODIFY_TREE, index,
1562 index->n_uniq, entry, thr, false);
1563
1564 switch (error) {
1565 case DB_SUCCESS:
1566 break;
1567 case DB_SUCCESS_LOCKED_REC:
1568 /* The row had already been copied to the table. */
1569 return (DB_SUCCESS);
1570 default:
1571 return (error);
1572 }
1573
1574 do {
1575 n_index++;
1576 index = index->next();
1577 if (!index) {
1578 break;
1579 }
1580
1581 if (index->type & DICT_FTS) {
1582 continue;
1583 }
1584
1585 entry = row_build_index_entry(row, nullptr, index, heap);
1586
1587 if (index->is_multi_value()) {
1588 error = apply_insert_multi_value(flags, index, offsets_heap, heap, entry,
1589 trx_id, thr);
1590 } else {
1591 error = row_ins_sec_index_entry_low(flags, BTR_MODIFY_TREE, index,
1592 offsets_heap, heap, entry, trx_id,
1593 thr, false);
1594 }
1595
1596 /* Report correct index name for duplicate key error. */
1597 if (error == DB_DUPLICATE_KEY) {
1598 thr_get_trx(thr)->error_key_num = n_index;
1599 }
1600
1601 } while (error == DB_SUCCESS);
1602
1603 return (error);
1604 }
1605
1606 /** Replays an insert operation on a table that was rebuilt.
1607 @return DB_SUCCESS or error code */
1608 [[nodiscard]] static dberr_t row_log_table_apply_insert(
1609 que_thr_t *thr, /*!< in: query graph */
1610 const ddl::mrec_t *mrec, /*!< in: record to insert */
1611 const ulint *offsets, /*!< in: offsets of mrec */
1612 mem_heap_t *offsets_heap, /*!< in/out: memory heap
1613 that can be emptied */
1614 mem_heap_t *heap, /*!< in/out: memory heap */
1615 ddl::Dup *dup, /*!< in/out: for reporting
1616 duplicate key errors */
1617 trx_id_t trx_id) /*!< in: DB_TRX_ID of mrec */
1618 {
1619 const row_log_t *log = dup->m_index->online_log;
1620 dberr_t error;
1621 const dtuple_t *row = row_log_table_apply_convert_mrec(
1622 mrec, dup->m_index, offsets, log, heap, &error);
1623
1624 switch (error) {
1625 case DB_MISSING_HISTORY:
1626 ut_ad(log->blobs);
1627 /* Because some BLOBs are missing, we know that the
1628 transaction was rolled back later (a rollback of
1629 an insert can free BLOBs).
1630 We can simply skip the insert: the subsequent
1631 ROW_T_DELETE will be ignored, or a ROW_T_UPDATE will
1632 be interpreted as ROW_T_INSERT. */
1633 return (DB_SUCCESS);
1634 case DB_SUCCESS:
1635 ut_ad(row != nullptr);
1636 break;
1637 default:
1638 ut_d(ut_error);
1639 [[fallthrough]];
1640 case DB_INVALID_NULL:
1641 ut_ad(row == nullptr);
1642 return (error);
1643 }
1644
1645 error =
1646 row_log_table_apply_insert_low(thr, row, trx_id, offsets_heap, heap, dup);
1647 if (error != DB_SUCCESS) {
1648 /* Report the erroneous row using the new
1649 version of the table. */
1650 innobase_row_to_mysql(dup->m_table, log->table, row);
1651 }
1652 return (error);
1653 }
1654
1655 /** Delete a record from a secondary index.
1656 @param[in] index secondary index
1657 @param[in] entry entry to delete
1658 @param[in,out] pcur B-tree cursor
1659 @return DB_SUCCESS or error code */
1660 [[nodiscard]] static inline dberr_t row_log_table_delete_sec(
1661 dict_index_t *index, const dtuple_t *entry, btr_pcur_t *pcur) {
1662 dberr_t error;
1663 mtr_t mtr;
1664
1665 ut_ad(!index->is_clustered());
1666
1667 mtr_start(&mtr);
1668
1669 pcur->open(index, 0, entry, PAGE_CUR_LE,
1670 BTR_MODIFY_TREE | BTR_LATCH_FOR_DELETE, &mtr, UT_LOCATION_HERE);
1671 #ifdef UNIV_DEBUG
1672 switch (pcur->get_btr_cur()->flag) {
1673 case BTR_CUR_UNSET:
1674 case BTR_CUR_DELETE_REF:
1675 case BTR_CUR_DEL_MARK_IBUF:
1676 case BTR_CUR_DELETE_IBUF:
1677 case BTR_CUR_INSERT_TO_IBUF:
1678 /* We did not request buffering. */
1679 break;
1680 case BTR_CUR_HASH:
1681 case BTR_CUR_HASH_NOT_ATTEMPTED:
1682 case BTR_CUR_HASH_FAIL:
1683 case BTR_CUR_BINARY:
1684 goto flag_ok;
1685 }
1686 ut_d(ut_error);
1687 flag_ok:
1688 #endif /* UNIV_DEBUG */
1689
1690 if (page_rec_is_infimum(pcur->get_rec()) ||
1691 pcur->get_low_match() < index->n_uniq) {
1692 /* All secondary index entries should be
1693 found, because new_table is being modified by
1694 this thread only, and all indexes should be
1695 updated in sync. */
1696 mtr_commit(&mtr);
1697 return (DB_INDEX_CORRUPT);
1698 }
1699
1700 btr_cur_pessimistic_delete(&error, false, pcur->get_btr_cur(),
1701 BTR_CREATE_FLAG, false, 0, 0, 0, &mtr, pcur,
1702 nullptr);
1703 mtr_commit(&mtr);
1704
1705 return (error);
1706 }
1707
1708 /** Deletes a record from a multi-value index.
1709 @param[in] row row to delete
1710 @param[in] ext external data
1711 @param[in] index multi-value index
1712 @param[in,out] pcur B-tree cursor
1713 @param[in,out] heap memory heap
1714 @return DB_SUCCESS or error code */
1715 [[nodiscard]] static inline dberr_t apply_delete_multi_value(
1716 const dtuple_t *row, row_ext_t *ext, dict_index_t *index, btr_pcur_t *pcur,
1717 mem_heap_t *heap) {
1718 dberr_t err = DB_SUCCESS;
1719 Multi_value_entry_builder_normal mv_entry_builder(row, ext, index, heap, true,
1720 false);
1721
1722 ut_ad(index->is_multi_value());
1723
1724 for (dtuple_t *entry = mv_entry_builder.begin(); entry != nullptr;
1725 entry = mv_entry_builder.next()) {
1726 err = row_log_table_delete_sec(index, entry, pcur);
1727 if (err != DB_SUCCESS) {
1728 return (err);
1729 }
1730 }
1731
1732 return (err);
1733 }
1734
1735 /** Deletes a record from a table that is being rebuilt.
1736 @return DB_SUCCESS or error code */
1737 [[nodiscard]] static dberr_t row_log_table_apply_delete_low(
1738 btr_pcur_t *pcur, /*!< in/out: B-tree cursor,
1739 will be trashed */
1740 const dtuple_t *ventry, /*!< in: dtuple holding
1741 virtual column info */
1742 const ulint *offsets, /*!< in: offsets on pcur */
1743 mem_heap_t *heap, /*!< in/out: memory heap */
1744 mtr_t *mtr) /*!< in/out: mini-transaction,
1745 will be committed */
1746 {
1747 dberr_t error;
1748 row_ext_t *ext = nullptr;
1749 dtuple_t *row;
1750 dict_index_t *index = pcur->get_btr_cur()->index;
1751
1752 ut_ad(index->is_clustered());
1753
1754 DBUG_PRINT(
1755 "ib_alter_table",
1756 ("delete table " IB_ID_FMT "(index " IB_ID_FMT "): %s", index->table->id,
1757 index->id, rec_printer(pcur->get_rec(), offsets).str().c_str()));
1758
1759 if (index->next()) {
1760 /* Build a row template for purging secondary index entries. */
1761 row = row_build(ROW_COPY_DATA, index, pcur->get_rec(), offsets, nullptr,
1762 nullptr, nullptr, &ext, heap);
1763 if (ventry) {
1764 dtuple_copy_v_fields(row, ventry);
1765 }
1766 } else {
1767 row = nullptr;
1768 }
1769
1770 btr_cur_pessimistic_delete(&error, false, pcur->get_btr_cur(),
1771 BTR_CREATE_FLAG, false, 0, 0, 0, mtr, pcur,
1772 nullptr);
1773 mtr_commit(mtr);
1774
1775 if (error != DB_SUCCESS) {
1776 return (error);
1777 }
1778
1779 while ((index = index->next()) != nullptr) {
1780 if (index->type & DICT_FTS) {
1781 continue;
1782 }
1783
1784 if (index->is_multi_value()) {
1785 error = apply_delete_multi_value(row, ext, index, pcur, heap);
1786 if (error == DB_INDEX_CORRUPT) {
1787 return (error);
1788 }
1789 continue;
1790 }
1791
1792 const dtuple_t *entry = row_build_index_entry(row, ext, index, heap);
1793
1794 if (row_log_table_delete_sec(index, entry, pcur) == DB_INDEX_CORRUPT) {
1795 return (DB_INDEX_CORRUPT);
1796 }
1797 }
1798
1799 return (error);
1800 }
1801
1802 /** Replays a delete operation on a table that was rebuilt.
1803 @return DB_SUCCESS or error code */
1804 [[nodiscard]] static dberr_t row_log_table_apply_delete(
1805 ulint trx_id_col, /*!< in: position of
1806 DB_TRX_ID in the new
1807 clustered index */
1808 const ddl::mrec_t *mrec, /*!< in: merge record */
1809 const ulint *moffsets, /*!< in: offsets of mrec */
1810 mem_heap_t *offsets_heap, /*!< in/out: memory heap
1811 that can be emptied */
1812 mem_heap_t *heap, /*!< in/out: memory heap */
1813 const row_log_t *log) /*!< in: online log */
1814 {
1815 dict_table_t *new_table = log->table;
1816 dict_index_t *index = new_table->first_index();
1817 dtuple_t *old_pk;
1818 mtr_t mtr;
1819 btr_pcur_t pcur;
1820 ulint *offsets;
1821 ulint num_v = new_table->n_v_cols;
1822
1823 ut_ad(rec_offs_n_fields(moffsets) == dict_index_get_n_unique(index) + 2U);
1824 ut_ad(!rec_offs_any_extern(moffsets));
1825
1826 /* Convert the row to a search tuple. */
1827 old_pk = dtuple_create_with_vcol(heap, index->n_uniq, num_v);
1828 dict_index_copy_types(old_pk, index, index->n_uniq);
1829
1830 if (num_v) {
1831 dict_table_copy_v_types(old_pk, index->table);
1832 }
1833
1834 for (ulint i = 0; i < index->n_uniq; i++) {
1835 ulint len;
1836 const void *field;
1837 field = rec_get_nth_field(nullptr, mrec, moffsets, i, &len);
1838 ut_ad(rec_field_not_null_not_add_col_def(len));
1839 dfield_set_data(dtuple_get_nth_field(old_pk, i), field, len);
1840 }
1841
1842 mtr_start(&mtr);
1843
1844 pcur.open(index, 0, old_pk, PAGE_CUR_LE,
1845 BTR_MODIFY_TREE | BTR_LATCH_FOR_DELETE, &mtr, UT_LOCATION_HERE);
1846 const auto guard = create_scope_guard([&pcur]() { pcur.close(); });
1847 #ifdef UNIV_DEBUG
1848 switch (pcur.get_btr_cur()->flag) {
1849 case BTR_CUR_UNSET:
1850 case BTR_CUR_DELETE_REF:
1851 case BTR_CUR_DEL_MARK_IBUF:
1852 case BTR_CUR_DELETE_IBUF:
1853 case BTR_CUR_INSERT_TO_IBUF:
1854 /* We did not request buffering. */
1855 break;
1856 case BTR_CUR_HASH:
1857 case BTR_CUR_HASH_NOT_ATTEMPTED:
1858 case BTR_CUR_HASH_FAIL:
1859 case BTR_CUR_BINARY:
1860 goto flag_ok;
1861 }
1862 ut_d(ut_error);
1863 flag_ok:
1864 #endif /* UNIV_DEBUG */
1865
1866 if (page_rec_is_infimum(pcur.get_rec()) ||
1867 pcur.get_low_match() < index->n_uniq) {
1868 all_done:
1869 mtr_commit(&mtr);
1870 /* The record was not found. All done. */
1871 /* This should only happen when an earlier
1872 ROW_T_INSERT was skipped or
1873 ROW_T_UPDATE was interpreted as ROW_T_DELETE
1874 due to BLOBs having been freed by rollback. */
1875 return (DB_SUCCESS);
1876 }
1877
1878 offsets = rec_get_offsets(pcur.get_rec(), index, nullptr, ULINT_UNDEFINED,
1879 UT_LOCATION_HERE, &offsets_heap);
1880 #if defined UNIV_DEBUG || defined UNIV_BLOB_LIGHT_DEBUG
1881 ut_a(!rec_offs_any_null_extern(index, pcur.get_rec(), offsets));
1882 #endif /* UNIV_DEBUG || UNIV_BLOB_LIGHT_DEBUG */
1883
1884 /* Only remove the record if DB_TRX_ID,DB_ROLL_PTR match. */
1885
1886 {
1887 ulint len;
1888 const byte *mrec_trx_id =
1889 rec_get_nth_field(nullptr, mrec, moffsets, trx_id_col, &len);
1890 ut_ad(len == DATA_TRX_ID_LEN);
1891 const byte *rec_trx_id =
1892 rec_get_nth_field(nullptr, pcur.get_rec(), offsets, trx_id_col, &len);
1893 ut_ad(len == DATA_TRX_ID_LEN);
1894
1895 ut_ad(rec_get_nth_field(nullptr, mrec, moffsets, trx_id_col + 1, &len) ==
1896 mrec_trx_id + DATA_TRX_ID_LEN);
1897 ut_ad(len == DATA_ROLL_PTR_LEN);
1898 ut_ad(rec_get_nth_field(nullptr, pcur.get_rec(), offsets, trx_id_col + 1,
1899 &len) == rec_trx_id + DATA_TRX_ID_LEN);
1900 ut_ad(len == DATA_ROLL_PTR_LEN);
1901
1902 if (memcmp(mrec_trx_id, rec_trx_id, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)) {
1903 /* The ROW_T_DELETE was logged for a different
1904 PRIMARY KEY,DB_TRX_ID,DB_ROLL_PTR.
1905 This is possible if a ROW_T_INSERT was skipped
1906 or a ROW_T_UPDATE was interpreted as ROW_T_DELETE
1907 because some BLOBs were missing due to
1908 (1) rolling back the initial insert, or
1909 (2) purging the BLOB for a later ROW_T_DELETE
1910 (3) purging 'old values' for a later ROW_T_UPDATE
1911 or ROW_T_DELETE. */
1912 ut_ad(!log->same_pk);
1913 goto all_done;
1914 }
1915 }
1916
1917 if (num_v) {
1918 byte *b = (byte *)mrec + rec_offs_data_size(moffsets);
1919 trx_undo_read_v_cols(log->table, b, old_pk, false, true,
1920 &(log->col_map[log->n_old_col]), heap);
1921 }
1922
1923 return (row_log_table_apply_delete_low(&pcur, old_pk, offsets, heap, &mtr));
1924 }
1925
1926 /** Replays an update operation on the multi-value index.
1927 @param[in] index multi-value index
1928 @param[in] n_index the sequence of the index
1929 @param[in] old_row old row of the update
1930 @param[in] old_ext old external data of the update
1931 @param[in] new_row new row of the update
1932 @param[in] non_mv_upd true if any non-multi-value field on the index
1933 gets updated too
1934 @param[in] trx_id transaction id of the update
1935 @param[in] thr query graph
1936 @param[in,out] offsets_heap memory heap that can be emptied
1937 @param[in,out] heap memory heap
1938 @return DB_SUCCESS or error code */
1939 [[nodiscard]] static dberr_t apply_update_multi_value(
1940 dict_index_t *index, uint32_t n_index, const dtuple_t *old_row,
1941 row_ext_t *old_ext, const dtuple_t *new_row, bool non_mv_upd,
1942 trx_id_t trx_id, que_thr_t *thr, mem_heap_t *offsets_heap,
1943 mem_heap_t *heap) {
1944 btr_pcur_t pcur;
1945 mtr_t mtr;
1946 dberr_t error = DB_SUCCESS;
1947
1948 ut_ad(index->is_multi_value());
1949
1950 /* Do the same with other secondary index handling in
1951 row_log_table_apply_update() */
1952 {
1953 Multi_value_entry_builder_normal mv_entry_builder(old_row, old_ext, index,
1954 heap, true, !non_mv_upd);
1955
1956 for (dtuple_t *entry = mv_entry_builder.begin(); entry != nullptr;
1957 entry = mv_entry_builder.next()) {
1958 mtr_start(&mtr);
1959 if (row_search_index_entry(index, entry, BTR_MODIFY_TREE, &pcur, &mtr) !=
1960 ROW_FOUND) {
1961 mtr_commit(&mtr);
1962 ut_d(ut_error);
1963 ut_o(return (DB_CORRUPTION));
1964 }
1965
1966 btr_cur_pessimistic_delete(&error, false, pcur.get_btr_cur(),
1967 BTR_CREATE_FLAG, false, 0, 0, 0, &mtr, &pcur,
1968 nullptr);
1969
1970 if (error != DB_SUCCESS) {
1971 return (error);
1972 }
1973
1974 mtr_commit(&mtr);
1975 }
1976 }
1977
1978 {
1979 Multi_value_entry_builder_normal mv_entry_builder(new_row, nullptr, index,
1980 heap, true, !non_mv_upd);
1981
1982 for (dtuple_t *entry = mv_entry_builder.begin(); entry != nullptr;
1983 entry = mv_entry_builder.next()) {
1984 error = row_ins_sec_index_entry_low(
1985 BTR_CREATE_FLAG | BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG |
1986 BTR_KEEP_SYS_FLAG,
1987 BTR_MODIFY_TREE, index, offsets_heap, heap, entry, trx_id, thr,
1988 false);
1989
1990 if (error == DB_DUPLICATE_KEY) {
1991 thr_get_trx(thr)->error_key_num = n_index;
1992 }
1993
1994 if (error != DB_SUCCESS) {
1995 return (error);
1996 }
1997 }
1998 }
1999
2000 return (error);
2001 }
2002
2003 /** Replays an update operation on a table that was rebuilt.
2004 @return DB_SUCCESS or error code */
2005 [[nodiscard]] static dberr_t row_log_table_apply_update(
2006 que_thr_t *thr, /*!< in: query graph */
2007 ulint new_trx_id_col, /*!< in: position of
2008 DB_TRX_ID in the new
2009 clustered index */
2010 const ddl::mrec_t *mrec, /*!< in: new value */
2011 const ulint *offsets, /*!< in: offsets of mrec */
2012 mem_heap_t *offsets_heap, /*!< in/out: memory heap
2013 that can be emptied */
2014 mem_heap_t *heap, /*!< in/out: memory heap */
2015 ddl::Dup *dup, /*!< in/out: for reporting
2016 duplicate key errors */
2017 trx_id_t trx_id, /*!< in: DB_TRX_ID of mrec */
2018 const dtuple_t *old_pk) /*!< in: PRIMARY KEY and
2019 DB_TRX_ID,DB_ROLL_PTR
2020 of the old value,
2021 or PRIMARY KEY if same_pk */
2022 {
2023 const row_log_t *log = dup->m_index->online_log;
2024 const dtuple_t *row;
2025 dict_index_t *index = log->table->first_index();
2026 mtr_t mtr;
2027 btr_pcur_t pcur;
2028 dberr_t error;
2029 bool non_mv_upd = true;
2030 uint32_t n_index = 0;
2031 trx_t *trx = thr_get_trx(thr);
2032
2033 ut_ad(dtuple_get_n_fields_cmp(old_pk) == dict_index_get_n_unique(index));
2034 ut_ad(dtuple_get_n_fields(old_pk) ==
2035 dict_index_get_n_unique(index) + (log->same_pk ? 0U : 2U));
2036
2037 row = row_log_table_apply_convert_mrec(mrec, dup->m_index, offsets, log, heap,
2038 &error);
2039
2040 switch (error) {
2041 case DB_MISSING_HISTORY:
2042 /* The record contained BLOBs that are now missing. */
2043 ut_ad(log->blobs);
2044 /* Whether or not we are updating the PRIMARY KEY, we
2045 know that there should be a subsequent
2046 ROW_T_DELETE for rolling back a preceding ROW_T_INSERT,
2047 overriding this ROW_T_UPDATE record. (*1)
2048
2049 This allows us to interpret this ROW_T_UPDATE
2050 as ROW_T_DELETE.
2051
2052 When applying the subsequent ROW_T_DELETE, no matching
2053 record will be found. */
2054 [[fallthrough]];
2055 case DB_SUCCESS:
2056 ut_ad(row != nullptr);
2057 break;
2058 default:
2059 ut_d(ut_error);
2060 [[fallthrough]];
2061 case DB_INVALID_NULL:
2062 ut_ad(row == nullptr);
2063 return (error);
2064 }
2065
2066 mtr_start(&mtr);
2067
2068 pcur.open(index, 0, old_pk, PAGE_CUR_LE, BTR_MODIFY_TREE, &mtr,
2069 UT_LOCATION_HERE);
2070 const auto guard = create_scope_guard([&pcur]() { pcur.close(); });
2071 #ifdef UNIV_DEBUG
2072 switch (pcur.get_btr_cur()->flag) {
2073 case BTR_CUR_UNSET:
2074 case BTR_CUR_DELETE_REF:
2075 case BTR_CUR_DEL_MARK_IBUF:
2076 case BTR_CUR_DELETE_IBUF:
2077 case BTR_CUR_INSERT_TO_IBUF:
2078 ut_d(ut_error); /* We did not request buffering. */
2079 case BTR_CUR_HASH:
2080 case BTR_CUR_HASH_NOT_ATTEMPTED:
2081 case BTR_CUR_HASH_FAIL:
2082 case BTR_CUR_BINARY:
2083 break;
2084 }
2085 #endif /* UNIV_DEBUG */
2086
2087 if (page_rec_is_infimum(pcur.get_rec()) ||
2088 pcur.get_low_match() < index->n_uniq) {
2089 /* The record was not found. This should only happen
2090 when an earlier ROW_T_INSERT or ROW_T_UPDATE was
2091 diverted because BLOBs were freed when the insert was
2092 later rolled back. */
2093
2094 ut_ad(log->blobs);
2095
2096 if (error == DB_SUCCESS) {
2097 /* An earlier ROW_T_INSERT could have been
2098 skipped because of a missing BLOB, like this:
2099
2100 BEGIN;
2101 INSERT INTO t SET blob_col='blob value';
2102 UPDATE t SET blob_col='';
2103 ROLLBACK;
2104
2105 This would generate the following records:
2106 ROW_T_INSERT (referring to 'blob value')
2107 ROW_T_UPDATE
2108 ROW_T_UPDATE (referring to 'blob value')
2109 ROW_T_DELETE
2110 [ROLLBACK removes the 'blob value']
2111
2112 The ROW_T_INSERT would have been skipped
2113 because of a missing BLOB. Now we are
2114 executing the first ROW_T_UPDATE.
2115 The second ROW_T_UPDATE (for the ROLLBACK)
2116 would be interpreted as ROW_T_DELETE, because
2117 the BLOB would be missing.
2118
2119 We could probably assume that the transaction
2120 has been rolled back and simply skip the
2121 'insert' part of this ROW_T_UPDATE record.
2122 However, there might be some complex scenario
2123 that could interfere with such a shortcut.
2124 So, we will insert the row (and risk
2125 introducing a bogus duplicate key error
2126 for the ALTER TABLE), and a subsequent
2127 ROW_T_UPDATE or ROW_T_DELETE will delete it. */
2128 mtr_commit(&mtr);
2129 error = row_log_table_apply_insert_low(thr, row, trx_id, offsets_heap,
2130 heap, dup);
2131 } else {
2132 /* Some BLOBs are missing, so we are interpreting
2133 this ROW_T_UPDATE as ROW_T_DELETE (see *1).
2134 Because the record was not found, we do nothing. */
2135 ut_ad(error == DB_MISSING_HISTORY);
2136 error = DB_SUCCESS;
2137 func_exit:
2138 mtr_commit(&mtr);
2139 }
2140 func_exit_committed:
2141 ut_ad(mtr.has_committed());
2142
2143 if (error != DB_SUCCESS) {
2144 /* Report the erroneous row using the new
2145 version of the table. */
2146 innobase_row_to_mysql(dup->m_table, log->table, row);
2147 }
2148
2149 return (error);
2150 }
2151
2152 /* Prepare to update (or delete) the record. */
2153 ulint *cur_offsets =
2154 rec_get_offsets(pcur.get_rec(), index, nullptr, ULINT_UNDEFINED,
2155 UT_LOCATION_HERE, &offsets_heap);
2156
2157 if (!log->same_pk) {
2158 /* Only update the record if DB_TRX_ID,DB_ROLL_PTR match what
2159 was buffered. */
2160 ulint len;
2161 const void *rec_trx_id = rec_get_nth_field(
2162 nullptr, pcur.get_rec(), cur_offsets, index->n_uniq, &len);
2163 ut_ad(len == DATA_TRX_ID_LEN);
2164 ut_ad(dtuple_get_nth_field(old_pk, index->n_uniq)->len == DATA_TRX_ID_LEN);
2165 ut_ad(dtuple_get_nth_field(old_pk, index->n_uniq + 1)->len ==
2166 DATA_ROLL_PTR_LEN);
2167 ut_ad(DATA_TRX_ID_LEN +
2168 static_cast<const char *>(
2169 dtuple_get_nth_field(old_pk, index->n_uniq)->data) ==
2170 dtuple_get_nth_field(old_pk, index->n_uniq + 1)->data);
2171 if (memcmp(rec_trx_id, dtuple_get_nth_field(old_pk, index->n_uniq)->data,
2172 DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)) {
2173 /* The ROW_T_UPDATE was logged for a different
2174 DB_TRX_ID,DB_ROLL_PTR. This is possible if an
2175 earlier ROW_T_INSERT or ROW_T_UPDATE was diverted
2176 because some BLOBs were missing due to rolling
2177 back the initial insert or due to purging
2178 the old BLOB values of an update. */
2179 ut_ad(log->blobs);
2180 if (error != DB_SUCCESS) {
2181 ut_ad(error == DB_MISSING_HISTORY);
2182 /* Some BLOBs are missing, so we are
2183 interpreting this ROW_T_UPDATE as
2184 ROW_T_DELETE (see *1).
2185 Because this is a different row,
2186 we will do nothing. */
2187 error = DB_SUCCESS;
2188 } else {
2189 /* Because the user record is missing due to
2190 BLOBs that were missing when processing
2191 an earlier log record, we should
2192 interpret the ROW_T_UPDATE as ROW_T_INSERT.
2193 However, there is a different user record
2194 with the same PRIMARY KEY value already. */
2195 error = DB_DUPLICATE_KEY;
2196 }
2197
2198 goto func_exit;
2199 }
2200 }
2201
2202 if (error != DB_SUCCESS) {
2203 ut_ad(error == DB_MISSING_HISTORY);
2204 ut_ad(log->blobs);
2205 /* Some BLOBs are missing, so we are interpreting
2206 this ROW_T_UPDATE as ROW_T_DELETE (see *1). */
2207 error =
2208 row_log_table_apply_delete_low(&pcur, old_pk, cur_offsets, heap, &mtr);
2209 goto func_exit_committed;
2210 }
2211
2212 /** It allows to create tuple with virtual column information. */
2213 dtuple_t *entry = row_build_index_entry_low(row, nullptr, index, heap,
2214 ROW_BUILD_FOR_INSERT);
2215 upd_t *update = row_upd_build_difference_binary(index, entry, pcur.get_rec(),
2216 cur_offsets, false, nullptr,
2217 heap, dup->m_table, &error);
2218 if (error != DB_SUCCESS) {
2219 goto func_exit;
2220 }
2221
2222 if (!update->n_fields) {
2223 /* Nothing to do. */
2224 goto func_exit;
2225 }
2226
2227 const bool pk_updated =
2228 upd_get_nth_field(update, 0)->field_no < new_trx_id_col;
2229
2230 if (pk_updated || rec_offs_any_extern(cur_offsets)) {
2231 /* If the record contains any externally stored
2232 columns, perform the update by delete and insert,
2233 because we will not write any undo log that would
2234 allow purge to free any orphaned externally stored
2235 columns. */
2236
2237 if (pk_updated && log->same_pk) {
2238 /* The ROW_T_UPDATE log record should only be
2239 written when the PRIMARY KEY fields of the
2240 record did not change in the old table. We
2241 can only get a change of PRIMARY KEY columns
2242 in the rebuilt table if the PRIMARY KEY was
2243 redefined (!same_pk). */
2244 error = DB_CORRUPTION;
2245 ut_d(ut_error);
2246 ut_o(goto func_exit);
2247 }
2248
2249 error =
2250 row_log_table_apply_delete_low(&pcur, old_pk, cur_offsets, heap, &mtr);
2251 ut_ad(mtr.has_committed());
2252
2253 if (error == DB_SUCCESS) {
2254 error = row_log_table_apply_insert_low(thr, row, trx_id, offsets_heap,
2255 heap, dup);
2256 }
2257
2258 goto func_exit_committed;
2259 }
2260
2261 dtuple_t *old_row;
2262 row_ext_t *old_ext;
2263
2264 if (index->next() != nullptr) {
2265 /* Construct the row corresponding to the old value of
2266 the record. */
2267 old_row = row_build(ROW_COPY_DATA, index, pcur.get_rec(), cur_offsets,
2268 nullptr, nullptr, nullptr, &old_ext, heap);
2269 ut_ad(old_row);
2270
2271 DBUG_PRINT("ib_alter_table",
2272 ("update table " IB_ID_FMT "(index " IB_ID_FMT "): %s to %s",
2273 index->table->id, index->id, rec_printer(old_row).str().c_str(),
2274 rec_printer(row).str().c_str()));
2275 } else {
2276 old_row = nullptr;
2277 old_ext = nullptr;
2278 }
2279
2280 big_rec_t *big_rec;
2281
2282 error = btr_cur_pessimistic_update(
2283 BTR_CREATE_FLAG | BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG |
2284 BTR_KEEP_SYS_FLAG | BTR_KEEP_POS_FLAG,
2285 pcur.get_btr_cur(), &cur_offsets, &offsets_heap, heap, &big_rec, update,
2286 0, thr, 0, 0, &mtr);
2287
2288 if (big_rec) {
2289 if (error == DB_SUCCESS) {
2290 error = lob::btr_store_big_rec_extern_fields(
2291 trx, &pcur, update, cur_offsets, big_rec, &mtr, lob::OPCODE_UPDATE);
2292 }
2293
2294 dtuple_big_rec_free(big_rec);
2295 }
2296 bool vfields_copied = false;
2297 while ((index = index->next()) != nullptr) {
2298 n_index++;
2299 if (error != DB_SUCCESS) {
2300 break;
2301 }
2302
2303 if (index->type & DICT_FTS) {
2304 continue;
2305 }
2306
2307 if (!vfields_copied && dict_index_has_virtual(index)) {
2308 dtuple_copy_v_fields(old_row, old_pk);
2309 vfields_copied = true;
2310 }
2311
2312 if (!row_upd_changes_ord_field_binary(
2313 index, update, thr, old_row, nullptr,
2314 (index->is_multi_value() ? &non_mv_upd : nullptr))) {
2315 continue;
2316 }
2317
2318 mtr_commit(&mtr);
2319
2320 if (index->is_multi_value()) {
2321 error =
2322 apply_update_multi_value(index, n_index, old_row, old_ext, row,
2323 non_mv_upd, trx_id, thr, offsets_heap, heap);
2324 mtr_start(&mtr);
2325 continue;
2326 }
2327
2328 entry = row_build_index_entry(old_row, old_ext, index, heap);
2329 if (!entry) {
2330 ut_d(ut_error);
2331 ut_o(return (DB_CORRUPTION));
2332 }
2333
2334 mtr_start(&mtr);
2335
2336 if (ROW_FOUND !=
2337 row_search_index_entry(index, entry, BTR_MODIFY_TREE, &pcur, &mtr)) {
2338 error = DB_CORRUPTION;
2339 ut_d(ut_error);
2340 ut_o(break);
2341 }
2342
2343 btr_cur_pessimistic_delete(&error, false, pcur.get_btr_cur(),
2344 BTR_CREATE_FLAG, false, 0, 0, 0, &mtr, &pcur,
2345 nullptr);
2346
2347 if (error != DB_SUCCESS) {
2348 break;
2349 }
2350
2351 mtr_commit(&mtr);
2352
2353 entry = row_build_index_entry(row, nullptr, index, heap);
2354 error = row_ins_sec_index_entry_low(
2355 BTR_CREATE_FLAG | BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG |
2356 BTR_KEEP_SYS_FLAG,
2357 BTR_MODIFY_TREE, index, offsets_heap, heap, entry, trx_id, thr, false);
2358
2359 /* Report correct index name for duplicate key error. */
2360 if (error == DB_DUPLICATE_KEY) {
2361 thr_get_trx(thr)->error_key_num = n_index;
2362 }
2363
2364 mtr_start(&mtr);
2365 }
2366
2367 goto func_exit;
2368 }
2369
2370 /** Applies an operation to a table that was rebuilt.
2371 @return NULL on failure (mrec corruption) or when out of data;
2372 pointer to next record on success */
2373 [[nodiscard]] static const ddl::mrec_t *row_log_table_apply_op(
2374 que_thr_t *thr, /*!< in: query graph */
2375 ulint trx_id_col, /*!< in: position of
2376 DB_TRX_ID in old index */
2377 ulint new_trx_id_col, /*!< in: position of
2378 DB_TRX_ID in new index */
2379 ddl::Dup *dup, /*!< in/out: for reporting
2380 duplicate key errors */
2381 dberr_t *error, /*!< out: DB_SUCCESS
2382 or error code */
2383 mem_heap_t *offsets_heap, /*!< in/out: memory heap
2384 that can be emptied */
2385 mem_heap_t *heap, /*!< in/out: memory heap */
2386 const ddl::mrec_t *mrec, /*!< in: merge record */
2387 const ddl::mrec_t *mrec_end, /*!< in: end of buffer */
2388 ulint *offsets) /*!< in/out: work area
2389 for parsing mrec */
2390 {
2391 row_log_t *log = dup->m_index->online_log;
2392 dict_index_t *new_index = log->table->first_index();
2393 ulint extra_size;
2394 const ddl::mrec_t *next_mrec;
2395 dtuple_t *old_pk;
2396
2397 ut_ad(dup->m_index->is_clustered());
2398 ut_ad(dup->m_index->table != log->table);
2399 ut_ad(log->head.total <= log->tail.total);
2400
2401 *error = DB_SUCCESS;
2402
2403 /* 3 = 1 (op type) + 1 (extra_size) + at least 1 byte payload */
2404 if (mrec + 3 >= mrec_end) {
2405 return (nullptr);
2406 }
2407
2408 const ddl::mrec_t *const mrec_start = mrec;
2409
2410 switch (*mrec++) {
2411 default:
2412 *error = DB_CORRUPTION;
2413 ut_d(ut_error);
2414 ut_o(return (nullptr));
2415 case ROW_T_INSERT:
2416 extra_size = *mrec++;
2417
2418 if (extra_size >= 0x80) {
2419 /* Read another byte of extra_size. */
2420
2421 extra_size = (extra_size & 0x7f) << 8;
2422 extra_size |= *mrec++;
2423 }
2424
2425 mrec += extra_size;
2426
2427 if (mrec > mrec_end) {
2428 return (nullptr);
2429 }
2430
2431 rec_offs_set_n_fields(offsets, dup->m_index->get_n_total_fields());
2432 rec_deserialize_init_offsets(mrec, dup->m_index, offsets);
2433
2434 next_mrec = mrec + rec_offs_data_size(offsets);
2435
2436 if (log->table->n_v_cols) {
2437 if (next_mrec + 2 > mrec_end) {
2438 return (nullptr);
2439 }
2440 next_mrec += mach_read_from_2(next_mrec);
2441 }
2442
2443 if (next_mrec > mrec_end) {
2444 return (nullptr);
2445 } else {
2446 log->head.total += next_mrec - mrec_start;
2447
2448 ulint len;
2449 const byte *db_trx_id =
2450 rec_get_nth_field(nullptr, mrec, offsets, trx_id_col, &len);
2451 ut_ad(len == DATA_TRX_ID_LEN);
2452 *error =
2453 row_log_table_apply_insert(thr, mrec, offsets, offsets_heap, heap,
2454 dup, trx_read_trx_id(db_trx_id));
2455 }
2456 break;
2457
2458 case ROW_T_DELETE:
2459 /* 1 (extra_size) + at least 1 (payload) */
2460 if (mrec + 2 >= mrec_end) {
2461 return (nullptr);
2462 }
2463
2464 extra_size = *mrec++;
2465 ut_ad(mrec < mrec_end);
2466
2467 /* We assume extra_size < 0x100 for the PRIMARY KEY prefix.
2468 For fixed-length PRIMARY key columns, it is 0. */
2469 mrec += extra_size;
2470
2471 rec_offs_set_n_fields(offsets, new_index->n_uniq + 2);
2472 rec_deserialize_init_offsets(mrec, new_index, offsets);
2473 next_mrec = mrec + rec_offs_data_size(offsets);
2474 if (log->table->n_v_cols) {
2475 if (next_mrec + 2 > mrec_end) {
2476 return (nullptr);
2477 }
2478
2479 next_mrec += mach_read_from_2(next_mrec);
2480 }
2481
2482 if (next_mrec > mrec_end) {
2483 return (nullptr);
2484 }
2485
2486 log->head.total += next_mrec - mrec_start;
2487
2488 *error = row_log_table_apply_delete(new_trx_id_col, mrec, offsets,
2489 offsets_heap, heap, log);
2490 break;
2491
2492 case ROW_T_UPDATE:
2493 /* Logically, the log entry consists of the
2494 (PRIMARY KEY,DB_TRX_ID) of the old value (converted
2495 to the new primary key definition) followed by
2496 the new value in the old table definition. If the
2497 definition of the columns belonging to PRIMARY KEY
2498 is not changed, the log will only contain
2499 DB_TRX_ID,new_row. */
2500 ulint num_v = new_index->table->n_v_cols;
2501
2502 if (dup->m_index->online_log->same_pk) {
2503 ut_ad(new_index->n_uniq == dup->m_index->n_uniq);
2504
2505 extra_size = *mrec++;
2506
2507 if (extra_size >= 0x80) {
2508 /* Read another byte of extra_size. */
2509
2510 extra_size = (extra_size & 0x7f) << 8;
2511 extra_size |= *mrec++;
2512 }
2513
2514 mrec += extra_size;
2515
2516 if (mrec > mrec_end) {
2517 return (nullptr);
2518 }
2519
2520 rec_offs_set_n_fields(offsets, dup->m_index->get_n_total_fields());
2521 rec_deserialize_init_offsets(mrec, dup->m_index, offsets);
2522
2523 next_mrec = mrec + rec_offs_data_size(offsets);
2524
2525 if (next_mrec > mrec_end) {
2526 return (nullptr);
2527 }
2528
2529 old_pk = dtuple_create_with_vcol(heap, new_index->n_uniq, num_v);
2530 dict_index_copy_types(old_pk, new_index, old_pk->n_fields);
2531 if (num_v) {
2532 dict_table_copy_v_types(old_pk, new_index->table);
2533 }
2534
2535 /* Copy the PRIMARY KEY fields from mrec to old_pk. */
2536 for (ulint i = 0; i < new_index->n_uniq; i++) {
2537 const void *field;
2538 ulint len;
2539 dfield_t *dfield;
2540
2541 ut_ad(!rec_offs_nth_extern(new_index, offsets, i));
2542
2543 field = rec_get_nth_field(nullptr, mrec, offsets, i, &len);
2544 ut_ad(rec_field_not_null_not_add_col_def(len));
2545
2546 dfield = dtuple_get_nth_field(old_pk, i);
2547 dfield_set_data(dfield, field, len);
2548 }
2549 } else {
2550 /* We assume extra_size < 0x100
2551 for the PRIMARY KEY prefix. */
2552 mrec += *mrec + 1;
2553
2554 if (mrec > mrec_end) {
2555 return (nullptr);
2556 }
2557
2558 /* Get offsets for PRIMARY KEY,
2559 DB_TRX_ID, DB_ROLL_PTR. */
2560 rec_offs_set_n_fields(offsets, new_index->n_uniq + 2);
2561 rec_deserialize_init_offsets(mrec, new_index, offsets);
2562
2563 next_mrec = mrec + rec_offs_data_size(offsets);
2564 if (next_mrec + 2 > mrec_end) {
2565 return (nullptr);
2566 }
2567
2568 /* Copy the PRIMARY KEY fields and
2569 DB_TRX_ID, DB_ROLL_PTR from mrec to old_pk. */
2570 old_pk = dtuple_create_with_vcol(heap, new_index->n_uniq + 2, num_v);
2571 dict_index_copy_types(old_pk, new_index, old_pk->n_fields);
2572
2573 if (num_v) {
2574 dict_table_copy_v_types(old_pk, new_index->table);
2575 }
2576
2577 for (ulint i = 0; i < dict_index_get_n_unique(new_index) + 2U; i++) {
2578 const void *field;
2579 ulint len;
2580 dfield_t *dfield;
2581
2582 ut_ad(!rec_offs_nth_extern(new_index, offsets, i));
2583
2584 field = rec_get_nth_field(nullptr, mrec, offsets, i, &len);
2585 ut_ad(rec_field_not_null_not_add_col_def(len));
2586
2587 dfield = dtuple_get_nth_field(old_pk, i);
2588 dfield_set_data(dfield, field, len);
2589 }
2590
2591 mrec = next_mrec;
2592
2593 /* Fetch the new value of the row as it was
2594 in the old table definition. */
2595 extra_size = *mrec++;
2596
2597 if (extra_size >= 0x80) {
2598 /* Read another byte of extra_size. */
2599
2600 extra_size = (extra_size & 0x7f) << 8;
2601 extra_size |= *mrec++;
2602 }
2603
2604 mrec += extra_size;
2605
2606 if (mrec > mrec_end) {
2607 return (nullptr);
2608 }
2609
2610 rec_offs_set_n_fields(offsets, dup->m_index->get_n_total_fields());
2611 rec_deserialize_init_offsets(mrec, dup->m_index, offsets);
2612
2613 next_mrec = mrec + rec_offs_data_size(offsets);
2614
2615 if (next_mrec > mrec_end) {
2616 return (nullptr);
2617 }
2618 }
2619
2620 /* Read virtual column info from log */
2621 if (num_v) {
2622 ulint o_v_size = 0;
2623 ulint n_v_size = 0;
2624 if (next_mrec + 2 > mrec_end) {
2625 return (nullptr);
2626 }
2627 n_v_size = mach_read_from_2(next_mrec);
2628 next_mrec += n_v_size;
2629
2630 if (next_mrec > mrec_end) {
2631 return (nullptr);
2632 }
2633
2634 /* if there is more than 2 bytes length info */
2635 if (n_v_size > 2) {
2636 if (next_mrec + 2 > mrec_end) {
2637 return (nullptr);
2638 }
2639 o_v_size = mach_read_from_2(next_mrec);
2640 if (next_mrec + o_v_size > mrec_end) {
2641 return (nullptr);
2642 }
2643
2644 trx_undo_read_v_cols(log->table, const_cast<byte *>(next_mrec),
2645 old_pk, false, true,
2646 &(log->col_map[log->n_old_col]), heap);
2647 }
2648
2649 next_mrec += o_v_size;
2650 ut_ad(next_mrec <= mrec_end);
2651 }
2652
2653 ut_ad(next_mrec <= mrec_end);
2654 log->head.total += next_mrec - mrec_start;
2655 dtuple_set_n_fields_cmp(old_pk, new_index->n_uniq);
2656
2657 {
2658 ulint len;
2659 const byte *db_trx_id =
2660 rec_get_nth_field(nullptr, mrec, offsets, trx_id_col, &len);
2661 ut_ad(len == DATA_TRX_ID_LEN);
2662 *error = row_log_table_apply_update(thr, new_trx_id_col, mrec, offsets,
2663 offsets_heap, heap, dup,
2664 trx_read_trx_id(db_trx_id), old_pk);
2665 }
2666
2667 break;
2668 }
2669
2670 ut_ad(log->head.total <= log->tail.total);
2671 mem_heap_empty(offsets_heap);
2672 mem_heap_empty(heap);
2673 return (next_mrec);
2674 }
2675
2676 #ifdef HAVE_PSI_STAGE_INTERFACE
2677 /** Estimate how much an ALTER TABLE progress should be incremented per
2678 one block of log applied.
2679 For the other phases of ALTER TABLE we increment the progress with 1 per
2680 page processed.
2681 @return amount of abstract units to add to work_completed when one block
2682 of log is applied.
2683 */
2684 inline ulint row_log_progress_inc_per_block() {
2685 /* We must increment the progress once per page (as in
2686 univ_page_size, usually 16KiB). One block here is srv_sort_buf_size
2687 (usually 1MiB). */
2688 const ulint pages_per_block = std::max(
2689 static_cast<unsigned long>(srv_sort_buf_size / univ_page_size.physical()),
2690 1UL);
2691
2692 /* Multiply by an artificial factor of 6 to even the pace with
2693 the rest of the ALTER TABLE phases, they process page_size amount
2694 of data faster. */
2695 return (pages_per_block * 6);
2696 }
2697
2698 /** Estimate how much work is to be done by the log apply phase
2699 of an ALTER TABLE for this index.
2700 @param[in] index index whose log to assess
2701 @return work to be done by log-apply in abstract units
2702 */
2703 ulint row_log_estimate_work(const dict_index_t *index) {
2704 if (index == nullptr || index->online_log == nullptr) {
2705 return (0);
2706 }
2707
2708 const row_log_t *l = index->online_log;
2709 const ulint bytes_left = static_cast<ulint>(l->tail.total - l->head.total);
2710 const ulint blocks_left = bytes_left / srv_sort_buf_size;
2711
2712 return (blocks_left * row_log_progress_inc_per_block());
2713 }
2714 #else /* HAVE_PSI_STAGE_INTERFACE */
2715 inline ulint row_log_progress_inc_per_block() { return (0); }
2716 #endif /* HAVE_PSI_STAGE_INTERFACE */
2717
2718 /** Applies operations to a table was rebuilt.
2719 @param[in] thr query graph
2720 @param[in,out] dup for reporting duplicate key errors
2721 @param[in,out] stage performance schema accounting object, used by
2722 ALTER TABLE. If not NULL, then stage->inc() will be called for each block
2723 of log that is applied.
2724 @return DB_SUCCESS, or error code on failure */
2725 [[nodiscard]] static dberr_t row_log_table_apply_ops(que_thr_t *thr,
2726 ddl::Dup *dup,
2727 Alter_stage *stage) {
2728 dberr_t error;
2729 const ddl::mrec_t *mrec = nullptr;
2730 const ddl::mrec_t *next_mrec;
2731 const ddl::mrec_t *mrec_end = nullptr; /* silence bogus warning */
2732 const ddl::mrec_t *next_mrec_end;
2733 mem_heap_t *heap;
2734 mem_heap_t *offsets_heap;
2735 ulint *offsets;
2736 bool has_index_lock;
2737 dict_index_t *index = const_cast<dict_index_t *>(dup->m_index);
2738 dict_table_t *new_table = index->online_log->table;
2739 dict_index_t *new_index = new_table->first_index();
2740 ulint n_fields = dict_index_get_n_fields(index);
2741 ulint n_unique = dict_index_get_n_unique(new_index) + 2;
2742 const ulint i = 1 + REC_OFFS_HEADER_SIZE + std::max(n_fields, n_unique);
2743 const ulint trx_id_col =
2744 dict_col_get_clust_pos(index->table->get_sys_col(DATA_TRX_ID), index);
2745 const ulint new_trx_id_col =
2746 dict_col_get_clust_pos(new_table->get_sys_col(DATA_TRX_ID), new_index);
2747 trx_t *trx = thr_get_trx(thr);
2748 dberr_t err;
2749
2750 ut_ad(index->is_clustered());
2751 ut_ad(dict_index_is_online_ddl(index));
2752 ut_ad(trx->mysql_thd);
2753 ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
2754 ut_ad(!dict_index_is_online_ddl(new_index));
2755 ut_ad(trx_id_col > 0);
2756 ut_ad(trx_id_col != ULINT_UNDEFINED);
2757 ut_ad(new_trx_id_col > 0);
2758 ut_ad(new_trx_id_col != ULINT_UNDEFINED);
2759
2760 UNIV_MEM_INVALID(&mrec_end, sizeof mrec_end);
2761
2762 offsets = static_cast<ulint *>(
2763 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, i * sizeof *offsets));
2764 offsets[0] = i;
2765 offsets[1] = dict_index_get_n_fields(index);
2766
2767 heap = mem_heap_create(UNIV_PAGE_SIZE, UT_LOCATION_HERE);
2768 offsets_heap = mem_heap_create(UNIV_PAGE_SIZE, UT_LOCATION_HERE);
2769 has_index_lock = true;
2770
2771 next_block:
2772 ut_ad(has_index_lock);
2773 ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
2774 ut_ad(index->online_log->head.bytes == 0);
2775
2776 stage->inc(row_log_progress_inc_per_block());
2777
2778 if (trx_is_interrupted(trx)) {
2779 goto interrupted;
2780 }
2781
2782 if (index->is_corrupted()) {
2783 error = DB_INDEX_CORRUPT;
2784 goto func_exit;
2785 }
2786
2787 ut_ad(dict_index_is_online_ddl(index));
2788
2789 error = index->online_log->error;
2790
2791 if (error != DB_SUCCESS) {
2792 goto func_exit;
2793 }
2794
2795 if (UNIV_UNLIKELY(index->online_log->head.blocks >
2796 index->online_log->tail.blocks)) {
2797 /* Note: release-only label. */
2798 ut_o(unexpected_eof:);
2799 ib::error(ER_IB_MSG_960)
2800 << "Unexpected end of temporary file for table " << index->table->name;
2801 corruption:
2802 error = DB_CORRUPTION;
2803 goto func_exit;
2804 }
2805
2806 if (index->online_log->head.blocks == index->online_log->tail.blocks) {
2807 if (index->online_log->head.blocks) {
2808 #ifdef HAVE_FTRUNCATE
2809 /* Truncate the file in order to save space. */
2810 if (index->online_log->file.is_open() &&
2811 ftruncate(index->online_log->file.get(), 0) == -1) {
2812 perror("ftruncate");
2813 }
2814 #endif /* HAVE_FTRUNCATE */
2815 index->online_log->head.blocks = index->online_log->tail.blocks = 0;
2816 }
2817
2818 next_mrec = index->online_log->tail.block;
2819 next_mrec_end = next_mrec + index->online_log->tail.bytes;
2820
2821 if (next_mrec_end == next_mrec) {
2822 /* End of log reached. */
2823 all_done:
2824 ut_ad(has_index_lock);
2825 ut_ad(index->online_log->head.blocks == 0);
2826 ut_ad(index->online_log->tail.blocks == 0);
2827 index->online_log->head.bytes = 0;
2828 index->online_log->tail.bytes = 0;
2829 error = DB_SUCCESS;
2830 goto func_exit;
2831 }
2832 } else {
2833 os_offset_t ofs;
2834
2835 ofs = (os_offset_t)index->online_log->head.blocks * srv_sort_buf_size;
2836
2837 ut_ad(has_index_lock);
2838 has_index_lock = false;
2839 rw_lock_x_unlock(dict_index_get_lock(index));
2840
2841 log_free_check();
2842
2843 ut_ad(dict_index_is_online_ddl(index));
2844
2845 if (!row_log_block_allocate(index->online_log->head)) {
2846 error = DB_OUT_OF_MEMORY;
2847 goto func_exit;
2848 }
2849
2850 IORequest request(IORequest::READ | IORequest::ROW_LOG);
2851 ;
2852
2853 err = os_file_read_no_error_handling_int_fd(
2854 request, index->online_log->path, index->online_log->file.get(),
2855 index->online_log->head.block, ofs, srv_sort_buf_size, nullptr);
2856
2857 if (err != DB_SUCCESS) {
2858 ib::error(ER_IB_MSG_961) << "Unable to read temporary file"
2859 " for table "
2860 << index->table_name;
2861 goto corruption;
2862 }
2863
2864 #ifdef POSIX_FADV_DONTNEED
2865 /* Each block is read exactly once. Free up the file cache. */
2866 posix_fadvise(index->online_log->file.get(), ofs, srv_sort_buf_size,
2867 POSIX_FADV_DONTNEED);
2868 #endif /* POSIX_FADV_DONTNEED */
2869
2870 next_mrec = index->online_log->head.block;
2871 next_mrec_end = next_mrec + srv_sort_buf_size;
2872 }
2873
2874 /* This read is not protected by index->online_log->mutex for
2875 performance reasons. We will eventually notice any error that
2876 was flagged by a DML thread. */
2877 error = index->online_log->error;
2878
2879 if (error != DB_SUCCESS) {
2880 goto func_exit;
2881 }
2882
2883 if (mrec) {
2884 /* A partial record was read from the previous block.
2885 Copy the temporary buffer full, as we do not know the
2886 length of the record. Parse subsequent records from
2887 the bigger buffer index->online_log->head.block
2888 or index->online_log->tail.block. */
2889
2890 ut_ad(mrec == index->online_log->head.buf);
2891 ut_ad(mrec_end > mrec);
2892 ut_ad(mrec_end < (&index->online_log->head.buf)[1]);
2893
2894 memcpy((ddl::mrec_t *)mrec_end, next_mrec,
2895 (&index->online_log->head.buf)[1] - mrec_end);
2896 mrec =
2897 row_log_table_apply_op(thr, trx_id_col, new_trx_id_col, dup, &error,
2898 offsets_heap, heap, index->online_log->head.buf,
2899 (&index->online_log->head.buf)[1], offsets);
2900 if (error != DB_SUCCESS) {
2901 goto func_exit;
2902 } else if (UNIV_UNLIKELY(mrec == nullptr)) {
2903 /* The record was not reassembled properly. */
2904 goto corruption;
2905 }
2906 /* The record was previously found out to be
2907 truncated. Now that the parse buffer was extended,
2908 it should proceed beyond the old end of the buffer. */
2909 ut_a(mrec > mrec_end);
2910
2911 index->online_log->head.bytes = mrec - mrec_end;
2912 next_mrec += index->online_log->head.bytes;
2913 }
2914
2915 ut_ad(next_mrec <= next_mrec_end);
2916 /* The following loop must not be parsing the temporary
2917 buffer, but head.block or tail.block. */
2918
2919 /* mrec!=NULL means that the next record starts from the
2920 middle of the block */
2921 ut_ad((mrec == nullptr) == (index->online_log->head.bytes == 0));
2922
2923 #ifdef UNIV_DEBUG
2924 if (index->online_log->head.block != nullptr &&
2925 next_mrec_end == index->online_log->head.block + srv_sort_buf_size) {
2926 /* If tail.bytes == 0, next_mrec_end can also be at
2927 the end of tail.block. */
2928 if (index->online_log->tail.bytes == 0) {
2929 ut_ad(next_mrec == next_mrec_end);
2930 ut_ad(index->online_log->tail.blocks == 0);
2931 ut_ad(index->online_log->head.blocks == 0);
2932 ut_ad(index->online_log->head.bytes == 0);
2933 } else {
2934 ut_ad(next_mrec ==
2935 index->online_log->head.block + index->online_log->head.bytes);
2936 ut_ad(index->online_log->tail.blocks > index->online_log->head.blocks);
2937 }
2938 } else if (next_mrec_end ==
2939 index->online_log->tail.block + index->online_log->tail.bytes) {
2940 ut_ad(next_mrec ==
2941 index->online_log->tail.block + index->online_log->head.bytes);
2942 ut_ad(index->online_log->tail.blocks == 0);
2943 ut_ad(index->online_log->head.blocks == 0);
2944 ut_ad(index->online_log->head.bytes <= index->online_log->tail.bytes);
2945 } else {
2946 ut_error;
2947 }
2948 #endif /* UNIV_DEBUG */
2949
2950 mrec_end = next_mrec_end;
2951
2952 while (!trx_is_interrupted(trx)) {
2953 if (next_mrec == next_mrec_end && has_index_lock) {
2954 goto all_done;
2955 }
2956
2957 mrec = next_mrec;
2958
2959 ut_ad(mrec < mrec_end);
2960
2961 if (!has_index_lock) {
2962 /* We are applying operations from a different
2963 block than the one that is being written to.
2964 We do not hold index->lock in order to
2965 allow other threads to concurrently buffer
2966 modifications. */
2967 ut_ad(mrec >= index->online_log->head.block);
2968 ut_ad(mrec_end == index->online_log->head.block + srv_sort_buf_size);
2969 ut_ad(index->online_log->head.bytes < srv_sort_buf_size);
2970
2971 /* Take the opportunity to do a redo log
2972 checkpoint if needed. */
2973 log_free_check();
2974 } else {
2975 /* We are applying operations from the last block.
2976 Do not allow other threads to buffer anything,
2977 so that we can finally catch up and synchronize. */
2978 ut_ad(index->online_log->head.blocks == 0);
2979 ut_ad(index->online_log->tail.blocks == 0);
2980 ut_ad(mrec_end ==
2981 index->online_log->tail.block + index->online_log->tail.bytes);
2982 ut_ad(mrec >= index->online_log->tail.block);
2983 }
2984
2985 /* This read is not protected by index->online_log->mutex
2986 for performance reasons. We will eventually notice any
2987 error that was flagged by a DML thread. */
2988 error = index->online_log->error;
2989
2990 if (error != DB_SUCCESS) {
2991 goto func_exit;
2992 }
2993
2994 next_mrec =
2995 row_log_table_apply_op(thr, trx_id_col, new_trx_id_col, dup, &error,
2996 offsets_heap, heap, mrec, mrec_end, offsets);
2997
2998 if (error != DB_SUCCESS) {
2999 goto func_exit;
3000 } else if (next_mrec == next_mrec_end) {
3001 /* The record happened to end on a block boundary.
3002 Do we have more blocks left? */
3003 if (has_index_lock) {
3004 /* The index will be locked while
3005 applying the last block. */
3006 goto all_done;
3007 }
3008
3009 mrec = nullptr;
3010 process_next_block:
3011 rw_lock_x_lock(dict_index_get_lock(index), UT_LOCATION_HERE);
3012 has_index_lock = true;
3013
3014 index->online_log->head.bytes = 0;
3015 index->online_log->head.blocks++;
3016 goto next_block;
3017 } else if (next_mrec != nullptr) {
3018 ut_ad(next_mrec < next_mrec_end);
3019 index->online_log->head.bytes += next_mrec - mrec;
3020 } else if (has_index_lock) {
3021 /* When mrec is within tail.block, it should
3022 be a complete record, because we are holding
3023 index->lock and thus excluding the writer. */
3024 ut_ad(index->online_log->tail.blocks == 0);
3025 ut_ad(mrec_end ==
3026 index->online_log->tail.block + index->online_log->tail.bytes);
3027 ut_d(ut_error);
3028 ut_o(goto unexpected_eof);
3029 } else {
3030 memcpy(index->online_log->head.buf, mrec, mrec_end - mrec);
3031 mrec_end += index->online_log->head.buf - mrec;
3032 mrec = index->online_log->head.buf;
3033 goto process_next_block;
3034 }
3035 }
3036
3037 interrupted:
3038 error = DB_INTERRUPTED;
3039 func_exit:
3040 if (!has_index_lock) {
3041 rw_lock_x_lock(dict_index_get_lock(index), UT_LOCATION_HERE);
3042 }
3043
3044 mem_heap_free(offsets_heap);
3045 mem_heap_free(heap);
3046 row_log_block_free(index->online_log->head);
3047 ut::free(offsets);
3048 return (error);
3049 }
3050
3051 /** Apply the row_log_table log to a table upon completing rebuild.
3052 @param[in] thr query graph
3053 @param[in] old_table old table
3054 @param[in,out] table MySQL table (for reporting duplicates)
3055 @param[in,out] stage performance schema accounting object, used by
3056 ALTER TABLE. stage->begin_phase_log_table() will be called initially and then
3057 stage->inc() will be called for each block of log that is applied.
3058 @return DB_SUCCESS, or error code on failure */
3059 dberr_t row_log_table_apply(que_thr_t *thr, dict_table_t *old_table,
3060 struct TABLE *table, Alter_stage *stage) {
3061 dberr_t error;
3062 dict_index_t *clust_index;
3063
3064 thr_get_trx(thr)->error_key_num = 0;
3065 DBUG_EXECUTE_IF("innodb_trx_duplicates", thr->prebuilt->replace = 1;);
3066
3067 stage->begin_phase_log_table();
3068
3069 ut_ad(!rw_lock_own(dict_operation_lock, RW_LOCK_S));
3070 clust_index = old_table->first_index();
3071
3072 rw_lock_x_lock(dict_index_get_lock(clust_index), UT_LOCATION_HERE);
3073
3074 if (!clust_index->online_log) {
3075 ut_ad(dict_index_get_online_status(clust_index) == ONLINE_INDEX_COMPLETE);
3076 /* This function should not be called unless
3077 rebuilding a table online. Build in some fault
3078 tolerance. */
3079 error = DB_ERROR;
3080 ut_d(ut_error);
3081 } else {
3082 ddl::Dup dup = {clust_index, table, clust_index->online_log->col_map, 0};
3083
3084 error = row_log_table_apply_ops(thr, &dup, stage);
3085
3086 ut_ad(error != DB_SUCCESS || clust_index->online_log->head.total ==
3087 clust_index->online_log->tail.total);
3088 }
3089
3090 rw_lock_x_unlock(dict_index_get_lock(clust_index));
3091 DBUG_EXECUTE_IF("innodb_trx_duplicates", thr->prebuilt->replace = 0;);
3092
3093 return (error);
3094 }
3095
3096 bool row_log_allocate(dict_index_t *index, dict_table_t *table, bool same_pk,
3097 const dtuple_t *add_cols, const ulint *col_map,
3098 const char *path) {
3099 row_log_t *log;
3100 DBUG_TRACE;
3101
3102 ut_ad(!dict_index_is_online_ddl(index));
3103 ut_ad(index->is_clustered() == !!table);
3104 ut_ad(!table || index->table != table);
3105 ut_ad(same_pk || table);
3106 ut_ad(!table || col_map);
3107 ut_ad(!add_cols || col_map);
3108 ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
3109
3110 log = ut::new_withkey<row_log_t>(UT_NEW_THIS_FILE_PSI_KEY);
3111
3112 if (log == nullptr) {
3113 return false;
3114 }
3115
3116 mutex_create(LATCH_ID_INDEX_ONLINE_LOG, &log->mutex);
3117
3118 log->blobs = nullptr;
3119 log->table = table;
3120 log->same_pk = same_pk;
3121 log->add_cols = add_cols;
3122 log->col_map = col_map;
3123 log->error = DB_SUCCESS;
3124 log->max_trx = 0;
3125 log->tail.blocks = log->tail.bytes = 0;
3126 log->tail.total = 0;
3127 log->tail.block = log->head.block = nullptr;
3128 log->head.blocks = log->head.bytes = 0;
3129 log->head.total = 0;
3130 log->path = path;
3131 log->n_old_col = index->table->n_cols;
3132 log->n_old_vcol = index->table->n_v_cols;
3133
3134 dict_index_set_online_status(index, ONLINE_INDEX_CREATION);
3135 index->online_log = log;
3136
3137 /* While we might be holding an exclusive data dictionary lock
3138 here, in row_log_abort_sec() we will not always be holding it. Use
3139 atomic operations in both cases. */
3140 MONITOR_ATOMIC_INC(MONITOR_ONLINE_CREATE_INDEX);
3141
3142 return true;
3143 }
3144
3145 /** Free the row log for an index that was being created online. */
3146 void row_log_free(row_log_t *&log) /*!< in,own: row log */
3147 {
3148 MONITOR_ATOMIC_DEC(MONITOR_ONLINE_CREATE_INDEX);
3149
3150 ut::delete_(log->blobs);
3151 row_log_block_free(log->tail);
3152 row_log_block_free(log->head);
3153 mutex_free(&log->mutex);
3154 ut::free(log);
3155 log = nullptr;
3156 }
3157
3158 /** Get the latest transaction ID that has invoked row_log_online_op()
3159 during online creation.
3160 @return latest transaction ID, or 0 if nothing was logged */
3161 trx_id_t row_log_get_max_trx(
3162 dict_index_t *index) /*!< in: index, must be locked */
3163 {
3164 ut_ad(dict_index_get_online_status(index) == ONLINE_INDEX_CREATION);
3165
3166 ut_ad((rw_lock_own(dict_index_get_lock(index), RW_LOCK_S) &&
3167 mutex_own(&index->online_log->mutex)) ||
3168 rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
3169
3170 return (index->online_log->max_trx);
3171 }
3172
3173 /** Applies an operation to a secondary index that was being created. */
3174 static void row_log_apply_op_low(
3175 dict_index_t *index, /*!< in/out: index */
3176 ddl::Dup *dup, /*!< in/out: for reporting
3177 duplicate key errors */
3178 dberr_t *error, /*!< out: DB_SUCCESS or error code */
3179 mem_heap_t *offsets_heap, /*!< in/out: memory heap for
3180 allocating offsets; can be emptied */
3181 bool has_index_lock, /*!< in: true if holding index->lock
3182 in exclusive mode */
3183 enum row_op op, /*!< in: operation being applied */
3184 trx_id_t trx_id, /*!< in: transaction identifier */
3185 const dtuple_t *entry) /*!< in: row */
3186 {
3187 mtr_t mtr;
3188 btr_cur_t cursor;
3189 ulint *offsets = nullptr;
3190
3191 ut_ad(!index->is_clustered());
3192
3193 ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X) == has_index_lock);
3194
3195 ut_ad(!index->is_corrupted());
3196 ut_ad(trx_id != 0 || op == ROW_OP_DELETE);
3197
3198 DBUG_PRINT("ib_create_index",
3199 ("%s %s index " IB_ID_FMT "," TRX_ID_FMT ": %s",
3200 op == ROW_OP_INSERT ? "insert" : "delete",
3201 has_index_lock ? "locked" : "unlocked", index->id, trx_id,
3202 rec_printer(entry).str().c_str()));
3203
3204 mtr_start(&mtr);
3205
3206 /* We perform the pessimistic variant of the operations if we
3207 already hold index->lock exclusively. First, search the
3208 record. The operation may already have been performed,
3209 depending on when the row in the clustered index was
3210 scanned. */
3211 btr_cur_search_to_nth_level(
3212 index, 0, entry, PAGE_CUR_LE,
3213 has_index_lock ? BTR_MODIFY_TREE : BTR_MODIFY_LEAF, &cursor, 0, __FILE__,
3214 __LINE__, &mtr);
3215
3216 ut_ad(dict_index_get_n_unique(index) > 0);
3217 /* This test is somewhat similar to row_ins_must_modify_rec(),
3218 but not identical for unique secondary indexes. */
3219 if (cursor.low_match >= dict_index_get_n_unique(index) &&
3220 !page_rec_is_infimum(btr_cur_get_rec(&cursor))) {
3221 /* We have a matching record. */
3222 bool exists = (cursor.low_match == dict_index_get_n_fields(index));
3223 #ifdef UNIV_DEBUG
3224 rec_t *rec = btr_cur_get_rec(&cursor);
3225 ut_ad(page_rec_is_user_rec(rec));
3226 ut_ad(!rec_get_deleted_flag(rec, page_rec_is_comp(rec)));
3227 #endif /* UNIV_DEBUG */
3228
3229 ut_ad(exists || dict_index_is_unique(index));
3230
3231 switch (op) {
3232 case ROW_OP_DELETE:
3233 if (!exists) {
3234 /* The existing record matches the
3235 unique secondary index key, but the
3236 PRIMARY KEY columns differ. So, this
3237 exact record does not exist. For
3238 example, we could detect a duplicate
3239 key error in some old index before
3240 logging an ROW_OP_INSERT for our
3241 index. This ROW_OP_DELETE could have
3242 been logged for rolling back
3243 TRX_UNDO_INSERT_REC. */
3244 goto func_exit;
3245 }
3246
3247 if (btr_cur_optimistic_delete(&cursor, BTR_CREATE_FLAG, &mtr)) {
3248 *error = DB_SUCCESS;
3249 break;
3250 }
3251
3252 if (!has_index_lock) {
3253 /* This needs a pessimistic operation.
3254 Lock the index tree exclusively. */
3255 mtr_commit(&mtr);
3256
3257 mtr_start(&mtr);
3258
3259 btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_LE,
3260 BTR_MODIFY_TREE, &cursor, 0, __FILE__,
3261 __LINE__, &mtr);
3262
3263 /* No other thread than the current one
3264 is allowed to modify the index tree.
3265 Thus, the record should still exist. */
3266 ut_ad(cursor.low_match >= dict_index_get_n_fields(index));
3267 ut_ad(page_rec_is_user_rec(btr_cur_get_rec(&cursor)));
3268 }
3269
3270 /* As there are no externally stored fields in
3271 a secondary index record, the parameter
3272 rollback=false will be ignored. */
3273
3274 btr_cur_pessimistic_delete(error, false, &cursor, BTR_CREATE_FLAG,
3275 false, 0, 0, 0, &mtr, nullptr, nullptr);
3276 break;
3277 case ROW_OP_INSERT:
3278 if (exists) {
3279 /* The record already exists. There
3280 is nothing to be inserted.
3281 This could happen when processing
3282 TRX_UNDO_DEL_MARK_REC in statement
3283 rollback:
3284
3285 UPDATE of PRIMARY KEY can lead to
3286 statement rollback if the updated
3287 value of the PRIMARY KEY already
3288 exists. In this case, the UPDATE would
3289 be mapped to DELETE;INSERT, and we
3290 only wrote undo log for the DELETE
3291 part. The duplicate key error would be
3292 triggered before logging the INSERT
3293 part.
3294
3295 Theoretically, we could also get a
3296 similar situation when a DELETE operation
3297 is blocked by a FOREIGN KEY constraint. */
3298 goto func_exit;
3299 }
3300
3301 if (dtuple_contains_null(entry)) {
3302 /* The UNIQUE KEY columns match, but
3303 there is a NULL value in the key, and
3304 NULL!=NULL. */
3305 goto insert_the_rec;
3306 }
3307
3308 goto duplicate;
3309 }
3310 } else {
3311 switch (op) {
3312 rec_t *rec;
3313 big_rec_t *big_rec;
3314 case ROW_OP_DELETE:
3315 /* The record does not exist. For example, we
3316 could detect a duplicate key error in some old
3317 index before logging an ROW_OP_INSERT for our
3318 index. This ROW_OP_DELETE could be logged for
3319 rolling back TRX_UNDO_INSERT_REC. */
3320 goto func_exit;
3321 case ROW_OP_INSERT:
3322 if (dict_index_is_unique(index) &&
3323 (cursor.up_match >= dict_index_get_n_unique(index) ||
3324 cursor.low_match >= dict_index_get_n_unique(index)) &&
3325 (!index->n_nullable || !dtuple_contains_null(entry))) {
3326 duplicate:
3327 /* Duplicate key */
3328 ut_ad(dict_index_is_unique(index));
3329 dup->report(entry->fields);
3330 *error = DB_DUPLICATE_KEY;
3331 goto func_exit;
3332 }
3333 insert_the_rec:
3334 /* Insert the record. As we are inserting into
3335 a secondary index, there cannot be externally
3336 stored columns (!big_rec). */
3337 *error = btr_cur_optimistic_insert(
3338 BTR_NO_UNDO_LOG_FLAG | BTR_NO_LOCKING_FLAG | BTR_CREATE_FLAG,
3339 &cursor, &offsets, &offsets_heap, const_cast<dtuple_t *>(entry),
3340 &rec, &big_rec, nullptr, &mtr);
3341 ut_ad(!big_rec);
3342 if (*error != DB_FAIL) {
3343 break;
3344 }
3345
3346 if (!has_index_lock) {
3347 /* This needs a pessimistic operation.
3348 Lock the index tree exclusively. */
3349 mtr_commit(&mtr);
3350
3351 mtr_start(&mtr);
3352
3353 btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_LE,
3354 BTR_MODIFY_TREE, &cursor, 0, __FILE__,
3355 __LINE__, &mtr);
3356 }
3357
3358 /* We already determined that the
3359 record did not exist. No other thread
3360 than the current one is allowed to
3361 modify the index tree. Thus, the
3362 record should still not exist. */
3363
3364 *error = btr_cur_pessimistic_insert(
3365 BTR_NO_UNDO_LOG_FLAG | BTR_NO_LOCKING_FLAG | BTR_CREATE_FLAG,
3366 &cursor, &offsets, &offsets_heap, const_cast<dtuple_t *>(entry),
3367 &rec, &big_rec, nullptr, &mtr);
3368 ut_ad(!big_rec);
3369 break;
3370 }
3371 mem_heap_empty(offsets_heap);
3372 }
3373
3374 if (*error == DB_SUCCESS && trx_id) {
3375 page_update_max_trx_id(btr_cur_get_block(&cursor),
3376 btr_cur_get_page_zip(&cursor), trx_id, &mtr);
3377 }
3378
3379 func_exit:
3380 mtr_commit(&mtr);
3381 }
3382
3383 /** Applies an operation to a secondary index that was being created.
3384 @return NULL on failure (mrec corruption) or when out of data;
3385 pointer to next record on success */
3386 [[nodiscard]] static const ddl::mrec_t *row_log_apply_op(
3387 dict_index_t *index, /*!< in/out: index */
3388 ddl::Dup *dup, /*!< in/out: for reporting
3389 duplicate key errors */
3390 dberr_t *error, /*!< out: DB_SUCCESS or error code */
3391 mem_heap_t *offsets_heap, /*!< in/out: memory heap for
3392 allocating offsets; can be emptied */
3393 mem_heap_t *heap, /*!< in/out: memory heap for
3394 allocating data tuples */
3395 bool has_index_lock, /*!< in: true if holding index->lock
3396 in exclusive mode */
3397 const ddl::mrec_t *mrec, /*!< in: merge record */
3398 const ddl::mrec_t *mrec_end, /*!< in: end of buffer */
3399 ulint *offsets) /*!< in/out: work area for
3400 rec_deserialize_init_offsets() */
3401
3402 {
3403 enum row_op op;
3404 ulint extra_size;
3405 ulint data_size;
3406 dtuple_t *entry;
3407 trx_id_t trx_id;
3408
3409 /* Online index creation is only used for secondary indexes. */
3410 ut_ad(!index->is_clustered());
3411
3412 ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X) == has_index_lock);
3413
3414 if (index->is_corrupted()) {
3415 *error = DB_INDEX_CORRUPT;
3416 return (nullptr);
3417 }
3418
3419 *error = DB_SUCCESS;
3420
3421 if (mrec + ROW_LOG_HEADER_SIZE >= mrec_end) {
3422 return (nullptr);
3423 }
3424
3425 switch (*mrec) {
3426 case ROW_OP_INSERT:
3427 if (ROW_LOG_HEADER_SIZE + DATA_TRX_ID_LEN + mrec >= mrec_end) {
3428 return (nullptr);
3429 }
3430
3431 op = static_cast<enum row_op>(*mrec++);
3432 trx_id = trx_read_trx_id(mrec);
3433 mrec += DATA_TRX_ID_LEN;
3434 break;
3435 case ROW_OP_DELETE:
3436 op = static_cast<enum row_op>(*mrec++);
3437 trx_id = 0;
3438 break;
3439 default:
3440 corrupted:
3441 *error = DB_CORRUPTION;
3442 ut_d(ut_error);
3443 ut_o(return (nullptr));
3444 }
3445
3446 extra_size = *mrec++;
3447
3448 ut_ad(mrec < mrec_end);
3449
3450 if (extra_size >= 0x80) {
3451 /* Read another byte of extra_size. */
3452
3453 extra_size = (extra_size & 0x7f) << 8;
3454 extra_size |= *mrec++;
3455 }
3456
3457 mrec += extra_size;
3458
3459 if (mrec > mrec_end) {
3460 return (nullptr);
3461 }
3462
3463 rec_deserialize_init_offsets(mrec, index, offsets);
3464
3465 if (rec_offs_any_extern(offsets)) {
3466 /* There should never be any externally stored fields
3467 in a secondary index, which is what online index
3468 creation is used for. Therefore, the log file must be
3469 corrupted. */
3470 goto corrupted;
3471 }
3472
3473 data_size = rec_offs_data_size(offsets);
3474
3475 mrec += data_size;
3476
3477 if (mrec > mrec_end) {
3478 return (nullptr);
3479 }
3480
3481 entry = row_rec_to_index_entry_low(mrec - data_size, index, offsets, heap);
3482 /* Online index creation is only implemented for secondary
3483 indexes, which never contain off-page columns. */
3484 ut_ad(!entry->has_ext());
3485
3486 row_log_apply_op_low(index, dup, error, offsets_heap, has_index_lock, op,
3487 trx_id, entry);
3488 return (mrec);
3489 }
3490
3491 /** Applies operations to a secondary index that was being created.
3492 @param[in] trx transaction (for checking if the operation was
3493 interrupted)
3494 @param[in,out] index index
3495 @param[in,out] dup for reporting duplicate key errors
3496 @param[in,out] stage performance schema accounting object, used by
3497 ALTER TABLE. If not NULL, then stage->inc() will be called for each block
3498 of log that is applied.
3499 @return DB_SUCCESS, or error code on failure */
3500 static dberr_t row_log_apply_ops(const trx_t *trx, dict_index_t *index,
3501 ddl::Dup *dup, Alter_stage *stage) {
3502 dberr_t error;
3503 const ddl::mrec_t *mrec = nullptr;
3504 const ddl::mrec_t *next_mrec;
3505 const ddl::mrec_t *mrec_end = nullptr; /* silence bogus warning */
3506 const ddl::mrec_t *next_mrec_end;
3507 mem_heap_t *offsets_heap;
3508 mem_heap_t *heap;
3509 ulint *offsets;
3510 bool has_index_lock;
3511 const ulint i = 1 + REC_OFFS_HEADER_SIZE + dict_index_get_n_fields(index);
3512
3513 ut_ad(dict_index_is_online_ddl(index));
3514 ut_ad(!index->is_committed());
3515 ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
3516 ut_ad(index->online_log);
3517 UNIV_MEM_INVALID(&mrec_end, sizeof mrec_end);
3518
3519 offsets = static_cast<ulint *>(
3520 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, i * sizeof *offsets));
3521 offsets[0] = i;
3522 offsets[1] = dict_index_get_n_fields(index);
3523
3524 offsets_heap = mem_heap_create(UNIV_PAGE_SIZE, UT_LOCATION_HERE);
3525 heap = mem_heap_create(UNIV_PAGE_SIZE, UT_LOCATION_HERE);
3526 has_index_lock = true;
3527
3528 next_block:
3529 ut_ad(has_index_lock);
3530 ut_ad(rw_lock_own(dict_index_get_lock(index), RW_LOCK_X));
3531 ut_ad(index->online_log->head.bytes == 0);
3532
3533 stage->inc(row_log_progress_inc_per_block());
3534
3535 if (trx_is_interrupted(trx)) {
3536 goto interrupted;
3537 }
3538
3539 error = index->online_log->error;
3540 if (error != DB_SUCCESS) {
3541 goto func_exit;
3542 }
3543
3544 if (index->is_corrupted()) {
3545 error = DB_INDEX_CORRUPT;
3546 goto func_exit;
3547 }
3548
3549 if (UNIV_UNLIKELY(index->online_log->head.blocks >
3550 index->online_log->tail.blocks)) {
3551 /* Note: release-only label. */
3552 ut_o(unexpected_eof:);
3553 ib::error(ER_IB_MSG_962)
3554 << "Unexpected end of temporary file for index " << index->name;
3555 corruption:
3556 error = DB_CORRUPTION;
3557 goto func_exit;
3558 }
3559
3560 if (index->online_log->head.blocks == index->online_log->tail.blocks) {
3561 if (index->online_log->head.blocks) {
3562 #ifdef HAVE_FTRUNCATE
3563 /* Truncate the file in order to save space. */
3564 if (index->online_log->file.is_open() &&
3565 ftruncate(index->online_log->file.get(), 0) == -1) {
3566 perror("ftruncate");
3567 }
3568 #endif /* HAVE_FTRUNCATE */
3569 index->online_log->head.blocks = index->online_log->tail.blocks = 0;
3570 }
3571
3572 next_mrec = index->online_log->tail.block;
3573 next_mrec_end = next_mrec + index->online_log->tail.bytes;
3574
3575 if (next_mrec_end == next_mrec) {
3576 /* End of log reached. */
3577 all_done:
3578 ut_ad(has_index_lock);
3579 ut_ad(index->online_log->head.blocks == 0);
3580 ut_ad(index->online_log->tail.blocks == 0);
3581 error = DB_SUCCESS;
3582 goto func_exit;
3583 }
3584 } else {
3585 os_offset_t ofs;
3586
3587 ofs = (os_offset_t)index->online_log->head.blocks * srv_sort_buf_size;
3588
3589 ut_ad(has_index_lock);
3590 has_index_lock = false;
3591 rw_lock_x_unlock(dict_index_get_lock(index));
3592
3593 log_free_check();
3594
3595 if (!row_log_block_allocate(index->online_log->head)) {
3596 error = DB_OUT_OF_MEMORY;
3597 goto func_exit;
3598 }
3599
3600 IORequest request(IORequest::READ | IORequest::ROW_LOG);
3601 dberr_t err = os_file_read_no_error_handling_int_fd(
3602 request, index->online_log->path, index->online_log->file.get(),
3603 index->online_log->head.block, ofs, srv_sort_buf_size, nullptr);
3604
3605 if (err != DB_SUCCESS) {
3606 ib::error(ER_IB_MSG_963) << "Unable to read temporary file"
3607 " for index "
3608 << index->name;
3609 goto corruption;
3610 }
3611
3612 #ifdef POSIX_FADV_DONTNEED
3613 /* Each block is read exactly once. Free up the file cache. */
3614 posix_fadvise(index->online_log->file.get(), ofs, srv_sort_buf_size,
3615 POSIX_FADV_DONTNEED);
3616 #endif /* POSIX_FADV_DONTNEED */
3617
3618 next_mrec = index->online_log->head.block;
3619 next_mrec_end = next_mrec + srv_sort_buf_size;
3620 }
3621
3622 if (mrec) {
3623 /* A partial record was read from the previous block.
3624 Copy the temporary buffer full, as we do not know the
3625 length of the record. Parse subsequent records from
3626 the bigger buffer index->online_log->head.block
3627 or index->online_log->tail.block. */
3628
3629 ut_ad(mrec == index->online_log->head.buf);
3630 ut_ad(mrec_end > mrec);
3631 ut_ad(mrec_end < (&index->online_log->head.buf)[1]);
3632
3633 memcpy((ddl::mrec_t *)mrec_end, next_mrec,
3634 (&index->online_log->head.buf)[1] - mrec_end);
3635 mrec = row_log_apply_op(index, dup, &error, offsets_heap, heap,
3636 has_index_lock, index->online_log->head.buf,
3637 (&index->online_log->head.buf)[1], offsets);
3638 if (error != DB_SUCCESS) {
3639 goto func_exit;
3640 } else if (UNIV_UNLIKELY(mrec == nullptr)) {
3641 /* The record was not reassembled properly. */
3642 goto corruption;
3643 }
3644 /* The record was previously found out to be
3645 truncated. Now that the parse buffer was extended,
3646 it should proceed beyond the old end of the buffer. */
3647 ut_a(mrec > mrec_end);
3648
3649 index->online_log->head.bytes = mrec - mrec_end;
3650 next_mrec += index->online_log->head.bytes;
3651 }
3652
3653 ut_ad(next_mrec <= next_mrec_end);
3654 /* The following loop must not be parsing the temporary
3655 buffer, but head.block or tail.block. */
3656
3657 /* mrec!=NULL means that the next record starts from the
3658 middle of the block */
3659 ut_ad((mrec == nullptr) == (index->online_log->head.bytes == 0));
3660
3661 #ifdef UNIV_DEBUG
3662 if (index->online_log->head.block != nullptr &&
3663 next_mrec_end == index->online_log->head.block + srv_sort_buf_size) {
3664 /* If tail.bytes == 0, next_mrec_end can also be at
3665 the end of tail.block. */
3666 if (index->online_log->tail.bytes == 0) {
3667 ut_ad(next_mrec == next_mrec_end);
3668 ut_ad(index->online_log->tail.blocks == 0);
3669 ut_ad(index->online_log->head.blocks == 0);
3670 ut_ad(index->online_log->head.bytes == 0);
3671 } else {
3672 ut_ad(next_mrec ==
3673 index->online_log->head.block + index->online_log->head.bytes);
3674 ut_ad(index->online_log->tail.blocks > index->online_log->head.blocks);
3675 }
3676 } else if (next_mrec_end ==
3677 index->online_log->tail.block + index->online_log->tail.bytes) {
3678 ut_ad(next_mrec ==
3679 index->online_log->tail.block + index->online_log->head.bytes);
3680 ut_ad(index->online_log->tail.blocks == 0);
3681 ut_ad(index->online_log->head.blocks == 0);
3682 ut_ad(index->online_log->head.bytes <= index->online_log->tail.bytes);
3683 } else {
3684 ut_error;
3685 }
3686 #endif /* UNIV_DEBUG */
3687
3688 mrec_end = next_mrec_end;
3689
3690 while (!trx_is_interrupted(trx)) {
3691 mrec = next_mrec;
3692 ut_ad(mrec < mrec_end);
3693
3694 if (!has_index_lock) {
3695 /* We are applying operations from a different
3696 block than the one that is being written to.
3697 We do not hold index->lock in order to
3698 allow other threads to concurrently buffer
3699 modifications. */
3700 ut_ad(mrec >= index->online_log->head.block);
3701 ut_ad(mrec_end == index->online_log->head.block + srv_sort_buf_size);
3702 ut_ad(index->online_log->head.bytes < srv_sort_buf_size);
3703
3704 /* Take the opportunity to do a redo log
3705 checkpoint if needed. */
3706 log_free_check();
3707 } else {
3708 /* We are applying operations from the last block.
3709 Do not allow other threads to buffer anything,
3710 so that we can finally catch up and synchronize. */
3711 ut_ad(index->online_log->head.blocks == 0);
3712 ut_ad(index->online_log->tail.blocks == 0);
3713 ut_ad(mrec_end ==
3714 index->online_log->tail.block + index->online_log->tail.bytes);
3715 ut_ad(mrec >= index->online_log->tail.block);
3716 }
3717
3718 next_mrec = row_log_apply_op(index, dup, &error, offsets_heap, heap,
3719 has_index_lock, mrec, mrec_end, offsets);
3720
3721 if (error != DB_SUCCESS) {
3722 goto func_exit;
3723 } else if (next_mrec == next_mrec_end) {
3724 /* The record happened to end on a block boundary.
3725 Do we have more blocks left? */
3726 if (has_index_lock) {
3727 /* The index will be locked while
3728 applying the last block. */
3729 goto all_done;
3730 }
3731
3732 mrec = nullptr;
3733 process_next_block:
3734 rw_lock_x_lock(dict_index_get_lock(index), UT_LOCATION_HERE);
3735 has_index_lock = true;
3736
3737 index->online_log->head.bytes = 0;
3738 index->online_log->head.blocks++;
3739 goto next_block;
3740 } else if (next_mrec != nullptr) {
3741 ut_ad(next_mrec < next_mrec_end);
3742 index->online_log->head.bytes += next_mrec - mrec;
3743 } else if (has_index_lock) {
3744 /* When mrec is within tail.block, it should
3745 be a complete record, because we are holding
3746 index->lock and thus excluding the writer. */
3747 ut_ad(index->online_log->tail.blocks == 0);
3748 ut_ad(mrec_end ==
3749 index->online_log->tail.block + index->online_log->tail.bytes);
3750 ut_d(ut_error);
3751 ut_o(goto unexpected_eof);
3752 } else {
3753 memcpy(index->online_log->head.buf, mrec, mrec_end - mrec);
3754 mrec_end += index->online_log->head.buf - mrec;
3755 mrec = index->online_log->head.buf;
3756 goto process_next_block;
3757 }
3758 }
3759
3760 interrupted:
3761 error = DB_INTERRUPTED;
3762 func_exit:
3763 if (!has_index_lock) {
3764 rw_lock_x_lock(dict_index_get_lock(index), UT_LOCATION_HERE);
3765 }
3766
3767 switch (error) {
3768 case DB_SUCCESS:
3769 break;
3770 case DB_INDEX_CORRUPT:
3771 if (((os_offset_t)index->online_log->tail.blocks + 1) *
3772 srv_sort_buf_size >=
3773 srv_online_max_size) {
3774 /* The log file grew too big. */
3775 error = DB_ONLINE_LOG_TOO_BIG;
3776 }
3777 [[fallthrough]];
3778 default:
3779 /* We set the flag directly instead of
3780 invoking dict_set_corrupted() here,
3781 because the index is not "public" yet. */
3782 index->type |= DICT_CORRUPT;
3783 }
3784
3785 mem_heap_free(heap);
3786 mem_heap_free(offsets_heap);
3787 row_log_block_free(index->online_log->head);
3788 ut::free(offsets);
3789 return (error);
3790 }
3791
3792 /** Apply the row log to the index upon completing index creation.
3793 @param[in] trx transaction (for checking if the operation was
3794 interrupted)
3795 @param[in,out] index secondary index
3796 @param[in,out] table MySQL table (for reporting duplicates)
3797 @param[in,out] stage performance schema accounting object, used by
3798 ALTER TABLE. stage->begin_phase_log_index() will be called initially and then
3799 stage->inc() will be called for each block of log that is applied.
3800 @return DB_SUCCESS, or error code on failure */
3801 dberr_t row_log_apply(const trx_t *trx, dict_index_t *index,
3802 struct TABLE *table, Alter_stage *stage) {
3803 dberr_t error;
3804 row_log_t *log;
3805 ddl::Dup dup = {index, table, nullptr, 0};
3806 DBUG_TRACE;
3807
3808 ut_ad(dict_index_is_online_ddl(index));
3809 ut_ad(!index->is_clustered());
3810
3811 stage->begin_phase_log_index();
3812
3813 log_free_check();
3814
3815 rw_lock_x_lock(dict_index_get_lock(index), UT_LOCATION_HERE);
3816
3817 if (!index->table->is_corrupted()) {
3818 error = row_log_apply_ops(trx, index, &dup, stage);
3819 } else {
3820 error = DB_SUCCESS;
3821 }
3822
3823 if (error != DB_SUCCESS) {
3824 ut_a(!dict_table_is_discarded(index->table));
3825 /* We set the flag directly instead of
3826 invoking dict_set_corrupted() here,
3827 because the index is not "public" yet. */
3828 index->type |= DICT_CORRUPT;
3829 index->table->drop_aborted = true;
3830
3831 dict_index_set_online_status(index, ONLINE_INDEX_ABORTED);
3832 } else {
3833 ut_ad(dup.m_n_dup == 0);
3834 dict_index_set_online_status(index, ONLINE_INDEX_COMPLETE);
3835 }
3836
3837 log = index->online_log;
3838 index->online_log = nullptr;
3839 rw_lock_x_unlock(dict_index_get_lock(index));
3840
3841 row_log_free(log);
3842
3843 return error;
3844 }