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