OSDN Git Service

275b0579ffa8a6ecddf20a8de8ee212cc5d84c48
[pg-rex/syncrep.git] / 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.124 2002/03/15 19:20:34 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/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 static MemoryContext nogc = NULL;               /* special no-gc mem context */
144
145 extern int      optind;
146 extern char *optarg;
147
148 /*
149  *      At bootstrap time, we first declare all the indices to be built, and
150  *      then build them.  The IndexList structure stores enough information
151  *      to allow us to build the indices after they've been declared.
152  */
153
154 typedef struct _IndexList
155 {
156         char       *il_heap;
157         char       *il_ind;
158         IndexInfo  *il_info;
159         struct _IndexList *il_next;
160 } IndexList;
161
162 static IndexList *ILHead = (IndexList *) NULL;
163
164
165 /* ----------------------------------------------------------------
166  *                                              misc functions
167  * ----------------------------------------------------------------
168  */
169
170 /* ----------------
171  *              error handling / abort routines
172  * ----------------
173  */
174 void
175 err_out(void)
176 {
177         Warnings++;
178         cleanup();
179 }
180
181 /* usage:
182    usage help for the bootstrap backen
183 */
184 static void
185 usage(void)
186 {
187         fprintf(stderr,
188                         gettext("Usage:\n"
189         "  postgres -boot [-d level] [-D datadir] [-F] [-o file] [-x num] dbname\n"
190                                         "  -d 1-5           debug mode\n"
191                                         "  -D datadir       data directory\n"
192                                         "  -F               turn off fsync\n"
193                                         "  -o file          send debug output to file\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:d:D:Fo:px:")) != -1)
252         {
253                 switch (flag)
254                 {
255                         case 'D':
256                                 potential_DataDir = optarg;
257                                 break;
258                         case 'd':
259                         {
260                                 /* Turn on debugging for the postmaster. */
261                                 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
262                                 sprintf(debugstr, "debug%s", optarg);
263                                 /* We use PGC_S_SESSION because we will reset in backend */
264                                 SetConfigOption("server_min_messages", debugstr, PGC_POSTMASTER, PGC_S_ARGV);
265                                 SetConfigOption("client_min_messages", debugstr, PGC_POSTMASTER, PGC_S_ARGV);
266                                 pfree(debugstr);
267                                 break;
268                         }
269                         break;
270                         case 'F':
271                                 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
272                                 break;
273                         case 'o':
274                                 StrNCpy(OutputFileName, optarg, MAXPGPATH);
275                                 break;
276                         case 'x':
277                                 xlogop = atoi(optarg);
278                                 break;
279                         case 'p':
280                                 /* indicates fork from postmaster */
281                                 break;
282                         case 'B':
283                                 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
284                                 break;
285                         default:
286                                 usage();
287                                 break;
288                 }
289         }                                                       /* while */
290
291         if (argc - optind != 1)
292                 usage();
293
294         dbName = argv[optind];
295
296         Assert(dbName);
297
298         if (!IsUnderPostmaster)
299         {
300                 if (!potential_DataDir)
301                 {
302                         fprintf(stderr,
303                                         gettext("%s does not know where to find the database system data.\n"
304                                                         "You must specify the directory that contains the database system\n"
305                                                         "either by specifying the -D invocation option or by setting the\n"
306                                                         "PGDATA environment variable.\n\n"),
307                                         argv[0]);
308                         proc_exit(1);
309                 }
310                 SetDataDir(potential_DataDir);
311         }
312
313         /* Validate we have been given a reasonable-looking DataDir */
314         Assert(DataDir);
315         ValidatePgVersion(DataDir);
316
317         if (IsUnderPostmaster)
318         {
319                 /*
320                  * Properly accept or ignore signals the postmaster might send us
321                  */
322                 pqsignal(SIGHUP, SIG_IGN);
323                 pqsignal(SIGINT, SIG_IGN);              /* ignore query-cancel */
324                 pqsignal(SIGTERM, die);
325                 pqsignal(SIGQUIT, quickdie);
326                 pqsignal(SIGALRM, SIG_IGN);
327                 pqsignal(SIGPIPE, SIG_IGN);
328                 pqsignal(SIGUSR1, SIG_IGN);
329                 pqsignal(SIGUSR2, SIG_IGN);
330
331                 /*
332                  * Reset some signals that are accepted by postmaster but not here
333                  */
334                 pqsignal(SIGCHLD, SIG_DFL);
335                 pqsignal(SIGTTIN, SIG_DFL);
336                 pqsignal(SIGTTOU, SIG_DFL);
337                 pqsignal(SIGCONT, SIG_DFL);
338                 pqsignal(SIGWINCH, SIG_DFL);
339
340                 /*
341                  * Unblock signals (they were blocked when the postmaster forked
342                  * us)
343                  */
344                 PG_SETMASK(&UnBlockSig);
345         }
346         else
347         {
348                 /* Set up appropriately for interactive use */
349                 pqsignal(SIGHUP, die);
350                 pqsignal(SIGINT, die);
351                 pqsignal(SIGTERM, die);
352                 pqsignal(SIGQUIT, die);
353
354                 /*
355                  * Create lockfile for data directory.
356                  */
357                 if (!CreateDataDirLockFile(DataDir, false))
358                         proc_exit(1);
359         }
360
361         SetProcessingMode(BootstrapProcessing);
362         IgnoreSystemIndexes(true);
363
364         XLOGPathInit();
365
366         BaseInit();
367
368         /*
369          * XLOG operations
370          */
371         SetProcessingMode(NormalProcessing);
372
373         switch (xlogop)
374         {
375                 case BS_XLOG_NOP:
376                         StartupXLOG();
377                         break;
378
379                 case BS_XLOG_BOOTSTRAP:
380                         BootStrapXLOG();
381                         StartupXLOG();
382                         break;
383
384                 case BS_XLOG_CHECKPOINT:
385                         if (IsUnderPostmaster)
386                                 InitDummyProcess();             /* needed to get LWLocks */
387                         CreateDummyCaches();
388                         CreateCheckPoint(false);
389                         SetSavedRedoRecPtr(); /* pass redo ptr back to postmaster */
390                         proc_exit(0);           /* done */
391
392                 case BS_XLOG_STARTUP:
393                         StartupXLOG();
394                         proc_exit(0);           /* done */
395
396                 case BS_XLOG_SHUTDOWN:
397                         ShutdownXLOG();
398                         proc_exit(0);           /* done */
399
400                 default:
401                         elog(PANIC, "Unsupported XLOG op %d", xlogop);
402                         proc_exit(0);
403         }
404
405         SetProcessingMode(BootstrapProcessing);
406
407         /*
408          * backend initialization
409          */
410         InitPostgres(dbName, NULL);
411
412         for (i = 0; i < MAXATTR; i++)
413         {
414                 attrtypes[i] = (Form_pg_attribute) NULL;
415                 Blanks[i] = ' ';
416         }
417         for (i = 0; i < STRTABLESIZE; ++i)
418                 strtable[i] = NULL;
419         for (i = 0; i < HASHTABLESIZE; ++i)
420                 hashtable[i] = NULL;
421
422         /*
423          * abort processing resumes here
424          */
425         if (sigsetjmp(Warn_restart, 1) != 0)
426         {
427                 Warnings++;
428                 AbortCurrentTransaction();
429         }
430
431         /*
432          * process input.
433          */
434
435         /*
436          * the sed script boot.sed renamed yyparse to Int_yyparse for the
437          * bootstrap parser to avoid conflicts with the normal SQL parser
438          */
439         Int_yyparse();
440
441         SetProcessingMode(NormalProcessing);
442         CreateCheckPoint(true);
443         SetProcessingMode(BootstrapProcessing);
444
445         /* clean up processing */
446         StartTransactionCommand();
447         cleanup();
448
449         /* not reached, here to make compiler happy */
450         return 0;
451
452 }
453
454 /* ----------------------------------------------------------------
455  *                              MANUAL BACKEND INTERACTIVE INTERFACE COMMANDS
456  * ----------------------------------------------------------------
457  */
458
459 /* ----------------
460  *              boot_openrel
461  * ----------------
462  */
463 void
464 boot_openrel(char *relname)
465 {
466         int                     i;
467         struct typmap **app;
468         Relation        rel;
469         HeapScanDesc scan;
470         HeapTuple       tup;
471
472         if (strlen(relname) >= NAMEDATALEN - 1)
473                 relname[NAMEDATALEN - 1] = '\0';
474
475         if (Typ == (struct typmap **) NULL)
476         {
477                 rel = heap_openr(TypeRelationName, NoLock);
478                 scan = heap_beginscan(rel, 0, SnapshotNow, 0, (ScanKey) NULL);
479                 i = 0;
480                 while (HeapTupleIsValid(tup = heap_getnext(scan, 0)))
481                         ++i;
482                 heap_endscan(scan);
483                 app = Typ = ALLOC(struct typmap *, i + 1);
484                 while (i-- > 0)
485                         *app++ = ALLOC(struct typmap, 1);
486                 *app = (struct typmap *) NULL;
487                 scan = heap_beginscan(rel, 0, SnapshotNow, 0, (ScanKey) NULL);
488                 app = Typ;
489                 while (HeapTupleIsValid(tup = heap_getnext(scan, 0)))
490                 {
491                         (*app)->am_oid = tup->t_data->t_oid;
492                         memcpy((char *) &(*app)->am_typ,
493                                    (char *) GETSTRUCT(tup),
494                                    sizeof((*app)->am_typ));
495                         app++;
496                 }
497                 heap_endscan(scan);
498                 heap_close(rel, NoLock);
499         }
500
501         if (reldesc != NULL)
502                 closerel(NULL);
503
504         elog(DEBUG3, "open relation %s, attrsize %d", relname ? relname : "(null)",
505                  (int) ATTRIBUTE_TUPLE_SIZE);
506
507         reldesc = heap_openr(relname, NoLock);
508         numattr = reldesc->rd_rel->relnatts;
509         for (i = 0; i < numattr; i++)
510         {
511                 if (attrtypes[i] == NULL)
512                         attrtypes[i] = AllocateAttribute();
513                 memmove((char *) attrtypes[i],
514                                 (char *) reldesc->rd_att->attrs[i],
515                                 ATTRIBUTE_TUPLE_SIZE);
516
517                 /* Some old pg_attribute tuples might not have attisset. */
518
519                 /*
520                  * If the attname is attisset, don't look for it - it may not be
521                  * defined yet.
522                  */
523                 if (namestrcmp(&attrtypes[i]->attname, "attisset") == 0)
524                         attrtypes[i]->attisset = get_attisset(RelationGetRelid(reldesc),
525                                                                                  NameStr(attrtypes[i]->attname));
526                 else
527                         attrtypes[i]->attisset = false;
528
529                 {
530                         Form_pg_attribute at = attrtypes[i];
531
532                         elog(DEBUG3, "create attribute %d name %s len %d num %d type %u",
533                                  i, NameStr(at->attname), at->attlen, at->attnum,
534                                  at->atttypid);
535                 }
536         }
537 }
538
539 /* ----------------
540  *              closerel
541  * ----------------
542  */
543 void
544 closerel(char *name)
545 {
546         if (name)
547         {
548                 if (reldesc)
549                 {
550                         if (strcmp(RelationGetRelationName(reldesc), name) != 0)
551                                 elog(ERROR, "closerel: close of '%s' when '%s' was expected",
552                                          name, relname ? relname : "(null)");
553                 }
554                 else
555                         elog(ERROR, "closerel: close of '%s' before any relation was opened",
556                                  name);
557
558         }
559
560         if (reldesc == NULL)
561                 elog(ERROR, "no open relation to close");
562         else
563         {
564                 elog(DEBUG3, "close relation %s", relname ? relname : "(null)");
565                 heap_close(reldesc, NoLock);
566                 reldesc = (Relation) NULL;
567         }
568 }
569
570
571
572 /* ----------------
573  * DEFINEATTR()
574  *
575  * define a <field,type> pair
576  * if there are n fields in a relation to be created, this routine
577  * will be called n times
578  * ----------------
579  */
580 void
581 DefineAttr(char *name, char *type, int attnum)
582 {
583         int                     attlen;
584         Oid                     typeoid;
585
586         if (reldesc != NULL)
587         {
588                 elog(LOG, "warning: no open relations allowed with 'create' command");
589                 closerel(relname);
590         }
591
592         typeoid = gettype(type);
593         if (attrtypes[attnum] == (Form_pg_attribute) NULL)
594                 attrtypes[attnum] = AllocateAttribute();
595         if (Typ != (struct typmap **) NULL)
596         {
597                 attrtypes[attnum]->atttypid = Ap->am_oid;
598                 namestrcpy(&attrtypes[attnum]->attname, name);
599                 elog(DEBUG3, "column %s %s", NameStr(attrtypes[attnum]->attname), type);
600                 attrtypes[attnum]->attnum = 1 + attnum; /* fillatt */
601                 attlen = attrtypes[attnum]->attlen = Ap->am_typ.typlen;
602                 attrtypes[attnum]->attbyval = Ap->am_typ.typbyval;
603                 attrtypes[attnum]->attstorage = Ap->am_typ.typstorage;;
604                 attrtypes[attnum]->attalign = Ap->am_typ.typalign;
605         }
606         else
607         {
608                 attrtypes[attnum]->atttypid = Procid[typeoid].oid;
609                 namestrcpy(&attrtypes[attnum]->attname, name);
610                 elog(DEBUG3, "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         elog(DEBUG3, "inserting row oid %u, %d columns", objectid, numattr);
659
660         tupDesc = CreateTupleDesc(numattr, attrtypes);
661         tuple = heap_formtuple(tupDesc, values, Blanks);
662         pfree(tupDesc);                         /* just free's tupDesc, not the attrtypes */
663
664         if (objectid != (Oid) 0)
665                 tuple->t_data->t_oid = objectid;
666         heap_insert(reldesc, tuple);
667         heap_freetuple(tuple);
668         elog(DEBUG3, "row inserted");
669
670         /*
671          * Reset blanks for next tuple
672          */
673         for (i = 0; i < numattr; i++)
674                 Blanks[i] = ' ';
675 }
676
677 /* ----------------
678  *              InsertOneValue
679  * ----------------
680  */
681 void
682 InsertOneValue(char *value, int i)
683 {
684         int                     typeindex;
685         char       *prt;
686         struct typmap **app;
687
688         AssertArg(i >= 0 || i < MAXATTR);
689
690         elog(DEBUG3, "inserting column %d value '%s'", i, value);
691
692         if (Typ != (struct typmap **) NULL)
693         {
694                 struct typmap *ap;
695
696                 elog(DEBUG3, "Typ != NULL");
697                 app = Typ;
698                 while (*app && (*app)->am_oid != reldesc->rd_att->attrs[i]->atttypid)
699                         ++app;
700                 ap = *app;
701                 if (ap == NULL)
702                 {
703                         elog(FATAL, "unable to find atttypid %u in Typ list",
704                                  reldesc->rd_att->attrs[i]->atttypid);
705                 }
706                 values[i] = OidFunctionCall3(ap->am_typ.typinput,
707                                                                          CStringGetDatum(value),
708                                                                          ObjectIdGetDatum(ap->am_typ.typelem),
709                                                                          Int32GetDatum(-1));
710                 prt = DatumGetCString(OidFunctionCall3(ap->am_typ.typoutput,
711                                                                                            values[i],
712                                                                         ObjectIdGetDatum(ap->am_typ.typelem),
713                                                                                            Int32GetDatum(-1)));
714                 elog(DEBUG3, " -> %s", prt);
715                 pfree(prt);
716         }
717         else
718         {
719                 for (typeindex = 0; typeindex < n_types; typeindex++)
720                 {
721                         if (Procid[typeindex].oid == attrtypes[i]->atttypid)
722                                 break;
723                 }
724                 if (typeindex >= n_types)
725                         elog(ERROR, "type oid %u not found", attrtypes[i]->atttypid);
726                 elog(DEBUG3, "Typ == NULL, typeindex = %u", typeindex);
727                 values[i] = OidFunctionCall3(Procid[typeindex].inproc,
728                                                                          CStringGetDatum(value),
729                                                                 ObjectIdGetDatum(Procid[typeindex].elem),
730                                                                          Int32GetDatum(-1));
731                 prt = DatumGetCString(OidFunctionCall3(Procid[typeindex].outproc,
732                                                                                            values[i],
733                                                                 ObjectIdGetDatum(Procid[typeindex].elem),
734                                                                                            Int32GetDatum(-1)));
735                 elog(DEBUG3, " -> %s", prt);
736                 pfree(prt);
737         }
738         elog(DEBUG3, "inserted");
739 }
740
741 /* ----------------
742  *              InsertOneNull
743  * ----------------
744  */
745 void
746 InsertOneNull(int i)
747 {
748         elog(DEBUG3, "inserting column %d NULL", i);
749         Assert(i >= 0 || i < MAXATTR);
750         values[i] = PointerGetDatum(NULL);
751         Blanks[i] = 'n';
752 }
753
754 #define MORE_THAN_THE_NUMBER_OF_CATALOGS 256
755
756 static bool
757 BootstrapAlreadySeen(Oid id)
758 {
759         static Oid      seenArray[MORE_THAN_THE_NUMBER_OF_CATALOGS];
760         static int      nseen = 0;
761         bool            seenthis;
762         int                     i;
763
764         seenthis = false;
765
766         for (i = 0; i < nseen; i++)
767         {
768                 if (seenArray[i] == id)
769                 {
770                         seenthis = true;
771                         break;
772                 }
773         }
774         if (!seenthis)
775         {
776                 seenArray[nseen] = id;
777                 nseen++;
778         }
779         return seenthis;
780 }
781
782 /* ----------------
783  *              cleanup
784  * ----------------
785  */
786 static void
787 cleanup()
788 {
789         static int      beenhere = 0;
790
791         if (!beenhere)
792                 beenhere = 1;
793         else
794         {
795                 elog(FATAL, "Memory manager fault: cleanup called twice.\n");
796                 proc_exit(1);
797         }
798         if (reldesc != (Relation) NULL)
799                 heap_close(reldesc, NoLock);
800         CommitTransactionCommand();
801         proc_exit(Warnings);
802 }
803
804 /* ----------------
805  *              gettype
806  * ----------------
807  */
808 static Oid
809 gettype(char *type)
810 {
811         int                     i;
812         Relation        rel;
813         HeapScanDesc scan;
814         HeapTuple       tup;
815         struct typmap **app;
816
817         if (Typ != (struct typmap **) NULL)
818         {
819                 for (app = Typ; *app != (struct typmap *) NULL; app++)
820                 {
821                         if (strncmp(NameStr((*app)->am_typ.typname), type, NAMEDATALEN) == 0)
822                         {
823                                 Ap = *app;
824                                 return (*app)->am_oid;
825                         }
826                 }
827         }
828         else
829         {
830                 for (i = 0; i <= n_types; i++)
831                 {
832                         if (strncmp(type, Procid[i].name, NAMEDATALEN) == 0)
833                                 return i;
834                 }
835                 elog(DEBUG3, "external type: %s", type);
836                 rel = heap_openr(TypeRelationName, NoLock);
837                 scan = heap_beginscan(rel, 0, SnapshotNow, 0, (ScanKey) NULL);
838                 i = 0;
839                 while (HeapTupleIsValid(tup = heap_getnext(scan, 0)))
840                         ++i;
841                 heap_endscan(scan);
842                 app = Typ = ALLOC(struct typmap *, i + 1);
843                 while (i-- > 0)
844                         *app++ = ALLOC(struct typmap, 1);
845                 *app = (struct typmap *) NULL;
846                 scan = heap_beginscan(rel, 0, SnapshotNow, 0, (ScanKey) NULL);
847                 app = Typ;
848                 while (HeapTupleIsValid(tup = heap_getnext(scan, 0)))
849                 {
850                         (*app)->am_oid = tup->t_data->t_oid;
851                         memmove((char *) &(*app++)->am_typ,
852                                         (char *) GETSTRUCT(tup),
853                                         sizeof((*app)->am_typ));
854                 }
855                 heap_endscan(scan);
856                 heap_close(rel, NoLock);
857                 return gettype(type);
858         }
859         elog(ERROR, "Error: unknown type '%s'.\n", type);
860         err_out();
861         /* not reached, here to make compiler happy */
862         return 0;
863 }
864
865 /* ----------------
866  *              AllocateAttribute
867  * ----------------
868  */
869 static Form_pg_attribute                /* XXX */
870 AllocateAttribute()
871 {
872         Form_pg_attribute attribute = (Form_pg_attribute) malloc(ATTRIBUTE_TUPLE_SIZE);
873
874         if (!PointerIsValid(attribute))
875                 elog(FATAL, "AllocateAttribute: malloc failed");
876         MemSet(attribute, 0, ATTRIBUTE_TUPLE_SIZE);
877
878         return attribute;
879 }
880
881 /* ----------------
882  *              MapArrayTypeName
883  * XXX arrays of "basetype" are always "_basetype".
884  *         this is an evil hack inherited from rel. 3.1.
885  * XXX array dimension is thrown away because we
886  *         don't support fixed-dimension arrays.  again,
887  *         sickness from 3.1.
888  *
889  * the string passed in must have a '[' character in it
890  *
891  * the string returned is a pointer to static storage and should NOT
892  * be freed by the CALLER.
893  * ----------------
894  */
895 char *
896 MapArrayTypeName(char *s)
897 {
898         int                     i,
899                                 j;
900         static char newStr[NAMEDATALEN];        /* array type names < NAMEDATALEN
901                                                                                  * long */
902
903         if (s == NULL || s[0] == '\0')
904                 return s;
905
906         j = 1;
907         newStr[0] = '_';
908         for (i = 0; i < NAMEDATALEN - 1 && s[i] != '['; i++, j++)
909                 newStr[j] = s[i];
910
911         newStr[j] = '\0';
912
913         return newStr;
914 }
915
916 /* ----------------
917  *              EnterString
918  *              returns the string table position of the identifier
919  *              passed to it.  We add it to the table if we can't find it.
920  * ----------------
921  */
922 int
923 EnterString(char *str)
924 {
925         hashnode   *node;
926         int                     len;
927
928         len = strlen(str);
929
930         node = FindStr(str, len, 0);
931         if (node)
932                 return node->strnum;
933         else
934         {
935                 node = AddStr(str, len, 0);
936                 return node->strnum;
937         }
938 }
939
940 /* ----------------
941  *              LexIDStr
942  *              when given an idnum into the 'string-table' return the string
943  *              associated with the idnum
944  * ----------------
945  */
946 char *
947 LexIDStr(int ident_num)
948 {
949         return strtable[ident_num];
950 }
951
952
953 /* ----------------
954  *              CompHash
955  *
956  *              Compute a hash function for a given string.  We look at the first,
957  *              the last, and the middle character of a string to try to get spread
958  *              the strings out.  The function is rather arbitrary, except that we
959  *              are mod'ing by a prime number.
960  * ----------------
961  */
962 static int
963 CompHash(char *str, int len)
964 {
965         int                     result;
966
967         result = (NUM * str[0] + NUMSQR * str[len - 1] + NUMCUBE * str[(len - 1) / 2]);
968
969         return result % HASHTABLESIZE;
970
971 }
972
973 /* ----------------
974  *              FindStr
975  *
976  *              This routine looks for the specified string in the hash
977  *              table.  It returns a pointer to the hash node found,
978  *              or NULL if the string is not in the table.
979  * ----------------
980  */
981 static hashnode *
982 FindStr(char *str, int length, hashnode *mderef)
983 {
984         hashnode   *node;
985
986         node = hashtable[CompHash(str, length)];
987         while (node != NULL)
988         {
989                 /*
990                  * We must differentiate between string constants that might have
991                  * the same value as a identifier and the identifier itself.
992                  */
993                 if (!strcmp(str, strtable[node->strnum]))
994                 {
995                         return node;            /* no need to check */
996                 }
997                 else
998                         node = node->next;
999         }
1000         /* Couldn't find it in the list */
1001         return NULL;
1002 }
1003
1004 /* ----------------
1005  *              AddStr
1006  *
1007  *              This function adds the specified string, along with its associated
1008  *              data, to the hash table and the string table.  We return the node
1009  *              so that the calling routine can find out the unique id that AddStr
1010  *              has assigned to this string.
1011  * ----------------
1012  */
1013 static hashnode *
1014 AddStr(char *str, int strlength, int mderef)
1015 {
1016         hashnode   *temp,
1017                            *trail,
1018                            *newnode;
1019         int                     hashresult;
1020         int                     len;
1021
1022         if (++strtable_end == STRTABLESIZE)
1023         {
1024                 /* Error, string table overflow, so we Punt */
1025                 elog(FATAL,
1026                          "There are too many string constants and identifiers for the compiler to handle.");
1027
1028
1029         }
1030
1031         /*
1032          * Some of the utilites (eg, define type, create relation) assume that
1033          * the string they're passed is a NAMEDATALEN.  We get array bound
1034          * read violations from purify if we don't allocate at least
1035          * NAMEDATALEN bytes for strings of this sort.  Because we're lazy, we
1036          * allocate at least NAMEDATALEN bytes all the time.
1037          */
1038
1039         if ((len = strlength + 1) < NAMEDATALEN)
1040                 len = NAMEDATALEN;
1041
1042         strtable[strtable_end] = malloc((unsigned) len);
1043         strcpy(strtable[strtable_end], str);
1044
1045         /* Now put a node in the hash table */
1046
1047         newnode = (hashnode *) malloc(sizeof(hashnode) * 1);
1048         newnode->strnum = strtable_end;
1049         newnode->next = NULL;
1050
1051         /* Find out where it goes */
1052
1053         hashresult = CompHash(str, strlength);
1054         if (hashtable[hashresult] == NULL)
1055                 hashtable[hashresult] = newnode;
1056         else
1057         {                                                       /* There is something in the list */
1058                 trail = hashtable[hashresult];
1059                 temp = trail->next;
1060                 while (temp != NULL)
1061                 {
1062                         trail = temp;
1063                         temp = temp->next;
1064                 }
1065                 trail->next = newnode;
1066         }
1067         return newnode;
1068 }
1069
1070
1071
1072 /*
1073  *      index_register() -- record an index that has been set up for building
1074  *                                              later.
1075  *
1076  *              At bootstrap time, we define a bunch of indices on system catalogs.
1077  *              We postpone actually building the indices until just before we're
1078  *              finished with initialization, however.  This is because more classes
1079  *              and indices may be defined, and we want to be sure that all of them
1080  *              are present in the index.
1081  */
1082 void
1083 index_register(char *heap,
1084                            char *ind,
1085                            IndexInfo *indexInfo)
1086 {
1087         IndexList  *newind;
1088         MemoryContext oldcxt;
1089
1090         /*
1091          * XXX mao 10/31/92 -- don't gc index reldescs, associated info at
1092          * bootstrap time.      we'll declare the indices now, but want to create
1093          * them later.
1094          */
1095
1096         if (nogc == NULL)
1097                 nogc = AllocSetContextCreate((MemoryContext) NULL,
1098                                                                          "BootstrapNoGC",
1099                                                                          ALLOCSET_DEFAULT_MINSIZE,
1100                                                                          ALLOCSET_DEFAULT_INITSIZE,
1101                                                                          ALLOCSET_DEFAULT_MAXSIZE);
1102
1103         oldcxt = MemoryContextSwitchTo(nogc);
1104
1105         newind = (IndexList *) palloc(sizeof(IndexList));
1106         newind->il_heap = pstrdup(heap);
1107         newind->il_ind = pstrdup(ind);
1108         newind->il_info = (IndexInfo *) palloc(sizeof(IndexInfo));
1109
1110         memcpy(newind->il_info, indexInfo, sizeof(IndexInfo));
1111         /* predicate will likely be null, but may as well copy it */
1112         newind->il_info->ii_Predicate = (List *)
1113                 copyObject(indexInfo->ii_Predicate);
1114
1115         newind->il_next = ILHead;
1116         ILHead = newind;
1117
1118         MemoryContextSwitchTo(oldcxt);
1119 }
1120
1121 void
1122 build_indices()
1123 {
1124         for (; ILHead != (IndexList *) NULL; ILHead = ILHead->il_next)
1125         {
1126                 Relation        heap;
1127                 Relation        ind;
1128
1129                 heap = heap_openr(ILHead->il_heap, NoLock);
1130                 ind = index_openr(ILHead->il_ind);
1131                 index_build(heap, ind, ILHead->il_info);
1132
1133                 /*
1134                  * In normal processing mode, index_build would close the heap and
1135                  * index, but in bootstrap mode it will not.
1136                  */
1137
1138                 /*
1139                  * All of the rest of this routine is needed only because in
1140                  * bootstrap processing we don't increment xact id's.  The normal
1141                  * DefineIndex code replaces a pg_class tuple with updated info
1142                  * including the relhasindex flag (which we need to have updated).
1143                  * Unfortunately, there are always two indices defined on each
1144                  * catalog causing us to update the same pg_class tuple twice for
1145                  * each catalog getting an index during bootstrap resulting in the
1146                  * ghost tuple problem (see heap_update).       To get around this we
1147                  * change the relhasindex field ourselves in this routine keeping
1148                  * track of what catalogs we already changed so that we don't
1149                  * modify those tuples twice.  The normal mechanism for updating
1150                  * pg_class is disabled during bootstrap.
1151                  *
1152                  * -mer
1153                  */
1154                 if (!BootstrapAlreadySeen(RelationGetRelid(heap)))
1155                         UpdateStats(RelationGetRelid(heap), 0);
1156
1157                 /* XXX Probably we ought to close the heap and index here? */
1158         }
1159 }