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