Debian Codegraph @

storage/innobase/row/row0ins.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 1996, 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/row0ins.cc
29 Insert into a table
30
31 Created 4/20/1996 Heikki Tuuri
32 *******************************************************/
33
34 #include <sys/types.h>
35
36 #include "btr0btr.h"
37 #include "btr0cur.h"
38 #include "buf0lru.h"
39 #include "current_thd.h"
40 #include "data0data.h"
41 #include "dict0boot.h"
42 #include "dict0dd.h"
43 #include "dict0dict.h"
44 #include "eval0eval.h"
45 #include "fts0fts.h"
46 #include "fts0types.h"
47 #include "gis0geo.h"
48 #include "ha_prototypes.h"
49 #include "lob0lob.h"
50 #include "lock0lock.h"
51 #include "log0chkp.h"
52 #include "m_string.h"
53 #include "mach0data.h"
54 #include "que0que.h"
55 #include "rem0cmp.h"
56 #include "row0ins.h"
57 #include "row0log.h"
58 #include "row0row.h"
59 #include "row0sel.h"
60 #include "row0upd.h"
61 #include "trx0rec.h"
62 #include "trx0undo.h"
63 #include "usr0sess.h"
64
65 #include <debug_sync.h>
66 #include "my_dbug.h"
67
68 /*************************************************************************
69 IMPORTANT NOTE: Any operation that generates redo MUST check that there
70 is enough space in the redo log before for that operation. This is
71 done by calling log_free_check(). The reason for checking the
72 availability of the redo log space before the start of the operation is
73 that we MUST not hold any synchronization objects when performing the
74 check.
75 If you make a change in this module make sure that no codepath is
76 introduced where a call to log_free_check() is bypassed. */
77
78 /** Creates an insert node struct.
79 @return own: insert node struct */
80 ins_node_t *ins_node_create(
81 ulint ins_type, /*!< in: INS_VALUES, ... */
82 dict_table_t *table, /*!< in: table where to insert */
83 mem_heap_t *heap) /*!< in: mem heap where created */
84 {
85 ins_node_t *node;
86
87 node = static_cast<ins_node_t *>(mem_heap_alloc(heap, sizeof(ins_node_t)));
88
89 node->common.type = QUE_NODE_INSERT;
90
91 node->ins_type = ins_type;
92
93 node->state = INS_NODE_SET_IX_LOCK;
94 node->table = table;
95 node->index = nullptr;
96 node->entry = nullptr;
97
98 node->select = nullptr;
99
100 node->trx_id = 0;
101
102 node->entry_sys_heap = mem_heap_create(128, UT_LOCATION_HERE);
103
104 node->magic_n = INS_NODE_MAGIC_N;
105
106 node->ins_multi_val_pos = 0;
107
108 return (node);
109 }
110
111 /** Creates an entry template for each index of a table. */
112 static void ins_node_create_entry_list(
113 ins_node_t *node) /*!< in: row insert node */
114 {
115 dict_index_t *index;
116 dtuple_t *entry;
117
118 ut_ad(node->entry_sys_heap);
119
120 UT_LIST_INIT(node->entry_list);
121
122 /* We will include all indexes (include those corrupted
123 secondary indexes) in the entry list. Filteration of
124 these corrupted index will be done in row_ins() */
125
126 for (index = node->table->first_index(); index != nullptr;
127 index = index->next()) {
128 entry = row_build_index_entry_low(
129 node->row, nullptr, index, node->entry_sys_heap, ROW_BUILD_FOR_INSERT);
130
131 UT_LIST_ADD_LAST(node->entry_list, entry);
132 }
133 }
134
135 /** Adds system field buffers to a row. */
136 static void row_ins_alloc_sys_fields(ins_node_t *node) /*!< in: insert node */
137 {
138 dtuple_t *row;
139 dict_table_t *table;
140 mem_heap_t *heap;
141 const dict_col_t *col;
142 dfield_t *dfield;
143 byte *ptr;
144
145 row = node->row;
146 table = node->table;
147 heap = node->entry_sys_heap;
148
149 ut_ad(row && table && heap);
150 ut_ad(dtuple_get_n_fields(row) == table->get_n_cols());
151
152 /* allocate buffer to hold the needed system created hidden columns. */
153 uint len = DATA_ROW_ID_LEN + DATA_TRX_ID_LEN;
154 if (!table->is_intrinsic()) {
155 len += DATA_ROLL_PTR_LEN;
156 }
157 ptr = static_cast<byte *>(mem_heap_zalloc(heap, len));
158
159 /* 1. Populate row-id */
160 col = table->get_sys_col(DATA_ROW_ID);
161
162 dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
163
164 dfield_set_data(dfield, ptr, DATA_ROW_ID_LEN);
165
166 node->row_id_buf = ptr;
167
168 ptr += DATA_ROW_ID_LEN;
169
170 /* 2. Populate trx id */
171 col = table->get_sys_col(DATA_TRX_ID);
172
173 dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
174
175 dfield_set_data(dfield, ptr, DATA_TRX_ID_LEN);
176
177 node->trx_id_buf = ptr;
178
179 ptr += DATA_TRX_ID_LEN;
180
181 if (!table->is_intrinsic()) {
182 col = table->get_sys_col(DATA_ROLL_PTR);
183
184 dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
185
186 dfield_set_data(dfield, ptr, DATA_ROLL_PTR_LEN);
187 }
188 }
189
190 /** Sets a new row to insert for an INS_DIRECT node. This function is only used
191 if we have constructed the row separately, which is a rare case; this
192 function is quite slow. */
193 void ins_node_set_new_row(
194 ins_node_t *node, /*!< in: insert node */
195 dtuple_t *row) /*!< in: new row (or first row) for the node */
196 {
197 node->state = INS_NODE_SET_IX_LOCK;
198 node->index = nullptr;
199 node->entry = nullptr;
200
201 node->row = row;
202
203 mem_heap_empty(node->entry_sys_heap);
204
205 /* Create templates for index entries */
206
207 ins_node_create_entry_list(node);
208
209 /* Allocate from entry_sys_heap buffers for sys fields */
210
211 row_ins_alloc_sys_fields(node);
212
213 /* As we allocated a new trx id buf, the trx id should be written
214 there again: */
215
216 node->trx_id = 0;
217 }
218
219 /** Does an insert operation by updating a delete-marked existing record
220 in the index. This situation can occur if the delete-marked record is
221 kept in the index for consistent reads.
222 @return DB_SUCCESS or error code */
223 [[nodiscard]] static dberr_t row_ins_sec_index_entry_by_modify(
224 ulint flags, /*!< in: undo logging and locking flags */
225 ulint mode, /*!< in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
226 depending on whether mtr holds just a leaf
227 latch or also a tree latch */
228 btr_cur_t *cursor, /*!< in: B-tree cursor */
229 ulint **offsets, /*!< in/out: offsets on cursor->page_cur.rec */
230 mem_heap_t *offsets_heap,
231 /*!< in/out: memory heap that can be emptied */
232 mem_heap_t *heap, /*!< in/out: memory heap */
233 const dtuple_t *entry, /*!< in: index entry to insert */
234 que_thr_t *thr, /*!< in: query thread */
235 mtr_t *mtr) /*!< in: mtr; must be committed before
236 latching any further pages */
237 {
238 big_rec_t *dummy_big_rec;
239 upd_t *update;
240 rec_t *rec;
241 dberr_t err;
242
243 rec = btr_cur_get_rec(cursor);
244
245 ut_ad(!cursor->index->is_clustered());
246 ut_ad(rec_offs_validate(rec, cursor->index, *offsets));
247 ut_ad(!entry->info_bits);
248
249 /* We know that in the alphabetical ordering, entry and rec are
250 identified. But in their binary form there may be differences if
251 there are char fields in them. Therefore we have to calculate the
252 difference. */
253
254 update = row_upd_build_sec_rec_difference_binary(rec, cursor->index, *offsets,
255 entry, heap);
256 ut_d(update->validate_for_index(cursor->index));
257
258 if (!rec_get_deleted_flag(rec, rec_offs_comp(*offsets))) {
259 /* We should never insert in place of a record that
260 has not been delete-marked. The only exception is when
261 online CREATE INDEX copied the changes that we already
262 made to the clustered index, and completed the
263 secondary index creation before we got here. In this
264 case, the change would already be there. The CREATE
265 INDEX should be waiting for a MySQL meta-data lock
266 upgrade at least until this INSERT or UPDATE
267 returns. After that point, set_committed(true)
268 would be invoked in commit_inplace_alter_table(). */
269 ut_a(update->n_fields == 0);
270 ut_a(!cursor->index->is_committed());
271 ut_ad(!dict_index_is_online_ddl(cursor->index));
272 return (DB_SUCCESS);
273 }
274
275 if (mode == BTR_MODIFY_LEAF) {
276 /* Try an optimistic updating of the record, keeping changes
277 within the page */
278
279 /* TODO: pass only *offsets */
280 err = btr_cur_optimistic_update(flags | BTR_KEEP_SYS_FLAG, cursor, offsets,
281 &offsets_heap, update, 0, thr,
282 thr_get_trx(thr)->id, mtr);
283 switch (err) {
284 case DB_OVERFLOW:
285 case DB_UNDERFLOW:
286 case DB_ZIP_OVERFLOW:
287 err = DB_FAIL;
288 default:
289 break;
290 }
291 } else {
292 ut_a(mode == BTR_MODIFY_TREE);
293 if (buf_LRU_buf_pool_running_out()) {
294 return (DB_LOCK_TABLE_FULL);
295 }
296
297 trx_t *trx = thr_get_trx(thr);
298 err = btr_cur_pessimistic_update(
299 flags | BTR_KEEP_SYS_FLAG, cursor, offsets, &offsets_heap, heap,
300 &dummy_big_rec, update, 0, thr, trx->id, trx->undo_no, mtr);
301 ut_ad(!dummy_big_rec);
302 }
303
304 return err;
305 }
306
307 /** Does an insert operation by delete unmarking and updating a delete marked
308 existing record in the index. This situation can occur if the delete marked
309 record is kept in the index for consistent reads.
310 @return DB_SUCCESS, DB_FAIL, or error code */
311 [[nodiscard]] static dberr_t row_ins_clust_index_entry_by_modify(
312 btr_pcur_t *pcur, /*!< in/out: a persistent cursor pointing
313 to the clust_rec that is being modified. */
314 ulint flags, /*!< in: undo logging and locking flags */
315 ulint mode, /*!< in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
316 depending on whether mtr holds just a leaf
317 latch or also a tree latch */
318 ulint **offsets, /*!< out: offsets on cursor->page_cur.rec */
319 mem_heap_t **offsets_heap,
320 /*!< in/out: pointer to memory heap that can
321 be emptied, or NULL */
322 mem_heap_t *heap, /*!< in/out: memory heap */
323 const dtuple_t *entry, /*!< in: index entry to insert */
324 que_thr_t *thr, /*!< in: query thread */
325 mtr_t *mtr) /*!< in: mtr; must be committed before
326 latching any further pages */
327 {
328 const rec_t *rec;
329 upd_t *update;
330 dberr_t err = DB_SUCCESS;
331 btr_cur_t *cursor = pcur->get_btr_cur();
332 TABLE *mysql_table = nullptr;
333 ut_ad(cursor->index->is_clustered());
334
335 rec = btr_cur_get_rec(cursor);
336
337 ut_ad(rec_get_deleted_flag(rec, dict_table_is_comp(cursor->index->table)));
338
339 /* Build an update vector containing all the fields to be modified;
340 NOTE that this vector may NOT contain system columns trx_id or
341 roll_ptr */
342 if (thr->prebuilt != nullptr) {
343 mysql_table = thr->prebuilt->m_mysql_table;
344 ut_ad(thr->prebuilt->trx == thr_get_trx(thr));
345 }
346
347 update = row_upd_build_difference_binary(cursor->index, entry, rec, nullptr,
348 true, thr_get_trx(thr), heap,
349 mysql_table, &err);
350 if (err != DB_SUCCESS) {
351 return err;
352 }
353 if (mode != BTR_MODIFY_TREE) {
354 ut_ad((mode & ~BTR_ALREADY_S_LATCHED) == BTR_MODIFY_LEAF);
355 ut_ad(update);
356 ut_d(update->validate_for_index(cursor->index));
357
358 /* Try optimistic updating of the record, keeping changes
359 within the page */
360
361 err = btr_cur_optimistic_update(flags, cursor, offsets, offsets_heap,
362 update, 0, thr, thr_get_trx(thr)->id, mtr);
363 switch (err) {
364 case DB_OVERFLOW:
365 case DB_UNDERFLOW:
366 case DB_ZIP_OVERFLOW:
367 err = DB_FAIL;
368 default:
369 break;
370 }
371 } else {
372 if (buf_LRU_buf_pool_running_out()) {
373 return DB_LOCK_TABLE_FULL;
374 }
375
376 big_rec_t *big_rec = nullptr;
377 trx_t *trx = thr_get_trx(thr);
378 trx_id_t trx_id = thr_get_trx(thr)->id;
379
380 DEBUG_SYNC_C("before_row_ins_upd_pessimistic");
381
382 err = btr_cur_pessimistic_update(flags | BTR_KEEP_POS_FLAG, cursor, offsets,
383 offsets_heap, heap, &big_rec, update, 0,
384 thr, trx_id, trx->undo_no, mtr);
385
386 if (big_rec) {
387 ut_a(err == DB_SUCCESS);
388
389 DEBUG_SYNC_C("before_row_ins_upd_extern");
390 err = lob::btr_store_big_rec_extern_fields(
391 trx, pcur, update, *offsets, big_rec, mtr, lob::OPCODE_INSERT_UPDATE);
392 DEBUG_SYNC_C("after_row_ins_upd_extern");
393 dtuple_big_rec_free(big_rec);
394 }
395 }
396
397 return err;
398 }
399
400 /** Returns true if in a cascaded update/delete an ancestor node of node
401 updates (not DELETE, but UPDATE) table.
402 @return true if an ancestor updates table */
403 static bool row_ins_cascade_ancestor_updates_table(
404 que_node_t *node, /*!< in: node in a query graph */
405 dict_table_t *table) /*!< in: table */
406 {
407 que_node_t *parent;
408
409 for (parent = que_node_get_parent(node);
410 que_node_get_type(parent) == QUE_NODE_UPDATE;
411 parent = que_node_get_parent(parent)) {
412 upd_node_t *upd_node;
413
414 upd_node = static_cast<upd_node_t *>(parent);
415
416 if (upd_node->table == table && upd_node->is_delete == false) {
417 return true;
418 }
419 }
420
421 return false;
422 }
423
424 /** Returns the number of ancestor UPDATE or DELETE nodes of a
425 cascaded update/delete node.
426 @return number of ancestors */
427 [[nodiscard]] static ulint row_ins_cascade_n_ancestors(
428 que_node_t *node) /*!< in: node in a query graph */
429 {
430 que_node_t *parent;
431 ulint n_ancestors = 0;
432
433 for (parent = que_node_get_parent(node);
434 que_node_get_type(parent) == QUE_NODE_UPDATE;
435 parent = que_node_get_parent(parent)) {
436 n_ancestors++;
437 }
438
439 return (n_ancestors);
440 }
441
442 /** Calculates the update vector node->cascade->update for a child table in
443 a cascaded update.
444 @return number of fields in the calculated update vector; the value
445 can also be 0 if no foreign key fields changed; the returned value is
446 ULINT_UNDEFINED if the column type in the child table is too short to
447 fit the new value in the parent table: that means the update fails */
448 [[nodiscard]] static ulint row_ins_cascade_calc_update_vec(
449 upd_node_t *node, /*!< in: update node of the parent
450 table */
451 dict_foreign_t *foreign, /*!< in: foreign key constraint whose
452 type is != 0 */
453 mem_heap_t *heap, /*!< in: memory heap to use as
454 temporary storage */
455 trx_t *trx, /*!< in: update transaction */
456 bool *fts_col_affected)
457 /*!< out: is FTS column affected */
458 {
459 upd_node_t *cascade = node->cascade_node;
460 dict_table_t *table = foreign->foreign_table;
461 dict_index_t *index = foreign->foreign_index;
462 upd_t *update;
463 dict_table_t *parent_table;
464 dict_index_t *parent_index;
465 upd_t *parent_update;
466 ulint n_fields_updated;
467 ulint parent_field_no;
468 ulint i;
469 ulint j;
470 bool doc_id_updated = false;
471 ulint doc_id_pos = 0;
472 doc_id_t new_doc_id = FTS_NULL_DOC_ID;
473
474 ut_a(node);
475 ut_a(foreign);
476 ut_a(cascade);
477 ut_a(table);
478 ut_a(index);
479
480 /* Calculate the appropriate update vector which will set the fields
481 in the child index record to the same value (possibly padded with
482 spaces if the column is a fixed length CHAR or FIXBINARY column) as
483 the referenced index record will get in the update. */
484
485 parent_table = node->table;
486 ut_a(parent_table == foreign->referenced_table);
487 parent_index = foreign->referenced_index;
488 parent_update = node->update;
489
490 update = cascade->update;
491
492 update->info_bits = 0;
493
494 n_fields_updated = 0;
495
496 *fts_col_affected = foreign->is_fts_col_affected();
497
498 if (table->fts) {
499 doc_id_pos = dict_table_get_nth_col_pos(table, table->fts->doc_col);
500 }
501
502 for (i = 0; i < foreign->n_fields; i++) {
503 parent_field_no =
504 dict_table_get_nth_col_pos(parent_table, parent_index->get_col_no(i));
505
506 for (j = 0; j < parent_update->n_fields; j++) {
507 const upd_field_t *parent_ufield = &parent_update->fields[j];
508
509 /* Skip if the updated field is virtual */
510 if (parent_ufield->is_virtual()) {
511 continue;
512 }
513
514 if (parent_ufield->field_no == parent_field_no) {
515 ulint min_size;
516 const dict_col_t *col;
517 ulint ufield_len;
518 upd_field_t *ufield;
519
520 col = index->get_col(i);
521
522 /* A field in the parent index record is
523 updated. Let us make the update vector
524 field for the child table. */
525
526 ufield = update->fields + n_fields_updated;
527
528 ufield->field_no =
529 dict_table_get_nth_col_pos(table, dict_col_get_no(col));
530 IF_DEBUG(ufield->field_phy_pos = col->get_col_phy_pos());
531
532 ufield->orig_len = 0;
533 ufield->exp = nullptr;
534
535 ufield->new_val = parent_ufield->new_val;
536 ufield_len = dfield_get_len(&ufield->new_val);
537
538 /* Clear the "external storage" flag */
539 dfield_set_len(&ufield->new_val, ufield_len);
540
541 /* Do not allow a NOT NULL column to be
542 updated as NULL */
543
544 if (dfield_is_null(&ufield->new_val) && (col->prtype & DATA_NOT_NULL)) {
545 return (ULINT_UNDEFINED);
546 }
547
548 /* If the new value would not fit in the
549 column, do not allow the update */
550
551 if (!dfield_is_null(&ufield->new_val) &&
552 dtype_get_at_most_n_mbchars(
553 col->prtype, col->mbminmaxlen, col->len, ufield_len,
554 static_cast<char *>(dfield_get_data(&ufield->new_val))) <
555 ufield_len) {
556 return (ULINT_UNDEFINED);
557 }
558
559 /* If the parent column type has a different
560 length than the child column type, we may
561 need to pad with spaces the new value of the
562 child column */
563
564 min_size = col->get_min_size();
565
566 /* Because UNIV_SQL_NULL (the marker
567 of SQL NULL values) exceeds all possible
568 values of min_size, the test below will
569 not hold for SQL NULL columns. */
570
571 if (min_size > ufield_len) {
572 byte *pad;
573 ulint pad_len;
574 byte *padded_data;
575 ulint mbminlen;
576
577 padded_data = static_cast<byte *>(mem_heap_alloc(heap, min_size));
578
579 pad = padded_data + ufield_len;
580 pad_len = min_size - ufield_len;
581
582 memcpy(padded_data, dfield_get_data(&ufield->new_val), ufield_len);
583
584 mbminlen = col->get_mbminlen();
585
586 ut_ad(!(ufield_len % mbminlen));
587 ut_ad(!(min_size % mbminlen));
588
589 if (mbminlen == 1 && dtype_get_charset_coll(col->prtype) ==
590 DATA_MYSQL_BINARY_CHARSET_COLL) {
591 /* Do not pad BINARY columns */
592 return (ULINT_UNDEFINED);
593 }
594
595 row_mysql_pad_col(mbminlen, pad, pad_len);
596 dfield_set_data(&ufield->new_val, padded_data, min_size);
597 }
598
599 /* If Doc ID is updated, check whether the
600 Doc ID is valid */
601 if (table->fts && ufield->field_no == doc_id_pos) {
602 doc_id_t n_doc_id;
603
604 n_doc_id = table->fts->cache->next_doc_id;
605
606 new_doc_id = fts_read_doc_id(
607 static_cast<const byte *>(dfield_get_data(&ufield->new_val)));
608
609 if (new_doc_id <= 0) {
610 ib::error(ER_IB_MSG_954) << "FTS Doc ID"
611 " must be larger than"
612 " 0";
613 return (ULINT_UNDEFINED);
614 }
615
616 if (new_doc_id < n_doc_id) {
617 ib::error(ER_IB_MSG_955)
618 << "FTS Doc ID"
619 " must be larger than "
620 << n_doc_id - 1 << " for table " << table->name;
621
622 return (ULINT_UNDEFINED);
623 }
624
625 *fts_col_affected = true;
626 doc_id_updated = true;
627 }
628
629 n_fields_updated++;
630 }
631 }
632 }
633
634 /* Generate a new Doc ID if FTS index columns get updated */
635 if (table->fts && *fts_col_affected) {
636 if (DICT_TF2_FLAG_IS_SET(table, DICT_TF2_FTS_HAS_DOC_ID)) {
637 doc_id_t doc_id;
638 doc_id_t *next_doc_id;
639 upd_field_t *ufield;
640
641 next_doc_id =
642 static_cast<doc_id_t *>(mem_heap_alloc(heap, sizeof(doc_id_t)));
643
644 ut_ad(!doc_id_updated);
645 ufield = update->fields + n_fields_updated;
646 fts_get_next_doc_id(table, next_doc_id);
647 doc_id = fts_update_doc_id(table, ufield, next_doc_id);
648 n_fields_updated++;
649 fts_trx_add_op(trx, table, doc_id, FTS_INSERT, nullptr);
650 } else {
651 if (doc_id_updated) {
652 ut_ad(new_doc_id);
653 fts_trx_add_op(trx, table, new_doc_id, FTS_INSERT, nullptr);
654 } else {
655 ib::error(ER_IB_MSG_956) << "FTS Doc ID must be updated"
656 " along with FTS indexed column for"
657 " table "
658 << table->name;
659 return (ULINT_UNDEFINED);
660 }
661 }
662 }
663
664 update->n_fields = n_fields_updated;
665
666 return (n_fields_updated);
667 }
668
669 /** Set detailed error message associated with foreign key errors for
670 the given transaction. */
671 static void row_ins_set_detailed(
672 trx_t *trx, /*!< in: transaction */
673 dict_foreign_t *foreign) /*!< in: foreign key constraint */
674 {
675 ut_ad(!srv_read_only_mode);
676
677 mutex_enter(&srv_misc_tmpfile_mutex);
678 rewind(srv_misc_tmpfile);
679
680 if (os_file_set_eof(srv_misc_tmpfile)) {
681 ut_print_name(srv_misc_tmpfile, trx, foreign->foreign_table_name);
682 dict_print_info_on_foreign_key_in_create_format(srv_misc_tmpfile, trx,
683 foreign, false);
684 trx_set_detailed_error_from_file(trx, srv_misc_tmpfile);
685 } else {
686 trx_set_detailed_error(trx, "temp file operation failed");
687 }
688
689 mutex_exit(&srv_misc_tmpfile_mutex);
690 }
691
692 /** Acquires dict_foreign_err_mutex, rewinds dict_foreign_err_file
693 and displays information about the given transaction.
694 The caller must release dict_foreign_err_mutex. */
695 static void row_ins_foreign_trx_print(trx_t *trx) /*!< in: transaction */
696 {
697 ulint n_rec_locks;
698 ulint n_trx_locks;
699 ulint heap_size;
700
701 if (srv_read_only_mode) {
702 return;
703 }
704
705 {
706 /** lock_number_of_rows_locked() requires global exclusive latch, and so
707 does accessing trx_locks with trx->mutex */
708 locksys::Global_exclusive_latch_guard guard{UT_LOCATION_HERE};
709 n_rec_locks = lock_number_of_rows_locked(&trx->lock);
710 n_trx_locks = UT_LIST_GET_LEN(trx->lock.trx_locks);
711 heap_size = mem_heap_get_size(trx->lock.lock_heap);
712 }
713
714 trx_sys_mutex_enter();
715
716 mutex_enter(&dict_foreign_err_mutex);
717 rewind(dict_foreign_err_file);
718 ut_print_timestamp(dict_foreign_err_file);
719 fputs(" Transaction:\n", dict_foreign_err_file);
720
721 trx_print_low(dict_foreign_err_file, trx, 600, n_rec_locks, n_trx_locks,
722 heap_size);
723
724 trx_sys_mutex_exit();
725
726 ut_ad(mutex_own(&dict_foreign_err_mutex));
727 }
728
729 /** Reports a foreign key error associated with an update or a delete of a
730 parent table index entry. */
731 static void row_ins_foreign_report_err(
732 const char *errstr, /*!< in: error string from the viewpoint
733 of the parent table */
734 que_thr_t *thr, /*!< in: query thread whose run_node
735 is an update node */
736 dict_foreign_t *foreign, /*!< in: foreign key constraint */
737 const rec_t *rec, /*!< in: a matching index record in the
738 child table */
739 const dtuple_t *entry) /*!< in: index entry in the parent
740 table */
741 {
742 if (srv_read_only_mode) {
743 return;
744 }
745
746 FILE *ef = dict_foreign_err_file;
747 trx_t *trx = thr_get_trx(thr);
748
749 row_ins_set_detailed(trx, foreign);
750
751 row_ins_foreign_trx_print(trx);
752
753 fputs("Foreign key constraint fails for table ", ef);
754 ut_print_name(ef, trx, foreign->foreign_table_name);
755 fputs(":\n", ef);
756 dict_print_info_on_foreign_key_in_create_format(ef, trx, foreign, true);
757 putc('\n', ef);
758 fputs(errstr, ef);
759 fprintf(ef, " in parent table, in index %s",
760 foreign->referenced_index->name());
761 if (entry) {
762 fputs(" tuple:\n", ef);
763 dtuple_print(ef, entry);
764 }
765 fputs("\nBut in child table ", ef);
766 ut_print_name(ef, trx, foreign->foreign_table_name);
767 fprintf(ef, ", in index %s", foreign->foreign_index->name());
768 if (rec) {
769 fputs(", there is a record:\n", ef);
770 rec_print(ef, rec, foreign->foreign_index);
771 } else {
772 fputs(", the record is not available\n", ef);
773 }
774 putc('\n', ef);
775
776 mutex_exit(&dict_foreign_err_mutex);
777 }
778
779 /** Reports a foreign key error to dict_foreign_err_file when we are trying
780 to add an index entry to a child table. Note that the adding may be the result
781 of an update, too. */
782 static void row_ins_foreign_report_add_err(
783 trx_t *trx, /*!< in: transaction */
784 dict_foreign_t *foreign, /*!< in: foreign key constraint */
785 const rec_t *rec, /*!< in: a record in the parent table:
786 it does not match entry because we
787 have an error! */
788 const dtuple_t *entry) /*!< in: index entry to insert in the
789 child table */
790 {
791 if (srv_read_only_mode) {
792 return;
793 }
794
795 FILE *ef = dict_foreign_err_file;
796
797 row_ins_set_detailed(trx, foreign);
798
799 row_ins_foreign_trx_print(trx);
800
801 fputs("Foreign key constraint fails for table ", ef);
802 ut_print_name(ef, trx, foreign->foreign_table_name);
803 fputs(":\n", ef);
804 dict_print_info_on_foreign_key_in_create_format(ef, trx, foreign, true);
805 fprintf(ef, "\nTrying to add in child table, in index %s",
806 foreign->foreign_index->name());
807 if (entry) {
808 fputs(" tuple:\n", ef);
809 /* TODO: DB_TRX_ID and DB_ROLL_PTR may be uninitialized.
810 It would be better to only display the user columns. */
811 dtuple_print(ef, entry);
812 }
813 fputs("\nBut in parent table ", ef);
814 ut_print_name(ef, trx, foreign->referenced_table_name);
815 fprintf(ef,
816 ", in index %s,\n"
817 "the closest match we can find is record:\n",
818 foreign->referenced_index->name());
819 if (rec && page_rec_is_supremum(rec)) {
820 /* If the cursor ended on a supremum record, it is better
821 to report the previous record in the error message, so that
822 the user gets a more descriptive error message. */
823 rec = page_rec_get_prev_const(rec);
824 }
825
826 if (rec) {
827 rec_print(ef, rec, foreign->referenced_index);
828 }
829 putc('\n', ef);
830
831 mutex_exit(&dict_foreign_err_mutex);
832 }
833
834 #ifdef UNIV_DEBUG
835
836 /* Check that a referential update action of a foreign key (changing key
837 fields in referencing/child record when referenced/parent record is
838 updated or deleted) has been applied to the child update node. This
839 is a prerequisite for calculating the values of virtual fields,
840 so we check it on a debug assertion. */
841 static void assert_nonvirtual_cascade_fields_are_populated(
842 upd_node_t *cascade, upd_node_t *parent, dict_foreign_t *foreign) {
843 /* Sanity checks - these do not check if the fields are populated,
844 but rather the basic assumptions we rely on to make that check */
845 ut_a(parent);
846 ut_a(parent->update);
847 ut_a(cascade);
848 ut_a(cascade->update);
849 ut_a(foreign);
850 ut_a(foreign->foreign_index);
851 ut_a(foreign->foreign_table);
852 ut_a(foreign->referenced_index);
853 ut_a(foreign->referenced_table);
854 ut_ad(parent->cascade_node == cascade);
855 ut_ad(foreign->foreign_table == cascade->table);
856 ut_ad(foreign->referenced_table == parent->table);
857 /* This cascade update needs to be triggered by an referential action */
858 if (parent->is_delete) {
859 ut_a(foreign->type & DICT_FOREIGN_ON_DELETE_SET_NULL);
860 } else {
861 ut_a(foreign->type &
862 (DICT_FOREIGN_ON_UPDATE_SET_NULL | DICT_FOREIGN_ON_UPDATE_CASCADE));
863 }
864
865 for (uint32_t foreign_pos = 0; foreign_pos < foreign->n_fields;
866 ++foreign_pos) {
867 const auto child_col = foreign->foreign_index->get_col(foreign_pos);
868 /* Sanity check - virtual columns in the child table cannot be part of
869 a foreign key which defines a referential update action */
870 ut_a(child_col);
871 ut_a(!child_col->is_virtual());
872 const auto child_col_no = dict_col_get_no(child_col);
873 /* assume update vector positions refer to clustered indexes */
874 const auto child_field_pos =
875 dict_table_get_nth_col_pos(foreign->foreign_table, child_col_no);
876 const auto child_field_update =
877 upd_get_field_by_field_no(cascade->update, child_field_pos, false);
878 if (parent->is_delete) {
879 ut_a(child_field_update);
880 ut_a(dfield_is_null(&child_field_update->new_val));
881 } else {
882 const auto parent_col = foreign->referenced_index->get_col(foreign_pos);
883 /* Sanity check - virtual columns cannot be referenced by a foreign key */
884 ut_a(!parent_col->is_virtual());
885
886 const auto parent_col_no = dict_col_get_no(parent_col);
887 const auto parent_field_pos =
888 dict_table_get_nth_col_pos(foreign->referenced_table, parent_col_no);
889 const auto parent_field_update =
890 upd_get_field_by_field_no(parent->update, parent_field_pos, false);
891 if (!parent_field_update ||
892 dfield_datas_are_binary_equal(&parent_field_update->old_val,
893 &parent_field_update->new_val)) {
894 continue;
895 }
896 ut_a(child_field_update);
897 if (foreign->type & DICT_FOREIGN_ON_UPDATE_SET_NULL) {
898 ut_a(dfield_is_null(&child_field_update->new_val));
899 } else {
900 /* foreign->type & DICT_FOREIGN_ON_UPDATE_CASCADE */
901 ut_a(dfield_datas_are_binary_equal(&parent_field_update->new_val,
902 &child_field_update->new_val));
903 }
904 }
905 }
906 }
907
908 #endif /* UNIV_DEBUG */
909
910 /** Fill virtual column information in cascade node for the child table.
911 @param[out] cascade child update node
912 @param[in] rec clustered rec of child table
913 @param[in] index clustered index of child table
914 @param[in] node parent update node
915 @param[in] foreign foreign key information.
916 @param[out] err error code. */
917 static void row_ins_foreign_fill_virtual(upd_node_t *cascade, const rec_t *rec,
918 dict_index_t *index, upd_node_t *node,
919 dict_foreign_t *foreign,
920 dberr_t *err) {
921 /* We rely on non-virtual update fields being filed before virtual fields */
922 ut_d(assert_nonvirtual_cascade_fields_are_populated(cascade, node, foreign));
923 row_ext_t *ext;
924 THD *thd = current_thd;
925 ulint offsets_[REC_OFFS_NORMAL_SIZE];
926 mem_heap_t *v_heap = nullptr;
927 upd_t *const update = cascade->update;
928 rec_offs_init(offsets_);
929 const ulint *const offsets = rec_get_offsets(
930 rec, index, offsets_, ULINT_UNDEFINED, UT_LOCATION_HERE, &update->heap);
931 dict_table_t *const table = index->table;
932 const ulint n_v_fld = table->n_v_def;
933 ulint n_diff;
934 upd_field_t *upd_field;
935 const dict_vcol_set *const v_cols = foreign->v_cols;
936
937 update->old_vrow = row_build(ROW_COPY_POINTERS, index, rec, offsets, table,
938 nullptr, nullptr, &ext, update->heap);
939
940 n_diff = update->n_fields;
941
942 update->n_fields += n_v_fld;
943
944 if (table->vc_templ == nullptr) {
945 /** This can occur when there is a cascading
946 delete or update after restart. */
947 innobase_init_vc_templ(table);
948 }
949
950 for (ulint i = 0; i < n_v_fld; i++) {
951 dict_v_col_t *const col = dict_table_get_nth_v_col(table, i);
952 auto it = v_cols->find(col);
953
954 if (it == v_cols->end()) {
955 continue;
956 }
957
958 const dfield_t *const vfield = innobase_get_computed_value(
959 update->old_vrow, col, table, &v_heap, update->heap, thd, nullptr);
960
961 if (vfield == nullptr) {
962 *err = DB_COMPUTE_VALUE_FAILED;
963 goto func_exit;
964 }
965
966 upd_field = upd_get_nth_field(update, n_diff);
967
968 upd_field->old_v_val = static_cast<dfield_t *>(
969 mem_heap_alloc(update->heap, sizeof *upd_field->old_v_val));
970
971 dfield_copy(upd_field->old_v_val, vfield);
972
973 upd_field_set_v_field_no(upd_field, i, index);
974
975 if (!dict_vcol_base_is_foreign_key(col, foreign)) {
976 /* If no base column of virtual col is in FK, the virtual field
977 is not affected by update */
978 dfield_copy(&(upd_field->new_val), vfield);
979 } else {
980 const dfield_t *const new_vfield = innobase_get_computed_value(
981 update->old_vrow, col, table, &v_heap, update->heap, thd, nullptr,
982 nullptr, nullptr, update);
983
984 if (new_vfield == nullptr) {
985 *err = DB_COMPUTE_VALUE_FAILED;
986 goto func_exit;
987 }
988
989 dfield_copy(&(upd_field->new_val), new_vfield);
990 }
991
992 n_diff++;
993 }
994
995 update->n_fields = n_diff;
996 *err = DB_SUCCESS;
997
998 func_exit:
999 if (v_heap) {
1000 mem_heap_free(v_heap);
1001 }
1002 }
1003
1004 /** Perform referential actions or checks when a parent row is deleted or
1005 updated and the constraint had an ON DELETE or ON UPDATE condition which was
1006 not RESTRICT.
1007 @return DB_SUCCESS, DB_LOCK_WAIT, or error code
1008 Disable inlining because of a bug in gcc8 which may lead to stack exhaustion.
1009 */
1010 [[nodiscard]] static NO_INLINE dberr_t row_ins_foreign_check_on_constraint(
1011 que_thr_t *thr, /*!< in: query thread whose run_node
1012 is an update node */
1013 dict_foreign_t *foreign, /*!< in: foreign key constraint whose
1014 type is != 0 */
1015 btr_pcur_t *pcur, /*!< in: cursor placed on a matching
1016 index record in the child table */
1017 dtuple_t *entry, /*!< in: index entry in the parent
1018 table */
1019 mtr_t *mtr) /*!< in: mtr holding the latch of pcur
1020 page */
1021 {
1022 upd_node_t *node;
1023 upd_node_t *cascade;
1024 dict_table_t *table = foreign->foreign_table;
1025 dict_index_t *index;
1026 dict_index_t *clust_index;
1027 dtuple_t *ref;
1028 const rec_t *rec;
1029 const rec_t *clust_rec;
1030 const buf_block_t *clust_block;
1031 upd_t *update;
1032 ulint n_to_update;
1033 dberr_t err;
1034 ulint i;
1035 trx_t *trx;
1036 mem_heap_t *tmp_heap = nullptr;
1037 doc_id_t doc_id = FTS_NULL_DOC_ID;
1038
1039 DBUG_TRACE;
1040 ut_a(thr);
1041 ut_a(foreign);
1042 ut_a(pcur);
1043 ut_a(mtr);
1044
1045 trx = thr_get_trx(thr);
1046
1047 node = static_cast<upd_node_t *>(thr->run_node);
1048
1049 if (node->is_delete &&
1050 0 == (foreign->type & (DICT_FOREIGN_ON_DELETE_CASCADE |
1051 DICT_FOREIGN_ON_DELETE_SET_NULL))) {
1052 row_ins_foreign_report_err("Trying to delete", thr, foreign,
1053 pcur->get_rec(), entry);
1054
1055 return DB_ROW_IS_REFERENCED;
1056 }
1057
1058 if (!node->is_delete &&
1059 0 == (foreign->type & (DICT_FOREIGN_ON_UPDATE_CASCADE |
1060 DICT_FOREIGN_ON_UPDATE_SET_NULL))) {
1061 /* This is an UPDATE */
1062
1063 row_ins_foreign_report_err("Trying to update", thr, foreign,
1064 pcur->get_rec(), entry);
1065
1066 return DB_ROW_IS_REFERENCED;
1067 }
1068
1069 if (node->cascade_node == nullptr) {
1070 node->cascade_heap = mem_heap_create(128, UT_LOCATION_HERE);
1071 node->cascade_node =
1072 row_create_update_node_for_mysql(table, node->cascade_heap);
1073 que_node_set_parent(node->cascade_node, node);
1074 }
1075 cascade = node->cascade_node;
1076 cascade->table = table;
1077 cascade->foreign = foreign;
1078
1079 if (node->is_delete && (foreign->type & DICT_FOREIGN_ON_DELETE_CASCADE)) {
1080 cascade->is_delete = true;
1081 } else {
1082 cascade->is_delete = false;
1083
1084 if (foreign->n_fields > cascade->update_n_fields) {
1085 /* We have to make the update vector longer */
1086
1087 cascade->update = upd_create(foreign->n_fields, node->cascade_heap);
1088 cascade->update_n_fields = foreign->n_fields;
1089 }
1090 }
1091
1092 cascade->update->table = table;
1093
1094 /* We do not allow cyclic cascaded updating (DELETE is allowed,
1095 but not UPDATE) of the same table, as this can lead to an infinite
1096 cycle. Check that we are not updating the same table which is
1097 already being modified in this cascade chain. We have to check
1098 this also because the modification of the indexes of a 'parent'
1099 table may still be incomplete, and we must avoid seeing the indexes
1100 of the parent table in an inconsistent state! */
1101
1102 if (!cascade->is_delete &&
1103 row_ins_cascade_ancestor_updates_table(cascade, table)) {
1104 /* We do not know if this would break foreign key
1105 constraints, but play safe and return an error */
1106
1107 err = DB_ROW_IS_REFERENCED;
1108
1109 row_ins_foreign_report_err(
1110 "Trying an update, possibly causing a cyclic"
1111 " cascaded update\n"
1112 "in the child table,",
1113 thr, foreign, pcur->get_rec(), entry);
1114
1115 goto nonstandard_exit_func;
1116 }
1117
1118 if (row_ins_cascade_n_ancestors(cascade) >= FK_MAX_CASCADE_DEL) {
1119 err = DB_FOREIGN_EXCEED_MAX_CASCADE;
1120
1121 row_ins_foreign_report_err("Trying a too deep cascaded delete or update\n",
1122 thr, foreign, pcur->get_rec(), entry);
1123
1124 goto nonstandard_exit_func;
1125 }
1126
1127 index = pcur->get_btr_cur()->index;
1128
1129 ut_a(index == foreign->foreign_index);
1130
1131 rec = pcur->get_rec();
1132
1133 tmp_heap = mem_heap_create(256, UT_LOCATION_HERE);
1134
1135 if (index->is_clustered()) {
1136 /* pcur is already positioned in the clustered index of
1137 the child table */
1138
1139 clust_index = index;
1140 clust_rec = rec;
1141 clust_block = pcur->get_block();
1142 } else {
1143 /* We have to look for the record in the clustered index
1144 in the child table */
1145
1146 clust_index = table->first_index();
1147
1148 ref = row_build_row_ref(ROW_COPY_POINTERS, index, rec, tmp_heap);
1149 cascade->pcur->open_no_init(clust_index, ref, PAGE_CUR_LE, BTR_SEARCH_LEAF,
1150 0, mtr, UT_LOCATION_HERE);
1151
1152 clust_rec = cascade->pcur->get_rec();
1153 clust_block = cascade->pcur->get_block();
1154
1155 if (!page_rec_is_user_rec(clust_rec) ||
1156 cascade->pcur->get_low_match() < dict_index_get_n_unique(clust_index)) {
1157 ib::error(ER_IB_MSG_957)
1158 << "In cascade of a foreign key op index " << index->name
1159 << " of table " << index->table->name;
1160
1161 fputs("InnoDB: record ", stderr);
1162 rec_print(stderr, rec, index);
1163 fputs(
1164 "\n"
1165 "InnoDB: clustered record ",
1166 stderr);
1167 rec_print(stderr, clust_rec, clust_index);
1168 fputs(
1169 "\n"
1170 "InnoDB: Submit a detailed bug report to"
1171 " http://bugs.mysql.com\n",
1172 stderr);
1173 err = DB_SUCCESS;
1174 ut_d(ut_error);
1175
1176 ut_o(goto nonstandard_exit_func);
1177 }
1178 }
1179
1180 /* Set an X-lock on the row to delete or update in the child table */
1181
1182 err = lock_table(0, table, LOCK_IX, thr);
1183
1184 if (err == DB_SUCCESS) {
1185 /* Here it suffices to use a LOCK_REC_NOT_GAP type lock;
1186 we already have a normal shared lock on the appropriate
1187 gap if the search criterion was not unique */
1188
1189 err = lock_clust_rec_read_check_and_lock_alt(
1190 clust_block, clust_rec, clust_index, LOCK_X, LOCK_REC_NOT_GAP, thr);
1191 }
1192
1193 if (err != DB_SUCCESS) {
1194 goto nonstandard_exit_func;
1195 }
1196
1197 if (rec_get_deleted_flag(clust_rec, dict_table_is_comp(table))) {
1198 /* This can happen if there is a circular reference of
1199 rows such that cascading delete comes to delete a row
1200 already in the process of being delete marked */
1201 err = DB_SUCCESS;
1202
1203 goto nonstandard_exit_func;
1204 }
1205
1206 if (table->fts) {
1207 doc_id = fts_get_doc_id_from_rec(table, clust_rec, clust_index, tmp_heap);
1208 }
1209
1210 /* A cascade delete from the parent table triggers delete on the child
1211 table. Before a clustered index record is deleted in the child table,
1212 a copy of row is built to remove secondary index records. This copy of
1213 the row requires virtual columns to be materialized. Hence, if child
1214 table has any virtual columns which are indexed, we have to initialize
1215 virtual column template. */
1216 if (cascade->is_delete && dict_table_has_indexed_v_cols(table) &&
1217 table->vc_templ == nullptr) {
1218 innobase_init_vc_templ(table);
1219 }
1220
1221 if (node->is_delete ? (foreign->type & DICT_FOREIGN_ON_DELETE_SET_NULL)
1222 : (foreign->type & DICT_FOREIGN_ON_UPDATE_SET_NULL)) {
1223 /* Build the appropriate update vector which sets
1224 foreign->n_fields first fields in rec to SQL NULL */
1225
1226 update = cascade->update;
1227
1228 update->info_bits = 0;
1229 update->n_fields = foreign->n_fields;
1230 UNIV_MEM_INVALID(update->fields, update->n_fields * sizeof *update->fields);
1231
1232 for (i = 0; i < foreign->n_fields; i++) {
1233 upd_field_t *ufield = &update->fields[i];
1234 ulint col_no = index->get_col_no(i);
1235
1236 ufield->field_no = dict_table_get_nth_col_pos(table, col_no);
1237 dict_col_t *col = table->get_col(col_no);
1238 IF_DEBUG(ufield->field_phy_pos = col->get_col_phy_pos();)
1239 col->copy_type(dfield_get_type(&ufield->new_val));
1240
1241 ufield->orig_len = 0;
1242 ufield->exp = nullptr;
1243 dfield_set_null(&ufield->new_val);
1244 }
1245
1246 if (foreign->is_fts_col_affected()) {
1247 fts_trx_add_op(trx, table, doc_id, FTS_DELETE, nullptr);
1248 }
1249
1250 if (foreign->v_cols != nullptr && foreign->v_cols->size() > 0) {
1251 row_ins_foreign_fill_virtual(cascade, clust_rec, clust_index, node,
1252 foreign, &err);
1253
1254 if (err != DB_SUCCESS) {
1255 goto nonstandard_exit_func;
1256 }
1257 }
1258
1259 } else if (table->fts && cascade->is_delete) {
1260 /* DICT_FOREIGN_ON_DELETE_CASCADE case */
1261 if (foreign->is_fts_col_affected()) {
1262 fts_trx_add_op(trx, table, doc_id, FTS_DELETE, nullptr);
1263 }
1264 }
1265
1266 if (!node->is_delete && (foreign->type & DICT_FOREIGN_ON_UPDATE_CASCADE)) {
1267 bool fts_col_affected = false;
1268 /* Build the appropriate update vector which sets changing
1269 foreign->n_fields first fields in rec to new values */
1270
1271 n_to_update = row_ins_cascade_calc_update_vec(node, foreign, tmp_heap, trx,
1272 &fts_col_affected);
1273
1274 if (foreign->v_cols != nullptr && foreign->v_cols->size() > 0) {
1275 row_ins_foreign_fill_virtual(cascade, clust_rec, clust_index, node,
1276 foreign, &err);
1277
1278 if (err != DB_SUCCESS) {
1279 goto nonstandard_exit_func;
1280 }
1281 }
1282
1283 if (n_to_update == ULINT_UNDEFINED) {
1284 err = DB_ROW_IS_REFERENCED;
1285
1286 row_ins_foreign_report_err(
1287 "Trying a cascaded update where the"
1288 " updated value in the child\n"
1289 "table would not fit in the length"
1290 " of the column, or the value would\n"
1291 "be NULL and the column is"
1292 " declared as not NULL in the child table,",
1293 thr, foreign, pcur->get_rec(), entry);
1294
1295 goto nonstandard_exit_func;
1296 }
1297
1298 if (cascade->update->n_fields == 0) {
1299 /* The update does not change any columns referred
1300 to in this foreign key constraint: no need to do
1301 anything */
1302
1303 err = DB_SUCCESS;
1304
1305 goto nonstandard_exit_func;
1306 }
1307
1308 /* Mark the old Doc ID as deleted */
1309 if (fts_col_affected) {
1310 ut_ad(table->fts);
1311 fts_trx_add_op(trx, table, doc_id, FTS_DELETE, nullptr);
1312 }
1313 }
1314
1315 /* Store pcur position and initialize or store the cascade node
1316 pcur stored position */
1317
1318 pcur->store_position(mtr);
1319
1320 if (index == clust_index) {
1321 btr_pcur_t::copy_stored_position(cascade->pcur, pcur);
1322 } else {
1323 cascade->pcur->store_position(mtr);
1324 }
1325
1326 mtr_commit(mtr);
1327
1328 ut_a(cascade->pcur->m_rel_pos == BTR_PCUR_ON);
1329
1330 cascade->state = UPD_NODE_UPDATE_CLUSTERED;
1331
1332 err = row_update_cascade_for_mysql(thr, cascade, foreign->foreign_table);
1333
1334 /* Release the data dictionary latch for a while, so that we do not
1335 starve other threads from doing CREATE TABLE etc. if we have a huge
1336 cascaded operation running. The counter n_foreign_key_checks_running
1337 will prevent other users from dropping or ALTERing the table when we
1338 release the latch. */
1339
1340 DEBUG_SYNC_C("innodb_dml_cascade_dict_unfreeze");
1341
1342 mtr_start(mtr);
1343
1344 /* Restore pcur position */
1345
1346 pcur->restore_position(BTR_SEARCH_LEAF, mtr, UT_LOCATION_HERE);
1347
1348 if (tmp_heap) {
1349 mem_heap_free(tmp_heap);
1350 }
1351
1352 return err;
1353
1354 nonstandard_exit_func:
1355
1356 if (tmp_heap) {
1357 mem_heap_free(tmp_heap);
1358 }
1359
1360 pcur->store_position(mtr);
1361
1362 mtr_commit(mtr);
1363 mtr_start(mtr);
1364
1365 pcur->restore_position(BTR_SEARCH_LEAF, mtr, UT_LOCATION_HERE);
1366
1367 return err;
1368 }
1369
1370 /** Sets a lock on a record. Used in locking possible duplicate key
1371 records and also in checking foreign key constraints.
1372 @param[in] mode requested lock type: LOCK_S or LOCK_X mode
1373 @param[in] type LOCK_ORDINARY, LOCK_GAP, or LOCK_REC_NOT_GAP type lock
1374 @param[in] block buffer block of rec
1375 @param[in] rec record
1376 @param[in] index index
1377 @param[in] offsets rec_get_offsets(rec, index)
1378 @param[in] thr query thread
1379 @return DB_SUCCESS, DB_SUCCESS_LOCKED_REC, or error code */
1380 static dberr_t row_ins_set_rec_lock(lock_mode mode, ulint type,
1381 const buf_block_t *block, const rec_t *rec,
1382 dict_index_t *index, const ulint *offsets,
1383 que_thr_t *thr) {
1384 dberr_t err;
1385
1386 ut_ad(rec_offs_validate(rec, index, offsets));
1387
1388 if (index->is_clustered()) {
1389 err = lock_clust_rec_read_check_and_lock(
1390 lock_duration_t::AT_LEAST_STATEMENT, block, rec, index, offsets,
1391 SELECT_ORDINARY, mode, type, thr);
1392 } else {
1393 err = lock_sec_rec_read_check_and_lock(lock_duration_t::AT_LEAST_STATEMENT,
1394 block, rec, index, offsets,
1395 SELECT_ORDINARY, mode, type, thr);
1396 }
1397
1398 return (err);
1399 }
1400
1401 /* Decrement a counter in the destructor. */
1402 class ib_dec_in_dtor {
1403 public:
1404 ib_dec_in_dtor(std::atomic<ulint> &c) : counter(c) {}
1405 ~ib_dec_in_dtor() { counter.fetch_sub(1); }
1406
1407 private:
1408 std::atomic<ulint> &counter;
1409 };
1410
1411 /** Checks if foreign key constraint fails for an index entry. Sets shared locks
1412 which lock either the success or the failure of the constraint. NOTE that
1413 the caller must have a shared latch on dict_operation_lock.
1414 @return DB_SUCCESS, DB_NO_REFERENCED_ROW, or DB_ROW_IS_REFERENCED */
1415 dberr_t row_ins_check_foreign_constraint(
1416 bool check_ref, /*!< in: true if we want to check that
1417 the referenced table is ok, false if we
1418 want to check the foreign key table */
1419 dict_foreign_t *foreign, /*!< in: foreign constraint; NOTE that the
1420 tables mentioned in it must be in the
1421 dictionary cache if they exist at all */
1422 dict_table_t *table, /*!< in: if check_ref is true, then the foreign
1423 table, else the referenced table */
1424 dtuple_t *entry, /*!< in: index entry for index */
1425 que_thr_t *thr) /*!< in: query thread */
1426 {
1427 dberr_t err;
1428 upd_node_t *upd_node;
1429 dict_table_t *check_table = nullptr;
1430 dict_index_t *check_index = nullptr;
1431 ulint n_fields_cmp;
1432 btr_pcur_t pcur;
1433 int cmp;
1434 mtr_t mtr;
1435 trx_t *trx = thr_get_trx(thr);
1436 mem_heap_t *heap = nullptr;
1437 ulint offsets_[REC_OFFS_NORMAL_SIZE];
1438 ulint *offsets = offsets_;
1439
1440 bool skip_gap_lock;
1441 MDL_ticket *mdl = nullptr;
1442 THD *thd = current_thd;
1443 bool tmp_open = false;
1444 dict_foreign_t *tmp_foreign = nullptr;
1445
1446 /* GAP locks are not needed on DD tables because serializability between
1447 different DDL statements is achieved using metadata locks. So no concurrent
1448 changes to DD tables when MDL is taken. */
1449 skip_gap_lock = (trx->isolation_level <= TRX_ISO_READ_COMMITTED) ||
1450 table->skip_gap_locks();
1451
1452 DBUG_TRACE;
1453
1454 if (dict_sys_t::is_dd_table_id(table->id)) {
1455 return DB_SUCCESS;
1456 }
1457
1458 rec_offs_init(offsets_);
1459
1460 err = DB_SUCCESS;
1461
1462 if (trx->check_foreigns == false) {
1463 /* The user has suppressed foreign key checks currently for
1464 this session */
1465 goto exit_func;
1466 }
1467
1468 /* If any of the foreign key fields in entry is SQL NULL, we
1469 suppress the foreign key check: this is compatible with Oracle,
1470 for example */
1471 for (ulint i = 0; i < foreign->n_fields; i++) {
1472 if (dfield_is_null(dtuple_get_nth_field(entry, i))) {
1473 goto exit_func;
1474 }
1475 }
1476
1477 if (que_node_get_type(thr->run_node) == QUE_NODE_UPDATE) {
1478 upd_node = static_cast<upd_node_t *>(thr->run_node);
1479
1480 if (!(upd_node->is_delete) && upd_node->foreign == foreign) {
1481 /* If a cascaded update is done as defined by a
1482 foreign key constraint, do not check that
1483 constraint for the child row. In ON UPDATE CASCADE
1484 the update of the parent row is only half done when
1485 we come here: if we would check the constraint here
1486 for the child row it would fail.
1487
1488 A QUESTION remains: if in the child table there are
1489 several constraints which refer to the same parent
1490 table, we should merge all updates to the child as
1491 one update? And the updates can be contradictory!
1492 Currently we just perform the update associated
1493 with each foreign key constraint, one after
1494 another, and the user has problems predicting in
1495 which order they are performed. */
1496
1497 goto exit_func;
1498 }
1499 }
1500
1501 if (check_ref) {
1502 check_table = foreign->referenced_table;
1503 check_index = foreign->referenced_index;
1504
1505 /* TODO: NewDD: Need to wait for WL#6049, as current
1506 referenced table does have has any info of any FK
1507 referencing to it */
1508 if (check_table == nullptr && foreign->referenced_table_name_lookup) {
1509 ut_ad(check_index == nullptr);
1510
1511 dict_sys_mutex_enter();
1512 check_table = dd_table_open_on_name(thd, &mdl,
1513 foreign->referenced_table_name_lookup,
1514 true, DICT_ERR_IGNORE_NONE);
1515
1516 if (check_table) {
1517 check_index = dict_foreign_find_index(
1518 check_table, nullptr, foreign->referenced_col_names,
1519 foreign->n_fields, foreign->foreign_index, false, false);
1520
1521 if (!check_index) {
1522 dd_table_close(check_table, thd, &mdl, true);
1523 check_table = nullptr;
1524 }
1525 }
1526
1527 if (check_table && check_index) {
1528 tmp_foreign = static_cast<dict_foreign_t *>(ut::malloc_withkey(
1529 UT_NEW_THIS_FILE_PSI_KEY, sizeof(dict_foreign_t)));
1530
1531 memcpy(tmp_foreign, foreign, sizeof(*foreign));
1532
1533 foreign = tmp_foreign;
1534 foreign->referenced_table = check_table;
1535 foreign->referenced_index = check_index;
1536 tmp_open = true;
1537 }
1538 dict_sys_mutex_exit();
1539 }
1540 } else {
1541 check_table = foreign->foreign_table;
1542 check_index = foreign->foreign_index;
1543 }
1544
1545 if (check_table == nullptr || check_table->ibd_file_missing ||
1546 check_index == nullptr) {
1547 if (!srv_read_only_mode && check_ref) {
1548 FILE *ef = dict_foreign_err_file;
1549
1550 row_ins_set_detailed(trx, foreign);
1551
1552 row_ins_foreign_trx_print(trx);
1553
1554 fputs("Foreign key constraint fails for table ", ef);
1555 ut_print_name(ef, trx, foreign->foreign_table_name);
1556 fputs(":\n", ef);
1557 dict_print_info_on_foreign_key_in_create_format(ef, trx, foreign, true);
1558 fprintf(ef, "\nTrying to add to index %s tuple:\n",
1559 foreign->foreign_index->name());
1560 dtuple_print(ef, entry);
1561 fputs("\nBut the parent table ", ef);
1562 ut_print_name(ef, trx, foreign->referenced_table_name);
1563 fputs(
1564 "\nor its .ibd file does"
1565 " not currently exist!\n",
1566 ef);
1567 mutex_exit(&dict_foreign_err_mutex);
1568
1569 err = DB_NO_REFERENCED_ROW;
1570 }
1571
1572 goto exit_func;
1573 }
1574
1575 if (check_table != table) {
1576 /* We already have a LOCK_IX on table, but not necessarily
1577 on check_table */
1578
1579 err = lock_table(0, check_table, LOCK_IS, thr);
1580
1581 if (err != DB_SUCCESS) {
1582 goto do_possible_lock_wait;
1583 }
1584 }
1585
1586 mtr_start(&mtr);
1587
1588 /* Store old value on n_fields_cmp */
1589
1590 n_fields_cmp = dtuple_get_n_fields_cmp(entry);
1591
1592 dtuple_set_n_fields_cmp(entry, foreign->n_fields);
1593
1594 pcur.open(check_index, 0, entry, PAGE_CUR_GE, BTR_SEARCH_LEAF, &mtr,
1595 UT_LOCATION_HERE);
1596
1597 /* Scan index records and check if there is a matching record */
1598
1599 do {
1600 const rec_t *rec = pcur.get_rec();
1601 const buf_block_t *block = pcur.get_block();
1602
1603 if (page_rec_is_infimum(rec)) {
1604 continue;
1605 }
1606
1607 offsets = rec_get_offsets(rec, check_index, offsets, ULINT_UNDEFINED,
1608 UT_LOCATION_HERE, &heap);
1609
1610 if (page_rec_is_supremum(rec)) {
1611 if (skip_gap_lock) {
1612 continue;
1613 }
1614
1615 err = row_ins_set_rec_lock(LOCK_S, LOCK_ORDINARY, block, rec, check_index,
1616 offsets, thr);
1617 switch (err) {
1618 case DB_SUCCESS_LOCKED_REC:
1619 case DB_SUCCESS:
1620 continue;
1621 default:
1622 goto end_scan;
1623 }
1624 }
1625
1626 cmp = cmp_dtuple_rec(entry, rec, check_index, offsets);
1627
1628 if (cmp == 0) {
1629 ulint lock_type;
1630
1631 lock_type = skip_gap_lock ? LOCK_REC_NOT_GAP : LOCK_ORDINARY;
1632
1633 if (rec_get_deleted_flag(rec, rec_offs_comp(offsets))) {
1634 err = row_ins_set_rec_lock(LOCK_S, lock_type, block, rec, check_index,
1635 offsets, thr);
1636 switch (err) {
1637 case DB_SUCCESS_LOCKED_REC:
1638 case DB_SUCCESS:
1639 break;
1640 default:
1641 goto end_scan;
1642 }
1643 } else {
1644 /* Found a matching record. Lock only
1645 a record because we can allow inserts
1646 into gaps */
1647
1648 err = row_ins_set_rec_lock(LOCK_S, LOCK_REC_NOT_GAP, block, rec,
1649 check_index, offsets, thr);
1650
1651 switch (err) {
1652 case DB_SUCCESS_LOCKED_REC:
1653 case DB_SUCCESS:
1654 break;
1655 default:
1656 goto end_scan;
1657 }
1658
1659 if (check_ref) {
1660 err = DB_SUCCESS;
1661
1662 goto end_scan;
1663 } else if (foreign->type != 0) {
1664 /* There is an ON UPDATE or ON DELETE
1665 condition: check them in a separate
1666 function */
1667
1668 err = row_ins_foreign_check_on_constraint(thr, foreign, &pcur, entry,
1669 &mtr);
1670 if (err != DB_SUCCESS) {
1671 /* Since reporting a plain
1672 "duplicate key" error
1673 message to the user in
1674 cases where a long CASCADE
1675 operation would lead to a
1676 duplicate key in some
1677 other table is very
1678 confusing, map duplicate
1679 key errors resulting from
1680 FK constraints to a
1681 separate error code. */
1682
1683 if (err == DB_DUPLICATE_KEY) {
1684 err = DB_FOREIGN_DUPLICATE_KEY;
1685 }
1686
1687 goto end_scan;
1688 }
1689
1690 /* row_ins_foreign_check_on_constraint
1691 may have repositioned pcur on a
1692 different block */
1693 block = pcur.get_block();
1694 } else {
1695 row_ins_foreign_report_err("Trying to delete or update", thr, foreign,
1696 rec, entry);
1697
1698 err = DB_ROW_IS_REFERENCED;
1699 goto end_scan;
1700 }
1701 }
1702 } else {
1703 ut_a(cmp < 0);
1704
1705 err = DB_SUCCESS;
1706
1707 if (!skip_gap_lock) {
1708 err = row_ins_set_rec_lock(LOCK_S, LOCK_GAP, block, rec, check_index,
1709 offsets, thr);
1710 }
1711
1712 switch (err) {
1713 case DB_SUCCESS_LOCKED_REC:
1714 case DB_SUCCESS:
1715 if (check_ref) {
1716 err = DB_NO_REFERENCED_ROW;
1717 row_ins_foreign_report_add_err(trx, foreign, rec, entry);
1718 } else {
1719 err = DB_SUCCESS;
1720 }
1721 default:
1722 break;
1723 }
1724
1725 goto end_scan;
1726 }
1727 } while (pcur.move_to_next(&mtr));
1728
1729 if (check_ref) {
1730 row_ins_foreign_report_add_err(trx, foreign, pcur.get_rec(), entry);
1731 err = DB_NO_REFERENCED_ROW;
1732 } else {
1733 err = DB_SUCCESS;
1734 }
1735
1736 end_scan:
1737 pcur.close();
1738
1739 mtr_commit(&mtr);
1740
1741 /* Restore old value */
1742 dtuple_set_n_fields_cmp(entry, n_fields_cmp);
1743
1744 do_possible_lock_wait:
1745 if (err == DB_LOCK_WAIT) {
1746 /* An object that will correctly decrement the FK check counter
1747 when it goes out of this scope. */
1748 ib_dec_in_dtor dec(check_table->n_foreign_key_checks_running);
1749
1750 trx->error_state = err;
1751
1752 que_thr_stop_for_mysql(thr);
1753
1754 thr->lock_state = QUE_THR_LOCK_ROW;
1755
1756 /* To avoid check_table being dropped, increment counter */
1757 check_table->n_foreign_key_checks_running.fetch_add(1);
1758
1759 trx_kill_blocking(trx);
1760
1761 lock_wait_suspend_thread(thr);
1762
1763 if (trx->error_state != DB_SUCCESS) {
1764 err = trx->error_state;
1765 goto exit_func;
1766 }
1767
1768 thr->lock_state = QUE_THR_LOCK_NOLOCK;
1769
1770 DBUG_PRINT("to_be_dropped", ("table: %s", check_table->name.m_name));
1771 if (check_table->to_be_dropped) {
1772 /* The table is being dropped. We shall timeout
1773 this operation */
1774 err = DB_LOCK_WAIT_TIMEOUT;
1775
1776 goto exit_func;
1777 }
1778 }
1779
1780 exit_func:
1781 if (heap != nullptr) {
1782 mem_heap_free(heap);
1783 }
1784
1785 /* TODO: NewDD: Remove this after WL#6049 */
1786 if (tmp_open) {
1787 dict_sys_mutex_enter();
1788 dd_table_close(check_table, thd, &mdl, true);
1789 ut::free(tmp_foreign);
1790 dict_sys_mutex_exit();
1791 }
1792
1793 return err;
1794 }
1795
1796 /** Checks if foreign key constraints fail for an index entry. If index
1797 is not mentioned in any constraint, this function does nothing,
1798 Otherwise does searches to the indexes of referenced tables and
1799 sets shared locks which lock either the success or the failure of
1800 a constraint.
1801 @return DB_SUCCESS or error code */
1802 [[nodiscard]] static dberr_t row_ins_check_foreign_constraints(
1803 dict_table_t *table, /*!< in: table */
1804 dict_index_t *index, /*!< in: index */
1805 dtuple_t *entry, /*!< in: index entry for index */
1806 que_thr_t *thr) /*!< in: query thread */
1807 {
1808 dict_foreign_t *foreign;
1809 dberr_t err;
1810 trx_t *trx;
1811
1812 /* Temporarily skip the FK check for DD tables */
1813 if (dict_sys_t::is_dd_table_id(table->id)) {
1814 return (DB_SUCCESS);
1815 }
1816
1817 trx = thr_get_trx(thr);
1818
1819 if (trx->check_foreigns == false) {
1820 return (DB_SUCCESS);
1821 }
1822 DEBUG_SYNC(thr_get_trx(thr)->mysql_thd, "foreign_constraint_check_for_ins");
1823
1824 for (dict_foreign_set::iterator it = table->foreign_set.begin();
1825 it != table->foreign_set.end(); ++it) {
1826 foreign = *it;
1827
1828 if (foreign->foreign_index == index) {
1829 dict_table_t *ref_table = nullptr;
1830 dict_table_t *foreign_table = foreign->foreign_table;
1831 dict_table_t *referenced_table = foreign->referenced_table;
1832 MDL_ticket *mdl = nullptr;
1833
1834 if (referenced_table == nullptr) {
1835 ref_table = dd_table_open_on_name(trx->mysql_thd, &mdl,
1836 foreign->referenced_table_name_lookup,
1837 false, DICT_ERR_IGNORE_NONE);
1838 }
1839
1840 if (referenced_table) {
1841 foreign_table->n_foreign_key_checks_running.fetch_add(1);
1842 }
1843
1844 /* NOTE that if the thread ends up waiting for a lock
1845 we will release dict_operation_lock temporarily!
1846 But the counter on the table protects the referenced
1847 table from being dropped while the check is running. */
1848
1849 err = row_ins_check_foreign_constraint(true, foreign, table, entry, thr);
1850
1851 if (referenced_table) {
1852 foreign_table->n_foreign_key_checks_running.fetch_sub(1);
1853 }
1854 if (ref_table != nullptr) {
1855 dd_table_close(ref_table, trx->mysql_thd, &mdl, false);
1856 }
1857
1858 if (err != DB_SUCCESS) {
1859 return (err);
1860 }
1861 }
1862 }
1863
1864 return (DB_SUCCESS);
1865 }
1866
1867 /** Checks if a unique key violation to rec would occur at the index entry
1868 insert.
1869 @return true if error */
1870 static bool row_ins_dupl_error_with_rec(
1871 const rec_t *rec, /*!< in: user record; NOTE that we assume
1872 that the caller already has a record lock on
1873 the record! */
1874 const dtuple_t *entry, /*!< in: entry to insert */
1875 dict_index_t *index, /*!< in: index */
1876 const ulint *offsets) /*!< in: rec_get_offsets(rec, index) */
1877 {
1878 ulint matched_fields;
1879 ulint n_unique;
1880 ulint i;
1881
1882 ut_ad(rec_offs_validate(rec, index, offsets));
1883
1884 n_unique = dict_index_get_n_unique(index);
1885
1886 matched_fields = 0;
1887
1888 entry->compare(rec, index, offsets, &matched_fields);
1889
1890 if (matched_fields < n_unique) {
1891 return false;
1892 }
1893
1894 /* In a unique secondary index we allow equal key values if they
1895 contain SQL NULLs */
1896
1897 if (!index->is_clustered() && !index->nulls_equal) {
1898 for (i = 0; i < n_unique; i++) {
1899 if (dfield_is_null(dtuple_get_nth_field(entry, i))) {
1900 return false;
1901 }
1902 }
1903 }
1904
1905 return rec_get_deleted_flag(rec, rec_offs_comp(offsets)) == 0;
1906 }
1907
1908 /** Determines if the query is REPLACE or ON DUPLICATE KEY UPDATE in which case
1909 duplicate values should be allowed (and further processed) instead of causing
1910 an error
1911 @param thr The query thread running the query
1912 @return true iff duplicated values should be allowed */
1913 static bool row_allow_duplicates(que_thr_t *thr) {
1914 return (thr->prebuilt && thr->prebuilt->allow_duplicates());
1915 }
1916
1917 /** Scans a unique non-clustered index at a given index entry to determine
1918 whether a uniqueness violation has occurred for the key value of the entry.
1919 Set shared locks on possible duplicate records.
1920 @return DB_SUCCESS, DB_DUPLICATE_KEY, or DB_LOCK_WAIT */
1921 [[nodiscard]] static dberr_t row_ins_scan_sec_index_for_duplicate(
1922 ulint flags, /*!< in: undo logging and locking flags */
1923 dict_index_t *index, /*!< in: non-clustered unique index */
1924 dtuple_t *entry, /*!< in: index entry */
1925 que_thr_t *thr, /*!< in: query thread */
1926 bool s_latch, /*!< in: whether index->lock is being held */
1927 mtr_t *mtr, /*!< in/out: mini-transaction */
1928 mem_heap_t *offsets_heap)
1929 /*!< in/out: memory heap that can be emptied */
1930 {
1931 ulint n_unique;
1932 ulint n_fields_cmp;
1933 btr_pcur_t pcur;
1934 dberr_t err = DB_SUCCESS;
1935 ulint allow_duplicates;
1936 ulint *offsets = nullptr;
1937 DBUG_TRACE;
1938
1939 ut_ad(s_latch ==
1940 rw_lock_own_flagged(&index->lock, RW_LOCK_FLAG_S | RW_LOCK_FLAG_SX));
1941
1942 n_unique = dict_index_get_n_unique(index);
1943
1944 /* If the secondary index is unique, but one of the fields in the
1945 n_unique first fields is NULL, a unique key violation cannot occur,
1946 since we define NULL != NULL in this case */
1947
1948 if (!index->nulls_equal) {
1949 for (ulint i = 0; i < n_unique; i++) {
1950 if (UNIV_SQL_NULL == dfield_get_len(dtuple_get_nth_field(entry, i))) {
1951 return DB_SUCCESS;
1952 }
1953 }
1954 }
1955
1956 /* Store old value on n_fields_cmp */
1957
1958 n_fields_cmp = dtuple_get_n_fields_cmp(entry);
1959
1960 dtuple_set_n_fields_cmp(entry, n_unique);
1961
1962 pcur.open(index, 0, entry, PAGE_CUR_GE,
1963 s_latch ? BTR_SEARCH_LEAF | BTR_ALREADY_S_LATCHED : BTR_SEARCH_LEAF,
1964 mtr, UT_LOCATION_HERE);
1965 allow_duplicates = row_allow_duplicates(thr);
1966
1967 const bool skip_gap_locks = index->table->skip_gap_locks();
1968 /* Scan index records and check if there is a duplicate */
1969
1970 do {
1971 const rec_t *rec = pcur.get_rec();
1972 const buf_block_t *block = pcur.get_block();
1973
1974 /* For DD tables, We don't use next-key locking for duplicates
1975 found. This means it is possible for another transaction to
1976 insert a duplicate key value but MDL protection on DD tables
1977 will prevent insertion of duplicates into unique secondary indexes*/
1978 ulint lock_type = skip_gap_locks ? LOCK_REC_NOT_GAP : LOCK_ORDINARY;
1979
1980 if (page_rec_is_infimum(rec)) {
1981 continue;
1982 }
1983
1984 offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED,
1985 UT_LOCATION_HERE, &offsets_heap);
1986
1987 const bool is_supremum = page_rec_is_supremum(rec);
1988 const bool is_next =
1989 !is_supremum && (cmp_dtuple_rec(entry, rec, index, offsets) < 0);
1990 if (flags & BTR_NO_LOCKING_FLAG) {
1991 /* Set no locks when applying log
1992 in online table rebuild. */
1993 } else if (allow_duplicates) {
1994 #if 0 // TODO: Enable this assert after WL#9509. REPLACE will not be allowed on
1995 // DD tables
1996 /* This assert means DD tables should not use REPLACE
1997 or INSERT INTO table.. ON DUPLICATE KEY */
1998 ut_ad(!index->table->is_dd_table);
1999 #endif
2000
2001 #if 1 // TODO: Remove this code after WL#9509. REPLACE will not be allowed on
2002 // DD tables
2003 if (skip_gap_locks) {
2004 /* Only GAP lock is possible on supremum. */
2005 if (is_supremum) {
2006 continue;
2007 }
2008 }
2009 #endif
2010
2011 /* If the SQL-query will update or replace duplicate key we will take
2012 X-lock for duplicates ( REPLACE, LOAD DATAFILE REPLACE, INSERT ON
2013 DUPLICATE KEY UPDATE). */
2014 err = row_ins_set_rec_lock(LOCK_X, lock_type, block, rec, index, offsets,
2015 thr);
2016 } else {
2017 if (skip_gap_locks) {
2018 /* Skip GAP lock on supremum */
2019 if (is_supremum) {
2020 continue;
2021 }
2022 /* Skip gap lock on next record. */
2023 if (is_next) {
2024 goto end_scan;
2025 }
2026 lock_type = LOCK_REC_NOT_GAP;
2027 } else if (is_supremum) {
2028 /* We use next key lock to possibly combine the locks in bitmap.
2029 Equivalent to LOCK_GAP. */
2030 lock_type = LOCK_ORDINARY;
2031 } else if (is_next) {
2032 /* Only gap lock is required on next record. */
2033 lock_type = LOCK_GAP;
2034 } else {
2035 /* Next key lock for all equal keys. */
2036 lock_type = LOCK_ORDINARY;
2037 }
2038 /* We only need to lock locations where duplicates could occur, which
2039 means rows which are equal, gaps between them, and gaps on both
2040 sides of them. We don't need to lock the first unequal record after the
2041 gap, just the gap before it.
2042 Note: This function will not be even called, and thus will not lock
2043 anything at all in case there wasn't any matching record, which is fine,
2044 because the B-tree page latch will be released only after inserting the
2045 implicitly locked record, so no protection is needed.*/
2046 err = row_ins_set_rec_lock(LOCK_S, lock_type, block, rec, index, offsets,
2047 thr);
2048 }
2049
2050 switch (err) {
2051 case DB_SUCCESS_LOCKED_REC:
2052 err = DB_SUCCESS;
2053 case DB_SUCCESS:
2054 break;
2055 default:
2056 goto end_scan;
2057 }
2058
2059 if (is_supremum) {
2060 continue;
2061 }
2062
2063 if (!is_next && !index->allow_duplicates) {
2064 if (row_ins_dupl_error_with_rec(rec, entry, index, offsets)) {
2065 err = DB_DUPLICATE_KEY;
2066
2067 thr_get_trx(thr)->error_index = index;
2068
2069 /* If the duplicate is on hidden FTS_DOC_ID,
2070 state so in the error log */
2071 if (index == index->table->fts_doc_id_index &&
2072 DICT_TF2_FLAG_IS_SET(index->table, DICT_TF2_FTS_HAS_DOC_ID)) {
2073 ib::error(ER_IB_MSG_958) << "Duplicate FTS_DOC_ID"
2074 " value on table "
2075 << index->table->name;
2076 }
2077
2078 goto end_scan;
2079 }
2080 } else {
2081 ut_a(is_next || index->allow_duplicates);
2082 goto end_scan;
2083 }
2084 } while (pcur.move_to_next(mtr));
2085
2086 end_scan:
2087 /* Restore old value */
2088 dtuple_set_n_fields_cmp(entry, n_fields_cmp);
2089
2090 pcur.close();
2091 return err;
2092 }
2093
2094 /** Checks for a duplicate when the table is being rebuilt online.
2095 @param[in] n_uniq offset of DB_TRX_ID
2096 @param[in] entry entry being inserted
2097 @param[in] rec clustered index record at insert position
2098 @param[in] index clustered index
2099 @param[in,out] offsets rec_get_offsets(rec)
2100 @retval DB_SUCCESS when no duplicate is detected
2101 @retval DB_SUCCESS_LOCKED_REC when rec is an exact match of entry or
2102 a newer version of entry (the entry should not be inserted)
2103 @retval DB_DUPLICATE_KEY when entry is a duplicate of rec */
2104 [[nodiscard]] static dberr_t row_ins_duplicate_online(ulint n_uniq,
2105 const dtuple_t *entry,
2106 const rec_t *rec,
2107 const dict_index_t *index,
2108 ulint *offsets) {
2109 ulint fields = 0;
2110
2111 /* During rebuild, there should not be any delete-marked rows
2112 in the new table. */
2113 ut_ad(!rec_get_deleted_flag(rec, rec_offs_comp(offsets)));
2114 ut_ad(dtuple_get_n_fields_cmp(entry) == n_uniq);
2115
2116 /* Compare the PRIMARY KEY fields and the
2117 DB_TRX_ID, DB_ROLL_PTR. */
2118 cmp_dtuple_rec_with_match_low(entry, rec, index, offsets, n_uniq + 2,
2119 &fields);
2120
2121 if (fields < n_uniq) {
2122 /* Not a duplicate. */
2123 return (DB_SUCCESS);
2124 }
2125
2126 if (fields == n_uniq + 2) {
2127 /* rec is an exact match of entry. */
2128 return (DB_SUCCESS_LOCKED_REC);
2129 }
2130
2131 return (DB_DUPLICATE_KEY);
2132 }
2133
2134 /** Checks for a duplicate when the table is being rebuilt online.
2135 @retval DB_SUCCESS when no duplicate is detected
2136 @retval DB_SUCCESS_LOCKED_REC when rec is an exact match of entry or
2137 a newer version of entry (the entry should not be inserted)
2138 @retval DB_DUPLICATE_KEY when entry is a duplicate of rec */
2139 [[nodiscard]] static dberr_t row_ins_duplicate_error_in_clust_online(
2140 ulint n_uniq, /*!< in: offset of DB_TRX_ID */
2141 const dtuple_t *entry, /*!< in: entry that is being inserted */
2142 const btr_cur_t *cursor, /*!< in: cursor on insert position */
2143 ulint **offsets, /*!< in/out: rec_get_offsets(rec) */
2144 mem_heap_t **heap) /*!< in/out: heap for offsets */
2145 {
2146 dberr_t err = DB_SUCCESS;
2147 const rec_t *rec = btr_cur_get_rec(cursor);
2148
2149 if (cursor->low_match >= n_uniq && !page_rec_is_infimum(rec)) {
2150 *offsets = rec_get_offsets(rec, cursor->index, *offsets, ULINT_UNDEFINED,
2151 UT_LOCATION_HERE, heap);
2152 err = row_ins_duplicate_online(n_uniq, entry, rec, cursor->index, *offsets);
2153 if (err != DB_SUCCESS) {
2154 return (err);
2155 }
2156 }
2157
2158 rec = page_rec_get_next_const(btr_cur_get_rec(cursor));
2159
2160 if (cursor->up_match >= n_uniq && !page_rec_is_supremum(rec)) {
2161 *offsets = rec_get_offsets(rec, cursor->index, *offsets, ULINT_UNDEFINED,
2162 UT_LOCATION_HERE, heap);
2163 err = row_ins_duplicate_online(n_uniq, entry, rec, cursor->index, *offsets);
2164 }
2165
2166 return (err);
2167 }
2168
2169 /** Checks if a unique key violation error would occur at an index entry
2170 insert. Sets shared locks on possible duplicate records. Works only
2171 for a clustered index!
2172 @retval DB_SUCCESS if no error
2173 @retval DB_DUPLICATE_KEY if error,
2174 @retval DB_LOCK_WAIT if we have to wait for a lock on a possible duplicate
2175 record
2176 @retval DB_SUCCESS_LOCKED_REC if an exact match of the record was found
2177 in online table rebuild (flags & (BTR_KEEP_SYS_FLAG | BTR_NO_LOCKING_FLAG)) */
2178 [[nodiscard]] static dberr_t row_ins_duplicate_error_in_clust(
2179 ulint flags, /*!< in: undo logging and locking flags */
2180 btr_cur_t *cursor, /*!< in: B-tree cursor */
2181 const dtuple_t *entry, /*!< in: entry to insert */
2182 que_thr_t *thr, /*!< in: query thread */
2183 mtr_t *mtr) /*!< in: mtr */
2184 {
2185 dberr_t err;
2186 rec_t *rec;
2187 ulint n_unique;
2188 trx_t *trx = thr_get_trx(thr);
2189 mem_heap_t *heap = nullptr;
2190 ulint offsets_[REC_OFFS_NORMAL_SIZE];
2191 ulint *offsets = offsets_;
2192 rec_offs_init(offsets_);
2193
2194 UT_NOT_USED(mtr);
2195
2196 ut_ad(cursor->index->is_clustered());
2197
2198 /* NOTE: For unique non-clustered indexes there may be any number
2199 of delete marked records with the same value for the non-clustered
2200 index key (remember multiversioning), and which differ only in
2201 the row reference part of the index record, containing the
2202 clustered index key fields. For such a secondary index record,
2203 to avoid race condition, we must FIRST do the insertion and after
2204 that check that the uniqueness condition is not breached! */
2205
2206 /* NOTE: A problem is that in the B-tree node pointers on an
2207 upper level may match more to the entry than the actual existing
2208 user records on the leaf level. So, even if low_match would suggest
2209 that a duplicate key violation may occur, this may not be the case. */
2210
2211 n_unique = dict_index_get_n_unique(cursor->index);
2212
2213 if (cursor->low_match >= n_unique) {
2214 rec = btr_cur_get_rec(cursor);
2215
2216 if (!page_rec_is_infimum(rec)) {
2217 offsets = rec_get_offsets(rec, cursor->index, offsets, ULINT_UNDEFINED,
2218 UT_LOCATION_HERE, &heap);
2219
2220 /* We set a lock on the possible duplicate: this
2221 is needed in logical logging of MySQL to make
2222 sure that in roll-forward we get the same duplicate
2223 errors as in original execution */
2224
2225 if (flags & BTR_NO_LOCKING_FLAG) {
2226 /* Do nothing if no-locking is set */
2227 err = DB_SUCCESS;
2228 } else {
2229 /* If the SQL-query will update or replace
2230 duplicate key we will take X-lock for
2231 duplicates ( REPLACE, LOAD DATAFILE REPLACE,
2232 INSERT ON DUPLICATE KEY UPDATE). */
2233
2234 err = row_ins_set_rec_lock(row_allow_duplicates(thr) ? LOCK_X : LOCK_S,
2235 LOCK_REC_NOT_GAP, btr_cur_get_block(cursor),
2236 rec, cursor->index, offsets, thr);
2237 }
2238
2239 switch (err) {
2240 case DB_SUCCESS_LOCKED_REC:
2241 case DB_SUCCESS:
2242 break;
2243 default:
2244 goto func_exit;
2245 }
2246
2247 if (row_ins_dupl_error_with_rec(rec, entry, cursor->index, offsets)) {
2248 duplicate:
2249 trx->error_index = cursor->index;
2250 err = DB_DUPLICATE_KEY;
2251 goto func_exit;
2252 }
2253 }
2254 }
2255
2256 if (cursor->up_match >= n_unique) {
2257 rec = page_rec_get_next(btr_cur_get_rec(cursor));
2258
2259 if (!page_rec_is_supremum(rec)) {
2260 offsets = rec_get_offsets(rec, cursor->index, offsets, ULINT_UNDEFINED,
2261 UT_LOCATION_HERE, &heap);
2262
2263 /* If the SQL-query will update or replace
2264 duplicate key we will take X-lock for
2265 duplicates ( REPLACE, LOAD DATAFILE REPLACE,
2266 INSERT ON DUPLICATE KEY UPDATE). */
2267
2268 err = row_ins_set_rec_lock(row_allow_duplicates(thr) ? LOCK_X : LOCK_S,
2269 LOCK_REC_NOT_GAP, btr_cur_get_block(cursor),
2270 rec, cursor->index, offsets, thr);
2271
2272 switch (err) {
2273 case DB_SUCCESS_LOCKED_REC:
2274 case DB_SUCCESS:
2275 break;
2276 default:
2277 goto func_exit;
2278 }
2279
2280 if (row_ins_dupl_error_with_rec(rec, entry, cursor->index, offsets)) {
2281 goto duplicate;
2282 }
2283 }
2284
2285 /* This should never happen */
2286 ut_error;
2287 }
2288
2289 err = DB_SUCCESS;
2290 func_exit:
2291 if (UNIV_LIKELY_NULL(heap)) {
2292 mem_heap_free(heap);
2293 }
2294 return (err);
2295 }
2296
2297 /** Checks if an index entry has long enough common prefix with an
2298 existing record so that the intended insert of the entry must be
2299 changed to a modify of the existing record. In the case of a clustered
2300 index, the prefix must be n_unique fields long. In the case of a
2301 secondary index, all fields must be equal. InnoDB never updates
2302 secondary index records in place, other than clearing or setting the
2303 delete-mark flag. We could be able to update the non-unique fields
2304 of a unique secondary index record by checking the cursor->up_match,
2305 but we do not do so, because it could have some locking implications.
2306 @return true if the existing record should be updated; false if not */
2307 static inline bool row_ins_must_modify_rec(
2308 const btr_cur_t *cursor) /*!< in: B-tree cursor */
2309 {
2310 /* NOTE: (compare to the note in row_ins_duplicate_error_in_clust)
2311 Because node pointers on upper levels of the B-tree may match more
2312 to entry than to actual user records on the leaf level, we
2313 have to check if the candidate record is actually a user record.
2314 A clustered index node pointer contains index->n_unique first fields,
2315 and a secondary index node pointer contains all index fields. */
2316
2317 return (cursor->low_match >= dict_index_get_n_unique_in_tree(cursor->index) &&
2318 !page_rec_is_infimum(btr_cur_get_rec(cursor)));
2319 }
2320
2321 /** Insert the externally stored fields (off-page columns)
2322 of a clustered index entry.
2323 @param[in] trx current transaction
2324 @param[in] entry index entry to insert
2325 @param[in] big_rec externally stored fields
2326 @param[in,out] offsets rec_get_offsets()
2327 @param[in,out] heap memory heap
2328 @param[in] thd client connection, or NULL
2329 @param[in] index clustered index
2330 @return error code
2331 @retval DB_SUCCESS
2332 @retval DB_OUT_OF_FILE_SPACE */
2333 static dberr_t row_ins_index_entry_big_rec_func(
2334 trx_t *trx, const dtuple_t *entry, const big_rec_t *big_rec, ulint *offsets,
2335 mem_heap_t **heap, IF_DEBUG(const THD *thd, ) dict_index_t *index) {
2336 mtr_t mtr;
2337 btr_pcur_t pcur;
2338 rec_t *rec;
2339 dberr_t error;
2340
2341 ut_ad(index->is_clustered());
2342
2343 DEBUG_SYNC_C_IF_THD(thd, "before_row_ins_extern_latch");
2344 DEBUG_SYNC_C("before_insertion_of_blob");
2345
2346 mtr_start(&mtr);
2347
2348 dict_disable_redo_if_temporary(index->table, &mtr);
2349
2350 pcur.open(index, 0, entry, PAGE_CUR_LE, BTR_MODIFY_TREE, &mtr,
2351 UT_LOCATION_HERE);
2352 rec = pcur.get_rec();
2353 offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED,
2354 UT_LOCATION_HERE, heap);
2355
2356 DEBUG_SYNC_C_IF_THD(thd, "before_row_ins_extern");
2357 error = lob::btr_store_big_rec_extern_fields(
2358 trx, &pcur, nullptr, offsets, big_rec, &mtr, lob::OPCODE_INSERT);
2359 DEBUG_SYNC_C_IF_THD(thd, "after_row_ins_extern");
2360
2361 if (error == DB_SUCCESS && dict_index_is_online_ddl(index)) {
2362 row_log_table_insert(pcur.get_rec(), entry, index, offsets);
2363 }
2364
2365 mtr_commit(&mtr);
2366
2367 pcur.close();
2368
2369 return (error);
2370 }
2371
2372 static inline dberr_t row_ins_index_entry_big_rec(
2373 trx_t *trx, const dtuple_t *e, const big_rec_t *big, ulint *ofs,
2374 mem_heap_t **heap, dict_index_t *index, const THD *thd [[maybe_unused]]) {
2375 return row_ins_index_entry_big_rec_func(trx, e, big, ofs, heap,
2376 IF_DEBUG(thd, ) index);
2377 }
2378
2379 /** Update all the prebuilts working on this temporary table
2380 @param[in,out] table dict_table_t for the table */
2381 static void row_ins_temp_prebuilt_tree_modified(dict_table_t *table) {
2382 if (table->temp_prebuilt == nullptr) {
2383 return;
2384 }
2385
2386 std::vector<row_prebuilt_t *>::const_iterator it;
2387
2388 for (it = table->temp_prebuilt->begin(); it != table->temp_prebuilt->end();
2389 ++it) {
2390 if ((*it)->m_temp_read_shared) {
2391 (*it)->m_temp_tree_modified = true;
2392 }
2393 }
2394 }
2395
2396 dberr_t row_ins_clust_index_entry_low(uint32_t flags, ulint mode,
2397 dict_index_t *index, ulint n_uniq,
2398 dtuple_t *entry, que_thr_t *thr,
2399 bool dup_chk_only) {
2400 btr_pcur_t pcur;
2401 btr_cur_t *cursor;
2402 dberr_t err = DB_SUCCESS;
2403 big_rec_t *big_rec = nullptr;
2404 mtr_t mtr;
2405 mem_heap_t *offsets_heap = nullptr;
2406 ulint offsets_[REC_OFFS_NORMAL_SIZE];
2407 ulint *offsets = offsets_;
2408 rec_offs_init(offsets_);
2409
2410 DBUG_TRACE;
2411
2412 #ifdef UNIV_DEBUG
2413 mtr_t temp_mtr;
2414 temp_mtr.start();
2415 mtr_s_lock(dict_index_get_lock(index), &temp_mtr, UT_LOCATION_HERE);
2416
2417 if (btr_height_get(index, &temp_mtr) >= BTR_MAX_NODE_LEVEL &&
2418 btr_cur_limit_optimistic_insert_debug > 1 &&
2419 btr_cur_limit_optimistic_insert_debug < 5) {
2420 ib::error(ER_IB_MSG_BTREE_LEVEL_LIMIT_EXCEEDED, index->name());
2421 temp_mtr.commit();
2422 return (DB_BTREE_LEVEL_LIMIT_EXCEEDED);
2423 }
2424
2425 temp_mtr.commit();
2426 #endif
2427
2428 ut_ad(index->is_clustered());
2429 ut_ad(!dict_index_is_unique(index) ||
2430 n_uniq == dict_index_get_n_unique(index));
2431 ut_ad(!n_uniq || n_uniq == dict_index_get_n_unique(index));
2432 ut_ad((flags & (BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG)) ||
2433 !thr_get_trx(thr)->in_rollback);
2434 ut_ad(thr != nullptr || !dup_chk_only);
2435
2436 mtr.start();
2437
2438 if (index->table->is_temporary()) {
2439 /* Disable REDO logging as the lifetime of temp-tables is
2440 limited to server or connection lifetime and so REDO
2441 information is not needed on restart for recovery.
2442 Disable locking as temp-tables are local to a connection. */
2443
2444 ut_ad(flags & BTR_NO_LOCKING_FLAG);
2445 ut_ad(!index->table->is_intrinsic() || (flags & BTR_NO_UNDO_LOG_FLAG));
2446
2447 mtr.set_log_mode(MTR_LOG_NO_REDO);
2448 }
2449
2450 if (mode == BTR_MODIFY_LEAF && dict_index_is_online_ddl(index)) {
2451 mode = BTR_MODIFY_LEAF | BTR_ALREADY_S_LATCHED;
2452 mtr_s_lock(dict_index_get_lock(index), &mtr, UT_LOCATION_HERE);
2453 }
2454
2455 /* Note that we use PAGE_CUR_LE as the search mode, because then
2456 the function will return in both low_match and up_match of the
2457 cursor sensible values */
2458 pcur.open(index, 0, entry, PAGE_CUR_LE, mode, &mtr, UT_LOCATION_HERE);
2459 cursor = pcur.get_btr_cur();
2460 cursor->thr = thr;
2461
2462 ut_ad(!index->table->is_intrinsic() ||
2463 cursor->page_cur.block->made_dirty_with_no_latch);
2464
2465 #ifdef UNIV_DEBUG
2466 {
2467 page_t *page = btr_cur_get_page(cursor);
2468 rec_t *first_rec = page_rec_get_next(page_get_infimum_rec(page));
2469 /* After INSTANT ADD/DROP, # of fields might differ from other records. */
2470 ut_ad(page_rec_is_supremum(first_rec) || index->has_row_versions() ||
2471 rec_n_fields_is_sane(index, first_rec, entry));
2472 }
2473 #endif /* UNIV_DEBUG */
2474
2475 bool persist_autoinc = false;
2476
2477 /* Write logs for AUTOINC right after index lock has been got and
2478 before any further resource acquisitions to prevent deadlock.
2479 No need to log for temporary tables */
2480 if (!index->table->is_temporary() &&
2481 dict_table_has_autoinc_col(index->table)) {
2482 ut_ad(!index->table->is_intrinsic());
2483 uint64_t counter =
2484 row_get_autoinc_counter(entry, index->table->autoinc_field_no);
2485
2486 if (counter != 0) {
2487 /* Always log the counter change first, so it won't
2488 be affected by any follow-up failure. */
2489 persist_autoinc = dict_table_autoinc_log(index->table, counter, &mtr);
2490 }
2491 }
2492
2493 DBUG_EXECUTE_IF("crash_create_after_autoinc_persisted_update",
2494 DBUG_SUICIDE(););
2495
2496 /* Allowing duplicates in clustered index is currently enabled
2497 only for intrinsic table and caller understand the limited
2498 operation that can be done in this case. */
2499 ut_ad(!index->allow_duplicates ||
2500 (index->allow_duplicates && index->table->is_intrinsic()));
2501
2502 if (!index->allow_duplicates && n_uniq &&
2503 (cursor->up_match >= n_uniq || cursor->low_match >= n_uniq)) {
2504 if (flags == (BTR_CREATE_FLAG | BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG |
2505 BTR_KEEP_SYS_FLAG)) {
2506 /* Set no locks when applying log
2507 in online table rebuild. Only check for duplicates. */
2508 err = row_ins_duplicate_error_in_clust_online(n_uniq, entry, cursor,
2509 &offsets, &offsets_heap);
2510
2511 switch (err) {
2512 case DB_SUCCESS:
2513 break;
2514 default:
2515 ut_d(ut_error);
2516 [[fallthrough]];
2517 case DB_SUCCESS_LOCKED_REC:
2518 case DB_DUPLICATE_KEY:
2519 if (thr != nullptr) {
2520 thr_get_trx(thr)->error_index = cursor->index;
2521 }
2522 }
2523 } else {
2524 /* Note that the following may return also
2525 DB_LOCK_WAIT */
2526
2527 err = row_ins_duplicate_error_in_clust(flags, cursor, entry, thr, &mtr);
2528 }
2529
2530 if (err != DB_SUCCESS) {
2531 err_exit:
2532 mtr.commit();
2533 goto func_exit;
2534 }
2535 }
2536
2537 if (dup_chk_only) {
2538 mtr.commit();
2539 goto func_exit;
2540 }
2541 /* Note: Allowing duplicates would qualify for modification of
2542 an existing record as the new entry is exactly same as old entry.
2543 Avoid this check if allow duplicates is enabled. */
2544 if (!index->allow_duplicates && row_ins_must_modify_rec(cursor)) {
2545 /* There is already an index entry with a long enough common
2546 prefix, we must convert the insert into a modify of an
2547 existing record */
2548 mem_heap_t *entry_heap = mem_heap_create(1024, UT_LOCATION_HERE);
2549
2550 /* If the existing record is being modified and the new record
2551 doesn't fit the provided slot then existing record is added
2552 to free list and new record is inserted. This also means
2553 cursor that we have cached for SELECT is now invalid. */
2554 if (index->last_sel_cur) {
2555 index->last_sel_cur->invalid = true;
2556 }
2557
2558 ut_ad(thr != nullptr);
2559 err = row_ins_clust_index_entry_by_modify(&pcur, flags, mode, &offsets,
2560 &offsets_heap, entry_heap, entry,
2561 thr, &mtr);
2562
2563 if (err == DB_SUCCESS && dict_index_is_online_ddl(index)) {
2564 row_log_table_insert(btr_cur_get_rec(cursor), entry, index, offsets);
2565 }
2566
2567 mtr.commit();
2568 mem_heap_free(entry_heap);
2569 } else {
2570 rec_t *insert_rec;
2571
2572 if (mode != BTR_MODIFY_TREE) {
2573 ut_ad((mode & ~BTR_ALREADY_S_LATCHED) == BTR_MODIFY_LEAF);
2574 err = btr_cur_optimistic_insert(flags, cursor, &offsets, &offsets_heap,
2575 entry, &insert_rec, &big_rec, thr, &mtr);
2576 } else {
2577 if (buf_LRU_buf_pool_running_out()) {
2578 err = DB_LOCK_TABLE_FULL;
2579 goto err_exit;
2580 }
2581
2582 DEBUG_SYNC_C("before_insert_pessimitic_row_ins_clust");
2583
2584 err = btr_cur_optimistic_insert(flags, cursor, &offsets, &offsets_heap,
2585 entry, &insert_rec, &big_rec, thr, &mtr);
2586
2587 if (err == DB_FAIL) {
2588 err =
2589 btr_cur_pessimistic_insert(flags, cursor, &offsets, &offsets_heap,
2590 entry, &insert_rec, &big_rec, thr, &mtr);
2591
2592 if (index->table->is_intrinsic() && err == DB_SUCCESS) {
2593 row_ins_temp_prebuilt_tree_modified(index->table);
2594 }
2595 }
2596 }
2597
2598 if (big_rec != nullptr) {
2599 mtr.commit();
2600
2601 /* Online table rebuild could read (and
2602 ignore) the incomplete record at this point.
2603 If online rebuild is in progress, the
2604 row_ins_index_entry_big_rec() will write log. */
2605
2606 DBUG_EXECUTE_IF("row_ins_extern_checkpoint",
2607 log_make_latest_checkpoint(););
2608 err = row_ins_index_entry_big_rec(thr_get_trx(thr), entry, big_rec,
2609 offsets, &offsets_heap, index,
2610 thr_get_trx(thr)->mysql_thd);
2611 dtuple_convert_back_big_rec(entry, big_rec);
2612 } else {
2613 if (err == DB_SUCCESS && dict_index_is_online_ddl(index)) {
2614 row_log_table_insert(insert_rec, entry, index, offsets);
2615 }
2616
2617 mtr.commit();
2618 }
2619 }
2620
2621 func_exit:
2622 if (offsets_heap != nullptr) {
2623 mem_heap_free(offsets_heap);
2624 }
2625
2626 pcur.close();
2627
2628 DBUG_EXECUTE_IF(
2629 "ib_sdi", if (dict_table_is_sdi(index->table->id)) {
2630 ib::info(ER_IB_MSG_959)
2631 << "ib_sdi: row_ins_clust_index_entry_low: " << index->name << " "
2632 << index->table->name << " return status: " << err;
2633 });
2634
2635 /* Persist auto increment value to DD buffer table if requested. Do it after
2636 closing the mini transaction and releasing latches. */
2637 if (persist_autoinc) {
2638 dict_table_persist_to_dd_table_buffer(index->table);
2639 }
2640
2641 return err;
2642 }
2643
2644 /** This is a specialized function meant for direct insertion to auto-generated
2645 clustered index based on cached position from last successful insert. To be
2646 used when data is sorted.
2647 @param[in] mode BTR_MODIFY_LEAF or BTR_MODIFY_TREE.
2648 depending on whether we wish optimistic or pessimistic
2649 descent down the index tree
2650 @param[in,out] index clustered index
2651 @param[in,out] entry index entry to insert
2652 @param[in] thr query thread
2653 @return error code */
2654 static dberr_t row_ins_sorted_clust_index_entry(ulint mode, dict_index_t *index,
2655 dtuple_t *entry,
2656 que_thr_t *thr) {
2657 dberr_t err;
2658 mtr_t *mtr;
2659 const bool commit_mtr = mode == BTR_MODIFY_TREE;
2660
2661 mem_heap_t *offsets_heap = nullptr;
2662 ulint offsets_[REC_OFFS_NORMAL_SIZE];
2663 ulint *offsets = offsets_;
2664 rec_offs_init(offsets_);
2665
2666 DBUG_TRACE;
2667
2668 ut_ad(index->last_ins_cur != nullptr);
2669 ut_ad(index->is_clustered());
2670 ut_ad(index->table->is_intrinsic());
2671 ut_ad(dict_index_is_auto_gen_clust(index));
2672
2673 btr_cur_t cursor;
2674 cursor.thr = thr;
2675 mtr = &index->last_ins_cur->mtr;
2676
2677 /* Search for position if tree needs to be split or if last position
2678 is not cached. */
2679 if (mode == BTR_MODIFY_TREE || index->last_ins_cur->rec == nullptr ||
2680 index->last_ins_cur->disable_caching) {
2681 /* Commit the previous mtr. */
2682 index->last_ins_cur->release();
2683
2684 mtr_start(mtr);
2685 mtr_set_log_mode(mtr, MTR_LOG_NO_REDO);
2686
2687 btr_cur_search_to_nth_level_with_no_latch(index, 0, entry, PAGE_CUR_LE,
2688 &cursor, __FILE__, __LINE__, mtr);
2689 ut_ad(cursor.page_cur.block != nullptr);
2690 ut_ad(cursor.page_cur.block->made_dirty_with_no_latch);
2691 } else {
2692 cursor.index = index;
2693
2694 cursor.page_cur.index = index;
2695
2696 cursor.page_cur.rec = index->last_ins_cur->rec;
2697
2698 cursor.page_cur.block = index->last_ins_cur->block;
2699 }
2700
2701 const ulint flags = BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG;
2702
2703 for (;;) {
2704 rec_t *insert_rec;
2705 big_rec_t *big_rec = nullptr;
2706
2707 if (mode != BTR_MODIFY_TREE) {
2708 ut_ad((mode & ~BTR_ALREADY_S_LATCHED) == BTR_MODIFY_LEAF);
2709
2710 err = btr_cur_optimistic_insert(flags, &cursor, &offsets, &offsets_heap,
2711 entry, &insert_rec, &big_rec, thr, mtr);
2712 if (err != DB_SUCCESS) {
2713 break;
2714 }
2715 } else {
2716 /* TODO: Check if this is needed for intrinsic table. */
2717 if (buf_LRU_buf_pool_running_out()) {
2718 err = DB_LOCK_TABLE_FULL;
2719 break;
2720 }
2721
2722 err = btr_cur_optimistic_insert(flags, &cursor, &offsets, &offsets_heap,
2723 entry, &insert_rec, &big_rec, thr, mtr);
2724
2725 if (err == DB_FAIL) {
2726 err =
2727 btr_cur_pessimistic_insert(flags, &cursor, &offsets, &offsets_heap,
2728 entry, &insert_rec, &big_rec, thr, mtr);
2729 if (index->table->is_intrinsic() && err == DB_SUCCESS) {
2730 row_ins_temp_prebuilt_tree_modified(index->table);
2731 }
2732 }
2733 }
2734
2735 if (big_rec != nullptr) {
2736 /* If index involves big-record optimization is
2737 turned-off. */
2738 index->last_ins_cur->release();
2739 index->last_ins_cur->disable_caching = true;
2740
2741 err = row_ins_index_entry_big_rec(thr_get_trx(thr), entry, big_rec,
2742 offsets, &offsets_heap, index,
2743 thr_get_trx(thr)->mysql_thd);
2744
2745 dtuple_convert_back_big_rec(entry, big_rec);
2746
2747 } else if (err == DB_SUCCESS) {
2748 if (!commit_mtr && !index->last_ins_cur->disable_caching) {
2749 index->last_ins_cur->rec = insert_rec;
2750
2751 index->last_ins_cur->block = cursor.page_cur.block;
2752 } else {
2753 index->last_ins_cur->release();
2754 }
2755 }
2756
2757 break;
2758 }
2759
2760 if (err != DB_SUCCESS) {
2761 index->last_ins_cur->release();
2762 }
2763
2764 if (offsets_heap != nullptr) {
2765 mem_heap_free(offsets_heap);
2766 }
2767
2768 return err;
2769 }
2770
2771 /** Start a mini-transaction and check if the index will be dropped.
2772 @param[in,out] mtr Mini-transaction
2773 @param[in,out] index Secondary index
2774 @param[in] check Whether to check
2775 @param[in] search_mode Flags
2776 @return true if the index is to be dropped */
2777 [[nodiscard]] static bool row_ins_sec_mtr_start_and_check_if_aborted(
2778 mtr_t *mtr, dict_index_t *index, bool check, ulint search_mode) {
2779 ut_ad(!index->is_clustered());
2780
2781 const mtr_log_t log_mode = mtr->get_log_mode();
2782
2783 mtr_start(mtr);
2784
2785 mtr->set_log_mode(log_mode);
2786
2787 if (!check) {
2788 return (false);
2789 }
2790
2791 if (search_mode & BTR_ALREADY_S_LATCHED) {
2792 mtr_s_lock(dict_index_get_lock(index), mtr, UT_LOCATION_HERE);
2793 } else {
2794 mtr_sx_lock(dict_index_get_lock(index), mtr, UT_LOCATION_HERE);
2795 }
2796
2797 switch (index->online_status) {
2798 case ONLINE_INDEX_ABORTED:
2799 case ONLINE_INDEX_ABORTED_DROPPED:
2800 ut_ad(!index->is_committed());
2801 return (true);
2802 case ONLINE_INDEX_COMPLETE:
2803 return (false);
2804 case ONLINE_INDEX_CREATION:
2805 break;
2806 }
2807
2808 ut_error;
2809 }
2810
2811 /** Tries to insert an entry into a secondary index. If a record with exactly
2812 the same fields is found, the other record is necessarily marked deleted.
2813 It is then unmarked. Otherwise, the entry is just inserted to the index.
2814 @param[in] flags undo logging and locking flags
2815 @param[in] mode BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
2816 depending on whether we wish optimistic or
2817 pessimistic descent down the index tree
2818 @param[in] index secondary index
2819 @param[in,out] offsets_heap memory heap that can be emptied
2820 @param[in,out] heap memory heap
2821 @param[in,out] entry index entry to insert
2822 @param[in] trx_id PAGE_MAX_TRX_ID during row_log_table_apply(),
2823 or trx_id when undo log is disabled during
2824 alter copy operation or 0
2825 @param[in] thr query thread
2826 @param[in] dup_chk_only true, just do duplicate check and return.
2827 don't execute actual insert
2828 @retval DB_SUCCESS on success
2829 @retval DB_LOCK_WAIT on lock wait when !(flags & BTR_NO_LOCKING_FLAG)
2830 @retval DB_FAIL if retry with BTR_MODIFY_TREE is needed
2831 @return error code */
2832 dberr_t row_ins_sec_index_entry_low(uint32_t flags, ulint mode,
2833 dict_index_t *index,
2834 mem_heap_t *offsets_heap, mem_heap_t *heap,
2835 dtuple_t *entry, trx_id_t trx_id,
2836 que_thr_t *thr, bool dup_chk_only) {
2837 DBUG_TRACE;
2838
2839 btr_cur_t cursor;
2840 ulint search_mode = mode;
2841 dberr_t err = DB_SUCCESS;
2842 ulint n_unique;
2843 mtr_t mtr;
2844 ulint offsets_[REC_OFFS_NORMAL_SIZE];
2845 ulint *offsets = offsets_;
2846 rec_offs_init(offsets_);
2847 rtr_info_t rtr_info;
2848
2849 ut_ad(!index->is_clustered());
2850 ut_ad(mode == BTR_MODIFY_LEAF || mode == BTR_MODIFY_TREE);
2851
2852 cursor.thr = thr;
2853 cursor.rtr_info = nullptr;
2854 ut_ad(thr_get_trx(thr)->id != 0 || index->table->is_intrinsic());
2855
2856 mtr_start(&mtr);
2857
2858 if (index->table->is_temporary()) {
2859 /* Disable REDO logging as the lifetime of temp-tables is
2860 limited to server or connection lifetime and so REDO
2861 information is not needed on restart for recovery.
2862 Disable locking as temp-tables are local to a connection. */
2863
2864 ut_ad(flags & BTR_NO_LOCKING_FLAG);
2865 ut_ad(!index->table->is_intrinsic() || (flags & BTR_NO_UNDO_LOG_FLAG));
2866
2867 mtr.set_log_mode(MTR_LOG_NO_REDO);
2868 } else if (!dict_index_is_spatial(index)) {
2869 /* Enable insert buffering if it's neither temp-table
2870 nor spatial index. */
2871 search_mode |= BTR_INSERT;
2872 }
2873
2874 /* Ensure that we acquire index->lock when inserting into an
2875 index with index->online_status == ONLINE_INDEX_COMPLETE, but
2876 could still be subject to rollback_inplace_alter_table().
2877 This prevents a concurrent change of index->online_status.
2878 The memory object cannot be freed as long as we have an open
2879 reference to the table, or index->table->n_ref_count > 0. */
2880 bool check = !index->is_committed();
2881
2882 DBUG_EXECUTE_IF("idx_mimic_not_committed", {
2883 check = true;
2884 mode = BTR_MODIFY_TREE;
2885 });
2886
2887 if (check) {
2888 DEBUG_SYNC(thr_get_trx(thr)->mysql_thd, "row_ins_sec_index_enter");
2889 if (mode == BTR_MODIFY_LEAF) {
2890 search_mode |= BTR_ALREADY_S_LATCHED;
2891 mtr_s_lock(dict_index_get_lock(index), &mtr, UT_LOCATION_HERE);
2892 } else {
2893 mtr_sx_lock(dict_index_get_lock(index), &mtr, UT_LOCATION_HERE);
2894 }
2895
2896 if (row_log_online_op_try(index, entry, thr_get_trx(thr)->id)) {
2897 goto func_exit;
2898 }
2899 }
2900
2901 /* Note that we use PAGE_CUR_LE as the search mode, because then
2902 the function will return in both low_match and up_match of the
2903 cursor sensible values */
2904
2905 if (!thr_get_trx(thr)->check_unique_secondary) {
2906 search_mode |= BTR_IGNORE_SEC_UNIQUE;
2907 }
2908
2909 if (dict_index_is_spatial(index)) {
2910 cursor.index = index;
2911 rtr_init_rtr_info(&rtr_info, false, &cursor, index, false);
2912 rtr_info_update_btr(&cursor, &rtr_info);
2913
2914 btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_RTREE_INSERT,
2915 search_mode, &cursor, 0, __FILE__, __LINE__,
2916 &mtr);
2917
2918 if (mode == BTR_MODIFY_LEAF && rtr_info.mbr_adj) {
2919 mtr_commit(&mtr);
2920 rtr_clean_rtr_info(&rtr_info, true);
2921 rtr_init_rtr_info(&rtr_info, false, &cursor, index, false);
2922 rtr_info_update_btr(&cursor, &rtr_info);
2923
2924 mtr_start(&mtr);
2925
2926 if (index->table->is_temporary()) {
2927 mtr.set_log_mode(MTR_LOG_NO_REDO);
2928 }
2929
2930 search_mode &= ~BTR_MODIFY_LEAF;
2931
2932 search_mode |= BTR_MODIFY_TREE;
2933
2934 btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_RTREE_INSERT,
2935 search_mode, &cursor, 0, __FILE__, __LINE__,
2936 &mtr);
2937 mode = BTR_MODIFY_TREE;
2938 }
2939
2940 DBUG_EXECUTE_IF("rtree_test_check_count", { goto func_exit; });
2941
2942 } else {
2943 if (index->table->is_intrinsic()) {
2944 btr_cur_search_to_nth_level_with_no_latch(
2945 index, 0, entry, PAGE_CUR_LE, &cursor, __FILE__, __LINE__, &mtr);
2946 ut_ad(cursor.page_cur.block != nullptr);
2947 ut_ad(cursor.page_cur.block->made_dirty_with_no_latch);
2948 } else {
2949 btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_LE, search_mode,
2950 &cursor, 0, __FILE__, __LINE__, &mtr);
2951 }
2952 }
2953
2954 if (cursor.flag == BTR_CUR_INSERT_TO_IBUF) {
2955 ut_ad(!dict_index_is_spatial(index));
2956 /* The insert was buffered during the search: we are done */
2957 goto func_exit;
2958 }
2959
2960 #ifdef UNIV_DEBUG
2961 {
2962 page_t *page = btr_cur_get_page(&cursor);
2963 rec_t *first_rec = page_rec_get_next(page_get_infimum_rec(page));
2964
2965 ut_ad(page_rec_is_supremum(first_rec) ||
2966 rec_n_fields_is_sane(index, first_rec, entry));
2967 }
2968 #endif /* UNIV_DEBUG */
2969
2970 n_unique = dict_index_get_n_unique(index);
2971
2972 if (dict_index_is_unique(index) &&
2973 (cursor.low_match >= n_unique || cursor.up_match >= n_unique)) {
2974 mtr_commit(&mtr);
2975
2976 DEBUG_SYNC_C("row_ins_sec_index_unique");
2977
2978 if (row_ins_sec_mtr_start_and_check_if_aborted(&mtr, index, check,
2979 search_mode)) {
2980 goto func_exit;
2981 }
2982
2983 err = row_ins_scan_sec_index_for_duplicate(flags, index, entry, thr, check,
2984 &mtr, offsets_heap);
2985
2986 mtr_commit(&mtr);
2987
2988 switch (err) {
2989 case DB_SUCCESS:
2990 break;
2991 case DB_DUPLICATE_KEY:
2992 if (!index->is_committed()) {
2993 ut_ad(!thr_get_trx(thr)->dict_operation_lock_mode);
2994
2995 dict_set_corrupted(index);
2996 /* Do not return any error to the
2997 caller. The duplicate will be reported
2998 by ALTER TABLE or CREATE UNIQUE INDEX.
2999 Unfortunately we cannot report the
3000 duplicate key value to the DDL thread,
3001 because the altered_table object is
3002 private to its call stack. */
3003 err = DB_SUCCESS;
3004 }
3005 [[fallthrough]];
3006 default:
3007 if (dict_index_is_spatial(index)) {
3008 rtr_clean_rtr_info(&rtr_info, true);
3009 }
3010 return err;
3011 }
3012
3013 if (row_ins_sec_mtr_start_and_check_if_aborted(&mtr, index, check,
3014 search_mode)) {
3015 goto func_exit;
3016 }
3017
3018 DEBUG_SYNC_C("row_ins_sec_index_entry_dup_locks_created");
3019
3020 /* We did not find a duplicate and we have now
3021 locked with s-locks the necessary records to
3022 prevent any insertion of a duplicate by another
3023 transaction. Let us now reposition the cursor and
3024 continue the insertion. */
3025 if (index->table->is_intrinsic()) {
3026 btr_cur_search_to_nth_level_with_no_latch(
3027 index, 0, entry, PAGE_CUR_LE, &cursor, __FILE__, __LINE__, &mtr);
3028 ut_ad(cursor.page_cur.block != nullptr);
3029 ut_ad(cursor.page_cur.block->made_dirty_with_no_latch);
3030 } else {
3031 btr_cur_search_to_nth_level(
3032 index, 0, entry, PAGE_CUR_LE,
3033 (search_mode & ~(BTR_INSERT | BTR_IGNORE_SEC_UNIQUE)), &cursor, 0,
3034 __FILE__, __LINE__, &mtr);
3035 }
3036 }
3037
3038 if (dup_chk_only) {
3039 goto func_exit;
3040 }
3041
3042 if (row_ins_must_modify_rec(&cursor)) {
3043 /* If the existing record is being modified and the new record
3044 is doesn't fit the provided slot then existing record is added
3045 to free list and new record is inserted. This also means
3046 cursor that we have cached for SELECT is now invalid. */
3047 if (index->last_sel_cur) {
3048 index->last_sel_cur->invalid = true;
3049 }
3050
3051 /* There is already an index entry with a long enough common
3052 prefix, we must convert the insert into a modify of an
3053 existing record */
3054 offsets = rec_get_offsets(btr_cur_get_rec(&cursor), index, offsets,
3055 ULINT_UNDEFINED, UT_LOCATION_HERE, &offsets_heap);
3056
3057 err = row_ins_sec_index_entry_by_modify(
3058 flags, mode, &cursor, &offsets, offsets_heap, heap, entry, thr, &mtr);
3059
3060 if (err == DB_SUCCESS && dict_index_is_spatial(index) && rtr_info.mbr_adj) {
3061 err = rtr_ins_enlarge_mbr(&cursor, &mtr);
3062 }
3063 } else {
3064 rec_t *insert_rec;
3065 big_rec_t *big_rec;
3066
3067 if (mode == BTR_MODIFY_LEAF) {
3068 err = btr_cur_optimistic_insert(flags, &cursor, &offsets, &offsets_heap,
3069 entry, &insert_rec, &big_rec, thr, &mtr);
3070 if (err == DB_SUCCESS && dict_index_is_spatial(index) &&
3071 rtr_info.mbr_adj) {
3072 err = rtr_ins_enlarge_mbr(&cursor, &mtr);
3073 }
3074 } else {
3075 ut_ad(mode == BTR_MODIFY_TREE);
3076 if (buf_LRU_buf_pool_running_out()) {
3077 err = DB_LOCK_TABLE_FULL;
3078 goto func_exit;
3079 }
3080
3081 err = btr_cur_optimistic_insert(flags, &cursor, &offsets, &offsets_heap,
3082 entry, &insert_rec, &big_rec, thr, &mtr);
3083 if (err == DB_FAIL) {
3084 err =
3085 btr_cur_pessimistic_insert(flags, &cursor, &offsets, &offsets_heap,
3086 entry, &insert_rec, &big_rec, thr, &mtr);
3087 }
3088 if (err == DB_SUCCESS && dict_index_is_spatial(index) &&
3089 rtr_info.mbr_adj) {
3090 err = rtr_ins_enlarge_mbr(&cursor, &mtr);
3091 }
3092 }
3093
3094 if (err == DB_SUCCESS && trx_id) {
3095 page_update_max_trx_id(btr_cur_get_block(&cursor),
3096 btr_cur_get_page_zip(&cursor), trx_id, &mtr);
3097 }
3098
3099 ut_ad(!big_rec);
3100 }
3101
3102 func_exit:
3103 if (dict_index_is_spatial(index)) {
3104 rtr_clean_rtr_info(&rtr_info, true);
3105 }
3106
3107 mtr_commit(&mtr);
3108 return err;
3109 }
3110
3111 /** Inserts an entry into a clustered index. Tries first optimistic,
3112 then pessimistic descent down the tree. If the entry matches enough
3113 to a delete marked record, performs the insert by updating or delete
3114 unmarking the delete marked record.
3115 @return DB_SUCCESS, DB_LOCK_WAIT, DB_DUPLICATE_KEY, or some other error code */
3116 dberr_t row_ins_clust_index_entry(
3117 dict_index_t *index, /*!< in: clustered index */
3118 dtuple_t *entry, /*!< in/out: index entry to insert */
3119 que_thr_t *thr, /*!< in: query thread */
3120 bool dup_chk_only)
3121 /*!< in: if true, just do duplicate check
3122 and return. don't execute actual insert. */
3123 {
3124 dberr_t err;
3125 ulint n_uniq;
3126
3127 DBUG_TRACE;
3128
3129 if (!index->table->foreign_set.empty()) {
3130 err = row_ins_check_foreign_constraints(index->table, index, entry, thr);
3131 if (err != DB_SUCCESS) {
3132 return err;
3133 }
3134 }
3135
3136 n_uniq = dict_index_is_unique(index) ? index->n_uniq : 0;
3137
3138 /* Try first optimistic descent to the B-tree */
3139 uint32_t flags;
3140
3141 if (!index->table->is_intrinsic()) {
3142 log_free_check();
3143 flags = index->table->is_temporary() ? BTR_NO_LOCKING_FLAG : 0;
3144
3145 /* For intermediate table of copy alter operation,
3146 skip undo logging and record lock checking for
3147 insertion operation. */
3148 if (index->table->skip_alter_undo) {
3149 flags |= BTR_NO_UNDO_LOG_FLAG | BTR_NO_LOCKING_FLAG;
3150 }
3151
3152 } else {
3153 flags = BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG;
3154 }
3155
3156 if (index->table->is_intrinsic() && dict_index_is_auto_gen_clust(index)) {
3157 /* Check if the memory allocated for intrinsic cache*/
3158 if (!index->last_ins_cur) {
3159 dict_allocate_mem_intrinsic_cache(index);
3160 }
3161 err = row_ins_sorted_clust_index_entry(BTR_MODIFY_LEAF, index, entry, thr);
3162 } else {
3163 err = row_ins_clust_index_entry_low(flags, BTR_MODIFY_LEAF, index, n_uniq,
3164 entry, thr, dup_chk_only);
3165 }
3166
3167 DEBUG_SYNC(thr_get_trx(thr)->mysql_thd,
3168 "after_row_ins_clust_index_entry_leaf");
3169
3170 if (err != DB_FAIL) {
3171 DEBUG_SYNC_C("row_ins_clust_index_entry_leaf_after");
3172 return err;
3173 }
3174
3175 /* Try then pessimistic descent to the B-tree */
3176 if (!index->table->is_intrinsic()) {
3177 log_free_check();
3178 } else if (!index->last_sel_cur) {
3179 dict_allocate_mem_intrinsic_cache(index);
3180 index->last_sel_cur->invalid = true;
3181 } else {
3182 index->last_sel_cur->invalid = true;
3183 }
3184
3185 if (index->table->is_intrinsic() && dict_index_is_auto_gen_clust(index)) {
3186 err = row_ins_sorted_clust_index_entry(BTR_MODIFY_TREE, index, entry, thr);
3187 } else {
3188 err = row_ins_clust_index_entry_low(flags, BTR_MODIFY_TREE, index, n_uniq,
3189 entry, thr, dup_chk_only);
3190 }
3191
3192 return err;
3193 }
3194
3195 /** Inserts an entry into a secondary index. Tries first optimistic,
3196 then pessimistic descent down the tree. If the entry matches enough
3197 to a delete marked record, performs the insert by updating or delete
3198 unmarking the delete marked record.
3199 @return DB_SUCCESS, DB_LOCK_WAIT, DB_DUPLICATE_KEY, or some other error code */
3200 dberr_t row_ins_sec_index_entry(
3201 dict_index_t *index, /*!< in: secondary index */
3202 dtuple_t *entry, /*!< in/out: index entry to insert */
3203 que_thr_t *thr, /*!< in: query thread */
3204 bool dup_chk_only)
3205 /*!< in: if true, just do duplicate check
3206 and return. don't execute actual insert. */
3207 {
3208 dberr_t err;
3209 mem_heap_t *offsets_heap;
3210 mem_heap_t *heap;
3211 trx_id_t trx_id = 0;
3212
3213 DBUG_EXECUTE_IF("row_ins_sec_index_entry_timeout", {
3214 DBUG_SET("-d,row_ins_sec_index_entry_timeout");
3215 return (DB_LOCK_WAIT);
3216 });
3217
3218 DBUG_EXECUTE_IF("row_ins_sec_index_entry_lock_wait", {
3219 static uint16_t count = 0;
3220 if (index->is_multi_value()) {
3221 ++count;
3222 }
3223 if (count == 2) {
3224 count = 0;
3225 return (DB_LOCK_WAIT);
3226 }
3227 });
3228
3229 if (!index->table->foreign_set.empty()) {
3230 err = row_ins_check_foreign_constraints(index->table, index, entry, thr);
3231 if (err != DB_SUCCESS) {
3232 return (err);
3233 }
3234 }
3235
3236 offsets_heap = mem_heap_create(1024, UT_LOCATION_HERE);
3237 heap = mem_heap_create(1024, UT_LOCATION_HERE);
3238
3239 /* Try first optimistic descent to the B-tree */
3240
3241 uint32_t flags;
3242
3243 if (!index->table->is_intrinsic()) {
3244 log_free_check();
3245 ut_ad(thr_get_trx(thr)->id != 0);
3246
3247 flags = index->table->is_temporary() ? BTR_NO_LOCKING_FLAG : 0;
3248 /* For intermediate table during copy alter table,
3249 skip the undo log and record lock checking for
3250 insertion operation. */
3251 if (index->table->skip_alter_undo) {
3252 trx_id = thr_get_trx(thr)->id;
3253 flags |= BTR_NO_UNDO_LOG_FLAG | BTR_NO_LOCKING_FLAG;
3254 }
3255
3256 } else {
3257 flags = BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG;
3258 }
3259
3260 err = row_ins_sec_index_entry_low(flags, BTR_MODIFY_LEAF, index, offsets_heap,
3261 heap, entry, trx_id, thr, dup_chk_only);
3262 if (err == DB_FAIL) {
3263 mem_heap_empty(heap);
3264
3265 /* Try then pessimistic descent to the B-tree */
3266
3267 if (!index->table->is_intrinsic()) {
3268 log_free_check();
3269 } else if (!index->last_sel_cur) {
3270 dict_allocate_mem_intrinsic_cache(index);
3271 index->last_sel_cur->invalid = true;
3272 } else {
3273 index->last_sel_cur->invalid = true;
3274 }
3275
3276 err =
3277 row_ins_sec_index_entry_low(flags, BTR_MODIFY_TREE, index, offsets_heap,
3278 heap, entry, 0, thr, dup_chk_only);
3279 }
3280
3281 mem_heap_free(heap);
3282 mem_heap_free(offsets_heap);
3283 return (err);
3284 }
3285
3286 /** Inserts an entry into a secondary index, which is created for
3287 multi-value field. For each value to be inserted, it tries first optimistic,
3288 then pessimistic descent down the tree. If the entry matches enough
3289 to a delete marked record, performs the insert by updating or delete
3290 unmarking the delete marked record.
3291 @param[in] index secondary index which is for multi-value field
3292 @param[in,out] entry index entry to insert
3293 @param[in,out] multi_val_pos the start position to insert next multi-value
3294 data, and the returned value should be either
3295 0 if all are done, or the position where the
3296 insert failed. So return value of 0 could be
3297 a bit ambiguous, however the return error
3298 can help to see which case it is
3299 @param[in] thr query thread
3300 @return DB_SUCCESS, DB_LOCK_WAIT, DB_DUPLICATE_KEY, or some other error code */
3301 static dberr_t row_ins_sec_index_multi_value_entry(dict_index_t *index,
3302 dtuple_t *entry,
3303 uint32_t &multi_val_pos,
3304 que_thr_t *thr) {
3305 ut_d(trx_t *trx = thr_get_trx(thr));
3306
3307 ut_ad(trx->id != 0);
3308 ut_ad(!index->table->is_intrinsic());
3309 ut_ad(index->is_committed());
3310 ut_ad(!dict_index_is_online_ddl(index));
3311 ut_ad(index->is_multi_value());
3312
3313 dberr_t err = DB_SUCCESS;
3314 Multi_value_entry_builder_insert mv_entry_builder(index, entry);
3315
3316 for (dtuple_t *mv_entry = mv_entry_builder.begin(multi_val_pos);
3317 mv_entry != nullptr; mv_entry = mv_entry_builder.next()) {
3318 err = row_ins_sec_index_entry(index, mv_entry, thr, false);
3319 if (err != DB_SUCCESS) {
3320 multi_val_pos = mv_entry_builder.last_multi_value_position();
3321 return (err);
3322 }
3323 }
3324
3325 multi_val_pos = 0;
3326
3327 return (err);
3328 }
3329
3330 /** Inserts an index entry to index. Tries first optimistic, then pessimistic
3331 descent down the tree. If the entry matches enough to a delete marked record,
3332 performs the insert by updating or delete unmarking the delete marked
3333 record.
3334 @param[in] index index to insert the entry
3335 @param[in,out] entry entry to insert
3336 @param[in,out] multi_val_pos if multi-value index, the start position
3337 to insert next multi-value data,
3338 and the returned value should be either
3339 0 if all are done, or the position where the
3340 insert failed. So return value of 0 could be
3341 a bit ambiguous, however the return error
3342 can help to see which case it is
3343 @param[in] thr query thread
3344 @return DB_SUCCESS, DB_LOCK_WAIT, DB_DUPLICATE_KEY, or some other error code */
3345 static dberr_t row_ins_index_entry(dict_index_t *index, dtuple_t *entry,
3346 uint32_t &multi_val_pos, que_thr_t *thr) {
3347 ut_ad(thr_get_trx(thr)->id != 0);
3348
3349 DBUG_EXECUTE_IF("row_ins_index_entry_timeout", {
3350 DBUG_SET("-d,row_ins_index_entry_timeout");
3351 return (DB_LOCK_WAIT);
3352 });
3353
3354 if (index->is_clustered()) {
3355 return (row_ins_clust_index_entry(index, entry, thr, false));
3356 } else if (index->is_multi_value()) {
3357 return (
3358 row_ins_sec_index_multi_value_entry(index, entry, multi_val_pos, thr));
3359 } else {
3360 return (row_ins_sec_index_entry(index, entry, thr, false));
3361 }
3362 }
3363
3364 /** This function generate MBR (Minimum Bounding Box) for spatial objects
3365 and set it to spatial index field. */
3366 static void row_ins_spatial_index_entry_set_mbr_field(
3367 dfield_t *field, /*!< in/out: mbr field */
3368 const dfield_t *row_field, /*!< in: row field */
3369 uint32_t *srid, /*!< in/out: spatial reference id */
3370 const dd::Spatial_reference_system *srs) /*!< in: SRS of row_field */
3371 {
3372 uchar *dptr = nullptr;
3373 ulint dlen = 0;
3374 double mbr[SPDIMS * 2];
3375
3376 /* This must be a GEOMETRY datatype */
3377 ut_ad(DATA_GEOMETRY_MTYPE(field->type.mtype));
3378
3379 dptr = static_cast<uchar *>(dfield_get_data(row_field));
3380 dlen = dfield_get_len(row_field);
3381
3382 /* obtain the MBR */
3383 get_mbr_from_store(srs, dptr, static_cast<uint>(dlen), SPDIMS, mbr, srid);
3384
3385 /* Set mbr as index entry data */
3386 dfield_write_mbr(field, mbr);
3387 }
3388
3389 /** Sets the values of the dtuple fields in entry from the values of appropriate
3390 columns in row.
3391 @param[in] index index handler
3392 @param[out] entry index entry to make
3393 @param[in] row row
3394 @return DB_SUCCESS if the set is successful */
3395 dberr_t row_ins_index_entry_set_vals(const dict_index_t *index, dtuple_t *entry,
3396 const dtuple_t *row) {
3397 ulint n_fields;
3398 ulint i;
3399 ulint num_v = dtuple_get_n_v_fields(entry);
3400
3401 n_fields = dtuple_get_n_fields(entry);
3402
3403 for (i = 0; i < n_fields + num_v; i++) {
3404 dict_field_t *ind_field = nullptr;
3405 dfield_t *field;
3406 const dfield_t *row_field;
3407 ulint len;
3408 dict_col_t *col;
3409
3410 if (i >= n_fields) {
3411 /* This is virtual field */
3412 field = dtuple_get_nth_v_field(entry, i - n_fields);
3413 col = &dict_table_get_nth_v_col(index->table, i - n_fields)->m_col;
3414 } else {
3415 field = dtuple_get_nth_field(entry, i);
3416 ind_field = index->get_field(i);
3417 col = ind_field->col;
3418 ut_ad(!col->is_instant_dropped());
3419 }
3420
3421 if (col->is_virtual()) {
3422 const dict_v_col_t *v_col = reinterpret_cast<const dict_v_col_t *>(col);
3423 ut_ad(dtuple_get_n_fields(row) == index->table->get_n_cols());
3424 row_field = dtuple_get_nth_v_field(row, v_col->v_pos);
3425 } else {
3426 row_field = dtuple_get_nth_field(row, ind_field->col->ind);
3427 }
3428
3429 len = dfield_get_len(row_field);
3430
3431 /* Check column prefix indexes */
3432 if (ind_field != nullptr && ind_field->prefix_len > 0 &&
3433 dfield_get_len(row_field) != UNIV_SQL_NULL) {
3434 const dict_col_t *col = ind_field->col;
3435
3436 len = dtype_get_at_most_n_mbchars(
3437 col->prtype, col->mbminmaxlen, ind_field->prefix_len, len,
3438 static_cast<const char *>(dfield_get_data(row_field)));
3439
3440 ut_ad(!dfield_is_ext(row_field));
3441 }
3442
3443 /* Handle spatial index. For the first field, replace
3444 the data with its MBR (Minimum Bounding Box). */
3445 if ((i == 0) && dict_index_is_spatial(index)) {
3446 if (!row_field->data || row_field->len < GEO_DATA_HEADER_SIZE) {
3447 return (DB_CANT_CREATE_GEOMETRY_OBJECT);
3448 }
3449
3450 uint32_t srid;
3451 row_ins_spatial_index_entry_set_mbr_field(field, row_field, &srid,
3452 index->rtr_srs.get());
3453
3454 if (index->srid_is_valid && index->srid != srid) {
3455 return DB_CANT_CREATE_GEOMETRY_OBJECT;
3456 }
3457
3458 continue;
3459 }
3460
3461 dfield_set_data(field, dfield_get_data(row_field), len);
3462 if (dfield_is_ext(row_field)) {
3463 ut_ad(index->is_clustered());
3464 dfield_set_ext(field);
3465 }
3466 }
3467
3468 return (DB_SUCCESS);
3469 }
3470
3471 /** Inserts a single index entry to the table.
3472 @return DB_SUCCESS if operation successfully completed, else error
3473 code or DB_LOCK_WAIT */
3474 [[nodiscard]] static dberr_t row_ins_index_entry_step(
3475 ins_node_t *node, /*!< in: row insert node */
3476 que_thr_t *thr) /*!< in: query thread */
3477 {
3478 dberr_t err;
3479
3480 DBUG_TRACE;
3481
3482 ut_ad(dtuple_check_typed(node->row));
3483
3484 err = row_ins_index_entry_set_vals(node->index, node->entry, node->row);
3485
3486 if (err != DB_SUCCESS) {
3487 return err;
3488 }
3489
3490 ut_ad(dtuple_check_typed(node->entry));
3491
3492 err = row_ins_index_entry(node->index, node->entry, node->ins_multi_val_pos,
3493 thr);
3494
3495 DEBUG_SYNC(thr_get_trx(thr)->mysql_thd, "after_row_ins_index_entry_step");
3496
3497 return err;
3498 }
3499
3500 /** Allocates a row id for row and inits the node->index field. */
3501 static inline void row_ins_alloc_row_id_step(
3502 ins_node_t *node) /*!< in: row insert node */
3503 {
3504 row_id_t row_id;
3505
3506 ut_ad(node->state == INS_NODE_ALLOC_ROW_ID);
3507
3508 if (dict_index_is_unique(node->table->first_index())) {
3509 /* No row id is stored if the clustered index is unique */
3510
3511 return;
3512 }
3513
3514 /* Fill in row id value to row */
3515
3516 row_id = dict_sys_get_new_row_id();
3517
3518 dict_sys_write_row_id(node->row_id_buf, row_id);
3519 }
3520
3521 /** Gets a row to insert from the values list. */
3522 static inline void row_ins_get_row_from_values(
3523 ins_node_t *node) /*!< in: row insert node */
3524 {
3525 que_node_t *list_node;
3526 dfield_t *dfield;
3527 dtuple_t *row;
3528 ulint i;
3529
3530 /* The field values are copied in the buffers of the select node and
3531 it is safe to use them until we fetch from select again: therefore
3532 we can just copy the pointers */
3533
3534 row = node->row;
3535
3536 i = 0;
3537 list_node = node->values_list;
3538
3539 while (list_node) {
3540 eval_exp(list_node);
3541
3542 dfield = dtuple_get_nth_field(row, i);
3543 dfield_copy_data(dfield, que_node_get_val(list_node));
3544
3545 i++;
3546 list_node = que_node_get_next(list_node);
3547 }
3548 }
3549
3550 /** Gets a row to insert from the select list. */
3551 static inline void row_ins_get_row_from_query_block(
3552 ins_node_t *node) /*!< in: row insert node */
3553 {
3554 que_node_t *list_node;
3555 dfield_t *dfield;
3556 dtuple_t *row;
3557 ulint i;
3558
3559 /* The field values are copied in the buffers of the select node and
3560 it is safe to use them until we fetch from select again: therefore
3561 we can just copy the pointers */
3562
3563 row = node->row;
3564
3565 i = 0;
3566 list_node = node->select->select_list;
3567
3568 while (list_node) {
3569 dfield = dtuple_get_nth_field(row, i);
3570 dfield_copy_data(dfield, que_node_get_val(list_node));
3571
3572 i++;
3573 list_node = que_node_get_next(list_node);
3574 }
3575 }
3576
3577 /** Inserts a row to a table.
3578 @return DB_SUCCESS if operation successfully completed, else error
3579 code or DB_LOCK_WAIT */
3580 [[nodiscard]] static dberr_t row_ins(
3581 ins_node_t *node, /*!< in: row insert node */
3582 que_thr_t *thr) /*!< in: query thread */
3583 {
3584 dberr_t err;
3585
3586 DBUG_TRACE;
3587
3588 DBUG_PRINT("row_ins", ("table: %s", node->table->name.m_name));
3589
3590 if (node->state == INS_NODE_ALLOC_ROW_ID) {
3591 row_ins_alloc_row_id_step(node);
3592
3593 node->index = node->table->first_index();
3594 node->entry = UT_LIST_GET_FIRST(node->entry_list);
3595
3596 if (node->ins_type == INS_SEARCHED) {
3597 row_ins_get_row_from_query_block(node);
3598
3599 } else if (node->ins_type == INS_VALUES) {
3600 row_ins_get_row_from_values(node);
3601 }
3602
3603 node->state = INS_NODE_INSERT_ENTRIES;
3604 }
3605
3606 ut_ad(node->state == INS_NODE_INSERT_ENTRIES);
3607
3608 while (node->index != nullptr) {
3609 if (node->index->type != DICT_FTS) {
3610 err = row_ins_index_entry_step(node, thr);
3611
3612 switch (err) {
3613 case DB_SUCCESS:
3614 break;
3615 case DB_DUPLICATE_KEY:
3616 thr_get_trx(thr)->error_state = DB_DUPLICATE_KEY;
3617 thr_get_trx(thr)->error_index = node->index;
3618 [[fallthrough]];
3619 default:
3620 return err;
3621 }
3622 }
3623
3624 node->index = node->index->next();
3625 node->entry = UT_LIST_GET_NEXT(tuple_list, node->entry);
3626
3627 DBUG_EXECUTE_IF("row_ins_skip_sec", node->index = nullptr;
3628 node->entry = nullptr; break;);
3629
3630 /* Skip corrupted secondary index and its entry */
3631 while (node->index && node->index->is_corrupted()) {
3632 node->index = node->index->next();
3633 node->entry = UT_LIST_GET_NEXT(tuple_list, node->entry);
3634 }
3635 }
3636
3637 ut_ad(node->entry == nullptr);
3638
3639 thr_get_trx(thr)->error_index = nullptr;
3640 node->state = INS_NODE_ALLOC_ROW_ID;
3641
3642 return DB_SUCCESS;
3643 }
3644
3645 /** Inserts a row to a table. This is a high-level function used in SQL
3646 execution graphs.
3647 @return query thread to run next or NULL */
3648 que_thr_t *row_ins_step(que_thr_t *thr) /*!< in: query thread */
3649 {
3650 ins_node_t *node;
3651 que_node_t *parent;
3652 sel_node_t *sel_node;
3653 trx_t *trx;
3654 dberr_t err;
3655
3656 ut_ad(thr);
3657
3658 DEBUG_SYNC_C("innodb_row_ins_step_enter");
3659
3660 trx = thr_get_trx(thr);
3661
3662 trx_start_if_not_started_xa(trx, true, UT_LOCATION_HERE);
3663
3664 node = static_cast<ins_node_t *>(thr->run_node);
3665
3666 ut_ad(que_node_get_type(node) == QUE_NODE_INSERT);
3667 ut_ad(!node->table->is_intrinsic());
3668
3669 parent = que_node_get_parent(node);
3670 sel_node = node->select;
3671
3672 if (thr->prev_node == parent) {
3673 node->state = INS_NODE_SET_IX_LOCK;
3674 }
3675
3676 /* If this is the first time this node is executed (or when
3677 execution resumes after wait for the table IX lock), set an
3678 IX lock on the table and reset the possible select node. MySQL's
3679 partitioned table code may also call an insert within the same
3680 SQL statement AFTER it has used this table handle to do a search.
3681 This happens, for example, when a row update moves it to another
3682 partition. In that case, we have already set the IX lock on the
3683 table during the search operation, and there is no need to set
3684 it again here. But we must write trx->id to node->trx_id_buf. */
3685
3686 memset(node->trx_id_buf, 0, DATA_TRX_ID_LEN);
3687 trx_write_trx_id(node->trx_id_buf, trx->id);
3688
3689 if (node->state == INS_NODE_SET_IX_LOCK) {
3690 node->state = INS_NODE_ALLOC_ROW_ID;
3691
3692 /* It may be that the current session has not yet started
3693 its transaction, or it has been committed: */
3694
3695 if (trx->id == node->trx_id) {
3696 /* No need to do IX-locking */
3697
3698 goto same_trx;
3699 }
3700
3701 err = lock_table(0, node->table, LOCK_IX, thr);
3702
3703 DBUG_EXECUTE_IF("ib_row_ins_ix_lock_wait", err = DB_LOCK_WAIT;);
3704
3705 if (err != DB_SUCCESS) {
3706 goto error_handling;
3707 }
3708
3709 node->trx_id = trx->id;
3710 same_trx:
3711 if (node->ins_type == INS_SEARCHED) {
3712 /* Reset the cursor */
3713 sel_node->state = SEL_NODE_OPEN;
3714
3715 /* Fetch a row to insert */
3716
3717 thr->run_node = sel_node;
3718
3719 return (thr);
3720 }
3721 }
3722
3723 if ((node->ins_type == INS_SEARCHED) && (sel_node->state != SEL_NODE_FETCH)) {
3724 ut_ad(sel_node->state == SEL_NODE_NO_MORE_ROWS);
3725
3726 /* No more rows to insert */
3727 thr->run_node = parent;
3728
3729 return (thr);
3730 }
3731
3732 /* DO THE CHECKS OF THE CONSISTENCY CONSTRAINTS HERE */
3733
3734 err = row_ins(node, thr);
3735
3736 error_handling:
3737 trx->error_state = err;
3738
3739 if (err != DB_SUCCESS) {
3740 /* err == DB_LOCK_WAIT or SQL error detected */
3741 return (nullptr);
3742 }
3743
3744 /* DO THE TRIGGER ACTIONS HERE */
3745
3746 if (node->ins_type == INS_SEARCHED) {
3747 /* Fetch a row to insert */
3748
3749 thr->run_node = sel_node;
3750 } else {
3751 thr->run_node = que_node_get_parent(node);
3752 }
3753
3754 return (thr);
3755 }