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

3
Copyright (c) 2000, 2012, Oracle and/or its affiliates. All Rights Reserved.
4 5 6 7 8 9 10 11 12 13

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
14 15
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
16 17 18

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

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
#include "lock0lock.h"
#include "rem0cmp.h"
#include "log0log.h"
#include "btr0sea.h"
#include "fil0fil.h"
#include "ibuf0ibuf.h"
54 55 56
#include "m_string.h"
#include "my_sys.h"

osku's avatar
osku committed
57

58
/** Provide optional 4.x backwards compatibility for 5.0 and above */
59
UNIV_INTERN ibool	row_rollback_on_timeout	= FALSE;
60

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

/** Chain node of the list of tables to drop in the background. */
osku's avatar
osku committed
65
struct row_mysql_drop_struct{
66 67 68
	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
69 70
};

71 72 73 74 75
/** @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. */
76
static UT_LIST_BASE_NODE_T(row_mysql_drop_t)	row_mysql_drop_list;
77
/** Flag: has row_mysql_drop_list been initialized? */
78
static ibool	row_mysql_drop_list_inited	= FALSE;
osku's avatar
osku committed
79

80 81
/** Magic table names for invoking various monitor threads */
/* @{ */
osku's avatar
osku committed
82 83 84 85 86
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";
87 88 89 90 91 92 93 94
/* @} */

/** 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 */
95 96 97 98
#define STR_EQ(str1, str1_len, str2_onstack) \
	((str1_len) == sizeof(str2_onstack) \
	 && memcmp(str1, str2_onstack, sizeof(str2_onstack)) == 0)

99
/*******************************************************************//**
100 101
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
102 103 104 105 106 107
static
ibool
row_mysql_is_system_table(
/*======================*/
	const char*	name)
{
108 109
	if (strncmp(name, "mysql/", 6) != 0) {

osku's avatar
osku committed
110 111
		return(FALSE);
	}
112

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

118
/*********************************************************************//**
marko's avatar
marko committed
119 120 121 122
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
123 124
table lazily.
@return	TRUE if the table was not yet in the drop list, and was added there */
marko's avatar
marko committed
125 126 127 128
static
ibool
row_add_table_to_background_drop_list(
/*==================================*/
129
	const char*	name);	/*!< in: table name */
130

131
/*******************************************************************//**
osku's avatar
osku committed
132 133 134 135 136 137 138 139 140 141 142
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);
	}
}

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

156
/*******************************************************************//**
osku's avatar
osku committed
157
Stores a >= 5.0.3 format true VARCHAR length to dest, in the MySQL row
158
format.
159 160
@return pointer to the data, we skip the 1 or 2 bytes at the start
that are used to store the len */
161
UNIV_INTERN
osku's avatar
osku committed
162 163 164
byte*
row_mysql_store_true_var_len(
/*=========================*/
165 166 167
	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
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
{
	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);
}

185
/*******************************************************************//**
osku's avatar
osku committed
186
Reads a >= 5.0.3 format true VARCHAR length, in the MySQL row format, and
187
returns a pointer to the data.
188 189
@return pointer to the data, we skip the 1 or 2 bytes at the start
that are used to store the len */
190
UNIV_INTERN
191
const byte*
osku's avatar
osku committed
192 193
row_mysql_read_true_varchar(
/*========================*/
194 195 196
	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
197
				or 2 bytes */
osku's avatar
osku committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211
{
	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);
}

212
/*******************************************************************//**
osku's avatar
osku committed
213
Stores a reference to a BLOB in the MySQL format. */
214
UNIV_INTERN
osku's avatar
osku committed
215 216 217
void
row_mysql_store_blob_ref(
/*=====================*/
218 219
	byte*		dest,	/*!< in: where to store */
	ulint		col_len,/*!< in: dest buffer size: determines into
osku's avatar
osku committed
220 221 222
				how many bytes the BLOB length is stored,
				the space for the length may vary from 1
				to 4 bytes */
223
	const void*	data,	/*!< in: BLOB data; if the value to store
osku's avatar
osku committed
224
				is SQL NULL this should be NULL pointer */
225
	ulint		len)	/*!< in: BLOB length; if the value to store
osku's avatar
osku committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
				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);

246
	memcpy(dest + col_len - 8, &data, sizeof data);
osku's avatar
osku committed
247 248
}

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

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

266
	memcpy(&data, ref + col_len - 8, sizeof data);
osku's avatar
osku committed
267 268 269 270

	return(data);
}

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
/**************************************************************//**
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));
295
		while (pad < pad_end) {
296 297
			*pad++ = 0x00;
			*pad++ = 0x20;
298
		};
299 300 301 302 303
		break;
	case 4:
		/* space=0x00000020 */
		pad_end = pad + len;
		ut_a(!(len % 4));
304
		while (pad < pad_end) {
305 306 307 308
			*pad++ = 0x00;
			*pad++ = 0x00;
			*pad++ = 0x00;
			*pad++ = 0x20;
309
		}
310 311 312 313
		break;
	}
}

314
/**************************************************************//**
osku's avatar
osku committed
315 316
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
317 318
row0sel.c.
@return	up to which byte we used buf in the conversion */
319
UNIV_INTERN
osku's avatar
osku committed
320 321 322
byte*
row_mysql_store_col_in_innobase_format(
/*===================================*/
323
	dfield_t*	dfield,		/*!< in/out: dfield where dtype
osku's avatar
osku committed
324 325
					information must be already set when
					this function is called! */
326
	byte*		buf,		/*!< in/out: buffer for a converted
osku's avatar
osku committed
327 328
					integer value; this must be at least
					col_len long then! */
329
	ibool		row_format_col,	/*!< TRUE if the mysql_data is from
osku's avatar
osku committed
330 331 332 333 334 335
					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! */
336
	const byte*	mysql_data,	/*!< in: MySQL column value, not
osku's avatar
osku committed
337 338 339 340
					SQL NULL; NOTE that dfield may also
					get a pointer to mysql_data,
					therefore do not discard this as long
					as dfield is used! */
341
	ulint		col_len,	/*!< in: MySQL column length; NOTE that
osku's avatar
osku committed
342 343 344 345 346
					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 */
347
	ulint		comp)		/*!< in: nonzero=compact format */
osku's avatar
osku committed
348
{
349
	const byte*	ptr	= mysql_data;
350
	const dtype_t*	dtype;
osku's avatar
osku committed
351 352 353 354 355 356 357 358 359 360 361 362
	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. */

363
		byte*	p = buf + col_len;
osku's avatar
osku committed
364 365

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

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

376
			*buf ^= 128;
osku's avatar
osku committed
377 378
		}

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

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

osku's avatar
osku committed
389 390 391 392 393 394 395 396 397 398 399 400
			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,
401
							  lenlen);
osku's avatar
osku committed
402 403 404 405
		} else {
			/* Remove trailing spaces from old style VARCHAR
			columns. */

406
			/* Handle Unicode strings differently. */
osku's avatar
osku committed
407 408 409 410
			ulint	mbminlen	= dtype_get_mbminlen(dtype);

			ptr = mysql_data;

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
			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
428 429 430 431 432
				/* space=0x0020 */
				/* Trim "half-chars", just in case. */
				col_len &= ~1;

				while (col_len >= 2 && ptr[col_len - 2] == 0x00
433
				       && ptr[col_len - 1] == 0x20) {
osku's avatar
osku committed
434 435
					col_len -= 2;
				}
436 437
				break;
			case 1:
osku's avatar
osku committed
438 439
				/* space=0x20 */
				while (col_len > 0
440
				       && ptr[col_len - 1] == 0x20) {
osku's avatar
osku committed
441 442 443 444 445
					col_len--;
				}
			}
		}
	} else if (comp && type == DATA_MYSQL
446 447
		   && dtype_get_mbminlen(dtype) == 1
		   && dtype_get_mbmaxlen(dtype) > 1) {
osku's avatar
osku committed
448 449 450
		/* 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
451
		bytes to store an ASCII string! */
osku's avatar
osku committed
452 453 454 455 456 457 458 459

		/* 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
460
		space padding.	If the field contains single-byte
osku's avatar
osku committed
461 462 463 464
		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
465
		be stored as "$%&a " (5 bytes).	 The string ".abc "
osku's avatar
osku committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
		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);
}

491
/**************************************************************//**
osku's avatar
osku committed
492 493 494 495 496 497 498
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(
/*==============================*/
499
	dtuple_t*	row,		/*!< in/out: Innobase row where the
osku's avatar
osku committed
500 501
					field type information is already
					copied there! */
502
	row_prebuilt_t*	prebuilt,	/*!< in: prebuilt struct where template
osku's avatar
osku committed
503
					must be of type ROW_MYSQL_WHOLE_ROW */
504
	byte*		mysql_rec)	/*!< in: row in the MySQL format;
osku's avatar
osku committed
505 506 507 508
					NOTE: do not discard as long as
					row is used, as row may contain
					pointers to this record! */
{
509
	const mysql_row_templ_t*templ;
osku's avatar
osku committed
510 511
	dfield_t*		dfield;
	ulint			i;
512

osku's avatar
osku committed
513 514 515 516 517 518
	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;
519
		dfield = dtuple_get_nth_field(row, i);
osku's avatar
osku committed
520 521 522 523

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

524 525
			if (mysql_rec[templ->mysql_null_byte_offset]
			    & (byte) (templ->mysql_null_bit_mask)) {
osku's avatar
osku committed
526 527 528

				/* It is SQL NULL */

529
				dfield_set_null(dfield);
osku's avatar
osku committed
530 531 532

				goto next_column;
			}
533 534
		}

535 536 537 538 539 540 541
		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
542 543
next_column:
		;
544
	}
osku's avatar
osku committed
545 546
}

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

handle_new_error:
	err = trx->error_state;
567

osku's avatar
osku committed
568
	ut_a(err != DB_SUCCESS);
569

osku's avatar
osku committed
570
	trx->error_state = DB_SUCCESS;
571

572 573 574
	switch (err) {
	case DB_LOCK_WAIT_TIMEOUT:
		if (row_rollback_on_timeout) {
575
			trx_general_rollback_for_mysql(trx, NULL);
576
			break;
osku's avatar
osku committed
577
		}
578 579 580 581
		/* fall through */
	case DB_DUPLICATE_KEY:
	case DB_FOREIGN_DUPLICATE_KEY:
	case DB_TOO_BIG_RECORD:
582
	case DB_UNDO_RECORD_TOO_BIG:
583 584 585 586 587
	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:
588
	case DB_INTERRUPTED:
589
		if (savept) {
osku's avatar
osku committed
590 591 592
			/* Roll back the latest, possibly incomplete
			insertion or update */

593
			trx_general_rollback_for_mysql(trx, savept);
osku's avatar
osku committed
594 595
		}
		/* MySQL will roll back the latest SQL statement */
596 597
		break;
	case DB_LOCK_WAIT:
osku's avatar
osku committed
598 599 600 601 602 603 604 605 606 607 608 609
		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);

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

615
		trx_general_rollback_for_mysql(trx, NULL);
616
		break;
617

618
	case DB_MUST_GET_MORE_FILE_SPACE:
619 620 621 622 623
		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);
624

osku's avatar
osku committed
625 626
		exit(1);

627
	case DB_CORRUPTION:
628 629 630 631 632 633 634 635 636 637 638
		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"
639
		      "InnoDB: " REFMAN "forcing-innodb-recovery.html"
640
		      " for help.\n", stderr);
641
		break;
642 643 644 645 646 647 648
	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;
649
	default:
osku's avatar
osku committed
650 651 652
		fprintf(stderr, "InnoDB: unknown error code %lu\n",
			(ulong) err);
		ut_error;
653
	}
osku's avatar
osku committed
654 655 656 657 658 659

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

osku's avatar
osku committed
661 662 663 664 665
	trx->error_state = DB_SUCCESS;

	return(FALSE);
}

666
/********************************************************************//**
667 668
Create a prebuilt struct for a MySQL table handle.
@return	own: a prebuilt struct */
669
UNIV_INTERN
osku's avatar
osku committed
670 671 672
row_prebuilt_t*
row_create_prebuilt(
/*================*/
673 674 675
	dict_table_t*	table,		/*!< in: Innobase table handle */
	ulint		mysql_row_len)	/*!< in: length in bytes of a row in
					the MySQL format */
osku's avatar
osku committed
676 677 678 679 680 681
{
	row_prebuilt_t*	prebuilt;
	mem_heap_t*	heap;
	dict_index_t*	clust_index;
	dtuple_t*	ref;
	ulint		ref_len;
682
	ulint		search_tuple_n_fields;
683

684
	search_tuple_n_fields = 2 * dict_table_get_n_cols(table);
osku's avatar
osku committed
685

686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
	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);

#define PREBUILT_HEAP_INITIAL_SIZE	\
	( \
	sizeof(*prebuilt) \
	/* allocd in this function */ \
	+ DTUPLE_EST_ALLOC(search_tuple_n_fields) \
	+ DTUPLE_EST_ALLOC(ref_len) \
	/* allocd in row_prebuild_sel_graph() */ \
	+ sizeof(sel_node_t) \
	+ sizeof(que_fork_t) \
	+ sizeof(que_thr_t) \
	/* allocd in row_get_prebuilt_update_vector() */ \
	+ sizeof(upd_node_t) \
	+ sizeof(upd_t) \
	+ sizeof(upd_field_t) \
	  * dict_table_get_n_cols(table) \
	+ sizeof(que_fork_t) \
	+ sizeof(que_thr_t) \
	/* allocd in row_get_prebuilt_insert_row() */ \
	+ sizeof(ins_node_t) \
	/* mysql_row_len could be huge and we are not \
	sure if this prebuilt instance is going to be \
	used in inserts */ \
	+ (mysql_row_len < 256 ? mysql_row_len : 0) \
	+ DTUPLE_EST_ALLOC(dict_table_get_n_cols(table)) \
	+ sizeof(que_fork_t) \
	+ sizeof(que_thr_t) \
	)

	/* We allocate enough space for the objects that are likely to
	be created later in order to minimize the number of malloc()
	calls */
	heap = mem_heap_create(PREBUILT_HEAP_INITIAL_SIZE);

	prebuilt = mem_heap_zalloc(heap, sizeof(*prebuilt));
osku's avatar
osku committed
727 728 729 730 731 732 733 734 735

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

	prebuilt->table = table;

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

736 737
	btr_pcur_reset(&prebuilt->pcur);
	btr_pcur_reset(&prebuilt->clust_pcur);
osku's avatar
osku committed
738 739 740

	prebuilt->select_lock_type = LOCK_NONE;
	prebuilt->stored_select_lock_type = 99999999;
741 742
	UNIV_MEM_INVALID(&prebuilt->stored_select_lock_type,
			 sizeof prebuilt->stored_select_lock_type);
osku's avatar
osku committed
743

744
	prebuilt->search_tuple = dtuple_create(heap, search_tuple_n_fields);
osku's avatar
osku committed
745 746 747 748 749 750 751

	ref = dtuple_create(heap, ref_len);

	dict_index_copy_types(ref, clust_index, ref_len);

	prebuilt->clust_ref = ref;

752
	prebuilt->autoinc_error = 0;
753 754 755 756 757 758 759 760
	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;

761 762
	prebuilt->mysql_row_len = mysql_row_len;

osku's avatar
osku committed
763 764 765
	return(prebuilt);
}

766
/********************************************************************//**
osku's avatar
osku committed
767
Free a prebuilt struct for a MySQL table handle. */
768
UNIV_INTERN
osku's avatar
osku committed
769 770 771
void
row_prebuilt_free(
/*==============*/
772 773
	row_prebuilt_t*	prebuilt,	/*!< in, own: prebuilt struct */
	ibool		dict_locked)	/*!< in: TRUE=data dictionary locked */
osku's avatar
osku committed
774 775 776
{
	ulint	i;

777 778 779
	if (UNIV_UNLIKELY
	    (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED
	     || prebuilt->magic_n2 != ROW_PREBUILT_ALLOCATED)) {
780

osku's avatar
osku committed
781
		fprintf(stderr,
782 783
			"InnoDB: Error: trying to free a corrupt\n"
			"InnoDB: table handle. Magic n %lu,"
784
			" magic n2 %lu, table name ",
785 786
			(ulong) prebuilt->magic_n,
			(ulong) prebuilt->magic_n2);
787
		ut_print_name(stderr, NULL, TRUE, prebuilt->table->name);
osku's avatar
osku committed
788 789
		putc('\n', stderr);

790
		mem_analyze_corruption(prebuilt);
osku's avatar
osku committed
791 792 793 794 795 796 797

		ut_error;
	}

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

798 799
	btr_pcur_reset(&prebuilt->pcur);
	btr_pcur_reset(&prebuilt->clust_pcur);
osku's avatar
osku committed
800 801 802 803 804 805 806 807 808 809 810 811

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

osku's avatar
osku committed
813 814 815
	if (prebuilt->upd_graph) {
		que_graph_free_recursive(prebuilt->upd_graph);
	}
816

osku's avatar
osku committed
817 818 819 820 821 822 823
	if (prebuilt->blob_heap) {
		mem_heap_free(prebuilt->blob_heap);
	}

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

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

828 829 830 831 832
			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))) {
833 834
				fputs("InnoDB: Error: trying to free"
				      " a corrupt fetch buffer.\n", stderr);
osku's avatar
osku committed
835

836 837
				mem_analyze_corruption(
					prebuilt->fetch_cache[i]);
osku's avatar
osku committed
838 839 840 841 842 843 844 845

				ut_error;
			}

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

846
	dict_table_decrement_handle_count(prebuilt->table, dict_locked);
osku's avatar
osku committed
847 848 849 850

	mem_heap_free(prebuilt->heap);
}

851
/*********************************************************************//**
osku's avatar
osku committed
852 853
Updates the transaction pointers in query graphs stored in the prebuilt
struct. */
854
UNIV_INTERN
osku's avatar
osku committed
855 856 857
void
row_update_prebuilt_trx(
/*====================*/
858
	row_prebuilt_t*	prebuilt,	/*!< in/out: prebuilt struct
859
					in MySQL handle */
860
	trx_t*		trx)		/*!< in: transaction handle */
861
{
osku's avatar
osku committed
862 863
	if (trx->magic_n != TRX_MAGIC_N) {
		fprintf(stderr,
864 865 866
			"InnoDB: Error: trying to use a corrupt\n"
			"InnoDB: trx handle. Magic n %lu\n",
			(ulong) trx->magic_n);
osku's avatar
osku committed
867

868
		mem_analyze_corruption(trx);
osku's avatar
osku committed
869 870 871 872 873 874

		ut_error;
	}

	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
		fprintf(stderr,
875
			"InnoDB: Error: trying to use a corrupt\n"
876
			"InnoDB: table handle. Magic n %lu, table name ",
877
			(ulong) prebuilt->magic_n);
878
		ut_print_name(stderr, trx, TRUE, prebuilt->table->name);
osku's avatar
osku committed
879 880
		putc('\n', stderr);

881
		mem_analyze_corruption(prebuilt);
osku's avatar
osku committed
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897

		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;
898
	}
osku's avatar
osku committed
899 900
}

901
/*********************************************************************//**
osku's avatar
osku committed
902 903
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
904 905
builds it.
@return	prebuilt dtuple; the column type information is also set in it */
osku's avatar
osku committed
906 907 908 909
static
dtuple_t*
row_get_prebuilt_insert_row(
/*========================*/
910
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in MySQL
osku's avatar
osku committed
911 912 913 914 915 916 917
					handle */
{
	ins_node_t*	node;
	dtuple_t*	row;
	dict_table_t*	table	= prebuilt->table;

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

osku's avatar
osku committed
919 920 921 922 923 924
	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);
925

osku's avatar
osku committed
926 927 928
		prebuilt->ins_node = node;

		if (prebuilt->ins_upd_rec_buff == NULL) {
929 930
			prebuilt->ins_upd_rec_buff = mem_heap_alloc(
				prebuilt->heap, prebuilt->mysql_row_len);
osku's avatar
osku committed
931
		}
932

osku's avatar
osku committed
933
		row = dtuple_create(prebuilt->heap,
934
				    dict_table_get_n_cols(table));
osku's avatar
osku committed
935 936 937 938 939

		dict_table_copy_types(row, table);

		ins_node_set_new_row(node, row);

940 941 942 943
		prebuilt->ins_graph = que_node_get_parent(
			pars_complete_graph_for_exec(node,
						     prebuilt->trx,
						     prebuilt->heap));
osku's avatar
osku committed
944 945 946
		prebuilt->ins_graph->state = QUE_FORK_ACTIVE;
	}

947
	return(prebuilt->ins_node->row);
osku's avatar
osku committed
948 949
}

950
/*********************************************************************//**
osku's avatar
osku committed
951 952 953 954 955 956
Updates the table modification counter and calculates new estimates
for table and index statistics if necessary. */
UNIV_INLINE
void
row_update_statistics_if_needed(
/*============================*/
957
	dict_table_t*	table)	/*!< in: table */
osku's avatar
osku committed
958 959
{
	ulint	counter;
960

osku's avatar
osku committed
961 962 963 964 965 966 967 968 969 970 971
	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
972
	    || ((ib_int64_t)counter > 16 + table->stat_n_rows / 16)) {
osku's avatar
osku committed
973

974 975
		dict_update_statistics(table, FALSE /* update even if stats
						    are initialized */);
976
	}
osku's avatar
osku committed
977
}
978

979
/*********************************************************************//**
980 981 982
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). */
983
UNIV_INTERN
984
void
osku's avatar
osku committed
985 986
row_unlock_table_autoinc_for_mysql(
/*===============================*/
987
	trx_t*	trx)	/*!< in/out: transaction */
osku's avatar
osku committed
988
{
989 990
	if (lock_trx_holds_autoinc_locks(trx)) {
		mutex_enter(&kernel_mutex);
osku's avatar
osku committed
991

992
		lock_release_autoinc_locks(trx);
osku's avatar
osku committed
993

994 995
		mutex_exit(&kernel_mutex);
	}
osku's avatar
osku committed
996 997
}

998
/*********************************************************************//**
osku's avatar
osku committed
999 1000 1001 1002
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
1003 1004
table.
@return	error code or DB_SUCCESS */
1005
UNIV_INTERN
osku's avatar
osku committed
1006 1007 1008
int
row_lock_table_autoinc_for_mysql(
/*=============================*/
1009
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in the MySQL
osku's avatar
osku committed
1010 1011
					table handle */
{
1012 1013 1014 1015 1016 1017
	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;
1018

osku's avatar
osku committed
1019
	ut_ad(trx);
1020

1021 1022 1023 1024
	/* 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
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076

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

1077
/*********************************************************************//**
1078 1079
Sets a table lock on the table mentioned in prebuilt.
@return	error code or DB_SUCCESS */
1080
UNIV_INTERN
osku's avatar
osku committed
1081 1082 1083
int
row_lock_table_for_mysql(
/*=====================*/
1084
	row_prebuilt_t*	prebuilt,	/*!< in: prebuilt struct in the MySQL
osku's avatar
osku committed
1085
					table handle */
1086
	dict_table_t*	table,		/*!< in: table to lock, or NULL
osku's avatar
osku committed
1087 1088 1089
					if prebuilt->table should be
					locked as
					prebuilt->select_lock_type */
1090
	ulint		mode)		/*!< in: lock mode of table
osku's avatar
osku committed
1091 1092
					(ignored if table==NULL) */
{
1093
	trx_t*		trx		= prebuilt->trx;
osku's avatar
osku committed
1094 1095 1096
	que_thr_t*	thr;
	ulint		err;
	ibool		was_lock_wait;
1097

osku's avatar
osku committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
	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,
1127
				 prebuilt->select_lock_type, thr);
osku's avatar
osku committed
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
	}

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

osku's avatar
osku committed
1148 1149
	trx->op_info = "";

1150
	return((int) err);
osku's avatar
osku committed
1151
}
1152

1153
/*********************************************************************//**
1154 1155
Does an insert for MySQL.
@return	error code or DB_SUCCESS */
1156
UNIV_INTERN
osku's avatar
osku committed
1157 1158 1159
int
row_insert_for_mysql(
/*=================*/
1160 1161
	byte*		mysql_rec,	/*!< in: row in the MySQL format */
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in MySQL
osku's avatar
osku committed
1162 1163 1164 1165 1166 1167
					handle */
{
	trx_savept_t	savept;
	que_thr_t*	thr;
	ulint		err;
	ibool		was_lock_wait;
1168
	trx_t*		trx		= prebuilt->trx;
osku's avatar
osku committed
1169
	ins_node_t*	node		= prebuilt->ins_node;
1170

osku's avatar
osku committed
1171 1172 1173
	ut_ad(trx);

	if (prebuilt->table->ibd_file_missing) {
1174 1175
		ut_print_timestamp(stderr);
		fprintf(stderr, "  InnoDB: Error:\n"
1176 1177 1178 1179 1180 1181 1182 1183
			"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"
1184
			"InnoDB: " REFMAN "innodb-troubleshooting.html\n"
1185 1186
			"InnoDB: how you can resolve the problem.\n",
			prebuilt->table->name);
osku's avatar
osku committed
1187 1188 1189
		return(DB_ERROR);
	}

1190
	if (UNIV_UNLIKELY(prebuilt->magic_n != ROW_PREBUILT_ALLOCATED)) {
osku's avatar
osku committed
1191
		fprintf(stderr,
1192
			"InnoDB: Error: trying to free a corrupt\n"
1193
			"InnoDB: table handle. Magic n %lu, table name ",
1194
			(ulong) prebuilt->magic_n);
1195
		ut_print_name(stderr, trx, TRUE, prebuilt->table->name);
osku's avatar
osku committed
1196 1197
		putc('\n', stderr);

1198
		mem_analyze_corruption(prebuilt);
osku's avatar
osku committed
1199 1200 1201 1202

		ut_error;
	}

1203
	if (UNIV_UNLIKELY(srv_created_new_raw || srv_force_recovery)) {
1204 1205 1206 1207 1208 1209 1210
		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
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226

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

osku's avatar
osku committed
1228
	savept = trx_savept_take(trx);
1229

osku's avatar
osku committed
1230 1231 1232 1233 1234 1235 1236 1237
	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;
	}
1238

osku's avatar
osku committed
1239 1240 1241 1242 1243 1244 1245
	que_thr_move_to_run_state_for_mysql(thr, trx);

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

	row_ins_step(thr);
1246

osku's avatar
osku committed
1247 1248 1249 1250 1251
	err = trx->error_state;

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

1252
		/* TODO: what is this? */ thr->lock_state= QUE_THR_LOCK_ROW;
osku's avatar
osku committed
1253 1254

		was_lock_wait = row_mysql_handle_errors(&err, trx, thr,
1255
							&savept);
osku's avatar
osku committed
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
		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);
1268

osku's avatar
osku committed
1269 1270 1271
	prebuilt->table->stat_n_rows++;

	srv_n_rows_inserted++;
1272

osku's avatar
osku committed
1273 1274 1275
	if (prebuilt->table->stat_n_rows == 0) {
		/* Avoid wrap-over */
		prebuilt->table->stat_n_rows--;
1276
	}
osku's avatar
osku committed
1277 1278 1279 1280 1281 1282 1283

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

	return((int) err);
}

1284
/*********************************************************************//**
osku's avatar
osku committed
1285
Builds a dummy query graph used in selects. */
1286
UNIV_INTERN
osku's avatar
osku committed
1287 1288 1289
void
row_prebuild_sel_graph(
/*===================*/
1290
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in MySQL
osku's avatar
osku committed
1291 1292 1293 1294 1295
					handle */
{
	sel_node_t*	node;

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

osku's avatar
osku committed
1297 1298 1299
	if (prebuilt->sel_graph == NULL) {

		node = sel_node_create(prebuilt->heap);
1300

1301 1302 1303 1304
		prebuilt->sel_graph = que_node_get_parent(
			pars_complete_graph_for_exec(node,
						     prebuilt->trx,
						     prebuilt->heap));
osku's avatar
osku committed
1305 1306 1307 1308 1309

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

1310
/*********************************************************************//**
osku's avatar
osku committed
1311
Creates an query graph node of 'update' type to be used in the MySQL
1312 1313
interface.
@return	own: update node */
1314
UNIV_INTERN
osku's avatar
osku committed
1315 1316 1317
upd_node_t*
row_create_update_node_for_mysql(
/*=============================*/
1318 1319
	dict_table_t*	table,	/*!< in: table to update */
	mem_heap_t*	heap)	/*!< in: mem heap from which allocated */
osku's avatar
osku committed
1320 1321 1322 1323
{
	upd_node_t*	node;

	node = upd_node_create(heap);
1324

osku's avatar
osku committed
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
	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);
1335

osku's avatar
osku committed
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
	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);
}

1346
/*********************************************************************//**
osku's avatar
osku committed
1347 1348
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
1349 1350
first builds it.
@return	prebuilt update vector */
1351
UNIV_INTERN
osku's avatar
osku committed
1352 1353 1354
upd_t*
row_get_prebuilt_update_vector(
/*===========================*/
1355
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in MySQL
osku's avatar
osku committed
1356 1357 1358 1359 1360 1361
					handle */
{
	dict_table_t*	table	= prebuilt->table;
	upd_node_t*	node;

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

osku's avatar
osku committed
1363 1364 1365 1366 1367 1368 1369 1370
	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;
1371

1372 1373 1374 1375
		prebuilt->upd_graph = que_node_get_parent(
			pars_complete_graph_for_exec(node,
						     prebuilt->trx,
						     prebuilt->heap));
osku's avatar
osku committed
1376 1377 1378 1379 1380 1381
		prebuilt->upd_graph->state = QUE_FORK_ACTIVE;
	}

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

1382
/*********************************************************************//**
1383 1384
Does an update or delete of a row for MySQL.
@return	error code or DB_SUCCESS */
1385
UNIV_INTERN
osku's avatar
osku committed
1386 1387 1388
int
row_update_for_mysql(
/*=================*/
1389
	byte*		mysql_rec,	/*!< in: the row to be updated, in
osku's avatar
osku committed
1390
					the MySQL format */
1391
	row_prebuilt_t*	prebuilt)	/*!< in: prebuilt struct in MySQL
osku's avatar
osku committed
1392 1393 1394 1395 1396 1397
					handle */
{
	trx_savept_t	savept;
	ulint		err;
	que_thr_t*	thr;
	ibool		was_lock_wait;
1398
	dict_index_t*	clust_index;
1399
	/*	ulint		ref_len; */
osku's avatar
osku committed
1400 1401 1402 1403 1404 1405
	upd_node_t*	node;
	dict_table_t*	table		= prebuilt->table;
	trx_t*		trx		= prebuilt->trx;

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

osku's avatar
osku committed
1407
	if (prebuilt->table->ibd_file_missing) {
1408 1409
		ut_print_timestamp(stderr);
		fprintf(stderr, "  InnoDB: Error:\n"
1410 1411 1412 1413 1414 1415 1416 1417
			"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"
1418
			"InnoDB: " REFMAN "innodb-troubleshooting.html\n"
1419 1420
			"InnoDB: how you can resolve the problem.\n",
			prebuilt->table->name);
osku's avatar
osku committed
1421 1422 1423
		return(DB_ERROR);
	}

1424
	if (UNIV_UNLIKELY(prebuilt->magic_n != ROW_PREBUILT_ALLOCATED)) {
osku's avatar
osku committed
1425
		fprintf(stderr,
1426
			"InnoDB: Error: trying to free a corrupt\n"
1427
			"InnoDB: table handle. Magic n %lu, table name ",
1428
			(ulong) prebuilt->magic_n);
1429
		ut_print_name(stderr, trx, TRUE, prebuilt->table->name);
osku's avatar
osku committed
1430 1431
		putc('\n', stderr);

1432
		mem_analyze_corruption(prebuilt);
osku's avatar
osku committed
1433 1434 1435 1436

		ut_error;
	}

1437
	if (UNIV_UNLIKELY(srv_created_new_raw || srv_force_recovery)) {
1438 1439 1440 1441 1442 1443 1444
		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
1445 1446 1447 1448

		return(DB_ERROR);
	}

1449 1450
	DEBUG_SYNC_C("innodb_row_update_for_mysql_begin");

osku's avatar
osku committed
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
	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);

1461 1462
	if (prebuilt->pcur.btr_cur.index == clust_index) {
		btr_pcur_copy_stored_position(node->pcur, &prebuilt->pcur);
osku's avatar
osku committed
1463 1464
	} else {
		btr_pcur_copy_stored_position(node->pcur,
1465
					      &prebuilt->clust_pcur);
osku's avatar
osku committed
1466
	}
1467

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

osku's avatar
osku committed
1470 1471 1472 1473 1474 1475 1476 1477
	/* 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);
1478

osku's avatar
osku committed
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
	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;
1490
	thr->fk_cascade_depth = 0;
osku's avatar
osku committed
1491 1492 1493 1494 1495

	row_upd_step(thr);

	err = trx->error_state;

1496 1497 1498
	/* Reset fk_cascade_depth back to 0 */
	thr->fk_cascade_depth = 0;

osku's avatar
osku committed
1499 1500
	if (err != DB_SUCCESS) {
		que_thr_stop_for_mysql(thr);
1501

osku's avatar
osku committed
1502 1503 1504 1505 1506 1507 1508
		if (err == DB_RECORD_NOT_FOUND) {
			trx->error_state = DB_SUCCESS;
			trx->op_info = "";

			return((int) err);
		}

1509
		thr->lock_state= QUE_THR_LOCK_ROW;
osku's avatar
osku committed
1510
		was_lock_wait = row_mysql_handle_errors(&err, trx, thr,
1511
							&savept);
1512 1513
		thr->lock_state= QUE_THR_LOCK_NOLOCK;

osku's avatar
osku committed
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
		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++;
	}

1535 1536 1537 1538 1539 1540
	/* 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
1541 1542 1543 1544 1545 1546

	trx->op_info = "";

	return((int) err);
}

1547
/*********************************************************************//**
1548 1549 1550 1551 1552 1553 1554 1555 1556
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 */
1557
UNIV_INTERN
osku's avatar
osku committed
1558 1559 1560
int
row_unlock_for_mysql(
/*=================*/
1561
	row_prebuilt_t*	prebuilt,	/*!< in/out: prebuilt struct in MySQL
osku's avatar
osku committed
1562
					handle */
1563 1564 1565 1566 1567
	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
1568
{
1569 1570
	btr_pcur_t*	pcur		= &prebuilt->pcur;
	btr_pcur_t*	clust_pcur	= &prebuilt->clust_pcur;
osku's avatar
osku committed
1571
	trx_t*		trx		= prebuilt->trx;
1572

osku's avatar
osku committed
1573
	ut_ad(prebuilt && trx);
1574

1575 1576
	if (UNIV_UNLIKELY
	    (!srv_locks_unsafe_for_binlog
Vasil Dimov's avatar
Vasil Dimov committed
1577
	     && trx->isolation_level > TRX_ISO_READ_COMMITTED)) {
osku's avatar
osku committed
1578 1579

		fprintf(stderr,
1580
			"InnoDB: Error: calling row_unlock_for_mysql though\n"
1581
			"InnoDB: innodb_locks_unsafe_for_binlog is FALSE and\n"
1582 1583
			"InnoDB: this session is not using"
			" READ COMMITTED isolation level.\n");
osku's avatar
osku committed
1584 1585 1586 1587 1588 1589

		return(DB_SUCCESS);
	}

	trx->op_info = "unlock_row";

1590
	if (prebuilt->new_rec_locks >= 1) {
osku's avatar
osku committed
1591

1592
		const rec_t*	rec;
1593
		dict_index_t*	index;
1594
		trx_id_t	rec_trx_id;
1595
		mtr_t		mtr;
osku's avatar
osku committed
1596 1597

		mtr_start(&mtr);
1598

osku's avatar
osku committed
1599
		/* Restore the cursor position and find the record */
1600

osku's avatar
osku committed
1601 1602 1603 1604 1605
		if (!has_latches_on_recs) {
			btr_pcur_restore_position(BTR_SEARCH_LEAF, pcur, &mtr);
		}

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

1608 1609 1610
		if (prebuilt->new_rec_locks >= 2) {
			/* Restore the cursor position and find the record
			in the clustered index. */
osku's avatar
osku committed
1611

1612 1613 1614 1615
			if (!has_latches_on_recs) {
				btr_pcur_restore_position(BTR_SEARCH_LEAF,
							  clust_pcur, &mtr);
			}
1616

1617 1618
			rec = btr_pcur_get_rec(clust_pcur);
			index = btr_pcur_get_btr_cur(clust_pcur)->index;
osku's avatar
osku committed
1619 1620
		}

1621 1622 1623 1624 1625 1626
		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;
		}

1627 1628
		/* If the record has been modified by this
		transaction, do not unlock it. */
osku's avatar
osku committed
1629

1630 1631 1632 1633 1634 1635 1636
		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
1637

1638 1639 1640
			rec_offs_init(offsets_);
			offsets = rec_get_offsets(rec, index, offsets,
						  ULINT_UNDEFINED, &heap);
1641

1642
			rec_trx_id = row_get_rec_trx_id(rec, index, offsets);
osku's avatar
osku committed
1643

1644 1645 1646
			if (UNIV_LIKELY_NULL(heap)) {
				mem_heap_free(heap);
			}
osku's avatar
osku committed
1647 1648
		}

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

1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
			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);
			}
		}
1668
no_unlock:
osku's avatar
osku committed
1669 1670
		mtr_commit(&mtr);
	}
1671

osku's avatar
osku committed
1672
	trx->op_info = "";
1673

osku's avatar
osku committed
1674 1675 1676
	return(DB_SUCCESS);
}

1677
/**********************************************************************//**
1678 1679
Does a cascaded delete or set null in a foreign key operation.
@return	error code or DB_SUCCESS */
1680
UNIV_INTERN
osku's avatar
osku committed
1681 1682 1683
ulint
row_update_cascade_for_mysql(
/*=========================*/
1684 1685
	que_thr_t*	thr,	/*!< in: query thread */
	upd_node_t*	node,	/*!< in: update node used in the cascade
osku's avatar
osku committed
1686
				or set null operation */
1687
	dict_table_t*	table)	/*!< in: table where we do the operation */
osku's avatar
osku committed
1688 1689 1690 1691 1692
{
	ulint	err;
	trx_t*	trx;

	trx = thr_get_trx(thr);
1693

1694 1695 1696
	/* 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. */
1697 1698 1699 1700 1701
	thr->fk_cascade_depth++;

	if (thr->fk_cascade_depth > FK_MAX_CASCADE_DEL) {
		return (DB_FOREIGN_EXCEED_MAX_CASCADE);
	}
osku's avatar
osku committed
1702 1703 1704 1705 1706 1707
run_again:
	thr->run_node = node;
	thr->prev_node = node;

	row_upd_step(thr);

1708 1709 1710 1711 1712 1713
	/* 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
1714 1715 1716 1717 1718 1719 1720 1721
	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 */
1722

osku's avatar
osku committed
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
		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 */
1737

osku's avatar
osku committed
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
		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);
}

1761
/*********************************************************************//**
osku's avatar
osku committed
1762
Checks if a table is such that we automatically created a clustered
1763 1764
index on it (on row id).
@return	TRUE if the clustered index was generated automatically */
1765
UNIV_INTERN
osku's avatar
osku committed
1766 1767 1768
ibool
row_table_got_default_clust_index(
/*==============================*/
1769
	const dict_table_t*	table)	/*!< in: table */
osku's avatar
osku committed
1770
{
1771
	const dict_index_t*	clust_index;
osku's avatar
osku committed
1772 1773 1774

	clust_index = dict_table_get_first_index(table);

1775
	return(dict_index_get_nth_col(clust_index, 0)->mtype == DATA_SYS);
osku's avatar
osku committed
1776 1777
}

1778
/*********************************************************************//**
osku's avatar
osku committed
1779 1780
Locks the data dictionary in shared mode from modifications, for performing
foreign key check, rollback, or other operation invisible to MySQL. */
1781
UNIV_INTERN
osku's avatar
osku committed
1782
void
1783 1784
row_mysql_freeze_data_dictionary_func(
/*==================================*/
1785 1786 1787
	trx_t*		trx,	/*!< in/out: transaction */
	const char*	file,	/*!< in: file name */
	ulint		line)	/*!< in: line number */
osku's avatar
osku committed
1788 1789
{
	ut_a(trx->dict_operation_lock_mode == 0);
1790

1791
	rw_lock_s_lock_inline(&dict_operation_lock, 0, file, line);
osku's avatar
osku committed
1792 1793 1794 1795

	trx->dict_operation_lock_mode = RW_S_LATCH;
}

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

	rw_lock_s_unlock(&dict_operation_lock);

	trx->dict_operation_lock_mode = 0;
}

1811
/*********************************************************************//**
osku's avatar
osku committed
1812 1813
Locks the data dictionary exclusively for performing a table create or other
data dictionary modification operation. */
1814
UNIV_INTERN
osku's avatar
osku committed
1815
void
1816 1817
row_mysql_lock_data_dictionary_func(
/*================================*/
1818 1819 1820
	trx_t*		trx,	/*!< in/out: transaction */
	const char*	file,	/*!< in: file name */
	ulint		line)	/*!< in: line number */
osku's avatar
osku committed
1821 1822
{
	ut_a(trx->dict_operation_lock_mode == 0
1823
	     || trx->dict_operation_lock_mode == RW_X_LATCH);
1824

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

1828
	rw_lock_x_lock_inline(&dict_operation_lock, 0, file, line);
osku's avatar
osku committed
1829 1830 1831 1832 1833
	trx->dict_operation_lock_mode = RW_X_LATCH;

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

1834
/*********************************************************************//**
osku's avatar
osku committed
1835
Unlocks the data dictionary exclusive lock. */
1836
UNIV_INTERN
osku's avatar
osku committed
1837 1838 1839
void
row_mysql_unlock_data_dictionary(
/*=============================*/
1840
	trx_t*	trx)	/*!< in/out: transaction */
osku's avatar
osku committed
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
{
	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;
}

1853
/*********************************************************************//**
1854
Creates a table for MySQL. If the name of the table ends in
1855 1856 1857
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",
Vasil Dimov's avatar
Vasil Dimov committed
1858 1859
InnoDB will try to invoke mem_validate(). On failure the transaction will
be rolled back and the 'table' object will be freed.
1860
@return	error code or DB_SUCCESS */
1861
UNIV_INTERN
osku's avatar
osku committed
1862 1863 1864
int
row_create_table_for_mysql(
/*=======================*/
1865
	dict_table_t*	table,	/*!< in, own: table definition
1866
				(will be freed) */
1867
	trx_t*		trx)	/*!< in: transaction handle */
osku's avatar
osku committed
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
{
	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 */
1879
	ut_ad(mutex_own(&(dict_sys->mutex)));
osku's avatar
osku committed
1880
	ut_ad(trx->dict_operation_lock_mode == RW_X_LATCH);
1881

osku's avatar
osku committed
1882
	if (srv_created_new_raw) {
1883 1884 1885 1886 1887
		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);
1888
err_exit:
1889
		dict_mem_table_free(table);
osku's avatar
osku committed
1890 1891 1892 1893 1894 1895
		trx_commit_for_mysql(trx);

		return(DB_ERROR);
	}

	trx->op_info = "creating table";
1896

osku's avatar
osku committed
1897 1898 1899
	if (row_mysql_is_system_table(table->name)) {

		fprintf(stderr,
1900 1901 1902 1903 1904
			"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);
1905
		goto err_exit;
osku's avatar
osku committed
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
	}

	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;

1919
	if (STR_EQ(table_name, table_name_len, S_innodb_monitor)) {
osku's avatar
osku committed
1920 1921 1922

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

osku's avatar
osku committed
1924 1925 1926 1927 1928 1929
		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);
1930 1931
	} else if (STR_EQ(table_name, table_name_len,
			  S_innodb_lock_monitor)) {
osku's avatar
osku committed
1932 1933 1934 1935

		srv_print_innodb_monitor = TRUE;
		srv_print_innodb_lock_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1936 1937
	} else if (STR_EQ(table_name, table_name_len,
			  S_innodb_tablespace_monitor)) {
osku's avatar
osku committed
1938 1939 1940

		srv_print_innodb_tablespace_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1941 1942
	} else if (STR_EQ(table_name, table_name_len,
			  S_innodb_table_monitor)) {
osku's avatar
osku committed
1943 1944 1945

		srv_print_innodb_table_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1946 1947
	} else if (STR_EQ(table_name, table_name_len,
			  S_innodb_mem_validate)) {
1948
		/* We define here a debugging feature intended for
osku's avatar
osku committed
1949 1950 1951
		developers */

		fputs("Validating InnoDB memory:\n"
1952 1953 1954 1955 1956 1957
		      "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
1958 1959 1960 1961 1962
#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",
1963
		      stderr);
osku's avatar
osku committed
1964 1965 1966 1967 1968
#endif /* UNIV_MEM_DEBUG */
	}

	heap = mem_heap_create(512);

1969
	trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
1970

osku's avatar
osku committed
1971 1972 1973 1974 1975 1976 1977 1978 1979
	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;

1980 1981 1982 1983
	switch (err) {
	case DB_SUCCESS:
		break;
	case DB_OUT_OF_FILE_SPACE:
1984
		trx->error_state = DB_SUCCESS;
1985
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
1986

1987 1988 1989 1990 1991
		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
1992

1993
		if (dict_table_get_low(table->name)) {
osku's avatar
osku committed
1994

1995
			row_drop_table_for_mysql(table->name, trx, FALSE);
1996
			trx_commit_for_mysql(trx);
Vasil Dimov's avatar
Vasil Dimov committed
1997 1998
		} else {
			dict_mem_table_free(table);
1999 2000
		}
		break;
osku's avatar
osku committed
2001

2002 2003
	case DB_TOO_MANY_CONCURRENT_TRXS:
		/* We already have .ibd file here. it should be deleted. */
unknown's avatar
unknown committed
2004

2005 2006
		if (table->space && !fil_delete_tablespace(table->space,
							   FALSE)) {
2007
			ut_print_timestamp(stderr);
2008 2009 2010 2011
			fprintf(stderr,
				"  InnoDB: Error: not able to"
				" delete tablespace %lu of table ",
				(ulong) table->space);
unknown's avatar
unknown committed
2012
			ut_print_name(stderr, trx, TRUE, table->name);
2013
			fputs("!\n", stderr);
2014
		}
2015
		/* fall through */
2016

2017
	case DB_DUPLICATE_KEY:
2018
	default:
osku's avatar
osku committed
2019 2020 2021
		/* We may also get err == DB_ERROR if the .ibd file for the
		table already exists */

2022 2023 2024
		trx->error_state = DB_SUCCESS;
		trx_general_rollback_for_mysql(trx, NULL);
		dict_mem_table_free(table);
2025
		break;
osku's avatar
osku committed
2026 2027 2028 2029 2030 2031 2032 2033 2034
	}

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

	trx->op_info = "";

	return((int) err);
}

2035
/*********************************************************************//**
osku's avatar
osku committed
2036 2037
Does an index creation operation for MySQL. TODO: currently failure
to create an index results in dropping the whole table! This is no problem
2038 2039
currently as all indexes must be created at the same time as the table.
@return	error number or DB_SUCCESS */
2040
UNIV_INTERN
osku's avatar
osku committed
2041 2042 2043
int
row_create_index_for_mysql(
/*=======================*/
2044
	dict_index_t*	index,		/*!< in, own: index definition
2045
					(will be freed) */
2046 2047
	trx_t*		trx,		/*!< in: transaction handle */
	const ulint*	field_lengths)	/*!< in: if not NULL, must contain
osku's avatar
osku committed
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
					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;
2058
	ulint		i;
osku's avatar
osku committed
2059
	ulint		len;
2060
	char*		table_name;
2061
	dict_table_t*	table;
2062

osku's avatar
osku committed
2063 2064 2065
#ifdef UNIV_SYNC_DEBUG
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
#endif /* UNIV_SYNC_DEBUG */
2066
	ut_ad(mutex_own(&(dict_sys->mutex)));
2067

osku's avatar
osku committed
2068 2069
	trx->op_info = "creating index";

2070 2071 2072 2073 2074
	/* 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);

2075 2076
	table = dict_table_get_low(table_name);

osku's avatar
osku committed
2077 2078
	trx_start_if_not_started(trx);

2079 2080 2081
	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
2082 2083 2084

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

2085
		if (field_lengths && field_lengths[i]) {
osku's avatar
osku committed
2086 2087
			len = ut_max(len, field_lengths[i]);
		}
2088

2089 2090 2091
		/* 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
2092

2093
			dict_mem_index_free(index);
osku's avatar
osku committed
2094 2095 2096 2097 2098 2099
			goto error_handling;
		}
	}

	heap = mem_heap_create(512);

2100
	trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
osku's avatar
osku committed
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111

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

2112
	err = trx->error_state;
osku's avatar
osku committed
2113 2114 2115 2116

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

error_handling:
2117

osku's avatar
osku committed
2118 2119
	if (err != DB_SUCCESS) {
		/* We have special error handling here */
2120

osku's avatar
osku committed
2121 2122
		trx->error_state = DB_SUCCESS;

2123
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
2124

2125
		row_drop_table_for_mysql(table_name, trx, FALSE);
osku's avatar
osku committed
2126

2127 2128
		trx_commit_for_mysql(trx);

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

osku's avatar
osku committed
2132 2133
	trx->op_info = "";

2134 2135
	mem_free(table_name);

osku's avatar
osku committed
2136 2137 2138
	return((int) err);
}

2139
/*********************************************************************//**
osku's avatar
osku committed
2140 2141 2142 2143
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
2144
both participating tables. The indexes are allowed to contain more
osku's avatar
osku committed
2145
fields than mentioned in the constraint. Check also that foreign key
2146 2147
constraints which reference this table are ok.
@return	error code or DB_SUCCESS */
2148
UNIV_INTERN
osku's avatar
osku committed
2149 2150 2151
int
row_table_add_foreign_constraints(
/*==============================*/
2152 2153
	trx_t*		trx,		/*!< in: transaction */
	const char*	sql_string,	/*!< in: table create statement where
osku's avatar
osku committed
2154 2155 2156 2157
					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 */
2158
	size_t		sql_length,	/*!< in: length of sql_string */
2159
	const char*	name,		/*!< in: table full name in the
osku's avatar
osku committed
2160 2161
					normalized form
					database_name/table_name */
2162
	ibool		reject_fks)	/*!< in: if TRUE, fail with error
osku's avatar
osku committed
2163 2164 2165 2166 2167 2168
					code DB_CANNOT_ADD_CONSTRAINT if
					any foreign keys are found. */
{
	ulint	err;

	ut_ad(mutex_own(&(dict_sys->mutex)));
2169
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
2170 2171 2172
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
#endif /* UNIV_SYNC_DEBUG */
	ut_a(sql_string);
2173

osku's avatar
osku committed
2174 2175 2176 2177
	trx->op_info = "adding foreign keys";

	trx_start_if_not_started(trx);

2178
	trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
osku's avatar
osku committed
2179

2180 2181
	err = dict_create_foreign_constraints(trx, sql_string, sql_length,
					      name, reject_fks);
osku's avatar
osku committed
2182 2183
	if (err == DB_SUCCESS) {
		/* Check that also referencing constraints are ok */
2184
		err = dict_load_foreigns(name, FALSE, TRUE);
osku's avatar
osku committed
2185
	}
2186

osku's avatar
osku committed
2187 2188
	if (err != DB_SUCCESS) {
		/* We have special error handling here */
2189

osku's avatar
osku committed
2190 2191
		trx->error_state = DB_SUCCESS;

2192
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
2193 2194 2195

		row_drop_table_for_mysql(name, trx, FALSE);

2196 2197
		trx_commit_for_mysql(trx);

osku's avatar
osku committed
2198 2199 2200 2201 2202 2203
		trx->error_state = DB_SUCCESS;
	}

	return((int) err);
}

2204
/*********************************************************************//**
osku's avatar
osku committed
2205 2206 2207 2208 2209
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
2210 2211
in srv0srv.c.
@return	error code or DB_SUCCESS */
osku's avatar
osku committed
2212 2213 2214 2215
static
int
row_drop_table_for_mysql_in_background(
/*===================================*/
2216
	const char*	name)	/*!< in: table name */
osku's avatar
osku committed
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
{
	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;

2229
	/*	fputs("InnoDB: Error: Dropping table ", stderr);
2230
	ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2231 2232
	fputs(" in background drop list\n", stderr); */

2233 2234 2235
	/* Try to drop the table in InnoDB */

	error = row_drop_table_for_mysql(name, trx, FALSE);
osku's avatar
osku committed
2236 2237 2238 2239

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

osku's avatar
osku committed
2241 2242
	log_buffer_flush_to_disk();

2243
	trx_commit_for_mysql(trx);
osku's avatar
osku committed
2244

2245
	trx_free_for_background(trx);
osku's avatar
osku committed
2246 2247 2248 2249

	return((int) error);
}

2250
/*********************************************************************//**
osku's avatar
osku committed
2251 2252
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
2253 2254
dropping of tables is needed in ALTER TABLE on Unix.
@return	how many tables dropped + remaining tables in list */
2255
UNIV_INTERN
osku's avatar
osku committed
2256 2257 2258 2259 2260 2261 2262 2263
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;
2264
loop:
osku's avatar
osku committed
2265 2266 2267 2268 2269 2270 2271 2272 2273
	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);
2274

osku's avatar
osku committed
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
	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) {
2290
		/* If for some reason the table has already been dropped
osku's avatar
osku committed
2291 2292
		through some other mechanism, do not try to drop it */

2293
		goto already_dropped;
osku's avatar
osku committed
2294
	}
2295

2296 2297
	if (DB_SUCCESS != row_drop_table_for_mysql_in_background(
		    drop->table_name)) {
osku's avatar
osku committed
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
		/* 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);

2311
	ut_print_timestamp(stderr);
2312 2313 2314
	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
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324

	mem_free(drop->table_name);

	mem_free(drop);

	mutex_exit(&kernel_mutex);

	goto loop;
}

2325
/*********************************************************************//**
osku's avatar
osku committed
2326
Get the background drop list length. NOTE: the caller must own the kernel
2327 2328
mutex!
@return	how many tables in list */
2329
UNIV_INTERN
osku's avatar
osku committed
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
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;
	}
2341

osku's avatar
osku committed
2342 2343 2344
	return(UT_LIST_GET_LEN(row_mysql_drop_list));
}

2345
/*********************************************************************//**
osku's avatar
osku committed
2346 2347 2348 2349
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
2350 2351
table lazily.
@return	TRUE if the table was not yet in the drop list, and was added there */
osku's avatar
osku committed
2352 2353 2354 2355
static
ibool
row_add_table_to_background_drop_list(
/*==================================*/
2356
	const char*	name)	/*!< in: table name */
osku's avatar
osku committed
2357 2358
{
	row_mysql_drop_t*	drop;
2359

osku's avatar
osku committed
2360 2361 2362 2363 2364 2365 2366
	mutex_enter(&kernel_mutex);

	if (!row_mysql_drop_list_inited) {

		UT_LIST_INIT(row_mysql_drop_list);
		row_mysql_drop_list_inited = TRUE;
	}
2367

osku's avatar
osku committed
2368 2369 2370 2371
	/* 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
2372
		if (strcmp(drop->table_name, name) == 0) {
osku's avatar
osku committed
2373
			/* Already in the list */
2374

osku's avatar
osku committed
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
			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
2385
	drop->table_name = mem_strdup(name);
2386

osku's avatar
osku committed
2387
	UT_LIST_ADD_LAST(row_mysql_drop_list, row_mysql_drop_list, drop);
2388

2389
	/*	fputs("InnoDB: Adding table ", stderr);
2390
	ut_print_name(stderr, trx, TRUE, drop->table_name);
osku's avatar
osku committed
2391 2392 2393 2394 2395 2396 2397
	fputs(" to background drop list\n", stderr); */

	mutex_exit(&kernel_mutex);

	return(TRUE);
}

2398
/*********************************************************************//**
osku's avatar
osku committed
2399 2400
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
2401 2402
the table. Also the flag table->ibd_file_missing is set TRUE.
@return	error code or DB_SUCCESS */
2403
UNIV_INTERN
osku's avatar
osku committed
2404 2405 2406
int
row_discard_tablespace_for_mysql(
/*=============================*/
2407 2408
	const char*	name,	/*!< in: table name */
	trx_t*		trx)	/*!< in: transaction handle */
osku's avatar
osku committed
2409 2410
{
	dict_foreign_t*	foreign;
2411
	table_id_t	new_id;
osku's avatar
osku committed
2412 2413 2414
	dict_table_t*	table;
	ibool		success;
	ulint		err;
2415
	pars_info_t*	info = NULL;
osku's avatar
osku committed
2416

2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
	/* 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
2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463

	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);
2464
		fputs("  InnoDB: Error: table ", stderr);
2465
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2466
		fputs("\n"
2467 2468
		      "InnoDB: is in the system tablespace 0"
		      " which cannot be discarded\n", stderr);
osku's avatar
osku committed
2469 2470 2471 2472 2473 2474 2475
		err = DB_ERROR;

		goto funct_exit;
	}

	if (table->n_foreign_key_checks_running > 0) {

2476
		ut_print_timestamp(stderr);
2477
		fputs("  InnoDB: You are trying to DISCARD table ", stderr);
2478
		ut_print_name(stderr, trx, TRUE, table->name);
osku's avatar
osku committed
2479
		fputs("\n"
2480 2481 2482 2483
		      "InnoDB: though there is a foreign key check"
		      " running on it.\n"
		      "InnoDB: Cannot discard the table.\n",
		      stderr);
osku's avatar
osku committed
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493

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

osku's avatar
osku committed
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
	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);

2512
		fputs("  Cannot DISCARD table ", ef);
2513
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2514
		fputs("\n"
2515
		      "because it is referenced by ", ef);
2516
		ut_print_name(stderr, trx, TRUE, foreign->foreign_table_name);
osku's avatar
osku committed
2517 2518 2519 2520 2521 2522
		putc('\n', ef);
		mutex_exit(&dict_foreign_err_mutex);

		goto funct_exit;
	}

2523
	dict_hdr_get_new_id(&new_id, NULL, NULL);
osku's avatar
osku committed
2524

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

2528
	info = pars_info_create();
osku's avatar
osku committed
2529

2530
	pars_info_add_str_literal(info, "table_name", name);
2531
	pars_info_add_ull_literal(info, "new_id", new_id);
osku's avatar
osku committed
2532

2533
	err = que_eval_sql(info,
2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553
			   "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
2554 2555 2556

	if (err != DB_SUCCESS) {
		trx->error_state = DB_SUCCESS;
2557
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
2558 2559 2560 2561 2562 2563 2564 2565
		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;
2566
			trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576
			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;
		}
	}
2577

2578 2579
funct_exit:
	trx_commit_for_mysql(trx);
osku's avatar
osku committed
2580

2581 2582
	row_mysql_unlock_data_dictionary(trx);

osku's avatar
osku committed
2583 2584 2585 2586 2587
	trx->op_info = "";

	return((int) err);
}

2588
/*****************************************************************//**
osku's avatar
osku committed
2589
Imports a tablespace. The space id in the .ibd file must match the space id
2590 2591
of the table in the data dictionary.
@return	error code or DB_SUCCESS */
2592
UNIV_INTERN
osku's avatar
osku committed
2593 2594 2595
int
row_import_tablespace_for_mysql(
/*============================*/
2596 2597
	const char*	name,	/*!< in: table name */
	trx_t*		trx)	/*!< in: transaction handle */
osku's avatar
osku committed
2598 2599 2600
{
	dict_table_t*	table;
	ibool		success;
2601
	ib_uint64_t	current_lsn;
osku's avatar
osku committed
2602 2603 2604 2605 2606 2607 2608
	ulint		err		= DB_SUCCESS;

	trx_start_if_not_started(trx);

	trx->op_info = "importing tablespace";

	current_lsn = log_get_lsn();
2609

osku's avatar
osku committed
2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625
	/* 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);
2626
		fputs("  InnoDB: Error: cannot reset lsn's in table ", stderr);
2627
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2628
		fputs("\n"
2629 2630
		      "InnoDB: in ALTER TABLE ... IMPORT TABLESPACE\n",
		      stderr);
osku's avatar
osku committed
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647

		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);
2648
		fputs("  InnoDB: table ", stderr);
2649
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2650
		fputs("\n"
2651 2652 2653
		      "InnoDB: does not exist in the InnoDB data dictionary\n"
		      "InnoDB: in ALTER TABLE ... IMPORT TABLESPACE\n",
		      stderr);
osku's avatar
osku committed
2654 2655 2656 2657 2658 2659 2660 2661

		err = DB_TABLE_NOT_FOUND;

		goto funct_exit;
	}

	if (table->space == 0) {
		ut_print_timestamp(stderr);
2662
		fputs("  InnoDB: Error: table ", stderr);
2663
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2664
		fputs("\n"
2665 2666
		      "InnoDB: is in the system tablespace 0"
		      " which cannot be imported\n", stderr);
osku's avatar
osku committed
2667 2668 2669 2670 2671 2672 2673
		err = DB_ERROR;

		goto funct_exit;
	}

	if (!table->tablespace_discarded) {
		ut_print_timestamp(stderr);
2674 2675 2676
		fputs("  InnoDB: Error: you are trying to"
		      " IMPORT a tablespace\n"
		      "InnoDB: ", stderr);
2677
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2678
		fputs(", though you have not called DISCARD on it yet\n"
2679 2680
		      "InnoDB: during the lifetime of the mysqld process!\n",
		      stderr);
osku's avatar
osku committed
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691

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

2692 2693 2694 2695
	success = fil_open_single_table_tablespace(
		TRUE, table->space,
		table->flags == DICT_TF_COMPACT ? 0 : table->flags,
		table->name);
osku's avatar
osku committed
2696 2697 2698 2699 2700 2701
	if (success) {
		table->ibd_file_missing = FALSE;
		table->tablespace_discarded = FALSE;
	} else {
		if (table->ibd_file_missing) {
			ut_print_timestamp(stderr);
2702 2703 2704
			fputs("  InnoDB: cannot find or open in the"
			      " database directory the .ibd file of\n"
			      "InnoDB: table ", stderr);
2705
			ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
2706
			fputs("\n"
2707 2708
			      "InnoDB: in ALTER TABLE ... IMPORT TABLESPACE\n",
			      stderr);
osku's avatar
osku committed
2709 2710 2711 2712 2713
		}

		err = DB_ERROR;
	}

2714 2715
funct_exit:
	trx_commit_for_mysql(trx);
osku's avatar
osku committed
2716

2717 2718
	row_mysql_unlock_data_dictionary(trx);

osku's avatar
osku committed
2719 2720 2721 2722 2723
	trx->op_info = "";

	return((int) err);
}

2724
/*********************************************************************//**
2725 2726
Truncates a table for MySQL.
@return	error code or DB_SUCCESS */
2727
UNIV_INTERN
osku's avatar
osku committed
2728 2729 2730
int
row_truncate_table_for_mysql(
/*=========================*/
2731 2732
	dict_table_t*	table,	/*!< in: table handle */
	trx_t*		trx)	/*!< in: transaction handle */
osku's avatar
osku committed
2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
{
	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;
2743
	table_id_t	new_id;
2744
	ulint		recreate_space = 0;
2745
	pars_info_t*	info = NULL;
osku's avatar
osku committed
2746

2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
	/* 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.

2769 2770 2771 2772 2773
	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.
2774 2775

	4) Linear readahead and random readahead: we use the same
2776 2777
	method as in 3) to discard ongoing operations. (This is only
	relevant for TRUNCATE TABLE by DISCARD TABLESPACE.)
2778 2779 2780

	5) FOREIGN KEY operations: if
	table->n_foreign_key_checks_running > 0, we do not allow the
2781 2782 2783 2784 2785
	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
2786 2787 2788 2789

	ut_ad(table);

	if (srv_created_new_raw) {
2790 2791 2792 2793 2794
		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
2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812

		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)));
2813
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
	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);

2836
		fputs("  Cannot truncate table ", ef);
2837
		ut_print_name(ef, trx, TRUE, table->name);
osku's avatar
osku committed
2838
		fputs(" by DROP+CREATE\n"
2839
		      "InnoDB: because it is referenced by ", ef);
2840
		ut_print_name(ef, trx, TRUE, foreign->foreign_table_name);
osku's avatar
osku committed
2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855
		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);
2856
		fputs("  InnoDB: Cannot truncate table ", stderr);
2857
		ut_print_name(stderr, trx, TRUE, table->name);
osku's avatar
osku committed
2858
		fputs(" by DROP+CREATE\n"
2859 2860 2861
		      "InnoDB: because there is a foreign key check"
		      " running on it.\n",
		      stderr);
osku's avatar
osku committed
2862 2863 2864 2865 2866
		err = DB_ERROR;

		goto funct_exit;
	}

2867 2868
	/* Remove all locks except the table-level S and X locks. */
	lock_remove_all_on_table(table, FALSE);
osku's avatar
osku committed
2869 2870 2871

	trx->table_id = table->id;

2872 2873 2874
	if (table->space && !table->dir_path_of_temp_table) {
		/* Discard and create the single-table tablespace. */
		ulint	space	= table->space;
2875
		ulint	flags	= fil_space_get_flags(space);
2876

2877
		if (flags != ULINT_UNDEFINED
2878 2879 2880 2881
		    && fil_discard_tablespace(space)) {

			dict_index_t*	index;

2882
			dict_hdr_get_new_id(NULL, NULL, &space);
2883

2884 2885 2886 2887 2888
			/* 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);

2889 2890 2891
			if (space == ULINT_UNDEFINED
			    || fil_create_new_single_table_tablespace(
				    space, table->name, FALSE, flags,
2892
				    FIL_IBD_FILE_INITIAL_SIZE) != DB_SUCCESS) {
2893
				dict_table_x_unlock_indexes(table);
2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921
				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);
		}
2922 2923 2924 2925 2926 2927 2928 2929 2930
	} 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);
2931 2932
	}

osku's avatar
osku committed
2933 2934 2935 2936
	/* scan SYS_INDEXES for all indexes of the table */
	heap = mem_heap_create(800);

	tuple = dtuple_create(heap, 1);
2937
	dfield = dtuple_get_nth_field(tuple, 0);
osku's avatar
osku committed
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947

	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,
2948
				  BTR_MODIFY_LEAF, &pcur, &mtr);
osku's avatar
osku committed
2949 2950 2951 2952 2953 2954
	for (;;) {
		rec_t*		rec;
		const byte*	field;
		ulint		len;
		ulint		root_page_no;

2955
		if (!btr_pcur_is_on_user_rec(&pcur)) {
osku's avatar
osku committed
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974
			/* 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
2975 2976
		/* This call may commit and restart mtr
		and reposition pcur. */
2977 2978
		root_page_no = dict_truncate_index_tree(table, recreate_space,
							&pcur, &mtr);
osku's avatar
osku committed
2979 2980 2981 2982

		rec = btr_pcur_get_rec(&pcur);

		if (root_page_no != FIL_NULL) {
2983
			page_rec_write_field(
2984 2985
				rec, DICT_SYS_INDEXES_PAGE_NO_FIELD,
				root_page_no, &mtr);
osku's avatar
osku committed
2986 2987 2988 2989 2990 2991 2992 2993
			/* 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,
2994
						  &pcur, &mtr);
osku's avatar
osku committed
2995 2996
		}

2997
next_rec:
osku's avatar
osku committed
2998 2999 3000 3001 3002 3003 3004 3005
		btr_pcur_move_to_next_user_rec(&pcur, &mtr);
	}

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

	mem_heap_free(heap);

3006 3007 3008 3009
	/* Done with index truncation, release index tree locks,
	subsequent work relates to table level metadata change */
	dict_table_x_unlock_indexes(table);

3010
	dict_hdr_get_new_id(&new_id, NULL, NULL);
osku's avatar
osku committed
3011

3012
	info = pars_info_create();
osku's avatar
osku committed
3013

3014
	pars_info_add_int4_literal(info, "space", (lint) table->space);
3015 3016
	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
3017

3018
	err = que_eval_sql(info,
3019 3020
			   "PROCEDURE RENUMBER_TABLESPACE_PROC () IS\n"
			   "BEGIN\n"
3021 3022
			   "UPDATE SYS_TABLES"
			   " SET ID = :new_id, SPACE = :space\n"
3023 3024 3025
			   " WHERE ID = :old_id;\n"
			   "UPDATE SYS_COLUMNS SET TABLE_ID = :new_id\n"
			   " WHERE TABLE_ID = :old_id;\n"
3026 3027
			   "UPDATE SYS_INDEXES"
			   " SET TABLE_ID = :new_id, SPACE = :space\n"
3028 3029 3030 3031
			   " WHERE TABLE_ID = :old_id;\n"
			   "COMMIT WORK;\n"
			   "END;\n"
			   , FALSE, trx);
osku's avatar
osku committed
3032 3033 3034

	if (err != DB_SUCCESS) {
		trx->error_state = DB_SUCCESS;
3035
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
3036 3037
		trx->error_state = DB_SUCCESS;
		ut_print_timestamp(stderr);
3038 3039
		fputs("  InnoDB: Unable to assign a new identifier to table ",
		      stderr);
3040
		ut_print_name(stderr, trx, TRUE, table->name);
osku's avatar
osku committed
3041
		fputs("\n"
3042 3043
		      "InnoDB: after truncating it.  Background processes"
		      " may corrupt the table!\n", stderr);
osku's avatar
osku committed
3044 3045 3046 3047 3048
		err = DB_ERROR;
	} else {
		dict_table_change_id_in_cache(table, new_id);
	}

3049
	/* Reset auto-increment. */
3050
	dict_table_autoinc_lock(table);
3051
	dict_table_autoinc_initialize(table, 1);
3052
	dict_table_autoinc_unlock(table);
3053 3054
	dict_update_statistics(table, FALSE /* update even if stats are
					    initialized */);
osku's avatar
osku committed
3055

3056
	trx_commit_for_mysql(trx);
osku's avatar
osku committed
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068

funct_exit:

	row_mysql_unlock_data_dictionary(trx);

	trx->op_info = "";

	srv_wake_master_thread();

	return((int) err);
}

3069
/*********************************************************************//**
3070
Drops a table for MySQL.  If the name of the dropped table ends in
3071 3072
one of "innodb_monitor", "innodb_lock_monitor", "innodb_tablespace_monitor",
"innodb_table_monitor", then this will also stop the printing of monitor
3073 3074
output by the master thread.  If the data dictionary was not already locked
by the transaction, the transaction will be committed.  Otherwise, the
3075 3076
data dictionary will remain locked.
@return	error code or DB_SUCCESS */
3077
UNIV_INTERN
osku's avatar
osku committed
3078 3079 3080
int
row_drop_table_for_mysql(
/*=====================*/
3081 3082 3083
	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
3084 3085 3086
{
	dict_foreign_t*	foreign;
	dict_table_t*	table;
3087
	dict_index_t*	index;
osku's avatar
osku committed
3088 3089 3090 3091 3092
	ulint		space_id;
	ulint		err;
	const char*	table_name;
	ulint		namelen;
	ibool		locked_dictionary	= FALSE;
3093
	pars_info_t*    info			= NULL;
osku's avatar
osku committed
3094 3095 3096 3097

	ut_a(name != NULL);

	if (srv_created_new_raw) {
3098 3099 3100 3101 3102
		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
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120

		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
3121 3122
	    && !memcmp(table_name, S_innodb_monitor,
		       sizeof S_innodb_monitor)) {
osku's avatar
osku committed
3123 3124 3125

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

osku's avatar
osku committed
3127 3128 3129
		srv_print_innodb_monitor = FALSE;
		srv_print_innodb_lock_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_lock_monitor
3130 3131
		   && !memcmp(table_name, S_innodb_lock_monitor,
			      sizeof S_innodb_lock_monitor)) {
osku's avatar
osku committed
3132 3133 3134
		srv_print_innodb_monitor = FALSE;
		srv_print_innodb_lock_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_tablespace_monitor
3135 3136
		   && !memcmp(table_name, S_innodb_tablespace_monitor,
			      sizeof S_innodb_tablespace_monitor)) {
osku's avatar
osku committed
3137 3138 3139

		srv_print_innodb_tablespace_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_table_monitor
3140 3141
		   && !memcmp(table_name, S_innodb_table_monitor,
			      sizeof S_innodb_table_monitor)) {
osku's avatar
osku committed
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158

		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)));
3159
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
3160 3161
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
#endif /* UNIV_SYNC_DEBUG */
3162

3163 3164
	table = dict_table_get_low_ignore_err(
		name, DICT_ERR_IGNORE_INDEX_ROOT | DICT_ERR_IGNORE_CORRUPT);
osku's avatar
osku committed
3165 3166 3167

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

3170
		fputs("  InnoDB: Error: table ", stderr);
3171
		ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3172
		fputs(" does not exist in the InnoDB internal\n"
3173 3174 3175 3176 3177 3178 3179
		      "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"
3180
		      "InnoDB: " REFMAN "innodb-troubleshooting.html\n",
3181
		      stderr);
osku's avatar
osku committed
3182 3183 3184 3185 3186 3187 3188
		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);
3189

osku's avatar
osku committed
3190
	while (foreign && foreign->foreign_table == table) {
3191
check_next_foreign:
osku's avatar
osku committed
3192 3193 3194
		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}

3195
	if (foreign && trx->check_foreigns
3196
	    && !(drop_db && dict_tables_have_same_db(
3197
			 name, foreign->foreign_table_name_lookup))) {
osku's avatar
osku committed
3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
		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);

3209
		fputs("  Cannot drop table ", ef);
3210
		ut_print_name(ef, trx, TRUE, name);
osku's avatar
osku committed
3211
		fputs("\n"
3212
		      "because it is referenced by ", ef);
3213
		ut_print_name(ef, trx, TRUE, foreign->foreign_table_name);
osku's avatar
osku committed
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226
		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
3227
		added = row_add_table_to_background_drop_list(table->name);
osku's avatar
osku committed
3228

3229
		if (added) {
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239
			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);
3240

osku's avatar
osku committed
3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259
			/* 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
3260 3261
		const char*	table_name = table->name;
		ibool		added;
osku's avatar
osku committed
3262

marko's avatar
marko committed
3263
		added = row_add_table_to_background_drop_list(table_name);
osku's avatar
osku committed
3264 3265

		if (added) {
3266
			ut_print_timestamp(stderr);
3267 3268
			fputs("  InnoDB: You are trying to drop table ",
			      stderr);
marko's avatar
marko committed
3269
			ut_print_name(stderr, trx, TRUE, table_name);
osku's avatar
osku committed
3270
			fputs("\n"
3271 3272 3273 3274 3275
			      "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
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287

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

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

3292
	trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
osku's avatar
osku committed
3293 3294
	trx->table_id = table->id;

3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306
	/* Mark all indexes unavailable in the data dictionary cache
	before starting to drop the table. */

	for (index = dict_table_get_first_index(table);
	     index != NULL;
	     index = dict_table_get_next_index(index)) {
		rw_lock_x_lock(dict_index_get_lock(index));
		ut_ad(!index->to_be_dropped);
		index->to_be_dropped = TRUE;
		rw_lock_x_unlock(dict_index_get_lock(index));
	}

3307 3308 3309 3310
	/* 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
3311

3312
	info = pars_info_create();
osku's avatar
osku committed
3313

3314 3315 3316
	pars_info_add_str_literal(info, "table_name", name);

	err = que_eval_sql(info,
3317 3318 3319 3320 3321 3322
			   "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
3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335

			   "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"

3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357
			   "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
3358
			   "OPEN cur_fk;\n"
3359
			   "WHILE found = 1 LOOP\n"
Vasil Dimov's avatar
Vasil Dimov committed
3360
			   "       FETCH cur_fk INTO foreign_id;\n"
3361 3362 3363 3364 3365 3366 3367 3368 3369
			   "       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
3370
			   "CLOSE cur_fk;\n"
3371
			   "found := 1;\n"
Vasil Dimov's avatar
Vasil Dimov committed
3372
			   "OPEN cur_idx;\n"
3373
			   "WHILE found = 1 LOOP\n"
Vasil Dimov's avatar
Vasil Dimov committed
3374
			   "       FETCH cur_idx INTO index_id;\n"
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384
			   "       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
3385
			   "CLOSE cur_idx;\n"
3386 3387 3388 3389 3390 3391
			   "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
3392

3393
	switch (err) {
3394
		ibool		is_temp;
osku's avatar
osku committed
3395
		const char*	name_or_path;
3396
		mem_heap_t*	heap;
osku's avatar
osku committed
3397

3398 3399
	case DB_SUCCESS:

3400 3401 3402 3403 3404 3405
		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
3406
		space_id = table->space;
3407

osku's avatar
osku committed
3408
		if (table->dir_path_of_temp_table != NULL) {
3409 3410
			name_or_path = mem_heap_strdup(
				heap, table->dir_path_of_temp_table);
3411
			is_temp = TRUE;
osku's avatar
osku committed
3412 3413
		} else {
			name_or_path = name;
3414 3415
			is_temp = (table->flags >> DICT_TF2_SHIFT)
				& DICT_TF2_TEMPORARY;
osku's avatar
osku committed
3416 3417 3418 3419
		}

		dict_table_remove_from_cache(table);

3420
		if (dict_load_table(name, TRUE, DICT_ERR_IGNORE_NONE) != NULL) {
osku's avatar
osku committed
3421
			ut_print_timestamp(stderr);
3422
			fputs("  InnoDB: Error: not able to remove table ",
3423
			      stderr);
3424
			ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3425 3426 3427 3428 3429 3430 3431 3432 3433
			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,
3434
							       name_or_path,
3435 3436
							       is_temp, FALSE,
							       !is_temp)) {
osku's avatar
osku committed
3437 3438 3439
				err = DB_SUCCESS;

				fprintf(stderr,
3440 3441 3442
					"InnoDB: We removed now the InnoDB"
					" internal data dictionary entry\n"
					"InnoDB: of table ");
3443
				ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3444
				fprintf(stderr, ".\n");
3445
			} else if (!fil_delete_tablespace(space_id, FALSE)) {
osku's avatar
osku committed
3446
				fprintf(stderr,
3447 3448 3449
					"InnoDB: We removed now the InnoDB"
					" internal data dictionary entry\n"
					"InnoDB: of table ");
3450
				ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3451 3452 3453 3454
				fprintf(stderr, ".\n");

				ut_print_timestamp(stderr);
				fprintf(stderr,
3455 3456
					"  InnoDB: Error: not able to"
					" delete tablespace %lu of table ",
osku's avatar
osku committed
3457
					(ulong) space_id);
3458
				ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3459 3460 3461 3462
				fputs("!\n", stderr);
				err = DB_ERROR;
			}
		}
3463 3464

		mem_heap_free(heap);
3465 3466 3467 3468 3469 3470 3471
		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. */
3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482

		/* Mark all indexes available in the data dictionary
		cache again. */

		for (index = dict_table_get_first_index(table);
		     index != NULL;
		     index = dict_table_get_next_index(index)) {
			rw_lock_x_lock(dict_index_get_lock(index));
			index->to_be_dropped = FALSE;
			rw_lock_x_unlock(dict_index_get_lock(index));
		}
3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494
		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
3495
	}
3496

osku's avatar
osku committed
3497 3498 3499
funct_exit:

	if (locked_dictionary) {
3500 3501
		trx_commit_for_mysql(trx);

3502
		row_mysql_unlock_data_dictionary(trx);
osku's avatar
osku committed
3503 3504 3505 3506 3507 3508 3509 3510 3511
	}

	trx->op_info = "";

	srv_wake_master_thread();

	return((int) err);
}

3512 3513 3514 3515 3516 3517 3518
/*********************************************************************//**
Drop all temporary tables during crash recovery. */
UNIV_INTERN
void
row_mysql_drop_temp_tables(void)
/*============================*/
{
3519 3520 3521 3522
	trx_t*		trx;
	btr_pcur_t	pcur;
	mtr_t		mtr;
	mem_heap_t*	heap;
3523 3524 3525 3526 3527

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

3528
	heap = mem_heap_create(200);
3529

3530 3531 3532 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 3572 3573 3574 3575 3576
	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);

3577
		table = dict_load_table(table_name, TRUE, DICT_ERR_IGNORE_NONE);
3578 3579 3580 3581 3582 3583 3584 3585 3586

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

3589 3590 3591
	btr_pcur_close(&pcur);
	mtr_commit(&mtr);
	mem_heap_free(heap);
3592 3593 3594 3595
	row_mysql_unlock_data_dictionary(trx);
	trx_free_for_background(trx);
}

3596
/*******************************************************************//**
3597
Drop all foreign keys in a database, see Bug#18942.
3598 3599
Called at the end of row_drop_database_for_mysql().
@return	error code or DB_SUCCESS */
3600 3601 3602 3603
static
ulint
drop_all_foreign_keys_in_db(
/*========================*/
3604 3605
	const char*	name,	/*!< in: database name which ends to '/' */
	trx_t*		trx)	/*!< in: transaction handle */
3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
{
	pars_info_t*	pinfo;
	ulint		err;

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

	pinfo = pars_info_create();

	pars_info_add_str_literal(pinfo, "dbname", name);

3616
/** true if for_name is not prefixed with dbname */
3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655
#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);
}

3656
/*********************************************************************//**
3657 3658
Drops a database for MySQL.
@return	error code or DB_SUCCESS */
3659
UNIV_INTERN
osku's avatar
osku committed
3660 3661 3662
int
row_drop_database_for_mysql(
/*========================*/
3663 3664
	const char*	name,	/*!< in: database name which ends to '/' */
	trx_t*		trx)	/*!< in: transaction handle */
osku's avatar
osku committed
3665
{
3666
	dict_table_t* table;
osku's avatar
osku committed
3667 3668 3669
	char*	table_name;
	int	err	= DB_SUCCESS;
	ulint	namelen	= strlen(name);
3670

osku's avatar
osku committed
3671 3672
	ut_a(name != NULL);
	ut_a(name[namelen - 1] == '/');
3673

osku's avatar
osku committed
3674
	trx->op_info = "dropping database";
3675

osku's avatar
osku committed
3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693
	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);
3694 3695
			fputs("  InnoDB: Warning: MySQL is trying to"
			      " drop database ", stderr);
3696
			ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3697
			fputs("\n"
3698 3699
			      "InnoDB: though there are still"
			      " open handles to table ", stderr);
3700
			ut_print_name(stderr, trx, TRUE, table_name);
osku's avatar
osku committed
3701 3702
			fputs(".\n", stderr);

3703
			os_thread_sleep(1000000);
osku's avatar
osku committed
3704

3705
			mem_free(table_name);
osku's avatar
osku committed
3706

3707
			goto loop;
osku's avatar
osku committed
3708 3709 3710
		}

		err = row_drop_table_for_mysql(table_name, trx, TRUE);
3711
		trx_commit_for_mysql(trx);
osku's avatar
osku committed
3712 3713 3714

		if (err != DB_SUCCESS) {
			fputs("InnoDB: DROP DATABASE ", stderr);
3715
			ut_print_name(stderr, trx, TRUE, name);
osku's avatar
osku committed
3716 3717
			fprintf(stderr, " failed with error %lu for table ",
				(ulint) err);
3718
			ut_print_name(stderr, trx, TRUE, table_name);
osku's avatar
osku committed
3719
			putc('\n', stderr);
3720
			mem_free(table_name);
osku's avatar
osku committed
3721 3722
			break;
		}
3723 3724

		mem_free(table_name);
osku's avatar
osku committed
3725 3726
	}

3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739
	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
3740 3741
	trx_commit_for_mysql(trx);

3742 3743
	row_mysql_unlock_data_dictionary(trx);

osku's avatar
osku committed
3744 3745 3746 3747 3748
	trx->op_info = "";

	return(err);
}

3749
/*********************************************************************//**
osku's avatar
osku committed
3750
Checks if a table name contains the string "/#sql" which denotes temporary
3751 3752
tables in MySQL.
@return	TRUE if temporary table */
osku's avatar
osku committed
3753 3754 3755 3756
static
ibool
row_is_mysql_tmp_table_name(
/*========================*/
3757
	const char*	name)	/*!< in: table name in the form
osku's avatar
osku committed
3758 3759
				'database/tablename' */
{
3760 3761
	return(strstr(name, "/#sql") != NULL);
	/* return(strstr(name, "/@0023sql") != NULL); */
osku's avatar
osku committed
3762 3763
}

3764
/****************************************************************//**
3765 3766
Delete a single constraint.
@return	error code or DB_SUCCESS */
3767 3768 3769 3770
static
int
row_delete_constraint_low(
/*======================*/
3771 3772
	const char*	id,		/*!< in: constraint id */
	trx_t*		trx)		/*!< in: transaction handle */
3773 3774 3775 3776 3777
{
	pars_info_t*	info = pars_info_create();

	pars_info_add_str_literal(info, "id", id);

3778
	return((int) que_eval_sql(info,
3779 3780 3781 3782 3783 3784
			    "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));
3785 3786
}

3787
/****************************************************************//**
3788 3789
Delete a single constraint.
@return	error code or DB_SUCCESS */
3790 3791 3792 3793
static
int
row_delete_constraint(
/*==================*/
3794 3795
	const char*	id,		/*!< in: constraint id */
	const char*	database_name,	/*!< in: database name, with the
3796
					trailing '/' */
3797 3798
	mem_heap_t*	heap,		/*!< in: memory heap */
	trx_t*		trx)		/*!< in: transaction handle */
3799 3800 3801 3802
{
	ulint		err;

	/* New format constraints have ids <databasename>/<constraintname>. */
3803 3804
	err = row_delete_constraint_low(
		mem_heap_strcat(heap, database_name, id), trx);
3805 3806 3807

	if ((err == DB_SUCCESS) && !strchr(id, '/')) {
		/* Old format < 4.0.18 constraints have constraint ids
3808
		NUMBER_NUMBER. We only try deleting them if the
3809 3810 3811 3812 3813 3814 3815 3816
		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);
	}

3817
	return((int) err);
3818 3819
}

3820
/*********************************************************************//**
3821 3822
Renames a table for MySQL.
@return	error code or DB_SUCCESS */
3823
UNIV_INTERN
3824
ulint
osku's avatar
osku committed
3825 3826
row_rename_table_for_mysql(
/*=======================*/
3827 3828 3829 3830
	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
3831 3832
{
	dict_table_t*	table;
3833
	ulint		err			= DB_ERROR;
osku's avatar
osku committed
3834 3835 3836
	mem_heap_t*	heap			= NULL;
	const char**	constraints_to_drop	= NULL;
	ulint		n_constraints_to_drop	= 0;
3837
	ibool		old_is_tmp, new_is_tmp;
3838
	pars_info_t*	info			= NULL;
3839
	int		retry;
osku's avatar
osku committed
3840 3841 3842

	ut_a(old_name != NULL);
	ut_a(new_name != NULL);
unknown's avatar
unknown committed
3843
	ut_ad(trx->conc_state == TRX_ACTIVE);
osku's avatar
osku committed
3844 3845

	if (srv_created_new_raw || srv_force_recovery) {
3846 3847 3848 3849 3850 3851 3852
		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
3853

3854
		goto funct_exit;
3855
	} else if (row_mysql_is_system_table(new_name)) {
3856

osku's avatar
osku committed
3857
		fprintf(stderr,
3858 3859 3860 3861 3862
			"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
3863

3864
		goto funct_exit;
osku's avatar
osku committed
3865 3866 3867 3868
	}

	trx->op_info = "renaming table";

3869 3870
	old_is_tmp = row_is_mysql_tmp_table_name(old_name);
	new_is_tmp = row_is_mysql_tmp_table_name(new_name);
3871

osku's avatar
osku committed
3872 3873 3874 3875
	table = dict_table_get_low(old_name);

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

3878
		fputs("  InnoDB: Error: table ", stderr);
3879
		ut_print_name(stderr, trx, TRUE, old_name);
3880
		fputs(" does not exist in the InnoDB internal\n"
3881 3882 3883 3884 3885 3886 3887
		      "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"
3888
		      "InnoDB: " REFMAN "innodb-troubleshooting.html\n",
3889
		      stderr);
osku's avatar
osku committed
3890
		goto funct_exit;
3891
	} else if (table->ibd_file_missing) {
osku's avatar
osku committed
3892
		err = DB_TABLE_NOT_FOUND;
3893
		ut_print_timestamp(stderr);
osku's avatar
osku committed
3894

3895
		fputs("  InnoDB: Error: table ", stderr);
3896
		ut_print_name(stderr, trx, TRUE, old_name);
3897 3898 3899
		fputs(" does not have an .ibd file"
		      " in the database directory.\n"
		      "InnoDB: You can look for further help from\n"
3900
		      "InnoDB: " REFMAN "innodb-troubleshooting.html\n",
3901
		      stderr);
osku's avatar
osku committed
3902
		goto funct_exit;
3903
	} else if (new_is_tmp) {
osku's avatar
osku committed
3904 3905 3906 3907 3908 3909 3910
		/* 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);
3911

3912 3913 3914
		err = dict_foreign_parse_drop_constraints(
			heap, trx, table, &n_constraints_to_drop,
			&constraints_to_drop);
3915

osku's avatar
osku committed
3916 3917 3918 3919
		if (err != DB_SUCCESS) {

			goto funct_exit;
		}
3920
	}
3921

3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940
	/* Is a foreign key check running on this table? */
	for (retry = 0; retry < 100
	     && table->n_foreign_key_checks_running > 0; ++retry) {
		row_mysql_unlock_data_dictionary(trx);
		os_thread_yield();
		row_mysql_lock_data_dictionary(trx);
	}

	if (table->n_foreign_key_checks_running > 0) {
		ut_print_timestamp(stderr);
		fputs(" InnoDB: Error: in ALTER TABLE ", stderr);
		ut_print_name(stderr, trx, TRUE, old_name);
		fprintf(stderr, "\n"
			"InnoDB: a FOREIGN KEY check is running.\n"
			"InnoDB: Cannot rename table.\n");
		err = DB_TABLE_IN_FK_CHECK;
		goto funct_exit;
	}

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

3944
	info = pars_info_create();
osku's avatar
osku committed
3945

3946 3947
	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
3948

3949
	err = que_eval_sql(info,
3950 3951 3952 3953 3954 3955
			   "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
3956

3957
	if (err != DB_SUCCESS) {
osku's avatar
osku committed
3958

3959
		goto end;
3960
	} else if (!new_is_tmp) {
3961
		/* Rename all constraints. */
3962

3963
		info = pars_info_create();
osku's avatar
osku committed
3964

3965 3966
		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
3967

3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032
		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
4033

4034 4035
	} else if (n_constraints_to_drop > 0) {
		/* Drop some constraints of tmp tables. */
osku's avatar
osku committed
4036

4037 4038
		ulint	db_name_len = dict_get_db_name_len(old_name) + 1;
		char*	db_name = mem_heap_strdupl(heap, old_name,
4039
						   db_name_len);
4040
		ulint	i;
osku's avatar
osku committed
4041

4042 4043
		for (i = 0; i < n_constraints_to_drop; i++) {
			err = row_delete_constraint(constraints_to_drop[i],
4044
						    db_name, heap, trx);
osku's avatar
osku committed
4045

4046 4047 4048 4049 4050
			if (err != DB_SUCCESS) {
				break;
			}
		}
	}
osku's avatar
osku committed
4051

4052
end:
osku's avatar
osku committed
4053 4054
	if (err != DB_SUCCESS) {
		if (err == DB_DUPLICATE_KEY) {
4055
			ut_print_timestamp(stderr);
4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070
			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"
4071
			      "InnoDB: " REFMAN "innodb-troubleshooting.html\n"
4072
			      "InnoDB: If table ", stderr);
4073
			ut_print_name(stderr, trx, TRUE, new_name);
4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088
			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
4089 4090
		}
		trx->error_state = DB_SUCCESS;
4091
		trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
4092 4093 4094 4095 4096
		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 */

4097 4098
		if (!dict_table_rename_in_cache(table, new_name,
						!new_is_tmp)) {
osku's avatar
osku committed
4099
			trx->error_state = DB_SUCCESS;
4100
			trx_general_rollback_for_mysql(trx, NULL);
osku's avatar
osku committed
4101
			trx->error_state = DB_SUCCESS;
unknown's avatar
unknown committed
4102
			err = DB_ERROR;
osku's avatar
osku committed
4103 4104 4105
			goto funct_exit;
		}

4106 4107
		/* We only want to switch off some of the type checking in
		an ALTER, not in a RENAME. */
4108

4109
		err = dict_load_foreigns(
4110
			new_name, FALSE, !old_is_tmp || trx->check_foreigns);
osku's avatar
osku committed
4111

4112 4113
		if (err != DB_SUCCESS) {
			ut_print_timestamp(stderr);
osku's avatar
osku committed
4114

4115
			if (old_is_tmp) {
4116
				fputs("  InnoDB: Error: in ALTER TABLE ",
4117
				      stderr);
4118
				ut_print_name(stderr, trx, TRUE, new_name);
osku's avatar
osku committed
4119
				fputs("\n"
4120 4121 4122 4123 4124
				      "InnoDB: has or is referenced"
				      " in foreign key constraints\n"
				      "InnoDB: which are not compatible"
				      " with the new table definition.\n",
				      stderr);
4125
			} else {
4126 4127 4128
				fputs("  InnoDB: Error: in RENAME TABLE"
				      " table ",
				      stderr);
4129
				ut_print_name(stderr, trx, TRUE, new_name);
osku's avatar
osku committed
4130
				fputs("\n"
4131 4132 4133 4134 4135
				      "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
4136
			}
4137 4138

			ut_a(dict_table_rename_in_cache(table,
4139
							old_name, FALSE));
4140
			trx->error_state = DB_SUCCESS;
4141
			trx_general_rollback_for_mysql(trx, NULL);
4142
			trx->error_state = DB_SUCCESS;
4143 4144 4145 4146 4147 4148 4149
		} else {
			if (old_is_tmp && !new_is_tmp) {
				/* After ALTER TABLE the table statistics
				needs to be rebuilt.  It will be rebuilt
				when the table is loaded again. */
				table->stat_initialized = FALSE;
			}
osku's avatar
osku committed
4150 4151
		}
	}
4152

4153
funct_exit:
4154 4155 4156 4157

	if (commit) {
		trx_commit_for_mysql(trx);
	}
osku's avatar
osku committed
4158 4159 4160 4161

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

osku's avatar
osku committed
4163 4164
	trx->op_info = "";

4165
	return(err);
osku's avatar
osku committed
4166 4167
}

4168
/*********************************************************************//**
osku's avatar
osku committed
4169 4170
Checks that the index contains entries in an ascending order, unique
constraint is not broken, and calculates the number of index entries
4171 4172
in the read view of the current transaction.
@return	TRUE if ok */
4173
UNIV_INTERN
osku's avatar
osku committed
4174
ibool
4175 4176 4177 4178 4179 4180 4181
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
4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194
{
	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;
4195
	ulint		n_ext;
osku's avatar
osku committed
4196
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
4197
	ulint*		offsets;
4198
	rec_offs_init(offsets_);
osku's avatar
osku committed
4199 4200

	*n_rows = 0;
4201

osku's avatar
osku committed
4202 4203
	buf = mem_alloc(UNIV_PAGE_SIZE);
	heap = mem_heap_create(100);
4204

osku's avatar
osku committed
4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215
	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;
	}
4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226

	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:
4227
func_exit:
osku's avatar
osku committed
4228 4229 4230 4231 4232 4233 4234
		mem_free(buf);
		mem_heap_free(heap);

		return(is_ok);
	}

	*n_rows = *n_rows + 1;
4235

osku's avatar
osku committed
4236 4237 4238
	/* 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 */
4239

osku's avatar
osku committed
4240 4241
	rec = buf + mach_read_from_4(buf);

4242 4243 4244
	offsets = rec_get_offsets(rec, index, offsets_,
				  ULINT_UNDEFINED, &heap);

osku's avatar
osku committed
4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256
	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 */

4257 4258
		for (i = 0;
		     i < dict_index_get_n_ordering_defined_by_user(index);
osku's avatar
osku committed
4259
		     i++) {
4260 4261
			if (UNIV_SQL_NULL == dfield_get_len(
				    dtuple_get_nth_field(prev_entry, i))) {
osku's avatar
osku committed
4262

4263 4264 4265
				contains_null = TRUE;
			}
		}
osku's avatar
osku committed
4266 4267 4268

		if (cmp > 0) {
			fputs("InnoDB: index records in a wrong order in ",
4269 4270
			      stderr);
not_ok:
osku's avatar
osku committed
4271
			dict_index_name_print(stderr,
4272
					      prebuilt->trx, index);
osku's avatar
osku committed
4273
			fputs("\n"
4274
			      "InnoDB: prev record ", stderr);
osku's avatar
osku committed
4275 4276
			dtuple_print(stderr, prev_entry);
			fputs("\n"
4277
			      "InnoDB: record ", stderr);
osku's avatar
osku committed
4278 4279 4280
			rec_print_new(stderr, rec, offsets);
			putc('\n', stderr);
			is_ok = FALSE;
4281
		} else if (dict_index_is_unique(index)
osku's avatar
osku committed
4282
			   && !contains_null
4283
			   && matched_fields
4284 4285
			   >= dict_index_get_n_ordering_defined_by_user(
				   index)) {
osku's avatar
osku committed
4286 4287 4288 4289 4290 4291

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

4292 4293
	{
		mem_heap_t*	tmp_heap = NULL;
4294

4295 4296 4297 4298 4299 4300 4301 4302 4303 4304
		/* 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);
		}
4305

4306
		mem_heap_empty(heap);
4307

4308 4309 4310
		prev_entry = row_rec_to_index_entry(ROW_COPY_DATA, rec,
						    index, offsets,
						    &n_ext, heap);
4311

4312 4313 4314
		if (UNIV_LIKELY_NULL(tmp_heap)) {
			mem_heap_free(tmp_heap);
		}
4315
	}
osku's avatar
osku committed
4316 4317 4318

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

4319
	goto loop;
osku's avatar
osku committed
4320 4321
}

4322
/*********************************************************************//**
4323 4324
Determines if a table is a magic monitor table.
@return	TRUE if monitor table */
4325 4326 4327 4328
UNIV_INTERN
ibool
row_is_magic_monitor_table(
/*=======================*/
4329
	const char*	table_name)	/*!< in: name of the table, in the
4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350
					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);
}