dict0dict.c 106 KB
Newer Older
osku's avatar
osku committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/**********************************************************************
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"
#include "dict0crea.h"
#include "trx0undo.h"
#include "btr0btr.h"
#include "btr0cur.h"
#include "btr0sea.h"
#include "pars0pars.h"
#include "pars0sym.h"
#include "que0que.h"
#include "rem0cmp.h"
29 30 31
#ifndef UNIV_HOTBACKUP
# include "m_ctype.h" /* my_isspace() */
#endif /* !UNIV_HOTBACKUP */
osku's avatar
osku committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

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

rw_lock_t	dict_operation_lock;	/* table create, drop, etc. reserve
					this in X-mode; implicit or backround
					operations purge, rollback, foreign
					key checks reserve this in S-mode; we
					cannot trust that MySQL protects
					implicit or background operations
					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 */

#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_VARYING	4	/* buffer pool max size per data
					dictionary varying size in bytes */

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

#ifndef UNIV_HOTBACKUP
/**********************************************************************
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
Converts an identifier to a table name.

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_convert_from_table_id(
/*===========================*/
	char*		to,	/* out: converted identifier */
	const char*	from,	/* in: identifier to convert */
	ulint		len);	/* in: length of 'to', in bytes;
				should be at least 5 * strlen(to) + 1 */
/**********************************************************************
Converts an identifier to UTF-8.

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_convert_from_id(
/*=====================*/
	char*		to,	/* out: converted identifier */
	const char*	from,	/* in: identifier to convert */
	ulint		len);	/* in: length of 'to', in bytes;
				should be at least 3 * strlen(to) + 1 */
/**********************************************************************
Removes the filename encoding of a table or database name.

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_convert_from_filename(
/*===========================*/
	char*		s);	/* in: identifier; out: decoded identifier */
/**********************************************************************
osku's avatar
osku committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
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 */
117 118 119 120 121 122 123 124 125 126 127

/**************************************************************************
Determines the connection character set.

NOTE: the prototype of this function is copied from ha_innodb.cc! If you change
this function, you MUST change also the prototype here! */
struct charset_info_st*
innobase_get_charset(
/*=================*/
				/* out: connection character set */
	void*	mysql_thd);	/* in: MySQL thread handle */
osku's avatar
osku committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
#endif /* !UNIV_HOTBACKUP */

/**************************************************************************
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 */
146
	dict_table_t*	table,	/* in: table */
osku's avatar
osku committed
147 148 149
	ulint		start,	/* in: first position to copy */
	ulint		end);	/* in: last position to copy */
/***********************************************************************
150 151
Tries to find column names for the index and sets the col field of the
index. */
osku's avatar
osku committed
152
static
153
void
osku's avatar
osku committed
154 155 156
dict_index_find_cols(
/*=================*/
	dict_table_t*	table,	/* in: table */
157
	dict_index_t*	index);	/* in: index */
osku's avatar
osku committed
158 159 160 161 162 163 164 165 166 167 168
/***********************************************************************
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
169
				index */
osku's avatar
osku committed
170 171 172 173 174 175 176 177 178 179 180
/***********************************************************************
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
181
				index */
osku's avatar
osku committed
182 183 184 185 186 187 188 189 190 191 192 193 194
/**************************************************************************
Removes a foreign constraint struct from the dictionary cache. */
static
void
dict_foreign_remove_from_cache(
/*===========================*/
	dict_foreign_t*	foreign);	/* in, own: foreign constraint */
/**************************************************************************
Prints a column data. */
static
void
dict_col_print_low(
/*===============*/
195 196
	const dict_table_t*	table,	/* in: table */
	const dict_col_t*	col);	/* in: column */
osku's avatar
osku committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
/**************************************************************************
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 */
/*************************************************************************
Frees a foreign key struct. */
static
void
dict_foreign_free(
/*==============*/
	dict_foreign_t*	foreign);	/* in, own: foreign key struct */

/* Stream for storing detailed information about the latest foreign key
and unique key errors */
FILE*	dict_foreign_err_file		= NULL;
222
mutex_t	dict_foreign_err_mutex;		/* mutex protecting the foreign
osku's avatar
osku committed
223
					and unique error buffers */
marko's avatar
marko committed
224 225

#ifndef UNIV_HOTBACKUP
osku's avatar
osku committed
226 227 228 229 230 231 232 233 234 235
/**********************************************************************
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);
}
marko's avatar
marko committed
236
#endif /* !UNIV_HOTBACKUP */
osku's avatar
osku committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

/************************************************************************
Checks if the database name in two table names is the same. */

ibool
dict_tables_have_same_db(
/*=====================*/
				/* 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 */
{
	for (; *name1 == *name2; name1++, name2++) {
		if (*name1 == '/') {
			return(TRUE);
		}
		ut_a(*name1); /* the names must contain '/' */
	}
	return(FALSE);
}

/************************************************************************
Return the end of table name where we have removed dbname and '/'. */
osku's avatar
osku committed
261

osku's avatar
osku committed
262 263 264 265 266 267 268
const char*
dict_remove_db_name(
/*================*/
				/* out: table name */
	const char*	name)	/* in: table name in the form
				dbname '/' tablename */
{
269
	const char*	s = strchr(name, '/');
osku's avatar
osku committed
270
	ut_a(s);
271 272

	return(s + 1);
osku's avatar
osku committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
}

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

ulint
dict_get_db_name_len(
/*=================*/
				/* out: database name length */
	const char*	name)	/* in: table name in the form
				dbname '/' tablename */
{
	const char*	s;
	s = strchr(name, '/');
	ut_a(s);
	return(s - name);
}
290

osku's avatar
osku committed
291 292 293 294 295 296 297 298 299
/************************************************************************
Reserves the dictionary system mutex for MySQL. */

void
dict_mutex_enter_for_mysql(void)
/*============================*/
{
	mutex_enter(&(dict_sys->mutex));
}
300

osku's avatar
osku committed
301 302 303 304 305 306 307 308 309
/************************************************************************
Releases the dictionary system mutex for MySQL. */

void
dict_mutex_exit_for_mysql(void)
/*===========================*/
{
	mutex_exit(&(dict_sys->mutex));
}
310

osku's avatar
osku committed
311 312 313 314 315 316 317 318 319 320 321 322 323
/************************************************************************
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--;
324

osku's avatar
osku committed
325 326 327
	mutex_exit(&(dict_sys->mutex));
}

328 329 330 331 332 333 334 335 336
/*************************************************************************
Gets the column data type. */

void
dict_col_copy_type_noninline(
/*=========================*/
	const dict_col_t*	col,	/* in: column */
	dtype_t*		type)	/* out: data type */
{
marko's avatar
marko committed
337
	dict_col_copy_type(col, type);
338 339
}

osku's avatar
osku committed
340 341 342
/************************************************************************
Gets the nth column of a table. */

343
const dict_col_t*
osku's avatar
osku committed
344 345
dict_table_get_nth_col_noninline(
/*=============================*/
346 347 348
					/* out: pointer to column object */
	const dict_table_t*	table,	/* in: table */
	ulint			pos)	/* in: position of column */
osku's avatar
osku committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
{
	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 */
	const char*	name)	/* in: index name */
{
	return(dict_table_get_index(table, name));
}
389

390 391 392 393 394 395
/**************************************************************************
Returns a column's name. */

const char*
dict_table_get_col_name(
/*====================*/
396
					/* out: column name. NOTE: not
397 398 399
					guaranteed to stay valid if table is
					modified in any way (columns added,
					etc.). */
400
	const dict_table_t*	table,	/* in: table */
401
	ulint			col_nr)	/* in: column number */
402
{
403 404 405
	ulint		i;
	const char*	s;

406
	ut_ad(table);
407
	ut_ad(col_nr < table->n_def);
408 409
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);

410 411 412 413 414 415 416
	s = table->col_names;

	for (i = 0; i < col_nr; i++) {
		s += strlen(s) + 1;
	}

	return(s);
417 418
}

osku's avatar
osku committed
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
/************************************************************************
Initializes the autoinc counter. It is not an error to initialize an already
initialized counter. */

void
dict_table_autoinc_initialize(
/*==========================*/
	dict_table_t*	table,	/* in: table */
	ib_longlong	value)	/* in: next value to assign to a row */
{
	mutex_enter(&(table->autoinc_mutex));

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

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

/************************************************************************
Gets the next autoinc value (== autoinc counter value), 0 if not yet
initialized. If initialized, increments the counter by 1. */

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;
		table->autoinc = table->autoinc + 1;
	}
458

osku's avatar
osku committed
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
	mutex_exit(&(table->autoinc_mutex));

	return(value);
}

/************************************************************************
Decrements the autoinc counter value by 1. */

void
dict_table_autoinc_decrement(
/*=========================*/
	dict_table_t*	table)	/* in: table */
{
	mutex_enter(&(table->autoinc_mutex));

	table->autoinc = table->autoinc - 1;
475

osku's avatar
osku committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
	mutex_exit(&(table->autoinc_mutex));
}

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

osku's avatar
osku committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
	mutex_exit(&(table->autoinc_mutex));

	return(value);
}

/************************************************************************
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
current value. If not inited, does nothing. */

void
dict_table_autoinc_update(
/*======================*/

	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) {
		if (value >= table->autoinc) {
			table->autoinc = value + 1;
		}
544
	}
osku's avatar
osku committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560

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

/************************************************************************
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 */
{
561 562 563 564
	const dict_field_t*	field;
	const dict_col_t*	col;
	ulint			pos;
	ulint			n_fields;
565

osku's avatar
osku committed
566 567 568 569 570 571 572
	ut_ad(index);
	ut_ad(index->magic_n == DICT_INDEX_MAGIC_N);

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

	if (index->type & DICT_CLUSTERED) {

marko's avatar
marko committed
573
		return(dict_col_get_clust_pos(col, index));
osku's avatar
osku committed
574 575 576
	}

	n_fields = dict_index_get_n_fields(index);
577

osku's avatar
osku committed
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
	for (pos = 0; pos < n_fields; pos++) {
		field = dict_index_get_nth_field(index, pos);

		if (col == field->col && field->prefix_len == 0) {

			return(pos);
		}
	}

	return(ULINT_UNDEFINED);
}

/************************************************************************
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 */
{
601 602 603 604
	const dict_field_t*	field;
	const dict_col_t*	col;
	ulint			pos;
	ulint			n_fields;
605

osku's avatar
osku committed
606 607 608 609 610 611 612 613 614 615 616
	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);
617

osku's avatar
osku committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
	for (pos = 0; pos < n_fields; pos++) {
		field = dict_index_get_nth_field(index, pos);

		if (col == field->col) {

			return(TRUE);
		}
	}

	return(FALSE);
}

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

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

osku's avatar
osku committed
651 652 653 654 655 656
	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);
657

osku's avatar
osku committed
658 659 660 661
	for (pos = 0; pos < n_fields; pos++) {
		field = dict_index_get_nth_field(index, pos);

		if (field->col == field2->col
662
		    && (field->prefix_len == 0
osku's avatar
osku committed
663
			|| (field->prefix_len >= field2->prefix_len
664
			    && field2->prefix_len != 0))) {
osku's avatar
osku committed
665 666 667 668 669 670 671 672 673

			return(pos);
		}
	}

	return(ULINT_UNDEFINED);
}

/**************************************************************************
674
Returns a table object based on table id. */
osku's avatar
osku committed
675 676 677 678 679 680 681 682 683

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

osku's avatar
osku committed
685
	if (ut_dulint_cmp(table_id, DICT_FIELDS_ID) <= 0
686
	    || trx->dict_operation_lock_mode == RW_X_LATCH) {
osku's avatar
osku committed
687 688 689 690 691 692 693
		/* 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! */

		ut_ad(mutex_own(&(dict_sys->mutex)));

694
		return(dict_table_get_on_id_low(table_id));
osku's avatar
osku committed
695 696 697 698
	}

	mutex_enter(&(dict_sys->mutex));

699
	table = dict_table_get_on_id_low(table_id);
700

osku's avatar
osku committed
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
	mutex_exit(&(dict_sys->mutex));

	return(table);
}

/************************************************************************
Looks for column n position in the clustered index. */

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),
718
					  n));
osku's avatar
osku committed
719 720
}

721 722 723 724 725 726 727 728 729 730 731 732 733
/************************************************************************
Check whether the table uses the compact page format. */

ibool
dict_table_is_comp_noninline(
/*=========================*/
					/* out: TRUE if table uses the
					compact page format */
	const dict_table_t*	table)	/* in: table */
{
	return(dict_table_is_comp(table));
}

osku's avatar
osku committed
734 735 736 737 738 739 740 741 742 743 744 745
/************************************************************************
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 */
{
746 747 748 749 750
	dict_index_t*		index;
	const dict_field_t*	field;
	const dict_col_t*	col;
	ulint			pos;
	ulint			n_fields;
751

osku's avatar
osku committed
752 753 754 755 756 757 758
	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);
759

osku's avatar
osku committed
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
	for (pos = 0; pos < n_fields; pos++) {
		field = dict_index_get_nth_field(index, pos);

		if (col == field->col) {

			return(TRUE);
		}
	}

	return(FALSE);
}

/**************************************************************************
Inits the data dictionary module. */

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

781
	mutex_create(&dict_sys->mutex, SYNC_DICT);
osku's avatar
osku committed
782

783 784 785 786 787 788
	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));
osku's avatar
osku committed
789 790 791 792
	dict_sys->size = 0;

	UT_LIST_INIT(dict_sys->table_LRU);

793
	rw_lock_create(&dict_operation_lock, SYNC_DICT_OPERATION);
osku's avatar
osku committed
794 795 796

	dict_foreign_err_file = os_file_create_tmpfile();
	ut_a(dict_foreign_err_file);
797

798
	mutex_create(&dict_foreign_err_mutex, SYNC_ANY_LATCH);
osku's avatar
osku committed
799 800 801
}

/**************************************************************************
802 803 804 805
Returns a table object and optionally increment its MySQL open handle count.
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. */
osku's avatar
osku committed
806 807 808 809 810 811

dict_table_t*
dict_table_get(
/*===========*/
					/* out: table, NULL if
					does not exist */
812 813 814 815
	const char*	table_name,	/* in: table name */
	ibool		inc_mysql_count)
     					/* in: whether to increment the open
					handle count on the table */
osku's avatar
osku committed
816 817 818 819
{
	dict_table_t*	table;

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

osku's avatar
osku committed
821 822
	table = dict_table_get_low(table_name);

823
	if (inc_mysql_count && table) {
824
		table->n_mysql_handles_opened++;
osku's avatar
osku committed
825 826 827 828 829
	}

	mutex_exit(&(dict_sys->mutex));

	if (table != NULL) {
830 831 832 833
		if (!table->stat_initialized) {
			/* If table->ibd_file_missing == TRUE, this will
			print an error message and return without doing
			anything. */
osku's avatar
osku committed
834 835 836
			dict_update_statistics(table);
		}
	}
837

osku's avatar
osku committed
838 839 840 841 842 843 844 845 846 847 848 849 850 851
	return(table);
}

/**************************************************************************
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;
osku's avatar
osku committed
852
	ulint	row_len;
853

osku's avatar
osku committed
854 855 856 857 858
	ut_ad(table);
	ut_ad(mutex_own(&(dict_sys->mutex)));
	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);
859

osku's avatar
osku committed
860 861
	fold = ut_fold_string(table->name);
	id_fold = ut_fold_dulint(table->id);
862

osku's avatar
osku committed
863
	table->cached = TRUE;
864

osku's avatar
osku committed
865 866 867 868 869 870 871
	/* 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. */

	dict_mem_table_add_col(table, "DB_ROW_ID", DATA_SYS,
872
			       DATA_ROW_ID | DATA_NOT_NULL,
873
			       DATA_ROW_ID_LEN);
osku's avatar
osku committed
874 875 876 877
#if DATA_ROW_ID != 0
#error "DATA_ROW_ID != 0"
#endif
	dict_mem_table_add_col(table, "DB_TRX_ID", DATA_SYS,
878
			       DATA_TRX_ID | DATA_NOT_NULL,
879
			       DATA_TRX_ID_LEN);
osku's avatar
osku committed
880 881 882 883
#if DATA_TRX_ID != 1
#error "DATA_TRX_ID != 1"
#endif
	dict_mem_table_add_col(table, "DB_ROLL_PTR", DATA_SYS,
884
			       DATA_ROLL_PTR | DATA_NOT_NULL,
885
			       DATA_ROLL_PTR_LEN);
osku's avatar
osku committed
886 887 888 889 890
#if DATA_ROLL_PTR != 2
#error "DATA_ROLL_PTR != 2"
#endif

	/* This check reminds that if a new system column is added to
891
	the program, it should be dealt with here */
892 893
#if DATA_N_SYS_COLS != 3
#error "DATA_N_SYS_COLS != 3"
osku's avatar
osku committed
894 895
#endif

896
	/* The lower limit for what we consider a "big" row */
897 898
#define BIG_ROW_SIZE 1024

osku's avatar
osku committed
899 900
	row_len = 0;
	for (i = 0; i < table->n_def; i++) {
901 902
		ulint	col_len = dict_col_get_max_size(
			dict_table_get_nth_col(table, i));
osku's avatar
osku committed
903

904 905
		row_len += col_len;

osku's avatar
osku committed
906
		/* If we have a single unbounded field, or several gigantic
907 908 909
		fields, mark the maximum row size as BIG_ROW_SIZE. */
		if (row_len >= BIG_ROW_SIZE || col_len >= BIG_ROW_SIZE) {
			row_len = BIG_ROW_SIZE;
osku's avatar
osku committed
910 911 912 913 914

			break;
		}
	}

915
	table->big_rows = row_len >= BIG_ROW_SIZE;
osku's avatar
osku committed
916

osku's avatar
osku committed
917 918 919 920
	/* 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,
921
			    (ut_strcmp(table2->name, table->name) == 0));
osku's avatar
osku committed
922 923 924 925 926 927 928
		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,
929
			    (ut_dulint_cmp(table2->id, table->id) == 0));
osku's avatar
osku committed
930 931 932 933 934
		ut_a(table2 == NULL);
	}

	/* Add table to hash table of tables */
	HASH_INSERT(dict_table_t, name_hash, dict_sys->table_hash, fold,
935
		    table);
osku's avatar
osku committed
936 937 938

	/* 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,
939
		    table);
osku's avatar
osku committed
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
	/* Add table to LRU list of tables */
	UT_LIST_ADD_FIRST(table_LRU, dict_sys->table_LRU, table);

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

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

osku's avatar
osku committed
960 961 962 963 964 965
	table = UT_LIST_GET_FIRST(dict_sys->table_LRU);

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

		while (index) {
966
			if (0 == ut_dulint_cmp(id, index->id)) {
osku's avatar
osku committed
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
				/* Found */

				return(index);
			}

			index = dict_table_get_next_index(index);
		}

		table = UT_LIST_GET_NEXT(table_LRU, table);
	}

	return(NULL);
}

/**************************************************************************
Renames a table object. */

ibool
dict_table_rename_in_cache(
/*=======================*/
					/* out: TRUE if success */
	dict_table_t*	table,		/* in: table */
	const char*	new_name,	/* in: new name */
	ibool		rename_also_foreigns)/* in: in ALTER TABLE we want
					to preserve the original table name
					in constraints which reference it */
{
	dict_foreign_t*	foreign;
	dict_index_t*	index;
	ulint		fold;
	ulint		old_size;
	char*		old_name;
	ibool		success;
1000

osku's avatar
osku committed
1001 1002 1003 1004
	ut_ad(table);
	ut_ad(mutex_own(&(dict_sys->mutex)));

	old_size = mem_heap_get_size(table->heap);
1005

osku's avatar
osku committed
1006
	fold = ut_fold_string(new_name);
1007

osku's avatar
osku committed
1008 1009 1010 1011
	/* 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,
1012
			    (ut_strcmp(table2->name, new_name) == 0));
osku's avatar
osku committed
1013 1014
		if (table2) {
			fprintf(stderr,
1015 1016
				"InnoDB: Error: dictionary cache"
				" already contains a table of name %s\n",
1017
				new_name);
osku's avatar
osku committed
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
			return(FALSE);
		}
	}

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

	if (table->space != 0) {
		if (table->dir_path_of_temp_table != NULL) {
			fprintf(stderr,
1028 1029 1030 1031
				"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);
osku's avatar
osku committed
1032 1033
			success = FALSE;
		} else {
1034 1035
			success = fil_rename_tablespace(
				table->name, table->space, new_name);
osku's avatar
osku committed
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
		}

		if (!success) {

			return(FALSE);
		}
	}

	/* Remove table from the hash tables of tables */
	HASH_DELETE(dict_table_t, name_hash, dict_sys->table_hash,
1046
		    ut_fold_string(table->name), table);
osku's avatar
osku committed
1047 1048 1049 1050 1051
	old_name = mem_heap_strdup(table->heap, table->name);
	table->name = mem_heap_strdup(table->heap, new_name);

	/* Add table to hash table of tables */
	HASH_INSERT(dict_table_t, name_hash, dict_sys->table_hash, fold,
1052
		    table);
osku's avatar
osku committed
1053 1054 1055 1056 1057 1058 1059
	dict_sys->size += (mem_heap_get_size(table->heap) - old_size);

	/* Update the table_name field in indexes */
	index = dict_table_get_first_index(table);

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

osku's avatar
osku committed
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
		index = dict_table_get_next_index(index);
	}

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

osku's avatar
osku committed
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
		/* 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;
1088

osku's avatar
osku committed
1089 1090 1091 1092 1093 1094
			foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
		}

		/* Make the list of referencing constraints empty */

		UT_LIST_INIT(table->referenced_list);
1095

osku's avatar
osku committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
		return(TRUE);
	}

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

	foreign = UT_LIST_GET_FIRST(table->foreign_list);

	while (foreign != NULL) {
1106 1107
		if (ut_strlen(foreign->foreign_table_name)
		    < ut_strlen(table->name)) {
osku's avatar
osku committed
1108 1109 1110
			/* Allocate a longer name buffer;
			TODO: store buf len to save memory */

1111 1112 1113
			foreign->foreign_table_name
				= mem_heap_alloc(foreign->heap,
						 ut_strlen(table->name) + 1);
osku's avatar
osku committed
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
		}

		strcpy(foreign->foreign_table_name, table->name);

		if (strchr(foreign->id, '/')) {
			ulint	db_len;
			char*	old_id;

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

			old_id = mem_strdup(foreign->id);

			if (ut_strlen(foreign->id) > ut_strlen(old_name)
1127 1128 1129 1130 1131
			    + ((sizeof dict_ibfk) - 1)
			    && !memcmp(foreign->id, old_name,
				       ut_strlen(old_name))
			    && !memcmp(foreign->id + ut_strlen(old_name),
				       dict_ibfk, (sizeof dict_ibfk) - 1)) {
osku's avatar
osku committed
1132 1133 1134

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

1135
				if (strlen(table->name) > strlen(old_name)) {
1136 1137 1138 1139
					foreign->id = mem_heap_alloc(
						foreign->heap,
						strlen(table->name)
						+ strlen(old_id) + 1);
osku's avatar
osku committed
1140
				}
1141

osku's avatar
osku committed
1142 1143 1144 1145
				/* Replace the prefix 'databasename/tablename'
				with the new names */
				strcpy(foreign->id, table->name);
				strcat(foreign->id,
1146
				       old_id + ut_strlen(old_name));
osku's avatar
osku committed
1147 1148 1149 1150 1151 1152
			} 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)
1153
				    > dict_get_db_name_len(foreign->id)) {
osku's avatar
osku committed
1154

1155 1156 1157
					foreign->id = mem_heap_alloc(
						foreign->heap,
						db_len + strlen(old_id) + 1);
osku's avatar
osku committed
1158 1159 1160 1161
				}

				/* Replace the database prefix in id with the
				one from table->name */
1162

osku's avatar
osku committed
1163 1164 1165
				ut_memcpy(foreign->id, table->name, db_len);

				strcpy(foreign->id + db_len,
1166
				       dict_remove_db_name(old_id));
osku's avatar
osku committed
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
			}

			mem_free(old_id);
		}

		foreign = UT_LIST_GET_NEXT(foreign_list, foreign);
	}

	foreign = UT_LIST_GET_FIRST(table->referenced_list);

	while (foreign != NULL) {
1178 1179
		if (ut_strlen(foreign->referenced_table_name)
		    < ut_strlen(table->name)) {
osku's avatar
osku committed
1180 1181 1182
			/* Allocate a longer name buffer;
			TODO: store buf len to save memory */

1183 1184
			foreign->referenced_table_name = mem_heap_alloc(
				foreign->heap, strlen(table->name) + 1);
osku's avatar
osku committed
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
		}

		strcpy(foreign->referenced_table_name, table->name);

		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}

	return(TRUE);
}

/**************************************************************************
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);
	ut_ad(mutex_own(&(dict_sys->mutex)));
	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,
1212
		    ut_fold_dulint(table->id), table);
osku's avatar
osku committed
1213 1214 1215 1216
	table->id = new_id;

	/* Add the table back to the hash table */
	HASH_INSERT(dict_table_t, id_hash, dict_sys->table_id_hash,
1217
		    ut_fold_dulint(table->id), table);
osku's avatar
osku committed
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
}

/**************************************************************************
Removes a table object from the dictionary cache. */

void
dict_table_remove_from_cache(
/*=========================*/
	dict_table_t*	table)	/* in, own: table */
{
	dict_foreign_t*	foreign;
	dict_index_t*	index;
	ulint		size;
1231

osku's avatar
osku committed
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
	ut_ad(table);
	ut_ad(mutex_own(&(dict_sys->mutex)));
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);

#if 0
	fputs("Removing table ", stderr);
	ut_print_name(stderr, table->name, ULINT_UNDEFINED);
	fputs(" from dictionary cache\n", stderr);
#endif

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

osku's avatar
osku committed
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
	}

	/* 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 table from the hash tables of tables */
	HASH_DELETE(dict_table_t, name_hash, dict_sys->table_hash,
1271
		    ut_fold_string(table->name), table);
osku's avatar
osku committed
1272
	HASH_DELETE(dict_table_t, id_hash, dict_sys->table_id_hash,
1273
		    ut_fold_dulint(table->id), table);
osku's avatar
osku committed
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283

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

	size = mem_heap_get_size(table->heap);

	ut_ad(dict_sys->size >= size);

	dict_sys->size -= size;

1284
	dict_mem_table_free(table);
osku's avatar
osku committed
1285 1286
}

1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
/*************************************************************************
Gets the column position in the clustered index. */

ulint
dict_col_get_clust_pos_noninline(
/*=============================*/
	const dict_col_t*	col,		/* in: table column */
	const dict_index_t*	clust_index)	/* in: clustered index */
{
	return(dict_col_get_clust_pos(col, clust_index));
}

1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
/********************************************************************
If the given column name is reserved for InnoDB system columns, return
TRUE. */

ibool
dict_col_name_is_reserved(
/*======================*/
				/* out: TRUE if name is reserved */
	const char*	name)	/* in: column name */
{
	/* This check reminds that if a new system column is added to
	the program, it should be dealt with here. */
1311 1312
#if DATA_N_SYS_COLS != 3
#error "DATA_N_SYS_COLS != 3"
1313 1314 1315
#endif

	static const char*	reserved_names[] = {
1316
		"DB_ROW_ID", "DB_TRX_ID", "DB_ROLL_PTR"
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
	};

	ulint			i;

	for (i = 0; i < UT_ARR_SIZE(reserved_names); i++) {
		if (strcmp(name, reserved_names[i]) == 0) {

			return(TRUE);
		}
	}

	return(FALSE);
}

osku's avatar
osku committed
1331 1332 1333
/**************************************************************************
Adds an index to the dictionary cache. */

1334
void
osku's avatar
osku committed
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
dict_index_add_to_cache(
/*====================*/
	dict_table_t*	table,	/* in: table on which the index is */
	dict_index_t*	index,	/* in, own: index; NOTE! The index memory
				object is freed in this function! */
	ulint		page_no)/* in: root page number of the index */
{
	dict_index_t*	new_index;
	ulint		n_ord;
	ulint		i;
1345

osku's avatar
osku committed
1346 1347 1348 1349
	ut_ad(index);
	ut_ad(mutex_own(&(dict_sys->mutex)));
	ut_ad(index->n_def == index->n_fields);
	ut_ad(index->magic_n == DICT_INDEX_MAGIC_N);
1350

osku's avatar
osku committed
1351 1352
	ut_ad(mem_heap_validate(index->heap));

1353
#ifdef UNIV_DEBUG
osku's avatar
osku committed
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
	{
		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);
		}
	}
1364 1365 1366
#endif /* UNIV_DEBUG */

	ut_a(!(index->type & DICT_CLUSTERED)
1367
	     || UT_LIST_GET_LEN(table->indexes) == 0);
osku's avatar
osku committed
1368

1369
	dict_index_find_cols(table, index);
1370

osku's avatar
osku committed
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
	/* 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);
1381

osku's avatar
osku committed
1382 1383 1384 1385
	/* 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;
1386

osku's avatar
osku committed
1387 1388
	/* Add the new index as the last index for the table */

1389
	UT_LIST_ADD_LAST(indexes, table->indexes, new_index);
osku's avatar
osku committed
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
	new_index->table = table;
	new_index->table_name = table->name;

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

	if (UNIV_UNLIKELY(index->type & DICT_UNIVERSAL)) {
		n_ord = new_index->n_fields;
	} else {
		n_ord = dict_index_get_n_unique(new_index);
	}

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

1403
		dict_index_get_nth_field(new_index, i)->col->ord_part = 1;
osku's avatar
osku committed
1404 1405
	}

1406 1407
	new_index->page = page_no;
	rw_lock_create(&new_index->lock, SYNC_INDEX_TREE);
osku's avatar
osku committed
1408 1409 1410

	if (!UNIV_UNLIKELY(new_index->type & DICT_UNIVERSAL)) {

1411 1412 1413 1414
		new_index->stat_n_diff_key_vals = mem_heap_alloc(
			new_index->heap,
			(1 + dict_index_get_n_unique(new_index))
			* sizeof(ib_longlong));
osku's avatar
osku committed
1415 1416 1417 1418 1419 1420 1421 1422
		/* 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;
		}
	}
1423

osku's avatar
osku committed
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
	dict_sys->size += mem_heap_get_size(new_index->heap);

	dict_mem_index_free(index);
}

/**************************************************************************
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 */
{
	ulint		size;

	ut_ad(table && index);
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);
	ut_ad(index->magic_n == DICT_INDEX_MAGIC_N);
	ut_ad(mutex_own(&(dict_sys->mutex)));

1445
	rw_lock_free(&index->lock);
osku's avatar
osku committed
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455

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

1456
	dict_mem_index_free(index);
osku's avatar
osku committed
1457 1458 1459
}

/***********************************************************************
1460 1461
Tries to find column names for the index and sets the col field of the
index. */
osku's avatar
osku committed
1462
static
1463
void
osku's avatar
osku committed
1464 1465 1466
dict_index_find_cols(
/*=================*/
	dict_table_t*	table,	/* in: table */
1467
	dict_index_t*	index)	/* in: index */
osku's avatar
osku committed
1468 1469
{
	ulint		i;
1470

osku's avatar
osku committed
1471 1472 1473 1474 1475
	ut_ad(table && index);
	ut_ad(table->magic_n == DICT_TABLE_MAGIC_N);
	ut_ad(mutex_own(&(dict_sys->mutex)));

	for (i = 0; i < index->n_fields; i++) {
1476 1477 1478 1479
		ulint		j;
		dict_field_t*	field = dict_index_get_nth_field(index, i);

		for (j = 0; j < table->n_cols; j++) {
1480 1481
			if (!strcmp(dict_table_get_col_name(table, j),
				    field->name)) {
1482 1483
				field->col = (dict_col_t*)
					dict_table_get_nth_col(table, j);
1484

1485 1486
				goto found;
			}
osku's avatar
osku committed
1487
		}
1488

1489 1490
		/* It is an error not to find a matching column. */
		ut_error;
osku's avatar
osku committed
1491

1492 1493 1494
	found:
		;
	}
osku's avatar
osku committed
1495
}
1496

osku's avatar
osku committed
1497 1498 1499 1500 1501 1502 1503
/***********************************************************************
Adds a column to index. */

void
dict_index_add_col(
/*===============*/
	dict_index_t*	index,		/* in: index */
1504
	dict_table_t*	table,		/* in: table */
osku's avatar
osku committed
1505 1506 1507 1508
	dict_col_t*	col,		/* in: column */
	ulint		prefix_len)	/* in: column prefix length */
{
	dict_field_t*	field;
1509 1510 1511
	const char*	col_name;

	col_name = dict_table_get_col_name(table, dict_col_get_no(col));
osku's avatar
osku committed
1512

1513
	dict_mem_index_add_field(index, col_name, prefix_len);
osku's avatar
osku committed
1514 1515 1516 1517

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

	field->col = col;
1518
	field->fixed_len = dict_col_get_fixed_size(col);
osku's avatar
osku committed
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531

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

	if (field->fixed_len > DICT_MAX_INDEX_COL_LEN) {
		field->fixed_len = 0;
	}

1532
	if (!(col->prtype & DATA_NOT_NULL)) {
osku's avatar
osku committed
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
		index->n_nullable++;
	}
}

/***********************************************************************
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 */
1545
	dict_table_t*	table,	/* in: table */
osku's avatar
osku committed
1546 1547 1548 1549 1550
	ulint		start,	/* in: first position to copy */
	ulint		end)	/* in: last position to copy */
{
	dict_field_t*	field;
	ulint		i;
1551

osku's avatar
osku committed
1552 1553 1554 1555 1556
	/* Copy fields contained in index2 */

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

		field = dict_index_get_nth_field(index2, i);
1557 1558
		dict_index_add_col(index1, table, field->col,
				   field->prefix_len);
osku's avatar
osku committed
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
	}
}

/***********************************************************************
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 */
{
	ulint		i;

	if (UNIV_UNLIKELY(index->type & DICT_UNIVERSAL)) {
		dtuple_set_types_binary(tuple, n_fields);

		return;
	}

	for (i = 0; i < n_fields; i++) {
1581 1582 1583 1584
		dict_field_t*	ifield;
		dtype_t*	dfield_type;

		ifield = dict_index_get_nth_field(index, i);
osku's avatar
osku committed
1585
		dfield_type = dfield_get_type(dtuple_get_nth_field(tuple, i));
1586
		dict_col_copy_type(dict_field_get_col(ifield), dfield_type);
1587 1588 1589
		if (UNIV_UNLIKELY(ifield->prefix_len)) {
			dfield_type->len = ifield->prefix_len;
		}
osku's avatar
osku committed
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
	}
}

/***********************************************************************
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;
	ulint		i;

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

		dfield_type = dfield_get_type(dtuple_get_nth_field(tuple, i));
1608 1609
		dict_col_copy_type(dict_table_get_nth_col(table, i),
				   dfield_type);
osku's avatar
osku committed
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
	}
}

/***********************************************************************
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
1624
				index */
osku's avatar
osku committed
1625 1626 1627 1628 1629 1630
{
	dict_index_t*	new_index;
	dict_field_t*	field;
	ulint		fixed_size;
	ulint		trx_id_pos;
	ulint		i;
1631
	ibool*		indexed;
osku's avatar
osku committed
1632 1633 1634 1635 1636 1637 1638 1639

	ut_ad(table && index);
	ut_ad(index->type & DICT_CLUSTERED);
	ut_ad(mutex_own(&(dict_sys->mutex)));
	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,
1640 1641 1642
					  index->name, table->space,
					  index->type,
					  index->n_fields + table->n_cols);
osku's avatar
osku committed
1643 1644 1645 1646 1647

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

osku's avatar
osku committed
1649 1650
	new_index->id = index->id;

1651
	/* Copy the fields of index */
1652
	dict_index_copy(new_index, index, table, 0, index->n_fields);
osku's avatar
osku committed
1653 1654 1655 1656

	if (UNIV_UNLIKELY(index->type & DICT_UNIVERSAL)) {
		/* No fixed number of fields determines an entry uniquely */

1657
		new_index->n_uniq = REC_MAX_N_FIELDS;
1658

osku's avatar
osku committed
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
	} 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;

1676 1677 1678 1679 1680 1681 1682 1683 1684
#if DATA_ROW_ID != 0
# error "DATA_ROW_ID != 0"
#endif
#if DATA_TRX_ID != 1
# error "DATA_TRX_ID != 1"
#endif
#if DATA_ROLL_PTR != 2
# error "DATA_ROLL_PTR != 2"
#endif
osku's avatar
osku committed
1685 1686

		if (!(index->type & DICT_UNIQUE)) {
1687
			dict_index_add_col(new_index, table, (dict_col_t*)
1688 1689 1690
					   dict_table_get_sys_col(
						   table, DATA_ROW_ID),
					   0);
osku's avatar
osku committed
1691 1692 1693
			trx_id_pos++;
		}

1694
		dict_index_add_col(new_index, table, (dict_col_t*)
1695 1696
				   dict_table_get_sys_col(table, DATA_TRX_ID),
				   0);
1697

1698
		dict_index_add_col(new_index, table, (dict_col_t*)
1699 1700 1701
				   dict_table_get_sys_col(table,
							  DATA_ROLL_PTR),
				   0);
osku's avatar
osku committed
1702 1703 1704

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

1705 1706
			fixed_size = dict_col_get_fixed_size(
				dict_index_get_nth_col(new_index, i));
osku's avatar
osku committed
1707 1708 1709 1710 1711 1712 1713 1714

			if (fixed_size == 0) {
				new_index->trx_id_offset = 0;

				break;
			}

			if (dict_index_get_nth_field(new_index, i)->prefix_len
1715
			    > 0) {
osku's avatar
osku committed
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
				new_index->trx_id_offset = 0;

				break;
			}

			new_index->trx_id_offset += fixed_size;
		}

	}

1726 1727 1728
	/* Remember the table columns already contained in new_index */
	indexed = mem_alloc(table->n_cols * sizeof *indexed);
	memset(indexed, 0, table->n_cols * sizeof *indexed);
osku's avatar
osku committed
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739

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

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

1740
			indexed[field->col->ind] = TRUE;
osku's avatar
osku committed
1741 1742
		}
	}
1743

osku's avatar
osku committed
1744 1745
	/* Add to new_index non-system columns of table not yet included
	there */
1746
	for (i = 0; i + DATA_N_SYS_COLS < (ulint) table->n_cols; i++) {
osku's avatar
osku committed
1747

1748 1749 1750
		dict_col_t*	col = (dict_col_t*)
			dict_table_get_nth_col(table, i);
		ut_ad(col->mtype != DATA_SYS);
osku's avatar
osku committed
1751

1752
		if (!indexed[col->ind]) {
1753
			dict_index_add_col(new_index, table, col, 0);
osku's avatar
osku committed
1754 1755 1756
		}
	}

1757 1758
	mem_free(indexed);

osku's avatar
osku committed
1759
	ut_ad((index->type & DICT_IBUF)
1760
	      || (UT_LIST_GET_LEN(table->indexes) == 0));
osku's avatar
osku committed
1761 1762 1763 1764

	new_index->cached = TRUE;

	return(new_index);
1765
}
osku's avatar
osku committed
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777

/***********************************************************************
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
1778
				index */
osku's avatar
osku committed
1779 1780 1781 1782 1783
{
	dict_field_t*	field;
	dict_index_t*	new_index;
	dict_index_t*	clust_index;
	ulint		i;
1784
	ibool*		indexed;
osku's avatar
osku committed
1785 1786 1787 1788 1789 1790 1791 1792

	ut_ad(table && index);
	ut_ad(0 == (index->type & DICT_CLUSTERED));
	ut_ad(mutex_own(&(dict_sys->mutex)));
	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);
1793

osku's avatar
osku committed
1794 1795 1796 1797 1798
	ut_ad(clust_index);
	ut_ad(clust_index->type & DICT_CLUSTERED);
	ut_ad(!(clust_index->type & DICT_UNIVERSAL));

	/* Create a new index */
1799 1800 1801
	new_index = dict_mem_index_create(
		table->name, index->name, index->space, index->type,
		index->n_fields + 1 + clust_index->n_uniq);
osku's avatar
osku committed
1802 1803 1804 1805 1806

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

osku's avatar
osku committed
1808 1809 1810
	new_index->id = index->id;

	/* Copy fields from index to new_index */
1811
	dict_index_copy(new_index, index, table, 0, index->n_fields);
osku's avatar
osku committed
1812

1813 1814 1815
	/* Remember the table columns already contained in new_index */
	indexed = mem_alloc(table->n_cols * sizeof *indexed);
	memset(indexed, 0, table->n_cols * sizeof *indexed);
osku's avatar
osku committed
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826

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

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

1827
			indexed[field->col->ind] = TRUE;
osku's avatar
osku committed
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
		}
	}

	/* Add to new_index the columns necessary to determine the clustered
	index entry uniquely */

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

		field = dict_index_get_nth_field(clust_index, i);

1838
		if (!indexed[field->col->ind]) {
1839
			dict_index_add_col(new_index, table, field->col,
1840
					   field->prefix_len);
osku's avatar
osku committed
1841 1842 1843
		}
	}

1844 1845
	mem_free(indexed);

osku's avatar
osku committed
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
	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);
1860
}
osku's avatar
osku committed
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874

/*====================== FOREIGN KEY PROCESSING ========================*/

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

osku's avatar
osku committed
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
		return(TRUE);
	}

	return(FALSE);
}

/*************************************************************************
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 */
{
	ut_ad(mutex_own(&(dict_sys->mutex)));
	ut_a(foreign);
1903

osku's avatar
osku committed
1904 1905
	if (foreign->referenced_table) {
		UT_LIST_REMOVE(referenced_list,
1906 1907
			       foreign->referenced_table->referenced_list,
			       foreign);
osku's avatar
osku committed
1908 1909 1910 1911
	}

	if (foreign->foreign_table) {
		UT_LIST_REMOVE(foreign_list,
1912 1913
			       foreign->foreign_table->foreign_list,
			       foreign);
osku's avatar
osku committed
1914 1915 1916 1917 1918 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
	}

	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 */
	const char*	id)	/* in: foreign constraint id */
{
	dict_foreign_t*	foreign;

	ut_ad(mutex_own(&(dict_sys->mutex)));

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

osku's avatar
osku committed
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
	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);
1957
}
osku's avatar
osku committed
1958

1959
#ifndef UNIV_HOTBACKUP
osku's avatar
osku committed
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
/*************************************************************************
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 */
	const char**	columns,/* in: array of column names */
	ulint		n_cols,	/* in: number of columns */
osku's avatar
osku committed
1971 1972
	dict_index_t*	types_idx, /* in: NULL or an index to whose types the
				   column types must match */
1973
	ibool		check_charsets,
1974 1975
				/* in: whether to check charsets.
				only has an effect if types_idx != NULL */
1976 1977 1978
	ulint		check_null)
				/* in: nonzero if none of the columns must
				be declared NOT NULL */
osku's avatar
osku committed
1979 1980
{
	dict_index_t*	index;
1981
	dict_field_t*	field;
osku's avatar
osku committed
1982 1983
	const char*	col_name;
	ulint		i;
1984

osku's avatar
osku committed
1985 1986 1987 1988 1989 1990
	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++) {
1991 1992 1993 1994 1995 1996
				field = dict_index_get_nth_field(index, i);

				col_name = dict_table_get_col_name(
					table, dict_col_get_no(field->col));

				if (field->prefix_len != 0) {
osku's avatar
osku committed
1997 1998
					/* We do not accept column prefix
					indexes here */
1999

osku's avatar
osku committed
2000 2001 2002 2003
					break;
				}

				if (0 != innobase_strcasecmp(columns[i],
2004
							     col_name)) {
2005
					break;
osku's avatar
osku committed
2006 2007
				}

2008 2009 2010 2011 2012 2013
				if (check_null
				    && (field->col->prtype & DATA_NOT_NULL)) {

					return(NULL);
				}

2014 2015 2016 2017 2018
				if (types_idx && !cmp_cols_are_equal(
					    dict_index_get_nth_col(index, i),
					    dict_index_get_nth_col(types_idx,
								   i),
					    check_charsets)) {
osku's avatar
osku committed
2019

2020 2021
					break;
				}
osku's avatar
osku committed
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
			}

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

				return(index);
			}
		}

		index = dict_table_get_next_index(index);
	}

	return(NULL);
}

/**************************************************************************
Report an error in a foreign key definition. */
static
void
dict_foreign_error_report_low(
/*==========================*/
	FILE*		file,	/* in: output stream */
	const char*	name)	/* in: table name */
{
	rewind(file);
	ut_print_timestamp(file);
	fprintf(file, " Error in foreign key constraint of table %s:\n",
		name);
}

/**************************************************************************
Report an error in a foreign key definition. */
static
void
dict_foreign_error_report(
/*======================*/
	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);
	dict_print_info_on_foreign_key_in_create_format(file, NULL, fk, TRUE);
2067
	putc('\n', file);
osku's avatar
osku committed
2068
	if (fk->foreign_index) {
2069
		fputs("The index in the foreign key in table is ", file);
2070
		ut_print_name(file, NULL, FALSE, fk->foreign_index->name);
2071
		fputs("\n"
2072 2073 2074 2075
		      "See http://dev.mysql.com/doc/refman/5.1/en/"
		      "innodb-foreign-key-constraints.html\n"
		      "for correct foreign key definition.\n",
		      file);
osku's avatar
osku committed
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
	}
	mutex_exit(&dict_foreign_err_mutex);
}

/**************************************************************************
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 */
	dict_foreign_t*	foreign,	/* in, own: foreign key constraint */
osku's avatar
osku committed
2091 2092
	ibool		check_charsets)	/* in: TRUE=check charset
					compatibility */
osku's avatar
osku committed
2093 2094 2095 2096 2097 2098
{
	dict_table_t*	for_table;
	dict_table_t*	ref_table;
	dict_foreign_t*	for_in_cache		= NULL;
	dict_index_t*	index;
	ibool		added_to_referenced_list= FALSE;
2099
	FILE*		ef			= dict_foreign_err_file;
osku's avatar
osku committed
2100 2101 2102

	ut_ad(mutex_own(&(dict_sys->mutex)));

2103 2104
	for_table = dict_table_check_if_in_cache_low(
		foreign->foreign_table_name);
2105

2106 2107
	ref_table = dict_table_check_if_in_cache_low(
		foreign->referenced_table_name);
osku's avatar
osku committed
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
	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) {
2126 2127 2128 2129
		index = dict_foreign_find_index(
			ref_table,
			(const char**) for_in_cache->referenced_col_names,
			for_in_cache->n_fields, for_in_cache->foreign_index,
2130
			check_charsets, FALSE);
osku's avatar
osku committed
2131 2132

		if (index == NULL) {
2133 2134 2135 2136 2137 2138 2139 2140
			dict_foreign_error_report(
				ef, for_in_cache,
				"there is no index in referenced table"
				" which would contain\n"
				"the columns as the first columns,"
				" or the data types in the\n"
				"referenced table do not match"
				" the ones in table.");
osku's avatar
osku committed
2141 2142 2143 2144 2145

			if (for_in_cache == foreign) {
				mem_heap_free(foreign->heap);
			}

2146
			return(DB_CANNOT_ADD_CONSTRAINT);
osku's avatar
osku committed
2147 2148 2149 2150 2151
		}

		for_in_cache->referenced_table = ref_table;
		for_in_cache->referenced_index = index;
		UT_LIST_ADD_LAST(referenced_list,
2152 2153
				 ref_table->referenced_list,
				 for_in_cache);
osku's avatar
osku committed
2154 2155 2156 2157
		added_to_referenced_list = TRUE;
	}

	if (for_in_cache->foreign_table == NULL && for_table) {
2158 2159 2160 2161
		index = dict_foreign_find_index(
			for_table,
			(const char**) for_in_cache->foreign_col_names,
			for_in_cache->n_fields,
2162 2163 2164 2165
			for_in_cache->referenced_index, check_charsets,
			for_in_cache->type
			& (DICT_FOREIGN_ON_DELETE_SET_NULL
			   | DICT_FOREIGN_ON_UPDATE_SET_NULL));
osku's avatar
osku committed
2166 2167

		if (index == NULL) {
2168 2169 2170 2171 2172 2173 2174
			dict_foreign_error_report(
				ef, for_in_cache,
				"there is no index in the table"
				" which would contain\n"
				"the columns as the first columns,"
				" or the data types in the\n"
				"table do not match"
2175 2176 2177
				" the ones in the referenced table\n"
				"or one of the ON ... SET NULL columns"
				" is declared NOT NULL.");
osku's avatar
osku committed
2178 2179 2180

			if (for_in_cache == foreign) {
				if (added_to_referenced_list) {
2181 2182 2183 2184
					UT_LIST_REMOVE(
						referenced_list,
						ref_table->referenced_list,
						for_in_cache);
osku's avatar
osku committed
2185
				}
2186

osku's avatar
osku committed
2187 2188 2189
				mem_heap_free(foreign->heap);
			}

2190
			return(DB_CANNOT_ADD_CONSTRAINT);
osku's avatar
osku committed
2191 2192 2193 2194 2195
		}

		for_in_cache->foreign_table = for_table;
		for_in_cache->foreign_index = index;
		UT_LIST_ADD_LAST(foreign_list,
2196 2197
				 for_table->foreign_list,
				 for_in_cache);
osku's avatar
osku committed
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
	}

	return(DB_SUCCESS);
}

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

const char*
dict_scan_to(
/*=========*/
				/* out: scanned up to this */
	const char*	ptr,	/* in: scan from */
	const char*	string)	/* in: look for this */
{
	char	quote	= '\0';

	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++) {
				if (toupper((int)(unsigned char)(ptr[i]))
2232 2233
				    != toupper((int)(unsigned char)
					       (string[i]))) {
osku's avatar
osku committed
2234 2235 2236 2237
					goto nomatch;
				}
			}
			break;
2238
nomatch:
osku's avatar
osku committed
2239 2240 2241 2242 2243 2244 2245 2246 2247
			;
		}
	}

	return(ptr);
}

/*************************************************************************
Accepts a specified string. Comparisons are case-insensitive. */
2248
static
osku's avatar
osku committed
2249 2250 2251 2252 2253
const char*
dict_accept(
/*========*/
				/* out: if string was accepted, the pointer
				is moved after that, else ptr is returned */
2254
	struct charset_info_st*	cs,/* in: the character set of ptr */
osku's avatar
osku committed
2255 2256 2257 2258 2259 2260 2261 2262 2263
	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 */
{
	const char*	old_ptr = ptr;
	const char*	old_ptr2;

	*success = FALSE;
2264

2265
	while (my_isspace(cs, *ptr)) {
osku's avatar
osku committed
2266 2267 2268 2269
		ptr++;
	}

	old_ptr2 = ptr;
2270

osku's avatar
osku committed
2271
	ptr = dict_scan_to(ptr, string);
2272

osku's avatar
osku committed
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
	if (*ptr == '\0' || old_ptr2 != ptr) {
		return(old_ptr);
	}

	*success = TRUE;

	return(ptr + ut_strlen(string));
}

/*************************************************************************
Scans an id. For the lexical definition of an 'id', see the code below.
Strips backquotes or double quotes from around the id. */
static
const char*
dict_scan_id(
/*=========*/
				/* out: scanned to */
2290
	struct charset_info_st*	cs,/* in: the character set of ptr */
osku's avatar
osku committed
2291 2292 2293 2294 2295 2296
	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
				scannable */
2297 2298
	ibool		table_id,/* in: TRUE=convert the allocated id
				as a table name; FALSE=convert to UTF-8 */
osku's avatar
osku committed
2299 2300 2301 2302 2303 2304 2305 2306
	ibool		accept_also_dot)
				/* in: TRUE if also a dot can appear in a
				non-quoted id; in a quoted id it can appear
				always */
{
	char		quote	= '\0';
	ulint		len	= 0;
	const char*	s;
2307 2308
	char*		str;
	char*		dst;
osku's avatar
osku committed
2309 2310 2311

	*id = NULL;

2312
	while (my_isspace(cs, *ptr)) {
osku's avatar
osku committed
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
		ptr++;
	}

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

		return(ptr);
	}

	if (*ptr == '`' || *ptr == '"') {
		quote = *ptr++;
	}

	s = ptr;

	if (quote) {
		for (;;) {
			if (!*ptr) {
				/* Syntax error */
				return(ptr);
			}
			if (*ptr == quote) {
				ptr++;
				if (*ptr != quote) {
					break;
				}
			}
			ptr++;
			len++;
		}
	} else {
2343
		while (!my_isspace(cs, *ptr) && *ptr != '(' && *ptr != ')'
2344 2345
		       && (accept_also_dot || *ptr != '.')
		       && *ptr != ',' && *ptr != '\0') {
osku's avatar
osku committed
2346 2347 2348 2349 2350 2351 2352

			ptr++;
		}

		len = ptr - s;
	}

2353 2354 2355 2356 2357 2358 2359 2360 2361
	if (UNIV_UNLIKELY(!heap)) {
		/* no heap given: id will point to source string */
		*id = s;
		return(ptr);
	}

	if (quote) {
		char*	d;
		str = d = mem_heap_alloc(heap, len + 1);
osku's avatar
osku committed
2362 2363 2364 2365 2366 2367
		while (len--) {
			if ((*d++ = *s++) == quote) {
				s++;
			}
		}
		*d++ = 0;
2368 2369 2370
		len = d - str;
		ut_ad(*s == quote);
		ut_ad(s + 1 == ptr);
osku's avatar
osku committed
2371
	} else {
2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383
		str = mem_heap_strdupl(heap, s, len);
	}

	if (!table_id) {
convert_id:
		/* Convert the identifier from connection character set
		to UTF-8. */
		len = 3 * len + 1;
		*id = dst = mem_heap_alloc(heap, len);

		innobase_convert_from_id(dst, str, len);
	} else if (!strncmp(str, srv_mysql50_table_name_prefix,
2384
			    sizeof srv_mysql50_table_name_prefix)) {
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
		/* This is a pre-5.1 table name
		containing chars other than [A-Za-z0-9].
		Discard the prefix and use raw UTF-8 encoding. */
		str += sizeof srv_mysql50_table_name_prefix;
		len -= sizeof srv_mysql50_table_name_prefix;
		goto convert_id;
	} else {
		/* Encode using filename-safe characters. */
		len = 5 * len + 1;
		*id = dst = mem_heap_alloc(heap, len);
osku's avatar
osku committed
2395

2396
		innobase_convert_from_table_id(dst, str, len);
osku's avatar
osku committed
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
	}

	return(ptr);
}

/*************************************************************************
Tries to scan a column name. */
static
const char*
dict_scan_col(
/*==========*/
2408 2409 2410 2411 2412 2413 2414 2415 2416
					/* out: scanned to */
	struct charset_info_st*	cs,	/* in: the character set of ptr */
	const char*		ptr,	/* in: scanned to */
	ibool*			success,/* out: TRUE if success */
	dict_table_t*		table,	/* in: table in which the column is */
	const dict_col_t**	column,	/* out: pointer to column if success */
	mem_heap_t*		heap,	/* in: heap where to allocate */
	const char**		name)	/* out,own: the column name;
					NULL if no name was scannable */
osku's avatar
osku committed
2417 2418 2419 2420 2421
{
	ulint		i;

	*success = FALSE;

2422
	ptr = dict_scan_id(cs, ptr, heap, name, FALSE, TRUE);
osku's avatar
osku committed
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432

	if (*name == NULL) {

		return(ptr);	/* Syntax error */
	}

	if (table == NULL) {
		*success = TRUE;
		*column = NULL;
	} else {
2433
		for (i = 0; i < dict_table_get_n_cols(table); i++) {
osku's avatar
osku committed
2434

2435 2436
			const char*	col_name = dict_table_get_col_name(
				table, i);
osku's avatar
osku committed
2437

2438
			if (0 == innobase_strcasecmp(col_name, *name)) {
2439
				/* Found */
osku's avatar
osku committed
2440

2441
				*success = TRUE;
2442 2443
				*column = dict_table_get_nth_col(table, i);
				strcpy((char*) *name, col_name);
osku's avatar
osku committed
2444

2445
				break;
osku's avatar
osku committed
2446 2447 2448
			}
		}
	}
2449

osku's avatar
osku committed
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
	return(ptr);
}

/*************************************************************************
Scans a table name from an SQL string. */
static
const char*
dict_scan_table_name(
/*=================*/
				/* out: scanned to */
2460
	struct charset_info_st*	cs,/* in: the character set of ptr */
osku's avatar
osku committed
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
	const char*	ptr,	/* in: scanned to */
	dict_table_t**	table,	/* out: table object or NULL */
	const char*	name,	/* in: foreign key table name */
	ibool*		success,/* out: TRUE if ok name found */
	mem_heap_t*	heap,	/* in: heap where to allocate the id */
	const char**	ref_name)/* out,own: the table name;
				NULL if no name was scannable */
{
	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;

	*success = FALSE;
	*table = NULL;
2478

2479
	ptr = dict_scan_id(cs, ptr, heap, &scan_name, TRUE, FALSE);
osku's avatar
osku committed
2480 2481

	if (scan_name == NULL) {
2482

osku's avatar
osku committed
2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
		return(ptr);	/* Syntax error */
	}

	if (*ptr == '.') {
		/* We scanned the database name; scan also the table name */

		ptr++;

		database_name = scan_name;
		database_name_len = strlen(database_name);

2494
		ptr = dict_scan_id(cs, ptr, heap, &table_name, TRUE, FALSE);
osku's avatar
osku committed
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504

		if (table_name == NULL) {

			return(ptr);	/* Syntax error */
		}
	} else {
		/* 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:
2505
		... REFERENCES `databasename.tablename` ...
osku's avatar
osku committed
2506
		starting from 4.0.18 it is
2507
		... REFERENCES `databasename`.`tablename` ... */
osku's avatar
osku committed
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
		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? */
			}
		}

		table_name = scan_name;
	}

	if (database_name == NULL) {
		/* Use the database name of the foreign key table */

		database_name = name;
		database_name_len = dict_get_db_name_len(name);
	}

	table_name_len = strlen(table_name);

	/* Copy database_name, '/', table_name, '\0' */
	ref = mem_heap_alloc(heap, database_name_len + table_name_len + 2);
	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__
	if (srv_lower_case_table_names) {
#endif /* !__WIN__ */
		/* The table name is always put to lower case on Windows. */
		innobase_casedn_str(ref);
#ifndef __WIN__
	}
#endif /* !__WIN__ */

	*success = TRUE;
	*ref_name = ref;
	*table = dict_table_get_low(ref);

	return(ptr);
}

/*************************************************************************
Skips one id. The id is allowed to contain also '.'. */
static
const char*
dict_skip_word(
/*===========*/
				/* out: scanned to */
2559
	struct charset_info_st*	cs,/* in: the character set of ptr */
osku's avatar
osku committed
2560 2561 2562 2563 2564
	const char*	ptr,	/* in: scanned to */
	ibool*		success)/* out: TRUE if success, FALSE if just spaces
				left in string or a syntax error */
{
	const char*	start;
2565

osku's avatar
osku committed
2566 2567
	*success = FALSE;

2568
	ptr = dict_scan_id(cs, ptr, NULL, &start, FALSE, TRUE);
osku's avatar
osku committed
2569 2570 2571 2572

	if (start) {
		*success = TRUE;
	}
2573

osku's avatar
osku committed
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
	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(
/*================*/
					/* out, own: SQL string stripped from
					comments; the caller must free this
					with mem_free()! */
	const char*	sql_string)	/* in: SQL string */
{
	char*		str;
	const char*	sptr;
	char*		ptr;
2595 2596
	/* unclosed quote character (0 if none) */
	char		quote	= 0;
osku's avatar
osku committed
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623

	str = mem_alloc(strlen(sql_string) + 1);

	sptr = sql_string;
	ptr = str;

	for (;;) {
scan_more:
		if (*sptr == '\0') {
			*ptr = '\0';

			ut_a(ptr <= str + strlen(sql_string));

			return(str);
		}

		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 == '#'
2624 2625
			   || (sptr[0] == '-' && sptr[1] == '-'
			       && sptr[2] == ' ')) {
osku's avatar
osku committed
2626 2627 2628 2629 2630
			for (;;) {
				/* In Unix a newline is 0x0A while in Windows
				it is 0x0D followed by 0x0A */

				if (*sptr == (char)0x0A
2631 2632
				    || *sptr == (char)0x0D
				    || *sptr == '\0') {
osku's avatar
osku committed
2633 2634 2635 2636 2637 2638 2639 2640 2641 2642

					goto scan_more;
				}

				sptr++;
			}
		} else if (!quote && *sptr == '/' && *(sptr + 1) == '*') {
			for (;;) {
				if (*sptr == '*' && *(sptr + 1) == '/') {

2643
					sptr += 2;
osku's avatar
osku committed
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688

					goto scan_more;
				}

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

					goto scan_more;
				}

				sptr++;
			}
		}

		*ptr = *sptr;

		ptr++;
		sptr++;
	}
}

/*************************************************************************
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;
	ulint		len;

	ut_a(table);

	len = ut_strlen(table->name);
	foreign = UT_LIST_GET_FIRST(table->foreign_list);

	while (foreign) {
		if (ut_strlen(foreign->id) > ((sizeof dict_ibfk) - 1) + len
2689 2690 2691 2692
		    && 0 == ut_memcmp(foreign->id, table->name, len)
		    && 0 == ut_memcmp(foreign->id + len,
				      dict_ibfk, (sizeof dict_ibfk) - 1)
		    && foreign->id[len + ((sizeof dict_ibfk) - 1)] != '0') {
osku's avatar
osku committed
2693 2694
			/* It is of the >= 4.0.18 format */

2695 2696 2697
			id = strtoul(foreign->id + len
				     + ((sizeof dict_ibfk) - 1),
				     &endp, 10);
osku's avatar
osku committed
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746
			if (*endp == '\0') {
				ut_a(id != biggest_id);

				if (id > biggest_id) {
					biggest_id = id;
				}
			}
		}

		foreign = UT_LIST_GET_NEXT(foreign_list, foreign);
	}

	return(biggest_id);
}

/*************************************************************************
Reports a simple foreign key create clause syntax error. */
static
void
dict_foreign_report_syntax_err(
/*===========================*/
	const char*	name,		/* in: table name */
	const char*	start_of_latest_foreign,
					/* in: start of the foreign key clause
					in the SQL string */
	const char*	ptr)		/* in: place of the syntax error */
{
	FILE*	 ef = dict_foreign_err_file;

	mutex_enter(&dict_foreign_err_mutex);
	dict_foreign_error_report_low(ef, name);
	fprintf(ef, "%s:\nSyntax error close to:\n%s\n",
		start_of_latest_foreign, ptr);
	mutex_exit(&dict_foreign_err_mutex);
}

/*************************************************************************
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. */
static
ulint
dict_create_foreign_constraints_low(
/*================================*/
				/* out: error code or DB_SUCCESS */
	trx_t*		trx,	/* in: transaction */
	mem_heap_t*	heap,	/* in: memory heap */
2747
	struct charset_info_st*	cs,/* in: the character set of sql_string */
osku's avatar
osku committed
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767
	const char*	sql_string,
				/* in: CREATE TABLE or ALTER TABLE 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 is the database of parameter name */
	const char*	name,	/* in: table full name in the normalized form
				database_name/table_name */
	ibool		reject_fks)
				/* in: if TRUE, fail with error code
				DB_CANNOT_ADD_CONSTRAINT if any foreign
				keys are found. */
{
	dict_table_t*	table;
	dict_table_t*	referenced_table;
	dict_table_t*	table_to_alter;
	ulint		highest_id_so_far	= 0;
	dict_index_t*	index;
	dict_foreign_t*	foreign;
2768
	const char*	ptr			= sql_string;
osku's avatar
osku committed
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
	const char*	start_of_latest_foreign	= sql_string;
	FILE*		ef			= dict_foreign_err_file;
	const char*	constraint_name;
	ibool		success;
	ulint		error;
	const char*	ptr1;
	const char*	ptr2;
	ulint		i;
	ulint		j;
	ibool		is_on_delete;
	ulint		n_on_deletes;
	ulint		n_on_updates;
2781
	const dict_col_t*columns[500];
osku's avatar
osku committed
2782 2783
	const char*	column_names[500];
	const char*	referenced_table_name;
2784

osku's avatar
osku committed
2785 2786 2787 2788 2789 2790 2791 2792
	ut_ad(mutex_own(&(dict_sys->mutex)));

	table = dict_table_get_low(name);

	if (table == NULL) {
		mutex_enter(&dict_foreign_err_mutex);
		dict_foreign_error_report_low(ef, name);
		fprintf(ef,
2793 2794 2795
			"Cannot find the table in the internal"
			" data dictionary of InnoDB.\n"
			"Create table statement:\n%s\n", sql_string);
osku's avatar
osku committed
2796 2797 2798 2799 2800 2801 2802 2803
		mutex_exit(&dict_foreign_err_mutex);

		return(DB_ERROR);
	}

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

2804
	ptr = dict_accept(cs, ptr, "ALTER", &success);
osku's avatar
osku committed
2805 2806 2807 2808 2809 2810

	if (!success) {

		goto loop;
	}

2811
	ptr = dict_accept(cs, ptr, "TABLE", &success);
osku's avatar
osku committed
2812 2813 2814 2815 2816 2817 2818 2819

	if (!success) {

		goto loop;
	}

	/* We are doing an ALTER TABLE: scan the table name we are altering */

2820
	ptr = dict_scan_table_name(cs, ptr, &table_to_alter, name,
2821
				   &success, heap, &referenced_table_name);
osku's avatar
osku committed
2822 2823
	if (!success) {
		fprintf(stderr,
2824 2825 2826
			"InnoDB: Error: could not find"
			" the table being ALTERED in:\n%s\n",
			sql_string);
osku's avatar
osku committed
2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842

		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 {
2843 2844
		highest_id_so_far = dict_table_get_highest_foreign_id(
			table_to_alter);
osku's avatar
osku committed
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
	}

	/* Scan for foreign key declarations in a loop */
loop:
	/* Scan either to "CONSTRAINT" or "FOREIGN", whichever is closer */

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

	constraint_name = NULL;

	if (ptr1 < ptr2) {
		/* The user may have specified a constraint name. Pick it so
		that we can store 'databasename/constraintname' as the id of
		of the constraint to system tables. */
		ptr = ptr1;

2862
		ptr = dict_accept(cs, ptr, "CONSTRAINT", &success);
osku's avatar
osku committed
2863 2864 2865

		ut_a(success);

2866
		if (!my_isspace(cs, *ptr) && *ptr != '"' && *ptr != '`') {
2867
			goto loop;
osku's avatar
osku committed
2868 2869
		}

2870
		while (my_isspace(cs, *ptr)) {
osku's avatar
osku committed
2871 2872 2873 2874 2875
			ptr++;
		}

		/* read constraint name unless got "CONSTRAINT FOREIGN" */
		if (ptr != ptr2) {
2876
			ptr = dict_scan_id(cs, ptr, heap,
2877
					   &constraint_name, FALSE, FALSE);
osku's avatar
osku committed
2878 2879 2880 2881 2882 2883 2884
		}
	} else {
		ptr = ptr2;
	}

	if (*ptr == '\0') {
		/* The proper way to reject foreign keys for temporary
2885 2886 2887 2888 2889 2890
		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. */
2891
		if (reject_fks && (UT_LIST_GET_LEN(table->foreign_list) > 0)) {
2892 2893

			return(DB_CANNOT_ADD_CONSTRAINT);
osku's avatar
osku committed
2894
		}
2895

osku's avatar
osku committed
2896 2897 2898
		/**********************************************************/
		/* The following call adds the foreign key constraints
		to the data dictionary system tables on disk */
2899

2900 2901
		error = dict_create_add_foreigns_to_dictionary(
			highest_id_so_far, table, trx);
osku's avatar
osku committed
2902 2903 2904 2905 2906
		return(error);
	}

	start_of_latest_foreign = ptr;

2907
	ptr = dict_accept(cs, ptr, "FOREIGN", &success);
2908

osku's avatar
osku committed
2909 2910 2911 2912
	if (!success) {
		goto loop;
	}

2913
	if (!my_isspace(cs, *ptr)) {
2914
		goto loop;
osku's avatar
osku committed
2915 2916
	}

2917
	ptr = dict_accept(cs, ptr, "KEY", &success);
osku's avatar
osku committed
2918 2919 2920 2921 2922

	if (!success) {
		goto loop;
	}

2923
	ptr = dict_accept(cs, ptr, "(", &success);
osku's avatar
osku committed
2924 2925 2926 2927

	if (!success) {
		/* MySQL allows also an index id before the '('; we
		skip it */
2928
		ptr = dict_skip_word(cs, ptr, &success);
osku's avatar
osku committed
2929 2930

		if (!success) {
2931 2932
			dict_foreign_report_syntax_err(
				name, start_of_latest_foreign, ptr);
osku's avatar
osku committed
2933 2934 2935 2936

			return(DB_CANNOT_ADD_CONSTRAINT);
		}

2937
		ptr = dict_accept(cs, ptr, "(", &success);
osku's avatar
osku committed
2938 2939 2940 2941 2942

		if (!success) {
			/* We do not flag a syntax error here because in an
			ALTER TABLE we may also have DROP FOREIGN KEY abc */

2943
			goto loop;
osku's avatar
osku committed
2944 2945 2946 2947 2948 2949 2950 2951
		}
	}

	i = 0;

	/* Scan the columns in the first list */
col_loop1:
	ut_a(i < (sizeof column_names) / sizeof *column_names);
2952
	ptr = dict_scan_col(cs, ptr, &success, table, columns + i,
2953
			    heap, column_names + i);
osku's avatar
osku committed
2954 2955 2956 2957
	if (!success) {
		mutex_enter(&dict_foreign_err_mutex);
		dict_foreign_error_report_low(ef, name);
		fprintf(ef, "%s:\nCannot resolve column name close to:\n%s\n",
2958
			start_of_latest_foreign, ptr);
osku's avatar
osku committed
2959 2960 2961 2962 2963 2964
		mutex_exit(&dict_foreign_err_mutex);

		return(DB_CANNOT_ADD_CONSTRAINT);
	}

	i++;
2965

2966
	ptr = dict_accept(cs, ptr, ",", &success);
osku's avatar
osku committed
2967 2968 2969 2970

	if (success) {
		goto col_loop1;
	}
2971

2972
	ptr = dict_accept(cs, ptr, ")", &success);
osku's avatar
osku committed
2973 2974

	if (!success) {
2975 2976
		dict_foreign_report_syntax_err(
			name, start_of_latest_foreign, ptr);
osku's avatar
osku committed
2977 2978 2979 2980 2981 2982
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

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

2983 2984
	index = dict_foreign_find_index(table, column_names, i,
					NULL, TRUE, FALSE);
osku's avatar
osku committed
2985 2986 2987 2988 2989

	if (!index) {
		mutex_enter(&dict_foreign_err_mutex);
		dict_foreign_error_report_low(ef, name);
		fputs("There is no index in table ", ef);
2990
		ut_print_name(ef, NULL, TRUE, name);
osku's avatar
osku committed
2991
		fprintf(ef, " where the columns appear\n"
2992 2993 2994 2995
			"as the first columns. Constraint:\n%s\n"
			"See http://dev.mysql.com/doc/refman/5.1/en/"
			"innodb-foreign-key-constraints.html\n"
			"for correct foreign key definition.\n",
osku's avatar
osku committed
2996 2997 2998 2999 3000
			start_of_latest_foreign);
		mutex_exit(&dict_foreign_err_mutex);

		return(DB_CANNOT_ADD_CONSTRAINT);
	}
3001
	ptr = dict_accept(cs, ptr, "REFERENCES", &success);
osku's avatar
osku committed
3002

3003
	if (!success || !my_isspace(cs, *ptr)) {
3004 3005
		dict_foreign_report_syntax_err(
			name, start_of_latest_foreign, ptr);
osku's avatar
osku committed
3006 3007 3008 3009 3010 3011 3012 3013
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

	/* Let us create a constraint struct */

	foreign = dict_mem_foreign_create();

	if (constraint_name) {
3014
		ulint	db_len;
osku's avatar
osku committed
3015 3016 3017 3018 3019 3020 3021 3022

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

3023 3024
		foreign->id = mem_heap_alloc(
			foreign->heap, db_len + strlen(constraint_name) + 2);
osku's avatar
osku committed
3025 3026 3027 3028 3029 3030 3031 3032

		ut_memcpy(foreign->id, table->name, db_len);
		foreign->id[db_len] = '/';
		strcpy(foreign->id + db_len + 1, constraint_name);
	}

	foreign->foreign_table = table;
	foreign->foreign_table_name = mem_heap_strdup(foreign->heap,
3033
						      table->name);
osku's avatar
osku committed
3034 3035 3036
	foreign->foreign_index = index;
	foreign->n_fields = i;
	foreign->foreign_col_names = mem_heap_alloc(foreign->heap,
3037
						    i * sizeof(void*));
osku's avatar
osku committed
3038
	for (i = 0; i < foreign->n_fields; i++) {
3039 3040 3041 3042
		foreign->foreign_col_names[i] = mem_heap_strdup(
			foreign->heap,
			dict_table_get_col_name(table,
						dict_col_get_no(columns[i])));
osku's avatar
osku committed
3043
	}
3044

3045
	ptr = dict_scan_table_name(cs, ptr, &referenced_table, name,
3046
				   &success, heap, &referenced_table_name);
osku's avatar
osku committed
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062

	/* Note that referenced_table can be NULL if the user has suppressed
	checking of foreign key constraints! */

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

		mutex_enter(&dict_foreign_err_mutex);
		dict_foreign_error_report_low(ef, name);
		fprintf(ef, "%s:\nCannot resolve table name close to:\n"
			"%s\n",
			start_of_latest_foreign, ptr);
		mutex_exit(&dict_foreign_err_mutex);

		return(DB_CANNOT_ADD_CONSTRAINT);
	}
3063

3064
	ptr = dict_accept(cs, ptr, "(", &success);
osku's avatar
osku committed
3065 3066 3067 3068

	if (!success) {
		dict_foreign_free(foreign);
		dict_foreign_report_syntax_err(name, start_of_latest_foreign,
3069
					       ptr);
osku's avatar
osku committed
3070 3071 3072 3073 3074 3075 3076
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

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

col_loop2:
3077
	ptr = dict_scan_col(cs, ptr, &success, referenced_table, columns + i,
3078
			    heap, column_names + i);
osku's avatar
osku committed
3079
	i++;
3080

osku's avatar
osku committed
3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
	if (!success) {
		dict_foreign_free(foreign);

		mutex_enter(&dict_foreign_err_mutex);
		dict_foreign_error_report_low(ef, name);
		fprintf(ef, "%s:\nCannot resolve column name close to:\n"
			"%s\n",
			start_of_latest_foreign, ptr);
		mutex_exit(&dict_foreign_err_mutex);

		return(DB_CANNOT_ADD_CONSTRAINT);
	}

3094
	ptr = dict_accept(cs, ptr, ",", &success);
osku's avatar
osku committed
3095 3096 3097 3098

	if (success) {
		goto col_loop2;
	}
3099

3100
	ptr = dict_accept(cs, ptr, ")", &success);
osku's avatar
osku committed
3101 3102 3103

	if (!success || foreign->n_fields != i) {
		dict_foreign_free(foreign);
3104

osku's avatar
osku committed
3105
		dict_foreign_report_syntax_err(name, start_of_latest_foreign,
3106
					       ptr);
osku's avatar
osku committed
3107 3108 3109 3110 3111
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

	n_on_deletes = 0;
	n_on_updates = 0;
3112

osku's avatar
osku committed
3113 3114 3115
scan_on_conditions:
	/* Loop here as long as we can find ON ... conditions */

3116
	ptr = dict_accept(cs, ptr, "ON", &success);
osku's avatar
osku committed
3117 3118 3119 3120 3121 3122

	if (!success) {

		goto try_find_index;
	}

3123
	ptr = dict_accept(cs, ptr, "DELETE", &success);
osku's avatar
osku committed
3124 3125

	if (!success) {
3126
		ptr = dict_accept(cs, ptr, "UPDATE", &success);
osku's avatar
osku committed
3127 3128 3129

		if (!success) {
			dict_foreign_free(foreign);
3130

3131 3132
			dict_foreign_report_syntax_err(
				name, start_of_latest_foreign, ptr);
osku's avatar
osku committed
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
			return(DB_CANNOT_ADD_CONSTRAINT);
		}

		is_on_delete = FALSE;
		n_on_updates++;
	} else {
		is_on_delete = TRUE;
		n_on_deletes++;
	}

3143
	ptr = dict_accept(cs, ptr, "RESTRICT", &success);
osku's avatar
osku committed
3144 3145 3146 3147 3148

	if (success) {
		goto scan_on_conditions;
	}

3149
	ptr = dict_accept(cs, ptr, "CASCADE", &success);
osku's avatar
osku committed
3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160

	if (success) {
		if (is_on_delete) {
			foreign->type |= DICT_FOREIGN_ON_DELETE_CASCADE;
		} else {
			foreign->type |= DICT_FOREIGN_ON_UPDATE_CASCADE;
		}

		goto scan_on_conditions;
	}

3161
	ptr = dict_accept(cs, ptr, "NO", &success);
osku's avatar
osku committed
3162 3163

	if (success) {
3164
		ptr = dict_accept(cs, ptr, "ACTION", &success);
osku's avatar
osku committed
3165 3166 3167

		if (!success) {
			dict_foreign_free(foreign);
3168 3169
			dict_foreign_report_syntax_err(
				name, start_of_latest_foreign, ptr);
3170

osku's avatar
osku committed
3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182
			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;
	}

3183
	ptr = dict_accept(cs, ptr, "SET", &success);
osku's avatar
osku committed
3184 3185 3186 3187

	if (!success) {
		dict_foreign_free(foreign);
		dict_foreign_report_syntax_err(name, start_of_latest_foreign,
3188
					       ptr);
osku's avatar
osku committed
3189 3190 3191
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

3192
	ptr = dict_accept(cs, ptr, "NULL", &success);
osku's avatar
osku committed
3193 3194 3195 3196

	if (!success) {
		dict_foreign_free(foreign);
		dict_foreign_report_syntax_err(name, start_of_latest_foreign,
3197
					       ptr);
osku's avatar
osku committed
3198 3199 3200 3201
		return(DB_CANNOT_ADD_CONSTRAINT);
	}

	for (j = 0; j < foreign->n_fields; j++) {
3202
		if ((dict_index_get_nth_col(foreign->foreign_index, j)->prtype)
3203
		    & DATA_NOT_NULL) {
osku's avatar
osku committed
3204 3205 3206 3207 3208 3209 3210 3211 3212

			/* It is not sensible to define SET NULL
			if the column is not allowed to be NULL! */

			dict_foreign_free(foreign);

			mutex_enter(&dict_foreign_err_mutex);
			dict_foreign_error_report_low(ef, name);
			fprintf(ef, "%s:\n"
3213 3214 3215 3216
				"You have defined a SET NULL condition"
				" though some of the\n"
				"columns are defined as NOT NULL.\n",
				start_of_latest_foreign);
osku's avatar
osku committed
3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227
			mutex_exit(&dict_foreign_err_mutex);

			return(DB_CANNOT_ADD_CONSTRAINT);
		}
	}

	if (is_on_delete) {
		foreign->type |= DICT_FOREIGN_ON_DELETE_SET_NULL;
	} else {
		foreign->type |= DICT_FOREIGN_ON_UPDATE_SET_NULL;
	}
3228

osku's avatar
osku committed
3229 3230 3231 3232 3233
	goto scan_on_conditions;

try_find_index:
	if (n_on_deletes > 1 || n_on_updates > 1) {
		/* It is an error to define more than 1 action */
3234

osku's avatar
osku committed
3235 3236 3237 3238 3239
		dict_foreign_free(foreign);

		mutex_enter(&dict_foreign_err_mutex);
		dict_foreign_error_report_low(ef, name);
		fprintf(ef, "%s:\n"
3240 3241
			"You have twice an ON DELETE clause"
			" or twice an ON UPDATE clause.\n",
osku's avatar
osku committed
3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253
			start_of_latest_foreign);
		mutex_exit(&dict_foreign_err_mutex);

		return(DB_CANNOT_ADD_CONSTRAINT);
	}

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

	if (referenced_table) {
		index = dict_foreign_find_index(referenced_table,
3254
						column_names, i,
3255 3256
						foreign->foreign_index,
						TRUE, FALSE);
osku's avatar
osku committed
3257 3258 3259 3260 3261
		if (!index) {
			dict_foreign_free(foreign);
			mutex_enter(&dict_foreign_err_mutex);
			dict_foreign_error_report_low(ef, name);
			fprintf(ef, "%s:\n"
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276
				"Cannot find an index in the"
				" referenced table where the\n"
				"referenced columns appear as the"
				" first columns, or column types\n"
				"in the table and the referenced table"
				" do not match for constraint.\n"
				"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"
				"See http://dev.mysql.com/doc/refman/5.1/en/"
				"innodb-foreign-key-constraints.html\n"
				"for correct foreign key definition.\n",
osku's avatar
osku committed
3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289
				start_of_latest_foreign);
			mutex_exit(&dict_foreign_err_mutex);

			return(DB_CANNOT_ADD_CONSTRAINT);
		}
	} else {
		ut_a(trx->check_foreigns == FALSE);
		index = NULL;
	}

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

3290 3291
	foreign->referenced_table_name
		= mem_heap_strdup(foreign->heap, referenced_table_name);
3292

osku's avatar
osku committed
3293
	foreign->referenced_col_names = mem_heap_alloc(foreign->heap,
3294
						       i * sizeof(void*));
osku's avatar
osku committed
3295 3296 3297 3298 3299 3300
	for (i = 0; i < foreign->n_fields; i++) {
		foreign->referenced_col_names[i]
			= mem_heap_strdup(foreign->heap, column_names[i]);
	}

	/* We found an ok constraint definition: add to the lists */
3301

osku's avatar
osku committed
3302 3303 3304 3305
	UT_LIST_ADD_LAST(foreign_list, table->foreign_list, foreign);

	if (referenced_table) {
		UT_LIST_ADD_LAST(referenced_list,
3306 3307
				 referenced_table->referenced_list,
				 foreign);
osku's avatar
osku committed
3308 3309 3310 3311 3312
	}

	goto loop;
}

3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
/**************************************************************************
Determines whether a string starts with the specified keyword. */

ibool
dict_str_starts_with_keyword(
/*=========================*/
					/* out: TRUE if str starts
					with keyword */
	void*		mysql_thd,	/* in: MySQL thread handle */
	const char*	str,		/* in: string to scan for keyword */
	const char*	keyword)	/* in: keyword to look for */
{
	struct charset_info_st*	cs	= innobase_get_charset(mysql_thd);
	ibool			success;

	dict_accept(cs, str, keyword, &success);
	return(success);
}

osku's avatar
osku committed
3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358
/*************************************************************************
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(
/*============================*/
					/* 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 */
	const char*	name,		/* in: table full name in the
					normalized form
					database_name/table_name */
	ibool		reject_fks)	/* in: if TRUE, fail with error
					code DB_CANNOT_ADD_CONSTRAINT if
					any foreign keys are found. */
{
3359 3360 3361 3362 3363
	char*			str;
	ulint			err;
	mem_heap_t*		heap;

	ut_a(trx && trx->mysql_thd);
osku's avatar
osku committed
3364 3365 3366 3367

	str = dict_strip_comments(sql_string);
	heap = mem_heap_create(10000);

3368 3369 3370
	err = dict_create_foreign_constraints_low(
		trx, heap, innobase_get_charset(trx->mysql_thd), str, name,
		reject_fks);
osku's avatar
osku committed
3371 3372 3373 3374

	mem_heap_free(heap);
	mem_free(str);

3375
	return(err);
osku's avatar
osku committed
3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396
}

/**************************************************************************
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 */
	const char***	constraints_to_drop)	/* out: id's of the
						constraints to drop */
{
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407
	dict_foreign_t*		foreign;
	ibool			success;
	char*			str;
	const char*		ptr;
	const char*		id;
	FILE*			ef	= dict_foreign_err_file;
	struct charset_info_st*	cs;

	ut_a(trx && trx->mysql_thd);

	cs = innobase_get_charset(trx->mysql_thd);
3408

osku's avatar
osku committed
3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421
	*n = 0;

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

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

	ut_ad(mutex_own(&(dict_sys->mutex)));
loop:
	ptr = dict_scan_to(ptr, "DROP");

	if (*ptr == '\0') {
		mem_free(str);
3422

osku's avatar
osku committed
3423 3424 3425
		return(DB_SUCCESS);
	}

3426
	ptr = dict_accept(cs, ptr, "DROP", &success);
osku's avatar
osku committed
3427

3428
	if (!my_isspace(cs, *ptr)) {
osku's avatar
osku committed
3429

3430
		goto loop;
osku's avatar
osku committed
3431 3432
	}

3433
	ptr = dict_accept(cs, ptr, "FOREIGN", &success);
3434

osku's avatar
osku committed
3435 3436
	if (!success) {

3437
		goto loop;
osku's avatar
osku committed
3438 3439
	}

3440
	ptr = dict_accept(cs, ptr, "KEY", &success);
osku's avatar
osku committed
3441 3442 3443 3444 3445 3446

	if (!success) {

		goto syntax_error;
	}

3447
	ptr = dict_scan_id(cs, ptr, heap, &id, FALSE, TRUE);
osku's avatar
osku committed
3448 3449 3450 3451 3452 3453 3454 3455 3456

	if (id == NULL) {

		goto syntax_error;
	}

	ut_a(*n < 1000);
	(*constraints_to_drop)[*n] = id;
	(*n)++;
3457

osku's avatar
osku committed
3458 3459 3460 3461 3462 3463
	/* Look for the given constraint id */

	foreign = UT_LIST_GET_FIRST(table->foreign_list);

	while (foreign != NULL) {
		if (0 == strcmp(foreign->id, id)
3464 3465 3466
		    || (strchr(foreign->id, '/')
			&& 0 == strcmp(id,
				       dict_remove_db_name(foreign->id)))) {
osku's avatar
osku committed
3467 3468 3469
			/* Found */
			break;
		}
3470

osku's avatar
osku committed
3471 3472 3473 3474 3475 3476 3477
		foreign = UT_LIST_GET_NEXT(foreign_list, foreign);
	}

	if (foreign == NULL) {
		mutex_enter(&dict_foreign_err_mutex);
		rewind(ef);
		ut_print_timestamp(ef);
3478
		fputs(" Error in dropping of a foreign key constraint"
3479
		      " of table ", ef);
3480
		ut_print_name(ef, NULL, TRUE, table->name);
osku's avatar
osku committed
3481
		fputs(",\n"
3482
		      "in SQL command\n", ef);
osku's avatar
osku committed
3483 3484
		fputs(str, ef);
		fputs("\nCannot find a constraint with the given id ", ef);
3485
		ut_print_name(ef, NULL, FALSE, id);
osku's avatar
osku committed
3486 3487 3488 3489 3490 3491 3492 3493
		fputs(".\n", ef);
		mutex_exit(&dict_foreign_err_mutex);

		mem_free(str);

		return(DB_CANNOT_DROP_CONSTRAINT);
	}

3494
	goto loop;
osku's avatar
osku committed
3495 3496 3497 3498 3499

syntax_error:
	mutex_enter(&dict_foreign_err_mutex);
	rewind(ef);
	ut_print_timestamp(ef);
3500 3501
	fputs(" Syntax error in dropping of a"
	      " foreign key constraint of table ", ef);
3502
	ut_print_name(ef, NULL, TRUE, table->name);
osku's avatar
osku committed
3503 3504 3505 3506 3507 3508 3509 3510
	fprintf(ef, ",\n"
		"close to:\n%s\n in SQL command\n%s\n", ptr, str);
	mutex_exit(&dict_foreign_err_mutex);

	mem_free(str);

	return(DB_CANNOT_DROP_CONSTRAINT);
}
3511
#endif /* UNIV_HOTBACKUP */
osku's avatar
osku committed
3512 3513 3514

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

3515
#ifdef UNIV_DEBUG
osku's avatar
osku committed
3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531
/**************************************************************************
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_index_t*	index;

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

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

3533
	index = dict_index_find_on_id_low(index_id);
osku's avatar
osku committed
3534 3535 3536 3537 3538

	mutex_exit(&(dict_sys->mutex));

	return(index);
}
3539
#endif /* UNIV_DEBUG */
osku's avatar
osku committed
3540

3541
#ifdef UNIV_DEBUG
osku's avatar
osku committed
3542 3543 3544 3545 3546
/**************************************************************************
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
3547 3548
dict_index_check_search_tuple(
/*==========================*/
osku's avatar
osku committed
3549
				/* out: TRUE if ok */
3550
	dict_index_t*	index,	/* in: index tree */
osku's avatar
osku committed
3551 3552
	dtuple_t*	tuple)	/* in: tuple used in a search */
{
3553
	ut_a(index);
osku's avatar
osku committed
3554
	ut_a(dtuple_get_n_fields_cmp(tuple)
3555
	     <= dict_index_get_n_unique_in_tree(index));
osku's avatar
osku committed
3556 3557
	return(TRUE);
}
3558
#endif /* UNIV_DEBUG */
osku's avatar
osku committed
3559 3560 3561 3562 3563

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

dtuple_t*
3564 3565
dict_index_build_node_ptr(
/*======================*/
osku's avatar
osku committed
3566
				/* out, own: node pointer */
3567
	dict_index_t*	index,	/* in: index tree */
osku's avatar
osku committed
3568 3569 3570 3571
	rec_t*		rec,	/* in: record for which to build node
				pointer */
	ulint		page_no,/* in: page number to put in node pointer */
	mem_heap_t*	heap,	/* in: memory heap where pointer created */
3572
	ulint		level)	/* in: level of rec in tree: 0 means leaf
osku's avatar
osku committed
3573 3574 3575 3576 3577 3578 3579
				level */
{
	dtuple_t*	tuple;
	dfield_t*	field;
	byte*		buf;
	ulint		n_unique;

3580
	if (UNIV_UNLIKELY(index->type & DICT_UNIVERSAL)) {
osku's avatar
osku committed
3581
		/* In a universal index tree, we take the whole record as
3582
		the node pointer if the record is on the leaf level,
osku's avatar
osku committed
3583 3584 3585
		on non-leaf levels we remove the last field, which
		contains the page number of the child page */

3586
		ut_a(!dict_table_is_comp(index->table));
osku's avatar
osku committed
3587 3588 3589
		n_unique = rec_get_n_fields_old(rec);

		if (level > 0) {
3590 3591
			ut_a(n_unique > 1);
			n_unique--;
osku's avatar
osku committed
3592
		}
3593
	} else {
3594
		n_unique = dict_index_get_n_unique_in_tree(index);
osku's avatar
osku committed
3595 3596 3597 3598 3599 3600 3601 3602 3603
	}

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

osku's avatar
osku committed
3605 3606
	dtuple_set_n_fields_cmp(tuple, n_unique);

3607
	dict_index_copy_types(tuple, index, n_unique);
3608

osku's avatar
osku committed
3609 3610 3611
	buf = mem_heap_alloc(heap, 4);

	mach_write_to_4(buf, page_no);
3612

osku's avatar
osku committed
3613 3614 3615
	field = dtuple_get_nth_field(tuple, n_unique);
	dfield_set_data(field, buf, 4);

3616
	dtype_set(dfield_get_type(field), DATA_SYS_CHILD, DATA_NOT_NULL, 4);
osku's avatar
osku committed
3617

3618
	rec_copy_prefix_to_dtuple(tuple, rec, index, n_unique, heap);
3619 3620
	dtuple_set_info_bits(tuple, dtuple_get_info_bits(tuple)
			     | REC_STATUS_NODE_PTR);
osku's avatar
osku committed
3621 3622 3623 3624

	ut_ad(dtuple_check_typed(tuple));

	return(tuple);
3625 3626
}

osku's avatar
osku committed
3627 3628 3629 3630 3631
/**************************************************************************
Copies an initial segment of a physical record, long enough to specify an
index entry uniquely. */

rec_t*
3632 3633
dict_index_copy_rec_order_prefix(
/*=============================*/
osku's avatar
osku committed
3634
				/* out: pointer to the prefix record */
3635
	dict_index_t*	index,	/* in: index tree */
osku's avatar
osku committed
3636 3637 3638 3639 3640 3641 3642 3643 3644 3645
	rec_t*		rec,	/* in: record for which to copy prefix */
	ulint*		n_fields,/* out: number of fields copied */
	byte**		buf,	/* in/out: memory buffer for the copied prefix,
				or NULL */
	ulint*		buf_size)/* in/out: buffer size */
{
	ulint		n;

	UNIV_PREFETCH_R(rec);

3646
	if (UNIV_UNLIKELY(index->type & DICT_UNIVERSAL)) {
3647
		ut_a(!dict_table_is_comp(index->table));
osku's avatar
osku committed
3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660
		n = rec_get_n_fields_old(rec);
	} else {
		n = dict_index_get_n_unique_in_tree(index);
	}

	*n_fields = n;
	return(rec_copy_prefix_to_buf(rec, index, n, buf, buf_size));
}

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

dtuple_t*
3661 3662
dict_index_build_data_tuple(
/*========================*/
osku's avatar
osku committed
3663
				/* out, own: data tuple */
3664
	dict_index_t*	index,	/* in: index tree */
osku's avatar
osku committed
3665 3666 3667 3668 3669 3670
	rec_t*		rec,	/* in: record for which to build data tuple */
	ulint		n_fields,/* in: number of data fields */
	mem_heap_t*	heap)	/* in: memory heap where tuple created */
{
	dtuple_t*	tuple;

3671
	ut_ad(dict_table_is_comp(index->table)
3672
	      || n_fields <= rec_get_n_fields_old(rec));
3673 3674

	tuple = dtuple_create(heap, n_fields);
osku's avatar
osku committed
3675

3676
	dict_index_copy_types(tuple, index, n_fields);
osku's avatar
osku committed
3677

3678
	rec_copy_prefix_to_dtuple(tuple, rec, index, n_fields, heap);
osku's avatar
osku committed
3679 3680 3681 3682

	ut_ad(dtuple_check_typed(tuple));

	return(tuple);
3683 3684
}

osku's avatar
osku committed
3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695
/*************************************************************************
Calculates the minimum record length in an index. */

ulint
dict_index_calc_min_rec_len(
/*========================*/
	dict_index_t*	index)	/* in: index */
{
	ulint	sum	= 0;
	ulint	i;

3696
	if (dict_table_is_comp(index->table)) {
osku's avatar
osku committed
3697 3698 3699
		ulint nullable = 0;
		sum = REC_N_NEW_EXTRA_BYTES;
		for (i = 0; i < dict_index_get_n_fields(index); i++) {
3700 3701 3702
			const dict_col_t*	col
				= dict_index_get_nth_col(index, i);
			ulint	size = dict_col_get_fixed_size(col);
osku's avatar
osku committed
3703 3704
			sum += size;
			if (!size) {
3705
				size = col->len;
osku's avatar
osku committed
3706 3707
				sum += size < 128 ? 1 : 2;
			}
3708
			if (!(col->prtype & DATA_NOT_NULL)) {
osku's avatar
osku committed
3709
				nullable++;
3710
			}
osku's avatar
osku committed
3711 3712 3713 3714 3715 3716 3717 3718 3719
		}

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

		return(sum);
	}

	for (i = 0; i < dict_index_get_n_fields(index); i++) {
3720 3721
		sum += dict_col_get_fixed_size(
			dict_index_get_nth_col(index, i));
osku's avatar
osku committed
3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
	}

	if (sum > 127) {
		sum += 2 * dict_index_get_n_fields(index);
	} else {
		sum += dict_index_get_n_fields(index);
	}

	sum += REC_N_OLD_EXTRA_BYTES;

	return(sum);
}

/*************************************************************************
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 */
	ibool		has_dict_mutex __attribute__((unused)))
3744 3745
					/* in: TRUE if the caller has the
					dictionary mutex */
osku's avatar
osku committed
3746 3747 3748 3749 3750 3751 3752 3753 3754
{
	dict_index_t*	index;
	ulint		size;
	ulint		sum_of_index_sizes	= 0;

	if (table->ibd_file_missing) {
		ut_print_timestamp(stderr);
		fprintf(stderr,
			"  InnoDB: cannot calculate statistics for table %s\n"
3755 3756 3757 3758
			"InnoDB: because the .ibd file is missing.  For help,"
			" please refer to\n"
			"InnoDB: http://dev.mysql.com/doc/refman/5.1/en/"
			"innodb-troubleshooting.html\n",
osku's avatar
osku committed
3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774
			table->name);

		return;
	}

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

	/* Find out the sizes of the indexes and how many different values
	for the key they approximately have */

3775
	index = dict_table_get_first_index(table);
osku's avatar
osku committed
3776 3777 3778

	if (index == NULL) {
		/* Table definition is corrupt */
3779

osku's avatar
osku committed
3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797
		return;
	}

	while (index) {
		size = btr_get_size(index, BTR_TOTAL_SIZE);

		index->stat_index_size = size;

		sum_of_index_sizes += size;

		size = btr_get_size(index, BTR_N_LEAF_PAGES);

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

		index->stat_n_leaf_pages = size;
3798

osku's avatar
osku committed
3799 3800 3801 3802 3803 3804 3805
		btr_estimate_number_of_different_key_vals(index);

		index = dict_table_get_next_index(index);
	}

	index = dict_table_get_first_index(table);

3806 3807
	table->stat_n_rows = index->stat_n_diff_key_vals[
		dict_index_get_n_unique(index)];
osku's avatar
osku committed
3808 3809 3810 3811

	table->stat_clustered_index_size = index->stat_index_size;

	table->stat_sum_of_other_index_sizes = sum_of_index_sizes
3812
		- index->stat_index_size;
osku's avatar
osku committed
3813 3814 3815

	table->stat_initialized = TRUE;

3816
	table->stat_modified_counter = 0;
osku's avatar
osku committed
3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830
}

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

osku's avatar
osku committed
3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842
/**************************************************************************
A noninlined version of dict_table_get_low. */

dict_table_t*
dict_table_get_low_noninlined(
/*==========================*/
					/* out: table, NULL if not found */
	const char*	table_name)	/* in: table name */
{
	return(dict_table_get_low(table_name));
}

osku's avatar
osku committed
3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862
/**************************************************************************
Prints info of a foreign key constraint. */
static
void
dict_foreign_print_low(
/*===================*/
	dict_foreign_t*	foreign)	/* in: foreign key constraint */
{
	ulint	i;

	ut_ad(mutex_own(&(dict_sys->mutex)));

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

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

	fprintf(stderr, " )\n"
3863
		"             REFERENCES %s (",
osku's avatar
osku committed
3864
		foreign->referenced_table_name);
3865

osku's avatar
osku committed
3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900
	for (i = 0; i < foreign->n_fields; i++) {
		fprintf(stderr, " %s", foreign->referenced_col_names[i]);
	}

	fputs(" )\n", stderr);
}

/**************************************************************************
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(
/*=====================*/
	const char*	name)
{
	dict_table_t*	table;

	mutex_enter(&(dict_sys->mutex));

	table = dict_table_get_low(name);

	ut_a(table);
3901

osku's avatar
osku committed
3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920
	dict_table_print_low(table);
	mutex_exit(&(dict_sys->mutex));
}

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

void
dict_table_print_low(
/*=================*/
	dict_table_t*	table)	/* in: table */
{
	dict_index_t*	index;
	dict_foreign_t*	foreign;
	ulint		i;

	ut_ad(mutex_own(&(dict_sys->mutex)));

	dict_update_statistics_low(table, TRUE);
3921

osku's avatar
osku committed
3922
	fprintf(stderr,
3923 3924 3925 3926 3927 3928 3929 3930 3931 3932
		"--------------------------------------\n"
		"TABLE: name %s, id %lu %lu, columns %lu, indexes %lu,"
		" appr.rows %lu\n"
		"  COLUMNS: ",
		table->name,
		(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);
osku's avatar
osku committed
3933

3934
	for (i = 0; i + 1 < (ulint) table->n_cols; i++) {
3935
		dict_col_print_low(table, dict_table_get_nth_col(table, i));
osku's avatar
osku committed
3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968
		fputs("; ", stderr);
	}

	putc('\n', stderr);

	index = UT_LIST_GET_FIRST(table->indexes);

	while (index != NULL) {
		dict_index_print_low(index);
		index = UT_LIST_GET_NEXT(indexes, index);
	}

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

/**************************************************************************
Prints a column data. */
static
void
dict_col_print_low(
/*===============*/
3969 3970
	const dict_table_t*	table,	/* in: table */
	const dict_col_t*	col)	/* in: column */
osku's avatar
osku committed
3971
{
3972
	dtype_t	type;
osku's avatar
osku committed
3973 3974 3975

	ut_ad(mutex_own(&(dict_sys->mutex)));

3976
	dict_col_copy_type(col, &type);
3977 3978
	fprintf(stderr, "%s: ", dict_table_get_col_name(table,
							dict_col_get_no(col)));
osku's avatar
osku committed
3979

3980
	dtype_print(&type);
osku's avatar
osku committed
3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996
}

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

	ut_ad(mutex_own(&(dict_sys->mutex)));

	if (index->n_user_defined_cols > 0) {
3997 3998
		n_vals = index->stat_n_diff_key_vals[
			index->n_user_defined_cols];
osku's avatar
osku committed
3999 4000 4001 4002 4003
	} else {
		n_vals = index->stat_n_diff_key_vals[1];
	}

	fprintf(stderr,
4004 4005
		"  INDEX: name %s, id %lu %lu, fields %lu/%lu,"
		" uniq %lu, type %lu\n"
osku's avatar
osku committed
4006 4007 4008 4009
		"   root page %lu, appr.key vals %lu,"
		" leaf pages %lu, size pages %lu\n"
		"   FIELDS: ",
		index->name,
4010 4011
		(ulong) ut_dulint_get_high(index->id),
		(ulong) ut_dulint_get_low(index->id),
osku's avatar
osku committed
4012
		(ulong) index->n_user_defined_cols,
4013 4014 4015
		(ulong) index->n_fields,
		(ulong) index->n_uniq,
		(ulong) index->type,
4016
		(ulong) index->page,
osku's avatar
osku committed
4017 4018 4019
		(ulong) n_vals,
		(ulong) index->stat_n_leaf_pages,
		(ulong) index->stat_index_size);
4020

osku's avatar
osku committed
4021 4022 4023 4024 4025 4026 4027
	for (i = 0; i < index->n_fields; i++) {
		dict_field_print_low(dict_index_get_nth_field(index, i));
	}

	putc('\n', stderr);

#ifdef UNIV_BTR_PRINT
4028
	btr_print_size(index);
osku's avatar
osku committed
4029

4030
	btr_print_index(index, 7);
osku's avatar
osku committed
4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042
#endif /* UNIV_BTR_PRINT */
}

/**************************************************************************
Prints a field data. */
static
void
dict_field_print_low(
/*=================*/
	dict_field_t*	field)	/* in: field */
{
	ut_ad(mutex_own(&(dict_sys->mutex)));
marko's avatar
marko committed
4043

osku's avatar
osku committed
4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064
	fprintf(stderr, " %s", field->name);

	if (field->prefix_len != 0) {
		fprintf(stderr, "(%lu)", (ulong) field->prefix_len);
	}
}

/**************************************************************************
Outputs info on a foreign key of a table in a format suitable for
CREATE TABLE. */

void
dict_print_info_on_foreign_key_in_create_format(
/*============================================*/
	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 */
{
	const char*	stripped_id;
	ulint	i;
4065

osku's avatar
osku committed
4066 4067 4068
	if (strchr(foreign->id, '/')) {
		/* Strip the preceding database name from the constraint id */
		stripped_id = foreign->id + 1
4069
			+ dict_get_db_name_len(foreign->id);
osku's avatar
osku committed
4070 4071 4072 4073 4074
	} else {
		stripped_id = foreign->id;
	}

	putc(',', file);
4075

osku's avatar
osku committed
4076 4077 4078 4079 4080 4081
	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);
	}
4082

osku's avatar
osku committed
4083
	fputs(" CONSTRAINT ", file);
4084
	ut_print_name(file, trx, FALSE, stripped_id);
osku's avatar
osku committed
4085 4086 4087
	fputs(" FOREIGN KEY (", file);

	for (i = 0;;) {
4088
		ut_print_name(file, trx, FALSE, foreign->foreign_col_names[i]);
osku's avatar
osku committed
4089 4090
		if (++i < foreign->n_fields) {
			fputs(", ", file);
4091
		} else {
osku's avatar
osku committed
4092 4093 4094 4095 4096 4097 4098
			break;
		}
	}

	fputs(") REFERENCES ", file);

	if (dict_tables_have_same_db(foreign->foreign_table_name,
4099
				     foreign->referenced_table_name)) {
osku's avatar
osku committed
4100
		/* Do not print the database name of the referenced table */
4101 4102 4103
		ut_print_name(file, trx, TRUE,
			      dict_remove_db_name(
				      foreign->referenced_table_name));
osku's avatar
osku committed
4104
	} else {
4105
		ut_print_name(file, trx, TRUE,
4106
			      foreign->referenced_table_name);
osku's avatar
osku committed
4107 4108 4109 4110 4111 4112
	}

	putc(' ', file);
	putc('(', file);

	for (i = 0;;) {
4113
		ut_print_name(file, trx, FALSE,
4114
			      foreign->referenced_col_names[i]);
osku's avatar
osku committed
4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126
		if (++i < foreign->n_fields) {
			fputs(", ", file);
		} else {
			break;
		}
	}

	putc(')', file);

	if (foreign->type & DICT_FOREIGN_ON_DELETE_CASCADE) {
		fputs(" ON DELETE CASCADE", file);
	}
4127

osku's avatar
osku committed
4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138
	if (foreign->type & DICT_FOREIGN_ON_DELETE_SET_NULL) {
		fputs(" ON DELETE SET NULL", file);
	}

	if (foreign->type & DICT_FOREIGN_ON_DELETE_NO_ACTION) {
		fputs(" ON DELETE NO ACTION", file);
	}

	if (foreign->type & DICT_FOREIGN_ON_UPDATE_CASCADE) {
		fputs(" ON UPDATE CASCADE", file);
	}
4139

osku's avatar
osku committed
4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176
	if (foreign->type & DICT_FOREIGN_ON_UPDATE_SET_NULL) {
		fputs(" ON UPDATE SET NULL", file);
	}

	if (foreign->type & DICT_FOREIGN_ON_UPDATE_NO_ACTION) {
		fputs(" ON UPDATE NO ACTION", file);
	}
}

/**************************************************************************
Outputs info on foreign keys of a table. */

void
dict_print_info_on_foreign_keys(
/*============================*/
	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 */
	FILE*		file,	/* in: file where to print */
	trx_t*		trx,	/* in: transaction */
	dict_table_t*	table)	/* in: table */
{
	dict_foreign_t*	foreign;

	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) {
		if (create_table_format) {
4177 4178
			dict_print_info_on_foreign_key_in_create_format(
				file, trx, foreign, TRUE);
osku's avatar
osku committed
4179 4180 4181 4182 4183 4184 4185 4186 4187
		} else {
			ulint	i;
			fputs("; (", file);

			for (i = 0; i < foreign->n_fields; i++) {
				if (i) {
					putc(' ', file);
				}

4188
				ut_print_name(file, trx, FALSE,
4189
					      foreign->foreign_col_names[i]);
osku's avatar
osku committed
4190 4191 4192
			}

			fputs(") REFER ", file);
4193
			ut_print_name(file, trx, TRUE,
4194
				      foreign->referenced_table_name);
osku's avatar
osku committed
4195 4196 4197 4198 4199 4200
			putc('(', file);

			for (i = 0; i < foreign->n_fields; i++) {
				if (i) {
					putc(' ', file);
				}
4201 4202 4203
				ut_print_name(
					file, trx, FALSE,
					foreign->referenced_col_names[i]);
osku's avatar
osku committed
4204 4205 4206 4207 4208 4209 4210
			}

			putc(')', file);

			if (foreign->type == DICT_FOREIGN_ON_DELETE_CASCADE) {
				fputs(" ON DELETE CASCADE", file);
			}
4211

osku's avatar
osku committed
4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222
			if (foreign->type == DICT_FOREIGN_ON_DELETE_SET_NULL) {
				fputs(" ON DELETE SET NULL", file);
			}

			if (foreign->type & DICT_FOREIGN_ON_DELETE_NO_ACTION) {
				fputs(" ON DELETE NO ACTION", file);
			}

			if (foreign->type & DICT_FOREIGN_ON_UPDATE_CASCADE) {
				fputs(" ON UPDATE CASCADE", file);
			}
4223

osku's avatar
osku committed
4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248
			if (foreign->type & DICT_FOREIGN_ON_UPDATE_SET_NULL) {
				fputs(" ON UPDATE SET NULL", file);
			}

			if (foreign->type & DICT_FOREIGN_ON_UPDATE_NO_ACTION) {
				fputs(" ON UPDATE NO ACTION", file);
			}
		}

		foreign = UT_LIST_GET_NEXT(foreign_list, foreign);
	}

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

/************************************************************************
Displays the names of the index and the table. */
void
dict_index_name_print(
/*==================*/
	FILE*			file,	/* in: output stream */
	trx_t*			trx,	/* in: transaction */
	const dict_index_t*	index)	/* in: index to print */
{
	fputs("index ", file);
4249
	ut_print_name(file, trx, FALSE, index->name);
osku's avatar
osku committed
4250
	fputs(" of table ", file);
4251
	ut_print_name(file, trx, TRUE, index->table_name);
osku's avatar
osku committed
4252
}