row0mysql.c 114 KB
Newer Older
1 2
/*****************************************************************************

3
Copyright (c) 2000, 2011, Oracle and/or its affiliates. All Rights Reserved.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

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., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA

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

19 20
/**************************************************//**
@file row/row0mysql.c
osku's avatar
osku committed
21 22 23 24 25 26 27 28 29 30 31 32 33
Interface between Innobase row operations and MySQL.
Contains also create table and other data dictionary operations.

Created 9/17/2000 Heikki Tuuri
*******************************************************/

#include "row0mysql.h"

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

#include "row0ins.h"
34
#include "row0merge.h"
osku's avatar
osku committed
35 36 37 38 39 40 41 42 43 44 45
#include "row0sel.h"
#include "row0upd.h"
#include "row0row.h"
#include "que0que.h"
#include "pars0pars.h"
#include "dict0dict.h"
#include "dict0crea.h"
#include "dict0load.h"
#include "dict0boot.h"
#include "trx0roll.h"
#include "trx0purge.h"
46 47
#include "trx0rec.h"
#include "trx0undo.h"
osku's avatar
osku committed
48 49 50 51 52 53 54
#include "lock0lock.h"
#include "rem0cmp.h"
#include "log0log.h"
#include "btr0sea.h"
#include "fil0fil.h"
#include "ibuf0ibuf.h"

55
/** Provide optional 4.x backwards compatibility for 5.0 and above */
56
UNIV_INTERN ibool	row_rollback_on_timeout	= FALSE;
57

58
/** Chain node of the list of tables to drop in the background. */
osku's avatar
osku committed
59
typedef struct row_mysql_drop_struct	row_mysql_drop_t;
60 61

/** Chain node of the list of tables to drop in the background. */
osku's avatar
osku committed
62
struct row_mysql_drop_struct{
63 64 65
	char*				table_name;	/*!< table name */
	UT_LIST_NODE_T(row_mysql_drop_t)row_mysql_drop_list;
							/*!< list chain node */
osku's avatar
osku committed
66 67
};

68 69 70 71 72
/** @brief List of tables we should drop in background.

ALTER TABLE in MySQL requires that the table handler can drop the
table in background when there are no queries to it any
more.  Protected by kernel_mutex. */
73
static UT_LIST_BASE_NODE_T(row_mysql_drop_t)	row_mysql_drop_list;
74
/** Flag: has row_mysql_drop_list been initialized? */
75
static ibool	row_mysql_drop_list_inited	= FALSE;
osku's avatar
osku committed
76

77 78
/** Magic table names for invoking various monitor threads */
/* @{ */
osku's avatar
osku committed
79 80 81 82 83
static const char S_innodb_monitor[] = "innodb_monitor";
static const char S_innodb_lock_monitor[] = "innodb_lock_monitor";
static const char S_innodb_tablespace_monitor[] = "innodb_tablespace_monitor";
static const char S_innodb_table_monitor[] = "innodb_table_monitor";
static const char S_innodb_mem_validate[] = "innodb_mem_validate";
84 85 86 87 88 89 90 91
/* @} */

/** Evaluates to true if str1 equals str2_onstack, used for comparing
the magic table names.
@param str1		in: string to compare
@param str1_len 	in: length of str1, in bytes, including terminating NUL
@param str2_onstack	in: char[] array containing a NUL terminated string
@return			TRUE if str1 equals str2_onstack */
92 93 94 95
#define STR_EQ(str1, str1_len, str2_onstack) \
	((str1_len) == sizeof(str2_onstack) \
	 && memcmp(str1, str2_onstack, sizeof(str2_onstack)) == 0)

96
/*******************************************************************//**
97 98
Determine if the given name is a name reserved for MySQL system tables.
@return	TRUE if name is a MySQL system table name */
osku's avatar
osku committed
99 100 101 102 103 104
static
ibool
row_mysql_is_system_table(
/*======================*/
	const char*	name)
{
105 106
	if (strncmp(name, "mysql/", 6) != 0) {

osku's avatar
osku committed
107 108
		return(FALSE);
	}
109

osku's avatar
osku committed
110
	return(0 == strcmp(name + 6, "host")
111 112
	       || 0 == strcmp(name + 6, "user")
	       || 0 == strcmp(name + 6, "db"));
osku's avatar
osku committed
113 114
}

115
/*********************************************************************//**
marko's avatar
marko committed
116 117 118 119
If a table is not yet in the drop list, adds the table to the list of tables
which the master thread drops in background. We need this on Unix because in
ALTER TABLE MySQL may call drop table even if the table has running queries on
it. Also, if there are running foreign key checks on the table, we drop the
120 121
table lazily.
@return	TRUE if the table was not yet in the drop list, and was added there */
marko's avatar
marko committed
122 123 124 125
static
ibool
row_add_table_to_background_drop_list(
/*==================================*/
126
	const char*	name);	/*!< in: table name */
127

128
/*******************************************************************//**
osku's avatar
osku committed
129 130 131 132 133 134 135 136 137 138 139
Delays an INSERT, DELETE or UPDATE operation if the purge is lagging. */
static
void
row_mysql_delay_if_needed(void)
/*===========================*/
{
	if (srv_dml_needed_delay) {
		os_thread_sleep(srv_dml_needed_delay);
	}
}

140
/*******************************************************************//**
osku's avatar
osku committed
141
Frees the blob heap in prebuilt when no longer needed. */
142
UNIV_INTERN
osku's avatar
osku committed
143 144 145
void
row_mysql_prebuilt_free_blob_heap(
/*==============================*/
146
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct of a
osku's avatar
osku committed
147 148 149 150 151 152
					ha_innobase:: table handle */
{
	mem_heap_free(prebuilt->blob_heap);
	prebuilt->blob_heap = NULL;
}

153
/*******************************************************************//**
osku's avatar
osku committed
154
Stores a >= 5.0.3 format true VARCHAR length to dest, in the MySQL row
155
format.
156 157
@return pointer to the data, we skip the 1 or 2 bytes at the start
that are used to store the len */
158
UNIV_INTERN
osku's avatar
osku committed
159 160 161
byte*
row_mysql_store_true_var_len(
/*=========================*/
162 163 164
	byte*	dest,	/*!< in: where to store */
	ulint	len,	/*!< in: length, must fit in two bytes */
	ulint	lenlen)	/*!< in: storage length of len: either 1 or 2 bytes */
osku's avatar
osku committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
{
	if (lenlen == 2) {
		ut_a(len < 256 * 256);

		mach_write_to_2_little_endian(dest, len);

		return(dest + 2);
	}

	ut_a(lenlen == 1);
	ut_a(len < 256);

	mach_write_to_1(dest, len);

	return(dest + 1);
}

182
/*******************************************************************//**
osku's avatar
osku committed
183
Reads a >= 5.0.3 format true VARCHAR length, in the MySQL row format, and
184
returns a pointer to the data.
185 186
@return pointer to the data, we skip the 1 or 2 bytes at the start
that are used to store the len */
187
UNIV_INTERN
188
const byte*
osku's avatar
osku committed
189 190
row_mysql_read_true_varchar(
/*========================*/
191 192 193
	ulint*		len,	/*!< out: variable-length field length */
	const byte*	field,	/*!< in: field in the MySQL format */
	ulint		lenlen)	/*!< in: storage length of len: either 1
194
				or 2 bytes */
osku's avatar
osku committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208
{
	if (lenlen == 2) {
		*len = mach_read_from_2_little_endian(field);

		return(field + 2);
	}

	ut_a(lenlen == 1);

	*len = mach_read_from_1(field);

	return(field + 1);
}

209
/*******************************************************************//**
osku's avatar
osku committed
210
Stores a reference to a BLOB in the MySQL format. */
211
UNIV_INTERN
osku's avatar
osku committed
212 213 214
void
row_mysql_store_blob_ref(
/*=====================*/
215 216
	byte*		dest,	/*!< in: where to store */
	ulint		col_len,/*!< in: dest buffer size: determines into
osku's avatar
osku committed
217 218 219
				how many bytes the BLOB length is stored,
				the space for the length may vary from 1
				to 4 bytes */
220
	const void*	data,	/*!< in: BLOB data; if the value to store
osku's avatar
osku committed
221
				is SQL NULL this should be NULL pointer */
222
	ulint		len)	/*!< in: BLOB length; if the value to store
osku's avatar
osku committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
				is SQL NULL this should be 0; remember
				also to set the NULL bit in the MySQL record
				header! */
{
	/* MySQL might assume the field is set to zero except the length and
	the pointer fields */

	memset(dest, '\0', col_len);

	/* In dest there are 1 - 4 bytes reserved for the BLOB length,
	and after that 8 bytes reserved for the pointer to the data.
	In 32-bit architectures we only use the first 4 bytes of the pointer
	slot. */

	ut_a(col_len - 8 > 1 || len < 256);
	ut_a(col_len - 8 > 2 || len < 256 * 256);
	ut_a(col_len - 8 > 3 || len < 256 * 256 * 256);

	mach_write_to_n_little_endian(dest, col_len - 8, len);

243
	memcpy(dest + col_len - 8, &data, sizeof data);
osku's avatar
osku committed
244 245
}

246
/*******************************************************************//**
247 248
Reads a reference to a BLOB in the MySQL format.
@return	pointer to BLOB data */
249
UNIV_INTERN
250
const byte*
osku's avatar
osku committed
251 252
row_mysql_read_blob_ref(
/*====================*/
253 254
	ulint*		len,		/*!< out: BLOB length */
	const byte*	ref,		/*!< in: BLOB reference in the
255
					MySQL format */
256
	ulint		col_len)	/*!< in: BLOB reference length
257
					(not BLOB length) */
osku's avatar
osku committed
258
{
259
	byte*	data;
osku's avatar
osku committed
260 261 262

	*len = mach_read_from_n_little_endian(ref, col_len - 8);

263
	memcpy(&data, ref + col_len - 8, sizeof data);
osku's avatar
osku committed
264 265 266 267

	return(data);
}

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
/**************************************************************//**
Pad a column with spaces. */
UNIV_INTERN
void
row_mysql_pad_col(
/*==============*/
	ulint	mbminlen,	/*!< in: minimum size of a character,
				in bytes */
	byte*	pad,		/*!< out: padded buffer */
	ulint	len)		/*!< in: number of bytes to pad */
{
	const byte*	pad_end;

	switch (UNIV_EXPECT(mbminlen, 1)) {
	default:
		ut_error;
	case 1:
		/* space=0x20 */
		memset(pad, 0x20, len);
		break;
	case 2:
		/* space=0x0020 */
		pad_end = pad + len;
		ut_a(!(len % 2));
292
		while (pad < pad_end) {
293 294
			*pad++ = 0x00;
			*pad++ = 0x20;
295
		};
296 297 298 299 300
		break;
	case 4:
		/* space=0x00000020 */
		pad_end = pad + len;
		ut_a(!(len % 4));
301
		while (pad < pad_end) {
302 303 304 305
			*pad++ = 0x00;
			*pad++ = 0x00;
			*pad++ = 0x00;
			*pad++ = 0x20;
306
		}
307 308 309 310
		break;
	}
}

311
/**************************************************************//**
osku's avatar
osku committed
312 313
Stores a non-SQL-NULL field given in the MySQL format in the InnoDB format.
The counterpart of this function is row_sel_field_store_in_mysql_format() in
314 315
row0sel.c.
@return	up to which byte we used buf in the conversion */
316
UNIV_INTERN
osku's avatar
osku committed
317 318 319
byte*
row_mysql_store_col_in_innobase_format(
/*===================================*/
320
	dfield_t*	dfield,		/*!< in/out: dfield where dtype
osku's avatar
osku committed
321 322
					information must be already set when
					this function is called! */
323
	byte*		buf,		/*!< in/out: buffer for a converted
osku's avatar
osku committed
324 325
					integer value; this must be at least
					col_len long then! */
326
	ibool		row_format_col,	/*!< TRUE if the mysql_data is from
osku's avatar
osku committed
327 328 329 330 331 332
					a MySQL row, FALSE if from a MySQL
					key value;
					in MySQL, a true VARCHAR storage
					format differs in a row and in a
					key value: in a key value the length
					is always stored in 2 bytes! */
333
	const byte*	mysql_data,	/*!< in: MySQL column value, not
osku's avatar
osku committed
334 335 336 337
					SQL NULL; NOTE that dfield may also
					get a pointer to mysql_data,
					therefore do not discard this as long
					as dfield is used! */
338
	ulint		col_len,	/*!< in: MySQL column length; NOTE that
osku's avatar
osku committed
339 340 341 342 343
					this is the storage length of the
					column in the MySQL format row, not
					necessarily the length of the actual
					payload data; if the column is a true
					VARCHAR then this is irrelevant */
344
	ulint		comp)		/*!< in: nonzero=compact format */
osku's avatar
osku committed
345
{
346
	const byte*	ptr	= mysql_data;
347
	const dtype_t*	dtype;
osku's avatar
osku committed
348 349 350 351 352 353 354 355 356 357 358 359
	ulint		type;
	ulint		lenlen;

	dtype = dfield_get_type(dfield);

	type = dtype->mtype;

	if (type == DATA_INT) {
		/* Store integer data in Innobase in a big-endian format,
		sign bit negated if the data is a signed integer. In MySQL,
		integers are stored in a little-endian format. */

360
		byte*	p = buf + col_len;
osku's avatar
osku committed
361 362

		for (;;) {
363 364
			p--;
			*p = *mysql_data;
365
			if (p == buf) {
osku's avatar
osku committed
366 367 368 369 370 371 372
				break;
			}
			mysql_data++;
		}

		if (!(dtype->prtype & DATA_UNSIGNED)) {

373
			*buf ^= 128;
osku's avatar
osku committed
374 375
		}

376
		ptr = buf;
osku's avatar
osku committed
377 378
		buf += col_len;
	} else if ((type == DATA_VARCHAR
379 380
		    || type == DATA_VARMYSQL
		    || type == DATA_BINARY)) {
osku's avatar
osku committed
381 382 383 384

		if (dtype_get_mysql_type(dtype) == DATA_MYSQL_TRUE_VARCHAR) {
			/* The length of the actual data is stored to 1 or 2
			bytes at the start of the field */
385

osku's avatar
osku committed
386 387 388 389 390 391 392 393 394 395 396 397
			if (row_format_col) {
				if (dtype->prtype & DATA_LONG_TRUE_VARCHAR) {
					lenlen = 2;
				} else {
					lenlen = 1;
				}
			} else {
				/* In a MySQL key value, lenlen is always 2 */
				lenlen = 2;
			}

			ptr = row_mysql_read_true_varchar(&col_len, mysql_data,
398
							  lenlen);
osku's avatar
osku committed
399 400 401 402
		} else {
			/* Remove trailing spaces from old style VARCHAR
			columns. */

403
			/* Handle Unicode strings differently. */
osku's avatar
osku committed
404 405 406 407
			ulint	mbminlen	= dtype_get_mbminlen(dtype);

			ptr = mysql_data;

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
			switch (mbminlen) {
			default:
				ut_error;
			case 4:
				/* space=0x00000020 */
				/* Trim "half-chars", just in case. */
				col_len &= ~3;

				while (col_len >= 4
				       && ptr[col_len - 4] == 0x00
				       && ptr[col_len - 3] == 0x00
				       && ptr[col_len - 2] == 0x00
				       && ptr[col_len - 1] == 0x20) {
					col_len -= 4;
				}
				break;
			case 2:
osku's avatar
osku committed
425 426 427 428 429
				/* space=0x0020 */
				/* Trim "half-chars", just in case. */
				col_len &= ~1;

				while (col_len >= 2 && ptr[col_len - 2] == 0x00
430
				       && ptr[col_len - 1] == 0x20) {
osku's avatar
osku committed
431 432
					col_len -= 2;
				}
433 434
				break;
			case 1:
osku's avatar
osku committed
435 436
				/* space=0x20 */
				while (col_len > 0
437
				       && ptr[col_len - 1] == 0x20) {
osku's avatar
osku committed
438 439 440 441 442
					col_len--;
				}
			}
		}
	} else if (comp && type == DATA_MYSQL
443 444
		   && dtype_get_mbminlen(dtype) == 1
		   && dtype_get_mbmaxlen(dtype) > 1) {
osku's avatar
osku committed
445 446 447
		/* In some cases we strip trailing spaces from UTF-8 and other
		multibyte charsets, from FIXED-length CHAR columns, to save
		space. UTF-8 would otherwise normally use 3 * the string length
448
		bytes to store an ASCII string! */
osku's avatar
osku committed
449 450 451 452 453 454 455 456

		/* We assume that this CHAR field is encoded in a
		variable-length character set where spaces have
		1:1 correspondence to 0x20 bytes, such as UTF-8.

		Consider a CHAR(n) field, a field of n characters.
		It will contain between n * mbminlen and n * mbmaxlen bytes.
		We will try to truncate it to n bytes by stripping
457
		space padding.	If the field contains single-byte
osku's avatar
osku committed
458 459 460 461
		characters only, it will be truncated to n characters.
		Consider a CHAR(5) field containing the string ".a   "
		where "." denotes a 3-byte character represented by
		the bytes "$%&".  After our stripping, the string will
462
		be stored as "$%&a " (5 bytes).	 The string ".abc "
osku's avatar
osku committed
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
		will be stored as "$%&abc" (6 bytes).

		The space padding will be restored in row0sel.c, function
		row_sel_field_store_in_mysql_format(). */

		ulint		n_chars;

		ut_a(!(dtype_get_len(dtype) % dtype_get_mbmaxlen(dtype)));

		n_chars = dtype_get_len(dtype) / dtype_get_mbmaxlen(dtype);

		/* Strip space padding. */
		while (col_len > n_chars && ptr[col_len - 1] == 0x20) {
			col_len--;
		}
	} else if (type == DATA_BLOB && row_format_col) {

		ptr = row_mysql_read_blob_ref(&col_len, mysql_data, col_len);
	}

	dfield_set_data(dfield, ptr, col_len);

	return(buf);
}

488
/**************************************************************//**
osku's avatar
osku committed
489 490 491 492 493 494 495
Convert a row in the MySQL format to a row in the Innobase format. Note that
the function to convert a MySQL format key value to an InnoDB dtuple is
row_sel_convert_mysql_key_to_innobase() in row0sel.c. */
static
void
row_mysql_convert_row_to_innobase(
/*==============================*/
496
	dtuple_t*	row,		/*!< in/out: Innobase row where the
osku's avatar
osku committed
497 498
					field type information is already
					copied there! */
499
	row_prebuilt_t*	prebuilt,	/*!< in: prebuilt struct where template
osku's avatar
osku committed
500
					must be of type ROW_MYSQL_WHOLE_ROW */
501
	byte*		mysql_rec)	/*!< in: row in the MySQL format;
osku's avatar
osku committed
502 503 504 505
					NOTE: do not discard as long as
					row is used, as row may contain
					pointers to this record! */
{
506
	const mysql_row_templ_t*templ;
osku's avatar
osku committed
507 508
	dfield_t*		dfield;
	ulint			i;
509

osku's avatar
osku committed
510 511 512 513 514 515
	ut_ad(prebuilt->template_type == ROW_MYSQL_WHOLE_ROW);
	ut_ad(prebuilt->mysql_template);

	for (i = 0; i < prebuilt->n_template; i++) {

		templ = prebuilt->mysql_template + i;
516
		dfield = dtuple_get_nth_field(row, i);
osku's avatar
osku committed
517 518 519 520

		if (templ->mysql_null_bit_mask != 0) {
			/* Column may be SQL NULL */

521 522
			if (mysql_rec[templ->mysql_null_byte_offset]
			    & (byte) (templ->mysql_null_bit_mask)) {
osku's avatar
osku committed
523 524 525

				/* It is SQL NULL */

526
				dfield_set_null(dfield);
osku's avatar
osku committed
527 528 529

				goto next_column;
			}
530 531
		}

532 533 534 535 536 537 538
		row_mysql_store_col_in_innobase_format(
			dfield,
			prebuilt->ins_upd_rec_buff + templ->mysql_col_offset,
			TRUE, /* MySQL row format data */
			mysql_rec + templ->mysql_col_offset,
			templ->mysql_col_len,
			dict_table_is_comp(prebuilt->table));
osku's avatar
osku committed
539 540
next_column:
		;
541
	}
osku's avatar
osku committed
542 543
}

544
/****************************************************************//**
545
Handles user errors and lock waits detected by the database engine.
546
@return TRUE if it was a lock wait and we should continue running the
547
query thread and in that case the thr is ALREADY in the running state. */
548
UNIV_INTERN
osku's avatar
osku committed
549 550 551
ibool
row_mysql_handle_errors(
/*====================*/
552
	ulint*		new_err,/*!< out: possible new error encountered in
osku's avatar
osku committed
553 554 555
				lock wait, or if no new error, the value
				of trx->error_state at the entry of this
				function */
556 557 558
	trx_t*		trx,	/*!< in: transaction */
	que_thr_t*	thr,	/*!< in: query thread */
	trx_savept_t*	savept)	/*!< in: savepoint or NULL */
osku's avatar
osku committed
559 560 561 562 563
{
	ulint	err;

handle_new_error:
	err = trx->error_state;
564

osku's avatar
osku committed
565
	ut_a(err != DB_SUCCESS);
566

osku's avatar
osku committed
567
	trx->error_state = DB_SUCCESS;
568

569 570 571
	switch (err) {
	case DB_LOCK_WAIT_TIMEOUT:
		if (row_rollback_on_timeout) {
572
			trx_general_rollback_for_mysql(trx, NULL);
573
			break;
osku's avatar
osku committed
574
		}
575 576 577 578
		/* fall through */
	case DB_DUPLICATE_KEY:
	case DB_FOREIGN_DUPLICATE_KEY:
	case DB_TOO_BIG_RECORD:
579
	case DB_UNDO_RECORD_TOO_BIG:
580 581 582 583 584
	case DB_ROW_IS_REFERENCED:
	case DB_NO_REFERENCED_ROW:
	case DB_CANNOT_ADD_CONSTRAINT:
	case DB_TOO_MANY_CONCURRENT_TRXS:
	case DB_OUT_OF_FILE_SPACE:
585
	case DB_INTERRUPTED:
586
		if (savept) {
osku's avatar
osku committed
587 588 589
			/* Roll back the latest, possibly incomplete
			insertion or update */

590
			trx_general_rollback_for_mysql(trx, savept);
osku's avatar
osku committed
591 592
		}
		/* MySQL will roll back the latest SQL statement */
593 594
		break;
	case DB_LOCK_WAIT:
osku's avatar
osku committed
595 596 597 598 599 600 601 602 603 604 605 606
		srv_suspend_mysql_thread(thr);

		if (trx->error_state != DB_SUCCESS) {
			que_thr_stop_for_mysql(thr);

			goto handle_new_error;
		}

		*new_err = err;

		return(TRUE);

607 608
	case DB_DEADLOCK:
	case DB_LOCK_TABLE_FULL:
osku's avatar
osku committed
609 610 611
		/* Roll back the whole transaction; this resolution was added
		to version 3.23.43 */

612
		trx_general_rollback_for_mysql(trx, NULL);
613
		break;
614

615
	case DB_MUST_GET_MORE_FILE_SPACE:
616 617 618 619 620
		fputs("InnoDB: The database cannot continue"
		      " operation because of\n"
		      "InnoDB: lack of space. You must add"
		      " a new data file to\n"
		      "InnoDB: my.cnf and restart the database.\n", stderr);
621

osku's avatar
osku committed
622 623
		exit(1);

624
	case DB_CORRUPTION:
625 626 627 628 629 630 631 632 633 634 635
		fputs("InnoDB: We detected index corruption"
		      " in an InnoDB type table.\n"
		      "InnoDB: You have to dump + drop + reimport"
		      " the table or, in\n"
		      "InnoDB: a case of widespread corruption,"
		      " dump all InnoDB\n"
		      "InnoDB: tables and recreate the"
		      " whole InnoDB tablespace.\n"
		      "InnoDB: If the mysqld server crashes"
		      " after the startup or when\n"
		      "InnoDB: you dump the tables, look at\n"
636
		      "InnoDB: " REFMAN "forcing-innodb-recovery.html"
637
		      " for help.\n", stderr);
638
		break;
639 640 641 642 643 644 645
	case DB_FOREIGN_EXCEED_MAX_CASCADE:
		fprintf(stderr, "InnoDB: Cannot delete/update rows with"
			" cascading foreign key constraints that exceed max"
			" depth of %lu\n"
			"Please drop excessive foreign constraints"
			" and try again\n", (ulong) DICT_FK_MAX_RECURSIVE_LOAD);
		break;
646
	default:
osku's avatar
osku committed
647 648 649
		fprintf(stderr, "InnoDB: unknown error code %lu\n",
			(ulong) err);
		ut_error;
650
	}
osku's avatar
osku committed
651 652 653 654 655 656

	if (trx->error_state != DB_SUCCESS) {
		*new_err = trx->error_state;
	} else {
		*new_err = err;
	}
657

osku's avatar
osku committed
658 659 660 661 662
	trx->error_state = DB_SUCCESS;

	return(FALSE);
}

663
/********************************************************************//**
664 665
Create a prebuilt struct for a MySQL table handle.
@return	own: a prebuilt struct */
666
UNIV_INTERN
osku's avatar
osku committed
667 668 669
row_prebuilt_t*
row_create_prebuilt(
/*================*/
670
	dict_table_t*	table)	/*!< in: Innobase table handle */
osku's avatar
osku committed
671 672 673 674 675 676
{
	row_prebuilt_t*	prebuilt;
	mem_heap_t*	heap;
	dict_index_t*	clust_index;
	dtuple_t*	ref;
	ulint		ref_len;
677

678
	heap = mem_heap_create(sizeof *prebuilt + 128);
osku's avatar
osku committed
679

680
	prebuilt = mem_heap_zalloc(heap, sizeof *prebuilt);
osku's avatar
osku committed
681 682 683 684 685 686 687 688 689

	prebuilt->magic_n = ROW_PREBUILT_ALLOCATED;
	prebuilt->magic_n2 = ROW_PREBUILT_ALLOCATED;

	prebuilt->table = table;

	prebuilt->sql_stat_start = TRUE;
	prebuilt->heap = heap;

690 691
	prebuilt->pcur = btr_pcur_create_for_mysql();
	prebuilt->clust_pcur = btr_pcur_create_for_mysql();
osku's avatar
osku committed
692 693 694

	prebuilt->select_lock_type = LOCK_NONE;
	prebuilt->stored_select_lock_type = 99999999;
695 696
	UNIV_MEM_INVALID(&prebuilt->stored_select_lock_type,
			 sizeof prebuilt->stored_select_lock_type);
osku's avatar
osku committed
697

698 699
	prebuilt->search_tuple = dtuple_create(
		heap, 2 * dict_table_get_n_cols(table));
700

osku's avatar
osku committed
701 702 703 704 705 706 707 708 709 710 711 712 713
	clust_index = dict_table_get_first_index(table);

	/* Make sure that search_tuple is long enough for clustered index */
	ut_a(2 * dict_table_get_n_cols(table) >= clust_index->n_fields);

	ref_len = dict_index_get_n_unique(clust_index);

	ref = dtuple_create(heap, ref_len);

	dict_index_copy_types(ref, clust_index, ref_len);

	prebuilt->clust_ref = ref;

714
	prebuilt->autoinc_error = 0;
715 716 717 718 719 720 721 722
	prebuilt->autoinc_offset = 0;

	/* Default to 1, we will set the actual value later in 
	ha_innobase::get_auto_increment(). */
	prebuilt->autoinc_increment = 1;

	prebuilt->autoinc_last_value = 0;

osku's avatar
osku committed
723 724 725
	return(prebuilt);
}

726
/********************************************************************//**
osku's avatar
osku committed
727
Free a prebuilt struct for a MySQL table handle. */
728
UNIV_INTERN
osku's avatar
osku committed
729 730 731
void
row_prebuilt_free(
/*==============*/
732 733
	row_prebuilt_t*	prebuilt,	/*!< in, own: prebuilt struct */
	ibool		dict_locked)	/*!< in: TRUE=data dictionary locked */
osku's avatar
osku committed
734 735 736
{
	ulint	i;

737 738 739
	if (UNIV_UNLIKELY
	    (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED
	     || prebuilt->magic_n2 != ROW_PREBUILT_ALLOCATED)) {
740

osku's avatar
osku committed
741
		fprintf(stderr,
742 743
			"InnoDB: Error: trying to free a corrupt\n"
			"InnoDB: table handle. Magic n %lu,"
744
			" magic n2 %lu, table name ",
745 746
			(ulong) prebuilt->magic_n,
			(ulong) prebuilt->magic_n2);
747
		ut_print_name(stderr, NULL, TRUE, prebuilt->table->name);
osku's avatar
osku committed
748 749
		putc('\n', stderr);

750
		mem_analyze_corruption(prebuilt);
osku's avatar
osku committed
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771

		ut_error;
	}

	prebuilt->magic_n = ROW_PREBUILT_FREED;
	prebuilt->magic_n2 = ROW_PREBUILT_FREED;

	btr_pcur_free_for_mysql(prebuilt->pcur);
	btr_pcur_free_for_mysql(prebuilt->clust_pcur);

	if (prebuilt->mysql_template) {
		mem_free(prebuilt->mysql_template);
	}

	if (prebuilt->ins_graph) {
		que_graph_free_recursive(prebuilt->ins_graph);
	}

	if (prebuilt->sel_graph) {
		que_graph_free_recursive(prebuilt->sel_graph);
	}
772

osku's avatar
osku committed
773 774 775
	if (prebuilt->upd_graph) {
		que_graph_free_recursive(prebuilt->upd_graph);
	}
776

osku's avatar
osku committed
777 778 779 780 781 782 783
	if (prebuilt->blob_heap) {
		mem_heap_free(prebuilt->blob_heap);
	}

	if (prebuilt->old_vers_heap) {
		mem_heap_free(prebuilt->old_vers_heap);
	}
784

osku's avatar
osku committed
785 786 787
	for (i = 0; i < MYSQL_FETCH_CACHE_SIZE; i++) {
		if (prebuilt->fetch_cache[i] != NULL) {

788 789 790 791 792
			if ((ROW_PREBUILT_FETCH_MAGIC_N != mach_read_from_4(
				     (prebuilt->fetch_cache[i]) - 4))
			    || (ROW_PREBUILT_FETCH_MAGIC_N != mach_read_from_4(
					(prebuilt->fetch_cache[i])
					+ prebuilt->mysql_row_len))) {
793 794
				fputs("InnoDB: Error: trying to free"
				      " a corrupt fetch buffer.\n", stderr);
osku's avatar
osku committed
795

796 797
				mem_analyze_corruption(
					prebuilt->fetch_cache[i]);
osku's avatar
osku committed
798 799 800 801 802 803 804 805

				ut_error;
			}

			mem_free((prebuilt->fetch_cache[i]) - 4);
		}
	}

806
	dict_table_decrement_handle_count(prebuilt->table, dict_locked);
osku's avatar
osku committed
807 808 809 810

	mem_heap_free(prebuilt->heap);
}

811
/*********************************************************************//**
osku's avatar
osku committed
812 813
Updates the transaction pointers in query graphs stored in the prebuilt
struct. */
814
UNIV_INTERN
osku's avatar
osku committed
815 816 817
void
row_update_prebuilt_trx(
/*====================*/
818
	row_prebuilt_t*	prebuilt,	/*!< in/out: prebuilt struct
819
					in MySQL handle */
820
	trx_t*		trx)		/*!< in: transaction handle */
821
{
osku's avatar
osku committed
822 823
	if (trx->magic_n != TRX_MAGIC_N) {
		fprintf(stderr,
824 825 826
			"InnoDB: Error: trying to use a corrupt\n"
			"InnoDB: trx handle. Magic n %lu\n",
			(ulong) trx->magic_n);
osku's avatar
osku committed
827

828
		mem_analyze_corruption(trx);
osku's avatar
osku committed
829 830 831 832 833 834

		ut_error;
	}

	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
		fprintf(stderr,
835
			"InnoDB: Error: trying to use a corrupt\n"
836
			"InnoDB: table handle. Magic n %lu, table name ",
837
			(ulong) prebuilt->magic_n);
838
		ut_print_name(stderr, trx, TRUE, prebuilt->table->name);
osku's avatar
osku committed
839 840
		putc('\n', stderr);

841
		mem_analyze_corruption(prebuilt);
osku's avatar
osku committed
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857

		ut_error;
	}

	prebuilt->trx = trx;

	if (prebuilt->ins_graph) {
		prebuilt->ins_graph->trx = trx;
	}

	if (prebuilt->upd_graph) {
		prebuilt->upd_graph->trx = trx;
	}

	if (prebuilt->sel_graph) {
		prebuilt->sel_graph->trx = trx;
858
	}
osku's avatar
osku committed
859 860
}

861
/*********************************************************************//**
osku's avatar
osku committed
862 863
Gets pointer to a prebuilt dtuple used in insertions. If the insert graph
has not yet been built in the prebuilt struct, then this function first
864 865
builds it.
@return	prebuilt dtuple; the column type information is also set in it */
osku's avatar
osku committed
866 867 868 869
static
dtuple_t*
row_get_prebuilt_insert_row(
/*========================*/
870
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in MySQL
osku's avatar
osku committed
871 872 873 874 875 876 877
					handle */
{
	ins_node_t*	node;
	dtuple_t*	row;
	dict_table_t*	table	= prebuilt->table;

	ut_ad(prebuilt && table && prebuilt->trx);
878

osku's avatar
osku committed
879 880 881 882 883 884
	if (prebuilt->ins_node == NULL) {

		/* Not called before for this handle: create an insert node
		and query graph to the prebuilt struct */

		node = ins_node_create(INS_DIRECT, table, prebuilt->heap);
885

osku's avatar
osku committed
886 887 888
		prebuilt->ins_node = node;

		if (prebuilt->ins_upd_rec_buff == NULL) {
889 890
			prebuilt->ins_upd_rec_buff = mem_heap_alloc(
				prebuilt->heap, prebuilt->mysql_row_len);
osku's avatar
osku committed
891
		}
892

osku's avatar
osku committed
893
		row = dtuple_create(prebuilt->heap,
894
				    dict_table_get_n_cols(table));
osku's avatar
osku committed
895 896 897 898 899

		dict_table_copy_types(row, table);

		ins_node_set_new_row(node, row);

900 901 902 903
		prebuilt->ins_graph = que_node_get_parent(
			pars_complete_graph_for_exec(node,
						     prebuilt->trx,
						     prebuilt->heap));
osku's avatar
osku committed
904 905 906
		prebuilt->ins_graph->state = QUE_FORK_ACTIVE;
	}

907
	return(prebuilt->ins_node->row);
osku's avatar
osku committed
908 909
}

910
/*********************************************************************//**
osku's avatar
osku committed
911 912 913 914 915 916
Updates the table modification counter and calculates new estimates
for table and index statistics if necessary. */
UNIV_INLINE
void
row_update_statistics_if_needed(
/*============================*/
917
	dict_table_t*	table)	/*!< in: table */
osku's avatar
osku committed
918 919
{
	ulint	counter;
920

osku's avatar
osku committed
921 922 923 924 925 926 927 928 929 930 931
	counter = table->stat_modified_counter;

	table->stat_modified_counter = counter + 1;

	/* Calculate new statistics if 1 / 16 of table has been modified
	since the last time a statistics batch was run, or if
	stat_modified_counter > 2 000 000 000 (to avoid wrap-around).
	We calculate statistics at most every 16th round, since we may have
	a counter table which is very small and updated very often. */

	if (counter > 2000000000
932
	    || ((ib_int64_t)counter > 16 + table->stat_n_rows / 16)) {
osku's avatar
osku committed
933

934 935
		dict_update_statistics(table, FALSE /* update even if stats
						    are initialized */);
936
	}
osku's avatar
osku committed
937
}
938

939
/*********************************************************************//**
940 941 942
Unlocks AUTO_INC type locks that were possibly reserved by a trx. This
function should be called at the the end of an SQL statement, by the
connection thread that owns the transaction (trx->mysql_thd). */
943
UNIV_INTERN
944
void
osku's avatar
osku committed
945 946
row_unlock_table_autoinc_for_mysql(
/*===============================*/
947
	trx_t*	trx)	/*!< in/out: transaction */
osku's avatar
osku committed
948
{
949 950
	if (lock_trx_holds_autoinc_locks(trx)) {
		mutex_enter(&kernel_mutex);
osku's avatar
osku committed
951

952
		lock_release_autoinc_locks(trx);
osku's avatar
osku committed
953

954 955
		mutex_exit(&kernel_mutex);
	}
osku's avatar
osku committed
956 957
}

958
/*********************************************************************//**
osku's avatar
osku committed
959 960 961 962
Sets an AUTO_INC type lock on the table mentioned in prebuilt. The
AUTO_INC lock gives exclusive access to the auto-inc counter of the
table. The lock is reserved only for the duration of an SQL statement.
It is not compatible with another AUTO_INC or exclusive lock on the
963 964
table.
@return	error code or DB_SUCCESS */
965
UNIV_INTERN
osku's avatar
osku committed
966 967 968
int
row_lock_table_autoinc_for_mysql(
/*=============================*/
969
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in the MySQL
osku's avatar
osku committed
970 971
					table handle */
{
972 973 974 975 976 977
	trx_t*			trx	= prebuilt->trx;
	ins_node_t*		node	= prebuilt->ins_node;
	const dict_table_t*	table	= prebuilt->table;
	que_thr_t*		thr;
	ulint			err;
	ibool			was_lock_wait;
978

osku's avatar
osku committed
979
	ut_ad(trx);
980

981 982 983 984
	/* If we already hold an AUTOINC lock on the table then do nothing.
        Note: We peek at the value of the current owner without acquiring
	the kernel mutex. **/
	if (trx == table->autoinc_trx) {
osku's avatar
osku committed
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036

		return(DB_SUCCESS);
	}

	trx->op_info = "setting auto-inc lock";

	if (node == NULL) {
		row_get_prebuilt_insert_row(prebuilt);
		node = prebuilt->ins_node;
	}

	/* We use the insert query graph as the dummy graph needed
	in the lock module call */

	thr = que_fork_get_first_thr(prebuilt->ins_graph);

	que_thr_move_to_run_state_for_mysql(thr, trx);

run_again:
	thr->run_node = node;
	thr->prev_node = node;

	/* It may be that the current session has not yet started
	its transaction, or it has been committed: */

	trx_start_if_not_started(trx);

	err = lock_table(0, prebuilt->table, LOCK_AUTO_INC, thr);

	trx->error_state = err;

	if (err != DB_SUCCESS) {
		que_thr_stop_for_mysql(thr);

		was_lock_wait = row_mysql_handle_errors(&err, trx, thr, NULL);

		if (was_lock_wait) {
			goto run_again;
		}

		trx->op_info = "";

		return((int) err);
	}

	que_thr_stop_for_mysql_no_error(thr, trx);

	trx->op_info = "";

	return((int) err);
}

1037
/*********************************************************************//**
1038 1039
Sets a table lock on the table mentioned in prebuilt.
@return	error code or DB_SUCCESS */
1040
UNIV_INTERN
osku's avatar
osku committed
1041 1042 1043
int
row_lock_table_for_mysql(
/*=====================*/
1044
	row_prebuilt_t*	prebuilt,	/*!< in: prebuilt struct in the MySQL
osku's avatar
osku committed
1045
					table handle */
1046
	dict_table_t*	table,		/*!< in: table to lock, or NULL
osku's avatar
osku committed
1047 1048 1049
					if prebuilt->table should be
					locked as
					prebuilt->select_lock_type */
1050
	ulint		mode)		/*!< in: lock mode of table
osku's avatar
osku committed
1051 1052
					(ignored if table==NULL) */
{
1053
	trx_t*		trx		= prebuilt->trx;
osku's avatar
osku committed
1054 1055 1056
	que_thr_t*	thr;
	ulint		err;
	ibool		was_lock_wait;
1057

osku's avatar
osku committed
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
	ut_ad(trx);

	trx->op_info = "setting table lock";

	if (prebuilt->sel_graph == NULL) {
		/* Build a dummy select query graph */
		row_prebuild_sel_graph(prebuilt);
	}

	/* We use the select query graph as the dummy graph needed
	in the lock module call */

	thr = que_fork_get_first_thr(prebuilt->sel_graph);

	que_thr_move_to_run_state_for_mysql(thr, trx);

run_again:
	thr->run_node = thr;
	thr->prev_node = thr->common.parent;

	/* It may be that the current session has not yet started
	its transaction, or it has been committed: */

	trx_start_if_not_started(trx);

	if (table) {
		err = lock_table(0, table, mode, thr);
	} else {
		err = lock_table(0, prebuilt->table,
1087
				 prebuilt->select_lock_type, thr);
osku's avatar
osku committed
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
	}

	trx->error_state = err;

	if (err != DB_SUCCESS) {
		que_thr_stop_for_mysql(thr);

		was_lock_wait = row_mysql_handle_errors(&err, trx, thr, NULL);

		if (was_lock_wait) {
			goto run_again;
		}

		trx->op_info = "";

		return((int) err);
	}

	que_thr_stop_for_mysql_no_error(thr, trx);
1107

osku's avatar
osku committed
1108 1109
	trx->op_info = "";

1110
	return((int) err);
osku's avatar
osku committed
1111
}
1112

1113
/*********************************************************************//**
1114 1115
Does an insert for MySQL.
@return	error code or DB_SUCCESS */
1116
UNIV_INTERN
osku's avatar
osku committed
1117 1118 1119
int
row_insert_for_mysql(
/*=================*/
1120 1121
	byte*		mysql_rec,	/*!< in: row in the MySQL format */
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in MySQL
osku's avatar
osku committed
1122 1123 1124 1125 1126 1127
					handle */
{
	trx_savept_t	savept;
	que_thr_t*	thr;
	ulint		err;
	ibool		was_lock_wait;
1128
	trx_t*		trx		= prebuilt->trx;
osku's avatar
osku committed
1129
	ins_node_t*	node		= prebuilt->ins_node;
1130

osku's avatar
osku committed
1131 1132 1133
	ut_ad(trx);

	if (prebuilt->table->ibd_file_missing) {
1134 1135
		ut_print_timestamp(stderr);
		fprintf(stderr, "  InnoDB: Error:\n"
1136 1137 1138 1139 1140 1141 1142 1143
			"InnoDB: MySQL is trying to use a table handle"
			" but the .ibd file for\n"
			"InnoDB: table %s does not exist.\n"
			"InnoDB: Have you deleted the .ibd file"
			" from the database directory under\n"
			"InnoDB: the MySQL datadir, or have you"
			" used DISCARD TABLESPACE?\n"
			"InnoDB: Look from\n"
1144
			"InnoDB: " REFMAN "innodb-troubleshooting.html\n"
1145 1146
			"InnoDB: how you can resolve the problem.\n",
			prebuilt->table->name);
osku's avatar
osku committed
1147 1148 1149
		return(DB_ERROR);
	}

1150
	if (UNIV_UNLIKELY(prebuilt->magic_n != ROW_PREBUILT_ALLOCATED)) {
osku's avatar
osku committed
1151
		fprintf(stderr,
1152
			"InnoDB: Error: trying to free a corrupt\n"
1153
			"InnoDB: table handle. Magic n %lu, table name ",
1154
			(ulong) prebuilt->magic_n);
1155
		ut_print_name(stderr, trx, TRUE, prebuilt->table->name);
osku's avatar
osku committed
1156 1157
		putc('\n', stderr);

1158
		mem_analyze_corruption(prebuilt);
osku's avatar
osku committed
1159 1160 1161 1162

		ut_error;
	}

1163
	if (UNIV_UNLIKELY(srv_created_new_raw || srv_force_recovery)) {
1164 1165 1166 1167 1168 1169 1170
		fputs("InnoDB: A new raw disk partition was initialized or\n"
		      "InnoDB: innodb_force_recovery is on: we do not allow\n"
		      "InnoDB: database modifications by the user. Shut down\n"
		      "InnoDB: mysqld and edit my.cnf so that"
		      " newraw is replaced\n"
		      "InnoDB: with raw, and innodb_force_... is removed.\n",
		      stderr);
osku's avatar
osku committed
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186

		return(DB_ERROR);
	}

	trx->op_info = "inserting";

	row_mysql_delay_if_needed();

	trx_start_if_not_started(trx);

	if (node == NULL) {
		row_get_prebuilt_insert_row(prebuilt);
		node = prebuilt->ins_node;
	}

	row_mysql_convert_row_to_innobase(node->row, prebuilt, mysql_rec);
1187

osku's avatar
osku committed
1188
	savept = trx_savept_take(trx);
1189

osku's avatar
osku committed
1190 1191 1192 1193 1194 1195 1196 1197
	thr = que_fork_get_first_thr(prebuilt->ins_graph);

	if (prebuilt->sql_stat_start) {
		node->state = INS_NODE_SET_IX_LOCK;
		prebuilt->sql_stat_start = FALSE;
	} else {
		node->state = INS_NODE_ALLOC_ROW_ID;
	}
1198

osku's avatar
osku committed
1199 1200 1201 1202 1203 1204 1205
	que_thr_move_to_run_state_for_mysql(thr, trx);

run_again:
	thr->run_node = node;
	thr->prev_node = node;

	row_ins_step(thr);
1206

osku's avatar
osku committed
1207 1208 1209 1210 1211
	err = trx->error_state;

	if (err != DB_SUCCESS) {
		que_thr_stop_for_mysql(thr);

1212
		/* TODO: what is this? */ thr->lock_state= QUE_THR_LOCK_ROW;
osku's avatar
osku committed
1213 1214

		was_lock_wait = row_mysql_handle_errors(&err, trx, thr,
1215
							&savept);
osku's avatar
osku committed
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
		thr->lock_state= QUE_THR_LOCK_NOLOCK;

		if (was_lock_wait) {
			goto run_again;
		}

		trx->op_info = "";

		return((int) err);
	}

	que_thr_stop_for_mysql_no_error(thr, trx);
1228

osku's avatar
osku committed
1229 1230 1231
	prebuilt->table->stat_n_rows++;

	srv_n_rows_inserted++;
1232

osku's avatar
osku committed
1233 1234 1235
	if (prebuilt->table->stat_n_rows == 0) {
		/* Avoid wrap-over */
		prebuilt->table->stat_n_rows--;
1236
	}
osku's avatar
osku committed
1237 1238 1239 1240 1241 1242 1243

	row_update_statistics_if_needed(prebuilt->table);
	trx->op_info = "";

	return((int) err);
}

1244
/*********************************************************************//**
osku's avatar
osku committed
1245
Builds a dummy query graph used in selects. */
1246
UNIV_INTERN
osku's avatar
osku committed
1247 1248 1249
void
row_prebuild_sel_graph(
/*===================*/
1250
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in MySQL
osku's avatar
osku committed
1251 1252 1253 1254 1255
					handle */
{
	sel_node_t*	node;

	ut_ad(prebuilt && prebuilt->trx);
1256

osku's avatar
osku committed
1257 1258 1259
	if (prebuilt->sel_graph == NULL) {

		node = sel_node_create(prebuilt->heap);
1260

1261 1262 1263 1264
		prebuilt->sel_graph = que_node_get_parent(
			pars_complete_graph_for_exec(node,
						     prebuilt->trx,
						     prebuilt->heap));
osku's avatar
osku committed
1265 1266 1267 1268 1269

		prebuilt->sel_graph->state = QUE_FORK_ACTIVE;
	}
}

1270
/*********************************************************************//**
osku's avatar
osku committed
1271
Creates an query graph node of 'update' type to be used in the MySQL
1272 1273
interface.
@return	own: update node */
1274
UNIV_INTERN
osku's avatar
osku committed
1275 1276 1277
upd_node_t*
row_create_update_node_for_mysql(
/*=============================*/
1278 1279
	dict_table_t*	table,	/*!< in: table to update */
	mem_heap_t*	heap)	/*!< in: mem heap from which allocated */
osku's avatar
osku committed
1280 1281 1282 1283
{
	upd_node_t*	node;

	node = upd_node_create(heap);
1284

osku's avatar
osku committed
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
	node->in_mysql_interface = TRUE;
	node->is_delete = FALSE;
	node->searched_update = FALSE;
	node->select = NULL;
	node->pcur = btr_pcur_create_for_mysql();
	node->table = table;

	node->update = upd_create(dict_table_get_n_cols(table), heap);

	node->update_n_fields = dict_table_get_n_cols(table);
1295

osku's avatar
osku committed
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
	UT_LIST_INIT(node->columns);
	node->has_clust_rec_x_lock = TRUE;
	node->cmpl_info = 0;

	node->table_sym = NULL;
	node->col_assign_list = NULL;

	return(node);
}

1306
/*********************************************************************//**
osku's avatar
osku committed
1307 1308
Gets pointer to a prebuilt update vector used in updates. If the update
graph has not yet been built in the prebuilt struct, then this function
1309 1310
first builds it.
@return	prebuilt update vector */
1311
UNIV_INTERN
osku's avatar
osku committed
1312 1313 1314
upd_t*
row_get_prebuilt_update_vector(
/*===========================*/
1315
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in MySQL
osku's avatar
osku committed
1316 1317 1318 1319 1320 1321
					handle */
{
	dict_table_t*	table	= prebuilt->table;
	upd_node_t*	node;

	ut_ad(prebuilt && table && prebuilt->trx);
1322

osku's avatar
osku committed
1323 1324 1325 1326 1327 1328 1329 1330
	if (prebuilt->upd_node == NULL) {

		/* Not called before for this handle: create an update node
		and query graph to the prebuilt struct */

		node = row_create_update_node_for_mysql(table, prebuilt->heap);

		prebuilt->upd_node = node;
1331

1332 1333 1334 1335
		prebuilt->upd_graph = que_node_get_parent(
			pars_complete_graph_for_exec(node,
						     prebuilt->trx,
						     prebuilt->heap));
osku's avatar
osku committed
1336 1337 1338 1339 1340 1341
		prebuilt->upd_graph->state = QUE_FORK_ACTIVE;
	}

	return(prebuilt->upd_node->update);
}

1342
/*********************************************************************//**
1343 1344
Does an update or delete of a row for MySQL.
@return	error code or DB_SUCCESS */
1345
UNIV_INTERN
osku's avatar
osku committed
1346 1347 1348
int
row_update_for_mysql(
/*=================*/
1349
	byte*		mysql_rec,	/*!< in: the row to be updated, in
osku's avatar
osku committed
1350
					the MySQL format */
1351
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in MySQL
osku's avatar
osku committed
1352 1353 1354 1355 1356 1357
					handle */
{
	trx_savept_t	savept;
	ulint		err;
	que_thr_t*	thr;
	ibool		was_lock_wait;
1358
	dict_index_t*	clust_index;
1359
	/*	ulint		ref_len; */
osku's avatar
osku committed
1360 1361 1362 1363 1364 1365
	upd_node_t*	node;
	dict_table_t*	table		= prebuilt->table;
	trx_t*		trx		= prebuilt->trx;

	ut_ad(prebuilt && trx);
	UT_NOT_USED(mysql_rec);
1366

osku's avatar
osku committed
1367
	if (prebuilt->table->ibd_file_missing) {
1368 1369
		ut_print_timestamp(stderr);
		fprintf(stderr, "  InnoDB: Error:\n"
1370 1371 1372 1373 1374 1375 1376 1377
			"InnoDB: MySQL is trying to use a table handle"
			" but the .ibd file for\n"
			"InnoDB: table %s does not exist.\n"
			"InnoDB: Have you deleted the .ibd file"
			" from the database directory under\n"
			"InnoDB: the MySQL datadir, or have you"
			" used DISCARD TABLESPACE?\n"
			"InnoDB: Look from\n"
1378
			"InnoDB: " REFMAN "innodb-troubleshooting.html\n"
1379 1380
			"InnoDB: how you can resolve the problem.\n",
			prebuilt->table->name);
osku's avatar
osku committed
1381 1382 1383
		return(DB_ERROR);
	}

1384
	if (UNIV_UNLIKELY(prebuilt->magic_n != ROW_PREBUILT_ALLOCATED)) {
osku's avatar
osku committed
1385
		fprintf(stderr,
1386
			"InnoDB: Error: trying to free a corrupt\n"
1387
			"InnoDB: table handle. Magic n %lu, table name ",
1388
			(ulong) prebuilt->magic_n);
1389
		ut_print_name(stderr, trx, TRUE, prebuilt->table->name);
osku's avatar
osku committed
1390 1391
		putc('\n', stderr);

1392
		mem_analyze_corruption(prebuilt);
osku's avatar
osku committed
1393 1394 1395 1396

		ut_error;
	}

1397
	if (UNIV_UNLIKELY(srv_created_new_raw || srv_force_recovery)) {
1398 1399 1400 1401 1402 1403 1404
		fputs("InnoDB: A new raw disk partition was initialized or\n"
		      "InnoDB: innodb_force_recovery is on: we do not allow\n"
		      "InnoDB: database modifications by the user. Shut down\n"
		      "InnoDB: mysqld and edit my.cnf so that newraw"
		      " is replaced\n"
		      "InnoDB: with raw, and innodb_force_... is removed.\n",
		      stderr);
osku's avatar
osku committed
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422

		return(DB_ERROR);
	}

	trx->op_info = "updating or deleting";

	row_mysql_delay_if_needed();

	trx_start_if_not_started(trx);

	node = prebuilt->upd_node;

	clust_index = dict_table_get_first_index(table);

	if (prebuilt->pcur->btr_cur.index == clust_index) {
		btr_pcur_copy_stored_position(node->pcur, prebuilt->pcur);
	} else {
		btr_pcur_copy_stored_position(node->pcur,
1423
					      prebuilt->clust_pcur);
osku's avatar
osku committed
1424
	}
1425

osku's avatar
osku committed
1426
	ut_a(node->pcur->rel_pos == BTR_PCUR_ON);
1427

osku's avatar
osku committed
1428 1429 1430 1431 1432 1433 1434 1435
	/* MySQL seems to call rnd_pos before updating each row it
	has cached: we can get the correct cursor position from
	prebuilt->pcur; NOTE that we cannot build the row reference
	from mysql_rec if the clustered index was automatically
	generated for the table: MySQL does not know anything about
	the row id used as the clustered index key */

	savept = trx_savept_take(trx);
1436

osku's avatar
osku committed
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
	thr = que_fork_get_first_thr(prebuilt->upd_graph);

	node->state = UPD_NODE_UPDATE_CLUSTERED;

	ut_ad(!prebuilt->sql_stat_start);

	que_thr_move_to_run_state_for_mysql(thr, trx);

run_again:
	thr->run_node = node;
	thr->prev_node = node;
1448
	thr->fk_cascade_depth = 0;
osku's avatar
osku committed
1449 1450 1451 1452 1453

	row_upd_step(thr);

	err = trx->error_state;

1454 1455 1456
	/* Reset fk_cascade_depth back to 0 */
	thr->fk_cascade_depth = 0;

osku's avatar
osku committed
1457 1458
	if (err != DB_SUCCESS) {
		que_thr_stop_for_mysql(thr);
1459

osku's avatar
osku committed
1460 1461 1462 1463 1464 1465 1466
		if (err == DB_RECORD_NOT_FOUND) {
			trx->error_state = DB_SUCCESS;
			trx->op_info = "";

			return((int) err);
		}

1467
		thr->lock_state= QUE_THR_LOCK_ROW;
osku's avatar
osku committed
1468
		was_lock_wait = row_mysql_handle_errors(&err, trx, thr,
1469
							&savept);
1470 1471
		thr->lock_state= QUE_THR_LOCK_NOLOCK;

osku's avatar
osku committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
		if (was_lock_wait) {
			goto run_again;
		}

		trx->op_info = "";

		return((int) err);
	}

	que_thr_stop_for_mysql_no_error(thr, trx);

	if (node->is_delete) {
		if (prebuilt->table->stat_n_rows > 0) {
			prebuilt->table->stat_n_rows--;
		}

		srv_n_rows_deleted++;
	} else {
		srv_n_rows_updated++;
	}

1493 1494 1495 1496 1497 1498
	/* We update table statistics only if it is a DELETE or UPDATE
	that changes indexed columns, UPDATEs that change only non-indexed
	columns would not affect statistics. */
	if (node->is_delete || !(node->cmpl_info & UPD_NODE_NO_ORD_CHANGE)) {
		row_update_statistics_if_needed(prebuilt->table);
	}
osku's avatar
osku committed
1499 1500 1501 1502 1503 1504

	trx->op_info = "";

	return((int) err);
}

1505
/*********************************************************************//**
1506 1507 1508 1509 1510 1511 1512 1513 1514
This can only be used when srv_locks_unsafe_for_binlog is TRUE or this
session is using a READ COMMITTED or READ UNCOMMITTED isolation level.
Before calling this function row_search_for_mysql() must have
initialized prebuilt->new_rec_locks to store the information which new
record locks really were set. This function removes a newly set
clustered index record lock under prebuilt->pcur or
prebuilt->clust_pcur.  Thus, this implements a 'mini-rollback' that
releases the latest clustered index record lock we set.
@return error code or DB_SUCCESS */
1515
UNIV_INTERN
osku's avatar
osku committed
1516 1517 1518
int
row_unlock_for_mysql(
/*=================*/
1519
	row_prebuilt_t*	prebuilt,	/*!< in/out: prebuilt struct in MySQL
osku's avatar
osku committed
1520
					handle */
1521 1522 1523 1524 1525
	ibool		has_latches_on_recs)/*!< in: TRUE if called so
					that we have the latches on
					the records under pcur and
					clust_pcur, and we do not need
					to reposition the cursors. */
osku's avatar
osku committed
1526 1527 1528 1529
{
	btr_pcur_t*	pcur		= prebuilt->pcur;
	btr_pcur_t*	clust_pcur	= prebuilt->clust_pcur;
	trx_t*		trx		= prebuilt->trx;
1530

osku's avatar
osku committed
1531
	ut_ad(prebuilt && trx);
1532

1533 1534
	if (UNIV_UNLIKELY
	    (!srv_locks_unsafe_for_binlog
Vasil Dimov's avatar
Vasil Dimov committed
1535
	     && trx->isolation_level > TRX_ISO_READ_COMMITTED)) {
osku's avatar
osku committed
1536 1537

		fprintf(stderr,
1538
			"InnoDB: Error: calling row_unlock_for_mysql though\n"
1539
			"InnoDB: innodb_locks_unsafe_for_binlog is FALSE and\n"
1540 1541
			"InnoDB: this session is not using"
			" READ COMMITTED isolation level.\n");
osku's avatar
osku committed
1542 1543 1544 1545 1546 1547

		return(DB_SUCCESS);
	}

	trx->op_info = "unlock_row";

1548
	if (prebuilt->new_rec_locks >= 1) {
osku's avatar
osku committed
1549

1550
		const rec_t*	rec;
1551
		dict_index_t*	index;
1552
		trx_id_t	rec_trx_id;
1553
		mtr_t		mtr;
osku's avatar
osku committed
1554 1555

		mtr_start(&mtr);
1556

osku's avatar
osku committed
1557
		/* Restore the cursor position and find the record */
1558

osku's avatar
osku committed
1559 1560 1561 1562 1563
		if (!has_latches_on_recs) {
			btr_pcur_restore_position(BTR_SEARCH_LEAF, pcur, &mtr);
		}

		rec = btr_pcur_get_rec(pcur);
1564
		index = btr_pcur_get_btr_cur(pcur)->index;
osku's avatar
osku committed
1565

1566 1567 1568
		if (prebuilt->new_rec_locks >= 2) {
			/* Restore the cursor position and find the record
			in the clustered index. */
osku's avatar
osku committed
1569

1570 1571 1572 1573
			if (!has_latches_on_recs) {
				btr_pcur_restore_position(BTR_SEARCH_LEAF,
							  clust_pcur, &mtr);
			}
1574

1575 1576
			rec = btr_pcur_get_rec(clust_pcur);
			index = btr_pcur_get_btr_cur(clust_pcur)->index;
osku's avatar
osku committed
1577 1578
		}

1579 1580 1581 1582 1583 1584
		if (UNIV_UNLIKELY(!dict_index_is_clust(index))) {
			/* This is not a clustered index record.  We
			do not know how to unlock the record. */
			goto no_unlock;
		}

1585 1586
		/* If the record has been modified by this
		transaction, do not unlock it. */
osku's avatar
osku committed
1587

1588 1589 1590 1591 1592 1593 1594
		if (index->trx_id_offset) {
			rec_trx_id = trx_read_trx_id(rec
						     + index->trx_id_offset);
		} else {
			mem_heap_t*	heap			= NULL;
			ulint	offsets_[REC_OFFS_NORMAL_SIZE];
			ulint*	offsets				= offsets_;
osku's avatar
osku committed
1595

1596 1597 1598
			rec_offs_init(offsets_);
			offsets = rec_get_offsets(rec, index, offsets,
						  ULINT_UNDEFINED, &heap);
1599

1600
			rec_trx_id = row_get_rec_trx_id(rec, index, offsets);
osku's avatar
osku committed
1601

1602 1603 1604
			if (UNIV_LIKELY_NULL(heap)) {
				mem_heap_free(heap);
			}
osku's avatar
osku committed
1605 1606
		}

1607
		if (rec_trx_id != trx->id) {
1608
			/* We did not update the record: unlock it */
osku's avatar
osku committed
1609

1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
			rec = btr_pcur_get_rec(pcur);
			index = btr_pcur_get_btr_cur(pcur)->index;

			lock_rec_unlock(trx, btr_pcur_get_block(pcur),
					rec, prebuilt->select_lock_type);

			if (prebuilt->new_rec_locks >= 2) {
				rec = btr_pcur_get_rec(clust_pcur);
				index = btr_pcur_get_btr_cur(clust_pcur)->index;

				lock_rec_unlock(trx,
						btr_pcur_get_block(clust_pcur),
						rec,
						prebuilt->select_lock_type);
			}
		}
1626
no_unlock:
osku's avatar
osku committed
1627 1628
		mtr_commit(&mtr);
	}
1629

osku's avatar
osku committed
1630
	trx->op_info = "";
1631

osku's avatar
osku committed
1632 1633 1634
	return(DB_SUCCESS);
}

1635
/**********************************************************************//**
1636 1637
Does a cascaded delete or set null in a foreign key operation.
@return	error code or DB_SUCCESS */
1638
UNIV_INTERN
osku's avatar
osku committed
1639 1640 1641
ulint
row_update_cascade_for_mysql(
/*=========================*/
1642 1643
	que_thr_t*	thr,	/*!< in: query thread */
	upd_node_t*	node,	/*!< in: update node used in the cascade
osku's avatar
osku committed
1644
				or set null operation */
1645
	dict_table_t*	table)	/*!< in: table where we do the operation */
osku's avatar
osku committed
1646 1647 1648 1649 1650
{
	ulint	err;
	trx_t*	trx;

	trx = thr_get_trx(thr);
1651

1652 1653 1654
	/* Increment fk_cascade_depth to record the recursive call depth on
	a single update/delete that affects multiple tables chained
	together with foreign key relations. */
1655 1656 1657 1658 1659
	thr->fk_cascade_depth++;

	if (thr->fk_cascade_depth > FK_MAX_CASCADE_DEL) {
		return (DB_FOREIGN_EXCEED_MAX_CASCADE);
	}
osku's avatar
osku committed
1660 1661 1662 1663 1664 1665
run_again:
	thr->run_node = node;
	thr->prev_node = node;

	row_upd_step(thr);

1666 1667 1668 1669 1670 1671
	/* The recursive call for cascading update/delete happens
	in above row_upd_step(), reset the counter once we come
	out of the recursive call, so it does not accumulate for
	different row deletes */
	thr->fk_cascade_depth = 0;

osku's avatar
osku committed
1672 1673 1674 1675 1676 1677 1678 1679
	err = trx->error_state;

	/* Note that the cascade node is a subnode of another InnoDB
	query graph node. We do a normal lock wait in this node, but
	all errors are handled by the parent node. */

	if (err == DB_LOCK_WAIT) {
		/* Handle lock wait here */
1680

osku's avatar
osku committed
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
		que_thr_stop_for_mysql(thr);

		srv_suspend_mysql_thread(thr);

		/* Note that a lock wait may also end in a lock wait timeout,
		or this transaction is picked as a victim in selective
		deadlock resolution */

		if (trx->error_state != DB_SUCCESS) {

			return(trx->error_state);
		}

		/* Retry operation after a normal lock wait */
1695

osku's avatar
osku committed
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
		goto run_again;
	}

	if (err != DB_SUCCESS) {

		return(err);
	}

	if (node->is_delete) {
		if (table->stat_n_rows > 0) {
			table->stat_n_rows--;
		}

		srv_n_rows_deleted++;
	} else {
		srv_n_rows_updated++;
	}

	row_update_statistics_if_needed(table);

	return(err);
}

1719
/*********************************************************************//**
osku's avatar
osku committed
1720
Checks if a table is such that we automatically created a clustered
1721 1722
index on it (on row id).
@return	TRUE if the clustered index was generated automatically */
1723
UNIV_INTERN
osku's avatar
osku committed
1724 1725 1726
ibool
row_table_got_default_clust_index(
/*==============================*/
1727
	const dict_table_t*	table)	/*!< in: table */
osku's avatar
osku committed
1728
{
1729
	const dict_index_t*	clust_index;
osku's avatar
osku committed
1730 1731 1732

	clust_index = dict_table_get_first_index(table);

1733
	return(dict_index_get_nth_col(clust_index, 0)->mtype == DATA_SYS);
osku's avatar
osku committed
1734 1735
}

1736
/*********************************************************************//**
osku's avatar
osku committed
1737 1738
Locks the data dictionary in shared mode from modifications, for performing
foreign key check, rollback, or other operation invisible to MySQL. */
1739
UNIV_INTERN
osku's avatar
osku committed
1740
void
1741 1742
row_mysql_freeze_data_dictionary_func(
/*==================================*/
1743 1744 1745
	trx_t*		trx,	/*!< in/out: transaction */
	const char*	file,	/*!< in: file name */
	ulint		line)	/*!< in: line number */
osku's avatar
osku committed
1746 1747
{
	ut_a(trx->dict_operation_lock_mode == 0);
1748

1749
	rw_lock_s_lock_func(&dict_operation_lock, 0, file, line);
osku's avatar
osku committed
1750 1751 1752 1753

	trx->dict_operation_lock_mode = RW_S_LATCH;
}

1754
/*********************************************************************//**
osku's avatar
osku committed
1755
Unlocks the data dictionary shared lock. */
1756
UNIV_INTERN
osku's avatar
osku committed
1757 1758 1759
void
row_mysql_unfreeze_data_dictionary(
/*===============================*/
1760
	trx_t*	trx)	/*!< in/out: transaction */
osku's avatar
osku committed
1761 1762 1763 1764 1765 1766 1767 1768
{
	ut_a(trx->dict_operation_lock_mode == RW_S_LATCH);

	rw_lock_s_unlock(&dict_operation_lock);

	trx->dict_operation_lock_mode = 0;
}

1769
/*********************************************************************//**
osku's avatar
osku committed
1770 1771
Locks the data dictionary exclusively for performing a table create or other
data dictionary modification operation. */
1772
UNIV_INTERN
osku's avatar
osku committed
1773
void
1774 1775
row_mysql_lock_data_dictionary_func(
/*================================*/
1776 1777 1778
	trx_t*		trx,	/*!< in/out: transaction */
	const char*	file,	/*!< in: file name */
	ulint		line)	/*!< in: line number */
osku's avatar
osku committed
1779 1780
{
	ut_a(trx->dict_operation_lock_mode == 0
1781
	     || trx->dict_operation_lock_mode == RW_X_LATCH);
1782

osku's avatar
osku committed
1783 1784 1785
	/* Serialize data dictionary operations with dictionary mutex:
	no deadlocks or lock waits can occur then in these operations */

1786
	rw_lock_x_lock_func(&dict_operation_lock, 0, file, line);
osku's avatar
osku committed
1787 1788 1789 1790 1791
	trx->dict_operation_lock_mode = RW_X_LATCH;

	mutex_enter(&(dict_sys->mutex));
}

1792
/*********************************************************************//**
osku's avatar
osku committed
1793
Unlocks the data dictionary exclusive lock. */
1794
UNIV_INTERN
osku's avatar
osku committed
1795 1796 1797
void
row_mysql_unlock_data_dictionary(
/*=============================*/
1798
	trx_t*	trx)	/*!< in/out: transaction */
osku's avatar
osku committed
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
{
	ut_a(trx->dict_operation_lock_mode == RW_X_LATCH);

	/* Serialize data dictionary operations with dictionary mutex:
	no deadlocks can occur then in these operations */

	mutex_exit(&(dict_sys->mutex));
	rw_lock_x_unlock(&dict_operation_lock);

	trx->dict_operation_lock_mode = 0;
}

1811
/*********************************************************************//**
1812
Creates a table for MySQL. If the name of the table ends in
1813 1814 1815
one of "innodb_monitor", "innodb_lock_monitor", "innodb_tablespace_monitor",
"innodb_table_monitor", then this will also start the printing of monitor
output by the master thread. If the table name ends in "innodb_mem_validate",
1816 1817
InnoDB will try to invoke mem_validate().
@return	error code or DB_SUCCESS */
1818
UNIV_INTERN
osku's avatar
osku committed
1819 1820 1821
int
row_create_table_for_mysql(
/*=======================*/
1822
	dict_table_t*	table,	/*!< in, own: table definition
1823
				(will be freed) */
1824
	trx_t*		trx)	/*!< in: transaction handle */
osku's avatar
osku committed
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
{
	tab_node_t*	node;
	mem_heap_t*	heap;
	que_thr_t*	thr;
	const char*	table_name;
	ulint		table_name_len;
	ulint		err;

#ifdef UNIV_SYNC_DEBUG
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
#endif /* UNIV_SYNC_DEBUG */
1836
	ut_ad(mutex_own(&(dict_sys->mutex)));
osku's avatar
osku committed
1837
	ut_ad(trx->dict_operation_lock_mode == RW_X_LATCH);
1838

osku's avatar
osku committed
1839
	if (srv_created_new_raw) {
1840 1841 1842 1843 1844
		fputs("InnoDB: A new raw disk partition was initialized:\n"
		      "InnoDB: we do not allow database modifications"
		      " by the user.\n"
		      "InnoDB: Shut down mysqld and edit my.cnf so that newraw"
		      " is replaced with raw.\n", stderr);
1845
err_exit:
1846
		dict_mem_table_free(table);
osku's avatar
osku committed
1847 1848 1849 1850 1851 1852
		trx_commit_for_mysql(trx);

		return(DB_ERROR);
	}

	trx->op_info = "creating table";
1853

osku's avatar
osku committed
1854 1855 1856
	if (row_mysql_is_system_table(table->name)) {

		fprintf(stderr,
1857 1858 1859 1860 1861
			"InnoDB: Error: trying to create a MySQL system"
			" table %s of type InnoDB.\n"
			"InnoDB: MySQL system tables must be"
			" of the MyISAM type!\n",
			table->name);
1862
		goto err_exit;
osku's avatar
osku committed
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
	}

	trx_start_if_not_started(trx);

	/* The table name is prefixed with the database name and a '/'.
	Certain table names starting with 'innodb_' have their special
	meaning regardless of the database name.  Thus, we need to
	ignore the database name prefix in the comparisons. */
	table_name = strchr(table->name, '/');
	ut_a(table_name);
	table_name++;
	table_name_len = strlen(table_name) + 1;

1876
	if (STR_EQ(table_name, table_name_len, S_innodb_monitor)) {
osku's avatar
osku committed
1877 1878 1879

		/* Table equals "innodb_monitor":
		start monitor prints */
1880

osku's avatar
osku committed
1881 1882 1883 1884 1885 1886
		srv_print_innodb_monitor = TRUE;

		/* The lock timeout monitor thread also takes care
		of InnoDB monitor prints */

		os_event_set(srv_lock_timeout_thread_event);
1887 1888
	} else if (STR_EQ(table_name, table_name_len,
			  S_innodb_lock_monitor)) {
osku's avatar
osku committed
1889 1890 1891 1892

		srv_print_innodb_monitor = TRUE;
		srv_print_innodb_lock_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1893 1894
	} else if (STR_EQ(table_name, table_name_len,
			  S_innodb_tablespace_monitor)) {
osku's avatar
osku committed
1895 1896 1897

		srv_print_innodb_tablespace_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1898 1899
	} else if (STR_EQ(table_name, table_name_len,
			  S_innodb_table_monitor)) {
osku's avatar
osku committed
1900 1901 1902

		srv_print_innodb_table_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1903 1904
	} else if (STR_EQ(table_name, table_name_len,
			  S_innodb_mem_validate)) {
1905
		/* We define here a debugging feature intended for
osku's avatar
osku committed
1906 1907 1908
		developers */

		fputs("Validating InnoDB memory:\n"
1909 1910 1911 1912 1913 1914
		      "to use this feature you must compile InnoDB with\n"
		      "UNIV_MEM_DEBUG defined in univ.i and"
		      " the server must be\n"
		      "quiet because allocation from a mem heap"
		      " is not protected\n"
		      "by any semaphore.\n", stderr);
osku's avatar
osku committed
1915 1916 1917 1918 1919
#ifdef UNIV_MEM_DEBUG
		ut_a(mem_validate());
		fputs("Memory validated\n", stderr);
#else /* UNIV_MEM_DEBUG */
		fputs("Memory NOT validated (recompile with UNIV_MEM_DEBUG)\n",
1920
		      stderr);
osku's avatar
osku committed
1921 1922 1923 1924 1925
#endif /* UNIV_MEM_DEBUG */
	}

	heap = mem_heap_create(512);

1926
	trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
1927

osku's avatar
osku committed
1928 1929 1930 1931 1932 1933 1934 1935 1936
	node = tab_create_graph_create(table, heap);

	thr = pars_complete_graph_for_exec(node, trx, heap);

	ut_a(thr == que_fork_start_command(que_node_get_parent(thr)));
	que_run_threads(thr);

	err = trx->error_state;

1937 1938 1939 1940
	switch (err) {
	case DB_SUCCESS:
		break;
	case DB_OUT_OF_FILE_SPACE:
1941
		trx->error_state = DB_SUCCESS;
1942
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
1943

1944 1945 1946 1947 1948
		ut_print_timestamp(stderr);
		fputs("  InnoDB: Warning: cannot create table ",
		      stderr);
		ut_print_name(stderr, trx, TRUE, table->name);
		fputs(" because tablespace full\n", stderr);
osku's avatar
osku committed
1949

1950
		if (dict_table_get_low(table->name)) {
osku's avatar
osku committed
1951

1952
			row_drop_table_for_mysql(table->name, trx, FALSE);
1953
			trx_commit_for_mysql(trx);
1954 1955
		}
		break;
osku's avatar
osku committed
1956

1957
	case DB_DUPLICATE_KEY:
1958
	default:
osku's avatar
osku committed
1959 1960 1961
		/* We may also get err == DB_ERROR if the .ibd file for the
		table already exists */

1962 1963 1964
		trx->error_state = DB_SUCCESS;
		trx_general_rollback_for_mysql(trx, NULL);
		dict_mem_table_free(table);
1965
		break;
osku's avatar
osku committed
1966 1967 1968 1969 1970 1971 1972 1973 1974
	}

	que_graph_free((que_t*) que_node_get_parent(thr));

	trx->op_info = "";

	return((int) err);
}

1975
/*********************************************************************//**
osku's avatar
osku committed
1976 1977
Does an index creation operation for MySQL. TODO: currently failure
to create an index results in dropping the whole table! This is no problem
1978 1979
currently as all indexes must be created at the same time as the table.
@return	error number or DB_SUCCESS */
1980
UNIV_INTERN
osku's avatar
osku committed
1981 1982 1983
int
row_create_index_for_mysql(
/*=======================*/
1984
	dict_index_t*	index,		/*!< in, own: index definition
1985
					(will be freed) */
1986 1987
	trx_t*		trx,		/*!< in: transaction handle */
	const ulint*	field_lengths)	/*!< in: if not NULL, must contain
osku's avatar
osku committed
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
					dict_index_get_n_fields(index)
					actual field lengths for the
					index columns, which are
					then checked for not being too
					large. */
{
	ind_node_t*	node;
	mem_heap_t*	heap;
	que_thr_t*	thr;
	ulint		err;
1998
	ulint		i;
osku's avatar
osku committed
1999
	ulint		len;
2000
	char*		table_name;
2001
	dict_table_t*	table;
2002

osku's avatar
osku committed
2003 2004 2005
#ifdef UNIV_SYNC_DEBUG
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
#endif /* UNIV_SYNC_DEBUG */
2006
	ut_ad(mutex_own(&(dict_sys->mutex)));
2007

osku's avatar
osku committed
2008 2009
	trx->op_info = "creating index";

2010 2011 2012 2013 2014
	/* Copy the table name because we may want to drop the
	table later, after the index object is freed (inside
	que_run_threads()) and thus index->table_name is not available. */
	table_name = mem_strdup(index->table_name);

2015 2016
	table = dict_table_get_low(table_name);

osku's avatar
osku committed
2017 2018
	trx_start_if_not_started(trx);

2019 2020 2021
	for (i = 0; i < index->n_def; i++) {
		/* Check that prefix_len and actual length
		< DICT_MAX_INDEX_COL_LEN */
osku's avatar
osku committed
2022 2023 2024

		len = dict_index_get_nth_field(index, i)->prefix_len;

2025
		if (field_lengths && field_lengths[i]) {
osku's avatar
osku committed
2026 2027
			len = ut_max(len, field_lengths[i]);
		}
2028

2029 2030 2031
		/* Column or prefix length exceeds maximum column length */
		if (len > (ulint) DICT_MAX_FIELD_LEN_BY_FORMAT(table)) {
			err = DB_TOO_BIG_INDEX_COL;
osku's avatar
osku committed
2032

2033
			dict_mem_index_free(index);
osku's avatar
osku committed
2034 2035 2036 2037 2038 2039
			goto error_handling;
		}
	}

	heap = mem_heap_create(512);

2040
	trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
osku's avatar
osku committed
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051

	/* Note that the space id where we store the index is inherited from
	the table in dict_build_index_def_step() in dict0crea.c. */

	node = ind_create_graph_create(index, heap);

	thr = pars_complete_graph_for_exec(node, trx, heap);

	ut_a(thr == que_fork_start_command(que_node_get_parent(thr)));
	que_run_threads(thr);

2052
	err = trx->error_state;
osku's avatar
osku committed
2053 2054 2055 2056

	que_graph_free((que_t*) que_node_get_parent(thr));

error_handling:
2057

osku's avatar
osku committed
2058 2059
	if (err != DB_SUCCESS) {
		/* We have special error handling here */
2060

osku's avatar
osku committed
2061 2062
		trx->error_state = DB_SUCCESS;

2063
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
2064

2065
		row_drop_table_for_mysql(table_name, trx, FALSE);
osku's avatar
osku committed
2066

2067 2068
		trx_commit_for_mysql(trx);

osku's avatar
osku committed
2069 2070
		trx->error_state = DB_SUCCESS;
	}
2071

osku's avatar
osku committed
2072 2073
	trx->op_info = "";

2074 2075
	mem_free(table_name);

osku's avatar
osku committed
2076 2077 2078
	return((int) err);
}

2079
/*********************************************************************//**
osku's avatar
osku committed
2080 2081 2082 2083
Scans a table create SQL string and adds to the data dictionary
the foreign key constraints declared in the string. This function
should be called after the indexes for a table have been created.
Each foreign key constraint must be accompanied with indexes in
2084
both participating tables. The indexes are allowed to contain more
osku's avatar
osku committed
2085
fields than mentioned in the constraint. Check also that foreign key
2086 2087
constraints which reference this table are ok.
@return	error code or DB_SUCCESS */
2088
UNIV_INTERN
osku's avatar
osku committed
2089 2090 2091
int
row_table_add_foreign_constraints(
/*==============================*/
2092 2093
	trx_t*		trx,		/*!< in: transaction */
	const char*	sql_string,	/*!< in: table create statement where
osku's avatar
osku committed
2094 2095 2096 2097
					foreign keys are declared like:
				FOREIGN KEY (a, b) REFERENCES table2(c, d),
					table2 can be written also with the
					database name before it: test.table2 */
2098
	size_t		sql_length,	/*!< in: length of sql_string */
2099
	const char*	name,		/*!< in: table full name in the
osku's avatar
osku committed
2100 2101
					normalized form
					database_name/table_name */
2102
	ibool		reject_fks)	/*!< in: if TRUE, fail with error
osku's avatar
osku committed
2103 2104 2105 2106 2107 2108
					code DB_CANNOT_ADD_CONSTRAINT if
					any foreign keys are found. */
{
	ulint	err;

	ut_ad(mutex_own(&(dict_sys->mutex)));
2109
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
2110 2111 2112
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
#endif /* UNIV_SYNC_DEBUG */
	ut_a(sql_string);
2113

osku's avatar
osku committed
2114 2115 2116 2117
	trx->op_info = "adding foreign keys";

	trx_start_if_not_started(trx);

2118
	trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
osku's avatar
osku committed
2119

2120 2121
	err = dict_create_foreign_constraints(trx, sql_string, sql_length,
					      name, reject_fks);
osku's avatar
osku committed
2122 2123
	if (err == DB_SUCCESS) {
		/* Check that also referencing constraints are ok */
2124
		err = dict_load_foreigns(name, FALSE, TRUE);
osku's avatar
osku committed
2125
	}
2126

osku's avatar
osku committed
2127 2128
	if (err != DB_SUCCESS) {
		/* We have special error handling here */
2129

osku's avatar
osku committed
2130 2131
		trx->error_state = DB_SUCCESS;

2132
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
2133 2134 2135

		row_drop_table_for_mysql(name, trx, FALSE);

2136 2137
		trx_commit_for_mysql(trx);

osku's avatar
osku committed
2138 2139 2140 2141 2142 2143
		trx->error_state = DB_SUCCESS;
	}

	return((int) err);
}

2144
/*********************************************************************//**
osku's avatar
osku committed
2145 2146 2147 2148 2149
Drops a table for MySQL as a background operation. MySQL relies on Unix
in ALTER TABLE to the fact that the table handler does not remove the
table before all handles to it has been removed. Furhermore, the MySQL's
call to drop table must be non-blocking. Therefore we do the drop table
as a background operation, which is taken care of by the master thread
2150 2151
in srv0srv.c.
@return	error code or DB_SUCCESS */
osku's avatar
osku committed
2152 2153 2154 2155
static
int
row_drop_table_for_mysql_in_background(
/*===================================*/
2156
	const char*	name)	/*!< in: table name */
osku's avatar
osku committed
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
{
	ulint	error;
	trx_t*	trx;

	trx = trx_allocate_for_background();

	/* If the original transaction was dropping a table referenced by
	foreign keys, we must set the following to be able to drop the
	table: */

	trx->check_foreigns = FALSE;

2169
	/*	fputs("InnoDB: Error: Dropping table ", stderr);
2170
	ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2171 2172
	fputs(" in background drop list\n", stderr); */

2173 2174 2175
	/* Try to drop the table in InnoDB */

	error = row_drop_table_for_mysql(name, trx, FALSE);
osku's avatar
osku committed
2176 2177 2178 2179

	/* Flush the log to reduce probability that the .frm files and
	the InnoDB data dictionary get out-of-sync if the user runs
	with innodb_flush_log_at_trx_commit = 0 */
2180

osku's avatar
osku committed
2181 2182
	log_buffer_flush_to_disk();

2183
	trx_commit_for_mysql(trx);
osku's avatar
osku committed
2184

2185
	trx_free_for_background(trx);
osku's avatar
osku committed
2186 2187 2188 2189

	return((int) error);
}

2190
/*********************************************************************//**
osku's avatar
osku committed
2191 2192
The master thread in srv0srv.c calls this regularly to drop tables which
we must drop in background after queries to them have ended. Such lazy
2193 2194
dropping of tables is needed in ALTER TABLE on Unix.
@return	how many tables dropped + remaining tables in list */
2195
UNIV_INTERN
osku's avatar
osku committed
2196 2197 2198 2199 2200 2201 2202 2203
ulint
row_drop_tables_for_mysql_in_background(void)
/*=========================================*/
{
	row_mysql_drop_t*	drop;
	dict_table_t*		table;
	ulint			n_tables;
	ulint			n_tables_dropped = 0;
2204
loop:
osku's avatar
osku committed
2205 2206 2207 2208 2209 2210 2211 2212 2213
	mutex_enter(&kernel_mutex);

	if (!row_mysql_drop_list_inited) {

		UT_LIST_INIT(row_mysql_drop_list);
		row_mysql_drop_list_inited = TRUE;
	}

	drop = UT_LIST_GET_FIRST(row_mysql_drop_list);
2214

osku's avatar
osku committed
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
	n_tables = UT_LIST_GET_LEN(row_mysql_drop_list);

	mutex_exit(&kernel_mutex);

	if (drop == NULL) {
		/* All tables dropped */

		return(n_tables + n_tables_dropped);
	}

	mutex_enter(&(dict_sys->mutex));
	table = dict_table_get_low(drop->table_name);
	mutex_exit(&(dict_sys->mutex));

	if (table == NULL) {
2230
		/* If for some reason the table has already been dropped
osku's avatar
osku committed
2231 2232
		through some other mechanism, do not try to drop it */

2233
		goto already_dropped;
osku's avatar
osku committed
2234
	}
2235

2236 2237
	if (DB_SUCCESS != row_drop_table_for_mysql_in_background(
		    drop->table_name)) {
osku's avatar
osku committed
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
		/* If the DROP fails for some table, we return, and let the
		main thread retry later */

		return(n_tables + n_tables_dropped);
	}

	n_tables_dropped++;

already_dropped:
	mutex_enter(&kernel_mutex);

	UT_LIST_REMOVE(row_mysql_drop_list, row_mysql_drop_list, drop);

2251
	ut_print_timestamp(stderr);
2252 2253 2254
	fputs("  InnoDB: Dropped table ", stderr);
	ut_print_name(stderr, NULL, TRUE, drop->table_name);
	fputs(" in background drop queue.\n", stderr);
osku's avatar
osku committed
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264

	mem_free(drop->table_name);

	mem_free(drop);

	mutex_exit(&kernel_mutex);

	goto loop;
}

2265
/*********************************************************************//**
osku's avatar
osku committed
2266
Get the background drop list length. NOTE: the caller must own the kernel
2267 2268
mutex!
@return	how many tables in list */
2269
UNIV_INTERN
osku's avatar
osku committed
2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
ulint
row_get_background_drop_list_len_low(void)
/*======================================*/
{
	ut_ad(mutex_own(&kernel_mutex));

	if (!row_mysql_drop_list_inited) {

		UT_LIST_INIT(row_mysql_drop_list);
		row_mysql_drop_list_inited = TRUE;
	}
2281

osku's avatar
osku committed
2282 2283 2284
	return(UT_LIST_GET_LEN(row_mysql_drop_list));
}

2285
/*********************************************************************//**
osku's avatar
osku committed
2286 2287 2288 2289
If a table is not yet in the drop list, adds the table to the list of tables
which the master thread drops in background. We need this on Unix because in
ALTER TABLE MySQL may call drop table even if the table has running queries on
it. Also, if there are running foreign key checks on the table, we drop the
2290 2291
table lazily.
@return	TRUE if the table was not yet in the drop list, and was added there */
osku's avatar
osku committed
2292 2293 2294 2295
static
ibool
row_add_table_to_background_drop_list(
/*==================================*/
2296
	const char*	name)	/*!< in: table name */
osku's avatar
osku committed
2297 2298
{
	row_mysql_drop_t*	drop;
2299

osku's avatar
osku committed
2300 2301 2302 2303 2304 2305 2306
	mutex_enter(&kernel_mutex);

	if (!row_mysql_drop_list_inited) {

		UT_LIST_INIT(row_mysql_drop_list);
		row_mysql_drop_list_inited = TRUE;
	}
2307

osku's avatar
osku committed
2308 2309 2310 2311
	/* Look if the table already is in the drop list */
	drop = UT_LIST_GET_FIRST(row_mysql_drop_list);

	while (drop != NULL) {
marko's avatar
marko committed
2312
		if (strcmp(drop->table_name, name) == 0) {
osku's avatar
osku committed
2313
			/* Already in the list */
2314

osku's avatar
osku committed
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
			mutex_exit(&kernel_mutex);

			return(FALSE);
		}

		drop = UT_LIST_GET_NEXT(row_mysql_drop_list, drop);
	}

	drop = mem_alloc(sizeof(row_mysql_drop_t));

marko's avatar
marko committed
2325
	drop->table_name = mem_strdup(name);
2326

osku's avatar
osku committed
2327
	UT_LIST_ADD_LAST(row_mysql_drop_list, row_mysql_drop_list, drop);
2328

2329
	/*	fputs("InnoDB: Adding table ", stderr);
2330
	ut_print_name(stderr, trx, TRUE, drop->table_name);
osku's avatar
osku committed
2331 2332 2333 2334 2335 2336 2337
	fputs(" to background drop list\n", stderr); */

	mutex_exit(&kernel_mutex);

	return(TRUE);
}

2338
/*********************************************************************//**
osku's avatar
osku committed
2339 2340
Discards the tablespace of a table which stored in an .ibd file. Discarding
means that this function deletes the .ibd file and assigns a new table id for
2341 2342
the table. Also the flag table->ibd_file_missing is set TRUE.
@return	error code or DB_SUCCESS */
2343
UNIV_INTERN
osku's avatar
osku committed
2344 2345 2346
int
row_discard_tablespace_for_mysql(
/*=============================*/
2347 2348
	const char*	name,	/*!< in: table name */
	trx_t*		trx)	/*!< in: transaction handle */
osku's avatar
osku committed
2349 2350
{
	dict_foreign_t*	foreign;
2351
	table_id_t	new_id;
osku's avatar
osku committed
2352 2353 2354
	dict_table_t*	table;
	ibool		success;
	ulint		err;
2355
	pars_info_t*	info = NULL;
osku's avatar
osku committed
2356

2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
	/* How do we prevent crashes caused by ongoing operations on
	the table? Old operations could try to access non-existent
	pages.

	1) SQL queries, INSERT, SELECT, ...: we must get an exclusive
	MySQL table lock on the table before we can do DISCARD
	TABLESPACE. Then there are no running queries on the table.

	2) Purge and rollback: we assign a new table id for the
	table. Since purge and rollback look for the table based on
	the table id, they see the table as 'dropped' and discard
	their operations.

	3) Insert buffer: we remove all entries for the tablespace in
	the insert buffer tree; as long as the tablespace mem object
	does not exist, ongoing insert buffer page merges are
	discarded in buf0rea.c. If we recreate the tablespace mem
	object with IMPORT TABLESPACE later, then the tablespace will
	have the same id, but the tablespace_version field in the mem
	object is different, and ongoing old insert buffer page merges
	get discarded.

	4) Linear readahead and random readahead: we use the same
	method as in 3) to discard ongoing operations.

	5) FOREIGN KEY operations: if
	table->n_foreign_key_checks_running > 0, we do not allow the
	discard. We also reserve the data dictionary latch. */
osku's avatar
osku committed
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403

	trx->op_info = "discarding tablespace";
	trx_start_if_not_started(trx);

	/* Serialize data dictionary operations with dictionary mutex:
	no deadlocks can occur then in these operations */

	row_mysql_lock_data_dictionary(trx);

	table = dict_table_get_low(name);

	if (!table) {
		err = DB_TABLE_NOT_FOUND;

		goto funct_exit;
	}

	if (table->space == 0) {
		ut_print_timestamp(stderr);
2404
		fputs("  InnoDB: Error: table ", stderr);
2405
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2406
		fputs("\n"
2407 2408
		      "InnoDB: is in the system tablespace 0"
		      " which cannot be discarded\n", stderr);
osku's avatar
osku committed
2409 2410 2411 2412 2413 2414 2415
		err = DB_ERROR;

		goto funct_exit;
	}

	if (table->n_foreign_key_checks_running > 0) {

2416
		ut_print_timestamp(stderr);
2417
		fputs("  InnoDB: You are trying to DISCARD table ", stderr);
2418
		ut_print_name(stderr, trx, TRUE, table->name);
osku's avatar
osku committed
2419
		fputs("\n"
2420 2421 2422 2423
		      "InnoDB: though there is a foreign key check"
		      " running on it.\n"
		      "InnoDB: Cannot discard the table.\n",
		      stderr);
osku's avatar
osku committed
2424 2425 2426 2427 2428 2429 2430 2431 2432 2433

		err = DB_ERROR;

		goto funct_exit;
	}

	/* Check if the table is referenced by foreign key constraints from
	some other table (not the table itself) */

	foreign = UT_LIST_GET_FIRST(table->referenced_list);
2434

osku's avatar
osku committed
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
	while (foreign && foreign->foreign_table == table) {
		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}

	if (foreign && trx->check_foreigns) {

		FILE*	ef	= dict_foreign_err_file;

		/* We only allow discarding a referenced table if
		FOREIGN_KEY_CHECKS is set to 0 */

		err = DB_CANNOT_DROP_CONSTRAINT;

		mutex_enter(&dict_foreign_err_mutex);
		rewind(ef);
		ut_print_timestamp(ef);

2452
		fputs("  Cannot DISCARD table ", ef);
2453
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2454
		fputs("\n"
2455
		      "because it is referenced by ", ef);
2456
		ut_print_name(stderr, trx, TRUE, foreign->foreign_table_name);
osku's avatar
osku committed
2457 2458 2459 2460 2461 2462
		putc('\n', ef);
		mutex_exit(&dict_foreign_err_mutex);

		goto funct_exit;
	}

2463
	dict_hdr_get_new_id(&new_id, NULL, NULL);
osku's avatar
osku committed
2464

2465 2466
	/* Remove all locks except the table-level S and X locks. */
	lock_remove_all_on_table(table, FALSE);
osku's avatar
osku committed
2467

2468
	info = pars_info_create();
osku's avatar
osku committed
2469

2470
	pars_info_add_str_literal(info, "table_name", name);
2471
	pars_info_add_ull_literal(info, "new_id", new_id);
osku's avatar
osku committed
2472

2473
	err = que_eval_sql(info,
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
			   "PROCEDURE DISCARD_TABLESPACE_PROC () IS\n"
			   "old_id CHAR;\n"
			   "BEGIN\n"
			   "SELECT ID INTO old_id\n"
			   "FROM SYS_TABLES\n"
			   "WHERE NAME = :table_name\n"
			   "LOCK IN SHARE MODE;\n"
			   "IF (SQL % NOTFOUND) THEN\n"
			   "       COMMIT WORK;\n"
			   "       RETURN;\n"
			   "END IF;\n"
			   "UPDATE SYS_TABLES SET ID = :new_id\n"
			   " WHERE ID = old_id;\n"
			   "UPDATE SYS_COLUMNS SET TABLE_ID = :new_id\n"
			   " WHERE TABLE_ID = old_id;\n"
			   "UPDATE SYS_INDEXES SET TABLE_ID = :new_id\n"
			   " WHERE TABLE_ID = old_id;\n"
			   "COMMIT WORK;\n"
			   "END;\n"
			   , FALSE, trx);
osku's avatar
osku committed
2494 2495 2496

	if (err != DB_SUCCESS) {
		trx->error_state = DB_SUCCESS;
2497
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
2498 2499 2500 2501 2502 2503 2504 2505
		trx->error_state = DB_SUCCESS;
	} else {
		dict_table_change_id_in_cache(table, new_id);

		success = fil_discard_tablespace(table->space);

		if (!success) {
			trx->error_state = DB_SUCCESS;
2506
			trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
			trx->error_state = DB_SUCCESS;

			err = DB_ERROR;
		} else {
			/* Set the flag which tells that now it is legal to
			IMPORT a tablespace for this table */
			table->tablespace_discarded = TRUE;
			table->ibd_file_missing = TRUE;
		}
	}
2517

2518 2519
funct_exit:
	trx_commit_for_mysql(trx);
osku's avatar
osku committed
2520

2521 2522
	row_mysql_unlock_data_dictionary(trx);

osku's avatar
osku committed
2523 2524 2525 2526 2527
	trx->op_info = "";

	return((int) err);
}

2528
/*****************************************************************//**
osku's avatar
osku committed
2529
Imports a tablespace. The space id in the .ibd file must match the space id
2530 2531
of the table in the data dictionary.
@return	error code or DB_SUCCESS */
2532
UNIV_INTERN
osku's avatar
osku committed
2533 2534 2535
int
row_import_tablespace_for_mysql(
/*============================*/
2536 2537
	const char*	name,	/*!< in: table name */
	trx_t*		trx)	/*!< in: transaction handle */
osku's avatar
osku committed
2538 2539 2540
{
	dict_table_t*	table;
	ibool		success;
2541
	ib_uint64_t	current_lsn;
osku's avatar
osku committed
2542 2543 2544 2545 2546 2547 2548
	ulint		err		= DB_SUCCESS;

	trx_start_if_not_started(trx);

	trx->op_info = "importing tablespace";

	current_lsn = log_get_lsn();
2549

osku's avatar
osku committed
2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
	/* It is possible, though very improbable, that the lsn's in the
	tablespace to be imported have risen above the current system lsn, if
	a lengthy purge, ibuf merge, or rollback was performed on a backup
	taken with ibbackup. If that is the case, reset page lsn's in the
	file. We assume that mysqld was shut down after it performed these
	cleanup operations on the .ibd file, so that it stamped the latest lsn
	to the FIL_PAGE_FILE_FLUSH_LSN in the first page of the .ibd file.

	TODO: reset also the trx id's in clustered index records and write
	a new space id to each data page. That would allow us to import clean
	.ibd files from another MySQL installation. */

	success = fil_reset_too_high_lsns(name, current_lsn);

	if (!success) {
		ut_print_timestamp(stderr);
2566
		fputs("  InnoDB: Error: cannot reset lsn's in table ", stderr);
2567
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2568
		fputs("\n"
2569 2570
		      "InnoDB: in ALTER TABLE ... IMPORT TABLESPACE\n",
		      stderr);
osku's avatar
osku committed
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587

		err = DB_ERROR;

		row_mysql_lock_data_dictionary(trx);

		goto funct_exit;
	}

	/* Serialize data dictionary operations with dictionary mutex:
	no deadlocks can occur then in these operations */

	row_mysql_lock_data_dictionary(trx);

	table = dict_table_get_low(name);

	if (!table) {
		ut_print_timestamp(stderr);
2588
		fputs("  InnoDB: table ", stderr);
2589
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2590
		fputs("\n"
2591 2592 2593
		      "InnoDB: does not exist in the InnoDB data dictionary\n"
		      "InnoDB: in ALTER TABLE ... IMPORT TABLESPACE\n",
		      stderr);
osku's avatar
osku committed
2594 2595 2596 2597 2598 2599 2600 2601

		err = DB_TABLE_NOT_FOUND;

		goto funct_exit;
	}

	if (table->space == 0) {
		ut_print_timestamp(stderr);
2602
		fputs("  InnoDB: Error: table ", stderr);
2603
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2604
		fputs("\n"
2605 2606
		      "InnoDB: is in the system tablespace 0"
		      " which cannot be imported\n", stderr);
osku's avatar
osku committed
2607 2608 2609 2610 2611 2612 2613
		err = DB_ERROR;

		goto funct_exit;
	}

	if (!table->tablespace_discarded) {
		ut_print_timestamp(stderr);
2614 2615 2616
		fputs("  InnoDB: Error: you are trying to"
		      " IMPORT a tablespace\n"
		      "InnoDB: ", stderr);
2617
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2618
		fputs(", though you have not called DISCARD on it yet\n"
2619 2620
		      "InnoDB: during the lifetime of the mysqld process!\n",
		      stderr);
osku's avatar
osku committed
2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631

		err = DB_ERROR;

		goto funct_exit;
	}

	/* Play safe and remove all insert buffer entries, though we should
	have removed them already when DISCARD TABLESPACE was called */

	ibuf_delete_for_discarded_space(table->space);

2632 2633 2634 2635
	success = fil_open_single_table_tablespace(
		TRUE, table->space,
		table->flags == DICT_TF_COMPACT ? 0 : table->flags,
		table->name);
osku's avatar
osku committed
2636 2637 2638 2639 2640 2641
	if (success) {
		table->ibd_file_missing = FALSE;
		table->tablespace_discarded = FALSE;
	} else {
		if (table->ibd_file_missing) {
			ut_print_timestamp(stderr);
2642 2643 2644
			fputs("  InnoDB: cannot find or open in the"
			      " database directory the .ibd file of\n"
			      "InnoDB: table ", stderr);
2645
			ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2646
			fputs("\n"
2647 2648
			      "InnoDB: in ALTER TABLE ... IMPORT TABLESPACE\n",
			      stderr);
osku's avatar
osku committed
2649 2650 2651 2652 2653
		}

		err = DB_ERROR;
	}

2654 2655
funct_exit:
	trx_commit_for_mysql(trx);
osku's avatar
osku committed
2656

2657 2658
	row_mysql_unlock_data_dictionary(trx);

osku's avatar
osku committed
2659 2660 2661 2662 2663
	trx->op_info = "";

	return((int) err);
}

2664
/*********************************************************************//**
2665 2666
Truncates a table for MySQL.
@return	error code or DB_SUCCESS */
2667
UNIV_INTERN
osku's avatar
osku committed
2668 2669 2670
int
row_truncate_table_for_mysql(
/*=========================*/
2671 2672
	dict_table_t*	table,	/*!< in: table handle */
	trx_t*		trx)	/*!< in: transaction handle */
osku's avatar
osku committed
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
{
	dict_foreign_t*	foreign;
	ulint		err;
	mem_heap_t*	heap;
	byte*		buf;
	dtuple_t*	tuple;
	dfield_t*	dfield;
	dict_index_t*	sys_index;
	btr_pcur_t	pcur;
	mtr_t		mtr;
2683
	table_id_t	new_id;
2684
	ulint		recreate_space = 0;
2685
	pars_info_t*	info = NULL;
osku's avatar
osku committed
2686

2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
	/* How do we prevent crashes caused by ongoing operations on
	the table? Old operations could try to access non-existent
	pages.

	1) SQL queries, INSERT, SELECT, ...: we must get an exclusive
	MySQL table lock on the table before we can do TRUNCATE
	TABLE. Then there are no running queries on the table. This is
	guaranteed, because in ha_innobase::store_lock(), we do not
	weaken the TL_WRITE lock requested by MySQL when executing
	SQLCOM_TRUNCATE.

	2) Purge and rollback: we assign a new table id for the
	table. Since purge and rollback look for the table based on
	the table id, they see the table as 'dropped' and discard
	their operations.

	3) Insert buffer: TRUNCATE TABLE is analogous to DROP TABLE,
	so we do not have to remove insert buffer records, as the
	insert buffer works at a low level. If a freed page is later
	reallocated, the allocator will remove the ibuf entries for
	it.

2709 2710 2711 2712 2713
	When we truncate *.ibd files by recreating them (analogous to
	DISCARD TABLESPACE), we remove all entries for the table in the
	insert buffer tree.  This is not strictly necessary, because
	in 6) we will assign a new tablespace identifier, but we can
	free up some space in the system tablespace.
2714 2715

	4) Linear readahead and random readahead: we use the same
2716 2717
	method as in 3) to discard ongoing operations. (This is only
	relevant for TRUNCATE TABLE by DISCARD TABLESPACE.)
2718 2719 2720

	5) FOREIGN KEY operations: if
	table->n_foreign_key_checks_running > 0, we do not allow the
2721 2722 2723 2724 2725
	TRUNCATE. We also reserve the data dictionary latch.

	6) Crash recovery: To prevent the application of pre-truncation
	redo log records on the truncated tablespace, we will assign
	a new tablespace identifier to the truncated tablespace. */
osku's avatar
osku committed
2726 2727 2728 2729

	ut_ad(table);

	if (srv_created_new_raw) {
2730 2731 2732 2733 2734
		fputs("InnoDB: A new raw disk partition was initialized:\n"
		      "InnoDB: we do not allow database modifications"
		      " by the user.\n"
		      "InnoDB: Shut down mysqld and edit my.cnf so that newraw"
		      " is replaced with raw.\n", stderr);
osku's avatar
osku committed
2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752

		return(DB_ERROR);
	}

	trx->op_info = "truncating table";

	trx_start_if_not_started(trx);

	/* Serialize data dictionary operations with dictionary mutex:
	no deadlocks can occur then in these operations */

	ut_a(trx->dict_operation_lock_mode == 0);
	/* Prevent foreign key checks etc. while we are truncating the
	table */

	row_mysql_lock_data_dictionary(trx);

	ut_ad(mutex_own(&(dict_sys->mutex)));
2753
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
#endif /* UNIV_SYNC_DEBUG */

	/* Check if the table is referenced by foreign key constraints from
	some other table (not the table itself) */

	foreign = UT_LIST_GET_FIRST(table->referenced_list);

	while (foreign && foreign->foreign_table == table) {
		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}

	if (foreign && trx->check_foreigns) {
		FILE*	ef	= dict_foreign_err_file;

		/* We only allow truncating a referenced table if
		FOREIGN_KEY_CHECKS is set to 0 */

		mutex_enter(&dict_foreign_err_mutex);
		rewind(ef);
		ut_print_timestamp(ef);

2776
		fputs("  Cannot truncate table ", ef);
2777
		ut_print_name(ef, trx, TRUE, table->name);
osku's avatar
osku committed
2778
		fputs(" by DROP+CREATE\n"
2779
		      "InnoDB: because it is referenced by ", ef);
2780
		ut_print_name(ef, trx, TRUE, foreign->foreign_table_name);
osku's avatar
osku committed
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795
		putc('\n', ef);
		mutex_exit(&dict_foreign_err_mutex);

		err = DB_ERROR;
		goto funct_exit;
	}

	/* TODO: could we replace the counter n_foreign_key_checks_running
	with lock checks on the table? Acquire here an exclusive lock on the
	table, and rewrite lock0lock.c and the lock wait in srv0srv.c so that
	they can cope with the table having been truncated here? Foreign key
	checks take an IS or IX lock on the table. */

	if (table->n_foreign_key_checks_running > 0) {
		ut_print_timestamp(stderr);
2796
		fputs("  InnoDB: Cannot truncate table ", stderr);
2797
		ut_print_name(stderr, trx, TRUE, table->name);
osku's avatar
osku committed
2798
		fputs(" by DROP+CREATE\n"
2799 2800 2801
		      "InnoDB: because there is a foreign key check"
		      " running on it.\n",
		      stderr);
osku's avatar
osku committed
2802 2803 2804 2805 2806
		err = DB_ERROR;

		goto funct_exit;
	}

2807 2808
	/* Remove all locks except the table-level S and X locks. */
	lock_remove_all_on_table(table, FALSE);
osku's avatar
osku committed
2809 2810 2811

	trx->table_id = table->id;

2812 2813 2814
	if (table->space && !table->dir_path_of_temp_table) {
		/* Discard and create the single-table tablespace. */
		ulint	space	= table->space;
2815
		ulint	flags	= fil_space_get_flags(space);
2816

2817
		if (flags != ULINT_UNDEFINED
2818 2819 2820 2821
		    && fil_discard_tablespace(space)) {

			dict_index_t*	index;

2822
			dict_hdr_get_new_id(NULL, NULL, &space);
2823

2824 2825 2826 2827 2828
			/* Lock all index trees for this table. We must
			do so after dict_hdr_get_new_id() to preserve
			the latch order */
			dict_table_x_lock_indexes(table);

2829 2830 2831
			if (space == ULINT_UNDEFINED
			    || fil_create_new_single_table_tablespace(
				    space, table->name, FALSE, flags,
2832
				    FIL_IBD_FILE_INITIAL_SIZE) != DB_SUCCESS) {
2833
				dict_table_x_unlock_indexes(table);
2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
				ut_print_timestamp(stderr);
				fprintf(stderr,
					"  InnoDB: TRUNCATE TABLE %s failed to"
					" create a new tablespace\n",
					table->name);
				table->ibd_file_missing = 1;
				err = DB_ERROR;
				goto funct_exit;
			}

			recreate_space = space;

			/* Replace the space_id in the data dictionary cache.
			The persisent data dictionary (SYS_TABLES.SPACE
			and SYS_INDEXES.SPACE) are updated later in this
			function. */
			table->space = space;
			index = dict_table_get_first_index(table);
			do {
				index->space = space;
				index = dict_table_get_next_index(index);
			} while (index);

			mtr_start(&mtr);
			fsp_header_init(space,
					FIL_IBD_FILE_INITIAL_SIZE, &mtr);
			mtr_commit(&mtr);
		}
2862 2863 2864 2865 2866 2867 2868 2869 2870
	} else {
		/* Lock all index trees for this table, as we will
		truncate the table/index and possibly change their metadata.
		All DML/DDL are blocked by table level lock, with
		a few exceptions such as queries into information schema
		about the table, MySQL could try to access index stats
		for this kind of query, we need to use index locks to
		sync up */
		dict_table_x_lock_indexes(table);
2871 2872
	}

osku's avatar
osku committed
2873 2874 2875 2876
	/* scan SYS_INDEXES for all indexes of the table */
	heap = mem_heap_create(800);

	tuple = dtuple_create(heap, 1);
2877
	dfield = dtuple_get_nth_field(tuple, 0);
osku's avatar
osku committed
2878 2879 2880 2881 2882 2883 2884 2885 2886 2887

	buf = mem_heap_alloc(heap, 8);
	mach_write_to_8(buf, table->id);

	dfield_set_data(dfield, buf, 8);
	sys_index = dict_table_get_first_index(dict_sys->sys_indexes);
	dict_index_copy_types(tuple, sys_index, 1);

	mtr_start(&mtr);
	btr_pcur_open_on_user_rec(sys_index, tuple, PAGE_CUR_GE,
2888
				  BTR_MODIFY_LEAF, &pcur, &mtr);
osku's avatar
osku committed
2889 2890 2891 2892 2893 2894
	for (;;) {
		rec_t*		rec;
		const byte*	field;
		ulint		len;
		ulint		root_page_no;

2895
		if (!btr_pcur_is_on_user_rec(&pcur)) {
osku's avatar
osku committed
2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914
			/* The end of SYS_INDEXES has been reached. */
			break;
		}

		rec = btr_pcur_get_rec(&pcur);

		field = rec_get_nth_field_old(rec, 0, &len);
		ut_ad(len == 8);

		if (memcmp(buf, field, len) != 0) {
			/* End of indexes for the table (TABLE_ID mismatch). */
			break;
		}

		if (rec_get_deleted_flag(rec, FALSE)) {
			/* The index has been dropped. */
			goto next_rec;
		}

marko's avatar
marko committed
2915 2916
		/* This call may commit and restart mtr
		and reposition pcur. */
2917 2918
		root_page_no = dict_truncate_index_tree(table, recreate_space,
							&pcur, &mtr);
osku's avatar
osku committed
2919 2920 2921 2922

		rec = btr_pcur_get_rec(&pcur);

		if (root_page_no != FIL_NULL) {
2923
			page_rec_write_field(
2924 2925
				rec, DICT_SYS_INDEXES_PAGE_NO_FIELD,
				root_page_no, &mtr);
osku's avatar
osku committed
2926 2927 2928 2929 2930 2931 2932 2933
			/* We will need to commit and restart the
			mini-transaction in order to avoid deadlocks.
			The dict_truncate_index_tree() call has allocated
			a page in this mini-transaction, and the rest of
			this loop could latch another index page. */
			mtr_commit(&mtr);
			mtr_start(&mtr);
			btr_pcur_restore_position(BTR_MODIFY_LEAF,
2934
						  &pcur, &mtr);
osku's avatar
osku committed
2935 2936
		}

2937
next_rec:
osku's avatar
osku committed
2938 2939 2940 2941 2942 2943 2944 2945
		btr_pcur_move_to_next_user_rec(&pcur, &mtr);
	}

	btr_pcur_close(&pcur);
	mtr_commit(&mtr);

	mem_heap_free(heap);

2946 2947 2948 2949
	/* Done with index truncation, release index tree locks,
	subsequent work relates to table level metadata change */
	dict_table_x_unlock_indexes(table);

2950
	dict_hdr_get_new_id(&new_id, NULL, NULL);
osku's avatar
osku committed
2951

2952
	info = pars_info_create();
osku's avatar
osku committed
2953

2954
	pars_info_add_int4_literal(info, "space", (lint) table->space);
2955 2956
	pars_info_add_ull_literal(info, "old_id", table->id);
	pars_info_add_ull_literal(info, "new_id", new_id);
osku's avatar
osku committed
2957

2958
	err = que_eval_sql(info,
2959 2960
			   "PROCEDURE RENUMBER_TABLESPACE_PROC () IS\n"
			   "BEGIN\n"
2961 2962
			   "UPDATE SYS_TABLES"
			   " SET ID = :new_id, SPACE = :space\n"
2963 2964 2965
			   " WHERE ID = :old_id;\n"
			   "UPDATE SYS_COLUMNS SET TABLE_ID = :new_id\n"
			   " WHERE TABLE_ID = :old_id;\n"
2966 2967
			   "UPDATE SYS_INDEXES"
			   " SET TABLE_ID = :new_id, SPACE = :space\n"
2968 2969 2970 2971
			   " WHERE TABLE_ID = :old_id;\n"
			   "COMMIT WORK;\n"
			   "END;\n"
			   , FALSE, trx);
osku's avatar
osku committed
2972 2973 2974

	if (err != DB_SUCCESS) {
		trx->error_state = DB_SUCCESS;
2975
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
2976 2977
		trx->error_state = DB_SUCCESS;
		ut_print_timestamp(stderr);
2978 2979
		fputs("  InnoDB: Unable to assign a new identifier to table ",
		      stderr);
2980
		ut_print_name(stderr, trx, TRUE, table->name);
osku's avatar
osku committed
2981
		fputs("\n"
2982 2983
		      "InnoDB: after truncating it.  Background processes"
		      " may corrupt the table!\n", stderr);
osku's avatar
osku committed
2984 2985 2986 2987 2988
		err = DB_ERROR;
	} else {
		dict_table_change_id_in_cache(table, new_id);
	}

2989
	/* Reset auto-increment. */
2990
	dict_table_autoinc_lock(table);
2991
	dict_table_autoinc_initialize(table, 1);
2992
	dict_table_autoinc_unlock(table);
2993 2994
	dict_update_statistics(table, FALSE /* update even if stats are
					    initialized */);
osku's avatar
osku committed
2995

2996
	trx_commit_for_mysql(trx);
osku's avatar
osku committed
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008

funct_exit:

	row_mysql_unlock_data_dictionary(trx);

	trx->op_info = "";

	srv_wake_master_thread();

	return((int) err);
}

3009
/*********************************************************************//**
3010
Drops a table for MySQL.  If the name of the dropped table ends in
3011 3012
one of "innodb_monitor", "innodb_lock_monitor", "innodb_tablespace_monitor",
"innodb_table_monitor", then this will also stop the printing of monitor
3013 3014
output by the master thread.  If the data dictionary was not already locked
by the transaction, the transaction will be committed.  Otherwise, the
3015 3016
data dictionary will remain locked.
@return	error code or DB_SUCCESS */
3017
UNIV_INTERN
osku's avatar
osku committed
3018 3019 3020
int
row_drop_table_for_mysql(
/*=====================*/
3021 3022 3023
	const char*	name,	/*!< in: table name */
	trx_t*		trx,	/*!< in: transaction handle */
	ibool		drop_db)/*!< in: TRUE=dropping whole database */
osku's avatar
osku committed
3024 3025 3026 3027 3028 3029 3030 3031
{
	dict_foreign_t*	foreign;
	dict_table_t*	table;
	ulint		space_id;
	ulint		err;
	const char*	table_name;
	ulint		namelen;
	ibool		locked_dictionary	= FALSE;
3032
	pars_info_t*    info			= NULL;
osku's avatar
osku committed
3033 3034 3035 3036

	ut_a(name != NULL);

	if (srv_created_new_raw) {
3037 3038 3039 3040 3041
		fputs("InnoDB: A new raw disk partition was initialized:\n"
		      "InnoDB: we do not allow database modifications"
		      " by the user.\n"
		      "InnoDB: Shut down mysqld and edit my.cnf so that newraw"
		      " is replaced with raw.\n", stderr);
osku's avatar
osku committed
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059

		return(DB_ERROR);
	}

	trx->op_info = "dropping table";

	trx_start_if_not_started(trx);

	/* The table name is prefixed with the database name and a '/'.
	Certain table names starting with 'innodb_' have their special
	meaning regardless of the database name.  Thus, we need to
	ignore the database name prefix in the comparisons. */
	table_name = strchr(name, '/');
	ut_a(table_name);
	table_name++;
	namelen = strlen(table_name) + 1;

	if (namelen == sizeof S_innodb_monitor
3060 3061
	    && !memcmp(table_name, S_innodb_monitor,
		       sizeof S_innodb_monitor)) {
osku's avatar
osku committed
3062 3063 3064

		/* Table name equals "innodb_monitor":
		stop monitor prints */
3065

osku's avatar
osku committed
3066 3067 3068
		srv_print_innodb_monitor = FALSE;
		srv_print_innodb_lock_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_lock_monitor
3069 3070
		   && !memcmp(table_name, S_innodb_lock_monitor,
			      sizeof S_innodb_lock_monitor)) {
osku's avatar
osku committed
3071 3072 3073
		srv_print_innodb_monitor = FALSE;
		srv_print_innodb_lock_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_tablespace_monitor
3074 3075
		   && !memcmp(table_name, S_innodb_tablespace_monitor,
			      sizeof S_innodb_tablespace_monitor)) {
osku's avatar
osku committed
3076 3077 3078

		srv_print_innodb_tablespace_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_table_monitor
3079 3080
		   && !memcmp(table_name, S_innodb_table_monitor,
			      sizeof S_innodb_table_monitor)) {
osku's avatar
osku committed
3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097

		srv_print_innodb_table_monitor = FALSE;
	}

	/* Serialize data dictionary operations with dictionary mutex:
	no deadlocks can occur then in these operations */

	if (trx->dict_operation_lock_mode != RW_X_LATCH) {
		/* Prevent foreign key checks etc. while we are dropping the
		table */

		row_mysql_lock_data_dictionary(trx);

		locked_dictionary = TRUE;
	}

	ut_ad(mutex_own(&(dict_sys->mutex)));
3098
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
3099 3100
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
#endif /* UNIV_SYNC_DEBUG */
3101

3102 3103
	table = dict_table_get_low_ignore_err(
		name, DICT_ERR_IGNORE_INDEX_ROOT | DICT_ERR_IGNORE_CORRUPT);
osku's avatar
osku committed
3104 3105 3106

	if (!table) {
		err = DB_TABLE_NOT_FOUND;
3107
		ut_print_timestamp(stderr);
osku's avatar
osku committed
3108

3109
		fputs("  InnoDB: Error: table ", stderr);
3110
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3111
		fputs(" does not exist in the InnoDB internal\n"
3112 3113 3114 3115 3116 3117 3118
		      "InnoDB: data dictionary though MySQL is"
		      " trying to drop it.\n"
		      "InnoDB: Have you copied the .frm file"
		      " of the table to the\n"
		      "InnoDB: MySQL database directory"
		      " from another database?\n"
		      "InnoDB: You can look for further help from\n"
3119
		      "InnoDB: " REFMAN "innodb-troubleshooting.html\n",
3120
		      stderr);
osku's avatar
osku committed
3121 3122 3123 3124 3125 3126 3127
		goto funct_exit;
	}

	/* Check if the table is referenced by foreign key constraints from
	some other table (not the table itself) */

	foreign = UT_LIST_GET_FIRST(table->referenced_list);
3128

osku's avatar
osku committed
3129
	while (foreign && foreign->foreign_table == table) {
3130
check_next_foreign:
osku's avatar
osku committed
3131 3132 3133
		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}

3134
	if (foreign && trx->check_foreigns
3135
	    && !(drop_db && dict_tables_have_same_db(
3136
			 name, foreign->foreign_table_name_lookup))) {
osku's avatar
osku committed
3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147
		FILE*	ef	= dict_foreign_err_file;

		/* We only allow dropping a referenced table if
		FOREIGN_KEY_CHECKS is set to 0 */

		err = DB_CANNOT_DROP_CONSTRAINT;

		mutex_enter(&dict_foreign_err_mutex);
		rewind(ef);
		ut_print_timestamp(ef);

3148
		fputs("  Cannot drop table ", ef);
3149
		ut_print_name(ef, trx, TRUE, name);
osku's avatar
osku committed
3150
		fputs("\n"
3151
		      "because it is referenced by ", ef);
3152
		ut_print_name(ef, trx, TRUE, foreign->foreign_table_name);
osku's avatar
osku committed
3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
		putc('\n', ef);
		mutex_exit(&dict_foreign_err_mutex);

		goto funct_exit;
	}

	if (foreign && trx->check_foreigns) {
		goto check_next_foreign;
	}

	if (table->n_mysql_handles_opened > 0) {
		ibool	added;

marko's avatar
marko committed
3166
		added = row_add_table_to_background_drop_list(table->name);
osku's avatar
osku committed
3167

3168
		if (added) {
3169 3170 3171 3172 3173 3174 3175 3176 3177 3178
			ut_print_timestamp(stderr);
			fputs("  InnoDB: Warning: MySQL is"
			      " trying to drop table ", stderr);
			ut_print_name(stderr, trx, TRUE, table->name);
			fputs("\n"
			      "InnoDB: though there are still"
			      " open handles to it.\n"
			      "InnoDB: Adding the table to the"
			      " background drop queue.\n",
			      stderr);
3179

osku's avatar
osku committed
3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198
			/* We return DB_SUCCESS to MySQL though the drop will
			happen lazily later */
			err = DB_SUCCESS;
		} else {
			/* The table is already in the background drop list */
			err = DB_ERROR;
		}

		goto funct_exit;
	}

	/* TODO: could we replace the counter n_foreign_key_checks_running
	with lock checks on the table? Acquire here an exclusive lock on the
	table, and rewrite lock0lock.c and the lock wait in srv0srv.c so that
	they can cope with the table having been dropped here? Foreign key
	checks take an IS or IX lock on the table. */

	if (table->n_foreign_key_checks_running > 0) {

marko's avatar
marko committed
3199 3200
		const char*	table_name = table->name;
		ibool		added;
osku's avatar
osku committed
3201

marko's avatar
marko committed
3202
		added = row_add_table_to_background_drop_list(table_name);
osku's avatar
osku committed
3203 3204

		if (added) {
3205
			ut_print_timestamp(stderr);
3206 3207
			fputs("  InnoDB: You are trying to drop table ",
			      stderr);
marko's avatar
marko committed
3208
			ut_print_name(stderr, trx, TRUE, table_name);
osku's avatar
osku committed
3209
			fputs("\n"
3210 3211 3212 3213 3214
			      "InnoDB: though there is a"
			      " foreign key check running on it.\n"
			      "InnoDB: Adding the table to"
			      " the background drop queue.\n",
			      stderr);
osku's avatar
osku committed
3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226

			/* We return DB_SUCCESS to MySQL though the drop will
			happen lazily later */

			err = DB_SUCCESS;
		} else {
			/* The table is already in the background drop list */
			err = DB_ERROR;
		}

		goto funct_exit;
	}
3227

3228 3229
	/* Remove all locks there are on the table or its records */
	lock_remove_all_on_table(table, TRUE);
osku's avatar
osku committed
3230

3231
	trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
osku's avatar
osku committed
3232 3233
	trx->table_id = table->id;

3234 3235 3236 3237
	/* We use the private SQL parser of Innobase to generate the
	query graphs needed in deleting the dictionary data from system
	tables in Innobase. Deleting a row from SYS_INDEXES table also
	frees the file segments of the B-tree associated with the index. */
osku's avatar
osku committed
3238

3239
	info = pars_info_create();
osku's avatar
osku committed
3240

3241 3242 3243
	pars_info_add_str_literal(info, "table_name", name);

	err = que_eval_sql(info,
3244 3245 3246 3247 3248 3249
			   "PROCEDURE DROP_TABLE_PROC () IS\n"
			   "sys_foreign_id CHAR;\n"
			   "table_id CHAR;\n"
			   "index_id CHAR;\n"
			   "foreign_id CHAR;\n"
			   "found INT;\n"
Vasil Dimov's avatar
Vasil Dimov committed
3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262

			   "DECLARE CURSOR cur_fk IS\n"
			   "SELECT ID FROM SYS_FOREIGN\n"
			   "WHERE FOR_NAME = :table_name\n"
			   "AND TO_BINARY(FOR_NAME)\n"
			   "  = TO_BINARY(:table_name)\n"
			   "LOCK IN SHARE MODE;\n"

			   "DECLARE CURSOR cur_idx IS\n"
			   "SELECT ID FROM SYS_INDEXES\n"
			   "WHERE TABLE_ID = table_id\n"
			   "LOCK IN SHARE MODE;\n"

3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
			   "BEGIN\n"
			   "SELECT ID INTO table_id\n"
			   "FROM SYS_TABLES\n"
			   "WHERE NAME = :table_name\n"
			   "LOCK IN SHARE MODE;\n"
			   "IF (SQL % NOTFOUND) THEN\n"
			   "       RETURN;\n"
			   "END IF;\n"
			   "found := 1;\n"
			   "SELECT ID INTO sys_foreign_id\n"
			   "FROM SYS_TABLES\n"
			   "WHERE NAME = 'SYS_FOREIGN'\n"
			   "LOCK IN SHARE MODE;\n"
			   "IF (SQL % NOTFOUND) THEN\n"
			   "       found := 0;\n"
			   "END IF;\n"
			   "IF (:table_name = 'SYS_FOREIGN') THEN\n"
			   "       found := 0;\n"
			   "END IF;\n"
			   "IF (:table_name = 'SYS_FOREIGN_COLS') THEN\n"
			   "       found := 0;\n"
			   "END IF;\n"
Vasil Dimov's avatar
Vasil Dimov committed
3285
			   "OPEN cur_fk;\n"
3286
			   "WHILE found = 1 LOOP\n"
Vasil Dimov's avatar
Vasil Dimov committed
3287
			   "       FETCH cur_fk INTO foreign_id;\n"
3288 3289 3290 3291 3292 3293 3294 3295 3296
			   "       IF (SQL % NOTFOUND) THEN\n"
			   "               found := 0;\n"
			   "       ELSE\n"
			   "               DELETE FROM SYS_FOREIGN_COLS\n"
			   "               WHERE ID = foreign_id;\n"
			   "               DELETE FROM SYS_FOREIGN\n"
			   "               WHERE ID = foreign_id;\n"
			   "       END IF;\n"
			   "END LOOP;\n"
Vasil Dimov's avatar
Vasil Dimov committed
3297
			   "CLOSE cur_fk;\n"
3298
			   "found := 1;\n"
Vasil Dimov's avatar
Vasil Dimov committed
3299
			   "OPEN cur_idx;\n"
3300
			   "WHILE found = 1 LOOP\n"
Vasil Dimov's avatar
Vasil Dimov committed
3301
			   "       FETCH cur_idx INTO index_id;\n"
3302 3303 3304 3305 3306 3307 3308 3309 3310 3311
			   "       IF (SQL % NOTFOUND) THEN\n"
			   "               found := 0;\n"
			   "       ELSE\n"
			   "               DELETE FROM SYS_FIELDS\n"
			   "               WHERE INDEX_ID = index_id;\n"
			   "               DELETE FROM SYS_INDEXES\n"
			   "               WHERE ID = index_id\n"
			   "               AND TABLE_ID = table_id;\n"
			   "       END IF;\n"
			   "END LOOP;\n"
Vasil Dimov's avatar
Vasil Dimov committed
3312
			   "CLOSE cur_idx;\n"
3313 3314 3315 3316 3317 3318
			   "DELETE FROM SYS_COLUMNS\n"
			   "WHERE TABLE_ID = table_id;\n"
			   "DELETE FROM SYS_TABLES\n"
			   "WHERE ID = table_id;\n"
			   "END;\n"
			   , FALSE, trx);
osku's avatar
osku committed
3319

3320
	switch (err) {
3321
		ibool		is_temp;
osku's avatar
osku committed
3322
		const char*	name_or_path;
3323
		mem_heap_t*	heap;
osku's avatar
osku committed
3324

3325 3326
	case DB_SUCCESS:

3327 3328 3329 3330 3331 3332
		heap = mem_heap_create(200);

		/* Clone the name, in case it has been allocated
		from table->heap, which will be freed by
		dict_table_remove_from_cache(table) below. */
		name = mem_heap_strdup(heap, name);
osku's avatar
osku committed
3333
		space_id = table->space;
3334

osku's avatar
osku committed
3335
		if (table->dir_path_of_temp_table != NULL) {
3336 3337
			name_or_path = mem_heap_strdup(
				heap, table->dir_path_of_temp_table);
3338
			is_temp = TRUE;
osku's avatar
osku committed
3339 3340
		} else {
			name_or_path = name;
3341 3342
			is_temp = (table->flags >> DICT_TF2_SHIFT)
				& DICT_TF2_TEMPORARY;
osku's avatar
osku committed
3343 3344 3345 3346
		}

		dict_table_remove_from_cache(table);

3347
		if (dict_load_table(name, TRUE, DICT_ERR_IGNORE_NONE) != NULL) {
osku's avatar
osku committed
3348
			ut_print_timestamp(stderr);
3349
			fputs("  InnoDB: Error: not able to remove table ",
3350
			      stderr);
3351
			ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3352 3353 3354 3355 3356 3357 3358 3359 3360
			fputs(" from the dictionary cache!\n", stderr);
			err = DB_ERROR;
		}

		/* Do not drop possible .ibd tablespace if something went
		wrong: we do not want to delete valuable data of the user */

		if (err == DB_SUCCESS && space_id > 0) {
			if (!fil_space_for_table_exists_in_mem(space_id,
3361
							       name_or_path,
3362 3363
							       is_temp, FALSE,
							       !is_temp)) {
osku's avatar
osku committed
3364 3365 3366
				err = DB_SUCCESS;

				fprintf(stderr,
3367 3368 3369
					"InnoDB: We removed now the InnoDB"
					" internal data dictionary entry\n"
					"InnoDB: of table ");
3370
				ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3371
				fprintf(stderr, ".\n");
3372
			} else if (!fil_delete_tablespace(space_id)) {
osku's avatar
osku committed
3373
				fprintf(stderr,
3374 3375 3376
					"InnoDB: We removed now the InnoDB"
					" internal data dictionary entry\n"
					"InnoDB: of table ");
3377
				ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3378 3379 3380 3381
				fprintf(stderr, ".\n");

				ut_print_timestamp(stderr);
				fprintf(stderr,
3382 3383
					"  InnoDB: Error: not able to"
					" delete tablespace %lu of table ",
osku's avatar
osku committed
3384
					(ulong) space_id);
3385
				ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3386 3387 3388 3389
				fputs("!\n", stderr);
				err = DB_ERROR;
			}
		}
3390 3391

		mem_heap_free(heap);
3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410
		break;

	case DB_TOO_MANY_CONCURRENT_TRXS:
		/* Cannot even find a free slot for the
		the undo log. We can directly exit here
		and return the DB_TOO_MANY_CONCURRENT_TRXS
		error. */
		break;

	case DB_OUT_OF_FILE_SPACE:
		err = DB_MUST_GET_MORE_FILE_SPACE;

		row_mysql_handle_errors(&err, trx, NULL, NULL);

		/* Fall through to raise error */

	default:
		/* No other possible error returns */
		ut_error;
osku's avatar
osku committed
3411
	}
3412

osku's avatar
osku committed
3413 3414 3415
funct_exit:

	if (locked_dictionary) {
3416 3417
		trx_commit_for_mysql(trx);

3418
		row_mysql_unlock_data_dictionary(trx);
osku's avatar
osku committed
3419 3420 3421 3422 3423 3424 3425 3426 3427
	}

	trx->op_info = "";

	srv_wake_master_thread();

	return((int) err);
}

3428 3429 3430 3431 3432 3433 3434
/*********************************************************************//**
Drop all temporary tables during crash recovery. */
UNIV_INTERN
void
row_mysql_drop_temp_tables(void)
/*============================*/
{
3435 3436 3437 3438
	trx_t*		trx;
	btr_pcur_t	pcur;
	mtr_t		mtr;
	mem_heap_t*	heap;
3439 3440 3441 3442 3443

	trx = trx_allocate_for_background();
	trx->op_info = "dropping temporary tables";
	row_mysql_lock_data_dictionary(trx);

3444
	heap = mem_heap_create(200);
3445

3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492
	mtr_start(&mtr);

	btr_pcur_open_at_index_side(
		TRUE,
		dict_table_get_first_index(dict_sys->sys_tables),
		BTR_SEARCH_LEAF, &pcur, TRUE, &mtr);

	for (;;) {
		const rec_t*	rec;
		const byte*	field;
		ulint		len;
		const char*	table_name;
		dict_table_t*	table;

		btr_pcur_move_to_next_user_rec(&pcur, &mtr);

		if (!btr_pcur_is_on_user_rec(&pcur)) {
			break;
		}

		rec = btr_pcur_get_rec(&pcur);
		field = rec_get_nth_field_old(rec, 4/*N_COLS*/, &len);
		if (len != 4 || !(mach_read_from_4(field) & 0x80000000UL)) {
			continue;
		}

		/* Because this is not a ROW_FORMAT=REDUNDANT table,
		the is_temp flag is valid.  Examine it. */

		field = rec_get_nth_field_old(rec, 7/*MIX_LEN*/, &len);
		if (len != 4
		    || !(mach_read_from_4(field) & DICT_TF2_TEMPORARY)) {
			continue;
		}

		/* This is a temporary table. */
		field = rec_get_nth_field_old(rec, 0/*NAME*/, &len);
		if (len == UNIV_SQL_NULL || len == 0) {
			/* Corrupted SYS_TABLES.NAME */
			continue;
		}

		table_name = mem_heap_strdupl(heap, (const char*) field, len);

		btr_pcur_store_position(&pcur, &mtr);
		btr_pcur_commit_specify_mtr(&pcur, &mtr);

3493
		table = dict_load_table(table_name, TRUE, DICT_ERR_IGNORE_NONE);
3494 3495 3496 3497 3498 3499 3500 3501 3502

		if (table) {
			row_drop_table_for_mysql(table_name, trx, FALSE);
			trx_commit_for_mysql(trx);
		}

		mtr_start(&mtr);
		btr_pcur_restore_position(BTR_SEARCH_LEAF,
					  &pcur, &mtr);
3503 3504
	}

3505 3506 3507
	btr_pcur_close(&pcur);
	mtr_commit(&mtr);
	mem_heap_free(heap);
3508 3509 3510 3511
	row_mysql_unlock_data_dictionary(trx);
	trx_free_for_background(trx);
}

3512
/*******************************************************************//**
3513
Drop all foreign keys in a database, see Bug#18942.
3514 3515
Called at the end of row_drop_database_for_mysql().
@return	error code or DB_SUCCESS */
3516 3517 3518 3519
static
ulint
drop_all_foreign_keys_in_db(
/*========================*/
3520 3521
	const char*	name,	/*!< in: database name which ends to '/' */
	trx_t*		trx)	/*!< in: transaction handle */
3522 3523 3524 3525 3526 3527 3528 3529 3530 3531
{
	pars_info_t*	pinfo;
	ulint		err;

	ut_a(name[strlen(name) - 1] == '/');

	pinfo = pars_info_create();

	pars_info_add_str_literal(pinfo, "dbname", name);

3532
/** true if for_name is not prefixed with dbname */
3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571
#define TABLE_NOT_IN_THIS_DB \
"SUBSTR(for_name, 0, LENGTH(:dbname)) <> :dbname"

	err = que_eval_sql(pinfo,
			   "PROCEDURE DROP_ALL_FOREIGN_KEYS_PROC () IS\n"
			   "foreign_id CHAR;\n"
			   "for_name CHAR;\n"
			   "found INT;\n"
			   "DECLARE CURSOR cur IS\n"
			   "SELECT ID, FOR_NAME FROM SYS_FOREIGN\n"
			   "WHERE FOR_NAME >= :dbname\n"
			   "LOCK IN SHARE MODE\n"
			   "ORDER BY FOR_NAME;\n"
			   "BEGIN\n"
			   "found := 1;\n"
			   "OPEN cur;\n"
			   "WHILE found = 1 LOOP\n"
			   "        FETCH cur INTO foreign_id, for_name;\n"
			   "        IF (SQL % NOTFOUND) THEN\n"
			   "                found := 0;\n"
			   "        ELSIF (" TABLE_NOT_IN_THIS_DB ") THEN\n"
			   "                found := 0;\n"
			   "        ELSIF (1=1) THEN\n"
			   "                DELETE FROM SYS_FOREIGN_COLS\n"
			   "                WHERE ID = foreign_id;\n"
			   "                DELETE FROM SYS_FOREIGN\n"
			   "                WHERE ID = foreign_id;\n"
			   "        END IF;\n"
			   "END LOOP;\n"
			   "CLOSE cur;\n"
			   "COMMIT WORK;\n"
			   "END;\n",
			   FALSE, /* do not reserve dict mutex,
				  we are already holding it */
			   trx);

	return(err);
}

3572
/*********************************************************************//**
3573 3574
Drops a database for MySQL.
@return	error code or DB_SUCCESS */
3575
UNIV_INTERN
osku's avatar
osku committed
3576 3577 3578
int
row_drop_database_for_mysql(
/*========================*/
3579 3580
	const char*	name,	/*!< in: database name which ends to '/' */
	trx_t*		trx)	/*!< in: transaction handle */
osku's avatar
osku committed
3581
{
3582
	dict_table_t* table;
osku's avatar
osku committed
3583 3584 3585
	char*	table_name;
	int	err	= DB_SUCCESS;
	ulint	namelen	= strlen(name);
3586

osku's avatar
osku committed
3587 3588
	ut_a(name != NULL);
	ut_a(name[namelen - 1] == '/');
3589

osku's avatar
osku committed
3590
	trx->op_info = "dropping database";
3591

osku's avatar
osku committed
3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609
	trx_start_if_not_started(trx);
loop:
	row_mysql_lock_data_dictionary(trx);

	while ((table_name = dict_get_first_table_name_in_db(name))) {
		ut_a(memcmp(table_name, name, namelen) == 0);

		table = dict_table_get_low(table_name);

		ut_a(table);

		/* Wait until MySQL does not have any queries running on
		the table */

		if (table->n_mysql_handles_opened > 0) {
			row_mysql_unlock_data_dictionary(trx);

			ut_print_timestamp(stderr);
3610 3611
			fputs("  InnoDB: Warning: MySQL is trying to"
			      " drop database ", stderr);
3612
			ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3613
			fputs("\n"
3614 3615
			      "InnoDB: though there are still"
			      " open handles to table ", stderr);
3616
			ut_print_name(stderr, trx, TRUE, table_name);
osku's avatar
osku committed
3617 3618
			fputs(".\n", stderr);

3619
			os_thread_sleep(1000000);
osku's avatar
osku committed
3620

3621
			mem_free(table_name);
osku's avatar
osku committed
3622

3623
			goto loop;
osku's avatar
osku committed
3624 3625 3626
		}

		err = row_drop_table_for_mysql(table_name, trx, TRUE);
3627
		trx_commit_for_mysql(trx);
osku's avatar
osku committed
3628 3629 3630

		if (err != DB_SUCCESS) {
			fputs("InnoDB: DROP DATABASE ", stderr);
3631
			ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3632 3633
			fprintf(stderr, " failed with error %lu for table ",
				(ulint) err);
3634
			ut_print_name(stderr, trx, TRUE, table_name);
osku's avatar
osku committed
3635
			putc('\n', stderr);
3636
			mem_free(table_name);
osku's avatar
osku committed
3637 3638
			break;
		}
3639 3640

		mem_free(table_name);
osku's avatar
osku committed
3641 3642
	}

3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655
	if (err == DB_SUCCESS) {
		/* after dropping all tables try to drop all leftover
		foreign keys in case orphaned ones exist */
		err = (int) drop_all_foreign_keys_in_db(name, trx);

		if (err != DB_SUCCESS) {
			fputs("InnoDB: DROP DATABASE ", stderr);
			ut_print_name(stderr, trx, TRUE, name);
			fprintf(stderr, " failed with error %d while "
				"dropping all foreign keys", err);
		}
	}

osku's avatar
osku committed
3656 3657
	trx_commit_for_mysql(trx);

3658 3659
	row_mysql_unlock_data_dictionary(trx);

osku's avatar
osku committed
3660 3661 3662 3663 3664
	trx->op_info = "";

	return(err);
}

3665
/*********************************************************************//**
osku's avatar
osku committed
3666
Checks if a table name contains the string "/#sql" which denotes temporary
3667 3668
tables in MySQL.
@return	TRUE if temporary table */
osku's avatar
osku committed
3669 3670 3671 3672
static
ibool
row_is_mysql_tmp_table_name(
/*========================*/
3673
	const char*	name)	/*!< in: table name in the form
osku's avatar
osku committed
3674 3675
				'database/tablename' */
{
3676 3677
	return(strstr(name, "/#sql") != NULL);
	/* return(strstr(name, "/@0023sql") != NULL); */
osku's avatar
osku committed
3678 3679
}

3680
/****************************************************************//**
3681 3682
Delete a single constraint.
@return	error code or DB_SUCCESS */
3683 3684 3685 3686
static
int
row_delete_constraint_low(
/*======================*/
3687 3688
	const char*	id,		/*!< in: constraint id */
	trx_t*		trx)		/*!< in: transaction handle */
3689 3690 3691 3692 3693
{
	pars_info_t*	info = pars_info_create();

	pars_info_add_str_literal(info, "id", id);

3694
	return((int) que_eval_sql(info,
3695 3696 3697 3698 3699 3700
			    "PROCEDURE DELETE_CONSTRAINT () IS\n"
			    "BEGIN\n"
			    "DELETE FROM SYS_FOREIGN_COLS WHERE ID = :id;\n"
			    "DELETE FROM SYS_FOREIGN WHERE ID = :id;\n"
			    "END;\n"
			    , FALSE, trx));
3701 3702
}

3703
/****************************************************************//**
3704 3705
Delete a single constraint.
@return	error code or DB_SUCCESS */
3706 3707 3708 3709
static
int
row_delete_constraint(
/*==================*/
3710 3711
	const char*	id,		/*!< in: constraint id */
	const char*	database_name,	/*!< in: database name, with the
3712
					trailing '/' */
3713 3714
	mem_heap_t*	heap,		/*!< in: memory heap */
	trx_t*		trx)		/*!< in: transaction handle */
3715 3716 3717 3718
{
	ulint		err;

	/* New format constraints have ids <databasename>/<constraintname>. */
3719 3720
	err = row_delete_constraint_low(
		mem_heap_strcat(heap, database_name, id), trx);
3721 3722 3723

	if ((err == DB_SUCCESS) && !strchr(id, '/')) {
		/* Old format < 4.0.18 constraints have constraint ids
3724
		NUMBER_NUMBER. We only try deleting them if the
3725 3726 3727 3728 3729 3730 3731 3732
		constraint name does not contain a '/' character, otherwise
		deleting a new format constraint named 'foo/bar' from
		database 'baz' would remove constraint 'bar' from database
		'foo', if it existed. */

		err = row_delete_constraint_low(id, trx);
	}

3733
	return((int) err);
3734 3735
}

3736
/*********************************************************************//**
3737 3738
Renames a table for MySQL.
@return	error code or DB_SUCCESS */
3739
UNIV_INTERN
3740
ulint
osku's avatar
osku committed
3741 3742
row_rename_table_for_mysql(
/*=======================*/
3743 3744 3745 3746
	const char*	old_name,	/*!< in: old table name */
	const char*	new_name,	/*!< in: new table name */
	trx_t*		trx,		/*!< in: transaction handle */
	ibool		commit)		/*!< in: if TRUE then commit trx */
osku's avatar
osku committed
3747 3748
{
	dict_table_t*	table;
3749
	ulint		err			= DB_ERROR;
osku's avatar
osku committed
3750 3751 3752
	mem_heap_t*	heap			= NULL;
	const char**	constraints_to_drop	= NULL;
	ulint		n_constraints_to_drop	= 0;
3753
	ibool		old_is_tmp, new_is_tmp;
3754
	pars_info_t*	info			= NULL;
osku's avatar
osku committed
3755 3756 3757 3758 3759

	ut_a(old_name != NULL);
	ut_a(new_name != NULL);

	if (srv_created_new_raw || srv_force_recovery) {
3760 3761 3762 3763 3764 3765 3766
		fputs("InnoDB: A new raw disk partition was initialized or\n"
		      "InnoDB: innodb_force_recovery is on: we do not allow\n"
		      "InnoDB: database modifications by the user. Shut down\n"
		      "InnoDB: mysqld and edit my.cnf so that newraw"
		      " is replaced\n"
		      "InnoDB: with raw, and innodb_force_... is removed.\n",
		      stderr);
osku's avatar
osku committed
3767

3768
		goto funct_exit;
3769
	} else if (row_mysql_is_system_table(new_name)) {
3770

osku's avatar
osku committed
3771
		fprintf(stderr,
3772 3773 3774 3775 3776
			"InnoDB: Error: trying to create a MySQL"
			" system table %s of type InnoDB.\n"
			"InnoDB: MySQL system tables must be"
			" of the MyISAM type!\n",
			new_name);
osku's avatar
osku committed
3777

3778
		goto funct_exit;
osku's avatar
osku committed
3779 3780 3781 3782 3783
	}

	trx->op_info = "renaming table";
	trx_start_if_not_started(trx);

3784 3785
	old_is_tmp = row_is_mysql_tmp_table_name(old_name);
	new_is_tmp = row_is_mysql_tmp_table_name(new_name);
3786

osku's avatar
osku committed
3787 3788 3789 3790
	table = dict_table_get_low(old_name);

	if (!table) {
		err = DB_TABLE_NOT_FOUND;
3791
		ut_print_timestamp(stderr);
osku's avatar
osku committed
3792

3793
		fputs("  InnoDB: Error: table ", stderr);
3794
		ut_print_name(stderr, trx, TRUE, old_name);
3795
		fputs(" does not exist in the InnoDB internal\n"
3796 3797 3798 3799 3800 3801 3802
		      "InnoDB: data dictionary though MySQL is"
		      " trying to rename the table.\n"
		      "InnoDB: Have you copied the .frm file"
		      " of the table to the\n"
		      "InnoDB: MySQL database directory"
		      " from another database?\n"
		      "InnoDB: You can look for further help from\n"
3803
		      "InnoDB: " REFMAN "innodb-troubleshooting.html\n",
3804
		      stderr);
osku's avatar
osku committed
3805
		goto funct_exit;
3806
	} else if (table->ibd_file_missing) {
osku's avatar
osku committed
3807
		err = DB_TABLE_NOT_FOUND;
3808
		ut_print_timestamp(stderr);
osku's avatar
osku committed
3809

3810
		fputs("  InnoDB: Error: table ", stderr);
3811
		ut_print_name(stderr, trx, TRUE, old_name);
3812 3813 3814
		fputs(" does not have an .ibd file"
		      " in the database directory.\n"
		      "InnoDB: You can look for further help from\n"
3815
		      "InnoDB: " REFMAN "innodb-troubleshooting.html\n",
3816
		      stderr);
osku's avatar
osku committed
3817
		goto funct_exit;
3818
	} else if (new_is_tmp) {
osku's avatar
osku committed
3819 3820 3821 3822 3823 3824 3825
		/* MySQL is doing an ALTER TABLE command and it renames the
		original table to a temporary table name. We want to preserve
		the original foreign key constraint definitions despite the
		name change. An exception is those constraints for which
		the ALTER TABLE contained DROP FOREIGN KEY <foreign key id>.*/

		heap = mem_heap_create(100);
3826

3827 3828 3829
		err = dict_foreign_parse_drop_constraints(
			heap, trx, table, &n_constraints_to_drop,
			&constraints_to_drop);
3830

osku's avatar
osku committed
3831 3832 3833 3834
		if (err != DB_SUCCESS) {

			goto funct_exit;
		}
3835
	}
3836

3837
	/* We use the private SQL parser of Innobase to generate the query
3838
	graphs needed in updating the dictionary data from system tables. */
osku's avatar
osku committed
3839

3840
	info = pars_info_create();
osku's avatar
osku committed
3841

3842 3843
	pars_info_add_str_literal(info, "new_table_name", new_name);
	pars_info_add_str_literal(info, "old_table_name", old_name);
osku's avatar
osku committed
3844

3845
	err = que_eval_sql(info,
3846 3847 3848 3849 3850 3851
			   "PROCEDURE RENAME_TABLE () IS\n"
			   "BEGIN\n"
			   "UPDATE SYS_TABLES SET NAME = :new_table_name\n"
			   " WHERE NAME = :old_table_name;\n"
			   "END;\n"
			   , FALSE, trx);
osku's avatar
osku committed
3852

3853
	if (err != DB_SUCCESS) {
osku's avatar
osku committed
3854

3855
		goto end;
3856
	} else if (!new_is_tmp) {
3857
		/* Rename all constraints. */
3858

3859
		info = pars_info_create();
osku's avatar
osku committed
3860

3861 3862
		pars_info_add_str_literal(info, "new_table_name", new_name);
		pars_info_add_str_literal(info, "old_table_name", old_name);
osku's avatar
osku committed
3863

3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928
		err = que_eval_sql(
			info,
			"PROCEDURE RENAME_CONSTRAINT_IDS () IS\n"
			"gen_constr_prefix CHAR;\n"
			"new_db_name CHAR;\n"
			"foreign_id CHAR;\n"
			"new_foreign_id CHAR;\n"
			"old_db_name_len INT;\n"
			"old_t_name_len INT;\n"
			"new_db_name_len INT;\n"
			"id_len INT;\n"
			"found INT;\n"
			"BEGIN\n"
			"found := 1;\n"
			"old_db_name_len := INSTR(:old_table_name, '/')-1;\n"
			"new_db_name_len := INSTR(:new_table_name, '/')-1;\n"
			"new_db_name := SUBSTR(:new_table_name, 0,\n"
			"                      new_db_name_len);\n"
			"old_t_name_len := LENGTH(:old_table_name);\n"
			"gen_constr_prefix := CONCAT(:old_table_name,\n"
			"                            '_ibfk_');\n"
			"WHILE found = 1 LOOP\n"
			"       SELECT ID INTO foreign_id\n"
			"        FROM SYS_FOREIGN\n"
			"        WHERE FOR_NAME = :old_table_name\n"
			"         AND TO_BINARY(FOR_NAME)\n"
			"           = TO_BINARY(:old_table_name)\n"
			"         LOCK IN SHARE MODE;\n"
			"       IF (SQL % NOTFOUND) THEN\n"
			"        found := 0;\n"
			"       ELSE\n"
			"        UPDATE SYS_FOREIGN\n"
			"        SET FOR_NAME = :new_table_name\n"
			"         WHERE ID = foreign_id;\n"
			"        id_len := LENGTH(foreign_id);\n"
			"        IF (INSTR(foreign_id, '/') > 0) THEN\n"
			"               IF (INSTR(foreign_id,\n"
			"                         gen_constr_prefix) > 0)\n"
			"               THEN\n"
			"                new_foreign_id :=\n"
			"                CONCAT(:new_table_name,\n"
			"                SUBSTR(foreign_id, old_t_name_len,\n"
			"                       id_len - old_t_name_len));\n"
			"               ELSE\n"
			"                new_foreign_id :=\n"
			"                CONCAT(new_db_name,\n"
			"                SUBSTR(foreign_id,\n"
			"                       old_db_name_len,\n"
			"                       id_len - old_db_name_len));\n"
			"               END IF;\n"
			"               UPDATE SYS_FOREIGN\n"
			"                SET ID = new_foreign_id\n"
			"                WHERE ID = foreign_id;\n"
			"               UPDATE SYS_FOREIGN_COLS\n"
			"                SET ID = new_foreign_id\n"
			"                WHERE ID = foreign_id;\n"
			"        END IF;\n"
			"       END IF;\n"
			"END LOOP;\n"
			"UPDATE SYS_FOREIGN SET REF_NAME = :new_table_name\n"
			"WHERE REF_NAME = :old_table_name\n"
			"  AND TO_BINARY(REF_NAME)\n"
			"    = TO_BINARY(:old_table_name);\n"
			"END;\n"
			, FALSE, trx);
osku's avatar
osku committed
3929

3930 3931
	} else if (n_constraints_to_drop > 0) {
		/* Drop some constraints of tmp tables. */
osku's avatar
osku committed
3932

3933 3934
		ulint	db_name_len = dict_get_db_name_len(old_name) + 1;
		char*	db_name = mem_heap_strdupl(heap, old_name,
3935
						   db_name_len);
3936
		ulint	i;
osku's avatar
osku committed
3937

3938 3939
		for (i = 0; i < n_constraints_to_drop; i++) {
			err = row_delete_constraint(constraints_to_drop[i],
3940
						    db_name, heap, trx);
osku's avatar
osku committed
3941

3942 3943 3944 3945 3946
			if (err != DB_SUCCESS) {
				break;
			}
		}
	}
osku's avatar
osku committed
3947

3948
end:
osku's avatar
osku committed
3949 3950
	if (err != DB_SUCCESS) {
		if (err == DB_DUPLICATE_KEY) {
3951
			ut_print_timestamp(stderr);
3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966
			fputs("  InnoDB: Error; possible reasons:\n"
			      "InnoDB: 1) Table rename would cause"
			      " two FOREIGN KEY constraints\n"
			      "InnoDB: to have the same internal name"
			      " in case-insensitive comparison.\n"
			      "InnoDB: 2) table ", stderr);
			ut_print_name(stderr, trx, TRUE, new_name);
			fputs(" exists in the InnoDB internal data\n"
			      "InnoDB: dictionary though MySQL is"
			      " trying to rename table ", stderr);
			ut_print_name(stderr, trx, TRUE, old_name);
			fputs(" to it.\n"
			      "InnoDB: Have you deleted the .frm file"
			      " and not used DROP TABLE?\n"
			      "InnoDB: You can look for further help from\n"
3967
			      "InnoDB: " REFMAN "innodb-troubleshooting.html\n"
3968
			      "InnoDB: If table ", stderr);
3969
			ut_print_name(stderr, trx, TRUE, new_name);
3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984
			fputs(" is a temporary table #sql..., then"
			      " it can be that\n"
			      "InnoDB: there are still queries running"
			      " on the table, and it will be\n"
			      "InnoDB: dropped automatically when"
			      " the queries end.\n"
			      "InnoDB: You can drop the orphaned table"
			      " inside InnoDB by\n"
			      "InnoDB: creating an InnoDB table with"
			      " the same name in another\n"
			      "InnoDB: database and copying the .frm file"
			      " to the current database.\n"
			      "InnoDB: Then MySQL thinks the table exists,"
			      " and DROP TABLE will\n"
			      "InnoDB: succeed.\n", stderr);
osku's avatar
osku committed
3985 3986
		}
		trx->error_state = DB_SUCCESS;
3987
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
3988 3989 3990 3991 3992
		trx->error_state = DB_SUCCESS;
	} else {
		/* The following call will also rename the .ibd data file if
		the table is stored in a single-table tablespace */

3993 3994
		if (!dict_table_rename_in_cache(table, new_name,
						!new_is_tmp)) {
osku's avatar
osku committed
3995
			trx->error_state = DB_SUCCESS;
3996
			trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
3997
			trx->error_state = DB_SUCCESS;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3998
			err = DB_ERROR;
osku's avatar
osku committed
3999 4000 4001
			goto funct_exit;
		}

4002 4003
		/* We only want to switch off some of the type checking in
		an ALTER, not in a RENAME. */
4004

4005
		err = dict_load_foreigns(
4006
			new_name, FALSE, !old_is_tmp || trx->check_foreigns);
osku's avatar
osku committed
4007

4008 4009
		if (err != DB_SUCCESS) {
			ut_print_timestamp(stderr);
osku's avatar
osku committed
4010

4011
			if (old_is_tmp) {
4012
				fputs("  InnoDB: Error: in ALTER TABLE ",
4013
				      stderr);
4014
				ut_print_name(stderr, trx, TRUE, new_name);
osku's avatar
osku committed
4015
				fputs("\n"
4016 4017 4018 4019 4020
				      "InnoDB: has or is referenced"
				      " in foreign key constraints\n"
				      "InnoDB: which are not compatible"
				      " with the new table definition.\n",
				      stderr);
4021
			} else {
4022 4023 4024
				fputs("  InnoDB: Error: in RENAME TABLE"
				      " table ",
				      stderr);
4025
				ut_print_name(stderr, trx, TRUE, new_name);
osku's avatar
osku committed
4026
				fputs("\n"
4027 4028 4029 4030 4031
				      "InnoDB: is referenced in"
				      " foreign key constraints\n"
				      "InnoDB: which are not compatible"
				      " with the new table definition.\n",
				      stderr);
osku's avatar
osku committed
4032
			}
4033 4034

			ut_a(dict_table_rename_in_cache(table,
4035
							old_name, FALSE));
4036
			trx->error_state = DB_SUCCESS;
4037
			trx_general_rollback_for_mysql(trx, NULL);
4038
			trx->error_state = DB_SUCCESS;
osku's avatar
osku committed
4039 4040
		}
	}
4041

4042
funct_exit:
4043 4044 4045 4046

	if (commit) {
		trx_commit_for_mysql(trx);
	}
osku's avatar
osku committed
4047 4048 4049 4050

	if (UNIV_LIKELY_NULL(heap)) {
		mem_heap_free(heap);
	}
4051

osku's avatar
osku committed
4052 4053
	trx->op_info = "";

4054
	return(err);
osku's avatar
osku committed
4055 4056
}

4057
/*********************************************************************//**
osku's avatar
osku committed
4058 4059
Checks that the index contains entries in an ascending order, unique
constraint is not broken, and calculates the number of index entries
4060 4061
in the read view of the current transaction.
@return	TRUE if ok */
4062
UNIV_INTERN
osku's avatar
osku committed
4063
ibool
4064 4065 4066 4067 4068 4069 4070
row_check_index_for_mysql(
/*======================*/
	row_prebuilt_t*		prebuilt,	/*!< in: prebuilt struct
						in MySQL handle */
	const dict_index_t*	index,		/*!< in: index */
	ulint*			n_rows)		/*!< out: number of entries
						seen in the consistent read */
osku's avatar
osku committed
4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083
{
	dtuple_t*	prev_entry	= NULL;
	ulint		matched_fields;
	ulint		matched_bytes;
	byte*		buf;
	ulint		ret;
	rec_t*		rec;
	ibool		is_ok		= TRUE;
	int		cmp;
	ibool		contains_null;
	ulint		i;
	ulint		cnt;
	mem_heap_t*	heap		= NULL;
4084
	ulint		n_ext;
osku's avatar
osku committed
4085
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
4086
	ulint*		offsets;
4087
	rec_offs_init(offsets_);
osku's avatar
osku committed
4088 4089

	*n_rows = 0;
4090

osku's avatar
osku committed
4091 4092
	buf = mem_alloc(UNIV_PAGE_SIZE);
	heap = mem_heap_create(100);
4093

osku's avatar
osku committed
4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104
	cnt = 1000;

	ret = row_search_for_mysql(buf, PAGE_CUR_G, prebuilt, 0, 0);
loop:
	/* Check thd->killed every 1,000 scanned rows */
	if (--cnt == 0) {
		if (trx_is_interrupted(prebuilt->trx)) {
			goto func_exit;
		}
		cnt = 1000;
	}
4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115

	switch (ret) {
	case DB_SUCCESS:
		break;
	default:
		ut_print_timestamp(stderr);
		fputs("  InnoDB: Warning: CHECK TABLE on ", stderr);
		dict_index_name_print(stderr, prebuilt->trx, index);
		fprintf(stderr, " returned %lu\n", ret);
		/* fall through (this error is ignored by CHECK TABLE) */
	case DB_END_OF_INDEX:
4116
func_exit:
osku's avatar
osku committed
4117 4118 4119 4120 4121 4122 4123
		mem_free(buf);
		mem_heap_free(heap);

		return(is_ok);
	}

	*n_rows = *n_rows + 1;
4124

osku's avatar
osku committed
4125 4126 4127
	/* row_search... returns the index record in buf, record origin offset
	within buf stored in the first 4 bytes, because we have built a dummy
	template */
4128

osku's avatar
osku committed
4129 4130
	rec = buf + mach_read_from_4(buf);

4131 4132 4133
	offsets = rec_get_offsets(rec, index, offsets_,
				  ULINT_UNDEFINED, &heap);

osku's avatar
osku committed
4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145
	if (prev_entry != NULL) {
		matched_fields = 0;
		matched_bytes = 0;

		cmp = cmp_dtuple_rec_with_match(prev_entry, rec, offsets,
						&matched_fields,
						&matched_bytes);
		contains_null = FALSE;

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

4146 4147
		for (i = 0;
		     i < dict_index_get_n_ordering_defined_by_user(index);
osku's avatar
osku committed
4148
		     i++) {
4149 4150
			if (UNIV_SQL_NULL == dfield_get_len(
				    dtuple_get_nth_field(prev_entry, i))) {
osku's avatar
osku committed
4151

4152 4153 4154
				contains_null = TRUE;
			}
		}
osku's avatar
osku committed
4155 4156 4157

		if (cmp > 0) {
			fputs("InnoDB: index records in a wrong order in ",
4158 4159
			      stderr);
not_ok:
osku's avatar
osku committed
4160
			dict_index_name_print(stderr,
4161
					      prebuilt->trx, index);
osku's avatar
osku committed
4162
			fputs("\n"
4163
			      "InnoDB: prev record ", stderr);
osku's avatar
osku committed
4164 4165
			dtuple_print(stderr, prev_entry);
			fputs("\n"
4166
			      "InnoDB: record ", stderr);
osku's avatar
osku committed
4167 4168 4169
			rec_print_new(stderr, rec, offsets);
			putc('\n', stderr);
			is_ok = FALSE;
4170
		} else if (dict_index_is_unique(index)
osku's avatar
osku committed
4171
			   && !contains_null
4172
			   && matched_fields
4173 4174
			   >= dict_index_get_n_ordering_defined_by_user(
				   index)) {
osku's avatar
osku committed
4175 4176 4177 4178 4179 4180

			fputs("InnoDB: duplicate key in ", stderr);
			goto not_ok;
		}
	}

4181 4182
	{
		mem_heap_t*	tmp_heap = NULL;
4183

4184 4185 4186 4187 4188 4189 4190 4191 4192 4193
		/* Empty the heap on each round.  But preserve offsets[]
		for the row_rec_to_index_entry() call, by copying them
		into a separate memory heap when needed. */
		if (UNIV_UNLIKELY(offsets != offsets_)) {
			ulint	size = rec_offs_get_n_alloc(offsets)
				* sizeof *offsets;

			tmp_heap = mem_heap_create(size);
			offsets = mem_heap_dup(tmp_heap, offsets, size);
		}
4194

4195
		mem_heap_empty(heap);
4196

4197 4198 4199
		prev_entry = row_rec_to_index_entry(ROW_COPY_DATA, rec,
						    index, offsets,
						    &n_ext, heap);
4200

4201 4202 4203
		if (UNIV_LIKELY_NULL(tmp_heap)) {
			mem_heap_free(tmp_heap);
		}
4204
	}
osku's avatar
osku committed
4205 4206 4207

	ret = row_search_for_mysql(buf, PAGE_CUR_G, prebuilt, 0, ROW_SEL_NEXT);

4208
	goto loop;
osku's avatar
osku committed
4209 4210
}

4211
/*********************************************************************//**
4212 4213
Determines if a table is a magic monitor table.
@return	TRUE if monitor table */
4214 4215 4216 4217
UNIV_INTERN
ibool
row_is_magic_monitor_table(
/*=======================*/
4218
	const char*	table_name)	/*!< in: name of the table, in the
4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239
					form database/table_name */
{
	const char*	name; /* table_name without database/ */
	ulint		len;

	name = strchr(table_name, '/');
	ut_a(name != NULL);
	name++;
	len = strlen(name) + 1;

	if (STR_EQ(name, len, S_innodb_monitor)
	    || STR_EQ(name, len, S_innodb_lock_monitor)
	    || STR_EQ(name, len, S_innodb_tablespace_monitor)
	    || STR_EQ(name, len, S_innodb_table_monitor)
	    || STR_EQ(name, len, S_innodb_mem_validate)) {

		return(TRUE);
	}

	return(FALSE);
}