Debian Codegraph @

storage/innobase/row/row0mysql.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2000, 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/row0mysql.cc
29 Interface between Innobase row operations and MySQL.
30 Contains also create table and other data dictionary operations.
31
32 Created 9/17/2000 Heikki Tuuri
33 *******************************************************/
34
35 #include <debug_sync.h>
36 #include <gstream.h>
37 #include <spatial.h>
38 #include <sql_class.h>
39 #include <sql_const.h>
40 #include <sys/types.h>
41 #include <algorithm>
42 #include <deque>
43 #include <new>
44 #include <vector>
45
46 #include "btr0sea.h"
47 #include "ddl0ddl.h"
48 #include "dict0boot.h"
49 #include "dict0crea.h"
50 #include "dict0dd.h"
51 #include "dict0dict.h"
52 #include "dict0load.h"
53 #include "dict0priv.h"
54 #include "dict0stats.h"
55 #include "dict0stats_bg.h"
56 #include "fil0fil.h"
57 #include "fsp0file.h"
58 #include "fsp0sysspace.h"
59 #include "fts0fts.h"
60 #include "fts0types.h"
61 #include "ha_prototypes.h"
62 #include "ibuf0ibuf.h"
63 #include "lock0lock.h"
64 #include "log0buf.h"
65 #include "log0chkp.h"
66 #include "pars0pars.h"
67 #include "que0que.h"
68 #include "rem0cmp.h"
69 #include "row0ext.h"
70 #include "row0import.h"
71 #include "row0ins.h"
72 #include "row0mysql.h"
73 #include "row0pread.h"
74 #include "row0row.h"
75 #include "row0sel.h"
76 #include "row0upd.h"
77 #include "trx0purge.h"
78 #include "trx0rec.h"
79 #include "trx0roll.h"
80 #include "trx0undo.h"
81 #include "ut0cpu_cache.h"
82 #include "ut0new.h"
83
84 #include "current_thd.h"
85 #include "my_dbug.h"
86 #include "my_io.h"
87
88 static const char *MODIFICATIONS_NOT_ALLOWED_MSG_FORCE_RECOVERY =
89 "innodb_force_recovery is on. We do not allow database modifications"
90 " by the user. Shut down mysqld and edit my.cnf to set"
91 " innodb_force_recovery=0";
92
93 /** Provide optional 4.x backwards compatibility for 5.0 and above */
94 bool row_rollback_on_timeout = false;
95
96 /** Chain node of the list of tables to drop in the background. */
97 struct row_mysql_drop_t {
98 char *table_name; /*!< table name */
99 UT_LIST_NODE_T(row_mysql_drop_t) row_mysql_drop_list;
100 /*!< list chain node */
101 };
102
103 /** @brief List of tables we should drop in background.
104
105 ALTER TABLE in MySQL requires that the table handler can drop the
106 table in background when there are no queries to it any
107 more. Protected by row_drop_list_mutex. */
108 static UT_LIST_BASE_NODE_T(row_mysql_drop_t,
109 row_mysql_drop_list) row_mysql_drop_list;
110
111 /** Mutex protecting the background table drop list. */
112 static ib_mutex_t row_drop_list_mutex;
113
114 /** Flag: has row_mysql_drop_list been initialized? */
115 static bool row_mysql_drop_list_inited = false;
116
117 /** If a table is not yet in the drop list, adds the table to the list of tables
118 which the master thread drops in background. We need this on Unix because in
119 ALTER TABLE MySQL may call drop table even if the table has running queries on
120 it. Also, if there are running foreign key checks on the table, we drop the
121 table lazily.
122 @return true if the table was not yet in the drop list, and was added there */
123 static bool row_add_table_to_background_drop_list(
124 const char *name); /*!< in: table name */
125
126 #ifdef UNIV_DEBUG
127 /** Wait for the background drop list to become empty. */
128 void row_wait_for_background_drop_list_empty() {
129 while (UT_LIST_GET_LEN(row_mysql_drop_list) > 0) {
130 std::this_thread::sleep_for(std::chrono::milliseconds(100));
131 }
132 /* At this point we know the drops were already processed without a need for
133 the mutex. The length is acquiring memory released in
134 row_drop_tables_for_mysql_in_background on UT_LIST_REMOVE, which is after
135 the drop processing is done. */
136 }
137 #endif /* UNIV_DEBUG */
138
139 /** Delays an INSERT, DELETE or UPDATE operation if the purge is lagging. */
140 static void row_mysql_delay_if_needed(void) {
141 if (srv_dml_needed_delay) {
142 std::this_thread::sleep_for(
143 std::chrono::microseconds(srv_dml_needed_delay));
144 }
145 }
146
147 void row_mysql_prebuilt_free_blob_heap(row_prebuilt_t *prebuilt) {
148 DBUG_TRACE;
149
150 DBUG_PRINT("row_mysql_prebuilt_free_blob_heap",
151 ("blob_heap freeing: %p", prebuilt->blob_heap));
152
153 mem_heap_free(prebuilt->blob_heap);
154 prebuilt->blob_heap = nullptr;
155 }
156
157 /** Stores a >= 5.0.3 format true VARCHAR length to dest, in the MySQL row
158 format.
159 @return pointer to the data, we skip the 1 or 2 bytes at the start
160 that are used to store the len */
161 byte *row_mysql_store_true_var_len(
162 byte *dest, /*!< in: where to store */
163 ulint len, /*!< in: length, must fit in two bytes */
164 ulint lenlen) /*!< in: storage length of len: either 1 or 2 bytes */
165 {
166 if (lenlen == 2) {
167 ut_a(len < 256 * 256);
168
169 mach_write_to_2_little_endian(dest, len);
170
171 return (dest + 2);
172 }
173
174 ut_a(lenlen == 1);
175 ut_a(len < 256);
176
177 mach_write_to_1(dest, len);
178
179 return (dest + 1);
180 }
181
182 /** Reads a >= 5.0.3 format true VARCHAR length, in the MySQL row format, and
183 returns a pointer to the data.
184 @return pointer to the data, we skip the 1 or 2 bytes at the start
185 that are used to store the len */
186 const byte *row_mysql_read_true_varchar(
187 ulint *len, /*!< out: variable-length field length */
188 const byte *field, /*!< in: field in the MySQL format */
189 ulint lenlen) /*!< in: storage length of len: either 1
190 or 2 bytes */
191 {
192 if (lenlen == 2) {
193 *len = mach_read_from_2_little_endian(field);
194
195 return (field + 2);
196 }
197
198 ut_a(lenlen == 1);
199
200 *len = mach_read_from_1(field);
201
202 return (field + 1);
203 }
204
205 /** Stores a reference to a BLOB in the MySQL format.
206 @param[in] dest Where to store
207 @param[in,out] col_len Dest buffer size: determines into how many bytes the blob
208 length is stored, the space for the length may vary from 1 to 4 bytes
209 @param[in] data Blob data; if the value to store is sql null this should be null
210 pointer
211 @param[in] len Blob length; if the value to store is sql null this should be 0;
212 remember also to set the null bit in the mysql record header! */
213 void row_mysql_store_blob_ref(byte *dest, ulint col_len, const void *data,
214 ulint len) {
215 /* MySQL might assume the field is set to zero except the length and
216 the pointer fields */
217
218 memset(dest, '\0', col_len);
219
220 /* In dest there are 1 - 4 bytes reserved for the BLOB length,
221 and after that 8 bytes reserved for the pointer to the data.
222 In 32-bit architectures we only use the first 4 bytes of the pointer
223 slot. */
224
225 ut_a(col_len - 8 > 1 || len < 256);
226 ut_a(col_len - 8 > 2 || len < 256 * 256);
227 ut_a(col_len - 8 > 3 || len < 256 * 256 * 256);
228
229 mach_write_to_n_little_endian(dest, col_len - 8, len);
230
231 memcpy(dest + col_len - 8, &data, sizeof data);
232 }
233
234 const byte *row_mysql_read_blob_ref(ulint *len, const byte *ref,
235 ulint col_len) {
236 byte *data;
237
238 *len = mach_read_from_n_little_endian(ref, col_len - 8);
239
240 memcpy(&data, ref + col_len - 8, sizeof data);
241
242 return (data);
243 }
244
245 /** Converting InnoDB geometry data format to MySQL data format. */
246 void row_mysql_store_geometry(
247 byte *dest, /*!< in/out: where to store */
248 ulint dest_len, /*!< in: dest buffer size: determines
249 into how many bytes the GEOMETRY length
250 is stored, the space for the length
251 may vary from 1 to 4 bytes */
252 const byte *src, /*!< in: GEOMETRY data; if the value to
253 store is SQL NULL this should be NULL
254 pointer */
255 ulint src_len) /*!< in: GEOMETRY length; if the value
256 to store is SQL NULL this should be 0;
257 remember also to set the NULL bit in
258 the MySQL record header! */
259 {
260 /* MySQL might assume the field is set to zero except the length and
261 the pointer fields */
262 UNIV_MEM_ASSERT_RW(src, src_len);
263 UNIV_MEM_ASSERT_W(dest, dest_len);
264 UNIV_MEM_INVALID(dest, dest_len);
265
266 memset(dest, '\0', dest_len);
267
268 /* In dest there are 1 - 4 bytes reserved for the BLOB length,
269 and after that 8 bytes reserved for the pointer to the data.
270 In 32-bit architectures we only use the first 4 bytes of the pointer
271 slot. */
272
273 ut_ad(dest_len - 8 > 1 || src_len < 1 << 8);
274 ut_ad(dest_len - 8 > 2 || src_len < 1 << 16);
275 ut_ad(dest_len - 8 > 3 || src_len < 1 << 24);
276
277 mach_write_to_n_little_endian(dest, dest_len - 8, src_len);
278
279 memcpy(dest + dest_len - 8, &src, sizeof src);
280
281 DBUG_EXECUTE_IF("row_print_geometry_data", {
282 String res;
283 Geometry_buffer buffer;
284 String wkt;
285
286 /** Show the meaning of geometry data. */
287 Geometry *g =
288 Geometry::construct(&buffer, (const char *)src, (uint32)src_len);
289
290 if (g) {
291 if (g->as_wkt(&wkt) == 0) {
292 ib::info(ER_IB_MSG_970) << "Write geometry data to"
293 " MySQL WKT format: "
294 << wkt.c_ptr_safe() << ".";
295 }
296 }
297 });
298 }
299
300 /** Read geometry data in the MySQL format.
301 @return pointer to geometry data */
302 static const byte *row_mysql_read_geometry(
303 ulint *len, /*!< out: data length */
304 const byte *ref, /*!< in: geometry data in the
305 MySQL format */
306 ulint col_len) /*!< in: MySQL format length */
307 {
308 byte *data;
309
310 *len = mach_read_from_n_little_endian(ref, col_len - 8);
311
312 memcpy(&data, ref + col_len - 8, sizeof data);
313
314 DBUG_EXECUTE_IF("row_print_geometry_data", {
315 String res;
316 Geometry_buffer buffer;
317 String wkt;
318
319 /** Show the meaning of geometry data. */
320 Geometry *g =
321 Geometry::construct(&buffer, (const char *)data, (uint32)*len);
322
323 if (g) {
324 if (g->as_wkt(&wkt) == 0) {
325 ib::info(ER_IB_MSG_971) << "Read geometry data in"
326 " MySQL's WKT format: "
327 << wkt.c_ptr_safe() << ".";
328 }
329 }
330 });
331
332 return (data);
333 }
334
335 /** Pad a column with spaces.
336 @param[in] mbminlen Minimum size of a character, in bytes
337 @param[out] pad Padded buffer
338 @param[in] len Number of bytes to pad */
339 void row_mysql_pad_col(ulint mbminlen, byte *pad, ulint len) {
340 const byte *pad_end;
341
342 switch (UNIV_EXPECT(mbminlen, 1)) {
343 default:
344 ut_error;
345 case 1:
346 /* space=0x20 */
347 memset(pad, 0x20, len);
348 break;
349 case 2:
350 /* space=0x0020 */
351 pad_end = pad + len;
352 ut_a(!(len % 2));
353 while (pad < pad_end) {
354 *pad++ = 0x00;
355 *pad++ = 0x20;
356 };
357 break;
358 case 4:
359 /* space=0x00000020 */
360 pad_end = pad + len;
361 ut_a(!(len % 4));
362 while (pad < pad_end) {
363 *pad++ = 0x00;
364 *pad++ = 0x00;
365 *pad++ = 0x00;
366 *pad++ = 0x20;
367 }
368 break;
369 }
370 }
371
372 /** Stores a non-SQL-NULL field given in the MySQL format in the InnoDB format.
373 The counterpart of this function is row_sel_field_store_in_mysql_format() in
374 row0sel.cc.
375 @return up to which byte we used buf in the conversion */
376 byte *row_mysql_store_col_in_innobase_format(
377 dfield_t *dfield, /*!< in/out: dfield where dtype
378 information must be already set when
379 this function is called! */
380 byte *buf, /*!< in/out: buffer for a converted
381 integer value; this must be at least
382 col_len long then! NOTE that dfield
383 may also get a pointer to 'buf',
384 therefore do not discard this as long
385 as dfield is used! */
386 bool row_format_col, /*!< true if the mysql_data is from
387 a MySQL row, false if from a MySQL
388 key value;
389 in MySQL, a true VARCHAR storage
390 format differs in a row and in a
391 key value: in a key value the length
392 is always stored in 2 bytes! */
393 const byte *mysql_data, /*!< in: MySQL column value, not
394 SQL NULL; NOTE that dfield may also
395 get a pointer to mysql_data,
396 therefore do not discard this as long
397 as dfield is used! */
398 ulint col_len, /*!< in: MySQL column length; NOTE that
399 this is the storage length of the
400 column in the MySQL format row, not
401 necessarily the length of the actual
402 payload data; if the column is a true
403 VARCHAR then this is irrelevant */
404 ulint comp) /*!< in: nonzero=compact format */
405 {
406 const byte *ptr = mysql_data;
407 const dtype_t *dtype;
408 ulint type;
409 ulint lenlen;
410
411 dtype = dfield_get_type(dfield);
412
413 type = dtype->mtype;
414
415 if (type == DATA_INT) {
416 /* Store integer data in Innobase in a big-endian format,
417 sign bit negated if the data is a signed integer. In MySQL,
418 integers are stored in a little-endian format. */
419
420 byte *p = buf + col_len;
421
422 for (;;) {
423 p--;
424 *p = *mysql_data;
425 if (p == buf) {
426 break;
427 }
428 mysql_data++;
429 }
430
431 if (!(dtype->prtype & DATA_UNSIGNED)) {
432 *buf ^= 128;
433 }
434
435 ptr = buf;
436 buf += col_len;
437 } else if ((type == DATA_VARCHAR || type == DATA_VARMYSQL ||
438 type == DATA_BINARY)) {
439 if (dtype_get_mysql_type(dtype) == DATA_MYSQL_TRUE_VARCHAR) {
440 /* The length of the actual data is stored to 1 or 2
441 bytes at the start of the field */
442
443 if (row_format_col) {
444 if (dtype->prtype & DATA_LONG_TRUE_VARCHAR) {
445 lenlen = 2;
446 } else {
447 lenlen = 1;
448 }
449 } else {
450 /* In a MySQL key value, lenlen is always 2 */
451 lenlen = 2;
452 }
453
454 ptr = row_mysql_read_true_varchar(&col_len, mysql_data, lenlen);
455 } else {
456 /* Remove trailing spaces from old style VARCHAR
457 columns. */
458
459 /* Handle Unicode strings differently. */
460 ulint mbminlen = dtype_get_mbminlen(dtype);
461
462 ptr = mysql_data;
463
464 switch (mbminlen) {
465 default:
466 ut_error;
467 case 4:
468 /* space=0x00000020 */
469 /* Trim "half-chars", just in case. */
470 col_len &= ~3;
471
472 while (col_len >= 4 && ptr[col_len - 4] == 0x00 &&
473 ptr[col_len - 3] == 0x00 && ptr[col_len - 2] == 0x00 &&
474 ptr[col_len - 1] == 0x20) {
475 col_len -= 4;
476 }
477 break;
478 case 2:
479 /* space=0x0020 */
480 /* Trim "half-chars", just in case. */
481 col_len &= ~1;
482
483 while (col_len >= 2 && ptr[col_len - 2] == 0x00 &&
484 ptr[col_len - 1] == 0x20) {
485 col_len -= 2;
486 }
487 break;
488 case 1:
489 /* space=0x20 */
490 while (col_len > 0 && ptr[col_len - 1] == 0x20) {
491 col_len--;
492 }
493 }
494 }
495 } else if (comp && type == DATA_MYSQL && dtype_get_mbminlen(dtype) == 1 &&
496 dtype_get_mbmaxlen(dtype) > 1) {
497 /* In some cases we strip trailing spaces from UTF-8 and other
498 multibyte charsets, from FIXED-length CHAR columns, to save
499 space. UTF-8 would otherwise normally use 3 * the string length
500 bytes to store an ASCII string! */
501
502 /* We assume that this CHAR field is encoded in a
503 variable-length character set where spaces have
504 1:1 correspondence to 0x20 bytes, such as UTF-8.
505
506 Consider a CHAR(n) field, a field of n characters.
507 It will contain between n * mbminlen and n * mbmaxlen bytes.
508 We will try to truncate it to n bytes by stripping
509 space padding. If the field contains single-byte
510 characters only, it will be truncated to n characters.
511 Consider a CHAR(5) field containing the string
512 ".a " where "." denotes a 3-byte character represented
513 by the bytes "$%&". After our stripping, the string will
514 be stored as "$%&a " (5 bytes). The string
515 ".abc " will be stored as "$%&abc" (6 bytes).
516
517 The space padding will be restored in row0sel.cc, function
518 row_sel_field_store_in_mysql_format(). */
519
520 ulint n_chars;
521
522 ut_a(!(dtype_get_len(dtype) % dtype_get_mbmaxlen(dtype)));
523
524 n_chars = dtype_get_len(dtype) / dtype_get_mbmaxlen(dtype);
525
526 /* Strip space padding. */
527 while (col_len > n_chars && ptr[col_len - 1] == 0x20) {
528 col_len--;
529 }
530 } else if (!row_format_col) {
531 /* if mysql data is from a MySQL key value
532 since the length is always stored in 2 bytes,
533 we need do nothing here. */
534 } else if (type == DATA_BLOB) {
535 ptr = row_mysql_read_blob_ref(&col_len, mysql_data, col_len);
536 } else if (DATA_GEOMETRY_MTYPE(type)) {
537 /* We use blob to store geometry data except DATA_POINT
538 internally, but in MySQL Layer the datatype is always blob. */
539 ptr = row_mysql_read_geometry(&col_len, mysql_data, col_len);
540 }
541
542 dfield_set_data(dfield, ptr, col_len);
543
544 return (buf);
545 }
546
547 /** Convert a row in the MySQL format to a row in the Innobase format. Note that
548 the function to convert a MySQL format key value to an InnoDB dtuple is
549 row_sel_convert_mysql_key_to_innobase() in row0sel.cc. */
550 static void row_mysql_convert_row_to_innobase(
551 dtuple_t *row, /*!< in/out: Innobase row where the
552 field type information is already
553 copied there! */
554 row_prebuilt_t *prebuilt, /*!< in: prebuilt struct where template
555 must be of type ROW_MYSQL_WHOLE_ROW */
556 const byte *mysql_rec, /*!< in: row in the MySQL format;
557 NOTE: do not discard as long as
558 row is used, as row may contain
559 pointers to this record! */
560 mem_heap_t **heap) /*!< in: heap will be used to duplicate
561 multi_value & blob data */
562 {
563 const mysql_row_templ_t *templ;
564 dfield_t *dfield;
565 ulint i;
566 ulint n_col = 0;
567 ulint n_v_col = 0;
568 ulint n_m_v_col = 0;
569
570 ut_ad(prebuilt->template_type == ROW_MYSQL_WHOLE_ROW);
571 ut_ad(prebuilt->mysql_template);
572
573 for (i = 0; i < prebuilt->n_template; i++) {
574 bool is_multi_val = false;
575
576 templ = prebuilt->mysql_template + i;
577
578 if (templ->is_virtual) {
579 ut_ad(n_v_col < dtuple_get_n_v_fields(row));
580 dfield = dtuple_get_nth_v_field(row, n_v_col);
581 n_v_col++;
582 if (dfield_is_multi_value(dfield)) {
583 is_multi_val = true;
584 n_m_v_col++;
585 }
586 } else {
587 dfield = dtuple_get_nth_field(row, n_col);
588 n_col++;
589 }
590
591 if (templ->mysql_null_bit_mask != 0) {
592 /* Column may be SQL NULL */
593
594 if (mysql_rec[templ->mysql_null_byte_offset] &
595 (byte)(templ->mysql_null_bit_mask)) {
596 /* It is SQL NULL */
597
598 dfield_set_null(dfield);
599
600 continue;
601 }
602 }
603
604 if (is_multi_val) {
605 dict_v_col_t *v_col =
606 dict_table_get_nth_v_col(prebuilt->table, n_v_col - 1);
607
608 innobase_get_multi_value(prebuilt->m_mysql_table, v_col->m_col.ind,
609 dfield, &prebuilt->mv_data[n_m_v_col - 1], 0,
610 dict_table_is_comp(prebuilt->table),
611 prebuilt->heap);
612 /* For multi-value data, the deep copy may cost too much.
613 So ideally this should be optimized by keeping and reading the
614 raw data. However, once more virtual column data needs to be
615 calculated later, for example, insert by modify, server will
616 overwrites the memory used here. So the safest way is a deep
617 copy. */
618 if (*heap == nullptr) {
619 *heap = mem_heap_create(128, UT_LOCATION_HERE);
620 }
621 dfield_multi_value_dup(dfield, *heap);
622 } else {
623 row_mysql_store_col_in_innobase_format(
624 dfield, prebuilt->ins_upd_rec_buff + templ->mysql_col_offset,
625 true, /* MySQL row format data */
626 mysql_rec + templ->mysql_col_offset, templ->mysql_col_len,
627 dict_table_is_comp(prebuilt->table));
628
629 /* server has issue regarding handling BLOB virtual fields,
630 and we need to duplicate it with our own memory here */
631 if (templ->is_virtual &&
632 DATA_LARGE_MTYPE(dfield_get_type(dfield)->mtype)) {
633 if (*heap == nullptr) {
634 *heap = mem_heap_create(dfield->len, UT_LOCATION_HERE);
635 }
636 dfield_dup(dfield, *heap);
637 }
638 }
639 }
640
641 /* If there is a FTS doc id column and it is not user supplied (
642 generated by server) then assign it a new doc id. */
643 if (prebuilt->table->fts) {
644 ut_a(prebuilt->table->fts->doc_col != ULINT_UNDEFINED);
645
646 fts_create_doc_id(prebuilt->table, row, prebuilt->heap);
647 }
648 }
649
650 /** Handles user errors and lock waits detected by the database engine.
651 @return true if it was a lock wait and we should continue running the
652 query thread and in that case the thr is ALREADY in the running state. */
653 bool row_mysql_handle_errors(
654 dberr_t *new_err, /*!< out: possible new error encountered in
655 lock wait, or if no new error, the value
656 of trx->error_state at the entry of this
657 function */
658 trx_t *trx, /*!< in: transaction */
659 que_thr_t *thr, /*!< in: query thread, or NULL */
660 trx_savept_t *savept) /*!< in: savepoint, or NULL */
661 {
662 dberr_t err;
663
664 handle_new_error:
665 err = trx->error_state;
666
667 ut_a(err != DB_SUCCESS);
668
669 trx->error_state = DB_SUCCESS;
670
671 switch (err) {
672 case DB_LOCK_WAIT_TIMEOUT:
673 if (row_rollback_on_timeout) {
674 trx_rollback_to_savepoint(trx, nullptr);
675 break;
676 }
677 [[fallthrough]];
678 case DB_DUPLICATE_KEY:
679 case DB_FOREIGN_DUPLICATE_KEY:
680 case DB_TOO_BIG_RECORD:
681 case DB_UNDO_RECORD_TOO_BIG:
682 case DB_ROW_IS_REFERENCED:
683 case DB_NO_REFERENCED_ROW:
684 case DB_CANNOT_ADD_CONSTRAINT:
685 case DB_TOO_MANY_CONCURRENT_TRXS:
686 case DB_OUT_OF_FILE_SPACE:
687 case DB_READ_ONLY:
688 case DB_FTS_INVALID_DOCID:
689 case DB_INTERRUPTED:
690 case DB_CANT_CREATE_GEOMETRY_OBJECT:
691 case DB_COMPUTE_VALUE_FAILED:
692 case DB_LOCK_NOWAIT:
693 case DB_BTREE_LEVEL_LIMIT_EXCEEDED:
694 DBUG_EXECUTE_IF("row_mysql_crash_if_error", {
695 log_buffer_flush_to_disk();
696 DBUG_SUICIDE();
697 });
698 if (savept) {
699 /* Roll back the latest, possibly incomplete insertion
700 or update */
701
702 trx_rollback_to_savepoint(trx, savept);
703 }
704 /* MySQL will roll back the latest SQL statement */
705 break;
706 case DB_LOCK_WAIT:
707
708 trx_kill_blocking(trx);
709 DEBUG_SYNC_C("before_lock_wait_suspend");
710
711 lock_wait_suspend_thread(thr);
712
713 if (trx->error_state != DB_SUCCESS) {
714 que_thr_stop_for_mysql(thr);
715
716 goto handle_new_error;
717 }
718
719 *new_err = err;
720
721 return (true);
722
723 case DB_DEADLOCK:
724 case DB_LOCK_TABLE_FULL:
725 /* Roll back the whole transaction; this resolution was added
726 to version 3.23.43 */
727
728 trx_rollback_to_savepoint(trx, nullptr);
729 break;
730
731 case DB_MUST_GET_MORE_FILE_SPACE:
732 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_972)
733 << "The database cannot continue operation because"
734 " of lack of space. You must add a new data file"
735 " to my.cnf and restart the database.";
736 break;
737
738 case DB_CORRUPTION:
739 ib::error(ER_IB_MSG_973)
740 << "We detected index corruption in an InnoDB type"
741 " table. You have to dump + drop + reimport the"
742 " table or, in a case of widespread corruption,"
743 " dump all InnoDB tables and recreate the whole"
744 " tablespace. If the mysqld server crashes after"
745 " the startup or when you dump the tables. "
746 << FORCE_RECOVERY_MSG;
747 break;
748 case DB_FOREIGN_EXCEED_MAX_CASCADE:
749 ib::error(ER_IB_MSG_974)
750 << "Cannot delete/update rows with cascading"
751 " foreign key constraints that exceed max depth of "
752 << FK_MAX_CASCADE_DEL
753 << ". Please drop excessive"
754 " foreign constraints and try again";
755 break;
756 default:
757 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_975)
758 << "Unknown error code " << err << ": " << ut_strerr(err);
759 }
760
761 if (trx->error_state != DB_SUCCESS) {
762 *new_err = trx->error_state;
763 } else {
764 *new_err = err;
765 }
766
767 trx->error_state = DB_SUCCESS;
768
769 return (false);
770 }
771
772 /* Maximum size of the buffer needed for conversion of INTs from
773 little endian format to big endian format in an index. An index
774 can have maximum 16 columns (MAX_REF_PARTS) in it. Therefore
775 Max size for PK: 16 * 8 bytes (BIGINT's size) = 128 bytes
776 Max size Secondary index: 16 * 8 bytes + PK = 256 bytes. */
777 constexpr uint32_t MAX_SRCH_KEY_VAL_BUFFER = 2 * 8 * MAX_REF_PARTS;
778
779 /** Create a prebuilt struct for a MySQL table handle.
780 @return own: a prebuilt struct */
781 row_prebuilt_t *row_create_prebuilt(
782 dict_table_t *table, /*!< in: Innobase table handle */
783 ulint mysql_row_len) /*!< in: length in bytes of a row in
784 the MySQL format */
785 {
786 DBUG_TRACE;
787
788 row_prebuilt_t *prebuilt;
789 mem_heap_t *heap;
790 dict_index_t *clust_index;
791 dict_index_t *temp_index;
792 dtuple_t *ref;
793 ulint ref_len;
794 uint srch_key_len = 0;
795 ulint search_tuple_n_fields;
796
797 search_tuple_n_fields =
798 2 * (table->get_n_cols() + dict_table_get_n_v_cols(table));
799
800 clust_index = table->first_index();
801
802 /* Make sure that search_tuple is long enough for clustered index */
803 ut_a(2 * table->get_n_cols() >= clust_index->n_fields);
804
805 ref_len = dict_index_get_n_unique(clust_index);
806
807 #define PREBUILT_HEAP_INITIAL_SIZE \
808 (sizeof(*prebuilt) /* allocd in this function */ \
809 + DTUPLE_EST_ALLOC(search_tuple_n_fields) /* search_tuple */ \
810 + DTUPLE_EST_ALLOC(search_tuple_n_fields) /* m_stop_tuple */ \
811 + DTUPLE_EST_ALLOC(ref_len) /* allocd in row_prebuild_sel_graph() */ \
812 + sizeof(sel_node_t) + sizeof(que_fork_t) + \
813 sizeof(que_thr_t) /* allocd in row_get_prebuilt_update_vector() */ \
814 + sizeof(upd_node_t) + sizeof(upd_t) + \
815 sizeof(upd_field_t) * table->get_n_cols() + sizeof(que_fork_t) + \
816 sizeof(que_thr_t) /* allocd in row_get_prebuilt_insert_row() */ \
817 + sizeof(ins_node_t) /* mysql_row_len could be huge and we are not \
818 sure if this prebuilt instance is going to be \
819 used in inserts */ \
820 + (mysql_row_len < 256 ? mysql_row_len : 0) + \
821 DTUPLE_EST_ALLOC(table->get_n_cols() + dict_table_get_n_v_cols(table)) + \
822 sizeof(que_fork_t) + sizeof(que_thr_t) + sizeof(*prebuilt->pcur) + \
823 sizeof(*prebuilt->clust_pcur))
824
825 /* Calculate size of key buffer used to store search key in
826 InnoDB format. MySQL stores INTs in little endian format and
827 InnoDB stores INTs in big endian format with the sign bit
828 flipped. All other field types are stored/compared the same
829 in MySQL and InnoDB, so we must create a buffer containing
830 the INT key parts in InnoDB format.We need two such buffers
831 since both start and end keys are used in records_in_range(). */
832
833 for (temp_index = table->first_index(); temp_index;
834 temp_index = temp_index->next()) {
835 DBUG_EXECUTE_IF("innodb_srch_key_buffer_max_value",
836 ut_a(temp_index->n_user_defined_cols == MAX_REF_PARTS););
837 uint temp_len = 0;
838 for (uint i = 0; i < temp_index->n_uniq; i++) {
839 ulint type = temp_index->fields[i].col->mtype;
840 if (type == DATA_INT) {
841 temp_len += temp_index->fields[i].fixed_len;
842 }
843 }
844 srch_key_len = std::max(srch_key_len, temp_len);
845 }
846
847 ut_a(srch_key_len <= MAX_SRCH_KEY_VAL_BUFFER);
848
849 DBUG_EXECUTE_IF("innodb_srch_key_buffer_max_value",
850 ut_a(srch_key_len == MAX_SRCH_KEY_VAL_BUFFER););
851
852 /* We allocate enough space for the objects that are likely to
853 be created later in order to minimize the number of malloc()
854 calls */
855 heap = mem_heap_create(PREBUILT_HEAP_INITIAL_SIZE + 2 * srch_key_len,
856 UT_LOCATION_HERE);
857
858 prebuilt =
859 static_cast<row_prebuilt_t *>(mem_heap_zalloc(heap, sizeof(*prebuilt)));
860
861 prebuilt->magic_n = ROW_PREBUILT_ALLOCATED;
862 prebuilt->magic_n2 = ROW_PREBUILT_ALLOCATED;
863
864 prebuilt->table = table;
865
866 prebuilt->sql_stat_start = true;
867 prebuilt->heap = heap;
868
869 prebuilt->srch_key_val_len = srch_key_len;
870 if (prebuilt->srch_key_val_len) {
871 prebuilt->srch_key_val1 = static_cast<byte *>(
872 mem_heap_alloc(prebuilt->heap, 2 * prebuilt->srch_key_val_len));
873 prebuilt->srch_key_val2 =
874 prebuilt->srch_key_val1 + prebuilt->srch_key_val_len;
875 } else {
876 prebuilt->srch_key_val1 = nullptr;
877 prebuilt->srch_key_val2 = nullptr;
878 }
879
880 prebuilt->pcur = static_cast<btr_pcur_t *>(
881 mem_heap_zalloc(prebuilt->heap, sizeof(btr_pcur_t)));
882 prebuilt->clust_pcur = static_cast<btr_pcur_t *>(
883 mem_heap_zalloc(prebuilt->heap, sizeof(btr_pcur_t)));
884 prebuilt->pcur->reset();
885 prebuilt->clust_pcur->reset();
886
887 prebuilt->select_lock_type = LOCK_NONE;
888 prebuilt->select_mode = SELECT_ORDINARY;
889
890 prebuilt->search_tuple = dtuple_create(heap, search_tuple_n_fields);
891 prebuilt->m_stop_tuple = dtuple_create(heap, search_tuple_n_fields);
892 ut_ad(!prebuilt->m_stop_tuple_found);
893 ut_ad(!prebuilt->is_reading_range());
894
895 ref = dtuple_create(heap, ref_len);
896
897 dict_index_copy_types(ref, clust_index, ref_len);
898
899 prebuilt->clust_ref = ref;
900
901 prebuilt->autoinc_error = DB_SUCCESS;
902 prebuilt->autoinc_offset = 0;
903
904 /* Default to 1, we will set the actual value later in
905 ha_innobase::get_auto_increment(). */
906 prebuilt->autoinc_increment = 1;
907
908 prebuilt->autoinc_last_value = 0;
909
910 /* During UPDATE and DELETE we need the doc id. */
911 prebuilt->fts_doc_id = 0;
912
913 prebuilt->mysql_row_len = mysql_row_len;
914
915 prebuilt->ins_sel_stmt = false;
916 prebuilt->session = nullptr;
917
918 prebuilt->fts_doc_id_in_read_set = false;
919 prebuilt->blob_heap = nullptr;
920
921 prebuilt->no_read_locking = false;
922 prebuilt->no_autoinc_locking = false;
923
924 prebuilt->m_no_prefetch = false;
925 prebuilt->m_read_virtual_key = false;
926
927 return prebuilt;
928 }
929
930 /** Free a prebuilt struct for a MySQL table handle.
931 @param[in,out] prebuilt Prebuilt struct
932 @param[in] dict_locked True=data dictionary locked */
933 void row_prebuilt_free(row_prebuilt_t *prebuilt, bool dict_locked) {
934 DBUG_TRACE;
935
936 ut_a(prebuilt->magic_n == ROW_PREBUILT_ALLOCATED);
937 ut_a(prebuilt->magic_n2 == ROW_PREBUILT_ALLOCATED);
938
939 prebuilt->magic_n = ROW_PREBUILT_FREED;
940 prebuilt->magic_n2 = ROW_PREBUILT_FREED;
941
942 /* It is better to fail here on assertion, than to let the destructor of the
943 active row_is_reading_range_guard_t modify some random place in memory. */
944 ut_a(!prebuilt->is_reading_range());
945
946 prebuilt->pcur->reset();
947 prebuilt->clust_pcur->reset();
948
949 ut::free(prebuilt->mysql_template);
950
951 if (prebuilt->ins_graph) {
952 que_graph_free_recursive(prebuilt->ins_graph);
953 }
954
955 if (prebuilt->sel_graph) {
956 que_graph_free_recursive(prebuilt->sel_graph);
957 }
958
959 if (prebuilt->upd_graph) {
960 que_graph_free_recursive(prebuilt->upd_graph);
961 }
962
963 if (prebuilt->blob_heap) {
964 row_mysql_prebuilt_free_blob_heap(prebuilt);
965 }
966
967 if (prebuilt->old_vers_heap) {
968 mem_heap_free(prebuilt->old_vers_heap);
969 }
970
971 if (prebuilt->fetch_cache[0] != nullptr) {
972 byte *base = prebuilt->fetch_cache[0] - 4;
973 byte *ptr = base;
974
975 for (ulint i = 0; i < MYSQL_FETCH_CACHE_SIZE; i++) {
976 ulint magic1 = mach_read_from_4(ptr);
977 ut_a(magic1 == ROW_PREBUILT_FETCH_MAGIC_N);
978 ptr += 4;
979
980 byte *row = ptr;
981 ut_a(row == prebuilt->fetch_cache[i]);
982 ptr += prebuilt->mysql_row_len;
983
984 ulint magic2 = mach_read_from_4(ptr);
985 ut_a(magic2 == ROW_PREBUILT_FETCH_MAGIC_N);
986 ptr += 4;
987 }
988
989 ut::free(base);
990 }
991
992 if (prebuilt->rtr_info) {
993 rtr_clean_rtr_info(prebuilt->rtr_info, true);
994 }
995
996 if (prebuilt->table) {
997 ut_ad(!prebuilt->table->is_fts_aux());
998 dd_table_close(prebuilt->table, nullptr, nullptr, dict_locked);
999 }
1000
1001 prebuilt->m_lob_undo.destroy();
1002
1003 mem_heap_free(prebuilt->heap);
1004 }
1005
1006 void row_update_prebuilt_trx(row_prebuilt_t *prebuilt, trx_t *trx) {
1007 ut_a(trx->magic_n == TRX_MAGIC_N);
1008 ut_a(prebuilt->magic_n == ROW_PREBUILT_ALLOCATED);
1009 ut_a(prebuilt->magic_n2 == ROW_PREBUILT_ALLOCATED);
1010
1011 prebuilt->trx = trx;
1012
1013 if (prebuilt->ins_graph) {
1014 prebuilt->ins_graph->trx = trx;
1015 }
1016
1017 if (prebuilt->upd_graph) {
1018 prebuilt->upd_graph->trx = trx;
1019 }
1020
1021 if (prebuilt->sel_graph) {
1022 prebuilt->sel_graph->trx = trx;
1023 }
1024 }
1025
1026 /** Gets pointer to a prebuilt dtuple used in insertions. If the insert graph
1027 has not yet been built in the prebuilt struct, then this function first
1028 builds it.
1029 @return prebuilt dtuple; the column type information is also set in it */
1030 static dtuple_t *row_get_prebuilt_insert_row(
1031 row_prebuilt_t *prebuilt) /*!< in: prebuilt struct in MySQL
1032 handle */
1033 {
1034 dict_table_t *table = prebuilt->table;
1035
1036 ut_ad(prebuilt && table && prebuilt->trx);
1037
1038 if (prebuilt->ins_node != nullptr) {
1039 prebuilt->ins_node->ins_multi_val_pos = 0;
1040
1041 /* Check if indexes have been dropped or added and we
1042 may need to rebuild the row insert template. */
1043
1044 if (prebuilt->trx_id == table->def_trx_id &&
1045 UT_LIST_GET_LEN(prebuilt->ins_node->entry_list) ==
1046 UT_LIST_GET_LEN(table->indexes)) {
1047 return (prebuilt->ins_node->row);
1048 }
1049
1050 ut_ad(prebuilt->trx_id < table->def_trx_id);
1051
1052 que_graph_free_recursive(prebuilt->ins_graph);
1053
1054 prebuilt->ins_graph = nullptr;
1055 }
1056
1057 /* Create an insert node and query graph to the prebuilt struct */
1058
1059 ins_node_t *node;
1060
1061 node = ins_node_create(INS_DIRECT, table, prebuilt->heap);
1062
1063 prebuilt->ins_node = node;
1064
1065 if (prebuilt->ins_upd_rec_buff == nullptr) {
1066 prebuilt->ins_upd_rec_buff = static_cast<byte *>(
1067 mem_heap_alloc(prebuilt->heap, prebuilt->mysql_row_len));
1068 }
1069
1070 if (table->n_m_v_cols > 0 && prebuilt->mv_data == nullptr) {
1071 prebuilt->mv_data = static_cast<multi_value_data *>(mem_heap_zalloc(
1072 prebuilt->heap, table->n_m_v_cols * sizeof(*prebuilt->mv_data)));
1073 for (ulint i = 0; i < table->n_m_v_cols; i++) {
1074 prebuilt->mv_data[i].alloc(multi_value_data::s_default_allocate_num,
1075 false, prebuilt->heap);
1076 }
1077 }
1078
1079 /* option 1 : HERE create the insert node as per row version now on disk */
1080 dtuple_t *row;
1081
1082 row = dtuple_create_with_vcol(prebuilt->heap, table->get_n_cols(),
1083 dict_table_get_n_v_cols(table));
1084
1085 dict_table_copy_types(row, table);
1086
1087 ins_node_set_new_row(node, row);
1088
1089 prebuilt->ins_graph = static_cast<que_fork_t *>(
1090 que_node_get_parent(pars_complete_graph_for_exec(
1091 node, prebuilt->trx, prebuilt->heap, prebuilt)));
1092
1093 prebuilt->ins_graph->state = QUE_FORK_ACTIVE;
1094
1095 prebuilt->trx_id = table->def_trx_id;
1096
1097 return (prebuilt->ins_node->row);
1098 }
1099
1100 /** Updates the table modification counter and calculates new estimates
1101 for table and index statistics if necessary. */
1102 static inline void row_update_statistics_if_needed(
1103 dict_table_t *table) /*!< in: table */
1104 {
1105 uint64_t counter;
1106 uint64_t n_rows;
1107
1108 if (!table->stat_initialized) {
1109 DBUG_EXECUTE_IF("test_upd_stats_if_needed_not_inited",
1110 fprintf(stderr,
1111 "test_upd_stats_if_needed_not_inited"
1112 " was executed\n"););
1113 return;
1114 }
1115
1116 counter = table->stat_modified_counter++;
1117 n_rows = dict_table_get_n_rows(table);
1118
1119 if (dict_stats_is_persistent_enabled(table)) {
1120 if (counter > n_rows / 10 /* 10% */
1121 && dict_stats_auto_recalc_is_enabled(table)) {
1122 dict_stats_recalc_pool_add(table);
1123 table->stat_modified_counter = 0;
1124 }
1125 return;
1126 }
1127
1128 /* Calculate new statistics if 1 / 16 of table has been modified
1129 since the last time a statistics batch was run.
1130 We calculate statistics at most every 16th round, since we may have
1131 a counter table which is very small and updated very often. */
1132
1133 if (counter > 16 + n_rows / 16 /* 6.25% */) {
1134 ut_ad(!dict_sys_mutex_own());
1135 /* this will reset table->stat_modified_counter to 0 */
1136 dict_stats_update(table, DICT_STATS_RECALC_TRANSIENT);
1137 }
1138 }
1139
1140 /** Sets an AUTO_INC type lock on the table mentioned in prebuilt. The
1141 AUTO_INC lock gives exclusive access to the auto-inc counter of the
1142 table. The lock is reserved only for the duration of an SQL statement.
1143 It is not compatible with another AUTO_INC or exclusive lock on the
1144 table.
1145 @return error code or DB_SUCCESS */
1146 dberr_t row_lock_table_autoinc_for_mysql(
1147 row_prebuilt_t *prebuilt) /*!< in: prebuilt struct in the MySQL
1148 table handle */
1149 {
1150 trx_t *trx = prebuilt->trx;
1151 ins_node_t *node = prebuilt->ins_node;
1152 const dict_table_t *table = prebuilt->table;
1153 que_thr_t *thr;
1154 dberr_t err;
1155
1156 /* If we already hold an AUTOINC lock on the table then do nothing.
1157 Note: We peek at the value of the current owner without acquiring any latch,
1158 which is OK, because if the equality holds, it means we were granted the lock,
1159 and the only way table->autoinc_trx can subsequently change is by releasing
1160 the lock, which can not happen concurrently with the thread running the trx.*/
1161 ut_ad(trx_can_be_handled_by_current_thread(trx));
1162 if (trx == table->autoinc_trx) {
1163 return (DB_SUCCESS);
1164 }
1165
1166 trx->op_info = "setting auto-inc lock";
1167
1168 row_get_prebuilt_insert_row(prebuilt);
1169 node = prebuilt->ins_node;
1170
1171 /* We use the insert query graph as the dummy graph needed
1172 in the lock module call */
1173
1174 thr = que_fork_get_first_thr(prebuilt->ins_graph);
1175
1176 que_thr_move_to_run_state_for_mysql(thr, trx);
1177
1178 run_again:
1179 thr->run_node = node;
1180 thr->prev_node = node;
1181
1182 /* It may be that the current session has not yet started
1183 its transaction, or it has been committed: */
1184
1185 trx_start_if_not_started_xa(trx, true, UT_LOCATION_HERE);
1186
1187 err = lock_table(0, prebuilt->table, LOCK_AUTO_INC, thr);
1188
1189 trx->error_state = err;
1190
1191 if (err != DB_SUCCESS) {
1192 que_thr_stop_for_mysql(thr);
1193
1194 auto was_lock_wait = row_mysql_handle_errors(&err, trx, thr, nullptr);
1195
1196 if (was_lock_wait) {
1197 goto run_again;
1198 }
1199
1200 trx->op_info = "";
1201
1202 return (err);
1203 }
1204
1205 que_thr_stop_for_mysql_no_error(thr, trx);
1206
1207 trx->op_info = "";
1208
1209 return (err);
1210 }
1211
1212 /** Sets a table lock on the table mentioned in prebuilt.
1213 @param[in,out] prebuilt table handle
1214 @return error code or DB_SUCCESS */
1215 dberr_t row_lock_table(row_prebuilt_t *prebuilt) {
1216 trx_t *trx = prebuilt->trx;
1217 que_thr_t *thr;
1218 dberr_t err;
1219
1220 trx->op_info = "setting table lock";
1221
1222 if (prebuilt->sel_graph == nullptr) {
1223 /* Build a dummy select query graph */
1224 row_prebuild_sel_graph(prebuilt);
1225 }
1226
1227 /* We use the select query graph as the dummy graph needed
1228 in the lock module call */
1229
1230 thr = que_fork_get_first_thr(prebuilt->sel_graph);
1231
1232 que_thr_move_to_run_state_for_mysql(thr, trx);
1233
1234 run_again:
1235 thr->run_node = thr;
1236 thr->prev_node = thr->common.parent;
1237
1238 /* It may be that the current session has not yet started
1239 its transaction, or it has been committed: */
1240
1241 trx_start_if_not_started_xa(trx, false, UT_LOCATION_HERE);
1242
1243 err =
1244 lock_table(0, prebuilt->table,
1245 static_cast<enum lock_mode>(prebuilt->select_lock_type), thr);
1246
1247 trx->error_state = err;
1248
1249 if (err != DB_SUCCESS) {
1250 que_thr_stop_for_mysql(thr);
1251
1252 auto was_lock_wait = row_mysql_handle_errors(&err, trx, thr, nullptr);
1253
1254 if (was_lock_wait) {
1255 goto run_again;
1256 }
1257
1258 trx->op_info = "";
1259
1260 return (err);
1261 }
1262
1263 que_thr_stop_for_mysql_no_error(thr, trx);
1264
1265 trx->op_info = "";
1266
1267 return (err);
1268 }
1269
1270 /** Perform explicit rollback in absence of UNDO logs.
1271 @param[in] index Apply rollback action on this index
1272 @param[in] entry Entry to remove/rollback.
1273 @param[in,out] thr Thread handler.
1274 @param[in,out] mtr Mini-transaction.
1275 @return error code or DB_SUCCESS */
1276 static dberr_t row_explicit_rollback(dict_index_t *index, const dtuple_t *entry,
1277 que_thr_t *thr, mtr_t *mtr) {
1278 btr_cur_t cursor;
1279 ulint flags;
1280 ulint offsets_[REC_OFFS_NORMAL_SIZE];
1281 ulint *offsets;
1282 mem_heap_t *heap = nullptr;
1283 dberr_t err;
1284
1285 rec_offs_init(offsets_);
1286 flags = BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG;
1287
1288 btr_cur_search_to_nth_level_with_no_latch(index, 0, entry, PAGE_CUR_LE,
1289 &cursor, __FILE__, __LINE__, mtr);
1290
1291 offsets = rec_get_offsets(btr_cur_get_rec(&cursor), index, offsets_,
1292 ULINT_UNDEFINED, UT_LOCATION_HERE, &heap);
1293
1294 if (index->is_clustered()) {
1295 err = btr_cur_del_mark_set_clust_rec(flags, btr_cur_get_block(&cursor),
1296 btr_cur_get_rec(&cursor), index,
1297 offsets, thr, entry, mtr);
1298 } else {
1299 err = btr_cur_del_mark_set_sec_rec(flags, &cursor, true, thr, mtr);
1300 }
1301 ut_ad(err == DB_SUCCESS);
1302
1303 /* Void call just to set mtr modification flag
1304 to true failing which block is not scheduled for flush*/
1305 byte *log_ptr = nullptr;
1306 if (mlog_open(mtr, 0, log_ptr)) {
1307 ut_d(ut_error);
1308 ut_o(mlog_close(mtr, log_ptr));
1309 }
1310
1311 if (heap != nullptr) {
1312 mem_heap_free(heap);
1313 }
1314
1315 return (err);
1316 }
1317
1318 /** Convert a row in the MySQL format to a row in the Innobase format.
1319 This is specialized function used for intrinsic table with reduce branching.
1320 @param[in,out] row row where field values are copied.
1321 @param[in] prebuilt prebuilt handler
1322 @param[in] mysql_rec row in mysql format. */
1323 static void row_mysql_to_innobase(dtuple_t *row, row_prebuilt_t *prebuilt,
1324 const byte *mysql_rec) {
1325 ut_ad(prebuilt->table->is_intrinsic());
1326
1327 const byte *ptr = mysql_rec;
1328
1329 for (ulint i = 0; i < prebuilt->n_template; i++) {
1330 const mysql_row_templ_t *templ;
1331 dfield_t *dfield;
1332
1333 templ = prebuilt->mysql_template + i;
1334 dfield = dtuple_get_nth_field(row, i);
1335
1336 /* Check if column has null value. */
1337 if (templ->mysql_null_bit_mask != 0) {
1338 if (mysql_rec[templ->mysql_null_byte_offset] &
1339 (byte)(templ->mysql_null_bit_mask)) {
1340 dfield_set_null(dfield);
1341 continue;
1342 }
1343 }
1344
1345 /* Extract the column value. */
1346 ptr = mysql_rec + templ->mysql_col_offset;
1347 const dtype_t *dtype = dfield_get_type(dfield);
1348 ulint col_len = templ->mysql_col_len;
1349
1350 ut_ad(dtype->mtype == DATA_INT || dtype->mtype == DATA_CHAR ||
1351 dtype->mtype == DATA_MYSQL || dtype->mtype == DATA_VARCHAR ||
1352 dtype->mtype == DATA_VARMYSQL || dtype->mtype == DATA_BINARY ||
1353 dtype->mtype == DATA_FIXBINARY || dtype->mtype == DATA_FLOAT ||
1354 dtype->mtype == DATA_DOUBLE || dtype->mtype == DATA_DECIMAL ||
1355 dtype->mtype == DATA_BLOB || dtype->mtype == DATA_GEOMETRY ||
1356 dtype->mtype == DATA_POINT || dtype->mtype == DATA_VAR_POINT);
1357
1358 #ifdef UNIV_DEBUG
1359 if (dtype_get_mysql_type(dtype) == DATA_MYSQL_TRUE_VARCHAR) {
1360 ut_ad(templ->mysql_length_bytes > 0);
1361 }
1362 #endif /* UNIV_DEBUG */
1363
1364 /* For now varchar field this has to be always 0 so
1365 memcpy of 0 bytes shouldn't affect the original col_len. */
1366 if (dtype->mtype == DATA_INT) {
1367 /* Convert and Store in big-endian. */
1368 byte *buf = prebuilt->ins_upd_rec_buff + templ->mysql_col_offset;
1369 byte *copy_to = buf + col_len;
1370 for (;;) {
1371 copy_to--;
1372 *copy_to = *ptr;
1373 if (copy_to == buf) {
1374 break;
1375 }
1376 ptr++;
1377 }
1378
1379 if (!(dtype->prtype & DATA_UNSIGNED)) {
1380 *buf ^= 128;
1381 }
1382
1383 ptr = buf;
1384 buf += col_len;
1385 } else if (dtype_get_mysql_type(dtype) == DATA_MYSQL_TRUE_VARCHAR) {
1386 ut_ad(dtype->mtype == DATA_VARCHAR || dtype->mtype == DATA_VARMYSQL ||
1387 dtype->mtype == DATA_BINARY);
1388
1389 col_len = 0;
1390 row_mysql_read_true_varchar(&col_len, ptr, templ->mysql_length_bytes);
1391 ptr += templ->mysql_length_bytes;
1392 } else if (dtype->mtype == DATA_BLOB) {
1393 ptr = row_mysql_read_blob_ref(&col_len, ptr, col_len);
1394 } else if (DATA_GEOMETRY_MTYPE(dtype->mtype)) {
1395 /* Point, Var-Point, Geometry */
1396 ptr = row_mysql_read_geometry(&col_len, ptr, col_len);
1397 }
1398
1399 dfield_set_data(dfield, ptr, col_len);
1400 }
1401 }
1402
1403 /** Does an insert for MySQL using cursor interface.
1404 Cursor interface is low level interface that directly interacts at
1405 Storage Level by-passing all the locking and transaction semantics.
1406 For InnoDB case, this will also by-pass hidden column generation.
1407 @param[in] mysql_rec row in the MySQL format
1408 @param[in,out] prebuilt prebuilt struct in MySQL handle
1409 @return error code or DB_SUCCESS */
1410 static dberr_t row_insert_for_mysql_using_cursor(const byte *mysql_rec,
1411 row_prebuilt_t *prebuilt) {
1412 dberr_t err = DB_SUCCESS;
1413 ins_node_t *node = nullptr;
1414 que_thr_t *thr = nullptr;
1415 mtr_t mtr;
1416
1417 /* Step-1: Get the reference of row to insert. */
1418 row_get_prebuilt_insert_row(prebuilt);
1419 node = prebuilt->ins_node;
1420 thr = que_fork_get_first_thr(prebuilt->ins_graph);
1421
1422 /* Step-2: Convert row from MySQL row format to InnoDB row format. */
1423 row_mysql_to_innobase(node->row, prebuilt, mysql_rec);
1424
1425 /* Step-3: Append row-id index is not unique. */
1426 dict_index_t *clust_index = node->table->first_index();
1427
1428 if (!dict_index_is_unique(clust_index)) {
1429 dict_sys_write_row_id(node->row_id_buf,
1430 dict_table_get_next_table_sess_row_id(node->table));
1431 }
1432
1433 trx_write_trx_id(node->trx_id_buf,
1434 dict_table_get_next_table_sess_trx_id(node->table));
1435
1436 /* Step-4: Iterate over all the indexes and insert entries. */
1437 dict_index_t *inserted_upto = nullptr;
1438 node->entry = UT_LIST_GET_FIRST(node->entry_list);
1439 for (dict_index_t *index = UT_LIST_GET_FIRST(node->table->indexes);
1440 index != nullptr; index = UT_LIST_GET_NEXT(indexes, index),
1441 node->entry = UT_LIST_GET_NEXT(tuple_list, node->entry)) {
1442 node->index = index;
1443 err = row_ins_index_entry_set_vals(node->index, node->entry, node->row);
1444 if (err != DB_SUCCESS) {
1445 break;
1446 }
1447
1448 if (index->is_clustered()) {
1449 err = row_ins_clust_index_entry(node->index, node->entry, thr, false);
1450 } else {
1451 err = row_ins_sec_index_entry(node->index, node->entry, thr, false);
1452 }
1453
1454 if (err == DB_SUCCESS) {
1455 inserted_upto = index;
1456 } else {
1457 break;
1458 }
1459 }
1460
1461 /* Step-5: If error is encountered while inserting entries to any
1462 of the index then entries inserted to previous indexes are removed
1463 explicitly. Automatic rollback is not in action as UNDO logs are
1464 turned-off. */
1465 if (err != DB_SUCCESS) {
1466 node->entry = UT_LIST_GET_FIRST(node->entry_list);
1467
1468 mtr_start(&mtr);
1469 dict_disable_redo_if_temporary(node->table, &mtr);
1470
1471 for (dict_index_t *index = UT_LIST_GET_FIRST(node->table->indexes);
1472 inserted_upto != nullptr; index = UT_LIST_GET_NEXT(indexes, index),
1473 node->entry = UT_LIST_GET_NEXT(tuple_list, node->entry)) {
1474 row_explicit_rollback(index, node->entry, thr, &mtr);
1475
1476 if (index == inserted_upto) {
1477 break;
1478 }
1479 }
1480
1481 mtr_commit(&mtr);
1482 } else {
1483 /* Not protected by dict_table_stats_lock() for performance
1484 reasons, we would rather get garbage in stat_n_rows (which is
1485 just an estimate anyway) than protecting the following code
1486 , with a latch. */
1487 dict_table_n_rows_inc(node->table);
1488
1489 if (node->table->is_system_table) {
1490 srv_stats.n_system_rows_inserted.inc();
1491 } else {
1492 srv_stats.n_rows_inserted.inc();
1493 }
1494 }
1495
1496 thr_get_trx(thr)->error_state = DB_SUCCESS;
1497 return (err);
1498 }
1499
1500 /** Does an insert for MySQL using INSERT graph. This function will run/execute
1501 INSERT graph.
1502 @param[in] mysql_rec row in the MySQL format
1503 @param[in,out] prebuilt prebuilt struct in MySQL handle
1504 @return error code or DB_SUCCESS */
1505 static dberr_t row_insert_for_mysql_using_ins_graph(const byte *mysql_rec,
1506 row_prebuilt_t *prebuilt) {
1507 trx_savept_t savept;
1508 que_thr_t *thr;
1509 dberr_t err;
1510 trx_t *trx = prebuilt->trx;
1511 ins_node_t *node = prebuilt->ins_node;
1512 dict_table_t *table = prebuilt->table;
1513 /* This temp heap is used to duplicate multi-value data and to compensate an
1514 issue in server for virtual column blob handling. */
1515 mem_heap_t *temp_heap = nullptr;
1516
1517 ut_ad(trx);
1518 ut_a(prebuilt->magic_n == ROW_PREBUILT_ALLOCATED);
1519 ut_a(prebuilt->magic_n2 == ROW_PREBUILT_ALLOCATED);
1520
1521 if (dict_table_is_discarded(prebuilt->table)) {
1522 ib::error(ER_IB_MSG_976)
1523 << "The table " << prebuilt->table->name
1524 << " doesn't have a corresponding tablespace, it was"
1525 " discarded.";
1526
1527 return (DB_TABLESPACE_DELETED);
1528
1529 } else if (prebuilt->table->ibd_file_missing) {
1530 ib::error(ER_IB_MSG_977)
1531 << ".ibd file is missing for table " << prebuilt->table->name;
1532
1533 return (DB_TABLESPACE_NOT_FOUND);
1534
1535 } else if (srv_force_recovery &&
1536 !(srv_force_recovery < SRV_FORCE_NO_UNDO_LOG_SCAN &&
1537 dict_sys_t::is_dd_table_id(prebuilt->table->id))) {
1538 /* Allow to modify hardcoded DD tables in some scenario to
1539 make DDL work */
1540
1541 ib::error(ER_IB_MSG_978) << MODIFICATIONS_NOT_ALLOWED_MSG_FORCE_RECOVERY;
1542
1543 return (DB_READ_ONLY);
1544 }
1545
1546 DBUG_EXECUTE_IF("mark_table_corrupted", {
1547 /* Mark the table corrupted for the clustered index */
1548 dict_index_t *index = table->first_index();
1549 ut_ad(index->is_clustered());
1550 dict_set_corrupted(index);
1551 });
1552
1553 if (table->is_corrupted()) {
1554 ib::error(ER_IB_MSG_979) << "Table " << table->name << " is corrupt.";
1555 return (DB_TABLE_CORRUPT);
1556 }
1557
1558 trx->op_info = "inserting";
1559
1560 row_mysql_delay_if_needed();
1561
1562 trx_start_if_not_started_xa(trx, true, UT_LOCATION_HERE);
1563
1564 row_get_prebuilt_insert_row(prebuilt);
1565 node = prebuilt->ins_node;
1566
1567 row_mysql_convert_row_to_innobase(node->row, prebuilt, mysql_rec, &temp_heap);
1568
1569 savept = trx_savept_take(trx);
1570
1571 thr = que_fork_get_first_thr(prebuilt->ins_graph);
1572
1573 if (prebuilt->sql_stat_start) {
1574 node->state = INS_NODE_SET_IX_LOCK;
1575 prebuilt->sql_stat_start = false;
1576 } else {
1577 node->state = INS_NODE_ALLOC_ROW_ID;
1578 }
1579
1580 que_thr_move_to_run_state_for_mysql(thr, trx);
1581
1582 run_again:
1583 thr->run_node = node;
1584 thr->prev_node = node;
1585
1586 row_ins_step(thr);
1587
1588 DEBUG_SYNC_C("ib_after_row_insert_step");
1589
1590 err = trx->error_state;
1591
1592 if (err != DB_SUCCESS) {
1593 error_exit:
1594 que_thr_stop_for_mysql(thr);
1595
1596 /* FIXME: What's this ? */
1597 thr->lock_state = QUE_THR_LOCK_ROW;
1598
1599 auto was_lock_wait = row_mysql_handle_errors(&err, trx, thr, &savept);
1600
1601 thr->lock_state = QUE_THR_LOCK_NOLOCK;
1602
1603 if (was_lock_wait) {
1604 ut_ad(node->state == INS_NODE_INSERT_ENTRIES ||
1605 node->state == INS_NODE_ALLOC_ROW_ID);
1606 goto run_again;
1607 }
1608
1609 trx->op_info = "";
1610
1611 if (temp_heap != nullptr) {
1612 mem_heap_free(temp_heap);
1613 }
1614
1615 return (err);
1616 }
1617
1618 if (dict_table_has_fts_index(table)) {
1619 doc_id_t doc_id;
1620
1621 /* Extract the doc id from the hidden FTS column */
1622 doc_id = fts_get_doc_id_from_row(table, node->row);
1623
1624 if (doc_id <= 0) {
1625 ib::error(ER_IB_MSG_980) << "FTS Doc ID must be large than 0";
1626 err = DB_FTS_INVALID_DOCID;
1627 trx->error_state = DB_FTS_INVALID_DOCID;
1628 goto error_exit;
1629 }
1630
1631 if (!DICT_TF2_FLAG_IS_SET(table, DICT_TF2_FTS_HAS_DOC_ID)) {
1632 doc_id_t next_doc_id = table->fts->cache->next_doc_id;
1633
1634 if (doc_id < next_doc_id) {
1635 ib::error(ER_IB_MSG_981)
1636 << "FTS Doc ID must be large than " << next_doc_id - 1
1637 << " for table " << table->name;
1638
1639 err = DB_FTS_INVALID_DOCID;
1640 trx->error_state = DB_FTS_INVALID_DOCID;
1641 goto error_exit;
1642 }
1643
1644 /* Difference between Doc IDs are restricted within
1645 4 bytes integer. See fts_get_encoded_len(). Consecutive
1646 doc_ids difference should not exceed
1647 FTS_DOC_ID_MAX_STEP value. */
1648
1649 if (doc_id - next_doc_id >= FTS_DOC_ID_MAX_STEP) {
1650 ib::error(ER_IB_MSG_982) << "Doc ID " << doc_id
1651 << " is too big. Its difference with"
1652 " largest used Doc ID "
1653 << next_doc_id - 1
1654 << " cannot"
1655 " exceed or equal to "
1656 << FTS_DOC_ID_MAX_STEP;
1657 err = DB_FTS_INVALID_DOCID;
1658 trx->error_state = DB_FTS_INVALID_DOCID;
1659 goto error_exit;
1660 }
1661 }
1662
1663 if (table->skip_alter_undo) {
1664 if (trx->fts_trx == nullptr) {
1665 trx->fts_trx = fts_trx_create(trx);
1666 }
1667
1668 fts_trx_table_t ftt;
1669 ftt.table = table;
1670 ftt.fts_trx = trx->fts_trx;
1671
1672 fts_add_doc_from_tuple(&ftt, doc_id, node->row);
1673
1674 } else {
1675 /* Pass NULL for the columns affected, since an INSERT
1676 affects all FTS indexes. */
1677 fts_trx_add_op(trx, table, doc_id, FTS_INSERT, nullptr);
1678 }
1679 }
1680
1681 que_thr_stop_for_mysql_no_error(thr, trx);
1682
1683 if (table->is_system_table) {
1684 srv_stats.n_system_rows_inserted.inc();
1685 } else {
1686 srv_stats.n_rows_inserted.inc();
1687 }
1688
1689 /* Not protected by dict_table_stats_lock() for performance
1690 reasons, we would rather get garbage in stat_n_rows (which is
1691 just an estimate anyway) than protecting the following code
1692 with a latch. */
1693 dict_table_n_rows_inc(table);
1694
1695 row_update_statistics_if_needed(table);
1696 trx->op_info = "";
1697
1698 if (temp_heap != nullptr) {
1699 mem_heap_free(temp_heap);
1700 }
1701
1702 return (err);
1703 }
1704
1705 /** Does an insert for MySQL.
1706 @param[in] mysql_rec row in the MySQL format
1707 @param[in,out] prebuilt prebuilt struct in MySQL handle
1708 @return error code or DB_SUCCESS*/
1709 dberr_t row_insert_for_mysql(const byte *mysql_rec, row_prebuilt_t *prebuilt) {
1710 /* For intrinsic tables there a lot of restrictions that can be
1711 relaxed including locking of table, transaction handling, etc.
1712 Use direct cursor interface for inserting to intrinsic tables. */
1713 if (prebuilt->table->is_intrinsic()) {
1714 return (row_insert_for_mysql_using_cursor(mysql_rec, prebuilt));
1715 } else {
1716 return (row_insert_for_mysql_using_ins_graph(mysql_rec, prebuilt));
1717 }
1718 }
1719
1720 void row_prebuild_sel_graph(row_prebuilt_t *prebuilt) {
1721 sel_node_t *node;
1722
1723 ut_ad(prebuilt && prebuilt->trx);
1724
1725 if (prebuilt->sel_graph == nullptr) {
1726 node = sel_node_create(prebuilt->heap);
1727
1728 prebuilt->sel_graph = static_cast<que_fork_t *>(que_node_get_parent(
1729 pars_complete_graph_for_exec(static_cast<sel_node_t *>(node),
1730 prebuilt->trx, prebuilt->heap, prebuilt)));
1731
1732 prebuilt->sel_graph->state = QUE_FORK_ACTIVE;
1733 }
1734 }
1735
1736 /** Creates an query graph node of 'update' type to be used in the MySQL
1737 interface.
1738 @return own: update node */
1739 upd_node_t *row_create_update_node_for_mysql(
1740 dict_table_t *table, /*!< in: table to update */
1741 mem_heap_t *heap) /*!< in: mem heap from which allocated */
1742 {
1743 upd_node_t *node;
1744
1745 DBUG_TRACE;
1746
1747 node = upd_node_create(heap);
1748
1749 node->in_mysql_interface = true;
1750 node->is_delete = false;
1751 node->searched_update = false;
1752 node->select = nullptr;
1753 node->pcur = btr_pcur_t::create_for_mysql();
1754
1755 DBUG_PRINT("info", ("node: %p, pcur: %p", node, node->pcur));
1756
1757 node->table = table;
1758
1759 node->update =
1760 upd_create(table->get_n_cols() + dict_table_get_n_v_cols(table), heap);
1761
1762 node->update->table = table;
1763
1764 node->update_n_fields = table->get_n_cols();
1765
1766 UT_LIST_INIT(node->columns);
1767
1768 node->has_clust_rec_x_lock = true;
1769 node->cmpl_info = 0;
1770
1771 node->table_sym = nullptr;
1772 node->col_assign_list = nullptr;
1773
1774 node->del_multi_val_pos = 0;
1775 node->upd_multi_val_pos = 0;
1776
1777 return node;
1778 }
1779
1780 /** Gets pointer to a prebuilt update vector used in updates. If the update
1781 graph has not yet been built in the prebuilt struct, then this function
1782 first builds it.
1783 @return prebuilt update vector */
1784 upd_t *row_get_prebuilt_update_vector(
1785 row_prebuilt_t *prebuilt) /*!< in: prebuilt struct in MySQL
1786 handle */
1787 {
1788 dict_table_t *table = prebuilt->table;
1789 upd_node_t *node;
1790
1791 ut_ad(prebuilt && table && prebuilt->trx);
1792
1793 if (prebuilt->upd_node == nullptr) {
1794 /* Not called before for this handle: create an update node
1795 and query graph to the prebuilt struct */
1796
1797 node = row_create_update_node_for_mysql(table, prebuilt->heap);
1798
1799 prebuilt->upd_node = node;
1800 prebuilt->upd_node->update->per_stmt_heap =
1801 mem_heap_create(128, UT_LOCATION_HERE);
1802
1803 prebuilt->upd_graph = static_cast<que_fork_t *>(que_node_get_parent(
1804 pars_complete_graph_for_exec(static_cast<upd_node_t *>(node),
1805 prebuilt->trx, prebuilt->heap, prebuilt)));
1806
1807 prebuilt->upd_graph->state = QUE_FORK_ACTIVE;
1808 }
1809
1810 return (prebuilt->upd_node->update);
1811 }
1812
1813 /********************************************************************
1814 Handle an update of a column that has an FTS index. */
1815 static void row_fts_do_update(
1816 trx_t *trx, /* in: transaction */
1817 dict_table_t *table, /* in: Table with FTS index */
1818 doc_id_t old_doc_id, /* in: old document id */
1819 doc_id_t new_doc_id) /* in: new document id */
1820 {
1821 if (trx->fts_next_doc_id) {
1822 fts_trx_add_op(trx, table, old_doc_id, FTS_DELETE, nullptr);
1823 if (new_doc_id != FTS_NULL_DOC_ID) {
1824 fts_trx_add_op(trx, table, new_doc_id, FTS_INSERT, nullptr);
1825 }
1826 }
1827 }
1828
1829 /************************************************************************
1830 Handles FTS matters for an update or a delete.
1831 NOTE: should not be called if the table does not have an FTS index. .*/
1832 static dberr_t row_fts_update_or_delete(
1833 row_prebuilt_t *prebuilt) /* in: prebuilt struct in MySQL
1834 handle */
1835 {
1836 trx_t *trx = prebuilt->trx;
1837 dict_table_t *table = prebuilt->table;
1838 upd_node_t *node = prebuilt->upd_node;
1839 doc_id_t old_doc_id = prebuilt->fts_doc_id;
1840
1841 DBUG_TRACE;
1842
1843 ut_a(dict_table_has_fts_index(prebuilt->table));
1844
1845 /* Deletes are simple; get them out of the way first. */
1846 if (node->is_delete) {
1847 /* A delete affects all FTS indexes, so we pass NULL */
1848 fts_trx_add_op(trx, table, old_doc_id, FTS_DELETE, nullptr);
1849 } else {
1850 doc_id_t new_doc_id;
1851 new_doc_id = fts_read_doc_id((byte *)&trx->fts_next_doc_id);
1852 ut_ad(new_doc_id != UINT64_UNDEFINED);
1853 if (new_doc_id == 0) {
1854 ib::error(ER_IB_MSG_983) << "InnoDB FTS: Doc ID cannot be 0";
1855 return (DB_FTS_INVALID_DOCID);
1856 }
1857 row_fts_do_update(trx, table, old_doc_id, new_doc_id);
1858 }
1859
1860 return DB_SUCCESS;
1861 }
1862
1863 /** Initialize the Doc ID system for FK table with FTS index */
1864 static void init_fts_doc_id_for_ref(
1865 dict_table_t *table, /*!< in: table */
1866 ulint *depth) /*!< in: recursive call depth */
1867 {
1868 dict_foreign_t *foreign;
1869
1870 table->fk_max_recusive_level = 0;
1871
1872 (*depth)++;
1873
1874 /* Limit on tables involved in cascading delete/update */
1875 if (*depth > FK_MAX_CASCADE_DEL) {
1876 return;
1877 }
1878
1879 /* Loop through this table's referenced list and also
1880 recursively traverse each table's foreign table list */
1881 for (dict_foreign_set::iterator it = table->referenced_set.begin();
1882 it != table->referenced_set.end(); ++it) {
1883 foreign = *it;
1884
1885 ut_ad(foreign->foreign_table != nullptr);
1886
1887 if (foreign->foreign_table->fts != nullptr) {
1888 fts_init_doc_id(foreign->foreign_table);
1889 }
1890
1891 if (!foreign->foreign_table->referenced_set.empty() &&
1892 foreign->foreign_table != table) {
1893 init_fts_doc_id_for_ref(foreign->foreign_table, depth);
1894 }
1895 }
1896 }
1897
1898 /* A functor for decrementing counters. */
1899 class ib_dec_counter {
1900 public:
1901 ib_dec_counter() = default;
1902
1903 void operator()(upd_node_t *node) {
1904 ut_ad(node->table->n_foreign_key_checks_running > 0);
1905 node->table->n_foreign_key_checks_running.fetch_sub(1);
1906 }
1907 };
1908
1909 /** Do an in-place update in the intrinsic table. The update should not
1910 modify any of the keys and it should not change the size of any fields.
1911 @param[in] node the update node.
1912 @return DB_SUCCESS on success, an error code on failure. */
1913 static dberr_t row_update_inplace_for_intrinsic(const upd_node_t *node) {
1914 mtr_t mtr;
1915 dict_table_t *table = node->table;
1916 mem_heap_t *heap = node->heap;
1917 dtuple_t *entry = node->row;
1918 ulint offsets_[REC_OFFS_NORMAL_SIZE];
1919 ulint *offsets = offsets_;
1920
1921 ut_ad(table->is_intrinsic());
1922 rec_offs_init(offsets_);
1923 mtr_start(&mtr);
1924 mtr_set_log_mode(&mtr, MTR_LOG_NO_REDO);
1925 btr_pcur_t pcur;
1926
1927 dict_index_t *index = table->first_index();
1928
1929 entry = row_build_index_entry(node->row, node->ext, index, heap);
1930
1931 pcur.open(index, 0, entry, PAGE_CUR_LE, BTR_MODIFY_LEAF, &mtr,
1932 UT_LOCATION_HERE);
1933
1934 rec_t *rec = pcur.get_rec();
1935
1936 ut_ad(!page_rec_is_infimum(rec));
1937 ut_ad(!page_rec_is_supremum(rec));
1938
1939 offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED,
1940 UT_LOCATION_HERE, &heap);
1941
1942 ut_ad(!cmp_dtuple_rec(entry, rec, index, offsets));
1943 ut_ad(!rec_get_deleted_flag(rec, dict_table_is_comp(index->table)));
1944 ut_ad(pcur.get_block()->made_dirty_with_no_latch);
1945
1946 bool size_changes =
1947 row_upd_changes_field_size_or_external(index, offsets, node->update);
1948
1949 if (size_changes) {
1950 pcur.close();
1951 mtr_commit(&mtr);
1952 return (DB_FAIL);
1953 }
1954
1955 row_upd_rec_in_place(rec, index, offsets, node->update, nullptr);
1956
1957 /* Set the changed pages as modified, so that if the page is
1958 evicted from the buffer pool it is flushed and we don't lose
1959 the changes */
1960 mtr.set_modified();
1961 pcur.close();
1962 mtr_commit(&mtr);
1963
1964 return (DB_SUCCESS);
1965 }
1966
1967 typedef std::vector<btr_pcur_t, ut::allocator<btr_pcur_t>> cursors_t;
1968
1969 /** Delete row from table (corresponding entries from all the indexes).
1970 Function will maintain cursor to the entries to invoke explicitly rollback
1971 just in case update action following delete fails.
1972
1973 @param[in] node update node carrying information to delete.
1974 @param[out] delete_entries vector of cursor to deleted entries.
1975 @param[in] restore_delete if true, then restore DELETE records by
1976 unmarking delete.
1977 @return error code or DB_SUCCESS */
1978 static dberr_t row_delete_for_mysql_using_cursor(const upd_node_t *node,
1979 cursors_t &delete_entries,
1980 const bool restore_delete) {
1981 mtr_t mtr;
1982 dict_table_t *table = node->table;
1983 mem_heap_t *heap = node->heap;
1984 dberr_t err = DB_SUCCESS;
1985 dtuple_t *entry;
1986
1987 mtr_start(&mtr);
1988 dict_disable_redo_if_temporary(table, &mtr);
1989
1990 for (auto index : table->indexes) {
1991 if (err != DB_SUCCESS || restore_delete) {
1992 break;
1993 }
1994 entry = row_build_index_entry(node->row, node->ext, index, heap);
1995
1996 btr_pcur_t pcur;
1997
1998 pcur.open(index, 0, entry, PAGE_CUR_LE, BTR_MODIFY_LEAF, &mtr,
1999 UT_LOCATION_HERE);
2000
2001 #ifdef UNIV_DEBUG
2002 ulint offsets_[REC_OFFS_NORMAL_SIZE];
2003 ulint *offsets = offsets_;
2004 rec_offs_init(offsets_);
2005
2006 offsets =
2007 rec_get_offsets(btr_cur_get_rec(pcur.get_btr_cur()), index, offsets,
2008 ULINT_UNDEFINED, UT_LOCATION_HERE, &heap);
2009
2010 ut_ad(!cmp_dtuple_rec(entry, btr_cur_get_rec(pcur.get_btr_cur()), index,
2011 offsets));
2012 #endif /* UNIV_DEBUG */
2013
2014 ut_ad(!rec_get_deleted_flag(btr_cur_get_rec(pcur.get_btr_cur()),
2015 dict_table_is_comp(index->table)));
2016
2017 ut_ad(pcur.get_block()->made_dirty_with_no_latch);
2018
2019 if (page_rec_is_infimum(pcur.get_rec()) ||
2020 page_rec_is_supremum(pcur.get_rec())) {
2021 err = DB_ERROR;
2022 } else {
2023 btr_cur_t *btr_cur = pcur.get_btr_cur();
2024
2025 btr_rec_set_deleted_flag(
2026 btr_cur_get_rec(btr_cur),
2027 buf_block_get_page_zip(btr_cur_get_block(btr_cur)), true);
2028
2029 /* Void call just to set mtr modification flag
2030 to true failing which block is not scheduled for flush*/
2031 byte *log_ptr = nullptr;
2032 if (mlog_open(&mtr, 0, log_ptr)) {
2033 ut_d(ut_error);
2034 ut_o(mlog_close(&mtr, log_ptr));
2035 }
2036
2037 pcur.store_position(&mtr);
2038
2039 delete_entries.push_back(pcur);
2040 }
2041 }
2042
2043 if (err != DB_SUCCESS || restore_delete) {
2044 /* Rollback half-way delete action that might have been
2045 applied to few of the indexes. */
2046 cursors_t::iterator end = delete_entries.end();
2047 for (cursors_t::iterator it = delete_entries.begin(); it != end; ++it) {
2048 bool success =
2049 it->restore_position(BTR_MODIFY_LEAF, &mtr, UT_LOCATION_HERE);
2050
2051 if (!success) {
2052 ut_a(success);
2053 } else {
2054 btr_cur_t *btr_cur = it->get_btr_cur();
2055
2056 ut_ad(btr_cur_get_block(btr_cur)->made_dirty_with_no_latch);
2057
2058 btr_rec_set_deleted_flag(
2059 btr_cur_get_rec(btr_cur),
2060 buf_block_get_page_zip(btr_cur_get_block(btr_cur)), false);
2061
2062 /* Void call just to set mtr modification flag
2063 to true failing which block is not scheduled for
2064 flush. */
2065 byte *log_ptr = nullptr;
2066 if (mlog_open(&mtr, 0, log_ptr)) {
2067 ut_d(ut_error);
2068 ut_o(mlog_close(&mtr, log_ptr));
2069 }
2070 }
2071 }
2072 }
2073
2074 mtr_commit(&mtr);
2075
2076 return (err);
2077 }
2078
2079 /** Does an update of a row for MySQL by inserting new entry with update values.
2080 @param[in] node update node carrying information to delete.
2081 @param[out] delete_entries vector of cursor to deleted entries.
2082 @param[in] thr thread handler
2083 @return error code or DB_SUCCESS */
2084 static dberr_t row_update_for_mysql_using_cursor(const upd_node_t *node,
2085 cursors_t &delete_entries,
2086 que_thr_t *thr) {
2087 dberr_t err = DB_SUCCESS;
2088 dict_table_t *table = node->table;
2089 mem_heap_t *heap = node->heap;
2090 dtuple_t *entry;
2091 dfield_t *trx_id_field;
2092
2093 /* Step-1: Update row-id column if table doesn't have unique index. */
2094 if (!dict_index_is_unique(table->first_index())) {
2095 /* Update the row_id column. */
2096 dfield_t *row_id_field;
2097
2098 row_id_field = dtuple_get_nth_field(node->upd_row, table->get_n_cols() - 2);
2099
2100 dict_sys_write_row_id(static_cast<byte *>(row_id_field->data),
2101 dict_table_get_next_table_sess_row_id(node->table));
2102 }
2103
2104 /* Step-2: Update the trx_id column. */
2105 trx_id_field = dtuple_get_nth_field(node->upd_row, table->get_n_cols() - 1);
2106 trx_write_trx_id(static_cast<byte *>(trx_id_field->data),
2107 dict_table_get_next_table_sess_trx_id(node->table));
2108
2109 /* Step-3: Check if UPDATE can lead to DUPLICATE key violation.
2110 If yes, then avoid executing it and return error. Only after ensuring
2111 that UPDATE is safe execute it as we can't rollback. */
2112 for (auto index : table->indexes) {
2113 if (err != DB_SUCCESS) {
2114 break;
2115 }
2116 entry = row_build_index_entry(node->upd_row, node->upd_ext, index, heap);
2117
2118 if (index->is_clustered()) {
2119 if (!dict_index_is_auto_gen_clust(index)) {
2120 err = row_ins_clust_index_entry(index, entry, thr, true);
2121 }
2122 } else {
2123 err = row_ins_sec_index_entry(index, entry, thr, true);
2124 }
2125 }
2126
2127 if (err != DB_SUCCESS) {
2128 /* This suggest update can't be executed safely.
2129 Avoid executing update. Rollback DELETE action. */
2130 row_delete_for_mysql_using_cursor(node, delete_entries, true);
2131 }
2132
2133 /* Step-4: It is now safe to execute update if there is no error */
2134 for (auto index : table->indexes) {
2135 if (err != DB_SUCCESS) {
2136 break;
2137 }
2138 entry = row_build_index_entry(node->upd_row, node->upd_ext, index, heap);
2139
2140 if (index->is_clustered()) {
2141 err = row_ins_clust_index_entry(index, entry, thr, false);
2142 /* Commit the open mtr as we are processing UPDATE. */
2143 if (index->last_ins_cur) {
2144 index->last_ins_cur->release();
2145 }
2146 } else {
2147 err = row_ins_sec_index_entry(index, entry, thr, false);
2148 }
2149
2150 /* Too big record is valid error and suggestion is to use
2151 bigger page-size or different format. */
2152 ut_ad(err == DB_SUCCESS || err == DB_TOO_BIG_RECORD ||
2153 err == DB_OUT_OF_FILE_SPACE);
2154
2155 if (err == DB_TOO_BIG_RECORD) {
2156 row_delete_for_mysql_using_cursor(node, delete_entries, true);
2157 }
2158 }
2159
2160 return (err);
2161 }
2162
2163 /** Does an update or delete of a row for MySQL.
2164 @param[in,out] prebuilt prebuilt struct in MySQL handle
2165 @return error code or DB_SUCCESS */
2166 static dberr_t row_del_upd_for_mysql_using_cursor(row_prebuilt_t *prebuilt) {
2167 dberr_t err = DB_SUCCESS;
2168 upd_node_t *node;
2169 cursors_t delete_entries;
2170 dict_index_t *clust_index;
2171 que_thr_t *thr = nullptr;
2172
2173 /* Step-0: If there is cached insert position commit it before
2174 starting delete/update action as this can result in btree structure
2175 to change. */
2176 thr = que_fork_get_first_thr(prebuilt->upd_graph);
2177 clust_index = prebuilt->table->first_index();
2178
2179 if (clust_index->last_ins_cur) {
2180 clust_index->last_ins_cur->release();
2181 }
2182
2183 /* Step-1: Select the appropriate cursor that will help build
2184 the original row and updated row. */
2185 node = prebuilt->upd_node;
2186 if (prebuilt->pcur->m_btr_cur.index == clust_index) {
2187 btr_pcur_t::copy_stored_position(node->pcur, prebuilt->pcur);
2188 } else {
2189 btr_pcur_t::copy_stored_position(node->pcur, prebuilt->clust_pcur);
2190 }
2191
2192 ut_ad(prebuilt->table->is_intrinsic());
2193 ut_ad(!prebuilt->table->n_v_cols);
2194
2195 /* Internal table is created by optimizer. So there
2196 should not be any virtual columns. */
2197 row_upd_store_row(node, nullptr, nullptr);
2198
2199 if (!node->is_delete) {
2200 /* UPDATE operation */
2201
2202 bool key_changed = false;
2203
2204 dict_table_t *table = prebuilt->table;
2205
2206 for (auto index : table->indexes) {
2207 key_changed = row_upd_changes_ord_field_binary(
2208 index, node->update, thr, node->upd_row, node->upd_ext, nullptr);
2209
2210 if (key_changed) {
2211 break;
2212 }
2213 }
2214
2215 if (!key_changed) {
2216 err = row_update_inplace_for_intrinsic(node);
2217
2218 if (err == DB_SUCCESS) {
2219 return (err);
2220 }
2221 }
2222 }
2223
2224 /* Step-2: Execute DELETE operation. */
2225 err = row_delete_for_mysql_using_cursor(node, delete_entries, false);
2226
2227 /* Step-3: If only DELETE operation then exit immediately. */
2228 if (node->is_delete) {
2229 if (err == DB_SUCCESS) {
2230 dict_table_n_rows_dec(prebuilt->table);
2231 if (node->table->is_system_table) {
2232 srv_stats.n_system_rows_deleted.inc();
2233 } else {
2234 srv_stats.n_rows_deleted.inc();
2235 }
2236 }
2237 }
2238
2239 if (err == DB_SUCCESS && !node->is_delete) {
2240 /* Step-4: Complete UPDATE operation by inserting new row with
2241 updated data. */
2242 err = row_update_for_mysql_using_cursor(node, delete_entries, thr);
2243
2244 if (err == DB_SUCCESS) {
2245 if (node->table->is_system_table) {
2246 srv_stats.n_system_rows_updated.inc();
2247 } else {
2248 srv_stats.n_rows_updated.inc();
2249 }
2250 }
2251 }
2252
2253 thr_get_trx(thr)->error_state = DB_SUCCESS;
2254 cursors_t::iterator end = delete_entries.end();
2255 for (cursors_t::iterator it = delete_entries.begin(); it != end; ++it) {
2256 it->close();
2257 }
2258
2259 return (err);
2260 }
2261
2262 /** Does an update or delete of a row for MySQL.
2263 @param[in] mysql_rec row in the MySQL format
2264 @param[in,out] prebuilt prebuilt struct in MySQL handle
2265 @return error code or DB_SUCCESS */
2266 static dberr_t row_update_for_mysql_using_upd_graph(const byte *mysql_rec,
2267 row_prebuilt_t *prebuilt) {
2268 trx_savept_t savept;
2269 dberr_t err;
2270 que_thr_t *thr;
2271 dict_index_t *clust_index;
2272 upd_node_t *node;
2273 dict_table_t *table = prebuilt->table;
2274 trx_t *trx = prebuilt->trx;
2275 ulint fk_depth = 0;
2276 bool got_s_lock = false;
2277
2278 DBUG_TRACE;
2279
2280 ut_ad(trx);
2281 ut_a(prebuilt->magic_n == ROW_PREBUILT_ALLOCATED);
2282 ut_a(prebuilt->magic_n2 == ROW_PREBUILT_ALLOCATED);
2283 UT_NOT_USED(mysql_rec);
2284
2285 if (prebuilt->table->ibd_file_missing) {
2286 ib::error(ER_IB_MSG_984)
2287 << "MySQL is trying to use a table handle but the"
2288 " .ibd file for table "
2289 << prebuilt->table->name
2290 << " does not exist. Have you deleted"
2291 " the .ibd file from the database directory under"
2292 " the MySQL datadir, or have you used DISCARD"
2293 " TABLESPACE? "
2294 << TROUBLESHOOTING_MSG;
2295 return DB_ERROR;
2296 }
2297
2298 /* Allow to modify hardcoded DD tables in some scenario to
2299 make DDL work */
2300 if (srv_force_recovery > 0 &&
2301 !(srv_force_recovery < SRV_FORCE_NO_UNDO_LOG_SCAN &&
2302 dict_sys_t::is_dd_table_id(prebuilt->table->id))) {
2303 ib::error(ER_IB_MSG_985) << MODIFICATIONS_NOT_ALLOWED_MSG_FORCE_RECOVERY;
2304 return DB_READ_ONLY;
2305 }
2306
2307 DEBUG_SYNC_C("innodb_row_update_for_mysql_begin");
2308
2309 trx->op_info = "updating or deleting";
2310
2311 row_mysql_delay_if_needed();
2312
2313 init_fts_doc_id_for_ref(table, &fk_depth);
2314
2315 trx_start_if_not_started_xa(trx, true, UT_LOCATION_HERE);
2316
2317 if (dict_table_is_referenced_by_foreign_key(table)) {
2318 /*TODO: use foreign key MDL to protect foreign
2319 key tables(wl#6049) */
2320 init_fts_doc_id_for_ref(table, &fk_depth);
2321 }
2322
2323 node = prebuilt->upd_node;
2324 node->del_multi_val_pos = 0;
2325 node->upd_multi_val_pos = 0;
2326
2327 clust_index = table->first_index();
2328
2329 if (prebuilt->pcur->m_btr_cur.index == clust_index) {
2330 btr_pcur_t::copy_stored_position(node->pcur, prebuilt->pcur);
2331 } else {
2332 btr_pcur_t::copy_stored_position(node->pcur, prebuilt->clust_pcur);
2333 }
2334
2335 ut_a(node->pcur->m_rel_pos == BTR_PCUR_ON);
2336
2337 /* MySQL seems to call rnd_pos before updating each row it
2338 has cached: we can get the correct cursor position from
2339 prebuilt->pcur; NOTE that we cannot build the row reference
2340 from mysql_rec if the clustered index was automatically
2341 generated for the table: MySQL does not know anything about
2342 the row id used as the clustered index key */
2343
2344 savept = trx_savept_take(trx);
2345
2346 thr = que_fork_get_first_thr(prebuilt->upd_graph);
2347
2348 node->state = UPD_NODE_UPDATE_CLUSTERED;
2349
2350 ut_ad(!prebuilt->sql_stat_start);
2351
2352 que_thr_move_to_run_state_for_mysql(thr, trx);
2353
2354 run_again:
2355
2356 thr->run_node = node;
2357 thr->prev_node = node;
2358 thr->fk_cascade_depth = 0;
2359 row_upd_step(thr);
2360
2361 err = trx->error_state;
2362
2363 if (err != DB_SUCCESS) {
2364 que_thr_stop_for_mysql(thr);
2365
2366 if (err == DB_RECORD_NOT_FOUND) {
2367 trx->error_state = DB_SUCCESS;
2368 trx->op_info = "";
2369
2370 if (thr->fk_cascade_depth > 0) {
2371 que_graph_free_recursive(node);
2372 }
2373 goto error;
2374 }
2375
2376 thr->lock_state = QUE_THR_LOCK_ROW;
2377
2378 DEBUG_SYNC(trx->mysql_thd, "row_update_for_mysql_error");
2379
2380 auto was_lock_wait = row_mysql_handle_errors(&err, trx, thr, &savept);
2381 thr->lock_state = QUE_THR_LOCK_NOLOCK;
2382
2383 if (was_lock_wait) {
2384 goto run_again;
2385 }
2386
2387 trx->op_info = "";
2388 goto error;
2389 }
2390
2391 que_thr_stop_for_mysql_no_error(thr, trx);
2392
2393 if (dict_table_has_fts_index(table) &&
2394 trx->fts_next_doc_id != UINT64_UNDEFINED) {
2395 err = row_fts_update_or_delete(prebuilt);
2396 ut_ad(err == DB_SUCCESS);
2397 if (err != DB_SUCCESS) {
2398 goto error;
2399 }
2400 }
2401
2402 /* Completed cascading operations (if any) */
2403 if (got_s_lock) {
2404 row_mysql_unfreeze_data_dictionary(trx);
2405 }
2406
2407 if (node->is_delete) {
2408 /* Not protected by dict_table_stats_lock() for performance
2409 reasons, we would rather get garbage in stat_n_rows (which is
2410 just an estimate anyway) than protecting the following code
2411 with a latch. */
2412 dict_table_n_rows_dec(prebuilt->table);
2413
2414 if (table->is_system_table) {
2415 srv_stats.n_system_rows_deleted.inc();
2416 } else {
2417 srv_stats.n_rows_deleted.inc();
2418 }
2419 } else {
2420 if (table->is_system_table) {
2421 srv_stats.n_system_rows_updated.inc();
2422 } else {
2423 srv_stats.n_rows_updated.inc();
2424 }
2425 }
2426
2427 /* We update table statistics only if it is a DELETE or UPDATE
2428 that changes indexed columns, UPDATEs that change only non-indexed
2429 columns would not affect statistics. */
2430 if (node->is_delete || !(node->cmpl_info & UPD_NODE_NO_ORD_CHANGE)) {
2431 row_update_statistics_if_needed(prebuilt->table);
2432 }
2433
2434 trx->op_info = "";
2435
2436 return err;
2437
2438 error:
2439 if (got_s_lock) {
2440 row_mysql_unfreeze_data_dictionary(trx);
2441 }
2442
2443 return err;
2444 }
2445
2446 /** Does an update or delete of a row for MySQL.
2447 @param[in] mysql_rec row in the MySQL format
2448 @param[in,out] prebuilt prebuilt struct in MySQL handle
2449 @return error code or DB_SUCCESS */
2450 dberr_t row_update_for_mysql(const byte *mysql_rec, row_prebuilt_t *prebuilt) {
2451 if (prebuilt->table->is_intrinsic()) {
2452 return (row_del_upd_for_mysql_using_cursor(prebuilt));
2453 } else {
2454 ut_a(prebuilt->template_type == ROW_MYSQL_WHOLE_ROW ||
2455 (dict_table_get_n_v_cols(prebuilt->table) > 0 &&
2456 prebuilt->read_just_key));
2457 return (row_update_for_mysql_using_upd_graph(mysql_rec, prebuilt));
2458 }
2459 }
2460
2461 /** Delete all rows for the given table by freeing/truncating indexes.
2462 @param[in,out] table table handler */
2463 void row_delete_all_rows(dict_table_t *table) {
2464 ut_ad(table->is_temporary());
2465 dict_index_t *index;
2466
2467 index = table->first_index();
2468 /* Step-0: If there is cached insert position along with mtr
2469 commit it before starting delete/update action. */
2470 if (index->last_ins_cur) {
2471 index->last_ins_cur->release();
2472 }
2473
2474 bool found;
2475 const page_size_t page_size(fil_space_get_page_size(table->space, &found));
2476 ut_a(found);
2477
2478 /* Step-1: Now truncate all the indexes and re-create them.
2479 Note: This is ddl action even though delete all rows is
2480 DML action. Any error during this action is ir-reversible. */
2481 for (auto index : table->indexes) {
2482 ut_ad(index->space == table->space);
2483 const page_id_t root(index->space, index->page);
2484 btr_free(root, page_size);
2485
2486 mtr_t mtr;
2487
2488 mtr.start();
2489 mtr.set_log_mode(MTR_LOG_NO_REDO);
2490 index->page = btr_create(index->type, index->space, index->id, index, &mtr);
2491 ut_ad(index->page != FIL_NULL);
2492 mtr.commit();
2493 }
2494 }
2495
2496 void row_prebuilt_t::try_unlock(bool has_latches_on_recs) {
2497 ut_ad(trx != nullptr);
2498
2499 if (dict_index_is_spatial(index)) {
2500 return;
2501 }
2502
2503 trx->op_info = "unlock_row";
2504
2505 if (0 < new_rec_locks_count()) {
2506 ut_ad(trx->releases_non_matching_rows());
2507 ut_ad(select_lock_type != LOCK_NONE);
2508 ut_ad(!table->is_intrinsic());
2509
2510 mtr_t mtr;
2511 mtr_start(&mtr);
2512 if (new_rec_lock[row_prebuilt_t::LOCK_PCUR]) {
2513 /* Restore the cursor position and find the record */
2514
2515 if (!has_latches_on_recs) {
2516 pcur->restore_position(BTR_SEARCH_LEAF, &mtr, UT_LOCATION_HERE);
2517 }
2518 }
2519 if (new_rec_lock[row_prebuilt_t::LOCK_CLUST_PCUR]) {
2520 /* Restore the cursor position and find the record
2521 in the clustered index. */
2522
2523 if (!has_latches_on_recs) {
2524 clust_pcur->restore_position(BTR_SEARCH_LEAF, &mtr, UT_LOCATION_HERE);
2525 }
2526
2527 ut_ad(clust_pcur->get_btr_cur()->index->is_clustered());
2528 }
2529
2530 /* If the record has been modified by this transaction, we shouldn't unlock
2531 it. In general we should not remove locks acquired during previous queries
2532 of the same transaction. It's a bit difficult to verify this rule holds for
2533 secondary indexes, as records in them do not track the TRX_ID which modified
2534 them. Therefore we verify only clustered index only, that whenever we've
2535 modified the row, then we are not trying to unlock it. This property should
2536 be ensured by setting the new_rec_lock[i] to true only when a new lock
2537 struct was created, which in turn means that no existing lock could be
2538 reused, which in turn means we haven't had any X-lock before, which in turn
2539 implies we hadn't have modified the record yet. */
2540 #ifdef UNIV_DEBUG
2541 {
2542 const btr_pcur_t *const the_pcur =
2543 new_rec_lock[row_prebuilt_t::LOCK_CLUST_PCUR] ? clust_pcur : pcur;
2544 const dict_index_t *const index = the_pcur->get_btr_cur()->index;
2545 if (index->is_clustered()) {
2546 const rec_t *const rec = the_pcur->get_rec();
2547 const trx_id_t rec_trx_id =
2548 index->trx_id_offset
2549 ? trx_read_trx_id(rec + index->trx_id_offset)
2550 : row_get_rec_trx_id(rec, index,
2551 Rec_offsets().compute(rec, index));
2552 ut_ad(rec_trx_id != trx->id);
2553 }
2554 }
2555 #endif
2556 /* We did not update the record: unlock it */
2557
2558 if (new_rec_lock[row_prebuilt_t::LOCK_PCUR]) {
2559 lock_rec_unlock(trx, pcur->get_block(), pcur->get_rec(),
2560 static_cast<enum lock_mode>(select_lock_type));
2561 }
2562
2563 if (new_rec_lock[row_prebuilt_t::LOCK_CLUST_PCUR]) {
2564 lock_rec_unlock(trx, clust_pcur->get_block(), clust_pcur->get_rec(),
2565 static_cast<enum lock_mode>(select_lock_type));
2566 }
2567
2568 mtr_commit(&mtr);
2569 }
2570
2571 trx->op_info = "";
2572 }
2573
2574 /** Does a cascaded delete or set null in a foreign key operation.
2575 @return error code or DB_SUCCESS */
2576 dberr_t row_update_cascade_for_mysql(
2577 que_thr_t *thr, /*!< in: query thread */
2578 upd_node_t *node, /*!< in: update node used in the cascade
2579 or set null operation */
2580 dict_table_t *table) /*!< in: table where we do the operation */
2581 {
2582 dberr_t err;
2583 trx_t *trx;
2584
2585 trx = thr_get_trx(thr);
2586
2587 /* Increment fk_cascade_depth to record the recursive call depth on
2588 a single update/delete that affects multiple tables chained
2589 together with foreign key relations. */
2590 thr->fk_cascade_depth++;
2591
2592 if (thr->fk_cascade_depth > FK_MAX_CASCADE_DEL) {
2593 return (DB_FOREIGN_EXCEED_MAX_CASCADE);
2594 }
2595 run_again:
2596 thr->run_node = node;
2597 thr->prev_node = node;
2598
2599 DEBUG_SYNC_C("foreign_constraint_update_cascade");
2600 TABLE *temp = thr->prebuilt->m_mysql_table;
2601 thr->prebuilt->m_mysql_table = nullptr;
2602 row_upd_step(thr);
2603 thr->prebuilt->m_mysql_table = temp;
2604 /* The recursive call for cascading update/delete happens
2605 in above row_upd_step(), reset the counter once we come
2606 out of the recursive call, so it does not accumulate for
2607 different row deletes */
2608 thr->fk_cascade_depth = 0;
2609
2610 err = trx->error_state;
2611
2612 /* Note that the cascade node is a subnode of another InnoDB
2613 query graph node. We do a normal lock wait in this node, but
2614 all errors are handled by the parent node. */
2615
2616 if (err == DB_LOCK_WAIT) {
2617 /* Handle lock wait here */
2618
2619 que_thr_stop_for_mysql(thr);
2620
2621 lock_wait_suspend_thread(thr);
2622
2623 /* Note that a lock wait may also end in a lock wait timeout,
2624 or this transaction is picked as a victim in selective
2625 deadlock resolution */
2626
2627 if (trx->error_state != DB_SUCCESS) {
2628 return (trx->error_state);
2629 }
2630
2631 /* Retry operation after a normal lock wait */
2632
2633 goto run_again;
2634 }
2635
2636 if (err != DB_SUCCESS) {
2637 return (err);
2638 }
2639
2640 if (node->is_delete) {
2641 /* Not protected by dict_table_stats_lock() for performance
2642 reasons, we would rather get garbage in stat_n_rows (which is
2643 just an estimate anyway) than protecting the following code
2644 with a latch. */
2645 dict_table_n_rows_dec(table);
2646
2647 if (table->is_system_table) {
2648 srv_stats.n_system_rows_deleted.add((size_t)trx->id, 1);
2649 } else {
2650 srv_stats.n_rows_deleted.add((size_t)trx->id, 1);
2651 }
2652 } else {
2653 if (table->is_system_table) {
2654 srv_stats.n_system_rows_updated.add((size_t)trx->id, 1);
2655 } else {
2656 srv_stats.n_rows_updated.add((size_t)trx->id, 1);
2657 }
2658 }
2659
2660 row_update_statistics_if_needed(table);
2661
2662 return (err);
2663 }
2664
2665 /** Checks if a table is such that we automatically created a clustered
2666 index on it (on row id).
2667 @return true if the clustered index was generated automatically */
2668 bool row_table_got_default_clust_index(
2669 const dict_table_t *table) /*!< in: table */
2670 {
2671 const dict_index_t *clust_index;
2672
2673 clust_index = table->first_index();
2674
2675 return (clust_index->get_col(0)->mtype == DATA_SYS);
2676 }
2677
2678 /** Locks the data dictionary in shared mode from modifications, for performing
2679 foreign key check, rollback, or other operation invisible to MySQL.
2680 @param[in,out] trx Transaction
2681 @param[in] location Location */
2682 void row_mysql_freeze_data_dictionary(trx_t *trx, ut::Location location) {
2683 ut_a(trx->dict_operation_lock_mode == 0);
2684
2685 rw_lock_s_lock_gen(dict_operation_lock, 0, location);
2686
2687 trx->dict_operation_lock_mode = RW_S_LATCH;
2688 }
2689
2690 /** Unlocks the data dictionary shared lock. */
2691 void row_mysql_unfreeze_data_dictionary(trx_t *trx) /*!< in/out: transaction */
2692 {
2693 ut_a(trx->dict_operation_lock_mode == RW_S_LATCH);
2694
2695 rw_lock_s_unlock(dict_operation_lock);
2696
2697 trx->dict_operation_lock_mode = 0;
2698 }
2699
2700 /** Locks the data dictionary exclusively for performing a table create or other
2701 data dictionary modification operation.
2702 @param[in,out] trx Transaction
2703 @param[in] location Location */
2704 void row_mysql_lock_data_dictionary(trx_t *trx, ut::Location location) {
2705 ut_a(trx->dict_operation_lock_mode == 0 ||
2706 trx->dict_operation_lock_mode == RW_X_LATCH);
2707
2708 /* Serialize data dictionary operations with dictionary mutex:
2709 no deadlocks or lock waits can occur then in these operations */
2710
2711 rw_lock_x_lock_gen(dict_operation_lock, 0, location);
2712 trx->dict_operation_lock_mode = RW_X_LATCH;
2713
2714 dict_sys_mutex_enter();
2715 }
2716
2717 /** Unlocks the data dictionary exclusive lock. */
2718 void row_mysql_unlock_data_dictionary(trx_t *trx) /*!< in/out: transaction */
2719 {
2720 ut_a(trx->dict_operation_lock_mode == RW_X_LATCH);
2721
2722 /* Serialize data dictionary operations with dictionary mutex:
2723 no deadlocks can occur then in these operations */
2724
2725 dict_sys_mutex_exit();
2726 rw_lock_x_unlock(dict_operation_lock);
2727
2728 trx->dict_operation_lock_mode = 0;
2729 }
2730
2731 dberr_t row_create_table_for_mysql(dict_table_t *&table,
2732 const char *compression,
2733 const HA_CREATE_INFO *create_info,
2734 trx_t *trx, mem_heap_t *heap) {
2735 dberr_t err;
2736
2737 ut_ad(!dict_sys_mutex_own());
2738
2739 DBUG_EXECUTE_IF("ib_create_table_fail_at_start_of_row_create_table_for_mysql",
2740 {
2741 dict_mem_table_free(table);
2742 table = nullptr;
2743
2744 trx->op_info = "";
2745
2746 return (DB_ERROR);
2747 });
2748
2749 trx->op_info = "creating table";
2750
2751 switch (trx_get_dict_operation(trx)) {
2752 case TRX_DICT_OP_NONE:
2753 case TRX_DICT_OP_TABLE:
2754 break;
2755 case TRX_DICT_OP_INDEX:
2756 /* If the transaction was previously flagged as
2757 TRX_DICT_OP_INDEX, we should be creating auxiliary
2758 tables for full-text indexes. */
2759 ut_ad(strstr(table->name.m_name, "/fts_") != nullptr);
2760 }
2761
2762 /* Assign table id and build table space. */
2763 err = dict_build_table_def(table, create_info, trx);
2764 if (err != DB_SUCCESS) {
2765 trx->error_state = DB_SUCCESS;
2766 trx->op_info = "";
2767 trx->dict_operation = TRX_DICT_OP_NONE;
2768 dict_mem_table_free(table);
2769 table = nullptr;
2770 return err;
2771 }
2772
2773 bool free_heap = false;
2774 if (heap == nullptr) {
2775 free_heap = true;
2776 heap = mem_heap_create(512, UT_LOCATION_HERE);
2777 }
2778
2779 dict_table_add_system_columns(table, heap);
2780
2781 dict_sys_mutex_enter();
2782 dict_table_add_to_cache(table, false);
2783 dict_sys_mutex_exit();
2784
2785 /* During upgrade, etc., the log_ddl may haven't been
2786 initialized and we don't need to write DDL logs too.
2787 This can only happen for CREATE TABLE. */
2788 if (log_ddl != nullptr) {
2789 err = log_ddl->write_remove_cache_log(trx, table);
2790 }
2791
2792 if (free_heap) {
2793 mem_heap_free(heap);
2794 }
2795
2796 if (err == DB_SUCCESS && dict_table_is_file_per_table(table)) {
2797 ut_ad(dict_table_is_file_per_table(table));
2798
2799 if (err == DB_SUCCESS && compression != nullptr && compression[0] != '\0') {
2800 ut_ad(!dict_table_in_shared_tablespace(table));
2801
2802 ut_ad(Compression::validate(compression) == DB_SUCCESS);
2803
2804 err = dict_set_compression(table, compression, false);
2805
2806 switch (err) {
2807 case DB_SUCCESS:
2808 break;
2809 case DB_NOT_FOUND:
2810 case DB_UNSUPPORTED:
2811 case DB_IO_NO_PUNCH_HOLE_FS:
2812 /* Return these errors */
2813 break;
2814 case DB_IO_NO_PUNCH_HOLE_TABLESPACE:
2815 /* Page Compression will not be used. */
2816 err = DB_SUCCESS;
2817 break;
2818 default:
2819 ut_error;
2820 }
2821
2822 /* We can check for file system punch hole support
2823 only after creating the tablespace. On Windows
2824 we can query that information but not on Linux. */
2825 ut_ad(err == DB_SUCCESS || err == DB_IO_NO_PUNCH_HOLE_FS);
2826
2827 /* In non-strict mode we ignore dodgy compression
2828 settings. */
2829 }
2830 }
2831 switch (err) {
2832 case DB_SUCCESS:
2833 case DB_IO_NO_PUNCH_HOLE_FS:
2834 break;
2835
2836 case DB_ERROR:
2837 case DB_OUT_OF_FILE_SPACE:
2838 case DB_TOO_MANY_CONCURRENT_TRXS:
2839 case DB_UNSUPPORTED:
2840 case DB_DUPLICATE_KEY:
2841
2842 if (err == DB_OUT_OF_FILE_SPACE) {
2843 ib::warn(ER_IB_MSG_986) << "Cannot create table " << table->name
2844 << " because the tablespace is full";
2845 }
2846
2847 trx->error_state = DB_SUCCESS;
2848
2849 /* Still do it here so that the table can always be freed */
2850 if (dd_table_open_on_name_in_mem(table->name.m_name, false)) {
2851 dict_sys_mutex_enter();
2852
2853 dd_table_close(table, nullptr, nullptr, true);
2854
2855 dict_table_remove_from_cache(table);
2856
2857 dict_sys_mutex_exit();
2858 } else {
2859 dict_mem_table_free(table);
2860 table = nullptr;
2861 }
2862 break;
2863
2864 default:
2865 trx->error_state = DB_SUCCESS;
2866 dict_mem_table_free(table);
2867 table = nullptr;
2868 break;
2869 }
2870
2871 trx->op_info = "";
2872 trx->dict_operation = TRX_DICT_OP_NONE;
2873
2874 return (err);
2875 }
2876
2877 /** Does an index creation operation for MySQL. TODO: currently failure
2878 to create an index results in dropping the whole table! This is no problem
2879 currently as all indexes must be created at the same time as the table.
2880 @return error number or DB_SUCCESS */
2881 dberr_t row_create_index_for_mysql(
2882 dict_index_t *index, /*!< in, own: index definition
2883 (will be freed) */
2884 trx_t *trx, /*!< in: transaction handle */
2885 const ulint *field_lengths, /*!< in: if not NULL, must contain
2886 dict_index_get_n_fields(index)
2887 actual field lengths for the
2888 index columns, which are
2889 then checked for not being too
2890 large. */
2891 dict_table_t *handler) /*!< in/out: table handler. */
2892 {
2893 dberr_t err;
2894 ulint i;
2895 ulint len;
2896 char *index_name;
2897 dict_table_t *table = nullptr;
2898 THD *thd = current_thd;
2899
2900 trx->op_info = "creating index";
2901
2902 /* Copy the index name because we may want destroy the index
2903 in dict_index_add_to_cache_w_vcol, or in dict_index_add_to_cache
2904 */
2905 index_name = mem_strdup(index->name);
2906
2907 auto is_fts = (index->type == DICT_FTS);
2908
2909 if (handler != nullptr && handler->is_intrinsic()) {
2910 table = handler;
2911 }
2912
2913 if (table == nullptr) {
2914 table = dd_table_open_on_name(thd, nullptr, index->table_name, false,
2915 DICT_ERR_IGNORE_NONE);
2916 } else {
2917 table->acquire();
2918 ut_ad(table->is_intrinsic());
2919 }
2920
2921 for (i = 0; i < index->n_def; i++) {
2922 /* Check that prefix_len and actual length
2923 < DICT_MAX_INDEX_COL_LEN */
2924
2925 len = index->get_field(i)->prefix_len;
2926
2927 if (field_lengths && field_lengths[i]) {
2928 len = std::max(len, field_lengths[i]);
2929 }
2930
2931 DBUG_EXECUTE_IF("ib_create_table_fail_at_create_index",
2932 len = DICT_MAX_FIELD_LEN_BY_FORMAT(table) + 1;);
2933
2934 /* Column or prefix length exceeds maximum column length */
2935 if (len > (ulint)DICT_MAX_FIELD_LEN_BY_FORMAT(table)) {
2936 err = DB_TOO_BIG_INDEX_COL;
2937
2938 dict_mem_index_free(index);
2939 goto error_handling;
2940 }
2941 }
2942
2943 trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
2944
2945 /* For temp-table we avoid insertion into SYSTEM TABLES to
2946 maintain performance and so we have separate path that directly
2947 just updates dictionary cache. */
2948 if (!table->is_temporary()) {
2949 /* Create B-tree */
2950 dict_build_index_def(table, index, trx);
2951
2952 err = dict_index_add_to_cache_w_vcol(table, index, nullptr, FIL_NULL,
2953 trx_is_strict(trx));
2954
2955 if (err == DB_TOO_BIG_RECORD) {
2956 ib::error() << "Cannot create the table " << table->name
2957 << " because the record size will exceed the maximum allowed "
2958 "size for a record.";
2959 }
2960 if (err != DB_SUCCESS) {
2961 goto error_handling;
2962 }
2963
2964 index = UT_LIST_GET_LAST(table->indexes);
2965
2966 err = dict_create_index_tree_in_mem(index, trx);
2967
2968 if (err != DB_SUCCESS) {
2969 goto error_handling;
2970 }
2971
2972 } else {
2973 dict_build_index_def(table, index, trx);
2974 #ifdef UNIV_DEBUG
2975 space_index_t index_id = index->id;
2976 #endif
2977
2978 /* add index to dictionary cache and also free index object.
2979 We allow intrinsic table to violate the size limits because
2980 they are used by optimizer for all record formats. */
2981 err = dict_index_add_to_cache(table, index, FIL_NULL,
2982 !table->is_intrinsic() && trx_is_strict(trx));
2983
2984 if (err != DB_SUCCESS) {
2985 goto error_handling;
2986 }
2987
2988 index = UT_LIST_GET_LAST(table->indexes);
2989 ut_ad(index->id == index_id);
2990
2991 /* as above function has freed index object re-load it
2992 now from dictionary cache using index_id */
2993 if (table->is_intrinsic()) {
2994 /* trx_id field is used for tracking which transaction
2995 created the index. For intrinsic table this is
2996 ir-relevant and so re-use it for tracking consistent
2997 view while processing SELECT as part of UPDATE. */
2998 index->trx_id = ULINT_UNDEFINED;
2999 }
3000 ut_a(index != nullptr);
3001 index->table = table;
3002
3003 err = dict_create_index_tree_in_mem(index, trx);
3004
3005 if (err != DB_SUCCESS && !table->is_intrinsic()) {
3006 dict_sys_mutex_enter();
3007 dict_index_remove_from_cache(table, index);
3008 dict_sys_mutex_exit();
3009 }
3010 }
3011
3012 /* Create the index specific FTS auxiliary tables. */
3013 if (err == DB_SUCCESS && is_fts) {
3014 dict_index_t *idx;
3015
3016 idx = dict_table_get_index_on_name(table, index_name);
3017
3018 ut_ad(idx);
3019 err = fts_create_index_tables_low(trx, idx, table->name.m_name, table->id);
3020 }
3021
3022 error_handling:
3023 dd_table_close(table, thd, nullptr, false);
3024
3025 trx->op_info = "";
3026 trx->dict_operation = TRX_DICT_OP_NONE;
3027
3028 ut::free(index_name);
3029
3030 return (err);
3031 }
3032
3033 /** Loads foreign key constraints for the table being created. This
3034 function should be called after the indexes for a table have been
3035 created. Each foreign key constraint must be accompanied with indexes
3036 in both participating tables. The indexes are allowed to contain more
3037 fields than mentioned in the constraint.
3038
3039 @param[in] trx transaction
3040 @param[in] name table full name in normalized form
3041 @param[in] dd_table MySQL dd::Table for the table
3042 @return error code or DB_SUCCESS */
3043 dberr_t row_table_load_foreign_constraints(trx_t *trx, const char *name,
3044 const dd::Table *dd_table) {
3045 dberr_t err;
3046
3047 DBUG_TRACE;
3048
3049 ut_ad(dict_sys_mutex_own());
3050
3051 trx->op_info = "adding foreign keys";
3052
3053 trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
3054
3055 DEBUG_SYNC_C("table_add_foreign_constraints");
3056
3057 /* Check like this shouldn't be done for table that doesn't
3058 have foreign keys but code still continues to run with void action.
3059 Disable it for intrinsic table at-least */
3060
3061 /* Check that also referencing constraints are ok */
3062 dict_names_t fk_tables;
3063 THD *thd = trx->mysql_thd;
3064
3065 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
3066 dd::cache::Dictionary_client::Auto_releaser releaser(client);
3067 dict_table_t *table = dd_table_open_on_name_in_mem(name, true);
3068
3069 err = dd_table_load_fk(client, name, nullptr, table, dd_table, thd, true,
3070 true, &fk_tables);
3071
3072 if (err != DB_SUCCESS) {
3073 dd_table_close(table, nullptr, nullptr, true);
3074 goto func_exit;
3075 }
3076
3077 /* Check whether virtual column or stored column affects
3078 the foreign key constraint of the table. */
3079
3080 if (dict_foreigns_has_s_base_col(table->foreign_set, table)) {
3081 dd_table_close(table, nullptr, nullptr, true);
3082 err = DB_NO_FK_ON_S_BASE_COL;
3083 goto func_exit;
3084 }
3085
3086 /* Fill the virtual column set in foreign when
3087 the table undergoes copy alter operation. */
3088 dict_mem_table_free_foreign_vcol_set(table);
3089 dict_mem_table_fill_foreign_vcol_set(table);
3090
3091 dd_open_fk_tables(fk_tables, true, thd);
3092 dd_table_close(table, nullptr, nullptr, true);
3093
3094 func_exit:
3095 trx->op_info = "";
3096 trx->dict_operation = TRX_DICT_OP_NONE;
3097
3098 return err;
3099 }
3100
3101 /** Drops a table for MySQL as a background operation. MySQL relies on Unix
3102 in ALTER TABLE to the fact that the table handler does not remove the
3103 table before all handles to it has been removed. Furthermore, the MySQL's
3104 call to drop table must be non-blocking. Therefore we do the drop table
3105 as a background operation, which is taken care of by the master thread
3106 in srv0srv.cc.
3107 @return error code or DB_SUCCESS */
3108 static dberr_t row_drop_table_for_mysql_in_background(
3109 const char *name) /*!< in: table name */
3110 {
3111 dberr_t error;
3112 trx_t *trx;
3113
3114 trx = trx_allocate_for_background();
3115
3116 /* If the original transaction was dropping a table referenced by
3117 foreign keys, we must set the following to be able to drop the
3118 table: */
3119
3120 trx->check_foreigns = false;
3121
3122 /* Check that there is enough reusable space in redo log files. */
3123 log_free_check();
3124
3125 /* Try to drop the table in InnoDB */
3126
3127 error = row_drop_table_for_mysql(name, trx);
3128
3129 /* Flush the log to reduce probability that the .frm files and
3130 the InnoDB data dictionary get out-of-sync if the user runs
3131 with innodb_flush_log_at_trx_commit = 0 */
3132
3133 log_buffer_flush_to_disk();
3134
3135 trx_commit_for_mysql(trx);
3136
3137 trx_free_for_background(trx);
3138
3139 return (error);
3140 }
3141
3142 /** TODO: NewDD: Need to check if there is need to keep background
3143 drop, in such case, the thd would be NULL (no MDL can be acquired)
3144 The master thread in srv0srv.cc calls this regularly to drop tables which
3145 we must drop in background after queries to them have ended. Such lazy
3146 dropping of tables is needed in ALTER TABLE on Unix.
3147 @return how many tables dropped + remaining tables in list */
3148 ulint row_drop_tables_for_mysql_in_background(void) {
3149 row_mysql_drop_t *drop;
3150 dict_table_t *table;
3151 ulint n_tables;
3152 ulint n_tables_dropped = 0;
3153 THD *thd = current_thd;
3154 loop:
3155 mutex_enter(&row_drop_list_mutex);
3156
3157 ut_a(row_mysql_drop_list_inited);
3158
3159 drop = UT_LIST_GET_FIRST(row_mysql_drop_list);
3160
3161 n_tables = UT_LIST_GET_LEN(row_mysql_drop_list);
3162
3163 mutex_exit(&row_drop_list_mutex);
3164
3165 if (drop == nullptr) {
3166 /* All tables dropped */
3167 if (thd != nullptr) {
3168 /* All these kind of table should not be
3169 intrinsic ones, so this is no need later. */
3170 ut::delete_(thd_to_innodb_session(thd));
3171 thd_to_innodb_session(thd) = nullptr;
3172 }
3173
3174 return (n_tables + n_tables_dropped);
3175 }
3176
3177 DBUG_EXECUTE_IF("row_drop_tables_in_background_sleep",
3178 std::this_thread::sleep_for(std::chrono::seconds(5)););
3179
3180 /* TODO: NewDD: we cannot get MDL lock here, as thd could be NULL */
3181 table = dd_table_open_on_name(thd, nullptr, drop->table_name, false,
3182 DICT_ERR_IGNORE_NONE);
3183
3184 if (table == nullptr) {
3185 /* If for some reason the table has already been dropped
3186 through some other mechanism, do not try to drop it */
3187
3188 goto already_dropped;
3189 }
3190
3191 if (!table->to_be_dropped) {
3192 /* There is a scenario: the old table is dropped
3193 just after it's added into drop list, and new
3194 table with the same name is created, then we try
3195 to drop the new table in background. */
3196 dd_table_close(table, nullptr, nullptr, false);
3197
3198 goto already_dropped;
3199 }
3200
3201 ut_a(!table->can_be_evicted);
3202
3203 dd_table_close(table, nullptr, nullptr, false);
3204
3205 if (DB_SUCCESS != row_drop_table_for_mysql_in_background(drop->table_name)) {
3206 /* If the DROP fails for some table, we return, and let the
3207 main thread retry later */
3208
3209 if (thd != nullptr) {
3210 /* All these kind of table should not be
3211 intrinsic ones, so this is no need later. */
3212 ut::delete_(thd_to_innodb_session(thd));
3213 thd_to_innodb_session(thd) = nullptr;
3214 }
3215
3216 return (n_tables + n_tables_dropped);
3217 }
3218
3219 n_tables_dropped++;
3220
3221 already_dropped:
3222 mutex_enter(&row_drop_list_mutex);
3223
3224 /* This can't be moved earlier, as row_wait_for_background_drop_list_empty()
3225 expects the item be removed from list only after the drop processing is
3226 completed.*/
3227 UT_LIST_REMOVE(row_mysql_drop_list, drop);
3228
3229 MONITOR_DEC(MONITOR_BACKGROUND_DROP_TABLE);
3230
3231 ib::info(ER_IB_MSG_987) << "Dropped table "
3232 << ut_get_name(nullptr, drop->table_name)
3233 << " in background drop queue.",
3234
3235 ut::free(drop->table_name);
3236
3237 ut::free(drop);
3238
3239 mutex_exit(&row_drop_list_mutex);
3240
3241 goto loop;
3242 }
3243
3244 /** If a table is not yet in the drop list, adds the table to the list of tables
3245 which the master thread drops in background. We need this on Unix because in
3246 ALTER TABLE MySQL may call drop table even if the table has running queries on
3247 it. Also, if there are running foreign key checks on the table, we drop the
3248 table lazily.
3249 @return true if the table was not yet in the drop list, and was added there */
3250 static bool row_add_table_to_background_drop_list(
3251 const char *name [[maybe_unused]]) /*!< in: table name */
3252 {
3253 /* WL6049, remove after WL6049. */
3254 ut_d(ut_error);
3255 #ifndef UNIV_DEBUG
3256 mutex_enter(&row_drop_list_mutex);
3257
3258 ut_a(row_mysql_drop_list_inited);
3259
3260 /* Look if the table already is in the drop list */
3261 for (auto drop : row_mysql_drop_list) {
3262 if (strcmp(drop->table_name, name) == 0) {
3263 /* Already in the list */
3264
3265 mutex_exit(&row_drop_list_mutex);
3266
3267 return false;
3268 }
3269 }
3270
3271 auto drop = static_cast<row_mysql_drop_t *>(
3272 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, sizeof(row_mysql_drop_t)));
3273
3274 drop->table_name = mem_strdup(name);
3275
3276 UT_LIST_ADD_LAST(row_mysql_drop_list, drop);
3277
3278 MONITOR_INC(MONITOR_BACKGROUND_DROP_TABLE);
3279
3280 mutex_exit(&row_drop_list_mutex);
3281
3282 return true;
3283 #endif
3284 }
3285
3286 /** Reassigns the table identifier of a table.
3287 @param[in,out] table table
3288 @param[out] new_id new table id
3289 @return error code or DB_SUCCESS */
3290 static dberr_t row_mysql_table_id_reassign(dict_table_t *table,
3291 table_id_t *new_id) {
3292 dict_hdr_get_new_id(new_id, nullptr, nullptr, table, false);
3293
3294 /* Remove all locks except the table-level S and X locks. */
3295 lock_remove_all_on_table(table, false);
3296
3297 return (DB_SUCCESS);
3298 }
3299
3300 /** Setup the pre-requisites for DISCARD TABLESPACE. It will start the
3301 transaction, acquire the data dictionary lock in X mode and open the table.
3302 @return table instance or 0 if not found. */
3303 static dict_table_t *row_discard_tablespace_begin(
3304 const char *name, /*!< in: table name */
3305 trx_t *trx) /*!< in: transaction handle */
3306 {
3307 trx->op_info = "discarding tablespace";
3308
3309 // trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
3310
3311 trx_start_if_not_started_xa(trx, true, UT_LOCATION_HERE);
3312
3313 /* Serialize data dictionary operations with dictionary mutex:
3314 this is to avoid deadlocks during data dictionary operations */
3315
3316 row_mysql_lock_data_dictionary(trx, UT_LOCATION_HERE);
3317
3318 dict_table_t *table;
3319 THD *thd = current_thd;
3320
3321 table = dd_table_open_on_name(thd, nullptr, name, true, DICT_ERR_IGNORE_NONE);
3322
3323 if (table) {
3324 dict_stats_wait_bg_to_stop_using_table(table, trx);
3325 ut_a(dict_table_is_file_per_table(table));
3326 ut_a(table->n_foreign_key_checks_running == 0);
3327 }
3328
3329 return (table);
3330 }
3331
3332 /** Do the foreign key constraint checks.
3333 @return DB_SUCCESS or error code. */
3334 static dberr_t row_discard_tablespace_foreign_key_checks(
3335 const trx_t *trx, /*!< in: transaction handle */
3336 const dict_table_t *table) /*!< in: table to be discarded */
3337 {
3338 if (srv_read_only_mode || !trx->check_foreigns) {
3339 return (DB_SUCCESS);
3340 }
3341
3342 /* Check if the table is referenced by foreign key constraints from
3343 some other table (not the table itself) */
3344 dict_foreign_set::iterator it =
3345 std::find_if(table->referenced_set.begin(), table->referenced_set.end(),
3346 dict_foreign_different_tables());
3347
3348 if (it == table->referenced_set.end()) {
3349 return (DB_SUCCESS);
3350 }
3351
3352 const dict_foreign_t *foreign = *it;
3353 FILE *ef = dict_foreign_err_file;
3354
3355 ut_ad(foreign->foreign_table != table);
3356 ut_ad(foreign->referenced_table == table);
3357
3358 /* We only allow discarding a referenced table if
3359 FOREIGN_KEY_CHECKS is set to 0 */
3360
3361 mutex_enter(&dict_foreign_err_mutex);
3362
3363 rewind(ef);
3364
3365 ut_print_timestamp(ef);
3366
3367 fputs(" Cannot DISCARD table ", ef);
3368 ut_print_name(ef, trx, table->name.m_name);
3369 fputs(
3370 "\n"
3371 "because it is referenced by ",
3372 ef);
3373 ut_print_name(ef, trx, foreign->foreign_table_name);
3374 putc('\n', ef);
3375
3376 mutex_exit(&dict_foreign_err_mutex);
3377
3378 return (DB_CANNOT_DROP_CONSTRAINT);
3379 }
3380
3381 /** Cleanup after the DISCARD TABLESPACE operation.
3382 @param[in,out] trx transaction handle
3383 @param[in,out] table table to be discarded
3384 @param[in] err error code
3385 @param[in,out] aux_vec fts aux table name vector
3386 @return error code. */
3387 static dberr_t row_discard_tablespace_end(trx_t *trx, dict_table_t *table,
3388 dberr_t err,
3389 aux_name_vec_t *aux_vec) {
3390 bool file_per_table = true;
3391 if (table != nullptr) {
3392 file_per_table = dict_table_is_file_per_table(table);
3393 dd_table_close(table, trx->mysql_thd, nullptr, true);
3394 }
3395
3396 DBUG_EXECUTE_IF("ib_discard_before_commit_crash",
3397 log_make_latest_checkpoint();
3398 DBUG_SUICIDE(););
3399
3400 DBUG_EXECUTE_IF("ib_discard_after_commit_crash", log_make_latest_checkpoint();
3401 DBUG_SUICIDE(););
3402
3403 row_mysql_unlock_data_dictionary(trx);
3404
3405 if (aux_vec->aux_name.size() > 0) {
3406 if (!fts_drop_dd_tables(aux_vec, file_per_table)) {
3407 err = DB_ERROR;
3408 }
3409 fts_free_aux_names(aux_vec);
3410 }
3411
3412 trx->op_info = "";
3413
3414 return (err);
3415 }
3416
3417 /** Do the DISCARD TABLESPACE operation.
3418 @param[in,out] trx transaction handle
3419 @param[in,out] table table to be discarded
3420 @param[in,out] aux_vec fts aux table name vector
3421 @return DB_SUCCESS or error code. */
3422 static dberr_t row_discard_tablespace(trx_t *trx, dict_table_t *table,
3423 aux_name_vec_t *aux_vec) {
3424 dberr_t err;
3425
3426 /* How do we prevent crashes caused by ongoing operations on
3427 the table? Old operations could try to access non-existent
3428 pages. MySQL will block all DML on the table using MDL and a
3429 DISCARD will not start unless all existing operations on the
3430 table to be discarded are completed.
3431
3432 1) Acquire the data dictionary latch in X mode. To prevent any
3433 internal operations that MySQL is not aware off and also for
3434 the internal SQL parser.
3435
3436 2) Purge and rollback: we assign a new table id for the
3437 table. Since purge and rollback look for the table based on
3438 the table id, they see the table as 'dropped' and discard
3439 their operations.
3440
3441 3) Insert buffer: we remove all entries for the tablespace in
3442 the insert buffer tree.
3443
3444 4) FOREIGN KEY operations: if table->n_foreign_key_checks_running > 0,
3445 we do not allow the discard. */
3446
3447 /* For SDI tables, acquire exclusive MDL and set sdi_table->ibd_file_missing
3448 to true. Purge on SDI table acquire shared MDL & also check for missing
3449 flag. */
3450 dict_sys_mutex_exit();
3451 MDL_ticket *sdi_mdl = nullptr;
3452 err = dd_sdi_acquire_exclusive_mdl(trx->mysql_thd, table->space, &sdi_mdl);
3453 if (err != DB_SUCCESS) {
3454 return (err);
3455 }
3456 dict_sys_mutex_enter();
3457
3458 /* Play safe and remove all insert buffer entries, though we should
3459 have removed them already when DISCARD TABLESPACE was called */
3460
3461 ibuf_delete_for_discarded_space(table->space);
3462
3463 table_id_t new_id;
3464
3465 /* Drop all the FTS auxiliary tables. */
3466 if (dict_table_has_fts_index(table) ||
3467 DICT_TF2_FLAG_IS_SET(table, DICT_TF2_FTS_HAS_DOC_ID)) {
3468 fts_drop_tables(trx, table, aux_vec);
3469 }
3470
3471 /* Assign a new space ID to the table definition so that purge
3472 can ignore the changes. Update the system table on disk. */
3473
3474 err = row_mysql_table_id_reassign(table, &new_id);
3475
3476 if (err != DB_SUCCESS) {
3477 return (err);
3478 }
3479
3480 /* Discard the physical file that is used for the tablespace. */
3481 err = fil_discard_tablespace(table->space);
3482
3483 switch (err) {
3484 case DB_SUCCESS:
3485 case DB_IO_ERROR:
3486 case DB_TABLESPACE_NOT_FOUND:
3487 /* All persistent operations successful, update the
3488 data dictionary memory cache. */
3489
3490 table->ibd_file_missing = true;
3491
3492 table->flags2 |= DICT_TF2_DISCARDED;
3493
3494 dict_table_change_id_in_cache(table, new_id);
3495
3496 /* Set SDI tables that ibd is missing */
3497 {
3498 dict_table_t *sdi_table = dict_sdi_get_table(table->space, true, false);
3499 if (sdi_table) {
3500 sdi_table->ibd_file_missing = true;
3501 dict_sdi_close_table(sdi_table);
3502 }
3503 }
3504
3505 /* If the tablespace did not already exist or we couldn't
3506 write to it, we treat that as a successful DISCARD. It is
3507 unusable anyway. */
3508
3509 err = DB_SUCCESS;
3510 break;
3511
3512 default:
3513 /* We need to rollback the disk changes, something failed. */
3514
3515 trx->error_state = DB_SUCCESS;
3516
3517 trx_rollback_to_savepoint(trx, nullptr);
3518
3519 trx->error_state = DB_SUCCESS;
3520 }
3521
3522 return (err);
3523 }
3524
3525 /** Discards the tablespace of a table which stored in an .ibd file. Discarding
3526 means that this function renames the .ibd file and assigns a new table id for
3527 the table. Also the flag table->ibd_file_missing is set to true.
3528 @return error code or DB_SUCCESS */
3529 dberr_t row_discard_tablespace_for_mysql(
3530 const char *name, /*!< in: table name */
3531 trx_t *trx) /*!< in: transaction handle */
3532 {
3533 dberr_t err;
3534 dict_table_t *table;
3535 aux_name_vec_t aux_vec;
3536
3537 /* Open the table and start the transaction if not started. */
3538
3539 table = row_discard_tablespace_begin(name, trx);
3540
3541 if (table == nullptr) {
3542 err = DB_TABLE_NOT_FOUND;
3543 } else if (table->is_temporary()) {
3544 ib_senderrf(trx->mysql_thd, IB_LOG_LEVEL_ERROR,
3545 ER_CANNOT_DISCARD_TEMPORARY_TABLE);
3546
3547 err = DB_ERROR;
3548
3549 } else if (table->space == TRX_SYS_SPACE) {
3550 char table_name[MAX_FULL_NAME_LEN + 1];
3551
3552 innobase_format_name(table_name, sizeof(table_name), table->name.m_name);
3553
3554 ib_senderrf(trx->mysql_thd, IB_LOG_LEVEL_ERROR,
3555 ER_TABLE_IN_SYSTEM_TABLESPACE, table_name);
3556
3557 err = DB_ERROR;
3558
3559 } else if (table->n_foreign_key_checks_running > 0) {
3560 char table_name[MAX_FULL_NAME_LEN + 1];
3561
3562 innobase_format_name(table_name, sizeof(table_name), table->name.m_name);
3563
3564 ib_senderrf(trx->mysql_thd, IB_LOG_LEVEL_ERROR,
3565 ER_DISCARD_FK_CHECKS_RUNNING, table_name);
3566
3567 err = DB_ERROR;
3568
3569 } else {
3570 /* Do foreign key constraint checks. */
3571
3572 err = row_discard_tablespace_foreign_key_checks(trx, table);
3573
3574 if (err == DB_SUCCESS) {
3575 err = row_discard_tablespace(trx, table, &aux_vec);
3576 }
3577 }
3578
3579 return (row_discard_tablespace_end(trx, table, err, &aux_vec));
3580 }
3581
3582 /** Sets an exclusive lock on a table.
3583 @return error code or DB_SUCCESS */
3584 dberr_t row_mysql_lock_table(
3585 trx_t *trx, /*!< in/out: transaction */
3586 dict_table_t *table, /*!< in: table to lock */
3587 enum lock_mode mode, /*!< in: LOCK_X or LOCK_S */
3588 const char *op_info) /*!< in: string for trx->op_info */
3589 {
3590 mem_heap_t *heap;
3591 que_thr_t *thr;
3592 dberr_t err;
3593 sel_node_t *node;
3594
3595 ut_ad(trx);
3596 ut_ad(mode == LOCK_X || mode == LOCK_S);
3597
3598 heap = mem_heap_create(512, UT_LOCATION_HERE);
3599
3600 trx->op_info = op_info;
3601
3602 node = sel_node_create(heap);
3603 thr = pars_complete_graph_for_exec(node, trx, heap, nullptr);
3604 thr->graph->state = QUE_FORK_ACTIVE;
3605
3606 /* We use the select query graph as the dummy graph needed
3607 in the lock module call */
3608
3609 thr = que_fork_get_first_thr(
3610 static_cast<que_fork_t *>(que_node_get_parent(thr)));
3611
3612 que_thr_move_to_run_state_for_mysql(thr, trx);
3613
3614 run_again:
3615 thr->run_node = thr;
3616 thr->prev_node = thr->common.parent;
3617
3618 err = lock_table(0, table, mode, thr);
3619
3620 trx->error_state = err;
3621
3622 if (err == DB_SUCCESS) {
3623 que_thr_stop_for_mysql_no_error(thr, trx);
3624 } else {
3625 que_thr_stop_for_mysql(thr);
3626
3627 auto was_lock_wait = row_mysql_handle_errors(&err, trx, thr, nullptr);
3628
3629 if (was_lock_wait) {
3630 goto run_again;
3631 }
3632 }
3633
3634 que_graph_free(thr->graph);
3635 trx->op_info = "";
3636
3637 return (err);
3638 }
3639
3640 /** Drop ancillary FTS tables as part of dropping a table.
3641 @param[in,out] table Table cache entry
3642 @param[in,out] aux_vec Fts aux table name vector
3643 @param[in,out] trx Transaction handle
3644 @return error code or DB_SUCCESS */
3645 static inline dberr_t row_drop_ancillary_fts_tables(dict_table_t *table,
3646 aux_name_vec_t *aux_vec,
3647 trx_t *trx) {
3648 /* Drop ancillary FTS tables */
3649 if (dict_table_has_fts_index(table) ||
3650 DICT_TF2_FLAG_IS_SET(table, DICT_TF2_FTS_HAS_DOC_ID)) {
3651 ut_ad(table->get_ref_count() == 0);
3652 ut_ad(trx_is_started(trx));
3653
3654 dberr_t err = fts_drop_tables(trx, table, aux_vec);
3655
3656 if (err != DB_SUCCESS) {
3657 ib::error(ER_IB_MSG_988) << " Unable to remove ancillary FTS"
3658 " tables for table "
3659 << table->name << " : " << ut_strerr(err);
3660
3661 return (err);
3662 }
3663 }
3664
3665 /* The table->fts flag can be set on the table for which
3666 the cluster index is being rebuilt. Such table might not have
3667 DICT_TF2_FTS flag set. So keep this out of above
3668 dict_table_has_fts_index condition */
3669 if (table->fts != nullptr) {
3670 fts_free(table);
3671 }
3672
3673 return (DB_SUCCESS);
3674 }
3675
3676 /** Drop a table from the memory cache as part of dropping a table.
3677 @param[in,out] table Table cache entry
3678 @param[in,out] trx Transaction handle
3679 @return error code or DB_SUCCESS */
3680 static inline dberr_t row_drop_table_from_cache(dict_table_t *table,
3681 trx_t *trx) {
3682 /* Remove the pointer to this table object from the list
3683 of modified tables by the transaction because the object
3684 is going to be destroyed below. */
3685 trx->mod_tables.erase(table);
3686
3687 if (!table->is_intrinsic()) {
3688 btr_drop_ahi_for_table(table);
3689 dict_table_remove_from_cache(table);
3690 } else {
3691 while (dict_index_t *index = UT_LIST_GET_FIRST(table->indexes)) {
3692 rw_lock_free(&index->lock);
3693
3694 UT_LIST_REMOVE(table->indexes, index);
3695
3696 dict_mem_index_free(index);
3697 }
3698
3699 dict_mem_table_free(table);
3700 table = nullptr;
3701 }
3702
3703 return (DB_SUCCESS);
3704 }
3705
3706 /** Drop a tablespace as part of dropping or renaming a table.
3707 This deletes the fil_space_t if found and the file on disk.
3708 @param[in] space_id Tablespace ID
3709 @param[in] filepath File path of tablespace to delete
3710 @return error code or DB_SUCCESS */
3711 dberr_t row_drop_tablespace(space_id_t space_id, const char *filepath) {
3712 dberr_t err = DB_SUCCESS;
3713
3714 /* If the tablespace is not in the cache, just delete the file. */
3715 if (!fil_space_exists_in_mem(space_id, nullptr, true, false)) {
3716 /* Force a delete of any discarded or temporary files. */
3717 if (fil_delete_file(filepath)) {
3718 ib::info(ER_IB_MSG_989)
3719 << "Removed datafile=" << filepath << ", space_id=" << space_id;
3720
3721 } else {
3722 ib::info(ER_IB_MSG_990)
3723 << "Failed to delete the datafile '" << filepath << "'!";
3724 }
3725
3726 } else {
3727 err = fil_delete_tablespace(space_id, BUF_REMOVE_NONE);
3728
3729 if (err != DB_SUCCESS && err != DB_TABLESPACE_NOT_FOUND) {
3730 ib::error(ER_IB_MSG_991)
3731 << "Failed to delete the datafile of tablespace ID=" << space_id
3732 << ", file '" << filepath << "'!";
3733 }
3734 }
3735
3736 return (err);
3737 }
3738
3739 /** Drop a table for MySQL. If the data dictionary was not already locked
3740 by the transaction, the transaction will be committed. Otherwise, the
3741 data dictionary will remain locked.
3742 @param[in] name Table name
3743 @param[in] trx Transaction handle
3744 @param[in] nonatomic Whether it is permitted to release
3745 and reacquire dict_operation_lock
3746 @param[in,out] handler Table handler or NULL
3747 @return error code or DB_SUCCESS */
3748 dberr_t row_drop_table_for_mysql(const char *name, trx_t *trx, bool nonatomic,
3749 dict_table_t *handler) {
3750 dberr_t err = DB_SUCCESS;
3751 dict_table_t *table = nullptr;
3752 char *filepath = nullptr;
3753 bool locked_dictionary = false;
3754 THD *thd = trx->mysql_thd;
3755 dd::Table *table_def = nullptr;
3756 bool file_per_table = false;
3757 aux_name_vec_t aux_vec;
3758
3759 DBUG_TRACE;
3760 DBUG_PRINT("row_drop_table_for_mysql", ("table: '%s'", name));
3761
3762 ut_a(name != nullptr);
3763
3764 /* Serialize data dictionary operations with dictionary mutex:
3765 no deadlocks can occur then in these operations */
3766
3767 trx->op_info = "dropping table";
3768
3769 if (handler != nullptr && handler->is_intrinsic()) {
3770 table = handler;
3771 }
3772
3773 if (table == nullptr) {
3774 if (trx->dict_operation_lock_mode != RW_X_LATCH) {
3775 /* Prevent foreign key checks etc. while we are
3776 dropping the table */
3777
3778 row_mysql_lock_data_dictionary(trx, UT_LOCATION_HERE);
3779
3780 locked_dictionary = true;
3781 nonatomic = true;
3782 }
3783
3784 ut_ad(dict_sys_mutex_own());
3785 ut_ad(rw_lock_own(dict_operation_lock, RW_LOCK_X));
3786
3787 table = dict_table_check_if_in_cache_low(name);
3788 /* If it's called from server, then it should exist in cache */
3789 if (table == nullptr) {
3790 /* MDL should already be held by server */
3791 int error = 0;
3792 table = dd_table_open_on_name(
3793 thd, nullptr, name, true,
3794 DICT_ERR_IGNORE_INDEX_ROOT | DICT_ERR_IGNORE_CORRUPT, &error);
3795 if (table == nullptr && error == HA_ERR_GENERIC) {
3796 err = DB_ERROR;
3797 goto funct_exit;
3798 }
3799 } else {
3800 table->acquire();
3801 }
3802
3803 /* Need to exclusive lock all AUX tables for drop table */
3804 if (table && table->fts) {
3805 dict_sys_mutex_exit();
3806 err = fts_lock_all_aux_tables(thd, table);
3807 dict_sys_mutex_enter();
3808
3809 if (err != DB_SUCCESS) {
3810 dd_table_close(table, nullptr, nullptr, true);
3811 goto funct_exit;
3812 }
3813 }
3814 } else {
3815 table->acquire();
3816 ut_ad(table->is_intrinsic());
3817 }
3818
3819 if (!table) {
3820 err = DB_TABLE_NOT_FOUND;
3821 goto funct_exit;
3822 }
3823
3824 file_per_table = dict_table_is_file_per_table(table);
3825
3826 /* Acquire MDL on SDI table of tablespace. This is to prevent
3827 concurrent DROP while purge is happening on SDI table */
3828 if (file_per_table) {
3829 MDL_ticket *sdi_mdl = nullptr;
3830 dict_sys_mutex_exit();
3831 err = dd_sdi_acquire_exclusive_mdl(thd, table->space, &sdi_mdl);
3832 dict_sys_mutex_enter();
3833
3834 if (err != DB_SUCCESS) {
3835 dd_table_close(table, nullptr, nullptr, true);
3836 goto funct_exit;
3837 }
3838 }
3839
3840 /* This function is called recursively via fts_drop_tables(). */
3841 if (!trx_is_started(trx)) {
3842 if (!table->is_temporary()) {
3843 trx_start_if_not_started(trx, true, UT_LOCATION_HERE);
3844 } else {
3845 trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
3846 }
3847 }
3848
3849 /* Turn on this drop bit before we could release the dictionary
3850 latch */
3851 table->to_be_dropped = true;
3852
3853 if (nonatomic) {
3854 /* This trx did not acquire any locks on dictionary
3855 table records yet. Thus it is safe to release and
3856 reacquire the data dictionary latches. */
3857 if (table->fts) {
3858 ut_ad(!table->fts->add_wq);
3859
3860 row_mysql_unlock_data_dictionary(trx);
3861 fts_optimize_remove_table(table);
3862 row_mysql_lock_data_dictionary(trx, UT_LOCATION_HERE);
3863 }
3864
3865 /* Do not bother to deal with persistent stats for temp
3866 tables since we know temp tables do not use persistent
3867 stats. */
3868 if (!table->is_temporary()) {
3869 dict_stats_wait_bg_to_stop_using_table(table, trx);
3870 }
3871 }
3872
3873 /* make sure background stats thread is not running on the table */
3874 ut_ad(!(table->stats_bg_flag & BG_STAT_IN_PROGRESS));
3875
3876 if (!table->is_temporary() && !table->is_fts_aux()) {
3877 if (srv_thread_is_active(srv_threads.m_dict_stats)) {
3878 dict_stats_recalc_pool_del(table);
3879 }
3880
3881 /* Remove stats for this table and all of its indexes from the
3882 persistent storage if it exists and if there are stats for this
3883 table in there. This function creates its own trx and commits
3884 it. */
3885 char errstr[1024];
3886 err = dict_stats_drop_table(name, errstr, sizeof(errstr));
3887
3888 if (err != DB_SUCCESS) {
3889 ib::warn(ER_IB_MSG_992) << errstr;
3890 }
3891 }
3892
3893 if (!table->is_intrinsic()) {
3894 dict_table_prevent_eviction(table);
3895 }
3896
3897 dd_table_close(table, thd, nullptr, true);
3898
3899 /* Check if the table is referenced by foreign key constraints from
3900 some other table now happens on SQL-layer. */
3901
3902 DBUG_EXECUTE_IF("row_drop_table_add_to_background",
3903 row_add_table_to_background_drop_list(table->name.m_name);
3904 err = DB_SUCCESS; goto funct_exit;);
3905
3906 /* TODO: could we replace the counter n_foreign_key_checks_running
3907 with lock checks on the table? Acquire here an exclusive lock on the
3908 table, and rewrite lock0lock.cc and the lock wait in srv0srv.cc so that
3909 they can cope with the table having been dropped here? Foreign key
3910 checks take an IS or IX lock on the table. */
3911
3912 if (table->n_foreign_key_checks_running > 0) {
3913 const char *save_tablename = table->name.m_name;
3914
3915 auto added = row_add_table_to_background_drop_list(save_tablename);
3916
3917 if (added) {
3918 ib::info(ER_IB_MSG_993) << "You are trying to drop table " << table->name
3919 << " though there is a foreign key check"
3920 " running on it. Adding the table to the"
3921 " background drop queue.";
3922
3923 /* We return DB_SUCCESS to MySQL though the drop will
3924 happen lazily later */
3925
3926 err = DB_SUCCESS;
3927 } else {
3928 /* The table is already in the background drop list */
3929 err = DB_ERROR;
3930 }
3931
3932 goto funct_exit;
3933 }
3934
3935 /* Remove all locks that are on the table or its records, if there
3936 are no references to the table but it has record locks, we release
3937 the record locks unconditionally. One use case is:
3938
3939 CREATE TABLE t2 (PRIMARY KEY (a)) SELECT * FROM t1;
3940
3941 If after the user transaction has done the SELECT and there is a
3942 problem in completing the CREATE TABLE operation, MySQL will drop
3943 the table. InnoDB will create a new background transaction to do the
3944 actual drop, the trx instance that is passed to this function. To
3945 preserve existing behaviour we remove the locks but ideally we
3946 shouldn't have to. There should never be record locks on a table
3947 that is going to be dropped. */
3948 if (table->get_ref_count() == 0) {
3949 /* We don't take lock on intrinsic table so nothing to remove.*/
3950 if (!table->is_intrinsic()) {
3951 lock_remove_all_on_table(table, true);
3952 }
3953 ut_a(table->n_rec_locks.load() == 0);
3954 } else if (table->get_ref_count() > 0 || table->n_rec_locks.load() > 0) {
3955 ut_d(ut_error);
3956 #ifndef UNIV_DEBUG
3957 ut_ad(!table->is_intrinsic());
3958
3959 const auto added =
3960 row_add_table_to_background_drop_list(table->name.m_name);
3961
3962 if (added) {
3963 ib::info(ER_IB_MSG_994) << "MySQL is trying to drop table " << table->name
3964 << " though there are still open handles to"
3965 " it. Adding the table to the background drop"
3966 " queue.";
3967
3968 /* We return DB_SUCCESS to MySQL though the drop will
3969 happen lazily later */
3970 err = DB_SUCCESS;
3971 } else {
3972 /* The table is already in the background drop list */
3973 err = DB_ERROR;
3974 }
3975
3976 goto funct_exit;
3977 #endif
3978 }
3979
3980 /* The "to_be_dropped" marks table that is to be dropped, but
3981 has not been dropped, instead, was put in the background drop
3982 list due to being used by concurrent DML operations. Clear it
3983 here since there are no longer any concurrent activities on it,
3984 and it is free to be dropped */
3985 table->to_be_dropped = false;
3986
3987 /* If we get this far then the table to be dropped must not have
3988 any table or record locks on it. */
3989
3990 ut_a(table->is_intrinsic() || !lock_table_has_locks(table));
3991
3992 switch (trx_get_dict_operation(trx)) {
3993 case TRX_DICT_OP_NONE:
3994 trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
3995 case TRX_DICT_OP_TABLE:
3996 break;
3997 case TRX_DICT_OP_INDEX:
3998 /* If the transaction was previously flagged as
3999 TRX_DICT_OP_INDEX, we should be dropping auxiliary
4000 tables for full-text indexes or temp tables. */
4001 ut_ad(strstr(table->name.m_name, "/fts_") != nullptr ||
4002 strstr(table->name.m_name, TEMP_FILE_PREFIX_INNODB) != nullptr);
4003 }
4004
4005 if (!table->is_temporary() && !file_per_table) {
4006 dict_sys_mutex_exit();
4007 for (dict_index_t *index = table->first_index();
4008 err == DB_SUCCESS && index != nullptr; index = index->next()) {
4009 err = log_ddl->write_free_tree_log(trx, index, true);
4010 }
4011 dict_sys_mutex_enter();
4012 if (err != DB_SUCCESS) {
4013 goto funct_exit;
4014 }
4015 }
4016
4017 /* Mark all indexes unavailable in the data dictionary cache
4018 before starting to drop the table. */
4019 for (dict_index_t *index = table->first_index(); index != nullptr;
4020 index = index->next()) {
4021 page_no_t page;
4022
4023 rw_lock_x_lock(dict_index_get_lock(index), UT_LOCATION_HERE);
4024 page = index->page;
4025 /* Mark the index unusable. */
4026 index->page = FIL_NULL;
4027 rw_lock_x_unlock(dict_index_get_lock(index));
4028
4029 if (table->is_temporary()) {
4030 dict_drop_temporary_table_index(index, page);
4031 }
4032 }
4033
4034 err = DB_SUCCESS;
4035
4036 space_id_t space_id;
4037 bool is_temp;
4038 bool is_discarded;
4039 bool shared_tablespace;
4040 table_id_t table_id;
4041 char *table_name;
4042
4043 space_id = table->space;
4044 table_id = table->id;
4045 is_discarded = dict_table_is_discarded(table);
4046 is_temp = table->is_temporary();
4047 shared_tablespace = DICT_TF_HAS_SHARED_SPACE(table->flags);
4048
4049 /* We do not allow temporary tables with a remote path. */
4050 ut_a(!(is_temp && DICT_TF_HAS_DATA_DIR(table->flags)));
4051
4052 /* Make sure the data_dir_path is set if needed. */
4053 dd_get_and_save_data_dir_path(table, table_def, true);
4054
4055 if (dict_table_has_fts_index(table) ||
4056 DICT_TF2_FLAG_IS_SET(table, DICT_TF2_FTS_HAS_DOC_ID)) {
4057 ut_ad(!is_temp);
4058
4059 err = row_drop_ancillary_fts_tables(table, &aux_vec, trx);
4060 if (err != DB_SUCCESS) {
4061 goto funct_exit;
4062 }
4063 }
4064
4065 /* Table space file name has been renamed in TRUNCATE. */
4066 table_name = table->trunc_name.m_name;
4067 if (table_name == nullptr) {
4068 table_name = table->name.m_name;
4069 } else {
4070 table->trunc_name.m_name = nullptr;
4071 }
4072
4073 /* Determine the tablespace filename before we drop
4074 dict_table_t. Free this memory before returning. */
4075 if (DICT_TF_HAS_DATA_DIR(table->flags)) {
4076 auto dir = dict_table_get_datadir(table);
4077
4078 filepath = Fil_path::make(dir, table_name, IBD, true);
4079
4080 } else if (!shared_tablespace) {
4081 filepath = Fil_path::make_ibd_from_table_name(table_name);
4082 }
4083
4084 /* Free the dict_table_t object. */
4085 err = row_drop_table_from_cache(table, trx);
4086 if (err != DB_SUCCESS) {
4087 ut_d(ut_error);
4088 ut_o(goto funct_exit);
4089 }
4090
4091 if (!is_temp) {
4092 log_ddl->write_drop_log(trx, table_id);
4093 }
4094
4095 /* Do not attempt to drop known-to-be-missing tablespaces,
4096 nor system or shared general tablespaces. */
4097 if (is_discarded || is_temp || shared_tablespace ||
4098 fsp_is_system_or_temp_tablespace(space_id)) {
4099 goto funct_exit;
4100 }
4101
4102 ut_ad(file_per_table);
4103 err = log_ddl->write_delete_space_log(trx, nullptr, space_id, filepath, true,
4104 true);
4105
4106 funct_exit:
4107
4108 ut::free(filepath);
4109
4110 if (locked_dictionary) {
4111 row_mysql_unlock_data_dictionary(trx);
4112 }
4113
4114 trx->op_info = "";
4115 trx->dict_operation = TRX_DICT_OP_NONE;
4116
4117 if (aux_vec.aux_name.size() > 0) {
4118 if (trx->dict_operation_lock_mode == RW_X_LATCH) {
4119 dict_sys_mutex_exit();
4120 }
4121
4122 if (!fts_drop_dd_tables(&aux_vec, file_per_table)) {
4123 err = DB_ERROR;
4124 }
4125
4126 if (trx->dict_operation_lock_mode == RW_X_LATCH) {
4127 dict_sys_mutex_enter();
4128 }
4129
4130 fts_free_aux_names(&aux_vec);
4131 }
4132
4133 return err;
4134 }
4135
4136 [[nodiscard]] bool row_is_mysql_tmp_table_name(const char *name) {
4137 return (strstr(name, "/" TEMP_FILE_PREFIX) != nullptr);
4138 /* return(strstr(name, "/@0023sql") != NULL); */
4139 }
4140
4141 /** Renames a table for MySQL.
4142 @param[in] old_name old table name
4143 @param[in] new_name new table name
4144 @param[in] dd_table dd::Table for new table
4145 @param[in,out] trx transaction
4146 @param[in] replay whether in replay stage
4147 @return error code or DB_SUCCESS */
4148 dberr_t row_rename_table_for_mysql(const char *old_name, const char *new_name,
4149 const dd::Table *dd_table, trx_t *trx,
4150 bool replay) {
4151 dict_table_t *table = nullptr;
4152 bool dict_locked = false;
4153 dberr_t err = DB_ERROR;
4154 int retry;
4155
4156 ut_a(old_name != nullptr);
4157 ut_a(new_name != nullptr);
4158 ut_ad(trx_can_be_handled_by_current_thread_or_is_hp_victim(trx));
4159 ut_ad(trx->state.load(std::memory_order_relaxed) == TRX_STATE_ACTIVE);
4160
4161 if (srv_force_recovery) {
4162 ib::info(ER_IB_MSG_995) << MODIFICATIONS_NOT_ALLOWED_MSG_FORCE_RECOVERY;
4163 return (DB_READ_ONLY);
4164 }
4165
4166 trx->op_info = "renaming table";
4167
4168 const bool old_is_tmp = row_is_mysql_tmp_table_name(old_name);
4169 const bool new_is_tmp = row_is_mysql_tmp_table_name(new_name);
4170 THD *thd = trx->mysql_thd;
4171
4172 dict_locked = trx->dict_operation_lock_mode == RW_X_LATCH;
4173
4174 /* thd could be NULL if these are FTS AUX tables */
4175 table = dd_table_open_on_name(thd, nullptr, old_name, dict_locked,
4176 DICT_ERR_IGNORE_NONE);
4177 if (!table) {
4178 err = DB_TABLE_NOT_FOUND;
4179 goto funct_exit;
4180
4181 } else if (table->ibd_file_missing && !dict_table_is_discarded(table)) {
4182 err = DB_TABLE_NOT_FOUND;
4183
4184 ib::error(ER_IB_MSG_996) << "Table " << old_name
4185 << " does not have an .ibd"
4186 " file in the database directory. "
4187 << TROUBLESHOOTING_MSG;
4188
4189 goto funct_exit;
4190 }
4191
4192 /* Is a foreign key check running on this table? */
4193 for (retry = 0; retry < 100 && table->n_foreign_key_checks_running > 0;
4194 ++retry) {
4195 row_mysql_unlock_data_dictionary(trx);
4196 std::this_thread::yield();
4197 row_mysql_lock_data_dictionary(trx, UT_LOCATION_HERE);
4198 }
4199
4200 if (table->n_foreign_key_checks_running > 0) {
4201 ib::error(ER_IB_MSG_997) << "In ALTER TABLE " << ut_get_name(trx, old_name)
4202 << " a FOREIGN KEY check is running. Cannot rename"
4203 " table.";
4204 err = DB_TABLE_IN_FK_CHECK;
4205 goto funct_exit;
4206 }
4207
4208 err = DB_SUCCESS;
4209
4210 if ((dict_table_has_fts_index(table) ||
4211 DICT_TF2_FLAG_IS_SET(table, DICT_TF2_FTS_HAS_DOC_ID)) &&
4212 !dict_tables_have_same_db(old_name, new_name)) {
4213 err = fts_rename_aux_tables(table, new_name, trx, replay);
4214 }
4215 if (err != DB_SUCCESS) {
4216 if (err == DB_DUPLICATE_KEY) {
4217 ib::error(ER_IB_MSG_998) << "Possible reasons:";
4218 ib::error(ER_IB_MSG_999) << "(1) Table rename would cause two"
4219 " FOREIGN KEY constraints to have the same"
4220 " internal name in case-insensitive"
4221 " comparison.";
4222 ib::error(ER_IB_MSG_1000)
4223 << "(2) Table " << ut_get_name(trx, new_name)
4224 << " exists in the InnoDB internal data"
4225 " dictionary though MySQL is trying to rename"
4226 " table "
4227 << ut_get_name(trx, old_name) << " to it.";
4228 ib::info(ER_IB_MSG_1001) << TROUBLESHOOTING_MSG;
4229 ib::error(ER_IB_MSG_1002)
4230 << "If table " << ut_get_name(trx, new_name)
4231 << " is a temporary table #sql..., then"
4232 " it can be that there are still queries"
4233 " running on the table, and it will be dropped"
4234 " automatically when the queries end. You can"
4235 " drop the orphaned table inside InnoDB by"
4236 " creating an InnoDB table with the same name"
4237 " in another database. Then MySQL thinks"
4238 " the table exists, and DROP TABLE will"
4239 " succeed.";
4240 }
4241 trx->error_state = DB_SUCCESS;
4242 } else {
4243 /* The following call will also rename the .ibd data file if
4244 the table is stored in a single-table tablespace */
4245
4246 err = dict_table_rename_in_cache(table, new_name,
4247 !table->refresh_fk && !new_is_tmp);
4248 if (err != DB_SUCCESS) {
4249 trx->error_state = DB_SUCCESS;
4250 goto funct_exit;
4251 }
4252
4253 /* In case of copy alter, template db_name and
4254 table_name should be renamed only for newly
4255 created table. */
4256 if (table->vc_templ != nullptr && !new_is_tmp) {
4257 innobase_rename_vc_templ(table);
4258 }
4259
4260 if (!dd_table) {
4261 goto funct_exit;
4262 }
4263
4264 /* We only want to switch off some of the type checking in
4265 an ALTER TABLE...ALGORITHM=COPY, not in a RENAME. */
4266 dict_names_t fk_tables;
4267
4268 THD *thd = current_thd;
4269 dd::cache::Dictionary_client *client = dd::get_dd_client(thd);
4270 dd::cache::Dictionary_client::Auto_releaser releaser(client);
4271
4272 /* If neither the old table, nor the new table is temporary, then it is a
4273 table rename command. */
4274 const bool is_rename = (!old_is_tmp && !new_is_tmp);
4275
4276 /* When table->refresh_fk is true, the foreign keys will be loaded when the
4277 table is opened. */
4278 if (is_rename || !table->refresh_fk) {
4279 if (dict_locked) {
4280 ut_ad(dict_sys_mutex_own());
4281 dict_sys_mutex_exit();
4282 }
4283
4284 err = dd_table_load_fk(client, new_name, nullptr, table, dd_table, thd,
4285 false, !old_is_tmp || trx->check_foreigns,
4286 &fk_tables);
4287
4288 if (dict_locked) {
4289 dict_sys_mutex_enter();
4290 }
4291
4292 if (is_rename) {
4293 /* Ensure that old renamed table names are not in this list. */
4294 for (auto it = fk_tables.begin(); it != fk_tables.end();) {
4295 if (strcmp(*it, old_name) == 0) {
4296 it = fk_tables.erase(it);
4297 } else {
4298 ++it;
4299 }
4300 }
4301 }
4302 }
4303
4304 if (err != DB_SUCCESS) {
4305 if (old_is_tmp) {
4306 ib::error(ER_IB_MSG_1003)
4307 << "In ALTER TABLE " << ut_get_name(trx, new_name)
4308 << " has or is referenced in foreign"
4309 " key constraints which are not"
4310 " compatible with the new table"
4311 " definition.";
4312 } else {
4313 ib::error(ER_IB_MSG_1004)
4314 << "In RENAME TABLE table " << ut_get_name(trx, new_name)
4315 << " is referenced in foreign key"
4316 " constraints which are not compatible"
4317 " with the new table definition.";
4318 }
4319
4320 dberr_t error = dict_table_rename_in_cache(table, old_name, false);
4321
4322 ut_a(error == DB_SUCCESS);
4323 goto funct_exit;
4324 }
4325 /* Check whether virtual column or stored column affects
4326 the foreign key constraint of the table. */
4327
4328 if (dict_foreigns_has_s_base_col(table->foreign_set, table)) {
4329 err = DB_NO_FK_ON_S_BASE_COL;
4330 dberr_t error = dict_table_rename_in_cache(table, old_name, false);
4331
4332 ut_a(error == DB_SUCCESS);
4333 goto funct_exit;
4334 }
4335
4336 /* Fill the virtual column set in foreign when
4337 the table undergoes copy alter operation. */
4338 dict_mem_table_free_foreign_vcol_set(table);
4339 dict_mem_table_fill_foreign_vcol_set(table);
4340
4341 dd_open_fk_tables(fk_tables, dict_locked, thd);
4342 }
4343
4344 funct_exit:
4345 if (table != nullptr) {
4346 dd_table_close(table, thd, nullptr, dict_locked);
4347 }
4348
4349 trx->op_info = "";
4350
4351 return (err);
4352 }
4353
4354 dberr_t row_mysql_parallel_select_count_star(
4355 trx_t *trx, std::vector<dict_index_t *> &indexes, size_t n_threads,
4356 ulint *n_rows) {
4357 ut_a(n_threads > 1);
4358 ut_a(!indexes.empty());
4359 using Shards = Counter::Shards<Parallel_reader::MAX_THREADS>;
4360
4361 Shards n_recs;
4362 Counter::clear(n_recs);
4363
4364 const Parallel_reader::Scan_range FULL_SCAN;
4365
4366 Parallel_reader reader(n_threads);
4367
4368 dberr_t err{DB_SUCCESS};
4369
4370 for (auto index : indexes) {
4371 Parallel_reader::Config config(FULL_SCAN, index);
4372
4373 err = reader.add_scan(trx, config, [&](const Parallel_reader::Ctx *ctx) {
4374 Counter::inc(n_recs, ctx->thread_id());
4375 return DB_SUCCESS;
4376 });
4377
4378 if (err != DB_SUCCESS) {
4379 break;
4380 }
4381 }
4382
4383 if (err == DB_SUCCESS) {
4384 err = reader.run(n_threads);
4385 }
4386
4387 if (err == DB_OUT_OF_RESOURCES) {
4388 ut_a(n_threads > 0);
4389
4390 ib::warn(ER_INNODB_OUT_OF_RESOURCES)
4391 << "Resource not available to create threads for parallel scan."
4392 << " Falling back to single thread mode.";
4393
4394 err = reader.run(0);
4395 }
4396
4397 if (err == DB_SUCCESS) {
4398 Counter::for_each(n_recs, [=](const Counter::Type n) {
4399 if (n > 0) {
4400 *n_rows += n;
4401 }
4402 });
4403 }
4404
4405 return err;
4406 }
4407
4408 static dberr_t parallel_check_table(trx_t *trx, dict_index_t *index,
4409 size_t n_threads, ulint *n_rows) {
4410 ut_a(n_threads > 1);
4411 using Shards = Counter::Shards<Parallel_reader::MAX_THREADS>;
4412
4413 Shards n_recs{};
4414 Shards n_dups{};
4415 Shards n_corrupt{};
4416
4417 Counter::clear(n_dups);
4418 Counter::clear(n_recs);
4419 Counter::clear(n_corrupt);
4420
4421 using Tuples = std::vector<dtuple_t *, ut::allocator<dtuple_t *>>;
4422 using Heaps = std::vector<mem_heap_t *, ut::allocator<mem_heap_t *>>;
4423 using Buf_block_allocator = ut::allocator<const buf_block_t *>;
4424 using Blocks = std::vector<const buf_block_t *, Buf_block_allocator>;
4425
4426 Heaps heaps;
4427 Tuples prev_tuples;
4428 Blocks prev_blocks;
4429
4430 for (size_t i = 0; i < n_threads; ++i) {
4431 heaps.push_back(mem_heap_create(4096, UT_LOCATION_HERE));
4432 }
4433
4434 Parallel_reader reader(n_threads);
4435 Parallel_reader::Scan_range full_scan;
4436 Parallel_reader::Config config(full_scan, index);
4437
4438 auto err = reader.add_scan(trx, config, [&](const Parallel_reader::Ctx *ctx) {
4439 const auto rec = ctx->m_rec;
4440 const auto block = ctx->m_block;
4441 const auto id = ctx->thread_id();
4442
4443 Counter::inc(n_recs, id);
4444
4445 auto heap = heaps[id];
4446
4447 if (ctx->m_start) {
4448 /* Starting scan of a new range. We need to reset the previous tuple
4449 because we don't know what the value of the previous last tuple was. */
4450 prev_tuples[id] = nullptr;
4451 }
4452
4453 auto prev_tuple = prev_tuples[id];
4454
4455 auto offsets = rec_get_offsets(rec, index, nullptr, ULINT_UNDEFINED,
4456 UT_LOCATION_HERE, &heap);
4457
4458 if (prev_tuple != nullptr) {
4459 ulint matched_fields = 0;
4460
4461 auto cmp = prev_tuple->compare(rec, index, offsets, &matched_fields);
4462
4463 /* In a unique secondary index we allow equal key values if
4464 they contain SQL NULLs */
4465
4466 bool contains_null = false;
4467 const auto n_ordering = dict_index_get_n_ordering_defined_by_user(index);
4468
4469 for (size_t i = 0; i < n_ordering; ++i) {
4470 const auto nth_field = dtuple_get_nth_field(prev_tuple, i);
4471
4472 if (UNIV_SQL_NULL == dfield_get_len(nth_field)) {
4473 contains_null = true;
4474 break;
4475 }
4476 }
4477
4478 if (cmp > 0) {
4479 Counter::inc(n_corrupt, id);
4480
4481 ib::error(ER_IB_ERR_INDEX_RECORDS_WRONG_ORDER)
4482 << "Index records in a wrong order in " << index->name
4483 << " of table " << index->table->name << ": " << *prev_tuple << ", "
4484 << rec_offsets_print(rec, offsets);
4485 /* Continue reading */
4486 } else if (dict_index_is_unique(index) && !contains_null &&
4487 matched_fields >=
4488 dict_index_get_n_ordering_defined_by_user(index)) {
4489 Counter::inc(n_dups, id);
4490
4491 ib::error(ER_IB_ERR_INDEX_DUPLICATE_KEY)
4492 << "Duplicate key in " << index->name << " of table "
4493 << index->table->name << ": " << *prev_tuple << ", "
4494 << rec_offsets_print(rec, offsets);
4495 }
4496 }
4497
4498 if (prev_blocks[id] != block || prev_blocks[id] == nullptr) {
4499 mem_heap_empty(heap);
4500 offsets = rec_get_offsets(rec, index, nullptr, ULINT_UNDEFINED,
4501 UT_LOCATION_HERE, &heap);
4502
4503 prev_blocks[id] = block;
4504 }
4505
4506 prev_tuples[id] = row_rec_to_index_entry(rec, index, offsets, heap);
4507
4508 return DB_SUCCESS;
4509 });
4510
4511 if (err == DB_SUCCESS) {
4512 prev_tuples.resize(n_threads);
4513 prev_blocks.resize(n_threads);
4514
4515 err = reader.run(n_threads);
4516 }
4517
4518 if (err == DB_OUT_OF_RESOURCES) {
4519 ut_a(n_threads > 0);
4520 ib::warn(ER_INNODB_OUT_OF_RESOURCES)
4521 << "Resource not available to create threads for parallel scan."
4522 << " Falling back to single thread mode.";
4523
4524 err = reader.run(0);
4525 }
4526
4527 for (auto heap : heaps) {
4528 mem_heap_free(heap);
4529 }
4530
4531 if (Counter::total(n_dups) > 0) {
4532 ib::error(ER_IB_ERR_FOUND_N_DUPLICATE_KEYS)
4533 << "Found " << Counter::total(n_dups) << " duplicate rows in "
4534 << index->name;
4535
4536 err = DB_DUPLICATE_KEY;
4537 }
4538
4539 if (Counter::total(n_corrupt) > 0) {
4540 ib::error(ER_IB_ERR_FOUND_N_RECORDS_WRONG_ORDER)
4541 << "Found " << Counter::total(n_corrupt)
4542 << " rows in the wrong order in " << index->name;
4543
4544 err = DB_INDEX_CORRUPT;
4545 }
4546
4547 *n_rows = Counter::total(n_recs);
4548
4549 return err;
4550 }
4551
4552 dberr_t row_scan_index_for_mysql(row_prebuilt_t *prebuilt, dict_index_t *index,
4553 size_t max_threads, bool check_keys,
4554 ulint *n_rows) {
4555 *n_rows = 0;
4556
4557 /* Don't support RTree Leaf level scan */
4558 ut_ad(!dict_index_is_spatial(index));
4559
4560 if (index->is_clustered()) {
4561 /* The clustered index of a table is always available.
4562 During online ALTER TABLE that rebuilds the table, the
4563 clustered index in the old table will have
4564 index->online_log pointing to the new table. All
4565 indexes of the old table will remain valid and the new
4566 table will be unaccessible to MySQL until the
4567 completion of the ALTER TABLE. */
4568 } else if (dict_index_is_online_ddl(index) || (index->type & DICT_FTS)) {
4569 /* Full Text index are implemented by auxiliary tables,
4570 not the B-tree. We also skip secondary indexes that are
4571 being created online. */
4572 return (DB_SUCCESS);
4573 }
4574
4575 DBUG_EXECUTE_IF("ib_disable_parallel_read", goto skip_parallel_read;);
4576
4577 if (prebuilt->trx->isolation_level > TRX_ISO_READ_UNCOMMITTED &&
4578 prebuilt->select_lock_type == LOCK_NONE && index->is_clustered() &&
4579 (check_keys || prebuilt->trx->mysql_n_tables_locked == 0) &&
4580 !prebuilt->ins_sel_stmt) {
4581 auto n_threads = Parallel_reader::available_threads(max_threads, false);
4582
4583 if (n_threads > 1) {
4584 /* No INSERT INTO ... SELECT and non-locking selects only. */
4585 trx_start_if_not_started_xa(prebuilt->trx, false, UT_LOCATION_HERE);
4586
4587 trx_assign_read_view(prebuilt->trx);
4588
4589 auto trx = prebuilt->trx;
4590
4591 ut_a(prebuilt->table == index->table);
4592
4593 std::vector<dict_index_t *> indexes;
4594
4595 indexes.push_back(index);
4596
4597 if (!check_keys) {
4598 return row_mysql_parallel_select_count_star(trx, indexes, n_threads,
4599 n_rows);
4600 }
4601
4602 return parallel_check_table(trx, index, n_threads, n_rows);
4603 } else if (n_threads == 1) {
4604 /* If there is a single thread available then we do a sync scan. */
4605 Parallel_reader::release_threads(n_threads);
4606 }
4607 }
4608
4609 #ifdef UNIV_DEBUG
4610 skip_parallel_read:
4611 #endif /* UNIV_DEBUG */
4612
4613 DBUG_EXECUTE_IF("ib_die_if_not_parallel_read", ut_error;);
4614
4615 bool contains_null;
4616 rec_t *rec = nullptr;
4617 ulint matched_fields;
4618 dtuple_t *prev_entry = nullptr;
4619 ulint offsets_[REC_OFFS_NORMAL_SIZE];
4620 ulint *offsets;
4621
4622 rec_offs_init(offsets_);
4623
4624 ulint cnt = 1000;
4625 ulint bufsize = std::max(UNIV_PAGE_SIZE, prebuilt->mysql_row_len);
4626 auto buf = static_cast<byte *>(
4627 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, bufsize));
4628 auto heap = mem_heap_create(100, UT_LOCATION_HERE);
4629
4630 auto ret = row_search_for_mysql(buf, PAGE_CUR_G, prebuilt, 0, 0);
4631
4632 loop:
4633 /* Check thd->killed every 1,000 scanned rows */
4634 if (--cnt == 0) {
4635 if (trx_is_interrupted(prebuilt->trx)) {
4636 ret = DB_INTERRUPTED;
4637 goto func_exit;
4638 }
4639 cnt = 1000;
4640 }
4641
4642 switch (ret) {
4643 case DB_SUCCESS:
4644 break;
4645 case DB_DEADLOCK:
4646 case DB_LOCK_TABLE_FULL:
4647 case DB_LOCK_WAIT_TIMEOUT:
4648 case DB_INTERRUPTED:
4649 goto func_exit;
4650 default: {
4651 const char *doing = check_keys ? "CHECK TABLE" : "COUNT(*)";
4652 ib::warn(ER_IB_MSG_1005) << doing << " on index " << index->name
4653 << " of"
4654 " table "
4655 << index->table->name << " returned " << ret;
4656 }
4657 /* fall through (this error is ignored by CHECK TABLE) */
4658 [[fallthrough]];
4659 case DB_END_OF_INDEX:
4660 ret = DB_SUCCESS;
4661 func_exit:
4662 ut::free(buf);
4663 mem_heap_free(heap);
4664
4665 return (ret);
4666 }
4667
4668 *n_rows = *n_rows + 1;
4669
4670 if (!check_keys) {
4671 goto next_rec;
4672 }
4673 /* else this code is doing handler::check() for CHECK TABLE */
4674
4675 /* row_search... returns the index record in buf, record origin offset
4676 within buf stored in the first 4 bytes, because we have built a dummy
4677 template */
4678
4679 rec = buf + mach_read_from_4(buf);
4680
4681 offsets = rec_get_offsets(rec, index, offsets_, ULINT_UNDEFINED,
4682 UT_LOCATION_HERE, &heap);
4683
4684 if (prev_entry != nullptr) {
4685 matched_fields = 0;
4686
4687 auto cmp = prev_entry->compare(rec, index, offsets, &matched_fields);
4688 contains_null = false;
4689
4690 /* In a unique secondary index we allow equal key values if
4691 they contain SQL NULLs */
4692
4693 const auto n_ordering = dict_index_get_n_ordering_defined_by_user(index);
4694
4695 for (ulint i = 0; i < n_ordering; ++i) {
4696 if (UNIV_SQL_NULL ==
4697 dfield_get_len(dtuple_get_nth_field(prev_entry, i))) {
4698 contains_null = true;
4699 break;
4700 }
4701 }
4702
4703 const char *msg;
4704
4705 if (cmp > 0) {
4706 ret = DB_INDEX_CORRUPT;
4707 msg = "index records in a wrong order in ";
4708 not_ok:
4709 ib::error(ER_IB_MSG_1006)
4710 << msg << index->name << " of table " << index->table->name << ": "
4711 << *prev_entry << ", " << rec_offsets_print(rec, offsets);
4712 /* Continue reading */
4713 } else if (dict_index_is_unique(index) && !contains_null &&
4714 matched_fields >=
4715 dict_index_get_n_ordering_defined_by_user(index)) {
4716 ret = DB_DUPLICATE_KEY;
4717 msg = "duplicate key in ";
4718 goto not_ok;
4719 }
4720 }
4721
4722 {
4723 mem_heap_t *tmp_heap = nullptr;
4724
4725 /* Empty the heap on each round. But preserve offsets[]
4726 for the row_rec_to_index_entry() call, by copying them
4727 into a separate memory heap when needed. */
4728 if (UNIV_UNLIKELY(offsets != offsets_)) {
4729 ulint size = rec_offs_get_n_alloc(offsets) * sizeof *offsets;
4730
4731 tmp_heap = mem_heap_create(size, UT_LOCATION_HERE);
4732
4733 offsets = static_cast<ulint *>(mem_heap_dup(tmp_heap, offsets, size));
4734 }
4735
4736 mem_heap_empty(heap);
4737
4738 prev_entry = row_rec_to_index_entry(rec, index, offsets, heap);
4739
4740 if (UNIV_LIKELY_NULL(tmp_heap)) {
4741 mem_heap_free(tmp_heap);
4742 }
4743 }
4744
4745 next_rec:
4746 ret = row_search_for_mysql(buf, PAGE_CUR_G, prebuilt, 0, ROW_SEL_NEXT);
4747
4748 goto loop;
4749 }
4750
4751 /** Initialize this module */
4752 void row_mysql_init(void) {
4753 mutex_create(LATCH_ID_ROW_DROP_LIST, &row_drop_list_mutex);
4754
4755 row_mysql_drop_list_inited = true;
4756 }
4757
4758 /** Close this module */
4759 void row_mysql_close(void) {
4760 ut_a(UT_LIST_GET_LEN(row_mysql_drop_list) == 0);
4761
4762 mutex_free(&row_drop_list_mutex);
4763
4764 row_mysql_drop_list_inited = false;
4765 }
4766
4767 /** Can a record buffer or a prefetch cache be utilized for prefetching
4768 records in this scan?
4769 @retval true if records can be prefetched
4770 @retval false if records cannot be prefetched */
4771 bool row_prebuilt_t::can_prefetch_records() const {
4772 /* Inside an update, for example, we do not cache rows, since
4773 we may use the cursor position to do the actual update, that
4774 is why we require select_lock_type == LOCK_NONE. Since we keep
4775 space in prebuilt only for the BLOBs of a single row, we
4776 cannot cache rows in the case there are BLOBs in the fields to
4777 be fetched. In HANDLER (note: the HANDLER statement, not the
4778 handler class) we do not cache rows because there the cursor
4779 is a scrollable cursor. */
4780 return select_lock_type == LOCK_NONE && !m_no_prefetch &&
4781 !templ_contains_blob && !templ_contains_fixed_point &&
4782 !clust_index_was_generated && !used_in_HANDLER && !innodb_api &&
4783 template_type != ROW_MYSQL_DUMMY_TEMPLATE && !in_fts_query;
4784 }
4785
4786 bool row_prebuilt_t::skip_concurrency_ticket() const {
4787 /* Since there are no locks on intrinsic tables, we should skip
4788 this for intrinsic temporary tables. */
4789
4790 /* When InnoDB uses DD APIs, it leaves InnoDB and re-inters InnoDB again.
4791 The reads, updates as part of DDLs should be exempt for concurrency
4792 tickets. */
4793 if (table->is_intrinsic() || table->is_dd_table) {
4794 return true;
4795 }
4796
4797 /* Skip concurrency ticket while implicitly updating GTID table. This is to
4798 avoid deadlock otherwise possible with low innodb_thread_concurrency.
4799 Session: RESET MASTER -> FLUSH LOGS -> get innodb ticket -> wait for GTID
4800 flush GTID Background: Write to GTID table -> wait for innodb ticket. */
4801 auto thd = trx->mysql_thd;
4802 if (thd == nullptr) {
4803 thd = current_thd;
4804 }
4805
4806 if (thd != nullptr) {
4807 /* Skip concurrency ticket for attachable transactions opened for
4808 operating within innodb implicitly. Since it is an independent transaction
4809 apart from the regular transaction owned by this THD in same thread, we
4810 could end up in deadlock. */
4811 if (thd->is_attachable_transaction_active() ||
4812 thd->is_operating_gtid_table_implicitly) {
4813 return true;
4814 }
4815 }
4816 return false;
4817 }
4818
4819 /** Inside this function perform activity that needs to be done at the
4820 end of statement. */
4821 void row_prebuilt_t::end_stmt() {
4822 if (upd_node && upd_node->update) {
4823 upd_node->update->empty_per_stmt_heap();
4824 }
4825 }