row0mysql.c 107 KB
Newer Older
1 2 3 4 5 6 7 8
/******************************************************
Interface between Innobase row operations and MySQL.
Contains also create table and other data dictionary operations.

(c) 2000 Innobase Oy

Created 9/17/2000 Heikki Tuuri
*******************************************************/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
9

10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include "row0mysql.h"

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

#include "row0ins.h"
#include "row0sel.h"
#include "row0upd.h"
#include "row0row.h"
#include "que0que.h"
#include "pars0pars.h"
#include "dict0dict.h"
#include "dict0crea.h"
24
#include "dict0load.h"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
25
#include "dict0boot.h"
26 27 28
#include "trx0roll.h"
#include "trx0purge.h"
#include "lock0lock.h"
29
#include "rem0cmp.h"
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
30
#include "log0log.h"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
31
#include "btr0sea.h"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
32 33
#include "fil0fil.h"
#include "ibuf0ibuf.h"
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
34

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
35 36 37
/* A dummy variable used to fool the compiler */
ibool	row_mysql_identically_false	= FALSE;

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
38 39 40 41 42 43 44 45 46 47
/* 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 the kernel mutex. */
typedef struct row_mysql_drop_struct	row_mysql_drop_t;
struct row_mysql_drop_struct{
	char*				table_name;
	UT_LIST_NODE_T(row_mysql_drop_t) row_mysql_drop_list;
};

UT_LIST_BASE_NODE_T(row_mysql_drop_t)	row_mysql_drop_list;
48
ibool	row_mysql_drop_list_inited	= FALSE;
49

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
/* Magic table names for invoking various monitor threads */
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";

/* Name suffix for recovered orphaned temporary tables */
static const char S_recover_innodb_tmp_table[] = "_recover_innodb_tmp_table";
/***********************************************************************
Determine if the given name ends in the suffix reserved for recovered
orphaned temporary tables. */
static
ibool
row_mysql_is_recovered_tmp_table(
/*=============================*/
				 /* out: TRUE if table name ends in
				 the reserved suffix */
	const char*	name)
{
	ulint	namelen	= strlen(name) + 1;
	return(namelen >= sizeof S_recover_innodb_tmp_table
		&& !memcmp(name + namelen -
			sizeof S_recover_innodb_tmp_table,
			S_recover_innodb_tmp_table,
			sizeof S_recover_innodb_tmp_table));
}

/***********************************************************************
Determine if the given name is a name reserved for MySQL system tables. */
static
ibool
row_mysql_is_system_table(
/*======================*/
				 /* out: TRUE if name is a MySQL
				 system table name */
	const char*	name)
{
88 89
	if (strncmp(name, "mysql/", 6) != 0) {

90 91
		return(FALSE);
	}
92

93
	return(0 == strcmp(name + 6, "host")
94 95
		|| 0 == strcmp(name + 6, "user")
		|| 0 == strcmp(name + 6, "db"));
96
}
97 98 99 100 101 102 103 104 105 106 107 108 109

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

110 111 112 113 114 115 116 117 118 119 120 121 122
/***********************************************************************
Frees the blob heap in prebuilt when no longer needed. */

void
row_mysql_prebuilt_free_blob_heap(
/*==============================*/
	row_prebuilt_t*	prebuilt)	/* in: prebuilt struct of a
					ha_innobase:: table handle */
{
	mem_heap_free(prebuilt->blob_heap);
	prebuilt->blob_heap = NULL;
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
/***********************************************************************
Stores a >= 5.0.3 format true VARCHAR length to dest, in the MySQL row
format. */

byte*
row_mysql_store_true_var_len(
/*=========================*/
			/* out: pointer to the data, we skip the 1 or 2 bytes
			at the start that are used to store the len */
	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 */
{
	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);
}

/***********************************************************************
Reads a >= 5.0.3 format true VARCHAR length, in the MySQL row format, and
returns a pointer to the data. */

byte*
row_mysql_read_true_varchar(
/*========================*/
			/* out: pointer to the data, we skip the 1 or 2 bytes
			at the start that are used to store the len */
	ulint*	len,	/* out: variable-length field length */
	byte*	field,	/* in: field in the MySQL format */
	ulint	lenlen)	/* in: storage length of len: either 1 or 2 bytes */
{
	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);
}

178 179 180 181 182 183 184 185 186
/***********************************************************************
Stores a reference to a BLOB in the MySQL format. */

void
row_mysql_store_blob_ref(
/*=====================*/
	byte*	dest,		/* in: where to store */
	ulint	col_len,	/* in: dest buffer size: determines into
				how many bytes the BLOB length is stored,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
187 188 189 190 191 192 193 194
				the space for the length may vary from 1
				to 4 bytes */
	byte*	data,		/* in: BLOB data; if the value to store
				is SQL NULL this should be NULL pointer */
	ulint	len)		/* in: BLOB length; if the value to store
				is SQL NULL this should be 0; remember
				also to set the NULL bit in the MySQL record
				header! */
195
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
196 197 198 199 200
	/* MySQL might assume the field is set to zero except the length and
	the pointer fields */

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

201 202 203 204 205
	/* 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. */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
206 207 208 209
	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);

210 211
	mach_write_to_n_little_endian(dest, col_len - 8, len);

212
	ut_memcpy(dest + col_len - 8, &data, sizeof(byte*));
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
}

/***********************************************************************
Reads a reference to a BLOB in the MySQL format. */

byte*
row_mysql_read_blob_ref(
/*====================*/
				/* out: pointer to BLOB data */
	ulint*	len,		/* out: BLOB length */
	byte*	ref,		/* in: BLOB reference in the MySQL format */
	ulint	col_len)	/* in: BLOB reference length (not BLOB
				length) */
{
	byte*	data;

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

231
	ut_memcpy(&data, ref + col_len - 8, sizeof(byte*));
232 233 234 235 236

	return(data);
}

/******************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
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
row0sel.c. */

byte*
row_mysql_store_col_in_innobase_format(
/*===================================*/
					/* out: up to which byte we used
					buf in the conversion */
	dfield_t*	dfield,		/* in/out: dfield where dtype
					information must be already set when
					this function is called! */
	byte*		buf,		/* in/out: buffer for a converted
					integer value; this must be at least
					col_len long then! */
	ibool		row_format_col,	/* TRUE if the mysql_data is from
					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! */
	byte*		mysql_data,	/* in: MySQL column value, not
					SQL NULL; NOTE that dfield may also
					get a pointer to mysql_data,
					therefore do not discard this as long
					as dfield is used! */
	ulint		col_len,	/* in: MySQL column length; NOTE that
					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 */
270
	ulint		comp)		/* in: nonzero=compact format */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
271
{
272
	byte*		ptr	= mysql_data;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
	dtype_t*	dtype;
	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. */

		ptr = buf + col_len;

		for (;;) {
			ptr--;
			*ptr = *mysql_data;
			if (ptr == buf) {
				break;
			}
			mysql_data++;
		}

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

			*ptr = (byte) (*ptr ^ 128);
		}

		buf += col_len;
	} else if ((type == DATA_VARCHAR
304 305
			|| type == DATA_VARMYSQL
			|| type == DATA_BINARY)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
306 307 308 309

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
311 312 313 314 315 316 317 318 319 320 321 322
			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,
323
				lenlen);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
		} else {
			/* Remove trailing spaces from old style VARCHAR
			columns. */

			/* Handle UCS2 strings differently. */
			ulint	mbminlen	= dtype_get_mbminlen(dtype);

			ptr = mysql_data;

			if (mbminlen == 2) {
				/* space=0x0020 */
				/* Trim "half-chars", just in case. */
				col_len &= ~1;

				while (col_len >= 2 && ptr[col_len - 2] == 0x00
						&& ptr[col_len - 1] == 0x20) {
					col_len -= 2;
				}
			} else {
				ut_a(mbminlen == 1);
				/* space=0x20 */
				while (col_len > 0
						&& ptr[col_len - 1] == 0x20) {
					col_len--;
				}
			}
		}
	} else if (comp && type == DATA_MYSQL
			&& dtype_get_mbminlen(dtype) == 1
			&& dtype_get_mbmaxlen(dtype) > 1) {
		/* 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
		bytes to store a latin1 string! */

		/* 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
366
		space padding.	If the field contains single-byte
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
367 368 369 370
		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
371
		be stored as "$%&a " (5 bytes).	 The string ".abc "
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
		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);
}

/******************************************************************
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. */
401 402 403 404 405 406
static
void
row_mysql_convert_row_to_innobase(
/*==============================*/
	dtuple_t*	row,		/* in/out: Innobase row where the
					field type information is already
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
407
					copied there! */
408 409 410 411 412 413 414
	row_prebuilt_t*	prebuilt,	/* in: prebuilt struct where template
					must be of type ROW_MYSQL_WHOLE_ROW */
	byte*		mysql_rec)	/* in: row in the MySQL format;
					NOTE: do not discard as long as
					row is used, as row may contain
					pointers to this record! */
{
415
	mysql_row_templ_t*	templ;
416 417
	dfield_t*		dfield;
	ulint			i;
418

419 420 421 422 423 424 425 426 427 428 429 430
	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;
		dfield = dtuple_get_nth_field(row, i);

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

			if (mysql_rec[templ->mysql_null_byte_offset] &
431
					(byte) (templ->mysql_null_bit_mask)) {
432 433 434 435 436 437 438

				/* It is SQL NULL */

				dfield_set_data(dfield, NULL, UNIV_SQL_NULL);

				goto next_column;
			}
439 440
		}

441
		row_mysql_store_col_in_innobase_format(dfield,
442 443 444 445 446 447
			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));
448 449
next_column:
		;
450
	}
451 452 453 454 455 456 457 458 459 460 461
}

/********************************************************************
Handles user errors and lock waits detected by the database engine. */

ibool
row_mysql_handle_errors(
/*====================*/
				/* out: TRUE if it was a lock wait and
				we should continue running the query thread */
	ulint*		new_err,/* out: possible new error encountered in
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
462 463 464
				lock wait, or if no new error, the value
				of trx->error_state at the entry of this
				function */
465 466
	trx_t*		trx,	/* in: transaction */
	que_thr_t*	thr,	/* in: query thread */
467
	trx_savept_t*	savept)	/* in: savepoint or NULL */
468
{
469
#ifndef UNIV_HOTBACKUP
470 471 472 473
	ulint	err;

handle_new_error:
	err = trx->error_state;
474

475
	ut_a(err != DB_SUCCESS);
476

477
	trx->error_state = DB_SUCCESS;
478

479 480
	if ((err == DB_DUPLICATE_KEY)
		|| (err == DB_FOREIGN_DUPLICATE_KEY)) {
481
		if (savept) {
482 483 484 485
			/* Roll back the latest, possibly incomplete
			insertion or update */

			trx_general_rollback_for_mysql(trx, TRUE, savept);
486
		}
487
	} else if (err == DB_TOO_BIG_RECORD) {
488
		if (savept) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
489 490 491 492 493
			/* Roll back the latest, possibly incomplete
			insertion or update */

			trx_general_rollback_for_mysql(trx, TRUE, savept);
		}
494
		/* MySQL will roll back the latest SQL statement */
495 496 497
	} else if (err == DB_ROW_IS_REFERENCED
		   || err == DB_NO_REFERENCED_ROW
		   || err == DB_CANNOT_ADD_CONSTRAINT) {
498
		if (savept) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
499 500 501 502 503
			/* Roll back the latest, possibly incomplete
			insertion or update */

			trx_general_rollback_for_mysql(trx, TRUE, savept);
		}
504
		/* MySQL will roll back the latest SQL statement */
505 506
	} else if (err == DB_LOCK_WAIT) {

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
507
		srv_suspend_mysql_thread(thr);
508

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
509
		if (trx->error_state != DB_SUCCESS) {
510 511 512 513 514 515 516 517 518
			que_thr_stop_for_mysql(thr);

			goto handle_new_error;
		}

		*new_err = err;

		return(TRUE);

519
	} else if (err == DB_DEADLOCK
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
520
		   || err == DB_LOCK_TABLE_FULL) {
521 522
		/* Roll back the whole transaction; this resolution was added
		to version 3.23.43 */
523

524
		trx_general_rollback_for_mysql(trx, FALSE, NULL);
525

526 527
	} else if (err == DB_OUT_OF_FILE_SPACE
		   || err == DB_LOCK_WAIT_TIMEOUT) {
528
		if (savept) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
529 530 531 532 533
			/* Roll back the latest, possibly incomplete
			insertion or update */

			trx_general_rollback_for_mysql(trx, TRUE, savept);
		}
534
		/* MySQL will roll back the latest SQL statement */
535 536 537

	} else if (err == DB_MUST_GET_MORE_FILE_SPACE) {

538
		fputs(
539 540
		"InnoDB: The database cannot continue operation because of\n"
		"InnoDB: lack of space. You must add a new data file to\n"
541
		"InnoDB: my.cnf and restart the database.\n", stderr);
542

543
		exit(1);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
544 545
	} else if (err == DB_CORRUPTION) {

546 547 548 549 550 551 552 553 554
		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"
	"InnoDB: http://dev.mysql.com/doc/mysql/en/Forcing_recovery.html"
	" for help.\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
555

556
	} else {
557 558
		fprintf(stderr, "InnoDB: unknown error code %lu\n",
			(ulong) err);
559
		ut_error;
560
	}
561 562 563 564 565 566

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

568 569 570
	trx->error_state = DB_SUCCESS;

	return(FALSE);
571 572 573 574 575
#else /* UNIV_HOTBACKUP */
	/* This function depends on MySQL code that is not included in
	InnoDB Hot Backup builds.  Besides, this function should never
	be called in InnoDB Hot Backup. */
	ut_error;
576
	return(FALSE);
577
#endif /* UNIV_HOTBACKUP */
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
}

/************************************************************************
Create a prebuilt struct for a MySQL table handle. */

row_prebuilt_t*
row_create_prebuilt(
/*================*/
				/* out, own: a prebuilt struct */
	dict_table_t*	table)	/* in: Innobase table handle */
{
	row_prebuilt_t*	prebuilt;
	mem_heap_t*	heap;
	dict_index_t*	clust_index;
	dtuple_t*	ref;
	ulint		ref_len;
	ulint		i;
595

596 597 598 599
	heap = mem_heap_create(128);

	prebuilt = mem_heap_alloc(heap, sizeof(row_prebuilt_t));

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
600
	prebuilt->magic_n = ROW_PREBUILT_ALLOCATED;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
601
	prebuilt->magic_n2 = ROW_PREBUILT_ALLOCATED;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
602

603 604 605 606 607 608
	prebuilt->table = table;

	prebuilt->trx = NULL;

	prebuilt->sql_stat_start = TRUE;

609 610
	prebuilt->mysql_has_locked = FALSE;

611
	prebuilt->index = NULL;
612 613 614

	prebuilt->used_in_HANDLER = FALSE;

615 616 617 618 619 620 621
	prebuilt->n_template = 0;
	prebuilt->mysql_template = NULL;

	prebuilt->heap = heap;
	prebuilt->ins_node = NULL;

	prebuilt->ins_upd_rec_buff = NULL;
622

623 624 625 626
	prebuilt->upd_node = NULL;
	prebuilt->ins_graph = NULL;
	prebuilt->upd_graph = NULL;

627 628
	prebuilt->pcur = btr_pcur_create_for_mysql();
	prebuilt->clust_pcur = btr_pcur_create_for_mysql();
629 630

	prebuilt->select_lock_type = LOCK_NONE;
631
	prebuilt->stored_select_lock_type = 99999999;
632

633 634
	prebuilt->row_read_type = ROW_READ_WITH_LOCKS;

635 636 637
	prebuilt->sel_graph = NULL;

	prebuilt->search_tuple = dtuple_create(heap,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
638
					2 * dict_table_get_n_cols(table));
639

640 641
	clust_index = dict_table_get_first_index(table);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
642 643 644
	/* Make sure that search_tuple is long enough for clustered index */
	ut_a(2 * dict_table_get_n_cols(table) >= clust_index->n_fields);

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
	ref_len = dict_index_get_n_unique(clust_index);

	ref = dtuple_create(heap, ref_len);

	dict_index_copy_types(ref, clust_index, ref_len);

	prebuilt->clust_ref = ref;

	for (i = 0; i < MYSQL_FETCH_CACHE_SIZE; i++) {
		prebuilt->fetch_cache[i] = NULL;
	}

	prebuilt->n_fetch_cached = 0;

	prebuilt->blob_heap = NULL;

	prebuilt->old_vers_heap = NULL;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
662

663 664 665 666 667 668 669 670 671 672 673 674 675
	return(prebuilt);
}

/************************************************************************
Free a prebuilt struct for a MySQL table handle. */

void
row_prebuilt_free(
/*==============*/
	row_prebuilt_t*	prebuilt)	/* in, own: prebuilt struct */
{
	ulint	i;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
676
	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED
677
		|| prebuilt->magic_n2 != ROW_PREBUILT_ALLOCATED) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
678
		fprintf(stderr,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
679
"InnoDB: Error: trying to free a corrupt\n"
monty@mishka.local's avatar
monty@mishka.local committed
680
"InnoDB: table handle. Magic n %lu, magic n2 %lu, table name",
681
		(ulong) prebuilt->magic_n,
monty@mishka.local's avatar
monty@mishka.local committed
682
		(ulong) prebuilt->magic_n2);
683
		ut_print_name(stderr, NULL, prebuilt->table->name);
684
		putc('\n', stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
685

686
		mem_analyze_corruption(prebuilt);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
687

688
		ut_error;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
689 690 691
	}

	prebuilt->magic_n = ROW_PREBUILT_FREED;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
692
	prebuilt->magic_n2 = ROW_PREBUILT_FREED;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
693

694 695 696 697 698 699 700 701 702 703 704 705 706 707
	btr_pcur_free_for_mysql(prebuilt->pcur);
	btr_pcur_free_for_mysql(prebuilt->clust_pcur);

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

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

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

709 710 711
	if (prebuilt->upd_graph) {
		que_graph_free_recursive(prebuilt->upd_graph);
	}
712

713 714 715 716 717 718 719
	if (prebuilt->blob_heap) {
		mem_heap_free(prebuilt->blob_heap);
	}

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

721 722
	for (i = 0; i < MYSQL_FETCH_CACHE_SIZE; i++) {
		if (prebuilt->fetch_cache[i] != NULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
723 724

			if ((ROW_PREBUILT_FETCH_MAGIC_N !=
725 726 727 728
					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))) {
729
				fputs(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
730
			"InnoDB: Error: trying to free a corrupt\n"
731
			"InnoDB: fetch buffer.\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
732 733 734 735

				mem_analyze_corruption(
						prebuilt->fetch_cache[i]);

736
				ut_error;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
737 738 739
			}

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

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
743 744
	dict_table_decrement_handle_count(prebuilt->table);

745 746 747 748 749 750 751 752 753 754 755 756 757 758
	mem_heap_free(prebuilt->heap);
}

/*************************************************************************
Updates the transaction pointers in query graphs stored in the prebuilt
struct. */

void
row_update_prebuilt_trx(
/*====================*/
					/* out: prebuilt dtuple */
	row_prebuilt_t*	prebuilt,	/* in: prebuilt struct in MySQL
					handle */
	trx_t*		trx)		/* in: transaction handle */
759
{
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
760
	if (trx->magic_n != TRX_MAGIC_N) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
761
		fprintf(stderr,
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
762 763
		"InnoDB: Error: trying to use a corrupt\n"
		"InnoDB: trx handle. Magic n %lu\n",
764
		(ulong) trx->magic_n);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
765

766
		mem_analyze_corruption(trx);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
767

768
		ut_error;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
769 770 771 772 773
	}

	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
		fprintf(stderr,
		"InnoDB: Error: trying to use a corrupt\n"
monty@mishka.local's avatar
monty@mishka.local committed
774 775
		"InnoDB: table handle. Magic n %lu, table name",
		(ulong) prebuilt->magic_n);
776
		ut_print_name(stderr, NULL, prebuilt->table->name);
777
		putc('\n', stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
778

779
		mem_analyze_corruption(prebuilt);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
780

781
		ut_error;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
782 783
	}

784 785 786 787 788 789 790 791 792 793 794 795
	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;
796
	}
797 798 799 800 801 802 803 804 805 806
}

/*************************************************************************
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
builds it. */
static
dtuple_t*
row_get_prebuilt_insert_row(
/*========================*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
807
					/* out: prebuilt dtuple; the column
808
					type information is also set in it */
809 810 811 812 813 814
	row_prebuilt_t*	prebuilt)	/* in: prebuilt struct in MySQL
					handle */
{
	ins_node_t*	node;
	dtuple_t*	row;
	dict_table_t*	table	= prebuilt->table;
815
	ulint		i;
816 817

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

819 820 821 822 823 824
	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);
825

826 827 828 829 830 831 832
		prebuilt->ins_node = node;

		if (prebuilt->ins_upd_rec_buff == NULL) {
			prebuilt->ins_upd_rec_buff = mem_heap_alloc(
						prebuilt->heap,
						prebuilt->mysql_row_len);
		}
833

834 835 836 837 838
		row = dtuple_create(prebuilt->heap,
					dict_table_get_n_cols(table));

		dict_table_copy_types(row, table);

839 840 841 842
		/* We init the value of every field to the SQL NULL to avoid
		a debug assertion from failing */

		for (i = 0; i < dtuple_get_n_fields(row); i++) {
843 844

			dtuple_get_nth_field(row, i)->len = UNIV_SQL_NULL;
845 846
		}

847 848 849 850 851 852 853 854 855 856
		ins_node_set_new_row(node, row);

		prebuilt->ins_graph =
			que_node_get_parent(
				pars_complete_graph_for_exec(node,
							prebuilt->trx,
							prebuilt->heap));
		prebuilt->ins_graph->state = QUE_FORK_ACTIVE;
	}

857
	return(prebuilt->ins_node->row);
858 859 860 861 862 863 864 865 866
}

/*************************************************************************
Updates the table modification counter and calculates new estimates
for table and index statistics if necessary. */
UNIV_INLINE
void
row_update_statistics_if_needed(
/*============================*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
867
	dict_table_t*	table)	/* in: table */
868 869
{
	ulint	counter;
870

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
871
	counter = table->stat_modified_counter;
872

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
873
	table->stat_modified_counter = counter + 1;
874 875 876

	/* Calculate new statistics if 1 / 16 of table has been modified
	since the last time a statistics batch was run, or if
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
877 878 879
	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. */
880 881

	if (counter > 2000000000
882
		|| ((ib_longlong)counter > 16 + table->stat_n_rows / 16)) {
883

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
884
		dict_update_statistics(table);
885
	}
886
}
887

888 889 890
/*************************************************************************
Unlocks an AUTO_INC type lock possibly reserved by trx. */

891
void
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
row_unlock_table_autoinc_for_mysql(
/*===============================*/
	trx_t*	trx)	/* in: transaction */
{
	if (!trx->auto_inc_lock) {

		return;
	}

	lock_table_unlock_auto_inc(trx);
}

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

int
row_lock_table_autoinc_for_mysql(
/*=============================*/
					/* out: error code or DB_SUCCESS */
	row_prebuilt_t*	prebuilt)	/* in: prebuilt struct in the MySQL
					table handle */
{
918
	trx_t*		trx		= prebuilt->trx;
919 920 921 922
	ins_node_t*	node		= prebuilt->ins_node;
	que_thr_t*	thr;
	ulint		err;
	ibool		was_lock_wait;
923

924 925
	ut_ad(trx);
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
926

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
927 928 929 930 931
	if (trx->auto_inc_lock) {

		return(DB_SUCCESS);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
932
	trx->op_info = "setting auto-inc lock";
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951

	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: */
952 953 954

	trx_start_if_not_started(trx);

955
	err = lock_table(0, prebuilt->table, LOCK_AUTO_INC, thr);
956 957 958 959 960 961 962 963 964 965 966 967

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

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
968
		trx->op_info = "";
969

970
		return((int) err);
971 972 973 974
	}

	que_thr_stop_for_mysql_no_error(thr, trx);

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
975
	trx->op_info = "";
976 977 978 979 980 981 982 983 984 985 986

	return((int) err);
}

/*************************************************************************
Sets a table lock on the table mentioned in prebuilt. */

int
row_lock_table_for_mysql(
/*=====================*/
					/* out: error code or DB_SUCCESS */
987
	row_prebuilt_t*	prebuilt,	/* in: prebuilt struct in the MySQL
988
					table handle */
989
	dict_table_t*	table,		/* in: table to lock, or NULL
990
					if prebuilt->table should be
991
					locked as
992
					prebuilt->select_lock_type */
993 994
	ulint		mode)		/* in: lock mode of table
					(ignored if table==NULL) */
995
{
996
	trx_t*		trx		= prebuilt->trx;
997 998 999
	que_thr_t*	thr;
	ulint		err;
	ibool		was_lock_wait;
1000

1001 1002 1003
	ut_ad(trx);
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1004
	trx->op_info = "setting table lock";
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

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

1025 1026
	trx_start_if_not_started(trx);

1027
	if (table) {
1028
		err = lock_table(0, table, mode, thr);
1029
	} else {
1030 1031
		err = lock_table(0, prebuilt->table,
				prebuilt->select_lock_type, thr);
1032
	}
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

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

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1045
		trx->op_info = "";
1046

1047
		return((int) err);
1048 1049 1050
	}

	que_thr_stop_for_mysql_no_error(thr, trx);
1051

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1052
	trx->op_info = "";
1053

1054
	return((int) err);
1055
}
1056

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
/*************************************************************************
Does an insert for MySQL. */

int
row_insert_for_mysql(
/*=================*/
					/* out: error code or DB_SUCCESS */
	byte*		mysql_rec,	/* in: row in the MySQL format */
	row_prebuilt_t*	prebuilt)	/* in: prebuilt struct in MySQL
					handle */
{
	trx_savept_t	savept;
	que_thr_t*	thr;
	ulint		err;
	ibool		was_lock_wait;
1072
	trx_t*		trx		= prebuilt->trx;
1073
	ins_node_t*	node		= prebuilt->ins_node;
1074

1075 1076
	ut_ad(trx);
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1077 1078

	if (prebuilt->table->ibd_file_missing) {
1079 1080
		ut_print_timestamp(stderr);
		fprintf(stderr, "  InnoDB: Error:\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
"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"
"http://dev.mysql.com/doc/mysql/en/InnoDB_troubleshooting_datadict.html\n"
"InnoDB: how you can resolve the problem.\n",
				prebuilt->table->name);
		return(DB_ERROR);
	}

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1092 1093 1094
	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
		fprintf(stderr,
		"InnoDB: Error: trying to free a corrupt\n"
monty@mishka.local's avatar
monty@mishka.local committed
1095 1096
		"InnoDB: table handle. Magic n %lu, table name",
		(ulong) prebuilt->magic_n);
1097
		ut_print_name(stderr, prebuilt->trx, prebuilt->table->name);
1098
		putc('\n', stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1099

1100
		mem_analyze_corruption(prebuilt);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1101

1102
		ut_error;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1103 1104
	}

1105
	if (srv_created_new_raw || srv_force_recovery) {
1106
		fputs(
1107 1108 1109 1110
		"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"
1111 1112
		"InnoDB: with raw, and innodb_force_... is removed.\n",
			stderr);
1113 1114 1115 1116

		return(DB_ERROR);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1117
	trx->op_info = "inserting";
1118

1119 1120
	row_mysql_delay_if_needed();

monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1121 1122
	trx_start_if_not_started(trx);

1123 1124 1125 1126 1127
	if (node == NULL) {
		row_get_prebuilt_insert_row(prebuilt);
		node = prebuilt->ins_node;
	}

1128
	row_mysql_convert_row_to_innobase(node->row, prebuilt, mysql_rec);
1129

1130
	savept = trx_savept_take(trx);
1131

1132 1133 1134 1135 1136 1137 1138 1139
	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;
	}
1140

1141 1142 1143 1144 1145 1146 1147
	que_thr_move_to_run_state_for_mysql(thr, trx);

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

	row_ins_step(thr);
1148

1149 1150 1151 1152
	err = trx->error_state;

	if (err != DB_SUCCESS) {
		que_thr_stop_for_mysql(thr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1153 1154 1155

/* TODO: what is this? */ thr->lock_state= QUE_THR_LOCK_ROW;

1156 1157
		was_lock_wait = row_mysql_handle_errors(&err, trx, thr,
								&savept);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1158 1159
		thr->lock_state= QUE_THR_LOCK_NOLOCK;

1160 1161 1162 1163
		if (was_lock_wait) {
			goto run_again;
		}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1164
		trx->op_info = "";
1165

1166
		return((int) err);
1167 1168 1169
	}

	que_thr_stop_for_mysql_no_error(thr, trx);
1170

1171 1172
	prebuilt->table->stat_n_rows++;

1173
	srv_n_rows_inserted++;
1174

1175 1176 1177
	if (prebuilt->table->stat_n_rows == 0) {
		/* Avoid wrap-over */
		prebuilt->table->stat_n_rows--;
1178
	}
1179

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1180
	row_update_statistics_if_needed(prebuilt->table);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1181
	trx->op_info = "";
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197

	return((int) err);
}

/*************************************************************************
Builds a dummy query graph used in selects. */

void
row_prebuild_sel_graph(
/*===================*/
	row_prebuilt_t*	prebuilt)	/* in: prebuilt struct in MySQL
					handle */
{
	sel_node_t*	node;

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

1199 1200 1201
	if (prebuilt->sel_graph == NULL) {

		node = sel_node_create(prebuilt->heap);
1202

1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
		prebuilt->sel_graph =
			que_node_get_parent(
				pars_complete_graph_for_exec(node,
							prebuilt->trx,
							prebuilt->heap));

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
/*************************************************************************
Creates an query graph node of 'update' type to be used in the MySQL
interface. */

upd_node_t*
row_create_update_node_for_mysql(
/*=============================*/
				/* out, own: update node */
	dict_table_t*	table,	/* in: table to update */
	mem_heap_t*	heap)	/* in: mem heap from which allocated */
{
	upd_node_t*	node;

	node = upd_node_create(heap);
1227

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
	node->in_mysql_interface = TRUE;
	node->is_delete = FALSE;
	node->searched_update = FALSE;
	node->select_will_do_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);
1239

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
	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);
}

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
/*************************************************************************
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
first builds it. */

upd_t*
row_get_prebuilt_update_vector(
/*===========================*/
					/* out: prebuilt update vector */
	row_prebuilt_t*	prebuilt)	/* in: prebuilt struct in MySQL
					handle */
{
	dict_table_t*	table	= prebuilt->table;
	upd_node_t*	node;

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

1267 1268 1269 1270 1271
	if (prebuilt->upd_node == NULL) {

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1272
		node = row_create_update_node_for_mysql(table, prebuilt->heap);
1273

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1274
		prebuilt->upd_node = node;
1275

1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
		prebuilt->upd_graph =
			que_node_get_parent(
				pars_complete_graph_for_exec(node,
							prebuilt->trx,
							prebuilt->heap));
		prebuilt->upd_graph->state = QUE_FORK_ACTIVE;
	}

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

/*************************************************************************
Does an update or delete of a row for MySQL. */

int
row_update_for_mysql(
/*=================*/
					/* out: error code or DB_SUCCESS */
	byte*		mysql_rec,	/* in: the row to be updated, in
					the MySQL format */
	row_prebuilt_t*	prebuilt)	/* in: prebuilt struct in MySQL
					handle */
{
	trx_savept_t	savept;
	ulint		err;
	que_thr_t*	thr;
	ibool		was_lock_wait;
1303
	dict_index_t*	clust_index;
1304
/*	ulint		ref_len; */
1305 1306 1307
	upd_node_t*	node;
	dict_table_t*	table		= prebuilt->table;
	trx_t*		trx		= prebuilt->trx;
1308

1309 1310
	ut_ad(prebuilt && trx);
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
1311
	UT_NOT_USED(mysql_rec);
1312

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1313
	if (prebuilt->table->ibd_file_missing) {
1314 1315
		ut_print_timestamp(stderr);
		fprintf(stderr, "  InnoDB: Error:\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
"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"
"http://dev.mysql.com/doc/mysql/en/InnoDB_troubleshooting_datadict.html\n"
"InnoDB: how you can resolve the problem.\n",
				prebuilt->table->name);
		return(DB_ERROR);
	}

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1327 1328 1329
	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
		fprintf(stderr,
		"InnoDB: Error: trying to free a corrupt\n"
monty@mishka.local's avatar
monty@mishka.local committed
1330 1331
		"InnoDB: table handle. Magic n %lu, table name",
		(ulong) prebuilt->magic_n);
1332
		ut_print_name(stderr, prebuilt->trx, prebuilt->table->name);
1333
		putc('\n', stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1334

1335
		mem_analyze_corruption(prebuilt);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1336

1337
		ut_error;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1338 1339
	}

1340
	if (srv_created_new_raw || srv_force_recovery) {
1341
		fputs(
1342 1343 1344 1345
		"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"
1346 1347
		"InnoDB: with raw, and innodb_force_... is removed.\n",
			stderr);
1348 1349 1350 1351

		return(DB_ERROR);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1352
	trx->op_info = "updating or deleting";
1353

1354 1355
	row_mysql_delay_if_needed();

monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1356 1357
	trx_start_if_not_started(trx);

1358 1359 1360 1361
	node = prebuilt->upd_node;

	clust_index = dict_table_get_first_index(table);

1362
	if (prebuilt->pcur->btr_cur.index == clust_index) {
1363
		btr_pcur_copy_stored_position(node->pcur, prebuilt->pcur);
1364
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1365 1366
		btr_pcur_copy_stored_position(node->pcur,
							prebuilt->clust_pcur);
1367
	}
1368

1369
	ut_a(node->pcur->rel_pos == BTR_PCUR_ON);
1370

1371 1372 1373 1374 1375 1376 1377
	/* 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 */

1378
	savept = trx_savept_take(trx);
1379

1380 1381 1382 1383 1384 1385 1386
	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);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1387

1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
run_again:
	thr->run_node = node;
	thr->prev_node = node;

	row_upd_step(thr);

	err = trx->error_state;

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

1399 1400
		if (err == DB_RECORD_NOT_FOUND) {
			trx->error_state = DB_SUCCESS;
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1401
			trx->op_info = "";
1402 1403 1404

			return((int) err);
		}
vtkachenko@intelp4d.mysql.com's avatar
vtkachenko@intelp4d.mysql.com committed
1405

1406
		thr->lock_state= QUE_THR_LOCK_ROW;
1407
		was_lock_wait = row_mysql_handle_errors(&err, trx, thr,
1408 1409 1410
			&savept);
		thr->lock_state= QUE_THR_LOCK_NOLOCK;

1411 1412 1413 1414
		if (was_lock_wait) {
			goto run_again;
		}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1415
		trx->op_info = "";
1416

1417
		return((int) err);
1418 1419 1420 1421
	}

	que_thr_stop_for_mysql_no_error(thr, trx);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1422
	if (node->is_delete) {
1423 1424 1425
		if (prebuilt->table->stat_n_rows > 0) {
			prebuilt->table->stat_n_rows--;
		}
1426 1427 1428 1429 1430

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1432
	row_update_statistics_if_needed(prebuilt->table);
1433

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1434
	trx->op_info = "";
1435

1436 1437 1438
	return((int) err);
}

1439
/*************************************************************************
1440 1441
This can only be used when srv_locks_unsafe_for_binlog is TRUE or
this session is using a READ COMMITTED isolation level. Before
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1442 1443 1444 1445 1446 1447 1448 1449
calling this function we must use trx_reset_new_rec_lock_info() and
trx_register_new_rec_lock() to store the information which new record locks
really were set. This function removes a newly set lock under prebuilt->pcur,
and also under prebuilt->clust_pcur. Currently, this is only used and tested
in the case of an UPDATE or a DELETE statement, where the row lock is of the
LOCK_X type.
Thus, this implements a 'mini-rollback' that releases the latest record
locks we set. */
1450 1451 1452 1453 1454

int
row_unlock_for_mysql(
/*=================*/
					/* out: error code or DB_SUCCESS */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1455
	row_prebuilt_t*	prebuilt,	/* in: prebuilt struct in MySQL
1456
					handle */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1457 1458 1459 1460
	ibool		has_latches_on_recs)/* 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. */
1461
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1462 1463 1464
	dict_index_t*	index;
	btr_pcur_t*	pcur		= prebuilt->pcur;
	btr_pcur_t*	clust_pcur	= prebuilt->clust_pcur;
1465
	trx_t*		trx		= prebuilt->trx;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1466
	rec_t*		rec;
1467 1468
	mtr_t		mtr;

1469 1470
	ut_ad(prebuilt && trx);
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
1471

1472 1473
	if (!(srv_locks_unsafe_for_binlog
	|| trx->isolation_level == TRX_ISO_READ_COMMITTED)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1474 1475 1476

		fprintf(stderr,
"InnoDB: Error: calling row_unlock_for_mysql though\n"
1477 1478
"InnoDB: srv_locks_unsafe_for_binlog is FALSE and\n"
"InnoDB: this session is not using READ COMMITTED isolation level.\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1479 1480 1481 1482

		return(DB_SUCCESS);
	}

1483 1484
	trx->op_info = "unlock_row";

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1485 1486 1487 1488 1489
	index = btr_pcur_get_btr_cur(pcur)->index;

	if (index != NULL && trx_new_rec_locks_contain(trx, index)) {

		mtr_start(&mtr);
1490

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1491
		/* Restore the cursor position and find the record */
1492

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1493 1494 1495
		if (!has_latches_on_recs) {
			btr_pcur_restore_position(BTR_SEARCH_LEAF, pcur, &mtr);
		}
1496

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1497
		rec = btr_pcur_get_rec(pcur);
1498

1499
		lock_rec_unlock(trx, rec, prebuilt->select_lock_type);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1500 1501 1502 1503 1504 1505 1506

		mtr_commit(&mtr);

		/* If the search was done through the clustered index, then
		we have not used clust_pcur at all, and we must NOT try to
		reset locks on clust_pcur. The values in clust_pcur may be
		garbage! */
1507

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1508
		if (index->type & DICT_CLUSTERED) {
1509

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1510
			goto func_exit;
1511
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1512 1513 1514 1515 1516 1517 1518
	}

	index = btr_pcur_get_btr_cur(clust_pcur)->index;

	if (index != NULL && trx_new_rec_locks_contain(trx, index)) {

		mtr_start(&mtr);
1519

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1520 1521 1522 1523 1524 1525 1526
		/* Restore the cursor position and find the record */

		if (!has_latches_on_recs) {
			btr_pcur_restore_position(BTR_SEARCH_LEAF, clust_pcur,
									&mtr);
		}

1527
		rec = btr_pcur_get_rec(clust_pcur);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1528

1529
		lock_rec_unlock(trx, rec, prebuilt->select_lock_type);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1530 1531

		mtr_commit(&mtr);
1532
	}
1533

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1534
func_exit:
1535
	trx->op_info = "";
1536

1537 1538 1539
	return(DB_SUCCESS);
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
/**************************************************************************
Does a cascaded delete or set null in a foreign key operation. */

ulint
row_update_cascade_for_mysql(
/*=========================*/
				/* out: error code or DB_SUCCESS */
	que_thr_t*	thr,	/* in: query thread */
	upd_node_t*	node,	/* in: update node used in the cascade
				or set null operation */
	dict_table_t*	table)	/* in: table where we do the operation */
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1552 1553
	ulint	err;
	trx_t*	trx;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563

	trx = thr_get_trx(thr);
run_again:
	thr->run_node = node;
	thr->prev_node = node;

	row_upd_step(thr);

	err = trx->error_state;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1564 1565 1566 1567
	/* 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. */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1568
	if (err == DB_LOCK_WAIT) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1569
		/* Handle lock wait here */
1570

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1571 1572 1573
		que_thr_stop_for_mysql(thr);

		srv_suspend_mysql_thread(thr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1574

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
		/* 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 */
1585

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
		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);
}

1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
/*************************************************************************
Checks if a table is such that we automatically created a clustered
index on it (on row id). */

ibool
row_table_got_default_clust_index(
/*==============================*/
	dict_table_t*	table)
{
	dict_index_t*	clust_index;

	clust_index = dict_table_get_first_index(table);

	if (dtype_get_mtype(dict_index_get_nth_type(clust_index, 0))
1623 1624
								== DATA_SYS) {
		return(TRUE);
1625 1626 1627 1628 1629
	}

	return(FALSE);
}

1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
/*************************************************************************
Calculates the key number used inside MySQL for an Innobase index. We have
to take into account if we generated a default clustered index for the table */

ulint
row_get_mysql_key_number_for_index(
/*===============================*/
	dict_index_t*	index)
{
	dict_index_t*	ind;
	ulint		i;

	ut_a(index);

	i = 0;
	ind = dict_table_get_first_index(index->table);

	while (index != ind) {
		ind = dict_table_get_next_index(ind);
		i++;
	}

	if (row_table_got_default_clust_index(index->table)) {
		ut_a(i > 0);
		i--;
	}

	return(i);
}

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
/*************************************************************************
Recovers an orphaned tmp table inside InnoDB by renaming it. In the table
name #sql becomes rsql, and "_recover_innodb_tmp_table" is catenated to
the end of name. table->name should be of the form
"dbname/rsql..._recover_innodb_tmp_table". This renames a table whose
name is "#sql..." */
static
int
row_mysql_recover_tmp_table(
/*========================*/
				/* out: error code or DB_SUCCESS */
	dict_table_t*	table,	/* in: table definition */
	trx_t*		trx)	/* in: transaction handle */
{
1674
	const char*	ptr	= strstr(table->name, "/rsql");
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1675

1676 1677
	if (!ptr) {
		/* table name does not begin with "/rsql" */
1678
		dict_mem_table_free(table);
1679
		trx_commit_for_mysql(trx);
1680

1681 1682 1683 1684
		return(DB_ERROR);
	}
	else {
		int	status;
1685
		int	namelen = (int) strlen(table->name);
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
		char*	old_name = mem_strdupl(table->name, namelen);
		/* replace "rsql" with "#sql" */
		old_name[ptr - table->name + 1] = '#';
		/* remove "_recover_innodb_tmp_table" suffix */
		ut_ad(namelen > (int) sizeof S_recover_innodb_tmp_table);
		ut_ad(!strcmp(old_name + namelen + 1 -
			sizeof S_recover_innodb_tmp_table,
			S_recover_innodb_tmp_table));
		old_name[namelen + 1 - sizeof S_recover_innodb_tmp_table] = 0;
		status = row_rename_table_for_mysql(old_name,
						table->name, trx);
		mem_free(old_name);
		return(status);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1699 1700 1701
	}
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1702
/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1703 1704
Locks the data dictionary in shared mode from modifications, for performing
foreign key check, rollback, or other operation invisible to MySQL. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1705 1706

void
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1707 1708 1709 1710 1711
row_mysql_freeze_data_dictionary(
/*=============================*/
	trx_t*	trx)	/* in: transaction */
{
	ut_a(trx->dict_operation_lock_mode == 0);
1712

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
	rw_lock_s_lock(&dict_operation_lock);

	trx->dict_operation_lock_mode = RW_S_LATCH;
}

/*************************************************************************
Unlocks the data dictionary shared lock. */

void
row_mysql_unfreeze_data_dictionary(
/*===============================*/
	trx_t*	trx)	/* in: transaction */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1725
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
	ut_a(trx->dict_operation_lock_mode == RW_S_LATCH);

	rw_lock_s_unlock(&dict_operation_lock);

	trx->dict_operation_lock_mode = 0;
}

/*************************************************************************
Locks the data dictionary exclusively for performing a table create or other
data dictionary modification operation. */

void
row_mysql_lock_data_dictionary(
/*===========================*/
	trx_t*	trx)	/* in: transaction */
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1742
	ut_a(trx->dict_operation_lock_mode == 0
1743 1744
		|| trx->dict_operation_lock_mode == RW_X_LATCH);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1745 1746 1747
	/* Serialize data dictionary operations with dictionary mutex:
	no deadlocks or lock waits can occur then in these operations */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1748
	rw_lock_x_lock(&dict_operation_lock);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1749 1750
	trx->dict_operation_lock_mode = RW_X_LATCH;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1751 1752 1753 1754
	mutex_enter(&(dict_sys->mutex));
}

/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1755
Unlocks the data dictionary exclusive lock. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1756 1757

void
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1758 1759 1760
row_mysql_unlock_data_dictionary(
/*=============================*/
	trx_t*	trx)	/* in: transaction */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1761
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1762 1763
	ut_a(trx->dict_operation_lock_mode == RW_X_LATCH);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1764 1765 1766 1767
	/* Serialize data dictionary operations with dictionary mutex:
	no deadlocks can occur then in these operations */

	mutex_exit(&(dict_sys->mutex));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1768
	rw_lock_x_unlock(&dict_operation_lock);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1769 1770

	trx->dict_operation_lock_mode = 0;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1771 1772
}

1773
/*************************************************************************
1774 1775 1776 1777
Does a table creation operation for MySQL.  If the name of the table
to be created is equal with one of the predefined magic table names,
then this also starts printing the corresponding monitor output by
the master thread. */
monty@mishka.local's avatar
monty@mishka.local committed
1778

1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
int
row_create_table_for_mysql(
/*=======================*/
				/* out: error code or DB_SUCCESS */
	dict_table_t*	table,	/* in: table definition */
	trx_t*		trx)	/* in: transaction handle */
{
	tab_node_t*	node;
	mem_heap_t*	heap;
	que_thr_t*	thr;
1789 1790
	const char*	table_name;
	ulint		table_name_len;
1791
	ulint		err;
1792
	ulint		i;
1793 1794

	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
1795
#ifdef UNIV_SYNC_DEBUG
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1796
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1797
	ut_ad(mutex_own(&(dict_sys->mutex)));
1798 1799
#endif /* UNIV_SYNC_DEBUG */
	ut_ad(trx->dict_operation_lock_mode == RW_X_LATCH);
1800

1801
	if (srv_created_new_raw) {
1802
		fputs(
1803 1804 1805 1806
		"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"
1807 1808
		"InnoDB: with raw, and innodb_force_... is removed.\n",
		stderr);
1809

1810
		dict_mem_table_free(table);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1811 1812
		trx_commit_for_mysql(trx);

1813 1814 1815
		return(DB_ERROR);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1816
	trx->op_info = "creating table";
1817

1818 1819
	if (row_mysql_is_system_table(table->name)) {

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1820 1821 1822 1823 1824
		fprintf(stderr,
    "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);

1825
		dict_mem_table_free(table);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1826 1827 1828 1829 1830
		trx_commit_for_mysql(trx);

		return(DB_ERROR);
	}

1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
	/* Check that no reserved column names are used. */
	for (i = 0; i < dict_table_get_n_user_cols(table); i++) {
		dict_col_t*	col = dict_table_get_nth_col(table, i);

		if (dict_col_name_is_reserved(col->name)) {

			dict_mem_table_free(table);
			trx_commit_for_mysql(trx);

			return(DB_ERROR);
		}
	}

monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1844 1845
	trx_start_if_not_started(trx);

1846
	if (row_mysql_is_recovered_tmp_table(table->name)) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1847 1848 1849 1850 1851 1852 1853

		/* MySQL prevents accessing of tables whose name begins
		with #sql, that is temporary tables. If mysqld crashes in
		the middle of an ALTER TABLE, we may get an orphaned
		#sql-table in the tablespace. We have here a special
		mechanism to recover such tables by renaming them to
		rsql... */
1854

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1855 1856 1857
		return(row_mysql_recover_tmp_table(table, trx));
	}

1858 1859 1860 1861 1862 1863 1864 1865
	/* 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;
1866

1867 1868
	if (table_name_len == sizeof S_innodb_monitor
			&& !memcmp(table_name, S_innodb_monitor,
1869
				sizeof S_innodb_monitor)) {
1870

1871
		/* Table equals "innodb_monitor":
1872
		start monitor prints */
1873

1874 1875 1876 1877 1878 1879
		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);
1880 1881
	} else if (table_name_len == sizeof S_innodb_lock_monitor
			&& !memcmp(table_name, S_innodb_lock_monitor,
1882
				sizeof S_innodb_lock_monitor)) {
1883 1884 1885 1886

		srv_print_innodb_monitor = TRUE;
		srv_print_innodb_lock_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1887 1888
	} else if (table_name_len == sizeof S_innodb_tablespace_monitor
			&& !memcmp(table_name, S_innodb_tablespace_monitor,
1889
				sizeof S_innodb_tablespace_monitor)) {
1890 1891 1892

		srv_print_innodb_tablespace_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1893 1894
	} else if (table_name_len == sizeof S_innodb_table_monitor
			&& !memcmp(table_name, S_innodb_table_monitor,
1895
				sizeof S_innodb_table_monitor)) {
1896 1897 1898

		srv_print_innodb_table_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1899 1900
	} else if (table_name_len == sizeof S_innodb_mem_validate
			&& !memcmp(table_name, S_innodb_mem_validate,
1901
				sizeof S_innodb_mem_validate)) {
1902
		/* We define here a debugging feature intended for
1903 1904
		developers */

1905
		fputs("Validating InnoDB memory:\n"
1906 1907 1908
		 "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"
1909
		"by any semaphore.\n", stderr);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1910
#ifdef UNIV_MEM_DEBUG
1911
		ut_a(mem_validate());
1912
		fputs("Memory validated\n", stderr);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1913
#else /* UNIV_MEM_DEBUG */
1914 1915
		fputs("Memory NOT validated (recompile with UNIV_MEM_DEBUG)\n",
			stderr);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1916
#endif /* UNIV_MEM_DEBUG */
1917 1918
	}

1919 1920 1921
	heap = mem_heap_create(512);

	trx->dict_operation = TRUE;
1922

1923 1924 1925 1926
	node = tab_create_graph_create(table, heap);

	thr = pars_complete_graph_for_exec(node, trx, heap);

1927
	ut_a(thr == que_fork_start_command(que_node_get_parent(thr)));
1928 1929 1930 1931 1932 1933
	que_run_threads(thr);

	err = trx->error_state;

	if (err != DB_SUCCESS) {
		/* We have special error handling here */
1934

1935
		trx->error_state = DB_SUCCESS;
1936

1937 1938
		trx_general_rollback_for_mysql(trx, FALSE, NULL);

1939
		if (err == DB_OUT_OF_FILE_SPACE) {
1940
			ut_print_timestamp(stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1941

1942
			fputs("  InnoDB: Warning: cannot create table ",
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1943
								stderr);
1944
			ut_print_name(stderr, trx, table->name);
1945
			fputs(" because tablespace full\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1946 1947 1948

			if (dict_table_get_low(table->name)) {

1949
				row_drop_table_for_mysql(table->name, trx,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1950 1951
								FALSE);
			}
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1952

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1953
		} else if (err == DB_DUPLICATE_KEY) {
1954
			ut_print_timestamp(stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1955

1956
			fputs("  InnoDB: Error: table ", stderr);
1957
			ut_print_name(stderr, trx, table->name);
1958
			fputs(" already exists in InnoDB internal\n"
1959
     "InnoDB: data dictionary. Have you deleted the .frm file\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1960
     "InnoDB: and not used DROP TABLE? Have you used DROP DATABASE\n"
1961
     "InnoDB: for InnoDB tables in MySQL version <= 3.23.43?\n"
1962
     "InnoDB: See the Restrictions section of the InnoDB manual.\n"
1963 1964
     "InnoDB: You can drop the orphaned table inside InnoDB by\n"
     "InnoDB: creating an InnoDB table with the same name in another\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1965
     "InnoDB: database and copying the .frm file to the current database.\n"
1966
     "InnoDB: Then MySQL thinks the table exists, and DROP TABLE will\n"
1967
     "InnoDB: succeed.\n"
1968 1969 1970
     "InnoDB: You can look for further help from\n"
     "InnoDB: http://dev.mysql.com/doc/mysql/en/"
     "InnoDB_troubleshooting_datadict.html\n", stderr);
1971
		}
1972

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1973 1974
		/* We may also get err == DB_ERROR if the .ibd file for the
		table already exists */
1975 1976 1977 1978 1979

		trx->error_state = DB_SUCCESS;
	}

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

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1981
	trx->op_info = "";
1982

1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
	return((int) err);
}

/*************************************************************************
Does an index creation operation for MySQL. TODO: currently failure
to create an index results in dropping the whole table! This is no problem
currently as all indexes must be created at the same time as the table. */

int
row_create_index_for_mysql(
/*=======================*/
					/* out: error number or DB_SUCCESS */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1995
	dict_index_t*	index,		/* in: index definition */
1996 1997 1998 1999 2000 2001 2002
	trx_t*		trx,		/* in: transaction handle */
	const ulint*	field_lengths)	/* in: if not NULL, must contain
					dict_index_get_n_fields(index)
					actual field lengths for the
					index columns, which are
					then checked for not being too
					large. */
2003 2004 2005 2006 2007
{
	ind_node_t*	node;
	mem_heap_t*	heap;
	que_thr_t*	thr;
	ulint		err;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2008
	ulint		i, j;
2009
	ulint		len;
2010

2011
#ifdef UNIV_SYNC_DEBUG
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2012
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2013
	ut_ad(mutex_own(&(dict_sys->mutex)));
2014
#endif /* UNIV_SYNC_DEBUG */
2015
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
2016

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2017
	trx->op_info = "creating index";
2018

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2019 2020
	trx_start_if_not_started(trx);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2021
	/* Check that the same column does not appear twice in the index.
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2022
	Starting from 4.0.14, InnoDB should be able to cope with that, but
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2023
	safer not to allow them. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2024 2025 2026 2027

	for (i = 0; i < dict_index_get_n_fields(index); i++) {
		for (j = 0; j < i; j++) {
			if (0 == ut_strcmp(
2028 2029
				    dict_index_get_nth_field(index, j)->name,
				    dict_index_get_nth_field(index, i)->name)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2030 2031 2032

				ut_print_timestamp(stderr);

2033
				fputs("  InnoDB: Error: column ", stderr);
2034
				ut_print_name(stderr, trx,
2035 2036
				dict_index_get_nth_field(index, i)->name);
				fputs(" appears twice in ", stderr);
2037
				dict_index_name_print(stderr, trx, index);
2038 2039 2040
				fputs("\n"
				"InnoDB: This is not allowed in InnoDB.\n",
					stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2041 2042 2043 2044 2045 2046

				err = DB_COL_APPEARS_TWICE_IN_INDEX;

				goto error_handling;
			}
		}
2047

2048 2049 2050 2051
		/* Check also that prefix_len and actual length
		< DICT_MAX_INDEX_COL_LEN */

		len = dict_index_get_nth_field(index, i)->prefix_len;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2052

2053 2054 2055
		if (field_lengths) {
			len = ut_max(len, field_lengths[i]);
		}
2056

2057
		if (len >= DICT_MAX_INDEX_COL_LEN) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2058 2059 2060 2061 2062
			err = DB_TOO_BIG_RECORD;

			goto error_handling;
		}
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2063

2064
	if (row_mysql_is_recovered_tmp_table(index->table_name)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2065 2066 2067 2068

		return(DB_SUCCESS);
	}

2069 2070 2071 2072
	heap = mem_heap_create(512);

	trx->dict_operation = TRUE;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2073 2074 2075
	/* Note that the space id where we store the index is inherited from
	the table in dict_build_index_def_step() in dict0crea.c. */

2076 2077 2078 2079
	node = ind_create_graph_create(index, heap);

	thr = pars_complete_graph_for_exec(node, trx, heap);

2080
	ut_a(thr == que_fork_start_command(que_node_get_parent(thr)));
2081 2082
	que_run_threads(thr);

2083
	err = trx->error_state;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2084 2085

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2087
error_handling:
2088 2089
	if (err != DB_SUCCESS) {
		/* We have special error handling here */
2090

2091 2092 2093 2094
		trx->error_state = DB_SUCCESS;

		trx_general_rollback_for_mysql(trx, FALSE, NULL);

2095
		row_drop_table_for_mysql(index->table_name, trx, FALSE);
2096 2097 2098

		trx->error_state = DB_SUCCESS;
	}
2099

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2100
	trx->op_info = "";
2101

2102 2103 2104
	return((int) err);
}

2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
/*************************************************************************
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
bot participating tables. The indexes are allowed to contain more
fields than mentioned in the constraint. Check also that foreign key
constraints which reference this table are ok. */

int
row_table_add_foreign_constraints(
/*==============================*/
2117 2118 2119 2120
					/* out: error code or DB_SUCCESS */
	trx_t*		trx,		/* in: transaction */
	const char*	sql_string,	/* in: table create statement where
					foreign keys are declared like:
2121
				FOREIGN KEY (a, b) REFERENCES table2(c, d),
2122 2123
					table2 can be written also with the
					database name before it: test.table2 */
2124
	const char*	name,		/* in: table full name in the
2125 2126
					normalized form
					database_name/table_name */
2127 2128 2129
	ibool		reject_fks)	/* in: if TRUE, fail with error
					code DB_CANNOT_ADD_CONSTRAINT if
					any foreign keys are found. */
2130 2131 2132
{
	ulint	err;

2133
#ifdef UNIV_SYNC_DEBUG
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2134
	ut_ad(mutex_own(&(dict_sys->mutex)));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2135
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
2136
#endif /* UNIV_SYNC_DEBUG */
2137
	ut_a(sql_string);
2138

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2139
	trx->op_info = "adding foreign keys";
2140

monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2141 2142
	trx_start_if_not_started(trx);

2143
	if (row_mysql_is_recovered_tmp_table(name)) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2144 2145 2146 2147

		return(DB_SUCCESS);
	}

2148 2149
	trx->dict_operation = TRUE;

2150 2151
	err = dict_create_foreign_constraints(trx, sql_string, name,
		reject_fks);
2152 2153 2154

	if (err == DB_SUCCESS) {
		/* Check that also referencing constraints are ok */
2155
		err = dict_load_foreigns(name, TRUE);
2156 2157 2158 2159
	}

	if (err != DB_SUCCESS) {
		/* We have special error handling here */
2160

2161 2162 2163 2164
		trx->error_state = DB_SUCCESS;

		trx_general_rollback_for_mysql(trx, FALSE, NULL);

2165
		row_drop_table_for_mysql(name, trx, FALSE);
2166 2167 2168 2169 2170 2171 2172

		trx->error_state = DB_SUCCESS;
	}

	return((int) err);
}

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
/*************************************************************************
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
in srv0srv.c. */
static
int
row_drop_table_for_mysql_in_background(
/*===================================*/
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2184 2185
				/* out: error code or DB_SUCCESS */
	const char*	name)	/* in: table name */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2186 2187 2188 2189 2190 2191
{
	ulint	error;
	trx_t*	trx;

	trx = trx_allocate_for_background();

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2192 2193 2194 2195 2196 2197
	/* 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;

2198 2199 2200 2201
/*	fputs("InnoDB: Error: Dropping table ", stderr);
	ut_print_name(stderr, name);
	fputs(" in background drop list\n", stderr); */

2202 2203 2204
	/* Try to drop the table in InnoDB */

	error = row_drop_table_for_mysql(name, trx, FALSE);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2205 2206 2207 2208

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2210
	log_buffer_flush_to_disk();
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2211

2212
	trx_commit_for_mysql(trx);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2213

2214
	trx_free_for_background(trx);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2215

2216
	return((int) error);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
}

/*************************************************************************
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
dropping of tables is needed in ALTER TABLE on Unix. */

ulint
row_drop_tables_for_mysql_in_background(void)
/*=========================================*/
					/* out: how many tables dropped
					+ remaining tables in list */
{
	row_mysql_drop_t*	drop;
	dict_table_t*		table;
	ulint			n_tables;
	ulint			n_tables_dropped = 0;
2234
loop:
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2235 2236 2237 2238 2239 2240 2241 2242 2243
	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);
2244

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2245 2246 2247 2248 2249
	n_tables = UT_LIST_GET_LEN(row_mysql_drop_list);

	mutex_exit(&kernel_mutex);

	if (drop == NULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2250
		/* All tables dropped */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2251 2252 2253 2254 2255 2256 2257 2258

		return(n_tables + n_tables_dropped);
	}

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

2259
	if (table == NULL) {
2260
		/* If for some reason the table has already been dropped
2261 2262
		through some other mechanism, do not try to drop it */

2263
		goto already_dropped;
2264
	}
2265

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2266 2267 2268 2269
	if (DB_SUCCESS != row_drop_table_for_mysql_in_background(
							drop->table_name)) {
		/* If the DROP fails for some table, we return, and let the
		main thread retry later */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2270 2271 2272 2273 2274 2275

		return(n_tables + n_tables_dropped);
	}

	n_tables_dropped++;

2276
already_dropped:
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2277 2278 2279 2280
	mutex_enter(&kernel_mutex);

	UT_LIST_REMOVE(row_mysql_drop_list, row_mysql_drop_list, drop);

2281
	ut_print_timestamp(stderr);
2282 2283 2284
	fprintf(stderr,
		"  InnoDB: Dropped table %s in background drop queue.\n",
		drop->table_name);
2285

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
	mem_free(drop->table_name);

	mem_free(drop);

	mutex_exit(&kernel_mutex);

	goto loop;
}

/*************************************************************************
Get the background drop list length. NOTE: the caller must own the kernel
mutex! */

ulint
row_get_background_drop_list_len_low(void)
/*======================================*/
					/* out: how many tables in list */
{
2304
#ifdef UNIV_SYNC_DEBUG
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2305
	ut_ad(mutex_own(&kernel_mutex));
2306
#endif /* UNIV_SYNC_DEBUG */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2307 2308 2309 2310 2311 2312

	if (!row_mysql_drop_list_inited) {

		UT_LIST_INIT(row_mysql_drop_list);
		row_mysql_drop_list_inited = TRUE;
	}
2313

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2314 2315 2316 2317
	return(UT_LIST_GET_LEN(row_mysql_drop_list));
}

/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2318 2319 2320 2321 2322
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
table lazily. */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2323
static
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2324
ibool
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2325 2326
row_add_table_to_background_drop_list(
/*==================================*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2327 2328
				/* out: TRUE if the table was not yet in the
				drop list, and was added there */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2329 2330 2331
	dict_table_t*	table)	/* in: table */
{
	row_mysql_drop_t*	drop;
2332

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2333 2334 2335 2336 2337 2338 2339
	mutex_enter(&kernel_mutex);

	if (!row_mysql_drop_list_inited) {

		UT_LIST_INIT(row_mysql_drop_list);
		row_mysql_drop_list_inited = TRUE;
	}
2340

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2341 2342 2343 2344 2345 2346
	/* Look if the table already is in the drop list */
	drop = UT_LIST_GET_FIRST(row_mysql_drop_list);

	while (drop != NULL) {
		if (strcmp(drop->table_name, table->name) == 0) {
			/* Already in the list */
2347

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2348 2349 2350 2351 2352 2353 2354
			mutex_exit(&kernel_mutex);

			return(FALSE);
		}

		drop = UT_LIST_GET_NEXT(row_mysql_drop_list, drop);
	}
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2355

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2356
	drop = mem_alloc(sizeof(row_mysql_drop_t));
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2357

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2358
	drop->table_name = mem_strdup(table->name);
2359

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2360
	UT_LIST_ADD_LAST(row_mysql_drop_list, row_mysql_drop_list, drop);
2361

2362 2363 2364 2365
/*	fputs("InnoDB: Adding table ", stderr);
	ut_print_name(stderr, drop->table_name);
	fputs(" to background drop list\n", stderr); */

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2366
	mutex_exit(&kernel_mutex);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2367 2368

	return(TRUE);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2369 2370
}

2371
#ifndef UNIV_HOTBACKUP
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2372 2373 2374
/*************************************************************************
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
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2375
the table. Also the flag table->ibd_file_missing is set TRUE. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2376

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
int
row_discard_tablespace_for_mysql(
/*=============================*/
				/* out: error code or DB_SUCCESS */
	const char*	name,	/* in: table name */
	trx_t*		trx)	/* in: transaction handle */
{
	dict_foreign_t*	foreign;
	dulint		new_id;
	dict_table_t*	table;
	ibool		success;
	ulint		err;
2389
	pars_info_t*	info = NULL;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2390

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2391
/* How do we prevent crashes caused by ongoing operations on the table? Old
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
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
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2407 2408 2409
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. */
2410

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2411 2412
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2413
	trx->op_info = "discarding tablespace";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
	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;
	}

2429 2430
	if (table->space == 0) {
		ut_print_timestamp(stderr);
2431
		fputs("  InnoDB: Error: table ", stderr);
2432
		ut_print_name(stderr, trx, name);
2433 2434
		fputs("\n"
"InnoDB: is in the system tablespace 0 which cannot be discarded\n", stderr);
2435 2436 2437 2438 2439
		err = DB_ERROR;

		goto funct_exit;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2440 2441
	if (table->n_foreign_key_checks_running > 0) {

2442 2443
		ut_print_timestamp(stderr);
		fputs("  InnoDB: You are trying to DISCARD table ", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
		ut_print_name(stderr, trx, table->name);
		fputs("\n"
		 "InnoDB: though there is a foreign key check running on it.\n"
		 "InnoDB: Cannot discard the table.\n",
			stderr);

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
	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);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2477
		fputs("  Cannot DISCARD table ", ef);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
		ut_print_name(ef, trx, name);
		fputs("\n"
			"because it is referenced by ", ef);
		ut_print_name(ef, trx, foreign->foreign_table_name);
		putc('\n', ef);
		mutex_exit(&dict_foreign_err_mutex);

		goto funct_exit;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2488 2489
	new_id = dict_hdr_get_new_id(DICT_HDR_TABLE_ID);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2490 2491 2492
	/* Remove any locks there are on the table or its records */
	lock_reset_all_on_table(table);

2493
	info = pars_info_create();
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2494

2495 2496
	pars_info_add_str_literal(info, "table_name", name);
	pars_info_add_dulint_literal(info, "new_id", new_id);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2497

2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
	err = que_eval_sql(info,
	"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"
	"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"
		, trx);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540

	if (err != DB_SUCCESS) {
		trx->error_state = DB_SUCCESS;
		trx_general_rollback_for_mysql(trx, FALSE, NULL);
		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;
			trx_general_rollback_for_mysql(trx, FALSE, NULL);
			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;
		}
	}
2541

2542
funct_exit:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2543 2544
	row_mysql_unlock_data_dictionary(trx);

2545
	trx_commit_for_mysql(trx);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2546

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2547
	trx->op_info = "";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558

	return((int) err);
}

/*********************************************************************
Imports a tablespace. The space id in the .ibd file must match the space id
of the table in the data dictionary. */

int
row_import_tablespace_for_mysql(
/*============================*/
2559 2560 2561
				/* out: error code or DB_SUCCESS */
	const char*	name,	/* in: table name */
	trx_t*		trx)	/* in: transaction handle */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2562 2563 2564
{
	dict_table_t*	table;
	ibool		success;
2565
	dulint		current_lsn;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2566 2567 2568 2569 2570 2571
	ulint		err		= DB_SUCCESS;

	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());

	trx_start_if_not_started(trx);

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2572
	trx->op_info = "importing tablespace";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2573

2574
	current_lsn = log_get_lsn();
2575

2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
	/* 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) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2591 2592 2593 2594 2595 2596
		ut_print_timestamp(stderr);
		fputs("  InnoDB: Error: cannot reset lsn's in table ", stderr);
		ut_print_name(stderr, trx, name);
		fputs("\n"
		"InnoDB: in ALTER TABLE ... IMPORT TABLESPACE\n", stderr);

2597 2598 2599 2600 2601 2602 2603
		err = DB_ERROR;

		row_mysql_lock_data_dictionary(trx);

		goto funct_exit;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2604 2605 2606 2607 2608 2609 2610 2611
	/* 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) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2612 2613 2614 2615 2616 2617 2618 2619
		ut_print_timestamp(stderr);
		fputs("  InnoDB: table ", stderr);
		ut_print_name(stderr, trx, name);
		fputs("\n"
"InnoDB: does not exist in the InnoDB data dictionary\n"
"InnoDB: in ALTER TABLE ... IMPORT TABLESPACE\n",
		stderr);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2620 2621 2622 2623 2624
		err = DB_TABLE_NOT_FOUND;

		goto funct_exit;
	}

2625 2626
	if (table->space == 0) {
		ut_print_timestamp(stderr);
2627
		fputs("  InnoDB: Error: table ", stderr);
2628
		ut_print_name(stderr, trx, name);
2629 2630
		fputs("\n"
"InnoDB: is in the system tablespace 0 which cannot be imported\n", stderr);
2631 2632 2633 2634 2635
		err = DB_ERROR;

		goto funct_exit;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2636 2637
	if (!table->tablespace_discarded) {
		ut_print_timestamp(stderr);
2638
		fputs(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2639
"  InnoDB: Error: you are trying to IMPORT a tablespace\n"
2640
"InnoDB: ", stderr);
2641
		ut_print_name(stderr, trx, name);
2642 2643
		fputs(", though you have not called DISCARD on it yet\n"
"InnoDB: during the lifetime of the mysqld process!\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2655 2656
	success = fil_open_single_table_tablespace(TRUE, table->space,
								table->name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2657 2658 2659 2660
	if (success) {
		table->ibd_file_missing = FALSE;
		table->tablespace_discarded = FALSE;
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2661 2662 2663
		if (table->ibd_file_missing) {
			ut_print_timestamp(stderr);
			fputs(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2664
"  InnoDB: cannot find or open in the database directory the .ibd file of\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2665 2666 2667 2668 2669 2670 2671
"InnoDB: table ", stderr);
			ut_print_name(stderr, trx, name);
			fputs("\n"
"InnoDB: in ALTER TABLE ... IMPORT TABLESPACE\n",
			stderr);
		}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2672 2673 2674
		err = DB_ERROR;
	}

2675
funct_exit:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2676 2677
	row_mysql_unlock_data_dictionary(trx);

2678
	trx_commit_for_mysql(trx);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2679

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2680
	trx->op_info = "";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2681 2682 2683 2684

	return((int) err);
}

2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704
/*************************************************************************
Truncates a table for MySQL. */

int
row_truncate_table_for_mysql(
/*=========================*/
				/* out: error code or DB_SUCCESS */
	dict_table_t*	table,	/* in: table handle */
	trx_t*		trx)	/* in: transaction handle */
{
	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;
	dulint		new_id;
2705
	pars_info_t*	info = NULL;
2706 2707 2708 2709 2710 2711

/* 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
2712 2713 2714
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.
2715 2716 2717
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.
2718 2719
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
2720
level. If a freed page is later reallocated, the allocator will remove
2721 2722 2723 2724 2725 2726
the ibuf entries for it.

TODO: when we truncate *.ibd files (analogous to DISCARD TABLESPACE), we
will have to remove we remove all entries for the table in the insert
buffer tree!

2727
4) Linear readahead and random readahead: we use the same method as in 3) to
2728
discard ongoing operations. (This will only be relevant for TRUNCATE TABLE
2729
by DISCARD TABLESPACE.)
2730
5) FOREIGN KEY operations: if table->n_foreign_key_checks_running > 0, we
2731
do not allow the TRUNCATE. We also reserve the data dictionary latch. */
2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742

	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
	ut_ad(table);

	if (srv_created_new_raw) {
		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",
2743
		stderr);
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754

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

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

2759
	row_mysql_lock_data_dictionary(trx);
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786

#ifdef UNIV_SYNC_DEBUG
	ut_ad(mutex_own(&(dict_sys->mutex)));
	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);

		fputs("  Cannot truncate table ", ef);
		ut_print_name(ef, trx, table->name);
2787 2788
		fputs(" by DROP+CREATE\n"
			"InnoDB: because it is referenced by ", ef);
2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804
		ut_print_name(ef, trx, foreign->foreign_table_name);
		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);
2805
		fputs("  InnoDB: Cannot truncate table ", stderr);
2806
		ut_print_name(stderr, trx, table->name);
2807 2808
		fputs(" by DROP+CREATE\n"
"InnoDB: because there is a foreign key check running on it.\n",
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
			stderr);
		err = DB_ERROR;

		goto funct_exit;
	}

	/* Remove any locks there are on the table or its records */

	lock_reset_all_on_table(table);

	trx->table_id = table->id;

	/* scan SYS_INDEXES for all indexes of the table */
	heap = mem_heap_create(800);

	tuple = dtuple_create(heap, 1);
	dfield = dtuple_get_nth_field(tuple, 0);

	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,
						BTR_MODIFY_LEAF, &pcur, &mtr);
	for (;;) {
		rec_t*		rec;
		const byte*	field;
		ulint		len;
2841
		ulint		root_page_no;
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859

		if (!btr_pcur_is_on_user_rec(&pcur, &mtr)) {
			/* 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. */
2860
			goto next_rec;
2861 2862
		}

2863
		btr_pcur_store_position(&pcur, &mtr);
2864

2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
		/* This call may commit and restart mtr. */
		root_page_no = dict_truncate_index_tree(table, rec, &mtr);

		btr_pcur_restore_position(BTR_MODIFY_LEAF, &pcur, &mtr);
		rec = btr_pcur_get_rec(&pcur);

		if (root_page_no != FIL_NULL) {
			page_rec_write_index_page_no(rec,
					DICT_SYS_INDEXES_PAGE_NO_FIELD,
					root_page_no, &mtr);
			/* 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,
							&pcur, &mtr);
		}

	next_rec:
2887 2888 2889 2890 2891 2892 2893 2894
		btr_pcur_move_to_next_user_rec(&pcur, &mtr);
	}

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

	mem_heap_free(heap);

2895
	new_id = dict_hdr_get_new_id(DICT_HDR_TABLE_ID);
2896

2897
	info = pars_info_create();
2898

2899 2900
	pars_info_add_dulint_literal(info, "old_id", table->id);
	pars_info_add_dulint_literal(info, "new_id", new_id);
2901

2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
	err = que_eval_sql(info,
		"PROCEDURE RENUMBER_TABLESPACE_PROC () IS\n"
		"BEGIN\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"
		, trx);
2914 2915 2916 2917 2918 2919

	if (err != DB_SUCCESS) {
		trx->error_state = DB_SUCCESS;
		trx_general_rollback_for_mysql(trx, FALSE, NULL);
		trx->error_state = DB_SUCCESS;
		ut_print_timestamp(stderr);
2920
fputs("  InnoDB: Unable to assign a new identifier to table ", stderr);
2921 2922 2923 2924 2925 2926 2927 2928 2929
		ut_print_name(stderr, trx, table->name);
		fputs("\n"
"InnoDB: after truncating it.  Background processes may corrupt the table!\n",
			stderr);
		err = DB_ERROR;
	} else {
		dict_table_change_id_in_cache(table, new_id);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2930
	dict_table_autoinc_initialize(table, 0);
2931 2932
	dict_update_statistics(table);

2933
	trx_commit_for_mysql(trx);
2934 2935 2936

funct_exit:

2937
	row_mysql_unlock_data_dictionary(trx);
2938 2939 2940 2941 2942 2943 2944

	trx->op_info = "";

	srv_wake_master_thread();

	return((int) err);
}
2945
#endif /* !UNIV_HOTBACKUP */
2946

2947
/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2948
Drops a table for MySQL. If the name of the table to be dropped is equal
2949 2950
with one of the predefined magic table names, then this also stops printing
the corresponding monitor output by the master thread. */
2951 2952 2953 2954

int
row_drop_table_for_mysql(
/*=====================*/
2955 2956 2957 2958
				/* out: error code or DB_SUCCESS */
	const char*	name,	/* in: table name */
	trx_t*		trx,	/* in: transaction handle */
	ibool		drop_db)/* in: TRUE=dropping whole database */
2959
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2960
	dict_foreign_t*	foreign;
2961
	dict_table_t*	table;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2962
	ulint		space_id;
2963
	ulint		err;
2964
	const char*	table_name;
2965
	ulint		namelen;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2966
	char*		dir_path_of_temp_table	= NULL;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2967
	ibool		success;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2968
	ibool		locked_dictionary	= FALSE;
2969
	pars_info_t*    info			= NULL;
2970

2971 2972 2973 2974 2975 2976 2977 2978 2979
	ut_a(name != NULL);

	if (srv_created_new_raw) {
		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",
2980
		stderr);
2981 2982 2983 2984

		return(DB_ERROR);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2985
	trx->op_info = "dropping table";
2986 2987

	trx_start_if_not_started(trx);
2988

2989 2990 2991 2992 2993 2994 2995 2996
	/* 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;
2997

2998
	if (namelen == sizeof S_innodb_monitor
2999
			&& !memcmp(table_name, S_innodb_monitor,
3000
				sizeof S_innodb_monitor)) {
3001

3002 3003
		/* Table name equals "innodb_monitor":
		stop monitor prints */
3004

3005 3006 3007
		srv_print_innodb_monitor = FALSE;
		srv_print_innodb_lock_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_lock_monitor
3008
			&& !memcmp(table_name, S_innodb_lock_monitor,
3009 3010 3011 3012
				sizeof S_innodb_lock_monitor)) {
		srv_print_innodb_monitor = FALSE;
		srv_print_innodb_lock_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_tablespace_monitor
3013
			&& !memcmp(table_name, S_innodb_tablespace_monitor,
3014
				sizeof S_innodb_tablespace_monitor)) {
3015

3016 3017
		srv_print_innodb_tablespace_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_table_monitor
3018
			&& !memcmp(table_name, S_innodb_table_monitor,
3019
				sizeof S_innodb_table_monitor)) {
3020

3021 3022 3023
		srv_print_innodb_table_monitor = FALSE;
	}

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3027
	if (trx->dict_operation_lock_mode != RW_X_LATCH) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3028 3029
		/* Prevent foreign key checks etc. while we are dropping the
		table */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3030

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3031 3032 3033
		row_mysql_lock_data_dictionary(trx);

		locked_dictionary = TRUE;
3034 3035
	}

3036
#ifdef UNIV_SYNC_DEBUG
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3037 3038
	ut_ad(mutex_own(&(dict_sys->mutex)));
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
3039
#endif /* UNIV_SYNC_DEBUG */
3040

3041 3042 3043 3044
	table = dict_table_get_low(name);

	if (!table) {
		err = DB_TABLE_NOT_FOUND;
3045
		ut_print_timestamp(stderr);
3046

3047
		fputs("  InnoDB: Error: table ", stderr);
3048
		ut_print_name(stderr, trx, name);
3049
		fputs(" does not exist in the InnoDB internal\n"
3050 3051
	"InnoDB: data dictionary though MySQL is trying to drop it.\n"
	"InnoDB: Have you copied the .frm file of the table to the\n"
3052
	"InnoDB: MySQL database directory from another database?\n"
3053 3054 3055
	"InnoDB: You can look for further help from\n"
	"InnoDB: http://dev.mysql.com/doc/mysql/en/"
	"InnoDB_troubleshooting_datadict.html\n", stderr);
3056 3057 3058
		goto funct_exit;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3059 3060 3061
	/* Check if the table is referenced by foreign key constraints from
	some other table (not the table itself) */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3062
	foreign = UT_LIST_GET_FIRST(table->referenced_list);
3063

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3064
	while (foreign && foreign->foreign_table == table) {
3065
	check_next_foreign:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3066 3067 3068
		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}

3069 3070 3071
	if (foreign && trx->check_foreigns &&
		!(drop_db && dict_tables_have_same_db(
			name, foreign->foreign_table_name))) {
3072
		FILE*	ef	= dict_foreign_err_file;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3073 3074 3075 3076 3077 3078 3079

		/* 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);
3080 3081 3082 3083
		rewind(ef);
		ut_print_timestamp(ef);

		fputs("  Cannot drop table ", ef);
3084
		ut_print_name(ef, trx, name);
3085 3086
		fputs("\n"
			"because it is referenced by ", ef);
3087
		ut_print_name(ef, trx, foreign->foreign_table_name);
3088
		putc('\n', ef);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3089 3090 3091 3092 3093
		mutex_exit(&dict_foreign_err_mutex);

		goto funct_exit;
	}

3094 3095 3096 3097
	if (foreign && trx->check_foreigns) {
		goto check_next_foreign;
	}

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3098
	if (table->n_mysql_handles_opened > 0) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3099
		ibool	added;
3100

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3101
		added = row_add_table_to_background_drop_list(table);
3102

3103
		if (added) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3104
			ut_print_timestamp(stderr);
3105
fputs("  InnoDB: Warning: MySQL is trying to drop table ", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3106 3107 3108 3109 3110
			ut_print_name(stderr, trx, 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);
3111

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3112 3113
			/* We return DB_SUCCESS to MySQL though the drop will
			happen lazily later */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3114

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3115 3116 3117 3118 3119
			err = DB_SUCCESS;
		} else {
			/* The table is already in the background drop list */
			err = DB_ERROR;
		}
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3120

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3121
		goto funct_exit;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3122
	}
3123

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3124 3125 3126 3127 3128 3129
	/* 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. */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3130
	if (table->n_foreign_key_checks_running > 0) {
3131

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3132 3133 3134 3135 3136
		ibool	added;

		added = row_add_table_to_background_drop_list(table);

		if (added) {
3137 3138
			ut_print_timestamp(stderr);
fputs("  InnoDB: You are trying to drop table ", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3139 3140 3141 3142
			ut_print_name(stderr, trx, table->name);
			fputs("\n"
"InnoDB: though there is a foreign key check running on it.\n"
"InnoDB: Adding the table to the background drop queue.\n",
3143
			stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3144

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3145 3146
			/* We return DB_SUCCESS to MySQL though the drop will
			happen lazily later */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3147

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3148 3149 3150 3151 3152
			err = DB_SUCCESS;
		} else {
			/* The table is already in the background drop list */
			err = DB_ERROR;
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3153 3154 3155

		goto funct_exit;
	}
3156

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3157
	/* Remove any locks there are on the table or its records */
3158

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3159 3160
	lock_reset_all_on_table(table);

3161 3162 3163
	trx->dict_operation = TRUE;
	trx->table_id = table->id;

3164 3165 3166 3167
	/* 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. */
3168

3169
	info = pars_info_create();
3170

3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
	pars_info_add_str_literal(info, "table_name", name);

	err = que_eval_sql(info,
	"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"
	"BEGIN\n"
	"SELECT ID INTO table_id\n"
	"FROM SYS_TABLES\n"
	"WHERE NAME = :table_name;\n"
	"IF (SQL % NOTFOUND) THEN\n"
	"       COMMIT WORK;\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"
	"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"
	"WHILE found = 1 LOOP\n"
	"       SELECT ID INTO foreign_id\n"
	"       FROM SYS_FOREIGN\n"
	"       WHERE FOR_NAME = :table_name\n"
	"               AND TO_BINARY(FOR_NAME) = TO_BINARY(:table_name);\n"
	"       IF (SQL % NOTFOUND) THEN\n"
	"               found := 0;\n"
	"       ELSE"
	"               DELETE FROM SYS_FOREIGN_COLS WHERE ID = foreign_id;\n"
	"               DELETE FROM SYS_FOREIGN WHERE ID = foreign_id;\n"
	"       END IF;\n"
	"END LOOP;\n"
	"found := 1;\n"
	"WHILE found = 1 LOOP\n"
	"       SELECT ID INTO index_id\n"
	"       FROM SYS_INDEXES\n"
	"       WHERE TABLE_ID = table_id;\n"
	"       IF (SQL % NOTFOUND) THEN\n"
	"               found := 0;\n"
	"       ELSE"
	"               DELETE FROM SYS_FIELDS WHERE INDEX_ID = index_id;\n"
	"               DELETE FROM SYS_INDEXES WHERE ID = index_id\n"
	"                                        AND TABLE_ID = table_id;\n"
	"       END IF;\n"
	"END LOOP;\n"
	"DELETE FROM SYS_COLUMNS WHERE TABLE_ID = table_id;\n"
	"DELETE FROM SYS_TABLES WHERE ID = table_id;\n"
	"COMMIT WORK;\n"
	"END;\n"
		, trx);
3231 3232 3233 3234 3235

	if (err != DB_SUCCESS) {
		ut_a(err == DB_OUT_OF_FILE_SPACE);

		err = DB_MUST_GET_MORE_FILE_SPACE;
3236

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

3239
		ut_error;
3240
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3241 3242 3243
		ibool		is_path;
		const char*	name_or_path;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3244
		space_id = table->space;
3245

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3246 3247 3248 3249 3250 3251 3252 3253 3254 3255
		if (table->dir_path_of_temp_table != NULL) {
			dir_path_of_temp_table =
				mem_strdup(table->dir_path_of_temp_table);
			is_path = TRUE;
			name_or_path = dir_path_of_temp_table;
		} else {
			is_path = FALSE;
			name_or_path = name;
		}

3256
		dict_table_remove_from_cache(table);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3257 3258 3259

		if (dict_load_table(name) != NULL) {
			ut_print_timestamp(stderr);
monty@mishka.local's avatar
monty@mishka.local committed
3260
			fputs("  InnoDB: Error: not able to remove table ",
3261
				stderr);
3262
			ut_print_name(stderr, trx, name);
monty@mishka.local's avatar
monty@mishka.local committed
3263
			fputs(" from the dictionary cache!\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3264 3265 3266 3267 3268 3269
			err = DB_ERROR;
		}

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3270
		if (err == DB_SUCCESS && space_id > 0) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3271 3272 3273
			if (!fil_space_for_table_exists_in_mem(space_id,
								name_or_path,
								is_path,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3274
								FALSE, TRUE)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3275 3276 3277 3278
				err = DB_SUCCESS;

				fprintf(stderr,
"InnoDB: We removed now the InnoDB internal data dictionary entry\n"
3279
"InnoDB: of table ");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3280 3281
				ut_print_name(stderr, trx, name);
				fprintf(stderr, ".\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3282 3283 3284

				goto funct_exit;
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3285

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3286 3287 3288
			success = fil_delete_tablespace(space_id);

			if (!success) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3289 3290
				fprintf(stderr,
"InnoDB: We removed now the InnoDB internal data dictionary entry\n"
3291
"InnoDB: of table ");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3292 3293 3294
				ut_print_name(stderr, trx, name);
				fprintf(stderr, ".\n");

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3295 3296
				ut_print_timestamp(stderr);
				fprintf(stderr,
3297 3298
"  InnoDB: Error: not able to delete tablespace %lu of table ",
					(ulong) space_id);
3299
				ut_print_name(stderr, trx, name);
3300
				fputs("!\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3301 3302
				err = DB_ERROR;
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3303
		}
3304
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3305
funct_exit:
3306

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3307
	if (locked_dictionary) {
3308
		row_mysql_unlock_data_dictionary(trx);
3309 3310
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3311 3312 3313 3314
	if (dir_path_of_temp_table) {
		mem_free(dir_path_of_temp_table);
	}

3315
	trx_commit_for_mysql(trx);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3316

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3317
	trx->op_info = "";
3318

3319
#ifndef UNIV_HOTBACKUP
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3320
	srv_wake_master_thread();
3321
#endif /* !UNIV_HOTBACKUP */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3322

3323 3324 3325
	return((int) err);
}

3326 3327 3328 3329 3330 3331
/*************************************************************************
Drops a database for MySQL. */

int
row_drop_database_for_mysql(
/*========================*/
3332 3333 3334
				/* out: error code or DB_SUCCESS */
	const char*	name,	/* in: database name which ends to '/' */
	trx_t*		trx)	/* in: transaction handle */
3335
{
3336
	dict_table_t* table;
3337 3338
	char*	table_name;
	int	err	= DB_SUCCESS;
3339
	ulint	namelen	= strlen(name);
3340

3341 3342
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
	ut_a(name != NULL);
3343
	ut_a(name[namelen - 1] == '/');
3344

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3345
	trx->op_info = "dropping database";
3346

monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
3347
	trx_start_if_not_started(trx);
3348
loop:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3349
	row_mysql_lock_data_dictionary(trx);
3350

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

3354 3355 3356 3357 3358 3359 3360 3361
		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) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3362
			row_mysql_unlock_data_dictionary(trx);
3363

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3364
			ut_print_timestamp(stderr);
3365 3366
			fputs(
	"  InnoDB: Warning: MySQL is trying to drop database ", stderr);
3367
			ut_print_name(stderr, trx, name);
3368 3369
			fputs("\n"
	"InnoDB: though there are still open handles to table ", stderr);
3370
			ut_print_name(stderr, trx, table_name);
3371
			fputs(".\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3372

3373
			os_thread_sleep(1000000);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3374

3375
			mem_free(table_name);
3376

3377
			goto loop;
3378 3379
		}

3380
		err = row_drop_table_for_mysql(table_name, trx, TRUE);
3381 3382 3383 3384

		mem_free(table_name);

		if (err != DB_SUCCESS) {
3385
			fputs("InnoDB: DROP DATABASE ", stderr);
3386
			ut_print_name(stderr, trx, name);
3387 3388
			fprintf(stderr, " failed with error %lu for table ",
				(ulint) err);
3389
			ut_print_name(stderr, trx, table_name);
3390
			putc('\n', stderr);
3391 3392 3393 3394
			break;
		}
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3395
	row_mysql_unlock_data_dictionary(trx);
3396

3397 3398
	trx_commit_for_mysql(trx);

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3399
	trx->op_info = "";
3400 3401 3402 3403

	return(err);
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3404 3405 3406 3407 3408 3409 3410
/*************************************************************************
Checks if a table name contains the string "/#sql" which denotes temporary
tables in MySQL. */
static
ibool
row_is_mysql_tmp_table_name(
/*========================*/
3411 3412 3413
				/* out: TRUE if temporary table */
	const char*	name)	/* in: table name in the form
				'database/tablename' */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3414
{
3415
	/* return(strstr(name, "/#sql") != NULL); */
3416
	return(strstr(name, "/@0023sql") != NULL);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3417 3418
}

3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474
/********************************************************************
Delete a single constraint. */
static
int
row_delete_constraint_low(
/*======================*/
					/* out: error code or DB_SUCCESS */
	const char*	id,		/* in: constraint id */
	trx_t*		trx)		/* in: transaction handle */
{
	pars_info_t*	info = pars_info_create();

	pars_info_add_str_literal(info, "id", id);

	return(que_eval_sql(info,
		"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"
		, trx));
}

/********************************************************************
Delete a single constraint. */
static
int
row_delete_constraint(
/*==================*/
					/* out: error code or DB_SUCCESS */
	const char*	id,		/* in: constraint id */
	const char*	database_name,	/* in: database name, with the
					trailing '/' */
	mem_heap_t*	heap,		/* in: memory heap */
	trx_t*		trx)		/* in: transaction handle */
{
	ulint		err;

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

	if ((err == DB_SUCCESS) && !strchr(id, '/')) {
		/* Old format < 4.0.18 constraints have constraint ids
		<number>_<number>. We only try deleting them if the
		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);
	}

	return(err);
}

3475 3476 3477 3478 3479 3480
/*************************************************************************
Renames a table for MySQL. */

int
row_rename_table_for_mysql(
/*=======================*/
3481 3482 3483 3484
					/* out: error code or DB_SUCCESS */
	const char*	old_name,	/* in: old table name */
	const char*	new_name,	/* in: new table name */
	trx_t*		trx)		/* in: transaction handle */
3485 3486 3487
{
	dict_table_t*	table;
	ulint		err;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3488
	mem_heap_t*	heap			= NULL;
3489
	const char**	constraints_to_drop	= NULL;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3490
	ulint		n_constraints_to_drop	= 0;
3491 3492
	ibool		recovering_temp_table	= FALSE;
	ibool		old_is_tmp, new_is_tmp;
3493
	pars_info_t*	info			= NULL;
3494 3495 3496 3497 3498

	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
	ut_a(old_name != NULL);
	ut_a(new_name != NULL);

3499
	if (srv_created_new_raw || srv_force_recovery) {
3500
		fputs(
3501 3502 3503 3504
		"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"
3505 3506
		"InnoDB: with raw, and innodb_force_... is removed.\n",
		stderr);
3507

3508
		trx_commit_for_mysql(trx);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3509 3510
		return(DB_ERROR);
	}
3511

3512
	if (row_mysql_is_system_table(new_name)) {
3513

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3514 3515 3516 3517 3518
		fprintf(stderr,
    "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);

3519
		trx_commit_for_mysql(trx);
3520 3521 3522
		return(DB_ERROR);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3523
	trx->op_info = "renaming table";
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
3524
	trx_start_if_not_started(trx);
3525

3526 3527 3528
	old_is_tmp = row_is_mysql_tmp_table_name(old_name);
	new_is_tmp = row_is_mysql_tmp_table_name(new_name);

3529
	if (row_mysql_is_recovered_tmp_table(new_name)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3530

3531 3532
		recovering_temp_table = TRUE;
	} else {
3533 3534
		/* Serialize data dictionary operations with dictionary mutex:
		no deadlocks can occur then in these operations */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3535 3536 3537

		row_mysql_lock_data_dictionary(trx);
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3538 3539 3540 3541 3542

	table = dict_table_get_low(old_name);

	if (!table) {
		err = DB_TABLE_NOT_FOUND;
3543
		ut_print_timestamp(stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3544

3545 3546 3547 3548 3549
		fputs("  InnoDB: Error: table ", stderr);
		ut_print_name(stderr, trx, old_name);
		fputs(" does not exist in the InnoDB internal\n"
	"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"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3550
	"InnoDB: MySQL database directory from another database?\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3551
	"InnoDB: You can look for further help from\n"
3552
	"InnoDB: http://dev.mysql.com/doc/mysql/en/"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3553
	"InnoDB_troubleshooting_datadict.html\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3554 3555 3556 3557 3558
		goto funct_exit;
	}

	if (table->ibd_file_missing) {
		err = DB_TABLE_NOT_FOUND;
3559
		ut_print_timestamp(stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3560

3561 3562 3563
		fputs("  InnoDB: Error: table ", stderr);
		ut_print_name(stderr, trx, old_name);
		fputs(
3564
	" does not have an .ibd file in the database directory.\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3565
	"InnoDB: You can look for further help from\n"
3566
	"InnoDB: http://dev.mysql.com/doc/mysql/en/"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3567
	"InnoDB_troubleshooting_datadict.html\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3568 3569 3570
		goto funct_exit;
	}

3571
	if (new_is_tmp) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3572 3573 3574 3575 3576
		/* 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>.*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3577

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3578
		heap = mem_heap_create(100);
3579

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3580
		err = dict_foreign_parse_drop_constraints(heap, trx,
3581 3582
			table, &n_constraints_to_drop, &constraints_to_drop);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3583 3584 3585 3586
		if (err != DB_SUCCESS) {

			goto funct_exit;
		}
3587
	}
3588

3589 3590 3591 3592
	/* 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. */
3593

3594
	info = pars_info_create();
3595

3596 3597
	pars_info_add_str_literal(info, "new_table_name", new_name);
	pars_info_add_str_literal(info, "old_table_name", old_name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3598

3599 3600 3601 3602 3603 3604 3605
	err = que_eval_sql(info,
		"PROCEDURE RENAME_TABLE () IS\n"
		"BEGIN\n"
		"UPDATE SYS_TABLES SET NAME = :new_table_name\n"
		" WHERE NAME = :old_table_name;\n"
		"END;\n"
		, trx);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3606

3607
	if (err != DB_SUCCESS) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3608

3609 3610
		goto end;
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3611

3612 3613
	if (!new_is_tmp) {
		/* Rename all constraints. */
3614

3615
		info = pars_info_create();
3616

3617 3618
		pars_info_add_str_literal(info, "new_table_name", new_name);
		pars_info_add_str_literal(info, "old_table_name", old_name);
3619

3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678
		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, new_db_name_len);\n"
	"old_t_name_len := LENGTH(:old_table_name);\n"
	"gen_constr_prefix := CONCAT(:old_table_name, '_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) = TO_BINARY(:old_table_name);\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) = TO_BINARY(:old_table_name);\n"
	"END;\n"
			, trx);
3679

3680 3681
	} else if (n_constraints_to_drop > 0) {
		/* Drop some constraints of tmp tables. */
3682

3683 3684 3685 3686
		ulint	db_name_len = dict_get_db_name_len(old_name) + 1;
		char*	db_name = mem_heap_strdupl(heap, old_name,
			db_name_len);
		ulint	i;
3687

3688 3689 3690
		for (i = 0; i < n_constraints_to_drop; i++) {
			err = row_delete_constraint(constraints_to_drop[i],
				db_name, heap, trx);
3691

3692 3693 3694 3695 3696
			if (err != DB_SUCCESS) {
				break;
			}
		}
	}
3697

3698
end:
3699
	if (err != DB_SUCCESS) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3700
		if (err == DB_DUPLICATE_KEY) {
3701
			ut_print_timestamp(stderr);
3702 3703 3704 3705 3706
			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);
3707 3708
		ut_print_name(stderr, trx, new_name);
		fputs(" exists in the InnoDB internal data\n"
3709
     "InnoDB: dictionary though MySQL is trying rename table ", stderr);
3710
		ut_print_name(stderr, trx, old_name);
3711
		fputs(" to it.\n"
3712
     "InnoDB: Have you deleted the .frm file and not used DROP TABLE?\n"
3713 3714 3715
     "InnoDB: You can look for further help from\n"
     "InnoDB: http://dev.mysql.com/doc/mysql/en/"
     "InnoDB_troubleshooting_datadict.html\n"
3716
     "InnoDB: If table ", stderr);
3717
			ut_print_name(stderr, trx, new_name);
3718 3719
			fputs(
		" is a temporary table #sql..., then it can be that\n"
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3720
     "InnoDB: there are still queries running on the table, and it will be\n"
3721
     "InnoDB: dropped automatically when the queries end.\n"
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3722 3723
     "InnoDB: You can drop the orphaned table inside InnoDB by\n"
     "InnoDB: creating an InnoDB table with the same name in another\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3724
     "InnoDB: database and copying the .frm file to the current database.\n"
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3725
     "InnoDB: Then MySQL thinks the table exists, and DROP TABLE will\n"
3726
     "InnoDB: succeed.\n", stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3727 3728 3729 3730
		}
		trx->error_state = DB_SUCCESS;
		trx_general_rollback_for_mysql(trx, FALSE, NULL);
		trx->error_state = DB_SUCCESS;
3731
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3732 3733 3734
		/* The following call will also rename the .ibd data file if
		the table is stored in a single-table tablespace */

3735
		ibool	success = dict_table_rename_in_cache(table, new_name,
3736
				!new_is_tmp);
3737

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3738 3739 3740 3741 3742
		if (!success) {
			trx->error_state = DB_SUCCESS;
			trx_general_rollback_for_mysql(trx, FALSE, NULL);
			trx->error_state = DB_SUCCESS;
			ut_print_timestamp(stderr);
3743 3744
			fputs(" InnoDB: Error in table rename, cannot rename ",
				stderr);
3745
			ut_print_name(stderr, trx, old_name);
3746
			fputs(" to ", stderr);
3747
			ut_print_name(stderr, trx, new_name);
3748
			putc('\n', stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3749 3750 3751 3752
			err = DB_ERROR;

			goto funct_exit;
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3753

3754 3755
		/* We only want to switch off some of the type checking in
		an ALTER, not in a RENAME. */
3756

3757 3758
		err = dict_load_foreigns(new_name,
			old_is_tmp ? trx->check_foreigns : TRUE);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3759

3760 3761
		if (err != DB_SUCCESS) {
			ut_print_timestamp(stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3762

3763
			if (old_is_tmp) {
3764 3765
				fputs("  InnoDB: Error: in ALTER TABLE ",
					stderr);
3766
				ut_print_name(stderr, trx, new_name);
3767 3768 3769 3770
				fputs("\n"
	"InnoDB: has or is referenced in foreign key constraints\n"
	"InnoDB: which are not compatible with the new table definition.\n",
					stderr);
3771
			} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3772 3773 3774
				fputs(
				"  InnoDB: Error: in RENAME TABLE table ",
					stderr);
3775
				ut_print_name(stderr, trx, new_name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3776
				fputs("\n"
3777 3778
	"InnoDB: is referenced in foreign key constraints\n"
	"InnoDB: which are not compatible with the new table definition.\n",
3779
					stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3780
			}
3781 3782 3783 3784

			ut_a(dict_table_rename_in_cache(table,
					old_name, FALSE));
			trx->error_state = DB_SUCCESS;
3785
			trx_general_rollback_for_mysql(trx, FALSE, NULL);
3786
			trx->error_state = DB_SUCCESS;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3787
		}
3788
	}
3789

3790
funct_exit:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3791 3792 3793
	if (!recovering_temp_table) {
		row_mysql_unlock_data_dictionary(trx);
	}
3794

3795
	if (UNIV_LIKELY_NULL(heap)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3796 3797
		mem_heap_free(heap);
	}
3798 3799

	trx_commit_for_mysql(trx);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3800

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3801
	trx->op_info = "";
3802

3803 3804
	return((int) err);
}
3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819

/*************************************************************************
Checks that the index contains entries in an ascending order, unique
constraint is not broken, and calculates the number of index entries
in the read view of the current transaction. */
static
ibool
row_scan_and_check_index(
/*=====================*/
					/* out: TRUE if ok */
	row_prebuilt_t*	prebuilt,	/* in: prebuilt struct in MySQL */
	dict_index_t*	index,		/* in: index */
	ulint*		n_rows)		/* out: number of entries seen in the
					current consistent read */
{
3820
	dtuple_t*	prev_entry	= NULL;
3821 3822 3823 3824 3825
	ulint		matched_fields;
	ulint		matched_bytes;
	byte*		buf;
	ulint		ret;
	rec_t*		rec;
3826
	ibool		is_ok		= TRUE;
3827
	int		cmp;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3828 3829
	ibool		contains_null;
	ulint		i;
3830
	ulint		cnt;
3831
	mem_heap_t*	heap		= NULL;
3832
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
3833
	ulint*		offsets		= offsets_;
3834
	*offsets_ = (sizeof offsets_) / sizeof *offsets_;
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3835

3836
	*n_rows = 0;
3837

3838 3839
	buf = mem_alloc(UNIV_PAGE_SIZE);
	heap = mem_heap_create(100);
3840

3841 3842 3843 3844 3845 3846 3847 3848 3849
	/* Make a dummy template in prebuilt, which we will use
	in scanning the index entries */

	prebuilt->index = index;
	prebuilt->sql_stat_start = TRUE;
	prebuilt->template_type = ROW_MYSQL_DUMMY_TEMPLATE;
	prebuilt->n_template = 0;
	prebuilt->need_to_access_clustered = FALSE;

3850
	dtuple_set_n_fields(prebuilt->search_tuple, 0);
3851 3852

	prebuilt->select_lock_type = LOCK_NONE;
3853
	cnt = 1000;
3854 3855 3856

	ret = row_search_for_mysql(buf, PAGE_CUR_G, prebuilt, 0, 0);
loop:
3857 3858 3859 3860 3861 3862 3863
	/* Check thd->killed every 1,000 scanned rows */
	if (--cnt == 0) {
		if (trx_is_interrupted(prebuilt->trx)) {
			goto func_exit;
		}
		cnt = 1000;
	}
3864
	if (ret != DB_SUCCESS) {
3865
	func_exit:
3866 3867 3868 3869 3870 3871 3872
		mem_free(buf);
		mem_heap_free(heap);

		return(is_ok);
	}

	*n_rows = *n_rows + 1;
3873

3874 3875 3876
	/* 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 */
3877

3878
	rec = buf + mach_read_from_4(buf);
3879

3880 3881 3882
	if (prev_entry != NULL) {
		matched_fields = 0;
		matched_bytes = 0;
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3883

3884 3885
		offsets = rec_get_offsets(rec, index, offsets,
						ULINT_UNDEFINED, &heap);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3886
		cmp = cmp_dtuple_rec_with_match(prev_entry, rec, offsets,
3887 3888
						&matched_fields,
						&matched_bytes);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3889 3890 3891 3892 3893
		contains_null = FALSE;

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

3894 3895
		for (i = 0;
		     i < dict_index_get_n_ordering_defined_by_user(index);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3896
		     i++) {
3897 3898
			if (UNIV_SQL_NULL == dfield_get_len(
				    dtuple_get_nth_field(prev_entry, i))) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3899

3900 3901 3902
				contains_null = TRUE;
			}
		}
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3903

3904
		if (cmp > 0) {
3905 3906 3907
			fputs("InnoDB: index records in a wrong order in ",
				stderr);
		not_ok:
3908 3909
			dict_index_name_print(stderr,
					prebuilt->trx, index);
3910 3911 3912 3913 3914
			fputs("\n"
				"InnoDB: prev record ", stderr);
			dtuple_print(stderr, prev_entry);
			fputs("\n"
				"InnoDB: record ", stderr);
3915
			rec_print_new(stderr, rec, offsets);
3916
			putc('\n', stderr);
3917 3918
			is_ok = FALSE;
		} else if ((index->type & DICT_UNIQUE)
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3919
			   && !contains_null
3920 3921
			   && matched_fields >=
			   dict_index_get_n_ordering_defined_by_user(index)) {
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
3922

3923 3924
			fputs("InnoDB: duplicate key in ", stderr);
			goto not_ok;
3925 3926 3927 3928
		}
	}

	mem_heap_empty(heap);
3929
	offsets = offsets_;
3930

3931 3932
	prev_entry = row_rec_to_index_entry(ROW_COPY_DATA, index, rec, heap);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3933
	ret = row_search_for_mysql(buf, PAGE_CUR_G, prebuilt, 0, ROW_SEL_NEXT);
3934

3935
	goto loop;
3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947
}

/*************************************************************************
Checks a table for corruption. */

ulint
row_check_table_for_mysql(
/*======================*/
					/* out: DB_ERROR or DB_SUCCESS */
	row_prebuilt_t*	prebuilt)	/* in: prebuilt struct in MySQL
					handle */
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3948
	dict_table_t*	table		= prebuilt->table;
3949 3950
	dict_index_t*	index;
	ulint		n_rows;
3951
	ulint		n_rows_in_table	= ULINT_UNDEFINED;
3952
	ulint		ret		= DB_SUCCESS;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3953
	ulint		old_isolation_level;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3954

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3955
	if (prebuilt->table->ibd_file_missing) {
3956 3957
		ut_print_timestamp(stderr);
		fprintf(stderr, "  InnoDB: Error:\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968
"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"
"http://dev.mysql.com/doc/mysql/en/InnoDB_troubleshooting_datadict.html\n"
"InnoDB: how you can resolve the problem.\n",
				prebuilt->table->name);
		return(DB_ERROR);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3969
	prebuilt->trx->op_info = "checking table";
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3970

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3971 3972 3973 3974 3975 3976 3977 3978
	old_isolation_level = prebuilt->trx->isolation_level;

	/* We must run the index record counts at an isolation level
	>= READ COMMITTED, because a dirty read can see a wrong number
	of records in some index; to play safe, we use always
	REPEATABLE READ here */

	prebuilt->trx->isolation_level = TRX_ISO_REPEATABLE_READ;
3979 3980 3981 3982 3983 3984

	/* Enlarge the fatal lock wait timeout during CHECK TABLE. */
	mutex_enter(&kernel_mutex);
	srv_fatal_semaphore_wait_threshold += 7200; /* 2 hours */
	mutex_exit(&kernel_mutex);

3985 3986 3987
	index = dict_table_get_first_index(table);

	while (index != NULL) {
3988 3989 3990
		/* fputs("Validating index ", stderr);
		ut_print_name(stderr, index->name);
		putc('\n', stderr); */
3991

3992
		if (!btr_validate_tree(index->tree, prebuilt->trx)) {
3993 3994 3995 3996 3997 3998 3999
			ret = DB_ERROR;
		} else {
			if (!row_scan_and_check_index(prebuilt,
							index, &n_rows)) {
				ret = DB_ERROR;
			}

4000 4001 4002 4003
			if (trx_is_interrupted(prebuilt->trx)) {
				break;
			}

4004 4005 4006 4007 4008 4009 4010 4011
			/* fprintf(stderr, "%lu entries in index %s\n", n_rows,
			  index->name); */

			if (index == dict_table_get_first_index(table)) {
				n_rows_in_table = n_rows;
			} else if (n_rows != n_rows_in_table) {

				ret = DB_ERROR;
4012

4013
				fputs("Error: ", stderr);
4014 4015
				dict_index_name_print(stderr,
					prebuilt->trx, index);
4016
				fprintf(stderr,
4017 4018
				" contains %lu entries, should be %lu\n",
					(ulong) n_rows,
4019
					(ulong) n_rows_in_table);
4020 4021 4022 4023 4024 4025
			}
		}

		index = dict_table_get_next_index(index);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4026 4027
	/* Restore the original isolation level */
	prebuilt->trx->isolation_level = old_isolation_level;
4028

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4029 4030 4031
	/* We validate also the whole adaptive hash index for all tables
	at every CHECK TABLE */

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
4032
	if (!btr_search_validate()) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4033 4034 4035 4036

		ret = DB_ERROR;
	}

4037 4038 4039 4040 4041
	/* Restore the fatal lock wait timeout after CHECK TABLE. */
	mutex_enter(&kernel_mutex);
	srv_fatal_semaphore_wait_threshold -= 7200; /* 2 hours */
	mutex_exit(&kernel_mutex);

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
4042
	prebuilt->trx->op_info = "";
4043

4044 4045
	return(ret);
}