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