row0ins.cc 105 KB
Newer Older
1 2
/*****************************************************************************

Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
3
Copyright (c) 1996, 2016, Oracle and/or its affiliates. All Rights Reserved.
4
Copyright (c) 2016, 2022, MariaDB Corporation.
5 6 7 8 9 10 11 12 13 14 15

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
16
51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

*****************************************************************************/

/**************************************************//**
@file row/row0ins.cc
Insert into a table

Created 4/20/1996 Heikki Tuuri
*******************************************************/

#include "row0ins.h"
#include "dict0dict.h"
#include "trx0rec.h"
#include "trx0undo.h"
#include "btr0btr.h"
#include "btr0cur.h"
#include "mach0data.h"
34
#include "ibuf0ibuf.h"
35 36 37 38 39 40 41 42 43 44 45 46
#include "que0que.h"
#include "row0upd.h"
#include "row0sel.h"
#include "row0log.h"
#include "rem0cmp.h"
#include "lock0lock.h"
#include "log0log.h"
#include "eval0eval.h"
#include "data0data.h"
#include "buf0lru.h"
#include "fts0fts.h"
#include "fts0types.h"
Brave Galera Crew's avatar
Galera4  
Brave Galera Crew committed
47
#ifdef WITH_WSREP
48 49
#include <wsrep.h>
#include <mysql/service_wsrep.h>
Brave Galera Crew's avatar
Galera4  
Brave Galera Crew committed
50
#endif /* WITH_WSREP */
51 52 53 54 55 56 57 58 59 60 61

/*************************************************************************
IMPORTANT NOTE: Any operation that generates redo MUST check that there
is enough space in the redo log before for that operation. This is
done by calling log_free_check(). The reason for checking the
availability of the redo log space before the start of the operation is
that we MUST not hold any synchonization objects when performing the
check.
If you make a change in this module make sure that no codepath is
introduced where a call to log_free_check() is bypassed. */

62 63
/** Create an row template for each index of a table. */
static void ins_node_create_entry_list(ins_node_t *node)
64
{
65 66 67 68 69 70 71 72 73 74 75 76 77
  node->entry_list.reserve(UT_LIST_GET_LEN(node->table->indexes));

  for (dict_index_t *index= dict_table_get_first_index(node->table); index;
       index= dict_table_get_next_index(index))
  {
    /* Corrupted or incomplete secondary indexes will be filtered out in
    row_ins(). */
    dtuple_t *entry= index->online_status >= ONLINE_INDEX_ABORTED
      ? dtuple_create(node->entry_sys_heap, 0)
      : row_build_index_entry_low(node->row, NULL, index, node->entry_sys_heap,
				  ROW_BUILD_FOR_INSERT);
    node->entry_list.push_back(entry);
  }
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
}

/*****************************************************************//**
Adds system field buffers to a row. */
static
void
row_ins_alloc_sys_fields(
/*=====================*/
	ins_node_t*	node)	/*!< in: insert node */
{
	dtuple_t*		row;
	dict_table_t*		table;
	const dict_col_t*	col;
	dfield_t*		dfield;

	row = node->row;
	table = node->table;

	ut_ad(dtuple_get_n_fields(row) == dict_table_get_n_cols(table));

Sergei Golubchik's avatar
5.6.19  
Sergei Golubchik committed
98
	/* allocate buffer to hold the needed system created hidden columns. */
99 100 101
	compile_time_assert(DATA_ROW_ID_LEN
			    + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN
			    == sizeof node->sys_buf);
102 103 104
	memset(node->sys_buf, 0, sizeof node->sys_buf);
	/* Assign DB_ROLL_PTR to 1 << ROLL_PTR_INSERT_FLAG_POS */
	node->sys_buf[DATA_ROW_ID_LEN + DATA_TRX_ID_LEN] = 0x80;
Marko Mäkelä's avatar
Marko Mäkelä committed
105 106
	ut_ad(!memcmp(node->sys_buf + DATA_ROW_ID_LEN, reset_trx_id,
		      sizeof reset_trx_id));
107

Sergei Golubchik's avatar
5.6.19  
Sergei Golubchik committed
108
	/* 1. Populate row-id */
109 110 111 112
	col = dict_table_get_sys_col(table, DATA_ROW_ID);

	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));

113
	dfield_set_data(dfield, node->sys_buf, DATA_ROW_ID_LEN);
114

Sergei Golubchik's avatar
5.6.19  
Sergei Golubchik committed
115
	/* 2. Populate trx id */
116 117 118 119
	col = dict_table_get_sys_col(table, DATA_TRX_ID);

	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));

120 121
	dfield_set_data(dfield, &node->sys_buf[DATA_ROW_ID_LEN],
			DATA_TRX_ID_LEN);
Sergei Golubchik's avatar
5.6.19  
Sergei Golubchik committed
122

123
	col = dict_table_get_sys_col(table, DATA_ROLL_PTR);
124

125
	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
126

127 128 129
	dfield_set_data(dfield, &node->sys_buf[DATA_ROW_ID_LEN
					       + DATA_TRX_ID_LEN],
			DATA_ROLL_PTR_LEN);
130 131 132 133 134 135 136 137 138 139 140 141 142 143
}

/*********************************************************************//**
Sets a new row to insert for an INS_DIRECT node. This function is only used
if we have constructed the row separately, which is a rare case; this
function is quite slow. */
void
ins_node_set_new_row(
/*=================*/
	ins_node_t*	node,	/*!< in: insert node */
	dtuple_t*	row)	/*!< in: new row (or first row) for the node */
{
	node->state = INS_NODE_SET_IX_LOCK;
	node->index = NULL;
144 145
	node->entry_list.clear();
	node->entry = node->entry_list.end();
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

	node->row = row;

	mem_heap_empty(node->entry_sys_heap);

	/* Create templates for index entries */

	ins_node_create_entry_list(node);

	/* Allocate from entry_sys_heap buffers for sys fields */

	row_ins_alloc_sys_fields(node);

	/* As we allocated a new trx id buf, the trx id should be written
	there again: */

	node->trx_id = 0;
}

/*******************************************************************//**
Does an insert operation by updating a delete-marked existing record
in the index. This situation can occur if the delete-marked record is
kept in the index for consistent reads.
169
@return DB_SUCCESS or error code */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
170
static MY_ATTRIBUTE((nonnull, warn_unused_result))
171 172 173 174 175 176 177 178
dberr_t
row_ins_sec_index_entry_by_modify(
/*==============================*/
	ulint		flags,	/*!< in: undo logging and locking flags */
	ulint		mode,	/*!< in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
				depending on whether mtr holds just a leaf
				latch or also a tree latch */
	btr_cur_t*	cursor,	/*!< in: B-tree cursor */
179
	rec_offs**	offsets,/*!< in/out: offsets on cursor->page_cur.rec */
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
	mem_heap_t*	offsets_heap,
				/*!< in/out: memory heap that can be emptied */
	mem_heap_t*	heap,	/*!< in/out: memory heap */
	const dtuple_t*	entry,	/*!< in: index entry to insert */
	que_thr_t*	thr,	/*!< in: query thread */
	mtr_t*		mtr)	/*!< in: mtr; must be committed before
				latching any further pages */
{
	big_rec_t*	dummy_big_rec;
	upd_t*		update;
	rec_t*		rec;
	dberr_t		err;

	rec = btr_cur_get_rec(cursor);

	ut_ad(!dict_index_is_clust(cursor->index));
	ut_ad(rec_offs_validate(rec, cursor->index, *offsets));
	ut_ad(!entry->info_bits);

	/* We know that in the alphabetical ordering, entry and rec are
	identified. But in their binary form there may be differences if
	there are char fields in them. Therefore we have to calculate the
	difference. */

	update = row_upd_build_sec_rec_difference_binary(
		rec, cursor->index, *offsets, entry, heap);

	if (!rec_get_deleted_flag(rec, rec_offs_comp(*offsets))) {
		/* We should never insert in place of a record that
		has not been delete-marked. The only exception is when
		online CREATE INDEX copied the changes that we already
		made to the clustered index, and completed the
		secondary index creation before we got here. In this
		case, the change would already be there. The CREATE
		INDEX should be waiting for a MySQL meta-data lock
		upgrade at least until this INSERT or UPDATE
216 217
		returns. After that point, set_committed(true)
		would be invoked in commit_inplace_alter_table(). */
218
		ut_a(update->n_fields == 0);
219
		ut_a(!cursor->index->is_committed());
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
		ut_ad(!dict_index_is_online_ddl(cursor->index));
		return(DB_SUCCESS);
	}

	if (mode == BTR_MODIFY_LEAF) {
		/* Try an optimistic updating of the record, keeping changes
		within the page */

		/* TODO: pass only *offsets */
		err = btr_cur_optimistic_update(
			flags | BTR_KEEP_SYS_FLAG, cursor,
			offsets, &offsets_heap, update, 0, thr,
			thr_get_trx(thr)->id, mtr);
		switch (err) {
		case DB_OVERFLOW:
		case DB_UNDERFLOW:
		case DB_ZIP_OVERFLOW:
			err = DB_FAIL;
		default:
			break;
		}
	} else {
		ut_a(mode == BTR_MODIFY_TREE);
243
		if (buf_pool.running_out()) {
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

			return(DB_LOCK_TABLE_FULL);
		}

		err = btr_cur_pessimistic_update(
			flags | BTR_KEEP_SYS_FLAG, cursor,
			offsets, &offsets_heap,
			heap, &dummy_big_rec, update, 0,
			thr, thr_get_trx(thr)->id, mtr);
		ut_ad(!dummy_big_rec);
	}

	return(err);
}

/*******************************************************************//**
Does an insert operation by delete unmarking and updating a delete marked
existing record in the index. This situation can occur if the delete marked
record is kept in the index for consistent reads.
263
@return DB_SUCCESS, DB_FAIL, or error code */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
264
static MY_ATTRIBUTE((nonnull, warn_unused_result))
265 266 267
dberr_t
row_ins_clust_index_entry_by_modify(
/*================================*/
268 269
	btr_pcur_t*	pcur,	/*!< in/out: a persistent cursor pointing
				to the clust_rec that is being modified. */
270 271 272 273
	ulint		flags,	/*!< in: undo logging and locking flags */
	ulint		mode,	/*!< in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
				depending on whether mtr holds just a leaf
				latch or also a tree latch */
274
	rec_offs**	offsets,/*!< out: offsets on cursor->page_cur.rec */
275 276 277 278 279 280 281 282 283 284
	mem_heap_t**	offsets_heap,
				/*!< in/out: pointer to memory heap that can
				be emptied, or NULL */
	mem_heap_t*	heap,	/*!< in/out: memory heap */
	const dtuple_t*	entry,	/*!< in: index entry to insert */
	que_thr_t*	thr,	/*!< in: query thread */
	mtr_t*		mtr)	/*!< in: mtr; must be committed before
				latching any further pages */
{
	const rec_t*	rec;
285
	upd_t*		update;
286
	dberr_t		err = DB_SUCCESS;
287
	btr_cur_t*	cursor	= btr_pcur_get_btr_cur(pcur);
288
	TABLE*		mysql_table = NULL;
289 290 291 292 293 294
	ut_ad(dict_index_is_clust(cursor->index));

	rec = btr_cur_get_rec(cursor);

	ut_ad(rec_get_deleted_flag(rec,
				   dict_table_is_comp(cursor->index->table)));
295 296 297
	/* In delete-marked records, DB_TRX_ID must
	always refer to an existing undo log record. */
	ut_ad(rec_get_trx_id(rec, cursor->index));
298 299 300 301

	/* Build an update vector containing all the fields to be modified;
	NOTE that this vector may NOT contain system columns trx_id or
	roll_ptr */
302 303 304 305
	if (thr->prebuilt != NULL) {
		mysql_table = thr->prebuilt->m_mysql_table;
		ut_ad(thr->prebuilt->trx == thr_get_trx(thr));
	}
306 307

	update = row_upd_build_difference_binary(
308
		cursor->index, entry, rec, NULL, true, true,
309 310 311 312 313
		thr_get_trx(thr), heap, mysql_table, &err);
	if (err != DB_SUCCESS) {
		return(err);
	}

314
	if (mode != BTR_MODIFY_TREE) {
315 316
		ut_ad((mode & ulint(~BTR_ALREADY_S_LATCHED))
		      == BTR_MODIFY_LEAF);
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

		/* Try optimistic updating of the record, keeping changes
		within the page */

		err = btr_cur_optimistic_update(
			flags, cursor, offsets, offsets_heap, update, 0, thr,
			thr_get_trx(thr)->id, mtr);
		switch (err) {
		case DB_OVERFLOW:
		case DB_UNDERFLOW:
		case DB_ZIP_OVERFLOW:
			err = DB_FAIL;
		default:
			break;
		}
	} else {
333 334
		if (buf_pool.running_out()) {
			return DB_LOCK_TABLE_FULL;
335
		}
336 337 338

		big_rec_t*	big_rec	= NULL;

339 340 341
		err = btr_cur_pessimistic_update(
			flags | BTR_KEEP_POS_FLAG,
			cursor, offsets, offsets_heap, heap,
342 343 344 345 346 347 348
			&big_rec, update, 0, thr, thr_get_trx(thr)->id, mtr);

		if (big_rec) {
			ut_a(err == DB_SUCCESS);

			DEBUG_SYNC_C("before_row_ins_upd_extern");
			err = btr_store_big_rec_extern_fields(
Marko Mäkelä's avatar
Marko Mäkelä committed
349
				pcur, *offsets, big_rec, mtr,
350 351 352 353
				BTR_STORE_INSERT_UPDATE);
			DEBUG_SYNC_C("after_row_ins_upd_extern");
			dtuple_big_rec_free(big_rec);
		}
354 355 356 357 358 359 360 361
	}

	return(err);
}

/*********************************************************************//**
Returns TRUE if in a cascaded update/delete an ancestor node of node
updates (not DELETE, but UPDATE) table.
362
@return TRUE if an ancestor updates table */
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
static
ibool
row_ins_cascade_ancestor_updates_table(
/*===================================*/
	que_node_t*	node,	/*!< in: node in a query graph */
	dict_table_t*	table)	/*!< in: table */
{
	que_node_t*	parent;

	for (parent = que_node_get_parent(node);
	     que_node_get_type(parent) == QUE_NODE_UPDATE;
	     parent = que_node_get_parent(parent)) {

		upd_node_t*	upd_node;

		upd_node = static_cast<upd_node_t*>(parent);

380
		if (upd_node->table == table && !upd_node->is_delete) {
381 382 383 384 385 386 387 388 389 390 391

			return(TRUE);
		}
	}

	return(FALSE);
}

/*********************************************************************//**
Returns the number of ancestor UPDATE or DELETE nodes of a
cascaded update/delete node.
392
@return number of ancestors */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
393
static MY_ATTRIBUTE((nonnull, warn_unused_result))
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
ulint
row_ins_cascade_n_ancestors(
/*========================*/
	que_node_t*	node)	/*!< in: node in a query graph */
{
	que_node_t*	parent;
	ulint		n_ancestors = 0;

	for (parent = que_node_get_parent(node);
	     que_node_get_type(parent) == QUE_NODE_UPDATE;
	     parent = que_node_get_parent(parent)) {

		n_ancestors++;
	}

	return(n_ancestors);
}

/******************************************************************//**
Calculates the update vector node->cascade->update for a child table in
a cascaded update.
Marko Mäkelä's avatar
Marko Mäkelä committed
415
@return whether any FULLTEXT INDEX is affected */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
416
static MY_ATTRIBUTE((nonnull, warn_unused_result))
Marko Mäkelä's avatar
Marko Mäkelä committed
417
bool
418 419 420 421 422 423 424 425
row_ins_cascade_calc_update_vec(
/*============================*/
	upd_node_t*	node,		/*!< in: update node of the parent
					table */
	dict_foreign_t*	foreign,	/*!< in: foreign key constraint whose
					type is != 0 */
	mem_heap_t*	heap,		/*!< in: memory heap to use as
					temporary storage */
426
	trx_t*		trx)		/*!< in: update transaction */
427
{
428
	upd_node_t*     cascade         = node->cascade_node;
429 430 431 432 433 434 435 436 437 438
	dict_table_t*	table		= foreign->foreign_table;
	dict_index_t*	index		= foreign->foreign_index;
	upd_t*		update;
	dict_table_t*	parent_table;
	dict_index_t*	parent_index;
	upd_t*		parent_update;
	ulint		n_fields_updated;
	ulint		parent_field_no;
	ulint		i;
	ulint		j;
Marko Mäkelä's avatar
Marko Mäkelä committed
439
	bool		doc_id_updated = false;
440
	unsigned	doc_id_pos = 0;
441
	doc_id_t	new_doc_id = FTS_NULL_DOC_ID;
442
	ulint		prefix_col;
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463

	ut_a(cascade);
	ut_a(table);
	ut_a(index);

	/* Calculate the appropriate update vector which will set the fields
	in the child index record to the same value (possibly padded with
	spaces if the column is a fixed length CHAR or FIXBINARY column) as
	the referenced index record will get in the update. */

	parent_table = node->table;
	ut_a(parent_table == foreign->referenced_table);
	parent_index = foreign->referenced_index;
	parent_update = node->update;

	update = cascade->update;

	update->info_bits = 0;

	n_fields_updated = 0;

Marko Mäkelä's avatar
Marko Mäkelä committed
464
	bool affects_fulltext = foreign->affects_fulltext();
465 466 467

	if (table->fts) {
		doc_id_pos = dict_table_get_nth_col_pos(
468
			table, table->fts->doc_col, &prefix_col);
469 470 471 472 473 474
	}

	for (i = 0; i < foreign->n_fields; i++) {

		parent_field_no = dict_table_get_nth_col_pos(
			parent_table,
475 476
			dict_index_get_nth_col_no(parent_index, i),
			&prefix_col);
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496

		for (j = 0; j < parent_update->n_fields; j++) {
			const upd_field_t*	parent_ufield
				= &parent_update->fields[j];

			if (parent_ufield->field_no == parent_field_no) {

				ulint			min_size;
				const dict_col_t*	col;
				ulint			ufield_len;
				upd_field_t*		ufield;

				col = dict_index_get_nth_col(index, i);

				/* A field in the parent index record is
				updated. Let us make the update vector
				field for the child table. */

				ufield = update->fields + n_fields_updated;

497 498 499 500
				ufield->field_no = static_cast<uint16_t>(
					dict_table_get_nth_col_pos(
						table, dict_col_get_no(col),
						&prefix_col));
501 502 503 504 505

				ufield->orig_len = 0;
				ufield->exp = NULL;

				ufield->new_val = parent_ufield->new_val;
506 507
				dfield_get_type(&ufield->new_val)->prtype |=
					col->prtype & DATA_VERSIONED;
508 509 510 511 512 513 514 515 516 517
				ufield_len = dfield_get_len(&ufield->new_val);

				/* Clear the "external storage" flag */
				dfield_set_len(&ufield->new_val, ufield_len);

				/* Do not allow a NOT NULL column to be
				updated as NULL */

				if (dfield_is_null(&ufield->new_val)
				    && (col->prtype & DATA_NOT_NULL)) {
Marko Mäkelä's avatar
Marko Mäkelä committed
518
					goto err_exit;
519 520 521 522 523 524 525
				}

				/* If the new value would not fit in the
				column, do not allow the update */

				if (!dfield_is_null(&ufield->new_val)
				    && dtype_get_at_most_n_mbchars(
526 527
					col->prtype,
					col->mbminlen, col->mbmaxlen,
528 529 530 531 532 533
					col->len,
					ufield_len,
					static_cast<char*>(
						dfield_get_data(
							&ufield->new_val)))
				    < ufield_len) {
Marko Mäkelä's avatar
Marko Mäkelä committed
534
					goto err_exit;
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
				}

				/* If the parent column type has a different
				length than the child column type, we may
				need to pad with spaces the new value of the
				child column */

				min_size = dict_col_get_min_size(col);

				/* Because UNIV_SQL_NULL (the marker
				of SQL NULL values) exceeds all possible
				values of min_size, the test below will
				not hold for SQL NULL columns. */

				if (min_size > ufield_len) {

					byte*	pad;
					ulint	pad_len;
					byte*	padded_data;
					ulint	mbminlen;

					padded_data = static_cast<byte*>(
						mem_heap_alloc(
							heap, min_size));

					pad = padded_data + ufield_len;
					pad_len = min_size - ufield_len;

					memcpy(padded_data,
					       dfield_get_data(&ufield
							       ->new_val),
					       ufield_len);

					mbminlen = dict_col_get_mbminlen(col);

					ut_ad(!(ufield_len % mbminlen));
					ut_ad(!(min_size % mbminlen));

					if (mbminlen == 1
					    && dtype_get_charset_coll(
						    col->prtype)
					    == DATA_MYSQL_BINARY_CHARSET_COLL) {
						/* Do not pad BINARY columns */
Marko Mäkelä's avatar
Marko Mäkelä committed
578
						goto err_exit;
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
					}

					row_mysql_pad_col(mbminlen,
							  pad, pad_len);
					dfield_set_data(&ufield->new_val,
							padded_data, min_size);
				}

				/* If Doc ID is updated, check whether the
				Doc ID is valid */
				if (table->fts
				    && ufield->field_no == doc_id_pos) {
					doc_id_t	n_doc_id;

					n_doc_id =
						table->fts->cache->next_doc_id;

					new_doc_id = fts_read_doc_id(
						static_cast<const byte*>(
							dfield_get_data(
							&ufield->new_val)));

Marko Mäkelä's avatar
Marko Mäkelä committed
601 602 603
					affects_fulltext = true;
					doc_id_updated = true;

604
					if (new_doc_id <= 0) {
605 606 607
						ib::error() << "FTS Doc ID"
							" must be larger than"
							" 0";
Marko Mäkelä's avatar
Marko Mäkelä committed
608
						goto err_exit;
609 610 611
					}

					if (new_doc_id < n_doc_id) {
612 613 614 615 616
						ib::error() << "FTS Doc ID"
							" must be larger than "
							<< n_doc_id - 1
							<< " for table "
							<< table->name;
Marko Mäkelä's avatar
Marko Mäkelä committed
617
						goto err_exit;
618 619 620 621 622 623 624 625
					}
				}

				n_fields_updated++;
			}
		}
	}

Marko Mäkelä's avatar
Marko Mäkelä committed
626 627 628
	if (affects_fulltext) {
		ut_ad(table->fts);

629 630
		if (DICT_TF2_FLAG_IS_SET(table, DICT_TF2_FTS_HAS_DOC_ID)) {
			doc_id_t	doc_id;
631 632 633 634 635
			doc_id_t*	next_doc_id;
			upd_field_t*	ufield;

			next_doc_id = static_cast<doc_id_t*>(mem_heap_alloc(
				heap, sizeof(doc_id_t)));
636 637 638

			ut_ad(!doc_id_updated);
			ufield = update->fields + n_fields_updated;
639 640
			fts_get_next_doc_id(table, next_doc_id);
			doc_id = fts_update_doc_id(table, ufield, next_doc_id);
641
			n_fields_updated++;
642
			fts_trx_add_op(trx, table, doc_id, FTS_INSERT, NULL);
643 644 645
		} else  {
			if (doc_id_updated) {
				ut_ad(new_doc_id);
646 647
				fts_trx_add_op(trx, table, new_doc_id,
					       FTS_INSERT, NULL);
648
			} else {
649 650 651
				ib::error() << "FTS Doc ID must be updated"
					" along with FTS indexed column for"
					" table " << table->name;
Marko Mäkelä's avatar
Marko Mäkelä committed
652 653
err_exit:
				n_fields_updated = ULINT_UNDEFINED;
654 655 656 657 658 659
			}
		}
	}

	update->n_fields = n_fields_updated;

Marko Mäkelä's avatar
Marko Mäkelä committed
660
	return affects_fulltext;
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
}

/*********************************************************************//**
Set detailed error message associated with foreign key errors for
the given transaction. */
static
void
row_ins_set_detailed(
/*=================*/
	trx_t*		trx,		/*!< in: transaction */
	dict_foreign_t*	foreign)	/*!< in: foreign key constraint */
{
	ut_ad(!srv_read_only_mode);

	mutex_enter(&srv_misc_tmpfile_mutex);
	rewind(srv_misc_tmpfile);

	if (os_file_set_eof(srv_misc_tmpfile)) {
679
		ut_print_name(srv_misc_tmpfile, trx,
680
			      foreign->foreign_table_name);
681
		std::string fk_str = dict_print_info_on_foreign_key_in_create_format(
682 683
			trx, foreign, FALSE);
		fputs(fk_str.c_str(), srv_misc_tmpfile);
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
		trx_set_detailed_error_from_file(trx, srv_misc_tmpfile);
	} else {
		trx_set_detailed_error(trx, "temp file operation failed");
	}

	mutex_exit(&srv_misc_tmpfile_mutex);
}

/*********************************************************************//**
Acquires dict_foreign_err_mutex, rewinds dict_foreign_err_file
and displays information about the given transaction.
The caller must release dict_foreign_err_mutex. */
static
void
row_ins_foreign_trx_print(
/*======================*/
	trx_t*	trx)	/*!< in: transaction */
{
	ulint	n_rec_locks;
	ulint	n_trx_locks;
	ulint	heap_size;

706
	ut_ad(!srv_read_only_mode);
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741

	lock_mutex_enter();
	n_rec_locks = lock_number_of_rows_locked(&trx->lock);
	n_trx_locks = UT_LIST_GET_LEN(trx->lock.trx_locks);
	heap_size = mem_heap_get_size(trx->lock.lock_heap);
	lock_mutex_exit();

	mutex_enter(&dict_foreign_err_mutex);
	rewind(dict_foreign_err_file);
	ut_print_timestamp(dict_foreign_err_file);
	fputs(" Transaction:\n", dict_foreign_err_file);

	trx_print_low(dict_foreign_err_file, trx, 600,
		      n_rec_locks, n_trx_locks, heap_size);

	ut_ad(mutex_own(&dict_foreign_err_mutex));
}

/*********************************************************************//**
Reports a foreign key error associated with an update or a delete of a
parent table index entry. */
static
void
row_ins_foreign_report_err(
/*=======================*/
	const char*	errstr,		/*!< in: error string from the viewpoint
					of the parent table */
	que_thr_t*	thr,		/*!< in: query thread whose run_node
					is an update node */
	dict_foreign_t*	foreign,	/*!< in: foreign key constraint */
	const rec_t*	rec,		/*!< in: a matching index record in the
					child table */
	const dtuple_t*	entry)		/*!< in: index entry in the parent
					table */
{
742 743
	std::string fk_str;

744 745 746 747 748 749 750 751 752 753 754 755
	if (srv_read_only_mode) {
		return;
	}

	FILE*	ef	= dict_foreign_err_file;
	trx_t*	trx	= thr_get_trx(thr);

	row_ins_set_detailed(trx, foreign);

	row_ins_foreign_trx_print(trx);

	fputs("Foreign key constraint fails for table ", ef);
756
	ut_print_name(ef, trx, foreign->foreign_table_name);
757
	fputs(":\n", ef);
758
	fk_str = dict_print_info_on_foreign_key_in_create_format(trx, foreign,
759
							TRUE);
760
	fputs(fk_str.c_str(), ef);
761 762
	putc('\n', ef);
	fputs(errstr, ef);
763 764
	fprintf(ef, " in parent table, in index %s",
		foreign->referenced_index->name());
765 766 767 768 769
	if (entry) {
		fputs(" tuple:\n", ef);
		dtuple_print(ef, entry);
	}
	fputs("\nBut in child table ", ef);
770 771
	ut_print_name(ef, trx, foreign->foreign_table_name);
	fprintf(ef, ", in index %s", foreign->foreign_index->name());
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
	if (rec) {
		fputs(", there is a record:\n", ef);
		rec_print(ef, rec, foreign->foreign_index);
	} else {
		fputs(", the record is not available\n", ef);
	}
	putc('\n', ef);

	mutex_exit(&dict_foreign_err_mutex);
}

/*********************************************************************//**
Reports a foreign key error to dict_foreign_err_file when we are trying
to add an index entry to a child table. Note that the adding may be the result
of an update, too. */
static
void
row_ins_foreign_report_add_err(
/*===========================*/
	trx_t*		trx,		/*!< in: transaction */
	dict_foreign_t*	foreign,	/*!< in: foreign key constraint */
	const rec_t*	rec,		/*!< in: a record in the parent table:
					it does not match entry because we
					have an error! */
	const dtuple_t*	entry)		/*!< in: index entry to insert in the
					child table */
{
799 800
	std::string fk_str;

801 802 803 804 805 806 807 808 809 810 811
	if (srv_read_only_mode) {
		return;
	}

	FILE*	ef	= dict_foreign_err_file;

	row_ins_set_detailed(trx, foreign);

	row_ins_foreign_trx_print(trx);

	fputs("Foreign key constraint fails for table ", ef);
812
	ut_print_name(ef, trx, foreign->foreign_table_name);
813
	fputs(":\n", ef);
814
	fk_str = dict_print_info_on_foreign_key_in_create_format(trx, foreign,
815
							TRUE);
816
	fputs(fk_str.c_str(), ef);
817 818 819 820 821 822
	if (foreign->foreign_index) {
		fprintf(ef, " in parent table, in index %s",
			foreign->foreign_index->name());
	} else {
		fputs(" in parent table", ef);
	}
823 824 825 826 827 828 829
	if (entry) {
		fputs(" tuple:\n", ef);
		/* TODO: DB_TRX_ID and DB_ROLL_PTR may be uninitialized.
		It would be better to only display the user columns. */
		dtuple_print(ef, entry);
	}
	fputs("\nBut in parent table ", ef);
830 831 832 833
	ut_print_name(ef, trx, foreign->referenced_table_name);
	fprintf(ef, ", in index %s,\n"
		"the closest match we can find is record:\n",
		foreign->referenced_index->name());
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
	if (rec && page_rec_is_supremum(rec)) {
		/* If the cursor ended on a supremum record, it is better
		to report the previous record in the error message, so that
		the user gets a more descriptive error message. */
		rec = page_rec_get_prev_const(rec);
	}

	if (rec) {
		rec_print(ef, rec, foreign->referenced_index);
	}
	putc('\n', ef);

	mutex_exit(&dict_foreign_err_mutex);
}

/*********************************************************************//**
Invalidate the query cache for the given table. */
static
void
row_ins_invalidate_query_cache(
/*===========================*/
	que_thr_t*	thr,		/*!< in: query thread whose run_node
					is an update node */
	const char*	name)		/*!< in: table name prefixed with
					database name and a '/' character */
{
Marko Mäkelä's avatar
Marko Mäkelä committed
860
	innobase_invalidate_query_cache(thr_get_trx(thr), name);
861
}
862 863 864 865 866 867 868

/** Fill virtual column information in cascade node for the child table.
@param[out]	cascade		child update node
@param[in]	rec		clustered rec of child table
@param[in]	index		clustered index of child table
@param[in]	node		parent update node
@param[in]	foreign		foreign key information
869
@return		error code. */
870
static
871
dberr_t
872 873 874 875 876
row_ins_foreign_fill_virtual(
	upd_node_t*		cascade,
	const rec_t*		rec,
	dict_index_t*		index,
	upd_node_t*		node,
877
	dict_foreign_t*		foreign)
878 879 880
{
	THD*		thd = current_thd;
	row_ext_t*	ext;
881
	rec_offs	offsets_[REC_OFFS_NORMAL_SIZE];
882
	rec_offs_init(offsets_);
883
	const rec_offs*	offsets =
884
		rec_get_offsets(rec, index, offsets_, index->n_core_fields,
885
				ULINT_UNDEFINED, &cascade->heap);
886
	TABLE*		mysql_table= NULL;
887 888 889 890 891 892
	upd_t*		update = cascade->update;
	ulint		n_v_fld = index->table->n_v_def;
	ulint		n_diff;
	upd_field_t*	upd_field;
	dict_vcol_set*	v_cols = foreign->v_cols;
	update->old_vrow = row_build(
893
		ROW_COPY_DATA, index, rec,
894
		offsets, index->table, NULL, NULL,
895
		&ext, update->heap);
896 897
	n_diff = update->n_fields;

898
	ut_ad(index->table->vc_templ != NULL);
899

900 901 902 903
	ib_vcol_row vc(NULL);
	uchar *record = vc.record(thd, index, &mysql_table);
	if (!record) {
		return DB_OUT_OF_MEMORY;
Marko Mäkelä's avatar
Marko Mäkelä committed
904
	}
905 906 907 908 909
	ut_ad(!node->is_delete
	      || (foreign->type & DICT_FOREIGN_ON_DELETE_SET_NULL));
	ut_ad(foreign->type & (DICT_FOREIGN_ON_DELETE_SET_NULL
			       | DICT_FOREIGN_ON_UPDATE_SET_NULL
			       | DICT_FOREIGN_ON_UPDATE_CASCADE));
910

911
	for (uint16_t i = 0; i < n_v_fld; i++) {
912 913 914 915 916 917 918 919 920 921 922 923

		dict_v_col_t*     col = dict_table_get_nth_v_col(
				index->table, i);

		dict_vcol_set::iterator it = v_cols->find(col);

		if (it == v_cols->end()) {
			continue;
		}

		dfield_t*	vfield = innobase_get_computed_value(
				update->old_vrow, col, index,
924
				&vc.heap, update->heap, NULL, thd, mysql_table,
925
				record, NULL, NULL);
926 927

		if (vfield == NULL) {
928
			return DB_COMPUTE_VALUE_FAILED;
929 930
		}

931
		upd_field = update->fields + n_diff;
932 933

		upd_field->old_v_val = static_cast<dfield_t*>(
934 935
			mem_heap_alloc(update->heap,
				       sizeof *upd_field->old_v_val));
936 937 938 939 940

		dfield_copy(upd_field->old_v_val, vfield);

		upd_field_set_v_field_no(upd_field, i, index);

941 942 943 944
		dfield_t* new_vfield = innobase_get_computed_value(
				update->old_vrow, col, index,
				&vc.heap, update->heap, NULL, thd,
				mysql_table, record, NULL,
945
				update);
946

947 948
		if (new_vfield == NULL) {
			return DB_COMPUTE_VALUE_FAILED;
949 950
		}

951 952 953 954 955 956
		dfield_copy(&upd_field->new_val, new_vfield);

		if (!dfield_datas_are_binary_equal(
				upd_field->old_v_val,
				&upd_field->new_val, 0))
			n_diff++;
957 958 959
	}

	update->n_fields = n_diff;
960
	return DB_SUCCESS;
961 962
}

963
#ifdef WITH_WSREP
964
dberr_t wsrep_append_foreign_key(trx_t *trx,
965 966 967
			       dict_foreign_t*	foreign,
			       const rec_t*	clust_rec,
			       dict_index_t*	clust_index,
968 969 970
			       bool		referenced,
			       upd_node_t*	upd_node,
			       bool		pa_disable,
Brave Galera Crew's avatar
Galera4  
Brave Galera Crew committed
971
			       Wsrep_service_key_type	key_type);
972
#endif /* WITH_WSREP */
973 974 975 976 977

/*********************************************************************//**
Perform referential actions or checks when a parent row is deleted or updated
and the constraint had an ON DELETE or ON UPDATE condition which was not
RESTRICT.
978
@return DB_SUCCESS, DB_LOCK_WAIT, or error code */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
979
static MY_ATTRIBUTE((nonnull, warn_unused_result))
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
dberr_t
row_ins_foreign_check_on_constraint(
/*================================*/
	que_thr_t*	thr,		/*!< in: query thread whose run_node
					is an update node */
	dict_foreign_t*	foreign,	/*!< in: foreign key constraint whose
					type is != 0 */
	btr_pcur_t*	pcur,		/*!< in: cursor placed on a matching
					index record in the child table */
	dtuple_t*	entry,		/*!< in: index entry in the parent
					table */
	mtr_t*		mtr)		/*!< in: mtr holding the latch of pcur
					page */
{
	upd_node_t*	node;
	upd_node_t*	cascade;
	dict_table_t*	table		= foreign->foreign_table;
	dict_index_t*	index;
	dict_index_t*	clust_index;
	dtuple_t*	ref;
	const rec_t*	rec;
	const rec_t*	clust_rec;
	const buf_block_t* clust_block;
	upd_t*		update;
	dberr_t		err;
	trx_t*		trx;
	mem_heap_t*	tmp_heap	= NULL;
	doc_id_t	doc_id = FTS_NULL_DOC_ID;

1009
	DBUG_ENTER("row_ins_foreign_check_on_constraint");
1010 1011 1012 1013 1014 1015

	trx = thr_get_trx(thr);

	/* Since we are going to delete or update a row, we have to invalidate
	the MySQL query cache for table. A deadlock of threads is not possible
	here because the caller of this function does not hold any latches with
1016 1017
	the mutex rank above the lock_sys_t::mutex. The query cache mutex
	has a rank just above the lock_sys_t::mutex. */
1018

1019
	row_ins_invalidate_query_cache(thr, table->name.m_name);
1020 1021 1022

	node = static_cast<upd_node_t*>(thr->run_node);

1023
	if (node->is_delete && 0 == (foreign->type
1024 1025 1026 1027 1028 1029 1030
				     & (DICT_FOREIGN_ON_DELETE_CASCADE
					| DICT_FOREIGN_ON_DELETE_SET_NULL))) {

		row_ins_foreign_report_err("Trying to delete",
					   thr, foreign,
					   btr_pcur_get_rec(pcur), entry);

1031
		DBUG_RETURN(DB_ROW_IS_REFERENCED);
1032 1033
	}

1034
	if (!node->is_delete && 0 == (foreign->type
1035 1036 1037 1038 1039 1040 1041 1042 1043
				      & (DICT_FOREIGN_ON_UPDATE_CASCADE
					 | DICT_FOREIGN_ON_UPDATE_SET_NULL))) {

		/* This is an UPDATE */

		row_ins_foreign_report_err("Trying to update",
					   thr, foreign,
					   btr_pcur_get_rec(pcur), entry);

1044
		DBUG_RETURN(DB_ROW_IS_REFERENCED);
1045 1046
	}

1047 1048 1049 1050 1051
	if (node->cascade_node == NULL) {
		node->cascade_heap = mem_heap_create(128);
		node->cascade_node = row_create_update_node_for_mysql(
			table, node->cascade_heap);
		que_node_set_parent(node->cascade_node, node);
1052

1053 1054
	}
	cascade = node->cascade_node;
1055 1056 1057
	cascade->table = table;
	cascade->foreign = foreign;

1058
	if (node->is_delete
1059
	    && (foreign->type & DICT_FOREIGN_ON_DELETE_CASCADE)) {
1060
		cascade->is_delete = PLAIN_DELETE;
1061
	} else {
1062
		cascade->is_delete = NO_DELETE;
1063 1064 1065 1066 1067 1068 1069 1070 1071

		if (foreign->n_fields > cascade->update_n_fields) {
			/* We have to make the update vector longer */

			cascade->update = upd_create(foreign->n_fields,
						     node->cascade_heap);
			cascade->update_n_fields = foreign->n_fields;
		}

Marko Mäkelä's avatar
Marko Mäkelä committed
1072 1073 1074 1075 1076 1077 1078 1079 1080
		/* We do not allow cyclic cascaded updating (DELETE is
		allowed, but not UPDATE) of the same table, as this
		can lead to an infinite cycle. Check that we are not
		updating the same table which is already being
		modified in this cascade chain. We have to check this
		also because the modification of the indexes of a
		'parent' table may still be incomplete, and we must
		avoid seeing the indexes of the parent table in an
		inconsistent state! */
1081

Marko Mäkelä's avatar
Marko Mäkelä committed
1082
		if (row_ins_cascade_ancestor_updates_table(cascade, table)) {
1083

Marko Mäkelä's avatar
Marko Mäkelä committed
1084 1085
			/* We do not know if this would break foreign key
			constraints, but play safe and return an error */
1086

Marko Mäkelä's avatar
Marko Mäkelä committed
1087
			err = DB_ROW_IS_REFERENCED;
1088

Marko Mäkelä's avatar
Marko Mäkelä committed
1089 1090 1091 1092 1093
			row_ins_foreign_report_err(
				"Trying an update, possibly causing a cyclic"
				" cascaded update\n"
				"in the child table,", thr, foreign,
				btr_pcur_get_rec(pcur), entry);
1094

Marko Mäkelä's avatar
Marko Mäkelä committed
1095 1096
			goto nonstandard_exit_func;
		}
1097 1098
	}

1099 1100
	if (row_ins_cascade_n_ancestors(cascade) >= FK_MAX_CASCADE_DEL) {
		err = DB_FOREIGN_EXCEED_MAX_CASCADE;
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

		row_ins_foreign_report_err(
			"Trying a too deep cascaded delete or update\n",
			thr, foreign, btr_pcur_get_rec(pcur), entry);

		goto nonstandard_exit_func;
	}

	index = btr_pcur_get_btr_cur(pcur)->index;

	ut_a(index == foreign->foreign_index);

	rec = btr_pcur_get_rec(pcur);

	tmp_heap = mem_heap_create(256);

	if (dict_index_is_clust(index)) {
		/* pcur is already positioned in the clustered index of
		the child table */

		clust_index = index;
		clust_rec = rec;
		clust_block = btr_pcur_get_block(pcur);
	} else {
		/* We have to look for the record in the clustered index
		in the child table */

		clust_index = dict_table_get_first_index(table);

		ref = row_build_row_ref(ROW_COPY_POINTERS, index, rec,
					tmp_heap);
		btr_pcur_open_with_no_init(clust_index, ref,
					   PAGE_CUR_LE, BTR_SEARCH_LEAF,
1134
					   cascade->pcur, mtr);
1135 1136 1137 1138 1139 1140 1141 1142

		clust_rec = btr_pcur_get_rec(cascade->pcur);
		clust_block = btr_pcur_get_block(cascade->pcur);

		if (!page_rec_is_user_rec(clust_rec)
		    || btr_pcur_get_low_match(cascade->pcur)
		    < dict_index_get_n_unique(clust_index)) {

1143 1144 1145
			ib::error() << "In cascade of a foreign key op index "
				<< index->name
				<< " of table " << index->table->name;
1146

1147
			fputs("InnoDB: record ", stderr);
1148 1149 1150 1151 1152 1153
			rec_print(stderr, rec, index);
			fputs("\n"
			      "InnoDB: clustered record ", stderr);
			rec_print(stderr, clust_rec, clust_index);
			fputs("\n"
			      "InnoDB: Submit a detailed bug report to"
1154
			      " https://jira.mariadb.org/\n", stderr);
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
			ut_ad(0);
			err = DB_SUCCESS;

			goto nonstandard_exit_func;
		}
	}

	/* Set an X-lock on the row to delete or update in the child table */

	err = lock_table(0, table, LOCK_IX, thr);

	if (err == DB_SUCCESS) {
		/* Here it suffices to use a LOCK_REC_NOT_GAP type lock;
		we already have a normal shared lock on the appropriate
		gap if the search criterion was not unique */

		err = lock_clust_rec_read_check_and_lock_alt(
			0, clust_block, clust_rec, clust_index,
			LOCK_X, LOCK_REC_NOT_GAP, thr);
	}

	if (err != DB_SUCCESS) {

		goto nonstandard_exit_func;
	}

	if (rec_get_deleted_flag(clust_rec, dict_table_is_comp(table))) {
1182 1183 1184
		/* In delete-marked records, DB_TRX_ID must
		always refer to an existing undo log record. */
		ut_ad(rec_get_trx_id(clust_rec, clust_index));
1185 1186 1187 1188 1189 1190 1191 1192 1193
		/* This can happen if there is a circular reference of
		rows such that cascading delete comes to delete a row
		already in the process of being delete marked */
		err = DB_SUCCESS;

		goto nonstandard_exit_func;
	}

	if (table->fts) {
1194 1195
		doc_id = fts_get_doc_id_from_rec(
			clust_rec, clust_index,
Marko Mäkelä's avatar
Marko Mäkelä committed
1196 1197
			rec_get_offsets(clust_rec, clust_index, NULL,
					clust_index->n_core_fields,
1198
					ULINT_UNDEFINED, &tmp_heap));
1199 1200
	}

1201
	if (node->is_delete
1202 1203 1204 1205 1206 1207 1208 1209 1210
	    ? (foreign->type & DICT_FOREIGN_ON_DELETE_SET_NULL)
	    : (foreign->type & DICT_FOREIGN_ON_UPDATE_SET_NULL)) {
		/* Build the appropriate update vector which sets
		foreign->n_fields first fields in rec to SQL NULL */

		update = cascade->update;

		update->info_bits = 0;
		update->n_fields = foreign->n_fields;
1211 1212
		MEM_UNDEFINED(update->fields,
			      update->n_fields * sizeof *update->fields);
1213

Marko Mäkelä's avatar
Marko Mäkelä committed
1214
		for (ulint i = 0; i < foreign->n_fields; i++) {
1215
			upd_field_t*	ufield = &update->fields[i];
1216 1217 1218
			ulint		col_no = dict_index_get_nth_col_no(
						index, i);
			ulint		prefix_col;
1219

1220 1221 1222
			ufield->field_no = static_cast<uint16_t>(
				dict_table_get_nth_col_pos(
					table, col_no, &prefix_col));
1223 1224 1225 1226
			dict_col_t*	col = dict_table_get_nth_col(
				table, col_no);
			dict_col_copy_type(col, dfield_get_type(&ufield->new_val));

1227 1228 1229 1230 1231
			ufield->orig_len = 0;
			ufield->exp = NULL;
			dfield_set_null(&ufield->new_val);
		}

1232
		if (foreign->affects_fulltext()) {
1233
			fts_trx_add_op(trx, table, doc_id, FTS_DELETE, NULL);
1234
		}
1235 1236 1237

		if (foreign->v_cols != NULL
		    && foreign->v_cols->size() > 0) {
1238
			err = row_ins_foreign_fill_virtual(
1239
				cascade, clust_rec, clust_index,
1240
				node, foreign);
1241 1242 1243 1244 1245

			if (err != DB_SUCCESS) {
				goto nonstandard_exit_func;
			}
		}
Marko Mäkelä's avatar
Marko Mäkelä committed
1246
	} else if (table->fts && cascade->is_delete == PLAIN_DELETE
1247
		   && foreign->affects_fulltext()) {
1248
		/* DICT_FOREIGN_ON_DELETE_CASCADE case */
1249
		fts_trx_add_op(trx, table, doc_id, FTS_DELETE, NULL);
1250 1251
	}

1252
	if (!node->is_delete
1253 1254 1255 1256 1257
	    && (foreign->type & DICT_FOREIGN_ON_UPDATE_CASCADE)) {

		/* Build the appropriate update vector which sets changing
		foreign->n_fields first fields in rec to new values */

Marko Mäkelä's avatar
Marko Mäkelä committed
1258
		bool affects_fulltext = row_ins_cascade_calc_update_vec(
1259
			node, foreign, tmp_heap, trx);
1260

Marko Mäkelä's avatar
Marko Mäkelä committed
1261
		if (foreign->v_cols && !foreign->v_cols->empty()) {
1262
			err = row_ins_foreign_fill_virtual(
1263
				cascade, clust_rec, clust_index,
1264
				node, foreign);
1265 1266 1267 1268 1269 1270

			if (err != DB_SUCCESS) {
				goto nonstandard_exit_func;
			}
		}

Marko Mäkelä's avatar
Marko Mäkelä committed
1271 1272
		switch (cascade->update->n_fields) {
		case ULINT_UNDEFINED:
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
			err = DB_ROW_IS_REFERENCED;

			row_ins_foreign_report_err(
				"Trying a cascaded update where the"
				" updated value in the child\n"
				"table would not fit in the length"
				" of the column, or the value would\n"
				"be NULL and the column is"
				" declared as not NULL in the child table,",
				thr, foreign, btr_pcur_get_rec(pcur), entry);

			goto nonstandard_exit_func;
Marko Mäkelä's avatar
Marko Mäkelä committed
1285
		case 0:
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
			/* The update does not change any columns referred
			to in this foreign key constraint: no need to do
			anything */

			err = DB_SUCCESS;

			goto nonstandard_exit_func;
		}

		/* Mark the old Doc ID as deleted */
Marko Mäkelä's avatar
Marko Mäkelä committed
1296
		if (affects_fulltext) {
1297
			ut_ad(table->fts);
1298
			fts_trx_add_op(trx, table, doc_id, FTS_DELETE, NULL);
1299 1300 1301
		}
	}

1302 1303
	if (table->versioned() && cascade->is_delete != PLAIN_DELETE
	    && cascade->update->affects_versioned()) {
1304
		ut_ad(!cascade->historical_heap);
1305
		cascade->historical_heap = mem_heap_create(srv_page_size);
1306
		cascade->historical_row = row_build(
1307
			ROW_COPY_DATA, clust_index, clust_rec, NULL, table,
1308
			NULL, NULL, NULL, cascade->historical_heap);
1309 1310
	}

1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
	/* Store pcur position and initialize or store the cascade node
	pcur stored position */

	btr_pcur_store_position(pcur, mtr);

	if (index == clust_index) {
		btr_pcur_copy_stored_position(cascade->pcur, pcur);
	} else {
		btr_pcur_store_position(cascade->pcur, mtr);
	}

1322
#ifdef WITH_WSREP
1323 1324 1325 1326 1327 1328 1329
	if (trx->is_wsrep()) {
		err = wsrep_append_foreign_key(trx, foreign, clust_rec, clust_index,
					       false, NULL, true,
					       WSREP_SERVICE_KEY_EXCLUSIVE);
		if (err != DB_SUCCESS) {
			goto nonstandard_exit_func;
		}
1330 1331
	}
#endif /* WITH_WSREP */
1332 1333 1334 1335 1336 1337
	mtr_commit(mtr);

	ut_a(cascade->pcur->rel_pos == BTR_PCUR_ON);

	cascade->state = UPD_NODE_UPDATE_CLUSTERED;

1338 1339
	err = row_update_cascade_for_mysql(thr, cascade,
					   foreign->foreign_table);
1340 1341 1342

	/* Release the data dictionary latch for a while, so that we do not
	starve other threads from doing CREATE TABLE etc. if we have a huge
1343
	cascaded operation running. */
1344 1345 1346 1347 1348 1349 1350

	row_mysql_unfreeze_data_dictionary(thr_get_trx(thr));

	DEBUG_SYNC_C("innodb_dml_cascade_dict_unfreeze");

	row_mysql_freeze_data_dictionary(thr_get_trx(thr));

1351
	mtr_start(mtr);
1352 1353 1354 1355 1356 1357 1358 1359 1360

	/* Restore pcur position */

	btr_pcur_restore_position(BTR_SEARCH_LEAF, pcur, mtr);

	if (tmp_heap) {
		mem_heap_free(tmp_heap);
	}

1361
	DBUG_RETURN(err);
1362 1363

nonstandard_exit_func:
1364

1365 1366 1367 1368 1369 1370 1371
	if (tmp_heap) {
		mem_heap_free(tmp_heap);
	}

	btr_pcur_store_position(pcur, mtr);

	mtr_commit(mtr);
1372
	mtr_start(mtr);
1373 1374 1375

	btr_pcur_restore_position(BTR_SEARCH_LEAF, pcur, mtr);

1376
	DBUG_RETURN(err);
1377 1378 1379 1380 1381
}

/*********************************************************************//**
Sets a shared lock on a record. Used in locking possible duplicate key
records and also in checking foreign key constraints.
1382
@return DB_SUCCESS, DB_SUCCESS_LOCKED_REC, or error code */
1383 1384 1385 1386
static
dberr_t
row_ins_set_shared_rec_lock(
/*========================*/
1387
	unsigned		type,	/*!< in: LOCK_ORDINARY, LOCK_GAP, or
1388 1389 1390 1391
					LOCK_REC_NOT_GAP type lock */
	const buf_block_t*	block,	/*!< in: buffer block of rec */
	const rec_t*		rec,	/*!< in: record */
	dict_index_t*		index,	/*!< in: index */
1392
	const rec_offs*		offsets,/*!< in: rec_get_offsets(rec, index) */
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
	que_thr_t*		thr)	/*!< in: query thread */
{
	dberr_t	err;

	ut_ad(rec_offs_validate(rec, index, offsets));

	if (dict_index_is_clust(index)) {
		err = lock_clust_rec_read_check_and_lock(
			0, block, rec, index, offsets, LOCK_S, type, thr);
	} else {
		err = lock_sec_rec_read_check_and_lock(
			0, block, rec, index, offsets, LOCK_S, type, thr);
	}

	return(err);
}

/*********************************************************************//**
Sets a exclusive lock on a record. Used in locking possible duplicate key
records
1413
@return DB_SUCCESS, DB_SUCCESS_LOCKED_REC, or error code */
1414 1415 1416 1417
static
dberr_t
row_ins_set_exclusive_rec_lock(
/*===========================*/
1418
	unsigned		type,	/*!< in: LOCK_ORDINARY, LOCK_GAP, or
1419 1420 1421 1422
					LOCK_REC_NOT_GAP type lock */
	const buf_block_t*	block,	/*!< in: buffer block of rec */
	const rec_t*		rec,	/*!< in: record */
	dict_index_t*		index,	/*!< in: index */
1423
	const rec_offs*		offsets,/*!< in: rec_get_offsets(rec, index) */
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
	que_thr_t*		thr)	/*!< in: query thread */
{
	dberr_t	err;

	ut_ad(rec_offs_validate(rec, index, offsets));

	if (dict_index_is_clust(index)) {
		err = lock_clust_rec_read_check_and_lock(
			0, block, rec, index, offsets, LOCK_X, type, thr);
	} else {
		err = lock_sec_rec_read_check_and_lock(
			0, block, rec, index, offsets, LOCK_X, type, thr);
	}

	return(err);
}

/***************************************************************//**
Checks if foreign key constraint fails for an index entry. Sets shared locks
which lock either the success or the failure of the constraint. NOTE that
1444
the caller must have a shared latch on dict_sys.latch.
1445
@return DB_SUCCESS, DB_NO_REFERENCED_ROW, or DB_ROW_IS_REFERENCED */
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
dberr_t
row_ins_check_foreign_constraint(
/*=============================*/
	ibool		check_ref,/*!< in: TRUE if we want to check that
				the referenced table is ok, FALSE if we
				want to check the foreign key table */
	dict_foreign_t*	foreign,/*!< in: foreign constraint; NOTE that the
				tables mentioned in it must be in the
				dictionary cache if they exist at all */
	dict_table_t*	table,	/*!< in: if check_ref is TRUE, then the foreign
				table, else the referenced table */
	dtuple_t*	entry,	/*!< in: index entry for index */
	que_thr_t*	thr)	/*!< in: query thread */
{
	dberr_t		err;
	upd_node_t*	upd_node;
	dict_table_t*	check_table;
	dict_index_t*	check_index;
	ulint		n_fields_cmp;
	btr_pcur_t	pcur;
	int		cmp;
	mtr_t		mtr;
	trx_t*		trx		= thr_get_trx(thr);
	mem_heap_t*	heap		= NULL;
1470 1471
	rec_offs	offsets_[REC_OFFS_NORMAL_SIZE];
	rec_offs*	offsets		= offsets_;
1472

1473 1474 1475 1476
	bool		skip_gap_lock;

	skip_gap_lock = (trx->isolation_level <= TRX_ISO_READ_COMMITTED);

1477 1478
	DBUG_ENTER("row_ins_check_foreign_constraint");

1479 1480
	rec_offs_init(offsets_);

1481 1482 1483
#ifdef WITH_WSREP
	upd_node= NULL;
#endif /* WITH_WSREP */
1484

1485
	ut_ad(rw_lock_own(&dict_sys.latch, RW_LOCK_S));
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497

	err = DB_SUCCESS;

	if (trx->check_foreigns == FALSE) {
		/* The user has suppressed foreign key checks currently for
		this session */
		goto exit_func;
	}

	/* If any of the foreign key fields in entry is SQL NULL, we
	suppress the foreign key check: this is compatible with Oracle,
	for example */
1498 1499 1500
	for (ulint i = 0; i < entry->n_fields; i++) {
		dfield_t* field = dtuple_get_nth_field(entry, i);
		if (i < foreign->n_fields && dfield_is_null(field)) {
1501 1502
			goto exit_func;
		}
Sergei Golubchik's avatar
Sergei Golubchik committed
1503
		/* System Versioning: if row_end != Inf, we
1504
		suppress the foreign key check */
1505
		if (field->type.vers_sys_end() && field->vers_history_row()) {
1506
			goto exit_func;
1507
		}
1508 1509 1510 1511 1512
	}

	if (que_node_get_type(thr->run_node) == QUE_NODE_UPDATE) {
		upd_node = static_cast<upd_node_t*>(thr->run_node);

Marko Mäkelä's avatar
Marko Mäkelä committed
1513 1514
		if (upd_node->is_delete != PLAIN_DELETE
		    && upd_node->foreign == foreign) {
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
			/* If a cascaded update is done as defined by a
			foreign key constraint, do not check that
			constraint for the child row. In ON UPDATE CASCADE
			the update of the parent row is only half done when
			we come here: if we would check the constraint here
			for the child row it would fail.

			A QUESTION remains: if in the child table there are
			several constraints which refer to the same parent
			table, we should merge all updates to the child as
			one update? And the updates can be contradictory!
			Currently we just perform the update associated
			with each foreign key constraint, one after
			another, and the user has problems predicting in
			which order they are performed. */

			goto exit_func;
		}
	}

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
	if (que_node_get_type(thr->run_node) == QUE_NODE_INSERT) {
		ins_node_t* insert_node =
			static_cast<ins_node_t*>(thr->run_node);
		dict_table_t* table = insert_node->index->table;
		if (table->versioned()) {
			dfield_t* row_end = dtuple_get_nth_field(
				insert_node->row, table->vers_end);
			if (row_end->vers_history_row()) {
				goto exit_func;
			}
		}
	}

1548 1549 1550 1551 1552 1553 1554 1555 1556
	if (check_ref) {
		check_table = foreign->referenced_table;
		check_index = foreign->referenced_index;
	} else {
		check_table = foreign->foreign_table;
		check_index = foreign->foreign_index;
	}

	if (check_table == NULL
1557
	    || !check_table->is_readable()
1558
	    || check_index == NULL) {
1559

1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
		FILE*	ef = dict_foreign_err_file;
		std::string fk_str;

		row_ins_set_detailed(trx, foreign);
		row_ins_foreign_trx_print(trx);

		fputs("Foreign key constraint fails for table ", ef);
		ut_print_name(ef, trx, check_ref
			      ? foreign->foreign_table_name
			      : foreign->referenced_table_name);
		fputs(":\n", ef);
		fk_str = dict_print_info_on_foreign_key_in_create_format(
			trx, foreign, TRUE);
		fputs(fk_str.c_str(), ef);
		if (check_ref) {
			if (foreign->foreign_index) {
				fprintf(ef, "\nTrying to add to index %s"
					" tuple:\n",
					foreign->foreign_index->name());
			} else {
				fputs("\nTrying to add tuple:\n", ef);
			}
1582 1583
			dtuple_print(ef, entry);
			fputs("\nBut the parent table ", ef);
1584 1585
			ut_print_name(ef, trx, foreign->referenced_table_name);
			fputs("\nor its .ibd file or the required index does"
1586 1587
			      " not currently exist!\n", ef);
			err = DB_NO_REFERENCED_ROW;
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
		} else {
			if (foreign->referenced_index) {
				fprintf(ef, "\nTrying to modify index %s"
					" tuple:\n",
					foreign->referenced_index->name());
			} else {
				fputs("\nTrying to modify tuple:\n", ef);
			}
			dtuple_print(ef, entry);
			fputs("\nBut the referencing table ", ef);
			ut_print_name(ef, trx, foreign->foreign_table_name);
			fputs("\nor its .ibd file or the required index does"
			      " not currently exist!\n", ef);
			err = DB_ROW_IS_REFERENCED;
1602 1603
		}

1604
		mutex_exit(&dict_foreign_err_mutex);
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
		goto exit_func;
	}

	if (check_table != table) {
		/* We already have a LOCK_IX on table, but not necessarily
		on check_table */

		err = lock_table(0, check_table, LOCK_IS, thr);

		if (err != DB_SUCCESS) {

			goto do_possible_lock_wait;
		}
	}

1620
	mtr_start(&mtr);
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641

	/* Store old value on n_fields_cmp */

	n_fields_cmp = dtuple_get_n_fields_cmp(entry);

	dtuple_set_n_fields_cmp(entry, foreign->n_fields);

	btr_pcur_open(check_index, entry, PAGE_CUR_GE,
		      BTR_SEARCH_LEAF, &pcur, &mtr);

	/* Scan index records and check if there is a matching record */

	do {
		const rec_t*		rec = btr_pcur_get_rec(&pcur);
		const buf_block_t*	block = btr_pcur_get_block(&pcur);

		if (page_rec_is_infimum(rec)) {

			continue;
		}

1642 1643
		offsets = rec_get_offsets(rec, check_index, offsets,
					  check_index->n_core_fields,
1644
					  ULINT_UNDEFINED, &heap);
1645 1646 1647

		if (page_rec_is_supremum(rec)) {

1648 1649 1650 1651 1652
			if (skip_gap_lock) {

				continue;
			}

1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
			err = row_ins_set_shared_rec_lock(LOCK_ORDINARY, block,
							  rec, check_index,
							  offsets, thr);
			switch (err) {
			case DB_SUCCESS_LOCKED_REC:
			case DB_SUCCESS:
				continue;
			default:
				goto end_scan;
			}
		}

		cmp = cmp_dtuple_rec(entry, rec, offsets);

		if (cmp == 0) {
			if (rec_get_deleted_flag(rec,
						 rec_offs_comp(offsets))) {
1670 1671 1672 1673 1674 1675
				/* In delete-marked records, DB_TRX_ID must
				always refer to an existing undo log record. */
				ut_ad(!dict_index_is_clust(check_index)
				      || row_get_rec_trx_id(rec, check_index,
							    offsets));

1676
				err = row_ins_set_shared_rec_lock(
1677 1678 1679
					skip_gap_lock
					? LOCK_REC_NOT_GAP
					: LOCK_ORDINARY, block,
1680 1681 1682 1683 1684 1685 1686 1687 1688
					rec, check_index, offsets, thr);
				switch (err) {
				case DB_SUCCESS_LOCKED_REC:
				case DB_SUCCESS:
					break;
				default:
					goto end_scan;
				}
			} else {
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
				if (check_table->versioned()) {
					bool history_row = false;

					if (check_index->is_primary()) {
						history_row = check_index->
							vers_history_row(rec,
									 offsets);
					} else if (check_index->
						vers_history_row(rec,
								 history_row)) {
						break;
					}

					if (history_row) {
						continue;
					}
				}
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
				/* Found a matching record. Lock only
				a record because we can allow inserts
				into gaps */

				err = row_ins_set_shared_rec_lock(
					LOCK_REC_NOT_GAP, block,
					rec, check_index, offsets, thr);

				switch (err) {
				case DB_SUCCESS_LOCKED_REC:
				case DB_SUCCESS:
					break;
				default:
					goto end_scan;
				}

				if (check_ref) {
					err = DB_SUCCESS;
1724
#ifdef WITH_WSREP
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
					if (trx->is_wsrep()) {
						err = wsrep_append_foreign_key(
							thr_get_trx(thr),
							foreign,
							rec,
							check_index,
							check_ref,
							upd_node,
						        false,
						        WSREP_SERVICE_KEY_REFERENCE);
1735
					}
1736
#endif /* WITH_WSREP */
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
					goto end_scan;
				} else if (foreign->type != 0) {
					/* There is an ON UPDATE or ON DELETE
					condition: check them in a separate
					function */

					err = row_ins_foreign_check_on_constraint(
						thr, foreign, &pcur, entry,
						&mtr);
					if (err != DB_SUCCESS) {
						/* Since reporting a plain
						"duplicate key" error
						message to the user in
						cases where a long CASCADE
						operation would lead to a
						duplicate key in some
						other table is very
						confusing, map duplicate
						key errors resulting from
						FK constraints to a
						separate error code. */

						if (err == DB_DUPLICATE_KEY) {
							err = DB_FOREIGN_DUPLICATE_KEY;
						}

						goto end_scan;
					}

					/* row_ins_foreign_check_on_constraint
					may have repositioned pcur on a
					different block */
					block = btr_pcur_get_block(&pcur);
				} else {
					row_ins_foreign_report_err(
						"Trying to delete or update",
						thr, foreign, rec, entry);

					err = DB_ROW_IS_REFERENCED;
					goto end_scan;
				}
			}
		} else {
			ut_a(cmp < 0);

1782 1783 1784
			err = skip_gap_lock
				? DB_SUCCESS
				: row_ins_set_shared_rec_lock(
1785 1786
					LOCK_GAP, block,
					rec, check_index, offsets, thr);
1787 1788 1789

			switch (err) {
			case DB_SUCCESS_LOCKED_REC:
1790 1791
				err = DB_SUCCESS;
				/* fall through */
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
			case DB_SUCCESS:
				if (check_ref) {
					err = DB_NO_REFERENCED_ROW;
					row_ins_foreign_report_add_err(
						trx, foreign, rec, entry);
				}
			default:
				break;
			}

			goto end_scan;
		}
	} while (btr_pcur_move_to_next(&pcur, &mtr));

	if (check_ref) {
		row_ins_foreign_report_add_err(
			trx, foreign, btr_pcur_get_rec(&pcur), entry);
		err = DB_NO_REFERENCED_ROW;
	} else {
		err = DB_SUCCESS;
	}

end_scan:
	btr_pcur_close(&pcur);

	mtr_commit(&mtr);

	/* Restore old value */
	dtuple_set_n_fields_cmp(entry, n_fields_cmp);

do_possible_lock_wait:
	if (err == DB_LOCK_WAIT) {
		trx->error_state = err;

		que_thr_stop_for_mysql(thr);

1828 1829
		thr->lock_state = QUE_THR_LOCK_ROW;

1830
		check_table->inc_fk_checks();
1831

1832 1833
		lock_wait_suspend_thread(thr);

1834 1835
		thr->lock_state = QUE_THR_LOCK_NOLOCK;

1836 1837 1838
		err = trx->error_state;
		if (err != DB_SUCCESS) {
		} else if (check_table->to_be_dropped) {
1839
			err = DB_LOCK_WAIT_TIMEOUT;
1840 1841
		} else {
			err = DB_LOCK_WAIT;
1842
		}
1843 1844

		check_table->dec_fk_checks();
1845 1846 1847
	}

exit_func:
1848
	if (heap != NULL) {
1849 1850
		mem_heap_free(heap);
	}
1851 1852

	DBUG_RETURN(err);
1853 1854
}

1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
/** Sets the values of the dtuple fields in ref_entry from the values of
foreign columns in entry.
@param[in]	foreign		foreign key constraint
@param[in]	index		clustered index
@param[in]	entry		tuple of clustered index
@param[in]	ref_entry	tuple of foreign columns
@return true if all foreign key fields present in clustered index */
static
bool row_ins_foreign_index_entry(dict_foreign_t *foreign,
                                 const dict_index_t *index,
                                 const dtuple_t *entry,
                                 dtuple_t *ref_entry)
{
  for (ulint i= 0; i < foreign->n_fields; i++)
  {
    for (ulint j= 0; j < index->n_fields; j++)
    {
1872 1873 1874 1875 1876 1877 1878 1879
      const dict_col_t *col= dict_index_get_nth_col(index, j);

      /* A clustered index may contain instantly dropped columns,
      which must be skipped. */
      if (col->is_dropped())
        continue;

      const char *col_name= dict_table_get_col_name(index->table, col->ind);
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
      if (0 == innobase_strcasecmp(col_name, foreign->foreign_col_names[i]))
      {
        dfield_copy(&ref_entry->fields[i], &entry->fields[j]);
        goto got_match;
      }
    }
    return false;
got_match:
    continue;
  }

  return true;
}

1894 1895 1896 1897 1898 1899
/***************************************************************//**
Checks if foreign key constraints fail for an index entry. If index
is not mentioned in any constraint, this function does nothing,
Otherwise does searches to the indexes of referenced tables and
sets shared locks which lock either the success or the failure of
a constraint.
1900
@return DB_SUCCESS or error code */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
1901
static MY_ATTRIBUTE((nonnull, warn_unused_result))
1902 1903 1904 1905 1906
dberr_t
row_ins_check_foreign_constraints(
/*==============================*/
	dict_table_t*	table,	/*!< in: table */
	dict_index_t*	index,	/*!< in: index */
1907
	bool		pk,	/*!< in: index->is_primary() */
1908
	dtuple_t*	entry,	/*!< in: index entry for index */
1909
	que_thr_t*	thr)	/*!< in: query thread */
1910 1911
{
	dict_foreign_t*	foreign;
1912
	dberr_t		err = DB_SUCCESS;
1913 1914
	trx_t*		trx;
	ibool		got_s_lock	= FALSE;
1915
	mem_heap_t*	heap = NULL;
1916

1917 1918
	DBUG_ASSERT(index->is_primary() == pk);

1919 1920 1921 1922 1923
	trx = thr_get_trx(thr);

	DEBUG_SYNC_C_IF_THD(thr_get_trx(thr)->mysql_thd,
			    "foreign_constraint_check_for_ins");

Sergei Golubchik's avatar
5.6.20  
Sergei Golubchik committed
1924
	for (dict_foreign_set::iterator it = table->foreign_set.begin();
1925
	     err == DB_SUCCESS && it != table->foreign_set.end();
Sergei Golubchik's avatar
5.6.20  
Sergei Golubchik committed
1926 1927 1928 1929
	     ++it) {

		foreign = *it;

1930 1931
		if (foreign->foreign_index == index
		    || (pk && !foreign->foreign_index)) {
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954

			dtuple_t*	ref_tuple = entry;
			if (UNIV_UNLIKELY(!foreign->foreign_index)) {
				/* Change primary key entry to
				foreign key index entry */
				if (!heap) {
					heap = mem_heap_create(1000);
				} else {
					mem_heap_empty(heap);
				}

				ref_tuple = dtuple_create(
					heap, foreign->n_fields);
				dtuple_set_n_fields_cmp(
					ref_tuple, foreign->n_fields);
				if (!row_ins_foreign_index_entry(
					foreign, index, entry, ref_tuple)) {
					err = DB_NO_REFERENCED_ROW;
					break;
				}

			}

1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
			dict_table_t*	ref_table = NULL;
			dict_table_t*	referenced_table
						= foreign->referenced_table;

			if (referenced_table == NULL) {

				ref_table = dict_table_open_on_name(
					foreign->referenced_table_name_lookup,
					FALSE, FALSE, DICT_ERR_IGNORE_NONE);
			}

			if (0 == trx->dict_operation_lock_mode) {
				got_s_lock = TRUE;

				row_mysql_freeze_data_dictionary(trx);
			}

1972
			if (referenced_table) {
Marko Mäkelä's avatar
Marko Mäkelä committed
1973
				foreign->foreign_table->inc_fk_checks();
1974 1975
			}

1976
			/* NOTE that if the thread ends up waiting for a lock
1977
			we will release dict_sys.latch temporarily!
1978 1979 1980 1981
			But the counter on the table protects the referenced
			table from being dropped while the check is running. */

			err = row_ins_check_foreign_constraint(
1982
				TRUE, foreign, table, ref_tuple, thr);
1983

1984
			if (referenced_table) {
Marko Mäkelä's avatar
Marko Mäkelä committed
1985
				foreign->foreign_table->dec_fk_checks();
1986 1987
			}

1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
			if (got_s_lock) {
				row_mysql_unfreeze_data_dictionary(trx);
			}

			if (ref_table != NULL) {
				dict_table_close(ref_table, FALSE, FALSE);
			}
		}
	}

1998 1999 2000 2001 2002
	if (UNIV_LIKELY_NULL(heap)) {
		mem_heap_free(heap);
	}

	return err;
2003 2004 2005 2006 2007
}

/***************************************************************//**
Checks if a unique key violation to rec would occur at the index entry
insert.
2008
@return TRUE if error */
2009 2010 2011 2012 2013 2014 2015 2016 2017
static
ibool
row_ins_dupl_error_with_rec(
/*========================*/
	const rec_t*	rec,	/*!< in: user record; NOTE that we assume
				that the caller already has a record lock on
				the record! */
	const dtuple_t*	entry,	/*!< in: entry to insert */
	dict_index_t*	index,	/*!< in: index */
2018
	const rec_offs*	offsets)/*!< in: rec_get_offsets(rec, index) */
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
{
	ulint	matched_fields;
	ulint	n_unique;
	ulint	i;

	ut_ad(rec_offs_validate(rec, index, offsets));

	n_unique = dict_index_get_n_unique(index);

	matched_fields = 0;

2030
	cmp_dtuple_rec_with_match(entry, rec, offsets, &matched_fields);
2031 2032 2033 2034 2035 2036 2037 2038 2039

	if (matched_fields < n_unique) {

		return(FALSE);
	}

	/* In a unique secondary index we allow equal key values if they
	contain SQL NULLs */

2040
	if (!dict_index_is_clust(index)) {
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052

		for (i = 0; i < n_unique; i++) {
			if (dfield_is_null(dtuple_get_nth_field(entry, i))) {

				return(FALSE);
			}
		}
	}

	return(!rec_get_deleted_flag(rec, rec_offs_comp(offsets)));
}

Marko Mäkelä's avatar
Marko Mäkelä committed
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
/** Determine whether a history row was inserted by this transaction
(row TRX_ID is the same as current TRX_ID).
@param index  secondary index
@param rec    secondary index record
@param trx    transaction
@return error code
@retval DB_SUCCESS                on success
@retval DB_FOREIGN_DUPLICATE_KEY  if a history row was inserted by trx */
static dberr_t vers_row_same_trx(dict_index_t* index, const rec_t* rec,
                                 const trx_t& trx)
2063 2064 2065 2066 2067 2068 2069 2070
{
  mtr_t mtr;
  dberr_t ret= DB_SUCCESS;
  dict_index_t *clust_index= dict_table_get_first_index(index->table);
  ut_ad(index != clust_index);

  mtr.start();

Marko Mäkelä's avatar
Marko Mäkelä committed
2071 2072
  if (const rec_t *clust_rec=
      row_get_clust_rec(BTR_SEARCH_LEAF, rec, index, &clust_index, &mtr))
2073
  {
Marko Mäkelä's avatar
Marko Mäkelä committed
2074 2075 2076 2077 2078
    rec_offs offsets_[REC_OFFS_NORMAL_SIZE];
    rec_offs *clust_offs= offsets_;
    rec_offs_init(offsets_);
    mem_heap_t *heap= NULL;

2079
    clust_offs=
Marko Mäkelä's avatar
Marko Mäkelä committed
2080 2081 2082
      rec_get_offsets(clust_rec, clust_index, clust_offs,
                      clust_index->n_core_fields, ULINT_UNDEFINED, &heap);
    if (clust_index->vers_history_row(clust_rec, clust_offs))
2083
    {
Marko Mäkelä's avatar
Marko Mäkelä committed
2084 2085 2086 2087 2088 2089 2090
      ulint trx_id_len;
      const byte *trx_id= rec_get_nth_field(clust_rec, clust_offs,
                                            clust_index->n_uniq, &trx_id_len);
      ut_ad(trx_id_len == DATA_TRX_ID_LEN);

      if (trx.id == trx_read_trx_id(trx_id))
        ret= DB_FOREIGN_DUPLICATE_KEY;
2091
    }
Marko Mäkelä's avatar
Marko Mäkelä committed
2092 2093 2094

    if (UNIV_LIKELY_NULL(heap))
      mem_heap_free(heap);
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
  }
  else
  {
    ib::error() << "foreign constraints: secondary index " << index->name <<
                   " of table " << index->table->name << " is out of sync";
    ut_ad("secondary index is out of sync" == 0);
    ret= DB_TABLE_CORRUPT;
  }

  mtr.commit();
  return ret;
}

2108 2109 2110 2111
/***************************************************************//**
Scans a unique non-clustered index at a given index entry to determine
whether a uniqueness violation has occurred for the key value of the entry.
Set shared locks on possible duplicate records.
2112
@return DB_SUCCESS, DB_DUPLICATE_KEY, or DB_LOCK_WAIT */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
2113
static MY_ATTRIBUTE((nonnull, warn_unused_result))
2114 2115 2116 2117 2118 2119 2120 2121 2122
dberr_t
row_ins_scan_sec_index_for_duplicate(
/*=================================*/
	ulint		flags,	/*!< in: undo logging and locking flags */
	dict_index_t*	index,	/*!< in: non-clustered unique index */
	dtuple_t*	entry,	/*!< in: index entry */
	que_thr_t*	thr,	/*!< in: query thread */
	bool		s_latch,/*!< in: whether index->lock is being held */
	mtr_t*		mtr,	/*!< in/out: mini-transaction */
2123
	mem_heap_t*	offsets_heap)
2124 2125 2126 2127 2128 2129 2130
				/*!< in/out: memory heap that can be emptied */
{
	ulint		n_unique;
	int		cmp;
	ulint		n_fields_cmp;
	btr_pcur_t	pcur;
	dberr_t		err		= DB_SUCCESS;
2131 2132
	rec_offs	offsets_[REC_OFFS_SEC_INDEX_SIZE];
	rec_offs*	offsets		= offsets_;
2133
	DBUG_ENTER("row_ins_scan_sec_index_for_duplicate");
2134

2135
	rec_offs_init(offsets_);
2136

2137
	ut_ad(s_latch == rw_lock_own_flagged(
2138
			&index->lock, RW_LOCK_FLAG_S | RW_LOCK_FLAG_SX));
2139 2140 2141 2142 2143 2144

	n_unique = dict_index_get_n_unique(index);

	/* If the secondary index is unique, but one of the fields in the
	n_unique first fields is NULL, a unique key violation cannot occur,
	since we define NULL != NULL in this case */
2145 2146
	if (index->n_nullable && dtuple_contains_null(entry, n_unique))
		DBUG_RETURN(DB_SUCCESS);
2147 2148 2149 2150 2151 2152 2153 2154 2155

	/* Store old value on n_fields_cmp */

	n_fields_cmp = dtuple_get_n_fields_cmp(entry);

	dtuple_set_n_fields_cmp(entry, n_unique);

	btr_pcur_open(index, entry, PAGE_CUR_GE,
		      s_latch
2156
		      ? BTR_SEARCH_LEAF_ALREADY_S_LATCHED
2157 2158 2159
		      : BTR_SEARCH_LEAF,
		      &pcur, mtr);

Marko Mäkelä's avatar
Marko Mäkelä committed
2160
	trx_t* const trx = thr_get_trx(thr);
2161 2162 2163 2164 2165 2166

	/* Scan index records and check if there is a duplicate */

	do {
		const rec_t*		rec	= btr_pcur_get_rec(&pcur);
		const buf_block_t*	block	= btr_pcur_get_block(&pcur);
Sergei Golubchik's avatar
5.6.21  
Sergei Golubchik committed
2167
		const ulint		lock_type = LOCK_ORDINARY;
2168 2169 2170 2171 2172 2173

		if (page_rec_is_infimum(rec)) {

			continue;
		}

2174 2175
		offsets = rec_get_offsets(rec, index, offsets,
					  index->n_core_fields,
2176 2177 2178 2179 2180
					  ULINT_UNDEFINED, &offsets_heap);

		if (flags & BTR_NO_LOCKING_FLAG) {
			/* Set no locks when applying log
			in online table rebuild. */
Marko Mäkelä's avatar
Marko Mäkelä committed
2181
		} else if (trx->duplicates) {
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211

			/* If the SQL-query will update or replace
			duplicate key we will take X-lock for
			duplicates ( REPLACE, LOAD DATAFILE REPLACE,
			INSERT ON DUPLICATE KEY UPDATE). */

			err = row_ins_set_exclusive_rec_lock(
				lock_type, block, rec, index, offsets, thr);
		} else {

			err = row_ins_set_shared_rec_lock(
				lock_type, block, rec, index, offsets, thr);
		}

		switch (err) {
		case DB_SUCCESS_LOCKED_REC:
			err = DB_SUCCESS;
		case DB_SUCCESS:
			break;
		default:
			goto end_scan;
		}

		if (page_rec_is_supremum(rec)) {

			continue;
		}

		cmp = cmp_dtuple_rec(entry, rec, offsets);

2212
		if (cmp == 0) {
2213 2214
			if (row_ins_dupl_error_with_rec(rec, entry,
							index, offsets)) {
2215

2216 2217
				err = DB_DUPLICATE_KEY;

Marko Mäkelä's avatar
Marko Mäkelä committed
2218
				trx->error_info = index;
2219

Marko Mäkelä's avatar
Marko Mäkelä committed
2220 2221 2222 2223 2224 2225
				if (!index->table->versioned()) {
				} else if (dberr_t e =
					   vers_row_same_trx(index, rec,
							     *trx)) {
					err = e;
					goto end_scan;
2226
				}
2227 2228 2229

				/* If the duplicate is on hidden FTS_DOC_ID,
				state so in the error log */
2230 2231
				if (index == index->table->fts_doc_id_index
				    && DICT_TF2_FLAG_IS_SET(
2232
					index->table,
2233 2234 2235 2236 2237
					DICT_TF2_FTS_HAS_DOC_ID)) {

					ib::error() << "Duplicate FTS_DOC_ID"
						" value on table "
						<< index->table->name;
2238 2239 2240 2241 2242
				}

				goto end_scan;
			}
		} else {
2243
			ut_a(cmp < 0);
2244 2245 2246 2247 2248 2249 2250 2251
			goto end_scan;
		}
	} while (btr_pcur_move_to_next(&pcur, mtr));

end_scan:
	/* Restore old value */
	dtuple_set_n_fields_cmp(entry, n_fields_cmp);

2252
	DBUG_RETURN(err);
2253 2254 2255
}

/** Checks for a duplicate when the table is being rebuilt online.
2256 2257
@retval DB_SUCCESS when no duplicate is detected
@retval DB_SUCCESS_LOCKED_REC when rec is an exact match of entry or
2258
a newer version of entry (the entry should not be inserted)
2259
@retval DB_DUPLICATE_KEY when entry is a duplicate of rec */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
2260
static MY_ATTRIBUTE((nonnull, warn_unused_result))
2261 2262 2263 2264 2265 2266
dberr_t
row_ins_duplicate_online(
/*=====================*/
	ulint		n_uniq,	/*!< in: offset of DB_TRX_ID */
	const dtuple_t*	entry,	/*!< in: entry that is being inserted */
	const rec_t*	rec,	/*!< in: clustered index record */
2267
	rec_offs*	offsets)/*!< in/out: rec_get_offsets(rec) */
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
{
	ulint	fields	= 0;

	/* During rebuild, there should not be any delete-marked rows
	in the new table. */
	ut_ad(!rec_get_deleted_flag(rec, rec_offs_comp(offsets)));
	ut_ad(dtuple_get_n_fields_cmp(entry) == n_uniq);

	/* Compare the PRIMARY KEY fields and the
	DB_TRX_ID, DB_ROLL_PTR. */
	cmp_dtuple_rec_with_match_low(
2279
		entry, rec, offsets, n_uniq + 2, &fields);
2280 2281 2282 2283 2284 2285

	if (fields < n_uniq) {
		/* Not a duplicate. */
		return(DB_SUCCESS);
	}

2286 2287 2288 2289 2290 2291 2292 2293
	ulint trx_id_len;

	if (fields == n_uniq + 2
	    && memcmp(rec_get_nth_field(rec, offsets, n_uniq, &trx_id_len),
		      reset_trx_id, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)) {
		ut_ad(trx_id_len == DATA_TRX_ID_LEN);
		/* rec is an exact match of entry, and DB_TRX_ID belongs
		to a transaction that started after our ALTER TABLE. */
2294 2295 2296 2297 2298 2299 2300
		return(DB_SUCCESS_LOCKED_REC);
	}

	return(DB_DUPLICATE_KEY);
}

/** Checks for a duplicate when the table is being rebuilt online.
2301 2302
@retval DB_SUCCESS when no duplicate is detected
@retval DB_SUCCESS_LOCKED_REC when rec is an exact match of entry or
2303
a newer version of entry (the entry should not be inserted)
2304
@retval DB_DUPLICATE_KEY when entry is a duplicate of rec */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
2305
static MY_ATTRIBUTE((nonnull, warn_unused_result))
2306 2307 2308 2309 2310 2311
dberr_t
row_ins_duplicate_error_in_clust_online(
/*====================================*/
	ulint		n_uniq,	/*!< in: offset of DB_TRX_ID */
	const dtuple_t*	entry,	/*!< in: entry that is being inserted */
	const btr_cur_t*cursor,	/*!< in: cursor on insert position */
2312
	rec_offs**	offsets,/*!< in/out: rec_get_offsets(rec) */
2313 2314 2315 2316 2317
	mem_heap_t**	heap)	/*!< in/out: heap for offsets */
{
	dberr_t		err	= DB_SUCCESS;
	const rec_t*	rec	= btr_cur_get_rec(cursor);

2318 2319
	ut_ad(!cursor->index->is_instant());

2320
	if (cursor->low_match >= n_uniq && !page_rec_is_infimum(rec)) {
2321 2322
		*offsets = rec_get_offsets(rec, cursor->index, *offsets,
					   cursor->index->n_fields,
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
					   ULINT_UNDEFINED, heap);
		err = row_ins_duplicate_online(n_uniq, entry, rec, *offsets);
		if (err != DB_SUCCESS) {
			return(err);
		}
	}

	rec = page_rec_get_next_const(btr_cur_get_rec(cursor));

	if (cursor->up_match >= n_uniq && !page_rec_is_supremum(rec)) {
2333 2334
		*offsets = rec_get_offsets(rec, cursor->index, *offsets,
					   cursor->index->n_fields,
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
					   ULINT_UNDEFINED, heap);
		err = row_ins_duplicate_online(n_uniq, entry, rec, *offsets);
	}

	return(err);
}

/***************************************************************//**
Checks if a unique key violation error would occur at an index entry
insert. Sets shared locks on possible duplicate records. Works only
for a clustered index!
@retval DB_SUCCESS if no error
@retval DB_DUPLICATE_KEY if error,
@retval DB_LOCK_WAIT if we have to wait for a lock on a possible duplicate
2349
record */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
2350
static MY_ATTRIBUTE((nonnull, warn_unused_result))
2351 2352 2353 2354 2355
dberr_t
row_ins_duplicate_error_in_clust(
	ulint		flags,	/*!< in: undo logging and locking flags */
	btr_cur_t*	cursor,	/*!< in: B-tree cursor */
	const dtuple_t*	entry,	/*!< in: entry to insert */
Marko Mäkelä's avatar
Marko Mäkelä committed
2356
	que_thr_t*	thr)	/*!< in: query thread */
2357 2358 2359 2360 2361 2362
{
	dberr_t	err;
	rec_t*	rec;
	ulint	n_unique;
	trx_t*	trx		= thr_get_trx(thr);
	mem_heap_t*heap		= NULL;
2363 2364
	rec_offs offsets_[REC_OFFS_NORMAL_SIZE];
	rec_offs* offsets		= offsets_;
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
	rec_offs_init(offsets_);

	ut_ad(dict_index_is_clust(cursor->index));

	/* NOTE: For unique non-clustered indexes there may be any number
	of delete marked records with the same value for the non-clustered
	index key (remember multiversioning), and which differ only in
	the row refererence part of the index record, containing the
	clustered index key fields. For such a secondary index record,
	to avoid race condition, we must FIRST do the insertion and after
	that check that the uniqueness condition is not breached! */

	/* NOTE: A problem is that in the B-tree node pointers on an
	upper level may match more to the entry than the actual existing
	user records on the leaf level. So, even if low_match would suggest
	that a duplicate key violation may occur, this may not be the case. */

	n_unique = dict_index_get_n_unique(cursor->index);

	if (cursor->low_match >= n_unique) {

		rec = btr_cur_get_rec(cursor);

		if (!page_rec_is_infimum(rec)) {
			offsets = rec_get_offsets(rec, cursor->index, offsets,
2390
						  cursor->index->n_core_fields,
2391 2392 2393 2394 2395 2396 2397
						  ULINT_UNDEFINED, &heap);

			/* We set a lock on the possible duplicate: this
			is needed in logical logging of MySQL to make
			sure that in roll-forward we get the same duplicate
			errors as in original execution */

2398 2399 2400 2401
			if (flags & BTR_NO_LOCKING_FLAG) {
				/* Do nothing if no-locking is set */
				err = DB_SUCCESS;
			} else if (trx->duplicates) {
2402 2403 2404 2405 2406 2407 2408

				/* If the SQL-query will update or replace
				duplicate key we will take X-lock for
				duplicates ( REPLACE, LOAD DATAFILE REPLACE,
				INSERT ON DUPLICATE KEY UPDATE). */

				err = row_ins_set_exclusive_rec_lock(
Marko Mäkelä's avatar
Marko Mäkelä committed
2409
					LOCK_REC_NOT_GAP,
2410 2411 2412 2413 2414
					btr_cur_get_block(cursor),
					rec, cursor->index, offsets, thr);
			} else {

				err = row_ins_set_shared_rec_lock(
Marko Mäkelä's avatar
Marko Mäkelä committed
2415
					LOCK_REC_NOT_GAP,
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429
					btr_cur_get_block(cursor), rec,
					cursor->index, offsets, thr);
			}

			switch (err) {
			case DB_SUCCESS_LOCKED_REC:
			case DB_SUCCESS:
				break;
			default:
				goto func_exit;
			}

			if (row_ins_dupl_error_with_rec(
				    rec, entry, cursor->index, offsets)) {
Marko Mäkelä's avatar
Marko Mäkelä committed
2430 2431 2432
duplicate:
				trx->error_info = cursor->index;
				err = DB_DUPLICATE_KEY;
2433 2434 2435 2436
				if (thr->prebuilt
				    && thr->prebuilt->upd_node
				    && thr->prebuilt->upd_node->is_delete
					== VERSIONED_DELETE
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
				    && entry->vers_history_row())
				{
					ulint trx_id_len;
					byte *trx_id = rec_get_nth_field(
						rec, offsets, n_unique,
						&trx_id_len);
					ut_ad(trx_id_len == DATA_TRX_ID_LEN);
					if (trx->id == trx_read_trx_id(trx_id)) {
						err = DB_FOREIGN_DUPLICATE_KEY;
					}
				}
Marko Mäkelä's avatar
Marko Mäkelä committed
2448
				goto func_exit;
2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
			}
		}
	}

	if (cursor->up_match >= n_unique) {

		rec = page_rec_get_next(btr_cur_get_rec(cursor));

		if (!page_rec_is_supremum(rec)) {
			offsets = rec_get_offsets(rec, cursor->index, offsets,
2459
						  cursor->index->n_core_fields,
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
						  ULINT_UNDEFINED, &heap);

			if (trx->duplicates) {

				/* If the SQL-query will update or replace
				duplicate key we will take X-lock for
				duplicates ( REPLACE, LOAD DATAFILE REPLACE,
				INSERT ON DUPLICATE KEY UPDATE). */

				err = row_ins_set_exclusive_rec_lock(
					LOCK_REC_NOT_GAP,
					btr_cur_get_block(cursor),
					rec, cursor->index, offsets, thr);
			} else {

				err = row_ins_set_shared_rec_lock(
					LOCK_REC_NOT_GAP,
					btr_cur_get_block(cursor),
					rec, cursor->index, offsets, thr);
			}

			switch (err) {
			case DB_SUCCESS_LOCKED_REC:
			case DB_SUCCESS:
				break;
			default:
				goto func_exit;
			}

			if (row_ins_dupl_error_with_rec(
				    rec, entry, cursor->index, offsets)) {
Marko Mäkelä's avatar
Marko Mäkelä committed
2491
				goto duplicate;
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535
			}
		}

		/* This should never happen */
		ut_error;
	}

	err = DB_SUCCESS;
func_exit:
	if (UNIV_LIKELY_NULL(heap)) {
		mem_heap_free(heap);
	}
	return(err);
}

/***************************************************************//**
Checks if an index entry has long enough common prefix with an
existing record so that the intended insert of the entry must be
changed to a modify of the existing record. In the case of a clustered
index, the prefix must be n_unique fields long. In the case of a
secondary index, all fields must be equal.  InnoDB never updates
secondary index records in place, other than clearing or setting the
delete-mark flag. We could be able to update the non-unique fields
of a unique secondary index record by checking the cursor->up_match,
but we do not do so, because it could have some locking implications.
@return TRUE if the existing record should be updated; FALSE if not */
UNIV_INLINE
ibool
row_ins_must_modify_rec(
/*====================*/
	const btr_cur_t*	cursor)	/*!< in: B-tree cursor */
{
	/* NOTE: (compare to the note in row_ins_duplicate_error_in_clust)
	Because node pointers on upper levels of the B-tree may match more
	to entry than to actual user records on the leaf level, we
	have to check if the candidate record is actually a user record.
	A clustered index node pointer contains index->n_unique first fields,
	and a secondary index node pointer contains all index fields. */

	return(cursor->low_match
	       >= dict_index_get_n_unique_in_tree(cursor->index)
	       && !page_rec_is_infimum(btr_cur_get_rec(cursor)));
}

2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551
/** Insert the externally stored fields (off-page columns)
of a clustered index entry.
@param[in]	entry	index entry to insert
@param[in]	big_rec	externally stored fields
@param[in,out]	offsets	rec_get_offsets()
@param[in,out]	heap	memory heap
@param[in]	thd	client connection, or NULL
@param[in]	index	clustered index
@return	error code
@retval	DB_SUCCESS
@retval DB_OUT_OF_FILE_SPACE */
static
dberr_t
row_ins_index_entry_big_rec(
	const dtuple_t*		entry,
	const big_rec_t*	big_rec,
2552
	rec_offs*		offsets,
2553
	mem_heap_t**		heap,
2554 2555
	dict_index_t*		index,
	const void*		thd __attribute__((unused)))
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
{
	mtr_t		mtr;
	btr_pcur_t	pcur;
	rec_t*		rec;
	dberr_t		error;

	ut_ad(dict_index_is_clust(index));

	DEBUG_SYNC_C_IF_THD(thd, "before_row_ins_extern_latch");

2566 2567 2568 2569
	mtr.start();
	if (index->table->is_temporary()) {
		mtr.set_log_mode(MTR_LOG_NO_REDO);
	} else {
2570
		index->set_modified(mtr);
2571
	}
2572 2573 2574 2575

	btr_pcur_open(index, entry, PAGE_CUR_LE, BTR_MODIFY_TREE,
		      &pcur, &mtr);
	rec = btr_pcur_get_rec(&pcur);
2576
	offsets = rec_get_offsets(rec, index, offsets, index->n_core_fields,
2577 2578 2579 2580
				  ULINT_UNDEFINED, heap);

	DEBUG_SYNC_C_IF_THD(thd, "before_row_ins_extern");
	error = btr_store_big_rec_extern_fields(
Marko Mäkelä's avatar
Marko Mäkelä committed
2581
		&pcur, offsets, big_rec, &mtr, BTR_STORE_INSERT);
2582 2583 2584 2585
	DEBUG_SYNC_C_IF_THD(thd, "after_row_ins_extern");

	if (error == DB_SUCCESS
	    && dict_index_is_online_ddl(index)) {
2586
		row_log_table_insert(btr_pcur_get_rec(&pcur), index, offsets);
2587 2588
	}

2589
	mtr.commit();
2590 2591 2592 2593 2594 2595

	btr_pcur_close(&pcur);

	return(error);
}

2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
/***************************************************************//**
Tries to insert an entry into a clustered index, ignoring foreign key
constraints. If a record with the same unique key is found, the other
record is necessarily marked deleted by a committed transaction, or a
unique key violation error occurs. The delete marked record is then
updated to an existing record, and we must write an undo log record on
the delete marked record.
@retval DB_SUCCESS on success
@retval DB_LOCK_WAIT on lock wait when !(flags & BTR_NO_LOCKING_FLAG)
@retval DB_FAIL if retry with BTR_MODIFY_TREE is needed
@return error code */
dberr_t
row_ins_clust_index_entry_low(
/*==========================*/
	ulint		flags,	/*!< in: undo logging and locking flags */
	ulint		mode,	/*!< in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
				depending on whether we wish optimistic or
				pessimistic descent down the index tree */
	dict_index_t*	index,	/*!< in: clustered index */
	ulint		n_uniq,	/*!< in: 0 or index->n_uniq */
	dtuple_t*	entry,	/*!< in/out: index entry to insert */
	ulint		n_ext,	/*!< in: number of externally stored columns */
2618
	que_thr_t*	thr)	/*!< in: query thread */
2619
{
2620 2621
	btr_pcur_t	pcur;
	btr_cur_t*	cursor;
2622
	dberr_t		err		= DB_SUCCESS;
2623 2624
	big_rec_t*	big_rec		= NULL;
	mtr_t		mtr;
2625
	ib_uint64_t	auto_inc	= 0;
2626
	mem_heap_t*	offsets_heap	= NULL;
2627 2628
	rec_offs	offsets_[REC_OFFS_NORMAL_SIZE];
	rec_offs*	offsets         = offsets_;
2629 2630 2631
	rec_offs_init(offsets_);

	DBUG_ENTER("row_ins_clust_index_entry_low");
2632 2633 2634 2635 2636

	ut_ad(dict_index_is_clust(index));
	ut_ad(!dict_index_is_unique(index)
	      || n_uniq == dict_index_get_n_unique(index));
	ut_ad(!n_uniq || n_uniq == dict_index_get_n_unique(index));
2637
	ut_ad(!thr_get_trx(thr)->in_rollback);
2638 2639 2640

	mtr_start(&mtr);

2641
	if (index->table->is_temporary()) {
2642 2643 2644 2645
		/* Disable REDO logging as the lifetime of temp-tables is
		limited to server or connection lifetime and so REDO
		information is not needed on restart for recovery.
		Disable locking as temp-tables are local to a connection. */
2646

2647
		ut_ad(flags & BTR_NO_LOCKING_FLAG);
2648 2649
		ut_ad(!dict_index_is_online_ddl(index));
		ut_ad(!index->table->persistent_autoinc);
2650
		ut_ad(!index->is_instant());
2651
		ut_ad(!entry->info_bits);
2652
		mtr.set_log_mode(MTR_LOG_NO_REDO);
2653
	} else {
2654
		index->set_modified(mtr);
2655

2656 2657
		if (UNIV_UNLIKELY(entry->info_bits != 0)) {
			ut_ad(entry->is_metadata());
2658 2659 2660
			ut_ad(index->is_instant());
			ut_ad(!dict_index_is_online_ddl(index));
			ut_ad(mode == BTR_MODIFY_TREE);
2661
			ut_ad(flags == BTR_NO_LOCKING_FLAG);
2662 2663 2664 2665
		} else {
			if (mode == BTR_MODIFY_LEAF
			    && dict_index_is_online_ddl(index)) {
				mode = BTR_MODIFY_LEAF_ALREADY_S_LATCHED;
Marko Mäkelä's avatar
Marko Mäkelä committed
2666
				mtr_s_lock_index(index, &mtr);
2667
			}
2668

2669 2670 2671 2672 2673 2674 2675 2676
			if (unsigned ai = index->table->persistent_autoinc) {
				/* Prepare to persist the AUTO_INCREMENT value
				from the index entry to PAGE_ROOT_AUTO_INC. */
				const dfield_t* dfield = dtuple_get_nth_field(
					entry, ai - 1);
				if (!dfield_is_null(dfield)) {
					auto_inc = row_parse_int(
						static_cast<const byte*>(
2677 2678 2679 2680 2681
							dfield->data),
						dfield->len,
						dfield->type.mtype,
						dfield->type.prtype
						& DATA_UNSIGNED);
2682 2683
				}
			}
2684
		}
2685 2686 2687 2688 2689
	}

	/* Note that we use PAGE_CUR_LE as the search mode, because then
	the function will return in both low_match and up_match of the
	cursor sensible values */
Marko Mäkelä's avatar
Marko Mäkelä committed
2690
 	err = btr_pcur_open_low(index, 0, entry, PAGE_CUR_LE, mode, &pcur,
2691
			  __FILE__, __LINE__, auto_inc, &mtr);
2692
	if (err != DB_SUCCESS) {
2693
		index->table->file_unreadable = true;
Marko Mäkelä's avatar
Marko Mäkelä committed
2694
		mtr.commit();
2695 2696 2697
		goto func_exit;
	}

2698
	cursor = btr_pcur_get_btr_cur(&pcur);
2699
	cursor->thr = thr;
2700

2701 2702
#ifdef UNIV_DEBUG
	{
2703
		page_t*	page = btr_cur_get_page(cursor);
2704 2705 2706 2707
		rec_t*	first_rec = page_rec_get_next(
			page_get_infimum_rec(page));

		ut_ad(page_rec_is_supremum(first_rec)
2708
		      || rec_n_fields_is_sane(index, first_rec, entry));
2709
	}
2710
#endif /* UNIV_DEBUG */
2711

2712
	if (UNIV_UNLIKELY(entry->info_bits != 0)) {
2713 2714
		const rec_t* rec = btr_cur_get_rec(cursor);

2715 2716
		if (rec_get_info_bits(rec, page_rec_is_comp(rec))
		    & REC_INFO_MIN_REC_FLAG) {
2717 2718 2719 2720
			thr_get_trx(thr)->error_info = index;
			err = DB_DUPLICATE_KEY;
			goto err_exit;
		}
2721 2722 2723

		ut_ad(!row_ins_must_modify_rec(cursor));
		goto do_insert;
2724 2725
	}

2726
	if (rec_is_metadata(btr_cur_get_rec(cursor), *index)) {
2727 2728 2729
		goto do_insert;
	}

2730
	if (n_uniq
2731
	    && (cursor->up_match >= n_uniq || cursor->low_match >= n_uniq)) {
2732 2733 2734

		if (flags
		    == (BTR_CREATE_FLAG | BTR_NO_LOCKING_FLAG
Eugene Kosov's avatar
Eugene Kosov committed
2735
			| BTR_NO_UNDO_LOG_FLAG | BTR_KEEP_SYS_FLAG)) {
2736 2737 2738
			/* Set no locks when applying log
			in online table rebuild. Only check for duplicates. */
			err = row_ins_duplicate_error_in_clust_online(
2739
				n_uniq, entry, cursor,
2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
				&offsets, &offsets_heap);

			switch (err) {
			case DB_SUCCESS:
				break;
			default:
				ut_ad(0);
				/* fall through */
			case DB_SUCCESS_LOCKED_REC:
			case DB_DUPLICATE_KEY:
2750
				thr_get_trx(thr)->error_info = cursor->index;
2751 2752 2753 2754 2755 2756
			}
		} else {
			/* Note that the following may return also
			DB_LOCK_WAIT */

			err = row_ins_duplicate_error_in_clust(
Marko Mäkelä's avatar
Marko Mäkelä committed
2757
				flags, cursor, entry, thr);
2758 2759 2760 2761 2762 2763 2764 2765 2766
		}

		if (err != DB_SUCCESS) {
err_exit:
			mtr_commit(&mtr);
			goto func_exit;
		}
	}

2767
	/* Note: Allowing duplicates would qualify for modification of
2768 2769
	an existing record as the new entry is exactly same as old entry. */
	if (row_ins_must_modify_rec(cursor)) {
2770 2771 2772 2773 2774
		/* There is already an index entry with a long enough common
		prefix, we must convert the insert into a modify of an
		existing record */
		mem_heap_t*	entry_heap	= mem_heap_create(1024);

2775 2776 2777
		err = row_ins_clust_index_entry_by_modify(
			&pcur, flags, mode, &offsets, &offsets_heap,
			entry_heap, entry, thr, &mtr);
2778 2779

		if (err == DB_SUCCESS && dict_index_is_online_ddl(index)) {
2780
			row_log_table_insert(btr_cur_get_rec(cursor),
2781
					     index, offsets);
2782 2783 2784 2785 2786
		}

		mtr_commit(&mtr);
		mem_heap_free(entry_heap);
	} else {
2787
		if (index->is_instant()) entry->trim(*index);
2788
do_insert:
2789 2790 2791
		rec_t*	insert_rec;

		if (mode != BTR_MODIFY_TREE) {
2792
			ut_ad((mode & ulint(~BTR_ALREADY_S_LATCHED))
2793 2794
			      == BTR_MODIFY_LEAF);
			err = btr_cur_optimistic_insert(
2795
				flags, cursor, &offsets, &offsets_heap,
2796 2797 2798
				entry, &insert_rec, &big_rec,
				n_ext, thr, &mtr);
		} else {
2799
			if (buf_pool.running_out()) {
2800 2801 2802 2803
				err = DB_LOCK_TABLE_FULL;
				goto err_exit;
			}

2804 2805
			DEBUG_SYNC_C("before_insert_pessimitic_row_ins_clust");

2806
			err = btr_cur_optimistic_insert(
2807
				flags, cursor,
2808 2809 2810 2811 2812 2813
				&offsets, &offsets_heap,
				entry, &insert_rec, &big_rec,
				n_ext, thr, &mtr);

			if (err == DB_FAIL) {
				err = btr_cur_pessimistic_insert(
2814
					flags, cursor,
2815 2816 2817 2818 2819 2820
					&offsets, &offsets_heap,
					entry, &insert_rec, &big_rec,
					n_ext, thr, &mtr);
			}
		}

2821 2822 2823 2824 2825 2826 2827 2828 2829
		if (err == DB_SUCCESS && entry->info_bits) {
			if (buf_block_t* root
			    = btr_root_block_get(index, RW_X_LATCH, &mtr)) {
				btr_set_instant(root, *index, &mtr);
			} else {
				ut_ad("cannot find root page" == 0);
			}
		}

2830
		if (big_rec != NULL) {
2831
			ut_ad(err == DB_SUCCESS);
2832 2833 2834 2835 2836 2837 2838 2839 2840
			mtr_commit(&mtr);

			/* Online table rebuild could read (and
			ignore) the incomplete record at this point.
			If online rebuild is in progress, the
			row_ins_index_entry_big_rec() will write log. */

			DBUG_EXECUTE_IF(
				"row_ins_extern_checkpoint",
2841
				log_write_up_to(mtr.commit_lsn(), true););
2842 2843
			err = row_ins_index_entry_big_rec(
				entry, big_rec, offsets, &offsets_heap, index,
2844
				thr_get_trx(thr)->mysql_thd);
2845 2846 2847 2848 2849
			dtuple_convert_back_big_rec(index, entry, big_rec);
		} else {
			if (err == DB_SUCCESS
			    && dict_index_is_online_ddl(index)) {
				row_log_table_insert(
2850
					insert_rec, index, offsets);
2851 2852 2853 2854 2855 2856 2857
			}

			mtr_commit(&mtr);
		}
	}

func_exit:
2858
	if (offsets_heap != NULL) {
2859 2860 2861
		mem_heap_free(offsets_heap);
	}

2862 2863 2864
	btr_pcur_close(&pcur);

	DBUG_RETURN(err);
2865 2866
}

2867 2868 2869 2870 2871
/** Start a mini-transaction and check if the index will be dropped.
@param[in,out]	mtr		mini-transaction
@param[in,out]	index		secondary index
@param[in]	check		whether to check
@param[in]	search_mode	flags
2872
@return true if the index is to be dropped */
2873
static MY_ATTRIBUTE((warn_unused_result))
2874
bool
2875 2876 2877 2878
row_ins_sec_mtr_start_and_check_if_aborted(
	mtr_t*		mtr,
	dict_index_t*	index,
	bool		check,
2879 2880 2881
	ulint		search_mode)
{
	ut_ad(!dict_index_is_clust(index));
2882
	ut_ad(mtr->is_named_space(index->table->space));
2883 2884

	const mtr_log_t	log_mode = mtr->get_log_mode();
2885

2886 2887
	mtr->start();
	index->set_modified(*mtr);
2888
	mtr->set_log_mode(log_mode);
2889 2890 2891 2892 2893 2894

	if (!check) {
		return(false);
	}

	if (search_mode & BTR_ALREADY_S_LATCHED) {
2895
		mtr_s_lock_index(index, mtr);
2896
	} else {
2897
		mtr_sx_lock_index(index, mtr);
2898 2899 2900 2901 2902
	}

	switch (index->online_status) {
	case ONLINE_INDEX_ABORTED:
	case ONLINE_INDEX_ABORTED_DROPPED:
2903
		ut_ad(!index->is_committed());
2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
		return(true);
	case ONLINE_INDEX_COMPLETE:
		return(false);
	case ONLINE_INDEX_CREATION:
		break;
	}

	ut_error;
	return(true);
}

/***************************************************************//**
Tries to insert an entry into a secondary index. If a record with exactly the
same fields is found, the other record is necessarily marked deleted.
It is then unmarked. Otherwise, the entry is just inserted to the index.
@retval DB_SUCCESS on success
@retval DB_LOCK_WAIT on lock wait when !(flags & BTR_NO_LOCKING_FLAG)
@retval DB_FAIL if retry with BTR_MODIFY_TREE is needed
@return error code */
dberr_t
row_ins_sec_index_entry_low(
/*========================*/
	ulint		flags,	/*!< in: undo logging and locking flags */
	ulint		mode,	/*!< in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
				depending on whether we wish optimistic or
				pessimistic descent down the index tree */
	dict_index_t*	index,	/*!< in: secondary index */
	mem_heap_t*	offsets_heap,
				/*!< in/out: memory heap that can be emptied */
	mem_heap_t*	heap,	/*!< in/out: memory heap */
	dtuple_t*	entry,	/*!< in/out: index entry to insert */
	trx_id_t	trx_id,	/*!< in: PAGE_MAX_TRX_ID during
				row_log_table_apply(), or 0 */
2937
	que_thr_t*	thr)	/*!< in: query thread */
2938
{
2939 2940
	DBUG_ENTER("row_ins_sec_index_entry_low");

2941
	btr_cur_t	cursor;
2942
	ulint		search_mode	= mode;
2943 2944 2945
	dberr_t		err		= DB_SUCCESS;
	ulint		n_unique;
	mtr_t		mtr;
2946 2947
	rec_offs	offsets_[REC_OFFS_NORMAL_SIZE];
	rec_offs*	offsets         = offsets_;
2948 2949
	rec_offs_init(offsets_);
	rtr_info_t	rtr_info;
2950 2951 2952 2953 2954

	ut_ad(!dict_index_is_clust(index));
	ut_ad(mode == BTR_MODIFY_LEAF || mode == BTR_MODIFY_TREE);

	cursor.thr = thr;
2955
	cursor.rtr_info = NULL;
2956
	ut_ad(thr_get_trx(thr)->id != 0);
2957

2958
	mtr.start();
2959

2960 2961 2962
	if (index->table->is_temporary()) {
		/* Disable locking, because temporary tables are never
		shared between transactions or connections. */
2963 2964
		ut_ad(flags & BTR_NO_LOCKING_FLAG);
		mtr.set_log_mode(MTR_LOG_NO_REDO);
2965
	} else {
2966
		index->set_modified(mtr);
2967 2968 2969
		if (!dict_index_is_spatial(index)) {
			search_mode |= BTR_INSERT;
		}
2970
	}
2971 2972 2973 2974 2975 2976 2977

	/* Ensure that we acquire index->lock when inserting into an
	index with index->online_status == ONLINE_INDEX_COMPLETE, but
	could still be subject to rollback_inplace_alter_table().
	This prevents a concurrent change of index->online_status.
	The memory object cannot be freed as long as we have an open
	reference to the table, or index->table->n_ref_count > 0. */
2978
	const bool	check = !index->is_committed();
2979 2980 2981 2982
	if (check) {
		DEBUG_SYNC_C("row_ins_sec_index_enter");
		if (mode == BTR_MODIFY_LEAF) {
			search_mode |= BTR_ALREADY_S_LATCHED;
2983
			mtr_s_lock_index(index, &mtr);
2984
		} else {
2985
			mtr_sx_lock_index(index, &mtr);
2986 2987 2988
		}

		if (row_log_online_op_try(
2989
			    index, entry, thr_get_trx(thr)->id)) {
2990 2991 2992 2993 2994 2995 2996 2997
			goto func_exit;
		}
	}

	/* Note that we use PAGE_CUR_LE as the search mode, because then
	the function will return in both low_match and up_match of the
	cursor sensible values */

2998
	if (!thr_get_trx(thr)->check_unique_secondary) {
2999 3000 3001
		search_mode |= BTR_IGNORE_SEC_UNIQUE;
	}

3002 3003 3004 3005 3006
	if (dict_index_is_spatial(index)) {
		cursor.index = index;
		rtr_init_rtr_info(&rtr_info, false, &cursor, index, false);
		rtr_info_update_btr(&cursor, &rtr_info);

3007
		err = btr_cur_search_to_nth_level(
3008 3009
			index, 0, entry, PAGE_CUR_RTREE_INSERT,
			search_mode,
3010
			&cursor, __FILE__, __LINE__, &mtr);
3011 3012 3013 3014 3015 3016 3017

		if (mode == BTR_MODIFY_LEAF && rtr_info.mbr_adj) {
			mtr_commit(&mtr);
			rtr_clean_rtr_info(&rtr_info, true);
			rtr_init_rtr_info(&rtr_info, false, &cursor,
					  index, false);
			rtr_info_update_btr(&cursor, &rtr_info);
3018 3019 3020 3021 3022 3023
			mtr.start();
			if (index->table->is_temporary()) {
				mtr.set_log_mode(MTR_LOG_NO_REDO);
			} else {
				index->set_modified(mtr);
			}
3024
			search_mode &= ulint(~BTR_MODIFY_LEAF);
3025
			search_mode |= BTR_MODIFY_TREE;
3026
			err = btr_cur_search_to_nth_level(
3027 3028
				index, 0, entry, PAGE_CUR_RTREE_INSERT,
				search_mode,
3029
				&cursor, __FILE__, __LINE__, &mtr);
3030 3031 3032 3033 3034 3035 3036 3037
			mode = BTR_MODIFY_TREE;
		}

		DBUG_EXECUTE_IF(
			"rtree_test_check_count", {
			goto func_exit;});

	} else {
3038 3039 3040
		err = btr_cur_search_to_nth_level(
			index, 0, entry, PAGE_CUR_LE,
			search_mode,
3041
			&cursor, __FILE__, __LINE__, &mtr);
3042
	}
3043 3044

	if (err != DB_SUCCESS) {
3045
		if (err == DB_DECRYPTION_FAILED) {
3046 3047
			innodb_decryption_failed(thr_get_trx(thr)->mysql_thd,
						 index->table);
3048 3049 3050
		}
		goto func_exit;
	}
3051 3052

	if (cursor.flag == BTR_CUR_INSERT_TO_IBUF) {
3053
		ut_ad(!dict_index_is_spatial(index));
3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064
		/* The insert was buffered during the search: we are done */
		goto func_exit;
	}

#ifdef UNIV_DEBUG
	{
		page_t*	page = btr_cur_get_page(&cursor);
		rec_t*	first_rec = page_rec_get_next(
			page_get_infimum_rec(page));

		ut_ad(page_rec_is_supremum(first_rec)
3065
		      || rec_n_fields_is_sane(index, first_rec, entry));
3066
	}
3067
#endif /* UNIV_DEBUG */
3068 3069 3070 3071 3072 3073 3074 3075 3076

	n_unique = dict_index_get_n_unique(index);

	if (dict_index_is_unique(index)
	    && (cursor.low_match >= n_unique || cursor.up_match >= n_unique)) {
		mtr_commit(&mtr);

		DEBUG_SYNC_C("row_ins_sec_index_unique");

3077 3078
		if (row_ins_sec_mtr_start_and_check_if_aborted(
			    &mtr, index, check, search_mode)) {
3079 3080 3081 3082
			goto func_exit;
		}

		err = row_ins_scan_sec_index_for_duplicate(
3083
			flags, index, entry, thr, check, &mtr, offsets_heap);
3084 3085 3086 3087 3088 3089 3090

		mtr_commit(&mtr);

		switch (err) {
		case DB_SUCCESS:
			break;
		case DB_DUPLICATE_KEY:
3091
			if (!index->is_committed()) {
3092
				ut_ad(!thr_get_trx(thr)
3093
				      ->dict_operation_lock_mode);
3094
				mutex_enter(&dict_sys.mutex);
3095
				dict_set_corrupted_index_cache_only(index);
3096
				mutex_exit(&dict_sys.mutex);
3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
				/* Do not return any error to the
				caller. The duplicate will be reported
				by ALTER TABLE or CREATE UNIQUE INDEX.
				Unfortunately we cannot report the
				duplicate key value to the DDL thread,
				because the altered_table object is
				private to its call stack. */
				err = DB_SUCCESS;
			}
			/* fall through */
		default:
3108 3109 3110 3111
			if (dict_index_is_spatial(index)) {
				rtr_clean_rtr_info(&rtr_info, true);
			}
			DBUG_RETURN(err);
3112 3113
		}

3114 3115
		if (row_ins_sec_mtr_start_and_check_if_aborted(
			    &mtr, index, check, search_mode)) {
3116 3117 3118
			goto func_exit;
		}

Sergei Golubchik's avatar
5.6.27  
Sergei Golubchik committed
3119 3120
		DEBUG_SYNC_C("row_ins_sec_index_entry_dup_locks_created");

3121 3122 3123 3124 3125
		/* We did not find a duplicate and we have now
		locked with s-locks the necessary records to
		prevent any insertion of a duplicate by another
		transaction. Let us now reposition the cursor and
		continue the insertion. */
3126 3127 3128 3129
		btr_cur_search_to_nth_level(
			index, 0, entry, PAGE_CUR_LE,
			(search_mode
			 & ~(BTR_INSERT | BTR_IGNORE_SEC_UNIQUE)),
3130
			&cursor, __FILE__, __LINE__, &mtr);
3131
	}
3132 3133 3134 3135 3136 3137

	if (row_ins_must_modify_rec(&cursor)) {
		/* There is already an index entry with a long enough common
		prefix, we must convert the insert into a modify of an
		existing record */
		offsets = rec_get_offsets(
3138 3139
			btr_cur_get_rec(&cursor), index, offsets,
			index->n_core_fields,
3140 3141 3142 3143 3144
			ULINT_UNDEFINED, &offsets_heap);

		err = row_ins_sec_index_entry_by_modify(
			flags, mode, &cursor, &offsets,
			offsets_heap, heap, entry, thr, &mtr);
3145 3146 3147

		if (err == DB_SUCCESS && dict_index_is_spatial(index)
		    && rtr_info.mbr_adj) {
Marko Mäkelä's avatar
Marko Mäkelä committed
3148
			err = rtr_ins_enlarge_mbr(&cursor, &mtr);
3149
		}
3150 3151 3152 3153 3154 3155 3156 3157 3158
	} else {
		rec_t*		insert_rec;
		big_rec_t*	big_rec;

		if (mode == BTR_MODIFY_LEAF) {
			err = btr_cur_optimistic_insert(
				flags, &cursor, &offsets, &offsets_heap,
				entry, &insert_rec,
				&big_rec, 0, thr, &mtr);
3159 3160 3161
			if (err == DB_SUCCESS
			    && dict_index_is_spatial(index)
			    && rtr_info.mbr_adj) {
Marko Mäkelä's avatar
Marko Mäkelä committed
3162
				err = rtr_ins_enlarge_mbr(&cursor, &mtr);
3163
			}
3164 3165
		} else {
			ut_ad(mode == BTR_MODIFY_TREE);
3166
			if (buf_pool.running_out()) {
3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182
				err = DB_LOCK_TABLE_FULL;
				goto func_exit;
			}

			err = btr_cur_optimistic_insert(
				flags, &cursor,
				&offsets, &offsets_heap,
				entry, &insert_rec,
				&big_rec, 0, thr, &mtr);
			if (err == DB_FAIL) {
				err = btr_cur_pessimistic_insert(
					flags, &cursor,
					&offsets, &offsets_heap,
					entry, &insert_rec,
					&big_rec, 0, thr, &mtr);
			}
3183 3184 3185
			if (err == DB_SUCCESS
				   && dict_index_is_spatial(index)
				   && rtr_info.mbr_adj) {
Marko Mäkelä's avatar
Marko Mäkelä committed
3186
				err = rtr_ins_enlarge_mbr(&cursor, &mtr);
3187
			}
3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200
		}

		if (err == DB_SUCCESS && trx_id) {
			page_update_max_trx_id(
				btr_cur_get_block(&cursor),
				btr_cur_get_page_zip(&cursor),
				trx_id, &mtr);
		}

		ut_ad(!big_rec);
	}

func_exit:
3201 3202 3203 3204
	if (dict_index_is_spatial(index)) {
		rtr_clean_rtr_info(&rtr_info, true);
	}

3205
	mtr_commit(&mtr);
3206
	DBUG_RETURN(err);
3207 3208 3209 3210 3211 3212 3213
}

/***************************************************************//**
Inserts an entry into a clustered index. Tries first optimistic,
then pessimistic descent down the tree. If the entry matches enough
to a delete marked record, performs the insert by updating or delete
unmarking the delete marked record.
3214
@return DB_SUCCESS, DB_LOCK_WAIT, DB_DUPLICATE_KEY, or some other error code */
3215 3216 3217 3218 3219 3220
dberr_t
row_ins_clust_index_entry(
/*======================*/
	dict_index_t*	index,	/*!< in: clustered index */
	dtuple_t*	entry,	/*!< in/out: index entry to insert */
	que_thr_t*	thr,	/*!< in: query thread */
3221
	ulint		n_ext)	/*!< in: number of externally stored columns */
3222 3223 3224 3225
{
	dberr_t	err;
	ulint	n_uniq;

3226 3227
	DBUG_ENTER("row_ins_clust_index_entry");

Sergei Golubchik's avatar
5.6.20  
Sergei Golubchik committed
3228
	if (!index->table->foreign_set.empty()) {
3229
		err = row_ins_check_foreign_constraints(
3230
			index->table, index, true, entry, thr);
3231 3232
		if (err != DB_SUCCESS) {

3233
			DBUG_RETURN(err);
3234 3235 3236 3237 3238
		}
	}

	n_uniq = dict_index_is_unique(index) ? index->n_uniq : 0;

Brave Galera Crew's avatar
Galera4  
Brave Galera Crew committed
3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255
#ifdef WITH_WSREP
	const bool skip_locking
		= wsrep_thd_skip_locking(thr_get_trx(thr)->mysql_thd);
	ulint	flags = index->table->no_rollback() ? BTR_NO_ROLLBACK
		: (index->table->is_temporary() || skip_locking)
		? BTR_NO_LOCKING_FLAG : 0;
#ifdef UNIV_DEBUG
	if (skip_locking && strcmp(wsrep_get_sr_table_name(),
                                   index->table->name.m_name)) {
		WSREP_ERROR("Record locking is disabled in this thread, "
			    "but the table being modified is not "
			    "`%s`: `%s`.", wsrep_get_sr_table_name(),
			    index->table->name.m_name);
		ut_error;
	}
#endif /* UNIV_DEBUG */
#else
Marko Mäkelä's avatar
Marko Mäkelä committed
3256
	ulint	flags = index->table->no_rollback() ? BTR_NO_ROLLBACK
3257
		: index->table->is_temporary()
3258
		? BTR_NO_LOCKING_FLAG : 0;
Brave Galera Crew's avatar
Galera4  
Brave Galera Crew committed
3259
#endif /* WITH_WSREP */
3260 3261
	const ulint	orig_n_fields = entry->n_fields;

3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272
	/* For intermediate table during copy alter table,
	   skip the undo log and record lock checking for
	   insertion operation.
	*/
	if (index->table->skip_alter_undo) {
		flags |= BTR_NO_UNDO_LOG_FLAG | BTR_NO_LOCKING_FLAG;
	}

	/* Try first optimistic descent to the B-tree */
	log_free_check();

3273 3274
	err = row_ins_clust_index_entry_low(
		flags, BTR_MODIFY_LEAF, index, n_uniq, entry,
3275
		n_ext, thr);
3276

3277
	entry->n_fields = orig_n_fields;
3278 3279 3280

	DEBUG_SYNC_C_IF_THD(thr_get_trx(thr)->mysql_thd,
			    "after_row_ins_clust_index_entry_leaf");
3281 3282 3283

	if (err != DB_FAIL) {
		DEBUG_SYNC_C("row_ins_clust_index_entry_leaf_after");
3284
		DBUG_RETURN(err);
3285 3286 3287
	}

	/* Try then pessimistic descent to the B-tree */
3288
	log_free_check();
3289

3290 3291
	err = row_ins_clust_index_entry_low(
		flags, BTR_MODIFY_TREE, index, n_uniq, entry,
3292
		n_ext, thr);
3293

3294 3295
	entry->n_fields = orig_n_fields;

3296
	DBUG_RETURN(err);
3297 3298 3299 3300 3301 3302 3303
}

/***************************************************************//**
Inserts an entry into a secondary index. Tries first optimistic,
then pessimistic descent down the tree. If the entry matches enough
to a delete marked record, performs the insert by updating or delete
unmarking the delete marked record.
3304
@return DB_SUCCESS, DB_LOCK_WAIT, DB_DUPLICATE_KEY, or some other error code */
3305 3306 3307 3308 3309
dberr_t
row_ins_sec_index_entry(
/*====================*/
	dict_index_t*	index,	/*!< in: secondary index */
	dtuple_t*	entry,	/*!< in/out: index entry to insert */
3310
	que_thr_t*	thr,	/*!< in: query thread */
3311 3312
	bool		check_foreign) /*!< in: true if check
				foreign table is needed, false otherwise */
3313 3314 3315 3316
{
	dberr_t		err;
	mem_heap_t*	offsets_heap;
	mem_heap_t*	heap;
3317
	trx_id_t	trx_id  = 0;
3318

3319 3320 3321 3322
	DBUG_EXECUTE_IF("row_ins_sec_index_entry_timeout", {
			DBUG_SET("-d,row_ins_sec_index_entry_timeout");
			return(DB_LOCK_WAIT);});

3323
	if (check_foreign && !index->table->foreign_set.empty()) {
3324
		err = row_ins_check_foreign_constraints(index->table, index,
3325
							false, entry, thr);
3326 3327 3328 3329 3330 3331
		if (err != DB_SUCCESS) {

			return(err);
		}
	}

3332
	ut_ad(thr_get_trx(thr)->id != 0);
3333 3334 3335 3336 3337 3338

	offsets_heap = mem_heap_create(1024);
	heap = mem_heap_create(1024);

	/* Try first optimistic descent to the B-tree */

3339
	log_free_check();
3340
	ulint flags = index->table->is_temporary()
3341 3342
		? BTR_NO_LOCKING_FLAG
		: 0;
3343

3344 3345 3346 3347 3348 3349 3350 3351 3352
	/* For intermediate table during copy alter table,
	   skip the undo log and record lock checking for
	   insertion operation.
	*/
	if (index->table->skip_alter_undo) {
		trx_id = thr_get_trx(thr)->id;
		flags |= BTR_NO_UNDO_LOG_FLAG | BTR_NO_LOCKING_FLAG;
	}

3353
	err = row_ins_sec_index_entry_low(
3354
		flags, BTR_MODIFY_LEAF, index, offsets_heap, heap, entry,
3355
		trx_id, thr);
3356 3357 3358
	if (err == DB_FAIL) {
		mem_heap_empty(heap);

3359
		if (index->table->space == fil_system.sys_space
3360 3361 3362 3363
		    && !(index->type & (DICT_UNIQUE | DICT_SPATIAL))) {
			ibuf_free_excess_pages();
		}

3364
		/* Try then pessimistic descent to the B-tree */
3365
		log_free_check();
3366 3367

		err = row_ins_sec_index_entry_low(
3368
			flags, BTR_MODIFY_TREE, index,
3369
			offsets_heap, heap, entry, 0, thr);
3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381
	}

	mem_heap_free(heap);
	mem_heap_free(offsets_heap);
	return(err);
}

/***************************************************************//**
Inserts an index entry to index. Tries first optimistic, then pessimistic
descent down the tree. If the entry matches enough to a delete marked record,
performs the insert by updating or delete unmarking the delete marked
record.
3382
@return DB_SUCCESS, DB_LOCK_WAIT, DB_DUPLICATE_KEY, or some other error code */
3383 3384 3385 3386 3387 3388 3389 3390
static
dberr_t
row_ins_index_entry(
/*================*/
	dict_index_t*	index,	/*!< in: index */
	dtuple_t*	entry,	/*!< in/out: index entry to insert */
	que_thr_t*	thr)	/*!< in: query thread */
{
Marko Mäkelä's avatar
Marko Mäkelä committed
3391 3392
	ut_ad(thr_get_trx(thr)->id || index->table->no_rollback()
	      || index->table->is_temporary());
3393

Sergei Golubchik's avatar
5.6.17  
Sergei Golubchik committed
3394 3395 3396 3397
	DBUG_EXECUTE_IF("row_ins_index_entry_timeout", {
			DBUG_SET("-d,row_ins_index_entry_timeout");
			return(DB_LOCK_WAIT);});

3398
	if (index->is_primary()) {
Marko Mäkelä's avatar
Marko Mäkelä committed
3399
		return row_ins_clust_index_entry(index, entry, thr, 0);
3400
	} else {
3401
		return row_ins_sec_index_entry(index, entry, thr);
3402 3403 3404
	}
}

3405 3406 3407 3408 3409

/*****************************************************************//**
This function generate MBR (Minimum Bounding Box) for spatial objects
and set it to spatial index field. */
static
3410
void
3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421
row_ins_spatial_index_entry_set_mbr_field(
/*======================================*/
	dfield_t*	field,		/*!< in/out: mbr field */
	const dfield_t*	row_field)	/*!< in: row field */
{
	ulint		dlen = 0;
	double		mbr[SPDIMS * 2];

	/* This must be a GEOMETRY datatype */
	ut_ad(DATA_GEOMETRY_MTYPE(field->type.mtype));

3422 3423
	const byte* dptr = static_cast<const byte*>(
		dfield_get_data(row_field));
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
	dlen = dfield_get_len(row_field);

	/* obtain the MBR */
	rtree_mbr_from_wkb(dptr + GEO_DATA_HEADER_SIZE,
			   static_cast<uint>(dlen - GEO_DATA_HEADER_SIZE),
			   SPDIMS, mbr);

	/* Set mbr as index entry data */
	dfield_write_mbr(field, mbr);
}

/** Sets the values of the dtuple fields in entry from the values of appropriate
columns in row.
@param[in]	index	index handler
@param[out]	entry	index entry to make
@param[in]	row	row
@return DB_SUCCESS if the set is successful */
3441
static
3442
dberr_t
3443
row_ins_index_entry_set_vals(
3444 3445 3446
	const dict_index_t*	index,
	dtuple_t*		entry,
	const dtuple_t*		row)
3447 3448 3449
{
	ulint	n_fields;
	ulint	i;
3450
	ulint	num_v = dtuple_get_n_v_fields(entry);
3451 3452 3453

	n_fields = dtuple_get_n_fields(entry);

3454 3455
	for (i = 0; i < n_fields + num_v; i++) {
		dict_field_t*	ind_field = NULL;
3456 3457 3458
		dfield_t*	field;
		const dfield_t*	row_field;
		ulint		len;
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471
		dict_col_t*	col;

		if (i >= n_fields) {
			/* This is virtual field */
			field = dtuple_get_nth_v_field(entry, i - n_fields);
			col = &dict_table_get_nth_v_col(
				index->table, i - n_fields)->m_col;
		} else {
			field = dtuple_get_nth_field(entry, i);
			ind_field = dict_index_get_nth_field(index, i);
			col = ind_field->col;
		}

3472
		if (col->is_virtual()) {
3473 3474 3475 3476 3477
			const dict_v_col_t*     v_col
				= reinterpret_cast<const dict_v_col_t*>(col);
			ut_ad(dtuple_get_n_fields(row)
			      == dict_table_get_n_cols(index->table));
			row_field = dtuple_get_nth_v_field(row, v_col->v_pos);
3478 3479 3480 3481 3482 3483 3484 3485
		} else if (col->is_dropped()) {
			ut_ad(index->is_primary());

			if (!(col->prtype & DATA_NOT_NULL)) {
				field->data = NULL;
				field->len = UNIV_SQL_NULL;
				field->type.prtype = DATA_BINARY_TYPE;
			} else {
3486
				ut_ad(ind_field->fixed_len <= col->len);
3487
				dfield_set_data(field, field_ref_zero,
3488
						ind_field->fixed_len);
3489 3490 3491 3492 3493 3494
				field->type.prtype = DATA_NOT_NULL;
			}

			field->type.mtype = col->len
				? DATA_FIXBINARY : DATA_BINARY;
			continue;
3495 3496 3497 3498
		} else {
			row_field = dtuple_get_nth_field(
				row, ind_field->col->ind);
		}
3499 3500 3501 3502

		len = dfield_get_len(row_field);

		/* Check column prefix indexes */
3503
		if (ind_field != NULL && ind_field->prefix_len > 0
3504
		    && len != UNIV_SQL_NULL) {
3505 3506 3507 3508 3509

			const	dict_col_t*	col
				= dict_field_get_col(ind_field);

			len = dtype_get_at_most_n_mbchars(
3510
				col->prtype, col->mbminlen, col->mbmaxlen,
3511 3512 3513 3514 3515 3516 3517 3518
				ind_field->prefix_len,
				len,
				static_cast<const char*>(
					dfield_get_data(row_field)));

			ut_ad(!dfield_is_ext(row_field));
		}

3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530
		/* Handle spatial index. For the first field, replace
		the data with its MBR (Minimum Bounding Box). */
		if ((i == 0) && dict_index_is_spatial(index)) {
			if (!row_field->data
			    || row_field->len < GEO_DATA_HEADER_SIZE) {
				return(DB_CANT_CREATE_GEOMETRY_OBJECT);
			}
			row_ins_spatial_index_entry_set_mbr_field(
				field, row_field);
			continue;
		}

3531 3532 3533 3534 3535 3536
		dfield_set_data(field, dfield_get_data(row_field), len);
		if (dfield_is_ext(row_field)) {
			ut_ad(dict_index_is_clust(index));
			dfield_set_ext(field);
		}
	}
3537 3538

	return(DB_SUCCESS);
3539 3540 3541 3542 3543 3544
}

/***********************************************************//**
Inserts a single index entry to the table.
@return DB_SUCCESS if operation successfully completed, else error
code or DB_LOCK_WAIT */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
3545
static MY_ATTRIBUTE((nonnull, warn_unused_result))
3546 3547 3548 3549 3550 3551 3552 3553
dberr_t
row_ins_index_entry_step(
/*=====================*/
	ins_node_t*	node,	/*!< in: row insert node */
	que_thr_t*	thr)	/*!< in: query thread */
{
	dberr_t	err;

3554 3555
	DBUG_ENTER("row_ins_index_entry_step");

3556 3557
	ut_ad(dtuple_check_typed(node->row));

3558
	err = row_ins_index_entry_set_vals(node->index, *node->entry,
3559
					   node->row);
3560 3561 3562 3563

	if (err != DB_SUCCESS) {
		DBUG_RETURN(err);
	}
3564

3565
	ut_ad(dtuple_check_typed(*node->entry));
3566

3567
	err = row_ins_index_entry(node->index, *node->entry, thr);
3568

3569 3570
	DEBUG_SYNC_C_IF_THD(thr_get_trx(thr)->mysql_thd,
			    "after_row_ins_index_entry_step");
3571

3572
	DBUG_RETURN(err);
3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597
}

/***********************************************************//**
Allocates a row id for row and inits the node->index field. */
UNIV_INLINE
void
row_ins_alloc_row_id_step(
/*======================*/
	ins_node_t*	node)	/*!< in: row insert node */
{
	row_id_t	row_id;

	ut_ad(node->state == INS_NODE_ALLOC_ROW_ID);

	if (dict_index_is_unique(dict_table_get_first_index(node->table))) {

		/* No row id is stored if the clustered index is unique */

		return;
	}

	/* Fill in row id value to row */

	row_id = dict_sys_get_new_row_id();

3598
	dict_sys_write_row_id(node->sys_buf, row_id);
3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668
}

/***********************************************************//**
Gets a row to insert from the values list. */
UNIV_INLINE
void
row_ins_get_row_from_values(
/*========================*/
	ins_node_t*	node)	/*!< in: row insert node */
{
	que_node_t*	list_node;
	dfield_t*	dfield;
	dtuple_t*	row;
	ulint		i;

	/* The field values are copied in the buffers of the select node and
	it is safe to use them until we fetch from select again: therefore
	we can just copy the pointers */

	row = node->row;

	i = 0;
	list_node = node->values_list;

	while (list_node) {
		eval_exp(list_node);

		dfield = dtuple_get_nth_field(row, i);
		dfield_copy_data(dfield, que_node_get_val(list_node));

		i++;
		list_node = que_node_get_next(list_node);
	}
}

/***********************************************************//**
Gets a row to insert from the select list. */
UNIV_INLINE
void
row_ins_get_row_from_select(
/*========================*/
	ins_node_t*	node)	/*!< in: row insert node */
{
	que_node_t*	list_node;
	dfield_t*	dfield;
	dtuple_t*	row;
	ulint		i;

	/* The field values are copied in the buffers of the select node and
	it is safe to use them until we fetch from select again: therefore
	we can just copy the pointers */

	row = node->row;

	i = 0;
	list_node = node->select->select_list;

	while (list_node) {
		dfield = dtuple_get_nth_field(row, i);
		dfield_copy_data(dfield, que_node_get_val(list_node));

		i++;
		list_node = que_node_get_next(list_node);
	}
}

/***********************************************************//**
Inserts a row to a table.
@return DB_SUCCESS if operation successfully completed, else error
code or DB_LOCK_WAIT */
Sergei Golubchik's avatar
5.6.31  
Sergei Golubchik committed
3669
static MY_ATTRIBUTE((nonnull, warn_unused_result))
3670 3671 3672 3673 3674 3675
dberr_t
row_ins(
/*====*/
	ins_node_t*	node,	/*!< in: row insert node */
	que_thr_t*	thr)	/*!< in: query thread */
{
3676 3677 3678 3679
	DBUG_ENTER("row_ins");

	DBUG_PRINT("row_ins", ("table: %s", node->table->name.m_name));

3680 3681 3682 3683 3684
	if (node->state == INS_NODE_ALLOC_ROW_ID) {

		row_ins_alloc_row_id_step(node);

		node->index = dict_table_get_first_index(node->table);
3685 3686
		ut_ad(node->entry_list.empty() == false);
		node->entry = node->entry_list.begin();
3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702

		if (node->ins_type == INS_SEARCHED) {

			row_ins_get_row_from_select(node);

		} else if (node->ins_type == INS_VALUES) {

			row_ins_get_row_from_values(node);
		}

		node->state = INS_NODE_INSERT_ENTRIES;
	}

	ut_ad(node->state == INS_NODE_INSERT_ENTRIES);

	while (node->index != NULL) {
3703
		if (!(node->index->type & DICT_FTS)) {
3704
			dberr_t err = row_ins_index_entry_step(node, thr);
3705

Marko Mäkelä's avatar
Marko Mäkelä committed
3706
			if (err != DB_SUCCESS) {
3707
				DBUG_RETURN(err);
3708 3709 3710 3711
			}
		}

		node->index = dict_table_get_next_index(node->index);
3712
		++node->entry;
3713 3714

		/* Skip corrupted secondary index and its entry */
3715
		while (node->index && node->index->is_corrupted()) {
3716
			node->index = dict_table_get_next_index(node->index);
3717
			++node->entry;
3718 3719 3720
		}
	}

3721
	ut_ad(node->entry == node->entry_list.end());
3722 3723 3724

	node->state = INS_NODE_ALLOC_ROW_ID;

Marko Mäkelä's avatar
Marko Mäkelä committed
3725
	DBUG_RETURN(DB_SUCCESS);
3726 3727 3728 3729 3730
}

/***********************************************************//**
Inserts a row to a table. This is a high-level function used in SQL execution
graphs.
3731
@return query thread to run next or NULL */
3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744
que_thr_t*
row_ins_step(
/*=========*/
	que_thr_t*	thr)	/*!< in: query thread */
{
	ins_node_t*	node;
	que_node_t*	parent;
	sel_node_t*	sel_node;
	trx_t*		trx;
	dberr_t		err;

	ut_ad(thr);

3745 3746
	DEBUG_SYNC_C("innodb_row_ins_step_enter");

3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767
	trx = thr_get_trx(thr);

	node = static_cast<ins_node_t*>(thr->run_node);

	ut_ad(que_node_get_type(node) == QUE_NODE_INSERT);

	parent = que_node_get_parent(node);
	sel_node = node->select;

	if (thr->prev_node == parent) {
		node->state = INS_NODE_SET_IX_LOCK;
	}

	/* If this is the first time this node is executed (or when
	execution resumes after wait for the table IX lock), set an
	IX lock on the table and reset the possible select node. MySQL's
	partitioned table code may also call an insert within the same
	SQL statement AFTER it has used this table handle to do a search.
	This happens, for example, when a row update moves it to another
	partition. In that case, we have already set the IX lock on the
	table during the search operation, and there is no need to set
3768
	it again here. But we must write trx->id to node->sys_buf. */
3769

3770
	if (node->table->no_rollback()) {
3771 3772 3773
		/* No-rollback tables should only be written to by a
		single thread at a time, but there can be multiple
		concurrent readers. We must hold an open table handle. */
Marko Mäkelä's avatar
Marko Mäkelä committed
3774
		DBUG_ASSERT(node->table->get_ref_count() > 0);
3775 3776
		DBUG_ASSERT(node->ins_type == INS_DIRECT);
		/* No-rollback tables can consist only of a single index. */
Marko Mäkelä's avatar
Marko Mäkelä committed
3777
		DBUG_ASSERT(node->entry_list.size() == 1);
3778 3779 3780 3781 3782 3783
		DBUG_ASSERT(UT_LIST_GET_LEN(node->table->indexes) == 1);
		/* There should be no possibility for interruption and
		restarting here. In theory, we could allow resumption
		from the INS_NODE_INSERT_ENTRIES state here. */
		DBUG_ASSERT(node->state == INS_NODE_SET_IX_LOCK);
		node->index = dict_table_get_first_index(node->table);
Marko Mäkelä's avatar
Marko Mäkelä committed
3784
		node->entry = node->entry_list.begin();
3785 3786 3787 3788
		node->state = INS_NODE_INSERT_ENTRIES;
		goto do_insert;
	}

3789
	if (UNIV_LIKELY(!node->table->skip_alter_undo)) {
Marko Mäkelä's avatar
Marko Mäkelä committed
3790
		trx_write_trx_id(&node->sys_buf[DATA_TRX_ID_LEN], trx->id);
3791
	}
3792 3793 3794 3795 3796

	if (node->state == INS_NODE_SET_IX_LOCK) {

		node->state = INS_NODE_ALLOC_ROW_ID;

3797 3798 3799 3800
		if (node->table->is_temporary()) {
			node->trx_id = trx->id;
		}

3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843
		/* It may be that the current session has not yet started
		its transaction, or it has been committed: */

		if (trx->id == node->trx_id) {
			/* No need to do IX-locking */

			goto same_trx;
		}

		err = lock_table(0, node->table, LOCK_IX, thr);

		DBUG_EXECUTE_IF("ib_row_ins_ix_lock_wait",
				err = DB_LOCK_WAIT;);

		if (err != DB_SUCCESS) {

			goto error_handling;
		}

		node->trx_id = trx->id;
same_trx:
		if (node->ins_type == INS_SEARCHED) {
			/* Reset the cursor */
			sel_node->state = SEL_NODE_OPEN;

			/* Fetch a row to insert */

			thr->run_node = sel_node;

			return(thr);
		}
	}

	if ((node->ins_type == INS_SEARCHED)
	    && (sel_node->state != SEL_NODE_FETCH)) {

		ut_ad(sel_node->state == SEL_NODE_NO_MORE_ROWS);

		/* No more rows to insert */
		thr->run_node = parent;

		return(thr);
	}
3844
do_insert:
3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868
	/* DO THE CHECKS OF THE CONSISTENCY CONSTRAINTS HERE */

	err = row_ins(node, thr);

error_handling:
	trx->error_state = err;

	if (err != DB_SUCCESS) {
		/* err == DB_LOCK_WAIT or SQL error detected */
		return(NULL);
	}

	/* DO THE TRIGGER ACTIONS HERE */

	if (node->ins_type == INS_SEARCHED) {
		/* Fetch a row to insert */

		thr->run_node = sel_node;
	} else {
		thr->run_node = que_node_get_parent(node);
	}

	return(thr);
}