From 7d1f2f8a270681f463a1ec5e433688248c58cc97 Mon Sep 17 00:00:00 2001
From: "Thomas G. Lockhart" <lockhart@fourpalms.org>
Date: Fri, 7 Nov 1997 06:38:51 +0000
Subject: [PATCH] Support alternate database locations.

---
 src/backend/parser/dbcommands.c   | 122 ++++++++---
 src/backend/storage/file/fd.c     |  28 +--
 src/backend/storage/smgr/md.c     |  11 +-
 src/backend/tcop/utility.c        |   4 +-
 src/backend/utils/init/postinit.c | 322 ++++++++++++------------------
 src/include/miscadmin.h           |   7 +-
 src/include/nodes/parsenodes.h    |   3 +-
 src/include/parser/dbcommands.h   |   4 +-
 8 files changed, 260 insertions(+), 241 deletions(-)

diff --git a/src/backend/parser/dbcommands.c b/src/backend/parser/dbcommands.c
index c39fa49404e..871cf245939 100644
--- a/src/backend/parser/dbcommands.c
+++ b/src/backend/parser/dbcommands.c
@@ -7,13 +7,14 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/parser/Attic/dbcommands.c,v 1.9 1997/09/08 21:46:07 momjian Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/parser/Attic/dbcommands.c,v 1.10 1997/11/07 06:37:55 thomas Exp $
  *
  *-------------------------------------------------------------------------
  */
 #include <stdio.h>
 #include <string.h>
 #include <signal.h>
+#include <sys/stat.h>
 
 #include "postgres.h"
 #include "miscadmin.h"			/* for DataDir */
@@ -36,41 +37,58 @@
 
 /* non-export function prototypes */
 static void
-check_permissions(char *command, char *dbname,
+check_permissions(char *command, char *dbpath, char *dbname,
 				  Oid *dbIdP, Oid *userIdP);
 static HeapTuple get_pg_dbtup(char *command, char *dbname, Relation dbrel);
-static void stop_vacuum(char *dbname);
+static void stop_vacuum(char *dbpath, char *dbname);
 
 void
-createdb(char *dbname)
+createdb(char *dbname, char *dbpath)
 {
 	Oid			db_id,
 				user_id;
 	char		buf[512];
+	char	   *lp,
+				loc[512];
 
 	/*
 	 * If this call returns, the database does not exist and we're allowed
 	 * to create databases.
 	 */
-	check_permissions("createdb", dbname, &db_id, &user_id);
+	check_permissions("createdb", dbpath, dbname, &db_id, &user_id);
 
 	/* close virtual file descriptors so we can do system() calls */
 	closeAllVfds();
 
-	sprintf(buf, "mkdir %s%cbase%c%s", DataDir, SEP_CHAR, SEP_CHAR, dbname);
-	system(buf);
-	sprintf(buf, "%s %s%cbase%ctemplate1%c* %s%cbase%c%s",
-			COPY_CMD, DataDir, SEP_CHAR, SEP_CHAR, SEP_CHAR, DataDir,
-			SEP_CHAR, SEP_CHAR, dbname);
+	/* Now create directory for this new database */
+	if ((dbpath != NULL) && (strcmp(dbpath,dbname) != 0))
+	{
+		if (*(dbpath+strlen(dbpath)-1) == SEP_CHAR)
+			*(dbpath+strlen(dbpath)-1) = '\0';
+		sprintf(loc, "%s%c%s", dbpath, SEP_CHAR, dbname);
+	}
+	else
+	{
+		strcpy(loc, dbname);
+	}
+
+	lp = ExpandDatabasePath(loc);
+
+	if (mkdir(lp,S_IRWXU) != 0)
+		elog(WARN,"Unable to create database directory %s",lp);
+
+	sprintf(buf, "%s %s%cbase%ctemplate1%c* %s",
+			COPY_CMD, DataDir, SEP_CHAR, SEP_CHAR, SEP_CHAR, lp);
 	system(buf);
 
-/*	  sprintf(buf, "insert into pg_database (datname, datdba, datpath) \
-                  values (\'%s\'::char16, \'%d\'::oid, \'%s\'::text);",
-			dbname, user_id, dbname);
-*/
+#if FALSE
 	sprintf(buf, "insert into pg_database (datname, datdba, datpath) \
-                  values (\'%s\', \'%d\', \'%s\');",
+                  values (\'%s\'::char16, \'%d\'::oid, \'%s\'::text);",
 			dbname, user_id, dbname);
+#endif
+
+	sprintf(buf, "insert into pg_database (datname, datdba, datpath)"
+		" values (\'%s\', \'%d\', \'%s\');", dbname, user_id, loc);
 
 	pg_eval(buf, (char **) NULL, (Oid *) NULL, 0);
 }
@@ -80,13 +98,20 @@ destroydb(char *dbname)
 {
 	Oid			user_id,
 				db_id;
+	char	   *path;
+	char		dbpath[MAXPGPATH+1];
 	char		buf[512];
+	char		loc[512];
+	text	   *dbtext;
+
+	Relation	dbrel;
+	HeapTuple	dbtup;
 
 	/*
 	 * If this call returns, the database exists and we're allowed to
 	 * remove it.
 	 */
-	check_permissions("destroydb", dbname, &db_id, &user_id);
+	check_permissions("destroydb", dbpath, dbname, &db_id, &user_id);
 
 	if (!OidIsValid(db_id))
 	{
@@ -94,7 +119,36 @@ destroydb(char *dbname)
 	}
 
 	/* stop the vacuum daemon */
-	stop_vacuum(dbname);
+	stop_vacuum(dbpath, dbname);
+
+#if FALSE
+	dbrel = heap_openr(DatabaseRelationName);
+	if (!RelationIsValid(dbrel))
+		elog(FATAL, "%s: cannot open relation \"%-.*s\"",
+			 "destroydb", DatabaseRelationName);
+
+	dbtup = get_pg_dbtup("destroydb", dbname, dbrel);
+
+	if (!HeapTupleIsValid(dbtup))
+		elog(NOTICE,"destroydb: pg_database entry not found %s",dbname);
+
+	dbtext = (text *) heap_getattr(dbtup, InvalidBuffer,
+								 Anum_pg_database_datpath,
+								 RelationGetTupleDescriptor(dbrel),
+								 (char *) NULL);
+	memcpy(loc, VARDATA(dbtext), (VARSIZE(dbtext)-VARHDRSZ));
+	*(loc+(VARSIZE(dbtext)-VARHDRSZ)) = '\0';
+
+#if FALSE
+	if (*loc != SEP_CHAR)
+	{
+		sprintf(buf, "%s/base/%s", DataDir, loc);
+		strcpy(loc, buf);
+	}
+#endif
+
+	heap_close(dbrel);
+#endif
 
 	/*
 	 * remove the pg_database tuple FIRST, this may fail due to
@@ -108,7 +162,9 @@ destroydb(char *dbname)
 	 * remove the data directory. If the DELETE above failed, this will
 	 * not be reached
 	 */
-	sprintf(buf, "rm -r %s/base/%s", DataDir, dbname);
+	path = ExpandDatabasePath(dbpath);
+
+	sprintf(buf, "rm -r %s", path);
 	system(buf);
 
 	/* drop pages for this database that are in the shared buffer cache */
@@ -160,6 +216,7 @@ get_pg_dbtup(char *command, char *dbname, Relation dbrel)
 
 static void
 check_permissions(char *command,
+				  char *dbpath,
 				  char *dbname,
 				  Oid *dbIdP,
 				  Oid *userIdP)
@@ -172,6 +229,8 @@ check_permissions(char *command,
 	bool		dbfound;
 	bool		use_super;
 	char	   *userName;
+	text	   *dbtext;
+	char		path[MAXPGPATH+1];
 
 	userName = GetPgUserName();
 	utup = SearchSysCacheTuple(USENAME, PointerGetDatum(userName),
@@ -228,6 +287,13 @@ check_permissions(char *command,
 									 RelationGetTupleDescriptor(dbrel),
 									 (char *) NULL);
 		*dbIdP = dbtup->t_oid;
+		dbtext = (text *) heap_getattr(dbtup, InvalidBuffer,
+								 Anum_pg_database_datpath,
+								 RelationGetTupleDescriptor(dbrel),
+								 (char *) NULL);
+
+		strncpy(path, VARDATA(dbtext), (VARSIZE(dbtext)-VARHDRSZ));
+		 *(path+VARSIZE(dbtext)-VARHDRSZ) = '\0';
 	}
 	else
 	{
@@ -259,21 +325,31 @@ check_permissions(char *command,
 		elog(WARN, "%s: database %s is not owned by you.", command, dbname);
 
 	}
-}
+
+	if (dbfound && !strcmp(command, "destroydb"))
+		strcpy(dbpath, path);
+} /* check_permissions() */
 
 /*
- *	stop_vacuum() -- stop the vacuum daemon on the database, if one is
- *					 running.
+ *	stop_vacuum() -- stop the vacuum daemon on the database, if one is running.
  */
 static void
-stop_vacuum(char *dbname)
+stop_vacuum(char *dbpath, char *dbname)
 {
 	char		filename[256];
 	FILE	   *fp;
 	int			pid;
 
-	sprintf(filename, "%s%cbase%c%s%c%s.vacuum", DataDir, SEP_CHAR, SEP_CHAR,
+	if (strchr(dbpath, SEP_CHAR) != 0)
+	{
+		sprintf(filename, "%s%cbase%c%s%c%s.vacuum", DataDir, SEP_CHAR, SEP_CHAR,
 			dbname, SEP_CHAR, dbname);
+	}
+	else
+	{
+		sprintf(filename, "%s%c%s.vacuum", dbpath, SEP_CHAR, dbname);
+	}
+
 	if ((fp = AllocateFile(filename, "r")) != NULL)
 	{
 		fscanf(fp, "%d", &pid);
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 4a4a943e938..c64b7c01096 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -6,7 +6,7 @@
  * Copyright (c) 1994, Regents of the University of California
  *
  * IDENTIFICATION
- *	  $Id: fd.c,v 1.26 1997/09/18 20:21:24 momjian Exp $
+ *	  $Id: fd.c,v 1.27 1997/11/07 06:38:15 thomas Exp $
  *
  * NOTES:
  *
@@ -125,8 +125,6 @@ static Size SizeVfdCache = 0;
  */
 static int	nfile = 0;
 
-static char Sep_char = '/';
-
 /*
  * Private Routines
  *
@@ -458,23 +456,25 @@ FreeVfd(File file)
 	VfdCache[0].nextFree = file;
 }
 
+/* filepath()
+ * Open specified file name.
+ * Fill in absolute path fields if necessary.
+ *
+ * Modify to use GetDatabasePath() rather than hardcoded paths.
+ * - thomas 1997-11-02
+ */
 static char *
 filepath(char *filename)
 {
 	char	   *buf;
-	char		basename[16];
 	int			len;
 
-	if (*filename != Sep_char)
+	/* Not an absolute path name? Then fill in with database path... */
+	if (*filename != SEP_CHAR)
 	{
-		/* Either /base/ or \base\ */
-		sprintf(basename, "%cbase%c", Sep_char, Sep_char);
-
-		len = strlen(DataDir) + strlen(basename) + strlen(GetDatabaseName())
-			+ strlen(filename) + 2;
+		len = strlen(GetDatabasePath()) + strlen(filename) + 2;
 		buf = (char *) palloc(len);
-		sprintf(buf, "%s%s%s%c%s",
-				DataDir, basename, GetDatabaseName(), Sep_char, filename);
+		sprintf(buf, "%s%c%s", GetDatabasePath(), SEP_CHAR, filename);
 	}
 	else
 	{
@@ -482,6 +482,10 @@ filepath(char *filename)
 		strcpy(buf, filename);
 	}
 
+#ifdef FILEDEBUG
+printf("filepath: path is %s\n", buf);
+#endif
+
 	return (buf);
 }
 
diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index 8be087d61b8..eaee63f2d48 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -7,7 +7,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/storage/smgr/md.c,v 1.23 1997/10/25 01:10:04 momjian Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/storage/smgr/md.c,v 1.24 1997/11/07 06:38:19 thomas Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -480,6 +480,7 @@ mdblindwrt(char *dbstr,
 		nchars = 0;
 
 	/* construct the path to the file and open it */
+	/* system table? then put in system area... */
 	if (dbid == (Oid) 0)
 	{
 		path = (char *) palloc(strlen(DataDir) + sizeof(NameData) + 2 + nchars);
@@ -488,8 +489,10 @@ mdblindwrt(char *dbstr,
 		else
 			sprintf(path, "%s/%s.%d", DataDir, relstr, segno);
 	}
+	/* user table? then put in user database area... */
 	else
 	{
+#if FALSE
 		path = (char *) palloc(strlen(DataDir) + strlen("/base/") + 2 * sizeof(NameData) + 2 + nchars);
 		if (segno == 0)
 			sprintf(path, "%s/base/%s/%s", DataDir,
@@ -497,6 +500,12 @@ mdblindwrt(char *dbstr,
 		else
 			sprintf(path, "%s/base/%s/%s.%d", DataDir, dbstr,
 					relstr, segno);
+#endif
+		path = (char *) palloc(strlen(GetDatabasePath()) + 2 * sizeof(NameData) + 2 + nchars);
+		if (segno == 0)
+			sprintf(path, "%s%c%s", GetDatabasePath(), SEP_CHAR, relstr);
+		else
+			sprintf(path, "%s%c%s.%d", GetDatabasePath(), SEP_CHAR, relstr, segno);
 	}
 
 	if ((fd = open(path, O_RDWR, 0600)) < 0)
diff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c
index 1fd20eb986a..9ffcf151d52 100644
--- a/src/backend/tcop/utility.c
+++ b/src/backend/tcop/utility.c
@@ -9,7 +9,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/tcop/utility.c,v 1.27 1997/10/28 14:57:24 vadim Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/tcop/utility.c,v 1.28 1997/11/07 06:38:51 thomas Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -569,7 +569,7 @@ ProcessUtility(Node * parsetree,
 
 				commandTag = "CREATEDB";
 				CHECK_IF_ABORTED();
-				createdb(stmt->dbname);
+				createdb(stmt->dbname, stmt->dbpath);
 			}
 			break;
 
diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c
index 47e7842d451..a6e670e5f6a 100644
--- a/src/backend/utils/init/postinit.c
+++ b/src/backend/utils/init/postinit.c
@@ -7,7 +7,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.14 1997/09/08 02:31:58 momjian Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.15 1997/11/07 06:38:46 thomas Exp $
  *
  * NOTES
  *		InitPostgres() is the function called from PostgresMain
@@ -50,7 +50,7 @@
 #include "access/transam.h"		/* XXX dependency problem */
 #include "utils/tqual.h"
 #include "utils/syscache.h"
-#include "storage/bufpage.h"	/* for page layout, for InitMyDatabaseId() */
+#include "storage/bufpage.h"	/* for page layout, for InitMyDatabaseInfo() */
 #include "storage/sinval.h"
 #include "storage/sinvaladt.h"
 #include "storage/lmgr.h"
@@ -70,11 +70,15 @@
 #include "port-protos.h"
 #include "libpq/libpq-be.h"
 
+static void VerifySystemDatabase(void);
+static void VerifyMyDatabase(void);
 static void InitCommunication(void);
-static void InitMyDatabaseId(void);
+static void InitMyDatabaseInfo(char *name);
 static void InitStdio(void);
 static void InitUserid(void);
 
+extern char *ExpandDatabasePath(char *name);
+extern void GetRawDatabaseInfo(char *name, Oid *owner, Oid *db_id, char *path);
 
 static IPCKey PostgresIpcKey;
 
@@ -84,7 +88,7 @@ static IPCKey PostgresIpcKey;
  */
 
 /* --------------------------------
- *	InitMyDatabaseId() -- Find and record the OID of the database we are
+ *	InitMyDatabaseInfo() -- Find and record the OID of the database we are
  *						  to open.
  *
  *		The database's oid forms half of the unique key for the system
@@ -98,133 +102,38 @@ static IPCKey PostgresIpcKey;
  *		about the internal format of tuples on disk and the length of
  *		the datname attribute.	It knows the location of the pg_database
  *		file.
+ *		Actually, the code looks as though it is using the pg_database
+ *		tuple definition to locate the database name, so the above statement
+ *		seems to be no longer correct. - thomas 1997-11-01
  *
- *		This code is called from InitDatabase(), after we chdir() to the
- *		database directory but before we open any relations.
+ *		This code is called from InitPostgres(), before we chdir() to the
+ *		local database directory and before we open any relations.
+ *		Used to be called after the chdir(), but we now want to confirm
+ *		the location of the target database using pg_database info.
+ *		- thomas 1997-11-01
  * --------------------------------
  */
 static void
-InitMyDatabaseId()
+InitMyDatabaseInfo(char *name)
 {
-	int			dbfd;
-	int			fileflags;
-	int			nbytes;
-	int			max,
-				i;
-	HeapTuple	tup;
-	Page		pg;
-	PageHeader	ph;
-	char	   *dbfname;
-	Form_pg_database tup_db;
+	Oid			owner;
+	char	   *path,
+				myPath[MAXPGPATH+1];
 
-	/*
-	 * At bootstrap time, we don't need to check the oid of the database
-	 * in use, since we're not using shared memory.  This is lucky, since
-	 * the database may not be in the tables yet.
-	 */
-
-	if (IsBootstrapProcessingMode())
-	{
-		LockDisable(true);
-		return;
-	}
-
-	dbfname = (char *) palloc(strlen(DataDir) + strlen("pg_database") + 2);
-	sprintf(dbfname, "%s%cpg_database", DataDir, SEP_CHAR);
-	fileflags = O_RDONLY;
-
-	if ((dbfd = open(dbfname, O_RDONLY, 0)) < 0)
-		elog(FATAL, "Cannot open %s", dbfname);
-
-	pfree(dbfname);
-
-	/* ----------------
-	 *	read and examine every page in pg_database
-	 *
-	 *	Raw I/O! Read those tuples the hard way! Yow!
-	 *
-	 *	Why don't we use the access methods or move this code
-	 *	someplace else?  This is really pg_database schema dependent
-	 *	code.  Perhaps it should go in lib/catalog/pg_database?
-	 *	-cim 10/3/90
-	 *
-	 *	mao replies 4 apr 91:  yeah, maybe this should be moved to
-	 *	lib/catalog.  however, we CANNOT use the access methods since
-	 *	those use the buffer cache, which uses the relation cache, which
-	 *	requires that the dbid be set, which is what we're trying to do
-	 *	here.
-	 * ----------------
-	 */
-	pg = (Page) palloc(BLCKSZ);
-	ph = (PageHeader) pg;
-
-	while ((nbytes = read(dbfd, pg, BLCKSZ)) == BLCKSZ)
-	{
-		max = PageGetMaxOffsetNumber(pg);
-
-		/* look at each tuple on the page */
-		for (i = 0; i <= max; i++)
-		{
-			int			offset;
-
-			/* if it's a freed tuple, ignore it */
-			if (!(ph->pd_linp[i].lp_flags & LP_USED))
-				continue;
-
-			/* get a pointer to the tuple itself */
-			offset = (int) ph->pd_linp[i].lp_off;
-			tup = (HeapTuple) (((char *) pg) + offset);
-
-			/*
-			 * if the tuple has been deleted (the database was destroyed),
-			 * skip this tuple.  XXX warning, will robinson:  violation of
-			 * transaction semantics happens right here.  we should check
-			 * to be sure that the xact that deleted this tuple actually
-			 * committed.  only way to do this at init time is to paw over
-			 * the log relation by hand, too.  let's be optimistic.
-			 *
-			 * XXX This is an evil type cast.  tup->t_xmax is char[5] while
-			 * TransactionId is struct * { char data[5] }.	It works but
-			 * if data is ever moved and no longer the first field this
-			 * will be broken!! -mer 11 Nov 1991.
-			 */
-			if (TransactionIdIsValid((TransactionId) tup->t_xmax))
-				continue;
-
-			/*
-			 * Okay, see if this is the one we want. XXX 1 july 91:  mao
-			 * and mer discover that tuples now squash t_bits.	Why is
-			 * this?
-			 *
-			 * 24 july 92:	mer realizes that the t_bits field is only used
-			 * in the event of null values.  If no fields are null we
-			 * reduce the header size by doing the squash.	t_hoff tells
-			 * you exactly how big the header actually is. use the PC
-			 * means of getting at sys cat attrs.
-			 */
-			tup_db = (Form_pg_database) GETSTRUCT(tup);
-
-			if (strncmp(GetDatabaseName(),
-						&(tup_db->datname.data[0]),
-						16) == 0)
-			{
-				MyDatabaseId = tup->t_oid;
-				goto done;
-			}
-		}
-	}
-
-done:
-	close(dbfd);
-	pfree(pg);
+	SetDatabaseName(name);
+	GetRawDatabaseInfo(name, &owner, &MyDatabaseId, myPath);
 
 	if (!OidIsValid(MyDatabaseId))
 		elog(FATAL,
 			 "Database %s does not exist in %s",
 			 GetDatabaseName(),
 			 DatabaseRelationName);
-}
 
+	path = ExpandDatabasePath(myPath);
+	SetDatabasePath(path);
+
+	return;
+} /* InitMyDatabaseInfo() */
 
 
 /*
@@ -237,21 +146,21 @@ done:
  *
  * Arguments:
  *		Path and name are invalid if it invalid as a string.
- *		Path is "badly formated" if it is not a string containing a path
+ *		Path is "badly formatted" if it is not a string containing a path
  *		to a writable directory.
- *		Name is "badly formated" if it contains more than 16 characters or if
+ *		Name is "badly formatted" if it contains more than 16 characters or if
  *		it is a bad file name (e.g., it contains a '/' or an 8-bit character).
  *
  * Exceptions:
  *		BadState if called more than once.
- *		BadArg if both path and name are "badly formated" or invalid.
+ *		BadArg if both path and name are "badly formatted" or invalid.
  *		BadArg if path and name are both "inconsistent" and valid.
  *
  *		This routine is inappropriate in bootstrap mode, since the directories
  *		and version files need not exist yet if we're in bootstrap mode.
  */
 static void
-DoChdirAndInitDatabaseNameAndPath(char *name)
+VerifySystemDatabase()
 {
 	char	   *reason;
 
@@ -261,84 +170,87 @@ DoChdirAndInitDatabaseNameAndPath(char *name)
 
 	if ((fd = open(DataDir, O_RDONLY, 0)) == -1)
 		sprintf(errormsg, "Database system does not exist.  "
-				"PGDATA directory '%s' not found.  Normally, you "
+				"PGDATA directory '%s' not found.\n\tNormally, you "
 				"create a database system by running initdb.",
 				DataDir);
 	else
 	{
-		char		myPath[MAXPGPATH];	/* DatabasePath points here! */
+		close(fd);
+		ValidatePgVersion(DataDir, &reason);
+		if (reason != NULL)
+			sprintf(errormsg,
+			 "InitPostgres could not validate that the database"
+			   " system version is compatible with this level of"
+			   " Postgres.\n\tYou may need to run initdb to create"
+			   " a new database system.\n\t%s", reason);
+	}
+	if (errormsg[0] != '\0')
+		elog(FATAL, errormsg);
+	/* Above does not return */
+} /* VerifySystemDatabase() */
+
 
+static void
+VerifyMyDatabase()
+{
+	char	   *name;
+	char	   *myPath;
+
+	/* Failure reason returned by some function.  NULL if no failure */
+	char	   *reason;
+	int			fd;
+	char		errormsg[1000];
+
+	name = GetDatabaseName();
+	myPath = GetDatabasePath();
+
+	if ((fd = open(myPath, O_RDONLY, 0)) == -1)
+		sprintf(errormsg,
+			"Database '%s' does not exist."
+			"\n\tWe know this because the directory '%s' does not exist."
+			"\n\tYou can create a database with the SQL command"
+			" CREATE DATABASE.\n\tTo see what databases exist,"
+			" look at the subdirectories of '%s/base/'.",
+			name, myPath, DataDir);
+	else
+	{
 		close(fd);
-		if (strlen(DataDir) + strlen(name) + 10 > sizeof(myPath))
-			sprintf(errormsg, "Internal error in postinit.c: database "
-					"pathname exceeds maximum allowable length.");
+		ValidatePgVersion(myPath, &reason);
+		if (reason != NULL)
+			sprintf(errormsg,
+				"InitPostgres could not validate that the database"
+				 " version is compatible with this level of Postgres"
+				 "\n\teven though the database system as a whole"
+				 " appears to be at a compatible level."
+				 "\n\tYou may need to recreate the database with SQL"
+				 " commands DROP DATABASE and CREATE DATABASE."
+				 "\n\t%s", reason);
 		else
 		{
-			sprintf(myPath, "%s/base/%s", DataDir, name);
+			/*
+			 * The directories and PG_VERSION files are in order.
+			 */
+			int rc; /* return code from some function we call */
 
-			if ((fd = open(myPath, O_RDONLY, 0)) == -1)
+#ifdef FILEDEBUG
+printf("Try changing directory for database %s to %s\n", name, myPath);
+#endif
+
+			rc = chdir(myPath);
+			if (rc < 0)
 				sprintf(errormsg,
-						"Database '%s' does not exist.  "
-						"(We know this because the directory '%s' "
-						"does not exist).  You can create a database "
-						"with the SQL command CREATE DATABASE.  To see "
-					  "what databases exist, look at the subdirectories "
-						"of '%s/base/'.",
-						name, myPath, DataDir);
+					"InitPostgres unable to change "
+					"current directory to '%s', errno = %s (%d).",
+					myPath, strerror(errno), errno);
 			else
-			{
-				close(fd);
-				ValidatePgVersion(DataDir, &reason);
-				if (reason != NULL)
-					sprintf(errormsg,
-					 "InitPostgres could not validate that the database "
-					   "system version is compatible with this level of "
-					   "Postgres.  You may need to run initdb to create "
-							"a new database system.  %s",
-							reason);
-				else
-				{
-					ValidatePgVersion(myPath, &reason);
-					if (reason != NULL)
-						sprintf(errormsg,
-							  "InitPostgres could not validate that the "
-						"database version is compatible with this level "
-						  "of Postgres, even though the database system "
-								"as a whole appears to be at a compatible level.  "
-						"You may need to recreate the database with SQL "
-						  "commands DROP DATABASE and CREATE DATABASE.  "
-								"%s",
-								reason);
-					else
-					{
-
-						/*
-						 * The directories and PG_VERSION files are in
-						 * order.
-						 */
-						int			rc; /* return code from some function
-										 * we call */
-
-						SetDatabasePath(myPath);
-						SetDatabaseName(name);
-						rc = chdir(myPath);
-						if (rc < 0)
-							sprintf(errormsg,
-									"InitPostgres unable to change "
-							"current directory to '%s', errno = %s (%d).",
-									myPath, strerror(errno), errno);
-						else
-							errormsg[0] = '\0';
-					}
-				}
-			}
+				errormsg[0] = '\0';
 		}
 	}
+
 	if (errormsg[0] != '\0')
 		elog(FATAL, errormsg);
 	/* Above does not return */
-}
-
+} /* VerifyMyDatabase() */
 
 
 /* --------------------------------
@@ -569,34 +481,43 @@ InitPostgres(char *name)		/* database name */
 	if (!TransactionFlushEnabled())
 		on_exitpg(FlushBufferPool, (caddr_t) NULL);
 
+	/* ----------------
+	 *	initialize the database id used for system caches and lock tables
+	 * ----------------
+	 */
 	if (bootstrap)
 	{
-		SetDatabasePath(".");
+		SetDatabasePath(ExpandDatabasePath(name));
 		SetDatabaseName(name);
+		LockDisable(true);
 	}
 	else
 	{
-		DoChdirAndInitDatabaseNameAndPath(name);
+		VerifySystemDatabase();
+		InitMyDatabaseInfo(name);
+		VerifyMyDatabase();
 	}
 
 	/*
-	 * ******************************** code after this point assumes we
-	 * are in the proper directory! ********************************
+	 * ********************************
+	 * code after this point assumes we are in the proper directory!
 	 *
+	 * So, how do we implement alternate locations for databases?
+	 * There are two possible locations for tables and we need to look
+	 * in DataDir/pg_database to find the true location of an
+	 * individual database. We can brute-force it as done in
+	 * InitMyDatabaseInfo(), or we can be patient and wait until we
+	 * open pg_database gracefully. Will try that, but may not work...
+	 * - thomas 1997-11-01
+	 * ********************************
 	 */
 
-	/* ----------------
-	 *	initialize the database id used for system caches and lock tables
-	 * ----------------
-	 */
-	InitMyDatabaseId();
-
+	/*  Does not touch files (?) - thomas 1997-11-01 */
 	smgrinit();
 
 	/* ----------------
-	 *	initialize the transaction system and the relation descriptor
-	 *	cache.	Note we have to make certain the lock manager is off while
-	 *	we do this.
+	 *	initialize the transaction system and the relation descriptor cache.
+	 *	Note we have to make certain the lock manager is off while we do this.
 	 * ----------------
 	 */
 	AmiTransactionOverride(IsBootstrapProcessingMode());
@@ -610,8 +531,7 @@ InitPostgres(char *name)		/* database name */
 	 * after initdb is done. -mer 15 June 1992
 	 */
 	RelationInitialize();		/* pre-allocated reldescs created here */
-	InitializeTransactionSystem();		/* pg_log,etc init/crash recovery
-										 * here */
+	InitializeTransactionSystem();	/* pg_log,etc init/crash recovery here */
 
 	LockDisable(false);
 
@@ -641,6 +561,7 @@ InitPostgres(char *name)		/* database name */
 
 	/* ----------------
 	 *	initialize the access methods.
+	 *  Does not touch files (?) - thomas 1997-11-01
 	 * ----------------
 	 */
 	initam();
@@ -650,6 +571,9 @@ InitPostgres(char *name)		/* database name */
 	 * ----------------
 	 */
 	zerocaches();
+	/*  Does not touch files since all routines are builtins (?)
+	 *  - thomas 1997-11-01
+	 */
 	InitCatalogCache();
 
 	/* ----------------
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 9ca72848d23..ff83dda86c0 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -11,7 +11,7 @@
  *
  * Copyright (c) 1994, Regents of the University of California
  *
- * $Id: miscadmin.h,v 1.16 1997/09/18 14:42:22 vadim Exp $
+ * $Id: miscadmin.h,v 1.17 1997/11/07 06:38:29 thomas Exp $
  *
  * NOTES
  *	  some of the information in this file will be moved to
@@ -107,6 +107,11 @@ extern Oid	LastOidProcessed;	/* for query rewrite */
  *			POSTGRES directory path definitions.							 *
  *****************************************************************************/
 
+/* in utils/misc/database.c */
+extern void GetRawDatabaseInfo(char *name, Oid *owner, Oid *db_id, char *path);
+extern int GetDatabaseInfo(char *name, Oid *owner, char *path);
+extern char *ExpandDatabasePath(char *path);
+
 /* now in utils/init/miscinit.c */
 extern char *GetDatabasePath(void);
 extern char *GetDatabaseName(void);
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 6e9e49b1c01..6fd9631f67b 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -6,7 +6,7 @@
  *
  * Copyright (c) 1994, Regents of the University of California
  *
- * $Id: parsenodes.h,v 1.29 1997/10/28 15:10:39 vadim Exp $
+ * $Id: parsenodes.h,v 1.30 1997/11/07 06:38:38 thomas Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -473,6 +473,7 @@ typedef struct CreatedbStmt
 {
 	NodeTag		type;
 	char	   *dbname;			/* database to create */
+	char	   *dbpath;			/* location of database */
 }			CreatedbStmt;
 
 /* ----------------------
diff --git a/src/include/parser/dbcommands.h b/src/include/parser/dbcommands.h
index 76b1dc6a0ee..31c6efd2db8 100644
--- a/src/include/parser/dbcommands.h
+++ b/src/include/parser/dbcommands.h
@@ -6,7 +6,7 @@
  *
  * Copyright (c) 1994, Regents of the University of California
  *
- * $Id: dbcommands.h,v 1.4 1997/09/08 02:38:05 momjian Exp $
+ * $Id: dbcommands.h,v 1.5 1997/11/07 06:38:09 thomas Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -20,7 +20,7 @@
 #define SIGKILLDAEMON1	SIGINT
 #define SIGKILLDAEMON2	SIGTERM
 
-extern void createdb(char *dbname);
+extern void createdb(char *dbname, char *dbpath);
 extern void destroydb(char *dbname);
 
 #endif							/* DBCOMMANDS_H */
-- 
GitLab