bootstrap.c 27.4 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * bootstrap.c
4 5
 *	  routines to support running postgres in 'bootstrap' mode
 *	bootstrap mode is used to create the initial template database
6
 *
B
Add:  
Bruce Momjian 已提交
7 8
 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
 * Portions Copyright (c) 1994, Regents of the University of California
9 10
 *
 * IDENTIFICATION
11
 *	  $Header: /cvsroot/pgsql/src/backend/bootstrap/bootstrap.c,v 1.89 2000/07/03 20:48:27 petere Exp $
12 13 14
 *
 *-------------------------------------------------------------------------
 */
B
Bruce Momjian 已提交
15
#include <unistd.h>
16 17 18 19
#include <time.h>
#include <signal.h>
#include <setjmp.h>

20
#define BOOTSTRAP_INCLUDE		/* mask out stuff in tcop/tcopprot.h */
21 22

#include "postgres.h"
23 24 25
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
26 27 28 29 30 31 32 33

#include "access/genam.h"
#include "access/heapam.h"
#include "bootstrap/bootstrap.h"
#include "catalog/catname.h"
#include "catalog/index.h"
#include "catalog/pg_type.h"
#include "libpq/pqsignal.h"
B
Bruce Momjian 已提交
34
#include "miscadmin.h"
35 36
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
37
#include "utils/exc.h"
38
#include "utils/fmgroids.h"
39
#include "utils/guc.h"
40
#include "utils/lsyscache.h"
41

M
-Wall'd  
Marc G. Fournier 已提交
42

43
#define ALLOC(t, c)		((t *) calloc((unsigned)(c), sizeof(t)))
44

45 46 47
extern void StartupXLOG(void);
extern void ShutdownXLOG(void);
extern void BootStrapXLOG(void);
48

49 50
extern char XLogDir[];
extern char ControlFilePath[];
51

52
extern int	Int_yyparse(void);
53
static hashnode *AddStr(char *str, int strlength, int mderef);
54
static Form_pg_attribute AllocateAttribute(void);
55 56
static bool BootstrapAlreadySeen(Oid id);
static int	CompHash(char *str, int len);
57
static hashnode *FindStr(char *str, int length, hashnode *mderef);
58
static Oid	gettype(char *type);
59
static void cleanup(void);
60

61
/* ----------------
62
 *		global variables
63 64 65 66 67 68 69 70 71 72 73 74
 * ----------------
 */
/*
 * In the lexical analyzer, we need to get the reference number quickly from
 * the string, and the string from the reference number.  Thus we have
 * as our data structure a hash table, where the hashing key taken from
 * the particular string.  The hash table is chained.  One of the fields
 * of the hash table node is an index into the array of character pointers.
 * The unique index number that every string is assigned is simply the
 * position of its string pointer in the array of string pointers.
 */

75 76
#define STRTABLESIZE	10000
#define HASHTABLESIZE	503
77 78

/* Hash function numbers */
79 80
#define NUM		23
#define NUMSQR	529
81
#define NUMCUBE 12167
82

83 84
char	   *strtable[STRTABLESIZE];
hashnode   *hashtable[HASHTABLESIZE];
85

86
static int	strtable_end = -1;	/* Tells us last occupied string space */
87 88 89 90 91

/*-
 * Basic information associated with each type.  This is used before
 * pg_type is created.
 *
92 93 94
 *		XXX several of these input/output functions do catalog scans
 *			(e.g., F_REGPROCIN scans pg_proc).	this obviously creates some
 *			order dependencies in the catalog creation process.
95
 */
96 97
struct typinfo
{
98 99 100 101 102 103
	char		name[NAMEDATALEN];
	Oid			oid;
	Oid			elem;
	int16		len;
	Oid			inproc;
	Oid			outproc;
104 105 106
};

static struct typinfo Procid[] = {
107 108 109 110 111
	{"bool", BOOLOID, 0, 1, F_BOOLIN, F_BOOLOUT},
	{"bytea", BYTEAOID, 0, -1, F_BYTEAIN, F_BYTEAOUT},
	{"char", CHAROID, 0, 1, F_CHARIN, F_CHAROUT},
	{"name", NAMEOID, 0, NAMEDATALEN, F_NAMEIN, F_NAMEOUT},
	{"int2", INT2OID, 0, 2, F_INT2IN, F_INT2OUT},
112
	{"int2vector", INT2VECTOROID, 0, INDEX_MAX_KEYS * 2, F_INT2VECTORIN, F_INT2VECTOROUT},
113 114 115
	{"int4", INT4OID, 0, 4, F_INT4IN, F_INT4OUT},
	{"regproc", REGPROCOID, 0, 4, F_REGPROCIN, F_REGPROCOUT},
	{"text", TEXTOID, 0, -1, F_TEXTIN, F_TEXTOUT},
116
	{"oid", OIDOID, 0, 4, F_OIDIN, F_OIDOUT},
117 118 119
	{"tid", TIDOID, 0, 6, F_TIDIN, F_TIDOUT},
	{"xid", XIDOID, 0, 4, F_XIDIN, F_XIDOUT},
	{"cid", CIDOID, 0, 4, F_CIDIN, F_CIDOUT},
120
	{"oidvector", 30, 0, INDEX_MAX_KEYS * 4, F_OIDVECTORIN, F_OIDVECTOROUT},
121
	{"smgr", 210, 0, 2, F_SMGRIN, F_SMGROUT},
122
	{"_int4", 1007, INT4OID, -1, F_ARRAY_IN, F_ARRAY_OUT},
123
	{"_aclitem", 1034, 1033, -1, F_ARRAY_IN, F_ARRAY_OUT}
124 125
};

126
static int	n_types = sizeof(Procid) / sizeof(struct typinfo);
127

128 129
struct typmap
{								/* a hack */
130
	Oid			am_oid;
131
	FormData_pg_type am_typ;
132 133
};

134 135 136
static struct typmap **Typ = (struct typmap **) NULL;
static struct typmap *Ap = (struct typmap *) NULL;

137 138
static int	Warnings = 0;
static char Blanks[MAXATTR];
139

140
static char *relname;			/* current relation name */
141

142
Form_pg_attribute attrtypes[MAXATTR];	/* points to attribute info */
143
static Datum values[MAXATTR];	/* corresponding attribute values */
144
int			numattr;			/* number of attributes for cur. rel */
145

146
int			DebugMode;
147 148

static MemoryContext nogc = NULL; /* special no-gc mem context */
149

150 151
extern int	optind;
extern char *optarg;
152 153

/*
154 155 156
 *	At bootstrap time, we first declare all the indices to be built, and
 *	then build them.  The IndexList structure stores enough information
 *	to allow us to build the indices after they've been declared.
157 158
 */

159 160
typedef struct _IndexList
{
161 162 163 164 165 166
	char	   *il_heap;
	char	   *il_ind;
	int			il_natts;
	AttrNumber *il_attnos;
	FuncIndexInfo *il_finfo;
	PredInfo   *il_predInfo;
167
	bool		il_unique;
168
	struct _IndexList *il_next;
169
} IndexList;
170 171

static IndexList *ILHead = (IndexList *) NULL;
172

173
typedef void (*sig_func) ();
174 175


176 177 178


/* ----------------------------------------------------------------
179
 *						misc functions
180 181 182 183
 * ----------------------------------------------------------------
 */

/* ----------------
184
 *		error handling / abort routines
185 186
 * ----------------
 */
187 188
void
err_out(void)
189
{
190 191
	Warnings++;
	cleanup();
192 193 194 195 196 197
}

/* usage:
   usage help for the bootstrap backen
*/
static void
198
usage(void)
M
-Wall'd  
Marc G. Fournier 已提交
199
{
200 201 202 203 204 205 206 207
	fprintf(stderr, "Usage: postgres -boot [-d] [-C] [-F] [-O] [-Q] ");
	fprintf(stderr, "[-P portno] [dbName]\n");
	fprintf(stderr, "     d: debug mode\n");
	fprintf(stderr, "     C: disable version checking\n");
	fprintf(stderr, "     F: turn off fsync\n");
	fprintf(stderr, "     O: set BootstrapProcessing mode\n");
	fprintf(stderr, "     P portno: specify port number\n");

208
	proc_exit(1);
209 210
}

211 212 213 214


int
BootstrapMain(int argc, char *argv[])
215
/* ----------------------------------------------------------------
216 217 218 219
 *	 The main loop for handling the backend in bootstrap mode
 *	 the bootstrap mode is used to initialize the template database
 *	 the bootstrap backend doesn't speak SQL, but instead expects
 *	 commands in a special bootstrap language.
220
 *
221 222 223
 *	 The arguments passed in to BootstrapMain are the run-time arguments
 *	 without the argument '-boot', the caller is required to have
 *	 removed -boot from the run-time args
224 225 226
 * ----------------------------------------------------------------
 */
{
227 228 229
	int			i;
	char	   *dbName;
	int			flag;
230
	bool		xloginit = false;
231

232 233
	extern int	optind;
	extern char *optarg;
234 235 236 237 238 239 240


	/* --------------------
	 *	initialize globals
	 * -------------------
	 */

B
Bruce Momjian 已提交
241
	MyProcPid = getpid();
242

243 244 245 246 247 248 249 250 251 252 253
	/*
	 * Fire up essential subsystems: error and memory management
	 *
	 * If we are running under the postmaster, this is done already.
	 */
	if (!IsUnderPostmaster)
	{
		EnableExceptionHandling(true);
		MemoryContextInit();
	}

254 255 256 257 258 259
	/* ----------------
	 *	process command arguments
	 * ----------------
	 */

	/* Set defaults, to be overriden by explicit options below */
260 261
	Quiet = false;
	Noversion = false;
262
	dbName = NULL;
263 264 265 266 267
	if (!IsUnderPostmaster)
	{
		ResetAllOptions();
		DataDir = getenv("PGDATA"); /* Null if no PGDATA variable */
	}
268

269
	while ((flag = getopt(argc, argv, "D:dCQxpB:F")) != EOF)
270 271 272
	{
		switch (flag)
		{
273 274 275 276
			case 'D':
				DataDir = optarg;
				break;
			case 'd':
277 278
				DebugMode = true;		/* print out debugging info while
										 * parsing */
279 280
				break;
			case 'C':
281
				Noversion = true;
282 283
				break;
			case 'F':
284
				enableFsync = false;
285 286
				break;
			case 'Q':
287
				Quiet = true;
288
				break;
289 290 291 292
			case 'x':
				xloginit = true;
				break;
			case 'p':
293
				/* indicates fork from postmaster */
294 295 296
				break;
			case 'B':
				NBuffers = atoi(optarg);
297 298 299 300
				break;
			default:
				usage();
				break;
301 302 303 304 305 306 307 308
		}
	}							/* while */

	if (argc - optind > 1)
		usage();
	else if (argc - optind == 1)
		dbName = argv[optind];

309
	SetProcessingMode(BootstrapProcessing);
H
Hiroshi Inoue 已提交
310
	IgnoreSystemIndexes(true);
311

312 313 314 315 316 317 318
	if (!DataDir)
	{
		fprintf(stderr, "%s does not know where to find the database system "
				"data.  You must specify the directory that contains the "
				"database system either by specifying the -D invocation "
			 "option or by setting the PGDATA environment variable.\n\n",
				argv[0]);
319
		proc_exit(1);
320 321 322 323 324 325 326 327 328
	}

	if (dbName == NULL)
	{
		dbName = getenv("USER");
		if (dbName == NULL)
		{
			fputs("bootstrap backend: failed, no db name specified\n", stderr);
			fputs("          and no USER enviroment variable\n", stderr);
329
			proc_exit(1);
330 331 332
		}
	}

333 334 335 336 337 338 339 340 341 342
	BaseInit();

	if (!IsUnderPostmaster)
	{
		pqsignal(SIGINT, (sig_func) die);
		pqsignal(SIGHUP, (sig_func) die);
		pqsignal(SIGTERM, (sig_func) die);
	}

	/*
343 344
	 * Bootstrap under Postmaster means two things: (xloginit) ?
	 * StartupXLOG : ShutdownXLOG
345 346
	 *
	 * If !under Postmaster and xloginit then BootStrapXLOG.
347
	 */
348
	if (IsUnderPostmaster || xloginit)
349
	{
350 351
		snprintf(XLogDir, MAXPGPATH, "%s/pg_xlog", DataDir);
		snprintf(ControlFilePath, MAXPGPATH, "%s/global/pg_control", DataDir);
352 353
	}

354 355 356 357 358 359 360 361 362 363 364
	if (IsUnderPostmaster && xloginit)
	{
		StartupXLOG();
		proc_exit(0);
	}

	if (!IsUnderPostmaster && xloginit)
		BootStrapXLOG();

	/*
	 * backend initialization
365 366 367 368
	 */
	InitPostgres(dbName);
	LockDisable(true);

369 370 371 372 373 374
	if (IsUnderPostmaster && !xloginit)
	{
		ShutdownXLOG();
		proc_exit(0);
	}

375 376
	for (i = 0; i < MAXATTR; i++)
	{
377
		attrtypes[i] = (Form_pg_attribute) NULL;
378 379 380 381 382 383 384 385
		Blanks[i] = ' ';
	}
	for (i = 0; i < STRTABLESIZE; ++i)
		strtable[i] = NULL;
	for (i = 0; i < HASHTABLESIZE; ++i)
		hashtable[i] = NULL;

	/* ----------------
386
	 *	abort processing resumes here
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
	 * ----------------
	 */
	pqsignal(SIGHUP, handle_warn);

	if (sigsetjmp(Warn_restart, 1) != 0)
	{
		Warnings++;
		AbortCurrentTransaction();
	}

	/* ----------------
	 *	process input.
	 * ----------------
	 */

	/*
	 * the sed script boot.sed renamed yyparse to Int_yyparse for the
	 * bootstrap parser to avoid conflicts with the normal SQL parser
	 */
	Int_yyparse();

	/* clean up processing */
	StartTransactionCommand();
	cleanup();

	/* not reached, here to make compiler happy */
	return 0;
414 415 416 417

}

/* ----------------------------------------------------------------
418
 *				MANUAL BACKEND INTERACTIVE INTERFACE COMMANDS
419 420 421 422
 * ----------------------------------------------------------------
 */

/* ----------------
423
 *		boot_openrel
424 425 426 427 428
 * ----------------
 */
void
boot_openrel(char *relname)
{
429
	int			i;
430
	struct typmap **app;
431 432
	Relation	rel;
	HeapScanDesc scan;
433
	HeapTuple	tup;
434

435 436
	if (strlen(relname) >= NAMEDATALEN - 1)
		relname[NAMEDATALEN - 1] = '\0';
437 438 439

	if (Typ == (struct typmap **) NULL)
	{
440 441
		rel = heap_openr(TypeRelationName, NoLock);
		Assert(rel);
442 443 444 445 446
		scan = heap_beginscan(rel, 0, SnapshotNow, 0, (ScanKey) NULL);
		i = 0;
		while (HeapTupleIsValid(tup = heap_getnext(scan, 0)))
			++i;
		heap_endscan(scan);
447 448 449 450
		app = Typ = ALLOC(struct typmap *, i + 1);
		while (i-- > 0)
			*app++ = ALLOC(struct typmap, 1);
		*app = (struct typmap *) NULL;
451
		scan = heap_beginscan(rel, 0, SnapshotNow, 0, (ScanKey) NULL);
452
		app = Typ;
453
		while (HeapTupleIsValid(tup = heap_getnext(scan, 0)))
454
		{
455
			(*app)->am_oid = tup->t_data->t_oid;
456 457 458 459
			memcpy((char *) &(*app)->am_typ,
				   (char *) GETSTRUCT(tup),
				   sizeof((*app)->am_typ));
			app++;
460
		}
461
		heap_endscan(scan);
462
		heap_close(rel, NoLock);
463 464 465 466 467 468 469 470 471
	}

	if (reldesc != NULL)
		closerel(NULL);

	if (!Quiet)
		printf("Amopen: relation %s. attrsize %d\n", relname ? relname : "(null)",
			   (int) ATTRIBUTE_TUPLE_SIZE);

472
	reldesc = heap_openr(relname, NoLock);
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
	Assert(reldesc);
	numattr = reldesc->rd_rel->relnatts;
	for (i = 0; i < numattr; i++)
	{
		if (attrtypes[i] == NULL)
			attrtypes[i] = AllocateAttribute();
		memmove((char *) attrtypes[i],
				(char *) reldesc->rd_att->attrs[i],
				ATTRIBUTE_TUPLE_SIZE);

		/* Some old pg_attribute tuples might not have attisset. */

		/*
		 * If the attname is attisset, don't look for it - it may not be
		 * defined yet.
		 */
		if (namestrcmp(&attrtypes[i]->attname, "attisset") == 0)
490
			attrtypes[i]->attisset = get_attisset(RelationGetRelid(reldesc),
491
										 NameStr(attrtypes[i]->attname));
492 493 494 495 496
		else
			attrtypes[i]->attisset = false;

		if (DebugMode)
		{
497
			Form_pg_attribute at = attrtypes[i];
498 499

			printf("create attribute %d name %s len %d num %d type %d\n",
500
				   i, NameStr(at->attname), at->attlen, at->attnum,
501 502 503 504 505
				   at->atttypid
				);
			fflush(stdout);
		}
	}
506 507 508
}

/* ----------------
509
 *		closerel
510 511 512 513 514
 * ----------------
 */
void
closerel(char *name)
{
515 516 517 518
	if (name)
	{
		if (reldesc)
		{
519
			if (strcmp(RelationGetRelationName(reldesc), name) != 0)
520
				elog(ERROR, "closerel: close of '%s' when '%s' was expected",
521 522 523
					 name, relname ? relname : "(null)");
		}
		else
524
			elog(ERROR, "closerel: close of '%s' before any relation was opened",
525 526 527 528 529
				 name);

	}

	if (reldesc == NULL)
530
		elog(ERROR, "Warning: no opened relation to close.\n");
531 532 533 534
	else
	{
		if (!Quiet)
			printf("Amclose: relation %s.\n", relname ? relname : "(null)");
535
		heap_close(reldesc, NoLock);
536 537
		reldesc = (Relation) NULL;
	}
538 539
}

540 541


542 543 544 545 546 547 548 549 550 551 552
/* ----------------
 * DEFINEATTR()
 *
 * define a <field,type> pair
 * if there are n fields in a relation to be created, this routine
 * will be called n times
 * ----------------
 */
void
DefineAttr(char *name, char *type, int attnum)
{
553
	int			attlen;
554
	Oid			typeoid;
555 556 557 558 559 560 561

	if (reldesc != NULL)
	{
		fputs("Warning: no open relations allowed with 't' command.\n", stderr);
		closerel(relname);
	}

562
	typeoid = gettype(type);
563
	if (attrtypes[attnum] == (Form_pg_attribute) NULL)
564 565 566 567 568 569
		attrtypes[attnum] = AllocateAttribute();
	if (Typ != (struct typmap **) NULL)
	{
		attrtypes[attnum]->atttypid = Ap->am_oid;
		namestrcpy(&attrtypes[attnum]->attname, name);
		if (!Quiet)
570
			printf("<%s %s> ", NameStr(attrtypes[attnum]->attname), type);
571 572 573
		attrtypes[attnum]->attnum = 1 + attnum; /* fillatt */
		attlen = attrtypes[attnum]->attlen = Ap->am_typ.typlen;
		attrtypes[attnum]->attbyval = Ap->am_typ.typbyval;
574
		attrtypes[attnum]->attstorage = 'p';
575
		attrtypes[attnum]->attalign = Ap->am_typ.typalign;
576 577 578
	}
	else
	{
579
		attrtypes[attnum]->atttypid = Procid[typeoid].oid;
580 581
		namestrcpy(&attrtypes[attnum]->attname, name);
		if (!Quiet)
582
			printf("<%s %s> ", NameStr(attrtypes[attnum]->attname), type);
583
		attrtypes[attnum]->attnum = 1 + attnum; /* fillatt */
584
		attlen = attrtypes[attnum]->attlen = Procid[typeoid].len;
585
		attrtypes[attnum]->attstorage = 'p';
B
Bruce Momjian 已提交
586 587 588

		/*
		 * Cheat like mad to fill in these items from the length only.
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
		 * This only has to work for types used in the system catalogs...
		 */
		switch (attlen)
		{
			case 1:
				attrtypes[attnum]->attbyval = true;
				attrtypes[attnum]->attalign = 'c';
				break;
			case 2:
				attrtypes[attnum]->attbyval = true;
				attrtypes[attnum]->attalign = 's';
				break;
			case 4:
				attrtypes[attnum]->attbyval = true;
				attrtypes[attnum]->attalign = 'i';
				break;
			default:
				attrtypes[attnum]->attbyval = false;
				attrtypes[attnum]->attalign = 'i';
				break;
		}
610
	}
611
	attrtypes[attnum]->attcacheoff = -1;
B
Bruce Momjian 已提交
612
	attrtypes[attnum]->atttypmod = -1;
613 614 615 616
}


/* ----------------
617 618
 *		InsertOneTuple
 *		assumes that 'oid' will not be zero.
619 620 621 622 623
 * ----------------
 */
void
InsertOneTuple(Oid objectid)
{
624 625
	HeapTuple	tuple;
	TupleDesc	tupDesc;
626

627
	int			i;
628 629 630

	if (DebugMode)
	{
631
		printf("InsertOneTuple oid %u, %d attrs\n", objectid, numattr);
632 633 634 635
		fflush(stdout);
	}

	tupDesc = CreateTupleDesc(numattr, attrtypes);
636
	tuple = heap_formtuple(tupDesc, values, Blanks);
637 638 639
	pfree(tupDesc);				/* just free's tupDesc, not the attrtypes */

	if (objectid != (Oid) 0)
640
		tuple->t_data->t_oid = objectid;
641
	heap_insert(reldesc, tuple);
642
	heap_freetuple(tuple);
643 644
	if (DebugMode)
	{
645
		printf("End InsertOneTuple, objectid=%u\n", objectid);
646 647 648 649 650 651 652 653
		fflush(stdout);
	}

	/*
	 * Reset blanks for next tuple
	 */
	for (i = 0; i < numattr; i++)
		Blanks[i] = ' ';
654 655 656
}

/* ----------------
657
 *		InsertOneValue
658 659 660 661 662
 * ----------------
 */
void
InsertOneValue(Oid objectid, char *value, int i)
{
663 664
	int			typeindex;
	char	   *prt;
665 666 667 668 669 670 671 672 673 674 675 676
	struct typmap **app;

	if (DebugMode)
		printf("Inserting value: '%s'\n", value);
	if (i < 0 || i >= MAXATTR)
	{
		printf("i out of range: %d\n", i);
		Assert(0);
	}

	if (Typ != (struct typmap **) NULL)
	{
677
		struct typmap *ap;
678 679 680 681 682 683 684 685 686

		if (DebugMode)
			puts("Typ != NULL");
		app = Typ;
		while (*app && (*app)->am_oid != reldesc->rd_att->attrs[i]->atttypid)
			++app;
		ap = *app;
		if (ap == NULL)
		{
687
			printf("Unable to find atttypid in Typ list! %u\n",
688 689 690 691
				   reldesc->rd_att->attrs[i]->atttypid
				);
			Assert(0);
		}
692 693 694 695 696 697 698 699
		values[i] = OidFunctionCall3(ap->am_typ.typinput,
									 CStringGetDatum(value),
									 ObjectIdGetDatum(ap->am_typ.typelem),
									 Int32GetDatum(-1));
		prt = DatumGetCString(OidFunctionCall3(ap->am_typ.typoutput,
							  values[i],
							  ObjectIdGetDatum(ap->am_typ.typelem),
							  Int32GetDatum(-1)));
700 701 702 703 704 705
		if (!Quiet)
			printf("%s ", prt);
		pfree(prt);
	}
	else
	{
706 707 708 709 710 711 712
		for (typeindex = 0; typeindex < n_types; typeindex++)
		{
			if (Procid[typeindex].oid == attrtypes[i]->atttypid)
				break;
		}
		if (typeindex >= n_types)
			elog(ERROR, "can't find type OID %u", attrtypes[i]->atttypid);
713
		if (DebugMode)
714
			printf("Typ == NULL, typeindex = %u idx = %d\n", typeindex, i);
715 716 717 718 719 720 721 722
		values[i] = OidFunctionCall3(Procid[typeindex].inproc,
									 CStringGetDatum(value),
									 ObjectIdGetDatum(Procid[typeindex].elem),
									 Int32GetDatum(-1));
		prt = DatumGetCString(OidFunctionCall3(Procid[typeindex].outproc,
							  values[i],
							  ObjectIdGetDatum(Procid[typeindex].elem),
							  Int32GetDatum(-1)));
723 724 725 726 727 728 729 730 731
		if (!Quiet)
			printf("%s ", prt);
		pfree(prt);
	}
	if (DebugMode)
	{
		puts("End InsertValue");
		fflush(stdout);
	}
732 733 734
}

/* ----------------
735
 *		InsertOneNull
736 737 738 739 740
 * ----------------
 */
void
InsertOneNull(int i)
{
741 742 743 744
	if (DebugMode)
		printf("Inserting null\n");
	if (i < 0 || i >= MAXATTR)
		elog(FATAL, "i out of range (too many attrs): %d\n", i);
745
	values[i] = PointerGetDatum(NULL);
746
	Blanks[i] = 'n';
747 748 749 750
}

#define MORE_THAN_THE_NUMBER_OF_CATALOGS 256

751
static bool
752 753
BootstrapAlreadySeen(Oid id)
{
754 755 756 757
	static Oid	seenArray[MORE_THAN_THE_NUMBER_OF_CATALOGS];
	static int	nseen = 0;
	bool		seenthis;
	int			i;
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773

	seenthis = false;

	for (i = 0; i < nseen; i++)
	{
		if (seenArray[i] == id)
		{
			seenthis = true;
			break;
		}
	}
	if (!seenthis)
	{
		seenArray[nseen] = id;
		nseen++;
	}
774
	return seenthis;
775 776 777
}

/* ----------------
778
 *		cleanup
779 780
 * ----------------
 */
781
static void
782 783
cleanup()
{
784
	static int	beenhere = 0;
785 786 787 788 789

	if (!beenhere)
		beenhere = 1;
	else
	{
790
		elog(FATAL, "Memory manager fault: cleanup called twice.\n");
791
		proc_exit(1);
792 793
	}
	if (reldesc != (Relation) NULL)
794
		heap_close(reldesc, NoLock);
795
	CommitTransactionCommand();
796
	proc_exit(Warnings);
797 798 799
}

/* ----------------
800
 *		gettype
801 802
 * ----------------
 */
803
static Oid
804 805
gettype(char *type)
{
806
	int			i;
807 808
	Relation	rel;
	HeapScanDesc scan;
809
	HeapTuple	tup;
810 811 812 813 814 815
	struct typmap **app;

	if (Typ != (struct typmap **) NULL)
	{
		for (app = Typ; *app != (struct typmap *) NULL; app++)
		{
816
			if (strncmp(NameStr((*app)->am_typ.typname), type, NAMEDATALEN) == 0)
817 818
			{
				Ap = *app;
819
				return (*app)->am_oid;
820 821 822 823 824 825 826 827
			}
		}
	}
	else
	{
		for (i = 0; i <= n_types; i++)
		{
			if (strncmp(type, Procid[i].name, NAMEDATALEN) == 0)
828
				return i;
829 830 831
		}
		if (DebugMode)
			printf("bootstrap.c: External Type: %s\n", type);
832 833
		rel = heap_openr(TypeRelationName, NoLock);
		Assert(rel);
834
		scan = heap_beginscan(rel, 0, SnapshotNow, 0, (ScanKey) NULL);
835
		i = 0;
836
		while (HeapTupleIsValid(tup = heap_getnext(scan, 0)))
837
			++i;
838
		heap_endscan(scan);
839 840 841 842
		app = Typ = ALLOC(struct typmap *, i + 1);
		while (i-- > 0)
			*app++ = ALLOC(struct typmap, 1);
		*app = (struct typmap *) NULL;
843
		scan = heap_beginscan(rel, 0, SnapshotNow, 0, (ScanKey) NULL);
844
		app = Typ;
845
		while (HeapTupleIsValid(tup = heap_getnext(scan, 0)))
846
		{
847
			(*app)->am_oid = tup->t_data->t_oid;
848 849 850 851
			memmove((char *) &(*app++)->am_typ,
					(char *) GETSTRUCT(tup),
					sizeof((*app)->am_typ));
		}
852
		heap_endscan(scan);
853
		heap_close(rel, NoLock);
854
		return gettype(type);
855
	}
856
	elog(ERROR, "Error: unknown type '%s'.\n", type);
857 858 859
	err_out();
	/* not reached, here to make compiler happy */
	return 0;
860 861 862
}

/* ----------------
863
 *		AllocateAttribute
864 865
 * ----------------
 */
866
static Form_pg_attribute		/* XXX */
867 868
AllocateAttribute()
{
869
	Form_pg_attribute attribute = (Form_pg_attribute) malloc(ATTRIBUTE_TUPLE_SIZE);
870 871 872

	if (!PointerIsValid(attribute))
		elog(FATAL, "AllocateAttribute: malloc failed");
B
Bruce Momjian 已提交
873
	MemSet(attribute, 0, ATTRIBUTE_TUPLE_SIZE);
874

875
	return attribute;
876 877 878
}

/* ----------------
879
 *		MapArrayTypeName
880
 * XXX arrays of "basetype" are always "_basetype".
881
 *	   this is an evil hack inherited from rel. 3.1.
882
 * XXX array dimension is thrown away because we
883 884 885 886
 *	   don't support fixed-dimension arrays.  again,
 *	   sickness from 3.1.
 *
 * the string passed in must have a '[' character in it
887 888 889 890 891
 *
 * the string returned is a pointer to static storage and should NOT
 * be freed by the CALLER.
 * ----------------
 */
892
char *
893 894
MapArrayTypeName(char *s)
{
895 896 897 898
	int			i,
				j;
	static char newStr[NAMEDATALEN];	/* array type names < NAMEDATALEN
										 * long */
899

900 901
	if (s == NULL || s[0] == '\0')
		return s;
902

903 904 905 906
	j = 1;
	newStr[0] = '_';
	for (i = 0; i < NAMEDATALEN - 1 && s[i] != '['; i++, j++)
		newStr[j] = s[i];
907

908 909 910
	newStr[j] = '\0';

	return newStr;
911 912 913
}

/* ----------------
914 915 916
 *		EnterString
 *		returns the string table position of the identifier
 *		passed to it.  We add it to the table if we can't find it.
917 918 919
 * ----------------
 */
int
920
EnterString(char *str)
921
{
922 923
	hashnode   *node;
	int			len;
924 925 926 927 928

	len = strlen(str);

	node = FindStr(str, len, 0);
	if (node)
929
		return node->strnum;
930 931 932
	else
	{
		node = AddStr(str, len, 0);
933
		return node->strnum;
934
	}
935 936 937
}

/* ----------------
938 939 940
 *		LexIDStr
 *		when given an idnum into the 'string-table' return the string
 *		associated with the idnum
941 942
 * ----------------
 */
943
char *
944
LexIDStr(int ident_num)
945
{
946
	return strtable[ident_num];
947
}
948 949 950


/* ----------------
951
 *		CompHash
952
 *
953 954 955 956
 *		Compute a hash function for a given string.  We look at the first,
 *		the last, and the middle character of a string to try to get spread
 *		the strings out.  The function is rather arbitrary, except that we
 *		are mod'ing by a prime number.
957 958
 * ----------------
 */
959
static int
960 961
CompHash(char *str, int len)
{
962
	int			result;
963 964 965

	result = (NUM * str[0] + NUMSQR * str[len - 1] + NUMCUBE * str[(len - 1) / 2]);

966
	return result % HASHTABLESIZE;
967

968 969 970
}

/* ----------------
971
 *		FindStr
972
 *
973 974 975
 *		This routine looks for the specified string in the hash
 *		table.	It returns a pointer to the hash node found,
 *		or NULL if the string is not in the table.
976 977
 * ----------------
 */
978
static hashnode *
979
FindStr(char *str, int length, hashnode *mderef)
980
{
981
	hashnode   *node;
982 983 984 985 986 987 988 989 990 991 992

	node = hashtable[CompHash(str, length)];
	while (node != NULL)
	{

		/*
		 * We must differentiate between string constants that might have
		 * the same value as a identifier and the identifier itself.
		 */
		if (!strcmp(str, strtable[node->strnum]))
		{
993
			return node;		/* no need to check */
994 995 996 997 998
		}
		else
			node = node->next;
	}
	/* Couldn't find it in the list */
999
	return NULL;
1000 1001 1002
}

/* ----------------
1003
 *		AddStr
1004
 *
1005 1006 1007 1008
 *		This function adds the specified string, along with its associated
 *		data, to the hash table and the string table.  We return the node
 *		so that the calling routine can find out the unique id that AddStr
 *		has assigned to this string.
1009 1010
 * ----------------
 */
1011
static hashnode *
1012 1013
AddStr(char *str, int strlength, int mderef)
{
1014 1015 1016 1017 1018
	hashnode   *temp,
			   *trail,
			   *newnode;
	int			hashresult;
	int			len;
1019 1020 1021 1022 1023 1024 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

	if (++strtable_end == STRTABLESIZE)
	{
		/* Error, string table overflow, so we Punt */
		elog(FATAL,
			 "There are too many string constants and identifiers for the compiler to handle.");


	}

	/*
	 * Some of the utilites (eg, define type, create relation) assume that
	 * the string they're passed is a NAMEDATALEN.  We get array bound
	 * read violations from purify if we don't allocate at least
	 * NAMEDATALEN bytes for strings of this sort.	Because we're lazy, we
	 * allocate at least NAMEDATALEN bytes all the time.
	 */

	if ((len = strlength + 1) < NAMEDATALEN)
		len = NAMEDATALEN;

	strtable[strtable_end] = malloc((unsigned) len);
	strcpy(strtable[strtable_end], str);

	/* Now put a node in the hash table */

	newnode = (hashnode *) malloc(sizeof(hashnode) * 1);
	newnode->strnum = strtable_end;
	newnode->next = NULL;

	/* Find out where it goes */

	hashresult = CompHash(str, strlength);
	if (hashtable[hashresult] == NULL)
		hashtable[hashresult] = newnode;
	else
	{							/* There is something in the list */
		trail = hashtable[hashresult];
		temp = trail->next;
		while (temp != NULL)
		{
			trail = temp;
			temp = temp->next;
		}
		trail->next = newnode;
	}
1065
	return newnode;
1066 1067 1068 1069 1070
}



/*
1071 1072
 *	index_register() -- record an index that has been set up for building
 *						later.
1073
 *
1074 1075 1076 1077 1078
 *		At bootstrap time, we define a bunch of indices on system catalogs.
 *		We postpone actually building the indices until just before we're
 *		finished with initialization, however.	This is because more classes
 *		and indices may be defined, and we want to be sure that all of them
 *		are present in the index.
1079 1080 1081
 */
void
index_register(char *heap,
1082 1083
			   char *ind,
			   int natts,
B
Bruce Momjian 已提交
1084
			   AttrNumber *attnos,
1085
			   FuncIndexInfo *finfo,
1086 1087
			   PredInfo *predInfo,
			   bool unique)
1088
{
1089 1090 1091
	IndexList  *newind;
	int			len;
	MemoryContext oldcxt;
1092 1093 1094 1095 1096 1097 1098

	/*
	 * XXX mao 10/31/92 -- don't gc index reldescs, associated info at
	 * bootstrap time.	we'll declare the indices now, but want to create
	 * them later.
	 */

1099 1100 1101 1102 1103 1104
	if (nogc == NULL)
		nogc = AllocSetContextCreate((MemoryContext) NULL,
									 "BootstrapNoGC",
									 ALLOCSET_DEFAULT_MINSIZE,
									 ALLOCSET_DEFAULT_INITSIZE,
									 ALLOCSET_DEFAULT_MAXSIZE);
1105

1106
	oldcxt = MemoryContextSwitchTo(nogc);
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

	newind = (IndexList *) palloc(sizeof(IndexList));
	newind->il_heap = pstrdup(heap);
	newind->il_ind = pstrdup(ind);
	newind->il_natts = natts;

	if (PointerIsValid(finfo))
		len = FIgetnArgs(finfo) * sizeof(AttrNumber);
	else
		len = natts * sizeof(AttrNumber);

	newind->il_attnos = (AttrNumber *) palloc(len);
1119
	memcpy(newind->il_attnos, attnos, len);
1120

1121
	if (PointerIsValid(finfo))
1122 1123
	{
		newind->il_finfo = (FuncIndexInfo *) palloc(sizeof(FuncIndexInfo));
1124
		memcpy(newind->il_finfo, finfo, sizeof(FuncIndexInfo));
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
	}
	else
		newind->il_finfo = (FuncIndexInfo *) NULL;

	if (predInfo != NULL)
	{
		newind->il_predInfo = (PredInfo *) palloc(sizeof(PredInfo));
		newind->il_predInfo->pred = predInfo->pred;
		newind->il_predInfo->oldPred = predInfo->oldPred;
	}
	else
		newind->il_predInfo = NULL;

1138 1139
	newind->il_unique = unique;

1140 1141 1142 1143 1144
	newind->il_next = ILHead;

	ILHead = newind;

	MemoryContextSwitchTo(oldcxt);
1145 1146 1147 1148 1149
}

void
build_indices()
{
1150 1151
	Relation	heap;
	Relation	ind;
1152 1153 1154

	for (; ILHead != (IndexList *) NULL; ILHead = ILHead->il_next)
	{
1155 1156
		heap = heap_openr(ILHead->il_heap, NoLock);
		Assert(heap);
1157
		ind = index_openr(ILHead->il_ind);
1158
		Assert(ind);
1159
		index_build(heap, ind, ILHead->il_natts, ILHead->il_attnos,
1160 1161
					ILHead->il_finfo, ILHead->il_predInfo,
					ILHead->il_unique);
1162 1163 1164 1165

		/*
		 * In normal processing mode, index_build would close the heap and
		 * index, but in bootstrap mode it will not.
1166
		 */
1167 1168 1169 1170 1171 1172 1173 1174 1175

		/*
		 * All of the rest of this routine is needed only because in
		 * bootstrap processing we don't increment xact id's.  The normal
		 * DefineIndex code replaces a pg_class tuple with updated info
		 * including the relhasindex flag (which we need to have updated).
		 * Unfortunately, there are always two indices defined on each
		 * catalog causing us to update the same pg_class tuple twice for
		 * each catalog getting an index during bootstrap resulting in the
1176
		 * ghost tuple problem (see heap_update).	To get around this we
1177 1178 1179 1180 1181 1182 1183
		 * change the relhasindex field ourselves in this routine keeping
		 * track of what catalogs we already changed so that we don't
		 * modify those tuples twice.  The normal mechanism for updating
		 * pg_class is disabled during bootstrap.
		 *
		 * -mer
		 */
1184 1185
		if (!BootstrapAlreadySeen(RelationGetRelid(heap)))
			UpdateStats(RelationGetRelid(heap), 0, true);
1186 1187

		/* XXX Probably we ought to close the heap and index here? */
1188
	}
1189
}