]> granicus.if.org Git - postgresql/blob - src/backend/bootstrap/bootstrap.c
pgindent run.
[postgresql] / src / backend / bootstrap / bootstrap.c
1 /*-------------------------------------------------------------------------
2  *
3  * bootstrap.c
4  *        routines to support running postgres in 'bootstrap' mode
5  *      bootstrap mode is used to create the initial template database
6  *
7  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/bootstrap/bootstrap.c,v 1.141 2002/09/04 20:31:13 momjian Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <unistd.h>
18 #include <time.h>
19 #include <signal.h>
20 #include <setjmp.h>
21 #ifdef HAVE_GETOPT_H
22 #include <getopt.h>
23 #endif
24
25 #define BOOTSTRAP_INCLUDE               /* mask out stuff in tcop/tcopprot.h */
26
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 "libpq/pqsignal.h"
35 #include "miscadmin.h"
36 #include "storage/ipc.h"
37 #include "storage/proc.h"
38 #include "tcop/tcopprot.h"
39 #include "utils/builtins.h"
40 #include "utils/fmgroids.h"
41 #include "utils/guc.h"
42 #include "utils/lsyscache.h"
43 #include "utils/relcache.h"
44
45
46 #define ALLOC(t, c)             ((t *) calloc((unsigned)(c), sizeof(t)))
47
48
49 extern int      Int_yyparse(void);
50 static hashnode *AddStr(char *str, int strlength, int mderef);
51 static Form_pg_attribute AllocateAttribute(void);
52 static bool BootstrapAlreadySeen(Oid id);
53 static int      CompHash(char *str, int len);
54 static hashnode *FindStr(char *str, int length, hashnode *mderef);
55 static Oid      gettype(char *type);
56 static void cleanup(void);
57
58 /* ----------------
59  *              global variables
60  * ----------------
61  */
62
63 Relation        boot_reldesc;           /* current relation descriptor */
64
65 /*
66  * In the lexical analyzer, we need to get the reference number quickly from
67  * the string, and the string from the reference number.  Thus we have
68  * as our data structure a hash table, where the hashing key taken from
69  * the particular string.  The hash table is chained.  One of the fields
70  * of the hash table node is an index into the array of character pointers.
71  * The unique index number that every string is assigned is simply the
72  * position of its string pointer in the array of string pointers.
73  */
74
75 #define STRTABLESIZE    10000
76 #define HASHTABLESIZE   503
77
78 /* Hash function numbers */
79 #define NUM             23
80 #define NUMSQR  529
81 #define NUMCUBE 12167
82
83 char       *strtable[STRTABLESIZE];
84 hashnode   *hashtable[HASHTABLESIZE];
85
86 static int      strtable_end = -1;      /* Tells us last occupied string space */
87
88 /*-
89  * Basic information associated with each type.  This is used before
90  * pg_type is created.
91  *
92  *              XXX several of these input/output functions do catalog scans
93  *                      (e.g., F_REGPROCIN scans pg_proc).      this obviously creates some
94  *                      order dependencies in the catalog creation process.
95  */
96 struct typinfo
97 {
98         char            name[NAMEDATALEN];
99         Oid                     oid;
100         Oid                     elem;
101         int16           len;
102         Oid                     inproc;
103         Oid                     outproc;
104 };
105
106 static struct typinfo Procid[] = {
107         {"bool", BOOLOID, 0, 1, F_BOOLIN, F_BOOLOUT},
108         {"bytea", BYTEAOID, 0, -1, F_BYTEAIN, F_BYTEAOUT},
109         {"char", CHAROID, 0, 1, F_CHARIN, F_CHAROUT},
110         {"name", NAMEOID, 0, NAMEDATALEN, F_NAMEIN, F_NAMEOUT},
111         {"int2", INT2OID, 0, 2, F_INT2IN, F_INT2OUT},
112         {"int2vector", INT2VECTOROID, 0, INDEX_MAX_KEYS * 2, F_INT2VECTORIN, F_INT2VECTOROUT},
113         {"int4", INT4OID, 0, 4, F_INT4IN, F_INT4OUT},
114         {"regproc", REGPROCOID, 0, 4, F_REGPROCIN, F_REGPROCOUT},
115         {"regclass", REGCLASSOID, 0, 4, F_REGCLASSIN, F_REGCLASSOUT},
116         {"regtype", REGTYPEOID, 0, 4, F_REGTYPEIN, F_REGTYPEOUT},
117         {"text", TEXTOID, 0, -1, F_TEXTIN, F_TEXTOUT},
118         {"oid", OIDOID, 0, 4, F_OIDIN, F_OIDOUT},
119         {"tid", TIDOID, 0, 6, F_TIDIN, F_TIDOUT},
120         {"xid", XIDOID, 0, 4, F_XIDIN, F_XIDOUT},
121         {"cid", CIDOID, 0, 4, F_CIDIN, F_CIDOUT},
122         {"oidvector", OIDVECTOROID, 0, INDEX_MAX_KEYS * 4, F_OIDVECTORIN, F_OIDVECTOROUT},
123         {"smgr", 210, 0, 2, F_SMGRIN, F_SMGROUT},
124         {"_int4", 1007, INT4OID, -1, F_ARRAY_IN, F_ARRAY_OUT},
125         {"_aclitem", 1034, 1033, -1, F_ARRAY_IN, F_ARRAY_OUT}
126 };
127
128 static int      n_types = sizeof(Procid) / sizeof(struct typinfo);
129
130 struct typmap
131 {                                                               /* a hack */
132         Oid                     am_oid;
133         FormData_pg_type am_typ;
134 };
135
136 static struct typmap **Typ = (struct typmap **) NULL;
137 static struct typmap *Ap = (struct typmap *) NULL;
138
139 static int      Warnings = 0;
140 static char Blanks[MAXATTR];
141
142 static char *relname;                   /* current relation name */
143
144 Form_pg_attribute attrtypes[MAXATTR];   /* points to attribute info */
145 static Datum values[MAXATTR];   /* corresponding attribute values */
146 int                     numattr;                        /* number of attributes for cur. rel */
147
148 static MemoryContext nogc = NULL;               /* special no-gc mem context */
149
150 extern int      optind;
151 extern char *optarg;
152
153 /*
154  *      At bootstrap time, we first declare all the indices to be built, and
155  *      then build them.  The IndexList structure stores enough information
156  *      to allow us to build the indices after they've been declared.
157  */
158
159 typedef struct _IndexList
160 {
161         Oid                     il_heap;
162         Oid                     il_ind;
163         IndexInfo  *il_info;
164         struct _IndexList *il_next;
165 } IndexList;
166
167 static IndexList *ILHead = (IndexList *) NULL;
168
169
170 /* ----------------------------------------------------------------
171  *                                              misc functions
172  * ----------------------------------------------------------------
173  */
174
175 /* ----------------
176  *              error handling / abort routines
177  * ----------------
178  */
179 void
180 err_out(void)
181 {
182         Warnings++;
183         cleanup();
184 }
185
186 /* usage:
187    usage help for the bootstrap backen
188 */
189 static void
190 usage(void)
191 {
192         fprintf(stderr,
193                         gettext("Usage:\n"
194                                         "  postgres -boot [-d level] [-D datadir] [-F] [-o file] [-x num] dbname\n"
195                                         "  -d 1-5           debug mode\n"
196                                         "  -D datadir       data directory\n"
197                                         "  -F               turn off fsync\n"
198                                         "  -o file          send debug output to file\n"
199                                         "  -x num           internal use\n"));
200
201         proc_exit(1);
202 }
203
204
205
206 int
207 BootstrapMain(int argc, char *argv[])
208 /* ----------------------------------------------------------------
209  *       The main loop for handling the backend in bootstrap mode
210  *       the bootstrap mode is used to initialize the template database
211  *       the bootstrap backend doesn't speak SQL, but instead expects
212  *       commands in a special bootstrap language.
213  *
214  *       The arguments passed in to BootstrapMain are the run-time arguments
215  *       without the argument '-boot', the caller is required to have
216  *       removed -boot from the run-time args
217  * ----------------------------------------------------------------
218  */
219 {
220         int                     i;
221         char       *dbName;
222         int                     flag;
223         int                     xlogop = BS_XLOG_NOP;
224         char       *potential_DataDir = NULL;
225
226         /*
227          * initialize globals
228          */
229
230         MyProcPid = getpid();
231
232         /*
233          * Fire up essential subsystems: error and memory management
234          *
235          * If we are running under the postmaster, this is done already.
236          */
237         if (!IsUnderPostmaster)
238                 MemoryContextInit();
239
240         /*
241          * process command arguments
242          */
243
244         /* Set defaults, to be overriden by explicit options below */
245         dbName = NULL;
246         if (!IsUnderPostmaster)
247         {
248                 InitializeGUCOptions();
249                 potential_DataDir = getenv("PGDATA");   /* Null if no PGDATA
250                                                                                                  * variable */
251         }
252
253         while ((flag = getopt(argc, argv, "B:d:D:Fo:px:")) != -1)
254         {
255                 switch (flag)
256                 {
257                         case 'D':
258                                 potential_DataDir = optarg;
259                                 break;
260                         case 'd':
261                                 {
262                                         /* Turn on debugging for the bootstrap process. */
263                                         char       *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
264
265                                         sprintf(debugstr, "debug%s", optarg);
266                                         SetConfigOption("server_min_messages", debugstr,
267                                                                         PGC_POSTMASTER, PGC_S_ARGV);
268                                         SetConfigOption("client_min_messages", debugstr,
269                                                                         PGC_POSTMASTER, PGC_S_ARGV);
270                                         pfree(debugstr);
271                                         break;
272                                 }
273                                 break;
274                         case 'F':
275                                 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
276                                 break;
277                         case 'o':
278                                 StrNCpy(OutputFileName, optarg, MAXPGPATH);
279                                 break;
280                         case 'x':
281                                 xlogop = atoi(optarg);
282                                 break;
283                         case 'p':
284                                 /* indicates fork from postmaster */
285                                 break;
286                         case 'B':
287                                 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
288                                 break;
289                         default:
290                                 usage();
291                                 break;
292                 }
293         }                                                       /* while */
294
295         if (argc - optind != 1)
296                 usage();
297
298         dbName = argv[optind];
299
300         Assert(dbName);
301
302         if (!IsUnderPostmaster)
303         {
304                 if (!potential_DataDir)
305                 {
306                         fprintf(stderr,
307                                         gettext("%s does not know where to find the database system data.\n"
308                                                         "You must specify the directory that contains the database system\n"
309                                                         "either by specifying the -D invocation option or by setting the\n"
310                                                         "PGDATA environment variable.\n\n"),
311                                         argv[0]);
312                         proc_exit(1);
313                 }
314                 SetDataDir(potential_DataDir);
315         }
316
317         /* Validate we have been given a reasonable-looking DataDir */
318         Assert(DataDir);
319         ValidatePgVersion(DataDir);
320
321         if (IsUnderPostmaster)
322         {
323                 /*
324                  * Properly accept or ignore signals the postmaster might send us
325                  */
326                 pqsignal(SIGHUP, SIG_IGN);
327                 pqsignal(SIGINT, SIG_IGN);              /* ignore query-cancel */
328                 pqsignal(SIGTERM, die);
329                 pqsignal(SIGQUIT, quickdie);
330                 pqsignal(SIGALRM, SIG_IGN);
331                 pqsignal(SIGPIPE, SIG_IGN);
332                 pqsignal(SIGUSR1, SIG_IGN);
333                 pqsignal(SIGUSR2, SIG_IGN);
334
335                 /*
336                  * Reset some signals that are accepted by postmaster but not here
337                  */
338                 pqsignal(SIGCHLD, SIG_DFL);
339                 pqsignal(SIGTTIN, SIG_DFL);
340                 pqsignal(SIGTTOU, SIG_DFL);
341                 pqsignal(SIGCONT, SIG_DFL);
342                 pqsignal(SIGWINCH, SIG_DFL);
343
344                 /*
345                  * Unblock signals (they were blocked when the postmaster forked
346                  * us)
347                  */
348                 PG_SETMASK(&UnBlockSig);
349         }
350         else
351         {
352                 /* Set up appropriately for interactive use */
353                 pqsignal(SIGHUP, die);
354                 pqsignal(SIGINT, die);
355                 pqsignal(SIGTERM, die);
356                 pqsignal(SIGQUIT, die);
357
358                 /*
359                  * Create lockfile for data directory.
360                  */
361                 if (!CreateDataDirLockFile(DataDir, false))
362                         proc_exit(1);
363         }
364
365         SetProcessingMode(BootstrapProcessing);
366         IgnoreSystemIndexes(true);
367
368         XLOGPathInit();
369
370         BaseInit();
371
372         /*
373          * XLOG operations
374          */
375         SetProcessingMode(NormalProcessing);
376
377         switch (xlogop)
378         {
379                 case BS_XLOG_NOP:
380                         StartupXLOG();
381                         break;
382
383                 case BS_XLOG_BOOTSTRAP:
384                         BootStrapXLOG();
385                         StartupXLOG();
386                         break;
387
388                 case BS_XLOG_CHECKPOINT:
389                         if (IsUnderPostmaster)
390                                 InitDummyProcess();             /* needed to get LWLocks */
391                         CreateDummyCaches();
392                         CreateCheckPoint(false);
393                         SetSavedRedoRecPtr();           /* pass redo ptr back to
394                                                                                  * postmaster */
395                         proc_exit(0);           /* done */
396
397                 case BS_XLOG_STARTUP:
398                         StartupXLOG();
399                         proc_exit(0);           /* done */
400
401                 case BS_XLOG_SHUTDOWN:
402                         ShutdownXLOG();
403                         proc_exit(0);           /* done */
404
405                 default:
406                         elog(PANIC, "Unsupported XLOG op %d", xlogop);
407                         proc_exit(0);
408         }
409
410         SetProcessingMode(BootstrapProcessing);
411
412         /*
413          * backend initialization
414          */
415         InitPostgres(dbName, NULL);
416
417         for (i = 0; i < MAXATTR; i++)
418         {
419                 attrtypes[i] = (Form_pg_attribute) NULL;
420                 Blanks[i] = ' ';
421         }
422         for (i = 0; i < STRTABLESIZE; ++i)
423                 strtable[i] = NULL;
424         for (i = 0; i < HASHTABLESIZE; ++i)
425                 hashtable[i] = NULL;
426
427         /*
428          * abort processing resumes here
429          */
430         if (sigsetjmp(Warn_restart, 1) != 0)
431         {
432                 Warnings++;
433                 AbortCurrentTransaction();
434         }
435
436         /*
437          * process input.
438          */
439
440         /*
441          * the sed script boot.sed renamed yyparse to Int_yyparse for the
442          * bootstrap parser to avoid conflicts with the normal SQL parser
443          */
444         Int_yyparse();
445
446         SetProcessingMode(NormalProcessing);
447         CreateCheckPoint(true);
448         SetProcessingMode(BootstrapProcessing);
449
450         /* clean up processing */
451         StartTransactionCommand(true);
452         cleanup();
453
454         /* not reached, here to make compiler happy */
455         return 0;
456
457 }
458
459 /* ----------------------------------------------------------------
460  *                              MANUAL BACKEND INTERACTIVE INTERFACE COMMANDS
461  * ----------------------------------------------------------------
462  */
463
464 /* ----------------
465  *              boot_openrel
466  * ----------------
467  */
468 void
469 boot_openrel(char *relname)
470 {
471         int                     i;
472         struct typmap **app;
473         Relation        rel;
474         HeapScanDesc scan;
475         HeapTuple       tup;
476
477         if (strlen(relname) >= NAMEDATALEN - 1)
478                 relname[NAMEDATALEN - 1] = '\0';
479
480         if (Typ == (struct typmap **) NULL)
481         {
482                 rel = heap_openr(TypeRelationName, NoLock);
483                 scan = heap_beginscan(rel, SnapshotNow, 0, (ScanKey) NULL);
484                 i = 0;
485                 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
486                         ++i;
487                 heap_endscan(scan);
488                 app = Typ = ALLOC(struct typmap *, i + 1);
489                 while (i-- > 0)
490                         *app++ = ALLOC(struct typmap, 1);
491                 *app = (struct typmap *) NULL;
492                 scan = heap_beginscan(rel, SnapshotNow, 0, (ScanKey) NULL);
493                 app = Typ;
494                 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
495                 {
496                         (*app)->am_oid = HeapTupleGetOid(tup);
497                         memcpy((char *) &(*app)->am_typ,
498                                    (char *) GETSTRUCT(tup),
499                                    sizeof((*app)->am_typ));
500                         app++;
501                 }
502                 heap_endscan(scan);
503                 heap_close(rel, NoLock);
504         }
505
506         if (boot_reldesc != NULL)
507                 closerel(NULL);
508
509         elog(DEBUG3, "open relation %s, attrsize %d", relname ? relname : "(null)",
510                  (int) ATTRIBUTE_TUPLE_SIZE);
511
512         boot_reldesc = heap_openr(relname, NoLock);
513         numattr = boot_reldesc->rd_rel->relnatts;
514         for (i = 0; i < numattr; i++)
515         {
516                 if (attrtypes[i] == NULL)
517                         attrtypes[i] = AllocateAttribute();
518                 memmove((char *) attrtypes[i],
519                                 (char *) boot_reldesc->rd_att->attrs[i],
520                                 ATTRIBUTE_TUPLE_SIZE);
521
522                 {
523                         Form_pg_attribute at = attrtypes[i];
524
525                         elog(DEBUG3, "create attribute %d name %s len %d num %d type %u",
526                                  i, NameStr(at->attname), at->attlen, at->attnum,
527                                  at->atttypid);
528                 }
529         }
530 }
531
532 /* ----------------
533  *              closerel
534  * ----------------
535  */
536 void
537 closerel(char *name)
538 {
539         if (name)
540         {
541                 if (boot_reldesc)
542                 {
543                         if (strcmp(RelationGetRelationName(boot_reldesc), name) != 0)
544                                 elog(ERROR, "closerel: close of '%s' when '%s' was expected",
545                                          name, relname ? relname : "(null)");
546                 }
547                 else
548                         elog(ERROR, "closerel: close of '%s' before any relation was opened",
549                                  name);
550         }
551
552         if (boot_reldesc == NULL)
553                 elog(ERROR, "no open relation to close");
554         else
555         {
556                 elog(DEBUG3, "close relation %s", relname ? relname : "(null)");
557                 heap_close(boot_reldesc, NoLock);
558                 boot_reldesc = (Relation) NULL;
559         }
560 }
561
562
563
564 /* ----------------
565  * DEFINEATTR()
566  *
567  * define a <field,type> pair
568  * if there are n fields in a relation to be created, this routine
569  * will be called n times
570  * ----------------
571  */
572 void
573 DefineAttr(char *name, char *type, int attnum)
574 {
575         int                     attlen;
576         Oid                     typeoid;
577
578         if (boot_reldesc != NULL)
579         {
580                 elog(LOG, "warning: no open relations allowed with 'create' command");
581                 closerel(relname);
582         }
583
584         if (attrtypes[attnum] == (Form_pg_attribute) NULL)
585                 attrtypes[attnum] = AllocateAttribute();
586         MemSet(attrtypes[attnum], 0, ATTRIBUTE_TUPLE_SIZE);
587
588         namestrcpy(&attrtypes[attnum]->attname, name);
589         elog(DEBUG3, "column %s %s", NameStr(attrtypes[attnum]->attname), type);
590         attrtypes[attnum]->attnum = 1 + attnum;         /* fillatt */
591
592         typeoid = gettype(type);
593
594         if (Typ != (struct typmap **) NULL)
595         {
596                 attrtypes[attnum]->atttypid = Ap->am_oid;
597                 attlen = attrtypes[attnum]->attlen = Ap->am_typ.typlen;
598                 attrtypes[attnum]->attbyval = Ap->am_typ.typbyval;
599                 attrtypes[attnum]->attstorage = Ap->am_typ.typstorage;
600                 attrtypes[attnum]->attalign = Ap->am_typ.typalign;
601         }
602         else
603         {
604                 attrtypes[attnum]->atttypid = Procid[typeoid].oid;
605                 attlen = attrtypes[attnum]->attlen = Procid[typeoid].len;
606
607                 /*
608                  * Cheat like mad to fill in these items from the length only.
609                  * This only has to work for types that appear in Procid[].
610                  */
611                 switch (attlen)
612                 {
613                         case 1:
614                                 attrtypes[attnum]->attbyval = true;
615                                 attrtypes[attnum]->attstorage = 'p';
616                                 attrtypes[attnum]->attalign = 'c';
617                                 break;
618                         case 2:
619                                 attrtypes[attnum]->attbyval = true;
620                                 attrtypes[attnum]->attstorage = 'p';
621                                 attrtypes[attnum]->attalign = 's';
622                                 break;
623                         case 4:
624                                 attrtypes[attnum]->attbyval = true;
625                                 attrtypes[attnum]->attstorage = 'p';
626                                 attrtypes[attnum]->attalign = 'i';
627                                 break;
628                         case -1:
629                                 attrtypes[attnum]->attbyval = false;
630                                 attrtypes[attnum]->attstorage = 'x';
631                                 attrtypes[attnum]->attalign = 'i';
632                                 break;
633                         default:
634                                 /* TID and fixed-length arrays, such as oidvector */
635                                 attrtypes[attnum]->attbyval = false;
636                                 attrtypes[attnum]->attstorage = 'p';
637                                 attrtypes[attnum]->attalign = 'i';
638                                 break;
639                 }
640         }
641         attrtypes[attnum]->attcacheoff = -1;
642         attrtypes[attnum]->atttypmod = -1;
643
644         /*
645          * Mark as "not null" if type is fixed-width and prior columns are
646          * too. This corresponds to case where column can be accessed directly
647          * via C struct declaration.
648          */
649         if (attlen > 0)
650         {
651                 int                     i;
652
653                 for (i = 0; i < attnum; i++)
654                 {
655                         if (attrtypes[i]->attlen <= 0)
656                                 break;
657                 }
658                 if (i == attnum)
659                         attrtypes[attnum]->attnotnull = true;
660         }
661 }
662
663
664 /* ----------------
665  *              InsertOneTuple
666  *
667  * If objectid is not zero, it is a specific OID to assign to the tuple.
668  * Otherwise, an OID will be assigned (if necessary) by heap_insert.
669  * ----------------
670  */
671 void
672 InsertOneTuple(Oid objectid)
673 {
674         HeapTuple       tuple;
675         TupleDesc       tupDesc;
676         int                     i;
677
678         elog(DEBUG3, "inserting row oid %u, %d columns", objectid, numattr);
679
680         tupDesc = CreateTupleDesc(numattr,
681                                                           RelationGetForm(boot_reldesc)->relhasoids,
682                                                           attrtypes);
683         tuple = heap_formtuple(tupDesc, values, Blanks);
684         if (objectid != (Oid) 0)
685                 HeapTupleSetOid(tuple, objectid);
686         pfree(tupDesc);                         /* just free's tupDesc, not the attrtypes */
687
688         simple_heap_insert(boot_reldesc, tuple);
689         heap_freetuple(tuple);
690         elog(DEBUG3, "row inserted");
691
692         /*
693          * Reset blanks for next tuple
694          */
695         for (i = 0; i < numattr; i++)
696                 Blanks[i] = ' ';
697 }
698
699 /* ----------------
700  *              InsertOneValue
701  * ----------------
702  */
703 void
704 InsertOneValue(char *value, int i)
705 {
706         int                     typeindex;
707         char       *prt;
708         struct typmap **app;
709
710         AssertArg(i >= 0 || i < MAXATTR);
711
712         elog(DEBUG3, "inserting column %d value '%s'", i, value);
713
714         if (Typ != (struct typmap **) NULL)
715         {
716                 struct typmap *ap;
717
718                 elog(DEBUG3, "Typ != NULL");
719                 app = Typ;
720                 while (*app && (*app)->am_oid != boot_reldesc->rd_att->attrs[i]->atttypid)
721                         ++app;
722                 ap = *app;
723                 if (ap == NULL)
724                 {
725                         elog(FATAL, "unable to find atttypid %u in Typ list",
726                                  boot_reldesc->rd_att->attrs[i]->atttypid);
727                 }
728                 values[i] = OidFunctionCall3(ap->am_typ.typinput,
729                                                                          CStringGetDatum(value),
730                                                                          ObjectIdGetDatum(ap->am_typ.typelem),
731                                                                          Int32GetDatum(-1));
732                 prt = DatumGetCString(OidFunctionCall3(ap->am_typ.typoutput,
733                                                                                            values[i],
734                                                                         ObjectIdGetDatum(ap->am_typ.typelem),
735                                                                                            Int32GetDatum(-1)));
736                 elog(DEBUG3, " -> %s", prt);
737                 pfree(prt);
738         }
739         else
740         {
741                 for (typeindex = 0; typeindex < n_types; typeindex++)
742                 {
743                         if (Procid[typeindex].oid == attrtypes[i]->atttypid)
744                                 break;
745                 }
746                 if (typeindex >= n_types)
747                         elog(ERROR, "type oid %u not found", attrtypes[i]->atttypid);
748                 elog(DEBUG3, "Typ == NULL, typeindex = %u", typeindex);
749                 values[i] = OidFunctionCall3(Procid[typeindex].inproc,
750                                                                          CStringGetDatum(value),
751                                                                 ObjectIdGetDatum(Procid[typeindex].elem),
752                                                                          Int32GetDatum(-1));
753                 prt = DatumGetCString(OidFunctionCall3(Procid[typeindex].outproc,
754                                                                                            values[i],
755                                                                 ObjectIdGetDatum(Procid[typeindex].elem),
756                                                                                            Int32GetDatum(-1)));
757                 elog(DEBUG3, " -> %s", prt);
758                 pfree(prt);
759         }
760         elog(DEBUG3, "inserted");
761 }
762
763 /* ----------------
764  *              InsertOneNull
765  * ----------------
766  */
767 void
768 InsertOneNull(int i)
769 {
770         elog(DEBUG3, "inserting column %d NULL", i);
771         Assert(i >= 0 || i < MAXATTR);
772         values[i] = PointerGetDatum(NULL);
773         Blanks[i] = 'n';
774 }
775
776 #define MORE_THAN_THE_NUMBER_OF_CATALOGS 256
777
778 static bool
779 BootstrapAlreadySeen(Oid id)
780 {
781         static Oid      seenArray[MORE_THAN_THE_NUMBER_OF_CATALOGS];
782         static int      nseen = 0;
783         bool            seenthis;
784         int                     i;
785
786         seenthis = false;
787
788         for (i = 0; i < nseen; i++)
789         {
790                 if (seenArray[i] == id)
791                 {
792                         seenthis = true;
793                         break;
794                 }
795         }
796         if (!seenthis)
797         {
798                 seenArray[nseen] = id;
799                 nseen++;
800         }
801         return seenthis;
802 }
803
804 /* ----------------
805  *              cleanup
806  * ----------------
807  */
808 static void
809 cleanup()
810 {
811         static int      beenhere = 0;
812
813         if (!beenhere)
814                 beenhere = 1;
815         else
816         {
817                 elog(FATAL, "Memory manager fault: cleanup called twice.\n");
818                 proc_exit(1);
819         }
820         if (boot_reldesc != NULL)
821                 closerel(NULL);
822         CommitTransactionCommand(true);
823         proc_exit(Warnings);
824 }
825
826 /* ----------------
827  *              gettype
828  *
829  * NB: this is really ugly; it will return an integer index into Procid[],
830  * and not an OID at all, until the first reference to a type not known in
831  * Procid[].  At that point it will read and cache pg_type in the Typ array,
832  * and subsequently return a real OID (and set the global pointer Ap to
833  * point at the found row in Typ).      So caller must check whether Typ is
834  * still NULL to determine what the return value is!
835  * ----------------
836  */
837 static Oid
838 gettype(char *type)
839 {
840         int                     i;
841         Relation        rel;
842         HeapScanDesc scan;
843         HeapTuple       tup;
844         struct typmap **app;
845
846         if (Typ != (struct typmap **) NULL)
847         {
848                 for (app = Typ; *app != (struct typmap *) NULL; app++)
849                 {
850                         if (strncmp(NameStr((*app)->am_typ.typname), type, NAMEDATALEN) == 0)
851                         {
852                                 Ap = *app;
853                                 return (*app)->am_oid;
854                         }
855                 }
856         }
857         else
858         {
859                 for (i = 0; i < n_types; i++)
860                 {
861                         if (strncmp(type, Procid[i].name, NAMEDATALEN) == 0)
862                                 return i;
863                 }
864                 elog(DEBUG3, "external type: %s", type);
865                 rel = heap_openr(TypeRelationName, NoLock);
866                 scan = heap_beginscan(rel, SnapshotNow, 0, (ScanKey) NULL);
867                 i = 0;
868                 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
869                         ++i;
870                 heap_endscan(scan);
871                 app = Typ = ALLOC(struct typmap *, i + 1);
872                 while (i-- > 0)
873                         *app++ = ALLOC(struct typmap, 1);
874                 *app = (struct typmap *) NULL;
875                 scan = heap_beginscan(rel, SnapshotNow, 0, (ScanKey) NULL);
876                 app = Typ;
877                 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
878                 {
879                         (*app)->am_oid = HeapTupleGetOid(tup);
880                         memmove((char *) &(*app++)->am_typ,
881                                         (char *) GETSTRUCT(tup),
882                                         sizeof((*app)->am_typ));
883                 }
884                 heap_endscan(scan);
885                 heap_close(rel, NoLock);
886                 return gettype(type);
887         }
888         elog(ERROR, "Error: unknown type '%s'.\n", type);
889         err_out();
890         /* not reached, here to make compiler happy */
891         return 0;
892 }
893
894 /* ----------------
895  *              AllocateAttribute
896  * ----------------
897  */
898 static Form_pg_attribute
899 AllocateAttribute(void)
900 {
901         Form_pg_attribute attribute = (Form_pg_attribute) malloc(ATTRIBUTE_TUPLE_SIZE);
902
903         if (!PointerIsValid(attribute))
904                 elog(FATAL, "AllocateAttribute: malloc failed");
905         MemSet(attribute, 0, ATTRIBUTE_TUPLE_SIZE);
906
907         return attribute;
908 }
909
910 /* ----------------
911  *              MapArrayTypeName
912  * XXX arrays of "basetype" are always "_basetype".
913  *         this is an evil hack inherited from rel. 3.1.
914  * XXX array dimension is thrown away because we
915  *         don't support fixed-dimension arrays.  again,
916  *         sickness from 3.1.
917  *
918  * the string passed in must have a '[' character in it
919  *
920  * the string returned is a pointer to static storage and should NOT
921  * be freed by the CALLER.
922  * ----------------
923  */
924 char *
925 MapArrayTypeName(char *s)
926 {
927         int                     i,
928                                 j;
929         static char newStr[NAMEDATALEN];        /* array type names < NAMEDATALEN
930                                                                                  * long */
931
932         if (s == NULL || s[0] == '\0')
933                 return s;
934
935         j = 1;
936         newStr[0] = '_';
937         for (i = 0; i < NAMEDATALEN - 1 && s[i] != '['; i++, j++)
938                 newStr[j] = s[i];
939
940         newStr[j] = '\0';
941
942         return newStr;
943 }
944
945 /* ----------------
946  *              EnterString
947  *              returns the string table position of the identifier
948  *              passed to it.  We add it to the table if we can't find it.
949  * ----------------
950  */
951 int
952 EnterString(char *str)
953 {
954         hashnode   *node;
955         int                     len;
956
957         len = strlen(str);
958
959         node = FindStr(str, len, 0);
960         if (node)
961                 return node->strnum;
962         else
963         {
964                 node = AddStr(str, len, 0);
965                 return node->strnum;
966         }
967 }
968
969 /* ----------------
970  *              LexIDStr
971  *              when given an idnum into the 'string-table' return the string
972  *              associated with the idnum
973  * ----------------
974  */
975 char *
976 LexIDStr(int ident_num)
977 {
978         return strtable[ident_num];
979 }
980
981
982 /* ----------------
983  *              CompHash
984  *
985  *              Compute a hash function for a given string.  We look at the first,
986  *              the last, and the middle character of a string to try to get spread
987  *              the strings out.  The function is rather arbitrary, except that we
988  *              are mod'ing by a prime number.
989  * ----------------
990  */
991 static int
992 CompHash(char *str, int len)
993 {
994         int                     result;
995
996         result = (NUM * str[0] + NUMSQR * str[len - 1] + NUMCUBE * str[(len - 1) / 2]);
997
998         return result % HASHTABLESIZE;
999
1000 }
1001
1002 /* ----------------
1003  *              FindStr
1004  *
1005  *              This routine looks for the specified string in the hash
1006  *              table.  It returns a pointer to the hash node found,
1007  *              or NULL if the string is not in the table.
1008  * ----------------
1009  */
1010 static hashnode *
1011 FindStr(char *str, int length, hashnode *mderef)
1012 {
1013         hashnode   *node;
1014
1015         node = hashtable[CompHash(str, length)];
1016         while (node != NULL)
1017         {
1018                 /*
1019                  * We must differentiate between string constants that might have
1020                  * the same value as a identifier and the identifier itself.
1021                  */
1022                 if (!strcmp(str, strtable[node->strnum]))
1023                 {
1024                         return node;            /* no need to check */
1025                 }
1026                 else
1027                         node = node->next;
1028         }
1029         /* Couldn't find it in the list */
1030         return NULL;
1031 }
1032
1033 /* ----------------
1034  *              AddStr
1035  *
1036  *              This function adds the specified string, along with its associated
1037  *              data, to the hash table and the string table.  We return the node
1038  *              so that the calling routine can find out the unique id that AddStr
1039  *              has assigned to this string.
1040  * ----------------
1041  */
1042 static hashnode *
1043 AddStr(char *str, int strlength, int mderef)
1044 {
1045         hashnode   *temp,
1046                            *trail,
1047                            *newnode;
1048         int                     hashresult;
1049         int                     len;
1050
1051         if (++strtable_end == STRTABLESIZE)
1052         {
1053                 /* Error, string table overflow, so we Punt */
1054                 elog(FATAL,
1055                          "There are too many string constants and identifiers for the compiler to handle.");
1056
1057
1058         }
1059
1060         /*
1061          * Some of the utilites (eg, define type, create relation) assume that
1062          * the string they're passed is a NAMEDATALEN.  We get array bound
1063          * read violations from purify if we don't allocate at least
1064          * NAMEDATALEN bytes for strings of this sort.  Because we're lazy, we
1065          * allocate at least NAMEDATALEN bytes all the time.
1066          */
1067
1068         if ((len = strlength + 1) < NAMEDATALEN)
1069                 len = NAMEDATALEN;
1070
1071         strtable[strtable_end] = malloc((unsigned) len);
1072         strcpy(strtable[strtable_end], str);
1073
1074         /* Now put a node in the hash table */
1075
1076         newnode = (hashnode *) malloc(sizeof(hashnode) * 1);
1077         newnode->strnum = strtable_end;
1078         newnode->next = NULL;
1079
1080         /* Find out where it goes */
1081
1082         hashresult = CompHash(str, strlength);
1083         if (hashtable[hashresult] == NULL)
1084                 hashtable[hashresult] = newnode;
1085         else
1086         {                                                       /* There is something in the list */
1087                 trail = hashtable[hashresult];
1088                 temp = trail->next;
1089                 while (temp != NULL)
1090                 {
1091                         trail = temp;
1092                         temp = temp->next;
1093                 }
1094                 trail->next = newnode;
1095         }
1096         return newnode;
1097 }
1098
1099
1100
1101 /*
1102  *      index_register() -- record an index that has been set up for building
1103  *                                              later.
1104  *
1105  *              At bootstrap time, we define a bunch of indices on system catalogs.
1106  *              We postpone actually building the indices until just before we're
1107  *              finished with initialization, however.  This is because more classes
1108  *              and indices may be defined, and we want to be sure that all of them
1109  *              are present in the index.
1110  */
1111 void
1112 index_register(Oid heap,
1113                            Oid ind,
1114                            IndexInfo *indexInfo)
1115 {
1116         IndexList  *newind;
1117         MemoryContext oldcxt;
1118
1119         /*
1120          * XXX mao 10/31/92 -- don't gc index reldescs, associated info at
1121          * bootstrap time.      we'll declare the indices now, but want to create
1122          * them later.
1123          */
1124
1125         if (nogc == NULL)
1126                 nogc = AllocSetContextCreate((MemoryContext) NULL,
1127                                                                          "BootstrapNoGC",
1128                                                                          ALLOCSET_DEFAULT_MINSIZE,
1129                                                                          ALLOCSET_DEFAULT_INITSIZE,
1130                                                                          ALLOCSET_DEFAULT_MAXSIZE);
1131
1132         oldcxt = MemoryContextSwitchTo(nogc);
1133
1134         newind = (IndexList *) palloc(sizeof(IndexList));
1135         newind->il_heap = heap;
1136         newind->il_ind = ind;
1137         newind->il_info = (IndexInfo *) palloc(sizeof(IndexInfo));
1138
1139         memcpy(newind->il_info, indexInfo, sizeof(IndexInfo));
1140         /* predicate will likely be null, but may as well copy it */
1141         newind->il_info->ii_Predicate = (List *)
1142                 copyObject(indexInfo->ii_Predicate);
1143
1144         newind->il_next = ILHead;
1145         ILHead = newind;
1146
1147         MemoryContextSwitchTo(oldcxt);
1148 }
1149
1150 void
1151 build_indices()
1152 {
1153         for (; ILHead != (IndexList *) NULL; ILHead = ILHead->il_next)
1154         {
1155                 Relation        heap;
1156                 Relation        ind;
1157
1158                 heap = heap_open(ILHead->il_heap, NoLock);
1159                 ind = index_open(ILHead->il_ind);
1160                 index_build(heap, ind, ILHead->il_info);
1161
1162                 /*
1163                  * In normal processing mode, index_build would close the heap and
1164                  * index, but in bootstrap mode it will not.
1165                  */
1166
1167                 /*
1168                  * All of the rest of this routine is needed only because in
1169                  * bootstrap processing we don't increment xact id's.  The normal
1170                  * DefineIndex code replaces a pg_class tuple with updated info
1171                  * including the relhasindex flag (which we need to have updated).
1172                  * Unfortunately, there are always two indices defined on each
1173                  * catalog causing us to update the same pg_class tuple twice for
1174                  * each catalog getting an index during bootstrap resulting in the
1175                  * ghost tuple problem (see heap_update).       To get around this we
1176                  * change the relhasindex field ourselves in this routine keeping
1177                  * track of what catalogs we already changed so that we don't
1178                  * modify those tuples twice.  The normal mechanism for updating
1179                  * pg_class is disabled during bootstrap.
1180                  *
1181                  * -mer
1182                  */
1183                 if (!BootstrapAlreadySeen(RelationGetRelid(heap)))
1184                         UpdateStats(RelationGetRelid(heap), 0);
1185
1186                 /* XXX Probably we ought to close the heap and index here? */
1187         }
1188 }