row0ins.c 57.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/******************************************************
Insert into a table

(c) 1996 Innobase Oy

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

#include "row0ins.h"

#ifdef UNIV_NONINL
#include "row0ins.ic"
#endif

#include "dict0dict.h"
#include "dict0boot.h"
#include "trx0undo.h"
#include "btr0btr.h"
#include "btr0cur.h"
#include "mach0data.h"
#include "que0que.h"
#include "row0upd.h"
#include "row0sel.h"
#include "row0row.h"
#include "rem0cmp.h"
#include "lock0lock.h"
#include "log0log.h"
#include "eval0eval.h"
#include "data0data.h"
#include "usr0sess.h"

#define	ROW_INS_PREV	1
#define	ROW_INS_NEXT	2

unknown's avatar
unknown committed
35 36 37 38 39 40

/*********************************************************************
This prototype is copied from /mysql/sql/ha_innodb.cc.
Invalidates the MySQL query cache for the table.
NOTE that the exact prototype of this function has to be in
/innobase/row/row0ins.c! */
unknown's avatar
unknown committed
41
extern
unknown's avatar
unknown committed
42 43 44
void
innobase_invalidate_query_cache(
/*============================*/
45 46 47 48 49 50 51
	trx_t*	trx,		/* in: transaction which modifies the table */
	char*	full_name,	/* in: concatenation of database name, null
				char '\0', table name, null char'\0';
				NOTE that in Windows this is always
				in LOWER CASE! */
	ulint	full_name_len);	/* in: full name length where also the null
				chars count */
unknown's avatar
unknown committed
52

53 54 55 56 57 58 59 60 61
/**********************************************************************
This function returns true if SQL-query in the current thread
is either REPLACE or LOAD DATA INFILE REPLACE. 
NOTE that /mysql/innobase/row/row0ins.c must contain the 
prototype for this function ! */

ibool
innobase_query_is_replace(void);
/*===========================*/
unknown's avatar
unknown committed
62

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
/*************************************************************************
Creates an insert node struct. */

ins_node_t*
ins_node_create(
/*============*/
					/* out, own: insert node struct */
	ulint		ins_type,	/* in: INS_VALUES, ... */
	dict_table_t*	table, 		/* in: table where to insert */
	mem_heap_t*	heap)		/* in: mem heap where created */
{
	ins_node_t*	node;

	node = mem_heap_alloc(heap, sizeof(ins_node_t));

	node->common.type = QUE_NODE_INSERT;

	node->ins_type = ins_type;

	node->state = INS_NODE_SET_IX_LOCK;
	node->table = table;
	node->index = NULL;
	node->entry = NULL;

	node->select = NULL;
	
	node->trx_id = ut_dulint_zero;
	
	node->entry_sys_heap = mem_heap_create(128);
92 93 94

	node->magic_n = INS_NODE_MAGIC_N;	
	
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 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 216 217 218 219 220 221 222 223 224 225 226 227 228
	return(node);
}

/***************************************************************
Creates an entry template for each index of a table. */
static
void
ins_node_create_entry_list(
/*=======================*/
	ins_node_t*	node)	/* in: row insert node */
{
	dict_index_t*	index;
	dtuple_t*	entry;

	ut_ad(node->entry_sys_heap);

	UT_LIST_INIT(node->entry_list);

	index = dict_table_get_first_index(node->table);
	
	while (index != NULL) {
		entry = row_build_index_entry(node->row, index,
							node->entry_sys_heap);
		UT_LIST_ADD_LAST(tuple_list, node->entry_list, entry);

		index = dict_table_get_next_index(index);
	}
}

/*********************************************************************
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;
	mem_heap_t*	heap;
	dict_col_t*	col;
	dfield_t*	dfield;
	ulint		len;
	byte*		ptr;

	row = node->row;
	table = node->table;
	heap = node->entry_sys_heap;

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

	/* 1. Allocate buffer for row id */

	col = dict_table_get_sys_col(table, DATA_ROW_ID);
	
	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));

	ptr = mem_heap_alloc(heap, DATA_ROW_ID_LEN);
				
	dfield_set_data(dfield, ptr, DATA_ROW_ID_LEN);

	node->row_id_buf = ptr;

	if (table->type == DICT_TABLE_CLUSTER_MEMBER) {

		/* 2. Fill in the dfield for mix id */

		col = dict_table_get_sys_col(table, DATA_MIX_ID);
	
		dfield = dtuple_get_nth_field(row, dict_col_get_no(col));

		len = mach_dulint_get_compressed_size(table->mix_id);
		ptr = mem_heap_alloc(heap, DATA_MIX_ID_LEN);
				
		mach_dulint_write_compressed(ptr, table->mix_id);
		dfield_set_data(dfield, ptr, len);
	}

	/* 3. Allocate buffer for trx id */

	col = dict_table_get_sys_col(table, DATA_TRX_ID);
	
	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
	ptr = mem_heap_alloc(heap, DATA_TRX_ID_LEN);
				
	dfield_set_data(dfield, ptr, DATA_TRX_ID_LEN);

	node->trx_id_buf = ptr;

	/* 4. Allocate buffer for roll ptr */

	col = dict_table_get_sys_col(table, DATA_ROLL_PTR);
	
	dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
	ptr = mem_heap_alloc(heap, DATA_ROLL_PTR_LEN);
				
	dfield_set_data(dfield, ptr, DATA_ROLL_PTR_LEN);
}

/*************************************************************************
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;
	node->entry = NULL;

	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 = ut_dulint_zero;
}

/***********************************************************************
unknown's avatar
unknown committed
229 230
Does an insert operation by updating a delete-marked existing record
in the index. This situation can occur if the delete-marked record is
231 232 233 234 235 236
kept in the index for consistent reads. */
static
ulint
row_ins_sec_index_entry_by_modify(
/*==============================*/
				/* out: DB_SUCCESS or error code */
unknown's avatar
unknown committed
237 238 239
	ulint		mode,	/* in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
				depending on whether mtr holds just a leaf
				latch or also a tree latch */
240
	btr_cur_t*	cursor,	/* in: B-tree cursor */
241
	dtuple_t*	entry,	/* in: index entry to insert */
242 243 244
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
{
unknown's avatar
unknown committed
245
	big_rec_t*	dummy_big_rec;
246 247 248 249 250 251
	mem_heap_t*	heap;
	upd_t*		update;
	rec_t*		rec;
	ulint		err;
	
	rec = btr_cur_get_rec(cursor);
252
	
253 254 255
	ut_ad((cursor->index->type & DICT_CLUSTERED) == 0);
	ut_ad(rec_get_deleted_flag(rec));
	
unknown's avatar
unknown committed
256
	/* We know that in the alphabetical ordering, entry and rec are
unknown's avatar
unknown committed
257
	identified. But in their binary form there may be differences if
unknown's avatar
unknown committed
258
	there are char fields in them. Therefore we have to calculate the
unknown's avatar
unknown committed
259
	difference. */
260 261 262 263
	
	heap = mem_heap_create(1024);
	
	update = row_upd_build_sec_rec_difference_binary(cursor->index,
264
				entry, rec, thr_get_trx(thr), heap);
unknown's avatar
unknown committed
265 266 267
	if (mode == BTR_MODIFY_LEAF) {
		/* Try an optimistic updating of the record, keeping changes
		within the page */
268

unknown's avatar
unknown committed
269 270 271 272 273 274 275 276 277 278
		err = btr_cur_optimistic_update(BTR_KEEP_SYS_FLAG, cursor,
						update, 0, thr, mtr);
		if (err == DB_OVERFLOW || err == DB_UNDERFLOW) {
			err = DB_FAIL;
		}
	} else  {
		ut_a(mode == BTR_MODIFY_TREE);
		err = btr_cur_pessimistic_update(BTR_KEEP_SYS_FLAG, cursor,
					&dummy_big_rec, update, 0, thr, mtr);
	}
279 280

	mem_heap_free(heap);
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297

	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. */
static
ulint
row_ins_clust_index_entry_by_modify(
/*================================*/
				/* out: DB_SUCCESS, DB_FAIL, or error code */
	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 */
298 299 300
	big_rec_t**	big_rec,/* out: possible big rec vector of fields
				which have to be stored externally by the
				caller */
301
	dtuple_t*	entry,	/* in: index entry to insert */
302 303 304
	ulint*		ext_vec,/* in: array containing field numbers of
				externally stored fields in entry, or NULL */
	ulint		n_ext_vec,/* in: number of fields in ext_vec */
305 306 307 308 309 310 311 312
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
{
	mem_heap_t*	heap;
	rec_t*		rec;
	upd_t*		update;
	ulint		err;
	
313
	ut_ad(cursor->index->type & DICT_CLUSTERED);
314
	
315 316
	*big_rec = NULL;

317 318 319 320 321 322 323
	rec = btr_cur_get_rec(cursor);

	ut_ad(rec_get_deleted_flag(rec));	

	heap = mem_heap_create(1024);
	
	/* Build an update vector containing all the fields to be modified;
unknown's avatar
Merge  
unknown committed
324 325
	NOTE that this vector may NOT contain system columns trx_id or
	roll_ptr */
326
	
327
	update = row_upd_build_difference_binary(cursor->index, entry, ext_vec,
328
			n_ext_vec, rec, thr_get_trx(thr), heap);
329 330 331 332
	if (mode == BTR_MODIFY_LEAF) {
		/* Try optimistic updating of the record, keeping changes
		within the page */

unknown's avatar
unknown committed
333 334
		err = btr_cur_optimistic_update(0, cursor, update, 0, thr,
								   mtr);
335
		if (err == DB_OVERFLOW || err == DB_UNDERFLOW) {
336 337 338
			err = DB_FAIL;
		}
	} else  {
339 340 341
		ut_a(mode == BTR_MODIFY_TREE);
		err = btr_cur_pessimistic_update(0, cursor, big_rec, update,
								0, thr, mtr);
342 343 344 345 346 347 348
	}
	
	mem_heap_free(heap);

	return(err);
}

unknown's avatar
unknown committed
349
/*************************************************************************
unknown's avatar
unknown committed
350
Returns TRUE if in a cascaded update/delete an ancestor node of node
unknown's avatar
unknown committed
351
updates (not DELETE, but UPDATE) table. */
unknown's avatar
unknown committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
static
ibool
row_ins_cascade_ancestor_updates_table(
/*===================================*/
				/* out: TRUE if an ancestor updates table */
	que_node_t*	node,	/* in: node in a query graph */
	dict_table_t*	table)	/* in: table */
{
	que_node_t*	parent;
	upd_node_t*	upd_node;

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

		upd_node = parent;

unknown's avatar
unknown committed
369
		if (upd_node->table == table && upd_node->is_delete == FALSE) {
unknown's avatar
unknown committed
370 371 372 373 374 375 376 377 378 379 380 381

			return(TRUE);
		}

		parent = que_node_get_parent(parent);

		ut_a(parent);
	}

	return(FALSE);
}
	
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
/*************************************************************************
Returns the number of ancestor UPDATE or DELETE nodes of a
cascaded update/delete node. */
static
ulint
row_ins_cascade_n_ancestors(
/*========================*/
				/* out: number of ancestors */
	que_node_t*	node)	/* in: node in a query graph */
{
	que_node_t*	parent;
	ulint		n_ancestors = 0;

	parent = que_node_get_parent(node);
	
	while (que_node_get_type(parent) == QUE_NODE_UPDATE) {
		n_ancestors++;

		parent = que_node_get_parent(parent);

		ut_a(parent);
	}

	return(n_ancestors);
}
	
unknown's avatar
unknown committed
408 409 410 411 412 413 414 415 416 417
/**********************************************************************
Calculates the update vector node->cascade->update for a child table in
a cascaded update. */
static
ulint
row_ins_cascade_calc_update_vec(
/*============================*/
					/* out: number of fields in the
					calculated update vector; the value
					can also be 0 if no foreign key
unknown's avatar
unknown committed
418 419 420 421 422
					fields changed; the returned value
					is ULINT_UNDEFINED if the column
					type in the child table is too short
					to fit the new value in the parent
					table: that means the update fails */
unknown's avatar
unknown committed
423 424
	upd_node_t*	node,		/* in: update node of the parent
					table */
unknown's avatar
unknown committed
425
	dict_foreign_t*	foreign,	/* in: foreign key constraint whose
unknown's avatar
unknown committed
426
					type is != 0 */
unknown's avatar
unknown committed
427 428
	mem_heap_t*	heap)		/* in: memory heap to use as
					temporary storage */
unknown's avatar
unknown committed
429 430 431 432 433 434 435 436 437 438 439 440
{
	upd_node_t*	cascade		= node->cascade_node;
	dict_table_t*	table		= foreign->foreign_table;
	dict_index_t*	index		= foreign->foreign_index;
	upd_t*		update;
	upd_field_t*	ufield;
	dict_table_t*	parent_table;
	dict_index_t*	parent_index;
	upd_t*		parent_update;
	upd_field_t*	parent_ufield;
	ulint		n_fields_updated;
	ulint           parent_field_no;
unknown's avatar
unknown committed
441
	dtype_t*	type;
unknown's avatar
unknown committed
442 443 444 445 446 447
	ulint		i;
	ulint		j;
	    	
	ut_a(node && foreign && cascade && table && index);

	/* Calculate the appropriate update vector which will set the fields
unknown's avatar
unknown committed
448 449 450
	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. */
unknown's avatar
unknown committed
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485

	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;
	update->n_fields = foreign->n_fields;
		
	n_fields_updated = 0;

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

		parent_field_no = dict_table_get_nth_col_pos(
					parent_table,
					dict_index_get_nth_col_no(
							parent_index, i));

		for (j = 0; j < parent_update->n_fields; j++) {
			parent_ufield = parent_update->fields + j;
		
			if (parent_ufield->field_no == parent_field_no) {

				/* 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;

				ufield->field_no =
					dict_table_get_nth_col_pos(table,
					dict_index_get_nth_col_no(index, i));
				ufield->exp = NULL;
unknown's avatar
unknown committed
486

unknown's avatar
unknown committed
487
				ufield->new_val = parent_ufield->new_val;
unknown's avatar
unknown committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535

				type = dict_index_get_nth_type(index, i);

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

				if (ufield->new_val.len == UNIV_SQL_NULL
				    && (type->prtype & DATA_NOT_NULL)) {

				        return(ULINT_UNDEFINED);
				}

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

				if (ufield->new_val.len != UNIV_SQL_NULL
				    && ufield->new_val.len
				       > dtype_get_len(type)) {

				        return(ULINT_UNDEFINED);
				}

				/* 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 */

				if (dtype_is_fixed_size(type)
				    && ufield->new_val.len != UNIV_SQL_NULL
				    && ufield->new_val.len
				       < dtype_get_fixed_size(type)) {

				        ufield->new_val.data =
						mem_heap_alloc(heap,
						  dtype_get_fixed_size(type));
					ufield->new_val.len = 
						dtype_get_fixed_size(type);
					ut_a(dtype_get_pad_char(type)
					     != ULINT_UNDEFINED);

					memset(ufield->new_val.data,
					       (byte)dtype_get_pad_char(type),
					       dtype_get_fixed_size(type));
					ut_memcpy(ufield->new_val.data,
						parent_ufield->new_val.data,
						parent_ufield->new_val.len);
				}

unknown's avatar
unknown committed
536 537 538 539 540 541 542 543 544 545 546 547
				ufield->extern_storage = FALSE;

				n_fields_updated++;
			}
		}
	}

	update->n_fields = n_fields_updated;

	return(n_fields_updated);
}

unknown's avatar
unknown committed
548 549 550 551 552 553 554
/*************************************************************************
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(
/*=======================*/
unknown's avatar
unknown committed
555
	const char*	errstr,		/* in: error string from the viewpoint
unknown's avatar
unknown committed
556 557 558 559 560 561 562 563 564
					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 */
	rec_t*		rec,		/* in: a matching index record in the
					child table */
	dtuple_t*	entry)		/* in: index entry in the parent
					table */
{
565
	FILE*	ef	= dict_foreign_err_file;
566
	trx_t*	trx	= thr_get_trx(thr);
unknown's avatar
unknown committed
567 568

	mutex_enter(&dict_foreign_err_mutex);
569 570 571
	rewind(ef);
	ut_print_timestamp(ef);
	fputs(" Transaction:\n", ef);
572
	trx_print(ef, trx);
573 574

	fputs("Foreign key constraint fails for table ", ef);
575
	ut_print_name(ef, trx, foreign->foreign_table_name);
576
	fputs(":\n", ef);
577
	dict_print_info_on_foreign_key_in_create_format(ef, trx, foreign);
578 579 580
	putc('\n', ef);
	fputs(errstr, ef);
	fputs(" in parent table, in index ", ef);
581
	ut_print_name(ef, trx, foreign->referenced_index->name);
unknown's avatar
unknown committed
582
	if (entry) {
583 584
		fputs(" tuple:\n", ef);
		dtuple_print(ef, entry);
unknown's avatar
unknown committed
585
	}
586
	fputs("\nBut in child table ", ef);
587
	ut_print_name(ef, trx, foreign->foreign_table_name);
588
	fputs(", in index ", ef);
589
	ut_print_name(ef, trx, foreign->foreign_index->name);
unknown's avatar
unknown committed
590
	if (rec) {
591 592 593 594
		fputs(", there is a record:\n", ef);
		rec_print(ef, rec);
	} else {
		fputs(", the record is not available\n", ef);
unknown's avatar
unknown committed
595
	}
596
	putc('\n', ef);
unknown's avatar
unknown committed
597 598 599 600 601 602 603 604 605 606 607 608

	mutex_exit(&dict_foreign_err_mutex);
}

/*************************************************************************
Reports a foreign key error to dict_foreign_err_buf 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(
/*===========================*/
609
	trx_t*		trx,		/* in: transaction */
unknown's avatar
unknown committed
610 611 612 613 614 615 616
	dict_foreign_t*	foreign,	/* in: foreign key constraint */
	rec_t*		rec,		/* in: a record in the parent table:
					it does not match entry because we
					have an error! */
	dtuple_t*	entry)		/* in: index entry to insert in the
					child table */
{
617
	FILE*	ef	= dict_foreign_err_file;
unknown's avatar
unknown committed
618 619

	mutex_enter(&dict_foreign_err_mutex);
620 621 622 623 624
	rewind(ef);
	ut_print_timestamp(ef);
	fputs(" Transaction:\n", ef);
	trx_print(ef, trx);
	fputs("Foreign key constraint fails for table ", ef);
625
	ut_print_name(ef, trx, foreign->foreign_table_name);
626
	fputs(":\n", ef);
627
	dict_print_info_on_foreign_key_in_create_format(ef, trx, foreign);
628
	fputs("\nTrying to add in child table, in index ", ef);
629
	ut_print_name(ef, trx, foreign->foreign_index->name);
unknown's avatar
unknown committed
630
	if (entry) {
631 632
		fputs(" tuple:\n", ef);
		dtuple_print(ef, entry);
unknown's avatar
unknown committed
633
	}
634
	fputs("\nBut in parent table ", ef);
635
	ut_print_name(ef, trx, foreign->referenced_table_name);
636
	fputs(", in index ", ef);
637
	ut_print_name(ef, trx, foreign->referenced_index->name);
638
	fputs(",\nthe closest match we can find is record:\n", ef);
unknown's avatar
unknown committed
639 640 641 642 643 644 645 646
	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(rec);
	}

	if (rec) {
647
		rec_print(ef, rec);
unknown's avatar
unknown committed
648
	}
649
	putc('\n', ef);
unknown's avatar
unknown committed
650 651 652 653

	mutex_exit(&dict_foreign_err_mutex);
}

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
/*************************************************************************
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 */
{
	char*	buf;
	char*	ptr;
	ulint	len = strlen(name) + 1;

	buf = mem_strdupl(name, len);

	ptr = strchr(buf, '/');
	ut_a(ptr);
	*ptr = '\0';

	/* We call a function in ha_innodb.cc */
#ifndef UNIV_HOTBACKUP
	innobase_invalidate_query_cache(thr_get_trx(thr), buf, len);
#endif
	mem_free(buf);
}

unknown's avatar
unknown committed
682 683 684 685
/*************************************************************************
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. */
unknown's avatar
unknown committed
686 687
static
ulint
unknown's avatar
unknown committed
688 689
row_ins_foreign_check_on_constraint(
/*================================*/
unknown's avatar
unknown committed
690 691 692 693 694 695 696 697
					/* out: DB_SUCCESS, DB_LOCK_WAIT,
					or error code */
	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 */
unknown's avatar
unknown committed
698 699
	dtuple_t*	entry,		/* in: index entry in the parent
					table */
unknown's avatar
unknown committed
700 701 702 703 704 705 706 707 708 709
	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;
	mem_heap_t*	tmp_heap;
unknown's avatar
unknown committed
710
	mem_heap_t*	upd_vec_heap	= NULL;
unknown's avatar
unknown committed
711 712 713
	rec_t*		rec;
	rec_t*		clust_rec;
	upd_t*		update;
unknown's avatar
unknown committed
714
	ulint		n_to_update;
unknown's avatar
unknown committed
715 716
	ulint		err;
	ulint		i;
717
	trx_t*		trx;
unknown's avatar
unknown committed
718

unknown's avatar
unknown committed
719 720 721
	
	ut_a(thr && foreign && pcur && mtr);

722 723
	trx = thr_get_trx(thr);

unknown's avatar
unknown committed
724 725 726
	/* Since we are going to delete or update a row, we have to invalidate
	the MySQL query cache for table */

727
	row_ins_invalidate_query_cache(thr, table->name);
unknown's avatar
unknown committed
728

unknown's avatar
unknown committed
729 730
	node = thr->run_node;

unknown's avatar
unknown committed
731 732 733 734
	if (node->is_delete && 0 == (foreign->type &
			(DICT_FOREIGN_ON_DELETE_CASCADE
			 | DICT_FOREIGN_ON_DELETE_SET_NULL))) {

unknown's avatar
unknown committed
735
		row_ins_foreign_report_err("Trying to delete",
unknown's avatar
unknown committed
736 737 738
					thr, foreign,
					btr_pcur_get_rec(pcur), entry);

unknown's avatar
unknown committed
739 740 741 742 743 744 745 746 747
	        return(DB_ROW_IS_REFERENCED);
	}

	if (!node->is_delete && 0 == (foreign->type &
			(DICT_FOREIGN_ON_UPDATE_CASCADE
			 | DICT_FOREIGN_ON_UPDATE_SET_NULL))) {

		/* This is an UPDATE */
			 
unknown's avatar
unknown committed
748
		row_ins_foreign_report_err("Trying to update",
unknown's avatar
unknown committed
749 750 751
					thr, foreign,
					btr_pcur_get_rec(pcur), entry);

unknown's avatar
unknown committed
752 753 754
	        return(DB_ROW_IS_REFERENCED);
	}

unknown's avatar
unknown committed
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
	if (node->cascade_node == NULL) {
		/* Extend our query graph by creating a child to current
		update node. The child is used in the cascade or set null
		operation. */

		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);
	}

	/* Initialize cascade_node to do the operation we want. Note that we
	use the SAME cascade node to do all foreign key operations of the
	SQL DELETE: the table of the cascade node may change if there are
	several child tables to the table where the delete is done! */

	cascade = node->cascade_node;
	
	cascade->table = table;

unknown's avatar
unknown committed
775 776 777 778
	cascade->foreign = foreign;
	
	if (node->is_delete
	    && (foreign->type & DICT_FOREIGN_ON_DELETE_CASCADE)) {
unknown's avatar
unknown committed
779 780 781 782 783 784 785 786 787 788 789 790 791
		cascade->is_delete = TRUE;
	} else {
		cascade->is_delete = FALSE;

		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;
		}
	}

unknown's avatar
unknown committed
792 793 794 795 796 797 798 799 800
	/* 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! */

	if (!cascade->is_delete
unknown's avatar
unknown committed
801 802 803 804 805 806 807
	    && row_ins_cascade_ancestor_updates_table(cascade, table)) {

	        /* We do not know if this would break foreign key
	        constraints, but play safe and return an error */

	        err = DB_ROW_IS_REFERENCED;

unknown's avatar
unknown committed
808
		row_ins_foreign_report_err(
unknown's avatar
unknown committed
809
"Trying an update, possibly causing a cyclic cascaded update\n"
unknown's avatar
unknown committed
810 811
"in the child table,", thr, foreign, btr_pcur_get_rec(pcur), entry);

unknown's avatar
unknown committed
812 813 814
		goto nonstandard_exit_func;
	}

815 816 817 818 819 820 821 822 823 824
	if (row_ins_cascade_n_ancestors(cascade) >= 15) {
		err = DB_ROW_IS_REFERENCED;

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

		goto nonstandard_exit_func;
	}

unknown's avatar
unknown committed
825 826
	index = btr_pcur_get_btr_cur(pcur)->index;

unknown's avatar
unknown committed
827 828
	ut_a(index == foreign->foreign_index);
	
unknown's avatar
unknown committed
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
	rec = btr_pcur_get_rec(pcur);

	if (index->type & DICT_CLUSTERED) {
		/* pcur is already positioned in the clustered index of
		the child table */
	
		clust_index = index;
		clust_rec = rec;
	} else {
		/* We have to look for the record in the clustered index
		in the child table */

		clust_index = dict_table_get_first_index(table);

		tmp_heap = mem_heap_create(256);
		
		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,
			cascade->pcur, 0, mtr);

		mem_heap_free(tmp_heap);

		clust_rec = btr_pcur_get_rec(cascade->pcur);

unknown's avatar
unknown committed
855 856 857 858
		if (!page_rec_is_user_rec(clust_rec)
		    || btr_pcur_get_low_match(cascade->pcur)
		       < dict_index_get_n_unique(clust_index)) {

859
			fputs(
unknown's avatar
unknown committed
860
			"InnoDB: error in cascade of a foreign key op\n"
861
			"InnoDB: ", stderr);
862
			dict_index_name_print(stderr, trx, index);
863 864 865 866 867 868 869 870

			fputs("\n"
				"InnoDB: record ", stderr);
			rec_print(stderr, rec);
			fputs("\n"
				"InnoDB: clustered record ", stderr);
			rec_print(stderr, clust_rec);
			fputs("\n"
871
"InnoDB: Submit a detailed bug report to http://bugs.mysql.com\n", stderr);
unknown's avatar
unknown committed
872

unknown's avatar
unknown committed
873
			err = DB_SUCCESS;
unknown's avatar
unknown committed
874

unknown's avatar
unknown committed
875 876
			goto nonstandard_exit_func;
		}
unknown's avatar
unknown committed
877 878 879 880 881 882 883
	}

	/* 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) {
unknown's avatar
unknown committed
884 885 886 887
		/* 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 */
		
unknown's avatar
unknown committed
888
		err = lock_clust_rec_read_check_and_lock(0, clust_rec,
unknown's avatar
unknown committed
889
				clust_index, LOCK_X, LOCK_REC_NOT_GAP, thr);
unknown's avatar
unknown committed
890 891 892 893 894 895 896 897
	}
	
	if (err != DB_SUCCESS) {

		goto nonstandard_exit_func;
	}

	if (rec_get_deleted_flag(clust_rec)) {
unknown's avatar
unknown committed
898 899 900 901
		/* 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;		
unknown's avatar
unknown committed
902 903 904 905

		goto nonstandard_exit_func;
	}

unknown's avatar
unknown committed
906 907 908 909 910
	if ((node->is_delete
	    && (foreign->type & DICT_FOREIGN_ON_DELETE_SET_NULL))
	   || (!node->is_delete
	    && (foreign->type & DICT_FOREIGN_ON_UPDATE_SET_NULL))) {
	    	
unknown's avatar
unknown committed
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
		/* 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;
		
		for (i = 0; i < foreign->n_fields; i++) {
			(update->fields + i)->field_no
				= dict_table_get_nth_col_pos(table,
					dict_index_get_nth_col_no(index, i));
			(update->fields + i)->exp = NULL;
			(update->fields + i)->new_val.len = UNIV_SQL_NULL;
			(update->fields + i)->new_val.data = NULL;
			(update->fields + i)->extern_storage = FALSE;
		}
	}

unknown's avatar
unknown committed
930 931 932 933 934 935
	if (!node->is_delete
	    && (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 */

unknown's avatar
unknown committed
936 937 938 939 940 941 942 943
		upd_vec_heap = mem_heap_create(256);

		n_to_update = row_ins_cascade_calc_update_vec(node, foreign,
							      upd_vec_heap);
		if (n_to_update == ULINT_UNDEFINED) {
		        err = DB_ROW_IS_REFERENCED;

			row_ins_foreign_report_err(
unknown's avatar
unknown committed
944
"Trying a cascaded update where the updated value in the child\n"
unknown's avatar
unknown committed
945 946 947 948 949 950
"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;
		}
unknown's avatar
unknown committed
951 952 953 954 955 956 957 958 959 960 961 962 963

		if (cascade->update->n_fields == 0) {

			/* 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;			
		}
	}
	
unknown's avatar
unknown committed
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
	/* 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);
	}
		
	mtr_commit(mtr);

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

	cascade->state = UPD_NODE_UPDATE_CLUSTERED;
	
	err = row_update_cascade_for_mysql(thr, cascade,
						foreign->foreign_table);
	mtr_start(mtr);

	/* Restore pcur position */
	
	btr_pcur_restore_position(BTR_SEARCH_LEAF, pcur, mtr);

unknown's avatar
unknown committed
989 990 991 992
	if (upd_vec_heap) {
	        mem_heap_free(upd_vec_heap);
	}

unknown's avatar
unknown committed
993 994 995 996
	return(err);

nonstandard_exit_func:

unknown's avatar
unknown committed
997 998 999 1000
	if (upd_vec_heap) {
	        mem_heap_free(upd_vec_heap);
	}

unknown's avatar
unknown committed
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
	btr_pcur_store_position(pcur, mtr);

	mtr_commit(mtr);
	mtr_start(mtr);

	btr_pcur_restore_position(BTR_SEARCH_LEAF, pcur, mtr);

	return(err);
}

unknown's avatar
unknown committed
1011 1012
/*************************************************************************
Sets a shared lock on a record. Used in locking possible duplicate key
unknown's avatar
unknown committed
1013
records and also in checking foreign key constraints. */
unknown's avatar
unknown committed
1014 1015 1016 1017 1018
static
ulint
row_ins_set_shared_rec_lock(
/*========================*/
				/* out: DB_SUCCESS or error code */
unknown's avatar
unknown committed
1019 1020
	ulint		type, 	/* in: LOCK_ORDINARY, LOCK_GAP, or
				LOCK_REC_NOT_GAP type lock */
unknown's avatar
unknown committed
1021 1022 1023 1024 1025
	rec_t*		rec,	/* in: record */
	dict_index_t*	index,	/* in: index */
	que_thr_t*	thr)	/* in: query thread */	
{
	ulint	err;
1026 1027

	if (index->type & DICT_CLUSTERED) {
unknown's avatar
unknown committed
1028
		err = lock_clust_rec_read_check_and_lock(0, rec, index, LOCK_S,
unknown's avatar
unknown committed
1029
								type, thr);
1030
	} else {
unknown's avatar
unknown committed
1031
		err = lock_sec_rec_read_check_and_lock(0, rec, index, LOCK_S,
unknown's avatar
unknown committed
1032
								type, thr);
1033 1034
	}

unknown's avatar
unknown committed
1035 1036
	return(err);
}
1037 1038 1039 1040 1041 1042 1043

/*************************************************************************
Sets a exclusive lock on a record. Used in locking possible duplicate key
records */
static
ulint
row_ins_set_exclusive_rec_lock(
1044
/*============================*/
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
				/* out: DB_SUCCESS or error code */
	ulint		type, 	/* in: LOCK_ORDINARY, LOCK_GAP, or
				LOCK_REC_NOT_GAP type lock */
	rec_t*		rec,	/* in: record */
	dict_index_t*	index,	/* in: index */
	que_thr_t*	thr)	/* in: query thread */	
{
	ulint	err;

	if (index->type & DICT_CLUSTERED) {
		err = lock_clust_rec_read_check_and_lock(0, rec, index, LOCK_X,
								type, thr);
	} else {
		err = lock_sec_rec_read_check_and_lock(0, rec, index, LOCK_X,
								type, thr);
	}

	return(err);
}
1064
	
1065 1066 1067
/*******************************************************************
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
unknown's avatar
unknown committed
1068
the caller must have a shared latch on dict_operation_lock. */
1069 1070 1071 1072

ulint
row_ins_check_foreign_constraint(
/*=============================*/
unknown's avatar
unknown committed
1073
				/* out: DB_SUCCESS,
1074 1075
				DB_NO_REFERENCED_ROW,
				or DB_ROW_IS_REFERENCED */
unknown's avatar
unknown committed
1076
	ibool		check_ref,/* in: TRUE if we want to check that
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
				the referenced table is ok, FALSE if we
				want to 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 */
{
unknown's avatar
unknown committed
1087
  	upd_node_t*  	upd_node;
1088 1089 1090
	dict_table_t*	check_table;
	dict_index_t*	check_index;
	ulint		n_fields_cmp;
unknown's avatar
unknown committed
1091
	ibool		unique_search;
1092 1093 1094 1095 1096
	rec_t*		rec;
	btr_pcur_t	pcur;
	ibool		moved;
	int		cmp;
	ulint		err;
unknown's avatar
unknown committed
1097
	ulint		i;
1098
	mtr_t		mtr;
1099
	trx_t*		trx = thr_get_trx(thr);
1100

unknown's avatar
unknown committed
1101
run_again:
1102
#ifdef UNIV_SYNC_DEBUG
unknown's avatar
unknown committed
1103
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_SHARED));
1104 1105
#endif /* UNIV_SYNC_DEBUG */

unknown's avatar
unknown committed
1106
	err = DB_SUCCESS;
1107

1108
	if (trx->check_foreigns == FALSE) {
unknown's avatar
unknown committed
1109 1110 1111 1112 1113 1114
		/* The user has suppressed foreign key checks currently for
		this session */

		return(DB_SUCCESS);
	}

unknown's avatar
unknown committed
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
	/* 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 */

	for (i = 0; i < foreign->n_fields; i++) {
		if (UNIV_SQL_NULL == dfield_get_len(
                                         dtuple_get_nth_field(entry, i))) {

			return(DB_SUCCESS);
		}
	}

unknown's avatar
unknown committed
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
	if (que_node_get_type(thr->run_node) == QUE_NODE_UPDATE) {
	        upd_node = thr->run_node;

	        if (!(upd_node->is_delete) && upd_node->foreign == foreign) {
		        /* 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. */
		
		        return(DB_SUCCESS);
		}
	}

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
	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) {
		if (check_ref) {
1161
			FILE*	ef = dict_foreign_err_file;
unknown's avatar
unknown committed
1162
			mutex_enter(&dict_foreign_err_mutex);
1163 1164 1165
			rewind(ef);
			ut_print_timestamp(ef);
			fputs(" Transaction:\n", ef);
1166
			trx_print(ef, trx);
1167
			fputs("Foreign key constraint fails for table ", ef);
1168
			ut_print_name(ef, trx, foreign->foreign_table_name);
1169 1170
			fputs(":\n", ef);
			dict_print_info_on_foreign_key_in_create_format(ef,
1171
					trx, foreign);
1172
			fputs("\nTrying to add to index ", ef);
1173
			ut_print_name(ef, trx, foreign->foreign_index->name);
1174 1175 1176
			fputs(" tuple:\n", ef);
			dtuple_print(ef, entry);
			fputs("\nBut the parent table ", ef);
1177
			ut_print_name(ef, trx, foreign->referenced_table_name);
1178
			fputs(" does not currently exist!\n", ef);
unknown's avatar
unknown committed
1179 1180
			mutex_exit(&dict_foreign_err_mutex);

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
			return(DB_NO_REFERENCED_ROW);
		}

		return(DB_SUCCESS);
	}

	ut_a(check_table && check_index);

	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) {

unknown's avatar
unknown committed
1197
			goto do_possible_lock_wait;
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
		}
	}

	mtr_start(&mtr);

	/* 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);

unknown's avatar
unknown committed
1209 1210 1211 1212 1213 1214 1215 1216
	if (dict_index_get_n_unique(check_index) <= foreign->n_fields) {
		/* We can just set a LOCK_REC_NOT_GAP type lock */
	
		unique_search = TRUE;
	} else {
		unique_search = FALSE;
	}

1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
	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 */

	for (;;) {
		rec = btr_pcur_get_rec(&pcur);

		if (rec == page_get_infimum_rec(buf_frame_align(rec))) {

			goto next_rec;
		}
unknown's avatar
unknown committed
1229
		
1230 1231
		if (rec == page_get_supremum_rec(buf_frame_align(rec))) {
		
unknown's avatar
unknown committed
1232 1233 1234 1235 1236 1237 1238
			err = row_ins_set_shared_rec_lock(LOCK_ORDINARY, rec,
							check_index, thr);
			if (err != DB_SUCCESS) {

				break;
			}

1239 1240 1241 1242 1243 1244
			goto next_rec;
		}

		cmp = cmp_dtuple_rec(entry, rec);

		if (cmp == 0) {
unknown's avatar
unknown committed
1245
			if (rec_get_deleted_flag(rec)) {
unknown's avatar
unknown committed
1246 1247
				err = row_ins_set_shared_rec_lock(
							LOCK_ORDINARY,
unknown's avatar
unknown committed
1248 1249 1250 1251 1252 1253
							rec, check_index, thr);
				if (err != DB_SUCCESS) {

					break;
				}
			} else {
1254
				/* Found a matching record */
unknown's avatar
unknown committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
				
				if (unique_search) {
					err = row_ins_set_shared_rec_lock(
							LOCK_REC_NOT_GAP,
							rec, check_index, thr);
				} else {
					err = row_ins_set_shared_rec_lock(
							LOCK_ORDINARY,
							rec, check_index, thr);
				}
				
				if (err != DB_SUCCESS) {

					break;
				}
1270 1271 1272

				if (check_ref) {			
					err = DB_SUCCESS;
unknown's avatar
unknown committed
1273 1274 1275

					break;
				} else if (foreign->type != 0) {
unknown's avatar
unknown committed
1276 1277 1278 1279
					/* There is an ON UPDATE or ON DELETE
					condition: check them in a separate
					function */

unknown's avatar
unknown committed
1280
					err =
unknown's avatar
unknown committed
1281
					  row_ins_foreign_check_on_constraint(
unknown's avatar
unknown committed
1282 1283
						thr, foreign, &pcur, entry,
									&mtr);
unknown's avatar
unknown committed
1284 1285 1286 1287
					if (err != DB_SUCCESS) {

						break;
					}
1288
				} else {
unknown's avatar
unknown committed
1289
					row_ins_foreign_report_err(
unknown's avatar
unknown committed
1290
						"Trying to delete or update",
unknown's avatar
unknown committed
1291 1292
						thr, foreign, rec, entry);

1293
					err = DB_ROW_IS_REFERENCED;
unknown's avatar
unknown committed
1294
					break;
1295 1296 1297 1298 1299
				}
			}
		}

		if (cmp < 0) {
unknown's avatar
unknown committed
1300 1301 1302 1303 1304 1305 1306
			err = row_ins_set_shared_rec_lock(LOCK_GAP,
						rec, check_index, thr);
			if (err != DB_SUCCESS) {

				break;
			}

1307 1308
			if (check_ref) {			
				err = DB_NO_REFERENCED_ROW;
unknown's avatar
unknown committed
1309
				row_ins_foreign_report_add_err(
1310
					trx, foreign, rec, entry);
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
			} else {
				err = DB_SUCCESS;
			}

			break;
		}

		ut_a(cmp == 0);
next_rec:
		moved = btr_pcur_move_to_next(&pcur, &mtr);

		if (!moved) {
			if (check_ref) {			
unknown's avatar
unknown committed
1324 1325
				rec = btr_pcur_get_rec(&pcur);
				row_ins_foreign_report_add_err(
1326
					trx, foreign, rec, entry);
1327 1328 1329 1330 1331 1332 1333 1334 1335
				err = DB_NO_REFERENCED_ROW;
			} else {
				err = DB_SUCCESS;
			}

			break;
		}
	}

unknown's avatar
unknown committed
1336 1337
	btr_pcur_close(&pcur);

1338 1339 1340 1341 1342
	mtr_commit(&mtr);

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

unknown's avatar
unknown committed
1343 1344
do_possible_lock_wait:
	if (err == DB_LOCK_WAIT) {
1345
		trx->error_state = err;
unknown's avatar
unknown committed
1346 1347

		que_thr_stop_for_mysql(thr);
unknown's avatar
unknown committed
1348

unknown's avatar
unknown committed
1349
		srv_suspend_mysql_thread(thr);
unknown's avatar
unknown committed
1350
	
1351
		if (trx->error_state == DB_SUCCESS) {
unknown's avatar
unknown committed
1352 1353 1354

		        goto run_again;
		}
unknown's avatar
unknown committed
1355

1356
		err = trx->error_state;
unknown's avatar
unknown committed
1357 1358
	}

1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
	return(err);
}

/*******************************************************************
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. */
static
ulint
row_ins_check_foreign_constraints(
/*==============================*/
unknown's avatar
unknown committed
1372
				/* out: DB_SUCCESS or error code */
1373 1374 1375 1376 1377 1378 1379
	dict_table_t*	table,	/* in: table */
	dict_index_t*	index,	/* in: index */
	dtuple_t*	entry,	/* in: index entry for index */
	que_thr_t*	thr)	/* in: query thread */
{
	dict_foreign_t*	foreign;
	ulint		err;
unknown's avatar
unknown committed
1380 1381 1382 1383
	trx_t*		trx;
	ibool		got_s_lock	= FALSE;

	trx = thr_get_trx(thr);
1384 1385 1386 1387 1388 1389 1390 1391

	foreign = UT_LIST_GET_FIRST(table->foreign_list);

	while (foreign) {
		if (foreign->foreign_index == index) {

			if (foreign->referenced_table == NULL) {
				dict_table_get(foreign->referenced_table_name,
unknown's avatar
unknown committed
1392
									trx);
1393 1394
			}

unknown's avatar
unknown committed
1395
			if (0 == trx->dict_operation_lock_mode) {
unknown's avatar
unknown committed
1396 1397
				got_s_lock = TRUE;

unknown's avatar
unknown committed
1398
				row_mysql_freeze_data_dictionary(trx);
unknown's avatar
unknown committed
1399
			}
1400 1401

			err = row_ins_check_foreign_constraint(TRUE, foreign,
unknown's avatar
unknown committed
1402
						table, entry, thr);
unknown's avatar
unknown committed
1403
			if (got_s_lock) {
unknown's avatar
unknown committed
1404
				row_mysql_unfreeze_data_dictionary(trx);
unknown's avatar
unknown committed
1405 1406
			}
				
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
			if (err != DB_SUCCESS) {
				return(err);
			}
		}

		foreign = UT_LIST_GET_NEXT(foreign_list, foreign);
	}

	return(DB_SUCCESS);
}

unknown's avatar
unknown committed
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
/*******************************************************************
Checks if a unique key violation to rec would occur at the index entry
insert. */
static
ibool
row_ins_dupl_error_with_rec(
/*========================*/
				/* out: TRUE if error */
	rec_t*		rec,	/* in: user record; NOTE that we assume
				that the caller already has a record lock on
				the record! */
	dtuple_t*	entry,	/* in: entry to insert */
	dict_index_t*	index)	/* in: index */
{
	ulint	matched_fields;
	ulint	matched_bytes;
	ulint	n_unique;
	ulint   i;
	
	n_unique = dict_index_get_n_unique(index);

	matched_fields = 0;
	matched_bytes = 0;

	cmp_dtuple_rec_with_match(entry, rec, &matched_fields, &matched_bytes);

	if (matched_fields < n_unique) {

	        return(FALSE);
	}

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

	if (!(index->type & DICT_CLUSTERED)) {

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

	                        return(FALSE);
	                }
	        }
	}

	if (!rec_get_deleted_flag(rec)) {

	        return(TRUE);
	}

	return(FALSE);
}	

1471 1472
/*******************************************************************
Scans a unique non-clustered index at a given index entry to determine
unknown's avatar
unknown committed
1473 1474
whether a uniqueness violation has occurred for the key value of the entry.
Set shared locks on possible duplicate records. */
1475 1476 1477 1478
static
ulint
row_ins_scan_sec_index_for_duplicate(
/*=================================*/
unknown's avatar
unknown committed
1479 1480
				/* out: DB_SUCCESS, DB_DUPLICATE_KEY, or
				DB_LOCK_WAIT */
1481 1482
	dict_index_t*	index,	/* in: non-clustered unique index */
	dtuple_t*	entry,	/* in: index entry */
unknown's avatar
unknown committed
1483
	que_thr_t*	thr)	/* in: query thread */
1484
{
unknown's avatar
unknown committed
1485 1486
	ulint		n_unique;
	ulint		i;
1487 1488 1489 1490
	int		cmp;
	ulint		n_fields_cmp;
	rec_t*		rec;
	btr_pcur_t	pcur;
unknown's avatar
unknown committed
1491 1492
	ulint		err		= DB_SUCCESS;
	ibool		moved;
1493
	mtr_t		mtr;
1494 1495 1496
	trx_t*		trx;
	const char*	ptr;
	
unknown's avatar
unknown committed
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
	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 */

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

			return(DB_SUCCESS);
		}
	}

1511 1512 1513 1514 1515 1516 1517 1518
	mtr_start(&mtr);

	/* Store old value on n_fields_cmp */

	n_fields_cmp = dtuple_get_n_fields_cmp(entry);

	dtuple_set_n_fields_cmp(entry, dict_index_get_n_unique(index));
	
unknown's avatar
unknown committed
1519
	btr_pcur_open(index, entry, PAGE_CUR_GE, BTR_SEARCH_LEAF, &pcur, &mtr);
1520

unknown's avatar
unknown committed
1521
	/* Scan index records and check if there is a duplicate */
1522 1523

	for (;;) {
unknown's avatar
unknown committed
1524 1525 1526 1527 1528 1529 1530
		rec = btr_pcur_get_rec(&pcur);

		if (rec == page_get_infimum_rec(buf_frame_align(rec))) {

			goto next_rec;
		}
				
unknown's avatar
unknown committed
1531
		/* Try to place a lock on the index record */
unknown's avatar
unknown committed
1532

1533 1534
		trx = thr_get_trx(thr);      
		ut_ad(trx);
1535

1536
		if (innobase_query_is_replace()) {
1537

1538 1539 1540 1541 1542 1543 1544
			/* The manual defines the REPLACE semantics that it 
			is either an INSERT or DELETE(s) for duplicate key
			+ INSERT. Therefore, we should take X-lock for 
			duplicates */
			
			err = row_ins_set_exclusive_rec_lock(
						LOCK_ORDINARY,rec,index,thr);
1545 1546
		} else {

1547 1548
			err = row_ins_set_shared_rec_lock(
						LOCK_ORDINARY, rec, index,thr);
1549 1550
		}

unknown's avatar
unknown committed
1551
		if (err != DB_SUCCESS) {
1552 1553 1554 1555

			break;
		}

unknown's avatar
unknown committed
1556 1557 1558 1559
		if (rec == page_get_supremum_rec(buf_frame_align(rec))) {
		
			goto next_rec;
		}
1560 1561 1562 1563

		cmp = cmp_dtuple_rec(entry, rec);

		if (cmp == 0) {
unknown's avatar
unknown committed
1564 1565 1566
			if (row_ins_dupl_error_with_rec(rec, entry, index)) {
				err = DB_DUPLICATE_KEY;

1567
				thr_get_trx(thr)->error_info = index;
unknown's avatar
unknown committed
1568 1569

				break;
1570 1571 1572 1573 1574 1575 1576 1577
			}
		}

		if (cmp < 0) {
			break;
		}

		ut_a(cmp == 0);
unknown's avatar
unknown committed
1578 1579
next_rec:
		moved = btr_pcur_move_to_next(&pcur, &mtr);
1580

unknown's avatar
unknown committed
1581 1582 1583
		if (!moved) {
			break;
		}
1584 1585 1586 1587 1588 1589 1590
	}

	mtr_commit(&mtr);

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

unknown's avatar
unknown committed
1591
	return(err);
1592 1593 1594
}

/*******************************************************************
unknown's avatar
unknown committed
1595 1596 1597
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! */
1598 1599
static
ulint
unknown's avatar
unknown committed
1600 1601 1602 1603 1604 1605
row_ins_duplicate_error_in_clust(
/*=============================*/
				/* out: DB_SUCCESS if no error,
				DB_DUPLICATE_KEY if error, DB_LOCK_WAIT if we
				have to wait for a lock on a possible
				duplicate record */
1606 1607
	btr_cur_t*	cursor,	/* in: B-tree cursor */
	dtuple_t*	entry,	/* in: entry to insert */
unknown's avatar
unknown committed
1608 1609
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
1610
{
unknown's avatar
unknown committed
1611
	ulint	err;
1612 1613 1614
	rec_t*	rec;
	page_t*	page;
	ulint	n_unique;
unknown's avatar
unknown committed
1615
	trx_t*	trx	= thr_get_trx(thr);
1616
	const char*	ptr;
1617

1618 1619
	UT_NOT_USED(mtr);
	
unknown's avatar
unknown committed
1620
	ut_a(cursor->index->type & DICT_CLUSTERED);
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
	ut_ad(cursor->index->type & DICT_UNIQUE);

	/* 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);
		page = buf_frame_align(rec);

		if (rec != page_get_infimum_rec(page)) {

unknown's avatar
unknown committed
1645 1646 1647 1648
			/* 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 */
1649

1650
			if (innobase_query_is_replace()) {
1651

1652 1653 1654 1655
				/* The manual defines the REPLACE semantics 
				that it is either an INSERT or DELETE(s) 
				for duplicate key + INSERT. Therefore, we 
				should take X-lock for duplicates */
1656 1657
				
				err = row_ins_set_exclusive_rec_lock(
1658 1659
					LOCK_REC_NOT_GAP,rec,cursor->index,
					thr);
1660 1661 1662
			} else {
				
				err = row_ins_set_shared_rec_lock(
1663 1664
					LOCK_REC_NOT_GAP,rec, cursor->index, 
					thr);
1665 1666
			} 

unknown's avatar
unknown committed
1667 1668 1669 1670 1671
			if (err != DB_SUCCESS) {
					
				return(err);
			}

1672
			if (row_ins_dupl_error_with_rec(rec, entry,
unknown's avatar
unknown committed
1673
							cursor->index)) {
1674
				trx->error_info = cursor->index;
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
				return(DB_DUPLICATE_KEY);
			}
		}
	}

	if (cursor->up_match >= n_unique) {

		rec = page_rec_get_next(btr_cur_get_rec(cursor));
		page = buf_frame_align(rec);

		if (rec != page_get_supremum_rec(page)) {

1687

1688 1689 1690
			/* The manual defines the REPLACE semantics that it 
			is either an INSERT or DELETE(s) for duplicate key
			+ INSERT. Therefore, we should take X-lock for
1691
			duplicates. */
1692

1693
			if (innobase_query_is_replace()) {
1694

1695 1696 1697 1698
				err = row_ins_set_exclusive_rec_lock(
						LOCK_REC_NOT_GAP,
						rec,cursor->index,thr);
			} else {
1699

1700 1701 1702 1703
				err = row_ins_set_shared_rec_lock(
						LOCK_REC_NOT_GAP,rec, 
						cursor->index, thr);
			}
1704

unknown's avatar
unknown committed
1705 1706 1707 1708 1709
			if (err != DB_SUCCESS) {
					
				return(err);
			}

1710
			if (row_ins_dupl_error_with_rec(rec, entry,
unknown's avatar
unknown committed
1711
							cursor->index)) {
1712
				trx->error_info = cursor->index;
1713 1714 1715 1716 1717 1718 1719 1720
				return(DB_DUPLICATE_KEY);
			}
		}

		ut_a(!(cursor->index->type & DICT_CLUSTERED));
						/* This should never happen */
	}

unknown's avatar
unknown committed
1721
	return(DB_SUCCESS);
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 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 1782 1783 1784 1785 1786 1787
}

/*******************************************************************
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, and in the case of a secondary index, all fields must be
equal. */
UNIV_INLINE
ulint
row_ins_must_modify(
/*================*/
				/* out: 0 if no update, ROW_INS_PREV if
				previous should be updated; currently we
				do the search so that only the low_match
				record can match enough to the search tuple,
				not the next record */
	btr_cur_t*	cursor)	/* in: B-tree cursor */
{
	ulint	enough_match;
	rec_t*	rec;
	page_t*	page;
	
	/* NOTE: (compare to the note in row_ins_duplicate_error) 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. In a clustered index
	node pointers contain index->n_unique first fields, and in the case
	of a secondary index, all fields of the index. */

	enough_match = dict_index_get_n_unique_in_tree(cursor->index);
	
	if (cursor->low_match >= enough_match) {

		rec = btr_cur_get_rec(cursor);
		page = buf_frame_align(rec);

		if (rec != page_get_infimum_rec(page)) {

			return(ROW_INS_PREV);
		}
	}

	return(0);
}

/*******************************************************************
Tries to insert an index entry to an index. If the index is clustered
and 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. If the index is secondary, and 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. */

ulint
row_ins_index_entry_low(
/*====================*/
				/* out: DB_SUCCESS, DB_LOCK_WAIT, DB_FAIL
				if pessimistic retry needed, or error code */
	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: index */
	dtuple_t*	entry,	/* in: index entry to insert */
1788 1789 1790
	ulint*		ext_vec,/* in: array containing field numbers of
				externally stored fields in entry, or NULL */
	ulint		n_ext_vec,/* in: number of fields in ext_vec */
1791 1792
	que_thr_t*	thr)	/* in: query thread */
{
unknown's avatar
unknown committed
1793 1794
	btr_cur_t	cursor;
	ulint		ignore_sec_unique	= 0;
unknown's avatar
unknown committed
1795
	ulint		modify = 0; /* remove warning */
1796
	rec_t*		insert_rec;
1797
	rec_t*		rec;
unknown's avatar
unknown committed
1798
	rec_t*		first_rec;
1799 1800
	ulint		err;
	ulint		n_unique;
unknown's avatar
unknown committed
1801
	big_rec_t*	big_rec			= NULL;
1802 1803 1804
	mtr_t		mtr;
	
	log_free_check();
unknown's avatar
unknown committed
1805

1806 1807 1808 1809 1810 1811 1812 1813
	mtr_start(&mtr);

	cursor.thr = thr;

	/* 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 */
	
unknown's avatar
unknown committed
1814 1815 1816 1817
	if (!(thr_get_trx(thr)->check_unique_secondary)) {
		ignore_sec_unique = BTR_IGNORE_SEC_UNIQUE;
	}

1818
	btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_LE,
unknown's avatar
unknown committed
1819 1820
				mode | BTR_INSERT | ignore_sec_unique,
				&cursor, 0, &mtr);
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830

	if (cursor.flag == BTR_CUR_INSERT_TO_IBUF) {
		/* The insertion was made to the insert buffer already during
		the search: we are done */

		err = DB_SUCCESS;

		goto function_exit;
	}	
					
unknown's avatar
unknown committed
1831 1832 1833 1834 1835 1836 1837 1838
	first_rec = page_rec_get_next(page_get_infimum_rec(
			buf_frame_align(btr_cur_get_rec(&cursor))));

	if (!page_rec_is_supremum(first_rec)) {
		ut_a((rec_get_n_fields(first_rec))
					== dtuple_get_n_fields(entry));
	}

1839 1840 1841 1842 1843
	n_unique = dict_index_get_n_unique(index);

	if (index->type & DICT_UNIQUE && (cursor.up_match >= n_unique
					 || cursor.low_match >= n_unique)) {

unknown's avatar
unknown committed
1844 1845 1846
		if (index->type & DICT_CLUSTERED) {			 
			/* Note that the following may return also
			DB_LOCK_WAIT */
1847

unknown's avatar
unknown committed
1848 1849 1850
			err = row_ins_duplicate_error_in_clust(&cursor,
							entry, thr, &mtr);
			if (err != DB_SUCCESS) {
1851

unknown's avatar
unknown committed
1852 1853 1854 1855 1856 1857 1858
				goto function_exit;
			}
		} else {
			mtr_commit(&mtr);
			err = row_ins_scan_sec_index_for_duplicate(index,
								entry, thr);
			mtr_start(&mtr);
1859

unknown's avatar
unknown committed
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
			if (err != DB_SUCCESS) {

				goto function_exit;
			}

			/* 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. */
			
			btr_cur_search_to_nth_level(index, 0, entry,
					PAGE_CUR_LE, mode | BTR_INSERT,
					&cursor, 0, &mtr);
		}		
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
	}

	modify = row_ins_must_modify(&cursor);

	if (modify != 0) {
		/* There is already an index entry with a long enough common
		prefix, we must convert the insert into a modify of an
		existing record */

		if (modify == ROW_INS_NEXT) {
			rec = page_rec_get_next(btr_cur_get_rec(&cursor));

			btr_cur_position(index, rec, &cursor);
		}

		if (index->type & DICT_CLUSTERED) {
			err = row_ins_clust_index_entry_by_modify(mode,
1892 1893 1894 1895
							&cursor, &big_rec,
							entry,
							ext_vec, n_ext_vec,
							thr, &mtr);
1896
		} else {
unknown's avatar
unknown committed
1897 1898
			err = row_ins_sec_index_entry_by_modify(mode, &cursor,
								entry,
1899 1900 1901 1902
								thr, &mtr);
		}
		
	} else {
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
		if (mode == BTR_MODIFY_LEAF) {
			err = btr_cur_optimistic_insert(0, &cursor, entry,
					&insert_rec, &big_rec, thr, &mtr);
		} else {
			ut_a(mode == BTR_MODIFY_TREE);
			err = btr_cur_pessimistic_insert(0, &cursor, entry,
					&insert_rec, &big_rec, thr, &mtr);
		}

		if (err == DB_SUCCESS) {
			if (ext_vec) {
				rec_set_field_extern_bits(insert_rec,
						ext_vec, n_ext_vec, &mtr);
			}
		}
1918
	}
1919

1920 1921 1922
function_exit:
	mtr_commit(&mtr);

1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
	if (big_rec) {
		mtr_start(&mtr);
	
		btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_LE,
					BTR_MODIFY_TREE, &cursor, 0, &mtr);

		err = btr_store_big_rec_extern_fields(index,
						btr_cur_get_rec(&cursor), 
						big_rec, &mtr);
		if (modify) {
			dtuple_big_rec_free(big_rec);
		} else {
			dtuple_convert_back_big_rec(index, entry, big_rec);
		}

		mtr_commit(&mtr);
	}

1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
	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. */

ulint
row_ins_index_entry(
/*================*/
				/* out: DB_SUCCESS, DB_LOCK_WAIT,
				DB_DUPLICATE_KEY, or some other error code */
	dict_index_t*	index,	/* in: index */
	dtuple_t*	entry,	/* in: index entry to insert */
1957 1958 1959
	ulint*		ext_vec,/* in: array containing field numbers of
				externally stored fields in entry, or NULL */
	ulint		n_ext_vec,/* in: number of fields in ext_vec */
1960 1961 1962 1963
	que_thr_t*	thr)	/* in: query thread */
{
	ulint	err;

1964 1965 1966 1967 1968 1969 1970 1971 1972
	if (UT_LIST_GET_FIRST(index->table->foreign_list)) {
		err = row_ins_check_foreign_constraints(index->table, index,
								entry, thr);
		if (err != DB_SUCCESS) {

			return(err);
		}
	}

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

1975
	err = row_ins_index_entry_low(BTR_MODIFY_LEAF, index, entry,
unknown's avatar
unknown committed
1976
						ext_vec, n_ext_vec, thr);
1977 1978 1979 1980 1981 1982 1983
	if (err != DB_FAIL) {

		return(err);
	}

	/* Try then pessimistic descent to the B-tree */

1984 1985
	err = row_ins_index_entry_low(BTR_MODIFY_TREE, index, entry,
						ext_vec, n_ext_vec, thr);
1986 1987 1988 1989 1990 1991
	return(err);
}

/***************************************************************
Sets the values of the dtuple fields in entry from the values of appropriate
columns in row. */
unknown's avatar
unknown committed
1992
static
1993 1994 1995
void
row_ins_index_entry_set_vals(
/*=========================*/
unknown's avatar
unknown committed
1996
	dict_index_t*	index,	/* in: index */
1997 1998 1999
	dtuple_t*	entry,	/* in: index entry to make */
	dtuple_t*	row)	/* in: row */
{
unknown's avatar
unknown committed
2000
	dict_field_t*	ind_field;
2001 2002 2003 2004
	dfield_t*	field;
	dfield_t*	row_field;
	ulint		n_fields;
	ulint		i;
2005
	dtype_t*        cur_type;
2006 2007 2008 2009 2010 2011 2012

	ut_ad(entry && row);

	n_fields = dtuple_get_n_fields(entry);

	for (i = 0; i < n_fields; i++) {
		field = dtuple_get_nth_field(entry, i);
unknown's avatar
unknown committed
2013 2014 2015
		ind_field = dict_index_get_nth_field(index, i);

		row_field = dtuple_get_nth_field(row, ind_field->col->ind);
2016

unknown's avatar
unknown committed
2017 2018
		/* Check column prefix indexes */
		if (ind_field->prefix_len > 0
2019 2020 2021 2022 2023
		    && dfield_get_len(row_field) != UNIV_SQL_NULL) {

			cur_type = dict_col_get_type(
				dict_field_get_col(ind_field));

unknown's avatar
unknown committed
2024 2025 2026
			field->len = dtype_get_at_most_n_mbchars(cur_type,
				  ind_field->prefix_len,
				  dfield_get_len(row_field), row_field->data);
unknown's avatar
unknown committed
2027 2028 2029
		} else {
		        field->len = row_field->len;
		}
2030 2031 2032 2033 2034 2035 2036

		field->data = row_field->data;
	}
}

/***************************************************************
Inserts a single index entry to the table. */
2037
static
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
ulint
row_ins_index_entry_step(
/*=====================*/
				/* out: DB_SUCCESS if operation successfully
				completed, else error code or DB_LOCK_WAIT */
	ins_node_t*	node,	/* in: row insert node */
	que_thr_t*	thr)	/* in: query thread */
{
	ulint	err;

	ut_ad(dtuple_check_typed(node->row));
	
unknown's avatar
unknown committed
2050
	row_ins_index_entry_set_vals(node->index, node->entry, node->row);
2051 2052 2053
	
	ut_ad(dtuple_check_typed(node->entry));

2054
	err = row_ins_index_entry(node->index, node->entry, NULL, 0, thr);
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 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 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223

	return(err);
}

/***************************************************************
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 */
{
	dulint	row_id;
	
	ut_ad(node->state == INS_NODE_ALLOC_ROW_ID);
	
	if (dict_table_get_first_index(node->table)->type & DICT_UNIQUE) {

		/* 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();

	dict_sys_write_row_id(node->row_id_buf, row_id);
}

/***************************************************************
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. */

ulint
row_ins(
/*====*/
				/* out: DB_SUCCESS if operation successfully
				completed, else error code or DB_LOCK_WAIT */
	ins_node_t*	node,	/* in: row insert node */
	que_thr_t*	thr)	/* in: query thread */
{
	ulint	err;
	
	ut_ad(node && thr);

	if (node->state == INS_NODE_ALLOC_ROW_ID) {

		row_ins_alloc_row_id_step(node);
	
		node->index = dict_table_get_first_index(node->table);
		node->entry = UT_LIST_GET_FIRST(node->entry_list);

		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) {
		err = row_ins_index_entry_step(node, thr);
		
		if (err != DB_SUCCESS) {

			return(err);
		}

		node->index = dict_table_get_next_index(node->index);
		node->entry = UT_LIST_GET_NEXT(tuple_list, node->entry);
	}

	ut_ad(node->entry == NULL);
	
	node->state = INS_NODE_ALLOC_ROW_ID;
	
	return(DB_SUCCESS);
}

/***************************************************************
Inserts a row to a table. This is a high-level function used in SQL execution
graphs. */

que_thr_t*
row_ins_step(
/*=========*/
				/* out: query thread to run next or NULL */
	que_thr_t*	thr)	/* in: query thread */
{
	ins_node_t*	node;
	que_node_t*	parent;
	sel_node_t*	sel_node;
	trx_t*		trx;
	ulint		err;

	ut_ad(thr);
	
	trx = thr_get_trx(thr);

unknown's avatar
Merge  
unknown committed
2224 2225
	trx_start_if_not_started(trx);
	
2226
	node = thr->run_node;
2227

2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294
	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. */

	if (node->state == INS_NODE_SET_IX_LOCK) {

		/* It may be that the current session has not yet started
		its transaction, or it has been committed: */
		
		if (UT_DULINT_EQ(trx->id, node->trx_id)) {
			/* No need to do IX-locking or write trx id to buf */

			goto same_trx;
		}	

		trx_write_trx_id(node->trx_id_buf, trx->id);

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

		if (err != DB_SUCCESS) {

			goto error_handling;
		}

		node->trx_id = trx->id;
	same_trx:				
		node->state = INS_NODE_ALLOC_ROW_ID;

		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);
	}

	/* DO THE CHECKS OF THE CONSISTENCY CONSTRAINTS HERE */

	err = row_ins(node, thr);

error_handling:
	trx->error_state = err;

2295 2296
	if (err != DB_SUCCESS) {
		/* err == DB_LOCK_WAIT or SQL error detected */
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
		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);
2311
}