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.188 2004/07/21 20:22:58 momjian 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 "postmaster/pg_autovacuum.h"
38 #include "storage/freespace.h"
39 #include "storage/ipc.h"
40 #include "storage/pg_shmem.h"
41 #include "storage/proc.h"
42 #include "tcop/tcopprot.h"
43 #include "utils/builtins.h"
44 #include "utils/fmgroids.h"
45 #include "utils/guc.h"
46 #include "utils/lsyscache.h"
47 #include "utils/ps_status.h"
48 #include "utils/relcache.h"
51 #define ALLOC(t, c) ((t *) calloc((unsigned)(c), sizeof(t)))
53 extern int Int_yyparse(void);
54 static void usage(void);
55 static void bootstrap_signals(void);
56 static hashnode *AddStr(char *str, int strlength, int mderef);
57 static Form_pg_attribute AllocateAttribute(void);
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 *userPGDATA = 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 userPGDATA = getenv("PGDATA"); /* Null if no PGDATA variable */
242 /* Ignore the initial -boot argument, if present */
243 if (argc > 1 && strcmp(argv[1], "-boot") == 0)
249 while ((flag = getopt(argc, argv, "B:c:d:D:Fo:p:x:-:")) != -1)
258 /* Turn on debugging for the bootstrap process. */
259 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
261 sprintf(debugstr, "debug%s", optarg);
262 SetConfigOption("log_min_messages", debugstr,
263 PGC_POSTMASTER, PGC_S_ARGV);
264 SetConfigOption("client_min_messages", debugstr,
265 PGC_POSTMASTER, PGC_S_ARGV);
271 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
274 StrNCpy(OutputFileName, optarg, MAXPGPATH);
277 xlogop = atoi(optarg);
280 dbname = strdup(optarg);
283 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
291 ParseLongOption(optarg, &name, &value);
296 (errcode(ERRCODE_SYNTAX_ERROR),
297 errmsg("--%s requires a value",
301 (errcode(ERRCODE_SYNTAX_ERROR),
302 errmsg("-c %s requires a value",
306 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
318 if (!dbname && argc - optind == 1)
320 dbname = argv[optind];
323 if (!dbname || argc != optind)
326 if (!IsUnderPostmaster)
330 write_stderr("%s does not know where to find the database system data.\n"
331 "You must specify the directory that contains the database system\n"
332 "either by specifying the -D invocation option or by setting the\n"
333 "PGDATA environment variable.\n",
337 SetDataDir(userPGDATA);
340 /* Validate we have been given a reasonable-looking DataDir */
342 ValidatePgVersion(DataDir);
345 * Identify myself via ps
347 if (IsUnderPostmaster)
353 case BS_XLOG_STARTUP:
354 statmsg = "startup process";
356 case BS_XLOG_BGWRITER:
357 statmsg = "writer process";
359 case BS_XLOG_AUTOVAC:
360 statmsg = "auto vacuum process";
363 statmsg = "??? process";
366 init_ps_display(statmsg, "", "");
370 /* Acquire configuration parameters, unless inherited from postmaster */
371 if (!IsUnderPostmaster)
373 ProcessConfigFile(PGC_POSTMASTER);
375 /* If timezone is not set, determine what the OS uses */
376 pg_timezone_initialize();
379 /* If standalone, create lockfile for data directory */
380 if (!IsUnderPostmaster)
381 CreateDataDirLockFile(DataDir, false);
383 SetProcessingMode(BootstrapProcessing);
384 IgnoreSystemIndexes(true);
390 /* needed to get LWLocks */
391 if (IsUnderPostmaster)
395 case BS_XLOG_BGWRITER:
396 InitDummyProcess(DUMMY_PROC_BGWRITER);
398 case BS_XLOG_AUTOVAC:
399 InitDummyProcess(DUMMY_PROC_AUTOVAC);
403 InitDummyProcess(DUMMY_PROC_DEFAULT);
411 SetProcessingMode(NormalProcessing);
419 case BS_XLOG_BOOTSTRAP:
425 case BS_XLOG_STARTUP:
429 proc_exit(0); /* startup done */
431 case BS_XLOG_BGWRITER:
432 /* don't set signals, bgwriter has its own agenda */
434 BackgroundWriterMain();
435 proc_exit(1); /* should never return */
437 case BS_XLOG_AUTOVAC:
438 /* don't set signals, autovac has its own agenda */
441 proc_exit(1); /* should never return */
444 elog(PANIC, "unrecognized XLOG op: %d", xlogop);
448 SetProcessingMode(BootstrapProcessing);
451 * backend initialization
453 InitPostgres(dbname, NULL);
456 * In NOP mode, all we really want to do is create shared memory and
457 * semaphores (just to prove we can do it with the current GUC
458 * settings). So, quit now.
460 if (xlogop == BS_XLOG_NOP)
463 /* Initialize stuff for bootstrap-file processing */
464 for (i = 0; i < MAXATTR; i++)
469 for (i = 0; i < STRTABLESIZE; ++i)
471 for (i = 0; i < HASHTABLESIZE; ++i)
475 * abort processing resumes here (this is probably dead code?)
477 if (sigsetjmp(Warn_restart, 1) != 0)
480 AbortCurrentTransaction();
484 * Process bootstrap input.
486 * the sed script boot.sed renamed yyparse to Int_yyparse for the
487 * bootstrap parser to avoid conflicts with the normal SQL parser
491 /* Perform a checkpoint to ensure everything's down to disk */
492 SetProcessingMode(NormalProcessing);
493 CreateCheckPoint(true, true);
494 SetProcessingMode(BootstrapProcessing);
496 /* Clean up and exit */
497 StartTransactionCommand();
500 /* not reached, here to make compiler happy */
505 /* ----------------------------------------------------------------
507 * ----------------------------------------------------------------
511 * usage help for the bootstrap backend
516 write_stderr("Usage:\n"
517 " postgres -boot [OPTION]... DBNAME\n"
518 " -c NAME=VALUE set run-time parameter\n"
519 " -d 1-5 debug level\n"
520 " -D datadir data directory\n"
521 " -F turn off fsync\n"
522 " -o file send debug output to file\n"
523 " -x num internal use\n");
529 * Set up signal handling for a bootstrap process
532 bootstrap_signals(void)
534 if (IsUnderPostmaster)
537 * Properly accept or ignore signals the postmaster might send us
539 pqsignal(SIGHUP, SIG_IGN);
540 pqsignal(SIGINT, SIG_IGN); /* ignore query-cancel */
541 pqsignal(SIGTERM, die);
542 pqsignal(SIGQUIT, quickdie);
543 pqsignal(SIGALRM, SIG_IGN);
544 pqsignal(SIGPIPE, SIG_IGN);
545 pqsignal(SIGUSR1, SIG_IGN);
546 pqsignal(SIGUSR2, SIG_IGN);
549 * Reset some signals that are accepted by postmaster but not here
551 pqsignal(SIGCHLD, SIG_DFL);
552 pqsignal(SIGTTIN, SIG_DFL);
553 pqsignal(SIGTTOU, SIG_DFL);
554 pqsignal(SIGCONT, SIG_DFL);
555 pqsignal(SIGWINCH, SIG_DFL);
558 * Unblock signals (they were blocked when the postmaster forked
561 PG_SETMASK(&UnBlockSig);
565 /* Set up appropriately for interactive use */
566 pqsignal(SIGHUP, die);
567 pqsignal(SIGINT, die);
568 pqsignal(SIGTERM, die);
569 pqsignal(SIGQUIT, die);
574 * error handling / abort routines
585 /* ----------------------------------------------------------------
586 * MANUAL BACKEND INTERACTIVE INTERFACE COMMANDS
587 * ----------------------------------------------------------------
595 boot_openrel(char *relname)
603 if (strlen(relname) >= NAMEDATALEN - 1)
604 relname[NAMEDATALEN - 1] = '\0';
608 rel = heap_openr(TypeRelationName, NoLock);
609 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
611 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
614 app = Typ = ALLOC(struct typmap *, i + 1);
616 *app++ = ALLOC(struct typmap, 1);
618 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
620 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
622 (*app)->am_oid = HeapTupleGetOid(tup);
623 memcpy((char *) &(*app)->am_typ,
624 (char *) GETSTRUCT(tup),
625 sizeof((*app)->am_typ));
629 heap_close(rel, NoLock);
632 if (boot_reldesc != NULL)
635 elog(DEBUG4, "open relation %s, attrsize %d",
636 relname ? relname : "(null)",
637 (int) ATTRIBUTE_TUPLE_SIZE);
639 boot_reldesc = heap_openr(relname, NoLock);
640 numattr = boot_reldesc->rd_rel->relnatts;
641 for (i = 0; i < numattr; i++)
643 if (attrtypes[i] == NULL)
644 attrtypes[i] = AllocateAttribute();
645 memmove((char *) attrtypes[i],
646 (char *) boot_reldesc->rd_att->attrs[i],
647 ATTRIBUTE_TUPLE_SIZE);
650 Form_pg_attribute at = attrtypes[i];
652 elog(DEBUG4, "create attribute %d name %s len %d num %d type %u",
653 i, NameStr(at->attname), at->attlen, at->attnum,
670 if (strcmp(RelationGetRelationName(boot_reldesc), name) != 0)
671 elog(ERROR, "close of %s when %s was expected",
672 name, relname ? relname : "(null)");
675 elog(ERROR, "close of %s before any relation was opened",
679 if (boot_reldesc == NULL)
680 elog(ERROR, "no open relation to close");
683 elog(DEBUG4, "close relation %s", relname ? relname : "(null)");
684 heap_close(boot_reldesc, NoLock);
694 * define a <field,type> pair
695 * if there are n fields in a relation to be created, this routine
696 * will be called n times
700 DefineAttr(char *name, char *type, int attnum)
705 if (boot_reldesc != NULL)
707 elog(WARNING, "no open relations allowed with CREATE command");
711 if (attrtypes[attnum] == NULL)
712 attrtypes[attnum] = AllocateAttribute();
713 MemSet(attrtypes[attnum], 0, ATTRIBUTE_TUPLE_SIZE);
715 namestrcpy(&attrtypes[attnum]->attname, name);
716 elog(DEBUG4, "column %s %s", NameStr(attrtypes[attnum]->attname), type);
717 attrtypes[attnum]->attnum = attnum + 1; /* fillatt */
719 typeoid = gettype(type);
723 attrtypes[attnum]->atttypid = Ap->am_oid;
724 attlen = attrtypes[attnum]->attlen = Ap->am_typ.typlen;
725 attrtypes[attnum]->attbyval = Ap->am_typ.typbyval;
726 attrtypes[attnum]->attstorage = Ap->am_typ.typstorage;
727 attrtypes[attnum]->attalign = Ap->am_typ.typalign;
728 /* if an array type, assume 1-dimensional attribute */
729 if (Ap->am_typ.typelem != InvalidOid && Ap->am_typ.typlen < 0)
730 attrtypes[attnum]->attndims = 1;
732 attrtypes[attnum]->attndims = 0;
736 attrtypes[attnum]->atttypid = TypInfo[typeoid].oid;
737 attlen = attrtypes[attnum]->attlen = TypInfo[typeoid].len;
738 attrtypes[attnum]->attbyval = TypInfo[typeoid].byval;
739 attrtypes[attnum]->attstorage = TypInfo[typeoid].storage;
740 attrtypes[attnum]->attalign = TypInfo[typeoid].align;
741 /* if an array type, assume 1-dimensional attribute */
742 if (TypInfo[typeoid].elem != InvalidOid && attlen < 0)
743 attrtypes[attnum]->attndims = 1;
745 attrtypes[attnum]->attndims = 0;
748 attrtypes[attnum]->attstattarget = -1;
749 attrtypes[attnum]->attcacheoff = -1;
750 attrtypes[attnum]->atttypmod = -1;
751 attrtypes[attnum]->attislocal = true;
754 * Mark as "not null" if type is fixed-width and prior columns are
755 * too. This corresponds to case where column can be accessed directly
756 * via C struct declaration.
762 for (i = 0; i < attnum; i++)
764 if (attrtypes[i]->attlen <= 0)
768 attrtypes[attnum]->attnotnull = true;
776 * If objectid is not zero, it is a specific OID to assign to the tuple.
777 * Otherwise, an OID will be assigned (if necessary) by heap_insert.
781 InsertOneTuple(Oid objectid)
787 elog(DEBUG4, "inserting row oid %u, %d columns", objectid, numattr);
789 tupDesc = CreateTupleDesc(numattr,
790 RelationGetForm(boot_reldesc)->relhasoids,
792 tuple = heap_formtuple(tupDesc, values, Blanks);
793 if (objectid != (Oid) 0)
794 HeapTupleSetOid(tuple, objectid);
795 pfree(tupDesc); /* just free's tupDesc, not the attrtypes */
797 simple_heap_insert(boot_reldesc, tuple);
798 heap_freetuple(tuple);
799 elog(DEBUG4, "row inserted");
802 * Reset blanks for next tuple
804 for (i = 0; i < numattr; i++)
813 InsertOneValue(char *value, int i)
821 AssertArg(i >= 0 || i < MAXATTR);
823 elog(DEBUG4, "inserting column %d value \"%s\"", i, value);
830 elog(DEBUG5, "Typ != NULL");
831 typoid = boot_reldesc->rd_att->attrs[i]->atttypid;
833 while (*app && (*app)->am_oid != typoid)
837 elog(ERROR, "could not find atttypid %u in Typ list", typoid);
839 /* XXX this should match getTypeIOParam() */
840 if (ap->am_typ.typtype == 'c')
843 typioparam = ap->am_typ.typelem;
845 typinput = ap->am_typ.typinput;
846 typoutput = ap->am_typ.typoutput;
852 /* XXX why is typoid determined differently in this path? */
853 typoid = attrtypes[i]->atttypid;
854 for (typeindex = 0; typeindex < n_types; typeindex++)
856 if (TypInfo[typeindex].oid == typoid)
859 if (typeindex >= n_types)
860 elog(ERROR, "type oid %u not found", typoid);
861 elog(DEBUG5, "Typ == NULL, typeindex = %u", typeindex);
863 /* XXX there are no composite types in TypInfo */
864 typioparam = TypInfo[typeindex].elem;
866 typinput = TypInfo[typeindex].inproc;
867 typoutput = TypInfo[typeindex].outproc;
870 values[i] = OidFunctionCall3(typinput,
871 CStringGetDatum(value),
872 ObjectIdGetDatum(typioparam),
874 prt = DatumGetCString(OidFunctionCall3(typoutput,
876 ObjectIdGetDatum(typioparam),
878 elog(DEBUG4, "inserted -> %s", prt);
889 elog(DEBUG4, "inserting column %d NULL", i);
890 Assert(i >= 0 || i < MAXATTR);
891 values[i] = PointerGetDatum(NULL);
902 static int beenhere = 0;
908 elog(FATAL, "cleanup called twice");
911 if (boot_reldesc != NULL)
913 CommitTransactionCommand();
914 proc_exit(Warnings ? 1 : 0);
920 * NB: this is really ugly; it will return an integer index into TypInfo[],
921 * and not an OID at all, until the first reference to a type not known in
922 * TypInfo[]. At that point it will read and cache pg_type in the Typ array,
923 * and subsequently return a real OID (and set the global pointer Ap to
924 * point at the found row in Typ). So caller must check whether Typ is
925 * still NULL to determine what the return value is!
939 for (app = Typ; *app != NULL; app++)
941 if (strncmp(NameStr((*app)->am_typ.typname), type, NAMEDATALEN) == 0)
944 return (*app)->am_oid;
950 for (i = 0; i < n_types; i++)
952 if (strncmp(type, TypInfo[i].name, NAMEDATALEN) == 0)
955 elog(DEBUG4, "external type: %s", type);
956 rel = heap_openr(TypeRelationName, NoLock);
957 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
959 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
962 app = Typ = ALLOC(struct typmap *, i + 1);
964 *app++ = ALLOC(struct typmap, 1);
966 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
968 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
970 (*app)->am_oid = HeapTupleGetOid(tup);
971 memmove((char *) &(*app++)->am_typ,
972 (char *) GETSTRUCT(tup),
973 sizeof((*app)->am_typ));
976 heap_close(rel, NoLock);
977 return gettype(type);
979 elog(ERROR, "unrecognized type \"%s\"", type);
981 /* not reached, here to make compiler happy */
989 static Form_pg_attribute
990 AllocateAttribute(void)
992 Form_pg_attribute attribute = (Form_pg_attribute) malloc(ATTRIBUTE_TUPLE_SIZE);
994 if (!PointerIsValid(attribute))
995 elog(FATAL, "out of memory");
996 MemSet(attribute, 0, ATTRIBUTE_TUPLE_SIZE);
1003 * XXX arrays of "basetype" are always "_basetype".
1004 * this is an evil hack inherited from rel. 3.1.
1005 * XXX array dimension is thrown away because we
1006 * don't support fixed-dimension arrays. again,
1007 * sickness from 3.1.
1009 * the string passed in must have a '[' character in it
1011 * the string returned is a pointer to static storage and should NOT
1012 * be freed by the CALLER.
1016 MapArrayTypeName(char *s)
1020 static char newStr[NAMEDATALEN]; /* array type names < NAMEDATALEN
1023 if (s == NULL || s[0] == '\0')
1028 for (i = 0; i < NAMEDATALEN - 1 && s[i] != '['; i++, j++)
1038 * returns the string table position of the identifier
1039 * passed to it. We add it to the table if we can't find it.
1043 EnterString(char *str)
1050 node = FindStr(str, len, 0);
1052 return node->strnum;
1055 node = AddStr(str, len, 0);
1056 return node->strnum;
1062 * when given an idnum into the 'string-table' return the string
1063 * associated with the idnum
1067 LexIDStr(int ident_num)
1069 return strtable[ident_num];
1076 * Compute a hash function for a given string. We look at the first,
1077 * the last, and the middle character of a string to try to get spread
1078 * the strings out. The function is rather arbitrary, except that we
1079 * are mod'ing by a prime number.
1083 CompHash(char *str, int len)
1087 result = (NUM * str[0] + NUMSQR * str[len - 1] + NUMCUBE * str[(len - 1) / 2]);
1089 return result % HASHTABLESIZE;
1096 * This routine looks for the specified string in the hash
1097 * table. It returns a pointer to the hash node found,
1098 * or NULL if the string is not in the table.
1102 FindStr(char *str, int length, hashnode *mderef)
1106 node = hashtable[CompHash(str, length)];
1107 while (node != NULL)
1110 * We must differentiate between string constants that might have
1111 * the same value as a identifier and the identifier itself.
1113 if (!strcmp(str, strtable[node->strnum]))
1115 return node; /* no need to check */
1120 /* Couldn't find it in the list */
1127 * This function adds the specified string, along with its associated
1128 * data, to the hash table and the string table. We return the node
1129 * so that the calling routine can find out the unique id that AddStr
1130 * has assigned to this string.
1134 AddStr(char *str, int strlength, int mderef)
1142 if (++strtable_end >= STRTABLESIZE)
1143 elog(FATAL, "bootstrap string table overflow");
1146 * Some of the utilites (eg, define type, create relation) assume that
1147 * the string they're passed is a NAMEDATALEN. We get array bound
1148 * read violations from purify if we don't allocate at least
1149 * NAMEDATALEN bytes for strings of this sort. Because we're lazy, we
1150 * allocate at least NAMEDATALEN bytes all the time.
1153 if ((len = strlength + 1) < NAMEDATALEN)
1156 strtable[strtable_end] = malloc((unsigned) len);
1157 strcpy(strtable[strtable_end], str);
1159 /* Now put a node in the hash table */
1161 newnode = (hashnode *) malloc(sizeof(hashnode) * 1);
1162 newnode->strnum = strtable_end;
1163 newnode->next = NULL;
1165 /* Find out where it goes */
1167 hashresult = CompHash(str, strlength);
1168 if (hashtable[hashresult] == NULL)
1169 hashtable[hashresult] = newnode;
1171 { /* There is something in the list */
1172 trail = hashtable[hashresult];
1174 while (temp != NULL)
1179 trail->next = newnode;
1187 * index_register() -- record an index that has been set up for building
1190 * At bootstrap time, we define a bunch of indices on system catalogs.
1191 * We postpone actually building the indices until just before we're
1192 * finished with initialization, however. This is because more classes
1193 * and indices may be defined, and we want to be sure that all of them
1194 * are present in the index.
1197 index_register(Oid heap,
1199 IndexInfo *indexInfo)
1202 MemoryContext oldcxt;
1205 * XXX mao 10/31/92 -- don't gc index reldescs, associated info at
1206 * bootstrap time. we'll declare the indices now, but want to create
1211 nogc = AllocSetContextCreate(NULL,
1213 ALLOCSET_DEFAULT_MINSIZE,
1214 ALLOCSET_DEFAULT_INITSIZE,
1215 ALLOCSET_DEFAULT_MAXSIZE);
1217 oldcxt = MemoryContextSwitchTo(nogc);
1219 newind = (IndexList *) palloc(sizeof(IndexList));
1220 newind->il_heap = heap;
1221 newind->il_ind = ind;
1222 newind->il_info = (IndexInfo *) palloc(sizeof(IndexInfo));
1224 memcpy(newind->il_info, indexInfo, sizeof(IndexInfo));
1225 /* expressions will likely be null, but may as well copy it */
1226 newind->il_info->ii_Expressions = (List *)
1227 copyObject(indexInfo->ii_Expressions);
1228 newind->il_info->ii_ExpressionsState = NIL;
1229 /* predicate will likely be null, but may as well copy it */
1230 newind->il_info->ii_Predicate = (List *)
1231 copyObject(indexInfo->ii_Predicate);
1232 newind->il_info->ii_PredicateState = NIL;
1234 newind->il_next = ILHead;
1237 MemoryContextSwitchTo(oldcxt);
1243 for (; ILHead != NULL; ILHead = ILHead->il_next)
1248 heap = heap_open(ILHead->il_heap, NoLock);
1249 ind = index_open(ILHead->il_ind);
1250 index_build(heap, ind, ILHead->il_info);
1253 * In normal processing mode, index_build would close the heap and
1254 * index, but in bootstrap mode it will not.
1257 /* XXX Probably we ought to close the heap and index here? */