datadic_xt.cc 79.6 KB
Newer Older
Paul McCullagh's avatar
Paul McCullagh 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
/* Copyright (c) 2005 PrimeBase Technologies GmbH
 *
 * PrimeBase XT
 *
 * 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; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * 2006-05-16	Paul McCullagh
 *
 * H&G2JCtL
 *
 * Implementation of the PBXT internal data dictionary.
 */


#include "xt_config.h"

29 30 31 32
#ifdef DRIZZLED
#include <bitset>
#endif

Paul McCullagh's avatar
Paul McCullagh committed
33 34 35 36 37
#include <ctype.h>
#include <errno.h>

#ifdef DEBUG
#ifdef DRIZZLED
38
//#include <drizzled/common_includes.h>
Paul McCullagh's avatar
Paul McCullagh committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 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 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
#else
#include "mysql_priv.h"
#endif
#endif

#include "pthread_xt.h"
#include "datadic_xt.h"
#include "util_xt.h"
#include "database_xt.h"
#include "table_xt.h"
#include "heap_xt.h"
#include "strutil_xt.h"
#include "myxt_xt.h"
#include "hashtab_xt.h"

/*
 * -----------------------------------------------------------------------
 * Lexical analyser
 */

#define XT_TK_EOF				0
#define XT_TK_IDENTIFIER		1
#define XT_TK_NUMBER			2
#define XT_TK_STRING			3
#define XT_TK_PUNCTUATION		4

#define XT_TK_RESERVER_WORDS	5
#define XT_TK_PRIMARY			5
#define XT_TK_UNIQUE			6
#define XT_TK_FULLTEXT			7
#define XT_TK_SPATIAL			8
#define XT_TK_INDEX				9
#define XT_TK_KEY				10
#define XT_TK_CHECK				11
#define XT_TK_FOREIGN			12
#define XT_TK_COLUMN			13
#define XT_TK_REFERENCES		14
#define XT_TK_NOT				15
#define XT_TK_NULL				16
#define XT_TK_AUTO_INCREMENT	17
#define XT_TK_COMMENT			18
#define XT_TK_DEFAULT			19
#define XT_TK_COLLATE			20

class XTToken {
	public:	
	u_int	tk_type;
	char	*tk_text;
	size_t	tk_length;

	void initCString(u_int type, char *start, char *end);
	inline char charAt(u_int i) {
		if (i >= tk_length)
			return 0;
		return toupper(tk_text[i]);
	}
	void expectKeyWord(XTThreadPtr self, c_char *keyword);
	void expectIdentifier(XTThreadPtr self);
	void expectNumber(XTThreadPtr self);
	bool isKeyWord(c_char *keyword);
	bool isReservedWord();
	bool isReservedWord(u_int word);
	void identifyReservedWord();
	bool isEOF();
	bool isIdentifier();
	bool isNumber();
	size_t getString(char *string, size_t len);
	void getTokenText(char *string, size_t len);
	XTToken *clone(XTThreadPtr self);
};

void XTToken::initCString(u_int type, char *start, char *end)
{
	tk_type = type;
	tk_text = start;
	tk_length = (size_t) end - (size_t) start;
}

bool XTToken::isKeyWord(c_char *keyword)
{
	char	*str = tk_text;
	size_t	len = tk_length;
	
	while (len && *keyword) {
		if (toupper(*keyword) != toupper(*str))
			return false;
		keyword++;
		str++;
		len--;
	}
	return !len && !*keyword;
}

bool XTToken::isReservedWord()
{
	return tk_type >= XT_TK_RESERVER_WORDS;
}

bool XTToken::isReservedWord(u_int word)
{
	return tk_type == word;
}

void XTToken::identifyReservedWord()
{
	if (tk_type == XT_TK_IDENTIFIER) {
		switch (charAt(0)) {
			case 'A':
				if (isKeyWord("AUTO_INCREMENT"))
					tk_type = XT_TK_AUTO_INCREMENT;
				break;
			case 'C':
				switch (charAt(2)) {
					case 'E':
						if (isKeyWord("CHECK"))
							tk_type = XT_TK_CHECK;
						break;
					case 'L':
						if (isKeyWord("COLUMN"))
							tk_type = XT_TK_COLUMN;
						else if (isKeyWord("COLLATE"))
							tk_type = XT_TK_COLLATE;
						break;
					case 'M':
						if (isKeyWord("COMMENT"))
							tk_type = XT_TK_COMMENT;
						break;
				}
				break;
			case 'D':
				if (isKeyWord("DEFAULT"))
					tk_type = XT_TK_DEFAULT;
				break;
			case 'F':
				switch (charAt(1)) {
					case 'O':
						if (isKeyWord("FOREIGN"))
							tk_type = XT_TK_FOREIGN;
						break;
					case 'U':
						if (isKeyWord("FULLTEXT"))
							tk_type = XT_TK_FULLTEXT;
						break;
				}
				break;
			case 'I':
				if (isKeyWord("INDEX"))
					tk_type = XT_TK_INDEX;
				break;
			case 'K':
				if (isKeyWord("KEY"))
					tk_type = XT_TK_KEY;
				break;
			case 'N':
				switch (charAt(1)) {
					case 'O':
						if (isKeyWord("NOT"))
							tk_type = XT_TK_NOT;
						break;
					case 'U':
						if (isKeyWord("NULL"))
							tk_type = XT_TK_NULL;
						break;
				}
				break;
			case 'P':
				if (isKeyWord("PRIMARY"))
					tk_type = XT_TK_PRIMARY;
				break;
			case 'R':
				if (isKeyWord("REFERENCES"))
					tk_type = XT_TK_REFERENCES;
				break;
			case 'S':
				if (isKeyWord("SPATIAL"))
					tk_type = XT_TK_SPATIAL;
				break;
			case 'U':
				if (isKeyWord("UNIQUE"))
					tk_type = XT_TK_UNIQUE;
				break;			
		}
	}
}

bool XTToken::isEOF()
{
	return tk_type == XT_TK_EOF;
}

bool XTToken::isIdentifier()
{
	return tk_type == XT_TK_IDENTIFIER;
}

bool XTToken::isNumber()
{
	return tk_type == XT_TK_NUMBER;
}

/* Return actual, or required string length. */
size_t XTToken::getString(char *dtext, size_t dsize)
{
	char	*buffer = dtext;
	int		slen;
	size_t	dlen;
	char	*stext;
	char	quote;

	if ((slen = (int) tk_length) == 0) {
		*dtext = 0;
		return 0;
	}
	switch (*tk_text) {
		case '\'':
		case '"':
		case '`':
			quote = *tk_text;
			stext = tk_text+1;
			slen -= 2;
			dlen = 0;
			while (slen > 0) {
				if (*stext == '\\') {
					stext++;
					slen--;
					if (slen > 0) {
						switch (*stext) {
							case '\0':
								*dtext = 0;
								break;
							case '\'':
								*dtext = '\'';
								break;
							case '"':
								*dtext = '"';
								break;
							case 'b':
								*dtext = '\b';
								break;
							case 'n':
								*dtext = '\n';
								break;
							case 'r':
								*dtext = '\r';
								break;
							case 't':
								*dtext = '\t';
								break;
							case 'z':
								*dtext = (char) 26;
								break;
							case '\\':
								*dtext = '\\';
								break;
							default:
								*dtext = *stext;
								break;
						}
					}
				}
				else if (*stext == quote) {
					if (dlen < dsize)
						*dtext = quote;
					stext++;
					slen--;
				}
				else {
					if (dlen < dsize)
						*dtext = *stext;
				}
				dtext++;
				dlen++;
				stext++;
				slen--;
			}
			if (dlen < dsize)
				buffer[dlen] = 0;
			else if (dsize > 0)
				buffer[dsize-1] = 0;
			break;
		default:
			if (dsize > 0) {
				dlen = dsize-1;
				if ((int) dlen > slen)
					dlen = slen;
				memcpy(dtext, tk_text, dlen);
				dtext[dlen] = 0;
			}
			dlen = tk_length;
			break;
	}
	return dlen;
}

/* Return the token as a string with ... in it if it is too long
 */
void XTToken::getTokenText(char *string, size_t size)
{
	if (tk_length == 0 || !tk_text) {
		xt_strcpy(size, string, "EOF");
		return;
	}

	size--;
	if (tk_length <= size) {
		memcpy(string, tk_text, tk_length);
		string[tk_length] = 0;
		return;
	}
	
	size = (size - 3) / 2;
	memcpy(string, tk_text, size);
	memcpy(string+size, "...", 3);
	memcpy(string+size+3, tk_text + tk_length - size, size);
	string[size+3+size] = 0;
}

XTToken *XTToken::clone(XTThreadPtr self)
{
	XTToken *tk;

	if (!(tk = new XTToken()))
		xt_throw_errno(XT_CONTEXT, XT_ENOMEM);
	tk->initCString(tk_type, tk_text, tk_text + tk_length);
	return tk;
}

void XTToken::expectKeyWord(XTThreadPtr self, c_char *keyword)
{
	char	buffer[100];

	if (isKeyWord(keyword))
		return;
	getTokenText(buffer, 100);
	xt_throw_i2xterr(XT_CONTEXT, XT_ERR_A_EXPECTED_NOT_B, keyword, buffer);
}

void XTToken::expectIdentifier(XTThreadPtr self)
{
	char buffer[100];

	if (isIdentifier())
		return;
	getTokenText(buffer, 100);
	xt_throw_i2xterr(XT_CONTEXT, XT_ERR_A_EXPECTED_NOT_B, "Identifier", buffer);
}

void XTToken::expectNumber(XTThreadPtr self)
{
	char buffer[100];

	if (isNumber())
		return;
	getTokenText(buffer, 100);
	xt_throw_i2xterr(XT_CONTEXT, XT_ERR_A_EXPECTED_NOT_B, "Value", buffer);
}

struct charset_info_st;

class XTTokenizer {
399
	MX_CONST_CHARSET_INFO	*tkn_charset;
Paul McCullagh's avatar
Paul McCullagh committed
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
	char					*tkn_cstring;
	char					*tkn_curr_pos;
	XTToken					*tkn_current;
	bool					tkn_in_comment;

	public:

	XTTokenizer(bool convert, char *cstring) {
		tkn_charset = myxt_getcharset(convert);
		tkn_cstring = cstring;
		tkn_curr_pos = cstring;
		tkn_current = NULL;
		tkn_in_comment = FALSE;
	}

	virtual ~XTTokenizer(void) {
		if (tkn_current)
			delete tkn_current;
	}

	inline bool isSingleChar(int ch)
	{
		return  ch != '$' && ch != '_' && myxt_ispunct(tkn_charset, ch);
	}

	inline bool isIdentifierChar(int ch)
	{
		return  ch && !isSingleChar(ch) && !myxt_isspace(tkn_charset, ch);
	}

	inline bool isNumberChar(int ch, int next_ch)
	{
		return myxt_isdigit(tkn_charset, ch) || ((ch == '-' || ch == '+') && myxt_isdigit(tkn_charset, next_ch));
	}

	XTToken *newToken(XTThreadPtr self, u_int type, char *start, char *end);
	XTToken *nextToken(XTThreadPtr self);
	XTToken *nextToken(XTThreadPtr self, c_char *keyword, XTToken *tk);
};

XTToken *XTTokenizer::newToken(XTThreadPtr self, u_int type, char *start, char *end)
{
	if (!tkn_current) {
		if (!(tkn_current = new XTToken()))
			xt_throw_errno(XT_CONTEXT, XT_ENOMEM);
	}
	tkn_current->initCString(type, start, end);
	if (type == XT_TK_IDENTIFIER)
		tkn_current->identifyReservedWord();
	return tkn_current;
}

XTToken *XTTokenizer::nextToken(XTThreadPtr self)
{
	char	*token_start;
	u_int	token_type = XT_TK_PUNCTUATION;
	char	quote;
	bool	must_be_num;

	restart:

	/* Ignore space: */
	while (*tkn_curr_pos && myxt_isspace(tkn_charset, *tkn_curr_pos)) tkn_curr_pos++;

	token_start = tkn_curr_pos;
	switch (*tkn_curr_pos) {
		case '\0':
			return newToken(self, XT_TK_EOF, NULL, NULL);
		// Comment: # ... EOL
		case '#':
			tkn_curr_pos++;
			while (*tkn_curr_pos && *tkn_curr_pos != '\n' && *tkn_curr_pos != '\r') tkn_curr_pos++;
			goto restart;
		case '-':
			if (tkn_curr_pos[1] == '-') {
				// Comment: -- ... EOL
				while (*tkn_curr_pos && *tkn_curr_pos != '\n' && *tkn_curr_pos != '\r') tkn_curr_pos++;
				goto restart;
			}
			if (myxt_isdigit(tkn_charset, tkn_curr_pos[1]))
				goto is_number;
			tkn_curr_pos++;
			break;
		case '+':
			if (myxt_isdigit(tkn_charset, tkn_curr_pos[1]))
				goto is_number;
			tkn_curr_pos++;
			break;
		case '/':
			tkn_curr_pos++;
			if (*tkn_curr_pos == '*') {
				// Comment: /* ... */
				// Look for: /*!99999 ... */  version conditional statements
				tkn_curr_pos++;
				if (*tkn_curr_pos == '!') {
					tkn_curr_pos++;
					if (isdigit(*tkn_curr_pos)) {
						while (isdigit(*tkn_curr_pos))
							tkn_curr_pos++;
						tkn_in_comment = true;
						goto restart;
					}
				}

				while (*tkn_curr_pos && !(*tkn_curr_pos == '*' && *(tkn_curr_pos+1) == '/')) tkn_curr_pos++;
				if (*tkn_curr_pos == '*' && *(tkn_curr_pos+1) == '/')
					tkn_curr_pos += 2;
				goto restart;
			}
			break;
		case '\'':
			token_type = XT_TK_STRING;
			goto is_string;
		case '"':
		case '`':
			token_type = XT_TK_IDENTIFIER;
			is_string:
			quote = *tkn_curr_pos;
			tkn_curr_pos++;
			while (*tkn_curr_pos) {
				if (*tkn_curr_pos == quote) {
					// Doubling the quote means stay in string...
					if (*(tkn_curr_pos + 1) != quote)
						break;
					tkn_curr_pos++;
				}
526 527 528 529 530 531 532
				/* TODO: Unless sql_mode == 'NO_BACKSLASH_ESCAPES'!!! */
				if (*tkn_curr_pos == '\\') {
					if (*(tkn_curr_pos+1) == quote) {
						if (quote == '"' || quote == '\'')
							tkn_curr_pos++;
					}
				}
Paul McCullagh's avatar
Paul McCullagh committed
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
				tkn_curr_pos++;
			}
			
			if (*tkn_curr_pos == quote)
				tkn_curr_pos++;
			break;
		case '$':
			goto is_identifier;
		case '*':
			if (tkn_in_comment) {
				if (tkn_curr_pos[1] == '/') {
					tkn_in_comment = false;
					tkn_curr_pos += 2;
					goto restart;
				}
			}
			/* No break required! */
		default:
			if (isNumberChar(tkn_curr_pos[0], tkn_curr_pos[1]))
				goto is_number;

			if (isSingleChar(*tkn_curr_pos)) {
				token_type = XT_TK_PUNCTUATION;
				// The rest are singles...
				tkn_curr_pos++;
				break;
			}
			
			is_identifier:
			// Identifier (any string of characters that is not punctuation or a space:
			token_type = XT_TK_IDENTIFIER;
			while (isIdentifierChar(*tkn_curr_pos))
				tkn_curr_pos++;
			break;

			is_number:
			must_be_num = false;
			token_type = XT_TK_NUMBER;

			if (*tkn_curr_pos == '-' || *tkn_curr_pos == '+') {
				must_be_num = true;
				tkn_curr_pos++;
			}

			// Number: 9999 [ . 9999 ] [ e/E [+/-] 9999 ]
			// However, 9999e or 9999E is an identifier!
			while (*tkn_curr_pos && myxt_isdigit(tkn_charset, *tkn_curr_pos)) tkn_curr_pos++;
			
			if (*tkn_curr_pos == '.') {
				must_be_num = true;
				tkn_curr_pos++;
				while (*tkn_curr_pos && myxt_isdigit(tkn_charset, *tkn_curr_pos)) tkn_curr_pos++;
			}

			if (*tkn_curr_pos == 'e' || *tkn_curr_pos == 'E') {
				tkn_curr_pos++;

				if (isNumberChar(tkn_curr_pos[0], tkn_curr_pos[1])) {
					must_be_num = true;

					if (*tkn_curr_pos == '-' || *tkn_curr_pos == '+')
						tkn_curr_pos++;
					while (*tkn_curr_pos && myxt_isdigit(tkn_charset, *tkn_curr_pos))
						tkn_curr_pos++;
				}
				else if (!must_be_num)
					token_type = XT_TK_IDENTIFIER;
			}

			if (must_be_num || !isIdentifierChar(*tkn_curr_pos))
				break;

			/* Crazy, but true. An identifier can start by looking like a number! */
			goto is_identifier;
	}

	return newToken(self, token_type, token_start, tkn_curr_pos);
}

XTToken *XTTokenizer::nextToken(XTThreadPtr self, c_char *keyword, XTToken *tk)
{
	tk->expectKeyWord(self, keyword);
	return nextToken(self);
}

/*
 * -----------------------------------------------------------------------
 * Parser
 */

/*
	We must parse the following syntax. Note that the constraints
	may be embedded in a CREATE TABLE/ALTER TABLE statement.

	[CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name, ...)
    [ON DELETE {RESTRICT | CASCADE | SET NULL | SET DEFAULT | NO ACTION}]
    [ON UPDATE {RESTRICT | CASCADE | SET NULL | SET DEFAULT | NO ACTION}]
*/

class XTParseTable : public XTObject {
	public:	
	void raiseError(XTThreadPtr self, XTToken *tk, int err);

	private:
	XTTokenizer			*pt_tokenizer;
	XTToken				*pt_current;
	XTStringBufferRec	pt_sbuffer;

	void syntaxError(XTThreadPtr self, XTToken *tk);	

	void parseIdentifier(XTThreadPtr self, char *name);
	int parseKeyAction(XTThreadPtr self);	
	void parseCreateTable(XTThreadPtr self);
	void parseAddTableItem(XTThreadPtr self);
648
	void parseQualifiedName(XTThreadPtr self, char *parent_name, char *name);
Paul McCullagh's avatar
Paul McCullagh committed
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
	void parseTableName(XTThreadPtr self, bool alterTable);
	void parseExpression(XTThreadPtr self, bool allow_reserved);
	void parseBrackets(XTThreadPtr self);
	void parseMoveColumn(XTThreadPtr self);
	
	/* If old_col_name is NULL, then this column is to be added,
	 * if old_col_name is empty (strlen() = 0) then the column
	 * exists, and should be modified, otherwize the column
	 * given is to be modified.
	 */
	void parseColumnDefinition(XTThreadPtr self, char *old_col_name);
	void parseDataType(XTThreadPtr self);
	void parseReferenceDefinition(XTThreadPtr self, u_int req_cols);
	void optionalIndexName(XTThreadPtr self);
	void optionalIndexType(XTThreadPtr self);
	u_int columnList(XTThreadPtr self, bool index_cols);
	void parseAlterTable(XTThreadPtr self);	
	void parseCreateIndex(XTThreadPtr self);
	void parseDropIndex(XTThreadPtr self);

	public:	
	XTParseTable() {
		pt_tokenizer = NULL;
		pt_current = NULL;
		memset(&pt_sbuffer, 0, sizeof(XTStringBufferRec));
	}

676
	virtual void finalize(XTThreadPtr XT_UNUSED(self)) {
Paul McCullagh's avatar
Paul McCullagh committed
677 678 679 680 681 682
		if (pt_tokenizer)
			delete pt_tokenizer;
		xt_sb_set_size(NULL, &pt_sbuffer, 0);
	}

	// Hooks to receive output from the parser:
683
	virtual void setTableName(XTThreadPtr XT_UNUSED(self), char *XT_UNUSED(name), bool XT_UNUSED(alterTable)) {
Paul McCullagh's avatar
Paul McCullagh committed
684
	}
685
	virtual void addColumn(XTThreadPtr XT_UNUSED(self), char *XT_UNUSED(col_name), char *XT_UNUSED(old_col_name)) {
Paul McCullagh's avatar
Paul McCullagh committed
686 687 688 689 690
	}
	virtual void setDataType(XTThreadPtr self, char *cstring) {
		if (cstring) 
			xt_free(self, cstring);
	}
691
	virtual void setNull(XTThreadPtr XT_UNUSED(self), bool XT_UNUSED(nullOK)) {
Paul McCullagh's avatar
Paul McCullagh committed
692
	}
693
	virtual void setAutoInc(XTThreadPtr XT_UNUSED(self), bool XT_UNUSED(autoInc)) {
Paul McCullagh's avatar
Paul McCullagh committed
694 695 696 697 698
	}
	
	/* Add a contraint. If lastColumn is TRUE then add the contraint 
	 * to the last column. If not, expect addListedColumn() to be called.
	 */
699
	virtual void addConstraint(XTThreadPtr XT_UNUSED(self), char *XT_UNUSED(name), u_int XT_UNUSED(type), bool XT_UNUSED(lastColumn)) {
Paul McCullagh's avatar
Paul McCullagh committed
700 701 702 703 704
	}
	
	/* Move the last column created. If symbol is NULL then move the column to the
	 * first position, else move it to the position just after the given column.
	 */
705
	virtual void moveColumn(XTThreadPtr XT_UNUSED(self), char *XT_UNUSED(col_name)) {
Paul McCullagh's avatar
Paul McCullagh committed
706 707
	}

708
	virtual void dropColumn(XTThreadPtr XT_UNUSED(self), char *XT_UNUSED(col_name)) {
Paul McCullagh's avatar
Paul McCullagh committed
709 710
	}

711
	virtual void dropConstraint(XTThreadPtr XT_UNUSED(self), char *XT_UNUSED(name), u_int XT_UNUSED(type)) {
Paul McCullagh's avatar
Paul McCullagh committed
712 713
	}

714
	virtual void setIndexName(XTThreadPtr XT_UNUSED(self), char *XT_UNUSED(name)) {
Paul McCullagh's avatar
Paul McCullagh committed
715
	}
716
	virtual void addListedColumn(XTThreadPtr XT_UNUSED(self), char *XT_UNUSED(index_col_name)) {
Paul McCullagh's avatar
Paul McCullagh committed
717
	}
718
	virtual void setReferencedTable(XTThreadPtr XT_UNUSED(self), char *XT_UNUSED(ref_schema), char *XT_UNUSED(ref_table)) {
Paul McCullagh's avatar
Paul McCullagh committed
719
	}
720
	virtual void addReferencedColumn(XTThreadPtr XT_UNUSED(self), char *XT_UNUSED(index_col_name)) {
Paul McCullagh's avatar
Paul McCullagh committed
721
	}
722
	virtual void setActions(XTThreadPtr XT_UNUSED(self), int XT_UNUSED(on_delete), int XT_UNUSED(on_update)) {
Paul McCullagh's avatar
Paul McCullagh committed
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
	}

	virtual void parseTable(XTThreadPtr self, bool convert, char *sql);	
};

void XTParseTable::raiseError(XTThreadPtr self, XTToken *tk, int err)
{
	char buffer[100];

	tk->getTokenText(buffer, 100);
	xt_throw_ixterr(XT_CONTEXT, err, buffer);
}

void XTParseTable::syntaxError(XTThreadPtr self, XTToken *tk)
{
	raiseError(self, tk, XT_ERR_SYNTAX);
}

void XTParseTable::parseIdentifier(XTThreadPtr self, char *name)
{
	pt_current->expectIdentifier(self);
	if (name) {
		if (pt_current->getString(name, XT_IDENTIFIER_NAME_SIZE) >= XT_IDENTIFIER_NAME_SIZE)
			raiseError(self, pt_current, XT_ERR_ID_TOO_LONG);
	}
	pt_current = pt_tokenizer->nextToken(self);
}

int XTParseTable::parseKeyAction(XTThreadPtr self)
{
	XTToken *tk;

	tk = pt_tokenizer->nextToken(self);

	if (tk->isKeyWord("RESTRICT"))
		return XT_KEY_ACTION_RESTRICT;

	if (tk->isKeyWord("CASCADE"))
		return XT_KEY_ACTION_CASCADE;

	if (tk->isKeyWord("SET")) {
		tk = pt_tokenizer->nextToken(self);
		if (tk->isKeyWord("DEFAULT"))
			return XT_KEY_ACTION_SET_DEFAULT;
		tk->expectKeyWord(self, "NULL");
		return XT_KEY_ACTION_SET_NULL;
	}

	if (tk->isKeyWord("NO")) {
		tk = pt_tokenizer->nextToken(self);
		tk->expectKeyWord(self, "ACTION");
		return XT_KEY_ACTION_NO_ACTION;
	}

	syntaxError(self, tk);
	return 0;
}

void XTParseTable::parseTable(XTThreadPtr self, bool convert, char *sql)
{
	if (pt_tokenizer)
		delete pt_tokenizer;
	pt_tokenizer = new XTTokenizer(convert, sql);
	if (!pt_tokenizer)
		xt_throw_errno(XT_CONTEXT, XT_ENOMEM);
	pt_current = pt_tokenizer->nextToken(self);

	if (pt_current->isKeyWord("CREATE")) {
		pt_current = pt_tokenizer->nextToken(self);
		if (pt_current->isKeyWord("TEMPORARY") || pt_current->isKeyWord("TABLE"))
			parseCreateTable(self);
		else
			parseCreateIndex(self);
	}
	else if (pt_current->isKeyWord("ALTER"))
		parseAlterTable(self);
	else if (pt_current->isKeyWord("DROP"))
		parseDropIndex(self);
	else if (pt_current->isKeyWord("TRUNCATE")) {
		pt_current = pt_tokenizer->nextToken(self);
		if (pt_current->isKeyWord("TABLE"))
			pt_current = pt_tokenizer->nextToken(self);
		parseTableName(self, true);
	}
	else if (pt_current->isKeyWord("OPTIMIZE") || pt_current->isKeyWord("REPAIR")) {
		/* OPTIMIZE [LOCAL | NO_WRITE_TO_BINLOG] TABLE tbl_name [, tbl_name] ...
		 *
		 * GOTCHA: This cannot work if more than one table is specified,
		 * because then I cannot find the source table?!
		 */
		pt_current = pt_tokenizer->nextToken(self);
		while (!pt_current->isEOF() && !pt_current->isKeyWord("TABLE"))
			pt_current = pt_tokenizer->nextToken(self);
		pt_current = pt_tokenizer->nextToken(self);
		parseTableName(self, true);
	}
	else
		syntaxError(self, pt_current);
}

void XTParseTable::parseCreateTable(XTThreadPtr self)
{
	if (pt_current->isKeyWord("TEMPORARY"))
		pt_current = pt_tokenizer->nextToken(self);
	pt_current = pt_tokenizer->nextToken(self, "TABLE", pt_current);
	if (pt_current->isKeyWord("IF")) {
		pt_current = pt_tokenizer->nextToken(self);
		pt_current = pt_tokenizer->nextToken(self, "NOT", pt_current);
		pt_current = pt_tokenizer->nextToken(self, "EXISTS", pt_current);
	}

	/* Table name is optional (when loading from dictionary)! */
	if (!pt_current->isKeyWord("("))
		parseTableName(self, false);
	else
		setTableName(self, NULL, false);

	/* We do not support CREATE ... SELECT! */
	if (pt_current->isKeyWord("(")) {
		pt_current = pt_tokenizer->nextToken(self);
		// Avoid this:
		// create table t3 (select group_concat(a) as a from t1 where a = 'a') union
		// (select group_concat(b) as a from t1 where a = 'b');
		if (pt_current->isKeyWord("SELECT"))
			return;
		
		/* Allow empty table definition for temporary table. */
		while (!pt_current->isEOF() && !pt_current->isKeyWord(")")) {
			parseAddTableItem(self);
			if (!pt_current->isKeyWord(","))
				break;
			pt_current = pt_tokenizer->nextToken(self);
		}
		pt_current = pt_tokenizer->nextToken(self, ")", pt_current);
	}
}

void XTParseTable::parseAddTableItem(XTThreadPtr self)
{
	char name[XT_IDENTIFIER_NAME_SIZE];

	*name = 0;
	if (pt_current->isKeyWord("CONSTRAINT")) {
		pt_current = pt_tokenizer->nextToken(self);
		if (pt_current->isIdentifier())
868
			parseQualifiedName(self, NULL, name);
Paul McCullagh's avatar
Paul McCullagh committed
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
	}

	if (pt_current->isReservedWord(XT_TK_PRIMARY)) {
		pt_current = pt_tokenizer->nextToken(self);
		pt_current = pt_tokenizer->nextToken(self, "KEY", pt_current);

		addConstraint(self, name, XT_DD_KEY_PRIMARY, false);
		optionalIndexType(self);

		/* GATCHA: Wierd?! This syntax is used in a test:
		 * alter table t1 add primary key aaa(tt);
		 */
		if (!pt_current->isKeyWord("("))
			pt_current = pt_tokenizer->nextToken(self);
		columnList(self, true);
	}
	else if (pt_current->isReservedWord(XT_TK_UNIQUE) ||
		pt_current->isReservedWord(XT_TK_FULLTEXT) ||
		pt_current->isReservedWord(XT_TK_SPATIAL) ||
		pt_current->isReservedWord(XT_TK_INDEX) ||
		pt_current->isReservedWord(XT_TK_KEY)) {
		bool is_unique = false;

		if (pt_current->isReservedWord(XT_TK_FULLTEXT) || pt_current->isReservedWord(XT_TK_SPATIAL))
			pt_current = pt_tokenizer->nextToken(self);
		else if (pt_current->isReservedWord(XT_TK_UNIQUE)) {
			pt_current = pt_tokenizer->nextToken(self);
			is_unique = true;
		}
		if (pt_current->isReservedWord(XT_TK_INDEX) || pt_current->isReservedWord(XT_TK_KEY))
			pt_current = pt_tokenizer->nextToken(self);

		addConstraint(self, name, is_unique ? XT_DD_INDEX_UNIQUE : XT_DD_INDEX, false);
		optionalIndexName(self);
		optionalIndexType(self);
		columnList(self, true);
	}
	else if (pt_current->isReservedWord(XT_TK_CHECK)) {
		pt_current = pt_tokenizer->nextToken(self);
		parseExpression(self, false);
	}
	else if (pt_current->isReservedWord(XT_TK_FOREIGN)) {
		u_int req_cols;

		pt_current = pt_tokenizer->nextToken(self);
		pt_current = pt_tokenizer->nextToken(self, "KEY", pt_current);

		addConstraint(self, name, XT_DD_KEY_FOREIGN, false);
		optionalIndexName(self);
		req_cols = columnList(self, false);
		/* GOTCHA: According the MySQL manual this is optional, but without domains,
		 * it is required!
		 */
		parseReferenceDefinition(self, req_cols);
	}
	else if (pt_current->isKeyWord("(")) {
		pt_current = pt_tokenizer->nextToken(self);
		for (;;) {
			parseColumnDefinition(self, NULL);
			if (!pt_current->isKeyWord(","))
				break;
			pt_current = pt_tokenizer->nextToken(self);
		}
		pt_current = pt_tokenizer->nextToken(self, ")", pt_current);
	}
	else {
		if (pt_current->isReservedWord(XT_TK_COLUMN))
			pt_current = pt_tokenizer->nextToken(self);
		parseColumnDefinition(self, NULL);
		parseMoveColumn(self);
	}
	/* GOTCHA: Support: create table t1 (a int not null, key `a` (a) key_block_size=1024)
	 * and any other undocumented syntax?!
	 */
	parseExpression(self, true);
}

void XTParseTable::parseExpression(XTThreadPtr self, bool allow_reserved)
{
	while (!pt_current->isEOF() && !pt_current->isKeyWord(",") &&
		!pt_current->isKeyWord(")") && (allow_reserved || !pt_current->isReservedWord())) {
		if (pt_current->isKeyWord("("))
			parseBrackets(self);
		else
			pt_current = pt_tokenizer->nextToken(self);
	}
}

void XTParseTable::parseBrackets(XTThreadPtr self)
{
	u_int cnt = 1;
	pt_current = pt_tokenizer->nextToken(self, "(", pt_current);
	while (cnt) {
		if (pt_current->isEOF())
			break;
		if (pt_current->isKeyWord("("))
			cnt++;
		if (pt_current->isKeyWord(")"))
			cnt--;
		pt_current = pt_tokenizer->nextToken(self);
	}
}

void XTParseTable::parseMoveColumn(XTThreadPtr self)
{
	if (pt_current->isKeyWord("FIRST")) {
		pt_current = pt_tokenizer->nextToken(self);
		/* If name is NULL it means move to the front. */
		moveColumn(self, NULL);
	}
	else if (pt_current->isKeyWord("AFTER")) {
		char	name[XT_IDENTIFIER_NAME_SIZE];

		pt_current = pt_tokenizer->nextToken(self);
983
		parseQualifiedName(self, NULL, name);
Paul McCullagh's avatar
Paul McCullagh committed
984 985 986 987
		moveColumn(self, name);
	}
}

988
void XTParseTable::parseQualifiedName(XTThreadPtr self, char *parent_name, char *name)
Paul McCullagh's avatar
Paul McCullagh committed
989
{
990 991
	if (parent_name)
		parent_name[0] = '\0';
Paul McCullagh's avatar
Paul McCullagh committed
992 993 994 995 996 997 998 999 1000
	/* Should be an identifier by I have this example:
	 * CREATE TABLE t1 ( comment CHAR(32) ASCII NOT NULL, koi8_ru_f CHAR(32) CHARACTER SET koi8r NOT NULL default '' ) CHARSET=latin5;
	 *
	 * COMMENT is elsewhere used as reserved word?!
	 */
	if (pt_current->getString(name, XT_IDENTIFIER_NAME_SIZE) >= XT_IDENTIFIER_NAME_SIZE)
		raiseError(self, pt_current, XT_ERR_ID_TOO_LONG);
	pt_current = pt_tokenizer->nextToken(self);
	while (pt_current->isKeyWord(".")) {
1001 1002
		if (parent_name)
			xt_strcpy(XT_IDENTIFIER_NAME_SIZE,parent_name, name);
Paul McCullagh's avatar
Paul McCullagh committed
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
		pt_current = pt_tokenizer->nextToken(self);
		/* Accept anything after the DOT! */
		if (pt_current->getString(name, XT_IDENTIFIER_NAME_SIZE) >= XT_IDENTIFIER_NAME_SIZE)
			raiseError(self, pt_current, XT_ERR_ID_TOO_LONG);
		pt_current = pt_tokenizer->nextToken(self);
	}
}

void XTParseTable::parseTableName(XTThreadPtr self, bool alterTable)
{
	char name[XT_IDENTIFIER_NAME_SIZE];

1015
	parseQualifiedName(self, NULL, name);
Paul McCullagh's avatar
Paul McCullagh committed
1016 1017 1018 1019 1020 1021 1022 1023
	setTableName(self, name, alterTable);
}

void XTParseTable::parseColumnDefinition(XTThreadPtr self, char *old_col_name)
{
	char col_name[XT_IDENTIFIER_NAME_SIZE];

	// column_definition
1024
	parseQualifiedName(self, NULL, col_name);
Paul McCullagh's avatar
Paul McCullagh committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
	addColumn(self, col_name, old_col_name);
	parseDataType(self);

	for (;;) {
		if (pt_current->isReservedWord(XT_TK_NOT)) {
			pt_current = pt_tokenizer->nextToken(self);
			pt_current = pt_tokenizer->nextToken(self, "NULL", pt_current);
			setNull(self, false);
		}
		else if (pt_current->isReservedWord(XT_TK_NULL)) {
			pt_current = pt_tokenizer->nextToken(self);
			setNull(self, true);
		}
		else if (pt_current->isReservedWord(XT_TK_DEFAULT)) {
			pt_current = pt_tokenizer->nextToken(self);
			/* Possible here [ + | - ] <value> or [ <charset> ] <string> */
			parseExpression(self, false);
		}
		else if (pt_current->isReservedWord(XT_TK_AUTO_INCREMENT)) {
			pt_current = pt_tokenizer->nextToken(self);
			setAutoInc(self, true);
		}
		else if (pt_current->isReservedWord(XT_TK_UNIQUE)) {
			pt_current = pt_tokenizer->nextToken(self);
			if (pt_current->isReservedWord(XT_TK_KEY))
				pt_current = pt_tokenizer->nextToken(self);
			addConstraint(self, NULL, XT_DD_INDEX_UNIQUE, true);
		}
		else if (pt_current->isReservedWord(XT_TK_KEY)) {
			pt_current = pt_tokenizer->nextToken(self);
			addConstraint(self, NULL, XT_DD_INDEX, true);
		}
		else if (pt_current->isReservedWord(XT_TK_PRIMARY)) {
			pt_current = pt_tokenizer->nextToken(self);
			pt_current = pt_tokenizer->nextToken(self, "KEY", pt_current);
			addConstraint(self, NULL, XT_DD_KEY_PRIMARY, true);
		}
		else if (pt_current->isReservedWord(XT_TK_COMMENT)) {
			pt_current = pt_tokenizer->nextToken(self);
			pt_current = pt_tokenizer->nextToken(self);
		}
		else if (pt_current->isReservedWord(XT_TK_REFERENCES)) {
			addConstraint(self, NULL, XT_DD_KEY_FOREIGN, true);
			parseReferenceDefinition(self, 1);
		}
		else if (pt_current->isReservedWord(XT_TK_CHECK)) {
			pt_current = pt_tokenizer->nextToken(self);
			parseExpression(self, false);
		}
		/* GOTCHA: Not in the documentation:
		 * CREATE TABLE t1 (c varchar(255) NOT NULL COLLATE utf8_general_ci, INDEX (c))
		 */
		else if (pt_current->isReservedWord(XT_TK_COLLATE)) {
			pt_current = pt_tokenizer->nextToken(self);
			pt_current = pt_tokenizer->nextToken(self);
		}
		else
			break;
	}
}

void XTParseTable::parseDataType(XTThreadPtr self)
{
	/* Not actually implemented because MySQL allows undocumented
	 * syntax like this:
	 * create table t1 (c national character varying(10))
	 */
	parseExpression(self, false);
	setDataType(self, NULL);
}

void XTParseTable::optionalIndexName(XTThreadPtr self)
{
	// [index_name]
	if (!pt_current->isKeyWord("USING") && !pt_current->isKeyWord("(")) {
		char name[XT_IDENTIFIER_NAME_SIZE];

		parseIdentifier(self, name);
		setIndexName(self, name);
	}
}

void XTParseTable::optionalIndexType(XTThreadPtr self)
{
	// USING {BTREE | HASH}
	if (pt_current->isKeyWord("USING")) {
		pt_current = pt_tokenizer->nextToken(self);
		pt_current = pt_tokenizer->nextToken(self);
	}
}

u_int XTParseTable::columnList(XTThreadPtr self, bool index_cols)
{
	char	name[XT_IDENTIFIER_NAME_SIZE];
	u_int	cols = 0;
	
	pt_current->expectKeyWord(self, "(");
	do {
		pt_current = pt_tokenizer->nextToken(self);
1124
		parseQualifiedName(self, NULL, name);
Paul McCullagh's avatar
Paul McCullagh committed
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
		addListedColumn(self, name);
		cols++;
		if (index_cols) {
			if (pt_current->isKeyWord("(")) {
				pt_current = pt_tokenizer->nextToken(self);
				pt_current = pt_tokenizer->nextToken(self);
				pt_current = pt_tokenizer->nextToken(self, ")", pt_current);
			}
			if (pt_current->isKeyWord("ASC"))
				pt_current = pt_tokenizer->nextToken(self);
			else if (pt_current->isKeyWord("DESC"))
				pt_current = pt_tokenizer->nextToken(self);
		}
	} while (pt_current->isKeyWord(","));
	pt_current = pt_tokenizer->nextToken(self, ")", pt_current);
	return cols;
}

void XTParseTable::parseReferenceDefinition(XTThreadPtr self, u_int req_cols)
{
Paul McCullagh's avatar
Paul McCullagh committed
1145 1146
	int		on_delete = XT_KEY_ACTION_RESTRICT;
	int		on_update = XT_KEY_ACTION_RESTRICT;
Paul McCullagh's avatar
Paul McCullagh committed
1147
	char	name[XT_IDENTIFIER_NAME_SIZE];
1148
	char	parent_name[XT_IDENTIFIER_NAME_SIZE];
Paul McCullagh's avatar
Paul McCullagh committed
1149 1150 1151 1152
	u_int	cols = 0;

	// REFERENCES tbl_name
	pt_current = pt_tokenizer->nextToken(self, "REFERENCES", pt_current);
1153 1154
	parseQualifiedName(self, parent_name, name);
	setReferencedTable(self, parent_name[0] ? parent_name : NULL, name);
Paul McCullagh's avatar
Paul McCullagh committed
1155 1156 1157 1158 1159 1160

	// [ (index_col_name,...) ]
	if (pt_current->isKeyWord("(")) {
		pt_current->expectKeyWord(self, "(");
		do {
			pt_current = pt_tokenizer->nextToken(self);
1161
			parseQualifiedName(self, NULL, name);
Paul McCullagh's avatar
Paul McCullagh committed
1162 1163 1164 1165 1166 1167 1168 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 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
			addReferencedColumn(self, name);
			cols++;
			if (cols > req_cols)
				raiseError(self, pt_current, XT_ERR_INCORRECT_NO_OF_COLS);
		} while (pt_current->isKeyWord(","));
		if (cols != req_cols)
			raiseError(self, pt_current, XT_ERR_INCORRECT_NO_OF_COLS);
		pt_current = pt_tokenizer->nextToken(self, ")", pt_current);			
	}
	else
		addReferencedColumn(self, NULL);

	// [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE]
	if (pt_current->isKeyWord("MATCH")) {
		pt_current = pt_tokenizer->nextToken(self);
		pt_current = pt_tokenizer->nextToken(self);
	}

	// [ON DELETE {RESTRICT | CASCADE | SET NULL | SET DEFAULT | NO ACTION}]
	// [ON UPDATE {RESTRICT | CASCADE | SET NULL | SET DEFAULT | NO ACTION}]
	while (pt_current->isKeyWord("ON")) {
		pt_current = pt_tokenizer->nextToken(self);
		if (pt_current->isKeyWord("DELETE"))
			on_delete = parseKeyAction(self);
		else if (pt_current->isKeyWord("UPDATE"))
			on_update = parseKeyAction(self);
		else
			syntaxError(self, pt_current);
		pt_current = pt_tokenizer->nextToken(self);
	}

	setActions(self, on_delete, on_update);
}

void XTParseTable::parseAlterTable(XTThreadPtr self)
{
	char name[XT_IDENTIFIER_NAME_SIZE];

	pt_current = pt_tokenizer->nextToken(self, "ALTER", pt_current);
	if (pt_current->isKeyWord("IGNORE"))
		pt_current = pt_tokenizer->nextToken(self);
	pt_current = pt_tokenizer->nextToken(self, "TABLE", pt_current);
	parseTableName(self, true);
	for (;;) {
		if (pt_current->isKeyWord("ADD")) {
			pt_current = pt_tokenizer->nextToken(self);
			parseAddTableItem(self);
		}
		else if (pt_current->isKeyWord("ALTER")) {
			pt_current = pt_tokenizer->nextToken(self);
			if (pt_current->isReservedWord(XT_TK_COLUMN))
				pt_current = pt_tokenizer->nextToken(self);
			pt_current->expectIdentifier(self);
			pt_current = pt_tokenizer->nextToken(self);
			if (pt_current->isKeyWord("SET")) {
				pt_current = pt_tokenizer->nextToken(self);
				pt_current = pt_tokenizer->nextToken(self, "DEFAULT", pt_current);
				pt_current = pt_tokenizer->nextToken(self);
			}
			else if (pt_current->isKeyWord("DROP")) {
				pt_current = pt_tokenizer->nextToken(self);
				pt_current = pt_tokenizer->nextToken(self, "DEFAULT", pt_current);
			}
		}
		else if (pt_current->isKeyWord("CHANGE")) {
			char old_col_name[XT_IDENTIFIER_NAME_SIZE];

			pt_current = pt_tokenizer->nextToken(self);
			if (pt_current->isReservedWord(XT_TK_COLUMN))
				pt_current = pt_tokenizer->nextToken(self);

1233
			parseQualifiedName(self, NULL, old_col_name);
Paul McCullagh's avatar
Paul McCullagh committed
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
			parseColumnDefinition(self, old_col_name);
			parseMoveColumn(self);
		}
		else if (pt_current->isKeyWord("MODIFY")) {
			pt_current = pt_tokenizer->nextToken(self);
			if (pt_current->isReservedWord(XT_TK_COLUMN))
				pt_current = pt_tokenizer->nextToken(self);
			parseColumnDefinition(self, NULL);
			parseMoveColumn(self);
		}
		else if (pt_current->isKeyWord("DROP")) {
			pt_current = pt_tokenizer->nextToken(self);
			if (pt_current->isReservedWord(XT_TK_PRIMARY)) {
				pt_current = pt_tokenizer->nextToken(self);
				pt_current = pt_tokenizer->nextToken(self, "KEY", pt_current);
				dropConstraint(self, NULL, XT_DD_KEY_PRIMARY);
			}
			else if (pt_current->isReservedWord(XT_TK_INDEX) || pt_current->isReservedWord(XT_TK_KEY)) {
				pt_current = pt_tokenizer->nextToken(self);
				parseIdentifier(self, name);
				dropConstraint(self, name, XT_DD_INDEX);
			}
			else if (pt_current->isReservedWord(XT_TK_FOREIGN)) {
				pt_current = pt_tokenizer->nextToken(self);
				pt_current = pt_tokenizer->nextToken(self, "KEY", pt_current);
				parseIdentifier(self, name);
				dropConstraint(self, name, XT_DD_KEY_FOREIGN);
			}
			else {
				if (pt_current->isReservedWord(XT_TK_COLUMN))
					pt_current = pt_tokenizer->nextToken(self);
1265
				parseQualifiedName(self, NULL, name);
Paul McCullagh's avatar
Paul McCullagh committed
1266 1267 1268 1269 1270 1271 1272
				dropColumn(self, name);
			}
		}
		else if (pt_current->isKeyWord("RENAME")) {
			pt_current = pt_tokenizer->nextToken(self);
			if (pt_current->isKeyWord("TO"))
				pt_current = pt_tokenizer->nextToken(self);
1273
			parseQualifiedName(self, NULL, name);
Paul McCullagh's avatar
Paul McCullagh committed
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
		}
		else
			/* Just ignore the syntax until the next , */
			parseExpression(self, true);
		if (!pt_current->isKeyWord(","))
			break;
		pt_current = pt_tokenizer->nextToken(self);
	}
}

void XTParseTable::parseCreateIndex(XTThreadPtr self)
{
	char name[XT_IDENTIFIER_NAME_SIZE];
	bool is_unique = false;

	if (pt_current->isReservedWord(XT_TK_UNIQUE)) {
		pt_current = pt_tokenizer->nextToken(self);
		is_unique = true;
	}
	else if (pt_current->isReservedWord(XT_TK_FULLTEXT))
		pt_current = pt_tokenizer->nextToken(self);
	else if (pt_current->isKeyWord("SPACIAL"))
		pt_current = pt_tokenizer->nextToken(self);
	pt_current = pt_tokenizer->nextToken(self, "INDEX", pt_current);
1298
	parseQualifiedName(self, NULL, name);
Paul McCullagh's avatar
Paul McCullagh committed
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
	optionalIndexType(self);
	pt_current = pt_tokenizer->nextToken(self, "ON", pt_current);
	parseTableName(self, true);
	addConstraint(self, NULL, is_unique ? XT_DD_INDEX_UNIQUE : XT_DD_INDEX, false);
	setIndexName(self, name);
	columnList(self, true);
}

void XTParseTable::parseDropIndex(XTThreadPtr self)
{
	char name[XT_IDENTIFIER_NAME_SIZE];

	pt_current = pt_tokenizer->nextToken(self, "DROP", pt_current);
	pt_current = pt_tokenizer->nextToken(self, "INDEX", pt_current);
1313
	parseQualifiedName(self, NULL, name);
Paul McCullagh's avatar
Paul McCullagh committed
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
	pt_current = pt_tokenizer->nextToken(self, "ON", pt_current);
	parseTableName(self, true);
	dropConstraint(self, name, XT_DD_INDEX);
}

/*
 * -----------------------------------------------------------------------
 * Create/Alter table table
 */

class XTCreateTable : public XTParseTable {
	public:
	bool					ct_convert;
1327
	MX_CONST_CHARSET_INFO	*ct_charset;
Paul McCullagh's avatar
Paul McCullagh committed
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
	XTPathStrPtr			ct_tab_path;
	u_int					ct_contraint_no;
	XTDDTable				*ct_curr_table;
	XTDDColumn				*ct_curr_column;
	XTDDConstraint			*ct_curr_constraint;

	XTCreateTable(bool convert, XTPathStrPtr tab_path) : XTParseTable() {
		ct_convert = convert;
		ct_charset = myxt_getcharset(convert);
		ct_tab_path = tab_path;
		ct_curr_table = NULL;
		ct_curr_column = NULL;
		ct_curr_constraint = NULL;
	}

	virtual void finalize(XTThreadPtr self) {
		if (ct_curr_table)
			ct_curr_table->release(self);
		XTParseTable::finalize(self);
	}

	virtual void setTableName(XTThreadPtr self, char *name, bool alterTable);
	virtual void addColumn(XTThreadPtr self, char *col_name, char *old_col_name);
	virtual void addConstraint(XTThreadPtr self, char *name, u_int type, bool lastColumn);
	virtual void dropConstraint(XTThreadPtr self, char *name, u_int type);
	virtual void addListedColumn(XTThreadPtr self, char *index_col_name);
1354
	virtual void setReferencedTable(XTThreadPtr self, char *ref_schema, char *ref_table);
Paul McCullagh's avatar
Paul McCullagh committed
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 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
	virtual void addReferencedColumn(XTThreadPtr self, char *index_col_name);
	virtual void setActions(XTThreadPtr self, int on_delete, int on_update);

	virtual void parseTable(XTThreadPtr self, bool convert, char *sql);	
};

static void ri_free_create_table(XTThreadPtr self, XTCreateTable *ct)
{
	if (ct)
		ct->release(self);
}

XTDDTable *xt_ri_create_table(XTThreadPtr self, bool convert, XTPathStrPtr tab_path, char *sql, XTDDTable *start_tab)
{
	XTCreateTable	*ct;
	XTDDTable		*dd_tab;

	if (!(ct = new XTCreateTable(convert, tab_path))) {
		if (start_tab)
			start_tab->release(self);
		xt_throw_errno(XT_CONTEXT, XT_ENOMEM);
	}

	ct->ct_curr_table = start_tab;

	pushr_(ri_free_create_table, ct);

	ct->parseTable(self, convert, sql);
	
	/* Return the table ... */
	dd_tab = ct->ct_curr_table;
	ct->ct_curr_table = NULL;

	freer_();
	return dd_tab;
}

void XTCreateTable::parseTable(XTThreadPtr self, bool convert, char *sql)
{
	u_int i;

	ct_contraint_no = 0;
	XTParseTable::parseTable(self, convert, sql);

	/* Remove contraints that do not have matching columns. */
	for (i=0; i<ct_curr_table->dt_indexes.size();) {
		if (!ct_curr_table->dt_indexes.itemAt(i)->attachColumns())
			ct_curr_table->dt_indexes.remove(self, i);
		else
			i++;
	}

	for (i=0; i<ct_curr_table->dt_fkeys.size(); ) {
		if (!ct_curr_table->dt_fkeys.itemAt(i)->attachColumns())
			ct_curr_table->dt_fkeys.remove(self, i);
		else
			i++;
	}
}

void XTCreateTable::setTableName(XTThreadPtr self, char *name, bool alterTable)
{
	char path[PATH_MAX];

	if (!name)
		return;

	xt_strcpy(PATH_MAX, path, ct_tab_path->ps_path);
	xt_remove_last_name_of_path(path);

	if (ct_convert) {
		char	buffer[XT_IDENTIFIER_NAME_SIZE];
		size_t	len;

		myxt_static_convert_identifier(self, ct_charset, name, buffer, XT_IDENTIFIER_NAME_SIZE);
		len = strlen(path);
		myxt_static_convert_table_name(self, buffer, &path[len], PATH_MAX - len);
	}
	else
		xt_strcat(PATH_MAX, path, name);

	if (alterTable) {
		XTTableHPtr	tab;

		/* Find the table... */
Paul McCullagh's avatar
Paul McCullagh committed
1440
		pushsr_(tab, xt_heap_release, xt_use_table(self, (XTPathStrPtr) path, FALSE, TRUE));
Paul McCullagh's avatar
Paul McCullagh committed
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 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 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 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548

		/* Clone the foreign key definitions: */
		if (tab && tab->tab_dic.dic_table) {
			ct_curr_table->dt_fkeys.deleteAll(self);
			ct_curr_table->dt_fkeys.clone(self, &tab->tab_dic.dic_table->dt_fkeys);	
			for (u_int i=0; i<ct_curr_table->dt_fkeys.size(); i++)
				ct_curr_table->dt_fkeys.itemAt(i)->co_table = ct_curr_table;
		}

		freer_(); // xt_heap_release(tab)
	}
}

/*
 * old_name is given if the column name was changed.
 * NOTE that we built the table desciption from the current MySQL table
 * description. This means that all changes to columns and 
 * indexes have already been applied.
 *
 * Our job is to now add the foreign key changes.
 * This means we have to note the current column here. It is
 * possible to add a FOREIGN KEY contraint directly to a column!
 */
void XTCreateTable::addColumn(XTThreadPtr self, char *new_name, char *old_name)
{
	char new_col_name[XT_IDENTIFIER_NAME_SIZE];

	myxt_static_convert_identifier(self, ct_charset, new_name, new_col_name, XT_IDENTIFIER_NAME_SIZE);
	ct_curr_column = ct_curr_table->findColumn(new_col_name);
	if (old_name) {
		char old_col_name[XT_IDENTIFIER_NAME_SIZE];

		myxt_static_convert_identifier(self, ct_charset, old_name, old_col_name, XT_IDENTIFIER_NAME_SIZE);
		ct_curr_table->alterColumnName(self, old_col_name, new_col_name);
	}
}

void XTCreateTable::addConstraint(XTThreadPtr self, char *name, u_int type, bool lastColumn)
{
	/* We are only interested in foreign keys! */
	if (type == XT_DD_KEY_FOREIGN) {
		char buffer[50];

		if (!(ct_curr_constraint = new XTDDForeignKey()))
			xt_throw_errno(XT_CONTEXT, XT_ENOMEM);
		ct_curr_table->dt_fkeys.append(self, (XTDDForeignKey *) ct_curr_constraint);
		ct_curr_constraint->co_table = ct_curr_table;

		if (name && *name)
			ct_curr_constraint->co_name = myxt_convert_identifier(self, ct_charset, name);
		else {
			// Generate a default constraint name:
			ct_contraint_no++;
			sprintf(buffer, "FOREIGN_%d", ct_contraint_no);
			ct_curr_constraint->co_name = xt_dup_string(self, buffer);
		}

		if (lastColumn && ct_curr_column) {
			/* This constraint has one column, the current column. */
			XTDDColumnRef	*cref;
			char			*col_name = xt_dup_string(self, ct_curr_column->dc_name);

			if (!(cref = new XTDDColumnRef())) {
				xt_free(self, col_name);
				xt_throw_errno(XT_CONTEXT, XT_ENOMEM);
			}
			cref->cr_col_name = col_name;
			ct_curr_constraint->co_cols.append(self, cref);
		}
	}
	else
		/* Other constraints/indexes do not interest us: */
		ct_curr_constraint = NULL;
}

void XTCreateTable::dropConstraint(XTThreadPtr self, char *name, u_int type)
{
	if (type == XT_DD_KEY_FOREIGN && name) {
		u_int			i;
		XTDDForeignKey	*fkey;
		char			con_name[XT_IDENTIFIER_NAME_SIZE];

		myxt_static_convert_identifier(self, ct_charset, name, con_name, XT_IDENTIFIER_NAME_SIZE);
		for (i=0; i<ct_curr_table->dt_fkeys.size(); i++) {
			fkey = ct_curr_table->dt_fkeys.itemAt(i);
			if (fkey->co_name && myxt_strcasecmp(con_name, fkey->co_name) == 0) {
				ct_curr_table->dt_fkeys.remove(fkey);
				fkey->release(self);
			}
		}
	}
}

void XTCreateTable::addListedColumn(XTThreadPtr self, char *index_col_name)
{
	if (ct_curr_constraint && ct_curr_constraint->co_type == XT_DD_KEY_FOREIGN) {
		XTDDColumnRef	*cref;
		char			*name = myxt_convert_identifier(self, ct_charset, index_col_name);

		if (!(cref = new XTDDColumnRef())) {
			xt_free(self, name);
			xt_throw_errno(XT_CONTEXT, XT_ENOMEM);
		}
		cref->cr_col_name = name;
		ct_curr_constraint->co_cols.append(self, cref);
	}
}

1549
void XTCreateTable::setReferencedTable(XTThreadPtr self, char *ref_schema, char *ref_table)
Paul McCullagh's avatar
Paul McCullagh committed
1550 1551 1552 1553
{
	XTDDForeignKey	*fk = (XTDDForeignKey *) ct_curr_constraint;
	char			path[PATH_MAX];

1554 1555 1556 1557 1558
	if (ref_schema) {
		xt_strcpy(PATH_MAX,path, ".");
		xt_add_dir_char(PATH_MAX, path);
		xt_strcat(PATH_MAX, path, ref_schema);
		xt_add_dir_char(PATH_MAX, path);
Paul McCullagh's avatar
Paul McCullagh committed
1559
		xt_strcat(PATH_MAX, path, ref_table);
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
	} else {
		xt_strcpy(PATH_MAX, path, ct_tab_path->ps_path);
		xt_remove_last_name_of_path(path);
		if (ct_convert) {
			char	buffer[XT_IDENTIFIER_NAME_SIZE];
			size_t	len;

			myxt_static_convert_identifier(self, ct_charset, ref_table, buffer, XT_IDENTIFIER_NAME_SIZE);
			len = strlen(path);
			myxt_static_convert_table_name(self, buffer, &path[len], PATH_MAX - len);
		}
		else
			xt_strcat(PATH_MAX, path, ref_table);
	}
Paul McCullagh's avatar
Paul McCullagh committed
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599

	fk->fk_ref_tab_name = (XTPathStrPtr) xt_dup_string(self, path);
}

/* If the referenced column is NULL, this means 
 * duplicate the local column list!
 */
void XTCreateTable::addReferencedColumn(XTThreadPtr self, char *index_col_name)
{
	XTDDForeignKey	*fk = (XTDDForeignKey *) ct_curr_constraint;
	XTDDColumnRef	*cref;
	char			*name;

	if (index_col_name) {
		name = myxt_convert_identifier(self, ct_charset, index_col_name);
		if (!(cref = new XTDDColumnRef())) {
			xt_free(self, name);
			xt_throw_errno(XT_CONTEXT, XT_ENOMEM);
		}
		cref->cr_col_name = name;
		fk->fk_ref_cols.append(self, cref);
	}
	else
		fk->fk_ref_cols.clone(self, &fk->co_cols);
}

1600
void XTCreateTable::setActions(XTThreadPtr XT_UNUSED(self), int on_delete, int on_update)
Paul McCullagh's avatar
Paul McCullagh committed
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 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 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
{
	XTDDForeignKey	*fk = (XTDDForeignKey *) ct_curr_constraint;

	fk->fk_on_delete = on_delete;
	fk->fk_on_update = on_update;
}

/*
 * -----------------------------------------------------------------------
 * Dictionary methods
 */

void XTDDColumn::init(XTThreadPtr self, XTObject *obj) {
	XTDDColumn *col = (XTDDColumn *) obj;

	XTObject::init(self, obj);
	if (col->dc_name)
		dc_name = xt_dup_string(self, col->dc_name);
	if (col->dc_data_type)
		dc_data_type = xt_dup_string(self, col->dc_data_type);
	dc_null_ok = col->dc_null_ok;
	dc_auto_inc = col->dc_auto_inc;
}

void XTDDColumn::finalize(XTThreadPtr self)
{
	if (dc_name)
		xt_free(self, dc_name);
	if (dc_data_type)
		xt_free(self, dc_data_type);
}

void XTDDColumn::loadString(XTThreadPtr self, XTStringBufferPtr sb)
{
	xt_sb_concat(self, sb, "`");
	xt_sb_concat(self, sb, dc_name);
	xt_sb_concat(self, sb, "` ");
	if (dc_data_type) {
		xt_sb_concat(self, sb, dc_data_type);
		if (dc_null_ok)
			xt_sb_concat(self, sb, " NULL");
		else
			xt_sb_concat(self, sb, " NOT NULL");
		if (dc_auto_inc)
			xt_sb_concat(self, sb, " AUTO_INCREMENT");
	}
}

void  XTDDColumnRef::init(XTThreadPtr self, XTObject *obj)
{
	XTDDColumnRef *cr = (XTDDColumnRef *) obj;

	XTObject::init(self, obj);
	cr_col_name = xt_dup_string(self, cr->cr_col_name);
}

void XTDDColumnRef::finalize(XTThreadPtr self)
{
	XTObject::finalize(self);
	if (cr_col_name) {
		xt_free(self, cr_col_name);
		cr_col_name = NULL;
	}
}

void  XTDDConstraint::init(XTThreadPtr self, XTObject *obj)
{
	XTDDConstraint *co = (XTDDConstraint *) obj;

	XTObject::init(self, obj);
	co_type = co->co_type;
	if (co->co_name)
		co_name = xt_dup_string(self, co->co_name);
	if (co->co_ind_name)
		co_ind_name = xt_dup_string(self, co->co_ind_name);
	co_cols.clone(self, &co->co_cols);
}

void XTDDConstraint::loadString(XTThreadPtr self, XTStringBufferPtr sb)
{
	if (co_name) {
		xt_sb_concat(self, sb, "CONSTRAINT `");
		xt_sb_concat(self, sb, co_name);
		xt_sb_concat(self, sb, "` ");
	}
	switch (co_type) {
		case XT_DD_INDEX:
			xt_sb_concat(self, sb, "INDEX ");
			break;
		case XT_DD_INDEX_UNIQUE:
			xt_sb_concat(self, sb, "UNIQUE INDEX ");
			break;
		case XT_DD_KEY_PRIMARY:
			xt_sb_concat(self, sb, "PRIMARY KEY ");
			break;
		case XT_DD_KEY_FOREIGN:
			xt_sb_concat(self, sb, "FOREIGN KEY ");
			break;		
	}
	if (co_ind_name) {
		xt_sb_concat(self, sb, "`");
		xt_sb_concat(self, sb, co_ind_name);
		xt_sb_concat(self, sb, "` ");
	}
	xt_sb_concat(self, sb, "(`");
	xt_sb_concat(self, sb, co_cols.itemAt(0)->cr_col_name);
	for (u_int i=1; i<co_cols.size(); i++) {
		xt_sb_concat(self, sb, "`, `");
		xt_sb_concat(self, sb, co_cols.itemAt(i)->cr_col_name);
	}
	xt_sb_concat(self, sb, "`)");
}

void XTDDConstraint::alterColumnName(XTThreadPtr self, char *from_name, char *to_name)
{
	XTDDColumnRef *col;

	for (u_int i=0; i<co_cols.size(); i++) {
		col = co_cols.itemAt(i);
		if (myxt_strcasecmp(col->cr_col_name, from_name) == 0) {
			char *name = xt_dup_string(self, to_name);

			xt_free(self, col->cr_col_name);
			col->cr_col_name = name;
			break;
		}
	}
}

void XTDDConstraint::getColumnList(char *buffer, size_t size)
{
	if (co_table->dt_table) {
1733 1734
		xt_strcpy(size, buffer, "`");
		xt_strcat(size, buffer, co_table->dt_table->tab_name->ps_path);
Paul McCullagh's avatar
Paul McCullagh committed
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
		xt_strcat(size, buffer, "` (`");
	}
	else
		xt_strcpy(size, buffer, "(`");
	xt_strcat(size, buffer, co_cols.itemAt(0)->cr_col_name);
	for (u_int i=1; i<co_cols.size(); i++) {
		xt_strcat(size, buffer, "`, `");
		xt_strcat(size, buffer, co_cols.itemAt(i)->cr_col_name);
	}
	xt_strcat(size, buffer, "`)");
}

bool XTDDConstraint::sameColumns(XTDDConstraint *co)
{
	u_int i = 0;

	if (co_cols.size() != co->co_cols.size())
		return false;
	while (i<co_cols.size()) {
		if (myxt_strcasecmp(co_cols.itemAt(i)->cr_col_name, co->co_cols.itemAt(i)->cr_col_name) != 0)
			return false;
		i++;
	}
	return OK;
}

1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
bool XTDDConstraint::samePrefixColumns(XTDDConstraint *co)
{
	u_int i = 0;

	if (co_cols.size() > co->co_cols.size())
		return false;
	while (i<co_cols.size()) {
		if (myxt_strcasecmp(co_cols.itemAt(i)->cr_col_name, co->co_cols.itemAt(i)->cr_col_name) != 0)
			return false;
		i++;
	}
	return OK;
}

Paul McCullagh's avatar
Paul McCullagh committed
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
bool XTDDConstraint::attachColumns()
{
	XTDDColumn		*col;

	for (u_int i=0; i<co_cols.size(); i++) {
		if (!(col = co_table->findColumn(co_cols.itemAt(i)->cr_col_name)))
			return false;
		/* If this is a primary key, then the column becomes not-null! */
		if (co_type == XT_DD_KEY_PRIMARY)
			col->dc_null_ok = false;
	}
	return true;
}

void XTDDTableRef::finalize(XTThreadPtr self)
{
	XTDDForeignKey	*fk;

	if ((fk = tr_fkey)) {
		tr_fkey = NULL;
		fk->removeReference(self);
		xt_heap_release(self, fk->co_table->dt_table); /* We referenced the database table, not the foreign key */
	}
	XTObject::finalize(self);
}

bool XTDDTableRef::checkReference(xtWord1 *before_buf, XTThreadPtr thread)
{
	XTIndexPtr			loc_ind, ind;
	xtBool				no_null = TRUE;
	XTOpenTablePtr		ot;
	XTIdxSearchKeyRec	search_key;
	xtXactID			xn_id;
	XTXactWaitRec		xw;
1809
	bool				ok = false;
Paul McCullagh's avatar
Paul McCullagh committed
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828

	if (!(loc_ind = tr_fkey->getReferenceIndexPtr()))
		return false;

	if (!(ind = tr_fkey->getIndexPtr()))
		return false;

	search_key.sk_key_value.sv_flags = 0;
	search_key.sk_key_value.sv_rec_id = 0;
	search_key.sk_key_value.sv_row_id = 0;
	search_key.sk_key_value.sv_key = search_key.sk_key_buf;
	search_key.sk_key_value.sv_length = myxt_create_foreign_key_from_row(loc_ind, search_key.sk_key_buf, before_buf, ind, &no_null);
	search_key.sk_on_key = FALSE;

	if (!no_null)
		return true;

	/* Search for the key in the child (referencing) table: */
	if (!(ot = xt_db_open_table_using_tab(tr_fkey->co_table->dt_table, thread)))
1829
		return false;
Paul McCullagh's avatar
Paul McCullagh committed
1830 1831 1832

	retry:
	if (!xt_idx_search(ot, ind, &search_key))
1833
		goto done;
Paul McCullagh's avatar
Paul McCullagh committed
1834 1835 1836 1837 1838 1839
		
	while (ot->ot_curr_rec_id && search_key.sk_on_key) {
		switch (xt_tab_maybe_committed(ot, ot->ot_curr_rec_id, &xn_id, &ot->ot_curr_row_id, &ot->ot_curr_updated)) {
			case XT_MAYBE:				
				xw.xw_xn_id = xn_id;
				if (!xt_xn_wait_for_xact(thread, &xw, NULL))
1840
					goto done;
Paul McCullagh's avatar
Paul McCullagh committed
1841 1842
				goto retry;
			case XT_ERR:
1843
				goto done;
Paul McCullagh's avatar
Paul McCullagh committed
1844 1845 1846
			case TRUE:
				/* We found a matching child: */
				xt_register_ixterr(XT_REG_CONTEXT, XT_ERR_ROW_IS_REFERENCED, tr_fkey->co_name);
1847
				goto done;
Paul McCullagh's avatar
Paul McCullagh committed
1848 1849
			case FALSE:
				if (!xt_idx_next(ot, ind, &search_key))
1850
					goto done;
Paul McCullagh's avatar
Paul McCullagh committed
1851 1852 1853 1854 1855
				break;
		}
	}

	/* No matching children, all OK: */
1856
	ok = true;
Paul McCullagh's avatar
Paul McCullagh committed
1857

1858 1859 1860 1861 1862
	done:
	if (ot->ot_ind_rhandle) {
		xt_ind_release_handle(ot->ot_ind_rhandle, FALSE, thread);
		ot->ot_ind_rhandle = NULL;
	}
Paul McCullagh's avatar
Paul McCullagh committed
1863
	xt_db_return_table_to_pool_ns(ot);
1864
	return ok;
Paul McCullagh's avatar
Paul McCullagh committed
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 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 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
}

/*
 * A row has been deleted or updated (after_buf non-NULL), check if it is referenced by the foreign key table.
 * If it is referenced, then we need to follow the specified action.
 */
bool XTDDTableRef::modifyRow(XTOpenTablePtr XT_UNUSED(ref_ot), xtWord1 *before_buf, xtWord1 *after_buf, XTThreadPtr thread)
{
	XTIndexPtr			loc_ind, ind;
	xtBool				no_null = TRUE;
	XTOpenTablePtr		ot;
	XTIdxSearchKeyRec	search_key;
	xtXactID			xn_id;
	int					action = after_buf ? tr_fkey->fk_on_update : tr_fkey->fk_on_delete;
	u_int				after_key_len = 0;
	xtWord1				*after_key = NULL;
	XTInfoBufferRec		after_info;
	XTXactWaitRec		xw;

	after_info.ib_free = FALSE;

	if (!(loc_ind = tr_fkey->getReferenceIndexPtr()))
		return false;

	if (!(ind = tr_fkey->getIndexPtr()))
		return false;

	search_key.sk_key_value.sv_flags = 0;
	search_key.sk_key_value.sv_rec_id = 0;
	search_key.sk_key_value.sv_row_id = 0;
	search_key.sk_key_value.sv_key = search_key.sk_key_buf;
	search_key.sk_key_value.sv_length = myxt_create_foreign_key_from_row(loc_ind, search_key.sk_key_buf, before_buf, ind, &no_null);
	search_key.sk_on_key = FALSE;

	if (!no_null)
		return true;

	if (after_buf) {
		if (!(after_key = (xtWord1 *) xt_malloc_ns(XT_INDEX_MAX_KEY_SIZE)))
			return false;
		after_key_len = myxt_create_foreign_key_from_row(loc_ind, after_key, after_buf, ind, NULL);
		
		/* Check whether the key value has changed, if not, we have nothing
		 * to do here!
		 */
		if (myxt_compare_key(ind, 0, search_key.sk_key_value.sv_length,
			search_key.sk_key_value.sv_key, after_key) == 0)
			goto success;

	}

	/* Search for the key in the child (referencing) table: */
	if (!(ot = xt_db_open_table_using_tab(tr_fkey->co_table->dt_table, thread)))
		goto failed;

	retry:
	if (!xt_idx_search(ot, ind, &search_key))
		goto failed_2;
		
	while (ot->ot_curr_rec_id && search_key.sk_on_key) {
		switch (xt_tab_maybe_committed(ot, ot->ot_curr_rec_id, &xn_id, &ot->ot_curr_row_id, &ot->ot_curr_updated)) {
			case XT_MAYBE:
				xw.xw_xn_id = xn_id;
				if (!xt_xn_wait_for_xact(thread, &xw, NULL))
					goto failed_2;
				goto retry;
			case XT_ERR:
				goto failed_2;
			case TRUE:
				/* We found a matching child: */
				switch (action) {
					case XT_KEY_ACTION_CASCADE:
						if (after_buf) {
							/* Do a cascaded update: */
							if (!xt_tab_load_record(ot, ot->ot_curr_rec_id, &after_info))
								goto failed_2;

							if (!myxt_create_row_from_key(ot, ind, after_key, after_key_len, after_info.ib_db.db_data))
								goto failed_2;

							if (!xt_tab_update_record(ot, NULL, after_info.ib_db.db_data)) {
								// Change to duplicate foreign key
								if (ot->ot_thread->t_exception.e_xt_err == XT_ERR_DUPLICATE_KEY)
									xt_register_ixterr(XT_REG_CONTEXT, XT_ERR_DUPLICATE_FKEY, tr_fkey->co_name);
								goto failed_2;
							}
						}
						else {
							/* Do a cascaded delete: */
							if (!xt_tab_delete_record(ot, NULL))
								goto failed_2;
						}
						break;
					case XT_KEY_ACTION_SET_NULL:
						if (!xt_tab_load_record(ot, ot->ot_curr_rec_id, &after_info))
							goto failed_2;

						myxt_set_null_row_from_key(ot, ind, after_info.ib_db.db_data);

						if (!xt_tab_update_record(ot, NULL, after_info.ib_db.db_data))
							goto failed_2;
						break;
					case XT_KEY_ACTION_SET_DEFAULT:

						if (!xt_tab_load_record(ot, ot->ot_curr_rec_id, &after_info))
							goto failed_2;

						myxt_set_default_row_from_key(ot, ind, after_info.ib_db.db_data);

						if (!xt_tab_update_record(ot, NULL, after_info.ib_db.db_data))
							goto failed_2;

						break;
					case XT_KEY_ACTION_NO_ACTION:
#ifdef XT_IMPLEMENT_NO_ACTION
						XTRestrictItemRec	r;
						
						r.ri_tab_id = ref_ot->ot_table->tab_id;
						r.ri_rec_id = ref_ot->ot_curr_rec_id;
						if (!xt_bl_append(NULL, &thread->st_restrict_list, (void *) &r))
							goto failed_2;
						break;
#endif
					default:
						xt_register_ixterr(XT_REG_CONTEXT, XT_ERR_ROW_IS_REFERENCED, tr_fkey->co_name);
						goto failed_2;
				}
				/* Fall throught to next: */
			case FALSE:
				if (!xt_idx_next(ot, ind, &search_key))
					goto failed_2;
				break;
		}
	}

	/* No matching children, all OK: */
2001 2002 2003 2004
	if (ot->ot_ind_rhandle) {
		xt_ind_release_handle(ot->ot_ind_rhandle, FALSE, thread);
		ot->ot_ind_rhandle = NULL;
	}
Paul McCullagh's avatar
Paul McCullagh committed
2005 2006 2007 2008 2009 2010 2011 2012 2013
	xt_db_return_table_to_pool_ns(ot);

	success:
	xt_ib_free(NULL, &after_info);
	if (after_key)
		xt_free_ns(after_key);
	return true;

	failed_2:
2014 2015 2016 2017
	if (ot->ot_ind_rhandle) {
		xt_ind_release_handle(ot->ot_ind_rhandle, FALSE, thread);
		ot->ot_ind_rhandle = NULL;
	}
Paul McCullagh's avatar
Paul McCullagh committed
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
	xt_db_return_table_to_pool_ns(ot);

	failed:
	xt_ib_free(NULL, &after_info);
	if (after_key)
		xt_free_ns(after_key);
	return false;
}

void XTDDTableRef::deleteAllRows(XTThreadPtr self)
{
	XTOpenTablePtr	ot;
Paul McCullagh's avatar
Paul McCullagh committed
2030 2031
	xtBool			eof;
	xtWord1			*buffer;
Paul McCullagh's avatar
Paul McCullagh committed
2032 2033

	if (!tr_fkey->getReferenceIndexPtr())
Paul McCullagh's avatar
Paul McCullagh committed
2034
		xt_throw(self);
Paul McCullagh's avatar
Paul McCullagh committed
2035 2036

	if (!tr_fkey->getIndexPtr())
Paul McCullagh's avatar
Paul McCullagh committed
2037
		xt_throw(self);
Paul McCullagh's avatar
Paul McCullagh committed
2038 2039

	if (!(ot = xt_db_open_table_using_tab(tr_fkey->co_table->dt_table, self)))
Paul McCullagh's avatar
Paul McCullagh committed
2040
		xt_throw(self);
Paul McCullagh's avatar
Paul McCullagh committed
2041

Paul McCullagh's avatar
Paul McCullagh committed
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
	/* Check if there are any rows in the referencing table: */
	if (!xt_tab_seq_init(ot))
		goto failed;

	if (!(buffer = (xtWord1 *) xt_malloc(self, ot->ot_table->tab_dic.dic_mysql_buf_size)))
		goto failed_1;

	if (!xt_tab_seq_next(ot, buffer, &eof))
		goto failed_2;

	xt_free(self, buffer);

	xt_tab_seq_exit(ot);
Paul McCullagh's avatar
Paul McCullagh committed
2055 2056 2057

	xt_db_return_table_to_pool_ns(ot);

Paul McCullagh's avatar
Paul McCullagh committed
2058
	if (!eof)
Paul McCullagh's avatar
Paul McCullagh committed
2059
		xt_throw_ixterr(XT_CONTEXT, XT_ERR_ROW_IS_REFERENCED, tr_fkey->co_name);
Paul McCullagh's avatar
Paul McCullagh committed
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
	return;

	failed_2:
	xt_free(self, buffer);

	failed_1:
	xt_tab_seq_exit(ot);

	failed:
	xt_db_return_table_to_pool_ns(ot);
	xt_throw(self);
Paul McCullagh's avatar
Paul McCullagh committed
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
}

void  XTDDIndex::init(XTThreadPtr self, XTObject *obj)
{
	XTDDConstraint::init(self, obj);
}

XTIndexPtr XTDDIndex::getIndexPtr()
{
	if (in_index >= co_table->dt_table->tab_dic.dic_key_count) {
		XTDDIndex		*in;

		if (!(in = co_table->findIndex(this)))
			return NULL;
		in_index = in->in_index;
	}
	return co_table->dt_table->tab_dic.dic_keys[in_index];
}

void XTDDForeignKey::init(XTThreadPtr self, XTObject *obj)
{
	XTDDForeignKey *fk = (XTDDForeignKey *) obj;

	XTDDIndex::init(self, obj);
	if (fk->fk_ref_tab_name)
		fk_ref_tab_name = (XTPathStrPtr) xt_dup_string(self, fk->fk_ref_tab_name->ps_path);
	fk_ref_cols.clone(self, &fk->fk_ref_cols);
	fk_on_delete = fk->fk_on_delete;
	fk_on_update = fk->fk_on_update;
}

void XTDDForeignKey::finalize(XTThreadPtr self)
{
	XTDDTable *ref_tab;

	if (fk_ref_tab_name) {
		xt_free(self, fk_ref_tab_name);
		fk_ref_tab_name = NULL;
	}

	if ((ref_tab = fk_ref_table)) {
		fk_ref_table = NULL;
		ref_tab->removeReference(self, this);
		xt_heap_release(self, ref_tab->dt_table); /* We referenced the table, not the index! */
	}

	fk_ref_index = UINT_MAX;

	fk_ref_cols.deleteAll(self);
	XTDDConstraint::finalize(self);
}

void XTDDForeignKey::loadString(XTThreadPtr self, XTStringBufferPtr sb)
{
2125 2126
	char schema_name[XT_IDENTIFIER_NAME_SIZE];
	
Paul McCullagh's avatar
Paul McCullagh committed
2127 2128
	XTDDConstraint::loadString(self, sb);
	xt_sb_concat(self, sb, " REFERENCES `");
2129 2130 2131
	xt_2nd_last_name_of_path(XT_IDENTIFIER_NAME_SIZE, schema_name, fk_ref_tab_name->ps_path);
	xt_sb_concat(self, sb, schema_name);
	xt_sb_concat(self, sb, "`.`");
Paul McCullagh's avatar
Paul McCullagh committed
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
	xt_sb_concat(self, sb, xt_last_name_of_path(fk_ref_tab_name->ps_path));
	xt_sb_concat(self, sb, "` ");

	xt_sb_concat(self, sb, "(`");
	xt_sb_concat(self, sb, fk_ref_cols.itemAt(0)->cr_col_name);
	for (u_int i=1; i<fk_ref_cols.size(); i++) {
		xt_sb_concat(self, sb, "`, `");
		xt_sb_concat(self, sb, fk_ref_cols.itemAt(i)->cr_col_name);
	}
	xt_sb_concat(self, sb, "`)");
	
Paul McCullagh's avatar
Paul McCullagh committed
2143
	if (fk_on_delete != XT_KEY_ACTION_RESTRICT) {
Paul McCullagh's avatar
Paul McCullagh committed
2144 2145 2146 2147 2148 2149 2150 2151
		xt_sb_concat(self, sb, " ON DELETE ");
		switch (fk_on_delete) {
			case XT_KEY_ACTION_CASCADE:		xt_sb_concat(self, sb, "CASCADE"); break;
			case XT_KEY_ACTION_SET_NULL:	xt_sb_concat(self, sb, "SET NULL"); break;
			case XT_KEY_ACTION_SET_DEFAULT:	xt_sb_concat(self, sb, "SET DEFAULT"); break;
			case XT_KEY_ACTION_NO_ACTION:	xt_sb_concat(self, sb, "NO ACTION"); break;
		}
	}
Paul McCullagh's avatar
Paul McCullagh committed
2152
	if (fk_on_update != XT_KEY_ACTION_RESTRICT) {
Paul McCullagh's avatar
Paul McCullagh committed
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
		xt_sb_concat(self, sb, " ON UPDATE ");
		switch (fk_on_update) {
			case XT_KEY_ACTION_RESTRICT:	xt_sb_concat(self, sb, "RESTRICT"); break;
			case XT_KEY_ACTION_CASCADE:		xt_sb_concat(self, sb, "CASCADE"); break;
			case XT_KEY_ACTION_SET_NULL:	xt_sb_concat(self, sb, "SET NULL"); break;
			case XT_KEY_ACTION_SET_DEFAULT:	xt_sb_concat(self, sb, "SET DEFAULT"); break;
			case XT_KEY_ACTION_NO_ACTION:	xt_sb_concat(self, sb, "NO ACTION"); break;
		}
	}
}

void XTDDForeignKey::getReferenceList(char *buffer, size_t size)
{
	buffer[0] = '`';
	xt_strcpy(size, buffer + 1, xt_last_name_of_path(fk_ref_tab_name->ps_path));
	xt_strcat(size, buffer, "` (");
	xt_strcat(size, buffer, fk_ref_cols.itemAt(0)->cr_col_name);
	for (u_int i=1; i<fk_ref_cols.size(); i++) {
		xt_strcat(size, buffer, ", ");
		xt_strcat(size, buffer, fk_ref_cols.itemAt(i)->cr_col_name);
	}
	xt_strcat(size, buffer, ")");
}

struct XTIndex *XTDDForeignKey::getReferenceIndexPtr()
{
	if (!fk_ref_table) {
		xt_register_taberr(XT_REG_CONTEXT, XT_ERR_REF_TABLE_NOT_FOUND, fk_ref_tab_name);
		return NULL;
	}
	if (fk_ref_index >= fk_ref_table->dt_table->tab_dic.dic_key_count) {
		XTDDIndex *in;

		if (!(in = fk_ref_table->findReferenceIndex(this)))
			return NULL;
		if (!checkReferencedTypes(fk_ref_table))
			return NULL;
		fk_ref_index = in->in_index;
	}

	return fk_ref_table->dt_table->tab_dic.dic_keys[fk_ref_index];
}

bool XTDDForeignKey::sameReferenceColumns(XTDDConstraint *co)
{
	u_int i = 0;

	if (fk_ref_cols.size() != co->co_cols.size())
		return false;
	while (i<fk_ref_cols.size()) {
		if (myxt_strcasecmp(fk_ref_cols.itemAt(i)->cr_col_name, co->co_cols.itemAt(i)->cr_col_name) != 0)
			return false;
		i++;
	}
	return OK;
}

2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
bool XTDDForeignKey::samePrefixReferenceColumns(XTDDConstraint *co)
{
	u_int i = 0;

	if (fk_ref_cols.size() > co->co_cols.size())
		return false;
	while (i<fk_ref_cols.size()) {
		if (myxt_strcasecmp(fk_ref_cols.itemAt(i)->cr_col_name, co->co_cols.itemAt(i)->cr_col_name) != 0)
			return false;
		i++;
	}
	return OK;
}

Paul McCullagh's avatar
Paul McCullagh committed
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
bool XTDDForeignKey::checkReferencedTypes(XTDDTable *dt)
{
	XTDDColumn *col, *ref_col;
	XTDDEnumerableColumn *enum_col, *enum_ref_col;

	if (dt->dt_table->tab_dic.dic_tab_flags & XT_TAB_FLAGS_TEMP_TAB) {
		xt_register_xterr(XT_REG_CONTEXT, XT_ERR_FK_REF_TEMP_TABLE);
		return false;
	}

	for (u_int i=0; i<co_cols.size() && i<fk_ref_cols.size(); i++) {
		col = co_table->findColumn(co_cols.itemAt(i)->cr_col_name);
		ref_col = dt->findColumn(fk_ref_cols.itemAt(i)->cr_col_name);
		if (!col || !ref_col)
			continue;

		enum_col = col->castToEnumerable();
		enum_ref_col = ref_col->castToEnumerable();

		if (!enum_col && !enum_ref_col && (strcmp(col->dc_data_type, ref_col->dc_data_type) == 0))
			continue;

		/* Allow match varchar(30) == varchar(40): */
		if (strncmp(col->dc_data_type, "varchar", 7) == 0 && strncmp(ref_col->dc_data_type, "varchar", 7) == 0) {
			char *t1, *t2;
			
			t1 = col->dc_data_type + 7;
			while (*t1 && (isdigit(*t1) || *t1 == '(' || *t1 == ')')) t1++;
			t2 = col->dc_data_type + 7;
			while (*t2 && (isdigit(*t2) || *t2 == '(' || *t2 == ')')) t2++;
			
			if (strcmp(t1, t2) == 0)
				continue;
		}

		/*
		 * MySQL stores ENUMs an integer indexes for string values. That's why
		 * it is ok to have refrences between columns that are different ENUMs as long
		 * as they contain equal number of members, so that for example a cascase update
		 * will not cause an invaid value to be stored in the child table. 
		 *
		 * The above is also true for SETs.
		 *
		 */

		if (enum_col && enum_ref_col && 
			(enum_col->enum_size == enum_ref_col->enum_size) && 
			(enum_col->is_enum == enum_ref_col->is_enum))
			continue;

		xt_register_tabcolerr(XT_REG_CONTEXT, XT_ERR_REF_TYPE_WRONG, fk_ref_tab_name, ref_col->dc_name);
		return false;
	}
	return true;
}

void XTDDForeignKey::removeReference(XTThreadPtr self)
{
	XTDDTable *ref_tab;

Paul McCullagh's avatar
Paul McCullagh committed
2284 2285
	xt_recurrwlock_xlock(self, &co_table->dt_ref_lock);
	pushr_(xt_recurrwlock_unxlock, &co_table->dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2286 2287 2288 2289 2290 2291 2292 2293 2294

	if ((ref_tab = fk_ref_table)) {			
		fk_ref_table = NULL;
		ref_tab->removeReference(self, this);
		xt_heap_release(self, ref_tab->dt_table); /* We referenced the table, not the index! */
	}

	fk_ref_index = UINT_MAX;

Paul McCullagh's avatar
Paul McCullagh committed
2295
	freer_(); // xt_recurrwlock_unxlock(&co_table->dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
}

/*
 * A row was inserted, check that a key exists in the referenced
 * table.
 */
bool XTDDForeignKey::insertRow(xtWord1 *before_buf, xtWord1 *rec_buf, XTThreadPtr thread)
{
	XTIndexPtr			loc_ind, ind;
	xtBool				no_null = TRUE;
	XTOpenTablePtr		ot;
	XTIdxSearchKeyRec	search_key;
	xtXactID			xn_id;
	XTXactWaitRec		xw;

	/* This lock ensures that the foreign key references are not
	 * changed.
	 */
Paul McCullagh's avatar
Paul McCullagh committed
2314
	xt_recurrwlock_slock_ns(&co_table->dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375

	if (!(loc_ind = getIndexPtr()))
		goto failed;

	if (!(ind = getReferenceIndexPtr()))
		goto failed;

	search_key.sk_key_value.sv_flags = 0;
	search_key.sk_key_value.sv_rec_id = 0;
	search_key.sk_key_value.sv_row_id = 0;
	search_key.sk_key_value.sv_key = search_key.sk_key_buf;
	search_key.sk_key_value.sv_length = myxt_create_foreign_key_from_row(loc_ind, search_key.sk_key_buf, rec_buf, ind, &no_null);
	search_key.sk_on_key = FALSE;

	if (!no_null)
		goto success;

	if (before_buf) {
		u_int	before_key_len;
		xtWord1	before_key[XT_INDEX_MAX_KEY_SIZE];

		/* If there is a before buffer, this insert was an update, so check
		 * if the key value has changed. If not, we need not do anything.
		 */
		before_key_len = myxt_create_foreign_key_from_row(loc_ind, before_key, before_buf, ind, NULL);
		
		/* Check whether the key value has changed, if not, we have nothing
		 * to do here!
		 */
		if (search_key.sk_key_value.sv_length == before_key_len &&
			memcmp(search_key.sk_key_buf, before_key, before_key_len) == 0)
			goto success;
	}

	/* Search for the key in the parent (referenced) table: */
	if (!(ot = xt_db_open_table_using_tab(fk_ref_table->dt_table, thread)))
		goto failed;

	retry:
	if (!xt_idx_search(ot, ind, &search_key))
		goto failed_2;
		
	while (ot->ot_curr_rec_id) {
		if (!search_key.sk_on_key)
			break;

		switch (xt_tab_maybe_committed(ot, ot->ot_curr_rec_id, &xn_id, &ot->ot_curr_row_id, &ot->ot_curr_updated)) {
			case XT_MAYBE:
				/* We should not get a deadlock here because the thread
				 * that we are waiting for, should not doing
				 * data definition (i.e. should not be trying to
				 * get an exclusive lock on dt_ref_lock.
				 */
				xw.xw_xn_id = xn_id;
				if (!xt_xn_wait_for_xact(thread, &xw, NULL))
					goto failed_2;
				goto retry;			
			case XT_ERR:
				goto failed_2;
			case TRUE:
				/* We found a matching parent: */
2376 2377 2378 2379
				if (ot->ot_ind_rhandle) {
					xt_ind_release_handle(ot->ot_ind_rhandle, FALSE, thread);
					ot->ot_ind_rhandle = NULL;
				}
Paul McCullagh's avatar
Paul McCullagh committed
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391
				xt_db_return_table_to_pool_ns(ot);
				goto success;
			case FALSE:
				if (!xt_idx_next(ot, ind, &search_key))
					goto failed_2;
				break;
		}
	}

	xt_register_ixterr(XT_REG_CONTEXT, XT_ERR_NO_REFERENCED_ROW, co_name);

	failed_2:
2392 2393 2394 2395
	if (ot->ot_ind_rhandle) {
		xt_ind_release_handle(ot->ot_ind_rhandle, FALSE, thread);
		ot->ot_ind_rhandle = NULL;
	}
Paul McCullagh's avatar
Paul McCullagh committed
2396 2397 2398
	xt_db_return_table_to_pool_ns(ot);

	failed:
Paul McCullagh's avatar
Paul McCullagh committed
2399
	xt_recurrwlock_unslock_ns(&co_table->dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2400 2401 2402
	return false;

	success:
Paul McCullagh's avatar
Paul McCullagh committed
2403
	xt_recurrwlock_unslock_ns(&co_table->dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
	return true;
}

/*
 * Convert XT_KEY_ACTION_* constants to strings
 */
const char *XTDDForeignKey::actionTypeToString(int action)
{
	switch (action)
	{
	case XT_KEY_ACTION_RESTRICT:
		return "RESTRICT";
	case XT_KEY_ACTION_CASCADE:
		return "CASCADE";
	case XT_KEY_ACTION_SET_NULL:
		return "SET NULL";
	case XT_KEY_ACTION_SET_DEFAULT:
		return "";
	case XT_KEY_ACTION_NO_ACTION:
		return "NO ACTION";
	}

	return "";
}

void XTDDTable::init(XTThreadPtr self)
{
Paul McCullagh's avatar
Paul McCullagh committed
2431
	xt_recurrwlock_init_with_autoname(self, &dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
	dt_trefs = NULL;
}

void XTDDTable::init(XTThreadPtr self, XTObject *obj)
{
	XTDDTable *tab = (XTDDTable *) obj;
	u_int		i;

	init(self);
	XTObject::init(self, obj);
	dt_cols.clone(self, &tab->dt_cols);	
	dt_indexes.clone(self, &tab->dt_indexes);	
	dt_fkeys.clone(self, &tab->dt_fkeys);	

	for (i=0; i<dt_indexes.size(); i++)
		dt_indexes.itemAt(i)->co_table = this;
	for (i=0; i<dt_fkeys.size(); i++)
		dt_fkeys.itemAt(i)->co_table = this;
}

void XTDDTable::finalize(XTThreadPtr self)
{
	XTDDTableRef *ptr;

	removeReferences(self);

	dt_cols.deleteAll(self);
	dt_indexes.deleteAll(self);
	dt_fkeys.deleteAll(self);

	while (dt_trefs) {
		ptr = dt_trefs;
		dt_trefs = dt_trefs->tr_next;
		ptr->release(self);
	}

Paul McCullagh's avatar
Paul McCullagh committed
2468
	xt_recurrwlock_free(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
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 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
}

XTDDColumn *XTDDTable::findColumn(char *name)
{
	XTDDColumn *col;

	for (u_int i=0; i<dt_cols.size(); i++) {
		col = dt_cols.itemAt(i);
		if (myxt_strcasecmp(name, col->dc_name) == 0)
			return col;
	}
	return NULL;
}

void XTDDTable::loadString(XTThreadPtr self, XTStringBufferPtr sb)
{
	u_int i;

	/* I do not specify a table name because that is known */
	xt_sb_concat(self, sb, "CREATE TABLE (\n  ");

	/* We only need to save the foreign key definitions!!
	for (i=0; i<dt_cols.size(); i++) {
		if (i != 0)
			xt_sb_concat(self, sb, ",\n  ");
		dt_cols.itemAt(i)->loadString(self, sb);
	}

	for (i=0; i<dt_indexes.size(); i++) {
		xt_sb_concat(self, sb, ",\n  ");
		dt_indexes.itemAt(i)->loadString(self, sb);
	}
	*/

	for (i=0; i<dt_fkeys.size(); i++) {
		if (i != 0)
			xt_sb_concat(self, sb, ",\n  ");
		dt_fkeys.itemAt(i)->loadString(self, sb);
	}

	xt_sb_concat(self, sb, "\n)\n");
}

void XTDDTable::loadForeignKeyString(XTThreadPtr self, XTStringBufferPtr sb)
{
	for (u_int i=0; i<dt_fkeys.size(); i++) {
		xt_sb_concat(self, sb, ",\n  ");
		dt_fkeys.itemAt(i)->loadString(self, sb);
	}
}

/* Change all references to the given column name to new name. */
void XTDDTable::alterColumnName(XTThreadPtr self, char *from_name, char *to_name)
{
	u_int i;

	/* We only alter references in the foreign keys (we copied the
	 * other changes from MySQL).
	 */
	for (i=0; i<dt_fkeys.size(); i++)
		dt_fkeys.itemAt(i)->alterColumnName(self, from_name, to_name);
}

void XTDDTable::attachReference(XTThreadPtr self, XTDDForeignKey *fk)
{
	XTDDTableRef	*tr;

	/* Remove the reference to this FK if one exists: */
	removeReference(self, fk);

	if (!fk->checkReferencedTypes(this)) {
		if (!self->st_ignore_fkeys)
			throw_();
	}

Paul McCullagh's avatar
Paul McCullagh committed
2544 2545
	xt_recurrwlock_xlock(self, &dt_ref_lock);
	pushr_(xt_recurrwlock_unxlock, &dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559

	if (!(tr = new XTDDTableRef()))
		xt_throw_errno(XT_CONTEXT, XT_ENOMEM);
	tr->tr_fkey = fk;
	tr->tr_next = dt_trefs;
	dt_trefs = tr;

	/* Reference the database table of the foreign key, not the FK itself.
	 * Just referencing the key will not guarantee that the
	 * table remains valid because the FK does not reference the
	 * table.
	 */
	xt_heap_reference(self, fk->co_table->dt_table);

Paul McCullagh's avatar
Paul McCullagh committed
2560
	freer_(); // xt_recurrwlock_unxlock(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2561 2562 2563 2564 2565 2566 2567 2568 2569
}

/*
 * Remove the reference to the given foreign key.
 */
void XTDDTable::removeReference(XTThreadPtr self, XTDDForeignKey *fk)
{
	XTDDTableRef	*tr, *prev_tr = NULL;

Paul McCullagh's avatar
Paul McCullagh committed
2570 2571
	xt_recurrwlock_xlock(self, &dt_ref_lock);
	pushr_(xt_recurrwlock_unxlock, &dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584

	tr = dt_trefs;
	while (tr) {
		if (tr->tr_fkey == fk) {
			if (prev_tr)
				prev_tr->tr_next = tr->tr_next;
			else
				dt_trefs = tr->tr_next;
			break;
		}
		prev_tr = tr;
		tr = tr->tr_next;
	}
Paul McCullagh's avatar
Paul McCullagh committed
2585
	freer_(); // xt_recurrwlock_unxlock(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
	if (tr)
		tr->release(self);
}

void XTDDTable::checkForeignKeyReference(XTThreadPtr self, XTDDForeignKey *fk)
{
	XTDDColumnRef	*cr;

	for (u_int i=0; i<fk->fk_ref_cols.size(); i++) {
		cr = fk->fk_ref_cols.itemAt(i);
		if (!findColumn(cr->cr_col_name))
			xt_throw_tabcolerr(XT_CONTEXT, XT_ERR_COLUMN_NOT_FOUND, fk->fk_ref_tab_name, cr->cr_col_name);
	}
}

void XTDDTable::attachReference(XTThreadPtr self, XTDDTable *dt)
{
	XTDDForeignKey	*fk;

	for (u_int i=0; i<dt_fkeys.size(); i++) {
		fk = dt_fkeys.itemAt(i);
		if (xt_tab_compare_names(fk->fk_ref_tab_name->ps_path, dt->dt_table->tab_name->ps_path) == 0) {
			fk->removeReference(self);

			dt->attachReference(self, fk);

Paul McCullagh's avatar
Paul McCullagh committed
2612 2613
			xt_recurrwlock_xlock(self, &dt_ref_lock);
			pushr_(xt_recurrwlock_unxlock, &dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2614 2615 2616 2617 2618 2619 2620 2621 2622
			/* Referenced the table, not the index!
			 * We do this because we know that if the table is referenced, the
			 * index will remain valid!
			 * This is because the table references the index, and only
			 * releases it when the table is released. The index does not
			 * reference the table though!
			 */
			xt_heap_reference(self, dt->dt_table);
			fk->fk_ref_table = dt;
Paul McCullagh's avatar
Paul McCullagh committed
2623
			freer_(); // xt_recurrwlock_unxlock(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
		}
	}
}

/*
 * This function assumes the database table list is locked!
 */
void XTDDTable::attachReferences(XTThreadPtr self, XTDatabaseHPtr db)
{
	XTDDForeignKey	*fk;
	XTTableHPtr		tab;
	XTDDTable		*dt;
	XTHashEnumRec	tables;

	/* Search for table referenced by this table. */
	for (u_int i=0; i<dt_fkeys.size(); i++) {
		fk = dt_fkeys.itemAt(i);
		fk->removeReference(self);

		// if self-reference
		if (xt_tab_compare_names(fk->fk_ref_tab_name->ps_path, this->dt_table->tab_name->ps_path) == 0)
			fk->fk_ref_table = this;
		else {
			/* get pointer to the referenced table, load it if needed
			 * cyclic references are being handled, absent table is ignored
			 */
Paul McCullagh's avatar
Paul McCullagh committed
2650
			tab = xt_use_table_no_lock(self, db, fk->fk_ref_tab_name, /*TRUE*/FALSE, /*FALSE*/TRUE, NULL);
Paul McCullagh's avatar
Paul McCullagh committed
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

			if (tab) {
				pushr_(xt_heap_release, tab);
				if ((dt = tab->tab_dic.dic_table)) {
					// Add a reverse reference:
					dt->attachReference(self, fk);
					xt_heap_reference(self, dt->dt_table); /* Referenced the table, not the index! */
					fk->fk_ref_table = dt;
				}
				freer_(); // xt_heap_release(tab)
			}
			else if (!self->st_ignore_fkeys) {
				xt_throw_taberr(XT_CONTEXT, XT_ERR_REF_TABLE_NOT_FOUND, fk->fk_ref_tab_name);
			}
		}
	}

	/* Search for tables that reference this table. */
	xt_ht_enum(self, dt_table->tab_db->db_tables, &tables);
	while ((tab = (XTTableHPtr) xt_ht_next(self, &tables))) {
		if (tab == this->dt_table) /* no need to re-reference itself, also this fails with "native" pthreads */
			continue;
		xt_heap_reference(self, tab);
		pushr_(xt_heap_release, tab);
		if ((dt = tab->tab_dic.dic_table))
			dt->attachReference(self, this);
		freer_(); // xt_heap_release(tab)
	}
}

void XTDDTable::removeReferences(XTThreadPtr self)
{
	XTDDForeignKey	*fk;
	XTDDTableRef	*tr;
	XTDDTable		*tab;

Paul McCullagh's avatar
Paul McCullagh committed
2687 2688
	xt_recurrwlock_xlock(self, &dt_ref_lock);
	pushr_(xt_recurrwlock_unxlock, &dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2689 2690 2691 2692 2693 2694 2695 2696 2697 2698

	for (u_int i=0; i<dt_fkeys.size(); i++) {
		fk = dt_fkeys.itemAt(i);
		if ((tab = fk->fk_ref_table)) {			
			fk->fk_ref_table = NULL;
			fk->fk_ref_index = UINT_MAX;
			if (tab != this) {
				/* To avoid deadlock we do not hold more than
				 * one lock at a time!
				 */
Paul McCullagh's avatar
Paul McCullagh committed
2699
				freer_(); // xt_recurrwlock_unxlock(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2700 2701 2702 2703
	
				tab->removeReference(self, fk);
				xt_heap_release(self, tab->dt_table); /* We referenced the table, not the index! */
	
Paul McCullagh's avatar
Paul McCullagh committed
2704 2705
				xt_recurrwlock_xlock(self, &dt_ref_lock);
				pushr_(xt_recurrwlock_unxlock, &dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2706 2707 2708 2709 2710 2711 2712
			}
		}
	}

	while (dt_trefs) {
		tr = dt_trefs;
		dt_trefs = tr->tr_next;
Paul McCullagh's avatar
Paul McCullagh committed
2713
		freer_(); // xt_recurrwlock_unxlock(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2714
		tr->release(self);
Paul McCullagh's avatar
Paul McCullagh committed
2715 2716
		xt_recurrwlock_xlock(self, &dt_ref_lock);
		pushr_(xt_recurrwlock_unxlock, &dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2717 2718
	}

Paul McCullagh's avatar
Paul McCullagh committed
2719
	freer_(); // xt_recurrwlock_unxlock(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
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 2747 2748 2749 2750
}

void XTDDTable::checkForeignKeys(XTThreadPtr self, bool temp_table)
{
	XTDDForeignKey	*fk;

	if (temp_table && dt_fkeys.size()) {
		/* Temporary tables cannot have foreign keys: */
		xt_throw_xterr(XT_CONTEXT, XT_ERR_FK_ON_TEMP_TABLE);
		
	}

	/* Search for table referenced by this table. */
	for (u_int i=0; i<dt_fkeys.size(); i++) {
		fk = dt_fkeys.itemAt(i);

		if (fk->fk_on_delete == XT_KEY_ACTION_SET_NULL || fk->fk_on_update == XT_KEY_ACTION_SET_NULL) {
			/* Check that all the columns can be set to NULL! */
			XTDDColumn *col;

			for (u_int j=0; j<fk->co_cols.size(); j++) {
				if ((col = findColumn(fk->co_cols.itemAt(j)->cr_col_name))) {
					if (!col->dc_null_ok)
						xt_throw_tabcolerr(XT_CONTEXT, XT_ERR_COLUMN_IS_NOT_NULL, fk->fk_ref_tab_name, col->dc_name);
				}
			}
		}

		// TODO: dont close table immediately so it can be possibly reused in this loop
		XTTable *ref_tab;

Paul McCullagh's avatar
Paul McCullagh committed
2751
		pushsr_(ref_tab, xt_heap_release, xt_use_table(self, fk->fk_ref_tab_name, FALSE, TRUE));
Paul McCullagh's avatar
Paul McCullagh committed
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766
		if (ref_tab && !fk->checkReferencedTypes(ref_tab->tab_dic.dic_table))
			throw_();
		freer_();

		/* Currently I allow foreign keys to be created on tables that do not yet exist!
		pushsr_(tab, xt_heap_release, xt_use_table(self, fk->fk_ref_tab_name, FALSE FALSE));
		if ((dt = tab->tab_dic.dic_table))
			dt->checkForeignKeyReference(self, fk);
		freer_(); // xt_heap_release(tab)
		*/
	}
}

XTDDIndex *XTDDTable::findIndex(XTDDConstraint *co)
{
2767 2768 2769
	XTDDIndex *ind = NULL;
	XTDDIndex *cur_ind;
	u_int index_size = UINT_MAX;
Paul McCullagh's avatar
Paul McCullagh committed
2770 2771

	for (u_int i=0; i<dt_indexes.size(); i++) {
2772 2773 2774 2775 2776 2777
		cur_ind = dt_indexes.itemAt(i);
		u_int sz = cur_ind->getIndexPtr()->mi_key_size;
		if (sz < index_size && co->samePrefixColumns(cur_ind)) {
			ind = cur_ind;
			index_size = sz;
		}
Paul McCullagh's avatar
Paul McCullagh committed
2778
	}
2779 2780 2781 2782

	if (ind) 
		return ind;
	
Paul McCullagh's avatar
Paul McCullagh committed
2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
	{
		char buffer[XT_ERR_MSG_SIZE - 200];
		co->getColumnList(buffer, XT_ERR_MSG_SIZE - 200);
		xt_register_ixterr(XT_REG_CONTEXT, XT_ERR_NO_MATCHING_INDEX, buffer);
	}
	return NULL;
}

XTDDIndex *XTDDTable::findReferenceIndex(XTDDForeignKey *fk)
{
2793 2794
	XTDDIndex		*ind = NULL;
	XTDDIndex		*cur_ind;
Paul McCullagh's avatar
Paul McCullagh committed
2795 2796
	XTDDColumnRef	*cr;
	u_int			i;
2797
	u_int			index_size = UINT_MAX;
Paul McCullagh's avatar
Paul McCullagh committed
2798 2799

	for (i=0; i<dt_indexes.size(); i++) {
2800 2801 2802 2803 2804 2805
		cur_ind = dt_indexes.itemAt(i);
		u_int sz = cur_ind->getIndexPtr()->mi_key_size;
		if (sz < index_size && fk->samePrefixReferenceColumns(cur_ind)) {
			ind = cur_ind;
			index_size = sz;
		}
Paul McCullagh's avatar
Paul McCullagh committed
2806 2807
	}

2808 2809 2810
	if (ind)
		return ind;

Paul McCullagh's avatar
Paul McCullagh committed
2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868
	/* If the index does not exist, maybe the columns do not exist?! */
	for (i=0; i<fk->fk_ref_cols.size(); i++) {
		cr = fk->fk_ref_cols.itemAt(i);
		if (!findColumn(cr->cr_col_name)) {
			xt_register_tabcolerr(XT_REG_CONTEXT, XT_ERR_COLUMN_NOT_FOUND, fk->fk_ref_tab_name, cr->cr_col_name);
			return NULL;
		}
	}
	
	{
		char buffer[XT_ERR_MSG_SIZE - 200];

		fk->getReferenceList(buffer, XT_ERR_MSG_SIZE - 200);
		xt_register_ixterr(XT_REG_CONTEXT, XT_ERR_NO_MATCHING_INDEX, buffer);
	}
	return NULL;
}

bool XTDDTable::insertRow(XTOpenTablePtr ot, xtWord1 *rec_ptr)
{
	bool			ok = true;
	XTInfoBufferRec	rec_buf;

	if (ot->ot_thread->st_ignore_fkeys)
		return true;

	rec_buf.ib_free = FALSE;
	if (!rec_ptr) {
		if (!xt_tab_load_record(ot, ot->ot_curr_rec_id, &rec_buf))
			return false;
		rec_ptr = rec_buf.ib_db.db_data;
		
	}
	for (u_int i=0; i<dt_fkeys.size(); i++) {
		if (!dt_fkeys.itemAt(i)->insertRow(NULL, rec_ptr, ot->ot_thread)) {
			ok = false;
			break;
		}
	}
	xt_ib_free(NULL, &rec_buf);
	return ok;
}

bool XTDDTable::checkNoAction(XTOpenTablePtr ot, xtRecordID rec_id)
{
	XTDDTableRef	*tr;
	bool			ok = true;
	XTInfoBufferRec	rec_buf;
	xtWord1			*rec_ptr;

	if (ot->ot_thread->st_ignore_fkeys)
		return true;

	rec_buf.ib_free = FALSE;
	if (!xt_tab_load_record(ot, rec_id, &rec_buf))
		return false;
	rec_ptr = rec_buf.ib_db.db_data;

Paul McCullagh's avatar
Paul McCullagh committed
2869
	xt_recurrwlock_slock_ns(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2870 2871 2872 2873 2874 2875 2876 2877
	tr = dt_trefs;
	while (tr) {
		if (!tr->checkReference(rec_ptr, ot->ot_thread)) {
			ok = false;
			break;
		}
		tr = tr->tr_next;
	}
Paul McCullagh's avatar
Paul McCullagh committed
2878
	xt_recurrwlock_unslock_ns(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
	xt_ib_free(NULL, &rec_buf);
	return ok;
}

bool XTDDTable::deleteRow(XTOpenTablePtr ot, xtWord1 *rec_ptr)
{
	XTDDTableRef	*tr;
	bool			ok = true;
	XTInfoBufferRec	rec_buf;

	if (ot->ot_thread->st_ignore_fkeys)
		return true;

	rec_buf.ib_free = FALSE;
	if (!rec_ptr) {
		if (!xt_tab_load_record(ot, ot->ot_curr_rec_id, &rec_buf))
			return false;
		rec_ptr = rec_buf.ib_db.db_data;
		
	}
Paul McCullagh's avatar
Paul McCullagh committed
2899
	xt_recurrwlock_slock_ns(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2900 2901 2902 2903 2904 2905 2906 2907
	tr = dt_trefs;
	while (tr) {
		if (!tr->modifyRow(ot, rec_ptr, NULL, ot->ot_thread)) {
			ok = false;
			break;
		}
		tr = tr->tr_next;
	}
Paul McCullagh's avatar
Paul McCullagh committed
2908
	xt_recurrwlock_unslock_ns(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2909 2910 2911 2912 2913 2914 2915 2916
	xt_ib_free(NULL, &rec_buf);
	return ok;
}

void XTDDTable::deleteAllRows(XTThreadPtr self)
{
	XTDDTableRef	*tr;

Paul McCullagh's avatar
Paul McCullagh committed
2917 2918
	xt_recurrwlock_slock(self, &dt_ref_lock);
	pushr_(xt_recurrwlock_unslock, &dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2919 2920 2921 2922 2923 2924 2925

	tr = dt_trefs;
	while (tr) {
		tr->deleteAllRows(self);
		tr = tr->tr_next;
	}

Paul McCullagh's avatar
Paul McCullagh committed
2926
	freer_(); // xt_recurrwlock_unslock(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955
}

bool XTDDTable::updateRow(XTOpenTablePtr ot, xtWord1 *before, xtWord1 *after)
{
	XTDDTableRef	*tr;
	bool			ok;
	XTInfoBufferRec	before_buf;

	ASSERT_NS(after);

	if (ot->ot_thread->st_ignore_fkeys)
		return true;

	/* If before is NULL then this is a cascaded
	 * update. In this case there is no need to check
	 * if the column has a parent!!
	 */
	if (before) {
		if (dt_fkeys.size() > 0) {
			for (u_int i=0; i<dt_fkeys.size(); i++) {
				if (!dt_fkeys.itemAt(i)->insertRow(before, after, ot->ot_thread))
					return false;
			}
		}
	}

	ok = true;
	before_buf.ib_free = FALSE;

Paul McCullagh's avatar
Paul McCullagh committed
2956
	xt_recurrwlock_slock_ns(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
	if ((tr = dt_trefs)) {
		if (!before) {
			if (!xt_tab_load_record(ot, ot->ot_curr_rec_id, &before_buf))
				return false;
			before = before_buf.ib_db.db_data;
		}

		while (tr) {
			if (!tr->modifyRow(ot, before, after, ot->ot_thread)) {
				ok = false;
				break;
			}
			tr = tr->tr_next;
		}
	}
Paul McCullagh's avatar
Paul McCullagh committed
2972
	xt_recurrwlock_unslock_ns(&dt_ref_lock);
Paul McCullagh's avatar
Paul McCullagh committed
2973 2974 2975 2976 2977
	
	xt_ib_free(NULL, &before_buf);
	return ok;
}

2978 2979 2980 2981 2982
/*
 * drop_db parameter is TRUE if we are dropping the schema of this table. In this case
 * we return TRUE if the table has only refs to the tables from its own schema
 */
xtBool XTDDTable::checkCanDrop(xtBool drop_db)
Paul McCullagh's avatar
Paul McCullagh committed
2983 2984
{
	/* no refs or references only itself */
2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
	if ((dt_trefs == NULL) || ((dt_trefs->tr_next == NULL) && (dt_trefs->tr_fkey->co_table == this)))
		return TRUE;

	if (!drop_db) 
		return FALSE;
	
	const char *this_schema = xt_last_2_names_of_path(dt_table->tab_name->ps_path);
	size_t this_schema_sz = xt_last_name_of_path(dt_table->tab_name->ps_path) - this_schema;
	XTDDTableRef *tr = dt_trefs;

	while (tr) {
		const char *tab_path = tr->tr_fkey->co_table->dt_table->tab_name->ps_path;
		const char *tab_schema = xt_last_2_names_of_path(tab_path);
		size_t tab_schema_sz = xt_last_name_of_path(tab_path) - tab_schema;

		if (this_schema_sz != tab_schema_sz || strncmp(this_schema, tab_schema, tab_schema_sz))
			return FALSE;
		
		tr = tr->tr_next;
	}

	return TRUE;
Paul McCullagh's avatar
Paul McCullagh committed
3007
}