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-2007, 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.235 2007/07/24 04:54:09 tgl Exp $
13 *-------------------------------------------------------------------------
23 #include "access/genam.h"
24 #include "access/heapam.h"
25 #include "access/xact.h"
26 #include "bootstrap/bootstrap.h"
27 #include "catalog/index.h"
28 #include "catalog/pg_type.h"
29 #include "libpq/pqsignal.h"
30 #include "miscadmin.h"
31 #include "nodes/makefuncs.h"
32 #include "postmaster/bgwriter.h"
33 #include "postmaster/walwriter.h"
34 #include "storage/freespace.h"
35 #include "storage/ipc.h"
36 #include "storage/proc.h"
37 #include "tcop/tcopprot.h"
38 #include "utils/builtins.h"
39 #include "utils/flatfiles.h"
40 #include "utils/fmgroids.h"
41 #include "utils/memutils.h"
42 #include "utils/ps_status.h"
48 #define ALLOC(t, c) ((t *) calloc((unsigned)(c), sizeof(t)))
50 static void CheckerModeMain(void);
51 static void BootstrapModeMain(void);
52 static void bootstrap_signals(void);
53 static void ShutdownAuxiliaryProcess(int code, Datum arg);
54 static hashnode *AddStr(char *str, int strlength, int mderef);
55 static Form_pg_attribute AllocateAttribute(void);
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];
112 static const struct typinfo TypInfo[] = {
113 {"bool", BOOLOID, 0, 1, true, 'c', 'p',
114 F_BOOLIN, F_BOOLOUT},
115 {"bytea", BYTEAOID, 0, -1, false, 'i', 'x',
116 F_BYTEAIN, F_BYTEAOUT},
117 {"char", CHAROID, 0, 1, true, 'c', 'p',
118 F_CHARIN, F_CHAROUT},
119 {"int2", INT2OID, 0, 2, true, 's', 'p',
120 F_INT2IN, F_INT2OUT},
121 {"int4", INT4OID, 0, 4, true, 'i', 'p',
122 F_INT4IN, F_INT4OUT},
123 {"float4", FLOAT4OID, 0, 4, false, 'i', 'p',
124 F_FLOAT4IN, F_FLOAT4OUT},
125 {"name", NAMEOID, CHAROID, NAMEDATALEN, false, 'i', 'p',
126 F_NAMEIN, F_NAMEOUT},
127 {"regclass", REGCLASSOID, 0, 4, true, 'i', 'p',
128 F_REGCLASSIN, F_REGCLASSOUT},
129 {"regproc", REGPROCOID, 0, 4, true, 'i', 'p',
130 F_REGPROCIN, F_REGPROCOUT},
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, -1, false, 'i', 'p',
144 F_INT2VECTORIN, F_INT2VECTOROUT},
145 {"oidvector", OIDVECTOROID, OIDOID, -1, 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 {"_oid", 1028, OIDOID, -1, false, 'i', 'x',
152 F_ARRAY_IN, F_ARRAY_OUT},
153 {"_char", 1002, CHAROID, -1, false, 'i', 'x',
154 F_ARRAY_IN, F_ARRAY_OUT},
155 {"_aclitem", 1034, ACLITEMOID, -1, false, 'i', 'x',
156 F_ARRAY_IN, F_ARRAY_OUT}
159 static const int n_types = sizeof(TypInfo) / sizeof(struct typinfo);
164 FormData_pg_type am_typ;
167 static struct typmap **Typ = NULL;
168 static struct typmap *Ap = NULL;
170 static char Blanks[MAXATTR];
172 Form_pg_attribute attrtypes[MAXATTR]; /* points to attribute info */
173 static Datum values[MAXATTR]; /* corresponding attribute values */
174 int numattr; /* number of attributes for cur. rel */
176 static MemoryContext nogc = NULL; /* special no-gc mem context */
179 * At bootstrap time, we first declare all the indices to be built, and
180 * then build them. The IndexList structure stores enough information
181 * to allow us to build the indices after they've been declared.
184 typedef struct _IndexList
189 struct _IndexList *il_next;
192 static IndexList *ILHead = NULL;
196 * AuxiliaryProcessMain
198 * The main entry point for auxiliary processes, such as the bgwriter,
199 * walwriter, bootstrapper and the shared memory checker code.
201 * This code is here just because of historical reasons.
204 AuxiliaryProcessMain(int argc, char *argv[])
206 char *progname = argv[0];
208 AuxProcType auxType = CheckerProcess;
209 char *userDoption = NULL;
214 MyProcPid = getpid();
217 * Fire up essential subsystems: error and memory management
219 * If we are running under the postmaster, this is done already.
221 if (!IsUnderPostmaster)
224 /* Compute paths, if we didn't inherit them from postmaster */
225 if (my_exec_path[0] == '\0')
227 if (find_my_exec(progname, my_exec_path) < 0)
228 elog(FATAL, "%s: could not locate my own executable path",
233 * process command arguments
236 /* Set defaults, to be overriden by explicit options below */
237 if (!IsUnderPostmaster)
238 InitializeGUCOptions();
240 /* Ignore the initial --boot argument, if present */
241 if (argc > 1 && strcmp(argv[1], "--boot") == 0)
247 while ((flag = getopt(argc, argv, "B:c:d:D:Fr:x:-:")) != -1)
252 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
255 userDoption = 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);
271 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
274 strlcpy(OutputFileName, optarg, MAXPGPATH);
277 auxType = atoi(optarg);
285 ParseLongOption(optarg, &name, &value);
290 (errcode(ERRCODE_SYNTAX_ERROR),
291 errmsg("--%s requires a value",
295 (errcode(ERRCODE_SYNTAX_ERROR),
296 errmsg("-c %s requires a value",
300 SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
307 write_stderr("Try \"%s --help\" for more information.\n",
316 write_stderr("%s: invalid command-line arguments\n", progname);
321 * Identify myself via ps
323 if (IsUnderPostmaster)
330 statmsg = "startup process";
332 case BgWriterProcess:
333 statmsg = "writer process";
335 case WalWriterProcess:
336 statmsg = "wal writer process";
339 statmsg = "??? process";
342 init_ps_display(statmsg, "", "", "");
345 /* Acquire configuration parameters, unless inherited from postmaster */
346 if (!IsUnderPostmaster)
348 if (!SelectConfigFiles(userDoption, progname))
350 /* If timezone is not set, determine what the OS uses */
351 pg_timezone_initialize();
352 /* If timezone_abbreviations is not set, select default */
353 pg_timezone_abbrev_initialize();
356 /* Validate we have been given a reasonable-looking DataDir */
358 ValidatePgVersion(DataDir);
360 /* Change into DataDir (if under postmaster, should be done already) */
361 if (!IsUnderPostmaster)
364 /* If standalone, create lockfile for data directory */
365 if (!IsUnderPostmaster)
366 CreateDataDirLockFile(false);
368 SetProcessingMode(BootstrapProcessing);
369 IgnoreSystemIndexes = true;
374 * When we are an auxiliary process, we aren't going to do the full
375 * InitPostgres pushups, but there are a couple of things that need to get
376 * lit up even in an auxiliary process.
378 if (IsUnderPostmaster)
381 * Create a PGPROC so we can use LWLocks. In the EXEC_BACKEND case,
382 * this was already done by SubPostmasterMain().
385 InitAuxiliaryProcess();
388 /* finish setting up bufmgr.c */
389 InitBufferPoolBackend();
391 /* register a shutdown callback for LWLock cleanup */
392 on_shmem_exit(ShutdownAuxiliaryProcess, 0);
398 SetProcessingMode(NormalProcessing);
405 proc_exit(1); /* should never return */
407 case BootstrapProcess:
412 proc_exit(1); /* should never return */
418 BuildFlatFiles(false);
419 proc_exit(0); /* startup done */
421 case BgWriterProcess:
422 /* don't set signals, bgwriter has its own agenda */
424 BackgroundWriterMain();
425 proc_exit(1); /* should never return */
427 case WalWriterProcess:
428 /* don't set signals, walwriter has its own agenda */
431 proc_exit(1); /* should never return */
434 elog(PANIC, "unrecognized process type: %d", auxType);
440 * In shared memory checker mode, all we really want to do is create shared
441 * memory and semaphores (just to prove we can do it with the current GUC
445 CheckerModeMain(void)
448 * We must be getting invoked for bootstrap mode
450 Assert(!IsUnderPostmaster);
452 SetProcessingMode(BootstrapProcessing);
455 * Do backend-like initialization for bootstrap mode
458 InitPostgres(NULL, InvalidOid, NULL, NULL);
463 * The main entry point for running the backend in bootstrap mode
465 * The bootstrap mode is used to initialize the template database.
466 * The bootstrap backend doesn't speak SQL, but instead expects
467 * commands in a special bootstrap language.
470 BootstrapModeMain(void)
474 Assert(!IsUnderPostmaster);
476 SetProcessingMode(BootstrapProcessing);
479 * Do backend-like initialization for bootstrap mode
482 InitPostgres(NULL, InvalidOid, NULL, NULL);
484 /* Initialize stuff for bootstrap-file processing */
485 for (i = 0; i < MAXATTR; i++)
490 for (i = 0; i < STRTABLESIZE; ++i)
492 for (i = 0; i < HASHTABLESIZE; ++i)
496 * Process bootstrap input.
500 /* Perform a checkpoint to ensure everything's down to disk */
501 SetProcessingMode(NormalProcessing);
502 CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
504 /* Clean up and exit */
510 /* ----------------------------------------------------------------
512 * ----------------------------------------------------------------
516 * Set up signal handling for a bootstrap process
519 bootstrap_signals(void)
521 if (IsUnderPostmaster)
524 * If possible, make this process a group leader, so that the
525 * postmaster can signal any child processes too.
529 elog(FATAL, "setsid() failed: %m");
533 * Properly accept or ignore signals the postmaster might send us
535 pqsignal(SIGHUP, SIG_IGN);
536 pqsignal(SIGINT, SIG_IGN); /* ignore query-cancel */
537 pqsignal(SIGTERM, die);
538 pqsignal(SIGQUIT, quickdie);
539 pqsignal(SIGALRM, SIG_IGN);
540 pqsignal(SIGPIPE, SIG_IGN);
541 pqsignal(SIGUSR1, SIG_IGN);
542 pqsignal(SIGUSR2, SIG_IGN);
545 * Reset some signals that are accepted by postmaster but not here
547 pqsignal(SIGCHLD, SIG_DFL);
548 pqsignal(SIGTTIN, SIG_DFL);
549 pqsignal(SIGTTOU, SIG_DFL);
550 pqsignal(SIGCONT, SIG_DFL);
551 pqsignal(SIGWINCH, SIG_DFL);
554 * Unblock signals (they were blocked when the postmaster forked us)
556 PG_SETMASK(&UnBlockSig);
560 /* Set up appropriately for interactive use */
561 pqsignal(SIGHUP, die);
562 pqsignal(SIGINT, die);
563 pqsignal(SIGTERM, die);
564 pqsignal(SIGQUIT, die);
569 * Begin shutdown of an auxiliary process. This is approximately the equivalent
570 * of ShutdownPostgres() in postinit.c. We can't run transactions in an
571 * auxiliary process, so most of the work of AbortTransaction() is not needed,
572 * but we do need to make sure we've released any LWLocks we are holding.
573 * (This is only critical during an error exit.)
576 ShutdownAuxiliaryProcess(int code, Datum arg)
581 /* ----------------------------------------------------------------
582 * MANUAL BACKEND INTERACTIVE INTERFACE COMMANDS
583 * ----------------------------------------------------------------
591 boot_openrel(char *relname)
599 if (strlen(relname) >= NAMEDATALEN)
600 relname[NAMEDATALEN - 1] = '\0';
604 /* We can now load the pg_type data */
605 rel = heap_open(TypeRelationId, NoLock);
606 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
608 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
611 app = Typ = ALLOC(struct typmap *, i + 1);
613 *app++ = ALLOC(struct typmap, 1);
615 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
617 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
619 (*app)->am_oid = HeapTupleGetOid(tup);
620 memcpy((char *) &(*app)->am_typ,
621 (char *) GETSTRUCT(tup),
622 sizeof((*app)->am_typ));
626 heap_close(rel, NoLock);
629 if (boot_reldesc != NULL)
632 elog(DEBUG4, "open relation %s, attrsize %d",
633 relname, (int) ATTRIBUTE_TUPLE_SIZE);
635 boot_reldesc = heap_openrv(makeRangeVar(NULL, relname), NoLock);
636 numattr = boot_reldesc->rd_rel->relnatts;
637 for (i = 0; i < numattr; i++)
639 if (attrtypes[i] == NULL)
640 attrtypes[i] = AllocateAttribute();
641 memmove((char *) attrtypes[i],
642 (char *) boot_reldesc->rd_att->attrs[i],
643 ATTRIBUTE_TUPLE_SIZE);
646 Form_pg_attribute at = attrtypes[i];
648 elog(DEBUG4, "create attribute %d name %s len %d num %d type %u",
649 i, NameStr(at->attname), at->attlen, at->attnum,
666 if (strcmp(RelationGetRelationName(boot_reldesc), name) != 0)
667 elog(ERROR, "close of %s when %s was expected",
668 name, RelationGetRelationName(boot_reldesc));
671 elog(ERROR, "close of %s before any relation was opened",
675 if (boot_reldesc == NULL)
676 elog(ERROR, "no open relation to close");
679 elog(DEBUG4, "close relation %s",
680 RelationGetRelationName(boot_reldesc));
681 heap_close(boot_reldesc, NoLock);
691 * define a <field,type> pair
692 * if there are n fields in a relation to be created, this routine
693 * will be called n times
697 DefineAttr(char *name, char *type, int attnum)
701 if (boot_reldesc != NULL)
703 elog(WARNING, "no open relations allowed with CREATE command");
707 if (attrtypes[attnum] == NULL)
708 attrtypes[attnum] = AllocateAttribute();
709 MemSet(attrtypes[attnum], 0, ATTRIBUTE_TUPLE_SIZE);
711 namestrcpy(&attrtypes[attnum]->attname, name);
712 elog(DEBUG4, "column %s %s", NameStr(attrtypes[attnum]->attname), type);
713 attrtypes[attnum]->attnum = attnum + 1; /* fillatt */
715 typeoid = gettype(type);
719 attrtypes[attnum]->atttypid = Ap->am_oid;
720 attrtypes[attnum]->attlen = Ap->am_typ.typlen;
721 attrtypes[attnum]->attbyval = Ap->am_typ.typbyval;
722 attrtypes[attnum]->attstorage = Ap->am_typ.typstorage;
723 attrtypes[attnum]->attalign = Ap->am_typ.typalign;
724 /* if an array type, assume 1-dimensional attribute */
725 if (Ap->am_typ.typelem != InvalidOid && Ap->am_typ.typlen < 0)
726 attrtypes[attnum]->attndims = 1;
728 attrtypes[attnum]->attndims = 0;
732 attrtypes[attnum]->atttypid = TypInfo[typeoid].oid;
733 attrtypes[attnum]->attlen = TypInfo[typeoid].len;
734 attrtypes[attnum]->attbyval = TypInfo[typeoid].byval;
735 attrtypes[attnum]->attstorage = TypInfo[typeoid].storage;
736 attrtypes[attnum]->attalign = TypInfo[typeoid].align;
737 /* if an array type, assume 1-dimensional attribute */
738 if (TypInfo[typeoid].elem != InvalidOid &&
739 attrtypes[attnum]->attlen < 0)
740 attrtypes[attnum]->attndims = 1;
742 attrtypes[attnum]->attndims = 0;
745 attrtypes[attnum]->attstattarget = -1;
746 attrtypes[attnum]->attcacheoff = -1;
747 attrtypes[attnum]->atttypmod = -1;
748 attrtypes[attnum]->attislocal = true;
751 * Mark as "not null" if type is fixed-width and prior columns are too.
752 * This corresponds to case where column can be accessed directly via C
753 * struct declaration.
755 * oidvector and int2vector are also treated as not-nullable, even though
756 * they are no longer fixed-width.
758 #define MARKNOTNULL(att) \
759 ((att)->attlen > 0 || \
760 (att)->atttypid == OIDVECTOROID || \
761 (att)->atttypid == INT2VECTOROID)
763 if (MARKNOTNULL(attrtypes[attnum]))
767 for (i = 0; i < attnum; i++)
769 if (!MARKNOTNULL(attrtypes[i]))
773 attrtypes[attnum]->attnotnull = true;
781 * If objectid is not zero, it is a specific OID to assign to the tuple.
782 * Otherwise, an OID will be assigned (if necessary) by heap_insert.
786 InsertOneTuple(Oid objectid)
792 elog(DEBUG4, "inserting row oid %u, %d columns", objectid, numattr);
794 tupDesc = CreateTupleDesc(numattr,
795 RelationGetForm(boot_reldesc)->relhasoids,
797 tuple = heap_formtuple(tupDesc, values, Blanks);
798 if (objectid != (Oid) 0)
799 HeapTupleSetOid(tuple, objectid);
800 pfree(tupDesc); /* just free's tupDesc, not the attrtypes */
802 simple_heap_insert(boot_reldesc, tuple);
803 heap_freetuple(tuple);
804 elog(DEBUG4, "row inserted");
807 * Reset blanks for next tuple
809 for (i = 0; i < numattr; i++)
818 InsertOneValue(char *value, int i)
830 AssertArg(i >= 0 || i < MAXATTR);
832 elog(DEBUG4, "inserting column %d value \"%s\"", i, value);
834 typoid = boot_reldesc->rd_att->attrs[i]->atttypid;
836 boot_get_type_io_data(typoid,
837 &typlen, &typbyval, &typalign,
838 &typdelim, &typioparam,
839 &typinput, &typoutput);
841 values[i] = OidInputFunctionCall(typinput, value, typioparam, -1);
842 prt = OidOutputFunctionCall(typoutput, values[i]);
843 elog(DEBUG4, "inserted -> %s", prt);
854 elog(DEBUG4, "inserting column %d NULL", i);
855 Assert(i >= 0 || i < MAXATTR);
856 values[i] = PointerGetDatum(NULL);
867 if (boot_reldesc != NULL)
874 * NB: this is really ugly; it will return an integer index into TypInfo[],
875 * and not an OID at all, until the first reference to a type not known in
876 * TypInfo[]. At that point it will read and cache pg_type in the Typ array,
877 * and subsequently return a real OID (and set the global pointer Ap to
878 * point at the found row in Typ). So caller must check whether Typ is
879 * still NULL to determine what the return value is!
893 for (app = Typ; *app != NULL; app++)
895 if (strncmp(NameStr((*app)->am_typ.typname), type, NAMEDATALEN) == 0)
898 return (*app)->am_oid;
904 for (i = 0; i < n_types; i++)
906 if (strncmp(type, TypInfo[i].name, NAMEDATALEN) == 0)
909 elog(DEBUG4, "external type: %s", type);
910 rel = heap_open(TypeRelationId, NoLock);
911 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
913 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
916 app = Typ = ALLOC(struct typmap *, i + 1);
918 *app++ = ALLOC(struct typmap, 1);
920 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
922 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
924 (*app)->am_oid = HeapTupleGetOid(tup);
925 memmove((char *) &(*app++)->am_typ,
926 (char *) GETSTRUCT(tup),
927 sizeof((*app)->am_typ));
930 heap_close(rel, NoLock);
931 return gettype(type);
933 elog(ERROR, "unrecognized type \"%s\"", type);
934 /* not reached, here to make compiler happy */
939 * boot_get_type_io_data
941 * Obtain type I/O information at bootstrap time. This intentionally has
942 * almost the same API as lsyscache.c's get_type_io_data, except that
943 * we only support obtaining the typinput and typoutput routines, not
944 * the binary I/O routines. It is exported so that array_in and array_out
945 * can be made to work during early bootstrap.
949 boot_get_type_io_data(Oid typid,
960 /* We have the boot-time contents of pg_type, so use it */
965 while (*app && (*app)->am_oid != typid)
969 elog(ERROR, "type OID %u not found in Typ list", typid);
971 *typlen = ap->am_typ.typlen;
972 *typbyval = ap->am_typ.typbyval;
973 *typalign = ap->am_typ.typalign;
974 *typdelim = ap->am_typ.typdelim;
976 /* XXX this logic must match getTypeIOParam() */
977 if (OidIsValid(ap->am_typ.typelem))
978 *typioparam = ap->am_typ.typelem;
982 *typinput = ap->am_typ.typinput;
983 *typoutput = ap->am_typ.typoutput;
987 /* We don't have pg_type yet, so use the hard-wired TypInfo array */
990 for (typeindex = 0; typeindex < n_types; typeindex++)
992 if (TypInfo[typeindex].oid == typid)
995 if (typeindex >= n_types)
996 elog(ERROR, "type OID %u not found in TypInfo", typid);
998 *typlen = TypInfo[typeindex].len;
999 *typbyval = TypInfo[typeindex].byval;
1000 *typalign = TypInfo[typeindex].align;
1001 /* We assume typdelim is ',' for all boot-time types */
1004 /* XXX this logic must match getTypeIOParam() */
1005 if (OidIsValid(TypInfo[typeindex].elem))
1006 *typioparam = TypInfo[typeindex].elem;
1008 *typioparam = typid;
1010 *typinput = TypInfo[typeindex].inproc;
1011 *typoutput = TypInfo[typeindex].outproc;
1019 static Form_pg_attribute
1020 AllocateAttribute(void)
1022 Form_pg_attribute attribute = (Form_pg_attribute) malloc(ATTRIBUTE_TUPLE_SIZE);
1024 if (!PointerIsValid(attribute))
1025 elog(FATAL, "out of memory");
1026 MemSet(attribute, 0, ATTRIBUTE_TUPLE_SIZE);
1033 * XXX arrays of "basetype" are always "_basetype".
1034 * this is an evil hack inherited from rel. 3.1.
1035 * XXX array dimension is thrown away because we
1036 * don't support fixed-dimension arrays. again,
1037 * sickness from 3.1.
1039 * the string passed in must have a '[' character in it
1041 * the string returned is a pointer to static storage and should NOT
1042 * be freed by the CALLER.
1046 MapArrayTypeName(char *s)
1050 static char newStr[NAMEDATALEN]; /* array type names < NAMEDATALEN long */
1052 if (s == NULL || s[0] == '\0')
1057 for (i = 0; i < NAMEDATALEN - 1 && s[i] != '['; i++, j++)
1067 * returns the string table position of the identifier
1068 * passed to it. We add it to the table if we can't find it.
1072 EnterString(char *str)
1079 node = FindStr(str, len, NULL);
1081 return node->strnum;
1084 node = AddStr(str, len, 0);
1085 return node->strnum;
1091 * when given an idnum into the 'string-table' return the string
1092 * associated with the idnum
1096 LexIDStr(int ident_num)
1098 return strtable[ident_num];
1105 * Compute a hash function for a given string. We look at the first,
1106 * the last, and the middle character of a string to try to get spread
1107 * the strings out. The function is rather arbitrary, except that we
1108 * are mod'ing by a prime number.
1112 CompHash(char *str, int len)
1116 result = (NUM * str[0] + NUMSQR * str[len - 1] + NUMCUBE * str[(len - 1) / 2]);
1118 return result % HASHTABLESIZE;
1125 * This routine looks for the specified string in the hash
1126 * table. It returns a pointer to the hash node found,
1127 * or NULL if the string is not in the table.
1131 FindStr(char *str, int length, hashnode *mderef)
1135 node = hashtable[CompHash(str, length)];
1136 while (node != NULL)
1139 * We must differentiate between string constants that might have the
1140 * same value as a identifier and the identifier itself.
1142 if (!strcmp(str, strtable[node->strnum]))
1144 return node; /* no need to check */
1149 /* Couldn't find it in the list */
1156 * This function adds the specified string, along with its associated
1157 * data, to the hash table and the string table. We return the node
1158 * so that the calling routine can find out the unique id that AddStr
1159 * has assigned to this string.
1163 AddStr(char *str, int strlength, int mderef)
1171 if (++strtable_end >= STRTABLESIZE)
1172 elog(FATAL, "bootstrap string table overflow");
1175 * Some of the utilites (eg, define type, create relation) assume that the
1176 * string they're passed is a NAMEDATALEN. We get array bound read
1177 * violations from purify if we don't allocate at least NAMEDATALEN bytes
1178 * for strings of this sort. Because we're lazy, we allocate at least
1179 * NAMEDATALEN bytes all the time.
1182 if ((len = strlength + 1) < NAMEDATALEN)
1185 strtable[strtable_end] = malloc((unsigned) len);
1186 strcpy(strtable[strtable_end], str);
1188 /* Now put a node in the hash table */
1190 newnode = (hashnode *) malloc(sizeof(hashnode) * 1);
1191 newnode->strnum = strtable_end;
1192 newnode->next = NULL;
1194 /* Find out where it goes */
1196 hashresult = CompHash(str, strlength);
1197 if (hashtable[hashresult] == NULL)
1198 hashtable[hashresult] = newnode;
1200 { /* There is something in the list */
1201 trail = hashtable[hashresult];
1203 while (temp != NULL)
1208 trail->next = newnode;
1216 * index_register() -- record an index that has been set up for building
1219 * At bootstrap time, we define a bunch of indexes on system catalogs.
1220 * We postpone actually building the indexes until just before we're
1221 * finished with initialization, however. This is because the indexes
1222 * themselves have catalog entries, and those have to be included in the
1223 * indexes on those catalogs. Doing it in two phases is the simplest
1224 * way of making sure the indexes have the right contents at the end.
1227 index_register(Oid heap,
1229 IndexInfo *indexInfo)
1232 MemoryContext oldcxt;
1235 * XXX mao 10/31/92 -- don't gc index reldescs, associated info at
1236 * bootstrap time. we'll declare the indexes now, but want to create them
1241 nogc = AllocSetContextCreate(NULL,
1243 ALLOCSET_DEFAULT_MINSIZE,
1244 ALLOCSET_DEFAULT_INITSIZE,
1245 ALLOCSET_DEFAULT_MAXSIZE);
1247 oldcxt = MemoryContextSwitchTo(nogc);
1249 newind = (IndexList *) palloc(sizeof(IndexList));
1250 newind->il_heap = heap;
1251 newind->il_ind = ind;
1252 newind->il_info = (IndexInfo *) palloc(sizeof(IndexInfo));
1254 memcpy(newind->il_info, indexInfo, sizeof(IndexInfo));
1255 /* expressions will likely be null, but may as well copy it */
1256 newind->il_info->ii_Expressions = (List *)
1257 copyObject(indexInfo->ii_Expressions);
1258 newind->il_info->ii_ExpressionsState = NIL;
1259 /* predicate will likely be null, but may as well copy it */
1260 newind->il_info->ii_Predicate = (List *)
1261 copyObject(indexInfo->ii_Predicate);
1262 newind->il_info->ii_PredicateState = NIL;
1264 newind->il_next = ILHead;
1267 MemoryContextSwitchTo(oldcxt);
1272 * build_indices -- fill in all the indexes registered earlier
1277 for (; ILHead != NULL; ILHead = ILHead->il_next)
1282 /* need not bother with locks during bootstrap */
1283 heap = heap_open(ILHead->il_heap, NoLock);
1284 ind = index_open(ILHead->il_ind, NoLock);
1286 index_build(heap, ind, ILHead->il_info, false);
1288 index_close(ind, NoLock);
1289 heap_close(heap, NoLock);