row0mysql.c 65.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"
25 26 27
#include "trx0roll.h"
#include "trx0purge.h"
#include "lock0lock.h"
28
#include "rem0cmp.h"
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
29
#include "log0log.h"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
30
#include "btr0sea.h"
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
31

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
32 33 34
/* 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
35 36 37 38 39 40 41 42 43 44 45
/* 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;
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

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

/***********************************************************************
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
70 71 72 73 74 75 76 77
				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! */
78
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
79 80 81
	ulint	sum	= 0;
	ulint	i;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
82 83 84 85 86
	/* MySQL might assume the field is set to zero except the length and
	the pointer fields */

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

87 88 89 90 91
	/* 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
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
	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);

	/* We try to track an elusive bug which probably was fixed
	May 9, 2002, but better be sure: we probe the data buffer
	to make sure it is in valid allocated memory */

	for (i = 0; i < len; i++) {

		sum += (ulint)(data + i);
	}

	/* The variable below is identically false, we just fool the
	compiler to not optimize away our loop */
	if (row_mysql_identically_false) {

		printf("Sum %lu\n", sum);
	}

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
	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
201 202 203
				lock wait, or if no new error, the value
				of trx->error_state at the entry of this
				function */
204 205
	trx_t*		trx,	/* in: transaction */
	que_thr_t*	thr,	/* in: query thread */
206
	trx_savept_t*	savept)	/* in: savepoint or NULL */
207 208 209 210 211 212 213 214 215 216 217
{
	ulint	err;

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

	if (err == DB_DUPLICATE_KEY) {
218
           	if (savept) {
219 220 221 222
			/* Roll back the latest, possibly incomplete
			insertion or update */

			trx_general_rollback_for_mysql(trx, TRUE, savept);
223
		}
224
	} else if (err == DB_TOO_BIG_RECORD) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
225 226 227 228 229 230
           	if (savept) {
			/* Roll back the latest, possibly incomplete
			insertion or update */

			trx_general_rollback_for_mysql(trx, TRUE, savept);
		}
231
		/* MySQL will roll back the latest SQL statement */
232 233 234
	} 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
235 236 237 238 239 240
           	if (savept) {
			/* Roll back the latest, possibly incomplete
			insertion or update */

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

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
246
		if (trx->error_state != DB_SUCCESS) {
247 248 249 250 251 252 253 254 255
			que_thr_stop_for_mysql(thr);

			goto handle_new_error;
		}

		*new_err = err;

		return(TRUE);

256 257 258
	} else if (err == DB_DEADLOCK || err == DB_LOCK_WAIT_TIMEOUT) {
		/* Roll back the whole transaction; this resolution was added
		to version 3.23.43 */
259

260 261
		trx_general_rollback_for_mysql(trx, FALSE, NULL);
				
262
	} else if (err == DB_OUT_OF_FILE_SPACE) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
263 264 265 266 267 268
           	if (savept) {
			/* Roll back the latest, possibly incomplete
			insertion or update */

			trx_general_rollback_for_mysql(trx, TRUE, savept);
		}
269
		/* MySQL will roll back the latest SQL statement */
270 271 272

	} else if (err == DB_MUST_GET_MORE_FILE_SPACE) {

273 274 275 276 277 278
		fprintf(stderr,
		"InnoDB: The database cannot continue operation because of\n"
		"InnoDB: lack of space. You must add a new data file to\n"
		"InnoDB: my.cnf and restart the database.\n");
		
		exit(1);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
279 280 281 282 283 284 285 286 287 288 289
	} else if (err == DB_CORRUPTION) {

	       fprintf(stderr,
	    "InnoDB: We detected index corruption in an InnoDB type table.\n"
	    "InnoDB: You have to dump + drop + reimport the table or, in\n"
	    "InnoDB: a case of widespread corruption, dump all InnoDB\n"
	    "InnoDB: tables and recreate the whole InnoDB tablespace.\n"
	    "InnoDB: If the mysqld server crashes after the startup or when\n"
	    "InnoDB: you dump the tables, look at section 6.1 of\n"
	    "InnoDB: http://www.innodb.com/ibman.html for help.\n");

290
	} else {
291
		fprintf(stderr, "InnoDB: unknown error code %lu\n", err);
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
		ut_a(0);
	}		

	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
326
	prebuilt->magic_n = ROW_PREBUILT_ALLOCATED;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
327
	prebuilt->magic_n2 = ROW_PREBUILT_ALLOCATED;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
328

329 330 331 332 333 334
	prebuilt->table = table;

	prebuilt->trx = NULL;

	prebuilt->sql_stat_start = TRUE;

335 336
	prebuilt->mysql_has_locked = FALSE;

337
	prebuilt->index = NULL;
338 339 340

	prebuilt->used_in_HANDLER = FALSE;

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
	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;

	prebuilt->sel_graph = NULL;

	prebuilt->search_tuple = dtuple_create(heap,
						dict_table_get_n_cols(table));
	
	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
382

383 384 385 386 387 388 389 390 391 392 393 394 395
	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
396 397
	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED
	    || prebuilt->magic_n2 != ROW_PREBUILT_ALLOCATED) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
398
		fprintf(stderr,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
399 400 401
"InnoDB: Error: trying to free a corrupt\n"
"InnoDB: table handle. Magic n %lu, magic n2 %lu, table name %s\n",
		prebuilt->magic_n, prebuilt->magic_n2, prebuilt->table->name);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
402 403 404 405 406 407 408

		mem_analyze_corruption((byte*)prebuilt);

		ut_a(0);
	}

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

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
	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
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

			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))) {
				fprintf(stderr,
			"InnoDB: Error: trying to free a corrupt\n"
			"InnoDB: fetch buffer.\n");

				mem_analyze_corruption(
						prebuilt->fetch_cache[i]);

				ut_a(0);
			}

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

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

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
	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
477
	if (trx->magic_n != TRX_MAGIC_N) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
478
		fprintf(stderr,
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
479 480 481
		"InnoDB: Error: trying to use a corrupt\n"
		"InnoDB: trx handle. Magic n %lu\n",
		trx->magic_n);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
482

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
483
		mem_analyze_corruption((byte*)trx);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498

		ut_a(0);
	}

	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
		fprintf(stderr,
		"InnoDB: Error: trying to use a corrupt\n"
		"InnoDB: table handle. Magic n %lu, table name %s\n",
		prebuilt->magic_n, prebuilt->table->name);

		mem_analyze_corruption((byte*)prebuilt);

		ut_a(0);
	}

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
	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;

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

		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
572
	dict_table_t*	table)	/* in: table */
573 574 575
{
	ulint	counter;
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
576
	counter = table->stat_modified_counter;
577

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
578
	table->stat_modified_counter = counter + 1;
579 580 581

	/* 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
582 583 584
	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. */
585 586

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
589
		dict_update_statistics(table);
590 591
	}	
}
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
		  	
/*************************************************************************
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
632 633 634 635 636
	if (trx->auto_inc_lock) {

		return(DB_SUCCESS);
	}

637
	trx->op_info = (char *) "setting auto-inc lock";
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

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

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

	thr = que_fork_get_first_thr(prebuilt->ins_graph);

	que_thr_move_to_run_state_for_mysql(thr, trx);

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

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

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

	trx->error_state = err;

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

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

		if (was_lock_wait) {
			goto run_again;
		}

673
		trx->op_info = (char *) "";
674 675 676 677 678 679

		return(err);
	}

	que_thr_stop_for_mysql_no_error(thr, trx);
		
680
	trx->op_info = (char *) "";
681

682 683 684
	return((int) err);	
}
					
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
/*************************************************************************
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@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
706 707 708 709 710 711 712 713 714 715 716
	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
		fprintf(stderr,
		"InnoDB: Error: trying to free a corrupt\n"
		"InnoDB: table handle. Magic n %lu, table name %s\n",
		prebuilt->magic_n, prebuilt->table->name);

		mem_analyze_corruption((byte*)prebuilt);

		ut_a(0);
	}

717 718 719 720 721 722 723 724 725 726 727
	if (srv_created_new_raw || srv_force_recovery) {
		fprintf(stderr,
		"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");

		return(DB_ERROR);
	}

728
	trx->op_info = (char *) "inserting";
729

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

732 733 734 735 736
	if (node == NULL) {
		row_get_prebuilt_insert_row(prebuilt);
		node = prebuilt->ins_node;
	}

737 738
	row_mysql_convert_row_to_innobase(node->row, prebuilt, mysql_rec);
	
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
	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;
		}

769
		trx->op_info = (char *) "";
770

771 772 773 774 775 776 777
		return(err);
	}

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

778 779
	srv_n_rows_inserted++;
	
780 781 782 783 784
	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
785
	row_update_statistics_if_needed(prebuilt->table);
786
	trx->op_info = (char *) "";
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817

	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
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
/*************************************************************************
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);
}

855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
/*************************************************************************
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
877
		node = row_create_update_node_for_mysql(table, prebuilt->heap);
878

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
879
		prebuilt->upd_node = node;
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
		
		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; 
909
/*	ulint		ref_len; */
910 911 912
	upd_node_t*	node;
	dict_table_t*	table		= prebuilt->table;
	trx_t*		trx		= prebuilt->trx;
913
/*	mem_heap_t*	heap;
914 915
	dtuple_t*	search_tuple;
	dtuple_t*	row_tuple;
916
	mtr_t		mtr; */
917 918 919
	
	ut_ad(prebuilt && trx);
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
920 921
	UT_NOT_USED(mysql_rec);
	
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
922 923 924 925 926 927 928 929 930 931 932
	if (prebuilt->magic_n != ROW_PREBUILT_ALLOCATED) {
		fprintf(stderr,
		"InnoDB: Error: trying to free a corrupt\n"
		"InnoDB: table handle. Magic n %lu, table name %s\n",
		prebuilt->magic_n, prebuilt->table->name);

		mem_analyze_corruption((byte*)prebuilt);

		ut_a(0);
	}

933 934 935 936 937 938 939 940 941 942 943
	if (srv_created_new_raw || srv_force_recovery) {
		fprintf(stderr,
		"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");

		return(DB_ERROR);
	}

944
	trx->op_info = (char *) "updating or deleting";
945

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

948 949 950 951
	node = prebuilt->upd_node;

	clust_index = dict_table_get_first_index(table);

952
	if (prebuilt->pcur->btr_cur.index == clust_index) {
953
		btr_pcur_copy_stored_position(node->pcur, prebuilt->pcur);
954 955
	} else {
		btr_pcur_copy_stored_position(node->pcur, prebuilt->clust_pcur);
956
	}
957 958 959 960 961 962 963 964 965 966
		
	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 */

967 968 969 970 971 972 973 974 975
	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
976

977 978 979 980 981 982 983 984 985 986 987 988 989
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;
990
			trx->op_info = (char *) "";
991 992 993 994 995 996 997 998 999 1000

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

1001
		trx->op_info = (char *) "";
1002

1003 1004 1005 1006 1007
		return(err);
	}

	que_thr_stop_for_mysql_no_error(thr, trx);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1008
	if (node->is_delete) {
1009 1010 1011
		if (prebuilt->table->stat_n_rows > 0) {
			prebuilt->table->stat_n_rows--;
		}
1012 1013 1014 1015 1016

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

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

1020
	trx->op_info = (char *) "";
1021

1022 1023 1024
	return((int) err);
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
/**************************************************************************
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
1037 1038
	ulint	err;
	trx_t*	trx;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048

	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
1049 1050 1051 1052
	/* 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
1053
	if (err == DB_LOCK_WAIT) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1054
		/* Handle lock wait here */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1055
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1056 1057 1058
		que_thr_stop_for_mysql(thr);

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
		/* 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
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
		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);
}

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
/*************************************************************************
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);
}

1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
/*************************************************************************
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
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
/*************************************************************************
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 */
{
	char*	ptr;
	char	old_name[1000];

	ut_memcpy(old_name, table->name, ut_strlen(table->name) + 1);

	ptr = old_name;

	for (;;) {
		if (ptr >= old_name + ut_strlen(table->name) - 6) {
			trx_commit_for_mysql(trx);

			return(DB_ERROR);
		}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1173
		if (0 == ut_memcmp(ptr, (char*)"/rsql", 5)) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
			ptr++;
			*ptr = '#';

			break;
		}

		ptr++;
	}

	old_name[ut_strlen(table->name)
			- ut_strlen("_recover_innodb_tmp_table")] = '\0';

	return(row_rename_table_for_mysql(old_name, table->name, trx));
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1189
/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1190 1191
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
1192 1193

void
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
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
1212
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
	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 */
{
	ut_a(trx->dict_operation_lock_mode == 0);
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1231 1232 1233
	/* 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
1234
	rw_lock_x_lock(&dict_operation_lock);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1235 1236
	trx->dict_operation_lock_mode = RW_X_LATCH;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1237 1238 1239 1240
	mutex_enter(&(dict_sys->mutex));
}

/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1241
Unlocks the data dictionary exclusive lock. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1242 1243

void
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1244 1245 1246
row_mysql_unlock_data_dictionary(
/*=============================*/
	trx_t*	trx)	/* in: transaction */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1247
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1248 1249
	ut_a(trx->dict_operation_lock_mode == RW_X_LATCH);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1250 1251 1252 1253
	/* 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
1254
	rw_lock_x_unlock(&dict_operation_lock);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1255 1256

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

1259
/*************************************************************************
1260 1261 1262
Does a table creation operation for MySQL. If the name of the created
table ends to characters INNODB_MONITOR, then this also starts
printing of monitor output by the master thread. */
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273

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;
1274 1275
	ulint		namelen;
	ulint		keywordlen;
1276 1277 1278
	ulint		err;

	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1279
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1280
	ut_ad(trx->dict_operation_lock_mode == RW_X_LATCH);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1281
	ut_ad(mutex_own(&(dict_sys->mutex)));
1282
	
1283
	if (srv_created_new_raw) {
1284 1285 1286 1287 1288 1289 1290
		fprintf(stderr,
		"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");

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

1293 1294 1295
		return(DB_ERROR);
	}

1296
	trx->op_info = (char *) "creating table";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1297 1298 1299 1300
	
	if (0 == ut_strcmp(table->name, (char*)"mysql/host")
	    || 0 == ut_strcmp(table->name, (char*)"mysql/user")
	    || 0 == ut_strcmp(table->name, (char*)"mysql/db")) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
	    	
		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
1312 1313
	trx_start_if_not_started(trx);

1314 1315
	namelen = ut_strlen(table->name);

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1316 1317 1318 1319
	keywordlen = ut_strlen("_recover_innodb_tmp_table");

	if (namelen >= keywordlen
		    && 0 == ut_memcmp(table->name + namelen - keywordlen,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1320
 		     (char*)"_recover_innodb_tmp_table", keywordlen)) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333

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

	namelen = ut_strlen(table->name);

1334
	keywordlen = ut_strlen((char *) "innodb_monitor");
1335 1336 1337

	if (namelen >= keywordlen
		    && 0 == ut_memcmp(table->name + namelen - keywordlen,
1338
 				(char *) "innodb_monitor", keywordlen)) {
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350

		/* Table name ends to characters innodb_monitor:
		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);
	}

1351
	keywordlen = ut_strlen((char *) "innodb_lock_monitor");
1352 1353 1354

	if (namelen >= keywordlen
		    && 0 == ut_memcmp(table->name + namelen - keywordlen,
1355
 				(char *) "innodb_lock_monitor", keywordlen)) {
1356 1357 1358 1359 1360 1361

		srv_print_innodb_monitor = TRUE;
		srv_print_innodb_lock_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
	}

1362
	keywordlen = ut_strlen((char *) "innodb_tablespace_monitor");
1363 1364 1365

	if (namelen >= keywordlen
		    && 0 == ut_memcmp(table->name + namelen - keywordlen,
1366 1367
				      (char *) "innodb_tablespace_monitor", 
				      keywordlen)) {
1368 1369 1370 1371 1372

		srv_print_innodb_tablespace_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
	}

1373
	keywordlen = ut_strlen((char *) "innodb_table_monitor");
1374 1375 1376

	if (namelen >= keywordlen
		    && 0 == ut_memcmp(table->name + namelen - keywordlen,
1377 1378
				      (char *) "innodb_table_monitor",
				      keywordlen)) {
1379 1380 1381 1382 1383

		srv_print_innodb_table_monitor = TRUE;
		os_event_set(srv_lock_timeout_thread_event);
	}

1384 1385 1386 1387
	keywordlen = ut_strlen("innodb_mem_validate");

	if (namelen >= keywordlen
		    && 0 == ut_memcmp(table->name + namelen - keywordlen,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1388
 				(char*)"innodb_mem_validate", keywordlen)) {
1389 1390 1391 1392 1393 1394 1395 1396

	        /* We define here a debugging feature intended for
		developers */

	        printf("Validating InnoDB memory:\n"
		 "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"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1397
		 "by any semaphore.\n");
1398 1399 1400 1401 1402 1403

		ut_a(mem_validate());
		      
		printf("Memory validated\n");
	}

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
	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);

	ut_a(thr == que_fork_start_command(que_node_get_parent(thr),
						SESS_COMM_EXECUTE, 0));
	que_run_threads(thr);

	err = trx->error_state;

	if (err != DB_SUCCESS) {
		/* We have special error handling here */
1420
		
1421 1422 1423 1424
		trx->error_state = DB_SUCCESS;
		
		trx_general_rollback_for_mysql(trx, FALSE, NULL);

1425
		if (err == DB_OUT_OF_FILE_SPACE) {
1426 1427 1428
			fprintf(stderr, 
     "InnoDB: Warning: cannot create table %s because tablespace full\n",
				 table->name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1429
		     	row_drop_table_for_mysql(table->name, trx);
1430
		} else {
1431
		       	ut_a(err == DB_DUPLICATE_KEY);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1432 1433 1434

	    		ut_print_timestamp(stderr);

1435
			fprintf(stderr, 
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1436
     "  InnoDB: Error: table %s already exists in InnoDB internal\n"
1437 1438
     "InnoDB: data dictionary. Have you deleted the .frm file\n"
     "InnoDB: and not used DROP TABLE? Have you used DROP DATABASE\n"
1439
     "InnoDB: for InnoDB tables in MySQL version <= 3.23.43?\n"
1440
     "InnoDB: See the Restrictions section of the InnoDB manual.\n",
1441
				 table->name);
1442 1443 1444 1445 1446
			fprintf(stderr,
     "InnoDB: You can drop the orphaned table inside InnoDB by\n"
     "InnoDB: creating an InnoDB table with the same name in another\n"
     "InnoDB: database and moving the .frm file to the current database.\n"
     "InnoDB: Then MySQL thinks the table exists, and DROP TABLE will\n"
1447 1448 1449
     "InnoDB: succeed.\n"
     "InnoDB: You can look further help from section 15.1 of\n"
     "InnoDB: http://www.innodb.com/ibman.html\n");
1450
		}
1451 1452 1453 1454 1455

		trx->error_state = DB_SUCCESS;
	}

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

1457
	trx->op_info = (char *) "";
1458

1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
	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
1471
	dict_index_t*	index,		/* in: index definition */
1472 1473 1474 1475 1476
	trx_t*		trx)		/* in: transaction handle */
{
	ind_node_t*	node;
	mem_heap_t*	heap;
	que_thr_t*	thr;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1477 1478
	ulint		namelen;
	ulint		keywordlen;
1479
	ulint		err;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1480 1481 1482
	ulint		i;
	ulint		j;
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1483
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1484
	ut_ad(mutex_own(&(dict_sys->mutex)));
1485 1486
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
	
1487
	trx->op_info = (char *) "creating index";
1488

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

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1491 1492 1493 1494 1495 1496 1497
	namelen = ut_strlen(index->table_name);

	keywordlen = ut_strlen("_recover_innodb_tmp_table");

	if (namelen >= keywordlen
		    && 0 == ut_memcmp(
				index->table_name + namelen - keywordlen,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1498
 			(char*)"_recover_innodb_tmp_table", keywordlen)) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1499 1500 1501 1502

		return(DB_SUCCESS);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
	/* Check that the same column does not appear twice in the index.
	InnoDB assumes this in its algorithms, e.g., update of an index
	entry */

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

				fprintf(stderr,
"  InnoDB: Error: column %s appears twice in index %s of table %s\n"
"InnoDB: This is not allowed in InnoDB.\n",
				dict_index_get_nth_field(index, i)->name,
				index->name, index->table_name);

				err = DB_COL_APPEARS_TWICE_IN_INDEX;

				goto error_handling;
			}
		}
	}

1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
	heap = mem_heap_create(512);

	trx->dict_operation = TRUE;

	node = ind_create_graph_create(index, heap);

	thr = pars_complete_graph_for_exec(node, trx, heap);

	ut_a(thr == que_fork_start_command(que_node_get_parent(thr),
						SESS_COMM_EXECUTE, 0));
	que_run_threads(thr);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1540 1541 1542
 	err = trx->error_state;

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1544
error_handling:
1545 1546 1547 1548 1549 1550 1551
	if (err != DB_SUCCESS) {
		/* We have special error handling here */
		
		trx->error_state = DB_SUCCESS;

		trx_general_rollback_for_mysql(trx, FALSE, NULL);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1552
		row_drop_table_for_mysql(index->table_name, trx);
1553 1554 1555 1556

		trx->error_state = DB_SUCCESS;
	}
	
1557
	trx->op_info = (char *) "";
1558

1559 1560 1561
	return((int) err);
}

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
/*************************************************************************
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(
/*==============================*/
				/* out: error code or DB_SUCCESS */
	trx_t*	trx,		/* in: transaction */
	char*	sql_string,	/* in: table create statement where
				foreign keys are declared like:
				FOREIGN KEY (a, b) REFERENCES table2(c, d),
				table2 can be written also with the database
				name before it: test.table2 */
	char*	name)		/* in: table full name in the normalized form
				database_name/table_name */
{
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1584 1585
	ulint	namelen;
	ulint	keywordlen;
1586 1587
	ulint	err;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1588
	ut_ad(mutex_own(&(dict_sys->mutex)));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1589
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
1590 1591
	ut_a(sql_string);
	
1592
	trx->op_info = (char *) "adding foreign keys";
1593

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

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1596 1597 1598 1599 1600 1601 1602
	namelen = ut_strlen(name);

	keywordlen = ut_strlen("_recover_innodb_tmp_table");

	if (namelen >= keywordlen
		    && 0 == ut_memcmp(
				name + namelen - keywordlen,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1603
 			(char*)"_recover_innodb_tmp_table", keywordlen)) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1604 1605 1606 1607

		return(DB_SUCCESS);
	}

1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
	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);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1624
		row_drop_table_for_mysql(name, trx);
1625 1626 1627 1628 1629 1630 1631

		trx->error_state = DB_SUCCESS;
	}

	return((int) err);
}

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
/*************************************************************************
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(
/*===================================*/
			/* out: error code or DB_SUCCESS */
	char*	name)	/* in: table name */
{
	ulint	error;
	trx_t*	trx;

	trx = trx_allocate_for_background();

/*	fprintf(stderr, "InnoDB: Dropping table %s in background drop list\n",
							name); */
  	/* Drop the table in InnoDB */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1655
  	error = row_drop_table_for_mysql(name, trx);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666

	if (error != DB_SUCCESS) {
		fprintf(stderr,
	"InnoDB: Error: Dropping table %s in background drop list failed\n",
								name);
	}
  	
	/* 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
1667
	log_write_up_to(ut_dulint_max, LOG_WAIT_ONE_GROUP, TRUE);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714

  	trx_commit_for_mysql(trx);

  	trx_free_for_background(trx);

	return(DB_SUCCESS);
}

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

		return(n_tables + n_tables_dropped);
	}

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

1715 1716 1717 1718 1719 1720 1721
	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
1722 1723
	if (table->n_mysql_handles_opened > 0
				|| table->n_foreign_key_checks_running > 0) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1724 1725 1726 1727 1728 1729 1730 1731

		return(n_tables + n_tables_dropped);
	}

	n_tables_dropped++;
							
	row_drop_table_for_mysql_in_background(drop->table_name);

1732
already_dropped:
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1733 1734 1735 1736
	mutex_enter(&kernel_mutex);

	UT_LIST_REMOVE(row_mysql_drop_list, row_mysql_drop_list, drop);

1737 1738 1739 1740 1741
        ut_print_timestamp(stderr);
        fprintf(stderr,
		"  InnoDB: Dropped table %s in background drop queue.\n",
		drop->table_name);

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
	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 */
{
	ut_ad(mutex_own(&kernel_mutex));

	if (!row_mysql_drop_list_inited) {

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

/*************************************************************************
Adds a 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. */
static
void
row_add_table_to_background_drop_list(
/*==================================*/
	dict_table_t*	table)	/* in: table */
{
	row_mysql_drop_t*	drop;
	
	drop = mem_alloc(sizeof(row_mysql_drop_t));

	drop->table_name = mem_alloc(1 + ut_strlen(table->name));

	ut_memcpy(drop->table_name, table->name, 1 + ut_strlen(table->name));

	mutex_enter(&kernel_mutex);

	if (!row_mysql_drop_list_inited) {

		UT_LIST_INIT(row_mysql_drop_list);
		row_mysql_drop_list_inited = TRUE;
	}

	UT_LIST_ADD_LAST(row_mysql_drop_list, row_mysql_drop_list, drop);
	
/*	fprintf(stderr, "InnoDB: Adding table %s to background drop list\n",
							drop->table_name); */
	mutex_exit(&kernel_mutex);
}

1804
/*************************************************************************
1805 1806 1807
Drops a table for MySQL. If the name of the dropped table ends to
characters INNODB_MONITOR, then this also stops printing of monitor
output by the master thread. */
1808 1809 1810 1811 1812 1813

int
row_drop_table_for_mysql(
/*=====================*/
				/* out: error code or DB_SUCCESS */
	char*	name,		/* in: table name */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1814
	trx_t*	trx)		/* in: transaction handle */
1815 1816 1817 1818 1819 1820 1821 1822
{
	dict_table_t*	table;
	que_thr_t*	thr;
	que_t*		graph;
	ulint		err;
	char*		str1;
	char*		str2;
	ulint		len;
1823 1824
	ulint		namelen;
	ulint		keywordlen;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1825
	ibool		locked_dictionary	= FALSE;
1826
	char		buf[10000];
1827

1828 1829
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
	ut_a(name != NULL);
1830

1831
	if (srv_created_new_raw) {
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
		fprintf(stderr,
		"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");

		return(DB_ERROR);
	}

1842
	trx->op_info = (char *) "dropping table";
1843

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

1846
	namelen = ut_strlen(name);
1847
	keywordlen = ut_strlen((char *) "innodb_monitor");
1848 1849 1850

	if (namelen >= keywordlen
	    && 0 == ut_memcmp(name + namelen - keywordlen,
1851
			      (char *) "innodb_monitor", keywordlen)) {
1852 1853 1854 1855 1856

		/* Table name ends to characters innodb_monitor:
		stop monitor prints */
 				
		srv_print_innodb_monitor = FALSE;
1857 1858 1859
		srv_print_innodb_lock_monitor = FALSE;
	}

1860
	keywordlen = ut_strlen((char *) "innodb_lock_monitor");
1861 1862 1863

	if (namelen >= keywordlen
		    && 0 == ut_memcmp(name + namelen - keywordlen,
1864 1865
				      (char *) "innodb_lock_monitor",
				      keywordlen)) {
1866 1867 1868 1869 1870

		srv_print_innodb_monitor = FALSE;
		srv_print_innodb_lock_monitor = FALSE;
	}

1871
	keywordlen = ut_strlen((char *) "innodb_tablespace_monitor");
1872 1873 1874

	if (namelen >= keywordlen
		    && 0 == ut_memcmp(name + namelen - keywordlen,
1875 1876
				      (char *) "innodb_tablespace_monitor",
				      keywordlen)) {
1877 1878

		srv_print_innodb_tablespace_monitor = FALSE;
1879 1880
	}

1881
	keywordlen = ut_strlen((char *) "innodb_table_monitor");
1882 1883 1884

	if (namelen >= keywordlen
		    && 0 == ut_memcmp(name + namelen - keywordlen,
1885 1886
				      (char *) "innodb_table_monitor",
				      keywordlen)) {
1887 1888 1889 1890

		srv_print_innodb_table_monitor = FALSE;
	}

1891 1892 1893 1894 1895
	/* 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. */

1896
	str1 = (char *) 
1897
	"PROCEDURE DROP_TABLE_PROC () IS\n"
1898 1899
	"table_name CHAR;\n"
	"sys_foreign_id CHAR;\n"
1900 1901
	"table_id CHAR;\n"
	"index_id CHAR;\n"
1902
	"foreign_id CHAR;\n"
1903 1904
	"found INT;\n"
	"BEGIN\n"
1905 1906
	"table_name := '";
	
1907
	str2 = (char *) 
1908
	"';\n"
1909 1910 1911
	"SELECT ID INTO table_id\n"
	"FROM SYS_TABLES\n"
	"WHERE NAME = table_name;\n"
1912 1913 1914 1915 1916
	"IF (SQL % NOTFOUND) THEN\n"
	"	COMMIT WORK;\n"
	"	RETURN;\n"
	"END IF;\n"
	"found := 1;\n"
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
	"SELECT ID INTO sys_foreign_id\n"
	"FROM SYS_TABLES\n"
	"WHERE NAME = 'SYS_FOREIGN';\n"
	"IF (SQL % NOTFOUND) THEN\n"
	"	found := 0;\n"
	"END IF;\n"
	"IF (table_name = 'SYS_FOREIGN') THEN\n"
	"	found := 0;\n"
	"END IF;\n"
	"IF (table_name = 'SYS_FOREIGN_COLS') THEN\n"
	"	found := 0;\n"
	"END IF;\n"
	"WHILE found = 1 LOOP\n"
	"	SELECT ID INTO foreign_id\n"
	"	FROM SYS_FOREIGN\n"
	"	WHERE FOR_NAME = table_name;\n"	
	"	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"
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
	"WHILE found = 1 LOOP\n"
	"	SELECT ID INTO index_id\n"
	"	FROM SYS_INDEXES\n"
	"	WHERE TABLE_ID = table_id;\n"	
	"	IF (SQL % NOTFOUND) THEN\n"
	"		found := 0;\n"
	"	ELSE"
	"		DELETE FROM SYS_FIELDS WHERE INDEX_ID = index_id;\n"
	"		DELETE FROM SYS_INDEXES WHERE ID = index_id;\n"
	"	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";

	len = ut_strlen(str1);

	ut_memcpy(buf, str1, len);
	ut_memcpy(buf + len, name, ut_strlen(name));

	len += ut_strlen(name);

	ut_memcpy(buf + len, str2, ut_strlen(str2) + 1);

	/* 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
1969
	if (trx->dict_operation_lock_mode != RW_X_LATCH) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1970 1971
		/* Prevent foreign key checks etc. while we are dropping the
		table */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1972

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1973 1974 1975
		row_mysql_lock_data_dictionary(trx);

		locked_dictionary = TRUE;
1976 1977
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1978 1979 1980
	ut_ad(mutex_own(&(dict_sys->mutex)));
	ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_EX));
	
1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
	graph = pars_sql(buf);

	ut_a(graph);

	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
1994
	    	ut_print_timestamp(stderr);
1995

1996
		fprintf(stderr, 
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1997
     	"  InnoDB: Error: table %s does not exist in the InnoDB internal\n"
1998 1999
     	"InnoDB: data dictionary though MySQL is trying to drop it.\n"
     	"InnoDB: Have you copied the .frm file of the table to the\n"
2000 2001 2002
	"InnoDB: MySQL database directory from another database?\n"
	"InnoDB: You can look further help from section 15.1 of\n"
        "InnoDB: http://www.innodb.com/ibman.html\n",
2003
				 name);
2004 2005 2006
		goto funct_exit;
	}

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2007 2008
	if (table->n_mysql_handles_opened > 0) {
		
2009 2010 2011 2012 2013 2014 2015
	        ut_print_timestamp(stderr);
	        fprintf(stderr,
		  "  InnoDB: Warning: MySQL is trying to drop table %s\n"
		  "InnoDB: though there are still open handles to it.\n"
		  "InnoDB: Adding the table to the background drop queue.\n",
		  table->name);

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2016
		row_add_table_to_background_drop_list(table);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2017

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2018
		err = DB_SUCCESS;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2019

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2020
		goto funct_exit;
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2021
	}
2022

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
	if (table->n_foreign_key_checks_running > 0) {
		
	        ut_print_timestamp(stderr);
	        fprintf(stderr,
		  "  InnoDB: You are trying to drop table %s\n"
		  "InnoDB: though there are foreign key check running on it.\n"
		  "InnoDB: Adding the table to the background drop queue.\n",
		  table->name);

		row_add_table_to_background_drop_list(table);

		err = DB_SUCCESS;

		goto funct_exit;
	}
	
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2039 2040 2041 2042
	/* Remove any locks there are on the table or its records */
	
	lock_reset_all_on_table(table);

2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
	trx->dict_operation = TRUE;
	trx->table_id = table->id;

	ut_a(thr = que_fork_start_command(graph, SESS_COMM_EXECUTE, 0));

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

		ut_a(0);
	} else {
		dict_table_remove_from_cache(table);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2062 2063 2064 2065 2066 2067 2068

		if (dict_load_table(name) != NULL) {
			ut_print_timestamp(stderr);
			fprintf(stderr,
"  InnoDB: Error: dropping of table %s failed!\n", name);

		}
2069
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2070
funct_exit:
2071

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2072 2073
	if (locked_dictionary) {
		row_mysql_unlock_data_dictionary(trx);	
2074 2075 2076 2077
	}

	que_graph_free(graph);
	
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2078 2079
  	trx_commit_for_mysql(trx);

2080
	trx->op_info = (char *) "";
2081

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2082 2083
	srv_wake_master_thread();

2084 2085 2086
	return((int) err);
}

2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
/*************************************************************************
Drops a database for MySQL. */

int
row_drop_database_for_mysql(
/*========================*/
			/* out: error code or DB_SUCCESS */
	char*	name,	/* in: database name which ends to '/' */
	trx_t*	trx)	/* in: transaction handle */
{
2097
        dict_table_t* table;
2098 2099 2100 2101 2102 2103 2104
	char*	table_name;
	int	err	= DB_SUCCESS;
	
	ut_ad(trx->mysql_thread_id == os_thread_get_curr_id());
	ut_a(name != NULL);
	ut_a(name[strlen(name) - 1] == '/');
	
2105
	trx->op_info = (char *) "dropping database";
2106
	
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2107
	trx_start_if_not_started(trx);
2108
loop:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2109
	row_mysql_lock_data_dictionary(trx);
2110

2111
	while ((table_name = dict_get_first_table_name_in_db(name))) {
2112 2113
		ut_a(memcmp(table_name, name, strlen(name)) == 0);

2114 2115 2116 2117 2118 2119 2120 2121
		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
2122
			row_mysql_unlock_data_dictionary(trx);
2123

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2124 2125 2126 2127 2128 2129 2130 2131 2132
			ut_print_timestamp(stderr);
			fprintf(stderr,
		"  InnoDB: Warning: MySQL is trying to drop database %s\n"
	    	"InnoDB: though there are still open handles to table %s.\n",
				name, table_name);

		        os_thread_sleep(1000000);

		        mem_free(table_name);
2133 2134 2135 2136

		        goto loop;
		}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2137
		err = row_drop_table_for_mysql(table_name, trx);
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148

		mem_free(table_name);

		if (err != DB_SUCCESS) {
			fprintf(stderr,
	"InnoDB: DROP DATABASE %s failed with error %lu for table %s\n",
				name, (ulint)err, table_name);
			break;
		}
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2149
	row_mysql_unlock_data_dictionary(trx);
2150
	
2151 2152
	trx_commit_for_mysql(trx);

2153
	trx->op_info = (char *) "";
2154 2155 2156 2157

	return(err);
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
/*************************************************************************
Checks if a table name contains the string "/#sql" which denotes temporary
tables in MySQL. */
static
ibool
row_is_mysql_tmp_table_name(
/*========================*/
			/* out: TRUE if temporary table */
	char*	name)	/* in: table name in the form 'database/tablename' */
{
	ulint	i;

	for (i = 0; i <= ut_strlen(name) - 5; i++) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2171
		if (ut_memcmp(name + i, (char*)"/#sql", 5) == 0) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2172 2173 2174 2175 2176 2177 2178 2179

			return(TRUE);
		}
	}

	return(FALSE);
}

2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
/*************************************************************************
Renames a table for MySQL. */

int
row_rename_table_for_mysql(
/*=======================*/
				/* out: error code or DB_SUCCESS */
	char*	old_name,	/* in: old table name */
	char*	new_name,	/* in: new table name */
	trx_t*	trx)		/* in: transaction handle */
{
	dict_table_t*	table;
	que_thr_t*	thr;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2193
	que_t*		graph			= NULL;
2194 2195 2196 2197
	ulint		err;
	char*		str1;
	char*		str2;
	char*		str3;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2198 2199 2200
	mem_heap_t*	heap			= NULL;
	char**		constraints_to_drop	= NULL;
	ulint		n_constraints_to_drop	= 0;
2201
	ulint		len;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2202
	ulint		i;
2203 2204 2205 2206 2207 2208
	char		buf[10000];

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

2209 2210 2211 2212 2213 2214 2215 2216
	if (srv_created_new_raw || srv_force_recovery) {
		fprintf(stderr,
		"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");

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2217 2218 2219
  		trx_commit_for_mysql(trx);
		return(DB_ERROR);
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2220 2221 2222 2223
	
	if (0 == ut_strcmp(new_name, (char*)"mysql/host")
	    || 0 == ut_strcmp(new_name, (char*)"mysql/user")
	    || 0 == ut_strcmp(new_name, (char*)"mysql/db")) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2224 2225 2226 2227 2228 2229 2230
	    	
		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);
2231 2232 2233
		return(DB_ERROR);
	}

2234
	trx->op_info = (char *) "renaming table";
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2235
	trx_start_if_not_started(trx);
2236

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
	/* 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(old_name);

	if (!table) {
		err = DB_TABLE_NOT_FOUND;

		goto funct_exit;
	}

2250
	str1 = (char *) 
2251
	"PROCEDURE RENAME_TABLE_PROC () IS\n"
2252 2253
	"new_table_name CHAR;\n"
	"old_table_name CHAR;\n"
2254
	"BEGIN\n"
2255
	"new_table_name :='";
2256

2257
	str2 = (char *) 
2258
	"';\nold_table_name := '";
2259

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2260 2261
	if (row_is_mysql_tmp_table_name(new_name)) {

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2262 2263 2264 2265 2266
		/* 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
2267

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298
		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;
		}
		
		str3 = mem_heap_alloc(heap,
					1000 + 500 * n_constraints_to_drop);
		*str3 = '\0';
		sprintf(str3,
			"';\n"
			"UPDATE SYS_TABLES SET NAME = new_table_name\n"
			"WHERE NAME = old_table_name;\n");

		for (i = 0; i < n_constraints_to_drop; i++) {
			sprintf(str3 + strlen(str3),
			"DELETE FROM SYS_FOREIGN_COLS WHERE ID = '%s';\n"
			"DELETE FROM SYS_FOREIGN WHERE ID = '%s';\n",
				constraints_to_drop[i],
				constraints_to_drop[i]);
		}

		sprintf(str3 + strlen(str3),
			"END;\n");

		ut_a(strlen(str3) < 1000 + 500 * n_constraints_to_drop);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2299
	} else {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2300
		str3 = (char*)
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2301 2302 2303 2304 2305 2306 2307 2308 2309
		"';\n"
		"UPDATE SYS_TABLES SET NAME = new_table_name\n"
		"WHERE NAME = old_table_name;\n"
		"UPDATE SYS_FOREIGN SET FOR_NAME = new_table_name\n"
		"WHERE FOR_NAME = old_table_name;\n"
		"UPDATE SYS_FOREIGN SET REF_NAME = new_table_name\n"
		"WHERE REF_NAME = old_table_name;\n"
		"END;\n";
	}
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344

	len = ut_strlen(str1);

	ut_memcpy(buf, str1, len);

	ut_memcpy(buf + len, new_name, ut_strlen(new_name));

	len += ut_strlen(new_name);

	ut_memcpy(buf + len, str2, ut_strlen(str2));

	len += ut_strlen(str2);

	ut_memcpy(buf + len, old_name, ut_strlen(old_name));

	len += ut_strlen(old_name);

	ut_memcpy(buf + len, str3, ut_strlen(str3) + 1);
	
	graph = pars_sql(buf);

	ut_a(graph);

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

	graph->fork_type = QUE_FORK_MYSQL_INTERFACE;

	ut_a(thr = que_fork_start_command(graph, SESS_COMM_EXECUTE, 0));

	que_run_threads(thr);

	err = trx->error_state;

	if (err != DB_SUCCESS) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2345 2346 2347 2348 2349 2350
		if (err == DB_DUPLICATE_KEY) {
	    		ut_print_timestamp(stderr);

			fprintf(stderr,
     "  InnoDB: Error: table %s exists in the InnoDB internal data\n"
     "InnoDB: dictionary though MySQL is trying rename table %s to it.\n"
2351 2352 2353
     "InnoDB: Have you deleted the .frm file and not used DROP TABLE?\n"
     "InnoDB: You can look further help from section 15.1 of\n"
     "InnoDB: http://www.innodb.com/ibman.html\n",
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
			new_name, old_name);

			fprintf(stderr,
     "InnoDB: If table %s is a temporary table #sql..., then it can be that\n"
     "InnoDB: there are still queries running on the table, and it will be\n"
     "InnoDB: dropped automatically when the queries end.\n", new_name);
			
			fprintf(stderr,
     "InnoDB: You can drop the orphaned table inside InnoDB by\n"
     "InnoDB: creating an InnoDB table with the same name in another\n"
     "InnoDB: database and moving the .frm file to the current database.\n"
     "InnoDB: Then MySQL thinks the table exists, and DROP TABLE will\n"
     "InnoDB: succeed.\n");
		}

		trx->error_state = DB_SUCCESS;
		trx_general_rollback_for_mysql(trx, FALSE, NULL);
		trx->error_state = DB_SUCCESS;
2372
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2373 2374 2375 2376 2377
		ut_a(dict_table_rename_in_cache(table, new_name,
				!row_is_mysql_tmp_table_name(new_name)));

		if (row_is_mysql_tmp_table_name(old_name)) {

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2378 2379 2380 2381 2382 2383 2384
			/* 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
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
			err = dict_load_foreigns(new_name);

			if (err != DB_SUCCESS) {

	    			ut_print_timestamp(stderr);

				fprintf(stderr,
     "  InnoDB: Error: in ALTER TABLE table %s\n"
     "InnoDB: has or is referenced in foreign key constraints\n"
     "InnoDB: which are not compatible with the new table definition.\n",
     new_name);
     
				ut_a(dict_table_rename_in_cache(table,
							old_name, FALSE));
						
				trx->error_state = DB_SUCCESS;
				trx_general_rollback_for_mysql(trx, FALSE,
									NULL);
				trx->error_state = DB_SUCCESS;
			}
		}
2406 2407
	}
funct_exit:	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2408
	row_mysql_unlock_data_dictionary(trx);
2409

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2410 2411 2412 2413 2414 2415 2416
	if (graph) {
		que_graph_free(graph);
	}

	if (heap) {
		mem_heap_free(heap);
	}
2417
	
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2418 2419
  	trx_commit_for_mysql(trx);

2420
	trx->op_info = (char *) "";
2421

2422 2423
	return((int) err);
}
2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447

/*************************************************************************
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
2448 2449
	ibool		contains_null;
	ulint		i;
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2450
	char           	err_buf[1000];
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
	
	*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);
	
	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
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
		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;
	                }
	        }

2510 2511 2512
		if (cmp > 0) {
			fprintf(stderr,
			"Error: index records in a wrong order in index %s\n",
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2513 2514 2515 2516 2517 2518 2519
								index->name);

	  		dtuple_sprintf(err_buf, 900, prev_entry);
	  		fprintf(stderr, "InnoDB: prev record %s\n", err_buf);

	  		rec_sprintf(err_buf, 900, rec);
	  		fprintf(stderr, "InnoDB: record %s\n", err_buf);
2520 2521 2522

			is_ok = FALSE;
		} else if ((index->type & DICT_UNIQUE)
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2523
			   && !contains_null
2524 2525
			   && matched_fields >=
			   dict_index_get_n_ordering_defined_by_user(index)) {
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2526 2527 2528 2529 2530 2531 2532 2533 2534

			fprintf(stderr, "Error: duplicate key in index %s\n",
								index->name);

	  		dtuple_sprintf(err_buf, 900, prev_entry);
	  		fprintf(stderr, "InnoDB: prev record %s\n", err_buf);

	  		rec_sprintf(err_buf, 900, rec);
	  		fprintf(stderr, "InnoDB: record %s\n", err_buf);
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558

			is_ok = FALSE;			   	
		}
	}

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

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

	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
2559
	dict_table_t*	table		= prebuilt->table;
2560 2561
	dict_index_t*	index;
	ulint		n_rows;
2562
	ulint		n_rows_in_table	= ULINT_UNDEFINED;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2563 2564 2565
	ulint		ret 		= DB_SUCCESS;
	ulint		old_isolation_level;
	
2566
	prebuilt->trx->op_info = (char *) "checking table";
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
2567

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2568 2569 2570 2571 2572 2573 2574 2575 2576
	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;
	
2577 2578 2579
	index = dict_table_get_first_index(table);

	while (index != NULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2580
      		/* fprintf(stderr, "Validating index %s\n", index->name); */
2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
	
		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;
 
				fprintf(stderr,
		"Error: index %s contains %lu entries, should be %lu\n",
					index->name, n_rows, n_rows_in_table);
			}
		}

		index = dict_table_get_next_index(index);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2608 2609 2610
	/* Restore the original isolation level */
	prebuilt->trx->isolation_level = old_isolation_level;
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2611 2612 2613 2614 2615 2616 2617 2618
	/* We validate also the whole adaptive hash index for all tables
	at every CHECK TABLE */

	if (!btr_search_validate()) {

		ret = DB_ERROR;
	}

2619
	prebuilt->trx->op_info = (char *) "";
2620

2621 2622
	return(ret);
}