dict0dict.c 113 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/**********************************************************************
Data dictionary system

(c) 1996 Innobase Oy

Created 1/8/1996 Heikki Tuuri
***********************************************************************/

#include "dict0dict.h"

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

#include "buf0buf.h"
#include "data0type.h"
#include "mach0data.h"
#include "dict0boot.h"
#include "dict0mem.h"
20
#include "dict0crea.h"
21 22
#include "trx0undo.h"
#include "btr0btr.h"
23
#include "btr0cur.h"
24 25 26 27
#include "btr0sea.h"
#include "pars0pars.h"
#include "pars0sym.h"
#include "que0que.h"
28
#include "rem0cmp.h"
29 30 31

dict_sys_t*	dict_sys	= NULL;	/* the dictionary system */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
32
rw_lock_t	dict_operation_lock;	/* table create, drop, etc. reserve
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
33
					this in X-mode; implicit or backround
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
34 35 36 37
					operations purge, rollback, foreign
					key checks reserve this in S-mode; we
					cannot trust that MySQL protects
					implicit or background operations
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
38 39 40 41 42
					a table drop since MySQL does not
					know of them; therefore we need this;
					NOTE: a transaction which reserves
					this must keep book on the mode in
					trx->dict_operation_lock_mode */
43

44 45 46 47 48 49 50 51
#define	DICT_HEAP_SIZE		100	/* initial memory heap size when
					creating a table or index object */
#define DICT_POOL_PER_TABLE_HASH 512	/* buffer pool max size per table
					hash table fixed size in bytes */
#define DICT_POOL_PER_COL_HASH	128	/* buffer pool max size per column
					hash table fixed size in bytes */
#define DICT_POOL_PER_VARYING	4	/* buffer pool max size per data
					dictionary varying size in bytes */
52 53 54 55

/* Identifies generated InnoDB foreign key names */
static char	dict_ibfk[] = "_ibfk_";

56
#ifndef UNIV_HOTBACKUP
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
/**********************************************************************
Compares NUL-terminated UTF-8 strings case insensitively.

NOTE: the prototype of this function is copied from ha_innodb.cc! If you change
this function, you MUST change also the prototype here! */
extern
int
innobase_strcasecmp(
/*================*/
				/* out: 0 if a=b, <0 if a<b, >1 if a>b */
	const char*	a,	/* in: first string to compare */
	const char*	b);	/* in: second string to compare */

/**********************************************************************
Makes all characters in a NUL-terminated UTF-8 string lower case.

NOTE: the prototype of this function is copied from ha_innodb.cc! If you change
this function, you MUST change also the prototype here! */
extern
void
innobase_casedn_str(
/*================*/
	char*	a);	/* in/out: string to put in lower case */
80
#endif /* !UNIV_HOTBACKUP */
81

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
/**************************************************************************
Adds a column to the data dictionary hash table. */
static
void
dict_col_add_to_cache(
/*==================*/
	dict_table_t*	table,	/* in: table */
	dict_col_t*	col);	/* in: column */
/**************************************************************************
Repositions a column in the data dictionary hash table when the table name
changes. */
static
void
dict_col_reposition_in_cache(
/*=========================*/
	dict_table_t*	table,		/* in: table */
	dict_col_t*	col,		/* in: column */
99
	const char*	new_name);	/* in: new table name */
100 101 102 103 104 105 106 107 108 109 110 111 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
/**************************************************************************
Removes a column from the data dictionary hash table. */
static
void
dict_col_remove_from_cache(
/*=======================*/
	dict_table_t*	table,	/* in: table */
	dict_col_t*	col);	/* in: column */
/**************************************************************************
Removes an index from the dictionary cache. */
static
void
dict_index_remove_from_cache(
/*=========================*/
	dict_table_t*	table,	/* in: table */
	dict_index_t*	index);	/* in, own: index */
/***********************************************************************
Copies fields contained in index2 to index1. */
static
void
dict_index_copy(
/*============*/
	dict_index_t*	index1,	/* in: index to copy to */
	dict_index_t*	index2,	/* in: index to copy from */
	ulint		start,	/* in: first position to copy */
	ulint		end);	/* in: last position to copy */
/***********************************************************************
Tries to find column names for the index in the column hash table and
sets the col field of the index. */
static
ibool
dict_index_find_cols(
/*=================*/
				/* out: TRUE if success */
	dict_table_t*	table,	/* in: table */
	dict_index_t*	index);	/* in: index */	
/***********************************************************************
Builds the internal dictionary cache representation for a clustered
index, containing also system fields not defined by the user. */
static
dict_index_t*
dict_index_build_internal_clust(
/*============================*/
				/* out, own: the internal representation
				of the clustered index */
	dict_table_t*	table,	/* in: table */
	dict_index_t*	index);	/* in: user representation of a clustered
				index */	
/***********************************************************************
Builds the internal dictionary cache representation for a non-clustered
index, containing also system fields not defined by the user. */
static
dict_index_t*
dict_index_build_internal_non_clust(
/*================================*/
				/* out, own: the internal representation
				of the non-clustered index */
	dict_table_t*	table,	/* in: table */
	dict_index_t*	index);	/* in: user representation of a non-clustered
				index */	
/**************************************************************************
161
Removes a foreign constraint struct from the dictionary cache. */
162 163
static
void
164 165 166
dict_foreign_remove_from_cache(
/*===========================*/
	dict_foreign_t*	foreign);	/* in, own: foreign constraint */
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
/**************************************************************************
Prints a column data. */
static
void
dict_col_print_low(
/*===============*/
	dict_col_t*	col);	/* in: column */
/**************************************************************************
Prints an index data. */
static
void
dict_index_print_low(
/*=================*/
	dict_index_t*	index);	/* in: index */
/**************************************************************************
Prints a field data. */
static
void
dict_field_print_low(
/*=================*/
	dict_field_t*	field);	/* in: field */
188 189 190 191 192 193 194
/*************************************************************************
Frees a foreign key struct. */
static
void
dict_foreign_free(
/*==============*/
	dict_foreign_t*	foreign);	/* in, own: foreign key struct */
195

196
/* Stream for storing detailed information about the latest foreign key
197
and unique key errors */
198
FILE*	dict_foreign_err_file		= NULL;
199 200
mutex_t	dict_foreign_err_mutex; 	/* mutex protecting the foreign
					and unique error buffers */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
201
	
202 203 204 205 206 207 208 209 210 211 212
/**********************************************************************
Makes all characters in a NUL-terminated UTF-8 string lower case. */

void
dict_casedn_str(
/*============*/
	char*	a)	/* in/out: string to put in lower case */
{
	innobase_casedn_str(a);
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
213 214
/************************************************************************
Checks if the database name in two table names is the same. */
215

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
216 217 218
ibool
dict_tables_have_same_db(
/*=====================*/
219 220 221 222 223
				/* out: TRUE if same db name */
	const char*	name1,	/* in: table name in the form
				dbname '/' tablename */
	const char*	name2)	/* in: table name in the form
				dbname '/' tablename */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
224
{
225 226
	for (; *name1 == *name2; name1++, name2++) {
		if (*name1 == '/') {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
227 228
			return(TRUE);
		}
229
		ut_a(*name1); /* the names must contain '/' */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
230 231 232 233 234 235 236
	}
	return(FALSE);
}

/************************************************************************
Return the end of table name where we have removed dbname and '/'. */
static
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
237
const char*
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
238 239
dict_remove_db_name(
/*================*/
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
240 241 242
				/* out: table name */
	const char*	name)	/* in: table name in the form
				dbname '/' tablename */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
243
{
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
244
	const char*	s;
245 246 247 248
	s = strchr(name, '/');
	ut_a(s);
	if (s) s++;
	return(s);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
249
}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
250 251 252 253 254 255 256

/************************************************************************
Get the database name length in a table name. */

ulint
dict_get_db_name_len(
/*=================*/
257 258 259
				/* out: database name length */
	const char*	name)	/* in: table name in the form
				dbname '/' tablename */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
260
{
261 262 263 264
	const char*	s;
	s = strchr(name, '/');
	ut_a(s);
	return(s - name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
265
}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
266
	
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
/************************************************************************
Reserves the dictionary system mutex for MySQL. */

void
dict_mutex_enter_for_mysql(void)
/*============================*/
{
	mutex_enter(&(dict_sys->mutex));
}
	
/************************************************************************
Releases the dictionary system mutex for MySQL. */

void
dict_mutex_exit_for_mysql(void)
/*===========================*/
{
	mutex_exit(&(dict_sys->mutex));
}
	
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
/************************************************************************
Decrements the count of open MySQL handles to a table. */

void
dict_table_decrement_handle_count(
/*==============================*/
	dict_table_t*	table)	/* in: table */
{
	mutex_enter(&(dict_sys->mutex));

	ut_a(table->n_mysql_handles_opened > 0);

	table->n_mysql_handles_opened--;
	
	mutex_exit(&(dict_sys->mutex));
}

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
/************************************************************************
Gets the nth column of a table. */

dict_col_t*
dict_table_get_nth_col_noninline(
/*=============================*/
				/* out: pointer to column object */
	dict_table_t*	table,	/* in: table */
	ulint		pos)	/* in: position of column */
{
	return(dict_table_get_nth_col(table, pos));
}

/************************************************************************
Gets the first index on the table (the clustered index). */

dict_index_t*
dict_table_get_first_index_noninline(
/*=================================*/
				/* out: index, NULL if none exists */
	dict_table_t*	table)	/* in: table */
{
	return(dict_table_get_first_index(table));
}

/************************************************************************
Gets the next index on the table. */

dict_index_t*
dict_table_get_next_index_noninline(
/*================================*/
				/* out: index, NULL if none left */
	dict_index_t*	index)	/* in: index */
{
	return(dict_table_get_next_index(index));
}

/**************************************************************************
Returns an index object. */

dict_index_t*
dict_table_get_index_noninline(
/*===========================*/
				/* out: index, NULL if does not exist */
	dict_table_t*	table,	/* in: table */
349
	const char*	name)	/* in: index name */
350 351 352
{
	return(dict_table_get_index(table, name));
}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
353
	
354
/************************************************************************
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
355
Initializes the autoinc counter. It is not an error to initialize an already
356 357 358 359 360 361
initialized counter. */

void
dict_table_autoinc_initialize(
/*==========================*/
	dict_table_t*	table,	/* in: table */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
362
	ib_longlong	value)	/* in: next value to assign to a row */
363 364 365 366 367 368 369 370 371 372
{
	mutex_enter(&(table->autoinc_mutex));

	table->autoinc_inited = TRUE;
	table->autoinc = value;

	mutex_exit(&(table->autoinc_mutex));
}

/************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
373 374
Gets the next autoinc value (== autoinc counter value), 0 if not yet
initialized. If initialized, increments the counter by 1. */
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

ib_longlong
dict_table_autoinc_get(
/*===================*/
				/* out: value for a new row, or 0 */
	dict_table_t*	table)	/* in: table */
{
	ib_longlong	value;

	mutex_enter(&(table->autoinc_mutex));

	if (!table->autoinc_inited) {

		value = 0;
	} else {
		value = table->autoinc;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
391
		table->autoinc = table->autoinc + 1;
392 393 394 395 396 397 398
	}
	
	mutex_exit(&(table->autoinc_mutex));

	return(value);
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
399
/************************************************************************
400
Decrements the autoinc counter value by 1. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
401

402 403 404
void
dict_table_autoinc_decrement(
/*=========================*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
405 406 407 408
	dict_table_t*	table)	/* in: table */
{
	mutex_enter(&(table->autoinc_mutex));

409
	table->autoinc = table->autoinc - 1;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
410 411 412 413
	
	mutex_exit(&(table->autoinc_mutex));
}

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
/************************************************************************
Reads the next autoinc value (== autoinc counter value), 0 if not yet
initialized. */

ib_longlong
dict_table_autoinc_read(
/*====================*/
				/* out: value for a new row, or 0 */
	dict_table_t*	table)	/* in: table */
{
	ib_longlong	value;

	mutex_enter(&(table->autoinc_mutex));

	if (!table->autoinc_inited) {

		value = 0;
	} else {
		value = table->autoinc;
	}
	
	mutex_exit(&(table->autoinc_mutex));

	return(value);
}

440
/************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
Peeks the autoinc counter value, 0 if not yet initialized. Does not
increment the counter. The read not protected by any mutex! */

ib_longlong
dict_table_autoinc_peek(
/*====================*/
				/* out: value of the counter */
	dict_table_t*	table)	/* in: table */
{
	ib_longlong	value;

	if (!table->autoinc_inited) {

		value = 0;
	} else {
		value = table->autoinc;
	}

	return(value);
}

/************************************************************************
Updates the autoinc counter if the value supplied is equal or bigger than the
464 465 466 467 468
current value. If not inited, does nothing. */

void
dict_table_autoinc_update(
/*======================*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
469

470 471 472 473 474 475
	dict_table_t*	table,	/* in: table */
	ib_longlong	value)	/* in: value which was assigned to a row */
{
	mutex_enter(&(table->autoinc_mutex));

	if (table->autoinc_inited) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
476 477
		if (value >= table->autoinc) {
			table->autoinc = value + 1;
478 479 480 481 482 483
		}
	}	

	mutex_exit(&(table->autoinc_mutex));
}

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
/************************************************************************
Looks for column n in an index. */

ulint
dict_index_get_nth_col_pos(
/*=======================*/
				/* out: position in internal representation
				of the index; if not contained, returns
				ULINT_UNDEFINED */
	dict_index_t*	index,	/* in: index */
	ulint		n)	/* in: column number */
{
	dict_field_t*	field;
	dict_col_t*	col;
	ulint		pos;
	ulint		n_fields;
	
	ut_ad(index);
	ut_ad(index->magic_n == DICT_INDEX_MAGIC_N);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
504 505
	col = dict_table_get_nth_col(index->table, n);

506 507 508 509 510 511 512 513 514 515
	if (index->type & DICT_CLUSTERED) {

		return(col->clust_pos);
	}

	n_fields = dict_index_get_n_fields(index);
	
	for (pos = 0; pos < n_fields; pos++) {
		field = dict_index_get_nth_field(index, pos);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
516
		if (col == field->col && field->prefix_len == 0) {
517 518 519 520 521 522 523

			return(pos);
		}
	}

	return(ULINT_UNDEFINED);
}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
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
/************************************************************************
Returns TRUE if the index contains a column or a prefix of that column. */

ibool
dict_index_contains_col_or_prefix(
/*==============================*/
				/* out: TRUE if contains the column or its
				prefix */
	dict_index_t*	index,	/* in: index */
	ulint		n)	/* in: column number */
{
	dict_field_t*	field;
	dict_col_t*	col;
	ulint		pos;
	ulint		n_fields;
	
	ut_ad(index);
	ut_ad(index->magic_n == DICT_INDEX_MAGIC_N);

	if (index->type & DICT_CLUSTERED) {

		return(TRUE);
	}

	col = dict_table_get_nth_col(index->table, n);

	n_fields = dict_index_get_n_fields(index);
	
	for (pos = 0; pos < n_fields; pos++) {
		field = dict_index_get_nth_field(index, pos);

		if (col == field->col) {

			return(TRUE);
		}
	}

	return(FALSE);
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
565
/************************************************************************
566 567 568 569
Looks for a matching field in an index. The column has to be the same. The
column in index must be complete, or must contain a prefix longer than the
column in index2. That is, we must be able to construct the prefix in index2
from the prefix in index. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584

ulint
dict_index_get_nth_field_pos(
/*=========================*/
				/* out: position in internal representation
				of the index; if not contained, returns
				ULINT_UNDEFINED */
	dict_index_t*	index,	/* in: index from which to search */
	dict_index_t*	index2,	/* in: index */
	ulint		n)	/* in: field number in index2 */
{
	dict_field_t*	field;
	dict_field_t*	field2;
	ulint		n_fields;
	ulint		pos;
585
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
586 587 588 589 590 591 592 593 594 595 596
	ut_ad(index);
	ut_ad(index->magic_n == DICT_INDEX_MAGIC_N);

	field2 = dict_index_get_nth_field(index2, n);

	n_fields = dict_index_get_n_fields(index);
	
	for (pos = 0; pos < n_fields; pos++) {
		field = dict_index_get_nth_field(index, pos);

		if (field->col == field2->col
597 598 599
		    && (field->prefix_len == 0
			|| (field->prefix_len >= field2->prefix_len
			    && field2->prefix_len != 0))) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
600 601 602 603 604 605 606 607

			return(pos);
		}
	}

	return(ULINT_UNDEFINED);
}

608 609 610 611 612 613 614 615 616 617 618 619
/**************************************************************************
Returns a table object, based on table id, and memoryfixes it. */

dict_table_t*
dict_table_get_on_id(
/*=================*/
				/* out: table, NULL if does not exist */
	dulint	table_id,	/* in: table id */
	trx_t*	trx)		/* in: transaction handle */
{
	dict_table_t*	table;
	
620
	if (ut_dulint_cmp(table_id, DICT_FIELDS_ID) <= 0
621
	   || trx->dict_operation_lock_mode == RW_X_LATCH) {
622 623 624 625 626
		/* It is a system table which will always exist in the table
		cache: we avoid acquiring the dictionary mutex, because
		if we are doing a rollback to handle an error in TABLE
		CREATE, for example, we already have the mutex! */

627
#ifdef UNIV_SYNC_DEBUG
628
		ut_ad(mutex_own(&(dict_sys->mutex)));
629
#endif /* UNIV_SYNC_DEBUG */
630 631 632 633 634 635 636 637 638 639 640 641 642 643

		return(dict_table_get_on_id_low(table_id, trx));
	}

	mutex_enter(&(dict_sys->mutex));

	table = dict_table_get_on_id_low(table_id, trx);
	
	mutex_exit(&(dict_sys->mutex));

	return(table);
}

/************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
644
Looks for column n position in the clustered index. */
645 646 647 648 649 650 651 652 653 654 655 656 657

ulint
dict_table_get_nth_col_pos(
/*=======================*/
				/* out: position in internal representation
				of the clustered index */
	dict_table_t*	table,	/* in: table */
	ulint		n)	/* in: column number */
{
	return(dict_index_get_nth_col_pos(dict_table_get_first_index(table),
								n));
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
658 659 660 661 662 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
/************************************************************************
Checks if a column is in the ordering columns of the clustered index of a
table. Column prefixes are treated like whole columns. */

ibool
dict_table_col_in_clustered_key(
/*============================*/
				/* out: TRUE if the column, or its prefix, is
				in the clustered key */
	dict_table_t*	table,	/* in: table */
	ulint		n)	/* in: column number */
{
	dict_index_t*	index;
	dict_field_t*	field;
	dict_col_t*	col;
	ulint		pos;
	ulint		n_fields;
	
	ut_ad(table);

	col = dict_table_get_nth_col(table, n);

	index = dict_table_get_first_index(table);

	n_fields = dict_index_get_n_unique(index);
	
	for (pos = 0; pos < n_fields; pos++) {
		field = dict_index_get_nth_field(index, pos);

		if (col == field->col) {

			return(TRUE);
		}
	}

	return(FALSE);
}

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
/**************************************************************************
Inits the data dictionary module. */

void
dict_init(void)
/*===========*/
{
	dict_sys = mem_alloc(sizeof(dict_sys_t));

	mutex_create(&(dict_sys->mutex));
	mutex_set_level(&(dict_sys->mutex), SYNC_DICT);

	dict_sys->table_hash = hash_create(buf_pool_get_max_size() /
					(DICT_POOL_PER_TABLE_HASH *
					UNIV_WORD_SIZE));
	dict_sys->table_id_hash = hash_create(buf_pool_get_max_size() /
					(DICT_POOL_PER_TABLE_HASH *
					UNIV_WORD_SIZE));
	dict_sys->col_hash = hash_create(buf_pool_get_max_size() /
					(DICT_POOL_PER_COL_HASH *
					UNIV_WORD_SIZE));
	dict_sys->size = 0;

	UT_LIST_INIT(dict_sys->table_LRU);
720

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
721 722
	rw_lock_create(&dict_operation_lock);
	rw_lock_set_level(&dict_operation_lock, SYNC_DICT_OPERATION);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
723

724
	dict_foreign_err_file = os_file_create_tmpfile();
725
	ut_a(dict_foreign_err_file);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
726 727
	mutex_create(&dict_foreign_err_mutex);
	mutex_set_level(&dict_foreign_err_mutex, SYNC_ANY_LATCH);
728 729 730 731 732 733 734 735 736 737
}

/**************************************************************************
Returns a table object and memoryfixes it. NOTE! This is a high-level
function to be used mainly from outside the 'dict' directory. Inside this
directory dict_table_get_low is usually the appropriate function. */

dict_table_t*
dict_table_get(
/*===========*/
738 739 740 741
					/* out: table, NULL if
					does not exist */
	const char*	table_name,	/* in: table name */
	trx_t*		trx)		/* in: transaction handle or NULL */
742 743 744 745 746 747 748 749 750 751 752 753
{
	dict_table_t*	table;

	UT_NOT_USED(trx);

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

	mutex_exit(&(dict_sys->mutex));

	if (table != NULL) {
754
	        if (!table->stat_initialized) {
755 756 757 758 759 760 761 762
			dict_update_statistics(table);
		}
	}
	
	return(table);
}

/**************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
763
Returns a table object and increments MySQL open handle count on the table. */
764 765 766 767

dict_table_t*
dict_table_get_and_increment_handle_count(
/*======================================*/
768 769 770 771
					/* out: table, NULL if
					does not exist */
	const char*	table_name,	/* in: table name */
	trx_t*		trx)		/* in: transaction handle or NULL */
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
{
	dict_table_t*	table;

	UT_NOT_USED(trx);

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

	if (table != NULL) {

	        table->n_mysql_handles_opened++;
	}

	mutex_exit(&(dict_sys->mutex));

	if (table != NULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
789
	        if (!table->stat_initialized && !table->ibd_file_missing) {
790 791 792 793 794 795 796
			dict_update_statistics(table);
		}
	}
	
	return(table);
}

797 798 799 800 801 802 803 804 805 806 807 808 809
/**************************************************************************
Adds a table object to the dictionary cache. */

void
dict_table_add_to_cache(
/*====================*/
	dict_table_t*	table)	/* in: table */
{
	ulint	fold;
	ulint	id_fold;
	ulint	i;
	
	ut_ad(table);
810
#ifdef UNIV_SYNC_DEBUG
811
	ut_ad(mutex_own(&(dict_sys->mutex)));
812
#endif /* UNIV_SYNC_DEBUG */
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
	ut_ad(table->n_def == table->n_cols - DATA_N_SYS_COLS);
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);
	ut_ad(table->cached == FALSE);
	
	fold = ut_fold_string(table->name);
	id_fold = ut_fold_dulint(table->id);
	
	table->cached = TRUE;
	
	/* NOTE: the system columns MUST be added in the following order
	(so that they can be indexed by the numerical value of DATA_ROW_ID,
	etc.) and as the last columns of the table memory object.
	The clustered index will not always physically contain all
	system columns. */

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
828
	dict_mem_table_add_col(table, "DB_ROW_ID", DATA_SYS,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
829
			DATA_ROW_ID | DATA_NOT_NULL, DATA_ROW_ID_LEN, 0);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
830 831 832 833
#if DATA_ROW_ID != 0
#error "DATA_ROW_ID != 0"
#endif
	dict_mem_table_add_col(table, "DB_TRX_ID", DATA_SYS,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
834
			DATA_TRX_ID | DATA_NOT_NULL, DATA_TRX_ID_LEN, 0);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
835 836 837 838
#if DATA_TRX_ID != 1
#error "DATA_TRX_ID != 1"
#endif
	dict_mem_table_add_col(table, "DB_ROLL_PTR", DATA_SYS,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
839
			DATA_ROLL_PTR | DATA_NOT_NULL, DATA_ROLL_PTR_LEN, 0);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
840 841 842 843
#if DATA_ROLL_PTR != 2
#error "DATA_ROLL_PTR != 2"
#endif
	dict_mem_table_add_col(table, "DB_MIX_ID", DATA_SYS,
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
844
			DATA_MIX_ID | DATA_NOT_NULL, DATA_MIX_ID_LEN, 0);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
845 846 847 848 849 850 851 852 853
#if DATA_MIX_ID != 3
#error "DATA_MIX_ID != 3"
#endif

	/* This check reminds that if a new system column is added to
	the program, it should be dealt with here */ 
#if DATA_N_SYS_COLS != 4
#error "DATA_N_SYS_COLS != 4"
#endif
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883

	/* Look for a table with the same name: error if such exists */
	{
		dict_table_t*	table2;
		HASH_SEARCH(name_hash, dict_sys->table_hash, fold, table2,
				(ut_strcmp(table2->name, table->name) == 0));
		ut_a(table2 == NULL);
	}

	/* Look for a table with the same id: error if such exists */
	{
		dict_table_t*	table2;
		HASH_SEARCH(id_hash, dict_sys->table_id_hash, id_fold, table2,
				(ut_dulint_cmp(table2->id, table->id) == 0));
		ut_a(table2 == NULL);
	}

	if (table->type == DICT_TABLE_CLUSTER_MEMBER) {

		table->mix_id_len = mach_dulint_get_compressed_size(
								table->mix_id);
		mach_dulint_write_compressed(table->mix_id_buf, table->mix_id);
	}

	/* Add the columns to the column hash table */
	for (i = 0; i < table->n_cols; i++) {
		dict_col_add_to_cache(table, dict_table_get_nth_col(table, i));
	}

	/* Add table to hash table of tables */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
884 885
	HASH_INSERT(dict_table_t, name_hash, dict_sys->table_hash, fold,
								   table);
886 887 888

	/* Add table to hash table of tables based on table id */
	HASH_INSERT(dict_table_t, id_hash, dict_sys->table_id_hash, id_fold,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
889
								   table);
890 891 892 893 894 895 896 897 898
	/* Add table to LRU list of tables */
	UT_LIST_ADD_FIRST(table_LRU, dict_sys->table_LRU, table);

	/* If the dictionary cache grows too big, trim the table LRU list */

	dict_sys->size += mem_heap_get_size(table->heap);
	/* dict_table_LRU_trim(); */
}

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
/**************************************************************************
Looks for an index with the given id. NOTE that we do not reserve
the dictionary mutex: this function is for emergency purposes like
printing info of a corrupt database page! */

dict_index_t*
dict_index_find_on_id_low(
/*======================*/
			/* out: index or NULL if not found from cache */
	dulint	id)	/* in: index id */
{
	dict_table_t*	table;
	dict_index_t*	index;
	
	table = UT_LIST_GET_FIRST(dict_sys->table_LRU);

	while (table) {
		index = dict_table_get_first_index(table);

		while (index) {
			if (0 == ut_dulint_cmp(id, index->tree->id)) {
				/* Found */

				return(index);
			}

			index = dict_table_get_next_index(index);
		}

		table = UT_LIST_GET_NEXT(table_LRU, table);
	}

	return(NULL);
}

934 935 936 937 938 939 940 941
/**************************************************************************
Renames a table object. */

ibool
dict_table_rename_in_cache(
/*=======================*/
					/* out: TRUE if success */
	dict_table_t*	table,		/* in: table */
942
	const char*	new_name,	/* in: new name */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
943 944 945
	ibool		rename_also_foreigns)/* in: in ALTER TABLE we want
					to preserve the original table name
					in constraints which reference it */
946
{
947 948 949 950
	dict_foreign_t*	foreign;
	dict_index_t*	index;
	ulint		fold;
	ulint		old_size;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
951
	char*		old_name;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
952
	ibool		success;
953
	ulint		i;
954 955
	
	ut_ad(table);
956
#ifdef UNIV_SYNC_DEBUG
957
	ut_ad(mutex_own(&(dict_sys->mutex)));
958 959
#endif /* UNIV_SYNC_DEBUG */

960 961 962 963 964 965 966 967 968 969
	old_size = mem_heap_get_size(table->heap);
	
	fold = ut_fold_string(new_name);
	
	/* Look for a table with the same name: error if such exists */
	{
		dict_table_t*	table2;
		HASH_SEARCH(name_hash, dict_sys->table_hash, fold, table2,
				(ut_strcmp(table2->name, new_name) == 0));
		if (table2) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
970 971 972 973 974 975 976 977 978 979 980
			fprintf(stderr,
"InnoDB: Error: dictionary cache already contains a table of name %s\n",
	 							     new_name);
			return(FALSE);
		}
	}

	/* If the table is stored in a single-table tablespace, rename the
	.ibd file */

	if (table->space != 0) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
981 982 983 984 985 986 987 988 989 990
		if (table->dir_path_of_temp_table != NULL) {
			fprintf(stderr,
"InnoDB: Error: trying to rename a table %s (%s) created with CREATE\n"
"InnoDB: TEMPORARY TABLE\n", table->name, table->dir_path_of_temp_table);
			success = FALSE;
		} else {
			success = fil_rename_tablespace(table->name,
						table->space, new_name);
		}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
991 992
		if (!success) {

993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
			return(FALSE);
		}
	}

	/* Reposition the columns in the column hash table; they are hashed
	according to the pair (table name, column name) */

	for (i = 0; i < table->n_cols; i++) {
		dict_col_reposition_in_cache(table,
				dict_table_get_nth_col(table, i), new_name);
	}

	/* Remove table from the hash tables of tables */
	HASH_DELETE(dict_table_t, name_hash, dict_sys->table_hash,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1007
					ut_fold_string(table->name), table);
1008 1009
	old_name = mem_heap_strdup(table->heap, table->name);
	table->name = mem_heap_strdup(table->heap, new_name);
1010 1011

	/* Add table to hash table of tables */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1012 1013
	HASH_INSERT(dict_table_t, name_hash, dict_sys->table_hash, fold,
								   table);
1014 1015
	dict_sys->size += (mem_heap_get_size(table->heap) - old_size);

1016 1017 1018 1019 1020 1021 1022 1023 1024
	/* Update the table_name field in indexes */
	index = dict_table_get_first_index(table);

	while (index != NULL) {
		index->table_name = table->name;
		
		index = dict_table_get_next_index(index);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
	if (!rename_also_foreigns) {
		/* In ALTER TABLE we think of the rename table operation
		in the direction table -> temporary table (#sql...)
		as dropping the table with the old name and creating
		a new with the new name. Thus we kind of drop the
		constraints from the dictionary cache here. The foreign key
		constraints will be inherited to the new table from the
		system tables through a call of dict_load_foreigns. */
	
		/* Remove the foreign constraints from the cache */
		foreign = UT_LIST_GET_LAST(table->foreign_list);

		while (foreign != NULL) {
			dict_foreign_remove_from_cache(foreign);
			foreign = UT_LIST_GET_LAST(table->foreign_list);
		}

		/* Reset table field in referencing constraints */

		foreign = UT_LIST_GET_FIRST(table->referenced_list);

		while (foreign != NULL) {
			foreign->referenced_table = NULL;
			foreign->referenced_index = NULL;
		
			foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
		}

		/* Make the list of referencing constraints empty */

		UT_LIST_INIT(table->referenced_list);
		
		return(TRUE);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1060 1061 1062
	/* Update the table name fields in foreign constraints, and update also
	the constraint id of new format >= 4.0.18 constraints. Note that at
	this point we have already changed table->name to the new name. */
1063 1064 1065 1066 1067 1068 1069 1070

	foreign = UT_LIST_GET_FIRST(table->foreign_list);

	while (foreign != NULL) {
		if (ut_strlen(foreign->foreign_table_name) <
						ut_strlen(table->name)) {
			/* Allocate a longer name buffer;
			TODO: store buf len to save memory */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1071

1072 1073 1074 1075 1076
			foreign->foreign_table_name = mem_heap_alloc(
					foreign->heap,
					ut_strlen(table->name) + 1);
		}

1077
		strcpy(foreign->foreign_table_name, table->name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1078

1079
		if (strchr(foreign->id, '/')) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1080
			ulint	db_len;
1081
			char*	old_id;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1082 1083 1084

			/* This is a >= 4.0.18 format id */

1085
			old_id = mem_strdup(foreign->id);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1086 1087

			if (ut_strlen(foreign->id) > ut_strlen(old_name)
1088
						+ ((sizeof dict_ibfk) - 1)
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1089 1090 1091 1092
			    && 0 == ut_memcmp(foreign->id, old_name,
						ut_strlen(old_name))
			    && 0 == ut_memcmp(
					foreign->id + ut_strlen(old_name),
1093
					dict_ibfk, (sizeof dict_ibfk) - 1)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1094 1095 1096

				/* This is a generated >= 4.0.18 format id */

1097
				if (ut_strlen(table->name) > ut_strlen(old_name)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1098 1099 1100 1101 1102 1103 1104 1105
					foreign->id = mem_heap_alloc(
					     foreign->heap,
						ut_strlen(table->name)
						+ ut_strlen(old_id) + 1);
				}
				
				/* Replace the prefix 'databasename/tablename'
				with the new names */
1106 1107
				strcpy(foreign->id, table->name);
				strcat(foreign->id,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
						old_id + ut_strlen(old_name));
			} else {
				/* This is a >= 4.0.18 format id where the user
				gave the id name */
				db_len = dict_get_db_name_len(table->name) + 1;

				if (dict_get_db_name_len(table->name)
			    	    > dict_get_db_name_len(foreign->id)) {

					foreign->id = mem_heap_alloc(
					     foreign->heap,
				 	     db_len + ut_strlen(old_id) + 1);
				}

				/* Replace the database prefix in id with the
				one from table->name */
			
				ut_memcpy(foreign->id, table->name, db_len);

1127
				strcpy(foreign->id + db_len,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1128 1129
						dict_remove_db_name(old_id));
			}
1130 1131

			mem_free(old_id);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1132
		}
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143

		foreign = UT_LIST_GET_NEXT(foreign_list, foreign);
	}

	foreign = UT_LIST_GET_FIRST(table->referenced_list);

	while (foreign != NULL) {
		if (ut_strlen(foreign->referenced_table_name) <
						ut_strlen(table->name)) {
			/* Allocate a longer name buffer;
			TODO: store buf len to save memory */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1144

1145 1146 1147 1148 1149
			foreign->referenced_table_name = mem_heap_alloc(
					foreign->heap,
					ut_strlen(table->name) + 1);
		}

1150
		strcpy(foreign->referenced_table_name, table->name);
1151 1152 1153 1154

		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}

1155 1156 1157
	return(TRUE);
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
/**************************************************************************
Change the id of a table object in the dictionary cache. This is used in
DISCARD TABLESPACE. */

void
dict_table_change_id_in_cache(
/*==========================*/
	dict_table_t*	table,	/* in: table object already in cache */
	dulint		new_id)	/* in: new id to set */
{
	ut_ad(table);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1169
#ifdef UNIV_SYNC_DEBUG
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1170
	ut_ad(mutex_own(&(dict_sys->mutex)));
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1171
#endif /* UNIV_SYNC_DEBUG */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);

	/* Remove the table from the hash table of id's */

	HASH_DELETE(dict_table_t, id_hash, dict_sys->table_id_hash,
					ut_fold_dulint(table->id), table);
	table->id = new_id;

	/* Add the table back to the hash table */
	HASH_INSERT(dict_table_t, id_hash, dict_sys->table_id_hash,
					ut_fold_dulint(table->id), table);
}

1185 1186 1187 1188 1189 1190 1191 1192
/**************************************************************************
Removes a table object from the dictionary cache. */

void
dict_table_remove_from_cache(
/*=========================*/
	dict_table_t*	table)	/* in, own: table */
{
1193
	dict_foreign_t*	foreign;
1194 1195 1196 1197 1198
	dict_index_t*	index;
	ulint		size;
	ulint		i;
	
	ut_ad(table);
1199
#ifdef UNIV_SYNC_DEBUG
1200
	ut_ad(mutex_own(&(dict_sys->mutex)));
1201
#endif /* UNIV_SYNC_DEBUG */
1202 1203
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);

1204 1205 1206 1207 1208
#if 0
	fputs("Removing table ", stderr);
	ut_print_name(stderr, table->name, ULINT_UNDEFINED);
	fputs(" from dictionary cache\n", stderr);
#endif
1209

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
	/* Remove the foreign constraints from the cache */
	foreign = UT_LIST_GET_LAST(table->foreign_list);

	while (foreign != NULL) {
		dict_foreign_remove_from_cache(foreign);
		foreign = UT_LIST_GET_LAST(table->foreign_list);
	}

	/* Reset table field in referencing constraints */

	foreign = UT_LIST_GET_FIRST(table->referenced_list);

	while (foreign != NULL) {
		foreign->referenced_table = NULL;
		foreign->referenced_index = NULL;
		
		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
	/* Remove the indexes from the cache */
	index = UT_LIST_GET_LAST(table->indexes);

	while (index != NULL) {
		dict_index_remove_from_cache(table, index);
		index = UT_LIST_GET_LAST(table->indexes);
	}

	/* Remove the columns of the table from the cache */
	for (i = 0; i < table->n_cols; i++) {
		dict_col_remove_from_cache(table,
					   dict_table_get_nth_col(table, i));
	}

	/* Remove table from the hash tables of tables */
	HASH_DELETE(dict_table_t, name_hash, dict_sys->table_hash,
					ut_fold_string(table->name), table);
	HASH_DELETE(dict_table_t, id_hash, dict_sys->table_id_hash,
					ut_fold_dulint(table->id), table);

	/* Remove table from LRU list of tables */
	UT_LIST_REMOVE(table_LRU, dict_sys->table_LRU, table);

1252 1253
	mutex_free(&(table->autoinc_mutex));

1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
	size = mem_heap_get_size(table->heap);

	ut_ad(dict_sys->size >= size);

	dict_sys->size -= size;

	mem_heap_free(table->heap);
}

/**************************************************************************
Frees tables from the end of table_LRU if the dictionary cache occupies
too much space. Currently not used! */
1266

1267 1268 1269 1270 1271 1272 1273
void
dict_table_LRU_trim(void)
/*=====================*/
{
	dict_table_t*	table;
	dict_table_t*	prev_table;

1274
	ut_error;
1275

1276
#ifdef UNIV_SYNC_DEBUG
1277
	ut_ad(mutex_own(&(dict_sys->mutex)));
1278
#endif /* UNIV_SYNC_DEBUG */
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306

	table = UT_LIST_GET_LAST(dict_sys->table_LRU);

	while (table && (dict_sys->size >
			 buf_pool_get_max_size() / DICT_POOL_PER_VARYING)) {

		prev_table = UT_LIST_GET_PREV(table_LRU, table);

		if (table->mem_fix == 0) {
			dict_table_remove_from_cache(table);
		}

		table = prev_table;
	}
}

/**************************************************************************
Adds a column to the data dictionary hash table. */
static
void
dict_col_add_to_cache(
/*==================*/
	dict_table_t*	table,	/* in: table */
	dict_col_t*	col)	/* in: column */
{
	ulint	fold;

	ut_ad(table && col);
1307
#ifdef UNIV_SYNC_DEBUG
1308
	ut_ad(mutex_own(&(dict_sys->mutex)));
1309
#endif /* UNIV_SYNC_DEBUG */
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);
	
	fold = ut_fold_ulint_pair(ut_fold_string(table->name),
				  ut_fold_string(col->name));

	/* Look for a column with same table name and column name: error */
	{
		dict_col_t*	col2;
		HASH_SEARCH(hash, dict_sys->col_hash, fold, col2,
			(ut_strcmp(col->name, col2->name) == 0)
			&& (ut_strcmp((col2->table)->name, table->name)
							== 0));  
		ut_a(col2 == NULL);
	}

	HASH_INSERT(dict_col_t, hash, dict_sys->col_hash, fold, col);
}

/**************************************************************************
Removes a column from the data dictionary hash table. */
static
void
dict_col_remove_from_cache(
/*=======================*/
	dict_table_t*	table,	/* in: table */
	dict_col_t*	col)	/* in: column */
{
	ulint		fold;

	ut_ad(table && col);
1340
#ifdef UNIV_SYNC_DEBUG
1341
	ut_ad(mutex_own(&(dict_sys->mutex)));
1342
#endif /* UNIV_SYNC_DEBUG */
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);
	
	fold = ut_fold_ulint_pair(ut_fold_string(table->name),
				  ut_fold_string(col->name));

	HASH_DELETE(dict_col_t, hash, dict_sys->col_hash, fold, col);
}

/**************************************************************************
Repositions a column in the data dictionary hash table when the table name
changes. */
static
void
dict_col_reposition_in_cache(
/*=========================*/
	dict_table_t*	table,		/* in: table */
	dict_col_t*	col,		/* in: column */
1360
	const char*	new_name)	/* in: new table name */
1361 1362 1363 1364
{
	ulint		fold;

	ut_ad(table && col);
1365
#ifdef UNIV_SYNC_DEBUG
1366
	ut_ad(mutex_own(&(dict_sys->mutex)));
1367
#endif /* UNIV_SYNC_DEBUG */
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);
	
	fold = ut_fold_ulint_pair(ut_fold_string(table->name),
				  ut_fold_string(col->name));

	HASH_DELETE(dict_col_t, hash, dict_sys->col_hash, fold, col);

	fold = ut_fold_ulint_pair(ut_fold_string(new_name),
				  ut_fold_string(col->name));
				  
	HASH_INSERT(dict_col_t, hash, dict_sys->col_hash, fold, col);
}

/**************************************************************************
Adds an index to the dictionary cache. */

ibool
dict_index_add_to_cache(
/*====================*/
				/* out: TRUE if success */
	dict_table_t*	table,	/* in: table on which the index is */
1389
	dict_index_t*	index,	/* in, own: index; NOTE! The index memory
1390
				object is freed in this function! */
1391
	ulint		page_no)/* in: root page number of the index */
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
{
	dict_index_t*	new_index;
	dict_tree_t*	tree;
	dict_table_t*	cluster;
	dict_field_t*	field;
	ulint		n_ord;
	ibool		success;
	ulint		i;
	
	ut_ad(index);
1402
#ifdef UNIV_SYNC_DEBUG
1403
	ut_ad(mutex_own(&(dict_sys->mutex)));
1404
#endif /* UNIV_SYNC_DEBUG */
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
	ut_ad(index->n_def == index->n_fields);
	ut_ad(index->magic_n == DICT_INDEX_MAGIC_N);
	
	ut_ad(mem_heap_validate(index->heap));

	{
		dict_index_t*	index2;
		index2 = UT_LIST_GET_FIRST(table->indexes);

		while (index2 != NULL) {
			ut_ad(ut_strcmp(index->name, index2->name) != 0);

			index2 = UT_LIST_GET_NEXT(indexes, index2);
		}

		ut_a(UT_LIST_GET_LEN(table->indexes) == 0
	      			|| (index->type & DICT_CLUSTERED) == 0);
	}

	success = dict_index_find_cols(table, index);

	if (!success) {
		dict_mem_index_free(index);

		return(FALSE);
	}
1431
	
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
	/* Build the cache internal representation of the index,
	containing also the added system fields */

	if (index->type & DICT_CLUSTERED) {
		new_index = dict_index_build_internal_clust(table, index);
	} else {
		new_index = dict_index_build_internal_non_clust(table, index);
	}

	new_index->search_info = btr_search_info_create(new_index->heap);
	
	/* Set the n_fields value in new_index to the actual defined
	number of fields in the cache internal representation */

	new_index->n_fields = new_index->n_def;
	
	/* Add the new index as the last index for the table */

	UT_LIST_ADD_LAST(indexes, table->indexes, new_index);	
	new_index->table = table;
	new_index->table_name = table->name;

	/* Increment the ord_part counts in columns which are ordering */

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1456
	if (UNIV_UNLIKELY(index->type & DICT_UNIVERSAL)) {
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
		n_ord = new_index->n_fields;
	} else {
		n_ord = dict_index_get_n_unique(new_index);
	}

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

		field = dict_index_get_nth_field(new_index, i);

		dict_field_get_col(field)->ord_part++;
	}

	if (table->type == DICT_TABLE_CLUSTER_MEMBER) {
		/* The index tree is found from the cluster object */
	    
		cluster = dict_table_get_low(table->cluster_name);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1474 1475
		tree = dict_index_get_tree(
					UT_LIST_GET_FIRST(cluster->indexes));
1476 1477 1478
		new_index->tree = tree;
	} else {
		/* Create an index tree memory object for the index */
1479
		tree = dict_tree_create(new_index, page_no);
1480 1481 1482 1483 1484
		ut_ad(tree);

		new_index->tree = tree;
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1485
	if (!UNIV_UNLIKELY(new_index->type & DICT_UNIVERSAL)) {
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499

		new_index->stat_n_diff_key_vals =
			mem_heap_alloc(new_index->heap,
				(1 + dict_index_get_n_unique(new_index))
				* sizeof(ib_longlong));
		/* Give some sensible values to stat_n_... in case we do
		not calculate statistics quickly enough */

		for (i = 0; i <= dict_index_get_n_unique(new_index); i++) {

			new_index->stat_n_diff_key_vals[i] = 100;
		}
	}
	
1500 1501 1502 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 1528
	/* Add the index to the list of indexes stored in the tree */
	UT_LIST_ADD_LAST(tree_indexes, tree->tree_indexes, new_index); 
	
	/* If the dictionary cache grows too big, trim the table LRU list */

	dict_sys->size += mem_heap_get_size(new_index->heap);
	/* dict_table_LRU_trim(); */

	dict_mem_index_free(index);

	return(TRUE);
}

/**************************************************************************
Removes an index from the dictionary cache. */
static
void
dict_index_remove_from_cache(
/*=========================*/
	dict_table_t*	table,	/* in: table */
	dict_index_t*	index)	/* in, own: index */
{
	dict_field_t*	field;
	ulint		size;
	ulint		i;

	ut_ad(table && index);
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);
	ut_ad(index->magic_n == DICT_INDEX_MAGIC_N);
1529
#ifdef UNIV_SYNC_DEBUG
1530
	ut_ad(mutex_own(&(dict_sys->mutex)));
1531
#endif /* UNIV_SYNC_DEBUG */
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574

	ut_ad(UT_LIST_GET_LEN((index->tree)->tree_indexes) == 1);
	dict_tree_free(index->tree);

	/* Decrement the ord_part counts in columns which are ordering */
	for (i = 0; i < dict_index_get_n_unique(index); i++) {

		field = dict_index_get_nth_field(index, i);

		ut_ad(dict_field_get_col(field)->ord_part > 0);
		(dict_field_get_col(field)->ord_part)--;
	}

	/* Remove the index from the list of indexes of the table */
	UT_LIST_REMOVE(indexes, table->indexes, index);

	size = mem_heap_get_size(index->heap);

	ut_ad(dict_sys->size >= size);

	dict_sys->size -= size;

	mem_heap_free(index->heap);
}

/***********************************************************************
Tries to find column names for the index in the column hash table and
sets the col field of the index. */
static
ibool
dict_index_find_cols(
/*=================*/
				/* out: TRUE if success */
	dict_table_t*	table,	/* in: table */
	dict_index_t*	index)	/* in: index */	
{
	dict_col_t*	col;
	dict_field_t*	field;
	ulint		fold;
	ulint		i;
	
	ut_ad(table && index);
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);
1575
#ifdef UNIV_SYNC_DEBUG
1576
	ut_ad(mutex_own(&(dict_sys->mutex)));
1577
#endif /* UNIV_SYNC_DEBUG */
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601

	for (i = 0; i < index->n_fields; i++) {
		field = dict_index_get_nth_field(index, i);

		fold = ut_fold_ulint_pair(ut_fold_string(table->name),
				  	       ut_fold_string(field->name));
			
		HASH_SEARCH(hash, dict_sys->col_hash, fold, col,
				(ut_strcmp(col->name, field->name) == 0)
				&& (ut_strcmp((col->table)->name, table->name)
								== 0));  
		if (col == NULL) {

 			return(FALSE);
		} else {
			field->col = col;
		}
	}

	return(TRUE);
}
	
/***********************************************************************
Adds a column to index. */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1602

1603 1604 1605
void
dict_index_add_col(
/*===============*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1606 1607 1608 1609
	dict_index_t*	index,		/* in: index */
	dict_col_t*	col,		/* in: column */
	ulint		order,		/* in: order criterion */
	ulint		prefix_len)	/* in: column prefix length */
1610 1611 1612
{
	dict_field_t*	field;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1613
	dict_mem_index_add_field(index, col->name, order, prefix_len);
1614 1615 1616 1617

	field = dict_index_get_nth_field(index, index->n_def - 1);

	field->col = col;
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
	field->fixed_len = dtype_get_fixed_size(&col->type);

	if (prefix_len && field->fixed_len > prefix_len) {
		field->fixed_len = prefix_len;
	}

	/* Long fixed-length fields that need external storage are treated as
	variable-length fields, so that the extern flag can be embedded in
	the length word. */

1628
	if (field->fixed_len > DICT_MAX_INDEX_COL_LEN) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
		field->fixed_len = 0;
	}

	if (!(dtype_get_prtype(&col->type) & DATA_NOT_NULL)) {
		index->n_nullable++;
	}

	if (index->n_def > 1) {
		const dict_field_t*	field2 =
			dict_index_get_nth_field(index, index->n_def - 2);
		field->fixed_offs = (!field2->fixed_len ||
					field2->fixed_offs == ULINT_UNDEFINED)
				? ULINT_UNDEFINED
				: field2->fixed_len + field2->fixed_offs;
	} else {
		field->fixed_offs = 0;
	}
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
}

/***********************************************************************
Copies fields contained in index2 to index1. */
static
void
dict_index_copy(
/*============*/
	dict_index_t*	index1,	/* in: index to copy to */
	dict_index_t*	index2,	/* in: index to copy from */
	ulint		start,	/* in: first position to copy */
	ulint		end)	/* in: last position to copy */
{
	dict_field_t*	field;
	ulint		i;
	
	/* Copy fields contained in index2 */

	for (i = start; i < end; i++) {

		field = dict_index_get_nth_field(index2, i);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1667 1668
		dict_index_add_col(index1, field->col, field->order,
						      field->prefix_len);
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
	}
}

/***********************************************************************
Copies types of fields contained in index to tuple. */

void
dict_index_copy_types(
/*==================*/
	dtuple_t*	tuple,		/* in: data tuple */
	dict_index_t*	index,		/* in: index */
	ulint		n_fields)	/* in: number of field types to copy */
{
	dtype_t*	dfield_type;
	dtype_t*	type;
	ulint		i;

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1686
	if (UNIV_UNLIKELY(index->type & DICT_UNIVERSAL)) {
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 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
		dtuple_set_types_binary(tuple, n_fields);

		return;
	}

	for (i = 0; i < n_fields; i++) {
		dfield_type = dfield_get_type(dtuple_get_nth_field(tuple, i));
		type = dict_col_get_type(dict_field_get_col(
				dict_index_get_nth_field(index, i)));
		*dfield_type = *type;
	}
}

/***********************************************************************
Copies types of columns contained in table to tuple. */

void
dict_table_copy_types(
/*==================*/
	dtuple_t*	tuple,	/* in: data tuple */
	dict_table_t*	table)	/* in: index */
{
	dtype_t*	dfield_type;
	dtype_t*	type;
	ulint		i;

	ut_ad(!(table->type & DICT_UNIVERSAL));

	for (i = 0; i < dtuple_get_n_fields(tuple); i++) {

		dfield_type = dfield_get_type(dtuple_get_nth_field(tuple, i));
		type = dict_col_get_type(dict_table_get_nth_col(table, i));

		*dfield_type = *type;
	}
}

/***********************************************************************
Builds the internal dictionary cache representation for a clustered
index, containing also system fields not defined by the user. */
static
dict_index_t*
dict_index_build_internal_clust(
/*============================*/
				/* out, own: the internal representation
				of the clustered index */
	dict_table_t*	table,	/* in: table */
	dict_index_t*	index)	/* in: user representation of a clustered
				index */	
{
	dict_index_t*	new_index;
	dict_field_t*	field;
	dict_col_t*	col;
	ulint		fixed_size;
	ulint		trx_id_pos;
	ulint		i;

	ut_ad(table && index);
	ut_ad(index->type & DICT_CLUSTERED);
1746
#ifdef UNIV_SYNC_DEBUG
1747
	ut_ad(mutex_own(&(dict_sys->mutex)));
1748
#endif /* UNIV_SYNC_DEBUG */
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);

	/* Create a new index object with certainly enough fields */
	new_index = dict_mem_index_create(table->name,
				     index->name,
				     table->space,
				     index->type,
				     index->n_fields + table->n_cols);

	/* Copy other relevant data from the old index struct to the new
	struct: it inherits the values */

	new_index->n_user_defined_cols = index->n_fields;
	
	new_index->id = index->id;

	if (table->type != DICT_TABLE_ORDINARY) {
		/* The index is mixed: copy common key prefix fields */
		
		dict_index_copy(new_index, index, 0, table->mix_len);

		/* Add the mix id column */
		dict_index_add_col(new_index,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1772
			  dict_table_get_sys_col(table, DATA_MIX_ID), 0, 0);
1773 1774 1775 1776 1777 1778 1779 1780 1781

		/* Copy the rest of fields */
		dict_index_copy(new_index, index, table->mix_len,
							index->n_fields);
	} else {
		/* Copy the fields of index */
		dict_index_copy(new_index, index, 0, index->n_fields);
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1782
	if (UNIV_UNLIKELY(index->type & DICT_UNIVERSAL)) {
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
		/* No fixed number of fields determines an entry uniquely */

		new_index->n_uniq = ULINT_MAX;
		
	} else if (index->type & DICT_UNIQUE) {
		/* Only the fields defined so far are needed to identify
		the index entry uniquely */

		new_index->n_uniq = new_index->n_def;
	} else {
		/* Also the row id is needed to identify the entry */
		new_index->n_uniq = 1 + new_index->n_def;
	}

	new_index->trx_id_offset = 0;

	if (!(index->type & DICT_IBUF)) {
		/* Add system columns, trx id first */

		trx_id_pos = new_index->n_def;

		ut_ad(DATA_ROW_ID == 0);
		ut_ad(DATA_TRX_ID == 1);
		ut_ad(DATA_ROLL_PTR == 2);

		if (!(index->type & DICT_UNIQUE)) {
			dict_index_add_col(new_index,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1810
			   dict_table_get_sys_col(table, DATA_ROW_ID), 0, 0);
1811 1812 1813 1814
			trx_id_pos++;
		}

		dict_index_add_col(new_index,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1815 1816
			   dict_table_get_sys_col(table, DATA_TRX_ID), 0, 0);
	
1817
		dict_index_add_col(new_index,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1818
			   dict_table_get_sys_col(table, DATA_ROLL_PTR), 0, 0);
1819 1820 1821 1822 1823 1824 1825

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

			fixed_size = dtype_get_fixed_size(
				dict_index_get_nth_type(new_index, i));

			if (fixed_size == 0) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1826 1827 1828 1829 1830 1831 1832
				new_index->trx_id_offset = 0;

				break;
			}

			if (dict_index_get_nth_field(new_index, i)->prefix_len
			    > 0) {
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
				new_index->trx_id_offset = 0;

				break;
			}

			new_index->trx_id_offset += fixed_size;
		}

	}

	/* Set auxiliary variables in table columns as undefined */
	for (i = 0; i < table->n_cols; i++) {

		col = dict_table_get_nth_col(table, i);
		col->aux = ULINT_UNDEFINED;
	}

	/* Mark with 0 the table columns already contained in new_index */
	for (i = 0; i < new_index->n_def; i++) {

		field = dict_index_get_nth_field(new_index, i);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1854 1855 1856 1857 1858 1859 1860 1861

		/* If there is only a prefix of the column in the index
		field, do not mark the column as contained in the index */

		if (field->prefix_len == 0) {

		        field->col->aux = 0;
		}
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
	}
	
	/* Add to new_index non-system columns of table not yet included
	there */
	for (i = 0; i < table->n_cols - DATA_N_SYS_COLS; i++) {

		col = dict_table_get_nth_col(table, i);
		ut_ad(col->type.mtype != DATA_SYS);

		if (col->aux == ULINT_UNDEFINED) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1872
			dict_index_add_col(new_index, col, 0, 0);
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
		}
	}

	ut_ad((index->type & DICT_IBUF)
				|| (UT_LIST_GET_LEN(table->indexes) == 0));

	/* Store to the column structs the position of the table columns
	in the clustered index */

	for (i = 0; i < new_index->n_def; i++) {
		field = dict_index_get_nth_field(new_index, i);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1884 1885 1886 1887 1888

		if (field->prefix_len == 0) {

		        field->col->clust_pos = i;
		}
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
	}
	
	new_index->cached = TRUE;

	return(new_index);
}	

/***********************************************************************
Builds the internal dictionary cache representation for a non-clustered
index, containing also system fields not defined by the user. */
static
dict_index_t*
dict_index_build_internal_non_clust(
/*================================*/
				/* out, own: the internal representation
				of the non-clustered index */
	dict_table_t*	table,	/* in: table */
	dict_index_t*	index)	/* in: user representation of a non-clustered
				index */	
{
	dict_field_t*	field;
	dict_index_t*	new_index;
	dict_index_t*	clust_index;
	ulint		i;

	ut_ad(table && index);
	ut_ad(0 == (index->type & DICT_CLUSTERED));
1916
#ifdef UNIV_SYNC_DEBUG
1917
	ut_ad(mutex_own(&(dict_sys->mutex)));
1918
#endif /* UNIV_SYNC_DEBUG */
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);

	/* The clustered index should be the first in the list of indexes */
	clust_index = UT_LIST_GET_FIRST(table->indexes);
	
	ut_ad(clust_index);
	ut_ad(clust_index->type & DICT_CLUSTERED);
	ut_ad(!(clust_index->type & DICT_UNIVERSAL));

	/* Create a new index */
	new_index = dict_mem_index_create(table->name,
				     index->name,
				     index->space,
				     index->type,
				     index->n_fields
				     + 1 + clust_index->n_uniq);

	/* Copy other relevant data from the old index
	struct to the new struct: it inherits the values */

	new_index->n_user_defined_cols = index->n_fields;
	
	new_index->id = index->id;

	/* Copy fields from index to new_index */
	dict_index_copy(new_index, index, 0, index->n_fields);

	/* Set the auxiliary variables in the clust_index unique columns
	as undefined */
	for (i = 0; i < clust_index->n_uniq; i++) {

		field = dict_index_get_nth_field(clust_index, i);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1951
		field->col->aux = ULINT_UNDEFINED;
1952 1953 1954 1955 1956 1957
	}

	/* Mark with 0 table columns already contained in new_index */
	for (i = 0; i < new_index->n_def; i++) {

		field = dict_index_get_nth_field(new_index, i);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1958 1959 1960 1961 1962 1963 1964 1965

		/* If there is only a prefix of the column in the index
		field, do not mark the column as contained in the index */

		if (field->prefix_len == 0) {

		        field->col->aux = 0;
		}
1966 1967
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1968
	/* Add to new_index the columns necessary to determine the clustered
1969 1970 1971 1972 1973 1974
	index entry uniquely */

	for (i = 0; i < clust_index->n_uniq; i++) {

		field = dict_index_get_nth_field(clust_index, i);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1975 1976 1977
		if (field->col->aux == ULINT_UNDEFINED) {
			dict_index_add_col(new_index, field->col, 0,
						      field->prefix_len);
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
		}
	}

	if ((index->type) & DICT_UNIQUE) {
		new_index->n_uniq = index->n_fields;
	} else {
		new_index->n_uniq = new_index->n_def;
	}

	/* Set the n_fields value in new_index to the actual defined
	number of fields */

	new_index->n_fields = new_index->n_def;

	new_index->cached = TRUE;

	return(new_index);
}	

1997 1998
/*====================== FOREIGN KEY PROCESSING ========================*/

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
/*************************************************************************
Checks if a table is referenced by foreign keys. */

ibool
dict_table_referenced_by_foreign_key(
/*=================================*/
				/* out: TRUE if table is referenced by a
				foreign key */
	dict_table_t*	table)	/* in: InnoDB table */
{
	if (UT_LIST_GET_LEN(table->referenced_list) > 0) {
		
		return(TRUE);
	}

	return(FALSE);
}

2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
/*************************************************************************
Frees a foreign key struct. */
static
void
dict_foreign_free(
/*==============*/
	dict_foreign_t*	foreign)	/* in, own: foreign key struct */
{
	mem_heap_free(foreign->heap);
}

/**************************************************************************
Removes a foreign constraint struct from the dictionary cache. */
static
void
dict_foreign_remove_from_cache(
/*===========================*/
	dict_foreign_t*	foreign)	/* in, own: foreign constraint */
{
2036
#ifdef UNIV_SYNC_DEBUG
2037
	ut_ad(mutex_own(&(dict_sys->mutex)));
2038
#endif /* UNIV_SYNC_DEBUG */
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
	ut_a(foreign);
	
	if (foreign->referenced_table) {
		UT_LIST_REMOVE(referenced_list,
			foreign->referenced_table->referenced_list, foreign);
	}

	if (foreign->foreign_table) {
		UT_LIST_REMOVE(foreign_list,
			foreign->foreign_table->foreign_list, foreign);
	}

	dict_foreign_free(foreign);
}

/**************************************************************************
Looks for the foreign constraint from the foreign and referenced lists
of a table. */
static
dict_foreign_t*
dict_foreign_find(
/*==============*/
				/* out: foreign constraint */
	dict_table_t*	table,	/* in: table object */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2063
	const char*	id)	/* in: foreign constraint id */
2064 2065 2066
{
	dict_foreign_t*	foreign;

2067
#ifdef UNIV_SYNC_DEBUG
2068
	ut_ad(mutex_own(&(dict_sys->mutex)));
2069
#endif /* UNIV_SYNC_DEBUG */
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104

	foreign = UT_LIST_GET_FIRST(table->foreign_list);

	while (foreign) {
		if (ut_strcmp(id, foreign->id) == 0) {

			return(foreign);
		}

		foreign = UT_LIST_GET_NEXT(foreign_list, foreign);
	}
	
	foreign = UT_LIST_GET_FIRST(table->referenced_list);

	while (foreign) {
		if (ut_strcmp(id, foreign->id) == 0) {

			return(foreign);
		}

		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}

	return(NULL);
}	

/*************************************************************************
Tries to find an index whose first fields are the columns in the array,
in the same order. */
static
dict_index_t*
dict_foreign_find_index(
/*====================*/
				/* out: matching index, NULL if not found */
	dict_table_t*	table,	/* in: table */
2105
	const char**	columns,/* in: array of column names */
2106
	ulint		n_cols,	/* in: number of columns */
2107 2108 2109 2110 2111
	dict_index_t*	types_idx, /* in: NULL or an index to whose types the
				   column types must match */
	ibool		check_charsets)	/* in: whether to check charsets.
					only has an effect if types_idx !=
					NULL. */
2112
{
2113
#ifndef UNIV_HOTBACKUP
2114
	dict_index_t*	index;
2115
	const char*	col_name;
2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
	ulint		i;
	
	index = dict_table_get_first_index(table);

	while (index != NULL) {
		if (dict_index_get_n_fields(index) >= n_cols) {

			for (i = 0; i < n_cols; i++) {
				col_name = dict_index_get_nth_field(index, i)
							->col->name;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2126 2127 2128 2129 2130 2131 2132 2133
				if (dict_index_get_nth_field(index, i)
						->prefix_len != 0) {
					/* We do not accept column prefix
					indexes here */
					
					break;
				}

2134
				if (0 != innobase_strcasecmp(columns[i],
2135
								col_name)) {
2136 2137 2138 2139 2140
				  	break;
				}

				if (types_idx && !cmp_types_are_equal(
				     dict_index_get_nth_type(index, i),
2141 2142
				     dict_index_get_nth_type(types_idx, i),
				     check_charsets)) {
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158

				  	break;
				}		
			}

			if (i == n_cols) {
				/* We found a matching index */

				return(index);
			}
		}

		index = dict_table_get_next_index(index);
	}

	return(NULL);
2159 2160 2161 2162 2163 2164
#else /* UNIV_HOTBACKUP */
	/* This function depends on MySQL code that is not included in
	InnoDB Hot Backup builds.  Besides, this function should never
	be called in InnoDB Hot Backup. */
	ut_error;
#endif /* UNIV_HOTBACKUP */
2165 2166
}

2167 2168 2169 2170 2171
/**************************************************************************
Report an error in a foreign key definition. */
static
void
dict_foreign_error_report_low(
2172
/*==========================*/
2173 2174 2175 2176 2177
	FILE*		file,	/* in: output stream */
	const char*	name)	/* in: table name */
{
	rewind(file);
	ut_print_timestamp(file);
2178 2179
	fprintf(file, " Error in foreign key constraint of table %s:\n",
		name);
2180 2181 2182 2183 2184 2185 2186
}

/**************************************************************************
Report an error in a foreign key definition. */
static
void
dict_foreign_error_report(
2187
/*======================*/
2188 2189 2190 2191 2192 2193 2194 2195
	FILE*		file,	/* in: output stream */
	dict_foreign_t*	fk,	/* in: foreign key constraint */
	const char*	msg)	/* in: the error message */
{
	mutex_enter(&dict_foreign_err_mutex);
	dict_foreign_error_report_low(file, fk->foreign_table_name);
	fputs(msg, file);
	fputs(" Constraint:\n", file);
2196
	dict_print_info_on_foreign_key_in_create_format(file, NULL, fk, TRUE);
2197 2198
	if (fk->foreign_index) {
		fputs("\nThe index in the foreign key in table is ", file);
2199
		ut_print_name(file, NULL, fk->foreign_index->name);
2200
		fputs(
2201 2202
"\nSee http://dev.mysql.com/doc/mysql/en/InnoDB_foreign_key_constraints.html\n"
"for correct foreign key definition.\n",
2203 2204 2205 2206 2207
		file);
	}
	mutex_exit(&dict_foreign_err_mutex);
}

2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
/**************************************************************************
Adds a foreign key constraint object to the dictionary cache. May free
the object if there already is an object with the same identifier in.
At least one of the foreign table and the referenced table must already
be in the dictionary cache! */

ulint
dict_foreign_add_to_cache(
/*======================*/
					/* out: DB_SUCCESS or error code */
2218
	dict_foreign_t*	foreign,	/* in, own: foreign key constraint */
2219 2220
	ibool		check_charsets)	/* in: TRUE=check charset
					compatibility */
2221 2222 2223
{
	dict_table_t*	for_table;
	dict_table_t*	ref_table;
2224
	dict_foreign_t*	for_in_cache		= NULL;
2225
	dict_index_t*	index;
2226 2227
	ibool		added_to_referenced_list= FALSE;
	FILE*		ef 			= dict_foreign_err_file;
2228

2229
#ifdef UNIV_SYNC_DEBUG
2230
	ut_ad(mutex_own(&(dict_sys->mutex)));
2231
#endif /* UNIV_SYNC_DEBUG */
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256

	for_table = dict_table_check_if_in_cache_low(
					foreign->foreign_table_name);
	
	ref_table = dict_table_check_if_in_cache_low(
					foreign->referenced_table_name);
	ut_a(for_table || ref_table);

	if (for_table) {
		for_in_cache = dict_foreign_find(for_table, foreign->id);
	}

	if (!for_in_cache && ref_table) {
		for_in_cache = dict_foreign_find(ref_table, foreign->id);
	}

	if (for_in_cache) {
		/* Free the foreign object */
		mem_heap_free(foreign->heap);
	} else {
		for_in_cache = foreign;
	}

	if (for_in_cache->referenced_table == NULL && ref_table) {
		index = dict_foreign_find_index(ref_table,
2257 2258
			(const char**) for_in_cache->referenced_col_names,
			for_in_cache->n_fields,
2259
			for_in_cache->foreign_index, check_charsets);
2260 2261

		if (index == NULL) {
2262
			dict_foreign_error_report(ef, for_in_cache,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2263 2264
"there is no index in referenced table which would contain\n"
"the columns as the first columns, or the data types in the\n"
2265 2266
"referenced table do not match to the ones in table.");

2267 2268 2269
			if (for_in_cache == foreign) {
				mem_heap_free(foreign->heap);
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2270

2271 2272 2273 2274 2275 2276 2277 2278
		    	return(DB_CANNOT_ADD_CONSTRAINT);
		}

		for_in_cache->referenced_table = ref_table;
		for_in_cache->referenced_index = index;
		UT_LIST_ADD_LAST(referenced_list,
					ref_table->referenced_list,
					for_in_cache);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2279
		added_to_referenced_list = TRUE;
2280 2281 2282 2283
	}

	if (for_in_cache->foreign_table == NULL && for_table) {
		index = dict_foreign_find_index(for_table,
2284 2285
			(const char**) for_in_cache->foreign_col_names,
			for_in_cache->n_fields,
2286
			for_in_cache->referenced_index, check_charsets);
2287 2288

		if (index == NULL) {
2289
			dict_foreign_error_report(ef, for_in_cache,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2290 2291
"there is no index in the table which would contain\n"
"the columns as the first columns, or the data types in the\n"
2292
"table do not match to the ones in the referenced table.");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2293

2294
			if (for_in_cache == foreign) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2295 2296 2297 2298 2299 2300
				if (added_to_referenced_list) {
					UT_LIST_REMOVE(referenced_list,
						ref_table->referenced_list,
						for_in_cache);
				}
			
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
				mem_heap_free(foreign->heap);
			}

		    	return(DB_CANNOT_ADD_CONSTRAINT);
		}

		for_in_cache->foreign_table = for_table;
		for_in_cache->foreign_index = index;
		UT_LIST_ADD_LAST(foreign_list,
					for_table->foreign_list,
					for_in_cache);
	}

	return(DB_SUCCESS);
}

/*************************************************************************
Scans from pointer onwards. Stops if is at the start of a copy of
2319 2320
'string' where characters are compared without case sensitivity, and
only outside `` or "" quotes. Stops also at '\0'. */
2321

2322
const char*
2323 2324
dict_scan_to(
/*=========*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2325
				/* out: scanned up to this */
2326 2327
	const char*	ptr,	/* in: scan from */
	const char*	string)	/* in: look for this */
2328
{
2329
	char	quote	= '\0';
2330

2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
	for (; *ptr; ptr++) {
		if (*ptr == quote) {
			/* Closing quote character: do not look for
			starting quote or the keyword. */
			quote = '\0';
		} else if (quote) {
			/* Within quotes: do nothing. */
		} else if (*ptr == '`' || *ptr == '"') {
			/* Starting quote: remember the quote character. */
			quote = *ptr;
		} else {
			/* Outside quotes: look for the keyword. */
			ulint	i;
			for (i = 0; string[i]; i++) {
2345 2346 2347
				if (toupper((int)(unsigned char)(ptr[i]))
						!= toupper((int)(unsigned char)
						(string[i]))) {
2348 2349 2350
					goto nomatch;
				}
			}
2351
			break;
2352 2353
		nomatch:
			;
2354 2355 2356
		}
	}

2357
	return(ptr);
2358 2359 2360 2361
}

/*************************************************************************
Accepts a specified string. Comparisons are case-insensitive. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2362

2363
const char*
2364 2365
dict_accept(
/*========*/
2366 2367 2368 2369 2370 2371
				/* out: if string was accepted, the pointer
				is moved after that, else ptr is returned */
	const char*	ptr,	/* in: scan from this */
	const char*	string,	/* in: accept only this string as the next
				non-whitespace string */
	ibool*		success)/* out: TRUE if accepted */
2372
{
2373 2374
	const char*	old_ptr = ptr;
	const char*	old_ptr2;
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395

	*success = FALSE;
	
	while (isspace(*ptr)) {
		ptr++;
	}

	old_ptr2 = ptr;
	
	ptr = dict_scan_to(ptr, string);
	
	if (*ptr == '\0' || old_ptr2 != ptr) {
		return(old_ptr);
	}

	*success = TRUE;

	return(ptr + ut_strlen(string));
}

/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2396 2397
Scans an id. For the lexical definition of an 'id', see the code below.
Strips backquotes or double quotes from around the id. */
2398
static
2399
const char*
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2400 2401
dict_scan_id(
/*=========*/
2402
				/* out: scanned to */
2403 2404 2405 2406 2407
	const char*	ptr,	/* in: scanned to */
	mem_heap_t*	heap,	/* in: heap where to allocate the id
				(NULL=id will not be allocated, but it
				will point to string near ptr) */
	const char**	id,	/* out,own: the id; NULL if no id was
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2408
				scannable */
2409 2410
	ibool		accept_also_dot)
				/* in: TRUE if also a dot can appear in a
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2411 2412
				non-quoted id; in a quoted id it can appear
				always */
2413
{
2414 2415 2416 2417
	char		quote	= '\0';
	ulint		len	= 0;
	const char*	s;
	char*		d;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2418 2419
	ulint		id_len;
	byte*		b;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2420

2421
	*id = NULL;
2422 2423 2424 2425 2426 2427 2428 2429 2430 2431

	while (isspace(*ptr)) {
		ptr++;
	}

	if (*ptr == '\0') {

		return(ptr);
	}

2432
	if (*ptr == '`' || *ptr == '"') {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2433 2434
		quote = *ptr++;
	}
2435 2436

	s = ptr;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2437

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2438
	if (quote) {
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
		for (;;) {
			if (!*ptr) {
				/* Syntax error */
				return(ptr);
			}
			if (*ptr == quote) {
				ptr++;
				if (*ptr != quote) {
					break;
				}
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2450
			ptr++;
2451
			len++;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2452
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2453 2454 2455 2456
	} else {
		while (!isspace(*ptr) && *ptr != '(' && *ptr != ')'
		       && (accept_also_dot || *ptr != '.')
		       && *ptr != ',' && *ptr != '\0') {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2457

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2458
			ptr++;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2459
		}
2460 2461

		len = ptr - s;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2462 2463
	}

2464 2465 2466 2467 2468 2469
	if (quote && heap) {
		*id = d = mem_heap_alloc(heap, len + 1);
		while (len--) {
			if ((*d++ = *s++) == quote) {
				s++;
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2470
		}
2471 2472 2473 2474 2475 2476 2477
		*d++ = 0;
		ut_a(*s == quote);
		ut_a(s + 1 == ptr);
	} else if (heap) {
		*id = mem_heap_strdupl(heap, s, len);
	} else {
		/* no heap given: id will point to source string */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2478
		*id = s;
2479
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2480

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2481
	if (heap && !quote) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491
		/* EMS MySQL Manager sometimes adds characters 0xA0 (in
		latin1, a 'non-breakable space') to the end of a table name.
		But isspace(0xA0) is not true, which confuses our foreign key
		parser. After the UTF-8 conversion in ha_innodb.cc, bytes 0xC2
		and 0xA0 are at the end of the string.

		TODO: we should lex the string using thd->charset_info, and
		my_isspace(). Only after that, convert id names to UTF-8. */

		b = (byte*)(*id);
2492
		id_len = strlen((char*) b);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
		
		if (id_len >= 3 && b[id_len - 1] == 0xA0
			       && b[id_len - 2] == 0xC2) {

			/* Strip the 2 last bytes */

			b[id_len - 2] = '\0';
		}
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2503 2504 2505
	return(ptr);
}

2506 2507 2508
/*************************************************************************
Tries to scan a column name. */
static
2509
const char*
2510 2511 2512
dict_scan_col(
/*==========*/
				/* out: scanned to */
2513
	const char*	ptr,	/* in: scanned to */
2514 2515 2516
	ibool*		success,/* out: TRUE if success */
	dict_table_t*	table,	/* in: table in which the column is */
	dict_col_t**	column,	/* out: pointer to column if success */
2517 2518 2519
	mem_heap_t*	heap,	/* in: heap where to allocate the name */
	const char**	name)	/* out,own: the column name; NULL if no name
				was scannable */
2520
{
2521
#ifndef UNIV_HOTBACKUP
2522 2523
	dict_col_t*	col;
	ulint		i;
2524

2525 2526
	*success = FALSE;

2527
	ptr = dict_scan_id(ptr, heap, name, TRUE);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2528

2529
	if (*name == NULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2530

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2531
		return(ptr);	/* Syntax error */
2532 2533
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2534 2535 2536 2537 2538
	if (table == NULL) {
		*success = TRUE;
		*column = NULL;
	} else {
	    	for (i = 0; i < dict_table_get_n_cols(table); i++) {
2539

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2540
			col = dict_table_get_nth_col(table, i);
2541

2542
			if (0 == innobase_strcasecmp(col->name, *name)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2543
		    		/* Found */
2544

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2545 2546
		    		*success = TRUE;
		    		*column = col;
2547
		    		strcpy((char*) *name, col->name);
2548

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2549 2550
		    		break;
			}
2551 2552 2553 2554
		}
	}
	
	return(ptr);
2555 2556 2557 2558 2559 2560
#else /* UNIV_HOTBACKUP */
	/* This function depends on MySQL code that is not included in
	InnoDB Hot Backup builds.  Besides, this function should never
	be called in InnoDB Hot Backup. */
	ut_error;
#endif /* UNIV_HOTBACKUP */
2561 2562 2563
}

/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2564
Scans a table name from an SQL string. */
2565
static
2566
const char*
2567 2568 2569
dict_scan_table_name(
/*=================*/
				/* out: scanned to */
2570
	const char*	ptr,	/* in: scanned to */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2571
	dict_table_t**	table,	/* out: table object or NULL */
2572
	const char*	name,	/* in: foreign key table name */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2573
	ibool*		success,/* out: TRUE if ok name found */
2574
	mem_heap_t*	heap,	/* in: heap where to allocate the id */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2575
	const char**	ref_name)/* out,own: the table name;
2576
				NULL if no name was scannable */
2577
{
2578
#ifndef UNIV_HOTBACKUP
2579 2580 2581 2582 2583 2584 2585
	const char*	database_name	= NULL;
	ulint		database_name_len = 0;
	const char*	table_name	= NULL;
	ulint		table_name_len;
	const char*	scan_name;
	char*		ref;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2586
	*success = FALSE;
2587
	*table = NULL;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2588
	
2589
	ptr = dict_scan_id(ptr, heap, &scan_name, FALSE);	
2590

2591
	if (scan_name == NULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2592 2593
		
		return(ptr);	/* Syntax error */
2594 2595
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2596 2597
	if (*ptr == '.') {
		/* We scanned the database name; scan also the table name */
2598

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2599 2600
		ptr++;

2601 2602
		database_name = scan_name;
		database_name_len = strlen(database_name);
2603

2604
		ptr = dict_scan_id(ptr, heap, &table_name, FALSE);
2605

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2606
		if (table_name == NULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2607

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2608
			return(ptr);	/* Syntax error */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2609
		}
2610
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2611 2612 2613 2614 2615 2616 2617
		/* To be able to read table dumps made with InnoDB-4.0.17 or
		earlier, we must allow the dot separator between the database
		name and the table name also to appear within a quoted
		identifier! InnoDB used to print a constraint as:
			... REFERENCES `databasename.tablename` ...
		starting from 4.0.18 it is
			... REFERENCES `databasename`.`tablename` ... */
2618 2619 2620 2621 2622 2623 2624 2625
		const char* s;

		for (s = scan_name; *s; s++) {
			if (*s == '.') {
				database_name = scan_name;
				database_name_len = s - scan_name;
				scan_name = ++s;
				break;/* to do: multiple dots? */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2626
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2627
		}
2628

2629
		table_name = scan_name;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2630 2631
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2632 2633
	if (database_name == NULL) {
		/* Use the database name of the foreign key table */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2634

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2635
		database_name = name;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2636
		database_name_len = dict_get_db_name_len(name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2637 2638
	}

2639 2640
	table_name_len = strlen(table_name);

2641
	/* Copy database_name, '/', table_name, '\0' */
2642
	ref = mem_heap_alloc(heap, database_name_len + table_name_len + 2);
2643 2644 2645 2646
	memcpy(ref, database_name, database_name_len);
	ref[database_name_len] = '/';
	memcpy(ref + database_name_len + 1, table_name, table_name_len + 1);
#ifndef __WIN__
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2647
	if (srv_lower_case_table_names) {
2648 2649 2650 2651
#endif /* !__WIN__ */
		/* The table name is always put to lower case on Windows. */
		innobase_casedn_str(ref);
#ifndef __WIN__
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2652
	}
2653
#endif /* !__WIN__ */
2654

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2655
	*success = TRUE;
2656 2657
	*ref_name = ref;
	*table = dict_table_get_low(ref);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2658 2659

	return(ptr);
2660 2661 2662 2663 2664 2665
#else /* UNIV_HOTBACKUP */
	/* This function depends on MySQL code that is not included in
	InnoDB Hot Backup builds.  Besides, this function should never
	be called in InnoDB Hot Backup. */
	ut_error;
#endif /* UNIV_HOTBACKUP */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2666 2667
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2668
/*************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2669
Skips one id. The id is allowed to contain also '.'. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2670
static
2671
const char*
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2672 2673
dict_skip_word(
/*===========*/
2674 2675 2676 2677
				/* out: scanned to */
	const char*	ptr,	/* in: scanned to */
	ibool*		success)/* out: TRUE if success, FALSE if just spaces
				left in string or a syntax error */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2678
{
2679
	const char*	start;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2680 2681 2682
	
	*success = FALSE;

2683
	ptr = dict_scan_id(ptr, NULL, &start, TRUE);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701

	if (start) {
		*success = TRUE;
	}
	
	return(ptr);
}

/*************************************************************************
Removes MySQL comments from an SQL string. A comment is either
(a) '#' to the end of the line,
(b) '--<space>' to the end of the line, or
(c) '<slash><asterisk>' till the next '<asterisk><slash>' (like the familiar
C comment syntax). */
static
char*
dict_strip_comments(
/*================*/
2702 2703 2704 2705
					/* out, own: SQL string stripped from
					comments; the caller must free this
					with mem_free()! */
	const char*	sql_string)	/* in: SQL string */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2706
{
2707 2708 2709
	char*		str;
	const char*	sptr;
	char*		ptr;
2710 2711 2712
 	/* unclosed quote character (0 if none) */
 	char		quote	= 0;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2713 2714 2715 2716 2717 2718
	str = mem_alloc(strlen(sql_string) + 1);

	sptr = sql_string;
	ptr = str;

	for (;;) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2719
scan_more:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2720 2721 2722
		if (*sptr == '\0') {
			*ptr = '\0';

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2723 2724
			ut_a(ptr <= str + strlen(sql_string));

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2725 2726
			return(str);
		}
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738

		if (*sptr == quote) {
			/* Closing quote character: do not look for
			starting quote or comments. */
			quote = 0;
		} else if (quote) {
			/* Within quotes: do not look for
			starting quotes or comments. */
		} else if (*sptr == '"' || *sptr == '`') {
			/* Starting quote: remember the quote character. */
			quote = *sptr;
		} else if (*sptr == '#'
2739 2740
                           || (sptr[0] == '-' && sptr[1] == '-' &&
                               sptr[2] == ' ')) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2741
			for (;;) {
2742 2743
				/* In Unix a newline is 0x0A while in Windows
				it is 0x0D followed by 0x0A */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2744 2745 2746 2747 2748

				if (*sptr == (char)0x0A
				    || *sptr == (char)0x0D
				    || *sptr == '\0') {

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2749
					goto scan_more;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2750 2751 2752 2753
				}

				sptr++;
			}
2754
		} else if (!quote && *sptr == '/' && *(sptr + 1) == '*') {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2755
			for (;;) {
2756
				if (*sptr == '*' && *(sptr + 1) == '/') {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2757 2758 2759

				     	sptr += 2;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2760
					goto scan_more;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2761 2762 2763 2764
				}

				if (*sptr == '\0') {

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2765
					goto scan_more;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778
				}

				sptr++;
			}
		}

		*ptr = *sptr;

		ptr++;
		sptr++;
	}
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
/*************************************************************************
Finds the highest <number> for foreign key constraints of the table. Looks
only at the >= 4.0.18-format id's, which are of the form
databasename/tablename_ibfk_<number>. */
static
ulint
dict_table_get_highest_foreign_id(
/*==============================*/
				/* out: highest number, 0 if table has no new
				format foreign key constraints */
	dict_table_t*	table)	/* in: table in the dictionary memory cache */
{
	dict_foreign_t*	foreign;
	char*		endp;
	ulint		biggest_id	= 0;
	ulint		id;
2795
	ulint		len;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2796 2797 2798

	ut_a(table);

2799
	len = ut_strlen(table->name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2800 2801 2802
	foreign = UT_LIST_GET_FIRST(table->foreign_list);

	while (foreign) {
2803 2804 2805 2806
		if (ut_strlen(foreign->id) > ((sizeof dict_ibfk) - 1) + len
		    && 0 == ut_memcmp(foreign->id, table->name, len)
		    && 0 == ut_memcmp(foreign->id + len,
				dict_ibfk, (sizeof dict_ibfk) - 1)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2807 2808
			/* It is of the >= 4.0.18 format */

2809
			id = strtoul(foreign->id + len + ((sizeof dict_ibfk) - 1),
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2810
					&endp, 10);
2811 2812
			if (*endp == '\0') {
				ut_a(id != biggest_id);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2813

2814 2815 2816
				if (id > biggest_id) {
					biggest_id = id;
				}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2817 2818 2819 2820 2821 2822 2823 2824 2825
			}
		}

		foreign = UT_LIST_GET_NEXT(foreign_list, foreign);
	}

	return(biggest_id);
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2826 2827 2828 2829 2830 2831
/*************************************************************************
Reports a simple foreign key create clause syntax error. */
static
void
dict_foreign_report_syntax_err(
/*===========================*/
2832 2833 2834
	const char*	name,		/* in: table name */
	const char*	start_of_latest_foreign,
					/* in: start of the foreign key clause
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2835
					in the SQL string */
2836
	const char*	ptr)		/* in: place of the syntax error */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2837
{
2838
	FILE*	 ef = dict_foreign_err_file;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2839 2840

	mutex_enter(&dict_foreign_err_mutex);
2841 2842 2843
	dict_foreign_error_report_low(ef, name);
	fprintf(ef, "%s:\nSyntax error close to:\n%s\n",
		start_of_latest_foreign, ptr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2844 2845
	mutex_exit(&dict_foreign_err_mutex);
}
2846 2847 2848 2849 2850 2851 2852

/*************************************************************************
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 both participating tables. The indexes are
allowed to contain more fields than mentioned in the constraint. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2853
static
2854
ulint
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2855 2856
dict_create_foreign_constraints_low(
/*================================*/
2857
				/* out: error code or DB_SUCCESS */
2858 2859 2860 2861 2862
	trx_t*		trx,	/* in: transaction */
	mem_heap_t*	heap,	/* in: memory heap */
	const char*	sql_string,
				/* in: CREATE TABLE or ALTER TABLE statement
				where foreign keys are declared like:
2863 2864 2865
				FOREIGN KEY (a, b) REFERENCES table2(c, d),
				table2 can be written also with the database
				name before it: test.table2; the default
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2866
				database is the database of parameter name */
2867
	const char*	name,	/* in: table full name in the normalized form
2868
				database_name/table_name */
2869 2870 2871 2872
	ibool		reject_fks)
				/* in: if TRUE, fail with error code
				DB_CANNOT_ADD_CONSTRAINT if any foreign
				keys are found. */
2873 2874 2875
{
	dict_table_t*	table;
	dict_table_t*	referenced_table;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2876 2877
	dict_table_t*	table_to_alter;
	ulint		highest_id_so_far	= 0;
2878 2879
	dict_index_t*	index;
	dict_foreign_t*	foreign;
2880
 	const char*	ptr			= sql_string;
2881
	const char*	start_of_latest_foreign	= sql_string;
2882
	FILE*		ef			= dict_foreign_err_file;
2883
	const char*	constraint_name;
2884 2885
	ibool		success;
	ulint		error;
2886 2887
	const char*	ptr1;
	const char*	ptr2;
2888
	ulint		i;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2889
	ulint		j;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2890 2891 2892
	ibool		is_on_delete;
	ulint		n_on_deletes;
	ulint		n_on_updates;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2893
	dict_col_t*	columns[500];
2894 2895
	const char*	column_names[500];
	const char*	referenced_table_name;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2896
	
2897
#ifdef UNIV_SYNC_DEBUG
2898
	ut_ad(mutex_own(&(dict_sys->mutex)));
2899
#endif /* UNIV_SYNC_DEBUG */
2900

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
2901
	table = dict_table_get_low(name);
2902 2903

	if (table == NULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2904
		mutex_enter(&dict_foreign_err_mutex);
2905 2906 2907 2908
		dict_foreign_error_report_low(ef, name);
		fprintf(ef,
"Cannot find the table in the internal data dictionary of InnoDB.\n"
"Create table statement:\n%s\n", sql_string);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2909 2910
		mutex_exit(&dict_foreign_err_mutex);

2911 2912
		return(DB_ERROR);
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2913 2914 2915 2916

	/* First check if we are actually doing an ALTER TABLE, and in that
	case look for the table being altered */

2917
	ptr = dict_accept(ptr, "ALTER", &success);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2918 2919 2920 2921 2922 2923

	if (!success) {

		goto loop;
	}

2924
	ptr = dict_accept(ptr, "TABLE", &success);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2925 2926 2927 2928 2929 2930

	if (!success) {

		goto loop;
	}

2931
	/* We are doing an ALTER TABLE: scan the table name we are altering */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2932 2933

	ptr = dict_scan_table_name(ptr, &table_to_alter, name,
2934
				&success, heap, &referenced_table_name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
	if (!success) {
		fprintf(stderr,
"InnoDB: Error: could not find the table being ALTERED in:\n%s\n", sql_string);

		return(DB_ERROR);
	}

	/* Starting from 4.0.18 and 4.1.2, we generate foreign key id's in the
	format databasename/tablename_ibfk_<number>, where <number> is local
	to the table; look for the highest <number> for table_to_alter, so
	that we can assign to new constraints higher numbers. */

	/* If we are altering a temporary table, the table name after ALTER
	TABLE does not correspond to the internal table name, and
	table_to_alter is NULL. TODO: should we fix this somehow? */

	if (table_to_alter == NULL) {
		highest_id_so_far = 0;
	} else {
		highest_id_so_far = dict_table_get_highest_foreign_id(
							table_to_alter);
	}

	/* Scan for foreign key declarations in a loop */
2959
loop:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2960
	/* Scan either to "CONSTRAINT" or "FOREIGN", whichever is closer */
2961

2962 2963
	ptr1 = dict_scan_to(ptr, "CONSTRAINT");
	ptr2 = dict_scan_to(ptr, "FOREIGN");
2964

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2965 2966 2967
	constraint_name = NULL;

	if (ptr1 < ptr2) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2968
		/* The user may have specified a constraint name. Pick it so
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2969
		that we can store 'databasename/constraintname' as the id of
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2970
		of the constraint to system tables. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2971 2972
		ptr = ptr1;

2973
		ptr = dict_accept(ptr, "CONSTRAINT", &success);
2974

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2975 2976
		ut_a(success);

2977
		if (!isspace(*ptr) && *ptr != '"' && *ptr != '`') {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2978 2979 2980
	        	goto loop;
		}

2981
		while (isspace(*ptr)) {
2982
			ptr++;
2983
		}
2984 2985 2986

		/* read constraint name unless got "CONSTRAINT FOREIGN" */
		if (ptr != ptr2) {
2987
			ptr = dict_scan_id(ptr, heap, &constraint_name, FALSE);
2988
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2989 2990 2991 2992 2993
	} else {
		ptr = ptr2;
	}

	if (*ptr == '\0') {
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
		/* The proper way to reject foreign keys for temporary
		   tables would be to split the lexing and syntactical
		   analysis of foreign key clauses from the actual adding
		   of them, so that ha_innodb.cc could first parse the SQL
		   command, determine if there are any foreign keys, and
		   if so, immediately reject the command if the table is a
		   temporary one. For now, this kludge will work. */
		if (reject_fks && (UT_LIST_GET_LEN(table->foreign_list) > 0))
		{
			return DB_CANNOT_ADD_CONSTRAINT;
		}
		
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3006
		/**********************************************************/
3007 3008 3009
		/* The following call adds the foreign key constraints
		to the data dictionary system tables on disk */
		
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3010 3011
		error = dict_create_add_foreigns_to_dictionary(
						highest_id_so_far, table, trx);
3012 3013 3014
		return(error);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3015 3016
	start_of_latest_foreign = ptr;

3017
	ptr = dict_accept(ptr, "FOREIGN", &success);		
3018
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3019 3020 3021 3022
	if (!success) {
		goto loop;
	}

3023
	if (!isspace(*ptr)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3024
	        goto loop;
3025 3026
	}

3027
	ptr = dict_accept(ptr, "KEY", &success);
3028 3029 3030 3031 3032

	if (!success) {
		goto loop;
	}

3033
	ptr = dict_accept(ptr, "(", &success);
3034 3035

	if (!success) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3036 3037 3038 3039 3040
		/* MySQL allows also an index id before the '('; we
		skip it */
		ptr = dict_skip_word(ptr, &success);

		if (!success) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3041 3042 3043
			dict_foreign_report_syntax_err(name,
					start_of_latest_foreign, ptr);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3044 3045 3046
			return(DB_CANNOT_ADD_CONSTRAINT);
		}

3047
		ptr = dict_accept(ptr, "(", &success);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3048 3049

		if (!success) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3050 3051 3052 3053
			/* We do not flag a syntax error here because in an
			ALTER TABLE we may also have DROP FOREIGN KEY abc */

		        goto loop;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3054
		}
3055 3056 3057 3058 3059 3060
	}

	i = 0;

	/* Scan the columns in the first list */
col_loop1:
3061
	ut_a(i < (sizeof column_names) / sizeof *column_names);
3062
	ptr = dict_scan_col(ptr, &success, table, columns + i,
3063
				heap, column_names + i);
3064
	if (!success) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3065
		mutex_enter(&dict_foreign_err_mutex);
3066 3067
		dict_foreign_error_report_low(ef, name);
		fprintf(ef, "%s:\nCannot resolve column name close to:\n%s\n",
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3068 3069 3070
					start_of_latest_foreign, ptr);
		mutex_exit(&dict_foreign_err_mutex);

3071 3072 3073 3074 3075
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

	i++;
	
3076
	ptr = dict_accept(ptr, ",", &success);
3077 3078 3079 3080 3081

	if (success) {
		goto col_loop1;
	}
	
3082
	ptr = dict_accept(ptr, ")", &success);
3083 3084

	if (!success) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3085 3086
		dict_foreign_report_syntax_err(name, start_of_latest_foreign,
									ptr);
3087 3088 3089 3090 3091 3092
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

	/* Try to find an index which contains the columns
	as the first fields and in the right order */

3093
	index = dict_foreign_find_index(table, column_names, i, NULL, TRUE);
3094 3095

	if (!index) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3096
		mutex_enter(&dict_foreign_err_mutex);
3097 3098
		dict_foreign_error_report_low(ef, name);
		fputs("There is no index in table ", ef);
3099
		ut_print_name(ef, NULL, name);
3100 3101
		fprintf(ef, " where the columns appear\n"
"as the first columns. Constraint:\n%s\n"
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3102
"See http://dev.mysql.com/doc/mysql/en/InnoDB_foreign_key_constraints.html\n"
3103
"for correct foreign key definition.\n",
3104
			start_of_latest_foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3105 3106
		mutex_exit(&dict_foreign_err_mutex);

3107 3108
		return(DB_CANNOT_ADD_CONSTRAINT);
	}
3109
	ptr = dict_accept(ptr, "REFERENCES", &success);
3110 3111

	if (!success || !isspace(*ptr)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3112 3113
		dict_foreign_report_syntax_err(name, start_of_latest_foreign,
									ptr);
3114 3115 3116 3117 3118 3119 3120
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

	/* Let us create a constraint struct */

	foreign = dict_mem_foreign_create();

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131
	if (constraint_name) {
		ulint	db_len;	

		/* Catenate 'databasename/' to the constraint name specified
		by the user: we conceive the constraint as belonging to the
		same MySQL 'database' as the table itself. We store the name
		to foreign->id. */

		db_len = dict_get_db_name_len(table->name);

		foreign->id = mem_heap_alloc(foreign->heap,
3132
				db_len + strlen(constraint_name) + 2);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3133

3134
		ut_memcpy(foreign->id, table->name, db_len);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3135
		foreign->id[db_len] = '/';
3136
		strcpy(foreign->id + db_len + 1, constraint_name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3137 3138
	}

3139
	foreign->foreign_table = table;
3140 3141
	foreign->foreign_table_name = mem_heap_strdup(foreign->heap,
							table->name);
3142 3143 3144 3145 3146
	foreign->foreign_index = index;
	foreign->n_fields = i;
	foreign->foreign_col_names = mem_heap_alloc(foreign->heap,
							i * sizeof(void*));
	for (i = 0; i < foreign->n_fields; i++) {
3147 3148
		foreign->foreign_col_names[i] =
			mem_heap_strdup(foreign->heap, columns[i]->name);
3149 3150
	}
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3151
	ptr = dict_scan_table_name(ptr, &referenced_table, name,
3152
				&success, heap, &referenced_table_name);
3153

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3154 3155 3156 3157
	/* Note that referenced_table can be NULL if the user has suppressed
	checking of foreign key constraints! */

	if (!success || (!referenced_table && trx->check_foreigns)) {
3158 3159
		dict_foreign_free(foreign);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3160
		mutex_enter(&dict_foreign_err_mutex);
3161 3162 3163 3164
		dict_foreign_error_report_low(ef, name);
		fprintf(ef, "%s:\nCannot resolve table name close to:\n"
			"%s\n",
			start_of_latest_foreign, ptr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3165 3166
		mutex_exit(&dict_foreign_err_mutex);

3167 3168 3169
		return(DB_CANNOT_ADD_CONSTRAINT);
	}
	
3170
	ptr = dict_accept(ptr, "(", &success);
3171 3172 3173

	if (!success) {
		dict_foreign_free(foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3174 3175
		dict_foreign_report_syntax_err(name, start_of_latest_foreign,
									ptr);
3176 3177 3178 3179 3180 3181 3182 3183
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

	/* Scan the columns in the second list */
	i = 0;

col_loop2:
	ptr = dict_scan_col(ptr, &success, referenced_table, columns + i,
3184
				heap, column_names + i);
3185 3186 3187 3188
	i++;
	
	if (!success) {
		dict_foreign_free(foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3189

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3190
		mutex_enter(&dict_foreign_err_mutex);
3191 3192 3193 3194
		dict_foreign_error_report_low(ef, name);
		fprintf(ef, "%s:\nCannot resolve column name close to:\n"
			"%s\n",
			start_of_latest_foreign, ptr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3195 3196
		mutex_exit(&dict_foreign_err_mutex);

3197 3198 3199
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

3200
	ptr = dict_accept(ptr, ",", &success);
3201 3202 3203 3204 3205

	if (success) {
		goto col_loop2;
	}
	
3206
	ptr = dict_accept(ptr, ")", &success);
3207 3208 3209 3210

	if (!success || foreign->n_fields != i) {
		dict_foreign_free(foreign);
		
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3211 3212
		dict_foreign_report_syntax_err(name, start_of_latest_foreign,
									ptr);
3213 3214 3215
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3216 3217 3218 3219 3220 3221
	n_on_deletes = 0;
	n_on_updates = 0;
	
scan_on_conditions:
	/* Loop here as long as we can find ON ... conditions */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3222 3223 3224 3225 3226 3227 3228 3229 3230 3231
	ptr = dict_accept(ptr, "ON", &success);

	if (!success) {

		goto try_find_index;
	}

	ptr = dict_accept(ptr, "DELETE", &success);

	if (!success) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3232 3233 3234 3235
		ptr = dict_accept(ptr, "UPDATE", &success);

		if (!success) {
			dict_foreign_free(foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3236
		
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3237 3238
			dict_foreign_report_syntax_err(name,
						start_of_latest_foreign, ptr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3239 3240 3241 3242 3243 3244 3245 3246
			return(DB_CANNOT_ADD_CONSTRAINT);
		}

		is_on_delete = FALSE;
		n_on_updates++;
	} else {
		is_on_delete = TRUE;
		n_on_deletes++;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3247 3248 3249
	}

	ptr = dict_accept(ptr, "RESTRICT", &success);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3250

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3251
	if (success) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3252
		goto scan_on_conditions;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3253 3254 3255 3256 3257
	}

	ptr = dict_accept(ptr, "CASCADE", &success);

	if (success) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3258 3259 3260 3261 3262
		if (is_on_delete) {
			foreign->type |= DICT_FOREIGN_ON_DELETE_CASCADE;
		} else {
			foreign->type |= DICT_FOREIGN_ON_UPDATE_CASCADE;
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3263

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
		goto scan_on_conditions;
	}

	ptr = dict_accept(ptr, "NO", &success);

	if (success) {
		ptr = dict_accept(ptr, "ACTION", &success);

		if (!success) {
			dict_foreign_free(foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3274 3275
			dict_foreign_report_syntax_err(name,
					start_of_latest_foreign, ptr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286
		
			return(DB_CANNOT_ADD_CONSTRAINT);
		}

		if (is_on_delete) {
			foreign->type |= DICT_FOREIGN_ON_DELETE_NO_ACTION;
		} else {
			foreign->type |= DICT_FOREIGN_ON_UPDATE_NO_ACTION;
		}

		goto scan_on_conditions;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3287 3288 3289 3290 3291
	}

	ptr = dict_accept(ptr, "SET", &success);

	if (!success) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3292
		dict_foreign_free(foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3293 3294
		dict_foreign_report_syntax_err(name, start_of_latest_foreign,
									ptr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3295
		return(DB_CANNOT_ADD_CONSTRAINT);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3296 3297 3298 3299
	}

	ptr = dict_accept(ptr, "NULL", &success);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3300 3301
	if (!success) {
		dict_foreign_free(foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3302 3303
		dict_foreign_report_syntax_err(name, start_of_latest_foreign,
									ptr);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3304 3305 3306 3307 3308
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

	for (j = 0; j < foreign->n_fields; j++) {
		if ((dict_index_get_nth_type(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3309 3310 3311
				foreign->foreign_index, j)->prtype)
				& DATA_NOT_NULL) {

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3312 3313
			/* It is not sensible to define SET NULL
			if the column is not allowed to be NULL! */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3314

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3315 3316
			dict_foreign_free(foreign);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3317
			mutex_enter(&dict_foreign_err_mutex);
3318 3319 3320 3321
			dict_foreign_error_report_low(ef, name);
			fprintf(ef, "%s:\n"
		"You have defined a SET NULL condition though some of the\n"
		"columns are defined as NOT NULL.\n", start_of_latest_foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3322 3323
			mutex_exit(&dict_foreign_err_mutex);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3324
			return(DB_CANNOT_ADD_CONSTRAINT);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3325
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3326
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3327

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3328 3329 3330 3331 3332
	if (is_on_delete) {
		foreign->type |= DICT_FOREIGN_ON_DELETE_SET_NULL;
	} else {
		foreign->type |= DICT_FOREIGN_ON_UPDATE_SET_NULL;
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3333
	
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3334
	goto scan_on_conditions;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3335

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3336 3337 3338 3339
try_find_index:
	if (n_on_deletes > 1 || n_on_updates > 1) {
		/* It is an error to define more than 1 action */
		
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3340 3341
		dict_foreign_free(foreign);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3342
		mutex_enter(&dict_foreign_err_mutex);
3343 3344
		dict_foreign_error_report_low(ef, name);
		fprintf(ef, "%s:\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3345
"You have twice an ON DELETE clause or twice an ON UPDATE clause.\n",
3346
			start_of_latest_foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3347 3348
		mutex_exit(&dict_foreign_err_mutex);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3349
		return(DB_CANNOT_ADD_CONSTRAINT);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3350
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3351

3352 3353 3354 3355
	/* Try to find an index which contains the columns as the first fields
	and in the right order, and the types are the same as in
	foreign->foreign_index */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3356 3357
	if (referenced_table) {
		index = dict_foreign_find_index(referenced_table,
3358
			column_names, i, foreign->foreign_index, TRUE);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3359 3360
		if (!index) {
			dict_foreign_free(foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3361
			mutex_enter(&dict_foreign_err_mutex);
3362 3363
			dict_foreign_error_report_low(ef, name);
			fprintf(ef, "%s:\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3364 3365
"Cannot find an index in the referenced table where the\n"
"referenced columns appear as the first columns, or column types\n"
3366
"in the table and the referenced table do not match for constraint.\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3367 3368 3369
"Note that the internal storage type of ENUM and SET changed in\n"
"tables created with >= InnoDB-4.1.12, and such columns in old tables\n"
"cannot be referenced by such columns in new tables.\n"
3370 3371
"See http://dev.mysql.com/doc/mysql/en/InnoDB_foreign_key_constraints.html\n"
"for correct foreign key definition.\n",
3372
				start_of_latest_foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3373 3374
			mutex_exit(&dict_foreign_err_mutex);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3375 3376 3377 3378 3379
			return(DB_CANNOT_ADD_CONSTRAINT);
		}
	} else {
		ut_a(trx->check_foreigns == FALSE);
		index = NULL;
3380 3381 3382 3383 3384
	}

	foreign->referenced_index = index;
	foreign->referenced_table = referenced_table;

3385 3386
	foreign->referenced_table_name = mem_heap_strdup(foreign->heap,
						referenced_table_name);
3387 3388 3389 3390 3391
					
	foreign->referenced_col_names = mem_heap_alloc(foreign->heap,
							i * sizeof(void*));
	for (i = 0; i < foreign->n_fields; i++) {
		foreign->referenced_col_names[i]
3392
			= mem_heap_strdup(foreign->heap, column_names[i]);
3393 3394 3395 3396 3397
	}

	/* We found an ok constraint definition: add to the lists */
	
	UT_LIST_ADD_LAST(foreign_list, table->foreign_list, foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3398 3399 3400 3401

	if (referenced_table) {
		UT_LIST_ADD_LAST(referenced_list,
					referenced_table->referenced_list,
3402
								foreign);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3403
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3404

3405 3406 3407
	goto loop;
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3408 3409 3410 3411 3412 3413 3414 3415 3416 3417
/*************************************************************************
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 both participating tables. The indexes are
allowed to contain more fields than mentioned in the constraint. */

ulint
dict_create_foreign_constraints(
/*============================*/
3418 3419 3420 3421 3422 3423 3424 3425 3426 3427
					/* 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:
					FOREIGN KEY (a, b) REFERENCES
					table2(c, d), table2 can be written
					also with the database
					name before it: test.table2; the
					default database id the database of
					parameter name */
3428
	const char*	name,		/* in: table full name in the
3429 3430
					normalized form
					database_name/table_name */
3431 3432 3433
	ibool		reject_fks)	/* in: if TRUE, fail with error
					code DB_CANNOT_ADD_CONSTRAINT if
					any foreign keys are found. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3434
{
3435 3436 3437
	char*		str;
	ulint		err;
	mem_heap_t*	heap;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3438 3439

	str = dict_strip_comments(sql_string);
3440
	heap = mem_heap_create(10000);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3441

3442 3443
	err = dict_create_foreign_constraints_low(trx, heap, str, name,
		reject_fks);
3444 3445 3446

	mem_heap_free(heap);
	mem_free(str);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466

	return(err);	
}

/**************************************************************************
Parses the CONSTRAINT id's to be dropped in an ALTER TABLE statement. */

ulint
dict_foreign_parse_drop_constraints(
/*================================*/
						/* out: DB_SUCCESS or
						DB_CANNOT_DROP_CONSTRAINT if
						syntax error or the constraint
						id does not match */
	mem_heap_t*	heap,			/* in: heap from which we can
						allocate memory */
	trx_t*		trx,			/* in: transaction */
	dict_table_t*	table,			/* in: table */
	ulint*		n,			/* out: number of constraints
						to drop */
3467
	const char***	constraints_to_drop)	/* out: id's of the
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3468 3469
						constraints to drop */
{
3470 3471 3472 3473 3474
	dict_foreign_t*	foreign;
	ibool		success;
	char*		str;
	const char*	ptr;
	const char*	id;
3475
	FILE*		ef	= dict_foreign_err_file;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3476 3477 3478 3479 3480 3481 3482 3483
	
	*n = 0;

	*constraints_to_drop = mem_heap_alloc(heap, 1000 * sizeof(char*));

	str = dict_strip_comments(*(trx->mysql_query_str));
	ptr = str;

3484
#ifdef UNIV_SYNC_DEBUG
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3485
	ut_ad(mutex_own(&(dict_sys->mutex)));
3486
#endif /* UNIV_SYNC_DEBUG */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3487
loop:
3488
	ptr = dict_scan_to(ptr, "DROP");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3489 3490 3491 3492 3493 3494 3495

	if (*ptr == '\0') {
		mem_free(str);
		
		return(DB_SUCCESS);
	}

3496
	ptr = dict_accept(ptr, "DROP", &success);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3497 3498 3499 3500 3501 3502

	if (!isspace(*ptr)) {

	        goto loop;
	}

3503
	ptr = dict_accept(ptr, "FOREIGN", &success);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3504 3505 3506 3507 3508 3509
	
	if (!success) {

	        goto loop;
	}

3510
	ptr = dict_accept(ptr, "KEY", &success);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3511 3512 3513 3514 3515 3516

	if (!success) {

		goto syntax_error;
	}

3517
	ptr = dict_scan_id(ptr, heap, &id, TRUE);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3518

3519
	if (id == NULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3520 3521 3522 3523

		goto syntax_error;
	}

3524
	ut_a(*n < 1000);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3525 3526 3527 3528 3529 3530 3531 3532
	(*constraints_to_drop)[*n] = id;
	(*n)++;
	
	/* Look for the given constraint id */

	foreign = UT_LIST_GET_FIRST(table->foreign_list);

	while (foreign != NULL) {
3533
		if (0 == strcmp(foreign->id, id)
3534
		    || (strchr(foreign->id, '/')
3535
			&& 0 == strcmp(id,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3536
					dict_remove_db_name(foreign->id)))) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3537 3538 3539 3540 3541 3542 3543 3544 3545
			/* Found */
			break;
		}
		
		foreign = UT_LIST_GET_NEXT(foreign_list, foreign);
	}

	if (foreign == NULL) {
		mutex_enter(&dict_foreign_err_mutex);
3546 3547 3548 3549
		rewind(ef);
		ut_print_timestamp(ef);
		fputs(
	" Error in dropping of a foreign key constraint of table ", ef);
3550
		ut_print_name(ef, NULL, table->name);
3551 3552 3553 3554
		fputs(",\n"
			"in SQL command\n", ef);
		fputs(str, ef);
		fputs("\nCannot find a constraint with the given id ", ef);
3555
		ut_print_name(ef, NULL, id);
3556
		fputs(".\n", ef);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567
		mutex_exit(&dict_foreign_err_mutex);

		mem_free(str);

		return(DB_CANNOT_DROP_CONSTRAINT);
	}

	goto loop;	

syntax_error:
	mutex_enter(&dict_foreign_err_mutex);
3568 3569 3570 3571
	rewind(ef);
	ut_print_timestamp(ef);
	fputs(
	" Syntax error in dropping of a foreign key constraint of table ", ef);
3572
	ut_print_name(ef, NULL, table->name);
3573 3574
	fprintf(ef, ",\n"
		"close to:\n%s\n in SQL command\n%s\n", ptr, str);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3575 3576 3577 3578 3579 3580 3581
	mutex_exit(&dict_foreign_err_mutex);

	mem_free(str);

	return(DB_CANNOT_DROP_CONSTRAINT);
}

3582 3583
/*==================== END OF FOREIGN KEY PROCESSING ====================*/

3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632
/**************************************************************************
Returns an index object if it is found in the dictionary cache. */

dict_index_t*
dict_index_get_if_in_cache(
/*=======================*/
				/* out: index, NULL if not found */
	dulint	index_id)	/* in: index id */
{
	dict_table_t*	table;
	dict_index_t*	index;

	if (dict_sys == NULL) {
		return(NULL);
	}

	mutex_enter(&(dict_sys->mutex));
	
	table = UT_LIST_GET_FIRST(dict_sys->table_LRU);

	while (table) {
		index = UT_LIST_GET_FIRST(table->indexes);

		while (index) {
			if (0 == ut_dulint_cmp(index->id, index_id)) {

				goto found;
			}

			index = UT_LIST_GET_NEXT(indexes, index);
		}

		table = UT_LIST_GET_NEXT(table_LRU, table);
	}

	index = NULL;
found:
	mutex_exit(&(dict_sys->mutex));

	return(index);
}

/**************************************************************************
Creates an index tree struct. */

dict_tree_t*
dict_tree_create(
/*=============*/
				/* out, own: created tree */
3633
	dict_index_t*	index,	/* in: the index for which to create: in the
3634 3635
				case of a mixed tree, this should be the
				index of the cluster object */
3636
	ulint		page_no)/* in: root page number of the index */
3637 3638 3639 3640 3641 3642 3643 3644 3645
{
	dict_tree_t*	tree;

	tree = mem_alloc(sizeof(dict_tree_t));

	/* Inherit info from the index */

	tree->type = index->type;
	tree->space = index->space;
3646
	tree->page = page_no;
3647 3648 3649 3650

	tree->id = index->id;
	
	UT_LIST_INIT(tree->tree_indexes);
3651

3652
	tree->magic_n = DICT_TREE_MAGIC_N;
3653

3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668
	rw_lock_create(&(tree->lock));

	rw_lock_set_level(&(tree->lock), SYNC_INDEX_TREE);

	return(tree);
}

/**************************************************************************
Frees an index tree struct. */

void
dict_tree_free(
/*===========*/
	dict_tree_t*	tree)	/* in, own: index tree */
{
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3669
	ut_a(tree);
monty@mysql.com's avatar
monty@mysql.com committed
3670
	ut_ad(tree->magic_n == DICT_TREE_MAGIC_N);
3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683

	rw_lock_free(&(tree->lock));
	mem_free(tree);
}

/**************************************************************************
In an index tree, finds the index corresponding to a record in the tree. */
UNIV_INLINE
dict_index_t*
dict_tree_find_index_low(
/*=====================*/
				/* out: index */
	dict_tree_t*	tree,	/* in: index tree */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3684 3685
	rec_t*		rec)	/* in: record for which to find correct
				index */
3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696
{
	dict_index_t*	index;
	dict_table_t*	table;
	dulint		mix_id;
	ulint		len;
	
	index = UT_LIST_GET_FIRST(tree->tree_indexes);
	ut_ad(index);
	table = index->table;
	
	if ((index->type & DICT_CLUSTERED)
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3697
			&& UNIV_UNLIKELY(table->type != DICT_TABLE_ORDINARY)) {
3698 3699

		/* Get the mix id of the record */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3700
		ut_a(!table->comp);
3701 3702

		mix_id = mach_dulint_read_compressed(
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3703
			rec_get_nth_field_old(rec, table->mix_len, &len));
3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723

		while (ut_dulint_cmp(table->mix_id, mix_id) != 0) {

			index = UT_LIST_GET_NEXT(tree_indexes, index);
			table = index->table;
			ut_ad(index);
		}
	}

	return(index);
}

/**************************************************************************
In an index tree, finds the index corresponding to a record in the tree. */

dict_index_t*
dict_tree_find_index(
/*=================*/
				/* out: index */
	dict_tree_t*	tree,	/* in: index tree */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3724 3725
	rec_t*		rec)	/* in: record for which to find correct
				index */
3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781
{
	dict_index_t*	index;
	
	index = dict_tree_find_index_low(tree, rec);
	
	return(index);
}

/**************************************************************************
In an index tree, finds the index corresponding to a dtuple which is used
in a search to a tree. */

dict_index_t*
dict_tree_find_index_for_tuple(
/*===========================*/
				/* out: index; NULL if the tuple does not
				contain the mix id field in a mixed tree */
	dict_tree_t*	tree,	/* in: index tree */
	dtuple_t*	tuple)	/* in: tuple for which to find index */
{
	dict_index_t*	index;
	dict_table_t*	table;
	dulint		mix_id;

	ut_ad(dtuple_check_typed(tuple));
	
	if (UT_LIST_GET_LEN(tree->tree_indexes) == 1) {

		return(UT_LIST_GET_FIRST(tree->tree_indexes));
	}

	index = UT_LIST_GET_FIRST(tree->tree_indexes);
	ut_ad(index);
	table = index->table;

	if (dtuple_get_n_fields(tuple) <= table->mix_len) {

		return(NULL);
	}

	/* Get the mix id of the record */

	mix_id = mach_dulint_read_compressed(
			dfield_get_data(
				dtuple_get_nth_field(tuple, table->mix_len)));

	while (ut_dulint_cmp(table->mix_id, mix_id) != 0) {

		index = UT_LIST_GET_NEXT(tree_indexes, index);
		table = index->table;
		ut_ad(index);
	}

	return(index);
}

3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804
/***********************************************************************
Checks if a table which is a mixed cluster member owns a record. */

ibool
dict_is_mixed_table_rec(
/*====================*/
				/* out: TRUE if the record belongs to this
				table */
	dict_table_t*	table,	/* in: table in a mixed cluster */
	rec_t*		rec)	/* in: user record in the clustered index */
{
	byte*	mix_id_field;
	ulint	len;

	ut_ad(!table->comp);

	mix_id_field = rec_get_nth_field_old(rec,
					table->mix_len, &len);

	return(len == table->mix_id_len
		&& !ut_memcmp(table->mix_id_buf, mix_id_field, len));
}

3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837
/**************************************************************************
Checks that a tuple has n_fields_cmp value in a sensible range, so that
no comparison can occur with the page number field in a node pointer. */

ibool
dict_tree_check_search_tuple(
/*=========================*/
				/* out: TRUE if ok */
	dict_tree_t*	tree,	/* in: index tree */
	dtuple_t*	tuple)	/* in: tuple used in a search */
{
	dict_index_t*	index;

	index = dict_tree_find_index_for_tuple(tree, tuple);

	if (index == NULL) {

		return(TRUE);
	}

	ut_a(dtuple_get_n_fields_cmp(tuple)
				<= dict_index_get_n_unique_in_tree(index));
	return(TRUE);
}

/**************************************************************************
Builds a node pointer out of a physical record and a page number. */

dtuple_t*
dict_tree_build_node_ptr(
/*=====================*/
				/* out, own: node pointer */
	dict_tree_t*	tree,	/* in: index tree */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3838 3839
	rec_t*		rec,	/* in: record for which to build node
				pointer */
3840
	ulint		page_no,/* in: page number to put in node pointer */
3841
	mem_heap_t*	heap,	/* in: memory heap where pointer created */
3842
	ulint           level)  /* in: level of rec in tree: 0 means leaf
3843
				level */
3844 3845 3846 3847 3848 3849 3850 3851 3852
{
	dtuple_t*	tuple;
	dict_index_t*	ind;
	dfield_t*	field;
	byte*		buf;
	ulint		n_unique;

	ind = dict_tree_find_index_low(tree, rec);
	
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3853
	if (UNIV_UNLIKELY(tree->type & DICT_UNIVERSAL)) {
3854
		/* In a universal index tree, we take the whole record as
3855 3856 3857
		the node pointer if the reord is on the leaf level,
		on non-leaf levels we remove the last field, which
		contains the page number of the child page */
3858

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3859 3860
		ut_a(!ind->table->comp);
		n_unique = rec_get_n_fields_old(rec);
3861 3862 3863 3864 3865

		if (level > 0) {
		        ut_a(n_unique > 1);
		        n_unique--;
		}
3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888
	} else {	
		n_unique = dict_index_get_n_unique_in_tree(ind);
	}

	tuple = dtuple_create(heap, n_unique + 1);

	/* When searching in the tree for the node pointer, we must not do
	comparison on the last field, the page number field, as on upper
	levels in the tree there may be identical node pointers with a
	different page number; therefore, we set the n_fields_cmp to one
	less: */
	
	dtuple_set_n_fields_cmp(tuple, n_unique);

	dict_index_copy_types(tuple, ind, n_unique);
	
	buf = mem_heap_alloc(heap, 4);

	mach_write_to_4(buf, page_no);
	
	field = dtuple_get_nth_field(tuple, n_unique);
	dfield_set_data(field, buf, 4);

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3889
	dtype_set(dfield_get_type(field), DATA_SYS_CHILD, DATA_NOT_NULL, 4, 0);
3890

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3891 3892 3893
	rec_copy_prefix_to_dtuple(tuple, rec, ind, n_unique, heap);
	dtuple_set_info_bits(tuple, dtuple_get_info_bits(tuple) |
					REC_STATUS_NODE_PTR);
3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909

	ut_ad(dtuple_check_typed(tuple));

	return(tuple);
}	
	
/**************************************************************************
Copies an initial segment of a physical record, long enough to specify an
index entry uniquely. */

rec_t*
dict_tree_copy_rec_order_prefix(
/*============================*/
				/* out: pointer to the prefix record */
	dict_tree_t*	tree,	/* in: index tree */
	rec_t*		rec,	/* in: record for which to copy prefix */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3910
	ulint*		n_fields,/* out: number of fields copied */
3911 3912 3913 3914
	byte**		buf,	/* in/out: memory buffer for the copied prefix,
				or NULL */
	ulint*		buf_size)/* in/out: buffer size */
{
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3915 3916
	dict_index_t*	index;
	ulint		n;
3917

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3918
	UNIV_PREFETCH_R(rec);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3919
	index = dict_tree_find_index_low(tree, rec);
3920

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3921
	if (UNIV_UNLIKELY(tree->type & DICT_UNIVERSAL)) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3922 3923 3924 3925
		ut_a(!index->table->comp);
		n = rec_get_n_fields_old(rec);
	} else {
		n = dict_index_get_n_unique_in_tree(index);
3926 3927
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3928 3929 3930
	*n_fields = n;
	return(rec_copy_prefix_to_buf(rec, index, n, buf, buf_size));
}
3931 3932 3933 3934 3935 3936 3937 3938 3939 3940

/**************************************************************************
Builds a typed data tuple out of a physical record. */

dtuple_t*
dict_tree_build_data_tuple(
/*=======================*/
				/* out, own: data tuple */
	dict_tree_t*	tree,	/* in: index tree */
	rec_t*		rec,	/* in: record for which to build data tuple */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3941
	ulint		n_fields,/* in: number of data fields */
3942 3943 3944 3945 3946 3947 3948
	mem_heap_t*	heap)	/* in: memory heap where tuple created */
{
	dtuple_t*	tuple;
	dict_index_t*	ind;

	ind = dict_tree_find_index_low(tree, rec);

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3949
	ut_ad(ind->table->comp || n_fields <= rec_get_n_fields_old(rec));
3950 3951 3952 3953 3954
	
	tuple = dtuple_create(heap, n_fields); 

	dict_index_copy_types(tuple, ind, n_fields);

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3955
	rec_copy_prefix_to_dtuple(tuple, rec, ind, n_fields, heap);
3956 3957 3958 3959 3960 3961 3962

	ut_ad(dtuple_check_typed(tuple));

	return(tuple);
}	
	
/*************************************************************************
3963
Calculates the minimum record length in an index. */
3964

3965 3966 3967 3968
ulint
dict_index_calc_min_rec_len(
/*========================*/
	dict_index_t*	index)	/* in: index */
3969
{
3970 3971
	ulint	sum	= 0;
	ulint	i;
3972

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3973
	if (UNIV_LIKELY(index->table->comp)) {
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993
		ulint nullable = 0;
		sum = REC_N_NEW_EXTRA_BYTES;
		for (i = 0; i < dict_index_get_n_fields(index); i++) {
			dtype_t*t = dict_index_get_nth_type(index, i);
			ulint	size = dtype_get_fixed_size(t);
			sum += size;
			if (!size) {
				size = dtype_get_len(t);
				sum += size < 128 ? 1 : 2;
			}
			if (!(dtype_get_prtype(t) & DATA_NOT_NULL))
				nullable++;
		}

		/* round the NULL flags up to full bytes */
		sum += (nullable + 7) / 8;

		return(sum);
	}

3994 3995 3996
	for (i = 0; i < dict_index_get_n_fields(index); i++) {
		sum += dtype_get_fixed_size(dict_index_get_nth_type(index, i));
	}
3997

3998 3999 4000 4001
	if (sum > 127) {
		sum += 2 * dict_index_get_n_fields(index);
	} else {
		sum += dict_index_get_n_fields(index);
4002 4003
	}

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
4004
	sum += REC_N_OLD_EXTRA_BYTES;
4005

4006 4007
	return(sum);
}
4008

4009 4010 4011 4012 4013 4014 4015 4016
/*************************************************************************
Calculates new estimates for table and index statistics. The statistics
are used in query optimization. */

void
dict_update_statistics_low(
/*=======================*/
	dict_table_t*	table,		/* in: table */
4017 4018
	ibool		has_dict_mutex __attribute__((unused)))
                                        /* in: TRUE if the caller has the
4019 4020 4021 4022 4023
					dictionary mutex */	
{
	dict_index_t*	index;
	ulint		size;
	ulint		sum_of_index_sizes	= 0;
4024

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4025 4026 4027
	if (table->ibd_file_missing) {
		ut_print_timestamp(stderr);
		fprintf(stderr,
4028 4029 4030 4031 4032
			"  InnoDB: cannot calculate statistics for table %s\n"
"InnoDB: because the .ibd file is missing.  For help, please refer to\n"
"InnoDB: "
"http://dev.mysql.com/doc/mysql/en/InnoDB_troubleshooting_datadict.html\n",
			table->name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4033 4034 4035 4036

		return;
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4037 4038 4039 4040 4041 4042 4043 4044
	/* If we have set a high innodb_force_recovery level, do not calculate
	statistics, as a badly corrupted index can cause a crash in it. */

	if (srv_force_recovery >= SRV_FORCE_NO_IBUF_MERGE) {

		return;
	}

4045 4046
	/* Find out the sizes of the indexes and how many different values
	for the key they approximately have */
4047 4048 4049

	index = dict_table_get_first_index(table);	

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4050 4051 4052 4053 4054 4055
	if (index == NULL) {
		/* Table definition is corrupt */
	
		return;
	}

4056 4057 4058
	while (index) {
		size = btr_get_size(index, BTR_TOTAL_SIZE);

4059 4060
		index->stat_index_size = size;

4061 4062
		sum_of_index_sizes += size;

4063
		size = btr_get_size(index, BTR_N_LEAF_PAGES);
4064

4065 4066 4067 4068
		if (size == 0) {
			/* The root node of the tree is a leaf */
			size = 1;
		}
4069

4070 4071 4072
		index->stat_n_leaf_pages = size;
		
		btr_estimate_number_of_different_key_vals(index);
4073 4074 4075 4076 4077 4078

		index = dict_table_get_next_index(index);
	}

	index = dict_table_get_first_index(table);

4079 4080 4081
	table->stat_n_rows = index->stat_n_diff_key_vals[
					dict_index_get_n_unique(index)];

4082 4083 4084
	table->stat_clustered_index_size = index->stat_index_size;

	table->stat_sum_of_other_index_sizes = sum_of_index_sizes
4085
						- index->stat_index_size;
4086

4087
	table->stat_initialized = TRUE;
4088

4089
        table->stat_modified_counter = 0;
4090 4091
}

4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113
/*************************************************************************
Calculates new estimates for table and index statistics. The statistics
are used in query optimization. */

void
dict_update_statistics(
/*===================*/
	dict_table_t*	table)	/* in: table */
{
	dict_update_statistics_low(table, FALSE);
}

/**************************************************************************
Prints info of a foreign key constraint. */
static
void
dict_foreign_print_low(
/*===================*/
	dict_foreign_t*	foreign)	/* in: foreign key constraint */
{
	ulint	i;

4114
#ifdef UNIV_SYNC_DEBUG
4115
	ut_ad(mutex_own(&(dict_sys->mutex)));
4116
#endif /* UNIV_SYNC_DEBUG */
4117

4118 4119
	fprintf(stderr, "  FOREIGN KEY CONSTRAINT %s: %s (",
		foreign->id, foreign->foreign_table_name);
4120

4121
	for (i = 0; i < foreign->n_fields; i++) {
4122
		fprintf(stderr, " %s", foreign->foreign_col_names[i]);
4123 4124
	}

4125 4126 4127
	fprintf(stderr, " )\n"
		"             REFERENCES %s (",
		foreign->referenced_table_name);
4128 4129
	
	for (i = 0; i < foreign->n_fields; i++) {
4130
		fprintf(stderr, " %s", foreign->referenced_col_names[i]);
4131 4132
	}

4133
	fputs(" )\n", stderr);
4134 4135
}

4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154
/**************************************************************************
Prints a table data. */

void
dict_table_print(
/*=============*/
	dict_table_t*	table)	/* in: table */
{
	mutex_enter(&(dict_sys->mutex));
	dict_table_print_low(table);
	mutex_exit(&(dict_sys->mutex));
}

/**************************************************************************
Prints a table data when we know the table name. */

void
dict_table_print_by_name(
/*=====================*/
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
4155
	const char*	name)
4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170
{
	dict_table_t*	table;

	mutex_enter(&(dict_sys->mutex));

	table = dict_table_get_low(name);

	ut_a(table);
	
	dict_table_print_low(table);
	mutex_exit(&(dict_sys->mutex));
}

/**************************************************************************
Prints a table data. */
4171

4172 4173 4174 4175 4176 4177
void
dict_table_print_low(
/*=================*/
	dict_table_t*	table)	/* in: table */
{
	dict_index_t*	index;
4178 4179
	dict_foreign_t*	foreign;
	ulint		i;
4180

4181
#ifdef UNIV_SYNC_DEBUG
4182
	ut_ad(mutex_own(&(dict_sys->mutex)));
4183
#endif /* UNIV_SYNC_DEBUG */
4184

4185 4186
	dict_update_statistics_low(table, TRUE);
	
4187
	fprintf(stderr,
4188 4189 4190 4191
"--------------------------------------\n"
"TABLE: name %s, id %lu %lu, columns %lu, indexes %lu, appr.rows %lu\n"
"  COLUMNS: ",
			table->name,
4192 4193 4194 4195 4196
			(ulong) ut_dulint_get_high(table->id),
			(ulong) ut_dulint_get_low(table->id),
			(ulong) table->n_cols,
		        (ulong) UT_LIST_GET_LEN(table->indexes),
			(ulong) table->stat_n_rows);
4197 4198

	for (i = 0; i < table->n_cols - 1; i++) {
4199
		dict_col_print_low(dict_table_get_nth_col(table, i));
4200
		fputs("; ", stderr);
4201 4202
	}

4203
	putc('\n', stderr);
4204

4205 4206 4207 4208 4209 4210
	index = UT_LIST_GET_FIRST(table->indexes);

	while (index != NULL) {
		dict_index_print_low(index);
		index = UT_LIST_GET_NEXT(indexes, index);
	}
4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224

	foreign = UT_LIST_GET_FIRST(table->foreign_list);

	while (foreign != NULL) {
		dict_foreign_print_low(foreign);
		foreign = UT_LIST_GET_NEXT(foreign_list, foreign);
	}

	foreign = UT_LIST_GET_FIRST(table->referenced_list);

	while (foreign != NULL) {
		dict_foreign_print_low(foreign);
		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}
4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236
}

/**************************************************************************
Prints a column data. */
static
void
dict_col_print_low(
/*===============*/
	dict_col_t*	col)	/* in: column */
{
	dtype_t*	type;

4237
#ifdef UNIV_SYNC_DEBUG
4238
	ut_ad(mutex_own(&(dict_sys->mutex)));
4239
#endif /* UNIV_SYNC_DEBUG */
4240 4241

	type = dict_col_get_type(col);
4242
	fprintf(stderr, "%s: ", col->name);
4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255

	dtype_print(type);
}

/**************************************************************************
Prints an index data. */
static
void
dict_index_print_low(
/*=================*/
	dict_index_t*	index)	/* in: index */
{
	dict_tree_t*	tree;
4256 4257
	ib_longlong	n_vals;
	ulint		i;
4258

4259
#ifdef UNIV_SYNC_DEBUG
4260
	ut_ad(mutex_own(&(dict_sys->mutex)));
4261
#endif /* UNIV_SYNC_DEBUG */
4262 4263

	tree = index->tree;
4264 4265 4266 4267 4268 4269 4270 4271

	if (index->n_user_defined_cols > 0) {
		n_vals = index->stat_n_diff_key_vals[
					index->n_user_defined_cols];
	} else {
		n_vals = index->stat_n_diff_key_vals[1];
	}

4272
	fprintf(stderr,
4273
		"  INDEX: name %s, id %lu %lu, fields %lu/%lu, type %lu\n"
4274 4275 4276
		"   root page %lu, appr.key vals %lu,"
		" leaf pages %lu, size pages %lu\n"
		"   FIELDS: ",
4277
		index->name,
monty@mishka.local's avatar
monty@mishka.local committed
4278 4279 4280 4281
		(ulong) ut_dulint_get_high(tree->id),
		(ulong) ut_dulint_get_low(tree->id),
		(ulong) index->n_user_defined_cols,
		(ulong) index->n_fields, (ulong) index->type,
4282 4283 4284 4285
		(ulong) tree->page,
		(ulong) n_vals,
		(ulong) index->stat_n_leaf_pages,
		(ulong) index->stat_index_size);
4286 4287 4288 4289 4290
			
	for (i = 0; i < index->n_fields; i++) {
		dict_field_print_low(dict_index_get_nth_field(index, i));
	}

4291
	putc('\n', stderr);
4292

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
4293 4294
#ifdef UNIV_BTR_PRINT
	btr_print_size(tree);
4295

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
4296 4297
	btr_print_tree(tree, 7);
#endif /* UNIV_BTR_PRINT */
4298 4299 4300 4301 4302 4303 4304 4305 4306 4307
}

/**************************************************************************
Prints a field data. */
static
void
dict_field_print_low(
/*=================*/
	dict_field_t*	field)	/* in: field */
{
4308
#ifdef UNIV_SYNC_DEBUG
4309
	ut_ad(mutex_own(&(dict_sys->mutex)));
4310
#endif /* UNIV_SYNC_DEBUG */
4311
	fprintf(stderr, " %s", field->name);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4312 4313

	if (field->prefix_len != 0) {
monty@mishka.local's avatar
monty@mishka.local committed
4314
		fprintf(stderr, "(%lu)", (ulong) field->prefix_len);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4315
	}
4316
}
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
4317

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4318
/**************************************************************************
4319 4320
Outputs info on a foreign key of a table in a format suitable for
CREATE TABLE. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4321

4322
void
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4323 4324
dict_print_info_on_foreign_key_in_create_format(
/*============================================*/
4325 4326 4327 4328
	FILE*		file,		/* in: file where to print */
	trx_t*		trx,		/* in: transaction */
	dict_foreign_t*	foreign,	/* in: foreign key constraint */
	ibool		add_newline)	/* in: whether to add a newline */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4329
{
4330
	const char*	stripped_id;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4331 4332
	ulint	i;
	
4333
	if (strchr(foreign->id, '/')) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4334 4335 4336 4337 4338 4339 4340
		/* Strip the preceding database name from the constraint id */
		stripped_id = foreign->id + 1
				+ dict_get_db_name_len(foreign->id);
	} else {
		stripped_id = foreign->id;
	}

4341 4342 4343 4344 4345 4346 4347 4348 4349 4350
	putc(',', file);
	
	if (add_newline) {
		/* SHOW CREATE TABLE wants constraints each printed nicely
		on its own line, while error messages want no newlines
		inserted. */
		fputs("\n ", file);
	}
	
	fputs(" CONSTRAINT ", file);
4351
	ut_print_name(file, trx, stripped_id);
4352
	fputs(" FOREIGN KEY (", file);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4353

4354
	for (i = 0;;) {
4355
		ut_print_name(file, trx, foreign->foreign_col_names[i]);
4356 4357 4358 4359
		if (++i < foreign->n_fields) {
			fputs(", ", file);
	        } else {
			break;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4360 4361 4362
		}
	}

4363 4364
	fputs(") REFERENCES ", file);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4365 4366
	if (dict_tables_have_same_db(foreign->foreign_table_name,
					foreign->referenced_table_name)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4367
		/* Do not print the database name of the referenced table */
4368
		ut_print_name(file, trx, dict_remove_db_name(
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4369 4370
					foreign->referenced_table_name));
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4371
		/* Look for the '/' in the table name */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4372

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4373 4374 4375 4376 4377
		i = 0;
		while (foreign->referenced_table_name[i] != '/') {
			i++;
		}

4378
		ut_print_namel(file, trx, foreign->referenced_table_name, i);
4379
		putc('.', file);
4380 4381
		ut_print_name(file, trx,
				foreign->referenced_table_name + i + 1);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4382 4383
	}

4384 4385 4386 4387
	putc(' ', file);
	putc('(', file);

	for (i = 0;;) {
4388
		ut_print_name(file, trx, foreign->referenced_col_names[i]);
4389 4390 4391 4392
		if (++i < foreign->n_fields) {
			fputs(", ", file);
		} else {
			break;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4393 4394 4395
		}
	}

4396
	putc(')', file);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4397 4398

	if (foreign->type & DICT_FOREIGN_ON_DELETE_CASCADE) {
4399
		fputs(" ON DELETE CASCADE", file);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4400 4401 4402
	}
	
	if (foreign->type & DICT_FOREIGN_ON_DELETE_SET_NULL) {
4403
		fputs(" ON DELETE SET NULL", file);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4404 4405 4406
	}

	if (foreign->type & DICT_FOREIGN_ON_DELETE_NO_ACTION) {
4407
		fputs(" ON DELETE NO ACTION", file);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4408 4409 4410
	}

	if (foreign->type & DICT_FOREIGN_ON_UPDATE_CASCADE) {
4411
		fputs(" ON UPDATE CASCADE", file);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4412 4413 4414
	}
	
	if (foreign->type & DICT_FOREIGN_ON_UPDATE_SET_NULL) {
4415
		fputs(" ON UPDATE SET NULL", file);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4416 4417 4418
	}

	if (foreign->type & DICT_FOREIGN_ON_UPDATE_NO_ACTION) {
4419
		fputs(" ON UPDATE NO ACTION", file);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4420 4421 4422
	}
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4423
/**************************************************************************
4424
Outputs info on foreign keys of a table. */
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
4425 4426 4427 4428

void
dict_print_info_on_foreign_keys(
/*============================*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4429 4430 4431 4432
	ibool		create_table_format, /* in: if TRUE then print in
				a format suitable to be inserted into
				a CREATE TABLE, otherwise in the format
				of SHOW TABLE STATUS */
4433
	FILE*		file,	/* in: file where to print */
4434
	trx_t*		trx,	/* in: transaction */
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
4435 4436 4437
	dict_table_t*	table)	/* in: table */
{
	dict_foreign_t*	foreign;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4438

monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449
	mutex_enter(&(dict_sys->mutex));

	foreign = UT_LIST_GET_FIRST(table->foreign_list);

	if (foreign == NULL) {
		mutex_exit(&(dict_sys->mutex));

		return;
	}

	while (foreign != NULL) {
4450 4451
		if (create_table_format) {
			dict_print_info_on_foreign_key_in_create_format(
4452
						file, trx, foreign, TRUE);
4453 4454 4455
		} else {
			ulint	i;
			fputs("; (", file);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4456

4457 4458 4459 4460
			for (i = 0; i < foreign->n_fields; i++) {
				if (i) {
					putc(' ', file);
				}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4461

4462
				ut_print_name(file, trx,
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
4463 4464 4465
					foreign->foreign_col_names[i]);
			}

4466
			fputs(") REFER ", file);
4467 4468
			ut_print_name(file, trx,
					foreign->referenced_table_name);
4469 4470 4471 4472 4473 4474
			putc('(', file);

			for (i = 0; i < foreign->n_fields; i++) {
				if (i) {
					putc(' ', file);
				}
4475
				ut_print_name(file, trx,
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
4476 4477 4478
					foreign->referenced_col_names[i]);
			}

4479
			putc(')', file);
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
4480

4481 4482 4483
			if (foreign->type == DICT_FOREIGN_ON_DELETE_CASCADE) {
				fputs(" ON DELETE CASCADE", file);
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4484
	
4485 4486 4487
			if (foreign->type == DICT_FOREIGN_ON_DELETE_SET_NULL) {
				fputs(" ON DELETE SET NULL", file);
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4488

4489 4490 4491
			if (foreign->type & DICT_FOREIGN_ON_DELETE_NO_ACTION) {
				fputs(" ON DELETE NO ACTION", file);
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4492

4493 4494 4495
			if (foreign->type & DICT_FOREIGN_ON_UPDATE_CASCADE) {
				fputs(" ON UPDATE CASCADE", file);
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4496
	
4497 4498 4499
			if (foreign->type & DICT_FOREIGN_ON_UPDATE_SET_NULL) {
				fputs(" ON UPDATE SET NULL", file);
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4500

4501 4502 4503
			if (foreign->type & DICT_FOREIGN_ON_UPDATE_NO_ACTION) {
				fputs(" ON UPDATE NO ACTION", file);
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4504 4505
		}

monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
4506 4507 4508
		foreign = UT_LIST_GET_NEXT(foreign_list, foreign);
	}

4509 4510
	mutex_exit(&(dict_sys->mutex));
}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4511

4512 4513 4514 4515 4516 4517
/************************************************************************
Displays the names of the index and the table. */
void
dict_index_name_print(
/*==================*/
	FILE*			file,	/* in: output stream */
4518
	trx_t*			trx,	/* in: transaction */
4519 4520 4521
	const dict_index_t*	index)	/* in: index to print */
{
	fputs("index ", file);
4522
	ut_print_name(file, trx, index->name);
4523
	fputs(" of table ", file);
4524
	ut_print_name(file, trx, index->table_name);
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
4525
}