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 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/bootstrap/bootstrap.c,v 1.47 1998/07/27 19:37:43 vadim Exp $
11 12 13
 *
 *-------------------------------------------------------------------------
 */
14
#include <unistd.h>				/* For getopt() */
15 16 17 18
#include <time.h>
#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
19
#include <string.h>
20

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

#include "postgres.h"

25 26 27
#include "miscadmin.h"
#include "fmgr.h"

Marc G. Fournier's avatar
Marc G. Fournier committed
28
#include "access/attnum.h"
29 30 31 32 33 34 35 36 37
#include "access/funcindex.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup.h"
#include "access/itup.h"
#include "access/relscan.h"
#include "access/sdir.h"
#include "access/skey.h"
#include "access/strat.h"
38
#include "access/tupdesc.h"
39 40 41 42
#include "access/xact.h"
#include "bootstrap/bootstrap.h"
#include "catalog/catname.h"
#include "catalog/index.h"
Marc G. Fournier's avatar
Marc G. Fournier committed
43
#include "catalog/pg_am.h"
44
#include "catalog/pg_attribute.h"
Marc G. Fournier's avatar
Marc G. Fournier committed
45
#include "catalog/pg_class.h"
46 47 48 49 50 51 52
#include "catalog/pg_type.h"
#include "executor/execdesc.h"
#include "executor/hashjoin.h"
#include "executor/tuptable.h"
#include "libpq/pqsignal.h"
#include "nodes/execnodes.h"
#include "nodes/memnodes.h"
Marc G. Fournier's avatar
Marc G. Fournier committed
53
#include "nodes/nodes.h"
54 55 56 57 58
#include "nodes/params.h"
#include "nodes/parsenodes.h"
#include "nodes/plannodes.h"
#include "nodes/pg_list.h"
#include "nodes/primnodes.h"
Marc G. Fournier's avatar
Marc G. Fournier committed
59 60
#include "rewrite/prs2lock.h"
#include "storage/block.h"
61
#include "storage/buf.h"
62
#include "storage/fd.h"
Marc G. Fournier's avatar
Marc G. Fournier committed
63
#include "storage/ipc.h"
64 65 66 67
#include "storage/itemptr.h"
#include "storage/lock.h"
#include "storage/off.h"
#include "storage/shmem.h"
Marc G. Fournier's avatar
Marc G. Fournier committed
68
#include "storage/spin.h"
69 70 71 72
#include "tcop/dest.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/geo_decls.h"
Marc G. Fournier's avatar
Marc G. Fournier committed
73
#include "utils/hsearch.h"
74 75 76 77 78
#include "utils/lsyscache.h"
#include "utils/mcxt.h"
#include "utils/nabstime.h"
#include "utils/portal.h"
#include "utils/rel.h"
Marc G. Fournier's avatar
Marc G. Fournier committed
79 80

#ifndef HAVE_MEMMOVE
81
#include "regex/utils.h"
Marc G. Fournier's avatar
Marc G. Fournier committed
82 83
#endif

84 85
#define ALLOC(t, c)		(t *)calloc((unsigned)(c), sizeof(t))
#define FIRST_TYPE_OID 16		/* OID of the first type */
86

87
extern int	Int_yyparse(void);
88 89
static hashnode *AddStr(char *str, int strlength, int mderef);
static AttributeTupleForm AllocateAttribute(void);
90 91
static bool BootstrapAlreadySeen(Oid id);
static int	CompHash(char *str, int len);
92
static hashnode *FindStr(char *str, int length, hashnode *mderef);
93 94
static int	gettype(char *type);
static void cleanup(void);
95

96
/* ----------------
97
 *		global variables
98 99 100 101 102 103 104 105 106 107 108 109
 * ----------------
 */
/*
 * 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.
 */

110 111
#define STRTABLESIZE	10000
#define HASHTABLESIZE	503
112 113

/* Hash function numbers */
114 115
#define NUM		23
#define NUMSQR	529
116
#define NUMCUBE 12167
117

118 119
char	   *strtable[STRTABLESIZE];
hashnode   *hashtable[HASHTABLESIZE];
120

121
static int	strtable_end = -1;	/* Tells us last occupied string space */
122 123 124 125 126

/*-
 * Basic information associated with each type.  This is used before
 * pg_type is created.
 *
127 128 129
 *		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.
130
 */
131 132
struct typinfo
{
133 134 135 136 137 138
	char		name[NAMEDATALEN];
	Oid			oid;
	Oid			elem;
	int16		len;
	Oid			inproc;
	Oid			outproc;
139 140 141
};

static struct typinfo Procid[] = {
142 143 144 145
	{"bool", 16, 0, 1, F_BOOLIN, F_BOOLOUT},
	{"bytea", 17, 0, -1, F_BYTEAIN, F_BYTEAOUT},
	{"char", 18, 0, 1, F_CHARIN, F_CHAROUT},
	{"name", 19, 0, NAMEDATALEN, F_NAMEIN, F_NAMEOUT},
146
	{"dummy", 20, 0, 16, 0, 0},
147 148 149 150 151 152 153 154 155 156 157 158 159 160
/*	  { "dt",		  20,	 0,  4, F_DTIN,			F_DTOUT}, */
	{"int2", 21, 0, 2, F_INT2IN, F_INT2OUT},
	{"int28", 22, 0, 16, F_INT28IN, F_INT28OUT},
	{"int4", 23, 0, 4, F_INT4IN, F_INT4OUT},
	{"regproc", 24, 0, 4, F_REGPROCIN, F_REGPROCOUT},
	{"text", 25, 0, -1, F_TEXTIN, F_TEXTOUT},
	{"oid", 26, 0, 4, F_INT4IN, F_INT4OUT},
	{"tid", 27, 0, 6, F_TIDIN, F_TIDOUT},
	{"xid", 28, 0, 5, F_XIDIN, F_XIDOUT},
	{"iid", 29, 0, 1, F_CIDIN, F_CIDOUT},
	{"oid8", 30, 0, 32, F_OID8IN, F_OID8OUT},
	{"smgr", 210, 0, 2, F_SMGRIN, F_SMGROUT},
	{"_int4", 1007, 23, -1, F_ARRAY_IN, F_ARRAY_OUT},
	{"_aclitem", 1034, 1033, -1, F_ARRAY_IN, F_ARRAY_OUT}
161 162
};

163
static int	n_types = sizeof(Procid) / sizeof(struct typinfo);
164

165 166
struct typmap
{								/* a hack */
167
	Oid			am_oid;
168
	TypeTupleFormData am_typ;
169 170
};

171 172 173
static struct typmap **Typ = (struct typmap **) NULL;
static struct typmap *Ap = (struct typmap *) NULL;

174 175
static int	Warnings = 0;
static char Blanks[MAXATTR];
176

177
static char *relname;			/* current relation name */
178

179
AttributeTupleForm attrtypes[MAXATTR];	/* points to attribute info */
180 181 182
static char *values[MAXATTR];	/* cooresponding attribute values */
int			numattr;			/* number of attributes for cur. rel */
extern int	fsyncOff;			/* do not fsync the database */
183

184
/* The test for HAVE_SIGSETJMP fails on Linux 2.0.x because the test
185 186 187
 *	explicitly disallows sigsetjmp being a #define, which is how it
 *	is declared in Linux. So, to avoid compiler warnings about
 *	sigsetjmp() being redefined, let's not redefine unless necessary.
188 189
 * - thomas 1997-12-27
 */
190

191 192
#if !defined(HAVE_SIGSETJMP) && !defined(sigsetjmp)
static jmp_buf Warn_restart;
193

194
#define sigsetjmp(x,y)	setjmp(x)
195
#define siglongjmp longjmp
196

197 198
#else
static sigjmp_buf Warn_restart;
199

200 201
#endif

202
int			DebugMode;
203 204 205
static GlobalMemory nogc = (GlobalMemory) NULL; /* special no-gc mem
												 * context */

206 207
extern int	optind;
extern char *optarg;
208 209

/*
210 211 212
 *	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.
213 214
 */

215 216
typedef struct _IndexList
{
217 218 219 220 221 222 223 224
	char	   *il_heap;
	char	   *il_ind;
	int			il_natts;
	AttrNumber *il_attnos;
	uint16		il_nparams;
	Datum	   *il_params;
	FuncIndexInfo *il_finfo;
	PredInfo   *il_predInfo;
225
	struct _IndexList *il_next;
226
} IndexList;
227 228

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

230
typedef void (*sig_func) ();
231 232


233 234 235


/* ----------------------------------------------------------------
236
 *						misc functions
237 238 239 240
 * ----------------------------------------------------------------
 */

/* ----------------
241
 *		error handling / abort routines
242 243
 * ----------------
 */
244 245
void
err_out(void)
246
{
247 248
	Warnings++;
	cleanup();
249 250 251 252 253 254
}

/* usage:
   usage help for the bootstrap backen
*/
static void
255
usage(void)
Marc G. Fournier's avatar
Marc G. Fournier committed
256
{
257 258 259 260 261 262 263 264
	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");

265
	proc_exit(1);
266 267
}

268 269 270 271


int
BootstrapMain(int argc, char *argv[])
272
/* ----------------------------------------------------------------
273 274 275 276
 *	 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.
277
 *
278 279 280
 *	 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
281 282 283
 * ----------------------------------------------------------------
 */
{
284 285 286 287 288 289
	int			i;
	int			portFd = -1;
	char	   *dbName;
	int			flag;
	int			override = 1;	/* use BootstrapProcessing or
								 * InitProcessing mode */
290

291 292
	extern int	optind;
	extern char *optarg;
293 294 295 296 297 298 299 300 301 302 303 304 305 306

	/* ----------------
	 *	initialize signal handlers
	 * ----------------
	 */
	pqsignal(SIGINT, (sig_func) die);
	pqsignal(SIGHUP, (sig_func) die);
	pqsignal(SIGTERM, (sig_func) die);

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

Bruce Momjian's avatar
Bruce Momjian committed
307
	MyProcPid = getpid();
308 309 310 311 312 313 314

	/* ----------------
	 *	process command arguments
	 * ----------------
	 */

	/* Set defaults, to be overriden by explicit options below */
315 316
	Quiet = false;
	Noversion = false;
317 318 319 320 321 322 323
	dbName = NULL;
	DataDir = getenv("PGDATA"); /* Null if no PGDATA variable */

	while ((flag = getopt(argc, argv, "D:dCOQP:F")) != EOF)
	{
		switch (flag)
		{
324 325 326 327
			case 'D':
				DataDir = optarg;
				break;
			case 'd':
328
				DebugMode = true;	/* print out debugging info while parsing */
329 330
				break;
			case 'C':
331
				Noversion = true;
332 333
				break;
			case 'F':
334
				fsyncOff = true;
335 336 337 338 339
				break;
			case 'O':
				override = true;
				break;
			case 'Q':
340
				Quiet = true;
341 342 343 344 345 346 347
				break;
			case 'P':			/* specify port */
				portFd = atoi(optarg);
				break;
			default:
				usage();
				break;
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
		}
	}							/* while */

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

	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]);
363
		proc_exit(1);
364 365 366 367 368 369 370 371 372
	}

	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);
373
			proc_exit(1);
374 375 376 377 378 379 380
		}
	}

	/* ----------------
	 *	initialize input fd
	 * ----------------
	 */
381
	if (IsUnderPostmaster && portFd < 0)
382 383
	{
		fputs("backend: failed, no -P option with -postmaster opt.\n", stderr);
384
		proc_exit(1);
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
	}

	/* ----------------
	 *	backend initialization
	 * ----------------
	 */
	SetProcessingMode((override) ? BootstrapProcessing : InitProcessing);
	InitPostgres(dbName);
	LockDisable(true);

	for (i = 0; i < MAXATTR; i++)
	{
		attrtypes[i] = (AttributeTupleForm) NULL;
		Blanks[i] = ' ';
	}
	for (i = 0; i < STRTABLESIZE; ++i)
		strtable[i] = NULL;
	for (i = 0; i < HASHTABLESIZE; ++i)
		hashtable[i] = NULL;

	/* ----------------
406
	 *	abort processing resumes here
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
	 * ----------------
	 */
	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;
434 435 436 437

}

/* ----------------------------------------------------------------
438
 *				MANUAL BACKEND INTERACTIVE INTERFACE COMMANDS
439 440 441 442
 * ----------------------------------------------------------------
 */

/* ----------------
443
 *		boot_openrel
444 445 446 447 448
 * ----------------
 */
void
boot_openrel(char *relname)
{
449
	int			i;
450
	struct typmap **app;
451 452 453
	Relation	rdesc;
	HeapScanDesc sdesc;
	HeapTuple	tup;
454

455 456
	if (strlen(relname) >= NAMEDATALEN - 1)
		relname[NAMEDATALEN - 1] = '\0';
457 458 459 460 461

	if (Typ == (struct typmap **) NULL)
	{
		StartPortalAllocMode(DefaultAllocMode, 0);
		rdesc = heap_openr(TypeRelationName);
462
		sdesc = heap_beginscan(rdesc, 0, SnapshotNow, 0, (ScanKey) NULL);
463 464 465 466 467 468
		for (i = 0; PointerIsValid(tup = heap_getnext(sdesc, 0, (Buffer *) NULL)); ++i);
		heap_endscan(sdesc);
		app = Typ = ALLOC(struct typmap *, i + 1);
		while (i-- > 0)
			*app++ = ALLOC(struct typmap, 1);
		*app = (struct typmap *) NULL;
469
		sdesc = heap_beginscan(rdesc, 0, SnapshotNow, 0, (ScanKey) NULL);
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
		app = Typ;
		while (PointerIsValid(tup = heap_getnext(sdesc, 0, (Buffer *) NULL)))
		{
			(*app)->am_oid = tup->t_oid;
			memmove((char *) &(*app++)->am_typ,
					(char *) GETSTRUCT(tup),
					sizeof((*app)->am_typ));
		}
		heap_endscan(sdesc);
		heap_close(rdesc);
		EndPortalAllocMode();
	}

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

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

	reldesc = heap_openr(relname);
	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)
			attrtypes[i]->attisset = get_attisset(reldesc->rd_id,
											 attrtypes[i]->attname.data);
		else
			attrtypes[i]->attisset = false;

		if (DebugMode)
		{
			AttributeTupleForm at = attrtypes[i];

			printf("create attribute %d name %s len %d num %d type %d\n",
				   i, at->attname.data, at->attlen, at->attnum,
				   at->atttypid
				);
			fflush(stdout);
		}
	}
524 525 526
}

/* ----------------
527
 *		closerel
528 529 530 531 532
 * ----------------
 */
void
closerel(char *name)
{
533 534 535 536 537
	if (name)
	{
		if (reldesc)
		{
			if (namestrcmp(RelationGetRelationName(reldesc), name) != 0)
538
				elog(ERROR, "closerel: close of '%s' when '%s' was expected",
539 540 541
					 name, relname ? relname : "(null)");
		}
		else
542
			elog(ERROR, "closerel: close of '%s' before any relation was opened",
543 544 545 546 547
				 name);

	}

	if (reldesc == NULL)
548
		elog(ERROR, "Warning: no opened relation to close.\n");
549 550 551 552 553 554 555
	else
	{
		if (!Quiet)
			printf("Amclose: relation %s.\n", relname ? relname : "(null)");
		heap_close(reldesc);
		reldesc = (Relation) NULL;
	}
556 557
}

558 559


560 561 562 563 564 565 566 567 568 569 570
/* ----------------
 * 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)
{
571 572
	int			attlen;
	int			t;
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

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

	t = gettype(type);
	if (attrtypes[attnum] == (AttributeTupleForm) NULL)
		attrtypes[attnum] = AllocateAttribute();
	if (Typ != (struct typmap **) NULL)
	{
		attrtypes[attnum]->atttypid = Ap->am_oid;
		namestrcpy(&attrtypes[attnum]->attname, name);
		if (!Quiet)
			printf("<%s %s> ", attrtypes[attnum]->attname.data, type);
		attrtypes[attnum]->attnum = 1 + attnum; /* fillatt */
		attlen = attrtypes[attnum]->attlen = Ap->am_typ.typlen;
		attrtypes[attnum]->attbyval = Ap->am_typ.typbyval;
	}
	else
	{
		attrtypes[attnum]->atttypid = Procid[t].oid;
		namestrcpy(&attrtypes[attnum]->attname, name);
		if (!Quiet)
			printf("<%s %s> ", attrtypes[attnum]->attname.data, type);
		attrtypes[attnum]->attnum = 1 + attnum; /* fillatt */
		attlen = attrtypes[attnum]->attlen = Procid[t].len;
		attrtypes[attnum]->attbyval = (attlen == 1) || (attlen == 2) || (attlen == 4);
	}
603
	attrtypes[attnum]->attcacheoff = -1;
Bruce Momjian's avatar
Bruce Momjian committed
604
	attrtypes[attnum]->atttypmod = -1;
605 606 607 608
}


/* ----------------
609 610
 *		InsertOneTuple
 *		assumes that 'oid' will not be zero.
611 612 613 614 615
 * ----------------
 */
void
InsertOneTuple(Oid objectid)
{
616 617
	HeapTuple	tuple;
	TupleDesc	tupDesc;
618

619
	int			i;
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

	if (DebugMode)
	{
		printf("InsertOneTuple oid %d, %d attrs\n", objectid, numattr);
		fflush(stdout);
	}

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

	if (objectid != (Oid) 0)
		tuple->t_oid = objectid;
	heap_insert(reldesc, tuple);
	pfree(tuple);
	if (DebugMode)
	{
		printf("End InsertOneTuple, objectid=%d\n", objectid);
		fflush(stdout);
	}

	/*
	 * Reset blanks for next tuple
	 */
	for (i = 0; i < numattr; i++)
		Blanks[i] = ' ';
646 647 648
}

/* ----------------
649
 *		InsertOneValue
650 651 652 653 654
 * ----------------
 */
void
InsertOneValue(Oid objectid, char *value, int i)
{
655 656
	int			typeindex;
	char	   *prt;
657 658 659 660 661 662 663 664 665 666 667 668
	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)
	{
669
		struct typmap *ap;
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713

		if (DebugMode)
			puts("Typ != NULL");
		app = Typ;
		while (*app && (*app)->am_oid != reldesc->rd_att->attrs[i]->atttypid)
			++app;
		ap = *app;
		if (ap == NULL)
		{
			printf("Unable to find atttypid in Typ list! %d\n",
				   reldesc->rd_att->attrs[i]->atttypid
				);
			Assert(0);
		}
		values[i] = fmgr(ap->am_typ.typinput,
						 value,
						 ap->am_typ.typelem,
						 -1);	/* shouldn't have char() or varchar()
								 * types during boostrapping but just to
								 * be safe */
		prt = fmgr(ap->am_typ.typoutput, values[i],
				   ap->am_typ.typelem);
		if (!Quiet)
			printf("%s ", prt);
		pfree(prt);
	}
	else
	{
		typeindex = attrtypes[i]->atttypid - FIRST_TYPE_OID;
		if (DebugMode)
			printf("Typ == NULL, typeindex = %d idx = %d\n", typeindex, i);
		values[i] = fmgr(Procid[typeindex].inproc, value,
						 Procid[typeindex].elem, -1);
		prt = fmgr(Procid[typeindex].outproc, values[i],
				   Procid[typeindex].elem);
		if (!Quiet)
			printf("%s ", prt);
		pfree(prt);
	}
	if (DebugMode)
	{
		puts("End InsertValue");
		fflush(stdout);
	}
714 715 716
}

/* ----------------
717
 *		InsertOneNull
718 719 720 721 722
 * ----------------
 */
void
InsertOneNull(int i)
{
723 724 725 726 727 728
	if (DebugMode)
		printf("Inserting null\n");
	if (i < 0 || i >= MAXATTR)
		elog(FATAL, "i out of range (too many attrs): %d\n", i);
	values[i] = (char *) NULL;
	Blanks[i] = 'n';
729 730 731 732
}

#define MORE_THAN_THE_NUMBER_OF_CATALOGS 256

733
static bool
734 735
BootstrapAlreadySeen(Oid id)
{
736 737 738 739
	static Oid	seenArray[MORE_THAN_THE_NUMBER_OF_CATALOGS];
	static int	nseen = 0;
	bool		seenthis;
	int			i;
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756

	seenthis = false;

	for (i = 0; i < nseen; i++)
	{
		if (seenArray[i] == id)
		{
			seenthis = true;
			break;
		}
	}
	if (!seenthis)
	{
		seenArray[nseen] = id;
		nseen++;
	}
	return (seenthis);
757 758 759
}

/* ----------------
760
 *		cleanup
761 762
 * ----------------
 */
763
static void
764 765
cleanup()
{
766
	static int	beenhere = 0;
767 768 769 770 771 772

	if (!beenhere)
		beenhere = 1;
	else
	{
		elog(FATAL, "Memory manager fault: cleanup called twice.\n", stderr);
773
		proc_exit(1);
774 775 776 777
	}
	if (reldesc != (Relation) NULL)
		heap_close(reldesc);
	CommitTransactionCommand();
778
	proc_exit(Warnings);
779 780 781
}

/* ----------------
782
 *		gettype
783 784
 * ----------------
 */
785
static int
786 787
gettype(char *type)
{
788 789 790 791
	int			i;
	Relation	rdesc;
	HeapScanDesc sdesc;
	HeapTuple	tup;
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
	struct typmap **app;

	if (Typ != (struct typmap **) NULL)
	{
		for (app = Typ; *app != (struct typmap *) NULL; app++)
		{
			if (strncmp((*app)->am_typ.typname.data, type, NAMEDATALEN) == 0)
			{
				Ap = *app;
				return ((*app)->am_oid);
			}
		}
	}
	else
	{
		for (i = 0; i <= n_types; i++)
		{
			if (strncmp(type, Procid[i].name, NAMEDATALEN) == 0)
				return (i);
		}
		if (DebugMode)
			printf("bootstrap.c: External Type: %s\n", type);
		rdesc = heap_openr(TypeRelationName);
815
		sdesc = heap_beginscan(rdesc, 0, SnapshotNow, 0, (ScanKey) NULL);
816 817 818 819 820 821 822 823
		i = 0;
		while (PointerIsValid(tup = heap_getnext(sdesc, 0, (Buffer *) NULL)))
			++i;
		heap_endscan(sdesc);
		app = Typ = ALLOC(struct typmap *, i + 1);
		while (i-- > 0)
			*app++ = ALLOC(struct typmap, 1);
		*app = (struct typmap *) NULL;
824
		sdesc = heap_beginscan(rdesc, 0, SnapshotNow, 0, (ScanKey) NULL);
825 826 827 828 829 830 831 832 833 834 835 836
		app = Typ;
		while (PointerIsValid(tup = heap_getnext(sdesc, 0, (Buffer *) NULL)))
		{
			(*app)->am_oid = tup->t_oid;
			memmove((char *) &(*app++)->am_typ,
					(char *) GETSTRUCT(tup),
					sizeof((*app)->am_typ));
		}
		heap_endscan(sdesc);
		heap_close(rdesc);
		return (gettype(type));
	}
837
	elog(ERROR, "Error: unknown type '%s'.\n", type);
838 839 840
	err_out();
	/* not reached, here to make compiler happy */
	return 0;
841 842 843
}

/* ----------------
844
 *		AllocateAttribute
845 846
 * ----------------
 */
847
static AttributeTupleForm		/* XXX */
848 849
AllocateAttribute()
{
850 851 852 853 854
	AttributeTupleForm attribute =
	(AttributeTupleForm) malloc(ATTRIBUTE_TUPLE_SIZE);

	if (!PointerIsValid(attribute))
		elog(FATAL, "AllocateAttribute: malloc failed");
Bruce Momjian's avatar
Bruce Momjian committed
855
	MemSet(attribute, 0, ATTRIBUTE_TUPLE_SIZE);
856 857

	return (attribute);
858 859 860
}

/* ----------------
861
 *		MapArrayTypeName
862
 * XXX arrays of "basetype" are always "_basetype".
863
 *	   this is an evil hack inherited from rel. 3.1.
864
 * XXX array dimension is thrown away because we
865 866 867 868
 *	   don't support fixed-dimension arrays.  again,
 *	   sickness from 3.1.
 *
 * the string passed in must have a '[' character in it
869 870 871 872 873
 *
 * the string returned is a pointer to static storage and should NOT
 * be freed by the CALLER.
 * ----------------
 */
874
char *
875 876
MapArrayTypeName(char *s)
{
877 878 879 880
	int			i,
				j;
	static char newStr[NAMEDATALEN];	/* array type names < NAMEDATALEN
										 * long */
881

882 883
	if (s == NULL || s[0] == '\0')
		return s;
884

885 886 887 888
	j = 1;
	newStr[0] = '_';
	for (i = 0; i < NAMEDATALEN - 1 && s[i] != '['; i++, j++)
		newStr[j] = s[i];
889

890 891 892
	newStr[j] = '\0';

	return newStr;
893 894 895
}

/* ----------------
896 897 898
 *		EnterString
 *		returns the string table position of the identifier
 *		passed to it.  We add it to the table if we can't find it.
899 900 901
 * ----------------
 */
int
902
EnterString(char *str)
903
{
904 905
	hashnode   *node;
	int			len;
906 907 908 909 910 911 912 913 914 915 916

	len = strlen(str);

	node = FindStr(str, len, 0);
	if (node)
		return (node->strnum);
	else
	{
		node = AddStr(str, len, 0);
		return (node->strnum);
	}
917 918 919
}

/* ----------------
920 921 922
 *		LexIDStr
 *		when given an idnum into the 'string-table' return the string
 *		associated with the idnum
923 924
 * ----------------
 */
925
char *
926
LexIDStr(int ident_num)
927
{
928 929
	return (strtable[ident_num]);
}
930 931 932


/* ----------------
933
 *		CompHash
934
 *
935 936 937 938
 *		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.
939 940
 * ----------------
 */
941
static int
942 943
CompHash(char *str, int len)
{
944
	int			result;
945 946 947 948 949

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

	return (result % HASHTABLESIZE);

950 951 952
}

/* ----------------
953
 *		FindStr
954
 *
955 956 957
 *		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.
958 959
 * ----------------
 */
960
static hashnode *
961
FindStr(char *str, int length, hashnode *mderef)
962
{
963
	hashnode   *node;
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981

	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]))
		{
			return (node);		/* no need to check */
		}
		else
			node = node->next;
	}
	/* Couldn't find it in the list */
	return (NULL);
982 983 984
}

/* ----------------
985
 *		AddStr
986
 *
987 988 989 990
 *		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.
991 992
 * ----------------
 */
993
static hashnode *
994 995
AddStr(char *str, int strlength, int mderef)
{
996 997 998 999 1000
	hashnode   *temp,
			   *trail,
			   *newnode;
	int			hashresult;
	int			len;
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 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

	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;
	}
	return (newnode);
1048 1049 1050 1051 1052
}



/*
1053 1054
 *	index_register() -- record an index that has been set up for building
 *						later.
1055
 *
1056 1057 1058 1059 1060
 *		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.
1061 1062 1063
 */
void
index_register(char *heap,
1064 1065
			   char *ind,
			   int natts,
Bruce Momjian's avatar
Bruce Momjian committed
1066
			   AttrNumber *attnos,
1067
			   uint16 nparams,
1068 1069 1070
			   Datum *params,
			   FuncIndexInfo *finfo,
			   PredInfo *predInfo)
1071
{
1072 1073 1074 1075
	Datum	   *v;
	IndexList  *newind;
	int			len;
	MemoryContext oldcxt;
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 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135

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

	if (nogc == (GlobalMemory) NULL)
		nogc = CreateGlobalMemory("BootstrapNoGC");

	oldcxt = MemoryContextSwitchTo((MemoryContext) nogc);

	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);
	memmove(newind->il_attnos, attnos, len);

	if ((newind->il_nparams = nparams) > 0)
	{
		v = newind->il_params = (Datum *) palloc(2 * nparams * sizeof(Datum));
		nparams *= 2;
		while (nparams-- > 0)
		{
			*v = (Datum) palloc(strlen((char *) (*params)) + 1);
			strcpy((char *) *v++, (char *) *params++);
		}
	}
	else
		newind->il_params = (Datum *) NULL;

	if (finfo != (FuncIndexInfo *) NULL)
	{
		newind->il_finfo = (FuncIndexInfo *) palloc(sizeof(FuncIndexInfo));
		memmove(newind->il_finfo, finfo, sizeof(FuncIndexInfo));
	}
	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;

	newind->il_next = ILHead;

	ILHead = newind;

	MemoryContextSwitchTo(oldcxt);
1136 1137 1138 1139 1140
}

void
build_indices()
{
1141 1142
	Relation	heap;
	Relation	ind;
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

	for (; ILHead != (IndexList *) NULL; ILHead = ILHead->il_next)
	{
		heap = heap_openr(ILHead->il_heap);
		ind = index_openr(ILHead->il_ind);
		index_build(heap, ind, ILHead->il_natts, ILHead->il_attnos,
				 ILHead->il_nparams, ILHead->il_params, ILHead->il_finfo,
					ILHead->il_predInfo);

		/*
		 * 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
		 * ghost tuple problem (see heap_replace).	To get around this we
		 * 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
		 */
		heap = heap_openr(ILHead->il_heap);

		if (!BootstrapAlreadySeen(heap->rd_id))
			UpdateStats(heap->rd_id, 0, true);
	}
1173
}