row0mysql.c 92.3 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 48
/* 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;
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 88 89 90 91 92 93 94
/* 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)
{
	if (memcmp(name, "mysql/", 6)) {
		return(FALSE);
	}
	return(0 == strcmp(name + 6, "host")
	    || 0 == strcmp(name + 6, "user")
	    || 0 == strcmp(name + 6, "db"));
}
95 96 97 98 99 100 101 102 103 104 105 106 107

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

108 109 110 111 112 113 114 115 116 117 118 119 120 121
/***********************************************************************
Reads a MySQL format variable-length field (like VARCHAR) length and
returns pointer to the field data. */

byte*
row_mysql_read_var_ref_noninline(
/*=============================*/
			/* out: field + 2 */
	ulint*	len,	/* out: variable-length field length */
	byte*	field)	/* in: field */
{
	return(row_mysql_read_var_ref(len, field));
}

122 123 124 125 126 127 128 129 130 131 132 133 134
/***********************************************************************
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;
}

135 136 137 138 139 140 141 142 143
/***********************************************************************
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
144 145 146 147 148 149 150 151
				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! */
152
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
153 154 155 156 157
	/* MySQL might assume the field is set to zero except the length and
	the pointer fields */

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

158 159 160 161 162
	/* 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
163 164 165 166
	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);

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
	mach_write_to_n_little_endian(dest, col_len - 8, len);

	ut_memcpy(dest + col_len - 8, (byte*)&data, sizeof(byte*));	
}

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

	ut_memcpy((byte*)&data, ref + col_len - 8, sizeof(byte*));

	return(data);
}

/******************************************************************
Convert a row in the MySQL format to a row in the Innobase format. */
static
void
row_mysql_convert_row_to_innobase(
/*==============================*/
	dtuple_t*	row,		/* in/out: Innobase row where the
					field type information is already
					copied there, or will be copied
					later */
	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! */
{
	mysql_row_templ_t*	templ;	
	dfield_t*		dfield;
	ulint			i;
	
	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] &
 					(byte) (templ->mysql_null_bit_mask)) {

				/* It is SQL NULL */

				dfield_set_data(dfield, NULL, UNIV_SQL_NULL);

				goto next_column;
			}
		}			
		
		row_mysql_store_col_in_innobase_format(dfield,
					prebuilt->ins_upd_rec_buff
						+ templ->mysql_col_offset,
					mysql_rec + templ->mysql_col_offset,
					templ->mysql_col_len,
					templ->type, templ->is_unsigned);
next_column:
		;
	} 
}

/********************************************************************
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
256 257 258
				lock wait, or if no new error, the value
				of trx->error_state at the entry of this
				function */
259 260
	trx_t*		trx,	/* in: transaction */
	que_thr_t*	thr,	/* in: query thread */
261
	trx_savept_t*	savept)	/* in: savepoint or NULL */
262 263 264 265 266 267 268 269 270 271 272
{
	ulint	err;

handle_new_error:
	err = trx->error_state;
	
	ut_a(err != DB_SUCCESS);
	
	trx->error_state = DB_SUCCESS;

	if (err == DB_DUPLICATE_KEY) {
273
           	if (savept) {
274 275 276 277
			/* Roll back the latest, possibly incomplete
			insertion or update */

			trx_general_rollback_for_mysql(trx, TRUE, savept);
278
		}
279
	} else if (err == DB_TOO_BIG_RECORD) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
280 281 282 283 284 285
           	if (savept) {
			/* Roll back the latest, possibly incomplete
			insertion or update */

			trx_general_rollback_for_mysql(trx, TRUE, savept);
		}
286
		/* MySQL will roll back the latest SQL statement */
287 288 289
	} else if (err == DB_ROW_IS_REFERENCED
		   || err == DB_NO_REFERENCED_ROW
		   || err == DB_CANNOT_ADD_CONSTRAINT) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
290 291 292 293 294 295
           	if (savept) {
			/* Roll back the latest, possibly incomplete
			insertion or update */

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

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
301
		if (trx->error_state != DB_SUCCESS) {
302 303 304 305 306 307 308 309 310
			que_thr_stop_for_mysql(thr);

			goto handle_new_error;
		}

		*new_err = err;

		return(TRUE);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
311 312
	} else if (err == DB_DEADLOCK || err == DB_LOCK_WAIT_TIMEOUT
		   || err == DB_LOCK_TABLE_FULL) {
313 314
		/* Roll back the whole transaction; this resolution was added
		to version 3.23.43 */
315

316 317
		trx_general_rollback_for_mysql(trx, FALSE, NULL);
				
318
	} else if (err == DB_OUT_OF_FILE_SPACE) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
319 320 321 322 323 324
           	if (savept) {
			/* Roll back the latest, possibly incomplete
			insertion or update */

			trx_general_rollback_for_mysql(trx, TRUE, savept);
		}
325
		/* MySQL will roll back the latest SQL statement */
326 327 328

	} else if (err == DB_MUST_GET_MORE_FILE_SPACE) {

329
		fputs(
330 331
		"InnoDB: The database cannot continue operation because of\n"
		"InnoDB: lack of space. You must add a new data file to\n"
332
		"InnoDB: my.cnf and restart the database.\n", stderr);
333 334
		
		exit(1);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
335 336
	} else if (err == DB_CORRUPTION) {

monty@mishka.local's avatar
monty@mishka.local committed
337
	       fputs(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
338 339 340 341 342
	    "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"
343 344 345
	    "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
346

347
	} else {
348 349
		fprintf(stderr, "InnoDB: unknown error code %lu\n",
			(ulong) err);
350
		ut_error;
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
	}		

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

	return(FALSE);
}

/************************************************************************
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;
	
	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
384
	prebuilt->magic_n = ROW_PREBUILT_ALLOCATED;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
385
	prebuilt->magic_n2 = ROW_PREBUILT_ALLOCATED;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
386

387 388 389 390 391 392
	prebuilt->table = table;

	prebuilt->trx = NULL;

	prebuilt->sql_stat_start = TRUE;

393 394
	prebuilt->mysql_has_locked = FALSE;

395
	prebuilt->index = NULL;
396 397 398

	prebuilt->used_in_HANDLER = FALSE;

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
	prebuilt->n_template = 0;
	prebuilt->mysql_template = NULL;

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

	prebuilt->ins_upd_rec_buff = NULL;
	
	prebuilt->upd_node = NULL;
	prebuilt->ins_graph = NULL;
	prebuilt->upd_graph = NULL;

  	prebuilt->pcur = btr_pcur_create_for_mysql();
  	prebuilt->clust_pcur = btr_pcur_create_for_mysql();

	prebuilt->select_lock_type = LOCK_NONE;
415
	prebuilt->stored_select_lock_type = 99999999;
416 417 418 419

	prebuilt->sel_graph = NULL;

	prebuilt->search_tuple = dtuple_create(heap,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
420
					2 * dict_table_get_n_cols(table));
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
	
	clust_index = dict_table_get_first_index(table);

	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
441

442 443 444 445 446 447 448 449 450 451 452 453 454
	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
455 456
	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED
	    || prebuilt->magic_n2 != ROW_PREBUILT_ALLOCATED) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
457
		fprintf(stderr,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
458
"InnoDB: Error: trying to free a corrupt\n"
monty@mishka.local's avatar
monty@mishka.local committed
459
"InnoDB: table handle. Magic n %lu, magic n2 %lu, table name",
460
		(ulong) prebuilt->magic_n,
monty@mishka.local's avatar
monty@mishka.local committed
461
		(ulong) prebuilt->magic_n2);
462
		ut_print_name(stderr, NULL, prebuilt->table->name);
463
		putc('\n', stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
464 465 466

		mem_analyze_corruption((byte*)prebuilt);

467
		ut_error;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
468 469 470
	}

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

473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
	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);
	}
	
	if (prebuilt->upd_graph) {
		que_graph_free_recursive(prebuilt->upd_graph);
	}
	
	if (prebuilt->blob_heap) {
		mem_heap_free(prebuilt->blob_heap);
	}

	if (prebuilt->old_vers_heap) {
		mem_heap_free(prebuilt->old_vers_heap);
	}
	
	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
502 503 504 505 506 507

			if ((ROW_PREBUILT_FETCH_MAGIC_N !=
			    mach_read_from_4((prebuilt->fetch_cache[i]) - 4))
			    || (ROW_PREBUILT_FETCH_MAGIC_N !=
			    mach_read_from_4((prebuilt->fetch_cache[i])
			    			+ prebuilt->mysql_row_len))) {
508
				fputs(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
509
			"InnoDB: Error: trying to free a corrupt\n"
510
			"InnoDB: fetch buffer.\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
511 512 513 514

				mem_analyze_corruption(
						prebuilt->fetch_cache[i]);

515
				ut_error;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
516 517 518
			}

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

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

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
	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 */
{	
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
539
	if (trx->magic_n != TRX_MAGIC_N) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
540
		fprintf(stderr,
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
541 542
		"InnoDB: Error: trying to use a corrupt\n"
		"InnoDB: trx handle. Magic n %lu\n",
543
		(ulong) trx->magic_n);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
544

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
545
		mem_analyze_corruption((byte*)trx);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
546

547
		ut_error;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
548 549 550 551 552
	}

	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
553 554
		"InnoDB: table handle. Magic n %lu, table name",
		(ulong) prebuilt->magic_n);
555
		ut_print_name(stderr, NULL, prebuilt->table->name);
556
		putc('\n', stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
557 558 559

		mem_analyze_corruption((byte*)prebuilt);

560
		ut_error;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
561 562
	}

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
	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;
	}	
}

/*************************************************************************
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(
/*========================*/
					/* out: prebuilt dtuple */
	row_prebuilt_t*	prebuilt)	/* in: prebuilt struct in MySQL
					handle */
{
	ins_node_t*	node;
	dtuple_t*	row;
	dict_table_t*	table	= prebuilt->table;
593
	ulint		i;
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616

	ut_ad(prebuilt && table && prebuilt->trx);
	
	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);
		
		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);
		}
		
		row = dtuple_create(prebuilt->heap,
					dict_table_get_n_cols(table));

		dict_table_copy_types(row, table);

617 618 619 620 621 622 623 624
		/* 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++) {
		    
		        dtuple_get_nth_field(row, i)->len = UNIV_SQL_NULL;
		}

625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
		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;
	}

	return(prebuilt->ins_node->row);	
}

/*************************************************************************
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
645
	dict_table_t*	table)	/* in: table */
646 647 648
{
	ulint	counter;
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
649
	counter = table->stat_modified_counter;
650

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
651
	table->stat_modified_counter = counter + 1;
652 653 654

	/* 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
655 656 657
	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. */
658 659

	if (counter > 2000000000
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
660
	    || ((ib_longlong)counter > 16 + table->stat_n_rows / 16)) {
661

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
662
		dict_update_statistics(table);
663 664
	}	
}
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
		  	
/*************************************************************************
Unlocks an AUTO_INC type lock possibly reserved by trx. */

void		  	
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 */
{
	trx_t*		trx 		= prebuilt->trx;
	ins_node_t*	node		= prebuilt->ins_node;
	que_thr_t*	thr;
	ulint		err;
	ibool		was_lock_wait;
	
	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
705 706 707 708 709
	if (trx->auto_inc_lock) {

		return(DB_SUCCESS);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
710
	trx->op_info = "setting auto-inc lock";
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729

	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: */
730 731 732

	trx_start_if_not_started(trx);

733
	err = lock_table(0, prebuilt->table, LOCK_AUTO_INC, thr);
734 735 736 737 738 739 740 741 742 743 744 745

	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
746
		trx->op_info = "";
747

748
		return((int) err);
749 750 751 752
	}

	que_thr_stop_for_mysql_no_error(thr, trx);

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
753
	trx->op_info = "";
754 755 756 757 758

	return((int) err);
}

/*************************************************************************
759 760
Unlocks all table locks explicitly requested by trx (with LOCK TABLES,
lock type LOCK_TABLE_EXP). */
761 762

void		  	
763 764
row_unlock_tables_for_mysql(
/*========================*/
765 766
	trx_t*	trx)	/* in: transaction */
{
767
	if (!trx->n_lock_table_exp) {
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782

		return;
	}

	mutex_enter(&kernel_mutex);
	lock_release_tables_off_kernel(trx);
	mutex_exit(&kernel_mutex);
}
/*************************************************************************
Sets a table lock on the table mentioned in prebuilt. */

int
row_lock_table_for_mysql(
/*=====================*/
					/* out: error code or DB_SUCCESS */
783
	row_prebuilt_t*	prebuilt,	/* in: prebuilt struct in the MySQL
784
					table handle */
785
	dict_table_t*	table,		/* in: table to lock, or NULL
786 787 788
					if prebuilt->table should be
					locked as LOCK_TABLE_EXP |
					prebuilt->select_lock_type */
789
	ulint		mode)		/* in: lock mode of table */
790 791 792 793 794 795 796 797 798
{
	trx_t*		trx 		= prebuilt->trx;
	que_thr_t*	thr;
	ulint		err;
	ibool		was_lock_wait;
	
	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
799
	trx->op_info = "setting table lock";
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819

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

820 821
	trx_start_if_not_started(trx);

822
	if (table) {
823
		err = lock_table(0, table, mode, thr);
824 825 826 827
	} else {
		err = lock_table(LOCK_TABLE_EXP, prebuilt->table,
			prebuilt->select_lock_type, thr);
	}
828 829 830 831 832 833 834 835 836 837 838 839

	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
840
		trx->op_info = "";
841

842
		return((int) err);
843 844 845 846
	}

	que_thr_stop_for_mysql_no_error(thr, trx);
		
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
847
	trx->op_info = "";
848

849 850 851
	return((int) err);	
}
					
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
/*************************************************************************
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;
	trx_t*		trx 		= prebuilt->trx;
	ins_node_t*	node		= prebuilt->ins_node;
	
	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
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886

	if (prebuilt->table->ibd_file_missing) {
	        ut_print_timestamp(stderr);
	        fprintf(stderr, "  InnoDB: Error:\n"
"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
887 888 889
	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
890 891
		"InnoDB: table handle. Magic n %lu, table name",
		(ulong) prebuilt->magic_n);
892
		ut_print_name(stderr, prebuilt->trx, prebuilt->table->name);
893
		putc('\n', stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
894 895 896

		mem_analyze_corruption((byte*)prebuilt);

897
		ut_error;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
898 899
	}

900
	if (srv_created_new_raw || srv_force_recovery) {
901
		fputs(
902 903 904 905
		"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"
906 907
		"InnoDB: with raw, and innodb_force_... is removed.\n",
			stderr);
908 909 910 911

		return(DB_ERROR);
	}

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

914 915
	row_mysql_delay_if_needed();

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

918 919 920 921 922
	if (node == NULL) {
		row_get_prebuilt_insert_row(prebuilt);
		node = prebuilt->ins_node;
	}

923 924
	row_mysql_convert_row_to_innobase(node->row, prebuilt, mysql_rec);
	
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
	savept = trx_savept_take(trx);
	
	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;
	}
	
	que_thr_move_to_run_state_for_mysql(thr, trx);

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

	row_ins_step(thr);
	
	err = trx->error_state;

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

		was_lock_wait = row_mysql_handle_errors(&err, trx, thr,
								&savept);
		if (was_lock_wait) {
			goto run_again;
		}

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

957
		return((int) err);
958 959 960 961 962 963
	}

	que_thr_stop_for_mysql_no_error(thr, trx);
	
	prebuilt->table->stat_n_rows++;

964 965
	srv_n_rows_inserted++;
	
966 967 968 969 970
	if (prebuilt->table->stat_n_rows == 0) {
		/* Avoid wrap-over */
		prebuilt->table->stat_n_rows--;
	}	

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
971
	row_update_statistics_if_needed(prebuilt->table);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
972
	trx->op_info = "";
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003

	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);
	
	if (prebuilt->sel_graph == NULL) {

		node = sel_node_create(prebuilt->heap);
				
		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
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
/*************************************************************************
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);
		
	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);
	
	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);
}

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
/*************************************************************************
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);
	
	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
1063
		node = row_create_update_node_for_mysql(table, prebuilt->heap);
1064

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1065
		prebuilt->upd_node = node;
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
		
		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;
	dict_index_t*	clust_index; 
1095
/*	ulint		ref_len; */
1096 1097 1098
	upd_node_t*	node;
	dict_table_t*	table		= prebuilt->table;
	trx_t*		trx		= prebuilt->trx;
1099

1100 1101
	ut_ad(prebuilt && trx);
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
1102 1103
	UT_NOT_USED(mysql_rec);
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
	if (prebuilt->table->ibd_file_missing) {
	        ut_print_timestamp(stderr);
	        fprintf(stderr, "  InnoDB: Error:\n"
"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
1118 1119 1120
	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
1121 1122
		"InnoDB: table handle. Magic n %lu, table name",
		(ulong) prebuilt->magic_n);
1123
		ut_print_name(stderr, prebuilt->trx, prebuilt->table->name);
1124
		putc('\n', stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1125 1126 1127

		mem_analyze_corruption((byte*)prebuilt);

1128
		ut_error;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1129 1130
	}

1131
	if (srv_created_new_raw || srv_force_recovery) {
1132
		fputs(
1133 1134 1135 1136
		"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"
1137 1138
		"InnoDB: with raw, and innodb_force_... is removed.\n",
			stderr);
1139 1140 1141 1142

		return(DB_ERROR);
	}

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

1145 1146
	row_mysql_delay_if_needed();

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

1149 1150 1151 1152
	node = prebuilt->upd_node;

	clust_index = dict_table_get_first_index(table);

1153
	if (prebuilt->pcur->btr_cur.index == clust_index) {
1154
		btr_pcur_copy_stored_position(node->pcur, prebuilt->pcur);
1155
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1156 1157
		btr_pcur_copy_stored_position(node->pcur,
							prebuilt->clust_pcur);
1158
	}
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
		
	ut_a(node->pcur->rel_pos == BTR_PCUR_ON);
	 	
	/* 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 */

1169 1170 1171 1172 1173 1174 1175 1176 1177
	savept = trx_savept_take(trx);
	
	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
1178

1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
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);
		
		if (err == DB_RECORD_NOT_FOUND) {
			trx->error_state = DB_SUCCESS;
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1192
			trx->op_info = "";
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202

			return((int) err);
		}
	
		was_lock_wait = row_mysql_handle_errors(&err, trx, thr,
								&savept);
		if (was_lock_wait) {
			goto run_again;
		}

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

1205
		return((int) err);
1206 1207 1208 1209
	}

	que_thr_stop_for_mysql_no_error(thr, trx);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1210
	if (node->is_delete) {
1211 1212 1213
		if (prebuilt->table->stat_n_rows > 0) {
			prebuilt->table->stat_n_rows--;
		}
1214 1215 1216 1217 1218

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

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

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

1224 1225 1226
	return((int) err);
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
/**************************************************************************
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
1239 1240
	ulint	err;
	trx_t*	trx;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250

	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
1251 1252 1253 1254
	/* 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
1255
	if (err == DB_LOCK_WAIT) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1256
		/* Handle lock wait here */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1257
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1258 1259 1260
		que_thr_stop_for_mysql(thr);

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
		/* 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 */
		
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
		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);
}

1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
/*************************************************************************
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))
	 							== DATA_SYS) {
	 	return(TRUE);
	}

	return(FALSE);
}

1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
/*************************************************************************
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
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
/*************************************************************************
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 */
{
1361
	const char*	ptr	= strstr(table->name, "/rsql");
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1362

1363 1364 1365 1366 1367 1368 1369
	if (!ptr) {
		/* table name does not begin with "/rsql" */
		trx_commit_for_mysql(trx);
		return(DB_ERROR);
	}
	else {
		int	status;
1370
		int	namelen = (int) strlen(table->name);
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
		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
1384 1385 1386
	}
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1387
/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1388 1389
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
1390 1391

void
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
row_mysql_freeze_data_dictionary(
/*=============================*/
	trx_t*	trx)	/* in: transaction */
{
	ut_a(trx->dict_operation_lock_mode == 0);
	
	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
1410
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
	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
1427 1428
	ut_a(trx->dict_operation_lock_mode == 0
	     || trx->dict_operation_lock_mode == RW_X_LATCH);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1429
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1430 1431 1432
	/* 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
1433
	rw_lock_x_lock(&dict_operation_lock);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1434 1435
	trx->dict_operation_lock_mode = RW_X_LATCH;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1436 1437 1438 1439
	mutex_enter(&(dict_sys->mutex));
}

/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1440
Unlocks the data dictionary exclusive lock. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1441 1442

void
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1443 1444 1445
row_mysql_unlock_data_dictionary(
/*=============================*/
	trx_t*	trx)	/* in: transaction */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1446
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1447 1448
	ut_a(trx->dict_operation_lock_mode == RW_X_LATCH);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1449 1450 1451 1452
	/* 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
1453
	rw_lock_x_unlock(&dict_operation_lock);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1454 1455

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

1458
/*************************************************************************
1459 1460 1461 1462
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
1463

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
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;
1474 1475
	const char*	table_name;
	ulint		table_name_len;
1476 1477 1478
	ulint		err;

	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
1479
#ifdef UNIV_SYNC_DEBUG
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1480
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1481
	ut_ad(mutex_own(&(dict_sys->mutex)));
1482 1483
#endif /* UNIV_SYNC_DEBUG */
	ut_ad(trx->dict_operation_lock_mode == RW_X_LATCH);
1484
	
1485
	if (srv_created_new_raw) {
1486
		fputs(
1487 1488 1489 1490
		"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"
1491 1492
		"InnoDB: with raw, and innodb_force_... is removed.\n",
		stderr);
1493

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

1496 1497 1498
		return(DB_ERROR);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1499
	trx->op_info = "creating table";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1500
	
1501 1502
	if (row_mysql_is_system_table(table->name)) {

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
		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);

		trx_commit_for_mysql(trx);

		return(DB_ERROR);
	}

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

1515
	if (row_mysql_is_recovered_tmp_table(table->name)) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526

		/* 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... */
 				
		return(row_mysql_recover_tmp_table(table, trx));
	}

1527 1528 1529 1530 1531 1532 1533 1534
	/* 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;
1535

1536 1537
	if (table_name_len == sizeof S_innodb_monitor
			&& !memcmp(table_name, S_innodb_monitor,
1538
				sizeof S_innodb_monitor)) {
1539

1540
		/* Table equals "innodb_monitor":
1541 1542 1543 1544 1545 1546 1547 1548
		start monitor prints */
 				
		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);
1549 1550
	} else if (table_name_len == sizeof S_innodb_lock_monitor
			&& !memcmp(table_name, S_innodb_lock_monitor,
1551
				sizeof S_innodb_lock_monitor)) {
1552 1553 1554 1555

		srv_print_innodb_monitor = TRUE;
		srv_print_innodb_lock_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1556 1557
	} else if (table_name_len == sizeof S_innodb_tablespace_monitor
			&& !memcmp(table_name, S_innodb_tablespace_monitor,
1558
				sizeof S_innodb_tablespace_monitor)) {
1559 1560 1561

		srv_print_innodb_tablespace_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1562 1563
	} else if (table_name_len == sizeof S_innodb_table_monitor
			&& !memcmp(table_name, S_innodb_table_monitor,
1564
				sizeof S_innodb_table_monitor)) {
1565 1566 1567

		srv_print_innodb_table_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
1568 1569
	} else if (table_name_len == sizeof S_innodb_mem_validate
			&& !memcmp(table_name, S_innodb_mem_validate,
1570
				sizeof S_innodb_mem_validate)) {
1571 1572 1573
	        /* We define here a debugging feature intended for
		developers */

1574
		fputs("Validating InnoDB memory:\n"
1575 1576 1577
		 "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"
1578
		"by any semaphore.\n", stderr);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1579
#ifdef UNIV_MEM_DEBUG
1580
		ut_a(mem_validate());
1581
		fputs("Memory validated\n", stderr);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1582
#else /* UNIV_MEM_DEBUG */
1583 1584
		fputs("Memory NOT validated (recompile with UNIV_MEM_DEBUG)\n",
			stderr);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1585
#endif /* UNIV_MEM_DEBUG */
1586 1587
	}

1588 1589 1590 1591 1592 1593 1594 1595
	heap = mem_heap_create(512);

	trx->dict_operation = TRUE;
	
	node = tab_create_graph_create(table, heap);

	thr = pars_complete_graph_for_exec(node, trx, heap);

1596
	ut_a(thr == que_fork_start_command(que_node_get_parent(thr)));
1597 1598 1599 1600 1601 1602
	que_run_threads(thr);

	err = trx->error_state;

	if (err != DB_SUCCESS) {
		/* We have special error handling here */
1603
		
1604 1605 1606 1607
		trx->error_state = DB_SUCCESS;
		
		trx_general_rollback_for_mysql(trx, FALSE, NULL);

1608
		if (err == DB_OUT_OF_FILE_SPACE) {
1609
			fputs("InnoDB: Warning: cannot create table ", stderr);
1610
			ut_print_name(stderr, trx, table->name);
1611
			fputs(" because tablespace full\n", stderr);
1612
		     	row_drop_table_for_mysql(table->name, trx, FALSE);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1613

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1614
		} else if (err == DB_DUPLICATE_KEY) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1615 1616
	    		ut_print_timestamp(stderr);

1617
			fputs("  InnoDB: Error: table ", stderr);
1618
			ut_print_name(stderr, trx, table->name);
1619
			fputs(" already exists in InnoDB internal\n"
1620
     "InnoDB: data dictionary. Have you deleted the .frm file\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1621
     "InnoDB: and not used DROP TABLE? Have you used DROP DATABASE\n"
1622
     "InnoDB: for InnoDB tables in MySQL version <= 3.23.43?\n"
1623
     "InnoDB: See the Restrictions section of the InnoDB manual.\n"
1624 1625
     "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
1626
     "InnoDB: database and copying the .frm file to the current database.\n"
1627
     "InnoDB: Then MySQL thinks the table exists, and DROP TABLE will\n"
1628
     "InnoDB: succeed.\n"
1629 1630 1631
     "InnoDB: You can look for further help from\n"
     "InnoDB: http://dev.mysql.com/doc/mysql/en/"
     "InnoDB_troubleshooting_datadict.html\n", stderr);
1632
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1633 1634 1635
		
		/* We may also get err == DB_ERROR if the .ibd file for the
		table already exists */
1636 1637 1638 1639 1640

		trx->error_state = DB_SUCCESS;
	}

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

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

1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
	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
1656
	dict_index_t*	index,		/* in: index definition */
1657 1658 1659 1660 1661 1662
	trx_t*		trx)		/* in: transaction handle */
{
	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
1663
	ulint		i, j;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1664
	
1665
#ifdef UNIV_SYNC_DEBUG
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1666
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1667
	ut_ad(mutex_own(&(dict_sys->mutex)));
1668
#endif /* UNIV_SYNC_DEBUG */
1669 1670
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
	
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1671
	trx->op_info = "creating index";
1672

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1673 1674
	trx_start_if_not_started(trx);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1675
	/* Check that the same column does not appear twice in the index.
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1676
	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
1677
	safer not to allow them. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1678 1679 1680 1681 1682 1683 1684 1685 1686

	for (i = 0; i < dict_index_get_n_fields(index); i++) {
		for (j = 0; j < i; j++) {
			if (0 == ut_strcmp(
			      dict_index_get_nth_field(index, j)->name,
			      dict_index_get_nth_field(index, i)->name)) {

				ut_print_timestamp(stderr);

1687
				fputs("  InnoDB: Error: column ", stderr);
1688
				ut_print_name(stderr, trx,
1689 1690
				dict_index_get_nth_field(index, i)->name);
				fputs(" appears twice in ", stderr);
1691
				dict_index_name_print(stderr, trx, index);
1692 1693 1694
				fputs("\n"
				"InnoDB: This is not allowed in InnoDB.\n",
					stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1695 1696 1697 1698 1699 1700

				err = DB_COL_APPEARS_TWICE_IN_INDEX;

				goto error_handling;
			}
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1701 1702
		
		/* Check also that prefix_len < DICT_MAX_COL_PREFIX_LEN */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1703

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1704 1705 1706 1707 1708 1709 1710
		if (dict_index_get_nth_field(index, i)->prefix_len
						>= DICT_MAX_COL_PREFIX_LEN) {
			err = DB_TOO_BIG_RECORD;

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

1712
	if (row_mysql_is_recovered_tmp_table(index->table_name)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1713 1714 1715 1716

		return(DB_SUCCESS);
	}

1717 1718 1719 1720
	heap = mem_heap_create(512);

	trx->dict_operation = TRUE;

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

1724 1725 1726 1727
	node = ind_create_graph_create(index, heap);

	thr = pars_complete_graph_for_exec(node, trx, heap);

1728
	ut_a(thr == que_fork_start_command(que_node_get_parent(thr)));
1729 1730
	que_run_threads(thr);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1731 1732 1733
 	err = trx->error_state;

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1735
error_handling:
1736 1737 1738 1739 1740 1741 1742
	if (err != DB_SUCCESS) {
		/* We have special error handling here */
		
		trx->error_state = DB_SUCCESS;

		trx_general_rollback_for_mysql(trx, FALSE, NULL);

1743
		row_drop_table_for_mysql(index->table_name, trx, FALSE);
1744 1745 1746 1747

		trx->error_state = DB_SUCCESS;
	}
	
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1748
	trx->op_info = "";
1749

1750 1751 1752
	return((int) err);
}

1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
/*************************************************************************
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(
/*==============================*/
1765 1766 1767 1768
					/* 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:
1769
				FOREIGN KEY (a, b) REFERENCES table2(c, d),
1770 1771 1772 1773 1774
					table2 can be written also with the
					database name before it: test.table2 */
	const char*	name)		/* in: table full name in the
					normalized form
					database_name/table_name */
1775 1776 1777
{
	ulint	err;

1778
#ifdef UNIV_SYNC_DEBUG
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1779
	ut_ad(mutex_own(&(dict_sys->mutex)));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1780
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
1781
#endif /* UNIV_SYNC_DEBUG */
1782 1783
	ut_a(sql_string);
	
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1784
	trx->op_info = "adding foreign keys";
1785

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

1788
	if (row_mysql_is_recovered_tmp_table(name)) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1789 1790 1791 1792

		return(DB_SUCCESS);
	}

1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
	trx->dict_operation = TRUE;

	err = dict_create_foreign_constraints(trx, sql_string, name);

	if (err == DB_SUCCESS) {
		/* Check that also referencing constraints are ok */
		err = dict_load_foreigns(name);
	}

	if (err != DB_SUCCESS) {
		/* We have special error handling here */
		
		trx->error_state = DB_SUCCESS;

		trx_general_rollback_for_mysql(trx, FALSE, NULL);

1809
		row_drop_table_for_mysql(name, trx, FALSE);
1810 1811 1812 1813 1814 1815 1816

		trx->error_state = DB_SUCCESS;
	}

	return((int) err);
}

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
/*************************************************************************
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
1828 1829
				/* out: error code or DB_SUCCESS */
	const char*	name)	/* in: table name */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1830 1831 1832 1833 1834 1835
{
	ulint	error;
	trx_t*	trx;

	trx = trx_allocate_for_background();

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1836 1837 1838 1839 1840 1841
	/* 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;

1842 1843 1844 1845
/*	fputs("InnoDB: Error: Dropping table ", stderr);
	ut_print_name(stderr, name);
	fputs(" in background drop list\n", stderr); */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1846
  	/* Try to drop the table in InnoDB */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1847

1848
  	error = row_drop_table_for_mysql(name, trx, FALSE);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1849 1850 1851 1852 1853
  	
	/* 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 */
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1854
	log_buffer_flush_to_disk();
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1855 1856 1857 1858 1859

  	trx_commit_for_mysql(trx);

  	trx_free_for_background(trx);

1860
	return((int) error);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
}

/*************************************************************************
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;
loop:	
	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);
	
	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
1894
		/* All tables dropped */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1895 1896 1897 1898 1899 1900 1901 1902

		return(n_tables + n_tables_dropped);
	}

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

1903 1904 1905 1906 1907 1908
	if (table == NULL) {
	        /* If for some reason the table has already been dropped
		through some other mechanism, do not try to drop it */

	        goto already_dropped;
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1909 1910 1911 1912 1913
							
	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
1914 1915 1916 1917 1918 1919

		return(n_tables + n_tables_dropped);
	}

	n_tables_dropped++;

1920
already_dropped:
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1921 1922 1923 1924
	mutex_enter(&kernel_mutex);

	UT_LIST_REMOVE(row_mysql_drop_list, row_mysql_drop_list, drop);

1925
        ut_print_timestamp(stderr);
1926 1927 1928
	fprintf(stderr,
		"  InnoDB: Dropped table %s in background drop queue.\n",
		drop->table_name);
1929

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
	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 */
{
1948
#ifdef UNIV_SYNC_DEBUG
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1949
	ut_ad(mutex_own(&kernel_mutex));
1950
#endif /* UNIV_SYNC_DEBUG */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961

	if (!row_mysql_drop_list_inited) {

		UT_LIST_INIT(row_mysql_drop_list);
		row_mysql_drop_list_inited = TRUE;
	}
	
	return(UT_LIST_GET_LEN(row_mysql_drop_list));
}

/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1962 1963 1964 1965 1966
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
1967
static
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1968
ibool
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1969 1970
row_add_table_to_background_drop_list(
/*==================================*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1971 1972
				/* 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
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
	dict_table_t*	table)	/* in: table */
{
	row_mysql_drop_t*	drop;
	
	mutex_enter(&kernel_mutex);

	if (!row_mysql_drop_list_inited) {

		UT_LIST_INIT(row_mysql_drop_list);
		row_mysql_drop_list_inited = TRUE;
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
	
	/* 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 */
			
			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
1999

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2000 2001 2002 2003
	drop = mem_alloc(sizeof(row_mysql_drop_t));

	drop->table_name = mem_strdup(table->name);
 
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2004 2005
	UT_LIST_ADD_LAST(row_mysql_drop_list, row_mysql_drop_list, drop);
	
2006 2007 2008 2009
/*	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
2010
	mutex_exit(&kernel_mutex);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2011 2012

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2015 2016 2017
/*************************************************************************
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
2018
the table. Also the flag table->ibd_file_missing is set TRUE. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2019

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
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;
	que_thr_t*	thr;
	que_t*		graph			= NULL;
	ibool		success;
	ulint		err;
	char*		buf;

/* How do we prevent crashes caused by ongoing operations on the table? Old
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
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
2052 2053 2054
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. */
2055 2056 2057 2058 2059 2060 2061 2062 2063

	static const char discard_tablespace_proc1[] =
	"PROCEDURE DISCARD_TABLESPACE_PROC () IS\n"
	"old_id CHAR;\n"
	"new_id CHAR;\n"
	"new_id_low INT;\n"
	"new_id_high INT;\n"
	"table_name CHAR;\n"
	"BEGIN\n"
2064
	"table_name := '";
2065
	static const char discard_tablespace_proc2[] =
2066
	"';\n"
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
	"new_id_high := %lu;\n"
	"new_id_low := %lu;\n"
   "new_id := CONCAT(TO_BINARY(new_id_high, 4), TO_BINARY(new_id_low, 4));\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";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2085 2086 2087

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

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2088
	trx->op_info = "discarding tablespace";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
	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;
	}

2104 2105
	if (table->space == 0) {
		ut_print_timestamp(stderr);
2106
		fputs("  InnoDB: Error: table ", stderr);
2107
		ut_print_name(stderr, trx, name);
2108 2109
		fputs("\n"
"InnoDB: is in the system tablespace 0 which cannot be discarded\n", stderr);
2110 2111 2112 2113 2114
		err = DB_ERROR;

		goto funct_exit;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
	if (table->n_foreign_key_checks_running > 0) {

	        ut_print_timestamp(stderr);
		fputs("	 InnoDB: You are trying to DISCARD table ", stderr);
		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);
	
	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
2152
		fputs("  Cannot DISCARD table ", ef);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
		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
2163 2164
	new_id = dict_hdr_get_new_id(DICT_HDR_TABLE_ID);

2165 2166 2167
	buf = mem_alloc((sizeof discard_tablespace_proc1) +
			(sizeof discard_tablespace_proc2) +
			20 + ut_strlenq(name, '\''));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2168

2169 2170 2171 2172 2173 2174
	memcpy(buf, discard_tablespace_proc1, sizeof discard_tablespace_proc1);
	sprintf(ut_strcpyq(buf + (sizeof discard_tablespace_proc1 - 1),
			'\'', name),
		discard_tablespace_proc2,
		(ulong) ut_dulint_get_high(new_id),
		(ulong) ut_dulint_get_low(new_id));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2175 2176 2177 2178 2179

	graph = pars_sql(buf);

	ut_a(graph);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2180 2181 2182 2183
	/* Remove any locks there are on the table or its records */
	
	lock_reset_all_on_table(table);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2184 2185 2186 2187 2188
	graph->trx = trx;
	trx->graph = NULL;

	graph->fork_type = QUE_FORK_MYSQL_INTERFACE;

monty@mysql.com's avatar
monty@mysql.com committed
2189
	ut_a(thr = que_fork_start_command(graph));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225

	que_run_threads(thr);

	err = trx->error_state;

	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;
		}
	}
funct_exit:	
	row_mysql_unlock_data_dictionary(trx);

	if (graph) {
		que_graph_free(graph);
	}

  	trx_commit_for_mysql(trx);

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2226
	trx->op_info = "";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237

	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(
/*============================*/
2238 2239 2240
				/* 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
2241 2242 2243
{
	dict_table_t*	table;
	ibool		success;
2244
	dulint		current_lsn;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2245 2246 2247 2248 2249 2250
	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
2251
	trx->op_info = "importing tablespace";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2252

2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
	current_lsn = log_get_lsn();
	
	/* 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
2270 2271 2272 2273 2274 2275
		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);

2276 2277 2278 2279 2280 2281 2282
		err = DB_ERROR;

		row_mysql_lock_data_dictionary(trx);

		goto funct_exit;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2283 2284 2285 2286 2287 2288 2289 2290
	/* 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
2291 2292 2293 2294 2295 2296 2297 2298
		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
2299 2300 2301 2302 2303
		err = DB_TABLE_NOT_FOUND;

		goto funct_exit;
	}

2304 2305
	if (table->space == 0) {
		ut_print_timestamp(stderr);
2306
		fputs("  InnoDB: Error: table ", stderr);
2307
		ut_print_name(stderr, trx, name);
2308 2309
		fputs("\n"
"InnoDB: is in the system tablespace 0 which cannot be imported\n", stderr);
2310 2311 2312 2313 2314
		err = DB_ERROR;

		goto funct_exit;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2315 2316
	if (!table->tablespace_discarded) {
		ut_print_timestamp(stderr);
2317
		fputs(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2318
"  InnoDB: Error: you are trying to IMPORT a tablespace\n"
2319
"InnoDB: ", stderr);
2320
		ut_print_name(stderr, trx, name);
2321 2322
		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
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333

		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
2334 2335
	success = fil_open_single_table_tablespace(TRUE, table->space,
								table->name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2336 2337 2338 2339
	if (success) {
		table->ibd_file_missing = FALSE;
		table->tablespace_discarded = FALSE;
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2340 2341 2342
		if (table->ibd_file_missing) {
			ut_print_timestamp(stderr);
			fputs(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2343
"  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
2344 2345 2346 2347 2348 2349 2350
"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
2351 2352 2353 2354 2355 2356 2357 2358
		err = DB_ERROR;
	}

funct_exit:	
	row_mysql_unlock_data_dictionary(trx);

  	trx_commit_for_mysql(trx);

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2359
	trx->op_info = "";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2360 2361 2362 2363

	return((int) err);
}

2364
/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2365
Drops a table for MySQL. If the name of the table to be dropped is equal
2366 2367
with one of the predefined magic table names, then this also stops printing
the corresponding monitor output by the master thread. */
2368 2369 2370 2371

int
row_drop_table_for_mysql(
/*=====================*/
2372 2373 2374 2375
				/* 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 */
2376
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2377
	dict_foreign_t*	foreign;
2378
	dict_table_t*	table;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2379
	ulint		space_id;
2380 2381 2382
	que_thr_t*	thr;
	que_t*		graph;
	ulint		err;
2383
	const char*	table_name;
2384
	ulint		namelen;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2385
	char*		dir_path_of_temp_table	= NULL;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2386
	ibool		success;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2387
	ibool		locked_dictionary	= FALSE;
2388 2389
	char*		quoted_name;
	char*		sql;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2390

2391 2392 2393 2394
	/* 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. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2395

2396
	static const char str1[] =
2397
	"PROCEDURE DROP_TABLE_PROC () IS\n"
2398 2399
	"table_name CHAR;\n"
	"sys_foreign_id CHAR;\n"
2400 2401
	"table_id CHAR;\n"
	"index_id CHAR;\n"
2402
	"foreign_id CHAR;\n"
2403 2404
	"found INT;\n"
	"BEGIN\n"
2405 2406 2407
	"table_name := ";
	static const char str2[] =
	";\n"
2408 2409 2410
	"SELECT ID INTO table_id\n"
	"FROM SYS_TABLES\n"
	"WHERE NAME = table_name;\n"
2411 2412 2413 2414 2415
	"IF (SQL % NOTFOUND) THEN\n"
	"	COMMIT WORK;\n"
	"	RETURN;\n"
	"END IF;\n"
	"found := 1;\n"
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
	"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"
2431 2432
	"	WHERE FOR_NAME = table_name\n"
        "             AND TO_BINARY(FOR_NAME) = TO_BINARY(table_name);\n"
2433 2434 2435 2436 2437 2438 2439 2440
	"	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"
2441 2442 2443 2444 2445 2446 2447 2448
	"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"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2449 2450
	"		DELETE FROM SYS_INDEXES WHERE ID = index_id\n"
	"					 AND TABLE_ID = table_id;\n"
2451 2452 2453 2454 2455 2456 2457
	"	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";

2458 2459 2460 2461 2462 2463 2464 2465 2466
	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",
monty@mishka.local's avatar
monty@mishka.local committed
2467
                stderr);
2468 2469 2470 2471

		return(DB_ERROR);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2472
	trx->op_info = "dropping table";
2473 2474

	trx_start_if_not_started(trx);
2475

2476 2477 2478 2479 2480 2481 2482 2483
	/* 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;
2484

2485
	if (namelen == sizeof S_innodb_monitor
2486
			&& !memcmp(table_name, S_innodb_monitor,
2487
				sizeof S_innodb_monitor)) {
2488

2489 2490 2491 2492 2493 2494
		/* Table name equals "innodb_monitor":
		stop monitor prints */
 				
		srv_print_innodb_monitor = FALSE;
		srv_print_innodb_lock_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_lock_monitor
2495
			&& !memcmp(table_name, S_innodb_lock_monitor,
2496 2497 2498 2499
				sizeof S_innodb_lock_monitor)) {
		srv_print_innodb_monitor = FALSE;
		srv_print_innodb_lock_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_tablespace_monitor
2500
			&& !memcmp(table_name, S_innodb_tablespace_monitor,
2501
				sizeof S_innodb_tablespace_monitor)) {
2502

2503 2504
		srv_print_innodb_tablespace_monitor = FALSE;
	} else if (namelen == sizeof S_innodb_table_monitor
2505
			&& !memcmp(table_name, S_innodb_table_monitor,
2506
				sizeof S_innodb_table_monitor)) {
2507

2508 2509 2510 2511 2512 2513 2514 2515 2516
		srv_print_innodb_table_monitor = FALSE;
	}

	quoted_name = mem_strdupq(name, '\'');
	namelen = strlen(quoted_name);
	sql = mem_alloc((sizeof str1) + (sizeof str2) - 2 + 1 + namelen);
	memcpy(sql, str1, (sizeof str1) - 1);
	memcpy(sql + (sizeof str1) - 1, quoted_name, namelen);
	memcpy(sql + (sizeof str1) - 1 + namelen, str2, sizeof str2);
2517
	mem_free(quoted_name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2518

2519 2520 2521
	/* 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
2522
	if (trx->dict_operation_lock_mode != RW_X_LATCH) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2523 2524
		/* Prevent foreign key checks etc. while we are dropping the
		table */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2525

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2526 2527 2528
		row_mysql_lock_data_dictionary(trx);

		locked_dictionary = TRUE;
2529 2530
	}

2531
#ifdef UNIV_SYNC_DEBUG
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2532 2533
	ut_ad(mutex_own(&(dict_sys->mutex)));
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
2534
#endif /* UNIV_SYNC_DEBUG */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2535
	
2536
	graph = pars_sql(sql);
2537 2538

	ut_a(graph);
2539
	mem_free(sql);
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549

	graph->trx = trx;
	trx->graph = NULL;

	graph->fork_type = QUE_FORK_MYSQL_INTERFACE;

	table = dict_table_get_low(name);

	if (!table) {
		err = DB_TABLE_NOT_FOUND;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2550
	    	ut_print_timestamp(stderr);
2551

2552
		fputs("  InnoDB: Error: table ", stderr);
2553
		ut_print_name(stderr, trx, name);
2554
		fputs(" does not exist in the InnoDB internal\n"
2555 2556
     	"InnoDB: data dictionary though MySQL is trying to drop it.\n"
     	"InnoDB: Have you copied the .frm file of the table to the\n"
2557
	"InnoDB: MySQL database directory from another database?\n"
2558 2559 2560
	"InnoDB: You can look for further help from\n"
	"InnoDB: http://dev.mysql.com/doc/mysql/en/"
	"InnoDB_troubleshooting_datadict.html\n", stderr);
2561 2562 2563
		goto funct_exit;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2564 2565 2566
	/* 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
2567 2568
	foreign = UT_LIST_GET_FIRST(table->referenced_list);
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2569 2570 2571 2572
	while (foreign && foreign->foreign_table == table) {
		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}

2573 2574 2575
	if (foreign && trx->check_foreigns &&
		!(drop_db && dict_tables_have_same_db(
			name, foreign->foreign_table_name))) {
2576
		FILE*	ef	= dict_foreign_err_file;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2577 2578 2579 2580 2581 2582 2583

		/* 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);
2584 2585 2586 2587
		rewind(ef);
		ut_print_timestamp(ef);

		fputs("  Cannot drop table ", ef);
2588
		ut_print_name(ef, trx, name);
2589 2590
		fputs("\n"
			"because it is referenced by ", ef);
2591
		ut_print_name(ef, trx, foreign->foreign_table_name);
2592
		putc('\n', ef);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2593 2594 2595 2596 2597
		mutex_exit(&dict_foreign_err_mutex);

		goto funct_exit;
	}

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2598
	if (table->n_mysql_handles_opened > 0) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2599
		ibool	added;
2600

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613
	        if (added) {
			ut_print_timestamp(stderr);
fputs("	 InnoDB: Warning: MySQL is trying to drop table ", stderr);
			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);
			
			/* We return DB_SUCCESS to MySQL though the drop will
			happen lazily later */
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2614

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2615 2616 2617 2618 2619
			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
2620

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2621
		goto funct_exit;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2622
	}
2623

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2624 2625 2626 2627 2628 2629
	/* 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
2630
	if (table->n_foreign_key_checks_running > 0) {
2631

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
		ibool	added;

		added = row_add_table_to_background_drop_list(table);

		if (added) {
	        	ut_print_timestamp(stderr);
fputs("	 InnoDB: You are trying to drop table ", stderr);
			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",
2643
			stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2644

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2648 2649 2650 2651 2652
			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
2653 2654 2655 2656

		goto funct_exit;
	}
	
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2657 2658 2659 2660
	/* Remove any locks there are on the table or its records */
	
	lock_reset_all_on_table(table);

2661 2662 2663
	trx->dict_operation = TRUE;
	trx->table_id = table->id;

2664
	ut_a(thr = que_fork_start_command(graph));
2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676

	que_run_threads(thr);

	err = trx->error_state;

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

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

2677
		ut_error;
2678
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2679 2680 2681
		ibool		is_path;
		const char*	name_or_path;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2682
		space_id = table->space;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
		
		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;
		}

2694
		dict_table_remove_from_cache(table);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2695 2696 2697

		if (dict_load_table(name) != NULL) {
			ut_print_timestamp(stderr);
monty@mishka.local's avatar
monty@mishka.local committed
2698
			fputs("  InnoDB: Error: not able to remove table ",
2699
				stderr);
2700
			ut_print_name(stderr, trx, name);
monty@mishka.local's avatar
monty@mishka.local committed
2701
			fputs(" from the dictionary cache!\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2702 2703 2704 2705 2706 2707
			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
2708
		if (err == DB_SUCCESS && space_id > 0) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2709 2710 2711
			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
2712
								FALSE, TRUE)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2713 2714 2715 2716 2717 2718 2719
				err = DB_SUCCESS;

				fprintf(stderr,
"InnoDB: We removed now the InnoDB internal data dictionary entry\n"
"InnoDB: of table ");	
				ut_print_name(stderr, trx, name);
				fprintf(stderr, ".\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2720 2721 2722

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2724 2725 2726
			success = fil_delete_tablespace(space_id);

			if (!success) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2727 2728 2729 2730 2731 2732
				fprintf(stderr,
"InnoDB: We removed now the InnoDB internal data dictionary entry\n"
"InnoDB: of table ");	
				ut_print_name(stderr, trx, name);
				fprintf(stderr, ".\n");

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2733 2734
				ut_print_timestamp(stderr);
				fprintf(stderr,
2735 2736
"  InnoDB: Error: not able to delete tablespace %lu of table ",
					(ulong) space_id);
2737
				ut_print_name(stderr, trx, name);
2738
				fputs("!\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2739 2740
				err = DB_ERROR;
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2741
		}
2742
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2743
funct_exit:
2744

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2745 2746
	if (locked_dictionary) {
		row_mysql_unlock_data_dictionary(trx);	
2747 2748
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2749 2750 2751 2752
	if (dir_path_of_temp_table) {
		mem_free(dir_path_of_temp_table);
	}

2753 2754
	que_graph_free(graph);
	
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2755 2756
  	trx_commit_for_mysql(trx);

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

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2759 2760
	srv_wake_master_thread();

2761 2762 2763
	return((int) err);
}

2764 2765 2766 2767 2768 2769
/*************************************************************************
Drops a database for MySQL. */

int
row_drop_database_for_mysql(
/*========================*/
2770 2771 2772
				/* out: error code or DB_SUCCESS */
	const char*	name,	/* in: database name which ends to '/' */
	trx_t*		trx)	/* in: transaction handle */
2773
{
2774
        dict_table_t* table;
2775 2776
	char*	table_name;
	int	err	= DB_SUCCESS;
2777
	ulint	namelen	= strlen(name);
2778 2779 2780
	
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
	ut_a(name != NULL);
2781
	ut_a(name[namelen - 1] == '/');
2782
	
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2783
	trx->op_info = "dropping database";
2784
	
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2785
	trx_start_if_not_started(trx);
2786
loop:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2787
	row_mysql_lock_data_dictionary(trx);
2788

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

2792 2793 2794 2795 2796 2797 2798 2799
		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
2800
			row_mysql_unlock_data_dictionary(trx);
2801

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2802
			ut_print_timestamp(stderr);
2803 2804
			fputs(
	"  InnoDB: Warning: MySQL is trying to drop database ", stderr);
2805
			ut_print_name(stderr, trx, name);
2806 2807
			fputs("\n"
	"InnoDB: though there are still open handles to table ", stderr);
2808
			ut_print_name(stderr, trx, table_name);
2809
			fputs(".\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2810 2811 2812 2813

		        os_thread_sleep(1000000);

		        mem_free(table_name);
2814 2815 2816 2817

		        goto loop;
		}

2818
		err = row_drop_table_for_mysql(table_name, trx, TRUE);
2819 2820 2821 2822

		mem_free(table_name);

		if (err != DB_SUCCESS) {
2823
			fputs("InnoDB: DROP DATABASE ", stderr);
2824
			ut_print_name(stderr, trx, name);
2825 2826
			fprintf(stderr, " failed with error %lu for table ",
				(ulint) err);
2827
			ut_print_name(stderr, trx, table_name);
2828
			putc('\n', stderr);
2829 2830 2831 2832
			break;
		}
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2833
	row_mysql_unlock_data_dictionary(trx);
2834
	
2835 2836
	trx_commit_for_mysql(trx);

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2837
	trx->op_info = "";
2838 2839 2840 2841

	return(err);
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2842 2843 2844 2845 2846 2847 2848
/*************************************************************************
Checks if a table name contains the string "/#sql" which denotes temporary
tables in MySQL. */
static
ibool
row_is_mysql_tmp_table_name(
/*========================*/
2849 2850 2851
				/* 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
2852
{
2853
	return(strstr(name, "/#sql") != NULL);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2854 2855
}

2856 2857 2858 2859 2860 2861
/*************************************************************************
Renames a table for MySQL. */

int
row_rename_table_for_mysql(
/*=======================*/
2862 2863 2864 2865
					/* 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 */
2866 2867 2868
{
	dict_table_t*	table;
	que_thr_t*	thr;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2869
	que_t*		graph			= NULL;
2870
	ulint		err;
2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910
	/* 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. */
	static const char str1[] =
	"PROCEDURE RENAME_TABLE_PROC () IS\n"
	"new_table_name CHAR;\n"
	"old_table_name CHAR;\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"
	"new_table_name := '";
	static const char str2[] =
	"';\nold_table_name := '";
	static const char str3[] =
	"';\n"
	"UPDATE SYS_TABLES SET NAME = new_table_name\n"
	"WHERE NAME = old_table_name;\n";
	static const char str4a1[] = /* drop some constraints of tmp tables */
	"DELETE FROM SYS_FOREIGN_COLS WHERE ID = '";
	static const char str4a2[] = "';\n"
	"DELETE FROM SYS_FOREIGN WHERE ID = '";
	static const char str4a3[] = "';\n";
	static const char str4b[] = /* rename all constraints */
	"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"
2911 2912
	"	WHERE FOR_NAME = old_table_name\n"
	"	      AND TO_BINARY(FOR_NAME) = TO_BINARY(old_table_name);\n"
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
	"	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"
2945 2946
	"WHERE REF_NAME = old_table_name\n"
	"      AND TO_BINARY(REF_NAME) = TO_BINARY(old_table_name);\n";
2947 2948 2949
	static const char str5[] =
	"END;\n";

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2950
	mem_heap_t*	heap			= NULL;
2951
	const char**	constraints_to_drop	= NULL;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2952
	ulint		n_constraints_to_drop	= 0;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2953
        ibool           recovering_temp_table   = FALSE;
2954
	ulint		len;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2955
	ulint		i;
monty@mishka.local's avatar
monty@mishka.local committed
2956
        ibool		success;
2957 2958 2959 2960
	/* length of database name; 0 if not renaming to a temporary table */
	ulint		db_name_len;
	char*		sql;
	char*		sqlend;
2961 2962 2963 2964 2965

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

2966
	if (srv_created_new_raw || srv_force_recovery) {
2967
		fputs(
2968 2969 2970 2971
		"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"
2972 2973
		"InnoDB: with raw, and innodb_force_... is removed.\n",
		stderr);
2974

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2975 2976 2977
  		trx_commit_for_mysql(trx);
		return(DB_ERROR);
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2978
	
2979
	if (row_mysql_is_system_table(new_name)) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2980 2981 2982 2983 2984 2985 2986
	    	
		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);

  		trx_commit_for_mysql(trx);
2987 2988 2989
		return(DB_ERROR);
	}

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

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2995
                recovering_temp_table = TRUE;
2996 2997 2998
        } else {
		/* 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
2999 3000 3001

		row_mysql_lock_data_dictionary(trx);
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3002 3003 3004 3005 3006

	table = dict_table_get_low(old_name);

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

3009
                fputs("  InnoDB: Error: table ", stderr);
3010
                ut_print_name(stderr, trx, old_name);
3011
                fputs(" does not exist in the InnoDB internal\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3012 3013 3014 3015
     	"InnoDB: data dictionary though MySQL is trying to rename the table.\n"
     	"InnoDB: Have you copied the .frm file of the table to the\n"
	"InnoDB: MySQL database directory from another database?\n"
	"InnoDB: You can look for further help from section 15.1 of\n"
3016
        "InnoDB: http://www.innodb.com/ibman.php\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3017 3018 3019 3020 3021 3022
		goto funct_exit;
	}

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

3024
                fputs("  InnoDB: Error: table ", stderr);
3025
                ut_print_name(stderr, trx, old_name);
3026 3027
                fputs(
	" does not have an .ibd file in the database directory.\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3028
	"InnoDB: You can look for further help from section 15.1 of\n"
3029
        "InnoDB: http://www.innodb.com/ibman.php\n", stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3030 3031 3032
		goto funct_exit;
	}

3033 3034 3035
	/* calculate the length of the SQL string */
	len = (sizeof str1) + (sizeof str2) + (sizeof str3) + (sizeof str5) - 4
		+ ut_strlenq(new_name, '\'') + ut_strlenq(old_name, '\'');
3036

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3037
	if (row_is_mysql_tmp_table_name(new_name)) {
3038
		db_name_len = dict_get_db_name_len(old_name) + 1;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3039

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3040 3041 3042 3043 3044
		/* 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
3045

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
		heap = mem_heap_create(100);
		
		err = dict_foreign_parse_drop_constraints(heap, trx,
					table,
					&n_constraints_to_drop,
					&constraints_to_drop);
		if (err != DB_SUCCESS) {

			goto funct_exit;
		}
		
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
		/* reserve space for all database names */
		len += 2 * n_constraints_to_drop
			* (ut_strlenq(old_name, '\'')
			- ut_strlenq(old_name + db_name_len, '\''));

		for (i = 0; i < n_constraints_to_drop; i++) {
			ulint	addlen
				= 2 * ut_strlenq(constraints_to_drop[i], '\'')
				+ ((sizeof str4a1) + (sizeof str4a2)
				+ (sizeof str4a3) - 3);
			if (!strchr(constraints_to_drop[i], '/')) {
				addlen *= 2;
			}
			len += addlen;
		}
	} else {
		db_name_len = 0;
		len += (sizeof str4b) - 1;
	}

	sql = sqlend = mem_alloc(len + 1);
	memcpy(sql, str1, (sizeof str1) - 1);
	sqlend += (sizeof str1) - 1;
	sqlend = ut_strcpyq(sqlend, '\'', new_name);
	memcpy(sqlend, str2, (sizeof str2) - 1);
	sqlend += (sizeof str2) - 1;
	sqlend = ut_strcpyq(sqlend, '\'', old_name);
	memcpy(sqlend, str3, (sizeof str3) - 1);
	sqlend += (sizeof str3) - 1;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3086

3087
	if (db_name_len) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3088 3089 3090 3091
		/* Internally, old format < 4.0.18 constraints have as the
		constraint id <number>_<number>, while new format constraints
		have <databasename>/<constraintname>. */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3092
		for (i = 0; i < n_constraints_to_drop; i++) {
3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106
			memcpy(sqlend, str4a1, (sizeof str4a1) - 1);
			sqlend += (sizeof str4a1) - 1;
			sqlend = ut_memcpyq(sqlend, '\'',
				old_name, db_name_len);
			sqlend = ut_strcpyq(sqlend, '\'',
				constraints_to_drop[i]);
			memcpy(sqlend, str4a2, (sizeof str4a2) - 1);
			sqlend += (sizeof str4a2) - 1;
			sqlend = ut_memcpyq(sqlend, '\'',
				old_name, db_name_len);
                        sqlend = ut_strcpyq(sqlend, '\'',
				constraints_to_drop[i]);
			memcpy(sqlend, str4a3, (sizeof str4a3) - 1);
			sqlend += (sizeof str4a3) - 1;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3107

3108
			if (!strchr(constraints_to_drop[i], '/')) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3109 3110 3111 3112 3113
				/* If this happens to be an old format
				constraint, let us delete it. Since all new
				format constraints contain '/', it does no
				harm to run these DELETEs anyway. */

3114 3115 3116 3117 3118 3119 3120 3121 3122 3123
				memcpy(sqlend, str4a1, (sizeof str4a1) - 1);
				sqlend += (sizeof str4a1) - 1;
				sqlend = ut_strcpyq(sqlend, '\'',
					constraints_to_drop[i]);
				memcpy(sqlend, str4a2, (sizeof str4a2) - 1);
				sqlend += (sizeof str4a2) - 1;
                        	sqlend = ut_strcpyq(sqlend, '\'',
					constraints_to_drop[i]);
				memcpy(sqlend, str4a3, (sizeof str4a3) - 1);
				sqlend += (sizeof str4a3) - 1;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3124
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3125
		}
3126 3127 3128 3129 3130
	}
	else {
		memcpy(sqlend, str4b, (sizeof str4b) - 1);
		sqlend += (sizeof str4b) - 1;
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3131

3132 3133
	memcpy(sqlend, str5, sizeof str5);
	sqlend += sizeof str5;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3134

3135
	ut_a(sqlend == sql + len + 1);
3136
	
3137
	graph = pars_sql(sql);
3138 3139

	ut_a(graph);
3140
	mem_free(sql);
3141 3142 3143 3144 3145 3146

	graph->trx = trx;
	trx->graph = NULL;

	graph->fork_type = QUE_FORK_MYSQL_INTERFACE;

3147
	ut_a(thr = que_fork_start_command(graph));
3148 3149 3150 3151 3152 3153

	que_run_threads(thr);

	err = trx->error_state;

	if (err != DB_SUCCESS) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3154 3155
		if (err == DB_DUPLICATE_KEY) {
	    		ut_print_timestamp(stderr);
3156 3157 3158 3159 3160
			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);
3161
                ut_print_name(stderr, trx, new_name);
3162 3163
                fputs(" exists in the InnoDB internal data\n"
     "InnoDB: dictionary though MySQL is trying rename table ", stderr);
3164
                ut_print_name(stderr, trx, old_name);
3165
		fputs(" to it.\n"
3166
     "InnoDB: Have you deleted the .frm file and not used DROP TABLE?\n"
3167 3168 3169
     "InnoDB: You can look for further help from\n"
     "InnoDB: http://dev.mysql.com/doc/mysql/en/"
     "InnoDB_troubleshooting_datadict.html\n"
3170
     "InnoDB: If table ", stderr);
3171
			ut_print_name(stderr, trx, new_name);
3172 3173
			fputs(
		" is a temporary table #sql..., then it can be that\n"
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3174
     "InnoDB: there are still queries running on the table, and it will be\n"
3175
     "InnoDB: dropped automatically when the queries end.\n"
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3176 3177
     "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
3178
     "InnoDB: database and copying the .frm file to the current database.\n"
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3179
     "InnoDB: Then MySQL thinks the table exists, and DROP TABLE will\n"
3180
     "InnoDB: succeed.\n", stderr);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3181 3182 3183 3184
		}
		trx->error_state = DB_SUCCESS;
		trx_general_rollback_for_mysql(trx, FALSE, NULL);
		trx->error_state = DB_SUCCESS;
3185
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3186 3187 3188 3189 3190 3191 3192 3193 3194 3195
		/* The following call will also rename the .ibd data file if
		the table is stored in a single-table tablespace */

		success = dict_table_rename_in_cache(table, new_name,
				!row_is_mysql_tmp_table_name(new_name));
		if (!success) {
			trx->error_state = DB_SUCCESS;
			trx_general_rollback_for_mysql(trx, FALSE, NULL);
			trx->error_state = DB_SUCCESS;
			ut_print_timestamp(stderr);
3196 3197
			fputs(" InnoDB: Error in table rename, cannot rename ",
				stderr);
3198
			ut_print_name(stderr, trx, old_name);
3199
			fputs(" to ", stderr);
3200
			ut_print_name(stderr, trx, new_name);
3201
			putc('\n', stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3202 3203 3204 3205
			err = DB_ERROR;

			goto funct_exit;
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3206 3207 3208

		if (row_is_mysql_tmp_table_name(old_name)) {

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3209 3210 3211 3212 3213 3214 3215
			/* MySQL is doing an ALTER TABLE command and it
			renames the created temporary table to the name
			of the original table. In the ALTER TABLE we maybe
			created some FOREIGN KEY constraints for the temporary
			table. But we want to load also the foreign key
			constraint definitions for the original table name. */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3216 3217 3218 3219
			err = dict_load_foreigns(new_name);

			if (err != DB_SUCCESS) {
	    			ut_print_timestamp(stderr);
3220 3221
				fputs("  InnoDB: Error: in ALTER TABLE ",
					stderr);
3222
				ut_print_name(stderr, trx, new_name);
3223 3224 3225 3226 3227
				fputs("\n"
	"InnoDB: has or is referenced in foreign key constraints\n"
	"InnoDB: which are not compatible with the new table definition.\n",
					stderr);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3228
				ut_a(dict_table_rename_in_cache(table,
3229
					old_name, FALSE));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3230 3231 3232 3233 3234
				trx->error_state = DB_SUCCESS;
				trx_general_rollback_for_mysql(trx, FALSE,
									NULL);
				trx->error_state = DB_SUCCESS;
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3235 3236 3237 3238 3239 3240 3241 3242 3243 3244
		} else {
			err = dict_load_foreigns(new_name);

			if (err != DB_SUCCESS) {

	    			ut_print_timestamp(stderr);

				fputs(
				"  InnoDB: Error: in RENAME TABLE table ",
					stderr);
3245
				ut_print_name(stderr, trx, new_name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3246 3247
				fputs("\n"
     "InnoDB: is referenced in foreign key constraints\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3248
     "InnoDB: which are not compatible with the new table definition.\n",
3249
					stderr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3250 3251
     
				ut_a(dict_table_rename_in_cache(table,
3252
					old_name, FALSE));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3253 3254 3255 3256 3257 3258 3259
						
				trx->error_state = DB_SUCCESS;
				trx_general_rollback_for_mysql(trx, FALSE,
									NULL);
				trx->error_state = DB_SUCCESS;
			}
		}
3260 3261
	}
funct_exit:	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3262 3263 3264
	if (!recovering_temp_table) {
		row_mysql_unlock_data_dictionary(trx);
	}
3265

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3266 3267 3268 3269 3270 3271 3272
	if (graph) {
		que_graph_free(graph);
	}

	if (heap) {
		mem_heap_free(heap);
	}
3273
	
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3274 3275
  	trx_commit_for_mysql(trx);

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

3278 3279
	return((int) err);
}
3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303

/*************************************************************************
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 */
{
	mem_heap_t*	heap;
	dtuple_t*	prev_entry = NULL;
	ulint		matched_fields;
	ulint		matched_bytes;
	byte*		buf;
	ulint		ret;
	rec_t*		rec;
	ibool		is_ok	= TRUE;
	int		cmp;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3304 3305
	ibool		contains_null;
	ulint		i;
3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341
	
	*n_rows = 0;
	
	buf = mem_alloc(UNIV_PAGE_SIZE);
	heap = mem_heap_create(100);
	
	/* 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;

 	dtuple_set_n_fields(prebuilt->search_tuple, 0);

	prebuilt->select_lock_type = LOCK_NONE;

	ret = row_search_for_mysql(buf, PAGE_CUR_G, prebuilt, 0, 0);
loop:
	if (ret != DB_SUCCESS) {

		mem_free(buf);
		mem_heap_free(heap);

		return(is_ok);
	}

	*n_rows = *n_rows + 1;
	
	/* 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 */
	
	rec = buf + mach_read_from_4(buf);
3342

3343 3344 3345 3346 3347 3348 3349
	if (prev_entry != NULL) {
		matched_fields = 0;
		matched_bytes = 0;
	
		cmp = cmp_dtuple_rec_with_match(prev_entry, rec,
						&matched_fields,
						&matched_bytes);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364
		contains_null = FALSE;

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

	        for (i = 0;
                     i < dict_index_get_n_ordering_defined_by_user(index);
		     i++) {
	                if (UNIV_SQL_NULL == dfield_get_len(
                                      dtuple_get_nth_field(prev_entry, i))) {

                        	contains_null = TRUE;
	                }
	        }

3365
		if (cmp > 0) {
3366 3367 3368
			fputs("InnoDB: index records in a wrong order in ",
				stderr);
		not_ok:
3369 3370
			dict_index_name_print(stderr,
					prebuilt->trx, index);
3371 3372 3373 3374 3375 3376 3377
			fputs("\n"
				"InnoDB: prev record ", stderr);
			dtuple_print(stderr, prev_entry);
			fputs("\n"
				"InnoDB: record ", stderr);
			rec_print(stderr, rec);
			putc('\n', stderr);
3378 3379
			is_ok = FALSE;
		} else if ((index->type & DICT_UNIQUE)
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3380
			   && !contains_null
3381 3382
			   && matched_fields >=
			   dict_index_get_n_ordering_defined_by_user(index)) {
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
3383

3384 3385
			fputs("InnoDB: duplicate key in ", stderr);
			goto not_ok;
3386 3387 3388 3389 3390 3391 3392
		}
	}

	mem_heap_empty(heap);
	
	prev_entry = row_rec_to_index_entry(ROW_COPY_DATA, index, rec, heap);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3393
	ret = row_search_for_mysql(buf, PAGE_CUR_G, prebuilt, 0, ROW_SEL_NEXT);
3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407

	goto loop;	
}

/*************************************************************************
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
3408
	dict_table_t*	table		= prebuilt->table;
3409 3410
	dict_index_t*	index;
	ulint		n_rows;
3411
	ulint		n_rows_in_table	= ULINT_UNDEFINED;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3412 3413
	ulint		ret 		= DB_SUCCESS;
	ulint		old_isolation_level;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3414

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428
	if (prebuilt->table->ibd_file_missing) {
	        ut_print_timestamp(stderr);
	        fprintf(stderr, "  InnoDB: Error:\n"
"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
3429
	prebuilt->trx->op_info = "checking table";
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
3430

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3431 3432 3433 3434 3435 3436 3437 3438
	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;
3439 3440 3441 3442 3443 3444

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

3445 3446 3447
	index = dict_table_get_first_index(table);

	while (index != NULL) {
3448 3449 3450
		/* fputs("Validating index ", stderr);
		ut_print_name(stderr, index->name);
		putc('\n', stderr); */
3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
	
		if (!btr_validate_tree(index->tree)) {
			ret = DB_ERROR;
		} else {
			if (!row_scan_and_check_index(prebuilt,
							index, &n_rows)) {
				ret = DB_ERROR;
			}

			/* 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;
 
3469
				fputs("Error: ", stderr);
3470 3471
				dict_index_name_print(stderr,
					prebuilt->trx, index);
3472
				fprintf(stderr,
3473 3474
				" contains %lu entries, should be %lu\n",
					(ulong) n_rows,
3475
					(ulong) n_rows_in_table);
3476 3477 3478 3479 3480 3481
			}
		}

		index = dict_table_get_next_index(index);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3482 3483 3484
	/* Restore the original isolation level */
	prebuilt->trx->isolation_level = old_isolation_level;
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3485 3486 3487 3488 3489 3490 3491 3492
	/* We validate also the whole adaptive hash index for all tables
	at every CHECK TABLE */

	if (!btr_search_validate()) {

		ret = DB_ERROR;
	}

3493 3494 3495 3496 3497
	/* 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
3498
	prebuilt->trx->op_info = "";
3499

3500 3501
	return(ret);
}