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