dict0crea.cc 66.3 KB
Newer Older
1 2
/*****************************************************************************

3
Copyright (c) 1996, 2016, Oracle and/or its affiliates. All Rights Reserved.
Marko Mäkelä's avatar
Marko Mäkelä committed
4
Copyright (c) 2017, 2018, MariaDB Corporation.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA

*****************************************************************************/

/**************************************************//**
@file dict/dict0crea.cc
Database object creation

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

27 28
#include "ha_prototypes.h"

29 30 31 32 33 34 35 36 37 38 39 40
#include "dict0crea.h"
#include "btr0pcur.h"
#include "btr0btr.h"
#include "page0page.h"
#include "mach0data.h"
#include "dict0boot.h"
#include "dict0dict.h"
#include "que0que.h"
#include "row0ins.h"
#include "row0mysql.h"
#include "pars0pars.h"
#include "trx0roll.h"
41
#include "trx0rseg.h"
42
#include "trx0undo.h"
43 44 45
#include "ut0vec.h"
#include "dict0priv.h"
#include "fts0priv.h"
46 47 48
#include "fsp0space.h"
#include "fsp0sysspace.h"
#include "srv0start.h"
49 50 51 52

/*****************************************************************//**
Based on a table object, this function builds the entry to be inserted
in the SYS_TABLES system table.
53
@return the tuple which should be inserted */
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
static
dtuple_t*
dict_create_sys_tables_tuple(
/*=========================*/
	const dict_table_t*	table,	/*!< in: table */
	mem_heap_t*		heap)	/*!< in: memory heap from
					which the memory for the built
					tuple is allocated */
{
	dict_table_t*	sys_tables;
	dtuple_t*	entry;
	dfield_t*	dfield;
	byte*		ptr;
	ulint		type;

	ut_ad(table);
70
	ut_ad(!table->space || table->space->id == table->space_id);
71
	ut_ad(heap);
72
	ut_ad(table->n_cols >= DATA_N_SYS_COLS);
73 74 75 76 77 78 79 80 81 82 83

	sys_tables = dict_sys->sys_tables;

	entry = dtuple_create(heap, 8 + DATA_N_SYS_COLS);

	dict_table_copy_types(entry, sys_tables);

	/* 0: NAME -----------------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_TABLES__NAME);

84 85
	dfield_set_data(dfield,
			table->name.m_name, strlen(table->name.m_name));
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

	/* 1: DB_TRX_ID added later */
	/* 2: DB_ROLL_PTR added later */
	/* 3: ID -------------------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_TABLES__ID);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 8));
	mach_write_to_8(ptr, table->id);

	dfield_set_data(dfield, ptr, 8);

	/* 4: N_COLS ---------------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_TABLES__N_COLS);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
103 104 105

	/* If there is any virtual column, encode it in N_COLS */
	mach_write_to_4(ptr, dict_table_encode_n_col(
106 107 108
				ulint(table->n_cols - DATA_N_SYS_COLS),
				ulint(table->n_v_def))
			| (ulint(table->flags & DICT_TF_COMPACT) << 31));
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
	dfield_set_data(dfield, ptr, 4);

	/* 5: TYPE (table flags) -----------------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_TABLES__TYPE);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));

	/* Validate the table flags and convert them to what is saved in
	SYS_TABLES.TYPE.  Table flag values 0 and 1 are both written to
	SYS_TABLES.TYPE as 1. */
	type = dict_tf_to_sys_tables_type(table->flags);
	mach_write_to_4(ptr, type);

	dfield_set_data(dfield, ptr, 4);

	/* 6: MIX_ID (obsolete) ---------------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_TABLES__MIX_ID);

	ptr = static_cast<byte*>(mem_heap_zalloc(heap, 8));

	dfield_set_data(dfield, ptr, 8);

	/* 7: MIX_LEN (additional flags) --------------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_TABLES__MIX_LEN);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
	/* Be sure all non-used bits are zero. */
139
	ut_a(!(table->flags2 & DICT_TF2_UNUSED_BIT_MASK));
140 141 142 143 144 145 146 147 148 149 150 151 152 153
	mach_write_to_4(ptr, table->flags2);

	dfield_set_data(dfield, ptr, 4);

	/* 8: CLUSTER_NAME ---------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_TABLES__CLUSTER_ID);
	dfield_set_null(dfield); /* not supported */

	/* 9: SPACE ----------------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_TABLES__SPACE);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
154
	mach_write_to_4(ptr, table->space_id);
155 156 157 158 159 160 161 162 163 164

	dfield_set_data(dfield, ptr, 4);
	/*----------------------------------*/

	return(entry);
}

/*****************************************************************//**
Based on a table object, this function builds the entry to be inserted
in the SYS_COLUMNS system table.
165
@return the tuple which should be inserted */
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
static
dtuple_t*
dict_create_sys_columns_tuple(
/*==========================*/
	const dict_table_t*	table,	/*!< in: table */
	ulint			i,	/*!< in: column number */
	mem_heap_t*		heap)	/*!< in: memory heap from
					which the memory for the built
					tuple is allocated */
{
	dict_table_t*		sys_columns;
	dtuple_t*		entry;
	const dict_col_t*	column;
	dfield_t*		dfield;
	byte*			ptr;
	const char*		col_name;
182 183
	ulint			num_base = 0;
	ulint			v_col_no = ULINT_UNDEFINED;
184 185 186 187

	ut_ad(table);
	ut_ad(heap);

188 189 190 191 192 193 194 195 196
	/* Any column beyond table->n_def would be virtual columns */
        if (i >= table->n_def) {
		dict_v_col_t*	v_col = dict_table_get_nth_v_col(
					table, i - table->n_def);
		column = &v_col->m_col;
		num_base = v_col->num_base;
		v_col_no = column->ind;
	} else {
		column = dict_table_get_nth_col(table, i);
197
		ut_ad(!column->is_virtual());
198
	}
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217

	sys_columns = dict_sys->sys_columns;

	entry = dtuple_create(heap, 7 + DATA_N_SYS_COLS);

	dict_table_copy_types(entry, sys_columns);

	/* 0: TABLE_ID -----------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_COLUMNS__TABLE_ID);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 8));
	mach_write_to_8(ptr, table->id);

	dfield_set_data(dfield, ptr, 8);

	/* 1: POS ----------------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_COLUMNS__POS);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
218 219 220 221 222 223 224 225 226

	if (v_col_no != ULINT_UNDEFINED) {
		/* encode virtual column's position in MySQL table and InnoDB
		table in "POS" */
		mach_write_to_4(ptr, dict_create_v_col_pos(
				i - table->n_def, v_col_no));
	} else {
		mach_write_to_4(ptr, i);
	}
227 228 229 230 231 232 233 234

	dfield_set_data(dfield, ptr, 4);

	/* 2: DB_TRX_ID added later */
	/* 3: DB_ROLL_PTR added later */
	/* 4: NAME ---------------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_COLUMNS__NAME);

235 236 237 238 239 240
        if (i >= table->n_def) {
		col_name = dict_table_get_v_col_name(table, i - table->n_def);
	} else {
		col_name = dict_table_get_col_name(table, i);
	}

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
	dfield_set_data(dfield, col_name, ut_strlen(col_name));

	/* 5: MTYPE --------------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_COLUMNS__MTYPE);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
	mach_write_to_4(ptr, column->mtype);

	dfield_set_data(dfield, ptr, 4);

	/* 6: PRTYPE -------------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_COLUMNS__PRTYPE);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
	mach_write_to_4(ptr, column->prtype);

	dfield_set_data(dfield, ptr, 4);

	/* 7: LEN ----------------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_COLUMNS__LEN);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
	mach_write_to_4(ptr, column->len);

	dfield_set_data(dfield, ptr, 4);

	/* 8: PREC ---------------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_COLUMNS__PREC);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
271
	mach_write_to_4(ptr, num_base);
272 273 274 275 276 277 278

	dfield_set_data(dfield, ptr, 4);
	/*---------------------------------*/

	return(entry);
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
/** Based on a table object, this function builds the entry to be inserted
in the SYS_VIRTUAL system table. Each row maps a virtual column to one of
its base column.
@param[in]	table	table
@param[in]	v_col_n	virtual column number
@param[in]	b_col_n	base column sequence num
@param[in]	heap	memory heap
@return the tuple which should be inserted */
static
dtuple_t*
dict_create_sys_virtual_tuple(
	const dict_table_t*	table,
	ulint			v_col_n,
	ulint			b_col_n,
	mem_heap_t*		heap)
{
	dict_table_t*		sys_virtual;
	dtuple_t*		entry;
	const dict_col_t*	base_column;
	dfield_t*		dfield;
	byte*			ptr;

	ut_ad(table);
	ut_ad(heap);

	ut_ad(v_col_n < table->n_v_def);
	dict_v_col_t*	v_col = dict_table_get_nth_v_col(table, v_col_n);
	base_column = v_col->base_col[b_col_n];

	sys_virtual = dict_sys->sys_virtual;

	entry = dtuple_create(heap, DICT_NUM_COLS__SYS_VIRTUAL
			      + DATA_N_SYS_COLS);

	dict_table_copy_types(entry, sys_virtual);

	/* 0: TABLE_ID -----------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_VIRTUAL__TABLE_ID);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 8));
	mach_write_to_8(ptr, table->id);

	dfield_set_data(dfield, ptr, 8);

	/* 1: POS ---------------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_VIRTUAL__POS);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
	ulint	v_col_no = dict_create_v_col_pos(v_col_n, v_col->m_col.ind);
	mach_write_to_4(ptr, v_col_no);

	dfield_set_data(dfield, ptr, 4);

	/* 2: BASE_POS ----------------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_VIRTUAL__BASE_POS);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
	mach_write_to_4(ptr, base_column->ind);

	dfield_set_data(dfield, ptr, 4);

	/* 3: DB_TRX_ID added later */
	/* 4: DB_ROLL_PTR added later */

	/*---------------------------------*/
	return(entry);
}

347 348
/***************************************************************//**
Builds a table definition to insert.
349
@return DB_SUCCESS or error code */
Sergei Golubchik's avatar
Sergei Golubchik committed
350
static MY_ATTRIBUTE((nonnull, warn_unused_result))
351 352 353 354 355 356
dberr_t
dict_build_table_def_step(
/*======================*/
	que_thr_t*	thr,	/*!< in: query thread */
	tab_node_t*	node)	/*!< in: table create node */
{
357
	ut_ad(mutex_own(&dict_sys->mutex));
358 359
	dict_table_t*	table = node->table;
	ut_ad(!table->is_temporary());
360 361
	ut_ad(!table->space);
	ut_ad(table->space_id == ULINT_UNDEFINED);
362
	dict_table_assign_new_id(table, thr_get_trx(thr));
363

364
	/* Always set this bit for all new created tables */
Sergei Golubchik's avatar
Sergei Golubchik committed
365 366 367 368 369
	DICT_TF2_FLAG_SET(table, DICT_TF2_FTS_AUX_HEX_NAME);
	DBUG_EXECUTE_IF("innodb_test_wrong_fts_aux_table_name",
			DICT_TF2_FLAG_UNSET(table,
					    DICT_TF2_FTS_AUX_HEX_NAME););

370
	if (DICT_TF2_FLAG_IS_SET(table, DICT_TF2_USE_FILE_PER_TABLE)) {
371 372 373
		/* This table will need a new tablespace. */

		ut_ad(DICT_TF_GET_ZIP_SSIZE(table->flags) == 0
374
		      || dict_table_has_atomic_blobs(table));
375
		trx_t* trx = thr_get_trx(thr);
376 377
		ut_ad(trx->table_id);
		mtr_t mtr;
378
		trx_undo_t* undo = trx->rsegs.m_redo.undo;
379 380 381 382 383 384 385 386
		if (undo && !undo->table_id
		    && trx_get_dict_operation(trx) == TRX_DICT_OP_TABLE) {
			/* This must be a TRUNCATE operation where
			the empty table is created after the old table
			was renamed. Be sure to mark the transaction
			associated with the new empty table, so that
			we can remove it on recovery. */
			mtr.start();
387 388 389 390 391 392 393 394 395 396 397 398
			undo->table_id = trx->table_id;
			undo->dict_operation = TRUE;
			page_t* page = trx_undo_page_get(
				page_id_t(trx->rsegs.m_redo.rseg->space->id,
					  undo->hdr_page_no),
				&mtr);
			mlog_write_ulint(page + undo->hdr_offset
					 + TRX_UNDO_DICT_TRANS,
					 TRUE, MLOG_1BYTE, &mtr);
			mlog_write_ull(page + undo->hdr_offset
				       + TRX_UNDO_TABLE_ID,
				       trx->table_id, &mtr);
399 400 401
			mtr.commit();
			log_write_up_to(mtr.commit_lsn(), true);
		}
402
		/* Get a new tablespace ID */
403 404
		ulint space_id;
		dict_hdr_get_new_id(NULL, NULL, &space_id, table, false);
405 406 407

		DBUG_EXECUTE_IF(
			"ib_create_table_fail_out_of_space_ids",
408
			space_id = ULINT_UNDEFINED;
409 410
		);

411
		if (space_id == ULINT_UNDEFINED) {
412
			return DB_ERROR;
413
		}
414 415 416

		/* Determine the tablespace flags. */
		bool	has_data_dir = DICT_TF_HAS_DATA_DIR(table->flags);
417
		ulint	fsp_flags = dict_tf_to_fsp_flags(table->flags);
418 419 420 421 422 423
		ut_ad(!has_data_dir || table->data_dir_path);
		char*	filepath = has_data_dir
			? fil_make_filepath(table->data_dir_path,
					    table->name.m_name, IBD, true)
			: fil_make_filepath(NULL,
					    table->name.m_name, IBD, false);
424 425 426 427 428 429

		/* We create a new single-table tablespace for the table.
		We initially let it be 4 pages:
		- page 0 is the fsp header and an extent descriptor page,
		- page 1 is an ibuf bitmap page,
		- page 2 is the first inode page,
430 431
		- page 3 will contain the root of the clustered index of
		the table we create here. */
432

433
		dberr_t err;
434
		table->space = fil_ibd_create(
435
			space_id, table->name.m_name, filepath, fsp_flags,
436
			FIL_IBD_FILE_INITIAL_SIZE,
437
			node->mode, node->key_id, &err);
438

439
		ut_free(filepath);
440

441
		if (!table->space) {
442 443
			ut_ad(err != DB_SUCCESS);
			return err;
444 445
		}

446
		table->space_id = space_id;
447
		mtr.start();
448 449
		mtr.set_named_space(table->space);
		fsp_header_init(table->space, FIL_IBD_FILE_INITIAL_SIZE, &mtr);
450
		mtr.commit();
451
	} else {
452 453
		ut_ad(dict_tf_get_rec_format(table->flags)
		      != REC_FORMAT_COMPRESSED);
454 455
		table->space = fil_system.sys_space;
		table->space_id = TRX_SYS_SPACE;
456
	}
457

458 459 460
	ins_node_set_new_row(node->tab_def,
			     dict_create_sys_tables_tuple(table, node->heap));
	return DB_SUCCESS;
461 462
}

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
/** Builds a SYS_VIRTUAL row definition to insert.
@param[in]	node	table create node */
static
void
dict_build_v_col_def_step(
	tab_node_t*	node)
{
	dtuple_t*	row;

	row = dict_create_sys_virtual_tuple(node->table, node->col_no,
					    node->base_col_no,
					    node->heap);
	ins_node_set_new_row(node->v_col_def, row);
}

478 479 480
/*****************************************************************//**
Based on an index object, this function builds the entry to be inserted
in the SYS_INDEXES system table.
481
@return the tuple which should be inserted */
482 483 484 485 486 487 488 489 490 491 492 493 494 495
static
dtuple_t*
dict_create_sys_indexes_tuple(
/*==========================*/
	const dict_index_t*	index,	/*!< in: index */
	mem_heap_t*		heap)	/*!< in: memory heap from
					which the memory for the built
					tuple is allocated */
{
	dict_table_t*	sys_indexes;
	dtuple_t*	entry;
	dfield_t*	dfield;
	byte*		ptr;

496
	ut_ad(mutex_own(&dict_sys->mutex));
497
	ut_ad(index);
498 499 500
	ut_ad(index->table->space || index->table->file_unreadable);
	ut_ad(!index->table->space
	      || index->table->space->id == index->table->space_id);
501 502 503 504
	ut_ad(heap);

	sys_indexes = dict_sys->sys_indexes;

505 506
	entry = dtuple_create(
		heap, DICT_NUM_COLS__SYS_INDEXES + DATA_N_SYS_COLS);
507 508 509 510 511 512 513 514

	dict_table_copy_types(entry, sys_indexes);

	/* 0: TABLE_ID -----------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_INDEXES__TABLE_ID);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 8));
515
	mach_write_to_8(ptr, index->table->id);
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533

	dfield_set_data(dfield, ptr, 8);

	/* 1: ID ----------------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_INDEXES__ID);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 8));
	mach_write_to_8(ptr, index->id);

	dfield_set_data(dfield, ptr, 8);

	/* 2: DB_TRX_ID added later */
	/* 3: DB_ROLL_PTR added later */
	/* 4: NAME --------------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_INDEXES__NAME);

534 535 536 537 538 539 540 541 542 543
	if (!index->is_committed()) {
		ulint	len	= strlen(index->name) + 1;
		char*	name	= static_cast<char*>(
			mem_heap_alloc(heap, len));
		*name = *TEMP_INDEX_PREFIX_STR;
		memcpy(name + 1, index->name, len - 1);
		dfield_set_data(dfield, name, len);
	} else {
		dfield_set_data(dfield, index->name, strlen(index->name));
	}
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568

	/* 5: N_FIELDS ----------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_INDEXES__N_FIELDS);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
	mach_write_to_4(ptr, index->n_fields);

	dfield_set_data(dfield, ptr, 4);

	/* 6: TYPE --------------------------*/
	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_INDEXES__TYPE);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
	mach_write_to_4(ptr, index->type);

	dfield_set_data(dfield, ptr, 4);

	/* 7: SPACE --------------------------*/

	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_INDEXES__SPACE);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
569
	mach_write_to_4(ptr, index->table->space_id);
570 571 572 573 574 575 576 577 578 579 580 581 582

	dfield_set_data(dfield, ptr, 4);

	/* 8: PAGE_NO --------------------------*/

	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_INDEXES__PAGE_NO);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
	mach_write_to_4(ptr, FIL_NULL);

	dfield_set_data(dfield, ptr, 4);

583 584 585 586 587 588 589 590 591 592
	/* 9: MERGE_THRESHOLD ----------------*/

	dfield = dtuple_get_nth_field(
		entry, DICT_COL__SYS_INDEXES__MERGE_THRESHOLD);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));
	mach_write_to_4(ptr, DICT_INDEX_MERGE_THRESHOLD_DEFAULT);

	dfield_set_data(dfield, ptr, 4);

593 594 595 596 597 598 599 600
	/*--------------------------------*/

	return(entry);
}

/*****************************************************************//**
Based on an index object, this function builds the entry to be inserted
in the SYS_FIELDS system table.
601
@return the tuple which should be inserted */
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
static
dtuple_t*
dict_create_sys_fields_tuple(
/*=========================*/
	const dict_index_t*	index,	/*!< in: index */
	ulint			fld_no,	/*!< in: field number */
	mem_heap_t*		heap)	/*!< in: memory heap from
					which the memory for the built
					tuple is allocated */
{
	dict_table_t*	sys_fields;
	dtuple_t*	entry;
	dict_field_t*	field;
	dfield_t*	dfield;
	byte*		ptr;
	ibool		index_contains_column_prefix_field	= FALSE;
	ulint		j;

	ut_ad(index);
	ut_ad(heap);

	for (j = 0; j < index->n_fields; j++) {
		if (dict_index_get_nth_field(index, j)->prefix_len > 0) {
			index_contains_column_prefix_field = TRUE;
			break;
		}
	}

	field = dict_index_get_nth_field(index, fld_no);

	sys_fields = dict_sys->sys_fields;

	entry = dtuple_create(heap, 3 + DATA_N_SYS_COLS);

	dict_table_copy_types(entry, sys_fields);

	/* 0: INDEX_ID -----------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_FIELDS__INDEX_ID);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 8));
	mach_write_to_8(ptr, index->id);

	dfield_set_data(dfield, ptr, 8);

	/* 1: POS; FIELD NUMBER & PREFIX LENGTH -----------------------*/

	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_FIELDS__POS);

	ptr = static_cast<byte*>(mem_heap_alloc(heap, 4));

	if (index_contains_column_prefix_field) {
		/* If there are column prefix fields in the index, then
		we store the number of the field to the 2 HIGH bytes
		and the prefix length to the 2 low bytes, */

		mach_write_to_4(ptr, (fld_no << 16) + field->prefix_len);
	} else {
		/* Else we store the number of the field to the 2 LOW bytes.
		This is to keep the storage format compatible with
		InnoDB versions < 4.0.14. */

		mach_write_to_4(ptr, fld_no);
	}

	dfield_set_data(dfield, ptr, 4);

	/* 2: DB_TRX_ID added later */
	/* 3: DB_ROLL_PTR added later */
	/* 4: COL_NAME -------------------------*/
	dfield = dtuple_get_nth_field(entry, DICT_COL__SYS_FIELDS__COL_NAME);

	dfield_set_data(dfield, field->name,
			ut_strlen(field->name));
	/*---------------------------------*/

	return(entry);
}

/*****************************************************************//**
Creates the tuple with which the index entry is searched for writing the index
tree root page number, if such a tree is created.
683
@return the tuple for search */
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
static
dtuple_t*
dict_create_search_tuple(
/*=====================*/
	const dtuple_t*	tuple,	/*!< in: the tuple inserted in the SYS_INDEXES
				table */
	mem_heap_t*	heap)	/*!< in: memory heap from which the memory for
				the built tuple is allocated */
{
	dtuple_t*	search_tuple;
	const dfield_t*	field1;
	dfield_t*	field2;

	ut_ad(tuple && heap);

	search_tuple = dtuple_create(heap, 2);

	field1 = dtuple_get_nth_field(tuple, 0);
	field2 = dtuple_get_nth_field(search_tuple, 0);

	dfield_copy(field2, field1);

	field1 = dtuple_get_nth_field(tuple, 1);
	field2 = dtuple_get_nth_field(search_tuple, 1);

	dfield_copy(field2, field1);

	ut_ad(dtuple_validate(search_tuple));

	return(search_tuple);
}

/***************************************************************//**
Builds an index definition row to insert.
718
@return DB_SUCCESS or error code */
Sergei Golubchik's avatar
Sergei Golubchik committed
719
static MY_ATTRIBUTE((nonnull, warn_unused_result))
720 721 722 723 724 725 726 727 728 729 730
dberr_t
dict_build_index_def_step(
/*======================*/
	que_thr_t*	thr,	/*!< in: query thread */
	ind_node_t*	node)	/*!< in: index create node */
{
	dict_table_t*	table;
	dict_index_t*	index;
	dtuple_t*	row;
	trx_t*		trx;

731
	ut_ad(mutex_own(&dict_sys->mutex));
732 733 734 735 736

	trx = thr_get_trx(thr);

	index = node->index;

737 738
	table = index->table = node->table = dict_table_open_on_name(
		node->table_name, TRUE, FALSE, DICT_ERR_IGNORE_NONE);
739 740 741 742 743 744 745 746 747 748 749 750 751

	if (table == NULL) {
		return(DB_TABLE_NOT_FOUND);
	}

	if (!trx->table_id) {
		/* Record only the first table id. */
		trx->table_id = table->id;
	}

	ut_ad((UT_LIST_GET_LEN(table->indexes) > 0)
	      || dict_index_is_clust(index));

752
	dict_hdr_get_new_id(NULL, &index->id, NULL, table, false);
753 754 755 756 757 758 759 760 761 762 763 764 765 766

	/* Inherit the space id from the table; we store all indexes of a
	table in the same tablespace */

	node->page_no = FIL_NULL;
	row = dict_create_sys_indexes_tuple(index, node->heap);
	node->ind_row = row;

	ins_node_set_new_row(node->ind_def, row);

	/* Note that the index was created by this transaction. */
	index->trx_id = trx->id;
	ut_ad(table->def_trx_id <= trx->id);
	table->def_trx_id = trx->id;
767
	dict_table_close(table, true, false);
768 769 770 771

	return(DB_SUCCESS);
}

772 773 774 775 776 777 778 779 780 781
/***************************************************************//**
Builds an index definition without updating SYSTEM TABLES.
@return DB_SUCCESS or error code */
void
dict_build_index_def(
/*=================*/
	const dict_table_t*	table,	/*!< in: table */
	dict_index_t*		index,	/*!< in/out: index */
	trx_t*			trx)	/*!< in/out: InnoDB transaction handle */
{
782
	ut_ad(mutex_own(&dict_sys->mutex));
783 784 785 786 787 788 789 790 791

	if (trx->table_id == 0) {
		/* Record only the first table id. */
		trx->table_id = table->id;
	}

	ut_ad((UT_LIST_GET_LEN(table->indexes) > 0)
	      || dict_index_is_clust(index));

792
	dict_hdr_get_new_id(NULL, &index->id, NULL, table, false);
793 794 795 796 797

	/* Note that the index was created by this transaction. */
	index->trx_id = trx->id;
}

798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
/***************************************************************//**
Builds a field definition row to insert. */
static
void
dict_build_field_def_step(
/*======================*/
	ind_node_t*	node)	/*!< in: index create node */
{
	dict_index_t*	index;
	dtuple_t*	row;

	index = node->index;

	row = dict_create_sys_fields_tuple(index, node->field_no, node->heap);

	ins_node_set_new_row(node->field_def, row);
}

/***************************************************************//**
Creates an index tree for the index if it is not a member of a cluster.
818
@return DB_SUCCESS or DB_OUT_OF_FILE_SPACE */
Sergei Golubchik's avatar
Sergei Golubchik committed
819
static MY_ATTRIBUTE((nonnull, warn_unused_result))
820 821 822 823 824
dberr_t
dict_create_index_tree_step(
/*========================*/
	ind_node_t*	node)	/*!< in: index create node */
{
825 826
	mtr_t		mtr;
	btr_pcur_t	pcur;
827 828 829 830
	dict_index_t*	index;
	dict_table_t*	sys_indexes;
	dtuple_t*	search_tuple;

831
	ut_ad(mutex_own(&dict_sys->mutex));
832 833 834 835 836 837 838 839 840 841 842 843 844 845

	index = node->index;

	sys_indexes = dict_sys->sys_indexes;

	if (index->type == DICT_FTS) {
		/* FTS index does not need an index tree */
		return(DB_SUCCESS);
	}

	/* Run a mini-transaction in which the index tree is allocated for
	the index and its root address is written to the index entry in
	sys_indexes */

846
	mtr.start();
847

848 849 850 851 852 853 854 855 856 857 858
	search_tuple = dict_create_search_tuple(node->ind_row, node->heap);

	btr_pcur_open(UT_LIST_GET_FIRST(sys_indexes->indexes),
		      search_tuple, PAGE_CUR_L, BTR_MODIFY_LEAF,
		      &pcur, &mtr);

	btr_pcur_move_to_next_user_rec(&pcur, &mtr);


	dberr_t		err = DB_SUCCESS;

859
	if (!index->is_readable()) {
860 861
		node->page_no = FIL_NULL;
	} else {
862 863
		index->set_modified(mtr);

864
		node->page_no = btr_create(
865
			index->type, index->table->space,
866
			index->id, index, NULL, &mtr);
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882

		if (node->page_no == FIL_NULL) {
			err = DB_OUT_OF_FILE_SPACE;
		}

		DBUG_EXECUTE_IF("ib_import_create_index_failure_1",
				node->page_no = FIL_NULL;
				err = DB_OUT_OF_FILE_SPACE; );
	}

	page_rec_write_field(
		btr_pcur_get_rec(&pcur), DICT_FLD__SYS_INDEXES__PAGE_NO,
		node->page_no, &mtr);

	btr_pcur_close(&pcur);

883
	mtr.commit();
884 885 886 887

	return(err);
}

888 889 890 891 892 893 894 895 896 897 898 899
/***************************************************************//**
Creates an index tree for the index if it is not a member of a cluster.
Don't update SYSTEM TABLES.
@return DB_SUCCESS or DB_OUT_OF_FILE_SPACE */
dberr_t
dict_create_index_tree_in_mem(
/*==========================*/
	dict_index_t*	index,	/*!< in/out: index */
	const trx_t*	trx)	/*!< in: InnoDB transaction handle */
{
	mtr_t		mtr;

900
	ut_ad(mutex_own(&dict_sys->mutex));
901
	ut_ad(!(index->type & DICT_FTS));
902 903 904 905 906 907

	mtr_start(&mtr);
	mtr_set_log_mode(&mtr, MTR_LOG_NO_REDO);

	/* Currently this function is being used by temp-tables only.
	Import/Discard of temp-table is blocked and so this assert. */
908
	ut_ad(index->is_readable());
909
	ut_ad(!(index->table->flags2 & DICT_TF2_DISCARDED));
910

911 912 913
	index->page = btr_create(index->type, index->table->space,
				 index->id, index, NULL, &mtr);
	mtr_commit(&mtr);
914 915 916

	index->trx_id = trx->id;

917
	return index->page == FIL_NULL ? DB_OUT_OF_FILE_SPACE : DB_SUCCESS;
918 919 920 921 922 923 924 925
}

/** Drop the index tree associated with a row in SYS_INDEXES table.
@param[in,out]	rec	SYS_INDEXES record
@param[in,out]	pcur	persistent cursor on rec
@param[in,out]	mtr	mini-transaction
@return	whether freeing the B-tree was attempted */
bool
926
dict_drop_index_tree(
927 928 929
	rec_t*		rec,
	btr_pcur_t*	pcur,
	mtr_t*		mtr)
930 931 932
{
	const byte*	ptr;
	ulint		len;
933
	ulint		space;
934
	ulint		root_page_no;
935

936
	ut_ad(mutex_own(&dict_sys->mutex));
937
	ut_a(!dict_table_is_comp(dict_sys->sys_indexes));
938 939

	ptr = rec_get_nth_field_old(rec, DICT_FLD__SYS_INDEXES__PAGE_NO, &len);
940 941 942

	ut_ad(len == 4);

943 944
	btr_pcur_store_position(pcur, mtr);

945 946 947 948 949
	root_page_no = mtr_read_ulint(ptr, MLOG_4BYTES, mtr);

	if (root_page_no == FIL_NULL) {
		/* The tree has already been freed */

950
		return(false);
951 952
	}

953 954
	mlog_write_ulint(const_cast<byte*>(ptr), FIL_NULL, MLOG_4BYTES, mtr);

955 956 957 958 959
	ptr = rec_get_nth_field_old(
		rec, DICT_FLD__SYS_INDEXES__SPACE, &len);

	ut_ad(len == 4);

960
	space = mtr_read_ulint(ptr, MLOG_4BYTES, mtr);
961

962 963 964 965 966
	ptr = rec_get_nth_field_old(
		rec, DICT_FLD__SYS_INDEXES__ID, &len);

	ut_ad(len == 8);

967 968 969 970 971 972 973 974 975 976 977
	bool			found;
	const page_size_t	page_size(fil_space_get_page_size(space,
								  &found));

	if (!found) {
		/* It is a single table tablespace and the .ibd file is
		missing: do nothing */

		return(false);
	}

978 979 980
	/* If tablespace is scheduled for truncate, do not try to drop
	the indexes in that tablespace. There is a truncate fixup action
	which will take care of it. */
981 982
	if (srv_is_tablespace_truncated(space)) {
		return(false);
983
	}
984

985 986
	btr_free_if_exists(page_id_t(space, root_page_no), page_size,
			   mach_read_from_8(ptr), mtr);
987

988
	return(true);
989
}
990 991

/*******************************************************************//**
992
Recreate the index tree associated with a row in SYS_INDEXES table.
993 994
@return	new root page number, or FIL_NULL on failure */
ulint
995
dict_recreate_index_tree(
996
/*=====================*/
997 998
	const dict_table_t*
			table,	/*!< in/out: the table the index belongs to */
999 1000 1001 1002
	btr_pcur_t*	pcur,	/*!< in/out: persistent cursor pointing to
				record in the clustered index of
				SYS_INDEXES table. The cursor may be
				repositioned in this call. */
1003 1004
	mtr_t*		mtr)	/*!< in/out: mtr having the latch
				on the record page. */
1005
{
1006 1007
	ut_ad(mutex_own(&dict_sys->mutex));
	ut_a(!dict_table_is_comp(dict_sys->sys_indexes));
1008
	ut_ad(!table->space || table->space->id == table->space_id);
1009

1010
	ulint		len;
1011
	const rec_t*	rec = btr_pcur_get_rec(pcur);
1012

1013
	const byte*	ptr = rec_get_nth_field_old(
1014 1015 1016 1017
		rec, DICT_FLD__SYS_INDEXES__PAGE_NO, &len);

	ut_ad(len == 4);

1018 1019 1020
	ut_ad(table->space_id == mach_read_from_4(
		      rec_get_nth_field_old(rec, DICT_FLD__SYS_INDEXES__SPACE,
					    &len)));
1021 1022
	ut_ad(len == 4);

1023
	if (!table->space) {
1024 1025 1026 1027 1028 1029
		/* It is a single table tablespae and the .ibd file is
		missing: do nothing. */

		ib::warn()
			<< "Trying to TRUNCATE a missing .ibd file of table "
			<< table->name << "!";
1030 1031 1032 1033

		return(FIL_NULL);
	}

1034
	ptr = rec_get_nth_field_old(rec, DICT_FLD__SYS_INDEXES__TYPE, &len);
1035
	ut_ad(len == 4);
1036
	ulint	type = mach_read_from_4(ptr);
1037 1038 1039

	ptr = rec_get_nth_field_old(rec, DICT_FLD__SYS_INDEXES__ID, &len);
	ut_ad(len == 8);
1040
	index_id_t	index_id = mach_read_from_8(ptr);
1041 1042 1043 1044 1045 1046 1047 1048

	/* We will need to commit the mini-transaction in order to avoid
	deadlocks in the btr_create() call, because otherwise we would
	be freeing and allocating pages in the same mini-transaction. */
	btr_pcur_store_position(pcur, mtr);
	mtr_commit(mtr);

	mtr_start(mtr);
1049
	mtr->set_named_space(table->space);
1050 1051 1052
	btr_pcur_restore_position(BTR_MODIFY_LEAF, pcur, mtr);

	/* Find the index corresponding to this SYS_INDEXES record. */
1053 1054
	for (dict_index_t* index = UT_LIST_GET_FIRST(table->indexes);
	     index != NULL;
1055 1056
	     index = UT_LIST_GET_NEXT(indexes, index)) {
		if (index->id == index_id) {
1057 1058
			ulint root_page_no = (index->type & DICT_FTS)
				? FIL_NULL
1059
				: btr_create(type, table->space,
1060 1061 1062
					     index_id, index, NULL, mtr);
			index->page = unsigned(root_page_no);
			return root_page_no;
1063 1064 1065
		}
	}

1066 1067
	ib::error() << "Failed to create index with index id " << index_id
		<< " of table " << table->name;
1068 1069 1070 1071 1072 1073

	return(FIL_NULL);
}

/*********************************************************************//**
Creates a table create graph.
1074
@return own: table create node */
1075 1076 1077 1078 1079 1080
tab_node_t*
tab_create_graph_create(
/*====================*/
	dict_table_t*	table,	/*!< in: table to create, built as a memory data
				structure */
	mem_heap_t*	heap,	/*!< in: heap where created */
1081
	fil_encryption_t mode,	/*!< in: encryption mode */
1082
	uint32_t	key_id)	/*!< in: encryption key_id */
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
{
	tab_node_t*	node;

	node = static_cast<tab_node_t*>(
		mem_heap_alloc(heap, sizeof(tab_node_t)));

	node->common.type = QUE_NODE_CREATE_TABLE;

	node->table = table;

	node->state = TABLE_BUILD_TABLE_DEF;
	node->heap = mem_heap_create(256);
1095 1096
	node->mode = mode;
	node->key_id = key_id;
1097 1098 1099 1100 1101 1102 1103 1104 1105

	node->tab_def = ins_node_create(INS_DIRECT, dict_sys->sys_tables,
					heap);
	node->tab_def->common.parent = node;

	node->col_def = ins_node_create(INS_DIRECT, dict_sys->sys_columns,
					heap);
	node->col_def->common.parent = node;

1106 1107 1108
	node->v_col_def = ins_node_create(INS_DIRECT, dict_sys->sys_virtual,
                                          heap);
	node->v_col_def->common.parent = node;
1109 1110 1111 1112

	return(node);
}

1113 1114
/** Creates an index create graph.
@param[in]	index	index to create, built as a memory data structure
1115
@param[in]	table	table name
1116 1117 1118 1119
@param[in,out]	heap	heap where created
@param[in]	add_v	new virtual columns added in the same clause with
			add index
@return own: index create node */
1120 1121
ind_node_t*
ind_create_graph_create(
1122
	dict_index_t*		index,
1123
	const char*		table,
1124 1125
	mem_heap_t*		heap,
	const dict_add_v_col_t*	add_v)
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
{
	ind_node_t*	node;

	node = static_cast<ind_node_t*>(
		mem_heap_alloc(heap, sizeof(ind_node_t)));

	node->common.type = QUE_NODE_CREATE_INDEX;

	node->index = index;

1136 1137
	node->table_name = table;

1138 1139
	node->add_v = add_v;

1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
	node->state = INDEX_BUILD_INDEX_DEF;
	node->page_no = FIL_NULL;
	node->heap = mem_heap_create(256);

	node->ind_def = ins_node_create(INS_DIRECT,
					dict_sys->sys_indexes, heap);
	node->ind_def->common.parent = node;

	node->field_def = ins_node_create(INS_DIRECT,
					  dict_sys->sys_fields, heap);
	node->field_def->common.parent = node;

	return(node);
}

/***********************************************************//**
Creates a table. This is a high-level function used in SQL execution graphs.
1157
@return query thread to run next or NULL */
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
que_thr_t*
dict_create_table_step(
/*===================*/
	que_thr_t*	thr)	/*!< in: query thread */
{
	tab_node_t*	node;
	dberr_t		err	= DB_ERROR;
	trx_t*		trx;

	ut_ad(thr);
1168
	ut_ad(mutex_own(&dict_sys->mutex));
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

	trx = thr_get_trx(thr);

	node = static_cast<tab_node_t*>(thr->run_node);

	ut_ad(que_node_get_type(node) == QUE_NODE_CREATE_TABLE);

	if (thr->prev_node == que_node_get_parent(node)) {
		node->state = TABLE_BUILD_TABLE_DEF;
	}

	if (node->state == TABLE_BUILD_TABLE_DEF) {

		/* DO THE CHECKS OF THE CONSISTENCY CONSTRAINTS HERE */

		err = dict_build_table_def_step(thr, node);
		if (err != DB_SUCCESS) {

			goto function_exit;
		}

		node->state = TABLE_BUILD_COL_DEF;
		node->col_no = 0;

		thr->run_node = node->tab_def;

		return(thr);
	}

	if (node->state == TABLE_BUILD_COL_DEF) {

1200 1201 1202
		if (node->col_no + DATA_N_SYS_COLS
		    < (static_cast<ulint>(node->table->n_def)
		       + static_cast<ulint>(node->table->n_v_def))) {
1203

1204 1205 1206 1207
			ulint i = node->col_no++;
			if (i + DATA_N_SYS_COLS >= node->table->n_def) {
				i += DATA_N_SYS_COLS;
			}
1208

1209 1210 1211 1212
			ins_node_set_new_row(
				node->col_def,
				dict_create_sys_columns_tuple(node->table, i,
							      node->heap));
1213 1214 1215 1216 1217

			thr->run_node = node->col_def;

			return(thr);
		} else {
1218 1219 1220 1221
			/* Move on to SYS_VIRTUAL table */
			node->col_no = 0;
                        node->base_col_no = 0;
                        node->state = TABLE_BUILD_V_COL_DEF;
1222 1223 1224
		}
	}

1225 1226 1227 1228 1229
	if (node->state == TABLE_BUILD_V_COL_DEF) {

		if (node->col_no < static_cast<ulint>(node->table->n_v_def)) {
			dict_v_col_t*   v_col = dict_table_get_nth_v_col(
						node->table, node->col_no);
1230

1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
			/* If no base column */
			while (v_col->num_base == 0) {
				node->col_no++;
				if (node->col_no == static_cast<ulint>(
					(node->table)->n_v_def)) {
					node->state = TABLE_ADD_TO_CACHE;
					break;
				}

				v_col = dict_table_get_nth_v_col(
					node->table, node->col_no);
				node->base_col_no = 0;
			}
1244

1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
			if (node->state != TABLE_ADD_TO_CACHE) {
				ut_ad(node->col_no == v_col->v_pos);
				dict_build_v_col_def_step(node);

				if (node->base_col_no < v_col->num_base - 1) {
					/* move on to next base column */
					node->base_col_no++;
				} else {
					/* move on to next virtual column */
					node->col_no++;
					node->base_col_no = 0;
				}
1257

1258
				thr->run_node = node->v_col_def;
1259

1260 1261 1262 1263 1264
				return(thr);
			}
		} else {
			node->state = TABLE_ADD_TO_CACHE;
		}
1265 1266 1267
	}

	if (node->state == TABLE_ADD_TO_CACHE) {
1268
		DBUG_EXECUTE_IF("ib_ddl_crash_during_create", DBUG_SUICIDE(););
1269

1270 1271
		node->table->can_be_evicted = true;
		node->table->add_to_cache();
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298

		err = DB_SUCCESS;
	}

function_exit:
	trx->error_state = err;

	if (err == DB_SUCCESS) {
		/* Ok: do nothing */

	} else if (err == DB_LOCK_WAIT) {

		return(NULL);
	} else {
		/* SQL error detected */

		return(NULL);
	}

	thr->run_node = que_node_get_parent(node);

	return(thr);
}

/***********************************************************//**
Creates an index. This is a high-level function used in SQL execution
graphs.
1299
@return query thread to run next or NULL */
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
que_thr_t*
dict_create_index_step(
/*===================*/
	que_thr_t*	thr)	/*!< in: query thread */
{
	ind_node_t*	node;
	dberr_t		err	= DB_ERROR;
	trx_t*		trx;

	ut_ad(thr);
1310
	ut_ad(mutex_own(&dict_sys->mutex));
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355

	trx = thr_get_trx(thr);

	node = static_cast<ind_node_t*>(thr->run_node);

	ut_ad(que_node_get_type(node) == QUE_NODE_CREATE_INDEX);

	if (thr->prev_node == que_node_get_parent(node)) {
		node->state = INDEX_BUILD_INDEX_DEF;
	}

	if (node->state == INDEX_BUILD_INDEX_DEF) {
		/* DO THE CHECKS OF THE CONSISTENCY CONSTRAINTS HERE */
		err = dict_build_index_def_step(thr, node);

		if (err != DB_SUCCESS) {

			goto function_exit;
		}

		node->state = INDEX_BUILD_FIELD_DEF;
		node->field_no = 0;

		thr->run_node = node->ind_def;

		return(thr);
	}

	if (node->state == INDEX_BUILD_FIELD_DEF) {

		if (node->field_no < (node->index)->n_fields) {

			dict_build_field_def_step(node);

			node->field_no++;

			thr->run_node = node->field_def;

			return(thr);
		} else {
			node->state = INDEX_ADD_TO_CACHE;
		}
	}

	if (node->state == INDEX_ADD_TO_CACHE) {
1356 1357 1358 1359
		ut_ad(node->index->table == node->table);
		node->index = dict_index_add_to_cache(
			node->index, FIL_NULL, trx_is_strict(trx),
			&err, node->add_v);
1360

1361
		ut_ad((node->index == NULL) == (err != DB_SUCCESS));
1362

1363
		if (!node->index) {
1364 1365 1366
			goto function_exit;
		}

1367 1368 1369 1370 1371
		ut_ad(!node->index->is_instant());
		ut_ad(node->index->n_core_null_bytes
		      == ((dict_index_is_clust(node->index)
			   && node->table->supports_instant())
			  ? dict_index_t::NO_CORE_NULL_BYTES
1372 1373
			  : UT_BITS_IN_BYTES(
				  unsigned(node->index->n_nullable))));
1374
		node->index->n_core_null_bytes = UT_BITS_IN_BYTES(
1375
			unsigned(node->index->n_nullable));
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
		node->state = INDEX_CREATE_INDEX_TREE;
	}

	if (node->state == INDEX_CREATE_INDEX_TREE) {

		err = dict_create_index_tree_step(node);

		DBUG_EXECUTE_IF("ib_dict_create_index_tree_fail",
				err = DB_OUT_OF_MEMORY;);

		if (err != DB_SUCCESS) {
			/* If this is a FTS index, we will need to remove
			it from fts->cache->indexes list as well */
			if ((node->index->type & DICT_FTS)
			    && node->table->fts) {
				fts_index_cache_t*	index_cache;

				rw_lock_x_lock(
					&node->table->fts->cache->init_lock);

				index_cache = (fts_index_cache_t*)
					 fts_find_index_cache(
						node->table->fts->cache,
						node->index);

				if (index_cache->words) {
					rbt_free(index_cache->words);
					index_cache->words = 0;
				}

				ib_vector_remove(
					node->table->fts->cache->indexes,
					*reinterpret_cast<void**>(index_cache));

				rw_lock_x_unlock(
					&node->table->fts->cache->init_lock);
			}

			dict_index_remove_from_cache(node->table, node->index);
			node->index = NULL;

			goto function_exit;
		}

		node->index->page = node->page_no;
		/* These should have been set in
		dict_build_index_def_step() and
		dict_index_add_to_cache(). */
		ut_ad(node->index->trx_id == trx->id);
		ut_ad(node->index->table->def_trx_id == trx->id);
	}

function_exit:
	trx->error_state = err;

	if (err == DB_SUCCESS) {
		/* Ok: do nothing */

	} else if (err == DB_LOCK_WAIT) {

		return(NULL);
	} else {
		/* SQL error detected */

		return(NULL);
	}

	thr->run_node = que_node_get_parent(node);

	return(thr);
}

/****************************************************************//**
Check whether a system table exists.  Additionally, if it exists,
move it to the non-LRU end of the table LRU list.  This is oly used
for system tables that can be upgraded or added to an older database,
which include SYS_FOREIGN, SYS_FOREIGN_COLS, SYS_TABLESPACES and
SYS_DATAFILES.
@return DB_SUCCESS if the sys table exists, DB_CORRUPTION if it exists
but is not current, DB_TABLE_NOT_FOUND if it does not exist*/
static
dberr_t
dict_check_if_system_table_exists(
/*==============================*/
	const char*	tablename,	/*!< in: name of table */
	ulint		num_fields,	/*!< in: number of fields */
	ulint		num_indexes)	/*!< in: number of indexes */
{
	dict_table_t*	sys_table;
	dberr_t		error = DB_SUCCESS;

	ut_a(srv_get_active_thread_type() == SRV_NONE);

	mutex_enter(&dict_sys->mutex);

	sys_table = dict_table_get_low(tablename);

	if (sys_table == NULL) {
		error = DB_TABLE_NOT_FOUND;

	} else if (UT_LIST_GET_LEN(sys_table->indexes) != num_indexes
		   || sys_table->n_cols != num_fields) {
		error = DB_CORRUPTION;

	} else {
		/* This table has already been created, and it is OK.
		Ensure that it can't be evicted from the table LRU cache. */

1484
		dict_table_prevent_eviction(sys_table);
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
	}

	mutex_exit(&dict_sys->mutex);

	return(error);
}

/****************************************************************//**
Creates the foreign key constraints system tables inside InnoDB
at server bootstrap or server start if they are not found or are
not of the right form.
1496
@return DB_SUCCESS or error code */
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
dberr_t
dict_create_or_check_foreign_constraint_tables(void)
/*================================================*/
{
	trx_t*		trx;
	my_bool		srv_file_per_table_backup;
	dberr_t		err;
	dberr_t		sys_foreign_err;
	dberr_t		sys_foreign_cols_err;

	ut_a(srv_get_active_thread_type() == SRV_NONE);

	/* Note: The master thread has not been started at this point. */


	sys_foreign_err = dict_check_if_system_table_exists(
		"SYS_FOREIGN", DICT_NUM_FIELDS__SYS_FOREIGN + 1, 3);
	sys_foreign_cols_err = dict_check_if_system_table_exists(
		"SYS_FOREIGN_COLS", DICT_NUM_FIELDS__SYS_FOREIGN_COLS + 1, 1);

	if (sys_foreign_err == DB_SUCCESS
	    && sys_foreign_cols_err == DB_SUCCESS) {
		return(DB_SUCCESS);
	}

1522 1523 1524 1525 1526
	if (srv_read_only_mode
	    || srv_force_recovery >= SRV_FORCE_NO_TRX_UNDO) {
		return(DB_READ_ONLY);
	}

1527
	trx = trx_create();
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537

	trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);

	trx->op_info = "creating foreign key sys tables";

	row_mysql_lock_data_dictionary(trx);

	/* Check which incomplete table definition to drop. */

	if (sys_foreign_err == DB_CORRUPTION) {
1538
		row_drop_table_after_create_fail("SYS_FOREIGN", trx);
1539 1540 1541
	}

	if (sys_foreign_cols_err == DB_CORRUPTION) {
1542
		row_drop_table_after_create_fail("SYS_FOREIGN_COLS", trx);
1543 1544
	}

1545
	ib::info() << "Creating foreign key constraint system tables.";
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585

	/* NOTE: in dict_load_foreigns we use the fact that
	there are 2 secondary indexes on SYS_FOREIGN, and they
	are defined just like below */

	/* NOTE: when designing InnoDB's foreign key support in 2001, we made
	an error and made the table names and the foreign key id of type
	'CHAR' (internally, really a VARCHAR). We should have made the type
	VARBINARY, like in other InnoDB system tables, to get a clean
	design. */

	srv_file_per_table_backup = srv_file_per_table;

	/* We always want SYSTEM tables to be created inside the system
	tablespace. */

	srv_file_per_table = 0;

	err = que_eval_sql(
		NULL,
		"PROCEDURE CREATE_FOREIGN_SYS_TABLES_PROC () IS\n"
		"BEGIN\n"
		"CREATE TABLE\n"
		"SYS_FOREIGN(ID CHAR, FOR_NAME CHAR,"
		" REF_NAME CHAR, N_COLS INT);\n"
		"CREATE UNIQUE CLUSTERED INDEX ID_IND"
		" ON SYS_FOREIGN (ID);\n"
		"CREATE INDEX FOR_IND"
		" ON SYS_FOREIGN (FOR_NAME);\n"
		"CREATE INDEX REF_IND"
		" ON SYS_FOREIGN (REF_NAME);\n"
		"CREATE TABLE\n"
		"SYS_FOREIGN_COLS(ID CHAR, POS INT,"
		" FOR_COL_NAME CHAR, REF_COL_NAME CHAR);\n"
		"CREATE UNIQUE CLUSTERED INDEX ID_IND"
		" ON SYS_FOREIGN_COLS (ID, POS);\n"
		"END;\n",
		FALSE, trx);

	if (err != DB_SUCCESS) {
1586 1587 1588 1589

		ib::error() << "Creation of SYS_FOREIGN and SYS_FOREIGN_COLS"
			" failed: " << ut_strerr(err) << ". Tablespace is"
			" full. Dropping incompletely created tables.";
1590 1591 1592 1593

		ut_ad(err == DB_OUT_OF_FILE_SPACE
		      || err == DB_TOO_MANY_CONCURRENT_TRXS);

1594 1595
		row_drop_table_after_create_fail("SYS_FOREIGN", trx);
		row_drop_table_after_create_fail("SYS_FOREIGN_COLS", trx);
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605

		if (err == DB_OUT_OF_FILE_SPACE) {
			err = DB_MUST_GET_MORE_FILE_SPACE;
		}
	}

	trx_commit_for_mysql(trx);

	row_mysql_unlock_data_dictionary(trx);

1606
	trx_free(trx);
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622

	srv_file_per_table = srv_file_per_table_backup;

	/* Note: The master thread has not been started at this point. */
	/* Confirm and move to the non-LRU part of the table LRU list. */
	sys_foreign_err = dict_check_if_system_table_exists(
		"SYS_FOREIGN", DICT_NUM_FIELDS__SYS_FOREIGN + 1, 3);
	ut_a(sys_foreign_err == DB_SUCCESS);

	sys_foreign_cols_err = dict_check_if_system_table_exists(
		"SYS_FOREIGN_COLS", DICT_NUM_FIELDS__SYS_FOREIGN_COLS + 1, 1);
	ut_a(sys_foreign_cols_err == DB_SUCCESS);

	return(err);
}

1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
/** Creates the virtual column system table (SYS_VIRTUAL) inside InnoDB
at server bootstrap or server start if the table is not found or is
not of the right form.
@return DB_SUCCESS or error code */
dberr_t
dict_create_or_check_sys_virtual()
{
	trx_t*		trx;
	my_bool		srv_file_per_table_backup;
	dberr_t		err;

	ut_a(srv_get_active_thread_type() == SRV_NONE);

	/* Note: The master thread has not been started at this point. */
	err = dict_check_if_system_table_exists(
		"SYS_VIRTUAL", DICT_NUM_FIELDS__SYS_VIRTUAL + 1, 1);

	if (err == DB_SUCCESS) {
		mutex_enter(&dict_sys->mutex);
		dict_sys->sys_virtual = dict_table_get_low("SYS_VIRTUAL");
		mutex_exit(&dict_sys->mutex);
		return(DB_SUCCESS);
	}

1647 1648 1649
	if (srv_read_only_mode
	    || srv_force_recovery >= SRV_FORCE_NO_TRX_UNDO) {
		return(DB_READ_ONLY);
1650 1651
	}

1652
	trx = trx_create();
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662

	trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);

	trx->op_info = "creating sys_virtual tables";

	row_mysql_lock_data_dictionary(trx);

	/* Check which incomplete table definition to drop. */

	if (err == DB_CORRUPTION) {
1663
		row_drop_table_after_create_fail("SYS_VIRTUAL", trx);
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
	}

	ib::info() << "Creating sys_virtual system tables.";

	srv_file_per_table_backup = srv_file_per_table;

	/* We always want SYSTEM tables to be created inside the system
	tablespace. */

	srv_file_per_table = 0;

	err = que_eval_sql(
		NULL,
		"PROCEDURE CREATE_SYS_VIRTUAL_TABLES_PROC () IS\n"
		"BEGIN\n"
		"CREATE TABLE\n"
		"SYS_VIRTUAL(TABLE_ID BIGINT, POS INT,"
		" BASE_POS INT);\n"
		"CREATE UNIQUE CLUSTERED INDEX BASE_IDX"
		" ON SYS_VIRTUAL(TABLE_ID, POS, BASE_POS);\n"
		"END;\n",
		FALSE, trx);

	if (err != DB_SUCCESS) {

		ib::error() << "Creation of SYS_VIRTUAL"
			" failed: " << ut_strerr(err) << ". Tablespace is"
			" full or too many transactions."
			" Dropping incompletely created tables.";

		ut_ad(err == DB_OUT_OF_FILE_SPACE
		      || err == DB_TOO_MANY_CONCURRENT_TRXS);

1697
		row_drop_table_after_create_fail("SYS_VIRTUAL", trx);
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707

		if (err == DB_OUT_OF_FILE_SPACE) {
			err = DB_MUST_GET_MORE_FILE_SPACE;
		}
	}

	trx_commit_for_mysql(trx);

	row_mysql_unlock_data_dictionary(trx);

1708
	trx_free(trx);
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723

	srv_file_per_table = srv_file_per_table_backup;

	/* Note: The master thread has not been started at this point. */
	/* Confirm and move to the non-LRU part of the table LRU list. */
	dberr_t sys_virtual_err = dict_check_if_system_table_exists(
		"SYS_VIRTUAL", DICT_NUM_FIELDS__SYS_VIRTUAL + 1, 1);
	ut_a(sys_virtual_err == DB_SUCCESS);
	mutex_enter(&dict_sys->mutex);
	dict_sys->sys_virtual = dict_table_get_low("SYS_VIRTUAL");
	mutex_exit(&dict_sys->mutex);

	return(err);
}

1724 1725
/****************************************************************//**
Evaluate the given foreign key SQL statement.
1726
@return error code or DB_SUCCESS */
Sergei Golubchik's avatar
Sergei Golubchik committed
1727
static MY_ATTRIBUTE((nonnull, warn_unused_result))
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
dberr_t
dict_foreign_eval_sql(
/*==================*/
	pars_info_t*	info,	/*!< in: info struct */
	const char*	sql,	/*!< in: SQL string to evaluate */
	const char*	name,	/*!< in: table name (for diagnostics) */
	const char*	id,	/*!< in: foreign key id */
	trx_t*		trx)	/*!< in/out: transaction */
{
	dberr_t	error;
	FILE*	ef	= dict_foreign_err_file;

	error = que_eval_sql(info, sql, FALSE, trx);

	if (error == DB_DUPLICATE_KEY) {
		mutex_enter(&dict_foreign_err_mutex);
		rewind(ef);
		ut_print_timestamp(ef);
		fputs(" Error in foreign key constraint creation for table ",
		      ef);
1748
		ut_print_name(ef, trx, name);
1749
		fputs(".\nA foreign key constraint of name ", ef);
1750
		ut_print_name(ef, trx, id);
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
		fputs("\nalready exists."
		      " (Note that internally InnoDB adds 'databasename'\n"
		      "in front of the user-defined constraint name.)\n"
		      "Note that InnoDB's FOREIGN KEY system tables store\n"
		      "constraint names as case-insensitive, with the\n"
		      "MySQL standard latin1_swedish_ci collation. If you\n"
		      "create tables or databases whose names differ only in\n"
		      "the character case, then collisions in constraint\n"
		      "names can occur. Workaround: name your constraints\n"
		      "explicitly with unique names.\n",
		      ef);

		mutex_exit(&dict_foreign_err_mutex);

		return(error);
	}

	if (error != DB_SUCCESS) {
1769 1770
		ib::error() << "Foreign key constraint creation failed: "
			<< ut_strerr(error);
1771 1772 1773 1774 1775

		mutex_enter(&dict_foreign_err_mutex);
		ut_print_timestamp(ef);
		fputs(" Internal error in foreign key constraint creation"
		      " for table ", ef);
1776
		ut_print_name(ef, trx, name);
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
		fputs(".\n"
		      "See the MySQL .err log in the datadir"
		      " for more information.\n", ef);
		mutex_exit(&dict_foreign_err_mutex);

		return(error);
	}

	return(DB_SUCCESS);
}

/********************************************************************//**
Add a single foreign key field definition to the data dictionary tables in
the database.
1791
@return error code or DB_SUCCESS */
Sergei Golubchik's avatar
Sergei Golubchik committed
1792
static MY_ATTRIBUTE((nonnull, warn_unused_result))
1793 1794 1795 1796 1797 1798 1799 1800
dberr_t
dict_create_add_foreign_field_to_dictionary(
/*========================================*/
	ulint			field_nr,	/*!< in: field number */
	const char*		table_name,	/*!< in: table name */
	const dict_foreign_t*	foreign,	/*!< in: foreign */
	trx_t*			trx)		/*!< in/out: transaction */
{
1801 1802
	DBUG_ENTER("dict_create_add_foreign_field_to_dictionary");

1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
	pars_info_t*	info = pars_info_create();

	pars_info_add_str_literal(info, "id", foreign->id);

	pars_info_add_int4_literal(info, "pos", field_nr);

	pars_info_add_str_literal(info, "for_col_name",
				  foreign->foreign_col_names[field_nr]);

	pars_info_add_str_literal(info, "ref_col_name",
				  foreign->referenced_col_names[field_nr]);

1815
	DBUG_RETURN(dict_foreign_eval_sql(
1816 1817 1818 1819 1820 1821 1822 1823 1824
		       info,
		       "PROCEDURE P () IS\n"
		       "BEGIN\n"
		       "INSERT INTO SYS_FOREIGN_COLS VALUES"
		       "(:id, :pos, :for_col_name, :ref_col_name);\n"
		       "END;\n",
		       table_name, foreign->id, trx));
}

1825 1826 1827
/********************************************************************//**
Construct foreign key constraint defintion from data dictionary information.
*/
1828
UNIV_INTERN
1829 1830
char*
dict_foreign_def_get(
1831
/*=================*/
1832 1833 1834
	dict_foreign_t*	foreign,/*!< in: foreign */
	trx_t*		trx)	/*!< in: trx */
{
1835
	char* fk_def = (char *)mem_heap_alloc(foreign->heap, 4*1024);
1836 1837
	const char* tbname;
	char tablebuf[MAX_TABLE_NAME_LEN + 1] = "";
1838
	unsigned i;
1839
	char* bufend;
1840 1841

	tbname = dict_remove_db_name(foreign->id);
1842
	bufend = innobase_convert_name(tablebuf, MAX_TABLE_NAME_LEN,
1843
				tbname, strlen(tbname), trx->mysql_thd);
1844
	tablebuf[bufend - tablebuf] = '\0';
1845 1846 1847 1848 1849 1850 1851 1852 1853

	sprintf(fk_def,
		(char *)"CONSTRAINT %s FOREIGN KEY (", (char *)tablebuf);

	for(i = 0; i < foreign->n_fields; i++) {
		char	buf[MAX_TABLE_NAME_LEN + 1] = "";
		innobase_convert_name(buf, MAX_TABLE_NAME_LEN,
				foreign->foreign_col_names[i],
				strlen(foreign->foreign_col_names[i]),
1854
				trx->mysql_thd);
1855
		strcat(fk_def, buf);
1856
		if (i < static_cast<unsigned>(foreign->n_fields-1)) {
1857 1858 1859 1860 1861 1862
			strcat(fk_def, (char *)",");
		}
	}

	strcat(fk_def,(char *)") REFERENCES ");

1863 1864 1865
	bufend = innobase_convert_name(tablebuf, MAX_TABLE_NAME_LEN,
	        	        foreign->referenced_table_name,
			        strlen(foreign->referenced_table_name),
1866
			        trx->mysql_thd);
1867
	tablebuf[bufend - tablebuf] = '\0';
1868 1869 1870 1871 1872 1873

	strcat(fk_def, tablebuf);
	strcat(fk_def, " (");

	for(i = 0; i < foreign->n_fields; i++) {
		char	buf[MAX_TABLE_NAME_LEN + 1] = "";
1874
		bufend = innobase_convert_name(buf, MAX_TABLE_NAME_LEN,
1875 1876
				foreign->referenced_col_names[i],
				strlen(foreign->referenced_col_names[i]),
1877
				trx->mysql_thd);
1878
		buf[bufend - buf] = '\0';
1879
		strcat(fk_def, buf);
1880
		if (i < (uint)foreign->n_fields-1) {
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
			strcat(fk_def, (char *)",");
		}
	}
	strcat(fk_def, (char *)")");

	return fk_def;
}

/********************************************************************//**
Convert foreign key column names from data dictionary to SQL-layer.
*/
static
void
dict_foreign_def_get_fields(
1895
/*========================*/
1896 1897 1898 1899
	dict_foreign_t*	foreign,/*!< in: foreign */
	trx_t*		trx,	/*!< in: trx */
	char**		field,  /*!< out: foreign column */
	char**		field2, /*!< out: referenced column */
1900
	ulint		col_no) /*!< in: column number */
1901
{
1902
	char* bufend;
1903 1904
	char* fieldbuf = (char *)mem_heap_alloc(foreign->heap, MAX_TABLE_NAME_LEN+1);
	char* fieldbuf2 = (char *)mem_heap_alloc(foreign->heap, MAX_TABLE_NAME_LEN+1);
1905 1906 1907 1908

	bufend = innobase_convert_name(fieldbuf, MAX_TABLE_NAME_LEN,
			foreign->foreign_col_names[col_no],
			strlen(foreign->foreign_col_names[col_no]),
1909
			trx->mysql_thd);
1910 1911 1912 1913 1914 1915

	fieldbuf[bufend - fieldbuf] = '\0';

	bufend = innobase_convert_name(fieldbuf2, MAX_TABLE_NAME_LEN,
			foreign->referenced_col_names[col_no],
			strlen(foreign->referenced_col_names[col_no]),
1916
			trx->mysql_thd);
1917 1918 1919 1920

	fieldbuf2[bufend - fieldbuf2] = '\0';
	*field = fieldbuf;
	*field2 = fieldbuf2;
1921 1922
}

1923 1924
/********************************************************************//**
Add a foreign key definition to the data dictionary tables.
1925
@return error code or DB_SUCCESS */
1926 1927 1928 1929 1930 1931 1932 1933
dberr_t
dict_create_add_foreign_to_dictionary(
/*==================================*/
	const char*		name,	/*!< in: table name */
	const dict_foreign_t*	foreign,/*!< in: foreign key */
	trx_t*			trx)	/*!< in/out: dictionary transaction */
{
	dberr_t		error;
1934 1935 1936

	DBUG_ENTER("dict_create_add_foreign_to_dictionary");

1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
	pars_info_t*	info = pars_info_create();

	pars_info_add_str_literal(info, "id", foreign->id);

	pars_info_add_str_literal(info, "for_name", name);

	pars_info_add_str_literal(info, "ref_name",
				  foreign->referenced_table_name);

	pars_info_add_int4_literal(info, "n_cols",
1947 1948
				   ulint(foreign->n_fields)
				   | (ulint(foreign->type) << 24));
1949

1950 1951 1952 1953 1954
	DBUG_PRINT("dict_create_add_foreign_to_dictionary",
		   ("'%s', '%s', '%s', %d", foreign->id, name,
		    foreign->referenced_table_name,
		    foreign->n_fields + (foreign->type << 24)));

1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
	error = dict_foreign_eval_sql(info,
				      "PROCEDURE P () IS\n"
				      "BEGIN\n"
				      "INSERT INTO SYS_FOREIGN VALUES"
				      "(:id, :for_name, :ref_name, :n_cols);\n"
				      "END;\n"
				      , name, foreign->id, trx);

	if (error != DB_SUCCESS) {

1965 1966
		if (error == DB_DUPLICATE_KEY) {
			char	buf[MAX_TABLE_NAME_LEN + 1] = "";
1967
			char	tablename[MAX_TABLE_NAME_LEN + 1] = "";
1968 1969
			char*	fk_def;

1970
			innobase_convert_name(tablename, MAX_TABLE_NAME_LEN,
1971
				name, strlen(name), trx->mysql_thd);
1972

1973
			innobase_convert_name(buf, MAX_TABLE_NAME_LEN,
1974
				foreign->id, strlen(foreign->id), trx->mysql_thd);
1975

1976
			fk_def = dict_foreign_def_get((dict_foreign_t*)foreign, trx);
1977

1978 1979 1980 1981
			ib_push_warning(trx, error,
				"Create or Alter table %s with foreign key constraint"
				" failed. Foreign key constraint %s"
				" already exists on data dictionary."
1982 1983
				" Foreign key constraint names need to be unique in database."
				" Error in foreign key definition: %s.",
1984
				tablename, buf, fk_def);
1985 1986
		}

1987
		DBUG_RETURN(error);
1988 1989 1990 1991 1992 1993 1994
	}

	for (ulint i = 0; i < foreign->n_fields; i++) {
		error = dict_create_add_foreign_field_to_dictionary(
			i, name, foreign, trx);

		if (error != DB_SUCCESS) {
1995
			char	buf[MAX_TABLE_NAME_LEN + 1] = "";
1996
			char	tablename[MAX_TABLE_NAME_LEN + 1] = "";
1997 1998 1999 2000
			char*	field=NULL;
			char*	field2=NULL;
			char*	fk_def;

2001
			innobase_convert_name(tablename, MAX_TABLE_NAME_LEN,
2002
				name, strlen(name), trx->mysql_thd);
2003
			innobase_convert_name(buf, MAX_TABLE_NAME_LEN,
2004
				foreign->id, strlen(foreign->id), trx->mysql_thd);
2005 2006
			fk_def = dict_foreign_def_get((dict_foreign_t*)foreign, trx);
			dict_foreign_def_get_fields((dict_foreign_t*)foreign, trx, &field, &field2, i);
2007 2008

			ib_push_warning(trx, error,
2009 2010 2011
				"Create or Alter table %s with foreign key constraint"
				" failed. Error adding foreign  key constraint name %s"
				" fields %s or %s to the dictionary."
2012
				" Error in foreign key definition: %s.",
2013
				tablename, buf, i+1, fk_def);
2014

2015
			DBUG_RETURN(error);
2016 2017 2018
		}
	}

2019
	DBUG_RETURN(error);
2020 2021
}

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 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
/** Check whether a column is in an index by the column name
@param[in]	col_name	column name for the column to be checked
@param[in]	index		the index to be searched
@return	true if this column is in the index, otherwise, false */
static
bool
dict_index_has_col_by_name(
/*=======================*/
	const char*		col_name,
	const dict_index_t*	index)
{
	for (ulint i = 0; i < index->n_fields; i++) {
		dict_field_t*   field = dict_index_get_nth_field(index, i);

		if (strcmp(field->name, col_name) == 0) {
			return(true);
		}
	}
	return(false);
}

/** Check whether the foreign constraint could be on a column that is
part of a virtual index (index contains virtual column) in the table
@param[in]	fk_col_name	FK column name to be checked
@param[in]	table		the table
@return	true if this column is indexed with other virtual columns */
bool
dict_foreign_has_col_in_v_index(
	const char*		fk_col_name,
	const dict_table_t*	table)
{
	/* virtual column can't be Primary Key, so start with secondary index */
	for (dict_index_t* index = dict_table_get_next_index(
		     dict_table_get_first_index(table));
	     index;
	     index = dict_table_get_next_index(index)) {

		if (dict_index_has_virtual(index)) {
			if (dict_index_has_col_by_name(fk_col_name, index)) {
				return(true);
			}
		}
	}

	return(false);
}


/** Check whether the foreign constraint could be on a column that is
a base column of some indexed virtual columns.
@param[in]	col_name	column name for the column to be checked
@param[in]	table		the table
@return	true if this column is a base column, otherwise, false */
bool
dict_foreign_has_col_as_base_col(
	const char*		col_name,
	const dict_table_t*	table)
{
	/* Loop through each virtual column and check if its base column has
	the same name as the column name being checked */
	for (ulint i = 0; i < table->n_v_cols; i++) {
		dict_v_col_t*	v_col = dict_table_get_nth_v_col(table, i);

		/* Only check if the virtual column is indexed */
		if (!v_col->m_col.ord_part) {
			continue;
		}

		for (ulint j = 0; j < v_col->num_base; j++) {
			if (strcmp(col_name, dict_table_get_col_name(
					   table,
					   v_col->base_col[j]->ind)) == 0) {
				return(true);
			}
		}
	}

	return(false);
}

/** Check if a foreign constraint is on the given column name.
@param[in]	col_name	column name to be searched for fk constraint
@param[in]	table		table to which foreign key constraint belongs
@return true if fk constraint is present on the table, false otherwise. */
static
bool
dict_foreign_base_for_stored(
	const char*		col_name,
	const dict_table_t*	table)
{
	/* Loop through each stored column and check if its base column has
	the same name as the column name being checked */
	dict_s_col_list::const_iterator	it;
	for (it = table->s_cols->begin();
	     it != table->s_cols->end(); ++it) {
		dict_s_col_t	s_col = *it;

		for (ulint j = 0; j < s_col.num_base; j++) {
			if (strcmp(col_name, dict_table_get_col_name(
						table,
						s_col.base_col[j]->ind)) == 0) {
				return(true);
			}
		}
	}

	return(false);
}

/** Check if a foreign constraint is on columns served as base columns
of any stored column. This is to prevent creating SET NULL or CASCADE
constraint on such columns
@param[in]	local_fk_set	set of foreign key objects, to be added to
the dictionary tables
@param[in]	table		table to which the foreign key objects in
local_fk_set belong to
@return true if yes, otherwise, false */
bool
dict_foreigns_has_s_base_col(
	const dict_foreign_set&	local_fk_set,
	const dict_table_t*	table)
{
	dict_foreign_t*	foreign;

	if (table->s_cols == NULL) {
		return (false);
	}

	for (dict_foreign_set::const_iterator it = local_fk_set.begin();
	     it != local_fk_set.end(); ++it) {

		foreign = *it;
		ulint	type = foreign->type;

		type &= ~(DICT_FOREIGN_ON_DELETE_NO_ACTION
			  | DICT_FOREIGN_ON_UPDATE_NO_ACTION);

		if (type == 0) {
			continue;
		}

		for (ulint i = 0; i < foreign->n_fields; i++) {
			/* Check if the constraint is on a column that
			is a base column of any stored column */
			if (dict_foreign_base_for_stored(
				foreign->foreign_col_names[i], table)) {
				return(true);
			}
		}
	}

	return(false);
}

/** Check if a column is in foreign constraint with CASCADE properties or
SET NULL
@param[in]	table		table
@param[in]	fk_col_name	name for the column to be checked
@return true if the column is in foreign constraint, otherwise, false */
bool
dict_foreigns_has_this_col(
	const dict_table_t*	table,
	const char*		col_name)
{
	dict_foreign_t*		foreign;
	const dict_foreign_set*	local_fk_set = &table->foreign_set;

	for (dict_foreign_set::const_iterator it = local_fk_set->begin();
	     it != local_fk_set->end();
	     ++it) {
		foreign = *it;
		ut_ad(foreign->id != NULL);
		ulint	type = foreign->type;

		type &= ~(DICT_FOREIGN_ON_DELETE_NO_ACTION
			  | DICT_FOREIGN_ON_UPDATE_NO_ACTION);

		if (type == 0) {
			continue;
		}

		for (ulint i = 0; i < foreign->n_fields; i++) {
			if (strcmp(foreign->foreign_col_names[i],
				   col_name) == 0) {
				return(true);
			}
		}
	}
	return(false);
}

Sergei Golubchik's avatar
Sergei Golubchik committed
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
/** Adds the given set of foreign key objects to the dictionary tables
in the database. This function does not modify the dictionary cache. The
caller must ensure that all foreign key objects contain a valid constraint
name in foreign->id.
@param[in]	local_fk_set	set of foreign key objects, to be added to
the dictionary tables
@param[in]	table		table to which the foreign key objects in
local_fk_set belong to
@param[in,out]	trx		transaction
@return error code or DB_SUCCESS */
2223 2224 2225
dberr_t
dict_create_add_foreigns_to_dictionary(
/*===================================*/
Sergei Golubchik's avatar
Sergei Golubchik committed
2226 2227 2228
	const dict_foreign_set&	local_fk_set,
	const dict_table_t*	table,
	trx_t*			trx)
2229 2230 2231 2232
{
	dict_foreign_t*	foreign;
	dberr_t		error;

2233
	ut_ad(mutex_own(&dict_sys->mutex));
2234 2235

	if (NULL == dict_table_get_low("SYS_FOREIGN")) {
2236 2237 2238

		ib::error() << "Table SYS_FOREIGN not found"
			" in internal data dictionary";
2239 2240 2241 2242

		return(DB_ERROR);
	}

Sergei Golubchik's avatar
Sergei Golubchik committed
2243 2244 2245
	for (dict_foreign_set::const_iterator it = local_fk_set.begin();
	     it != local_fk_set.end();
	     ++it) {
2246

Sergei Golubchik's avatar
Sergei Golubchik committed
2247 2248
		foreign = *it;
		ut_ad(foreign->id != NULL);
2249

2250
		error = dict_create_add_foreign_to_dictionary(
2251
			table->name.m_name, foreign, trx);
2252 2253 2254 2255 2256 2257 2258 2259 2260

		if (error != DB_SUCCESS) {

			return(error);
		}
	}

	trx->op_info = "committing foreign key definitions";

2261 2262 2263 2264
	if (trx_is_started(trx)) {

		trx_commit(trx);
	}
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274

	trx->op_info = "";

	return(DB_SUCCESS);
}

/****************************************************************//**
Creates the tablespaces and datafiles system tables inside InnoDB
at server bootstrap or server start if they are not found or are
not of the right form.
2275
@return DB_SUCCESS or error code */
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
dberr_t
dict_create_or_check_sys_tablespace(void)
/*=====================================*/
{
	trx_t*		trx;
	my_bool		srv_file_per_table_backup;
	dberr_t		err;
	dberr_t		sys_tablespaces_err;
	dberr_t		sys_datafiles_err;

	ut_a(srv_get_active_thread_type() == SRV_NONE);

	/* Note: The master thread has not been started at this point. */

	sys_tablespaces_err = dict_check_if_system_table_exists(
		"SYS_TABLESPACES", DICT_NUM_FIELDS__SYS_TABLESPACES + 1, 1);
	sys_datafiles_err = dict_check_if_system_table_exists(
		"SYS_DATAFILES", DICT_NUM_FIELDS__SYS_DATAFILES + 1, 1);

	if (sys_tablespaces_err == DB_SUCCESS
	    && sys_datafiles_err == DB_SUCCESS) {
2297
		srv_sys_tablespaces_open = true;
2298 2299 2300
		return(DB_SUCCESS);
	}

2301 2302 2303 2304 2305
	if (srv_read_only_mode
	    || srv_force_recovery >= SRV_FORCE_NO_TRX_UNDO) {
		return(DB_READ_ONLY);
	}

2306
	trx = trx_create();
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316

	trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);

	trx->op_info = "creating tablepace and datafile sys tables";

	row_mysql_lock_data_dictionary(trx);

	/* Check which incomplete table definition to drop. */

	if (sys_tablespaces_err == DB_CORRUPTION) {
2317
		row_drop_table_after_create_fail("SYS_TABLESPACES", trx);
2318 2319 2320
	}

	if (sys_datafiles_err == DB_CORRUPTION) {
2321
		row_drop_table_after_create_fail("SYS_DATAFILES", trx);
2322 2323
	}

2324
	ib::info() << "Creating tablespace and datafile system tables.";
2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346

	/* We always want SYSTEM tables to be created inside the system
	tablespace. */
	srv_file_per_table_backup = srv_file_per_table;
	srv_file_per_table = 0;

	err = que_eval_sql(
		NULL,
		"PROCEDURE CREATE_SYS_TABLESPACE_PROC () IS\n"
		"BEGIN\n"
		"CREATE TABLE SYS_TABLESPACES(\n"
		" SPACE INT, NAME CHAR, FLAGS INT);\n"
		"CREATE UNIQUE CLUSTERED INDEX SYS_TABLESPACES_SPACE"
		" ON SYS_TABLESPACES (SPACE);\n"
		"CREATE TABLE SYS_DATAFILES(\n"
		" SPACE INT, PATH CHAR);\n"
		"CREATE UNIQUE CLUSTERED INDEX SYS_DATAFILES_SPACE"
		" ON SYS_DATAFILES (SPACE);\n"
		"END;\n",
		FALSE, trx);

	if (err != DB_SUCCESS) {
2347 2348 2349 2350

		ib::error() << "Creation of SYS_TABLESPACES and SYS_DATAFILES"
			" has failed with error " << ut_strerr(err)
			<< ". Dropping incompletely created tables.";
2351 2352

		ut_a(err == DB_OUT_OF_FILE_SPACE
2353
		     || err == DB_DUPLICATE_KEY
2354 2355
		     || err == DB_TOO_MANY_CONCURRENT_TRXS);

2356 2357
		row_drop_table_after_create_fail("SYS_TABLESPACES", trx);
		row_drop_table_after_create_fail("SYS_DATAFILES", trx);
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367

		if (err == DB_OUT_OF_FILE_SPACE) {
			err = DB_MUST_GET_MORE_FILE_SPACE;
		}
	}

	trx_commit_for_mysql(trx);

	row_mysql_unlock_data_dictionary(trx);

2368
	trx_free(trx);
2369 2370 2371 2372

	srv_file_per_table = srv_file_per_table_backup;

	if (err == DB_SUCCESS) {
2373
		srv_sys_tablespaces_open = true;
2374 2375 2376 2377 2378 2379 2380
	}

	/* Note: The master thread has not been started at this point. */
	/* Confirm and move to the non-LRU part of the table LRU list. */

	sys_tablespaces_err = dict_check_if_system_table_exists(
		"SYS_TABLESPACES", DICT_NUM_FIELDS__SYS_TABLESPACES + 1, 1);
2381
	ut_a(sys_tablespaces_err == DB_SUCCESS || err != DB_SUCCESS);
2382 2383 2384

	sys_datafiles_err = dict_check_if_system_table_exists(
		"SYS_DATAFILES", DICT_NUM_FIELDS__SYS_DATAFILES + 1, 1);
2385
	ut_a(sys_datafiles_err == DB_SUCCESS || err != DB_SUCCESS);
2386 2387 2388 2389

	return(err);
}

2390 2391 2392 2393 2394 2395 2396 2397
/** Put a tablespace definition into the data dictionary,
replacing what was there previously.
@param[in]	space	Tablespace id
@param[in]	name	Tablespace name
@param[in]	flags	Tablespace flags
@param[in]	path	Tablespace path
@param[in]	trx	Transaction
@return error code or DB_SUCCESS */
2398
dberr_t
2399 2400 2401 2402 2403
dict_replace_tablespace_in_dictionary(
	ulint		space_id,
	const char*	name,
	ulint		flags,
	const char*	path,
2404
	trx_t*		trx)
2405
{
2406 2407 2408 2409 2410
	if (!srv_sys_tablespaces_open) {
		/* Startup procedure is not yet ready for updates. */
		return(DB_SUCCESS);
	}

2411 2412 2413 2414
	dberr_t		error;

	pars_info_t*	info = pars_info_create();

2415
	pars_info_add_int4_literal(info, "space", space_id);
2416 2417 2418 2419 2420 2421 2422 2423 2424

	pars_info_add_str_literal(info, "name", name);

	pars_info_add_int4_literal(info, "flags", flags);

	pars_info_add_str_literal(info, "path", path);

	error = que_eval_sql(info,
			     "PROCEDURE P () IS\n"
2425 2426 2427 2428 2429 2430
			     "p CHAR;\n"

			     "DECLARE CURSOR c IS\n"
			     " SELECT PATH FROM SYS_DATAFILES\n"
			     " WHERE SPACE=:space FOR UPDATE;\n"

2431
			     "BEGIN\n"
2432 2433 2434 2435 2436 2437 2438
			     "OPEN c;\n"
			     "FETCH c INTO p;\n"

			     "IF (SQL % NOTFOUND) THEN"
			     "  DELETE FROM SYS_TABLESPACES "
			     "WHERE SPACE=:space;\n"
			     "  INSERT INTO SYS_TABLESPACES VALUES"
2439
			     "(:space, :name, :flags);\n"
2440
			     "  INSERT INTO SYS_DATAFILES VALUES"
2441
			     "(:space, :path);\n"
2442 2443 2444 2445
			     "ELSIF p <> :path THEN\n"
			     "  UPDATE SYS_DATAFILES SET PATH=:path"
			     " WHERE CURRENT OF c;\n"
			     "END IF;\n"
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
			     "END;\n",
			     FALSE, trx);

	if (error != DB_SUCCESS) {
		return(error);
	}

	trx->op_info = "";

	return(error);
}
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508

/** Delete records from SYS_TABLESPACES and SYS_DATAFILES associated
with a particular tablespace ID.
@param[in]	space	Tablespace ID
@param[in,out]	trx	Current transaction
@return DB_SUCCESS if OK, dberr_t if the operation failed */

dberr_t
dict_delete_tablespace_and_datafiles(
	ulint		space,
	trx_t*		trx)
{
	dberr_t		err = DB_SUCCESS;

	ut_ad(rw_lock_own(dict_operation_lock, RW_LOCK_X));
	ut_ad(mutex_own(&dict_sys->mutex));
	ut_ad(srv_sys_tablespaces_open);

	trx->op_info = "delete tablespace and datafiles from dictionary";

	pars_info_t*	info = pars_info_create();
	ut_a(!is_system_tablespace(space));
	pars_info_add_int4_literal(info, "space", space);

	err = que_eval_sql(info,
			   "PROCEDURE P () IS\n"
			   "BEGIN\n"
			   "DELETE FROM SYS_TABLESPACES\n"
			   "WHERE SPACE = :space;\n"
			   "DELETE FROM SYS_DATAFILES\n"
			   "WHERE SPACE = :space;\n"
			   "END;\n",
			   FALSE, trx);

	if (err != DB_SUCCESS) {
		ib::warn() << "Could not delete space_id "
			<< space << " from data dictionary";
	}

	trx->op_info = "";

	return(err);
}

/** Assign a new table ID and put it into the table cache and the transaction.
@param[in,out]	table	Table that needs an ID
@param[in,out]	trx	Transaction */
void
dict_table_assign_new_id(
	dict_table_t*	table,
	trx_t*		trx)
{
2509
	dict_hdr_get_new_id(&table->id, NULL, NULL, table, false);
2510 2511
	trx->table_id = table->id;
}