1 /*-------------------------------------------------------------------------
4 * routines to support running postgres in 'bootstrap' mode
5 * bootstrap mode is used to create the initial template database
7 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/bootstrap/bootstrap.c,v 1.155 2003/05/06 23:34:55 momjian Exp $
13 *-------------------------------------------------------------------------
25 #define BOOTSTRAP_INCLUDE /* mask out stuff in tcop/tcopprot.h */
27 #include "access/genam.h"
28 #include "access/heapam.h"
29 #include "access/xlog.h"
30 #include "bootstrap/bootstrap.h"
31 #include "catalog/catname.h"
32 #include "catalog/index.h"
33 #include "catalog/pg_type.h"
34 #include "executor/executor.h"
35 #include "libpq/pqsignal.h"
36 #include "miscadmin.h"
37 #include "storage/freespace.h"
38 #include "storage/ipc.h"
39 #include "storage/pg_shmem.h"
40 #include "storage/proc.h"
41 #include "tcop/tcopprot.h"
42 #include "utils/builtins.h"
43 #include "utils/fmgroids.h"
44 #include "utils/guc.h"
45 #include "utils/lsyscache.h"
46 #include "utils/relcache.h"
49 #define ALLOC(t, c) ((t *) calloc((unsigned)(c), sizeof(t)))
52 extern int Int_yyparse(void);
53 static hashnode *AddStr(char *str, int strlength, int mderef);
54 static Form_pg_attribute AllocateAttribute(void);
55 static bool BootstrapAlreadySeen(Oid id);
56 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);
66 Relation boot_reldesc; /* current relation descriptor */
69 * In the lexical analyzer, we need to get the reference number quickly from
70 * the string, and the string from the reference number. Thus we have
71 * as our data structure a hash table, where the hashing key taken from
72 * the particular string. The hash table is chained. One of the fields
73 * of the hash table node is an index into the array of character pointers.
74 * The unique index number that every string is assigned is simply the
75 * position of its string pointer in the array of string pointers.
78 #define STRTABLESIZE 10000
79 #define HASHTABLESIZE 503
81 /* Hash function numbers */
86 char *strtable[STRTABLESIZE];
87 hashnode *hashtable[HASHTABLESIZE];
89 static int strtable_end = -1; /* Tells us last occupied string space */
92 * Basic information associated with each type. This is used before
95 * XXX several of these input/output functions do catalog scans
96 * (e.g., F_REGPROCIN scans pg_proc). this obviously creates some
97 * order dependencies in the catalog creation process.
101 char name[NAMEDATALEN];
109 static struct typinfo Procid[] = {
110 {"bool", BOOLOID, 0, 1, F_BOOLIN, F_BOOLOUT},
111 {"bytea", BYTEAOID, 0, -1, F_BYTEAIN, F_BYTEAOUT},
112 {"char", CHAROID, 0, 1, F_CHARIN, F_CHAROUT},
113 {"name", NAMEOID, 0, NAMEDATALEN, F_NAMEIN, F_NAMEOUT},
114 {"int2", INT2OID, 0, 2, F_INT2IN, F_INT2OUT},
115 {"int2vector", INT2VECTOROID, 0, INDEX_MAX_KEYS * 2, F_INT2VECTORIN, F_INT2VECTOROUT},
116 {"int4", INT4OID, 0, 4, F_INT4IN, F_INT4OUT},
117 {"regproc", REGPROCOID, 0, 4, F_REGPROCIN, F_REGPROCOUT},
118 {"regclass", REGCLASSOID, 0, 4, F_REGCLASSIN, F_REGCLASSOUT},
119 {"regtype", REGTYPEOID, 0, 4, F_REGTYPEIN, F_REGTYPEOUT},
120 {"text", TEXTOID, 0, -1, F_TEXTIN, F_TEXTOUT},
121 {"oid", OIDOID, 0, 4, F_OIDIN, F_OIDOUT},
122 {"tid", TIDOID, 0, 6, F_TIDIN, F_TIDOUT},
123 {"xid", XIDOID, 0, 4, F_XIDIN, F_XIDOUT},
124 {"cid", CIDOID, 0, 4, F_CIDIN, F_CIDOUT},
125 {"oidvector", OIDVECTOROID, 0, INDEX_MAX_KEYS * 4, F_OIDVECTORIN, F_OIDVECTOROUT},
126 {"smgr", 210, 0, 2, F_SMGRIN, F_SMGROUT},
127 {"_int4", 1007, INT4OID, -1, F_ARRAY_IN, F_ARRAY_OUT},
128 {"_aclitem", 1034, 1033, -1, F_ARRAY_IN, F_ARRAY_OUT}
131 static int n_types = sizeof(Procid) / sizeof(struct typinfo);
136 FormData_pg_type am_typ;
139 static struct typmap **Typ = (struct typmap **) NULL;
140 static struct typmap *Ap = (struct typmap *) NULL;
142 static int Warnings = 0;
143 static char Blanks[MAXATTR];
145 static char *relname; /* current relation name */
147 Form_pg_attribute attrtypes[MAXATTR]; /* points to attribute info */
148 static Datum values[MAXATTR]; /* corresponding attribute values */
149 int numattr; /* number of attributes for cur. rel */
151 static MemoryContext nogc = NULL; /* special no-gc mem context */
157 * At bootstrap time, we first declare all the indices to be built, and
158 * then build them. The IndexList structure stores enough information
159 * to allow us to build the indices after they've been declared.
162 typedef struct _IndexList
167 struct _IndexList *il_next;
170 static IndexList *ILHead = (IndexList *) NULL;
173 /* ----------------------------------------------------------------
175 * ----------------------------------------------------------------
179 * error handling / abort routines
190 usage help for the bootstrap backen
197 " postgres -boot [-d level] [-D datadir] [-F] [-o file] [-x num] dbname\n"
198 " -d 1-5 debug mode\n"
199 " -D datadir data directory\n"
200 " -F turn off fsync\n"
201 " -o file send debug output to file\n"
202 " -x num internal use\n"));
210 BootstrapMain(int argc, char *argv[])
211 /* ----------------------------------------------------------------
212 * The main loop for handling the backend in bootstrap mode
213 * the bootstrap mode is used to initialize the template database
214 * the bootstrap backend doesn't speak SQL, but instead expects
215 * commands in a special bootstrap language.
217 * The arguments passed in to BootstrapMain are the run-time arguments
218 * without the argument '-boot', the caller is required to have
219 * removed -boot from the run-time args
220 * ----------------------------------------------------------------
226 int xlogop = BS_XLOG_NOP;
227 char *potential_DataDir = NULL;
233 MyProcPid = getpid();
236 * Fire up essential subsystems: error and memory management
238 * If we are running under the postmaster, this is done already.
240 if (!IsUnderPostmaster /* when exec || ExecBackend */)
244 * process command arguments
247 /* Set defaults, to be overriden by explicit options below */
249 if (!IsUnderPostmaster /* when exec || ExecBackend*/)
251 InitializeGUCOptions();
252 potential_DataDir = getenv("PGDATA"); /* Null if no PGDATA
256 while ((flag = getopt(argc, argv, "B:d:D:Fo:p:x:")) != -1)
261 potential_DataDir = optarg;
265 /* Turn on debugging for the bootstrap process. */
266 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
268 sprintf(debugstr, "debug%s", optarg);
269 SetConfigOption("log_min_messages", debugstr,
270 PGC_POSTMASTER, PGC_S_ARGV);
271 SetConfigOption("client_min_messages", debugstr,
272 PGC_POSTMASTER, PGC_S_ARGV);
278 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
281 StrNCpy(OutputFileName, optarg, MAXPGPATH);
284 xlogop = atoi(optarg);
288 /* indicates fork from postmaster */
291 sscanf(optarg, "%d,", &UsedShmemSegID);
292 p = strchr(optarg, ',');
294 dbname = strdup(p+1);
296 dbname = strdup(optarg);
301 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
309 if (!dbname && argc - optind == 1)
311 dbname = argv[optind];
314 if (!dbname || argc != optind)
318 if (IsUnderPostmaster && ExecBackend && MyProc /* ordinary backend */)
320 AttachSharedMemoryAndSemaphores();
323 if (!IsUnderPostmaster /* when exec || ExecBackend*/)
325 if (!potential_DataDir)
328 gettext("%s does not know where to find the database system data.\n"
329 "You must specify the directory that contains the database system\n"
330 "either by specifying the -D invocation option or by setting the\n"
331 "PGDATA environment variable.\n\n"),
335 SetDataDir(potential_DataDir);
338 /* Validate we have been given a reasonable-looking DataDir */
340 ValidatePgVersion(DataDir);
343 read_nondefault_variables();
346 if (IsUnderPostmaster)
349 * Properly accept or ignore signals the postmaster might send us
351 pqsignal(SIGHUP, SIG_IGN);
352 pqsignal(SIGINT, SIG_IGN); /* ignore query-cancel */
353 pqsignal(SIGTERM, die);
354 pqsignal(SIGQUIT, quickdie);
355 pqsignal(SIGALRM, SIG_IGN);
356 pqsignal(SIGPIPE, SIG_IGN);
357 pqsignal(SIGUSR1, SIG_IGN);
358 pqsignal(SIGUSR2, SIG_IGN);
361 * Reset some signals that are accepted by postmaster but not here
363 pqsignal(SIGCHLD, SIG_DFL);
364 pqsignal(SIGTTIN, SIG_DFL);
365 pqsignal(SIGTTOU, SIG_DFL);
366 pqsignal(SIGCONT, SIG_DFL);
367 pqsignal(SIGWINCH, SIG_DFL);
370 * Unblock signals (they were blocked when the postmaster forked
373 PG_SETMASK(&UnBlockSig);
377 /* Set up appropriately for interactive use */
378 pqsignal(SIGHUP, die);
379 pqsignal(SIGINT, die);
380 pqsignal(SIGTERM, die);
381 pqsignal(SIGQUIT, die);
384 * Create lockfile for data directory.
386 if (!CreateDataDirLockFile(DataDir, false))
390 SetProcessingMode(BootstrapProcessing);
391 IgnoreSystemIndexes(true);
397 if (IsUnderPostmaster)
398 InitDummyProcess(); /* needed to get LWLocks */
403 SetProcessingMode(NormalProcessing);
411 case BS_XLOG_BOOTSTRAP:
416 case BS_XLOG_CHECKPOINT:
418 CreateCheckPoint(false, false);
419 SetSavedRedoRecPtr(); /* pass redo ptr back to
421 proc_exit(0); /* done */
423 case BS_XLOG_STARTUP:
426 proc_exit(0); /* done */
428 case BS_XLOG_SHUTDOWN:
431 proc_exit(0); /* done */
434 elog(PANIC, "Unsupported XLOG op %d", xlogop);
438 SetProcessingMode(BootstrapProcessing);
441 * backend initialization
443 InitPostgres(dbname, NULL);
445 for (i = 0; i < MAXATTR; i++)
447 attrtypes[i] = (Form_pg_attribute) NULL;
450 for (i = 0; i < STRTABLESIZE; ++i)
452 for (i = 0; i < HASHTABLESIZE; ++i)
456 * abort processing resumes here
458 if (sigsetjmp(Warn_restart, 1) != 0)
461 AbortCurrentTransaction();
469 * the sed script boot.sed renamed yyparse to Int_yyparse for the
470 * bootstrap parser to avoid conflicts with the normal SQL parser
474 SetProcessingMode(NormalProcessing);
475 CreateCheckPoint(true, true);
476 SetProcessingMode(BootstrapProcessing);
478 /* clean up processing */
479 StartTransactionCommand(true);
482 /* not reached, here to make compiler happy */
487 /* ----------------------------------------------------------------
488 * MANUAL BACKEND INTERACTIVE INTERFACE COMMANDS
489 * ----------------------------------------------------------------
497 boot_openrel(char *relname)
505 if (strlen(relname) >= NAMEDATALEN - 1)
506 relname[NAMEDATALEN - 1] = '\0';
508 if (Typ == (struct typmap **) NULL)
510 rel = heap_openr(TypeRelationName, NoLock);
511 scan = heap_beginscan(rel, SnapshotNow, 0, (ScanKey) NULL);
513 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
516 app = Typ = ALLOC(struct typmap *, i + 1);
518 *app++ = ALLOC(struct typmap, 1);
519 *app = (struct typmap *) NULL;
520 scan = heap_beginscan(rel, SnapshotNow, 0, (ScanKey) NULL);
522 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
524 (*app)->am_oid = HeapTupleGetOid(tup);
525 memcpy((char *) &(*app)->am_typ,
526 (char *) GETSTRUCT(tup),
527 sizeof((*app)->am_typ));
531 heap_close(rel, NoLock);
534 if (boot_reldesc != NULL)
537 elog(DEBUG3, "open relation %s, attrsize %d", relname ? relname : "(null)",
538 (int) ATTRIBUTE_TUPLE_SIZE);
540 boot_reldesc = heap_openr(relname, NoLock);
541 numattr = boot_reldesc->rd_rel->relnatts;
542 for (i = 0; i < numattr; i++)
544 if (attrtypes[i] == NULL)
545 attrtypes[i] = AllocateAttribute();
546 memmove((char *) attrtypes[i],
547 (char *) boot_reldesc->rd_att->attrs[i],
548 ATTRIBUTE_TUPLE_SIZE);
551 Form_pg_attribute at = attrtypes[i];
553 elog(DEBUG3, "create attribute %d name %s len %d num %d type %u",
554 i, NameStr(at->attname), at->attlen, at->attnum,
571 if (strcmp(RelationGetRelationName(boot_reldesc), name) != 0)
572 elog(ERROR, "closerel: close of '%s' when '%s' was expected",
573 name, relname ? relname : "(null)");
576 elog(ERROR, "closerel: close of '%s' before any relation was opened",
580 if (boot_reldesc == NULL)
581 elog(ERROR, "no open relation to close");
584 elog(DEBUG3, "close relation %s", relname ? relname : "(null)");
585 heap_close(boot_reldesc, NoLock);
586 boot_reldesc = (Relation) NULL;
595 * define a <field,type> pair
596 * if there are n fields in a relation to be created, this routine
597 * will be called n times
601 DefineAttr(char *name, char *type, int attnum)
606 if (boot_reldesc != NULL)
608 elog(LOG, "warning: no open relations allowed with 'create' command");
612 if (attrtypes[attnum] == (Form_pg_attribute) NULL)
613 attrtypes[attnum] = AllocateAttribute();
614 MemSet(attrtypes[attnum], 0, ATTRIBUTE_TUPLE_SIZE);
616 namestrcpy(&attrtypes[attnum]->attname, name);
617 elog(DEBUG3, "column %s %s", NameStr(attrtypes[attnum]->attname), type);
618 attrtypes[attnum]->attnum = attnum + 1; /* fillatt */
620 typeoid = gettype(type);
622 if (Typ != (struct typmap **) NULL)
624 attrtypes[attnum]->atttypid = Ap->am_oid;
625 attlen = attrtypes[attnum]->attlen = Ap->am_typ.typlen;
626 attrtypes[attnum]->attbyval = Ap->am_typ.typbyval;
627 attrtypes[attnum]->attstorage = Ap->am_typ.typstorage;
628 attrtypes[attnum]->attalign = Ap->am_typ.typalign;
632 attrtypes[attnum]->atttypid = Procid[typeoid].oid;
633 attlen = attrtypes[attnum]->attlen = Procid[typeoid].len;
636 * Cheat like mad to fill in these items from the length only.
637 * This only has to work for types that appear in Procid[].
642 attrtypes[attnum]->attbyval = true;
643 attrtypes[attnum]->attstorage = 'p';
644 attrtypes[attnum]->attalign = 'c';
647 attrtypes[attnum]->attbyval = true;
648 attrtypes[attnum]->attstorage = 'p';
649 attrtypes[attnum]->attalign = 's';
652 attrtypes[attnum]->attbyval = true;
653 attrtypes[attnum]->attstorage = 'p';
654 attrtypes[attnum]->attalign = 'i';
657 attrtypes[attnum]->attbyval = false;
658 attrtypes[attnum]->attstorage = 'x';
659 attrtypes[attnum]->attalign = 'i';
662 /* TID and fixed-length arrays, such as oidvector */
663 attrtypes[attnum]->attbyval = false;
664 attrtypes[attnum]->attstorage = 'p';
665 attrtypes[attnum]->attalign = 'i';
669 attrtypes[attnum]->attcacheoff = -1;
670 attrtypes[attnum]->atttypmod = -1;
671 attrtypes[attnum]->attislocal = true;
674 * Mark as "not null" if type is fixed-width and prior columns are
675 * too. This corresponds to case where column can be accessed directly
676 * via C struct declaration.
682 for (i = 0; i < attnum; i++)
684 if (attrtypes[i]->attlen <= 0)
688 attrtypes[attnum]->attnotnull = true;
696 * If objectid is not zero, it is a specific OID to assign to the tuple.
697 * Otherwise, an OID will be assigned (if necessary) by heap_insert.
701 InsertOneTuple(Oid objectid)
707 elog(DEBUG3, "inserting row oid %u, %d columns", objectid, numattr);
709 tupDesc = CreateTupleDesc(numattr,
710 RelationGetForm(boot_reldesc)->relhasoids,
712 tuple = heap_formtuple(tupDesc, values, Blanks);
713 if (objectid != (Oid) 0)
714 HeapTupleSetOid(tuple, objectid);
715 pfree(tupDesc); /* just free's tupDesc, not the attrtypes */
717 simple_heap_insert(boot_reldesc, tuple);
718 heap_freetuple(tuple);
719 elog(DEBUG3, "row inserted");
722 * Reset blanks for next tuple
724 for (i = 0; i < numattr; i++)
733 InsertOneValue(char *value, int i)
739 AssertArg(i >= 0 || i < MAXATTR);
741 elog(DEBUG3, "inserting column %d value '%s'", i, value);
743 if (Typ != (struct typmap **) NULL)
747 elog(DEBUG3, "Typ != NULL");
749 while (*app && (*app)->am_oid != boot_reldesc->rd_att->attrs[i]->atttypid)
754 elog(FATAL, "unable to find atttypid %u in Typ list",
755 boot_reldesc->rd_att->attrs[i]->atttypid);
757 values[i] = OidFunctionCall3(ap->am_typ.typinput,
758 CStringGetDatum(value),
759 ObjectIdGetDatum(ap->am_typ.typelem),
761 prt = DatumGetCString(OidFunctionCall3(ap->am_typ.typoutput,
763 ObjectIdGetDatum(ap->am_typ.typelem),
765 elog(DEBUG3, " -> %s", prt);
770 for (typeindex = 0; typeindex < n_types; typeindex++)
772 if (Procid[typeindex].oid == attrtypes[i]->atttypid)
775 if (typeindex >= n_types)
776 elog(ERROR, "type oid %u not found", attrtypes[i]->atttypid);
777 elog(DEBUG3, "Typ == NULL, typeindex = %u", typeindex);
778 values[i] = OidFunctionCall3(Procid[typeindex].inproc,
779 CStringGetDatum(value),
780 ObjectIdGetDatum(Procid[typeindex].elem),
782 prt = DatumGetCString(OidFunctionCall3(Procid[typeindex].outproc,
784 ObjectIdGetDatum(Procid[typeindex].elem),
786 elog(DEBUG3, " -> %s", prt);
789 elog(DEBUG3, "inserted");
799 elog(DEBUG3, "inserting column %d NULL", i);
800 Assert(i >= 0 || i < MAXATTR);
801 values[i] = PointerGetDatum(NULL);
805 #define MORE_THAN_THE_NUMBER_OF_CATALOGS 256
808 BootstrapAlreadySeen(Oid id)
810 static Oid seenArray[MORE_THAN_THE_NUMBER_OF_CATALOGS];
811 static int nseen = 0;
817 for (i = 0; i < nseen; i++)
819 if (seenArray[i] == id)
827 seenArray[nseen] = id;
840 static int beenhere = 0;
846 elog(FATAL, "Memory manager fault: cleanup called twice.\n");
849 if (boot_reldesc != NULL)
851 CommitTransactionCommand(true);
858 * NB: this is really ugly; it will return an integer index into Procid[],
859 * and not an OID at all, until the first reference to a type not known in
860 * Procid[]. At that point it will read and cache pg_type in the Typ array,
861 * and subsequently return a real OID (and set the global pointer Ap to
862 * point at the found row in Typ). So caller must check whether Typ is
863 * still NULL to determine what the return value is!
875 if (Typ != (struct typmap **) NULL)
877 for (app = Typ; *app != (struct typmap *) NULL; app++)
879 if (strncmp(NameStr((*app)->am_typ.typname), type, NAMEDATALEN) == 0)
882 return (*app)->am_oid;
888 for (i = 0; i < n_types; i++)
890 if (strncmp(type, Procid[i].name, NAMEDATALEN) == 0)
893 elog(DEBUG3, "external type: %s", type);
894 rel = heap_openr(TypeRelationName, NoLock);
895 scan = heap_beginscan(rel, SnapshotNow, 0, (ScanKey) NULL);
897 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
900 app = Typ = ALLOC(struct typmap *, i + 1);
902 *app++ = ALLOC(struct typmap, 1);
903 *app = (struct typmap *) NULL;
904 scan = heap_beginscan(rel, SnapshotNow, 0, (ScanKey) NULL);
906 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
908 (*app)->am_oid = HeapTupleGetOid(tup);
909 memmove((char *) &(*app++)->am_typ,
910 (char *) GETSTRUCT(tup),
911 sizeof((*app)->am_typ));
914 heap_close(rel, NoLock);
915 return gettype(type);
917 elog(ERROR, "Error: unknown type '%s'.\n", type);
919 /* not reached, here to make compiler happy */
927 static Form_pg_attribute
928 AllocateAttribute(void)
930 Form_pg_attribute attribute = (Form_pg_attribute) malloc(ATTRIBUTE_TUPLE_SIZE);
932 if (!PointerIsValid(attribute))
933 elog(FATAL, "AllocateAttribute: malloc failed");
934 MemSet(attribute, 0, ATTRIBUTE_TUPLE_SIZE);
941 * XXX arrays of "basetype" are always "_basetype".
942 * this is an evil hack inherited from rel. 3.1.
943 * XXX array dimension is thrown away because we
944 * don't support fixed-dimension arrays. again,
947 * the string passed in must have a '[' character in it
949 * the string returned is a pointer to static storage and should NOT
950 * be freed by the CALLER.
954 MapArrayTypeName(char *s)
958 static char newStr[NAMEDATALEN]; /* array type names < NAMEDATALEN
961 if (s == NULL || s[0] == '\0')
966 for (i = 0; i < NAMEDATALEN - 1 && s[i] != '['; i++, j++)
976 * returns the string table position of the identifier
977 * passed to it. We add it to the table if we can't find it.
981 EnterString(char *str)
988 node = FindStr(str, len, 0);
993 node = AddStr(str, len, 0);
1000 * when given an idnum into the 'string-table' return the string
1001 * associated with the idnum
1005 LexIDStr(int ident_num)
1007 return strtable[ident_num];
1014 * Compute a hash function for a given string. We look at the first,
1015 * the last, and the middle character of a string to try to get spread
1016 * the strings out. The function is rather arbitrary, except that we
1017 * are mod'ing by a prime number.
1021 CompHash(char *str, int len)
1025 result = (NUM * str[0] + NUMSQR * str[len - 1] + NUMCUBE * str[(len - 1) / 2]);
1027 return result % HASHTABLESIZE;
1034 * This routine looks for the specified string in the hash
1035 * table. It returns a pointer to the hash node found,
1036 * or NULL if the string is not in the table.
1040 FindStr(char *str, int length, hashnode *mderef)
1044 node = hashtable[CompHash(str, length)];
1045 while (node != NULL)
1048 * We must differentiate between string constants that might have
1049 * the same value as a identifier and the identifier itself.
1051 if (!strcmp(str, strtable[node->strnum]))
1053 return node; /* no need to check */
1058 /* Couldn't find it in the list */
1065 * This function adds the specified string, along with its associated
1066 * data, to the hash table and the string table. We return the node
1067 * so that the calling routine can find out the unique id that AddStr
1068 * has assigned to this string.
1072 AddStr(char *str, int strlength, int mderef)
1080 if (++strtable_end == STRTABLESIZE)
1082 /* Error, string table overflow, so we Punt */
1084 "There are too many string constants and identifiers for the compiler to handle.");
1090 * Some of the utilites (eg, define type, create relation) assume that
1091 * the string they're passed is a NAMEDATALEN. We get array bound
1092 * read violations from purify if we don't allocate at least
1093 * NAMEDATALEN bytes for strings of this sort. Because we're lazy, we
1094 * allocate at least NAMEDATALEN bytes all the time.
1097 if ((len = strlength + 1) < NAMEDATALEN)
1100 strtable[strtable_end] = malloc((unsigned) len);
1101 strcpy(strtable[strtable_end], str);
1103 /* Now put a node in the hash table */
1105 newnode = (hashnode *) malloc(sizeof(hashnode) * 1);
1106 newnode->strnum = strtable_end;
1107 newnode->next = NULL;
1109 /* Find out where it goes */
1111 hashresult = CompHash(str, strlength);
1112 if (hashtable[hashresult] == NULL)
1113 hashtable[hashresult] = newnode;
1115 { /* There is something in the list */
1116 trail = hashtable[hashresult];
1118 while (temp != NULL)
1123 trail->next = newnode;
1131 * index_register() -- record an index that has been set up for building
1134 * At bootstrap time, we define a bunch of indices on system catalogs.
1135 * We postpone actually building the indices until just before we're
1136 * finished with initialization, however. This is because more classes
1137 * and indices may be defined, and we want to be sure that all of them
1138 * are present in the index.
1141 index_register(Oid heap,
1143 IndexInfo *indexInfo)
1146 MemoryContext oldcxt;
1149 * XXX mao 10/31/92 -- don't gc index reldescs, associated info at
1150 * bootstrap time. we'll declare the indices now, but want to create
1155 nogc = AllocSetContextCreate((MemoryContext) NULL,
1157 ALLOCSET_DEFAULT_MINSIZE,
1158 ALLOCSET_DEFAULT_INITSIZE,
1159 ALLOCSET_DEFAULT_MAXSIZE);
1161 oldcxt = MemoryContextSwitchTo(nogc);
1163 newind = (IndexList *) palloc(sizeof(IndexList));
1164 newind->il_heap = heap;
1165 newind->il_ind = ind;
1166 newind->il_info = (IndexInfo *) palloc(sizeof(IndexInfo));
1168 memcpy(newind->il_info, indexInfo, sizeof(IndexInfo));
1169 /* predicate will likely be null, but may as well copy it */
1170 newind->il_info->ii_Predicate = (List *)
1171 copyObject(indexInfo->ii_Predicate);
1172 newind->il_info->ii_PredicateState = NIL;
1174 newind->il_next = ILHead;
1177 MemoryContextSwitchTo(oldcxt);
1183 for (; ILHead != (IndexList *) NULL; ILHead = ILHead->il_next)
1188 heap = heap_open(ILHead->il_heap, NoLock);
1189 ind = index_open(ILHead->il_ind);
1190 index_build(heap, ind, ILHead->il_info);
1193 * In normal processing mode, index_build would close the heap and
1194 * index, but in bootstrap mode it will not.
1198 * All of the rest of this routine is needed only because in
1199 * bootstrap processing we don't increment xact id's. The normal
1200 * DefineIndex code replaces a pg_class tuple with updated info
1201 * including the relhasindex flag (which we need to have updated).
1202 * Unfortunately, there are always two indices defined on each
1203 * catalog causing us to update the same pg_class tuple twice for
1204 * each catalog getting an index during bootstrap resulting in the
1205 * ghost tuple problem (see heap_update). To get around this we
1206 * change the relhasindex field ourselves in this routine keeping
1207 * track of what catalogs we already changed so that we don't
1208 * modify those tuples twice. The normal mechanism for updating
1209 * pg_class is disabled during bootstrap.
1213 if (!BootstrapAlreadySeen(RelationGetRelid(heap)))
1214 UpdateStats(RelationGetRelid(heap), 0);
1216 /* XXX Probably we ought to close the heap and index here? */