]> granicus.if.org Git - postgresql/blob - src/backend/bootstrap/bootstrap.c
Reverse out XLogDir/-X write-ahead log handling, per discussion.
[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.138 2002/08/17 15:12:06 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         {
239                 MemoryContextInit();
240         }
241
242         /*
243          * process command arguments
244          */
245
246         /* Set defaults, to be overriden by explicit options below */
247         dbName = NULL;
248         if (!IsUnderPostmaster)
249         {
250                 InitializeGUCOptions();
251                 potential_DataDir = getenv("PGDATA");   /* Null if no PGDATA
252                                                                                                  * variable */
253         }
254
255         while ((flag = getopt(argc, argv, "B:d:D:Fo:px:")) != -1)
256         {
257                 switch (flag)
258                 {
259                         case 'D':
260                                 potential_DataDir = optarg;
261                                 break;
262                         case 'd':
263                         {
264                                 /* Turn on debugging for the bootstrap process. */
265                                 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
266                                 sprintf(debugstr, "debug%s", optarg);
267                                 SetConfigOption("server_min_messages", debugstr,
268                                                                 PGC_POSTMASTER, PGC_S_ARGV);
269                                 SetConfigOption("client_min_messages", debugstr,
270                                                                 PGC_POSTMASTER, PGC_S_ARGV);
271                                 pfree(debugstr);
272                                 break;
273                         }
274                         break;
275                         case 'F':
276                                 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
277                                 break;
278                         case 'o':
279                                 StrNCpy(OutputFileName, optarg, MAXPGPATH);
280                                 break;
281                         case 'x':
282                                 xlogop = atoi(optarg);
283                                 break;
284                         case 'p':
285                                 /* indicates fork from postmaster */
286                                 break;
287                         case 'B':
288                                 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
289                                 break;
290                         default:
291                                 usage();
292                                 break;
293                 }
294         }                                                       /* while */
295
296         if (argc - optind != 1)
297                 usage();
298
299         dbName = argv[optind];
300
301         Assert(dbName);
302
303         if (!IsUnderPostmaster)
304         {
305                 if (!potential_DataDir)
306                 {
307                         fprintf(stderr,
308                                         gettext("%s does not know where to find the database system data.\n"
309                                                         "You must specify the directory that contains the database system\n"
310                                                         "either by specifying the -D invocation option or by setting the\n"
311                                                         "PGDATA environment variable.\n\n"),
312                                         argv[0]);
313                         proc_exit(1);
314                 }
315                 SetDataDir(potential_DataDir);
316         }
317
318         /* Validate we have been given a reasonable-looking DataDir */
319         Assert(DataDir);
320         ValidatePgVersion(DataDir);
321
322         if (IsUnderPostmaster)
323         {
324                 /*
325                  * Properly accept or ignore signals the postmaster might send us
326                  */
327                 pqsignal(SIGHUP, SIG_IGN);
328                 pqsignal(SIGINT, SIG_IGN);              /* ignore query-cancel */
329                 pqsignal(SIGTERM, die);
330                 pqsignal(SIGQUIT, quickdie);
331                 pqsignal(SIGALRM, SIG_IGN);
332                 pqsignal(SIGPIPE, SIG_IGN);
333                 pqsignal(SIGUSR1, SIG_IGN);
334                 pqsignal(SIGUSR2, SIG_IGN);
335
336                 /*
337                  * Reset some signals that are accepted by postmaster but not here
338                  */
339                 pqsignal(SIGCHLD, SIG_DFL);
340                 pqsignal(SIGTTIN, SIG_DFL);
341                 pqsignal(SIGTTOU, SIG_DFL);
342                 pqsignal(SIGCONT, SIG_DFL);
343                 pqsignal(SIGWINCH, SIG_DFL);
344
345                 /*
346                  * Unblock signals (they were blocked when the postmaster forked
347                  * us)
348                  */
349                 PG_SETMASK(&UnBlockSig);
350         }
351         else
352         {
353                 /* Set up appropriately for interactive use */
354                 pqsignal(SIGHUP, die);
355                 pqsignal(SIGINT, die);
356                 pqsignal(SIGTERM, die);
357                 pqsignal(SIGQUIT, die);
358
359                 /*
360                  * Create lockfile for data directory.
361                  */
362                 if (!CreateDataDirLockFile(DataDir, false))
363                         proc_exit(1);
364         }
365
366         SetProcessingMode(BootstrapProcessing);
367         IgnoreSystemIndexes(true);
368
369         XLOGPathInit();
370
371         BaseInit();
372
373         /*
374          * XLOG operations
375          */
376         SetProcessingMode(NormalProcessing);
377
378         switch (xlogop)
379         {
380                 case BS_XLOG_NOP:
381                         StartupXLOG();
382                         break;
383
384                 case BS_XLOG_BOOTSTRAP:
385                         BootStrapXLOG();
386                         StartupXLOG();
387                         break;
388
389                 case BS_XLOG_CHECKPOINT:
390                         if (IsUnderPostmaster)
391                                 InitDummyProcess();             /* needed to get LWLocks */
392                         CreateDummyCaches();
393                         CreateCheckPoint(false);
394                         SetSavedRedoRecPtr(); /* pass redo ptr back to 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();
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                         AssertTupleDescHasOid(rel->rd_att);
497                         (*app)->am_oid = HeapTupleGetOid(tup);
498                         memcpy((char *) &(*app)->am_typ,
499                                    (char *) GETSTRUCT(tup),
500                                    sizeof((*app)->am_typ));
501                         app++;
502                 }
503                 heap_endscan(scan);
504                 heap_close(rel, NoLock);
505         }
506
507         if (boot_reldesc != NULL)
508                 closerel(NULL);
509
510         elog(DEBUG3, "open relation %s, attrsize %d", relname ? relname : "(null)",
511                  (int) ATTRIBUTE_TUPLE_SIZE);
512
513         boot_reldesc = heap_openr(relname, NoLock);
514         numattr = boot_reldesc->rd_rel->relnatts;
515         for (i = 0; i < numattr; i++)
516         {
517                 if (attrtypes[i] == NULL)
518                         attrtypes[i] = AllocateAttribute();
519                 memmove((char *) attrtypes[i],
520                                 (char *) boot_reldesc->rd_att->attrs[i],
521                                 ATTRIBUTE_TUPLE_SIZE);
522
523                 {
524                         Form_pg_attribute at = attrtypes[i];
525
526                         elog(DEBUG3, "create attribute %d name %s len %d num %d type %u",
527                                  i, NameStr(at->attname), at->attlen, at->attnum,
528                                  at->atttypid);
529                 }
530         }
531 }
532
533 /* ----------------
534  *              closerel
535  * ----------------
536  */
537 void
538 closerel(char *name)
539 {
540         if (name)
541         {
542                 if (boot_reldesc)
543                 {
544                         if (strcmp(RelationGetRelationName(boot_reldesc), name) != 0)
545                                 elog(ERROR, "closerel: close of '%s' when '%s' was expected",
546                                          name, relname ? relname : "(null)");
547                 }
548                 else
549                         elog(ERROR, "closerel: close of '%s' before any relation was opened",
550                                  name);
551         }
552
553         if (boot_reldesc == NULL)
554                 elog(ERROR, "no open relation to close");
555         else
556         {
557                 elog(DEBUG3, "close relation %s", relname ? relname : "(null)");
558                 heap_close(boot_reldesc, NoLock);
559                 boot_reldesc = (Relation) NULL;
560         }
561 }
562
563
564
565 /* ----------------
566  * DEFINEATTR()
567  *
568  * define a <field,type> pair
569  * if there are n fields in a relation to be created, this routine
570  * will be called n times
571  * ----------------
572  */
573 void
574 DefineAttr(char *name, char *type, int attnum)
575 {
576         int                     attlen;
577         Oid                     typeoid;
578
579         if (boot_reldesc != NULL)
580         {
581                 elog(LOG, "warning: no open relations allowed with 'create' command");
582                 closerel(relname);
583         }
584
585         if (attrtypes[attnum] == (Form_pg_attribute) NULL)
586                 attrtypes[attnum] = AllocateAttribute();
587         MemSet(attrtypes[attnum], 0, ATTRIBUTE_TUPLE_SIZE);
588
589         namestrcpy(&attrtypes[attnum]->attname, name);
590         elog(DEBUG3, "column %s %s", NameStr(attrtypes[attnum]->attname), type);
591         attrtypes[attnum]->attnum = 1 + attnum; /* fillatt */
592
593         typeoid = gettype(type);
594
595         if (Typ != (struct typmap **) NULL)
596         {
597                 attrtypes[attnum]->atttypid = Ap->am_oid;
598                 attlen = attrtypes[attnum]->attlen = Ap->am_typ.typlen;
599                 attrtypes[attnum]->attbyval = Ap->am_typ.typbyval;
600                 attrtypes[attnum]->attstorage = Ap->am_typ.typstorage;
601                 attrtypes[attnum]->attalign = Ap->am_typ.typalign;
602         }
603         else
604         {
605                 attrtypes[attnum]->atttypid = Procid[typeoid].oid;
606                 attlen = attrtypes[attnum]->attlen = Procid[typeoid].len;
607
608                 /*
609                  * Cheat like mad to fill in these items from the length only.
610                  * This only has to work for types that appear in Procid[].
611                  */
612                 switch (attlen)
613                 {
614                         case 1:
615                                 attrtypes[attnum]->attbyval = true;
616                                 attrtypes[attnum]->attstorage = 'p';
617                                 attrtypes[attnum]->attalign = 'c';
618                                 break;
619                         case 2:
620                                 attrtypes[attnum]->attbyval = true;
621                                 attrtypes[attnum]->attstorage = 'p';
622                                 attrtypes[attnum]->attalign = 's';
623                                 break;
624                         case 4:
625                                 attrtypes[attnum]->attbyval = true;
626                                 attrtypes[attnum]->attstorage = 'p';
627                                 attrtypes[attnum]->attalign = 'i';
628                                 break;
629                         case -1:
630                                 attrtypes[attnum]->attbyval = false;
631                                 attrtypes[attnum]->attstorage = 'x';
632                                 attrtypes[attnum]->attalign = 'i';
633                                 break;
634                         default:
635                                 /* TID and fixed-length arrays, such as oidvector */
636                                 attrtypes[attnum]->attbyval = false;
637                                 attrtypes[attnum]->attstorage = 'p';
638                                 attrtypes[attnum]->attalign = 'i';
639                                 break;
640                 }
641         }
642         attrtypes[attnum]->attcacheoff = -1;
643         attrtypes[attnum]->atttypmod = -1;
644         /*
645          * Mark as "not null" if type is fixed-width and prior columns are too.
646          * This corresponds to case where column can be accessed directly via
647          * 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, attrtypes);
681         tupDesc->tdhasoid = BoolToHasOid(RelationGetForm(boot_reldesc)->relhasoids);
682         tuple = heap_formtuple(tupDesc, values, Blanks);
683
684         if (objectid != (Oid) 0)
685         {
686                 AssertTupleDescHasOid(tupDesc);
687                 HeapTupleSetOid(tuple, objectid);
688         }
689         pfree(tupDesc);                         /* just free's tupDesc, not the attrtypes */
690         simple_heap_insert(boot_reldesc, tuple);
691         heap_freetuple(tuple);
692         elog(DEBUG3, "row inserted");
693
694         /*
695          * Reset blanks for next tuple
696          */
697         for (i = 0; i < numattr; i++)
698                 Blanks[i] = ' ';
699 }
700
701 /* ----------------
702  *              InsertOneValue
703  * ----------------
704  */
705 void
706 InsertOneValue(char *value, int i)
707 {
708         int                     typeindex;
709         char       *prt;
710         struct typmap **app;
711
712         AssertArg(i >= 0 || i < MAXATTR);
713
714         elog(DEBUG3, "inserting column %d value '%s'", i, value);
715
716         if (Typ != (struct typmap **) NULL)
717         {
718                 struct typmap *ap;
719
720                 elog(DEBUG3, "Typ != NULL");
721                 app = Typ;
722                 while (*app && (*app)->am_oid != boot_reldesc->rd_att->attrs[i]->atttypid)
723                         ++app;
724                 ap = *app;
725                 if (ap == NULL)
726                 {
727                         elog(FATAL, "unable to find atttypid %u in Typ list",
728                                  boot_reldesc->rd_att->attrs[i]->atttypid);
729                 }
730                 values[i] = OidFunctionCall3(ap->am_typ.typinput,
731                                                                          CStringGetDatum(value),
732                                                                          ObjectIdGetDatum(ap->am_typ.typelem),
733                                                                          Int32GetDatum(-1));
734                 prt = DatumGetCString(OidFunctionCall3(ap->am_typ.typoutput,
735                                                                                            values[i],
736                                                                         ObjectIdGetDatum(ap->am_typ.typelem),
737                                                                                            Int32GetDatum(-1)));
738                 elog(DEBUG3, " -> %s", prt);
739                 pfree(prt);
740         }
741         else
742         {
743                 for (typeindex = 0; typeindex < n_types; typeindex++)
744                 {
745                         if (Procid[typeindex].oid == attrtypes[i]->atttypid)
746                                 break;
747                 }
748                 if (typeindex >= n_types)
749                         elog(ERROR, "type oid %u not found", attrtypes[i]->atttypid);
750                 elog(DEBUG3, "Typ == NULL, typeindex = %u", typeindex);
751                 values[i] = OidFunctionCall3(Procid[typeindex].inproc,
752                                                                          CStringGetDatum(value),
753                                                                 ObjectIdGetDatum(Procid[typeindex].elem),
754                                                                          Int32GetDatum(-1));
755                 prt = DatumGetCString(OidFunctionCall3(Procid[typeindex].outproc,
756                                                                                            values[i],
757                                                                 ObjectIdGetDatum(Procid[typeindex].elem),
758                                                                                            Int32GetDatum(-1)));
759                 elog(DEBUG3, " -> %s", prt);
760                 pfree(prt);
761         }
762         elog(DEBUG3, "inserted");
763 }
764
765 /* ----------------
766  *              InsertOneNull
767  * ----------------
768  */
769 void
770 InsertOneNull(int i)
771 {
772         elog(DEBUG3, "inserting column %d NULL", i);
773         Assert(i >= 0 || i < MAXATTR);
774         values[i] = PointerGetDatum(NULL);
775         Blanks[i] = 'n';
776 }
777
778 #define MORE_THAN_THE_NUMBER_OF_CATALOGS 256
779
780 static bool
781 BootstrapAlreadySeen(Oid id)
782 {
783         static Oid      seenArray[MORE_THAN_THE_NUMBER_OF_CATALOGS];
784         static int      nseen = 0;
785         bool            seenthis;
786         int                     i;
787
788         seenthis = false;
789
790         for (i = 0; i < nseen; i++)
791         {
792                 if (seenArray[i] == id)
793                 {
794                         seenthis = true;
795                         break;
796                 }
797         }
798         if (!seenthis)
799         {
800                 seenArray[nseen] = id;
801                 nseen++;
802         }
803         return seenthis;
804 }
805
806 /* ----------------
807  *              cleanup
808  * ----------------
809  */
810 static void
811 cleanup()
812 {
813         static int      beenhere = 0;
814
815         if (!beenhere)
816                 beenhere = 1;
817         else
818         {
819                 elog(FATAL, "Memory manager fault: cleanup called twice.\n");
820                 proc_exit(1);
821         }
822         if (boot_reldesc != NULL)
823                 closerel(NULL);
824         CommitTransactionCommand();
825         proc_exit(Warnings);
826 }
827
828 /* ----------------
829  *              gettype
830  *
831  * NB: this is really ugly; it will return an integer index into Procid[],
832  * and not an OID at all, until the first reference to a type not known in
833  * Procid[].  At that point it will read and cache pg_type in the Typ array,
834  * and subsequently return a real OID (and set the global pointer Ap to
835  * point at the found row in Typ).  So caller must check whether Typ is
836  * still NULL to determine what the return value is!
837  * ----------------
838  */
839 static Oid
840 gettype(char *type)
841 {
842         int                     i;
843         Relation        rel;
844         HeapScanDesc scan;
845         HeapTuple       tup;
846         struct typmap **app;
847
848         if (Typ != (struct typmap **) NULL)
849         {
850                 for (app = Typ; *app != (struct typmap *) NULL; app++)
851                 {
852                         if (strncmp(NameStr((*app)->am_typ.typname), type, NAMEDATALEN) == 0)
853                         {
854                                 Ap = *app;
855                                 return (*app)->am_oid;
856                         }
857                 }
858         }
859         else
860         {
861                 for (i = 0; i < n_types; i++)
862                 {
863                         if (strncmp(type, Procid[i].name, NAMEDATALEN) == 0)
864                                 return i;
865                 }
866                 elog(DEBUG3, "external type: %s", type);
867                 rel = heap_openr(TypeRelationName, NoLock);
868                 scan = heap_beginscan(rel, SnapshotNow, 0, (ScanKey) NULL);
869                 i = 0;
870                 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
871                         ++i;
872                 heap_endscan(scan);
873                 app = Typ = ALLOC(struct typmap *, i + 1);
874                 while (i-- > 0)
875                         *app++ = ALLOC(struct typmap, 1);
876                 *app = (struct typmap *) NULL;
877                 scan = heap_beginscan(rel, SnapshotNow, 0, (ScanKey) NULL);
878                 app = Typ;
879                 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
880                 {
881                         AssertTupleDescHasOid(rel->rd_att);
882                         (*app)->am_oid = HeapTupleGetOid(tup);
883                         memmove((char *) &(*app++)->am_typ,
884                                         (char *) GETSTRUCT(tup),
885                                         sizeof((*app)->am_typ));
886                 }
887                 heap_endscan(scan);
888                 heap_close(rel, NoLock);
889                 return gettype(type);
890         }
891         elog(ERROR, "Error: unknown type '%s'.\n", type);
892         err_out();
893         /* not reached, here to make compiler happy */
894         return 0;
895 }
896
897 /* ----------------
898  *              AllocateAttribute
899  * ----------------
900  */
901 static Form_pg_attribute
902 AllocateAttribute(void)
903 {
904         Form_pg_attribute attribute = (Form_pg_attribute) malloc(ATTRIBUTE_TUPLE_SIZE);
905
906         if (!PointerIsValid(attribute))
907                 elog(FATAL, "AllocateAttribute: malloc failed");
908         MemSet(attribute, 0, ATTRIBUTE_TUPLE_SIZE);
909
910         return attribute;
911 }
912
913 /* ----------------
914  *              MapArrayTypeName
915  * XXX arrays of "basetype" are always "_basetype".
916  *         this is an evil hack inherited from rel. 3.1.
917  * XXX array dimension is thrown away because we
918  *         don't support fixed-dimension arrays.  again,
919  *         sickness from 3.1.
920  *
921  * the string passed in must have a '[' character in it
922  *
923  * the string returned is a pointer to static storage and should NOT
924  * be freed by the CALLER.
925  * ----------------
926  */
927 char *
928 MapArrayTypeName(char *s)
929 {
930         int                     i,
931                                 j;
932         static char newStr[NAMEDATALEN];        /* array type names < NAMEDATALEN
933                                                                                  * long */
934
935         if (s == NULL || s[0] == '\0')
936                 return s;
937
938         j = 1;
939         newStr[0] = '_';
940         for (i = 0; i < NAMEDATALEN - 1 && s[i] != '['; i++, j++)
941                 newStr[j] = s[i];
942
943         newStr[j] = '\0';
944
945         return newStr;
946 }
947
948 /* ----------------
949  *              EnterString
950  *              returns the string table position of the identifier
951  *              passed to it.  We add it to the table if we can't find it.
952  * ----------------
953  */
954 int
955 EnterString(char *str)
956 {
957         hashnode   *node;
958         int                     len;
959
960         len = strlen(str);
961
962         node = FindStr(str, len, 0);
963         if (node)
964                 return node->strnum;
965         else
966         {
967                 node = AddStr(str, len, 0);
968                 return node->strnum;
969         }
970 }
971
972 /* ----------------
973  *              LexIDStr
974  *              when given an idnum into the 'string-table' return the string
975  *              associated with the idnum
976  * ----------------
977  */
978 char *
979 LexIDStr(int ident_num)
980 {
981         return strtable[ident_num];
982 }
983
984
985 /* ----------------
986  *              CompHash
987  *
988  *              Compute a hash function for a given string.  We look at the first,
989  *              the last, and the middle character of a string to try to get spread
990  *              the strings out.  The function is rather arbitrary, except that we
991  *              are mod'ing by a prime number.
992  * ----------------
993  */
994 static int
995 CompHash(char *str, int len)
996 {
997         int                     result;
998
999         result = (NUM * str[0] + NUMSQR * str[len - 1] + NUMCUBE * str[(len - 1) / 2]);
1000
1001         return result % HASHTABLESIZE;
1002
1003 }
1004
1005 /* ----------------
1006  *              FindStr
1007  *
1008  *              This routine looks for the specified string in the hash
1009  *              table.  It returns a pointer to the hash node found,
1010  *              or NULL if the string is not in the table.
1011  * ----------------
1012  */
1013 static hashnode *
1014 FindStr(char *str, int length, hashnode *mderef)
1015 {
1016         hashnode   *node;
1017
1018         node = hashtable[CompHash(str, length)];
1019         while (node != NULL)
1020         {
1021                 /*
1022                  * We must differentiate between string constants that might have
1023                  * the same value as a identifier and the identifier itself.
1024                  */
1025                 if (!strcmp(str, strtable[node->strnum]))
1026                 {
1027                         return node;            /* no need to check */
1028                 }
1029                 else
1030                         node = node->next;
1031         }
1032         /* Couldn't find it in the list */
1033         return NULL;
1034 }
1035
1036 /* ----------------
1037  *              AddStr
1038  *
1039  *              This function adds the specified string, along with its associated
1040  *              data, to the hash table and the string table.  We return the node
1041  *              so that the calling routine can find out the unique id that AddStr
1042  *              has assigned to this string.
1043  * ----------------
1044  */
1045 static hashnode *
1046 AddStr(char *str, int strlength, int mderef)
1047 {
1048         hashnode   *temp,
1049                            *trail,
1050                            *newnode;
1051         int                     hashresult;
1052         int                     len;
1053
1054         if (++strtable_end == STRTABLESIZE)
1055         {
1056                 /* Error, string table overflow, so we Punt */
1057                 elog(FATAL,
1058                          "There are too many string constants and identifiers for the compiler to handle.");
1059
1060
1061         }
1062
1063         /*
1064          * Some of the utilites (eg, define type, create relation) assume that
1065          * the string they're passed is a NAMEDATALEN.  We get array bound
1066          * read violations from purify if we don't allocate at least
1067          * NAMEDATALEN bytes for strings of this sort.  Because we're lazy, we
1068          * allocate at least NAMEDATALEN bytes all the time.
1069          */
1070
1071         if ((len = strlength + 1) < NAMEDATALEN)
1072                 len = NAMEDATALEN;
1073
1074         strtable[strtable_end] = malloc((unsigned) len);
1075         strcpy(strtable[strtable_end], str);
1076
1077         /* Now put a node in the hash table */
1078
1079         newnode = (hashnode *) malloc(sizeof(hashnode) * 1);
1080         newnode->strnum = strtable_end;
1081         newnode->next = NULL;
1082
1083         /* Find out where it goes */
1084
1085         hashresult = CompHash(str, strlength);
1086         if (hashtable[hashresult] == NULL)
1087                 hashtable[hashresult] = newnode;
1088         else
1089         {                                                       /* There is something in the list */
1090                 trail = hashtable[hashresult];
1091                 temp = trail->next;
1092                 while (temp != NULL)
1093                 {
1094                         trail = temp;
1095                         temp = temp->next;
1096                 }
1097                 trail->next = newnode;
1098         }
1099         return newnode;
1100 }
1101
1102
1103
1104 /*
1105  *      index_register() -- record an index that has been set up for building
1106  *                                              later.
1107  *
1108  *              At bootstrap time, we define a bunch of indices on system catalogs.
1109  *              We postpone actually building the indices until just before we're
1110  *              finished with initialization, however.  This is because more classes
1111  *              and indices may be defined, and we want to be sure that all of them
1112  *              are present in the index.
1113  */
1114 void
1115 index_register(Oid heap,
1116                            Oid ind,
1117                            IndexInfo *indexInfo)
1118 {
1119         IndexList  *newind;
1120         MemoryContext oldcxt;
1121
1122         /*
1123          * XXX mao 10/31/92 -- don't gc index reldescs, associated info at
1124          * bootstrap time.      we'll declare the indices now, but want to create
1125          * them later.
1126          */
1127
1128         if (nogc == NULL)
1129                 nogc = AllocSetContextCreate((MemoryContext) NULL,
1130                                                                          "BootstrapNoGC",
1131                                                                          ALLOCSET_DEFAULT_MINSIZE,
1132                                                                          ALLOCSET_DEFAULT_INITSIZE,
1133                                                                          ALLOCSET_DEFAULT_MAXSIZE);
1134
1135         oldcxt = MemoryContextSwitchTo(nogc);
1136
1137         newind = (IndexList *) palloc(sizeof(IndexList));
1138         newind->il_heap = heap;
1139         newind->il_ind = ind;
1140         newind->il_info = (IndexInfo *) palloc(sizeof(IndexInfo));
1141
1142         memcpy(newind->il_info, indexInfo, sizeof(IndexInfo));
1143         /* predicate will likely be null, but may as well copy it */
1144         newind->il_info->ii_Predicate = (List *)
1145                 copyObject(indexInfo->ii_Predicate);
1146
1147         newind->il_next = ILHead;
1148         ILHead = newind;
1149
1150         MemoryContextSwitchTo(oldcxt);
1151 }
1152
1153 void
1154 build_indices()
1155 {
1156         for (; ILHead != (IndexList *) NULL; ILHead = ILHead->il_next)
1157         {
1158                 Relation        heap;
1159                 Relation        ind;
1160
1161                 heap = heap_open(ILHead->il_heap, NoLock);
1162                 ind = index_open(ILHead->il_ind);
1163                 index_build(heap, ind, ILHead->il_info);
1164
1165                 /*
1166                  * In normal processing mode, index_build would close the heap and
1167                  * index, but in bootstrap mode it will not.
1168                  */
1169
1170                 /*
1171                  * All of the rest of this routine is needed only because in
1172                  * bootstrap processing we don't increment xact id's.  The normal
1173                  * DefineIndex code replaces a pg_class tuple with updated info
1174                  * including the relhasindex flag (which we need to have updated).
1175                  * Unfortunately, there are always two indices defined on each
1176                  * catalog causing us to update the same pg_class tuple twice for
1177                  * each catalog getting an index during bootstrap resulting in the
1178                  * ghost tuple problem (see heap_update).       To get around this we
1179                  * change the relhasindex field ourselves in this routine keeping
1180                  * track of what catalogs we already changed so that we don't
1181                  * modify those tuples twice.  The normal mechanism for updating
1182                  * pg_class is disabled during bootstrap.
1183                  *
1184                  * -mer
1185                  */
1186                 if (!BootstrapAlreadySeen(RelationGetRelid(heap)))
1187                         UpdateStats(RelationGetRelid(heap), 0);
1188
1189                 /* XXX Probably we ought to close the heap and index here? */
1190         }
1191 }