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-2003, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/bootstrap/bootstrap.c,v 1.185 2004/06/24 21:02:24 tgl Exp $
13 *-------------------------------------------------------------------------
24 #define BOOTSTRAP_INCLUDE /* mask out stuff in tcop/tcopprot.h */
26 #include "access/genam.h"
27 #include "access/heapam.h"
28 #include "access/xlog.h"
29 #include "bootstrap/bootstrap.h"
30 #include "catalog/catname.h"
31 #include "catalog/index.h"
32 #include "catalog/pg_type.h"
33 #include "executor/executor.h"
34 #include "libpq/pqsignal.h"
35 #include "miscadmin.h"
36 #include "postmaster/bgwriter.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/ps_status.h"
47 #include "utils/relcache.h"
50 #define ALLOC(t, c) ((t *) calloc((unsigned)(c), sizeof(t)))
52 extern int Int_yyparse(void);
53 static void usage(void);
54 static void bootstrap_signals(void);
55 static hashnode *AddStr(char *str, int strlength, int mderef);
56 static Form_pg_attribute AllocateAttribute(void);
57 static bool BootstrapAlreadySeen(Oid id);
58 static int CompHash(char *str, int len);
59 static hashnode *FindStr(char *str, int length, hashnode *mderef);
60 static Oid gettype(char *type);
61 static void cleanup(void);
68 Relation boot_reldesc; /* current relation descriptor */
71 * In the lexical analyzer, we need to get the reference number quickly from
72 * the string, and the string from the reference number. Thus we have
73 * as our data structure a hash table, where the hashing key taken from
74 * the particular string. The hash table is chained. One of the fields
75 * of the hash table node is an index into the array of character pointers.
76 * The unique index number that every string is assigned is simply the
77 * position of its string pointer in the array of string pointers.
80 #define STRTABLESIZE 10000
81 #define HASHTABLESIZE 503
83 /* Hash function numbers */
88 char *strtable[STRTABLESIZE];
89 hashnode *hashtable[HASHTABLESIZE];
91 static int strtable_end = -1; /* Tells us last occupied string space */
94 * Basic information associated with each type. This is used before
97 * XXX several of these input/output functions do catalog scans
98 * (e.g., F_REGPROCIN scans pg_proc). this obviously creates some
99 * order dependencies in the catalog creation process.
103 char name[NAMEDATALEN];
114 static const struct typinfo TypInfo[] = {
115 {"bool", BOOLOID, 0, 1, true, 'c', 'p',
116 F_BOOLIN, F_BOOLOUT},
117 {"bytea", BYTEAOID, 0, -1, false, 'i', 'x',
118 F_BYTEAIN, F_BYTEAOUT},
119 {"char", CHAROID, 0, 1, true, 'c', 'p',
120 F_CHARIN, F_CHAROUT},
121 {"name", NAMEOID, CHAROID, NAMEDATALEN, false, 'i', 'p',
122 F_NAMEIN, F_NAMEOUT},
123 {"int2", INT2OID, 0, 2, true, 's', 'p',
124 F_INT2IN, F_INT2OUT},
125 {"int4", INT4OID, 0, 4, true, 'i', 'p',
126 F_INT4IN, F_INT4OUT},
127 {"regproc", REGPROCOID, 0, 4, true, 'i', 'p',
128 F_REGPROCIN, F_REGPROCOUT},
129 {"regclass", REGCLASSOID, 0, 4, true, 'i', 'p',
130 F_REGCLASSIN, F_REGCLASSOUT},
131 {"regtype", REGTYPEOID, 0, 4, true, 'i', 'p',
132 F_REGTYPEIN, F_REGTYPEOUT},
133 {"text", TEXTOID, 0, -1, false, 'i', 'x',
134 F_TEXTIN, F_TEXTOUT},
135 {"oid", OIDOID, 0, 4, true, 'i', 'p',
137 {"tid", TIDOID, 0, 6, false, 's', 'p',
139 {"xid", XIDOID, 0, 4, true, 'i', 'p',
141 {"cid", CIDOID, 0, 4, true, 'i', 'p',
143 {"int2vector", INT2VECTOROID, INT2OID, INDEX_MAX_KEYS * 2, false, 's', 'p',
144 F_INT2VECTORIN, F_INT2VECTOROUT},
145 {"oidvector", OIDVECTOROID, OIDOID, INDEX_MAX_KEYS * 4, false, 'i', 'p',
146 F_OIDVECTORIN, F_OIDVECTOROUT},
147 {"_int4", INT4ARRAYOID, INT4OID, -1, false, 'i', 'x',
148 F_ARRAY_IN, F_ARRAY_OUT},
149 {"_text", 1009, TEXTOID, -1, false, 'i', 'x',
150 F_ARRAY_IN, F_ARRAY_OUT},
151 {"_aclitem", 1034, ACLITEMOID, -1, false, 'i', 'x',
152 F_ARRAY_IN, F_ARRAY_OUT}
155 static const int n_types = sizeof(TypInfo) / sizeof(struct typinfo);
160 FormData_pg_type am_typ;
163 static struct typmap **Typ = NULL;
164 static struct typmap *Ap = NULL;
166 static int Warnings = 0;
167 static char Blanks[MAXATTR];
169 static char *relname; /* current relation name */
171 Form_pg_attribute attrtypes[MAXATTR]; /* points to attribute info */
172 static Datum values[MAXATTR]; /* corresponding attribute values */
173 int numattr; /* number of attributes for cur. rel */
175 static MemoryContext nogc = NULL; /* special no-gc mem context */
181 * At bootstrap time, we first declare all the indices to be built, and
182 * then build them. The IndexList structure stores enough information
183 * to allow us to build the indices after they've been declared.
186 typedef struct _IndexList
191 struct _IndexList *il_next;
194 static IndexList *ILHead = NULL;
198 * The main entry point for running the backend in bootstrap mode
200 * The bootstrap mode is used to initialize the template database.
201 * The bootstrap backend doesn't speak SQL, but instead expects
202 * commands in a special bootstrap language.
204 * For historical reasons, BootstrapMain is also used as the control
205 * routine for non-backend subprocesses launched by the postmaster,
206 * such as startup and shutdown.
209 BootstrapMain(int argc, char *argv[])
214 int xlogop = BS_XLOG_NOP;
215 char *potential_DataDir = NULL;
220 MyProcPid = getpid();
223 * Fire up essential subsystems: error and memory management
225 * If we are running under the postmaster, this is done already.
227 if (!IsUnderPostmaster)
231 * process command arguments
234 /* Set defaults, to be overriden by explicit options below */
236 if (!IsUnderPostmaster)
238 InitializeGUCOptions();
239 potential_DataDir = getenv("PGDATA"); /* Null if no PGDATA
243 /* Ignore the initial -boot argument, if present */
244 if (argc > 1 && strcmp(argv[1], "-boot") == 0)
250 while ((flag = getopt(argc, argv, "B:c:d:D:Fo:p:x:-:")) != -1)
255 potential_DataDir = optarg;
259 /* Turn on debugging for the bootstrap process. */
260 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
262 sprintf(debugstr, "debug%s", optarg);
263 SetConfigOption("log_min_messages", debugstr,
264 PGC_POSTMASTER, PGC_S_ARGV);
265 SetConfigOption("client_min_messages", debugstr,
266 PGC_POSTMASTER, PGC_S_ARGV);
272 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
275 StrNCpy(OutputFileName, optarg, MAXPGPATH);
278 xlogop = atoi(optarg);
281 dbname = strdup(optarg);
284 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
292 ParseLongOption(optarg, &name, &value);
297 (errcode(ERRCODE_SYNTAX_ERROR),
298 errmsg("--%s requires a value",
302 (errcode(ERRCODE_SYNTAX_ERROR),
303 errmsg("-c %s requires a value",
307 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
319 if (!dbname && argc - optind == 1)
321 dbname = argv[optind];
324 if (!dbname || argc != optind)
327 if (!IsUnderPostmaster)
329 if (!potential_DataDir)
331 write_stderr("%s does not know where to find the database system data.\n"
332 "You must specify the directory that contains the database system\n"
333 "either by specifying the -D invocation option or by setting the\n"
334 "PGDATA environment variable.\n",
338 SetDataDir(potential_DataDir);
341 /* Validate we have been given a reasonable-looking DataDir */
343 ValidatePgVersion(DataDir);
346 * Identify myself via ps
348 if (IsUnderPostmaster)
354 case BS_XLOG_STARTUP:
355 statmsg = "startup process";
357 case BS_XLOG_BGWRITER:
358 statmsg = "writer process";
361 statmsg = "??? process";
364 init_ps_display(statmsg, "", "");
368 /* Acquire configuration parameters, unless inherited from postmaster */
369 if (!IsUnderPostmaster)
371 ProcessConfigFile(PGC_POSTMASTER);
373 /* If timezone is not set, determine what the OS uses */
374 pg_timezone_initialize();
377 /* If standalone, create lockfile for data directory */
378 if (!IsUnderPostmaster)
379 CreateDataDirLockFile(DataDir, false);
381 SetProcessingMode(BootstrapProcessing);
382 IgnoreSystemIndexes(true);
388 /* needed to get LWLocks */
389 if (IsUnderPostmaster)
393 case BS_XLOG_BGWRITER:
394 InitDummyProcess(DUMMY_PROC_BGWRITER);
398 InitDummyProcess(DUMMY_PROC_DEFAULT);
406 SetProcessingMode(NormalProcessing);
414 case BS_XLOG_BOOTSTRAP:
420 case BS_XLOG_STARTUP:
424 proc_exit(0); /* startup done */
426 case BS_XLOG_BGWRITER:
427 /* don't set signals, bgwriter has its own agenda */
429 BackgroundWriterMain();
430 proc_exit(1); /* should never return */
433 elog(PANIC, "unrecognized XLOG op: %d", xlogop);
437 SetProcessingMode(BootstrapProcessing);
440 * backend initialization
442 InitPostgres(dbname, NULL);
445 * In NOP mode, all we really want to do is create shared memory and
446 * semaphores (just to prove we can do it with the current GUC
447 * settings). So, quit now.
449 if (xlogop == BS_XLOG_NOP)
452 /* Initialize stuff for bootstrap-file processing */
453 for (i = 0; i < MAXATTR; i++)
458 for (i = 0; i < STRTABLESIZE; ++i)
460 for (i = 0; i < HASHTABLESIZE; ++i)
464 * abort processing resumes here (this is probably dead code?)
466 if (sigsetjmp(Warn_restart, 1) != 0)
469 AbortCurrentTransaction();
473 * Process bootstrap input.
475 * the sed script boot.sed renamed yyparse to Int_yyparse for the
476 * bootstrap parser to avoid conflicts with the normal SQL parser
480 /* Perform a checkpoint to ensure everything's down to disk */
481 SetProcessingMode(NormalProcessing);
482 CreateCheckPoint(true, true);
483 SetProcessingMode(BootstrapProcessing);
485 /* Clean up and exit */
486 StartTransactionCommand();
489 /* not reached, here to make compiler happy */
494 /* ----------------------------------------------------------------
496 * ----------------------------------------------------------------
500 * usage help for the bootstrap backend
505 write_stderr("Usage:\n"
506 " postgres -boot [OPTION]... DBNAME\n"
507 " -c NAME=VALUE set run-time parameter\n"
508 " -d 1-5 debug level\n"
509 " -D datadir data directory\n"
510 " -F turn off fsync\n"
511 " -o file send debug output to file\n"
512 " -x num internal use\n");
518 * Set up signal handling for a bootstrap process
521 bootstrap_signals(void)
523 if (IsUnderPostmaster)
526 * Properly accept or ignore signals the postmaster might send us
528 pqsignal(SIGHUP, SIG_IGN);
529 pqsignal(SIGINT, SIG_IGN); /* ignore query-cancel */
530 pqsignal(SIGTERM, die);
531 pqsignal(SIGQUIT, quickdie);
532 pqsignal(SIGALRM, SIG_IGN);
533 pqsignal(SIGPIPE, SIG_IGN);
534 pqsignal(SIGUSR1, SIG_IGN);
535 pqsignal(SIGUSR2, SIG_IGN);
538 * Reset some signals that are accepted by postmaster but not here
540 pqsignal(SIGCHLD, SIG_DFL);
541 pqsignal(SIGTTIN, SIG_DFL);
542 pqsignal(SIGTTOU, SIG_DFL);
543 pqsignal(SIGCONT, SIG_DFL);
544 pqsignal(SIGWINCH, SIG_DFL);
547 * Unblock signals (they were blocked when the postmaster forked
550 PG_SETMASK(&UnBlockSig);
554 /* Set up appropriately for interactive use */
555 pqsignal(SIGHUP, die);
556 pqsignal(SIGINT, die);
557 pqsignal(SIGTERM, die);
558 pqsignal(SIGQUIT, die);
563 * error handling / abort routines
574 /* ----------------------------------------------------------------
575 * MANUAL BACKEND INTERACTIVE INTERFACE COMMANDS
576 * ----------------------------------------------------------------
584 boot_openrel(char *relname)
592 if (strlen(relname) >= NAMEDATALEN - 1)
593 relname[NAMEDATALEN - 1] = '\0';
597 rel = heap_openr(TypeRelationName, NoLock);
598 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
600 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
603 app = Typ = ALLOC(struct typmap *, i + 1);
605 *app++ = ALLOC(struct typmap, 1);
607 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
609 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
611 (*app)->am_oid = HeapTupleGetOid(tup);
612 memcpy((char *) &(*app)->am_typ,
613 (char *) GETSTRUCT(tup),
614 sizeof((*app)->am_typ));
618 heap_close(rel, NoLock);
621 if (boot_reldesc != NULL)
624 elog(DEBUG4, "open relation %s, attrsize %d",
625 relname ? relname : "(null)",
626 (int) ATTRIBUTE_TUPLE_SIZE);
628 boot_reldesc = heap_openr(relname, NoLock);
629 numattr = boot_reldesc->rd_rel->relnatts;
630 for (i = 0; i < numattr; i++)
632 if (attrtypes[i] == NULL)
633 attrtypes[i] = AllocateAttribute();
634 memmove((char *) attrtypes[i],
635 (char *) boot_reldesc->rd_att->attrs[i],
636 ATTRIBUTE_TUPLE_SIZE);
639 Form_pg_attribute at = attrtypes[i];
641 elog(DEBUG4, "create attribute %d name %s len %d num %d type %u",
642 i, NameStr(at->attname), at->attlen, at->attnum,
659 if (strcmp(RelationGetRelationName(boot_reldesc), name) != 0)
660 elog(ERROR, "close of %s when %s was expected",
661 name, relname ? relname : "(null)");
664 elog(ERROR, "close of %s before any relation was opened",
668 if (boot_reldesc == NULL)
669 elog(ERROR, "no open relation to close");
672 elog(DEBUG4, "close relation %s", relname ? relname : "(null)");
673 heap_close(boot_reldesc, NoLock);
683 * define a <field,type> pair
684 * if there are n fields in a relation to be created, this routine
685 * will be called n times
689 DefineAttr(char *name, char *type, int attnum)
694 if (boot_reldesc != NULL)
696 elog(WARNING, "no open relations allowed with CREATE command");
700 if (attrtypes[attnum] == NULL)
701 attrtypes[attnum] = AllocateAttribute();
702 MemSet(attrtypes[attnum], 0, ATTRIBUTE_TUPLE_SIZE);
704 namestrcpy(&attrtypes[attnum]->attname, name);
705 elog(DEBUG4, "column %s %s", NameStr(attrtypes[attnum]->attname), type);
706 attrtypes[attnum]->attnum = attnum + 1; /* fillatt */
708 typeoid = gettype(type);
712 attrtypes[attnum]->atttypid = Ap->am_oid;
713 attlen = attrtypes[attnum]->attlen = Ap->am_typ.typlen;
714 attrtypes[attnum]->attbyval = Ap->am_typ.typbyval;
715 attrtypes[attnum]->attstorage = Ap->am_typ.typstorage;
716 attrtypes[attnum]->attalign = Ap->am_typ.typalign;
717 /* if an array type, assume 1-dimensional attribute */
718 if (Ap->am_typ.typelem != InvalidOid && Ap->am_typ.typlen < 0)
719 attrtypes[attnum]->attndims = 1;
721 attrtypes[attnum]->attndims = 0;
725 attrtypes[attnum]->atttypid = TypInfo[typeoid].oid;
726 attlen = attrtypes[attnum]->attlen = TypInfo[typeoid].len;
727 attrtypes[attnum]->attbyval = TypInfo[typeoid].byval;
728 attrtypes[attnum]->attstorage = TypInfo[typeoid].storage;
729 attrtypes[attnum]->attalign = TypInfo[typeoid].align;
730 /* if an array type, assume 1-dimensional attribute */
731 if (TypInfo[typeoid].elem != InvalidOid && attlen < 0)
732 attrtypes[attnum]->attndims = 1;
734 attrtypes[attnum]->attndims = 0;
737 attrtypes[attnum]->attstattarget = -1;
738 attrtypes[attnum]->attcacheoff = -1;
739 attrtypes[attnum]->atttypmod = -1;
740 attrtypes[attnum]->attislocal = true;
743 * Mark as "not null" if type is fixed-width and prior columns are
744 * too. This corresponds to case where column can be accessed directly
745 * via C struct declaration.
751 for (i = 0; i < attnum; i++)
753 if (attrtypes[i]->attlen <= 0)
757 attrtypes[attnum]->attnotnull = true;
765 * If objectid is not zero, it is a specific OID to assign to the tuple.
766 * Otherwise, an OID will be assigned (if necessary) by heap_insert.
770 InsertOneTuple(Oid objectid)
776 elog(DEBUG4, "inserting row oid %u, %d columns", objectid, numattr);
778 tupDesc = CreateTupleDesc(numattr,
779 RelationGetForm(boot_reldesc)->relhasoids,
781 tuple = heap_formtuple(tupDesc, values, Blanks);
782 if (objectid != (Oid) 0)
783 HeapTupleSetOid(tuple, objectid);
784 pfree(tupDesc); /* just free's tupDesc, not the attrtypes */
786 simple_heap_insert(boot_reldesc, tuple);
787 heap_freetuple(tuple);
788 elog(DEBUG4, "row inserted");
791 * Reset blanks for next tuple
793 for (i = 0; i < numattr; i++)
802 InsertOneValue(char *value, int i)
810 AssertArg(i >= 0 || i < MAXATTR);
812 elog(DEBUG4, "inserting column %d value \"%s\"", i, value);
819 elog(DEBUG5, "Typ != NULL");
820 typoid = boot_reldesc->rd_att->attrs[i]->atttypid;
822 while (*app && (*app)->am_oid != typoid)
826 elog(ERROR, "could not find atttypid %u in Typ list", typoid);
828 /* XXX this should match getTypeIOParam() */
829 if (ap->am_typ.typtype == 'c')
832 typioparam = ap->am_typ.typelem;
834 typinput = ap->am_typ.typinput;
835 typoutput = ap->am_typ.typoutput;
841 /* XXX why is typoid determined differently in this path? */
842 typoid = attrtypes[i]->atttypid;
843 for (typeindex = 0; typeindex < n_types; typeindex++)
845 if (TypInfo[typeindex].oid == typoid)
848 if (typeindex >= n_types)
849 elog(ERROR, "type oid %u not found", typoid);
850 elog(DEBUG5, "Typ == NULL, typeindex = %u", typeindex);
852 /* XXX there are no composite types in TypInfo */
853 typioparam = TypInfo[typeindex].elem;
855 typinput = TypInfo[typeindex].inproc;
856 typoutput = TypInfo[typeindex].outproc;
859 values[i] = OidFunctionCall3(typinput,
860 CStringGetDatum(value),
861 ObjectIdGetDatum(typioparam),
863 prt = DatumGetCString(OidFunctionCall3(typoutput,
865 ObjectIdGetDatum(typioparam),
867 elog(DEBUG4, "inserted -> %s", prt);
878 elog(DEBUG4, "inserting column %d NULL", i);
879 Assert(i >= 0 || i < MAXATTR);
880 values[i] = PointerGetDatum(NULL);
884 #define MORE_THAN_THE_NUMBER_OF_CATALOGS 256
887 BootstrapAlreadySeen(Oid id)
889 static Oid seenArray[MORE_THAN_THE_NUMBER_OF_CATALOGS];
890 static int nseen = 0;
896 for (i = 0; i < nseen; i++)
898 if (seenArray[i] == id)
906 seenArray[nseen] = id;
919 static int beenhere = 0;
925 elog(FATAL, "cleanup called twice");
928 if (boot_reldesc != NULL)
930 CommitTransactionCommand();
931 proc_exit(Warnings ? 1 : 0);
937 * NB: this is really ugly; it will return an integer index into TypInfo[],
938 * and not an OID at all, until the first reference to a type not known in
939 * TypInfo[]. At that point it will read and cache pg_type in the Typ array,
940 * and subsequently return a real OID (and set the global pointer Ap to
941 * point at the found row in Typ). So caller must check whether Typ is
942 * still NULL to determine what the return value is!
956 for (app = Typ; *app != NULL; app++)
958 if (strncmp(NameStr((*app)->am_typ.typname), type, NAMEDATALEN) == 0)
961 return (*app)->am_oid;
967 for (i = 0; i < n_types; i++)
969 if (strncmp(type, TypInfo[i].name, NAMEDATALEN) == 0)
972 elog(DEBUG4, "external type: %s", type);
973 rel = heap_openr(TypeRelationName, NoLock);
974 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
976 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
979 app = Typ = ALLOC(struct typmap *, i + 1);
981 *app++ = ALLOC(struct typmap, 1);
983 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
985 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
987 (*app)->am_oid = HeapTupleGetOid(tup);
988 memmove((char *) &(*app++)->am_typ,
989 (char *) GETSTRUCT(tup),
990 sizeof((*app)->am_typ));
993 heap_close(rel, NoLock);
994 return gettype(type);
996 elog(ERROR, "unrecognized type \"%s\"", type);
998 /* not reached, here to make compiler happy */
1006 static Form_pg_attribute
1007 AllocateAttribute(void)
1009 Form_pg_attribute attribute = (Form_pg_attribute) malloc(ATTRIBUTE_TUPLE_SIZE);
1011 if (!PointerIsValid(attribute))
1012 elog(FATAL, "out of memory");
1013 MemSet(attribute, 0, ATTRIBUTE_TUPLE_SIZE);
1020 * XXX arrays of "basetype" are always "_basetype".
1021 * this is an evil hack inherited from rel. 3.1.
1022 * XXX array dimension is thrown away because we
1023 * don't support fixed-dimension arrays. again,
1024 * sickness from 3.1.
1026 * the string passed in must have a '[' character in it
1028 * the string returned is a pointer to static storage and should NOT
1029 * be freed by the CALLER.
1033 MapArrayTypeName(char *s)
1037 static char newStr[NAMEDATALEN]; /* array type names < NAMEDATALEN
1040 if (s == NULL || s[0] == '\0')
1045 for (i = 0; i < NAMEDATALEN - 1 && s[i] != '['; i++, j++)
1055 * returns the string table position of the identifier
1056 * passed to it. We add it to the table if we can't find it.
1060 EnterString(char *str)
1067 node = FindStr(str, len, 0);
1069 return node->strnum;
1072 node = AddStr(str, len, 0);
1073 return node->strnum;
1079 * when given an idnum into the 'string-table' return the string
1080 * associated with the idnum
1084 LexIDStr(int ident_num)
1086 return strtable[ident_num];
1093 * Compute a hash function for a given string. We look at the first,
1094 * the last, and the middle character of a string to try to get spread
1095 * the strings out. The function is rather arbitrary, except that we
1096 * are mod'ing by a prime number.
1100 CompHash(char *str, int len)
1104 result = (NUM * str[0] + NUMSQR * str[len - 1] + NUMCUBE * str[(len - 1) / 2]);
1106 return result % HASHTABLESIZE;
1113 * This routine looks for the specified string in the hash
1114 * table. It returns a pointer to the hash node found,
1115 * or NULL if the string is not in the table.
1119 FindStr(char *str, int length, hashnode *mderef)
1123 node = hashtable[CompHash(str, length)];
1124 while (node != NULL)
1127 * We must differentiate between string constants that might have
1128 * the same value as a identifier and the identifier itself.
1130 if (!strcmp(str, strtable[node->strnum]))
1132 return node; /* no need to check */
1137 /* Couldn't find it in the list */
1144 * This function adds the specified string, along with its associated
1145 * data, to the hash table and the string table. We return the node
1146 * so that the calling routine can find out the unique id that AddStr
1147 * has assigned to this string.
1151 AddStr(char *str, int strlength, int mderef)
1159 if (++strtable_end >= STRTABLESIZE)
1160 elog(FATAL, "bootstrap string table overflow");
1163 * Some of the utilites (eg, define type, create relation) assume that
1164 * the string they're passed is a NAMEDATALEN. We get array bound
1165 * read violations from purify if we don't allocate at least
1166 * NAMEDATALEN bytes for strings of this sort. Because we're lazy, we
1167 * allocate at least NAMEDATALEN bytes all the time.
1170 if ((len = strlength + 1) < NAMEDATALEN)
1173 strtable[strtable_end] = malloc((unsigned) len);
1174 strcpy(strtable[strtable_end], str);
1176 /* Now put a node in the hash table */
1178 newnode = (hashnode *) malloc(sizeof(hashnode) * 1);
1179 newnode->strnum = strtable_end;
1180 newnode->next = NULL;
1182 /* Find out where it goes */
1184 hashresult = CompHash(str, strlength);
1185 if (hashtable[hashresult] == NULL)
1186 hashtable[hashresult] = newnode;
1188 { /* There is something in the list */
1189 trail = hashtable[hashresult];
1191 while (temp != NULL)
1196 trail->next = newnode;
1204 * index_register() -- record an index that has been set up for building
1207 * At bootstrap time, we define a bunch of indices on system catalogs.
1208 * We postpone actually building the indices until just before we're
1209 * finished with initialization, however. This is because more classes
1210 * and indices may be defined, and we want to be sure that all of them
1211 * are present in the index.
1214 index_register(Oid heap,
1216 IndexInfo *indexInfo)
1219 MemoryContext oldcxt;
1222 * XXX mao 10/31/92 -- don't gc index reldescs, associated info at
1223 * bootstrap time. we'll declare the indices now, but want to create
1228 nogc = AllocSetContextCreate(NULL,
1230 ALLOCSET_DEFAULT_MINSIZE,
1231 ALLOCSET_DEFAULT_INITSIZE,
1232 ALLOCSET_DEFAULT_MAXSIZE);
1234 oldcxt = MemoryContextSwitchTo(nogc);
1236 newind = (IndexList *) palloc(sizeof(IndexList));
1237 newind->il_heap = heap;
1238 newind->il_ind = ind;
1239 newind->il_info = (IndexInfo *) palloc(sizeof(IndexInfo));
1241 memcpy(newind->il_info, indexInfo, sizeof(IndexInfo));
1242 /* expressions will likely be null, but may as well copy it */
1243 newind->il_info->ii_Expressions = (List *)
1244 copyObject(indexInfo->ii_Expressions);
1245 newind->il_info->ii_ExpressionsState = NIL;
1246 /* predicate will likely be null, but may as well copy it */
1247 newind->il_info->ii_Predicate = (List *)
1248 copyObject(indexInfo->ii_Predicate);
1249 newind->il_info->ii_PredicateState = NIL;
1251 newind->il_next = ILHead;
1254 MemoryContextSwitchTo(oldcxt);
1260 for (; ILHead != NULL; ILHead = ILHead->il_next)
1265 heap = heap_open(ILHead->il_heap, NoLock);
1266 ind = index_open(ILHead->il_ind);
1267 index_build(heap, ind, ILHead->il_info);
1270 * In normal processing mode, index_build would close the heap and
1271 * index, but in bootstrap mode it will not.
1275 * All of the rest of this routine is needed only because in
1276 * bootstrap processing we don't increment xact id's. The normal
1277 * DefineIndex code replaces a pg_class tuple with updated info
1278 * including the relhasindex flag (which we need to have updated).
1279 * Unfortunately, there are always two indices defined on each
1280 * catalog causing us to update the same pg_class tuple twice for
1281 * each catalog getting an index during bootstrap resulting in the
1282 * ghost tuple problem (see heap_update). To get around this we
1283 * change the relhasindex field ourselves in this routine keeping
1284 * track of what catalogs we already changed so that we don't
1285 * modify those tuples twice. The normal mechanism for updating
1286 * pg_class is disabled during bootstrap.
1290 if (!BootstrapAlreadySeen(RelationGetRelid(heap)))
1291 UpdateStats(RelationGetRelid(heap), 0);
1293 /* XXX Probably we ought to close the heap and index here? */