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